Welcome to mirror list, hosted at ThFree Co, Russian Federation.

github.com/mono/corefx.git - Unnamed repository; edit this file 'description' to name the repository.
summaryrefslogtreecommitdiff
diff options
context:
space:
mode:
authorAlexander Köplinger <alex.koeplinger@outlook.com>2017-07-16 03:10:42 +0300
committerAlexander Köplinger <alex.koeplinger@outlook.com>2017-07-16 03:10:42 +0300
commit797f074e49933b5fffb42d1a945270f3a88de042 (patch)
tree49f171cc5e7edba5adf6cfee4e9512aef11774c8
parent7e70a4e9236104c350e7d9ca3505225755065569 (diff)
parentc8e2d532ecb97ac4021c382578be2d385d7b3219 (diff)
Merge remote-tracking branch 'upstream/master'
# Conflicts: # src/Microsoft.Win32.Primitives/src/System/ComponentModel/Win32Exception.cs # src/System.ComponentModel.TypeConverter/src/System/ComponentModel/BindingList.cs # src/System.DirectoryServices/src/System/DirectoryServices/DirectoryServicesCOMException.cs # src/System.ObjectModel/src/System/Collections/ObjectModel/ObservableCollection.cs # src/System.ObjectModel/src/System/Collections/ObjectModel/ReadOnlyObservableCollection.cs
-rw-r--r--BuildToolsVersion.txt2
-rw-r--r--Documentation/debugging/windows-instructions.md3
-rw-r--r--Documentation/project-docs/issue-guide.md2
-rw-r--r--build.proj2
-rw-r--r--buildpipeline/DotNet-CoreFx-Trusted-Linux-Crossbuild.json265
-rw-r--r--buildpipeline/DotNet-CoreFx-Trusted-Linux.json285
-rw-r--r--buildpipeline/DotNet-CoreFx-Trusted-Windows.json171
-rw-r--r--buildpipeline/DotNet-Trusted-Publish-Symbols.json2
-rw-r--r--buildpipeline/linux.groovy15
-rw-r--r--buildpipeline/osx.groovy17
-rw-r--r--buildpipeline/windows.groovy17
-rw-r--r--dependencies.props30
-rw-r--r--dir.props7
-rw-r--r--dir.targets4
-rw-r--r--external/runtime/runtime.depproj3
-rw-r--r--external/test-runtime/XUnit.Runtime.depproj2
-rw-r--r--external/test-runtime/optional.json6
-rw-r--r--init-tools.cmd21
-rwxr-xr-xinit-tools.sh14
-rw-r--r--pkg/Microsoft.Private.CoreFx.UAP/Microsoft.Private.CoreFx.UAP.pkgproj2
-rw-r--r--pkg/Microsoft.Private.PackageBaseline/Microsoft.Private.PackageBaseline.pkgproj2
-rw-r--r--pkg/Microsoft.Private.PackageBaseline/packageIndex.json284
-rw-r--r--pkg/NETStandard.Library.NETFramework/NETStandard.Library.NETFramework.pkgproj41
-rw-r--r--pkg/NETStandard.Library.NETFramework/targets/NETStandard.Library.NETFramework.common.targets5
-rw-r--r--pkg/NETStandard.Library.NETFramework/targets/net461/NETStandard.Library.NETFramework.targets10
-rw-r--r--pkg/NETStandard.Library.NETFramework/targets/net462/NETStandard.Library.NETFramework.targets10
-rw-r--r--pkg/NETStandard.Library.NETFramework/targets/net47/NETStandard.Library.NETFramework.targets10
-rw-r--r--pkg/frameworkPackage.targets25
-rw-r--r--src/Common/src/Interop/Unix/System.Net.Http.Native/Interop.VersionInfo.cs1
-rw-r--r--src/Common/src/Interop/Unix/System.Security.Cryptography.Native/Interop.OpenSsl.cs55
-rw-r--r--src/Common/src/Interop/Unix/System.Security.Cryptography.Native/Interop.Ssl.cs16
-rw-r--r--src/Common/src/Interop/Unix/System.Security.Cryptography.Native/Interop.X509.cs1
-rw-r--r--src/Common/src/Interop/Windows/NtDll/Interop.NtQueryInformationProcess.cs29
-rw-r--r--src/Common/src/Interop/Windows/kernel32/Interop.CheckTokenMembershipEx.cs18
-rw-r--r--src/Common/src/Interop/Windows/kernel32/Interop.GetProcessId.cs15
-rw-r--r--src/Common/src/Interop/Windows/kernel32/Interop.SafeCreateFile.cs2
-rw-r--r--src/Common/src/System/CharArrayHelpers.cs12
-rw-r--r--src/Common/src/System/Collections/Generic/EnumerableHelpers.Linq.cs9
-rw-r--r--src/Common/src/System/Collections/Generic/EnumerableHelpers.cs9
-rw-r--r--src/Common/src/System/Collections/Generic/LargeArrayBuilder.cs3
-rw-r--r--src/Common/src/System/Data/Common/AdapterUtil.cs9
-rw-r--r--src/Common/src/System/IO/PathInternal.Unix.cs16
-rw-r--r--src/Common/src/System/IO/PathInternal.Windows.cs18
-rw-r--r--src/Common/src/System/MathF.netstandard.cs (renamed from src/System.Numerics.Vectors/src/System/MathF.cs)7
-rw-r--r--src/Common/src/System/Net/CompletionPortHelper.Uap.cs19
-rw-r--r--src/Common/src/System/Net/ContextAwareResult.Uap.cs19
-rw-r--r--src/Common/src/System/Net/CookieParser.cs19
-rw-r--r--src/Common/src/System/Net/Security/CertificateHelper.Uap.cs60
-rw-r--r--src/Common/src/System/Net/Security/CertificateHelper.Windows.cs27
-rw-r--r--src/Common/src/System/Net/Security/CertificateHelper.cs71
-rw-r--r--src/Common/tests/Common.Tests.csproj3
-rw-r--r--src/Common/tests/System/Collections/IEnumerable.Generic.Serialization.Tests.cs1
-rw-r--r--src/Common/tests/System/Net/Configuration.Http.cs2
-rw-r--r--src/Common/tests/System/Net/HttpsTestServer.cs25
-rw-r--r--src/Common/tests/System/Net/PlatformDetection.Networking.cs14
-rw-r--r--src/Common/tests/System/PlatformDetection.cs7
-rw-r--r--src/Common/tests/System/Runtime/Serialization/Formatters/BinaryFormatterHelpers.cs47
-rw-r--r--src/CoreFx.Private.TestUtilities/ref/CoreFx.Private.TestUtilities.cs27
-rw-r--r--src/CoreFx.Private.TestUtilities/src/CoreFx.Private.TestUtilities.csproj2
-rw-r--r--src/CoreFx.Private.TestUtilities/src/System/AssertExtensions.cs (renamed from src/Common/tests/System/AssertExtensions.cs)0
-rw-r--r--src/CoreFx.Private.TestUtilities/src/System/IO/FileCleanupTestBase.cs5
-rw-r--r--src/Microsoft.CSharp/pkg/Microsoft.CSharp.pkgproj2
-rw-r--r--src/Microsoft.CSharp/src/Microsoft/CSharp/RuntimeBinder/CSharpArgumentInfo.cs4
-rw-r--r--src/Microsoft.CSharp/src/Microsoft/CSharp/RuntimeBinder/RuntimeBinder.cs4
-rw-r--r--src/Microsoft.CSharp/src/Microsoft/CSharp/RuntimeBinder/Semantics/PredefinedMembers.cs230
-rw-r--r--src/Microsoft.CSharp/src/Microsoft/CSharp/RuntimeBinder/Semantics/Tree/Visitors/ExpressionTreeRewriter.cs23
-rw-r--r--src/Microsoft.CSharp/src/Microsoft/CSharp/RuntimeBinder/SymbolTable.cs6
-rw-r--r--src/Microsoft.VisualBasic/pkg/Microsoft.VisualBasic.pkgproj2
-rw-r--r--src/Microsoft.VisualBasic/tests/Microsoft.VisualBasic.Tests.csproj10
-rw-r--r--src/Microsoft.VisualBasic/tests/OperatorsTests.cs12
-rw-r--r--src/Microsoft.VisualBasic/tests/Resources/Microsoft.VisualBasic.Tests.rd.xml7
-rw-r--r--src/Microsoft.VisualBasic/tests/UtilsTests.cs6
-rw-r--r--src/Microsoft.Win32.Primitives/src/System/ComponentModel/Win32Exception.cs84
-rw-r--r--src/Microsoft.Win32.Primitives/tests/Microsoft.Win32.Primitives.Tests.csproj9
-rw-r--r--src/Microsoft.Win32.Primitives/tests/Win32ExceptionTests.cs (renamed from src/Microsoft.Win32.Primitives/tests/Win32Exception.cs)9
-rw-r--r--src/Microsoft.Win32.Registry/tests/Microsoft.Win32.Registry.Tests.csproj3
-rw-r--r--src/Native/Unix/System.Native/pal_networkstatistics.cpp1
-rw-r--r--src/Native/Unix/System.Security.Cryptography.Native.Apple/pal_x509chain.cpp5
-rw-r--r--src/Native/Unix/System.Security.Cryptography.Native/pal_ssl.cpp54
-rw-r--r--src/Native/Unix/System.Security.Cryptography.Native/pal_ssl.h28
-rw-r--r--src/Native/Unix/System.Security.Cryptography.Native/pal_x509.cpp1
-rw-r--r--src/Native/Unix/System.Security.Cryptography.Native/pal_x509.h1
-rw-r--r--src/System.AppContext/tests/System.AppContext.Tests.csproj3
-rw-r--r--src/System.Buffers/pkg/System.Buffers.pkgproj2
-rw-r--r--src/System.Buffers/tests/System.Buffers.Tests.csproj3
-rw-r--r--src/System.CodeDom/tests/System.CodeDom.Tests.csproj3
-rw-r--r--src/System.Collections.Concurrent/src/System/Collections/Concurrent/ConcurrentQueue.cs4
-rw-r--r--src/System.Collections.Concurrent/tests/System.Collections.Concurrent.Tests.csproj3
-rw-r--r--src/System.Collections.Immutable/pkg/System.Collections.Immutable.pkgproj2
-rw-r--r--src/System.Collections.Immutable/tests/System.Collections.Immutable.Tests.csproj3
-rw-r--r--src/System.Collections.NonGeneric/tests/System.Collections.NonGeneric.Tests.csproj3
-rw-r--r--src/System.Collections.Specialized/tests/System.Collections.Specialized.Tests.csproj3
-rw-r--r--src/System.Collections/tests/Generic/Comparers/EqualityComparer.Generic.Serialization.Tests.cs1
-rw-r--r--src/System.Collections/tests/Generic/Dictionary/Dictionary.Tests.cs2
-rw-r--r--src/System.Collections/tests/Resources/System.Collections.Tests.rd.xml7
-rw-r--r--src/System.Collections/tests/System.Collections.Tests.csproj8
-rw-r--r--src/System.ComponentModel.Annotations/pkg/System.ComponentModel.Annotations.pkgproj2
-rw-r--r--src/System.ComponentModel.Annotations/tests/System.ComponentModel.Annotations.Tests.csproj3
-rw-r--r--src/System.ComponentModel.TypeConverter/src/Resources/System.ComponentModel.TypeConverter.rd.xml3
-rw-r--r--src/System.ComponentModel.TypeConverter/src/System/ComponentModel/AmbientValueAttribute.cs94
-rw-r--r--src/System.ComponentModel.TypeConverter/src/System/ComponentModel/BaseNumberConverter.cs5
-rw-r--r--src/System.ComponentModel.TypeConverter/src/System/ComponentModel/BindingList.cs182
-rw-r--r--src/System.ComponentModel.TypeConverter/src/System/ComponentModel/ByteConverter.cs9
-rw-r--r--src/System.ComponentModel.TypeConverter/src/System/ComponentModel/ComponentResourceManager.cs5
-rw-r--r--src/System.ComponentModel.TypeConverter/src/System/ComponentModel/Container.cs153
-rw-r--r--src/System.ComponentModel.TypeConverter/src/System/ComponentModel/DecimalConverter.cs9
-rw-r--r--src/System.ComponentModel.TypeConverter/src/System/ComponentModel/DoubleConverter.cs9
-rw-r--r--src/System.ComponentModel.TypeConverter/src/System/ComponentModel/Int16Converter.cs9
-rw-r--r--src/System.ComponentModel.TypeConverter/src/System/ComponentModel/Int32Converter.cs11
-rw-r--r--src/System.ComponentModel.TypeConverter/src/System/ComponentModel/Int64Converter.cs11
-rw-r--r--src/System.ComponentModel.TypeConverter/src/System/ComponentModel/SByteConverter.cs9
-rw-r--r--src/System.ComponentModel.TypeConverter/src/System/ComponentModel/SingleConverter.cs9
-rw-r--r--src/System.ComponentModel.TypeConverter/src/System/ComponentModel/UInt16Converter.cs9
-rw-r--r--src/System.ComponentModel.TypeConverter/src/System/ComponentModel/UInt32Converter.cs9
-rw-r--r--src/System.ComponentModel.TypeConverter/src/System/ComponentModel/UInt64Converter.cs9
-rw-r--r--src/System.ComponentModel.TypeConverter/tests/AmbientValueAttributeTests.cs133
-rw-r--r--src/System.ComponentModel.TypeConverter/tests/BindingListTests.cs1147
-rw-r--r--src/System.ComponentModel.TypeConverter/tests/ComponentResourceManagerTests.cs204
-rw-r--r--src/System.ComponentModel.TypeConverter/tests/ContainerTests.cs185
-rw-r--r--src/System.ComponentModel.TypeConverter/tests/Resources/TestResx.Designer.cs118
-rw-r--r--src/System.ComponentModel.TypeConverter/tests/Resources/TestResx.resx79
-rw-r--r--src/System.ComponentModel.TypeConverter/tests/System.ComponentModel.TypeConverter.Tests.csproj19
-rw-r--r--src/System.Composition.AttributedModel/tests/System.Composition.AttributeModel.Tests.csproj3
-rw-r--r--src/System.Composition.Hosting/tests/System.Composition.Hosting.Tests.csproj3
-rw-r--r--src/System.Composition.Runtime/tests/System.Composition.Runtime.Tests.csproj3
-rw-r--r--src/System.Composition.TypedParts/tests/System.Composition.TypedParts.Tests.csproj3
-rw-r--r--src/System.Configuration.ConfigurationManager/ref/System.Configuration.ConfigurationManager.csproj7
-rw-r--r--src/System.Configuration.ConfigurationManager/ref/System.Configuration.cs10
-rw-r--r--src/System.Configuration.ConfigurationManager/src/System.Configuration.ConfigurationManager.csproj2
-rw-r--r--src/System.Configuration.ConfigurationManager/src/System/Drawing/Configuration/SystemDrawingSection.cs (renamed from src/System.Drawing.Common/src/System/Drawing/Configuration/SystemDrawingSection.cs)2
-rw-r--r--src/System.Configuration.ConfigurationManager/tests/System.Configuration.ConfigurationManager.Tests.csproj4
-rw-r--r--src/System.Configuration.ConfigurationManager/tests/System/Drawing/Configuration/SystemDrawingSectionTests.cs31
-rw-r--r--src/System.Console/tests/System.Console.Tests.csproj3
-rw-r--r--src/System.Data.Common/src/Configurations.props1
-rw-r--r--src/System.Data.Common/src/System.Data.Common.csproj10
-rw-r--r--src/System.Data.Common/src/System/Data/SQLTypes/SqlXml.cs10
-rw-r--r--src/System.Data.Common/tests/System.Data.Common.Tests.csproj3
-rw-r--r--src/System.Data.Common/tests/System/Data/SqlTypes/SqlXmlTest.cs8
-rw-r--r--src/System.Data.SqlClient/pkg/System.Data.SqlClient.pkgproj2
-rw-r--r--src/System.Data.SqlClient/ref/System.Data.SqlClient.cs1
-rw-r--r--src/System.Data.SqlClient/ref/System.Data.SqlClient.csproj6
-rw-r--r--src/System.Data.SqlClient/src/Interop/SNINativeMethodWrapper.Common.cs24
-rw-r--r--src/System.Data.SqlClient/src/Interop/SNINativeMethodWrapper.Unix.cs19
-rw-r--r--src/System.Data.SqlClient/src/Interop/SNINativeMethodWrapper.Windows.cs14
-rw-r--r--src/System.Data.SqlClient/src/Resources/Strings.resx42
-rw-r--r--src/System.Data.SqlClient/src/System.Data.SqlClient.csproj21
-rw-r--r--src/System.Data.SqlClient/src/System/Data/Common/AdapterUtil.SqlClient.cs20
-rw-r--r--src/System.Data.SqlClient/src/System/Data/Common/DbConnectionStringCommon.cs6
-rw-r--r--src/System.Data.SqlClient/src/System/Data/ProviderBase/DbConnectionClosed.cs15
-rw-r--r--src/System.Data.SqlClient/src/System/Data/ProviderBase/DbConnectionFactory.cs20
-rw-r--r--src/System.Data.SqlClient/src/System/Data/ProviderBase/DbConnectionInternal.cs371
-rw-r--r--src/System.Data.SqlClient/src/System/Data/ProviderBase/DbConnectionPool.cs475
-rw-r--r--src/System.Data.SqlClient/src/System/Data/ProviderBase/DbConnectionPoolIdentity.Unix.cs12
-rw-r--r--src/System.Data.SqlClient/src/System/Data/ProviderBase/DbConnectionPoolIdentity.Windows.cs10
-rw-r--r--src/System.Data.SqlClient/src/System/Data/ProviderBase/DbConnectionPoolIdentity.cs15
-rw-r--r--src/System.Data.SqlClient/src/System/Data/ProviderBase/DbConnectionPoolOptions.cs10
-rw-r--r--src/System.Data.SqlClient/src/System/Data/SqlClient/LocalDBAPI.Common.cs121
-rw-r--r--src/System.Data.SqlClient/src/System/Data/SqlClient/LocalDBAPI.Unix.cs9
-rw-r--r--src/System.Data.SqlClient/src/System/Data/SqlClient/LocalDBAPI.Windows.cs6
-rw-r--r--src/System.Data.SqlClient/src/System/Data/SqlClient/LocalDBAPI.cs116
-rw-r--r--src/System.Data.SqlClient/src/System/Data/SqlClient/LocalDBAPI.uap.cs19
-rw-r--r--src/System.Data.SqlClient/src/System/Data/SqlClient/SNI/LocalDB.Windows.cs3
-rw-r--r--src/System.Data.SqlClient/src/System/Data/SqlClient/SNI/SNINpHandle.cs5
-rw-r--r--src/System.Data.SqlClient/src/System/Data/SqlClient/SqlCommand.cs18
-rw-r--r--src/System.Data.SqlClient/src/System/Data/SqlClient/SqlConnection.cs26
-rw-r--r--src/System.Data.SqlClient/src/System/Data/SqlClient/SqlConnectionFactory.cs4
-rw-r--r--src/System.Data.SqlClient/src/System/Data/SqlClient/SqlConnectionHelper.cs36
-rw-r--r--src/System.Data.SqlClient/src/System/Data/SqlClient/SqlConnectionString.cs39
-rw-r--r--src/System.Data.SqlClient/src/System/Data/SqlClient/SqlConnectionStringBuilder.cs21
-rw-r--r--src/System.Data.SqlClient/src/System/Data/SqlClient/SqlDelegatedTransaction.cs466
-rw-r--r--src/System.Data.SqlClient/src/System/Data/SqlClient/SqlInternalConnection.cs377
-rw-r--r--src/System.Data.SqlClient/src/System/Data/SqlClient/SqlInternalConnectionTds.cs259
-rw-r--r--src/System.Data.SqlClient/src/System/Data/SqlClient/SqlUtil.cs88
-rw-r--r--src/System.Data.SqlClient/src/System/Data/SqlClient/TdsEnums.cs5
-rw-r--r--src/System.Data.SqlClient/src/System/Data/SqlClient/TdsParser.cs223
-rw-r--r--src/System.Data.SqlClient/src/System/Data/SqlClient/sqlinternaltransaction.cs30
-rw-r--r--src/System.Data.SqlClient/tests/FunctionalTests/AmbientTransactionFailureTest.cs11
-rw-r--r--src/System.Data.SqlClient/tests/FunctionalTests/ExceptionTest.cs14
-rw-r--r--src/System.Data.SqlClient/tests/FunctionalTests/System.Data.SqlClient.Tests.csproj3
-rw-r--r--src/System.Data.SqlClient/tests/FunctionalTests/TcpDefaultForAzureTest.cs1
-rw-r--r--src/System.Data.SqlClient/tests/ManualTests/SQL/TransactionTest/TransactionEnlistmentTest.cs124
-rw-r--r--src/System.Data.SqlClient/tests/ManualTests/System.Data.SqlClient.ManualTesting.Tests.csproj1
-rw-r--r--src/System.Diagnostics.Contracts/tests/System.Diagnostics.Contracts.Tests.csproj3
-rw-r--r--src/System.Diagnostics.Debug/tests/System.Diagnostics.Debug.Tests.csproj3
-rw-r--r--src/System.Diagnostics.DiagnosticSource/src/ActivityUserGuide.md10
-rw-r--r--src/System.Diagnostics.DiagnosticSource/src/FlatRequestId.md100
-rw-r--r--src/System.Diagnostics.DiagnosticSource/src/HierarchicalRequestId.md111
-rw-r--r--src/System.Diagnostics.DiagnosticSource/src/HttpCorrelationProtocol.md83
-rw-r--r--src/System.Diagnostics.DiagnosticSource/tests/ActivityTests.cs5
-rw-r--r--src/System.Diagnostics.DiagnosticSource/tests/DiagnosticSourceEventSourceBridgeTests.cs8
-rw-r--r--src/System.Diagnostics.Process/src/PinvokeAnalyzerExceptionList.analyzerdata.uap3
-rw-r--r--src/System.Diagnostics.Process/src/Resources/Strings.resx3
-rw-r--r--src/System.Diagnostics.Process/src/System.Diagnostics.Process.csproj19
-rw-r--r--src/System.Diagnostics.Process/src/System/Diagnostics/ProcessManager.Uap.cs70
-rw-r--r--src/System.Diagnostics.Process/src/System/Diagnostics/ProcessManager.Win32.cs258
-rw-r--r--src/System.Diagnostics.Process/src/System/Diagnostics/ProcessManager.Windows.cs264
-rw-r--r--src/System.Diagnostics.Process/tests/Configurations.props1
-rw-r--r--src/System.Diagnostics.Process/tests/ProcessCollectionTests.cs1
-rw-r--r--src/System.Diagnostics.Process/tests/ProcessModuleTests.cs1
-rw-r--r--src/System.Diagnostics.Process/tests/ProcessStandardConsoleTests.cs1
-rw-r--r--src/System.Diagnostics.Process/tests/ProcessStartInfoTests.cs7
-rw-r--r--src/System.Diagnostics.Process/tests/ProcessStreamReadTests.cs1
-rw-r--r--src/System.Diagnostics.Process/tests/ProcessTestBase.cs2
-rw-r--r--src/System.Diagnostics.Process/tests/ProcessTests.cs58
-rw-r--r--src/System.Diagnostics.Process/tests/ProcessThreadTests.cs7
-rw-r--r--src/System.Diagnostics.Process/tests/ProcessWaitingTests.cs10
-rw-r--r--src/System.Diagnostics.Process/tests/System.Diagnostics.Process.Tests.csproj10
-rw-r--r--src/System.Diagnostics.StackTrace/tests/System.Diagnostics.StackTrace.Tests.csproj3
-rw-r--r--src/System.Diagnostics.TextWriterTraceListener/tests/System.Diagnostics.TextWriterTraceListener.Tests.csproj3
-rw-r--r--src/System.Diagnostics.TraceSource/tests/System.Diagnostics.TraceSource.Tests.csproj3
-rw-r--r--src/System.Diagnostics.Tracing/tests/BasicEventSourceTest/FuzzyTests.cs1
-rw-r--r--src/System.Diagnostics.Tracing/tests/BasicEventSourceTest/LoudListener.cs3
-rw-r--r--src/System.Diagnostics.Tracing/tests/BasicEventSourceTest/TestsEventSourceLifetime.cs2
-rw-r--r--src/System.Diagnostics.Tracing/tests/BasicEventSourceTest/TestsManifestGeneration.cs2
-rw-r--r--src/System.Diagnostics.Tracing/tests/BasicEventSourceTest/TestsManifestNegative.cs92
-rw-r--r--src/System.Diagnostics.Tracing/tests/BasicEventSourceTest/TestsUserErrors.cs12
-rw-r--r--src/System.Diagnostics.Tracing/tests/BasicEventSourceTest/TestsWrite.cs3
-rw-r--r--src/System.Diagnostics.Tracing/tests/BasicEventSourceTest/TestsWriteEventToListener.cs11
-rw-r--r--src/System.Diagnostics.Tracing/tests/Resources/System.Diagnostics.Tracing.Tests.rd.xml6
-rw-r--r--src/System.Diagnostics.Tracing/tests/System.Diagnostics.Tracing.Tests.csproj8
-rw-r--r--src/System.DirectoryServices.AccountManagement/tests/ComputerPrincipalTest.cs5
-rw-r--r--src/System.DirectoryServices.AccountManagement/tests/PrincipalContextTests.cs23
-rw-r--r--src/System.DirectoryServices.AccountManagement/tests/System.DirectoryServices.AccountManagement.Tests.csproj3
-rw-r--r--src/System.DirectoryServices.Protocols/src/System.DirectoryServices.Protocols.csproj1
-rw-r--r--src/System.DirectoryServices.Protocols/src/System/DirectoryServices/Protocols/ExternDll.cs83
-rw-r--r--src/System.DirectoryServices.Protocols/src/System/DirectoryServices/Protocols/common/BerConverter.cs44
-rw-r--r--src/System.DirectoryServices.Protocols/src/System/DirectoryServices/Protocols/common/DirectoryControl.cs18
-rw-r--r--src/System.DirectoryServices.Protocols/src/System/DirectoryServices/Protocols/ldap/LdapAsyncResult.cs108
-rw-r--r--src/System.DirectoryServices.Protocols/src/System/DirectoryServices/Protocols/ldap/LdapConnection.cs1235
-rw-r--r--src/System.DirectoryServices.Protocols/src/System/DirectoryServices/Protocols/ldap/LdapDirectoryIdentifier.cs65
-rw-r--r--src/System.DirectoryServices.Protocols/src/System/DirectoryServices/Protocols/ldap/LdapException.cs49
-rw-r--r--src/System.DirectoryServices.Protocols/src/System/DirectoryServices/Protocols/ldap/LdapPartialResultsProcessor.cs244
-rw-r--r--src/System.DirectoryServices.Protocols/src/System/DirectoryServices/Protocols/ldap/LdapSessionOptions.cs806
-rw-r--r--src/System.DirectoryServices.Protocols/src/System/DirectoryServices/Protocols/ldap/SafeHandles.cs53
-rw-r--r--src/System.DirectoryServices.Protocols/src/System/DirectoryServices/Protocols/ldap/Wldap32UnsafeMethods.cs212
-rw-r--r--src/System.DirectoryServices.Protocols/tests/System.DirectoryServices.Protocols.Tests.csproj3
-rw-r--r--src/System.DirectoryServices/src/Interop/AdsAuthentication.cs1
-rw-r--r--src/System.DirectoryServices/src/Interop/AdsOptions.cs1
-rw-r--r--src/System.DirectoryServices/src/Interop/AdsPropertyOperation.cs10
-rw-r--r--src/System.DirectoryServices/src/Interop/AdsSearchColumn.cs6
-rw-r--r--src/System.DirectoryServices/src/Interop/AdsSearchPreferenceInfo.cs6
-rw-r--r--src/System.DirectoryServices/src/Interop/AdsSearchPreferences.cs1
-rw-r--r--src/System.DirectoryServices/src/Interop/AdsSortKey.cs6
-rw-r--r--src/System.DirectoryServices/src/Interop/AdsStatus.cs1
-rw-r--r--src/System.DirectoryServices/src/Interop/AdsType.cs1
-rw-r--r--src/System.DirectoryServices/src/Interop/AdsValue2.cs6
-rw-r--r--src/System.DirectoryServices/src/Interop/AdsValueHelper2.cs140
-rw-r--r--src/System.DirectoryServices/src/Interop/NativeMethods.cs10
-rw-r--r--src/System.DirectoryServices/src/Interop/SafeNativeMethods.cs79
-rw-r--r--src/System.DirectoryServices/src/Interop/UnsafeNativeMethods.cs300
-rw-r--r--src/System.DirectoryServices/src/System.DirectoryServices.csproj2
-rw-r--r--src/System.DirectoryServices/src/System/DirectoryServices/ActiveDirectory/ADAMInstance.cs42
-rw-r--r--src/System.DirectoryServices/src/System/DirectoryServices/ActiveDirectory/ADAMInstanceCollection.cs14
-rw-r--r--src/System.DirectoryServices/src/System/DirectoryServices/ActiveDirectory/ADSearcher.cs50
-rw-r--r--src/System.DirectoryServices/src/System/DirectoryServices/ActiveDirectory/ActiveDirectoryInterSiteTransport.cs16
-rw-r--r--src/System.DirectoryServices/src/System/DirectoryServices/ActiveDirectory/ActiveDirectoryPartition.cs11
-rw-r--r--src/System.DirectoryServices/src/System/DirectoryServices/ActiveDirectory/ActiveDirectoryReplicationMetaData.cs40
-rw-r--r--src/System.DirectoryServices/src/System/DirectoryServices/ActiveDirectory/ActiveDirectorySchedule.cs13
-rw-r--r--src/System.DirectoryServices/src/System/DirectoryServices/ActiveDirectory/ActiveDirectorySchema.cs19
-rw-r--r--src/System.DirectoryServices/src/System/DirectoryServices/ActiveDirectory/ActiveDirectorySchemaClass.cs24
-rw-r--r--src/System.DirectoryServices/src/System/DirectoryServices/ActiveDirectory/ActiveDirectorySchemaClassCollection.cs94
-rw-r--r--src/System.DirectoryServices/src/System/DirectoryServices/ActiveDirectory/ActiveDirectorySchemaProperty.cs28
-rw-r--r--src/System.DirectoryServices/src/System/DirectoryServices/ActiveDirectory/ActiveDirectorySchemaPropertyCollection.cs43
-rw-r--r--src/System.DirectoryServices/src/System/DirectoryServices/ActiveDirectory/ActiveDirectorySite.cs45
-rw-r--r--src/System.DirectoryServices/src/System/DirectoryServices/ActiveDirectory/ActiveDirectorySiteCollection.cs36
-rw-r--r--src/System.DirectoryServices/src/System/DirectoryServices/ActiveDirectory/ActiveDirectorySiteLink.cs31
-rw-r--r--src/System.DirectoryServices/src/System/DirectoryServices/ActiveDirectory/ActiveDirectorySiteLinkBridge.cs27
-rw-r--r--src/System.DirectoryServices/src/System/DirectoryServices/ActiveDirectory/ActiveDirectorySiteLinkCollection.cs36
-rw-r--r--src/System.DirectoryServices/src/System/DirectoryServices/ActiveDirectory/ActiveDirectorySubnet.cs24
-rw-r--r--src/System.DirectoryServices/src/System/DirectoryServices/ActiveDirectory/ActiveDirectorySubnetCollection.cs45
-rw-r--r--src/System.DirectoryServices/src/System/DirectoryServices/ActiveDirectory/ActiveDirectorySyntax.cs29
-rw-r--r--src/System.DirectoryServices/src/System/DirectoryServices/ActiveDirectory/ApplicationPartition.cs16
-rw-r--r--src/System.DirectoryServices/src/System/DirectoryServices/ActiveDirectory/ApplicationPartitionCollection.cs15
-rw-r--r--src/System.DirectoryServices/src/System/DirectoryServices/ActiveDirectory/AttributeMetaData.cs95
-rw-r--r--src/System.DirectoryServices/src/System/DirectoryServices/ActiveDirectory/AttributeMetadataCollection.cs19
-rw-r--r--src/System.DirectoryServices/src/System/DirectoryServices/ActiveDirectory/ConfigSet.cs42
-rw-r--r--src/System.DirectoryServices/src/System/DirectoryServices/ActiveDirectory/DirectoryContext.cs69
-rw-r--r--src/System.DirectoryServices/src/System/DirectoryServices/ActiveDirectory/DirectoryEntryManager.cs47
-rw-r--r--src/System.DirectoryServices/src/System/DirectoryServices/ActiveDirectory/DirectoryServer.cs59
-rw-r--r--src/System.DirectoryServices/src/System/DirectoryServices/ActiveDirectory/DirectoryServerCollection.cs43
-rw-r--r--src/System.DirectoryServices/src/System/DirectoryServices/ActiveDirectory/Domain.cs40
-rw-r--r--src/System.DirectoryServices/src/System/DirectoryServices/ActiveDirectory/DomainCollection.cs26
-rw-r--r--src/System.DirectoryServices/src/System/DirectoryServices/ActiveDirectory/DomainController.cs68
-rw-r--r--src/System.DirectoryServices/src/System/DirectoryServices/ActiveDirectory/DomainControllerCollection.cs14
-rw-r--r--src/System.DirectoryServices/src/System/DirectoryServices/ActiveDirectory/Exception.cs158
-rw-r--r--src/System.DirectoryServices/src/System/DirectoryServices/ActiveDirectory/Forest.cs66
-rw-r--r--src/System.DirectoryServices/src/System/DirectoryServices/ActiveDirectory/ForestTrustCollision.cs63
-rw-r--r--src/System.DirectoryServices/src/System/DirectoryServices/ActiveDirectory/ForestTrustDomainInfoCollection.cs17
-rw-r--r--src/System.DirectoryServices/src/System/DirectoryServices/ActiveDirectory/ForestTrustDomainInformation.cs47
-rw-r--r--src/System.DirectoryServices/src/System/DirectoryServices/ActiveDirectory/ForestTrustRelationshipInformation.cs11
-rw-r--r--src/System.DirectoryServices/src/System/DirectoryServices/ActiveDirectory/GlobalCatalog.cs27
-rw-r--r--src/System.DirectoryServices/src/System/DirectoryServices/ActiveDirectory/GlobalCatalogCollection.cs14
-rw-r--r--src/System.DirectoryServices/src/System/DirectoryServices/ActiveDirectory/Locator.cs11
-rw-r--r--src/System.DirectoryServices/src/System/DirectoryServices/ActiveDirectory/LocatorFlag.cs22
-rw-r--r--src/System.DirectoryServices/src/System/DirectoryServices/ActiveDirectory/NativeMethods.cs39
-rw-r--r--src/System.DirectoryServices/src/System/DirectoryServices/ActiveDirectory/PropertyManager.cs14
-rw-r--r--src/System.DirectoryServices/src/System/DirectoryServices/ActiveDirectory/ReadOnlyActiveDirectorySchemaClassCollection.cs11
-rw-r--r--src/System.DirectoryServices/src/System/DirectoryServices/ActiveDirectory/ReadOnlyActiveDirectorySchemaPropertyCollection.cs11
-rw-r--r--src/System.DirectoryServices/src/System/DirectoryServices/ActiveDirectory/ReadOnlyDirectoryServerCollection.cs29
-rw-r--r--src/System.DirectoryServices/src/System/DirectoryServices/ActiveDirectory/ReadOnlySiteCollection.cs27
-rw-r--r--src/System.DirectoryServices/src/System/DirectoryServices/ActiveDirectory/ReadOnlySiteLinkBridgeCollection.cs23
-rw-r--r--src/System.DirectoryServices/src/System/DirectoryServices/ActiveDirectory/ReadOnlySiteLinkCollection.cs24
-rw-r--r--src/System.DirectoryServices/src/System/DirectoryServices/ActiveDirectory/ReadOnlyStringCollection.cs12
-rw-r--r--src/System.DirectoryServices/src/System/DirectoryServices/ActiveDirectory/ReplicationConnection.cs20
-rw-r--r--src/System.DirectoryServices/src/System/DirectoryServices/ActiveDirectory/ReplicationConnectionCollection.cs23
-rw-r--r--src/System.DirectoryServices/src/System/DirectoryServices/ActiveDirectory/ReplicationCursor.cs50
-rw-r--r--src/System.DirectoryServices/src/System/DirectoryServices/ActiveDirectory/ReplicationCursorCollection.cs23
-rw-r--r--src/System.DirectoryServices/src/System/DirectoryServices/ActiveDirectory/ReplicationFailure.cs63
-rw-r--r--src/System.DirectoryServices/src/System/DirectoryServices/ActiveDirectory/ReplicationFailureCollection.cs24
-rw-r--r--src/System.DirectoryServices/src/System/DirectoryServices/ActiveDirectory/ReplicationNeighbor.cs136
-rw-r--r--src/System.DirectoryServices/src/System/DirectoryServices/ActiveDirectory/ReplicationNeighborCollection.cs24
-rw-r--r--src/System.DirectoryServices/src/System/DirectoryServices/ActiveDirectory/ReplicationOperation.cs82
-rw-r--r--src/System.DirectoryServices/src/System/DirectoryServices/ActiveDirectory/ReplicationOperationCollection.cs25
-rw-r--r--src/System.DirectoryServices/src/System/DirectoryServices/ActiveDirectory/ReplicationOperationInformation.cs29
-rw-r--r--src/System.DirectoryServices/src/System/DirectoryServices/ActiveDirectory/RoleOwner.cs2
-rw-r--r--src/System.DirectoryServices/src/System/DirectoryServices/ActiveDirectory/RoleOwnerCollection.cs25
-rw-r--r--src/System.DirectoryServices/src/System/DirectoryServices/ActiveDirectory/SafeHandle.cs27
-rw-r--r--src/System.DirectoryServices/src/System/DirectoryServices/ActiveDirectory/SecurityLevel.cs2
-rw-r--r--src/System.DirectoryServices/src/System/DirectoryServices/ActiveDirectory/SystemFlag.cs2
-rw-r--r--src/System.DirectoryServices/src/System/DirectoryServices/ActiveDirectory/TopLevelName.cs27
-rw-r--r--src/System.DirectoryServices/src/System/DirectoryServices/ActiveDirectory/TopLevelNameCollection.cs15
-rw-r--r--src/System.DirectoryServices/src/System/DirectoryServices/ActiveDirectory/TrustHelper.cs49
-rw-r--r--src/System.DirectoryServices/src/System/DirectoryServices/ActiveDirectory/TrustRelationshipInformation.cs38
-rw-r--r--src/System.DirectoryServices/src/System/DirectoryServices/ActiveDirectory/TrustRelationshipInformationCollection.cs17
-rw-r--r--src/System.DirectoryServices/src/System/DirectoryServices/ActiveDirectory/UnsafeNativeMethods.cs8
-rw-r--r--src/System.DirectoryServices/src/System/DirectoryServices/ActiveDirectory/Utils.cs46
-rw-r--r--src/System.DirectoryServices/src/System/DirectoryServices/ActiveDirectory/WellKnownDN.cs2
-rw-r--r--src/System.DirectoryServices/src/System/DirectoryServices/ActiveDirectorySecurity.cs61
-rw-r--r--src/System.DirectoryServices/src/System/DirectoryServices/AdsVLV.cs5
-rw-r--r--src/System.DirectoryServices/src/System/DirectoryServices/AuthenticationTypes.cs26
-rw-r--r--src/System.DirectoryServices/src/System/DirectoryServices/DerefAlias.cs12
-rw-r--r--src/System.DirectoryServices/src/System/DirectoryServices/Design/DirectoryEntryConverter.cs50
-rw-r--r--src/System.DirectoryServices/src/System/DirectoryServices/DirectoryEntries.cs93
-rw-r--r--src/System.DirectoryServices/src/System/DirectoryServices/DirectoryEntry.cs282
-rw-r--r--src/System.DirectoryServices/src/System/DirectoryServices/DirectoryEntryConfiguration.cs10
-rw-r--r--src/System.DirectoryServices/src/System/DirectoryServices/DirectorySearcher.cs368
-rw-r--r--src/System.DirectoryServices/src/System/DirectoryServices/DirectoryServicesCOMException.cs42
-rw-r--r--src/System.DirectoryServices/src/System/DirectoryServices/DirectoryVirtualListViewContext.cs2
-rw-r--r--src/System.DirectoryServices/src/System/DirectoryServices/ExtendedDn.cs10
-rw-r--r--src/System.DirectoryServices/src/System/DirectoryServices/PrivilegedConfigurationManager.cs27
-rw-r--r--src/System.DirectoryServices/src/System/DirectoryServices/PropertyCollection.cs285
-rw-r--r--src/System.DirectoryServices/src/System/DirectoryServices/PropertyValueCollection.cs135
-rw-r--r--src/System.DirectoryServices/src/System/DirectoryServices/ReferalChasingOption.cs24
-rw-r--r--src/System.DirectoryServices/src/System/DirectoryServices/ResultPropertyCollection.cs45
-rw-r--r--src/System.DirectoryServices/src/System/DirectoryServices/ResultPropertyValueCollection.cs46
-rw-r--r--src/System.DirectoryServices/src/System/DirectoryServices/SchemaNameCollection.cs197
-rw-r--r--src/System.DirectoryServices/src/System/DirectoryServices/SearchResult.cs55
-rw-r--r--src/System.DirectoryServices/src/System/DirectoryServices/SearchResultCollection.cs202
-rw-r--r--src/System.DirectoryServices/src/System/DirectoryServices/SearchScope.cs15
-rw-r--r--src/System.DirectoryServices/src/System/DirectoryServices/SearchWaitHandler.cs70
-rw-r--r--src/System.DirectoryServices/src/System/DirectoryServices/SecurityMasks.cs14
-rw-r--r--src/System.DirectoryServices/src/System/DirectoryServices/SortDirection.cs11
-rw-r--r--src/System.DirectoryServices/tests/System.DirectoryServices.Tests.csproj3
-rw-r--r--src/System.DirectoryServices/tests/System/DirectoryServices/ActiveDirectory/ActiveDirectoryInterSiteTransportTests.cs3
-rw-r--r--src/System.DirectoryServices/tests/System/DirectoryServices/ActiveDirectory/DomainControllerTests.cs6
-rw-r--r--src/System.DirectoryServices/tests/System/DirectoryServices/ActiveDirectory/ForestTests.cs2
-rw-r--r--src/System.Drawing.Common/ref/System.Drawing.Common.cs10
-rw-r--r--src/System.Drawing.Common/src/System.Drawing.Common.csproj7
-rw-r--r--src/System.Drawing.Common/src/System/Drawing/ClientUtils.cs272
-rw-r--r--src/System.Drawing.Common/src/System/Drawing/Drawing2D/AdjustableArrowCap.cs41
-rw-r--r--src/System.Drawing.Common/src/System/Drawing/Drawing2D/GraphicsPath.cs8
-rw-r--r--src/System.Drawing.Common/src/System/Drawing/Drawing2D/LinearGradientBrush.cs9
-rw-r--r--src/System.Drawing.Common/src/System/Drawing/Drawing2D/PathGradientBrush.cs30
-rw-r--r--src/System.Drawing.Common/src/System/Drawing/Font.cs327
-rw-r--r--src/System.Drawing.Common/src/System/Drawing/FontFamily.cs1
-rw-r--r--src/System.Drawing.Common/src/System/Drawing/Gdiplus.cs2314
-rw-r--r--src/System.Drawing.Common/src/System/Drawing/Graphics.cs2088
-rw-r--r--src/System.Drawing.Common/src/System/Drawing/Image.cs2
-rw-r--r--src/System.Drawing.Common/src/System/Drawing/Imaging/EncoderParameters.cs2
-rw-r--r--src/System.Drawing.Common/src/System/Drawing/Imaging/ImageCodecInfo.cs2
-rw-r--r--src/System.Drawing.Common/src/System/Drawing/Imaging/Metafile.cs12
-rw-r--r--src/System.Drawing.Common/src/System/Drawing/Internal/GPPOINT.cs15
-rw-r--r--src/System.Drawing.Common/src/System/Drawing/Internal/GPPOINTF.cs10
-rw-r--r--src/System.Drawing.Common/src/System/Drawing/Internal/GPRECT.cs9
-rw-r--r--src/System.Drawing.Common/src/System/Drawing/Internal/GPRECTF.cs16
-rw-r--r--src/System.Drawing.Common/src/System/Drawing/Internal/GPStream.cs71
-rw-r--r--src/System.Drawing.Common/src/System/Drawing/Internal/ISystemEventTracker.cs2
-rw-r--r--src/System.Drawing.Common/src/System/Drawing/Internal/RectangleFEx.cs14
-rw-r--r--src/System.Drawing.Common/src/System/Drawing/Internal/SystemColorTracker.cs14
-rw-r--r--src/System.Drawing.Common/src/System/Drawing/NativeMethods.cs309
-rw-r--r--src/System.Drawing.Common/src/System/Drawing/Pen.cs14
-rw-r--r--src/System.Drawing.Common/src/System/Drawing/Printing/PageSettings.cs12
-rw-r--r--src/System.Drawing.Common/src/System/Drawing/Printing/PrinterResolution.cs5
-rw-r--r--src/System.Drawing.Common/src/System/Drawing/Printing/PrinterSettings.cs18
-rw-r--r--src/System.Drawing.Common/src/System/Drawing/PropertyItemInternal.cs2
-rw-r--r--src/System.Drawing.Common/src/System/Drawing/Region.cs8
-rw-r--r--src/System.Drawing.Common/src/System/Drawing/StringFormat.cs15
-rw-r--r--src/System.Drawing.Common/src/System/Drawing/SystemFonts.cs235
-rw-r--r--src/System.Drawing.Common/src/System/Drawing/Text/PrivateFontCollection.cs3
-rw-r--r--src/System.Drawing.Common/src/System/Drawing/TextureBrush.cs8
-rw-r--r--src/System.Drawing.Common/src/System/Drawing/ToolboxBitmapAttribute.cs3
-rw-r--r--src/System.Drawing.Common/src/System/Drawing/UnsafeNativeMethods.cs188
-rw-r--r--src/System.Drawing.Common/src/misc/ClientUtils.cs490
-rw-r--r--src/System.Drawing.Common/src/misc/CompModSwitches.cs12
-rw-r--r--src/System.Drawing.Common/src/misc/CoreSwitches.cs26
-rw-r--r--src/System.Drawing.Common/src/misc/DbgUtil.cs192
-rw-r--r--src/System.Drawing.Common/src/misc/DebugHandleTracker.cs27
-rw-r--r--src/System.Drawing.Common/src/misc/DpiHelper.cs17
-rw-r--r--src/System.Drawing.Common/src/misc/ExternDll.cs33
-rw-r--r--src/System.Drawing.Common/src/misc/GDI/DeviceContext.cs95
-rw-r--r--src/System.Drawing.Common/src/misc/GDI/DeviceContextGraphicsMode.cs39
-rw-r--r--src/System.Drawing.Common/src/misc/GDI/DeviceContexts.cs16
-rw-r--r--src/System.Drawing.Common/src/misc/GDI/GdiObjectType.cs27
-rw-r--r--src/System.Drawing.Common/src/misc/GDI/NativeMethods.cs318
-rw-r--r--src/System.Drawing.Common/src/misc/GDI/SafeNativeMethods.cs61
-rw-r--r--src/System.Drawing.Common/src/misc/GDI/UnsafeNativeMethods.cs383
-rw-r--r--src/System.Drawing.Common/src/misc/GDI/WindowsGraphics.cs99
-rw-r--r--src/System.Drawing.Common/src/misc/GDI/WindowsRegion.cs32
-rw-r--r--src/System.Drawing.Common/src/misc/HandleCollector.cs81
-rw-r--r--src/System.Drawing.Common/tests/BrushesTests.cs8
-rw-r--r--src/System.Drawing.Common/tests/Drawing2D/AdjustableArrowCapTests.cs140
-rw-r--r--src/System.Drawing.Common/tests/Drawing2D/CustomLineCapTests.cs247
-rw-r--r--src/System.Drawing.Common/tests/Drawing2D/GraphicsPathIteratorTests.cs427
-rw-r--r--src/System.Drawing.Common/tests/Drawing2D/GraphicsPathTests.cs2684
-rw-r--r--src/System.Drawing.Common/tests/Drawing2D/PathGradientBrushTests.cs1071
-rw-r--r--src/System.Drawing.Common/tests/FontTests.cs852
-rw-r--r--src/System.Drawing.Common/tests/GraphicsTests.cs2059
-rw-r--r--src/System.Drawing.Common/tests/IconTests.cs6
-rw-r--r--src/System.Drawing.Common/tests/Imaging/EncoderParameterTests.cs326
-rw-r--r--src/System.Drawing.Common/tests/Imaging/EncoderParametersTests.cs58
-rw-r--r--src/System.Drawing.Common/tests/PenTests.cs1
-rw-r--r--src/System.Drawing.Common/tests/PensTests.cs8
-rw-r--r--src/System.Drawing.Common/tests/System.Drawing.Common.Tests.csproj11
-rw-r--r--src/System.Drawing.Common/tests/SystemBrushesTests.cs8
-rw-r--r--src/System.Drawing.Common/tests/SystemFontsTests.cs64
-rw-r--r--src/System.Drawing.Common/tests/SystemIconsTests.cs8
-rw-r--r--src/System.Drawing.Common/tests/SystemPensTest.cs8
-rw-r--r--src/System.Drawing.Common/tests/Text/PrivateFontCollectionTests.cs76
-rw-r--r--src/System.Drawing.Primitives/tests/System.Drawing.Primitives.Tests.csproj3
-rw-r--r--src/System.Dynamic.Runtime/tests/System.Dynamic.Runtime.Tests.csproj3
-rw-r--r--src/System.Globalization.Calendars/tests/System.Globalization.Calendars.Tests.csproj3
-rw-r--r--src/System.Globalization.Extensions/tests/System.Globalization.Extensions.Tests.csproj3
-rw-r--r--src/System.Globalization/tests/System.Globalization.Tests.csproj3
-rw-r--r--src/System.IO.Compression.ZipFile/tests/System.IO.Compression.ZipFile.Tests.csproj3
-rw-r--r--src/System.IO.Compression/tests/System.IO.Compression.Tests.csproj3
-rw-r--r--src/System.IO.FileSystem.AccessControl/tests/System.IO.FileSystem.AccessControl.Tests.csproj3
-rw-r--r--src/System.IO.FileSystem.DriveInfo/tests/System.IO.FileSystem.DriveInfo.Tests.csproj3
-rw-r--r--src/System.IO.FileSystem.Watcher/tests/System.IO.FileSystem.Watcher.Tests.csproj3
-rw-r--r--src/System.IO.FileSystem/src/System/IO/Directory.cs7
-rw-r--r--src/System.IO.FileSystem/src/System/IO/DirectoryInfo.cs6
-rw-r--r--src/System.IO.FileSystem/src/System/IO/PathHelpers.Windows.cs5
-rw-r--r--src/System.IO.FileSystem/src/System/IO/UnixFileSystem.cs6
-rw-r--r--src/System.IO.FileSystem/src/System/IO/Win32FileSystem.cs3
-rw-r--r--src/System.IO.FileSystem/tests/Directory/CreateDirectory.cs195
-rw-r--r--src/System.IO.FileSystem/tests/Directory/Exists.cs128
-rw-r--r--src/System.IO.FileSystem/tests/Directory/GetFileSystemEntries_str.cs36
-rw-r--r--src/System.IO.FileSystem/tests/Directory/GetFileSystemEntries_str_str.cs40
-rw-r--r--src/System.IO.FileSystem/tests/DirectoryInfo/CreateSubdirectory.cs97
-rw-r--r--src/System.IO.FileSystem/tests/File/Copy.cs30
-rw-r--r--src/System.IO.FileSystem/tests/File/Create.cs49
-rw-r--r--src/System.IO.FileSystem/tests/File/Exists.cs89
-rw-r--r--src/System.IO.FileSystem/tests/File/Move.cs24
-rw-r--r--src/System.IO.FileSystem/tests/FileSystemTest.cs8
-rw-r--r--src/System.IO.FileSystem/tests/PortedCommon/IOInputs.cs23
-rw-r--r--src/System.IO.FileSystem/tests/System.IO.FileSystem.Tests.csproj3
-rw-r--r--src/System.IO.IsolatedStorage/tests/System.IO.IsolatedStorage.Tests.csproj3
-rw-r--r--src/System.IO.MemoryMappedFiles/tests/System.IO.MemoryMappedFiles.Tests.csproj3
-rw-r--r--src/System.IO.Packaging/src/System.IO.Packaging.csproj6
-rw-r--r--src/System.IO.Packaging/tests/System.IO.Packaging.Tests.csproj3
-rw-r--r--src/System.IO.Pipes/tests/System.IO.Pipes.Tests.csproj3
-rw-r--r--src/System.IO.Ports/tests/System.IO.Ports.Tests.csproj3
-rw-r--r--src/System.IO.UnmanagedMemoryStream/tests/System.IO.UnmanagedMemoryStream.Tests.csproj3
-rw-r--r--src/System.IO.UnmanagedMemoryStream/tests/Uma.ReadWriteStructArray.cs1
-rw-r--r--src/System.IO/tests/BufferedStream/BufferedStreamTests.cs14
-rw-r--r--src/System.IO/tests/Resources/System.IO.Tests.rd.xml6
-rw-r--r--src/System.IO/tests/StreamReader/StreamReader.cs34
-rw-r--r--src/System.IO/tests/System.IO.Tests.csproj6
-rw-r--r--src/System.Json/tests/System.Json.Tests.csproj3
-rw-r--r--src/System.Linq.Expressions/src/Resources/System.Linq.Expressions.rd.xml2
-rw-r--r--src/System.Linq.Expressions/src/System/Linq/Expressions/Interpreter/ArrayOperations.cs10
-rw-r--r--src/System.Linq.Expressions/tests/Array/NewArrayBoundsTests.cs45
-rw-r--r--src/System.Linq.Expressions/tests/System.Linq.Expressions.Tests.csproj4
-rw-r--r--src/System.Linq.Parallel/tests/System.Linq.Parallel.Tests.csproj3
-rw-r--r--src/System.Linq.Queryable/tests/System.Linq.Queryable.Tests.csproj3
-rw-r--r--src/System.Linq/src/System/Linq/AppendPrepend.cs29
-rw-r--r--src/System.Linq/src/System/Linq/Buffer.cs3
-rw-r--r--src/System.Linq/src/System/Linq/Cast.cs5
-rw-r--r--src/System.Linq/src/System/Linq/Concat.cs13
-rw-r--r--src/System.Linq/src/System/Linq/Contains.cs14
-rw-r--r--src/System.Linq/src/System/Linq/Count.cs9
-rw-r--r--src/System.Linq/src/System/Linq/DebugView.cs22
-rw-r--r--src/System.Linq/src/System/Linq/DefaultIfEmpty.cs14
-rw-r--r--src/System.Linq/src/System/Linq/Distinct.cs25
-rw-r--r--src/System.Linq/src/System/Linq/ElementAt.cs18
-rw-r--r--src/System.Linq/src/System/Linq/Enumerable.cs10
-rw-r--r--src/System.Linq/src/System/Linq/First.cs37
-rw-r--r--src/System.Linq/src/System/Linq/Grouping.cs271
-rw-r--r--src/System.Linq/src/System/Linq/Iterator.cs5
-rw-r--r--src/System.Linq/src/System/Linq/Last.cs42
-rw-r--r--src/System.Linq/src/System/Linq/Lookup.cs34
-rw-r--r--src/System.Linq/src/System/Linq/OrderBy.cs24
-rw-r--r--src/System.Linq/src/System/Linq/OrderedEnumerable.cs93
-rw-r--r--src/System.Linq/src/System/Linq/Partition.cs70
-rw-r--r--src/System.Linq/src/System/Linq/Range.cs10
-rw-r--r--src/System.Linq/src/System/Linq/Repeat.cs11
-rw-r--r--src/System.Linq/src/System/Linq/Reverse.cs25
-rw-r--r--src/System.Linq/src/System/Linq/Select.cs125
-rw-r--r--src/System.Linq/src/System/Linq/SequenceEqual.cs15
-rw-r--r--src/System.Linq/src/System/Linq/Set.cs8
-rw-r--r--src/System.Linq/src/System/Linq/Single.cs18
-rw-r--r--src/System.Linq/src/System/Linq/SingleLinkedNode.cs2
-rw-r--r--src/System.Linq/src/System/Linq/Skip.cs11
-rw-r--r--src/System.Linq/src/System/Linq/Take.cs6
-rw-r--r--src/System.Linq/src/System/Linq/ToCollection.cs40
-rw-r--r--src/System.Linq/src/System/Linq/Union.cs33
-rw-r--r--src/System.Linq/src/System/Linq/Utilities.cs12
-rw-r--r--src/System.Linq/src/System/Linq/Where.cs108
-rw-r--r--src/System.Linq/tests/System.Linq.Tests.csproj3
-rw-r--r--src/System.Linq/tests/ToArrayTests.cs27
-rw-r--r--src/System.Memory/tests/System.Memory.Tests.csproj3
-rw-r--r--src/System.Net.Http.WinHttpHandler/src/System.Net.Http.WinHttpHandler.msbuild2
-rw-r--r--src/System.Net.Http.WinHttpHandler/src/System/Net/Http/WinHttpCertificateHelper.cs47
-rw-r--r--src/System.Net.Http.WinHttpHandler/src/System/Net/Http/WinHttpHandler.cs4
-rw-r--r--src/System.Net.Http.WinHttpHandler/src/System/Net/Http/WinHttpRequestCallback.cs6
-rw-r--r--src/System.Net.Http.WinHttpHandler/src/System/Net/Http/WinHttpResponseStream.cs5
-rw-r--r--src/System.Net.Http.WinHttpHandler/tests/UnitTests/FakeX509Certificates.cs2
-rw-r--r--src/System.Net.Http.WinHttpHandler/tests/UnitTests/System.Net.Http.WinHttpHandler.Unit.Tests.csproj10
-rw-r--r--src/System.Net.Http/src/Resources/Strings.resx6
-rw-r--r--src/System.Net.Http/src/System.Net.Http.csproj22
-rw-r--r--src/System.Net.Http/src/System/Net/Http/Headers/ContentRangeHeaderValue.cs7
-rw-r--r--src/System.Net.Http/src/System/Net/Http/Headers/HeaderUtilities.cs63
-rw-r--r--src/System.Net.Http/src/System/Net/Http/Headers/HttpGeneralHeaders.cs50
-rw-r--r--src/System.Net.Http/src/System/Net/Http/Headers/HttpRequestHeaders.cs2
-rw-r--r--src/System.Net.Http/src/System/Net/Http/Headers/HttpResponseHeaders.cs2
-rw-r--r--src/System.Net.Http/src/System/Net/Http/Headers/Int32NumberHeaderParser.cs2
-rw-r--r--src/System.Net.Http/src/System/Net/Http/Headers/Int64NumberHeaderParser.cs2
-rw-r--r--src/System.Net.Http/src/System/Net/Http/Headers/RangeItemHeaderValue.cs4
-rw-r--r--src/System.Net.Http/src/System/Net/Http/Headers/RetryConditionHeaderValue.cs2
-rw-r--r--src/System.Net.Http/src/System/Net/Http/Headers/TimeSpanHeaderParser.cs2
-rw-r--r--src/System.Net.Http/src/System/Net/Http/Headers/WarningHeaderValue.cs2
-rw-r--r--src/System.Net.Http/src/System/Net/Http/HttpClientHandler.Core.cs52
-rw-r--r--src/System.Net.Http/src/System/Net/Http/HttpClientHandler.Windows.cs1
-rw-r--r--src/System.Net.Http/src/System/Net/Http/Managed/ConnectHelper.cs47
-rw-r--r--src/System.Net.Http/src/System/Net/Http/Managed/HttpConnection.cs94
-rw-r--r--src/System.Net.Http/src/System/Net/Http/Managed/HttpConnectionHandler.cs6
-rw-r--r--src/System.Net.Http/src/System/Net/Http/Managed/HttpConnectionPool.cs11
-rw-r--r--src/System.Net.Http/src/System/Net/Http/Managed/HttpProxyConnectionHandler.cs4
-rw-r--r--src/System.Net.Http/src/System/Net/Http/OSX/CurlHandler.SslProvider.cs20
-rw-r--r--src/System.Net.Http/src/System/Net/Http/Unix/CurlException.cs5
-rw-r--r--src/System.Net.Http/src/System/Net/Http/Unix/CurlHandler.MultiAgent.cs44
-rw-r--r--src/System.Net.Http/src/System/Net/Http/Unix/CurlHandler.SslProvider.cs169
-rw-r--r--src/System.Net.Http/src/System/Net/Http/Unix/CurlHandler.cs20
-rw-r--r--src/System.Net.Http/src/uap/System/Net/CookieHelper.cs (renamed from src/System.Net.Http/src/netcore50/System/Net/CookieHelper.cs)0
-rw-r--r--src/System.Net.Http/src/uap/System/Net/HttpClientHandler.cs (renamed from src/System.Net.Http/src/netcore50/System/Net/HttpClientHandler.cs)236
-rw-r--r--src/System.Net.Http/src/uap/System/Net/HttpHandlerToFilter.cs (renamed from src/System.Net.Http/src/netcore50/System/Net/HttpHandlerToFilter.cs)29
-rw-r--r--src/System.Net.Http/src/uap/System/Net/cookie.cs (renamed from src/System.Net.Http/src/netcore50/System/Net/cookie.cs)0
-rw-r--r--src/System.Net.Http/src/uap/System/Net/cookieexception.cs (renamed from src/System.Net.Http/src/netcore50/System/Net/cookieexception.cs)0
-rw-r--r--src/System.Net.Http/tests/FunctionalTests/HttpClientHandlerTest.AcceptAllCerts.cs12
-rw-r--r--src/System.Net.Http/tests/FunctionalTests/HttpClientHandlerTest.ClientCertificates.cs142
-rw-r--r--src/System.Net.Http/tests/FunctionalTests/HttpClientHandlerTest.ServerCertificates.Unix.cs13
-rw-r--r--src/System.Net.Http/tests/FunctionalTests/HttpClientHandlerTest.ServerCertificates.Windows.cs3
-rw-r--r--src/System.Net.Http/tests/FunctionalTests/HttpClientHandlerTest.ServerCertificates.cs215
-rw-r--r--src/System.Net.Http/tests/FunctionalTests/HttpClientHandlerTest.SslProtocols.Unix.cs3
-rw-r--r--src/System.Net.Http/tests/FunctionalTests/HttpClientHandlerTest.SslProtocols.cs19
-rw-r--r--src/System.Net.Http/tests/FunctionalTests/HttpClientHandlerTest.cs309
-rw-r--r--src/System.Net.Http/tests/FunctionalTests/HttpClientMiniStressTest.cs3
-rw-r--r--src/System.Net.Http/tests/FunctionalTests/ManagedHandlerTest.cs186
-rw-r--r--src/System.Net.Http/tests/FunctionalTests/MultiInterfaceNonRewindableReadOnlyStream.cs132
-rw-r--r--src/System.Net.Http/tests/FunctionalTests/MultiInterfaceReadOnlyStream.cs210
-rw-r--r--src/System.Net.Http/tests/FunctionalTests/MultiInterfaceStreamContent.cs24
-rw-r--r--src/System.Net.Http/tests/FunctionalTests/PostScenarioUWPTest.cs162
-rw-r--r--src/System.Net.Http/tests/FunctionalTests/System.Net.Http.Functional.Tests.csproj10
-rw-r--r--src/System.Net.Http/tests/UnitTests/System.Net.Http.Unit.Tests.csproj3
-rw-r--r--src/System.Net.HttpListener/src/System.Net.HttpListener.csproj9
-rw-r--r--src/System.Net.HttpListener/src/System/Net/Windows/CookieExtensions.cs39
-rw-r--r--src/System.Net.HttpListener/tests/HttpListenerAuthenticationTests.cs27
-rw-r--r--src/System.Net.HttpListener/tests/HttpListenerContextTests.cs14
-rw-r--r--src/System.Net.HttpListener/tests/HttpListenerFactory.cs91
-rw-r--r--src/System.Net.HttpListener/tests/HttpListenerPrefixCollectionTests.cs42
-rw-r--r--src/System.Net.HttpListener/tests/HttpListenerRequestTests.cs32
-rw-r--r--src/System.Net.HttpListener/tests/HttpListenerResponseTests.Cookies.cs11
-rw-r--r--src/System.Net.HttpListener/tests/HttpListenerResponseTests.Headers.cs64
-rw-r--r--src/System.Net.HttpListener/tests/HttpListenerResponseTests.cs16
-rw-r--r--src/System.Net.HttpListener/tests/HttpListenerTests.cs13
-rw-r--r--src/System.Net.HttpListener/tests/HttpListenerTimeoutManagerTests.cs27
-rw-r--r--src/System.Net.HttpListener/tests/HttpListenerWebSocketTests.cs26
-rw-r--r--src/System.Net.HttpListener/tests/HttpRequestStreamTests.cs36
-rw-r--r--src/System.Net.HttpListener/tests/HttpResponseStreamTests.cs34
-rw-r--r--src/System.Net.HttpListener/tests/InvalidClientRequestTests.cs1
-rw-r--r--src/System.Net.HttpListener/tests/Resources/System.Net.HttpListener.Tests.rd.xml6
-rw-r--r--src/System.Net.HttpListener/tests/SimpleHttpTests.cs11
-rw-r--r--src/System.Net.HttpListener/tests/System.Net.HttpListener.Tests.csproj22
-rw-r--r--src/System.Net.HttpListener/tests/WebSocketTests.cs1
-rw-r--r--src/System.Net.Mail/src/System/Net/Mail/SmtpClient.cs16
-rw-r--r--src/System.Net.Mail/tests/Functional/SmtpClientTest.cs7
-rw-r--r--src/System.Net.Mail/tests/Functional/SmtpServer.cs5
-rw-r--r--src/System.Net.Mail/tests/Functional/System.Net.Mail.Functional.Tests.csproj6
-rw-r--r--src/System.Net.NameResolution/tests/UnitTests/InitializationTest.cs1
-rw-r--r--src/System.Net.NetworkInformation/src/System.Net.NetworkInformation.csproj8
-rw-r--r--src/System.Net.Ping/tests/FunctionalTests/PingTest.cs30
-rw-r--r--src/System.Net.Ping/tests/FunctionalTests/System.Net.Ping.Functional.Tests.csproj3
-rw-r--r--src/System.Net.Primitives/src/Resources/System.Net.Primitives.rd.xml22
-rw-r--r--src/System.Net.Primitives/src/System.Net.Primitives.csproj3
-rw-r--r--src/System.Net.Primitives/src/System/Net/Cookie.cs81
-rw-r--r--src/System.Net.Primitives/src/System/Net/CookieCollection.cs16
-rw-r--r--src/System.Net.Primitives/tests/FunctionalTests/System.Net.Primitives.Functional.Tests.csproj3
-rw-r--r--src/System.Net.Primitives/tests/UnitTests/System.Net.Primitives.UnitTests.Tests.csproj3
-rw-r--r--src/System.Net.Requests/tests/System.Net.Requests.Tests.csproj3
-rw-r--r--src/System.Net.Security/src/System/Net/Security/SecureChannel.cs5
-rw-r--r--src/System.Net.Security/tests/FunctionalTests/NegotiateStreamStreamToStreamTest.cs22
-rw-r--r--src/System.Net.Security/tests/FunctionalTests/SslStreamSystemDefaultsTest.cs251
-rw-r--r--src/System.Net.Security/tests/FunctionalTests/System.Net.Security.Tests.csproj3
-rw-r--r--src/System.Net.Security/tests/UnitTests/System.Net.Security.Unit.Tests.csproj3
-rw-r--r--src/System.Net.ServicePoint/tests/System.Net.ServicePoint.Tests.csproj3
-rw-r--r--src/System.Net.Sockets/src/System.Net.Sockets.csproj19
-rw-r--r--src/System.Net.Sockets/src/System/Net/Sockets/SocketAsyncEventArgs.Windows.cs140
-rw-r--r--src/System.Net.Sockets/src/System/Net/Sockets/SocketPal.Unix.cs23
-rw-r--r--src/System.Net.Sockets/tests/FunctionalTests/ReceiveMessageFromAsync.cs133
-rw-r--r--src/System.Net.Sockets/tests/FunctionalTests/SendReceive.cs29
-rw-r--r--src/System.Net.Sockets/tests/FunctionalTests/System.Net.Sockets.Tests.csproj3
-rw-r--r--src/System.Net.WebClient/tests/System.Net.WebClient.Tests.csproj3
-rw-r--r--src/System.Net.WebClient/tests/WebClientTest.cs17
-rw-r--r--src/System.Net.WebHeaderCollection/tests/System.Net.WebHeaderCollection.Tests.csproj3
-rw-r--r--src/System.Net.WebProxy/tests/System.Net.WebProxy.Tests.csproj3
-rw-r--r--src/System.Net.WebSockets.Client/src/Resources/Strings.resx6
-rw-r--r--src/System.Net.WebSockets.Client/src/System.Net.WebSockets.Client.csproj6
-rw-r--r--src/System.Net.WebSockets.Client/src/System/Net/WebSockets/WinRTWebSocket.cs101
-rw-r--r--src/System.Net.WebSockets.Client/tests/CancelTest.cs1
-rw-r--r--src/System.Net.WebSockets.Client/tests/ClientWebSocketOptionsTests.cs8
-rw-r--r--src/System.Net.WebSockets.Client/tests/ClientWebSocketUnitTest.cs49
-rw-r--r--src/System.Net.WebSockets.Client/tests/CloseTest.cs30
-rw-r--r--src/System.Net.WebSockets.Client/tests/SendReceiveTest.cs5
-rw-r--r--src/System.Net.WebSockets.Client/tests/System.Net.WebSockets.Client.Tests.csproj6
-rw-r--r--src/System.Net.WebSockets/tests/System.Net.WebSockets.Tests.csproj3
-rw-r--r--src/System.Numerics.Vectors/pkg/System.Numerics.Vectors.pkgproj2
-rw-r--r--src/System.Numerics.Vectors/src/System.Numerics.Vectors.csproj4
-rw-r--r--src/System.Numerics.Vectors/tests/GenericVectorTests.cs107
-rw-r--r--src/System.Numerics.Vectors/tests/GenericVectorTests.tt90
-rw-r--r--src/System.Numerics.Vectors/tests/System.Numerics.Vectors.Tests.csproj6
-rw-r--r--src/System.ObjectModel/src/System/Collections/ObjectModel/ObservableCollection.cs4
-rw-r--r--src/System.ObjectModel/src/System/Collections/ObjectModel/ReadOnlyObservableCollection.cs2
-rw-r--r--src/System.ObjectModel/tests/System.ObjectModel.Tests.csproj3
-rw-r--r--src/System.Private.Reflection.Metadata.Ecma335/src/Shims/Marshal.cs10
-rw-r--r--src/System.Private.Uri/tests/ExtendedFunctionalTests/System.Private.Uri.ExtendedFunctional.Tests.csproj3
-rw-r--r--src/System.Private.Uri/tests/FunctionalTests/System.Private.Uri.Functional.Tests.csproj3
-rw-r--r--src/System.Private.Xml.Linq/tests/Properties/System.Xml.Linq.Properties.Tests.csproj3
-rw-r--r--src/System.Private.Xml.Linq/tests/SDMSample/System.Xml.Linq.SDMSample.Tests.csproj3
-rw-r--r--src/System.Private.Xml.Linq/tests/Streaming/System.Xml.Linq.Streaming.Tests.csproj3
-rw-r--r--src/System.Private.Xml.Linq/tests/XDocument.Test.ModuleCore/testexception.cs4
-rw-r--r--src/System.Private.Xml.Linq/tests/axes/System.Xml.Linq.Axes.Tests.csproj3
-rw-r--r--src/System.Private.Xml.Linq/tests/misc/System.Xml.Linq.Misc.Tests.csproj3
-rw-r--r--src/System.Private.Xml.Linq/tests/xNodeBuilder/ErrorConditions.cs64
-rw-r--r--src/System.Private.Xml.Linq/tests/xNodeBuilder/System.Xml.Linq.xNodeBuilder.Tests.csproj3
-rw-r--r--src/System.Private.Xml/src/System.Private.Xml.csproj2
-rw-r--r--src/System.Private.Xml/src/System/Xml/Core/XmlReader.cs4
-rw-r--r--src/System.Private.Xml/src/System/Xml/Schema/XmlSchema.cs2
-rw-r--r--src/System.Private.Xml/src/System/Xml/Serialization/ReflectionXmlSerializationWriter.cs21
-rw-r--r--src/System.Private.Xml/src/System/Xml/Serialization/Types.cs18
-rw-r--r--src/System.Private.Xml/src/System/Xml/Serialization/XmlSerializationWriter.cs4
-rw-r--r--src/System.Private.Xml/src/System/Xml/XmlResolver.cs2
-rw-r--r--src/System.Private.Xml/tests/Writers/XmlWriterApi/TCXmlWriterTestModule.cs1
-rw-r--r--src/System.Private.Xml/tests/XmlDocument/System.Xml.XmlDocument.Tests.csproj3
-rw-r--r--src/System.Private.Xml/tests/XmlReader/Tests/BaseUriTests.cs2
-rw-r--r--src/System.Private.Xml/tests/XmlReader/XmlResolver/XmlSystemPathResolverTests.cs2
-rw-r--r--src/System.Private.Xml/tests/XmlSchema/XmlSchemaSet/System.Xml.XmlSchemaSet.Tests.csproj1
-rw-r--r--src/System.Private.Xml/tests/XmlSchema/XmlSchemaSet/TC_SchemaSet_AnyAttribute.cs193
-rw-r--r--src/System.Private.Xml/tests/XmlSerializer/ReflectionOnly/System.Xml.XmlSerializer.ReflectionOnly.Tests.csproj3
-rw-r--r--src/System.Private.Xml/tests/XmlSerializer/System.Xml.XmlSerializer.Tests.csproj3
-rw-r--r--src/System.Private.Xml/tests/XmlSerializer/XmlSerializerTests.cs137
-rw-r--r--src/System.Private.Xml/tests/XmlWriter/System.Xml.RW.XmlWriter.Tests.csproj3
-rw-r--r--src/System.Reflection.DispatchProxy/pkg/System.Reflection.DispatchProxy.pkgproj4
-rw-r--r--src/System.Reflection.DispatchProxy/tests/System.Reflection.DispatchProxy.Tests.csproj3
-rw-r--r--src/System.Reflection.Emit.ILGeneration/tests/System.Reflection.Emit.ILGeneration.Tests.csproj3
-rw-r--r--src/System.Reflection.Emit.Lightweight/tests/System.Reflection.Emit.Lightweight.Tests.csproj3
-rw-r--r--src/System.Reflection.Emit/tests/System.Reflection.Emit.Tests.csproj3
-rw-r--r--src/System.Reflection.Extensions/tests/System.Reflection.Extensions.Tests.csproj3
-rw-r--r--src/System.Reflection.Metadata/pkg/System.Reflection.Metadata.pkgproj2
-rw-r--r--src/System.Reflection.Metadata/src/System/Reflection/Metadata/TypeSystem/ModuleDefinition.cs5
-rw-r--r--src/System.Reflection.Metadata/tests/System.Reflection.Metadata.Tests.csproj3
-rw-r--r--src/System.Reflection.TypeExtensions/pkg/System.Reflection.TypeExtensions.pkgproj4
-rw-r--r--src/System.Reflection.TypeExtensions/tests/System.Reflection.TypeExtensions.Tests.csproj3
-rw-r--r--src/System.Reflection/tests/System.Reflection.Tests.csproj3
-rw-r--r--src/System.Resources.Reader/tests/System.Resources.Reader.Tests.csproj3
-rw-r--r--src/System.Resources.Writer/tests/System.Resources.Writer.Tests.csproj3
-rw-r--r--src/System.Runtime.Extensions/src/System/Environment.cs7
-rw-r--r--src/System.Runtime.Extensions/src/System/IO/BufferedStream.cs3
-rw-r--r--src/System.Runtime.Extensions/src/System/IO/StreamReader.cs8
-rw-r--r--src/System.Runtime.Extensions/tests/System.Runtime.Extensions.Tests.csproj3
-rw-r--r--src/System.Runtime.Extensions/tests/System/AppDomainTests.cs1
-rw-r--r--src/System.Runtime.Extensions/tests/System/EnvironmentTests.cs9
-rw-r--r--src/System.Runtime.InteropServices.RuntimeInformation/tests/System.Runtime.InteropServices.RuntimeInformation.Tests.csproj3
-rw-r--r--src/System.Runtime.InteropServices.WindowsRuntime/tests/System.Runtime.InteropServices.WindowsRuntime.Tests.csproj3
-rw-r--r--src/System.Runtime.InteropServices/tests/System.Runtime.InteropServices.Tests.csproj3
-rw-r--r--src/System.Runtime.Loader/tests/DefaultContext/DefaultLoadContextTest.cs115
-rw-r--r--src/System.Runtime.Loader/tests/DefaultContext/System.Runtime.Loader.DefaultContext.Tests.csproj3
-rw-r--r--src/System.Runtime.Numerics/tests/System.Runtime.Numerics.Tests.csproj3
-rw-r--r--src/System.Runtime.Serialization.Formatters/tests/BinaryFormatterTestData.cs20
-rw-r--r--src/System.Runtime.Serialization.Formatters/tests/FormatterServicesTests.cs13
-rw-r--r--src/System.Runtime.Serialization.Formatters/tests/System.Runtime.Serialization.Formatters.Tests.csproj3
-rw-r--r--src/System.Runtime.Serialization.Json/tests/DataContractJsonSerializer.cs26
-rw-r--r--src/System.Runtime.Serialization.Json/tests/ReflectionOnly/System.Runtime.Serialization.Json.ReflectionOnly.Tests.csproj3
-rw-r--r--src/System.Runtime.Serialization.Json/tests/System.Runtime.Serialization.Json.Tests.csproj3
-rw-r--r--src/System.Runtime.Serialization.Xml/tests/DataContractSerializer.cs62
-rw-r--r--src/System.Runtime.Serialization.Xml/tests/DataContractSerializerTestData.cs21
-rw-r--r--src/System.Runtime.Serialization.Xml/tests/ReflectionOnly/System.Runtime.Serialization.Xml.ReflectionOnly.Tests.csproj1
-rw-r--r--src/System.Runtime.Serialization.Xml/tests/SerializationTypes.cs124
-rw-r--r--src/System.Runtime.Serialization.Xml/tests/System.Runtime.Serialization.Xml.Tests.csproj1
-rw-r--r--src/System.Runtime.WindowsRuntime.UI.Xaml/tests/System.Runtime.WindowsRuntime.UI.Xaml.Tests.csproj3
-rw-r--r--src/System.Runtime.WindowsRuntime.UI.Xaml/tests/Windows/UI/Xaml/Media/Animation/RepeatBehaviorTests.cs5
-rw-r--r--src/System.Runtime.WindowsRuntime/src/System/Resources/WindowsRuntimeResourceManager.cs26
-rw-r--r--src/System.Runtime.WindowsRuntime/tests/System.Runtime.WindowsRuntime.Tests.csproj3
-rw-r--r--src/System.Runtime/tests/ArrayTests.cs282
-rw-r--r--src/System.Runtime/tests/ArrayTests.netcoreapp.cs3
-rw-r--r--src/System.Runtime/tests/DBNullTests.cs83
-rw-r--r--src/System.Runtime/tests/EnumTests.cs45
-rw-r--r--src/System.Runtime/tests/GetTypeCodeTests.cs36
-rw-r--r--src/System.Runtime/tests/Resources/System.Runtime.Tests.rd.xml7
-rw-r--r--src/System.Runtime/tests/System.Runtime.Tests.csproj173
-rw-r--r--src/System.Runtime/tests/System/ArrayTests.cs285
-rw-r--r--src/System.Runtime/tests/System/ArrayTests.netcoreapp.cs15
-rw-r--r--src/System.Runtime/tests/System/BooleanTests.cs57
-rw-r--r--src/System.Runtime/tests/System/ByteTests.cs32
-rw-r--r--src/System.Runtime/tests/System/CharTests.cs27
-rw-r--r--src/System.Runtime/tests/System/DBNullTests.cs148
-rw-r--r--src/System.Runtime/tests/System/DecimalTests.cs210
-rw-r--r--src/System.Runtime/tests/System/DoubleTests.cs32
-rw-r--r--src/System.Runtime/tests/System/EnumTests.cs33
-rw-r--r--src/System.Runtime/tests/System/EnumTests.netcoreapp.cs3
-rw-r--r--src/System.Runtime/tests/System/GCTests.cs70
-rw-r--r--src/System.Runtime/tests/System/GCTests.netcoreapp.cs1
-rw-r--r--src/System.Runtime/tests/System/Int16Tests.cs29
-rw-r--r--src/System.Runtime/tests/System/Int32Tests.cs28
-rw-r--r--src/System.Runtime/tests/System/Int64Tests.cs29
-rw-r--r--src/System.Runtime/tests/System/Runtime/MemoryFailPointTests.cs36
-rw-r--r--src/System.Runtime/tests/System/Runtime/Tests.netstandard.1.7.cs37
-rw-r--r--src/System.Runtime/tests/System/SByteTests.cs28
-rw-r--r--src/System.Runtime/tests/System/SingleTests.cs31
-rw-r--r--src/System.Runtime/tests/System/StringTests.cs30
-rw-r--r--src/System.Runtime/tests/System/TimeZoneNotFoundExceptionTests.cs (renamed from src/System.Runtime/tests/TimeZoneNotFoundExceptionTests.cs)0
-rw-r--r--src/System.Runtime/tests/System/TimeZoneTests.cs (renamed from src/System.Runtime/tests/TimeZoneTests.cs)0
-rw-r--r--src/System.Runtime/tests/System/UInt16Tests.cs29
-rw-r--r--src/System.Runtime/tests/System/UInt32Tests.cs29
-rw-r--r--src/System.Runtime/tests/System/UInt64Tests.cs32
-rw-r--r--src/System.Runtime/tests/System/VersionTests.cs113
-rw-r--r--src/System.Runtime/tests/VersionTests.cs39
-rw-r--r--src/System.Runtime/tests/netstandard.1.7.Tests.cs43
-rw-r--r--src/System.Security.AccessControl/pkg/System.Security.AccessControl.pkgproj2
-rw-r--r--src/System.Security.AccessControl/ref/System.Security.AccessControl.csproj6
-rw-r--r--src/System.Security.AccessControl/tests/System.Security.AccessControl.Tests.csproj3
-rw-r--r--src/System.Security.Claims/tests/System.Security.Claims.Tests.csproj3
-rw-r--r--src/System.Security.Cryptography.Algorithms/ref/Configurations.props1
-rw-r--r--src/System.Security.Cryptography.Algorithms/ref/System.Security.Cryptography.Algorithms.csproj8
-rw-r--r--src/System.Security.Cryptography.Algorithms/src/Configurations.props1
-rw-r--r--src/System.Security.Cryptography.Algorithms/src/System.Security.Cryptography.Algorithms.csproj14
-rw-r--r--src/System.Security.Cryptography.Algorithms/tests/System.Security.Cryptography.Algorithms.Tests.csproj3
-rw-r--r--src/System.Security.Cryptography.Cng/pkg/System.Security.Cryptography.Cng.pkgproj2
-rw-r--r--src/System.Security.Cryptography.Cng/tests/System.Security.Cryptography.Cng.Tests.csproj3
-rw-r--r--src/System.Security.Cryptography.Csp/tests/System.Security.Cryptography.Csp.Tests.csproj3
-rw-r--r--src/System.Security.Cryptography.Encoding/tests/System.Security.Cryptography.Encoding.Tests.csproj3
-rw-r--r--src/System.Security.Cryptography.OpenSsl/tests/System.Security.Cryptography.OpenSsl.Tests.csproj3
-rw-r--r--src/System.Security.Cryptography.Pkcs/tests/System.Security.Cryptography.Pkcs.Tests.csproj3
-rw-r--r--src/System.Security.Cryptography.Primitives/tests/System.Security.Cryptography.Primitives.Tests.csproj3
-rw-r--r--src/System.Security.Cryptography.X509Certificates/src/Internal/Cryptography/Pal.Unix/OpenSslX509ChainProcessor.cs1
-rw-r--r--src/System.Security.Cryptography.X509Certificates/src/Internal/Cryptography/Pal.Windows/CertificatePal.Import.cs3
-rw-r--r--src/System.Security.Cryptography.X509Certificates/src/Internal/Cryptography/Pal.Windows/CertificatePal.PrivateKey.cs24
-rw-r--r--src/System.Security.Cryptography.X509Certificates/src/Internal/Cryptography/Pal.Windows/CertificatePal.cs4
-rw-r--r--src/System.Security.Cryptography.X509Certificates/src/Internal/Cryptography/Pal.Windows/Native/Interop.crypt32.cs4
-rw-r--r--src/System.Security.Cryptography.X509Certificates/src/Internal/Cryptography/Pal.Windows/Native/Interop.cryptoapi.cs2
-rw-r--r--src/System.Security.Cryptography.X509Certificates/src/Internal/Cryptography/Pal.Windows/Native/SafeHandles.cs2
-rw-r--r--src/System.Security.Cryptography.X509Certificates/src/Internal/Cryptography/Pal.Windows/X509Pal.PublicKey.cs27
-rw-r--r--src/System.Security.Cryptography.X509Certificates/src/System.Security.Cryptography.X509Certificates.csproj1
-rw-r--r--src/System.Security.Cryptography.X509Certificates/tests/Cert.cs2
-rw-r--r--src/System.Security.Cryptography.X509Certificates/tests/CertTests.cs17
-rw-r--r--src/System.Security.Cryptography.X509Certificates/tests/CertificateCreation/CertificateRequestApiTests.cs26
-rw-r--r--src/System.Security.Cryptography.X509Certificates/tests/CertificateCreation/CertificateRequestChainTests.cs3
-rw-r--r--src/System.Security.Cryptography.X509Certificates/tests/CertificateCreation/CertificateRequestUsageTests.cs3
-rw-r--r--src/System.Security.Cryptography.X509Certificates/tests/CertificateCreation/ECDsaX509SignatureGeneratorTests.cs2
-rw-r--r--src/System.Security.Cryptography.X509Certificates/tests/CertificateCreation/RSAPkcs1X509SignatureGeneratorTests.cs2
-rw-r--r--src/System.Security.Cryptography.X509Certificates/tests/CertificateCreation/RSAPssX509SignatureGeneratorTests.cs2
-rw-r--r--src/System.Security.Cryptography.X509Certificates/tests/ChainTests.cs6
-rw-r--r--src/System.Security.Cryptography.X509Certificates/tests/CollectionImportTests.cs23
-rw-r--r--src/System.Security.Cryptography.X509Certificates/tests/CollectionTests.cs9
-rw-r--r--src/System.Security.Cryptography.X509Certificates/tests/Configurations.props1
-rw-r--r--src/System.Security.Cryptography.X509Certificates/tests/CtorTests.cs4
-rw-r--r--src/System.Security.Cryptography.X509Certificates/tests/PfxTests.cs20
-rw-r--r--src/System.Security.Cryptography.X509Certificates/tests/PublicKeyTests.cs10
-rw-r--r--src/System.Security.Cryptography.X509Certificates/tests/System.Security.Cryptography.X509Certificates.Tests.csproj8
-rw-r--r--src/System.Security.Cryptography.Xml/src/System/Security/Cryptography/Xml/CryptoHelpers.cs10
-rw-r--r--src/System.Security.Cryptography.Xml/src/System/Security/Cryptography/Xml/DSASignatureDescription.cs14
-rw-r--r--src/System.Security.Cryptography.Xml/src/System/Security/Cryptography/Xml/RSAPKCS1SHA1SignatureDescription.cs8
-rw-r--r--src/System.Security.Cryptography.Xml/src/System/Security/Cryptography/Xml/RSAPKCS1SHA256SignatureDescription.cs6
-rw-r--r--src/System.Security.Cryptography.Xml/src/System/Security/Cryptography/Xml/RSAPKCS1SHA384SignatureDescription.cs6
-rw-r--r--src/System.Security.Cryptography.Xml/src/System/Security/Cryptography/Xml/RSAPKCS1SHA512SignatureDescription.cs6
-rw-r--r--src/System.Security.Cryptography.Xml/src/System/Security/Cryptography/Xml/RSAPKCS1SignatureDescription.cs12
-rw-r--r--src/System.Security.Cryptography.Xml/tests/System.Security.Cryptography.Xml.Tests.csproj3
-rw-r--r--src/System.Security.Permissions/ref/System.Security.Permissions.csproj6
-rw-r--r--src/System.Security.Permissions/tests/System.Security.Permissions.Tests.csproj3
-rw-r--r--src/System.Security.Principal.Windows/pkg/System.Security.Principal.Windows.pkgproj2
-rw-r--r--src/System.Security.Principal.Windows/ref/System.Security.Principal.Windows.csproj6
-rw-r--r--src/System.Security.Principal.Windows/src/PinvokeAnalyzerExceptionList.analyzerdata.uap1
-rw-r--r--src/System.Security.Principal.Windows/src/System.Security.Principal.Windows.csproj16
-rw-r--r--src/System.Security.Principal.Windows/src/System/Security/Principal/WindowsIdentity.cs10
-rw-r--r--src/System.Security.Principal.Windows/src/System/Security/Principal/WindowsPrincipal.cs9
-rw-r--r--src/System.Security.Principal.Windows/tests/System.Security.Principal.Windows.Tests.csproj3
-rw-r--r--src/System.Security.Principal.Windows/tests/WindowsIdentityTests.cs10
-rw-r--r--src/System.Security.Principal/src/System.Security.Principal.csproj1
-rw-r--r--src/System.Security.SecureString/tests/System.Security.SecureString.Tests.csproj3
-rw-r--r--src/System.ServiceProcess.ServiceController/tests/System.ServiceProcess.ServiceController.Tests/System.ServiceProcess.ServiceController.Tests.csproj3
-rw-r--r--src/System.Text.Encoding.CodePages/pkg/System.Text.Encoding.CodePages.pkgproj2
-rw-r--r--src/System.Text.Encoding.CodePages/tests/System.Text.Encoding.CodePages.Tests.csproj3
-rw-r--r--src/System.Text.Encoding/tests/Encoding/Encoding.cs3
-rw-r--r--src/System.Text.Encoding/tests/System.Text.Encoding.Tests.csproj3
-rw-r--r--src/System.Text.Encoding/tests/UTF32Encoding/UTF32EncodingTests.cs1
-rw-r--r--src/System.Text.Encoding/tests/UnicodeEncoding/UnicodeEncodingDecode.cs3
-rw-r--r--src/System.Text.Encoding/tests/UnicodeEncoding/UnicodeEncodingTests.cs1
-rw-r--r--src/System.Text.Encodings.Web/tests/System.Text.Encodings.Web.Tests.csproj3
-rw-r--r--src/System.Text.RegularExpressions/tests/Regex.Groups.Tests.cs194
-rw-r--r--src/System.Text.RegularExpressions/tests/Regex.Match.Tests.cs11
-rw-r--r--src/System.Text.RegularExpressions/tests/System.Text.RegularExpressions.Tests.csproj6
-rw-r--r--src/System.Threading.Overlapped/tests/System.Threading.Overlapped.Tests.csproj3
-rw-r--r--src/System.Threading.Tasks.Dataflow/pkg/System.Threading.Tasks.Dataflow.pkgproj2
-rw-r--r--src/System.Threading.Tasks.Dataflow/tests/System.Threading.Tasks.Dataflow.Tests.csproj3
-rw-r--r--src/System.Threading.Tasks.Extensions/src/System/Runtime/CompilerServices/AsyncMethodBuilderAttribute.cs5
-rw-r--r--src/System.Threading.Tasks.Extensions/src/System/Runtime/CompilerServices/AsyncValueTaskMethodBuilder.cs4
-rw-r--r--src/System.Threading.Tasks.Extensions/src/System/Runtime/CompilerServices/ConfiguredValueTaskAwaitable.cs22
-rw-r--r--src/System.Threading.Tasks.Extensions/src/System/Runtime/CompilerServices/ValueTaskAwaiter.cs18
-rw-r--r--src/System.Threading.Tasks.Extensions/src/System/Threading/Tasks/ValueTask.cs72
-rw-r--r--src/System.Threading.Tasks.Extensions/tests/System.Threading.Tasks.Extensions.Tests.csproj3
-rw-r--r--src/System.Threading.Tasks.Parallel/tests/System.Threading.Tasks.Parallel.Tests.csproj3
-rw-r--r--src/System.Threading.Tasks/tests/System.Threading.Tasks.Tests.csproj3
-rw-r--r--src/System.Threading.Thread/tests/System.Threading.Thread.Tests.csproj3
-rw-r--r--src/System.Threading/src/System.Threading.csproj8
-rw-r--r--src/System.Threading/src/System/Threading/Barrier.cs2
-rw-r--r--src/System.Threading/tests/BarrierTests.cs39
-rw-r--r--src/System.Threading/tests/EtwTests.cs1
-rw-r--r--src/System.Threading/tests/MutexTests.cs1
-rw-r--r--src/System.Threading/tests/ReaderWriterLockTests.cs25
-rw-r--r--src/System.Threading/tests/System.Threading.Tests.csproj3
-rw-r--r--src/System.Transactions.Local/tests/System.Transactions.Local.Tests.csproj3
-rw-r--r--src/System.ValueTuple/pkg/System.ValueTuple.pkgproj2
-rw-r--r--src/System.ValueTuple/tests/System.ValueTuple.Tests.csproj3
-rw-r--r--tools-local/targetgroups.props30
832 files changed, 25858 insertions, 18051 deletions
diff --git a/BuildToolsVersion.txt b/BuildToolsVersion.txt
index c8c426f199..d8caee9fe1 100644
--- a/BuildToolsVersion.txt
+++ b/BuildToolsVersion.txt
@@ -1 +1 @@
-2.0.0-prerelease-01726-03 \ No newline at end of file
+2.0.0-prerelease-01812-02
diff --git a/Documentation/debugging/windows-instructions.md b/Documentation/debugging/windows-instructions.md
index a6da9330a4..45943cc1e5 100644
--- a/Documentation/debugging/windows-instructions.md
+++ b/Documentation/debugging/windows-instructions.md
@@ -149,6 +149,9 @@ The following EventSources are built-in to CoreFX. The ones that are not marked
* `*System.Linq.Parallel.PlinqEventSource {159eeeec-4a14-4418-a8fe-faabcd987887}`: Provides an event source for tracing PLINQ information.
#### System.Net namespaces
+
+Helper scripts are available at https://github.com/dotnet/corefx/tree/master/src/Common/tests/Scripts/Tools. Run `net_startlog.cmd` as Administrator, run the application, then run `net_stoplog.cmd`. Open the `.etl` file with PerfView.
+
* `*Microsoft-System-Net-Http {bdd9a83e-1929-5482-0d73-2fe5e1c0e16d}`: HTTP-related traces.
* `*Microsoft-System-Net-Mail {42c8027b-f048-58d2-537d-a4a9d5ee7038}`: SMTP-related traces.
* `*Microsoft-System-Net-NameResolution {5f302add-3825-520e-8fa0-627b206e2e7e}`: DNS-related traces.
diff --git a/Documentation/project-docs/issue-guide.md b/Documentation/project-docs/issue-guide.md
index e8e5cb3de9..88b89cbc10 100644
--- a/Documentation/project-docs/issue-guide.md
+++ b/Documentation/project-docs/issue-guide.md
@@ -44,7 +44,7 @@ Areas are tracked by labels area-&#42; (e.g. area-System.Collections). Each area
|-----------------------------------------------------------------------------------------------|------------------|-------------|
| [area-Infrastructure](https://github.com/dotnet/corefx/labels/area-Infrastructure) | [@mellinoe](https://github.com/mellinoe), [@ericstj](https://github.com/ericstj), [@weshaggard](https://github.com/weshaggard) |Covers:<ul><li>Packaging</li><li>Build and test infra for CoreFX repo</li><li>VS integration</li></ul><br/> |
| [area-Meta](https://github.com/dotnet/corefx/labels/area-Meta) | [@tarekgh](https://github.com/tarekgh) | Issues without clear association to any specific API/contract, e.g. <ul><li>new contract proposals</li><li>cross-cutting code/test pattern changes (e.g. FxCop failures)</li><li>project-wide docs</li></ul><br/> |
-| [area-Serialization](https://github.com/dotnet/corefx/labels/area-Serialization) | [@shmao](https://github.com/shmao), [@zhenlan](https://github.com/zhenlan) | Packages:<ul><li>System.Runtime.Serialization.Xml</li><li>System.Runtime.Serialization.Json</li><li>System.Private.DataContractSerialization</li><li>System.Xml.XmlSerialization</li></ul> Excluded:<ul><li>System.Runtime.Serialization.Formatters</li></ul> |
+| [area-Serialization](https://github.com/dotnet/corefx/labels/area-Serialization) | [@shmao](https://github.com/shmao), [@zhenlan](https://github.com/zhenlan) | Packages:<ul><li>System.Runtime.Serialization.Xml</li><li>System.Runtime.Serialization.Json</li><li>System.Private.DataContractSerialization</li><li>System.Xml.XmlSerializer</li></ul> Excluded:<ul><li>System.Runtime.Serialization.Formatters</li></ul> |
| **System contract assemblies** | | |
| [System.AppContext](https://github.com/dotnet/corefx/labels/area-System.AppContext) | [@AlexGhiondea](https://github.com/AlexGhiondea) | | |
| [System.Buffers](https://github.com/dotnet/corefx/labels/area-System.Buffers) | [@safern](https://github.com/safern) | |
diff --git a/build.proj b/build.proj
index 775f6a5418..e00c9826dc 100644
--- a/build.proj
+++ b/build.proj
@@ -55,7 +55,7 @@
<Target Name="UpdateVSConfigurations">
<Message Importance="High" Text="Updating configurations for projects ..." />
<ItemGroup>
- <_projectsToExcludeFromUpdate Include="$(MSBuildThisFileDirectory)src/**/RestoreSDKProject.csproj" />
+ <_projectsToExcludeFromUpdate Include="$(MSBuildThisFileDirectory)src/SharedFrameworkValidation/**/*.csproj" />
<_projectsToUpdate Include="$(MSBuildThisFileDirectory)src/**/*.*csproj" Exclude="@(_projectsToExcludeFromUpdate)" />
<_projectsToUpdate Include="$(MSBuildThisFileDirectory)src/**/*.*ilproj" Exclude="@(_projectsToExcludeFromUpdate)" />
<_solutionsToUpdateFiles Include="$(MSBuildThisFileDirectory)src/*/dir.props" />
diff --git a/buildpipeline/DotNet-CoreFx-Trusted-Linux-Crossbuild.json b/buildpipeline/DotNet-CoreFx-Trusted-Linux-Crossbuild.json
index d5568222d5..a189c04748 100644
--- a/buildpipeline/DotNet-CoreFx-Trusted-Linux-Crossbuild.json
+++ b/buildpipeline/DotNet-CoreFx-Trusted-Linux-Crossbuild.json
@@ -4,23 +4,7 @@
"enabled": true,
"continueOnError": false,
"alwaysRun": false,
- "displayName": "Delete files from $(Build.SourcesDirectory)",
- "timeoutInMinutes": 0,
- "task": {
- "id": "b7e8b412-0437-4065-9371-edc5881de25b",
- "versionSpec": "1.*",
- "definitionType": "task"
- },
- "inputs": {
- "SourceFolder": "$(Build.SourcesDirectory)",
- "Contents": "**\n.gitignore"
- }
- },
- {
- "enabled": true,
- "continueOnError": false,
- "alwaysRun": false,
- "displayName": "git clone",
+ "displayName": "Change permissions to agent folder for cleanup steps",
"timeoutInMinutes": 0,
"task": {
"id": "d9bafed4-0b18-4f58-968d-86655b4d2ce9",
@@ -28,9 +12,9 @@
"definitionType": "task"
},
"inputs": {
- "filename": "git",
- "arguments": "clone $(PB_VsoCorefxGitUrl) corefx",
- "workingFolder": "",
+ "filename": "sudo",
+ "arguments": "chmod 777 -R .",
+ "workingFolder": "$(Agent.WorkFolder)",
"failOnStandardError": "false"
}
},
@@ -38,43 +22,23 @@
"enabled": true,
"continueOnError": false,
"alwaysRun": false,
- "displayName": "git checkout",
+ "displayName": "Delete files from $(PB_GitDirectory)",
"timeoutInMinutes": 0,
"task": {
- "id": "d9bafed4-0b18-4f58-968d-86655b4d2ce9",
- "versionSpec": "1.*",
- "definitionType": "task"
- },
- "inputs": {
- "filename": "git",
- "arguments": "checkout $(SourceVersion)",
- "workingFolder": "$(Build.SourcesDirectory)/corefx",
- "failOnStandardError": "false"
- }
- },
- {
- "enabled": true,
- "continueOnError": false,
- "alwaysRun": true,
- "displayName": "Initialize tools",
- "timeoutInMinutes": 0,
- "task": {
- "id": "d9bafed4-0b18-4f58-968d-86655b4d2ce9",
+ "id": "b7e8b412-0437-4065-9371-edc5881de25b",
"versionSpec": "1.*",
"definitionType": "task"
},
"inputs": {
- "filename": "$(Build.SourcesDirectory)/corefx/init-tools.sh",
- "arguments": "",
- "workingFolder": "",
- "failOnStandardError": "false"
+ "SourceFolder": "$(PB_GitDirectory)",
+ "Contents": "**\n.gitignore\n.editorconfig\n.gitattributes\n.gitmirrorall\n.git/**\n.git"
}
},
{
"enabled": true,
"continueOnError": false,
"alwaysRun": false,
- "displayName": "Initialize Docker",
+ "displayName": "git clone",
"timeoutInMinutes": 0,
"task": {
"id": "d9bafed4-0b18-4f58-968d-86655b4d2ce9",
@@ -82,8 +46,8 @@
"definitionType": "task"
},
"inputs": {
- "filename": "$(Build.SourcesDirectory)/corefx/Tools/scripts/docker/init-docker.sh",
- "arguments": "$(PB_DockerImageName)",
+ "filename": "git",
+ "arguments": "clone $(PB_VsoCorefxGitUrl) $(PB_GitDirectory)",
"workingFolder": "",
"failOnStandardError": "false"
}
@@ -92,7 +56,7 @@
"enabled": true,
"continueOnError": false,
"alwaysRun": false,
- "displayName": "Start detached docker container",
+ "displayName": "git checkout",
"timeoutInMinutes": 0,
"task": {
"id": "d9bafed4-0b18-4f58-968d-86655b4d2ce9",
@@ -100,9 +64,9 @@
"definitionType": "task"
},
"inputs": {
- "filename": "docker",
- "arguments": "run --privileged -d -w $(PB_GitDirectory) --name $(PB_DockerContainerName) $(PB_DockerImageName) sleep 7200",
- "workingFolder": "",
+ "filename": "git",
+ "arguments": "checkout $(SourceVersion)",
+ "workingFolder": "$(PB_GitDirectory)",
"failOnStandardError": "false"
}
},
@@ -110,7 +74,7 @@
"enabled": true,
"continueOnError": false,
"alwaysRun": false,
- "displayName": "Clone repository",
+ "displayName": "Initialize tools",
"timeoutInMinutes": 0,
"task": {
"id": "d9bafed4-0b18-4f58-968d-86655b4d2ce9",
@@ -118,9 +82,9 @@
"definitionType": "task"
},
"inputs": {
- "filename": "docker",
- "arguments": "exec $(PB_DockerContainerName) git clone $(PB_VsoCorefxGitUrl) $(PB_GitDirectory)",
- "workingFolder": "",
+ "filename": "$(PB_GitDirectory)/init-tools.sh",
+ "arguments": "",
+ "workingFolder": "$(PB_GitDirectory)",
"failOnStandardError": "false"
}
},
@@ -128,7 +92,7 @@
"enabled": true,
"continueOnError": false,
"alwaysRun": false,
- "displayName": "Check out the specified commit",
+ "displayName": "Initialize Docker",
"timeoutInMinutes": 0,
"task": {
"id": "d9bafed4-0b18-4f58-968d-86655b4d2ce9",
@@ -136,8 +100,8 @@
"definitionType": "task"
},
"inputs": {
- "filename": "docker",
- "arguments": "exec $(PB_DockerContainerName) git checkout $(SourceVersion)",
+ "filename": "$(PB_GitDirectory)/Tools/scripts/docker/init-docker.sh",
+ "arguments": "$(PB_DockerImageName)",
"workingFolder": "",
"failOnStandardError": "false"
}
@@ -155,7 +119,7 @@
},
"inputs": {
"filename": "docker",
- "arguments": "exec $(PB_DockerContainerName) $(PB_GitDirectory)/build-managed.sh -OfficialBuildId=$(OfficialBuildId) -- /t:GenerateVersionSourceFile /p:GenerateVersionSourceFile=true",
+ "arguments": "run $(PB_DockerCommonRunArgs) $(PB_DockerVolumeName)/build-managed.sh -OfficialBuildId=$(OfficialBuildId) -- /t:GenerateVersionSourceFile /p:GenerateVersionSourceFile=true",
"workingFolder": "",
"failOnStandardError": "false"
}
@@ -173,7 +137,7 @@
},
"inputs": {
"filename": "docker",
- "arguments": "exec $(PB_DockerContainerName) $(PB_GitDirectory)/sync.sh -p -- /p:ArchGroup=$(PB_Architecture)",
+ "arguments": "run $(PB_DockerCommonRunArgs) $(PB_DockerVolumeName)/sync.sh -p -- /p:ArchGroup=$(PB_Architecture)",
"workingFolder": "",
"failOnStandardError": "false"
}
@@ -191,7 +155,7 @@
},
"inputs": {
"filename": "docker",
- "arguments": "exec -e ROOTFS_DIR $(PB_DockerContainerName) $(PB_GitDirectory)/build.sh -OfficialBuildId=$(OfficialBuildId) $(PB_BuildArguments)",
+ "arguments": "run -e ROOTFS_DIR $(PB_DockerCommonRunArgs) $(PB_DockerVolumeName)/build.sh -OfficialBuildId=$(OfficialBuildId) $(PB_BuildArguments)",
"workingFolder": "",
"failOnStandardError": "false"
}
@@ -209,59 +173,7 @@
},
"inputs": {
"filename": "docker",
- "arguments": "exec $(PB_DockerContainerName) $(PB_GitDirectory)/publish-packages.sh -AzureAccount=$(PB_CloudDropAccountName) -AzureToken=$(CloudDropAccessToken) -Container=$(PB_Label) -verbose -- /p:OverwriteOnPublish=false",
- "workingFolder": "",
- "failOnStandardError": "false"
- }
- },
- {
- "enabled": true,
- "continueOnError": true,
- "alwaysRun": true,
- "displayName": "Remove old docker build logs",
- "timeoutInMinutes": 0,
- "task": {
- "id": "b7e8b412-0437-4065-9371-edc5881de25b",
- "versionSpec": "1.*",
- "definitionType": "task"
- },
- "inputs": {
- "SourceFolder": "$(PB_DockerCopyDest)",
- "Contents": "*"
- }
- },
- {
- "enabled": true,
- "continueOnError": true,
- "alwaysRun": true,
- "displayName": "Expose docker repo for publishing",
- "timeoutInMinutes": 0,
- "task": {
- "id": "d9bafed4-0b18-4f58-968d-86655b4d2ce9",
- "versionSpec": "1.*",
- "definitionType": "task"
- },
- "inputs": {
- "filename": "docker",
- "arguments": "cp $(PB_DockerContainerName):$(PB_GitDirectory) $(PB_DockerCopyDest)",
- "workingFolder": "",
- "failOnStandardError": "false"
- }
- },
- {
- "enabled": true,
- "continueOnError": true,
- "alwaysRun": true,
- "displayName": "Remove container",
- "timeoutInMinutes": 0,
- "task": {
- "id": "d9bafed4-0b18-4f58-968d-86655b4d2ce9",
- "versionSpec": "1.*",
- "definitionType": "task"
- },
- "inputs": {
- "filename": "docker",
- "arguments": "rm -f $(PB_DockerContainerName)",
+ "arguments": "run $(PB_DockerCommonRunArgs) $(PB_DockerVolumeName)/publish-packages.sh -AzureAccount=$(PB_CloudDropAccountName) -AzureToken=$(CloudDropAccessToken) -Container=$(PB_Label) -verbose -- /p:OverwriteOnPublish=false",
"workingFolder": "",
"failOnStandardError": "false"
}
@@ -278,7 +190,7 @@
"definitionType": "task"
},
"inputs": {
- "CopyRoot": "$(PB_DockerCopyDest)/corefx",
+ "CopyRoot": "$(PB_GitDirectory)",
"Contents": "*.log",
"ArtifactName": "BuildLogs",
"ArtifactType": "Container",
@@ -297,7 +209,7 @@
"definitionType": "task"
},
"inputs": {
- "filename": "$(Build.SourcesDirectory)/corefx/Tools/scripts/docker/cleanup-docker.sh",
+ "filename": "$(PB_GitDirectory)/Tools/scripts/docker/cleanup-docker.sh",
"arguments": "",
"workingFolder": "",
"failOnStandardError": "false"
@@ -315,7 +227,7 @@
"definitionType": "task"
},
"inputs": {
- "filename": "$(Build.SourcesDirectory)/corefx/Tools/msbuild.sh",
+ "filename": "$(PB_GitDirectory)/Tools/msbuild.sh",
"arguments": "cleanupagent.proj /p:AgentDirectory=$(Agent.HomeDirectory) /p:DoClean=$(PB_CleanAgent)",
"workingFolder": "$(Build.SourcesDirectory)/corefx/Tools/scripts/vstsagent/",
"failOnStandardError": "false"
@@ -326,6 +238,25 @@
{
"enabled": false,
"definition": {
+ "id": "5d58cc01-7c75-450c-be18-a388ddb129ec"
+ },
+ "inputs": {
+ "branchFilters": "[\"+refs/heads/*\"]",
+ "additionalFields": "{}"
+ }
+ },
+ {
+ "enabled": false,
+ "definition": {
+ "id": "5bc3cfb7-6b54-4a4b-b5d2-a3905949f8a6"
+ },
+ "inputs": {
+ "additionalFields": "{}"
+ }
+ },
+ {
+ "enabled": false,
+ "definition": {
"id": "7c555368-ca64-4199-add6-9ebaf0b0137d"
},
"inputs": {
@@ -357,22 +288,40 @@
}
],
"variables": {
- "system.debug": {
- "value": "false",
- "allowOverride": true
+ "CloudDropAccessToken": {
+ "value": null,
+ "isSecret": true
+ },
+ "GitHubBranch": {
+ "value": "sni_plus_latestbuildtools"
+ },
+ "OfficialBuildId": {
+ "value": "$(Build.BuildNumber)"
+ },
+ "PB_Architecture": {
+ "value": "arm"
+ },
+ "PB_BuildArguments": {
+ "value": "-BuildArch=$(PB_Architecture)"
+ },
+ "PB_CleanAgent": {
+ "value": "true"
+ },
+ "PB_CloudDropAccountName": {
+ "value": "dotnetbuildoutput"
},
"PB_ConfigurationGroup": {
"value": "Release"
},
- "PB_VsoCorefxGitUrl": {
- "value": "http://github.com/dotnet/corefx.git"
- },
- "PB_GitDirectory": {
- "value": "/root/corefx"
+ "PB_DockerCommonRunArgs": {
+ "value": "--rm --name $(PB_DockerContainerName) -v \"$(PB_GitDirectory):$(PB_DockerVolumeName)\" -w=\"$(PB_DockerVolumeName)\" $(PB_DockerImageName)"
},
"PB_DockerContainerName": {
"value": "corefx-cross-$(Build.BuildId)"
},
+ "PB_DockerCopyDest": {
+ "value": "$(Build.BinariesDirectory)/docker_repo"
+ },
"PB_DockerImageName": {
"value": "$(PB_DockerRepository):$(PB_DockerTag)"
},
@@ -380,47 +329,45 @@
"value": "microsoft/dotnet-buildtools-prereqs"
},
"PB_DockerTag": {
- "value": "ubuntu1404_cross_prereqs_v2",
+ "value": "ubuntu-14.04-cross-0cd4667-20172211042239",
"allowOverride": true
},
- "PB_CloudDropAccountName": {
- "value": "dotnetbuildoutput"
- },
- "CloudDropAccessToken": {
- "value": null,
- "isSecret": true
+ "PB_DockerVolumeName": {
+ "value": "/root/corefx-$(Build.BuildId)"
},
- "OfficialBuildId": {
- "value": "$(Build.BuildNumber)"
+ "PB_GitDirectory": {
+ "value": "$(Build.SourcesDirectory)/corefx"
},
"PB_Label": {
"value": "$(Build.BuildNumber)"
},
- "GitHubBranch": {
- "value": "sni_plus_latestbuildtools"
+ "PB_VsoAccountName": {
+ "value": "dn-bot"
},
- "PB_Architecture": {
- "value": "arm"
+ "PB_VsoCorefxGitUrl": {
+ "value": "https://$(PB_VsoAccountName):$(VsoPassword)@devdiv.visualstudio.com/DevDiv/_git/$(PB_VsoRepositoryName)/"
},
- "PB_BuildArguments": {
+ "PB_VsoRepositoryName": {
+ "value": "DotNet-CoreFX-Trusted"
+ },
+ "portableBuild": {
"value": ""
},
+ "ROOTFS_DIR": {
+ "value": "/crossrootfs/$(PB_Architecture)",
+ "allowOverride": true
+ },
"SourceVersion": {
"value": "HEAD",
"allowOverride": true
},
- "PB_DockerCopyDest": {
- "value": "$(Build.BinariesDirectory)/docker_repo"
- },
- "ROOTFS_DIR": {
- "value": "/crossrootfs/$(PB_Architecture)",
+ "system.debug": {
+ "value": "false",
"allowOverride": true
},
- "portableBuild": {
- "value": ""
- },
- "PB_CleanAgent": {
- "value": "true"
+ "VsoPassword": {
+ "value": null,
+ "isSecret": true
}
},
"demands": [
@@ -445,6 +392,7 @@
"buildNumberFormat": "$(date:yyyyMMdd)$(rev:-rr)",
"jobAuthorizationScope": "projectCollection",
"jobTimeoutInMinutes": 90,
+ "jobCancelTimeoutInMinutes": 5,
"repository": {
"properties": {
"labelSources": "0",
@@ -452,7 +400,9 @@
"fetchDepth": "0",
"gitLfsSupport": "false",
"skipSyncSource": "false",
- "cleanOptions": "0"
+ "cleanOptions": "0",
+ "checkoutNestedSubmodules": "false",
+ "labelSourcesFormat": "$(build.buildNumber)"
},
"id": "58fa2458-e392-4373-ba2b-dd3ef0c2d7ce",
"type": "TfsGit",
@@ -462,26 +412,27 @@
"clean": "false",
"checkoutSubmodules": false
},
+ "processParameters": {},
"quality": "definition",
"queue": {
+ "id": 36,
+ "name": "DotNet-Build",
"pool": {
"id": 39,
"name": "DotNet-Build"
- },
- "id": 36,
- "name": "DotNet-Build"
+ }
},
- "path": "\\",
- "type": "build",
"id": 5247,
"name": "DotNet-CoreFx-Trusted-Linux-Crossbuild",
- "url": "https://devdiv.visualstudio.com/DefaultCollection/0bdbc590-a062-4c3f-b0f6-9383f67865ee/_apis/build/Definitions/5247",
+ "path": "\\",
+ "type": "build",
"project": {
"id": "0bdbc590-a062-4c3f-b0f6-9383f67865ee",
"name": "DevDiv",
"description": "Visual Studio and DevDiv team project for git source code repositories. Work items will be added for Adams, Dev14 work items are tracked in vstfdevdiv. ",
"url": "https://devdiv.visualstudio.com/DefaultCollection/_apis/projects/0bdbc590-a062-4c3f-b0f6-9383f67865ee",
"state": "wellFormed",
- "revision": 418097503
+ "revision": 418097767,
+ "visibility": "private"
}
} \ No newline at end of file
diff --git a/buildpipeline/DotNet-CoreFx-Trusted-Linux.json b/buildpipeline/DotNet-CoreFx-Trusted-Linux.json
index 86de94303e..f5469b2e3c 100644
--- a/buildpipeline/DotNet-CoreFx-Trusted-Linux.json
+++ b/buildpipeline/DotNet-CoreFx-Trusted-Linux.json
@@ -4,23 +4,7 @@
"enabled": true,
"continueOnError": false,
"alwaysRun": false,
- "displayName": "Delete files from $(Build.SourcesDirectory)",
- "timeoutInMinutes": 0,
- "task": {
- "id": "b7e8b412-0437-4065-9371-edc5881de25b",
- "versionSpec": "1.*",
- "definitionType": "task"
- },
- "inputs": {
- "SourceFolder": "$(Build.SourcesDirectory)",
- "Contents": "**\n.gitignore"
- }
- },
- {
- "enabled": true,
- "continueOnError": false,
- "alwaysRun": false,
- "displayName": "git clone",
+ "displayName": "Change permissions to agent folder for cleanup steps",
"timeoutInMinutes": 0,
"task": {
"id": "d9bafed4-0b18-4f58-968d-86655b4d2ce9",
@@ -28,53 +12,33 @@
"definitionType": "task"
},
"inputs": {
- "filename": "git",
- "arguments": "clone $(PB_VsoCorefxGitUrl) corefx",
- "workingFolder": "",
+ "filename": "sudo",
+ "arguments": "chmod 777 -R .",
+ "workingFolder": "$(Agent.WorkFolder)",
"failOnStandardError": "false"
}
},
{
"enabled": true,
- "continueOnError": false,
+ "continueOnError": true,
"alwaysRun": false,
- "displayName": "git checkout",
- "timeoutInMinutes": 0,
- "task": {
- "id": "d9bafed4-0b18-4f58-968d-86655b4d2ce9",
- "versionSpec": "1.*",
- "definitionType": "task"
- },
- "inputs": {
- "filename": "git",
- "arguments": "checkout $(SourceVersion)",
- "workingFolder": "$(Build.SourcesDirectory)/corefx",
- "failOnStandardError": "false"
- }
- },
- {
- "enabled": true,
- "continueOnError": false,
- "alwaysRun": true,
- "displayName": "Initialize tools",
+ "displayName": "Delete files from $(PB_GitDirectory)",
"timeoutInMinutes": 0,
"task": {
- "id": "d9bafed4-0b18-4f58-968d-86655b4d2ce9",
+ "id": "b7e8b412-0437-4065-9371-edc5881de25b",
"versionSpec": "1.*",
"definitionType": "task"
},
"inputs": {
- "filename": "$(Build.SourcesDirectory)/corefx/init-tools.sh",
- "arguments": "",
- "workingFolder": "",
- "failOnStandardError": "false"
+ "SourceFolder": "$(PB_GitDirectory)",
+ "Contents": "**\n.gitignore\n.editorconfig\n.gitattributes\n.gitmirrorall\n.git/**\n.git"
}
},
{
"enabled": true,
"continueOnError": false,
"alwaysRun": false,
- "displayName": "Initialize Docker",
+ "displayName": "git clone",
"timeoutInMinutes": 0,
"task": {
"id": "d9bafed4-0b18-4f58-968d-86655b4d2ce9",
@@ -82,8 +46,8 @@
"definitionType": "task"
},
"inputs": {
- "filename": "$(Build.SourcesDirectory)/corefx/Tools/scripts/docker/init-docker.sh",
- "arguments": "$(PB_DockerImageName)",
+ "filename": "git",
+ "arguments": "clone $(PB_VsoCorefxGitUrl) $(PB_GitDirectory)",
"workingFolder": "",
"failOnStandardError": "false"
}
@@ -92,7 +56,7 @@
"enabled": true,
"continueOnError": false,
"alwaysRun": false,
- "displayName": "Start detached docker container",
+ "displayName": "git checkout",
"timeoutInMinutes": 0,
"task": {
"id": "d9bafed4-0b18-4f58-968d-86655b4d2ce9",
@@ -100,9 +64,9 @@
"definitionType": "task"
},
"inputs": {
- "filename": "docker",
- "arguments": "run -d -w $(PB_GitDirectory) --name $(PB_DockerContainerName) $(PB_DockerImageName) sleep 7200",
- "workingFolder": "",
+ "filename": "git",
+ "arguments": "checkout $(SourceVersion)",
+ "workingFolder": "$(PB_GitDirectory)",
"failOnStandardError": "false"
}
},
@@ -110,7 +74,7 @@
"enabled": true,
"continueOnError": false,
"alwaysRun": false,
- "displayName": "Clone repository",
+ "displayName": "Initialize tools",
"timeoutInMinutes": 0,
"task": {
"id": "d9bafed4-0b18-4f58-968d-86655b4d2ce9",
@@ -118,9 +82,9 @@
"definitionType": "task"
},
"inputs": {
- "filename": "docker",
- "arguments": "exec $(PB_DockerContainerName) git clone $(PB_VsoCorefxGitUrl) $(PB_GitDirectory)",
- "workingFolder": "",
+ "filename": "$(PB_GitDirectory)/init-tools.sh",
+ "arguments": "",
+ "workingFolder": "$(PB_GitDirectory)",
"failOnStandardError": "false"
}
},
@@ -128,7 +92,7 @@
"enabled": true,
"continueOnError": false,
"alwaysRun": false,
- "displayName": "Check out the specified commit",
+ "displayName": "Initialize Docker",
"timeoutInMinutes": 0,
"task": {
"id": "d9bafed4-0b18-4f58-968d-86655b4d2ce9",
@@ -136,8 +100,8 @@
"definitionType": "task"
},
"inputs": {
- "filename": "docker",
- "arguments": "exec $(PB_DockerContainerName) git checkout $(SourceVersion)",
+ "filename": "$(Build.SourcesDirectory)/corefx/Tools/scripts/docker/init-docker.sh",
+ "arguments": "$(PB_DockerImageName)",
"workingFolder": "",
"failOnStandardError": "false"
}
@@ -155,7 +119,7 @@
},
"inputs": {
"filename": "docker",
- "arguments": "exec $(PB_DockerContainerName) $(PB_GitDirectory)/build-managed.sh -OfficialBuildId=$(OfficialBuildId) -- /t:GenerateVersionSourceFile /p:GenerateVersionSourceFile=true",
+ "arguments": "run $(PB_DockerCommonRunArgs) $(PB_DockerVolumeName)/build-managed.sh -OfficialBuildId=$(OfficialBuildId) -- /t:GenerateVersionSourceFile /p:GenerateVersionSourceFile=true",
"workingFolder": "",
"failOnStandardError": "false"
}
@@ -173,7 +137,7 @@
},
"inputs": {
"filename": "docker",
- "arguments": "exec $(PB_DockerContainerName) $(PB_GitDirectory)/sync.sh $(PB_SyncArguments)",
+ "arguments": "run $(PB_DockerCommonRunArgs) $(PB_DockerVolumeName)/sync.sh $(PB_SyncArguments)",
"workingFolder": "",
"failOnStandardError": "false"
}
@@ -191,7 +155,7 @@
},
"inputs": {
"filename": "docker",
- "arguments": "exec $(PB_DockerContainerName) $(PB_GitDirectory)/build.sh -OfficialBuildId=$(OfficialBuildId) $(PB_BuildArguments)",
+ "arguments": "run $(PB_DockerCommonRunArgs) $(PB_DockerVolumeName)/build.sh -OfficialBuildId=$(OfficialBuildId) $(PB_BuildArguments)",
"workingFolder": "",
"failOnStandardError": "false"
}
@@ -209,7 +173,7 @@
},
"inputs": {
"filename": "docker",
- "arguments": "exec $(PB_DockerContainerName) $(PB_GitDirectory)/build-tests.sh $(PB_BuildTestsArguments)",
+ "arguments": "run $(PB_DockerCommonRunArgs) $(PB_DockerVolumeName)/build-tests.sh $(PB_BuildTestsArguments)",
"workingFolder": "",
"failOnStandardError": "false"
}
@@ -227,7 +191,7 @@
},
"inputs": {
"filename": "docker",
- "arguments": "exec $(PB_DockerContainerName) $(PB_GitDirectory)/Tools/msbuild.sh $(PB_GitDirectory)/src/upload-tests.proj $(PB_CreateHelixArguments) /p:\"CloudDropAccountName=$(PB_CloudDropAccountName)\" /p:\"CloudResultsAccountName=$(PB_CloudResultsAccountName)\" /p:\"CloudDropAccessToken=$(CloudDropAccessToken)\" /p:\"CloudResultsAccessToken=$(OutputCloudResultsAccessToken)\" /p:\"HelixApiAccessKey=$(HelixApiAccessKey)\" /p:HelixApiEndpoint=$(PB_HelixApiEndPoint) /p:\"Branch=$(SourceBranch)\" /p:TargetQueues=$(PB_TargetQueue) /p:\"OfficialBuildId=$(OfficialBuildId)\"",
+ "arguments": "run $(PB_DockerCommonRunArgs) $(PB_DockerVolumeName)/Tools/msbuild.sh $(PB_DockerVolumeName)/src/upload-tests.proj $(PB_CreateHelixArguments) /p:\"CloudDropAccountName=$(PB_CloudDropAccountName)\" /p:\"CloudResultsAccountName=$(PB_CloudResultsAccountName)\" /p:\"CloudDropAccessToken=$(CloudDropAccessToken)\" /p:\"CloudResultsAccessToken=$(PB_CloudResultsAccessToken)\" /p:\"HelixApiAccessKey=$(HelixApiAccessKey)\" /p:HelixApiEndpoint=$(PB_HelixApiEndPoint) /p:\"Branch=$(SourceBranch)\" /p:TargetQueues=$(PB_TargetQueue) /p:\"OfficialBuildId=$(OfficialBuildId)\"",
"workingFolder": "",
"failOnStandardError": "false"
}
@@ -245,59 +209,7 @@
},
"inputs": {
"filename": "docker",
- "arguments": "exec $(PB_DockerContainerName) $(PB_GitDirectory)/publish-packages.sh -AzureAccount=$(PB_CloudDropAccountName) -AzureToken=$(CloudDropAccessToken) -Container=$(PB_Label) -verbose -- /p:OverwriteOnPublish=false",
- "workingFolder": "",
- "failOnStandardError": "false"
- }
- },
- {
- "enabled": true,
- "continueOnError": true,
- "alwaysRun": true,
- "displayName": "Remove old docker build logs",
- "timeoutInMinutes": 0,
- "task": {
- "id": "b7e8b412-0437-4065-9371-edc5881de25b",
- "versionSpec": "1.*",
- "definitionType": "task"
- },
- "inputs": {
- "SourceFolder": "$(PB_DockerCopyDest)",
- "Contents": "*"
- }
- },
- {
- "enabled": true,
- "continueOnError": true,
- "alwaysRun": true,
- "displayName": "Expose docker repo for publishing",
- "timeoutInMinutes": 0,
- "task": {
- "id": "d9bafed4-0b18-4f58-968d-86655b4d2ce9",
- "versionSpec": "1.*",
- "definitionType": "task"
- },
- "inputs": {
- "filename": "docker",
- "arguments": "cp $(PB_DockerContainerName):$(PB_GitDirectory) $(PB_DockerCopyDest)",
- "workingFolder": "",
- "failOnStandardError": "false"
- }
- },
- {
- "enabled": true,
- "continueOnError": true,
- "alwaysRun": true,
- "displayName": "Remove container",
- "timeoutInMinutes": 0,
- "task": {
- "id": "d9bafed4-0b18-4f58-968d-86655b4d2ce9",
- "versionSpec": "1.*",
- "definitionType": "task"
- },
- "inputs": {
- "filename": "docker",
- "arguments": "rm -f $(PB_DockerContainerName)",
+ "arguments": "run $(PB_DockerCommonRunArgs) $(PB_DockerVolumeName)/publish-packages.sh -AzureAccount=$(PB_CloudDropAccountName) -AzureToken=$(CloudDropAccessToken) -Container=$(PB_Label) -verbose -- /p:OverwriteOnPublish=false",
"workingFolder": "",
"failOnStandardError": "false"
}
@@ -314,7 +226,7 @@
"definitionType": "task"
},
"inputs": {
- "CopyRoot": "$(PB_DockerCopyDest)/corefx",
+ "CopyRoot": "$(PB_GitDirectory)",
"Contents": "*.log",
"ArtifactName": "BuildLogs",
"ArtifactType": "Container",
@@ -333,7 +245,7 @@
"definitionType": "task"
},
"inputs": {
- "filename": "$(Build.SourcesDirectory)/corefx/Tools/scripts/docker/cleanup-docker.sh",
+ "filename": "$(PB_GitDirectory)/Tools/scripts/docker/cleanup-docker.sh",
"arguments": "",
"workingFolder": "",
"failOnStandardError": "false"
@@ -351,9 +263,9 @@
"definitionType": "task"
},
"inputs": {
- "filename": "$(Build.SourcesDirectory)/corefx/Tools/msbuild.sh",
+ "filename": "$(PB_GitDirectory)/Tools/msbuild.sh",
"arguments": "cleanupagent.proj /p:AgentDirectory=$(Agent.HomeDirectory) /p:DoClean=$(PB_CleanAgent)",
- "workingFolder": "$(Build.SourcesDirectory)/corefx/Tools/scripts/vstsagent/",
+ "workingFolder": "$(PB_GitDirectory)/Tools/scripts/vstsagent/",
"failOnStandardError": "false"
}
}
@@ -362,6 +274,25 @@
{
"enabled": false,
"definition": {
+ "id": "5d58cc01-7c75-450c-be18-a388ddb129ec"
+ },
+ "inputs": {
+ "branchFilters": "[\"+refs/heads/*\"]",
+ "additionalFields": "{}"
+ }
+ },
+ {
+ "enabled": false,
+ "definition": {
+ "id": "5bc3cfb7-6b54-4a4b-b5d2-a3905949f8a6"
+ },
+ "inputs": {
+ "additionalFields": "{}"
+ }
+ },
+ {
+ "enabled": false,
+ "definition": {
"id": "7c555368-ca64-4199-add6-9ebaf0b0137d"
},
"inputs": {
@@ -393,16 +324,48 @@
}
],
"variables": {
- "system.debug": {
- "value": "false",
+ "CloudDropAccessToken": {
+ "value": null,
+ "isSecret": true
+ },
+ "OfficialBuildId": {
+ "value": "$(Build.BuildNumber)",
"allowOverride": true
},
- "PB_GitDirectory": {
- "value": "/root/corefx"
+ "PB_BuildArguments": {
+ "value": "-buildArch=x64 -Release -stripSymbols",
+ "allowOverride": true
+ },
+ "PB_BuildTestsArguments": {
+ "value": "-buildArch=x64 -Release -SkipTests -Outerloop -- /p:ArchiveTests=true /p:EnableDumpling=true",
+ "allowOverride": true
+ },
+ "PB_CleanAgent": {
+ "value": "true"
+ },
+ "PB_CloudDropAccountName": {
+ "value": "dotnetbuildoutput"
+ },
+ "PB_CloudResultsAccessToken": {
+ "value": null,
+ "isSecret": true
+ },
+ "PB_CloudResultsAccountName": {
+ "value": "dotnetjobresult"
+ },
+ "PB_CreateHelixArguments": {
+ "value": "\"/p:ArchGroup=x64 /p:ConfigurationGroup=Release /p:TestProduct=corefx /p:TimeoutInSeconds=1200 /p:TargetOS=Linux",
+ "allowOverride": true
+ },
+ "PB_DockerCommonRunArgs": {
+ "value": "--rm --name $(PB_DockerContainerName) -v \"$(PB_GitDirectory):$(PB_DockerVolumeName)\" -w=\"$(PB_DockerVolumeName)\" $(PB_DockerImageName)"
},
"PB_DockerContainerName": {
"value": "corefx-$(Build.BuildId)"
},
+ "PB_DockerCopyDest": {
+ "value": "$(Build.BinariesDirectory)/docker_repo"
+ },
"PB_DockerImageName": {
"value": "$(PB_DockerRepository):$(PB_DockerTag)"
},
@@ -410,63 +373,46 @@
"value": "microsoft/dotnet-buildtools-prereqs"
},
"PB_DockerTag": {
- "value": "debian82_prereqs_2",
+ "value": "rhel7_prereqs_2",
"allowOverride": true
},
- "PB_CloudDropAccountName": {
- "value": "dotnetbuildoutput"
- },
- "CloudDropAccessToken": {
- "value": null,
- "isSecret": true
+ "PB_DockerVolumeName": {
+ "value": "/root/corefx-$(Build.BuildId)"
},
- "OfficialBuildId": {
- "value": "$(Build.BuildNumber)",
- "allowOverride": true
+ "PB_GitDirectory": {
+ "value": "$(Build.SourcesDirectory)/corefx"
},
"PB_Label": {
"value": "$(Build.BuildNumber)",
"allowOverride": true
},
- "SourceVersion": {
- "value": "HEAD",
+ "PB_SyncArguments": {
+ "value": "-p -- /p:ArchGroup=x64",
"allowOverride": true
},
- "PB_DockerCopyDest": {
- "value": "$(Build.BinariesDirectory)/docker_repo"
+ "PB_TargetQueue": {
+ "value": "Centos.73.Amd64+RedHat.72.Amd64+RedHat.73.Amd64+Debian.87.Amd64+Debian.90.Amd64+Ubuntu.1404.Amd64+Ubuntu.1604.Amd64+Ubuntu.1610.Amd64+Ubuntu.1704.Amd64+suse.422.amd64+SLES.12.Amd64+fedora.25.amd64+Fedora.26.Amd64"
},
"PB_VsoAccountName": {
"value": "dn-bot"
},
- "VsoPassword": {
- "value": null,
- "isSecret": true
- },
- "PB_VsoRepositoryName": {
- "value": "DotNet-CoreFX-Trusted",
- "allowOverride": true
- },
"PB_VsoCorefxGitUrl": {
- "value": "https://github.com/dotnet/corefx"
- },
- "PB_BuildArguments": {
- "value": "-buildArch=x64 -Release",
- "allowOverride": true
+ "value": "https://$(PB_VsoAccountName):$(VsoPassword)@devdiv.visualstudio.com/DevDiv/_git/$(PB_VsoRepositoryName)/"
},
- "PB_SyncArguments": {
- "value": "-p -- /p:ArchGroup=x64",
- "allowOverride": true
+ "PB_VsoRepositoryName": {
+ "value": "DotNet-CoreFX-Trusted"
},
- "PB_BuildTestsArguments": {
- "value": "-BuildArch=x64 -Release -SkipTests",
+ "SourceVersion": {
+ "value": "HEAD",
"allowOverride": true
},
- "PB_CreateHelixArguments": {
- "value": "/t:CloudBuild /p:ArchGroup=x64 /p:ConfigurationGroup=Debug /p:\"EnableCloudTest=true /p:\"TestProduct=corefx /p:\"TimeoutInSeconds=1200\" /p:\"TargetOS=Linux\" /p:FilterToOSGroup=Linux",
+ "system.debug": {
+ "value": "false",
"allowOverride": true
},
- "PB_CleanAgent": {
- "value": "true"
+ "VsoPassword": {
+ "value": null,
+ "isSecret": true
}
},
"demands": [
@@ -487,9 +433,10 @@
"deleteTestResults": true
}
],
- "buildNumberFormat": "$(date:yyyyMMdd)$(rev:-rr)-$(PB_DockerTag)",
+ "buildNumberFormat": "$(date:yyyyMMdd)$(rev:-rr)",
"jobAuthorizationScope": "projectCollection",
"jobTimeoutInMinutes": 60,
+ "jobCancelTimeoutInMinutes": 5,
"repository": {
"properties": {
"labelSources": "0",
@@ -507,25 +454,27 @@
"clean": "false",
"checkoutSubmodules": false
},
+ "processParameters": {},
"quality": "definition",
"queue": {
+ "id": 36,
+ "name": "DotNet-Build",
"pool": {
"id": 39,
"name": "DotNet-Build"
- },
- "id": 36,
- "name": "DotNet-Build"
+ }
},
- "path": "\\",
- "type": "build",
"id": 5008,
"name": "DotNet-CoreFx-Trusted-Linux",
+ "path": "\\",
+ "type": "build",
"project": {
"id": "0bdbc590-a062-4c3f-b0f6-9383f67865ee",
"name": "DevDiv",
"description": "Visual Studio and DevDiv team project for git source code repositories. Work items will be added for Adams, Dev14 work items are tracked in vstfdevdiv. ",
"url": "https://devdiv.visualstudio.com/DefaultCollection/_apis/projects/0bdbc590-a062-4c3f-b0f6-9383f67865ee",
"state": "wellFormed",
- "revision": 418097459
+ "revision": 418097767,
+ "visibility": "private"
}
} \ No newline at end of file
diff --git a/buildpipeline/DotNet-CoreFx-Trusted-Windows.json b/buildpipeline/DotNet-CoreFx-Trusted-Windows.json
index 2ccfd8640d..6f762a7d45 100644
--- a/buildpipeline/DotNet-CoreFx-Trusted-Windows.json
+++ b/buildpipeline/DotNet-CoreFx-Trusted-Windows.json
@@ -15,8 +15,8 @@
"scriptType": "inlineScript",
"scriptName": "",
"arguments": "-path $(build.SourcesDirectory)\\corefx",
- "inlineScript": "param($path)\n\nif (Test-Path $path){\n Stop-Process -processname msbuild -ErrorAction Ignore -Verbose\n Stop-Process -processname dotnet -ErrorAction Ignore -Verbose\n Stop-Process -processname vbcscompiler -ErrorAction Ignore -Verbose\n # this will print out an error each time a file can't be deleted.\n Remove-Item -Recurse -Force $path\n }\n",
"workingFolder": "",
+ "inlineScript": "param($path)\n\nif (Test-Path $path){\n Stop-Process -processname msbuild -ErrorAction Ignore -Verbose\n Stop-Process -processname dotnet -ErrorAction Ignore -Verbose\n Stop-Process -processname vbcscompiler -ErrorAction Ignore -Verbose\n # this will print out an error each time a file can't be deleted.\n Remove-Item -Recurse -Force $path\n }",
"failOnStandardError": "true"
}
},
@@ -177,6 +177,10 @@
},
"inputs": {
"solution": "$(Build.SourcesDirectory)\\corefx\\src\\upload-tests.proj",
+ "msbuildLocationMethod": "version",
+ "msbuildVersion": "14.0",
+ "msbuildArchitecture": "x64",
+ "msbuildLocation": "",
"platform": "",
"configuration": "",
"msbuildArguments": "$(PB_CreateHelixArguments) /p:\"Branch=$(SourceBranch)\" /p:\"CloudDropConnectionString=DefaultEndpointsProtocol=https;AccountName=$(PB_CloudDropAccountName);AccountKey=$(CloudDropAccessToken);EndpointSuffix=core.windows.net\" /p:\"CloudResultsConnectionString=DefaultEndpointsProtocol=https;AccountName=$(PB_CloudResultsAccountName);AccountKey=$(OutputCloudResultsAccessToken);EndpointSuffix=core.windows.net\" /p:\"HelixApiAccessKey=$(HelixApiAccessKey)\" /p:\"HelixApiEndpoint=$(PB_HelixApiEndPoint)\" /p:\"OfficialBuildId=$(OfficialBuildId)\"",
@@ -184,11 +188,7 @@
"maximumCpuCount": "false",
"restoreNugetPackages": "false",
"logProjectEvents": "false",
- "createLogFile": "false",
- "msbuildLocationMethod": "version",
- "msbuildVersion": "14.0",
- "msbuildArchitecture": "x64",
- "msbuildLocation": ""
+ "createLogFile": "false"
}
},
{
@@ -212,7 +212,7 @@
{
"enabled": true,
"continueOnError": false,
- "alwaysRun": true,
+ "alwaysRun": false,
"displayName": "Copy Publish Artifact: BuildLogs",
"timeoutInMinutes": 0,
"task": {
@@ -254,7 +254,7 @@
{
"enabled": true,
"continueOnError": false,
- "alwaysRun": true,
+ "alwaysRun": false,
"displayName": "Execute cleanup tasks",
"timeoutInMinutes": 0,
"task": {
@@ -295,6 +295,10 @@
},
"inputs": {
"solution": "corefx\\Tools\\scripts\\vstsagent\\cleanupagent.proj",
+ "msbuildLocationMethod": "version",
+ "msbuildVersion": "14.0",
+ "msbuildArchitecture": "x86",
+ "msbuildLocation": "",
"platform": "",
"configuration": "",
"msbuildArguments": "/p:AgentDirectory=$(Agent.HomeDirectory) /p:DoClean=$(PB_CleanAgent)",
@@ -302,11 +306,7 @@
"maximumCpuCount": "false",
"restoreNugetPackages": "false",
"logProjectEvents": "false",
- "createLogFile": "false",
- "msbuildLocationMethod": "version",
- "msbuildVersion": "14.0",
- "msbuildArchitecture": "x86",
- "msbuildLocation": ""
+ "createLogFile": "false"
}
}
],
@@ -314,6 +314,16 @@
{
"enabled": false,
"definition": {
+ "id": "5d58cc01-7c75-450c-be18-a388ddb129ec"
+ },
+ "inputs": {
+ "branchFilters": "[\"+refs/heads/*\"]",
+ "additionalFields": "{}"
+ }
+ },
+ {
+ "enabled": false,
+ "definition": {
"id": "5bc3cfb7-6b54-4a4b-b5d2-a3905949f8a6"
},
"inputs": {
@@ -354,104 +364,106 @@
}
],
"variables": {
- "system.debug": {
- "value": "false",
+ "CloudDropAccessToken": {
+ "value": null,
+ "isSecret": true
+ },
+ "OfficialBuildId": {
+ "value": "$(Build.BuildNumber)",
"allowOverride": true
},
- "PB_ConfigurationGroup": {
- "value": "Debug",
+ "PB_BuildArguments": {
+ "value": "-buildArch=x64 -Release -- /p:SignType=test /p:RuntimeOS=win10",
"allowOverride": true
},
- "PB_Platform": {
- "value": "x64",
+ "PB_BuildTestsArguments": {
+ "value": "-buildArch=x64 -Release -SkipTests -- /p:RuntimeOS=win10",
"allowOverride": true
},
+ "PB_CleanAgent": {
+ "value": "true"
+ },
"PB_CloudDropAccountName": {
"value": "dotnetbuildoutput"
},
- "CloudDropAccessToken": {
- "value": null,
- "isSecret": true
+ "PB_ConfigurationGroup": {
+ "value": "Debug",
+ "allowOverride": true
},
- "OfficialBuildId": {
- "value": "$(Build.BuildNumber)",
+ "PB_CreateHelixArguments": {
+ "value": "/t:CloudBuild /p:ArchGroup=x64 /p:ConfigurationGroup=Release /p:\"EnableCloudTest=true\" /p:\"BuildMoniker=none\" /p:\"TargetQueue=Windows.10.Amd64\" /p:\"TestProduct=corefx\" /p:\"TimeoutInSeconds=1200\" /p:\"TargetOS=Windows_NT\" /p:FilterToOSGroup=Windows_NT",
"allowOverride": true
},
+ "PB_Git": {
+ "value": "$(ProgramFiles)\\Git\\cmd\\git.exe"
+ },
"PB_Label": {
"value": "$(Build.BuildNumber)",
"allowOverride": true
},
- "SourceVersion": {
- "value": "HEAD",
- "allowOverride": true
- },
- "PB_VsoAccountName": {
- "value": "dn-bot"
+ "PB_OptionalToolingSyncArguments": {
+ "value": "/p:OptionalToolSource=$(PB_OptionalToolSource) /p:OptionalToolSourceUser=$(PB_OptionalToolSourceUser);OptionalToolSourcePassword=$(PB_OptionalToolSourcePAT)"
},
- "VsoPassword": {
+ "PB_OptionalToolSource": {
"value": null,
+ "allowOverride": true,
"isSecret": true
},
- "PB_VsoRepositoryName": {
- "value": "DotNet-CoreFX-Trusted",
- "allowOverride": true
+ "PB_OptionalToolSourcePAT": {
+ "value": null,
+ "allowOverride": true,
+ "isSecret": true
},
- "PB_VsoCorefxGitUrl": {
- "value": "https://github.com/dotnet/corefx"
+ "PB_OptionalToolSourceUser": {
+ "value": null,
+ "allowOverride": true,
+ "isSecret": true
},
- "PB_SourceBranch": {
- "value": "master",
+ "PB_PipelineBuildMSBuildArguments": {
+ "value": "",
"allowOverride": true
},
- "PB_Git": {
- "value": "$(ProgramFiles)\\Git\\cmd\\git.exe"
- },
- "TeamName": {
- "value": "DotNetCore"
+ "PB_Platform": {
+ "value": "x64",
+ "allowOverride": true
},
"PB_RuntimeOS": {
"value": "win10"
},
- "PB_CleanAgent": {
- "value": "true"
+ "PB_SourceBranch": {
+ "value": "master",
+ "allowOverride": true
},
"PB_SyncArguments": {
"value": "-p -- /p:ArchGroup=x64 /p:RuntimeOS=win10",
"allowOverride": true
},
- "PB_BuildArguments": {
- "value": "-buildArch=x64 -Release -- /p:SignType=test /p:RuntimeOS=win10",
- "allowOverride": true
+ "PB_VsoAccountName": {
+ "value": "dn-bot"
},
- "PB_BuildTestsArguments": {
- "value": "-buildArch=x64 -Release -SkipTests -- /p:RuntimeOS=win10",
- "allowOverride": true
+ "PB_VsoCorefxGitUrl": {
+ "value": "https://$(PB_VsoAccountName):$(VsoPassword)@devdiv.visualstudio.com/DevDiv/_git/$(PB_VsoRepositoryName)/"
},
- "PB_CreateHelixArguments": {
- "value": "/t:CloudBuild /p:ArchGroup=x64 /p:ConfigurationGroup=Release /p:\"EnableCloudTest=true\" /p:\"BuildMoniker=none\" /p:\"TargetQueue=Windows.10.Amd64\" /p:\"TestProduct=corefx\" /p:\"TimeoutInSeconds=1200\" /p:\"TargetOS=Windows_NT\" /p:FilterToOSGroup=Windows_NT",
+ "PB_VsoRepositoryName": {
+ "value": "DotNet-CoreFX-Trusted"
+ },
+ "SourceVersion": {
+ "value": "HEAD",
"allowOverride": true
},
- "PB_OptionalToolSource": {
- "value": null,
- "allowOverride": true,
- "isSecret": true
+ "system.debug": {
+ "value": "false",
+ "allowOverride": true
},
- "PB_OptionalToolSourceUser": {
- "value": null,
- "allowOverride": true,
- "isSecret": true
+ "TeamName": {
+ "value": "DotNetCore"
},
- "PB_OptionalToolSourcePAT": {
+ "VsoPassword": {
"value": null,
- "allowOverride": true,
"isSecret": true
},
- "PB_OptionalToolingSyncArguments": {
- "value": "/p:OptionalToolSource=$(PB_OptionalToolSource) /p:OptionalToolSourceUser=$(PB_OptionalToolSourceUser);OptionalToolSourcePassword=$(PB_OptionalToolSourcePAT)"
- },
- "PB_PipelineBuildMSBuildArguments": {
- "value": "",
- "allowOverride": true
+ "PB_SignType": {
+ "value": "real"
}
},
"demands": [
@@ -475,6 +487,7 @@
"buildNumberFormat": "$(date:yyyyMMdd)$(rev:-rr)",
"jobAuthorizationScope": "projectCollection",
"jobTimeoutInMinutes": 180,
+ "jobCancelTimeoutInMinutes": 5,
"repository": {
"properties": {
"labelSources": "0",
@@ -482,7 +495,9 @@
"fetchDepth": "0",
"gitLfsSupport": "false",
"skipSyncSource": "true",
- "cleanOptions": "3"
+ "cleanOptions": "3",
+ "checkoutNestedSubmodules": "false",
+ "labelSourcesFormat": "$(build.buildNumber)"
},
"id": "0a2b2664-c1be-429c-9b40-8a24dee27a4a",
"type": "TfsGit",
@@ -492,25 +507,27 @@
"clean": "false",
"checkoutSubmodules": false
},
+ "processParameters": {},
"quality": "definition",
"queue": {
+ "id": 36,
+ "name": "DotNet-Build",
"pool": {
"id": 39,
"name": "DotNet-Build"
- },
- "id": 36,
- "name": "DotNet-Build"
+ }
},
- "path": "\\",
- "type": "build",
"id": 893,
"name": "DotNet-CoreFx-Trusted-Windows",
+ "path": "\\",
+ "type": "build",
"project": {
"id": "0bdbc590-a062-4c3f-b0f6-9383f67865ee",
"name": "DevDiv",
"description": "Visual Studio and DevDiv team project for git source code repositories. Work items will be added for Adams, Dev14 work items are tracked in vstfdevdiv. ",
"url": "https://devdiv.visualstudio.com/DefaultCollection/_apis/projects/0bdbc590-a062-4c3f-b0f6-9383f67865ee",
"state": "wellFormed",
- "revision": 418097607
+ "revision": 418097767,
+ "visibility": "private"
}
-}
+} \ No newline at end of file
diff --git a/buildpipeline/DotNet-Trusted-Publish-Symbols.json b/buildpipeline/DotNet-Trusted-Publish-Symbols.json
index 569184ef3f..e3fdeb4c41 100644
--- a/buildpipeline/DotNet-Trusted-Publish-Symbols.json
+++ b/buildpipeline/DotNet-Trusted-Publish-Symbols.json
@@ -56,7 +56,7 @@
"scriptName": "",
"arguments": "-ConfigGroup $(PB_ConfigurationGroup) -SymPkgGlob $(PB_AzureContainerSymbolPackageGlob) -Branch $(SourceBranch)",
"workingFolder": "$(Pipeline.SourcesDirectory)",
- "inlineScript": "param($ConfigGroup, $SymPkgGlob, $Branch)\nif ($ConfigGroup -ne \"Release\") { exit }\n$archive = $Branch.StartsWith(\"release/\")\n\n$target = \"UnzipSymbolPackagesForPublish\"\nif ($archive) { $target = \"SubmitSymbolsRequest\" }\n\n.\\build-managed.cmd -- `\n/t:$target `\n/p:SymbolPackagesToPublishGlob=$SymPkgGlob `\n/p:ArchiveSymbols=$archive `\n/v:D",
+ "inlineScript": "param($ConfigGroup, $SymPkgGlob, $Branch)\nif ($ConfigGroup -ne \"Release\") { exit }\n$archive = $Branch.StartsWith(\"release/\")\n\n$target = \"GetAllSymbolFilesToPublish\"\nif ($archive) { $target = \"SubmitSymbolsRequest\" }\n\n.\\build-managed.cmd -- `\n/t:$target `\n/p:SymbolPackagesToPublishGlob=$SymPkgGlob `\n/p:ArchiveSymbols=$archive `\n/v:D",
"failOnStandardError": "true"
}
},
diff --git a/buildpipeline/linux.groovy b/buildpipeline/linux.groovy
index 26414a56be..15f1689585 100644
--- a/buildpipeline/linux.groovy
+++ b/buildpipeline/linux.groovy
@@ -16,17 +16,8 @@ simpleDockerNode('microsoft/dotnet-buildtools-prereqs:rhel7_prereqs_2') {
def logFolder = getLogFolder()
stage ('Initialize tools') {
- try {
- // Init tools
- sh './init-tools.sh'
- }
- catch (err) {
- // On errors for build tools initializations, it's useful to echo the contents of the file
- // for easy diagnosis. This could also be copied to the log directory
- sh 'cat init-tools.log'
- // Ensure the build result is still propagated.
- throw err
- }
+ // Init tools
+ sh './init-tools.sh'
}
stage ('Generate version assets') {
// Generate the version assets. Do we need to even do this for non-official builds?
@@ -87,4 +78,4 @@ stage ('Execute Tests') {
contextBase = "Linux x64 Tests - ${params.CGroup}"
}
waitForHelixRuns(submittedHelixJson, contextBase)
-} \ No newline at end of file
+}
diff --git a/buildpipeline/osx.groovy b/buildpipeline/osx.groovy
index 72b0275ca7..113899ab83 100644
--- a/buildpipeline/osx.groovy
+++ b/buildpipeline/osx.groovy
@@ -16,18 +16,9 @@ simpleNode('OSX10.12','latest') {
def logFolder = getLogFolder()
stage ('Initialize tools') {
- try {
- // Workaround nuget issue https://github.com/NuGet/Home/issues/5085 were we need to set HOME
- // Init tools
- sh 'HOME=\$WORKSPACE/tempHome ./init-tools.sh'
- }
- catch (err) {
- // On errors for build tools initializations, it's useful to echo the contents of the file
- // for easy diagnosis. This could also be copied to the log directory
- sh 'cat init-tools.log'
- // Ensure the build result is still propagated.
- throw err
- }
+ // Workaround nuget issue https://github.com/NuGet/Home/issues/5085 were we need to set HOME
+ // Init tools
+ sh 'HOME=\$WORKSPACE/tempHome ./init-tools.sh'
}
stage ('Generate version assets') {
// Generate the version assets. Do we need to even do this for non-official builds?
@@ -46,4 +37,4 @@ simpleNode('OSX10.12','latest') {
}
sh "HOME=\$WORKSPACE/tempHome ./build-tests.sh -buildArch=x64 -${params.CGroup} ${additionalArgs} -- /p:ArchiveTests=true /p:EnableDumpling=true"
}
-} \ No newline at end of file
+}
diff --git a/buildpipeline/windows.groovy b/buildpipeline/windows.groovy
index 0b13998df4..6b042f8c68 100644
--- a/buildpipeline/windows.groovy
+++ b/buildpipeline/windows.groovy
@@ -28,19 +28,8 @@ simpleNode('Windows_NT','latest') {
def buildTests = (params.TGroup != 'all')
stage ('Initialize tools') {
- try {
- // Init tools
- bat '.\\init-tools.cmd'
- // Temporarily always dump the init-tools.log to try and identify why sometimes it takes really long
- bat 'type init-tools.log'
- }
- catch (err) {
- // On errors for build tools initializations, it's useful to echo the contents of the file
- // for easy diagnosis. This could also be copied to the log directory
- bat 'type init-tools.log'
- // Ensure the build result is still propagated.
- throw err
- }
+ // Init tools
+ bat '.\\init-tools.cmd'
}
stage ('Sync') {
bat ".\\sync.cmd -p -- /p:ArchGroup=${params.AGroup} /p:RuntimeOS=win10"
@@ -112,4 +101,4 @@ if (submitToHelix) {
}
waitForHelixRuns(submittedHelixJson, contextBase)
}
-} \ No newline at end of file
+}
diff --git a/dependencies.props b/dependencies.props
index 0c7582370e..7f1417e6ad 100644
--- a/dependencies.props
+++ b/dependencies.props
@@ -9,30 +9,30 @@
These ref versions are pulled from https://github.com/dotnet/versions.
-->
<PropertyGroup>
- <CoreFxCurrentRef>2342388ed30a2c364ae8e55d936a6a54d52b4efe</CoreFxCurrentRef>
- <CoreClrCurrentRef>2342388ed30a2c364ae8e55d936a6a54d52b4efe</CoreClrCurrentRef>
- <CoreSetupCurrentRef>2342388ed30a2c364ae8e55d936a6a54d52b4efe</CoreSetupCurrentRef>
+ <CoreFxCurrentRef>e12b5082d6d2babb30fa975f257fac46ad96d407</CoreFxCurrentRef>
+ <CoreClrCurrentRef>e12b5082d6d2babb30fa975f257fac46ad96d407</CoreClrCurrentRef>
+ <CoreSetupCurrentRef>e12b5082d6d2babb30fa975f257fac46ad96d407</CoreSetupCurrentRef>
<ExternalCurrentRef>5a0606fccb09fce4b47545ae9896139acca547f5</ExternalCurrentRef>
- <ProjectNTfsCurrentRef>5b11b9d95b0a9651fd4303af7285fcc22a5825d1</ProjectNTfsCurrentRef>
- <ProjectNTfsTestILCCurrentRef>5b11b9d95b0a9651fd4303af7285fcc22a5825d1</ProjectNTfsTestILCCurrentRef>
- <SniCurrentRef>97059fa979a3c8fb8b9fba127c526f15e48c9dde</SniCurrentRef>
- <StandardCurrentRef>217863ea1522764354c0cae722ffb90429e823c1</StandardCurrentRef>
+ <ProjectNTfsCurrentRef>43518ef74e043d6040190ef6f595dfbbb51dbbff</ProjectNTfsCurrentRef>
+ <ProjectNTfsTestILCCurrentRef>43518ef74e043d6040190ef6f595dfbbb51dbbff</ProjectNTfsTestILCCurrentRef>
+ <SniCurrentRef>8bd1ec5fac9f0eec34ff6b34b1d878b4359e02dd</SniCurrentRef>
+ <StandardCurrentRef>0045776673a3fa4f3bfb877bf1df6f500f9657a6</StandardCurrentRef>
</PropertyGroup>
<!-- Auto-upgraded properties for each build info dependency. -->
<PropertyGroup>
<PlatformPackageVersion>2.1.0-preview1-25324-02</PlatformPackageVersion>
- <CoreFxExpectedPrerelease>preview2-25502-02</CoreFxExpectedPrerelease>
- <CoreClrPackageVersion>2.1.0-preview2-25502-01</CoreClrPackageVersion>
+ <CoreFxExpectedPrerelease>preview2-25515-01</CoreFxExpectedPrerelease>
+ <CoreClrPackageVersion>2.1.0-preview2-25514-02</CoreClrPackageVersion>
<ExternalExpectedPrerelease>beta-25322-00</ExternalExpectedPrerelease>
- <ProjectNTfsExpectedPrerelease>beta-25430-00</ProjectNTfsExpectedPrerelease>
- <ProjectNTfsTestILCExpectedPrerelease>beta-25430-00</ProjectNTfsTestILCExpectedPrerelease>
- <ProjectNTfsTestILCPackageVersion>1.0.0-beta-25430-00</ProjectNTfsTestILCPackageVersion>
- <NETStandardPackageVersion>2.1.0-preview1-25430-01</NETStandardPackageVersion>
+ <ProjectNTfsExpectedPrerelease>beta-25514-01</ProjectNTfsExpectedPrerelease>
+ <ProjectNTfsTestILCExpectedPrerelease>beta-25514-01</ProjectNTfsTestILCExpectedPrerelease>
+ <ProjectNTfsTestILCPackageVersion>1.0.0-beta-25514-01</ProjectNTfsTestILCPackageVersion>
+ <NETStandardPackageVersion>2.1.0-preview1-25514-01</NETStandardPackageVersion>
<NETStandardPackageId>NETStandard.Library</NETStandardPackageId>
- <MicrosoftNETCoreAppPackageVersion>2.1.0-preview2-25501-06</MicrosoftNETCoreAppPackageVersion>
+ <MicrosoftNETCoreAppPackageVersion>2.1.0-preview2-25514-02</MicrosoftNETCoreAppPackageVersion>
<!-- Use the SNI runtime package -->
- <SniPackageVersion>4.4.0-preview2-25312-01</SniPackageVersion>
+ <SniPackageVersion>4.4.0</SniPackageVersion>
</PropertyGroup>
<!-- Full package version strings that are used in other parts of the build. -->
diff --git a/dir.props b/dir.props
index 72055e1c14..e97595d201 100644
--- a/dir.props
+++ b/dir.props
@@ -9,6 +9,13 @@
<MinorVersion>6</MinorVersion>
</PropertyGroup>
+ <!-- Define vNext UAP Moniker -->
+ <PropertyGroup>
+ <UAPvNextVersion>10.0.15138</UAPvNextVersion>
+ <UAPvNextTFMFull>UAP,Version=v$(UAPvNextVersion)</UAPvNextTFMFull>
+ <UAPvNextTFM>uap$(UAPvNextVersion)</UAPvNextTFM>
+ </PropertyGroup>
+
<Import Condition="Exists('$(MSBuildProjectDirectory)/Configurations.props')" Project="$(MSBuildProjectDirectory)/Configurations.props" />
<!-- Informs build tools to apply .NET Framework metadata if not a test project -->
diff --git a/dir.targets b/dir.targets
index 73c674caa3..0938077faf 100644
--- a/dir.targets
+++ b/dir.targets
@@ -92,8 +92,8 @@
<Import Project="$(MSBuildThisFileDirectory)illink.targets" />
<ItemGroup Condition="'$(NuGetTargetMoniker)'=='.NETStandard,Version=v1.7'">
- <!-- Temporarily suppress the message until we get a nuget version that knows about the mapping between netstandard1.7 and uap10.1 -->
- <SuppressPackageTargetFrameworkCompatibility Include="uap10.1" />
+ <!-- Temporarily suppress the message until we get a nuget version that knows about the mapping between netstandard1.7 and uapvNext -->
+ <SuppressPackageTargetFrameworkCompatibility Include="$(UAPvNextTFM)" />
</ItemGroup>
<Target Name="ProducesPackageId"
diff --git a/external/runtime/runtime.depproj b/external/runtime/runtime.depproj
index ad7ff3fbdf..7423fd37ba 100644
--- a/external/runtime/runtime.depproj
+++ b/external/runtime/runtime.depproj
@@ -10,6 +10,9 @@
<RidSpecificAssets>true</RidSpecificAssets>
</PropertyGroup>
<PropertyGroup Condition="'$(TargetGroup)' == 'uapaot'">
+ <!-- Temporarily Override restore moniker since NETNative's targeting pack still uses uap10.1 moniker -->
+ <NuGetTargetMoniker>UAP,Version=v10.1</NuGetTargetMoniker>
+ <NuGetTargetMonikerShort>uap10.1</NuGetTargetMonikerShort>
<!-- System.Private.* can't be on the ILCInputFolder since ilc.exe needs to use the matching one from its toolchain. -->
<BinPlaceILCInputFolder>false</BinPlaceILCInputFolder>
<NuGetDeploySourceItem>Reference</NuGetDeploySourceItem>
diff --git a/external/test-runtime/XUnit.Runtime.depproj b/external/test-runtime/XUnit.Runtime.depproj
index 2e277ea663..c172bb486e 100644
--- a/external/test-runtime/XUnit.Runtime.depproj
+++ b/external/test-runtime/XUnit.Runtime.depproj
@@ -94,7 +94,7 @@
</ItemGroup>
<PropertyGroup Condition="'$(TargetGroup)' == 'uap'">
- <UAPToolsPackageVersion>1.0.12</UAPToolsPackageVersion>
+ <UAPToolsPackageVersion>1.0.13</UAPToolsPackageVersion>
</PropertyGroup>
<ItemGroup Condition="'$(TargetGroup)' == 'uap'">
diff --git a/external/test-runtime/optional.json b/external/test-runtime/optional.json
index ac3f276c4b..185d257a4a 100644
--- a/external/test-runtime/optional.json
+++ b/external/test-runtime/optional.json
@@ -3,9 +3,9 @@
"net45": {
"dependencies": {
"Microsoft.DotNet.IBCMerge": "4.6.0-alpha-00001",
- "TestILC.amd64ret": "1.0.0-beta-25430-00",
- "TestILC.armret": "1.0.0-beta-25430-00",
- "TestILC.x86ret": "1.0.0-beta-25430-00"
+ "TestILC.amd64ret": "1.0.0-beta-25514-01",
+ "TestILC.armret": "1.0.0-beta-25514-01",
+ "TestILC.x86ret": "1.0.0-beta-25514-01"
}
}
}
diff --git a/init-tools.cmd b/init-tools.cmd
index 6c9494e5b9..a634f01af5 100644
--- a/init-tools.cmd
+++ b/init-tools.cmd
@@ -18,7 +18,7 @@ if [%1]==[force] (
if exist "%PACKAGES_DIR%Microsoft.DotNet.BuildTools" rmdir /S /Q "%PACKAGES_DIR%Microsoft.DotNet.BuildTools"
)
-:: If sempahore exists do nothing
+:: If semaphore exists do nothing
if exist "%BUILD_TOOLS_SEMAPHORE%" (
echo Tools are already initialized.
goto :EOF
@@ -39,8 +39,8 @@ set DOTNET_LOCAL_PATH=%DOTNET_PATH%%DOTNET_ZIP_NAME%
echo Installing '%DOTNET_REMOTE_PATH%' to '%DOTNET_LOCAL_PATH%' >> "%INIT_TOOLS_LOG%"
powershell -NoProfile -ExecutionPolicy unrestricted -Command "$retryCount = 0; $success = $false; do { try { (New-Object Net.WebClient).DownloadFile('%DOTNET_REMOTE_PATH%', '%DOTNET_LOCAL_PATH%'); $success = $true; } catch { if ($retryCount -ge 6) { throw; } else { $retryCount++; Start-Sleep -Seconds (5 * $retryCount); } } } while ($success -eq $false); Add-Type -Assembly 'System.IO.Compression.FileSystem' -ErrorVariable AddTypeErrors; if ($AddTypeErrors.Count -eq 0) { [System.IO.Compression.ZipFile]::ExtractToDirectory('%DOTNET_LOCAL_PATH%', '%DOTNET_PATH%') } else { (New-Object -com shell.application).namespace('%DOTNET_PATH%').CopyHere((new-object -com shell.application).namespace('%DOTNET_LOCAL_PATH%').Items(),16) }" >> "%INIT_TOOLS_LOG%"
if NOT exist "%DOTNET_LOCAL_PATH%" (
- echo ERROR: Could not install dotnet cli correctly. See '%INIT_TOOLS_LOG%' for more details. 1>&2
- exit /b 1
+ echo ERROR: Could not install dotnet cli correctly. 1>&2
+ goto :error
)
:afterdotnetrestore
@@ -50,8 +50,8 @@ echo Restoring BuildTools version %BUILDTOOLS_VERSION%...
echo Running: "%DOTNET_CMD%" restore "%INIT_TOOLS_RESTORE_PROJECT%" --no-cache --packages %PACKAGES_DIR% --source "%BUILDTOOLS_SOURCE%" /p:BuildToolsPackageVersion=%BUILDTOOLS_VERSION% >> "%INIT_TOOLS_LOG%"
call "%DOTNET_CMD%" restore "%INIT_TOOLS_RESTORE_PROJECT%" --no-cache --packages %PACKAGES_DIR% --source "%BUILDTOOLS_SOURCE%" /p:BuildToolsPackageVersion=%BUILDTOOLS_VERSION% >> "%INIT_TOOLS_LOG%"
if NOT exist "%BUILD_TOOLS_PATH%init-tools.cmd" (
- echo ERROR: Could not restore build tools correctly. See '%INIT_TOOLS_LOG%' for more details. 1>&2
- exit /b 1
+ echo ERROR: Could not restore build tools correctly. 1>&2
+ goto :error
)
:afterbuildtoolsrestore
@@ -61,11 +61,16 @@ echo Running: "%BUILD_TOOLS_PATH%init-tools.cmd" "%~dp0" "%DOTNET_CMD%" "%TOOLRU
call "%BUILD_TOOLS_PATH%init-tools.cmd" "%~dp0" "%DOTNET_CMD%" "%TOOLRUNTIME_DIR%" >> "%INIT_TOOLS_LOG%"
set INIT_TOOLS_ERRORLEVEL=%ERRORLEVEL%
if not [%INIT_TOOLS_ERRORLEVEL%]==[0] (
- echo ERROR: An error occured when trying to initialize the tools. Please check '%INIT_TOOLS_LOG%' for more details. 1>&2
- exit /b %INIT_TOOLS_ERRORLEVEL%
+ echo ERROR: An error occured when trying to initialize the tools. 1>&2
+ goto :error
)
-:: Create sempahore file
+:: Create semaphore file
echo Done initializing tools.
echo Init-Tools.cmd completed for BuildTools Version: %BUILDTOOLS_VERSION% > "%BUILD_TOOLS_SEMAPHORE%"
exit /b 0
+
+:error
+echo Please check the detailed log that follows. 1>&2
+type "%INIT_TOOLS_LOG%" 1>&2
+exit /b 1
diff --git a/init-tools.sh b/init-tools.sh
index 3b8527822a..a0e35c5302 100755
--- a/init-tools.sh
+++ b/init-tools.sh
@@ -46,6 +46,12 @@ OSName=$(uname -s)
esac
fi
+display_error_message()
+{
+ echo "Please check the detailed log that follows." 1>&2
+ cat "$__init_tools_log" 1>&2
+}
+
if [ ! -e $__INIT_TOOLS_DONE_MARKER ]; then
__PATCH_CLI_NUGET_FRAMEWORKS=0
@@ -94,7 +100,10 @@ if [ ! -e $__INIT_TOOLS_DONE_MARKER ]; then
echo "Restoring BuildTools version $__BUILD_TOOLS_PACKAGE_VERSION..."
echo "Running: $__DOTNET_CMD restore \"$__INIT_TOOLS_RESTORE_PROJECT\" --no-cache --packages $__PACKAGES_DIR --source $__BUILDTOOLS_SOURCE /p:BuildToolsPackageVersion=$__BUILD_TOOLS_PACKAGE_VERSION" >> $__init_tools_log
$__DOTNET_CMD restore "$__INIT_TOOLS_RESTORE_PROJECT" --no-cache --packages $__PACKAGES_DIR --source $__BUILDTOOLS_SOURCE /p:BuildToolsPackageVersion=$__BUILD_TOOLS_PACKAGE_VERSION >> $__init_tools_log
- if [ ! -e "$__BUILD_TOOLS_PATH/init-tools.sh" ]; then echo "ERROR: Could not restore build tools correctly. See '$__init_tools_log' for more details."1>&2; fi
+ if [ ! -e "$__BUILD_TOOLS_PATH/init-tools.sh" ]; then
+ echo "ERROR: Could not restore build tools correctly." 1>&2
+ display_error_message
+ fi
fi
echo "Initializing BuildTools..."
@@ -104,7 +113,8 @@ if [ ! -e $__INIT_TOOLS_DONE_MARKER ]; then
chmod +x $__BUILD_TOOLS_PATH/init-tools.sh
$__BUILD_TOOLS_PATH/init-tools.sh $__scriptpath $__DOTNET_CMD $__TOOLRUNTIME_DIR >> $__init_tools_log
if [ "$?" != "0" ]; then
- echo "ERROR: An error occured when trying to initialize the tools. Please check '$__init_tools_log' for more details."1>&2
+ echo "ERROR: An error occured when trying to initialize the tools." 1>&2
+ display_error_message
exit 1
fi
fi
diff --git a/pkg/Microsoft.Private.CoreFx.UAP/Microsoft.Private.CoreFx.UAP.pkgproj b/pkg/Microsoft.Private.CoreFx.UAP/Microsoft.Private.CoreFx.UAP.pkgproj
index 5882618b23..d7723c7a2a 100644
--- a/pkg/Microsoft.Private.CoreFx.UAP/Microsoft.Private.CoreFx.UAP.pkgproj
+++ b/pkg/Microsoft.Private.CoreFx.UAP/Microsoft.Private.CoreFx.UAP.pkgproj
@@ -4,7 +4,7 @@
<PropertyGroup>
<TargetFrameworkName>uap</TargetFrameworkName>
- <TargetFrameworkVersion>10.1</TargetFrameworkVersion>
+ <TargetFrameworkVersion>$(UAPvNextVersion)</TargetFrameworkVersion>
<TargetFramework>$(TargetFrameworkName)$(TargetFrameworkVersion)</TargetFramework>
<RefBinDir>$(UAPPackageRefPath)</RefBinDir>
diff --git a/pkg/Microsoft.Private.PackageBaseline/Microsoft.Private.PackageBaseline.pkgproj b/pkg/Microsoft.Private.PackageBaseline/Microsoft.Private.PackageBaseline.pkgproj
index 0e108d764a..6796f7c7e7 100644
--- a/pkg/Microsoft.Private.PackageBaseline/Microsoft.Private.PackageBaseline.pkgproj
+++ b/pkg/Microsoft.Private.PackageBaseline/Microsoft.Private.PackageBaseline.pkgproj
@@ -34,7 +34,7 @@
<TargetFramework>netcoreapp2.0</TargetFramework>
</FrameworkLayout>
<FrameworkLayout Include="$(UAPPackageRefPath)">
- <TargetFramework>uap10.1</TargetFramework>
+ <TargetFramework>$(UAPvNextTFM)</TargetFramework>
</FrameworkLayout>
<FrameworkLayout Include="$(PackagesDir)$(NETStandardPackageId)\$(NETStandardPackageVersion)\build\netstandard2.0\ref">
<TargetFramework>netstandard2.0</TargetFramework>
diff --git a/pkg/Microsoft.Private.PackageBaseline/packageIndex.json b/pkg/Microsoft.Private.PackageBaseline/packageIndex.json
index 43d797ce5b..a11ac2ff95 100644
--- a/pkg/Microsoft.Private.PackageBaseline/packageIndex.json
+++ b/pkg/Microsoft.Private.PackageBaseline/packageIndex.json
@@ -73,7 +73,7 @@
"portable46-wp81+wpa81": "4.0.0.0",
"monoandroid10": "Any",
"monotouch10": "Any",
- "uap10.1": "4.0.4.0",
+ "uap10.0.15138": "4.0.4.0",
"win8": "4.0.0.0",
"wp8": "4.0.0.0",
"wpa81": "4.0.0.0",
@@ -172,7 +172,7 @@
"portable46-win81+wpa81": "10.0.0.0",
"portable46-net451+win81": "10.0.0.0",
"portable45-net45+win8": "10.0.0.0",
- "uap10.1": "10.0.0.0",
+ "uap10.0.15138": "10.0.0.0",
"win8": "10.0.0.0",
"wpa81": "10.0.0.0"
},
@@ -217,7 +217,7 @@
"netstandard2.0": "4.0.1.0",
"monoandroid10": "Any",
"monotouch10": "Any",
- "uap10.1": "4.1.1.0",
+ "uap10.0.15138": "4.1.1.0",
"xamarinios10": "Any",
"xamarinmac20": "Any",
"xamarintvos10": "Any",
@@ -327,7 +327,7 @@
"netstandard2.0": "4.0.0.0",
"monoandroid10": "Any",
"monotouch10": "Any",
- "uap10.1": "4.0.0.0",
+ "uap10.0.15138": "4.0.0.0",
"win8": "4.0.0.0",
"wp8": "2.0.5.0",
"wpa81": "4.0.0.0",
@@ -347,7 +347,7 @@
"netcoreapp2.0": "2.0.1.0",
"net461": "2.0.0.0",
"netstandard2.0": "2.0.0.0",
- "uap10.1": "2.0.1.0"
+ "uap10.0.15138": "2.0.1.0"
}
},
"NETStandard.Library": {
@@ -460,7 +460,7 @@
"netstandard2.0": "4.0.0.0",
"monoandroid10": "Any",
"monotouch10": "Any",
- "uap10.1": "4.0.0.0",
+ "uap10.0.15138": "4.0.0.0",
"win8": "4.0.0.0",
"wp8": "2.0.5.0",
"wpa81": "4.0.0.0",
@@ -518,7 +518,7 @@
"netstandard2.0": "4.1.0.0",
"monoandroid10": "Any",
"monotouch10": "Any",
- "uap10.1": "4.2.1.0",
+ "uap10.0.15138": "4.2.1.0",
"xamarinios10": "Any",
"xamarinmac20": "Any",
"xamarintvos10": "Any",
@@ -538,7 +538,7 @@
"BaselineVersion": "4.4.0",
"InboxOn": {
"netcoreapp2.0": "4.0.3.0",
- "uap10.1": "4.0.3.0"
+ "uap10.0.15138": "4.0.3.0"
},
"AssemblyVersionInPackageVersion": {
"4.0.0.0": "4.0.0",
@@ -580,7 +580,7 @@
"netstandard2.0": "4.0.10.0",
"monoandroid10": "Any",
"monotouch10": "Any",
- "uap10.1": "4.1.1.0",
+ "uap10.0.15138": "4.1.1.0",
"win8": "4.0.0.0",
"wp8": "4.0.0.0",
"wpa81": "4.0.0.0",
@@ -616,7 +616,7 @@
"netstandard2.0": "4.0.10.0",
"monoandroid10": "Any",
"monotouch10": "Any",
- "uap10.1": "4.0.14.0",
+ "uap10.0.15138": "4.0.14.0",
"win8": "4.0.0.0",
"wpa81": "4.0.0.0",
"xamarinios10": "Any",
@@ -641,7 +641,7 @@
"BaselineVersion": "1.4.0",
"InboxOn": {
"netcoreapp2.0": "1.2.3.0",
- "uap10.1": "1.2.3.0"
+ "uap10.0.15138": "1.2.3.0"
},
"AssemblyVersionInPackageVersion": {
"1.1.36.0": "1.1.36",
@@ -665,7 +665,7 @@
"netstandard2.0": "4.0.1.0",
"monoandroid10": "Any",
"monotouch10": "Any",
- "uap10.1": "4.1.1.0",
+ "uap10.0.15138": "4.1.1.0",
"xamarinios10": "Any",
"xamarinmac20": "Any",
"xamarintvos10": "Any",
@@ -690,7 +690,7 @@
"netstandard2.0": "4.0.1.0",
"monoandroid10": "Any",
"monotouch10": "Any",
- "uap10.1": "4.1.1.0",
+ "uap10.0.15138": "4.1.1.0",
"xamarinios10": "Any",
"xamarinmac20": "Any",
"xamarintvos10": "Any",
@@ -726,7 +726,7 @@
"netstandard2.0": "4.0.0.0",
"monoandroid10": "Any",
"monotouch10": "Any",
- "uap10.1": "4.0.3.0",
+ "uap10.0.15138": "4.0.3.0",
"win8": "4.0.0.0",
"wp8": "4.0.0.0",
"wpa81": "4.0.0.0",
@@ -757,7 +757,7 @@
"portable45-net45+win8": "4.0.0.0",
"monoandroid10": "Any",
"monotouch10": "Any",
- "uap10.1": "4.2.1.0",
+ "uap10.0.15138": "4.2.1.0",
"win8": "4.0.0.0",
"xamarinios10": "Any",
"xamarinmac20": "Any",
@@ -780,7 +780,7 @@
"netstandard2.0": "4.0.0.0",
"monoandroid10": "Any",
"monotouch10": "Any",
- "uap10.1": "4.0.0.0",
+ "uap10.0.15138": "4.0.0.0",
"xamarinios10": "Any",
"xamarinmac20": "Any",
"xamarintvos10": "Any",
@@ -800,7 +800,7 @@
"portable45-net45+win8": "4.0.0.0",
"monoandroid10": "Any",
"monotouch10": "Any",
- "uap10.1": "4.0.0.0",
+ "uap10.0.15138": "4.0.0.0",
"win8": "4.0.0.0",
"xamarinios10": "Any",
"xamarinmac20": "Any",
@@ -834,7 +834,7 @@
"netstandard2.0": "4.0.10.0",
"monoandroid10": "Any",
"monotouch10": "Any",
- "uap10.1": "4.1.1.0",
+ "uap10.0.15138": "4.1.1.0",
"win8": "4.0.0.0",
"wp8": "4.0.0.0",
"wpa81": "4.0.0.0",
@@ -863,7 +863,7 @@
"netstandard2.0": "4.1.0.0",
"monoandroid10": "Any",
"monotouch10": "Any",
- "uap10.1": "4.2.1.0",
+ "uap10.0.15138": "4.2.1.0",
"xamarinios10": "Any",
"xamarinmac20": "Any",
"xamarintvos10": "Any",
@@ -888,7 +888,7 @@
"netstandard2.0": "4.1.0.0",
"monoandroid10": "Any",
"monotouch10": "Any",
- "uap10.1": "4.2.1.0",
+ "uap10.0.15138": "4.2.1.0",
"xamarinios10": "Any",
"xamarinmac20": "Any",
"xamarintvos10": "Any",
@@ -971,7 +971,7 @@
"InboxOn": {
"netcoreapp2.0": "4.0.0.0",
"net45": "4.0.0.0",
- "uap10.1": "4.0.0.0"
+ "uap10.0.15138": "4.0.0.0"
}
},
"System.Configuration.ConfigurationManager": {
@@ -998,7 +998,7 @@
"netstandard2.0": "4.0.0.0",
"monoandroid10": "Any",
"monotouch10": "Any",
- "uap10.1": "4.1.1.0",
+ "uap10.0.15138": "4.1.1.0",
"xamarinios10": "Any",
"xamarinmac20": "Any",
"xamarintvos10": "Any",
@@ -1027,7 +1027,7 @@
"netstandard2.0": "4.0.0.0",
"monoandroid10": "Any",
"monotouch10": "Any",
- "uap10.1": "4.0.0.0",
+ "uap10.0.15138": "4.0.0.0",
"win8": "4.0.0.0",
"wp8": "2.0.5.0",
"wpa81": "4.0.0.0",
@@ -1044,7 +1044,7 @@
"netstandard2.0": "4.0.0.0",
"monoandroid10": "Any",
"monotouch10": "Any",
- "uap10.1": "4.0.0.0",
+ "uap10.0.15138": "4.0.0.0",
"xamarinios10": "Any",
"xamarinmac20": "Any",
"xamarintvos10": "Any",
@@ -1064,7 +1064,7 @@
"netstandard2.0": "4.1.0.0",
"monoandroid10": "Any",
"monotouch10": "Any",
- "uap10.1": "4.2.1.0",
+ "uap10.0.15138": "4.2.1.0",
"xamarinios10": "Any",
"xamarinmac20": "Any",
"xamarintvos10": "Any",
@@ -1191,7 +1191,7 @@
"netstandard2.0": "4.0.0.0",
"monoandroid10": "Any",
"monotouch10": "Any",
- "uap10.1": "4.0.3.0",
+ "uap10.0.15138": "4.0.3.0",
"win8": "4.0.0.0",
"wp8": "4.0.0.0",
"wpa81": "4.0.0.0",
@@ -1232,7 +1232,7 @@
"netstandard2.0": "4.0.10.0",
"monoandroid10": "Any",
"monotouch10": "Any",
- "uap10.1": "4.1.1.0",
+ "uap10.0.15138": "4.1.1.0",
"win8": "4.0.0.0",
"wp8": "4.0.0.0",
"wpa81": "4.0.0.0",
@@ -1276,7 +1276,7 @@
"netstandard2.0": "4.0.0.0",
"monoandroid10": "Any",
"monotouch10": "Any",
- "uap10.1": "4.0.3.0",
+ "uap10.0.15138": "4.0.3.0",
"xamarinios10": "Any",
"xamarinmac20": "Any",
"xamarintvos10": "Any",
@@ -1309,7 +1309,7 @@
"netstandard2.0": "4.1.0.0",
"monoandroid10": "Any",
"monotouch10": "Any",
- "uap10.1": "4.2.1.0",
+ "uap10.0.15138": "4.2.1.0",
"xamarinios10": "Any",
"xamarinmac20": "Any",
"xamarintvos10": "Any",
@@ -1335,7 +1335,7 @@
"netstandard2.0": "4.0.2.0",
"monoandroid10": "Any",
"monotouch10": "Any",
- "uap10.1": "4.1.1.0",
+ "uap10.0.15138": "4.1.1.0",
"xamarinios10": "Any",
"xamarinmac20": "Any",
"xamarintvos10": "Any",
@@ -1360,7 +1360,7 @@
"netstandard2.0": "4.0.0.0",
"monoandroid10": "Any",
"monotouch10": "Any",
- "uap10.1": "4.1.1.0",
+ "uap10.0.15138": "4.1.1.0",
"xamarinios10": "Any",
"xamarinmac20": "Any",
"xamarintvos10": "Any",
@@ -1395,7 +1395,7 @@
"netstandard2.0": "4.0.0.0",
"monoandroid10": "Any",
"monotouch10": "Any",
- "uap10.1": "4.1.1.0",
+ "uap10.0.15138": "4.1.1.0",
"win8": "4.0.0.0",
"wp8": "4.0.0.0",
"wpa81": "4.0.0.0",
@@ -1432,7 +1432,7 @@
"netstandard2.0": "4.0.0.0",
"monoandroid10": "Any",
"monotouch10": "Any",
- "uap10.1": "4.1.1.0",
+ "uap10.0.15138": "4.1.1.0",
"xamarinios10": "Any",
"xamarinmac20": "Any",
"xamarintvos10": "Any",
@@ -1466,7 +1466,7 @@
"netstandard2.0": "4.1.0.0",
"monoandroid10": "Any",
"monotouch10": "Any",
- "uap10.1": "4.2.1.0",
+ "uap10.0.15138": "4.2.1.0",
"win8": "4.0.0.0",
"win81": "4.0.10.0",
"wpa81": "4.0.10.0",
@@ -1512,7 +1512,7 @@
"netcoreapp2.0": "4.0.0.0",
"net45": "4.0.0.0",
"netstandard2.0": "4.0.0.0",
- "uap10.1": "4.0.0.0"
+ "uap10.0.15138": "4.0.0.0"
}
},
"System.Drawing.Design": {
@@ -1532,7 +1532,7 @@
"netstandard2.0": "4.0.0.0",
"monoandroid10": "Any",
"monotouch10": "Any",
- "uap10.1": "4.2.0.0",
+ "uap10.0.15138": "4.2.0.0",
"xamarinios10": "Any",
"xamarinmac20": "Any",
"xamarintvos10": "Any",
@@ -1575,7 +1575,7 @@
"netstandard2.0": "4.0.10.0",
"monoandroid10": "Any",
"monotouch10": "Any",
- "uap10.1": "4.1.1.0",
+ "uap10.0.15138": "4.1.1.0",
"win8": "4.0.0.0",
"wp8": "4.0.0.0",
"wpa81": "4.0.0.0",
@@ -1623,7 +1623,7 @@
"netstandard2.0": "4.0.10.0",
"monoandroid10": "Any",
"monotouch10": "Any",
- "uap10.1": "4.1.1.0",
+ "uap10.0.15138": "4.1.1.0",
"win8": "4.0.0.0",
"wp8": "4.0.0.0",
"wpa81": "4.0.0.0",
@@ -1652,7 +1652,7 @@
"netstandard2.0": "4.0.1.0",
"monoandroid10": "Any",
"monotouch10": "Any",
- "uap10.1": "4.1.1.0",
+ "uap10.0.15138": "4.1.1.0",
"xamarinios10": "Any",
"xamarinmac20": "Any",
"xamarintvos10": "Any",
@@ -1677,7 +1677,7 @@
"netstandard2.0": "4.0.1.0",
"monoandroid10": "Any",
"monotouch10": "Any",
- "uap10.1": "4.1.1.0",
+ "uap10.0.15138": "4.1.1.0",
"xamarinios10": "Any",
"xamarinmac20": "Any",
"xamarintvos10": "Any",
@@ -1731,7 +1731,7 @@
"netstandard2.0": "4.1.0.0",
"monoandroid10": "Any",
"monotouch10": "Any",
- "uap10.1": "4.2.1.0",
+ "uap10.0.15138": "4.2.1.0",
"win8": "4.0.0.0",
"wp8": "4.0.0.0",
"wpa81": "4.0.0.0",
@@ -1767,7 +1767,7 @@
"netstandard2.0": "4.1.1.0",
"monoandroid10": "Any",
"monotouch10": "Any",
- "uap10.1": "4.2.1.0",
+ "uap10.0.15138": "4.2.1.0",
"win8": "4.0.0.0",
"wpa81": "4.0.0.0",
"xamarinios10": "Any",
@@ -1789,7 +1789,7 @@
"netstandard2.0": "4.0.0.0",
"monoandroid10": "Any",
"monotouch10": "Any",
- "uap10.1": "4.0.0.0",
+ "uap10.0.15138": "4.0.0.0",
"xamarinios10": "Any",
"xamarinmac20": "Any",
"xamarintvos10": "Any",
@@ -1809,7 +1809,7 @@
"netstandard2.0": "4.0.1.0",
"monoandroid10": "Any",
"monotouch10": "Any",
- "uap10.1": "4.0.4.0",
+ "uap10.0.15138": "4.0.4.0",
"xamarinios10": "Any",
"xamarinmac20": "Any",
"xamarintvos10": "Any",
@@ -1834,7 +1834,7 @@
"netstandard2.0": "4.0.1.0",
"monoandroid10": "Any",
"monotouch10": "Any",
- "uap10.1": "4.1.1.0",
+ "uap10.0.15138": "4.1.1.0",
"xamarinios10": "Any",
"xamarinmac20": "Any",
"xamarintvos10": "Any",
@@ -1872,7 +1872,7 @@
"netstandard2.0": "4.0.0.0",
"monoandroid10": "Any",
"monotouch10": "Any",
- "uap10.1": "4.1.1.0",
+ "uap10.0.15138": "4.1.1.0",
"xamarinios10": "Any",
"xamarinmac20": "Any",
"xamarintvos10": "Any",
@@ -1896,7 +1896,7 @@
"netstandard2.0": "4.0.1.0",
"monoandroid10": "Any",
"monotouch10": "Any",
- "uap10.1": "4.1.1.0",
+ "uap10.0.15138": "4.1.1.0",
"xamarinios10": "Any",
"xamarinmac20": "Any",
"xamarintvos10": "Any",
@@ -1920,7 +1920,7 @@
"netstandard2.0": "4.0.0.0",
"monoandroid10": "Any",
"monotouch10": "Any",
- "uap10.1": "4.1.1.0",
+ "uap10.0.15138": "4.1.1.0",
"xamarinios10": "Any",
"xamarinmac20": "Any",
"xamarintvos10": "Any",
@@ -1944,7 +1944,7 @@
"netstandard2.0": "4.0.1.0",
"monoandroid10": "Any",
"monotouch10": "Any",
- "uap10.1": "4.1.1.0",
+ "uap10.0.15138": "4.1.1.0",
"xamarinios10": "Any",
"xamarinmac20": "Any",
"xamarintvos10": "Any",
@@ -1973,7 +1973,7 @@
"netstandard2.0": "4.0.0.0",
"monoandroid10": "Any",
"monotouch10": "Any",
- "uap10.1": "4.1.1.0",
+ "uap10.0.15138": "4.1.1.0",
"xamarinios10": "Any",
"xamarinmac20": "Any",
"xamarintvos10": "Any",
@@ -2008,7 +2008,7 @@
"netcoreapp2.0": "4.1.1.0",
"net461": "4.0.0.0",
"netstandard2.0": "4.0.0.0",
- "uap10.1": "4.1.1.0"
+ "uap10.0.15138": "4.1.1.0"
},
"AssemblyVersionInPackageVersion": {
"4.0.0.0": "4.0.0",
@@ -2047,7 +2047,7 @@
"netstandard2.0": "4.0.1.0",
"monoandroid10": "Any",
"monotouch10": "Any",
- "uap10.1": "4.1.1.0",
+ "uap10.0.15138": "4.1.1.0",
"xamarinios10": "Any",
"xamarinmac20": "Any",
"xamarintvos10": "Any",
@@ -2099,7 +2099,7 @@
"netstandard2.0": "4.1.0.0",
"monoandroid10": "Any",
"monotouch10": "Any",
- "uap10.1": "4.2.1.0",
+ "uap10.0.15138": "4.2.1.0",
"win8": "4.0.0.0",
"wp8": "4.0.0.0",
"wpa81": "4.0.0.0",
@@ -2141,7 +2141,7 @@
"netstandard2.0": "4.1.0.0",
"monoandroid10": "Any",
"monotouch10": "Any",
- "uap10.1": "4.2.1.0",
+ "uap10.0.15138": "4.2.1.0",
"win8": "4.0.0.0",
"wp8": "4.0.0.0",
"wpa81": "4.0.0.0",
@@ -2175,7 +2175,7 @@
"netstandard2.0": "4.0.0.0",
"monoandroid10": "Any",
"monotouch10": "Any",
- "uap10.1": "4.0.3.0",
+ "uap10.0.15138": "4.0.3.0",
"win8": "4.0.0.0",
"wpa81": "4.0.0.0",
"xamarinios10": "Any",
@@ -2213,7 +2213,7 @@
"netstandard2.0": "4.0.0.0",
"monoandroid10": "Any",
"monotouch10": "Any",
- "uap10.1": "4.0.3.0",
+ "uap10.0.15138": "4.0.3.0",
"win8": "4.0.0.0",
"wp8": "4.0.0.0",
"wpa81": "4.0.0.0",
@@ -2267,7 +2267,7 @@
"portable46-wp81+wpa81": "3.9.0.0",
"monoandroid10": "Any",
"monotouch10": "Any",
- "uap10.1": "4.0.0.0",
+ "uap10.0.15138": "4.0.0.0",
"win8": "4.0.0.0",
"wp8": "3.9.0.0",
"wpa81": "4.0.0.0",
@@ -2317,7 +2317,7 @@
"netstandard2.0": "4.1.1.0",
"monoandroid10": "Any",
"monotouch10": "Any",
- "uap10.1": "4.2.1.0",
+ "uap10.0.15138": "4.2.1.0",
"win8": "4.0.0.0",
"wpa81": "4.0.0.0",
"xamarinios10": "Any",
@@ -2340,7 +2340,7 @@
],
"BaselineVersion": "4.4.0",
"InboxOn": {
- "uap10.1": "4.0.4.0",
+ "uap10.0.15138": "4.0.4.0",
"win8": "4.0.0.0"
},
"AssemblyVersionInPackageVersion": {
@@ -2386,7 +2386,7 @@
"netcoreapp2.0": "4.0.1.0",
"monoandroid10": "Any",
"monotouch10": "Any",
- "uap10.1": "4.0.1.0",
+ "uap10.0.15138": "4.0.1.0",
"xamarinios10": "Any",
"xamarinmac20": "Any",
"xamarintvos10": "Any",
@@ -2398,7 +2398,7 @@
"netcoreapp2.0": "4.0.1.0",
"monoandroid10": "Any",
"monotouch10": "Any",
- "uap10.1": "4.0.1.0",
+ "uap10.0.15138": "4.0.1.0",
"xamarinios10": "Any",
"xamarinmac20": "Any",
"xamarintvos10": "Any",
@@ -2417,7 +2417,7 @@
"netstandard2.0": "4.0.0.0",
"monoandroid10": "Any",
"monotouch10": "Any",
- "uap10.1": "4.1.1.0",
+ "uap10.0.15138": "4.1.1.0",
"xamarinios10": "Any",
"xamarinmac20": "Any",
"xamarintvos10": "Any",
@@ -2454,7 +2454,7 @@
"netstandard2.0": "4.1.0.0",
"monoandroid10": "Any",
"monotouch10": "Any",
- "uap10.1": "4.2.1.0",
+ "uap10.0.15138": "4.2.1.0",
"win8": "4.0.0.0",
"wp8": "4.0.0.0",
"wpa81": "4.0.0.0",
@@ -2481,7 +2481,7 @@
"netstandard2.0": "4.0.0.0",
"monoandroid10": "Any",
"monotouch10": "Any",
- "uap10.1": "4.1.1.0",
+ "uap10.0.15138": "4.1.1.0",
"xamarinios10": "Any",
"xamarinmac20": "Any",
"xamarintvos10": "Any",
@@ -2519,7 +2519,7 @@
"netstandard2.0": "4.0.10.0",
"monoandroid10": "Any",
"monotouch10": "Any",
- "uap10.1": "4.1.1.0",
+ "uap10.0.15138": "4.1.1.0",
"win8": "4.0.0.0",
"wp8": "3.9.0.0",
"wpa81": "4.0.0.0",
@@ -2563,7 +2563,7 @@
"netstandard2.0": "4.0.10.0",
"monoandroid10": "Any",
"monotouch10": "Any",
- "uap10.1": "4.1.1.0",
+ "uap10.0.15138": "4.1.1.0",
"win8": "4.0.0.0",
"wp8": "3.9.0.0",
"wpa81": "4.0.0.0",
@@ -2592,7 +2592,7 @@
"netstandard2.0": "4.0.0.0",
"monoandroid10": "Any",
"monotouch10": "Any",
- "uap10.1": "4.1.1.0",
+ "uap10.0.15138": "4.1.1.0",
"xamarinios10": "Any",
"xamarinmac20": "Any",
"xamarintvos10": "Any",
@@ -2608,7 +2608,7 @@
"netcoreapp2.0": "4.0.1.0",
"monoandroid10": "Any",
"monotouch10": "Any",
- "uap10.1": "4.0.1.0",
+ "uap10.0.15138": "4.0.1.0",
"xamarinios10": "Any",
"xamarinmac20": "Any",
"xamarintvos10": "Any",
@@ -2628,7 +2628,7 @@
"netstandard2.0": "4.1.0.0",
"monoandroid10": "Any",
"monotouch10": "Any",
- "uap10.1": "4.2.1.0",
+ "uap10.0.15138": "4.2.1.0",
"xamarinios10": "Any",
"xamarinmac20": "Any",
"xamarintvos10": "Any",
@@ -2654,7 +2654,7 @@
"System.Net.WebClient": {
"InboxOn": {
"netcoreapp2.0": "4.0.1.0",
- "uap10.1": "4.0.1.0"
+ "uap10.0.15138": "4.0.1.0"
}
},
"System.Net.WebHeaderCollection": {
@@ -2670,7 +2670,7 @@
"netstandard2.0": "4.0.0.0",
"monoandroid10": "Any",
"monotouch10": "Any",
- "uap10.1": "4.1.1.0",
+ "uap10.0.15138": "4.1.1.0",
"xamarinios10": "Any",
"xamarinmac20": "Any",
"xamarintvos10": "Any",
@@ -2685,7 +2685,7 @@
"System.Net.WebProxy": {
"InboxOn": {
"netcoreapp2.0": "4.0.1.0",
- "uap10.1": "4.0.1.0"
+ "uap10.0.15138": "4.0.1.0"
}
},
"System.Net.WebSockets": {
@@ -2700,7 +2700,7 @@
"netstandard2.0": "4.0.0.0",
"monoandroid10": "Any",
"monotouch10": "Any",
- "uap10.1": "4.1.1.0",
+ "uap10.0.15138": "4.1.1.0",
"xamarinios10": "Any",
"xamarinmac20": "Any",
"xamarintvos10": "Any",
@@ -2723,7 +2723,7 @@
"netstandard2.0": "4.0.0.0",
"monoandroid10": "Any",
"monotouch10": "Any",
- "uap10.1": "4.1.1.0",
+ "uap10.0.15138": "4.1.1.0",
"xamarinios10": "Any",
"xamarinmac20": "Any",
"xamarintvos10": "Any",
@@ -2746,7 +2746,7 @@
"netstandard2.0": "4.0.0.0",
"monoandroid10": "Any",
"monotouch10": "Any",
- "uap10.1": "4.0.0.0",
+ "uap10.0.15138": "4.0.0.0",
"win8": "4.0.0.0",
"wpa81": "4.0.0.0",
"xamarinios10": "Any",
@@ -2769,7 +2769,7 @@
"net461": "4.1.2.0",
"monoandroid10": "Any",
"monotouch10": "Any",
- "uap10.1": "4.1.4.0",
+ "uap10.0.15138": "4.1.4.0",
"xamarinios10": "Any",
"xamarinmac20": "Any",
"xamarintvos10": "Any",
@@ -2792,7 +2792,7 @@
],
"BaselineVersion": "4.4.0",
"InboxOn": {
- "uap10.1": "4.0.4.0"
+ "uap10.0.15138": "4.0.4.0"
},
"AssemblyVersionInPackageVersion": {
"4.0.0.0": "4.0.0",
@@ -2827,7 +2827,7 @@
"netstandard2.0": "4.0.10.0",
"monoandroid10": "Any",
"monotouch10": "Any",
- "uap10.1": "4.1.1.0",
+ "uap10.0.15138": "4.1.1.0",
"win8": "4.0.0.0",
"wp8": "4.0.0.0",
"wpa81": "4.0.0.0",
@@ -2906,7 +2906,7 @@
"netstandard2.0": "4.1.0.0",
"monoandroid10": "Any",
"monotouch10": "Any",
- "uap10.1": "4.2.1.0",
+ "uap10.0.15138": "4.2.1.0",
"win8": "4.0.0.0",
"wp8": "4.0.0.0",
"wpa81": "4.0.0.0",
@@ -2933,7 +2933,7 @@
"net45": "4.0.0.0",
"portable46-net451+win81": "4.0.0.0",
"portable45-net45+win8": "4.0.0.0",
- "uap10.1": "4.0.3.0",
+ "uap10.0.15138": "4.0.3.0",
"win8": "4.0.0.0"
},
"AssemblyVersionInPackageVersion": {
@@ -2954,7 +2954,7 @@
"netcoreapp2.0": "4.0.4.0",
"monoandroid10": "Any",
"monotouch10": "Any",
- "uap10.1": "4.0.4.0",
+ "uap10.0.15138": "4.0.4.0",
"xamarinios10": "Any",
"xamarinmac20": "Any",
"xamarintvos10": "Any",
@@ -3062,7 +3062,7 @@
"netstandard2.0": "4.0.0.0",
"monoandroid10": "Any",
"monotouch10": "Any",
- "uap10.1": "4.1.1.0",
+ "uap10.0.15138": "4.1.1.0",
"win8": "4.0.0.0",
"wp8": "4.0.0.0",
"wpa81": "4.0.0.0",
@@ -3088,7 +3088,7 @@
"BaselineVersion": "1.5.0",
"InboxOn": {
"netcoreapp2.0": "1.4.3.0",
- "uap10.1": "1.4.3.0"
+ "uap10.0.15138": "1.4.3.0"
},
"AssemblyVersionInPackageVersion": {
"1.0.22.0": "1.0.22",
@@ -3124,7 +3124,7 @@
"netstandard2.0": "4.0.0.0",
"monoandroid10": "Any",
"monotouch10": "Any",
- "uap10.1": "4.1.1.0",
+ "uap10.0.15138": "4.1.1.0",
"win8": "4.0.0.0",
"wp8": "4.0.0.0",
"wpa81": "4.0.0.0",
@@ -3150,7 +3150,7 @@
"netcoreapp2.0": "4.1.3.0",
"monoandroid10": "Any",
"monotouch10": "Any",
- "uap10.1": "4.1.3.0",
+ "uap10.0.15138": "4.1.3.0",
"xamarinios10": "Any",
"xamarinmac20": "Any",
"xamarintvos10": "Any",
@@ -3174,7 +3174,7 @@
"netcoreapp2.0": "4.1.1.0",
"net461": "4.0.1.0",
"netstandard2.0": "4.0.1.0",
- "uap10.1": "4.1.1.0"
+ "uap10.0.15138": "4.1.1.0"
},
"AssemblyVersionInPackageVersion": {
"4.0.0.0": "4.0.0",
@@ -3215,7 +3215,7 @@
"netstandard2.0": "4.0.0.0",
"monoandroid10": "Any",
"monotouch10": "Any",
- "uap10.1": "4.1.1.0",
+ "uap10.0.15138": "4.1.1.0",
"win8": "4.0.0.0",
"wp8": "4.0.0.0",
"wpa81": "4.0.0.0",
@@ -3240,7 +3240,7 @@
"netcoreapp2.0": "4.1.1.0",
"net461": "4.0.1.0",
"netstandard2.0": "4.0.1.0",
- "uap10.1": "4.1.1.0"
+ "uap10.0.15138": "4.1.1.0"
},
"AssemblyVersionInPackageVersion": {
"4.0.0.0": "4.0.0",
@@ -3276,7 +3276,7 @@
"netstandard2.0": "4.1.0.0",
"monoandroid10": "Any",
"monotouch10": "Any",
- "uap10.1": "4.2.1.0",
+ "uap10.0.15138": "4.2.1.0",
"win8": "4.0.0.0",
"win81": "4.0.10.0",
"wp8": "4.0.0.0",
@@ -3325,7 +3325,7 @@
"netstandard2.0": "4.0.0.0",
"monoandroid10": "Any",
"monotouch10": "Any",
- "uap10.1": "4.1.1.0",
+ "uap10.0.15138": "4.1.1.0",
"xamarinios10": "Any",
"xamarinmac20": "Any",
"xamarintvos10": "Any",
@@ -3368,7 +3368,7 @@
"netstandard2.0": "4.1.0.0",
"monoandroid10": "Any",
"monotouch10": "Any",
- "uap10.1": "4.2.1.0",
+ "uap10.0.15138": "4.2.1.0",
"win8": "4.0.0.0",
"wp8": "4.0.0.0",
"wpa81": "4.0.0.0",
@@ -3397,7 +3397,7 @@
"netstandard2.0": "4.0.0.0",
"monoandroid10": "Any",
"monotouch10": "Any",
- "uap10.1": "4.1.1.0",
+ "uap10.0.15138": "4.1.1.0",
"xamarinios10": "Any",
"xamarinmac20": "Any",
"xamarintvos10": "Any",
@@ -3432,7 +3432,7 @@
"netstandard2.0": "4.1.0.0",
"monoandroid10": "Any",
"monotouch10": "Any",
- "uap10.1": "4.2.1.0",
+ "uap10.0.15138": "4.2.1.0",
"win8": "4.0.0.0",
"win81": "4.0.10.0",
"wpa81": "4.0.10.0",
@@ -3459,7 +3459,7 @@
"netcoreapp2.0": "4.0.3.0",
"monoandroid10": "Any",
"monotouch10": "Any",
- "uap10.1": "4.0.3.0",
+ "uap10.0.15138": "4.0.3.0",
"xamarinios10": "Any",
"xamarinmac20": "Any",
"xamarintvos10": "Any",
@@ -3494,7 +3494,7 @@
"portable46-wp81+wpa81": "4.0.0.0",
"monoandroid10": "Any",
"monotouch10": "Any",
- "uap10.1": "4.0.3.0",
+ "uap10.0.15138": "4.0.3.0",
"win8": "4.0.0.0",
"wp8": "4.0.0.0",
"wpa81": "4.0.0.0",
@@ -3541,7 +3541,7 @@
"netstandard2.0": "4.0.0.0",
"monoandroid10": "Any",
"monotouch10": "Any",
- "uap10.1": "4.1.1.0",
+ "uap10.0.15138": "4.1.1.0",
"win8": "4.0.0.0",
"wpa81": "4.0.0.0",
"xamarinios10": "Any",
@@ -3578,7 +3578,7 @@
"netstandard2.0": "4.0.0.0",
"monoandroid10": "Any",
"monotouch10": "Any",
- "uap10.1": "4.0.0.0",
+ "uap10.0.15138": "4.0.0.0",
"win8": "4.0.0.0",
"wp8": "2.0.5.0",
"wpa81": "4.0.0.0",
@@ -3599,7 +3599,7 @@
"netstandard2.0": "4.0.1.0",
"monoandroid10": "Any",
"monotouch10": "Any",
- "uap10.1": "4.0.3.0",
+ "uap10.0.15138": "4.0.3.0",
"xamarinios10": "Any",
"xamarinmac20": "Any",
"xamarintvos10": "Any",
@@ -3639,7 +3639,7 @@
"netstandard2.0": "4.0.0.0",
"monoandroid10": "Any",
"monotouch10": "Any",
- "uap10.1": "4.0.4.0",
+ "uap10.0.15138": "4.0.4.0",
"win8": "4.0.0.0",
"wp8": "4.0.0.0",
"wpa81": "4.0.0.0",
@@ -3683,7 +3683,7 @@
"netstandard2.0": "4.1.1.0",
"monoandroid10": "Any",
"monotouch10": "Any",
- "uap10.1": "4.2.1.0",
+ "uap10.0.15138": "4.2.1.0",
"win8": "4.0.0.0",
"wp8": "4.0.0.0",
"wpa81": "4.0.0.0",
@@ -3728,7 +3728,7 @@
"netstandard2.0": "4.1.1.0",
"monoandroid10": "Any",
"monotouch10": "Any",
- "uap10.1": "4.1.4.0",
+ "uap10.0.15138": "4.1.4.0",
"win8": "4.0.0.0",
"wp8": "4.0.0.0",
"wpa81": "4.0.0.0",
@@ -3758,7 +3758,7 @@
"portable46-win81+wp81": "4.0.0.0",
"portable46-win81+wpa81": "4.0.10.0",
"portable46-wp81+wpa81": "4.0.0.0",
- "uap10.1": "4.0.14.0",
+ "uap10.0.15138": "4.0.14.0",
"win8": "4.0.0.0",
"win81": "4.0.10.0",
"wp8": "4.0.0.0",
@@ -3781,7 +3781,7 @@
"BaselineVersion": "4.4.0",
"InboxOn": {
"portable46-win81+wpa81": "4.0.0.0",
- "uap10.1": "4.0.4.0",
+ "uap10.0.15138": "4.0.4.0",
"win8": "4.0.0.0",
"wpa81": "4.0.0.0"
},
@@ -3796,7 +3796,7 @@
"InboxOn": {
"netcoreapp2.0": "4.0.0.0",
"net45": "4.0.0.0",
- "uap10.1": "4.0.0.0"
+ "uap10.0.15138": "4.0.0.0"
}
},
"System.Security.AccessControl": {
@@ -3826,7 +3826,7 @@
"netstandard2.0": "4.0.1.0",
"monoandroid10": "Any",
"monotouch10": "Any",
- "uap10.1": "4.1.1.0",
+ "uap10.0.15138": "4.1.1.0",
"xamarinios10": "Any",
"xamarinmac20": "Any",
"xamarintvos10": "Any",
@@ -3850,7 +3850,7 @@
"netstandard2.0": "4.2.0.0",
"monoandroid10": "Any",
"monotouch10": "Any",
- "uap10.1": "4.3.1.0",
+ "uap10.0.15138": "4.3.1.0",
"xamarinios10": "Any",
"xamarinmac20": "Any",
"xamarintvos10": "Any",
@@ -3891,7 +3891,7 @@
"netstandard2.0": "4.0.0.0",
"monoandroid10": "Any",
"monotouch10": "Any",
- "uap10.1": "4.1.1.0",
+ "uap10.0.15138": "4.1.1.0",
"xamarinios10": "Any",
"xamarinmac20": "Any",
"xamarintvos10": "Any",
@@ -3914,7 +3914,7 @@
"netstandard2.0": "4.0.0.0",
"monoandroid10": "Any",
"monotouch10": "Any",
- "uap10.1": "4.1.1.0",
+ "uap10.0.15138": "4.1.1.0",
"xamarinios10": "Any",
"xamarinmac20": "Any",
"xamarintvos10": "Any",
@@ -3965,7 +3965,7 @@
"netstandard2.0": "4.0.0.0",
"monoandroid10": "Any",
"monotouch10": "Any",
- "uap10.1": "4.1.1.0",
+ "uap10.0.15138": "4.1.1.0",
"xamarinios10": "Any",
"xamarinmac20": "Any",
"xamarintvos10": "Any",
@@ -4009,7 +4009,7 @@
"netstandard2.0": "4.1.0.0",
"monoandroid10": "Any",
"monotouch10": "Any",
- "uap10.1": "4.2.1.0",
+ "uap10.0.15138": "4.2.1.0",
"xamarinios10": "Any",
"xamarinmac20": "Any",
"xamarintvos10": "Any",
@@ -4060,7 +4060,7 @@
"netstandard2.0": "4.0.0.0",
"monoandroid10": "Any",
"monotouch10": "Any",
- "uap10.1": "4.1.1.0",
+ "uap10.0.15138": "4.1.1.0",
"win8": "4.0.0.0",
"wp8": "4.0.0.0",
"wpa81": "4.0.0.0",
@@ -4101,7 +4101,7 @@
"netstandard2.0": "4.0.0.0",
"monoandroid10": "Any",
"monotouch10": "Any",
- "uap10.1": "4.1.1.0",
+ "uap10.0.15138": "4.1.1.0",
"xamarinios10": "Any",
"xamarinmac20": "Any",
"xamarintvos10": "Any",
@@ -4265,7 +4265,7 @@
"portable46-wp81+wpa81": "4.0.0.0",
"monoandroid10": "Any",
"monotouch10": "Any",
- "uap10.1": "4.0.0.0",
+ "uap10.0.15138": "4.0.0.0",
"win8": "4.0.0.0",
"wp8": "2.0.5.0",
"wpa81": "4.0.0.0",
@@ -4279,7 +4279,7 @@
"InboxOn": {
"netcoreapp2.0": "4.0.0.0",
"net45": "4.0.0.0",
- "uap10.1": "4.0.0.0"
+ "uap10.0.15138": "4.0.0.0"
}
},
"System.ServiceProcess.ServiceController": {
@@ -4327,7 +4327,7 @@
"netstandard2.0": "4.0.10.0",
"monoandroid10": "Any",
"monotouch10": "Any",
- "uap10.1": "4.1.1.0",
+ "uap10.0.15138": "4.1.1.0",
"win8": "4.0.0.0",
"wp8": "4.0.0.0",
"wpa81": "4.0.0.0",
@@ -4353,7 +4353,7 @@
"InboxOn": {
"monoandroid10": "Any",
"monotouch10": "Any",
- "uap10.1": "4.1.1.0",
+ "uap10.0.15138": "4.1.1.0",
"xamarinios10": "Any",
"xamarinmac20": "Any",
"xamarintvos10": "Any",
@@ -4393,7 +4393,7 @@
"netstandard2.0": "4.0.10.0",
"monoandroid10": "Any",
"monotouch10": "Any",
- "uap10.1": "4.1.1.0",
+ "uap10.0.15138": "4.1.1.0",
"win8": "4.0.0.0",
"wp8": "4.0.0.0",
"wpa81": "4.0.0.0",
@@ -4450,7 +4450,7 @@
"netstandard2.0": "4.1.0.0",
"monoandroid10": "Any",
"monotouch10": "Any",
- "uap10.1": "4.2.1.0",
+ "uap10.0.15138": "4.2.1.0",
"win8": "4.0.0.0",
"wp8": "4.0.0.0",
"wpa81": "4.0.0.0",
@@ -4492,7 +4492,7 @@
"netstandard2.0": "4.0.10.0",
"monoandroid10": "Any",
"monotouch10": "Any",
- "uap10.1": "4.1.1.0",
+ "uap10.0.15138": "4.1.1.0",
"win8": "4.0.0.0",
"wp8": "4.0.0.0",
"wpa81": "4.0.0.0",
@@ -4533,7 +4533,7 @@
"netcoreapp2.0": "4.1.1.0",
"net461": "4.0.1.0",
"netstandard2.0": "4.0.1.0",
- "uap10.1": "4.1.1.0"
+ "uap10.0.15138": "4.1.1.0"
},
"AssemblyVersionInPackageVersion": {
"4.0.0.0": "4.0.0",
@@ -4567,7 +4567,7 @@
"netstandard2.0": "4.0.10.0",
"monoandroid10": "Any",
"monotouch10": "Any",
- "uap10.1": "4.1.1.0",
+ "uap10.0.15138": "4.1.1.0",
"win8": "4.0.0.0",
"wp8": "4.0.0.0",
"wpa81": "4.0.0.0",
@@ -4592,7 +4592,7 @@
"BaselineVersion": "4.8.0",
"InboxOn": {
"netcoreapp2.0": "4.6.3.0",
- "uap10.1": "4.6.3.0"
+ "uap10.0.15138": "4.6.3.0"
},
"AssemblyVersionInPackageVersion": {
"4.5.25.0": "4.5.25",
@@ -4636,7 +4636,7 @@
"netstandard2.0": "4.0.0.0",
"monoandroid10": "Any",
"monotouch10": "Any",
- "uap10.1": "4.0.3.0",
+ "uap10.0.15138": "4.0.3.0",
"win8": "4.0.0.0",
"wpa81": "4.0.0.0",
"xamarinios10": "Any",
@@ -4662,7 +4662,7 @@
"netstandard2.0": "4.0.0.0",
"monoandroid10": "Any",
"monotouch10": "Any",
- "uap10.1": "4.1.1.0",
+ "uap10.0.15138": "4.1.1.0",
"xamarinios10": "Any",
"xamarinmac20": "Any",
"xamarintvos10": "Any",
@@ -4685,7 +4685,7 @@
"netstandard2.0": "4.0.10.0",
"monoandroid10": "Any",
"monotouch10": "Any",
- "uap10.1": "4.1.1.0",
+ "uap10.0.15138": "4.1.1.0",
"xamarinios10": "Any",
"xamarinmac20": "Any",
"xamarintvos10": "Any",
@@ -4712,7 +4712,7 @@
"netstandard2.0": "4.0.0.0",
"monoandroid10": "Any",
"monotouch10": "Any",
- "uap10.1": "4.1.1.0",
+ "uap10.0.15138": "4.1.1.0",
"win81": "4.0.0.0",
"wpa81": "4.0.0.0",
"xamarinios10": "Any",
@@ -4733,7 +4733,7 @@
"netstandard2.0": "4.0.0.0",
"monoandroid10": "Any",
"monotouch10": "Any",
- "uap10.1": "4.0.0.0",
+ "uap10.0.15138": "4.0.0.0",
"xamarinios10": "Any",
"xamarinmac20": "Any",
"xamarintvos10": "Any",
@@ -4743,7 +4743,7 @@
"System.Transactions.Local": {
"InboxOn": {
"netcoreapp2.0": "4.0.1.0",
- "uap10.1": "4.0.1.0"
+ "uap10.0.15138": "4.0.1.0"
}
},
"System.ValueTuple": {
@@ -4756,7 +4756,7 @@
"netstandard2.0": "4.0.2.0",
"monoandroid10": "Any",
"monotouch10": "Any",
- "uap10.1": "4.0.3.0",
+ "uap10.0.15138": "4.0.3.0",
"xamarinios10": "Any",
"xamarinmac20": "Any",
"xamarintvos10": "Any",
@@ -4773,7 +4773,7 @@
"netcoreapp2.0": "4.0.0.0",
"net45": "4.0.0.0",
"netstandard2.0": "4.0.0.0",
- "uap10.1": "4.0.0.0"
+ "uap10.0.15138": "4.0.0.0"
}
},
"System.Web.Abstractions": {
@@ -4829,7 +4829,7 @@
"System.Web.HttpUtility": {
"InboxOn": {
"netcoreapp2.0": "4.0.1.0",
- "uap10.1": "4.0.1.0"
+ "uap10.0.15138": "4.0.1.0"
}
},
"System.Web.Mobile": {
@@ -4875,7 +4875,7 @@
"portable46-wp81+wpa81": "4.0.0.0",
"monoandroid10": "Any",
"monotouch10": "Any",
- "uap10.1": "4.0.0.0",
+ "uap10.0.15138": "4.0.0.0",
"win8": "4.0.0.0",
"wp8": "2.0.6.0",
"wpa81": "4.0.0.0",
@@ -4958,7 +4958,7 @@
"netstandard2.0": "4.0.0.0",
"monoandroid10": "Any",
"monotouch10": "Any",
- "uap10.1": "4.0.0.0",
+ "uap10.0.15138": "4.0.0.0",
"win8": "4.0.0.0",
"wp8": "2.0.5.0",
"wpa81": "4.0.0.0",
@@ -4986,7 +4986,7 @@
"netstandard2.0": "4.0.0.0",
"monoandroid10": "Any",
"monotouch10": "Any",
- "uap10.1": "4.0.0.0",
+ "uap10.0.15138": "4.0.0.0",
"win8": "4.0.0.0",
"wp8": "2.0.5.0",
"wpa81": "4.0.0.0",
@@ -5023,7 +5023,7 @@
"netstandard2.0": "4.1.0.0",
"monoandroid10": "Any",
"monotouch10": "Any",
- "uap10.1": "4.2.1.0",
+ "uap10.0.15138": "4.2.1.0",
"win8": "4.0.0.0",
"wp8": "4.0.0.0",
"wpa81": "4.0.0.0",
@@ -5056,7 +5056,7 @@
"portable46-wp81+wpa81": "4.0.0.0",
"monoandroid10": "Any",
"monotouch10": "Any",
- "uap10.1": "4.0.0.0",
+ "uap10.0.15138": "4.0.0.0",
"win8": "4.0.0.0",
"wp8": "2.0.5.0",
"wpa81": "4.0.0.0",
@@ -5092,7 +5092,7 @@
"netstandard2.0": "4.0.10.0",
"monoandroid10": "Any",
"monotouch10": "Any",
- "uap10.1": "4.1.1.0",
+ "uap10.0.15138": "4.1.1.0",
"win8": "4.0.0.0",
"wp8": "4.0.0.0",
"wpa81": "4.0.0.0",
@@ -5121,7 +5121,7 @@
"netstandard2.0": "4.0.1.0",
"monoandroid10": "Any",
"monotouch10": "Any",
- "uap10.1": "4.1.1.0",
+ "uap10.0.15138": "4.1.1.0",
"xamarinios10": "Any",
"xamarinmac20": "Any",
"xamarintvos10": "Any",
@@ -5159,7 +5159,7 @@
"netstandard2.0": "4.0.10.0",
"monoandroid10": "Any",
"monotouch10": "Any",
- "uap10.1": "4.1.1.0",
+ "uap10.0.15138": "4.1.1.0",
"win8": "4.0.0.0",
"wp8": "4.0.0.0",
"wpa81": "4.0.0.0",
@@ -5188,7 +5188,7 @@
"netstandard2.0": "4.0.1.0",
"monoandroid10": "Any",
"monotouch10": "Any",
- "uap10.1": "4.1.1.0",
+ "uap10.0.15138": "4.1.1.0",
"xamarinios10": "Any",
"xamarinmac20": "Any",
"xamarintvos10": "Any",
@@ -5213,7 +5213,7 @@
"netstandard2.0": "4.0.1.0",
"monoandroid10": "Any",
"monotouch10": "Any",
- "uap10.1": "4.1.1.0",
+ "uap10.0.15138": "4.1.1.0",
"xamarinios10": "Any",
"xamarinmac20": "Any",
"xamarintvos10": "Any",
@@ -5280,7 +5280,7 @@
"InboxOn": {
"netcoreapp2.0": "4.0.0.0",
"net45": "4.0.0.0",
- "uap10.1": "4.0.0.0"
+ "uap10.0.15138": "4.0.0.0"
}
},
"WindowsFormsIntegration": {
diff --git a/pkg/NETStandard.Library.NETFramework/NETStandard.Library.NETFramework.pkgproj b/pkg/NETStandard.Library.NETFramework/NETStandard.Library.NETFramework.pkgproj
index ecf97ce0ac..4b1ccc68e0 100644
--- a/pkg/NETStandard.Library.NETFramework/NETStandard.Library.NETFramework.pkgproj
+++ b/pkg/NETStandard.Library.NETFramework/NETStandard.Library.NETFramework.pkgproj
@@ -13,12 +13,12 @@
<IsFrameworkPackage>true</IsFrameworkPackage>
<IncludeLibFiles>true</IncludeLibFiles>
-
- <!-- ValidatePackage doesn't evaluate our targets/props so it does
+
+ <!-- ValidatePackage doesn't evaluate our targets/props so it does
not find any of the assets in this package -->
<SkipValidatePackage>true</SkipValidatePackage>
</PropertyGroup>
-
+
<ItemGroup>
<StampFile Include="targets\NETStandard.Library.NETFramework.common.props">
<TargetPath>build</TargetPath>
@@ -71,7 +71,7 @@
<StampedFile>$(IntermediateOutputPath)%(StampFile.RelativeDir)%(StampFile.FileName)%(StampFile.Extension)</StampedFile>
</StampFile>
</ItemGroup>
-
+
<MakeDir Directories="$([System.IO.Path]::GetDirectoryName('%(StampFile.StampedFile)'))" />
<!-- Update targets templates -->
<WriteLinesToFile
@@ -83,7 +83,7 @@
<File Include="@(StampFile->'%(StampedFile)')" />
</ItemGroup>
</Target>
-
+
<Target Name="AddNETStandardLibraryReference" AfterTargets="ApplyBaselineToStaticDependencies">
<ItemGroup>
<!-- ApplyBaseline doesn't handle NuGet versions, so workaround that by
@@ -96,7 +96,30 @@
</ItemGroup>
</Target>
- <Target Name="ExpandClosureFilesByTargetFramework"
+ <Target Name="AddFrameworkClosureFiles" AfterTargets="ExpandClosureFilesByTargetFramework">
+ <ItemGroup>
+ <FrameworkClosureFile Include="@(NetFxReference->'$(RefRootPath)netfx/%(Identity).dll')" >
+ <FileSet>reference-net461</FileSet>
+ </FrameworkClosureFile>
+ <FrameworkClosureFile Include="@(NetFxReference->'$(RefRootPath)netfx/%(Identity).dll')" >
+ <FileSet>runtime-net461</FileSet>
+ </FrameworkClosureFile>
+ <FrameworkClosureFile Include="@(NetFxReference->'$(RefRootPath)net462/%(Identity).dll')" >
+ <FileSet>reference-net462</FileSet>
+ </FrameworkClosureFile>
+ <FrameworkClosureFile Include="@(NetFxReference->'$(RefRootPath)net462/%(Identity).dll')" >
+ <FileSet>runtime-net462</FileSet>
+ </FrameworkClosureFile>
+ <FrameworkClosureFile Include="@(NetFxReference->'$(RefRootPath)net47/%(Identity).dll')" >
+ <FileSet>reference-net47</FileSet>
+ </FrameworkClosureFile>
+ <FrameworkClosureFile Include="@(NetFxReference->'$(RefRootPath)net47/%(Identity).dll')" >
+ <FileSet>runtime-net47</FileSet>
+ </FrameworkClosureFile>
+ </ItemGroup>
+ </Target>
+
+ <Target Name="ExpandClosureFilesByTargetFramework"
AfterTargets="GetClosureFiles"
Inputs="%(ClosureFile.FileSet)"
Outputs="batching-on-Closure-metadata">
@@ -123,7 +146,7 @@
<ClosureFile Include="@(_closureFileNet462->'%(Original)')">
<FileSet>%(FileSet)-net462</FileSet>
</ClosureFile>
-
+
<ClosureFile Include="@(_closureFileNet47->'%(Original)')" >
<FileSet>%(FileSet)-net47</FileSet>
</ClosureFile>
@@ -132,7 +155,7 @@
<Import Project="$([MSBuild]::GetDirectoryNameOfFileAbove($(MSBuildThisFileDirectory), dir.targets))\dir.targets" />
- <!-- runs as initial target, overrides IncludeFiles in frameworkPackage.targets to define TFM-specific TargetPath
+ <!-- runs as initial target, overrides IncludeFiles in frameworkPackage.targets to define TFM-specific TargetPath
under the build folder -->
<Target Name="IncludeFiles" DependsOnTargets="IncludeNETStandardShims">
<PropertyGroup>
@@ -144,7 +167,7 @@
<File Include="@(RefFile)">
<TargetPath Condition="'%(RefFile.TargetPath)' == ''">build/%(RefFile.TargetFramework)/ref%(RefFile.SubFolder)</TargetPath>
</File>
-
+
<!-- Include lib -->
<File Include="@(LibFile)">
<TargetPath Condition="'%(LibFile.TargetPath)' == '' ">build/%(LibFile.TargetFramework)/lib%(LibFile.SubFolder)</TargetPath>
diff --git a/pkg/NETStandard.Library.NETFramework/targets/NETStandard.Library.NETFramework.common.targets b/pkg/NETStandard.Library.NETFramework/targets/NETStandard.Library.NETFramework.common.targets
index 4ce7315585..a8454df011 100644
--- a/pkg/NETStandard.Library.NETFramework/targets/NETStandard.Library.NETFramework.common.targets
+++ b/pkg/NETStandard.Library.NETFramework/targets/NETStandard.Library.NETFramework.common.targets
@@ -1,4 +1,7 @@
<Project xmlns="http://schemas.microsoft.com/developer/msbuild/2003">
+ <PropertyGroup>
+ <ImportedNETStandardLibraryNETFrameworkCommonTargets>true</ImportedNETStandardLibraryNETFrameworkCommonTargets>
+ </PropertyGroup>
<Choose>
<!-- Allow completely disabling the conflict resolution targets-->
<When Condition="'$(ImplicitlyExpandNETStandardFacades)' != 'true'" />
@@ -28,7 +31,7 @@
<!-- Ensure this runs before conflict resolution since the added files may cause conflicts -->
<HandlePackageFileConflictsDependsOn>ImplicitlyExpandNETStandardFacades;$(HandlePackageFileConflictsDependsOn)</HandlePackageFileConflictsDependsOn>
</PropertyGroup>
-
+
<ItemGroup Condition="'$(DontTrimNETStandardLibraryNETFramework)' != 'true'">
<!-- mark this package as trimmable so that files in the same package aren't automatically rooted -->
<TrimmablePackages Include="NETStandard.Library.NETFramework" />
diff --git a/pkg/NETStandard.Library.NETFramework/targets/net461/NETStandard.Library.NETFramework.targets b/pkg/NETStandard.Library.NETFramework/targets/net461/NETStandard.Library.NETFramework.targets
index 1dc201bbe6..a01175375e 100644
--- a/pkg/NETStandard.Library.NETFramework/targets/net461/NETStandard.Library.NETFramework.targets
+++ b/pkg/NETStandard.Library.NETFramework/targets/net461/NETStandard.Library.NETFramework.targets
@@ -1,11 +1,11 @@
<Project xmlns="http://schemas.microsoft.com/developer/msbuild/2003">
<ItemGroup Condition="'$(ImplicitlyExpandNETStandardFacades)' == 'true'">
- <_NETStandardLibraryNETFrameworkReference Include="$(MSBuildThisFileDirectory)\ref\*.dll"
- Exclude="@(_NETStandardLibraryNETFrameworkReference->'$(MSBuildThisFileDirectory)\ref\%(FileName).dll'" />
+ <_NETStandardLibraryNETFrameworkReference Include="$(MSBuildThisFileDirectory)\ref\*.dll"
+ Exclude="@(_NETStandardLibraryNETFrameworkReference->'$(MSBuildThisFileDirectory)\ref\%(FileName).dll')" />
- <_NETStandardLibraryNETFrameworkLib Include="$(MSBuildThisFileDirectory)\lib\*.dll"
- Exclude="@(_NETStandardLibraryNETFrameworkLib->'$(MSBuildThisFileDirectory)\ref\%(FileName).dll'" />
+ <_NETStandardLibraryNETFrameworkLib Include="$(MSBuildThisFileDirectory)\lib\*.dll"
+ Exclude="@(_NETStandardLibraryNETFrameworkLib->'$(MSBuildThisFileDirectory)\ref\%(FileName).dll')" />
</ItemGroup>
- <Import Project="..\$(MSBuildThisFileName).common.targets" />
+ <Import Project="..\$(MSBuildThisFileName).common.targets" Condition="'$(ImportedNETStandardLibraryNETFrameworkCommonTargets)' != 'true'" />
</Project>
diff --git a/pkg/NETStandard.Library.NETFramework/targets/net462/NETStandard.Library.NETFramework.targets b/pkg/NETStandard.Library.NETFramework/targets/net462/NETStandard.Library.NETFramework.targets
index f895bdb42b..2d0419841b 100644
--- a/pkg/NETStandard.Library.NETFramework/targets/net462/NETStandard.Library.NETFramework.targets
+++ b/pkg/NETStandard.Library.NETFramework/targets/net462/NETStandard.Library.NETFramework.targets
@@ -1,12 +1,12 @@
<Project xmlns="http://schemas.microsoft.com/developer/msbuild/2003">
<ItemGroup Condition="'$(ImplicitlyExpandNETStandardFacades)' == 'true'">
- <_NETStandardLibraryNETFrameworkReference Include="$(MSBuildThisFileDirectory)\ref\*.dll"
- Exclude="@(_NETStandardLibraryNETFrameworkReference->'$(MSBuildThisFileDirectory)\ref\%(FileName).dll'" />
+ <_NETStandardLibraryNETFrameworkReference Include="$(MSBuildThisFileDirectory)\ref\*.dll"
+ Exclude="@(_NETStandardLibraryNETFrameworkReference->'$(MSBuildThisFileDirectory)\ref\%(FileName).dll')" />
- <_NETStandardLibraryNETFrameworkLib Include="$(MSBuildThisFileDirectory)\lib\*.dll"
- Exclude="@(_NETStandardLibraryNETFrameworkLib->'$(MSBuildThisFileDirectory)\ref\%(FileName).dll'" />
+ <_NETStandardLibraryNETFrameworkLib Include="$(MSBuildThisFileDirectory)\lib\*.dll"
+ Exclude="@(_NETStandardLibraryNETFrameworkLib->'$(MSBuildThisFileDirectory)\ref\%(FileName).dll')" />
</ItemGroup>
<Import Project="..\net461\$(MSBuildThisFile)" />
- <Import Project="..\$(MSBuildThisFileName).common.targets" />
+ <Import Project="..\$(MSBuildThisFileName).common.targets" Condition="'$(ImportedNETStandardLibraryNETFrameworkCommonTargets)' != 'true'" />
</Project>
diff --git a/pkg/NETStandard.Library.NETFramework/targets/net47/NETStandard.Library.NETFramework.targets b/pkg/NETStandard.Library.NETFramework/targets/net47/NETStandard.Library.NETFramework.targets
index 9282977714..a27d071d79 100644
--- a/pkg/NETStandard.Library.NETFramework/targets/net47/NETStandard.Library.NETFramework.targets
+++ b/pkg/NETStandard.Library.NETFramework/targets/net47/NETStandard.Library.NETFramework.targets
@@ -1,12 +1,12 @@
<Project xmlns="http://schemas.microsoft.com/developer/msbuild/2003">
<ItemGroup Condition="'$(ImplicitlyExpandNETStandardFacades)' == 'true'">
- <_NETStandardLibraryNETFrameworkReference Include="$(MSBuildThisFileDirectory)\ref\*.dll"
- Exclude="@(_NETStandardLibraryNETFrameworkReference->'$(MSBuildThisFileDirectory)\ref\%(FileName).dll'" />
+ <_NETStandardLibraryNETFrameworkReference Include="$(MSBuildThisFileDirectory)\ref\*.dll"
+ Exclude="@(_NETStandardLibraryNETFrameworkReference->'$(MSBuildThisFileDirectory)\ref\%(FileName).dll')" />
- <_NETStandardLibraryNETFrameworkLib Include="$(MSBuildThisFileDirectory)\lib\*.dll"
- Exclude="@(_NETStandardLibraryNETFrameworkLib->'$(MSBuildThisFileDirectory)\ref\%(FileName).dll'" />
+ <_NETStandardLibraryNETFrameworkLib Include="$(MSBuildThisFileDirectory)\lib\*.dll"
+ Exclude="@(_NETStandardLibraryNETFrameworkLib->'$(MSBuildThisFileDirectory)\ref\%(FileName).dll')" />
</ItemGroup>
<Import Project="..\net462\$(MSBuildThisFile)" />
- <Import Project="..\$(MSBuildThisFileName).common.targets" />
+ <Import Project="..\$(MSBuildThisFileName).common.targets" Condition="'$(ImportedNETStandardLibraryNETFrameworkCommonTargets)' != 'true'" />
</Project>
diff --git a/pkg/frameworkPackage.targets b/pkg/frameworkPackage.targets
index a775cb74b4..c2df42f615 100644
--- a/pkg/frameworkPackage.targets
+++ b/pkg/frameworkPackage.targets
@@ -17,6 +17,7 @@
<LibFileTargetPath Condition="'$(LibFileTargetPath)' == '' AND '$(PackageTargetRuntime)' != ''">runtimes/$(PackageTargetRuntime)/lib/$(TargetFramework)</LibFileTargetPath>
<NativeFileTargetPath Condition="'$(NativeFileTargetPath)' == '' AND '$(PackageTargetRuntime)' != ''">runtimes/$(PackageTargetRuntime)/native</NativeFileTargetPath>
+ <NativeBinDir Condition="'$(PackageTargetRuntimeSuffix)' == 'aot'">$(NativeBinDir)_aot</NativeBinDir>
</PropertyGroup>
<!-- Bring in ref content from binplaced ref props -->
@@ -53,7 +54,7 @@
<!-- force a missing file if native build is absent -->
<NativeFile Include="$(NativeBinDir)/MISSING_NATIVE_BUILD" Condition="'@(NativeFile)' == ''" />
</ItemGroup>
-
+
<Target Name="_CheckForFiles">
<Error Condition="'$(IncludeReferenceFiles)' == 'true' AND '@(RefFile)' == ''"
Text="IncludeReferenceFiles was specified but no file props were found in '$(RefBinDir)'" />
@@ -62,7 +63,7 @@
<Error Condition="'$(IncludeNativeFiles)' == 'true' AND '@(NativeFile)' == ''"
Text="IncludeNativeFiles was specified but no files were found in '$(NativeBinDir)'" />
</Target>
-
+
<Target Name="IncludeFiles">
<PropertyGroup>
<_projectDirLength>$(ProjectDir.Length)</_projectDirLength>
@@ -73,7 +74,7 @@
<File Include="@(RefFile)">
<TargetPath Condition="'%(RefFile.TargetPath)' == ''">$(RefFileTargetPath)%(RefFile.SubFolder)</TargetPath>
</File>
-
+
<!-- Include lib -->
<File Include="@(LibFile)">
<TargetPath Condition="'%(LibFile.TargetPath)' == '' ">$(LibFileTargetPath)%(LibFile.SubFolder)</TargetPath>
@@ -106,8 +107,8 @@
</ItemGroup>
</Target>
- <Target Name="VerifyClosure"
- DependsOnTargets="GetClosureFiles"
+ <Target Name="VerifyClosure"
+ DependsOnTargets="GetClosureFiles"
AfterTargets="Build"
Inputs="%(ClosureFile.FileSet)"
Outputs="batching-on-FileSet-metadata">
@@ -126,15 +127,21 @@
</Target>
- <Target Name="VerifyDuplicateTypes"
- DependsOnTargets="GetClosureFiles"
+ <Target Name="VerifyDuplicateTypes"
+ DependsOnTargets="GetClosureFiles"
AfterTargets="Build"
Inputs="%(ClosureFile.FileSet)"
Outputs="batching-on-FileSet-metadata">
+ <PropertyGroup>
+ <_fileSet>%(ClosureFile.FileSet)</_fileSet>
+ </PropertyGroup>
<ItemGroup>
<_dupTypeFileName Include="@(ClosureFile->'%(FileName)')">
<Original>%(Identity)</Original>
</_dupTypeFileName>
+ <_dupTypeFileName Include="@(FrameworkClosureFile->'%(FileName)')" Exclude="@(_dupTypeFileName)" Condition="'$(_fileSet)' == '%(FrameworkClosureFile.FileSet)'">
+ <Original>%(Identity)</Original>
+ </_dupTypeFileName>
<_dupTypeFileNamesFiltered Include="@(_dupTypeFileName)" Exclude="@(ExcludeFromDuplicateTypes)"/>
<_dupTypeFileFiltered Include="@(_dupTypeFileNamesFiltered->'%(Original)')"/>
</ItemGroup>
@@ -145,8 +152,8 @@
</Target>
- <Target Name="VerifyNETStandard"
- DependsOnTargets="GetClosureFiles"
+ <Target Name="VerifyNETStandard"
+ DependsOnTargets="GetClosureFiles"
AfterTargets="Build"
Inputs="%(ClosureFile.FileSet)"
Outputs="batching-on-FileSet-metadata">
diff --git a/src/Common/src/Interop/Unix/System.Net.Http.Native/Interop.VersionInfo.cs b/src/Common/src/Interop/Unix/System.Net.Http.Native/Interop.VersionInfo.cs
index 09a6004355..1899fd0af3 100644
--- a/src/Common/src/Interop/Unix/System.Net.Http.Native/Interop.VersionInfo.cs
+++ b/src/Common/src/Interop/Unix/System.Net.Http.Native/Interop.VersionInfo.cs
@@ -49,5 +49,6 @@ internal static partial class Interop
internal const string OpenSsl10Description = "openssl/1.0";
internal const string SecureTransportDescription = "SecureTransport";
+ internal const string LibreSslDescription = "LibreSSL";
}
}
diff --git a/src/Common/src/Interop/Unix/System.Security.Cryptography.Native/Interop.OpenSsl.cs b/src/Common/src/Interop/Unix/System.Security.Cryptography.Native/Interop.OpenSsl.cs
index 63daeafc8b..5ac8a42b59 100644
--- a/src/Common/src/Interop/Unix/System.Security.Cryptography.Native/Interop.OpenSsl.cs
+++ b/src/Common/src/Interop/Unix/System.Security.Cryptography.Native/Interop.OpenSsl.cs
@@ -50,9 +50,10 @@ internal static partial class Interop
{
SafeSslHandle context = null;
- IntPtr method = GetSslMethod(protocols);
-
- using (SafeSslContextHandle innerContext = Ssl.SslCtxCreate(method))
+ // Always use SSLv23_method, regardless of protocols. It supports negotiating to the highest
+ // mutually supported version and can thus handle any of the set protocols, and we then use
+ // SetProtocolOptions to ensure we only allow the ones requested.
+ using (SafeSslContextHandle innerContext = Ssl.SslCtxCreate(Ssl.SslMethods.SSLv23_method))
{
if (innerContext.IsInvalid)
{
@@ -309,54 +310,6 @@ internal static partial class Interop
bindingHandle.SetCertHashLength(certHashLength);
}
- private static IntPtr GetSslMethod(SslProtocols protocols)
- {
-#pragma warning disable 0618 // Ssl2, Ssl3 are deprecated.
- bool ssl2 = (protocols & SslProtocols.Ssl2) == SslProtocols.Ssl2;
- bool ssl3 = (protocols & SslProtocols.Ssl3) == SslProtocols.Ssl3;
-#pragma warning restore
- bool tls10 = (protocols & SslProtocols.Tls) == SslProtocols.Tls;
- bool tls11 = (protocols & SslProtocols.Tls11) == SslProtocols.Tls11;
- bool tls12 = (protocols & SslProtocols.Tls12) == SslProtocols.Tls12;
-
- IntPtr method = Ssl.SslMethods.SSLv23_method; // default
- string methodName = "SSLv23_method";
-
- if (!ssl2)
- {
- if (!ssl3)
- {
- if (!tls11 && !tls12)
- {
- method = Ssl.SslMethods.TLSv1_method;
- methodName = "TLSv1_method";
- }
- else if (!tls10 && !tls12)
- {
- method = Ssl.SslMethods.TLSv1_1_method;
- methodName = "TLSv1_1_method";
- }
- else if (!tls10 && !tls11)
- {
- method = Ssl.SslMethods.TLSv1_2_method;
- methodName = "TLSv1_2_method";
- }
- }
- else if (!tls10 && !tls11 && !tls12)
- {
- method = Ssl.SslMethods.SSLv3_method;
- methodName = "SSLv3_method";
- }
- }
-
- if (IntPtr.Zero == method)
- {
- throw new SslException(SR.Format(SR.net_get_ssl_method_failed, methodName));
- }
-
- return method;
- }
-
private static int VerifyClientCertificate(int preverify_ok, IntPtr x509_ctx_ptr)
{
// Full validation is handled after the handshake in VerifyCertificateProperties and the
diff --git a/src/Common/src/Interop/Unix/System.Security.Cryptography.Native/Interop.Ssl.cs b/src/Common/src/Interop/Unix/System.Security.Cryptography.Native/Interop.Ssl.cs
index 876bbd9ff8..c468e1a34a 100644
--- a/src/Common/src/Interop/Unix/System.Security.Cryptography.Native/Interop.Ssl.cs
+++ b/src/Common/src/Interop/Unix/System.Security.Cryptography.Native/Interop.Ssl.cs
@@ -20,18 +20,6 @@ internal static partial class Interop
[DllImport(Libraries.CryptoNative, EntryPoint = "CryptoNative_SslV2_3Method")]
internal static extern IntPtr SslV2_3Method();
- [DllImport(Libraries.CryptoNative, EntryPoint = "CryptoNative_SslV3Method")]
- internal static extern IntPtr SslV3Method();
-
- [DllImport(Libraries.CryptoNative, EntryPoint = "CryptoNative_TlsV1Method")]
- internal static extern IntPtr TlsV1Method();
-
- [DllImport(Libraries.CryptoNative, EntryPoint = "CryptoNative_TlsV1_1Method")]
- internal static extern IntPtr TlsV1_1Method();
-
- [DllImport(Libraries.CryptoNative, EntryPoint = "CryptoNative_TlsV1_2Method")]
- internal static extern IntPtr TlsV1_2Method();
-
[DllImport(Libraries.CryptoNative, EntryPoint = "CryptoNative_SslCreate")]
internal static extern SafeSslHandle SslCreate(SafeSslContextHandle ctx);
@@ -157,10 +145,6 @@ internal static partial class Interop
internal static class SslMethods
{
- internal static readonly IntPtr TLSv1_method = TlsV1Method();
- internal static readonly IntPtr TLSv1_1_method = TlsV1_1Method();
- internal static readonly IntPtr TLSv1_2_method = TlsV1_2Method();
- internal static readonly IntPtr SSLv3_method = SslV3Method();
internal static readonly IntPtr SSLv23_method = SslV2_3Method();
}
diff --git a/src/Common/src/Interop/Unix/System.Security.Cryptography.Native/Interop.X509.cs b/src/Common/src/Interop/Unix/System.Security.Cryptography.Native/Interop.X509.cs
index b64db05b81..c7f88e63d5 100644
--- a/src/Common/src/Interop/Unix/System.Security.Cryptography.Native/Interop.X509.cs
+++ b/src/Common/src/Interop/Unix/System.Security.Cryptography.Native/Interop.X509.cs
@@ -176,6 +176,7 @@ internal static partial class Interop
X509_V_ERR_UNABLE_TO_GET_ISSUER_CERT = 2,
X509_V_ERR_UNABLE_TO_GET_CRL = 3,
X509_V_ERR_UNABLE_TO_DECRYPT_CRL_SIGNATURE = 5,
+ X509_V_ERR_UNABLE_TO_DECODE_ISSUER_PUBLIC_KEY = 6,
X509_V_ERR_CERT_SIGNATURE_FAILURE = 7,
X509_V_ERR_CRL_SIGNATURE_FAILURE = 8,
X509_V_ERR_CERT_NOT_YET_VALID = 9,
diff --git a/src/Common/src/Interop/Windows/NtDll/Interop.NtQueryInformationProcess.cs b/src/Common/src/Interop/Windows/NtDll/Interop.NtQueryInformationProcess.cs
deleted file mode 100644
index 0b7cb53093..0000000000
--- a/src/Common/src/Interop/Windows/NtDll/Interop.NtQueryInformationProcess.cs
+++ /dev/null
@@ -1,29 +0,0 @@
-// Licensed to the .NET Foundation under one or more agreements.
-// The .NET Foundation licenses this file to you under the MIT license.
-// See the LICENSE file in the project root for more information.
-
-using Microsoft.Win32.SafeHandles;
-using System;
-using System.Runtime.InteropServices;
-
-internal partial class Interop
-{
- internal partial class NtDll
- {
- [DllImport(Libraries.NtDll)]
- internal static extern int NtQueryInformationProcess(SafeProcessHandle processHandle, int query, NtProcessBasicInfo info, int size, int[] returnedSize);
-
- [StructLayout(LayoutKind.Sequential)]
- internal class NtProcessBasicInfo
- {
- internal int ExitStatus = 0;
- internal IntPtr PebBaseAddress = (IntPtr)0;
- internal IntPtr AffinityMask = (IntPtr)0;
- internal int BasePriority = 0;
- internal IntPtr UniqueProcessId = (IntPtr)0;
- internal IntPtr InheritedFromUniqueProcessId = (IntPtr)0;
- }
-
- internal const int NtQueryProcessBasicInfo = 0;
- }
-}
diff --git a/src/Common/src/Interop/Windows/kernel32/Interop.CheckTokenMembershipEx.cs b/src/Common/src/Interop/Windows/kernel32/Interop.CheckTokenMembershipEx.cs
new file mode 100644
index 0000000000..2a3d3820fc
--- /dev/null
+++ b/src/Common/src/Interop/Windows/kernel32/Interop.CheckTokenMembershipEx.cs
@@ -0,0 +1,18 @@
+// Licensed to the .NET Foundation under one or more agreements.
+// The .NET Foundation licenses this file to you under the MIT license.
+// See the LICENSE file in the project root for more information.
+
+using Microsoft.Win32.SafeHandles;
+using System;
+using System.Runtime.InteropServices;
+
+internal static partial class Interop
+{
+ internal static partial class Kernel32
+ {
+ internal const uint CTMF_INCLUDE_APPCONTAINER = 0x00000001;
+
+ [DllImport(Interop.Libraries.Kernel32, SetLastError = true)]
+ internal static extern bool CheckTokenMembershipEx(SafeAccessTokenHandle TokenHandle, byte[] SidToCheck, uint Flags, ref bool IsMember);
+ }
+}
diff --git a/src/Common/src/Interop/Windows/kernel32/Interop.GetProcessId.cs b/src/Common/src/Interop/Windows/kernel32/Interop.GetProcessId.cs
new file mode 100644
index 0000000000..c7317fb14b
--- /dev/null
+++ b/src/Common/src/Interop/Windows/kernel32/Interop.GetProcessId.cs
@@ -0,0 +1,15 @@
+// Licensed to the .NET Foundation under one or more agreements.
+// The .NET Foundation licenses this file to you under the MIT license.
+// See the LICENSE file in the project root for more information.
+
+using Microsoft.Win32.SafeHandles;
+using System.Runtime.InteropServices;
+
+internal partial class Interop
+{
+ internal partial class Kernel32
+ {
+ [DllImport(Libraries.Kernel32)]
+ public static extern int GetProcessId(SafeProcessHandle nativeHandle);
+ }
+}
diff --git a/src/Common/src/Interop/Windows/kernel32/Interop.SafeCreateFile.cs b/src/Common/src/Interop/Windows/kernel32/Interop.SafeCreateFile.cs
index d9e1b55bb2..78f382cc01 100644
--- a/src/Common/src/Interop/Windows/kernel32/Interop.SafeCreateFile.cs
+++ b/src/Common/src/Interop/Windows/kernel32/Interop.SafeCreateFile.cs
@@ -10,8 +10,6 @@ internal partial class Interop
{
internal partial class Kernel32
{
- internal static readonly IntPtr INVALID_HANDLE_VALUE = new IntPtr(-1); // WinBase.h
-
/// <summary>
/// Does not allow access to non-file devices. This disallows DOS devices like "con:", "com1:",
/// "lpt1:", etc. Use this to avoid security problems, like allowing a web client asking a server
diff --git a/src/Common/src/System/CharArrayHelpers.cs b/src/Common/src/System/CharArrayHelpers.cs
index cb670ad2ce..98f67f3997 100644
--- a/src/Common/src/System/CharArrayHelpers.cs
+++ b/src/Common/src/System/CharArrayHelpers.cs
@@ -10,7 +10,7 @@ namespace System
{
internal static bool EqualsOrdinal(string left, char[] right, int rightStartIndex, int rightLength)
{
- Debug.Assert(left != null);
+ Debug.Assert(left != null, "Expected non-null string");
DebugAssertArrayInputs(right, rightStartIndex, rightLength);
if (left.Length != rightLength)
@@ -31,7 +31,7 @@ namespace System
internal static bool EqualsOrdinalAsciiIgnoreCase(string left, char[] right, int rightStartIndex, int rightLength)
{
- Debug.Assert(left != null);
+ Debug.Assert(left != null, "Expected non-null string");
DebugAssertArrayInputs(right, rightStartIndex, rightLength);
if (left.Length != rightLength)
@@ -83,10 +83,10 @@ namespace System
[Conditional("DEBUG")]
internal static void DebugAssertArrayInputs(char[] array, int startIndex, int length)
{
- Debug.Assert(array != null);
- Debug.Assert(startIndex >= 0);
- Debug.Assert(length >= 0);
- Debug.Assert(startIndex <= array.Length - length);
+ Debug.Assert(array != null, "Null array");
+ Debug.Assert(startIndex >= 0, $"Expected {nameof(startIndex)} to be >= 0, got {startIndex}");
+ Debug.Assert(length >= 0, $"Expected {nameof(length)} to be >= 0, got {length}");
+ Debug.Assert(startIndex <= array.Length - length, $"Expected {startIndex} to be <= {array.Length} - {length}, got {startIndex}");
}
}
}
diff --git a/src/Common/src/System/Collections/Generic/EnumerableHelpers.Linq.cs b/src/Common/src/System/Collections/Generic/EnumerableHelpers.Linq.cs
index 6969505ea7..75760ed4de 100644
--- a/src/Common/src/System/Collections/Generic/EnumerableHelpers.Linq.cs
+++ b/src/Common/src/System/Collections/Generic/EnumerableHelpers.Linq.cs
@@ -23,18 +23,15 @@ namespace System.Collections.Generic
{
Debug.Assert(source != null);
- var collection = source as ICollection<T>;
- if (collection != null)
+ if (source is ICollection<T> collection)
{
count = collection.Count;
return true;
}
- var provider = source as IIListProvider<T>;
- if (provider != null)
+ if (source is IIListProvider<T> provider)
{
- count = provider.GetCount(onlyIfCheap: true);
- return count >= 0;
+ return (count = provider.GetCount(onlyIfCheap: true)) >= 0;
}
count = -1;
diff --git a/src/Common/src/System/Collections/Generic/EnumerableHelpers.cs b/src/Common/src/System/Collections/Generic/EnumerableHelpers.cs
index 6b0da4ba5b..72f8ef8141 100644
--- a/src/Common/src/System/Collections/Generic/EnumerableHelpers.cs
+++ b/src/Common/src/System/Collections/Generic/EnumerableHelpers.cs
@@ -26,8 +26,7 @@ namespace System.Collections.Generic
Debug.Assert(count >= 0);
Debug.Assert(array?.Length - arrayIndex >= count);
- var collection = source as ICollection<T>;
- if (collection != null)
+ if (source is ICollection<T> collection)
{
Debug.Assert(collection.Count == count);
collection.CopyTo(array, arrayIndex);
@@ -68,8 +67,7 @@ namespace System.Collections.Generic
{
Debug.Assert(source != null);
- var collection = source as ICollection<T>;
- if (collection != null)
+ if (source is ICollection<T> collection)
{
int count = collection.Count;
if (count == 0)
@@ -96,8 +94,7 @@ namespace System.Collections.Generic
/// </returns>
internal static T[] ToArray<T>(IEnumerable<T> source, out int length)
{
- ICollection<T> ic = source as ICollection<T>;
- if (ic != null)
+ if (source is ICollection<T> ic)
{
int count = ic.Count;
if (count != 0)
diff --git a/src/Common/src/System/Collections/Generic/LargeArrayBuilder.cs b/src/Common/src/System/Collections/Generic/LargeArrayBuilder.cs
index 3be1d5de88..fd17c34b10 100644
--- a/src/Common/src/System/Collections/Generic/LargeArrayBuilder.cs
+++ b/src/Common/src/System/Collections/Generic/LargeArrayBuilder.cs
@@ -266,8 +266,7 @@ namespace System.Collections.Generic
/// </summary>
public T[] ToArray()
{
- T[] array;
- if (TryMove(out array))
+ if (TryMove(out T[] array))
{
// No resizing to do.
return array;
diff --git a/src/Common/src/System/Data/Common/AdapterUtil.cs b/src/Common/src/System/Data/Common/AdapterUtil.cs
index 7e88739026..2da62fd3e7 100644
--- a/src/Common/src/System/Data/Common/AdapterUtil.cs
+++ b/src/Common/src/System/Data/Common/AdapterUtil.cs
@@ -11,6 +11,7 @@ using System.Security;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
+using System.Transactions;
namespace System.Data.Common
{
@@ -428,5 +429,13 @@ namespace System.Data.Common
{
return ArgumentOutOfRange(SR.ADP_InvalidSeekOrigin, parameterName);
}
+
+ internal static readonly bool IsWindowsNT = (PlatformID.Win32NT == Environment.OSVersion.Platform);
+ internal static readonly bool IsPlatformNT5 = (ADP.IsWindowsNT && (Environment.OSVersion.Version.Major >= 5));
+
+ internal static void SetCurrentTransaction(Transaction transaction)
+ {
+ Transaction.Current = transaction;
+ }
}
} \ No newline at end of file
diff --git a/src/Common/src/System/IO/PathInternal.Unix.cs b/src/Common/src/System/IO/PathInternal.Unix.cs
index ccf1069a28..06af7cb5f6 100644
--- a/src/Common/src/System/IO/PathInternal.Unix.cs
+++ b/src/Common/src/System/IO/PathInternal.Unix.cs
@@ -39,22 +39,6 @@ namespace System.IO
}
/// <summary>
- /// Returns true if the path is too long
- /// </summary>
- internal static bool IsPathTooLong(string fullPath)
- {
- return fullPath.Length >= Interop.Sys.MaxPath;
- }
-
- /// <summary>
- /// Returns true if the directory is too long
- /// </summary>
- internal static bool IsDirectoryTooLong(string fullPath)
- {
- return fullPath.Length >= Interop.Sys.MaxPath;
- }
-
- /// <summary>
/// Normalize separators in the given path. Compresses forward slash runs.
/// </summary>
internal static string NormalizeDirectorySeparators(string path)
diff --git a/src/Common/src/System/IO/PathInternal.Windows.cs b/src/Common/src/System/IO/PathInternal.Windows.cs
index f98062bb45..d29835b64b 100644
--- a/src/Common/src/System/IO/PathInternal.Windows.cs
+++ b/src/Common/src/System/IO/PathInternal.Windows.cs
@@ -83,24 +83,6 @@ namespace System.IO
}
/// <summary>
- /// Returns true if the path is too long
- /// </summary>
- internal static bool IsPathTooLong(string fullPath)
- {
- // We'll never know precisely what will fail as paths get changed internally in Windows and
- // may grow to exceed MaxLongPath.
- return fullPath.Length >= MaxLongPath;
- }
-
- /// <summary>
- /// Returns true if the directory is too long
- /// </summary>
- internal static bool IsDirectoryTooLong(string fullPath)
- {
- return IsPathTooLong(fullPath);
- }
-
- /// <summary>
/// Adds the extended path prefix (\\?\) if not already a device path, IF the path is not relative,
/// AND the path is more than 259 characters. (> MAX_PATH + null)
/// </summary>
diff --git a/src/System.Numerics.Vectors/src/System/MathF.cs b/src/Common/src/System/MathF.netstandard.cs
index d3eaa4b126..7f80ee7f85 100644
--- a/src/System.Numerics.Vectors/src/System/MathF.cs
+++ b/src/Common/src/System/MathF.netstandard.cs
@@ -6,6 +6,7 @@ using System.Runtime.CompilerServices;
namespace System
{
+ // MathF emulation on platforms which don't support it natively.
internal static class MathF
{
public const float PI = (float)Math.PI;
@@ -35,6 +36,12 @@ namespace System
}
[MethodImpl(MethodImplOptions.AggressiveInlining)]
+ public static float Pow(float x, float y)
+ {
+ return (float)Math.Pow(x, y);
+ }
+
+ [MethodImpl(MethodImplOptions.AggressiveInlining)]
public static float Sin(float x)
{
return (float)Math.Sin(x);
diff --git a/src/Common/src/System/Net/CompletionPortHelper.Uap.cs b/src/Common/src/System/Net/CompletionPortHelper.Uap.cs
deleted file mode 100644
index aac501ccb3..0000000000
--- a/src/Common/src/System/Net/CompletionPortHelper.Uap.cs
+++ /dev/null
@@ -1,19 +0,0 @@
-// Licensed to the .NET Foundation under one or more agreements.
-// The .NET Foundation licenses this file to you under the MIT license.
-// See the LICENSE file in the project root for more information.
-
-using System.Runtime.InteropServices;
-
-namespace System.Net.Sockets
-{
- internal static class CompletionPortHelper
- {
- internal static bool SkipCompletionPortOnSuccess(SafeHandle handle)
- {
- // SetFileCompletionNotificationModes is not supported on UAP.
- return false;
- }
-
- internal static readonly bool PlatformHasUdpIssue = false;
- }
-}
diff --git a/src/Common/src/System/Net/ContextAwareResult.Uap.cs b/src/Common/src/System/Net/ContextAwareResult.Uap.cs
deleted file mode 100644
index 19e6ed5522..0000000000
--- a/src/Common/src/System/Net/ContextAwareResult.Uap.cs
+++ /dev/null
@@ -1,19 +0,0 @@
-// Licensed to the .NET Foundation under one or more agreements.
-// The .NET Foundation licenses this file to you under the MIT license.
-// See the LICENSE file in the project root for more information.
-
-namespace System.Net
-{
- partial class ContextAwareResult
- {
- private void SafeCaptureIdentity()
- {
- // WindowsIdentity is not supported on UAP
- }
-
- private void CleanupInternal()
- {
- // Nothing to cleanup
- }
- }
-}
diff --git a/src/Common/src/System/Net/CookieParser.cs b/src/Common/src/System/Net/CookieParser.cs
index de73508ca0..e6fdd7eb98 100644
--- a/src/Common/src/System/Net/CookieParser.cs
+++ b/src/Common/src/System/Net/CookieParser.cs
@@ -557,6 +557,7 @@ namespace System.Net
{
if (s_internalSetNameMethod == null)
{
+ // TODO: #13607
// We need to use Cookie.InternalSetName instead of the Cookie.set_Name wrapped in a try catch block, as
// Cookie.set_Name keeps the original name if the string is empty or null.
// Unfortunately this API is internal so we use reflection to access it. The method is cached for performance reasons.
@@ -583,7 +584,14 @@ namespace System.Net
{
if (s_isQuotedDomainField == null)
{
- FieldInfo field = typeof(Cookie).GetField("IsQuotedDomain", BindingFlags.NonPublic | BindingFlags.Instance);
+ // TODO: #13607
+ BindingFlags flags = BindingFlags.Instance;
+#if uap
+ flags |= BindingFlags.Public;
+#else
+ flags |= BindingFlags.NonPublic;
+#endif
+ FieldInfo field = typeof(Cookie).GetField("IsQuotedDomain", flags);
Debug.Assert(field != null, "We need to use an internal field named IsQuotedDomain that is declared on Cookie.");
s_isQuotedDomainField = field;
}
@@ -599,7 +607,14 @@ namespace System.Net
{
if (s_isQuotedVersionField == null)
{
- FieldInfo field = typeof(Cookie).GetField("IsQuotedVersion", BindingFlags.NonPublic | BindingFlags.Instance);
+ // TODO: #13607
+ BindingFlags flags = BindingFlags.Instance;
+#if uap
+ flags |= BindingFlags.Public;
+#else
+ flags |= BindingFlags.NonPublic;
+#endif
+ FieldInfo field = typeof(Cookie).GetField("IsQuotedVersion", flags);
Debug.Assert(field != null, "We need to use an internal field named IsQuotedVersion that is declared on Cookie.");
s_isQuotedVersionField = field;
}
diff --git a/src/Common/src/System/Net/Security/CertificateHelper.Uap.cs b/src/Common/src/System/Net/Security/CertificateHelper.Uap.cs
new file mode 100644
index 0000000000..28bcfce003
--- /dev/null
+++ b/src/Common/src/System/Net/Security/CertificateHelper.Uap.cs
@@ -0,0 +1,60 @@
+// Licensed to the .NET Foundation under one or more agreements.
+// The .NET Foundation licenses this file to you under the MIT license.
+// See the LICENSE file in the project root for more information.
+
+using System.Collections.Generic;
+using System.Runtime.InteropServices.WindowsRuntime;
+using System.Security.Cryptography.X509Certificates;
+using System.Threading.Tasks;
+
+using RTCertificate = Windows.Security.Cryptography.Certificates.Certificate;
+using RTCertificateQuery = Windows.Security.Cryptography.Certificates.CertificateQuery;
+using RTCertificateStores = Windows.Security.Cryptography.Certificates.CertificateStores;
+using RTIBuffer = Windows.Storage.Streams.IBuffer;
+
+namespace System.Net.Security
+{
+ internal static partial class CertificateHelper
+ {
+ // There are currently only two ways to convert a .NET X509Certificate2 object into a WinRT Certificate without
+ // losing its private keys, each with its own limitations:
+ //
+ // (1) Using the X509Certificate2.Export method with PKCS12/PFX to obtain a byte[] representation (including private
+ // keys) that can then be passed into the IBuffer-based WinRT Certificate constructor. Unfortunately, the
+ // X509Certificate2.Export operation will only succeed if the app-provided X509Certificate2 object was created
+ // with the non-default X509KeyStorageFlags.Exportable flag.
+ //
+ // (2) Going through the certificate store. That is, retrieving the certificate represented by the X509Certificate2
+ // object as a WinRT Certificate via WinRT CertificateStores APIs. Of course, this requires the certificate to
+ // have been added to a certificate store in the first place.
+ //
+ // Furthermore, WinRT WebSockets only support certificates that have been added to the personal certificate store
+ // (i.e., "MY" store) due to other WinRT-specific private key limitations. With that in mind, approach (2) is the
+ // most appropriate for our needs, as it guarantees that WinRT WebSockets will be able to handle the resulting
+ // WinRT Certificate during ConnectAsync.
+ internal static async Task<RTCertificate> ConvertDotNetClientCertToWinRtClientCertAsync(X509Certificate2 dotNetCertificate)
+ {
+ var query = new RTCertificateQuery
+ {
+ Thumbprint = dotNetCertificate.GetCertHash(),
+ IncludeDuplicates = false,
+ StoreName = "MY"
+ };
+
+ IReadOnlyList<RTCertificate> certificates = await RTCertificateStores.FindAllAsync(query).AsTask().ConfigureAwait(false);
+ if (certificates.Count > 0)
+ {
+ return certificates[0];
+ }
+
+ return null;
+ }
+
+ internal static X509Certificate2 ConvertPublicKeyCertificate(RTCertificate cert)
+ {
+ // Convert Windows X509v2 cert to .NET X509v2 cert.
+ RTIBuffer blob = cert.GetCertificateBlob();
+ return new X509Certificate2(blob.ToArray());
+ }
+ }
+}
diff --git a/src/Common/src/System/Net/Security/CertificateHelper.Windows.cs b/src/Common/src/System/Net/Security/CertificateHelper.Windows.cs
new file mode 100644
index 0000000000..dd89e581c9
--- /dev/null
+++ b/src/Common/src/System/Net/Security/CertificateHelper.Windows.cs
@@ -0,0 +1,27 @@
+// Licensed to the .NET Foundation under one or more agreements.
+// The .NET Foundation licenses this file to you under the MIT license.
+// See the LICENSE file in the project root for more information.
+
+using Microsoft.Win32.SafeHandles;
+using System.Diagnostics;
+using System.Globalization;
+using System.Security.Cryptography.X509Certificates;
+
+namespace System.Net.Security
+{
+ internal static partial class CertificateHelper
+ {
+ internal static X509Certificate2 GetEligibleClientCertificate()
+ {
+ // Get initial list of client certificates from the MY store.
+ X509Certificate2Collection candidateCerts;
+ using (var myStore = new X509Store(StoreName.My, StoreLocation.CurrentUser))
+ {
+ myStore.Open(OpenFlags.OpenExistingOnly | OpenFlags.ReadOnly);
+ candidateCerts = myStore.Certificates;
+ }
+
+ return GetEligibleClientCertificate(candidateCerts);
+ }
+ }
+}
diff --git a/src/Common/src/System/Net/Security/CertificateHelper.cs b/src/Common/src/System/Net/Security/CertificateHelper.cs
new file mode 100644
index 0000000000..813677b850
--- /dev/null
+++ b/src/Common/src/System/Net/Security/CertificateHelper.cs
@@ -0,0 +1,71 @@
+// Licensed to the .NET Foundation under one or more agreements.
+// The .NET Foundation licenses this file to you under the MIT license.
+// See the LICENSE file in the project root for more information.
+
+using Microsoft.Win32.SafeHandles;
+using System.Diagnostics;
+using System.Globalization;
+using System.Security.Cryptography.X509Certificates;
+
+namespace System.Net.Security
+{
+ internal static partial class CertificateHelper
+ {
+ private const string ClientAuthenticationOID = "1.3.6.1.5.5.7.3.2";
+
+ internal static X509Certificate2 GetEligibleClientCertificate(X509CertificateCollection candidateCerts)
+ {
+ if (candidateCerts.Count == 0)
+ {
+ return null;
+ }
+
+ var certs = new X509Certificate2Collection();
+ certs.AddRange(candidateCerts);
+
+ return GetEligibleClientCertificate(certs);
+ }
+
+ internal static X509Certificate2 GetEligibleClientCertificate(X509Certificate2Collection candidateCerts)
+ {
+ if (candidateCerts.Count == 0)
+ {
+ return null;
+ }
+
+ // Build a new collection with certs that have a private key. We need to do this manually because there is
+ // no X509FindType to match this criteria.
+ // Find(...) returns a collection of clones instead of a filtered collection, so do this before calling
+ // Find(...) to minimize the number of unnecessary allocations and finalizations.
+ var eligibleCerts = new X509Certificate2Collection();
+ foreach (X509Certificate2 cert in candidateCerts)
+ {
+ if (cert.HasPrivateKey)
+ {
+ eligibleCerts.Add(cert);
+ }
+ }
+
+ // Don't call Find(...) if we don't need to.
+ if (eligibleCerts.Count == 0)
+ {
+ return null;
+ }
+
+ // Reduce the set of certificates to match the proper 'Client Authentication' criteria.
+ // Client EKU is probably more rare than the DigitalSignature KU. Filter by ClientAuthOid first to reduce
+ // the candidate space as quickly as possible.
+ eligibleCerts = eligibleCerts.Find(X509FindType.FindByApplicationPolicy, ClientAuthenticationOID, false);
+ eligibleCerts = eligibleCerts.Find(X509FindType.FindByKeyUsage, X509KeyUsageFlags.DigitalSignature, false);
+
+ if (eligibleCerts.Count > 0)
+ {
+ return eligibleCerts[0];
+ }
+ else
+ {
+ return null;
+ }
+ }
+ }
+}
diff --git a/src/Common/tests/Common.Tests.csproj b/src/Common/tests/Common.Tests.csproj
index aad5077e4e..97970dc36e 100644
--- a/src/Common/tests/Common.Tests.csproj
+++ b/src/Common/tests/Common.Tests.csproj
@@ -57,9 +57,6 @@
<Compile Include="$(CommonPath)\System\Text\ReusableTextReader.cs">
<Link>Common\System\Text\ReusableTextReader.cs</Link>
</Compile>
- <Compile Include="$(CommonTestPath)\System\AssertExtensions.cs">
- <Link>CommonTest\System\AssertExtensions.cs</Link>
- </Compile>
<Compile Include="$(CommonPath)\System\Security\IdentityHelper.cs">
<Link>Common\System\Security\IdentityHelper.cs</Link>
</Compile>
diff --git a/src/Common/tests/System/Collections/IEnumerable.Generic.Serialization.Tests.cs b/src/Common/tests/System/Collections/IEnumerable.Generic.Serialization.Tests.cs
index 682f2b01ce..e435ab1da0 100644
--- a/src/Common/tests/System/Collections/IEnumerable.Generic.Serialization.Tests.cs
+++ b/src/Common/tests/System/Collections/IEnumerable.Generic.Serialization.Tests.cs
@@ -12,7 +12,6 @@ namespace System.Collections.Tests
{
[Theory]
[MemberData(nameof(ValidCollectionSizes))]
- [ActiveIssue(20888, TargetFrameworkMonikers.UapAot)]
public void IGenericSharedAPI_SerializeDeserialize(int count)
{
IEnumerable<T> expected = GenericIEnumerableFactory(count);
diff --git a/src/Common/tests/System/Net/Configuration.Http.cs b/src/Common/tests/System/Net/Configuration.Http.cs
index d340ec09dc..e10cfe7b4c 100644
--- a/src/Common/tests/System/Net/Configuration.Http.cs
+++ b/src/Common/tests/System/Net/Configuration.Http.cs
@@ -39,6 +39,8 @@ namespace System.Net.Test.Common
public static string SelfSignedCertRemoteServer => GetValue("COREFX_HTTPHOST_SELFSIGNEDCERT", "https://self-signed.badssl.com/");
public static string RevokedCertRemoteServer => GetValue("COREFX_HTTPHOST_REVOKEDCERT", "https://revoked.grc.com/");
+ public static string EchoClientCertificateRemoteServer => GetValue("COREFX_HTTPHOST_ECHOCLIENTCERT", "https://corefx-net-tls.azurewebsites.net/EchoClientCertificate.ashx");
+
private const string HttpScheme = "http";
private const string HttpsScheme = "https";
diff --git a/src/Common/tests/System/Net/HttpsTestServer.cs b/src/Common/tests/System/Net/HttpsTestServer.cs
index a378bad91f..83d54da61e 100644
--- a/src/Common/tests/System/Net/HttpsTestServer.cs
+++ b/src/Common/tests/System/Net/HttpsTestServer.cs
@@ -17,18 +17,10 @@ namespace System.Net.Test.Common
public class Options
{
public const string DefaultResponseString =
-@"HTTP/1.1 200 OK
-Connection: close
-
-<html>
-<head>
-<title>Test Server</title>
-</head>
-<body>
-<h1>TLS test server</h1>
-</body>
-</html>
-";
+ "HTTP/1.1 200 OK\r\n" +
+ "Connection: close\r\n" +
+ "\r\n" +
+ "<html><head><title>Test Server</title></head><body><h1>TLS test server</h1></body></html>\r\n";
public IPAddress Address { get; set; } = IPAddress.Loopback;
@@ -99,11 +91,12 @@ Connection: close
{
try
{
- using (TcpClient requestClient = await _listener.AcceptTcpClientAsync().ConfigureAwait(false))
+ using (Socket accepted = await _listener.AcceptSocketAsync().ConfigureAwait(false))
{
_log.WriteLine("[Server] Client connected.");
- using (Stream = new SslStream(requestClient.GetStream(), true, RemoteCertificateCallback))
+ using (NetworkStream ns = new NetworkStream(accepted, ownsSocket: false))
+ using (Stream = new SslStream(ns, false, RemoteCertificateCallback))
{
_log.WriteLine(
"[Server] Authenticating. Protocols = {0}, Certificate = {1}, ClientCertRequired = {2}",
@@ -123,11 +116,13 @@ Connection: close
if (httpConversation == null)
{
- httpConversation = DefaultHttpConversation;
+ httpConversation = DefaultHttpConversation;
}
done = await ProcessHttp(httpConversation).ConfigureAwait(false);
}
+
+ accepted.Shutdown(SocketShutdown.Send);
}
}
catch (IOException ex)
diff --git a/src/Common/tests/System/Net/PlatformDetection.Networking.cs b/src/Common/tests/System/Net/PlatformDetection.Networking.cs
new file mode 100644
index 0000000000..fb96c895df
--- /dev/null
+++ b/src/Common/tests/System/Net/PlatformDetection.Networking.cs
@@ -0,0 +1,14 @@
+// Licensed to the .NET Foundation under one or more agreements.
+// The .NET Foundation licenses this file to you under the MIT license.
+// See the LICENSE file in the project root for more information.
+
+namespace System
+{
+ public static partial class PlatformDetection
+ {
+ // Windows 10 Insider Preview Build 16215 introduced the necessary APIs for the UAP version of
+ // ClientWebSocket.ReceiveAsync to consume partial message data as it arrives, without having to wait
+ // for "end of message" to be signaled.
+ public static bool ClientWebSocketPartialMessagesSupported => !IsUap || IsWindows10InsiderPreviewBuild16215OrGreater;
+ }
+}
diff --git a/src/Common/tests/System/PlatformDetection.cs b/src/Common/tests/System/PlatformDetection.cs
index 4ba727749c..541933d130 100644
--- a/src/Common/tests/System/PlatformDetection.cs
+++ b/src/Common/tests/System/PlatformDetection.cs
@@ -21,6 +21,7 @@ namespace System
public static bool IsUap => IsWinRT || IsNetNative;
public static bool IsFullFramework => RuntimeInformation.FrameworkDescription.StartsWith(".NET Framework", StringComparison.OrdinalIgnoreCase);
public static bool IsNetNative => RuntimeInformation.FrameworkDescription.StartsWith(".NET Native", StringComparison.OrdinalIgnoreCase);
+ public static bool IsNetCore => RuntimeInformation.FrameworkDescription.StartsWith(".NET Core", StringComparison.OrdinalIgnoreCase);
public static bool IsWindows => RuntimeInformation.IsOSPlatform(OSPlatform.Windows);
public static bool IsWindows7 => IsWindows && GetWindowsVersion() == 6 && GetWindowsMinorVersion() == 1;
@@ -36,6 +37,8 @@ namespace System
GetWindowsVersion() == 10 && GetWindowsMinorVersion() == 0 && GetWindowsBuildNumber() >= 14393;
public static bool IsWindows10Version1703OrGreater => IsWindows &&
GetWindowsVersion() == 10 && GetWindowsMinorVersion() == 0 && GetWindowsBuildNumber() >= 15063;
+ public static bool IsWindows10InsiderPreviewBuild16215OrGreater => IsWindows &&
+ GetWindowsVersion() == 10 && GetWindowsMinorVersion() == 0 && GetWindowsBuildNumber() >= 16215;
public static bool IsArmProcess => RuntimeInformation.ProcessArchitecture == Architecture.Arm;
public static bool IsNotArmProcess => !IsArmProcess;
@@ -195,6 +198,10 @@ namespace System
public static bool IsCentos7 => IsDistroAndVersion("centos", "7");
public static bool IsTizen => IsDistroAndVersion("tizen");
+ // If we need this long-term hopefully we can come up with a better detection than the kernel verison.
+ public static bool IsMacOsHighSierra { get; } =
+ IsOSX && RuntimeInformation.OSDescription.StartsWith("Darwin 17.0.0");
+
/// <summary>
/// Get whether the OS platform matches the given Linux distro and optional version.
/// </summary>
diff --git a/src/Common/tests/System/Runtime/Serialization/Formatters/BinaryFormatterHelpers.cs b/src/Common/tests/System/Runtime/Serialization/Formatters/BinaryFormatterHelpers.cs
index e7d0bb1433..51383d4c6c 100644
--- a/src/Common/tests/System/Runtime/Serialization/Formatters/BinaryFormatterHelpers.cs
+++ b/src/Common/tests/System/Runtime/Serialization/Formatters/BinaryFormatterHelpers.cs
@@ -3,6 +3,7 @@
// See the LICENSE file in the project root for more information.
using System.IO;
+using System.Reflection;
using System.Runtime.InteropServices;
using System.Runtime.Serialization.Formatters.Binary;
@@ -71,5 +72,51 @@ namespace System.Runtime.Serialization.Formatters.Tests
}
}
}
+
+ public static void AssertExceptionDeserializationFails<T>() where T : Exception
+ {
+ // .NET Core and .NET Native throw PlatformNotSupportedExceptions when deserializing many exceptions.
+ // The .NET Framework supports full deserialization.
+ if (PlatformDetection.IsFullFramework)
+ {
+ return;
+ }
+
+ // Construct a valid serialization payload. This is necessary as most constructors call
+ // the base constructor before throwing a PlatformNotSupportedException, and the base
+ // constructor validates the SerializationInfo passed.
+ var info = new SerializationInfo(typeof(T), new FormatterConverter());
+ info.AddValue("ClassName", "ClassName");
+ info.AddValue("Message", "Message");
+ info.AddValue("InnerException", null);
+ info.AddValue("HelpURL", null);
+ info.AddValue("StackTraceString", null);
+ info.AddValue("RemoteStackTraceString", null);
+ info.AddValue("RemoteStackIndex", 5);
+ info.AddValue("HResult", 5);
+ info.AddValue("Source", null);
+ info.AddValue("ExceptionMethod", null);
+
+ // Serialization constructors are of the form .ctor(SerializationInfo, StreamingContext).
+ ConstructorInfo constructor = null;
+ foreach (ConstructorInfo c in typeof(T).GetTypeInfo().DeclaredConstructors)
+ {
+ ParameterInfo[] parameters = c.GetParameters();
+ if (parameters.Length == 2 && parameters[0].ParameterType == typeof(SerializationInfo) && parameters[1].ParameterType == typeof(StreamingContext))
+ {
+ constructor = c;
+ break;
+ }
+ };
+
+ // .NET Native prevents reflection on private constructors on non-serializable types.
+ if (constructor == null)
+ {
+ return;
+ }
+
+ Exception ex = Assert.Throws<TargetInvocationException>(() => constructor.Invoke(new object[] { info, new StreamingContext() }));
+ Assert.IsType<PlatformNotSupportedException>(ex.InnerException);
+ }
}
}
diff --git a/src/CoreFx.Private.TestUtilities/ref/CoreFx.Private.TestUtilities.cs b/src/CoreFx.Private.TestUtilities/ref/CoreFx.Private.TestUtilities.cs
index 1f5751cac9..4ccf717e5d 100644
--- a/src/CoreFx.Private.TestUtilities/ref/CoreFx.Private.TestUtilities.cs
+++ b/src/CoreFx.Private.TestUtilities/ref/CoreFx.Private.TestUtilities.cs
@@ -10,6 +10,33 @@ using Xunit;
namespace System
{
+ public static class AssertExtensions
+ {
+ public static void Throws<T>(System.Action action, string message) where T : System.Exception { }
+ public static void Throws<T>(string netCoreParamName, string netFxParamName, Action action) where T : System.ArgumentException { }
+ public static T Throws<T>(string paramName, System.Action action) where T : System.ArgumentException { throw null; }
+ public static T Throws<T>(string paramName, Func<object> testCode) where T : System.ArgumentException { throw null; }
+ public static System.Threading.Tasks.Task<T> ThrowsAsync<T>(string paramName, System.Func<Task> testCode) where T : System.ArgumentException { throw null; }
+ public static void Throws<TNetCoreExceptionType, TNetFxExceptionType>(string paramName, System.Action action)
+ where TNetCoreExceptionType : System.ArgumentException
+ where TNetFxExceptionType : System.ArgumentException
+ { }
+ public static void Throws<TNetCoreExceptionType, TNetFxExceptionType>(string netCoreParamName, string netFxParamName, System.Action action)
+ where TNetCoreExceptionType : System.ArgumentException
+ where TNetFxExceptionType : System.ArgumentException
+ { }
+ public static void ThrowsAny(System.Type firstExceptionType, System.Type secondExceptionType, System.Action action) { }
+ public static void ThrowsAny<TFirstExceptionType, TSecondExceptionType>(System.Action action)
+ where TFirstExceptionType : System.Exception
+ where TSecondExceptionType : System.Exception
+ { }
+ public static void ThrowsIf<T>(bool condition, System.Action action) where T : System.Exception { }
+ public static void GreaterThan<T>(T actual, T greaterThan, string userMessage = null) where T : System.IComparable { }
+ public static void LessThan<T>(T actual, T lessThan, string userMessage = null) where T : System.IComparable { }
+ public static void LessThanOrEqualTo<T>(T actual, T lessThanOrEqualTo, string userMessage = null) where T : System.IComparable { }
+ public static void GreaterThanOrEqualTo<T>(T actual, T greaterThanOrEqualTo, string userMessage = null) where T : System.IComparable { }
+ public static void Equal(byte[] expected, byte[] actual) { }
+ }
public static class TheoryExtensions
{
[CLSCompliant(false)]
diff --git a/src/CoreFx.Private.TestUtilities/src/CoreFx.Private.TestUtilities.csproj b/src/CoreFx.Private.TestUtilities/src/CoreFx.Private.TestUtilities.csproj
index 89523b6a9d..e756a8a914 100644
--- a/src/CoreFx.Private.TestUtilities/src/CoreFx.Private.TestUtilities.csproj
+++ b/src/CoreFx.Private.TestUtilities/src/CoreFx.Private.TestUtilities.csproj
@@ -29,6 +29,7 @@
<Compile Include="$(CommonPath)\System\PasteArguments.cs">
<Link>Common\System\PasteArguments.cs</Link>
</Compile>
+ <Compile Include="System\AssertExtensions.cs" />
<Compile Include="System\TheoryExtensions.cs" />
</ItemGroup>
<ItemGroup>
@@ -36,6 +37,7 @@
<Reference Include="System.IO.FileSystem" />
<Reference Include="System.Linq" />
<Reference Include="System.Threading.Thread" />
+ <Reference Include="System.Threading.Tasks" />
<Reference Include="System.Runtime.Extensions" />
<Reference Include="System.Diagnostics.Process" />
<Reference Include="System.ComponentModel.Primitives" />
diff --git a/src/Common/tests/System/AssertExtensions.cs b/src/CoreFx.Private.TestUtilities/src/System/AssertExtensions.cs
index 97724a16fa..97724a16fa 100644
--- a/src/Common/tests/System/AssertExtensions.cs
+++ b/src/CoreFx.Private.TestUtilities/src/System/AssertExtensions.cs
diff --git a/src/CoreFx.Private.TestUtilities/src/System/IO/FileCleanupTestBase.cs b/src/CoreFx.Private.TestUtilities/src/System/IO/FileCleanupTestBase.cs
index 131c58d0dd..eab1de6a3f 100644
--- a/src/CoreFx.Private.TestUtilities/src/System/IO/FileCleanupTestBase.cs
+++ b/src/CoreFx.Private.TestUtilities/src/System/IO/FileCleanupTestBase.cs
@@ -63,7 +63,10 @@ namespace System.IO
catch { } // avoid exceptions escaping Dispose
}
- /// <summary>Gets the test directory into which all files and directories created by tests should be stored.</summary>
+ /// <summary>
+ /// Gets the test directory into which all files and directories created by tests should be stored.
+ /// This directory is isolated per test class.
+ /// </summary>
protected string TestDirectory { get; }
/// <summary>Gets a test file full path that is associated with the call site.</summary>
diff --git a/src/Microsoft.CSharp/pkg/Microsoft.CSharp.pkgproj b/src/Microsoft.CSharp/pkg/Microsoft.CSharp.pkgproj
index 515e0c601b..eb6c2fe98f 100644
--- a/src/Microsoft.CSharp/pkg/Microsoft.CSharp.pkgproj
+++ b/src/Microsoft.CSharp/pkg/Microsoft.CSharp.pkgproj
@@ -19,7 +19,7 @@
<AsFrameworkReference>true</AsFrameworkReference>
</InboxOnTargetFramework>
<InboxOnTargetFramework Include="netcoreapp2.0" />
- <InboxOnTargetFramework Include="uap10.1" />
+ <InboxOnTargetFramework Include="$(UAPvNextTFM)" />
<InboxOnTargetFramework Include="win8" />
<InboxOnTargetFramework Include="wp80" />
<InboxOnTargetFramework Include="wpa81" />
diff --git a/src/Microsoft.CSharp/src/Microsoft/CSharp/RuntimeBinder/CSharpArgumentInfo.cs b/src/Microsoft.CSharp/src/Microsoft/CSharp/RuntimeBinder/CSharpArgumentInfo.cs
index 5e20eca10e..e03833a0ca 100644
--- a/src/Microsoft.CSharp/src/Microsoft/CSharp/RuntimeBinder/CSharpArgumentInfo.cs
+++ b/src/Microsoft.CSharp/src/Microsoft/CSharp/RuntimeBinder/CSharpArgumentInfo.cs
@@ -19,7 +19,7 @@ namespace Microsoft.CSharp.RuntimeBinder
/// <summary>
/// The flags for the argument.
/// </summary>
- internal CSharpArgumentInfoFlags Flags { get; }
+ private CSharpArgumentInfoFlags Flags { get; }
/// <summary>
/// The name of the argument, if named; otherwise null.
@@ -49,7 +49,7 @@ namespace Microsoft.CSharp.RuntimeBinder
internal bool NamedArgument => (Flags & CSharpArgumentInfoFlags.NamedArgument) != 0;
- internal bool IsByRef => (Flags & CSharpArgumentInfoFlags.IsRef) != 0;
+ internal bool IsByRefOrOut => (Flags & (CSharpArgumentInfoFlags.IsRef | CSharpArgumentInfoFlags.IsOut)) != 0;
internal bool IsOut => (Flags & CSharpArgumentInfoFlags.IsOut) != 0;
diff --git a/src/Microsoft.CSharp/src/Microsoft/CSharp/RuntimeBinder/RuntimeBinder.cs b/src/Microsoft.CSharp/src/Microsoft/CSharp/RuntimeBinder/RuntimeBinder.cs
index 6dc888c6ef..3e09a265f5 100644
--- a/src/Microsoft.CSharp/src/Microsoft/CSharp/RuntimeBinder/RuntimeBinder.cs
+++ b/src/Microsoft.CSharp/src/Microsoft/CSharp/RuntimeBinder/RuntimeBinder.cs
@@ -313,7 +313,7 @@ namespace Microsoft.CSharp.RuntimeBinder
Type t = argInfo.UseCompileTimeType ? param.Type : arg.LimitType;
Debug.Assert(t != null);
- if ((argInfo.Flags & (CSharpArgumentInfoFlags.IsRef | CSharpArgumentInfoFlags.IsOut)) != 0)
+ if (argInfo.IsByRefOrOut)
{
// If we have a ref our an out parameter, make the byref type.
// If we have the receiver of a call or invoke that is ref, it must be because of
@@ -459,7 +459,7 @@ namespace Microsoft.CSharp.RuntimeBinder
if (paramExp != null && paramExp.IsByRef)
{
CSharpArgumentInfo info = arguments[i].Info;
- if (info.IsByRef || info.IsOut)
+ if (info.IsByRefOrOut)
{
type = _semanticChecker.GetTypeManager().GetParameterModifier(type, info.IsOut);
}
diff --git a/src/Microsoft.CSharp/src/Microsoft/CSharp/RuntimeBinder/Semantics/PredefinedMembers.cs b/src/Microsoft.CSharp/src/Microsoft/CSharp/RuntimeBinder/Semantics/PredefinedMembers.cs
index a05c94cbf7..3ddb8ab407 100644
--- a/src/Microsoft.CSharp/src/Microsoft/CSharp/RuntimeBinder/Semantics/PredefinedMembers.cs
+++ b/src/Microsoft.CSharp/src/Microsoft/CSharp/RuntimeBinder/Semantics/PredefinedMembers.cs
@@ -154,12 +154,6 @@ namespace Microsoft.CSharp.RuntimeBinder.Semantics
PP_COUNT,
};
- internal enum MethodRequiredEnum
- {
- Required,
- Optional
- }
-
internal enum MethodCallingConventionEnum
{
Static,
@@ -203,7 +197,7 @@ namespace Microsoft.CSharp.RuntimeBinder.Semantics
public int cTypeVars;
public int[] signature; // Size 8. expand this if a new method has a signature which doesn't fit in the current space
- public PredefinedMethodInfo(PREDEFMETH method, MethodRequiredEnum required, PredefinedType type, PredefinedName name, MethodCallingConventionEnum callingConvention, ACCESS access, int cTypeVars, int[] signature)
+ public PredefinedMethodInfo(PREDEFMETH method, PredefinedType type, PredefinedName name, MethodCallingConventionEnum callingConvention, ACCESS access, int cTypeVars, int[] signature)
{
this.method = method;
this.type = type;
@@ -224,7 +218,7 @@ namespace Microsoft.CSharp.RuntimeBinder.Semantics
public PREDEFMETH getter;
public PREDEFMETH setter;
- public PredefinedPropertyInfo(PREDEFPROP property, MethodRequiredEnum required, PredefinedName name, PREDEFMETH getter, PREDEFMETH setter)
+ public PredefinedPropertyInfo(PREDEFPROP property, PredefinedName name, PREDEFMETH getter, PREDEFMETH setter)
{
this.property = property;
this.name = name;
@@ -696,8 +690,8 @@ namespace Microsoft.CSharp.RuntimeBinder.Semantics
// the list of predefined property definitions.
// This list must be in the same order as the PREDEFPROP enum.
private static readonly PredefinedPropertyInfo[] s_predefinedProperties = {
- new PredefinedPropertyInfo( PREDEFPROP.PP_FIRST, MethodRequiredEnum.Optional, PredefinedName.PN_COUNT, PREDEFMETH.PM_COUNT, PREDEFMETH.PM_COUNT ),
- new PredefinedPropertyInfo( PREDEFPROP.PP_G_OPTIONAL_VALUE, MethodRequiredEnum.Optional, PredefinedName.PN_CAP_VALUE, PREDEFMETH.PM_G_OPTIONAL_GETVALUE, PREDEFMETH.PM_COUNT ),
+ new PredefinedPropertyInfo(PREDEFPROP.PP_FIRST, PredefinedName.PN_COUNT, PREDEFMETH.PM_COUNT, PREDEFMETH.PM_COUNT),
+ new PredefinedPropertyInfo(PREDEFPROP.PP_G_OPTIONAL_VALUE, PredefinedName.PN_CAP_VALUE, PREDEFMETH.PM_G_OPTIONAL_GETVALUE, PREDEFMETH.PM_COUNT)
};
private static PredefinedPropertyInfo GetPropInfo(PREDEFPROP property)
@@ -754,114 +748,114 @@ namespace Microsoft.CSharp.RuntimeBinder.Semantics
// the list of predefined method definitions.
// This list must be in the same order as the PREDEFMETH enum.
private static readonly PredefinedMethodInfo[] s_predefinedMethods = new PredefinedMethodInfo[(int)PREDEFMETH.PM_COUNT] {
- new PredefinedMethodInfo( PREDEFMETH.PM_FIRST, MethodRequiredEnum.Optional, PredefinedType.PT_COUNT, PredefinedName.PN_COUNT, MethodCallingConventionEnum.Static, ACCESS.ACC_PUBLIC, 0, new int[] { (int)PredefinedType.PT_VOID, 0 }),
- new PredefinedMethodInfo( PREDEFMETH.PM_DECIMAL_OPDECREMENT, MethodRequiredEnum.Optional, PredefinedType.PT_DECIMAL, PredefinedName.PN_OPDECREMENT, MethodCallingConventionEnum.Static, ACCESS.ACC_PUBLIC, 0, new int[] { (int)PredefinedType.PT_DECIMAL, 1, (int)PredefinedType.PT_DECIMAL }),
- new PredefinedMethodInfo( PREDEFMETH.PM_DECIMAL_OPDIVISION, MethodRequiredEnum.Optional, PredefinedType.PT_DECIMAL, PredefinedName.PN_OPDIVISION, MethodCallingConventionEnum.Static, ACCESS.ACC_PUBLIC, 0, new int[] { (int)PredefinedType.PT_DECIMAL, 2, (int)PredefinedType.PT_DECIMAL, (int)PredefinedType.PT_DECIMAL }),
- new PredefinedMethodInfo( PREDEFMETH.PM_DECIMAL_OPEQUALITY, MethodRequiredEnum.Optional, PredefinedType.PT_DECIMAL, PredefinedName.PN_OPEQUALITY, MethodCallingConventionEnum.Static, ACCESS.ACC_PUBLIC, 0, new int[] { (int)PredefinedType.PT_BOOL, 2, (int)PredefinedType.PT_DECIMAL, (int)PredefinedType.PT_DECIMAL }),
- new PredefinedMethodInfo( PREDEFMETH.PM_DECIMAL_OPGREATERTHAN, MethodRequiredEnum.Optional, PredefinedType.PT_DECIMAL, PredefinedName.PN_OPGREATERTHAN, MethodCallingConventionEnum.Static, ACCESS.ACC_PUBLIC, 0, new int[] { (int)PredefinedType.PT_BOOL, 2, (int)PredefinedType.PT_DECIMAL, (int)PredefinedType.PT_DECIMAL }),
- new PredefinedMethodInfo( PREDEFMETH.PM_DECIMAL_OPGREATERTHANOREQUAL, MethodRequiredEnum.Optional, PredefinedType.PT_DECIMAL, PredefinedName.PN_OPGREATERTHANOREQUAL, MethodCallingConventionEnum.Static, ACCESS.ACC_PUBLIC, 0, new int[] { (int)PredefinedType.PT_BOOL, 2, (int)PredefinedType.PT_DECIMAL, (int)PredefinedType.PT_DECIMAL }),
- new PredefinedMethodInfo( PREDEFMETH.PM_DECIMAL_OPINCREMENT, MethodRequiredEnum.Optional, PredefinedType.PT_DECIMAL, PredefinedName.PN_OPINCREMENT, MethodCallingConventionEnum.Static, ACCESS.ACC_PUBLIC, 0, new int[] { (int)PredefinedType.PT_DECIMAL, 1, (int)PredefinedType.PT_DECIMAL }),
- new PredefinedMethodInfo( PREDEFMETH.PM_DECIMAL_OPINEQUALITY, MethodRequiredEnum.Optional, PredefinedType.PT_DECIMAL, PredefinedName.PN_OPINEQUALITY, MethodCallingConventionEnum.Static, ACCESS.ACC_PUBLIC, 0, new int[] { (int)PredefinedType.PT_BOOL, 2, (int)PredefinedType.PT_DECIMAL, (int)PredefinedType.PT_DECIMAL }),
- new PredefinedMethodInfo( PREDEFMETH.PM_DECIMAL_OPLESSTHAN, MethodRequiredEnum.Optional, PredefinedType.PT_DECIMAL, PredefinedName.PN_OPLESSTHAN, MethodCallingConventionEnum.Static, ACCESS.ACC_PUBLIC, 0, new int[] { (int)PredefinedType.PT_BOOL, 2, (int)PredefinedType.PT_DECIMAL, (int)PredefinedType.PT_DECIMAL }),
- new PredefinedMethodInfo( PREDEFMETH.PM_DECIMAL_OPLESSTHANOREQUAL, MethodRequiredEnum.Optional, PredefinedType.PT_DECIMAL, PredefinedName.PN_OPLESSTHANOREQUAL, MethodCallingConventionEnum.Static, ACCESS.ACC_PUBLIC, 0, new int[] { (int)PredefinedType.PT_BOOL, 2, (int)PredefinedType.PT_DECIMAL, (int)PredefinedType.PT_DECIMAL }),
- new PredefinedMethodInfo( PREDEFMETH.PM_DECIMAL_OPMINUS, MethodRequiredEnum.Optional, PredefinedType.PT_DECIMAL, PredefinedName.PN_OPMINUS, MethodCallingConventionEnum.Static, ACCESS.ACC_PUBLIC, 0, new int[] { (int)PredefinedType.PT_DECIMAL, 2, (int)PredefinedType.PT_DECIMAL, (int)PredefinedType.PT_DECIMAL }),
- new PredefinedMethodInfo( PREDEFMETH.PM_DECIMAL_OPMODULUS, MethodRequiredEnum.Optional, PredefinedType.PT_DECIMAL, PredefinedName.PN_OPMODULUS, MethodCallingConventionEnum.Static, ACCESS.ACC_PUBLIC, 0, new int[] { (int)PredefinedType.PT_DECIMAL, 2, (int)PredefinedType.PT_DECIMAL, (int)PredefinedType.PT_DECIMAL }),
- new PredefinedMethodInfo( PREDEFMETH.PM_DECIMAL_OPMULTIPLY, MethodRequiredEnum.Optional, PredefinedType.PT_DECIMAL, PredefinedName.PN_OPMULTIPLY, MethodCallingConventionEnum.Static, ACCESS.ACC_PUBLIC, 0, new int[] { (int)PredefinedType.PT_DECIMAL, 2, (int)PredefinedType.PT_DECIMAL, (int)PredefinedType.PT_DECIMAL }),
- new PredefinedMethodInfo( PREDEFMETH.PM_DECIMAL_OPPLUS, MethodRequiredEnum.Optional, PredefinedType.PT_DECIMAL, PredefinedName.PN_OPPLUS, MethodCallingConventionEnum.Static, ACCESS.ACC_PUBLIC, 0, new int[] { (int)PredefinedType.PT_DECIMAL, 2, (int)PredefinedType.PT_DECIMAL, (int)PredefinedType.PT_DECIMAL }),
- new PredefinedMethodInfo( PREDEFMETH.PM_DECIMAL_OPUNARYMINUS, MethodRequiredEnum.Optional, PredefinedType.PT_DECIMAL, PredefinedName.PN_OPUNARYMINUS, MethodCallingConventionEnum.Static, ACCESS.ACC_PUBLIC, 0, new int[] { (int)PredefinedType.PT_DECIMAL, 1, (int)PredefinedType.PT_DECIMAL }),
- new PredefinedMethodInfo( PREDEFMETH.PM_DECIMAL_OPUNARYPLUS, MethodRequiredEnum.Optional, PredefinedType.PT_DECIMAL, PredefinedName.PN_OPUNARYPLUS, MethodCallingConventionEnum.Static, ACCESS.ACC_PUBLIC, 0, new int[] { (int)PredefinedType.PT_DECIMAL, 1, (int)PredefinedType.PT_DECIMAL }),
- new PredefinedMethodInfo( PREDEFMETH.PM_DELEGATE_COMBINE, MethodRequiredEnum.Optional, PredefinedType.PT_DELEGATE, PredefinedName.PN_COMBINE, MethodCallingConventionEnum.Static, ACCESS.ACC_PUBLIC, 0, new int[] { (int)PredefinedType.PT_DELEGATE, 2, (int)PredefinedType.PT_DELEGATE, (int)PredefinedType.PT_DELEGATE }),
- new PredefinedMethodInfo( PREDEFMETH.PM_DELEGATE_OPEQUALITY, MethodRequiredEnum.Optional, PredefinedType.PT_DELEGATE, PredefinedName.PN_OPEQUALITY, MethodCallingConventionEnum.Static, ACCESS.ACC_PUBLIC, 0, new int[] { (int)PredefinedType.PT_BOOL, 2, (int)PredefinedType.PT_DELEGATE, (int)PredefinedType.PT_DELEGATE }),
- new PredefinedMethodInfo( PREDEFMETH.PM_DELEGATE_OPINEQUALITY, MethodRequiredEnum.Optional, PredefinedType.PT_DELEGATE, PredefinedName.PN_OPINEQUALITY, MethodCallingConventionEnum.Static, ACCESS.ACC_PUBLIC, 0, new int[] { (int)PredefinedType.PT_BOOL, 2, (int)PredefinedType.PT_DELEGATE, (int)PredefinedType.PT_DELEGATE }),
- new PredefinedMethodInfo( PREDEFMETH.PM_DELEGATE_REMOVE, MethodRequiredEnum.Optional, PredefinedType.PT_DELEGATE, PredefinedName.PN_REMOVE, MethodCallingConventionEnum.Static, ACCESS.ACC_PUBLIC, 0, new int[] { (int)PredefinedType.PT_DELEGATE, 2, (int)PredefinedType.PT_DELEGATE, (int)PredefinedType.PT_DELEGATE }),
- new PredefinedMethodInfo( PREDEFMETH.PM_EXPRESSION_ADD, MethodRequiredEnum.Optional, PredefinedType.PT_EXPRESSION, PredefinedName.PN_ADD, MethodCallingConventionEnum.Static, ACCESS.ACC_PUBLIC, 0, new int[] { (int)PredefinedType.PT_BINARYEXPRESSION, 2, (int)PredefinedType.PT_EXPRESSION, (int)PredefinedType.PT_EXPRESSION }),
- new PredefinedMethodInfo( PREDEFMETH.PM_EXPRESSION_ADD_USER_DEFINED, MethodRequiredEnum.Optional, PredefinedType.PT_EXPRESSION, PredefinedName.PN_ADD, MethodCallingConventionEnum.Static, ACCESS.ACC_PUBLIC, 0, new int[] { (int)PredefinedType.PT_BINARYEXPRESSION, 3, (int)PredefinedType.PT_EXPRESSION, (int)PredefinedType.PT_EXPRESSION, (int)PredefinedType.PT_METHODINFO }),
- new PredefinedMethodInfo( PREDEFMETH.PM_EXPRESSION_ADDCHECKED, MethodRequiredEnum.Optional, PredefinedType.PT_EXPRESSION, PredefinedName.PN_ADDCHECKED, MethodCallingConventionEnum.Static, ACCESS.ACC_PUBLIC, 0, new int[] { (int)PredefinedType.PT_BINARYEXPRESSION, 2, (int)PredefinedType.PT_EXPRESSION, (int)PredefinedType.PT_EXPRESSION }),
- new PredefinedMethodInfo( PREDEFMETH.PM_EXPRESSION_ADDCHECKED_USER_DEFINED, MethodRequiredEnum.Optional, PredefinedType.PT_EXPRESSION, PredefinedName.PN_ADDCHECKED, MethodCallingConventionEnum.Static, ACCESS.ACC_PUBLIC, 0, new int[] { (int)PredefinedType.PT_BINARYEXPRESSION, 3, (int)PredefinedType.PT_EXPRESSION, (int)PredefinedType.PT_EXPRESSION, (int)PredefinedType.PT_METHODINFO }),
- new PredefinedMethodInfo( PREDEFMETH.PM_EXPRESSION_AND, MethodRequiredEnum.Optional, PredefinedType.PT_EXPRESSION, PredefinedName.PN_AND, MethodCallingConventionEnum.Static, ACCESS.ACC_PUBLIC, 0, new int[] { (int)PredefinedType.PT_BINARYEXPRESSION, 2, (int)PredefinedType.PT_EXPRESSION, (int)PredefinedType.PT_EXPRESSION }),
- new PredefinedMethodInfo( PREDEFMETH.PM_EXPRESSION_AND_USER_DEFINED, MethodRequiredEnum.Optional, PredefinedType.PT_EXPRESSION, PredefinedName.PN_AND, MethodCallingConventionEnum.Static, ACCESS.ACC_PUBLIC, 0, new int[] { (int)PredefinedType.PT_BINARYEXPRESSION, 3, (int)PredefinedType.PT_EXPRESSION, (int)PredefinedType.PT_EXPRESSION, (int)PredefinedType.PT_METHODINFO }),
- new PredefinedMethodInfo( PREDEFMETH.PM_EXPRESSION_ANDALSO, MethodRequiredEnum.Optional, PredefinedType.PT_EXPRESSION, PredefinedName.PN_ANDALSO, MethodCallingConventionEnum.Static, ACCESS.ACC_PUBLIC, 0, new int[] { (int)PredefinedType.PT_BINARYEXPRESSION, 2, (int)PredefinedType.PT_EXPRESSION, (int)PredefinedType.PT_EXPRESSION }),
- new PredefinedMethodInfo( PREDEFMETH.PM_EXPRESSION_ANDALSO_USER_DEFINED, MethodRequiredEnum.Optional, PredefinedType.PT_EXPRESSION, PredefinedName.PN_ANDALSO, MethodCallingConventionEnum.Static, ACCESS.ACC_PUBLIC, 0, new int[] { (int)PredefinedType.PT_BINARYEXPRESSION, 3, (int)PredefinedType.PT_EXPRESSION, (int)PredefinedType.PT_EXPRESSION, (int)PredefinedType.PT_METHODINFO }),
- new PredefinedMethodInfo( PREDEFMETH.PM_EXPRESSION_ARRAYINDEX, MethodRequiredEnum.Optional, PredefinedType.PT_EXPRESSION, PredefinedName.PN_ARRAYINDEX, MethodCallingConventionEnum.Static, ACCESS.ACC_PUBLIC, 0, new int[] { (int)PredefinedType.PT_BINARYEXPRESSION, 2, (int)PredefinedType.PT_EXPRESSION, (int)PredefinedType.PT_EXPRESSION }),
- new PredefinedMethodInfo( PREDEFMETH.PM_EXPRESSION_ARRAYINDEX2, MethodRequiredEnum.Optional, PredefinedType.PT_EXPRESSION, PredefinedName.PN_ARRAYINDEX, MethodCallingConventionEnum.Static, ACCESS.ACC_PUBLIC, 0, new int[] { (int)PredefinedType.PT_METHODCALLEXPRESSION, 2, (int)PredefinedType.PT_EXPRESSION, (int)MethodSignatureEnum.SIG_SZ_ARRAY, (int)PredefinedType.PT_EXPRESSION }),
- new PredefinedMethodInfo( PREDEFMETH.PM_EXPRESSION_ASSIGN, MethodRequiredEnum.Optional, PredefinedType.PT_EXPRESSION, PredefinedName.PN_ASSIGN, MethodCallingConventionEnum.Static, ACCESS.ACC_PUBLIC, 0, new int[] { (int)PredefinedType.PT_BINARYEXPRESSION, 2, (int)PredefinedType.PT_EXPRESSION, (int)PredefinedType.PT_EXPRESSION }),
- new PredefinedMethodInfo( PREDEFMETH.PM_EXPRESSION_CONDITION, MethodRequiredEnum.Optional, PredefinedType.PT_EXPRESSION, PredefinedName.PN_CONDITION, MethodCallingConventionEnum.Static, ACCESS.ACC_PUBLIC, 0, new int[] { (int)PredefinedType.PT_CONDITIONALEXPRESSION, 3, (int)PredefinedType.PT_EXPRESSION, (int)PredefinedType.PT_EXPRESSION, (int)PredefinedType.PT_EXPRESSION }),
- new PredefinedMethodInfo( PREDEFMETH.PM_EXPRESSION_CONSTANT_OBJECT_TYPE, MethodRequiredEnum.Optional, PredefinedType.PT_EXPRESSION, PredefinedName.PN_CONSTANT, MethodCallingConventionEnum.Static, ACCESS.ACC_PUBLIC, 0, new int[] { (int)PredefinedType.PT_CONSTANTEXPRESSION, 2, (int)PredefinedType.PT_OBJECT, (int)PredefinedType.PT_TYPE }),
- new PredefinedMethodInfo( PREDEFMETH.PM_EXPRESSION_CONVERT, MethodRequiredEnum.Optional, PredefinedType.PT_EXPRESSION, PredefinedName.PN_CONVERT, MethodCallingConventionEnum.Static, ACCESS.ACC_PUBLIC, 0, new int[] { (int)PredefinedType.PT_UNARYEXPRESSION, 2, (int)PredefinedType.PT_EXPRESSION, (int)PredefinedType.PT_TYPE }),
- new PredefinedMethodInfo( PREDEFMETH.PM_EXPRESSION_CONVERT_USER_DEFINED, MethodRequiredEnum.Optional, PredefinedType.PT_EXPRESSION, PredefinedName.PN_CONVERT, MethodCallingConventionEnum.Static, ACCESS.ACC_PUBLIC, 0, new int[] { (int)PredefinedType.PT_UNARYEXPRESSION, 3, (int)PredefinedType.PT_EXPRESSION, (int)PredefinedType.PT_TYPE, (int)PredefinedType.PT_METHODINFO }),
- new PredefinedMethodInfo( PREDEFMETH.PM_EXPRESSION_CONVERTCHECKED, MethodRequiredEnum.Optional, PredefinedType.PT_EXPRESSION, PredefinedName.PN_CONVERTCHECKED, MethodCallingConventionEnum.Static, ACCESS.ACC_PUBLIC, 0, new int[] { (int)PredefinedType.PT_UNARYEXPRESSION, 2, (int)PredefinedType.PT_EXPRESSION, (int)PredefinedType.PT_TYPE }),
- new PredefinedMethodInfo( PREDEFMETH.PM_EXPRESSION_CONVERTCHECKED_USER_DEFINED, MethodRequiredEnum.Optional, PredefinedType.PT_EXPRESSION, PredefinedName.PN_CONVERTCHECKED, MethodCallingConventionEnum.Static, ACCESS.ACC_PUBLIC, 0, new int[] { (int)PredefinedType.PT_UNARYEXPRESSION, 3, (int)PredefinedType.PT_EXPRESSION, (int)PredefinedType.PT_TYPE, (int)PredefinedType.PT_METHODINFO }),
- new PredefinedMethodInfo( PREDEFMETH.PM_EXPRESSION_DIVIDE, MethodRequiredEnum.Optional, PredefinedType.PT_EXPRESSION, PredefinedName.PN_DIVIDE, MethodCallingConventionEnum.Static, ACCESS.ACC_PUBLIC, 0, new int[] { (int)PredefinedType.PT_BINARYEXPRESSION, 2, (int)PredefinedType.PT_EXPRESSION, (int)PredefinedType.PT_EXPRESSION }),
- new PredefinedMethodInfo( PREDEFMETH.PM_EXPRESSION_DIVIDE_USER_DEFINED, MethodRequiredEnum.Optional, PredefinedType.PT_EXPRESSION, PredefinedName.PN_DIVIDE, MethodCallingConventionEnum.Static, ACCESS.ACC_PUBLIC, 0, new int[] { (int)PredefinedType.PT_BINARYEXPRESSION, 3, (int)PredefinedType.PT_EXPRESSION, (int)PredefinedType.PT_EXPRESSION, (int)PredefinedType.PT_METHODINFO }),
- new PredefinedMethodInfo( PREDEFMETH.PM_EXPRESSION_EQUAL, MethodRequiredEnum.Optional, PredefinedType.PT_EXPRESSION, PredefinedName.PN_EQUAL, MethodCallingConventionEnum.Static, ACCESS.ACC_PUBLIC, 0, new int[] { (int)PredefinedType.PT_BINARYEXPRESSION, 2, (int)PredefinedType.PT_EXPRESSION, (int)PredefinedType.PT_EXPRESSION }),
- new PredefinedMethodInfo( PREDEFMETH.PM_EXPRESSION_EQUAL_USER_DEFINED, MethodRequiredEnum.Optional, PredefinedType.PT_EXPRESSION, PredefinedName.PN_EQUAL, MethodCallingConventionEnum.Static, ACCESS.ACC_PUBLIC, 0, new int[] { (int)PredefinedType.PT_BINARYEXPRESSION, 4, (int)PredefinedType.PT_EXPRESSION, (int)PredefinedType.PT_EXPRESSION, (int)PredefinedType.PT_BOOL, (int)PredefinedType.PT_METHODINFO }),
- new PredefinedMethodInfo( PREDEFMETH.PM_EXPRESSION_EXCLUSIVEOR, MethodRequiredEnum.Optional, PredefinedType.PT_EXPRESSION, PredefinedName.PN_EXCLUSIVEOR, MethodCallingConventionEnum.Static, ACCESS.ACC_PUBLIC, 0, new int[] { (int)PredefinedType.PT_BINARYEXPRESSION, 2, (int)PredefinedType.PT_EXPRESSION, (int)PredefinedType.PT_EXPRESSION }),
- new PredefinedMethodInfo( PREDEFMETH.PM_EXPRESSION_EXCLUSIVEOR_USER_DEFINED, MethodRequiredEnum.Optional, PredefinedType.PT_EXPRESSION, PredefinedName.PN_EXCLUSIVEOR, MethodCallingConventionEnum.Static, ACCESS.ACC_PUBLIC, 0, new int[] { (int)PredefinedType.PT_BINARYEXPRESSION, 3, (int)PredefinedType.PT_EXPRESSION, (int)PredefinedType.PT_EXPRESSION, (int)PredefinedType.PT_METHODINFO }),
- new PredefinedMethodInfo( PREDEFMETH.PM_EXPRESSION_FIELD, MethodRequiredEnum.Optional, PredefinedType.PT_EXPRESSION, PredefinedName.PN_CAP_FIELD, MethodCallingConventionEnum.Static, ACCESS.ACC_PUBLIC, 0, new int[] { (int)PredefinedType.PT_MEMBEREXPRESSION, 2, (int)PredefinedType.PT_EXPRESSION, (int)PredefinedType.PT_FIELDINFO }),
- new PredefinedMethodInfo( PREDEFMETH.PM_EXPRESSION_GREATERTHAN, MethodRequiredEnum.Optional, PredefinedType.PT_EXPRESSION, PredefinedName.PN_GREATERTHAN, MethodCallingConventionEnum.Static, ACCESS.ACC_PUBLIC, 0, new int[] { (int)PredefinedType.PT_BINARYEXPRESSION, 2, (int)PredefinedType.PT_EXPRESSION, (int)PredefinedType.PT_EXPRESSION }),
- new PredefinedMethodInfo( PREDEFMETH.PM_EXPRESSION_GREATERTHAN_USER_DEFINED, MethodRequiredEnum.Optional, PredefinedType.PT_EXPRESSION, PredefinedName.PN_GREATERTHAN, MethodCallingConventionEnum.Static, ACCESS.ACC_PUBLIC, 0, new int[] { (int)PredefinedType.PT_BINARYEXPRESSION, 4, (int)PredefinedType.PT_EXPRESSION, (int)PredefinedType.PT_EXPRESSION, (int)PredefinedType.PT_BOOL, (int)PredefinedType.PT_METHODINFO }),
- new PredefinedMethodInfo( PREDEFMETH.PM_EXPRESSION_GREATERTHANOREQUAL, MethodRequiredEnum.Optional, PredefinedType.PT_EXPRESSION, PredefinedName.PN_GREATERTHANOREQUAL, MethodCallingConventionEnum.Static, ACCESS.ACC_PUBLIC, 0, new int[] { (int)PredefinedType.PT_BINARYEXPRESSION, 2, (int)PredefinedType.PT_EXPRESSION, (int)PredefinedType.PT_EXPRESSION }),
- new PredefinedMethodInfo( PREDEFMETH.PM_EXPRESSION_GREATERTHANOREQUAL_USER_DEFINED, MethodRequiredEnum.Optional, PredefinedType.PT_EXPRESSION, PredefinedName.PN_GREATERTHANOREQUAL, MethodCallingConventionEnum.Static, ACCESS.ACC_PUBLIC, 0, new int[] { (int)PredefinedType.PT_BINARYEXPRESSION, 4, (int)PredefinedType.PT_EXPRESSION, (int)PredefinedType.PT_EXPRESSION, (int)PredefinedType.PT_BOOL, (int)PredefinedType.PT_METHODINFO }),
- new PredefinedMethodInfo( PREDEFMETH.PM_EXPRESSION_LAMBDA, MethodRequiredEnum.Optional, PredefinedType.PT_EXPRESSION, PredefinedName.PN_LAMBDA, MethodCallingConventionEnum.Static, ACCESS.ACC_PUBLIC, 1, new int[] { (int)PredefinedType.PT_G_EXPRESSION, (int)MethodSignatureEnum.SIG_METH_TYVAR, 0, 2, (int)PredefinedType.PT_EXPRESSION, (int)MethodSignatureEnum.SIG_SZ_ARRAY, (int)PredefinedType.PT_PARAMETEREXPRESSION }),
- new PredefinedMethodInfo( PREDEFMETH.PM_EXPRESSION_LEFTSHIFT, MethodRequiredEnum.Optional, PredefinedType.PT_EXPRESSION, PredefinedName.PN_LEFTSHIFT, MethodCallingConventionEnum.Static, ACCESS.ACC_PUBLIC, 0, new int[] { (int)PredefinedType.PT_BINARYEXPRESSION, 2, (int)PredefinedType.PT_EXPRESSION, (int)PredefinedType.PT_EXPRESSION }),
- new PredefinedMethodInfo( PREDEFMETH.PM_EXPRESSION_LEFTSHIFT_USER_DEFINED, MethodRequiredEnum.Optional, PredefinedType.PT_EXPRESSION, PredefinedName.PN_LEFTSHIFT, MethodCallingConventionEnum.Static, ACCESS.ACC_PUBLIC, 0, new int[] { (int)PredefinedType.PT_BINARYEXPRESSION, 3, (int)PredefinedType.PT_EXPRESSION, (int)PredefinedType.PT_EXPRESSION, (int)PredefinedType.PT_METHODINFO }),
- new PredefinedMethodInfo( PREDEFMETH.PM_EXPRESSION_LESSTHAN, MethodRequiredEnum.Optional, PredefinedType.PT_EXPRESSION, PredefinedName.PN_LESSTHAN, MethodCallingConventionEnum.Static, ACCESS.ACC_PUBLIC, 0, new int[] { (int)PredefinedType.PT_BINARYEXPRESSION, 2, (int)PredefinedType.PT_EXPRESSION, (int)PredefinedType.PT_EXPRESSION }),
- new PredefinedMethodInfo( PREDEFMETH.PM_EXPRESSION_LESSTHAN_USER_DEFINED, MethodRequiredEnum.Optional, PredefinedType.PT_EXPRESSION, PredefinedName.PN_LESSTHAN, MethodCallingConventionEnum.Static, ACCESS.ACC_PUBLIC, 0, new int[] { (int)PredefinedType.PT_BINARYEXPRESSION, 4, (int)PredefinedType.PT_EXPRESSION, (int)PredefinedType.PT_EXPRESSION, (int)PredefinedType.PT_BOOL, (int)PredefinedType.PT_METHODINFO }),
- new PredefinedMethodInfo( PREDEFMETH.PM_EXPRESSION_LESSTHANOREQUAL, MethodRequiredEnum.Optional, PredefinedType.PT_EXPRESSION, PredefinedName.PN_LESSTHANOREQUAL, MethodCallingConventionEnum.Static, ACCESS.ACC_PUBLIC, 0, new int[] { (int)PredefinedType.PT_BINARYEXPRESSION, 2, (int)PredefinedType.PT_EXPRESSION, (int)PredefinedType.PT_EXPRESSION }),
- new PredefinedMethodInfo( PREDEFMETH.PM_EXPRESSION_LESSTHANOREQUAL_USER_DEFINED, MethodRequiredEnum.Optional, PredefinedType.PT_EXPRESSION, PredefinedName.PN_LESSTHANOREQUAL, MethodCallingConventionEnum.Static, ACCESS.ACC_PUBLIC, 0, new int[] { (int)PredefinedType.PT_BINARYEXPRESSION, 4, (int)PredefinedType.PT_EXPRESSION, (int)PredefinedType.PT_EXPRESSION, (int)PredefinedType.PT_BOOL, (int)PredefinedType.PT_METHODINFO }),
- new PredefinedMethodInfo( PREDEFMETH.PM_EXPRESSION_MODULO, MethodRequiredEnum.Optional, PredefinedType.PT_EXPRESSION, PredefinedName.PN_MODULO, MethodCallingConventionEnum.Static, ACCESS.ACC_PUBLIC, 0, new int[] { (int)PredefinedType.PT_BINARYEXPRESSION, 2, (int)PredefinedType.PT_EXPRESSION, (int)PredefinedType.PT_EXPRESSION }),
- new PredefinedMethodInfo( PREDEFMETH.PM_EXPRESSION_MODULO_USER_DEFINED, MethodRequiredEnum.Optional, PredefinedType.PT_EXPRESSION, PredefinedName.PN_MODULO, MethodCallingConventionEnum.Static, ACCESS.ACC_PUBLIC, 0, new int[] { (int)PredefinedType.PT_BINARYEXPRESSION, 3, (int)PredefinedType.PT_EXPRESSION, (int)PredefinedType.PT_EXPRESSION, (int)PredefinedType.PT_METHODINFO }),
- new PredefinedMethodInfo( PREDEFMETH.PM_EXPRESSION_MULTIPLY, MethodRequiredEnum.Optional, PredefinedType.PT_EXPRESSION, PredefinedName.PN_MULTIPLY, MethodCallingConventionEnum.Static, ACCESS.ACC_PUBLIC, 0, new int[] { (int)PredefinedType.PT_BINARYEXPRESSION, 2, (int)PredefinedType.PT_EXPRESSION, (int)PredefinedType.PT_EXPRESSION }),
- new PredefinedMethodInfo( PREDEFMETH.PM_EXPRESSION_MULTIPLY_USER_DEFINED, MethodRequiredEnum.Optional, PredefinedType.PT_EXPRESSION, PredefinedName.PN_MULTIPLY, MethodCallingConventionEnum.Static, ACCESS.ACC_PUBLIC, 0, new int[] { (int)PredefinedType.PT_BINARYEXPRESSION, 3, (int)PredefinedType.PT_EXPRESSION, (int)PredefinedType.PT_EXPRESSION, (int)PredefinedType.PT_METHODINFO }),
- new PredefinedMethodInfo( PREDEFMETH.PM_EXPRESSION_MULTIPLYCHECKED, MethodRequiredEnum.Optional, PredefinedType.PT_EXPRESSION, PredefinedName.PN_MULTIPLYCHECKED, MethodCallingConventionEnum.Static, ACCESS.ACC_PUBLIC, 0, new int[] { (int)PredefinedType.PT_BINARYEXPRESSION, 2, (int)PredefinedType.PT_EXPRESSION, (int)PredefinedType.PT_EXPRESSION }),
- new PredefinedMethodInfo( PREDEFMETH.PM_EXPRESSION_MULTIPLYCHECKED_USER_DEFINED, MethodRequiredEnum.Optional, PredefinedType.PT_EXPRESSION, PredefinedName.PN_MULTIPLYCHECKED, MethodCallingConventionEnum.Static, ACCESS.ACC_PUBLIC, 0, new int[] { (int)PredefinedType.PT_BINARYEXPRESSION, 3, (int)PredefinedType.PT_EXPRESSION, (int)PredefinedType.PT_EXPRESSION, (int)PredefinedType.PT_METHODINFO }),
- new PredefinedMethodInfo( PREDEFMETH.PM_EXPRESSION_NOTEQUAL, MethodRequiredEnum.Optional, PredefinedType.PT_EXPRESSION, PredefinedName.PN_NOTEQUAL, MethodCallingConventionEnum.Static, ACCESS.ACC_PUBLIC, 0, new int[] { (int)PredefinedType.PT_BINARYEXPRESSION, 2, (int)PredefinedType.PT_EXPRESSION, (int)PredefinedType.PT_EXPRESSION }),
- new PredefinedMethodInfo( PREDEFMETH.PM_EXPRESSION_NOTEQUAL_USER_DEFINED, MethodRequiredEnum.Optional, PredefinedType.PT_EXPRESSION, PredefinedName.PN_NOTEQUAL, MethodCallingConventionEnum.Static, ACCESS.ACC_PUBLIC, 0, new int[] { (int)PredefinedType.PT_BINARYEXPRESSION, 4, (int)PredefinedType.PT_EXPRESSION, (int)PredefinedType.PT_EXPRESSION, (int)PredefinedType.PT_BOOL, (int)PredefinedType.PT_METHODINFO }),
- new PredefinedMethodInfo( PREDEFMETH.PM_EXPRESSION_OR, MethodRequiredEnum.Optional, PredefinedType.PT_EXPRESSION, PredefinedName.PN_OR, MethodCallingConventionEnum.Static, ACCESS.ACC_PUBLIC, 0, new int[] { (int)PredefinedType.PT_BINARYEXPRESSION, 2, (int)PredefinedType.PT_EXPRESSION, (int)PredefinedType.PT_EXPRESSION }),
- new PredefinedMethodInfo( PREDEFMETH.PM_EXPRESSION_OR_USER_DEFINED, MethodRequiredEnum.Optional, PredefinedType.PT_EXPRESSION, PredefinedName.PN_OR, MethodCallingConventionEnum.Static, ACCESS.ACC_PUBLIC, 0, new int[] { (int)PredefinedType.PT_BINARYEXPRESSION, 3, (int)PredefinedType.PT_EXPRESSION, (int)PredefinedType.PT_EXPRESSION, (int)PredefinedType.PT_METHODINFO }),
- new PredefinedMethodInfo( PREDEFMETH.PM_EXPRESSION_ORELSE, MethodRequiredEnum.Optional, PredefinedType.PT_EXPRESSION, PredefinedName.PN_ORELSE, MethodCallingConventionEnum.Static, ACCESS.ACC_PUBLIC, 0, new int[] { (int)PredefinedType.PT_BINARYEXPRESSION, 2, (int)PredefinedType.PT_EXPRESSION, (int)PredefinedType.PT_EXPRESSION }),
- new PredefinedMethodInfo( PREDEFMETH.PM_EXPRESSION_ORELSE_USER_DEFINED, MethodRequiredEnum.Optional, PredefinedType.PT_EXPRESSION, PredefinedName.PN_ORELSE, MethodCallingConventionEnum.Static, ACCESS.ACC_PUBLIC, 0, new int[] { (int)PredefinedType.PT_BINARYEXPRESSION, 3, (int)PredefinedType.PT_EXPRESSION, (int)PredefinedType.PT_EXPRESSION, (int)PredefinedType.PT_METHODINFO }),
- new PredefinedMethodInfo( PREDEFMETH.PM_EXPRESSION_PARAMETER, MethodRequiredEnum.Optional, PredefinedType.PT_EXPRESSION, PredefinedName.PN_PARAMETER, MethodCallingConventionEnum.Static, ACCESS.ACC_PUBLIC, 0, new int[] { (int)PredefinedType.PT_PARAMETEREXPRESSION, 2, (int)PredefinedType.PT_TYPE, (int)PredefinedType.PT_STRING }),
- new PredefinedMethodInfo( PREDEFMETH.PM_EXPRESSION_RIGHTSHIFT, MethodRequiredEnum.Optional, PredefinedType.PT_EXPRESSION, PredefinedName.PN_RIGHTSHIFT, MethodCallingConventionEnum.Static, ACCESS.ACC_PUBLIC, 0, new int[] { (int)PredefinedType.PT_BINARYEXPRESSION, 2, (int)PredefinedType.PT_EXPRESSION, (int)PredefinedType.PT_EXPRESSION }),
- new PredefinedMethodInfo( PREDEFMETH.PM_EXPRESSION_RIGHTSHIFT_USER_DEFINED, MethodRequiredEnum.Optional, PredefinedType.PT_EXPRESSION, PredefinedName.PN_RIGHTSHIFT, MethodCallingConventionEnum.Static, ACCESS.ACC_PUBLIC, 0, new int[] { (int)PredefinedType.PT_BINARYEXPRESSION, 3, (int)PredefinedType.PT_EXPRESSION, (int)PredefinedType.PT_EXPRESSION, (int)PredefinedType.PT_METHODINFO }),
- new PredefinedMethodInfo( PREDEFMETH.PM_EXPRESSION_SUBTRACT, MethodRequiredEnum.Optional, PredefinedType.PT_EXPRESSION, PredefinedName.PN_SUBTRACT, MethodCallingConventionEnum.Static, ACCESS.ACC_PUBLIC, 0, new int[] { (int)PredefinedType.PT_BINARYEXPRESSION, 2, (int)PredefinedType.PT_EXPRESSION, (int)PredefinedType.PT_EXPRESSION }),
- new PredefinedMethodInfo( PREDEFMETH.PM_EXPRESSION_SUBTRACT_USER_DEFINED, MethodRequiredEnum.Optional, PredefinedType.PT_EXPRESSION, PredefinedName.PN_SUBTRACT, MethodCallingConventionEnum.Static, ACCESS.ACC_PUBLIC, 0, new int[] { (int)PredefinedType.PT_BINARYEXPRESSION, 3, (int)PredefinedType.PT_EXPRESSION, (int)PredefinedType.PT_EXPRESSION, (int)PredefinedType.PT_METHODINFO }),
- new PredefinedMethodInfo( PREDEFMETH.PM_EXPRESSION_SUBTRACTCHECKED, MethodRequiredEnum.Optional, PredefinedType.PT_EXPRESSION, PredefinedName.PN_SUBTRACTCHECKED, MethodCallingConventionEnum.Static, ACCESS.ACC_PUBLIC, 0, new int[] { (int)PredefinedType.PT_BINARYEXPRESSION, 2, (int)PredefinedType.PT_EXPRESSION, (int)PredefinedType.PT_EXPRESSION }),
- new PredefinedMethodInfo( PREDEFMETH.PM_EXPRESSION_SUBTRACTCHECKED_USER_DEFINED, MethodRequiredEnum.Optional, PredefinedType.PT_EXPRESSION, PredefinedName.PN_SUBTRACTCHECKED, MethodCallingConventionEnum.Static, ACCESS.ACC_PUBLIC, 0, new int[] { (int)PredefinedType.PT_BINARYEXPRESSION, 3, (int)PredefinedType.PT_EXPRESSION, (int)PredefinedType.PT_EXPRESSION, (int)PredefinedType.PT_METHODINFO }),
- new PredefinedMethodInfo( PREDEFMETH.PM_EXPRESSION_UNARYPLUS_USER_DEFINED, MethodRequiredEnum.Optional, PredefinedType.PT_EXPRESSION, PredefinedName.PN_PLUS , MethodCallingConventionEnum.Static, ACCESS.ACC_PUBLIC, 0, new int[] { (int)PredefinedType.PT_UNARYEXPRESSION, 2, (int)PredefinedType.PT_EXPRESSION, (int)PredefinedType.PT_METHODINFO }),
- new PredefinedMethodInfo( PREDEFMETH.PM_EXPRESSION_NEGATE, MethodRequiredEnum.Optional, PredefinedType.PT_EXPRESSION, PredefinedName.PN_NEGATE, MethodCallingConventionEnum.Static, ACCESS.ACC_PUBLIC, 0, new int[] { (int)PredefinedType.PT_UNARYEXPRESSION, 1, (int)PredefinedType.PT_EXPRESSION }),
- new PredefinedMethodInfo( PREDEFMETH.PM_EXPRESSION_NEGATE_USER_DEFINED, MethodRequiredEnum.Optional, PredefinedType.PT_EXPRESSION, PredefinedName.PN_NEGATE, MethodCallingConventionEnum.Static, ACCESS.ACC_PUBLIC, 0, new int[] { (int)PredefinedType.PT_UNARYEXPRESSION, 2, (int)PredefinedType.PT_EXPRESSION, (int)PredefinedType.PT_METHODINFO }),
- new PredefinedMethodInfo( PREDEFMETH.PM_EXPRESSION_NEGATECHECKED, MethodRequiredEnum.Optional, PredefinedType.PT_EXPRESSION, PredefinedName.PN_NEGATECHECKED, MethodCallingConventionEnum.Static, ACCESS.ACC_PUBLIC, 0, new int[] { (int)PredefinedType.PT_UNARYEXPRESSION, 1, (int)PredefinedType.PT_EXPRESSION }),
- new PredefinedMethodInfo( PREDEFMETH.PM_EXPRESSION_NEGATECHECKED_USER_DEFINED, MethodRequiredEnum.Optional, PredefinedType.PT_EXPRESSION, PredefinedName.PN_NEGATECHECKED, MethodCallingConventionEnum.Static, ACCESS.ACC_PUBLIC, 0, new int[] { (int)PredefinedType.PT_UNARYEXPRESSION, 2, (int)PredefinedType.PT_EXPRESSION, (int)PredefinedType.PT_METHODINFO }),
- new PredefinedMethodInfo( PREDEFMETH.PM_EXPRESSION_CALL, MethodRequiredEnum.Optional, PredefinedType.PT_EXPRESSION, PredefinedName.PN_CALL, MethodCallingConventionEnum.Static, ACCESS.ACC_PUBLIC, 0, new int[] { (int)PredefinedType.PT_METHODCALLEXPRESSION, 3, (int)PredefinedType.PT_EXPRESSION, (int)PredefinedType.PT_METHODINFO, (int)MethodSignatureEnum.SIG_SZ_ARRAY, (int)PredefinedType.PT_EXPRESSION }),
- new PredefinedMethodInfo( PREDEFMETH.PM_EXPRESSION_NEW, MethodRequiredEnum.Optional, PredefinedType.PT_EXPRESSION, PredefinedName.PN_NEW, MethodCallingConventionEnum.Static, ACCESS.ACC_PUBLIC, 0, new int[] { (int)PredefinedType.PT_NEWEXPRESSION, 2, (int)PredefinedType.PT_CONSTRUCTORINFO, (int)MethodSignatureEnum.SIG_SZ_ARRAY, (int)PredefinedType.PT_EXPRESSION }),
- new PredefinedMethodInfo( PREDEFMETH.PM_EXPRESSION_NEW_MEMBERS, MethodRequiredEnum.Optional, PredefinedType.PT_EXPRESSION, PredefinedName.PN_NEW, MethodCallingConventionEnum.Static, ACCESS.ACC_PUBLIC, 0, new int[] { (int)PredefinedType.PT_NEWEXPRESSION, 3, (int)PredefinedType.PT_CONSTRUCTORINFO, (int)PredefinedType.PT_G_IENUMERABLE, (int)PredefinedType.PT_EXPRESSION, (int)MethodSignatureEnum.SIG_SZ_ARRAY, (int)PredefinedType.PT_MEMBERINFO }),
- new PredefinedMethodInfo( PREDEFMETH.PM_EXPRESSION_NEW_TYPE, MethodRequiredEnum.Optional, PredefinedType.PT_EXPRESSION, PredefinedName.PN_NEW, MethodCallingConventionEnum.Static, ACCESS.ACC_PUBLIC, 0, new int[] { (int)PredefinedType.PT_NEWEXPRESSION, 1, (int)PredefinedType.PT_TYPE }),
- new PredefinedMethodInfo( PREDEFMETH.PM_EXPRESSION_QUOTE, MethodRequiredEnum.Optional, PredefinedType.PT_EXPRESSION, PredefinedName.PN_QUOTE, MethodCallingConventionEnum.Static, ACCESS.ACC_PUBLIC, 0, new int[] { (int)PredefinedType.PT_UNARYEXPRESSION, 1, (int)PredefinedType.PT_EXPRESSION }),
- new PredefinedMethodInfo( PREDEFMETH.PM_EXPRESSION_ARRAYLENGTH, MethodRequiredEnum.Optional, PredefinedType.PT_EXPRESSION, PredefinedName.PN_ARRAYLENGTH, MethodCallingConventionEnum.Static, ACCESS.ACC_PUBLIC, 0, new int[] { (int)PredefinedType.PT_UNARYEXPRESSION, 1, (int)PredefinedType.PT_EXPRESSION }),
- new PredefinedMethodInfo( PREDEFMETH.PM_EXPRESSION_NOT, MethodRequiredEnum.Optional, PredefinedType.PT_EXPRESSION, PredefinedName.PN_NOT, MethodCallingConventionEnum.Static, ACCESS.ACC_PUBLIC, 0, new int[] { (int)PredefinedType.PT_UNARYEXPRESSION, 1, (int)PredefinedType.PT_EXPRESSION }),
- new PredefinedMethodInfo( PREDEFMETH.PM_EXPRESSION_NOT_USER_DEFINED, MethodRequiredEnum.Optional, PredefinedType.PT_EXPRESSION, PredefinedName.PN_NOT, MethodCallingConventionEnum.Static, ACCESS.ACC_PUBLIC, 0, new int[] { (int)PredefinedType.PT_UNARYEXPRESSION, 2, (int)PredefinedType.PT_EXPRESSION, (int)PredefinedType.PT_METHODINFO }),
- new PredefinedMethodInfo( PREDEFMETH.PM_EXPRESSION_NEWARRAYINIT, MethodRequiredEnum.Optional, PredefinedType.PT_EXPRESSION, PredefinedName.PN_NEWARRAYINIT, MethodCallingConventionEnum.Static, ACCESS.ACC_PUBLIC, 0, new int[] { (int)PredefinedType.PT_NEWARRAYEXPRESSION, 2, (int)PredefinedType.PT_TYPE, (int)MethodSignatureEnum.SIG_SZ_ARRAY, (int)PredefinedType.PT_EXPRESSION }),
- new PredefinedMethodInfo( PREDEFMETH.PM_EXPRESSION_PROPERTY, MethodRequiredEnum.Optional, PredefinedType.PT_EXPRESSION, PredefinedName.PN_EXPRESSION_PROPERTY, MethodCallingConventionEnum.Static, ACCESS.ACC_PUBLIC, 0, new int[] { (int)PredefinedType.PT_MEMBEREXPRESSION, 2, (int)PredefinedType.PT_EXPRESSION, (int)PredefinedType.PT_PROPERTYINFO }),
- new PredefinedMethodInfo( PREDEFMETH.PM_EXPRESSION_INVOKE, MethodRequiredEnum.Optional, PredefinedType.PT_EXPRESSION, PredefinedName.PN_INVOKE, MethodCallingConventionEnum.Static, ACCESS.ACC_PUBLIC, 0, new int[] { (int)PredefinedType.PT_INVOCATIONEXPRESSION, 2, (int)PredefinedType.PT_EXPRESSION, (int)MethodSignatureEnum.SIG_SZ_ARRAY, (int)PredefinedType.PT_EXPRESSION }),
- new PredefinedMethodInfo( PREDEFMETH.PM_METHODINFO_CREATEDELEGATE_TYPE_OBJECT, MethodRequiredEnum.Optional, PredefinedType.PT_METHODINFO, PredefinedName.PN_CREATEDELEGATE, MethodCallingConventionEnum.Virtual, ACCESS.ACC_PUBLIC, 0, new int[] { (int)PredefinedType.PT_DELEGATE, 2, (int)PredefinedType.PT_TYPE, (int)PredefinedType.PT_OBJECT}),
- new PredefinedMethodInfo( PREDEFMETH.PM_G_OPTIONAL_CTOR, MethodRequiredEnum.Optional, PredefinedType.PT_G_OPTIONAL, PredefinedName.PN_CTOR, MethodCallingConventionEnum.Instance, ACCESS.ACC_PUBLIC, 0, new int[] { (int)PredefinedType.PT_VOID, 1, (int)MethodSignatureEnum.SIG_CLASS_TYVAR, 0 }),
- new PredefinedMethodInfo( PREDEFMETH.PM_G_OPTIONAL_GETHASVALUE, MethodRequiredEnum.Optional, PredefinedType.PT_G_OPTIONAL, PredefinedName.PN_GETHASVALUE, MethodCallingConventionEnum.Instance, ACCESS.ACC_PUBLIC, 0, new int[] { (int)PredefinedType.PT_BOOL, 0 }),
- new PredefinedMethodInfo( PREDEFMETH.PM_G_OPTIONAL_GETVALUE, MethodRequiredEnum.Optional, PredefinedType.PT_G_OPTIONAL, PredefinedName.PN_GETVALUE, MethodCallingConventionEnum.Instance, ACCESS.ACC_PUBLIC, 0, new int[] { (int)MethodSignatureEnum.SIG_CLASS_TYVAR, 0, 0 }),
- new PredefinedMethodInfo( PREDEFMETH.PM_G_OPTIONAL_GET_VALUE_OR_DEF, MethodRequiredEnum.Optional, PredefinedType.PT_G_OPTIONAL, PredefinedName.PN_GET_VALUE_OR_DEF, MethodCallingConventionEnum.Instance, ACCESS.ACC_PUBLIC, 0, new int[] { (int)MethodSignatureEnum.SIG_CLASS_TYVAR, 0, 0 }),
- new PredefinedMethodInfo( PREDEFMETH.PM_STRING_CONCAT_OBJECT_1, MethodRequiredEnum.Optional, PredefinedType.PT_STRING, PredefinedName.PN_CONCAT, MethodCallingConventionEnum.Static, ACCESS.ACC_PUBLIC, 0, new int[] { (int)PredefinedType.PT_STRING, 1, (int)PredefinedType.PT_OBJECT }),
- new PredefinedMethodInfo( PREDEFMETH.PM_STRING_CONCAT_OBJECT_2, MethodRequiredEnum.Optional, PredefinedType.PT_STRING, PredefinedName.PN_CONCAT, MethodCallingConventionEnum.Static, ACCESS.ACC_PUBLIC, 0, new int[] { (int)PredefinedType.PT_STRING, 2, (int)PredefinedType.PT_OBJECT, (int)PredefinedType.PT_OBJECT }),
- new PredefinedMethodInfo( PREDEFMETH.PM_STRING_CONCAT_OBJECT_3, MethodRequiredEnum.Optional, PredefinedType.PT_STRING, PredefinedName.PN_CONCAT, MethodCallingConventionEnum.Static, ACCESS.ACC_PUBLIC, 0, new int[] { (int)PredefinedType.PT_STRING, 3, (int)PredefinedType.PT_OBJECT, (int)PredefinedType.PT_OBJECT, (int)PredefinedType.PT_OBJECT }),
- new PredefinedMethodInfo( PREDEFMETH.PM_STRING_CONCAT_STRING_1, MethodRequiredEnum.Optional, PredefinedType.PT_STRING, PredefinedName.PN_CONCAT, MethodCallingConventionEnum.Static, ACCESS.ACC_PUBLIC, 0, new int[] { (int)PredefinedType.PT_STRING, 1, (int)PredefinedType.PT_STRING }),
- new PredefinedMethodInfo( PREDEFMETH.PM_STRING_CONCAT_STRING_2, MethodRequiredEnum.Optional, PredefinedType.PT_STRING, PredefinedName.PN_CONCAT, MethodCallingConventionEnum.Static, ACCESS.ACC_PUBLIC, 0, new int[] { (int)PredefinedType.PT_STRING, 2, (int)PredefinedType.PT_STRING, (int)PredefinedType.PT_STRING }),
- new PredefinedMethodInfo( PREDEFMETH.PM_STRING_CONCAT_STRING_3, MethodRequiredEnum.Optional, PredefinedType.PT_STRING, PredefinedName.PN_CONCAT, MethodCallingConventionEnum.Static, ACCESS.ACC_PUBLIC, 0, new int[] { (int)PredefinedType.PT_STRING, 3, (int)PredefinedType.PT_STRING, (int)PredefinedType.PT_STRING, (int)PredefinedType.PT_STRING }),
- new PredefinedMethodInfo( PREDEFMETH.PM_STRING_CONCAT_STRING_4, MethodRequiredEnum.Optional, PredefinedType.PT_STRING, PredefinedName.PN_CONCAT, MethodCallingConventionEnum.Static, ACCESS.ACC_PUBLIC, 0, new int[] { (int)PredefinedType.PT_STRING, 4, (int)PredefinedType.PT_STRING, (int)PredefinedType.PT_STRING, (int)PredefinedType.PT_STRING, (int)PredefinedType.PT_STRING }),
- new PredefinedMethodInfo( PREDEFMETH.PM_STRING_CONCAT_SZ_OBJECT, MethodRequiredEnum.Optional, PredefinedType.PT_STRING, PredefinedName.PN_CONCAT, MethodCallingConventionEnum.Static, ACCESS.ACC_PUBLIC, 0, new int[] { (int)PredefinedType.PT_STRING, 1, (int)MethodSignatureEnum.SIG_SZ_ARRAY, (int)PredefinedType.PT_OBJECT }),
- new PredefinedMethodInfo( PREDEFMETH.PM_STRING_CONCAT_SZ_STRING, MethodRequiredEnum.Optional, PredefinedType.PT_STRING, PredefinedName.PN_CONCAT, MethodCallingConventionEnum.Static, ACCESS.ACC_PUBLIC, 0, new int[] { (int)PredefinedType.PT_STRING, 1, (int)MethodSignatureEnum.SIG_SZ_ARRAY, (int)PredefinedType.PT_STRING }),
- new PredefinedMethodInfo( PREDEFMETH.PM_STRING_GETCHARS, MethodRequiredEnum.Optional, PredefinedType.PT_STRING, PredefinedName.PN_GETCHARS, MethodCallingConventionEnum.Instance, ACCESS.ACC_PUBLIC, 0, new int[] { (int)PredefinedType.PT_CHAR, 1, (int)PredefinedType.PT_INT }),
- new PredefinedMethodInfo( PREDEFMETH.PM_STRING_GETLENGTH, MethodRequiredEnum.Optional, PredefinedType.PT_STRING, PredefinedName.PN_GETLENGTH, MethodCallingConventionEnum.Instance, ACCESS.ACC_PUBLIC, 0, new int[] { (int)PredefinedType.PT_INT, 0, }),
- new PredefinedMethodInfo( PREDEFMETH.PM_STRING_OPEQUALITY, MethodRequiredEnum.Optional, PredefinedType.PT_STRING, PredefinedName.PN_OPEQUALITY, MethodCallingConventionEnum.Static, ACCESS.ACC_PUBLIC, 0, new int[] { (int)PredefinedType.PT_BOOL, 2, (int)PredefinedType.PT_STRING, (int)PredefinedType.PT_STRING }),
- new PredefinedMethodInfo( PREDEFMETH.PM_STRING_OPINEQUALITY, MethodRequiredEnum.Optional, PredefinedType.PT_STRING, PredefinedName.PN_OPINEQUALITY, MethodCallingConventionEnum.Static, ACCESS.ACC_PUBLIC, 0, new int[] { (int)PredefinedType.PT_BOOL, 2, (int)PredefinedType.PT_STRING, (int)PredefinedType.PT_STRING }),
+ new PredefinedMethodInfo( PREDEFMETH.PM_FIRST, PredefinedType.PT_COUNT, PredefinedName.PN_COUNT, MethodCallingConventionEnum.Static, ACCESS.ACC_PUBLIC, 0, new int[] { (int)PredefinedType.PT_VOID, 0 }),
+ new PredefinedMethodInfo( PREDEFMETH.PM_DECIMAL_OPDECREMENT, PredefinedType.PT_DECIMAL, PredefinedName.PN_OPDECREMENT, MethodCallingConventionEnum.Static, ACCESS.ACC_PUBLIC, 0, new int[] { (int)PredefinedType.PT_DECIMAL, 1, (int)PredefinedType.PT_DECIMAL }),
+ new PredefinedMethodInfo( PREDEFMETH.PM_DECIMAL_OPDIVISION, PredefinedType.PT_DECIMAL, PredefinedName.PN_OPDIVISION, MethodCallingConventionEnum.Static, ACCESS.ACC_PUBLIC, 0, new int[] { (int)PredefinedType.PT_DECIMAL, 2, (int)PredefinedType.PT_DECIMAL, (int)PredefinedType.PT_DECIMAL }),
+ new PredefinedMethodInfo( PREDEFMETH.PM_DECIMAL_OPEQUALITY, PredefinedType.PT_DECIMAL, PredefinedName.PN_OPEQUALITY, MethodCallingConventionEnum.Static, ACCESS.ACC_PUBLIC, 0, new int[] { (int)PredefinedType.PT_BOOL, 2, (int)PredefinedType.PT_DECIMAL, (int)PredefinedType.PT_DECIMAL }),
+ new PredefinedMethodInfo( PREDEFMETH.PM_DECIMAL_OPGREATERTHAN, PredefinedType.PT_DECIMAL, PredefinedName.PN_OPGREATERTHAN, MethodCallingConventionEnum.Static, ACCESS.ACC_PUBLIC, 0, new int[] { (int)PredefinedType.PT_BOOL, 2, (int)PredefinedType.PT_DECIMAL, (int)PredefinedType.PT_DECIMAL }),
+ new PredefinedMethodInfo( PREDEFMETH.PM_DECIMAL_OPGREATERTHANOREQUAL, PredefinedType.PT_DECIMAL, PredefinedName.PN_OPGREATERTHANOREQUAL, MethodCallingConventionEnum.Static, ACCESS.ACC_PUBLIC, 0, new int[] { (int)PredefinedType.PT_BOOL, 2, (int)PredefinedType.PT_DECIMAL, (int)PredefinedType.PT_DECIMAL }),
+ new PredefinedMethodInfo( PREDEFMETH.PM_DECIMAL_OPINCREMENT, PredefinedType.PT_DECIMAL, PredefinedName.PN_OPINCREMENT, MethodCallingConventionEnum.Static, ACCESS.ACC_PUBLIC, 0, new int[] { (int)PredefinedType.PT_DECIMAL, 1, (int)PredefinedType.PT_DECIMAL }),
+ new PredefinedMethodInfo( PREDEFMETH.PM_DECIMAL_OPINEQUALITY, PredefinedType.PT_DECIMAL, PredefinedName.PN_OPINEQUALITY, MethodCallingConventionEnum.Static, ACCESS.ACC_PUBLIC, 0, new int[] { (int)PredefinedType.PT_BOOL, 2, (int)PredefinedType.PT_DECIMAL, (int)PredefinedType.PT_DECIMAL }),
+ new PredefinedMethodInfo( PREDEFMETH.PM_DECIMAL_OPLESSTHAN, PredefinedType.PT_DECIMAL, PredefinedName.PN_OPLESSTHAN, MethodCallingConventionEnum.Static, ACCESS.ACC_PUBLIC, 0, new int[] { (int)PredefinedType.PT_BOOL, 2, (int)PredefinedType.PT_DECIMAL, (int)PredefinedType.PT_DECIMAL }),
+ new PredefinedMethodInfo( PREDEFMETH.PM_DECIMAL_OPLESSTHANOREQUAL, PredefinedType.PT_DECIMAL, PredefinedName.PN_OPLESSTHANOREQUAL, MethodCallingConventionEnum.Static, ACCESS.ACC_PUBLIC, 0, new int[] { (int)PredefinedType.PT_BOOL, 2, (int)PredefinedType.PT_DECIMAL, (int)PredefinedType.PT_DECIMAL }),
+ new PredefinedMethodInfo( PREDEFMETH.PM_DECIMAL_OPMINUS, PredefinedType.PT_DECIMAL, PredefinedName.PN_OPMINUS, MethodCallingConventionEnum.Static, ACCESS.ACC_PUBLIC, 0, new int[] { (int)PredefinedType.PT_DECIMAL, 2, (int)PredefinedType.PT_DECIMAL, (int)PredefinedType.PT_DECIMAL }),
+ new PredefinedMethodInfo( PREDEFMETH.PM_DECIMAL_OPMODULUS, PredefinedType.PT_DECIMAL, PredefinedName.PN_OPMODULUS, MethodCallingConventionEnum.Static, ACCESS.ACC_PUBLIC, 0, new int[] { (int)PredefinedType.PT_DECIMAL, 2, (int)PredefinedType.PT_DECIMAL, (int)PredefinedType.PT_DECIMAL }),
+ new PredefinedMethodInfo( PREDEFMETH.PM_DECIMAL_OPMULTIPLY, PredefinedType.PT_DECIMAL, PredefinedName.PN_OPMULTIPLY, MethodCallingConventionEnum.Static, ACCESS.ACC_PUBLIC, 0, new int[] { (int)PredefinedType.PT_DECIMAL, 2, (int)PredefinedType.PT_DECIMAL, (int)PredefinedType.PT_DECIMAL }),
+ new PredefinedMethodInfo( PREDEFMETH.PM_DECIMAL_OPPLUS, PredefinedType.PT_DECIMAL, PredefinedName.PN_OPPLUS, MethodCallingConventionEnum.Static, ACCESS.ACC_PUBLIC, 0, new int[] { (int)PredefinedType.PT_DECIMAL, 2, (int)PredefinedType.PT_DECIMAL, (int)PredefinedType.PT_DECIMAL }),
+ new PredefinedMethodInfo( PREDEFMETH.PM_DECIMAL_OPUNARYMINUS, PredefinedType.PT_DECIMAL, PredefinedName.PN_OPUNARYMINUS, MethodCallingConventionEnum.Static, ACCESS.ACC_PUBLIC, 0, new int[] { (int)PredefinedType.PT_DECIMAL, 1, (int)PredefinedType.PT_DECIMAL }),
+ new PredefinedMethodInfo( PREDEFMETH.PM_DECIMAL_OPUNARYPLUS, PredefinedType.PT_DECIMAL, PredefinedName.PN_OPUNARYPLUS, MethodCallingConventionEnum.Static, ACCESS.ACC_PUBLIC, 0, new int[] { (int)PredefinedType.PT_DECIMAL, 1, (int)PredefinedType.PT_DECIMAL }),
+ new PredefinedMethodInfo( PREDEFMETH.PM_DELEGATE_COMBINE, PredefinedType.PT_DELEGATE, PredefinedName.PN_COMBINE, MethodCallingConventionEnum.Static, ACCESS.ACC_PUBLIC, 0, new int[] { (int)PredefinedType.PT_DELEGATE, 2, (int)PredefinedType.PT_DELEGATE, (int)PredefinedType.PT_DELEGATE }),
+ new PredefinedMethodInfo( PREDEFMETH.PM_DELEGATE_OPEQUALITY, PredefinedType.PT_DELEGATE, PredefinedName.PN_OPEQUALITY, MethodCallingConventionEnum.Static, ACCESS.ACC_PUBLIC, 0, new int[] { (int)PredefinedType.PT_BOOL, 2, (int)PredefinedType.PT_DELEGATE, (int)PredefinedType.PT_DELEGATE }),
+ new PredefinedMethodInfo( PREDEFMETH.PM_DELEGATE_OPINEQUALITY, PredefinedType.PT_DELEGATE, PredefinedName.PN_OPINEQUALITY, MethodCallingConventionEnum.Static, ACCESS.ACC_PUBLIC, 0, new int[] { (int)PredefinedType.PT_BOOL, 2, (int)PredefinedType.PT_DELEGATE, (int)PredefinedType.PT_DELEGATE }),
+ new PredefinedMethodInfo( PREDEFMETH.PM_DELEGATE_REMOVE, PredefinedType.PT_DELEGATE, PredefinedName.PN_REMOVE, MethodCallingConventionEnum.Static, ACCESS.ACC_PUBLIC, 0, new int[] { (int)PredefinedType.PT_DELEGATE, 2, (int)PredefinedType.PT_DELEGATE, (int)PredefinedType.PT_DELEGATE }),
+ new PredefinedMethodInfo( PREDEFMETH.PM_EXPRESSION_ADD, PredefinedType.PT_EXPRESSION, PredefinedName.PN_ADD, MethodCallingConventionEnum.Static, ACCESS.ACC_PUBLIC, 0, new int[] { (int)PredefinedType.PT_BINARYEXPRESSION, 2, (int)PredefinedType.PT_EXPRESSION, (int)PredefinedType.PT_EXPRESSION }),
+ new PredefinedMethodInfo( PREDEFMETH.PM_EXPRESSION_ADD_USER_DEFINED, PredefinedType.PT_EXPRESSION, PredefinedName.PN_ADD, MethodCallingConventionEnum.Static, ACCESS.ACC_PUBLIC, 0, new int[] { (int)PredefinedType.PT_BINARYEXPRESSION, 3, (int)PredefinedType.PT_EXPRESSION, (int)PredefinedType.PT_EXPRESSION, (int)PredefinedType.PT_METHODINFO }),
+ new PredefinedMethodInfo( PREDEFMETH.PM_EXPRESSION_ADDCHECKED, PredefinedType.PT_EXPRESSION, PredefinedName.PN_ADDCHECKED, MethodCallingConventionEnum.Static, ACCESS.ACC_PUBLIC, 0, new int[] { (int)PredefinedType.PT_BINARYEXPRESSION, 2, (int)PredefinedType.PT_EXPRESSION, (int)PredefinedType.PT_EXPRESSION }),
+ new PredefinedMethodInfo( PREDEFMETH.PM_EXPRESSION_ADDCHECKED_USER_DEFINED, PredefinedType.PT_EXPRESSION, PredefinedName.PN_ADDCHECKED, MethodCallingConventionEnum.Static, ACCESS.ACC_PUBLIC, 0, new int[] { (int)PredefinedType.PT_BINARYEXPRESSION, 3, (int)PredefinedType.PT_EXPRESSION, (int)PredefinedType.PT_EXPRESSION, (int)PredefinedType.PT_METHODINFO }),
+ new PredefinedMethodInfo( PREDEFMETH.PM_EXPRESSION_AND, PredefinedType.PT_EXPRESSION, PredefinedName.PN_AND, MethodCallingConventionEnum.Static, ACCESS.ACC_PUBLIC, 0, new int[] { (int)PredefinedType.PT_BINARYEXPRESSION, 2, (int)PredefinedType.PT_EXPRESSION, (int)PredefinedType.PT_EXPRESSION }),
+ new PredefinedMethodInfo( PREDEFMETH.PM_EXPRESSION_AND_USER_DEFINED, PredefinedType.PT_EXPRESSION, PredefinedName.PN_AND, MethodCallingConventionEnum.Static, ACCESS.ACC_PUBLIC, 0, new int[] { (int)PredefinedType.PT_BINARYEXPRESSION, 3, (int)PredefinedType.PT_EXPRESSION, (int)PredefinedType.PT_EXPRESSION, (int)PredefinedType.PT_METHODINFO }),
+ new PredefinedMethodInfo( PREDEFMETH.PM_EXPRESSION_ANDALSO, PredefinedType.PT_EXPRESSION, PredefinedName.PN_ANDALSO, MethodCallingConventionEnum.Static, ACCESS.ACC_PUBLIC, 0, new int[] { (int)PredefinedType.PT_BINARYEXPRESSION, 2, (int)PredefinedType.PT_EXPRESSION, (int)PredefinedType.PT_EXPRESSION }),
+ new PredefinedMethodInfo( PREDEFMETH.PM_EXPRESSION_ANDALSO_USER_DEFINED, PredefinedType.PT_EXPRESSION, PredefinedName.PN_ANDALSO, MethodCallingConventionEnum.Static, ACCESS.ACC_PUBLIC, 0, new int[] { (int)PredefinedType.PT_BINARYEXPRESSION, 3, (int)PredefinedType.PT_EXPRESSION, (int)PredefinedType.PT_EXPRESSION, (int)PredefinedType.PT_METHODINFO }),
+ new PredefinedMethodInfo( PREDEFMETH.PM_EXPRESSION_ARRAYINDEX, PredefinedType.PT_EXPRESSION, PredefinedName.PN_ARRAYINDEX, MethodCallingConventionEnum.Static, ACCESS.ACC_PUBLIC, 0, new int[] { (int)PredefinedType.PT_BINARYEXPRESSION, 2, (int)PredefinedType.PT_EXPRESSION, (int)PredefinedType.PT_EXPRESSION }),
+ new PredefinedMethodInfo( PREDEFMETH.PM_EXPRESSION_ARRAYINDEX2, PredefinedType.PT_EXPRESSION, PredefinedName.PN_ARRAYINDEX, MethodCallingConventionEnum.Static, ACCESS.ACC_PUBLIC, 0, new int[] { (int)PredefinedType.PT_METHODCALLEXPRESSION, 2, (int)PredefinedType.PT_EXPRESSION, (int)MethodSignatureEnum.SIG_SZ_ARRAY, (int)PredefinedType.PT_EXPRESSION }),
+ new PredefinedMethodInfo( PREDEFMETH.PM_EXPRESSION_ASSIGN, PredefinedType.PT_EXPRESSION, PredefinedName.PN_ASSIGN, MethodCallingConventionEnum.Static, ACCESS.ACC_PUBLIC, 0, new int[] { (int)PredefinedType.PT_BINARYEXPRESSION, 2, (int)PredefinedType.PT_EXPRESSION, (int)PredefinedType.PT_EXPRESSION }),
+ new PredefinedMethodInfo( PREDEFMETH.PM_EXPRESSION_CONDITION, PredefinedType.PT_EXPRESSION, PredefinedName.PN_CONDITION, MethodCallingConventionEnum.Static, ACCESS.ACC_PUBLIC, 0, new int[] { (int)PredefinedType.PT_CONDITIONALEXPRESSION, 3, (int)PredefinedType.PT_EXPRESSION, (int)PredefinedType.PT_EXPRESSION, (int)PredefinedType.PT_EXPRESSION }),
+ new PredefinedMethodInfo( PREDEFMETH.PM_EXPRESSION_CONSTANT_OBJECT_TYPE, PredefinedType.PT_EXPRESSION, PredefinedName.PN_CONSTANT, MethodCallingConventionEnum.Static, ACCESS.ACC_PUBLIC, 0, new int[] { (int)PredefinedType.PT_CONSTANTEXPRESSION, 2, (int)PredefinedType.PT_OBJECT, (int)PredefinedType.PT_TYPE }),
+ new PredefinedMethodInfo( PREDEFMETH.PM_EXPRESSION_CONVERT, PredefinedType.PT_EXPRESSION, PredefinedName.PN_CONVERT, MethodCallingConventionEnum.Static, ACCESS.ACC_PUBLIC, 0, new int[] { (int)PredefinedType.PT_UNARYEXPRESSION, 2, (int)PredefinedType.PT_EXPRESSION, (int)PredefinedType.PT_TYPE }),
+ new PredefinedMethodInfo( PREDEFMETH.PM_EXPRESSION_CONVERT_USER_DEFINED, PredefinedType.PT_EXPRESSION, PredefinedName.PN_CONVERT, MethodCallingConventionEnum.Static, ACCESS.ACC_PUBLIC, 0, new int[] { (int)PredefinedType.PT_UNARYEXPRESSION, 3, (int)PredefinedType.PT_EXPRESSION, (int)PredefinedType.PT_TYPE, (int)PredefinedType.PT_METHODINFO }),
+ new PredefinedMethodInfo( PREDEFMETH.PM_EXPRESSION_CONVERTCHECKED, PredefinedType.PT_EXPRESSION, PredefinedName.PN_CONVERTCHECKED, MethodCallingConventionEnum.Static, ACCESS.ACC_PUBLIC, 0, new int[] { (int)PredefinedType.PT_UNARYEXPRESSION, 2, (int)PredefinedType.PT_EXPRESSION, (int)PredefinedType.PT_TYPE }),
+ new PredefinedMethodInfo( PREDEFMETH.PM_EXPRESSION_CONVERTCHECKED_USER_DEFINED, PredefinedType.PT_EXPRESSION, PredefinedName.PN_CONVERTCHECKED, MethodCallingConventionEnum.Static, ACCESS.ACC_PUBLIC, 0, new int[] { (int)PredefinedType.PT_UNARYEXPRESSION, 3, (int)PredefinedType.PT_EXPRESSION, (int)PredefinedType.PT_TYPE, (int)PredefinedType.PT_METHODINFO }),
+ new PredefinedMethodInfo( PREDEFMETH.PM_EXPRESSION_DIVIDE, PredefinedType.PT_EXPRESSION, PredefinedName.PN_DIVIDE, MethodCallingConventionEnum.Static, ACCESS.ACC_PUBLIC, 0, new int[] { (int)PredefinedType.PT_BINARYEXPRESSION, 2, (int)PredefinedType.PT_EXPRESSION, (int)PredefinedType.PT_EXPRESSION }),
+ new PredefinedMethodInfo( PREDEFMETH.PM_EXPRESSION_DIVIDE_USER_DEFINED, PredefinedType.PT_EXPRESSION, PredefinedName.PN_DIVIDE, MethodCallingConventionEnum.Static, ACCESS.ACC_PUBLIC, 0, new int[] { (int)PredefinedType.PT_BINARYEXPRESSION, 3, (int)PredefinedType.PT_EXPRESSION, (int)PredefinedType.PT_EXPRESSION, (int)PredefinedType.PT_METHODINFO }),
+ new PredefinedMethodInfo( PREDEFMETH.PM_EXPRESSION_EQUAL, PredefinedType.PT_EXPRESSION, PredefinedName.PN_EQUAL, MethodCallingConventionEnum.Static, ACCESS.ACC_PUBLIC, 0, new int[] { (int)PredefinedType.PT_BINARYEXPRESSION, 2, (int)PredefinedType.PT_EXPRESSION, (int)PredefinedType.PT_EXPRESSION }),
+ new PredefinedMethodInfo( PREDEFMETH.PM_EXPRESSION_EQUAL_USER_DEFINED, PredefinedType.PT_EXPRESSION, PredefinedName.PN_EQUAL, MethodCallingConventionEnum.Static, ACCESS.ACC_PUBLIC, 0, new int[] { (int)PredefinedType.PT_BINARYEXPRESSION, 4, (int)PredefinedType.PT_EXPRESSION, (int)PredefinedType.PT_EXPRESSION, (int)PredefinedType.PT_BOOL, (int)PredefinedType.PT_METHODINFO }),
+ new PredefinedMethodInfo( PREDEFMETH.PM_EXPRESSION_EXCLUSIVEOR, PredefinedType.PT_EXPRESSION, PredefinedName.PN_EXCLUSIVEOR, MethodCallingConventionEnum.Static, ACCESS.ACC_PUBLIC, 0, new int[] { (int)PredefinedType.PT_BINARYEXPRESSION, 2, (int)PredefinedType.PT_EXPRESSION, (int)PredefinedType.PT_EXPRESSION }),
+ new PredefinedMethodInfo( PREDEFMETH.PM_EXPRESSION_EXCLUSIVEOR_USER_DEFINED, PredefinedType.PT_EXPRESSION, PredefinedName.PN_EXCLUSIVEOR, MethodCallingConventionEnum.Static, ACCESS.ACC_PUBLIC, 0, new int[] { (int)PredefinedType.PT_BINARYEXPRESSION, 3, (int)PredefinedType.PT_EXPRESSION, (int)PredefinedType.PT_EXPRESSION, (int)PredefinedType.PT_METHODINFO }),
+ new PredefinedMethodInfo( PREDEFMETH.PM_EXPRESSION_FIELD, PredefinedType.PT_EXPRESSION, PredefinedName.PN_CAP_FIELD, MethodCallingConventionEnum.Static, ACCESS.ACC_PUBLIC, 0, new int[] { (int)PredefinedType.PT_MEMBEREXPRESSION, 2, (int)PredefinedType.PT_EXPRESSION, (int)PredefinedType.PT_FIELDINFO }),
+ new PredefinedMethodInfo( PREDEFMETH.PM_EXPRESSION_GREATERTHAN, PredefinedType.PT_EXPRESSION, PredefinedName.PN_GREATERTHAN, MethodCallingConventionEnum.Static, ACCESS.ACC_PUBLIC, 0, new int[] { (int)PredefinedType.PT_BINARYEXPRESSION, 2, (int)PredefinedType.PT_EXPRESSION, (int)PredefinedType.PT_EXPRESSION }),
+ new PredefinedMethodInfo( PREDEFMETH.PM_EXPRESSION_GREATERTHAN_USER_DEFINED, PredefinedType.PT_EXPRESSION, PredefinedName.PN_GREATERTHAN, MethodCallingConventionEnum.Static, ACCESS.ACC_PUBLIC, 0, new int[] { (int)PredefinedType.PT_BINARYEXPRESSION, 4, (int)PredefinedType.PT_EXPRESSION, (int)PredefinedType.PT_EXPRESSION, (int)PredefinedType.PT_BOOL, (int)PredefinedType.PT_METHODINFO }),
+ new PredefinedMethodInfo( PREDEFMETH.PM_EXPRESSION_GREATERTHANOREQUAL, PredefinedType.PT_EXPRESSION, PredefinedName.PN_GREATERTHANOREQUAL, MethodCallingConventionEnum.Static, ACCESS.ACC_PUBLIC, 0, new int[] { (int)PredefinedType.PT_BINARYEXPRESSION, 2, (int)PredefinedType.PT_EXPRESSION, (int)PredefinedType.PT_EXPRESSION }),
+ new PredefinedMethodInfo( PREDEFMETH.PM_EXPRESSION_GREATERTHANOREQUAL_USER_DEFINED, PredefinedType.PT_EXPRESSION, PredefinedName.PN_GREATERTHANOREQUAL, MethodCallingConventionEnum.Static, ACCESS.ACC_PUBLIC, 0, new int[] { (int)PredefinedType.PT_BINARYEXPRESSION, 4, (int)PredefinedType.PT_EXPRESSION, (int)PredefinedType.PT_EXPRESSION, (int)PredefinedType.PT_BOOL, (int)PredefinedType.PT_METHODINFO }),
+ new PredefinedMethodInfo( PREDEFMETH.PM_EXPRESSION_LAMBDA, PredefinedType.PT_EXPRESSION, PredefinedName.PN_LAMBDA, MethodCallingConventionEnum.Static, ACCESS.ACC_PUBLIC, 1, new int[] { (int)PredefinedType.PT_G_EXPRESSION, (int)MethodSignatureEnum.SIG_METH_TYVAR, 0, 2, (int)PredefinedType.PT_EXPRESSION, (int)MethodSignatureEnum.SIG_SZ_ARRAY, (int)PredefinedType.PT_PARAMETEREXPRESSION }),
+ new PredefinedMethodInfo( PREDEFMETH.PM_EXPRESSION_LEFTSHIFT, PredefinedType.PT_EXPRESSION, PredefinedName.PN_LEFTSHIFT, MethodCallingConventionEnum.Static, ACCESS.ACC_PUBLIC, 0, new int[] { (int)PredefinedType.PT_BINARYEXPRESSION, 2, (int)PredefinedType.PT_EXPRESSION, (int)PredefinedType.PT_EXPRESSION }),
+ new PredefinedMethodInfo( PREDEFMETH.PM_EXPRESSION_LEFTSHIFT_USER_DEFINED, PredefinedType.PT_EXPRESSION, PredefinedName.PN_LEFTSHIFT, MethodCallingConventionEnum.Static, ACCESS.ACC_PUBLIC, 0, new int[] { (int)PredefinedType.PT_BINARYEXPRESSION, 3, (int)PredefinedType.PT_EXPRESSION, (int)PredefinedType.PT_EXPRESSION, (int)PredefinedType.PT_METHODINFO }),
+ new PredefinedMethodInfo( PREDEFMETH.PM_EXPRESSION_LESSTHAN, PredefinedType.PT_EXPRESSION, PredefinedName.PN_LESSTHAN, MethodCallingConventionEnum.Static, ACCESS.ACC_PUBLIC, 0, new int[] { (int)PredefinedType.PT_BINARYEXPRESSION, 2, (int)PredefinedType.PT_EXPRESSION, (int)PredefinedType.PT_EXPRESSION }),
+ new PredefinedMethodInfo( PREDEFMETH.PM_EXPRESSION_LESSTHAN_USER_DEFINED, PredefinedType.PT_EXPRESSION, PredefinedName.PN_LESSTHAN, MethodCallingConventionEnum.Static, ACCESS.ACC_PUBLIC, 0, new int[] { (int)PredefinedType.PT_BINARYEXPRESSION, 4, (int)PredefinedType.PT_EXPRESSION, (int)PredefinedType.PT_EXPRESSION, (int)PredefinedType.PT_BOOL, (int)PredefinedType.PT_METHODINFO }),
+ new PredefinedMethodInfo( PREDEFMETH.PM_EXPRESSION_LESSTHANOREQUAL, PredefinedType.PT_EXPRESSION, PredefinedName.PN_LESSTHANOREQUAL, MethodCallingConventionEnum.Static, ACCESS.ACC_PUBLIC, 0, new int[] { (int)PredefinedType.PT_BINARYEXPRESSION, 2, (int)PredefinedType.PT_EXPRESSION, (int)PredefinedType.PT_EXPRESSION }),
+ new PredefinedMethodInfo( PREDEFMETH.PM_EXPRESSION_LESSTHANOREQUAL_USER_DEFINED, PredefinedType.PT_EXPRESSION, PredefinedName.PN_LESSTHANOREQUAL, MethodCallingConventionEnum.Static, ACCESS.ACC_PUBLIC, 0, new int[] { (int)PredefinedType.PT_BINARYEXPRESSION, 4, (int)PredefinedType.PT_EXPRESSION, (int)PredefinedType.PT_EXPRESSION, (int)PredefinedType.PT_BOOL, (int)PredefinedType.PT_METHODINFO }),
+ new PredefinedMethodInfo( PREDEFMETH.PM_EXPRESSION_MODULO, PredefinedType.PT_EXPRESSION, PredefinedName.PN_MODULO, MethodCallingConventionEnum.Static, ACCESS.ACC_PUBLIC, 0, new int[] { (int)PredefinedType.PT_BINARYEXPRESSION, 2, (int)PredefinedType.PT_EXPRESSION, (int)PredefinedType.PT_EXPRESSION }),
+ new PredefinedMethodInfo( PREDEFMETH.PM_EXPRESSION_MODULO_USER_DEFINED, PredefinedType.PT_EXPRESSION, PredefinedName.PN_MODULO, MethodCallingConventionEnum.Static, ACCESS.ACC_PUBLIC, 0, new int[] { (int)PredefinedType.PT_BINARYEXPRESSION, 3, (int)PredefinedType.PT_EXPRESSION, (int)PredefinedType.PT_EXPRESSION, (int)PredefinedType.PT_METHODINFO }),
+ new PredefinedMethodInfo( PREDEFMETH.PM_EXPRESSION_MULTIPLY, PredefinedType.PT_EXPRESSION, PredefinedName.PN_MULTIPLY, MethodCallingConventionEnum.Static, ACCESS.ACC_PUBLIC, 0, new int[] { (int)PredefinedType.PT_BINARYEXPRESSION, 2, (int)PredefinedType.PT_EXPRESSION, (int)PredefinedType.PT_EXPRESSION }),
+ new PredefinedMethodInfo( PREDEFMETH.PM_EXPRESSION_MULTIPLY_USER_DEFINED, PredefinedType.PT_EXPRESSION, PredefinedName.PN_MULTIPLY, MethodCallingConventionEnum.Static, ACCESS.ACC_PUBLIC, 0, new int[] { (int)PredefinedType.PT_BINARYEXPRESSION, 3, (int)PredefinedType.PT_EXPRESSION, (int)PredefinedType.PT_EXPRESSION, (int)PredefinedType.PT_METHODINFO }),
+ new PredefinedMethodInfo( PREDEFMETH.PM_EXPRESSION_MULTIPLYCHECKED, PredefinedType.PT_EXPRESSION, PredefinedName.PN_MULTIPLYCHECKED, MethodCallingConventionEnum.Static, ACCESS.ACC_PUBLIC, 0, new int[] { (int)PredefinedType.PT_BINARYEXPRESSION, 2, (int)PredefinedType.PT_EXPRESSION, (int)PredefinedType.PT_EXPRESSION }),
+ new PredefinedMethodInfo( PREDEFMETH.PM_EXPRESSION_MULTIPLYCHECKED_USER_DEFINED, PredefinedType.PT_EXPRESSION, PredefinedName.PN_MULTIPLYCHECKED, MethodCallingConventionEnum.Static, ACCESS.ACC_PUBLIC, 0, new int[] { (int)PredefinedType.PT_BINARYEXPRESSION, 3, (int)PredefinedType.PT_EXPRESSION, (int)PredefinedType.PT_EXPRESSION, (int)PredefinedType.PT_METHODINFO }),
+ new PredefinedMethodInfo( PREDEFMETH.PM_EXPRESSION_NOTEQUAL, PredefinedType.PT_EXPRESSION, PredefinedName.PN_NOTEQUAL, MethodCallingConventionEnum.Static, ACCESS.ACC_PUBLIC, 0, new int[] { (int)PredefinedType.PT_BINARYEXPRESSION, 2, (int)PredefinedType.PT_EXPRESSION, (int)PredefinedType.PT_EXPRESSION }),
+ new PredefinedMethodInfo( PREDEFMETH.PM_EXPRESSION_NOTEQUAL_USER_DEFINED, PredefinedType.PT_EXPRESSION, PredefinedName.PN_NOTEQUAL, MethodCallingConventionEnum.Static, ACCESS.ACC_PUBLIC, 0, new int[] { (int)PredefinedType.PT_BINARYEXPRESSION, 4, (int)PredefinedType.PT_EXPRESSION, (int)PredefinedType.PT_EXPRESSION, (int)PredefinedType.PT_BOOL, (int)PredefinedType.PT_METHODINFO }),
+ new PredefinedMethodInfo( PREDEFMETH.PM_EXPRESSION_OR, PredefinedType.PT_EXPRESSION, PredefinedName.PN_OR, MethodCallingConventionEnum.Static, ACCESS.ACC_PUBLIC, 0, new int[] { (int)PredefinedType.PT_BINARYEXPRESSION, 2, (int)PredefinedType.PT_EXPRESSION, (int)PredefinedType.PT_EXPRESSION }),
+ new PredefinedMethodInfo( PREDEFMETH.PM_EXPRESSION_OR_USER_DEFINED, PredefinedType.PT_EXPRESSION, PredefinedName.PN_OR, MethodCallingConventionEnum.Static, ACCESS.ACC_PUBLIC, 0, new int[] { (int)PredefinedType.PT_BINARYEXPRESSION, 3, (int)PredefinedType.PT_EXPRESSION, (int)PredefinedType.PT_EXPRESSION, (int)PredefinedType.PT_METHODINFO }),
+ new PredefinedMethodInfo( PREDEFMETH.PM_EXPRESSION_ORELSE, PredefinedType.PT_EXPRESSION, PredefinedName.PN_ORELSE, MethodCallingConventionEnum.Static, ACCESS.ACC_PUBLIC, 0, new int[] { (int)PredefinedType.PT_BINARYEXPRESSION, 2, (int)PredefinedType.PT_EXPRESSION, (int)PredefinedType.PT_EXPRESSION }),
+ new PredefinedMethodInfo( PREDEFMETH.PM_EXPRESSION_ORELSE_USER_DEFINED, PredefinedType.PT_EXPRESSION, PredefinedName.PN_ORELSE, MethodCallingConventionEnum.Static, ACCESS.ACC_PUBLIC, 0, new int[] { (int)PredefinedType.PT_BINARYEXPRESSION, 3, (int)PredefinedType.PT_EXPRESSION, (int)PredefinedType.PT_EXPRESSION, (int)PredefinedType.PT_METHODINFO }),
+ new PredefinedMethodInfo( PREDEFMETH.PM_EXPRESSION_PARAMETER, PredefinedType.PT_EXPRESSION, PredefinedName.PN_PARAMETER, MethodCallingConventionEnum.Static, ACCESS.ACC_PUBLIC, 0, new int[] { (int)PredefinedType.PT_PARAMETEREXPRESSION, 2, (int)PredefinedType.PT_TYPE, (int)PredefinedType.PT_STRING }),
+ new PredefinedMethodInfo( PREDEFMETH.PM_EXPRESSION_RIGHTSHIFT, PredefinedType.PT_EXPRESSION, PredefinedName.PN_RIGHTSHIFT, MethodCallingConventionEnum.Static, ACCESS.ACC_PUBLIC, 0, new int[] { (int)PredefinedType.PT_BINARYEXPRESSION, 2, (int)PredefinedType.PT_EXPRESSION, (int)PredefinedType.PT_EXPRESSION }),
+ new PredefinedMethodInfo( PREDEFMETH.PM_EXPRESSION_RIGHTSHIFT_USER_DEFINED, PredefinedType.PT_EXPRESSION, PredefinedName.PN_RIGHTSHIFT, MethodCallingConventionEnum.Static, ACCESS.ACC_PUBLIC, 0, new int[] { (int)PredefinedType.PT_BINARYEXPRESSION, 3, (int)PredefinedType.PT_EXPRESSION, (int)PredefinedType.PT_EXPRESSION, (int)PredefinedType.PT_METHODINFO }),
+ new PredefinedMethodInfo( PREDEFMETH.PM_EXPRESSION_SUBTRACT, PredefinedType.PT_EXPRESSION, PredefinedName.PN_SUBTRACT, MethodCallingConventionEnum.Static, ACCESS.ACC_PUBLIC, 0, new int[] { (int)PredefinedType.PT_BINARYEXPRESSION, 2, (int)PredefinedType.PT_EXPRESSION, (int)PredefinedType.PT_EXPRESSION }),
+ new PredefinedMethodInfo( PREDEFMETH.PM_EXPRESSION_SUBTRACT_USER_DEFINED, PredefinedType.PT_EXPRESSION, PredefinedName.PN_SUBTRACT, MethodCallingConventionEnum.Static, ACCESS.ACC_PUBLIC, 0, new int[] { (int)PredefinedType.PT_BINARYEXPRESSION, 3, (int)PredefinedType.PT_EXPRESSION, (int)PredefinedType.PT_EXPRESSION, (int)PredefinedType.PT_METHODINFO }),
+ new PredefinedMethodInfo( PREDEFMETH.PM_EXPRESSION_SUBTRACTCHECKED, PredefinedType.PT_EXPRESSION, PredefinedName.PN_SUBTRACTCHECKED, MethodCallingConventionEnum.Static, ACCESS.ACC_PUBLIC, 0, new int[] { (int)PredefinedType.PT_BINARYEXPRESSION, 2, (int)PredefinedType.PT_EXPRESSION, (int)PredefinedType.PT_EXPRESSION }),
+ new PredefinedMethodInfo( PREDEFMETH.PM_EXPRESSION_SUBTRACTCHECKED_USER_DEFINED, PredefinedType.PT_EXPRESSION, PredefinedName.PN_SUBTRACTCHECKED, MethodCallingConventionEnum.Static, ACCESS.ACC_PUBLIC, 0, new int[] { (int)PredefinedType.PT_BINARYEXPRESSION, 3, (int)PredefinedType.PT_EXPRESSION, (int)PredefinedType.PT_EXPRESSION, (int)PredefinedType.PT_METHODINFO }),
+ new PredefinedMethodInfo( PREDEFMETH.PM_EXPRESSION_UNARYPLUS_USER_DEFINED, PredefinedType.PT_EXPRESSION, PredefinedName.PN_PLUS , MethodCallingConventionEnum.Static, ACCESS.ACC_PUBLIC, 0, new int[] { (int)PredefinedType.PT_UNARYEXPRESSION, 2, (int)PredefinedType.PT_EXPRESSION, (int)PredefinedType.PT_METHODINFO }),
+ new PredefinedMethodInfo( PREDEFMETH.PM_EXPRESSION_NEGATE, PredefinedType.PT_EXPRESSION, PredefinedName.PN_NEGATE, MethodCallingConventionEnum.Static, ACCESS.ACC_PUBLIC, 0, new int[] { (int)PredefinedType.PT_UNARYEXPRESSION, 1, (int)PredefinedType.PT_EXPRESSION }),
+ new PredefinedMethodInfo( PREDEFMETH.PM_EXPRESSION_NEGATE_USER_DEFINED, PredefinedType.PT_EXPRESSION, PredefinedName.PN_NEGATE, MethodCallingConventionEnum.Static, ACCESS.ACC_PUBLIC, 0, new int[] { (int)PredefinedType.PT_UNARYEXPRESSION, 2, (int)PredefinedType.PT_EXPRESSION, (int)PredefinedType.PT_METHODINFO }),
+ new PredefinedMethodInfo( PREDEFMETH.PM_EXPRESSION_NEGATECHECKED, PredefinedType.PT_EXPRESSION, PredefinedName.PN_NEGATECHECKED, MethodCallingConventionEnum.Static, ACCESS.ACC_PUBLIC, 0, new int[] { (int)PredefinedType.PT_UNARYEXPRESSION, 1, (int)PredefinedType.PT_EXPRESSION }),
+ new PredefinedMethodInfo( PREDEFMETH.PM_EXPRESSION_NEGATECHECKED_USER_DEFINED, PredefinedType.PT_EXPRESSION, PredefinedName.PN_NEGATECHECKED, MethodCallingConventionEnum.Static, ACCESS.ACC_PUBLIC, 0, new int[] { (int)PredefinedType.PT_UNARYEXPRESSION, 2, (int)PredefinedType.PT_EXPRESSION, (int)PredefinedType.PT_METHODINFO }),
+ new PredefinedMethodInfo( PREDEFMETH.PM_EXPRESSION_CALL, PredefinedType.PT_EXPRESSION, PredefinedName.PN_CALL, MethodCallingConventionEnum.Static, ACCESS.ACC_PUBLIC, 0, new int[] { (int)PredefinedType.PT_METHODCALLEXPRESSION, 3, (int)PredefinedType.PT_EXPRESSION, (int)PredefinedType.PT_METHODINFO, (int)MethodSignatureEnum.SIG_SZ_ARRAY, (int)PredefinedType.PT_EXPRESSION }),
+ new PredefinedMethodInfo( PREDEFMETH.PM_EXPRESSION_NEW, PredefinedType.PT_EXPRESSION, PredefinedName.PN_NEW, MethodCallingConventionEnum.Static, ACCESS.ACC_PUBLIC, 0, new int[] { (int)PredefinedType.PT_NEWEXPRESSION, 2, (int)PredefinedType.PT_CONSTRUCTORINFO, (int)MethodSignatureEnum.SIG_SZ_ARRAY, (int)PredefinedType.PT_EXPRESSION }),
+ new PredefinedMethodInfo( PREDEFMETH.PM_EXPRESSION_NEW_MEMBERS, PredefinedType.PT_EXPRESSION, PredefinedName.PN_NEW, MethodCallingConventionEnum.Static, ACCESS.ACC_PUBLIC, 0, new int[] { (int)PredefinedType.PT_NEWEXPRESSION, 3, (int)PredefinedType.PT_CONSTRUCTORINFO, (int)PredefinedType.PT_G_IENUMERABLE, (int)PredefinedType.PT_EXPRESSION, (int)MethodSignatureEnum.SIG_SZ_ARRAY, (int)PredefinedType.PT_MEMBERINFO }),
+ new PredefinedMethodInfo( PREDEFMETH.PM_EXPRESSION_NEW_TYPE, PredefinedType.PT_EXPRESSION, PredefinedName.PN_NEW, MethodCallingConventionEnum.Static, ACCESS.ACC_PUBLIC, 0, new int[] { (int)PredefinedType.PT_NEWEXPRESSION, 1, (int)PredefinedType.PT_TYPE }),
+ new PredefinedMethodInfo( PREDEFMETH.PM_EXPRESSION_QUOTE, PredefinedType.PT_EXPRESSION, PredefinedName.PN_QUOTE, MethodCallingConventionEnum.Static, ACCESS.ACC_PUBLIC, 0, new int[] { (int)PredefinedType.PT_UNARYEXPRESSION, 1, (int)PredefinedType.PT_EXPRESSION }),
+ new PredefinedMethodInfo( PREDEFMETH.PM_EXPRESSION_ARRAYLENGTH, PredefinedType.PT_EXPRESSION, PredefinedName.PN_ARRAYLENGTH, MethodCallingConventionEnum.Static, ACCESS.ACC_PUBLIC, 0, new int[] { (int)PredefinedType.PT_UNARYEXPRESSION, 1, (int)PredefinedType.PT_EXPRESSION }),
+ new PredefinedMethodInfo( PREDEFMETH.PM_EXPRESSION_NOT, PredefinedType.PT_EXPRESSION, PredefinedName.PN_NOT, MethodCallingConventionEnum.Static, ACCESS.ACC_PUBLIC, 0, new int[] { (int)PredefinedType.PT_UNARYEXPRESSION, 1, (int)PredefinedType.PT_EXPRESSION }),
+ new PredefinedMethodInfo( PREDEFMETH.PM_EXPRESSION_NOT_USER_DEFINED, PredefinedType.PT_EXPRESSION, PredefinedName.PN_NOT, MethodCallingConventionEnum.Static, ACCESS.ACC_PUBLIC, 0, new int[] { (int)PredefinedType.PT_UNARYEXPRESSION, 2, (int)PredefinedType.PT_EXPRESSION, (int)PredefinedType.PT_METHODINFO }),
+ new PredefinedMethodInfo( PREDEFMETH.PM_EXPRESSION_NEWARRAYINIT, PredefinedType.PT_EXPRESSION, PredefinedName.PN_NEWARRAYINIT, MethodCallingConventionEnum.Static, ACCESS.ACC_PUBLIC, 0, new int[] { (int)PredefinedType.PT_NEWARRAYEXPRESSION, 2, (int)PredefinedType.PT_TYPE, (int)MethodSignatureEnum.SIG_SZ_ARRAY, (int)PredefinedType.PT_EXPRESSION }),
+ new PredefinedMethodInfo( PREDEFMETH.PM_EXPRESSION_PROPERTY, PredefinedType.PT_EXPRESSION, PredefinedName.PN_EXPRESSION_PROPERTY, MethodCallingConventionEnum.Static, ACCESS.ACC_PUBLIC, 0, new int[] { (int)PredefinedType.PT_MEMBEREXPRESSION, 2, (int)PredefinedType.PT_EXPRESSION, (int)PredefinedType.PT_PROPERTYINFO }),
+ new PredefinedMethodInfo( PREDEFMETH.PM_EXPRESSION_INVOKE, PredefinedType.PT_EXPRESSION, PredefinedName.PN_INVOKE, MethodCallingConventionEnum.Static, ACCESS.ACC_PUBLIC, 0, new int[] { (int)PredefinedType.PT_INVOCATIONEXPRESSION, 2, (int)PredefinedType.PT_EXPRESSION, (int)MethodSignatureEnum.SIG_SZ_ARRAY, (int)PredefinedType.PT_EXPRESSION }),
+ new PredefinedMethodInfo( PREDEFMETH.PM_METHODINFO_CREATEDELEGATE_TYPE_OBJECT, PredefinedType.PT_METHODINFO, PredefinedName.PN_CREATEDELEGATE, MethodCallingConventionEnum.Virtual, ACCESS.ACC_PUBLIC, 0, new int[] { (int)PredefinedType.PT_DELEGATE, 2, (int)PredefinedType.PT_TYPE, (int)PredefinedType.PT_OBJECT}),
+ new PredefinedMethodInfo( PREDEFMETH.PM_G_OPTIONAL_CTOR, PredefinedType.PT_G_OPTIONAL, PredefinedName.PN_CTOR, MethodCallingConventionEnum.Instance, ACCESS.ACC_PUBLIC, 0, new int[] { (int)PredefinedType.PT_VOID, 1, (int)MethodSignatureEnum.SIG_CLASS_TYVAR, 0 }),
+ new PredefinedMethodInfo( PREDEFMETH.PM_G_OPTIONAL_GETHASVALUE, PredefinedType.PT_G_OPTIONAL, PredefinedName.PN_GETHASVALUE, MethodCallingConventionEnum.Instance, ACCESS.ACC_PUBLIC, 0, new int[] { (int)PredefinedType.PT_BOOL, 0 }),
+ new PredefinedMethodInfo( PREDEFMETH.PM_G_OPTIONAL_GETVALUE, PredefinedType.PT_G_OPTIONAL, PredefinedName.PN_GETVALUE, MethodCallingConventionEnum.Instance, ACCESS.ACC_PUBLIC, 0, new int[] { (int)MethodSignatureEnum.SIG_CLASS_TYVAR, 0, 0 }),
+ new PredefinedMethodInfo( PREDEFMETH.PM_G_OPTIONAL_GET_VALUE_OR_DEF, PredefinedType.PT_G_OPTIONAL, PredefinedName.PN_GET_VALUE_OR_DEF, MethodCallingConventionEnum.Instance, ACCESS.ACC_PUBLIC, 0, new int[] { (int)MethodSignatureEnum.SIG_CLASS_TYVAR, 0, 0 }),
+ new PredefinedMethodInfo( PREDEFMETH.PM_STRING_CONCAT_OBJECT_1, PredefinedType.PT_STRING, PredefinedName.PN_CONCAT, MethodCallingConventionEnum.Static, ACCESS.ACC_PUBLIC, 0, new int[] { (int)PredefinedType.PT_STRING, 1, (int)PredefinedType.PT_OBJECT }),
+ new PredefinedMethodInfo( PREDEFMETH.PM_STRING_CONCAT_OBJECT_2, PredefinedType.PT_STRING, PredefinedName.PN_CONCAT, MethodCallingConventionEnum.Static, ACCESS.ACC_PUBLIC, 0, new int[] { (int)PredefinedType.PT_STRING, 2, (int)PredefinedType.PT_OBJECT, (int)PredefinedType.PT_OBJECT }),
+ new PredefinedMethodInfo( PREDEFMETH.PM_STRING_CONCAT_OBJECT_3, PredefinedType.PT_STRING, PredefinedName.PN_CONCAT, MethodCallingConventionEnum.Static, ACCESS.ACC_PUBLIC, 0, new int[] { (int)PredefinedType.PT_STRING, 3, (int)PredefinedType.PT_OBJECT, (int)PredefinedType.PT_OBJECT, (int)PredefinedType.PT_OBJECT }),
+ new PredefinedMethodInfo( PREDEFMETH.PM_STRING_CONCAT_STRING_1, PredefinedType.PT_STRING, PredefinedName.PN_CONCAT, MethodCallingConventionEnum.Static, ACCESS.ACC_PUBLIC, 0, new int[] { (int)PredefinedType.PT_STRING, 1, (int)PredefinedType.PT_STRING }),
+ new PredefinedMethodInfo( PREDEFMETH.PM_STRING_CONCAT_STRING_2, PredefinedType.PT_STRING, PredefinedName.PN_CONCAT, MethodCallingConventionEnum.Static, ACCESS.ACC_PUBLIC, 0, new int[] { (int)PredefinedType.PT_STRING, 2, (int)PredefinedType.PT_STRING, (int)PredefinedType.PT_STRING }),
+ new PredefinedMethodInfo( PREDEFMETH.PM_STRING_CONCAT_STRING_3, PredefinedType.PT_STRING, PredefinedName.PN_CONCAT, MethodCallingConventionEnum.Static, ACCESS.ACC_PUBLIC, 0, new int[] { (int)PredefinedType.PT_STRING, 3, (int)PredefinedType.PT_STRING, (int)PredefinedType.PT_STRING, (int)PredefinedType.PT_STRING }),
+ new PredefinedMethodInfo( PREDEFMETH.PM_STRING_CONCAT_STRING_4, PredefinedType.PT_STRING, PredefinedName.PN_CONCAT, MethodCallingConventionEnum.Static, ACCESS.ACC_PUBLIC, 0, new int[] { (int)PredefinedType.PT_STRING, 4, (int)PredefinedType.PT_STRING, (int)PredefinedType.PT_STRING, (int)PredefinedType.PT_STRING, (int)PredefinedType.PT_STRING }),
+ new PredefinedMethodInfo( PREDEFMETH.PM_STRING_CONCAT_SZ_OBJECT, PredefinedType.PT_STRING, PredefinedName.PN_CONCAT, MethodCallingConventionEnum.Static, ACCESS.ACC_PUBLIC, 0, new int[] { (int)PredefinedType.PT_STRING, 1, (int)MethodSignatureEnum.SIG_SZ_ARRAY, (int)PredefinedType.PT_OBJECT }),
+ new PredefinedMethodInfo( PREDEFMETH.PM_STRING_CONCAT_SZ_STRING, PredefinedType.PT_STRING, PredefinedName.PN_CONCAT, MethodCallingConventionEnum.Static, ACCESS.ACC_PUBLIC, 0, new int[] { (int)PredefinedType.PT_STRING, 1, (int)MethodSignatureEnum.SIG_SZ_ARRAY, (int)PredefinedType.PT_STRING }),
+ new PredefinedMethodInfo( PREDEFMETH.PM_STRING_GETCHARS, PredefinedType.PT_STRING, PredefinedName.PN_GETCHARS, MethodCallingConventionEnum.Instance, ACCESS.ACC_PUBLIC, 0, new int[] { (int)PredefinedType.PT_CHAR, 1, (int)PredefinedType.PT_INT }),
+ new PredefinedMethodInfo( PREDEFMETH.PM_STRING_GETLENGTH, PredefinedType.PT_STRING, PredefinedName.PN_GETLENGTH, MethodCallingConventionEnum.Instance, ACCESS.ACC_PUBLIC, 0, new int[] { (int)PredefinedType.PT_INT, 0, }),
+ new PredefinedMethodInfo( PREDEFMETH.PM_STRING_OPEQUALITY, PredefinedType.PT_STRING, PredefinedName.PN_OPEQUALITY, MethodCallingConventionEnum.Static, ACCESS.ACC_PUBLIC, 0, new int[] { (int)PredefinedType.PT_BOOL, 2, (int)PredefinedType.PT_STRING, (int)PredefinedType.PT_STRING }),
+ new PredefinedMethodInfo( PREDEFMETH.PM_STRING_OPINEQUALITY, PredefinedType.PT_STRING, PredefinedName.PN_OPINEQUALITY, MethodCallingConventionEnum.Static, ACCESS.ACC_PUBLIC, 0, new int[] { (int)PredefinedType.PT_BOOL, 2, (int)PredefinedType.PT_STRING, (int)PredefinedType.PT_STRING }),
};
}
}
diff --git a/src/Microsoft.CSharp/src/Microsoft/CSharp/RuntimeBinder/Semantics/Tree/Visitors/ExpressionTreeRewriter.cs b/src/Microsoft.CSharp/src/Microsoft/CSharp/RuntimeBinder/Semantics/Tree/Visitors/ExpressionTreeRewriter.cs
index 8a841ee5d9..5c7a70866a 100644
--- a/src/Microsoft.CSharp/src/Microsoft/CSharp/RuntimeBinder/Semantics/Tree/Visitors/ExpressionTreeRewriter.cs
+++ b/src/Microsoft.CSharp/src/Microsoft/CSharp/RuntimeBinder/Semantics/Tree/Visitors/ExpressionTreeRewriter.cs
@@ -12,14 +12,12 @@ namespace Microsoft.CSharp.RuntimeBinder.Semantics
public static Expr Rewrite(Expr expr, ExprFactory expressionFactory, SymbolLoader symbolLoader)
{
ExpressionTreeRewriter rewriter = new ExpressionTreeRewriter(expressionFactory, symbolLoader);
- rewriter.alwaysRewrite = true;
return rewriter.Visit(expr);
}
private ExprFactory expressionFactory;
private SymbolLoader symbolLoader;
private ExprBoundLambda currentAnonMeth;
- private bool alwaysRewrite;
private ExprFactory GetExprFactory() { return expressionFactory; }
@@ -29,7 +27,6 @@ namespace Microsoft.CSharp.RuntimeBinder.Semantics
{
this.expressionFactory = expressionFactory;
this.symbolLoader = symbolLoader;
- this.alwaysRewrite = false;
}
protected override Expr Dispatch(Expr expr)
@@ -49,7 +46,6 @@ namespace Microsoft.CSharp.RuntimeBinder.Semantics
protected override Expr VisitASSIGNMENT(ExprAssignment assignment)
{
Debug.Assert(assignment != null);
- Debug.Assert(alwaysRewrite || currentAnonMeth != null);
// For assignments, we either have a member assignment or an indexed assignment.
//Debug.Assert(assignment.GetLHS().isPROP() || assignment.GetLHS().isFIELD() || assignment.GetLHS().isARRAYINDEX() || assignment.GetLHS().isLOCAL());
@@ -138,13 +134,11 @@ namespace Microsoft.CSharp.RuntimeBinder.Semantics
protected override Expr VisitCONSTANT(ExprConstant expr)
{
Debug.Assert(expr != null);
- Debug.Assert(alwaysRewrite || currentAnonMeth != null);
return GenerateConstant(expr);
}
protected override Expr VisitLOCAL(ExprLocal local)
{
Debug.Assert(local != null);
- Debug.Assert(alwaysRewrite || currentAnonMeth != null);
Debug.Assert(!local.Local.isThis);
// this is true for all parameters of an expression lambda
if (local.Local.wrap != null)
@@ -172,13 +166,11 @@ namespace Microsoft.CSharp.RuntimeBinder.Semantics
protected override Expr VisitUSERDEFINEDCONVERSION(ExprUserDefinedConversion expr)
{
Debug.Assert(expr != null);
- Debug.Assert(alwaysRewrite || currentAnonMeth != null);
return GenerateUserDefinedConversion(expr, expr.Argument);
}
protected override Expr VisitCAST(ExprCast pExpr)
{
Debug.Assert(pExpr != null);
- Debug.Assert(alwaysRewrite || currentAnonMeth != null);
Expr pArgument = pExpr.Argument;
@@ -211,7 +203,6 @@ namespace Microsoft.CSharp.RuntimeBinder.Semantics
protected override Expr VisitCONCAT(ExprConcat expr)
{
Debug.Assert(expr != null);
- Debug.Assert(alwaysRewrite || currentAnonMeth != null);
PREDEFMETH pdm;
if (expr.FirstArgument.Type.isPredefType(PredefinedType.PT_STRING) && expr.SecondArgument.Type.isPredefType(PredefinedType.PT_STRING))
{
@@ -230,7 +221,6 @@ namespace Microsoft.CSharp.RuntimeBinder.Semantics
protected override Expr VisitBINOP(ExprBinOp expr)
{
Debug.Assert(expr != null);
- Debug.Assert(alwaysRewrite || currentAnonMeth != null);
if (expr.UserDefinedCallMethod != null)
{
return GenerateUserDefinedBinaryOperator(expr);
@@ -243,7 +233,6 @@ namespace Microsoft.CSharp.RuntimeBinder.Semantics
protected override Expr VisitUNARYOP(ExprUnaryOp pExpr)
{
Debug.Assert(pExpr != null);
- Debug.Assert(alwaysRewrite || currentAnonMeth != null);
if (pExpr.UserDefinedCallMethod != null)
{
return GenerateUserDefinedUnaryOperator(pExpr);
@@ -256,7 +245,6 @@ namespace Microsoft.CSharp.RuntimeBinder.Semantics
protected override Expr VisitARRAYINDEX(ExprArrayIndex pExpr)
{
Debug.Assert(pExpr != null);
- Debug.Assert(alwaysRewrite || currentAnonMeth != null);
Expr arr = Visit(pExpr.Array);
Expr args = GenerateIndexList(pExpr.Index);
if (args is ExprList)
@@ -270,8 +258,6 @@ namespace Microsoft.CSharp.RuntimeBinder.Semantics
protected override Expr VisitCALL(ExprCall expr)
{
Debug.Assert(expr != null);
- Debug.Assert(alwaysRewrite || currentAnonMeth != null);
-
switch (expr.NullableCallLiftKind)
{
default:
@@ -335,7 +321,6 @@ namespace Microsoft.CSharp.RuntimeBinder.Semantics
protected override Expr VisitPROP(ExprProperty expr)
{
Debug.Assert(expr != null);
- Debug.Assert(alwaysRewrite || currentAnonMeth != null);
Expr pObject;
if (expr.PropWithTypeSlot.Prop().isStatic || expr.MemberGroup.OptionalObject== null)
{
@@ -358,7 +343,6 @@ namespace Microsoft.CSharp.RuntimeBinder.Semantics
protected override Expr VisitARRINIT(ExprArrayInit expr)
{
Debug.Assert(expr != null);
- Debug.Assert(alwaysRewrite || currentAnonMeth != null);
// POSSIBLE ERROR: Multi-d should be an error?
Expr pTypeOf = CreateTypeOf(expr.Type.AsArrayType().GetElementType());
Expr args = GenerateArgsList(expr.OptionalArguments);
@@ -368,7 +352,6 @@ namespace Microsoft.CSharp.RuntimeBinder.Semantics
protected override Expr VisitZEROINIT(ExprZeroInit expr)
{
Debug.Assert(expr != null);
- Debug.Assert(alwaysRewrite || currentAnonMeth != null);
Debug.Assert(expr.OptionalArgument == null);
if (expr.IsConstructor)
@@ -382,7 +365,6 @@ namespace Microsoft.CSharp.RuntimeBinder.Semantics
protected override Expr VisitTYPEOF(ExprTypeOf expr)
{
Debug.Assert(expr != null);
- Debug.Assert(alwaysRewrite || currentAnonMeth != null);
return GenerateConstant(expr);
}
@@ -402,7 +384,6 @@ namespace Microsoft.CSharp.RuntimeBinder.Semantics
private Expr GenerateBuiltInBinaryOperator(ExprBinOp expr)
{
Debug.Assert(expr != null);
- Debug.Assert(alwaysRewrite || currentAnonMeth != null);
PREDEFMETH pdm;
switch (expr.Kind)
@@ -511,7 +492,6 @@ namespace Microsoft.CSharp.RuntimeBinder.Semantics
private Expr GenerateBuiltInUnaryOperator(ExprUnaryOp expr)
{
Debug.Assert(expr != null);
- Debug.Assert(alwaysRewrite || currentAnonMeth != null);
PREDEFMETH pdm;
switch (expr.Kind)
{
@@ -552,7 +532,6 @@ namespace Microsoft.CSharp.RuntimeBinder.Semantics
private Expr GenerateUserDefinedBinaryOperator(ExprBinOp expr)
{
Debug.Assert(expr != null);
- Debug.Assert(alwaysRewrite || currentAnonMeth != null);
PREDEFMETH pdm;
switch (expr.Kind)
@@ -632,7 +611,6 @@ namespace Microsoft.CSharp.RuntimeBinder.Semantics
private Expr GenerateUserDefinedUnaryOperator(ExprUnaryOp expr)
{
Debug.Assert(expr != null);
- Debug.Assert(alwaysRewrite || currentAnonMeth != null);
PREDEFMETH pdm;
Expr arg = expr.Child;
ExprCall call = (ExprCall)expr.OptionalUserDefinedCall;
@@ -683,7 +661,6 @@ namespace Microsoft.CSharp.RuntimeBinder.Semantics
private Expr GenerateUserDefinedComparisonOperator(ExprBinOp expr)
{
Debug.Assert(expr != null);
- Debug.Assert(alwaysRewrite || currentAnonMeth != null);
PREDEFMETH pdm;
switch (expr.Kind)
diff --git a/src/Microsoft.CSharp/src/Microsoft/CSharp/RuntimeBinder/SymbolTable.cs b/src/Microsoft.CSharp/src/Microsoft/CSharp/RuntimeBinder/SymbolTable.cs
index 2063e0fff3..0d2e9eca93 100644
--- a/src/Microsoft.CSharp/src/Microsoft/CSharp/RuntimeBinder/SymbolTable.cs
+++ b/src/Microsoft.CSharp/src/Microsoft/CSharp/RuntimeBinder/SymbolTable.cs
@@ -1133,7 +1133,7 @@ namespace Microsoft.CSharp.RuntimeBinder
agg.SetTypeManager(_typeManager);
agg.SetFirstUDConversion(null);
SetInterfacesOnAggregate(agg, type);
- agg.SetHasPubNoArgCtor(Enumerable.Any(type.GetConstructors(), c => c.GetParameters().Length == 0));
+ agg.SetHasPubNoArgCtor(type.GetConstructor(Type.EmptyTypes) != null);
// If we have a delegate, get its invoke and constructor methods as well.
if (agg.IsDelegate())
@@ -1513,9 +1513,7 @@ namespace Microsoft.CSharp.RuntimeBinder
// Check if we have constructors or not.
if (methodName == NameManager.GetPredefinedName(PredefinedName.PN_CTOR))
{
- var ctors = Enumerable.Where(t.GetConstructors(), m => m.Name == methodName.Text);
-
- foreach (ConstructorInfo c in ctors)
+ foreach (ConstructorInfo c in t.GetConstructors())
{
AddMethodToSymbolTable(
c,
diff --git a/src/Microsoft.VisualBasic/pkg/Microsoft.VisualBasic.pkgproj b/src/Microsoft.VisualBasic/pkg/Microsoft.VisualBasic.pkgproj
index d9a3982a23..cdca494df9 100644
--- a/src/Microsoft.VisualBasic/pkg/Microsoft.VisualBasic.pkgproj
+++ b/src/Microsoft.VisualBasic/pkg/Microsoft.VisualBasic.pkgproj
@@ -13,7 +13,7 @@
<HarvestIncludePaths Include="ref/netstandard1.1" />
<HarvestIncludePaths Include="lib/netstandard1.3" />
<InboxOnTargetFramework Include="netcoreapp2.0" />
- <InboxOnTargetFramework Include="uap10.1" />
+ <InboxOnTargetFramework Include="$(UAPvNextTFM)" />
<InboxOnTargetFramework Include="win8" />
<InboxOnTargetFramework Include="wpa81" />
<InboxOnTargetFramework Include="portable-net45+win8+wpa81" />
diff --git a/src/Microsoft.VisualBasic/tests/Microsoft.VisualBasic.Tests.csproj b/src/Microsoft.VisualBasic/tests/Microsoft.VisualBasic.Tests.csproj
index 7c34b69711..0c98cb1ef7 100644
--- a/src/Microsoft.VisualBasic/tests/Microsoft.VisualBasic.Tests.csproj
+++ b/src/Microsoft.VisualBasic/tests/Microsoft.VisualBasic.Tests.csproj
@@ -3,6 +3,8 @@
<Import Project="$([MSBuild]::GetDirectoryNameOfFileAbove($(MSBuildThisFileDirectory), dir.props))\dir.props" />
<PropertyGroup>
<ProjectGuid>{325260D6-D5DD-4E06-9DA2-9AF2AD9DE8C8}</ProjectGuid>
+ <!-- CodeGen bug is causing two tests to fail if ILC builds ret -->
+ <ILCBuildType>chk</ILCBuildType>
</PropertyGroup>
<PropertyGroup Condition="'$(Configuration)|$(Platform)' == 'netstandard-Debug|AnyCPU'" />
<PropertyGroup Condition="'$(Configuration)|$(Platform)' == 'netstandard-Release|AnyCPU'" />
@@ -10,9 +12,6 @@
<Compile Include="OperatorsTests.cs" />
<Compile Include="UtilsTests.cs" />
<Compile Include="StringsTests.cs" />
- <Compile Include="$(CommonTestPath)\System\AssertExtensions.cs">
- <Link>Common\System\AssertExtensions.cs</Link>
- </Compile>
<Compile Include="$(CommonTestPath)\System\PlatformDetection.cs">
<Link>Common\System\PlatformDetection.cs</Link>
</Compile>
@@ -20,5 +19,8 @@
<Link>Common\System\Runtime\Serialization\Formatters\BinaryFormatterHelpers.cs</Link>
</Compile>
</ItemGroup>
+ <ItemGroup>
+ <EmbeddedResource Include="Resources\$(AssemblyName).rd.xml" />
+ </ItemGroup>
<Import Project="$([MSBuild]::GetDirectoryNameOfFileAbove($(MSBuildThisFileDirectory), dir.targets))\dir.targets" />
-</Project> \ No newline at end of file
+</Project>
diff --git a/src/Microsoft.VisualBasic/tests/OperatorsTests.cs b/src/Microsoft.VisualBasic/tests/OperatorsTests.cs
index 31d5a52523..7a675982a7 100644
--- a/src/Microsoft.VisualBasic/tests/OperatorsTests.cs
+++ b/src/Microsoft.VisualBasic/tests/OperatorsTests.cs
@@ -112,7 +112,6 @@ namespace Microsoft.VisualBasic.CompilerServices.Tests
yield return new object[] { (ulong)12, "2", (double)14 };
yield return new object[] { (ulong)13, true, (decimal)12 };
yield return new object[] { (ulong)14, null, (ulong)14 };
- yield return new object[] { (ulong)15, ulong.MaxValue, decimal.Parse("18446744073709551630") };
// long + primitives.
yield return new object[] { (long)8, (long)2, (long)10 };
@@ -122,7 +121,6 @@ namespace Microsoft.VisualBasic.CompilerServices.Tests
yield return new object[] { (long)12, "2", (double)14 };
yield return new object[] { (long)13, true, (long)12 };
yield return new object[] { (long)14, null, (long)14 };
- yield return new object[] { (long)15, long.MaxValue, decimal.Parse("9223372036854775822") };
// float + primitives
yield return new object[] { (float)9, (float)2, (float)11 };
@@ -168,7 +166,6 @@ namespace Microsoft.VisualBasic.CompilerServices.Tests
[Theory]
[MemberData(nameof(AddObject_Idempotent_TestData))]
- [ActiveIssue(21682, TargetFrameworkMonikers.UapAot)]
public void AddObject_Convertible_ReturnsExpected(object left, object right, object expected)
{
Assert.Equal(expected, Operators.AddObject(left, right));
@@ -185,6 +182,14 @@ namespace Microsoft.VisualBasic.CompilerServices.Tests
}
[Fact]
+ [ActiveIssue("https://github.com/dotnet/corefx/issues/21682 -- fails when /buildtype:ret passed to ILC", TargetFrameworkMonikers.UapAot)]
+ public void AddObject_Convertible_ReturnsExpected_64BitOverflow()
+ {
+ AddObject_Convertible_ReturnsExpected((ulong)15, ulong.MaxValue, decimal.Parse("18446744073709551630"));
+ AddObject_Convertible_ReturnsExpected((long)15, long.MaxValue, decimal.Parse("9223372036854775822"));
+ }
+
+ [Fact]
public void AddObject_DateString_ReturnsExpected()
{
string expected = Assert.IsType<string>(Operators.AddObject("String", new DateTime(2017, 10, 10)));
@@ -239,7 +244,6 @@ namespace Microsoft.VisualBasic.CompilerServices.Tests
[Theory]
[MemberData(nameof(IncompatibleAddObject_TestData))]
- [ActiveIssue(21682, TargetFrameworkMonikers.UapAot)]
public void AddObject_Incompatible_ThrowsInvalidCastException(object left, object right)
{
Assert.Throws<InvalidCastException>(() => Operators.AddObject(left, right));
diff --git a/src/Microsoft.VisualBasic/tests/Resources/Microsoft.VisualBasic.Tests.rd.xml b/src/Microsoft.VisualBasic/tests/Resources/Microsoft.VisualBasic.Tests.rd.xml
new file mode 100644
index 0000000000..8c50934a34
--- /dev/null
+++ b/src/Microsoft.VisualBasic/tests/Resources/Microsoft.VisualBasic.Tests.rd.xml
@@ -0,0 +1,7 @@
+<Directives xmlns="http://schemas.microsoft.com/netfx/2013/01/metadata">
+ <Library>
+ <!-- Needed because of objects in [Theory] data which causes xunit to reflect on its ToString() -->
+ <Type Name="System.DBNull" Dynamic="Required Public" />
+ </Library>
+</Directives>
+
diff --git a/src/Microsoft.VisualBasic/tests/UtilsTests.cs b/src/Microsoft.VisualBasic/tests/UtilsTests.cs
index 453695d95a..1cfbd927d4 100644
--- a/src/Microsoft.VisualBasic/tests/UtilsTests.cs
+++ b/src/Microsoft.VisualBasic/tests/UtilsTests.cs
@@ -71,8 +71,7 @@ namespace Microsoft.VisualBasic.CompilerServices.Tests
Assert.Throws<InvalidCastException>(() => Utils.CopyArray(new int[1], new int[1, 1]));
}
- [Fact]
- [ActiveIssue(21682, TargetFrameworkMonikers.UapAot)]
+ [ConditionalFact(nameof(PlatformDetection) + "." + nameof(PlatformDetection.IsNonZeroLowerBoundArraySupported))]
public void CopyArray_RankGreaterThanTwoAndNonMatchingBounds_ThrowsArrayTypeMismatchException()
{
Array array1 = Array.CreateInstance(typeof(int), new int[] { 1, 2, 3 }, new int[] { 2, 3, 4 });
@@ -81,8 +80,7 @@ namespace Microsoft.VisualBasic.CompilerServices.Tests
Assert.Throws<ArrayTypeMismatchException>(() => Utils.CopyArray(array2, array1));
}
- [Fact]
- [ActiveIssue(21682, TargetFrameworkMonikers.UapAot)]
+ [ConditionalFact(nameof(PlatformDetection) + "." + nameof(PlatformDetection.IsNonZeroLowerBoundArraySupported))]
public void CopyArray_NonMatchingBounds_ThrowsArgumentOutOfRangeException()
{
Array array1 = Array.CreateInstance(typeof(int), new int[] { 1, 2 }, new int[] { 2, 3 });
diff --git a/src/Microsoft.Win32.Primitives/src/System/ComponentModel/Win32Exception.cs b/src/Microsoft.Win32.Primitives/src/System/ComponentModel/Win32Exception.cs
index db93a2d1fa..b7957e21cd 100644
--- a/src/Microsoft.Win32.Primitives/src/System/ComponentModel/Win32Exception.cs
+++ b/src/Microsoft.Win32.Primitives/src/System/ComponentModel/Win32Exception.cs
@@ -7,81 +7,57 @@ using System.Runtime.Serialization;
namespace System.ComponentModel
{
- /// <devdoc>
- /// <para>The exception that is thrown for a Win32 error code.</para>
- /// </devdoc>
- [Serializable]
+ /// <summary>
+ /// The exception that is thrown for a Win32 error code.
+ /// </summary>
public partial class Win32Exception : ExternalException, ISerializable
{
- /// <devdoc>
- /// <para>Represents the Win32 error code associated with this exception. This
- /// field is read-only.</para>
- /// </devdoc>
- private readonly int nativeErrorCode;
-
private const int E_FAIL = unchecked((int)0x80004005);
- /// <devdoc>
- /// <para>Initializes a new instance of the <see cref='System.ComponentModel.Win32Exception'/> class with the last Win32 error
- /// that occurred.</para>
- /// </devdoc>
+ /// <summary>
+ /// Initializes a new instance of the <see cref='System.ComponentModel.Win32Exception'/> class with the last Win32 error
+ /// that occurred.
+ /// </summary>
public Win32Exception() : this(Marshal.GetLastWin32Error())
{
}
- /// <devdoc>
- /// <para>Initializes a new instance of the <see cref='System.ComponentModel.Win32Exception'/> class with the specified error.</para>
- /// </devdoc>
+
+ /// <summary>
+ /// Initializes a new instance of the <see cref='System.ComponentModel.Win32Exception'/> class with the specified error.
+ /// </summary>
public Win32Exception(int error) : this(error, GetErrorMessage(error))
{
}
- /// <devdoc>
- /// <para>Initializes a new instance of the <see cref='System.ComponentModel.Win32Exception'/> class with the specified error and the
- /// specified detailed description.</para>
- /// </devdoc>
- public Win32Exception(int error, string message)
- : base(message)
+ /// <summary>
+ /// Initializes a new instance of the <see cref='System.ComponentModel.Win32Exception'/> class with the specified error and the
+ /// specified detailed description.
+ /// </summary>
+ public Win32Exception(int error, string message) : base(message)
{
- nativeErrorCode = error;
+ NativeErrorCode = error;
}
- /// <devdoc>
- /// Initializes a new instance of the Exception class with a specified error message.
- /// FxCop CA1032: Multiple constructors are required to correctly implement a custom exception.
- /// </devdoc>
+ /// <summary>
+ /// Initializes a new instance of the Exception class with a specified error message.
+ /// </summary>
public Win32Exception(string message) : this(Marshal.GetLastWin32Error(), message)
{
}
- /// <devdoc>
- /// Initializes a new instance of the Exception class with a specified error message and a
- /// reference to the inner exception that is the cause of this exception.
- /// FxCop CA1032: Multiple constructors are required to correctly implement a custom exception.
- /// </devdoc>
+ /// <summary>
+ /// Initializes a new instance of the Exception class with a specified error message and a
+ /// reference to the inner exception that is the cause of this exception.
+ /// </summary>
public Win32Exception(string message, Exception innerException) : base(message, innerException)
{
- nativeErrorCode = Marshal.GetLastWin32Error();
+ NativeErrorCode = Marshal.GetLastWin32Error();
}
- protected Win32Exception(SerializationInfo info, StreamingContext context) : base(info, context)
- {
- throw new PlatformNotSupportedException();
- }
+ protected Win32Exception(SerializationInfo info, StreamingContext context) : base(info, context) { }
- public override void GetObjectData(SerializationInfo info, StreamingContext context)
- {
- base.GetObjectData(info, context);
- }
-
- /// <devdoc>
- /// <para>Represents the Win32 error code associated with this exception. This
- /// field is read-only.</para>
- /// </devdoc>
- public int NativeErrorCode
- {
- get
- {
- return nativeErrorCode;
- }
- }
+ /// <summary>
+ /// Represents the Win32 error code associated with this exception. This field is read-only.
+ /// </summary>
+ public int NativeErrorCode { get; }
}
}
diff --git a/src/Microsoft.Win32.Primitives/tests/Microsoft.Win32.Primitives.Tests.csproj b/src/Microsoft.Win32.Primitives/tests/Microsoft.Win32.Primitives.Tests.csproj
index 98d7da1b73..43e29a6460 100644
--- a/src/Microsoft.Win32.Primitives/tests/Microsoft.Win32.Primitives.Tests.csproj
+++ b/src/Microsoft.Win32.Primitives/tests/Microsoft.Win32.Primitives.Tests.csproj
@@ -7,12 +7,9 @@
<PropertyGroup Condition="'$(Configuration)|$(Platform)' == 'netstandard-Debug|AnyCPU'" />
<PropertyGroup Condition="'$(Configuration)|$(Platform)' == 'netstandard-Release|AnyCPU'" />
<ItemGroup>
- <Compile Include="Win32Exception.cs" />
- <Compile Include="$(CommonTestPath)\System\AssertExtensions.cs">
- <Link>Common\System\AssertExtensions.cs</Link>
- </Compile>
+ <Compile Include="Win32ExceptionTests.cs" />
<Compile Include="$(CommonTestPath)\System\PlatformDetection.cs">
- <Link>CommonTest\System\PlatformDetection.cs</Link>
+ <Link>Common\System\PlatformDetection.cs</Link>
</Compile>
<Compile Include="$(CommonTestPath)\System\Runtime\Serialization\Formatters\BinaryFormatterHelpers.cs">
<Link>Common\System\Runtime\Serialization\Formatters\BinaryFormatterHelpers.cs</Link>
@@ -22,4 +19,4 @@
<EmbeddedResource Include="Resources\$(AssemblyName).rd.xml" />
</ItemGroup>
<Import Project="$([MSBuild]::GetDirectoryNameOfFileAbove($(MSBuildThisFileDirectory), dir.targets))\dir.targets" />
-</Project>
+</Project> \ No newline at end of file
diff --git a/src/Microsoft.Win32.Primitives/tests/Win32Exception.cs b/src/Microsoft.Win32.Primitives/tests/Win32ExceptionTests.cs
index 097703161e..f9956ac08b 100644
--- a/src/Microsoft.Win32.Primitives/tests/Win32Exception.cs
+++ b/src/Microsoft.Win32.Primitives/tests/Win32ExceptionTests.cs
@@ -2,10 +2,7 @@
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
-using System;
-using System.Collections.Generic;
using System.Runtime.InteropServices;
-using System.Runtime.Serialization;
using System.Runtime.Serialization.Formatters.Tests;
using System.Text;
using Xunit;
@@ -101,5 +98,11 @@ namespace System.ComponentModel.Tests
Assert.Equal(expected: "Unknown error (0x23)", actual: ex.Message);
}
}
+
+ [Fact]
+ public static void Deserialize_NetCore_ThrowsPlatformNotSupportedException()
+ {
+ BinaryFormatterHelpers.AssertExceptionDeserializationFails<Win32Exception>();
+ }
}
}
diff --git a/src/Microsoft.Win32.Registry/tests/Microsoft.Win32.Registry.Tests.csproj b/src/Microsoft.Win32.Registry/tests/Microsoft.Win32.Registry.Tests.csproj
index bede9d7675..83a3a3139d 100644
--- a/src/Microsoft.Win32.Registry/tests/Microsoft.Win32.Registry.Tests.csproj
+++ b/src/Microsoft.Win32.Registry/tests/Microsoft.Win32.Registry.Tests.csproj
@@ -63,9 +63,6 @@
<Compile Include="RegistryTestsBase.cs" />
<Compile Include="TestData.cs" />
<Compile Include="XunitAssemblyAttributes.cs" />
- <Compile Include="$(CommonTestPath)\System\AssertExtensions.cs">
- <Link>Common\System\AssertExtensions.cs</Link>
- </Compile>
</ItemGroup>
<Import Project="$([MSBuild]::GetDirectoryNameOfFileAbove($(MSBuildThisFileDirectory), dir.targets))\dir.targets" />
</Project>
diff --git a/src/Native/Unix/System.Native/pal_networkstatistics.cpp b/src/Native/Unix/System.Native/pal_networkstatistics.cpp
index 3221cb73ca..3802d72b03 100644
--- a/src/Native/Unix/System.Native/pal_networkstatistics.cpp
+++ b/src/Native/Unix/System.Native/pal_networkstatistics.cpp
@@ -20,6 +20,7 @@
#include <errno.h>
#include <memory>
#include <net/route.h>
+#include <net/if.h>
#include <sys/types.h>
#if HAVE_SYS_SYSCTL_H
diff --git a/src/Native/Unix/System.Security.Cryptography.Native.Apple/pal_x509chain.cpp b/src/Native/Unix/System.Security.Cryptography.Native.Apple/pal_x509chain.cpp
index 587091d695..6db3d53e9f 100644
--- a/src/Native/Unix/System.Security.Cryptography.Native.Apple/pal_x509chain.cpp
+++ b/src/Native/Unix/System.Security.Cryptography.Native.Apple/pal_x509chain.cpp
@@ -65,7 +65,10 @@ extern "C" int32_t AppleCryptoNative_X509ChainEvaluate(SecTrustRef chain,
SecTrustResultType trustResult;
*pOSStatus = SecTrustEvaluate(chain, &trustResult);
- if (*pOSStatus != noErr)
+ // If any error is reported from the function or the trust result value indicates that
+ // otherwise was a failed chain build (vs an untrusted chain, etc) return failure and
+ // we'll throw in the managed layer. (but if we hit the "or" the message is "No error")
+ if (*pOSStatus != noErr || trustResult == kSecTrustResultInvalid)
{
return 0;
}
diff --git a/src/Native/Unix/System.Security.Cryptography.Native/pal_ssl.cpp b/src/Native/Unix/System.Security.Cryptography.Native/pal_ssl.cpp
index dbccbf9ef9..fda1f4da95 100644
--- a/src/Native/Unix/System.Security.Cryptography.Native/pal_ssl.cpp
+++ b/src/Native/Unix/System.Security.Cryptography.Native/pal_ssl.cpp
@@ -27,48 +27,6 @@ extern "C" const SSL_METHOD* CryptoNative_SslV2_3Method()
return method;
}
-extern "C" const SSL_METHOD* CryptoNative_SslV3Method()
-{
- const SSL_METHOD* method = nullptr;
-#ifndef OPENSSL_NO_SSL3_METHOD
- if (API_EXISTS(SSLv3_method))
- {
- method = SSLv3_method();
- assert(method != nullptr);
- }
-#endif
- return method;
-}
-
-extern "C" const SSL_METHOD* CryptoNative_TlsV1Method()
-{
- const SSL_METHOD* method = TLSv1_method();
- assert(method != nullptr);
- return method;
-}
-
-extern "C" const SSL_METHOD* CryptoNative_TlsV1_1Method()
-{
-#if HAVE_TLS_V1_1
- const SSL_METHOD* method = TLSv1_1_method();
- assert(method != nullptr);
- return method;
-#else
- return nullptr;
-#endif
-}
-
-extern "C" const SSL_METHOD* CryptoNative_TlsV1_2Method()
-{
-#if HAVE_TLS_V1_2
- const SSL_METHOD* method = TLSv1_2_method();
- assert(method != nullptr);
- return method;
-#else
- return nullptr;
-#endif
-}
-
extern "C" SSL_CTX* CryptoNative_SslCtxCreate(SSL_METHOD* method)
{
SSL_CTX* ctx = SSL_CTX_new(method);
@@ -85,7 +43,12 @@ extern "C" SSL_CTX* CryptoNative_SslCtxCreate(SSL_METHOD* method)
extern "C" void CryptoNative_SetProtocolOptions(SSL_CTX* ctx, SslProtocols protocols)
{
- // protocols may be 0 (default). Less secure protocols should be excluded in this case.
+ // protocols may be 0, meaning system default, in which case let OpenSSL do what OpenSSL wants.
+ if (protocols == 0)
+ {
+ return;
+ }
+
long protocolOptions = 0;
if ((protocols & PAL_SSL_SSL2) != PAL_SSL_SSL2)
@@ -94,10 +57,13 @@ extern "C" void CryptoNative_SetProtocolOptions(SSL_CTX* ctx, SslProtocols proto
}
#ifndef OPENSSL_NO_SSL3
if ((protocols & PAL_SSL_SSL3) != PAL_SSL_SSL3)
+#endif
{
+ // If OPENSSL_NO_SSL3 is defined, then ensure we always include
+ // SSL_OP_NO_SSLv3 in case we end up running against a binary
+ // which had SSLv3 enabled (we don't want to use SSLv3 in that case).
protocolOptions |= SSL_OP_NO_SSLv3;
}
-#endif
if ((protocols & PAL_SSL_TLS) != PAL_SSL_TLS)
{
protocolOptions |= SSL_OP_NO_TLSv1;
diff --git a/src/Native/Unix/System.Security.Cryptography.Native/pal_ssl.h b/src/Native/Unix/System.Security.Cryptography.Native/pal_ssl.h
index 03f6a4e0dc..4fd7fb59c0 100644
--- a/src/Native/Unix/System.Security.Cryptography.Native/pal_ssl.h
+++ b/src/Native/Unix/System.Security.Cryptography.Native/pal_ssl.h
@@ -130,34 +130,6 @@ Returns the requested SSL_METHOD.
extern "C" const SSL_METHOD* CryptoNative_SslV2_3Method();
/*
-Shims the SSLv3_method method.
-
-Returns the requested SSL_METHOD.
-*/
-extern "C" const SSL_METHOD* CryptoNative_SslV3Method();
-
-/*
-Shims the TLSv1_method method.
-
-Returns the requested SSL_METHOD.
-*/
-extern "C" const SSL_METHOD* CryptoNative_TlsV1Method();
-
-/*
-Shims the TLSv1_1_method method.
-
-Returns the requested SSL_METHOD.
-*/
-extern "C" const SSL_METHOD* CryptoNative_TlsV1_1Method();
-
-/*
-Shims the TLSv1_2_method method.
-
-Returns the requested SSL_METHOD.
-*/
-extern "C" const SSL_METHOD* CryptoNative_TlsV1_2Method();
-
-/*
Shims the SSL_CTX_new method.
Returns the new SSL_CTX instance.
diff --git a/src/Native/Unix/System.Security.Cryptography.Native/pal_x509.cpp b/src/Native/Unix/System.Security.Cryptography.Native/pal_x509.cpp
index 4b8bec0c2b..0a3dfcc2c8 100644
--- a/src/Native/Unix/System.Security.Cryptography.Native/pal_x509.cpp
+++ b/src/Native/Unix/System.Security.Cryptography.Native/pal_x509.cpp
@@ -10,6 +10,7 @@ static_assert(PAL_X509_V_OK == X509_V_OK, "");
static_assert(PAL_X509_V_ERR_UNABLE_TO_GET_ISSUER_CERT == X509_V_ERR_UNABLE_TO_GET_ISSUER_CERT, "");
static_assert(PAL_X509_V_ERR_UNABLE_TO_GET_CRL == X509_V_ERR_UNABLE_TO_GET_CRL, "");
static_assert(PAL_X509_V_ERR_UNABLE_TO_DECRYPT_CRL_SIGNATURE == X509_V_ERR_UNABLE_TO_DECRYPT_CRL_SIGNATURE, "");
+static_assert(PAL_X509_V_ERR_UNABLE_TO_DECODE_ISSUER_PUBLIC_KEY == X509_V_ERR_UNABLE_TO_DECODE_ISSUER_PUBLIC_KEY, "");
static_assert(PAL_X509_V_ERR_CERT_SIGNATURE_FAILURE == X509_V_ERR_CERT_SIGNATURE_FAILURE, "");
static_assert(PAL_X509_V_ERR_CRL_SIGNATURE_FAILURE == X509_V_ERR_CRL_SIGNATURE_FAILURE, "");
static_assert(PAL_X509_V_ERR_CERT_NOT_YET_VALID == X509_V_ERR_CERT_NOT_YET_VALID, "");
diff --git a/src/Native/Unix/System.Security.Cryptography.Native/pal_x509.h b/src/Native/Unix/System.Security.Cryptography.Native/pal_x509.h
index c1bd695ece..d182de6569 100644
--- a/src/Native/Unix/System.Security.Cryptography.Native/pal_x509.h
+++ b/src/Native/Unix/System.Security.Cryptography.Native/pal_x509.h
@@ -26,6 +26,7 @@ enum X509VerifyStatusCode : int32_t
PAL_X509_V_ERR_UNABLE_TO_GET_ISSUER_CERT = 2,
PAL_X509_V_ERR_UNABLE_TO_GET_CRL = 3,
PAL_X509_V_ERR_UNABLE_TO_DECRYPT_CRL_SIGNATURE = 5,
+ PAL_X509_V_ERR_UNABLE_TO_DECODE_ISSUER_PUBLIC_KEY = 6,
PAL_X509_V_ERR_CERT_SIGNATURE_FAILURE = 7,
PAL_X509_V_ERR_CRL_SIGNATURE_FAILURE = 8,
PAL_X509_V_ERR_CERT_NOT_YET_VALID = 9,
diff --git a/src/System.AppContext/tests/System.AppContext.Tests.csproj b/src/System.AppContext/tests/System.AppContext.Tests.csproj
index ac1c9052d6..c68a2dac0f 100644
--- a/src/System.AppContext/tests/System.AppContext.Tests.csproj
+++ b/src/System.AppContext/tests/System.AppContext.Tests.csproj
@@ -9,9 +9,6 @@
<ItemGroup>
<Compile Include="AppContext.Switch.cs" />
<Compile Include="AppContext.Switch.Validation.cs" />
- <Compile Include="$(CommonTestPath)\System\AssertExtensions.cs">
- <Link>Common\System\AssertExtensions.cs</Link>
- </Compile>
</ItemGroup>
<Import Project="$([MSBuild]::GetDirectoryNameOfFileAbove($(MSBuildThisFileDirectory), dir.targets))\dir.targets" />
</Project> \ No newline at end of file
diff --git a/src/System.Buffers/pkg/System.Buffers.pkgproj b/src/System.Buffers/pkg/System.Buffers.pkgproj
index fe4abc8aa0..4312458b78 100644
--- a/src/System.Buffers/pkg/System.Buffers.pkgproj
+++ b/src/System.Buffers/pkg/System.Buffers.pkgproj
@@ -8,7 +8,7 @@
<ProjectReference Include="..\src\System.Buffers.csproj" />
<InboxOnTargetFramework Include="netcoreapp2.0" />
- <InboxOnTargetFramework Include="uap10.1" />
+ <InboxOnTargetFramework Include="$(UAPvNextTFM)" />
<!-- this package is part of the implementation closure of NETStandard.Library
therefore it cannot reference NETStandard.Library -->
<SuppressMetaPackage Include="NETStandard.Library" />
diff --git a/src/System.Buffers/tests/System.Buffers.Tests.csproj b/src/System.Buffers/tests/System.Buffers.Tests.csproj
index d8e2eb8942..71a002e77a 100644
--- a/src/System.Buffers/tests/System.Buffers.Tests.csproj
+++ b/src/System.Buffers/tests/System.Buffers.Tests.csproj
@@ -8,9 +8,6 @@
<PropertyGroup Condition="'$(Configuration)|$(Platform)' == 'netstandard-Release|AnyCPU'" />
<ItemGroup>
<Compile Include="ArrayPool\UnitTests.cs" />
- <Compile Include="$(CommonTestPath)\System\AssertExtensions.cs">
- <Link>Common\System\AssertExtensions.cs</Link>
- </Compile>
<Compile Include="$(CommonTestPath)\System\Diagnostics\Tracing\TestEventListener.cs" />
</ItemGroup>
<Import Project="$([MSBuild]::GetDirectoryNameOfFileAbove($(MSBuildThisFileDirectory), dir.targets))\dir.targets" />
diff --git a/src/System.CodeDom/tests/System.CodeDom.Tests.csproj b/src/System.CodeDom/tests/System.CodeDom.Tests.csproj
index 9a9cb5a4bb..5bdc89f107 100644
--- a/src/System.CodeDom/tests/System.CodeDom.Tests.csproj
+++ b/src/System.CodeDom/tests/System.CodeDom.Tests.csproj
@@ -91,9 +91,6 @@
<Compile Include="Other\CodeAttributeArgumentTests.cs" />
<Compile Include="VBCodeGenerationTests.cs" />
<Compile Include="CSharpCodeGenerationTests.cs" />
- <Compile Include="$(CommonTestPath)\System\AssertExtensions.cs">
- <Link>Common\System\AssertExtensions.cs</Link>
- </Compile>
<Compile Include="$(CommonTestPath)\System\Runtime\Serialization\Formatters\BinaryFormatterHelpers.cs">
<Link>Common\System\Runtime\Serialization\Formatters\BinaryFormatterHelpers.cs</Link>
</Compile>
diff --git a/src/System.Collections.Concurrent/src/System/Collections/Concurrent/ConcurrentQueue.cs b/src/System.Collections.Concurrent/src/System/Collections/Concurrent/ConcurrentQueue.cs
index 806658e064..8c28c3e3cb 100644
--- a/src/System.Collections.Concurrent/src/System/Collections/Concurrent/ConcurrentQueue.cs
+++ b/src/System.Collections.Concurrent/src/System/Collections/Concurrent/ConcurrentQueue.cs
@@ -117,7 +117,7 @@ namespace System.Collections.Concurrent
int count = c.Count;
if (count > length)
{
- length = RoundUpToPowerOf2(count);
+ length = Math.Min(RoundUpToPowerOf2(count), MaxSegmentLength);
}
}
@@ -678,7 +678,7 @@ namespace System.Collections.Concurrent
// initial segment length; if these observations are happening frequently,
// this will help to avoid wasted memory, and if they're not, we'll
// relatively quickly grow again to a larger size.
- int nextSize = tail._preservedForObservation ? InitialSegmentLength : tail.Capacity * 2;
+ int nextSize = tail._preservedForObservation ? InitialSegmentLength : Math.Min(tail.Capacity * 2, MaxSegmentLength);
var newTail = new Segment(nextSize);
// Hook up the new tail.
diff --git a/src/System.Collections.Concurrent/tests/System.Collections.Concurrent.Tests.csproj b/src/System.Collections.Concurrent/tests/System.Collections.Concurrent.Tests.csproj
index 9f187a8355..a471769673 100644
--- a/src/System.Collections.Concurrent/tests/System.Collections.Concurrent.Tests.csproj
+++ b/src/System.Collections.Concurrent/tests/System.Collections.Concurrent.Tests.csproj
@@ -10,9 +10,6 @@
<PropertyGroup Condition="'$(Configuration)|$(Platform)' == 'netstandard-Debug|AnyCPU'" />
<PropertyGroup Condition="'$(Configuration)|$(Platform)' == 'netstandard-Release|AnyCPU'" />
<ItemGroup>
- <Compile Include="$(CommonTestPath)\System\AssertExtensions.cs">
- <Link>Common\System\AssertExtensions.cs</Link>
- </Compile>
<Compile Include="$(CommonTestPath)\System\Collections\DictionaryExtensions.cs" Condition="'$(TargetGroup)'!='netcoreapp'">
<Link>Common\System\Collections\DictionaryExtensions.cs</Link>
</Compile>
diff --git a/src/System.Collections.Immutable/pkg/System.Collections.Immutable.pkgproj b/src/System.Collections.Immutable/pkg/System.Collections.Immutable.pkgproj
index 9722c4575a..3fc9266e62 100644
--- a/src/System.Collections.Immutable/pkg/System.Collections.Immutable.pkgproj
+++ b/src/System.Collections.Immutable/pkg/System.Collections.Immutable.pkgproj
@@ -10,7 +10,7 @@
<SupportedFramework>net45;netcore45;netcoreapp1.0;wp8;wpa81;$(AllXamarinFrameworks)</SupportedFramework>
</ProjectReference>
<InboxOnTargetFramework Include="netcoreapp2.0" />
- <InboxOnTargetFramework Include="uap10.1" />
+ <InboxOnTargetFramework Include="$(UAPvNextTFM)" />
</ItemGroup>
<Import Project="$([MSBuild]::GetDirectoryNameOfFileAbove($(MSBuildThisFileDirectory), dir.targets))\dir.targets" />
</Project> \ No newline at end of file
diff --git a/src/System.Collections.Immutable/tests/System.Collections.Immutable.Tests.csproj b/src/System.Collections.Immutable/tests/System.Collections.Immutable.Tests.csproj
index e2d0f2e511..a3e2c46eee 100644
--- a/src/System.Collections.Immutable/tests/System.Collections.Immutable.Tests.csproj
+++ b/src/System.Collections.Immutable/tests/System.Collections.Immutable.Tests.csproj
@@ -48,9 +48,6 @@
<Compile Include="RequiresTests.cs" />
<Compile Include="SimpleElementImmutablesTestBase.cs" />
<Compile Include="TestExtensionsMethods.cs" />
- <Compile Include="$(CommonTestPath)\System\AssertExtensions.cs">
- <Link>Common\System\AssertExtensions.cs</Link>
- </Compile>
<Compile Include="$(CommonTestPath)\System\Diagnostics\DebuggerAttributes.cs">
<Link>Common\System\Diagnostics\DebuggerAttributes.cs</Link>
</Compile>
diff --git a/src/System.Collections.NonGeneric/tests/System.Collections.NonGeneric.Tests.csproj b/src/System.Collections.NonGeneric/tests/System.Collections.NonGeneric.Tests.csproj
index bf90122ef5..714b533e9f 100644
--- a/src/System.Collections.NonGeneric/tests/System.Collections.NonGeneric.Tests.csproj
+++ b/src/System.Collections.NonGeneric/tests/System.Collections.NonGeneric.Tests.csproj
@@ -8,9 +8,6 @@
<PropertyGroup Condition="'$(Configuration)|$(Platform)' == 'netstandard-Debug|AnyCPU'" />
<PropertyGroup Condition="'$(Configuration)|$(Platform)' == 'netstandard-Release|AnyCPU'" />
<ItemGroup>
- <Compile Include="$(CommonTestPath)\System\AssertExtensions.cs">
- <Link>Common\System\AssertExtensions.cs</Link>
- </Compile>
<!-- Common Collections tests -->
<Compile Include="$(CommonTestPath)\System\Collections\ICollection.NonGeneric.Tests.cs">
<Link>Common\System\Collections\ICollection.NonGeneric.Tests.cs</Link>
diff --git a/src/System.Collections.Specialized/tests/System.Collections.Specialized.Tests.csproj b/src/System.Collections.Specialized/tests/System.Collections.Specialized.Tests.csproj
index 29c2d0fc45..612db11279 100644
--- a/src/System.Collections.Specialized/tests/System.Collections.Specialized.Tests.csproj
+++ b/src/System.Collections.Specialized/tests/System.Collections.Specialized.Tests.csproj
@@ -8,9 +8,6 @@
<PropertyGroup Condition="'$(Configuration)|$(Platform)' == 'netstandard-Debug|AnyCPU'" />
<PropertyGroup Condition="'$(Configuration)|$(Platform)' == 'netstandard-Release|AnyCPU'" />
<ItemGroup>
- <Compile Include="$(CommonTestPath)\System\AssertExtensions.cs">
- <Link>Common\System\AssertExtensions.cs</Link>
- </Compile>
<!-- Common Collections tests -->
<Compile Include="$(CommonTestPath)\System\Collections\CollectionAsserts.cs">
<Link>Common\System\Collections\CollectionAsserts.cs</Link>
diff --git a/src/System.Collections/tests/Generic/Comparers/EqualityComparer.Generic.Serialization.Tests.cs b/src/System.Collections/tests/Generic/Comparers/EqualityComparer.Generic.Serialization.Tests.cs
index 2ca0e6a063..cb58f0f492 100644
--- a/src/System.Collections/tests/Generic/Comparers/EqualityComparer.Generic.Serialization.Tests.cs
+++ b/src/System.Collections/tests/Generic/Comparers/EqualityComparer.Generic.Serialization.Tests.cs
@@ -13,7 +13,6 @@ namespace System.Collections.Generic.Tests
public abstract partial class ComparersGenericTests<T>
{
[Fact]
- [ActiveIssue(20888, TargetFrameworkMonikers.Uap)]
public void EqualityComparer_SerializationRoundtrip()
{
var bf = new BinaryFormatter();
diff --git a/src/System.Collections/tests/Generic/Dictionary/Dictionary.Tests.cs b/src/System.Collections/tests/Generic/Dictionary/Dictionary.Tests.cs
index 7b8d2fbe5a..9f954f6152 100644
--- a/src/System.Collections/tests/Generic/Dictionary/Dictionary.Tests.cs
+++ b/src/System.Collections/tests/Generic/Dictionary/Dictionary.Tests.cs
@@ -198,7 +198,6 @@ namespace System.Collections.Tests
[Theory]
[MemberData(nameof(CopyConstructorInt32ComparerData))]
- [ActiveIssue(20888, TargetFrameworkMonikers.UapAot)]
public void CopyConstructorInt32Comparer(int size, Func<int, int> keyValueSelector, Func<IDictionary<int, int>, IDictionary<int, int>> dictionarySelector, IEqualityComparer<int> comparer)
{
TestCopyConstructor(size, keyValueSelector, dictionarySelector, comparer);
@@ -220,7 +219,6 @@ namespace System.Collections.Tests
[Theory]
[MemberData(nameof(CopyConstructorStringComparerData))]
- [ActiveIssue(20888, TargetFrameworkMonikers.UapAot)]
public void CopyConstructorStringComparer(int size, Func<int, string> keyValueSelector, Func<IDictionary<string, string>, IDictionary<string, string>> dictionarySelector, IEqualityComparer<string> comparer)
{
TestCopyConstructor(size, keyValueSelector, dictionarySelector, comparer);
diff --git a/src/System.Collections/tests/Resources/System.Collections.Tests.rd.xml b/src/System.Collections/tests/Resources/System.Collections.Tests.rd.xml
new file mode 100644
index 0000000000..7b409ae9fd
--- /dev/null
+++ b/src/System.Collections/tests/Resources/System.Collections.Tests.rd.xml
@@ -0,0 +1,7 @@
+<Directives xmlns="http://schemas.microsoft.com/netfx/2013/01/metadata">
+ <Library>
+ <!-- Needed because test code calls IsSerializable on these types -->
+ <Type Name="System.Collections.Generic.SortedList`2" Browse="Required Public" />
+ <Type Name="System.Collections.Generic.SortedDictionary`2" Browse="Required Public" />
+ </Library>
+</Directives>
diff --git a/src/System.Collections/tests/System.Collections.Tests.csproj b/src/System.Collections/tests/System.Collections.Tests.csproj
index a047e39664..0dad64f966 100644
--- a/src/System.Collections/tests/System.Collections.Tests.csproj
+++ b/src/System.Collections/tests/System.Collections.Tests.csproj
@@ -10,9 +10,6 @@
<PropertyGroup Condition="'$(Configuration)|$(Platform)' == 'netstandard-Debug|AnyCPU'" />
<PropertyGroup Condition="'$(Configuration)|$(Platform)' == 'netstandard-Release|AnyCPU'" />
<ItemGroup>
- <Compile Include="$(CommonTestPath)\System\AssertExtensions.cs">
- <Link>Common\System\AssertExtensions.cs</Link>
- </Compile>
<!-- Common Collections tests -->
<Compile Include="$(CommonTestPath)\System\Collections\CollectionAsserts.cs">
<Link>Common\System\Collections\CollectionAsserts.cs</Link>
@@ -169,5 +166,8 @@
<ItemGroup>
<EmbeddedResource Include="ILCConfigurations.rd.xml" />
</ItemGroup>
+ <ItemGroup>
+ <EmbeddedResource Include="Resources\$(AssemblyName).rd.xml" />
+ </ItemGroup>
<Import Project="$([MSBuild]::GetDirectoryNameOfFileAbove($(MSBuildThisFileDirectory), dir.targets))\dir.targets" />
-</Project> \ No newline at end of file
+</Project>
diff --git a/src/System.ComponentModel.Annotations/pkg/System.ComponentModel.Annotations.pkgproj b/src/System.ComponentModel.Annotations/pkg/System.ComponentModel.Annotations.pkgproj
index 9cfba11978..957e23392c 100644
--- a/src/System.ComponentModel.Annotations/pkg/System.ComponentModel.Annotations.pkgproj
+++ b/src/System.ComponentModel.Annotations/pkg/System.ComponentModel.Annotations.pkgproj
@@ -16,7 +16,7 @@
<FrameworkReference>System.ComponentModel.DataAnnotations</FrameworkReference>
</InboxOnTargetFramework>
<InboxOnTargetFramework Include="netcoreapp2.0" />
- <InboxOnTargetFramework Include="uap10.1" />
+ <InboxOnTargetFramework Include="$(UAPvNextTFM)" />
<InboxOnTargetFramework Include="win8" />
<InboxOnTargetFramework Include="portable-net45+win8" />
<InboxOnTargetFramework Include="xamarinios10" />
diff --git a/src/System.ComponentModel.Annotations/tests/System.ComponentModel.Annotations.Tests.csproj b/src/System.ComponentModel.Annotations/tests/System.ComponentModel.Annotations.Tests.csproj
index 300d2e33e0..d2ac137f99 100644
--- a/src/System.ComponentModel.Annotations/tests/System.ComponentModel.Annotations.Tests.csproj
+++ b/src/System.ComponentModel.Annotations/tests/System.ComponentModel.Annotations.Tests.csproj
@@ -48,9 +48,6 @@
<Compile Include="$(CommonTestPath)\System\PlatformDetection.cs">
<Link>Common\System\PlatformDetection.cs</Link>
</Compile>
- <Compile Include="$(CommonTestPath)\System\AssertExtensions.cs">
- <Link>Common\System\AssertExtensions.cs</Link>
- </Compile>
</ItemGroup>
<Import Project="$([MSBuild]::GetDirectoryNameOfFileAbove($(MSBuildThisFileDirectory), dir.targets))\dir.targets" />
</Project> \ No newline at end of file
diff --git a/src/System.ComponentModel.TypeConverter/src/Resources/System.ComponentModel.TypeConverter.rd.xml b/src/System.ComponentModel.TypeConverter/src/Resources/System.ComponentModel.TypeConverter.rd.xml
index 1260070793..4072a66323 100644
--- a/src/System.ComponentModel.TypeConverter/src/Resources/System.ComponentModel.TypeConverter.rd.xml
+++ b/src/System.ComponentModel.TypeConverter/src/Resources/System.ComponentModel.TypeConverter.rd.xml
@@ -23,8 +23,7 @@
relies on AttributeCollection returning ReadOnlyAttribute.Default if none was placed in the collection.
That lookup is done by Reflection.
-->
- <Field Name="Default" Dynamic="Required Public">
- </Field>
+ <Field Name="Default" Dynamic="Required" />
</Type>
</Namespace>
</Assembly>
diff --git a/src/System.ComponentModel.TypeConverter/src/System/ComponentModel/AmbientValueAttribute.cs b/src/System.ComponentModel.TypeConverter/src/System/ComponentModel/AmbientValueAttribute.cs
index 4b26b4074b..f1be518264 100644
--- a/src/System.ComponentModel.TypeConverter/src/System/ComponentModel/AmbientValueAttribute.cs
+++ b/src/System.ComponentModel.TypeConverter/src/System/ComponentModel/AmbientValueAttribute.cs
@@ -2,33 +2,26 @@
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
-using System;
-using System.ComponentModel;
-using System.Diagnostics;
-using System.Globalization;
-using System.Runtime.InteropServices;
-using System.Security.Permissions;
+using System.Diagnostics.CodeAnalysis;
namespace System.ComponentModel
{
/// <summary>
- /// <para>Specifies the ambient value for a property. The ambient value is the value you
- /// can set into a property to make it inherit its ambient.</para>
+ /// Specifies the ambient value for a property. The ambient value is the value you
+ /// can set into a property to make it inherit its ambient.
/// </summary>
- [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Design", "CA1019:DefineAccessorsForAttributeArguments")]
+ [SuppressMessage("Microsoft.Design", "CA1019:DefineAccessorsForAttributeArguments")]
[AttributeUsage(AttributeTargets.All)]
public sealed class AmbientValueAttribute : Attribute
{
/// <summary>
- /// <para>Initializes a new instance of the <see cref='System.ComponentModel.AmbientValueAttribute'/> class, converting the
- /// specified value to the
- /// specified type, and using the U.S. English culture as the
- /// translation
- /// context.</para>
+ /// Initializes a new instance of the <see cref='System.ComponentModel.AmbientValueAttribute'/> class, converting the
+ /// specified value to the specified type, and using the U.S. English culture as the
+ /// translation context.
/// </summary>
public AmbientValueAttribute(Type type, string value)
{
- // The try/catch here is because attributes should never throw exceptions. We would fail to
+ // The try/catch here is because attributes should never throw exceptions. We would fail to
// load an otherwise normal class.
try
{
@@ -36,42 +29,45 @@ namespace System.ComponentModel
}
catch
{
- Debug.Fail($"Ambient value attribute of type {type.FullName} threw converting from the string '{value}'.");
}
}
/// <summary>
- /// <para>Initializes a new instance of the <see cref='System.ComponentModel.AmbientValueAttribute'/> class using a Unicode
- /// character.</para>
+ /// Initializes a new instance of the <see cref='System.ComponentModel.AmbientValueAttribute'/> class using a Unicode
+ /// character.
/// </summary>
public AmbientValueAttribute(char value)
{
Value = value;
}
+
/// <summary>
- /// <para>Initializes a new instance of the <see cref='System.ComponentModel.AmbientValueAttribute'/> class using an 8-bit unsigned
- /// integer.</para>
+ /// Initializes a new instance of the <see cref='System.ComponentModel.AmbientValueAttribute'/> class using an 8-bit unsigned
+ /// integer.
/// </summary>
public AmbientValueAttribute(byte value)
{
Value = value;
}
+
/// <summary>
- /// <para>Initializes a new instance of the <see cref='System.ComponentModel.AmbientValueAttribute'/> class using a 16-bit signed
- /// integer.</para>
+ /// Initializes a new instance of the <see cref='System.ComponentModel.AmbientValueAttribute'/> class using a 16-bit signed
+ /// integer.
/// </summary>
public AmbientValueAttribute(short value)
{
Value = value;
}
+
/// <summary>
- /// <para>Initializes a new instance of the <see cref='System.ComponentModel.AmbientValueAttribute'/> class using a 32-bit signed
- /// integer.</para>
+ /// Initializes a new instance of the <see cref='System.ComponentModel.AmbientValueAttribute'/> class using a 32-bit signed
+ /// integer.
/// </summary>
public AmbientValueAttribute(int value)
{
Value = value;
}
+
/// <summary>
/// <para>Initializes a new instance of the <see cref='System.ComponentModel.AmbientValueAttribute'/> class using a 64-bit signed
/// integer.</para>
@@ -80,34 +76,36 @@ namespace System.ComponentModel
{
Value = value;
}
+
/// <summary>
- /// <para>Initializes a new instance of the <see cref='System.ComponentModel.AmbientValueAttribute'/> class using a
- /// single-precision floating point
- /// number.</para>
+ /// Initializes a new instance of the <see cref='System.ComponentModel.AmbientValueAttribute'/> class using a
+ /// single-precision floating point number.
/// </summary>
public AmbientValueAttribute(float value)
{
Value = value;
}
+
/// <summary>
- /// <para>Initializes a new instance of the <see cref='System.ComponentModel.AmbientValueAttribute'/> class using a
- /// double-precision floating point
- /// number.</para>
+ /// Initializes a new instance of the <see cref='System.ComponentModel.AmbientValueAttribute'/> class using a
+ /// double-precision floating point number.
/// </summary>
public AmbientValueAttribute(double value)
{
Value = value;
}
+
/// <summary>
- /// <para>Initializes a new instance of the <see cref='System.ComponentModel.AmbientValueAttribute'/> class using a <see cref='System.Boolean'/>
- /// value.</para>
+ /// Initializes a new instance of the <see cref='System.ComponentModel.AmbientValueAttribute'/> class using a <see cref='System.Boolean'/>
+ /// value.
/// </summary>
public AmbientValueAttribute(bool value)
{
Value = value;
}
+
/// <summary>
- /// <para>Initializes a new instance of the <see cref='System.ComponentModel.AmbientValueAttribute'/> class using a <see cref='System.String'/>.</para>
+ /// Initializes a new instance of the <see cref='System.ComponentModel.AmbientValueAttribute'/> class using a <see cref='System.String'/>.
/// </summary>
public AmbientValueAttribute(string value)
{
@@ -115,8 +113,8 @@ namespace System.ComponentModel
}
/// <summary>
- /// <para>Initializes a new instance of the <see cref='System.ComponentModel.AmbientValueAttribute'/>
- /// class.</para>
+ /// Initializes a new instance of the <see cref='System.ComponentModel.AmbientValueAttribute'/>
+ /// class.
/// </summary>
public AmbientValueAttribute(object value)
{
@@ -124,11 +122,7 @@ namespace System.ComponentModel
}
/// <summary>
- /// <para>
- /// Gets the ambient value of the property this
- /// attribute is
- /// bound to.
- /// </para>
+ /// Gets the ambient value of the property this attribute is bound to.
/// </summary>
public object Value { get; }
@@ -139,26 +133,14 @@ namespace System.ComponentModel
return true;
}
- AmbientValueAttribute other = obj as AmbientValueAttribute;
-
- if (other != null)
+ if (obj is AmbientValueAttribute other)
{
- if (Value != null)
- {
- return Value.Equals(other.Value);
- }
- else
- {
- return (other.Value == null);
- }
+ return Value != null ? Value.Equals(other.Value) : other.Value == null;
}
+
return false;
}
- public override int GetHashCode()
- {
- return base.GetHashCode();
- }
+ public override int GetHashCode() => base.GetHashCode();
}
}
-
diff --git a/src/System.ComponentModel.TypeConverter/src/System/ComponentModel/BaseNumberConverter.cs b/src/System.ComponentModel.TypeConverter/src/System/ComponentModel/BaseNumberConverter.cs
index 56c6b317ce..69b7487cf7 100644
--- a/src/System.ComponentModel.TypeConverter/src/System/ComponentModel/BaseNumberConverter.cs
+++ b/src/System.ComponentModel.TypeConverter/src/System/ComponentModel/BaseNumberConverter.cs
@@ -36,11 +36,6 @@ namespace System.ComponentModel
internal abstract object FromString(string value, NumberFormatInfo formatInfo);
/// <summary>
- /// Convert the given value to a string using the given CultureInfo
- /// </summary>
- internal abstract object FromString(string value, CultureInfo culture);
-
- /// <summary>
/// Create an error based on the failed text and the exception thrown.
/// </summary>
internal virtual Exception FromStringError(string failedText, Exception innerException)
diff --git a/src/System.ComponentModel.TypeConverter/src/System/ComponentModel/BindingList.cs b/src/System.ComponentModel.TypeConverter/src/System/ComponentModel/BindingList.cs
index 20511a59b9..a53aa9d747 100644
--- a/src/System.ComponentModel.TypeConverter/src/System/ComponentModel/BindingList.cs
+++ b/src/System.ComponentModel.TypeConverter/src/System/ComponentModel/BindingList.cs
@@ -2,23 +2,20 @@
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
-[assembly: System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Naming", "CA1710:IdentifiersShouldHaveCorrectSuffix", Scope = "type", Target = "System.ComponentModel.BindingList`1")]
+using System.Reflection;
+using System.Collections.ObjectModel;
+using System.Collections.Generic;
+using System.Diagnostics;
+using System.Diagnostics.CodeAnalysis;
+using System.Runtime.CompilerServices;
+
+[assembly: SuppressMessage("Microsoft.Naming", "CA1710:IdentifiersShouldHaveCorrectSuffix", Scope = "type", Target = "System.ComponentModel.BindingList`1")]
namespace System.ComponentModel
{
- using System;
- using System.Reflection;
- using System.Collections;
- using System.Collections.ObjectModel;
- using System.Collections.Generic;
- using System.ComponentModel;
- using System.Diagnostics;
-
- /// <summary>
- /// </summary>
[Serializable]
#if !MONO
- [System.Runtime.CompilerServices.TypeForwardedFrom("System, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089")]
+ [TypeForwardedFrom("System, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089")]
#endif
public class BindingList<T> : Collection<T>, IBindingList, ICancelAddNew, IRaiseItemChangedEvents
{
@@ -48,16 +45,10 @@ namespace System.ComponentModel
#region Constructors
- /// <summary>
- /// Default constructor.
- /// </summary>
- public BindingList()
- {
- Initialize();
- }
+ public BindingList() => Initialize();
/// <summary>
- /// Constructor that allows substitution of the inner list with a custom list.
+ /// Constructor that allows substitution of the inner list with a custom list.
/// </summary>
public BindingList(IList<T> list) : base(list)
{
@@ -94,12 +85,8 @@ namespace System.ComponentModel
return true;
}
- if (itemType.GetConstructor(BindingFlags.Public | BindingFlags.Instance | BindingFlags.CreateInstance, null, Array.Empty<Type>(), null) != null)
- {
- return true;
- }
-
- return false;
+ const BindingFlags BindingFlags = BindingFlags.Public | BindingFlags.Instance | BindingFlags.CreateInstance;
+ return itemType.GetConstructor(BindingFlags, null, Array.Empty<Type>(), null) != null;
}
}
@@ -108,7 +95,7 @@ namespace System.ComponentModel
#region AddingNew event
/// <summary>
- /// Event that allows a custom item to be provided as the new item added to the list by AddNew().
+ /// Event that allows a custom item to be provided as the new item added to the list by AddNew().
/// </summary>
public event AddingNewEventHandler AddingNew
{
@@ -133,12 +120,9 @@ namespace System.ComponentModel
}
/// <summary>
- /// Raises the AddingNew event.
+ /// Raises the AddingNew event.
/// </summary>
- protected virtual void OnAddingNew(AddingNewEventArgs e)
- {
- _onAddingNew?.Invoke(this, e);
- }
+ protected virtual void OnAddingNew(AddingNewEventArgs e) => _onAddingNew?.Invoke(this, e);
// Private helper method
private object FireAddingNew()
@@ -153,54 +137,27 @@ namespace System.ComponentModel
#region ListChanged event
/// <summary>
- /// Event that reports changes to the list or to items in the list.
+ /// Event that reports changes to the list or to items in the list.
/// </summary>
public event ListChangedEventHandler ListChanged
{
- add
- {
- _onListChanged += value;
- }
- remove
- {
- _onListChanged -= value;
- }
+ add => _onListChanged += value;
+ remove => _onListChanged -= value;
}
-
/// <summary>
- /// Raises the ListChanged event.
+ /// Raises the ListChanged event.
/// </summary>
- protected virtual void OnListChanged(ListChangedEventArgs e)
- {
- _onListChanged?.Invoke(this, e);
- }
+ protected virtual void OnListChanged(ListChangedEventArgs e) => _onListChanged?.Invoke(this, e);
public bool RaiseListChangedEvents
{
- get
- {
- return raiseListChangedEvents;
- }
-
- set
- {
- if (raiseListChangedEvents != value)
- {
- raiseListChangedEvents = value;
- }
- }
+ get => raiseListChangedEvents;
+ set => raiseListChangedEvents = value;
}
- /// <summary>
- /// </summary>
- public void ResetBindings()
- {
- FireListChanged(ListChangedType.Reset, -1);
- }
+ public void ResetBindings() => FireListChanged(ListChangedType.Reset, -1);
- /// <summary>
- /// </summary>
public void ResetItem(int position)
{
FireListChanged(ListChangedType.ItemChanged, position);
@@ -292,7 +249,7 @@ namespace System.ComponentModel
#region ICancelAddNew interface
/// <summary>
- /// If item added using AddNew() is still cancellable, then remove that item from the list.
+ /// If item added using AddNew() is still cancellable, then remove that item from the list.
/// </summary>
public virtual void CancelNew(int itemIndex)
{
@@ -304,7 +261,7 @@ namespace System.ComponentModel
}
/// <summary>
- /// If item added using AddNew() is still cancellable, then commit that item.
+ /// If item added using AddNew() is still cancellable, then commit that item.
/// </summary>
public virtual void EndNew(int itemIndex)
{
@@ -319,18 +276,15 @@ namespace System.ComponentModel
#region IBindingList interface
/// <summary>
- /// Adds a new item to the list. Calls <see cref='AddNewCore'> to create and add the item.
+ /// Adds a new item to the list. Calls <see cref='AddNewCore'> to create and add the item.
///
- /// Add operations are cancellable via the <see cref='ICancelAddNew'> interface. The position of the
- /// new item is tracked until the add operation is either cancelled by a call to <see cref='CancelNew'>,
- /// explicitly commited by a call to <see cref='EndNew'>, or implicitly commmited some other operation
- /// that changes the contents of the list (such as an Insert or Remove). When an add operation is
+ /// Add operations are cancellable via the <see cref='ICancelAddNew'> interface. The position of the
+ /// new item is tracked until the add operation is either cancelled by a call to <see cref='CancelNew'>,
+ /// explicitly commited by a call to <see cref='EndNew'>, or implicitly commmited some other operation
+ /// changes the contents of the list (such as an Insert or Remove). When an add operation is
/// cancelled, the new item is removed from the list.
/// </summary>
- public T AddNew()
- {
- return (T)((this as IBindingList).AddNew());
- }
+ public T AddNew() => (T)((this as IBindingList).AddNew());
object IBindingList.AddNew()
{
@@ -347,13 +301,13 @@ namespace System.ComponentModel
private bool AddingNewHandled => _onAddingNew != null && _onAddingNew.GetInvocationList().Length > 0;
/// <summary>
- /// Creates a new item and adds it to the list.
+ /// Creates a new item and adds it to the list.
///
- /// The base implementation raises the AddingNew event to allow an event handler to
- /// supply a custom item to add to the list. Otherwise an item of type T is created.
- /// The new item is then added to the end of the list.
+ /// The base implementation raises the AddingNew event to allow an event handler to
+ /// supply a custom item to add to the list. Otherwise an item of type T is created.
+ /// The new item is then added to the end of the list.
/// </summary>
- [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Security", "CA2113:SecureLateBindingMethods")]
+ [SuppressMessage("Microsoft.Security", "CA2113:SecureLateBindingMethods")]
protected virtual object AddNewCore()
{
// Allow event handler to supply the new item for us
@@ -380,22 +334,22 @@ namespace System.ComponentModel
{
get
{
- //If the user set AllowNew, return what they set. If we have a default constructor, allowNew will be
- //true and we should just return true.
+ // If the user set AllowNew, return what they set. If we have a default constructor, allowNew will be
+ // true and we should just return true.
if (userSetAllowNew || allowNew)
{
return allowNew;
}
- //Even if the item doesn't have a default constructor, the user can hook AddingNew to provide an item.
- //If there's a handler for this, we should allow new.
+ // Even if the item doesn't have a default constructor, the user can hook AddingNew to provide an item.
+ // If there's a handler for this, we should allow new.
return AddingNewHandled;
}
set
{
bool oldAllowNewValue = AllowNew;
userSetAllowNew = true;
- //Note that we don't want to set allowNew only if AllowNew didn't match value,
- //since AllowNew can depend on onAddingNew handler
+ // Note that we don't want to set allowNew only if AllowNew didn't match value,
+ // since AllowNew can depend on onAddingNew handler
allowNew = value;
if (oldAllowNewValue != value)
{
@@ -404,17 +358,11 @@ namespace System.ComponentModel
}
}
- /* private */
bool IBindingList.AllowNew => AllowNew;
- /// <summary>
- /// </summary>
public bool AllowEdit
{
- get
- {
- return allowEdit;
- }
+ get => allowEdit;
set
{
if (allowEdit != value)
@@ -425,17 +373,11 @@ namespace System.ComponentModel
}
}
- /* private */
bool IBindingList.AllowEdit => AllowEdit;
- /// <summary>
- /// </summary>
public bool AllowRemove
{
- get
- {
- return allowRemove;
- }
+ get => allowRemove;
set
{
if (allowRemove != value)
@@ -446,7 +388,6 @@ namespace System.ComponentModel
}
}
- /* private */
bool IBindingList.AllowRemove => AllowRemove;
bool IBindingList.SupportsChangeNotification => SupportsChangeNotificationCore;
@@ -483,20 +424,14 @@ namespace System.ComponentModel
throw new NotSupportedException();
}
- void IBindingList.RemoveSort()
- {
- RemoveSortCore();
- }
+ void IBindingList.RemoveSort() => RemoveSortCore();
protected virtual void RemoveSortCore()
{
throw new NotSupportedException();
}
- int IBindingList.Find(PropertyDescriptor prop, object key)
- {
- return FindCore(prop, key);
- }
+ int IBindingList.Find(PropertyDescriptor prop, object key) => FindCore(prop, key);
protected virtual int FindCore(PropertyDescriptor prop, object key)
{
@@ -519,10 +454,8 @@ namespace System.ComponentModel
private void HookPropertyChanged(T item)
{
- INotifyPropertyChanged inpc = (item as INotifyPropertyChanged);
-
// Note: inpc may be null if item is null, so always check.
- if (null != inpc)
+ if (item is INotifyPropertyChanged inpc)
{
if (_propertyChangedEventHandler == null)
{
@@ -534,10 +467,8 @@ namespace System.ComponentModel
private void UnhookPropertyChanged(T item)
{
- INotifyPropertyChanged inpc = (item as INotifyPropertyChanged);
-
// Note: inpc may be null if item is null, so always check.
- if (null != inpc && null != _propertyChangedEventHandler)
+ if (item is INotifyPropertyChanged inpc && _propertyChangedEventHandler != null)
{
inpc.PropertyChanged -= _propertyChangedEventHandler;
}
@@ -555,7 +486,7 @@ namespace System.ComponentModel
else
{
// The change event is broken should someone pass an item to us that is not
- // of type T. Still, if they do so, detect it and ignore. It is an incorrect
+ // of type T. Still, if they do so, detect it and ignore. It is an incorrect
// and rare enough occurrence that we do not want to slow the mainline path
// with "is" checks.
T item;
@@ -570,7 +501,7 @@ namespace System.ComponentModel
return;
}
- // Find the position of the item. This should never be -1. If it is,
+ // Find the position of the item. This should never be -1. If it is,
// somehow the item has been removed from our list without our knowledge.
int pos = _lastChangeIndex;
@@ -582,7 +513,8 @@ namespace System.ComponentModel
if (pos == -1)
{
- Debug.Fail("Item is no longer in our list but we are still getting change notifications.");
+ // The item was removed from the list but we still get change notifications or
+ // the sender is invalid and was never added to the list.
UnhookPropertyChanged(item);
ResetBindings();
}
@@ -598,7 +530,7 @@ namespace System.ComponentModel
PropertyDescriptor pd = _itemTypeProperties.Find(e.PropertyName, true);
- // Create event args. If there was no matching property descriptor,
+ // Create event args. If there was no matching property descriptor,
// we raise the list changed anyway.
ListChangedEventArgs args = new ListChangedEventArgs(ListChangedType.ItemChanged, pos, pd);
@@ -614,9 +546,9 @@ namespace System.ComponentModel
#region IRaiseItemChangedEvents interface
/// <summary>
- /// Returns false to indicate that BindingList<T> does NOT raise ListChanged events
- /// of type ItemChanged as a result of property changes on individual list items
- /// unless those items support INotifyPropertyChanged
+ /// Returns false to indicate that BindingList<T> does NOT raise ListChanged events
+ /// of type ItemChanged as a result of property changes on individual list items
+ /// unless those items support INotifyPropertyChanged.
/// </summary>
bool IRaiseItemChangedEvents.RaisesItemChangedEvents => raiseItemChangedEvents;
diff --git a/src/System.ComponentModel.TypeConverter/src/System/ComponentModel/ByteConverter.cs b/src/System.ComponentModel.TypeConverter/src/System/ComponentModel/ByteConverter.cs
index 163a0f082c..baffdd2d6a 100644
--- a/src/System.ComponentModel.TypeConverter/src/System/ComponentModel/ByteConverter.cs
+++ b/src/System.ComponentModel.TypeConverter/src/System/ComponentModel/ByteConverter.cs
@@ -34,15 +34,6 @@ namespace System.ComponentModel
return Byte.Parse(value, NumberStyles.Integer, formatInfo);
}
-
- /// <summary>
- /// Convert the given string to a Byte using the given CultureInfo
- /// </summary>
- internal override object FromString(string value, CultureInfo culture)
- {
- return Byte.Parse(value, culture);
- }
-
/// <summary>
/// Convert the given value to a string using the given formatInfo
/// </summary>
diff --git a/src/System.ComponentModel.TypeConverter/src/System/ComponentModel/ComponentResourceManager.cs b/src/System.ComponentModel.TypeConverter/src/System/ComponentModel/ComponentResourceManager.cs
index e7baf6f8e6..265da59ef2 100644
--- a/src/System.ComponentModel.TypeConverter/src/System/ComponentModel/ComponentResourceManager.cs
+++ b/src/System.ComponentModel.TypeConverter/src/System/ComponentModel/ComponentResourceManager.cs
@@ -132,12 +132,7 @@ namespace System.ComponentModel
foreach (KeyValuePair<string, object> kvp in resources)
{
// See if this key matches our object.
- //
string key = kvp.Key;
- if (key == null)
- {
- continue;
- }
if (IgnoreCase)
{
diff --git a/src/System.ComponentModel.TypeConverter/src/System/ComponentModel/Container.cs b/src/System.ComponentModel.TypeConverter/src/System/ComponentModel/Container.cs
index 41017d3167..2c87c068a1 100644
--- a/src/System.ComponentModel.TypeConverter/src/System/ComponentModel/Container.cs
+++ b/src/System.ComponentModel.TypeConverter/src/System/ComponentModel/Container.cs
@@ -2,20 +2,10 @@
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
-using System;
-using System.ComponentModel;
-using System.Diagnostics;
-using System.Globalization;
-using System.IO;
-using System.Security.Permissions;
-
namespace System.ComponentModel
{
/// <summary>
- /// <para>
- /// Encapsulates
- /// zero or more components.
- /// </para>
+ /// Encapsulates zero or more components.
/// </summary>
public class Container : IContainer
{
@@ -25,19 +15,13 @@ namespace System.ComponentModel
private ContainerFilterService _filter;
private bool _checkedFilter;
- private readonly object _syncObj = new Object();
+ private readonly object _syncObj = new object();
- ~Container()
- {
- Dispose(false);
- }
+ ~Container() => Dispose(false);
- // Adds a component to the container.
/// <summary>
- /// <para>
- /// Adds the specified component to the <see cref='System.ComponentModel.Container'/>
- /// . The component is unnamed.
- /// </para>
+ /// Adds the specified component to the <see cref='System.ComponentModel.Container'/>
+ /// The component is unnamed.
/// </summary>
public virtual void Add(IComponent component)
{
@@ -46,12 +30,10 @@ namespace System.ComponentModel
// Adds a component to the container.
/// <summary>
- /// <para>
- /// Adds the specified component to the <see cref='System.ComponentModel.Container'/> and assigns a name to
- /// it.
- /// </para>
+ /// Adds the specified component to the <see cref='System.ComponentModel.Container'/> and assigns
+ /// a name to it.
/// </summary>
- public virtual void Add(IComponent component, String name)
+ public virtual void Add(IComponent component, string name)
{
lock (_syncObj)
{
@@ -61,7 +43,6 @@ namespace System.ComponentModel
}
ISite site = component.Site;
-
if (site != null && site.Container == this)
{
return;
@@ -95,40 +76,34 @@ namespace System.ComponentModel
}
}
- // Creates a site for the component within the container.
/// <summary>
- /// <para>Creates a Site <see cref='System.ComponentModel.ISite'/> for the given <see cref='System.ComponentModel.IComponent'/>
- /// and assigns the given name to the site.</para>
+ /// Creates a Site <see cref='System.ComponentModel.ISite'/> for the given <see cref='System.ComponentModel.IComponent'/>
+ /// and assigns the given name to the site.
/// </summary>
protected virtual ISite CreateSite(IComponent component, string name)
{
return new Site(component, this, name);
}
- // Disposes of the container. A call to the Dispose method indicates that
- // the user of the container has no further need for it.
- //
- // The implementation of Dispose must:
- //
- // (1) Remove any references the container is holding to other components.
- // This is typically accomplished by assigning null to any fields that
- // contain references to other components.
- //
- // (2) Release any system resources that are associated with the container,
- // such as file handles, window handles, or database connections.
- //
- // (3) Dispose of child components by calling the Dispose method of each.
- //
- // Ideally, a call to Dispose will revert a container to the state it was
- // in immediately after it was created. However, this is not a requirement.
- // Following a call to its Dispose method, a container is permitted to raise
- // exceptions for operations that cannot meaningfully be performed.
- //
/// <summary>
- /// <para>
- /// Disposes of the <see cref='System.ComponentModel.Container'/>
- /// .
- /// </para>
+ /// Disposes of the container. A call to the Dispose method indicates that
+ /// the user of the container has no further need for it.
+ ///
+ /// The implementation of Dispose must:
+ ///
+ /// (1) Remove any references the container is holding to other components.
+ /// This is typically accomplished by assigning null to any fields that
+ /// contain references to other components.
+ ///
+ /// (2) Release any system resources that are associated with the container,
+ /// such as file handles, window handles, or database connections.
+ ///
+ /// (3) Dispose of child components by calling the Dispose method of each.
+ ///
+ /// Ideally, a call to Dispose will revert a container to the state it was
+ /// in immediately after it was created. However, this is not a requirement.
+ /// Following a call to its Dispose method, a container is permitted to raise
+ /// exceptions for operations that cannot meaningfully be performed.
/// </summary>
public void Dispose()
{
@@ -154,20 +129,10 @@ namespace System.ComponentModel
}
}
+ protected virtual object GetService(Type service) => service == typeof(IContainer) ? this : null;
+
/// <summary>
- /// <para>[To be supplied.]</para>
- /// </summary>
- protected virtual object GetService(Type service)
- {
- return ((service == typeof(IContainer)) ? this : null);
- }
-
- // The components in the container.
- /// <summary>
- /// <para>
- /// Gets all the components in the <see cref='System.ComponentModel.Container'/>
- /// .
- /// </para>
+ /// Gets all the components in the <see cref='System.ComponentModel.Container'/>.
/// </summary>
public virtual ComponentCollection Components
{
@@ -201,7 +166,6 @@ namespace System.ComponentModel
if (_filter != null)
{
ComponentCollection filteredComponents = _filter.FilterComponents(_components);
- Debug.Assert(filteredComponents != null, "Incorrect ContainerFilterService implementation.");
if (filteredComponents != null)
{
_components = filteredComponents;
@@ -213,17 +177,10 @@ namespace System.ComponentModel
}
}
- // Removes a component from the container.
/// <summary>
- /// <para>
- /// Removes a component from the <see cref='System.ComponentModel.Container'/>
- /// .
- /// </para>
+ /// Removes a component from the <see cref='System.ComponentModel.Container'/>.
/// </summary>
- public virtual void Remove(IComponent component)
- {
- Remove(component, false);
- }
+ public virtual void Remove(IComponent component) => Remove(component, false);
private void Remove(IComponent component, bool preserveSite)
{
@@ -231,9 +188,15 @@ namespace System.ComponentModel
{
ISite site = component?.Site;
if (site == null || site.Container != this)
+ {
return;
+ }
+
if (!preserveSite)
+ {
component.Site = null;
+ }
+
for (int i = 0; i < _siteCount; i++)
{
if (_sites[i] == site)
@@ -248,15 +211,12 @@ namespace System.ComponentModel
}
}
- protected void RemoveWithoutUnsiting(IComponent component)
- {
- Remove(component, true);
- }
+ protected void RemoveWithoutUnsiting(IComponent component) => Remove(component, true);
/// <summary>
- /// Validates that the given name is valid for a component. The default implementation
- /// verifies that name is either null or unique compared to the names of other
- /// components in the container.
+ /// Validates that the given name is valid for a component. The default implementation
+ /// verifies that name is either null or unique compared to the names of other
+ /// components in the container.
/// </summary>
protected virtual void ValidateName(IComponent component, string name)
{
@@ -285,40 +245,45 @@ namespace System.ComponentModel
private class Site : ISite
{
- private String _name;
+ private string _name;
- internal Site(IComponent component, Container container, String name)
+ internal Site(IComponent component, Container container, string name)
{
Component = component;
Container = container;
_name = name;
}
- // The component sited by this component site.
+ /// <summary>
+ /// The component sited by this component site.
+ /// </summary>
public IComponent Component { get; }
- // The container in which the component is sited.
+ /// <summary>
+ /// The container in which the component is sited.
+ /// </summary>
public IContainer Container { get; }
- public Object GetService(Type service)
+ public object GetService(Type service)
{
return ((service == typeof(ISite)) ? this : ((Container)Container).GetService(service));
}
-
- // Indicates whether the component is in design mode.
+ /// <summary>
+ /// Indicates whether the component is in design mode.
+ /// </summary>
public bool DesignMode => false;
- // The name of the component.
- //
- public String Name
+ /// <summary>
+ /// The name of the component.
+ /// </summary>
+ public string Name
{
get { return _name; }
set
{
if (value == null || _name == null || !value.Equals(_name))
{
- // UNDONE : This is a breaking change.
((Container)Container).ValidateName(Component, value);
_name = value;
}
diff --git a/src/System.ComponentModel.TypeConverter/src/System/ComponentModel/DecimalConverter.cs b/src/System.ComponentModel.TypeConverter/src/System/ComponentModel/DecimalConverter.cs
index 5d1aecb30f..1c35836b2d 100644
--- a/src/System.ComponentModel.TypeConverter/src/System/ComponentModel/DecimalConverter.cs
+++ b/src/System.ComponentModel.TypeConverter/src/System/ComponentModel/DecimalConverter.cs
@@ -91,15 +91,6 @@ namespace System.ComponentModel
return Decimal.Parse(value, NumberStyles.Float, formatInfo);
}
-
- /// <summary>
- /// Convert the given value to a string using the given CultureInfo
- /// </summary>
- internal override object FromString(string value, CultureInfo culture)
- {
- return Decimal.Parse(value, culture);
- }
-
/// <summary>
/// Convert the given value from a string using the given formatInfo
/// </summary>
diff --git a/src/System.ComponentModel.TypeConverter/src/System/ComponentModel/DoubleConverter.cs b/src/System.ComponentModel.TypeConverter/src/System/ComponentModel/DoubleConverter.cs
index cd5d9441ce..16cf875e97 100644
--- a/src/System.ComponentModel.TypeConverter/src/System/ComponentModel/DoubleConverter.cs
+++ b/src/System.ComponentModel.TypeConverter/src/System/ComponentModel/DoubleConverter.cs
@@ -39,15 +39,6 @@ namespace System.ComponentModel
return Double.Parse(value, NumberStyles.Float, formatInfo);
}
-
- /// <summary>
- /// Convert the given value to a string using the given CultureInfo
- /// </summary>
- internal override object FromString(string value, CultureInfo culture)
- {
- return Double.Parse(value, culture);
- }
-
/// <summary>
/// Convert the given value from a string using the given formatInfo
/// </summary>
diff --git a/src/System.ComponentModel.TypeConverter/src/System/ComponentModel/Int16Converter.cs b/src/System.ComponentModel.TypeConverter/src/System/ComponentModel/Int16Converter.cs
index dbc27d94da..88ea747e6b 100644
--- a/src/System.ComponentModel.TypeConverter/src/System/ComponentModel/Int16Converter.cs
+++ b/src/System.ComponentModel.TypeConverter/src/System/ComponentModel/Int16Converter.cs
@@ -26,15 +26,6 @@ namespace System.ComponentModel
}
/// <summary>
- /// Convert the given value to a string using the given CultureInfo
- /// </summary>
- internal override object FromString(string value, CultureInfo culture)
- {
- return Int16.Parse(value, culture);
- }
-
-
- /// <summary>
/// Convert the given value to a string using the given formatInfo
/// </summary>
internal override object FromString(string value, NumberFormatInfo formatInfo)
diff --git a/src/System.ComponentModel.TypeConverter/src/System/ComponentModel/Int32Converter.cs b/src/System.ComponentModel.TypeConverter/src/System/ComponentModel/Int32Converter.cs
index b1e49ac205..a3aa16f1ca 100644
--- a/src/System.ComponentModel.TypeConverter/src/System/ComponentModel/Int32Converter.cs
+++ b/src/System.ComponentModel.TypeConverter/src/System/ComponentModel/Int32Converter.cs
@@ -33,17 +33,6 @@ namespace System.ComponentModel
return Int32.Parse(value, NumberStyles.Integer, formatInfo);
}
-
- /// <summary>
- /// Convert the given value to a string using the given CultureInfo
- /// </summary>
- internal override object FromString(string value, CultureInfo culture)
- {
- return Int32.Parse(value, culture);
- }
-
-
-
/// <summary>
/// Convert the given value from a string using the given formatInfo
/// </summary>
diff --git a/src/System.ComponentModel.TypeConverter/src/System/ComponentModel/Int64Converter.cs b/src/System.ComponentModel.TypeConverter/src/System/ComponentModel/Int64Converter.cs
index 96f0ecb7e9..af1c17e0fd 100644
--- a/src/System.ComponentModel.TypeConverter/src/System/ComponentModel/Int64Converter.cs
+++ b/src/System.ComponentModel.TypeConverter/src/System/ComponentModel/Int64Converter.cs
@@ -32,16 +32,7 @@ namespace System.ComponentModel
{
return Int64.Parse(value, NumberStyles.Integer, formatInfo);
}
-
-
- /// <summary>
- /// Convert the given value to a string using the given CultureInfo
- /// </summary>
- internal override object FromString(string value, CultureInfo culture)
- {
- return Int64.Parse(value, culture);
- }
-
+
/// <summary>
/// Convert the given value from a string using the given formatInfo
/// </summary>
diff --git a/src/System.ComponentModel.TypeConverter/src/System/ComponentModel/SByteConverter.cs b/src/System.ComponentModel.TypeConverter/src/System/ComponentModel/SByteConverter.cs
index 55e7596bff..3d493c7399 100644
--- a/src/System.ComponentModel.TypeConverter/src/System/ComponentModel/SByteConverter.cs
+++ b/src/System.ComponentModel.TypeConverter/src/System/ComponentModel/SByteConverter.cs
@@ -34,15 +34,6 @@ namespace System.ComponentModel
return SByte.Parse(value, NumberStyles.Integer, formatInfo);
}
-
- /// <summary>
- /// Convert the given value to a string using the given CultureInfo
- /// </summary>
- internal override object FromString(string value, CultureInfo culture)
- {
- return SByte.Parse(value, culture);
- }
-
/// <summary>
/// Convert the given value from a string using the given formatInfo
/// </summary>
diff --git a/src/System.ComponentModel.TypeConverter/src/System/ComponentModel/SingleConverter.cs b/src/System.ComponentModel.TypeConverter/src/System/ComponentModel/SingleConverter.cs
index 12e3c2e099..a34d758313 100644
--- a/src/System.ComponentModel.TypeConverter/src/System/ComponentModel/SingleConverter.cs
+++ b/src/System.ComponentModel.TypeConverter/src/System/ComponentModel/SingleConverter.cs
@@ -39,15 +39,6 @@ namespace System.ComponentModel
return Single.Parse(value, NumberStyles.Float, formatInfo);
}
-
- /// <summary>
- /// Convert the given value to a string using the given CultureInfo
- /// </summary>
- internal override object FromString(string value, CultureInfo culture)
- {
- return Single.Parse(value, culture);
- }
-
/// <summary>
/// Convert the given value from a string using the given formatInfo
/// </summary>
diff --git a/src/System.ComponentModel.TypeConverter/src/System/ComponentModel/UInt16Converter.cs b/src/System.ComponentModel.TypeConverter/src/System/ComponentModel/UInt16Converter.cs
index 3de486cdbf..d18a2555e6 100644
--- a/src/System.ComponentModel.TypeConverter/src/System/ComponentModel/UInt16Converter.cs
+++ b/src/System.ComponentModel.TypeConverter/src/System/ComponentModel/UInt16Converter.cs
@@ -33,15 +33,6 @@ namespace System.ComponentModel
return UInt16.Parse(value, NumberStyles.Integer, formatInfo);
}
-
- /// <summary>
- /// Convert the given value to a string using the given CultureInfo
- /// </summary>
- internal override object FromString(string value, CultureInfo culture)
- {
- return UInt16.Parse(value, culture);
- }
-
/// <summary>
/// Convert the given value from a string using the given formatInfo
/// </summary>
diff --git a/src/System.ComponentModel.TypeConverter/src/System/ComponentModel/UInt32Converter.cs b/src/System.ComponentModel.TypeConverter/src/System/ComponentModel/UInt32Converter.cs
index 201bbfb3ef..3c3ee9f2a6 100644
--- a/src/System.ComponentModel.TypeConverter/src/System/ComponentModel/UInt32Converter.cs
+++ b/src/System.ComponentModel.TypeConverter/src/System/ComponentModel/UInt32Converter.cs
@@ -33,15 +33,6 @@ namespace System.ComponentModel
return UInt32.Parse(value, NumberStyles.Integer, formatInfo);
}
-
- /// <summary>
- /// Convert the given value to a string using the given CultureInfo
- /// </summary>
- internal override object FromString(string value, CultureInfo culture)
- {
- return UInt32.Parse(value, culture);
- }
-
/// <summary>
/// Convert the given value from a string using the given formatInfo
/// </summary>
diff --git a/src/System.ComponentModel.TypeConverter/src/System/ComponentModel/UInt64Converter.cs b/src/System.ComponentModel.TypeConverter/src/System/ComponentModel/UInt64Converter.cs
index 913a9ce1a8..ff19a57a85 100644
--- a/src/System.ComponentModel.TypeConverter/src/System/ComponentModel/UInt64Converter.cs
+++ b/src/System.ComponentModel.TypeConverter/src/System/ComponentModel/UInt64Converter.cs
@@ -33,15 +33,6 @@ namespace System.ComponentModel
return UInt64.Parse(value, NumberStyles.Integer, formatInfo);
}
-
- /// <summary>
- /// Convert the given value to a string using the given CultureInfo
- /// </summary>
- internal override object FromString(string value, CultureInfo culture)
- {
- return UInt64.Parse(value, culture);
- }
-
/// <summary>
/// Convert the given value from a string using the given formatInfo
/// </summary>
diff --git a/src/System.ComponentModel.TypeConverter/tests/AmbientValueAttributeTests.cs b/src/System.ComponentModel.TypeConverter/tests/AmbientValueAttributeTests.cs
new file mode 100644
index 0000000000..166670a484
--- /dev/null
+++ b/src/System.ComponentModel.TypeConverter/tests/AmbientValueAttributeTests.cs
@@ -0,0 +1,133 @@
+// Licensed to the .NET Foundation under one or more agreements.
+// The .NET Foundation licenses this file to you under the MIT license.
+// See the LICENSE file in the project root for more information.
+
+using System.Collections.Generic;
+using Xunit;
+
+namespace System.ComponentModel.Tests
+{
+ public class AmbientValueAttributeTests
+ {
+ [Theory]
+ [InlineData(null, null, null)]
+ [InlineData(typeof(int*), "1", null)]
+ [InlineData(typeof(string), "1", "1")]
+ [InlineData(typeof(int), "1", 1)]
+ public void Ctor_Type_Value(Type type, string value, object expectedValue)
+ {
+ var attribute = new AmbientValueAttribute(type, value);
+ Assert.Equal(expectedValue, attribute.Value);
+ }
+
+ [Fact]
+ public void Ctor_Char()
+ {
+ char value = 'a';
+ var args = new AmbientValueAttribute(value);
+ Assert.Equal(value, args.Value);
+ }
+
+ [Fact]
+ public void Ctor_Byte()
+ {
+ byte value = 123;
+ var args = new AmbientValueAttribute(value);
+ Assert.Equal(value, args.Value);
+ }
+
+ [Fact]
+ public void Ctor_Short()
+ {
+ short value = 123;
+ var args = new AmbientValueAttribute(value);
+ Assert.Equal(value, args.Value);
+ }
+
+ [Fact]
+ public void Ctor_Int()
+ {
+ int value = 123;
+ var args = new AmbientValueAttribute(value);
+ Assert.Equal(value, args.Value);
+ }
+
+ [Fact]
+ public void Ctor_Long()
+ {
+ long value = 123;
+ var args = new AmbientValueAttribute(value);
+ Assert.Equal(value, args.Value);
+ }
+
+ [Fact]
+ public void Ctor_Float()
+ {
+ float value = 123;
+ var args = new AmbientValueAttribute(value);
+ Assert.Equal(value, args.Value);
+ }
+
+ [Fact]
+ public void Ctor_Double()
+ {
+ double value = 123;
+ var args = new AmbientValueAttribute(value);
+ Assert.Equal(value, args.Value);
+ }
+
+ [Fact]
+ public void Ctor_Bool()
+ {
+ bool value = true;
+ var args = new AmbientValueAttribute(value);
+ Assert.Equal(value, args.Value);
+ }
+
+ [Theory]
+ [InlineData(null)]
+ [InlineData("Value")]
+ public void Ctor_String(string value)
+ {
+ var args = new AmbientValueAttribute(value);
+ Assert.Same(value, args.Value);
+ }
+
+ [Theory]
+ [InlineData(null)]
+ [InlineData("Value")]
+ public void Ctor_Object(object value)
+ {
+ var args = new AmbientValueAttribute(value);
+ Assert.Same(value, args.Value);
+ }
+
+ public static IEnumerable<object[]> Equals_TestData()
+ {
+ var attribute = new AmbientValueAttribute(true);
+ yield return new object[] { attribute, attribute, true };
+ yield return new object[] { new AmbientValueAttribute(true), new AmbientValueAttribute(true), true };
+ yield return new object[] { new AmbientValueAttribute(true), new AmbientValueAttribute(false), false };
+ yield return new object[] { new AmbientValueAttribute(true), new AmbientValueAttribute(null), false };
+ yield return new object[] { new AmbientValueAttribute(null), new AmbientValueAttribute(false), false };
+ yield return new object[] { new AmbientValueAttribute(null), new AmbientValueAttribute(null), true };
+
+ yield return new object[] { new AmbientValueAttribute(true), new object(), false };
+ yield return new object[] { new AmbientValueAttribute(true), null, false };
+ }
+
+ [Theory]
+ [MemberData(nameof(Equals_TestData))]
+ public void Equals_Object_ReturnsExpected(AmbientValueAttribute attribute, object other, bool expected)
+ {
+ Assert.Equal(expected, attribute.Equals(other));
+ }
+
+ [Fact]
+ public void GetHashCode_Invoke_ReturnsConsistentValue()
+ {
+ var attribute = new AmbientValueAttribute(null);
+ Assert.Equal(attribute.GetHashCode(), attribute.GetHashCode());
+ }
+ }
+}
diff --git a/src/System.ComponentModel.TypeConverter/tests/BindingListTests.cs b/src/System.ComponentModel.TypeConverter/tests/BindingListTests.cs
index 018e7767b2..f22bc2f134 100644
--- a/src/System.ComponentModel.TypeConverter/tests/BindingListTests.cs
+++ b/src/System.ComponentModel.TypeConverter/tests/BindingListTests.cs
@@ -9,671 +9,996 @@ namespace System.ComponentModel.Tests
public class BindingListTest
{
[Fact]
- public void BindingListDefaults()
+ public void Ctor_Default()
{
- BindingList<string> l = new BindingList<string>();
- IBindingList ibl = (IBindingList)l;
-
- Assert.True(l.AllowEdit, "1");
- Assert.False(l.AllowNew, "2");
- Assert.True(l.AllowRemove, "3");
- Assert.True(l.RaiseListChangedEvents, "4");
-
- Assert.False(ibl.IsSorted, "5");
- Assert.Equal(ibl.SortDirection, ListSortDirection.Ascending);
- Assert.True(ibl.SupportsChangeNotification, "7");
- Assert.False(ibl.SupportsSearching, "8");
- Assert.False(ibl.SupportsSorting, "9");
- Assert.False(((IRaiseItemChangedEvents)l).RaisesItemChangedEvents, "10");
+ var list = new BindingList<string>();
+ IBindingList iBindingList = list;
+
+ Assert.True(list.AllowEdit);
+ Assert.False(list.AllowNew);
+ Assert.True(list.AllowRemove);
+ Assert.True(list.RaiseListChangedEvents);
+
+ Assert.True(iBindingList.AllowEdit);
+ Assert.False(iBindingList.AllowNew);
+ Assert.True(iBindingList.AllowRemove);
+ Assert.Equal(ListSortDirection.Ascending, iBindingList.SortDirection);
+ Assert.True(iBindingList.SupportsChangeNotification);
+ Assert.False(iBindingList.SupportsSearching);
+ Assert.False(iBindingList.SupportsSorting);
+ Assert.False(((IRaiseItemChangedEvents)list).RaisesItemChangedEvents);
}
[Fact]
- public void BindingListDefaults_FixedSizeList()
+ public void Ctor_FixedSizeIList()
{
- string[] arr = new string[10];
- BindingList<string> l = new BindingList<string>(arr);
- IBindingList ibl = (IBindingList)l;
-
- Assert.True(l.AllowEdit, "1");
- Assert.False(l.AllowNew, "2");
- Assert.True(l.AllowRemove, "3");
- Assert.True(l.RaiseListChangedEvents, "4");
-
- Assert.False(ibl.IsSorted, "5");
- Assert.Equal(ibl.SortDirection, ListSortDirection.Ascending);
- Assert.True(ibl.SupportsChangeNotification, "7");
- Assert.False(ibl.SupportsSearching, "8");
- Assert.False(ibl.SupportsSorting, "9");
- Assert.False(((IRaiseItemChangedEvents)l).RaisesItemChangedEvents, "10");
+ var array = new string[10];
+ var bindingList = new BindingList<string>(array);
+ IBindingList iBindingList = bindingList;
+
+ Assert.True(bindingList.AllowEdit);
+ Assert.False(bindingList.AllowNew);
+ Assert.True(bindingList.AllowRemove);
+ Assert.True(bindingList.RaiseListChangedEvents);
+
+ Assert.True(iBindingList.AllowEdit);
+ Assert.False(iBindingList.AllowNew);
+ Assert.True(iBindingList.AllowRemove);
+ Assert.False(iBindingList.IsSorted);
+ Assert.Equal(ListSortDirection.Ascending, iBindingList.SortDirection);
+ Assert.True(iBindingList.SupportsChangeNotification);
+ Assert.False(iBindingList.SupportsSearching);
+ Assert.False(iBindingList.SupportsSorting);
+ Assert.False(((IRaiseItemChangedEvents)bindingList).RaisesItemChangedEvents);
}
[Fact]
- public void BindingListDefaults_NonFixedSizeList()
+ public void Ctor_NonFixedSizeIList()
{
- List<string> list = new List<string>();
- BindingList<string> l = new BindingList<string>(list);
- IBindingList ibl = (IBindingList)l;
-
- Assert.True(l.AllowEdit, "1");
- Assert.False(l.AllowNew, "2");
- Assert.True(l.AllowRemove, "3");
- Assert.True(l.RaiseListChangedEvents, "4");
-
- Assert.False(ibl.IsSorted, "5");
- Assert.Equal(ibl.SortDirection, ListSortDirection.Ascending);
- Assert.True(ibl.SupportsChangeNotification, "7");
- Assert.False(ibl.SupportsSearching, "8");
- Assert.False(ibl.SupportsSorting, "9");
- Assert.False(((IRaiseItemChangedEvents)l).RaisesItemChangedEvents, "10");
+ var list = new List<string>();
+ var bindingList = new BindingList<string>(list);
+ IBindingList iBindingList = bindingList;
+
+ Assert.True(bindingList.AllowEdit);
+ Assert.False(bindingList.AllowNew);
+ Assert.True(bindingList.AllowRemove);
+ Assert.True(bindingList.RaiseListChangedEvents);
+
+ Assert.True(iBindingList.AllowEdit);
+ Assert.False(iBindingList.AllowNew);
+ Assert.True(iBindingList.AllowRemove);
+ Assert.False(iBindingList.IsSorted);
+ Assert.Equal(ListSortDirection.Ascending, iBindingList.SortDirection);
+ Assert.True(iBindingList.SupportsChangeNotification);
+ Assert.False(iBindingList.SupportsSearching);
+ Assert.False(iBindingList.SupportsSorting);
+ Assert.False(((IRaiseItemChangedEvents)bindingList).RaisesItemChangedEvents);
}
[Fact]
- public void BindingListDefaults_ReadOnlyList()
+ public void Ctor_IReadOnlyList()
{
- List<string> list = new List<string>();
- BindingList<string> l = new BindingList<string>(list);
- IBindingList ibl = (IBindingList)l;
-
- Assert.True(l.AllowEdit, "1");
- Assert.False(l.AllowNew, "2");
- Assert.True(l.AllowRemove, "3");
- Assert.True(l.RaiseListChangedEvents, "4");
-
- Assert.False(ibl.IsSorted, "5");
- Assert.Equal(ibl.SortDirection, ListSortDirection.Ascending);
- Assert.True(ibl.SupportsChangeNotification, "7");
- Assert.False(ibl.SupportsSearching, "8");
- Assert.False(ibl.SupportsSorting, "9");
- Assert.False(((IRaiseItemChangedEvents)l).RaisesItemChangedEvents, "10");
+ var list = new List<string>();
+ var bindingList = new BindingList<string>(list);
+ IBindingList iBindingList = bindingList;
+
+ Assert.True(bindingList.AllowEdit);
+ Assert.False(bindingList.AllowNew);
+ Assert.True(bindingList.AllowRemove);
+ Assert.True(bindingList.RaiseListChangedEvents);
+
+ Assert.True(iBindingList.AllowEdit);
+ Assert.False(iBindingList.AllowNew);
+ Assert.True(iBindingList.AllowRemove);
+ Assert.False(iBindingList.IsSorted);
+ Assert.Equal(ListSortDirection.Ascending, iBindingList.SortDirection);
+ Assert.True(iBindingList.SupportsChangeNotification);
+ Assert.False(iBindingList.SupportsSearching);
+ Assert.False(iBindingList.SupportsSorting);
+ Assert.False(((IRaiseItemChangedEvents)bindingList).RaisesItemChangedEvents);
}
[Fact]
- public void TestAllowNew()
+ public void AllowNew_GetWithDefaultCtor_ReturnsTrue()
{
- // Object has a default ctor
- BindingList<object> l1 = new BindingList<object>();
- Assert.True(l1.AllowNew, "1");
+ var bindingList = new BindingList<object>();
+ Assert.True(bindingList.AllowNew);
+ }
- // string has no default ctor
- BindingList<string> l2 = new BindingList<string>();
- Assert.False(l2.AllowNew, "2");
+ [Fact]
+ public void AllowNew_Primitive_ReturnsTrue()
+ {
+ var bindingList = new BindingList<int>();
+ Assert.True(bindingList.AllowNew);
+ }
- // adding a delegate to AddingNew fixes that
- l2.AddingNew += delegate (object sender, AddingNewEventArgs e) { };
- Assert.True(l2.AllowNew, "3");
+ [Fact]
+ public void AllowNew_NoDefaultCtor_ReturnsExpected()
+ {
+ var bindingList = new BindingList<string>();
+ Assert.False(bindingList.AllowNew);
- l1 = new BindingList<object>();
+ // Binding an AddingNew delegate allows new.
+ bindingList.AddingNew += (object sender, AddingNewEventArgs e) => { };
+ Assert.True(bindingList.AllowNew);
+ }
- bool list_changed = false;
- bool expected = false;
+ [Fact]
+ public void AllowNew_SetFalse_CallsListChanged()
+ {
+ var bindingList = new BindingList<object>();
- l1.ListChanged += delegate (object sender, ListChangedEventArgs e)
+ bool calledListChanged = false;
+ bindingList.ListChanged += (object sender, ListChangedEventArgs e) =>
{
- list_changed = true;
+ calledListChanged = true;
Assert.Equal(-1, e.NewIndex);
Assert.Equal(ListChangedType.Reset, e.ListChangedType);
- Assert.Equal(expected, l1.AllowNew);
+ Assert.False(bindingList.AllowNew);
};
+ bindingList.AllowNew = false;
- expected = false;
- l1.AllowNew = false;
-
- Assert.True(list_changed, "7");
-
- //the default for T=object is true, so check
- //if we enter the block for raising the event
- //if we explicitly set it to the value it
- //currently has.
- l1 = new BindingList<object>();
+ Assert.True(calledListChanged);
+ }
- list_changed = false;
+ [Fact]
+ public void AllowNew_SetTrue_DoesNotCallListChanged()
+ {
+ // The default for T=object is true, so check if we enter the
+ // block for raising the event if we explicitly set it to the value
+ // it currently has.
+ var bindingList = new BindingList<object>();
- l1.ListChanged += delegate (object sender, ListChangedEventArgs e)
+ bool calledListChanged = false;
+ bindingList.ListChanged += delegate (object sender, ListChangedEventArgs e)
{
- list_changed = true;
+ calledListChanged = true;
Assert.Equal(-1, e.NewIndex);
Assert.Equal(ListChangedType.Reset, e.ListChangedType);
- Assert.Equal(expected, l1.AllowNew);
+ Assert.True(bindingList.AllowNew);
};
+ bindingList.AllowNew = true;
- expected = true;
- l1.AllowNew = true;
-
- //turns out it doesn't raise the event, so the check must only be for "allow_new == value"
- Assert.False(list_changed, "11");
+ // It doesn't raise the event.
+ Assert.False(calledListChanged);
}
[Fact]
- public void TestResetBindings()
+ public void ResetBindings_Invoke_CallsListChanged()
{
- BindingList<object> l = new BindingList<object>();
+ var bindingList = new BindingList<object>();
- bool list_changed = false;
-
- l.ListChanged += delegate (object sender, ListChangedEventArgs e)
+ bool calledListChanged = false;
+ bindingList.ListChanged += (object sender, ListChangedEventArgs e) =>
{
- list_changed = true;
+ calledListChanged = true;
Assert.Equal(-1, e.NewIndex);
Assert.Equal(ListChangedType.Reset, e.ListChangedType);
};
+ bindingList.ResetBindings();
- l.ResetBindings();
-
- Assert.True(list_changed, "3");
+ Assert.True(calledListChanged);
}
[Fact]
- public void TestResetItem()
+ public void ResetItem_Invoke_CallsListChanged()
{
- List<object> list = new List<object>();
- list.Add(new object());
+ var list = new List<object> { new object() };
+ var bindingList = new BindingList<object>(list);
- BindingList<object> l = new BindingList<object>(list);
-
- bool item_changed = false;
-
- l.ListChanged += delegate (object sender, ListChangedEventArgs e)
+ bool calledListChanged = false;
+ bindingList.ListChanged += (object sender, ListChangedEventArgs e) =>
{
- item_changed = true;
+ calledListChanged = true;
Assert.Equal(0, e.NewIndex);
Assert.Equal(ListChangedType.ItemChanged, e.ListChangedType);
};
+ bindingList.ResetItem(0);
- l.ResetItem(0);
-
- Assert.True(item_changed, "3");
+ Assert.True(calledListChanged);
}
[Fact]
- public void TestRemoveItem()
+ public void RemoveAt_Invoke_CallsListChanged()
{
- List<object> list = new List<object>();
- list.Add(new object());
+ var list = new List<object> { new object() };
+ var bindingList = new BindingList<object>(list);
- BindingList<object> l = new BindingList<object>(list);
-
- bool item_deleted = false;
-
- l.ListChanged += delegate (object sender, ListChangedEventArgs e)
+ bool calledListChanged = false;
+ bindingList.ListChanged += (object sender, ListChangedEventArgs e) =>
{
- item_deleted = true;
+ calledListChanged = true;
Assert.Equal(0, e.NewIndex);
Assert.Equal(ListChangedType.ItemDeleted, e.ListChangedType);
- Assert.Equal(0, l.Count); // to show the event is raised after the removal
+
+ // The event is raised after the removal.
+ Assert.Equal(0, bindingList.Count);
};
+ bindingList.RemoveAt(0);
- l.RemoveAt(0);
+ Assert.True(calledListChanged);
+ }
+
+ [Fact]
+ public void RemoteAt_AllowRemoveFalse_ThrowsNotSupportedException()
+ {
+ var list = new List<object> { new object() };
+ var bindingList = new BindingList<object>(list) { AllowRemove = false };
- Assert.True(item_deleted, "4");
+ Assert.Throws<NotSupportedException>(() => bindingList.RemoveAt(0));
}
[Fact]
- public void TestRemoveItem_AllowRemoveFalse()
+ public void AllowEdit_Set_InvokesListChanged()
{
- List<object> list = new List<object>();
- list.Add(new object());
+ var bindingList = new BindingList<object>();
- BindingList<object> l = new BindingList<object>(list);
+ bool calledListChanged = false;
+ bool expectedAllowEdit = false;
+ bindingList.ListChanged += (object sender, ListChangedEventArgs e) =>
+ {
+ calledListChanged = true;
+ Assert.Equal(-1, e.NewIndex);
+ Assert.Equal(ListChangedType.Reset, e.ListChangedType);
+ Assert.Equal(expectedAllowEdit, bindingList.AllowEdit);
+ };
- l.AllowRemove = false;
+ bindingList.AllowEdit = false;
+ Assert.True(calledListChanged);
- Assert.Throws<NotSupportedException>(() => l.RemoveAt(0));
+ // ListChanged is not called if RaiseListChangedEvents is false.
+ bindingList.RaiseListChangedEvents = false;
+ bindingList.RaiseListChangedEvents = false;
+ calledListChanged = false;
+ bindingList.AllowEdit = true;
+ Assert.False(calledListChanged);
}
[Fact]
- public void TestAllowEditEvent()
+ public void AllowRemove_Set_InvokesListChanged()
{
- BindingList<object> l = new BindingList<object>();
+ var bindingList = new BindingList<object>();
- bool event_raised = false;
- bool expected = false;
-
- l.ListChanged += delegate (object sender, ListChangedEventArgs e)
+ bool calledListChanged = false;
+ bool expectedAllowRemove = false;
+ bindingList.ListChanged += (object sender, ListChangedEventArgs e) =>
{
- event_raised = true;
+ calledListChanged = true;
Assert.Equal(-1, e.NewIndex);
Assert.Equal(ListChangedType.Reset, e.ListChangedType);
- Assert.Equal(expected, l.AllowEdit);
+ Assert.Equal(expectedAllowRemove, bindingList.AllowRemove);
};
+
+ bindingList.AllowRemove = false;
+ Assert.True(calledListChanged);
+
+ // ListChanged is not called if RaiseListChangedEvents is false.
+ bindingList.RaiseListChangedEvents = false;
- expected = false;
- l.AllowEdit = false;
+ calledListChanged = false;
+ bindingList.AllowRemove = true;
+ Assert.False(calledListChanged);
+ }
- Assert.True(event_raised, "4");
+ [Fact]
+ public void AddNew_SetArgsNewObject_ReturnsNewObject()
+ {
+ BindingList<object> bindingList = new BindingList<object>();
- // check to see if RaiseListChangedEvents affects AllowEdit's event.
- l.RaiseListChangedEvents = false;
+ bool calledAddingNew = false;
+ var newObject = new object();
- event_raised = false;
- expected = true;
- l.AllowEdit = true;
+ bindingList.AddingNew += (object sender, AddingNewEventArgs e) =>
+ {
+ calledAddingNew = true;
+ Assert.Null(e.NewObject);
+ e.NewObject = newObject;
+ };
- Assert.False(event_raised, "5");
+ Assert.Same(newObject, bindingList.AddNew());
+ Assert.True(calledAddingNew);
}
[Fact]
- public void TestAllowRemove()
+ public void AddNew_NullArgsNewObject_ReturnsNotNul()
{
- BindingList<object> l = new BindingList<object>();
-
- bool event_raised = false;
- bool expected = false;
+ var bindingList = new BindingList<object>();
- l.ListChanged += delegate (object sender, ListChangedEventArgs e)
+ bool calledAddingNew = false;
+ bindingList.AddingNew += delegate (object sender, AddingNewEventArgs e)
{
- event_raised = true;
- Assert.Equal(-1, e.NewIndex);
- Assert.Equal(ListChangedType.Reset, e.ListChangedType);
- Assert.Equal(expected, l.AllowRemove);
+ calledAddingNew = true;
+ Assert.Null(e.NewObject);
};
- expected = false;
- l.AllowRemove = false;
+ Assert.NotNull(bindingList.AddNew());
+ Assert.True(calledAddingNew);
+ }
- Assert.True(event_raised, "4");
+ [Fact]
+ public void AddNew_CancelNew_Success()
+ {
+ var bindingList = new BindingList<object>();
- // check to see if RaiseListChangedEvents affects AllowRemove's event.
- l.RaiseListChangedEvents = false;
+ bool calledAddingNew = false;
+ bool calledListChanged = false;
+ ListChangedType listChangedType = ListChangedType.Reset;
+ int listChangedIndex = -1;
- event_raised = false;
- expected = true;
- l.AllowRemove = true;
+ bindingList.AddingNew += (object sender, AddingNewEventArgs e) =>
+ {
+ calledAddingNew = true;
+ Assert.Null(e.NewObject);
+ };
+ bindingList.ListChanged += (object sender, ListChangedEventArgs e) =>
+ {
+ calledListChanged = true;
+ listChangedType = e.ListChangedType;
+ listChangedIndex = e.NewIndex;
+ };
- Assert.False(event_raised, "5");
+ object newValue = bindingList.AddNew();
+ Assert.True(calledAddingNew);
+ Assert.NotNull(newValue);
+
+ Assert.Equal(1, bindingList.Count);
+ Assert.Equal(0, bindingList.IndexOf(newValue));
+ Assert.True(calledListChanged);
+ Assert.Equal(ListChangedType.ItemAdded, listChangedType);
+ Assert.Equal(0, listChangedIndex);
+
+ calledListChanged = false;
+ bindingList.CancelNew(0);
+ Assert.Equal(0, bindingList.Count);
+ Assert.True(calledListChanged);
+ Assert.Equal(ListChangedType.ItemDeleted, listChangedType);
+ Assert.Equal(0, listChangedIndex);
}
[Fact]
- public void TestAddNew_SettingArgsNewObject()
+ public void AddNew_CancelNewMultipleIndices_RemovesAddNewIndex()
{
- BindingList<object> l = new BindingList<object>();
+ var list = new List<object> { new object(), new object() };
+ var bindingList = new BindingList<object>(list);
- bool adding_event_raised = false;
- object o = new object();
+ bool calledAddingNew = false;
+ bool calledListChanged = false;
+ ListChangedType listChangedType = ListChangedType.Reset;
+ int listChangedIndex = -1;
- l.AddingNew += delegate (object sender, AddingNewEventArgs e)
+ bindingList.AddingNew += (object sender, AddingNewEventArgs e) =>
{
- adding_event_raised = true;
+ calledAddingNew = true;
Assert.Null(e.NewObject);
- e.NewObject = o;
};
+ bindingList.ListChanged += (object sender, ListChangedEventArgs e) =>
+ {
+ calledListChanged = true;
+ listChangedType = e.ListChangedType;
+ listChangedIndex = e.NewIndex;
+ };
+
+ object newValue = bindingList.AddNew();
+ Assert.True(calledAddingNew);
+ Assert.NotNull(newValue);
+
+ Assert.Equal(3, bindingList.Count);
+ Assert.Equal(2, bindingList.IndexOf(newValue));
+ Assert.True(calledListChanged);
+ Assert.Equal(ListChangedType.ItemAdded, listChangedType);
+ Assert.Equal(2, listChangedIndex);
- object rv = l.AddNew();
- Assert.True(adding_event_raised, "2");
- Assert.Same(o, rv);
+ // Cancelling index 0 does not change the list.
+ calledListChanged = false;
+ bindingList.CancelNew(0);
+
+ Assert.False(calledListChanged);
+ Assert.Equal(3, bindingList.Count);
+
+ // Cancelling index 2 changes the list.
+ bindingList.CancelNew(2);
+
+ Assert.True(calledListChanged);
+ Assert.Equal(ListChangedType.ItemDeleted, listChangedType);
+ Assert.Equal(2, listChangedIndex);
+ Assert.Equal(2, bindingList.Count);
}
[Fact]
- public void TestAddNew()
+ public void AddNew_EndNew_Success()
{
- BindingList<object> l = new BindingList<object>();
+ var bindingList = new BindingList<object>();
- bool adding_event_raised = false;
- object o = new object();
+ bool calledAddNew = false;
+ bool calledListChanged = false;
+ ListChangedType listChangedType = ListChangedType.Reset;
+ int listChangedIndex = -1;
- l.AddingNew += delegate (object sender, AddingNewEventArgs e)
+ bindingList.AddingNew += (object sender, AddingNewEventArgs e) =>
{
- adding_event_raised = true;
+ calledAddNew = true;
Assert.Null(e.NewObject);
};
+ bindingList.ListChanged += (object sender, ListChangedEventArgs e) =>
+ {
+ calledListChanged = true;
+ listChangedType = e.ListChangedType;
+ listChangedIndex = e.NewIndex;
+ };
- object rv = l.AddNew();
- Assert.True(adding_event_raised, "2");
- Assert.NotNull(rv);
+ // Make sure the item was added.
+ object newValue = bindingList.AddNew();
+ Assert.True(calledAddNew);
+ Assert.NotNull(newValue);
+
+ Assert.Equal(1, bindingList.Count);
+ Assert.Equal(0, bindingList.IndexOf(newValue));
+ Assert.True(calledListChanged);
+ Assert.Equal(ListChangedType.ItemAdded, listChangedType);
+ Assert.Equal(0, listChangedIndex);
+
+ // EndNew does not change the list.
+ calledListChanged = false;
+ bindingList.EndNew(0);
+ Assert.Equal(1, bindingList.Count);
+ Assert.False(calledListChanged);
}
[Fact]
- public void TestAddNew_Cancel()
+ public void AddNew_CancelDifferentIndexThenEnd_Success()
{
- BindingList<object> l = new BindingList<object>();
-
- bool adding_event_raised = false;
- object o = new object();
+ var list = new BindingList<object>();
- bool list_changed = false;
- ListChangedType change_type = ListChangedType.Reset;
- int list_changed_index = -1;
+ bool calledAddingNew = false;
+ bool calledListChanged = false;
+ ListChangedType listChangedType = ListChangedType.Reset;
+ int listChangedIndex = -1;
- l.AddingNew += delegate (object sender, AddingNewEventArgs e)
+ list.AddingNew += delegate (object sender, AddingNewEventArgs e)
{
- adding_event_raised = true;
+ calledAddingNew = true;
Assert.Null(e.NewObject);
};
-
- l.ListChanged += delegate (object sender, ListChangedEventArgs e)
+ list.ListChanged += delegate (object sender, ListChangedEventArgs e)
{
- list_changed = true;
- change_type = e.ListChangedType;
- list_changed_index = e.NewIndex;
+ calledListChanged = true;
+ listChangedType = e.ListChangedType;
+ listChangedIndex = e.NewIndex;
};
- object rv = l.AddNew();
- Assert.True(adding_event_raised, "2");
- Assert.NotNull(rv);
+ // Make sure AddNew changed the list.
+ object newValue = list.AddNew();
+ Assert.True(calledAddingNew);
+ Assert.NotNull(newValue);
+
+ Assert.Equal(1, list.Count);
+ Assert.Equal(0, list.IndexOf(newValue));
+ Assert.True(calledListChanged);
+ Assert.Equal(ListChangedType.ItemAdded, listChangedType);
+ Assert.Equal(0, listChangedIndex);
+
+ // Calling CancelNew on an invalid index does not change the list.
+ calledListChanged = false;
+ list.CancelNew(2);
+ Assert.Equal(1, list.Count);
+ Assert.False(calledListChanged);
+
+ // Calling EndNew does not change the list.
+ list.EndNew(0);
+ Assert.Equal(1, list.Count);
+ Assert.False(calledListChanged);
+ }
- Assert.Equal(1, l.Count);
- Assert.Equal(0, l.IndexOf(rv));
- Assert.True(list_changed, "6");
- Assert.Equal(ListChangedType.ItemAdded, change_type);
- Assert.Equal(0, list_changed_index);
+ [Fact]
+ public void AddNew_EndDifferenceIndexThanCancel_Success()
+ {
+ var bindingList = new BindingList<object>();
- list_changed = false;
+ bool calledAddingNew = false;
+ bool calledListChanged = false;
+ ListChangedType listChangedType = ListChangedType.Reset;
+ int listChangedIndex = -1;
- l.CancelNew(0);
+ bindingList.AddingNew += (object sender, AddingNewEventArgs e) =>
+ {
+ calledAddingNew = true;
+ Assert.Null(e.NewObject);
+ };
+ bindingList.ListChanged += (object sender, ListChangedEventArgs e) =>
+ {
+ calledListChanged = true;
+ listChangedType = e.ListChangedType;
+ listChangedIndex = e.NewIndex;
+ };
- Assert.Equal(0, l.Count);
- Assert.True(list_changed, "10");
- Assert.Equal(ListChangedType.ItemDeleted, change_type);
- Assert.Equal(0, list_changed_index);
+ // Make sure AddNew changed the list.
+ object newValue = bindingList.AddNew();
+ Assert.True(calledAddingNew);
+ Assert.NotNull(newValue);
+
+ Assert.Equal(1, bindingList.Count);
+ Assert.Equal(0, bindingList.IndexOf(newValue));
+ Assert.True(calledListChanged);
+ Assert.Equal(ListChangedType.ItemAdded, listChangedType);
+ Assert.Equal(0, listChangedIndex);
+
+ // EndNew with an invalid index does not change the list.
+ calledListChanged = false;
+ bindingList.EndNew(2);
+ Assert.Equal(1, bindingList.Count);
+ Assert.False(calledListChanged);
+
+ // CancelNew with a valid index changes the list.
+ bindingList.CancelNew(0);
+ Assert.True(calledListChanged);
+ Assert.Equal(ListChangedType.ItemDeleted, listChangedType);
+ Assert.Equal(0, listChangedIndex);
}
[Fact]
- public void TestAddNew_CancelDifferentIndex()
+ public void AddingNew_RemoveWithAllowNewByDefault_Success()
{
- List<object> list = new List<object>();
+ var bindingList = new BindingList<int>();
- list.Add(new object());
- list.Add(new object());
+ bool calledAddingNew = false;
+ AddingNewEventHandler handler = (object sender, AddingNewEventArgs e) => calledAddingNew = true;
+ bindingList.AddingNew += handler;
- BindingList<object> l = new BindingList<object>(list);
+ bool calledListChanged = false;
+ bindingList.ListChanged += (object sender, ListChangedEventArgs e) => calledListChanged = true;
- bool adding_event_raised = false;
- object o = new object();
+ // Make sure removing the handler was successful.
+ bindingList.AddingNew -= handler;
+ Assert.False(calledListChanged);
- bool list_changed = false;
- ListChangedType change_type = ListChangedType.Reset;
- int list_changed_index = -1;
+ bindingList.AddNew();
+ Assert.False(calledAddingNew);
- l.AddingNew += delegate (object sender, AddingNewEventArgs e)
- {
- adding_event_raised = true;
- Assert.Null(e.NewObject);
- };
+ // Make sure removing multiple times is a nop.
+ bindingList.AddingNew -= handler;
+ }
- l.ListChanged += delegate (object sender, ListChangedEventArgs e)
+ [Fact]
+ public void AddingNew_RemoveWithNotAllowNewByDefault_CallsListChanged()
+ {
+ var bindingList = new BindingList<string>();
+
+ bool calledAddingNew = false;
+ AddingNewEventHandler handler = (object sender, AddingNewEventArgs e) => calledAddingNew = true;
+ bindingList.AddingNew += handler;
+
+ bool calledListChanged = false;
+ bindingList.ListChanged += (object sender, ListChangedEventArgs e) =>
{
- list_changed = true;
- change_type = e.ListChangedType;
- list_changed_index = e.NewIndex;
+ calledListChanged = true;
+ Assert.Equal(ListChangedType.Reset, e.ListChangedType);
+ Assert.Equal(-1, e.NewIndex);
};
- object rv = l.AddNew();
- Assert.True(adding_event_raised, "2");
- Assert.NotNull(rv);
+ // Make sure removing the handler was successful.
+ bindingList.AddingNew -= handler;
+ Assert.True(calledListChanged);
- Assert.Equal(3, l.Count);
- Assert.Equal(2, l.IndexOf(rv));
- Assert.True(list_changed, "6");
- Assert.Equal(ListChangedType.ItemAdded, change_type);
- Assert.Equal(2, list_changed_index);
+ Assert.Throws<MissingMethodException>(() => bindingList.AddNew());
+ Assert.False(calledAddingNew);
+ }
- list_changed = false;
+ [Fact]
+ public void ListChanged_AddRemove_Success()
+ {
+ var bindingList = new BindingList<int>();
- l.CancelNew(0);
+ bool calledListChanged = false;
+ ListChangedEventHandler handler = (object sender, ListChangedEventArgs e) => calledListChanged = true;
+ bindingList.ListChanged += handler;
- Assert.False(list_changed, "9");
- Assert.Equal(3, l.Count);
+ // Make sure removing the handler was successful.
+ bindingList.ListChanged -= handler;
+ bindingList.AddNew();
+ Assert.False(calledListChanged);
+ }
- l.CancelNew(2);
+ [Fact]
+ public void RaiseListChangedEvents_Set_GetReturnsExpected()
+ {
+ var bindingList = new BindingList<object> { RaiseListChangedEvents = false };
+ Assert.False(bindingList.RaiseListChangedEvents);
- Assert.True(list_changed, "11");
- Assert.Equal(ListChangedType.ItemDeleted, change_type);
- Assert.Equal(2, list_changed_index);
- Assert.Equal(2, l.Count);
+ bindingList.RaiseListChangedEvents = false;
+ Assert.False(bindingList.RaiseListChangedEvents);
}
[Fact]
- public void TestAddNew_End()
+ public void AllowNew_Set_GetReturnsExpected()
{
- BindingList<object> l = new BindingList<object>();
+ var bindingList = new BindingList<int> { AllowNew = false };
+ Assert.False(bindingList.AllowNew);
- bool adding_event_raised = false;
- object o = new object();
+ bindingList.AllowNew = false;
+ Assert.False(bindingList.AllowNew);
+ }
- bool list_changed = false;
- ListChangedType change_type = ListChangedType.Reset;
- int list_changed_index = -1;
+ [Fact]
+ public void AllowEdit_Set_GetReturnsExpected()
+ {
+ var bindingList = new BindingList<int> { AllowEdit = false };
+ Assert.False(bindingList.AllowEdit);
- l.AddingNew += delegate (object sender, AddingNewEventArgs e)
+ bindingList.AllowEdit = false;
+ Assert.False(bindingList.AllowEdit);
+ }
+
+ [Fact]
+ public void AllowRemove_Set_GetReturnsExpected()
+ {
+ var bindingList = new BindingList<int> { AllowRemove = false };
+ Assert.False(bindingList.AllowRemove);
+
+ bindingList.AllowRemove = false;
+ Assert.False(bindingList.AllowRemove);
+ }
+
+ [Fact]
+ public void Clear_Invoke_Success()
+ {
+ var bindingList = new BindingList<object> { new object(), new object() };
+
+ bool calledListChanged = false;
+ bindingList.ListChanged += (object sender, ListChangedEventArgs e) =>
{
- adding_event_raised = true;
- Assert.Null(e.NewObject);
+ calledListChanged = true;
+ Assert.Equal(ListChangedType.Reset, e.ListChangedType);
+ Assert.Equal(-1, e.NewIndex);
};
- l.ListChanged += delegate (object sender, ListChangedEventArgs e)
+ bindingList.Clear();
+ Assert.True(calledListChanged);
+ Assert.Empty(bindingList);
+ }
+
+ [Fact]
+ public void Clear_INotifyPropertyChangedItems_RemovesPropertyChangedEventHandlers()
+ {
+ var item1 = new Item();
+ var item2 = new Item();
+ var list = new List<Item> { item1, item2, null };
+ var bindingList = new BindingList<Item>(list);
+ Assert.Equal(1, item1.InvocationList.Length);
+ Assert.Equal(1, item2.InvocationList.Length);
+
+ bool calledListChanged = false;
+ bindingList.ListChanged += (object sender, ListChangedEventArgs e) =>
{
- list_changed = true;
- change_type = e.ListChangedType;
- list_changed_index = e.NewIndex;
+ calledListChanged = true;
+ Assert.Equal(ListChangedType.Reset, e.ListChangedType);
+ Assert.Equal(-1, e.NewIndex);
};
- object rv = l.AddNew();
- Assert.True(adding_event_raised, "2");
- Assert.NotNull(rv);
+ bindingList.Clear();
+ Assert.True(calledListChanged);
+ Assert.Empty(bindingList);
- Assert.Equal(1, l.Count);
- Assert.Equal(0, l.IndexOf(rv));
- Assert.True(list_changed, "6");
- Assert.Equal(ListChangedType.ItemAdded, change_type);
- Assert.Equal(0, list_changed_index);
+ Assert.Null(item1.InvocationList);
+ Assert.Null(item2.InvocationList);
+ }
- list_changed = false;
+ [Fact]
+ public void RemoveAt_INotifyPropertyChangedItems_RemovesPropertyChangedEventHandlers()
+ {
+ var item = new Item();
+ var bindingList = new BindingList<Item> { item };
+ Assert.Equal(1, item.InvocationList.Length);
- l.EndNew(0);
+ bool calledListChanged = false;
+ bindingList.ListChanged += (object sender, ListChangedEventArgs e) =>
+ {
+ calledListChanged = true;
+ Assert.Equal(ListChangedType.ItemDeleted, e.ListChangedType);
+ Assert.Equal(0, e.NewIndex);
+ };
- Assert.Equal(1, l.Count);
- Assert.False(list_changed, "10");
+ bindingList.RemoveAt(0);
+ Assert.True(calledListChanged);
+ Assert.Empty(bindingList);
+ Assert.Null(item.InvocationList);
}
[Fact]
- public void TestAddNew_CancelDifferentIndexThenEnd()
+ public void ItemSet_Invoke_CallsListChanged()
{
- BindingList<object> l = new BindingList<object>();
-
- bool adding_event_raised = false;
- object o = new object();
-
- bool list_changed = false;
- ListChangedType change_type = ListChangedType.Reset;
- int list_changed_index = -1;
+ var bindingList = new BindingList<int> { 1 };
- l.AddingNew += delegate (object sender, AddingNewEventArgs e)
+ bool calledListChanged = false;
+ bindingList.ListChanged += (object sender, ListChangedEventArgs e) =>
{
- adding_event_raised = true;
- Assert.Null(e.NewObject);
+ calledListChanged = true;
+ Assert.Equal(ListChangedType.ItemChanged, e.ListChangedType);
+ Assert.Equal(0, e.NewIndex);
};
- l.ListChanged += delegate (object sender, ListChangedEventArgs e)
+ bindingList[0] = 2;
+ Assert.True(calledListChanged);
+ Assert.Equal(2, bindingList[0]);
+ }
+
+ [Fact]
+ public void ItemSet_INotifyPropertyChangedItem_RemovesPropertyChangedEventHandlers()
+ {
+ var item1 = new Item();
+ var item2 = new Item();
+ var bindingList = new BindingList<Item> { item1 };
+ Assert.Equal(1, item1.InvocationList.Length);
+
+ bool calledListChanged = false;
+ bindingList.ListChanged += (object sender, ListChangedEventArgs e) =>
{
- list_changed = true;
- change_type = e.ListChangedType;
- list_changed_index = e.NewIndex;
+ calledListChanged = true;
+ Assert.Equal(ListChangedType.ItemChanged, e.ListChangedType);
+ Assert.Equal(0, e.NewIndex);
};
- object rv = l.AddNew();
- Assert.True(adding_event_raised, "2");
- Assert.NotNull(rv);
-
- Assert.Equal(1, l.Count);
- Assert.Equal(0, l.IndexOf(rv));
- Assert.True(list_changed, "6");
- Assert.Equal(ListChangedType.ItemAdded, change_type);
- Assert.Equal(0, list_changed_index);
+ bindingList[0] = item2;
+ Assert.True(calledListChanged);
+ Assert.Equal(item2, bindingList[0]);
+ Assert.Null(item1.InvocationList);
+ Assert.Equal(1, item2.InvocationList.Length);
+ }
- list_changed = false;
+ [Fact]
+ public void SortProperty_Get_ReturnsNull()
+ {
+ IBindingList bindingList = new BindingList<object>();
+ Assert.Null(bindingList.SortProperty);
+ }
- l.CancelNew(2);
+ [Fact]
+ public void ApplySort_Invoke_ThrowsNotSupportedException()
+ {
+ IBindingList bindingList = new BindingList<object>();
+ Assert.Throws<NotSupportedException>(() => bindingList.ApplySort(null, ListSortDirection.Descending));
+ }
- Assert.Equal(1, l.Count);
- Assert.False(list_changed, "10");
+ [Fact]
+ public void RemoveSort_Invoke_ThrowsNotSupportedException()
+ {
+ IBindingList bindingList = new BindingList<object>();
+ Assert.Throws<NotSupportedException>(() => bindingList.RemoveSort());
+ }
- l.EndNew(0);
+ [Fact]
+ public void Find_Invoke_ThrowsNotSupportedException()
+ {
+ IBindingList bindingList = new BindingList<object>();
+ Assert.Throws<NotSupportedException>(() => bindingList.Find(null, null));
+ }
- Assert.Equal(1, l.Count);
- Assert.False(list_changed, "12");
+ [Fact]
+ public void AddIndex_RemoveIndex_Nop()
+ {
+ IBindingList bindingList = new BindingList<object>();
+ bindingList.AddIndex(null);
+ bindingList.RemoveIndex(null);
}
[Fact]
- public void TestAddNew_EndDifferentIndexThenCancel()
+ public void ItemPropertyChanged_RaiseListChangedEventsFalse_InvokesItemChanged()
{
- BindingList<object> l = new BindingList<object>();
+ var item = new Item();
+ var bindingList = new BindingList<Item> { item };
- bool adding_event_raised = false;
- object o = new object();
+ bool calledListChanged = false;
+ bindingList.ListChanged += (object sender, ListChangedEventArgs e) =>
+ {
+ calledListChanged = true;
+ Assert.Equal(ListChangedType.ItemChanged, e.ListChangedType);
+ Assert.Equal(0, e.NewIndex);
+ Assert.Equal("Name", e.PropertyDescriptor.Name);
+ Assert.Equal(typeof(string), e.PropertyDescriptor.PropertyType);
+ };
- bool list_changed = false;
- ListChangedType change_type = ListChangedType.Reset;
- int list_changed_index = -1;
+ // Invoke once
+ item.Name = "name";
+ Assert.True(calledListChanged);
+
+ // Invoke twice.
+ calledListChanged = false;
+ item.Name = "name2";
+ Assert.True(calledListChanged);
+ }
- l.AddingNew += delegate (object sender, AddingNewEventArgs e)
+ [Theory]
+ [InlineData(null)]
+ [InlineData("sender")]
+ public void ItemPropertyChanged_InvalidSender_InvokesReset(object invokeSender)
+ {
+ var item = new Item();
+ var bindingList = new BindingList<Item> { item };
+
+ bool calledListChanged = false;
+ bindingList.ListChanged += (object sender, ListChangedEventArgs e) =>
{
- adding_event_raised = true;
- Assert.Null(e.NewObject);
+ calledListChanged = true;
+ Assert.Equal(ListChangedType.Reset, e.ListChangedType);
+ Assert.Equal(-1, e.NewIndex);
};
- l.ListChanged += delegate (object sender, ListChangedEventArgs e)
+ item.InvokePropertyChanged(invokeSender, new PropertyChangedEventArgs("Name"));
+ Assert.True(calledListChanged);
+ }
+
+ public static IEnumerable<object[]> InvalidEventArgs_TestData()
+ {
+ yield return new object[] { null };
+ yield return new object[] { new PropertyChangedEventArgs(null) };
+ yield return new object[] { new PropertyChangedEventArgs(string.Empty) };
+ }
+
+ [Theory]
+ [MemberData(nameof(InvalidEventArgs_TestData))]
+ public void ItemPropertyChanged_InvalidEventArgs_InvokesReset(PropertyChangedEventArgs eventArgs)
+ {
+ var item = new Item();
+ var bindingList = new BindingList<Item> { item };
+
+ bool calledListChanged = false;
+ bindingList.ListChanged += (object sender, ListChangedEventArgs e) =>
{
- list_changed = true;
- change_type = e.ListChangedType;
- list_changed_index = e.NewIndex;
+ calledListChanged = true;
+ Assert.Equal(ListChangedType.Reset, e.ListChangedType);
+ Assert.Equal(-1, e.NewIndex);
};
- object rv = l.AddNew();
- Assert.True(adding_event_raised, "2");
- Assert.NotNull(rv);
+ item.InvokePropertyChanged(item, eventArgs);
+ Assert.True(calledListChanged);
+ }
+
+ [Fact]
+ public void InvokePropertyChanged_NoSuchObjectAnymore_InvokesReset()
+ {
+ var item1 = new Item();
+ var item2 = new Item();
+ var bindingList = new BindingList<Item> { item1 };
+
+ bool calledListChanged = false;
+ bindingList.ListChanged += (object sender, ListChangedEventArgs e) =>
+ {
+ calledListChanged = true;
+ Assert.Equal(ListChangedType.Reset, e.ListChangedType);
+ Assert.Equal(-1, e.NewIndex);
+ };
- Assert.Equal(1, l.Count);
- Assert.Equal(0, l.IndexOf(rv));
- Assert.True(list_changed, "6");
- Assert.Equal(ListChangedType.ItemAdded, change_type);
- Assert.Equal(0, list_changed_index);
+ item1.InvokePropertyChanged(item2, new PropertyChangedEventArgs("Name"));
+ Assert.True(calledListChanged);
+ }
- list_changed = false;
+ [Fact]
+ public void ItemPropertyChanged_RaiseListChangedEventsFalse_DoesNotInvokeListChanged()
+ {
+ var item = new Item();
+ var bindingList = new BindingList<Item> { item };
+ bindingList.RaiseListChangedEvents = false;
- l.EndNew(2);
+ bool calledListChanged = false;
+ bindingList.ListChanged += (object sender, ListChangedEventArgs e) => calledListChanged = true;
- Assert.Equal(1, l.Count);
- Assert.False(list_changed, "10");
+ item.Name = "name";
+ Assert.False(calledListChanged);
+ }
- l.CancelNew(0);
+ [Fact]
+ public void AddingNewCore_ReturnsNull_Success()
+ {
+ var bindingList = new BindingListWithNullAddCore();
+ Assert.Null(bindingList.AddNew());
+ }
- Assert.True(list_changed, "11");
- Assert.Equal(ListChangedType.ItemDeleted, change_type);
- Assert.Equal(0, list_changed_index);
+ private class BindingListWithNullAddCore : BindingList<object>
+ {
+ protected override object AddNewCore() => null;
}
- class BindingListPoker : BindingList<object>
+ private class BindingListPoker : BindingList<object>
{
- public object DoAddNewCore()
- {
- return base.AddNewCore();
- }
+ public object DoAddNewCore() => base.AddNewCore();
}
- // test to make sure that the events are raised in AddNewCore and not in AddNew
[Fact]
- public void TestAddNewCore_Insert()
+ public void AddNewCore_Invoke_CallsAddingNewAndListChanged()
{
- BindingListPoker poker = new BindingListPoker();
-
- bool adding_event_raised = false;
+ var poker = new BindingListPoker();
- bool list_changed = false;
- ListChangedType change_type = ListChangedType.Reset;
- int list_changed_index = -1;
+ bool calledAddingNew = false;
+ bool calledListChanged = false;
+ ListChangedType listChangedType = ListChangedType.Reset;
+ int listChangedIndex = -1;
- poker.AddingNew += delegate (object sender, AddingNewEventArgs e)
+ poker.AddingNew += (object sender, AddingNewEventArgs e) =>
{
- adding_event_raised = true;
+ calledAddingNew = true;
};
-
- poker.ListChanged += delegate (object sender, ListChangedEventArgs e)
+ poker.ListChanged += (object sender, ListChangedEventArgs e) =>
{
- list_changed = true;
- change_type = e.ListChangedType;
- list_changed_index = e.NewIndex;
+ calledListChanged = true;
+ listChangedType = e.ListChangedType;
+ listChangedIndex = e.NewIndex;
};
- object o = poker.DoAddNewCore();
+ object newValue = poker.DoAddNewCore();
+ Assert.True(calledAddingNew);
+ Assert.True(calledListChanged);
- Assert.True(adding_event_raised, "1");
- Assert.True(list_changed, "2");
- Assert.Equal(ListChangedType.ItemAdded, change_type);
- Assert.Equal(0, list_changed_index);
+ Assert.Equal(ListChangedType.ItemAdded, listChangedType);
+ Assert.Equal(0, listChangedIndex);
Assert.Equal(1, poker.Count);
}
private class Item : INotifyPropertyChanged
{
-
public event PropertyChangedEventHandler PropertyChanged;
- string _name;
-
+ private string _name;
public string Name
{
- get { return _name; }
+ get => _name;
set
{
if (_name != value)
{
_name = value;
- OnPropertyChanged("Name");
+ OnPropertyChanged();
}
}
}
- void OnPropertyChanged(string name)
+ public Delegate[] InvocationList => PropertyChanged?.GetInvocationList();
+
+ public void InvokePropertyChanged(object sender, PropertyChangedEventArgs e)
+ {
+ PropertyChanged?.Invoke(sender, e);
+ }
+
+ private void OnPropertyChanged()
{
- var fn = PropertyChanged;
- if (fn != null)
- fn(this, new PropertyChangedEventArgs(name));
+ PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(nameof(Name)));
}
}
[Fact]
- public void Test_InsertNull()
+ public void Insert_Null_Success()
{
var list = new BindingList<Item>();
list.Insert(0, null);
- var count = list.Count;
- Assert.Equal(1, count);
+ Assert.Equal(1, list.Count);
}
- private class Person : INotifyPropertyChanged
+ [Fact]
+ public void ApplySort_ApplySortCoreOverriden_DoesNotThrow()
{
- private string _lastName;
- private string _firstName;
-
- public string FirstName
- {
- get { return _firstName; }
- set
- {
- _firstName = value;
- OnPropertyChanged("FirstName"); // string matches property name
- }
- }
+ IBindingList bindingList = new SubBindingList();
+ bindingList.ApplySort(null, ListSortDirection.Descending);
+ }
- public string LastName
- {
- get { return _lastName; }
- set
- {
- _lastName = value;
- OnPropertyChanged("NotTheName"); // string doesn't match property name
- }
- }
+ [Fact]
+ public void RemoveSort_RemoveSortCoreOverriden_DoesNotThrow()
+ {
+ IBindingList bindingList = new SubBindingList();
+ bindingList.RemoveSort();
+ }
- public event PropertyChangedEventHandler PropertyChanged;
+ [Fact]
+ public void Find_FindCoreOverriden_DoesNotThrow()
+ {
+ IBindingList bindingList = new SubBindingList();
+ Assert.Equal(200, bindingList.Find(null, null));
+ }
- protected virtual void OnPropertyChanged(string propertyName = null)
- {
- PropertyChangedEventHandler handler = PropertyChanged;
- if (handler != null)
- handler(this, new PropertyChangedEventArgs(propertyName));
- }
+ private class SubBindingList : BindingList<object>
+ {
+ protected override void ApplySortCore(PropertyDescriptor prop, ListSortDirection direction) { }
+ protected override void RemoveSortCore() { }
+ protected override int FindCore(PropertyDescriptor prop, object key) => 200;
}
}
}
diff --git a/src/System.ComponentModel.TypeConverter/tests/ComponentResourceManagerTests.cs b/src/System.ComponentModel.TypeConverter/tests/ComponentResourceManagerTests.cs
new file mode 100644
index 0000000000..d4534f2f99
--- /dev/null
+++ b/src/System.ComponentModel.TypeConverter/tests/ComponentResourceManagerTests.cs
@@ -0,0 +1,204 @@
+// Licensed to the .NET Foundation under one or more agreements.
+// The .NET Foundation licenses this file to you under the MIT license.
+// See the LICENSE file in the project root for more information.
+
+using System.Collections.Generic;
+using System.Globalization;
+using System.Reflection;
+using Xunit;
+
+namespace System.ComponentModel.Tests
+{
+ public class ComponentResourceManagerTests
+ {
+ [Fact]
+ public void Ctor_Default()
+ {
+ var resourceManager = new ComponentResourceManager();
+ Assert.Null(resourceManager.BaseName);
+ Assert.False(resourceManager.IgnoreCase);
+ Assert.NotNull(resourceManager.ResourceSetType);
+ }
+
+ [Theory]
+ [InlineData(typeof(int))]
+ public void Ctor_Type(Type type)
+ {
+ var resourceManager = new ComponentResourceManager(type);
+ Assert.Equal("Int32", resourceManager.BaseName);
+ Assert.False(resourceManager.IgnoreCase);
+ Assert.NotNull(resourceManager.ResourceSetType);
+ }
+
+ [Theory]
+ [InlineData(true)]
+ [InlineData(false)]
+ public void ApplyResources_ValueExists_ReturnsExpected(bool ignoreCase)
+ {
+ var resourceManager = new ComponentResourceManager(typeof(global::Resources.TestResx))
+ {
+ IgnoreCase = ignoreCase
+ };
+
+ var value = new TestValue();
+ resourceManager.ApplyResources(value, "Object");
+ Assert.Equal("One", value.GetSetProperty);
+ Assert.Null(value.GetOnlyProperty);
+ Assert.Null(value.GetPrivateProperty());
+ }
+
+ private class TestValue
+ {
+ public string GetSetProperty { get; set; }
+ public string GetOnlyProperty { get; }
+ private string PrivateProperty { get; set; }
+
+ public string GetPrivateProperty() => PrivateProperty;
+ }
+
+ [Fact]
+ public void ApplyResources_AmibguousWithSameDeclaringType_ThrowsAmbiguousMatchException()
+ {
+ var resourceManager = new ComponentResourceManager(typeof(global::Resources.TestResx))
+ {
+ IgnoreCase = true
+ };
+
+ var value = new MulticasedClass();
+ Assert.Throws<AmbiguousMatchException>(() => resourceManager.ApplyResources(value, "Object"));
+ }
+
+ private class MulticasedClass
+ {
+ public string GetSetProperty { get; set; }
+ public string getsetproperty { get; set; }
+ }
+
+ public static IEnumerable<object[]> AmbiguousWithDifferentDeclaringType_TestData()
+ {
+ yield return new object[] { new MulticaseSubClass() };
+ yield return new object[] { new MulticaseSubSubClass() };
+ }
+
+ [Theory]
+ [MemberData(nameof(AmbiguousWithDifferentDeclaringType_TestData))]
+ public void ApplyResources_AmibguousWithDifferentDeclaringTypeInValueType_UsesMostDeclaredProperty<T>(T value) where T : MulticaseSubClass
+ {
+ var resourceManager = new ComponentResourceManager(typeof(global::Resources.TestResx))
+ {
+ IgnoreCase = true
+ };
+
+ resourceManager.ApplyResources(value, "Object");
+
+ Assert.Null(value.GetSetProperty);
+ Assert.Equal("One", value.getsetproperty);
+ }
+
+ public class MulticaseBaseClass
+ {
+ public string GetSetProperty { get; set; }
+ }
+
+ public class MulticaseSubClass : MulticaseBaseClass
+ {
+ public string getsetproperty { get; set; }
+ }
+
+ public class MulticaseSubSubClass : MulticaseSubClass { }
+
+ [Fact]
+ public void ApplyResources_IComponentWithNullSite_Success()
+ {
+ var resourceManager = new ComponentResourceManager(typeof(global::Resources.TestResx))
+ {
+ IgnoreCase = true
+ };
+
+ var value = new TestComponent();
+ resourceManager.ApplyResources(value, "Object");
+ Assert.Equal("One", value.GetSetProperty);
+ }
+
+ [Fact]
+ public void ApplyResources_IComponentWithNonDesignModeSite_Success()
+ {
+ var resourceManager = new ComponentResourceManager(typeof(global::Resources.TestResx))
+ {
+ IgnoreCase = true
+ };
+
+ var value = new TestComponent { Site = new TestSite { DesignMode = false } };
+ resourceManager.ApplyResources(value, "Object");
+ Assert.Equal("One", value.GetSetProperty);
+ }
+
+ [Fact]
+ [ActiveIssue(22145, TargetFrameworkMonikers.NetFramework)]
+ public void ApplyResources_IComponentWithDesignModeSite_Success()
+ {
+ var resourceManager = new ComponentResourceManager(typeof(global::Resources.TestResx))
+ {
+ IgnoreCase = true
+ };
+
+ var value = new TestComponent { Site = new TestSite { DesignMode = true } };
+ resourceManager.ApplyResources(value, "Object");
+ Assert.Equal("One", value.GetSetProperty);
+ }
+
+ private class TestSite : ISite
+ {
+ public bool DesignMode { get; set; }
+
+ public IComponent Component => throw new NotImplementedException();
+ public IContainer Container => throw new NotImplementedException();
+ public string Name { get => throw new NotImplementedException(); set => throw new NotImplementedException(); }
+ public object GetService(Type serviceType) => null;
+ }
+
+ private class TestComponent : IComponent
+ {
+ public ISite Site { get; set; }
+
+#pragma warning disable 0067
+ public event EventHandler Disposed;
+#pragma warning restore 0067
+
+ public void Dispose() { }
+
+ public string GetSetProperty { get; set; }
+ }
+
+ [Theory]
+ [InlineData(true)]
+ [InlineData(false)]
+ public void ApplyResources_NoSuchValue_Nop(bool ignoreCase)
+ {
+ var resourceManager = new ComponentResourceManager(typeof(global::Resources.TestResx))
+ {
+ IgnoreCase = ignoreCase
+ };
+
+ resourceManager.ApplyResources("Value", "ObjectName");
+ resourceManager.ApplyResources("Value", "ObjectName", CultureInfo.CurrentUICulture);
+ resourceManager.ApplyResources("Value", "ObjectName", CultureInfo.InvariantCulture);
+ }
+
+ [Fact]
+ public void ApplyResources_NullValue_ThrowsArgumentNullException()
+ {
+ var resourceManager = new ComponentResourceManager();
+ AssertExtensions.Throws<ArgumentNullException>("value", () => resourceManager.ApplyResources(null, "objectName"));
+ AssertExtensions.Throws<ArgumentNullException>("value", () => resourceManager.ApplyResources(null, "objectName", CultureInfo.CurrentCulture));
+ }
+
+ [Fact]
+ public void ApplyResources_NullObjectName_ThrowsArgumentNullException()
+ {
+ var resourceManager = new ComponentResourceManager();
+ AssertExtensions.Throws<ArgumentNullException>("objectName", () => resourceManager.ApplyResources("value", null));
+ AssertExtensions.Throws<ArgumentNullException>("objectName", () => resourceManager.ApplyResources("value", null, CultureInfo.CurrentCulture));
+ }
+ }
+}
diff --git a/src/System.ComponentModel.TypeConverter/tests/ContainerTests.cs b/src/System.ComponentModel.TypeConverter/tests/ContainerTests.cs
index f154d8f132..58e08bb363 100644
--- a/src/System.ComponentModel.TypeConverter/tests/ContainerTests.cs
+++ b/src/System.ComponentModel.TypeConverter/tests/ContainerTests.cs
@@ -13,6 +13,7 @@
//
using System.ComponentModel.Design;
+using System.Linq;
using Xunit;
namespace System.ComponentModel.Tests
@@ -283,6 +284,19 @@ namespace System.ComponentModel.Tests
}
[Fact]
+ public void Add_ExceedsSizeOfBuffer_Success()
+ {
+ var container = new Container();
+ var components = new Component[] { new Component(), new Component(), new Component(), new Component(), new Component() };
+
+ for (int i = 0; i < components.Length; i++)
+ {
+ container.Add(components[i]);
+ Assert.Same(components[i], container.Components[i]);
+ }
+ }
+
+ [Fact]
public void Add2_Component_Null()
{
_container.Add((IComponent)null, "A");
@@ -369,6 +383,50 @@ namespace System.ComponentModel.Tests
}
[Fact]
+ public void Add_SetSiteName_ReturnsExpected()
+ {
+ var component = new Component();
+ var container = new Container();
+
+ container.Add(component, "Name1");
+ Assert.Equal("Name1", component.Site.Name);
+
+ component.Site.Name = "OtherName";
+ Assert.Equal("OtherName", component.Site.Name);
+
+ // Setting to the same value is a nop.
+ component.Site.Name = "OtherName";
+ Assert.Equal("OtherName", component.Site.Name);
+ }
+
+ [Fact]
+ public void Add_SetSiteNameDuplicate_ThrowsArgumentException()
+ {
+ var component1 = new Component();
+ var component2 = new Component();
+ var container = new Container();
+
+ container.Add(component1, "Name1");
+ container.Add(component2, "Name2");
+
+ Assert.Throws<ArgumentException>(null, () => component1.Site.Name = "Name2");
+ }
+
+ [Fact]
+ public void Add_DuplicateNameWithInheritedReadOnly_AddsSuccessfully()
+ {
+ var component1 = new Component();
+ var component2 = new Component();
+ TypeDescriptor.AddAttributes(component1, new InheritanceAttribute(InheritanceLevel.InheritedReadOnly));
+
+ var container = new Container();
+ container.Add(component1, "Name");
+ container.Add(component2, "Name");
+
+ Assert.Equal(new IComponent[] { component1, component2 }, container.Components.Cast<IComponent>());
+ }
+
+ [Fact]
public void AddRemove()
{
TestComponent component = new TestComponent();
@@ -617,6 +675,31 @@ namespace System.ComponentModel.Tests
}
[Fact]
+ public void Remove_NoSuchComponentWithoutUnsiting_Nop()
+ {
+ var component1 = new Component();
+ var component2 = new Component();
+ var container = new SitingContainer();
+
+ container.Add(component1);
+ container.Add(component2);
+
+ container.DoRemoveWithoutUnsitting(component1);
+ Assert.Equal(1, container.Components.Count);
+
+ container.DoRemoveWithoutUnsitting(component1);
+ Assert.Equal(1, container.Components.Count);
+
+ container.DoRemoveWithoutUnsitting(component2);
+ Assert.Equal(0, container.Components.Count);
+ }
+
+ private class SitingContainer : Container
+ {
+ public void DoRemoveWithoutUnsitting(IComponent component) => RemoveWithoutUnsiting(component);
+ }
+
+ [Fact]
public void ValidateName_Component_Null()
{
ArgumentNullException ex = Assert.Throws<ArgumentNullException>(() => _container.InvokeValidateName((IComponent)null, "A"));
@@ -703,6 +786,108 @@ namespace System.ComponentModel.Tests
Assert.Same(compD, container2.Components[0]);
}
+ [Fact]
+ public void Components_GetWithDefaultFilterService_ReturnsAllComponents()
+ {
+ var component1 = new SubComponent();
+ var component2 = new Component();
+ var component3 = new SubComponent();
+
+ var container = new FilterContainer { FilterService = new DefaultFilterService() };
+ container.Add(component1);
+ container.Add(component2);
+ container.Add(component3);
+
+ Assert.Equal(new IComponent[] { component1, component2, component3 }, container.Components.Cast<IComponent>());
+ }
+
+ [Fact]
+ public void Components_GetWithCustomFilterService_ReturnsFilteredComponents()
+ {
+ var component1 = new SubComponent();
+ var component2 = new Component();
+ var component3 = new SubComponent();
+
+ // This filter only includes SubComponents.
+ var container = new FilterContainer { FilterService = new CustomContainerFilterService() };
+ container.Add(component1);
+ container.Add(component2);
+ container.Add(component3);
+
+ Assert.Equal(new IComponent[] { component1, component3 }, container.Components.Cast<IComponent>());
+ }
+
+ [Fact]
+ public void Components_GetWithCustomFilterServiceAfterChangingComponents_ReturnsUpdatedComponents()
+ {
+ var component1 = new SubComponent();
+ var component2 = new Component();
+ var component3 = new SubComponent();
+
+ // This filter only includes SubComponents.
+ var container = new FilterContainer { FilterService = new CustomContainerFilterService() };
+ container.Add(component1);
+ container.Add(component2);
+ container.Add(component3);
+
+ Assert.Equal(new IComponent[] { component1, component3 }, container.Components.Cast<IComponent>());
+
+ container.Remove(component1);
+ Assert.Equal(new IComponent[] { component3 }, container.Components.Cast<IComponent>());
+ }
+
+ [Fact]
+ public void Components_GetWithNullFilterService_ReturnsUnfiltered()
+ {
+ var component1 = new SubComponent();
+ var component2 = new Component();
+ var component3 = new SubComponent();
+
+ // This filter only includes SubComponents.
+ var container = new FilterContainer { FilterService = new NullContainerFilterService() };
+ container.Add(component1);
+ container.Add(component2);
+ container.Add(component3);
+
+ Assert.Equal(new IComponent[] { component1, component2, component3 }, container.Components.Cast<IComponent>());
+ }
+
+ private class FilterContainer : Container
+ {
+ public ContainerFilterService FilterService { get; set; }
+
+ protected override object GetService(Type service)
+ {
+ if (service == typeof(ContainerFilterService))
+ {
+ return FilterService;
+ }
+
+ return base.GetService(service);
+ }
+ }
+
+ private class SubComponent : Component { }
+
+ private class DefaultFilterService : ContainerFilterService { }
+
+ private class CustomContainerFilterService : ContainerFilterService
+ {
+ public override ComponentCollection FilterComponents(ComponentCollection components)
+ {
+ SubComponent[] newComponents = components.OfType<SubComponent>().ToArray();
+ return new ComponentCollection(newComponents);
+ }
+ }
+
+ private class NullContainerFilterService : ContainerFilterService
+ {
+ public override ComponentCollection FilterComponents(ComponentCollection components)
+ {
+ return null;
+ }
+ }
+
private class MyComponent : Component
{
private Container container;
diff --git a/src/System.ComponentModel.TypeConverter/tests/Resources/TestResx.Designer.cs b/src/System.ComponentModel.TypeConverter/tests/Resources/TestResx.Designer.cs
new file mode 100644
index 0000000000..b92d389fb5
--- /dev/null
+++ b/src/System.ComponentModel.TypeConverter/tests/Resources/TestResx.Designer.cs
@@ -0,0 +1,118 @@
+//------------------------------------------------------------------------------
+// <auto-generated>
+// This code was generated by a tool.
+// Runtime Version:4.0.30319.42000
+//
+// Changes to this file may cause incorrect behavior and will be lost if
+// the code is regenerated.
+// </auto-generated>
+//------------------------------------------------------------------------------
+
+namespace Resources {
+ using System;
+ using System.Reflection;
+
+
+ /// <summary>
+ /// A strongly-typed resource class, for looking up localized strings, etc.
+ /// </summary>
+ // This class was auto-generated by the StronglyTypedResourceBuilder
+ // class via a tool like ResGen or Visual Studio.
+ // To add or remove a member, edit your .ResX file then rerun ResGen
+ // with the /str option, or rebuild your VS project.
+ [global::System.CodeDom.Compiler.GeneratedCodeAttribute("System.Resources.Tools.StronglyTypedResourceBuilder", "4.0.0.0")]
+ [global::System.Diagnostics.DebuggerNonUserCodeAttribute()]
+ [global::System.Runtime.CompilerServices.CompilerGeneratedAttribute()]
+ internal class TestResx {
+
+ private static global::System.Resources.ResourceManager resourceMan;
+
+ private static global::System.Globalization.CultureInfo resourceCulture;
+
+ [global::System.Diagnostics.CodeAnalysis.SuppressMessageAttribute("Microsoft.Performance", "CA1811:AvoidUncalledPrivateCode")]
+ internal TestResx() {
+ }
+
+ /// <summary>
+ /// Returns the cached ResourceManager instance used by this class.
+ /// </summary>
+ [global::System.ComponentModel.EditorBrowsableAttribute(global::System.ComponentModel.EditorBrowsableState.Advanced)]
+ internal static global::System.Resources.ResourceManager ResourceManager {
+ get {
+ if (object.ReferenceEquals(resourceMan, null)) {
+ global::System.Resources.ResourceManager temp = new global::System.Resources.ResourceManager("Resources.TestResx", typeof(TestResx).GetTypeInfo().Assembly);
+ resourceMan = temp;
+ }
+ return resourceMan;
+ }
+ }
+
+ /// <summary>
+ /// Overrides the current thread's CurrentUICulture property for all
+ /// resource lookups using this strongly typed resource class.
+ /// </summary>
+ [global::System.ComponentModel.EditorBrowsableAttribute(global::System.ComponentModel.EditorBrowsableState.Advanced)]
+ internal static global::System.Globalization.CultureInfo Culture {
+ get {
+ return resourceCulture;
+ }
+ set {
+ resourceCulture = value;
+ }
+ }
+
+ /// <summary>
+ /// Looks up a localized string similar to No Name.
+ /// </summary>
+ internal static string _ {
+ get {
+ return ResourceManager.GetString("", resourceCulture);
+ }
+ }
+
+ /// <summary>
+ /// Looks up a localized string similar to Value-One.
+ /// </summary>
+ internal static string Object {
+ get {
+ return ResourceManager.GetString("Object", resourceCulture);
+ }
+ }
+
+ /// <summary>
+ /// Looks up a localized string similar to Third.
+ /// </summary>
+ internal static string Object_GetOnlyProperty {
+ get {
+ return ResourceManager.GetString("Object.GetOnlyProperty", resourceCulture);
+ }
+ }
+
+ /// <summary>
+ /// Looks up a localized string similar to One.
+ /// </summary>
+ internal static string Object_GetSetProperty {
+ get {
+ return ResourceManager.GetString("Object.GetSetProperty", resourceCulture);
+ }
+ }
+
+ /// <summary>
+ /// Looks up a localized string similar to Second.
+ /// </summary>
+ internal static string Object_NoSuchProperty {
+ get {
+ return ResourceManager.GetString("Object.NoSuchProperty", resourceCulture);
+ }
+ }
+
+ /// <summary>
+ /// Looks up a localized string similar to Third.
+ /// </summary>
+ internal static string Object_PrivateProperty {
+ get {
+ return ResourceManager.GetString("Object.PrivateProperty", resourceCulture);
+ }
+ }
+ }
+}
diff --git a/src/System.ComponentModel.TypeConverter/tests/Resources/TestResx.resx b/src/System.ComponentModel.TypeConverter/tests/Resources/TestResx.resx
new file mode 100644
index 0000000000..cc748dee7e
--- /dev/null
+++ b/src/System.ComponentModel.TypeConverter/tests/Resources/TestResx.resx
@@ -0,0 +1,79 @@
+<?xml version="1.0" encoding="utf-8"?>
+<root>
+ <xsd:schema id="root" xmlns="" xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns:msdata="urn:schemas-microsoft-com:xml-msdata">
+ <xsd:import namespace="http://www.w3.org/XML/1998/namespace" />
+ <xsd:element name="root" msdata:IsDataSet="true">
+ <xsd:complexType>
+ <xsd:choice maxOccurs="unbounded">
+ <xsd:element name="metadata">
+ <xsd:complexType>
+ <xsd:sequence>
+ <xsd:element name="value" type="xsd:string" minOccurs="0" />
+ </xsd:sequence>
+ <xsd:attribute name="name" use="required" type="xsd:string" />
+ <xsd:attribute name="type" type="xsd:string" />
+ <xsd:attribute name="mimetype" type="xsd:string" />
+ <xsd:attribute ref="xml:space" />
+ </xsd:complexType>
+ </xsd:element>
+ <xsd:element name="assembly">
+ <xsd:complexType>
+ <xsd:attribute name="alias" type="xsd:string" />
+ <xsd:attribute name="name" type="xsd:string" />
+ </xsd:complexType>
+ </xsd:element>
+ <xsd:element name="data">
+ <xsd:complexType>
+ <xsd:sequence>
+ <xsd:element name="value" type="xsd:string" minOccurs="0" msdata:Ordinal="1" />
+ <xsd:element name="comment" type="xsd:string" minOccurs="0" msdata:Ordinal="2" />
+ </xsd:sequence>
+ <xsd:attribute name="name" type="xsd:string" use="required" msdata:Ordinal="1" />
+ <xsd:attribute name="type" type="xsd:string" msdata:Ordinal="3" />
+ <xsd:attribute name="mimetype" type="xsd:string" msdata:Ordinal="4" />
+ <xsd:attribute ref="xml:space" />
+ </xsd:complexType>
+ </xsd:element>
+ <xsd:element name="resheader">
+ <xsd:complexType>
+ <xsd:sequence>
+ <xsd:element name="value" type="xsd:string" minOccurs="0" msdata:Ordinal="1" />
+ </xsd:sequence>
+ <xsd:attribute name="name" type="xsd:string" use="required" />
+ </xsd:complexType>
+ </xsd:element>
+ </xsd:choice>
+ </xsd:complexType>
+ </xsd:element>
+ </xsd:schema>
+ <resheader name="resmimetype">
+ <value>text/microsoft-resx</value>
+ </resheader>
+ <resheader name="version">
+ <value>2.0</value>
+ </resheader>
+ <resheader name="reader">
+ <value>System.Resources.ResXResourceReader, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089</value>
+ </resheader>
+ <resheader name="writer">
+ <value>System.Resources.ResXResourceWriter, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089</value>
+ </resheader>
+ <data name="" xml:space="preserve">
+ <value>No Name</value>
+ </data>
+ <data name="Object" xml:space="preserve">
+ <value>Value-One</value>
+ </data>
+ <data name="Object.GetSetProperty" xml:space="preserve">
+ <value>One</value>
+ </data>
+ <data name="Object.NoSuchProperty" xml:space="preserve">
+ <value>Second</value>
+ </data>
+ <data name="Object.GetOnlyProperty" xml:space="preserve">
+ <value>Third</value>
+ </data>
+ <data name="Object.PrivateProperty" xml:space="preserve">
+ <value>Third</value>
+ </data>
+</root> \ No newline at end of file
diff --git a/src/System.ComponentModel.TypeConverter/tests/System.ComponentModel.TypeConverter.Tests.csproj b/src/System.ComponentModel.TypeConverter/tests/System.ComponentModel.TypeConverter.Tests.csproj
index b5ac1d292a..90b22fbe94 100644
--- a/src/System.ComponentModel.TypeConverter/tests/System.ComponentModel.TypeConverter.Tests.csproj
+++ b/src/System.ComponentModel.TypeConverter/tests/System.ComponentModel.TypeConverter.Tests.csproj
@@ -22,19 +22,19 @@
<Compile Include="Drawing\SizeFConverterTests.cs" />
</ItemGroup>
<ItemGroup>
- <Compile Include="$(CommonTestPath)\System\AssertExtensions.cs">
- <Link>Common\System\AssertExtensions.cs</Link>
- </Compile>
<Compile Include="$(CommonTestPath)\System\PlatformDetection.cs">
<Link>Common\tests\System\PlatformDetection.cs</Link>
</Compile>
+ <Compile Include="AmbientValueAttributeTests.cs" />
<Compile Include="ArrayConverterTests.cs" />
<Compile Include="AttributeCollectionTests.cs" />
<Compile Include="AttributeProviderAttributeTests.cs" />
+ <Compile Include="BindingListTests.cs" />
<Compile Include="BooleanConverterTests.cs" />
<Compile Include="ByteConvertersTests.cs" />
<Compile Include="CharConverterTests.cs" />
<Compile Include="CollectionConverterTests.cs" />
+ <Compile Include="ComponentResourceManagerTests.cs" />
<Compile Include="ConverterTestBase.cs" />
<Compile Include="CustomTypeDescriptorTests.cs" />
<Compile Include="DateTimeConverterTests.cs" />
@@ -60,6 +60,11 @@
<Compile Include="PropertyDescriptorCollectionTests.cs" />
<Compile Include="PropertyDescriptorTests.cs" />
<Compile Include="ProvidePropertyAttributeTests.cs" />
+ <Compile Include="Resources\TestResx.Designer.cs">
+ <AutoGen>True</AutoGen>
+ <DesignTime>True</DesignTime>
+ <DependentUpon>TestResx.resx</DependentUpon>
+ </Compile>
<Compile Include="SampleClasses.cs" />
<Compile Include="SByteConverterTests.cs" />
<Compile Include="SingleConverterTests.cs" />
@@ -76,7 +81,6 @@
<Compile Include="UriTypeConverterTests.cs" />
<Compile Include="Drawing\StringTypeConverterTestBase.cs" />
<Compile Include="TimerTests.cs" />
- <Compile Include="BindingListTests.cs" />
<Compile Include="ContainerTests.cs" />
<Compile Include="CultureInfoConverterTests.cs" />
<Compile Include="LicenseManagerTests.cs" />
@@ -91,5 +95,12 @@
<Name>RemoteExecutorConsoleApp</Name>
</ProjectReference>
</ItemGroup>
+ <ItemGroup>
+ <EmbeddedResource Include="Resources\TestResx.resx">
+ <Generator>ResXFileCodeGenerator</Generator>
+ <LastGenOutput>TestResx.Designer.cs</LastGenOutput>
+ </EmbeddedResource>
+ </ItemGroup>
+ <ItemGroup />
<Import Project="$([MSBuild]::GetDirectoryNameOfFileAbove($(MSBuildThisFileDirectory), dir.targets))\dir.targets" />
</Project> \ No newline at end of file
diff --git a/src/System.Composition.AttributedModel/tests/System.Composition.AttributeModel.Tests.csproj b/src/System.Composition.AttributedModel/tests/System.Composition.AttributeModel.Tests.csproj
index 584f4187cd..d41d1d7fc0 100644
--- a/src/System.Composition.AttributedModel/tests/System.Composition.AttributeModel.Tests.csproj
+++ b/src/System.Composition.AttributedModel/tests/System.Composition.AttributeModel.Tests.csproj
@@ -18,9 +18,6 @@
<Compile Include="ImportAttributeTests.cs" />
<Compile Include="ExportMetadataAttributeTests.cs" />
<Compile Include="ExportAttributeTests.cs" />
- <Compile Include="$(CommonTestPath)\System\AssertExtensions.cs">
- <Link>Common\System\AssertExtensions.cs</Link>
- </Compile>
</ItemGroup>
<Import Project="$([MSBuild]::GetDirectoryNameOfFileAbove($(MSBuildThisFileDirectory), dir.targets))\dir.targets" />
</Project> \ No newline at end of file
diff --git a/src/System.Composition.Hosting/tests/System.Composition.Hosting.Tests.csproj b/src/System.Composition.Hosting/tests/System.Composition.Hosting.Tests.csproj
index 37aa1c8be7..23afc7b81d 100644
--- a/src/System.Composition.Hosting/tests/System.Composition.Hosting.Tests.csproj
+++ b/src/System.Composition.Hosting/tests/System.Composition.Hosting.Tests.csproj
@@ -15,9 +15,6 @@
<Compile Include="System\Composition\Hosting\Core\ExportDescriptorProviderTests.cs" />
<Compile Include="System\Composition\Hosting\Core\LifetimeContextTests.cs" />
<Compile Include="System\Composition\Hosting\Core\ExportDescriptorTests.cs" />
- <Compile Include="$(CommonTestPath)\System\AssertExtensions.cs">
- <Link>Common\System\AssertExtensions.cs</Link>
- </Compile>
<Compile Include="$(CommonTestPath)\System\PlatformDetection.cs">
<Link>Common\System\PlatformDetection.cs</Link>
</Compile>
diff --git a/src/System.Composition.Runtime/tests/System.Composition.Runtime.Tests.csproj b/src/System.Composition.Runtime/tests/System.Composition.Runtime.Tests.csproj
index 07417c2e77..842c342da6 100644
--- a/src/System.Composition.Runtime/tests/System.Composition.Runtime.Tests.csproj
+++ b/src/System.Composition.Runtime/tests/System.Composition.Runtime.Tests.csproj
@@ -13,9 +13,6 @@
<Compile Include="ExportFactoryTMetadataTests.cs" />
<Compile Include="ExportFactoryTests.cs" />
<Compile Include="ExportTests.cs" />
- <Compile Include="$(CommonTestPath)\System\AssertExtensions.cs">
- <Link>Common\System\AssertExtensions.cs</Link>
- </Compile>
</ItemGroup>
<Import Project="$([MSBuild]::GetDirectoryNameOfFileAbove($(MSBuildThisFileDirectory), dir.targets))\dir.targets" />
</Project> \ No newline at end of file
diff --git a/src/System.Composition.TypedParts/tests/System.Composition.TypedParts.Tests.csproj b/src/System.Composition.TypedParts/tests/System.Composition.TypedParts.Tests.csproj
index 7011169d7f..45f80cc2b8 100644
--- a/src/System.Composition.TypedParts/tests/System.Composition.TypedParts.Tests.csproj
+++ b/src/System.Composition.TypedParts/tests/System.Composition.TypedParts.Tests.csproj
@@ -8,9 +8,6 @@
<PropertyGroup Condition="'$(Configuration)|$(Platform)' == 'netstandard-Release|AnyCPU'" />
<ItemGroup>
<Compile Include="ContainerConfigurationTests.cs" />
- <Compile Include="$(CommonTestPath)\System\AssertExtensions.cs">
- <Link>Common\System\AssertExtensions.cs</Link>
- </Compile>
<Compile Include="$(CommonTestPath)\System\Diagnostics\DebuggerAttributes.cs">
<Link>Common\System\Diagnostics\DebuggerAttributes.cs</Link>
</Compile>
diff --git a/src/System.Configuration.ConfigurationManager/ref/System.Configuration.ConfigurationManager.csproj b/src/System.Configuration.ConfigurationManager/ref/System.Configuration.ConfigurationManager.csproj
index 937f2ba8d6..948dd3bedd 100644
--- a/src/System.Configuration.ConfigurationManager/ref/System.Configuration.ConfigurationManager.csproj
+++ b/src/System.Configuration.ConfigurationManager/ref/System.Configuration.ConfigurationManager.csproj
@@ -3,8 +3,8 @@
<Import Project="$([MSBuild]::GetDirectoryNameOfFileAbove($(MSBuildThisFileDirectory), dir.props))\dir.props" />
<PropertyGroup>
<ProjectGuid>{FD6AA2B9-56DB-4BCC-85E0-7727506562B0}</ProjectGuid>
- <!-- UAP10.1 is not yet mapped to netstandard2.0, manually duplicate this ref -->
- <PackageTargetFramework Condition="'$(TargetGroup)' == 'netstandard'">netstandard2.0;uap10.1</PackageTargetFramework>
+ <!-- UAPvNext is not yet mapped to netstandard2.0, manually duplicate this ref -->
+ <PackageTargetFramework Condition="'$(TargetGroup)' == 'netstandard'">netstandard2.0;$(UAPvNextTFM)</PackageTargetFramework>
<IsPartialFacadeAssembly Condition="'$(TargetGroup)' == 'netfx'">true</IsPartialFacadeAssembly>
</PropertyGroup>
<PropertyGroup Condition="'$(Configuration)|$(Platform)' == 'netfx-Debug|AnyCPU'" />
@@ -12,7 +12,7 @@
<PropertyGroup Condition="'$(Configuration)|$(Platform)' == 'netstandard-Debug|AnyCPU'" />
<PropertyGroup Condition="'$(Configuration)|$(Platform)' == 'netstandard-Release|AnyCPU'" />
<ItemGroup>
- <SuppressPackageTargetFrameworkCompatibility Include="uap10.1" />
+ <SuppressPackageTargetFrameworkCompatibility Include="$(UAPvNextTFM)" />
<Compile Include="System.Configuration.cs" />
</ItemGroup>
<ItemGroup Condition="'$(IsPartialFacadeAssembly)' == 'true'">
@@ -20,6 +20,7 @@
<Reference Include="System" />
<Reference Include="System.Configuration" />
<Reference Include="System.Core" />
+ <Reference Include="System.Drawing" />
<Reference Include="System.Xml" />
</ItemGroup>
<Import Project="$([MSBuild]::GetDirectoryNameOfFileAbove($(MSBuildThisFileDirectory), dir.targets))\dir.targets" />
diff --git a/src/System.Configuration.ConfigurationManager/ref/System.Configuration.cs b/src/System.Configuration.ConfigurationManager/ref/System.Configuration.cs
index 2b328ec149..e7ec34477d 100644
--- a/src/System.Configuration.ConfigurationManager/ref/System.Configuration.cs
+++ b/src/System.Configuration.ConfigurationManager/ref/System.Configuration.cs
@@ -1596,6 +1596,16 @@ namespace System.Configuration.Provider
public ProviderException(string message, System.Exception innerException) { }
}
}
+namespace System.Drawing.Configuration
+{
+ public sealed partial class SystemDrawingSection : System.Configuration.ConfigurationSection
+ {
+ public SystemDrawingSection() { }
+ [System.Configuration.ConfigurationPropertyAttribute("bitmapSuffix")]
+ public string BitmapSuffix { get { throw null; } set { } }
+ protected override System.Configuration.ConfigurationPropertyCollection Properties { get { throw null; } }
+ }
+}
#pragma warning restore CS0618
diff --git a/src/System.Configuration.ConfigurationManager/src/System.Configuration.ConfigurationManager.csproj b/src/System.Configuration.ConfigurationManager/src/System.Configuration.ConfigurationManager.csproj
index 330a90e881..6b9ff6aebd 100644
--- a/src/System.Configuration.ConfigurationManager/src/System.Configuration.ConfigurationManager.csproj
+++ b/src/System.Configuration.ConfigurationManager/src/System.Configuration.ConfigurationManager.csproj
@@ -243,6 +243,7 @@
<Compile Include="System\Configuration\WhiteSpaceTrimStringConverter.cs" />
<Compile Include="System\Configuration\XmlUtil.cs" />
<Compile Include="System\Configuration\XmlUtilWriter.cs" />
+ <Compile Include="System\Drawing\Configuration\SystemDrawingSection.cs" />
<Compile Include="$(CommonPath)\System\Security\IdentityHelper.cs">
<Link>Common\System\Security\IdentityHelper.cs</Link>
</Compile>
@@ -266,6 +267,7 @@
<Reference Include="System" />
<Reference Include="System.Core" />
<Reference Include="System.Configuration" />
+ <Reference Include="System.Drawing" />
<Reference Include="System.Xml" />
</ItemGroup>
<Import Project="$([MSBuild]::GetDirectoryNameOfFileAbove($(MSBuildThisFileDirectory), dir.targets))\dir.targets" />
diff --git a/src/System.Drawing.Common/src/System/Drawing/Configuration/SystemDrawingSection.cs b/src/System.Configuration.ConfigurationManager/src/System/Drawing/Configuration/SystemDrawingSection.cs
index cf6653214e..6ddf41b39e 100644
--- a/src/System.Drawing.Common/src/System/Drawing/Configuration/SystemDrawingSection.cs
+++ b/src/System.Configuration.ConfigurationManager/src/System/Drawing/Configuration/SystemDrawingSection.cs
@@ -19,7 +19,7 @@ namespace System.Drawing.Configuration
set => this[s_bitmapSuffix] = value;
}
- protected override ConfigurationPropertyCollection Properties => s_properties;
+ protected internal override ConfigurationPropertyCollection Properties => s_properties;
private static readonly ConfigurationPropertyCollection s_properties = new ConfigurationPropertyCollection();
diff --git a/src/System.Configuration.ConfigurationManager/tests/System.Configuration.ConfigurationManager.Tests.csproj b/src/System.Configuration.ConfigurationManager/tests/System.Configuration.ConfigurationManager.Tests.csproj
index 18fa12319b..0e5f2b741c 100644
--- a/src/System.Configuration.ConfigurationManager/tests/System.Configuration.ConfigurationManager.Tests.csproj
+++ b/src/System.Configuration.ConfigurationManager/tests/System.Configuration.ConfigurationManager.Tests.csproj
@@ -105,9 +105,7 @@
<Compile Include="System\Configuration\UriSectionTests.cs" />
<Compile Include="System\Configuration\UrlPathTests.cs" />
<Compile Include="System\Configuration\ValidatiorUtilsTests.cs" />
- <Compile Include="$(CommonTestPath)\System\AssertExtensions.cs">
- <Link>Common\System\AssertExtensions.cs</Link>
- </Compile>
+ <Compile Include="System\Drawing\Configuration\SystemDrawingSectionTests.cs" />
</ItemGroup>
<Import Project="$([MSBuild]::GetDirectoryNameOfFileAbove($(MSBuildThisFileDirectory), dir.targets))\dir.targets" />
</Project> \ No newline at end of file
diff --git a/src/System.Configuration.ConfigurationManager/tests/System/Drawing/Configuration/SystemDrawingSectionTests.cs b/src/System.Configuration.ConfigurationManager/tests/System/Drawing/Configuration/SystemDrawingSectionTests.cs
new file mode 100644
index 0000000000..bf92e32a03
--- /dev/null
+++ b/src/System.Configuration.ConfigurationManager/tests/System/Drawing/Configuration/SystemDrawingSectionTests.cs
@@ -0,0 +1,31 @@
+// Licensed to the .NET Foundation under one or more agreements.
+// See the LICENSE file in the project root for more information.
+
+using System.Configuration;
+using Xunit;
+
+namespace System.Drawing.Configuration.Tests
+{
+ public class SystemDrawingSectionTests
+ {
+ [Fact]
+ public void Ctor_Default()
+ {
+ var section = new SystemDrawingSection();
+ Assert.Null(section.BitmapSuffix);
+ }
+
+ [Theory]
+ [InlineData(null)]
+ [InlineData("")]
+ [InlineData("BitmapSuffix")]
+ public void BitmapSuffix_Set_GetReturnsExpected(string bitmapSuffix)
+ {
+ var section = new SystemDrawingSection { BitmapSuffix = bitmapSuffix };
+ Assert.Equal(bitmapSuffix, section.BitmapSuffix);
+
+ PropertyInformation propertyInformation = section.ElementInformation.Properties["bitmapSuffix"];
+ Assert.Equal(bitmapSuffix, propertyInformation.Value);
+ }
+ }
+}
diff --git a/src/System.Console/tests/System.Console.Tests.csproj b/src/System.Console/tests/System.Console.Tests.csproj
index 7729b83ea5..2ce0244bd2 100644
--- a/src/System.Console/tests/System.Console.Tests.csproj
+++ b/src/System.Console/tests/System.Console.Tests.csproj
@@ -34,9 +34,6 @@
<Compile Include="TermInfo.cs" />
<Compile Include="RedirectedStream.cs" />
<Compile Include="ReadKey.cs" />
- <Compile Include="$(CommonTestPath)\System\AssertExtensions.cs">
- <Link>Common\System\AssertExtensions.cs</Link>
- </Compile>
<Compile Include="$(CommonTestPath)\System\IO\InterceptStreamWriter.cs">
<Link>Common\System\IO\InterceptStreamWriter.cs</Link>
</Compile>
diff --git a/src/System.Data.Common/src/Configurations.props b/src/System.Data.Common/src/Configurations.props
index dec427aa16..c172e09c79 100644
--- a/src/System.Data.Common/src/Configurations.props
+++ b/src/System.Data.Common/src/Configurations.props
@@ -5,6 +5,7 @@
uap-Windows_NT;
netcoreapp;
netfx;
+ uapaot-Windows_NT;
</BuildConfigurations>
</PropertyGroup>
</Project> \ No newline at end of file
diff --git a/src/System.Data.Common/src/System.Data.Common.csproj b/src/System.Data.Common/src/System.Data.Common.csproj
index a8f3487284..2f897127f4 100644
--- a/src/System.Data.Common/src/System.Data.Common.csproj
+++ b/src/System.Data.Common/src/System.Data.Common.csproj
@@ -7,6 +7,7 @@
<AllowUnsafeBlocks>true</AllowUnsafeBlocks>
<PlatformTarget>AnyCPU</PlatformTarget>
<IsPartialFacadeAssembly Condition="'$(TargetGroup)' == 'netfx'">true</IsPartialFacadeAssembly>
+ <DefineConstants Condition="'$(TargetGroup)' == 'uapaot'">$(DefineConstants);uapaot</DefineConstants>
</PropertyGroup>
<PropertyGroup Condition="'$(Configuration)|$(Platform)' == 'netcoreapp-Debug|AnyCPU'" />
<PropertyGroup Condition="'$(Configuration)|$(Platform)' == 'netcoreapp-Release|AnyCPU'" />
@@ -14,6 +15,8 @@
<PropertyGroup Condition="'$(Configuration)|$(Platform)' == 'netfx-Release|AnyCPU'" />
<PropertyGroup Condition="'$(Configuration)|$(Platform)' == 'uap-Windows_NT-Debug|AnyCPU'" />
<PropertyGroup Condition="'$(Configuration)|$(Platform)' == 'uap-Windows_NT-Release|AnyCPU'" />
+ <PropertyGroup Condition="'$(Configuration)|$(Platform)' == 'uapaot-Windows_NT-Debug|AnyCPU'" />
+ <PropertyGroup Condition="'$(Configuration)|$(Platform)' == 'uapaot-Windows_NT-Release|AnyCPU'" />
<ItemGroup>
<Compile Include="System\Data\Common\DbColumn.cs" />
<Compile Include="System\Data\Common\IDbColumnSchemaGenerator.cs" />
@@ -310,10 +313,15 @@
<Reference Include="System.Threading" />
<Reference Include="System.Threading.Thread" />
<Reference Include="System.Transactions.Local" />
+ </ItemGroup>
+ <ItemGroup Condition="'$(TargetGroup)' != 'uapaot' and '$(TargetGroup)' != 'netfx'">
<Reference Include="System.Xml.ReaderWriter" />
<Reference Include="System.Xml.XmlSerializer" />
</ItemGroup>
- <ItemGroup Condition="'$(TargetGroup)' == 'netcoreapp' or '$(TargetGroup)' == 'uap'">
+ <ItemGroup Condition="'$(TargetGroup)' == 'uapaot'">
+ <ProjectReference Include="..\..\System.Private.Xml\src\System.Private.Xml.csproj" />
+ </ItemGroup>
+ <ItemGroup Condition="'$(TargetGroup)' == 'netcoreapp' or '$(TargetGroup)' == 'uap' or '$(TargetGroup)' == 'uapaot'">
<EmbeddedResource Include="Resources\$(AssemblyName).rd.xml" />
</ItemGroup>
<Import Project="$([MSBuild]::GetDirectoryNameOfFileAbove($(MSBuildThisFileDirectory), dir.targets))\dir.targets" />
diff --git a/src/System.Data.Common/src/System/Data/SQLTypes/SqlXml.cs b/src/System.Data.Common/src/System/Data/SQLTypes/SqlXml.cs
index 8a9b90508b..82fb494164 100644
--- a/src/System.Data.Common/src/System/Data/SQLTypes/SqlXml.cs
+++ b/src/System.Data.Common/src/System/Data/SQLTypes/SqlXml.cs
@@ -19,12 +19,14 @@ namespace System.Data.SqlTypes
private static readonly Func<Stream, XmlReaderSettings, XmlParserContext, XmlReader> s_sqlReaderDelegate = CreateSqlReaderDelegate();
private static readonly XmlReaderSettings s_defaultXmlReaderSettings = new XmlReaderSettings() { ConformanceLevel = ConformanceLevel.Fragment };
private static readonly XmlReaderSettings s_defaultXmlReaderSettingsCloseInput = new XmlReaderSettings() { ConformanceLevel = ConformanceLevel.Fragment, CloseInput = true };
+#if !uapaot
private static MethodInfo s_createSqlReaderMethodInfo;
+ private MethodInfo _createSqlReaderMethodInfo;
+#endif
private bool _fNotNull; // false if null, the default ctor (plain 0) will make it Null
private Stream _stream;
private bool _firstCreateReader;
- private MethodInfo _createSqlReaderMethodInfo;
public SqlXml()
{
@@ -84,12 +86,14 @@ namespace System.Data.SqlTypes
stream.Seek(0, SeekOrigin.Begin);
}
+#if !uapaot
// NOTE: Maintaining createSqlReaderMethodInfo private field member to preserve the serialization of the class
if (_createSqlReaderMethodInfo == null)
{
_createSqlReaderMethodInfo = CreateSqlReaderMethodInfo;
}
Debug.Assert(_createSqlReaderMethodInfo != null, "MethodInfo reference for XmlReader.CreateSqlReader should not be null.");
+#endif
XmlReader r = CreateSqlXmlReader(stream);
_firstCreateReader = false;
@@ -118,6 +122,9 @@ namespace System.Data.SqlTypes
}
}
+#if uapaot
+ private static Func<Stream, XmlReaderSettings, XmlParserContext, XmlReader> CreateSqlReaderDelegate() => System.Xml.XmlReader.CreateSqlReader;
+#else
private static Func<Stream, XmlReaderSettings, XmlParserContext, XmlReader> CreateSqlReaderDelegate()
{
Debug.Assert(CreateSqlReaderMethodInfo != null, "MethodInfo reference for XmlReader.CreateSqlReader should not be null.");
@@ -137,6 +144,7 @@ namespace System.Data.SqlTypes
return s_createSqlReaderMethodInfo;
}
}
+#endif
// INullable
public bool IsNull
diff --git a/src/System.Data.Common/tests/System.Data.Common.Tests.csproj b/src/System.Data.Common/tests/System.Data.Common.Tests.csproj
index 1a16691524..00f409e47d 100644
--- a/src/System.Data.Common/tests/System.Data.Common.Tests.csproj
+++ b/src/System.Data.Common/tests/System.Data.Common.Tests.csproj
@@ -101,9 +101,6 @@
<Compile Include="System\Data\VersionNotFoundException.cs" />
<Compile Include="System\Data\XmlDataLoaderTest.cs" />
<Compile Include="System\Data\XmlDataReaderTest.cs" />
- <Compile Include="$(CommonTestPath)\System\AssertExtensions.cs">
- <Link>Common\System\AssertExtensions.cs</Link>
- </Compile>
<Compile Include="$(CommonTestPath)\System\Diagnostics\Tracing\TestEventListener.cs">
<Link>Common\System\Diagnostics\Tracing\TestEventListener.cs</Link>
</Compile>
diff --git a/src/System.Data.Common/tests/System/Data/SqlTypes/SqlXmlTest.cs b/src/System.Data.Common/tests/System/Data/SqlTypes/SqlXmlTest.cs
index 8010510b73..2fc999247d 100644
--- a/src/System.Data.Common/tests/System/Data/SqlTypes/SqlXmlTest.cs
+++ b/src/System.Data.Common/tests/System/Data/SqlTypes/SqlXmlTest.cs
@@ -49,7 +49,6 @@ namespace System.Data.Tests.SqlTypes
// Test constructor
[Fact] // .ctor (Stream)
//[Category ("NotDotNet")] // Name cannot begin with the '.' character, hexadecimal value 0x00. Line 1, position 2
- [ActiveIssue("https://github.com/dotnet/corefx/issues/19202", TargetFrameworkMonikers.UapAot)]
public void Constructor2_Stream_Unicode()
{
string xmlStr = "<Employee><FirstName>Varadhan</FirstName><LastName>Veerapuram</LastName></Employee>";
@@ -60,7 +59,6 @@ namespace System.Data.Tests.SqlTypes
}
[Fact] // .ctor (Stream)
- [ActiveIssue("https://github.com/dotnet/corefx/issues/19202", TargetFrameworkMonikers.UapAot)]
public void Constructor2_Stream_Empty()
{
MemoryStream ms = new MemoryStream();
@@ -86,7 +84,6 @@ namespace System.Data.Tests.SqlTypes
}
[Fact] // .ctor (XmlReader)
- [ActiveIssue("https://github.com/dotnet/corefx/issues/19202", TargetFrameworkMonikers.UapAot)]
public void Constructor3()
{
string xmlStr = "<Employee><FirstName>Varadhan</FirstName><LastName>Veerapuram</LastName></Employee>";
@@ -97,7 +94,6 @@ namespace System.Data.Tests.SqlTypes
}
[Fact] // .ctor (XmlReader)
- [ActiveIssue("https://github.com/dotnet/corefx/issues/19202", TargetFrameworkMonikers.UapAot)]
public void Constructor3_XmlReader_Empty()
{
XmlReaderSettings xs = new XmlReaderSettings();
@@ -126,7 +122,6 @@ namespace System.Data.Tests.SqlTypes
[Fact]
//[Category ("NotDotNet")] // Name cannot begin with the '.' character, hexadecimal value 0x00. Line 1, position 2
- [ActiveIssue("https://github.com/dotnet/corefx/issues/19202", TargetFrameworkMonikers.UapAot)]
public void CreateReader_Stream_Unicode()
{
string xmlStr = "<Employee><FirstName>Varadhan</FirstName><LastName>Veerapuram</LastName></Employee>";
@@ -140,7 +135,6 @@ namespace System.Data.Tests.SqlTypes
}
[Fact]
- [ActiveIssue("https://github.com/dotnet/corefx/issues/19202", TargetFrameworkMonikers.UapAot)]
public void SqlXml_fromXmlReader_CreateReaderTest()
{
string xmlStr = "<Employee><FirstName>Varadhan</FirstName><LastName>Veerapuram</LastName></Employee>";
@@ -154,7 +148,6 @@ namespace System.Data.Tests.SqlTypes
}
[Fact]
- [ActiveIssue("https://github.com/dotnet/corefx/issues/19202", TargetFrameworkMonikers.UapAot)]
public void SqlXml_fromZeroLengthStream_CreateReaderTest()
{
MemoryStream stream = new MemoryStream();
@@ -166,7 +159,6 @@ namespace System.Data.Tests.SqlTypes
}
[Fact]
- [ActiveIssue("https://github.com/dotnet/corefx/issues/19202", TargetFrameworkMonikers.UapAot)]
public void SqlXml_fromZeroLengthXmlReader_CreateReaderTest_withFragment()
{
XmlReaderSettings xs = new XmlReaderSettings();
diff --git a/src/System.Data.SqlClient/pkg/System.Data.SqlClient.pkgproj b/src/System.Data.SqlClient/pkg/System.Data.SqlClient.pkgproj
index b9db8ddf69..25cf504279 100644
--- a/src/System.Data.SqlClient/pkg/System.Data.SqlClient.pkgproj
+++ b/src/System.Data.SqlClient/pkg/System.Data.SqlClient.pkgproj
@@ -3,7 +3,7 @@
<Import Project="$([MSBuild]::GetDirectoryNameOfFileAbove($(MSBuildThisFileDirectory), dir.props))\dir.props" />
<ItemGroup>
<ProjectReference Include="..\ref\System.Data.SqlClient.csproj">
- <SupportedFramework>net461;netcoreapp2.0;uap10.1;$(AllXamarinFrameworks)</SupportedFramework>
+ <SupportedFramework>net461;netcoreapp2.0;$(UAPvNextTFM);$(AllXamarinFrameworks)</SupportedFramework>
</ProjectReference>
<ProjectReference Include="..\src\System.Data.SqlClient.csproj" />
<HarvestIncludePaths Include="ref/net451;lib/net451;runtimes/win/lib/net451" />
diff --git a/src/System.Data.SqlClient/ref/System.Data.SqlClient.cs b/src/System.Data.SqlClient/ref/System.Data.SqlClient.cs
index 850a48c526..db2bef225b 100644
--- a/src/System.Data.SqlClient/ref/System.Data.SqlClient.cs
+++ b/src/System.Data.SqlClient/ref/System.Data.SqlClient.cs
@@ -433,6 +433,7 @@ namespace System.Data.SqlClient
public bool PersistSecurityInfo { get { throw null; } set { } }
public bool Pooling { get { throw null; } set { } }
public bool Replication { get { throw null; } set { } }
+ public string TransactionBinding { get { throw null; } set { } }
public bool TrustServerCertificate { get { throw null; } set { } }
public string TypeSystemVersion { get { throw null; } set { } }
public string UserID { get { throw null; } set { } }
diff --git a/src/System.Data.SqlClient/ref/System.Data.SqlClient.csproj b/src/System.Data.SqlClient/ref/System.Data.SqlClient.csproj
index 02599cc2b8..0647919132 100644
--- a/src/System.Data.SqlClient/ref/System.Data.SqlClient.csproj
+++ b/src/System.Data.SqlClient/ref/System.Data.SqlClient.csproj
@@ -4,15 +4,15 @@
<PropertyGroup>
<ProjectGuid>{D58E8D2B-3331-4660-8DFB-512D66F8EC63}</ProjectGuid>
<IsPartialFacadeAssembly Condition="'$(TargetGroup)' == 'netfx'">true</IsPartialFacadeAssembly>
- <!-- UAP10.1 is not yet mapped to netstandard2.0, manually duplicate this ref -->
- <PackageTargetFramework Condition="'$(TargetGroup)' == 'netstandard'">netstandard2.0;uap10.1</PackageTargetFramework>
+ <!-- UAPvNext is not yet mapped to netstandard2.0, manually duplicate this ref -->
+ <PackageTargetFramework Condition="'$(TargetGroup)' == 'netstandard'">netstandard2.0;$(UAPvNextTFM)</PackageTargetFramework>
</PropertyGroup>
<PropertyGroup Condition="'$(Configuration)|$(Platform)' == 'netfx-Debug|AnyCPU'" />
<PropertyGroup Condition="'$(Configuration)|$(Platform)' == 'netfx-Release|AnyCPU'" />
<PropertyGroup Condition="'$(Configuration)|$(Platform)' == 'netstandard-Debug|AnyCPU'" />
<PropertyGroup Condition="'$(Configuration)|$(Platform)' == 'netstandard-Release|AnyCPU'" />
<ItemGroup>
- <SuppressPackageTargetFrameworkCompatibility Include="uap10.1" />
+ <SuppressPackageTargetFrameworkCompatibility Include="$(UAPvNextTFM)" />
<Compile Include="System.Data.SqlClient.cs" />
<Compile Include="System.Data.SqlClient.Manual.cs" />
</ItemGroup>
diff --git a/src/System.Data.SqlClient/src/Interop/SNINativeMethodWrapper.Common.cs b/src/System.Data.SqlClient/src/Interop/SNINativeMethodWrapper.Common.cs
new file mode 100644
index 0000000000..5093d47052
--- /dev/null
+++ b/src/System.Data.SqlClient/src/Interop/SNINativeMethodWrapper.Common.cs
@@ -0,0 +1,24 @@
+// Licensed to the .NET Foundation under one or more agreements.
+// The .NET Foundation licenses this file to you under the MIT license.
+// See the LICENSE file in the project root for more information.
+
+using System.Data.SqlClient.SNI;
+
+namespace System.Data.SqlClient
+{
+ internal static partial class SNINativeMethodWrapper
+ {
+ internal enum SniSpecialErrors : uint
+ {
+ LocalDBErrorCode = SNICommon.LocalDBErrorCode,
+
+ // multi-subnet-failover specific error codes
+ MultiSubnetFailoverWithMoreThan64IPs = SNICommon.MultiSubnetFailoverWithMoreThan64IPs,
+ MultiSubnetFailoverWithInstanceSpecified = SNICommon.MultiSubnetFailoverWithInstanceSpecified,
+ MultiSubnetFailoverWithNonTcpProtocol = SNICommon.MultiSubnetFailoverWithNonTcpProtocol,
+
+ // max error code value
+ MaxErrorValue = SNICommon.MaxErrorValue
+ }
+ }
+} \ No newline at end of file
diff --git a/src/System.Data.SqlClient/src/Interop/SNINativeMethodWrapper.Unix.cs b/src/System.Data.SqlClient/src/Interop/SNINativeMethodWrapper.Unix.cs
index 673c91efb7..329bb4f5f8 100644
--- a/src/System.Data.SqlClient/src/Interop/SNINativeMethodWrapper.Unix.cs
+++ b/src/System.Data.SqlClient/src/Interop/SNINativeMethodWrapper.Unix.cs
@@ -4,25 +4,6 @@
using System.Data.SqlClient.SNI;
-namespace System.Data.SqlClient
-{
- internal static class SNINativeMethodWrapper
- {
- internal enum SniSpecialErrors : uint
- {
- LocalDBErrorCode = SNICommon.LocalDBErrorCode,
-
- // multi-subnet-failover specific error codes
- MultiSubnetFailoverWithMoreThan64IPs = SNICommon.MultiSubnetFailoverWithMoreThan64IPs,
- MultiSubnetFailoverWithInstanceSpecified = SNICommon.MultiSubnetFailoverWithInstanceSpecified,
- MultiSubnetFailoverWithNonTcpProtocol = SNICommon.MultiSubnetFailoverWithNonTcpProtocol,
-
- // max error code value
- MaxErrorValue = SNICommon.MaxErrorValue
- }
- }
-}
-
namespace System.Data
{
internal static partial class SafeNativeMethods
diff --git a/src/System.Data.SqlClient/src/Interop/SNINativeMethodWrapper.Windows.cs b/src/System.Data.SqlClient/src/Interop/SNINativeMethodWrapper.Windows.cs
index 4f5784f954..1902b7045a 100644
--- a/src/System.Data.SqlClient/src/Interop/SNINativeMethodWrapper.Windows.cs
+++ b/src/System.Data.SqlClient/src/Interop/SNINativeMethodWrapper.Windows.cs
@@ -8,7 +8,7 @@ using System.Runtime.InteropServices;
namespace System.Data.SqlClient
{
- internal static class SNINativeMethodWrapper
+ internal static partial class SNINativeMethodWrapper
{
private const string SNI = "sni.dll";
@@ -178,18 +178,6 @@ namespace System.Data.SqlClient
internal uint lineNumber;
}
- internal enum SniSpecialErrors : uint
- {
- LocalDBErrorCode = 50,
-
- // multi-subnet-failover specific error codes
- MultiSubnetFailoverWithMoreThan64IPs = 47,
- MultiSubnetFailoverWithInstanceSpecified = 48,
- MultiSubnetFailoverWithNonTcpProtocol = 49,
-
- // max error code value
- MaxErrorValue = 50157
- }
#endregion
#region DLL Imports
diff --git a/src/System.Data.SqlClient/src/Resources/Strings.resx b/src/System.Data.SqlClient/src/Resources/Strings.resx
index d080916d71..bd17307171 100644
--- a/src/System.Data.SqlClient/src/Resources/Strings.resx
+++ b/src/System.Data.SqlClient/src/Resources/Strings.resx
@@ -115,6 +115,12 @@
<data name="ADP_InvalidOffsetValue" xml:space="preserve">
<value>Invalid parameter Offset value '{0}'. The value must be greater than or equal to 0.</value>
</data>
+ <data name="ADP_TransactionPresent" xml:space="preserve">
+ <value>Connection currently has transaction enlisted. Finish current transaction and retry.</value>
+ </data>
+ <data name="ADP_LocalTransactionPresent" xml:space="preserve">
+ <value>Cannot enlist in the transaction because a local transaction is in progress on the connection. Finish local transaction and retry.</value>
+ </data>
<data name="ADP_NoConnectionString" xml:space="preserve">
<value>The ConnectionString property has not been initialized.</value>
</data>
@@ -493,6 +499,9 @@
<data name="SQL_XmlReaderNotSupportOnColumnType" xml:space="preserve">
<value>Invalid attempt to GetXmlReader on column '{0}'. The GetXmlReader function can only be used on columns of type Xml.</value>
</data>
+ <data name="SqlDelegatedTransaction_PromotionFailed" xml:space="preserve">
+ <value>Failure while attempting to promote transaction.</value>
+ </data>
<data name="SQL_InvalidBufferSizeOrIndex" xml:space="preserve">
<value>Buffer offset '{1}' plus the bytes available '{0}' is greater than the length of the passed in buffer.</value>
</data>
@@ -550,6 +559,9 @@
<data name="SQL_BulkLoadPendingOperation" xml:space="preserve">
<value>Attempt to invoke bulk copy on an object that has a pending operation.</value>
</data>
+ <data name="SQL_CannotGetDTCAddress" xml:space="preserve">
+ <value>Unable to get the address of the distributed transaction coordinator for the server, from the server. Is DTC enabled on the server?</value>
+ </data>
<data name="SQL_ConnectionDoomed" xml:space="preserve">
<value>The requested operation cannot be completed because the connection has been broken.</value>
</data>
@@ -577,6 +589,9 @@
<data name="SQL_ExRoutingDestination" xml:space="preserve">
<value>Routing Destination:{0}</value>
</data>
+ <data name="SQL_UnsupportedSysTxVersion" xml:space="preserve">
+ <value>The currently loaded System.Transactions.dll does not support Global Transactions.</value>
+ </data>
<data name="SqlMisc_NullString" xml:space="preserve">
<value>Null</value>
</data>
@@ -667,6 +682,9 @@
<data name="ADP_OperationAbortedExceptionMessage" xml:space="preserve">
<value>Operation aborted due to an exception (see InnerException for details).</value>
</data>
+ <data name="ADP_TransactionCompletedButNotDisposed" xml:space="preserve">
+ <value>The transaction associated with the current connection has completed but has not been disposed. The transaction must be disposed before the connection can be used to execute SQL statements.</value>
+ </data>
<data name="SqlParameter_UnsupportedTVPOutputParameter" xml:space="preserve">
<value>ParameterDirection '{0}' specified for parameter '{1}' is not supported. Table-valued parameters only support ParameterDirection.Input.</value>
</data>
@@ -688,6 +706,12 @@
<data name="SQL_EnumeratedRecordFieldCountChanged" xml:space="preserve">
<value>Number of fields in record '{0}' does not match the number in the original record.</value>
</data>
+ <data name="GT_Disabled" xml:space="preserve">
+ <value>Global Transactions are not enabled for this Azure SQL Database. Please contact Azure SQL Database support for assistance.</value>
+ </data>
+ <data name="SQL_UnknownSysTxIsolationLevel" xml:space="preserve">
+ <value>Unrecognized System.Transactions.IsolationLevel enumeration value: {0}.</value>
+ </data>
<data name="SQLNotify_AlreadyHasCommand" xml:space="preserve">
<value>This SqlCommand object is already associated with another SqlDependency object.</value>
</data>
@@ -1106,28 +1130,28 @@
<value>The size of column '{0}' is not supported. The size is {1}.</value>
</data>
<data name="MDF_InvalidXmlInvalidValue" xml:space="preserve">
- <value>The metadata XML is invalid. The {1} column of the {0} collection must contain a non-empty string.</value>
+ <value>The metadata XML is invalid. The {1} column of the {0} collection must contain a non-empty string.</value>
</data>
<data name="MDF_CollectionNameISNotUnique" xml:space="preserve">
- <value>There are multiple collections named '{0}'.</value>
+ <value>There are multiple collections named '{0}'.</value>
</data>
<data name="MDF_InvalidXmlMissingColumn" xml:space="preserve">
- <value>The metadata XML is invalid. The {0} collection must contain a {1} column and it must be a string column.</value>
+ <value>The metadata XML is invalid. The {0} collection must contain a {1} column and it must be a string column.</value>
</data>
<data name="MDF_InvalidXml" xml:space="preserve">
- <value>The metadata XML is invalid.</value>
+ <value>The metadata XML is invalid.</value>
</data>
<data name="MDF_NoColumns" xml:space="preserve">
- <value>The schema table contains no columns.</value>
+ <value>The schema table contains no columns.</value>
</data>
<data name="MDF_QueryFailed" xml:space="preserve">
- <value>Unable to build the '{0}' collection because execution of the SQL query failed. See the inner exception for details.</value>
+ <value>Unable to build the '{0}' collection because execution of the SQL query failed. See the inner exception for details.</value>
</data>
<data name="MDF_TooManyRestrictions" xml:space="preserve">
- <value>More restrictions were provided than the requested schema ('{0}') supports.</value>
+ <value>More restrictions were provided than the requested schema ('{0}') supports.</value>
</data>
<data name="MDF_DataTableDoesNotExist" xml:space="preserve">
- <value>The collection '{0}' is missing from the metadata XML.</value>
+ <value>The collection '{0}' is missing from the metadata XML.</value>
</data>
<data name="MDF_UndefinedCollection" xml:space="preserve">
<value>The requested collection ({0}) is not defined.</value>
@@ -1156,4 +1180,4 @@
<data name="AmbientTransactionsNotSupported" xml:space="preserve">
<value>Enlisting in Ambient transactions is not supported.</value>
</data>
-</root>
+</root> \ No newline at end of file
diff --git a/src/System.Data.SqlClient/src/System.Data.SqlClient.csproj b/src/System.Data.SqlClient/src/System.Data.SqlClient.csproj
index 5cd48d5ee1..7e41d3ae5c 100644
--- a/src/System.Data.SqlClient/src/System.Data.SqlClient.csproj
+++ b/src/System.Data.SqlClient/src/System.Data.SqlClient.csproj
@@ -125,6 +125,7 @@
<Compile Include="System\Data\SqlClient\SqlDependency.cs" />
<Compile Include="System\Data\SqlClient\SqlDependencyListener.cs" />
<Compile Include="System\Data\SqlClient\SqlDependencyUtils.cs" />
+ <Compile Include="System\Data\SqlClient\SqlDelegatedTransaction.cs" />
<Compile Include="System\Data\SqlClient\SqlEnums.cs" />
<Compile Include="System\Data\SqlClient\SqlError.cs" />
<Compile Include="System\Data\SqlClient\SqlErrorCollection.cs" />
@@ -189,6 +190,7 @@
<Compile Include="System\Data\SqlClient\SNI\SspiClientContextStatus.cs" />
<Compile Include="System\Data\SqlClient\SNI\SSRP.cs" />
<Compile Include="System\Data\SqlClient\TdsParserStateObjectManaged.cs" />
+ <Compile Include="Interop\SNINativeMethodWrapper.Common.cs" />
</ItemGroup>
<!-- Manage the SNI toggle for Windows netstandard and UWP -->
<ItemGroup Condition="'$(TargetGroup)' == 'netstandard' AND '$(TargetsWindows)' == 'true'">
@@ -196,15 +198,22 @@
</ItemGroup>
<ItemGroup Condition="'$(TargetGroup)' == 'uap'">
<Compile Include="System\Data\SqlClient\TdsParserStateObjectFactory.Managed.cs" />
+ <Compile Include="System\Data\SqlClient\LocalDBAPI.uap.cs" />
+ <Compile Include="System\Data\ProviderBase\DbConnectionPoolIdentity.Unix.cs" />
+ <Compile Include="System\Data\SqlClient\TdsParser.Unix.cs" />
</ItemGroup>
- <ItemGroup Condition=" '$(TargetsWindows)' == 'true' And '$(IsPartialFacadeAssembly)' != 'true' ">
- <Compile Include="System\Data\ProviderBase\DbConnectionPoolIdentity.Windows.cs" />
+ <!-- Assets needed on Windows but should be avoided on UAP to avoid sni.dll -->
+ <ItemGroup Condition=" '$(TargetsWindows)' == 'true' And '$(IsPartialFacadeAssembly)' != 'true' and '$(TargetGroup)' != 'uap' ">
+ <Compile Include="System\Data\SqlClient\TdsParserStateObjectNative.cs" />
<Compile Include="Interop\SNINativeMethodWrapper.Windows.cs" />
<Compile Include="System\Data\SqlClient\TdsParserSafeHandles.cs" />
- <Compile Include="System\Data\SqlClient\TdsParserStateObjectNative.cs" />
- <Compile Include="System\Data\SqlClient\TdsParser.Windows.cs" />
<Compile Include="System\Data\SqlClient\LocalDBAPI.Windows.cs" />
+ <Compile Include="System\Data\ProviderBase\DbConnectionPoolIdentity.Windows.cs" />
+ <Compile Include="System\Data\SqlClient\TdsParser.Windows.cs" />
+ </ItemGroup>
+ <ItemGroup Condition=" '$(TargetsWindows)' == 'true' And '$(IsPartialFacadeAssembly)' != 'true'">
<Compile Include="System\Data\SqlClient\SNI\LocalDB.Windows.cs" />
+ <Compile Include="System\Data\SqlClient\LocalDBAPI.Common.cs" />
<Compile Include="$(CommonPath)\Interop\Windows\kernel32\Interop.LoadLibraryEx.cs">
<Link>Common\Interop\Windows\kernel32\Interop.LoadLibraryEx.cs</Link>
</Compile>
@@ -430,8 +439,8 @@
<Reference Include="System.Diagnostics.Tracing" />
</ItemGroup>
<ItemGroup Condition="'$(OSGroup)' != 'AnyOS' AND '$(TargetGroup)' == 'uap'">
- <Reference Include="System.Transactions.Local" />
- <Reference Include="System.Collections.NonGeneric" />
+ <Reference Include="System.Transactions.Local" />
+ <Reference Include="System.Collections.NonGeneric" />
</ItemGroup>
<ItemGroup Condition="'$(TargetGroup)' == 'netfx'">
<Reference Include="mscorlib" />
diff --git a/src/System.Data.SqlClient/src/System/Data/Common/AdapterUtil.SqlClient.cs b/src/System.Data.SqlClient/src/System/Data/Common/AdapterUtil.SqlClient.cs
index 63990dc4e8..73f5e075cc 100644
--- a/src/System.Data.SqlClient/src/System/Data/Common/AdapterUtil.SqlClient.cs
+++ b/src/System.Data.SqlClient/src/System/Data/Common/AdapterUtil.SqlClient.cs
@@ -312,7 +312,7 @@ namespace System.Data.Common
return InvalidOperation(SR.GetString(SR.ADP_NonSequentialColumnAccess, badCol.ToString(CultureInfo.InvariantCulture), currCol.ToString(CultureInfo.InvariantCulture)));
}
- static internal Exception InvalidXmlInvalidValue(string collectionName, string columnName)
+ internal static Exception InvalidXmlInvalidValue(string collectionName, string columnName)
{
return Argument(SR.GetString(SR.MDF_InvalidXmlInvalidValue, collectionName, columnName));
}
@@ -395,6 +395,14 @@ namespace System.Data.Common
{
return InvalidOperation(SR.GetString(SR.ADP_ConnectionAlreadyOpen, ADP.ConnectionStateMsg(state)));
}
+ internal static Exception TransactionPresent()
+ {
+ return InvalidOperation(SR.GetString(SR.ADP_TransactionPresent));
+ }
+ internal static Exception LocalTransactionPresent()
+ {
+ return InvalidOperation(SR.GetString(SR.ADP_LocalTransactionPresent));
+ }
internal static Exception OpenConnectionPropertySet(string property, ConnectionState state)
{
return InvalidOperation(SR.GetString(SR.ADP_OpenConnectionPropertySet, property, ADP.ConnectionStateMsg(state)));
@@ -769,7 +777,7 @@ namespace System.Data.Common
return false;
}
- static internal ArgumentOutOfRangeException InvalidDataRowVersion(DataRowVersion value)
+ internal static ArgumentOutOfRangeException InvalidDataRowVersion(DataRowVersion value)
{
#if DEBUG
switch (value)
@@ -897,5 +905,13 @@ namespace System.Data.Common
{
return InvalidOperation(SR.GetString(SR.ADP_NoStoredProcedureExists, sproc));
}
+
+ //
+ // DbProviderException
+ //
+ internal static InvalidOperationException TransactionCompletedButNotDisposed()
+ {
+ return Provider(SR.GetString(SR.ADP_TransactionCompletedButNotDisposed));
+ }
}
} \ No newline at end of file
diff --git a/src/System.Data.SqlClient/src/System/Data/Common/DbConnectionStringCommon.cs b/src/System.Data.SqlClient/src/System/Data/Common/DbConnectionStringCommon.cs
index e9a7ed8345..1f7e557857 100644
--- a/src/System.Data.SqlClient/src/System/Data/Common/DbConnectionStringCommon.cs
+++ b/src/System.Data.SqlClient/src/System/Data/Common/DbConnectionStringCommon.cs
@@ -227,8 +227,7 @@ namespace System.Data.Common
internal static partial class DbConnectionStringDefaults
{
// all
- // internal const string NamedConnection = "";
-
+ // internal const string NamedConnection = "";
// SqlClient
internal const ApplicationIntent ApplicationIntent = System.Data.SqlClient.ApplicationIntent.ReadWrite;
@@ -266,8 +265,7 @@ namespace System.Data.Common
internal static partial class DbConnectionStringKeywords
{
// all
- // internal const string NamedConnection = "Named Connection";
-
+ // internal const string NamedConnection = "Named Connection";
// SqlClient
internal const string ApplicationIntent = "ApplicationIntent";
diff --git a/src/System.Data.SqlClient/src/System/Data/ProviderBase/DbConnectionClosed.cs b/src/System.Data.SqlClient/src/System/Data/ProviderBase/DbConnectionClosed.cs
index a4d8904097..3faa50d468 100644
--- a/src/System.Data.SqlClient/src/System/Data/ProviderBase/DbConnectionClosed.cs
+++ b/src/System.Data.SqlClient/src/System/Data/ProviderBase/DbConnectionClosed.cs
@@ -9,6 +9,7 @@
using System.Data.Common;
using System.Diagnostics;
using System.Threading.Tasks;
+using System.Transactions;
namespace System.Data.ProviderBase
@@ -20,7 +21,7 @@ namespace System.Data.ProviderBase
{
}
- override public string ServerVersion
+ public override string ServerVersion
{
get
{
@@ -28,17 +29,17 @@ namespace System.Data.ProviderBase
}
}
- override protected void Activate()
+ protected override void Activate(Transaction transaction)
{
throw ADP.ClosedConnectionError();
}
- override public DbTransaction BeginTransaction(IsolationLevel il)
+ public override DbTransaction BeginTransaction(IsolationLevel il)
{
throw ADP.ClosedConnectionError();
}
- override public void ChangeDatabase(string database)
+ public override void ChangeDatabase(string database)
{
throw ADP.ClosedConnectionError();
}
@@ -48,11 +49,15 @@ namespace System.Data.ProviderBase
// not much to do here...
}
- override protected void Deactivate()
+ protected override void Deactivate()
{
throw ADP.ClosedConnectionError();
}
+ public override void EnlistTransaction(Transaction transaction)
+ {
+ throw ADP.ClosedConnectionError();
+ }
protected override DbReferenceCollection CreateReferenceCollection()
{
diff --git a/src/System.Data.SqlClient/src/System/Data/ProviderBase/DbConnectionFactory.cs b/src/System.Data.SqlClient/src/System/Data/ProviderBase/DbConnectionFactory.cs
index 884ebe22c6..f11157e53c 100644
--- a/src/System.Data.SqlClient/src/System/Data/ProviderBase/DbConnectionFactory.cs
+++ b/src/System.Data.SqlClient/src/System/Data/ProviderBase/DbConnectionFactory.cs
@@ -20,7 +20,6 @@ namespace System.Data.ProviderBase
private readonly List<DbConnectionPool> _poolsToRelease;
private readonly List<DbConnectionPoolGroup> _poolGroupsToRelease;
private readonly Timer _pruningTimer;
-
private const int PruningDueTime = 4 * 60 * 1000; // 4 minutes
private const int PruningPeriod = 30 * 1000; // thirty seconds
@@ -219,13 +218,22 @@ namespace System.Data.ProviderBase
// If it is a new slot or a completed task, this continuation will start right away.
newTask = s_pendingOpenNonPooled[idx].ContinueWith((_) =>
{
- var newConnection = CreateNonPooledConnection(owningConnection, poolGroup, userOptions);
- if ((oldConnection != null) && (oldConnection.State == ConnectionState.Open))
+ Transactions.Transaction originalTransaction = ADP.GetCurrentTransaction();
+ try
+ {
+ ADP.SetCurrentTransaction(retry.Task.AsyncState as Transactions.Transaction);
+ var newConnection = CreateNonPooledConnection(owningConnection, poolGroup, userOptions);
+ if ((oldConnection != null) && (oldConnection.State == ConnectionState.Open))
+ {
+ oldConnection.PrepareForReplaceConnection();
+ oldConnection.Dispose();
+ }
+ return newConnection;
+ }
+ finally
{
- oldConnection.PrepareForReplaceConnection();
- oldConnection.Dispose();
+ ADP.SetCurrentTransaction(originalTransaction);
}
- return newConnection;
}, cancellationTokenSource.Token, TaskContinuationOptions.LongRunning, TaskScheduler.Default);
// Place this new task in the slot so any future work will be queued behind it
diff --git a/src/System.Data.SqlClient/src/System/Data/ProviderBase/DbConnectionInternal.cs b/src/System.Data.SqlClient/src/System/Data/ProviderBase/DbConnectionInternal.cs
index 167c504d4c..3b0391740c 100644
--- a/src/System.Data.SqlClient/src/System/Data/ProviderBase/DbConnectionInternal.cs
+++ b/src/System.Data.SqlClient/src/System/Data/ProviderBase/DbConnectionInternal.cs
@@ -11,6 +11,7 @@ using System.Data.SqlClient;
using System.Diagnostics;
using System.Threading;
using System.Threading.Tasks;
+using System.Transactions;
namespace System.Data.ProviderBase
@@ -32,9 +33,17 @@ namespace System.Data.ProviderBase
private bool _connectionIsDoomed; // true when the connection should no longer be used.
private bool _cannotBePooled; // true when the connection should no longer be pooled.
+ private bool _isInStasis;
private DateTime _createTime; // when the connection was created.
+ private Transaction _enlistedTransaction; // [usage must be thread-safe] the transaction that we're enlisted in, either manually or automatically
+
+ // _enlistedTransaction is a clone, so that transaction information can be queried even if the original transaction object is disposed.
+ // However, there are times when we need to know if the original transaction object was disposed, so we keep a reference to it here.
+ // This field should only be assigned a value at the same time _enlistedTransaction is updated.
+ // Also, this reference should not be disposed, since we aren't taking ownership of it.
+ private Transaction _enlistedTransactionOriginal;
#if DEBUG
private int _activateCount; // debug only counter to verify activate/deactivates are in sync.
@@ -69,6 +78,164 @@ namespace System.Data.ProviderBase
}
}
+ protected internal Transaction EnlistedTransaction
+ {
+ get
+ {
+ return _enlistedTransaction;
+ }
+ set
+ {
+ Transaction currentEnlistedTransaction = _enlistedTransaction;
+ if (((null == currentEnlistedTransaction) && (null != value))
+ || ((null != currentEnlistedTransaction) && !currentEnlistedTransaction.Equals(value)))
+ { // WebData 20000024
+
+ // Pay attention to the order here:
+ // 1) defect from any notifications
+ // 2) replace the transaction
+ // 3) re-enlist in notifications for the new transaction
+
+ // SQLBUDT #230558 we need to use a clone of the transaction
+ // when we store it, or we'll end up keeping it past the
+ // duration of the using block of the TransactionScope
+ Transaction valueClone = null;
+ Transaction previousTransactionClone = null;
+ try
+ {
+ if (null != value)
+ {
+ valueClone = value.Clone();
+ }
+
+ // NOTE: rather than take locks around several potential round-
+ // trips to the server, and/or virtual function calls, we simply
+ // presume that you aren't doing something illegal from multiple
+ // threads, and check once we get around to finalizing things
+ // inside a lock.
+
+ lock (this)
+ {
+ // NOTE: There is still a race condition here, when we are
+ // called from EnlistTransaction (which cannot re-enlist)
+ // instead of EnlistDistributedTransaction (which can),
+ // however this should have been handled by the outer
+ // connection which checks to ensure that it's OK. The
+ // only case where we have the race condition is multiple
+ // concurrent enlist requests to the same connection, which
+ // is a bit out of line with something we should have to
+ // support.
+
+ // enlisted transaction can be nullified in Dispose call without lock
+ previousTransactionClone = Interlocked.Exchange(ref _enlistedTransaction, valueClone);
+ _enlistedTransactionOriginal = value;
+ value = valueClone;
+ valueClone = null; // we've stored it, don't dispose it.
+ }
+ }
+ finally
+ {
+ // we really need to dispose our clones; they may have
+ // native resources and GC may not happen soon enough.
+ // VSDevDiv 479564: don't dispose if still holding reference in _enlistedTransaction
+ if (null != previousTransactionClone &&
+ !Object.ReferenceEquals(previousTransactionClone, _enlistedTransaction))
+ {
+ previousTransactionClone.Dispose();
+ }
+ if (null != valueClone && !Object.ReferenceEquals(valueClone, _enlistedTransaction))
+ {
+ valueClone.Dispose();
+ }
+ }
+
+ // I don't believe that we need to lock to protect the actual
+ // enlistment in the transaction; it would only protect us
+ // against multiple concurrent calls to enlist, which really
+ // isn't supported anyway.
+
+ if (null != value)
+ {
+ TransactionOutcomeEnlist(value);
+ }
+ }
+ }
+ }
+
+ /// <summary>
+ /// Get boolean value that indicates whether the enlisted transaction has been disposed.
+ /// </summary>
+ /// <value>
+ /// True if there is an enlisted transaction, and it has been diposed.
+ /// False if there is an enlisted transaction that has not been disposed, or if the transaction reference is null.
+ /// </value>
+ /// <remarks>
+ /// This method must be called while holding a lock on the DbConnectionInternal instance.
+ /// </remarks>
+ protected bool EnlistedTransactionDisposed
+ {
+ get
+ {
+ // Until the Transaction.Disposed property is public it is necessary to access a member
+ // that throws if the object is disposed to determine if in fact the transaction is disposed.
+ try
+ {
+ bool disposed;
+
+ Transaction currentEnlistedTransactionOriginal = _enlistedTransactionOriginal;
+ if (currentEnlistedTransactionOriginal != null)
+ {
+ disposed = currentEnlistedTransactionOriginal.TransactionInformation == null;
+ }
+ else
+ {
+ // Don't expect to get here in the general case,
+ // Since this getter is called by CheckEnlistedTransactionBinding
+ // after checking for a non-null enlisted transaction (and it does so under lock).
+ disposed = false;
+ }
+
+ return disposed;
+ }
+ catch (ObjectDisposedException)
+ {
+ return true;
+ }
+ }
+ }
+
+ internal bool IsTxRootWaitingForTxEnd
+ {
+ get
+ {
+ return _isInStasis;
+ }
+ }
+
+ virtual protected bool UnbindOnTransactionCompletion
+ {
+ get
+ {
+ return true;
+ }
+ }
+
+ // Is this a connection that must be put in stasis (or is already in stasis) pending the end of it's transaction?
+ virtual protected internal bool IsNonPoolableTransactionRoot
+ {
+ get
+ {
+ return false; // if you want to have delegated transactions that are non-poolable, you better override this...
+ }
+ }
+
+ virtual internal bool IsTransactionRoot
+ {
+ get
+ {
+ return false; // if you want to have delegated transactions, you better override this...
+ }
+ }
protected internal bool IsConnectionDoomed
{
@@ -138,6 +305,13 @@ namespace System.Data.ProviderBase
}
}
+ virtual protected bool ReadyToPrepareTransaction
+ {
+ get
+ {
+ return true;
+ }
+ }
protected internal DbReferenceCollection ReferenceCollection
{
@@ -177,20 +351,14 @@ namespace System.Data.ProviderBase
}
}
- abstract protected void Activate();
+ abstract protected void Activate(Transaction transaction);
- internal void ActivateConnection()
+ internal void ActivateConnection(Transaction transaction)
{
// Internal method called from the connection pooler so we don't expose
// the Activate method publicly.
-#if DEBUG
-
- int activateCount = Interlocked.Increment(ref _activateCount);
- Debug.Assert(1 == activateCount, "activated multiple times?");
-#endif // DEBUG
-
- Activate();
+ Activate(transaction);
}
internal void AddWeakReference(object value, int tag)
@@ -272,6 +440,8 @@ namespace System.Data.ProviderBase
DbConnectionPool connectionPool = Pool;
+ // Detach from enlisted transactions that are no longer active on close
+ DetachCurrentTransactionIfEnded();
// The singleton closed classes won't have owners and
// connection pools, and we won't want to put them back
@@ -296,7 +466,14 @@ namespace System.Data.ProviderBase
// certain.
_owningObject.Target = null;
- Dispose();
+ if (IsTransactionRoot)
+ {
+ SetInStasis();
+ }
+ else
+ {
+ Dispose();
+ }
}
}
finally
@@ -344,7 +521,6 @@ namespace System.Data.ProviderBase
#if DEBUG
int activateCount = Interlocked.Decrement(ref _activateCount);
- Debug.Assert(0 == activateCount, "activated multiple times?");
#endif // DEBUG
@@ -362,11 +538,71 @@ namespace System.Data.ProviderBase
Deactivate();
}
+ virtual internal void DelegatedTransactionEnded()
+ {
+ // Called by System.Transactions when the delegated transaction has
+ // completed. We need to make closed connections that are in stasis
+ // available again, or disposed closed/leaked non-pooled connections.
+
+ // IMPORTANT NOTE: You must have taken a lock on the object before
+ // you call this method to prevent race conditions with Clear and
+ // ReclaimEmancipatedObjects.
+
+
+ if (1 == _pooledCount)
+ {
+ // When _pooledCount is 1, it indicates a closed, pooled,
+ // connection so it is ready to put back into the pool for
+ // general use.
+
+ TerminateStasis(true);
+
+ Deactivate(); // call it one more time just in case
+
+ DbConnectionPool pool = Pool;
+
+ if (null == pool)
+ {
+ throw ADP.InternalError(ADP.InternalErrorCode.PooledObjectWithoutPool); // pooled connection does not have a pool
+ }
+ pool.PutObjectFromTransactedPool(this);
+ }
+ else if (-1 == _pooledCount && !_owningObject.IsAlive)
+ {
+ // When _pooledCount is -1 and the owning object no longer exists,
+ // it indicates a closed (or leaked), non-pooled connection so
+ // it is safe to dispose.
+
+ TerminateStasis(false);
+
+ Deactivate(); // call it one more time just in case
+
+ // it's a non-pooled connection, we need to dispose of it
+ // once and for all, or the server will have fits about us
+ // leaving connections open until the client-side GC kicks
+ // in.
+ Dispose();
+ }
+ // When _pooledCount is 0, the connection is a pooled connection
+ // that is either open (if the owning object is alive) or leaked (if
+ // the owning object is not alive) In either case, we can't muck
+ // with the connection here.
+ }
public virtual void Dispose()
{
_connectionPool = null;
_connectionIsDoomed = true;
+ _enlistedTransactionOriginal = null; // should not be disposed
+
+ // Dispose of the _enlistedTransaction since it is a clone
+ // of the original reference.
+ // VSDD 780271 - _enlistedTransaction can be changed by another thread (TX end event)
+ Transaction enlistedTransaction = Interlocked.Exchange(ref _enlistedTransaction, null);
+ if (enlistedTransaction != null)
+ {
+ enlistedTransaction.Dispose();
+ }
}
protected internal void DoNotPoolThisConnection()
@@ -380,6 +616,17 @@ namespace System.Data.ProviderBase
_connectionIsDoomed = true;
}
+ abstract public void EnlistTransaction(Transaction transaction);
+
+ protected internal virtual DataTable GetSchema(DbConnectionFactory factory, DbConnectionPoolGroup poolGroup, DbConnection outerConnection, string collectionName, string[] restrictions)
+ {
+ Debug.Assert(outerConnection != null, "outerConnection may not be null.");
+
+ DbMetaDataFactory metaDataFactory = factory.GetMetaDataFactory(poolGroup, this);
+ Debug.Assert(metaDataFactory != null, "metaDataFactory may not be null.");
+
+ return metaDataFactory.GetSchema(outerConnection, collectionName, restrictions);
+ }
internal void MakeNonPooledObject(object owningObject)
{
@@ -539,6 +786,98 @@ namespace System.Data.ProviderBase
}
}
+ // Cleanup connection's transaction-specific structures (currently used by Delegated transaction).
+ // This is a separate method because cleanup can be triggered in multiple ways for a delegated
+ // transaction.
+ virtual protected void CleanupTransactionOnCompletion(Transaction transaction)
+ {
+ }
+
+ internal void DetachCurrentTransactionIfEnded()
+ {
+ Transaction enlistedTransaction = EnlistedTransaction;
+ if (enlistedTransaction != null)
+ {
+ bool transactionIsDead;
+ try
+ {
+ transactionIsDead = (TransactionStatus.Active != enlistedTransaction.TransactionInformation.Status);
+ }
+ catch (TransactionException)
+ {
+ // If the transaction is being processed (i.e. is part way through a rollback\commit\etc then TransactionInformation.Status will throw an exception)
+ transactionIsDead = true;
+ }
+ if (transactionIsDead)
+ {
+ DetachTransaction(enlistedTransaction, true);
+ }
+ }
+ }
+
+ // Detach transaction from connection.
+ internal void DetachTransaction(Transaction transaction, bool isExplicitlyReleasing)
+ {
+ // potentially a multi-threaded event, so lock the connection to make sure we don't enlist in a new
+ // transaction between compare and assignment. No need to short circuit outside of lock, since failed comparisons should
+ // be the exception, not the rule.
+ lock (this)
+ {
+ // Detach if detach-on-end behavior, or if outer connection was closed
+ DbConnection owner = (DbConnection)Owner;
+ if (isExplicitlyReleasing || UnbindOnTransactionCompletion || null == owner)
+ {
+ Transaction currentEnlistedTransaction = _enlistedTransaction;
+ if (currentEnlistedTransaction != null && transaction.Equals(currentEnlistedTransaction))
+ {
+ EnlistedTransaction = null;
+
+ if (IsTxRootWaitingForTxEnd)
+ {
+ DelegatedTransactionEnded();
+ }
+ }
+ }
+ }
+ }
+
+ // Handle transaction detach, pool cleanup and other post-transaction cleanup tasks associated with
+ internal void CleanupConnectionOnTransactionCompletion(Transaction transaction)
+ {
+ DetachTransaction(transaction, false);
+
+ DbConnectionPool pool = Pool;
+ if (null != pool)
+ {
+ pool.TransactionEnded(transaction, this);
+ }
+ }
+
+ void TransactionCompletedEvent(object sender, TransactionEventArgs e)
+ {
+ Transaction transaction = e.Transaction;
+
+ CleanupTransactionOnCompletion(transaction);
+
+ CleanupConnectionOnTransactionCompletion(transaction);
+ }
+
+ // TODO: Review whether we need the unmanaged code permission when we have the new object model available.
+ // [SecurityPermission(SecurityAction.Assert, Flags = SecurityPermissionFlag.UnmanagedCode)]
+ private void TransactionOutcomeEnlist(Transaction transaction)
+ {
+ transaction.TransactionCompleted += new TransactionCompletedEventHandler(TransactionCompletedEvent);
+ }
+
+ internal void SetInStasis()
+ {
+ _isInStasis = true;
+ }
+
+ private void TerminateStasis(bool returningToPool)
+ {
+ _isInStasis = false;
+ }
/// <summary>
/// When overridden in a derived class, will check if the underlying connection is still actually alive
@@ -550,15 +889,5 @@ namespace System.Data.ProviderBase
{
return true;
}
-
- protected internal virtual DataTable GetSchema(DbConnectionFactory factory, DbConnectionPoolGroup poolGroup, DbConnection outerConnection, string collectionName, string[] restrictions)
- {
- Debug.Assert(outerConnection != null, "outerConnection may not be null.");
-
- DbMetaDataFactory metaDataFactory = factory.GetMetaDataFactory(poolGroup, this);
- Debug.Assert(metaDataFactory != null, "metaDataFactory may not be null.");
-
- return metaDataFactory.GetSchema(outerConnection, collectionName, restrictions);
- }
}
}
diff --git a/src/System.Data.SqlClient/src/System/Data/ProviderBase/DbConnectionPool.cs b/src/System.Data.SqlClient/src/System/Data/ProviderBase/DbConnectionPool.cs
index 9c1b71122f..99830b6370 100644
--- a/src/System.Data.SqlClient/src/System/Data/ProviderBase/DbConnectionPool.cs
+++ b/src/System.Data.SqlClient/src/System/Data/ProviderBase/DbConnectionPool.cs
@@ -12,6 +12,7 @@ using System.Diagnostics;
using System.Threading;
using System.Threading.Tasks;
using System.Collections.Concurrent;
+using System.Transactions;
namespace System.Data.ProviderBase
{
@@ -24,6 +25,25 @@ namespace System.Data.ProviderBase
ShuttingDown,
}
+ // This class is a way to stash our cloned Tx key for later disposal when it's no longer needed.
+ // We can't get at the key in the dictionary without enumerating entries, so we stash an extra
+ // copy as part of the value.
+ sealed private class TransactedConnectionList : List<DbConnectionInternal>
+ {
+ private Transaction _transaction;
+ internal TransactedConnectionList(int initialAllocation, Transaction tx) : base(initialAllocation)
+ {
+ _transaction = tx;
+ }
+
+ internal void Dispose()
+ {
+ if (null != _transaction)
+ {
+ _transaction.Dispose();
+ }
+ }
+ }
private sealed class PendingGetConnection
{
@@ -39,6 +59,229 @@ namespace System.Data.ProviderBase
public DbConnectionOptions UserOptions { get; private set; }
}
+ sealed private class TransactedConnectionPool
+ {
+ Dictionary<Transaction, TransactedConnectionList> _transactedCxns;
+
+ DbConnectionPool _pool;
+
+ private static int _objectTypeCount; // Bid counter
+ internal readonly int _objectID = System.Threading.Interlocked.Increment(ref _objectTypeCount);
+
+ internal TransactedConnectionPool(DbConnectionPool pool)
+ {
+ Debug.Assert(null != pool, "null pool?");
+
+ _pool = pool;
+ _transactedCxns = new Dictionary<Transaction, TransactedConnectionList>();
+ }
+
+ internal int ObjectID
+ {
+ get
+ {
+ return _objectID;
+ }
+ }
+
+ internal DbConnectionPool Pool
+ {
+ get
+ {
+ return _pool;
+ }
+ }
+
+ internal DbConnectionInternal GetTransactedObject(Transaction transaction)
+ {
+ Debug.Assert(null != transaction, "null transaction?");
+
+ DbConnectionInternal transactedObject = null;
+
+ TransactedConnectionList connections;
+ bool txnFound = false;
+
+ lock (_transactedCxns)
+ {
+ txnFound = _transactedCxns.TryGetValue(transaction, out connections);
+ }
+
+ // NOTE: GetTransactedObject is only used when AutoEnlist = True and the ambient transaction
+ // (Sys.Txns.Txn.Current) is still valid/non-null. This, in turn, means that we don't need
+ // to worry about a pending asynchronous TransactionCompletedEvent to trigger processing in
+ // TransactionEnded below and potentially wipe out the connections list underneath us. It
+ // is similarly alright if a pending addition to the connections list in PutTransactedObject
+ // below is not completed prior to the lock on the connections object here...getting a new
+ // connection is probably better than unnecessarily locking
+ if (txnFound)
+ {
+ Debug.Assert(connections != null);
+
+ // synchronize multi-threaded access with PutTransactedObject (TransactionEnded should
+ // not be a concern, see comments above)
+ lock (connections)
+ {
+ int i = connections.Count - 1;
+ if (0 <= i)
+ {
+ transactedObject = connections[i];
+ connections.RemoveAt(i);
+ }
+ }
+ }
+
+ return transactedObject;
+ }
+
+ internal void PutTransactedObject(Transaction transaction, DbConnectionInternal transactedObject)
+ {
+ Debug.Assert(null != transaction, "null transaction?");
+ Debug.Assert(null != transactedObject, "null transactedObject?");
+
+ TransactedConnectionList connections;
+ bool txnFound = false;
+
+ // NOTE: because TransactionEnded is an asynchronous notification, there's no guarantee
+ // around the order in which PutTransactionObject and TransactionEnded are called.
+
+ lock (_transactedCxns)
+ {
+ // Check if a transacted pool has been created for this transaction
+ if (txnFound = _transactedCxns.TryGetValue(transaction, out connections))
+ {
+ Debug.Assert(connections != null);
+
+ // synchronize multi-threaded access with GetTransactedObject
+ lock (connections)
+ {
+ Debug.Assert(0 > connections.IndexOf(transactedObject), "adding to pool a second time?");
+ connections.Add(transactedObject);
+ }
+ }
+ }
+
+ // CONSIDER: the following code is more complicated than it needs to be to avoid cloning the
+ // transaction and allocating memory within a lock. Is that complexity really necessary?
+ if (!txnFound)
+ {
+ // create the transacted pool, making sure to clone the associated transaction
+ // for use as a key in our internal dictionary of transactions and connections
+ Transaction transactionClone = null;
+ TransactedConnectionList newConnections = null;
+
+ try
+ {
+ transactionClone = transaction.Clone();
+ newConnections = new TransactedConnectionList(2, transactionClone); // start with only two connections in the list; most times we won't need that many.
+
+ lock (_transactedCxns)
+ {
+ // NOTE: in the interim between the locks on the transacted pool (this) during
+ // execution of this method, another thread (threadB) may have attempted to
+ // add a different connection to the transacted pool under the same
+ // transaction. As a result, threadB may have completed creating the
+ // transacted pool while threadA was processing the above instructions.
+ if (txnFound = _transactedCxns.TryGetValue(transaction, out connections))
+ {
+ Debug.Assert(connections != null);
+
+ // synchronize multi-threaded access with GetTransactedObject
+ lock (connections)
+ {
+ Debug.Assert(0 > connections.IndexOf(transactedObject), "adding to pool a second time?");
+ connections.Add(transactedObject);
+ }
+ }
+ else
+ {
+ // add the connection/transacted object to the list
+ newConnections.Add(transactedObject);
+
+ _transactedCxns.Add(transactionClone, newConnections);
+ transactionClone = null; // we've used it -- don't throw it or the TransactedConnectionList that references it away.
+ }
+ }
+ }
+ finally
+ {
+ if (null != transactionClone)
+ {
+ if (newConnections != null)
+ {
+ // another thread created the transaction pool and thus the new
+ // TransactedConnectionList was not used, so dispose of it and
+ // the transaction clone that it incorporates.
+ newConnections.Dispose();
+ }
+ else
+ {
+ // memory allocation for newConnections failed...clean up unused transactionClone
+ transactionClone.Dispose();
+ }
+ }
+ }
+ }
+ }
+
+ internal void TransactionEnded(Transaction transaction, DbConnectionInternal transactedObject)
+ {
+ TransactedConnectionList connections;
+ int entry = -1;
+
+ // NOTE: because TransactionEnded is an asynchronous notification, there's no guarantee
+ // around the order in which PutTransactionObject and TransactionEnded are called. As
+ // such, it is possible that the transaction does not yet have a pool created.
+
+ // TODO: is this a plausible and/or likely scenario? Do we need to have a mechanism to ensure
+ // TODO: that the pending creation of a transacted pool for this transaction is aborted when
+ // TODO: PutTransactedObject finally gets some CPU time?
+
+ lock (_transactedCxns)
+ {
+ if (_transactedCxns.TryGetValue(transaction, out connections))
+ {
+ Debug.Assert(connections != null);
+
+ bool shouldDisposeConnections = false;
+
+ // Lock connections to avoid conflict with GetTransactionObject
+ lock (connections)
+ {
+ entry = connections.IndexOf(transactedObject);
+
+ if (entry >= 0)
+ {
+ connections.RemoveAt(entry);
+ }
+
+ // Once we've completed all the ended notifications, we can
+ // safely remove the list from the transacted pool.
+ if (0 >= connections.Count)
+ {
+ _transactedCxns.Remove(transaction);
+
+ // we really need to dispose our connection list; it may have
+ // native resources via the tx and GC may not happen soon enough.
+ shouldDisposeConnections = true;
+ }
+ }
+
+ if (shouldDisposeConnections)
+ {
+ connections.Dispose();
+ }
+ }
+ }
+
+ // If (and only if) we found the connection in the list of
+ // connections, we'll put it back...
+ if (0 <= entry)
+ {
+ Pool.PutObjectFromTransactedPool(transactedObject);
+ }
+ }
+
+ }
private sealed class PoolWaitHandles
{
@@ -130,6 +373,7 @@ namespace System.Data.ProviderBase
private Timer _cleanupTimer;
+ private readonly TransactedConnectionPool _transactedConnectionPool;
private readonly List<DbConnectionInternal> _objectList;
private int _totalObjects;
@@ -169,6 +413,11 @@ namespace System.Data.ProviderBase
_objectList = new List<DbConnectionInternal>(MaxPoolSize);
+ if (ADP.IsPlatformNT5)
+ {
+ _transactedConnectionPool = new TransactedConnectionPool(this);
+ }
+
_poolCreateRequest = new WaitCallback(PoolCreateRequest); // used by CleanupCallback
_state = State.Running;
@@ -196,6 +445,10 @@ namespace System.Data.ProviderBase
get { return _errorOccurred; }
}
+ private bool HasTransactionAffinity
+ {
+ get { return PoolGroupOptions.HasTransactionAffinity; }
+ }
internal TimeSpan LoadBalanceTimeout
{
@@ -245,7 +498,6 @@ namespace System.Data.ProviderBase
get { return PoolGroupOptions.MinPoolSize; }
}
-
internal DbConnectionPoolGroup PoolGroup
{
get { return _connectionPoolGroup; }
@@ -306,7 +558,36 @@ namespace System.Data.ProviderBase
Debug.Assert(obj != null, "null connection is not expected");
// If we obtained one from the old stack, destroy it.
- DestroyObject(obj);
+ // Transaction roots must survive even aging out (TxEnd event will clean them up).
+ bool shouldDestroy = true;
+ lock (obj)
+ { // Lock to prevent race condition window between IsTransactionRoot and shouldDestroy assignment
+ if (obj.IsTransactionRoot)
+ {
+ shouldDestroy = false;
+ }
+ }
+
+ // !!!!!!!!!! WARNING !!!!!!!!!!!!!
+ // ONLY touch obj after lock release if shouldDestroy is false!!! Otherwise, it may be destroyed
+ // by transaction-end thread!
+
+ // Note that there is a minor race condition between this task and the transaction end event, if the latter runs
+ // between the lock above and the SetInStasis call below. The reslult is that the stasis counter may be
+ // incremented without a corresponding decrement (the transaction end task is normally expected
+ // to decrement, but will only do so if the stasis flag is set when it runs). I've minimized the size
+ // of the window, but we aren't totally eliminating it due to SetInStasis needing to do bid tracing, which
+ // we don't want to do under this lock, if possible. It should be possible to eliminate this race condition with
+ // more substantial re-architecture of the pool, but we don't have the time to do that work for the current release.
+
+ if (shouldDestroy)
+ {
+ DestroyObject(obj);
+ }
+ else
+ {
+ obj.SetInStasis();
+ }
}
else
{
@@ -334,8 +615,6 @@ namespace System.Data.ProviderBase
break;
Debug.Assert(obj != null, "null connection is not expected");
-
-
Debug.Assert(!obj.IsEmancipated, "pooled object not in pool");
Debug.Assert(obj.CanBePooled, "pooled object is not poolable");
@@ -484,6 +763,7 @@ namespace System.Data.ProviderBase
bool returnToGeneralPool = false;
bool destroyObject = false;
+ bool rootTxn = false;
if (obj.IsConnectionDoomed)
{
@@ -506,26 +786,78 @@ namespace System.Data.ProviderBase
if (_state == State.ShuttingDown)
{
- // connection is being closed and the pool has been marked as shutting
- // down, so destroy this object.
- destroyObject = true;
+ if (obj.IsTransactionRoot)
+ {
+ // SQLHotfix# 50003503 - connections that are affiliated with a
+ // root transaction and that also happen to be in a connection
+ // pool that is being shutdown need to be put in stasis so that
+ // the root transaction isn't effectively orphaned with no
+ // means to promote itself to a full delegated transaction or
+ // Commit or Rollback
+ obj.SetInStasis();
+ rootTxn = true;
+ }
+ else
+ {
+ // connection is being closed and the pool has been marked as shutting
+ // down, so destroy this object.
+ destroyObject = true;
+ }
}
else
{
- if (obj.CanBePooled)
+ if (obj.IsNonPoolableTransactionRoot)
+ {
+ obj.SetInStasis();
+ rootTxn = true;
+ }
+ else if (obj.CanBePooled)
{
// We must put this connection into the transacted pool
// while inside a lock to prevent a race condition with
// the transaction asynchronously completing on a second
// thread.
- // return to general pool
- returnToGeneralPool = true;
+ Transaction transaction = obj.EnlistedTransaction;
+ if (null != transaction)
+ {
+ // NOTE: we're not locking on _state, so it's possible that its
+ // value could change between the conditional check and here.
+ // Although perhaps not ideal, this is OK because the
+ // DelegatedTransactionEnded event will clean up the
+ // connection appropriately regardless of the pool state.
+ Debug.Assert(_transactedConnectionPool != null, "Transacted connection pool was not expected to be null.");
+ _transactedConnectionPool.PutTransactedObject(transaction, obj);
+ rootTxn = true;
+ }
+ else
+ {
+ // return to general pool
+ returnToGeneralPool = true;
+ }
}
else
{
- // object is not fit for reuse -- just dispose of it
- destroyObject = true;
+ if (obj.IsTransactionRoot && !obj.IsConnectionDoomed)
+ {
+ // SQLHotfix# 50003503 - if the object cannot be pooled but is a transaction
+ // root, then we must have hit one of two race conditions:
+ // 1) PruneConnectionPoolGroups shutdown the pool and marked this connection
+ // as non-poolable while we were processing within this lock
+ // 2) The LoadBalancingTimeout expired on this connection and marked this
+ // connection as DoNotPool.
+ //
+ // This connection needs to be put in stasis so that the root transaction isn't
+ // effectively orphaned with no means to promote itself to a full delegated
+ // transaction or Commit or Rollback
+ obj.SetInStasis();
+ rootTxn = true;
+ }
+ else
+ {
+ // object is not fit for reuse -- just dispose of it
+ destroyObject = true;
+ }
}
}
}
@@ -549,8 +881,7 @@ namespace System.Data.ProviderBase
// postcondition
// ensure that the connection was processed
- Debug.Assert(
- returnToGeneralPool == true || destroyObject == true);
+ Debug.Assert(rootTxn == true || returnToGeneralPool == true || destroyObject == true);
}
internal void DestroyObject(DbConnectionInternal obj)
@@ -560,18 +891,18 @@ namespace System.Data.ProviderBase
// we simply leave it alone; when the transaction completes, it will
// come back through PutObjectFromTransactedPool, which will call us
// again.
- bool removed = false;
- lock (_objectList)
+ if (!obj.IsTxRootWaitingForTxEnd)
{
- removed = _objectList.Remove(obj);
- Debug.Assert(removed, "attempt to DestroyObject not in list");
- _totalObjects = _objectList.Count;
- }
+ bool removed = false;
+ lock (_objectList)
+ {
+ removed = _objectList.Remove(obj);
+ Debug.Assert(removed, "attempt to DestroyObject not in list");
+ _totalObjects = _objectList.Count;
+ }
- if (removed)
- {
+ obj.Dispose();
}
- obj.Dispose();
}
private void ErrorCallback(Object state)
@@ -650,6 +981,7 @@ namespace System.Data.ProviderBase
{
bool allowCreate = true;
bool onlyOneCheckConnection = false;
+ ADP.SetCurrentTransaction(next.Completion.Task.AsyncState as Transactions.Transaction);
timeout = !TryGetConnection(next.Owner, delay, allowCreate, onlyOneCheckConnection, next.UserOptions, out connection);
}
catch (Exception e)
@@ -742,6 +1074,15 @@ namespace System.Data.ProviderBase
private bool TryGetConnection(DbConnection owningObject, uint waitForMultipleObjectsTimeout, bool allowCreate, bool onlyOneCheckConnection, DbConnectionOptions userOptions, out DbConnectionInternal connection)
{
DbConnectionInternal obj = null;
+ Transaction transaction = null;
+
+ // If automatic transaction enlistment is required, then we try to
+ // get the connection from the transacted connection pool first.
+ if (HasTransactionAffinity)
+ {
+ obj = GetFromTransactedPool(out transaction);
+ }
+
if (null == obj)
{
Interlocked.Increment(ref _waitCount);
@@ -778,7 +1119,6 @@ namespace System.Data.ProviderBase
throw TryCloneCachedException();
case CREATION_HANDLE:
-
try
{
obj = UserCreateRequest(owningObject, userOptions);
@@ -870,14 +1210,14 @@ namespace System.Data.ProviderBase
if (null != obj)
{
- PrepareConnection(owningObject, obj);
+ PrepareConnection(owningObject, obj, transaction);
}
connection = obj;
return true;
}
- private void PrepareConnection(DbConnection owningObject, DbConnectionInternal obj)
+ private void PrepareConnection(DbConnection owningObject, DbConnectionInternal obj, Transaction transaction)
{
lock (obj)
{ // Protect against Clear and ReclaimEmancipatedObjects, which call IsEmancipated, which is affected by PrePush and PostPop
@@ -885,7 +1225,7 @@ namespace System.Data.ProviderBase
}
try
{
- obj.ActivateConnection();
+ obj.ActivateConnection(transaction);
}
catch
{
@@ -909,7 +1249,7 @@ namespace System.Data.ProviderBase
if (newConnection != null)
{
- PrepareConnection(owningObject, newConnection);
+ PrepareConnection(owningObject, newConnection, oldConnection.EnlistedTransaction);
oldConnection.PrepareForReplaceConnection();
oldConnection.DeactivateConnection();
oldConnection.Dispose();
@@ -949,6 +1289,39 @@ namespace System.Data.ProviderBase
return (obj);
}
+ private DbConnectionInternal GetFromTransactedPool(out Transaction transaction)
+ {
+ transaction = ADP.GetCurrentTransaction();
+ DbConnectionInternal obj = null;
+
+ if (null != transaction && null != _transactedConnectionPool)
+ {
+ obj = _transactedConnectionPool.GetTransactedObject(transaction);
+
+ if (null != obj)
+ {
+ if (obj.IsTransactionRoot)
+ {
+ try
+ {
+ obj.IsConnectionAlive(true);
+ }
+ catch
+ {
+ DestroyObject(obj);
+ throw;
+ }
+ }
+ else if (!obj.IsConnectionAlive())
+ {
+ DestroyObject(obj);
+ obj = null;
+ }
+ }
+ }
+ return obj;
+ }
+
private void PoolCreateRequest(object state)
{
// called by pooler to ensure pool requests are currently being satisfied -
@@ -1071,6 +1444,30 @@ namespace System.Data.ProviderBase
DeactivateObject(obj);
}
+ internal void PutObjectFromTransactedPool(DbConnectionInternal obj)
+ {
+ Debug.Assert(null != obj, "null pooledObject?");
+ Debug.Assert(obj.EnlistedTransaction == null, "pooledObject is still enlisted?");
+
+ // called by the transacted connection pool , once it's removed the
+ // connection from it's list. We put the connection back in general
+ // circulation.
+
+ // NOTE: there is no locking required here because if we're in this
+ // method, we can safely presume that the caller is the only person
+ // that is using the connection, and that all pre-push logic has been
+ // done and all transactions are ended.
+
+ if (_state == State.Running && obj.CanBePooled)
+ {
+ PutNewObject(obj);
+ }
+ else
+ {
+ DestroyObject(obj);
+ QueuePoolCreateRequest();
+ }
+ }
private void QueuePoolCreateRequest()
{
@@ -1139,6 +1536,7 @@ namespace System.Data.ProviderBase
emancipatedObjectFound = true;
+ obj.DetachCurrentTransactionIfEnded();
DeactivateObject(obj);
}
return emancipatedObjectFound;
@@ -1166,6 +1564,27 @@ namespace System.Data.ProviderBase
}
}
+ // TransactionEnded merely provides the plumbing for DbConnectionInternal to access the transacted pool
+ // that is implemented inside DbConnectionPool. This method's counterpart (PutTransactedObject) should
+ // only be called from DbConnectionPool.DeactivateObject and thus the plumbing to provide access to
+ // other objects is unnecessary (hence the asymmetry of Ended but no Begin)
+ internal void TransactionEnded(Transaction transaction, DbConnectionInternal transactedObject)
+ {
+ Debug.Assert(null != transaction, "null transaction?");
+ Debug.Assert(null != transactedObject, "null transactedObject?");
+ // Note: connection may still be associated with transaction due to Explicit Unbinding requirement.
+
+ // called by the internal connection when it get's told that the
+ // transaction is completed. We tell the transacted pool to remove
+ // the connection from it's list, then we put the connection back in
+ // general circulation.
+
+ TransactedConnectionPool transactedConnectionPool = _transactedConnectionPool;
+ if (null != transactedConnectionPool)
+ {
+ transactedConnectionPool.TransactionEnded(transaction, transactedObject);
+ }
+ }
private DbConnectionInternal UserCreateRequest(DbConnection owningObject, DbConnectionOptions userOptions, DbConnectionInternal oldConnection = null)
{
diff --git a/src/System.Data.SqlClient/src/System/Data/ProviderBase/DbConnectionPoolIdentity.Unix.cs b/src/System.Data.SqlClient/src/System/Data/ProviderBase/DbConnectionPoolIdentity.Unix.cs
index 20dbd34945..e0986b9d01 100644
--- a/src/System.Data.SqlClient/src/System/Data/ProviderBase/DbConnectionPoolIdentity.Unix.cs
+++ b/src/System.Data.SqlClient/src/System/Data/ProviderBase/DbConnectionPoolIdentity.Unix.cs
@@ -2,23 +2,13 @@
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
-
-//------------------------------------------------------------------------------
-
-using System.Security.Principal;
-
-
namespace System.Data.ProviderBase
{
partial class DbConnectionPoolIdentity
{
internal static DbConnectionPoolIdentity GetCurrent()
{
- string sidString = (!string.IsNullOrWhiteSpace(System.Environment.UserDomainName) ? System.Environment.UserDomainName + "\\" : "")
- + System.Environment.UserName;
- bool isNetwork = false;
- bool isRestricted = false;
- return new DbConnectionPoolIdentity(sidString, isRestricted, isNetwork);
+ return GetCurrentManaged();
}
}
}
diff --git a/src/System.Data.SqlClient/src/System/Data/ProviderBase/DbConnectionPoolIdentity.Windows.cs b/src/System.Data.SqlClient/src/System/Data/ProviderBase/DbConnectionPoolIdentity.Windows.cs
index 42040d5c5e..8c398a03fa 100644
--- a/src/System.Data.SqlClient/src/System/Data/ProviderBase/DbConnectionPoolIdentity.Windows.cs
+++ b/src/System.Data.SqlClient/src/System/Data/ProviderBase/DbConnectionPoolIdentity.Windows.cs
@@ -2,12 +2,9 @@
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
-
-//------------------------------------------------------------------------------
-
+using System.Data.SqlClient;
using System.Security.Principal;
-
namespace System.Data.ProviderBase
{
partial class DbConnectionPoolIdentity
@@ -16,6 +13,11 @@ namespace System.Data.ProviderBase
internal static DbConnectionPoolIdentity GetCurrent()
{
+ return TdsParserStateObjectFactory.UseManagedSNI ? GetCurrentManaged() : GetCurrentNative();
+ }
+
+ private static DbConnectionPoolIdentity GetCurrentNative()
+ {
DbConnectionPoolIdentity current;
using (WindowsIdentity identity = WindowsIdentity.GetCurrent())
{
diff --git a/src/System.Data.SqlClient/src/System/Data/ProviderBase/DbConnectionPoolIdentity.cs b/src/System.Data.SqlClient/src/System/Data/ProviderBase/DbConnectionPoolIdentity.cs
index 1134619a88..c1f9c98c6f 100644
--- a/src/System.Data.SqlClient/src/System/Data/ProviderBase/DbConnectionPoolIdentity.cs
+++ b/src/System.Data.SqlClient/src/System/Data/ProviderBase/DbConnectionPoolIdentity.cs
@@ -2,12 +2,6 @@
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
-
-//------------------------------------------------------------------------------
-
-using System.Security.Principal;
-
-
namespace System.Data.ProviderBase
{
[Serializable]
@@ -49,6 +43,15 @@ namespace System.Data.ProviderBase
{
return _hashCode;
}
+
+ internal static DbConnectionPoolIdentity GetCurrentManaged()
+ {
+ string sidString = (!string.IsNullOrWhiteSpace(System.Environment.UserDomainName) ? System.Environment.UserDomainName + "\\" : "")
+ + System.Environment.UserName;
+ bool isNetwork = false;
+ bool isRestricted = false;
+ return new DbConnectionPoolIdentity(sidString, isRestricted, isNetwork);
+ }
}
}
diff --git a/src/System.Data.SqlClient/src/System/Data/ProviderBase/DbConnectionPoolOptions.cs b/src/System.Data.SqlClient/src/System/Data/ProviderBase/DbConnectionPoolOptions.cs
index 8530e79af7..c04bd293e6 100644
--- a/src/System.Data.SqlClient/src/System/Data/ProviderBase/DbConnectionPoolOptions.cs
+++ b/src/System.Data.SqlClient/src/System/Data/ProviderBase/DbConnectionPoolOptions.cs
@@ -15,6 +15,7 @@ namespace System.Data.ProviderBase
private readonly int _maxPoolSize;
private readonly int _creationTimeout;
private readonly TimeSpan _loadBalanceTimeout;
+ private readonly bool _hasTransactionAffinity;
private readonly bool _useLoadBalancing;
public DbConnectionPoolGroupOptions(
@@ -22,7 +23,8 @@ namespace System.Data.ProviderBase
int minPoolSize,
int maxPoolSize,
int creationTimeout,
- int loadBalanceTimeout
+ int loadBalanceTimeout,
+ bool hasTransactionAffinity
)
{
_poolByIdentity = poolByIdentity;
@@ -35,12 +37,18 @@ namespace System.Data.ProviderBase
_loadBalanceTimeout = new TimeSpan(0, 0, loadBalanceTimeout);
_useLoadBalancing = true;
}
+
+ _hasTransactionAffinity = hasTransactionAffinity;
}
public int CreationTimeout
{
get { return _creationTimeout; }
}
+ public bool HasTransactionAffinity
+ {
+ get { return _hasTransactionAffinity; }
+ }
public TimeSpan LoadBalanceTimeout
{
get { return _loadBalanceTimeout; }
diff --git a/src/System.Data.SqlClient/src/System/Data/SqlClient/LocalDBAPI.Common.cs b/src/System.Data.SqlClient/src/System/Data/SqlClient/LocalDBAPI.Common.cs
new file mode 100644
index 0000000000..6ea840952a
--- /dev/null
+++ b/src/System.Data.SqlClient/src/System/Data/SqlClient/LocalDBAPI.Common.cs
@@ -0,0 +1,121 @@
+// Licensed to the .NET Foundation under one or more agreements.
+// The .NET Foundation licenses this file to you under the MIT license.
+// See the LICENSE file in the project root for more information.
+
+
+using System.Data.SqlClient;
+using System.Diagnostics;
+using System.Globalization;
+using System.Runtime.InteropServices;
+using System.Text;
+
+namespace System.Data
+{
+ internal static partial class LocalDBAPI
+ {
+ private static LocalDBFormatMessageDelegate s_localDBFormatMessage = null;
+
+ internal static void ReleaseDLLHandles()
+ {
+ s_userInstanceDLLHandle = IntPtr.Zero;
+ s_localDBFormatMessage = null;
+ }
+
+
+ private static LocalDBFormatMessageDelegate LocalDBFormatMessage
+ {
+ get
+ {
+ if (s_localDBFormatMessage == null)
+ {
+ lock (s_dllLock)
+ {
+ if (s_localDBFormatMessage == null)
+ {
+ IntPtr functionAddr = LoadProcAddress();
+
+ if (functionAddr == IntPtr.Zero)
+ {
+ int hResult = Marshal.GetLastWin32Error();
+ throw CreateLocalDBException(errorMessage: SR.LocalDB_MethodNotFound);
+ }
+ s_localDBFormatMessage = Marshal.GetDelegateForFunctionPointer<LocalDBFormatMessageDelegate>(functionAddr);
+ }
+ }
+ }
+ return s_localDBFormatMessage;
+ }
+ }
+
+ //This is copy of handle that SNI maintains, so we are responsible for freeing it - therefore there we are not using SafeHandle
+ private static IntPtr s_userInstanceDLLHandle = IntPtr.Zero;
+
+ private static readonly object s_dllLock = new object();
+
+
+ private const UInt32 const_LOCALDB_TRUNCATE_ERR_MESSAGE = 1;// flag for LocalDBFormatMessage that indicates that message can be truncated if it does not fit in the buffer
+ private const int const_ErrorMessageBufferSize = 1024; // Buffer size for Local DB error message 1K will be enough for all messages
+
+
+ internal static string GetLocalDBMessage(int hrCode)
+ {
+ Debug.Assert(hrCode < 0, "HRCode does not indicate error");
+ try
+ {
+ StringBuilder buffer = new StringBuilder((int)const_ErrorMessageBufferSize);
+ UInt32 len = (UInt32)buffer.Capacity;
+
+
+ // First try for current culture
+ int hResult = LocalDBFormatMessage(hrLocalDB: hrCode, dwFlags: const_LOCALDB_TRUNCATE_ERR_MESSAGE, dwLanguageId: (uint)CultureInfo.CurrentCulture.LCID,
+ buffer: buffer, buflen: ref len);
+ if (hResult >= 0)
+ return buffer.ToString();
+ else
+ {
+ // Message is not available for current culture, try default
+ buffer = new StringBuilder((int)const_ErrorMessageBufferSize);
+ len = (UInt32)buffer.Capacity;
+ hResult = LocalDBFormatMessage(hrLocalDB: hrCode, dwFlags: const_LOCALDB_TRUNCATE_ERR_MESSAGE, dwLanguageId: 0 /* thread locale with fallback to English */,
+ buffer: buffer, buflen: ref len);
+ if (hResult >= 0)
+ return buffer.ToString();
+ else
+ return string.Format(CultureInfo.CurrentCulture, "{0} (0x{1:X}).", SR.LocalDB_UnobtainableMessage, hResult);
+ }
+ }
+ catch (SqlException exc)
+ {
+ return string.Format(CultureInfo.CurrentCulture, "{0} ({1}).", SR.LocalDB_UnobtainableMessage, exc.Message);
+ }
+ }
+
+
+ private static SqlException CreateLocalDBException(string errorMessage, string instance = null, int localDbError = 0, int sniError = 0)
+ {
+ Debug.Assert((localDbError == 0) || (sniError == 0), "LocalDB error and SNI error cannot be specified simultaneously");
+ Debug.Assert(!string.IsNullOrEmpty(errorMessage), "Error message should not be null or empty");
+ SqlErrorCollection collection = new SqlErrorCollection();
+
+ int errorCode = (localDbError == 0) ? sniError : localDbError;
+
+ if (sniError != 0)
+ {
+ string sniErrorMessage = SQL.GetSNIErrorMessage(sniError);
+ errorMessage = String.Format((IFormatProvider)null, "{0} (error: {1} - {2})",
+ errorMessage, sniError, sniErrorMessage);
+ }
+
+ collection.Add(new SqlError(errorCode, 0, TdsEnums.FATAL_ERROR_CLASS, instance, errorMessage, null, 0));
+
+ if (localDbError != 0)
+ collection.Add(new SqlError(errorCode, 0, TdsEnums.FATAL_ERROR_CLASS, instance, GetLocalDBMessage(localDbError), null, 0));
+
+ SqlException exc = SqlException.CreateException(collection, null);
+
+ exc._doNotReconnect = true;
+
+ return exc;
+ }
+ }
+}
diff --git a/src/System.Data.SqlClient/src/System/Data/SqlClient/LocalDBAPI.Unix.cs b/src/System.Data.SqlClient/src/System/Data/SqlClient/LocalDBAPI.Unix.cs
index a46c18e1de..f69f3abf23 100644
--- a/src/System.Data.SqlClient/src/System/Data/SqlClient/LocalDBAPI.Unix.cs
+++ b/src/System.Data.SqlClient/src/System/Data/SqlClient/LocalDBAPI.Unix.cs
@@ -7,12 +7,7 @@ namespace System.Data
{
internal static partial class LocalDBAPI
{
- private static IntPtr UserInstanceDLLHandle
- {
- get
- {
- return IntPtr.Zero;
- }
- }
+ internal static string GetLocalDBMessage(int hrCode) =>
+ throw new PlatformNotSupportedException(SR.LocalDBNotSupported); // LocalDB is not available for Unix and hence it cannot be supported.
}
}
diff --git a/src/System.Data.SqlClient/src/System/Data/SqlClient/LocalDBAPI.Windows.cs b/src/System.Data.SqlClient/src/System/Data/SqlClient/LocalDBAPI.Windows.cs
index cc816ca79a..33a6cfce0b 100644
--- a/src/System.Data.SqlClient/src/System/Data/SqlClient/LocalDBAPI.Windows.cs
+++ b/src/System.Data.SqlClient/src/System/Data/SqlClient/LocalDBAPI.Windows.cs
@@ -3,13 +3,17 @@
// See the LICENSE file in the project root for more information.
-using System.Threading;
using System.Data.SqlClient;
+using System.Diagnostics;
+using System.Globalization;
+using System.Runtime.InteropServices;
+using System.Text;
namespace System.Data
{
internal static partial class LocalDBAPI
{
+ private static IntPtr LoadProcAddress() => SafeNativeMethods.GetProcAddress(UserInstanceDLLHandle, "LocalDBFormatMessage");
private static IntPtr UserInstanceDLLHandle
{
diff --git a/src/System.Data.SqlClient/src/System/Data/SqlClient/LocalDBAPI.cs b/src/System.Data.SqlClient/src/System/Data/SqlClient/LocalDBAPI.cs
index ba91cfe26d..e0154da5df 100644
--- a/src/System.Data.SqlClient/src/System/Data/SqlClient/LocalDBAPI.cs
+++ b/src/System.Data.SqlClient/src/System/Data/SqlClient/LocalDBAPI.cs
@@ -3,11 +3,7 @@
// See the LICENSE file in the project root for more information.
using System.Runtime.InteropServices;
-using System.Globalization;
-using System.Data.SqlClient;
using System.Text;
-using System.Diagnostics;
-
namespace System.Data
{
@@ -16,6 +12,9 @@ namespace System.Data
private const string const_localDbPrefix = @"(localdb)\";
+ [UnmanagedFunctionPointer(CallingConvention.Cdecl, CharSet = CharSet.Unicode)]
+ private delegate int LocalDBFormatMessageDelegate(int hrLocalDB, UInt32 dwFlags, UInt32 dwLanguageId, StringBuilder buffer, ref UInt32 buflen);
+
// check if name is in format (localdb)\<InstanceName - not empty> and return instance name if it is
internal static string GetLocalDbInstanceNameFromServerName(string serverName)
{
@@ -30,114 +29,5 @@ namespace System.Data
else
return instanceName;
}
-
-
- internal static void ReleaseDLLHandles()
- {
- s_userInstanceDLLHandle = IntPtr.Zero;
- s_localDBFormatMessage = null;
- }
-
-
-
- //This is copy of handle that SNI maintains, so we are responsible for freeing it - therefore there we are not using SafeHandle
- private static IntPtr s_userInstanceDLLHandle = IntPtr.Zero;
-
- private static readonly object s_dllLock = new object();
-
- [UnmanagedFunctionPointer(CallingConvention.Cdecl, CharSet = CharSet.Unicode)]
- private delegate int LocalDBFormatMessageDelegate(int hrLocalDB, UInt32 dwFlags, UInt32 dwLanguageId, StringBuilder buffer, ref UInt32 buflen);
-
- private static LocalDBFormatMessageDelegate s_localDBFormatMessage = null;
-
- private static LocalDBFormatMessageDelegate LocalDBFormatMessage
- {
- get
- {
- if (s_localDBFormatMessage == null)
- {
- lock (s_dllLock)
- {
- if (s_localDBFormatMessage == null)
- {
- IntPtr functionAddr = SafeNativeMethods.GetProcAddress(UserInstanceDLLHandle, "LocalDBFormatMessage");
-
- if (functionAddr == IntPtr.Zero)
- {
- int hResult = Marshal.GetLastWin32Error();
- throw CreateLocalDBException(errorMessage: SR.LocalDB_MethodNotFound);
- }
- s_localDBFormatMessage = Marshal.GetDelegateForFunctionPointer<LocalDBFormatMessageDelegate>(functionAddr);
- }
- }
- }
- return s_localDBFormatMessage;
- }
- }
-
- private const UInt32 const_LOCALDB_TRUNCATE_ERR_MESSAGE = 1;// flag for LocalDBFormatMessage that indicates that message can be truncated if it does not fit in the buffer
- private const int const_ErrorMessageBufferSize = 1024; // Buffer size for Local DB error message 1K will be enough for all messages
-
-
- internal static string GetLocalDBMessage(int hrCode)
- {
- Debug.Assert(hrCode < 0, "HRCode does not indicate error");
- try
- {
- StringBuilder buffer = new StringBuilder((int)const_ErrorMessageBufferSize);
- UInt32 len = (UInt32)buffer.Capacity;
-
-
- // First try for current culture
- int hResult = LocalDBFormatMessage(hrLocalDB: hrCode, dwFlags: const_LOCALDB_TRUNCATE_ERR_MESSAGE, dwLanguageId: (uint)CultureInfo.CurrentCulture.LCID,
- buffer: buffer, buflen: ref len);
- if (hResult >= 0)
- return buffer.ToString();
- else
- {
- // Message is not available for current culture, try default
- buffer = new StringBuilder((int)const_ErrorMessageBufferSize);
- len = (UInt32)buffer.Capacity;
- hResult = LocalDBFormatMessage(hrLocalDB: hrCode, dwFlags: const_LOCALDB_TRUNCATE_ERR_MESSAGE, dwLanguageId: 0 /* thread locale with fallback to English */,
- buffer: buffer, buflen: ref len);
- if (hResult >= 0)
- return buffer.ToString();
- else
- return string.Format(CultureInfo.CurrentCulture, "{0} (0x{1:X}).", SR.LocalDB_UnobtainableMessage, hResult);
- }
- }
- catch (SqlException exc)
- {
- return string.Format(CultureInfo.CurrentCulture, "{0} ({1}).", SR.LocalDB_UnobtainableMessage, exc.Message);
- }
- }
-
-
- private static SqlException CreateLocalDBException(string errorMessage, string instance = null, int localDbError = 0, int sniError = 0)
- {
- Debug.Assert((localDbError == 0) || (sniError == 0), "LocalDB error and SNI error cannot be specified simultaneously");
- Debug.Assert(!string.IsNullOrEmpty(errorMessage), "Error message should not be null or empty");
- SqlErrorCollection collection = new SqlErrorCollection();
-
- int errorCode = (localDbError == 0) ? sniError : localDbError;
-
- if (sniError != 0)
- {
- string sniErrorMessage = SQL.GetSNIErrorMessage(sniError);
- errorMessage = String.Format((IFormatProvider)null, "{0} (error: {1} - {2})",
- errorMessage, sniError, sniErrorMessage);
- }
-
- collection.Add(new SqlError(errorCode, 0, TdsEnums.FATAL_ERROR_CLASS, instance, errorMessage, null, 0));
-
- if (localDbError != 0)
- collection.Add(new SqlError(errorCode, 0, TdsEnums.FATAL_ERROR_CLASS, instance, GetLocalDBMessage(localDbError), null, 0));
-
- SqlException exc = SqlException.CreateException(collection, null);
-
- exc._doNotReconnect = true;
-
- return exc;
- }
}
}
diff --git a/src/System.Data.SqlClient/src/System/Data/SqlClient/LocalDBAPI.uap.cs b/src/System.Data.SqlClient/src/System/Data/SqlClient/LocalDBAPI.uap.cs
new file mode 100644
index 0000000000..c148d5c94b
--- /dev/null
+++ b/src/System.Data.SqlClient/src/System/Data/SqlClient/LocalDBAPI.uap.cs
@@ -0,0 +1,19 @@
+// Licensed to the .NET Foundation under one or more agreements.
+// The .NET Foundation licenses this file to you under the MIT license.
+// See the LICENSE file in the project root for more information.
+
+
+using System.Threading;
+using System.Data.SqlClient;
+using System.Data.SqlClient.SNI;
+using System.Runtime.InteropServices;
+
+namespace System.Data
+{
+ internal static partial class LocalDBAPI
+ {
+
+ private static IntPtr LoadProcAddress() => LocalDB.GetProcAddress("LocalDBFormatMessage");
+
+ }
+}
diff --git a/src/System.Data.SqlClient/src/System/Data/SqlClient/SNI/LocalDB.Windows.cs b/src/System.Data.SqlClient/src/System/Data/SqlClient/SNI/LocalDB.Windows.cs
index 1466585bb6..7abe9bf924 100644
--- a/src/System.Data.SqlClient/src/System/Data/SqlClient/SNI/LocalDB.Windows.cs
+++ b/src/System.Data.SqlClient/src/System/Data/SqlClient/SNI/LocalDB.Windows.cs
@@ -42,6 +42,9 @@ namespace System.Data.SqlClient.SNI
internal static string GetLocalDBConnectionString(string localDbInstance) =>
Instance.LoadUserInstanceDll() ? Instance.GetConnectionString(localDbInstance) : null;
+ internal static IntPtr GetProcAddress(string functionName) =>
+ Instance.LoadUserInstanceDll() ? Interop.Kernel32.GetProcAddress(LocalDB.Instance._sqlUserInstanceLibraryHandle, functionName) : IntPtr.Zero;
+
private string GetConnectionString(string localDbInstance)
{
StringBuilder localDBConnectionString = new StringBuilder(MAX_LOCAL_DB_CONNECTION_STRING_SIZE + 1);
diff --git a/src/System.Data.SqlClient/src/System/Data/SqlClient/SNI/SNINpHandle.cs b/src/System.Data.SqlClient/src/System/Data/SqlClient/SNI/SNINpHandle.cs
index 2d0698c27c..657518f1a1 100644
--- a/src/System.Data.SqlClient/src/System/Data/SqlClient/SNI/SNINpHandle.cs
+++ b/src/System.Data.SqlClient/src/System/Data/SqlClient/SNI/SNINpHandle.cs
@@ -6,7 +6,6 @@ using System.ComponentModel;
using System.IO;
using System.IO.Pipes;
using System.Net.Security;
-using System.Net.Sockets;
using System.Security.Authentication;
using System.Security.Cryptography.X509Certificates;
using System.Threading.Tasks;
@@ -68,8 +67,8 @@ namespace System.Data.SqlClient.SNI
}
catch(TimeoutException te)
{
- SNICommon.ReportSNIError(SNIProviders.NP_PROV, SNICommon.ConnTimeoutError, te);
- _status = TdsEnums.SNI_WAIT_TIMEOUT;
+ SNICommon.ReportSNIError(SNIProviders.NP_PROV, SNICommon.ConnOpenFailedError, te);
+ _status = TdsEnums.SNI_ERROR;
return;
}
catch(IOException ioe)
diff --git a/src/System.Data.SqlClient/src/System/Data/SqlClient/SqlCommand.cs b/src/System.Data.SqlClient/src/System/Data/SqlClient/SqlCommand.cs
index 9978790a83..be7d790bbd 100644
--- a/src/System.Data.SqlClient/src/System/Data/SqlClient/SqlCommand.cs
+++ b/src/System.Data.SqlClient/src/System/Data/SqlClient/SqlCommand.cs
@@ -340,7 +340,7 @@ namespace System.Data.SqlClient
{
if (null != _activeConnection)
{
- if (_activeConnection.StatisticsEnabled ||
+ if (_activeConnection.StatisticsEnabled ||
_diagnosticListener.IsEnabled(SqlClientDiagnosticListenerExtensions.SqlAfterExecuteCommand))
{
return _activeConnection.Statistics;
@@ -792,7 +792,7 @@ namespace System.Data.SqlClient
Guid operationId = _diagnosticListener.WriteCommandBefore(this);
SqlStatistics statistics = null;
-
+
Exception e = null;
try
{
@@ -860,7 +860,7 @@ namespace System.Data.SqlClient
Guid operationId = _diagnosticListener.WriteCommandBefore(this);
SqlStatistics statistics = null;
-
+
Exception e = null;
try
{
@@ -876,7 +876,7 @@ namespace System.Data.SqlClient
finally
{
SqlStatistics.StopTimer(statistics);
-
+
if (e != null)
{
_diagnosticListener.WriteCommandError(operationId, this, e);
@@ -1185,7 +1185,7 @@ namespace System.Data.SqlClient
Guid operationId = _diagnosticListener.WriteCommandBefore(this);
SqlStatistics statistics = null;
-
+
Exception e = null;
try
{
@@ -1204,7 +1204,7 @@ namespace System.Data.SqlClient
finally
{
SqlStatistics.StopTimer(statistics);
-
+
if (e != null)
{
_diagnosticListener.WriteCommandError(operationId, this, e);
@@ -1402,7 +1402,7 @@ namespace System.Data.SqlClient
Guid operationId = _diagnosticListener.WriteCommandBefore(this);
SqlStatistics statistics = null;
-
+
Exception e = null;
try
{
@@ -1417,7 +1417,7 @@ namespace System.Data.SqlClient
finally
{
SqlStatistics.StopTimer(statistics);
-
+
if (e != null)
{
_diagnosticListener.WriteCommandError(operationId, this, e);
@@ -2699,7 +2699,7 @@ namespace System.Data.SqlClient
{
ds.Close();
}
- catch(Exception exClose)
+ catch (Exception exClose)
{
Debug.WriteLine("Received this exception from SqlDataReader.Close() while in another catch block: " + exClose.ToString());
}
diff --git a/src/System.Data.SqlClient/src/System/Data/SqlClient/SqlConnection.cs b/src/System.Data.SqlClient/src/System/Data/SqlClient/SqlConnection.cs
index f9b77f48af..5dab5aecb2 100644
--- a/src/System.Data.SqlClient/src/System/Data/SqlClient/SqlConnection.cs
+++ b/src/System.Data.SqlClient/src/System/Data/SqlClient/SqlConnection.cs
@@ -145,6 +145,14 @@ namespace System.Data.SqlClient
}
}
+ internal SqlConnectionString.TransactionBindingEnum TransactionBinding
+ {
+ get
+ {
+ return ((SqlConnectionString)ConnectionOptions).TransactionBinding;
+ }
+ }
+
internal SqlConnectionString.TypeSystem TypeSystem
{
get
@@ -612,11 +620,6 @@ namespace System.Data.SqlClient
}
}
- public override void EnlistTransaction(Transaction transaction)
- {
- throw ADP.AmbientTransactionIsNotSupported();
- }
-
internal void RegisterWaitingForReconnect(Task waitingTask)
{
if (((SqlConnectionString)ConnectionOptions).MARS)
@@ -729,6 +732,7 @@ namespace System.Data.SqlClient
bool callDisconnect = false;
lock (_reconnectLock)
{
+ tdsConn.CheckEnlistedTransactionBinding();
runningReconnect = _currentReconnectionTask; // double check after obtaining the lock
if (runningReconnect == null)
{
@@ -834,7 +838,8 @@ namespace System.Data.SqlClient
{
statistics = SqlStatistics.StartTimer(Statistics);
- TaskCompletionSource<DbConnectionInternal> completion = new TaskCompletionSource<DbConnectionInternal>();
+ System.Transactions.Transaction transaction = ADP.GetCurrentTransaction();
+ TaskCompletionSource<DbConnectionInternal> completion = new TaskCompletionSource<DbConnectionInternal>(transaction);
TaskCompletionSource<object> result = new TaskCompletionSource<object>();
if (s_diagnosticListener.IsEnabled(SqlClientDiagnosticListenerExtensions.SqlAfterOpenConnection) ||
@@ -1012,12 +1017,6 @@ namespace System.Data.SqlClient
{
SqlConnectionString connectionOptions = (SqlConnectionString)ConnectionOptions;
- // Fail Fast in case an application is trying to enlist the SqlConnection in a Transaction Scope.
- if (connectionOptions.Enlist && ADP.GetCurrentTransaction() != null)
- {
- throw ADP.AmbientTransactionIsNotSupported();
- }
-
_applyTransientFaultHandling = (retry == null && connectionOptions != null && connectionOptions.ConnectRetryCount > 0);
if (ForceNewConnection)
@@ -1037,6 +1036,7 @@ namespace System.Data.SqlClient
// does not require GC.KeepAlive(this) because of OnStateChange
var tdsInnerConnection = (SqlInternalConnectionTds)InnerConnection;
+
Debug.Assert(tdsInnerConnection.Parser != null, "Where's the parser?");
if (!tdsInnerConnection.ConnectionOptions.Pooling)
@@ -1048,7 +1048,7 @@ namespace System.Data.SqlClient
// The _statistics can change with StatisticsEnabled. Copying to a local variable before checking for a null value.
SqlStatistics statistics = _statistics;
if (StatisticsEnabled ||
- ( s_diagnosticListener.IsEnabled(SqlClientDiagnosticListenerExtensions.SqlAfterExecuteCommand) && statistics != null))
+ (s_diagnosticListener.IsEnabled(SqlClientDiagnosticListenerExtensions.SqlAfterExecuteCommand) && statistics != null))
{
ADP.TimerCurrent(out _statistics._openTimestamp);
tdsInnerConnection.Parser.Statistics = _statistics;
diff --git a/src/System.Data.SqlClient/src/System/Data/SqlClient/SqlConnectionFactory.cs b/src/System.Data.SqlClient/src/System/Data/SqlClient/SqlConnectionFactory.cs
index 1fcbe365c1..d99413f48f 100644
--- a/src/System.Data.SqlClient/src/System/Data/SqlClient/SqlConnectionFactory.cs
+++ b/src/System.Data.SqlClient/src/System/Data/SqlClient/SqlConnectionFactory.cs
@@ -175,8 +175,8 @@ namespace System.Data.SqlClient
opt.MinPoolSize,
opt.MaxPoolSize,
connectionTimeout,
- opt.LoadBalanceTimeout
- );
+ opt.LoadBalanceTimeout,
+ opt.Enlist);
}
return poolingOptions;
}
diff --git a/src/System.Data.SqlClient/src/System/Data/SqlClient/SqlConnectionHelper.cs b/src/System.Data.SqlClient/src/System/Data/SqlClient/SqlConnectionHelper.cs
index 5c2a354a67..2e318bfa81 100644
--- a/src/System.Data.SqlClient/src/System/Data/SqlClient/SqlConnectionHelper.cs
+++ b/src/System.Data.SqlClient/src/System/Data/SqlClient/SqlConnectionHelper.cs
@@ -10,6 +10,7 @@ using System.Data.Common;
using System.Data.ProviderBase;
using System.Diagnostics;
using System.Threading;
+using System.Transactions;
namespace System.Data.SqlClient
@@ -154,6 +155,41 @@ namespace System.Data.SqlClient
partial void RepairInnerConnection();
+ public override void EnlistTransaction(Transaction transaction)
+ {
+ // If we're currently enlisted in a transaction and we were called
+ // on the EnlistTransaction method (Whidbey) we're not allowed to
+ // enlist in a different transaction.
+
+ DbConnectionInternal innerConnection = InnerConnection;
+
+ // NOTE: since transaction enlistment involves round trips to the
+ // server, we don't want to lock here, we'll handle the race conditions
+ // elsewhere.
+ Transaction enlistedTransaction = innerConnection.EnlistedTransaction;
+ if (enlistedTransaction != null)
+ {
+ // Allow calling enlist if already enlisted (no-op)
+ if (enlistedTransaction.Equals(transaction))
+ {
+ return;
+ }
+
+ // Allow enlisting in a different transaction if the enlisted transaction has completed.
+ if (enlistedTransaction.TransactionInformation.Status == TransactionStatus.Active)
+ {
+ throw ADP.TransactionPresent();
+ }
+ }
+ RepairInnerConnection();
+ InnerConnection.EnlistTransaction(transaction);
+
+ // NOTE: If this outer connection were to be GC'd while we're
+ // enlisting, the pooler would attempt to reclaim the inner connection
+ // while we're attempting to enlist; not sure how likely that is but
+ // we should consider a GC.KeepAlive(this) here.
+ GC.KeepAlive(this);
+ }
internal void NotifyWeakReference(int message)
{
diff --git a/src/System.Data.SqlClient/src/System/Data/SqlClient/SqlConnectionString.cs b/src/System.Data.SqlClient/src/System/Data/SqlClient/SqlConnectionString.cs
index 064e35cd73..008f6ba7ca 100644
--- a/src/System.Data.SqlClient/src/System/Data/SqlClient/SqlConnectionString.cs
+++ b/src/System.Data.SqlClient/src/System/Data/SqlClient/SqlConnectionString.cs
@@ -4,9 +4,6 @@
-//------------------------------------------------------------------------------
-
-using System.Collections;
using System.Collections.Generic;
using System.Data.Common;
using System.Diagnostics;
@@ -153,6 +150,17 @@ namespace System.Data.SqlClient
internal const string SQL_Server_2012 = "SQL Server 2012";
}
+ internal enum TransactionBindingEnum
+ {
+ ImplicitUnbind,
+ ExplicitUnbind
+ }
+
+ internal static class TRANSACTIONBINDING
+ {
+ internal const string ImplicitUnbind = "Implicit Unbind";
+ internal const string ExplicitUnbind = "Explicit Unbind";
+ }
private static Dictionary<string, string> s_sqlClientSynonyms;
@@ -190,12 +198,14 @@ namespace System.Data.SqlClient
private readonly string _workstationId;
private readonly TypeSystem _typeSystemVersion;
+
+ private readonly TransactionBindingEnum _transactionBinding;
+
internal SqlConnectionString(string connectionString) : base(connectionString, GetParseSynonyms())
{
ThrowUnsupportedIfKeywordSet(KEY.AsynchronousProcessing);
ThrowUnsupportedIfKeywordSet(KEY.Connection_Reset);
ThrowUnsupportedIfKeywordSet(KEY.Context_Connection);
- ThrowUnsupportedIfKeywordSet(KEY.TransactionBinding);
// Network Library has its own special error message
if (ContainsKey(KEY.Network_Library))
@@ -234,6 +244,7 @@ namespace System.Data.SqlClient
// Temporary string - this value is stored internally as an enum.
string typeSystemVersionString = ConvertValueToString(KEY.Type_System_Version, null);
+ string transactionBindingString = ConvertValueToString(KEY.TransactionBinding, null);
_userID = ConvertValueToString(KEY.User_ID, DEFAULT.User_ID);
_workstationId = ConvertValueToString(KEY.Workstation_Id, null);
@@ -342,6 +353,23 @@ namespace System.Data.SqlClient
throw ADP.InvalidConnectionOptionValue(KEY.Type_System_Version);
}
+ if (string.IsNullOrEmpty(transactionBindingString))
+ {
+ transactionBindingString = DbConnectionStringDefaults.TransactionBinding;
+ }
+
+ if (transactionBindingString.Equals(TRANSACTIONBINDING.ImplicitUnbind, StringComparison.OrdinalIgnoreCase))
+ {
+ _transactionBinding = TransactionBindingEnum.ImplicitUnbind;
+ }
+ else if (transactionBindingString.Equals(TRANSACTIONBINDING.ExplicitUnbind, StringComparison.OrdinalIgnoreCase))
+ {
+ _transactionBinding = TransactionBindingEnum.ExplicitUnbind;
+ }
+ else
+ {
+ throw ADP.InvalidConnectionOptionValue(KEY.TransactionBinding);
+ }
if (_applicationIntent == ApplicationIntent.ReadOnly && !String.IsNullOrEmpty(_failoverPartner))
throw SQL.ROR_FailoverNotSupportedConnString();
@@ -395,6 +423,7 @@ namespace System.Data.SqlClient
_userID = connectionOptions._userID;
_workstationId = connectionOptions._workstationId;
_typeSystemVersion = connectionOptions._typeSystemVersion;
+ _transactionBinding = connectionOptions._transactionBinding;
_applicationIntent = connectionOptions._applicationIntent;
_connectRetryCount = connectionOptions._connectRetryCount;
_connectRetryInterval = connectionOptions._connectRetryInterval;
@@ -444,6 +473,8 @@ namespace System.Data.SqlClient
internal TypeSystem TypeSystemVersion { get { return _typeSystemVersion; } }
+ internal TransactionBindingEnum TransactionBinding { get { return _transactionBinding; } }
+
// This dictionary is meant to be read-only translation of parsed string
// keywords/synonyms to a known keyword string.
internal static Dictionary<string, string> GetParseSynonyms()
diff --git a/src/System.Data.SqlClient/src/System/Data/SqlClient/SqlConnectionStringBuilder.cs b/src/System.Data.SqlClient/src/System/Data/SqlClient/SqlConnectionStringBuilder.cs
index 53fdd8ed54..d5ad65a88f 100644
--- a/src/System.Data.SqlClient/src/System/Data/SqlClient/SqlConnectionStringBuilder.cs
+++ b/src/System.Data.SqlClient/src/System/Data/SqlClient/SqlConnectionStringBuilder.cs
@@ -47,6 +47,7 @@ namespace System.Data.SqlClient
UserInstance,
+ TransactionBinding,
ApplicationIntent,
@@ -61,7 +62,7 @@ namespace System.Data.SqlClient
}
internal const int KeywordsCount = (int)Keywords.KeywordsCount;
- internal const int DeprecatedKeywordsCount = 5;
+ internal const int DeprecatedKeywordsCount = 4;
private static readonly string[] s_validKeywords = CreateValidKeywords();
private static readonly Dictionary<string, Keywords> s_keywords = CreateKeywordsDictionary();
@@ -75,6 +76,7 @@ namespace System.Data.SqlClient
private string _initialCatalog = DbConnectionStringDefaults.InitialCatalog;
// private string _namedConnection = DbConnectionStringDefaults.NamedConnection;
private string _password = DbConnectionStringDefaults.Password;
+ private string _transactionBinding = DbConnectionStringDefaults.TransactionBinding;
private string _typeSystemVersion = DbConnectionStringDefaults.TypeSystemVersion;
private string _userID = DbConnectionStringDefaults.UserID;
private string _workstationID = DbConnectionStringDefaults.WorkstationID;
@@ -123,6 +125,7 @@ namespace System.Data.SqlClient
validKeywords[(int)Keywords.PersistSecurityInfo] = DbConnectionStringKeywords.PersistSecurityInfo;
validKeywords[(int)Keywords.Pooling] = DbConnectionStringKeywords.Pooling;
validKeywords[(int)Keywords.Replication] = DbConnectionStringKeywords.Replication;
+ validKeywords[(int)Keywords.TransactionBinding] = DbConnectionStringKeywords.TransactionBinding;
validKeywords[(int)Keywords.TrustServerCertificate] = DbConnectionStringKeywords.TrustServerCertificate;
validKeywords[(int)Keywords.TypeSystemVersion] = DbConnectionStringKeywords.TypeSystemVersion;
validKeywords[(int)Keywords.UserID] = DbConnectionStringKeywords.UserID;
@@ -158,6 +161,7 @@ namespace System.Data.SqlClient
hash.Add(DbConnectionStringKeywords.PersistSecurityInfo, Keywords.PersistSecurityInfo);
hash.Add(DbConnectionStringKeywords.Pooling, Keywords.Pooling);
hash.Add(DbConnectionStringKeywords.Replication, Keywords.Replication);
+ hash.Add(DbConnectionStringKeywords.TransactionBinding, Keywords.TransactionBinding);
hash.Add(DbConnectionStringKeywords.TrustServerCertificate, Keywords.TrustServerCertificate);
hash.Add(DbConnectionStringKeywords.TypeSystemVersion, Keywords.TypeSystemVersion);
hash.Add(DbConnectionStringKeywords.UserID, Keywords.UserID);
@@ -224,6 +228,7 @@ namespace System.Data.SqlClient
// case Keywords.NamedConnection: NamedConnection = ConvertToString(value); break;
case Keywords.Password: Password = ConvertToString(value); break;
case Keywords.UserID: UserID = ConvertToString(value); break;
+ case Keywords.TransactionBinding: TransactionBinding = ConvertToString(value); break;
case Keywords.TypeSystemVersion: TypeSystemVersion = ConvertToString(value); break;
case Keywords.WorkstationID: WorkstationID = ConvertToString(value); break;
@@ -549,6 +554,16 @@ namespace System.Data.SqlClient
}
}
+ public string TransactionBinding
+ {
+ get { return _transactionBinding; }
+ set
+ {
+ SetValue(DbConnectionStringKeywords.TransactionBinding, value);
+ _transactionBinding = value;
+ }
+ }
+
public string TypeSystemVersion
{
get { return _typeSystemVersion; }
@@ -675,6 +690,7 @@ namespace System.Data.SqlClient
case Keywords.PersistSecurityInfo: return PersistSecurityInfo;
case Keywords.Pooling: return Pooling;
case Keywords.Replication: return Replication;
+ case Keywords.TransactionBinding: return TransactionBinding;
case Keywords.TrustServerCertificate: return TrustServerCertificate;
case Keywords.TypeSystemVersion: return TypeSystemVersion;
case Keywords.UserID: return UserID;
@@ -792,6 +808,9 @@ namespace System.Data.SqlClient
case Keywords.Replication:
_replication = DbConnectionStringDefaults.Replication;
break;
+ case Keywords.TransactionBinding:
+ _transactionBinding = DbConnectionStringDefaults.TransactionBinding;
+ break;
case Keywords.TrustServerCertificate:
_trustServerCertificate = DbConnectionStringDefaults.TrustServerCertificate;
break;
diff --git a/src/System.Data.SqlClient/src/System/Data/SqlClient/SqlDelegatedTransaction.cs b/src/System.Data.SqlClient/src/System/Data/SqlClient/SqlDelegatedTransaction.cs
new file mode 100644
index 0000000000..ecd03c1136
--- /dev/null
+++ b/src/System.Data.SqlClient/src/System/Data/SqlClient/SqlDelegatedTransaction.cs
@@ -0,0 +1,466 @@
+using System.Data.Common;
+using System.Data.SqlClient;
+using System.Diagnostics;
+using System.Reflection;
+using System.Runtime.CompilerServices;
+using System.Runtime.ConstrainedExecution;
+using System.Threading;
+using System.Transactions;
+
+namespace System.Data.SqlClient
+{
+ sealed internal class SqlDelegatedTransaction : IPromotableSinglePhaseNotification
+ {
+ private static int _objectTypeCount;
+ private readonly int _objectID = Interlocked.Increment(ref _objectTypeCount);
+ private const int _globalTransactionsTokenVersionSizeInBytes = 4; // the size of the version in the PromotedDTCToken for Global Transactions
+ internal int ObjectID
+ {
+ get
+ {
+ return _objectID;
+ }
+ }
+
+ // WARNING!!! Multithreaded object!
+ // Locking strategy: Any potentailly-multithreaded operation must first lock the associated connection, then
+ // validate this object's active state. Locked activities should ONLY include Sql-transaction state altering activities
+ // or notifications of same. Updates to the connection's association with the transaction or to the connection pool
+ // may be initiated here AFTER the connection lock is released, but should NOT fall under this class's locking strategy.
+
+ private SqlInternalConnection _connection; // the internal connection that is the root of the transaction
+ private IsolationLevel _isolationLevel; // the IsolationLevel of the transaction we delegated to the server
+ private SqlInternalTransaction _internalTransaction; // the SQL Server transaction we're delegating to
+
+ private Transaction _atomicTransaction;
+
+ private bool _active; // Is the transaction active?
+
+ internal SqlDelegatedTransaction(SqlInternalConnection connection, Transaction tx)
+ {
+ Debug.Assert(null != connection, "null connection?");
+ _connection = connection;
+ _atomicTransaction = tx;
+ _active = false;
+ Transactions.IsolationLevel systxIsolationLevel = (Transactions.IsolationLevel)tx.IsolationLevel;
+
+ // We need to map the System.Transactions IsolationLevel to the one
+ // that System.Data uses and communicates to SqlServer. We could
+ // arguably do that in Initialize when the transaction is delegated,
+ // however it is better to do this before we actually begin the process
+ // of delegation, in case System.Transactions adds another isolation
+ // level we don't know about -- we can throw the exception at a better
+ // place.
+ switch (systxIsolationLevel)
+ {
+ case Transactions.IsolationLevel.ReadCommitted:
+ _isolationLevel = IsolationLevel.ReadCommitted;
+ break;
+ case Transactions.IsolationLevel.ReadUncommitted:
+ _isolationLevel = IsolationLevel.ReadUncommitted;
+ break;
+ case Transactions.IsolationLevel.RepeatableRead:
+ _isolationLevel = IsolationLevel.RepeatableRead;
+ break;
+ case Transactions.IsolationLevel.Serializable:
+ _isolationLevel = IsolationLevel.Serializable;
+ break;
+ case Transactions.IsolationLevel.Snapshot:
+ _isolationLevel = IsolationLevel.Snapshot;
+ break;
+ default:
+ throw SQL.UnknownSysTxIsolationLevel(systxIsolationLevel);
+ }
+ }
+
+ internal Transaction Transaction
+ {
+ get { return _atomicTransaction; }
+ }
+
+ public void Initialize()
+ {
+ // if we get here, then we know for certain that we're the delegated
+ // transaction.
+ SqlInternalConnection connection = _connection;
+ SqlConnection usersConnection = connection.Connection;
+
+ RuntimeHelpers.PrepareConstrainedRegions();
+ try
+ {
+ if (connection.IsEnlistedInTransaction)
+ { // defect first
+ connection.EnlistNull();
+ }
+
+ _internalTransaction = new SqlInternalTransaction(connection, TransactionType.Delegated, null);
+
+ connection.ExecuteTransaction(SqlInternalConnection.TransactionRequest.Begin, null, _isolationLevel, _internalTransaction, true);
+
+ // Handle case where ExecuteTran didn't produce a new transaction, but also didn't throw.
+ if (null == connection.CurrentTransaction)
+ {
+ connection.DoomThisConnection();
+ throw ADP.InternalError(ADP.InternalErrorCode.UnknownTransactionFailure);
+ }
+
+ _active = true;
+ }
+ catch (System.OutOfMemoryException e)
+ {
+ usersConnection.Abort(e);
+ throw;
+ }
+ catch (System.StackOverflowException e)
+ {
+ usersConnection.Abort(e);
+ throw;
+ }
+ catch (System.Threading.ThreadAbortException e)
+ {
+ usersConnection.Abort(e);
+ throw;
+ }
+ }
+
+ internal bool IsActive
+ {
+ get
+ {
+ return _active;
+ }
+ }
+
+ public Byte[] Promote()
+ {
+ // Operations that might be affected by multi-threaded use MUST be done inside the lock.
+ // Don't read values off of the connection outside the lock unless it doesn't really matter
+ // from an operational standpoint (i.e. logging connection's ObjectID should be fine,
+ // but the PromotedDTCToken can change over calls. so that must be protected).
+ SqlInternalConnection connection = GetValidConnection();
+
+ Exception promoteException;
+ byte[] returnValue = null;
+ SqlConnection usersConnection = connection.Connection;
+
+ RuntimeHelpers.PrepareConstrainedRegions();
+ try
+ {
+ lock (connection)
+ {
+ try
+ {
+ // Now that we've acquired the lock, make sure we still have valid state for this operation.
+ ValidateActiveOnConnection(connection);
+
+ connection.ExecuteTransaction(SqlInternalConnection.TransactionRequest.Promote, null, IsolationLevel.Unspecified, _internalTransaction, true);
+ returnValue = _connection.PromotedDTCToken;
+
+ // For Global Transactions, we need to set the Transaction Id since we use a Non-MSDTC Promoter type.
+ if (_connection.IsGlobalTransaction)
+ {
+ if (SysTxForGlobalTransactions.SetDistributedTransactionIdentifier == null)
+ {
+ throw SQL.UnsupportedSysTxForGlobalTransactions();
+ }
+
+ if (!_connection.IsGlobalTransactionsEnabledForServer)
+ {
+ throw SQL.GlobalTransactionsNotEnabled();
+ }
+
+ SysTxForGlobalTransactions.SetDistributedTransactionIdentifier.Invoke(_atomicTransaction, new object[] { this, GetGlobalTxnIdentifierFromToken() });
+ }
+
+ promoteException = null;
+ }
+ catch (SqlException e)
+ {
+ promoteException = e;
+
+ // Doom the connection, to make sure that the transaction is
+ // eventually rolled back.
+ // VSTS 144562: doom the connection while having the lock on it to prevent race condition with "Transaction Ended" Event
+ connection.DoomThisConnection();
+ }
+ catch (InvalidOperationException e)
+ {
+ promoteException = e;
+ connection.DoomThisConnection();
+ }
+ }
+ }
+ catch (System.OutOfMemoryException e)
+ {
+ usersConnection.Abort(e);
+ throw;
+ }
+ catch (System.StackOverflowException e)
+ {
+ usersConnection.Abort(e);
+ throw;
+ }
+ catch (System.Threading.ThreadAbortException e)
+ {
+ usersConnection.Abort(e);
+ throw;
+ }
+
+ if (promoteException != null)
+ {
+ throw SQL.PromotionFailed(promoteException);
+ }
+
+ return returnValue;
+ }
+
+ // Called by transaction to initiate abort sequence
+ public void Rollback(SinglePhaseEnlistment enlistment)
+ {
+ Debug.Assert(null != enlistment, "null enlistment?");
+
+ SqlInternalConnection connection = GetValidConnection();
+ SqlConnection usersConnection = connection.Connection;
+
+ RuntimeHelpers.PrepareConstrainedRegions();
+ try
+ {
+ lock (connection)
+ {
+ try
+ {
+ // Now that we've acquired the lock, make sure we still have valid state for this operation.
+ ValidateActiveOnConnection(connection);
+ _active = false; // set to inactive first, doesn't matter how the execute completes, this transaction is done.
+ _connection = null; // Set prior to ExecuteTransaction call in case this initiates a TransactionEnd event
+
+ // If we haven't already rolled back (or aborted) then tell the SQL Server to roll back
+ if (!_internalTransaction.IsAborted)
+ {
+ connection.ExecuteTransaction(SqlInternalConnection.TransactionRequest.Rollback, null, IsolationLevel.Unspecified, _internalTransaction, true);
+ }
+ }
+ catch (SqlException)
+ {
+ // Doom the connection, to make sure that the transaction is
+ // eventually rolled back.
+ // VSTS 144562: doom the connection while having the lock on it to prevent race condition with "Transaction Ended" Event
+ connection.DoomThisConnection();
+
+ // Unlike SinglePhaseCommit, a rollback is a rollback, regardless
+ // of how it happens, so SysTx won't throw an exception, and we
+ // don't want to throw an exception either, because SysTx isn't
+ // handling it and it may create a fail fast scenario. In the end,
+ // there is no way for us to communicate to the consumer that this
+ // failed for more serious reasons than usual.
+ //
+ // This is a bit like "should you throw if Close fails", however,
+ // it only matters when you really need to know. In that case,
+ // we have the tracing that we're doing to fallback on for the
+ // investigation.
+ }
+ catch (InvalidOperationException)
+ {
+ connection.DoomThisConnection();
+ }
+ }
+
+ // it doesn't matter whether the rollback succeeded or not, we presume
+ // that the transaction is aborted, because it will be eventually.
+ connection.CleanupConnectionOnTransactionCompletion(_atomicTransaction);
+ enlistment.Aborted();
+ }
+ catch (System.OutOfMemoryException e)
+ {
+ usersConnection.Abort(e);
+ throw;
+ }
+ catch (System.StackOverflowException e)
+ {
+ usersConnection.Abort(e);
+ throw;
+ }
+ catch (System.Threading.ThreadAbortException e)
+ {
+ usersConnection.Abort(e);
+ throw;
+ }
+ }
+
+ // Called by the transaction to initiate commit sequence
+ public void SinglePhaseCommit(SinglePhaseEnlistment enlistment)
+ {
+ Debug.Assert(null != enlistment, "null enlistment?");
+
+ SqlInternalConnection connection = GetValidConnection();
+ SqlConnection usersConnection = connection.Connection;
+
+ RuntimeHelpers.PrepareConstrainedRegions();
+ try
+ {
+ // If the connection is dooomed, we can be certain that the
+ // transaction will eventually be rolled back, and we shouldn't
+ // attempt to commit it.
+ if (connection.IsConnectionDoomed)
+ {
+ lock (connection)
+ {
+ _active = false; // set to inactive first, doesn't matter how the rest completes, this transaction is done.
+ _connection = null;
+ }
+
+ enlistment.Aborted(SQL.ConnectionDoomed());
+ }
+ else
+ {
+ Exception commitException;
+ lock (connection)
+ {
+ try
+ {
+ // Now that we've acquired the lock, make sure we still have valid state for this operation.
+ ValidateActiveOnConnection(connection);
+
+ _active = false; // set to inactive first, doesn't matter how the rest completes, this transaction is done.
+ _connection = null; // Set prior to ExecuteTransaction call in case this initiates a TransactionEnd event
+
+ connection.ExecuteTransaction(SqlInternalConnection.TransactionRequest.Commit, null, IsolationLevel.Unspecified, _internalTransaction, true);
+ commitException = null;
+ }
+ catch (SqlException e)
+ {
+ commitException = e;
+
+ // Doom the connection, to make sure that the transaction is
+ // eventually rolled back.
+ // VSTS 144562: doom the connection while having the lock on it to prevent race condition with "Transaction Ended" Event
+ connection.DoomThisConnection();
+ }
+ catch (InvalidOperationException e)
+ {
+ commitException = e;
+ connection.DoomThisConnection();
+ }
+ }
+ if (commitException != null)
+ {
+ // connection.ExecuteTransaction failed with exception
+ if (_internalTransaction.IsCommitted)
+ {
+ // Even though we got an exception, the transaction
+ // was committed by the server.
+ enlistment.Committed();
+ }
+ else if (_internalTransaction.IsAborted)
+ {
+ // The transaction was aborted, report that to
+ // SysTx.
+ enlistment.Aborted(commitException);
+ }
+ else
+ {
+ // The transaction is still active, we cannot
+ // know the state of the transaction.
+ enlistment.InDoubt(commitException);
+ }
+
+ // We eat the exception. This is called on the SysTx
+ // thread, not the applications thread. If we don't
+ // eat the exception an UnhandledException will occur,
+ // causing the process to FailFast.
+ }
+
+ connection.CleanupConnectionOnTransactionCompletion(_atomicTransaction);
+ if (commitException == null)
+ {
+ // connection.ExecuteTransaction succeeded
+ enlistment.Committed();
+ }
+ }
+ }
+ catch (System.OutOfMemoryException e)
+ {
+ usersConnection.Abort(e);
+ throw;
+ }
+ catch (System.StackOverflowException e)
+ {
+ usersConnection.Abort(e);
+ throw;
+ }
+ catch (System.Threading.ThreadAbortException e)
+ {
+ usersConnection.Abort(e);
+ throw;
+ }
+ }
+
+ // Event notification that transaction ended. This comes from the subscription to the Transaction's
+ // ended event via the internal connection. If it occurs without a prior Rollback or SinglePhaseCommit call,
+ // it indicates the transaction was ended externally (generally that one the the DTC participants aborted
+ // the transaction).
+ internal void TransactionEnded(Transaction transaction)
+ {
+ SqlInternalConnection connection = _connection;
+
+ if (connection != null)
+ {
+ lock (connection)
+ {
+ if (_atomicTransaction.Equals(transaction))
+ {
+ // No need to validate active on connection, this operation can be called on completed transactions
+ _active = false;
+ _connection = null;
+ }
+ }
+ }
+ }
+
+ // Check for connection validity
+ private SqlInternalConnection GetValidConnection()
+ {
+ SqlInternalConnection connection = _connection;
+ if (null == connection)
+ {
+ throw ADP.ObjectDisposed(this);
+ }
+
+ return connection;
+ }
+
+ // Dooms connection and throws and error if not a valid, active, delegated transaction for the given
+ // connection. Designed to be called AFTER a lock is placed on the connection, otherwise a normal return
+ // may not be trusted.
+ private void ValidateActiveOnConnection(SqlInternalConnection connection)
+ {
+ bool valid = _active && (connection == _connection) && (connection.DelegatedTransaction == this);
+
+ if (!valid)
+ {
+ // Invalid indicates something BAAAD happened (Commit after TransactionEnded, for instance)
+ // Doom anything remotely involved.
+ if (null != connection)
+ {
+ connection.DoomThisConnection();
+ }
+ if (connection != _connection && null != _connection)
+ {
+ _connection.DoomThisConnection();
+ }
+
+ throw ADP.InternalError(ADP.InternalErrorCode.UnpooledObjectHasWrongOwner); //TODO: Create a new code
+ }
+ }
+
+ // Get the server-side Global Transaction Id from the PromotedDTCToken
+ // Skip first 4 bytes since they contain the version
+ private Guid GetGlobalTxnIdentifierFromToken()
+ {
+ byte[] txnGuid = new byte[16];
+ Array.Copy(_connection.PromotedDTCToken, _globalTransactionsTokenVersionSizeInBytes, // Skip the version
+ txnGuid, 0, txnGuid.Length);
+ return new Guid(txnGuid);
+ }
+ }
+}
diff --git a/src/System.Data.SqlClient/src/System/Data/SqlClient/SqlInternalConnection.cs b/src/System.Data.SqlClient/src/System/Data/SqlClient/SqlInternalConnection.cs
index 80f08d1377..8651a17a32 100644
--- a/src/System.Data.SqlClient/src/System/Data/SqlClient/SqlInternalConnection.cs
+++ b/src/System.Data.SqlClient/src/System/Data/SqlClient/SqlInternalConnection.cs
@@ -9,6 +9,7 @@
using System.Data.Common;
using System.Data.ProviderBase;
using System.Diagnostics;
+using System.Transactions;
namespace System.Data.SqlClient
@@ -16,6 +17,13 @@ namespace System.Data.SqlClient
abstract internal class SqlInternalConnection : DbConnectionInternal
{
private readonly SqlConnectionString _connectionOptions;
+ private bool _isEnlistedInTransaction; // is the server-side connection enlisted? true while we're enlisted, reset only after we send a null...
+ private byte[] _promotedDTCToken; // token returned by the server when we promote transaction
+ private byte[] _whereAbouts; // cache the whereabouts (DTC Address) for exporting
+
+ private bool _isGlobalTransaction = false; // Whether this is a Global Transaction (Non-MSDTC, Azure SQL DB Transaction)
+ private bool _isGlobalTransactionEnabledForServer = false; // Whether Global Transactions are enabled for this Azure SQL DB Server
+ private static readonly Guid _globalTransactionTMID = new Guid("1c742caf-6680-40ea-9c26-6b6846079764"); // ID of the Non-MSDTC, Azure SQL DB Transaction Manager
// if connection is not open: null
// if connection is open: currently active database
@@ -27,10 +35,13 @@ namespace System.Data.SqlClient
// * for connections with FailoverPartner, it is set to the FailoverPartner value from connection string if the connection was opened to it.
internal string CurrentDataSource { get; set; }
+ // the delegated (or promoted) transaction we're responsible for.
+ internal SqlDelegatedTransaction DelegatedTransaction { get; set; }
internal enum TransactionRequest
{
Begin,
+ Promote,
Commit,
Rollback,
IfRollback,
@@ -75,6 +86,28 @@ namespace System.Data.SqlClient
}
}
+ abstract internal SqlInternalTransaction PendingTransaction
+ {
+ get;
+ }
+
+ override protected internal bool IsNonPoolableTransactionRoot
+ {
+ get
+ {
+ return IsTransactionRoot; // default behavior is that root transactions are NOT poolable. Subclasses may override.
+ }
+ }
+
+ override internal bool IsTransactionRoot
+ {
+ get
+ {
+ var delegatedTransaction = DelegatedTransaction;
+ return ((null != delegatedTransaction) && (delegatedTransaction.IsActive));
+ }
+ }
+
internal bool HasLocalTransaction
{
@@ -96,6 +129,13 @@ namespace System.Data.SqlClient
}
}
+ internal bool IsEnlistedInTransaction
+ {
+ get
+ {
+ return _isEnlistedInTransaction;
+ }
+ }
abstract internal bool IsLockedForBulkCopy
{
@@ -108,6 +148,41 @@ namespace System.Data.SqlClient
get;
}
+ internal byte[] PromotedDTCToken
+ {
+ get
+ {
+ return _promotedDTCToken;
+ }
+ set
+ {
+ _promotedDTCToken = value;
+ }
+ }
+
+ internal bool IsGlobalTransaction
+ {
+ get
+ {
+ return _isGlobalTransaction;
+ }
+ set
+ {
+ _isGlobalTransaction = value;
+ }
+ }
+
+ internal bool IsGlobalTransactionsEnabledForServer
+ {
+ get
+ {
+ return _isGlobalTransactionEnabledForServer;
+ }
+ set
+ {
+ _isGlobalTransactionEnabledForServer = value;
+ }
+ }
override public DbTransaction BeginTransaction(IsolationLevel iso)
{
@@ -121,7 +196,6 @@ namespace System.Data.SqlClient
{
statistics = SqlStatistics.StartTimer(Connection.Statistics);
-
ValidateConnectionForExecute(null);
if (HasLocalTransactionFromAPI)
@@ -134,7 +208,7 @@ namespace System.Data.SqlClient
SqlTransaction transaction = new SqlTransaction(this, Connection, iso, AvailableInternalTransaction);
transaction.InternalTransaction.RestoreBrokenConnection = shouldReconnect;
- ExecuteTransaction(TransactionRequest.Begin, transactionName, iso, transaction.InternalTransaction);
+ ExecuteTransaction(TransactionRequest.Begin, transactionName, iso, transaction.InternalTransaction, false);
transaction.InternalTransaction.RestoreBrokenConnection = false;
return transaction;
}
@@ -158,6 +232,16 @@ namespace System.Data.SqlClient
abstract protected void ChangeDatabaseInternal(string database);
+ override protected void CleanupTransactionOnCompletion(Transaction transaction)
+ {
+ // Note: unlocked, potentially multi-threaded code, so pull delegate to local to
+ // ensure it doesn't change between test and call.
+ SqlDelegatedTransaction delegatedTransaction = DelegatedTransaction;
+ if (null != delegatedTransaction)
+ {
+ delegatedTransaction.TransactionEnded(transaction);
+ }
+ }
override protected DbReferenceCollection CreateReferenceCollection()
{
@@ -195,10 +279,285 @@ namespace System.Data.SqlClient
override public void Dispose()
{
+ _whereAbouts = null;
base.Dispose();
}
- abstract internal void ExecuteTransaction(TransactionRequest transactionRequest, string name, IsolationLevel iso, SqlInternalTransaction internalTransaction);
+ protected void Enlist(Transaction tx)
+ {
+ // This method should not be called while the connection has a
+ // reference to an active delegated transaction.
+ // Manual enlistment via SqlConnection.EnlistTransaction
+ // should catch this case and throw an exception.
+ //
+ // Automatic enlistment isn't possible because
+ // Sys.Tx keeps the connection alive until the transaction is completed.
+ Debug.Assert(!IsNonPoolableTransactionRoot, "cannot defect an active delegated transaction!"); // potential race condition, but it's an assert
+
+ if (null == tx)
+ {
+ if (IsEnlistedInTransaction)
+ {
+ EnlistNull();
+ }
+ else
+ {
+ // When IsEnlistedInTransaction is false, it means we are in one of two states:
+ // 1. EnlistTransaction is null, so the connection is truly not enlisted in a transaction, or
+ // 2. Connection is enlisted in a SqlDelegatedTransaction.
+ //
+ // For #2, we have to consider whether or not the delegated transaction is active.
+ // If it is not active, we allow the enlistment in the NULL transaction.
+ //
+ // If it is active, technically this is an error.
+ // However, no exception is thrown as this was the precedent (and this case is silently ignored, no error, but no enlistment either).
+ // There are two mitigations for this:
+ // 1. SqlConnection.EnlistTransaction checks that the enlisted transaction has completed before allowing a different enlistment.
+ // 2. For debug builds, the assert at the beginning of this method checks for an enlistment in an active delegated transaction.
+ Transaction enlistedTransaction = EnlistedTransaction;
+ if (enlistedTransaction != null && enlistedTransaction.TransactionInformation.Status != TransactionStatus.Active)
+ {
+ EnlistNull();
+ }
+ }
+ }
+ // Only enlist if it's different...
+ else if (!tx.Equals(EnlistedTransaction))
+ { // WebData 20000024 - Must use Equals, not !=
+ EnlistNonNull(tx);
+ }
+ }
+
+ private void EnlistNonNull(Transaction tx)
+ {
+ Debug.Assert(null != tx, "null transaction?");
+
+ bool hasDelegatedTransaction = false;
+
+ // Promotable transactions are only supported on Yukon
+ // servers or newer.
+ SqlDelegatedTransaction delegatedTransaction = new SqlDelegatedTransaction(this, tx);
+
+ try
+ {
+ // NOTE: System.Transactions claims to resolve all
+ // potential race conditions between multiple delegate
+ // requests of the same transaction to different
+ // connections in their code, such that only one
+ // attempt to delegate will succeed.
+
+ // NOTE: PromotableSinglePhaseEnlist will eventually
+ // make a round trip to the server; doing this inside
+ // a lock is not the best choice. We presume that you
+ // aren't trying to enlist concurrently on two threads
+ // and leave it at that -- We don't claim any thread
+ // safety with regard to multiple concurrent requests
+ // to enlist the same connection in different
+ // transactions, which is good, because we don't have
+ // it anyway.
+
+ // PromotableSinglePhaseEnlist may not actually promote
+ // the transaction when it is already delegated (this is
+ // the way they resolve the race condition when two
+ // threads attempt to delegate the same Lightweight
+ // Transaction) In that case, we can safely ignore
+ // our delegated transaction, and proceed to enlist
+ // in the promoted one.
+
+ // NOTE: Global Transactions is an Azure SQL DB only
+ // feature where the Transaction Manager (TM) is not
+ // MS-DTC. Sys.Tx added APIs to support Non MS-DTC
+ // promoter types/TM in .NET 4.6.1. Following directions
+ // from .NETFX shiproom, to avoid a "hard-dependency"
+ // (compile time) on Sys.Tx, we use reflection to invoke
+ // the new APIs. Further, the _isGlobalTransaction flag
+ // indicates that this is an Azure SQL DB Transaction
+ // that could be promoted to a Global Transaction (it's
+ // always false for on-prem Sql Server). The Promote()
+ // call in SqlDelegatedTransaction makes sure that the
+ // right Sys.Tx.dll is loaded and that Global Transactions
+ // are actually allowed for this Azure SQL DB.
+
+ if (_isGlobalTransaction)
+ {
+ if (SysTxForGlobalTransactions.EnlistPromotableSinglePhase == null)
+ {
+ // This could be a local Azure SQL DB transaction.
+ hasDelegatedTransaction = tx.EnlistPromotableSinglePhase(delegatedTransaction);
+ }
+ else
+ {
+ hasDelegatedTransaction = (bool)SysTxForGlobalTransactions.EnlistPromotableSinglePhase.Invoke(tx, new object[] { delegatedTransaction, _globalTransactionTMID });
+ }
+ }
+ else
+ {
+ // This is an MS-DTC distributed transaction
+ hasDelegatedTransaction = tx.EnlistPromotableSinglePhase(delegatedTransaction);
+ }
+
+ if (hasDelegatedTransaction)
+ {
+ this.DelegatedTransaction = delegatedTransaction;
+ }
+ }
+ catch (SqlException e)
+ {
+ // we do not want to eat the error if it is a fatal one
+ if (e.Class >= TdsEnums.FATAL_ERROR_CLASS)
+ {
+ throw;
+ }
+
+ // if the parser is null or its state is not openloggedin, the connection is no longer good.
+ SqlInternalConnectionTds tdsConnection = this as SqlInternalConnectionTds;
+ if (tdsConnection != null)
+ {
+ TdsParser parser = tdsConnection.Parser;
+ if (parser == null || parser.State != TdsParserState.OpenLoggedIn)
+ {
+ throw;
+ }
+ }
+
+ // In this case, SqlDelegatedTransaction.Initialize
+ // failed and we don't necessarily want to reject
+ // things -- there may have been a legitimate reason
+ // for the failure.
+ }
+
+ if (!hasDelegatedTransaction)
+ {
+ byte[] cookie = null;
+
+ if (_isGlobalTransaction)
+ {
+ if (SysTxForGlobalTransactions.GetPromotedToken == null)
+ {
+ throw SQL.UnsupportedSysTxForGlobalTransactions();
+ }
+
+ cookie = (byte[])SysTxForGlobalTransactions.GetPromotedToken.Invoke(tx, null);
+ }
+ else
+ {
+ if (null == _whereAbouts)
+ {
+ byte[] dtcAddress = GetDTCAddress();
+
+ if (null == dtcAddress)
+ {
+ throw SQL.CannotGetDTCAddress();
+ }
+ _whereAbouts = dtcAddress;
+ }
+ cookie = GetTransactionCookie(tx, _whereAbouts);
+ }
+
+ // send cookie to server to finish enlistment
+ PropagateTransactionCookie(cookie);
+
+ _isEnlistedInTransaction = true;
+ }
+
+ EnlistedTransaction = tx; // Tell the base class about our enlistment
+
+
+ // If we're on a Yukon or newer server, and we we delegate the
+ // transaction successfully, we will have done a begin transaction,
+ // which produces a transaction id that we should execute all requests
+ // on. The TdsParser or SmiEventSink will store this information as
+ // the current transaction.
+ //
+ // Likewise, propagating a transaction to a Yukon or newer server will
+ // produce a transaction id that The TdsParser or SmiEventSink will
+ // store as the current transaction.
+ //
+ // In either case, when we're working with a Yukon or newer server
+ // we better have a current transaction by now.
+
+ Debug.Assert(null != CurrentTransaction, "delegated/enlisted transaction with null current transaction?");
+ }
+
+ internal void EnlistNull()
+ {
+ // We were in a transaction, but now we are not - so send
+ // message to server with empty transaction - confirmed proper
+ // behavior from Sameet Agarwal
+ //
+ // The connection pooler maintains separate pools for enlisted
+ // transactions, and only when that transaction is committed or
+ // rolled back will those connections be taken from that
+ // separate pool and returned to the general pool of connections
+ // that are not affiliated with any transactions. When this
+ // occurs, we will have a new transaction of null and we are
+ // required to send an empty transaction payload to the server.
+
+ PropagateTransactionCookie(null);
+
+ _isEnlistedInTransaction = false;
+ EnlistedTransaction = null; // Tell the base class about our enlistment
+
+ // The EnlistTransaction above will return an TransactionEnded event,
+ // which causes the TdsParser or SmiEventSink should to clear the
+ // current transaction.
+ //
+ // In either case, when we're working with a Yukon or newer server
+ // we better not have a current transaction at this point.
+
+ Debug.Assert(null == CurrentTransaction, "unenlisted transaction with non-null current transaction?"); // verify it!
+ }
+
+ override public void EnlistTransaction(Transaction transaction)
+ {
+ ValidateConnectionForExecute(null);
+
+ // If a connection has a local transaction outstanding and you try
+ // to enlist in a DTC transaction, SQL Server will rollback the
+ // local transaction and then do the enlist (7.0 and 2000). So, if
+ // the user tries to do this, throw.
+ if (HasLocalTransaction)
+ {
+ throw ADP.LocalTransactionPresent();
+ }
+
+ if (null != transaction && transaction.Equals(EnlistedTransaction))
+ {
+ // No-op if this is the current transaction
+ return;
+ }
+
+ // If a connection is already enlisted in a DTC transaction and you
+ // try to enlist in another one, in 7.0 the existing DTC transaction
+ // would roll back and then the connection would enlist in the new
+ // one. In SQL 2000 & Yukon, when you enlist in a DTC transaction
+ // while the connection is already enlisted in a DTC transaction,
+ // the connection simply switches enlistments. Regardless, simply
+ // enlist in the user specified distributed transaction. This
+ // behavior matches OLEDB and ODBC.
+
+ try
+ {
+ Enlist(transaction);
+ }
+ catch (System.OutOfMemoryException e)
+ {
+ Connection.Abort(e);
+ throw;
+ }
+ catch (System.StackOverflowException e)
+ {
+ Connection.Abort(e);
+ throw;
+ }
+ catch (System.Threading.ThreadAbortException e)
+ {
+ Connection.Abort(e);
+ throw;
+ }
+ }
+
+ abstract internal void ExecuteTransaction(TransactionRequest transactionRequest, string name, IsolationLevel iso, SqlInternalTransaction internalTransaction, bool isDelegateControlRequest);
internal SqlDataReader FindLiveReader(SqlCommand command)
{
@@ -222,6 +581,17 @@ namespace System.Data.SqlClient
return command;
}
+ abstract protected byte[] GetDTCAddress();
+
+ static private byte[] GetTransactionCookie(Transaction transaction, byte[] whereAbouts)
+ {
+ byte[] transactionCookie = null;
+ if (null != transaction)
+ {
+ transactionCookie = TransactionInterop.GetExportCookie(transaction, whereAbouts);
+ }
+ return transactionCookie;
+ }
virtual protected void InternalDeactivate()
{
@@ -249,6 +619,7 @@ namespace System.Data.SqlClient
}
}
+ abstract protected void PropagateTransactionCookie(byte[] transactionCookie);
abstract internal void ValidateConnectionForExecute(SqlCommand command);
}
diff --git a/src/System.Data.SqlClient/src/System/Data/SqlClient/SqlInternalConnectionTds.cs b/src/System.Data.SqlClient/src/System/Data/SqlClient/SqlInternalConnectionTds.cs
index 8d71238057..3e7346dbf2 100644
--- a/src/System.Data.SqlClient/src/System/Data/SqlClient/SqlInternalConnectionTds.cs
+++ b/src/System.Data.SqlClient/src/System/Data/SqlClient/SqlInternalConnectionTds.cs
@@ -14,6 +14,7 @@ using System.Globalization;
using System.Threading;
using System.Diagnostics.CodeAnalysis;
using System.Threading.Tasks;
+using System.Transactions;
namespace System.Data.SqlClient
{
@@ -424,7 +425,7 @@ namespace System.Data.SqlClient
}
}
- override internal SqlInternalTransaction CurrentTransaction
+ internal override SqlInternalTransaction CurrentTransaction
{
get
{
@@ -432,7 +433,7 @@ namespace System.Data.SqlClient
}
}
- override internal SqlInternalTransaction AvailableInternalTransaction
+ internal override SqlInternalTransaction AvailableInternalTransaction
{
get
{
@@ -440,7 +441,13 @@ namespace System.Data.SqlClient
}
}
-
+ internal override SqlInternalTransaction PendingTransaction
+ {
+ get
+ {
+ return _parser.PendingTransaction;
+ }
+ }
internal DbConnectionPoolIdentity Identity
{
@@ -458,7 +465,7 @@ namespace System.Data.SqlClient
}
}
- override internal bool IsLockedForBulkCopy
+ internal override bool IsLockedForBulkCopy
{
get
{
@@ -466,8 +473,15 @@ namespace System.Data.SqlClient
}
}
+ internal protected override bool IsNonPoolableTransactionRoot
+ {
+ get
+ {
+ return IsTransactionRoot && (!IsKatmaiOrNewer || null == Pool);
+ }
+ }
- override internal bool IsKatmaiOrNewer
+ internal override bool IsKatmaiOrNewer
{
get
{
@@ -507,8 +521,16 @@ namespace System.Data.SqlClient
}
}
+ protected override bool ReadyToPrepareTransaction
+ {
+ get
+ {
+ bool result = (null == FindLiveReader(null)); // can't prepare with a live data reader...
+ return result;
+ }
+ }
- override public string ServerVersion
+ public override string ServerVersion
{
get
{
@@ -517,13 +539,20 @@ namespace System.Data.SqlClient
}
}
+ protected override bool UnbindOnTransactionCompletion
+ {
+ get
+ {
+ return false;
+ }
+ }
////////////////////////////////////////////////////////////////////////////////////////
// GENERAL METHODS
////////////////////////////////////////////////////////////////////////////////////////
[SuppressMessage("Microsoft.Globalization", "CA1303:DoNotPassLiteralsAsLocalizedParameters")] // copied from Triaged.cs
- override protected void ChangeDatabaseInternal(string database)
+ protected override void ChangeDatabaseInternal(string database)
{
// Add brackets around database
database = SqlConnection.FixupDatabaseTransactionName(database);
@@ -532,7 +561,7 @@ namespace System.Data.SqlClient
_parser.Run(RunBehavior.UntilDone, null, null, null, _parser._physicalStateObj);
}
- override public void Dispose()
+ public override void Dispose()
{
try
{
@@ -554,7 +583,7 @@ namespace System.Data.SqlClient
base.Dispose();
}
- override internal void ValidateConnectionForExecute(SqlCommand command)
+ internal override void ValidateConnectionForExecute(SqlCommand command)
{
TdsParser parser = _parser;
if ((parser == null) || (parser.State == TdsParserState.Broken) || (parser.State == TdsParserState.Closed))
@@ -596,6 +625,64 @@ namespace System.Data.SqlClient
}
}
+ /// <summary>
+ /// Validate the enlisted transaction state, taking into consideration the ambient transaction and transaction unbinding mode.
+ /// If there is no enlisted transaction, this method is a nop.
+ /// </summary>
+ /// <remarks>
+ /// <para>
+ /// This method must be called while holding a lock on the SqlInternalConnection instance,
+ /// to ensure we don't accidentally execute after the transaction has completed on a different thread,
+ /// causing us to unwittingly execute in auto-commit mode.
+ /// </para>
+ ///
+ /// <para>
+ /// When using Explicit transaction unbinding,
+ /// verify that the enlisted transaction is active and equal to the current ambient transaction.
+ /// </para>
+ ///
+ /// <para>
+ /// When using Implicit transaction unbinding,
+ /// verify that the enlisted transaction is active.
+ /// If it is not active, and the transaction object has been diposed, unbind from the transaction.
+ /// If it is not active and not disposed, throw an exception.
+ /// </para>
+ /// </remarks>
+ internal void CheckEnlistedTransactionBinding()
+ {
+ // If we are enlisted in a transaction, check that transaction is active.
+ // When using explicit transaction unbinding, also verify that the enlisted transaction is the current transaction.
+ Transaction enlistedTransaction = EnlistedTransaction;
+
+ if (enlistedTransaction != null)
+ {
+ bool requireExplicitTransactionUnbind = ConnectionOptions.TransactionBinding == SqlConnectionString.TransactionBindingEnum.ExplicitUnbind;
+
+ if (requireExplicitTransactionUnbind)
+ {
+ Transaction currentTransaction = Transaction.Current;
+
+ if (TransactionStatus.Active != enlistedTransaction.TransactionInformation.Status || !enlistedTransaction.Equals(currentTransaction))
+ {
+ throw ADP.TransactionConnectionMismatch();
+ }
+ }
+ else // implicit transaction unbind
+ {
+ if (TransactionStatus.Active != enlistedTransaction.TransactionInformation.Status)
+ {
+ if (EnlistedTransactionDisposed)
+ {
+ DetachTransaction(enlistedTransaction, true);
+ }
+ else
+ {
+ throw ADP.TransactionCompletedButNotDisposed();
+ }
+ }
+ }
+ }
+ }
internal override bool IsConnectionAlive(bool throwOnException)
{
@@ -608,11 +695,30 @@ namespace System.Data.SqlClient
// POOLING METHODS
////////////////////////////////////////////////////////////////////////////////////////
- override protected void Activate()
+ protected override void Activate(Transaction transaction)
{
+ // When we're required to automatically enlist in transactions and
+ // there is one we enlist in it. On the other hand, if there isn't a
+ // transaction and we are currently enlisted in one, then we
+ // unenlist from it.
+ //
+ // Regardless of whether we're required to automatically enlist,
+ // when there is not a current transaction, we cannot leave the
+ // connection enlisted in a transaction.
+ if (null != transaction)
+ {
+ if (ConnectionOptions.Enlist)
+ {
+ Enlist(transaction);
+ }
+ }
+ else
+ {
+ Enlist(null);
+ }
}
- override protected void InternalDeactivate()
+ protected override void InternalDeactivate()
{
// When we're deactivated, the user must have called End on all
// the async commands, or we don't know that we're in a state that
@@ -628,14 +734,17 @@ namespace System.Data.SqlClient
// cause our transaction to be rolled back and the connection
// to be reset. We'll get called again once the delegated
// transaction is completed and we can do it all then.
- Debug.Assert(null != _parser || IsConnectionDoomed, "Deactivating a disposed connection?");
- if (_parser != null)
+ if (!IsNonPoolableTransactionRoot)
{
- _parser.Deactivate(IsConnectionDoomed);
-
- if (!IsConnectionDoomed)
+ Debug.Assert(null != _parser || IsConnectionDoomed, "Deactivating a disposed connection?");
+ if (_parser != null)
{
- ResetConnection();
+ _parser.Deactivate(IsConnectionDoomed);
+
+ if (!IsConnectionDoomed)
+ {
+ ResetConnection();
+ }
}
}
}
@@ -657,7 +766,7 @@ namespace System.Data.SqlClient
// distributed transaction - otherwise don't reset!
// Prepare the parser for the connection reset - the next time a trip
// to the server is made.
- _parser.PrepareResetConnection();
+ _parser.PrepareResetConnection(IsTransactionRoot && !IsNonPoolableTransactionRoot);
// Reset dictionary values, since calling reset will not send us env_changes.
CurrentDatabase = _originalDatabase;
@@ -680,7 +789,7 @@ namespace System.Data.SqlClient
// LOCAL TRANSACTION METHODS
////////////////////////////////////////////////////////////////////////////////////////
- override internal void DisconnectTransaction(SqlInternalTransaction internalTransaction)
+ internal override void DisconnectTransaction(SqlInternalTransaction internalTransaction)
{
TdsParser parser = Parser;
@@ -690,7 +799,12 @@ namespace System.Data.SqlClient
}
}
- override internal void ExecuteTransaction(TransactionRequest transactionRequest, string name, IsolationLevel iso, SqlInternalTransaction internalTransaction)
+ internal void ExecuteTransaction(TransactionRequest transactionRequest, string name, IsolationLevel iso)
+ {
+ ExecuteTransaction(transactionRequest, name, iso, null, false);
+ }
+
+ internal override void ExecuteTransaction(TransactionRequest transactionRequest, string name, IsolationLevel iso, SqlInternalTransaction internalTransaction, bool isDelegateControlRequest)
{
if (IsConnectionDoomed)
{ // doomed means we can't do anything else...
@@ -714,7 +828,7 @@ namespace System.Data.SqlClient
string transactionName = (null == name) ? String.Empty : name;
- ExecuteTransactionYukon(transactionRequest, transactionName, iso, internalTransaction);
+ ExecuteTransactionYukon(transactionRequest, transactionName, iso, internalTransaction, isDelegateControlRequest);
}
@@ -722,7 +836,8 @@ namespace System.Data.SqlClient
TransactionRequest transactionRequest,
string transactionName,
IsolationLevel iso,
- SqlInternalTransaction internalTransaction
+ SqlInternalTransaction internalTransaction,
+ bool isDelegateControlRequest
)
{
TdsEnums.TransactionManagerRequestType requestType = TdsEnums.TransactionManagerRequestType.Begin;
@@ -773,6 +888,9 @@ namespace System.Data.SqlClient
case TransactionRequest.Begin:
requestType = TdsEnums.TransactionManagerRequestType.Begin;
break;
+ case TransactionRequest.Promote:
+ requestType = TdsEnums.TransactionManagerRequestType.Promote;
+ break;
case TransactionRequest.Commit:
requestType = TdsEnums.TransactionManagerRequestType.Commit;
break;
@@ -808,14 +926,39 @@ namespace System.Data.SqlClient
}
}
-
-
+ // SQLBUDT #20010853 - Promote, Commit and Rollback requests for
+ // delegated transactions often happen while there is an open result
+ // set, so we need to handle them by using a different MARS session,
+ // otherwise we'll write on the physical state objects while someone
+ // else is using it. When we don't have MARS enabled, we need to
+ // lock the physical state object to syncronize it's use at least
+ // until we increment the open results count. Once it's been
+ // incremented the delegated transaction requests will fail, so they
+ // won't stomp on anything.
+ //
+ // We need to keep this lock through the duration of the TM reqeuest
+ // so that we won't hijack a different request's data stream and a
+ // different request won't hijack ours, so we have a lock here on
+ // an object that the ExecTMReq will also lock, but since we're on
+ // the same thread, the lock is a no-op.
+
+ if (null != internalTransaction && internalTransaction.IsDelegated)
+ {
+ if (_parser.MARSOn)
+ {
+ stateObj = _parser.GetSession(this);
+ mustPutSession = true;
+ }
+ else if (internalTransaction.OpenResultsCount != 0)
+ {
+ //throw SQL.CannotCompleteDelegatedTransactionWithOpenResults(this);
+ }
+ }
// _parser may be nulled out during TdsExecuteTrannsactionManagerRequest.
// Only use local variable after this call.
_parser.TdsExecuteTransactionManagerRequest(null, requestType, transactionName, isoLevel,
- ConnectionOptions.ConnectTimeout, internalTransaction, stateObj
- );
+ ConnectionOptions.ConnectTimeout, internalTransaction, stateObj, isDelegateControlRequest);
}
finally
{
@@ -836,6 +979,22 @@ namespace System.Data.SqlClient
// DISTRIBUTED TRANSACTION METHODS
////////////////////////////////////////////////////////////////////////////////////////
+ internal override void DelegatedTransactionEnded()
+ {
+ base.DelegatedTransactionEnded();
+ }
+
+ protected override byte[] GetDTCAddress()
+ {
+ byte[] dtcAddress = _parser.GetDTCAddress(ConnectionOptions.ConnectTimeout, _parser.GetSession(this));
+ Debug.Assert(null != dtcAddress, "null dtcAddress?");
+ return dtcAddress;
+ }
+
+ protected override void PropagateTransactionCookie(byte[] cookie)
+ {
+ _parser.PropagateDistributedTransaction(cookie, ConnectionOptions.ConnectTimeout, _parser._physicalStateObj);
+ }
////////////////////////////////////////////////////////////////////////////////////////
// LOGIN-RELATED METHODS
@@ -882,6 +1041,15 @@ namespace System.Data.SqlClient
_fConnectionOpen = true; // mark connection as open
+ // for non-pooled connections, enlist in a distributed transaction
+ // if present - and user specified to enlist
+ if (enlistOK && ConnectionOptions.Enlist)
+ {
+ _parser._physicalStateObj.SniContext = SniContext.Snix_AutoEnlist;
+ Transaction tx = ADP.GetCurrentTransaction();
+ Enlist(tx);
+ }
+
_parser._physicalStateObj.SniContext = SniContext.Snix_Login;
}
@@ -940,6 +1108,8 @@ namespace System.Data.SqlClient
_sessionRecoveryRequested = true;
}
+ // The GLOBALTRANSACTIONS feature is implicitly requested
+ requestedFeatures |= TdsEnums.FeatureExtension.GlobalTransactions;
_parser.TdsLogin(login, requestedFeatures, _recoverySessionData);
}
@@ -1554,6 +1724,8 @@ namespace System.Data.SqlClient
case TdsEnums.ENV_BEGINTRAN:
case TdsEnums.ENV_COMMITTRAN:
case TdsEnums.ENV_ROLLBACKTRAN:
+ case TdsEnums.ENV_ENLISTDTC:
+ case TdsEnums.ENV_DEFECTDTC:
// only used on parser
break;
@@ -1565,6 +1737,16 @@ namespace System.Data.SqlClient
_currentFailoverPartner = rec.newValue;
break;
+ case TdsEnums.ENV_PROMOTETRANSACTION:
+ PromotedDTCToken = rec.newBinValue;
+ break;
+
+ case TdsEnums.ENV_TRANSACTIONENDED:
+ break;
+
+ case TdsEnums.ENV_TRANSACTIONMANAGERADDRESS:
+ // For now we skip these Yukon only env change notifications
+ break;
case TdsEnums.ENV_SPRESETCONNECTIONACK:
// connection is being reset
@@ -1586,15 +1768,6 @@ namespace System.Data.SqlClient
_routingInfo = rec.newRoutingInfo;
break;
- // ENVCHANGE tokens not supported by Project K\CoreCLR
- case TdsEnums.ENV_ENLISTDTC:
- case TdsEnums.ENV_DEFECTDTC:
- case TdsEnums.ENV_TRANSACTIONENDED:
- case TdsEnums.ENV_PROMOTETRANSACTION:
- case TdsEnums.ENV_TRANSACTIONMANAGERADDRESS:
- Debug.Assert(false, "Unsupported tokens were passed to OnEnvChange - TdsParser should have failed these");
- break;
-
default:
Debug.Assert(false, "Missed token in EnvChange!");
break;
@@ -1670,6 +1843,22 @@ namespace System.Data.SqlClient
}
break;
}
+
+ case TdsEnums.FEATUREEXT_GLOBALTRANSACTIONS:
+ {
+ if (data.Length < 1)
+ {
+ throw SQL.ParsingError();
+ }
+
+ IsGlobalTransaction = true;
+ if (1 == data[0])
+ {
+ IsGlobalTransactionsEnabledForServer = true;
+ }
+ break;
+ }
+
default:
{
// Unknown feature ack
diff --git a/src/System.Data.SqlClient/src/System/Data/SqlClient/SqlUtil.cs b/src/System.Data.SqlClient/src/System/Data/SqlClient/SqlUtil.cs
index fe895721ea..d82cc052fc 100644
--- a/src/System.Data.SqlClient/src/System/Data/SqlClient/SqlUtil.cs
+++ b/src/System.Data.SqlClient/src/System/Data/SqlClient/SqlUtil.cs
@@ -10,6 +10,8 @@ using System.Runtime.ExceptionServices;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
+using System.Reflection;
+using System.Transactions;
namespace System.Data.SqlClient
{
@@ -157,6 +159,10 @@ namespace System.Data.SqlClient
//
// SQL.Connection
//
+ internal static Exception CannotGetDTCAddress()
+ {
+ return ADP.InvalidOperation(SR.GetString(SR.SQL_CannotGetDTCAddress));
+ }
internal static Exception InvalidInternalPacketSize(string str)
{
@@ -198,6 +204,20 @@ namespace System.Data.SqlClient
{
return ADP.InvalidOperation(SR.GetString(SR.SQL_InstanceFailure));
}
+
+ //
+ // Global Transactions.
+ //
+ internal static Exception GlobalTransactionsNotEnabled()
+ {
+ return ADP.InvalidOperation(SR.GetString(SR.GT_Disabled));
+ }
+ internal static Exception UnknownSysTxIsolationLevel(Transactions.IsolationLevel isolationLevel)
+ {
+ return ADP.InvalidOperation(SR.GetString(SR.SQL_UnknownSysTxIsolationLevel, isolationLevel.ToString()));
+ }
+
+
internal static Exception InvalidPartnerConfiguration(string server, string database)
{
return ADP.InvalidOperation(SR.GetString(SR.SQL_InvalidPartnerConfiguration, server, database));
@@ -462,6 +482,17 @@ namespace System.Data.SqlClient
}
//
+ // SQL.SqlDelegatedTransaction
+ //
+ internal static TransactionPromotionException PromotionFailed(Exception inner)
+ {
+ TransactionPromotionException e = new TransactionPromotionException(SR.GetString(SR.SqlDelegatedTransaction_PromotionFailed), inner);
+ ADP.TraceExceptionAsReturnValue(e);
+ return e;
+ }
+ //Failure while attempting to promote transaction.
+
+ //
// SQL.SqlMetaData
//
internal static Exception InvalidSqlDbTypeForConstructor(SqlDbType type)
@@ -613,6 +644,11 @@ namespace System.Data.SqlClient
return ADP.InvalidOperation(SR.GetString(SR.SQL_OpenResultCountExceeded));
}
+ internal static Exception UnsupportedSysTxForGlobalTransactions()
+ {
+ return ADP.InvalidOperation(SR.GetString(SR.SQL_UnsupportedSysTxVersion));
+ }
+
internal static readonly byte[] AttentionHeader = new byte[] {
TdsEnums.MT_ATTN, // Message Type
TdsEnums.ST_EOM, // Status
@@ -1050,4 +1086,56 @@ namespace System.Data.SqlClient
}
}
}
+
+ /// <summary>
+ /// This class holds methods invoked on System.Transactions through reflection for Global Transactions
+ /// </summary>
+ static internal class SysTxForGlobalTransactions
+ {
+ private static readonly Lazy<MethodInfo> _enlistPromotableSinglePhase = new Lazy<MethodInfo>(() =>
+ typeof(Transaction).GetMethod("EnlistPromotableSinglePhase", new Type[] { typeof(IPromotableSinglePhaseNotification), typeof(Guid) }));
+
+ private static readonly Lazy<MethodInfo> _setDistributedTransactionIdentifier = new Lazy<MethodInfo>(() =>
+ typeof(Transaction).GetMethod("SetDistributedTransactionIdentifier", new Type[] { typeof(IPromotableSinglePhaseNotification), typeof(Guid) }));
+
+ private static readonly Lazy<MethodInfo> _getPromotedToken = new Lazy<MethodInfo>(() =>
+ typeof(Transaction).GetMethod("GetPromotedToken"));
+
+ /// <summary>
+ /// Enlists the given IPromotableSinglePhaseNotification and Non-MSDTC Promoter type into a transaction
+ /// </summary>
+ /// <returns>The MethodInfo instance to be invoked. Null if the method doesn't exist</returns>
+ public static MethodInfo EnlistPromotableSinglePhase
+ {
+ get
+ {
+ return _enlistPromotableSinglePhase.Value;
+ }
+ }
+
+ /// <summary>
+ /// Sets the given DistributedTransactionIdentifier for a Transaction instance.
+ /// Needs to be invoked when using a Non-MSDTC Promoter type
+ /// </summary>
+ /// <returns>The MethodInfo instance to be invoked. Null if the method doesn't exist</returns>
+ public static MethodInfo SetDistributedTransactionIdentifier
+ {
+ get
+ {
+ return _setDistributedTransactionIdentifier.Value;
+ }
+ }
+
+ /// <summary>
+ /// Gets the Promoted Token for a Transaction
+ /// </summary>
+ /// <returns>The MethodInfo instance to be invoked. Null if the method doesn't exist</returns>
+ public static MethodInfo GetPromotedToken
+ {
+ get
+ {
+ return _getPromotedToken.Value;
+ }
+ }
+ }
}//namespace
diff --git a/src/System.Data.SqlClient/src/System/Data/SqlClient/TdsEnums.cs b/src/System.Data.SqlClient/src/System/Data/SqlClient/TdsEnums.cs
index 37bab8acd3..14efc67378 100644
--- a/src/System.Data.SqlClient/src/System/Data/SqlClient/TdsEnums.cs
+++ b/src/System.Data.SqlClient/src/System/Data/SqlClient/TdsEnums.cs
@@ -204,12 +204,14 @@ namespace System.Data.SqlClient
// Feature Extension
public const byte FEATUREEXT_TERMINATOR = 0xFF;
public const byte FEATUREEXT_SRECOVERY = 0x01;
+ public const byte FEATUREEXT_GLOBALTRANSACTIONS = 0x05;
[Flags]
public enum FeatureExtension : uint
{
None = 0,
SessionRecovery = 1,
+ GlobalTransactions = 8,
}
@@ -828,7 +830,10 @@ namespace System.Data.SqlClient
internal enum TransactionManagerRequestType
{
+ GetDTCAddress = 0,
+ Propagate = 1,
Begin = 5,
+ Promote = 6,
Commit = 7,
Rollback = 8,
Save = 9
diff --git a/src/System.Data.SqlClient/src/System/Data/SqlClient/TdsParser.cs b/src/System.Data.SqlClient/src/System/Data/SqlClient/TdsParser.cs
index 5a561b35fa..a065427699 100644
--- a/src/System.Data.SqlClient/src/System/Data/SqlClient/TdsParser.cs
+++ b/src/System.Data.SqlClient/src/System/Data/SqlClient/TdsParser.cs
@@ -57,6 +57,7 @@ namespace System.Data.SqlClient
private string _server = ""; // name of server that the parser connects to
internal volatile bool _fResetConnection = false; // flag to denote whether we are needing to call sp_reset
+ internal volatile bool _fPreserveTransaction = false; // flag to denote whether we need to preserve the transaction when reseting
private SqlCollation _defaultCollation; // default collation from the server
@@ -73,6 +74,9 @@ namespace System.Data.SqlClient
private SqlInternalTransaction _currentTransaction;
private SqlInternalTransaction _pendingTransaction; // pending transaction for Yukon and beyond.
+ // need to hold on to the transaction id if distributed transaction merely rolls back without defecting.
+ private long _retainedTransactionId = SqlInternalTransaction.NullTransactionId;
+
// This counter is used for the entire connection to track the open result count for all
// operations not under a transaction.
private int _nonTransactedOpenResultCount = 0;
@@ -1271,6 +1275,12 @@ namespace System.Data.SqlClient
Debug.Assert(!stateObj._fResetConnectionSent, "Unexpected state for sending reset connection");
+ if (_fPreserveTransaction)
+ {
+ // if we are reseting, set bit in header by or'ing with other value
+ stateObj._outBuff[1] = (Byte)(stateObj._outBuff[1] | TdsEnums.ST_RESET_CONNECTION_PRESERVE_TRANSACTION);
+ }
+ else
{
// if we are reseting, set bit in header by or'ing with other value
stateObj._outBuff[1] = (Byte)(stateObj._outBuff[1] | TdsEnums.ST_RESET_CONNECTION);
@@ -1279,6 +1289,7 @@ namespace System.Data.SqlClient
if (!_fMARS)
{
_fResetConnection = false; // If not MARS, can turn off flag now.
+ _fPreserveTransaction = false;
}
else
{
@@ -1460,10 +1471,11 @@ namespace System.Data.SqlClient
stateObj.WriteByteArray(bytes, bytes.Length, 0);
}
- internal void PrepareResetConnection()
+ internal void PrepareResetConnection(bool preserveTransaction)
{
// Set flag to reset connection upon next use - only for use on shiloh!
_fResetConnection = true;
+ _fPreserveTransaction = preserveTransaction;
}
@@ -1812,6 +1824,7 @@ namespace System.Data.SqlClient
switch (env[ii].type)
{
case TdsEnums.ENV_BEGINTRAN:
+ case TdsEnums.ENV_ENLISTDTC:
// When we get notification from the server of a new
// transaction, we move any pending transaction over to
// the current transaction, then we store the token in it.
@@ -1835,8 +1848,14 @@ namespace System.Data.SqlClient
_statistics.SafeIncrement(ref _statistics._transactions);
}
_statisticsIsInTransaction = true;
+ _retainedTransactionId = SqlInternalTransaction.NullTransactionId;
break;
+ case TdsEnums.ENV_DEFECTDTC:
+ case TdsEnums.ENV_TRANSACTIONENDED:
case TdsEnums.ENV_COMMITTRAN:
+ // Must clear the retain id if the server-side transaction ends by anything other
+ // than rollback.
+ _retainedTransactionId = SqlInternalTransaction.NullTransactionId;
goto case TdsEnums.ENV_ROLLBACKTRAN;
case TdsEnums.ENV_ROLLBACKTRAN:
// When we get notification of a completed transaction
@@ -1857,6 +1876,13 @@ namespace System.Data.SqlClient
}
else if (TdsEnums.ENV_ROLLBACKTRAN == env[ii].type)
{
+ // Hold onto transaction id if distributed tran is rolled back. This must
+ // be sent to the server on subsequent executions even though the transaction
+ // is considered to be rolled back.
+ if (_currentTransaction.IsDistributed && _currentTransaction.IsActive)
+ {
+ _retainedTransactionId = env[ii].oldLongValue;
+ }
_currentTransaction.Completed(TransactionState.Aborted);
}
else
@@ -1867,11 +1893,7 @@ namespace System.Data.SqlClient
}
_statisticsIsInTransaction = false;
break;
- case TdsEnums.ENV_ENLISTDTC:
- case TdsEnums.ENV_DEFECTDTC:
- case TdsEnums.ENV_TRANSACTIONENDED:
- Debug.Fail("Should have thrown if DTC token encountered");
- break;
+
default:
_connHandler.OnEnvChange(env[ii]);
break;
@@ -2264,7 +2286,9 @@ namespace System.Data.SqlClient
case TdsEnums.ENV_BEGINTRAN:
case TdsEnums.ENV_COMMITTRAN:
case TdsEnums.ENV_ROLLBACKTRAN:
-
+ case TdsEnums.ENV_ENLISTDTC:
+ case TdsEnums.ENV_DEFECTDTC:
+ case TdsEnums.ENV_TRANSACTIONENDED:
if (!stateObj.TryReadByte(out byteLength))
{
return false;
@@ -2318,6 +2342,29 @@ namespace System.Data.SqlClient
}
break;
+ case TdsEnums.ENV_PROMOTETRANSACTION:
+ if (!stateObj.TryReadInt32(out env.newLength))
+ { // new value has 4 byte length
+ return false;
+ }
+ env.newBinValue = new byte[env.newLength];
+ if (!stateObj.TryReadByteArray(env.newBinValue, 0, env.newLength))
+ { // read new value with 4 byte length
+ return false;
+ }
+
+ if (!stateObj.TryReadByte(out byteLength))
+ {
+ return false;
+ }
+ env.oldLength = byteLength;
+ Debug.Assert(0 == env.oldLength, "old length should be zero");
+
+ // env.length includes 1 byte for type token
+ env.length = 5 + env.newLength;
+ break;
+
+ case TdsEnums.ENV_TRANSACTIONMANAGERADDRESS:
case TdsEnums.ENV_SPRESETCONNECTIONACK:
if (!TryReadTwoBinaryFields(env, stateObj))
{
@@ -2372,14 +2419,6 @@ namespace System.Data.SqlClient
env.length = env.newLength + oldLength + 5; // 5=2*sizeof(UInt16)+sizeof(byte) [token+newLength+oldLength]
break;
- // ENVCHANGE tokens not supported by CoreCLR
- case TdsEnums.ENV_ENLISTDTC:
- case TdsEnums.ENV_DEFECTDTC:
- case TdsEnums.ENV_TRANSACTIONENDED:
- case TdsEnums.ENV_PROMOTETRANSACTION:
- case TdsEnums.ENV_TRANSACTIONMANAGERADDRESS:
- throw SQL.UnsupportedFeatureAndToken(_connHandler, ((TdsEnums.EnvChangeType)env.type).ToString());
-
default:
Debug.Assert(false, "Unknown environment change token: " + env.type);
break;
@@ -5891,6 +5930,20 @@ namespace System.Data.SqlClient
return len;
}
+ internal int WriteGlobalTransactionsFeatureRequest(bool write /* if false just calculates the length */)
+ {
+ int len = 5; // 1byte = featureID, 4bytes = featureData length
+
+ if (write)
+ {
+ // Write Feature ID
+ _physicalStateObj.WriteByte(TdsEnums.FEATUREEXT_GLOBALTRANSACTIONS);
+ WriteInt(0, _physicalStateObj); // we don't send any data
+ }
+
+ return len;
+ }
+
internal void TdsLogin(SqlLogin rec, TdsEnums.FeatureExtension requestedFeatures, SessionData recoverySessionData)
{
_physicalStateObj.SetTimeoutSeconds(rec.timeout);
@@ -5918,12 +5971,9 @@ namespace System.Data.SqlClient
string userName;
- {
- userName = rec.userName;
- encryptedPassword = TdsParserStaticMethods.ObfuscatePassword(rec.password);
- encryptedPasswordLengthInBytes = encryptedPassword.Length; // password in clear text is already encrypted and its length is in byte
- }
-
+ userName = rec.userName;
+ encryptedPassword = TdsParserStaticMethods.ObfuscatePassword(rec.password);
+ encryptedPasswordLengthInBytes = encryptedPassword.Length; // password in clear text is already encrypted and its length is in byte
// set the message type
@@ -5997,7 +6047,11 @@ namespace System.Data.SqlClient
if ((requestedFeatures & TdsEnums.FeatureExtension.SessionRecovery) != 0)
{
length += WriteSessionRecoveryFeatureRequest(recoverySessionData, false);
- };
+ }
+ if ((requestedFeatures & TdsEnums.FeatureExtension.GlobalTransactions) != 0)
+ {
+ length += WriteGlobalTransactionsFeatureRequest(false);
+ }
length++; // for terminator
}
@@ -6209,7 +6263,11 @@ namespace System.Data.SqlClient
if ((requestedFeatures & TdsEnums.FeatureExtension.SessionRecovery) != 0)
{
length += WriteSessionRecoveryFeatureRequest(recoverySessionData, true);
- };
+ }
+ if ((requestedFeatures & TdsEnums.FeatureExtension.GlobalTransactions) != 0)
+ {
+ WriteGlobalTransactionsFeatureRequest(true);
+ }
_physicalStateObj.WriteByte(0xFF); // terminator
}
}
@@ -6305,8 +6363,62 @@ namespace System.Data.SqlClient
ThrowExceptionAndWarning(_physicalStateObj);
}
-
+ internal byte[] GetDTCAddress(int timeout, TdsParserStateObject stateObj)
+ {
+ // If this fails, the server will return a server error - Sameet Agarwal confirmed.
+ // Success: DTCAddress returned. Failure: SqlError returned.
+
+ byte[] dtcAddr = null;
+
+ using (SqlDataReader dtcReader = TdsExecuteTransactionManagerRequest(
+ null,
+ TdsEnums.TransactionManagerRequestType.GetDTCAddress,
+ null,
+ TdsEnums.TransactionManagerIsolationLevel.Unspecified,
+ timeout, null, stateObj, true))
+ {
+
+ Debug.Assert(SniContext.Snix_Read == stateObj.SniContext, String.Format((IFormatProvider)null, "The SniContext should be Snix_Read but it actually is {0}", stateObj.SniContext));
+ if (null != dtcReader && dtcReader.Read())
+ {
+ Debug.Assert(dtcReader.GetName(0) == "TM Address", "TdsParser: GetDTCAddress did not return 'TM Address'");
+
+ // DTCAddress is of variable size, and does not have a maximum. So we call GetBytes
+ // to get the length of the dtcAddress, then allocate a byte array of that length,
+ // then call GetBytes again on that byte[] with the length
+ long dtcLength = dtcReader.GetBytes(0, 0, null, 0, 0);
+
+ //
+ if (dtcLength <= Int32.MaxValue)
+ {
+ int cb = (int)dtcLength;
+
+ dtcAddr = new byte[cb];
+ dtcReader.GetBytes(0, 0, dtcAddr, 0, cb);
+ }
+#if DEBUG
+ else
+ {
+ Debug.Assert(false, "unexpected length (> Int32.MaxValue) returned from dtcReader.GetBytes");
+ // if we hit this case we'll just return a null address so that the user
+ // will get a transcaction enlistment error in the upper layers
+ }
+#endif
+ }
+ }
+ return dtcAddr;
+ }
+
+ // Propagate the dtc cookie to the server, enlisting the connection.
+ internal void PropagateDistributedTransaction(byte[] buffer, int timeout, TdsParserStateObject stateObj)
+ {
+ // if this fails, the server will return a server error - Sameet Agarwal confirmed
+ // Success: server will return done token. Failure: SqlError returned.
+ TdsExecuteTransactionManagerRequest(buffer,
+ TdsEnums.TransactionManagerRequestType.Propagate, null,
+ TdsEnums.TransactionManagerIsolationLevel.Unspecified, timeout, null, stateObj, true);
+ }
internal SqlDataReader TdsExecuteTransactionManagerRequest(
byte[] buffer,
@@ -6315,7 +6427,8 @@ namespace System.Data.SqlClient
TdsEnums.TransactionManagerIsolationLevel isoLevel,
int timeout,
SqlInternalTransaction transaction,
- TdsParserStateObject stateObj
+ TdsParserStateObject stateObj,
+ bool isDelegateControlRequest
)
{
Debug.Assert(this == stateObj.Parser, "different parsers");
@@ -6350,6 +6463,12 @@ namespace System.Data.SqlClient
// Temporarily disable async writes
_asyncWrite = false;
+ // This validation step MUST be done after locking the connection to guarantee we don't
+ // accidentally execute after the transaction has completed on a different thread.
+ if (!isDelegateControlRequest)
+ {
+ _connHandler.CheckEnlistedTransactionBinding();
+ }
stateObj._outputMessageType = TdsEnums.MT_TRANS; // set message type
stateObj.SetTimeoutSeconds(timeout);
@@ -6367,8 +6486,26 @@ namespace System.Data.SqlClient
WriteShort((short)request, stateObj); // write TransactionManager Request type
+ bool returnReader = false;
+
switch (request)
{
+ case TdsEnums.TransactionManagerRequestType.GetDTCAddress:
+ WriteShort(0, stateObj);
+
+ returnReader = true;
+ break;
+ case TdsEnums.TransactionManagerRequestType.Propagate:
+ if (null != buffer)
+ {
+ WriteShort(buffer.Length, stateObj);
+ stateObj.WriteByteArray(buffer, buffer.Length, 0);
+ }
+ else
+ {
+ WriteShort(0, stateObj);
+ }
+ break;
case TdsEnums.TransactionManagerRequestType.Begin:
Debug.Assert(null != transaction, "Should have specified an internalTransaction when doing a BeginTransaction request!");
@@ -6397,6 +6534,11 @@ namespace System.Data.SqlClient
stateObj.WriteByte((byte)(transactionName.Length * 2)); // Write number of bytes (unicode string).
WriteString(transactionName, stateObj);
break;
+ case TdsEnums.TransactionManagerRequestType.Promote:
+ // No payload - except current transaction in header
+ // Promote returns a DTC cookie. However, the transaction cookie we use for the
+ // connection does not change after a promote.
+ break;
case TdsEnums.TransactionManagerRequestType.Commit:
Debug.Assert(transactionName.Length == 0, "Should not have a transaction name on Commit");
@@ -6434,10 +6576,33 @@ namespace System.Data.SqlClient
stateObj._pendingData = true;
stateObj._messageStatus = 0;
+ SqlDataReader dtcReader = null;
stateObj.SniContext = SniContext.Snix_Read;
- Run(RunBehavior.UntilDone, null, null, null, stateObj);
+ if (returnReader)
+ {
+ dtcReader = new SqlDataReader(null, CommandBehavior.Default);
+ Debug.Assert(this == stateObj.Parser, "different parser");
+#if DEBUG
+ // Remove the current owner of stateObj - otherwise we will hit asserts
+ stateObj.Owner = null;
+#endif
+ dtcReader.Bind(stateObj);
- return null;
+ // force consumption of metadata
+ _SqlMetaDataSet metaData = dtcReader.MetaData;
+ }
+ else
+ {
+ Run(RunBehavior.UntilDone, null, null, null, stateObj);
+ }
+
+ // If the retained ID is no longer valid (because we are enlisting in null or a new transaction) then it should be cleared
+ if (((request == TdsEnums.TransactionManagerRequestType.Begin) || (request == TdsEnums.TransactionManagerRequestType.Propagate)) && ((transaction == null) || (transaction.TransactionId != _retainedTransactionId)))
+ {
+ _retainedTransactionId = SqlInternalTransaction.NullTransactionId;
+ }
+
+ return dtcReader;
}
catch (Exception e)
{
@@ -6549,6 +6714,9 @@ namespace System.Data.SqlClient
throw ADP.ClosedConnectionError();
}
+ // This validation step MUST be done after locking the connection to guarantee we don't
+ // accidentally execute after the transaction has completed on a different thread.
+ _connHandler.CheckEnlistedTransactionBinding();
stateObj.SetTimeoutSeconds(timeout);
stateObj.SniContext = SniContext.Snix_Execute;
@@ -6664,6 +6832,7 @@ namespace System.Data.SqlClient
{
_asyncWrite = !sync;
+ _connHandler.CheckEnlistedTransactionBinding();
stateObj.SetTimeoutSeconds(timeout);
stateObj.SniContext = SniContext.Snix_Execute;
diff --git a/src/System.Data.SqlClient/src/System/Data/SqlClient/sqlinternaltransaction.cs b/src/System.Data.SqlClient/src/System/Data/SqlClient/sqlinternaltransaction.cs
index a7fc0e1ef0..3811de6a7f 100644
--- a/src/System.Data.SqlClient/src/System/Data/SqlClient/sqlinternaltransaction.cs
+++ b/src/System.Data.SqlClient/src/System/Data/SqlClient/sqlinternaltransaction.cs
@@ -25,6 +25,9 @@ namespace System.Data.SqlClient
{
LocalFromTSQL = 1,
LocalFromAPI = 2,
+ Delegated = 3,
+ Distributed = 4,
+ Context = 5, // only valid in proc.
};
sealed internal class SqlInternalTransaction
@@ -109,6 +112,23 @@ namespace System.Data.SqlClient
}
}
+ internal bool IsDelegated
+ {
+ get
+ {
+ bool result = (TransactionType.Delegated == _transactionType);
+ return result;
+ }
+ }
+
+ internal bool IsDistributed
+ {
+ get
+ {
+ bool result = (TransactionType.Distributed == _transactionType);
+ return result;
+ }
+ }
internal bool IsLocal
{
@@ -230,7 +250,7 @@ namespace System.Data.SqlClient
bool processFinallyBlock = true;
try
{
- innerConnection.ExecuteTransaction(SqlInternalConnection.TransactionRequest.IfRollback, null, IsolationLevel.Unspecified, null);
+ innerConnection.ExecuteTransaction(SqlInternalConnection.TransactionRequest.IfRollback, null, IsolationLevel.Unspecified, null, false);
}
catch (Exception e)
{
@@ -264,7 +284,7 @@ namespace System.Data.SqlClient
{
// COMMIT ignores transaction names, and so there is no reason to pass it anything. COMMIT
// simply commits the transaction from the most recent BEGIN, nested or otherwise.
- _innerConnection.ExecuteTransaction(SqlInternalConnection.TransactionRequest.Commit, null, IsolationLevel.Unspecified, null);
+ _innerConnection.ExecuteTransaction(SqlInternalConnection.TransactionRequest.Commit, null, IsolationLevel.Unspecified, null, false);
{
ZombieParent();
}
@@ -366,7 +386,7 @@ namespace System.Data.SqlClient
{
// If no arg is given to ROLLBACK it will rollback to the outermost begin - rolling back
// all nested transactions as well as the outermost transaction.
- _innerConnection.ExecuteTransaction(SqlInternalConnection.TransactionRequest.IfRollback, null, IsolationLevel.Unspecified, null);
+ _innerConnection.ExecuteTransaction(SqlInternalConnection.TransactionRequest.IfRollback, null, IsolationLevel.Unspecified, null, false);
// Since Rollback will rollback to outermost begin, no need to check
// server transaction level. This transaction has been completed.
@@ -409,7 +429,7 @@ namespace System.Data.SqlClient
try
{
- _innerConnection.ExecuteTransaction(SqlInternalConnection.TransactionRequest.Rollback, transactionName, IsolationLevel.Unspecified, null);
+ _innerConnection.ExecuteTransaction(SqlInternalConnection.TransactionRequest.Rollback, transactionName, IsolationLevel.Unspecified, null, false);
}
catch (Exception e)
{
@@ -436,7 +456,7 @@ namespace System.Data.SqlClient
try
{
- _innerConnection.ExecuteTransaction(SqlInternalConnection.TransactionRequest.Save, savePointName, IsolationLevel.Unspecified, null);
+ _innerConnection.ExecuteTransaction(SqlInternalConnection.TransactionRequest.Save, savePointName, IsolationLevel.Unspecified, null, false);
}
catch (Exception e)
{
diff --git a/src/System.Data.SqlClient/tests/FunctionalTests/AmbientTransactionFailureTest.cs b/src/System.Data.SqlClient/tests/FunctionalTests/AmbientTransactionFailureTest.cs
index fac17c7143..1e6cbfcb0e 100644
--- a/src/System.Data.SqlClient/tests/FunctionalTests/AmbientTransactionFailureTest.cs
+++ b/src/System.Data.SqlClient/tests/FunctionalTests/AmbientTransactionFailureTest.cs
@@ -82,17 +82,6 @@ namespace System.Data.SqlClient.Tests
});
}
- [Theory]
- [MemberData(nameof(ExceptionTestDataForNotSupportedException))]
- [SkipOnTargetFramework(TargetFrameworkMonikers.NetFramework, ".NET Framework doesn't throw the Not Supported Exception")]
- public void TestNotSupportedException(Action<string> connectAction, string connectionString)
- {
- Assert.Throws<NotSupportedException>(() =>
- {
- connectAction(connectionString);
- });
- }
-
[Fact]
[SkipOnTargetFramework(TargetFrameworkMonikers.NetFramework, ".NET Framework doesn't throw the Not Supported Exception")]
public void TestNotSupportedExceptionForTransactionScopeAsync()
diff --git a/src/System.Data.SqlClient/tests/FunctionalTests/ExceptionTest.cs b/src/System.Data.SqlClient/tests/FunctionalTests/ExceptionTest.cs
index 68df6608a1..8556f45bce 100644
--- a/src/System.Data.SqlClient/tests/FunctionalTests/ExceptionTest.cs
+++ b/src/System.Data.SqlClient/tests/FunctionalTests/ExceptionTest.cs
@@ -76,7 +76,6 @@ namespace System.Data.SqlClient.Tests
}
}
- [ActiveIssue(19057)]
[Theory]
[InlineData(@"np:\\.\pipe\sqlbad\query")]
[InlineData(@"np:\\.\pipe\MSSQL$NonExistentInstance\sql\query")]
@@ -92,15 +91,18 @@ namespace System.Data.SqlClient.Tests
SqlConnectionStringBuilder builder = new SqlConnectionStringBuilder();
builder.DataSource = dataSource;
builder.ConnectTimeout = 1;
- using(SqlConnection connection = new SqlConnection(builder.ConnectionString))
+
+ using (SqlConnection connection = new SqlConnection(builder.ConnectionString))
{
- VerifyConnectionFailure<SqlException>(() => connection.Open(), "(provider: Named Pipes Provider, error: 11 - Timeout error)");
+ string expectedErrorMsg = "(provider: Named Pipes Provider, error: 40 - Could not open a connection to SQL Server)";
+ VerifyConnectionFailure<SqlException>(() => connection.Open(), expectedErrorMsg);
}
}
- [ActiveIssue(19057)]
- [Fact]
- public void NamedPipeInvalidConnStringTest()
+ public static bool IsUsingManagedSNI() => ManualTesting.Tests.DataTestUtility.IsUsingManagedSNI();
+
+ [ConditionalFact(nameof(IsUsingManagedSNI))]
+ public void NamedPipeInvalidConnStringTest_ManagedSNI()
{
SqlConnectionStringBuilder builder = new SqlConnectionStringBuilder();
builder.ConnectTimeout = 1;
diff --git a/src/System.Data.SqlClient/tests/FunctionalTests/System.Data.SqlClient.Tests.csproj b/src/System.Data.SqlClient/tests/FunctionalTests/System.Data.SqlClient.Tests.csproj
index 77e2f7f277..8a8238b2d6 100644
--- a/src/System.Data.SqlClient/tests/FunctionalTests/System.Data.SqlClient.Tests.csproj
+++ b/src/System.Data.SqlClient/tests/FunctionalTests/System.Data.SqlClient.Tests.csproj
@@ -28,9 +28,6 @@
<Compile Include="SqlConnectionTest.cs" />
<Compile Include="TestTdsServer.cs" />
<Compile Include="..\ManualTests\DataCommon\DataTestUtility.cs" />
- <Compile Include="$(CommonTestPath)\System\AssertExtensions.cs">
- <Link>Common\System\AssertExtensions.cs</Link>
- </Compile>
<Compile Include="$(CommonTestPath)\System\PlatformDetection.cs">
<Link>Common\System\PlatformDetection.cs</Link>
</Compile>
diff --git a/src/System.Data.SqlClient/tests/FunctionalTests/TcpDefaultForAzureTest.cs b/src/System.Data.SqlClient/tests/FunctionalTests/TcpDefaultForAzureTest.cs
index 9e82dd4f8c..07cf3622f8 100644
--- a/src/System.Data.SqlClient/tests/FunctionalTests/TcpDefaultForAzureTest.cs
+++ b/src/System.Data.SqlClient/tests/FunctionalTests/TcpDefaultForAzureTest.cs
@@ -33,6 +33,7 @@ namespace System.Data.SqlClient.Tests
}
[Fact]
+ [SkipOnTargetFramework(TargetFrameworkMonikers.Uap)] // Cannot retrieve UseManagedSNI flag via reflection on UAP
public static void NonAzureNoProtocolConnectionTest()
{
builder.DataSource = InvalidHostname;
diff --git a/src/System.Data.SqlClient/tests/ManualTests/SQL/TransactionTest/TransactionEnlistmentTest.cs b/src/System.Data.SqlClient/tests/ManualTests/SQL/TransactionTest/TransactionEnlistmentTest.cs
new file mode 100644
index 0000000000..ac749a5c8e
--- /dev/null
+++ b/src/System.Data.SqlClient/tests/ManualTests/SQL/TransactionTest/TransactionEnlistmentTest.cs
@@ -0,0 +1,124 @@
+// Licensed to the .NET Foundation under one or more agreements.
+// The .NET Foundation licenses this file to you under the MIT license.
+// See the LICENSE file in the project root for more information.
+
+using System.Collections.Generic;
+using System.Transactions;
+using Xunit;
+
+namespace System.Data.SqlClient.ManualTesting.Tests
+{
+ public class TransactionEnlistmentTest
+ {
+ [CheckConnStrSetupFact]
+ public static void TestAmbientTransaction_TxScopeComplete()
+ {
+ const int inputCol1 = 1;
+ const string inputCol2 = "one";
+
+ SqlConnectionStringBuilder builder = new SqlConnectionStringBuilder(DataTestUtility.TcpConnStr);
+ string connectionString = builder.ConnectionString;
+ string testTableName = GenerateTableName();
+
+ RunNonQuery(connectionString, $"create table {testTableName} (col1 int, col2 text)");
+
+ try
+ {
+ using (TransactionScope txScope = new TransactionScope(TransactionScopeOption.Required, TimeSpan.MaxValue))
+ {
+ using (SqlConnection connection = new SqlConnection(connectionString))
+ {
+ connection.Open();
+ using (SqlCommand command = connection.CreateCommand())
+ {
+ command.CommandText = $"INSERT INTO {testTableName} VALUES ({inputCol1}, '{inputCol2}')";
+ command.ExecuteNonQuery();
+ }
+ }
+ txScope.Complete();
+ }
+
+ DataTable result = RunQuery(connectionString, $"select col2 from {testTableName} where col1 = {inputCol1}");
+ Assert.True(result.Rows.Count > 0);
+ Assert.True(string.Equals(result.Rows[0][0], inputCol2));
+ }
+ finally
+ {
+ RunNonQuery(connectionString, $"drop table {testTableName}");
+ }
+ }
+
+ [CheckConnStrSetupFact]
+ public static void TestAmbientTransaction_TxScopeNonComplete()
+ {
+ const int inputCol1 = 2;
+ const string inputCol2 = "two";
+
+ SqlConnectionStringBuilder builder = new SqlConnectionStringBuilder(DataTestUtility.TcpConnStr);
+ string connectionString = builder.ConnectionString;
+ string testTableName = GenerateTableName();
+
+ RunNonQuery(connectionString, $"create table {testTableName} (col1 int, col2 text)");
+
+ try
+ {
+ using (TransactionScope txScope = new TransactionScope(TransactionScopeOption.Required, TimeSpan.MaxValue))
+ {
+ using (SqlConnection connection = new SqlConnection(connectionString))
+ {
+ connection.Open();
+ using (SqlCommand command = connection.CreateCommand())
+ {
+ command.CommandText = $"INSERT INTO {testTableName} VALUES ({inputCol1}, '{inputCol2}')";
+ command.ExecuteNonQuery();
+ }
+ }
+ }
+
+ DataTable result = RunQuery(connectionString, $"select col2 from {testTableName} where col1 = {inputCol1}");
+ Assert.True(result.Rows.Count == 0);
+ }
+ finally
+ {
+ RunNonQuery(connectionString, $"drop table {testTableName}");
+ }
+ }
+
+ private static void RunNonQuery(string connectionString, string sql)
+ {
+ using (SqlConnection connection = new SqlConnection(connectionString))
+ {
+ connection.Open();
+ using (SqlCommand command = connection.CreateCommand())
+ {
+ command.CommandText = sql;
+ command.ExecuteNonQuery();
+ }
+ }
+ }
+
+ private static DataTable RunQuery(string connectionString, string sql)
+ {
+ DataTable result = null;
+ using (SqlConnection connection = new SqlConnection(connectionString))
+ {
+ connection.Open();
+ using (SqlCommand command = connection.CreateCommand())
+ {
+ command.CommandText = sql;
+ using (SqlDataReader reader = command.ExecuteReader())
+ {
+ result = new DataTable();
+ result.Load(reader);
+ }
+ }
+ }
+ return result;
+ }
+
+ private static string GenerateTableName()
+ {
+ return string.Format("TEST_{0}{1}{2}", Environment.GetEnvironmentVariable("ComputerName"), Environment.TickCount, Guid.NewGuid()).Replace('-', '_');
+ }
+ }
+}
diff --git a/src/System.Data.SqlClient/tests/ManualTests/System.Data.SqlClient.ManualTesting.Tests.csproj b/src/System.Data.SqlClient/tests/ManualTests/System.Data.SqlClient.ManualTesting.Tests.csproj
index 64ceb991d9..d6c76ff31d 100644
--- a/src/System.Data.SqlClient/tests/ManualTests/System.Data.SqlClient.ManualTesting.Tests.csproj
+++ b/src/System.Data.SqlClient/tests/ManualTests/System.Data.SqlClient.ManualTesting.Tests.csproj
@@ -108,6 +108,7 @@
<Compile Include="SQL\SplitPacketTest\SplitPacketTest.cs" />
<Compile Include="SQL\SqlNotificationTest\SqlNotificationTest.cs" />
<Compile Include="SQL\TransactionTest\TransactionTest.cs" />
+ <Compile Include="SQL\TransactionTest\TransactionEnlistmentTest.cs" />
<Compile Include="SQL\WeakRefTest\WeakRefTest.cs" />
<Compile Include="SQL\WeakRefTestYukonSpecific\WeakRefTestYukonSpecific.cs" />
<Compile Include="XUnitAssemblyAttributes.cs" />
diff --git a/src/System.Diagnostics.Contracts/tests/System.Diagnostics.Contracts.Tests.csproj b/src/System.Diagnostics.Contracts/tests/System.Diagnostics.Contracts.Tests.csproj
index 47324290ee..e456d1d099 100644
--- a/src/System.Diagnostics.Contracts/tests/System.Diagnostics.Contracts.Tests.csproj
+++ b/src/System.Diagnostics.Contracts/tests/System.Diagnostics.Contracts.Tests.csproj
@@ -14,9 +14,6 @@
<Compile Include="ForAllTests.cs" />
<Compile Include="Utilities.cs" />
<Compile Include="ValueTests.cs" />
- <Compile Include="$(CommonTestPath)\System\AssertExtensions.cs">
- <Link>Common\System\AssertExtensions.cs</Link>
- </Compile>
<Compile Include="$(CommonTestPath)\System\PlatformDetection.cs">
<Link>Common\System\PlatformDetection.cs</Link>
</Compile>
diff --git a/src/System.Diagnostics.Debug/tests/System.Diagnostics.Debug.Tests.csproj b/src/System.Diagnostics.Debug/tests/System.Diagnostics.Debug.Tests.csproj
index 3243a7c64e..67b2b8d245 100644
--- a/src/System.Diagnostics.Debug/tests/System.Diagnostics.Debug.Tests.csproj
+++ b/src/System.Diagnostics.Debug/tests/System.Diagnostics.Debug.Tests.csproj
@@ -26,9 +26,6 @@
<Compile Include="DebugTests.cs" />
<Compile Include="EmptyAttributeTests.cs" />
<Compile Include="XunitAssemblyAttributes.cs" />
- <Compile Include="$(CommonTestPath)\System\AssertExtensions.cs">
- <Link>Common\System\AssertExtensions.cs</Link>
- </Compile>
<Compile Include="$(CommonTestPath)\System\PlatformDetection.cs">
<Link>Common\System\PlatformDetection.cs</Link>
</Compile>
diff --git a/src/System.Diagnostics.DiagnosticSource/src/ActivityUserGuide.md b/src/System.Diagnostics.DiagnosticSource/src/ActivityUserGuide.md
index a66cb52d53..3bca931764 100644
--- a/src/System.Diagnostics.DiagnosticSource/src/ActivityUserGuide.md
+++ b/src/System.Diagnostics.DiagnosticSource/src/ActivityUserGuide.md
@@ -194,7 +194,7 @@ Applications start Activity to represent logical piece of work to be done; one A
The whole operation may be represented as a tree of Activities. All operations done by the distributed system may be represented as a forest of Activities trees.
Id uniquely identifies Activity in the forest. It has an hierarchical structure to efficiently describe the operation as Activity tree.
-Activity.Id serves as hierarchical Request-Id in terms of [HTTP standard proposal for correlation](https://github.com/lmolkova/correlation/blob/master/http_protocol_proposal_v1.md)
+Activity.Id serves as hierarchical Request-Id in terms of [HTTP Correlation Protocol](HttpCorrelationProtocol.md)
### Id Format
@@ -206,16 +206,16 @@ e.g.
It starts with '|' followed by [root-id](#root-id) followed by '.' and small identifiers of local Activities, separated by '.' or '_'.
-[Root-id](#root-id) identifies the whole operation and 'Id' identifies particular Actvity involved in operation processing.
+[Root-id](#root-id) identifies the whole operation and 'Id' identifies particular Activity involved in operation processing.
-'|' indicates Id has hierarchcal structure, which is useful information for logging system.
+'|' indicates Id has hierarchical structure, which is useful information for logging system.
* Id is 1024 bytes or shorter
* Id consist of [Base64](https://en.wikipedia.org/wiki/Base64), '-' (hyphen), '.' (dot), '_' (underscore) and '#' (pound) characters.
Where base64 and '-' are used in nodes and other characters delimit nodes. Id always ends with one of the delimiters.
### Root Id
-When you start the first Activity for the operation, you may optionaly provide root-id through `Activity.SetParentId(string)` API.
+When you start the first Activity for the operation, you may optionally provide root-id through `Activity.SetParentId(string)` API.
If you don't provide it, Activity will generate root-id: e.g. `a000b421-5d183ab6`
@@ -276,7 +276,7 @@ Id is passed to external dependencies and considered as [ParentId](#parentid) fo
`string ParentId { get; private set; }` - Activity may have either an in-process [Parent](#parent) or an external Parent if it was deserialized from request. ParentId together with Id represent the parent-child relationship in logs and allows you to correlate outgoing and incoming requests.
### RootId
-`string RootId { get; private set; }` - Returns [root id](#root-id): Id (or ParentId) substring from '|' to first '.' occurence.
+`string RootId { get; private set; }` - Returns [root id](#root-id): Id (or ParentId) substring from '|' to first '.' occurrence.
### Current
`static Activity Current { get; }` - Returns current Activity which flows across async calls.
diff --git a/src/System.Diagnostics.DiagnosticSource/src/FlatRequestId.md b/src/System.Diagnostics.DiagnosticSource/src/FlatRequestId.md
new file mode 100644
index 0000000000..31683b679a
--- /dev/null
+++ b/src/System.Diagnostics.DiagnosticSource/src/FlatRequestId.md
@@ -0,0 +1,100 @@
+# Flat Request-Ids
+This document provide guidance for implementations of [HTTP Correlation Protocol](HttpCorrelationProtocol.md) without [Hierarchical Request-Id](HierarchicalRequestId.md) support or interoperability with services that do not support it.
+
+We strongly recommend every implementation to support [Hierarchical Request-Id](HierarchicalRequestId.md) wherever possible. If implementation do not support it, it still MUST ensure essential requirements are met:
+* `Request-Id` uniquely identifies every HTTP request involved in operation processing and MUST be generated for every incoming and outgoing request
+* `Correlation-Context` has `Id` property serving as single unique identifier of the whole operation and implementation MUST generate one if it is missing.
+
+It is important to log `Request-Id` received from the upstream service along with the incoming request. It ensures that parent-child relationships between requests are retained and the whole tree of the requests could be restored.
+Therefore implementations MUST provide access to the 'parent' Request-Id for logging system.
+
+[Root Request Id](HierarchicalRequestId.md#root-request-id-generation) requirements and generation considerations must be used for flat Request-Id
+
+## Correlation Id (Trace Id)
+Many applications and tracing systems use single correlation/trace id to identify whole operation through all services and client applications.
+In case of heterogeneous environment (where some services generate hierarchical Request-Ids and others generate flat Ids) having single identifier, common for all requests, helps to make telemetry query simple and efficient.
+
+If implementation generates flat Request-Id, it MUST ensure `Id` is present in `Correlation-Context` or [generate](#correlation-id-generation) new one and add to the `Correlation-Context`.
+
+### Correlation Id generation
+If implementation needs to add `Id` property to `Correlation-Context`:
+* SHOULD use root node of the Request-Id received from upstream service if it has hierarchical structure.
+* MUST follow [Root Request Id Generation](HierarchicalRequestId.md#root-request-id-generation) rules otherwise
+
+## Non-hierarchical Request-Id example
+1. A: service-a receives request
+ * scans through its headers does not find Request-Id.
+ * generates a new one: `abc`
+ * adds extra property to CorrelationContext `Id=123`
+ * logs event that operation was started along with `Request-Id: abc`, `Correlation-Context: Id=123`
+2. A: service-a makes request to service-b:
+ * generates new `Request-Id: def`
+ * logs that outgoing request is about to be sent with all the available context: `Request-Id: def`, `Correlation-Context: Id=123`
+ * sends request to service-b
+3. B: service-b receives request
+ * scans through its headers and finds `Request-Id: ghi`, `Correlation-Context: Id=123`
+ * logs event that operation was started along with all available context: `Request-Id: ghi`, `Correlation-Context: Id=123`
+ * processes request and responds to service-a
+4. A: service-a receives response from service-b
+ * logs response with context: `Request-Id: def`, `Correlation-Context: Id=123`
+ * Processes request and responds to caller
+
+As a result log records may look like:
+
+| Message | Component Name | Context |
+| ---------| --------------- | ------- |
+| user starts request to service-a | user | |
+| incoming request | service-a | `Request-Id=abc; Parent-Request-Id=; Id=123` |
+| request to service-b | service-a | `Request-Id=def; Parent-Request-Id=abc, Id=123` |
+| incoming request | service-b | `Request-Id=ghi; Parent-Request-Id=def; Id=123` |
+| response | service-b |`Request-Id=ghi; Parent-Request-Id=def; Id=123` |
+| response from service-b | service-a | `Request-Id=def; Parent-Request-Id=abc; Id=123` |
+| response | service-a |`Request-Id=abc; Parent-Request-Id=; Id=123` |
+| response from service-a | user | |
+
+#### Remarks
+* Logs for operation may be queried by `Id=123` match, logs for particular request may be queried by exact Request-Id match
+* Note that since hierarchical request Id was not used, Id must be logged with every trace. Parent-Request-Id must be logged to restore parent-child relationships between incoming/outgoing requests.
+
+## Mixed hierarchical and non-hierarchical scenario
+In heterogeneous environment, some services may support hierarchical Request-Id generation and others may not.
+
+Requirements listed [Request-Id](HttpCorrelationProtocol.md#request-id) help to ensure all telemetry for the operation still is accessible:
+- if implementation supports hierarchical Request-Id, it MUST propagate `Correlation-Context` and **MAY** add `Id` if missing
+- if implementation does NOT support hierarchical Request-Id, it MUST propagate `Correlation-Context` and **MUST** add `Id` if missing
+
+Let's imagine service-a supports hierarchical Request-Id and service-b does not:
+
+1. A: service-a receives request
+ * scans through its headers and does not find `Request-Id`.
+ * generates a new one: `|Guid.`
+ * logs event that operation was started along with `Request-Id: |Guid.`
+2. A: service-a makes request to service-b:
+ * generates new `Request-Id: |Guid.1_`
+ * logs that outgoing request is about to be sent
+ * sends request to service-b
+3. B: service-b receives request
+ * scans through its headers and finds `Request-Id: |Guid.1_`
+ * generates a new Request-Id: `def`
+ * does not see `Correlation-Context`. It parses parent Request-Id, extracts root node: `Guid` and adds `Id` property to `CorrelationContext : Id=abc`
+ * logs event that operation was started
+ * processes request and responds to service-a
+4. A: service-a receives response from service-b
+ * logs response with context: `Request-Id: |Guid.1_`
+ * Processes request and responds to caller
+
+As a result log records may look like:
+
+| Message | Component Name | Context |
+| ---------| --------------- | ------- |
+| incoming request | service-a | `Request-Id=|Guid.` |
+| request to service-b | service-a | `Request-Id=|Guid.1_` |
+| incoming request | service-b | `Request-Id=def; Parent-Request-Id=|Guid.1_; Id=Guid` |
+| response | service-b |`Request-Id=def; Parent-Request-Id=|Guid.1_; Id=Guid` |
+| response from service-b | service-a | `Request-Id=|Guid.1_; Parent-Request-Id=|abc.bcec871c; Id=Guid` |
+| response | service-a |`Request-Id=|Guid.` |
+
+#### Remarks
+* Note, that even if service-b does not **generate** hierarchical Request-Id, it still could benefit from hierarchical structure, by assigning `Correlation-Context: Id` to the root node of Request-Id
+* Retrieving all log records then could be done by query like `Id == Guid || RequestId.startsWith('|Guid')`
+* If the first service to process request does not support hierarchical ids, then it sets `Correlation-Context: Id` immediately and it's propagated further and still may be used to query all logs.
diff --git a/src/System.Diagnostics.DiagnosticSource/src/HierarchicalRequestId.md b/src/System.Diagnostics.DiagnosticSource/src/HierarchicalRequestId.md
new file mode 100644
index 0000000000..f878f84c95
--- /dev/null
+++ b/src/System.Diagnostics.DiagnosticSource/src/HierarchicalRequestId.md
@@ -0,0 +1,111 @@
+# Hierarchical Request-Id
+This document describes hierarchical Request-Id schema for [HTTP Correlation Protocol](HttpCorrelationProtocol.md) for telemetry correlation.
+
+## Overview
+The main requirement for Request-Id is uniqueness, any two requests processed by the cluster must not collide.
+Guids or big random number help to achieve it, but they require other identifiers to query all requests related to the operation.
+
+Hierarchical Request-Id looks like `|<root-id>.<local-id1>.<local-id2>.` (e.g. `|9e74f0e5-efc4-41b5-86d1-3524a43bd891.bcec871c_1.`) and holds all information needed to trace whole operation and particular request.
+Root-id serves as common identifier for all requests involved in operation processing and local-ids represent internal activities (and requests) done within scope of this operation.
+
+Upstream service/client application may be instrumented with other tracing system, so implementation MAY have compatibility layer that parses another set of trace headers.
+Therefore implementation SHOULD be tolerant to other formats of trace identifiers and do the best effort to keep `root-id` equivalent in particular tracing system.
+
+### Formatting Hierarchical Request-Id
+If `Request-Id` was not provided from upstream service and implementation decides to trace the request, it MUST generate new `Request-Id` (see [Root Request Id Generation](#root-request-id-generation)) to represent incoming request.
+
+In heterogeneous environment implementations of this protocol with hierarchical `Request-Id` may interact with other services that do not implement this protocol, but still have notion of request Id. Implementation or logging system should be able unambiguously identify if given `Request-Id` has hierarchical schema.
+
+Therefore every implementation which support hierarchical structure MUST prepend "|" (vertical bar) to generated `Request-Id`.
+
+It also MUST append "." (dot) to the end of generated Request-Id to unambiguously mark end of it (e.g. search for `|123` may return `|1234`, but search for `|123.` would be exact)
+
+#### Root Request Id Generation
+Root Request-Id is the top most Request-Id generated by the first instrumented service. In a hierarchical Request-Id, it is a root node and common for all requests involved in operation processing.
+It MUST be unique to every high-level operation in the system, so for every traced operation, implementation MUST generate sufficiently large identifier: e.g. GUID, 64-bit or 128-bit random number.
+Note that random numbers could be encoded to string to decrease Request-Id length.
+
+Root Request-Id MUST contain only [Base64](https://en.wikipedia.org/wiki/Base64) and "-" (hyphen) characters.
+
+Same considerations are applied to client applications making HTTP requests and generating root Request-Id.
+
+Note that in addition to unique part, it may be useful to include some meaningful information such as host name, device or process id, etc. Implementation is free to do it, keeping root id relatively short.
+
+#### Incoming Request
+When Request-Id is provided by upstream service, there is no guarantee that it is unique within the entire system.
+
+Implementation SHOULD make it unique by adding small suffix to incoming Request-Id to represent internal activity and use it for outgoing requests.
+If implementation does not trust incoming Request-Id in the least, suffix may be as long as [Root Request Id](HttpCorrelationProtocol.md#root-request-id-generation).
+We recommend appending random string of 8 characters length (e.g. 32-bit hex-encoded random integer).
+
+Suffix MUST contain only [Base64](https://en.wikipedia.org/wiki/Base64) and "-" (hyphen) characters
+
+Implementation MUST append "_" (underscore) to mark the end of generated incoming Request-Id.
+
+#### Outgoing Request
+When making request to downstream service, implementation MUST append small id to the incoming Request-Id and pass a new Request-Id to downstream service.
+
+- Suffix MUST be unique for every outgoing HTTP request sent while processing the incoming request; monotonically incremented number of outgoing request within the scope of this incoming operation, is a good candidate.
+- Suffix MUST contain only [Base64](https://en.wikipedia.org/wiki/Base64) and "-" (hyphen) characters
+
+Implementation MUST append "." (dot) to mark the end of generated outgoing Request-Id.
+
+It may be useful to split incoming request processing to multiple logical sub-operations and assign different identifiers to them, similarly as it is done for outgoing request, except the sub-operation is processed within the same service.
+
+#### Request-Id Overflow
+Extending `Request-Id` may cause it to exceed length limit.
+To handle overflow, implementation:
+* MUST generate suffix that keeps possibility of collision with any of the previous or future Request-Id within the same operation neglectable.
+* MUST append "#" symbol to suffix to indicate that overflow happened.
+* MUST trim end of existing Request-Id to make a room for generated LocalId. Implementation MUST trim whole nodes (separated with ".", "_") without preceding delimiter, i.e. it's invalid to trim only part of node.
+* Suffix MUST contain only [Base64](https://en.wikipedia.org/wiki/Base64) and '-' (hyphen) characters
+
+As a result Request-Id will look like:
+
+ `Beginning-Of-Incoming-Request-Id.LocalId#`
+
+Thus, to the extent possible, Request-Id will keep valid part of hierarchical Id.
+
+Overflow suffix should be large enough to ensure new Request-Id does not collide with one of previous/future Request-Ids within the same operation. Using random 32-bytes integer (or 8 chars string) is a good candidate for it.
+Note that applications could asynchronously start multiple outgoing requests almost at the same time, which makes timestamp even with ticks precision bad candidate for overflow suffix.
+
+## Example
+Let's consider three services: service-a, service-b and service-c. User calls service-a, which calls service-b to fulfill the user request
+
+`User -> service-a -> service-b`
+
+1. A: service-a receives request
+ * does not find `Request-Id` and generates a new root Request-Id `|Guid.`
+ * trace that incoming request was started along with `Request-Id: |Guid.`
+2. A: service-a makes request to service-b:
+ * generates new `Request-Id` by appending request number to the parent request id: `|Guid.1.`
+ * logs that outgoing request is about to be sent with all the available context: `Request-Id: |Guid.1.`
+ * sends request to service-b
+3. B: service-b receives request
+ * scans through its headers and finds `Request-Id: |Guid.1.`
+ * it generates a new Request-Id: `|Guid.1.da4e9679_` to uniquely describe operation within service-b
+ * logs event that operation was started along with all available context: `Request-Id: |Guid.1.da4e9679_`
+ * processes request and responds to service-a
+4. A: service-a receives response from service-b
+ * logs response with context: `Request-Id: |Guid.1.`
+ * Processes request and responds to caller
+
+As a result log records may look like:
+
+| Message | Component name | Context |
+| ---------| --------------- | ------- |
+| user starts request to service-a | user | |
+| incoming request | service-a | `Request-Id=|Guid.` |
+| request to service-b | service-a | `Request-Id=|Guid.1.` |
+| incoming request | service-b | `Request-Id=|Guid.1.da4e9679_` |
+| response | service-b | `Request-Id=|Guid.1.da4e9679_` |
+| response from service-b | service-a | `Request-Id=|Guid.1.` |
+| response | service-a | `Request-Id=|Guid.` |
+| response from service-a | user | |
+
+### Remarks
+* All operation logs may be queried by Request-Id prefix `|Guid.`, logs for particular request may be queried by exact Request-Id match
+* When service-a generates a new Request-Id, it does not append suffix, since it generates a root Request-Id and ensures its uniqueness
+
+# See also
+- [Flat Request-Id](FlatRequestId.md)
diff --git a/src/System.Diagnostics.DiagnosticSource/src/HttpCorrelationProtocol.md b/src/System.Diagnostics.DiagnosticSource/src/HttpCorrelationProtocol.md
new file mode 100644
index 0000000000..498209b5e4
--- /dev/null
+++ b/src/System.Diagnostics.DiagnosticSource/src/HttpCorrelationProtocol.md
@@ -0,0 +1,83 @@
+# Overview
+One of the common problems in microservices development is ability to trace request flow from client (application, browser) through all the services involved in processing.
+
+Typical scenarios include:
+
+1. Tracing error received by user
+2. Performance analysis and optimization: whole stack of request needs to be analyzed to find where performance issues come from
+3. A/B testing: metrics for requests with experimental features should be distinguished and compared to 'production' data.
+
+These scenarios require every request to carry additional context and services to enrich their telemetry events with this context, so it would possible to correlate telemetry from all services involved in operation processing.
+
+Tracing an operation involves an overhead on application performance and should always be considered as optional, so application may not trace anything, trace only particular operations or some percent of all operations.
+Tracing should be consistent: operation should be either fully traced, or not traced at all.
+
+This document provides guidance on the context needed for telemetry correlation and describes its format in HTTP communication. The context is not specific to HTTP protocol, it represents set of identifiers that is needed or helpful for end-to-end tracing. Applications widely use distributed queues for asynchronous processing so operation may start (or continue) from a queue message; applications should propagate the context through the queues and restore (create) it when they start processing received task.
+
+# HTTP Protocol proposal
+| Header name | Format | Description |
+| ----------------------| ---------- | ---------- |
+| Request-Id | Required. String | Unique identifier for every HTTP request involved in operation processing |
+| Correlation-Context | Optional. Comma separated list of key-value pairs: Id=id, key1=value1, key2=value2 | Operation context which is propagated across all services involved in operation processing |
+
+## Request-Id
+`Request-Id` uniquely identifies every HTTP request involved in operation processing.
+
+Request-Id is generated on the caller side and passed to callee.
+
+Implementation of this protocol should expect to receive `Request-Id` in header of incoming request.
+Absence of Request-Id indicates that it is either the first instrumented service in the system or this request was not traced by upstream service and therefore does not have any context associated with it.
+To start tracing the request, implementation MUST generate new `Request-Id` (see [Root Request Id Generation](#root-request-id-generation)) for the incoming request.
+
+When Request-Id is provided by upstream service, there is no guarantee that it is unique within the entire system.
+Implementation SHOULD make it unique by adding small suffix to incoming Request-Id to represent internal activity and use it for outgoing requests, see more details in [Hierarchical Request-Id document](HierarchicalRequestId.md).
+
+`Request-Id` is required field, i.e., every instrumented request MUST have it. If implementation does not find `Request-Id` in the incoming request headers, it should consider it as non-traced and MAY not look for `Correlation-Context`.
+
+It is essential that 'incoming' and 'outgoing' Request-Ids are included in the telemetry events, so implementation of this protocol MUST provide read access to Request-Id for logging systems.
+
+### Request-Id Format
+`Request-Id` is a string up to 1024 bytes length. It contains only [Base64](https://en.wikipedia.org/wiki/Base64) and "-" (hyphen), "|" (vertical bar), "." (dot), and "_" (underscore) characters.
+
+Vertical bar, dot and underscore are reserved characters that are used to mark and delimit hierarchical Request-Id, and must not be present in the nodes. Hyphen may be used in the nodes.
+
+Implementations SHOULD support hierarchical structure for the Request-Id, described in [Hierarchical Request-Id document](HierarchicalRequestId.md).
+See [Flat Request-Id](FlatRequestId.md) for non-hierarchical Request-Id requirements.
+
+## Correlation-Context
+First service MAY add state (key value pairs) that will automatically propagate to all other services including intermediary services (that support this protocol). A typical scenarios for the Correlation-Context include logging control and sampling or A/B testing (feature flags) so that the first service has a way to pass this kind of information down to all services (including intermediary). All services other than the first one SHOULD consider Correlation-Context as read-only.
+It is important to keep the size of any property small because these get serialized into HTTP headers which have significant size restrictions; Correlation-Context parsing, storing and propagation involves performance overhead on all downstream services.
+
+Correlation-Context MUST NOT be used as generic data passing mechanism between services or within one service.
+
+We anticipate that there will be common well-known Correlation-Context keys. If you wish to use this for you own custom (not well-known) context key, prefix it with "@".
+
+`Correlation-Context` is optional, it may or may not be provided by upstream (instrumented) service.
+If `Correlation-Context` is provided by upstream service, implementation MUST propagate it further to downstream services. It MUST NOT change or remove properties and SHOULD NOT add new properties.
+
+Implementation MUST provide read access to `Correlation-Context` for logging systems and MUST support adding properties to Correlation-Context.
+
+### Correlation-Context Format
+`Correlation-Context` is represented as comma separated list of key value pairs, where each pair is represented in key=value format:
+
+`Correlation-Context: key1=value1, key2=value2`
+
+Keys and values MUST NOT contain "=" (equals) or "," (comma) characters.
+
+Overall Correlation-Context length MUST NOT exceed 1024 bytes, key and value length should stay well under the combined limit of 1024 bytes.
+
+Note that uniqueness of the key within the Correlation-Context is not guaranteed. Context received from upstream service is read-only and implementation MUST NOT remove or aggregate duplicated keys.
+
+# HTTP Guidelines and Limitations
+- [HTTP 1.1 RFC2616](https://tools.ietf.org/html/rfc2616)
+- [HTTP Header encoding RFC5987](https://tools.ietf.org/html/rfc5987)
+- De-facto overall HTTP headers size is limited to several kilobytes (depending on a web server)
+
+# Industry standards
+- [Google Dapper tracing system](http://static.googleusercontent.com/media/research.google.com/en//pubs/archive/36356.pdf)
+- [Zipkin](http://zipkin.io/)
+- [OpenTracing](http://opentracing.io/)
+
+# See also
+- [Hierarchical Request-Id](HierarchicalRequestId.md)
+- [Flat Request-Id](FlatRequestId.md)
diff --git a/src/System.Diagnostics.DiagnosticSource/tests/ActivityTests.cs b/src/System.Diagnostics.DiagnosticSource/tests/ActivityTests.cs
index 08cdd1f692..95a6a9c201 100644
--- a/src/System.Diagnostics.DiagnosticSource/tests/ActivityTests.cs
+++ b/src/System.Diagnostics.DiagnosticSource/tests/ActivityTests.cs
@@ -320,10 +320,11 @@ namespace System.Diagnostics.Tests
// DateTime.UtcNow is not precise on some platforms, but Activity stop time is precise
// in this test we set start time, but not stop time and check duration.
//
- // Let's check that duration is 1sec - maximum DateTime.UtcNow error or bigger.
+ // Let's check that duration is 1sec - 2 * maximum DateTime.UtcNow error or bigger.
+ // As both start and stop timestamps may have error.
// There is another test (ActivityDateTimeTests.StartStopReturnsPreciseDuration)
// that checks duration precision on netfx.
- Assert.InRange(activity.Duration.TotalMilliseconds, 1000 - MaxClockErrorMSec, double.MaxValue);
+ Assert.InRange(activity.Duration.TotalMilliseconds, 1000 - 2 * MaxClockErrorMSec, double.MaxValue);
}
/// <summary>
diff --git a/src/System.Diagnostics.DiagnosticSource/tests/DiagnosticSourceEventSourceBridgeTests.cs b/src/System.Diagnostics.DiagnosticSource/tests/DiagnosticSourceEventSourceBridgeTests.cs
index 2c48d49e03..ac5c33fca3 100644
--- a/src/System.Diagnostics.DiagnosticSource/tests/DiagnosticSourceEventSourceBridgeTests.cs
+++ b/src/System.Diagnostics.DiagnosticSource/tests/DiagnosticSourceEventSourceBridgeTests.cs
@@ -22,7 +22,6 @@ namespace System.Diagnostics.Tests
/// the events you want.
/// </summary>
[Fact]
- [ActiveIssue(20579,TargetFrameworkMonikers.UapAot)]
public void TestSpecificEvents()
{
using (var eventSourceListener = new TestDiagnosticSourceEventListener())
@@ -161,7 +160,6 @@ namespace System.Diagnostics.Tests
/// Tests what happens when you wildcard the source name (empty string)
/// </summary>
[Fact]
- [ActiveIssue(20579, TargetFrameworkMonikers.UapAot)]
public void TestWildCardSourceName()
{
using (var eventSourceListener = new TestDiagnosticSourceEventListener())
@@ -223,7 +221,6 @@ namespace System.Diagnostics.Tests
/// Tests what happens when you wildcard event name (but not the source name)
/// </summary>
[Fact]
- [ActiveIssue(20579, TargetFrameworkMonikers.UapAot)]
public void TestWildCardEventName()
{
using (var eventSourceListener = new TestDiagnosticSourceEventListener())
@@ -280,7 +277,6 @@ namespace System.Diagnostics.Tests
/// ignored.
/// </summary>
[Fact]
- [ActiveIssue(20579, TargetFrameworkMonikers.UapAot)]
public void TestNulls()
{
using (var eventSourceListener = new TestDiagnosticSourceEventListener())
@@ -359,7 +355,6 @@ namespace System.Diagnostics.Tests
/// of the payload object.
/// </summary>
[Fact]
- [ActiveIssue(20579, TargetFrameworkMonikers.UapAot)]
public void TestNoImplicitTransforms()
{
using (var eventSourceListener = new TestDiagnosticSourceEventListener())
@@ -390,7 +385,6 @@ namespace System.Diagnostics.Tests
/// Tests what happens when wacky characters are used in property specs.
/// </summary>
[Fact]
- [ActiveIssue(20579, TargetFrameworkMonikers.UapAot)]
public void TestBadProperties()
{
using (var eventSourceListener = new TestDiagnosticSourceEventListener())
@@ -450,7 +444,6 @@ namespace System.Diagnostics.Tests
/// Tests the feature to send the messages as EventSource Activities.
/// </summary>
[Fact]
- [ActiveIssue(20579, TargetFrameworkMonikers.UapAot)]
public void TestActivities()
{
using (var eventSourceListener = new TestDiagnosticSourceEventListener())
@@ -521,7 +514,6 @@ namespace System.Diagnostics.Tests
/// Tests that keywords that define shortcuts work.
/// </summary>
[Fact]
- [ActiveIssue(20579, TargetFrameworkMonikers.UapAot)]
public void TestShortcutKeywords()
{
using (var eventSourceListener = new TestDiagnosticSourceEventListener())
diff --git a/src/System.Diagnostics.Process/src/PinvokeAnalyzerExceptionList.analyzerdata.uap b/src/System.Diagnostics.Process/src/PinvokeAnalyzerExceptionList.analyzerdata.uap
index 07c1cd2c40..566d3c8ea4 100644
--- a/src/System.Diagnostics.Process/src/PinvokeAnalyzerExceptionList.analyzerdata.uap
+++ b/src/System.Diagnostics.Process/src/PinvokeAnalyzerExceptionList.analyzerdata.uap
@@ -1,7 +1,4 @@
advapi32.dll!OpenProcessToken
kernel32.dll!GetProcessAffinityMask
-kernel32.dll!K32EnumProcessModules
kernel32.dll!SetProcessAffinityMask
kernel32.dll!SetThreadAffinityMask
-ntdll.dll!NtQueryInformationProcess
-ntdll.dll!NtQuerySystemInformation \ No newline at end of file
diff --git a/src/System.Diagnostics.Process/src/Resources/Strings.resx b/src/System.Diagnostics.Process/src/Resources/Strings.resx
index fb8b82585a..71dc8266c7 100644
--- a/src/System.Diagnostics.Process/src/Resources/Strings.resx
+++ b/src/System.Diagnostics.Process/src/Resources/Strings.resx
@@ -303,4 +303,7 @@
<data name="UseShellExecuteNotSupported" xml:space="preserve">
<value>UseShellExecute is not supported on this platform.</value>
</data>
+ <data name="GetProcessInfoNotSupported" xml:space="preserve">
+ <value>Retrieving information about local processes is not supported on this platform.</value>
+ </data>
</root> \ No newline at end of file
diff --git a/src/System.Diagnostics.Process/src/System.Diagnostics.Process.csproj b/src/System.Diagnostics.Process/src/System.Diagnostics.Process.csproj
index 0fe703e55e..4e3cd026a1 100644
--- a/src/System.Diagnostics.Process/src/System.Diagnostics.Process.csproj
+++ b/src/System.Diagnostics.Process/src/System.Diagnostics.Process.csproj
@@ -47,6 +47,12 @@
<Compile Include="System\Collections\Specialized\StringDictionaryWrapper.cs" />
</ItemGroup>
<ItemGroup Condition=" '$(TargetsWindows)' == 'true' and '$(TargetGroup)' != 'uap'">
+ <Compile Include="$(CommonPath)\Interop\Windows\kernel32\Interop.EnumProcessModules.cs">
+ <Link>Common\Interop\Windows\kernel32\Interop.EnumProcessModules.cs</Link>
+ </Compile>
+ <Compile Include="$(CommonPath)\Interop\Windows\NtDll\Interop.NtQuerySystemInformation.cs">
+ <Link>Common\Interop\Windows\NtDll\Interop.NtQuerySystemInformation.cs</Link>
+ </Compile>
<Compile Include="$(CommonPath)\Interop\Windows\user32\Interop.EnumWindows.cs">
<Link>Common\Interop\Windows\user32\Interop.EnumWindows.cs</Link>
</Compile>
@@ -115,9 +121,6 @@
<Compile Include="$(CommonPath)\Interop\Windows\kernel32\Interop.OpenProcess.cs">
<Link>Common\Interop\Windows\kernel32\Interop.OpenProcess.cs</Link>
</Compile>
- <Compile Include="$(CommonPath)\Interop\Windows\kernel32\Interop.EnumProcessModules.cs">
- <Link>Common\Interop\Windows\kernel32\Interop.EnumProcessModules.cs</Link>
- </Compile>
<Compile Include="$(CommonPath)\Interop\Windows\kernel32\Interop.EnumProcesses.cs">
<Link>Common\Interop\Windows\kernel32\Interop.EnumProcesses.cs</Link>
</Compile>
@@ -142,6 +145,9 @@
<Compile Include="$(CommonPath)\Interop\Windows\kernel32\Interop.GetProcessAffinityMask.cs">
<Link>Common\Interop\Windows\kernel32\Interop.GetProcessAffinityMask.cs</Link>
</Compile>
+ <Compile Include="$(CommonPath)\Interop\Windows\kernel32\Interop.GetProcessId.cs">
+ <Link>Common\Interop\Windows\kernel32\Interop.GetProcessId.cs</Link>
+ </Compile>
<Compile Include="$(CommonPath)\Interop\Windows\kernel32\Interop.GetThreadPriorityBoost.cs">
<Link>Common\Interop\Windows\kernel32\Interop.GetThreadPriorityBoost.cs</Link>
</Compile>
@@ -175,12 +181,6 @@
<Compile Include="$(CommonPath)\Interop\Windows\kernel32\Interop.SetPriorityClass.cs">
<Link>Common\Interop\Windows\kernel32\Interop.SetPriorityClass.cs</Link>
</Compile>
- <Compile Include="$(CommonPath)\Interop\Windows\NtDll\Interop.NtQueryInformationProcess.cs">
- <Link>Common\Interop\Windows\NtDll\Interop.NtQueryInformationProcess.cs</Link>
- </Compile>
- <Compile Include="$(CommonPath)\Interop\Windows\NtDll\Interop.NtQuerySystemInformation.cs">
- <Link>Common\Interop\Windows\NtDll\Interop.NtQuerySystemInformation.cs</Link>
- </Compile>
<Compile Include="$(CommonPath)\Interop\Windows\kernel32\Interop.DuplicateHandle_SafeProcessHandle.cs">
<Link>Common\Interop\Windows\kernel32\Interop.DuplicateHandle.cs</Link>
</Compile>
@@ -400,6 +400,7 @@
<ItemGroup>
<Reference Include="Microsoft.Win32.Primitives" />
<Reference Condition="'$(TargetGroup)' != 'uap'" Include="Microsoft.Win32.Registry" />
+ <Reference Condition="'$(TargetGroup)' == 'uap'" Include="System.Buffers" />
<Reference Include="System.Collections" />
<Reference Include="System.Collections.NonGeneric" />
<Reference Include="System.Collections.Specialized" />
diff --git a/src/System.Diagnostics.Process/src/System/Diagnostics/ProcessManager.Uap.cs b/src/System.Diagnostics.Process/src/System/Diagnostics/ProcessManager.Uap.cs
index eb614b5636..e4f077d54a 100644
--- a/src/System.Diagnostics.Process/src/System/Diagnostics/ProcessManager.Uap.cs
+++ b/src/System.Diagnostics.Process/src/System/Diagnostics/ProcessManager.Uap.cs
@@ -2,10 +2,13 @@
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
+using System.Buffers;
using System.Collections.Generic;
using System.ComponentModel;
using System.Globalization;
+using System.IO;
using System.Runtime.InteropServices;
+using System.Text;
using System.Threading;
using Microsoft.Win32.SafeHandles;
@@ -14,5 +17,72 @@ namespace System.Diagnostics
internal static partial class ProcessManager
{
public static IntPtr GetMainWindowHandle(int processId) => IntPtr.Zero;
+
+ /// <summary>Gets process infos for each process on the specified machine.</summary>
+ /// <param name="machineName">The target machine.</param>
+ /// <returns>An array of process infos, one per found process.</returns>
+ public static ProcessInfo[] GetProcessInfos(string machineName)
+ {
+ if (!IsRemoteMachine(machineName))
+ throw new PlatformNotSupportedException(SR.GetProcessInfoNotSupported); // NtDll.NtQuerySystemInformation is not available in Uap
+
+ return NtProcessManager.GetProcessInfos(machineName, isRemoteMachine: true);
+ }
+ }
+
+ internal static partial class NtProcessManager
+ {
+ private static ProcessModuleCollection GetModules(int processId, bool firstModuleOnly)
+ {
+ // We don't have a good way of getting all of the modules of the particular process,
+ // but we can at least get the path to the executable file for the process, and
+ // other than for debugging tools, that's the main reason consumers of Modules care about it,
+ // and why MainModule exists.
+ char[] chars = null;
+ int capacity = 64, length = 0;
+ try
+ {
+ // Get the path to the executable
+ using (Process process = Process.GetProcessById(processId))
+ {
+ do
+ {
+ if(chars != null)
+ {
+ ArrayPool<char>.Shared.Return(chars);
+ }
+ capacity = Math.Min(capacity * 2, short.MaxValue);
+ chars = ArrayPool<char>.Shared.Rent(capacity);
+ length = Interop.Kernel32.GetModuleFileNameEx(process.SafeHandle, IntPtr.Zero, chars, chars.Length);
+ // GetModuleFileNameEx truncates the name if capacity isn't sufficient. If provided buffer is full and smaller
+ // than the maximum size of a Windows string (see UNICODE_STRING), retry with a bigger buffer.
+ } while (length == chars.Length - 1 && capacity <= short.MaxValue);
+
+ string exePath = new string(chars, 0, length);
+
+ if (!string.IsNullOrEmpty(exePath))
+ {
+ return new ProcessModuleCollection(1)
+ {
+ new ProcessModule()
+ {
+ FileName = exePath,
+ ModuleName = Path.GetFileName(exePath)
+ }
+ };
+ }
+ }
+ }
+ catch { } // eat all errors
+ finally
+ {
+ if (chars != null)
+ {
+ ArrayPool<char>.Shared.Return(chars);
+ }
+ }
+
+ return new ProcessModuleCollection(0);
+ }
}
}
diff --git a/src/System.Diagnostics.Process/src/System/Diagnostics/ProcessManager.Win32.cs b/src/System.Diagnostics.Process/src/System/Diagnostics/ProcessManager.Win32.cs
index dad3423535..ea44afa15d 100644
--- a/src/System.Diagnostics.Process/src/System/Diagnostics/ProcessManager.Win32.cs
+++ b/src/System.Diagnostics.Process/src/System/Diagnostics/ProcessManager.Win32.cs
@@ -18,6 +18,16 @@ namespace System.Diagnostics
MainWindowFinder finder = new MainWindowFinder();
return finder.FindMainWindow(processId);
}
+
+ /// <summary>Gets process infos for each process on the specified machine.</summary>
+ /// <param name="machineName">The target machine.</param>
+ /// <returns>An array of process infos, one per found process.</returns>
+ public static ProcessInfo[] GetProcessInfos(string machineName)
+ {
+ return IsRemoteMachine(machineName) ?
+ NtProcessManager.GetProcessInfos(machineName, isRemoteMachine: true) :
+ NtProcessInfoHelper.GetProcessInfos(); // Do not use performance counter for local machine
+ }
}
internal sealed class MainWindowFinder
@@ -59,4 +69,252 @@ namespace System.Diagnostics
return true;
}
}
+
+ internal static partial class NtProcessManager
+ {
+ private static ProcessModuleCollection GetModules(int processId, bool firstModuleOnly)
+ {
+ // preserving Everett behavior.
+ if (processId == SystemProcessID || processId == IdleProcessID)
+ {
+ // system process and idle process doesn't have any modules
+ throw new Win32Exception(Interop.Errors.EFail, SR.EnumProcessModuleFailed);
+ }
+
+ SafeProcessHandle processHandle = SafeProcessHandle.InvalidHandle;
+ try
+ {
+ processHandle = ProcessManager.OpenProcess(processId, Interop.Advapi32.ProcessOptions.PROCESS_QUERY_INFORMATION | Interop.Advapi32.ProcessOptions.PROCESS_VM_READ, true);
+
+ IntPtr[] moduleHandles = new IntPtr[64];
+ GCHandle moduleHandlesArrayHandle = new GCHandle();
+ int moduleCount = 0;
+ for (;;)
+ {
+ bool enumResult = false;
+ try
+ {
+ moduleHandlesArrayHandle = GCHandle.Alloc(moduleHandles, GCHandleType.Pinned);
+ enumResult = Interop.Kernel32.EnumProcessModules(processHandle, moduleHandlesArrayHandle.AddrOfPinnedObject(), moduleHandles.Length * IntPtr.Size, ref moduleCount);
+
+ // The API we need to use to enumerate process modules differs on two factors:
+ // 1) If our process is running in WOW64.
+ // 2) The bitness of the process we wish to introspect.
+ //
+ // If we are not running in WOW64 or we ARE in WOW64 but want to inspect a 32 bit process
+ // we can call psapi!EnumProcessModules.
+ //
+ // If we are running in WOW64 and we want to inspect the modules of a 64 bit process then
+ // psapi!EnumProcessModules will return false with ERROR_PARTIAL_COPY (299). In this case we can't
+ // do the enumeration at all. So we'll detect this case and bail out.
+ //
+ // Also, EnumProcessModules is not a reliable method to get the modules for a process.
+ // If OS loader is touching module information, this method might fail and copy part of the data.
+ // This is no easy solution to this problem. The only reliable way to fix this is to
+ // suspend all the threads in target process. Of course we don't want to do this in Process class.
+ // So we just to try avoid the race by calling the same method 50 (an arbitrary number) times.
+ //
+ if (!enumResult)
+ {
+ bool sourceProcessIsWow64 = false;
+ bool targetProcessIsWow64 = false;
+ SafeProcessHandle hCurProcess = SafeProcessHandle.InvalidHandle;
+ try
+ {
+ hCurProcess = ProcessManager.OpenProcess(unchecked((int)Interop.Kernel32.GetCurrentProcessId()), Interop.Advapi32.ProcessOptions.PROCESS_QUERY_INFORMATION, true);
+ bool wow64Ret;
+
+ wow64Ret = Interop.Kernel32.IsWow64Process(hCurProcess, ref sourceProcessIsWow64);
+ if (!wow64Ret)
+ {
+ throw new Win32Exception();
+ }
+
+ wow64Ret = Interop.Kernel32.IsWow64Process(processHandle, ref targetProcessIsWow64);
+ if (!wow64Ret)
+ {
+ throw new Win32Exception();
+ }
+
+ if (sourceProcessIsWow64 && !targetProcessIsWow64)
+ {
+ // Wow64 isn't going to allow this to happen, the best we can do is give a descriptive error to the user.
+ throw new Win32Exception(Interop.Errors.ERROR_PARTIAL_COPY, SR.EnumProcessModuleFailedDueToWow);
+ }
+ }
+ finally
+ {
+ if (hCurProcess != SafeProcessHandle.InvalidHandle)
+ {
+ hCurProcess.Dispose();
+ }
+ }
+
+ // If the failure wasn't due to Wow64, try again.
+ for (int i = 0; i < 50; i++)
+ {
+ enumResult = Interop.Kernel32.EnumProcessModules(processHandle, moduleHandlesArrayHandle.AddrOfPinnedObject(), moduleHandles.Length * IntPtr.Size, ref moduleCount);
+ if (enumResult)
+ {
+ break;
+ }
+ Thread.Sleep(1);
+ }
+ }
+ }
+ finally
+ {
+ moduleHandlesArrayHandle.Free();
+ }
+
+ if (!enumResult)
+ {
+ throw new Win32Exception();
+ }
+
+ moduleCount /= IntPtr.Size;
+ if (moduleCount <= moduleHandles.Length)
+ break;
+ moduleHandles = new IntPtr[moduleHandles.Length * 2];
+ }
+
+ var modules = new ProcessModuleCollection(firstModuleOnly ? 1 : moduleCount);
+
+ char[] chars = new char[1024];
+
+ for (int i = 0; i < moduleCount; i++)
+ {
+ if (i > 0)
+ {
+ // If the user is only interested in the main module, break now.
+ // This avoid some waste of time. In addition, if the application unloads a DLL
+ // we will not get an exception.
+ if (firstModuleOnly)
+ {
+ break;
+ }
+ }
+
+ IntPtr moduleHandle = moduleHandles[i];
+ Interop.Kernel32.NtModuleInfo ntModuleInfo;
+ if (!Interop.Kernel32.GetModuleInformation(processHandle, moduleHandle, out ntModuleInfo))
+ {
+ HandleError();
+ continue;
+ }
+
+ var module = new ProcessModule()
+ {
+ ModuleMemorySize = ntModuleInfo.SizeOfImage,
+ EntryPointAddress = ntModuleInfo.EntryPoint,
+ BaseAddress = ntModuleInfo.BaseOfDll
+ };
+
+ int length = Interop.Kernel32.GetModuleBaseName(processHandle, moduleHandle, chars, chars.Length);
+ if (length == 0)
+ {
+ HandleError();
+ continue;
+ }
+
+ module.ModuleName = new string(chars, 0, length);
+
+ length = Interop.Kernel32.GetModuleFileNameEx(processHandle, moduleHandle, chars, chars.Length);
+ if (length == 0)
+ {
+ HandleError();
+ continue;
+ }
+
+ module.FileName = (length >= 4 && chars[0] == '\\' && chars[1] == '\\' && chars[2] == '?' && chars[3] == '\\') ?
+ new string(chars, 4, length - 4) :
+ new string(chars, 0, length);
+
+ modules.Add(module);
+ }
+
+ return modules;
+ }
+ finally
+ {
+#if FEATURE_TRACESWITCH
+ Debug.WriteLineIf(Process._processTracing.TraceVerbose, "Process - CloseHandle(process)");
+#endif
+ if (!processHandle.IsInvalid)
+ {
+ processHandle.Dispose();
+ }
+ }
+ }
+ }
+
+ internal static partial class NtProcessInfoHelper
+ {
+ // Cache a single buffer for use in GetProcessInfos().
+ private static long[] CachedBuffer;
+
+ public static ProcessInfo[] GetProcessInfos()
+ {
+ int requiredSize = 0;
+ int status;
+
+ ProcessInfo[] processInfos;
+ GCHandle bufferHandle = new GCHandle();
+
+ // Start with the default buffer size.
+ int bufferSize = DefaultCachedBufferSize;
+
+ // Get the cached buffer.
+ long[] buffer = Interlocked.Exchange(ref CachedBuffer, null);
+
+ try
+ {
+ do
+ {
+ if (buffer == null)
+ {
+ // Allocate buffer of longs since some platforms require the buffer to be 64-bit aligned.
+ buffer = new long[(bufferSize + 7) / 8];
+ }
+ else
+ {
+ // If we have cached buffer, set the size properly.
+ bufferSize = buffer.Length * sizeof(long);
+ }
+
+ bufferHandle = GCHandle.Alloc(buffer, GCHandleType.Pinned);
+
+ status = Interop.NtDll.NtQuerySystemInformation(
+ Interop.NtDll.NtQuerySystemProcessInformation,
+ bufferHandle.AddrOfPinnedObject(),
+ bufferSize,
+ out requiredSize);
+
+ if (unchecked((uint)status) == Interop.NtDll.STATUS_INFO_LENGTH_MISMATCH)
+ {
+ if (bufferHandle.IsAllocated) bufferHandle.Free();
+ buffer = null;
+ bufferSize = GetNewBufferSize(bufferSize, requiredSize);
+ }
+ } while (unchecked((uint)status) == Interop.NtDll.STATUS_INFO_LENGTH_MISMATCH);
+
+ if (status < 0)
+ { // see definition of NT_SUCCESS(Status) in SDK
+ throw new InvalidOperationException(SR.CouldntGetProcessInfos, new Win32Exception(status));
+ }
+
+ // Parse the data block to get process information
+ processInfos = GetProcessInfos(bufferHandle.AddrOfPinnedObject());
+ }
+ finally
+ {
+ // Cache the final buffer for use on the next call.
+ Interlocked.Exchange(ref CachedBuffer, buffer);
+
+ if (bufferHandle.IsAllocated) bufferHandle.Free();
+ }
+
+ return processInfos;
+ }
+ }
}
diff --git a/src/System.Diagnostics.Process/src/System/Diagnostics/ProcessManager.Windows.cs b/src/System.Diagnostics.Process/src/System/Diagnostics/ProcessManager.Windows.cs
index 7865e72ffe..80a79f9a01 100644
--- a/src/System.Diagnostics.Process/src/System/Diagnostics/ProcessManager.Windows.cs
+++ b/src/System.Diagnostics.Process/src/System/Diagnostics/ProcessManager.Windows.cs
@@ -61,16 +61,6 @@ namespace System.Diagnostics
return null;
}
- /// <summary>Gets process infos for each process on the specified machine.</summary>
- /// <param name="machineName">The target machine.</param>
- /// <returns>An array of process infos, one per found process.</returns>
- public static ProcessInfo[] GetProcessInfos(string machineName)
- {
- return IsRemoteMachine(machineName) ?
- NtProcessManager.GetProcessInfos(machineName, true) :
- NtProcessInfoHelper.GetProcessInfos(); // Do not use performance counter for local machine
- }
-
/// <summary>Gets the IDs of all processes on the specified machine.</summary>
/// <param name="machineName">The machine to examine.</param>
/// <returns>An array of process IDs from the specified machine.</returns>
@@ -215,7 +205,7 @@ namespace System.Diagnostics
/// information. Module information is obtained using PSAPI.
/// </devdoc>
/// <internalonly/>
- internal static class NtProcessManager
+ internal static partial class NtProcessManager
{
private const int ProcessPerfCounterId = 230;
private const int ThreadPerfCounterId = 232;
@@ -294,180 +284,6 @@ namespace System.Diagnostics
return modules.Count == 0 ? null : modules[0];
}
- private static ProcessModuleCollection GetModules(int processId, bool firstModuleOnly)
- {
- // preserving Everett behavior.
- if (processId == SystemProcessID || processId == IdleProcessID)
- {
- // system process and idle process doesn't have any modules
- throw new Win32Exception(Interop.Errors.EFail, SR.EnumProcessModuleFailed);
- }
-
- SafeProcessHandle processHandle = SafeProcessHandle.InvalidHandle;
- try
- {
- processHandle = ProcessManager.OpenProcess(processId, Interop.Advapi32.ProcessOptions.PROCESS_QUERY_INFORMATION | Interop.Advapi32.ProcessOptions.PROCESS_VM_READ, true);
-
- IntPtr[] moduleHandles = new IntPtr[64];
- GCHandle moduleHandlesArrayHandle = new GCHandle();
- int moduleCount = 0;
- for (; ; )
- {
- bool enumResult = false;
- try
- {
- moduleHandlesArrayHandle = GCHandle.Alloc(moduleHandles, GCHandleType.Pinned);
- enumResult = Interop.Kernel32.EnumProcessModules(processHandle, moduleHandlesArrayHandle.AddrOfPinnedObject(), moduleHandles.Length * IntPtr.Size, ref moduleCount);
-
- // The API we need to use to enumerate process modules differs on two factors:
- // 1) If our process is running in WOW64.
- // 2) The bitness of the process we wish to introspect.
- //
- // If we are not running in WOW64 or we ARE in WOW64 but want to inspect a 32 bit process
- // we can call psapi!EnumProcessModules.
- //
- // If we are running in WOW64 and we want to inspect the modules of a 64 bit process then
- // psapi!EnumProcessModules will return false with ERROR_PARTIAL_COPY (299). In this case we can't
- // do the enumeration at all. So we'll detect this case and bail out.
- //
- // Also, EnumProcessModules is not a reliable method to get the modules for a process.
- // If OS loader is touching module information, this method might fail and copy part of the data.
- // This is no easy solution to this problem. The only reliable way to fix this is to
- // suspend all the threads in target process. Of course we don't want to do this in Process class.
- // So we just to try avoid the race by calling the same method 50 (an arbitrary number) times.
- //
- if (!enumResult)
- {
- bool sourceProcessIsWow64 = false;
- bool targetProcessIsWow64 = false;
- SafeProcessHandle hCurProcess = SafeProcessHandle.InvalidHandle;
- try
- {
- hCurProcess = ProcessManager.OpenProcess(unchecked((int)Interop.Kernel32.GetCurrentProcessId()), Interop.Advapi32.ProcessOptions.PROCESS_QUERY_INFORMATION, true);
- bool wow64Ret;
-
- wow64Ret = Interop.Kernel32.IsWow64Process(hCurProcess, ref sourceProcessIsWow64);
- if (!wow64Ret)
- {
- throw new Win32Exception();
- }
-
- wow64Ret = Interop.Kernel32.IsWow64Process(processHandle, ref targetProcessIsWow64);
- if (!wow64Ret)
- {
- throw new Win32Exception();
- }
-
- if (sourceProcessIsWow64 && !targetProcessIsWow64)
- {
- // Wow64 isn't going to allow this to happen, the best we can do is give a descriptive error to the user.
- throw new Win32Exception(Interop.Errors.ERROR_PARTIAL_COPY, SR.EnumProcessModuleFailedDueToWow);
- }
- }
- finally
- {
- if (hCurProcess != SafeProcessHandle.InvalidHandle)
- {
- hCurProcess.Dispose();
- }
- }
-
- // If the failure wasn't due to Wow64, try again.
- for (int i = 0; i < 50; i++)
- {
- enumResult = Interop.Kernel32.EnumProcessModules(processHandle, moduleHandlesArrayHandle.AddrOfPinnedObject(), moduleHandles.Length * IntPtr.Size, ref moduleCount);
- if (enumResult)
- {
- break;
- }
- Thread.Sleep(1);
- }
- }
- }
- finally
- {
- moduleHandlesArrayHandle.Free();
- }
-
- if (!enumResult)
- {
- throw new Win32Exception();
- }
-
- moduleCount /= IntPtr.Size;
- if (moduleCount <= moduleHandles.Length) break;
- moduleHandles = new IntPtr[moduleHandles.Length * 2];
- }
-
- var modules = new ProcessModuleCollection(firstModuleOnly ? 1 : moduleCount);
-
- char[] chars = new char[1024];
-
- for (int i = 0; i < moduleCount; i++)
- {
- if (i > 0)
- {
- // If the user is only interested in the main module, break now.
- // This avoid some waste of time. In addition, if the application unloads a DLL
- // we will not get an exception.
- if (firstModuleOnly)
- {
- break;
- }
- }
-
- IntPtr moduleHandle = moduleHandles[i];
- Interop.Kernel32.NtModuleInfo ntModuleInfo;
- if (!Interop.Kernel32.GetModuleInformation(processHandle, moduleHandle, out ntModuleInfo))
- {
- HandleError();
- continue;
- }
-
- var module = new ProcessModule()
- {
- ModuleMemorySize = ntModuleInfo.SizeOfImage,
- EntryPointAddress = ntModuleInfo.EntryPoint,
- BaseAddress = ntModuleInfo.BaseOfDll
- };
-
- int length = Interop.Kernel32.GetModuleBaseName(processHandle, moduleHandle, chars, chars.Length);
- if (length == 0)
- {
- HandleError();
- continue;
- }
-
- module.ModuleName = new string(chars, 0, length);
-
- length = Interop.Kernel32.GetModuleFileNameEx(processHandle, moduleHandle, chars, chars.Length);
- if (length == 0)
- {
- HandleError();
- continue;
- }
-
- module.FileName = (length >= 4 && chars[0] == '\\' && chars[1] == '\\' && chars[2] == '?' && chars[3] == '\\') ?
- new string(chars, 4, length - 4) :
- new string(chars, 0, length);
-
- modules.Add(module);
- }
-
- return modules;
- }
- finally
- {
-#if FEATURE_TRACESWITCH
- Debug.WriteLineIf(Process._processTracing.TraceVerbose, "Process - CloseHandle(process)");
-#endif
- if (!processHandle.IsInvalid)
- {
- processHandle.Dispose();
- }
- }
- }
-
private static void HandleError()
{
int lastError = Marshal.GetLastWin32Error();
@@ -486,14 +302,7 @@ namespace System.Diagnostics
public static int GetProcessIdFromHandle(SafeProcessHandle processHandle)
{
- Interop.NtDll.NtProcessBasicInfo info = new Interop.NtDll.NtProcessBasicInfo();
- int status = Interop.NtDll.NtQueryInformationProcess(processHandle, Interop.NtDll.NtQueryProcessBasicInfo, info, (int)Marshal.SizeOf(info), null);
- if (status != 0)
- {
- throw new InvalidOperationException(SR.CantGetProcessId, new Win32Exception(status));
- }
- // We should change the signature of this function and ID property in process class.
- return info.UniqueProcessId.ToInt32();
+ return Interop.Kernel32.GetProcessId(processHandle);
}
public static ProcessInfo[] GetProcessInfos(string machineName, bool isRemoteMachine)
@@ -828,7 +637,7 @@ namespace System.Diagnostics
}
- internal static class NtProcessInfoHelper
+ internal static partial class NtProcessInfoHelper
{
private static int GetNewBufferSize(int existingBufferSize, int requiredSize)
{
@@ -860,70 +669,6 @@ namespace System.Diagnostics
}
}
- public static ProcessInfo[] GetProcessInfos()
- {
- int requiredSize = 0;
- int status;
-
- ProcessInfo[] processInfos;
- GCHandle bufferHandle = new GCHandle();
-
- // Start with the default buffer size.
- int bufferSize = DefaultCachedBufferSize;
-
- // Get the cached buffer.
- long[] buffer = Interlocked.Exchange(ref CachedBuffer, null);
-
- try
- {
- do
- {
- if (buffer == null)
- {
- // Allocate buffer of longs since some platforms require the buffer to be 64-bit aligned.
- buffer = new long[(bufferSize + 7) / 8];
- }
- else
- {
- // If we have cached buffer, set the size properly.
- bufferSize = buffer.Length * sizeof(long);
- }
-
- bufferHandle = GCHandle.Alloc(buffer, GCHandleType.Pinned);
-
- status = Interop.NtDll.NtQuerySystemInformation(
- Interop.NtDll.NtQuerySystemProcessInformation,
- bufferHandle.AddrOfPinnedObject(),
- bufferSize,
- out requiredSize);
-
- if (unchecked((uint)status) == Interop.NtDll.STATUS_INFO_LENGTH_MISMATCH)
- {
- if (bufferHandle.IsAllocated) bufferHandle.Free();
- buffer = null;
- bufferSize = GetNewBufferSize(bufferSize, requiredSize);
- }
- } while (unchecked((uint)status) == Interop.NtDll.STATUS_INFO_LENGTH_MISMATCH);
-
- if (status < 0)
- { // see definition of NT_SUCCESS(Status) in SDK
- throw new InvalidOperationException(SR.CouldntGetProcessInfos, new Win32Exception(status));
- }
-
- // Parse the data block to get process information
- processInfos = GetProcessInfos(bufferHandle.AddrOfPinnedObject());
- }
- finally
- {
- // Cache the final buffer for use on the next call.
- Interlocked.Exchange(ref CachedBuffer, buffer);
-
- if (bufferHandle.IsAllocated) bufferHandle.Free();
- }
-
- return processInfos;
- }
-
// Use a smaller buffer size on debug to ensure we hit the retry path.
#if DEBUG
private const int DefaultCachedBufferSize = 1024;
@@ -931,9 +676,6 @@ namespace System.Diagnostics
private const int DefaultCachedBufferSize = 128 * 1024;
#endif
- // Cache a single buffer for use in GetProcessInfos().
- private static long[] CachedBuffer;
-
private static unsafe ProcessInfo[] GetProcessInfos(IntPtr dataPtr)
{
// Use a dictionary to avoid duplicate entries if any
diff --git a/src/System.Diagnostics.Process/tests/Configurations.props b/src/System.Diagnostics.Process/tests/Configurations.props
index c71f0fb5ae..f333d20c1a 100644
--- a/src/System.Diagnostics.Process/tests/Configurations.props
+++ b/src/System.Diagnostics.Process/tests/Configurations.props
@@ -4,7 +4,6 @@
<BuildConfigurations>
netstandard-Windows_NT;
netstandard-Unix;
- uap-Windows_NT;
</BuildConfigurations>
</PropertyGroup>
</Project> \ No newline at end of file
diff --git a/src/System.Diagnostics.Process/tests/ProcessCollectionTests.cs b/src/System.Diagnostics.Process/tests/ProcessCollectionTests.cs
index 3a4e3976b7..b4d2f1d8e6 100644
--- a/src/System.Diagnostics.Process/tests/ProcessCollectionTests.cs
+++ b/src/System.Diagnostics.Process/tests/ProcessCollectionTests.cs
@@ -59,6 +59,7 @@ namespace System.Diagnostics.Tests
}
[Fact]
+ [SkipOnTargetFramework(TargetFrameworkMonikers.UapNotUapAot, "https://github.com/dotnet/corefx/issues/22174")]
public void TestThreadCollectionBehavior()
{
CreateDefaultProcess();
diff --git a/src/System.Diagnostics.Process/tests/ProcessModuleTests.cs b/src/System.Diagnostics.Process/tests/ProcessModuleTests.cs
index dbb45872ef..9142a2989e 100644
--- a/src/System.Diagnostics.Process/tests/ProcessModuleTests.cs
+++ b/src/System.Diagnostics.Process/tests/ProcessModuleTests.cs
@@ -29,6 +29,7 @@ namespace System.Diagnostics.Tests
}
[Fact]
+ [SkipOnTargetFramework(TargetFrameworkMonikers.UapNotUapAot, "https://github.com/dotnet/corefx/issues/22174")]
public void Modules_Get_ContainsHostFileName()
{
ProcessModuleCollection modules = Process.GetCurrentProcess().Modules;
diff --git a/src/System.Diagnostics.Process/tests/ProcessStandardConsoleTests.cs b/src/System.Diagnostics.Process/tests/ProcessStandardConsoleTests.cs
index 95e46e1f88..828802ac87 100644
--- a/src/System.Diagnostics.Process/tests/ProcessStandardConsoleTests.cs
+++ b/src/System.Diagnostics.Process/tests/ProcessStandardConsoleTests.cs
@@ -14,6 +14,7 @@ namespace System.Diagnostics.Tests
private const int s_ConsoleEncoding = 437;
[Fact]
+ [SkipOnTargetFramework(TargetFrameworkMonikers.UapNotUapAot, "https://github.com/dotnet/corefx/issues/22174")]
public void TestChangesInConsoleEncoding()
{
Action<int> run = expectedCodePage =>
diff --git a/src/System.Diagnostics.Process/tests/ProcessStartInfoTests.cs b/src/System.Diagnostics.Process/tests/ProcessStartInfoTests.cs
index 3bd28ffc73..5c3fa0335e 100644
--- a/src/System.Diagnostics.Process/tests/ProcessStartInfoTests.cs
+++ b/src/System.Diagnostics.Process/tests/ProcessStartInfoTests.cs
@@ -196,6 +196,7 @@ namespace System.Diagnostics.Tests
}
[Fact]
+ [SkipOnTargetFramework(TargetFrameworkMonikers.UapNotUapAot, "https://github.com/dotnet/corefx/issues/22174")]
public void TestEnvironmentOfChildProcess()
{
const string ItemSeparator = "CAFF9451396B4EEF8A5155A15BDC2080"; // random string that shouldn't be in any env vars; used instead of newline to separate env var strings
@@ -322,6 +323,7 @@ namespace System.Diagnostics.Tests
}
[Theory, InlineData(true), InlineData(false)]
+ [SkipOnTargetFramework(TargetFrameworkMonikers.UapNotUapAot, "https://github.com/dotnet/corefx/issues/22174")]
public void TestCreateNoWindowProperty(bool value)
{
Process testProcess = CreateProcessLong();
@@ -342,6 +344,7 @@ namespace System.Diagnostics.Tests
}
[Fact]
+ [SkipOnTargetFramework(TargetFrameworkMonikers.UapNotUapAot, "https://github.com/dotnet/corefx/issues/22174")]
public void TestWorkingDirectoryProperty()
{
CreateDefaultProcess();
@@ -502,6 +505,7 @@ namespace System.Diagnostics.Tests
[PlatformSpecific(TestPlatforms.Windows)] // Test case is specific to Windows
[Fact]
+ [SkipOnTargetFramework(TargetFrameworkMonikers.UapNotUapAot, "https://github.com/dotnet/corefx/issues/22174")]
public void Verbs_GetWithExeExtension_ReturnsExpected()
{
var psi = new ProcessStartInfo { FileName = $"{Process.GetCurrentProcess().ProcessName}.exe" };
@@ -672,7 +676,8 @@ namespace System.Diagnostics.Tests
[PlatformSpecific(TestPlatforms.AnyUnix)] // Test case is specific to Unix
[Fact]
- public void TestEnvironmentVariablesPropertyUnix(){
+ public void TestEnvironmentVariablesPropertyUnix()
+ {
ProcessStartInfo psi = new ProcessStartInfo();
// Creating a detached ProcessStartInfo will pre-populate the environment
diff --git a/src/System.Diagnostics.Process/tests/ProcessStreamReadTests.cs b/src/System.Diagnostics.Process/tests/ProcessStreamReadTests.cs
index f08acfa95f..c79ed6bbd9 100644
--- a/src/System.Diagnostics.Process/tests/ProcessStreamReadTests.cs
+++ b/src/System.Diagnostics.Process/tests/ProcessStreamReadTests.cs
@@ -10,6 +10,7 @@ using Xunit;
namespace System.Diagnostics.Tests
{
+ [SkipOnTargetFramework(TargetFrameworkMonikers.UapNotUapAot, "https://github.com/dotnet/corefx/issues/22174")]
public class ProcessStreamReadTests : ProcessTestBase
{
[Fact]
diff --git a/src/System.Diagnostics.Process/tests/ProcessTestBase.cs b/src/System.Diagnostics.Process/tests/ProcessTestBase.cs
index 6c08c56ee0..1f347e80eb 100644
--- a/src/System.Diagnostics.Process/tests/ProcessTestBase.cs
+++ b/src/System.Diagnostics.Process/tests/ProcessTestBase.cs
@@ -10,7 +10,7 @@ namespace System.Diagnostics.Tests
{
public class ProcessTestBase : RemoteExecutorTestBase
{
- protected const int WaitInMS = 600 * 1000;
+ protected const int WaitInMS = 30 * 1000;
protected Process _process;
protected readonly List<Process> _processes = new List<Process>();
diff --git a/src/System.Diagnostics.Process/tests/ProcessTests.cs b/src/System.Diagnostics.Process/tests/ProcessTests.cs
index 4a1fb8269a..814dc6c0d3 100644
--- a/src/System.Diagnostics.Process/tests/ProcessTests.cs
+++ b/src/System.Diagnostics.Process/tests/ProcessTests.cs
@@ -59,6 +59,7 @@ namespace System.Diagnostics.Tests
}
[Fact]
+ [SkipOnTargetFramework(TargetFrameworkMonikers.UapNotUapAot, "https://github.com/dotnet/corefx/issues/22174")]
[PlatformSpecific(TestPlatforms.Windows)] // Expected behavior varies on Windows and Unix
public void TestBasePriorityOnWindows()
{
@@ -88,6 +89,7 @@ namespace System.Diagnostics.Tests
}
[Theory]
+ [SkipOnTargetFramework(TargetFrameworkMonikers.UapNotUapAot, "https://github.com/dotnet/corefx/issues/22174")]
[InlineData(true)]
[InlineData(false)]
[InlineData(null)]
@@ -120,6 +122,7 @@ namespace System.Diagnostics.Tests
}
[Fact]
+ [SkipOnTargetFramework(TargetFrameworkMonikers.UapNotUapAot, "https://github.com/dotnet/corefx/issues/22174")]
public void TestExitCode()
{
{
@@ -137,6 +140,7 @@ namespace System.Diagnostics.Tests
}
[Fact]
+ [SkipOnTargetFramework(TargetFrameworkMonikers.UapNotUapAot, "https://github.com/dotnet/corefx/issues/22174")]
public void TestExitTime()
{
// ExitTime resolution on some platforms is less accurate than our DateTime.UtcNow resolution, so
@@ -164,6 +168,7 @@ namespace System.Diagnostics.Tests
}
[Fact]
+ [SkipOnTargetFramework(TargetFrameworkMonikers.UapNotUapAot, "https://github.com/dotnet/corefx/issues/22174")]
public void TestId()
{
CreateDefaultProcess();
@@ -180,6 +185,7 @@ namespace System.Diagnostics.Tests
}
[Fact]
+ [SkipOnTargetFramework(TargetFrameworkMonikers.UapNotUapAot, "https://github.com/dotnet/corefx/issues/22174")]
public void TestHasExited()
{
{
@@ -221,6 +227,7 @@ namespace System.Diagnostics.Tests
}
[Fact]
+ [SkipOnTargetFramework(TargetFrameworkMonikers.UapNotUapAot, "https://github.com/dotnet/corefx/issues/22174")]
public void TestMachineName()
{
CreateDefaultProcess();
@@ -237,6 +244,7 @@ namespace System.Diagnostics.Tests
}
[Fact]
+ [SkipOnTargetFramework(TargetFrameworkMonikers.UapNotUapAot, "https://github.com/dotnet/corefx/issues/22174")]
public void TestMainModuleOnNonOSX()
{
Process p = Process.GetCurrentProcess();
@@ -247,6 +255,7 @@ namespace System.Diagnostics.Tests
}
[Fact]
+ [SkipOnTargetFramework(TargetFrameworkMonikers.UapNotUapAot, "https://github.com/dotnet/corefx/issues/22174")]
public void TestMaxWorkingSet()
{
CreateDefaultProcess();
@@ -301,6 +310,7 @@ namespace System.Diagnostics.Tests
}
[Fact]
+ [SkipOnTargetFramework(TargetFrameworkMonikers.UapNotUapAot, "https://github.com/dotnet/corefx/issues/22174")]
public void TestMinWorkingSet()
{
CreateDefaultProcess();
@@ -372,6 +382,7 @@ namespace System.Diagnostics.Tests
}
[Fact]
+ [SkipOnTargetFramework(TargetFrameworkMonikers.UapNotUapAot, "https://github.com/dotnet/corefx/issues/22174")]
public void TestNonpagedSystemMemorySize64()
{
CreateDefaultProcess();
@@ -387,6 +398,7 @@ namespace System.Diagnostics.Tests
}
[Fact]
+ [SkipOnTargetFramework(TargetFrameworkMonikers.UapNotUapAot, "https://github.com/dotnet/corefx/issues/22174")]
public void TestPagedMemorySize64()
{
CreateDefaultProcess();
@@ -402,6 +414,7 @@ namespace System.Diagnostics.Tests
}
[Fact]
+ [SkipOnTargetFramework(TargetFrameworkMonikers.UapNotUapAot, "https://github.com/dotnet/corefx/issues/22174")]
public void TestPagedSystemMemorySize64()
{
CreateDefaultProcess();
@@ -417,6 +430,7 @@ namespace System.Diagnostics.Tests
}
[Fact]
+ [SkipOnTargetFramework(TargetFrameworkMonikers.UapNotUapAot, "https://github.com/dotnet/corefx/issues/22174")]
public void TestPeakPagedMemorySize64()
{
CreateDefaultProcess();
@@ -432,6 +446,7 @@ namespace System.Diagnostics.Tests
}
[Fact]
+ [SkipOnTargetFramework(TargetFrameworkMonikers.UapNotUapAot, "https://github.com/dotnet/corefx/issues/22174")]
public void TestPeakVirtualMemorySize64()
{
CreateDefaultProcess();
@@ -447,6 +462,7 @@ namespace System.Diagnostics.Tests
}
[Fact]
+ [SkipOnTargetFramework(TargetFrameworkMonikers.UapNotUapAot, "https://github.com/dotnet/corefx/issues/22174")]
public void TestPeakWorkingSet64()
{
CreateDefaultProcess();
@@ -462,6 +478,7 @@ namespace System.Diagnostics.Tests
}
[Fact]
+ [SkipOnTargetFramework(TargetFrameworkMonikers.UapNotUapAot, "https://github.com/dotnet/corefx/issues/22174")]
public void TestPrivateMemorySize64()
{
CreateDefaultProcess();
@@ -477,6 +494,7 @@ namespace System.Diagnostics.Tests
}
[Fact]
+ [SkipOnTargetFramework(TargetFrameworkMonikers.UapNotUapAot, "https://github.com/dotnet/corefx/issues/22174")]
public void TestVirtualMemorySize64()
{
CreateDefaultProcess();
@@ -492,6 +510,7 @@ namespace System.Diagnostics.Tests
}
[Fact]
+ [SkipOnTargetFramework(TargetFrameworkMonikers.UapNotUapAot, "https://github.com/dotnet/corefx/issues/22174")]
public void TestWorkingSet64()
{
CreateDefaultProcess();
@@ -514,6 +533,7 @@ namespace System.Diagnostics.Tests
}
[Fact]
+ [SkipOnTargetFramework(TargetFrameworkMonikers.UapNotUapAot, "https://github.com/dotnet/corefx/issues/22174")]
public void TestProcessorTime()
{
CreateDefaultProcess();
@@ -557,6 +577,7 @@ namespace System.Diagnostics.Tests
}
[Fact]
+ [SkipOnTargetFramework(TargetFrameworkMonikers.UapNotUapAot, "https://github.com/dotnet/corefx/issues/22174")]
public void TestProcessStartTime()
{
TimeSpan allowedWindow = TimeSpan.FromSeconds(3);
@@ -580,6 +601,7 @@ namespace System.Diagnostics.Tests
}
[Fact]
+ [SkipOnTargetFramework(TargetFrameworkMonikers.UapNotUapAot, "https://github.com/dotnet/corefx/issues/22174")]
[PlatformSpecific(~TestPlatforms.OSX)] // getting/setting affinity not supported on OSX
public void TestProcessorAffinity()
{
@@ -599,6 +621,7 @@ namespace System.Diagnostics.Tests
}
[Fact]
+ [SkipOnTargetFramework(TargetFrameworkMonikers.UapNotUapAot, "https://github.com/dotnet/corefx/issues/22174")]
public void TestPriorityBoostEnabled()
{
CreateDefaultProcess();
@@ -628,6 +651,7 @@ namespace System.Diagnostics.Tests
}
[Fact, PlatformSpecific(TestPlatforms.Windows)] // Expected behavior varies on Windows and Unix
+ [SkipOnTargetFramework(TargetFrameworkMonikers.UapNotUapAot, "https://github.com/dotnet/corefx/issues/22174")]
public void TestPriorityClassWindows()
{
CreateDefaultProcess();
@@ -664,6 +688,7 @@ namespace System.Diagnostics.Tests
}
[Fact]
+ [SkipOnTargetFramework(TargetFrameworkMonikers.UapNotUapAot, "https://github.com/dotnet/corefx/issues/22174")]
public void TestProcessName()
{
CreateDefaultProcess();
@@ -681,6 +706,7 @@ namespace System.Diagnostics.Tests
}
[Fact]
+ [SkipOnTargetFramework(TargetFrameworkMonikers.UapNotUapAot, "https://github.com/dotnet/corefx/issues/22174")]
public void TestSafeHandle()
{
CreateDefaultProcess();
@@ -696,6 +722,7 @@ namespace System.Diagnostics.Tests
}
[Fact]
+ [SkipOnTargetFramework(TargetFrameworkMonikers.UapNotUapAot, "https://github.com/dotnet/corefx/issues/22174")]
public void TestSessionId()
{
CreateDefaultProcess();
@@ -734,6 +761,7 @@ namespace System.Diagnostics.Tests
}
[Fact]
+ [SkipOnTargetFramework(TargetFrameworkMonikers.UapNotUapAot, "https://github.com/dotnet/corefx/issues/22174")]
public void TestGetProcessById()
{
CreateDefaultProcess();
@@ -744,6 +772,7 @@ namespace System.Diagnostics.Tests
}
[Fact]
+ [SkipOnTargetFramework(TargetFrameworkMonikers.UapNotUapAot, "https://github.com/dotnet/corefx/issues/22174")]
public void TestGetProcesses()
{
Process currentProcess = Process.GetCurrentProcess();
@@ -775,6 +804,7 @@ namespace System.Diagnostics.Tests
}
[Fact]
+ [SkipOnTargetFramework(TargetFrameworkMonikers.UapNotUapAot, "https://github.com/dotnet/corefx/issues/22174")]
public void GetProcessesByName_ProcessName_ReturnsExpected()
{
// Get the current process using its name
@@ -800,6 +830,7 @@ namespace System.Diagnostics.Tests
}
[Theory]
+ [SkipOnTargetFramework(TargetFrameworkMonikers.UapNotUapAot, "https://github.com/dotnet/corefx/issues/22174")]
[MemberData(nameof(MachineName_TestData))]
public void GetProcessesByName_ProcessNameMachineName_ReturnsExpected(string machineName)
{
@@ -826,6 +857,7 @@ namespace System.Diagnostics.Tests
}
[Fact]
+ [SkipOnTargetFramework(TargetFrameworkMonikers.UapNotUapAot, "https://github.com/dotnet/corefx/issues/22174")]
public void GetProcessesByName_NoSuchProcess_ReturnsEmpty()
{
string processName = Guid.NewGuid().ToString("N");
@@ -833,6 +865,7 @@ namespace System.Diagnostics.Tests
}
[Fact]
+ [SkipOnTargetFramework(TargetFrameworkMonikers.UapNotUapAot, "https://github.com/dotnet/corefx/issues/22174")]
public void GetProcessesByName_NullMachineName_ThrowsArgumentNullException()
{
Process currentProcess = Process.GetCurrentProcess();
@@ -840,6 +873,7 @@ namespace System.Diagnostics.Tests
}
[Fact]
+ [SkipOnTargetFramework(TargetFrameworkMonikers.UapNotUapAot, "https://github.com/dotnet/corefx/issues/22174")]
public void GetProcessesByName_EmptyMachineName_ThrowsArgumentException()
{
Process currentProcess = Process.GetCurrentProcess();
@@ -849,6 +883,7 @@ namespace System.Diagnostics.Tests
[Fact]
[PlatformSpecific(TestPlatforms.Windows)] // Behavior differs on Windows and Unix
[ActiveIssue("https://github.com/dotnet/corefx/issues/18212", TargetFrameworkMonikers.UapAot)]
+ [SkipOnTargetFramework(TargetFrameworkMonikers.UapNotUapAot, "https://github.com/dotnet/corefx/issues/22174")]
public void TestProcessOnRemoteMachineWindows()
{
Process currentProccess = Process.GetCurrentProcess();
@@ -876,6 +911,7 @@ namespace System.Diagnostics.Tests
}
[Fact]
+ [SkipOnTargetFramework(TargetFrameworkMonikers.UapNotUapAot, "https://github.com/dotnet/corefx/issues/22174")]
public void StartInfo_GetFileName_ReturnsExpected()
{
Process process = CreateProcessLong();
@@ -890,6 +926,7 @@ namespace System.Diagnostics.Tests
}
[Fact]
+ [SkipOnTargetFramework(TargetFrameworkMonikers.UapNotUapAot, "https://github.com/dotnet/corefx/issues/22174")]
public void StartInfo_SetOnRunningProcess_ThrowsInvalidOperationException()
{
Process process = CreateProcessLong();
@@ -946,6 +983,7 @@ namespace System.Diagnostics.Tests
}
[Theory]
+ [SkipOnTargetFramework(TargetFrameworkMonikers.UapNotUapAot, "https://github.com/dotnet/corefx/issues/22174")]
[InlineData(@"""abc"" d e", @"abc,d,e")]
[InlineData(@"""abc"" d e", @"abc,d,e")]
[InlineData("\"abc\"\t\td\te", @"abc,d,e")]
@@ -1086,6 +1124,7 @@ namespace System.Diagnostics.Tests
}
[Fact]
+ [SkipOnTargetFramework(TargetFrameworkMonikers.UapNotUapAot, "https://github.com/dotnet/corefx/issues/22174")]
[PlatformSpecific(TestPlatforms.Linux | TestPlatforms.Windows)] // Expected process HandleCounts differs on OSX
public void TestHandleCount()
{
@@ -1108,6 +1147,7 @@ namespace System.Diagnostics.Tests
[Fact]
[PlatformSpecific(TestPlatforms.Linux | TestPlatforms.Windows)] // Expected process HandleCounts differs on OSX
[SkipOnTargetFramework(TargetFrameworkMonikers.NetFramework, "Handle count change is not reliable, but seems less robust on NETFX")]
+ [SkipOnTargetFramework(TargetFrameworkMonikers.UapNotUapAot, "https://github.com/dotnet/corefx/issues/22174")]
public void HandleCountChanges()
{
RemoteInvoke(() =>
@@ -1138,6 +1178,7 @@ namespace System.Diagnostics.Tests
}
[Fact]
+ [SkipOnTargetFramework(TargetFrameworkMonikers.UapNotUapAot, "https://github.com/dotnet/corefx/issues/22174")]
[PlatformSpecific(TestPlatforms.Windows)] // MainWindowHandle is not supported on Unix.
public void MainWindowHandle_NoWindow_ReturnsEmptyHandle()
{
@@ -1157,6 +1198,7 @@ namespace System.Diagnostics.Tests
}
[Fact]
+ [SkipOnTargetFramework(TargetFrameworkMonikers.UapNotUapAot, "https://github.com/dotnet/corefx/issues/22174")]
public void MainWindowTitle_NoWindow_ReturnsEmpty()
{
CreateDefaultProcess();
@@ -1175,6 +1217,7 @@ namespace System.Diagnostics.Tests
}
[Fact]
+ [SkipOnTargetFramework(TargetFrameworkMonikers.UapNotUapAot, "https://github.com/dotnet/corefx/issues/22174")]
public void CloseMainWindow_NoWindow_ReturnsFalse()
{
CreateDefaultProcess();
@@ -1183,7 +1226,8 @@ namespace System.Diagnostics.Tests
}
[Fact]
- [PlatformSpecific(TestPlatforms.Windows)] // CloseMainWindow is a no-op and always returns false on Unix.
+ [PlatformSpecific(TestPlatforms.Windows)] // CloseMainWindow is a no-op and always returns false on Unix.
+ [SkipOnTargetFramework(TargetFrameworkMonikers.UapNotUapAot, "https://github.com/dotnet/corefx/issues/22174")]
public void CloseMainWindow_NotStarted_ThrowsInvalidOperationException()
{
var process = new Process();
@@ -1210,6 +1254,7 @@ namespace System.Diagnostics.Tests
}
[Fact]
+ [SkipOnTargetFramework(TargetFrameworkMonikers.UapNotUapAot, "https://github.com/dotnet/corefx/issues/22174")]
public void TestNonpagedSystemMemorySize()
{
CreateDefaultProcess();
@@ -1229,6 +1274,7 @@ namespace System.Diagnostics.Tests
}
[Fact]
+ [SkipOnTargetFramework(TargetFrameworkMonikers.UapNotUapAot, "https://github.com/dotnet/corefx/issues/22174")]
public void TestPagedMemorySize()
{
CreateDefaultProcess();
@@ -1248,6 +1294,7 @@ namespace System.Diagnostics.Tests
}
[Fact]
+ [SkipOnTargetFramework(TargetFrameworkMonikers.UapNotUapAot, "https://github.com/dotnet/corefx/issues/22174")]
public void TestPagedSystemMemorySize()
{
CreateDefaultProcess();
@@ -1267,6 +1314,7 @@ namespace System.Diagnostics.Tests
}
[Fact]
+ [SkipOnTargetFramework(TargetFrameworkMonikers.UapNotUapAot, "https://github.com/dotnet/corefx/issues/22174")]
public void TestPeakPagedMemorySize()
{
CreateDefaultProcess();
@@ -1286,6 +1334,7 @@ namespace System.Diagnostics.Tests
}
[Fact]
+ [SkipOnTargetFramework(TargetFrameworkMonikers.UapNotUapAot, "https://github.com/dotnet/corefx/issues/22174")]
public void TestPeakVirtualMemorySize()
{
CreateDefaultProcess();
@@ -1305,6 +1354,7 @@ namespace System.Diagnostics.Tests
}
[Fact]
+ [SkipOnTargetFramework(TargetFrameworkMonikers.UapNotUapAot, "https://github.com/dotnet/corefx/issues/22174")]
public void TestPeakWorkingSet()
{
CreateDefaultProcess();
@@ -1324,6 +1374,7 @@ namespace System.Diagnostics.Tests
}
[Fact]
+ [SkipOnTargetFramework(TargetFrameworkMonikers.UapNotUapAot, "https://github.com/dotnet/corefx/issues/22174")]
public void TestPrivateMemorySize()
{
CreateDefaultProcess();
@@ -1343,6 +1394,7 @@ namespace System.Diagnostics.Tests
}
[Fact]
+ [SkipOnTargetFramework(TargetFrameworkMonikers.UapNotUapAot, "https://github.com/dotnet/corefx/issues/22174")]
public void TestVirtualMemorySize()
{
CreateDefaultProcess();
@@ -1362,6 +1414,7 @@ namespace System.Diagnostics.Tests
}
[Fact]
+ [SkipOnTargetFramework(TargetFrameworkMonikers.UapNotUapAot, "https://github.com/dotnet/corefx/issues/22174")]
public void TestWorkingSet()
{
CreateDefaultProcess();
@@ -1400,6 +1453,7 @@ namespace System.Diagnostics.Tests
[Fact]
[PlatformSpecific(TestPlatforms.Windows)] // Starting process with authentication not supported on Unix
+ [SkipOnTargetFramework(TargetFrameworkMonikers.UapNotUapAot, "https://github.com/dotnet/corefx/issues/22174")]
public void Process_StartWithInvalidUserNamePassword()
{
SecureString password = AsSecureString("Value");
@@ -1409,6 +1463,7 @@ namespace System.Diagnostics.Tests
[Fact]
[PlatformSpecific(TestPlatforms.Windows)] // Starting process with authentication not supported on Unix
+ [SkipOnTargetFramework(TargetFrameworkMonikers.UapNotUapAot, "https://github.com/dotnet/corefx/issues/22174")]
public void Process_StartTest()
{
string currentProcessName = GetCurrentProcessName();
@@ -1429,6 +1484,7 @@ namespace System.Diagnostics.Tests
[Fact]
[PlatformSpecific(TestPlatforms.Windows)] // Starting process with authentication not supported on Unix
+ [SkipOnTargetFramework(TargetFrameworkMonikers.UapNotUapAot, "https://github.com/dotnet/corefx/issues/22174")]
public void Process_StartWithArgumentsTest()
{
string currentProcessName = GetCurrentProcessName();
diff --git a/src/System.Diagnostics.Process/tests/ProcessThreadTests.cs b/src/System.Diagnostics.Process/tests/ProcessThreadTests.cs
index b2c5945536..e5354803b6 100644
--- a/src/System.Diagnostics.Process/tests/ProcessThreadTests.cs
+++ b/src/System.Diagnostics.Process/tests/ProcessThreadTests.cs
@@ -14,6 +14,7 @@ namespace System.Diagnostics.Tests
public class ProcessThreadTests : ProcessTestBase
{
[Fact]
+ [SkipOnTargetFramework(TargetFrameworkMonikers.UapNotUapAot, "https://github.com/dotnet/corefx/issues/22174")]
public void TestCommonPriorityAndTimeProperties()
{
CreateDefaultProcess();
@@ -44,6 +45,7 @@ namespace System.Diagnostics.Tests
}
[Fact]
+ [SkipOnTargetFramework(TargetFrameworkMonikers.UapNotUapAot, "https://github.com/dotnet/corefx/issues/22174")]
public void TestThreadCount()
{
int numOfThreads = 10;
@@ -85,6 +87,7 @@ namespace System.Diagnostics.Tests
[Fact]
[PlatformSpecific(~TestPlatforms.OSX)] // OSX throws PNSE from StartTime
+ [SkipOnTargetFramework(TargetFrameworkMonikers.UapNotUapAot, "https://github.com/dotnet/corefx/issues/22174")]
public async Task TestStartTimeProperty()
{
TimeSpan allowedWindow = TimeSpan.FromSeconds(1);
@@ -137,6 +140,7 @@ namespace System.Diagnostics.Tests
}
[Fact]
+ [SkipOnTargetFramework(TargetFrameworkMonikers.UapNotUapAot, "https://github.com/dotnet/corefx/issues/22174")]
public void TestStartAddressProperty()
{
using (Process p = Process.GetCurrentProcess())
@@ -153,6 +157,7 @@ namespace System.Diagnostics.Tests
}
[Fact]
+ [SkipOnTargetFramework(TargetFrameworkMonikers.UapNotUapAot, "https://github.com/dotnet/corefx/issues/22174")]
public void TestPriorityLevelProperty()
{
CreateDefaultProcess();
@@ -186,6 +191,7 @@ namespace System.Diagnostics.Tests
}
[Fact]
+ [SkipOnTargetFramework(TargetFrameworkMonikers.UapNotUapAot, "https://github.com/dotnet/corefx/issues/22174")]
public void TestThreadStateProperty()
{
CreateDefaultProcess();
@@ -198,6 +204,7 @@ namespace System.Diagnostics.Tests
}
[Fact]
+ [SkipOnTargetFramework(TargetFrameworkMonikers.UapNotUapAot, "https://github.com/dotnet/corefx/issues/22174")]
public void Threads_GetMultipleTimes_ReturnsSameInstance()
{
CreateDefaultProcess();
diff --git a/src/System.Diagnostics.Process/tests/ProcessWaitingTests.cs b/src/System.Diagnostics.Process/tests/ProcessWaitingTests.cs
index e0d20fc299..06690580dc 100644
--- a/src/System.Diagnostics.Process/tests/ProcessWaitingTests.cs
+++ b/src/System.Diagnostics.Process/tests/ProcessWaitingTests.cs
@@ -11,6 +11,7 @@ namespace System.Diagnostics.Tests
public class ProcessWaitingTests : ProcessTestBase
{
[Fact]
+ [SkipOnTargetFramework(TargetFrameworkMonikers.UapNotUapAot, "https://github.com/dotnet/corefx/issues/22174")]
public void MultipleProcesses_StartAllKillAllWaitAll()
{
const int Iters = 10;
@@ -22,6 +23,7 @@ namespace System.Diagnostics.Tests
}
[Fact]
+ [SkipOnTargetFramework(TargetFrameworkMonikers.UapNotUapAot, "https://github.com/dotnet/corefx/issues/22174")]
public void MultipleProcesses_SerialStartKillWait()
{
const int Iters = 10;
@@ -35,6 +37,7 @@ namespace System.Diagnostics.Tests
}
[Fact]
+ [SkipOnTargetFramework(TargetFrameworkMonikers.UapNotUapAot, "https://github.com/dotnet/corefx/issues/22174")]
public void MultipleProcesses_ParallelStartKillWait()
{
const int Tasks = 4, ItersPerTask = 10;
@@ -60,6 +63,7 @@ namespace System.Diagnostics.Tests
}
[Fact]
+ [SkipOnTargetFramework(TargetFrameworkMonikers.UapNotUapAot, "https://github.com/dotnet/corefx/issues/22174")]
public void SingleProcess_TryWaitMultipleTimesBeforeCompleting()
{
Process p = CreateProcessLong();
@@ -80,6 +84,7 @@ namespace System.Diagnostics.Tests
}
[Theory]
+ [SkipOnTargetFramework(TargetFrameworkMonikers.UapNotUapAot, "https://github.com/dotnet/corefx/issues/22174")]
[InlineData(false)]
[InlineData(true)]
public async Task SingleProcess_WaitAfterExited(bool addHandlerBeforeStart)
@@ -105,6 +110,7 @@ namespace System.Diagnostics.Tests
}
[Theory]
+ [SkipOnTargetFramework(TargetFrameworkMonikers.UapNotUapAot, "https://github.com/dotnet/corefx/issues/22174")]
[ActiveIssue("https://github.com/dotnet/corefx/issues/18210", TargetFrameworkMonikers.UapAot)]
[InlineData(0)]
[InlineData(1)]
@@ -123,6 +129,7 @@ namespace System.Diagnostics.Tests
}
[Fact]
+ [SkipOnTargetFramework(TargetFrameworkMonikers.UapNotUapAot, "https://github.com/dotnet/corefx/issues/22174")]
public void SingleProcess_CopiesShareExitInformation()
{
Process p = CreateProcessLong();
@@ -141,6 +148,7 @@ namespace System.Diagnostics.Tests
}
[Fact]
+ [SkipOnTargetFramework(TargetFrameworkMonikers.UapNotUapAot, "https://github.com/dotnet/corefx/issues/22174")]
public void WaitForPeerProcess()
{
Process child1 = CreateProcessLong();
@@ -167,6 +175,7 @@ namespace System.Diagnostics.Tests
}
[Fact]
+ [SkipOnTargetFramework(TargetFrameworkMonikers.UapNotUapAot, "https://github.com/dotnet/corefx/issues/22174")]
[ActiveIssue(15844, TestPlatforms.AnyUnix)]
public void WaitChain()
{
@@ -195,6 +204,7 @@ namespace System.Diagnostics.Tests
}
[Fact]
+ [SkipOnTargetFramework(TargetFrameworkMonikers.UapNotUapAot, "https://github.com/dotnet/corefx/issues/22174")]
public void WaitForSelfTerminatingChild()
{
Process child = CreateProcess(() =>
diff --git a/src/System.Diagnostics.Process/tests/System.Diagnostics.Process.Tests.csproj b/src/System.Diagnostics.Process/tests/System.Diagnostics.Process.Tests.csproj
index ae6b50a8a8..8fa2eb6f56 100644
--- a/src/System.Diagnostics.Process/tests/System.Diagnostics.Process.Tests.csproj
+++ b/src/System.Diagnostics.Process/tests/System.Diagnostics.Process.Tests.csproj
@@ -6,18 +6,12 @@
<AllowUnsafeBlocks>true</AllowUnsafeBlocks>
<DefineConstants Condition="'$(TargetsWindows)' == 'true'">$(DefineConstants);TargetsWindows</DefineConstants>
</PropertyGroup>
+ <!-- Default configurations to help VS understand the configurations -->
<PropertyGroup Condition="'$(Configuration)|$(Platform)' == 'netstandard-Unix-Debug|AnyCPU'" />
<PropertyGroup Condition="'$(Configuration)|$(Platform)' == 'netstandard-Unix-Release|AnyCPU'" />
<PropertyGroup Condition="'$(Configuration)|$(Platform)' == 'netstandard-Windows_NT-Debug|AnyCPU'" />
<PropertyGroup Condition="'$(Configuration)|$(Platform)' == 'netstandard-Windows_NT-Release|AnyCPU'" />
- <PropertyGroup Condition="'$(Configuration)|$(Platform)' == 'uap-Windows_NT-Debug|AnyCPU'" />
- <PropertyGroup Condition="'$(Configuration)|$(Platform)' == 'uap-Windows_NT-Release|AnyCPU'" />
- <!-- Default configurations to help VS understand the configurations -->
- <!-- Disable the whole Process tests on UAP with the active issue https://github.com/dotnet/corefx/issues/20948 -->
- <ItemGroup Condition="'$(TargetGroup)' != 'uap'">
- <Compile Include="$(CommonTestPath)\System\AssertExtensions.cs">
- <Link>Common\System\AssertExtensions.cs</Link>
- </Compile>
+ <ItemGroup>
<Compile Include="$(CommonTestPath)\System\PlatformDetection.cs">
<Link>Common\tests\System\PlatformDetection.cs</Link>
</Compile>
diff --git a/src/System.Diagnostics.StackTrace/tests/System.Diagnostics.StackTrace.Tests.csproj b/src/System.Diagnostics.StackTrace/tests/System.Diagnostics.StackTrace.Tests.csproj
index 15739e4a6f..2bc1b752ce 100644
--- a/src/System.Diagnostics.StackTrace/tests/System.Diagnostics.StackTrace.Tests.csproj
+++ b/src/System.Diagnostics.StackTrace/tests/System.Diagnostics.StackTrace.Tests.csproj
@@ -17,9 +17,6 @@
<Compile Include="SymbolTokenTests.cs" />
<Compile Include="StackFrameTests.cs" />
<Compile Include="StackFrameExtensionsTests.cs" Condition="'$(TargetGroup)' != 'netfx'" />
- <Compile Include="$(CommonTestPath)\System\AssertExtensions.cs">
- <Link>Common\System\AssertExtensions.cs</Link>
- </Compile>
<Compile Include="$(CommonTestPath)\System\PlatformDetection.cs">
<Link>Common\System\PlatformDetection.cs</Link>
</Compile>
diff --git a/src/System.Diagnostics.TextWriterTraceListener/tests/System.Diagnostics.TextWriterTraceListener.Tests.csproj b/src/System.Diagnostics.TextWriterTraceListener/tests/System.Diagnostics.TextWriterTraceListener.Tests.csproj
index 163556b0ce..bceee637e1 100644
--- a/src/System.Diagnostics.TextWriterTraceListener/tests/System.Diagnostics.TextWriterTraceListener.Tests.csproj
+++ b/src/System.Diagnostics.TextWriterTraceListener/tests/System.Diagnostics.TextWriterTraceListener.Tests.csproj
@@ -14,9 +14,6 @@
<Compile Include="TextWriterTraceListener_WriteTests.cs" />
<Compile Include="CtorsStreamTests.cs" />
<Compile Include="DelimiterWriteMethodTests.cs" />
- <Compile Include="$(CommonTestPath)\System\AssertExtensions.cs">
- <Link>Common\System\AssertExtensions.cs</Link>
- </Compile>
</ItemGroup>
<Import Project="$([MSBuild]::GetDirectoryNameOfFileAbove($(MSBuildThisFileDirectory), dir.targets))\dir.targets" />
</Project> \ No newline at end of file
diff --git a/src/System.Diagnostics.TraceSource/tests/System.Diagnostics.TraceSource.Tests.csproj b/src/System.Diagnostics.TraceSource/tests/System.Diagnostics.TraceSource.Tests.csproj
index 58badc80b5..95f0ae1f70 100644
--- a/src/System.Diagnostics.TraceSource/tests/System.Diagnostics.TraceSource.Tests.csproj
+++ b/src/System.Diagnostics.TraceSource/tests/System.Diagnostics.TraceSource.Tests.csproj
@@ -31,9 +31,6 @@
<Compile Include="TraceSwitchClassTests.cs" />
<Compile Include="TraceTestHelper.cs" />
<Compile Include="CorrelationManagerTests.cs" />
- <Compile Include="$(CommonTestPath)\System\AssertExtensions.cs">
- <Link>Common\System\AssertExtensions.cs</Link>
- </Compile>
<Compile Include="$(CommonTestPath)\System\PlatformDetection.cs">
<Link>Common\tests\System\PlatformDetection.cs</Link>
</Compile>
diff --git a/src/System.Diagnostics.Tracing/tests/BasicEventSourceTest/FuzzyTests.cs b/src/System.Diagnostics.Tracing/tests/BasicEventSourceTest/FuzzyTests.cs
index d60c3fe92a..72476cb0a5 100644
--- a/src/System.Diagnostics.Tracing/tests/BasicEventSourceTest/FuzzyTests.cs
+++ b/src/System.Diagnostics.Tracing/tests/BasicEventSourceTest/FuzzyTests.cs
@@ -22,7 +22,6 @@ namespace BasicEventSourceTests
///
/// </summary>
[Fact]
- [ActiveIssue(20744,TargetFrameworkMonikers.UapAot)]
public void Test_Write_Fuzzy()
{
using (var logger = new EventSource("EventSourceName"))
diff --git a/src/System.Diagnostics.Tracing/tests/BasicEventSourceTest/LoudListener.cs b/src/System.Diagnostics.Tracing/tests/BasicEventSourceTest/LoudListener.cs
index 65d77a3c97..f5280d0dbe 100644
--- a/src/System.Diagnostics.Tracing/tests/BasicEventSourceTest/LoudListener.cs
+++ b/src/System.Diagnostics.Tracing/tests/BasicEventSourceTest/LoudListener.cs
@@ -13,9 +13,8 @@ namespace BasicEventSourceTests
[ThreadStatic]
public static EventWrittenEventArgs t_lastEvent;
- protected override void OnEventSourceCreated(EventSource eventSource)
+ public LoudListener(EventSource eventSource)
{
- base.OnEventSourceCreated(eventSource);
EnableEvents(eventSource, EventLevel.LogAlways, (EventKeywords)0xffffffff);
}
diff --git a/src/System.Diagnostics.Tracing/tests/BasicEventSourceTest/TestsEventSourceLifetime.cs b/src/System.Diagnostics.Tracing/tests/BasicEventSourceTest/TestsEventSourceLifetime.cs
index c81548001a..f9d1ffd2fd 100644
--- a/src/System.Diagnostics.Tracing/tests/BasicEventSourceTest/TestsEventSourceLifetime.cs
+++ b/src/System.Diagnostics.Tracing/tests/BasicEventSourceTest/TestsEventSourceLifetime.cs
@@ -21,7 +21,7 @@ namespace BasicEventSourceTests
/// </summary>
[Fact]
[PlatformSpecific(TestPlatforms.Windows)] // non-Windows EventSources don't have lifetime
- [ActiveIssue(20837,TargetFrameworkMonikers.UapAot)]
+ [SkipOnTargetFramework(TargetFrameworkMonikers.UapAot, "Test requires private reflection.")]
public void Test_EventSource_Lifetime()
{
TestUtilities.CheckNoEventSourcesRunning("Start");
diff --git a/src/System.Diagnostics.Tracing/tests/BasicEventSourceTest/TestsManifestGeneration.cs b/src/System.Diagnostics.Tracing/tests/BasicEventSourceTest/TestsManifestGeneration.cs
index d138998231..26d6f21d4c 100644
--- a/src/System.Diagnostics.Tracing/tests/BasicEventSourceTest/TestsManifestGeneration.cs
+++ b/src/System.Diagnostics.Tracing/tests/BasicEventSourceTest/TestsManifestGeneration.cs
@@ -30,7 +30,7 @@ namespace BasicEventSourceTests
{
using (var es = new SdtEventSources.DontPollute.EventSource())
{
- using (var el = new LoudListener())
+ using (var el = new LoudListener(es))
{
int i = 12;
es.EventWrite(i);
diff --git a/src/System.Diagnostics.Tracing/tests/BasicEventSourceTest/TestsManifestNegative.cs b/src/System.Diagnostics.Tracing/tests/BasicEventSourceTest/TestsManifestNegative.cs
index 22dede4ab5..13b392930e 100644
--- a/src/System.Diagnostics.Tracing/tests/BasicEventSourceTest/TestsManifestNegative.cs
+++ b/src/System.Diagnostics.Tracing/tests/BasicEventSourceTest/TestsManifestNegative.cs
@@ -18,8 +18,17 @@ namespace BasicEventSourceTests
{
public class TestsManifestNegative
{
+ private static void AsserExceptionStringsEqual(Func<string> expectedStrFunc, Exception ex)
+ {
+ if (!PlatformDetection.IsNetNative)
+ {
+ string expectedStr = expectedStrFunc();
+ Assert.Equal(ex.Message, expectedStr);
+ }
+ }
+
#region Message string building
- public static string GetResourceString(string key, params object[] args)
+ private static string GetResourceString(string key, params object[] args)
{
string fmt = GetResourceStringFromReflection(key);
if (fmt != null)
@@ -59,10 +68,10 @@ namespace BasicEventSourceTests
Assert.NotNull(EventSource.GenerateManifest(typeof(Sdt.UnsealedEventSource), string.Empty));
Exception e = AssertExtensions.Throws<ArgumentException>(null, () => EventSource.GenerateManifest(typeof(Sdt.UnsealedEventSource), string.Empty, strictOptions));
- Assert.Equal(GetResourceString("EventSource_TypeMustBeSealedOrAbstract"), e.Message);
+ AsserExceptionStringsEqual(() => GetResourceString("EventSource_TypeMustBeSealedOrAbstract"), e);
e = AssertExtensions.Throws<ArgumentException>(null, () => EventSource.GenerateManifest(typeof(Sdt.UnsealedEventSource), string.Empty, strictOptions));
- Assert.Equal(GetResourceString("EventSource_TypeMustBeSealedOrAbstract"), e.Message);
+ AsserExceptionStringsEqual(() => GetResourceString("EventSource_TypeMustBeSealedOrAbstract"), e);
// starting with NuGet we allow non-void returning methods as long as they have the [Event] attribute
Assert.NotNull(EventSource.GenerateManifest(typeof(Sdt.EventWithReturnEventSource), string.Empty));
@@ -72,19 +81,19 @@ namespace BasicEventSourceTests
Assert.NotNull(EventSource.GenerateManifest(typeof(Sdt.EventWithReturnEventSource), string.Empty, EventManifestOptions.AllowEventSourceOverride));
e = AssertExtensions.Throws<ArgumentException>(null, () => EventSource.GenerateManifest(typeof(Sdt.NegativeEventIdEventSource), string.Empty));
- Assert.Equal(GetResourceString("EventSource_NeedPositiveId", "WriteInteger"), e.Message);
+ AsserExceptionStringsEqual(() => GetResourceString("EventSource_NeedPositiveId", "WriteInteger"), e);
e = AssertExtensions.Throws<ArgumentException>(null, () => EventSource.GenerateManifest(typeof(Sdt.NegativeEventIdEventSource), string.Empty, strictOptions));
- Assert.Equal(GetResourceString("EventSource_NeedPositiveId", "WriteInteger"), e.Message);
+ AsserExceptionStringsEqual(() => GetResourceString("EventSource_NeedPositiveId", "WriteInteger"), e);
e = AssertExtensions.Throws<ArgumentException>(null, () => EventSource.GenerateManifest(typeof(Sdt.NegativeEventIdEventSource), string.Empty, EventManifestOptions.AllowEventSourceOverride));
- Assert.Equal(GetResourceString("EventSource_NeedPositiveId", "WriteInteger"), e.Message);
+ AsserExceptionStringsEqual(() => GetResourceString("EventSource_NeedPositiveId", "WriteInteger"), e);
e = AssertExtensions.Throws<ArgumentException>(null, () => EventSource.GenerateManifest(typeof(Sdt.OutOfRangeKwdEventSource), string.Empty, strictOptions));
- Assert.Equal(String.Join(Environment.NewLine,
+ AsserExceptionStringsEqual(() => String.Join(Environment.NewLine,
GetResourceString("EventSource_IllegalKeywordsValue", "Kwd1", "0x100000000000"),
GetResourceString("EventSource_KeywordCollision", "Session3", "Kwd1", "0x100000000000")),
- e.Message);
+ e);
#if FEATURE_ADVANCED_MANAGED_ETW_CHANNELS
e = AssertExtensions.Throws<ArgumentException>(GetResourceString("EventSource_MaxChannelExceeded"),
@@ -97,103 +106,108 @@ namespace BasicEventSourceTests
#endif // USE_ETW
e = AssertExtensions.Throws<ArgumentException>(null, () => EventSource.GenerateManifest(typeof(Sdt.ReservedOpcodeEventSource), string.Empty, strictOptions));
- Assert.Equal(String.Join(Environment.NewLine,
+ AsserExceptionStringsEqual(() => String.Join(Environment.NewLine,
GetResourceString("EventSource_IllegalOpcodeValue", "Op1", 3),
GetResourceString("EventSource_EventMustHaveTaskIfNonDefaultOpcode", "WriteInteger", 1)),
- e.Message);
+ e);
e = AssertExtensions.Throws<ArgumentException>(null, () => EventSource.GenerateManifest(typeof(Sdt.ReservedOpcodeEventSource), string.Empty, strictOptions));
- Assert.Equal(String.Join(Environment.NewLine,
+ AsserExceptionStringsEqual(() => String.Join(Environment.NewLine,
GetResourceString("EventSource_IllegalOpcodeValue", "Op1", 3),
GetResourceString("EventSource_EventMustHaveTaskIfNonDefaultOpcode", "WriteInteger", 1)),
- e.Message);
+ e);
e = AssertExtensions.Throws<ArgumentException>(null, () => EventSource.GenerateManifest(typeof(Sdt.EnumKindMismatchEventSource), string.Empty));
- Assert.Equal(GetResourceString("EventSource_UndefinedKeyword", "0x1", "WriteInteger"), e.Message);
+ AsserExceptionStringsEqual(() => GetResourceString("EventSource_UndefinedKeyword", "0x1", "WriteInteger"), e);
e = AssertExtensions.Throws<ArgumentException>(null, () => EventSource.GenerateManifest(typeof(Sdt.EnumKindMismatchEventSource), string.Empty, strictOptions));
- Assert.Equal(String.Join(Environment.NewLine,
+ AsserExceptionStringsEqual(() => String.Join(Environment.NewLine,
GetResourceString("EventSource_EnumKindMismatch", "Op1", "EventKeywords", "Opcodes"),
GetResourceString("EventSource_UndefinedKeyword", "0x1", "WriteInteger")),
- e.Message);
+ e);
e = AssertExtensions.Throws<ArgumentException>(null, () => EventSource.GenerateManifest(typeof(Sdt.EnumKindMismatchEventSource), string.Empty, EventManifestOptions.AllowEventSourceOverride));
- Assert.Equal(GetResourceString("EventSource_UndefinedKeyword", "0x1", "WriteInteger"), e.Message);
+ AsserExceptionStringsEqual(() => GetResourceString("EventSource_UndefinedKeyword", "0x1", "WriteInteger"), e);
Assert.NotNull(EventSource.GenerateManifest(typeof(Sdt.MismatchIdEventSource), string.Empty));
- e = AssertExtensions.Throws<ArgumentException>(null, () => EventSource.GenerateManifest(typeof(Sdt.MismatchIdEventSource), string.Empty, strictOptions));
- Assert.Equal(GetResourceString("EventSource_MismatchIdToWriteEvent", "WriteInteger", 10, 1), e.Message);
+ // These tests require the IL to be present for inspection.
+ if (!PlatformDetection.IsNetNative)
+ {
+ e = AssertExtensions.Throws<ArgumentException>(null, () => EventSource.GenerateManifest(typeof(Sdt.MismatchIdEventSource), string.Empty, strictOptions));
+ AsserExceptionStringsEqual(() => GetResourceString("EventSource_MismatchIdToWriteEvent", "WriteInteger", 10, 1), e);
- e = AssertExtensions.Throws<ArgumentException>(null, () => EventSource.GenerateManifest(typeof(Sdt.MismatchIdEventSource), string.Empty, strictOptions));
- Assert.Equal(GetResourceString("EventSource_MismatchIdToWriteEvent", "WriteInteger", 10, 1), e.Message);
+ e = AssertExtensions.Throws<ArgumentException>(null, () => EventSource.GenerateManifest(typeof(Sdt.MismatchIdEventSource), string.Empty, strictOptions));
+ AsserExceptionStringsEqual(() => GetResourceString("EventSource_MismatchIdToWriteEvent", "WriteInteger", 10, 1), e);
+ }
Assert.NotNull(EventSource.GenerateManifest(typeof(Sdt.EventIdReusedEventSource), string.Empty));
e = AssertExtensions.Throws<ArgumentException>(null, () => EventSource.GenerateManifest(typeof(Sdt.EventIdReusedEventSource), string.Empty, strictOptions));
- Assert.Equal(String.Join(Environment.NewLine,
+ AsserExceptionStringsEqual(() => String.Join(Environment.NewLine,
GetResourceString("EventSource_EventIdReused", "WriteInteger2", 1, "WriteInteger1"),
GetResourceString("EventSource_TaskOpcodePairReused", "WriteInteger2", 1, "WriteInteger1", 1)),
- e.Message);
+ e);
+
e = AssertExtensions.Throws<ArgumentException>(null, () => EventSource.GenerateManifest(typeof(Sdt.EventIdReusedEventSource), string.Empty, strictOptions));
- Assert.Equal(String.Join(Environment.NewLine,
+ AsserExceptionStringsEqual(() => String.Join(Environment.NewLine,
GetResourceString("EventSource_EventIdReused", "WriteInteger2", 1, "WriteInteger1"),
GetResourceString("EventSource_TaskOpcodePairReused", "WriteInteger2", 1, "WriteInteger1", 1)),
- e.Message);
+ e);
e = AssertExtensions.Throws<ArgumentException>(null, () => EventSource.GenerateManifest(typeof(Sdt.EventNameReusedEventSource), string.Empty, strictOptions));
- Assert.Equal(GetResourceString("EventSource_EventNameReused", "WriteInteger"), e.Message);
+ AsserExceptionStringsEqual(() => GetResourceString("EventSource_EventNameReused", "WriteInteger"), e);
e = AssertExtensions.Throws<ArgumentException>(null, () => EventSource.GenerateManifest(typeof(Sdt.EventNameReusedEventSource), string.Empty, strictOptions));
- Assert.Equal(GetResourceString("EventSource_EventNameReused", "WriteInteger"), e.Message);
+ AsserExceptionStringsEqual(() => GetResourceString("EventSource_EventNameReused", "WriteInteger"), e);
Assert.NotNull(EventSource.GenerateManifest(typeof(Sdt.TaskOpcodePairReusedEventSource), string.Empty));
e = AssertExtensions.Throws<ArgumentException>(null, () => EventSource.GenerateManifest(typeof(Sdt.TaskOpcodePairReusedEventSource), string.Empty, strictOptions));
- Assert.Equal(GetResourceString("EventSource_TaskOpcodePairReused", "WriteInteger2", 2, "WriteInteger1", 1), e.Message);
+ AsserExceptionStringsEqual(() => GetResourceString("EventSource_TaskOpcodePairReused", "WriteInteger2", 2, "WriteInteger1", 1), e);
e = AssertExtensions.Throws<ArgumentException>(null, () => EventSource.GenerateManifest(typeof(Sdt.TaskOpcodePairReusedEventSource), string.Empty, strictOptions));
- Assert.Equal(GetResourceString("EventSource_TaskOpcodePairReused", "WriteInteger2", 2, "WriteInteger1", 1), e.Message);
+ AsserExceptionStringsEqual(() => GetResourceString("EventSource_TaskOpcodePairReused", "WriteInteger2", 2, "WriteInteger1", 1), e);
Assert.NotNull(EventSource.GenerateManifest(typeof(Sdt.EventWithOpcodeNoTaskEventSource), string.Empty));
e = AssertExtensions.Throws<ArgumentException>(null, () => EventSource.GenerateManifest(typeof(Sdt.EventWithOpcodeNoTaskEventSource), string.Empty, strictOptions));
- Assert.Equal(GetResourceString("EventSource_EventMustHaveTaskIfNonDefaultOpcode", "WriteInteger", 1), e.Message);
+ AsserExceptionStringsEqual(() => GetResourceString("EventSource_EventMustHaveTaskIfNonDefaultOpcode", "WriteInteger", 1), e);
e = AssertExtensions.Throws<ArgumentException>(null, () => EventSource.GenerateManifest(typeof(Sdt.EventWithOpcodeNoTaskEventSource), string.Empty, strictOptions));
- Assert.Equal(GetResourceString("EventSource_EventMustHaveTaskIfNonDefaultOpcode", "WriteInteger", 1), e.Message);
+ AsserExceptionStringsEqual(() => GetResourceString("EventSource_EventMustHaveTaskIfNonDefaultOpcode", "WriteInteger", 1), e);
Assert.NotNull(EventSource.GenerateManifest(typeof(Sdt.EventWithInvalidMessageEventSource), string.Empty));
e = AssertExtensions.Throws<ArgumentException>(null, () => EventSource.GenerateManifest(typeof(Sdt.EventWithInvalidMessageEventSource), string.Empty, strictOptions));
- Assert.Equal(GetResourceString("EventSource_UnsupportedMessageProperty", "WriteString", "Message = {0,12:G}"), e.Message);
+ AsserExceptionStringsEqual(() => GetResourceString("EventSource_UnsupportedMessageProperty", "WriteString", "Message = {0,12:G}"), e);
e = AssertExtensions.Throws<ArgumentException>(null, () => EventSource.GenerateManifest(typeof(Sdt.AbstractWithKwdTaskOpcodeEventSource), string.Empty, strictOptions));
- Assert.Equal(String.Join(Environment.NewLine,
+ AsserExceptionStringsEqual(() => String.Join(Environment.NewLine,
GetResourceString("EventSource_AbstractMustNotDeclareKTOC", "Keywords"),
GetResourceString("EventSource_AbstractMustNotDeclareKTOC", "Tasks"),
GetResourceString("EventSource_AbstractMustNotDeclareKTOC", "Opcodes")),
- e.Message);
+ e);
e = AssertExtensions.Throws<ArgumentException>(null, () => EventSource.GenerateManifest(typeof(Sdt.AbstractWithKwdTaskOpcodeEventSource), string.Empty, strictOptions));
- Assert.Equal(String.Join(Environment.NewLine,
+ AsserExceptionStringsEqual(() => String.Join(Environment.NewLine,
GetResourceString("EventSource_AbstractMustNotDeclareKTOC", "Keywords"),
GetResourceString("EventSource_AbstractMustNotDeclareKTOC", "Tasks"),
GetResourceString("EventSource_AbstractMustNotDeclareKTOC", "Opcodes")),
- e.Message);
+ e);
e = AssertExtensions.Throws<ArgumentException>(null, () => EventSource.GenerateManifest(typeof(Sdt.AbstractWithEventsEventSource), string.Empty, strictOptions));
- Assert.Equal(GetResourceString("EventSource_AbstractMustNotDeclareEventMethods", "WriteInteger", 1), e.Message);
+ AsserExceptionStringsEqual(() => GetResourceString("EventSource_AbstractMustNotDeclareEventMethods", "WriteInteger", 1), e);
e = AssertExtensions.Throws<ArgumentException>(null, () => EventSource.GenerateManifest(typeof(Sdt.AbstractWithEventsEventSource), string.Empty, strictOptions));
- Assert.Equal(GetResourceString("EventSource_AbstractMustNotDeclareEventMethods", "WriteInteger", 1), e.Message);
+ AsserExceptionStringsEqual(() => GetResourceString("EventSource_AbstractMustNotDeclareEventMethods", "WriteInteger", 1), e);
e = AssertExtensions.Throws<ArgumentException>(null, () => EventSource.GenerateManifest(typeof(Sdt.ImplementsInterfaceEventSource), string.Empty, strictOptions));
- Assert.Equal(GetResourceString("EventSource_EventMustNotBeExplicitImplementation", "SdtEventSources.ILogging.Error", 1), e.Message);
+ AsserExceptionStringsEqual(() => GetResourceString("EventSource_EventMustNotBeExplicitImplementation", "SdtEventSources.ILogging.Error", 1), e);
e = AssertExtensions.Throws<ArgumentException>(null, () => EventSource.GenerateManifest(typeof(Sdt.ImplementsInterfaceEventSource), string.Empty, strictOptions));
- Assert.Equal(GetResourceString("EventSource_EventMustNotBeExplicitImplementation", "SdtEventSources.ILogging.Error", 1), e.Message);
+ AsserExceptionStringsEqual(() => GetResourceString("EventSource_EventMustNotBeExplicitImplementation", "SdtEventSources.ILogging.Error", 1), e);
TestUtilities.CheckNoEventSourcesRunning("Stop");
}
diff --git a/src/System.Diagnostics.Tracing/tests/BasicEventSourceTest/TestsUserErrors.cs b/src/System.Diagnostics.Tracing/tests/BasicEventSourceTest/TestsUserErrors.cs
index ea226f7449..58dae42aaf 100644
--- a/src/System.Diagnostics.Tracing/tests/BasicEventSourceTest/TestsUserErrors.cs
+++ b/src/System.Diagnostics.Tracing/tests/BasicEventSourceTest/TestsUserErrors.cs
@@ -47,9 +47,14 @@ namespace BasicEventSourceTests
Assert.Equal(events.Count, 1);
Event _event = events[0];
Assert.Equal("EventSourceMessage", _event.EventName);
- string message = _event.PayloadString(0, "message");
- // expected message: "ERROR: Exception in Command Processing for EventSource BadEventSource_Bad_Type_ByteArray: Unsupported type Byte[] in event source. "
- Assert.True(Regex.IsMatch(message, "Unsupported type"));
+
+ // Check the exception text if not ProjectN.
+ if (!PlatformDetection.IsNetNative)
+ {
+ string message = _event.PayloadString(0, "message");
+ // expected message: "ERROR: Exception in Command Processing for EventSource BadEventSource_Bad_Type_ByteArray: Unsupported type Byte[] in event source. "
+ Assert.True(Regex.IsMatch(message, "Unsupported type"));
+ }
}
}
finally
@@ -62,6 +67,7 @@ namespace BasicEventSourceTests
/// Test the
/// </summary>
[Fact]
+ [SkipOnTargetFramework(TargetFrameworkMonikers.UapAot, "Depends on inspecting IL at runtime.")]
public void Test_BadEventSource_MismatchedIds()
{
#if USE_ETW // TODO: Enable when TraceEvent is available on CoreCLR. GitHub issue #4864.
diff --git a/src/System.Diagnostics.Tracing/tests/BasicEventSourceTest/TestsWrite.cs b/src/System.Diagnostics.Tracing/tests/BasicEventSourceTest/TestsWrite.cs
index e290a170b9..207cbd0ea2 100644
--- a/src/System.Diagnostics.Tracing/tests/BasicEventSourceTest/TestsWrite.cs
+++ b/src/System.Diagnostics.Tracing/tests/BasicEventSourceTest/TestsWrite.cs
@@ -40,7 +40,6 @@ namespace BasicEventSourceTests
/// </summary>
[Fact]
[ActiveIssue("dotnet/corefx #19455", TargetFrameworkMonikers.NetFramework)]
- [ActiveIssue(20744, TargetFrameworkMonikers.UapAot)]
public void Test_Write_T_EventListener()
{
using (var listener = new EventListenerListener())
@@ -55,7 +54,6 @@ namespace BasicEventSourceTests
/// </summary>
[Fact]
[ActiveIssue("dotnet/corefx #19455", TargetFrameworkMonikers.NetFramework)]
- [ActiveIssue(20744, TargetFrameworkMonikers.UapAot)]
public void Test_Write_T_EventListener_UseEvents()
{
Test_Write_T(new EventListenerListener(true));
@@ -412,7 +410,6 @@ namespace BasicEventSourceTests
/// </summary>
[Fact]
[ActiveIssue("dotnet/corefx #18806", TargetFrameworkMonikers.NetFramework)]
- [ActiveIssue(20744, TargetFrameworkMonikers.UapAot)]
public void Test_Write_T_In_Manifest_Serialization()
{
using (var eventListener = new EventListenerListener())
diff --git a/src/System.Diagnostics.Tracing/tests/BasicEventSourceTest/TestsWriteEventToListener.cs b/src/System.Diagnostics.Tracing/tests/BasicEventSourceTest/TestsWriteEventToListener.cs
index 9cb58dba1b..1cc1125c7d 100644
--- a/src/System.Diagnostics.Tracing/tests/BasicEventSourceTest/TestsWriteEventToListener.cs
+++ b/src/System.Diagnostics.Tracing/tests/BasicEventSourceTest/TestsWriteEventToListener.cs
@@ -22,7 +22,7 @@ namespace BasicEventSourceTests
TestUtilities.CheckNoEventSourcesRunning("Start");
using (var log = new EventSourceTest())
{
- using (var el = new LoudListener())
+ using (var el = new LoudListener(log))
{
var sources = EventSource.GetSources();
Assert.True(sources.Contains(log));
@@ -167,7 +167,7 @@ namespace BasicEventSourceTests
TestUtilities.CheckNoEventSourcesRunning("Start");
using (var log = new EventSourceTest())
{
- using (var el = new LoudListener())
+ using (var el = new LoudListener(log))
{
// coverage for EventSource.SendCommand()
var options = new Dictionary<string, string>() { { "arg", "val" } };
@@ -222,7 +222,7 @@ namespace BasicEventSourceTests
TestUtilities.CheckNoEventSourcesRunning("Start");
using (var log = new InvalidCallsToWriteEventEventSource())
{
- using (var el = new LoudListener())
+ using (var el = new LoudListener(log))
{
log.WriteTooManyArgs("Hello");
Assert.Equal(2, LoudListener.t_lastEvent.EventId);
@@ -243,10 +243,9 @@ namespace BasicEventSourceTests
{
TestUtilities.CheckNoEventSourcesRunning("Start");
- using (var el = new LoudListener())
using (var log = new SimpleEventSource())
+ using (var el = new LoudListener(log))
{
- el.EnableEvents(log, EventLevel.Verbose);
log.WriteIntToAdmin(10);
}
TestUtilities.CheckNoEventSourcesRunning("Stop");
@@ -320,7 +319,7 @@ namespace BasicEventSourceTests
using (var log = new EventSourceTest())
{
- using (var el = new LoudListener())
+ using (var el = new LoudListener(log))
{
// match any kwds == 0
el.EnableEvents(log, 0, 0);
diff --git a/src/System.Diagnostics.Tracing/tests/Resources/System.Diagnostics.Tracing.Tests.rd.xml b/src/System.Diagnostics.Tracing/tests/Resources/System.Diagnostics.Tracing.Tests.rd.xml
new file mode 100644
index 0000000000..81f0e2d936
--- /dev/null
+++ b/src/System.Diagnostics.Tracing/tests/Resources/System.Diagnostics.Tracing.Tests.rd.xml
@@ -0,0 +1,6 @@
+<Directives xmlns="http://schemas.microsoft.com/netfx/2013/01/metadata">
+ <Library>
+ <!-- TraceLogging tests need to be able to create this type using reflection. -->
+ <Type Name="BasicEventSourceTests.UserData" Dynamic="Required All" />
+ </Library>
+</Directives>
diff --git a/src/System.Diagnostics.Tracing/tests/System.Diagnostics.Tracing.Tests.csproj b/src/System.Diagnostics.Tracing/tests/System.Diagnostics.Tracing.Tests.csproj
index eaac0b4029..050cf0b16d 100644
--- a/src/System.Diagnostics.Tracing/tests/System.Diagnostics.Tracing.Tests.csproj
+++ b/src/System.Diagnostics.Tracing/tests/System.Diagnostics.Tracing.Tests.csproj
@@ -36,12 +36,12 @@
<Compile Include="CustomEventSources\SimpleEventSource.cs" />
<Compile Include="CustomEventSources\UseAbstractEventSource.cs" />
<Compile Include="CustomEventSources\UseInterfaceEventSource.cs" />
- <Compile Include="$(CommonTestPath)\System\AssertExtensions.cs">
- <Link>CommonTest\System\AssertExtensions.cs</Link>
- </Compile>
<Compile Include="$(CommonTestPath)\System\PlatformDetection.cs">
<Link>CommonTest\System\PlatformDetection.cs</Link>
</Compile>
</ItemGroup>
+ <ItemGroup>
+ <EmbeddedResource Include="Resources\$(AssemblyName).rd.xml" />
+ </ItemGroup>
<Import Project="$([MSBuild]::GetDirectoryNameOfFileAbove($(MSBuildThisFileDirectory), dir.targets))\dir.targets" />
-</Project> \ No newline at end of file
+</Project>
diff --git a/src/System.DirectoryServices.AccountManagement/tests/ComputerPrincipalTest.cs b/src/System.DirectoryServices.AccountManagement/tests/ComputerPrincipalTest.cs
index 379a177315..04ac152d6b 100644
--- a/src/System.DirectoryServices.AccountManagement/tests/ComputerPrincipalTest.cs
+++ b/src/System.DirectoryServices.AccountManagement/tests/ComputerPrincipalTest.cs
@@ -46,10 +46,11 @@ namespace System.DirectoryServices.AccountManagement.Tests
}
[ConditionalFact(nameof(PlatformDetection) + "." + nameof(PlatformDetection.IsNotWindowsNanoServer))]
- public void Ctor_MachineContext_ThrowsInvalidCastException()
+ public void Ctor_MachineContext_NoException()
{
var context = new PrincipalContext(ContextType.Machine);
- Assert.Throws<InvalidCastException>(() => new ComputerPrincipal(context, "samAccountName", "password", enabled: true));
+ var principal = new ComputerPrincipal(context, "samAccountName", "password", enabled: true);
+ Assert.Equal(ContextType.Machine, principal.ContextType);
}
[Fact]
diff --git a/src/System.DirectoryServices.AccountManagement/tests/PrincipalContextTests.cs b/src/System.DirectoryServices.AccountManagement/tests/PrincipalContextTests.cs
index c856f8762a..3dcf65ca9e 100644
--- a/src/System.DirectoryServices.AccountManagement/tests/PrincipalContextTests.cs
+++ b/src/System.DirectoryServices.AccountManagement/tests/PrincipalContextTests.cs
@@ -19,10 +19,12 @@ namespace System.DirectoryServices.AccountManagement.Tests
Assert.Null(context.Container);
Assert.Null(context.UserName);
Assert.Equal(ContextOptions.Negotiate, context.Options);
- Assert.Throws<InvalidCastException>(() => context.ConnectedServer);
+ Assert.NotNull(context.ConnectedServer);
+ Assert.Equal(Environment.MachineName, context.ConnectedServer);
}
[ConditionalTheory(nameof(PlatformDetection) + "." + nameof(PlatformDetection.IsNotWindowsNanoServer))]
+ [OuterLoop("Takes too long on domain joined machines")]
[InlineData(ContextType.Machine, null)]
[InlineData(ContextType.Machine, "")]
[InlineData(ContextType.Machine, "\0")]
@@ -42,11 +44,13 @@ namespace System.DirectoryServices.AccountManagement.Tests
}
else
{
- Assert.Throws<InvalidCastException>(() => context.ConnectedServer);
+ Assert.NotNull(context.ConnectedServer);
+ Assert.Equal(Environment.MachineName, context.ConnectedServer);
}
}
[ConditionalTheory(nameof(PlatformDetection) + "." + nameof(PlatformDetection.IsNotWindowsNanoServer))]
+ [OuterLoop("Takes too long on domain joined machines")]
[InlineData(ContextType.Machine, null, null)]
[InlineData(ContextType.Machine, "", null)]
[InlineData(ContextType.Machine, "\0", null)]
@@ -66,11 +70,13 @@ namespace System.DirectoryServices.AccountManagement.Tests
}
else
{
- Assert.Throws<InvalidCastException>(() => context.ConnectedServer);
+ Assert.NotNull(context.ConnectedServer);
+ Assert.Equal(Environment.MachineName, context.ConnectedServer);
}
}
[ConditionalTheory(nameof(PlatformDetection) + "." + nameof(PlatformDetection.IsNotWindowsNanoServer))]
+ [OuterLoop("Takes too long on domain joined machines")]
[InlineData(ContextType.Machine, null, null, ContextOptions.Negotiate)]
[InlineData(ContextType.Machine, "", null, ContextOptions.Negotiate)]
[InlineData(ContextType.Machine, "\0", null, ContextOptions.Negotiate)]
@@ -90,11 +96,13 @@ namespace System.DirectoryServices.AccountManagement.Tests
}
else
{
- Assert.Throws<InvalidCastException>(() => context.ConnectedServer);
+ Assert.NotNull(context.ConnectedServer);
+ Assert.Equal(Environment.MachineName, context.ConnectedServer);
}
}
[ConditionalTheory(nameof(PlatformDetection) + "." + nameof(PlatformDetection.IsNotWindowsNanoServer))]
+ [OuterLoop("Takes too long on domain joined machines")]
[InlineData(ContextType.Machine, null, "userName", "password")]
[InlineData(ContextType.Machine, "", "", "")]
[InlineData(ContextType.Machine, "\0", "userName", "")]
@@ -114,11 +122,12 @@ namespace System.DirectoryServices.AccountManagement.Tests
}
else
{
- Assert.Throws<InvalidCastException>(() => context.ConnectedServer);
+ Assert.Throws<Exception>(() => context.ConnectedServer);
}
}
[ConditionalTheory(nameof(PlatformDetection) + "." + nameof(PlatformDetection.IsNotWindowsNanoServer))]
+ [OuterLoop("Takes too long on domain joined machines")]
[InlineData(ContextType.Machine, null, null, "userName", "password")]
[InlineData(ContextType.Machine, "", null, "", "")]
[InlineData(ContextType.Machine, "\0", null, "userName", "")]
@@ -138,7 +147,7 @@ namespace System.DirectoryServices.AccountManagement.Tests
}
else
{
- Assert.Throws<InvalidCastException>(() => context.ConnectedServer);
+ Assert.Throws<Exception>(() => context.ConnectedServer);
}
}
@@ -284,6 +293,7 @@ namespace System.DirectoryServices.AccountManagement.Tests
}
[ConditionalFact(nameof(PlatformDetection) + "." + nameof(PlatformDetection.IsNotWindowsNanoServer))]
+ [OuterLoop("Takes too long on domain joined machines")]
public void ValidateCredentials_InvalidUserName_ThrowsException()
{
var context = new PrincipalContext(ContextType.Machine);
@@ -291,6 +301,7 @@ namespace System.DirectoryServices.AccountManagement.Tests
}
[ConditionalFact(nameof(PlatformDetection) + "." + nameof(PlatformDetection.IsNotWindowsNanoServer))]
+ [OuterLoop("Takes too long on domain joined machines")]
public void ValidateCredentials_IncorrectUserNamePassword_ThrowsException()
{
var context = new PrincipalContext(ContextType.Machine);
diff --git a/src/System.DirectoryServices.AccountManagement/tests/System.DirectoryServices.AccountManagement.Tests.csproj b/src/System.DirectoryServices.AccountManagement/tests/System.DirectoryServices.AccountManagement.Tests.csproj
index fd80707e39..f76dc01b65 100644
--- a/src/System.DirectoryServices.AccountManagement/tests/System.DirectoryServices.AccountManagement.Tests.csproj
+++ b/src/System.DirectoryServices.AccountManagement/tests/System.DirectoryServices.AccountManagement.Tests.csproj
@@ -14,9 +14,6 @@
<Compile Include="PrincipalTest.cs" />
<Compile Include="PrincipalContextTests.cs" />
<Compile Include="UserPrincipalTest.cs" />
- <Compile Include="$(CommonTestPath)\System\AssertExtensions.cs">
- <Link>Common\System\AssertExtensions.cs</Link>
- </Compile>
<Compile Include="$(CommonTestPath)\System\PlatformDetection.cs">
<Link>Common\System\PlatformDetection.cs</Link>
</Compile>
diff --git a/src/System.DirectoryServices.Protocols/src/System.DirectoryServices.Protocols.csproj b/src/System.DirectoryServices.Protocols/src/System.DirectoryServices.Protocols.csproj
index 3de36056ce..03773f23ed 100644
--- a/src/System.DirectoryServices.Protocols/src/System.DirectoryServices.Protocols.csproj
+++ b/src/System.DirectoryServices.Protocols/src/System.DirectoryServices.Protocols.csproj
@@ -19,7 +19,6 @@
<Compile Include="FxCopBaseline.AnyOS.cs" />
</ItemGroup>
<ItemGroup Condition="'$(TargetsWindows)' == 'true'">
- <Compile Include="System\DirectoryServices\Protocols\externdll.cs" />
<Compile Include="System\DirectoryServices\Protocols\common\AuthTypes.cs" />
<Compile Include="System\DirectoryServices\Protocols\common\BerConverter.cs" />
<Compile Include="System\DirectoryServices\Protocols\common\DereferenceAlias.cs" />
diff --git a/src/System.DirectoryServices.Protocols/src/System/DirectoryServices/Protocols/ExternDll.cs b/src/System.DirectoryServices.Protocols/src/System/DirectoryServices/Protocols/ExternDll.cs
deleted file mode 100644
index 6877ccedf6..0000000000
--- a/src/System.DirectoryServices.Protocols/src/System/DirectoryServices/Protocols/ExternDll.cs
+++ /dev/null
@@ -1,83 +0,0 @@
-// Licensed to the .NET Foundation under one or more agreements.
-// The .NET Foundation licenses this file to you under the MIT license.
-// See the LICENSE file in the project root for more information.
-
-namespace System
-{
- internal static class ExternDll
- {
-#if FEATURE_PAL && !SILVERLIGHT
-
-#if !PLATFORM_UNIX
- internal const String DLLPREFIX = "";
- internal const String DLLSUFFIX = ".dll";
-#else // !PLATFORM_UNIX
-#if __APPLE__
- internal const String DLLPREFIX = "lib";
- internal const String DLLSUFFIX = ".dylib";
-#elif _AIX
- internal const String DLLPREFIX = "lib";
- internal const String DLLSUFFIX = ".a";
-#elif __hppa__ || IA64
- internal const String DLLPREFIX = "lib";
- internal const String DLLSUFFIX = ".sl";
-#else
- internal const String DLLPREFIX = "lib";
- internal const String DLLSUFFIX = ".so";
-#endif
-#endif // !PLATFORM_UNIX
-
- public const string Kernel32 = DLLPREFIX + "rotor_pal" + DLLSUFFIX;
- public const string User32 = DLLPREFIX + "rotor_pal" + DLLSUFFIX;
- public const string Mscoree = DLLPREFIX + "sscoree" + DLLSUFFIX;
-
-#elif FEATURE_PAL && SILVERLIGHT
-
- public const string Kernel32 = "coreclr";
- public const string User32 = "coreclr";
-
-#else
- public const string Activeds = "activeds.dll";
- public const string Advapi32 = "advapi32.dll";
- public const string Comctl32 = "comctl32.dll";
- public const string Comdlg32 = "comdlg32.dll";
- public const string Gdi32 = "gdi32.dll";
- public const string Gdiplus = "gdiplus.dll";
- public const string Hhctrl = "hhctrl.ocx";
- public const string Imm32 = "imm32.dll";
- public const string Kernel32 = "kernel32.dll";
- public const string Loadperf = "Loadperf.dll";
- public const string Mscoree = "mscoree.dll";
- public const string Clr = "clr.dll";
- public const string Msi = "msi.dll";
- public const string Mqrt = "mqrt.dll";
- public const string Ntdll = "ntdll.dll";
- public const string Ole32 = "ole32.dll";
- public const string Oleacc = "oleacc.dll";
- public const string Oleaut32 = "oleaut32.dll";
- public const string Olepro32 = "olepro32.dll";
- public const string PerfCounter = "perfcounter.dll";
- public const string Powrprof = "Powrprof.dll";
- public const string Psapi = "psapi.dll";
- public const string Shell32 = "shell32.dll";
- public const string User32 = "user32.dll";
- public const string Uxtheme = "uxtheme.dll";
- public const string WinMM = "winmm.dll";
- public const string Winspool = "winspool.drv";
- public const string Wtsapi32 = "wtsapi32.dll";
- public const string Version = "version.dll";
- public const string Vsassert = "vsassert.dll";
- public const string Fxassert = "Fxassert.dll";
- public const string Shlwapi = "shlwapi.dll";
- public const string Crypt32 = "crypt32.dll";
-
- // system.data specific
- internal const string Odbc32 = "odbc32.dll";
- internal const string SNI = "System.Data.dll";
-
- // system.data.oracleclient specific
- internal const string OciDll = "oci.dll";
- internal const string OraMtsDll = "oramts.dll";
-#endif //!FEATURE_PAL
- }
-}
diff --git a/src/System.DirectoryServices.Protocols/src/System/DirectoryServices/Protocols/common/BerConverter.cs b/src/System.DirectoryServices.Protocols/src/System/DirectoryServices/Protocols/common/BerConverter.cs
index a562fea761..42a2ca8d01 100644
--- a/src/System.DirectoryServices.Protocols/src/System/DirectoryServices/Protocols/common/BerConverter.cs
+++ b/src/System.DirectoryServices.Protocols/src/System/DirectoryServices/Protocols/common/BerConverter.cs
@@ -214,7 +214,7 @@ namespace System.DirectoryServices.Protocols
// get the binary value back
berval binaryValue = new berval();
- IntPtr flattenptr = (IntPtr)0;
+ IntPtr flattenptr = IntPtr.Zero;
try
{
@@ -228,7 +228,7 @@ namespace System.DirectoryServices.Protocols
throw new BerConversionException();
}
- if (flattenptr != (IntPtr)0)
+ if (flattenptr != IntPtr.Zero)
{
Marshal.PtrToStructure(flattenptr, binaryValue);
}
@@ -246,7 +246,7 @@ namespace System.DirectoryServices.Protocols
}
finally
{
- if (flattenptr != (IntPtr)0)
+ if (flattenptr != IntPtr.Zero)
Wldap32.ber_bvfree(flattenptr);
}
@@ -281,7 +281,7 @@ namespace System.DirectoryServices.Protocols
if (value == null)
{
berValue.bv_len = 0;
- berValue.bv_val = (IntPtr)0;
+ berValue.bv_val = IntPtr.Zero;
}
else
{
@@ -296,7 +296,7 @@ namespace System.DirectoryServices.Protocols
}
finally
{
- if (berValue.bv_val != (IntPtr)0)
+ if (berValue.bv_val != IntPtr.Zero)
Marshal.FreeHGlobal(berValue.bv_val);
}
@@ -363,14 +363,14 @@ namespace System.DirectoryServices.Protocols
else if (fmt == 'B')
{
// return a bitstring and its length
- IntPtr ptrResult = (IntPtr)0;
+ IntPtr ptrResult = IntPtr.Zero;
int length = 0;
error = Wldap32.ber_scanf_bitstring(berElement, "B", ref ptrResult, ref length);
if (error == 0)
{
byte[] byteArray = null;
- if (ptrResult != (IntPtr)0)
+ if (ptrResult != IntPtr.Zero)
{
byteArray = new byte[length];
Marshal.Copy(ptrResult, byteArray, 0, length);
@@ -459,7 +459,7 @@ namespace System.DirectoryServices.Protocols
}
else
{
- error = Wldap32.ber_printf_bytearray(berElement, new string(fmt, 1), new HGlobalMemHandle((IntPtr)0), 0);
+ error = Wldap32.ber_printf_bytearray(berElement, new string(fmt, 1), new HGlobalMemHandle(IntPtr.Zero), 0);
}
return error;
@@ -468,7 +468,7 @@ namespace System.DirectoryServices.Protocols
private static byte[] DecodingByteArrayHelper(BerSafeHandle berElement, char fmt, ref int error)
{
error = 0;
- IntPtr result = (IntPtr)0;
+ IntPtr result = IntPtr.Zero;
berval binaryValue = new berval();
byte[] byteArray = null;
@@ -480,7 +480,7 @@ namespace System.DirectoryServices.Protocols
{
if (error == 0)
{
- if (result != (IntPtr)0)
+ if (result != IntPtr.Zero)
{
Marshal.PtrToStructure(result, binaryValue);
@@ -493,7 +493,7 @@ namespace System.DirectoryServices.Protocols
}
finally
{
- if (result != (IntPtr)0)
+ if (result != IntPtr.Zero)
Wldap32.ber_bvfree(result);
}
@@ -502,8 +502,8 @@ namespace System.DirectoryServices.Protocols
private static int EncodingMultiByteArrayHelper(BerSafeHandle berElement, byte[][] tempValue, char fmt)
{
- IntPtr berValArray = (IntPtr)0;
- IntPtr tempPtr = (IntPtr)0;
+ IntPtr berValArray = IntPtr.Zero;
+ IntPtr tempPtr = IntPtr.Zero;
SafeBerval[] managedBerVal = null;
int error = 0;
@@ -526,7 +526,7 @@ namespace System.DirectoryServices.Protocols
if (byteArray == null)
{
managedBerVal[i].bv_len = 0;
- managedBerVal[i].bv_val = (IntPtr)0;
+ managedBerVal[i].bv_val = IntPtr.Zero;
}
else
{
@@ -544,7 +544,7 @@ namespace System.DirectoryServices.Protocols
}
tempPtr = (IntPtr)((long)berValArray + IntPtr.Size * i);
- Marshal.WriteIntPtr(tempPtr, (IntPtr)0);
+ Marshal.WriteIntPtr(tempPtr, IntPtr.Zero);
}
error = Wldap32.ber_printf_berarray(berElement, new string(fmt, 1), berValArray);
@@ -553,12 +553,12 @@ namespace System.DirectoryServices.Protocols
}
finally
{
- if (berValArray != (IntPtr)0)
+ if (berValArray != IntPtr.Zero)
{
for (int i = 0; i < tempValue.Length; i++)
{
IntPtr ptr = Marshal.ReadIntPtr(berValArray, IntPtr.Size * i);
- if (ptr != (IntPtr)0)
+ if (ptr != IntPtr.Zero)
Marshal.FreeHGlobal(ptr);
}
Marshal.FreeHGlobal(berValArray);
@@ -572,10 +572,10 @@ namespace System.DirectoryServices.Protocols
{
error = 0;
// several berval
- IntPtr ptrResult = (IntPtr)0;
+ IntPtr ptrResult = IntPtr.Zero;
int i = 0;
ArrayList binaryList = new ArrayList();
- IntPtr tempPtr = (IntPtr)0;
+ IntPtr tempPtr = IntPtr.Zero;
byte[][] result = null;
try
@@ -584,10 +584,10 @@ namespace System.DirectoryServices.Protocols
if (error == 0)
{
- if (ptrResult != (IntPtr)0)
+ if (ptrResult != IntPtr.Zero)
{
tempPtr = Marshal.ReadIntPtr(ptrResult);
- while (tempPtr != (IntPtr)0)
+ while (tempPtr != IntPtr.Zero)
{
berval ber = new berval();
Marshal.PtrToStructure(tempPtr, ber);
@@ -613,7 +613,7 @@ namespace System.DirectoryServices.Protocols
}
finally
{
- if (ptrResult != (IntPtr)0)
+ if (ptrResult != IntPtr.Zero)
{
Wldap32.ber_bvecfree(ptrResult);
}
diff --git a/src/System.DirectoryServices.Protocols/src/System/DirectoryServices/Protocols/common/DirectoryControl.cs b/src/System.DirectoryServices.Protocols/src/System/DirectoryServices/Protocols/common/DirectoryControl.cs
index 4983beb318..679a970f21 100644
--- a/src/System.DirectoryServices.Protocols/src/System/DirectoryServices/Protocols/common/DirectoryControl.cs
+++ b/src/System.DirectoryServices.Protocols/src/System/DirectoryServices/Protocols/common/DirectoryControl.cs
@@ -708,15 +708,15 @@ namespace System.DirectoryServices.Protocols
public override byte[] GetValue()
{
- IntPtr control = (IntPtr)0;
+ IntPtr control = IntPtr.Zero;
int structSize = Marshal.SizeOf(typeof(SortKey));
int keyCount = _keys.Length;
IntPtr memHandle = Utility.AllocHGlobalIntPtrArray(keyCount + 1);
try
{
- IntPtr tempPtr = (IntPtr)0;
- IntPtr sortPtr = (IntPtr)0;
+ IntPtr tempPtr = IntPtr.Zero;
+ IntPtr sortPtr = IntPtr.Zero;
int i = 0;
for (i = 0; i < keyCount; i++)
{
@@ -726,7 +726,7 @@ namespace System.DirectoryServices.Protocols
Marshal.WriteIntPtr(tempPtr, sortPtr);
}
tempPtr = (IntPtr)((long)memHandle + IntPtr.Size * i);
- Marshal.WriteIntPtr(tempPtr, (IntPtr)0);
+ Marshal.WriteIntPtr(tempPtr, IntPtr.Zero);
bool critical = IsCritical;
int error = Wldap32.ldap_create_sort_control(UtilityHandle.GetHandle(), memHandle, critical ? (byte)1 : (byte)0, ref control);
@@ -757,28 +757,28 @@ namespace System.DirectoryServices.Protocols
}
finally
{
- if (control != (IntPtr)0)
+ if (control != IntPtr.Zero)
{
Wldap32.ldap_control_free(control);
}
- if (memHandle != (IntPtr)0)
+ if (memHandle != IntPtr.Zero)
{
//release the memory from the heap
for (int i = 0; i < keyCount; i++)
{
IntPtr tempPtr = Marshal.ReadIntPtr(memHandle, IntPtr.Size * i);
- if (tempPtr != (IntPtr)0)
+ if (tempPtr != IntPtr.Zero)
{
// free the marshalled name
IntPtr ptr = Marshal.ReadIntPtr(tempPtr);
- if (ptr != (IntPtr)0)
+ if (ptr != IntPtr.Zero)
{
Marshal.FreeHGlobal(ptr);
}
// free the marshalled rule
ptr = Marshal.ReadIntPtr(tempPtr, IntPtr.Size);
- if (ptr != (IntPtr)0)
+ if (ptr != IntPtr.Zero)
{
Marshal.FreeHGlobal(ptr);
}
diff --git a/src/System.DirectoryServices.Protocols/src/System/DirectoryServices/Protocols/ldap/LdapAsyncResult.cs b/src/System.DirectoryServices.Protocols/src/System/DirectoryServices/Protocols/ldap/LdapAsyncResult.cs
index 8a0e66be42..7e69cc1fec 100644
--- a/src/System.DirectoryServices.Protocols/src/System/DirectoryServices/Protocols/ldap/LdapAsyncResult.cs
+++ b/src/System.DirectoryServices.Protocols/src/System/DirectoryServices/Protocols/ldap/LdapAsyncResult.cs
@@ -2,97 +2,70 @@
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
+using System.Threading;
+using Microsoft.Win32.SafeHandles;
+
namespace System.DirectoryServices.Protocols
{
- using System;
- using System.Threading;
- using System.Net;
- using System.Text;
- using System.IO;
- using Microsoft.Win32.SafeHandles;
-
internal class LdapAsyncResult : IAsyncResult
{
private LdapAsyncWaitHandle _asyncWaitHandle = null;
- internal AsyncCallback callback = null;
- internal bool completed = false;
+ internal AsyncCallback _callback = null;
+ internal bool _completed = false;
private bool _completedSynchronously = false;
- internal ManualResetEvent manualResetEvent = null;
+ internal ManualResetEvent _manualResetEvent = null;
private object _stateObject = null;
- internal LdapRequestState resultObject = null;
- internal bool partialResults = false;
+ internal LdapRequestState _resultObject = null;
+ internal bool _partialResults = false;
public LdapAsyncResult(AsyncCallback callbackRoutine, object state, bool partialResults)
{
_stateObject = state;
- callback = callbackRoutine;
- manualResetEvent = new ManualResetEvent(false);
- this.partialResults = partialResults;
+ _callback = callbackRoutine;
+ _manualResetEvent = new ManualResetEvent(false);
+ _partialResults = partialResults;
}
- object IAsyncResult.AsyncState
- {
- get { return _stateObject; }
- }
+ object IAsyncResult.AsyncState => _stateObject;
WaitHandle IAsyncResult.AsyncWaitHandle
{
- get
- {
- if (null == _asyncWaitHandle)
- {
- _asyncWaitHandle = new LdapAsyncWaitHandle(manualResetEvent.SafeWaitHandle);
- }
-
- return (WaitHandle)_asyncWaitHandle;
- }
+ get => _asyncWaitHandle ?? (_asyncWaitHandle = new LdapAsyncWaitHandle(_manualResetEvent.SafeWaitHandle));
}
- bool IAsyncResult.CompletedSynchronously
- {
- get { return _completedSynchronously; }
- }
+ bool IAsyncResult.CompletedSynchronously => _completedSynchronously;
- bool IAsyncResult.IsCompleted
- {
- get { return completed; }
- }
+ bool IAsyncResult.IsCompleted => _completed;
- public override int GetHashCode()
- {
- return manualResetEvent.GetHashCode();
- }
+ public override int GetHashCode() => _manualResetEvent.GetHashCode();
- public override bool Equals(object o)
+ public override bool Equals(object obj)
{
- if ((!(o is LdapAsyncResult)) || (o == null))
+ if (!(obj is LdapAsyncResult otherAsyncResult))
{
return false;
}
- return (this == (LdapAsyncResult)o);
+ return this == otherAsyncResult;
}
- sealed internal class LdapAsyncWaitHandle : WaitHandle
+ private sealed class LdapAsyncWaitHandle : WaitHandle
{
public LdapAsyncWaitHandle(SafeWaitHandle handle) : base()
{
- this.SafeWaitHandle = handle;
+ SafeWaitHandle = handle;
}
- ~LdapAsyncWaitHandle()
- {
- this.SafeWaitHandle = null;
- }
+ ~LdapAsyncWaitHandle() => SafeWaitHandle = null;
}
}
internal class LdapRequestState
{
- internal DirectoryResponse response = null;
- internal LdapAsyncResult ldapAsync = null;
- internal Exception exception = null;
- internal bool abortCalled = false;
+ internal DirectoryResponse _response = null;
+ internal LdapAsyncResult _ldapAsync = null;
+ internal Exception _exception = null;
+ internal bool _abortCalled = false;
public LdapRequestState() { }
}
@@ -106,25 +79,24 @@ namespace System.DirectoryServices.Protocols
internal class LdapPartialAsyncResult : LdapAsyncResult
{
- internal LdapConnection con;
- internal int messageID = -1;
- internal bool partialCallback;
- internal ResultsStatus resultStatus = ResultsStatus.PartialResult;
- internal TimeSpan requestTimeout;
+ internal LdapConnection _con;
+ internal int _messageID = -1;
+ internal bool _partialCallback;
+ internal ResultsStatus _resultStatus = ResultsStatus.PartialResult;
+ internal TimeSpan _requestTimeout;
- internal SearchResponse response = null;
- internal Exception exception = null;
- internal DateTime startTime;
+ internal SearchResponse _response = null;
+ internal Exception _exception = null;
+ internal DateTime _startTime;
public LdapPartialAsyncResult(int messageID, AsyncCallback callbackRoutine, object state, bool partialResults, LdapConnection con, bool partialCallback, TimeSpan requestTimeout) : base(callbackRoutine, state, partialResults)
{
- this.messageID = messageID;
- this.con = con;
- this.partialResults = true;
- this.partialCallback = partialCallback;
- this.requestTimeout = requestTimeout;
- this.startTime = DateTime.Now;
+ _messageID = messageID;
+ _con = con;
+ _partialResults = true;
+ _partialCallback = partialCallback;
+ _requestTimeout = requestTimeout;
+ _startTime = DateTime.Now;
}
}
}
-
diff --git a/src/System.DirectoryServices.Protocols/src/System/DirectoryServices/Protocols/ldap/LdapConnection.cs b/src/System.DirectoryServices.Protocols/src/System/DirectoryServices/Protocols/ldap/LdapConnection.cs
index 16625b590a..a2e3743822 100644
--- a/src/System.DirectoryServices.Protocols/src/System/DirectoryServices/Protocols/ldap/LdapConnection.cs
+++ b/src/System.DirectoryServices.Protocols/src/System/DirectoryServices/Protocols/ldap/LdapConnection.cs
@@ -2,22 +2,20 @@
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
+using System.Globalization;
+using System.Net;
+using System.Collections;
+using System.ComponentModel;
+using System.Text;
+using System.Diagnostics;
+using System.Runtime.InteropServices;
+using System.Xml;
+using System.Threading;
+using System.Security.Cryptography.X509Certificates;
+using System.Security.Permissions;
+
namespace System.DirectoryServices.Protocols
{
- using System;
- using System.Globalization;
- using System.Net;
- using System.Collections;
- using System.ComponentModel;
- using System.Text;
- using System.Diagnostics;
- using System.Runtime.InteropServices;
- using System.Xml;
- using System.Threading;
- using System.Security.Cryptography.X509Certificates;
- using System.DirectoryServices;
- using System.Security.Permissions;
-
internal delegate DirectoryResponse GetLdapResponseCallback(int messageId, LdapOperation operation, ResultAll resultType, TimeSpan requestTimeout, bool exceptionOnTimeOut);
[UnmanagedFunctionPointer(CallingConvention.Cdecl)]
@@ -40,29 +38,28 @@ namespace System.DirectoryServices.Protocols
private const int LDAP_MOD_BVALUES = 0x80;
private AuthType _connectionAuthType = AuthType.Negotiate;
- private LdapSessionOptions _options = null;
- internal ConnectionHandle ldapHandle = null;
- internal bool disposed = false;
+ internal ConnectionHandle _ldapHandle = null;
+ internal bool _disposed = false;
private bool _bounded = false;
private bool _needRebind = false;
- internal static Hashtable handleTable = null;
- internal static object objectLock = null;
+ internal static Hashtable s_handleTable = null;
+ internal static object s_objectLock = null;
private GetLdapResponseCallback _fd = null;
private static Hashtable s_asyncResultTable = null;
private static LdapPartialResultsProcessor s_partialResultsProcessor = null;
private static ManualResetEvent s_waitHandle = null;
private static PartialResultsRetriever s_retriever = null;
private bool _setFQDNDone = false;
- internal bool automaticBind = true;
- internal bool needDispose = true;
+ internal bool _needDispose = true;
private bool _connected = false;
- internal QUERYCLIENTCERT clientCertificateRoutine = null;
+ internal QUERYCLIENTCERT _clientCertificateRoutine = null;
static LdapConnection()
{
- handleTable = new Hashtable();
- // initialize the lock
- objectLock = new Object();
+ s_handleTable = new Hashtable();
+
+ // Initialize the lock.
+ s_objectLock = new object();
Hashtable tempAsyncTable = new Hashtable();
s_asyncResultTable = Hashtable.Synchronized(tempAsyncTable);
@@ -95,49 +92,49 @@ namespace System.DirectoryServices.Protocols
_connectionAuthType = authType;
if (authType < AuthType.Anonymous || authType > AuthType.Kerberos)
- throw new InvalidEnumArgumentException("authType", (int)authType, typeof(AuthType));
+ {
+ throw new InvalidEnumArgumentException(nameof(authType), (int)authType, typeof(AuthType));
+ }
- // if user wants to do anonymous bind, but specifies credential, error out
- if (AuthType == AuthType.Anonymous && (_directoryCredential != null && ((_directoryCredential.Password != null && _directoryCredential.Password.Length != 0) || (_directoryCredential.UserName != null && _directoryCredential.UserName.Length != 0))))
- throw new ArgumentException(String.Format(CultureInfo.CurrentCulture, SR.InvalidAuthCredential));
+ // Throw if user wants to do anonymous bind but specifies credentials.
+ if (AuthType == AuthType.Anonymous && (_directoryCredential != null && (!string.IsNullOrEmpty(_directoryCredential.Password) || !string.IsNullOrEmpty(_directoryCredential.UserName))))
+ {
+ throw new ArgumentException(SR.InvalidAuthCredential);
+ }
Init();
- _options = new LdapSessionOptions(this);
- clientCertificateRoutine = new QUERYCLIENTCERT(ProcessClientCertificate);
+ SessionOptions = new LdapSessionOptions(this);
+ _clientCertificateRoutine = new QUERYCLIENTCERT(ProcessClientCertificate);
}
internal LdapConnection(LdapDirectoryIdentifier identifier, NetworkCredential credential, AuthType authType, IntPtr handle)
{
_directoryIdentifier = identifier;
- needDispose = false;
- ldapHandle = new ConnectionHandle(handle, needDispose);
+ _needDispose = false;
+ _ldapHandle = new ConnectionHandle(handle, _needDispose);
_directoryCredential = credential;
_connectionAuthType = authType;
- _options = new LdapSessionOptions(this);
- clientCertificateRoutine = new QUERYCLIENTCERT(ProcessClientCertificate);
+ SessionOptions = new LdapSessionOptions(this);
+ _clientCertificateRoutine = new QUERYCLIENTCERT(ProcessClientCertificate);
}
- ~LdapConnection()
- {
- Dispose(false);
- }
+ ~LdapConnection() => Dispose(false);
public override TimeSpan Timeout
{
- get
- {
- return _connectionTimeOut;
- }
+ get => _connectionTimeOut;
set
{
if (value < TimeSpan.Zero)
{
- throw new ArgumentException(String.Format(CultureInfo.CurrentCulture, SR.NoNegativeTime), "value");
+ throw new ArgumentException(SR.NoNegativeTime, nameof(value));
}
- // prevent integer overflow
- if (value.TotalSeconds > Int32.MaxValue)
- throw new ArgumentException(String.Format(CultureInfo.CurrentCulture, SR.TimespanExceedMax), "value");
+ // Prevent integer overflow.
+ if (value.TotalSeconds > int.MaxValue)
+ {
+ throw new ArgumentException(SR.TimespanExceedMax, nameof(value));
+ }
_connectionTimeOut = value;
}
@@ -145,16 +142,16 @@ namespace System.DirectoryServices.Protocols
public AuthType AuthType
{
- get
- {
- return _connectionAuthType;
- }
+ get => _connectionAuthType;
set
{
if (value < AuthType.Anonymous || value > AuthType.Kerberos)
- throw new InvalidEnumArgumentException("value", (int)value, typeof(AuthType));
+ {
+ throw new InvalidEnumArgumentException(nameof(value), (int)value, typeof(AuthType));
+ }
- // if the change is made after we have bound to the server and value is really changed, set the flag to indicate the need to do rebind
+ // If the change is made after we have bound to the server and value is really
+ // changed, set the flag to indicate the need to do rebind.
if (_bounded && (value != _connectionAuthType))
{
_needRebind = true;
@@ -164,128 +161,139 @@ namespace System.DirectoryServices.Protocols
}
}
- public LdapSessionOptions SessionOptions
- {
- get
- {
- return _options;
- }
- }
+ public LdapSessionOptions SessionOptions { get; }
public override NetworkCredential Credential
{
set
{
if (_bounded && !SameCredential(_directoryCredential, value))
+ {
_needRebind = true;
+ }
_directoryCredential = (value != null) ? new NetworkCredential(value.UserName, value.Password, value.Domain) : null;
}
}
-
- public bool AutoBind
- {
- get
- {
- return automaticBind;
- }
- set
- {
- automaticBind = value;
- }
- }
+
+ public bool AutoBind { get; set; } = true;
internal bool NeedDispose
{
- get
- {
- return needDispose;
- }
+ get => _needDispose;
set
{
- if (null != ldapHandle)
+ if (_ldapHandle != null)
{
- ldapHandle.needDispose = value;
+ _ldapHandle._needDispose = value;
}
- needDispose = value;
+
+ _needDispose = value;
}
}
internal void Init()
{
string hostname = null;
- string[] servers = (_directoryIdentifier == null ? null : ((LdapDirectoryIdentifier)_directoryIdentifier).Servers);
+ string[] servers = ((LdapDirectoryIdentifier)_directoryIdentifier)?.Servers;
if (servers != null && servers.Length != 0)
{
- StringBuilder temp = new StringBuilder(200);
+ var temp = new StringBuilder(200);
for (int i = 0; i < servers.Length; i++)
{
if (servers[i] != null)
{
temp.Append(servers[i]);
if (i < servers.Length - 1)
+ {
temp.Append(" ");
+ }
}
}
+
if (temp.Length != 0)
+ {
hostname = temp.ToString();
+ }
}
- // user wants to setup a connectionless session with server
+ // User wants to setup a connectionless session with server.
if (((LdapDirectoryIdentifier)_directoryIdentifier).Connectionless == true)
{
- ldapHandle = new ConnectionHandle(Wldap32.cldap_open(hostname, ((LdapDirectoryIdentifier)_directoryIdentifier).PortNumber), needDispose);
+ _ldapHandle = new ConnectionHandle(Wldap32.cldap_open(hostname, ((LdapDirectoryIdentifier)_directoryIdentifier).PortNumber), _needDispose);
}
else
{
- ldapHandle = new ConnectionHandle(Wldap32.ldap_init(hostname, ((LdapDirectoryIdentifier)_directoryIdentifier).PortNumber), needDispose);
+ _ldapHandle = new ConnectionHandle(Wldap32.ldap_init(hostname, ((LdapDirectoryIdentifier)_directoryIdentifier).PortNumber), _needDispose);
}
- // create a WeakReference object with the target of ldapHandle and put it into our handle table.
- lock (objectLock)
+ // Create a WeakReference object with the target of ldapHandle and put it into our handle table.
+ lock (s_objectLock)
{
- if (handleTable[ldapHandle.DangerousGetHandle()] != null)
- handleTable.Remove(ldapHandle.DangerousGetHandle());
+ if (s_handleTable[_ldapHandle.DangerousGetHandle()] != null)
+ {
+ s_handleTable.Remove(_ldapHandle.DangerousGetHandle());
+ }
- handleTable.Add(ldapHandle.DangerousGetHandle(), new WeakReference(this));
+ s_handleTable.Add(_ldapHandle.DangerousGetHandle(), new WeakReference(this));
}
}
public override DirectoryResponse SendRequest(DirectoryRequest request)
{
- // no request specific timeout is specified, use the connection timeout
+ // No request specific timeout is specified, use the connection timeout.
return SendRequest(request, _connectionTimeOut);
}
public DirectoryResponse SendRequest(DirectoryRequest request, TimeSpan requestTimeout)
{
- if (this.disposed)
+ if (_disposed)
+ {
throw new ObjectDisposedException(GetType().Name);
+ }
if (request == null)
- throw new ArgumentNullException("request");
+ {
+ throw new ArgumentNullException(nameof(request));
+ }
if (request is DsmlAuthRequest)
- throw new NotSupportedException(String.Format(CultureInfo.CurrentCulture, SR.DsmlAuthRequestNotSupported));
+ {
+ throw new NotSupportedException(SR.DsmlAuthRequestNotSupported);
+ }
int messageID = 0;
int error = SendRequestHelper(request, ref messageID);
LdapOperation operation = LdapOperation.LdapSearch;
if (request is DeleteRequest)
+ {
operation = LdapOperation.LdapDelete;
+ }
else if (request is AddRequest)
+ {
operation = LdapOperation.LdapAdd;
+ }
else if (request is ModifyRequest)
+ {
operation = LdapOperation.LdapModify;
+ }
else if (request is SearchRequest)
+ {
operation = LdapOperation.LdapSearch;
+ }
else if (request is ModifyDNRequest)
+ {
operation = LdapOperation.LdapModifyDn;
+ }
else if (request is CompareRequest)
+ {
operation = LdapOperation.LdapCompare;
+ }
else if (request is ExtendedRequest)
+ {
operation = LdapOperation.LdapExtendedRequest;
+ }
if (error == 0 && messageID != -1)
{
@@ -295,7 +303,7 @@ namespace System.DirectoryServices.Protocols
{
if (error == 0)
{
- // success code but message is -1, unexpected
+ // Success code but message is -1, unexpected.
error = Wldap32.LdapGetLastError();
}
@@ -310,126 +318,152 @@ namespace System.DirectoryServices.Protocols
public IAsyncResult BeginSendRequest(DirectoryRequest request, TimeSpan requestTimeout, PartialResultProcessing partialMode, AsyncCallback callback, object state)
{
- int messageID = 0;
- int error = 0;
-
- if (this.disposed)
+ if (_disposed)
+ {
throw new ObjectDisposedException(GetType().Name);
-
- // parameter validation
+ }
+
if (request == null)
- throw new ArgumentNullException("request");
+ {
+ throw new ArgumentNullException(nameof(request));
+ }
if (partialMode < PartialResultProcessing.NoPartialResultSupport || partialMode > PartialResultProcessing.ReturnPartialResultsAndNotifyCallback)
- throw new InvalidEnumArgumentException("partialMode", (int)partialMode, typeof(PartialResultProcessing));
+ {
+ throw new InvalidEnumArgumentException(nameof(partialMode), (int)partialMode, typeof(PartialResultProcessing));
+ }
if (partialMode != PartialResultProcessing.NoPartialResultSupport && !(request is SearchRequest))
- throw new NotSupportedException(String.Format(CultureInfo.CurrentCulture, SR.PartialResultsNotSupported));
+ {
+ throw new NotSupportedException(SR.PartialResultsNotSupported);
+ }
- if (partialMode == PartialResultProcessing.ReturnPartialResultsAndNotifyCallback && (callback == null))
- throw new ArgumentException(String.Format(CultureInfo.CurrentCulture, SR.CallBackIsNull), "callback");
+ if (partialMode == PartialResultProcessing.ReturnPartialResultsAndNotifyCallback && callback == null)
+ {
+ throw new ArgumentException(SR.CallBackIsNull, nameof(callback));
+ }
- error = SendRequestHelper(request, ref messageID);
+ int messageID = 0;
+ int error = SendRequestHelper(request, ref messageID);
LdapOperation operation = LdapOperation.LdapSearch;
if (request is DeleteRequest)
+ {
operation = LdapOperation.LdapDelete;
+ }
else if (request is AddRequest)
+ {
operation = LdapOperation.LdapAdd;
+ }
else if (request is ModifyRequest)
+ {
operation = LdapOperation.LdapModify;
+ }
else if (request is SearchRequest)
+ {
operation = LdapOperation.LdapSearch;
+ }
else if (request is ModifyDNRequest)
+ {
operation = LdapOperation.LdapModifyDn;
+ }
else if (request is CompareRequest)
+ {
operation = LdapOperation.LdapCompare;
+ }
else if (request is ExtendedRequest)
+ {
operation = LdapOperation.LdapExtendedRequest;
+ }
if (error == 0 && messageID != -1)
{
if (partialMode == PartialResultProcessing.NoPartialResultSupport)
{
- LdapRequestState rs = new LdapRequestState();
- LdapAsyncResult asyncResult = new LdapAsyncResult(callback, state, false);
+ var requestState = new LdapRequestState();
+ var asyncResult = new LdapAsyncResult(callback, state, false);
- rs.ldapAsync = asyncResult;
- asyncResult.resultObject = rs;
+ requestState._ldapAsync = asyncResult;
+ asyncResult._resultObject = requestState;
s_asyncResultTable.Add(asyncResult, messageID);
- _fd.BeginInvoke(messageID, operation, ResultAll.LDAP_MSG_ALL, requestTimeout, true, new AsyncCallback(ResponseCallback), rs);
+ _fd.BeginInvoke(messageID, operation, ResultAll.LDAP_MSG_ALL, requestTimeout, true, new AsyncCallback(ResponseCallback), requestState);
- return (IAsyncResult)asyncResult;
+ return asyncResult;
}
else
{
// the user registers to retrieve partial results
- bool partialCallback = false;
- if (partialMode == PartialResultProcessing.ReturnPartialResultsAndNotifyCallback)
- partialCallback = true;
- LdapPartialAsyncResult asyncResult = new LdapPartialAsyncResult(messageID, callback, state, true, this, partialCallback, requestTimeout);
+ bool partialCallback = partialMode == PartialResultProcessing.ReturnPartialResultsAndNotifyCallback;
+
+ var asyncResult = new LdapPartialAsyncResult(messageID, callback, state, true, this, partialCallback, requestTimeout);
s_partialResultsProcessor.Add(asyncResult);
- return (IAsyncResult)asyncResult;
+ return asyncResult;
}
}
- else
- {
- if (error == 0)
- {
- // success code but message is -1, unexpected
- error = Wldap32.LdapGetLastError();
- }
- throw ConstructException(error, operation);
+ if (error == 0)
+ {
+ // Success code but message is -1, unexpected.
+ error = Wldap32.LdapGetLastError();
}
+
+ throw ConstructException(error, operation);
}
private void ResponseCallback(IAsyncResult asyncResult)
{
- LdapRequestState rs = (LdapRequestState)asyncResult.AsyncState;
+ LdapRequestState requestState = (LdapRequestState)asyncResult.AsyncState;
try
{
DirectoryResponse response = _fd.EndInvoke(asyncResult);
- rs.response = response;
+ requestState._response = response;
}
catch (Exception e)
{
- rs.exception = e;
- rs.response = null;
+ requestState._exception = e;
+ requestState._response = null;
}
- // signal waitable object, indicate operation completed and fire callback
- rs.ldapAsync.manualResetEvent.Set();
- rs.ldapAsync.completed = true;
- if (rs.ldapAsync.callback != null && !rs.abortCalled)
+ // Signal waitable object, indicate operation completed and fire callback.
+ requestState._ldapAsync._manualResetEvent.Set();
+ requestState._ldapAsync._completed = true;
+
+ if (requestState._ldapAsync._callback != null && !requestState._abortCalled)
{
- rs.ldapAsync.callback((IAsyncResult)rs.ldapAsync);
+ requestState._ldapAsync._callback(requestState._ldapAsync);
}
}
public void Abort(IAsyncResult asyncResult)
{
- if (this.disposed)
+ if (_disposed)
+ {
throw new ObjectDisposedException(GetType().Name);
+ }
if (asyncResult == null)
- throw new ArgumentNullException("asyncResult");
+ {
+ throw new ArgumentNullException(nameof(asyncResult));
+ }
if (!(asyncResult is LdapAsyncResult))
- throw new ArgumentException(String.Format(CultureInfo.CurrentCulture, SR.NotReturnedAsyncResult, "asyncResult"));
+ {
+ throw new ArgumentException(SR.Format(SR.NotReturnedAsyncResult, nameof(asyncResult)));
+ }
int messageId = -1;
LdapAsyncResult result = (LdapAsyncResult)asyncResult;
-
- if (!result.partialResults)
+ if (!result._partialResults)
{
if (!s_asyncResultTable.Contains(asyncResult))
- throw new ArgumentException(String.Format(CultureInfo.CurrentCulture, SR.InvalidAsyncResult));
+ {
+ throw new ArgumentException(SR.InvalidAsyncResult);
+ }
messageId = (int)(s_asyncResultTable[asyncResult]);
@@ -439,103 +473,119 @@ namespace System.DirectoryServices.Protocols
else
{
s_partialResultsProcessor.Remove((LdapPartialAsyncResult)asyncResult);
- messageId = ((LdapPartialAsyncResult)asyncResult).messageID;
+ messageId = ((LdapPartialAsyncResult)asyncResult)._messageID;
}
- // cancel the request
- Wldap32.ldap_abandon(ldapHandle, messageId);
+ // Cancel the request.
+ Wldap32.ldap_abandon(_ldapHandle, messageId);
- LdapRequestState rs = result.resultObject;
- if (rs != null)
- rs.abortCalled = true;
+ LdapRequestState resultObject = result._resultObject;
+ if (resultObject != null)
+ {
+ resultObject._abortCalled = true;
+ }
}
public PartialResultsCollection GetPartialResults(IAsyncResult asyncResult)
{
- if (this.disposed)
+ if (_disposed)
+ {
throw new ObjectDisposedException(GetType().Name);
+ }
if (asyncResult == null)
- throw new ArgumentNullException("asyncResult");
+ {
+ throw new ArgumentNullException(nameof(asyncResult));
+ }
if (!(asyncResult is LdapAsyncResult))
- throw new ArgumentException(String.Format(CultureInfo.CurrentCulture, SR.NotReturnedAsyncResult, "asyncResult"));
+ {
+ throw new ArgumentException(SR.Format(SR.NotReturnedAsyncResult, nameof(asyncResult)));
+ }
if (!(asyncResult is LdapPartialAsyncResult))
- throw new InvalidOperationException(String.Format(CultureInfo.CurrentCulture, SR.NoPartialResults));
+ {
+ throw new InvalidOperationException(SR.NoPartialResults);
+ }
return s_partialResultsProcessor.GetPartialResults((LdapPartialAsyncResult)asyncResult);
}
public DirectoryResponse EndSendRequest(IAsyncResult asyncResult)
{
- if (this.disposed)
+ if (_disposed)
+ {
throw new ObjectDisposedException(GetType().Name);
+ }
if (asyncResult == null)
- throw new ArgumentNullException("asyncResult");
+ {
+ throw new ArgumentNullException(nameof(asyncResult));
+ }
if (!(asyncResult is LdapAsyncResult))
- throw new ArgumentException(String.Format(CultureInfo.CurrentCulture, SR.NotReturnedAsyncResult, "asyncResult"));
+ {
+ throw new ArgumentException(SR.Format(SR.NotReturnedAsyncResult, nameof(asyncResult)));
+ }
LdapAsyncResult result = (LdapAsyncResult)asyncResult;
- if (!result.partialResults)
+ if (!result._partialResults)
{
- // not a partial results
+ // Not a partial results.
if (!s_asyncResultTable.Contains(asyncResult))
- throw new ArgumentException(String.Format(CultureInfo.CurrentCulture, SR.InvalidAsyncResult));
+ {
+ throw new ArgumentException(SR.InvalidAsyncResult);
+ }
- // remove the asyncResult from our connection table
+ // Remove the asyncResult from our connection table.
s_asyncResultTable.Remove(asyncResult);
asyncResult.AsyncWaitHandle.WaitOne();
- if (result.resultObject.exception != null)
- throw result.resultObject.exception;
- else
- return result.resultObject.response;
- }
- else
- {
- // deal with partial results
- s_partialResultsProcessor.NeedCompleteResult((LdapPartialAsyncResult)asyncResult);
- asyncResult.AsyncWaitHandle.WaitOne();
+ if (result._resultObject._exception != null)
+ {
+ throw result._resultObject._exception;
+ }
- return s_partialResultsProcessor.GetCompleteResult((LdapPartialAsyncResult)asyncResult);
+ return result._resultObject._response;
}
+
+ // Deal with partial results.
+ s_partialResultsProcessor.NeedCompleteResult((LdapPartialAsyncResult)asyncResult);
+ asyncResult.AsyncWaitHandle.WaitOne();
+
+ return s_partialResultsProcessor.GetCompleteResult((LdapPartialAsyncResult)asyncResult);
}
private int SendRequestHelper(DirectoryRequest request, ref int messageID)
{
- IntPtr serverControlArray = (IntPtr)0;
+ IntPtr serverControlArray = IntPtr.Zero;
LdapControl[] managedServerControls = null;
- IntPtr clientControlArray = (IntPtr)0;
+ IntPtr clientControlArray = IntPtr.Zero;
LdapControl[] managedClientControls = null;
- string strValue = null;
-
- ArrayList ptrToFree = new ArrayList();
+ var ptrToFree = new ArrayList();
LdapMod[] modifications = null;
- IntPtr modArray = (IntPtr)0;
+ IntPtr modArray = IntPtr.Zero;
int addModCount = 0;
berval berValuePtr = null;
- IntPtr searchAttributes = (IntPtr)0;
- DereferenceAlias searchAliases;
+ IntPtr searchAttributes = IntPtr.Zero;
int attributeCount = 0;
int error = 0;
- // connect to the server first if have not done so
+ // Connect to the server first if have not done so.
if (!_connected)
{
Connect();
_connected = true;
}
- //do Bind if user has not turned off automatic bind, have not done so or there is a need to do rebind, also connectionless LDAP does not need to do bind
+ // Bind if user has not turned off automatic bind, have not done so or there is a need
+ // to do rebind, also connectionless LDAP does not need to do bind.
if (AutoBind && (!_bounded || _needRebind) && ((LdapDirectoryIdentifier)Directory).Connectionless != true)
{
Debug.WriteLine("rebind occurs\n");
@@ -544,10 +594,9 @@ namespace System.DirectoryServices.Protocols
try
{
- IntPtr controlPtr = (IntPtr)0;
- IntPtr tempPtr = (IntPtr)0;
+ IntPtr tempPtr = IntPtr.Zero;
- // build server control
+ // Build server control.
managedServerControls = BuildControlArray(request.Controls, true);
int structSize = Marshal.SizeOf(typeof(LdapControl));
@@ -556,13 +605,14 @@ namespace System.DirectoryServices.Protocols
serverControlArray = Utility.AllocHGlobalIntPtrArray(managedServerControls.Length + 1);
for (int i = 0; i < managedServerControls.Length; i++)
{
- controlPtr = Marshal.AllocHGlobal(structSize);
+ IntPtr controlPtr = Marshal.AllocHGlobal(structSize);
Marshal.StructureToPtr(managedServerControls[i], controlPtr, false);
tempPtr = (IntPtr)((long)serverControlArray + IntPtr.Size * i);
Marshal.WriteIntPtr(tempPtr, controlPtr);
}
+
tempPtr = (IntPtr)((long)serverControlArray + IntPtr.Size * managedServerControls.Length);
- Marshal.WriteIntPtr(tempPtr, (IntPtr)0);
+ Marshal.WriteIntPtr(tempPtr, IntPtr.Zero);
}
// build client control
@@ -572,73 +622,83 @@ namespace System.DirectoryServices.Protocols
clientControlArray = Utility.AllocHGlobalIntPtrArray(managedClientControls.Length + 1);
for (int i = 0; i < managedClientControls.Length; i++)
{
- controlPtr = Marshal.AllocHGlobal(structSize);
+ IntPtr controlPtr = Marshal.AllocHGlobal(structSize);
Marshal.StructureToPtr(managedClientControls[i], controlPtr, false);
tempPtr = (IntPtr)((long)clientControlArray + IntPtr.Size * i);
Marshal.WriteIntPtr(tempPtr, controlPtr);
}
+
tempPtr = (IntPtr)((long)clientControlArray + IntPtr.Size * managedClientControls.Length);
- Marshal.WriteIntPtr(tempPtr, (IntPtr)0);
+ Marshal.WriteIntPtr(tempPtr, IntPtr.Zero);
}
if (request is DeleteRequest)
{
- // it is an delete operation
- error = Wldap32.ldap_delete_ext(ldapHandle, ((DeleteRequest)request).DistinguishedName, serverControlArray, clientControlArray, ref messageID);
+ // It is an delete operation.
+ error = Wldap32.ldap_delete_ext(_ldapHandle, ((DeleteRequest)request).DistinguishedName, serverControlArray, clientControlArray, ref messageID);
}
else if (request is ModifyDNRequest)
{
- // it is a modify dn operation
- error = Wldap32.ldap_rename(ldapHandle,
+ // It is a modify dn operation
+ error = Wldap32.ldap_rename(_ldapHandle,
((ModifyDNRequest)request).DistinguishedName,
((ModifyDNRequest)request).NewName,
((ModifyDNRequest)request).NewParentDistinguishedName,
((ModifyDNRequest)request).DeleteOldRdn ? 1 : 0,
serverControlArray, clientControlArray, ref messageID);
}
- else if (request is CompareRequest)
+ else if (request is CompareRequest compareRequest)
{
- // it is a compare request
- DirectoryAttribute assertion = ((CompareRequest)request).Assertion;
+ // It is a compare request.
+ DirectoryAttribute assertion = compareRequest.Assertion;
if (assertion == null)
- throw new ArgumentException(String.Format(CultureInfo.CurrentCulture, SR.WrongAssertionCompare));
+ {
+ throw new ArgumentException(SR.WrongAssertionCompare);
+ }
if (assertion.Count != 1)
- throw new ArgumentException(String.Format(CultureInfo.CurrentCulture, SR.WrongNumValuesCompare));
+ {
+ throw new ArgumentException(SR.WrongNumValuesCompare);
+ }
- // process the attribute
- byte[] byteArray = assertion[0] as byte[];
- if (byteArray != null)
+ // Process the attribute.
+ string stringValue = null;
+ if (assertion[0] is byte[] byteArray)
{
if (byteArray != null && byteArray.Length != 0)
{
- berValuePtr = new berval();
- berValuePtr.bv_len = byteArray.Length;
- berValuePtr.bv_val = Marshal.AllocHGlobal(byteArray.Length);
+ berValuePtr = new berval
+ {
+ bv_len = byteArray.Length,
+ bv_val = Marshal.AllocHGlobal(byteArray.Length)
+ };
Marshal.Copy(byteArray, 0, berValuePtr.bv_val, byteArray.Length);
}
}
else
{
- strValue = assertion[0].ToString();
+ stringValue = assertion[0].ToString();
}
- // it is a compare request
- error = Wldap32.ldap_compare(ldapHandle,
+ // It is a compare request.
+ error = Wldap32.ldap_compare(_ldapHandle,
((CompareRequest)request).DistinguishedName,
assertion.Name,
- strValue,
+ stringValue,
berValuePtr,
serverControlArray, clientControlArray, ref messageID);
}
else if (request is AddRequest || request is ModifyRequest)
{
- // build the attributes
-
+ // Build the attributes.
if (request is AddRequest)
+ {
modifications = BuildAttributes(((AddRequest)request).Attributes, ptrToFree);
+ }
else
+ {
modifications = BuildAttributes(((ModifyRequest)request).Modifications, ptrToFree);
+ }
addModCount = (modifications == null ? 1 : modifications.Length + 1);
modArray = Utility.AllocHGlobalIntPtrArray(addModCount);
@@ -646,62 +706,66 @@ namespace System.DirectoryServices.Protocols
int i = 0;
for (i = 0; i < addModCount - 1; i++)
{
- controlPtr = Marshal.AllocHGlobal(modStructSize);
+ IntPtr controlPtr = Marshal.AllocHGlobal(modStructSize);
Marshal.StructureToPtr(modifications[i], controlPtr, false);
tempPtr = (IntPtr)((long)modArray + IntPtr.Size * i);
Marshal.WriteIntPtr(tempPtr, controlPtr);
}
tempPtr = (IntPtr)((long)modArray + IntPtr.Size * i);
- Marshal.WriteIntPtr(tempPtr, (IntPtr)0);
+ Marshal.WriteIntPtr(tempPtr, IntPtr.Zero);
if (request is AddRequest)
{
- error = Wldap32.ldap_add(ldapHandle,
+ error = Wldap32.ldap_add(_ldapHandle,
((AddRequest)request).DistinguishedName,
modArray,
serverControlArray, clientControlArray, ref messageID);
}
else
{
- error = Wldap32.ldap_modify(ldapHandle,
+ error = Wldap32.ldap_modify(_ldapHandle,
((ModifyRequest)request).DistinguishedName,
modArray,
serverControlArray, clientControlArray, ref messageID);
}
}
- else if (request is ExtendedRequest)
+ else if (request is ExtendedRequest extendedRequest)
{
- string name = ((ExtendedRequest)request).RequestName;
- byte[] val = ((ExtendedRequest)request).RequestValue;
+ string name = extendedRequest.RequestName;
+ byte[] val = extendedRequest.RequestValue;
// process the requestvalue
if (val != null && val.Length != 0)
{
- berValuePtr = new berval();
- berValuePtr.bv_len = val.Length;
- berValuePtr.bv_val = Marshal.AllocHGlobal(val.Length);
+ berValuePtr = new berval()
+ {
+ bv_len = val.Length,
+ bv_val = Marshal.AllocHGlobal(val.Length)
+ };
Marshal.Copy(val, 0, berValuePtr.bv_val, val.Length);
}
- error = Wldap32.ldap_extended_operation(ldapHandle,
+ error = Wldap32.ldap_extended_operation(_ldapHandle,
name,
berValuePtr,
serverControlArray, clientControlArray, ref messageID);
}
- else if (request is SearchRequest)
+ else if (request is SearchRequest searchRequest)
{
- // processing the filter
- SearchRequest searchRequest = (SearchRequest)request;
+ // Process the filter.
object filter = searchRequest.Filter;
if (filter != null)
{
- // LdapConnection only supports ldap filter
+ // LdapConnection only supports ldap filter.
if (filter is XmlDocument)
- throw new ArgumentException(String.Format(CultureInfo.CurrentCulture, SR.InvalidLdapSearchRequestFilter));
+ {
+ throw new ArgumentException(SR.InvalidLdapSearchRequestFilter);
+ }
}
+
string searchRequestFilter = (string)filter;
- // processing the attributes
+ // Process the attributes.
attributeCount = (searchRequest.Attributes == null ? 0 : searchRequest.Attributes.Count);
if (attributeCount != 0)
{
@@ -709,27 +773,28 @@ namespace System.DirectoryServices.Protocols
int i = 0;
for (i = 0; i < attributeCount; i++)
{
- controlPtr = Marshal.StringToHGlobalUni(searchRequest.Attributes[i]);
+ IntPtr controlPtr = Marshal.StringToHGlobalUni(searchRequest.Attributes[i]);
tempPtr = (IntPtr)((long)searchAttributes + IntPtr.Size * i);
Marshal.WriteIntPtr(tempPtr, controlPtr);
}
+
tempPtr = (IntPtr)((long)searchAttributes + IntPtr.Size * i);
- Marshal.WriteIntPtr(tempPtr, (IntPtr)0);
+ Marshal.WriteIntPtr(tempPtr, IntPtr.Zero);
}
- // processing the scope
+ // Process the scope.
int searchScope = (int)searchRequest.Scope;
- // processing the timelimit
+ // Process the timelimit.
int searchTimeLimit = (int)(searchRequest.TimeLimit.Ticks / TimeSpan.TicksPerSecond);
- // processing the alias
- searchAliases = _options.DerefAlias;
- _options.DerefAlias = searchRequest.Aliases;
+ // Process the alias.
+ DereferenceAlias searchAliases = SessionOptions.DerefAlias;
+ SessionOptions.DerefAlias = searchRequest.Aliases;
try
{
- error = Wldap32.ldap_search(ldapHandle,
+ error = Wldap32.ldap_search(_ldapHandle,
searchRequest.DistinguishedName,
searchScope,
searchRequestFilter,
@@ -743,19 +808,23 @@ namespace System.DirectoryServices.Protocols
}
finally
{
- // revert back
- _options.DerefAlias = searchAliases;
+ // Revert back.
+ SessionOptions.DerefAlias = searchAliases;
}
}
else
{
- throw new NotSupportedException(String.Format(CultureInfo.CurrentCulture, SR.InvliadRequestType));
+ throw new NotSupportedException(SR.InvliadRequestType);
}
- // the asynchronous call itself timeout, this actually means that we time out the LDAP_OPT_SEND_TIMEOUT specified in the session option
- // wldap32 does not differentiate that, but the application caller actually needs this information to determin what to do with the error code
+ // The asynchronous call itself timeout, this actually means that we time out the
+ // LDAP_OPT_SEND_TIMEOUT specified in the session option wldap32 does not differentiate
+ // that, but the application caller actually needs this information to determin what to
+ // do with the error code
if (error == (int)LdapError.TimeOut)
+ {
error = (int)LdapError.SendTimeOut;
+ }
return error;
}
@@ -763,14 +832,16 @@ namespace System.DirectoryServices.Protocols
{
GC.KeepAlive(modifications);
- if (serverControlArray != (IntPtr)0)
+ if (serverControlArray != IntPtr.Zero)
{
- //release the memory from the heap
+ // Release the memory from the heap.
for (int i = 0; i < managedServerControls.Length; i++)
{
IntPtr tempPtr = Marshal.ReadIntPtr(serverControlArray, IntPtr.Size * i);
- if (tempPtr != (IntPtr)0)
+ if (tempPtr != IntPtr.Zero)
+ {
Marshal.FreeHGlobal(tempPtr);
+ }
}
Marshal.FreeHGlobal(serverControlArray);
}
@@ -779,26 +850,33 @@ namespace System.DirectoryServices.Protocols
{
for (int i = 0; i < managedServerControls.Length; i++)
{
- if (managedServerControls[i].ldctl_oid != (IntPtr)0)
+ if (managedServerControls[i].ldctl_oid != IntPtr.Zero)
+ {
Marshal.FreeHGlobal(managedServerControls[i].ldctl_oid);
+ }
if (managedServerControls[i].ldctl_value != null)
{
- if (managedServerControls[i].ldctl_value.bv_val != (IntPtr)0)
+ if (managedServerControls[i].ldctl_value.bv_val != IntPtr.Zero)
+ {
Marshal.FreeHGlobal(managedServerControls[i].ldctl_value.bv_val);
+ }
}
}
}
- if (clientControlArray != (IntPtr)0)
+ if (clientControlArray != IntPtr.Zero)
{
- // release the memory from the heap
+ // Release the memory from the heap.
for (int i = 0; i < managedClientControls.Length; i++)
{
IntPtr tempPtr = Marshal.ReadIntPtr(clientControlArray, IntPtr.Size * i);
- if (tempPtr != (IntPtr)0)
+ if (tempPtr != IntPtr.Zero)
+ {
Marshal.FreeHGlobal(tempPtr);
+ }
}
+
Marshal.FreeHGlobal(clientControlArray);
}
@@ -806,50 +884,59 @@ namespace System.DirectoryServices.Protocols
{
for (int i = 0; i < managedClientControls.Length; i++)
{
- if (managedClientControls[i].ldctl_oid != (IntPtr)0)
+ if (managedClientControls[i].ldctl_oid != IntPtr.Zero)
+ {
Marshal.FreeHGlobal(managedClientControls[i].ldctl_oid);
+ }
if (managedClientControls[i].ldctl_value != null)
{
- if (managedClientControls[i].ldctl_value.bv_val != (IntPtr)0)
+ if (managedClientControls[i].ldctl_value.bv_val != IntPtr.Zero)
+ {
Marshal.FreeHGlobal(managedClientControls[i].ldctl_value.bv_val);
+ }
}
}
}
- if (modArray != (IntPtr)0)
+ if (modArray != IntPtr.Zero)
{
// release the memory from the heap
for (int i = 0; i < addModCount - 1; i++)
{
IntPtr tempPtr = Marshal.ReadIntPtr(modArray, IntPtr.Size * i);
- if (tempPtr != (IntPtr)0)
+ if (tempPtr != IntPtr.Zero)
+ {
Marshal.FreeHGlobal(tempPtr);
+ }
}
+
Marshal.FreeHGlobal(modArray);
}
- // free the pointers
+ // Free the pointers.
for (int x = 0; x < ptrToFree.Count; x++)
{
IntPtr tempPtr = (IntPtr)ptrToFree[x];
Marshal.FreeHGlobal(tempPtr);
}
- if (berValuePtr != null)
+ if (berValuePtr != null && berValuePtr.bv_val != IntPtr.Zero)
{
- if (berValuePtr.bv_val != (IntPtr)0)
- Marshal.FreeHGlobal(berValuePtr.bv_val);
+ Marshal.FreeHGlobal(berValuePtr.bv_val);
}
- if (searchAttributes != (IntPtr)0)
+ if (searchAttributes != IntPtr.Zero)
{
for (int i = 0; i < attributeCount; i++)
{
IntPtr tempPtr = Marshal.ReadIntPtr(searchAttributes, IntPtr.Size * i);
- if (tempPtr != (IntPtr)0)
+ if (tempPtr != IntPtr.Zero)
+ {
Marshal.FreeHGlobal(tempPtr);
+ }
}
+
Marshal.FreeHGlobal(searchAttributes);
}
}
@@ -857,39 +944,38 @@ namespace System.DirectoryServices.Protocols
private bool ProcessClientCertificate(IntPtr ldapHandle, IntPtr CAs, ref IntPtr certificate)
{
- ArrayList list = new ArrayList();
- byte[][] certAuthorities = null;
int count = ClientCertificates == null ? 0 : ClientCertificates.Count;
-
- if (count == 0 && _options.clientCertificateDelegate == null)
+ if (count == 0 && SessionOptions._clientCertificateDelegate == null)
{
return false;
}
- // if user specify certificate through property and not though option, we don't need to check CA
- if (_options.clientCertificateDelegate == null)
+ // If the user specify certificate through property and not though option, we don't need to check the certificate authority.
+ if (SessionOptions._clientCertificateDelegate == null)
{
certificate = ClientCertificates[0].Handle;
return true;
}
- // processing the CA
- if (CAs != (IntPtr)0)
+ // Processing the certificate authority.
+ var list = new ArrayList();
+ if (CAs != IntPtr.Zero)
{
SecPkgContext_IssuerListInfoEx trustedCAs = (SecPkgContext_IssuerListInfoEx)Marshal.PtrToStructure(CAs, typeof(SecPkgContext_IssuerListInfoEx));
int issuerNumber = trustedCAs.cIssuers;
- IntPtr tempPtr = (IntPtr)0;
for (int i = 0; i < issuerNumber; i++)
{
- tempPtr = (IntPtr)((long)trustedCAs.aIssuers + Marshal.SizeOf(typeof(CRYPTOAPI_BLOB)) * i);
+ IntPtr tempPtr = (IntPtr)((long)trustedCAs.aIssuers + Marshal.SizeOf(typeof(CRYPTOAPI_BLOB)) * i);
CRYPTOAPI_BLOB info = (CRYPTOAPI_BLOB)Marshal.PtrToStructure(tempPtr, typeof(CRYPTOAPI_BLOB));
int dataLength = info.cbData;
+
byte[] context = new byte[dataLength];
Marshal.Copy(info.pbData, context, 0, dataLength);
list.Add(context);
}
}
+ byte[][] certAuthorities = null;
if (list.Count != 0)
{
certAuthorities = new byte[list.Count][];
@@ -899,149 +985,152 @@ namespace System.DirectoryServices.Protocols
}
}
- X509Certificate cert = _options.clientCertificateDelegate(this, certAuthorities);
+ X509Certificate cert = SessionOptions._clientCertificateDelegate(this, certAuthorities);
if (cert != null)
{
certificate = cert.Handle;
return true;
}
- else
- {
- certificate = (IntPtr)0;
- return false;
- }
+
+ certificate = IntPtr.Zero;
+ return false;
}
private void Connect()
{
- int error = 0;
- string errorMessage;
-
- // currently ldap does not accept more than one certificate, so check here
+ //Ccurrently ldap does not accept more than one certificate.
if (ClientCertificates.Count > 1)
- throw new InvalidOperationException(String.Format(CultureInfo.CurrentCulture, SR.InvalidClientCertificates));
+ {
+ throw new InvalidOperationException(SR.InvalidClientCertificates);
+ }
- // set the certificate callback routine here if user adds the certifcate to the certificate collection
+ // Set the certificate callback routine here if user adds the certifcate to the certificate collection.
if (ClientCertificates.Count != 0)
{
- int certerror = Wldap32.ldap_set_option_clientcert(ldapHandle, LdapOption.LDAP_OPT_CLIENT_CERTIFICATE, clientCertificateRoutine);
- if (certerror != (int)ResultCode.Success)
+ int certError = Wldap32.ldap_set_option_clientcert(_ldapHandle, LdapOption.LDAP_OPT_CLIENT_CERTIFICATE, _clientCertificateRoutine);
+ if (certError != (int)ResultCode.Success)
{
- if (Utility.IsLdapError((LdapError)certerror))
+ if (Utility.IsLdapError((LdapError)certError))
{
- string certerrorMessage = LdapErrorMappings.MapResultCode(certerror);
- throw new LdapException(certerror, certerrorMessage);
+ string certerrorMessage = LdapErrorMappings.MapResultCode(certError);
+ throw new LdapException(certError, certerrorMessage);
}
- else
- throw new LdapException(certerror);
+
+ throw new LdapException(certError);
}
- // when certificate is specified, automatic bind is disabled
- automaticBind = false;
+
+ // When certificate is specified, automatic bind is disabled.
+ AutoBind = false;
}
- // set the LDAP_OPT_AREC_EXCLUSIVE flag if necessary
+ // Set the LDAP_OPT_AREC_EXCLUSIVE flag if necessary.
if (((LdapDirectoryIdentifier)Directory).FullyQualifiedDnsHostName && !_setFQDNDone)
{
SessionOptions.FQDN = true;
_setFQDNDone = true;
}
- // connect explicitly to the server
- LDAP_TIMEVAL timeout = new LDAP_TIMEVAL();
- timeout.tv_sec = (int)(_connectionTimeOut.Ticks / TimeSpan.TicksPerSecond);
- Debug.Assert(!ldapHandle.IsInvalid);
- error = Wldap32.ldap_connect(ldapHandle, timeout);
- // failed, throw exception
+ // Connect explicitly to the server.
+ var timeout = new LDAP_TIMEVAL()
+ {
+ tv_sec = (int)(_connectionTimeOut.Ticks / TimeSpan.TicksPerSecond)
+ };
+ Debug.Assert(!_ldapHandle.IsInvalid);
+ int error = Wldap32.ldap_connect(_ldapHandle, timeout);
+
+ // Filed, throw an exception.
if (error != (int)ResultCode.Success)
{
if (Utility.IsLdapError((LdapError)error))
{
- errorMessage = LdapErrorMappings.MapResultCode(error);
+ string errorMessage = LdapErrorMappings.MapResultCode(error);
throw new LdapException(error, errorMessage);
}
- else
- throw new LdapException(error);
+
+ throw new LdapException(error);
}
}
- public void Bind()
- {
- BindHelper(_directoryCredential, false /* no need to reset credential */);
- }
+ public void Bind() => BindHelper(_directoryCredential, needSetCredential: false);
- public void Bind(NetworkCredential newCredential)
- {
- BindHelper(newCredential, true /* need to reset credential */);
- }
+ public void Bind(NetworkCredential newCredential) => BindHelper(newCredential, needSetCredential: true);
- [
- EnvironmentPermission(SecurityAction.Assert, Unrestricted = true),
- SecurityPermission(SecurityAction.Assert, Flags = SecurityPermissionFlag.UnmanagedCode)
- ]
+ [EnvironmentPermission(SecurityAction.Assert, Unrestricted = true)]
+ [SecurityPermission(SecurityAction.Assert, Flags = SecurityPermissionFlag.UnmanagedCode)]
private void BindHelper(NetworkCredential newCredential, bool needSetCredential)
- {
- int error = 0;
- string errorMessage;
- string username;
- string domainname;
- string password;
- NetworkCredential tempCredential = null;
-
- // if already disposed, we need to throw exception
- if (this.disposed)
+ {
+ if (_disposed)
+ {
throw new ObjectDisposedException(GetType().Name);
+ }
- // if user wants to do anonymous bind, but specifies credential, error out
- if (AuthType == AuthType.Anonymous && (newCredential != null && ((newCredential.Password != null && newCredential.Password.Length != 0) || (newCredential.UserName != null && newCredential.UserName.Length != 0))))
- throw new InvalidOperationException(String.Format(CultureInfo.CurrentCulture, SR.InvalidAuthCredential));
+ // Throw if user wants to do anonymous bind but specifies credentials.
+ if (AuthType == AuthType.Anonymous && (newCredential != null && (!string.IsNullOrEmpty(newCredential.Password) || string.IsNullOrEmpty(newCredential.UserName))))
+ {
+ throw new InvalidOperationException(SR.InvalidAuthCredential);
+ }
- // set the credential
+ // Set the credential.
+ NetworkCredential tempCredential = null;
if (needSetCredential)
+ {
_directoryCredential = tempCredential = (newCredential != null ? new NetworkCredential(newCredential.UserName, newCredential.Password, newCredential.Domain) : null);
+ }
else
+ {
tempCredential = _directoryCredential;
+ }
- // connect to the server first
+ // Connect to the server first.
if (!_connected)
{
Connect();
_connected = true;
}
- // bind to the server
+ // Bind to the server.
+ string username;
+ string domainName;
+ string password;
if (tempCredential != null && tempCredential.UserName.Length == 0 && tempCredential.Password.Length == 0 && tempCredential.Domain.Length == 0)
{
- // default credential
+ // Default credentials.
username = null;
- domainname = null;
+ domainName = null;
password = null;
}
else
{
- username = (tempCredential == null) ? null : tempCredential.UserName;
- domainname = (tempCredential == null) ? null : tempCredential.Domain;
- password = (tempCredential == null) ? null : tempCredential.Password;
+ username = tempCredential?.UserName;
+ domainName = tempCredential?.Domain;
+ password = tempCredential?.Password;
}
+ int error;
if (AuthType == AuthType.Anonymous)
- error = Wldap32.ldap_simple_bind_s(ldapHandle, null, null);
+ {
+ error = Wldap32.ldap_simple_bind_s(_ldapHandle, null, null);
+ }
else if (AuthType == AuthType.Basic)
{
- StringBuilder tempdn = new StringBuilder(100);
- if (domainname != null && domainname.Length != 0)
+ var tempDomainName = new StringBuilder(100);
+ if (domainName != null && domainName.Length != 0)
{
- tempdn.Append(domainname);
- tempdn.Append("\\");
+ tempDomainName.Append(domainName);
+ tempDomainName.Append("\\");
}
- tempdn.Append(username);
- error = Wldap32.ldap_simple_bind_s(ldapHandle, tempdn.ToString(), password);
+
+ tempDomainName.Append(username);
+ error = Wldap32.ldap_simple_bind_s(_ldapHandle, tempDomainName.ToString(), password);
}
else
{
- SEC_WINNT_AUTH_IDENTITY_EX cred = new SEC_WINNT_AUTH_IDENTITY_EX();
- cred.version = Wldap32.SEC_WINNT_AUTH_IDENTITY_VERSION;
- cred.length = Marshal.SizeOf(typeof(SEC_WINNT_AUTH_IDENTITY_EX));
- cred.flags = Wldap32.SEC_WINNT_AUTH_IDENTITY_UNICODE;
+ var cred = new SEC_WINNT_AUTH_IDENTITY_EX()
+ {
+ version = Wldap32.SEC_WINNT_AUTH_IDENTITY_VERSION,
+ length = Marshal.SizeOf(typeof(SEC_WINNT_AUTH_IDENTITY_EX)),
+ flags = Wldap32.SEC_WINNT_AUTH_IDENTITY_UNICODE
+ };
if (AuthType == AuthType.Kerberos)
{
cred.packageList = Wldap32.MICROSOFT_KERBEROS_NAME_W;
@@ -1052,8 +1141,8 @@ namespace System.DirectoryServices.Protocols
{
cred.user = username;
cred.userLength = (username == null ? 0 : username.Length);
- cred.domain = domainname;
- cred.domainLength = (domainname == null ? 0 : domainname.Length);
+ cred.domain = domainName;
+ cred.domainLength = (domainName == null ? 0 : domainName.Length);
cred.password = password;
cred.passwordLength = (password == null ? 0 : password.Length);
}
@@ -1087,44 +1176,43 @@ namespace System.DirectoryServices.Protocols
break;
}
- if ((tempCredential == null) && (AuthType == AuthType.External))
+ if (tempCredential == null && AuthType == AuthType.External)
{
- error = Wldap32.ldap_bind_s(ldapHandle, null, null, method);
+ error = Wldap32.ldap_bind_s(_ldapHandle, null, null, method);
}
else
{
- error = Wldap32.ldap_bind_s(ldapHandle, null, cred, method);
+ error = Wldap32.ldap_bind_s(_ldapHandle, null, cred, method);
}
}
- // failed, throw exception
+ // Failed, throw exception.
if (error != (int)ResultCode.Success)
{
if (Utility.IsResultCode((ResultCode)error))
{
- errorMessage = OperationErrorMappings.MapResultCode(error);
+ string errorMessage = OperationErrorMappings.MapResultCode(error);
throw new DirectoryOperationException(null, errorMessage);
}
else if (Utility.IsLdapError((LdapError)error))
{
- errorMessage = LdapErrorMappings.MapResultCode(error);
- string serverErrorMessage = _options.ServerErrorMessage;
- if ((serverErrorMessage != null) && (serverErrorMessage.Length > 0))
+ string errorMessage = LdapErrorMappings.MapResultCode(error);
+ string serverErrorMessage = SessionOptions.ServerErrorMessage;
+ if (!string.IsNullOrEmpty(serverErrorMessage))
{
throw new LdapException(error, errorMessage, serverErrorMessage);
}
- else
- {
- throw new LdapException(error, errorMessage);
- }
+
+ throw new LdapException(error, errorMessage);
}
- else
- throw new LdapException(error);
+
+ throw new LdapException(error);
}
- // we successfully bind to the server
+ // We successfully bound to the server.
_bounded = true;
- // rebind has been done
+
+ // Rebind has been done.
_needRebind = false;
}
@@ -1138,78 +1226,83 @@ namespace System.DirectoryServices.Protocols
{
if (disposing)
{
- // free other state (managed objects)
-
- // we need to remove the handle from the handle table
- lock (objectLock)
+ // We need to remove the handle from the handle table.
+ lock (s_objectLock)
{
- if (null != ldapHandle)
+ if (_ldapHandle != null)
{
- handleTable.Remove(ldapHandle.DangerousGetHandle());
+ s_handleTable.Remove(_ldapHandle.DangerousGetHandle());
}
}
}
- // free your own state (unmanaged objects)
-
- // close the ldap connection
- if (needDispose && ldapHandle != null && !ldapHandle.IsInvalid)
- ldapHandle.Dispose();
- ldapHandle = null;
- disposed = true;
+ // Close the ldap connection.
+ if (_needDispose && _ldapHandle != null && !_ldapHandle.IsInvalid)
+ {
+ _ldapHandle.Dispose();
+ }
- Debug.WriteLine("Connection object is disposed\n");
+ _ldapHandle = null;
+ _disposed = true;
}
internal LdapControl[] BuildControlArray(DirectoryControlCollection controls, bool serverControl)
{
- int count = 0;
LdapControl[] managedControls = null;
if (controls != null && controls.Count != 0)
{
- ArrayList controlList = new ArrayList();
+ var controlList = new ArrayList();
foreach (DirectoryControl col in controls)
{
if (serverControl == true)
{
if (col.ServerSide)
+ {
controlList.Add(col);
+ }
}
- else
+ else if (!col.ServerSide)
{
- if (!col.ServerSide)
- controlList.Add(col);
+ controlList.Add(col);
}
}
+
if (controlList.Count != 0)
{
- count = controlList.Count;
-
+ int count = controlList.Count;
managedControls = new LdapControl[count];
for (int i = 0; i < count; i++)
{
- managedControls[i] = new LdapControl();
- // get the control type
- managedControls[i].ldctl_oid = Marshal.StringToHGlobalUni(((DirectoryControl)controlList[i]).Type);
- //get the control cricality
- managedControls[i].ldctl_iscritical = ((DirectoryControl)controlList[i]).IsCritical;
- // get the control value
+ managedControls[i] = new LdapControl()
+ {
+ // Get the control type.
+ ldctl_oid = Marshal.StringToHGlobalUni(((DirectoryControl)controlList[i]).Type),
+
+ // Get the control cricality.
+ ldctl_iscritical = ((DirectoryControl)controlList[i]).IsCritical
+ };
+
+ // Get the control value.
DirectoryControl tempControl = (DirectoryControl)controlList[i];
byte[] byteControlValue = tempControl.GetValue();
if (byteControlValue == null || byteControlValue.Length == 0)
{
- // treat the control value as null
- managedControls[i].ldctl_value = new berval();
- managedControls[i].ldctl_value.bv_len = 0;
- managedControls[i].ldctl_value.bv_val = (IntPtr)0;
+ // Treat the control value as null.
+ managedControls[i].ldctl_value = new berval
+ {
+ bv_len = 0,
+ bv_val = IntPtr.Zero
+ };
}
else
{
- managedControls[i].ldctl_value = new berval();
- managedControls[i].ldctl_value.bv_len = byteControlValue.Length;
- managedControls[i].ldctl_value.bv_val = Marshal.AllocHGlobal(Marshal.SizeOf(typeof(byte)) * managedControls[i].ldctl_value.bv_len);
+ managedControls[i].ldctl_value = new berval
+ {
+ bv_len = byteControlValue.Length,
+ bv_val = Marshal.AllocHGlobal(Marshal.SizeOf(typeof(byte)) * byteControlValue.Length)
+ };
Marshal.Copy(byteControlValue, 0, managedControls[i].ldctl_value.bv_val, managedControls[i].ldctl_value.bv_len);
}
}
@@ -1222,13 +1315,13 @@ namespace System.DirectoryServices.Protocols
internal LdapMod[] BuildAttributes(CollectionBase directoryAttributes, ArrayList ptrToFree)
{
LdapMod[] attributes = null;
- UTF8Encoding encoder = new UTF8Encoding();
- DirectoryAttributeCollection attributeCollection = null;
- DirectoryAttributeModificationCollection modificationCollection = null;
- DirectoryAttribute modAttribute = null;
if (directoryAttributes != null && directoryAttributes.Count != 0)
{
+ var encoder = new UTF8Encoding();
+ DirectoryAttributeModificationCollection modificationCollection = null;
+ DirectoryAttributeCollection attributeCollection = null;
+
if (directoryAttributes is DirectoryAttributeModificationCollection)
{
modificationCollection = (DirectoryAttributeModificationCollection)directoryAttributes;
@@ -1241,15 +1334,20 @@ namespace System.DirectoryServices.Protocols
attributes = new LdapMod[directoryAttributes.Count];
for (int i = 0; i < directoryAttributes.Count; i++)
{
- // get the managed attribute first
+ // Get the managed attribute first.
+ DirectoryAttribute modAttribute = null;
if (attributeCollection != null)
+ {
modAttribute = attributeCollection[i];
+ }
else
+ {
modAttribute = modificationCollection[i];
+ }
attributes[i] = new LdapMod();
- // operation type
+ // Write the operation type.
if (modAttribute is DirectoryAttributeModification)
{
attributes[i].type = (int)((DirectoryAttributeModification)modAttribute).Operation;
@@ -1258,13 +1356,14 @@ namespace System.DirectoryServices.Protocols
{
attributes[i].type = (int)DirectoryAttributeOperation.Add;
}
- // we treat all the values as binary
- attributes[i].type |= (int)LDAP_MOD_BVALUES;
- //attribute name
+ // We treat all the values as binary
+ attributes[i].type |= LDAP_MOD_BVALUES;
+
+ // Write the attribute name.
attributes[i].attribute = Marshal.StringToHGlobalUni(modAttribute.Name);
- // values
+ // Write the values.
int valuesCount = 0;
berval[] berValues = null;
if (modAttribute.Count > 0)
@@ -1275,15 +1374,24 @@ namespace System.DirectoryServices.Protocols
{
byte[] byteArray = null;
if (modAttribute[j] is string)
+ {
byteArray = encoder.GetBytes((string)modAttribute[j]);
+ }
else if (modAttribute[j] is Uri)
+ {
byteArray = encoder.GetBytes(((Uri)modAttribute[j]).ToString());
+ }
else
+ {
byteArray = (byte[])modAttribute[j];
+ }
+
+ berValues[j] = new berval()
+ {
+ bv_len = byteArray.Length,
+ bv_val = Marshal.AllocHGlobal(byteArray.Length)
+ };
- berValues[j] = new berval();
- berValues[j].bv_len = byteArray.Length;
- berValues[j].bv_val = Marshal.AllocHGlobal(berValues[j].bv_len);
// need to free the memory allocated on the heap when we are done
ptrToFree.Add(berValues[j].bv_val);
Marshal.Copy(byteArray, 0, berValues[j].bv_val, berValues[j].bv_len);
@@ -1292,20 +1400,22 @@ namespace System.DirectoryServices.Protocols
attributes[i].values = Utility.AllocHGlobalIntPtrArray(valuesCount + 1);
int structSize = Marshal.SizeOf(typeof(berval));
- IntPtr controlPtr = (IntPtr)0;
- IntPtr tempPtr = (IntPtr)0;
+ IntPtr controlPtr = IntPtr.Zero;
+ IntPtr tempPtr = IntPtr.Zero;
+
int m = 0;
for (m = 0; m < valuesCount; m++)
{
controlPtr = Marshal.AllocHGlobal(structSize);
- // need to free the memory allocated on the heap when we are done
+
+ // Need to free the memory allocated on the heap when we are done.
ptrToFree.Add(controlPtr);
Marshal.StructureToPtr(berValues[m], controlPtr, false);
tempPtr = (IntPtr)((long)attributes[i].values + IntPtr.Size * m);
Marshal.WriteIntPtr(tempPtr, controlPtr);
}
tempPtr = (IntPtr)((long)attributes[i].values + IntPtr.Size * m);
- Marshal.WriteIntPtr(tempPtr, (IntPtr)0);
+ Marshal.WriteIntPtr(tempPtr, IntPtr.Zero);
}
}
@@ -1314,16 +1424,17 @@ namespace System.DirectoryServices.Protocols
internal DirectoryResponse ConstructResponse(int messageId, LdapOperation operation, ResultAll resultType, TimeSpan requestTimeOut, bool exceptionOnTimeOut)
{
- int error;
- LDAP_TIMEVAL timeout = new LDAP_TIMEVAL();
- timeout.tv_sec = (int)(requestTimeOut.Ticks / TimeSpan.TicksPerSecond);
- IntPtr ldapResult = (IntPtr)0;
+ var timeout = new LDAP_TIMEVAL()
+ {
+ tv_sec = (int)(requestTimeOut.Ticks / TimeSpan.TicksPerSecond)
+ };
+ IntPtr ldapResult = IntPtr.Zero;
DirectoryResponse response = null;
- IntPtr requestName = (IntPtr)0;
- IntPtr requestValue = (IntPtr)0;
+ IntPtr requestName = IntPtr.Zero;
+ IntPtr requestValue = IntPtr.Zero;
- IntPtr entryMessage = (IntPtr)0;
+ IntPtr entryMessage = IntPtr.Zero;
bool needAbandon = true;
@@ -1335,20 +1446,22 @@ namespace System.DirectoryServices.Protocols
timeout.tv_usec = 0;
if (resultType == ResultAll.LDAP_MSG_POLLINGALL)
+ {
resultType = ResultAll.LDAP_MSG_ALL;
+ }
// when doing partial results retrieving, if ldap_result failed, we don't do ldap_abandon here.
needAbandon = false;
}
- error = Wldap32.ldap_result(ldapHandle, messageId, (int)resultType, timeout, ref ldapResult);
+ int error = Wldap32.ldap_result(_ldapHandle, messageId, (int)resultType, timeout, ref ldapResult);
if (error != -1 && error != 0)
{
// parsing the result
int serverError = 0;
try
{
- int resulterror = 0;
+ int resultError = 0;
string responseDn = null;
string responseMessage = null;
Uri[] responseReferral = null;
@@ -1356,43 +1469,55 @@ namespace System.DirectoryServices.Protocols
// ldap_parse_result skips over messages of type LDAP_RES_SEARCH_ENTRY and LDAP_RES_SEARCH_REFERRAL
if (error != (int)LdapResult.LDAP_RES_SEARCH_ENTRY && error != (int)LdapResult.LDAP_RES_REFERRAL)
- resulterror = ConstructParsedResult(ldapResult, ref serverError, ref responseDn, ref responseMessage, ref responseReferral, ref responseControl);
+ {
+ resultError = ConstructParsedResult(ldapResult, ref serverError, ref responseDn, ref responseMessage, ref responseReferral, ref responseControl);
+ }
- if (resulterror == 0)
+ if (resultError == 0)
{
- resulterror = serverError;
+ resultError = serverError;
if (error == (int)LdapResult.LDAP_RES_ADD)
- response = new AddResponse(responseDn, responseControl, (ResultCode)resulterror, responseMessage, responseReferral);
+ {
+ response = new AddResponse(responseDn, responseControl, (ResultCode)resultError, responseMessage, responseReferral);
+ }
else if (error == (int)LdapResult.LDAP_RES_MODIFY)
- response = new ModifyResponse(responseDn, responseControl, (ResultCode)resulterror, responseMessage, responseReferral);
+ {
+ response = new ModifyResponse(responseDn, responseControl, (ResultCode)resultError, responseMessage, responseReferral);
+ }
else if (error == (int)LdapResult.LDAP_RES_DELETE)
- response = new DeleteResponse(responseDn, responseControl, (ResultCode)resulterror, responseMessage, responseReferral);
+ {
+ response = new DeleteResponse(responseDn, responseControl, (ResultCode)resultError, responseMessage, responseReferral);
+ }
else if (error == (int)LdapResult.LDAP_RES_MODRDN)
- response = new ModifyDNResponse(responseDn, responseControl, (ResultCode)resulterror, responseMessage, responseReferral);
+ {
+ response = new ModifyDNResponse(responseDn, responseControl, (ResultCode)resultError, responseMessage, responseReferral);
+ }
else if (error == (int)LdapResult.LDAP_RES_COMPARE)
- response = new CompareResponse(responseDn, responseControl, (ResultCode)resulterror, responseMessage, responseReferral);
+ {
+ response = new CompareResponse(responseDn, responseControl, (ResultCode)resultError, responseMessage, responseReferral);
+ }
else if (error == (int)LdapResult.LDAP_RES_EXTENDED)
{
- response = new ExtendedResponse(responseDn, responseControl, (ResultCode)resulterror, responseMessage, responseReferral);
- if (resulterror == (int)ResultCode.Success)
+ response = new ExtendedResponse(responseDn, responseControl, (ResultCode)resultError, responseMessage, responseReferral);
+ if (resultError == (int)ResultCode.Success)
{
- resulterror = Wldap32.ldap_parse_extended_result(ldapHandle, ldapResult, ref requestName, ref requestValue, 0 /*not free it*/);
- if (resulterror == 0)
+ resultError = Wldap32.ldap_parse_extended_result(_ldapHandle, ldapResult, ref requestName, ref requestValue, 0 /*not free it*/);
+ if (resultError == 0)
{
string name = null;
- if (requestName != (IntPtr)0)
+ if (requestName != IntPtr.Zero)
{
name = Marshal.PtrToStringUni(requestName);
}
berval val = null;
byte[] requestValueArray = null;
- if (requestValue != (IntPtr)0)
+ if (requestValue != IntPtr.Zero)
{
val = new berval();
Marshal.PtrToStructure(requestValue, val);
- if (val.bv_len != 0 && val.bv_val != (IntPtr)0)
+ if (val.bv_len != 0 && val.bv_val != IntPtr.Zero)
{
requestValueArray = new byte[val.bv_len];
Marshal.Copy(val.bv_val, requestValueArray, 0, val.bv_len);
@@ -1408,7 +1533,7 @@ namespace System.DirectoryServices.Protocols
error == (int)LdapResult.LDAP_RES_SEARCH_ENTRY ||
error == (int)LdapResult.LDAP_RES_REFERRAL)
{
- response = new SearchResponse(responseDn, responseControl, (ResultCode)resulterror, responseMessage, responseReferral);
+ response = new SearchResponse(responseDn, responseControl, (ResultCode)resultError, responseMessage, responseReferral);
//set the flag here so our partial result processor knows whether the search is done or not
if (error == (int)LdapResult.LDAP_RES_SEARCH_RESULT)
@@ -1420,64 +1545,74 @@ namespace System.DirectoryServices.Protocols
SearchResultReferenceCollection searchResultReferences = new SearchResultReferenceCollection();
// parsing the resultentry
- entryMessage = Wldap32.ldap_first_entry(ldapHandle, ldapResult);
+ entryMessage = Wldap32.ldap_first_entry(_ldapHandle, ldapResult);
int entrycount = 0;
- while (entryMessage != (IntPtr)0)
+ while (entryMessage != IntPtr.Zero)
{
SearchResultEntry entry = ConstructEntry(entryMessage);
if (entry != null)
+ {
searchResultEntries.Add(entry);
+ }
entrycount++;
- entryMessage = Wldap32.ldap_next_entry(ldapHandle, entryMessage);
+ entryMessage = Wldap32.ldap_next_entry(_ldapHandle, entryMessage);
}
- // parsing the reference
- IntPtr referenceMessage = Wldap32.ldap_first_reference(ldapHandle, ldapResult);
+ // Parse the reference.
+ IntPtr referenceMessage = Wldap32.ldap_first_reference(_ldapHandle, ldapResult);
- while (referenceMessage != (IntPtr)0)
+ while (referenceMessage != IntPtr.Zero)
{
SearchResultReference reference = ConstructReference(referenceMessage);
if (reference != null)
+ {
searchResultReferences.Add(reference);
+ }
- referenceMessage = Wldap32.ldap_next_reference(ldapHandle, referenceMessage);
+ referenceMessage = Wldap32.ldap_next_reference(_ldapHandle, referenceMessage);
}
((SearchResponse)response).Entries = searchResultEntries;
((SearchResponse)response).References = searchResultReferences;
}
- if (resulterror != (int)ResultCode.Success && resulterror != (int)ResultCode.CompareFalse && resulterror != (int)ResultCode.CompareTrue && resulterror != (int)ResultCode.Referral && resulterror != (int)ResultCode.ReferralV2)
+ if (resultError != (int)ResultCode.Success && resultError != (int)ResultCode.CompareFalse && resultError != (int)ResultCode.CompareTrue && resultError != (int)ResultCode.Referral && resultError != (int)ResultCode.ReferralV2)
{
- // throw operation exception
- if (Utility.IsResultCode((ResultCode)resulterror))
+ // Throw operation exception.
+ if (Utility.IsResultCode((ResultCode)resultError))
{
- throw new DirectoryOperationException(response, OperationErrorMappings.MapResultCode(resulterror));
+ throw new DirectoryOperationException(response, OperationErrorMappings.MapResultCode(resultError));
}
else
- // should not occur
+ {
+ // This should not occur.
throw new DirectoryOperationException(response);
+ }
}
return response;
}
else
{
- // fall over, throw the exception beow
- error = resulterror;
+ // Fall through, throw the exception beow.
+ error = resultError;
}
}
finally
{
- if (requestName != (IntPtr)0)
+ if (requestName != IntPtr.Zero)
+ {
Wldap32.ldap_memfree(requestName);
+ }
- if (requestValue != (IntPtr)0)
+ if (requestValue != IntPtr.Zero)
+ {
Wldap32.ldap_memfree(requestValue);
+ }
- if (ldapResult != (IntPtr)0)
+ if (ldapResult != IntPtr.Zero)
{
Wldap32.ldap_msgfree(ldapResult);
}
@@ -1490,12 +1625,13 @@ namespace System.DirectoryServices.Protocols
{
if (exceptionOnTimeOut)
{
- // client side timeout
+ // Client side timeout.
error = (int)LdapError.TimeOut;
}
else
{
- // if we don't throw exception on time out (notification search for example), we just return empty resposne
+ // If we don't throw exception on time out (notification search for example), we
+ // just return an empty response.
return null;
}
}
@@ -1504,42 +1640,43 @@ namespace System.DirectoryServices.Protocols
error = Wldap32.LdapGetLastError();
}
- // abandon the request
+ // Abandon the request.
if (needAbandon)
- Wldap32.ldap_abandon(ldapHandle, messageId);
+ {
+ Wldap32.ldap_abandon(_ldapHandle, messageId);
+ }
}
- // throw proper exception here
+ // Throw the proper exception here.
throw ConstructException(error, operation);
}
internal unsafe int ConstructParsedResult(IntPtr ldapResult, ref int serverError, ref string responseDn, ref string responseMessage, ref Uri[] responseReferral, ref DirectoryControl[] responseControl)
{
- IntPtr dn = (IntPtr)0;
- IntPtr message = (IntPtr)0;
- IntPtr referral = (IntPtr)0;
- IntPtr control = (IntPtr)0;
- int resulterror = 0;
+ IntPtr dn = IntPtr.Zero;
+ IntPtr message = IntPtr.Zero;
+ IntPtr referral = IntPtr.Zero;
+ IntPtr control = IntPtr.Zero;
try
{
- resulterror = Wldap32.ldap_parse_result(ldapHandle, ldapResult, ref serverError, ref dn, ref message, ref referral, ref control, 0 /* not free it */);
+ int resultError = Wldap32.ldap_parse_result(_ldapHandle, ldapResult, ref serverError, ref dn, ref message, ref referral, ref control, 0 /* not free it */);
- if (resulterror == 0)
+ if (resultError == 0)
{
- // parsing dn
+ // Parse the dn.
responseDn = Marshal.PtrToStringUni(dn);
- // parsing message
+ // Parse the message.
responseMessage = Marshal.PtrToStringUni(message);
- // parsing referral
- if (referral != (IntPtr)0)
+ // Parse the referral.
+ if (referral != IntPtr.Zero)
{
char** tempPtr = (char**)referral;
char* singleReferral = tempPtr[0];
int i = 0;
- ArrayList referralList = new ArrayList();
+ var referralList = new ArrayList();
while (singleReferral != null)
{
string s = Marshal.PtrToStringUni((IntPtr)singleReferral);
@@ -1553,18 +1690,20 @@ namespace System.DirectoryServices.Protocols
{
responseReferral = new Uri[referralList.Count];
for (int j = 0; j < referralList.Count; j++)
+ {
responseReferral[j] = new Uri((string)referralList[j]);
+ }
}
}
- // parsing control
- if (control != (IntPtr)0)
+ // Parse the control.
+ if (control != IntPtr.Zero)
{
int i = 0;
IntPtr tempControlPtr = control;
IntPtr singleControl = Marshal.ReadIntPtr(tempControlPtr, 0);
- ArrayList controlList = new ArrayList();
- while (singleControl != (IntPtr)0)
+ var controlList = new ArrayList();
+ while (singleControl != IntPtr.Zero)
{
DirectoryControl directoryControl = ConstructControl(singleControl);
controlList.Add(directoryControl);
@@ -1580,91 +1719,98 @@ namespace System.DirectoryServices.Protocols
else
{
// we need to take care of one special case, when can't connect to the server, ldap_parse_result fails with local error
- if (resulterror == (int)LdapError.LocalError)
+ if (resultError == (int)LdapError.LocalError)
{
- int tmpResult = Wldap32.ldap_result2error(ldapHandle, ldapResult, 0 /* not free it */);
+ int tmpResult = Wldap32.ldap_result2error(_ldapHandle, ldapResult, 0 /* not free it */);
if (tmpResult != 0)
{
- resulterror = tmpResult;
+ resultError = tmpResult;
}
}
}
+
+ return resultError;
}
finally
{
- if (dn != (IntPtr)0)
+ if (dn != IntPtr.Zero)
{
Wldap32.ldap_memfree(dn);
}
- if (message != (IntPtr)0)
+ if (message != IntPtr.Zero)
+ {
Wldap32.ldap_memfree(message);
+ }
- if (referral != (IntPtr)0)
+ if (referral != IntPtr.Zero)
+ {
Wldap32.ldap_value_free(referral);
+ }
- if (control != (IntPtr)0)
+ if (control != IntPtr.Zero)
+ {
Wldap32.ldap_controls_free(control);
+ }
}
-
- return resulterror;
}
internal SearchResultEntry ConstructEntry(IntPtr entryMessage)
{
- IntPtr dn = (IntPtr)0;
- string entryDn = null;
- IntPtr attribute = (IntPtr)0;
- IntPtr address = (IntPtr)0;
- SearchResultAttributeCollection attributes = null;
+ IntPtr dn = IntPtr.Zero;
+ IntPtr attribute = IntPtr.Zero;
+ IntPtr address = IntPtr.Zero;
try
{
- // get the dn
- dn = Wldap32.ldap_get_dn(ldapHandle, entryMessage);
- if (dn != (IntPtr)0)
+ // Get the dn.
+ string entryDn = null;
+ dn = Wldap32.ldap_get_dn(_ldapHandle, entryMessage);
+ if (dn != IntPtr.Zero)
{
entryDn = Marshal.PtrToStringUni(dn);
Wldap32.ldap_memfree(dn);
- dn = (IntPtr)0;
+ dn = IntPtr.Zero;
}
SearchResultEntry resultEntry = new SearchResultEntry(entryDn);
- attributes = resultEntry.Attributes;
+ SearchResultAttributeCollection attributes = resultEntry.Attributes;
- // get attributes
- attribute = Wldap32.ldap_first_attribute(ldapHandle, entryMessage, ref address);
+ // Get attributes.
+ attribute = Wldap32.ldap_first_attribute(_ldapHandle, entryMessage, ref address);
int tempcount = 0;
- while (attribute != (IntPtr)0)
+ while (attribute != IntPtr.Zero)
{
DirectoryAttribute attr = ConstructAttribute(entryMessage, attribute);
attributes.Add(attr.Name, attr);
Wldap32.ldap_memfree(attribute);
tempcount++;
- attribute = Wldap32.ldap_next_attribute(ldapHandle, entryMessage, address);
+ attribute = Wldap32.ldap_next_attribute(_ldapHandle, entryMessage, address);
}
- if (address != (IntPtr)0)
+ if (address != IntPtr.Zero)
{
Wldap32.ber_free(address, 0);
- address = (IntPtr)0;
+ address = IntPtr.Zero;
}
return resultEntry;
}
finally
{
- if (dn != (IntPtr)0)
+ if (dn != IntPtr.Zero)
{
Wldap32.ldap_memfree(dn);
}
- if (attribute != (IntPtr)0)
+ if (attribute != IntPtr.Zero)
+ {
Wldap32.ldap_memfree(attribute);
+ }
- if (address != (IntPtr)0)
+ if (address != IntPtr.Zero)
{
Wldap32.ber_free(address, 0);
}
@@ -1673,28 +1819,27 @@ namespace System.DirectoryServices.Protocols
internal DirectoryAttribute ConstructAttribute(IntPtr entryMessage, IntPtr attributeName)
{
- DirectoryAttribute attribute = new DirectoryAttribute();
- attribute._isSearchResult = true;
+ var attribute = new DirectoryAttribute()
+ {
+ _isSearchResult = true
+ };
- // get name
string name = Marshal.PtrToStringUni(attributeName);
attribute.Name = name;
- // get values
- IntPtr valuesArray = Wldap32.ldap_get_values_len(ldapHandle, entryMessage, name);
+ IntPtr valuesArray = Wldap32.ldap_get_values_len(_ldapHandle, entryMessage, name);
try
{
- IntPtr tempPtr = (IntPtr)0;
- int count = 0;
- if (valuesArray != (IntPtr)0)
+ if (valuesArray != IntPtr.Zero)
{
- tempPtr = Marshal.ReadIntPtr(valuesArray, IntPtr.Size * count);
- while (tempPtr != (IntPtr)0)
+ int count = 0;
+ IntPtr tempPtr = Marshal.ReadIntPtr(valuesArray, IntPtr.Size * count);
+ while (tempPtr != IntPtr.Zero)
{
berval bervalue = new berval();
Marshal.PtrToStructure(tempPtr, bervalue);
byte[] byteArray = null;
- if (bervalue.bv_len > 0 && bervalue.bv_val != (IntPtr)0)
+ if (bervalue.bv_len > 0 && bervalue.bv_val != IntPtr.Zero)
{
byteArray = new byte[bervalue.bv_len];
Marshal.Copy(bervalue.bv_val, byteArray, 0, bervalue.bv_len);
@@ -1708,8 +1853,10 @@ namespace System.DirectoryServices.Protocols
}
finally
{
- if (valuesArray != (IntPtr)0)
+ if (valuesArray != IntPtr.Zero)
+ {
Wldap32.ldap_value_free_len(valuesArray);
+ }
}
return attribute;
@@ -1717,23 +1864,21 @@ namespace System.DirectoryServices.Protocols
internal SearchResultReference ConstructReference(IntPtr referenceMessage)
{
- SearchResultReference reference = null;
- ArrayList referralList = new ArrayList();
- Uri[] uris = null;
- IntPtr referenceArray = (IntPtr)0;
+ IntPtr referenceArray = IntPtr.Zero;
- int error = Wldap32.ldap_parse_reference(ldapHandle, referenceMessage, ref referenceArray);
+ int error = Wldap32.ldap_parse_reference(_ldapHandle, referenceMessage, ref referenceArray);
try
{
if (error == 0)
{
- IntPtr tempPtr = (IntPtr)0;
+ var referralList = new ArrayList();
+ IntPtr tempPtr = IntPtr.Zero;
int count = 0;
- if (referenceArray != (IntPtr)0)
+ if (referenceArray != IntPtr.Zero)
{
tempPtr = Marshal.ReadIntPtr(referenceArray, IntPtr.Size * count);
- while (tempPtr != (IntPtr)0)
+ while (tempPtr != IntPtr.Zero)
{
string s = Marshal.PtrToStringUni(tempPtr);
referralList.Add(s);
@@ -1743,28 +1888,30 @@ namespace System.DirectoryServices.Protocols
}
Wldap32.ldap_value_free(referenceArray);
- referenceArray = (IntPtr)0;
+ referenceArray = IntPtr.Zero;
}
if (referralList.Count > 0)
{
- uris = new Uri[referralList.Count];
+ Uri[] uris = new Uri[referralList.Count];
for (int i = 0; i < referralList.Count; i++)
{
uris[i] = new Uri((string)referralList[i]);
}
- reference = new SearchResultReference(uris);
+ return new SearchResultReference(uris);
}
}
}
finally
{
- if (referenceArray != (IntPtr)0)
+ if (referenceArray != IntPtr.Zero)
+ {
Wldap32.ldap_value_free(referenceArray);
+ }
}
- return reference;
+ return null;
}
private DirectoryException ConstructException(int error, LdapOperation operation)
@@ -1774,19 +1921,33 @@ namespace System.DirectoryServices.Protocols
if (Utility.IsResultCode((ResultCode)error))
{
if (operation == LdapOperation.LdapAdd)
+ {
response = new AddResponse(null, null, (ResultCode)error, OperationErrorMappings.MapResultCode(error), null);
+ }
else if (operation == LdapOperation.LdapModify)
+ {
response = new ModifyResponse(null, null, (ResultCode)error, OperationErrorMappings.MapResultCode(error), null);
+ }
else if (operation == LdapOperation.LdapDelete)
+ {
response = new DeleteResponse(null, null, (ResultCode)error, OperationErrorMappings.MapResultCode(error), null);
+ }
else if (operation == LdapOperation.LdapModifyDn)
+ {
response = new ModifyDNResponse(null, null, (ResultCode)error, OperationErrorMappings.MapResultCode(error), null);
+ }
else if (operation == LdapOperation.LdapCompare)
+ {
response = new CompareResponse(null, null, (ResultCode)error, OperationErrorMappings.MapResultCode(error), null);
+ }
else if (operation == LdapOperation.LdapSearch)
+ {
response = new SearchResponse(null, null, (ResultCode)error, OperationErrorMappings.MapResultCode(error), null);
+ }
else if (operation == LdapOperation.LdapExtendedRequest)
+ {
response = new ExtendedResponse(null, null, (ResultCode)error, OperationErrorMappings.MapResultCode(error), null);
+ }
string errorMessage = OperationErrorMappings.MapResultCode(error);
return new DirectoryOperationException(response, errorMessage);
@@ -1796,18 +1957,16 @@ namespace System.DirectoryServices.Protocols
if (Utility.IsLdapError((LdapError)error))
{
string errorMessage = LdapErrorMappings.MapResultCode(error);
- string serverErrorMessage = _options.ServerErrorMessage;
- if ((serverErrorMessage != null) && (serverErrorMessage.Length > 0))
+ string serverErrorMessage = SessionOptions.ServerErrorMessage;
+ if (!string.IsNullOrEmpty(serverErrorMessage))
{
throw new LdapException(error, errorMessage, serverErrorMessage);
}
- else
- {
- return new LdapException(error, errorMessage);
- }
+
+ return new LdapException(error, errorMessage);
}
- else
- return new LdapException(error);
+
+ return new LdapException(error);
}
}
@@ -1816,7 +1975,7 @@ namespace System.DirectoryServices.Protocols
LdapControl control = new LdapControl();
Marshal.PtrToStructure(controlPtr, control);
- Debug.Assert(control.ldctl_oid != (IntPtr)0);
+ Debug.Assert(control.ldctl_oid != IntPtr.Zero);
string controlType = Marshal.PtrToStringUni(control.ldctl_oid);
byte[] bytes = new byte[control.ldctl_value.bv_len];
@@ -1830,19 +1989,29 @@ namespace System.DirectoryServices.Protocols
private bool SameCredential(NetworkCredential oldCredential, NetworkCredential newCredential)
{
if (oldCredential == null && newCredential == null)
+ {
return true;
+ }
else if (oldCredential == null && newCredential != null)
+ {
return false;
+ }
else if (oldCredential != null && newCredential == null)
+ {
return false;
+ }
else
{
if (oldCredential.Domain == newCredential.Domain &&
oldCredential.UserName == newCredential.UserName &&
oldCredential.Password == newCredential.Password)
+ {
return true;
+ }
else
+ {
return false;
+ }
}
}
}
diff --git a/src/System.DirectoryServices.Protocols/src/System/DirectoryServices/Protocols/ldap/LdapDirectoryIdentifier.cs b/src/System.DirectoryServices.Protocols/src/System/DirectoryServices/Protocols/ldap/LdapDirectoryIdentifier.cs
index e43ba76e02..2e4987e157 100644
--- a/src/System.DirectoryServices.Protocols/src/System/DirectoryServices/Protocols/ldap/LdapDirectoryIdentifier.cs
+++ b/src/System.DirectoryServices.Protocols/src/System/DirectoryServices/Protocols/ldap/LdapDirectoryIdentifier.cs
@@ -4,15 +4,9 @@
namespace System.DirectoryServices.Protocols
{
- using System;
- using System.Globalization;
-
public class LdapDirectoryIdentifier : DirectoryIdentifier
{
private string[] _servers = null;
- private bool _fullyQualifiedDnsHostName = false;
- private bool _connectionless = false;
- private int _portNumber = 389;
public LdapDirectoryIdentifier(string server) : this(server != null ? new string[] { server } : null, false, false)
{
@@ -43,18 +37,22 @@ namespace System.DirectoryServices.Protocols
string trimmedName = servers[i].Trim();
string[] result = trimmedName.Split(new char[] { ' ' });
if (result.Length > 1)
- throw new ArgumentException(String.Format(CultureInfo.CurrentCulture, SR.WhiteSpaceServerName));
+ {
+ throw new ArgumentException(SR.WhiteSpaceServerName);
+ }
+
_servers[i] = trimmedName;
}
}
}
- _fullyQualifiedDnsHostName = fullyQualifiedDnsHostName;
- _connectionless = connectionless;
+
+ FullyQualifiedDnsHostName = fullyQualifiedDnsHostName;
+ Connectionless = connectionless;
}
public LdapDirectoryIdentifier(string[] servers, int portNumber, bool fullyQualifiedDnsHostName, bool connectionless) : this(servers, fullyQualifiedDnsHostName, connectionless)
{
- _portNumber = portNumber;
+ PortNumber = portNumber;
}
public string[] Servers
@@ -62,44 +60,31 @@ namespace System.DirectoryServices.Protocols
get
{
if (_servers == null)
- return new string[0];
- else
{
- string[] temporaryServers = new string[_servers.Length];
- for (int i = 0; i < _servers.Length; i++)
+ return Array.Empty<string>();
+ }
+
+ var temporaryServers = new string[_servers.Length];
+ for (int i = 0; i < _servers.Length; i++)
+ {
+ if (_servers[i] != null)
+ {
+ temporaryServers[i] = string.Copy(_servers[i]);
+ }
+ else
{
- if (_servers[i] != null)
- temporaryServers[i] = String.Copy(_servers[i]);
- else
- temporaryServers[i] = null;
+ temporaryServers[i] = null;
}
- return temporaryServers;
}
- }
- }
- public bool Connectionless
- {
- get
- {
- return _connectionless;
+ return temporaryServers;
}
}
- public bool FullyQualifiedDnsHostName
- {
- get
- {
- return _fullyQualifiedDnsHostName;
- }
- }
+ public bool Connectionless { get; }
- public int PortNumber
- {
- get
- {
- return _portNumber;
- }
- }
+ public bool FullyQualifiedDnsHostName { get; }
+
+ public int PortNumber { get; } = 389;
}
}
diff --git a/src/System.DirectoryServices.Protocols/src/System/DirectoryServices/Protocols/ldap/LdapException.cs b/src/System.DirectoryServices.Protocols/src/System/DirectoryServices/Protocols/ldap/LdapException.cs
index 62a24c2903..4f80ba37f0 100644
--- a/src/System.DirectoryServices.Protocols/src/System/DirectoryServices/Protocols/ldap/LdapException.cs
+++ b/src/System.DirectoryServices.Protocols/src/System/DirectoryServices/Protocols/ldap/LdapException.cs
@@ -67,9 +67,6 @@ namespace System.DirectoryServices.Protocols
[Serializable]
public class LdapException : DirectoryException, ISerializable
{
- private int _errorCode;
- private string _serverErrorMessage;
- internal PartialResultsCollection results = new PartialResultsCollection();
protected LdapException(SerializationInfo info, StreamingContext context) : base(info, context) { }
public LdapException() : base() { }
@@ -80,53 +77,30 @@ namespace System.DirectoryServices.Protocols
public LdapException(int errorCode) : base(SR.DefaultLdapError)
{
- _errorCode = errorCode;
+ ErrorCode = errorCode;
}
public LdapException(int errorCode, string message) : base(message)
{
- _errorCode = errorCode;
+ ErrorCode = errorCode;
}
public LdapException(int errorCode, string message, string serverErrorMessage) : base(message)
{
- _errorCode = errorCode;
- _serverErrorMessage = serverErrorMessage;
+ ErrorCode = errorCode;
+ ServerErrorMessage = serverErrorMessage;
}
public LdapException(int errorCode, string message, Exception inner) : base(message, inner)
{
- _errorCode = errorCode;
+ ErrorCode = errorCode;
}
- public int ErrorCode
- {
- get
- {
- return _errorCode;
- }
- }
+ public int ErrorCode { get; }
- public string ServerErrorMessage
- {
- get
- {
- return _serverErrorMessage;
- }
- }
+ public string ServerErrorMessage { get; }
- public PartialResultsCollection PartialResults
- {
- get
- {
- return this.results;
- }
- }
-
- public override void GetObjectData(SerializationInfo serializationInfo, StreamingContext streamingContext)
- {
- base.GetObjectData(serializationInfo, streamingContext);
- }
+ public PartialResultsCollection PartialResults { get; } = new PartialResultsCollection();
}
[Serializable]
@@ -157,21 +131,22 @@ namespace System.DirectoryServices.Protocols
{
public static void CheckAndSetLdapError(int error)
{
- string errorMessage;
if (error != (int)ResultCode.Success)
{
if (Utility.IsResultCode((ResultCode)error))
{
- errorMessage = OperationErrorMappings.MapResultCode(error);
+ string errorMessage = OperationErrorMappings.MapResultCode(error);
throw new DirectoryOperationException(null, errorMessage);
}
else if (Utility.IsLdapError((LdapError)error))
{
- errorMessage = LdapErrorMappings.MapResultCode(error);
+ string errorMessage = LdapErrorMappings.MapResultCode(error);
throw new LdapException(error, errorMessage);
}
else
+ {
throw new LdapException(error);
+ }
}
}
}
diff --git a/src/System.DirectoryServices.Protocols/src/System/DirectoryServices/Protocols/ldap/LdapPartialResultsProcessor.cs b/src/System.DirectoryServices.Protocols/src/System/DirectoryServices/Protocols/ldap/LdapPartialResultsProcessor.cs
index cff516b92c..2c09a5fea1 100644
--- a/src/System.DirectoryServices.Protocols/src/System/DirectoryServices/Protocols/ldap/LdapPartialResultsProcessor.cs
+++ b/src/System.DirectoryServices.Protocols/src/System/DirectoryServices/Protocols/ldap/LdapPartialResultsProcessor.cs
@@ -2,24 +2,22 @@
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
+using System.Globalization;
+using System.Threading;
+using System.Collections;
+using System.Diagnostics;
+
namespace System.DirectoryServices.Protocols
{
- using System;
- using System.Globalization;
- using System.Threading;
- using System.Collections;
- using System.Diagnostics;
-
internal class LdapPartialResultsProcessor
{
- private ArrayList _resultList = null;
+ private ArrayList _resultList = new ArrayList();
private ManualResetEvent _workThreadWaitHandle = null;
private bool _workToDo = false;
private int _currentIndex = 0;
internal LdapPartialResultsProcessor(ManualResetEvent eventHandle)
{
- _resultList = new ArrayList();
_workThreadWaitHandle = eventHandle;
}
@@ -31,7 +29,7 @@ namespace System.DirectoryServices.Protocols
if (!_workToDo)
{
- // need to wake up the workthread if it is not running already
+ // Need to wake up the workthread if it is not running already.
_workThreadWaitHandle.Set();
_workToDo = true;
}
@@ -40,174 +38,185 @@ namespace System.DirectoryServices.Protocols
public void Remove(LdapPartialAsyncResult asyncResult)
{
- // called by Abort operation
+ // Called by Abort operation.
lock (this)
{
if (!_resultList.Contains(asyncResult))
- throw new ArgumentException(String.Format(CultureInfo.CurrentCulture, SR.InvalidAsyncResult));
+ {
+ throw new ArgumentException(SR.InvalidAsyncResult);
+ }
- // remove this async operation from the list
+ // Remove this async operation from the list.
_resultList.Remove(asyncResult);
}
}
public void RetrievingSearchResults()
{
- int count = 0;
- int i = 0;
LdapPartialAsyncResult asyncResult = null;
AsyncCallback tmpCallback = null;
lock (this)
{
- count = _resultList.Count;
+ int count = _resultList.Count;
if (count == 0)
{
- // no asynchronous operation pending, begin to wait
+ // No asynchronous operation pending, begin to wait.
_workThreadWaitHandle.Reset();
_workToDo = false;
return;
}
- // might have work to do
+ // Might have work to do.
+ int i = 0;
while (true)
{
if (_currentIndex >= count)
{
- // some element is moved after last iteration
+ // Some element is moved after last iteration.
_currentIndex = 0;
}
asyncResult = (LdapPartialAsyncResult)_resultList[_currentIndex];
i++;
_currentIndex++;
-
- // have work to do
- if (asyncResult.resultStatus != ResultsStatus.Done)
+
+ // Have work to do.
+ if (asyncResult._resultStatus != ResultsStatus.Done)
+ {
break;
+ }
if (i >= count)
{
- // all the operations are done just waiting for the user to pick up the results
+ // All the operations are done just waiting for the user to pick up the results.
_workToDo = false;
_workThreadWaitHandle.Reset();
return;
}
}
- // try to get the results availabe for this asynchronous operation
+ // Try to get the results availabe for this asynchronous operation .
GetResultsHelper(asyncResult);
-
- // if we are done with the asynchronous search, we need to fire callback and signal the waitable object
- if (asyncResult.resultStatus == ResultsStatus.Done)
+
+ // If we are done with the asynchronous search, we need to fire callback and signal the waitable object.
+ if (asyncResult._resultStatus == ResultsStatus.Done)
{
- asyncResult.manualResetEvent.Set();
- asyncResult.completed = true;
- if (asyncResult.callback != null)
+ asyncResult._manualResetEvent.Set();
+ asyncResult._completed = true;
+ if (asyncResult._callback != null)
{
- tmpCallback = asyncResult.callback;
+ tmpCallback = asyncResult._callback;
}
}
- else if (asyncResult.callback != null && asyncResult.partialCallback)
+ else if (asyncResult._callback != null && asyncResult._partialCallback)
{
- // if user specify callback to be called even when partial results become available
- if (asyncResult.response != null && (asyncResult.response.Entries.Count > 0 || asyncResult.response.References.Count > 0))
+ // The user specified a callback to be called even when partial results become available.
+ if (asyncResult._response != null && (asyncResult._response.Entries.Count > 0 || asyncResult._response.References.Count > 0))
{
- tmpCallback = asyncResult.callback;
+ tmpCallback = asyncResult._callback;
}
}
}
- if (tmpCallback != null)
- tmpCallback((IAsyncResult)asyncResult);
+ tmpCallback?.Invoke(asyncResult);
}
private void GetResultsHelper(LdapPartialAsyncResult asyncResult)
{
- LdapConnection con = asyncResult.con;
- IntPtr ldapResult = (IntPtr)0;
- IntPtr entryMessage = (IntPtr)0;
+ LdapConnection connection = asyncResult._con;
ResultAll resultType = ResultAll.LDAP_MSG_RECEIVED;
- if (asyncResult.resultStatus == ResultsStatus.CompleteResult)
+ if (asyncResult._resultStatus == ResultsStatus.CompleteResult)
+ {
resultType = ResultAll.LDAP_MSG_POLLINGALL;
+ }
try
{
- SearchResponse response = (SearchResponse)con.ConstructResponse(asyncResult.messageID, LdapOperation.LdapSearch, resultType, asyncResult.requestTimeout, false);
- // this should only happen in the polling thread case
+ SearchResponse response = (SearchResponse)connection.ConstructResponse(asyncResult._messageID, LdapOperation.LdapSearch, resultType, asyncResult._requestTimeout, false);
+
+ // This should only happen in the polling thread case.
if (response == null)
{
- // only when request time out has not yet expiered
- if ((asyncResult.startTime.Ticks + asyncResult.requestTimeout.Ticks) > DateTime.Now.Ticks)
+ // Only when request time out has not yet expiered.
+ if ((asyncResult._startTime.Ticks + asyncResult._requestTimeout.Ticks) > DateTime.Now.Ticks)
{
- // this is expected, just the client does not have the result yet
+ // This is expected, just the client does not have the result yet .
return;
}
else
{
- // time out, now we need to throw proper exception
+ // time out, now we need to throw proper exception
throw new LdapException((int)LdapError.TimeOut, LdapErrorMappings.MapResultCode((int)LdapError.TimeOut));
}
}
- if (asyncResult.response != null)
- AddResult(asyncResult.response, response);
+ if (asyncResult._response != null)
+ {
+ AddResult(asyncResult._response, response);
+ }
else
- asyncResult.response = response;
+ {
+ asyncResult._response = response;
+ }
- // if search is done, set the flag
+ // If search is done, set the flag.
if (response.searchDone)
- asyncResult.resultStatus = ResultsStatus.Done;
+ {
+ asyncResult._resultStatus = ResultsStatus.Done;
+ }
}
- catch (Exception e)
+ catch (Exception exception)
{
- if (e is DirectoryOperationException)
+ if (exception is DirectoryOperationException directoryOperationException)
{
- SearchResponse response = (SearchResponse)(((DirectoryOperationException)e).Response);
-
- if (asyncResult.response != null)
- AddResult(asyncResult.response, response);
+ SearchResponse response = (SearchResponse)directoryOperationException.Response;
+ if (asyncResult._response != null)
+ {
+ AddResult(asyncResult._response, response);
+ }
else
- asyncResult.response = response;
+ {
+ asyncResult._response = response;
+ }
- // set the response back to the exception so it holds all the results up to now
- ((DirectoryOperationException)e).Response = asyncResult.response;
+ // Set the response back to the exception so it holds all the results up to now.
+ directoryOperationException.Response = asyncResult._response;
}
- else if (e is LdapException)
+ else if (exception is LdapException ldapException)
{
- LdapException ldapE = (LdapException)e;
- LdapError errorCode = (LdapError)ldapE.ErrorCode;
+ LdapError errorCode = (LdapError)ldapException.ErrorCode;
- if (asyncResult.response != null)
+ if (asyncResult._response != null)
{
// add previous retrieved entries if available
- if (asyncResult.response.Entries != null)
+ if (asyncResult._response.Entries != null)
{
- for (int i = 0; i < asyncResult.response.Entries.Count; i++)
+ for (int i = 0; i < asyncResult._response.Entries.Count; i++)
{
- ldapE.results.Add(asyncResult.response.Entries[i]);
+ ldapException.PartialResults.Add(asyncResult._response.Entries[i]);
}
}
// add previous retrieved references if available
- if (asyncResult.response.References != null)
+ if (asyncResult._response.References != null)
{
- for (int i = 0; i < asyncResult.response.References.Count; i++)
+ for (int i = 0; i < asyncResult._response.References.Count; i++)
{
- ldapE.results.Add(asyncResult.response.References[i]);
+ ldapException.PartialResults.Add(asyncResult._response.References[i]);
}
}
}
}
+
+ // Exception occurs, this operation is done.
+ asyncResult._exception = exception;
+ asyncResult._resultStatus = ResultsStatus.Done;
- // exception occurs, this operation is done.
- asyncResult.exception = e;
- asyncResult.resultStatus = ResultsStatus.Done;
-
- // need to abandon this request
- Wldap32.ldap_abandon(con.ldapHandle, asyncResult.messageID);
+ // Need to abandon this request.
+ Wldap32.ldap_abandon(connection._ldapHandle, asyncResult._messageID);
}
}
@@ -217,12 +226,14 @@ namespace System.DirectoryServices.Protocols
{
if (_resultList.Contains(asyncResult))
{
- // we don't need partial results anymore, polling for complete results
- if (asyncResult.resultStatus == ResultsStatus.PartialResult)
- asyncResult.resultStatus = ResultsStatus.CompleteResult;
+ // We don't need partial results anymore, polling for complete results.
+ if (asyncResult._resultStatus == ResultsStatus.PartialResult)
+ asyncResult._resultStatus = ResultsStatus.CompleteResult;
}
else
- throw new ArgumentException(String.Format(CultureInfo.CurrentCulture, SR.InvalidAsyncResult));
+ {
+ throw new ArgumentException(SR.InvalidAsyncResult);
+ }
}
}
@@ -231,35 +242,40 @@ namespace System.DirectoryServices.Protocols
lock (this)
{
if (!_resultList.Contains(asyncResult))
- throw new ArgumentException(String.Format(CultureInfo.CurrentCulture, SR.InvalidAsyncResult));
-
- if (asyncResult.exception != null)
{
- // remove this async operation
+ throw new ArgumentException(SR.InvalidAsyncResult);
+ }
- // the async operation basically failed, we won't do it any more, so throw exception to the user and remove it from the list
+ if (asyncResult._exception != null)
+ {
+ // Remove this async operation
+ // The async operation basically failed, we won't do it any more, so throw
+ // exception to the user and remove it from the list.
_resultList.Remove(asyncResult);
- throw asyncResult.exception;
+ throw asyncResult._exception;
}
- PartialResultsCollection collection = new PartialResultsCollection();
-
- if (asyncResult.response != null)
+ var collection = new PartialResultsCollection();
+ if (asyncResult._response != null)
{
- if (asyncResult.response.Entries != null)
+ if (asyncResult._response.Entries != null)
{
- for (int i = 0; i < asyncResult.response.Entries.Count; i++)
- collection.Add(asyncResult.response.Entries[i]);
+ for (int i = 0; i < asyncResult._response.Entries.Count; i++)
+ {
+ collection.Add(asyncResult._response.Entries[i]);
+ }
- asyncResult.response.Entries.Clear();
+ asyncResult._response.Entries.Clear();
}
- if (asyncResult.response.References != null)
+ if (asyncResult._response.References != null)
{
- for (int i = 0; i < asyncResult.response.References.Count; i++)
- collection.Add(asyncResult.response.References[i]);
+ for (int i = 0; i < asyncResult._response.References.Count; i++)
+ {
+ collection.Add(asyncResult._response.References[i]);
+ }
- asyncResult.response.References.Clear();
+ asyncResult._response.References.Clear();
}
}
@@ -272,19 +288,21 @@ namespace System.DirectoryServices.Protocols
lock (this)
{
if (!_resultList.Contains(asyncResult))
- throw new ArgumentException(String.Format(CultureInfo.CurrentCulture, SR.InvalidAsyncResult));
+ {
+ throw new ArgumentException(SR.InvalidAsyncResult);
+ }
- Debug.Assert(asyncResult.resultStatus == ResultsStatus.Done);
+ Debug.Assert(asyncResult._resultStatus == ResultsStatus.Done);
_resultList.Remove(asyncResult);
- if (asyncResult.exception != null)
+ if (asyncResult._exception != null)
{
- throw asyncResult.exception;
+ throw asyncResult._exception;
}
else
{
- return asyncResult.response;
+ return asyncResult._response;
}
}
}
@@ -292,7 +310,9 @@ namespace System.DirectoryServices.Protocols
private void AddResult(SearchResponse partialResults, SearchResponse newResult)
{
if (newResult == null)
+ {
return;
+ }
if (newResult.Entries != null)
{
@@ -315,39 +335,41 @@ namespace System.DirectoryServices.Protocols
internal class PartialResultsRetriever
{
private ManualResetEvent _workThreadWaitHandle = null;
- private Thread _oThread = null;
private LdapPartialResultsProcessor _processor = null;
+
internal PartialResultsRetriever(ManualResetEvent eventHandle, LdapPartialResultsProcessor processor)
{
_workThreadWaitHandle = eventHandle;
_processor = processor;
- _oThread = new Thread(new ThreadStart(ThreadRoutine));
- _oThread.IsBackground = true;
- // start the thread
- _oThread.Start();
+ // Start the thread.
+ var thread = new Thread(new ThreadStart(ThreadRoutine))
+ {
+ IsBackground = true
+ };
+ thread.Start();
}
private void ThreadRoutine()
{
while (true)
{
- // make sure there is work to do
+ // Make sure there is work to do.
_workThreadWaitHandle.WaitOne();
- // do the real work
+ // Do the real work.
try
{
_processor.RetrievingSearchResults();
}
catch (Exception e)
{
- // we catch the exception here as we don't really want our worker thread to die because it
+ // We catch the exception here as we don't really want our worker thread to die because it
// encounter certain exception when processing a single async operation.
Debug.WriteLine(e.Message);
}
- // Voluntarily gives up the CPU time
+ // Voluntarily gives up the CPU time.
Thread.Sleep(250);
}
}
diff --git a/src/System.DirectoryServices.Protocols/src/System/DirectoryServices/Protocols/ldap/LdapSessionOptions.cs b/src/System.DirectoryServices.Protocols/src/System/DirectoryServices/Protocols/ldap/LdapSessionOptions.cs
index b11b27bcd6..83777e9aa5 100644
--- a/src/System.DirectoryServices.Protocols/src/System/DirectoryServices/Protocols/ldap/LdapSessionOptions.cs
+++ b/src/System.DirectoryServices.Protocols/src/System/DirectoryServices/Protocols/ldap/LdapSessionOptions.cs
@@ -2,21 +2,20 @@
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
+using System.Globalization;
+using System.Net;
+using System.Security.Cryptography.X509Certificates;
+using System.ComponentModel;
+using System.Runtime.InteropServices;
+using System.Collections;
+using System.Text;
+using System.Diagnostics;
+using System.Security.Authentication;
+using System.Runtime.CompilerServices;
+using System.Security.Permissions;
+
namespace System.DirectoryServices.Protocols
{
- using System;
- using System.Globalization;
- using System.Net;
- using System.Security.Cryptography.X509Certificates;
- using System.ComponentModel;
- using System.Runtime.InteropServices;
- using System.Collections;
- using System.Text;
- using System.Diagnostics;
- using System.Security.Authentication;
- using System.Runtime.CompilerServices;
- using System.Security.Permissions;
-
public delegate LdapConnection QueryForConnectionCallback(LdapConnection primaryConnection, LdapConnection referralFromConnection, string newDistinguishedName, LdapDirectoryIdentifier identifier, NetworkCredential credential, long currentUserToken);
public delegate bool NotifyOfNewConnectionCallback(LdapConnection primaryConnection, LdapConnection referralFromConnection, string newDistinguishedName, LdapDirectoryIdentifier identifier, LdapConnection newConnection, NetworkCredential credential, long currentUserToken, int errorCodeFromBind);
public delegate void DereferenceConnectionCallback(LdapConnection primaryConnection, LdapConnection connectionToDereference);
@@ -84,108 +83,32 @@ namespace System.DirectoryServices.Protocols
{
}
- public SecurityProtocol Protocol
- {
- get
- {
- return _securityProtocol;
- }
- }
+ public SecurityProtocol Protocol => _securityProtocol;
- public CipherAlgorithmType AlgorithmIdentifier
- {
- get
- {
- return _identifier;
- }
- }
+ public CipherAlgorithmType AlgorithmIdentifier => _identifier;
- public int CipherStrength
- {
- get
- {
- return _strength;
- }
- }
+ public int CipherStrength => _strength;
- public HashAlgorithmType Hash
- {
- get
- {
- return _hashAlgorithm;
- }
- }
+ public HashAlgorithmType Hash => _hashAlgorithm;
- public int HashStrength
- {
- get
- {
- return _hashStrength;
- }
- }
+ public int HashStrength => _hashStrength;
- public int KeyExchangeAlgorithm
- {
- get
- {
- return _keyExchangeAlgorithm;
- }
- }
+ public int KeyExchangeAlgorithm => _keyExchangeAlgorithm;
- public int ExchangeStrength
- {
- get
- {
- return _exchangeStrength;
- }
- }
+ public int ExchangeStrength => _exchangeStrength;
}
public sealed class ReferralCallback
{
- private QueryForConnectionCallback _query;
- private NotifyOfNewConnectionCallback _notify;
- private DereferenceConnectionCallback _dereference;
-
public ReferralCallback()
{
}
- public QueryForConnectionCallback QueryForConnection
- {
- get
- {
- return _query;
- }
- set
- {
- _query = value;
- }
- }
+ public QueryForConnectionCallback QueryForConnection { get; set; }
- public NotifyOfNewConnectionCallback NotifyNewConnection
- {
- get
- {
- return _notify;
- }
- set
- {
- _notify = value;
- }
- }
+ public NotifyOfNewConnectionCallback NotifyNewConnection { get; set; }
- public DereferenceConnectionCallback DereferenceConnection
- {
- get
- {
- return _dereference;
- }
- set
- {
- _dereference = value;
- }
- }
+ public DereferenceConnectionCallback DereferenceConnection { get; set; }
}
internal struct SecurityHandle
@@ -198,7 +121,7 @@ namespace System.DirectoryServices.Protocols
{
private LdapConnection _connection = null;
private ReferralCallback _callbackRoutine = new ReferralCallback();
- internal QueryClientCertificateCallback clientCertificateDelegate = null;
+ internal QueryClientCertificateCallback _clientCertificateDelegate = null;
private VerifyServerCertificateCallback _serverCertificateDelegate = null;
private QUERYFORCONNECTIONInternal _queryDelegate = null;
@@ -220,16 +143,14 @@ namespace System.DirectoryServices.Protocols
get
{
int result = GetIntValueHelper(LdapOption.LDAP_OPT_REFERRALS);
-
- if (result == 1)
- return ReferralChasingOptions.All;
- else
- return (ReferralChasingOptions)result;
+ return result == 1 ? ReferralChasingOptions.All : (ReferralChasingOptions)result;
}
set
{
if (((value) & (~ReferralChasingOptions.All)) != 0)
- throw new InvalidEnumArgumentException("value", (int)value, typeof(ReferralChasingOptions));
+ {
+ throw new InvalidEnumArgumentException(nameof(value), (int)value, typeof(ReferralChasingOptions));
+ }
SetIntValueHelper(LdapOption.LDAP_OPT_REFERRALS, (int)value);
}
@@ -240,34 +161,24 @@ namespace System.DirectoryServices.Protocols
get
{
int outValue = GetIntValueHelper(LdapOption.LDAP_OPT_SSL);
-
- if (outValue == 1)
- return true;
- else
- return false;
+ return outValue == 1;
}
set
{
- int temp;
- if (value)
- temp = 1;
- else
- temp = 0;
-
+ int temp = value ? 1 : 0;
SetIntValueHelper(LdapOption.LDAP_OPT_SSL, temp);
}
}
public int ReferralHopLimit
{
- get
- {
- return GetIntValueHelper(LdapOption.LDAP_OPT_REFERRAL_HOP_LIMIT);
- }
+ get => GetIntValueHelper(LdapOption.LDAP_OPT_REFERRAL_HOP_LIMIT);
set
{
if (value < 0)
- throw new ArgumentException(String.Format(CultureInfo.CurrentCulture, SR.ValidValue), "value");
+ {
+ throw new ArgumentException(SR.ValidValue, nameof(value));
+ }
SetIntValueHelper(LdapOption.LDAP_OPT_REFERRAL_HOP_LIMIT, value);
}
@@ -275,38 +186,20 @@ namespace System.DirectoryServices.Protocols
public int ProtocolVersion
{
- get
- {
- return GetIntValueHelper(LdapOption.LDAP_OPT_VERSION);
- }
- set
- {
- SetIntValueHelper(LdapOption.LDAP_OPT_VERSION, value);
- }
+ get => GetIntValueHelper(LdapOption.LDAP_OPT_VERSION);
+ set => SetIntValueHelper(LdapOption.LDAP_OPT_VERSION, value);
}
public string HostName
{
- get
- {
- return GetStringValueHelper(LdapOption.LDAP_OPT_HOST_NAME, false);
- }
- set
- {
- SetStringValueHelper(LdapOption.LDAP_OPT_HOST_NAME, value);
- }
+ get => GetStringValueHelper(LdapOption.LDAP_OPT_HOST_NAME, false);
+ set => SetStringValueHelper(LdapOption.LDAP_OPT_HOST_NAME, value);
}
public string DomainName
{
- get
- {
- return GetStringValueHelper(LdapOption.LDAP_OPT_DNSDOMAIN_NAME, true);
- }
- set
- {
- SetStringValueHelper(LdapOption.LDAP_OPT_DNSDOMAIN_NAME, value);
- }
+ get => GetStringValueHelper(LdapOption.LDAP_OPT_DNSDOMAIN_NAME, true);
+ set => SetStringValueHelper(LdapOption.LDAP_OPT_DNSDOMAIN_NAME, value);
}
public LocatorFlags LocatorFlag
@@ -314,14 +207,12 @@ namespace System.DirectoryServices.Protocols
get
{
int result = GetIntValueHelper(LdapOption.LDAP_OPT_GETDSNAME_FLAGS);
-
return (LocatorFlags)result;
}
set
{
- // we don't do validation to the dirsync flag here as underneath API does not check for it and we don't want to put
+ // We don't do validation to the dirsync flag here as underneath API does not check for it and we don't want to put
// unnecessary limitation on it.
-
SetIntValueHelper(LdapOption.LDAP_OPT_GETDSNAME_FLAGS, (int)value);
}
}
@@ -331,11 +222,7 @@ namespace System.DirectoryServices.Protocols
get
{
int outValue = GetIntValueHelper(LdapOption.LDAP_OPT_HOST_REACHABLE);
-
- if (outValue == 1)
- return true;
- else
- return false;
+ return outValue == 1;
}
}
@@ -350,31 +237,29 @@ namespace System.DirectoryServices.Protocols
{
if (value < TimeSpan.Zero)
{
- throw new ArgumentException(String.Format(CultureInfo.CurrentCulture, SR.NoNegativeTime), "value");
+ throw new ArgumentException(SR.NoNegativeTime, nameof(value));
}
- // prevent integer overflow
- if (value.TotalSeconds > Int32.MaxValue)
+ // Prevent integer overflow.
+ if (value.TotalSeconds > int.MaxValue)
{
- throw new ArgumentException(String.Format(CultureInfo.CurrentCulture, SR.TimespanExceedMax), "value");
+ throw new ArgumentException(SR.TimespanExceedMax, nameof(value));
}
int seconds = (int)(value.Ticks / TimeSpan.TicksPerSecond);
-
- SetIntValueHelper(LdapOption.LDAP_OPT_PING_KEEP_ALIVE, (int)seconds);
+ SetIntValueHelper(LdapOption.LDAP_OPT_PING_KEEP_ALIVE, seconds);
}
}
public int PingLimit
{
- get
- {
- return GetIntValueHelper(LdapOption.LDAP_OPT_PING_LIMIT);
- }
+ get => GetIntValueHelper(LdapOption.LDAP_OPT_PING_LIMIT);
set
{
if (value < 0)
- throw new ArgumentException(String.Format(CultureInfo.CurrentCulture, SR.ValidValue), "value");
+ {
+ throw new ArgumentException(SR.ValidValue, nameof(value));
+ }
SetIntValueHelper(LdapOption.LDAP_OPT_PING_LIMIT, value);
}
@@ -391,18 +276,17 @@ namespace System.DirectoryServices.Protocols
{
if (value < TimeSpan.Zero)
{
- throw new ArgumentException(String.Format(CultureInfo.CurrentCulture, SR.NoNegativeTime), "value");
+ throw new ArgumentException(SR.NoNegativeTime, nameof(value));
}
- // prevent integer overflow
- if (value.TotalMilliseconds > Int32.MaxValue)
+ // Prevent integer overflow.
+ if (value.TotalMilliseconds > int.MaxValue)
{
- throw new ArgumentException(String.Format(CultureInfo.CurrentCulture, SR.TimespanExceedMax), "value");
+ throw new ArgumentException(SR.TimespanExceedMax, nameof(value));
}
int milliseconds = (int)(value.Ticks / TimeSpan.TicksPerMillisecond);
-
- SetIntValueHelper(LdapOption.LDAP_OPT_PING_WAIT_TIME, (int)milliseconds);
+ SetIntValueHelper(LdapOption.LDAP_OPT_PING_WAIT_TIME, milliseconds);
}
}
@@ -411,45 +295,32 @@ namespace System.DirectoryServices.Protocols
get
{
int outValue = GetIntValueHelper(LdapOption.LDAP_OPT_AUTO_RECONNECT);
-
- if (outValue == 1)
- return true;
- else
- return false;
+ return outValue == 1;
}
set
{
- int temp;
- if (value)
- temp = 1;
- else
- temp = 0;
-
+ int temp = value ? 1 : 0;
SetIntValueHelper(LdapOption.LDAP_OPT_AUTO_RECONNECT, temp);
}
}
public int SspiFlag
{
- get
- {
- return GetIntValueHelper(LdapOption.LDAP_OPT_SSPI_FLAGS);
- }
- set
- {
- SetIntValueHelper(LdapOption.LDAP_OPT_SSPI_FLAGS, value);
- }
+ get => GetIntValueHelper(LdapOption.LDAP_OPT_SSPI_FLAGS);
+ set => SetIntValueHelper(LdapOption.LDAP_OPT_SSPI_FLAGS, value);
}
public SecurityPackageContextConnectionInformation SslInformation
{
get
{
- if (_connection.disposed)
+ if (_connection._disposed)
+ {
throw new ObjectDisposedException(GetType().Name);
+ }
- SecurityPackageContextConnectionInformation secInfo = new SecurityPackageContextConnectionInformation();
- int error = Wldap32.ldap_get_option_secInfo(_connection.ldapHandle, LdapOption.LDAP_OPT_SSL_INFO, secInfo);
+ var secInfo = new SecurityPackageContextConnectionInformation();
+ int error = Wldap32.ldap_get_option_secInfo(_connection._ldapHandle, LdapOption.LDAP_OPT_SSL_INFO, secInfo);
ErrorChecking.CheckAndSetLdapError(error);
return secInfo;
@@ -460,12 +331,14 @@ namespace System.DirectoryServices.Protocols
{
get
{
- if (_connection.disposed)
+ if (_connection._disposed)
+ {
throw new ObjectDisposedException(GetType().Name);
+ }
- SecurityHandle tempHandle = new SecurityHandle();
+ var tempHandle = new SecurityHandle();
- int error = Wldap32.ldap_get_option_sechandle(_connection.ldapHandle, LdapOption.LDAP_OPT_SECURITY_CONTEXT, ref tempHandle);
+ int error = Wldap32.ldap_get_option_sechandle(_connection._ldapHandle, LdapOption.LDAP_OPT_SECURITY_CONTEXT, ref tempHandle);
ErrorChecking.CheckAndSetLdapError(error);
return tempHandle;
@@ -477,20 +350,11 @@ namespace System.DirectoryServices.Protocols
get
{
int outValue = GetIntValueHelper(LdapOption.LDAP_OPT_SIGN);
-
- if (outValue == 1)
- return true;
- else
- return false;
+ return outValue == 1;
}
set
{
- int temp;
- if (value)
- temp = 1;
- else
- temp = 0;
-
+ int temp = value ? 1 : 0;
SetIntValueHelper(LdapOption.LDAP_OPT_SIGN, temp);
}
}
@@ -500,34 +364,19 @@ namespace System.DirectoryServices.Protocols
get
{
int outValue = GetIntValueHelper(LdapOption.LDAP_OPT_ENCRYPT);
-
- if (outValue == 1)
- return true;
- else
- return false;
+ return outValue == 1;
}
set
{
- int temp;
- if (value)
- temp = 1;
- else
- temp = 0;
-
+ int temp = value ? 1 : 0;
SetIntValueHelper(LdapOption.LDAP_OPT_ENCRYPT, temp);
}
}
public string SaslMethod
{
- get
- {
- return GetStringValueHelper(LdapOption.LDAP_OPT_SASL_METHOD, true);
- }
- set
- {
- SetStringValueHelper(LdapOption.LDAP_OPT_SASL_METHOD, value);
- }
+ get => GetStringValueHelper(LdapOption.LDAP_OPT_SASL_METHOD, true);
+ set => SetStringValueHelper(LdapOption.LDAP_OPT_SASL_METHOD, value);
}
public bool RootDseCache
@@ -535,20 +384,11 @@ namespace System.DirectoryServices.Protocols
get
{
int outValue = GetIntValueHelper(LdapOption.LDAP_OPT_ROOTDSE_CACHE);
-
- if (outValue == 1)
- return true;
- else
- return false;
+ return outValue == 1;
}
set
{
- int temp;
- if (value)
- temp = 1;
- else
- temp = 0;
-
+ int temp = value ? 1 : 0;
SetIntValueHelper(LdapOption.LDAP_OPT_ROOTDSE_CACHE, temp);
}
}
@@ -558,20 +398,11 @@ namespace System.DirectoryServices.Protocols
get
{
int outValue = GetIntValueHelper(LdapOption.LDAP_OPT_TCP_KEEPALIVE);
-
- if (outValue == 1)
- return true;
- else
- return false;
+ return outValue == 1;
}
set
{
- int temp;
- if (value)
- temp = 1;
- else
- temp = 0;
-
+ int temp = value ? 1 : 0;
SetIntValueHelper(LdapOption.LDAP_OPT_TCP_KEEPALIVE, temp);
}
}
@@ -587,18 +418,17 @@ namespace System.DirectoryServices.Protocols
{
if (value < TimeSpan.Zero)
{
- throw new ArgumentException(String.Format(CultureInfo.CurrentCulture, SR.NoNegativeTime), "value");
+ throw new ArgumentException(SR.NoNegativeTime, nameof(value));
}
- // prevent integer overflow
- if (value.TotalSeconds > Int32.MaxValue)
+ // Prevent integer overflow.
+ if (value.TotalSeconds > int.MaxValue)
{
- throw new ArgumentException(String.Format(CultureInfo.CurrentCulture, SR.TimespanExceedMax), "value");
+ throw new ArgumentException(SR.TimespanExceedMax, nameof(value));
}
int seconds = (int)(value.Ticks / TimeSpan.TicksPerSecond);
-
- SetIntValueHelper(LdapOption.LDAP_OPT_SEND_TIMEOUT, (int)seconds);
+ SetIntValueHelper(LdapOption.LDAP_OPT_SEND_TIMEOUT, seconds);
}
}
@@ -606,17 +436,21 @@ namespace System.DirectoryServices.Protocols
{
get
{
- if (_connection.disposed)
+ if (_connection._disposed)
+ {
throw new ObjectDisposedException(GetType().Name);
+ }
return _callbackRoutine;
}
set
{
- if (_connection.disposed)
+ if (_connection._disposed)
+ {
throw new ObjectDisposedException(GetType().Name);
+ }
- ReferralCallback tempCallback = new ReferralCallback();
+ var tempCallback = new ReferralCallback();
if (value != null)
{
@@ -632,8 +466,6 @@ namespace System.DirectoryServices.Protocols
}
ProcessCallBackRoutine(tempCallback);
-
- // set the callback property
_callbackRoutine = value;
}
}
@@ -642,33 +474,41 @@ namespace System.DirectoryServices.Protocols
{
get
{
- if (_connection.disposed)
+ if (_connection._disposed)
+ {
throw new ObjectDisposedException(GetType().Name);
+ }
- return clientCertificateDelegate;
+ return _clientCertificateDelegate;
}
set
{
- if (_connection.disposed)
+ if (_connection._disposed)
+ {
throw new ObjectDisposedException(GetType().Name);
+ }
if (value != null)
{
- int certerror = Wldap32.ldap_set_option_clientcert(_connection.ldapHandle, LdapOption.LDAP_OPT_CLIENT_CERTIFICATE, _connection.clientCertificateRoutine);
- if (certerror != (int)ResultCode.Success)
+ int certError = Wldap32.ldap_set_option_clientcert(_connection._ldapHandle, LdapOption.LDAP_OPT_CLIENT_CERTIFICATE, _connection._clientCertificateRoutine);
+ if (certError != (int)ResultCode.Success)
{
- if (Utility.IsLdapError((LdapError)certerror))
+ if (Utility.IsLdapError((LdapError)certError))
{
- string certerrorMessage = LdapErrorMappings.MapResultCode(certerror);
- throw new LdapException(certerror, certerrorMessage);
+ string certerrorMessage = LdapErrorMappings.MapResultCode(certError);
+ throw new LdapException(certError, certerrorMessage);
}
else
- throw new LdapException(certerror);
+ {
+ throw new LdapException(certError);
+ }
}
- // certificate callback is specified, automatic bind is disabled
- _connection.automaticBind = false;
+
+ // A certificate callback is specified so automatic bind is disabled.
+ _connection.AutoBind = false;
}
- clientCertificateDelegate = value;
+
+ _clientCertificateDelegate = value;
}
}
@@ -676,43 +516,36 @@ namespace System.DirectoryServices.Protocols
{
get
{
- if (_connection.disposed)
+ if (_connection._disposed)
+ {
throw new ObjectDisposedException(GetType().Name);
+ }
return _serverCertificateDelegate;
}
set
{
- if (_connection.disposed)
+ if (_connection._disposed)
+ {
throw new ObjectDisposedException(GetType().Name);
+ }
if (value != null)
{
- int error = Wldap32.ldap_set_option_servercert(_connection.ldapHandle, LdapOption.LDAP_OPT_SERVER_CERTIFICATE, _serverCertificateRoutine);
+ int error = Wldap32.ldap_set_option_servercert(_connection._ldapHandle, LdapOption.LDAP_OPT_SERVER_CERTIFICATE, _serverCertificateRoutine);
ErrorChecking.CheckAndSetLdapError(error);
}
+
_serverCertificateDelegate = value;
}
}
- internal string ServerErrorMessage
- {
- get
- {
- return GetStringValueHelper(LdapOption.LDAP_OPT_SERVER_ERROR, true);
- }
- }
+ internal string ServerErrorMessage => GetStringValueHelper(LdapOption.LDAP_OPT_SERVER_ERROR, true);
internal DereferenceAlias DerefAlias
{
- get
- {
- return (DereferenceAlias)GetIntValueHelper(LdapOption.LDAP_OPT_DEREF);
- }
- set
- {
- SetIntValueHelper(LdapOption.LDAP_OPT_DEREF, (int)value);
- }
+ get => (DereferenceAlias)GetIntValueHelper(LdapOption.LDAP_OPT_DEREF);
+ set => SetIntValueHelper(LdapOption.LDAP_OPT_DEREF, (int)value);
}
internal bool FQDN
@@ -726,37 +559,41 @@ namespace System.DirectoryServices.Protocols
public void FastConcurrentBind()
{
- if (_connection.disposed)
+ if (_connection._disposed)
+ {
throw new ObjectDisposedException(GetType().Name);
+ }
- int inValue = 1;
- // bump up the protocol version
+
+ // Bump up the protocol version
ProtocolVersion = 3;
- // do the fast concurrent bind
- int error = Wldap32.ldap_set_option_int(_connection.ldapHandle, LdapOption.LDAP_OPT_FAST_CONCURRENT_BIND, ref inValue);
- //we only throw PlatformNotSupportedException when we get parameter error and os is win2k3 below which does not support fast concurrent bind
+
+ // Do the fast concurrent bind.
+ int inValue = 1;
+ int error = Wldap32.ldap_set_option_int(_connection._ldapHandle, LdapOption.LDAP_OPT_FAST_CONCURRENT_BIND, ref inValue);
ErrorChecking.CheckAndSetLdapError(error);
}
public unsafe void StartTransportLayerSecurity(DirectoryControlCollection controls)
{
- IntPtr serverControlArray = (IntPtr)0;
+ IntPtr serverControlArray = IntPtr.Zero;
LdapControl[] managedServerControls = null;
- IntPtr clientControlArray = (IntPtr)0;
+ IntPtr clientControlArray = IntPtr.Zero;
LdapControl[] managedClientControls = null;
- IntPtr ldapResult = (IntPtr)0;
- IntPtr referral = (IntPtr)0;
+ IntPtr ldapResult = IntPtr.Zero;
+ IntPtr referral = IntPtr.Zero;
int serverError = 0;
Uri[] responseReferral = null;
- if (_connection.disposed)
+ if (_connection._disposed)
+ {
throw new ObjectDisposedException(GetType().Name);
+ }
try
{
- IntPtr controlPtr = (IntPtr)0;
- IntPtr tempPtr = (IntPtr)0;
+ IntPtr tempPtr = IntPtr.Zero;
// build server control
managedServerControls = _connection.BuildControlArray(controls, true);
@@ -766,67 +603,66 @@ namespace System.DirectoryServices.Protocols
serverControlArray = Utility.AllocHGlobalIntPtrArray(managedServerControls.Length + 1);
for (int i = 0; i < managedServerControls.Length; i++)
{
- controlPtr = Marshal.AllocHGlobal(structSize);
+ IntPtr controlPtr = Marshal.AllocHGlobal(structSize);
Marshal.StructureToPtr(managedServerControls[i], controlPtr, false);
tempPtr = (IntPtr)((long)serverControlArray + IntPtr.Size * i);
Marshal.WriteIntPtr(tempPtr, controlPtr);
}
tempPtr = (IntPtr)((long)serverControlArray + IntPtr.Size * managedServerControls.Length);
- Marshal.WriteIntPtr(tempPtr, (IntPtr)0);
+ Marshal.WriteIntPtr(tempPtr, IntPtr.Zero);
}
- // build client control
+ // Build client control.
managedClientControls = _connection.BuildControlArray(controls, false);
if (managedClientControls != null)
{
clientControlArray = Utility.AllocHGlobalIntPtrArray(managedClientControls.Length + 1);
for (int i = 0; i < managedClientControls.Length; i++)
{
- controlPtr = Marshal.AllocHGlobal(structSize);
+ IntPtr controlPtr = Marshal.AllocHGlobal(structSize);
Marshal.StructureToPtr(managedClientControls[i], controlPtr, false);
tempPtr = (IntPtr)((long)clientControlArray + IntPtr.Size * i);
Marshal.WriteIntPtr(tempPtr, controlPtr);
}
+
tempPtr = (IntPtr)((long)clientControlArray + IntPtr.Size * managedClientControls.Length);
- Marshal.WriteIntPtr(tempPtr, (IntPtr)0);
+ Marshal.WriteIntPtr(tempPtr, IntPtr.Zero);
}
- int error = Wldap32.ldap_start_tls(_connection.ldapHandle, ref serverError, ref ldapResult, serverControlArray, clientControlArray);
- if (ldapResult != (IntPtr)0)
+ int error = Wldap32.ldap_start_tls(_connection._ldapHandle, ref serverError, ref ldapResult, serverControlArray, clientControlArray);
+ if (ldapResult != IntPtr.Zero)
{
- // parsing the referral
- int resulterror = Wldap32.ldap_parse_result_referral(_connection.ldapHandle, ldapResult, (IntPtr)0, (IntPtr)0, (IntPtr)0, ref referral, (IntPtr)0, 0 /* not free it */);
- if (resulterror == 0)
+ // Parse the referral.
+ int resultError = Wldap32.ldap_parse_result_referral(_connection._ldapHandle, ldapResult, IntPtr.Zero, IntPtr.Zero, IntPtr.Zero, ref referral, IntPtr.Zero, 0 /* not free it */);
+ if (resultError == 0 && referral != IntPtr.Zero)
{
- // parsing referral
- if (referral != (IntPtr)0)
+ char** referralPtr = (char**)referral;
+ char* singleReferral = referralPtr[0];
+ int i = 0;
+ ArrayList referralList = new ArrayList();
+ while (singleReferral != null)
{
- char** referralPtr = (char**)referral;
- char* singleReferral = referralPtr[0];
- int i = 0;
- ArrayList referralList = new ArrayList();
- while (singleReferral != null)
- {
- string s = Marshal.PtrToStringUni((IntPtr)singleReferral);
- referralList.Add(s);
+ string s = Marshal.PtrToStringUni((IntPtr)singleReferral);
+ referralList.Add(s);
- i++;
- singleReferral = referralPtr[i];
- }
+ i++;
+ singleReferral = referralPtr[i];
+ }
- // free heap memory
- if (referral != (IntPtr)0)
- {
- Wldap32.ldap_value_free(referral);
- referral = (IntPtr)0;
- }
+ // Free heap memory.
+ if (referral != IntPtr.Zero)
+ {
+ Wldap32.ldap_value_free(referral);
+ referral = IntPtr.Zero;
+ }
- if (referralList.Count > 0)
+ if (referralList.Count > 0)
+ {
+ responseReferral = new Uri[referralList.Count];
+ for (int j = 0; j < referralList.Count; j++)
{
- responseReferral = new Uri[referralList.Count];
- for (int j = 0; j < referralList.Count; j++)
- responseReferral[j] = new Uri((string)referralList[j]);
+ responseReferral[j] = new Uri((string)referralList[j]);
}
}
}
@@ -834,36 +670,39 @@ namespace System.DirectoryServices.Protocols
if (error != (int)ResultCode.Success)
{
- string errorMessage = String.Format(CultureInfo.CurrentCulture, SR.DefaultLdapError);
if (Utility.IsResultCode((ResultCode)error))
{
- //If the server failed request for whatever reason, the ldap_start_tls returns LDAP_OTHER
+ // If the server failed request for whatever reason, the ldap_start_tls returns LDAP_OTHER
// and the ServerReturnValue will contain the error code from the server.
if (error == (int)ResultCode.Other)
+ {
error = serverError;
+ }
- errorMessage = OperationErrorMappings.MapResultCode(error);
+ string errorMessage = OperationErrorMappings.MapResultCode(error);
ExtendedResponse response = new ExtendedResponse(null, null, (ResultCode)error, errorMessage, responseReferral);
response.ResponseName = "1.3.6.1.4.1.1466.20037";
throw new TlsOperationException(response);
}
else if (Utility.IsLdapError((LdapError)error))
{
- errorMessage = LdapErrorMappings.MapResultCode(error);
+ string errorMessage = LdapErrorMappings.MapResultCode(error);
throw new LdapException(error, errorMessage);
}
}
}
finally
{
- if (serverControlArray != (IntPtr)0)
+ if (serverControlArray != IntPtr.Zero)
{
- //release the memory from the heap
+ // Release the memory from the heap.
for (int i = 0; i < managedServerControls.Length; i++)
{
IntPtr tempPtr = Marshal.ReadIntPtr(serverControlArray, IntPtr.Size * i);
- if (tempPtr != (IntPtr)0)
+ if (tempPtr != IntPtr.Zero)
+ {
Marshal.FreeHGlobal(tempPtr);
+ }
}
Marshal.FreeHGlobal(serverControlArray);
}
@@ -872,26 +711,33 @@ namespace System.DirectoryServices.Protocols
{
for (int i = 0; i < managedServerControls.Length; i++)
{
- if (managedServerControls[i].ldctl_oid != (IntPtr)0)
+ if (managedServerControls[i].ldctl_oid != IntPtr.Zero)
+ {
Marshal.FreeHGlobal(managedServerControls[i].ldctl_oid);
+ }
if (managedServerControls[i].ldctl_value != null)
{
- if (managedServerControls[i].ldctl_value.bv_val != (IntPtr)0)
+ if (managedServerControls[i].ldctl_value.bv_val != IntPtr.Zero)
+ {
Marshal.FreeHGlobal(managedServerControls[i].ldctl_value.bv_val);
+ }
}
}
}
- if (clientControlArray != (IntPtr)0)
+ if (clientControlArray != IntPtr.Zero)
{
- // release the memor from the heap
+ // Release the memor from the heap.
for (int i = 0; i < managedClientControls.Length; i++)
{
IntPtr tempPtr = Marshal.ReadIntPtr(clientControlArray, IntPtr.Size * i);
- if (tempPtr != (IntPtr)0)
+ if (tempPtr != IntPtr.Zero)
+ {
Marshal.FreeHGlobal(tempPtr);
+ }
}
+
Marshal.FreeHGlobal(clientControlArray);
}
@@ -899,81 +745,100 @@ namespace System.DirectoryServices.Protocols
{
for (int i = 0; i < managedClientControls.Length; i++)
{
- if (managedClientControls[i].ldctl_oid != (IntPtr)0)
+ if (managedClientControls[i].ldctl_oid != IntPtr.Zero)
+ {
Marshal.FreeHGlobal(managedClientControls[i].ldctl_oid);
+ }
if (managedClientControls[i].ldctl_value != null)
{
- if (managedClientControls[i].ldctl_value.bv_val != (IntPtr)0)
+ if (managedClientControls[i].ldctl_value.bv_val != IntPtr.Zero)
Marshal.FreeHGlobal(managedClientControls[i].ldctl_value.bv_val);
}
}
}
- if (referral != (IntPtr)0)
+ if (referral != IntPtr.Zero)
+ {
Wldap32.ldap_value_free(referral);
+ }
}
}
public void StopTransportLayerSecurity()
{
- if (_connection.disposed)
+ if (_connection._disposed)
+ {
throw new ObjectDisposedException(GetType().Name);
+ }
- byte result = Wldap32.ldap_stop_tls(_connection.ldapHandle);
+ byte result = Wldap32.ldap_stop_tls(_connection._ldapHandle);
if (result == 0)
- // caller needs to close this ldap connection
- throw new TlsOperationException(null, String.Format(CultureInfo.CurrentCulture, SR.TLSStopFailure));
+ {
+ throw new TlsOperationException(null, SR.TLSStopFailure);
+ }
}
private int GetIntValueHelper(LdapOption option)
{
- if (_connection.disposed)
+ if (_connection._disposed)
+ {
throw new ObjectDisposedException(GetType().Name);
+ }
int outValue = 0;
- int error = Wldap32.ldap_get_option_int(_connection.ldapHandle, option, ref outValue);
-
+ int error = Wldap32.ldap_get_option_int(_connection._ldapHandle, option, ref outValue);
ErrorChecking.CheckAndSetLdapError(error);
+
return outValue;
}
private void SetIntValueHelper(LdapOption option, int value)
{
- if (_connection.disposed)
+ if (_connection._disposed)
+ {
throw new ObjectDisposedException(GetType().Name);
+ }
int temp = value;
- int error = Wldap32.ldap_set_option_int(_connection.ldapHandle, option, ref temp);
+ int error = Wldap32.ldap_set_option_int(_connection._ldapHandle, option, ref temp);
ErrorChecking.CheckAndSetLdapError(error);
}
private string GetStringValueHelper(LdapOption option, bool releasePtr)
{
- if (_connection.disposed)
+ if (_connection._disposed)
+ {
throw new ObjectDisposedException(GetType().Name);
+ }
IntPtr outValue = new IntPtr(0);
- int error = Wldap32.ldap_get_option_ptr(_connection.ldapHandle, option, ref outValue);
+ int error = Wldap32.ldap_get_option_ptr(_connection._ldapHandle, option, ref outValue);
ErrorChecking.CheckAndSetLdapError(error);
- string s = null;
- if (outValue != (IntPtr)0)
- s = Marshal.PtrToStringUni(outValue);
+ string stringValue = null;
+ if (outValue != IntPtr.Zero)
+ {
+ stringValue = Marshal.PtrToStringUni(outValue);
+ }
if (releasePtr)
+ {
Wldap32.ldap_memfree(outValue);
+ }
- return s;
+ return stringValue;
}
private void SetStringValueHelper(LdapOption option, string value)
{
- if (_connection.disposed)
+ if (_connection._disposed)
+ {
throw new ObjectDisposedException(GetType().Name);
+ }
- IntPtr inValue = new IntPtr(0);
+ IntPtr inValue = IntPtr.Zero;
if (value != null)
{
inValue = Marshal.StringToHGlobalUni(value);
@@ -981,25 +846,29 @@ namespace System.DirectoryServices.Protocols
try
{
- int error = Wldap32.ldap_set_option_ptr(_connection.ldapHandle, option, ref inValue);
+ int error = Wldap32.ldap_set_option_ptr(_connection._ldapHandle, option, ref inValue);
ErrorChecking.CheckAndSetLdapError(error);
}
finally
{
- if (inValue != (IntPtr)0)
+ if (inValue != IntPtr.Zero)
+ {
Marshal.FreeHGlobal(inValue);
+ }
}
}
private void ProcessCallBackRoutine(ReferralCallback tempCallback)
{
- LdapReferralCallback value = new LdapReferralCallback();
- value.sizeofcallback = Marshal.SizeOf(typeof(LdapReferralCallback));
- value.query = tempCallback.QueryForConnection == null ? null : _queryDelegate;
- value.notify = tempCallback.NotifyNewConnection == null ? null : _notifiyDelegate;
- value.dereference = tempCallback.DereferenceConnection == null ? null : _dereferenceDelegate;
+ LdapReferralCallback value = new LdapReferralCallback()
+ {
+ sizeofcallback = Marshal.SizeOf(typeof(LdapReferralCallback)),
+ query = tempCallback.QueryForConnection == null ? null : _queryDelegate,
+ notify = tempCallback.NotifyNewConnection == null ? null : _notifiyDelegate,
+ dereference = tempCallback.DereferenceConnection == null ? null : _dereferenceDelegate
+ };
- int error = Wldap32.ldap_set_option_referral(_connection.ldapHandle, LdapOption.LDAP_OPT_REFERRAL_CALLBACK, ref value);
+ int error = Wldap32.ldap_set_option_referral(_connection._ldapHandle, LdapOption.LDAP_OPT_REFERRAL_CALLBACK, ref value);
ErrorChecking.CheckAndSetLdapError(error);
}
@@ -1008,138 +877,150 @@ namespace System.DirectoryServices.Protocols
ConnectionToUse = IntPtr.Zero;
string NewDN = null;
- // user must have registered callback function
+ // The user must have registered callback function.
Debug.Assert(_callbackRoutine.QueryForConnection != null);
- // user registers the QUERYFORCONNECTION callback
+ // The user registers the QUERYFORCONNECTION callback.
if (_callbackRoutine.QueryForConnection != null)
{
- if (NewDNPtr != (IntPtr)0)
+ if (NewDNPtr != IntPtr.Zero)
+ {
NewDN = Marshal.PtrToStringUni(NewDNPtr);
- StringBuilder target = new StringBuilder();
+ }
+
+ var target = new StringBuilder();
target.Append(HostName);
target.Append(":");
target.Append(PortNumber);
- LdapDirectoryIdentifier identifier = new LdapDirectoryIdentifier(target.ToString());
+ var identifier = new LdapDirectoryIdentifier(target.ToString());
+
NetworkCredential cred = ProcessSecAuthIdentity(SecAuthIdentity);
LdapConnection tempReferralConnection = null;
- WeakReference reference = null;
- // if referrafromconnection handle is valid
- if (ReferralFromConnection != (IntPtr)0)
+ // If ReferralFromConnection handle is valid.
+ if (ReferralFromConnection != IntPtr.Zero)
{
- lock (LdapConnection.objectLock)
+ lock (LdapConnection.s_objectLock)
{
- //make sure first whether we have saved it in the handle table before
- reference = (WeakReference)(LdapConnection.handleTable[ReferralFromConnection]);
+ // Make sure first whether we have saved it in the handle table before
+ WeakReference reference = (WeakReference)(LdapConnection.s_handleTable[ReferralFromConnection]);
if (reference != null && reference.IsAlive)
{
- // save this before and object has not been garbage collected yet.
+ // Save this before and object has not been garbage collected yet.
tempReferralConnection = (LdapConnection)reference.Target;
}
else
{
if (reference != null)
{
- // connection has been garbage collected, we need to remove this one
- LdapConnection.handleTable.Remove(ReferralFromConnection);
+ // Connection has been garbage collected, we need to remove this one.
+ LdapConnection.s_handleTable.Remove(ReferralFromConnection);
}
- // we don't have it yet, construct a new one
- tempReferralConnection = new LdapConnection(((LdapDirectoryIdentifier)(_connection.Directory)), _connection.GetCredential(), _connection.AuthType, ReferralFromConnection);
- // save it to the handle table
- LdapConnection.handleTable.Add(ReferralFromConnection, new WeakReference(tempReferralConnection));
+ // We don't have it yet, construct a new one.
+ tempReferralConnection = new LdapConnection(((LdapDirectoryIdentifier)(_connection.Directory)), _connection.GetCredential(), _connection.AuthType, ReferralFromConnection);
+
+ // Save it to the handle table.
+ LdapConnection.s_handleTable.Add(ReferralFromConnection, new WeakReference(tempReferralConnection));
}
}
}
- long tokenValue = (long)((uint)CurrentUserToken.LowPart + (((long)CurrentUserToken.HighPart) << 32));
+ long tokenValue = (uint)CurrentUserToken.LowPart + (((long)CurrentUserToken.HighPart) << 32);
LdapConnection con = _callbackRoutine.QueryForConnection(_connection, tempReferralConnection, NewDN, identifier, cred, tokenValue);
- if (null != con && null != con.ldapHandle && !con.ldapHandle.IsInvalid)
+ if (con != null && con._ldapHandle != null && !con._ldapHandle.IsInvalid)
{
bool success = AddLdapHandleRef(con);
if (success)
{
- ConnectionToUse = con.ldapHandle.DangerousGetHandle();
+ ConnectionToUse = con._ldapHandle.DangerousGetHandle();
}
}
+
return 0;
}
- else
- {
- // user does not take ownership of the connection
- return 1;
- }
+
+ // The user does not take ownership of the connection.
+ return 1;
}
- private bool ProcessNotifyConnection(IntPtr PrimaryConnection, IntPtr ReferralFromConnection, IntPtr NewDNPtr, string HostName, IntPtr NewConnection, int PortNumber, SEC_WINNT_AUTH_IDENTITY_EX SecAuthIdentity, Luid CurrentUser, int ErrorCodeFromBind)
+ private bool ProcessNotifyConnection(IntPtr primaryConnection, IntPtr referralFromConnection, IntPtr newDNPtr, string hostName, IntPtr newConnection, int portNumber, SEC_WINNT_AUTH_IDENTITY_EX SecAuthIdentity, Luid currentUser, int errorCodeFromBind)
{
- string NewDN = null;
- if (NewConnection != (IntPtr)0 && _callbackRoutine.NotifyNewConnection != null)
+ if (newConnection != IntPtr.Zero && _callbackRoutine.NotifyNewConnection != null)
{
- if (NewDNPtr != (IntPtr)0)
- NewDN = Marshal.PtrToStringUni(NewDNPtr);
- StringBuilder target = new StringBuilder();
- target.Append(HostName);
+ string newDN = null;
+ if (newDNPtr != IntPtr.Zero)
+ {
+ newDN = Marshal.PtrToStringUni(newDNPtr);
+ }
+
+ var target = new StringBuilder();
+ target.Append(hostName);
target.Append(":");
- target.Append(PortNumber);
- LdapDirectoryIdentifier identifier = new LdapDirectoryIdentifier(target.ToString());
+ target.Append(portNumber);
+ var identifier = new LdapDirectoryIdentifier(target.ToString());
+
NetworkCredential cred = ProcessSecAuthIdentity(SecAuthIdentity);
LdapConnection tempNewConnection = null;
LdapConnection tempReferralConnection = null;
- WeakReference reference = null;
- lock (LdapConnection.objectLock)
+ lock (LdapConnection.s_objectLock)
{
- // if referrafromconnection handle is valid
- if (ReferralFromConnection != (IntPtr)0)
+ // Check whether the referralFromConnection handle is valid.
+ if (referralFromConnection != IntPtr.Zero)
{
- //check whether we have save it in the handle table before
- reference = (WeakReference)(LdapConnection.handleTable[ReferralFromConnection]);
- if (reference != null && reference.IsAlive && null != ((LdapConnection)reference.Target).ldapHandle)
+ // Check whether we have save it in the handle table before.
+ WeakReference reference = (WeakReference)(LdapConnection.s_handleTable[referralFromConnection]);
+ if (reference != null && reference.IsAlive && null != ((LdapConnection)reference.Target)._ldapHandle)
{
- // save this before and object has not been garbage collected yet.
+ // Save this before and object has not been garbage collected yet.
tempReferralConnection = (LdapConnection)reference.Target;
}
else
{
- // connection has been garbage collected, we need to remove this one
+ // Connection has been garbage collected, we need to remove this one.
if (reference != null)
- LdapConnection.handleTable.Remove(ReferralFromConnection);
+ {
+ LdapConnection.s_handleTable.Remove(referralFromConnection);
+ }
- // we don't have it yet, construct a new one
- tempReferralConnection = new LdapConnection(((LdapDirectoryIdentifier)(_connection.Directory)), _connection.GetCredential(), _connection.AuthType, ReferralFromConnection);
- // save it to the handle table
- LdapConnection.handleTable.Add(ReferralFromConnection, new WeakReference(tempReferralConnection));
+ // We don't have it yet, construct a new one.
+ tempReferralConnection = new LdapConnection(((LdapDirectoryIdentifier)(_connection.Directory)), _connection.GetCredential(), _connection.AuthType, referralFromConnection);
+
+ // Save it to the handle table.
+ LdapConnection.s_handleTable.Add(referralFromConnection, new WeakReference(tempReferralConnection));
}
}
- if (NewConnection != (IntPtr)0)
+ if (newConnection != IntPtr.Zero)
{
- //check whether we have save it in the handle table before
- reference = (WeakReference)(LdapConnection.handleTable[NewConnection]);
- if (reference != null && reference.IsAlive && null != ((LdapConnection)reference.Target).ldapHandle)
+ // Check whether we have save it in the handle table before.
+ WeakReference reference = (WeakReference)(LdapConnection.s_handleTable[newConnection]);
+ if (reference != null && reference.IsAlive && null != ((LdapConnection)reference.Target)._ldapHandle)
{
- // save this before and object has not been garbage collected yet.
+ // Save this before and object has not been garbage collected yet.
tempNewConnection = (LdapConnection)reference.Target;
}
else
{
- // connection has been garbage collected, we need to remove this one
+ // Connection has been garbage collected, we need to remove this one.
if (reference != null)
- LdapConnection.handleTable.Remove(NewConnection);
+ {
+ LdapConnection.s_handleTable.Remove(newConnection);
+ }
- // we don't have it yet, construct a new one
- tempNewConnection = new LdapConnection(identifier, cred, _connection.AuthType, NewConnection);
- // save it to the handle table
- LdapConnection.handleTable.Add(NewConnection, new WeakReference(tempNewConnection));
+ // We don't have it yet, construct a new one.
+ tempNewConnection = new LdapConnection(identifier, cred, _connection.AuthType, newConnection);
+
+ // Save it to the handle table.
+ LdapConnection.s_handleTable.Add(newConnection, new WeakReference(tempNewConnection));
}
}
}
- long tokenValue = (long)((uint)CurrentUser.LowPart + (((long)CurrentUser.HighPart) << 32));
- bool value = _callbackRoutine.NotifyNewConnection(_connection, tempReferralConnection, NewDN, identifier, tempNewConnection, cred, tokenValue, ErrorCodeFromBind);
+ long tokenValue = (uint)currentUser.LowPart + (((long)currentUser.HighPart) << 32);
+ bool value = _callbackRoutine.NotifyNewConnection(_connection, tempReferralConnection, newDN, identifier, tempNewConnection, cred, tokenValue, errorCodeFromBind);
if (value)
{
@@ -1149,35 +1030,37 @@ namespace System.DirectoryServices.Protocols
tempNewConnection.NeedDispose = true;
}
}
+
return value;
}
- else
- {
- return false;
- }
+
+ return false;
}
private int ProcessDereferenceConnection(IntPtr PrimaryConnection, IntPtr ConnectionToDereference)
{
- if (ConnectionToDereference != (IntPtr)0 && _callbackRoutine.DereferenceConnection != null)
+ if (ConnectionToDereference != IntPtr.Zero && _callbackRoutine.DereferenceConnection != null)
{
LdapConnection dereferenceConnection = null;
WeakReference reference = null;
// in most cases it should be in our table
- lock (LdapConnection.objectLock)
+ lock (LdapConnection.s_objectLock)
{
- reference = (WeakReference)(LdapConnection.handleTable[ConnectionToDereference]);
+ reference = (WeakReference)(LdapConnection.s_handleTable[ConnectionToDereference]);
}
// not been added to the table before or it is garbage collected, we need to construct it
if (reference == null || !reference.IsAlive)
+ {
dereferenceConnection = new LdapConnection(((LdapDirectoryIdentifier)(_connection.Directory)), _connection.GetCredential(), _connection.AuthType, ConnectionToDereference);
+ }
else
{
dereferenceConnection = (LdapConnection)reference.Target;
ReleaseLdapHandleRef(dereferenceConnection);
}
+
_callbackRoutine.DereferenceConnection(_connection, dereferenceConnection);
// there is no need to remove the connection object from the handle table, as it will be removed automatically when
@@ -1190,37 +1073,39 @@ namespace System.DirectoryServices.Protocols
private NetworkCredential ProcessSecAuthIdentity(SEC_WINNT_AUTH_IDENTITY_EX SecAuthIdentit)
{
if (SecAuthIdentit == null)
- return new NetworkCredential();
- else
{
- string user = SecAuthIdentit.user;
- string domain = SecAuthIdentit.domain;
- string password = SecAuthIdentit.password;
-
- return new NetworkCredential(user, password, domain);
+ return new NetworkCredential();
}
+
+ string user = SecAuthIdentit.user;
+ string domain = SecAuthIdentit.domain;
+ string password = SecAuthIdentit.password;
+
+ return new NetworkCredential(user, password, domain);
}
- private bool ProcessServerCertificate(IntPtr Connection, IntPtr pServerCert)
+ private bool ProcessServerCertificate(IntPtr connection, IntPtr serverCert)
{
- // if callback is not specified by user, it means server certificate is accepted
+ // If callback is not specified by user, it means the server certificate is accepted.
bool value = true;
if (_serverCertificateDelegate != null)
{
- IntPtr certPtr = (IntPtr)0;
+ IntPtr certPtr = IntPtr.Zero;
X509Certificate certificate = null;
try
{
- Debug.Assert(pServerCert != (IntPtr)0);
- certPtr = Marshal.ReadIntPtr(pServerCert);
+ Debug.Assert(serverCert != IntPtr.Zero);
+ certPtr = Marshal.ReadIntPtr(serverCert);
certificate = new X509Certificate(certPtr);
}
finally
{
Wldap32.CertFreeCRLContext(certPtr);
}
+
value = _serverCertificateDelegate(_connection, certificate);
}
+
return value;
}
@@ -1228,28 +1113,29 @@ namespace System.DirectoryServices.Protocols
private static bool AddLdapHandleRef(LdapConnection ldapConnection)
{
bool success = false;
- if (null != ldapConnection && null != ldapConnection.ldapHandle && !ldapConnection.ldapHandle.IsInvalid)
+ if (ldapConnection != null && ldapConnection._ldapHandle != null && !ldapConnection._ldapHandle.IsInvalid)
{
RuntimeHelpers.PrepareConstrainedRegions();
try { }
finally
{
- ldapConnection.ldapHandle.DangerousAddRef(ref success);
+ ldapConnection._ldapHandle.DangerousAddRef(ref success);
}
}
+
return success;
}
[PermissionSet(SecurityAction.Assert, Unrestricted = true)]
private static void ReleaseLdapHandleRef(LdapConnection ldapConnection)
{
- if (null != ldapConnection && null != ldapConnection.ldapHandle && !ldapConnection.ldapHandle.IsInvalid)
+ if (ldapConnection != null && ldapConnection._ldapHandle != null && !ldapConnection._ldapHandle.IsInvalid)
{
RuntimeHelpers.PrepareConstrainedRegions();
try { }
finally
{
- ldapConnection.ldapHandle.DangerousRelease();
+ ldapConnection._ldapHandle.DangerousRelease();
}
}
}
diff --git a/src/System.DirectoryServices.Protocols/src/System/DirectoryServices/Protocols/ldap/SafeHandles.cs b/src/System.DirectoryServices.Protocols/src/System/DirectoryServices/Protocols/ldap/SafeHandles.cs
index 3771c40d38..c719d1afea 100644
--- a/src/System.DirectoryServices.Protocols/src/System/DirectoryServices/Protocols/ldap/SafeHandles.cs
+++ b/src/System.DirectoryServices.Protocols/src/System/DirectoryServices/Protocols/ldap/SafeHandles.cs
@@ -2,31 +2,31 @@
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
+using Microsoft.Win32.SafeHandles;
+using System.Runtime.InteropServices;
+using System.Security;
+
namespace System.DirectoryServices.Protocols
{
- using System;
- using Microsoft.Win32.SafeHandles;
- using System.Runtime.InteropServices;
- using System.Runtime.CompilerServices;
- using System.Runtime.ConstrainedExecution;
- using System.Diagnostics;
- using System.Security;
-
- [SuppressUnmanagedCodeSecurityAttribute()]
+ [SuppressUnmanagedCodeSecurity]
internal sealed class BerSafeHandle : SafeHandleZeroOrMinusOneIsInvalid
{
internal BerSafeHandle() : base(true)
{
SetHandle(Wldap32.ber_alloc(1));
- if (handle == (IntPtr)0)
+ if (handle == IntPtr.Zero)
+ {
throw new OutOfMemoryException();
+ }
}
internal BerSafeHandle(berval value) : base(true)
{
SetHandle(Wldap32.ber_init(value));
- if (handle == (IntPtr)0)
+ if (handle == IntPtr.Zero)
+ {
throw new BerConversionException();
+ }
}
override protected bool ReleaseHandle()
@@ -36,8 +36,8 @@ namespace System.DirectoryServices.Protocols
}
}
- [SuppressUnmanagedCodeSecurityAttribute()]
- sealed internal class HGlobalMemHandle : SafeHandleZeroOrMinusOneIsInvalid
+ [SuppressUnmanagedCodeSecurity]
+ internal sealed class HGlobalMemHandle : SafeHandleZeroOrMinusOneIsInvalid
{
internal HGlobalMemHandle(IntPtr value) : base(true)
{
@@ -51,15 +51,16 @@ namespace System.DirectoryServices.Protocols
}
}
- [SuppressUnmanagedCodeSecurityAttribute()]
- sealed internal class ConnectionHandle : SafeHandleZeroOrMinusOneIsInvalid
+ [SuppressUnmanagedCodeSecurity]
+ internal sealed class ConnectionHandle : SafeHandleZeroOrMinusOneIsInvalid
{
- internal bool needDispose = false;
+ internal bool _needDispose = false;
+
internal ConnectionHandle() : base(true)
{
SetHandle(Wldap32.ldap_init(null, 389));
- if (handle == (IntPtr)0)
+ if (handle == IntPtr.Zero)
{
int error = Wldap32.LdapGetLastError();
if (Utility.IsLdapError((LdapError)error))
@@ -68,15 +69,16 @@ namespace System.DirectoryServices.Protocols
throw new LdapException(error, errorMessage);
}
else
+ {
throw new LdapException(error);
+ }
}
}
- internal ConnectionHandle(IntPtr value, bool disposeHandle)
- : base(true)
+ internal ConnectionHandle(IntPtr value, bool disposeHandle) : base(true)
{
- needDispose = disposeHandle;
- if (value == (IntPtr)0)
+ _needDispose = disposeHandle;
+ if (value == IntPtr.Zero)
{
int error = Wldap32.LdapGetLastError();
if (Utility.IsLdapError((LdapError)error))
@@ -85,7 +87,9 @@ namespace System.DirectoryServices.Protocols
throw new LdapException(error, errorMessage);
}
else
+ {
throw new LdapException(error);
+ }
}
else
{
@@ -94,13 +98,14 @@ namespace System.DirectoryServices.Protocols
}
override protected bool ReleaseHandle()
{
- if (handle != (IntPtr)0)
+ if (handle != IntPtr.Zero)
{
- if (needDispose)
+ if (_needDispose)
{
Wldap32.ldap_unbind(handle);
}
- handle = (IntPtr)0;
+
+ handle = IntPtr.Zero;
}
return true;
}
diff --git a/src/System.DirectoryServices.Protocols/src/System/DirectoryServices/Protocols/ldap/Wldap32UnsafeMethods.cs b/src/System.DirectoryServices.Protocols/src/System/DirectoryServices/Protocols/ldap/Wldap32UnsafeMethods.cs
index 92994c19b7..088d51ae30 100644
--- a/src/System.DirectoryServices.Protocols/src/System/DirectoryServices/Protocols/ldap/Wldap32UnsafeMethods.cs
+++ b/src/System.DirectoryServices.Protocols/src/System/DirectoryServices/Protocols/ldap/Wldap32UnsafeMethods.cs
@@ -2,37 +2,19 @@
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
+using System.Runtime.InteropServices;
+using System.Security;
+
namespace System.DirectoryServices.Protocols
{
- using System;
- using System.Runtime.InteropServices;
- using System.Security;
-
[StructLayout(LayoutKind.Sequential, CharSet = CharSet.Unicode)]
internal class Luid
{
- internal int lowPart;
- internal int highPart;
-
- internal Luid()
- {
- }
-
- public int LowPart
- {
- get
- {
- return lowPart;
- }
- }
+ private int _lowPart;
+ private int _highPart;
- public int HighPart
- {
- get
- {
- return highPart;
- }
- }
+ public int LowPart => _lowPart;
+ public int HighPart => _highPart;
}
[StructLayout(LayoutKind.Sequential, CharSet = CharSet.Unicode)]
@@ -53,8 +35,6 @@ namespace System.DirectoryServices.Protocols
internal enum BindMethod : uint
{
- LDAP_AUTH_SIMPLE = 0x80,
- LDAP_AUTH_SASL = 0x83,
LDAP_AUTH_OTHERKIND = 0x86,
LDAP_AUTH_SICILY = LDAP_AUTH_OTHERKIND | 0x0200,
LDAP_AUTH_MSN = LDAP_AUTH_OTHERKIND | 0x0800,
@@ -109,7 +89,6 @@ namespace System.DirectoryServices.Protocols
internal enum ResultAll
{
- LDAP_MSG_ONE = 0,
LDAP_MSG_ALL = 1,
LDAP_MSG_RECEIVED = 2,
LDAP_MSG_POLLINGALL = 3
@@ -126,7 +105,7 @@ namespace System.DirectoryServices.Protocols
internal sealed class berval
{
public int bv_len = 0;
- public IntPtr bv_val = (IntPtr)0;
+ public IntPtr bv_val = IntPtr.Zero;
public berval() { }
}
@@ -135,21 +114,21 @@ namespace System.DirectoryServices.Protocols
internal sealed class SafeBerval
{
public int bv_len = 0;
- public IntPtr bv_val = (IntPtr)0;
-
- public SafeBerval() { }
+ public IntPtr bv_val = IntPtr.Zero;
~SafeBerval()
{
- if (bv_val != (IntPtr)0)
+ if (bv_val != IntPtr.Zero)
+ {
Marshal.FreeHGlobal(bv_val);
+ }
}
}
[StructLayout(LayoutKind.Sequential, CharSet = CharSet.Unicode)]
internal sealed class LdapControl
{
- public IntPtr ldctl_oid = (IntPtr)0;
+ public IntPtr ldctl_oid = IntPtr.Zero;
public berval ldctl_value = null;
public bool ldctl_iscritical = false;
@@ -183,237 +162,216 @@ namespace System.DirectoryServices.Protocols
internal sealed class LdapMod
{
public int type = 0;
- public IntPtr attribute = (IntPtr)0;
- public IntPtr values = (IntPtr)0;
+ public IntPtr attribute = IntPtr.Zero;
+ public IntPtr values = IntPtr.Zero;
- public LdapMod() { }
~LdapMod()
{
- if (attribute != (IntPtr)0)
+ if (attribute != IntPtr.Zero)
+ {
Marshal.FreeHGlobal(attribute);
+ }
- if (values != (IntPtr)0)
+ if (values != IntPtr.Zero)
+ {
Marshal.FreeHGlobal(values);
+ }
}
}
- [StructLayout(LayoutKind.Sequential, CharSet = CharSet.Unicode)]
- internal sealed class LdapVlvInfo
- {
- private int _version = 1;
- private int _beforeCount = 0;
- private int _afterCount = 0;
- private int _offset = 0;
- private int _count = 0;
- private IntPtr _attrvalue = (IntPtr)0;
- private IntPtr _context = (IntPtr)0;
- private IntPtr _extraData = (IntPtr)0;
-
- public LdapVlvInfo(int version, int before, int after, int offset, int count, IntPtr attribute, IntPtr context)
- {
- _version = version;
- _beforeCount = before;
- _afterCount = after;
- _offset = offset;
- _count = count;
- _attrvalue = attribute;
- _context = context;
- }
- }
-
- [
- SuppressUnmanagedCodeSecurityAttribute()
- ]
+ [SuppressUnmanagedCodeSecurity]
internal class Wldap32
{
+ private const string Wldap32dll = "wldap32.dll";
+
public const int SEC_WINNT_AUTH_IDENTITY_UNICODE = 0x2;
public const int SEC_WINNT_AUTH_IDENTITY_VERSION = 0x200;
public const string MICROSOFT_KERBEROS_NAME_W = "Kerberos";
- [DllImport("wldap32.dll", CallingConvention = CallingConvention.Cdecl, EntryPoint = "ldap_bind_sW", CharSet = CharSet.Unicode)]
+ [DllImport(Wldap32dll, CallingConvention = CallingConvention.Cdecl, EntryPoint = "ldap_bind_sW", CharSet = CharSet.Unicode)]
public static extern int ldap_bind_s([In]ConnectionHandle ldapHandle, string dn, SEC_WINNT_AUTH_IDENTITY_EX credentials, BindMethod method);
- [DllImport("wldap32.dll", CallingConvention = CallingConvention.Cdecl, EntryPoint = "ldap_initW", SetLastError = true, CharSet = CharSet.Unicode)]
+ [DllImport(Wldap32dll, CallingConvention = CallingConvention.Cdecl, EntryPoint = "ldap_initW", SetLastError = true, CharSet = CharSet.Unicode)]
public static extern IntPtr ldap_init(string hostName, int portNumber);
- [DllImport("wldap32.dll", CallingConvention = CallingConvention.Cdecl, ExactSpelling = true, EntryPoint = "ldap_connect", CharSet = CharSet.Unicode)]
+ [DllImport(Wldap32dll, CallingConvention = CallingConvention.Cdecl, ExactSpelling = true, EntryPoint = "ldap_connect", CharSet = CharSet.Unicode)]
public static extern int ldap_connect([In] ConnectionHandle ldapHandle, LDAP_TIMEVAL timeout);
- [DllImport("wldap32.dll", CallingConvention = CallingConvention.Cdecl, ExactSpelling = true, EntryPoint = "ldap_unbind", CharSet = CharSet.Unicode)]
+ [DllImport(Wldap32dll, CallingConvention = CallingConvention.Cdecl, ExactSpelling = true, EntryPoint = "ldap_unbind", CharSet = CharSet.Unicode)]
public static extern int ldap_unbind([In] IntPtr ldapHandle);
- [DllImport("wldap32.dll", CallingConvention = CallingConvention.Cdecl, EntryPoint = "ldap_get_optionW", CharSet = CharSet.Unicode)]
+ [DllImport(Wldap32dll, CallingConvention = CallingConvention.Cdecl, EntryPoint = "ldap_get_optionW", CharSet = CharSet.Unicode)]
public static extern int ldap_get_option_int([In] ConnectionHandle ldapHandle, [In] LdapOption option, ref int outValue);
- [DllImport("wldap32.dll", CallingConvention = CallingConvention.Cdecl, EntryPoint = "ldap_set_optionW", CharSet = CharSet.Unicode)]
+ [DllImport(Wldap32dll, CallingConvention = CallingConvention.Cdecl, EntryPoint = "ldap_set_optionW", CharSet = CharSet.Unicode)]
public static extern int ldap_set_option_int([In] ConnectionHandle ldapHandle, [In] LdapOption option, ref int inValue);
- [DllImport("wldap32.dll", CallingConvention = CallingConvention.Cdecl, EntryPoint = "ldap_get_optionW", CharSet = CharSet.Unicode)]
+ [DllImport(Wldap32dll, CallingConvention = CallingConvention.Cdecl, EntryPoint = "ldap_get_optionW", CharSet = CharSet.Unicode)]
public static extern int ldap_get_option_ptr([In] ConnectionHandle ldapHandle, [In] LdapOption option, ref IntPtr outValue);
- [DllImport("wldap32.dll", CallingConvention = CallingConvention.Cdecl, EntryPoint = "ldap_set_optionW", CharSet = CharSet.Unicode)]
+ [DllImport(Wldap32dll, CallingConvention = CallingConvention.Cdecl, EntryPoint = "ldap_set_optionW", CharSet = CharSet.Unicode)]
public static extern int ldap_set_option_ptr([In] ConnectionHandle ldapHandle, [In] LdapOption option, ref IntPtr inValue);
- [DllImport("wldap32.dll", CallingConvention = CallingConvention.Cdecl, EntryPoint = "ldap_get_optionW", CharSet = CharSet.Unicode)]
+ [DllImport(Wldap32dll, CallingConvention = CallingConvention.Cdecl, EntryPoint = "ldap_get_optionW", CharSet = CharSet.Unicode)]
public static extern int ldap_get_option_sechandle([In] ConnectionHandle ldapHandle, [In] LdapOption option, ref SecurityHandle outValue);
- [DllImport("wldap32.dll", CallingConvention = CallingConvention.Cdecl, EntryPoint = "ldap_get_optionW", CharSet = CharSet.Unicode)]
+ [DllImport(Wldap32dll, CallingConvention = CallingConvention.Cdecl, EntryPoint = "ldap_get_optionW", CharSet = CharSet.Unicode)]
public static extern int ldap_get_option_secInfo([In] ConnectionHandle ldapHandle, [In] LdapOption option, [In, Out] SecurityPackageContextConnectionInformation outValue);
- [DllImport("wldap32.dll", CallingConvention = CallingConvention.Cdecl, EntryPoint = "ldap_set_optionW", CharSet = CharSet.Unicode)]
+ [DllImport(Wldap32dll, CallingConvention = CallingConvention.Cdecl, EntryPoint = "ldap_set_optionW", CharSet = CharSet.Unicode)]
public static extern int ldap_set_option_referral([In] ConnectionHandle ldapHandle, [In] LdapOption option, ref LdapReferralCallback outValue);
- [DllImport("wldap32.dll", CallingConvention = CallingConvention.Cdecl, EntryPoint = "ldap_set_optionW", CharSet = CharSet.Unicode)]
+ [DllImport(Wldap32dll, CallingConvention = CallingConvention.Cdecl, EntryPoint = "ldap_set_optionW", CharSet = CharSet.Unicode)]
public static extern int ldap_set_option_clientcert([In] ConnectionHandle ldapHandle, [In] LdapOption option, QUERYCLIENTCERT outValue);
- [DllImport("wldap32.dll", CallingConvention = CallingConvention.Cdecl, EntryPoint = "ldap_set_optionW", CharSet = CharSet.Unicode)]
+ [DllImport(Wldap32dll, CallingConvention = CallingConvention.Cdecl, EntryPoint = "ldap_set_optionW", CharSet = CharSet.Unicode)]
public static extern int ldap_set_option_servercert([In] ConnectionHandle ldapHandle, [In] LdapOption option, VERIFYSERVERCERT outValue);
- [DllImport("wldap32.dll", CallingConvention = CallingConvention.Cdecl, EntryPoint = "LdapGetLastError")]
+ [DllImport(Wldap32dll, CallingConvention = CallingConvention.Cdecl, EntryPoint = "LdapGetLastError")]
public static extern int LdapGetLastError();
- [DllImport("wldap32.dll", CallingConvention = CallingConvention.Cdecl, EntryPoint = "cldap_openW", SetLastError = true, CharSet = CharSet.Unicode)]
+ [DllImport(Wldap32dll, CallingConvention = CallingConvention.Cdecl, EntryPoint = "cldap_openW", SetLastError = true, CharSet = CharSet.Unicode)]
public static extern IntPtr cldap_open(string hostName, int portNumber);
- [DllImport("wldap32.dll", CallingConvention = CallingConvention.Cdecl, EntryPoint = "ldap_simple_bind_sW", CharSet = CharSet.Unicode)]
+ [DllImport(Wldap32dll, CallingConvention = CallingConvention.Cdecl, EntryPoint = "ldap_simple_bind_sW", CharSet = CharSet.Unicode)]
public static extern int ldap_simple_bind_s([In] ConnectionHandle ldapHandle, string distinguishedName, string password);
- [DllImport("wldap32.dll", CallingConvention = CallingConvention.Cdecl, EntryPoint = "ldap_delete_extW", CharSet = CharSet.Unicode)]
+ [DllImport(Wldap32dll, CallingConvention = CallingConvention.Cdecl, EntryPoint = "ldap_delete_extW", CharSet = CharSet.Unicode)]
public static extern int ldap_delete_ext([In] ConnectionHandle ldapHandle, string dn, IntPtr servercontrol, IntPtr clientcontrol, ref int messageNumber);
- [DllImport("wldap32.dll", CallingConvention = CallingConvention.Cdecl, EntryPoint = "ldap_result", SetLastError = true, CharSet = CharSet.Unicode)]
+ [DllImport(Wldap32dll, CallingConvention = CallingConvention.Cdecl, EntryPoint = "ldap_result", SetLastError = true, CharSet = CharSet.Unicode)]
public static extern int ldap_result([In] ConnectionHandle ldapHandle, int messageId, int all, LDAP_TIMEVAL timeout, ref IntPtr Mesage);
- [DllImport("wldap32.dll", CallingConvention = CallingConvention.Cdecl, EntryPoint = "ldap_parse_resultW", CharSet = CharSet.Unicode)]
+ [DllImport(Wldap32dll, CallingConvention = CallingConvention.Cdecl, EntryPoint = "ldap_parse_resultW", CharSet = CharSet.Unicode)]
public static extern int ldap_parse_result([In] ConnectionHandle ldapHandle, [In] IntPtr result, ref int serverError, ref IntPtr dn, ref IntPtr message, ref IntPtr referral, ref IntPtr control, byte freeIt);
- [DllImport("wldap32.dll", CallingConvention = CallingConvention.Cdecl, EntryPoint = "ldap_parse_resultW", CharSet = CharSet.Unicode)]
+ [DllImport(Wldap32dll, CallingConvention = CallingConvention.Cdecl, EntryPoint = "ldap_parse_resultW", CharSet = CharSet.Unicode)]
public static extern int ldap_parse_result_referral([In] ConnectionHandle ldapHandle, [In] IntPtr result, IntPtr serverError, IntPtr dn, IntPtr message, ref IntPtr referral, IntPtr control, byte freeIt);
- [DllImport("wldap32.dll", CallingConvention = CallingConvention.Cdecl, EntryPoint = "ldap_memfreeW", CharSet = CharSet.Unicode)]
+ [DllImport(Wldap32dll, CallingConvention = CallingConvention.Cdecl, EntryPoint = "ldap_memfreeW", CharSet = CharSet.Unicode)]
public static extern void ldap_memfree([In] IntPtr value);
- [DllImport("wldap32.dll", CallingConvention = CallingConvention.Cdecl, EntryPoint = "ldap_value_freeW", CharSet = CharSet.Unicode)]
+ [DllImport(Wldap32dll, CallingConvention = CallingConvention.Cdecl, EntryPoint = "ldap_value_freeW", CharSet = CharSet.Unicode)]
public static extern int ldap_value_free([In] IntPtr value);
- [DllImport("wldap32.dll", CallingConvention = CallingConvention.Cdecl, EntryPoint = "ldap_controls_freeW", CharSet = CharSet.Unicode)]
+ [DllImport(Wldap32dll, CallingConvention = CallingConvention.Cdecl, EntryPoint = "ldap_controls_freeW", CharSet = CharSet.Unicode)]
public static extern int ldap_controls_free([In] IntPtr value);
- [DllImport("wldap32.dll", CallingConvention = CallingConvention.Cdecl, EntryPoint = "ldap_abandon", CharSet = CharSet.Unicode)]
+ [DllImport(Wldap32dll, CallingConvention = CallingConvention.Cdecl, EntryPoint = "ldap_abandon", CharSet = CharSet.Unicode)]
public static extern int ldap_abandon([In] ConnectionHandle ldapHandle, [In] int messagId);
- [DllImport("wldap32.dll", CallingConvention = CallingConvention.Cdecl, EntryPoint = "ldap_start_tls_sW", CharSet = CharSet.Unicode)]
+ [DllImport(Wldap32dll, CallingConvention = CallingConvention.Cdecl, EntryPoint = "ldap_start_tls_sW", CharSet = CharSet.Unicode)]
public static extern int ldap_start_tls(ConnectionHandle ldapHandle, ref int ServerReturnValue, ref IntPtr Message, IntPtr ServerControls, IntPtr ClientControls);
- [DllImport("wldap32.dll", CallingConvention = CallingConvention.Cdecl, EntryPoint = "ldap_stop_tls_s", CharSet = CharSet.Unicode)]
+ [DllImport(Wldap32dll, CallingConvention = CallingConvention.Cdecl, EntryPoint = "ldap_stop_tls_s", CharSet = CharSet.Unicode)]
public static extern byte ldap_stop_tls(ConnectionHandle ldapHandle);
- [DllImport("wldap32.dll", CallingConvention = CallingConvention.Cdecl, EntryPoint = "ldap_rename_extW", CharSet = CharSet.Unicode)]
+ [DllImport(Wldap32dll, CallingConvention = CallingConvention.Cdecl, EntryPoint = "ldap_rename_extW", CharSet = CharSet.Unicode)]
public static extern int ldap_rename([In] ConnectionHandle ldapHandle, string dn, string newRdn, string newParentDn, int deleteOldRdn, IntPtr servercontrol, IntPtr clientcontrol, ref int messageNumber);
- [DllImport("wldap32.dll", CallingConvention = CallingConvention.Cdecl, EntryPoint = "ldap_compare_extW", CharSet = CharSet.Unicode)]
+ [DllImport(Wldap32dll, CallingConvention = CallingConvention.Cdecl, EntryPoint = "ldap_compare_extW", CharSet = CharSet.Unicode)]
public static extern int ldap_compare([In] ConnectionHandle ldapHandle, string dn, string attributeName, string strValue, berval binaryValue, IntPtr servercontrol, IntPtr clientcontrol, ref int messageNumber);
- [DllImport("wldap32.dll", CallingConvention = CallingConvention.Cdecl, EntryPoint = "ldap_add_extW", CharSet = CharSet.Unicode)]
+ [DllImport(Wldap32dll, CallingConvention = CallingConvention.Cdecl, EntryPoint = "ldap_add_extW", CharSet = CharSet.Unicode)]
public static extern int ldap_add([In] ConnectionHandle ldapHandle, string dn, IntPtr attrs, IntPtr servercontrol, IntPtr clientcontrol, ref int messageNumber);
- [DllImport("wldap32.dll", CallingConvention = CallingConvention.Cdecl, EntryPoint = "ldap_modify_extW", CharSet = CharSet.Unicode)]
+ [DllImport(Wldap32dll, CallingConvention = CallingConvention.Cdecl, EntryPoint = "ldap_modify_extW", CharSet = CharSet.Unicode)]
public static extern int ldap_modify([In] ConnectionHandle ldapHandle, string dn, IntPtr attrs, IntPtr servercontrol, IntPtr clientcontrol, ref int messageNumber);
- [DllImport("wldap32.dll", CallingConvention = CallingConvention.Cdecl, EntryPoint = "ldap_extended_operationW", CharSet = CharSet.Unicode)]
+ [DllImport(Wldap32dll, CallingConvention = CallingConvention.Cdecl, EntryPoint = "ldap_extended_operationW", CharSet = CharSet.Unicode)]
public static extern int ldap_extended_operation([In] ConnectionHandle ldapHandle, string oid, berval data, IntPtr servercontrol, IntPtr clientcontrol, ref int messageNumber);
- [DllImport("wldap32.dll", CallingConvention = CallingConvention.Cdecl, EntryPoint = "ldap_parse_extended_resultW", CharSet = CharSet.Unicode)]
+ [DllImport(Wldap32dll, CallingConvention = CallingConvention.Cdecl, EntryPoint = "ldap_parse_extended_resultW", CharSet = CharSet.Unicode)]
public static extern int ldap_parse_extended_result([In] ConnectionHandle ldapHandle, [In] IntPtr result, ref IntPtr oid, ref IntPtr data, byte freeIt);
- [DllImport("wldap32.dll", CallingConvention = CallingConvention.Cdecl, EntryPoint = "ldap_msgfree", CharSet = CharSet.Unicode)]
+ [DllImport(Wldap32dll, CallingConvention = CallingConvention.Cdecl, EntryPoint = "ldap_msgfree", CharSet = CharSet.Unicode)]
public static extern int ldap_msgfree([In] IntPtr result);
- [DllImport("wldap32.dll", CallingConvention = CallingConvention.Cdecl, EntryPoint = "ldap_search_extW", CharSet = CharSet.Unicode)]
+ [DllImport(Wldap32dll, CallingConvention = CallingConvention.Cdecl, EntryPoint = "ldap_search_extW", CharSet = CharSet.Unicode)]
public static extern int ldap_search([In] ConnectionHandle ldapHandle, string dn, int scope, string filter, IntPtr attributes, bool attributeOnly, IntPtr servercontrol, IntPtr clientcontrol, int timelimit, int sizelimit, ref int messageNumber);
- [DllImport("wldap32.dll", CallingConvention = CallingConvention.Cdecl, EntryPoint = "ldap_first_entry", CharSet = CharSet.Unicode)]
+ [DllImport(Wldap32dll, CallingConvention = CallingConvention.Cdecl, EntryPoint = "ldap_first_entry", CharSet = CharSet.Unicode)]
public static extern IntPtr ldap_first_entry([In] ConnectionHandle ldapHandle, [In] IntPtr result);
- [DllImport("wldap32.dll", CallingConvention = CallingConvention.Cdecl, EntryPoint = "ldap_next_entry", CharSet = CharSet.Unicode)]
+ [DllImport(Wldap32dll, CallingConvention = CallingConvention.Cdecl, EntryPoint = "ldap_next_entry", CharSet = CharSet.Unicode)]
public static extern IntPtr ldap_next_entry([In] ConnectionHandle ldapHandle, [In] IntPtr result);
- [DllImport("wldap32.dll", CallingConvention = CallingConvention.Cdecl, EntryPoint = "ldap_first_reference", CharSet = CharSet.Unicode)]
+ [DllImport(Wldap32dll, CallingConvention = CallingConvention.Cdecl, EntryPoint = "ldap_first_reference", CharSet = CharSet.Unicode)]
public static extern IntPtr ldap_first_reference([In] ConnectionHandle ldapHandle, [In] IntPtr result);
- [DllImport("wldap32.dll", CallingConvention = CallingConvention.Cdecl, EntryPoint = "ldap_next_reference", CharSet = CharSet.Unicode)]
+ [DllImport(Wldap32dll, CallingConvention = CallingConvention.Cdecl, EntryPoint = "ldap_next_reference", CharSet = CharSet.Unicode)]
public static extern IntPtr ldap_next_reference([In] ConnectionHandle ldapHandle, [In] IntPtr result);
- [DllImport("wldap32.dll", CallingConvention = CallingConvention.Cdecl, EntryPoint = "ldap_get_dnW", CharSet = CharSet.Unicode)]
+ [DllImport(Wldap32dll, CallingConvention = CallingConvention.Cdecl, EntryPoint = "ldap_get_dnW", CharSet = CharSet.Unicode)]
public static extern IntPtr ldap_get_dn([In] ConnectionHandle ldapHandle, [In] IntPtr result);
- [DllImport("wldap32.dll", CallingConvention = CallingConvention.Cdecl, EntryPoint = "ldap_first_attributeW", CharSet = CharSet.Unicode)]
+ [DllImport(Wldap32dll, CallingConvention = CallingConvention.Cdecl, EntryPoint = "ldap_first_attributeW", CharSet = CharSet.Unicode)]
public static extern IntPtr ldap_first_attribute([In] ConnectionHandle ldapHandle, [In] IntPtr result, ref IntPtr address);
- [DllImport("wldap32.dll", CallingConvention = CallingConvention.Cdecl, EntryPoint = "ldap_next_attributeW", CharSet = CharSet.Unicode)]
+ [DllImport(Wldap32dll, CallingConvention = CallingConvention.Cdecl, EntryPoint = "ldap_next_attributeW", CharSet = CharSet.Unicode)]
public static extern IntPtr ldap_next_attribute([In] ConnectionHandle ldapHandle, [In] IntPtr result, [In, Out] IntPtr address);
- [DllImport("wldap32.dll", CallingConvention = CallingConvention.Cdecl, EntryPoint = "ber_free", CharSet = CharSet.Unicode)]
+ [DllImport(Wldap32dll, CallingConvention = CallingConvention.Cdecl, EntryPoint = "ber_free", CharSet = CharSet.Unicode)]
public static extern IntPtr ber_free([In] IntPtr berelement, int option);
- [DllImport("wldap32.dll", CallingConvention = CallingConvention.Cdecl, EntryPoint = "ldap_get_values_lenW", CharSet = CharSet.Unicode)]
+ [DllImport(Wldap32dll, CallingConvention = CallingConvention.Cdecl, EntryPoint = "ldap_get_values_lenW", CharSet = CharSet.Unicode)]
public static extern IntPtr ldap_get_values_len([In] ConnectionHandle ldapHandle, [In] IntPtr result, string name);
- [DllImport("wldap32.dll", CallingConvention = CallingConvention.Cdecl, EntryPoint = "ldap_value_free_len", CharSet = CharSet.Unicode)]
+ [DllImport(Wldap32dll, CallingConvention = CallingConvention.Cdecl, EntryPoint = "ldap_value_free_len", CharSet = CharSet.Unicode)]
public static extern IntPtr ldap_value_free_len([In] IntPtr berelement);
- [DllImport("wldap32.dll", CallingConvention = CallingConvention.Cdecl, EntryPoint = "ldap_parse_referenceW", CharSet = CharSet.Unicode)]
+ [DllImport(Wldap32dll, CallingConvention = CallingConvention.Cdecl, EntryPoint = "ldap_parse_referenceW", CharSet = CharSet.Unicode)]
public static extern int ldap_parse_reference([In] ConnectionHandle ldapHandle, [In] IntPtr result, ref IntPtr referrals);
- [DllImport("wldap32.dll", CallingConvention = CallingConvention.Cdecl, EntryPoint = "ber_alloc_t", CharSet = CharSet.Unicode)]
+ [DllImport(Wldap32dll, CallingConvention = CallingConvention.Cdecl, EntryPoint = "ber_alloc_t", CharSet = CharSet.Unicode)]
public static extern IntPtr ber_alloc(int option);
- [DllImport("wldap32.dll", CallingConvention = CallingConvention.Cdecl, EntryPoint = "ber_printf", CharSet = CharSet.Unicode)]
+ [DllImport(Wldap32dll, CallingConvention = CallingConvention.Cdecl, EntryPoint = "ber_printf", CharSet = CharSet.Unicode)]
public static extern int ber_printf_emptyarg(BerSafeHandle berElement, string format);
- [DllImport("wldap32.dll", CallingConvention = CallingConvention.Cdecl, EntryPoint = "ber_printf", CharSet = CharSet.Unicode)]
+ [DllImport(Wldap32dll, CallingConvention = CallingConvention.Cdecl, EntryPoint = "ber_printf", CharSet = CharSet.Unicode)]
public static extern int ber_printf_int(BerSafeHandle berElement, string format, int value);
- [DllImport("wldap32.dll", CallingConvention = CallingConvention.Cdecl, EntryPoint = "ber_printf", CharSet = CharSet.Unicode)]
+ [DllImport(Wldap32dll, CallingConvention = CallingConvention.Cdecl, EntryPoint = "ber_printf", CharSet = CharSet.Unicode)]
public static extern int ber_printf_bytearray(BerSafeHandle berElement, string format, HGlobalMemHandle value, int length);
- [DllImport("wldap32.dll", CallingConvention = CallingConvention.Cdecl, EntryPoint = "ber_printf", CharSet = CharSet.Unicode)]
+ [DllImport(Wldap32dll, CallingConvention = CallingConvention.Cdecl, EntryPoint = "ber_printf", CharSet = CharSet.Unicode)]
public static extern int ber_printf_berarray(BerSafeHandle berElement, string format, IntPtr value);
- [DllImport("wldap32.dll", CallingConvention = CallingConvention.Cdecl, EntryPoint = "ber_flatten", CharSet = CharSet.Unicode)]
+ [DllImport(Wldap32dll, CallingConvention = CallingConvention.Cdecl, EntryPoint = "ber_flatten", CharSet = CharSet.Unicode)]
public static extern int ber_flatten(BerSafeHandle berElement, ref IntPtr value);
- [DllImport("wldap32.dll", CallingConvention = CallingConvention.Cdecl, EntryPoint = "ber_init", CharSet = CharSet.Unicode)]
+ [DllImport(Wldap32dll, CallingConvention = CallingConvention.Cdecl, EntryPoint = "ber_init", CharSet = CharSet.Unicode)]
public static extern IntPtr ber_init(berval value);
- [DllImport("wldap32.dll", CallingConvention = CallingConvention.Cdecl, EntryPoint = "ber_scanf", CharSet = CharSet.Unicode)]
+ [DllImport(Wldap32dll, CallingConvention = CallingConvention.Cdecl, EntryPoint = "ber_scanf", CharSet = CharSet.Unicode)]
public static extern int ber_scanf(BerSafeHandle berElement, string format);
- [DllImport("wldap32.dll", CallingConvention = CallingConvention.Cdecl, EntryPoint = "ber_scanf", CharSet = CharSet.Unicode)]
+ [DllImport(Wldap32dll, CallingConvention = CallingConvention.Cdecl, EntryPoint = "ber_scanf", CharSet = CharSet.Unicode)]
public static extern int ber_scanf_int(BerSafeHandle berElement, string format, ref int value);
- [DllImport("wldap32.dll", CallingConvention = CallingConvention.Cdecl, EntryPoint = "ber_scanf", CharSet = CharSet.Unicode)]
+ [DllImport(Wldap32dll, CallingConvention = CallingConvention.Cdecl, EntryPoint = "ber_scanf", CharSet = CharSet.Unicode)]
public static extern int ber_scanf_ptr(BerSafeHandle berElement, string format, ref IntPtr value);
- [DllImport("wldap32.dll", CallingConvention = CallingConvention.Cdecl, EntryPoint = "ber_scanf", CharSet = CharSet.Unicode)]
+ [DllImport(Wldap32dll, CallingConvention = CallingConvention.Cdecl, EntryPoint = "ber_scanf", CharSet = CharSet.Unicode)]
public static extern int ber_scanf_bitstring(BerSafeHandle berElement, string format, ref IntPtr value, ref int length);
- [DllImport("wldap32.dll", CallingConvention = CallingConvention.Cdecl, EntryPoint = "ber_bvfree", CharSet = CharSet.Unicode)]
+ [DllImport(Wldap32dll, CallingConvention = CallingConvention.Cdecl, EntryPoint = "ber_bvfree", CharSet = CharSet.Unicode)]
public static extern int ber_bvfree(IntPtr value);
- [DllImport("wldap32.dll", CallingConvention = CallingConvention.Cdecl, EntryPoint = "ber_bvecfree", CharSet = CharSet.Unicode)]
+ [DllImport(Wldap32dll, CallingConvention = CallingConvention.Cdecl, EntryPoint = "ber_bvecfree", CharSet = CharSet.Unicode)]
public static extern int ber_bvecfree(IntPtr value);
- [DllImport("wldap32.dll", CallingConvention = CallingConvention.Cdecl, EntryPoint = "ldap_create_sort_controlW", CharSet = CharSet.Unicode)]
+ [DllImport(Wldap32dll, CallingConvention = CallingConvention.Cdecl, EntryPoint = "ldap_create_sort_controlW", CharSet = CharSet.Unicode)]
public static extern int ldap_create_sort_control(ConnectionHandle handle, IntPtr keys, byte critical, ref IntPtr control);
- [DllImport("wldap32.dll", CallingConvention = CallingConvention.Cdecl, EntryPoint = "ldap_control_freeW", CharSet = CharSet.Unicode)]
+ [DllImport(Wldap32dll, CallingConvention = CallingConvention.Cdecl, EntryPoint = "ldap_control_freeW", CharSet = CharSet.Unicode)]
public static extern int ldap_control_free(IntPtr control);
[DllImport("Crypt32.dll", EntryPoint = "CertFreeCRLContext", CharSet = CharSet.Unicode)]
public static extern int CertFreeCRLContext(IntPtr certContext);
- [DllImport("wldap32.dll", CallingConvention = CallingConvention.Cdecl, EntryPoint = "ldap_result2error", CharSet = CharSet.Unicode)]
+ [DllImport(Wldap32dll, CallingConvention = CallingConvention.Cdecl, EntryPoint = "ldap_result2error", CharSet = CharSet.Unicode)]
public static extern int ldap_result2error([In] ConnectionHandle ldapHandle, [In] IntPtr result, int freeIt);
}
}
diff --git a/src/System.DirectoryServices.Protocols/tests/System.DirectoryServices.Protocols.Tests.csproj b/src/System.DirectoryServices.Protocols/tests/System.DirectoryServices.Protocols.Tests.csproj
index bbce92570a..2a1e8f98f3 100644
--- a/src/System.DirectoryServices.Protocols/tests/System.DirectoryServices.Protocols.Tests.csproj
+++ b/src/System.DirectoryServices.Protocols/tests/System.DirectoryServices.Protocols.Tests.csproj
@@ -8,9 +8,6 @@
<PropertyGroup Condition="'$(Configuration)|$(Platform)' == 'netstandard-Windows_NT-Release|AnyCPU'" />
<!-- Default configurations to help VS understand the configurations -->
<ItemGroup>
- <Compile Include="$(CommonTestPath)\System\AssertExtensions.cs">
- <Link>Common\System\AssertExtensions.cs</Link>
- </Compile>
<Compile Include="BerConverterTests.cs" />
<Compile Include="LdapSessionOptionsTests.cs" />
<Compile Include="PermissiveModifyControlTests.cs" />
diff --git a/src/System.DirectoryServices/src/Interop/AdsAuthentication.cs b/src/System.DirectoryServices/src/Interop/AdsAuthentication.cs
index 2412cf47e8..7d5ee8f882 100644
--- a/src/System.DirectoryServices/src/Interop/AdsAuthentication.cs
+++ b/src/System.DirectoryServices/src/Interop/AdsAuthentication.cs
@@ -17,4 +17,3 @@ namespace System.DirectoryServices.Interop
ADS_USE_SEALING = 0x80
}
}
-
diff --git a/src/System.DirectoryServices/src/Interop/AdsOptions.cs b/src/System.DirectoryServices/src/Interop/AdsOptions.cs
index 41566ec617..64d555fffb 100644
--- a/src/System.DirectoryServices/src/Interop/AdsOptions.cs
+++ b/src/System.DirectoryServices/src/Interop/AdsOptions.cs
@@ -16,4 +16,3 @@ namespace System.DirectoryServices.Interop
ADS_OPTION_PASSWORD_METHOD = 7
}
}
-
diff --git a/src/System.DirectoryServices/src/Interop/AdsPropertyOperation.cs b/src/System.DirectoryServices/src/Interop/AdsPropertyOperation.cs
index 7b9c21d86f..eb9cb07daf 100644
--- a/src/System.DirectoryServices/src/Interop/AdsPropertyOperation.cs
+++ b/src/System.DirectoryServices/src/Interop/AdsPropertyOperation.cs
@@ -2,23 +2,13 @@
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
-/*
- */
-
namespace System.DirectoryServices.Interop
{
- using System;
- using System.Runtime.InteropServices;
- using System.Diagnostics;
-
internal enum AdsPropertyOperation
{
Clear = 1,
-
Update = 2,
-
Append = 3,
-
Delete = 4
}
}
diff --git a/src/System.DirectoryServices/src/Interop/AdsSearchColumn.cs b/src/System.DirectoryServices/src/Interop/AdsSearchColumn.cs
index a7cd9e75d0..87962f392b 100644
--- a/src/System.DirectoryServices/src/Interop/AdsSearchColumn.cs
+++ b/src/System.DirectoryServices/src/Interop/AdsSearchColumn.cs
@@ -2,11 +2,10 @@
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
+using System.Runtime.InteropServices;
+
namespace System.DirectoryServices.Interop
{
- using System;
- using System.Runtime.InteropServices;
-
[StructLayout(LayoutKind.Sequential)]
internal unsafe struct AdsSearchColumn
{
@@ -17,4 +16,3 @@ namespace System.DirectoryServices.Interop
public IntPtr hReserved;
}
}
-
diff --git a/src/System.DirectoryServices/src/Interop/AdsSearchPreferenceInfo.cs b/src/System.DirectoryServices/src/Interop/AdsSearchPreferenceInfo.cs
index ef0738d23e..6a8933a4df 100644
--- a/src/System.DirectoryServices/src/Interop/AdsSearchPreferenceInfo.cs
+++ b/src/System.DirectoryServices/src/Interop/AdsSearchPreferenceInfo.cs
@@ -2,11 +2,10 @@
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
+using System.Runtime.InteropServices;
+
namespace System.DirectoryServices.Interop
{
- using System;
- using System.Runtime.InteropServices;
-
[StructLayout(LayoutKind.Sequential)]
internal struct AdsSearchPreferenceInfo
{
@@ -17,4 +16,3 @@ namespace System.DirectoryServices.Interop
internal int pad2;
}
}
-
diff --git a/src/System.DirectoryServices/src/Interop/AdsSearchPreferences.cs b/src/System.DirectoryServices/src/Interop/AdsSearchPreferences.cs
index 804ccb3eb6..4d0653ec0d 100644
--- a/src/System.DirectoryServices/src/Interop/AdsSearchPreferences.cs
+++ b/src/System.DirectoryServices/src/Interop/AdsSearchPreferences.cs
@@ -27,4 +27,3 @@ namespace System.DirectoryServices.Interop
EXTENDED_DN = 18
}
}
-
diff --git a/src/System.DirectoryServices/src/Interop/AdsSortKey.cs b/src/System.DirectoryServices/src/Interop/AdsSortKey.cs
index edfee10e3f..03af293278 100644
--- a/src/System.DirectoryServices/src/Interop/AdsSortKey.cs
+++ b/src/System.DirectoryServices/src/Interop/AdsSortKey.cs
@@ -2,11 +2,10 @@
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
+using System.Runtime.InteropServices;
+
namespace System.DirectoryServices.Interop
{
- using System;
- using System.Runtime.InteropServices;
-
[StructLayout(LayoutKind.Sequential)]
internal struct AdsSortKey
{
@@ -15,4 +14,3 @@ namespace System.DirectoryServices.Interop
public int fReverseOrder;
}
}
-
diff --git a/src/System.DirectoryServices/src/Interop/AdsStatus.cs b/src/System.DirectoryServices/src/Interop/AdsStatus.cs
index d3d039cfa2..b82fe4e568 100644
--- a/src/System.DirectoryServices/src/Interop/AdsStatus.cs
+++ b/src/System.DirectoryServices/src/Interop/AdsStatus.cs
@@ -11,4 +11,3 @@ namespace System.DirectoryServices.Interop
ADS_STATUS_INVALID_SEARCHPREFVALUE = 2
}
}
-
diff --git a/src/System.DirectoryServices/src/Interop/AdsType.cs b/src/System.DirectoryServices/src/Interop/AdsType.cs
index 7cae8ed409..6d052a8c5d 100644
--- a/src/System.DirectoryServices/src/Interop/AdsType.cs
+++ b/src/System.DirectoryServices/src/Interop/AdsType.cs
@@ -37,4 +37,3 @@ namespace System.DirectoryServices.Interop
ADSTYPE_DN_WITH_STRING = 28
}
}
-
diff --git a/src/System.DirectoryServices/src/Interop/AdsValue2.cs b/src/System.DirectoryServices/src/Interop/AdsValue2.cs
index ffb35510df..2c96d28818 100644
--- a/src/System.DirectoryServices/src/Interop/AdsValue2.cs
+++ b/src/System.DirectoryServices/src/Interop/AdsValue2.cs
@@ -2,11 +2,10 @@
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
+using System.Runtime.InteropServices;
+
namespace System.DirectoryServices.Interop
{
- using System;
- using System.Runtime.InteropServices;
-
[StructLayout(LayoutKind.Sequential)]
internal struct Ads_Pointer
{
@@ -44,4 +43,3 @@ namespace System.DirectoryServices.Interop
public Ads_Generic generic;
}
}
-
diff --git a/src/System.DirectoryServices/src/Interop/AdsValueHelper2.cs b/src/System.DirectoryServices/src/Interop/AdsValueHelper2.cs
index 9c41c41636..ca34136183 100644
--- a/src/System.DirectoryServices/src/Interop/AdsValueHelper2.cs
+++ b/src/System.DirectoryServices/src/Interop/AdsValueHelper2.cs
@@ -2,14 +2,12 @@
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
+using System.Text;
+using System.Runtime.InteropServices;
+using System.Globalization;
+
namespace System.DirectoryServices.Interop
{
- using System;
- using System.Text;
- using System.Runtime.InteropServices;
- using System.Globalization;
- using System.Security.Permissions;
-
[StructLayout(LayoutKind.Sequential)]
internal struct SystemTime
{
@@ -38,7 +36,9 @@ namespace System.DirectoryServices.Interop
public IntPtr pszDNString; // Distinguished Name
}
- // helper class for dealing with struct AdsValue.
+ /// <summary>
+ /// Helper class for dealing with struct AdsValue.
+ /// </summary>
internal class AdsValueHelper
{
public AdsValue adsvalue;
@@ -62,10 +62,7 @@ namespace System.DirectoryServices.Interop
public long LowInt64
{
- get
- {
- return (long)((uint)adsvalue.generic.a + (((long)adsvalue.generic.b) << 32));
- }
+ get => (uint)adsvalue.generic.a + (((long)adsvalue.generic.b) << 32);
set
{
adsvalue.generic.a = (int)(value & 0xFFFFFFFF);
@@ -76,73 +73,80 @@ namespace System.DirectoryServices.Interop
~AdsValueHelper()
{
if (_pinnedHandle.IsAllocated)
+ {
_pinnedHandle.Free();
+ }
}
private AdsType GetAdsTypeForManagedType(Type type)
{
- //Consider this code is only excercised by DirectorySearcher
- //it just translates the types needed by such a component, if more managed
- //types are to be used in the future, this function needs to be expanded.
+ // Consider this code is only excercised by DirectorySearcher
+ // it just translates the types needed by such a component, if more managed
+ // types are to be used in the future, this function needs to be expanded.
if (type == typeof(int))
+ {
return AdsType.ADSTYPE_INTEGER;
+ }
+
if (type == typeof(long))
+ {
return AdsType.ADSTYPE_LARGE_INTEGER;
+ }
+
if (type == typeof(bool))
+ {
return AdsType.ADSTYPE_BOOLEAN;
+ }
return AdsType.ADSTYPE_UNKNOWN;
}
- public AdsValue GetStruct()
- {
- return adsvalue;
- }
+ public AdsValue GetStruct() => adsvalue;
- private static ushort LowOfInt(int i)
- {
- return unchecked((ushort)(i & 0xFFFF));
- }
+ private static ushort LowOfInt(int i) => unchecked((ushort)(i & 0xFFFF));
- private static ushort HighOfInt(int i)
- {
- return unchecked((ushort)((i >> 16) & 0xFFFF));
- }
+ private static ushort HighOfInt(int i) => unchecked((ushort)((i >> 16) & 0xFFFF));
public object GetValue()
{
switch ((AdsType)adsvalue.dwType)
{
- // Common for DNS and LDAP
+ // Common for DNS and LDAP.
case AdsType.ADSTYPE_UTC_TIME:
{
- SystemTime st = new SystemTime();
-
- st.wYear = LowOfInt(adsvalue.generic.a);
- st.wMonth = HighOfInt(adsvalue.generic.a);
- st.wDayOfWeek = LowOfInt(adsvalue.generic.b);
- st.wDay = HighOfInt(adsvalue.generic.b);
- st.wHour = LowOfInt(adsvalue.generic.c);
- st.wMinute = HighOfInt(adsvalue.generic.c);
- st.wSecond = LowOfInt(adsvalue.generic.d);
- st.wMilliseconds = HighOfInt(adsvalue.generic.d);
+ var st = new SystemTime()
+ {
+ wYear = LowOfInt(adsvalue.generic.a),
+ wMonth = HighOfInt(adsvalue.generic.a),
+ wDayOfWeek = LowOfInt(adsvalue.generic.b),
+ wDay = HighOfInt(adsvalue.generic.b),
+ wHour = LowOfInt(adsvalue.generic.c),
+ wMinute = HighOfInt(adsvalue.generic.c),
+ wSecond = LowOfInt(adsvalue.generic.d),
+ wMilliseconds = HighOfInt(adsvalue.generic.d)
+ };
return new DateTime(st.wYear, st.wMonth, st.wDay, st.wHour, st.wMinute, st.wSecond, st.wMilliseconds);
}
case AdsType.ADSTYPE_DN_WITH_BINARY:
{
- DnWithBinary dnb = new DnWithBinary();
+ var dnb = new DnWithBinary();
Marshal.PtrToStructure(adsvalue.pointer.value, dnb);
+
byte[] bytes = new byte[dnb.dwLength];
Marshal.Copy(dnb.lpBinaryValue, bytes, 0, dnb.dwLength);
- StringBuilder strb = new StringBuilder();
- StringBuilder binaryPart = new StringBuilder();
+
+ var strb = new StringBuilder();
+ var binaryPart = new StringBuilder();
for (int i = 0; i < bytes.Length; i++)
{
string s = bytes[i].ToString("X", CultureInfo.InvariantCulture);
if (s.Length == 1)
+ {
binaryPart.Append("0");
+ }
+
binaryPart.Append(s);
}
@@ -152,24 +156,24 @@ namespace System.DirectoryServices.Interop
strb.Append(binaryPart.ToString());
strb.Append(":");
strb.Append(Marshal.PtrToStringUni(dnb.pszDNString));
+
return strb.ToString();
}
case AdsType.ADSTYPE_DN_WITH_STRING:
{
- DnWithString dns = new DnWithString();
+ var dns = new DnWithString();
Marshal.PtrToStructure(adsvalue.pointer.value, dns);
- string strValue = Marshal.PtrToStringUni(dns.pszStringValue);
- if (strValue == null)
- strValue = "";
+ string strValue = Marshal.PtrToStringUni(dns.pszStringValue) ?? string.Empty;
- StringBuilder strb = new StringBuilder();
+ var strb = new StringBuilder();
strb.Append("S:");
strb.Append(strValue.Length);
strb.Append(":");
strb.Append(strValue);
strb.Append(":");
strb.Append(Marshal.PtrToStringUni(dns.pszDNString));
+
return strb.ToString();
}
@@ -179,21 +183,21 @@ namespace System.DirectoryServices.Interop
case AdsType.ADSTYPE_PRINTABLE_STRING:
case AdsType.ADSTYPE_NUMERIC_STRING:
case AdsType.ADSTYPE_OBJECT_CLASS:
- // string
+ // The value is a String.
return Marshal.PtrToStringUni(adsvalue.pointer.value);
case AdsType.ADSTYPE_BOOLEAN:
- // bool
+ // The value is a bool.
return adsvalue.generic.a != 0;
case AdsType.ADSTYPE_INTEGER:
- // int
+ // The value is an int.
return adsvalue.generic.a;
case AdsType.ADSTYPE_NT_SECURITY_DESCRIPTOR:
case AdsType.ADSTYPE_OCTET_STRING:
case AdsType.ADSTYPE_PROV_SPECIFIC:
- // byte[]
+ // The value is a byte[].
int len = adsvalue.octetString.length;
byte[] value = new byte[len];
Marshal.Copy(adsvalue.octetString.value, value, 0, len);
@@ -205,7 +209,7 @@ namespace System.DirectoryServices.Interop
case AdsType.ADSTYPE_LARGE_INTEGER:
return LowInt64;
- // not used in LDAP
+ // Not used in LDAP
case AdsType.ADSTYPE_CASEIGNORE_LIST:
case AdsType.ADSTYPE_OCTET_LIST:
case AdsType.ADSTYPE_PATH:
@@ -220,36 +224,40 @@ namespace System.DirectoryServices.Interop
case AdsType.ADSTYPE_TYPEDNAME:
case AdsType.ADSTYPE_REPLICAPOINTER:
case AdsType.ADSTYPE_UNKNOWN:
- return new NotImplementedException(String.Format(CultureInfo.CurrentCulture, SR.DSAdsvalueTypeNYI , "0x" + Convert.ToString(adsvalue.dwType, 16)));
+ return new NotImplementedException(SR.Format(SR.DSAdsvalueTypeNYI , "0x" + Convert.ToString(adsvalue.dwType, 16)));
default:
- return new ArgumentException(String.Format(CultureInfo.CurrentCulture, SR.DSConvertFailed , "0x" + Convert.ToString(LowInt64, 16), "0x" + Convert.ToString(adsvalue.dwType, 16)));
+ return new ArgumentException(SR.Format(SR.DSConvertFailed , "0x" + Convert.ToString(LowInt64, 16), "0x" + Convert.ToString(adsvalue.dwType, 16)));
}
}
public object GetVlvValue()
{
- AdsVLV vlv = new AdsVLV();
+ var vlv = new AdsVLV();
Marshal.PtrToStructure(adsvalue.octetString.value, vlv);
+
byte[] bytes = null;
if (vlv.contextID != (IntPtr)0 && vlv.contextIDlength != 0)
{
bytes = new byte[vlv.contextIDlength];
Marshal.Copy(vlv.contextID, bytes, 0, vlv.contextIDlength);
}
- DirectoryVirtualListView vlvResponse = new DirectoryVirtualListView();
- vlvResponse.Offset = vlv.offset;
- vlvResponse.ApproximateTotal = vlv.contentCount;
- DirectoryVirtualListViewContext context = new DirectoryVirtualListViewContext(bytes);
- vlvResponse.DirectoryVirtualListViewContext = context;
- return vlvResponse;
+ return new DirectoryVirtualListView
+ {
+ Offset = vlv.offset,
+ ApproximateTotal = vlv.contentCount,
+ DirectoryVirtualListViewContext = new DirectoryVirtualListViewContext(bytes)
+ };
}
private unsafe void SetValue(object managedValue, AdsType adsType)
{
- adsvalue = new AdsValue();
- adsvalue.dwType = (int)adsType;
+ adsvalue = new AdsValue()
+ {
+ dwType = (int)adsType
+ };
+
switch (adsType)
{
case AdsType.ADSTYPE_INTEGER:
@@ -260,10 +268,7 @@ namespace System.DirectoryServices.Interop
LowInt64 = (long)managedValue;
break;
case AdsType.ADSTYPE_BOOLEAN:
- if ((bool)managedValue)
- LowInt64 = -1;
- else
- LowInt64 = 0;
+ LowInt64 = (bool)managedValue ? -1 : 0;
break;
case AdsType.ADSTYPE_CASE_IGNORE_STRING:
_pinnedHandle = GCHandle.Alloc(managedValue, GCHandleType.Pinned);
@@ -271,7 +276,7 @@ namespace System.DirectoryServices.Interop
break;
case AdsType.ADSTYPE_PROV_SPECIFIC:
byte[] bytes = (byte[])managedValue;
- // filling in an ADS_PROV_SPECIFIC struct.
+ // Filling in an ADS_PROV_SPECIFIC struct.
// 1st dword (our member a) is DWORD dwLength.
// 2nd dword (our member b) is byte *lpValue.
adsvalue.octetString.length = bytes.Length;
@@ -279,9 +284,8 @@ namespace System.DirectoryServices.Interop
adsvalue.octetString.value = _pinnedHandle.AddrOfPinnedObject();
break;
default:
- throw new NotImplementedException(String.Format(CultureInfo.CurrentCulture, SR.DSAdsvalueTypeNYI , "0x" + Convert.ToString((int)adsType, 16)));
+ throw new NotImplementedException(SR.Format(SR.DSAdsvalueTypeNYI , "0x" + Convert.ToString((int)adsType, 16)));
}
}
}
}
-
diff --git a/src/System.DirectoryServices/src/Interop/NativeMethods.cs b/src/System.DirectoryServices/src/Interop/NativeMethods.cs
index 9767032e66..c630051dce 100644
--- a/src/System.DirectoryServices/src/Interop/NativeMethods.cs
+++ b/src/System.DirectoryServices/src/Interop/NativeMethods.cs
@@ -4,14 +4,6 @@
namespace System.DirectoryServices.Interop
{
-#pragma warning disable BCL0015 // CoreFXPort
- using System.Runtime.InteropServices;
- using System;
- using System.Security.Permissions;
- using System.Collections;
- using System.IO;
- using System.Text;
-
internal class NativeMethods
{
public enum AuthenticationModes
@@ -20,7 +12,6 @@ namespace System.DirectoryServices.Interop
UseEncryption = 0x2,
UseSSL = 0x2,
ReadonlyServer = 0x4,
- // PromptCredentials = 0x8, // Deprecated by ADSI
NoAuthentication = 0x10,
FastBind = 0x20,
UseSigning = 0x40,
@@ -30,4 +21,3 @@ namespace System.DirectoryServices.Interop
}
}
}
-
diff --git a/src/System.DirectoryServices/src/Interop/SafeNativeMethods.cs b/src/System.DirectoryServices/src/Interop/SafeNativeMethods.cs
index fdddc91dda..5aec29efff 100644
--- a/src/System.DirectoryServices/src/Interop/SafeNativeMethods.cs
+++ b/src/System.DirectoryServices/src/Interop/SafeNativeMethods.cs
@@ -2,61 +2,54 @@
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
+using System.Text;
+using System.Security;
+using System.Runtime.InteropServices;
+
namespace System.DirectoryServices.Interop
{
- using System;
- using System.Text;
- using System.Security;
- using System.Security.Permissions;
- using System.Runtime.InteropServices;
#pragma warning disable BCL0015 // CoreFxPort
- [
- SuppressUnmanagedCodeSecurityAttribute()
- ]
+ [SuppressUnmanagedCodeSecurity]
internal class SafeNativeMethods
{
[DllImport(ExternDll.Oleaut32, PreserveSig = false)]
public static extern void VariantClear(IntPtr pObject);
+
[DllImport(ExternDll.Oleaut32)]
public static extern void VariantInit(IntPtr pObject);
+
[DllImport(ExternDll.Activeds)]
public static extern bool FreeADsMem(IntPtr pVoid);
- public const int FORMAT_MESSAGE_ALLOCATE_BUFFER = 0x00000100,
+ public const int
FORMAT_MESSAGE_IGNORE_INSERTS = 0x00000200,
- FORMAT_MESSAGE_FROM_STRING = 0x00000400,
- FORMAT_MESSAGE_FROM_HMODULE = 0x00000800,
FORMAT_MESSAGE_FROM_SYSTEM = 0x00001000,
FORMAT_MESSAGE_ARGUMENT_ARRAY = 0x00002000,
- FORMAT_MESSAGE_MAX_WIDTH_MASK = 0x000000FF,
ERROR_MORE_DATA = 234,
ERROR_SUCCESS = 0;
- [DllImport(ExternDll.Activeds, CharSet = System.Runtime.InteropServices.CharSet.Unicode)]
+ [DllImport(ExternDll.Activeds, CharSet = CharSet.Unicode)]
public static extern int ADsGetLastError(out int error, StringBuilder errorBuffer,
int errorBufferLength, StringBuilder nameBuffer, int nameBufferLength);
- [DllImport(ExternDll.Activeds, CharSet = System.Runtime.InteropServices.CharSet.Unicode)]
+ [DllImport(ExternDll.Activeds, CharSet = CharSet.Unicode)]
public static extern int ADsSetLastError(int error, string errorString, string provider);
- [DllImport(ExternDll.Kernel32, CharSet = System.Runtime.InteropServices.CharSet.Unicode)]
+ [DllImport(ExternDll.Kernel32, CharSet = CharSet.Unicode)]
public static extern int FormatMessageW(int dwFlags, int lpSource, int dwMessageId,
int dwLanguageId, StringBuilder lpBuffer, int nSize, int arguments);
public class EnumVariant
{
private static readonly object s_noMoreValues = new object();
- private Object _currentValue = s_noMoreValues;
+ private object _currentValue = s_noMoreValues;
private IEnumVariant _enumerator;
public EnumVariant(IEnumVariant en)
{
- if (en == null)
- throw new ArgumentNullException("en");
- _enumerator = en;
+ _enumerator = en ?? throw new ArgumentNullException(nameof(en));
}
- /// <include file='doc\SafeNativeMethods.uex' path='docs/doc[@for="SafeNativeMethods.EnumVariant.GetNext"]/*' />
/// <devdoc>
/// Moves the enumerator to the next value In the list.
/// </devdoc>
@@ -66,19 +59,20 @@ namespace System.DirectoryServices.Interop
return _currentValue != s_noMoreValues;
}
- /// <include file='doc\SafeNativeMethods.uex' path='docs/doc[@for="SafeNativeMethods.EnumVariant.GetValue"]/*' />
/// <devdoc>
/// Returns the current value of the enumerator. If GetNext() has never been called,
/// or if it has been called but it returned false, will throw an exception.
/// </devdoc>
- public Object GetValue()
+ public object GetValue()
{
if (_currentValue == s_noMoreValues)
+ {
throw new InvalidOperationException(SR.DSEnumerator);
+ }
+
return _currentValue;
}
- /// <include file='doc\SafeNativeMethods.uex' path='docs/doc[@for="SafeNativeMethods.EnumVariant.Reset"]/*' />
/// <devdoc>
/// Returns the enumerator to the start of the sequence.
/// </devdoc>
@@ -88,7 +82,6 @@ namespace System.DirectoryServices.Interop
_currentValue = s_noMoreValues;
}
- /// <include file='doc\SafeNativeMethods.uex' path='docs/doc[@for="SafeNativeMethods.EnumVariant.Advance"]/*' />
/// <devdoc>
/// Moves the pointer to the next value In the contained IEnumVariant, and
/// stores the current value In currentValue.
@@ -100,7 +93,7 @@ namespace System.DirectoryServices.Interop
try
{
int[] numRead = new int[] { 0 };
- SafeNativeMethods.VariantInit(addr);
+ VariantInit(addr);
_enumerator.Next(1, addr, numRead);
try
@@ -114,7 +107,7 @@ namespace System.DirectoryServices.Interop
}
finally
{
- SafeNativeMethods.VariantClear(addr);
+ VariantClear(addr);
}
}
finally
@@ -124,30 +117,24 @@ namespace System.DirectoryServices.Interop
}
}
- [ComImport(), Guid("00020404-0000-0000-C000-000000000046"), System.Runtime.InteropServices.InterfaceTypeAttribute(System.Runtime.InteropServices.ComInterfaceType.InterfaceIsIUnknown)]
+ [ComImport]
+ [Guid("00020404-0000-0000-C000-000000000046")]
+ [InterfaceType(ComInterfaceType.InterfaceIsIUnknown)]
public interface IEnumVariant
{
- [SuppressUnmanagedCodeSecurityAttribute()]
- void Next(
- [In, MarshalAs(UnmanagedType.U4)]
- int celt,
- [In, Out]
- IntPtr rgvar,
- [Out, MarshalAs(UnmanagedType.LPArray)]
- int[] pceltFetched);
-
- [SuppressUnmanagedCodeSecurityAttribute()]
- void Skip(
- [In, MarshalAs(UnmanagedType.U4)]
- int celt);
-
- [SuppressUnmanagedCodeSecurityAttribute()]
+ [SuppressUnmanagedCodeSecurity]
+ void Next([In, MarshalAs(UnmanagedType.U4)] int celt,
+ [In, Out] IntPtr rgvar,
+ [Out, MarshalAs(UnmanagedType.LPArray)] int[] pceltFetched);
+
+ [SuppressUnmanagedCodeSecurity]
+ void Skip([In, MarshalAs(UnmanagedType.U4)] int celt);
+
+ [SuppressUnmanagedCodeSecurity]
void Reset();
- [SuppressUnmanagedCodeSecurityAttribute()]
- void Clone(
- [Out, MarshalAs(UnmanagedType.LPArray)]
- IEnumVariant[] ppenum);
+ [SuppressUnmanagedCodeSecurity]
+ void Clone([Out, MarshalAs(UnmanagedType.LPArray)] IEnumVariant[] ppenum);
}
}
}
diff --git a/src/System.DirectoryServices/src/Interop/UnsafeNativeMethods.cs b/src/System.DirectoryServices/src/Interop/UnsafeNativeMethods.cs
index 1680b2df03..cc9b3dd757 100644
--- a/src/System.DirectoryServices/src/Interop/UnsafeNativeMethods.cs
+++ b/src/System.DirectoryServices/src/Interop/UnsafeNativeMethods.cs
@@ -2,16 +2,12 @@
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
+using System.Runtime.InteropServices;
+using System.Security;
+
namespace System.DirectoryServices.Interop
{
#pragma warning disable BCL0015 // CoreFxPort
- using System.Runtime.InteropServices;
- using System;
- using System.Security;
- using System.Security.Permissions;
- using System.Collections;
- using System.IO;
- using System.Text;
[StructLayout(LayoutKind.Explicit)]
internal struct Variant
@@ -32,13 +28,12 @@ namespace System.DirectoryServices.Interop
public IntPtr ptr2;
}
- [
- SuppressUnmanagedCodeSecurityAttribute()
- ]
+ [SuppressUnmanagedCodeSecurity]
internal class UnsafeNativeMethods
{
[DllImport(ExternDll.Activeds, ExactSpelling = true, EntryPoint = "ADsOpenObject", CharSet = System.Runtime.InteropServices.CharSet.Unicode)]
private static extern int IntADsOpenObject(string path, string userName, string password, int flags, [In, Out] ref Guid iid, [Out, MarshalAs(UnmanagedType.Interface)] out object ppObject);
+
public static int ADsOpenObject(string path, string userName, string password, int flags, [In, Out] ref Guid iid, [Out, MarshalAs(UnmanagedType.Interface)] out object ppObject)
{
try
@@ -51,205 +46,167 @@ namespace System.DirectoryServices.Interop
}
}
+ [ComImport, Guid("FD8256D0-FD15-11CE-ABC4-02608C9E7553")]
public interface IAds
{
string Name
{
[return: MarshalAs(UnmanagedType.BStr)]
- [SuppressUnmanagedCodeSecurityAttribute()]
+ [SuppressUnmanagedCodeSecurity]
get;
}
string Class
{
[return: MarshalAs(UnmanagedType.BStr)]
- [SuppressUnmanagedCodeSecurityAttribute()]
+ [SuppressUnmanagedCodeSecurity]
get;
}
string GUID
{
[return: MarshalAs(UnmanagedType.BStr)]
- [SuppressUnmanagedCodeSecurityAttribute()]
+ [SuppressUnmanagedCodeSecurity]
get;
}
string ADsPath
{
[return: MarshalAs(UnmanagedType.BStr)]
- [SuppressUnmanagedCodeSecurityAttribute()]
+ [SuppressUnmanagedCodeSecurity]
get;
}
string Parent
{
[return: MarshalAs(UnmanagedType.BStr)]
- [SuppressUnmanagedCodeSecurityAttribute()]
+ [SuppressUnmanagedCodeSecurity]
get;
}
string Schema
{
[return: MarshalAs(UnmanagedType.BStr)]
- [SuppressUnmanagedCodeSecurityAttribute()]
+ [SuppressUnmanagedCodeSecurity]
get;
}
- [SuppressUnmanagedCodeSecurityAttribute()]
+ [SuppressUnmanagedCodeSecurity]
void GetInfo();
- [SuppressUnmanagedCodeSecurityAttribute()]
+ [SuppressUnmanagedCodeSecurity]
void SetInfo();
- Object Get(
- [In, MarshalAs(UnmanagedType.BStr)]
- string bstrName);
+ object Get([In, MarshalAs(UnmanagedType.BStr)] string bstrName);
- [SuppressUnmanagedCodeSecurityAttribute()]
- void Put(
- [In, MarshalAs(UnmanagedType.BStr)]
- string bstrName,
- [In]
- Object vProp);
+ [SuppressUnmanagedCodeSecurity]
+ void Put([In, MarshalAs(UnmanagedType.BStr)] string bstrName, [In] object vProp);
- [SuppressUnmanagedCodeSecurityAttribute()]
+ [SuppressUnmanagedCodeSecurity]
[PreserveSig]
- int GetEx(
- [In, MarshalAs(UnmanagedType.BStr)]
- String bstrName,
- [Out]
- out object value);
+ int GetEx([In, MarshalAs(UnmanagedType.BStr)] string bstrName, [Out] out object value);
- [SuppressUnmanagedCodeSecurityAttribute()]
+ [SuppressUnmanagedCodeSecurity]
void PutEx(
- [In, MarshalAs(UnmanagedType.U4)]
- int lnControlCode,
- [In, MarshalAs(UnmanagedType.BStr)]
- string bstrName,
- [In]
- Object vProp);
-
- [SuppressUnmanagedCodeSecurityAttribute()]
- void GetInfoEx(
- [In]
- Object vProperties,
- [In, MarshalAs(UnmanagedType.U4)]
- int lnReserved);
+ [In, MarshalAs(UnmanagedType.U4)] int lnControlCode,
+ [In, MarshalAs(UnmanagedType.BStr)] string bstrName,
+ [In] object vProp);
+
+ [SuppressUnmanagedCodeSecurity]
+ void GetInfoEx([In] object vProperties, [In, MarshalAs(UnmanagedType.U4)] int lnReserved);
}
+ [ComImport, Guid("001677D0-FD16-11CE-ABC4-02608C9E7553")]
public interface IAdsContainer
{
int Count
{
[return: MarshalAs(UnmanagedType.U4)]
- [SuppressUnmanagedCodeSecurityAttribute()]
+ [SuppressUnmanagedCodeSecurity]
get;
}
object _NewEnum
{
[return: MarshalAs(UnmanagedType.Interface)]
- [SuppressUnmanagedCodeSecurityAttribute()]
+ [SuppressUnmanagedCodeSecurity]
get;
}
- object Filter
- {
- get;
- set;
- }
+ object Filter { get; set; }
- object Hints
- {
- get;
- set;
- }
+ object Hints { get; set; }
[return: MarshalAs(UnmanagedType.Interface)]
- [SuppressUnmanagedCodeSecurityAttribute()]
+ [SuppressUnmanagedCodeSecurity]
object GetObject(
- [In, MarshalAs(UnmanagedType.BStr)]
- string className,
- [In, MarshalAs(UnmanagedType.BStr)]
- string relativeName);
+ [In, MarshalAs(UnmanagedType.BStr)] string className,
+ [In, MarshalAs(UnmanagedType.BStr)] string relativeName);
[return: MarshalAs(UnmanagedType.Interface)]
- [SuppressUnmanagedCodeSecurityAttribute()]
+ [SuppressUnmanagedCodeSecurity]
object Create(
- [In, MarshalAs(UnmanagedType.BStr)]
- string className,
- [In, MarshalAs(UnmanagedType.BStr)]
- string relativeName);
+ [In, MarshalAs(UnmanagedType.BStr)] string className,
+ [In, MarshalAs(UnmanagedType.BStr)] string relativeName);
- [SuppressUnmanagedCodeSecurityAttribute()]
+ [SuppressUnmanagedCodeSecurity]
void Delete(
- [In, MarshalAs(UnmanagedType.BStr)]
- string className,
- [In, MarshalAs(UnmanagedType.BStr)]
- string relativeName);
+ [In, MarshalAs(UnmanagedType.BStr)] string className,
+ [In, MarshalAs(UnmanagedType.BStr)] string relativeName);
[return: MarshalAs(UnmanagedType.Interface)]
- [SuppressUnmanagedCodeSecurityAttribute()]
+ [SuppressUnmanagedCodeSecurity]
object CopyHere(
- [In, MarshalAs(UnmanagedType.BStr)]
- string sourceName,
- [In, MarshalAs(UnmanagedType.BStr)]
- string newName);
+ [In, MarshalAs(UnmanagedType.BStr)] string sourceName,
+ [In, MarshalAs(UnmanagedType.BStr)] string newName);
[return: MarshalAs(UnmanagedType.Interface)]
- [SuppressUnmanagedCodeSecurityAttribute()]
+ [SuppressUnmanagedCodeSecurity]
object MoveHere(
- [In, MarshalAs(UnmanagedType.BStr)]
- string sourceName,
- [In, MarshalAs(UnmanagedType.BStr)]
- string newName);
+ [In, MarshalAs(UnmanagedType.BStr)] string sourceName,
+ [In, MarshalAs(UnmanagedType.BStr)] string newName);
}
+ [ComImport, Guid("B2BD0902-8878-11D1-8C21-00C04FD8D503")]
public interface IAdsDeleteOps
{
- [SuppressUnmanagedCodeSecurityAttribute()]
+ [SuppressUnmanagedCodeSecurity]
void DeleteObject(int flags);
}
- //
- // PropertyValue as a co-class that implements the IAdsPropertyValue interface
- //
+ /// <summary>
+ /// PropertyValue as a co-class that implements the IAdsPropertyValue interface.
+ /// </summary>
[ComImport, Guid("7b9e38b0-a97c-11d0-8534-00c04fd8d503")]
public class PropertyValue
{
}
+ [ComImport, Guid("9068270B-0939-11D1-8BE1-00C04FD8D503")]
public interface IADsLargeInteger
{
- int HighPart
- {
- get;
- set;
- }
- int LowPart
- {
- get;
- set;
- }
+ int HighPart { get; set; }
+ int LowPart { get; set; }
}
+ [ComImport, Guid("79FA9AD0-A97C-11D0-8534-00C04FD8D503")]
public interface IAdsPropertyValue
{
- [SuppressUnmanagedCodeSecurityAttribute()]
+ [SuppressUnmanagedCodeSecurity]
void Clear();
int ADsType
{
- [SuppressUnmanagedCodeSecurityAttribute()]
+ [SuppressUnmanagedCodeSecurity]
get;
- [SuppressUnmanagedCodeSecurityAttribute()]
+ [SuppressUnmanagedCodeSecurity]
set;
}
string DNString
{
[return: MarshalAs(UnmanagedType.BStr)]
- [SuppressUnmanagedCodeSecurityAttribute()]
+ [SuppressUnmanagedCodeSecurity]
get;
[param: MarshalAs(UnmanagedType.BStr)]
set;
@@ -258,7 +215,7 @@ namespace System.DirectoryServices.Interop
string CaseExactString
{
[return: MarshalAs(UnmanagedType.BStr)]
- [SuppressUnmanagedCodeSecurityAttribute()]
+ [SuppressUnmanagedCodeSecurity]
get;
[param: MarshalAs(UnmanagedType.BStr)]
set;
@@ -267,7 +224,7 @@ namespace System.DirectoryServices.Interop
string CaseIgnoreString
{
[return: MarshalAs(UnmanagedType.BStr)]
- [SuppressUnmanagedCodeSecurityAttribute()]
+ [SuppressUnmanagedCodeSecurity]
get;
[param: MarshalAs(UnmanagedType.BStr)]
set;
@@ -276,7 +233,7 @@ namespace System.DirectoryServices.Interop
string PrintableString
{
[return: MarshalAs(UnmanagedType.BStr)]
- [SuppressUnmanagedCodeSecurityAttribute()]
+ [SuppressUnmanagedCodeSecurity]
get;
[param: MarshalAs(UnmanagedType.BStr)]
set;
@@ -285,36 +242,28 @@ namespace System.DirectoryServices.Interop
string NumericString
{
[return: MarshalAs(UnmanagedType.BStr)]
- [SuppressUnmanagedCodeSecurityAttribute()]
+ [SuppressUnmanagedCodeSecurity]
get;
[param: MarshalAs(UnmanagedType.BStr)]
set;
}
- bool Boolean
- {
- get;
- set;
- }
+ bool Boolean { get; set; }
- int Integer
- {
- get;
- set;
- }
+ int Integer { get; set; }
object OctetString
{
- [SuppressUnmanagedCodeSecurityAttribute()]
+ [SuppressUnmanagedCodeSecurity]
get;
- [SuppressUnmanagedCodeSecurityAttribute()]
+ [SuppressUnmanagedCodeSecurity]
set;
}
object SecurityDescriptor
{
- [SuppressUnmanagedCodeSecurityAttribute()]
+ [SuppressUnmanagedCodeSecurity]
get;
set;
@@ -322,7 +271,7 @@ namespace System.DirectoryServices.Interop
object LargeInteger
{
- [SuppressUnmanagedCodeSecurityAttribute()]
+ [SuppressUnmanagedCodeSecurity]
get;
set;
@@ -330,82 +279,81 @@ namespace System.DirectoryServices.Interop
object UTCTime
{
- [SuppressUnmanagedCodeSecurityAttribute()]
+ [SuppressUnmanagedCodeSecurity]
get;
set;
}
}
- //
- // PropertyEntry as a co-class that implements the IAdsPropertyEntry interface
- //
+ /// <summary>
+ /// PropertyEntry as a co-class that implements the IAdsPropertyEntry interface.
+ /// </summary>
+ [ComImport, Guid("72D3EDC2-A4C4-11D0-8533-00C04FD8D503")]
public class PropertyEntry
{
}
+ [ComImport, Guid("05792C8E-941F-11D0-8529-00C04FD8D503")]
public interface IAdsPropertyEntry
{
- [SuppressUnmanagedCodeSecurityAttribute()]
+ [SuppressUnmanagedCodeSecurity]
void Clear();
string Name
{
[return: MarshalAs(UnmanagedType.BStr)]
- [SuppressUnmanagedCodeSecurityAttribute()]
+ [SuppressUnmanagedCodeSecurity]
get;
[param: MarshalAs(UnmanagedType.BStr)]
- [SuppressUnmanagedCodeSecurityAttribute()]
+ [SuppressUnmanagedCodeSecurity]
set;
}
int ADsType
{
- [SuppressUnmanagedCodeSecurityAttribute()]
+ [SuppressUnmanagedCodeSecurity]
get;
- [SuppressUnmanagedCodeSecurityAttribute()]
+ [SuppressUnmanagedCodeSecurity]
set;
}
int ControlCode
{
- [SuppressUnmanagedCodeSecurityAttribute()]
+ [SuppressUnmanagedCodeSecurity]
get;
- [SuppressUnmanagedCodeSecurityAttribute()]
+ [SuppressUnmanagedCodeSecurity]
set;
}
- object Values
- {
- get;
- set;
- }
+ object Values { get; set; }
}
+ [ComImport, Guid("C6F602B6-8F69-11D0-8528-00C04FD8D503")]
public interface IAdsPropertyList
{
int PropertyCount
{
[return: MarshalAs(UnmanagedType.U4)]
- [SuppressUnmanagedCodeSecurityAttribute()]
+ [SuppressUnmanagedCodeSecurity]
get;
}
[return: MarshalAs(UnmanagedType.I4)]
- [SuppressUnmanagedCodeSecurityAttribute()]
+ [SuppressUnmanagedCodeSecurity]
[PreserveSig]
int Next([Out] out object nextProp);
void Skip([In] int cElements);
- [SuppressUnmanagedCodeSecurityAttribute()]
+ [SuppressUnmanagedCodeSecurity]
void Reset();
object Item([In] object varIndex);
object GetPropertyItem([In, MarshalAs(UnmanagedType.BStr)] string bstrName, int ADsType);
- [SuppressUnmanagedCodeSecurityAttribute()]
+ [SuppressUnmanagedCodeSecurity]
void PutPropertyItem([In] object varData);
void ResetPropertyItem([In] object varEntry);
@@ -416,85 +364,76 @@ namespace System.DirectoryServices.Interop
[ComImport, Guid("109BA8EC-92F0-11D0-A790-00C04FD8D5A8"), System.Runtime.InteropServices.InterfaceTypeAttribute(System.Runtime.InteropServices.ComInterfaceType.InterfaceIsIUnknown)]
public interface IDirectorySearch
{
- [SuppressUnmanagedCodeSecurityAttribute()]
- void SetSearchPreference(
- [In]
- IntPtr /*ads_searchpref_info * */pSearchPrefs,
- //ads_searchpref_info[] pSearchPrefs,
- int dwNumPrefs);
-
- [SuppressUnmanagedCodeSecurityAttribute()]
+ [SuppressUnmanagedCodeSecurity]
+ void SetSearchPreference([In] IntPtr /*ads_searchpref_info * */pSearchPrefs, int dwNumPrefs);
+
+ [SuppressUnmanagedCodeSecurity]
void ExecuteSearch(
- [In, MarshalAs(UnmanagedType.LPWStr)]
- string pszSearchFilter,
- [In, MarshalAs(UnmanagedType.LPArray)]
- string[] pAttributeNames,
- [In]
- int dwNumberAttributes,
- [Out]
- out IntPtr hSearchResult);
-
- [SuppressUnmanagedCodeSecurityAttribute()]
+ [In, MarshalAs(UnmanagedType.LPWStr)] string pszSearchFilter,
+ [In, MarshalAs(UnmanagedType.LPArray)] string[] pAttributeNames,
+ [In] int dwNumberAttributes,
+ [Out] out IntPtr hSearchResult);
+
+ [SuppressUnmanagedCodeSecurity]
void AbandonSearch([In] IntPtr hSearchResult);
[return: MarshalAs(UnmanagedType.U4)]
- [SuppressUnmanagedCodeSecurityAttribute()]
+ [SuppressUnmanagedCodeSecurity]
[PreserveSig]
int GetFirstRow([In] IntPtr hSearchResult);
[return: MarshalAs(UnmanagedType.U4)]
- [SuppressUnmanagedCodeSecurityAttribute()]
+ [SuppressUnmanagedCodeSecurity]
[PreserveSig]
int GetNextRow([In] IntPtr hSearchResult);
[return: MarshalAs(UnmanagedType.U4)]
- [SuppressUnmanagedCodeSecurityAttribute()]
+ [SuppressUnmanagedCodeSecurity]
[PreserveSig]
int GetPreviousRow([In] IntPtr hSearchResult);
[return: MarshalAs(UnmanagedType.U4)]
- [SuppressUnmanagedCodeSecurityAttribute()]
+ [SuppressUnmanagedCodeSecurity]
[PreserveSig]
int GetNextColumnName(
[In] IntPtr hSearchResult,
- [Out]
- IntPtr ppszColumnName);
+ [Out] IntPtr ppszColumnName);
- [SuppressUnmanagedCodeSecurityAttribute()]
+ [SuppressUnmanagedCodeSecurity]
void GetColumn(
[In] IntPtr hSearchResult,
- [In] //, MarshalAs(UnmanagedType.LPWStr)]
- IntPtr /* char * */ szColumnName,
- [In]
- IntPtr pSearchColumn);
+ [In] IntPtr /* char * */ szColumnName,
+ [In] IntPtr pSearchColumn);
- [SuppressUnmanagedCodeSecurityAttribute()]
- void FreeColumn(
- [In]
- IntPtr pSearchColumn);
+ [SuppressUnmanagedCodeSecurity]
+ void FreeColumn([In] IntPtr pSearchColumn);
- [SuppressUnmanagedCodeSecurityAttribute()]
+ [SuppressUnmanagedCodeSecurity]
void CloseSearchHandle([In] IntPtr hSearchResult);
}
+ [ComImport, Guid("46F14FDA-232B-11D1-A808-00C04FD8D5A8")]
public interface IAdsObjectOptions
{
object GetOption(int flag);
- [SuppressUnmanagedCodeSecurityAttribute()]
+ [SuppressUnmanagedCodeSecurity]
void SetOption(int flag, [In] object varValue);
}
- // for boolean type, the default marshaller does not work, so need to have specific marshaller. For other types, use the
- // default marshaller which is more efficient
-
+ /// <summary>
+ /// For boolean type, the default marshaller does not work, so need to have specific marshaller. For other types, use the
+ /// default marshaller which is more efficient. There is no such interface on the type library this is the same as IAdsObjectOptions
+ /// with a different signature.
+ /// </summary>
+ [ComImport, Guid("46F14FDA-232B-11D1-A808-00C04FD8D5A8")]
public interface IAdsObjectOptions2
{
- [SuppressUnmanagedCodeSecurityAttribute()]
+ [SuppressUnmanagedCodeSecurity]
[PreserveSig]
int GetOption(int flag, [Out] out object value);
- [SuppressUnmanagedCodeSecurityAttribute()]
+ [SuppressUnmanagedCodeSecurity]
void SetOption(int option, Variant value);
}
@@ -504,4 +443,3 @@ namespace System.DirectoryServices.Interop
internal const int SIZE_LIMIT_EXCEEDED = unchecked((int)0x80072023);
}
}
-
diff --git a/src/System.DirectoryServices/src/System.DirectoryServices.csproj b/src/System.DirectoryServices/src/System.DirectoryServices.csproj
index bb6f01fa4f..a3bfc8e80a 100644
--- a/src/System.DirectoryServices/src/System.DirectoryServices.csproj
+++ b/src/System.DirectoryServices/src/System.DirectoryServices.csproj
@@ -19,7 +19,6 @@
</ItemGroup>
<ItemGroup Condition="'$(TargetsWindows)' == 'true'">
<Compile Include="System\DirectoryServices\externdll.cs" />
- <Compile Include="System\DirectoryServices\PrivilegedConfigurationManager.cs" />
<Compile Include="System\DirectoryServices\ActiveDirectorySecurity.cs" />
<Compile Include="System\DirectoryServices\AdsVLV.cs" />
<Compile Include="System\DirectoryServices\AuthenticationTypes.cs" />
@@ -47,7 +46,6 @@
<Compile Include="System\DirectoryServices\SearchResult.cs" />
<Compile Include="System\DirectoryServices\SearchResultCollection.cs" />
<Compile Include="System\DirectoryServices\SearchScope.cs" />
- <Compile Include="System\DirectoryServices\SearchWaitHandler.cs" />
<Compile Include="System\DirectoryServices\SecurityMasks.cs" />
<Compile Include="System\DirectoryServices\SortDirection.cs" />
<Compile Include="System\DirectoryServices\SortOption.cs" />
diff --git a/src/System.DirectoryServices/src/System/DirectoryServices/ActiveDirectory/ADAMInstance.cs b/src/System.DirectoryServices/src/System/DirectoryServices/ActiveDirectory/ADAMInstance.cs
index 57de6c187c..e410e13f92 100644
--- a/src/System.DirectoryServices/src/System/DirectoryServices/ActiveDirectory/ADAMInstance.cs
+++ b/src/System.DirectoryServices/src/System/DirectoryServices/ActiveDirectory/ADAMInstance.cs
@@ -2,20 +2,16 @@
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
+using System.Net;
+using System.Collections;
+using System.ComponentModel;
+using System.Runtime.InteropServices;
+
namespace System.DirectoryServices.ActiveDirectory
{
- using System;
- using System.Net;
- using System.Collections;
- using System.ComponentModel;
- using System.Runtime.InteropServices;
- using System.Threading;
- using System.Security.Permissions;
- using System.Globalization;
-
public class AdamInstance : DirectoryServer
{
- private string[] _becomeRoleOwnerAttrs = null;
+ private readonly string[] _becomeRoleOwnerAttrs = null;
private bool _disposed = false;
// for public properties
@@ -31,7 +27,7 @@ namespace System.DirectoryServices.ActiveDirectory
private IntPtr _ADAMHandle = (IntPtr)0;
private IntPtr _authIdentity = IntPtr.Zero;
private SyncUpdateCallback _userDelegate = null;
- private SyncReplicaFromAllServersCallback _syncAllFunctionPointer = null;
+ private readonly SyncReplicaFromAllServersCallback _syncAllFunctionPointer = null;
#region constructors
internal AdamInstance(DirectoryContext context, string adamInstanceName)
@@ -132,7 +128,7 @@ namespace System.DirectoryServices.ActiveDirectory
// target must be a server
if ((!context.isServer()))
{
- throw new ActiveDirectoryObjectNotFoundException(String.Format(CultureInfo.CurrentCulture, SR.AINotFound , context.Name), typeof(AdamInstance), context.Name);
+ throw new ActiveDirectoryObjectNotFoundException(SR.Format(SR.AINotFound , context.Name), typeof(AdamInstance), context.Name);
}
// work with copy of the context
@@ -147,7 +143,7 @@ namespace System.DirectoryServices.ActiveDirectory
// This will ensure that we are talking to ADAM instance only
if (!Utils.CheckCapability(rootDSE, Capability.ActiveDirectoryApplicationMode))
{
- throw new ActiveDirectoryObjectNotFoundException(String.Format(CultureInfo.CurrentCulture, SR.AINotFound , context.Name), typeof(AdamInstance), context.Name);
+ throw new ActiveDirectoryObjectNotFoundException(SR.Format(SR.AINotFound , context.Name), typeof(AdamInstance), context.Name);
}
dnsHostName = (string)PropertyManager.GetPropertyValue(context, rootDSE, PropertyManager.DnsHostName);
}
@@ -157,7 +153,7 @@ namespace System.DirectoryServices.ActiveDirectory
if (errorCode == unchecked((int)0x8007203a))
{
- throw new ActiveDirectoryObjectNotFoundException(String.Format(CultureInfo.CurrentCulture, SR.AINotFound , context.Name), typeof(AdamInstance), context.Name);
+ throw new ActiveDirectoryObjectNotFoundException(SR.Format(SR.AINotFound , context.Name), typeof(AdamInstance), context.Name);
}
else
{
@@ -664,7 +660,7 @@ namespace System.DirectoryServices.ActiveDirectory
// this adam instance
if (!Partitions.Contains(value))
{
- throw new ArgumentException(String.Format(CultureInfo.CurrentCulture, SR.ServerNotAReplica , value), "value");
+ throw new ArgumentException(SR.Format(SR.ServerNotAReplica , value), "value");
}
ntdsaEntry.Properties[PropertyManager.MsDSDefaultNamingContext].Value = value;
}
@@ -821,21 +817,9 @@ namespace System.DirectoryServices.ActiveDirectory
}
}
- public override ReplicationConnectionCollection InboundConnections
- {
- get
- {
- return GetInboundConnectionsHelper();
- }
- }
+ public override ReplicationConnectionCollection InboundConnections => GetInboundConnectionsHelper();
- public override ReplicationConnectionCollection OutboundConnections
- {
- get
- {
- return GetOutboundConnectionsHelper();
- }
- }
+ public override ReplicationConnectionCollection OutboundConnections => GetOutboundConnectionsHelper();
#endregion public properties
diff --git a/src/System.DirectoryServices/src/System/DirectoryServices/ActiveDirectory/ADAMInstanceCollection.cs b/src/System.DirectoryServices/src/System/DirectoryServices/ActiveDirectory/ADAMInstanceCollection.cs
index ba67320a7c..6924232d9a 100644
--- a/src/System.DirectoryServices/src/System/DirectoryServices/ActiveDirectory/ADAMInstanceCollection.cs
+++ b/src/System.DirectoryServices/src/System/DirectoryServices/ActiveDirectory/ADAMInstanceCollection.cs
@@ -2,12 +2,10 @@
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
+using System.Collections;
+
namespace System.DirectoryServices.ActiveDirectory
{
- using System;
- using System.Globalization;
- using System.Collections;
-
public class AdamInstanceCollection : ReadOnlyCollectionBase
{
internal AdamInstanceCollection() { }
@@ -20,13 +18,7 @@ namespace System.DirectoryServices.ActiveDirectory
}
}
- public AdamInstance this[int index]
- {
- get
- {
- return (AdamInstance)InnerList[index];
- }
- }
+ public AdamInstance this[int index] => (AdamInstance)InnerList[index];
public bool Contains(AdamInstance adamInstance)
{
diff --git a/src/System.DirectoryServices/src/System/DirectoryServices/ActiveDirectory/ADSearcher.cs b/src/System.DirectoryServices/src/System/DirectoryServices/ActiveDirectory/ADSearcher.cs
index 6744db670b..9f2dfea54d 100644
--- a/src/System.DirectoryServices/src/System/DirectoryServices/ActiveDirectory/ADSearcher.cs
+++ b/src/System.DirectoryServices/src/System/DirectoryServices/ActiveDirectory/ADSearcher.cs
@@ -2,15 +2,13 @@
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
+using System.Collections.Specialized;
+
namespace System.DirectoryServices.ActiveDirectory
{
- using System;
- using System.Collections.Specialized;
- using System.Security.Permissions;
-
internal class ADSearcher
{
- private DirectorySearcher _searcher = null;
+ private readonly DirectorySearcher _searcher = null;
private static TimeSpan s_defaultTimeSpan = new TimeSpan(0, 120, 0);
public ADSearcher(DirectoryEntry searchRoot, string filter, string[] propertiesToLoad, SearchScope scope)
@@ -40,49 +38,21 @@ namespace System.DirectoryServices.ActiveDirectory
_searcher.ServerPageTimeLimit = s_defaultTimeSpan;
}
- if (cacheResults)
- {
- _searcher.CacheResults = true;
- }
- else
- {
- _searcher.CacheResults = false;
- }
+ _searcher.CacheResults = cacheResults;
}
- public SearchResult FindOne()
- {
- return _searcher.FindOne();
- }
+ public SearchResult FindOne() => _searcher.FindOne();
- public SearchResultCollection FindAll()
- {
- return _searcher.FindAll();
- }
+ public SearchResultCollection FindAll() => _searcher.FindAll();
- public StringCollection PropertiesToLoad
- {
- get
- {
- return _searcher.PropertiesToLoad;
- }
- }
+ public StringCollection PropertiesToLoad => _searcher.PropertiesToLoad;
public string Filter
{
- get
- {
- return _searcher.Filter;
- }
- set
- {
- _searcher.Filter = value;
- }
+ get => _searcher.Filter;
+ set => _searcher.Filter = value;
}
- public void Dispose()
- {
- _searcher.Dispose();
- }
+ public void Dispose() => _searcher.Dispose();
}
}
diff --git a/src/System.DirectoryServices/src/System/DirectoryServices/ActiveDirectory/ActiveDirectoryInterSiteTransport.cs b/src/System.DirectoryServices/src/System/DirectoryServices/ActiveDirectory/ActiveDirectoryInterSiteTransport.cs
index b262485884..e8e01f1ac6 100644
--- a/src/System.DirectoryServices/src/System/DirectoryServices/ActiveDirectory/ActiveDirectoryInterSiteTransport.cs
+++ b/src/System.DirectoryServices/src/System/DirectoryServices/ActiveDirectory/ActiveDirectoryInterSiteTransport.cs
@@ -2,17 +2,11 @@
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
+using System.Runtime.InteropServices;
+using System.ComponentModel;
+
namespace System.DirectoryServices.ActiveDirectory
{
- using System;
- using System.Runtime.InteropServices;
- using System.Collections;
- using System.DirectoryServices;
- using System.Globalization;
- using System.ComponentModel;
- using System.Diagnostics;
- using System.Security.Permissions;
-
public class ActiveDirectoryInterSiteTransport : IDisposable
{
private DirectoryContext _context = null;
@@ -77,7 +71,7 @@ namespace System.DirectoryServices.ActiveDirectory
catch (ActiveDirectoryObjectNotFoundException)
{
// this is the case where the context is a config set and we could not find an ADAM instance in that config set
- throw new ActiveDirectoryOperationException(String.Format(CultureInfo.CurrentCulture, SR.ADAMInstanceNotFoundInConfigSet , context.Name));
+ throw new ActiveDirectoryOperationException(SR.Format(SR.ADAMInstanceNotFoundInConfigSet , context.Name));
}
try
@@ -95,7 +89,7 @@ namespace System.DirectoryServices.ActiveDirectory
throw new NotSupportedException(SR.NotSupportTransportSMTP);
}
- throw new ActiveDirectoryObjectNotFoundException(String.Format(CultureInfo.CurrentCulture, SR.TransportNotFound , transport.ToString()), typeof(ActiveDirectoryInterSiteTransport), transport.ToString());
+ throw new ActiveDirectoryObjectNotFoundException(SR.Format(SR.TransportNotFound , transport.ToString()), typeof(ActiveDirectoryInterSiteTransport), transport.ToString());
}
else
throw ExceptionHelper.GetExceptionFromCOMException(context, e);
diff --git a/src/System.DirectoryServices/src/System/DirectoryServices/ActiveDirectory/ActiveDirectoryPartition.cs b/src/System.DirectoryServices/src/System/DirectoryServices/ActiveDirectory/ActiveDirectoryPartition.cs
index 20042bb687..330e5ebb97 100644
--- a/src/System.DirectoryServices/src/System/DirectoryServices/ActiveDirectory/ActiveDirectoryPartition.cs
+++ b/src/System.DirectoryServices/src/System/DirectoryServices/ActiveDirectory/ActiveDirectoryPartition.cs
@@ -4,12 +4,6 @@
namespace System.DirectoryServices.ActiveDirectory
{
- using System;
- using System.Collections;
- using System.Globalization;
- using System.Runtime.InteropServices;
- using System.Security.Permissions;
-
public abstract class ActiveDirectoryPartition : IDisposable
{
private bool _disposed = false;
@@ -57,10 +51,7 @@ namespace System.DirectoryServices.ActiveDirectory
#endregion IDisposable
#region public methods
- public override string ToString()
- {
- return Name;
- }
+ public override string ToString() => Name;
public abstract DirectoryEntry GetDirectoryEntry();
diff --git a/src/System.DirectoryServices/src/System/DirectoryServices/ActiveDirectory/ActiveDirectoryReplicationMetaData.cs b/src/System.DirectoryServices/src/System/DirectoryServices/ActiveDirectory/ActiveDirectoryReplicationMetaData.cs
index 679530df3c..7ab7cccf23 100644
--- a/src/System.DirectoryServices/src/System/DirectoryServices/ActiveDirectory/ActiveDirectoryReplicationMetaData.cs
+++ b/src/System.DirectoryServices/src/System/DirectoryServices/ActiveDirectory/ActiveDirectoryReplicationMetaData.cs
@@ -2,20 +2,16 @@
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
+using System.Collections;
+using System.Runtime.InteropServices;
+using System.Globalization;
+
namespace System.DirectoryServices.ActiveDirectory
{
- using System;
- using System.Collections;
- using System.Runtime.InteropServices;
- using System.Diagnostics;
- using System.Globalization;
-
public class ActiveDirectoryReplicationMetadata : DictionaryBase
{
- private DirectoryServer _server = null;
- private Hashtable _nameTable = null;
- private AttributeMetadataCollection _dataValueCollection = new AttributeMetadataCollection();
- private ReadOnlyStringCollection _dataNameCollection = new ReadOnlyStringCollection();
+ private readonly DirectoryServer _server = null;
+ private readonly Hashtable _nameTable = null;
internal ActiveDirectoryReplicationMetadata(DirectoryServer server)
{
@@ -38,21 +34,9 @@ namespace System.DirectoryServices.ActiveDirectory
}
}
- public ReadOnlyStringCollection AttributeNames
- {
- get
- {
- return _dataNameCollection;
- }
- }
+ public ReadOnlyStringCollection AttributeNames { get; } = new ReadOnlyStringCollection();
- public AttributeMetadataCollection Values
- {
- get
- {
- return _dataValueCollection;
- }
- }
+ public AttributeMetadataCollection Values { get; } = new AttributeMetadataCollection();
public bool Contains(string attributeName)
{
@@ -60,10 +44,6 @@ namespace System.DirectoryServices.ActiveDirectory
return Dictionary.Contains(tempName);
}
- /// <include file='doc\ResultPropertyCollection.uex' path='docs/doc[@for="ResultPropertyCollection.CopyTo"]/*' />
- /// <devdoc>
- /// <para>[To be supplied.]</para>
- /// </devdoc>
public void CopyTo(AttributeMetadata[] array, int index)
{
Dictionary.Values.CopyTo((Array)array, index);
@@ -73,8 +53,8 @@ namespace System.DirectoryServices.ActiveDirectory
{
Dictionary.Add(name.ToLower(CultureInfo.InvariantCulture), value);
- _dataNameCollection.Add(name);
- _dataValueCollection.Add(value);
+ AttributeNames.Add(name);
+ Values.Add(value);
}
internal void AddHelper(int count, IntPtr info, bool advanced)
diff --git a/src/System.DirectoryServices/src/System/DirectoryServices/ActiveDirectory/ActiveDirectorySchedule.cs b/src/System.DirectoryServices/src/System/DirectoryServices/ActiveDirectory/ActiveDirectorySchedule.cs
index 5ca73910a0..fd3a02d4cd 100644
--- a/src/System.DirectoryServices/src/System/DirectoryServices/ActiveDirectory/ActiveDirectorySchedule.cs
+++ b/src/System.DirectoryServices/src/System/DirectoryServices/ActiveDirectory/ActiveDirectorySchedule.cs
@@ -2,15 +2,10 @@
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
+using System.ComponentModel;
+
namespace System.DirectoryServices.ActiveDirectory
{
- using System;
- using System.Runtime.InteropServices;
- using System.Collections;
- using System.DirectoryServices;
- using System.Globalization;
- using System.ComponentModel;
-
public enum HourOfDay
{
Zero,
@@ -50,8 +45,8 @@ namespace System.DirectoryServices.ActiveDirectory
public class ActiveDirectorySchedule
{
// 24*7*4 = 672
- private bool[] _scheduleArray = new bool[672];
- private long _utcOffSet = 0;
+ private readonly bool[] _scheduleArray = new bool[672];
+ private readonly long _utcOffSet = 0;
public ActiveDirectorySchedule()
{
diff --git a/src/System.DirectoryServices/src/System/DirectoryServices/ActiveDirectory/ActiveDirectorySchema.cs b/src/System.DirectoryServices/src/System/DirectoryServices/ActiveDirectory/ActiveDirectorySchema.cs
index 99e19e8c02..c3937c6e1b 100644
--- a/src/System.DirectoryServices/src/System/DirectoryServices/ActiveDirectory/ActiveDirectorySchema.cs
+++ b/src/System.DirectoryServices/src/System/DirectoryServices/ActiveDirectory/ActiveDirectorySchema.cs
@@ -2,16 +2,13 @@
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
+using System.Text;
+using System.Collections;
+using System.ComponentModel;
+using System.Runtime.InteropServices;
+
namespace System.DirectoryServices.ActiveDirectory
{
- using System;
- using System.Text;
- using System.Collections;
- using System.ComponentModel;
- using System.Runtime.InteropServices;
- using System.Security.Permissions;
- using System.Globalization;
-
public enum SchemaClassType : int
{
Type88 = 0,
@@ -123,7 +120,7 @@ namespace System.DirectoryServices.ActiveDirectory
}
else
{
- throw new ActiveDirectoryObjectNotFoundException(String.Format(CultureInfo.CurrentCulture, SR.ServerNotFound , context.Name), typeof(ActiveDirectorySchema), null);
+ throw new ActiveDirectoryObjectNotFoundException(SR.Format(SR.ServerNotFound , context.Name), typeof(ActiveDirectorySchema), null);
}
}
}
@@ -139,7 +136,7 @@ namespace System.DirectoryServices.ActiveDirectory
if ((context.isServer()) && (!Utils.CheckCapability(rootDSE, Capability.ActiveDirectoryOrADAM)))
{
- throw new ActiveDirectoryObjectNotFoundException(String.Format(CultureInfo.CurrentCulture, SR.ServerNotFound , context.Name), typeof(ActiveDirectorySchema), null);
+ throw new ActiveDirectoryObjectNotFoundException(SR.Format(SR.ServerNotFound , context.Name), typeof(ActiveDirectorySchema), null);
}
schemaNC = (string)PropertyManager.GetPropertyValue(context, rootDSE, PropertyManager.SchemaNamingContext);
@@ -160,7 +157,7 @@ namespace System.DirectoryServices.ActiveDirectory
}
else
{
- throw new ActiveDirectoryObjectNotFoundException(String.Format(CultureInfo.CurrentCulture, SR.ServerNotFound , context.Name), typeof(ActiveDirectorySchema), null);
+ throw new ActiveDirectoryObjectNotFoundException(SR.Format(SR.ServerNotFound , context.Name), typeof(ActiveDirectorySchema), null);
}
}
else
diff --git a/src/System.DirectoryServices/src/System/DirectoryServices/ActiveDirectory/ActiveDirectorySchemaClass.cs b/src/System.DirectoryServices/src/System/DirectoryServices/ActiveDirectory/ActiveDirectorySchemaClass.cs
index 248dce42e8..1328706b01 100644
--- a/src/System.DirectoryServices/src/System/DirectoryServices/ActiveDirectory/ActiveDirectorySchemaClass.cs
+++ b/src/System.DirectoryServices/src/System/DirectoryServices/ActiveDirectory/ActiveDirectorySchemaClass.cs
@@ -2,18 +2,16 @@
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
+using System.Text;
+using System.ComponentModel;
+using System.Collections;
+using System.Diagnostics;
+using System.Globalization;
+using System.Runtime.InteropServices;
+using System.Security.AccessControl;
+
namespace System.DirectoryServices.ActiveDirectory
{
- using System;
- using System.Text;
- using System.ComponentModel;
- using System.Collections;
- using System.Diagnostics;
- using System.Globalization;
- using System.Runtime.InteropServices;
- using System.Security.AccessControl;
- using System.Security.Permissions;
-
public class ActiveDirectorySchemaClass : IDisposable
{
// private variables
@@ -131,7 +129,7 @@ namespace System.DirectoryServices.ActiveDirectory
catch (ActiveDirectoryObjectNotFoundException)
{
// this is the case where the context is a config set and we could not find an ADAM instance in that config set
- throw new ActiveDirectoryOperationException(String.Format(CultureInfo.CurrentCulture, SR.ADAMInstanceNotFoundInConfigSet , context.Name));
+ throw new ActiveDirectoryOperationException(SR.Format(SR.ADAMInstanceNotFoundInConfigSet , context.Name));
}
// set the bind flag
@@ -308,7 +306,7 @@ namespace System.DirectoryServices.ActiveDirectory
catch (ActiveDirectoryObjectNotFoundException)
{
// this is the case where the context is a config set and we could not find an ADAM instance in that config set
- throw new ActiveDirectoryOperationException(String.Format(CultureInfo.CurrentCulture, SR.ADAMInstanceNotFoundInConfigSet , _context.Name));
+ throw new ActiveDirectoryOperationException(SR.Format(SR.ADAMInstanceNotFoundInConfigSet , _context.Name));
}
// set the ldap display name property
@@ -1098,7 +1096,7 @@ namespace System.DirectoryServices.ActiveDirectory
Debug.Assert(values != null);
if (values.Count < 1 && mustExist)
{
- throw new ActiveDirectoryOperationException(String.Format(CultureInfo.CurrentCulture, SR.PropertyNotFound , propertyName));
+ throw new ActiveDirectoryOperationException(SR.Format(SR.PropertyNotFound , propertyName));
}
else if (values.Count > 0)
{
diff --git a/src/System.DirectoryServices/src/System/DirectoryServices/ActiveDirectory/ActiveDirectorySchemaClassCollection.cs b/src/System.DirectoryServices/src/System/DirectoryServices/ActiveDirectory/ActiveDirectorySchemaClassCollection.cs
index 5779b16758..1cf1e3780c 100644
--- a/src/System.DirectoryServices/src/System/DirectoryServices/ActiveDirectory/ActiveDirectorySchemaClassCollection.cs
+++ b/src/System.DirectoryServices/src/System/DirectoryServices/ActiveDirectory/ActiveDirectorySchemaClassCollection.cs
@@ -2,20 +2,18 @@
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
+using System.Collections;
+using System.Runtime.InteropServices;
+
namespace System.DirectoryServices.ActiveDirectory
{
- using System;
- using System.Collections;
- using System.Globalization;
- using System.Runtime.InteropServices;
-
public class ActiveDirectorySchemaClassCollection : CollectionBase
{
private DirectoryEntry _classEntry = null;
- private string _propertyName = null;
- private ActiveDirectorySchemaClass _schemaClass = null;
- private bool _isBound = false;
- private DirectoryContext _context = null;
+ private readonly string _propertyName = null;
+ private readonly ActiveDirectorySchemaClass _schemaClass = null;
+ private readonly bool _isBound = false;
+ private readonly DirectoryContext _context = null;
internal ActiveDirectorySchemaClassCollection(DirectoryContext context,
ActiveDirectorySchemaClass schemaClass,
@@ -33,7 +31,7 @@ namespace System.DirectoryServices.ActiveDirectory
{
// all properties in writeable class collection are non-defunct
// so calling constructor for non-defunct class
- this.InnerList.Add(new ActiveDirectorySchemaClass(context, ldapDisplayName, (DirectoryEntry)null, null));
+ InnerList.Add(new ActiveDirectorySchemaClass(context, ldapDisplayName, (DirectoryEntry)null, null));
}
}
@@ -50,24 +48,23 @@ namespace System.DirectoryServices.ActiveDirectory
foreach (ActiveDirectorySchemaClass schClass in classes)
{
- this.InnerList.Add(schClass);
+ InnerList.Add(schClass);
}
}
public ActiveDirectorySchemaClass this[int index]
{
- get
- {
- return (ActiveDirectorySchemaClass)List[index];
- }
+ get => (ActiveDirectorySchemaClass)List[index];
set
{
if (value == null)
- throw new ArgumentNullException("value");
+ {
+ throw new ArgumentNullException(nameof(value));
+ }
if (!value.isBound)
{
- throw new InvalidOperationException(String.Format(CultureInfo.CurrentCulture, SR.SchemaObjectNotCommitted , value.Name));
+ throw new InvalidOperationException(SR.Format(SR.SchemaObjectNotCommitted , value.Name));
}
if (!Contains(value))
@@ -76,7 +73,7 @@ namespace System.DirectoryServices.ActiveDirectory
}
else
{
- throw new ArgumentException(String.Format(CultureInfo.CurrentCulture, SR.AlreadyExistingInCollection , value), "value");
+ throw new ArgumentException(SR.Format(SR.AlreadyExistingInCollection , value), nameof(value));
}
}
}
@@ -85,12 +82,12 @@ namespace System.DirectoryServices.ActiveDirectory
{
if (schemaClass == null)
{
- throw new ArgumentNullException("schemaClass");
+ throw new ArgumentNullException(nameof(schemaClass));
}
if (!schemaClass.isBound)
{
- throw new InvalidOperationException(String.Format(CultureInfo.CurrentCulture, SR.SchemaObjectNotCommitted , schemaClass.Name));
+ throw new InvalidOperationException(SR.Format(SR.SchemaObjectNotCommitted , schemaClass.Name));
}
if (!Contains(schemaClass))
@@ -99,7 +96,7 @@ namespace System.DirectoryServices.ActiveDirectory
}
else
{
- throw new ArgumentException(String.Format(CultureInfo.CurrentCulture, SR.AlreadyExistingInCollection , schemaClass), "schemaClass");
+ throw new ArgumentException(SR.Format(SR.AlreadyExistingInCollection , schemaClass), nameof(schemaClass));
}
}
@@ -107,20 +104,20 @@ namespace System.DirectoryServices.ActiveDirectory
{
if (schemaClasses == null)
{
- throw new ArgumentNullException("schemaClasses");
+ throw new ArgumentNullException(nameof(schemaClasses));
}
foreach (ActiveDirectorySchemaClass schemaClass in schemaClasses)
{
if (schemaClass == null)
{
- throw new ArgumentException("schemaClasses");
+ throw new ArgumentException(nameof(schemaClasses));
}
}
for (int i = 0; ((i) < (schemaClasses.Length)); i = ((i) + (1)))
{
- this.Add((ActiveDirectorySchemaClass)schemaClasses[i]);
+ Add(schemaClasses[i]);
}
}
@@ -128,21 +125,21 @@ namespace System.DirectoryServices.ActiveDirectory
{
if (schemaClasses == null)
{
- throw new ArgumentNullException("schemaClasses");
+ throw new ArgumentNullException(nameof(schemaClasses));
}
foreach (ActiveDirectorySchemaClass schemaClass in schemaClasses)
{
if (schemaClass == null)
{
- throw new ArgumentException("schemaClasses");
+ throw new ArgumentException(nameof(schemaClasses));
}
}
int currentCount = schemaClasses.Count;
for (int i = 0; i < currentCount; i++)
{
- this.Add(schemaClasses[i]);
+ Add(schemaClasses[i]);
}
}
@@ -150,21 +147,21 @@ namespace System.DirectoryServices.ActiveDirectory
{
if (schemaClasses == null)
{
- throw new ArgumentNullException("schemaClasses");
+ throw new ArgumentNullException(nameof(schemaClasses));
}
foreach (ActiveDirectorySchemaClass schemaClass in schemaClasses)
{
if (schemaClass == null)
{
- throw new ArgumentException("schemaClasses");
+ throw new ArgumentException(nameof(schemaClasses));
}
}
int currentCount = schemaClasses.Count;
for (int i = 0; i < currentCount; i++)
{
- this.Add(schemaClasses[i]);
+ Add(schemaClasses[i]);
}
}
@@ -172,12 +169,12 @@ namespace System.DirectoryServices.ActiveDirectory
{
if (schemaClass == null)
{
- throw new ArgumentNullException("schemaClass");
+ throw new ArgumentNullException(nameof(schemaClass));
}
if (!schemaClass.isBound)
{
- throw new InvalidOperationException(String.Format(CultureInfo.CurrentCulture, SR.SchemaObjectNotCommitted , schemaClass.Name));
+ throw new InvalidOperationException(SR.Format(SR.SchemaObjectNotCommitted , schemaClass.Name));
}
for (int i = 0; i < InnerList.Count; i++)
@@ -189,19 +186,19 @@ namespace System.DirectoryServices.ActiveDirectory
return;
}
}
- throw new ArgumentException(String.Format(CultureInfo.CurrentCulture, SR.NotFoundInCollection , schemaClass), "schemaClass");
+ throw new ArgumentException(SR.Format(SR.NotFoundInCollection , schemaClass), nameof(schemaClass));
}
public void Insert(int index, ActiveDirectorySchemaClass schemaClass)
{
if (schemaClass == null)
{
- throw new ArgumentNullException("schemaClass");
+ throw new ArgumentNullException(nameof(schemaClass));
}
if (!schemaClass.isBound)
{
- throw new InvalidOperationException(String.Format(CultureInfo.CurrentCulture, SR.SchemaObjectNotCommitted , schemaClass.Name));
+ throw new InvalidOperationException(SR.Format(SR.SchemaObjectNotCommitted , schemaClass.Name));
}
if (!Contains(schemaClass))
@@ -210,7 +207,7 @@ namespace System.DirectoryServices.ActiveDirectory
}
else
{
- throw new ArgumentException(String.Format(CultureInfo.CurrentCulture, SR.AlreadyExistingInCollection , schemaClass), "schemaClass");
+ throw new ArgumentException(SR.Format(SR.AlreadyExistingInCollection , schemaClass), nameof(schemaClass));
}
}
@@ -218,12 +215,12 @@ namespace System.DirectoryServices.ActiveDirectory
{
if (schemaClass == null)
{
- throw new ArgumentNullException("schemaClass");
+ throw new ArgumentNullException(nameof(schemaClass));
}
if (!schemaClass.isBound)
{
- throw new InvalidOperationException(String.Format(CultureInfo.CurrentCulture, SR.SchemaObjectNotCommitted , schemaClass.Name));
+ throw new InvalidOperationException(SR.Format(SR.SchemaObjectNotCommitted , schemaClass.Name));
}
for (int i = 0; i < InnerList.Count; i++)
@@ -234,6 +231,7 @@ namespace System.DirectoryServices.ActiveDirectory
return true;
}
}
+
return false;
}
@@ -245,11 +243,13 @@ namespace System.DirectoryServices.ActiveDirectory
public int IndexOf(ActiveDirectorySchemaClass schemaClass)
{
if (schemaClass == null)
- throw new ArgumentNullException("schemaClass");
+ {
+ throw new ArgumentNullException(nameof(schemaClass));
+ }
if (!schemaClass.isBound)
{
- throw new InvalidOperationException(String.Format(CultureInfo.CurrentCulture, SR.SchemaObjectNotCommitted , schemaClass.Name));
+ throw new InvalidOperationException(SR.Format(SR.SchemaObjectNotCommitted , schemaClass.Name));
}
for (int i = 0; i < InnerList.Count; i++)
@@ -260,6 +260,7 @@ namespace System.DirectoryServices.ActiveDirectory
return i;
}
}
+
return -1;
}
@@ -350,15 +351,20 @@ namespace System.DirectoryServices.ActiveDirectory
}
}
- protected override void OnValidate(Object value)
+ protected override void OnValidate(object value)
{
- if (value == null) throw new ArgumentNullException("value");
+ if (value == null)
+ {
+ throw new ArgumentNullException(nameof(value));
+ }
if (!(value is ActiveDirectorySchemaClass))
- throw new ArgumentException("value");
+ {
+ throw new ArgumentException(nameof(value));
+ }
if (!((ActiveDirectorySchemaClass)value).isBound)
- throw new InvalidOperationException(String.Format(CultureInfo.CurrentCulture, SR.SchemaObjectNotCommitted , ((ActiveDirectorySchemaClass)value).Name));
+ throw new InvalidOperationException(SR.Format(SR.SchemaObjectNotCommitted , ((ActiveDirectorySchemaClass)value).Name));
}
internal string[] GetMultiValuedProperty()
diff --git a/src/System.DirectoryServices/src/System/DirectoryServices/ActiveDirectory/ActiveDirectorySchemaProperty.cs b/src/System.DirectoryServices/src/System/DirectoryServices/ActiveDirectory/ActiveDirectorySchemaProperty.cs
index 25e5375190..33f3532c25 100644
--- a/src/System.DirectoryServices/src/System/DirectoryServices/ActiveDirectory/ActiveDirectorySchemaProperty.cs
+++ b/src/System.DirectoryServices/src/System/DirectoryServices/ActiveDirectory/ActiveDirectorySchemaProperty.cs
@@ -2,16 +2,13 @@
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
+using System.Text;
+using System.Diagnostics;
+using System.ComponentModel;
+using System.Runtime.InteropServices;
+
namespace System.DirectoryServices.ActiveDirectory
{
- using System;
- using System.Text;
- using System.Diagnostics;
- using System.Globalization;
- using System.ComponentModel;
- using System.Runtime.InteropServices;
- using System.Security.Permissions;
-
internal enum SearchFlags : int
{
None = 0,
@@ -186,7 +183,7 @@ namespace System.DirectoryServices.ActiveDirectory
catch (ActiveDirectoryObjectNotFoundException)
{
// this is the case where the context is a config set and we could not find an ADAM instance in that config set
- throw new ActiveDirectoryOperationException(String.Format(CultureInfo.CurrentCulture, SR.ADAMInstanceNotFoundInConfigSet , context.Name));
+ throw new ActiveDirectoryOperationException(SR.Format(SR.ADAMInstanceNotFoundInConfigSet , context.Name));
}
// set the bind flag
@@ -351,7 +348,7 @@ namespace System.DirectoryServices.ActiveDirectory
catch (ActiveDirectoryObjectNotFoundException)
{
// this is the case where the context is a config set and we could not find an ADAM instance in that config set
- throw new ActiveDirectoryOperationException(String.Format(CultureInfo.CurrentCulture, SR.ADAMInstanceNotFoundInConfigSet , _context.Name));
+ throw new ActiveDirectoryOperationException(SR.Format(SR.ADAMInstanceNotFoundInConfigSet , _context.Name));
}
// set the ldap display name property
@@ -480,10 +477,7 @@ namespace System.DirectoryServices.ActiveDirectory
isBound = true;
}
- public override string ToString()
- {
- return Name;
- }
+ public override string ToString() => Name;
public DirectoryEntry GetDirectoryEntry()
{
@@ -1018,7 +1012,7 @@ namespace System.DirectoryServices.ActiveDirectory
if (linkedProperties.Count != 1)
{
- throw new ActiveDirectoryObjectNotFoundException(String.Format(CultureInfo.CurrentCulture, SR.LinkedPropertyNotFound , linkIdToSearch), typeof(ActiveDirectorySchemaProperty), null);
+ throw new ActiveDirectoryObjectNotFoundException(SR.Format(SR.LinkedPropertyNotFound , linkIdToSearch), typeof(ActiveDirectorySchemaProperty), null);
}
_linkedProperty = linkedProperties[0];
@@ -1155,7 +1149,7 @@ namespace System.DirectoryServices.ActiveDirectory
{
if (mustExist)
{
- throw new ActiveDirectoryOperationException(String.Format(CultureInfo.CurrentCulture, SR.PropertyNotFound , propertyName));
+ throw new ActiveDirectoryOperationException(SR.Format(SR.PropertyNotFound , propertyName));
}
}
else
@@ -1423,7 +1417,7 @@ namespace System.DirectoryServices.ActiveDirectory
return (ActiveDirectorySyntax)i;
}
}
- throw new ActiveDirectoryOperationException(String.Format(CultureInfo.CurrentCulture, SR.UnknownSyntax , _ldapDisplayName));
+ throw new ActiveDirectoryOperationException(SR.Format(SR.UnknownSyntax , _ldapDisplayName));
}
private void SetSyntax(ActiveDirectorySyntax syntax)
diff --git a/src/System.DirectoryServices/src/System/DirectoryServices/ActiveDirectory/ActiveDirectorySchemaPropertyCollection.cs b/src/System.DirectoryServices/src/System/DirectoryServices/ActiveDirectory/ActiveDirectorySchemaPropertyCollection.cs
index 67918f7a56..d83536ae47 100644
--- a/src/System.DirectoryServices/src/System/DirectoryServices/ActiveDirectory/ActiveDirectorySchemaPropertyCollection.cs
+++ b/src/System.DirectoryServices/src/System/DirectoryServices/ActiveDirectory/ActiveDirectorySchemaPropertyCollection.cs
@@ -2,20 +2,18 @@
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
+using System.Collections;
+using System.Runtime.InteropServices;
+
namespace System.DirectoryServices.ActiveDirectory
{
- using System;
- using System.Collections;
- using System.Globalization;
- using System.Runtime.InteropServices;
-
public class ActiveDirectorySchemaPropertyCollection : CollectionBase
{
private DirectoryEntry _classEntry = null;
- private string _propertyName = null;
- private ActiveDirectorySchemaClass _schemaClass = null;
- private bool _isBound = false;
- private DirectoryContext _context = null;
+ private readonly string _propertyName = null;
+ private readonly ActiveDirectorySchemaClass _schemaClass = null;
+ private readonly bool _isBound = false;
+ private readonly DirectoryContext _context = null;
internal ActiveDirectorySchemaPropertyCollection(DirectoryContext context,
ActiveDirectorySchemaClass schemaClass,
@@ -56,10 +54,7 @@ namespace System.DirectoryServices.ActiveDirectory
public ActiveDirectorySchemaProperty this[int index]
{
- get
- {
- return (ActiveDirectorySchemaProperty)List[index];
- }
+ get => (ActiveDirectorySchemaProperty)List[index];
set
{
if (value == null)
@@ -67,7 +62,7 @@ namespace System.DirectoryServices.ActiveDirectory
if (!value.isBound)
{
- throw new InvalidOperationException(String.Format(CultureInfo.CurrentCulture, SR.SchemaObjectNotCommitted , value.Name));
+ throw new InvalidOperationException(SR.Format(SR.SchemaObjectNotCommitted , value.Name));
}
if (!Contains(value))
@@ -76,7 +71,7 @@ namespace System.DirectoryServices.ActiveDirectory
}
else
{
- throw new ArgumentException(String.Format(CultureInfo.CurrentCulture, SR.AlreadyExistingInCollection , value), "value");
+ throw new ArgumentException(SR.Format(SR.AlreadyExistingInCollection , value), "value");
}
}
}
@@ -90,7 +85,7 @@ namespace System.DirectoryServices.ActiveDirectory
if (!schemaProperty.isBound)
{
- throw new InvalidOperationException(String.Format(CultureInfo.CurrentCulture, SR.SchemaObjectNotCommitted , schemaProperty.Name));
+ throw new InvalidOperationException(SR.Format(SR.SchemaObjectNotCommitted , schemaProperty.Name));
}
if (!Contains(schemaProperty))
@@ -99,7 +94,7 @@ namespace System.DirectoryServices.ActiveDirectory
}
else
{
- throw new ArgumentException(String.Format(CultureInfo.CurrentCulture, SR.AlreadyExistingInCollection , schemaProperty), "schemaProperty");
+ throw new ArgumentException(SR.Format(SR.AlreadyExistingInCollection , schemaProperty), "schemaProperty");
}
}
@@ -179,7 +174,7 @@ namespace System.DirectoryServices.ActiveDirectory
if (!schemaProperty.isBound)
{
- throw new InvalidOperationException(String.Format(CultureInfo.CurrentCulture, SR.SchemaObjectNotCommitted , schemaProperty.Name));
+ throw new InvalidOperationException(SR.Format(SR.SchemaObjectNotCommitted , schemaProperty.Name));
}
for (int i = 0; i < InnerList.Count; i++)
@@ -191,7 +186,7 @@ namespace System.DirectoryServices.ActiveDirectory
return;
}
}
- throw new ArgumentException(String.Format(CultureInfo.CurrentCulture, SR.NotFoundInCollection , schemaProperty), "schemaProperty");
+ throw new ArgumentException(SR.Format(SR.NotFoundInCollection , schemaProperty), "schemaProperty");
}
public void Insert(int index, ActiveDirectorySchemaProperty schemaProperty)
@@ -203,7 +198,7 @@ namespace System.DirectoryServices.ActiveDirectory
if (!schemaProperty.isBound)
{
- throw new InvalidOperationException(String.Format(CultureInfo.CurrentCulture, SR.SchemaObjectNotCommitted , schemaProperty.Name));
+ throw new InvalidOperationException(SR.Format(SR.SchemaObjectNotCommitted , schemaProperty.Name));
}
if (!Contains(schemaProperty))
@@ -212,7 +207,7 @@ namespace System.DirectoryServices.ActiveDirectory
}
else
{
- throw new ArgumentException(String.Format(CultureInfo.CurrentCulture, SR.AlreadyExistingInCollection , schemaProperty), "schemaProperty");
+ throw new ArgumentException(SR.Format(SR.AlreadyExistingInCollection , schemaProperty), "schemaProperty");
}
}
@@ -225,7 +220,7 @@ namespace System.DirectoryServices.ActiveDirectory
if (!schemaProperty.isBound)
{
- throw new InvalidOperationException(String.Format(CultureInfo.CurrentCulture, SR.SchemaObjectNotCommitted , schemaProperty.Name));
+ throw new InvalidOperationException(SR.Format(SR.SchemaObjectNotCommitted , schemaProperty.Name));
}
for (int i = 0; i < InnerList.Count; i++)
@@ -268,7 +263,7 @@ namespace System.DirectoryServices.ActiveDirectory
if (!schemaProperty.isBound)
{
- throw new InvalidOperationException(String.Format(CultureInfo.CurrentCulture, SR.SchemaObjectNotCommitted , schemaProperty.Name));
+ throw new InvalidOperationException(SR.Format(SR.SchemaObjectNotCommitted , schemaProperty.Name));
}
for (int i = 0; i < InnerList.Count; i++)
@@ -377,7 +372,7 @@ namespace System.DirectoryServices.ActiveDirectory
throw new ArgumentException("value");
if (!((ActiveDirectorySchemaProperty)value).isBound)
- throw new InvalidOperationException(String.Format(CultureInfo.CurrentCulture, SR.SchemaObjectNotCommitted , ((ActiveDirectorySchemaProperty)value).Name));
+ throw new InvalidOperationException(SR.Format(SR.SchemaObjectNotCommitted , ((ActiveDirectorySchemaProperty)value).Name));
}
internal string[] GetMultiValuedProperty()
diff --git a/src/System.DirectoryServices/src/System/DirectoryServices/ActiveDirectory/ActiveDirectorySite.cs b/src/System.DirectoryServices/src/System/DirectoryServices/ActiveDirectory/ActiveDirectorySite.cs
index 607ab6ac27..a55fb92360 100644
--- a/src/System.DirectoryServices/src/System/DirectoryServices/ActiveDirectory/ActiveDirectorySite.cs
+++ b/src/System.DirectoryServices/src/System/DirectoryServices/ActiveDirectory/ActiveDirectorySite.cs
@@ -2,18 +2,13 @@
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
+using System.Runtime.InteropServices;
+using System.Collections;
+using System.Diagnostics;
+using System.Text;
+
namespace System.DirectoryServices.ActiveDirectory
{
- using System;
- using System.Runtime.InteropServices;
- using System.Collections;
- using System.DirectoryServices;
- using System.Diagnostics;
- using System.Globalization;
- using System.Text;
- using System.ComponentModel;
- using System.Security.Permissions;
-
[Flags]
public enum ActiveDirectorySiteOptions
{
@@ -33,21 +28,21 @@ namespace System.DirectoryServices.ActiveDirectory
public class ActiveDirectorySite : IDisposable
{
- internal DirectoryContext context = null;
- private string _name = null;
- internal DirectoryEntry cachedEntry = null;
+ internal readonly DirectoryContext context = null;
+ private readonly string _name = null;
+ internal readonly DirectoryEntry cachedEntry = null;
private DirectoryEntry _ntdsEntry = null;
- private ActiveDirectorySubnetCollection _subnets = null;
+ private readonly ActiveDirectorySubnetCollection _subnets = null;
private DirectoryServer _topologyGenerator = null;
- private ReadOnlySiteCollection _adjacentSites = new ReadOnlySiteCollection();
+ private readonly ReadOnlySiteCollection _adjacentSites = new ReadOnlySiteCollection();
private bool _disposed = false;
- private DomainCollection _domains = new DomainCollection(null);
- private ReadOnlyDirectoryServerCollection _servers = new ReadOnlyDirectoryServerCollection();
- private ReadOnlySiteLinkCollection _links = new ReadOnlySiteLinkCollection();
+ private readonly DomainCollection _domains = new DomainCollection(null);
+ private readonly ReadOnlyDirectoryServerCollection _servers = new ReadOnlyDirectoryServerCollection();
+ private readonly ReadOnlySiteLinkCollection _links = new ReadOnlySiteLinkCollection();
private ActiveDirectorySiteOptions _siteOptions = ActiveDirectorySiteOptions.None;
private ReadOnlyDirectoryServerCollection _bridgeheadServers = new ReadOnlyDirectoryServerCollection();
- private DirectoryServerCollection _SMTPBridgeheadServers = null;
- private DirectoryServerCollection _RPCBridgeheadServers = null;
+ private readonly DirectoryServerCollection _SMTPBridgeheadServers = null;
+ private readonly DirectoryServerCollection _RPCBridgeheadServers = null;
private byte[] _replicationSchedule = null;
internal bool existing = false;
@@ -90,7 +85,7 @@ namespace System.DirectoryServices.ActiveDirectory
catch (ActiveDirectoryObjectNotFoundException)
{
// this is the case where the context is a config set and we could not find an ADAM instance in that config set
- throw new ActiveDirectoryOperationException(String.Format(CultureInfo.CurrentCulture, SR.ADAMInstanceNotFoundInConfigSet , context.Name));
+ throw new ActiveDirectoryOperationException(SR.Format(SR.ADAMInstanceNotFoundInConfigSet , context.Name));
}
try
@@ -161,7 +156,7 @@ namespace System.DirectoryServices.ActiveDirectory
catch (ActiveDirectoryObjectNotFoundException)
{
// this is the case where the context is a config set and we could not find an ADAM instance in that config set
- throw new ActiveDirectoryOperationException(String.Format(CultureInfo.CurrentCulture, SR.ADAMInstanceNotFoundInConfigSet , context.Name));
+ throw new ActiveDirectoryOperationException(SR.Format(SR.ADAMInstanceNotFoundInConfigSet , context.Name));
}
finally
{
@@ -705,7 +700,7 @@ namespace System.DirectoryServices.ActiveDirectory
{
if (e.ErrorCode == unchecked((int)0x80072030))
{
- string message = String.Format(CultureInfo.CurrentCulture, SR.NTDSSiteSetting , _name);
+ string message = SR.Format(SR.NTDSSiteSetting , _name);
throw new ActiveDirectoryOperationException(message, e, 0x2030);
}
throw ExceptionHelper.GetExceptionFromCOMException(context, e);
@@ -1220,7 +1215,7 @@ namespace System.DirectoryServices.ActiveDirectory
else
{
// should not happen
- string message = String.Format(CultureInfo.CurrentCulture, SR.UnknownTransport , transportName);
+ string message = SR.Format(SR.UnknownTransport , transportName);
throw new ActiveDirectoryOperationException(message);
}
@@ -1287,7 +1282,7 @@ namespace System.DirectoryServices.ActiveDirectory
else
{
// should not happen
- string message = String.Format(CultureInfo.CurrentCulture, SR.UnknownTransport , transport);
+ string message = SR.Format(SR.UnknownTransport , transport);
throw new ActiveDirectoryOperationException(message);
}
diff --git a/src/System.DirectoryServices/src/System/DirectoryServices/ActiveDirectory/ActiveDirectorySiteCollection.cs b/src/System.DirectoryServices/src/System/DirectoryServices/ActiveDirectory/ActiveDirectorySiteCollection.cs
index 7816a11954..9c73f50e81 100644
--- a/src/System.DirectoryServices/src/System/DirectoryServices/ActiveDirectory/ActiveDirectorySiteCollection.cs
+++ b/src/System.DirectoryServices/src/System/DirectoryServices/ActiveDirectory/ActiveDirectorySiteCollection.cs
@@ -2,14 +2,11 @@
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
+using System.Runtime.InteropServices;
+using System.Collections;
+
namespace System.DirectoryServices.ActiveDirectory
{
- using System;
- using System.Runtime.InteropServices;
- using System.Collections;
- using System.DirectoryServices;
- using System.Globalization;
-
public class ActiveDirectorySiteCollection : CollectionBase
{
internal DirectoryEntry de = null;
@@ -26,10 +23,7 @@ namespace System.DirectoryServices.ActiveDirectory
public ActiveDirectorySite this[int index]
{
- get
- {
- return (ActiveDirectorySite)InnerList[index];
- }
+ get => (ActiveDirectorySite)InnerList[index];
set
{
ActiveDirectorySite site = (ActiveDirectorySite)value;
@@ -38,12 +32,12 @@ namespace System.DirectoryServices.ActiveDirectory
throw new ArgumentNullException("value");
if (!site.existing)
- throw new InvalidOperationException(String.Format(CultureInfo.CurrentCulture, SR.SiteNotCommitted , site.Name));
+ throw new InvalidOperationException(SR.Format(SR.SiteNotCommitted , site.Name));
if (!Contains(site))
List[index] = site;
else
- throw new ArgumentException(String.Format(CultureInfo.CurrentCulture, SR.AlreadyExistingInCollection , site), "value");
+ throw new ArgumentException(SR.Format(SR.AlreadyExistingInCollection , site), "value");
}
}
@@ -53,12 +47,12 @@ namespace System.DirectoryServices.ActiveDirectory
throw new ArgumentNullException("site");
if (!site.existing)
- throw new InvalidOperationException(String.Format(CultureInfo.CurrentCulture, SR.SiteNotCommitted , site.Name));
+ throw new InvalidOperationException(SR.Format(SR.SiteNotCommitted , site.Name));
if (!Contains(site))
return List.Add(site);
else
- throw new ArgumentException(String.Format(CultureInfo.CurrentCulture, SR.AlreadyExistingInCollection , site), "site");
+ throw new ArgumentException(SR.Format(SR.AlreadyExistingInCollection , site), "site");
}
public void AddRange(ActiveDirectorySite[] sites)
@@ -86,7 +80,7 @@ namespace System.DirectoryServices.ActiveDirectory
throw new ArgumentNullException("site");
if (!site.existing)
- throw new InvalidOperationException(String.Format(CultureInfo.CurrentCulture, SR.SiteNotCommitted , site.Name));
+ throw new InvalidOperationException(SR.Format(SR.SiteNotCommitted , site.Name));
string dn = (string)PropertyManager.GetPropertyValue(site.context, site.cachedEntry, PropertyManager.DistinguishedName);
@@ -114,7 +108,7 @@ namespace System.DirectoryServices.ActiveDirectory
throw new ArgumentNullException("site");
if (!site.existing)
- throw new InvalidOperationException(String.Format(CultureInfo.CurrentCulture, SR.SiteNotCommitted , site.Name));
+ throw new InvalidOperationException(SR.Format(SR.SiteNotCommitted , site.Name));
string dn = (string)PropertyManager.GetPropertyValue(site.context, site.cachedEntry, PropertyManager.DistinguishedName);
@@ -137,12 +131,12 @@ namespace System.DirectoryServices.ActiveDirectory
throw new ArgumentNullException("site");
if (!site.existing)
- throw new InvalidOperationException(String.Format(CultureInfo.CurrentCulture, SR.SiteNotCommitted , site.Name));
+ throw new InvalidOperationException(SR.Format(SR.SiteNotCommitted , site.Name));
if (!Contains(site))
List.Insert(index, site);
else
- throw new ArgumentException(String.Format(CultureInfo.CurrentCulture, SR.AlreadyExistingInCollection , site), "site");
+ throw new ArgumentException(SR.Format(SR.AlreadyExistingInCollection , site), "site");
}
public void Remove(ActiveDirectorySite site)
@@ -151,7 +145,7 @@ namespace System.DirectoryServices.ActiveDirectory
throw new ArgumentNullException("site");
if (!site.existing)
- throw new InvalidOperationException(String.Format(CultureInfo.CurrentCulture, SR.SiteNotCommitted , site.Name));
+ throw new InvalidOperationException(SR.Format(SR.SiteNotCommitted , site.Name));
string dn = (string)PropertyManager.GetPropertyValue(site.context, site.cachedEntry, PropertyManager.DistinguishedName);
@@ -168,7 +162,7 @@ namespace System.DirectoryServices.ActiveDirectory
}
// something that does not exist in the collectio
- throw new ArgumentException(String.Format(CultureInfo.CurrentCulture, SR.NotFoundInCollection , site), "site");
+ throw new ArgumentException(SR.Format(SR.NotFoundInCollection , site), "site");
}
protected override void OnClearComplete()
@@ -241,7 +235,7 @@ namespace System.DirectoryServices.ActiveDirectory
throw new ArgumentException("value");
if (!((ActiveDirectorySite)value).existing)
- throw new InvalidOperationException(String.Format(CultureInfo.CurrentCulture, SR.SiteNotCommitted , ((ActiveDirectorySite)value).Name));
+ throw new InvalidOperationException(SR.Format(SR.SiteNotCommitted , ((ActiveDirectorySite)value).Name));
}
}
}
diff --git a/src/System.DirectoryServices/src/System/DirectoryServices/ActiveDirectory/ActiveDirectorySiteLink.cs b/src/System.DirectoryServices/src/System/DirectoryServices/ActiveDirectory/ActiveDirectorySiteLink.cs
index a5e6ebf248..3780dac6b4 100644
--- a/src/System.DirectoryServices/src/System/DirectoryServices/ActiveDirectory/ActiveDirectorySiteLink.cs
+++ b/src/System.DirectoryServices/src/System/DirectoryServices/ActiveDirectory/ActiveDirectorySiteLink.cs
@@ -2,31 +2,28 @@
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
+using System.Runtime.InteropServices;
+using System.Collections;
+using System.Globalization;
+using System.ComponentModel;
+using System.Diagnostics;
+
namespace System.DirectoryServices.ActiveDirectory
{
- using System;
- using System.Runtime.InteropServices;
- using System.Collections;
- using System.DirectoryServices;
- using System.Globalization;
- using System.ComponentModel;
- using System.Diagnostics;
- using System.Security.Permissions;
-
public class ActiveDirectorySiteLink : IDisposable
{
- internal DirectoryContext context = null;
- private string _name = null;
- private ActiveDirectoryTransportType _transport = ActiveDirectoryTransportType.Rpc;
+ internal readonly DirectoryContext context = null;
+ private readonly string _name = null;
+ private readonly ActiveDirectoryTransportType _transport = ActiveDirectoryTransportType.Rpc;
private bool _disposed = false;
internal bool existing = false;
- internal DirectoryEntry cachedEntry = null;
+ internal readonly DirectoryEntry cachedEntry = null;
private const int systemDefaultCost = 0;
- private TimeSpan _systemDefaultInterval = new TimeSpan(0, 15, 0);
+ private readonly TimeSpan _systemDefaultInterval = new TimeSpan(0, 15, 0);
private const int appDefaultCost = 100;
private const int appDefaultInterval = 180;
- private ActiveDirectorySiteCollection _sites = new ActiveDirectorySiteCollection();
+ private readonly ActiveDirectorySiteCollection _sites = new ActiveDirectorySiteCollection();
private bool _siteRetrieved = false;
public ActiveDirectorySiteLink(DirectoryContext context, string siteLinkName) : this(context, siteLinkName, ActiveDirectoryTransportType.Rpc, null)
@@ -71,7 +68,7 @@ namespace System.DirectoryServices.ActiveDirectory
catch (ActiveDirectoryObjectNotFoundException)
{
// this is the case where the context is a config set and we could not find an ADAM instance in that config set
- throw new ActiveDirectoryOperationException(String.Format(CultureInfo.CurrentCulture, SR.ADAMInstanceNotFoundInConfigSet , context.Name));
+ throw new ActiveDirectoryOperationException(SR.Format(SR.ADAMInstanceNotFoundInConfigSet , context.Name));
}
try
@@ -146,7 +143,7 @@ namespace System.DirectoryServices.ActiveDirectory
catch (ActiveDirectoryObjectNotFoundException)
{
// this is the case where the context is a config set and we could not find an ADAM instance in that config set
- throw new ActiveDirectoryOperationException(String.Format(CultureInfo.CurrentCulture, SR.ADAMInstanceNotFoundInConfigSet , context.Name));
+ throw new ActiveDirectoryOperationException(SR.Format(SR.ADAMInstanceNotFoundInConfigSet , context.Name));
}
try
diff --git a/src/System.DirectoryServices/src/System/DirectoryServices/ActiveDirectory/ActiveDirectorySiteLinkBridge.cs b/src/System.DirectoryServices/src/System/DirectoryServices/ActiveDirectory/ActiveDirectorySiteLinkBridge.cs
index 7270b48070..ba8961fdae 100644
--- a/src/System.DirectoryServices/src/System/DirectoryServices/ActiveDirectory/ActiveDirectorySiteLinkBridge.cs
+++ b/src/System.DirectoryServices/src/System/DirectoryServices/ActiveDirectory/ActiveDirectorySiteLinkBridge.cs
@@ -2,27 +2,24 @@
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
+using System.Runtime.InteropServices;
+using System.Collections;
+using System.Globalization;
+using System.ComponentModel;
+using System.Diagnostics;
+
namespace System.DirectoryServices.ActiveDirectory
{
- using System;
- using System.Runtime.InteropServices;
- using System.Collections;
- using System.DirectoryServices;
- using System.Globalization;
- using System.ComponentModel;
- using System.Diagnostics;
- using System.Security.Permissions;
-
public class ActiveDirectorySiteLinkBridge : IDisposable
{
- internal DirectoryContext context = null;
- private string _name = null;
- private ActiveDirectoryTransportType _transport = ActiveDirectoryTransportType.Rpc;
+ internal readonly DirectoryContext context = null;
+ private readonly string _name = null;
+ private readonly ActiveDirectoryTransportType _transport = ActiveDirectoryTransportType.Rpc;
private bool _disposed = false;
private bool _existing = false;
internal DirectoryEntry cachedEntry = null;
- private ActiveDirectorySiteLinkCollection _links = new ActiveDirectorySiteLinkCollection();
+ private readonly ActiveDirectorySiteLinkCollection _links = new ActiveDirectorySiteLinkCollection();
private bool _linksRetrieved = false;
public ActiveDirectorySiteLinkBridge(DirectoryContext context, string bridgeName) : this(context, bridgeName, ActiveDirectoryTransportType.Rpc)
@@ -62,7 +59,7 @@ namespace System.DirectoryServices.ActiveDirectory
catch (ActiveDirectoryObjectNotFoundException)
{
// this is the case where the context is a config set and we could not find an ADAM instance in that config set
- throw new ActiveDirectoryOperationException(String.Format(CultureInfo.CurrentCulture, SR.ADAMInstanceNotFoundInConfigSet , context.Name));
+ throw new ActiveDirectoryOperationException(SR.Format(SR.ADAMInstanceNotFoundInConfigSet , context.Name));
}
try
@@ -133,7 +130,7 @@ namespace System.DirectoryServices.ActiveDirectory
catch (ActiveDirectoryObjectNotFoundException)
{
// this is the case where the context is a config set and we could not find an ADAM instance in that config set
- throw new ActiveDirectoryOperationException(String.Format(CultureInfo.CurrentCulture, SR.ADAMInstanceNotFoundInConfigSet , context.Name));
+ throw new ActiveDirectoryOperationException(SR.Format(SR.ADAMInstanceNotFoundInConfigSet , context.Name));
}
try
diff --git a/src/System.DirectoryServices/src/System/DirectoryServices/ActiveDirectory/ActiveDirectorySiteLinkCollection.cs b/src/System.DirectoryServices/src/System/DirectoryServices/ActiveDirectory/ActiveDirectorySiteLinkCollection.cs
index 2f0ddf3db1..3bc02ceb9f 100644
--- a/src/System.DirectoryServices/src/System/DirectoryServices/ActiveDirectory/ActiveDirectorySiteLinkCollection.cs
+++ b/src/System.DirectoryServices/src/System/DirectoryServices/ActiveDirectory/ActiveDirectorySiteLinkCollection.cs
@@ -2,14 +2,11 @@
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
+using System.Runtime.InteropServices;
+using System.Collections;
+
namespace System.DirectoryServices.ActiveDirectory
{
- using System;
- using System.Runtime.InteropServices;
- using System.Collections;
- using System.DirectoryServices;
- using System.Globalization;
-
public class ActiveDirectorySiteLinkCollection : CollectionBase
{
internal DirectoryEntry de = null;
@@ -20,10 +17,7 @@ namespace System.DirectoryServices.ActiveDirectory
public ActiveDirectorySiteLink this[int index]
{
- get
- {
- return (ActiveDirectorySiteLink)InnerList[index];
- }
+ get => (ActiveDirectorySiteLink)InnerList[index];
set
{
ActiveDirectorySiteLink link = (ActiveDirectorySiteLink)value;
@@ -32,12 +26,12 @@ namespace System.DirectoryServices.ActiveDirectory
throw new ArgumentNullException("value");
if (!link.existing)
- throw new InvalidOperationException(String.Format(CultureInfo.CurrentCulture, SR.SiteLinkNotCommitted , link.Name));
+ throw new InvalidOperationException(SR.Format(SR.SiteLinkNotCommitted , link.Name));
if (!Contains(link))
List[index] = link;
else
- throw new ArgumentException(String.Format(CultureInfo.CurrentCulture, SR.AlreadyExistingInCollection , link), "value");
+ throw new ArgumentException(SR.Format(SR.AlreadyExistingInCollection , link), "value");
}
}
@@ -47,12 +41,12 @@ namespace System.DirectoryServices.ActiveDirectory
throw new ArgumentNullException("link");
if (!link.existing)
- throw new InvalidOperationException(String.Format(CultureInfo.CurrentCulture, SR.SiteLinkNotCommitted , link.Name));
+ throw new InvalidOperationException(SR.Format(SR.SiteLinkNotCommitted , link.Name));
if (!Contains(link))
return List.Add(link);
else
- throw new ArgumentException(String.Format(CultureInfo.CurrentCulture, SR.AlreadyExistingInCollection , link), "link");
+ throw new ArgumentException(SR.Format(SR.AlreadyExistingInCollection , link), "link");
}
public void AddRange(ActiveDirectorySiteLink[] links)
@@ -80,7 +74,7 @@ namespace System.DirectoryServices.ActiveDirectory
throw new ArgumentNullException("link");
if (!link.existing)
- throw new InvalidOperationException(String.Format(CultureInfo.CurrentCulture, SR.SiteLinkNotCommitted , link.Name));
+ throw new InvalidOperationException(SR.Format(SR.SiteLinkNotCommitted , link.Name));
string dn = (string)PropertyManager.GetPropertyValue(link.context, link.cachedEntry, PropertyManager.DistinguishedName);
@@ -108,7 +102,7 @@ namespace System.DirectoryServices.ActiveDirectory
throw new ArgumentNullException("link");
if (!link.existing)
- throw new InvalidOperationException(String.Format(CultureInfo.CurrentCulture, SR.SiteLinkNotCommitted , link.Name));
+ throw new InvalidOperationException(SR.Format(SR.SiteLinkNotCommitted , link.Name));
string dn = (string)PropertyManager.GetPropertyValue(link.context, link.cachedEntry, PropertyManager.DistinguishedName);
@@ -131,12 +125,12 @@ namespace System.DirectoryServices.ActiveDirectory
throw new ArgumentNullException("value");
if (!link.existing)
- throw new InvalidOperationException(String.Format(CultureInfo.CurrentCulture, SR.SiteLinkNotCommitted , link.Name));
+ throw new InvalidOperationException(SR.Format(SR.SiteLinkNotCommitted , link.Name));
if (!Contains(link))
List.Insert(index, link);
else
- throw new ArgumentException(String.Format(CultureInfo.CurrentCulture, SR.AlreadyExistingInCollection , link), "link");
+ throw new ArgumentException(SR.Format(SR.AlreadyExistingInCollection , link), "link");
}
public void Remove(ActiveDirectorySiteLink link)
@@ -145,7 +139,7 @@ namespace System.DirectoryServices.ActiveDirectory
throw new ArgumentNullException("link");
if (!link.existing)
- throw new InvalidOperationException(String.Format(CultureInfo.CurrentCulture, SR.SiteLinkNotCommitted , link.Name));
+ throw new InvalidOperationException(SR.Format(SR.SiteLinkNotCommitted , link.Name));
string dn = (string)PropertyManager.GetPropertyValue(link.context, link.cachedEntry, PropertyManager.DistinguishedName);
@@ -162,7 +156,7 @@ namespace System.DirectoryServices.ActiveDirectory
}
// something that does not exist in the collectio
- throw new ArgumentException(String.Format(CultureInfo.CurrentCulture, SR.NotFoundInCollection , link), "link");
+ throw new ArgumentException(SR.Format(SR.NotFoundInCollection , link), "link");
}
protected override void OnClearComplete()
@@ -235,7 +229,7 @@ namespace System.DirectoryServices.ActiveDirectory
throw new ArgumentException("value");
if (!((ActiveDirectorySiteLink)value).existing)
- throw new InvalidOperationException(String.Format(CultureInfo.CurrentCulture, SR.SiteLinkNotCommitted , ((ActiveDirectorySiteLink)value).Name));
+ throw new InvalidOperationException(SR.Format(SR.SiteLinkNotCommitted , ((ActiveDirectorySiteLink)value).Name));
}
}
}
diff --git a/src/System.DirectoryServices/src/System/DirectoryServices/ActiveDirectory/ActiveDirectorySubnet.cs b/src/System.DirectoryServices/src/System/DirectoryServices/ActiveDirectory/ActiveDirectorySubnet.cs
index eb95c1a951..a51a60c40d 100644
--- a/src/System.DirectoryServices/src/System/DirectoryServices/ActiveDirectory/ActiveDirectorySubnet.cs
+++ b/src/System.DirectoryServices/src/System/DirectoryServices/ActiveDirectory/ActiveDirectorySubnet.cs
@@ -2,20 +2,16 @@
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
+using System.Runtime.InteropServices;
+using System.Diagnostics;
+
namespace System.DirectoryServices.ActiveDirectory
{
- using System;
- using System.Runtime.InteropServices;
- using System.Collections;
- using System.Globalization;
- using System.Diagnostics;
- using System.Security.Permissions;
-
public class ActiveDirectorySubnet : IDisposable
{
private ActiveDirectorySite _site = null;
- private string _name = null;
- internal DirectoryContext context = null;
+ private readonly string _name = null;
+ internal readonly DirectoryContext context = null;
private bool _disposed = false;
internal bool existing = false;
@@ -45,7 +41,7 @@ namespace System.DirectoryServices.ActiveDirectory
catch (ActiveDirectoryObjectNotFoundException)
{
// this is the case where the context is a config set and we could not find an ADAM instance in that config set
- throw new ActiveDirectoryOperationException(String.Format(CultureInfo.CurrentCulture, SR.ADAMInstanceNotFoundInConfigSet , context.Name));
+ throw new ActiveDirectoryOperationException(SR.Format(SR.ADAMInstanceNotFoundInConfigSet , context.Name));
}
try
@@ -144,7 +140,7 @@ namespace System.DirectoryServices.ActiveDirectory
catch (ActiveDirectoryObjectNotFoundException)
{
// this is the case where the context is a config set and we could not find an ADAM instance in that config set
- throw new ActiveDirectoryOperationException(String.Format(CultureInfo.CurrentCulture, SR.ADAMInstanceNotFoundInConfigSet , context.Name));
+ throw new ActiveDirectoryOperationException(SR.Format(SR.ADAMInstanceNotFoundInConfigSet , context.Name));
}
finally
{
@@ -168,7 +164,7 @@ namespace System.DirectoryServices.ActiveDirectory
}
catch (ActiveDirectoryObjectNotFoundException)
{
- throw new ArgumentException(String.Format(CultureInfo.CurrentCulture, SR.SiteNotExist , siteName), "siteName");
+ throw new ArgumentException(SR.Format(SR.SiteNotExist , siteName), "siteName");
}
}
@@ -187,7 +183,7 @@ namespace System.DirectoryServices.ActiveDirectory
}
catch (ActiveDirectoryObjectNotFoundException)
{
- throw new ArgumentException(String.Format(CultureInfo.CurrentCulture, SR.SiteNotExist , siteName), "siteName");
+ throw new ArgumentException(SR.Format(SR.SiteNotExist , siteName), "siteName");
}
}
@@ -223,7 +219,7 @@ namespace System.DirectoryServices.ActiveDirectory
{
// check whether the site exists or not, you can not create a new site and set it to a subnet object with commit change to site object first
if (!value.existing)
- throw new InvalidOperationException(String.Format(CultureInfo.CurrentCulture, SR.SiteNotCommitted , value));
+ throw new InvalidOperationException(SR.Format(SR.SiteNotCommitted , value));
}
_site = value;
diff --git a/src/System.DirectoryServices/src/System/DirectoryServices/ActiveDirectory/ActiveDirectorySubnetCollection.cs b/src/System.DirectoryServices/src/System/DirectoryServices/ActiveDirectory/ActiveDirectorySubnetCollection.cs
index f6d981420b..b6872de91e 100644
--- a/src/System.DirectoryServices/src/System/DirectoryServices/ActiveDirectory/ActiveDirectorySubnetCollection.cs
+++ b/src/System.DirectoryServices/src/System/DirectoryServices/ActiveDirectory/ActiveDirectorySubnetCollection.cs
@@ -2,21 +2,19 @@
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
+using System.Runtime.InteropServices;
+using System.Collections;
+using System.Text;
+
namespace System.DirectoryServices.ActiveDirectory
{
- using System;
- using System.Runtime.InteropServices;
- using System.Collections;
- using System.Globalization;
- using System.Text;
-
public class ActiveDirectorySubnetCollection : CollectionBase
{
- internal Hashtable changeList = null;
+ internal readonly Hashtable changeList = null;
internal bool initialized = false;
- private string _siteDN = null;
- private DirectoryContext _context = null;
- private ArrayList _copyList = new ArrayList();
+ private readonly string _siteDN = null;
+ private readonly DirectoryContext _context = null;
+ private readonly ArrayList _copyList = new ArrayList();
internal ActiveDirectorySubnetCollection(DirectoryContext context, string siteDN)
{
@@ -29,10 +27,7 @@ namespace System.DirectoryServices.ActiveDirectory
public ActiveDirectorySubnet this[int index]
{
- get
- {
- return (ActiveDirectorySubnet)InnerList[index];
- }
+ get => (ActiveDirectorySubnet)InnerList[index];
set
{
ActiveDirectorySubnet subnet = (ActiveDirectorySubnet)value;
@@ -41,12 +36,12 @@ namespace System.DirectoryServices.ActiveDirectory
throw new ArgumentNullException("value");
if (!subnet.existing)
- throw new InvalidOperationException(String.Format(CultureInfo.CurrentCulture, SR.SubnetNotCommitted , subnet.Name));
+ throw new InvalidOperationException(SR.Format(SR.SubnetNotCommitted , subnet.Name));
if (!Contains(subnet))
List[index] = subnet;
else
- throw new ArgumentException(String.Format(CultureInfo.CurrentCulture, SR.AlreadyExistingInCollection , subnet), "value");
+ throw new ArgumentException(SR.Format(SR.AlreadyExistingInCollection , subnet), "value");
}
}
@@ -56,12 +51,12 @@ namespace System.DirectoryServices.ActiveDirectory
throw new ArgumentNullException("subnet");
if (!subnet.existing)
- throw new InvalidOperationException(String.Format(CultureInfo.CurrentCulture, SR.SubnetNotCommitted , subnet.Name));
+ throw new InvalidOperationException(SR.Format(SR.SubnetNotCommitted , subnet.Name));
if (!Contains(subnet))
return List.Add(subnet);
else
- throw new ArgumentException(String.Format(CultureInfo.CurrentCulture, SR.AlreadyExistingInCollection , subnet), "subnet");
+ throw new ArgumentException(SR.Format(SR.AlreadyExistingInCollection , subnet), "subnet");
}
public void AddRange(ActiveDirectorySubnet[] subnets)
@@ -97,7 +92,7 @@ namespace System.DirectoryServices.ActiveDirectory
throw new ArgumentNullException("subnet");
if (!subnet.existing)
- throw new InvalidOperationException(String.Format(CultureInfo.CurrentCulture, SR.SubnetNotCommitted , subnet.Name));
+ throw new InvalidOperationException(SR.Format(SR.SubnetNotCommitted , subnet.Name));
string dn = (string)PropertyManager.GetPropertyValue(subnet.context, subnet.cachedEntry, PropertyManager.DistinguishedName);
@@ -125,7 +120,7 @@ namespace System.DirectoryServices.ActiveDirectory
throw new ArgumentNullException("subnet");
if (!subnet.existing)
- throw new InvalidOperationException(String.Format(CultureInfo.CurrentCulture, SR.SubnetNotCommitted , subnet.Name));
+ throw new InvalidOperationException(SR.Format(SR.SubnetNotCommitted , subnet.Name));
string dn = (string)PropertyManager.GetPropertyValue(subnet.context, subnet.cachedEntry, PropertyManager.DistinguishedName);
@@ -148,12 +143,12 @@ namespace System.DirectoryServices.ActiveDirectory
throw new ArgumentNullException("subnet");
if (!subnet.existing)
- throw new InvalidOperationException(String.Format(CultureInfo.CurrentCulture, SR.SubnetNotCommitted , subnet.Name));
+ throw new InvalidOperationException(SR.Format(SR.SubnetNotCommitted , subnet.Name));
if (!Contains(subnet))
List.Insert(index, subnet);
else
- throw new ArgumentException(String.Format(CultureInfo.CurrentCulture, SR.AlreadyExistingInCollection , subnet), "subnet");
+ throw new ArgumentException(SR.Format(SR.AlreadyExistingInCollection , subnet), "subnet");
}
public void Remove(ActiveDirectorySubnet subnet)
@@ -162,7 +157,7 @@ namespace System.DirectoryServices.ActiveDirectory
throw new ArgumentNullException("subnet");
if (!subnet.existing)
- throw new InvalidOperationException(String.Format(CultureInfo.CurrentCulture, SR.SubnetNotCommitted , subnet.Name));
+ throw new InvalidOperationException(SR.Format(SR.SubnetNotCommitted , subnet.Name));
string dn = (string)PropertyManager.GetPropertyValue(subnet.context, subnet.cachedEntry, PropertyManager.DistinguishedName);
@@ -179,7 +174,7 @@ namespace System.DirectoryServices.ActiveDirectory
}
// something that does not exist in the collectio
- throw new ArgumentException(String.Format(CultureInfo.CurrentCulture, SR.NotFoundInCollection , subnet), "subnet");
+ throw new ArgumentException(SR.Format(SR.NotFoundInCollection , subnet), "subnet");
}
protected override void OnClear()
@@ -271,7 +266,7 @@ namespace System.DirectoryServices.ActiveDirectory
throw new ArgumentException("value");
if (!((ActiveDirectorySubnet)value).existing)
- throw new InvalidOperationException(String.Format(CultureInfo.CurrentCulture, SR.SubnetNotCommitted , ((ActiveDirectorySubnet)value).Name));
+ throw new InvalidOperationException(SR.Format(SR.SubnetNotCommitted , ((ActiveDirectorySubnet)value).Name));
}
private string MakePath(string subnetDN)
diff --git a/src/System.DirectoryServices/src/System/DirectoryServices/ActiveDirectory/ActiveDirectorySyntax.cs b/src/System.DirectoryServices/src/System/DirectoryServices/ActiveDirectory/ActiveDirectorySyntax.cs
index 286bf0a6d7..8ecf3e03ef 100644
--- a/src/System.DirectoryServices/src/System/DirectoryServices/ActiveDirectory/ActiveDirectorySyntax.cs
+++ b/src/System.DirectoryServices/src/System/DirectoryServices/ActiveDirectory/ActiveDirectorySyntax.cs
@@ -4,8 +4,6 @@
namespace System.DirectoryServices.ActiveDirectory
{
- using System;
-
public enum ActiveDirectorySyntax : int
{
CaseExactString = 0,
@@ -35,21 +33,16 @@ namespace System.DirectoryServices.ActiveDirectory
internal class OMObjectClass
{
- public byte[] data = null;
-
- public OMObjectClass(byte[] data)
- {
- this.data = data;
- }
+ public OMObjectClass(byte[] data) => Data = data;
public bool Equals(OMObjectClass OMObjectClass)
{
bool result = true;
- if (data.Length == OMObjectClass.data.Length)
+ if (Data.Length == OMObjectClass.Data.Length)
{
- for (int i = 0; i < data.Length; i++)
+ for (int i = 0; i < Data.Length; i++)
{
- if (data[i] != OMObjectClass.data[i])
+ if (Data[i] != OMObjectClass.Data[i])
{
result = false;
break;
@@ -63,20 +56,14 @@ namespace System.DirectoryServices.ActiveDirectory
return result;
}
- public byte[] Data
- {
- get
- {
- return data;
- }
- }
+ public byte[] Data { get; }
}
internal class Syntax
{
- public string attributeSyntax = null;
- public int oMSyntax = 0;
- public OMObjectClass oMObjectClass = null;
+ public readonly string attributeSyntax = null;
+ public readonly int oMSyntax = 0;
+ public readonly OMObjectClass oMObjectClass = null;
public Syntax(string attributeSyntax, int oMSyntax, OMObjectClass oMObjectClass)
{
diff --git a/src/System.DirectoryServices/src/System/DirectoryServices/ActiveDirectory/ApplicationPartition.cs b/src/System.DirectoryServices/src/System/DirectoryServices/ActiveDirectory/ApplicationPartition.cs
index f707950c7b..5f58ccb791 100644
--- a/src/System.DirectoryServices/src/System/DirectoryServices/ActiveDirectory/ApplicationPartition.cs
+++ b/src/System.DirectoryServices/src/System/DirectoryServices/ActiveDirectory/ApplicationPartition.cs
@@ -2,17 +2,13 @@
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
+using System.Text;
+using System.Collections;
+using System.Diagnostics;
+using System.Runtime.InteropServices;
+
namespace System.DirectoryServices.ActiveDirectory
{
- using System;
- using System.Text;
- using System.Threading;
- using System.Collections;
- using System.Globalization;
- using System.Diagnostics;
- using System.Runtime.InteropServices;
- using System.Security.Permissions;
-
internal enum NCFlags : int
{
InstanceTypeIsNCHead = 1,
@@ -212,7 +208,7 @@ namespace System.DirectoryServices.ActiveDirectory
catch (ActiveDirectoryObjectNotFoundException)
{
// this is the case where the context is a config set and we could not find an ADAM instance in that config set
- throw new ActiveDirectoryOperationException(String.Format(CultureInfo.CurrentCulture, SR.ADAMInstanceNotFoundInConfigSet , context.Name));
+ throw new ActiveDirectoryOperationException(SR.Format(SR.ADAMInstanceNotFoundInConfigSet , context.Name));
}
// build the filter
diff --git a/src/System.DirectoryServices/src/System/DirectoryServices/ActiveDirectory/ApplicationPartitionCollection.cs b/src/System.DirectoryServices/src/System/DirectoryServices/ActiveDirectory/ApplicationPartitionCollection.cs
index df5a8da288..5f53942295 100644
--- a/src/System.DirectoryServices/src/System/DirectoryServices/ActiveDirectory/ApplicationPartitionCollection.cs
+++ b/src/System.DirectoryServices/src/System/DirectoryServices/ActiveDirectory/ApplicationPartitionCollection.cs
@@ -2,13 +2,10 @@
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
+using System.Collections;
+
namespace System.DirectoryServices.ActiveDirectory
{
- using System;
- using System.Collections;
- using System.Globalization;
- using System.DirectoryServices;
-
public class ApplicationPartitionCollection : ReadOnlyCollectionBase
{
internal ApplicationPartitionCollection() { }
@@ -21,13 +18,7 @@ namespace System.DirectoryServices.ActiveDirectory
}
}
- public ApplicationPartition this[int index]
- {
- get
- {
- return (ApplicationPartition)InnerList[index];
- }
- }
+ public ApplicationPartition this[int index] => (ApplicationPartition)InnerList[index];
public bool Contains(ApplicationPartition applicationPartition)
{
diff --git a/src/System.DirectoryServices/src/System/DirectoryServices/ActiveDirectory/AttributeMetaData.cs b/src/System.DirectoryServices/src/System/DirectoryServices/ActiveDirectory/AttributeMetaData.cs
index 8d9f0f2cb7..1d55b97d84 100644
--- a/src/System.DirectoryServices/src/System/DirectoryServices/ActiveDirectory/AttributeMetaData.cs
+++ b/src/System.DirectoryServices/src/System/DirectoryServices/ActiveDirectory/AttributeMetaData.cs
@@ -2,27 +2,20 @@
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
+using System.Collections;
+using System.Runtime.InteropServices;
+using System.Diagnostics;
+
namespace System.DirectoryServices.ActiveDirectory
{
- using System;
- using System.Collections;
- using System.Runtime.InteropServices;
- using System.Diagnostics;
-
public class AttributeMetadata
{
- private string _pszAttributeName = null;
- private int _dwVersion;
- private DateTime _ftimeLastOriginatingChange;
- private Guid _uuidLastOriginatingDsaInvocationID;
- private long _usnOriginatingChange;
- private long _usnLocalChange;
- private string _pszLastOriginatingDsaDN = null;
+ private readonly string _pszLastOriginatingDsaDN = null;
private string _originatingServerName = null;
- private DirectoryServer _server = null;
- private Hashtable _nameTable = null;
- private bool _advanced = false;
+ private readonly DirectoryServer _server = null;
+ private readonly Hashtable _nameTable = null;
+ private readonly bool _advanced = false;
internal AttributeMetadata(IntPtr info, bool advanced, DirectoryServer server, Hashtable table)
{
@@ -32,13 +25,13 @@ namespace System.DirectoryServices.ActiveDirectory
Marshal.PtrToStructure(info, attrMetaData);
Debug.Assert(attrMetaData != null);
- _pszAttributeName = Marshal.PtrToStringUni(attrMetaData.pszAttributeName);
- _dwVersion = attrMetaData.dwVersion;
+ Name = Marshal.PtrToStringUni(attrMetaData.pszAttributeName);
+ Version = attrMetaData.dwVersion;
long ftimeChangeValue = (long)((uint)attrMetaData.ftimeLastOriginatingChange1 + (((long)attrMetaData.ftimeLastOriginatingChange2) << 32));
- _ftimeLastOriginatingChange = DateTime.FromFileTime(ftimeChangeValue);
- _uuidLastOriginatingDsaInvocationID = attrMetaData.uuidLastOriginatingDsaInvocationID;
- _usnOriginatingChange = attrMetaData.usnOriginatingChange;
- _usnLocalChange = attrMetaData.usnLocalChange;
+ LastOriginatingChangeTime = DateTime.FromFileTime(ftimeChangeValue);
+ LastOriginatingInvocationId = attrMetaData.uuidLastOriginatingDsaInvocationID;
+ OriginatingChangeUsn = attrMetaData.usnOriginatingChange;
+ LocalChangeUsn = attrMetaData.usnLocalChange;
_pszLastOriginatingDsaDN = Marshal.PtrToStringUni(attrMetaData.pszLastOriginatingDsaDN);
}
else
@@ -47,66 +40,30 @@ namespace System.DirectoryServices.ActiveDirectory
Marshal.PtrToStructure(info, attrMetaData);
Debug.Assert(attrMetaData != null);
- _pszAttributeName = Marshal.PtrToStringUni(attrMetaData.pszAttributeName);
- _dwVersion = attrMetaData.dwVersion;
+ Name = Marshal.PtrToStringUni(attrMetaData.pszAttributeName);
+ Version = attrMetaData.dwVersion;
long ftimeChangeValue = (long)((uint)attrMetaData.ftimeLastOriginatingChange1 + (((long)attrMetaData.ftimeLastOriginatingChange2) << 32));
- _ftimeLastOriginatingChange = DateTime.FromFileTime(ftimeChangeValue);
- _uuidLastOriginatingDsaInvocationID = attrMetaData.uuidLastOriginatingDsaInvocationID;
- _usnOriginatingChange = attrMetaData.usnOriginatingChange;
- _usnLocalChange = attrMetaData.usnLocalChange;
+ LastOriginatingChangeTime = DateTime.FromFileTime(ftimeChangeValue);
+ LastOriginatingInvocationId = attrMetaData.uuidLastOriginatingDsaInvocationID;
+ OriginatingChangeUsn = attrMetaData.usnOriginatingChange;
+ LocalChangeUsn = attrMetaData.usnLocalChange;
}
_server = server;
_nameTable = table;
_advanced = advanced;
}
- public string Name
- {
- get
- {
- return _pszAttributeName;
- }
- }
+ public string Name { get; }
- public int Version
- {
- get
- {
- return _dwVersion;
- }
- }
+ public int Version { get; }
- public DateTime LastOriginatingChangeTime
- {
- get
- {
- return _ftimeLastOriginatingChange;
- }
- }
+ public DateTime LastOriginatingChangeTime { get; }
- public Guid LastOriginatingInvocationId
- {
- get
- {
- return _uuidLastOriginatingDsaInvocationID;
- }
- }
+ public Guid LastOriginatingInvocationId { get; }
- public long OriginatingChangeUsn
- {
- get
- {
- return _usnOriginatingChange;
- }
- }
+ public long OriginatingChangeUsn { get; }
- public long LocalChangeUsn
- {
- get
- {
- return _usnLocalChange;
- }
- }
+ public long LocalChangeUsn { get; }
public string OriginatingServer
{
diff --git a/src/System.DirectoryServices/src/System/DirectoryServices/ActiveDirectory/AttributeMetadataCollection.cs b/src/System.DirectoryServices/src/System/DirectoryServices/ActiveDirectory/AttributeMetadataCollection.cs
index f84d1b9d8b..f1455d952b 100644
--- a/src/System.DirectoryServices/src/System/DirectoryServices/ActiveDirectory/AttributeMetadataCollection.cs
+++ b/src/System.DirectoryServices/src/System/DirectoryServices/ActiveDirectory/AttributeMetadataCollection.cs
@@ -2,23 +2,15 @@
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
+using System.Collections;
+
namespace System.DirectoryServices.ActiveDirectory
{
- using System;
- using System.Collections;
- using System.Globalization;
-
public class AttributeMetadataCollection : ReadOnlyCollectionBase
{
internal AttributeMetadataCollection() { }
- public AttributeMetadata this[int index]
- {
- get
- {
- return (AttributeMetadata)InnerList[index];
- }
- }
+ public AttributeMetadata this[int index] => (AttributeMetadata)InnerList[index];
public bool Contains(AttributeMetadata metadata)
{
@@ -60,9 +52,6 @@ namespace System.DirectoryServices.ActiveDirectory
InnerList.CopyTo(metadata, index);
}
- internal int Add(AttributeMetadata metadata)
- {
- return InnerList.Add(metadata);
- }
+ internal int Add(AttributeMetadata metadata) => InnerList.Add(metadata);
}
}
diff --git a/src/System.DirectoryServices/src/System/DirectoryServices/ActiveDirectory/ConfigSet.cs b/src/System.DirectoryServices/src/System/DirectoryServices/ActiveDirectory/ConfigSet.cs
index 660005406f..a2133c8cef 100644
--- a/src/System.DirectoryServices/src/System/DirectoryServices/ActiveDirectory/ConfigSet.cs
+++ b/src/System.DirectoryServices/src/System/DirectoryServices/ActiveDirectory/ConfigSet.cs
@@ -2,26 +2,23 @@
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
+using System.Text;
+using System.Collections;
+using System.ComponentModel;
+using System.Diagnostics;
+using System.Runtime.InteropServices;
+
namespace System.DirectoryServices.ActiveDirectory
{
- using System;
- using System.Text;
- using System.Collections;
- using System.ComponentModel;
- using System.Globalization;
- using System.Diagnostics;
- using System.Runtime.InteropServices;
- using System.Security.Permissions;
-
public class ConfigurationSet
{
// Private Variables
- private DirectoryContext _context = null;
- private DirectoryEntryManager _directoryEntryMgr = null;
+ private readonly DirectoryContext _context = null;
+ private readonly DirectoryEntryManager _directoryEntryMgr = null;
private bool _disposed = false;
// variables corresponding to public properties
- private string _configSetName = null;
+ private readonly string _configSetName = null;
private ReadOnlySiteCollection _cachedSites = null;
private AdamInstanceCollection _cachedADAMInstances = null;
private ApplicationPartitionCollection _cachedApplicationPartitions = null;
@@ -49,10 +46,7 @@ namespace System.DirectoryServices.ActiveDirectory
#region IDisposable
- public void Dispose()
- {
- Dispose(true);
- }
+ public void Dispose() => Dispose(true);
// private Dispose method
protected virtual void Dispose(bool disposing)
@@ -99,7 +93,7 @@ namespace System.DirectoryServices.ActiveDirectory
}
else
{
- throw new ActiveDirectoryObjectNotFoundException(String.Format(CultureInfo.CurrentCulture, SR.AINotFound , context.Name), typeof(ConfigurationSet), null);
+ throw new ActiveDirectoryObjectNotFoundException(SR.Format(SR.AINotFound , context.Name), typeof(ConfigurationSet), null);
}
}
@@ -118,7 +112,7 @@ namespace System.DirectoryServices.ActiveDirectory
rootDSE = directoryEntryMgr.GetCachedDirectoryEntry(WellKnownDN.RootDSE);
if ((context.isServer()) && (!Utils.CheckCapability(rootDSE, Capability.ActiveDirectoryApplicationMode)))
{
- throw new ActiveDirectoryObjectNotFoundException(String.Format(CultureInfo.CurrentCulture, SR.AINotFound , context.Name), typeof(ConfigurationSet), null);
+ throw new ActiveDirectoryObjectNotFoundException(SR.Format(SR.AINotFound , context.Name), typeof(ConfigurationSet), null);
}
configSetName = (string)PropertyManager.GetPropertyValue(context, rootDSE, PropertyManager.ConfigurationNamingContext);
@@ -135,7 +129,7 @@ namespace System.DirectoryServices.ActiveDirectory
}
else
{
- throw new ActiveDirectoryObjectNotFoundException(String.Format(CultureInfo.CurrentCulture, SR.AINotFound , context.Name), typeof(ConfigurationSet), null);
+ throw new ActiveDirectoryObjectNotFoundException(SR.Format(SR.AINotFound , context.Name), typeof(ConfigurationSet), null);
}
}
else
@@ -267,10 +261,8 @@ namespace System.DirectoryServices.ActiveDirectory
_cachedSecurityLevel = (ReplicationSecurityLevel)(-1);
}
- public override string ToString()
- {
- return Name;
- }
+ public override string ToString() => Name;
+
#endregion public methods
#region public properties
@@ -600,7 +592,7 @@ namespace System.DirectoryServices.ActiveDirectory
{
// if we are passed the timeout period, we should throw, else do nothing
if (DateTime.UtcNow.Subtract(startTime) > s_locationTimeout)
- throw new ActiveDirectoryObjectNotFoundException(String.Format(CultureInfo.CurrentCulture, SR.ADAMInstanceNotFoundInConfigSet , (configSetName != null) ? configSetName : context.Name), typeof(AdamInstance), null);
+ throw new ActiveDirectoryObjectNotFoundException(SR.Format(SR.ADAMInstanceNotFoundInConfigSet , (configSetName != null) ? configSetName : context.Name), typeof(AdamInstance), null);
}
else
throw ExceptionHelper.GetExceptionFromCOMException(context, e);
@@ -613,7 +605,7 @@ namespace System.DirectoryServices.ActiveDirectory
}
// if we reach here, we haven't found an adam instance
- throw new ActiveDirectoryObjectNotFoundException(String.Format(CultureInfo.CurrentCulture, SR.ADAMInstanceNotFoundInConfigSet , (configSetName != null) ? configSetName : context.Name), typeof(AdamInstance), null);
+ throw new ActiveDirectoryObjectNotFoundException(SR.Format(SR.ADAMInstanceNotFoundInConfigSet , (configSetName != null) ? configSetName : context.Name), typeof(AdamInstance), null);
}
/// <returns>Returns a DomainController object for the DC that holds the specified FSMO role</returns>
diff --git a/src/System.DirectoryServices/src/System/DirectoryServices/ActiveDirectory/DirectoryContext.cs b/src/System.DirectoryServices/src/System/DirectoryServices/ActiveDirectory/DirectoryContext.cs
index c74a4d6ec0..98885b040c 100644
--- a/src/System.DirectoryServices/src/System/DirectoryServices/ActiveDirectory/DirectoryContext.cs
+++ b/src/System.DirectoryServices/src/System/DirectoryServices/ActiveDirectory/DirectoryContext.cs
@@ -2,17 +2,16 @@
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
+using System.Net;
+using System.Security.Principal;
+using System.Diagnostics;
+using System.Runtime.InteropServices;
+using System.ComponentModel;
+using System.Security.Permissions;
+using System.IO;
+
namespace System.DirectoryServices.ActiveDirectory
{
- using System;
- using System.Net;
- using System.Security.Principal;
- using System.Diagnostics;
- using System.Runtime.InteropServices;
- using System.ComponentModel;
- using System.Security.Permissions;
- using System.IO;
-
public enum DirectoryContextType
{
Domain = 0,
@@ -173,60 +172,19 @@ namespace System.DirectoryServices.ActiveDirectory
#region public properties
- public string Name
- {
- get
- {
- return _name;
- }
- }
+ public string Name => _name;
- public string UserName
- {
- get
- {
- if (usernameIsNull)
- {
- return null;
- }
- else
- {
- return _credential.UserName;
- }
- }
- }
+ public string UserName => usernameIsNull ? null : _credential.UserName;
internal string Password
{
[SecurityPermission(SecurityAction.Assert, Flags = SecurityPermissionFlag.UnmanagedCode)]
- get
- {
- if (passwordIsNull)
- {
- return null;
- }
- else
- {
- return _credential.Password;
- }
- }
+ get => passwordIsNull ? null : _credential.Password;
}
- public DirectoryContextType ContextType
- {
- get
- {
- return _contextType;
- }
- }
+ public DirectoryContextType ContextType => _contextType;
- internal NetworkCredential Credential
- {
- get
- {
- return _credential;
- }
- }
+ internal NetworkCredential Credential => _credential;
#endregion public properties
@@ -758,4 +716,3 @@ namespace System.DirectoryServices.ActiveDirectory
#endregion private methods
}
}
-
diff --git a/src/System.DirectoryServices/src/System/DirectoryServices/ActiveDirectory/DirectoryEntryManager.cs b/src/System.DirectoryServices/src/System/DirectoryServices/ActiveDirectory/DirectoryEntryManager.cs
index dc4fa8d813..e5b0a2eeca 100644
--- a/src/System.DirectoryServices/src/System/DirectoryServices/ActiveDirectory/DirectoryEntryManager.cs
+++ b/src/System.DirectoryServices/src/System/DirectoryServices/ActiveDirectory/DirectoryEntryManager.cs
@@ -2,51 +2,37 @@
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
+using System.Collections;
+using System.ComponentModel;
+
namespace System.DirectoryServices.ActiveDirectory
{
- using System;
- using System.Net;
- using System.Collections;
- using System.Globalization;
- using System.ComponentModel;
- using System.DirectoryServices;
- using System.Runtime.InteropServices;
- using System.Security.Permissions;
-
/// <summary>
/// Internal class that is used as a key in the hashtable
/// of directory entries
/// </summary>
internal class DistinguishedName
{
- private Component[] _components = null;
-
public DistinguishedName(string dn)
{
- _components = Utils.GetDNComponents(dn);
+ Components = Utils.GetDNComponents(dn);
}
- public Component[] Components
- {
- get
- {
- return _components;
- }
- }
+ public Component[] Components { get; }
public bool Equals(DistinguishedName dn)
{
bool result = true;
- if ((dn == null) || (_components.GetLength(0) != dn.Components.GetLength(0)))
+ if ((dn == null) || (Components.GetLength(0) != dn.Components.GetLength(0)))
{
result = false;
}
else
{
- for (int i = 0; i < _components.GetLength(0); i++)
+ for (int i = 0; i < Components.GetLength(0); i++)
{
- if ((Utils.Compare(_components[i].Name, dn.Components[i].Name) != 0)
- || (Utils.Compare(_components[i].Value, dn.Components[i].Value) != 0))
+ if ((Utils.Compare(Components[i].Name, dn.Components[i].Name) != 0)
+ || (Utils.Compare(Components[i].Value, dn.Components[i].Value) != 0))
{
result = false;
break;
@@ -71,19 +57,19 @@ namespace System.DirectoryServices.ActiveDirectory
public override int GetHashCode()
{
int hashCode = 0;
- for (int i = 0; i < _components.GetLength(0); i++)
+ for (int i = 0; i < Components.GetLength(0); i++)
{
- hashCode = hashCode + _components[i].Name.ToUpperInvariant().GetHashCode() + _components[i].Value.ToUpperInvariant().GetHashCode();
+ hashCode = hashCode + Components[i].Name.ToUpperInvariant().GetHashCode() + Components[i].Value.ToUpperInvariant().GetHashCode();
}
return hashCode;
}
public override string ToString()
{
- string dn = _components[0].Name + "=" + _components[0].Value;
- for (int i = 1; i < _components.GetLength(0); i++)
+ string dn = Components[0].Name + "=" + Components[0].Value;
+ for (int i = 1; i < Components.GetLength(0); i++)
{
- dn = dn + "," + _components[i].Name + "=" + _components[i].Value;
+ dn = dn + "," + Components[i].Name + "=" + Components[i].Value;
}
return dn;
}
@@ -110,10 +96,7 @@ namespace System.DirectoryServices.ActiveDirectory
_pathCracker.EscapedMode = NativeComInterfaces.ADS_ESCAPEDMODE_ON;
}
- internal ICollection GetCachedDirectoryEntries()
- {
- return _directoryEntries.Values;
- }
+ internal ICollection GetCachedDirectoryEntries() => _directoryEntries.Values;
internal DirectoryEntry GetCachedDirectoryEntry(WellKnownDN dn)
{
diff --git a/src/System.DirectoryServices/src/System/DirectoryServices/ActiveDirectory/DirectoryServer.cs b/src/System.DirectoryServices/src/System/DirectoryServices/ActiveDirectory/DirectoryServer.cs
index 50cd72ce8a..db8d0ff956 100644
--- a/src/System.DirectoryServices/src/System/DirectoryServices/ActiveDirectory/DirectoryServer.cs
+++ b/src/System.DirectoryServices/src/System/DirectoryServices/ActiveDirectory/DirectoryServer.cs
@@ -2,15 +2,13 @@
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
+using System.Collections;
+using System.Globalization;
+using System.Runtime.InteropServices;
+using System.Diagnostics;
+
namespace System.DirectoryServices.ActiveDirectory
{
- using System;
- using System.Collections;
- using System.Globalization;
- using System.Runtime.InteropServices;
- using System.Diagnostics;
- using System.Security.Permissions;
-
public abstract class DirectoryServer : IDisposable
{
private bool _disposed = false;
@@ -46,11 +44,7 @@ namespace System.DirectoryServices.ActiveDirectory
#endregion constructors
#region IDisposable
- ~DirectoryServer()
- {
- // finalizer is called => Dispose has not been called yet.
- Dispose(false);
- }
+ ~DirectoryServer() => Dispose(false);
public void Dispose()
{
@@ -83,10 +77,7 @@ namespace System.DirectoryServices.ActiveDirectory
#endregion IDisposable
#region public methods
- public override string ToString()
- {
- return Name;
- }
+ public override string ToString() => Name;
public void MoveToAnotherSite(string siteName)
{
@@ -221,30 +212,16 @@ namespace System.DirectoryServices.ActiveDirectory
#endregion public properties
#region abstract public properties
- public abstract string IPAddress
- {
- get;
- }
- public abstract String SiteName
- {
- get;
- }
- public abstract SyncUpdateCallback SyncFromAllServersCallback
- {
- get;
+ public abstract string IPAddress { get; }
- set;
- }
- public abstract ReplicationConnectionCollection InboundConnections
- {
- get;
- }
+ public abstract string SiteName { get; }
- public abstract ReplicationConnectionCollection OutboundConnections
- {
- get;
- }
+ public abstract SyncUpdateCallback SyncFromAllServersCallback { get; set; }
+
+ public abstract ReplicationConnectionCollection InboundConnections { get; }
+
+ public abstract ReplicationConnectionCollection OutboundConnections { get; }
#endregion abstract public properties
@@ -319,13 +296,7 @@ namespace System.DirectoryServices.ActiveDirectory
}
}
- internal DirectoryContext Context
- {
- get
- {
- return context;
- }
- }
+ internal DirectoryContext Context => context;
internal void CheckConsistencyHelper(IntPtr dsHandle, LoadLibrarySafeHandle libHandle)
{
diff --git a/src/System.DirectoryServices/src/System/DirectoryServices/ActiveDirectory/DirectoryServerCollection.cs b/src/System.DirectoryServices/src/System/DirectoryServices/ActiveDirectory/DirectoryServerCollection.cs
index 8073473e4d..bf8186475f 100644
--- a/src/System.DirectoryServices/src/System/DirectoryServices/ActiveDirectory/DirectoryServerCollection.cs
+++ b/src/System.DirectoryServices/src/System/DirectoryServices/ActiveDirectory/DirectoryServerCollection.cs
@@ -2,25 +2,23 @@
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
+using System.Runtime.InteropServices;
+using System.Collections;
+using System.Diagnostics;
+
namespace System.DirectoryServices.ActiveDirectory
{
- using System;
- using System.Runtime.InteropServices;
- using System.Collections;
- using System.Globalization;
- using System.Diagnostics;
-
public class DirectoryServerCollection : CollectionBase
{
- internal string siteDN = null;
- internal string transportDN = null;
- internal DirectoryContext context = null;
+ internal readonly string siteDN = null;
+ internal readonly string transportDN = null;
+ internal readonly DirectoryContext context = null;
internal bool initialized = false;
- internal Hashtable changeList = null;
- private ArrayList _copyList = new ArrayList();
- private DirectoryEntry _crossRefEntry = null;
- private bool _isADAM = false;
- private bool _isForNC = false;
+ internal readonly Hashtable changeList = null;
+ private readonly ArrayList _copyList = new ArrayList();
+ private readonly DirectoryEntry _crossRefEntry = null;
+ private readonly bool _isADAM = false;
+ private readonly bool _isForNC = false;
internal DirectoryServerCollection(DirectoryContext context, string siteDN, string transportName)
{
@@ -47,10 +45,7 @@ namespace System.DirectoryServices.ActiveDirectory
public DirectoryServer this[int index]
{
- get
- {
- return (DirectoryServer)InnerList[index];
- }
+ get => (DirectoryServer)InnerList[index];
set
{
DirectoryServer server = (DirectoryServer)value;
@@ -61,7 +56,7 @@ namespace System.DirectoryServices.ActiveDirectory
if (!Contains(server))
List[index] = server;
else
- throw new ArgumentException(String.Format(CultureInfo.CurrentCulture, SR.AlreadyExistingInCollection , server), "value");
+ throw new ArgumentException(SR.Format(SR.AlreadyExistingInCollection , server), "value");
}
}
@@ -92,7 +87,7 @@ namespace System.DirectoryServices.ActiveDirectory
}
else
{
- throw new ArgumentException(String.Format(CultureInfo.CurrentCulture, SR.AlreadyExistingInCollection , server), "server");
+ throw new ArgumentException(SR.Format(SR.AlreadyExistingInCollection , server), "server");
}
}
else
@@ -107,7 +102,7 @@ namespace System.DirectoryServices.ActiveDirectory
if (!Contains(server))
return List.Add(server);
else
- throw new ArgumentException(String.Format(CultureInfo.CurrentCulture, SR.AlreadyExistingInCollection , server), "server");
+ throw new ArgumentException(SR.Format(SR.AlreadyExistingInCollection , server), "server");
}
}
@@ -193,7 +188,7 @@ namespace System.DirectoryServices.ActiveDirectory
}
else
{
- throw new ArgumentException(String.Format(CultureInfo.CurrentCulture, SR.AlreadyExistingInCollection , server), "server");
+ throw new ArgumentException(SR.Format(SR.AlreadyExistingInCollection , server), "server");
}
}
else
@@ -209,7 +204,7 @@ namespace System.DirectoryServices.ActiveDirectory
if (!Contains(server))
List.Insert(index, server);
else
- throw new ArgumentException(String.Format(CultureInfo.CurrentCulture, SR.AlreadyExistingInCollection , server));
+ throw new ArgumentException(SR.Format(SR.AlreadyExistingInCollection , server));
}
}
@@ -230,7 +225,7 @@ namespace System.DirectoryServices.ActiveDirectory
}
// something that does not exist in the collection
- throw new ArgumentException(String.Format(CultureInfo.CurrentCulture, SR.NotFoundInCollection , server), "server");
+ throw new ArgumentException(SR.Format(SR.NotFoundInCollection , server), "server");
}
protected override void OnClear()
diff --git a/src/System.DirectoryServices/src/System/DirectoryServices/ActiveDirectory/Domain.cs b/src/System.DirectoryServices/src/System/DirectoryServices/ActiveDirectory/Domain.cs
index ecd71488fa..f24d907df9 100644
--- a/src/System.DirectoryServices/src/System/DirectoryServices/ActiveDirectory/Domain.cs
+++ b/src/System.DirectoryServices/src/System/DirectoryServices/ActiveDirectory/Domain.cs
@@ -2,18 +2,15 @@
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
+using System.Text;
+using System.Collections;
+using System.Globalization;
+using System.ComponentModel;
+using System.Runtime.InteropServices;
+using System.Diagnostics;
+
namespace System.DirectoryServices.ActiveDirectory
{
- using System;
- using System.Text;
- using System.Collections;
- using System.Globalization;
- using System.ComponentModel;
- using System.DirectoryServices;
- using System.Runtime.InteropServices;
- using System.Diagnostics;
- using System.Security.Permissions;
-
public enum DomainMode : int
{
Unknown = -1,
@@ -90,7 +87,7 @@ namespace System.DirectoryServices.ActiveDirectory
}
else
{
- throw new ActiveDirectoryObjectNotFoundException(String.Format(CultureInfo.CurrentCulture, SR.DCNotFound , context.Name), typeof(Domain), null);
+ throw new ActiveDirectoryObjectNotFoundException(SR.Format(SR.DCNotFound , context.Name), typeof(Domain), null);
}
}
}
@@ -108,7 +105,7 @@ namespace System.DirectoryServices.ActiveDirectory
rootDSE = directoryEntryMgr.GetCachedDirectoryEntry(WellKnownDN.RootDSE);
if ((context.isServer()) && (!Utils.CheckCapability(rootDSE, Capability.ActiveDirectory)))
{
- throw new ActiveDirectoryObjectNotFoundException(String.Format(CultureInfo.CurrentCulture, SR.DCNotFound , context.Name), typeof(Domain), null);
+ throw new ActiveDirectoryObjectNotFoundException(SR.Format(SR.DCNotFound , context.Name), typeof(Domain), null);
}
defaultDomainNC = (string)PropertyManager.GetPropertyValue(context, rootDSE, PropertyManager.DefaultNamingContext);
}
@@ -124,7 +121,7 @@ namespace System.DirectoryServices.ActiveDirectory
}
else
{
- throw new ActiveDirectoryObjectNotFoundException(String.Format(CultureInfo.CurrentCulture, SR.DCNotFound , context.Name), typeof(Domain), null);
+ throw new ActiveDirectoryObjectNotFoundException(SR.Format(SR.DCNotFound , context.Name), typeof(Domain), null);
}
}
else
@@ -530,7 +527,7 @@ namespace System.DirectoryServices.ActiveDirectory
if (collection.Count == 0)
{
// trust relationship does not exist
- throw new ActiveDirectoryObjectNotFoundException(String.Format(CultureInfo.CurrentCulture, SR.DomainTrustDoesNotExist , Name, targetDomainName), typeof(TrustRelationshipInformation), null);
+ throw new ActiveDirectoryObjectNotFoundException(SR.Format(SR.DomainTrustDoesNotExist , Name, targetDomainName), typeof(TrustRelationshipInformation), null);
}
else
{
@@ -651,7 +648,7 @@ namespace System.DirectoryServices.ActiveDirectory
}
catch (ActiveDirectoryObjectNotFoundException)
{
- throw new ActiveDirectoryObjectNotFoundException(String.Format(CultureInfo.CurrentCulture, SR.WrongTrustDirection , Name, targetDomain.Name, direction), typeof(TrustRelationshipInformation), null);
+ throw new ActiveDirectoryObjectNotFoundException(SR.Format(SR.WrongTrustDirection , Name, targetDomain.Name, direction), typeof(TrustRelationshipInformation), null);
}
}
@@ -664,7 +661,7 @@ namespace System.DirectoryServices.ActiveDirectory
}
catch (ActiveDirectoryObjectNotFoundException)
{
- throw new ActiveDirectoryObjectNotFoundException(String.Format(CultureInfo.CurrentCulture, SR.WrongTrustDirection , Name, targetDomain.Name, direction), typeof(TrustRelationshipInformation), null);
+ throw new ActiveDirectoryObjectNotFoundException(SR.Format(SR.WrongTrustDirection , Name, targetDomain.Name, direction), typeof(TrustRelationshipInformation), null);
}
}
}
@@ -825,7 +822,7 @@ namespace System.DirectoryServices.ActiveDirectory
}
catch (ActiveDirectoryObjectNotFoundException)
{
- throw new ActiveDirectoryObjectNotFoundException(String.Format(CultureInfo.CurrentCulture, SR.WrongTrustDirection , Name, targetDomain.Name, direction), typeof(TrustRelationshipInformation), null);
+ throw new ActiveDirectoryObjectNotFoundException(SR.Format(SR.WrongTrustDirection , Name, targetDomain.Name, direction), typeof(TrustRelationshipInformation), null);
}
}
@@ -965,10 +962,7 @@ namespace System.DirectoryServices.ActiveDirectory
#region private methods
- internal DirectoryContext GetDirectoryContext()
- {
- return context;
- }
+ internal DirectoryContext GetDirectoryContext() => context;
private int GetDomainModeLevel()
{
@@ -1510,7 +1504,7 @@ namespace System.DirectoryServices.ActiveDirectory
}
catch (ActiveDirectoryObjectNotFoundException)
{
- throw new ActiveDirectoryObjectNotFoundException(String.Format(CultureInfo.CurrentCulture, SR.WrongTrustDirection , Name, targetDomain.Name, direction), typeof(TrustRelationshipInformation), null);
+ throw new ActiveDirectoryObjectNotFoundException(SR.Format(SR.WrongTrustDirection , Name, targetDomain.Name, direction), typeof(TrustRelationshipInformation), null);
}
}
@@ -1523,7 +1517,7 @@ namespace System.DirectoryServices.ActiveDirectory
}
catch (ActiveDirectoryObjectNotFoundException)
{
- throw new ActiveDirectoryObjectNotFoundException(String.Format(CultureInfo.CurrentCulture, SR.WrongTrustDirection , Name, targetDomain.Name, direction), typeof(TrustRelationshipInformation), null);
+ throw new ActiveDirectoryObjectNotFoundException(SR.Format(SR.WrongTrustDirection , Name, targetDomain.Name, direction), typeof(TrustRelationshipInformation), null);
}
}
}
diff --git a/src/System.DirectoryServices/src/System/DirectoryServices/ActiveDirectory/DomainCollection.cs b/src/System.DirectoryServices/src/System/DirectoryServices/ActiveDirectory/DomainCollection.cs
index 977d660009..38a19277b4 100644
--- a/src/System.DirectoryServices/src/System/DirectoryServices/ActiveDirectory/DomainCollection.cs
+++ b/src/System.DirectoryServices/src/System/DirectoryServices/ActiveDirectory/DomainCollection.cs
@@ -2,13 +2,10 @@
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
+using System.Collections;
+
namespace System.DirectoryServices.ActiveDirectory
{
- using System;
- using System.Collections;
- using System.Globalization;
- using System.DirectoryServices;
-
public class DomainCollection : ReadOnlyCollectionBase
{
internal DomainCollection() { }
@@ -24,13 +21,7 @@ namespace System.DirectoryServices.ActiveDirectory
}
}
- public Domain this[int index]
- {
- get
- {
- return (Domain)InnerList[index];
- }
- }
+ public Domain this[int index] => (Domain)InnerList[index];
public bool Contains(Domain domain)
{
@@ -69,13 +60,8 @@ namespace System.DirectoryServices.ActiveDirectory
InnerList.CopyTo(domains, index);
}
- internal int Add(Domain domain)
- {
- return InnerList.Add(domain);
- }
- internal void Clear()
- {
- InnerList.Clear();
- }
+ internal int Add(Domain domain) => InnerList.Add(domain);
+
+ internal void Clear() => InnerList.Clear();
}
}
diff --git a/src/System.DirectoryServices/src/System/DirectoryServices/ActiveDirectory/DomainController.cs b/src/System.DirectoryServices/src/System/DirectoryServices/ActiveDirectory/DomainController.cs
index 3cdffbdd1a..6d357992cb 100644
--- a/src/System.DirectoryServices/src/System/DirectoryServices/ActiveDirectory/DomainController.cs
+++ b/src/System.DirectoryServices/src/System/DirectoryServices/ActiveDirectory/DomainController.cs
@@ -2,19 +2,15 @@
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
+using System.Net;
+using System.ComponentModel;
+using System.Collections;
+using System.Globalization;
+using System.Runtime.InteropServices;
+using System.Diagnostics;
+
namespace System.DirectoryServices.ActiveDirectory
{
- using System;
- using System.Net;
- using System.ComponentModel;
- using System.Collections;
- using System.Globalization;
- using System.Security.Principal;
- using System.Runtime.InteropServices;
- using System.Threading;
- using System.Diagnostics;
- using System.Security.Permissions;
-
[Flags]
public enum SyncFromAllServersOptions
{
@@ -46,7 +42,7 @@ namespace System.DirectoryServices.ActiveDirectory
{
private IntPtr _dsHandle = IntPtr.Zero;
private IntPtr _authIdentity = IntPtr.Zero;
- private string[] _becomeRoleOwnerAttrs = null;
+ private readonly string[] _becomeRoleOwnerAttrs = null;
private bool _disposed = false;
// internal variables for the public properties
@@ -59,7 +55,7 @@ namespace System.DirectoryServices.ActiveDirectory
private bool _dcInfoInitialized = false;
internal SyncUpdateCallback userDelegate = null;
- internal SyncReplicaFromAllServersCallback syncAllFunctionPointer = null;
+ internal readonly SyncReplicaFromAllServersCallback syncAllFunctionPointer = null;
// this is twice the maximum allowed RIDPool size which is 15k
internal const int UpdateRidPoolSeizureValue = 30000;
@@ -97,11 +93,7 @@ namespace System.DirectoryServices.ActiveDirectory
#region IDisposable
- ~DomainController()
- {
- // finalizer is called => Dispose has not been called yet.
- Dispose(false);
- }
+ ~DomainController() => Dispose(false);
// private Dispose method
protected override void Dispose(bool disposing)
@@ -145,7 +137,7 @@ namespace System.DirectoryServices.ActiveDirectory
// target should be a server
if (!(context.isServer()))
{
- throw new ActiveDirectoryObjectNotFoundException(String.Format(CultureInfo.CurrentCulture, SR.DCNotFound , context.Name), typeof(DomainController), context.Name);
+ throw new ActiveDirectoryObjectNotFoundException(SR.Format(SR.DCNotFound , context.Name), typeof(DomainController), context.Name);
}
// work with copy of the context
@@ -159,7 +151,7 @@ namespace System.DirectoryServices.ActiveDirectory
DirectoryEntry rootDSE = directoryEntryMgr.GetCachedDirectoryEntry(WellKnownDN.RootDSE);
if (!Utils.CheckCapability(rootDSE, Capability.ActiveDirectory))
{
- throw new ActiveDirectoryObjectNotFoundException(String.Format(CultureInfo.CurrentCulture, SR.DCNotFound , context.Name), typeof(DomainController), context.Name);
+ throw new ActiveDirectoryObjectNotFoundException(SR.Format(SR.DCNotFound , context.Name), typeof(DomainController), context.Name);
}
dcDnsName = (string)PropertyManager.GetPropertyValue(context, rootDSE, PropertyManager.DnsHostName);
}
@@ -169,7 +161,7 @@ namespace System.DirectoryServices.ActiveDirectory
if (errorCode == unchecked((int)0x8007203a))
{
- throw new ActiveDirectoryObjectNotFoundException(String.Format(CultureInfo.CurrentCulture, SR.DCNotFound , context.Name), typeof(DomainController), context.Name);
+ throw new ActiveDirectoryObjectNotFoundException(SR.Format(SR.DCNotFound , context.Name), typeof(DomainController), context.Name);
}
else
{
@@ -785,7 +777,7 @@ namespace System.DirectoryServices.ActiveDirectory
}
if (cachedSiteName == null)
{
- throw new ActiveDirectoryOperationException(String.Format(CultureInfo.CurrentCulture, SR.SiteNameNotFound , Name));
+ throw new ActiveDirectoryOperationException(SR.Format(SR.SiteNameNotFound , Name));
}
return cachedSiteName;
@@ -803,7 +795,7 @@ namespace System.DirectoryServices.ActiveDirectory
}
if (cachedSiteObjectName == null)
{
- throw new ActiveDirectoryOperationException(String.Format(CultureInfo.CurrentCulture, SR.SiteObjectNameNotFound , Name));
+ throw new ActiveDirectoryOperationException(SR.Format(SR.SiteObjectNameNotFound , Name));
}
return cachedSiteObjectName;
}
@@ -820,7 +812,7 @@ namespace System.DirectoryServices.ActiveDirectory
}
if (_cachedComputerObjectName == null)
{
- throw new ActiveDirectoryOperationException(String.Format(CultureInfo.CurrentCulture, SR.ComputerObjectNameNotFound , Name));
+ throw new ActiveDirectoryOperationException(SR.Format(SR.ComputerObjectNameNotFound , Name));
}
return _cachedComputerObjectName;
}
@@ -837,7 +829,7 @@ namespace System.DirectoryServices.ActiveDirectory
}
if (cachedServerObjectName == null)
{
- throw new ActiveDirectoryOperationException(String.Format(CultureInfo.CurrentCulture, SR.ServerObjectNameNotFound , Name));
+ throw new ActiveDirectoryOperationException(SR.Format(SR.ServerObjectNameNotFound , Name));
}
return cachedServerObjectName;
}
@@ -854,7 +846,7 @@ namespace System.DirectoryServices.ActiveDirectory
}
if (cachedNtdsaObjectName == null)
{
- throw new ActiveDirectoryOperationException(String.Format(CultureInfo.CurrentCulture, SR.NtdsaObjectNameNotFound , Name));
+ throw new ActiveDirectoryOperationException(SR.Format(SR.NtdsaObjectNameNotFound , Name));
}
return cachedNtdsaObjectName;
}
@@ -871,7 +863,7 @@ namespace System.DirectoryServices.ActiveDirectory
}
if (cachedNtdsaObjectGuid.Equals(Guid.Empty))
{
- throw new ActiveDirectoryOperationException(String.Format(CultureInfo.CurrentCulture, SR.NtdsaObjectGuidNotFound , Name));
+ throw new ActiveDirectoryOperationException(SR.Format(SR.NtdsaObjectGuidNotFound , Name));
}
return cachedNtdsaObjectGuid;
}
@@ -896,21 +888,9 @@ namespace System.DirectoryServices.ActiveDirectory
}
}
- public override ReplicationConnectionCollection InboundConnections
- {
- get
- {
- return GetInboundConnectionsHelper();
- }
- }
+ public override ReplicationConnectionCollection InboundConnections => GetInboundConnectionsHelper();
- public override ReplicationConnectionCollection OutboundConnections
- {
- get
- {
- return GetOutboundConnectionsHelper();
- }
- }
+ public override ReplicationConnectionCollection OutboundConnections => GetOutboundConnectionsHelper();
internal IntPtr Handle
{
@@ -961,7 +941,7 @@ namespace System.DirectoryServices.ActiveDirectory
}
else
{
- throw new ActiveDirectoryObjectNotFoundException(String.Format(CultureInfo.CurrentCulture, SR.DCNotFoundInDomain , context.Name), typeof(DomainController), null);
+ throw new ActiveDirectoryObjectNotFoundException(SR.Format(SR.DCNotFoundInDomain , context.Name), typeof(DomainController), null);
}
}
else
@@ -991,7 +971,7 @@ namespace System.DirectoryServices.ActiveDirectory
if (e.ErrorCode == unchecked((int)0x8007203a))
{
// server is down
- throw new ActiveDirectoryObjectNotFoundException(String.Format(CultureInfo.CurrentCulture, SR.DCNotFoundInDomain , context.Name), typeof(DomainController), null);
+ throw new ActiveDirectoryObjectNotFoundException(SR.Format(SR.DCNotFoundInDomain , context.Name), typeof(DomainController), null);
}
else
{
@@ -1036,7 +1016,7 @@ namespace System.DirectoryServices.ActiveDirectory
if (errorCode == NativeMethods.ERROR_NO_SUCH_DOMAIN)
{
- throw new ActiveDirectoryObjectNotFoundException(String.Format(CultureInfo.CurrentCulture, SR.DCNotFoundInDomain , domainName), typeof(DomainController), null);
+ throw new ActiveDirectoryObjectNotFoundException(SR.Format(SR.DCNotFoundInDomain , domainName), typeof(DomainController), null);
}
// this can only occur when flag is being explicitly passed (since the flags that we pass internally are valid)
if (errorCode == NativeMethods.ERROR_INVALID_FLAGS)
diff --git a/src/System.DirectoryServices/src/System/DirectoryServices/ActiveDirectory/DomainControllerCollection.cs b/src/System.DirectoryServices/src/System/DirectoryServices/ActiveDirectory/DomainControllerCollection.cs
index 72815f98eb..7d536e0491 100644
--- a/src/System.DirectoryServices/src/System/DirectoryServices/ActiveDirectory/DomainControllerCollection.cs
+++ b/src/System.DirectoryServices/src/System/DirectoryServices/ActiveDirectory/DomainControllerCollection.cs
@@ -2,12 +2,10 @@
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
+using System.Collections;
+
namespace System.DirectoryServices.ActiveDirectory
{
- using System;
- using System.Collections;
- using System.Globalization;
-
public class DomainControllerCollection : ReadOnlyCollectionBase
{
internal DomainControllerCollection() { }
@@ -20,13 +18,7 @@ namespace System.DirectoryServices.ActiveDirectory
}
}
- public DomainController this[int index]
- {
- get
- {
- return (DomainController)InnerList[index];
- }
- }
+ public DomainController this[int index] => (DomainController)InnerList[index];
public bool Contains(DomainController domainController)
{
diff --git a/src/System.DirectoryServices/src/System/DirectoryServices/ActiveDirectory/Exception.cs b/src/System.DirectoryServices/src/System/DirectoryServices/ActiveDirectory/Exception.cs
index 7e5d64c9df..e9a9d2e289 100644
--- a/src/System.DirectoryServices/src/System/DirectoryServices/ActiveDirectory/Exception.cs
+++ b/src/System.DirectoryServices/src/System/DirectoryServices/ActiveDirectory/Exception.cs
@@ -2,89 +2,44 @@
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
-// </copyright>
+using System.Runtime.InteropServices;
+using System.Security.Authentication;
+using System.Text;
+using System.Collections;
+using System.Runtime.Serialization;
+using System.Security.Permissions;
namespace System.DirectoryServices.ActiveDirectory
{
- using System;
- using System.Net;
- using System.Runtime.InteropServices;
- using System.Security.Authentication;
- using System.Text;
- using System.Collections;
- using System.Runtime.Serialization;
- using System.Security.Permissions;
- using System.Globalization;
-
-
public class SyncFromAllServersErrorInformation
{
- private SyncFromAllServersErrorCategory _category;
- private int _errorCode;
- private string _errorMessage = null;
- private string _sourceServer = null;
- private string _targetServer = null;
-
internal SyncFromAllServersErrorInformation(SyncFromAllServersErrorCategory category, int errorCode, string errorMessage, string sourceServer, string targetServer)
{
- _category = category;
- _errorCode = errorCode;
- _errorMessage = errorMessage;
- _sourceServer = sourceServer;
- _targetServer = targetServer;
+ ErrorCategory = category;
+ ErrorCode = errorCode;
+ ErrorMessage = errorMessage;
+ SourceServer = sourceServer;
+ TargetServer = targetServer;
}
- public SyncFromAllServersErrorCategory ErrorCategory
- {
- get
- {
- return _category;
- }
- }
+ public SyncFromAllServersErrorCategory ErrorCategory { get; }
- public int ErrorCode
- {
- get
- {
- return _errorCode;
- }
- }
+ public int ErrorCode { get; }
- public string ErrorMessage
- {
- get
- {
- return _errorMessage;
- }
- }
+ public string ErrorMessage { get; }
- public string TargetServer
- {
- get
- {
- return _targetServer;
- }
- }
+ public string TargetServer { get; }
- public string SourceServer
- {
- get
- {
- return _sourceServer;
- }
- }
+ public string SourceServer { get; }
}
[Serializable]
public class ActiveDirectoryObjectNotFoundException : Exception, ISerializable
{
- private Type _objectType;
- private string _name = null;
-
public ActiveDirectoryObjectNotFoundException(string message, Type type, string name) : base(message)
{
- _objectType = type;
- _name = name;
+ Type = type;
+ Name = name;
}
public ActiveDirectoryObjectNotFoundException(string message, Exception inner) : base(message, inner) { }
@@ -98,21 +53,9 @@ namespace System.DirectoryServices.ActiveDirectory
throw new PlatformNotSupportedException();
}
- public Type Type
- {
- get
- {
- return _objectType;
- }
- }
+ public Type Type { get; }
- public string Name
- {
- get
- {
- return _name;
- }
- }
+ public string Name { get; }
[SecurityPermissionAttribute(SecurityAction.LinkDemand, SerializationFormatter = true)]
public override void GetObjectData(SerializationInfo serializationInfo, StreamingContext streamingContext)
@@ -124,16 +67,14 @@ namespace System.DirectoryServices.ActiveDirectory
[Serializable]
public class ActiveDirectoryOperationException : Exception, ISerializable
{
- private int _errorCode = 0;
-
public ActiveDirectoryOperationException(string message, Exception inner, int errorCode) : base(message, inner)
{
- _errorCode = errorCode;
+ ErrorCode = errorCode;
}
public ActiveDirectoryOperationException(string message, int errorCode) : base(message)
{
- _errorCode = errorCode;
+ ErrorCode = errorCode;
}
public ActiveDirectoryOperationException(string message, Exception inner) : base(message, inner) { }
@@ -147,13 +88,7 @@ namespace System.DirectoryServices.ActiveDirectory
throw new PlatformNotSupportedException();
}
- public int ErrorCode
- {
- get
- {
- return _errorCode;
- }
- }
+ public int ErrorCode { get; }
public override void GetObjectData(SerializationInfo serializationInfo, StreamingContext streamingContext)
{
@@ -164,19 +99,16 @@ namespace System.DirectoryServices.ActiveDirectory
[Serializable]
public class ActiveDirectoryServerDownException : Exception, ISerializable
{
- private int _errorCode = 0;
- private string _name = null;
-
public ActiveDirectoryServerDownException(string message, Exception inner, int errorCode, string name) : base(message, inner)
{
- _errorCode = errorCode;
- _name = name;
+ ErrorCode = errorCode;
+ Name = name;
}
public ActiveDirectoryServerDownException(string message, int errorCode, string name) : base(message)
{
- _errorCode = errorCode;
- _name = name;
+ ErrorCode = errorCode;
+ Name = name;
}
public ActiveDirectoryServerDownException(string message, Exception inner) : base(message, inner) { }
@@ -190,30 +122,18 @@ namespace System.DirectoryServices.ActiveDirectory
throw new PlatformNotSupportedException();
}
- public int ErrorCode
- {
- get
- {
- return _errorCode;
- }
- }
+ public int ErrorCode { get; }
- public string Name
- {
- get
- {
- return _name;
- }
- }
+ public string Name { get; }
public override String Message
{
get
{
String s = base.Message;
- if (!((_name == null) ||
- (_name.Length == 0)))
- return s + Environment.NewLine + String.Format(CultureInfo.CurrentCulture, SR.Name , _name) + Environment.NewLine;
+ if (!((Name == null) ||
+ (Name.Length == 0)))
+ return s + Environment.NewLine + SR.Format(SR.Name , Name) + Environment.NewLine;
else
return s;
}
@@ -285,11 +205,9 @@ namespace System.DirectoryServices.ActiveDirectory
[Serializable]
public class ForestTrustCollisionException : ActiveDirectoryOperationException, ISerializable
{
- private ForestTrustRelationshipCollisionCollection _collisions = new ForestTrustRelationshipCollisionCollection();
-
public ForestTrustCollisionException(string message, Exception inner, ForestTrustRelationshipCollisionCollection collisions) : base(message, inner)
{
- _collisions = collisions;
+ Collisions = collisions;
}
public ForestTrustCollisionException(string message, Exception inner) : base(message, inner) { }
@@ -303,13 +221,7 @@ namespace System.DirectoryServices.ActiveDirectory
throw new PlatformNotSupportedException();
}
- public ForestTrustRelationshipCollisionCollection Collisions
- {
- get
- {
- return _collisions;
- }
- }
+ public ForestTrustRelationshipCollisionCollection Collisions { get; } = new ForestTrustRelationshipCollisionCollection();
public override void GetObjectData(SerializationInfo serializationInfo, StreamingContext streamingContext)
{
@@ -467,7 +379,7 @@ namespace System.DirectoryServices.ActiveDirectory
}
else
{
- errorMsg = String.Format(CultureInfo.CurrentCulture, SR.DSUnknown , Convert.ToString(temp, 16));
+ errorMsg = SR.Format(SR.DSUnknown , Convert.ToString(temp, 16));
}
return errorMsg;
diff --git a/src/System.DirectoryServices/src/System/DirectoryServices/ActiveDirectory/Forest.cs b/src/System.DirectoryServices/src/System/DirectoryServices/ActiveDirectory/Forest.cs
index 3551bb18cd..91ca6ba433 100644
--- a/src/System.DirectoryServices/src/System/DirectoryServices/ActiveDirectory/Forest.cs
+++ b/src/System.DirectoryServices/src/System/DirectoryServices/ActiveDirectory/Forest.cs
@@ -2,19 +2,15 @@
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
+using System.Text;
+using System.Collections;
+using System.Globalization;
+using System.ComponentModel;
+using System.Runtime.InteropServices;
+using System.Diagnostics;
+
namespace System.DirectoryServices.ActiveDirectory
{
- using System;
- using System.Text;
- using System.Threading;
- using System.Collections;
- using System.Globalization;
- using System.ComponentModel;
- using System.DirectoryServices;
- using System.Runtime.InteropServices;
- using System.Diagnostics;
- using System.Security.Permissions;
-
public enum ForestMode : int
{
Unknown = -1,
@@ -30,14 +26,14 @@ namespace System.DirectoryServices.ActiveDirectory
public class Forest : IDisposable
{
// Private Variables
- private DirectoryContext _context = null;
- private DirectoryEntryManager _directoryEntryMgr = null;
- private IntPtr _dsHandle = IntPtr.Zero;
- private IntPtr _authIdentity = IntPtr.Zero;
+ private readonly DirectoryContext _context = null;
+ private readonly DirectoryEntryManager _directoryEntryMgr = null;
+ private readonly IntPtr _dsHandle = IntPtr.Zero;
+ private readonly IntPtr _authIdentity = IntPtr.Zero;
private bool _disposed = false;
// Internal variables corresponding to public properties
- private string _forestDnsName = null;
+ private readonly string _forestDnsName = null;
private ReadOnlySiteCollection _cachedSites = null;
private DomainCollection _cachedDomains = null;
private GlobalCatalogCollection _cachedGlobalCatalogs = null;
@@ -64,10 +60,7 @@ namespace System.DirectoryServices.ActiveDirectory
#region IDisposable
- public void Dispose()
- {
- Dispose(true);
- }
+ public void Dispose() => Dispose(true);
// private Dispose method
protected void Dispose(bool disposing)
@@ -124,7 +117,7 @@ namespace System.DirectoryServices.ActiveDirectory
}
else
{
- throw new ActiveDirectoryObjectNotFoundException(String.Format(CultureInfo.CurrentCulture, SR.DCNotFound , context.Name), typeof(Forest), null);
+ throw new ActiveDirectoryObjectNotFoundException(SR.Format(SR.DCNotFound , context.Name), typeof(Forest), null);
}
}
}
@@ -141,7 +134,7 @@ namespace System.DirectoryServices.ActiveDirectory
rootDSE = directoryEntryMgr.GetCachedDirectoryEntry(WellKnownDN.RootDSE);
if ((context.isServer()) && (!Utils.CheckCapability(rootDSE, Capability.ActiveDirectory)))
{
- throw new ActiveDirectoryObjectNotFoundException(String.Format(CultureInfo.CurrentCulture, SR.DCNotFound , context.Name), typeof(Forest), null);
+ throw new ActiveDirectoryObjectNotFoundException(SR.Format(SR.DCNotFound , context.Name), typeof(Forest), null);
}
rootDomainNC = (string)PropertyManager.GetPropertyValue(context, rootDSE, PropertyManager.RootDomainNamingContext);
}
@@ -157,7 +150,7 @@ namespace System.DirectoryServices.ActiveDirectory
}
else
{
- throw new ActiveDirectoryObjectNotFoundException(String.Format(CultureInfo.CurrentCulture, SR.DCNotFound , context.Name), typeof(Forest), null);
+ throw new ActiveDirectoryObjectNotFoundException(SR.Format(SR.DCNotFound , context.Name), typeof(Forest), null);
}
}
else
@@ -236,10 +229,7 @@ namespace System.DirectoryServices.ActiveDirectory
RaiseForestFunctionalityLevel((int)forestMode);
}
- public override string ToString()
- {
- return Name;
- }
+ public override string ToString() => Name;
public GlobalCatalog FindGlobalCatalog()
{
@@ -351,7 +341,7 @@ namespace System.DirectoryServices.ActiveDirectory
else
{
// trust relationship does not exist
- throw new ActiveDirectoryObjectNotFoundException(String.Format(CultureInfo.CurrentCulture, SR.ForestTrustDoesNotExist , Name, targetForestName), typeof(TrustRelationshipInformation), null);
+ throw new ActiveDirectoryObjectNotFoundException(SR.Format(SR.ForestTrustDoesNotExist , Name, targetForestName), typeof(TrustRelationshipInformation), null);
}
}
@@ -467,7 +457,7 @@ namespace System.DirectoryServices.ActiveDirectory
}
catch (ActiveDirectoryObjectNotFoundException)
{
- throw new ActiveDirectoryObjectNotFoundException(String.Format(CultureInfo.CurrentCulture, SR.WrongTrustDirection , Name, targetForest.Name, direction), typeof(ForestTrustRelationshipInformation), null);
+ throw new ActiveDirectoryObjectNotFoundException(SR.Format(SR.WrongTrustDirection , Name, targetForest.Name, direction), typeof(ForestTrustRelationshipInformation), null);
}
}
@@ -480,7 +470,7 @@ namespace System.DirectoryServices.ActiveDirectory
}
catch (ActiveDirectoryObjectNotFoundException)
{
- throw new ActiveDirectoryObjectNotFoundException(String.Format(CultureInfo.CurrentCulture, SR.WrongTrustDirection , Name, targetForest.Name, direction), typeof(ForestTrustRelationshipInformation), null);
+ throw new ActiveDirectoryObjectNotFoundException(SR.Format(SR.WrongTrustDirection , Name, targetForest.Name, direction), typeof(ForestTrustRelationshipInformation), null);
}
}
}
@@ -638,14 +628,11 @@ namespace System.DirectoryServices.ActiveDirectory
}
catch (ActiveDirectoryObjectNotFoundException)
{
- throw new ActiveDirectoryObjectNotFoundException(String.Format(CultureInfo.CurrentCulture, SR.WrongTrustDirection , Name, targetForest.Name, direction), typeof(ForestTrustRelationshipInformation), null);
+ throw new ActiveDirectoryObjectNotFoundException(SR.Format(SR.WrongTrustDirection , Name, targetForest.Name, direction), typeof(ForestTrustRelationshipInformation), null);
}
}
- public static Forest GetCurrentForest()
- {
- return Forest.GetForest(new DirectoryContext(DirectoryContextType.Forest));
- }
+ public static Forest GetCurrentForest() => GetForest(new DirectoryContext(DirectoryContextType.Forest));
#endregion public methods
@@ -806,10 +793,7 @@ namespace System.DirectoryServices.ActiveDirectory
#region private methods
- internal DirectoryContext GetDirectoryContext()
- {
- return _context;
- }
+ internal DirectoryContext GetDirectoryContext() => _context;
private int GetForestModeLevel()
{
@@ -1235,7 +1219,7 @@ namespace System.DirectoryServices.ActiveDirectory
}
catch (ActiveDirectoryObjectNotFoundException)
{
- throw new ActiveDirectoryObjectNotFoundException(String.Format(CultureInfo.CurrentCulture, SR.WrongTrustDirection , Name, targetForest.Name, direction), typeof(ForestTrustRelationshipInformation), null);
+ throw new ActiveDirectoryObjectNotFoundException(SR.Format(SR.WrongTrustDirection , Name, targetForest.Name, direction), typeof(ForestTrustRelationshipInformation), null);
}
}
@@ -1248,7 +1232,7 @@ namespace System.DirectoryServices.ActiveDirectory
}
catch (ActiveDirectoryObjectNotFoundException)
{
- throw new ActiveDirectoryObjectNotFoundException(String.Format(CultureInfo.CurrentCulture, SR.WrongTrustDirection , Name, targetForest.Name, direction), typeof(ForestTrustRelationshipInformation), null);
+ throw new ActiveDirectoryObjectNotFoundException(SR.Format(SR.WrongTrustDirection , Name, targetForest.Name, direction), typeof(ForestTrustRelationshipInformation), null);
}
}
}
diff --git a/src/System.DirectoryServices/src/System/DirectoryServices/ActiveDirectory/ForestTrustCollision.cs b/src/System.DirectoryServices/src/System/DirectoryServices/ActiveDirectory/ForestTrustCollision.cs
index aca9bb97f1..e01d041fac 100644
--- a/src/System.DirectoryServices/src/System/DirectoryServices/ActiveDirectory/ForestTrustCollision.cs
+++ b/src/System.DirectoryServices/src/System/DirectoryServices/ActiveDirectory/ForestTrustCollision.cs
@@ -2,60 +2,27 @@
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
+using System.Collections;
+
namespace System.DirectoryServices.ActiveDirectory
{
- using System;
- using System.Runtime.InteropServices;
- using System.Collections;
- using System.Collections.Specialized;
- using System.Diagnostics;
-
public class ForestTrustRelationshipCollision
{
- private ForestTrustCollisionType _type;
- private TopLevelNameCollisionOptions _tlnFlag;
- private DomainCollisionOptions _domainFlag;
- private string _record = null;
-
internal ForestTrustRelationshipCollision(ForestTrustCollisionType collisionType, TopLevelNameCollisionOptions TLNFlag, DomainCollisionOptions domainFlag, string record)
{
- _type = collisionType;
- _tlnFlag = TLNFlag;
- _domainFlag = domainFlag;
- _record = record;
+ CollisionType = collisionType;
+ TopLevelNameCollisionOption = TLNFlag;
+ DomainCollisionOption = domainFlag;
+ CollisionRecord = record;
}
- public ForestTrustCollisionType CollisionType
- {
- get
- {
- return _type;
- }
- }
+ public ForestTrustCollisionType CollisionType { get; }
- public TopLevelNameCollisionOptions TopLevelNameCollisionOption
- {
- get
- {
- return _tlnFlag;
- }
- }
+ public TopLevelNameCollisionOptions TopLevelNameCollisionOption { get; }
- public DomainCollisionOptions DomainCollisionOption
- {
- get
- {
- return _domainFlag;
- }
- }
+ public DomainCollisionOptions DomainCollisionOption { get; }
- public string CollisionRecord
- {
- get
- {
- return _record;
- }
- }
+ public string CollisionRecord { get; }
}
public class ForestTrustRelationshipCollisionCollection : ReadOnlyCollectionBase
@@ -64,10 +31,7 @@ namespace System.DirectoryServices.ActiveDirectory
public ForestTrustRelationshipCollision this[int index]
{
- get
- {
- return (ForestTrustRelationshipCollision)InnerList[index];
- }
+ get => (ForestTrustRelationshipCollision)InnerList[index];
}
public bool Contains(ForestTrustRelationshipCollision collision)
@@ -91,9 +55,6 @@ namespace System.DirectoryServices.ActiveDirectory
InnerList.CopyTo(array, index);
}
- internal int Add(ForestTrustRelationshipCollision collision)
- {
- return InnerList.Add(collision);
- }
+ internal int Add(ForestTrustRelationshipCollision collision) => InnerList.Add(collision);
}
}
diff --git a/src/System.DirectoryServices/src/System/DirectoryServices/ActiveDirectory/ForestTrustDomainInfoCollection.cs b/src/System.DirectoryServices/src/System/DirectoryServices/ActiveDirectory/ForestTrustDomainInfoCollection.cs
index c4176cc756..0a291b16ea 100644
--- a/src/System.DirectoryServices/src/System/DirectoryServices/ActiveDirectory/ForestTrustDomainInfoCollection.cs
+++ b/src/System.DirectoryServices/src/System/DirectoryServices/ActiveDirectory/ForestTrustDomainInfoCollection.cs
@@ -2,23 +2,17 @@
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
+using System.Collections;
+
namespace System.DirectoryServices.ActiveDirectory
{
- using System;
- using System.Runtime.InteropServices;
- using System.Collections;
- using System.Globalization;
-
public class ForestTrustDomainInfoCollection : ReadOnlyCollectionBase
{
internal ForestTrustDomainInfoCollection() { }
public ForestTrustDomainInformation this[int index]
{
- get
- {
- return (ForestTrustDomainInformation)InnerList[index];
- }
+ get => (ForestTrustDomainInformation)InnerList[index];
}
public bool Contains(ForestTrustDomainInformation information)
@@ -42,9 +36,6 @@ namespace System.DirectoryServices.ActiveDirectory
InnerList.CopyTo(array, index);
}
- internal int Add(ForestTrustDomainInformation info)
- {
- return InnerList.Add(info);
- }
+ internal int Add(ForestTrustDomainInformation info) => InnerList.Add(info);
}
}
diff --git a/src/System.DirectoryServices/src/System/DirectoryServices/ActiveDirectory/ForestTrustDomainInformation.cs b/src/System.DirectoryServices/src/System/DirectoryServices/ActiveDirectory/ForestTrustDomainInformation.cs
index 2dc86aade0..ff85328061 100644
--- a/src/System.DirectoryServices/src/System/DirectoryServices/ActiveDirectory/ForestTrustDomainInformation.cs
+++ b/src/System.DirectoryServices/src/System/DirectoryServices/ActiveDirectory/ForestTrustDomainInformation.cs
@@ -2,14 +2,11 @@
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
+using System.Runtime.InteropServices;
+using System.ComponentModel;
+
namespace System.DirectoryServices.ActiveDirectory
{
- using System;
- using System.Runtime.InteropServices;
- using System.Collections;
- using System.Globalization;
- using System.ComponentModel;
-
public enum ForestTrustDomainStatus
{
Enabled = 0,
@@ -21,17 +18,14 @@ namespace System.DirectoryServices.ActiveDirectory
public class ForestTrustDomainInformation
{
- private string _dnsName = null;
- private string _nbName = null;
- private string _sid = null;
private ForestTrustDomainStatus _status;
internal LARGE_INTEGER time;
internal ForestTrustDomainInformation(int flag, LSA_FOREST_TRUST_DOMAIN_INFO domainInfo, LARGE_INTEGER time)
{
_status = (ForestTrustDomainStatus)flag;
- _dnsName = Marshal.PtrToStringUni(domainInfo.DNSNameBuffer, domainInfo.DNSNameLength / 2);
- _nbName = Marshal.PtrToStringUni(domainInfo.NetBIOSNameBuffer, domainInfo.NetBIOSNameLength / 2);
+ DnsName = Marshal.PtrToStringUni(domainInfo.DNSNameBuffer, domainInfo.DNSNameLength / 2);
+ NetBiosName = Marshal.PtrToStringUni(domainInfo.NetBIOSNameBuffer, domainInfo.NetBIOSNameLength / 2);
IntPtr ptr = (IntPtr)0;
int result = UnsafeNativeMethods.ConvertSidToStringSidW(domainInfo.sid, ref ptr);
if (result == 0)
@@ -41,7 +35,7 @@ namespace System.DirectoryServices.ActiveDirectory
try
{
- _sid = Marshal.PtrToStringUni(ptr);
+ DomainSid = Marshal.PtrToStringUni(ptr);
}
finally
{
@@ -51,36 +45,15 @@ namespace System.DirectoryServices.ActiveDirectory
this.time = time;
}
- public string DnsName
- {
- get
- {
- return _dnsName;
- }
- }
+ public string DnsName { get; }
- public string NetBiosName
- {
- get
- {
- return _nbName;
- }
- }
+ public string NetBiosName { get; }
- public string DomainSid
- {
- get
- {
- return _sid;
- }
- }
+ public string DomainSid { get; }
public ForestTrustDomainStatus Status
{
- get
- {
- return _status;
- }
+ get => _status;
set
{
if (value != ForestTrustDomainStatus.Enabled &&
diff --git a/src/System.DirectoryServices/src/System/DirectoryServices/ActiveDirectory/ForestTrustRelationshipInformation.cs b/src/System.DirectoryServices/src/System/DirectoryServices/ActiveDirectory/ForestTrustRelationshipInformation.cs
index f729a0dd08..ad2b3ed364 100644
--- a/src/System.DirectoryServices/src/System/DirectoryServices/ActiveDirectory/ForestTrustRelationshipInformation.cs
+++ b/src/System.DirectoryServices/src/System/DirectoryServices/ActiveDirectory/ForestTrustRelationshipInformation.cs
@@ -2,15 +2,12 @@
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
+using System.Runtime.InteropServices;
+using System.Collections;
+using System.Collections.Specialized;
+
namespace System.DirectoryServices.ActiveDirectory
{
- using System;
- using System.Runtime.InteropServices;
- using System.Collections;
- using System.Collections.Specialized;
- using System.Diagnostics;
- using System.Security.Permissions;
-
public class ForestTrustRelationshipInformation : TrustRelationshipInformation
{
private TopLevelNameCollection _topLevelNames = new TopLevelNameCollection();
diff --git a/src/System.DirectoryServices/src/System/DirectoryServices/ActiveDirectory/GlobalCatalog.cs b/src/System.DirectoryServices/src/System/DirectoryServices/ActiveDirectory/GlobalCatalog.cs
index 5d0857ad78..e42bb71896 100644
--- a/src/System.DirectoryServices/src/System/DirectoryServices/ActiveDirectory/GlobalCatalog.cs
+++ b/src/System.DirectoryServices/src/System/DirectoryServices/ActiveDirectory/GlobalCatalog.cs
@@ -2,17 +2,12 @@
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
+using System.Collections;
+using System.Diagnostics;
+using System.Runtime.InteropServices;
+
namespace System.DirectoryServices.ActiveDirectory
{
- using System;
- using System.Collections;
- using System.Diagnostics;
- using System.ComponentModel;
- using System.Security.Principal;
- using System.Runtime.InteropServices;
- using System.Security.Permissions;
- using System.Globalization;
-
public class GlobalCatalog : DomainController
{
// private variables
@@ -50,7 +45,7 @@ namespace System.DirectoryServices.ActiveDirectory
// target should be a server
if (!(context.isServer()))
{
- throw new ActiveDirectoryObjectNotFoundException(String.Format(CultureInfo.CurrentCulture, SR.GCNotFound , context.Name), typeof(GlobalCatalog), context.Name);
+ throw new ActiveDirectoryObjectNotFoundException(SR.Format(SR.GCNotFound , context.Name), typeof(GlobalCatalog), context.Name);
}
// work with copy of the context
@@ -65,14 +60,14 @@ namespace System.DirectoryServices.ActiveDirectory
DirectoryEntry rootDSE = DirectoryEntryManager.GetDirectoryEntry(context, WellKnownDN.RootDSE);
if (!Utils.CheckCapability(rootDSE, Capability.ActiveDirectory))
{
- throw new ActiveDirectoryObjectNotFoundException(String.Format(CultureInfo.CurrentCulture, SR.GCNotFound , context.Name), typeof(GlobalCatalog), context.Name);
+ throw new ActiveDirectoryObjectNotFoundException(SR.Format(SR.GCNotFound , context.Name), typeof(GlobalCatalog), context.Name);
}
gcDnsName = (string)PropertyManager.GetPropertyValue(context, rootDSE, PropertyManager.DnsHostName);
isGlobalCatalog = (bool)Boolean.Parse((string)PropertyManager.GetPropertyValue(context, rootDSE, PropertyManager.IsGlobalCatalogReady));
if (!isGlobalCatalog)
{
- throw new ActiveDirectoryObjectNotFoundException(String.Format(CultureInfo.CurrentCulture, SR.GCNotFound , context.Name), typeof(GlobalCatalog), context.Name);
+ throw new ActiveDirectoryObjectNotFoundException(SR.Format(SR.GCNotFound , context.Name), typeof(GlobalCatalog), context.Name);
}
}
catch (COMException e)
@@ -81,7 +76,7 @@ namespace System.DirectoryServices.ActiveDirectory
if (errorCode == unchecked((int)0x8007203a))
{
- throw new ActiveDirectoryObjectNotFoundException(String.Format(CultureInfo.CurrentCulture, SR.GCNotFound , context.Name), typeof(GlobalCatalog), context.Name);
+ throw new ActiveDirectoryObjectNotFoundException(SR.Format(SR.GCNotFound , context.Name), typeof(GlobalCatalog), context.Name);
}
else
{
@@ -323,7 +318,7 @@ namespace System.DirectoryServices.ActiveDirectory
}
else
{
- throw new ActiveDirectoryObjectNotFoundException(String.Format(CultureInfo.CurrentCulture, SR.GCNotFoundInForest , context.Name), typeof(GlobalCatalog), null);
+ throw new ActiveDirectoryObjectNotFoundException(SR.Format(SR.GCNotFoundInForest , context.Name), typeof(GlobalCatalog), null);
}
}
else
@@ -353,7 +348,7 @@ namespace System.DirectoryServices.ActiveDirectory
if (e.ErrorCode == unchecked((int)0x8007203a))
{
// server is down
- throw new ActiveDirectoryObjectNotFoundException(String.Format(CultureInfo.CurrentCulture, SR.GCNotFoundInForest , context.Name), typeof(GlobalCatalog), null);
+ throw new ActiveDirectoryObjectNotFoundException(SR.Format(SR.GCNotFoundInForest , context.Name), typeof(GlobalCatalog), null);
}
else
{
@@ -413,7 +408,7 @@ namespace System.DirectoryServices.ActiveDirectory
if (errorCode == NativeMethods.ERROR_NO_SUCH_DOMAIN)
{
- throw new ActiveDirectoryObjectNotFoundException(String.Format(CultureInfo.CurrentCulture, SR.GCNotFoundInForest , forestName), typeof(GlobalCatalog), null);
+ throw new ActiveDirectoryObjectNotFoundException(SR.Format(SR.GCNotFoundInForest , forestName), typeof(GlobalCatalog), null);
}
// this can only occur when flag is being explicitly passed (since the flags that we pass internally are valid)
if (errorCode == NativeMethods.ERROR_INVALID_FLAGS)
diff --git a/src/System.DirectoryServices/src/System/DirectoryServices/ActiveDirectory/GlobalCatalogCollection.cs b/src/System.DirectoryServices/src/System/DirectoryServices/ActiveDirectory/GlobalCatalogCollection.cs
index cc7f232e5c..2dc51eb6f3 100644
--- a/src/System.DirectoryServices/src/System/DirectoryServices/ActiveDirectory/GlobalCatalogCollection.cs
+++ b/src/System.DirectoryServices/src/System/DirectoryServices/ActiveDirectory/GlobalCatalogCollection.cs
@@ -2,12 +2,10 @@
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
+using System.Collections;
+
namespace System.DirectoryServices.ActiveDirectory
{
- using System;
- using System.Globalization;
- using System.Collections;
-
public class GlobalCatalogCollection : ReadOnlyCollectionBase
{
internal GlobalCatalogCollection() { }
@@ -20,13 +18,7 @@ namespace System.DirectoryServices.ActiveDirectory
}
}
- public GlobalCatalog this[int index]
- {
- get
- {
- return (GlobalCatalog)InnerList[index];
- }
- }
+ public GlobalCatalog this[int index] => (GlobalCatalog)InnerList[index];
public bool Contains(GlobalCatalog globalCatalog)
{
diff --git a/src/System.DirectoryServices/src/System/DirectoryServices/ActiveDirectory/Locator.cs b/src/System.DirectoryServices/src/System/DirectoryServices/ActiveDirectory/Locator.cs
index cc69a52e4b..4b0ec6fc14 100644
--- a/src/System.DirectoryServices/src/System/DirectoryServices/ActiveDirectory/Locator.cs
+++ b/src/System.DirectoryServices/src/System/DirectoryServices/ActiveDirectory/Locator.cs
@@ -2,15 +2,12 @@
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
+using System.Collections;
+using System.Globalization;
+using System.Runtime.InteropServices;
+
namespace System.DirectoryServices.ActiveDirectory
{
- using System;
- using System.Net;
- using System.Text;
- using System.Collections;
- using System.Globalization;
- using System.Runtime.InteropServices;
-
internal sealed class Locator
{
// To disable public/protected constructors for this class
diff --git a/src/System.DirectoryServices/src/System/DirectoryServices/ActiveDirectory/LocatorFlag.cs b/src/System.DirectoryServices/src/System/DirectoryServices/ActiveDirectory/LocatorFlag.cs
index 19075d037f..5a60b0659d 100644
--- a/src/System.DirectoryServices/src/System/DirectoryServices/ActiveDirectory/LocatorFlag.cs
+++ b/src/System.DirectoryServices/src/System/DirectoryServices/ActiveDirectory/LocatorFlag.cs
@@ -4,28 +4,6 @@
namespace System.DirectoryServices.ActiveDirectory
{
- using System;
-
- /*
- #define DS_FORCE_REDISCOVERY 0x00000001
- #define DS_DIRECTORY_SERVICE_REQUIRED 0x00000010
- #define DS_DIRECTORY_SERVICE_PREFERRED 0x00000020
- #define DS_GC_SERVER_REQUIRED 0x00000040
- #define DS_PDC_REQUIRED 0x00000080
- #define DS_BACKGROUND_ONLY 0x00000100
- #define DS_IP_REQUIRED 0x00000200
- #define DS_KDC_REQUIRED 0x00000400
- #define DS_TIMESERV_REQUIRED 0x00000800
- #define DS_WRITABLE_REQUIRED 0x00001000
- #define DS_GOOD_TIMESERV_PREFERRED 0x00002000
- #define DS_AVOID_SELF 0x00004000
- #define DS_ONLY_LDAP_NEEDED 0x00008000
- #define DS_IS_FLAT_NAME 0x00010000
- #define DS_IS_DNS_NAME 0x00020000
- #define DS_RETURN_DNS_NAME 0x40000000
- #define DS_RETURN_FLAT_NAME 0x80000000
- */
-
[Flags]
public enum LocatorOptions : long
{
diff --git a/src/System.DirectoryServices/src/System/DirectoryServices/ActiveDirectory/NativeMethods.cs b/src/System.DirectoryServices/src/System/DirectoryServices/ActiveDirectory/NativeMethods.cs
index a4b8700c29..3b55664c5d 100644
--- a/src/System.DirectoryServices/src/System/DirectoryServices/ActiveDirectory/NativeMethods.cs
+++ b/src/System.DirectoryServices/src/System/DirectoryServices/ActiveDirectory/NativeMethods.cs
@@ -2,15 +2,12 @@
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
+using System.Security;
+using System.Runtime.InteropServices;
+
namespace System.DirectoryServices.ActiveDirectory
{
#pragma warning disable BCL0015 // CoreFxPort
- using System;
- using System.Security;
- using System.Collections;
- using System.DirectoryServices;
- using System.DirectoryServices.Interop;
- using System.Runtime.InteropServices;
/*typedef struct _DOMAIN_CONTROLLER_INFO {
LPTSTR DomainControllerName;
@@ -882,17 +879,9 @@ namespace System.DirectoryServices.ActiveDirectory
set;
}
- bool Abstract
- {
- get;
- set;
- }
+ bool Abstract { get; set; }
- bool Auxiliary
- {
- get;
- set;
- }
+ bool Auxiliary { get; set; }
object MandatoryProperties
{
@@ -908,11 +897,7 @@ namespace System.DirectoryServices.ActiveDirectory
set;
}
- object NamingProperties
- {
- get;
- set;
- }
+ object NamingProperties { get; set; }
object DerivedFrom
{
@@ -934,17 +919,9 @@ namespace System.DirectoryServices.ActiveDirectory
set;
}
- object Containment
- {
- get;
- set;
- }
+ object Containment { get; set; }
- bool Container
- {
- get;
- set;
- }
+ bool Container { get; set; }
string HelpFileName
{
diff --git a/src/System.DirectoryServices/src/System/DirectoryServices/ActiveDirectory/PropertyManager.cs b/src/System.DirectoryServices/src/System/DirectoryServices/ActiveDirectory/PropertyManager.cs
index d8001e1087..47a46ed32f 100644
--- a/src/System.DirectoryServices/src/System/DirectoryServices/ActiveDirectory/PropertyManager.cs
+++ b/src/System.DirectoryServices/src/System/DirectoryServices/ActiveDirectory/PropertyManager.cs
@@ -2,13 +2,11 @@
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
+using System.Diagnostics;
+using System.Runtime.InteropServices;
+
namespace System.DirectoryServices.ActiveDirectory
{
- using System;
- using System.Diagnostics;
- using System.Runtime.InteropServices;
- using System.Globalization;
-
internal class PropertyManager
{
public static string DefaultNamingContext = "defaultNamingContext";
@@ -144,11 +142,11 @@ namespace System.DirectoryServices.ActiveDirectory
{
if (directoryEntry.Properties[PropertyManager.DistinguishedName].Count != 0)
{
- throw new ActiveDirectoryOperationException(String.Format(CultureInfo.CurrentCulture, SR.PropertyNotFoundOnObject , propertyName, directoryEntry.Properties[PropertyManager.DistinguishedName].Value));
+ throw new ActiveDirectoryOperationException(SR.Format(SR.PropertyNotFoundOnObject , propertyName, directoryEntry.Properties[PropertyManager.DistinguishedName].Value));
}
else
{
- throw new ActiveDirectoryOperationException(String.Format(CultureInfo.CurrentCulture, SR.PropertyNotFound , propertyName));
+ throw new ActiveDirectoryOperationException(SR.Format(SR.PropertyNotFound , propertyName));
}
}
}
@@ -172,7 +170,7 @@ namespace System.DirectoryServices.ActiveDirectory
propertyValues = res.Properties[propertyName];
if ((propertyValues == null) || (propertyValues.Count < 1))
{
- throw new ActiveDirectoryOperationException(String.Format(CultureInfo.CurrentCulture, SR.PropertyNotFound , propertyName));
+ throw new ActiveDirectoryOperationException(SR.Format(SR.PropertyNotFound , propertyName));
}
}
catch (COMException e)
diff --git a/src/System.DirectoryServices/src/System/DirectoryServices/ActiveDirectory/ReadOnlyActiveDirectorySchemaClassCollection.cs b/src/System.DirectoryServices/src/System/DirectoryServices/ActiveDirectory/ReadOnlyActiveDirectorySchemaClassCollection.cs
index d68acc590a..03e14e7b88 100644
--- a/src/System.DirectoryServices/src/System/DirectoryServices/ActiveDirectory/ReadOnlyActiveDirectorySchemaClassCollection.cs
+++ b/src/System.DirectoryServices/src/System/DirectoryServices/ActiveDirectory/ReadOnlyActiveDirectorySchemaClassCollection.cs
@@ -2,12 +2,10 @@
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
+using System.Collections;
+
namespace System.DirectoryServices.ActiveDirectory
{
- using System;
- using System.Globalization;
- using System.Collections;
-
public class ReadOnlyActiveDirectorySchemaClassCollection : ReadOnlyCollectionBase
{
internal ReadOnlyActiveDirectorySchemaClassCollection() { }
@@ -22,10 +20,7 @@ namespace System.DirectoryServices.ActiveDirectory
public ActiveDirectorySchemaClass this[int index]
{
- get
- {
- return (ActiveDirectorySchemaClass)InnerList[index];
- }
+ get => (ActiveDirectorySchemaClass)InnerList[index];
}
public bool Contains(ActiveDirectorySchemaClass schemaClass)
diff --git a/src/System.DirectoryServices/src/System/DirectoryServices/ActiveDirectory/ReadOnlyActiveDirectorySchemaPropertyCollection.cs b/src/System.DirectoryServices/src/System/DirectoryServices/ActiveDirectory/ReadOnlyActiveDirectorySchemaPropertyCollection.cs
index 2f0692af06..a729e56d9f 100644
--- a/src/System.DirectoryServices/src/System/DirectoryServices/ActiveDirectory/ReadOnlyActiveDirectorySchemaPropertyCollection.cs
+++ b/src/System.DirectoryServices/src/System/DirectoryServices/ActiveDirectory/ReadOnlyActiveDirectorySchemaPropertyCollection.cs
@@ -2,12 +2,10 @@
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
+using System.Collections;
+
namespace System.DirectoryServices.ActiveDirectory
{
- using System;
- using System.Globalization;
- using System.Collections;
-
public class ReadOnlyActiveDirectorySchemaPropertyCollection : ReadOnlyCollectionBase
{
internal ReadOnlyActiveDirectorySchemaPropertyCollection() { }
@@ -22,10 +20,7 @@ namespace System.DirectoryServices.ActiveDirectory
public ActiveDirectorySchemaProperty this[int index]
{
- get
- {
- return (ActiveDirectorySchemaProperty)InnerList[index];
- }
+ get => (ActiveDirectorySchemaProperty)InnerList[index];
}
public bool Contains(ActiveDirectorySchemaProperty schemaProperty)
diff --git a/src/System.DirectoryServices/src/System/DirectoryServices/ActiveDirectory/ReadOnlyDirectoryServerCollection.cs b/src/System.DirectoryServices/src/System/DirectoryServices/ActiveDirectory/ReadOnlyDirectoryServerCollection.cs
index 113baf7eb4..7c1bfb71ba 100644
--- a/src/System.DirectoryServices/src/System/DirectoryServices/ActiveDirectory/ReadOnlyDirectoryServerCollection.cs
+++ b/src/System.DirectoryServices/src/System/DirectoryServices/ActiveDirectory/ReadOnlyDirectoryServerCollection.cs
@@ -2,12 +2,10 @@
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
+using System.Collections;
+
namespace System.DirectoryServices.ActiveDirectory
{
- using System;
- using System.Globalization;
- using System.Collections;
-
public class ReadOnlyDirectoryServerCollection : ReadOnlyCollectionBase
{
internal ReadOnlyDirectoryServerCollection() { }
@@ -23,13 +21,7 @@ namespace System.DirectoryServices.ActiveDirectory
}
}
- public DirectoryServer this[int index]
- {
- get
- {
- return (DirectoryServer)InnerList[index];
- }
- }
+ public DirectoryServer this[int index] => (DirectoryServer)InnerList[index];
public bool Contains(DirectoryServer directoryServer)
{
@@ -68,19 +60,10 @@ namespace System.DirectoryServices.ActiveDirectory
InnerList.CopyTo(directoryServers, index);
}
- internal int Add(DirectoryServer server)
- {
- return InnerList.Add(server);
- }
+ internal int Add(DirectoryServer server) => InnerList.Add(server);
- internal void AddRange(ICollection servers)
- {
- InnerList.AddRange(servers);
- }
+ internal void AddRange(ICollection servers) => InnerList.AddRange(servers);
- internal void Clear()
- {
- InnerList.Clear();
- }
+ internal void Clear() => InnerList.Clear();
}
}
diff --git a/src/System.DirectoryServices/src/System/DirectoryServices/ActiveDirectory/ReadOnlySiteCollection.cs b/src/System.DirectoryServices/src/System/DirectoryServices/ActiveDirectory/ReadOnlySiteCollection.cs
index e80b1b0fe1..9f7e676ce2 100644
--- a/src/System.DirectoryServices/src/System/DirectoryServices/ActiveDirectory/ReadOnlySiteCollection.cs
+++ b/src/System.DirectoryServices/src/System/DirectoryServices/ActiveDirectory/ReadOnlySiteCollection.cs
@@ -2,15 +2,10 @@
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
+using System.Collections;
+
namespace System.DirectoryServices.ActiveDirectory
{
- using System;
- using System.Runtime.InteropServices;
- using System.Collections;
- using System.DirectoryServices;
- using System.Diagnostics;
- using System.Globalization;
-
public class ReadOnlySiteCollection : ReadOnlyCollectionBase
{
internal ReadOnlySiteCollection() { }
@@ -23,13 +18,7 @@ namespace System.DirectoryServices.ActiveDirectory
}
}
- public ActiveDirectorySite this[int index]
- {
- get
- {
- return (ActiveDirectorySite)InnerList[index];
- }
- }
+ public ActiveDirectorySite this[int index] => (ActiveDirectorySite)InnerList[index];
public bool Contains(ActiveDirectorySite site)
{
@@ -78,14 +67,8 @@ namespace System.DirectoryServices.ActiveDirectory
InnerList.CopyTo(sites, index);
}
- internal int Add(ActiveDirectorySite site)
- {
- return InnerList.Add(site);
- }
+ internal int Add(ActiveDirectorySite site) => InnerList.Add(site);
- internal void Clear()
- {
- InnerList.Clear();
- }
+ internal void Clear() => InnerList.Clear();
}
}
diff --git a/src/System.DirectoryServices/src/System/DirectoryServices/ActiveDirectory/ReadOnlySiteLinkBridgeCollection.cs b/src/System.DirectoryServices/src/System/DirectoryServices/ActiveDirectory/ReadOnlySiteLinkBridgeCollection.cs
index aec6cd78bc..98f272ecb8 100644
--- a/src/System.DirectoryServices/src/System/DirectoryServices/ActiveDirectory/ReadOnlySiteLinkBridgeCollection.cs
+++ b/src/System.DirectoryServices/src/System/DirectoryServices/ActiveDirectory/ReadOnlySiteLinkBridgeCollection.cs
@@ -2,24 +2,17 @@
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
+using System.Collections;
+
namespace System.DirectoryServices.ActiveDirectory
{
- using System;
- using System.Runtime.InteropServices;
- using System.Collections;
- using System.DirectoryServices;
- using System.Globalization;
-
public class ReadOnlySiteLinkBridgeCollection : ReadOnlyCollectionBase
{
internal ReadOnlySiteLinkBridgeCollection() { }
public ActiveDirectorySiteLinkBridge this[int index]
{
- get
- {
- return (ActiveDirectorySiteLinkBridge)InnerList[index];
- }
+ get => (ActiveDirectorySiteLinkBridge)InnerList[index];
}
public bool Contains(ActiveDirectorySiteLinkBridge bridge)
@@ -67,14 +60,8 @@ namespace System.DirectoryServices.ActiveDirectory
InnerList.CopyTo(bridges, index);
}
- internal int Add(ActiveDirectorySiteLinkBridge bridge)
- {
- return InnerList.Add(bridge);
- }
+ internal int Add(ActiveDirectorySiteLinkBridge bridge) => InnerList.Add(bridge);
- internal void Clear()
- {
- InnerList.Clear();
- }
+ internal void Clear() => InnerList.Clear();
}
}
diff --git a/src/System.DirectoryServices/src/System/DirectoryServices/ActiveDirectory/ReadOnlySiteLinkCollection.cs b/src/System.DirectoryServices/src/System/DirectoryServices/ActiveDirectory/ReadOnlySiteLinkCollection.cs
index 01a48a1bc8..bf8fcae6db 100644
--- a/src/System.DirectoryServices/src/System/DirectoryServices/ActiveDirectory/ReadOnlySiteLinkCollection.cs
+++ b/src/System.DirectoryServices/src/System/DirectoryServices/ActiveDirectory/ReadOnlySiteLinkCollection.cs
@@ -2,24 +2,17 @@
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
+using System.Collections;
+
namespace System.DirectoryServices.ActiveDirectory
{
- using System;
- using System.Runtime.InteropServices;
- using System.Collections;
- using System.DirectoryServices;
- using System.Globalization;
-
public class ReadOnlySiteLinkCollection : ReadOnlyCollectionBase
{
internal ReadOnlySiteLinkCollection() { }
public ActiveDirectorySiteLink this[int index]
{
- get
- {
- return (ActiveDirectorySiteLink)InnerList[index];
- }
+ get => (ActiveDirectorySiteLink)InnerList[index];
}
public bool Contains(ActiveDirectorySiteLink link)
@@ -67,15 +60,8 @@ namespace System.DirectoryServices.ActiveDirectory
InnerList.CopyTo(links, index);
}
- internal int Add(ActiveDirectorySiteLink link)
- {
- return InnerList.Add(link);
- }
+ internal int Add(ActiveDirectorySiteLink link) => InnerList.Add(link);
- internal void Clear()
- {
- InnerList.Clear();
- }
+ internal void Clear() => InnerList.Clear();
}
}
-
diff --git a/src/System.DirectoryServices/src/System/DirectoryServices/ActiveDirectory/ReadOnlyStringCollection.cs b/src/System.DirectoryServices/src/System/DirectoryServices/ActiveDirectory/ReadOnlyStringCollection.cs
index ec603b94f1..95a79e0bea 100644
--- a/src/System.DirectoryServices/src/System/DirectoryServices/ActiveDirectory/ReadOnlyStringCollection.cs
+++ b/src/System.DirectoryServices/src/System/DirectoryServices/ActiveDirectory/ReadOnlyStringCollection.cs
@@ -2,13 +2,10 @@
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
+using System.Collections;
+
namespace System.DirectoryServices.ActiveDirectory
{
- using System;
- using System.Collections;
- using System.Globalization;
- using System.DirectoryServices;
-
public class ReadOnlyStringCollection : ReadOnlyCollectionBase
{
internal ReadOnlyStringCollection() { }
@@ -76,9 +73,6 @@ namespace System.DirectoryServices.ActiveDirectory
InnerList.CopyTo(values, index);
}
- internal void Add(String value)
- {
- InnerList.Add(value);
- }
+ internal void Add(string value) => InnerList.Add(value);
}
}
diff --git a/src/System.DirectoryServices/src/System/DirectoryServices/ActiveDirectory/ReplicationConnection.cs b/src/System.DirectoryServices/src/System/DirectoryServices/ActiveDirectory/ReplicationConnection.cs
index f1ba2a82b9..8673b9e242 100644
--- a/src/System.DirectoryServices/src/System/DirectoryServices/ActiveDirectory/ReplicationConnection.cs
+++ b/src/System.DirectoryServices/src/System/DirectoryServices/ActiveDirectory/ReplicationConnection.cs
@@ -2,16 +2,12 @@
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
+using System.Runtime.InteropServices;
+using System.Diagnostics;
+using System.ComponentModel;
+
namespace System.DirectoryServices.ActiveDirectory
{
- using System;
- using System.Runtime.InteropServices;
- using System.DirectoryServices;
- using System.Diagnostics;
- using System.ComponentModel;
- using System.Globalization;
- using System.Security.Permissions;
-
public enum NotificationStatus
{
NoNotification = 0,
@@ -27,18 +23,18 @@ namespace System.DirectoryServices.ActiveDirectory
public class ReplicationConnection : IDisposable
{
- internal DirectoryContext context = null;
- internal DirectoryEntry cachedDirectoryEntry = null;
+ internal readonly DirectoryContext context = null;
+ internal readonly DirectoryEntry cachedDirectoryEntry = null;
internal bool existingConnection = false;
private bool _disposed = false;
private bool _checkADAM = false;
private bool _isADAMServer = false;
private int _options = 0;
- private string _connectionName = null;
+ private readonly string _connectionName = null;
private string _sourceServerName = null;
private string _destinationServerName = null;
- private ActiveDirectoryTransportType _transport = ActiveDirectoryTransportType.Rpc;
+ private readonly ActiveDirectoryTransportType _transport = ActiveDirectoryTransportType.Rpc;
private const string ADAMGuid = "1.2.840.113556.1.4.1851";
diff --git a/src/System.DirectoryServices/src/System/DirectoryServices/ActiveDirectory/ReplicationConnectionCollection.cs b/src/System.DirectoryServices/src/System/DirectoryServices/ActiveDirectory/ReplicationConnectionCollection.cs
index a26d7476f0..6f95647425 100644
--- a/src/System.DirectoryServices/src/System/DirectoryServices/ActiveDirectory/ReplicationConnectionCollection.cs
+++ b/src/System.DirectoryServices/src/System/DirectoryServices/ActiveDirectory/ReplicationConnectionCollection.cs
@@ -2,23 +2,15 @@
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
+using System.Collections;
+
namespace System.DirectoryServices.ActiveDirectory
{
- using System;
- using System.Collections;
- using System.Globalization;
-
public class ReplicationConnectionCollection : ReadOnlyCollectionBase
{
internal ReplicationConnectionCollection() { }
- public ReplicationConnection this[int index]
- {
- get
- {
- return (ReplicationConnection)InnerList[index];
- }
- }
+ public ReplicationConnection this[int index] => (ReplicationConnection)InnerList[index];
public bool Contains(ReplicationConnection connection)
{
@@ -26,7 +18,7 @@ namespace System.DirectoryServices.ActiveDirectory
throw new ArgumentNullException("connection");
if (!connection.existingConnection)
- throw new InvalidOperationException(String.Format(CultureInfo.CurrentCulture, SR.ConnectionNotCommitted , connection.Name));
+ throw new InvalidOperationException(SR.Format(SR.ConnectionNotCommitted , connection.Name));
string dn = (string)PropertyManager.GetPropertyValue(connection.context, connection.cachedDirectoryEntry, PropertyManager.DistinguishedName);
@@ -49,7 +41,7 @@ namespace System.DirectoryServices.ActiveDirectory
throw new ArgumentNullException("connection");
if (!connection.existingConnection)
- throw new InvalidOperationException(String.Format(CultureInfo.CurrentCulture, SR.ConnectionNotCommitted , connection.Name));
+ throw new InvalidOperationException(SR.Format(SR.ConnectionNotCommitted , connection.Name));
string dn = (string)PropertyManager.GetPropertyValue(connection.context, connection.cachedDirectoryEntry, PropertyManager.DistinguishedName);
@@ -71,9 +63,6 @@ namespace System.DirectoryServices.ActiveDirectory
InnerList.CopyTo(connections, index);
}
- internal int Add(ReplicationConnection value)
- {
- return InnerList.Add(value);
- }
+ internal int Add(ReplicationConnection value) => InnerList.Add(value);
}
}
diff --git a/src/System.DirectoryServices/src/System/DirectoryServices/ActiveDirectory/ReplicationCursor.cs b/src/System.DirectoryServices/src/System/DirectoryServices/ActiveDirectory/ReplicationCursor.cs
index 6c1ebfa986..67d2d1a06b 100644
--- a/src/System.DirectoryServices/src/System/DirectoryServices/ActiveDirectory/ReplicationCursor.cs
+++ b/src/System.DirectoryServices/src/System/DirectoryServices/ActiveDirectory/ReplicationCursor.cs
@@ -2,30 +2,26 @@
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
+using System.Runtime.InteropServices;
+
namespace System.DirectoryServices.ActiveDirectory
{
- using System;
- using System.Runtime.InteropServices;
-
public class ReplicationCursor
{
- private string _partition;
- private Guid _invocationID;
- private long _USN;
private string _serverDN = null;
- private DateTime _syncTime;
- private bool _advanced = false;
+ private readonly DateTime _syncTime;
+ private readonly bool _advanced = false;
private string _sourceServer = null;
- private DirectoryServer _server = null;
+ private readonly DirectoryServer _server = null;
private ReplicationCursor() { }
internal ReplicationCursor(DirectoryServer server, string partition, Guid guid, long filter, long time, IntPtr dn)
{
- _partition = partition;
- _invocationID = guid;
- _USN = filter;
+ PartitionName = partition;
+ SourceInvocationId = guid;
+ UpToDatenessUsn = filter;
// convert filetime to DateTime
_syncTime = DateTime.FromFileTime(time);
@@ -40,36 +36,18 @@ namespace System.DirectoryServices.ActiveDirectory
internal ReplicationCursor(DirectoryServer server, string partition, Guid guid, long filter)
{
- _partition = partition;
- _invocationID = guid;
- _USN = filter;
+ PartitionName = partition;
+ SourceInvocationId = guid;
+ UpToDatenessUsn = filter;
_server = server;
}
- public string PartitionName
- {
- get
- {
- return _partition;
- }
- }
+ public string PartitionName { get; }
- public Guid SourceInvocationId
- {
- get
- {
- return _invocationID;
- }
- }
+ public Guid SourceInvocationId { get; }
- public long UpToDatenessUsn
- {
- get
- {
- return _USN;
- }
- }
+ public long UpToDatenessUsn { get; }
public string SourceServer
{
diff --git a/src/System.DirectoryServices/src/System/DirectoryServices/ActiveDirectory/ReplicationCursorCollection.cs b/src/System.DirectoryServices/src/System/DirectoryServices/ActiveDirectory/ReplicationCursorCollection.cs
index dde8543f3a..5e09b45efc 100644
--- a/src/System.DirectoryServices/src/System/DirectoryServices/ActiveDirectory/ReplicationCursorCollection.cs
+++ b/src/System.DirectoryServices/src/System/DirectoryServices/ActiveDirectory/ReplicationCursorCollection.cs
@@ -2,27 +2,21 @@
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
+using System.Collections;
+using System.Runtime.InteropServices;
+
namespace System.DirectoryServices.ActiveDirectory
{
- using System;
- using System.Collections;
- using System.Runtime.InteropServices;
-
public class ReplicationCursorCollection : ReadOnlyCollectionBase
{
- private DirectoryServer _server = null;
+ private readonly DirectoryServer _server = null;
+
internal ReplicationCursorCollection(DirectoryServer server)
{
_server = server;
}
- public ReplicationCursor this[int index]
- {
- get
- {
- return (ReplicationCursor)InnerList[index];
- }
- }
+ public ReplicationCursor this[int index] => (ReplicationCursor)InnerList[index];
public bool Contains(ReplicationCursor cursor)
{
@@ -45,10 +39,7 @@ namespace System.DirectoryServices.ActiveDirectory
InnerList.CopyTo(values, index);
}
- private int Add(ReplicationCursor cursor)
- {
- return InnerList.Add(cursor);
- }
+ private int Add(ReplicationCursor cursor) => InnerList.Add(cursor);
internal void AddHelper(string partition, object cursors, bool advanced, IntPtr info)
{
diff --git a/src/System.DirectoryServices/src/System/DirectoryServices/ActiveDirectory/ReplicationFailure.cs b/src/System.DirectoryServices/src/System/DirectoryServices/ActiveDirectory/ReplicationFailure.cs
index b6a97bbd69..9acc0c21af 100644
--- a/src/System.DirectoryServices/src/System/DirectoryServices/ActiveDirectory/ReplicationFailure.cs
+++ b/src/System.DirectoryServices/src/System/DirectoryServices/ActiveDirectory/ReplicationFailure.cs
@@ -2,24 +2,19 @@
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
+using System.Runtime.InteropServices;
+using System.Collections;
+
namespace System.DirectoryServices.ActiveDirectory
{
- using System;
- using System.Runtime.InteropServices;
- using System.Collections;
- using System.Diagnostics;
-
public class ReplicationFailure
{
- private string _sourceDsaDN;
- private Guid _uuidDsaObjGuid;
- private DateTime _timeFirstFailure;
- private int _numFailures;
+ private readonly string _sourceDsaDN;
internal int lastResult;
- private DirectoryServer _server = null;
+ private readonly DirectoryServer _server = null;
private string _sourceServer = null;
- private Hashtable _nameTable = null;
+ private readonly Hashtable _nameTable = null;
internal ReplicationFailure(IntPtr addr, DirectoryServer server, Hashtable table)
{
@@ -27,9 +22,9 @@ namespace System.DirectoryServices.ActiveDirectory
Marshal.PtrToStructure(addr, failure);
_sourceDsaDN = Marshal.PtrToStringUni(failure.pszDsaDN);
- _uuidDsaObjGuid = failure.uuidDsaObjGuid;
- _timeFirstFailure = DateTime.FromFileTime(failure.ftimeFirstFailure);
- _numFailures = failure.cNumFailures;
+ SourceServerGuid = failure.uuidDsaObjGuid;
+ FirstFailureTime = DateTime.FromFileTime(failure.ftimeFirstFailure);
+ ConsecutiveFailureCount = failure.cNumFailures;
lastResult = failure.dwLastResult;
_server = server;
@@ -59,44 +54,14 @@ namespace System.DirectoryServices.ActiveDirectory
}
}
- private Guid SourceServerGuid
- {
- get
- {
- return _uuidDsaObjGuid;
- }
- }
+ private Guid SourceServerGuid { get; }
- public DateTime FirstFailureTime
- {
- get
- {
- return _timeFirstFailure;
- }
- }
+ public DateTime FirstFailureTime { get; }
- public int ConsecutiveFailureCount
- {
- get
- {
- return _numFailures;
- }
- }
+ public int ConsecutiveFailureCount { get; }
- public int LastErrorCode
- {
- get
- {
- return lastResult;
- }
- }
+ public int LastErrorCode => lastResult;
- public string LastErrorMessage
- {
- get
- {
- return ExceptionHelper.GetErrorMessage(lastResult, false);
- }
- }
+ public string LastErrorMessage => ExceptionHelper.GetErrorMessage(LastErrorCode, false);
}
}
diff --git a/src/System.DirectoryServices/src/System/DirectoryServices/ActiveDirectory/ReplicationFailureCollection.cs b/src/System.DirectoryServices/src/System/DirectoryServices/ActiveDirectory/ReplicationFailureCollection.cs
index c0530978af..54e1f9c399 100644
--- a/src/System.DirectoryServices/src/System/DirectoryServices/ActiveDirectory/ReplicationFailureCollection.cs
+++ b/src/System.DirectoryServices/src/System/DirectoryServices/ActiveDirectory/ReplicationFailureCollection.cs
@@ -2,16 +2,15 @@
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
+using System.Collections;
+using System.Runtime.InteropServices;
+
namespace System.DirectoryServices.ActiveDirectory
{
- using System;
- using System.Collections;
- using System.Runtime.InteropServices;
-
public class ReplicationFailureCollection : ReadOnlyCollectionBase
{
- private DirectoryServer _server = null;
- private Hashtable _nameTable = null;
+ private readonly DirectoryServer _server = null;
+ private readonly Hashtable _nameTable = null;
internal ReplicationFailureCollection(DirectoryServer server)
{
@@ -20,13 +19,7 @@ namespace System.DirectoryServices.ActiveDirectory
_nameTable = Hashtable.Synchronized(tempNameTable);
}
- public ReplicationFailure this[int index]
- {
- get
- {
- return (ReplicationFailure)InnerList[index];
- }
- }
+ public ReplicationFailure this[int index] => (ReplicationFailure)InnerList[index];
public bool Contains(ReplicationFailure failure)
{
@@ -49,10 +42,7 @@ namespace System.DirectoryServices.ActiveDirectory
InnerList.CopyTo(failures, index);
}
- private int Add(ReplicationFailure failure)
- {
- return InnerList.Add(failure);
- }
+ private int Add(ReplicationFailure failure) => InnerList.Add(failure);
internal void AddHelper(DS_REPL_KCC_DSA_FAILURES failures, IntPtr info)
{
diff --git a/src/System.DirectoryServices/src/System/DirectoryServices/ActiveDirectory/ReplicationNeighbor.cs b/src/System.DirectoryServices/src/System/DirectoryServices/ActiveDirectory/ReplicationNeighbor.cs
index 5fa56b8ed7..751df664f3 100644
--- a/src/System.DirectoryServices/src/System/DirectoryServices/ActiveDirectory/ReplicationNeighbor.cs
+++ b/src/System.DirectoryServices/src/System/DirectoryServices/ActiveDirectory/ReplicationNeighbor.cs
@@ -2,13 +2,11 @@
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
+using System.Runtime.InteropServices;
+using System.Collections;
+
namespace System.DirectoryServices.ActiveDirectory
{
- using System;
- using System.Runtime.InteropServices;
- using System.Collections;
- using System.Globalization;
-
public enum ActiveDirectoryTransportType
{
Rpc = 0,
@@ -36,29 +34,19 @@ namespace System.DirectoryServices.ActiveDirectory
NoChangeNotifications = 0x20000000,
PartialAttributeSet = 0x40000000
}
+
+ private readonly string _sourceServerDN;
- private string _namingContext;
- private string _sourceServerDN;
- private ActiveDirectoryTransportType _transportType;
- private ReplicationNeighborOptions _replicaFlags;
- private Guid _uuidSourceDsaInvocationID;
- private long _usnLastObjChangeSynced;
- private long _usnAttributeFilter;
- private DateTime _timeLastSyncSuccess;
- private DateTime _timeLastSyncAttempt;
- private int _lastSyncResult;
- private int _consecutiveSyncFailures;
-
- private DirectoryServer _server = null;
+ private readonly DirectoryServer _server = null;
private string _sourceServer = null;
- private Hashtable _nameTable = null;
+ private readonly Hashtable _nameTable = null;
internal ReplicationNeighbor(IntPtr addr, DirectoryServer server, Hashtable table)
{
DS_REPL_NEIGHBOR neighbor = new DS_REPL_NEIGHBOR();
Marshal.PtrToStructure(addr, neighbor);
- _namingContext = Marshal.PtrToStringUni(neighbor.pszNamingContext);
+ PartitionName = Marshal.PtrToStringUni(neighbor.pszNamingContext);
_sourceServerDN = Marshal.PtrToStringUni(neighbor.pszSourceDsaDN);
string transportDN = Marshal.PtrToStringUni(neighbor.pszAsyncIntersiteTransportDN);
@@ -68,31 +56,25 @@ namespace System.DirectoryServices.ActiveDirectory
string transport = (Utils.GetDNComponents(rdn))[0].Value;
if (String.Compare(transport, "SMTP", StringComparison.OrdinalIgnoreCase) == 0)
- _transportType = ActiveDirectoryTransportType.Smtp;
+ TransportType = ActiveDirectoryTransportType.Smtp;
else
- _transportType = ActiveDirectoryTransportType.Rpc;
+ TransportType = ActiveDirectoryTransportType.Rpc;
}
- _replicaFlags = (ReplicationNeighborOptions)neighbor.dwReplicaFlags;
- _uuidSourceDsaInvocationID = neighbor.uuidSourceDsaInvocationID;
- _usnLastObjChangeSynced = neighbor.usnLastObjChangeSynced;
- _usnAttributeFilter = neighbor.usnAttributeFilter;
- _timeLastSyncSuccess = DateTime.FromFileTime(neighbor.ftimeLastSyncSuccess);
- _timeLastSyncAttempt = DateTime.FromFileTime(neighbor.ftimeLastSyncAttempt);
- _lastSyncResult = neighbor.dwLastSyncResult;
- _consecutiveSyncFailures = neighbor.cNumConsecutiveSyncFailures;
+ ReplicationNeighborOption = (ReplicationNeighborOptions)neighbor.dwReplicaFlags;
+ SourceInvocationId = neighbor.uuidSourceDsaInvocationID;
+ UsnLastObjectChangeSynced = neighbor.usnLastObjChangeSynced;
+ UsnAttributeFilter = neighbor.usnAttributeFilter;
+ LastSuccessfulSync = DateTime.FromFileTime(neighbor.ftimeLastSyncSuccess);
+ LastAttemptedSync = DateTime.FromFileTime(neighbor.ftimeLastSyncAttempt);
+ LastSyncResult = neighbor.dwLastSyncResult;
+ ConsecutiveFailureCount = neighbor.cNumConsecutiveSyncFailures;
_server = server;
_nameTable = table;
}
- public string PartitionName
- {
- get
- {
- return _namingContext;
- }
- }
+ public string PartitionName { get; }
public string SourceServer
{
@@ -117,84 +99,24 @@ namespace System.DirectoryServices.ActiveDirectory
}
}
- public ActiveDirectoryTransportType TransportType
- {
- get
- {
- return _transportType;
- }
- }
+ public ActiveDirectoryTransportType TransportType { get; }
- public ReplicationNeighborOptions ReplicationNeighborOption
- {
- get
- {
- return _replicaFlags;
- }
- }
+ public ReplicationNeighborOptions ReplicationNeighborOption { get; }
- public Guid SourceInvocationId
- {
- get
- {
- return _uuidSourceDsaInvocationID;
- }
- }
+ public Guid SourceInvocationId { get; }
- public long UsnLastObjectChangeSynced
- {
- get
- {
- return _usnLastObjChangeSynced;
- }
- }
+ public long UsnLastObjectChangeSynced { get; }
- public long UsnAttributeFilter
- {
- get
- {
- return _usnAttributeFilter;
- }
- }
+ public long UsnAttributeFilter { get; }
- public DateTime LastSuccessfulSync
- {
- get
- {
- return _timeLastSyncSuccess;
- }
- }
+ public DateTime LastSuccessfulSync { get; }
- public DateTime LastAttemptedSync
- {
- get
- {
- return _timeLastSyncAttempt;
- }
- }
+ public DateTime LastAttemptedSync { get; }
- public int LastSyncResult
- {
- get
- {
- return _lastSyncResult;
- }
- }
+ public int LastSyncResult { get; }
- public string LastSyncMessage
- {
- get
- {
- return ExceptionHelper.GetErrorMessage(_lastSyncResult, false);
- }
- }
+ public string LastSyncMessage => ExceptionHelper.GetErrorMessage(LastSyncResult, false);
- public int ConsecutiveFailureCount
- {
- get
- {
- return _consecutiveSyncFailures;
- }
- }
+ public int ConsecutiveFailureCount { get; }
}
}
diff --git a/src/System.DirectoryServices/src/System/DirectoryServices/ActiveDirectory/ReplicationNeighborCollection.cs b/src/System.DirectoryServices/src/System/DirectoryServices/ActiveDirectory/ReplicationNeighborCollection.cs
index 0d89a09445..fd3c38e218 100644
--- a/src/System.DirectoryServices/src/System/DirectoryServices/ActiveDirectory/ReplicationNeighborCollection.cs
+++ b/src/System.DirectoryServices/src/System/DirectoryServices/ActiveDirectory/ReplicationNeighborCollection.cs
@@ -2,16 +2,15 @@
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
+using System.Collections;
+using System.Runtime.InteropServices;
+
namespace System.DirectoryServices.ActiveDirectory
{
- using System;
- using System.Collections;
- using System.Runtime.InteropServices;
-
public class ReplicationNeighborCollection : ReadOnlyCollectionBase
{
- private DirectoryServer _server = null;
- private Hashtable _nameTable = null;
+ private readonly DirectoryServer _server = null;
+ private readonly Hashtable _nameTable = null;
internal ReplicationNeighborCollection(DirectoryServer server)
{
@@ -20,13 +19,7 @@ namespace System.DirectoryServices.ActiveDirectory
_nameTable = Hashtable.Synchronized(tempNameTable);
}
- public ReplicationNeighbor this[int index]
- {
- get
- {
- return (ReplicationNeighbor)InnerList[index];
- }
- }
+ public ReplicationNeighbor this[int index] => (ReplicationNeighbor)InnerList[index];
public bool Contains(ReplicationNeighbor neighbor)
{
@@ -49,10 +42,7 @@ namespace System.DirectoryServices.ActiveDirectory
InnerList.CopyTo(neighbors, index);
}
- private int Add(ReplicationNeighbor neighbor)
- {
- return InnerList.Add(neighbor);
- }
+ private int Add(ReplicationNeighbor neighbor) => InnerList.Add(neighbor);
internal void AddHelper(DS_REPL_NEIGHBORS neighbors, IntPtr info)
{
diff --git a/src/System.DirectoryServices/src/System/DirectoryServices/ActiveDirectory/ReplicationOperation.cs b/src/System.DirectoryServices/src/System/DirectoryServices/ActiveDirectory/ReplicationOperation.cs
index d1db7b707c..305ca147ae 100644
--- a/src/System.DirectoryServices/src/System/DirectoryServices/ActiveDirectory/ReplicationOperation.cs
+++ b/src/System.DirectoryServices/src/System/DirectoryServices/ActiveDirectory/ReplicationOperation.cs
@@ -2,26 +2,18 @@
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
+using System.Runtime.InteropServices;
+using System.Collections;
+
namespace System.DirectoryServices.ActiveDirectory
{
- using System;
- using System.Runtime.InteropServices;
- using System.Collections;
- using System.Diagnostics;
-
public class ReplicationOperation
{
- private DateTime _timeEnqueued;
- private int _serialNumber;
- private int _priority;
- private ReplicationOperationType _operationType;
- private string _namingContext;
- private string _dsaDN;
- private Guid _uuidDsaObjGuid;
-
- private DirectoryServer _server = null;
+ private readonly string _dsaDN;
+
+ private readonly DirectoryServer _server = null;
private string _sourceServer = null;
- private Hashtable _nameTable = null;
+ private readonly Hashtable _nameTable = null;
internal ReplicationOperation(IntPtr addr, DirectoryServer server, Hashtable table)
{
@@ -29,69 +21,39 @@ namespace System.DirectoryServices.ActiveDirectory
Marshal.PtrToStructure(addr, operation);
// get the enqueued time
- _timeEnqueued = DateTime.FromFileTime(operation.ftimeEnqueued);
+ TimeEnqueued = DateTime.FromFileTime(operation.ftimeEnqueued);
// get the operation identifier
- _serialNumber = operation.ulSerialNumber;
+ OperationNumber = operation.ulSerialNumber;
// get the priority
- _priority = operation.ulPriority;
+ Priority = operation.ulPriority;
// get the operation type
- _operationType = operation.OpType;
+ OperationType = operation.OpType;
// get the partition name
- _namingContext = Marshal.PtrToStringUni(operation.pszNamingContext);
+ PartitionName = Marshal.PtrToStringUni(operation.pszNamingContext);
// get the dsaDN
_dsaDN = Marshal.PtrToStringUni(operation.pszDsaDN);
// get the dsaobject guid
- _uuidDsaObjGuid = operation.uuidDsaObjGuid;
+ SourceServerGuid = operation.uuidDsaObjGuid;
_server = server;
_nameTable = table;
}
- public DateTime TimeEnqueued
- {
- get
- {
- return _timeEnqueued;
- }
- }
+ public DateTime TimeEnqueued { get; }
- public int OperationNumber
- {
- get
- {
- return _serialNumber;
- }
- }
+ public int OperationNumber { get; }
- public int Priority
- {
- get
- {
- return _priority;
- }
- }
+ public int Priority { get; }
- public ReplicationOperationType OperationType
- {
- get
- {
- return _operationType;
- }
- }
+ public ReplicationOperationType OperationType { get; }
- public string PartitionName
- {
- get
- {
- return _namingContext;
- }
- }
+ public string PartitionName { get; }
public string SourceServer
{
@@ -116,12 +78,6 @@ namespace System.DirectoryServices.ActiveDirectory
}
}
- private Guid SourceServerGuid
- {
- get
- {
- return _uuidDsaObjGuid;
- }
- }
+ private Guid SourceServerGuid { get; }
}
}
diff --git a/src/System.DirectoryServices/src/System/DirectoryServices/ActiveDirectory/ReplicationOperationCollection.cs b/src/System.DirectoryServices/src/System/DirectoryServices/ActiveDirectory/ReplicationOperationCollection.cs
index ab4bf1f30a..e271dbfb1a 100644
--- a/src/System.DirectoryServices/src/System/DirectoryServices/ActiveDirectory/ReplicationOperationCollection.cs
+++ b/src/System.DirectoryServices/src/System/DirectoryServices/ActiveDirectory/ReplicationOperationCollection.cs
@@ -2,16 +2,15 @@
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
+using System.Collections;
+using System.Runtime.InteropServices;
+
namespace System.DirectoryServices.ActiveDirectory
{
- using System;
- using System.Collections;
- using System.Runtime.InteropServices;
-
public class ReplicationOperationCollection : ReadOnlyCollectionBase
{
- private DirectoryServer _server = null;
- private Hashtable _nameTable = null;
+ private readonly DirectoryServer _server = null;
+ private readonly Hashtable _nameTable = null;
internal ReplicationOperationCollection(DirectoryServer server)
{
@@ -20,13 +19,7 @@ namespace System.DirectoryServices.ActiveDirectory
_nameTable = Hashtable.Synchronized(tempNameTable);
}
- public ReplicationOperation this[int index]
- {
- get
- {
- return (ReplicationOperation)InnerList[index];
- }
- }
+ public ReplicationOperation this[int index] => (ReplicationOperation)InnerList[index];
public bool Contains(ReplicationOperation operation)
{
@@ -49,10 +42,7 @@ namespace System.DirectoryServices.ActiveDirectory
InnerList.CopyTo(operations, index);
}
- private int Add(ReplicationOperation operation)
- {
- return InnerList.Add(operation);
- }
+ private int Add(ReplicationOperation operation) => InnerList.Add(operation);
internal void AddHelper(DS_REPL_PENDING_OPS operations, IntPtr info)
{
@@ -79,4 +69,3 @@ namespace System.DirectoryServices.ActiveDirectory
}
}
}
-
diff --git a/src/System.DirectoryServices/src/System/DirectoryServices/ActiveDirectory/ReplicationOperationInformation.cs b/src/System.DirectoryServices/src/System/DirectoryServices/ActiveDirectory/ReplicationOperationInformation.cs
index d439165f5a..579af1108f 100644
--- a/src/System.DirectoryServices/src/System/DirectoryServices/ActiveDirectory/ReplicationOperationInformation.cs
+++ b/src/System.DirectoryServices/src/System/DirectoryServices/ActiveDirectory/ReplicationOperationInformation.cs
@@ -4,11 +4,6 @@
namespace System.DirectoryServices.ActiveDirectory
{
- using System;
- using System.Runtime.InteropServices;
- using System.Collections;
- using System.Diagnostics;
-
public class ReplicationOperationInformation
{
internal DateTime startTime;
@@ -19,28 +14,10 @@ namespace System.DirectoryServices.ActiveDirectory
{
}
- public DateTime OperationStartTime
- {
- get
- {
- return startTime;
- }
- }
+ public DateTime OperationStartTime => startTime;
- public ReplicationOperation CurrentOperation
- {
- get
- {
- return currentOp;
- }
- }
+ public ReplicationOperation CurrentOperation => currentOp;
- public ReplicationOperationCollection PendingOperations
- {
- get
- {
- return collection;
- }
- }
+ public ReplicationOperationCollection PendingOperations => collection;
}
}
diff --git a/src/System.DirectoryServices/src/System/DirectoryServices/ActiveDirectory/RoleOwner.cs b/src/System.DirectoryServices/src/System/DirectoryServices/ActiveDirectory/RoleOwner.cs
index ef9427cf43..f7ba00af1b 100644
--- a/src/System.DirectoryServices/src/System/DirectoryServices/ActiveDirectory/RoleOwner.cs
+++ b/src/System.DirectoryServices/src/System/DirectoryServices/ActiveDirectory/RoleOwner.cs
@@ -4,8 +4,6 @@
namespace System.DirectoryServices.ActiveDirectory
{
- using System;
-
public enum ActiveDirectoryRole : int
{
SchemaRole = 0,
diff --git a/src/System.DirectoryServices/src/System/DirectoryServices/ActiveDirectory/RoleOwnerCollection.cs b/src/System.DirectoryServices/src/System/DirectoryServices/ActiveDirectory/RoleOwnerCollection.cs
index 4adaf964d8..aa8e8eb9f2 100644
--- a/src/System.DirectoryServices/src/System/DirectoryServices/ActiveDirectory/RoleOwnerCollection.cs
+++ b/src/System.DirectoryServices/src/System/DirectoryServices/ActiveDirectory/RoleOwnerCollection.cs
@@ -2,14 +2,11 @@
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
+using System.Collections;
+using System.ComponentModel;
+
namespace System.DirectoryServices.ActiveDirectory
{
- using System;
- using System.Collections;
- using System.Globalization;
- using System.ComponentModel;
- using System.Runtime.InteropServices;
-
public class ActiveDirectoryRoleCollection : ReadOnlyCollectionBase
{
internal ActiveDirectoryRoleCollection() { }
@@ -22,13 +19,7 @@ namespace System.DirectoryServices.ActiveDirectory
}
}
- public ActiveDirectoryRole this[int index]
- {
- get
- {
- return (ActiveDirectoryRole)InnerList[index];
- }
- }
+ public ActiveDirectoryRole this[int index] => (ActiveDirectoryRole)InnerList[index];
public bool Contains(ActiveDirectoryRole role)
{
@@ -86,13 +77,7 @@ namespace System.DirectoryServices.ActiveDirectory
}
}
- public AdamRole this[int index]
- {
- get
- {
- return (AdamRole)InnerList[index];
- }
- }
+ public AdamRole this[int index] => (AdamRole)InnerList[index];
public bool Contains(AdamRole role)
{
diff --git a/src/System.DirectoryServices/src/System/DirectoryServices/ActiveDirectory/SafeHandle.cs b/src/System.DirectoryServices/src/System/DirectoryServices/ActiveDirectory/SafeHandle.cs
index c342df108c..7358376170 100644
--- a/src/System.DirectoryServices/src/System/DirectoryServices/ActiveDirectory/SafeHandle.cs
+++ b/src/System.DirectoryServices/src/System/DirectoryServices/ActiveDirectory/SafeHandle.cs
@@ -2,15 +2,11 @@
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
+using System.Security;
+using Microsoft.Win32.SafeHandles;
+
namespace System.DirectoryServices.ActiveDirectory
{
- using System;
- using Microsoft.Win32.SafeHandles;
- using System.Runtime.InteropServices;
- using System.Runtime.CompilerServices;
- using System.Runtime.ConstrainedExecution;
- using System.Security;
-
[SuppressUnmanagedCodeSecurityAttribute()]
internal sealed class PolicySafeHandle : SafeHandleZeroOrMinusOneIsInvalid
{
@@ -19,11 +15,7 @@ namespace System.DirectoryServices.ActiveDirectory
SetHandle(value);
}
- override protected bool ReleaseHandle()
- {
- // STATUS_SUCCESS is 0
- return UnsafeNativeMethods.LsaClose(handle) == 0;
- }
+ override protected bool ReleaseHandle() => UnsafeNativeMethods.LsaClose(handle) == 0;
}
[SuppressUnmanagedCodeSecurityAttribute()]
@@ -36,11 +28,7 @@ namespace System.DirectoryServices.ActiveDirectory
SetHandle(value);
}
- override protected bool ReleaseHandle()
- {
- // STATUS_SUCCESS is 0
- return NativeMethods.LsaDeregisterLogonProcess(handle) == 0;
- }
+ override protected bool ReleaseHandle() => NativeMethods.LsaDeregisterLogonProcess(handle) == 0;
}
[SuppressUnmanagedCodeSecurityAttribute()]
@@ -53,9 +41,6 @@ namespace System.DirectoryServices.ActiveDirectory
SetHandle(value);
}
- override protected bool ReleaseHandle()
- {
- return UnsafeNativeMethods.FreeLibrary(handle) != 0;
- }
+ override protected bool ReleaseHandle() => UnsafeNativeMethods.FreeLibrary(handle) != 0;
}
}
diff --git a/src/System.DirectoryServices/src/System/DirectoryServices/ActiveDirectory/SecurityLevel.cs b/src/System.DirectoryServices/src/System/DirectoryServices/ActiveDirectory/SecurityLevel.cs
index 8f272e2670..dca544c820 100644
--- a/src/System.DirectoryServices/src/System/DirectoryServices/ActiveDirectory/SecurityLevel.cs
+++ b/src/System.DirectoryServices/src/System/DirectoryServices/ActiveDirectory/SecurityLevel.cs
@@ -4,8 +4,6 @@
namespace System.DirectoryServices.ActiveDirectory
{
- using System;
-
public enum ReplicationSecurityLevel : int
{
MutualAuthentication = 2,
diff --git a/src/System.DirectoryServices/src/System/DirectoryServices/ActiveDirectory/SystemFlag.cs b/src/System.DirectoryServices/src/System/DirectoryServices/ActiveDirectory/SystemFlag.cs
index dbe8286e5a..d9145d8401 100644
--- a/src/System.DirectoryServices/src/System/DirectoryServices/ActiveDirectory/SystemFlag.cs
+++ b/src/System.DirectoryServices/src/System/DirectoryServices/ActiveDirectory/SystemFlag.cs
@@ -4,8 +4,6 @@
namespace System.DirectoryServices.ActiveDirectory
{
- using System;
-
internal enum SystemFlag : int
{
SystemFlagNtdsNC = 1,
diff --git a/src/System.DirectoryServices/src/System/DirectoryServices/ActiveDirectory/TopLevelName.cs b/src/System.DirectoryServices/src/System/DirectoryServices/ActiveDirectory/TopLevelName.cs
index 9fc52bb89c..fd04cb8865 100644
--- a/src/System.DirectoryServices/src/System/DirectoryServices/ActiveDirectory/TopLevelName.cs
+++ b/src/System.DirectoryServices/src/System/DirectoryServices/ActiveDirectory/TopLevelName.cs
@@ -2,14 +2,11 @@
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
+using System.Runtime.InteropServices;
+using System.ComponentModel;
+
namespace System.DirectoryServices.ActiveDirectory
{
- using System;
- using System.Runtime.InteropServices;
- using System.Collections;
- using System.Globalization;
- using System.ComponentModel;
-
public enum TopLevelNameStatus
{
Enabled = 0,
@@ -20,31 +17,21 @@ namespace System.DirectoryServices.ActiveDirectory
public class TopLevelName
{
- private string _name = null;
private TopLevelNameStatus _status;
- internal LARGE_INTEGER time;
+ internal readonly LARGE_INTEGER time;
internal TopLevelName(int flag, LSA_UNICODE_STRING val, LARGE_INTEGER time)
{
_status = (TopLevelNameStatus)flag;
- _name = Marshal.PtrToStringUni(val.Buffer, val.Length / 2);
+ Name = Marshal.PtrToStringUni(val.Buffer, val.Length / 2);
this.time = time;
}
- public string Name
- {
- get
- {
- return _name;
- }
- }
+ public string Name { get; }
public TopLevelNameStatus Status
{
- get
- {
- return _status;
- }
+ get => _status;
set
{
if (value != TopLevelNameStatus.Enabled &&
diff --git a/src/System.DirectoryServices/src/System/DirectoryServices/ActiveDirectory/TopLevelNameCollection.cs b/src/System.DirectoryServices/src/System/DirectoryServices/ActiveDirectory/TopLevelNameCollection.cs
index 789b603741..d646f72e19 100644
--- a/src/System.DirectoryServices/src/System/DirectoryServices/ActiveDirectory/TopLevelNameCollection.cs
+++ b/src/System.DirectoryServices/src/System/DirectoryServices/ActiveDirectory/TopLevelNameCollection.cs
@@ -2,24 +2,15 @@
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
+using System.Collections;
+
namespace System.DirectoryServices.ActiveDirectory
{
- using System;
- using System.Runtime.InteropServices;
- using System.Collections;
- using System.Globalization;
-
public class TopLevelNameCollection : ReadOnlyCollectionBase
{
internal TopLevelNameCollection() { }
- public TopLevelName this[int index]
- {
- get
- {
- return (TopLevelName)InnerList[index];
- }
- }
+ public TopLevelName this[int index] => (TopLevelName)InnerList[index];
public bool Contains(TopLevelName name)
{
diff --git a/src/System.DirectoryServices/src/System/DirectoryServices/ActiveDirectory/TrustHelper.cs b/src/System.DirectoryServices/src/System/DirectoryServices/ActiveDirectory/TrustHelper.cs
index 3079851996..e645ffc55c 100644
--- a/src/System.DirectoryServices/src/System/DirectoryServices/ActiveDirectory/TrustHelper.cs
+++ b/src/System.DirectoryServices/src/System/DirectoryServices/ActiveDirectory/TrustHelper.cs
@@ -2,17 +2,12 @@
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
+using System.Runtime.InteropServices;
+using System.Diagnostics;
+using System.Security.Cryptography;
+
namespace System.DirectoryServices.ActiveDirectory
{
- using System;
- using System.Runtime.InteropServices;
- using System.Collections;
- using System.Globalization;
- using System.ComponentModel;
- using System.Diagnostics;
- using System.Text;
- using System.Security.Cryptography;
-
internal enum TRUSTED_INFORMATION_CLASS
{
TrustedDomainNameInformation = 1,
@@ -100,9 +95,9 @@ namespace System.DirectoryServices.ActiveDirectory
if (win32Error == s_STATUS_OBJECT_NAME_NOT_FOUND)
{
if (isForest)
- throw new ActiveDirectoryObjectNotFoundException(String.Format(CultureInfo.CurrentCulture, SR.ForestTrustDoesNotExist , sourceName, targetName), typeof(ForestTrustRelationshipInformation), null);
+ throw new ActiveDirectoryObjectNotFoundException(SR.Format(SR.ForestTrustDoesNotExist , sourceName, targetName), typeof(ForestTrustRelationshipInformation), null);
else
- throw new ActiveDirectoryObjectNotFoundException(String.Format(CultureInfo.CurrentCulture, SR.DomainTrustDoesNotExist , sourceName, targetName), typeof(TrustRelationshipInformation), null);
+ throw new ActiveDirectoryObjectNotFoundException(SR.Format(SR.DomainTrustDoesNotExist , sourceName, targetName), typeof(TrustRelationshipInformation), null);
}
else
throw ExceptionHelper.GetExceptionFromErrorCode(win32Error, serverName);
@@ -198,9 +193,9 @@ namespace System.DirectoryServices.ActiveDirectory
if (win32Error == s_STATUS_OBJECT_NAME_NOT_FOUND)
{
if (isForest)
- throw new ActiveDirectoryObjectNotFoundException(String.Format(CultureInfo.CurrentCulture, SR.ForestTrustDoesNotExist , sourceName, targetName), typeof(ForestTrustRelationshipInformation), null);
+ throw new ActiveDirectoryObjectNotFoundException(SR.Format(SR.ForestTrustDoesNotExist , sourceName, targetName), typeof(ForestTrustRelationshipInformation), null);
else
- throw new ActiveDirectoryObjectNotFoundException(String.Format(CultureInfo.CurrentCulture, SR.DomainTrustDoesNotExist , sourceName, targetName), typeof(TrustRelationshipInformation), null);
+ throw new ActiveDirectoryObjectNotFoundException(SR.Format(SR.DomainTrustDoesNotExist , sourceName, targetName), typeof(TrustRelationshipInformation), null);
}
else
throw ExceptionHelper.GetExceptionFromErrorCode(win32Error, serverName);
@@ -328,9 +323,9 @@ namespace System.DirectoryServices.ActiveDirectory
if (win32Error == s_STATUS_OBJECT_NAME_NOT_FOUND)
{
if (isForest)
- throw new ActiveDirectoryObjectNotFoundException(String.Format(CultureInfo.CurrentCulture, SR.ForestTrustDoesNotExist , sourceName, targetName), typeof(ForestTrustRelationshipInformation), null);
+ throw new ActiveDirectoryObjectNotFoundException(SR.Format(SR.ForestTrustDoesNotExist , sourceName, targetName), typeof(ForestTrustRelationshipInformation), null);
else
- throw new ActiveDirectoryObjectNotFoundException(String.Format(CultureInfo.CurrentCulture, SR.DomainTrustDoesNotExist , sourceName, targetName), typeof(TrustRelationshipInformation), null);
+ throw new ActiveDirectoryObjectNotFoundException(SR.Format(SR.DomainTrustDoesNotExist , sourceName, targetName), typeof(TrustRelationshipInformation), null);
}
else
throw ExceptionHelper.GetExceptionFromErrorCode(win32Error, serverName);
@@ -574,9 +569,9 @@ namespace System.DirectoryServices.ActiveDirectory
if (result == s_ERROR_ALREADY_EXISTS)
{
if (isForest)
- throw new ActiveDirectoryObjectExistsException(String.Format(CultureInfo.CurrentCulture, SR.AlreadyExistingForestTrust , sourceName, targetName));
+ throw new ActiveDirectoryObjectExistsException(SR.Format(SR.AlreadyExistingForestTrust , sourceName, targetName));
else
- throw new ActiveDirectoryObjectExistsException(String.Format(CultureInfo.CurrentCulture, SR.AlreadyExistingDomainTrust , sourceName, targetName));
+ throw new ActiveDirectoryObjectExistsException(SR.Format(SR.AlreadyExistingDomainTrust , sourceName, targetName));
}
else
throw ExceptionHelper.GetExceptionFromErrorCode(result, serverName);
@@ -647,9 +642,9 @@ namespace System.DirectoryServices.ActiveDirectory
if (win32Error == s_STATUS_OBJECT_NAME_NOT_FOUND)
{
if (isForest)
- throw new ActiveDirectoryObjectNotFoundException(String.Format(CultureInfo.CurrentCulture, SR.ForestTrustDoesNotExist , sourceName, targetName), typeof(ForestTrustRelationshipInformation), null);
+ throw new ActiveDirectoryObjectNotFoundException(SR.Format(SR.ForestTrustDoesNotExist , sourceName, targetName), typeof(ForestTrustRelationshipInformation), null);
else
- throw new ActiveDirectoryObjectNotFoundException(String.Format(CultureInfo.CurrentCulture, SR.DomainTrustDoesNotExist , sourceName, targetName), typeof(TrustRelationshipInformation), null);
+ throw new ActiveDirectoryObjectNotFoundException(SR.Format(SR.DomainTrustDoesNotExist , sourceName, targetName), typeof(TrustRelationshipInformation), null);
}
else
throw ExceptionHelper.GetExceptionFromErrorCode(win32Error, serverName);
@@ -780,9 +775,9 @@ namespace System.DirectoryServices.ActiveDirectory
if (win32Error == s_STATUS_OBJECT_NAME_NOT_FOUND)
{
if (isForest)
- throw new ActiveDirectoryObjectNotFoundException(String.Format(CultureInfo.CurrentCulture, SR.ForestTrustDoesNotExist , sourceName, targetName), typeof(ForestTrustRelationshipInformation), null);
+ throw new ActiveDirectoryObjectNotFoundException(SR.Format(SR.ForestTrustDoesNotExist , sourceName, targetName), typeof(ForestTrustRelationshipInformation), null);
else
- throw new ActiveDirectoryObjectNotFoundException(String.Format(CultureInfo.CurrentCulture, SR.DomainTrustDoesNotExist , sourceName, targetName), typeof(TrustRelationshipInformation), null);
+ throw new ActiveDirectoryObjectNotFoundException(SR.Format(SR.DomainTrustDoesNotExist , sourceName, targetName), typeof(TrustRelationshipInformation), null);
}
else
throw ExceptionHelper.GetExceptionFromErrorCode(win32Error, serverName);
@@ -898,9 +893,9 @@ namespace System.DirectoryServices.ActiveDirectory
if (win32Error == s_STATUS_OBJECT_NAME_NOT_FOUND)
{
if (isForest)
- throw new ActiveDirectoryObjectNotFoundException(String.Format(CultureInfo.CurrentCulture, SR.ForestTrustDoesNotExist , sourceName, targetName), typeof(ForestTrustRelationshipInformation), null);
+ throw new ActiveDirectoryObjectNotFoundException(SR.Format(SR.ForestTrustDoesNotExist , sourceName, targetName), typeof(ForestTrustRelationshipInformation), null);
else
- throw new ActiveDirectoryObjectNotFoundException(String.Format(CultureInfo.CurrentCulture, SR.DomainTrustDoesNotExist , sourceName, targetName), typeof(TrustRelationshipInformation), null);
+ throw new ActiveDirectoryObjectNotFoundException(SR.Format(SR.DomainTrustDoesNotExist , sourceName, targetName), typeof(TrustRelationshipInformation), null);
}
else
throw ExceptionHelper.GetExceptionFromErrorCode(win32Error, serverName);
@@ -922,9 +917,9 @@ namespace System.DirectoryServices.ActiveDirectory
if ((direction & domainInfo.TrustDirection) == 0)
{
if (isForest)
- throw new ActiveDirectoryObjectNotFoundException(String.Format(CultureInfo.CurrentCulture, SR.WrongTrustDirection , sourceName, targetName, (TrustDirection)direction), typeof(ForestTrustRelationshipInformation), null);
+ throw new ActiveDirectoryObjectNotFoundException(SR.Format(SR.WrongTrustDirection , sourceName, targetName, (TrustDirection)direction), typeof(ForestTrustRelationshipInformation), null);
else
- throw new ActiveDirectoryObjectNotFoundException(String.Format(CultureInfo.CurrentCulture, SR.WrongTrustDirection , sourceName, targetName, (TrustDirection)direction), typeof(TrustRelationshipInformation), null);
+ throw new ActiveDirectoryObjectNotFoundException(SR.Format(SR.WrongTrustDirection , sourceName, targetName, (TrustDirection)direction), typeof(TrustRelationshipInformation), null);
}
}
}
@@ -942,7 +937,7 @@ namespace System.DirectoryServices.ActiveDirectory
// it should be a forest trust, make sure that TRUST_ATTRIBUTE_FOREST_TRANSITIVE bit is set
if ((domainInfo.TrustAttributes & TRUST_ATTRIBUTE.TRUST_ATTRIBUTE_FOREST_TRANSITIVE) == 0)
{
- throw new ActiveDirectoryObjectNotFoundException(String.Format(CultureInfo.CurrentCulture, SR.ForestTrustDoesNotExist , sourceName, targetName), typeof(ForestTrustRelationshipInformation), null);
+ throw new ActiveDirectoryObjectNotFoundException(SR.Format(SR.ForestTrustDoesNotExist , sourceName, targetName), typeof(ForestTrustRelationshipInformation), null);
}
}
else
@@ -950,7 +945,7 @@ namespace System.DirectoryServices.ActiveDirectory
// it should not be a forest trust, make sure that TRUST_ATTRIBUTE_FOREST_TRANSITIVE bit is not set
if ((domainInfo.TrustAttributes & TRUST_ATTRIBUTE.TRUST_ATTRIBUTE_FOREST_TRANSITIVE) != 0)
{
- throw new ActiveDirectoryObjectNotFoundException(String.Format(CultureInfo.CurrentCulture, SR.WrongForestTrust , sourceName, targetName), typeof(TrustRelationshipInformation), null);
+ throw new ActiveDirectoryObjectNotFoundException(SR.Format(SR.WrongForestTrust , sourceName, targetName), typeof(TrustRelationshipInformation), null);
}
// we don't deal with NT4 trust also
diff --git a/src/System.DirectoryServices/src/System/DirectoryServices/ActiveDirectory/TrustRelationshipInformation.cs b/src/System.DirectoryServices/src/System/DirectoryServices/ActiveDirectory/TrustRelationshipInformation.cs
index 5ed2de9138..0b8201a7b1 100644
--- a/src/System.DirectoryServices/src/System/DirectoryServices/ActiveDirectory/TrustRelationshipInformation.cs
+++ b/src/System.DirectoryServices/src/System/DirectoryServices/ActiveDirectory/TrustRelationshipInformation.cs
@@ -4,12 +4,6 @@
namespace System.DirectoryServices.ActiveDirectory
{
- using System;
- using System.Runtime.InteropServices;
- using System.Collections;
- using System.Globalization;
- using System.Net;
-
public enum TrustType
{
TreeRoot = 0,
@@ -58,36 +52,12 @@ namespace System.DirectoryServices.ActiveDirectory
this.type = obj.TrustType;
}
- public string SourceName
- {
- get
- {
- return this.source;
- }
- }
+ public string SourceName => source;
- public string TargetName
- {
- get
- {
- return target;
- }
- }
+ public string TargetName => target;
- public TrustType TrustType
- {
- get
- {
- return type;
- }
- }
+ public TrustType TrustType => type;
- public TrustDirection TrustDirection
- {
- get
- {
- return direction;
- }
- }
+ public TrustDirection TrustDirection => direction;
}
}
diff --git a/src/System.DirectoryServices/src/System/DirectoryServices/ActiveDirectory/TrustRelationshipInformationCollection.cs b/src/System.DirectoryServices/src/System/DirectoryServices/ActiveDirectory/TrustRelationshipInformationCollection.cs
index 83f03a2e12..8c6f523080 100644
--- a/src/System.DirectoryServices/src/System/DirectoryServices/ActiveDirectory/TrustRelationshipInformationCollection.cs
+++ b/src/System.DirectoryServices/src/System/DirectoryServices/ActiveDirectory/TrustRelationshipInformationCollection.cs
@@ -2,13 +2,10 @@
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
+using System.Collections;
+
namespace System.DirectoryServices.ActiveDirectory
{
- using System;
- using System.Runtime.InteropServices;
- using System.Collections;
- using System.Globalization;
-
public class TrustRelationshipInformationCollection : ReadOnlyCollectionBase
{
internal TrustRelationshipInformationCollection() { }
@@ -31,10 +28,7 @@ namespace System.DirectoryServices.ActiveDirectory
public TrustRelationshipInformation this[int index]
{
- get
- {
- return (TrustRelationshipInformation)InnerList[index];
- }
+ get => (TrustRelationshipInformation)InnerList[index];
}
public bool Contains(TrustRelationshipInformation information)
@@ -58,9 +52,6 @@ namespace System.DirectoryServices.ActiveDirectory
InnerList.CopyTo(array, index);
}
- internal int Add(TrustRelationshipInformation info)
- {
- return InnerList.Add(info);
- }
+ internal int Add(TrustRelationshipInformation info) => InnerList.Add(info);
}
}
diff --git a/src/System.DirectoryServices/src/System/DirectoryServices/ActiveDirectory/UnsafeNativeMethods.cs b/src/System.DirectoryServices/src/System/DirectoryServices/ActiveDirectory/UnsafeNativeMethods.cs
index 7451a0c9bc..cffff43fa9 100644
--- a/src/System.DirectoryServices/src/System/DirectoryServices/ActiveDirectory/UnsafeNativeMethods.cs
+++ b/src/System.DirectoryServices/src/System/DirectoryServices/ActiveDirectory/UnsafeNativeMethods.cs
@@ -25,13 +25,13 @@
// public int dwEnumerationContext;
//}
+using System.Runtime.InteropServices;
+using System.Security;
+using System.Text;
+
namespace System.DirectoryServices.ActiveDirectory
{
#pragma warning disable BCL0015 // CoreFxPort
- using System;
- using System.Runtime.InteropServices;
- using System.Security;
- using System.Text;
internal enum DS_REPL_INFO_TYPE
{
diff --git a/src/System.DirectoryServices/src/System/DirectoryServices/ActiveDirectory/Utils.cs b/src/System.DirectoryServices/src/System/DirectoryServices/ActiveDirectory/Utils.cs
index 3a87ebc904..5512312aa6 100644
--- a/src/System.DirectoryServices/src/System/DirectoryServices/ActiveDirectory/Utils.cs
+++ b/src/System.DirectoryServices/src/System/DirectoryServices/ActiveDirectory/Utils.cs
@@ -2,19 +2,17 @@
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
-using System;
using System.Text;
using System.Net;
using System.Collections;
using System.Security.Principal;
using System.Security.Permissions;
-using System.DirectoryServices;
using System.Runtime.InteropServices;
using System.Diagnostics;
using System.Globalization;
#pragma warning disable 618
-[assembly:SecurityPermission(SecurityAction.RequestMinimum, UnmanagedCode = true),
+[assembly: SecurityPermission(SecurityAction.RequestMinimum, UnmanagedCode = true),
SecurityPermission(SecurityAction.RequestMinimum, SkipVerification = true),
EnvironmentPermission(SecurityAction.RequestMinimum, Unrestricted = true),
]
@@ -321,7 +319,7 @@ namespace System.DirectoryServices.ActiveDirectory
{
if (resCol.Count != 2)
{
- throw new ActiveDirectoryOperationException(String.Format(CultureInfo.CurrentCulture, SR.NoHostNameOrPortNumber , dn));
+ throw new ActiveDirectoryOperationException(SR.Format(SR.NoHostNameOrPortNumber , dn));
}
foreach (SearchResult res in resCol)
@@ -347,7 +345,7 @@ namespace System.DirectoryServices.ActiveDirectory
if ((ldapPort == -1) || (dnsHostName == null))
{
- throw new ActiveDirectoryOperationException(String.Format(CultureInfo.CurrentCulture, SR.NoHostNameOrPortNumber , dn));
+ throw new ActiveDirectoryOperationException(SR.Format(SR.NoHostNameOrPortNumber , dn));
}
return dnsHostName + ":" + ldapPort;
@@ -380,7 +378,7 @@ namespace System.DirectoryServices.ActiveDirectory
{
if (resCol.Count != 2)
{
- throw new ActiveDirectoryOperationException(String.Format(CultureInfo.CurrentCulture, SR.NoHostNameOrPortNumber , dn));
+ throw new ActiveDirectoryOperationException(SR.Format(SR.NoHostNameOrPortNumber , dn));
}
foreach (SearchResult res in resCol)
@@ -407,7 +405,7 @@ namespace System.DirectoryServices.ActiveDirectory
if ((ldapPort == -1) || (sslPort == -1) || (dnsHostName == null))
{
- throw new ActiveDirectoryOperationException(String.Format(CultureInfo.CurrentCulture, SR.NoHostNameOrPortNumber , dn));
+ throw new ActiveDirectoryOperationException(SR.Format(SR.NoHostNameOrPortNumber , dn));
}
return dnsHostName + ":" + ldapPort + ":" + sslPort;
@@ -814,7 +812,7 @@ namespace System.DirectoryServices.ActiveDirectory
return ActiveDirectoryTransportType.Smtp;
else
{
- string message = String.Format(CultureInfo.CurrentCulture, SR.UnknownTransport , transportName);
+ string message = SR.Format(SR.UnknownTransport , transportName);
throw new ActiveDirectoryOperationException(message);
}
}
@@ -1746,11 +1744,11 @@ namespace System.DirectoryServices.ActiveDirectory
Debug.Fail(string.Format(CultureInfo.InvariantCulture, "ConfigurationSet::GetReplicaList - no dnsHostName information for replica {0}", ntdsaName));
if (isADAM)
{
- throw new ActiveDirectoryOperationException(String.Format(CultureInfo.CurrentCulture, SR.NoHostNameOrPortNumber , ntdsaName));
+ throw new ActiveDirectoryOperationException(SR.Format(SR.NoHostNameOrPortNumber , ntdsaName));
}
else
{
- throw new ActiveDirectoryOperationException(String.Format(CultureInfo.CurrentCulture, SR.NoHostName , ntdsaName));
+ throw new ActiveDirectoryOperationException(SR.Format(SR.NoHostName , ntdsaName));
}
}
@@ -1759,7 +1757,7 @@ namespace System.DirectoryServices.ActiveDirectory
if (serverPorts[ntdsaName] == null)
{
Debug.Fail(string.Format(CultureInfo.InvariantCulture, "ConfigurationSet::GetReplicaList - no port number information for replica {0}", ntdsaName));
- throw new ActiveDirectoryOperationException(String.Format(CultureInfo.CurrentCulture, SR.NoHostNameOrPortNumber , ntdsaName));
+ throw new ActiveDirectoryOperationException(SR.Format(SR.NoHostNameOrPortNumber , ntdsaName));
}
}
@@ -2101,18 +2099,12 @@ namespace System.DirectoryServices.ActiveDirectory
))
{
int lastError = Marshal.GetLastWin32Error();
- throw new InvalidOperationException(
- String.Format(CultureInfo.CurrentCulture,
- SR.UnableToOpenToken,
- lastError));
+ throw new InvalidOperationException(SR.Format(SR.UnableToOpenToken, lastError));
}
}
else
{
- throw new InvalidOperationException(
- String.Format(CultureInfo.CurrentCulture,
- SR.UnableToOpenToken,
- error));
+ throw new InvalidOperationException(SR.Format(SR.UnableToOpenToken, error));
}
}
@@ -2133,7 +2125,7 @@ namespace System.DirectoryServices.ActiveDirectory
if ((getTokenInfoError = Marshal.GetLastWin32Error()) != 122) // ERROR_INSUFFICIENT_BUFFER
{
throw new InvalidOperationException(
- String.Format(CultureInfo.CurrentCulture, SR.UnableToRetrieveTokenInfo, getTokenInfoError));
+ SR.Format(SR.UnableToRetrieveTokenInfo, getTokenInfoError));
}
// Allocate the necessary buffer.
@@ -2152,7 +2144,7 @@ namespace System.DirectoryServices.ActiveDirectory
{
int lastError = Marshal.GetLastWin32Error();
throw new InvalidOperationException(
- String.Format(CultureInfo.CurrentCulture, SR.UnableToRetrieveTokenInfo, lastError));
+ SR.Format(SR.UnableToRetrieveTokenInfo, lastError));
}
// Retrieve the user's SID from the user info
@@ -2169,7 +2161,7 @@ namespace System.DirectoryServices.ActiveDirectory
{
int lastError = Marshal.GetLastWin32Error();
throw new InvalidOperationException(
- String.Format(CultureInfo.CurrentCulture, SR.UnableToRetrieveTokenInfo, lastError));
+ SR.Format(SR.UnableToRetrieveTokenInfo, lastError));
}
return pCopyOfUserSid;
@@ -2205,9 +2197,7 @@ namespace System.DirectoryServices.ActiveDirectory
if (err != 0)
{
- throw new InvalidOperationException(String.Format(CultureInfo.CurrentCulture,
- SR.UnableToRetrievePolicy,
- NativeMethods.LsaNtStatusToWinError(err)));
+ throw new InvalidOperationException(SR.Format(SR.UnableToRetrievePolicy, NativeMethods.LsaNtStatusToWinError(err)));
}
Debug.Assert(pPolicyHandle != IntPtr.Zero);
@@ -2218,9 +2208,7 @@ namespace System.DirectoryServices.ActiveDirectory
if (err != 0)
{
- throw new InvalidOperationException(String.Format(CultureInfo.CurrentCulture,
- SR.UnableToRetrievePolicy,
- NativeMethods.LsaNtStatusToWinError(err)));
+ throw new InvalidOperationException(SR.Format(SR.UnableToRetrievePolicy, NativeMethods.LsaNtStatusToWinError(err)));
}
Debug.Assert(pBuffer != IntPtr.Zero);
@@ -2237,7 +2225,7 @@ namespace System.DirectoryServices.ActiveDirectory
{
int lastError = Marshal.GetLastWin32Error();
throw new InvalidOperationException(
- String.Format(CultureInfo.CurrentCulture, SR.UnableToRetrievePolicy, lastError));
+ SR.Format(SR.UnableToRetrievePolicy, lastError));
}
return pCopyOfSid;
diff --git a/src/System.DirectoryServices/src/System/DirectoryServices/ActiveDirectory/WellKnownDN.cs b/src/System.DirectoryServices/src/System/DirectoryServices/ActiveDirectory/WellKnownDN.cs
index 4fb5e5e74c..9539515295 100644
--- a/src/System.DirectoryServices/src/System/DirectoryServices/ActiveDirectory/WellKnownDN.cs
+++ b/src/System.DirectoryServices/src/System/DirectoryServices/ActiveDirectory/WellKnownDN.cs
@@ -4,8 +4,6 @@
namespace System.DirectoryServices.ActiveDirectory
{
- using System;
-
internal enum WellKnownDN : int
{
RootDSE = 0,
diff --git a/src/System.DirectoryServices/src/System/DirectoryServices/ActiveDirectorySecurity.cs b/src/System.DirectoryServices/src/System/DirectoryServices/ActiveDirectorySecurity.cs
index b3b5bc70ed..b553819444 100644
--- a/src/System.DirectoryServices/src/System/DirectoryServices/ActiveDirectorySecurity.cs
+++ b/src/System.DirectoryServices/src/System/DirectoryServices/ActiveDirectorySecurity.cs
@@ -2,18 +2,13 @@
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
+using System.Diagnostics;
+using System.ComponentModel;
+using System.Security.Principal;
+using System.Security.AccessControl;
+
namespace System.DirectoryServices
{
- using System;
- using System.Security;
- using System.Diagnostics;
- using System.Globalization;
- using System.ComponentModel;
- using System.Security.Principal;
- using System.Security.AccessControl;
- using System.Runtime.InteropServices;
- using System.DirectoryServices.Interop;
-
[Flags]
public enum ActiveDirectoryRights
{
@@ -55,12 +50,11 @@ namespace System.DirectoryServices
public class ActiveDirectorySecurity : DirectoryObjectSecurity
{
- private SecurityMasks _securityMaskUsedInRetrieval = SecurityMasks.Owner | SecurityMasks.Group | SecurityMasks.Dacl | SecurityMasks.Sacl;
+ private readonly SecurityMasks _securityMaskUsedInRetrieval = SecurityMasks.Owner | SecurityMasks.Group | SecurityMasks.Dacl | SecurityMasks.Sacl;
#region Constructors
public ActiveDirectorySecurity()
- : base()
{
}
@@ -360,20 +354,13 @@ namespace System.DirectoryServices
#endregion
#region some overrides
- public override Type AccessRightType
- {
- get { return typeof(System.DirectoryServices.ActiveDirectoryRights); }
- }
- public override Type AccessRuleType
- {
- get { return typeof(System.DirectoryServices.ActiveDirectoryAccessRule); }
- }
+ public override Type AccessRightType => typeof(ActiveDirectoryRights);
+
+ public override Type AccessRuleType => typeof(ActiveDirectoryAccessRule);
+
+ public override Type AuditRuleType => typeof(ActiveDirectoryAuditRule);
- public override Type AuditRuleType
- {
- get { return typeof(System.DirectoryServices.ActiveDirectoryAuditRule); }
- }
#endregion
}
@@ -382,10 +369,8 @@ namespace System.DirectoryServices
{
#region Access mask to rights translation
- internal static int AccessMaskFromRights(ActiveDirectoryRights adRights)
- {
- return (int)adRights;
- }
+ internal static int AccessMaskFromRights(ActiveDirectoryRights adRights) => (int)adRights;
+
internal static ActiveDirectoryRights RightsFromAccessMask(int accessMask)
{
return (ActiveDirectoryRights)accessMask;
@@ -671,18 +656,12 @@ namespace System.DirectoryServices
public ActiveDirectoryRights ActiveDirectoryRights
{
- get
- {
- return ActiveDirectoryRightsTranslator.RightsFromAccessMask(base.AccessMask);
- }
+ get => ActiveDirectoryRightsTranslator.RightsFromAccessMask(base.AccessMask);
}
public ActiveDirectorySecurityInheritance InheritanceType
{
- get
- {
- return ActiveDirectoryInheritanceTranslator.GetEffectiveInheritanceFlags(base.InheritanceFlags, base.PropagationFlags);
- }
+ get => ActiveDirectoryInheritanceTranslator.GetEffectiveInheritanceFlags(InheritanceFlags, PropagationFlags);
}
#endregion
@@ -1422,18 +1401,12 @@ namespace System.DirectoryServices
public ActiveDirectoryRights ActiveDirectoryRights
{
- get
- {
- return ActiveDirectoryRightsTranslator.RightsFromAccessMask(base.AccessMask);
- }
+ get => ActiveDirectoryRightsTranslator.RightsFromAccessMask(AccessMask);
}
public ActiveDirectorySecurityInheritance InheritanceType
{
- get
- {
- return ActiveDirectoryInheritanceTranslator.GetEffectiveInheritanceFlags(base.InheritanceFlags, base.PropagationFlags);
- }
+ get => ActiveDirectoryInheritanceTranslator.GetEffectiveInheritanceFlags(InheritanceFlags, PropagationFlags);
}
#endregion
diff --git a/src/System.DirectoryServices/src/System/DirectoryServices/AdsVLV.cs b/src/System.DirectoryServices/src/System/DirectoryServices/AdsVLV.cs
index f1c9eee281..e3af05eb87 100644
--- a/src/System.DirectoryServices/src/System/DirectoryServices/AdsVLV.cs
+++ b/src/System.DirectoryServices/src/System/DirectoryServices/AdsVLV.cs
@@ -2,11 +2,10 @@
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
+using System.Runtime.InteropServices;
+
namespace System.DirectoryServices
{
- using System;
- using System.Runtime.InteropServices;
-
[StructLayout(LayoutKind.Sequential)]
internal class AdsVLV
{
diff --git a/src/System.DirectoryServices/src/System/DirectoryServices/AuthenticationTypes.cs b/src/System.DirectoryServices/src/System/DirectoryServices/AuthenticationTypes.cs
index 728fdeba97..9b93efe16b 100644
--- a/src/System.DirectoryServices/src/System/DirectoryServices/AuthenticationTypes.cs
+++ b/src/System.DirectoryServices/src/System/DirectoryServices/AuthenticationTypes.cs
@@ -2,52 +2,42 @@
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
+using System.DirectoryServices.Interop;
+
namespace System.DirectoryServices
{
- using System;
- using System.DirectoryServices.Interop;
-
- /// <include file='doc\AuthenticationTypes.uex' path='docs/doc[@for="AuthenticationTypes"]/*' />
/// <devdoc>
- /// <para>
- /// Specifies what kind of acknowledgment to get after sending a message.
- /// </para>
+ /// Specifies what kind of acknowledgment to get after sending a message.
/// </devdoc>
[Flags]
public enum AuthenticationTypes
{
- /// <include file='doc\AuthenticationTypes.uex' path='docs/doc[@for="AuthenticationTypes.None"]/*' />
None = 0,
- /// <include file='doc\AuthenticationTypes.uex' path='docs/doc[@for="AuthenticationTypes.Secure"]/*' />
/// <devdoc>
/// Requests secure authentication. When this flag is set, the WinNT provider uses NT LAN Manager (NTLM)
/// to authenticate the client. Active Directory will use Kerberos, and possibly NTLM, to authenticate the client.
/// </devdoc>
Secure = NativeMethods.AuthenticationModes.SecureAuthentication,
- /// <include file='doc\AuthenticationTypes.uex' path='docs/doc[@for="AuthenticationTypes.Encription"]/*' />
/// <devdoc>
/// Forces ADSI to use encryption for data exchange over the network.
/// </devdoc>
Encryption = NativeMethods.AuthenticationModes.UseEncryption,
- /// <include file='doc\AuthenticationTypes.uex' path='docs/doc[@for="AuthenticationTypes.SecureSocketsLayer"]/*' />
/// <devdoc>
/// Encrypts the channel with SSL. Data will be encrypted using SSL. Active Directory requires that the
/// Certificate Server be installed to support SSL encryption.
/// </devdoc>
SecureSocketsLayer = NativeMethods.AuthenticationModes.UseSSL,
- /// <include file='doc\AuthenticationTypes.uex' path='docs/doc[@for="AuthenticationTypes.ReadonlyServer"]/*' />
/// <devdoc>
/// For a WinNT provider, ADSI tries to connect to a primary domain controller or a backup domain
/// controller. For Active Directory, this flag indicates that a writeable server is not required for a
/// serverless binding.
/// </devdoc>
ReadonlyServer = NativeMethods.AuthenticationModes.ReadonlyServer,
-
- /// <include file='doc\AuthenticationTypes.uex' path='docs/doc[@for="AuthenticationTypes.Anonymous"]/*' />
+
/// <devdoc>
/// Request no authentication. The providers may attempt to bind client, as an anonymous user, to the targeted
/// object. The WinNT provider does not support this flag. Active Directory establishes a connection between
@@ -55,34 +45,29 @@ namespace System.DirectoryServices
/// requesting an anonymous binding, which means "Everyone" as the security context.
/// </devdoc>
Anonymous = NativeMethods.AuthenticationModes.NoAuthentication,
-
- /// <include file='doc\AuthenticationTypes.uex' path='docs/doc[@for="AuthenticationTypes.FastBind"]/*' />
+
/// <devdoc>
/// When this flag is set, ADSI will not attempt to query the objectClass property and thus will only expose
/// the base interfaces supported by all ADSI objects instead of the full object support.
/// </devdoc>
FastBind = NativeMethods.AuthenticationModes.FastBind,
- /// <include file='doc\AuthenticationTypes.uex' path='docs/doc[@for="AuthenticationTypes.Signing"]/*' />
/// <devdoc>
/// Verifies data integrity to ensure the data received is the same as the data sent. The Secure flag
/// must be set also in order to use the signing.
/// </devdoc>
Signing = NativeMethods.AuthenticationModes.UseSigning,
- /// <include file='doc\AuthenticationTypes.uex' path='docs/doc[@for="AuthenticationTypes.Sealing"]/*' />
/// <devdoc>
/// Encrypts data using Kerberos. The Secure flag must be set also in order to use the sealing.
/// </devdoc>
Sealing = NativeMethods.AuthenticationModes.UseSealing,
- /// <include file='doc\AuthenticationTypes.uex' path='docs/doc[@for="AuthenticationTypes.Delegation"]/*' />
/// <devdoc>
/// Enables ADSI to delegate the user's security context, which is necessary for moving objects across domains.
/// </devdoc>
Delegation = NativeMethods.AuthenticationModes.UseDelegation,
- /// <include file='doc\AuthenticationTypes.uex' path='docs/doc[@for="AuthenticationTypes.ServerBind"]/*' />
/// <devdoc>
/// Specify this flag when using the LDAP provider if your ADsPath includes a server name. Do not use
/// this flag for paths that include a domain name or for serverless paths.
@@ -90,4 +75,3 @@ namespace System.DirectoryServices
ServerBind = NativeMethods.AuthenticationModes.UseServerBinding
}
}
-
diff --git a/src/System.DirectoryServices/src/System/DirectoryServices/DerefAlias.cs b/src/System.DirectoryServices/src/System/DirectoryServices/DerefAlias.cs
index 3bbb5e41ce..920877ae08 100644
--- a/src/System.DirectoryServices/src/System/DirectoryServices/DerefAlias.cs
+++ b/src/System.DirectoryServices/src/System/DirectoryServices/DerefAlias.cs
@@ -4,24 +4,14 @@
namespace System.DirectoryServices
{
- /// <include file='doc\DerefAlias.uex' path='docs/doc[@for="DerefAlias"]/*' />
/// <devdoc>
- /// <para>
- /// Specifies the behavior in which aliases are dereferenced.
- /// </para>
+ /// Specifies the behavior in which aliases are dereferenced.
/// </devdoc>
public enum DereferenceAlias
{
- /// <include file='doc\DerefAlias.uex' path='docs/doc[@for="DerefAlias.Never"]/*' />
Never = 0,
-
- /// <include file='doc\DerefAlias.uex' path='docs/doc[@for="DerefAlias.Searching"]/*' />
InSearching = 1,
-
- /// <include file='doc\DerefAlias.uex' path='docs/doc[@for="DerefAlias.Finding"]/*' />
FindingBaseObject = 2,
-
- /// <include file='doc\DerefAlias.uex' path='docs/doc[@for="DerefAlias.Always"]/*' />
Always = 3
}
}
diff --git a/src/System.DirectoryServices/src/System/DirectoryServices/Design/DirectoryEntryConverter.cs b/src/System.DirectoryServices/src/System/DirectoryServices/Design/DirectoryEntryConverter.cs
index a42bc57f96..7924b84f52 100644
--- a/src/System.DirectoryServices/src/System/DirectoryServices/Design/DirectoryEntryConverter.cs
+++ b/src/System.DirectoryServices/src/System/DirectoryServices/Design/DirectoryEntryConverter.cs
@@ -2,36 +2,27 @@
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
+using System.ComponentModel;
+using System.Collections;
+using System.Globalization;
+
namespace System.DirectoryServices.Design
{
- using System.ComponentModel;
- using System.ComponentModel.Design;
- using System;
- using System.Reflection;
- using System.Collections;
- using System.Collections.Specialized;
- using System.Globalization;
-
- /// <include file='doc\DirectoryEntryConverter.uex' path='docs/doc[@for="DirectoryEntryConverter"]/*' />
- /// <internalonly/>
internal class DirectoryEntryConverter : TypeConverter
{
private static StandardValuesCollection s_values;
private static Hashtable s_componentsCreated = new Hashtable(StringComparer.OrdinalIgnoreCase);
-
- /// <include file='doc\DirectoryEntryConverter.uex' path='docs/doc[@for="DirectoryEntryConverter.CanConvertFrom"]/*' />
- /// <internalonly/>
+
public override bool CanConvertFrom(ITypeDescriptorContext context, Type sourceType)
{
if (sourceType == typeof(string))
{
return true;
}
+
return base.CanConvertFrom(context, sourceType);
}
-
- /// <include file='doc\DirectoryEntryConverter.uex' path='docs/doc[@for="DirectoryEntryConverter.ConvertFrom"]/*' />
- /// <internalonly/>
+
public override object ConvertFrom(ITypeDescriptorContext context, CultureInfo culture, object value)
{
if (value != null && value is string)
@@ -58,9 +49,7 @@ namespace System.DirectoryServices.Design
return null;
}
-
- /// <include file='doc\DirectoryEntryConverter.uex' path='docs/doc[@for="DirectoryEntryConverter.ConvertTo"]/*' />
- /// <internalonly/>
+
public override object ConvertTo(ITypeDescriptorContext context, CultureInfo culture, object value, Type destinationType)
{
if (destinationType != null && destinationType == typeof(string))
@@ -73,9 +62,7 @@ namespace System.DirectoryServices.Design
return base.ConvertTo(context, culture, value, destinationType);
}
-
- /// <include file='doc\MessageFormatterConverter.uex' path='docs/doc[@for="DirectoryEntryConverter.GetStandardValues"]/*' />
- /// <internalonly/>
+
public override StandardValuesCollection GetStandardValues(ITypeDescriptorContext context)
{
if (s_values == null)
@@ -103,20 +90,9 @@ namespace System.DirectoryServices.Design
return null;
}
-
- /// <include file='doc\MessageFormatterConverter.uex' path='docs/doc[@for="DirectoryEntryConverter.GetStandardValuesExclusive"]/*' />
- /// <internalonly/>
- public override bool GetStandardValuesExclusive(ITypeDescriptorContext context)
- {
- return false;
- }
-
- /// <include file='doc\MessageFormatterConverter.uex' path='docs/doc[@for="DirectoryEntryConverter.GetStandardValuesSupported"]/*' />
- /// <internalonly/>
- public override bool GetStandardValuesSupported(ITypeDescriptorContext context)
- {
- return true;
- }
+
+ public override bool GetStandardValuesExclusive(ITypeDescriptorContext context) => false;
+
+ public override bool GetStandardValuesSupported(ITypeDescriptorContext context) => true;
}
}
-
diff --git a/src/System.DirectoryServices/src/System/DirectoryServices/DirectoryEntries.cs b/src/System.DirectoryServices/src/System/DirectoryServices/DirectoryEntries.cs
index 775091e370..2f894aa6d1 100644
--- a/src/System.DirectoryServices/src/System/DirectoryServices/DirectoryEntries.cs
+++ b/src/System.DirectoryServices/src/System/DirectoryServices/DirectoryEntries.cs
@@ -2,33 +2,27 @@
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
+using System.Runtime.InteropServices;
+using System.Collections;
+using System.DirectoryServices.Interop;
+
namespace System.DirectoryServices
{
- using System;
- using System.Runtime.InteropServices;
- using System.Collections;
- using System.Diagnostics;
- using System.DirectoryServices.Interop;
- using System.Security.Permissions;
- using System.Globalization;
-
- /// <include file='doc\DirectoryEntries.uex' path='docs/doc[@for="DirectoryEntries"]/*' />
/// <devdoc>
- /// <para>Contains the children (child entries) of an entry in the Active Directory.</para>
+ /// Contains the children (child entries) of an entry in the Active Directory.
/// </devdoc>
public class DirectoryEntries : IEnumerable
{
// the parent of the children in this collection
- private DirectoryEntry _container;
+ private readonly DirectoryEntry _container;
internal DirectoryEntries(DirectoryEntry parent)
{
_container = parent;
}
-
- /// <include file='doc\DirectoryEntries.uex' path='docs/doc[@for="DirectoryEntries.SchemaFilter"]/*' />
+
/// <devdoc>
- /// <para>Gets the schemas that specify which children are shown.</para>
+ /// Gets the schemas that specify which children are shown.
/// </devdoc>
public SchemaNameCollection SchemaFilter
{
@@ -43,13 +37,12 @@ namespace System.DirectoryServices
private void CheckIsContainer()
{
if (!_container.IsContainer)
- throw new InvalidOperationException(String.Format(CultureInfo.CurrentCulture, SR.DSNotAContainer , _container.Path));
+ throw new InvalidOperationException(SR.Format(SR.DSNotAContainer , _container.Path));
}
-
- /// <include file='doc\DirectoryEntries.uex' path='docs/doc[@for="DirectoryEntries.Add"]/*' />
+
/// <devdoc>
- /// <para>Creates a request to create a new entry in the container.</para>
- /// </devdoc>
+ /// Creates a request to create a new entry in the container.
+ /// </devdoc>
public DirectoryEntry Add(string name, string schemaClassName)
{
CheckIsContainer();
@@ -58,21 +51,19 @@ namespace System.DirectoryServices
entry.JustCreated = true; // suspend writing changes until CommitChanges() is called
return entry;
}
-
- /// <include file='doc\DirectoryEntries.uex' path='docs/doc[@for="DirectoryEntries.Find"]/*' />
+
/// <devdoc>
- /// <para>Returns the child with the given name.</para>
- /// </devdoc>
+ /// Returns the child with the given name.
+ /// </devdoc>
public DirectoryEntry Find(string name)
{
// For IIS: and WinNT: providers schemaClassName == "" does general search.
return Find(name, null);
}
- /// <include file='doc\DirectoryEntries.uex' path='docs/doc[@for="DirectoryEntries.Find1"]/*' />
/// <devdoc>
- /// <para>Returns the child with the given name and of the given type.</para>
- /// </devdoc>
+ /// Returns the child with the given name and of the given type.
+ /// </devdoc>
public DirectoryEntry Find(string name, string schemaClassName)
{
CheckIsContainer();
@@ -88,11 +79,10 @@ namespace System.DirectoryServices
}
return new DirectoryEntry(o, _container.UsePropertyCache, _container.GetUsername(), _container.GetPassword(), _container.AuthenticationType);
}
-
- /// <include file='doc\DirectoryEntries.uex' path='docs/doc[@for="DirectoryEntries.Remove"]/*' />
+
/// <devdoc>
- /// <para>Deletes a child <see cref='System.DirectoryServices.DirectoryEntry'/> from this collection.</para>
- /// </devdoc>
+ /// Deletes a child <see cref='System.DirectoryServices.DirectoryEntry'/> from this collection.
+ /// </devdoc>
public void Remove(DirectoryEntry entry)
{
CheckIsContainer();
@@ -106,21 +96,11 @@ namespace System.DirectoryServices
}
}
- /// <include file='doc\DirectoryEntries.uex' path='docs/doc[@for="DirectoryEntries.GetEnumerator"]/*' />
- /// <devdoc>
- /// <para>[To be supplied.]</para>
- /// </devdoc>
- public IEnumerator GetEnumerator()
- {
- return new ChildEnumerator(_container);
- }
-
- /// <include file='doc\DirectoryEntries.uex' path='docs/doc[@for="DirectoryEntries.ChildEnumerator"]/*' />
+ public IEnumerator GetEnumerator() => new ChildEnumerator(_container);
+
/// <devdoc>
- /// <para>
- /// Supports a simple ForEach-style iteration over a collection and defines
- /// enumerators, size, and synchronization methods.
- /// </para>
+ /// Supports a simple ForEach-style iteration over a collection and defines
+ /// enumerators, size, and synchronization methods.
/// </devdoc>
private class ChildEnumerator : IEnumerator
{
@@ -136,10 +116,9 @@ namespace System.DirectoryServices
_enumVariant = new SafeNativeMethods.EnumVariant((SafeNativeMethods.IEnumVariant)container.ContainerObject._NewEnum);
}
}
-
- /// <include file='doc\DirectoryEntries.uex' path='docs/doc[@for="DirectoryEntries.ChildEnumerator.Current"]/*' />
+
/// <devdoc>
- /// <para>Gets the current element in the collection.</para>
+ /// Gets the current element in the collection.
/// </devdoc>
public DirectoryEntry Current
{
@@ -154,12 +133,10 @@ namespace System.DirectoryServices
return _currentEntry;
}
}
-
- /// <include file='doc\DirectoryEntries.uex' path='docs/doc[@for="DirectoryEntries.ChildEnumerator.MoveNext"]/*' />
+
/// <devdoc>
- /// <para>Advances
- /// the enumerator to the next element of the collection
- /// and returns a Boolean value indicating whether a valid element is available.</para>
+ /// Advances the enumerator to the next element of the collection
+ /// and returns a Boolean value indicating whether a valid element is available.</para>
/// </devdoc>
public bool MoveNext()
{
@@ -170,9 +147,8 @@ namespace System.DirectoryServices
return _enumVariant.GetNext();
}
- /// <include file='doc\DirectoryEntries.uex' path='docs/doc[@for="DirectoryEntries.ChildEnumerator.Reset"]/*' />
/// <devdoc>
- /// <para>Resets the enumerator back to its initial position before the first element in the collection.</para>
+ /// Resets the enumerator back to its initial position before the first element in the collection.
/// </devdoc>
public void Reset()
{
@@ -191,14 +167,7 @@ namespace System.DirectoryServices
}
}
- object IEnumerator.Current
- {
- get
- {
- return Current;
- }
- }
+ object IEnumerator.Current => Current;
}
}
}
-
diff --git a/src/System.DirectoryServices/src/System/DirectoryServices/DirectoryEntry.cs b/src/System.DirectoryServices/src/System/DirectoryServices/DirectoryEntry.cs
index 13fbfbb341..6acd25b35c 100644
--- a/src/System.DirectoryServices/src/System/DirectoryServices/DirectoryEntry.cs
+++ b/src/System.DirectoryServices/src/System/DirectoryServices/DirectoryEntry.cs
@@ -2,25 +2,21 @@
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
+using System.Runtime.InteropServices;
+using System.Diagnostics;
+using System.DirectoryServices.Interop;
+using System.ComponentModel;
+using System.Threading;
+using System.Reflection;
+using System.Security.Permissions;
+using System.DirectoryServices.Design;
+using System.Globalization;
+using System.Net;
+
namespace System.DirectoryServices
{
- using System;
- using System.Text;
- using System.Runtime.InteropServices;
- using System.Collections;
- using System.Diagnostics;
- using System.DirectoryServices.Interop;
- using System.ComponentModel;
- using System.Threading;
- using System.Reflection;
- using System.Security.Permissions;
- using System.DirectoryServices.Design;
- using System.Globalization;
- using System.Net;
-
- /// <include file='doc\DirectoryEntry.uex' path='docs/doc[@for="DirectoryEntry"]/*' />
/// <devdoc>
- /// <para> Encapsulates a node or an object in the Active Directory hierarchy.</para>
+ /// Encapsulates a node or an object in the Active Directory hierarchy.
/// </devdoc>
[
TypeConverterAttribute(typeof(DirectoryEntryConverter)),
@@ -37,11 +33,10 @@ namespace System.DirectoryServices
#pragma warning disable 0414
internal bool propertiesAlreadyEnumerated = false;
#pragma warning restore 0414
- private bool _justCreated = false; // 'true' if newly created entry was not yet stored by CommitChanges().
private bool _disposed = false;
private AuthenticationTypes _authenticationType = AuthenticationTypes.Secure;
private NetworkCredential _credentials;
- private DirectoryEntryConfiguration _options;
+ private readonly DirectoryEntryConfiguration _options;
private PropertyCollection _propertyCollection = null;
internal bool allowMultipleChange = false;
@@ -52,44 +47,32 @@ namespace System.DirectoryServices
private ActiveDirectorySecurity _objectSecurity = null;
private static string s_securityDescriptorProperty = "ntSecurityDescriptor";
- /// <include file='doc\DirectoryEntry.uex' path='docs/doc[@for="DirectoryEntry.DirectoryEntry"]/*' />
/// <devdoc>
- /// <para>
- /// Initializes a new instance of the <see cref='System.DirectoryServices.DirectoryEntry'/>class.
- /// </para>
+ /// Initializes a new instance of the <see cref='System.DirectoryServices.DirectoryEntry'/>class.
/// </devdoc>
public DirectoryEntry()
{
_options = new DirectoryEntryConfiguration(this);
}
-
- /// <include file='doc\DirectoryEntry.uex' path='docs/doc[@for="DirectoryEntry.DirectoryEntry1"]/*' />
+
/// <devdoc>
- /// <para>
- /// Initializes a new instance of the <see cref='System.DirectoryServices.DirectoryEntry'/> class that will bind
- /// to the directory entry at <paramref name="path"/>.
- /// </para>
+ /// Initializes a new instance of the <see cref='System.DirectoryServices.DirectoryEntry'/> class that will bind
+ /// to the directory entry at <paramref name="path"/>.
/// </devdoc>
public DirectoryEntry(string path) : this()
{
Path = path;
}
- /// <include file='doc\DirectoryEntry.uex' path='docs/doc[@for="DirectoryEntry.DirectoryEntry2"]/*' />
/// <devdoc>
- /// <para>
- /// Initializes a new instance of the <see cref='System.DirectoryServices.DirectoryEntry'/> class.
- /// </para>
+ /// Initializes a new instance of the <see cref='System.DirectoryServices.DirectoryEntry'/> class.
/// </devdoc>
public DirectoryEntry(string path, string username, string password) : this(path, username, password, AuthenticationTypes.Secure)
{
}
- /// <include file='doc\DirectoryEntry.uex' path='docs/doc[@for="DirectoryEntry.DirectoryEntry3"]/*' />
/// <devdoc>
- /// <para>
- /// Initializes a new instance of the <see cref='System.DirectoryServices.DirectoryEntry'/> class.
- /// </para>
+ /// Initializes a new instance of the <see cref='System.DirectoryServices.DirectoryEntry'/> class.
/// </devdoc>
public DirectoryEntry(string path, string username, string password, AuthenticationTypes authenticationType) : this(path)
{
@@ -119,12 +102,9 @@ namespace System.DirectoryServices
_options = new DirectoryEntryConfiguration(this);
}
- /// <include file='doc\DirectoryEntry.uex' path='docs/doc[@for="DirectoryEntry.DirectoryEntry4"]/*' />
/// <devdoc>
- /// <para>
- /// Initializes a new instance of the <see cref='System.DirectoryServices.DirectoryEntry'/> class that will bind
- /// to the native Active Directory object which is passed in.
- /// </para>
+ /// Initializes a new instance of the <see cref='System.DirectoryServices.DirectoryEntry'/> class that will bind
+ /// to the native Active Directory object which is passed in.
/// </devdoc>
public DirectoryEntry(object adsObject)
: this(adsObject, true, null, null, AuthenticationTypes.Secure, true)
@@ -179,17 +159,11 @@ namespace System.DirectoryServices
return _adsObject;
}
}
-
- /// <include file='doc\DirectoryEntry.uex' path='docs/doc[@for="DirectoryEntry.AuthenticationType"]/*' />
- [
- DefaultValue(AuthenticationTypes.Secure),
- ]
+
+ [DefaultValue(AuthenticationTypes.Secure)]
public AuthenticationTypes AuthenticationType
{
- get
- {
- return _authenticationType;
- }
+ get => _authenticationType;
set
{
if (_authenticationType == value)
@@ -200,27 +174,14 @@ namespace System.DirectoryServices
}
}
- private bool Bound
- {
- get
- {
- return _adsObject != null;
- }
- }
+ private bool Bound => _adsObject != null;
- /// <include file='doc\DirectoryEntry.uex' path='docs/doc[@for="DirectoryEntry.Children"]/*' />
/// <devdoc>
- /// <para>Gets a <see cref='System.DirectoryServices.DirectoryEntries'/>
+ /// Gets a <see cref='System.DirectoryServices.DirectoryEntries'/>
/// containing the child entries of this node in the Active
- /// Directory hierarchy.</para>
+ /// Directory hierarchy.
/// </devdoc>
- public DirectoryEntries Children
- {
- get
- {
- return new DirectoryEntries(this);
- }
- }
+ public DirectoryEntries Children => new DirectoryEntries(this);
internal UnsafeNativeMethods.IAdsContainer ContainerObject
{
@@ -231,11 +192,8 @@ namespace System.DirectoryServices
}
}
- /// <include file='doc\DirectoryEntry.uex' path='docs/doc[@for="DirectoryEntry.Guid"]/*' />
/// <devdoc>
- /// <para>
- /// Gets the globally unique identifier of the <see cref='System.DirectoryServices.DirectoryEntry'/>.
- /// </para>
+ /// Gets the globally unique identifier of the <see cref='System.DirectoryServices.DirectoryEntry'/>.
/// </devdoc>
public Guid Guid
{
@@ -294,24 +252,10 @@ namespace System.DirectoryServices
}
}
- internal bool JustCreated
- {
- get
- {
- return _justCreated;
- }
- set
- {
- _justCreated = value;
- }
- }
+ internal bool JustCreated { get; set; }
- /// <include file='doc\DirectoryEntry.uex' path='docs/doc[@for="DirectoryEntry.Name"]/*' />
/// <devdoc>
- /// <para>
- /// Gets the relative name of the object as named with the
- /// underlying directory service.
- /// </para>
+ /// Gets the relative name of the object as named with the underlying directory service.
/// </devdoc>
public string Name
{
@@ -323,11 +267,7 @@ namespace System.DirectoryServices
return tmpName;
}
}
-
- /// <include file='doc\DirectoryEntry.uex' path='docs/doc[@for="DirectoryEntry.NativeGuid"]/*' />
- /// <devdoc>
- /// <para>[To be supplied.]</para>
- /// </devdoc>
+
public string NativeGuid
{
get
@@ -339,11 +279,8 @@ namespace System.DirectoryServices
}
}
- /// <include file='doc\DirectoryEntry.uex' path='docs/doc[@for="DirectoryEntry.NativeObject"]/*' />
/// <devdoc>
- /// <para>
- /// Gets the native Active Directory Services Interface (ADSI) object.
- /// </para>
+ /// Gets the native Active Directory Services Interface (ADSI) object.
/// </devdoc>
public object NativeObject
{
@@ -354,12 +291,8 @@ namespace System.DirectoryServices
}
}
- /// <include file='doc\DirectoryEntry.uex' path='docs/doc[@for="DirectoryEntry.Parent"]/*' />
/// <devdoc>
- /// <para>
- /// Gets this
- /// entry's parent entry in the Active Directory hierarchy.
- /// </para>
+ /// Gets this entry's parent entry in the Active Directory hierarchy.
/// </devdoc>
public DirectoryEntry Parent
{
@@ -370,13 +303,10 @@ namespace System.DirectoryServices
}
}
- /// <include file='doc\DirectoryEntry.uex' path='docs/doc[@for="DirectoryEntry.Password"]/*' />
/// <devdoc>
- /// <para>Gets or sets the password to use when authenticating the client.</para>
+ /// Gets or sets the password to use when authenticating the client.
/// </devdoc>
- [
- DefaultValue(null),
- ]
+ [DefaultValue(null)]
public string Password
{
set
@@ -402,9 +332,8 @@ namespace System.DirectoryServices
}
}
- /// <include file='doc\DirectoryEntry.uex' path='docs/doc[@for="DirectoryEntry.Path"]/*' />
/// <devdoc>
- /// <para>Gets or sets the path for this <see cref='System.DirectoryServices.DirectoryEntry'/>.</para>
+ /// Gets or sets the path for this <see cref='System.DirectoryServices.DirectoryEntry'/>.
/// </devdoc>
[
DefaultValue(""),
@@ -413,10 +342,7 @@ namespace System.DirectoryServices
]
public string Path
{
- get
- {
- return _path;
- }
+ get => _path;
set
{
if (value == null)
@@ -430,12 +356,8 @@ namespace System.DirectoryServices
}
}
- /// <include file='doc\DirectoryEntry.uex' path='docs/doc[@for="DirectoryEntry.Properties"]/*' />
/// <devdoc>
- /// <para>
- /// Gets a <see cref='System.DirectoryServices.PropertyCollection'/>
- /// of properties set on this object.
- /// </para>
+ /// Gets a <see cref='System.DirectoryServices.PropertyCollection'/> of properties set on this object.
/// </devdoc>
public PropertyCollection Properties
{
@@ -450,9 +372,8 @@ namespace System.DirectoryServices
}
}
- /// <include file='doc\DirectoryEntry.uex' path='docs/doc[@for="DirectoryEntry.SchemaClassName"]/*' />
/// <devdoc>
- /// <para>Gets the name of the schema used for this <see cref='System.DirectoryServices.DirectoryEntry'/>.</para>
+ /// Gets the name of the schema used for this <see cref='System.DirectoryServices.DirectoryEntry'/>
/// </devdoc>
public string SchemaClassName
{
@@ -465,11 +386,10 @@ namespace System.DirectoryServices
}
}
- /// <include file='doc\DirectoryEntry.uex' path='docs/doc[@for="DirectoryEntry.SchemaEntry"]/*' />
/// <devdoc>
- /// <para>Gets the <see cref='System.DirectoryServices.DirectoryEntry'/> that holds schema information for this
- /// entry. An entry's <see cref='System.DirectoryServices.DirectoryEntry.SchemaClassName'/>
- /// determines what properties are valid for it.</para>
+ /// Gets the <see cref='System.DirectoryServices.DirectoryEntry'/> that holds schema information for this
+ /// entry. An entry's <see cref='System.DirectoryServices.DirectoryEntry.SchemaClassName'/>
+ /// determines what properties are valid for it.</para>
/// </devdoc>
public DirectoryEntry SchemaEntry
{
@@ -485,22 +405,14 @@ namespace System.DirectoryServices
// the first read. Setting this to false will cause the
// cache to be committed after each operation.
//
- /// <include file='doc\DirectoryEntry.uex' path='docs/doc[@for="DirectoryEntry.UsePropertyCache"]/*' />
/// <devdoc>
- /// <para>
- /// Gets a value indicating whether the cache should be committed after each
- /// operation.
- /// </para>
+ /// Gets a value indicating whether the cache should be committed after each
+ /// operation.
/// </devdoc>
- [
- DefaultValue(true),
- ]
+ [DefaultValue(true)]
public bool UsePropertyCache
{
- get
- {
- return _useCache;
- }
+ get => _useCache;
set
{
if (value == _useCache)
@@ -515,9 +427,8 @@ namespace System.DirectoryServices
}
}
- /// <include file='doc\DirectoryEntry.uex' path='docs/doc[@for="DirectoryEntry.Username"]/*' />
/// <devdoc>
- /// <para>Gets or sets the username to use when authenticating the client.</para>
+ /// Gets or sets the username to use when authenticating the client.</para>
/// </devdoc>
[
DefaultValue(null),
@@ -603,7 +514,6 @@ namespace System.DirectoryServices
}
}
- /// <include file='doc\DirectoryEntry.uex' path='docs/doc[@for="DirectoryEntry.Bind"]/*' />
/// <devdoc>
/// Binds to the ADs object (if not already bound).
/// </devdoc>
@@ -664,28 +574,21 @@ namespace System.DirectoryServices
return newEntry;
}
- /// <include file='doc\DirectoryEntry.uex' path='docs/doc[@for="DirectoryEntry.Close"]/*' />
/// <devdoc>
- /// <para>
- /// Closes the <see cref='System.DirectoryServices.DirectoryEntry'/>
- /// and releases any system resources associated with this component.
- /// </para>
+ /// Closes the <see cref='System.DirectoryServices.DirectoryEntry'/>
+ /// and releases any system resources associated with this component.
/// </devdoc>
public void Close()
{
Unbind();
}
- /// <include file='doc\DirectoryEntry.uex' path='docs/doc[@for="DirectoryEntry.CommitChanges"]/*' />
/// <devdoc>
- /// <para>
- /// Saves any
- /// changes to the entry in the directory store.
- /// </para>
+ /// Saves any changes to the entry in the directory store.
/// </devdoc>
public void CommitChanges()
{
- if (_justCreated)
+ if (JustCreated)
{
// Note: Permissions Demand is not necessary here, because entry has already been created with appr. permissions.
// Write changes regardless of Caching mode to finish construction of a new entry.
@@ -702,7 +605,7 @@ namespace System.DirectoryServices
{
throw COMExceptionHelper.CreateFormattedComException(e);
}
- _justCreated = false;
+ JustCreated = false;
_objectSecurityInitialized = false;
_objectSecurityModified = false;
@@ -743,7 +646,7 @@ namespace System.DirectoryServices
internal void CommitIfNotCaching()
{
- if (_justCreated)
+ if (JustCreated)
return; // Do not write changes, beacuse the entry is just under construction until CommitChanges() is called.
if (_useCache)
@@ -771,26 +674,18 @@ namespace System.DirectoryServices
_propertyCollection = null;
}
- /// <include file='doc\DirectoryEntry.uex' path='docs/doc[@for="DirectoryEntry.CopyTo"]/*' />
/// <devdoc>
- /// <para>Creates a copy of this entry as a child of the given parent.</para>
+ /// Creates a copy of this entry as a child of the given parent.
/// </devdoc>
- public DirectoryEntry CopyTo(DirectoryEntry newParent)
- {
- return CopyTo(newParent, null);
- }
+ public DirectoryEntry CopyTo(DirectoryEntry newParent) => CopyTo(newParent, null);
- /// <include file='doc\DirectoryEntry.uex' path='docs/doc[@for="DirectoryEntry.CopyTo1"]/*' />
/// <devdoc>
- /// <para>
- /// Creates a copy of this entry as a child of the given parent and
- /// gives it a new name.
- /// </para>
+ /// Creates a copy of this entry as a child of the given parent and gives it a new name.
/// </devdoc>
public DirectoryEntry CopyTo(DirectoryEntry newParent, string newName)
{
if (!newParent.IsContainer)
- throw new InvalidOperationException(String.Format(CultureInfo.CurrentCulture, SR.DSNotAContainer , newParent.Path));
+ throw new InvalidOperationException(SR.Format(SR.DSNotAContainer , newParent.Path));
object copy = null;
try
@@ -804,10 +699,8 @@ namespace System.DirectoryServices
return new DirectoryEntry(copy, newParent.UsePropertyCache, GetUsername(), GetPassword(), AuthenticationType);
}
- /// <include file='doc\DirectoryEntry.uex' path='docs/doc[@for="DirectoryEntry.DeleteTree"]/*' />
/// <devdoc>
- /// <para>Deletes this entry and its entire subtree from the
- /// Active Directory hierarchy.</para>
+ /// Deletes this entry and its entire subtree from the Active Directory hierarchy.
/// </devdoc>
public void DeleteTree()
{
@@ -827,9 +720,6 @@ namespace System.DirectoryServices
GC.KeepAlive(this);
}
- /// <include file='doc\DirectoryEntry.uex' path='docs/doc[@for="DirectoryEntry.Dispose"]/*' />
- /// <devdoc>
- /// </devdoc>
protected override void Dispose(bool disposing)
{
// no managed object to free
@@ -844,12 +734,8 @@ namespace System.DirectoryServices
base.Dispose(disposing);
}
- /// <include file='doc\DirectoryEntry.uex' path='docs/doc[@for="DirectoryEntry.Exists"]/*' />
/// <devdoc>
- /// <para>
- /// Searches the directory store at the given
- /// path to see whether an entry exists.
- /// </para>
+ /// Searches the directory store at the given path to see whether an entry exists.
/// </devdoc>
public static bool Exists(string path)
{
@@ -873,7 +759,6 @@ namespace System.DirectoryServices
}
}
- /// <include file='doc\DirectoryEntry.uex' path='docs/doc[@for="DirectoryEntry.FillCache"]/*' />
/// <devdoc>
/// If UsePropertyCache is true, calls GetInfo the first time it's necessary.
/// If it's false, calls GetInfoEx on the given property name.
@@ -905,10 +790,8 @@ namespace System.DirectoryServices
}
}
- /// <include file='doc\DirectoryEntry.uex' path='docs/doc[@for="DirectoryEntry.Invoke"]/*' />
/// <devdoc>
- /// <para>Calls
- /// a method on the native Active Directory.</para>
+ /// Calls a method on the native Active Directory.
/// </devdoc>
public object Invoke(string methodName, params object[] args)
{
@@ -945,10 +828,8 @@ namespace System.DirectoryServices
return result;
}
- /// <include file='doc\DirectoryEntry.uex' path='docs/doc[@for="DirectoryEntry.InvokeGet"]/*' />
/// <devdoc>
- /// <para>Reads
- /// a property on the native Active Directory object.</para>
+ /// Reads a property on the native Active Directory object.
/// </devdoc>
public object InvokeGet(string propertyName)
{
@@ -981,10 +862,8 @@ namespace System.DirectoryServices
return result;
}
- /// <include file='doc\DirectoryEntry.uex' path='docs/doc[@for="DirectoryEntry.InvokeSet"]/*' />
/// <devdoc>
- /// <para>Sets
- /// a property on the native Active Directory object.</para>
+ /// Sets a property on the native Active Directory object.
/// </devdoc>
public void InvokeSet(string propertyName, params object[] args)
{
@@ -1014,24 +893,19 @@ namespace System.DirectoryServices
}
}
- /// <include file='doc\DirectoryEntry.uex' path='docs/doc[@for="DirectoryEntry.MoveTo"]/*' />
/// <devdoc>
- /// <para>Moves this entry to the given parent.</para>
+ /// Moves this entry to the given parent.
/// </devdoc>
- public void MoveTo(DirectoryEntry newParent)
- {
- MoveTo(newParent, null);
- }
+ public void MoveTo(DirectoryEntry newParent) => MoveTo(newParent, null);
- /// <include file='doc\DirectoryEntry.uex' path='docs/doc[@for="DirectoryEntry.MoveTo1"]/*' />
/// <devdoc>
- /// <para>Moves this entry to the given parent, and gives it a new name.</para>
+ /// Moves this entry to the given parent, and gives it a new name.
/// </devdoc>
public void MoveTo(DirectoryEntry newParent, string newName)
{
object newEntry = null;
if (!(newParent.AdsObject is UnsafeNativeMethods.IAdsContainer))
- throw new InvalidOperationException(String.Format(CultureInfo.CurrentCulture, SR.DSNotAContainer , newParent.Path));
+ throw new InvalidOperationException(SR.Format(SR.DSNotAContainer , newParent.Path));
try
{
if (AdsObject.ADsPath.StartsWith("WinNT:", StringComparison.Ordinal))
@@ -1082,12 +956,8 @@ namespace System.DirectoryServices
RefreshCache(); // in ADSI cache is lost after moving
}
- /// <include file='doc\DirectoryEntry.uex' path='docs/doc[@for="DirectoryEntry.RefreshCache"]/*' />
/// <devdoc>
- /// <para>
- /// Loads the property values for this directory entry into
- /// the property cache.
- /// </para>
+ /// Loads the property values for this directory entry into the property cache.
/// </devdoc>
public void RefreshCache()
{
@@ -1110,12 +980,8 @@ namespace System.DirectoryServices
_objectSecurityModified = false;
}
- /// <include file='doc\DirectoryEntry.uex' path='docs/doc[@for="DirectoryEntry.RefreshCache1"]/*' />
/// <devdoc>
- /// <para>
- /// Loads the values of the specified properties into the
- /// property cache.
- /// </para>
+ /// Loads the values of the specified properties into the property cache.
/// </devdoc>
public void RefreshCache(string[] propertyNames)
{
@@ -1178,16 +1044,10 @@ namespace System.DirectoryServices
}
}
- /// <include file='doc\DirectoryEntry.uex' path='docs/doc[@for="DirectoryEntry.Rename"]/*' />
/// <devdoc>
- /// <para>
- /// Changes the name of this entry.
- /// </para>
+ /// Changes the name of this entry.
/// </devdoc>
- public void Rename(string newName)
- {
- MoveTo(Parent, newName);
- }
+ public void Rename(string newName) => MoveTo(Parent, newName);
private void Unbind()
{
diff --git a/src/System.DirectoryServices/src/System/DirectoryServices/DirectoryEntryConfiguration.cs b/src/System.DirectoryServices/src/System/DirectoryServices/DirectoryEntryConfiguration.cs
index a03821d417..c05b5e88c6 100644
--- a/src/System.DirectoryServices/src/System/DirectoryServices/DirectoryEntryConfiguration.cs
+++ b/src/System.DirectoryServices/src/System/DirectoryServices/DirectoryEntryConfiguration.cs
@@ -2,16 +2,14 @@
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
+using System.DirectoryServices.Interop;
+using System.ComponentModel;
+
namespace System.DirectoryServices
{
- using System;
- using System.DirectoryServices.Interop;
- using System.ComponentModel;
- using System.Security.Permissions;
-
public class DirectoryEntryConfiguration
{
- private DirectoryEntry _entry;
+ private readonly DirectoryEntry _entry;
private const int ISC_RET_MUTUAL_AUTH = 0x00000002;
internal DirectoryEntryConfiguration(DirectoryEntry entry)
diff --git a/src/System.DirectoryServices/src/System/DirectoryServices/DirectorySearcher.cs b/src/System.DirectoryServices/src/System/DirectoryServices/DirectorySearcher.cs
index 311a31df05..1cdab36817 100644
--- a/src/System.DirectoryServices/src/System/DirectoryServices/DirectorySearcher.cs
+++ b/src/System.DirectoryServices/src/System/DirectoryServices/DirectorySearcher.cs
@@ -2,26 +2,18 @@
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
+using System.Runtime.InteropServices;
+using System.Collections;
+using System.Collections.Specialized;
+using System.DirectoryServices.Interop;
+using System.ComponentModel;
+
using INTPTR_INTPTRCAST = System.IntPtr;
-using INTPTR_INTCAST = System.Int32;
namespace System.DirectoryServices
{
- using System;
- using System.Runtime.InteropServices;
- using System.Collections;
- using System.Collections.Specialized;
- using System.Diagnostics;
- using System.DirectoryServices.Interop;
- using System.DirectoryServices.Design;
- using System.ComponentModel;
- using System.Security.Permissions;
- using System.Globalization;
- using Microsoft.Win32;
-
- /// <include file='doc\DirectorySearcher.uex' path='docs/doc[@for="DirectorySearcher"]/*' />
/// <devdoc>
- /// <para> Performs queries against the Active Directory hierarchy.</para>
+ /// Performs queries against the Active Directory hierarchy.
/// </devdoc>
public class DirectorySearcher : Component
{
@@ -37,7 +29,6 @@ namespace System.DirectoryServices
private bool _scopeSpecified = false;
private int _sizeLimit = 0;
private TimeSpan _serverTimeLimit = s_minusOneSecond;
- private bool _propertyNamesOnly = false;
private TimeSpan _clientTimeout = s_minusOneSecond;
private int _pageSize = 0;
private TimeSpan _serverPageTimeLimit = s_minusOneSecond;
@@ -47,8 +38,6 @@ namespace System.DirectoryServices
private bool _cacheResultsSpecified = false;
private bool _rootEntryAllocated = false; // true: if a temporary entry inside Searcher has been created
private string _assertDefaultNamingContext = null;
- private bool _asynchronous = false;
- private bool _tombstone = false;
private string _attributeScopeQuery = "";
private bool _attributeScopeQuerySpecified = false;
private DereferenceAlias _derefAlias = DereferenceAlias.Never;
@@ -62,84 +51,76 @@ namespace System.DirectoryServices
private const string defaultFilter = "(objectClass=*)";
- /// <include file='doc\DirectorySearcher.uex' path='docs/doc[@for="DirectorySearcher.DirectorySearcher"]/*' />
/// <devdoc>
- /// <para>Initializes a new instance of the <see cref='System.DirectoryServices.DirectorySearcher'/> class with <see cref='System.DirectoryServices.DirectorySearcher.SearchRoot'/>,
- /// <see cref='System.DirectoryServices.DirectorySearcher.Filter'/>, <see cref='System.DirectoryServices.DirectorySearcher.PropertiesToLoad'/>, and <see cref='System.DirectoryServices.DirectorySearcher.SearchScope'/> set to their default values.</para>
+ /// Initializes a new instance of the <see cref='System.DirectoryServices.DirectorySearcher'/> class with <see cref='System.DirectoryServices.DirectorySearcher.SearchRoot'/>,
+ /// <see cref='System.DirectoryServices.DirectorySearcher.Filter'/>, <see cref='System.DirectoryServices.DirectorySearcher.PropertiesToLoad'/>, and <see cref='System.DirectoryServices.DirectorySearcher.SearchScope'/> set to their default values.
/// </devdoc>
public DirectorySearcher() : this(null, defaultFilter, null, System.DirectoryServices.SearchScope.Subtree)
{
_scopeSpecified = false;
}
- /// <include file='doc\DirectorySearcher.uex' path='docs/doc[@for="DirectorySearcher.DirectorySearcher1"]/*' />
/// <devdoc>
- /// <para>Initializes a new instance of the <see cref='System.DirectoryServices.DirectorySearcher'/> class with
+ /// Initializes a new instance of the <see cref='System.DirectoryServices.DirectorySearcher'/> class with
/// <see cref='System.DirectoryServices.DirectorySearcher.Filter'/>, <see cref='System.DirectoryServices.DirectorySearcher.PropertiesToLoad'/>, and <see cref='System.DirectoryServices.DirectorySearcher.SearchScope'/> set to their default
- /// values, and <see cref='System.DirectoryServices.DirectorySearcher.SearchRoot'/> set to the given value.</para>
+ /// values, and <see cref='System.DirectoryServices.DirectorySearcher.SearchRoot'/> set to the given value.
/// </devdoc>
public DirectorySearcher(DirectoryEntry searchRoot) : this(searchRoot, defaultFilter, null, System.DirectoryServices.SearchScope.Subtree)
{
_scopeSpecified = false;
}
- /// <include file='doc\DirectorySearcher.uex' path='docs/doc[@for="DirectorySearcher.DirectorySearcher2"]/*' />
/// <devdoc>
- /// <para>Initializes a new instance of the <see cref='System.DirectoryServices.DirectorySearcher'/> class with
+ /// Initializes a new instance of the <see cref='System.DirectoryServices.DirectorySearcher'/> class with
/// <see cref='System.DirectoryServices.DirectorySearcher.PropertiesToLoad'/> and <see cref='System.DirectoryServices.DirectorySearcher.SearchScope'/> set to their default
- /// values, and <see cref='System.DirectoryServices.DirectorySearcher.SearchRoot'/> and <see cref='System.DirectoryServices.DirectorySearcher.Filter'/> set to the respective given values.</para>
+ /// values, and <see cref='System.DirectoryServices.DirectorySearcher.SearchRoot'/> and <see cref='System.DirectoryServices.DirectorySearcher.Filter'/> set to the respective given values.
/// </devdoc>
public DirectorySearcher(DirectoryEntry searchRoot, string filter) : this(searchRoot, filter, null, System.DirectoryServices.SearchScope.Subtree)
{
_scopeSpecified = false;
}
- /// <include file='doc\DirectorySearcher.uex' path='docs/doc[@for="DirectorySearcher.DirectorySearcher3"]/*' />
/// <devdoc>
- /// <para>Initializes a new instance of the <see cref='System.DirectoryServices.DirectorySearcher'/> class with
+ /// Initializes a new instance of the <see cref='System.DirectoryServices.DirectorySearcher'/> class with
/// <see cref='System.DirectoryServices.DirectorySearcher.SearchScope'/> set to its default
- /// value, and <see cref='System.DirectoryServices.DirectorySearcher.SearchRoot'/>, <see cref='System.DirectoryServices.DirectorySearcher.Filter'/>, and <see cref='System.DirectoryServices.DirectorySearcher.PropertiesToLoad'/> set to the respective given values.</para>
+ /// value, and <see cref='System.DirectoryServices.DirectorySearcher.SearchRoot'/>, <see cref='System.DirectoryServices.DirectorySearcher.Filter'/>, and <see cref='System.DirectoryServices.DirectorySearcher.PropertiesToLoad'/> set to the respective given values.
/// </devdoc>
public DirectorySearcher(DirectoryEntry searchRoot, string filter, string[] propertiesToLoad) : this(searchRoot, filter, propertiesToLoad, System.DirectoryServices.SearchScope.Subtree)
{
_scopeSpecified = false;
}
- /// <include file='doc\DirectorySearcher.uex' path='docs/doc[@for="DirectorySearcher.DirectorySearcher4"]/*' />
/// <devdoc>
- /// <para>Initializes a new instance of the <see cref='System.DirectoryServices.DirectorySearcher'/> class with <see cref='System.DirectoryServices.DirectorySearcher.SearchRoot'/>,
+ /// Initializes a new instance of the <see cref='System.DirectoryServices.DirectorySearcher'/> class with <see cref='System.DirectoryServices.DirectorySearcher.SearchRoot'/>,
/// <see cref='System.DirectoryServices.DirectorySearcher.PropertiesToLoad'/>, and <see cref='System.DirectoryServices.DirectorySearcher.SearchScope'/> set to their default
- /// values, and <see cref='System.DirectoryServices.DirectorySearcher.Filter'/> set to the given value.</para>
+ /// values, and <see cref='System.DirectoryServices.DirectorySearcher.Filter'/> set to the given value.
/// </devdoc>
public DirectorySearcher(string filter) : this(null, filter, null, System.DirectoryServices.SearchScope.Subtree)
{
_scopeSpecified = false;
}
- /// <include file='doc\DirectorySearcher.uex' path='docs/doc[@for="DirectorySearcher.DirectorySearcher5"]/*' />
/// <devdoc>
- /// <para>Initializes a new instance of the <see cref='System.DirectoryServices.DirectorySearcher'/> class with <see cref='System.DirectoryServices.DirectorySearcher.SearchRoot'/>
+ /// Initializes a new instance of the <see cref='System.DirectoryServices.DirectorySearcher'/> class with <see cref='System.DirectoryServices.DirectorySearcher.SearchRoot'/>
/// and <see cref='System.DirectoryServices.DirectorySearcher.SearchScope'/> set to their default
- /// values, and <see cref='System.DirectoryServices.DirectorySearcher.Filter'/> and <see cref='System.DirectoryServices.DirectorySearcher.PropertiesToLoad'/> set to the respective given values.</para>
+ /// values, and <see cref='System.DirectoryServices.DirectorySearcher.Filter'/> and <see cref='System.DirectoryServices.DirectorySearcher.PropertiesToLoad'/> set to the respective given values.
/// </devdoc>
public DirectorySearcher(string filter, string[] propertiesToLoad) : this(null, filter, propertiesToLoad, System.DirectoryServices.SearchScope.Subtree)
{
_scopeSpecified = false;
}
- /// <include file='doc\DirectorySearcher.uex' path='docs/doc[@for="DirectorySearcher.DirectorySearcher6"]/*' />
/// <devdoc>
- /// <para>Initializes a new instance of the <see cref='System.DirectoryServices.DirectorySearcher'/> class with <see cref='System.DirectoryServices.DirectorySearcher.SearchRoot'/> set to its default
- /// value, and <see cref='System.DirectoryServices.DirectorySearcher.Filter'/>, <see cref='System.DirectoryServices.DirectorySearcher.PropertiesToLoad'/>, and <see cref='System.DirectoryServices.DirectorySearcher.SearchScope'/> set to the respective given values.</para>
+ /// Initializes a new instance of the <see cref='System.DirectoryServices.DirectorySearcher'/> class with <see cref='System.DirectoryServices.DirectorySearcher.SearchRoot'/> set to its default
+ /// value, and <see cref='System.DirectoryServices.DirectorySearcher.Filter'/>, <see cref='System.DirectoryServices.DirectorySearcher.PropertiesToLoad'/>, and <see cref='System.DirectoryServices.DirectorySearcher.SearchScope'/> set to the respective given values.</para>
/// </devdoc>
public DirectorySearcher(string filter, string[] propertiesToLoad, SearchScope scope) : this(null, filter, propertiesToLoad, scope)
{
}
- /// <include file='doc\DirectorySearcher.uex' path='docs/doc[@for="DirectorySearcher.DirectorySearcher7"]/*' />
/// <devdoc>
- /// <para>Initializes a new instance of the <see cref='System.DirectoryServices.DirectorySearcher'/> class with the <see cref='System.DirectoryServices.DirectorySearcher.SearchRoot'/>, <see cref='System.DirectoryServices.DirectorySearcher.Filter'/>, <see cref='System.DirectoryServices.DirectorySearcher.PropertiesToLoad'/>, and <see cref='System.DirectoryServices.DirectorySearcher.SearchScope'/> properties set to the given
- /// values.</para>
+ /// Initializes a new instance of the <see cref='System.DirectoryServices.DirectorySearcher'/> class with the <see cref='System.DirectoryServices.DirectorySearcher.SearchRoot'/>, <see cref='System.DirectoryServices.DirectorySearcher.Filter'/>, <see cref='System.DirectoryServices.DirectorySearcher.PropertiesToLoad'/>, and <see cref='System.DirectoryServices.DirectorySearcher.SearchScope'/> properties set to the given
+ /// values.
/// </devdoc>
public DirectorySearcher(DirectoryEntry searchRoot, string filter, string[] propertiesToLoad, SearchScope scope)
{
@@ -150,9 +131,6 @@ namespace System.DirectoryServices
this.SearchScope = scope;
}
- /// <include file='doc\DirectorySearcher.uex' path='docs/doc[@for="DirectorySearcher.Dispose"]/*' />
- /// <devdoc>
- /// </devdoc>
protected override void Dispose(bool disposing)
{
// safe to call while finalizing or disposing
@@ -167,22 +145,14 @@ namespace System.DirectoryServices
base.Dispose(disposing);
}
- /// <include file='doc\DirectorySearcher.uex' path='docs/doc[@for="DirectorySearcher.CacheResults"]/*' />
/// <devdoc>
- /// <para>
- /// Gets or sets a value indicating whether the result should be cached on the
- /// client machine.
- /// </para>
+ /// Gets or sets a value indicating whether the result should be cached on the
+ /// client machine.
/// </devdoc>
- [
- DefaultValue(true),
- ]
+ [DefaultValue(true)]
public bool CacheResults
{
- get
- {
- return _cacheResults;
- }
+ get => _cacheResults;
set
{
// user explicitly set CacheResults to true and also want VLV
@@ -195,18 +165,14 @@ namespace System.DirectoryServices
}
}
- /// <include file='doc\DirectorySearcher.uex' path='docs/doc[@for="DirectorySearcher.ClientTimeout"]/*' />
/// <devdoc>
- /// <para>Gets or sets the maximum amount of time that the client waits for
- /// the server to return results. If the server does not respond within this time,
- /// the search is aborted, and no results are returned.</para>
+ /// Gets or sets the maximum amount of time that the client waits for
+ /// the server to return results. If the server does not respond within this time,
+ /// the search is aborted, and no results are returned.</para>
/// </devdoc>
public TimeSpan ClientTimeout
{
- get
- {
- return _clientTimeout;
- }
+ get => _clientTimeout;
set
{
// prevent integer overflow
@@ -219,32 +185,16 @@ namespace System.DirectoryServices
}
}
- /// <include file='doc\DirectorySearcher.uex' path='docs/doc[@for="DirectorySearcher.PropertyNamesOnly"]/*' />
/// <devdoc>
- /// <para>Gets or sets a value indicating whether the search should retrieve only the names of requested
- /// properties or the names and values of requested properties.</para>
+ /// Gets or sets a value indicating whether the search should retrieve only the names of requested
+ /// properties or the names and values of requested properties.</para>
/// </devdoc>
- [
- DefaultValue(false),
- ]
- public bool PropertyNamesOnly
- {
- get
- {
- return _propertyNamesOnly;
- }
- set
- {
- _propertyNamesOnly = value;
- }
- }
+ [DefaultValue(false)]
+ public bool PropertyNamesOnly { get; set; }
- /// <include file='doc\DirectorySearcher.uex' path='docs/doc[@for="DirectorySearcher.Filter"]/*' />
/// <devdoc>
- /// <para>Gets or sets the Lightweight Directory Access Protocol (LDAP) filter string
- /// format.</para>
- /// <![CDATA[ (objectClass=*) (!(objectClass=user)) (&(objectClass=user)(sn=Jones)) ]]>
- /// </devdoc>
+ /// Gets or sets the Lightweight Directory Access Protocol (LDAP) filter string format.
+ /// </devdoc>
[
DefaultValue(defaultFilter),
// CoreFXPort - Remove design support
@@ -252,10 +202,7 @@ namespace System.DirectoryServices
]
public string Filter
{
- get
- {
- return _filter;
- }
+ get => _filter;
set
{
if (value == null || value.Length == 0)
@@ -264,19 +211,13 @@ namespace System.DirectoryServices
}
}
- /// <include file='doc\DirectorySearcher.uex' path='docs/doc[@for="DirectorySearcher.PageSize"]/*' />
/// <devdoc>
- /// <para>Gets or sets the page size in a paged search.</para>
+ /// Gets or sets the page size in a paged search.
/// </devdoc>
- [
- DefaultValue(0),
- ]
+ [DefaultValue(0)]
public int PageSize
{
- get
- {
- return _pageSize;
- }
+ get => _pageSize;
set
{
if (value < 0)
@@ -290,10 +231,9 @@ namespace System.DirectoryServices
}
}
- /// <include file='doc\DirectorySearcher.uex' path='docs/doc[@for="DirectorySearcher.PropertiesToLoad"]/*' />
/// <devdoc>
- /// <para>Gets the set of properties retrieved during the search. By default, the <see cref='System.DirectoryServices.DirectoryEntry.Path'/>
- /// and <see cref='System.DirectoryServices.DirectoryEntry.Name'/> properties are retrieved.</para>
+ /// Gets the set of properties retrieved during the search. By default, the <see cref='System.DirectoryServices.DirectoryEntry.Path'/>
+ /// and <see cref='System.DirectoryServices.DirectoryEntry.Name'/> properties are retrieved.
/// </devdoc>
public StringCollection PropertiesToLoad
{
@@ -307,19 +247,13 @@ namespace System.DirectoryServices
}
}
- /// <include file='doc\DirectorySearcher.uex' path='docs/doc[@for="DirectorySearcher.ReferralChasing"]/*' />
/// <devdoc>
- /// <para>Gets or sets how referrals are chased.</para>
+ /// Gets or sets how referrals are chased.
/// </devdoc>
- [
- DefaultValue(ReferralChasingOption.External),
- ]
+ [DefaultValue(ReferralChasingOption.External)]
public ReferralChasingOption ReferralChasing
{
- get
- {
- return _referralChasing;
- }
+ get => _referralChasing;
set
{
if (value != ReferralChasingOption.None &&
@@ -332,19 +266,13 @@ namespace System.DirectoryServices
}
}
- /// <include file='doc\DirectorySearcher.uex' path='docs/doc[@for="DirectorySearcher.SearchScope"]/*' />
/// <devdoc>
- /// <para>Gets or sets the scope of the search that should be observed by the server.</para>
+ /// Gets or sets the scope of the search that should be observed by the server.
/// </devdoc>
- [
- DefaultValue(SearchScope.Subtree),
- ]
+ [DefaultValue(SearchScope.Subtree)]
public SearchScope SearchScope
{
- get
- {
- return _scope;
- }
+ get => _scope;
set
{
if (value < SearchScope.Base || value > SearchScope.Subtree)
@@ -362,18 +290,13 @@ namespace System.DirectoryServices
}
}
- /// <include file='doc\DirectorySearcher.uex' path='docs/doc[@for="DirectorySearcher.ServerPageTimeLimit"]/*' />
/// <devdoc>
- /// <para> Gets or sets the time limit that the server should
- /// observe to search a page of results (as opposed to
- /// the time limit for the entire search).</para>
+ /// Gets or sets the time limit that the server should observe to search a page of results (as
+ /// opposed to the time limit for the entire search).
/// </devdoc>
public TimeSpan ServerPageTimeLimit
{
- get
- {
- return _serverPageTimeLimit;
- }
+ get => _serverPageTimeLimit;
set
{
// prevent integer overflow
@@ -386,17 +309,13 @@ namespace System.DirectoryServices
}
}
- /// <include file='doc\DirectorySearcher.uex' path='docs/doc[@for="DirectorySearcher.ServerTimeLimit"]/*' />
/// <devdoc>
- /// <para>Gets or sets the maximum amount of time the server spends searching. If the
- /// time limit is reached, only entries found up to that point will be returned.</para>
+ /// Gets or sets the maximum amount of time the server spends searching. If the
+ /// time limit is reached, only entries found up to that point will be returned.
/// </devdoc>
public TimeSpan ServerTimeLimit
{
- get
- {
- return _serverTimeLimit;
- }
+ get => _serverTimeLimit;
set
{
// prevent integer overflow
@@ -409,20 +328,14 @@ namespace System.DirectoryServices
}
}
- /// <include file='doc\DirectorySearcher.uex' path='docs/doc[@for="DirectorySearcher.SizeLimit"]/*' />
/// <devdoc>
- /// <para>Gets or sets the maximum number of objects that the
- /// server should return in a search.</para>
+ /// Gets or sets the maximum number of objects that the
+ /// server should return in a search.
/// </devdoc>
- [
- DefaultValue(0),
- ]
+ [DefaultValue(0)]
public int SizeLimit
{
- get
- {
- return _sizeLimit;
- }
+ get => _sizeLimit;
set
{
if (value < 0)
@@ -431,14 +344,11 @@ namespace System.DirectoryServices
}
}
- /// <include file='doc\DirectorySearcher.uex' path='docs/doc[@for="DirectorySearcher.SearchRoot"]/*' />
/// <devdoc>
- /// <para>Gets or sets the node in the Active Directory hierarchy
- /// at which the search will start.</para>
+ /// Gets or sets the node in the Active Directory hierarchy
+ /// at which the search will start.
/// </devdoc>
- [
- DefaultValueAttribute(null)
- ]
+ [DefaultValue(null)]
public DirectoryEntry SearchRoot
{
get
@@ -470,74 +380,33 @@ namespace System.DirectoryServices
}
}
- /// <include file='doc\DirectorySearcher.uex' path='docs/doc[@for="DirectorySearcher.Sort"]/*' />
/// <devdoc>
- /// <para>Gets the property on which the results should be
- /// sorted.</para>
+ /// Gets the property on which the results should be sorted.
/// </devdoc>
- [
- TypeConverterAttribute(typeof(ExpandableObjectConverter))
- ]
+ [TypeConverter(typeof(ExpandableObjectConverter))]
public SortOption Sort
{
- get
- {
- return _sort;
- }
-
- set
- {
- if (value == null)
- throw new ArgumentNullException("value");
-
- _sort = value;
- }
+ get => _sort;
+ set => _sort = value ?? throw new ArgumentNullException(nameof(value));
}
- /// <include file='doc\DirectorySearcher.uex' path='docs/doc[@for="DirectorySearcher.Asynchronous"]/*' />
/// <devdoc>
- /// <para>Gets or sets a value indicating whether searches should be carried out in an asynchronous
- /// way.</para>
+ /// Gets or sets a value indicating whether searches should be carried out in an asynchronous
+ /// way.
/// </devdoc>
- [
- DefaultValue(false),
- ]
- public bool Asynchronous
- {
- get
- {
- return _asynchronous;
- }
- set
- {
- _asynchronous = value;
- }
- }
+ [DefaultValue(false)]
+ public bool Asynchronous { get; set; }
- /// <include file='doc\DirectorySearcher.uex' path='docs/doc[@for="DirectorySearcher.Tombstone"]/*' />
/// <devdoc>
- /// <para>Gets or sets a value indicateing whether the search should also return deleted objects that match the search
- /// filter.</para>
+ /// Gets or sets a value indicateing whether the search should also return deleted objects that match the search
+ /// filter.
/// </devdoc>
- [
- DefaultValue(false),
- ]
- public bool Tombstone
- {
- get
- {
- return _tombstone;
- }
- set
- {
- _tombstone = value;
- }
- }
+ [DefaultValue(false)]
+ public bool Tombstone { get; set; }
- /// <include file='doc\DirectorySearcher.uex' path='docs/doc[@for="DirectorySearcher.AttributeScopeQuery"]/*' />
/// <devdoc>
- /// <para>Gets or sets an attribute name to indicate that an attribute-scoped query search should be
- /// performed.</para>
+ /// Gets or sets an attribute name to indicate that an attribute-scoped query search should be
+ /// performed.
/// </devdoc>
[
DefaultValue(""),
@@ -546,10 +415,7 @@ namespace System.DirectoryServices
]
public string AttributeScopeQuery
{
- get
- {
- return _attributeScopeQuery;
- }
+ get => _attributeScopeQuery;
set
{
if (value == null)
@@ -578,21 +444,14 @@ namespace System.DirectoryServices
}
}
- /// <include file='doc\DirectorySearcher.uex' path='docs/doc[@for="DirectorySearcher.DerefAlias"]/*' />
/// <devdoc>
- /// <para>Gets or sets a value to indicate how the aliases of found objects are to be
- /// resolved.</para>
+ /// Gets or sets a value to indicate how the aliases of found objects are to be
+ /// resolved.
/// </devdoc>
- [
- DefaultValue(DereferenceAlias.Never),
- ]
+ [DefaultValue(DereferenceAlias.Never)]
public DereferenceAlias DerefAlias
{
- get
- {
- return _derefAlias;
- }
-
+ get => _derefAlias;
set
{
if (value < DereferenceAlias.Never || value > DereferenceAlias.Always)
@@ -602,20 +461,14 @@ namespace System.DirectoryServices
}
}
- /// <include file='doc\DirectorySearcher.uex' path='docs/doc[@for="DirectorySearcher.SecurityMasks"]/*' />
/// <devdoc>
- /// <para>Gets or sets a value to indicate the search should return security access information for the specified
- /// attributes.</para>
+ /// Gets or sets a value to indicate the search should return security access information for the specified
+ /// attributes.
/// </devdoc>
- [
- DefaultValue(SecurityMasks.None),
- ]
+ [DefaultValue(SecurityMasks.None)]
public SecurityMasks SecurityMasks
{
- get
- {
- return _securityMask;
- }
+ get => _securityMask;
set
{
// make sure the behavior is consistent with native ADSI
@@ -626,20 +479,14 @@ namespace System.DirectoryServices
}
}
- /// <include file='doc\DirectorySearcher.uex' path='docs/doc[@for="DirectorySearcher.ExtendedDn"]/*' />
/// <devdoc>
- /// <para>Gets or sets a value to return extended DNs according to the requested
- /// format.</para>
+ /// Gets or sets a value to return extended DNs according to the requested
+ /// format.
/// </devdoc>
- [
- DefaultValue(ExtendedDN.None),
- ]
+ [DefaultValue(ExtendedDN.None)]
public ExtendedDN ExtendedDN
{
- get
- {
- return _extendedDN;
- }
+ get => _extendedDN;
set
{
if (value < ExtendedDN.None || value > ExtendedDN.Standard)
@@ -649,14 +496,11 @@ namespace System.DirectoryServices
}
}
- /// <include file='doc\DirectorySearcher.uex' path='docs/doc[@for="DirectorySearcher.DirectorySynchronization"]/*' />
/// <devdoc>
- /// <para>Gets or sets a value to indicate a directory synchronization search, which returns all changes since a specified
- /// state.</para>
+ /// Gets or sets a value to indicate a directory synchronization search, which returns all changes since a specified
+ /// state.
/// </devdoc>
- [
- DefaultValue(null),
- ]
+ [DefaultValue(null)]
public DirectorySynchronization DirectorySynchronization
{
get
@@ -689,14 +533,11 @@ namespace System.DirectoryServices
}
}
- /// <include file='doc\DirectorySearcher.uex' path='docs/doc[@for="DirectorySearcher.VirtualListView"]/*' />
/// <devdoc>
- /// <para>Gets or sets a value to indicate the search should use the LDAP virtual list view (VLV)
- /// control.</para>
+ /// Gets or sets a value to indicate the search should use the LDAP virtual list view (VLV)
+ /// control.
/// </devdoc>
- [
- DefaultValue(null),
- ]
+ [DefaultValue(null)]
public DirectoryVirtualListView VirtualListView
{
get
@@ -737,10 +578,9 @@ namespace System.DirectoryServices
}
}
- /// <include file='doc\DirectorySearcher.uex' path='docs/doc[@for="DirectorySearcher.FindOne"]/*' />
/// <devdoc>
- /// <para>Executes the search and returns only the first entry that is found.</para>
- /// </devdoc>
+ /// Executes the search and returns only the first entry that is found.
+ /// </devdoc>
public SearchResult FindOne()
{
DirectorySynchronization tempsync = null;
@@ -776,14 +616,10 @@ namespace System.DirectoryServices
return resultEntry;
}
- /// <include file='doc\DirectorySearcher.uex' path='docs/doc[@for="DirectorySearcher.FindAll"]/*' />
/// <devdoc>
- /// <para> Executes the search and returns a collection of the entries that are found.</para>
- /// </devdoc>
- public SearchResultCollection FindAll()
- {
- return FindAll(true);
- }
+ /// Executes the search and returns a collection of the entries that are found.
+ /// </devdoc>
+ public SearchResultCollection FindAll() => FindAll(true);
private SearchResultCollection FindAll(bool findMoreThanOne)
{
@@ -801,7 +637,7 @@ namespace System.DirectoryServices
UnsafeNativeMethods.IAds adsObject = clonedRoot.AdsObject;
if (!(adsObject is UnsafeNativeMethods.IDirectorySearch))
- throw new NotSupportedException(String.Format(CultureInfo.CurrentCulture, SR.DSSearchUnsupported , SearchRoot.Path));
+ throw new NotSupportedException(SR.Format(SR.DSSearchUnsupported , SearchRoot.Path));
// this is a little bit hacky, but we need to perform a bind here, so we make sure the LDAP connection that we hold has more than
// one reference count, one by SearchResultCollection object, one by DirectorySearcher object. In this way, when user calls
@@ -1163,7 +999,7 @@ namespace System.DirectoryServices
property = "VirtualListView";
break;
}
- throw new InvalidOperationException(String.Format(CultureInfo.CurrentCulture, SR.DSSearchPreferencesNotAccepted , property));
+ throw new InvalidOperationException(SR.Format(SR.DSSearchPreferencesNotAccepted , property));
}
tempPtr = IntPtr.Add(tempPtr, structSize);
diff --git a/src/System.DirectoryServices/src/System/DirectoryServices/DirectoryServicesCOMException.cs b/src/System.DirectoryServices/src/System/DirectoryServices/DirectoryServicesCOMException.cs
index 44df63eb99..fcfa36bdd0 100644
--- a/src/System.DirectoryServices/src/System/DirectoryServices/DirectoryServicesCOMException.cs
+++ b/src/System.DirectoryServices/src/System/DirectoryServices/DirectoryServicesCOMException.cs
@@ -2,25 +2,21 @@
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
+using System.Text;
+using System.Runtime.InteropServices;
+using System.Runtime.Serialization;
+using System.DirectoryServices.Interop;
+
namespace System.DirectoryServices
{
- using System;
- using System.Text;
- using System.Runtime.InteropServices;
- using System.Runtime.Serialization;
- using System.DirectoryServices.Interop;
- using System.Security.Permissions;
- using System.Globalization;
-
- [Serializable]
public class DirectoryServicesCOMException : COMException, ISerializable
{
- private int _extendederror = 0;
- private string _extendedmessage = "";
-
public DirectoryServicesCOMException() { }
+
public DirectoryServicesCOMException(string message) : base(message) { }
+
public DirectoryServicesCOMException(string message, Exception inner) : base(message, inner) { }
+
protected DirectoryServicesCOMException(SerializationInfo info, StreamingContext context) : base(info, context)
{
throw new PlatformNotSupportedException();
@@ -28,25 +24,13 @@ namespace System.DirectoryServices
internal DirectoryServicesCOMException(string extendedMessage, int extendedError, COMException e) : base(e.Message, e.ErrorCode)
{
- _extendederror = extendedError;
- _extendedmessage = extendedMessage;
+ ExtendedError = extendedError;
+ ExtendedErrorMessage = extendedMessage;
}
- public int ExtendedError
- {
- get
- {
- return _extendederror;
- }
- }
+ public int ExtendedError { get; }
- public string ExtendedErrorMessage
- {
- get
- {
- return _extendedmessage;
- }
- }
+ public string ExtendedErrorMessage { get; }
public override void GetObjectData(SerializationInfo serializationInfo, StreamingContext streamingContext)
{
@@ -70,7 +54,7 @@ namespace System.DirectoryServices
}
else
{
- errorMsg = String.Format(CultureInfo.CurrentCulture, SR.DSUnknown , Convert.ToString(hr, 16));
+ errorMsg = SR.Format(SR.DSUnknown , Convert.ToString(hr, 16));
}
return CreateFormattedComException(new COMException(errorMsg, hr));
diff --git a/src/System.DirectoryServices/src/System/DirectoryServices/DirectoryVirtualListViewContext.cs b/src/System.DirectoryServices/src/System/DirectoryServices/DirectoryVirtualListViewContext.cs
index 3ec558bdae..b3c239367b 100644
--- a/src/System.DirectoryServices/src/System/DirectoryServices/DirectoryVirtualListViewContext.cs
+++ b/src/System.DirectoryServices/src/System/DirectoryServices/DirectoryVirtualListViewContext.cs
@@ -6,7 +6,7 @@ namespace System.DirectoryServices
{
public class DirectoryVirtualListViewContext
{
- internal byte[] _context;
+ internal readonly byte[] _context;
public DirectoryVirtualListViewContext() : this(new byte[0])
{
diff --git a/src/System.DirectoryServices/src/System/DirectoryServices/ExtendedDn.cs b/src/System.DirectoryServices/src/System/DirectoryServices/ExtendedDn.cs
index 525bae3788..fca3710c26 100644
--- a/src/System.DirectoryServices/src/System/DirectoryServices/ExtendedDn.cs
+++ b/src/System.DirectoryServices/src/System/DirectoryServices/ExtendedDn.cs
@@ -4,21 +4,13 @@
namespace System.DirectoryServices
{
- /// <include file='doc\ExtendedDN.uex' path='docs/doc[@for="ExtendedDn"]/*' />
/// <devdoc>
- /// <para>
- /// Specifies the possible representations of the distinguished name.
- /// </para>
+ /// Specifies the possible representations of the distinguished name.
/// </devdoc>
public enum ExtendedDN
{
- /// <include file='doc\ExtendedDn.uex' path='docs/doc[@for="ExtendedDn.None"]/*' />
None = -1,
-
- /// <include file='doc\ExtendedDn.uex' path='docs/doc[@for="ExtendedDn.HexString"]/*' />
HexString = 0,
-
- /// <include file='doc\ExtendedDn.uex' path='docs/doc[@for="ExtendedDn.Standard"]/*' />
Standard = 1
}
}
diff --git a/src/System.DirectoryServices/src/System/DirectoryServices/PrivilegedConfigurationManager.cs b/src/System.DirectoryServices/src/System/DirectoryServices/PrivilegedConfigurationManager.cs
deleted file mode 100644
index 03549cc2f7..0000000000
--- a/src/System.DirectoryServices/src/System/DirectoryServices/PrivilegedConfigurationManager.cs
+++ /dev/null
@@ -1,27 +0,0 @@
-// Licensed to the .NET Foundation under one or more agreements.
-// The .NET Foundation licenses this file to you under the MIT license.
-// See the LICENSE file in the project root for more information.
-
-namespace System.Configuration
-{
- using System.Collections.Specialized;
- using System.Security;
- using System.Security.Permissions;
-
- internal static class PrivilegedConfigurationManager
- {
- //internal static ConnectionStringSettingsCollection ConnectionStrings
- //{
- // [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Performance", "CA1811:AvoidUncalledPrivateCode")]
- // get
- // {
- // return ConfigurationManager.ConnectionStrings;
- // }
- //}
-
- //internal static object GetSection(string sectionName)
- //{
- // return ConfigurationManager.GetSection(sectionName);
- //}
- }
-}
diff --git a/src/System.DirectoryServices/src/System/DirectoryServices/PropertyCollection.cs b/src/System.DirectoryServices/src/System/DirectoryServices/PropertyCollection.cs
index c583972899..b125797a73 100644
--- a/src/System.DirectoryServices/src/System/DirectoryServices/PropertyCollection.cs
+++ b/src/System.DirectoryServices/src/System/DirectoryServices/PropertyCollection.cs
@@ -2,24 +2,20 @@
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
+using System.Runtime.InteropServices;
+using System.Collections;
+using System.DirectoryServices.Interop;
+using System.Globalization;
+
namespace System.DirectoryServices
{
- using System;
- using System.Runtime.InteropServices;
- using System.Collections;
- using System.Diagnostics;
- using System.DirectoryServices.Interop;
- using System.Security.Permissions;
- using System.Globalization;
-
- /// <include file='doc\PropertyCollection.uex' path='docs/doc[@for="PropertyCollection"]/*' />
/// <devdoc>
- /// <para>Contains the properties on a <see cref='System.DirectoryServices.DirectoryEntry'/>.</para>
+ /// Contains the properties on a <see cref='System.DirectoryServices.DirectoryEntry'/>.
/// </devdoc>
public class PropertyCollection : IDictionary
{
- private DirectoryEntry _entry;
- internal Hashtable valueTable = null;
+ private readonly DirectoryEntry _entry;
+ internal readonly Hashtable valueTable = null;
internal PropertyCollection(DirectoryEntry entry)
{
@@ -28,9 +24,8 @@ namespace System.DirectoryServices
valueTable = Hashtable.Synchronized(tempTable);
}
- /// <include file='doc\PropertyCollection.uex' path='docs/doc[@for="PropertyCollection.this"]/*' />
/// <devdoc>
- /// <para>Gets the property with the given name.</para>
+ /// Gets the property with the given name.
/// </devdoc>
public PropertyValueCollection this[string propertyName]
{
@@ -51,9 +46,8 @@ namespace System.DirectoryServices
}
}
- /// <include file='doc\PropertyCollection.uex' path='docs/doc[@for="PropertyCollection.Count"]/*' />
/// <devdoc>
- /// <para>Gets the number of properties available on this entry.</para>
+ /// Gets the number of properties available on this entry.
/// </devdoc>
public int Count
{
@@ -70,37 +64,13 @@ namespace System.DirectoryServices
}
}
- /// <include file='doc\PropertyCollection.uex' path='docs/doc[@for="PropertyCollection.PropertyNames"]/*' />
- /// <devdoc>
- /// <para>[To be supplied.]</para>
/// </devdoc>
- public ICollection PropertyNames
- {
- get
- {
- return new KeysCollection(this);
- }
- }
+ public ICollection PropertyNames => new KeysCollection(this);
- /// <include file='doc\PropertyCollection.uex' path='docs/doc[@for="PropertyCollection.Values"]/*' />
- /// <devdoc>
- /// <para>[To be supplied.]</para>
- /// </devdoc>
- public ICollection Values
- {
- get
- {
- return new ValuesCollection(this);
- }
- }
+ public ICollection Values => new ValuesCollection(this);
- /// <include file='doc\PropertyCollection.uex' path='docs/doc[@for="PropertyCollection.Contains"]/*' />
- /// <devdoc>
- /// <para>[To be supplied.]</para>
- /// </devdoc>
public bool Contains(string propertyName)
{
- //entry.FillCache(propertyName);
object var;
int unmanagedResult = _entry.AdsObject.GetEx(propertyName, out var);
if (unmanagedResult != 0)
@@ -119,18 +89,16 @@ namespace System.DirectoryServices
return true;
}
- /// <include file='doc\PropertyCollection.uex' path='docs/doc[@for="PropertyCollection.CopyTo"]/*' />
/// <devdoc>
- /// <para>Copies the elements of this instance into an <see cref='System.Array'/>, starting at a particular index into the array.</para>
+ /// Copies the elements of this instance into an <see cref='System.Array'/>, starting at a particular index into the array.
/// </devdoc>
public void CopyTo(PropertyValueCollection[] array, int index)
{
((ICollection)this).CopyTo((Array)array, index);
}
- /// <include file='doc\PropertyCollection.uex' path='docs/doc[@for="PropertyCollection.GetEnumerator"]/*' />
/// <devdoc>
- /// <para>Returns an enumerator, which can be used to iterate through the collection.</para>
+ /// Returns an enumerator, which can be used to iterate through the collection.
/// </devdoc>
public IDictionaryEnumerator GetEnumerator()
{
@@ -149,108 +117,41 @@ namespace System.DirectoryServices
return new PropertyEnumerator(_entry, entryToUse);
}
- /// <include file='doc\PropertyCollection.uex' path='docs/doc[@for="PropertyCollection.IDictionary.this"]/*' />
- ///<internalonly/>
object IDictionary.this[object key]
{
- get
- {
- return this[(string)key];
- }
-
- set
- {
- throw new NotSupportedException(SR.DSPropertySetSupported);
- }
+ get => this[(string)key];
+ set => throw new NotSupportedException(SR.DSPropertySetSupported);
}
- /// <include file='doc\PropertyCollection.uex' path='docs/doc[@for="PropertyCollection.IDictionary.IsFixedSize"]/*' />
- ///<internalonly/>
- bool IDictionary.IsFixedSize
- {
- get
- {
- return true;
- }
- }
+ bool IDictionary.IsFixedSize => true;
- /// <include file='doc\PropertyCollection.uex' path='docs/doc[@for="PropertyCollection.IDictionary.IsReadOnly"]/*' />
- ///<internalonly/>
- bool IDictionary.IsReadOnly
- {
- get
- {
- return true;
- }
- }
+ bool IDictionary.IsReadOnly => true;
- /// <include file='doc\PropertyCollection.uex' path='docs/doc[@for="PropertyCollection.IDictionary.Keys"]/*' />
- ///<internalonly/>
- ICollection IDictionary.Keys
- {
- get
- {
- return new KeysCollection(this);
- }
- }
+ ICollection IDictionary.Keys => new KeysCollection(this);
- /// <include file='doc\PropertyCollection.uex' path='docs/doc[@for="PropertyCollection.IDictionary.Add"]/*' />
- ///<internalonly/>
void IDictionary.Add(object key, object value)
{
throw new NotSupportedException(SR.DSAddNotSupported);
}
- /// <include file='doc\PropertyCollection.uex' path='docs/doc[@for="PropertyCollection.IDictionary.Clear"]/*' />
- ///<internalonly/>
void IDictionary.Clear()
{
throw new NotSupportedException(SR.DSClearNotSupported);
}
- /// <include file='doc\PropertyCollection.uex' path='docs/doc[@for="PropertyCollection.IDictionary.Contains"]/*' />
- ///<internalonly/>
- bool IDictionary.Contains(object value)
- {
- return this.Contains((string)value);
- }
+ bool IDictionary.Contains(object value) => Contains((string)value);
- /// <include file='doc\PropertyCollection.uex' path='docs/doc[@for="PropertyCollection.IDictionary.Remove"]/*' />
- ///<internalonly/>
void IDictionary.Remove(object key)
{
throw new NotSupportedException(SR.DSRemoveNotSupported);
}
- /// <include file='doc\PropertyCollection.uex' path='docs/doc[@for="PropertyCollection.IEnumerable.GetEnumerator"]/*' />
- ///<internalonly/>
- IEnumerator IEnumerable.GetEnumerator()
- {
- return (IEnumerator)GetEnumerator();
- }
+ IEnumerator IEnumerable.GetEnumerator() => GetEnumerator();
- /// <include file='doc\PropertyCollection.uex' path='docs/doc[@for="PropertyCollection.ICollection.IsSynchronized"]/*' />
- ///<internalonly/>
- bool ICollection.IsSynchronized
- {
- get
- {
- return false;
- }
- }
+ bool ICollection.IsSynchronized => false;
- /// <include file='doc\PropertyCollection.uex' path='docs/doc[@for="PropertyCollection.ICollection.SyncRoot"]/*' />
- ///<internalonly/>
- object ICollection.SyncRoot
- {
- get
- {
- return this;
- }
- }
+ object ICollection.SyncRoot => this;
- /// <include file='doc\PropertyCollection.uex' path='docs/doc[@for="PropertyCollection.ICollection.CopyTo"]/*' />
- ///<internalonly/>
void ICollection.CopyTo(Array array, Int32 index)
{
if (array == null)
@@ -272,39 +173,26 @@ namespace System.DirectoryServices
}
}
- /// <include file='doc\PropertyCollection.uex' path='docs/doc[@for="PropertyCollection.PropertyEnumerator"]/*' />
- ///<internalonly/>
private class PropertyEnumerator : IDictionaryEnumerator, IDisposable
{
private DirectoryEntry _entry; // clone (to be disposed)
private DirectoryEntry _parentEntry; // original entry to pass to PropertyValueCollection
private string _currentPropName = null;
- /// <include file='doc\PropertyCollection.uex' path='docs/doc[@for="PropertyCollection.PropertyEnumerator.PropertyEnumerator"]/*' />
- ///<internalonly/>
public PropertyEnumerator(DirectoryEntry parent, DirectoryEntry clone)
{
_entry = clone;
_parentEntry = parent;
}
- ~PropertyEnumerator()
- {
- Dispose(true); // finalizer is called => Dispose has not been called yet.
- }
+ ~PropertyEnumerator() => Dispose(true);
- /// <include file='doc\PropertyCollection.uex' path='docs/doc[@for="PropertyEnumerator.Dispose"]/*' />
- /// <devdoc>
- /// </devdoc>
public void Dispose()
{
Dispose(true);
GC.SuppressFinalize(this);
}
- /// <include file='doc\PropertyCollection.uex' path='docs/doc[@for="PropertyEnumerator.Dispose1"]/*' />
- /// <devdoc>
- /// </devdoc>
protected virtual void Dispose(bool disposing)
{
if (disposing)
@@ -313,18 +201,8 @@ namespace System.DirectoryServices
}
}
- /// <include file='doc\PropertyCollection.uex' path='docs/doc[@for="PropertyCollection.PropertyEnumerator.Current"]/*' />
- ///<internalonly/>
- public object Current
- {
- get
- {
- return Entry.Value;
- }
- }
+ public object Current => Entry.Value;
- /// <include file='doc\PropertyCollection.uex' path='docs/doc[@for="PropertyCollection.PropertyEnumerator.Entry"]/*' />
- ///<internalonly/>
public DictionaryEntry Entry
{
get
@@ -336,28 +214,10 @@ namespace System.DirectoryServices
}
}
- /// <include file='doc\PropertyCollection.uex' path='docs/doc[@for="PropertyCollection.PropertyEnumerator.Key"]/*' />
- ///<internalonly/>
- public object Key
- {
- get
- {
- return Entry.Key;
- }
- }
+ public object Key => Entry.Key;
- /// <include file='doc\PropertyCollection.uex' path='docs/doc[@for="PropertyCollection.PropertyEnumerator.Value"]/*' />
- ///<internalonly/>
- public object Value
- {
- get
- {
- return Entry.Value;
- }
- }
+ public object Value => Entry.Value;
- /// <include file='doc\PropertyCollection.uex' path='docs/doc[@for="PropertyCollection.PropertyEnumerator.MoveNext"]/*' />
- ///<internalonly/>
public bool MoveNext()
{
object prop;
@@ -387,8 +247,6 @@ namespace System.DirectoryServices
}
}
- /// <include file='doc\PropertyCollection.uex' path='docs/doc[@for="PropertyCollection.PropertyEnumerator.Reset"]/*' />
- ///<internalonly/>
public void Reset()
{
((UnsafeNativeMethods.IAdsPropertyList)_entry.AdsObject).Reset();
@@ -396,88 +254,38 @@ namespace System.DirectoryServices
}
}
- /// <include file='doc\PropertyCollection.uex' path='docs/doc[@for="PropertyCollection.ValuesCollection"]/*' />
- ///<internalonly/>
private class ValuesCollection : ICollection
{
protected PropertyCollection props;
- /// <include file='doc\PropertyCollection.uex' path='docs/doc[@for="PropertyCollection.ValuesCollection.ValuesCollection"]/*' />
- ///<internalonly/>
public ValuesCollection(PropertyCollection props)
{
this.props = props;
}
- /// <include file='doc\PropertyCollection.uex' path='docs/doc[@for="PropertyCollection.ValuesCollection.Count"]/*' />
- ///<internalonly/>
- public int Count
- {
- get
- {
- return props.Count;
- }
- }
+ public int Count => props.Count;
- /// <include file='doc\PropertyCollection.uex' path='docs/doc[@for="PropertyCollection.ValuesCollection.IsReadOnly"]/*' />
- ///<internalonly/>
- public bool IsReadOnly
- {
- get
- {
- return true;
- }
- }
+ public bool IsReadOnly => true;
- /// <include file='doc\PropertyCollection.uex' path='docs/doc[@for="PropertyCollection.ValuesCollection.IsSynchronized"]/*' />
- ///<internalonly/>
- public bool IsSynchronized
- {
- get
- {
- return false;
- }
- }
+ public bool IsSynchronized => false;
- /// <include file='doc\PropertyCollection.uex' path='docs/doc[@for="PropertyCollection.ValuesCollection.SyncRoot"]/*' />
- ///<internalonly/>
- public object SyncRoot
- {
- get
- {
- return ((ICollection)props).SyncRoot;
- }
- }
+ public object SyncRoot => ((ICollection)props).SyncRoot;
- /// <include file='doc\PropertyCollection.uex' path='docs/doc[@for="PropertyCollection.ValuesCollection.CopyTo"]/*' />
- ///<internalonly/>
public void CopyTo(Array array, int index)
{
foreach (object value in this)
array.SetValue(value, index++);
}
- /// <include file='doc\PropertyCollection.uex' path='docs/doc[@for="PropertyCollection.ValuesCollection.GetEnumerator"]/*' />
- ///<internalonly/>
- public virtual IEnumerator GetEnumerator()
- {
- return new ValuesEnumerator(props);
- }
+ public virtual IEnumerator GetEnumerator() => new ValuesEnumerator(props);
}
- /// <include file='doc\PropertyCollection.uex' path='docs/doc[@for="PropertyCollection.KeysCollection"]/*' />
- ///<internalonly/>
private class KeysCollection : ValuesCollection
{
- /// <include file='doc\PropertyCollection.uex' path='docs/doc[@for="PropertyCollection.KeysCollection.KeysCollection"]/*' />
- ///<internalonly/>
- public KeysCollection(PropertyCollection props)
- : base(props)
+ public KeysCollection(PropertyCollection props) : base(props)
{
}
- /// <include file='doc\PropertyCollection.uex' path='docs/doc[@for="PropertyCollection.KeysCollection.GetEnumerator"]/*' />
- ///<internalonly/>
public override IEnumerator GetEnumerator()
{
props._entry.FillCache("");
@@ -485,22 +293,16 @@ namespace System.DirectoryServices
}
}
- /// <include file='doc\PropertyCollection.uex' path='docs/doc[@for="PropertyCollection.ValuesEnumerator"]/*' />
- ///<internalonly/>
private class ValuesEnumerator : IEnumerator
{
private int _currentIndex = -1;
protected PropertyCollection propCollection;
- /// <include file='doc\PropertyCollection.uex' path='docs/doc[@for="PropertyCollection.ValuesEnumerator.ValuesEnumerator"]/*' />
- ///<internalonly/>
public ValuesEnumerator(PropertyCollection propCollection)
{
this.propCollection = propCollection;
}
- /// <include file='doc\PropertyCollection.uex' path='docs/doc[@for="PropertyCollection.ValuesEnumerator.CurrentIndex"]/*' />
- ///<internalonly/>
protected int CurrentIndex
{
get
@@ -511,8 +313,6 @@ namespace System.DirectoryServices
}
}
- /// <include file='doc\PropertyCollection.uex' path='docs/doc[@for="PropertyCollection.ValuesEnumerator.Current"]/*' />
- ///<internalonly/>
public virtual object Current
{
get
@@ -522,8 +322,6 @@ namespace System.DirectoryServices
}
}
- /// <include file='doc\PropertyCollection.uex' path='docs/doc[@for="PropertyCollection.ValuesEnumerator.MoveNext"]/*' />
- ///<internalonly/>
public bool MoveNext()
{
_currentIndex++;
@@ -536,27 +334,15 @@ namespace System.DirectoryServices
return true;
}
- /// <include file='doc\PropertyCollection.uex' path='docs/doc[@for="PropertyCollection.ValuesEnumerator.Reset"]/*' />
- ///<internalonly/>
- public void Reset()
- {
- _currentIndex = -1;
- }
+ public void Reset() => _currentIndex = -1;
}
- /// <include file='doc\PropertyCollection.uex' path='docs/doc[@for="PropertyCollection.KeysEnumerator"]/*' />
- ///<internalonly/>
private class KeysEnumerator : ValuesEnumerator
{
- /// <include file='doc\PropertyCollection.uex' path='docs/doc[@for="PropertyCollection.KeysEnumerator.KeysEnumerator"]/*' />
- ///<internalonly/>
- public KeysEnumerator(PropertyCollection collection)
- : base(collection)
+ public KeysEnumerator(PropertyCollection collection) : base(collection)
{
}
- /// <include file='doc\PropertyCollection.uex' path='docs/doc[@for="PropertyCollection.KeysEnumerator.Current"]/*' />
- ///<internalonly/>
public override object Current
{
get
@@ -569,4 +355,3 @@ namespace System.DirectoryServices
}
}
}
-
diff --git a/src/System.DirectoryServices/src/System/DirectoryServices/PropertyValueCollection.cs b/src/System.DirectoryServices/src/System/DirectoryServices/PropertyValueCollection.cs
index 54a2b71724..f28d75c0cd 100644
--- a/src/System.DirectoryServices/src/System/DirectoryServices/PropertyValueCollection.cs
+++ b/src/System.DirectoryServices/src/System/DirectoryServices/PropertyValueCollection.cs
@@ -2,18 +2,13 @@
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
+using System.Collections;
+using System.DirectoryServices.Interop;
+
namespace System.DirectoryServices
{
- using System;
- using System.Runtime.InteropServices;
- using System.Collections;
- using System.Diagnostics;
- using System.DirectoryServices.Interop;
- using System.Security.Permissions;
-
- /// <include file='doc\PropertyValueCollection.uex' path='docs/doc[@for="PropertyValueCollection"]/*' />
/// <devdoc>
- /// <para>Holds a collection of values for a multi-valued property.</para>
+ /// Holds a collection of values for a multi-valued property.
/// </devdoc>
public class PropertyValueCollection : CollectionBase
{
@@ -25,17 +20,16 @@ namespace System.DirectoryServices
None = 3
}
- private DirectoryEntry _entry;
- private string _propertyName;
+ private readonly DirectoryEntry _entry;
private UpdateType _updateType = UpdateType.None;
- private ArrayList _changeList = null;
- private bool _allowMultipleChange = false;
- private bool _needNewBehavior = false;
+ private readonly ArrayList _changeList = null;
+ private readonly bool _allowMultipleChange = false;
+ private readonly bool _needNewBehavior = false;
internal PropertyValueCollection(DirectoryEntry entry, string propertyName)
{
_entry = entry;
- _propertyName = propertyName;
+ PropertyName = propertyName;
PopulateList();
ArrayList tempList = new ArrayList();
_changeList = ArrayList.Synchronized(tempList);
@@ -53,16 +47,9 @@ namespace System.DirectoryServices
}
}
- /// <include file='doc\PropertyValueCollection.uex' path='docs/doc[@for="PropertyValueCollection.this"]/*' />
- /// <devdoc>
- /// <para>[To be supplied.]</para>
- /// </devdoc>
public object this[int index]
{
- get
- {
- return List[index];
- }
+ get => List[index];
set
{
if (_needNewBehavior && !_allowMultipleChange)
@@ -74,22 +61,8 @@ namespace System.DirectoryServices
}
}
- /// <include file='doc\PropertyValueCollection.uex' path='docs/doc[@for="PropertyValueCollection.PropertyName"]/*' />
- /// <devdoc>
- /// <para>[To be supplied.]</para>
- /// </devdoc>
- public string PropertyName
- {
- get
- {
- return _propertyName;
- }
- }
+ public string PropertyName { get; }
- /// <include file='doc\PropertyValueCollection.uex' path='docs/doc[@for="PropertyValueCollection.Value"]/*' />
- /// <devdoc>
- /// <para>[To be supplied.]</para>
- /// </devdoc>
public object Value
{
get
@@ -146,7 +119,7 @@ namespace System.DirectoryServices
object[] allValues = new object[_changeList.Count];
_changeList.CopyTo(allValues, 0);
- _entry.AdsObject.PutEx((int)AdsPropertyOperation.Update, _propertyName, allValues);
+ _entry.AdsObject.PutEx((int)AdsPropertyOperation.Update, PropertyName, allValues);
_entry.CommitIfNotCaching();
@@ -155,18 +128,13 @@ namespace System.DirectoryServices
}
}
- /// <include file='doc\PropertyValueCollection.uex' path='docs/doc[@for="PropertyValueCollection.Add"]/*' />
/// <devdoc>
- /// <para>Appends the value to the set of values for this property.</para>
+ /// Appends the value to the set of values for this property.
/// </devdoc>
- public int Add(object value)
- {
- return List.Add(value);
- }
+ public int Add(object value) => List.Add(value);
- /// <include file='doc\PropertyValueCollection.uex' path='docs/doc[@for="PropertyValueCollection.AddRange"]/*' />
/// <devdoc>
- /// <para>Appends the values to the set of values for this property.</para>
+ /// Appends the values to the set of values for this property.
/// </devdoc>
public void AddRange(object[] value)
{
@@ -180,9 +148,8 @@ namespace System.DirectoryServices
}
}
- /// <include file='doc\PropertyValueCollection.uex' path='docs/doc[@for="PropertyValueCollection.AddRange1"]/*' />
/// <devdoc>
- /// <para>Appends the values to the set of values for this property.</para>
+ /// Appends the values to the set of values for this property.
/// </devdoc>
public void AddRange(PropertyValueCollection value)
{
@@ -197,46 +164,21 @@ namespace System.DirectoryServices
}
}
- /// <include file='doc\PropertyValueCollection.uex' path='docs/doc[@for="PropertyValueCollection.Contains"]/*' />
- /// <devdoc>
- /// <para>[To be supplied.]</para>
- /// </devdoc>
- public bool Contains(object value)
- {
- return List.Contains(value);
- }
+ public bool Contains(object value) => List.Contains(value);
- /// <include file='doc\PropertyValueCollection.uex' path='docs/doc[@for="PropertyValueCollection.CopyTo"]/*' />
/// <devdoc>
- /// <para>Copies the elements of this instance into an <see cref='System.Array'/>,
- /// starting at a particular index
- /// into the given <paramref name="array"/>.</para>
+ /// Copies the elements of this instance into an <see cref='System.Array'/>,
+ /// starting at a particular index into the given <paramref name="array"/>.
/// </devdoc>
public void CopyTo(object[] array, int index)
{
List.CopyTo(array, index);
}
- /// <include file='doc\PropertyValueCollection.uex' path='docs/doc[@for="PropertyValueCollection.IndexOf"]/*' />
- /// <devdoc>
- /// <para>[To be supplied.]</para>
- /// </devdoc>
- public int IndexOf(object value)
- {
- return List.IndexOf(value);
- }
+ public int IndexOf(object value) => List.IndexOf(value);
- /// <include file='doc\PropertyValueCollection.uex' path='docs/doc[@for="PropertyValueCollection.Insert"]/*' />
- /// <devdoc>
- /// <para>[To be supplied.]</para>
- /// </devdoc>
- public void Insert(int index, object value)
- {
- List.Insert(index, value);
- }
+ public void Insert(int index, object value) => List.Insert(index, value);
- /// <include file='doc\PropertyValueCollection.uex' path='docs/doc[@for="PropertyValueCollection.PopulateList"]/*' />
- ///<internalonly/>
private void PopulateList()
{
//No need to fill the cache here, when GetEx is calles, an implicit
@@ -244,7 +186,7 @@ namespace System.DirectoryServices
//cache. Which is exactly what FillCache does.
//entry.FillCache(propertyName);
object var;
- int unmanagedResult = _entry.AdsObject.GetEx(_propertyName, out var);
+ int unmanagedResult = _entry.AdsObject.GetEx(PropertyName, out var);
if (unmanagedResult != 0)
{
// property not found (IIS provider returns 0x80005006, other provides return 0x8000500D).
@@ -263,9 +205,8 @@ namespace System.DirectoryServices
InnerList.Add(var);
}
- /// <include file='doc\PropertyValueCollection.uex' path='docs/doc[@for="PropertyValueCollection.Remove"]/*' />
/// <devdoc>
- /// <para>Removes the value from the collection.</para>
+ /// Removes the value from the collection.
/// </devdoc>
public void Remove(object value)
{
@@ -286,15 +227,13 @@ namespace System.DirectoryServices
List.Remove(value);
}
- /// <include file='doc\PropertyValueCollection.uex' path='docs/doc[@for="PropertyValueCollection.OnClear"]/*' />
- ///<internalonly/>
protected override void OnClearComplete()
{
if (_needNewBehavior && !_allowMultipleChange && _updateType != UpdateType.None && _updateType != UpdateType.Update)
{
throw new InvalidOperationException(SR.DSPropertyValueSupportOneOperation);
}
- _entry.AdsObject.PutEx((int)AdsPropertyOperation.Clear, _propertyName, null);
+ _entry.AdsObject.PutEx((int)AdsPropertyOperation.Clear, PropertyName, null);
_updateType = UpdateType.Update;
try
{
@@ -309,8 +248,6 @@ namespace System.DirectoryServices
}
}
- /// <include file='doc\PropertyValueCollection.uex' path='docs/doc[@for="PropertyValueCollection.OnInsert"]/*' />
- ///<internalonly/>
protected override void OnInsertComplete(int index, object value)
{
if (_needNewBehavior)
@@ -326,26 +263,24 @@ namespace System.DirectoryServices
object[] allValues = new object[_changeList.Count];
_changeList.CopyTo(allValues, 0);
- _entry.AdsObject.PutEx((int)AdsPropertyOperation.Append, _propertyName, allValues);
+ _entry.AdsObject.PutEx((int)AdsPropertyOperation.Append, PropertyName, allValues);
_updateType = UpdateType.Add;
}
else
{
- _entry.AdsObject.PutEx((int)AdsPropertyOperation.Append, _propertyName, new object[] { value });
+ _entry.AdsObject.PutEx((int)AdsPropertyOperation.Append, PropertyName, new object[] { value });
}
}
else
{
object[] allValues = new object[InnerList.Count];
InnerList.CopyTo(allValues, 0);
- _entry.AdsObject.PutEx((int)AdsPropertyOperation.Update, _propertyName, allValues);
+ _entry.AdsObject.PutEx((int)AdsPropertyOperation.Update, PropertyName, allValues);
}
_entry.CommitIfNotCaching();
}
- /// <include file='doc\PropertyValueCollection.uex' path='docs/doc[@for="PropertyValueCollection.OnRemove"]/*' />
- ///<internalonly/>
protected override void OnRemoveComplete(int index, object value)
{
if (_needNewBehavior)
@@ -360,46 +295,44 @@ namespace System.DirectoryServices
_changeList.Add(value);
object[] allValues = new object[_changeList.Count];
_changeList.CopyTo(allValues, 0);
- _entry.AdsObject.PutEx((int)AdsPropertyOperation.Delete, _propertyName, allValues);
+ _entry.AdsObject.PutEx((int)AdsPropertyOperation.Delete, PropertyName, allValues);
_updateType = UpdateType.Delete;
}
else
{
- _entry.AdsObject.PutEx((int)AdsPropertyOperation.Delete, _propertyName, new object[] { value });
+ _entry.AdsObject.PutEx((int)AdsPropertyOperation.Delete, PropertyName, new object[] { value });
}
}
else
{
object[] allValues = new object[InnerList.Count];
InnerList.CopyTo(allValues, 0);
- _entry.AdsObject.PutEx((int)AdsPropertyOperation.Update, _propertyName, allValues);
+ _entry.AdsObject.PutEx((int)AdsPropertyOperation.Update, PropertyName, allValues);
}
_entry.CommitIfNotCaching();
}
- /// <include file='doc\PropertyValueCollection.uex' path='docs/doc[@for="PropertyValueCollection.OnSet"]/*' />
- ///<internalonly/>
protected override void OnSetComplete(int index, object oldValue, object newValue)
{
// no need to consider the not allowing accumulative change case as it does not support Set
if (Count <= 1)
{
- _entry.AdsObject.Put(_propertyName, newValue);
+ _entry.AdsObject.Put(PropertyName, newValue);
}
else
{
if (_needNewBehavior)
{
- _entry.AdsObject.PutEx((int)AdsPropertyOperation.Delete, _propertyName, new object[] { oldValue });
- _entry.AdsObject.PutEx((int)AdsPropertyOperation.Append, _propertyName, new object[] { newValue });
+ _entry.AdsObject.PutEx((int)AdsPropertyOperation.Delete, PropertyName, new object[] { oldValue });
+ _entry.AdsObject.PutEx((int)AdsPropertyOperation.Append, PropertyName, new object[] { newValue });
}
else
{
object[] allValues = new object[InnerList.Count];
InnerList.CopyTo(allValues, 0);
- _entry.AdsObject.PutEx((int)AdsPropertyOperation.Update, _propertyName, allValues);
+ _entry.AdsObject.PutEx((int)AdsPropertyOperation.Update, PropertyName, allValues);
}
}
diff --git a/src/System.DirectoryServices/src/System/DirectoryServices/ReferalChasingOption.cs b/src/System.DirectoryServices/src/System/DirectoryServices/ReferalChasingOption.cs
index b9db5bf981..1457fc836f 100644
--- a/src/System.DirectoryServices/src/System/DirectoryServices/ReferalChasingOption.cs
+++ b/src/System.DirectoryServices/src/System/DirectoryServices/ReferalChasingOption.cs
@@ -4,33 +4,31 @@
namespace System.DirectoryServices
{
- /// <include file='doc\ReferalChasingOption.uex' path='docs/doc[@for="ReferralChasingOption"]/*' />
/// <devdoc>
- /// <para>Specifies if and how referral chasing is pursued.</para>
+ /// Specifies if and how referral chasing is pursued.
/// </devdoc>
public enum ReferralChasingOption
{
- /// <include file='doc\ReferalChasingOption.uex' path='docs/doc[@for="ReferralChasingOption.None"]/*' />
/// <devdoc>
- /// <para> Never chase the referred-to server. Setthing this option
- /// prevents a client from contacting other servers in a referral process.</para>
+ /// Never chase the referred-to server. Setthing this option
+ /// prevents a client from contacting other servers in a referral process.
/// </devdoc>
None = 0,
- /// <include file='doc\ReferalChasingOption.uex' path='docs/doc[@for="ReferralChasingOption.Subordinate"]/*' />
+
/// <devdoc>
- /// <para>Chase only subordinate referrals which are a subordinate naming context in a
- /// directory tree. The ADSI LDAP provider always turns off this flag for paged
- /// searches.</para>
+ /// Chase only subordinate referrals which are a subordinate naming context in a
+ /// directory tree. The ADSI LDAP provider always turns off this flag for paged
+ /// searches.
/// </devdoc>
Subordinate = 0x20,
- /// <include file='doc\ReferalChasingOption.uex' path='docs/doc[@for="ReferralChasingOption.External"]/*' />
+
/// <devdoc>
- /// <para>Chase external referrals.</para>
+ /// Chase external referrals.
/// </devdoc>
External = 0x40,
- /// <include file='doc\ReferalChasingOption.uex' path='docs/doc[@for="ReferralChasingOption.All"]/*' />
+
/// <devdoc>
- /// <para>Chase referrals of either the subordinate or external type.</para>
+ /// Chase referrals of either the subordinate or external type.
/// </devdoc>
All = Subordinate | External
}
diff --git a/src/System.DirectoryServices/src/System/DirectoryServices/ResultPropertyCollection.cs b/src/System.DirectoryServices/src/System/DirectoryServices/ResultPropertyCollection.cs
index 2edf1a4cd9..7e93bb160b 100644
--- a/src/System.DirectoryServices/src/System/DirectoryServices/ResultPropertyCollection.cs
+++ b/src/System.DirectoryServices/src/System/DirectoryServices/ResultPropertyCollection.cs
@@ -2,18 +2,13 @@
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
+using System.Collections;
+using System.Globalization;
+
namespace System.DirectoryServices
{
- using System;
- using System.Runtime.InteropServices;
- using System.Collections;
- using System.Diagnostics;
- using System.Security.Permissions;
- using System.Globalization;
-
- /// <include file='doc\ResultPropertyCollection.uex' path='docs/doc[@for="ResultPropertyCollection"]/*' />
/// <devdoc>
- /// <para>Contains the properties on a <see cref='System.DirectoryServices.SearchResult'/>.</para>
+ /// Contains the properties on a <see cref='System.DirectoryServices.SearchResult'/>.
/// </devdoc>
public class ResultPropertyCollection : DictionaryBase
{
@@ -21,9 +16,8 @@ namespace System.DirectoryServices
{
}
- /// <include file='doc\ResultPropertyCollection.uex' path='docs/doc[@for="ResultPropertyCollection.this"]/*' />
/// <devdoc>
- /// <para>Gets the property with the given name.</para>
+ /// Gets the property with the given name.
/// </devdoc>
public ResultPropertyValueCollection this[string name]
{
@@ -41,46 +35,21 @@ namespace System.DirectoryServices
}
}
- /// <include file='doc\ResultPropertyCollection.uex' path='docs/doc[@for="ResultPropertyCollection.PropertyNames"]/*' />
- /// <devdoc>
- /// <para>[To be supplied.]</para>
- /// </devdoc>
- public ICollection PropertyNames
- {
- get { return Dictionary.Keys; }
- }
+ public ICollection PropertyNames => Dictionary.Keys;
- /// <include file='doc\ResultPropertyCollection.uex' path='docs/doc[@for="ResultPropertyCollection.Values"]/*' />
- /// <devdoc>
- /// <para>[To be supplied.]</para>
- /// </devdoc>
- public ICollection Values
- {
- get
- {
- return Dictionary.Values;
- }
- }
+ public ICollection Values => Dictionary.Values;
internal void Add(string name, ResultPropertyValueCollection value)
{
Dictionary.Add(name.ToLower(CultureInfo.InvariantCulture), value);
}
- /// <include file='doc\ResultPropertyCollection.uex' path='docs/doc[@for="ResultPropertyCollection.Contains"]/*' />
- /// <devdoc>
- /// <para>[To be supplied.]</para>
- /// </devdoc>
public bool Contains(string propertyName)
{
object objectName = propertyName.ToLower(CultureInfo.InvariantCulture);
return Dictionary.Contains(objectName);
}
- /// <include file='doc\ResultPropertyCollection.uex' path='docs/doc[@for="ResultPropertyCollection.CopyTo"]/*' />
- /// <devdoc>
- /// <para>[To be supplied.]</para>
- /// </devdoc>
public void CopyTo(ResultPropertyValueCollection[] array, int index)
{
Dictionary.Values.CopyTo((Array)array, index);
diff --git a/src/System.DirectoryServices/src/System/DirectoryServices/ResultPropertyValueCollection.cs b/src/System.DirectoryServices/src/System/DirectoryServices/ResultPropertyValueCollection.cs
index 4a729b848a..62e7b61650 100644
--- a/src/System.DirectoryServices/src/System/DirectoryServices/ResultPropertyValueCollection.cs
+++ b/src/System.DirectoryServices/src/System/DirectoryServices/ResultPropertyValueCollection.cs
@@ -2,31 +2,20 @@
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
+using System.Collections;
+
namespace System.DirectoryServices
{
- using System;
- using System.Runtime.InteropServices;
- using System.Collections;
- using System.Diagnostics;
-
- /// <include file='doc\ResultPropertyValueCollection.uex' path='docs/doc[@for="ResultPropertyValueCollection"]/*' />
/// <devdoc>
- /// <para>Specifies a collection of values for a multi-valued property.</para>
+ /// Specifies a collection of values for a multi-valued property.
/// </devdoc>
public class ResultPropertyValueCollection : ReadOnlyCollectionBase
{
internal ResultPropertyValueCollection(object[] values)
{
- if (values == null)
- values = new object[0];
-
- InnerList.AddRange(values);
+ InnerList.AddRange(values ?? Array.Empty<object>());
}
- /// <include file='doc\ResultPropertyValueCollection.uex' path='docs/doc[@for="ResultPropertyValueCollection.this"]/*' />
- /// <devdoc>
- /// <para>[To be supplied.]</para>
- /// </devdoc>
public object this[int index]
{
get
@@ -39,31 +28,10 @@ namespace System.DirectoryServices
}
}
- /// <include file='doc\ResultPropertyValueCollection.uex' path='docs/doc[@for="ResultPropertyValueCollection.Contains"]/*' />
- /// <devdoc>
- /// <para>[To be supplied.]</para>
- /// </devdoc>
- public bool Contains(object value)
- {
- return InnerList.Contains(value);
- }
+ public bool Contains(object value) => InnerList.Contains(value);
- /// <include file='doc\ResultPropertyValueCollection.uex' path='docs/doc[@for="ResultPropertyValueCollection.IndexOf"]/*' />
- /// <devdoc>
- /// <para>[To be supplied.]</para>
- /// </devdoc>
- public int IndexOf(object value)
- {
- return InnerList.IndexOf(value);
- }
+ public int IndexOf(object value) => InnerList.IndexOf(value);
- /// <include file='doc\ResultPropertyValueCollection.uex' path='docs/doc[@for="ResultPropertyValueCollection.CopyTo"]/*' />
- /// <devdoc>
- /// <para>[To be supplied.]</para>
- /// </devdoc>
- public void CopyTo(object[] values, int index)
- {
- InnerList.CopyTo(values, index);
- }
+ public void CopyTo(object[] values, int index) => InnerList.CopyTo(values, index);
}
}
diff --git a/src/System.DirectoryServices/src/System/DirectoryServices/SchemaNameCollection.cs b/src/System.DirectoryServices/src/System/DirectoryServices/SchemaNameCollection.cs
index 6cc8708e3a..138da5f2ec 100644
--- a/src/System.DirectoryServices/src/System/DirectoryServices/SchemaNameCollection.cs
+++ b/src/System.DirectoryServices/src/System/DirectoryServices/SchemaNameCollection.cs
@@ -2,22 +2,18 @@
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
+using System.Collections;
+using System.DirectoryServices.Interop;
+
namespace System.DirectoryServices
{
- using System;
- using System.Runtime.InteropServices;
- using System.Collections;
- using System.Diagnostics;
- using System.DirectoryServices.Interop;
-
- /// <include file='doc\SchemaNameCollection.uex' path='docs/doc[@for="SchemaNameCollection"]/*' />
/// <devdoc>
- /// <para>Contains a list of schema names used for the <see cref='System.DirectoryServices.DirectoryEntries.SchemaFilter'/> property of a <see cref='System.DirectoryServices.DirectoryEntries'/>.</para>
+ /// Contains a list of schema names used for the <see cref='System.DirectoryServices.DirectoryEntries.SchemaFilter'/> property of a <see cref='System.DirectoryServices.DirectoryEntries'/>.
/// </devdoc>
public class SchemaNameCollection : IList
{
- private VariantPropGetter _propGetter;
- private VariantPropSetter _propSetter;
+ private readonly VariantPropGetter _propGetter;
+ private readonly VariantPropSetter _propSetter;
internal SchemaNameCollection(VariantPropGetter propGetter, VariantPropSetter propSetter)
{
@@ -25,11 +21,9 @@ namespace System.DirectoryServices
_propSetter = propSetter;
}
- /// <include file='doc\SchemaNameCollection.uex' path='docs/doc[@for="SchemaNameCollection.this"]/*' />
/// <devdoc>
- /// <para>Gets or sets the object
- /// at the given index.</para>
- /// </devdoc>
+ /// Gets or sets the object at the given index.
+ /// </devdoc>
public string this[int index]
{
get
@@ -45,11 +39,8 @@ namespace System.DirectoryServices
}
}
- /// <include file='doc\SchemaNameCollection.uex' path='docs/doc[@for="SchemaNameCollection.Count"]/*' />
/// <devdoc>
- /// <para>
- /// Gets the number of objects available on this entry.
- /// </para>
+ /// Gets the number of objects available on this entry.
/// </devdoc>
public int Count
{
@@ -60,12 +51,8 @@ namespace System.DirectoryServices
}
}
- /// <include file='doc\SchemaNameCollection.uex' path='docs/doc[@for="SchemaNameCollection.Add"]/*' />
/// <devdoc>
- /// <para>
- /// Appends the value to the
- /// collection.
- /// </para>
+ /// Appends the value to the collection.
/// </devdoc>
public int Add(string value)
{
@@ -78,11 +65,8 @@ namespace System.DirectoryServices
return newValues.Length - 1;
}
- /// <include file='doc\SchemaNameCollection.uex' path='docs/doc[@for="SchemaNameCollection.AddRange"]/*' />
/// <devdoc>
- /// <para>
- /// Appends the values to the collection.
- /// </para>
+ /// Appends the values to the collection.
/// </devdoc>
public void AddRange(string[] value)
{
@@ -99,10 +83,6 @@ namespace System.DirectoryServices
_propSetter(newValues);
}
- /// <include file='doc\SchemaNameCollection.uex' path='docs/doc[@for="SchemaNameCollection.AddRange1"]/*' />
- /// <devdoc>
- /// <para>[To be supplied.]</para>
- /// </devdoc>
public void AddRange(SchemaNameCollection value)
{
if (value == null)
@@ -118,11 +98,8 @@ namespace System.DirectoryServices
_propSetter(newValues);
}
- /// <include file='doc\SchemaNameCollection.uex' path='docs/doc[@for="SchemaNameCollection.Clear"]/*' />
/// <devdoc>
- /// <para>
- /// Removes all items from the collection.
- /// </para>
+ /// Removes all items from the collection.
/// </devdoc>
public void Clear()
{
@@ -130,31 +107,17 @@ namespace System.DirectoryServices
_propSetter(newValues);
}
- /// <include file='doc\SchemaNameCollection.uex' path='docs/doc[@for="SchemaNameCollection.Contains"]/*' />
/// <devdoc>
- /// <para>
- /// Determines if the collection contains a specific value.
- /// </para>
+ /// Determines if the collection contains a specific value.
/// </devdoc>
- public bool Contains(string value)
- {
- return IndexOf(value) != -1;
- }
+ public bool Contains(string value) => IndexOf(value) != -1;
- /// <include file='doc\SchemaNameCollection.uex' path='docs/doc[@for="SchemaNameCollection.CopyTo"]/*' />
- /// <devdoc>
- /// <para>[To be supplied.]</para>
- /// </devdoc>
public void CopyTo(String[] stringArray, int index)
{
object[] values = GetValue();
values.CopyTo(stringArray, index);
}
- /// <include file='doc\SchemaNameCollection.uex' path='docs/doc[@for="SchemaNameCollection.GetEnumerator"]/*' />
- /// <devdoc>
- /// <para>[To be supplied.]</para>
- /// </devdoc>
public IEnumerator GetEnumerator()
{
object[] values = GetValue();
@@ -170,11 +133,8 @@ namespace System.DirectoryServices
return (object[])value;
}
- /// <include file='doc\SchemaNameCollection.uex' path='docs/doc[@for="SchemaNameCollection.IndexOf"]/*' />
/// <devdoc>
- /// <para>
- /// Determines the index of a specific item in the collection.
- /// </para>
+ /// Determines the index of a specific item in the collection.
/// </devdoc>
public int IndexOf(string value)
{
@@ -187,9 +147,8 @@ namespace System.DirectoryServices
return -1;
}
- /// <include file='doc\SchemaNameCollection.uex' path='docs/doc[@for="SchemaNameCollection.Insert"]/*' />
/// <devdoc>
- /// <para>Inserts an item at the specified position in the collection.</para>
+ /// nserts an item at the specified position in the collection.
/// </devdoc>
public void Insert(int index, string value)
{
@@ -198,9 +157,8 @@ namespace System.DirectoryServices
_propSetter(tmpList.ToArray());
}
- /// <include file='doc\SchemaNameCollection.uex' path='docs/doc[@for="SchemaNameCollection.Remove"]/*' />
/// <devdoc>
- /// <para>Removes an item from the collection.</para>
+ /// Removes an item from the collection.
/// </devdoc>
public void Remove(string value)
{
@@ -209,10 +167,8 @@ namespace System.DirectoryServices
RemoveAt(index);
}
- /// <include file='doc\SchemaNameCollection.uex' path='docs/doc[@for="SchemaNameCollection.RemoveAt"]/*' />
/// <devdoc>
- /// <para>Removes the
- /// item at the specified index from the collection.</para>
+ /// Removes the item at the specified index from the collection.
/// </devdoc>
public void RemoveAt(int index)
{
@@ -228,102 +184,35 @@ namespace System.DirectoryServices
_propSetter(newValues);
}
- /// <include file='doc\SchemaNameCollection.uex' path='docs/doc[@for="SchemaNameCollection.IList.IsReadOnly"]/*' />
- /// <internalonly/>
- bool IList.IsReadOnly
- {
- get
- {
- return false;
- }
- }
+ bool IList.IsReadOnly => false;
- /// <include file='doc\SchemaNameCollection.uex' path='docs/doc[@for="SchemaNameCollection.IList.IsFixedSize"]/*' />
- /// <internalonly/>
- bool IList.IsFixedSize
- {
- get
- {
- return false;
- }
- }
+ bool IList.IsFixedSize => false;
- /// <include file='doc\SchemaNameCollection.uex' path='docs/doc[@for="SchemaNameCollection.ICollection.CopyTo"]/*' />
- /// <internalonly/>
void ICollection.CopyTo(Array array, int index)
{
object[] values = GetValue();
values.CopyTo(array, index);
}
- /// <include file='doc\SchemaNameCollection.uex' path='docs/doc[@for="SchemaNameCollection.ICollection.IsSynchronized"]/*' />
- /// <internalonly/>
- bool ICollection.IsSynchronized
- {
- get
- {
- return false;
- }
- }
+ bool ICollection.IsSynchronized => false;
- /// <include file='doc\SchemaNameCollection.uex' path='docs/doc[@for="SchemaNameCollection.ICollection.SyncRoot"]/*' />
- /// <internalonly/>
- object ICollection.SyncRoot
- {
- get
- {
- return this;
- }
- }
+ object ICollection.SyncRoot => this;
- /// <include file='doc\SchemaNameCollection.uex' path='docs/doc[@for="SchemaNameCollection.IList.this"]/*' />
- /// <internalonly/>
object IList.this[int index]
{
- get
- {
- return this[index];
- }
- set
- {
- this[index] = (string)value;
- }
+ get => this[index];
+ set => this[index] = (string)value;
}
- /// <include file='doc\SchemaNameCollection.uex' path='docs/doc[@for="SchemaNameCollection.IList.Add"]/*' />
- /// <internalonly/>
- int IList.Add(object value)
- {
- return Add((string)value);
- }
+ int IList.Add(object value) => Add((string)value);
- /// <include file='doc\SchemaNameCollection.uex' path='docs/doc[@for="SchemaNameCollection.IList.Contains"]/*' />
- /// <internalonly/>
- bool IList.Contains(object value)
- {
- return Contains((string)value);
- }
+ bool IList.Contains(object value) => Contains((string)value);
- /// <include file='doc\SchemaNameCollection.uex' path='docs/doc[@for="SchemaNameCollection.IList.IndexOf"]/*' />
- /// <internalonly/>
- int IList.IndexOf(object value)
- {
- return IndexOf((string)value);
- }
+ int IList.IndexOf(object value) => IndexOf((string)value);
- /// <include file='doc\SchemaNameCollection.uex' path='docs/doc[@for="SchemaNameCollection.IList.Insert"]/*' />
- /// <internalonly/>
- void IList.Insert(int index, object value)
- {
- Insert(index, (string)value);
- }
+ void IList.Insert(int index, object value) => Insert(index, (string)value);
- /// <include file='doc\SchemaNameCollection.uex' path='docs/doc[@for="SchemaNameCollection.IList.Remove"]/*' />
- /// <internalonly/>
- void IList.Remove(object value)
- {
- Remove((string)value);
- }
+ void IList.Remove(object value) => Remove((string)value);
internal delegate object VariantPropGetter();
internal delegate void VariantPropSetter(object value);
@@ -338,32 +227,14 @@ namespace System.DirectoryServices
{
_obj = wrapped;
}
- public VariantPropGetter Getter
- {
- get
- {
- return new VariantPropGetter(GetFilter);
- }
- }
- public VariantPropSetter Setter
- {
- get
- {
- return new VariantPropSetter(SetFilter);
- }
- }
+ public VariantPropGetter Getter => new VariantPropGetter(GetFilter);
- private object GetFilter()
- {
- return _obj.Filter;
- }
+ public VariantPropSetter Setter => new VariantPropSetter(SetFilter);
- private void SetFilter(object value)
- {
- _obj.Filter = value;
- }
+ private object GetFilter() => _obj.Filter;
+
+ private void SetFilter(object value) => _obj.Filter = value;
}
}
}
-
diff --git a/src/System.DirectoryServices/src/System/DirectoryServices/SearchResult.cs b/src/System.DirectoryServices/src/System/DirectoryServices/SearchResult.cs
index 17405141e4..c94454bfa0 100644
--- a/src/System.DirectoryServices/src/System/DirectoryServices/SearchResult.cs
+++ b/src/System.DirectoryServices/src/System/DirectoryServices/SearchResult.cs
@@ -2,25 +2,19 @@
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
+using System.Net;
+using System.Security.Permissions;
+
namespace System.DirectoryServices
{
- using System;
- using System.Net;
- using System.Runtime.InteropServices;
- using System.Collections;
- using System.Diagnostics;
- using System.Security.Permissions;
-
- /// <include file='doc\SearchResult.uex' path='docs/doc[@for="SearchResult"]/*' />
/// <devdoc>
- /// <para>Encapsulates a node in the Active Directory hierarchy
- /// that is returned during a search through <see cref='System.DirectoryServices.DirectorySearcher'/>.</para>
+ /// Encapsulates a node in the Active Directory hierarchy
+ /// that is returned during a search through <see cref='System.DirectoryServices.DirectorySearcher'/>.
/// </devdoc>
public class SearchResult
{
- private NetworkCredential _parentCredentials;
- private AuthenticationTypes _parentAuthenticationType;
- private ResultPropertyCollection _properties = new ResultPropertyCollection();
+ private readonly NetworkCredential _parentCredentials;
+ private readonly AuthenticationTypes _parentAuthenticationType;
internal SearchResult(NetworkCredential parentCredentials, AuthenticationTypes parentAuthenticationType)
{
@@ -28,15 +22,12 @@ namespace System.DirectoryServices
_parentAuthenticationType = parentAuthenticationType;
}
- /// <include file='doc\SearchResult.uex' path='docs/doc[@for="SearchResult.GetDirectoryEntry"]/*' />
/// <devdoc>
- /// <para>Retrieves the <see cref='System.DirectoryServices.DirectoryEntry'/> that corresponds to the <see cref='System.DirectoryServices.SearchResult'/>, from the Active Directory
- /// hierarchy.</para>
+ /// Retrieves the <see cref='System.DirectoryServices.DirectoryEntry'/> that corresponds to the <see cref='System.DirectoryServices.SearchResult'/>, from the Active Directory
+ /// hierarchy.
/// </devdoc>
- [
- EnvironmentPermission(SecurityAction.Assert, Unrestricted = true),
- SecurityPermission(SecurityAction.Assert, Flags = SecurityPermissionFlag.UnmanagedCode)
- ]
+ [EnvironmentPermission(SecurityAction.Assert, Unrestricted = true)]
+ [SecurityPermission(SecurityAction.Assert, Flags = SecurityPermissionFlag.UnmanagedCode)]
public DirectoryEntry GetDirectoryEntry()
{
if (_parentCredentials != null)
@@ -48,29 +39,15 @@ namespace System.DirectoryServices
}
}
- /// <include file='doc\SearchResult.uex' path='docs/doc[@for="SearchResult.Path"]/*' />
/// <devdoc>
- /// <para> Gets the path for this <see cref='System.DirectoryServices.SearchResult'/>.</para>
+ /// Gets the path for this <see cref='System.DirectoryServices.SearchResult'/>.
/// </devdoc>
- public string Path
- {
- get
- {
- return (string)Properties["ADsPath"][0];
- }
- }
+ public string Path => (string)Properties["ADsPath"][0];
- /// <include file='doc\SearchResult.uex' path='docs/doc[@for="SearchResult.Properties"]/*' />
/// <devdoc>
- /// <para>Gets a <see cref='System.DirectoryServices.ResultPropertyCollection'/>
- /// of properties set on this object.</para>
+ /// Gets a <see cref='System.DirectoryServices.ResultPropertyCollection'/>
+ /// of properties set on this object.
/// </devdoc>
- public ResultPropertyCollection Properties
- {
- get
- {
- return _properties;
- }
- }
+ public ResultPropertyCollection Properties { get; } = new ResultPropertyCollection();
}
}
diff --git a/src/System.DirectoryServices/src/System/DirectoryServices/SearchResultCollection.cs b/src/System.DirectoryServices/src/System/DirectoryServices/SearchResultCollection.cs
index f5f9ad96e7..bddf376f96 100644
--- a/src/System.DirectoryServices/src/System/DirectoryServices/SearchResultCollection.cs
+++ b/src/System.DirectoryServices/src/System/DirectoryServices/SearchResultCollection.cs
@@ -2,86 +2,48 @@
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
-using INTPTR_INTCAST = System.Int32;
+using System.Net;
+using System.Runtime.InteropServices;
+using System.Collections;
+using System.DirectoryServices.Interop;
+using System.Text;
+
using INTPTR_INTPTRCAST = System.IntPtr;
namespace System.DirectoryServices
{
- using System;
- using System.Net;
- using System.Runtime.InteropServices;
- using System.Collections;
- using System.Diagnostics;
- using System.DirectoryServices.Interop;
- using System.Text;
- using System.Configuration;
- using System.Security.Permissions;
- using System.Globalization;
-
- /// <include file='doc\SearchResultCollection.uex' path='docs/doc[@for="SearchResultCollection"]/*' />
/// <devdoc>
- /// <para>Contains the instances of <see cref='System.DirectoryServices.SearchResult'/> returned during a
- /// query to the Active Directory hierarchy through <see cref='System.DirectoryServices.DirectorySearcher'/>.</para>
+ /// Contains the instances of <see cref='System.DirectoryServices.SearchResult'/> returned during a
+ /// query to the Active Directory hierarchy through <see cref='System.DirectoryServices.DirectorySearcher'/>.
/// </devdoc>
public class SearchResultCollection : MarshalByRefObject, ICollection, IEnumerable, IDisposable
{
private IntPtr _handle;
- private string[] _properties;
private UnsafeNativeMethods.IDirectorySearch _searchObject;
- private string _filter;
private ArrayList _innerList;
private bool _disposed;
- private DirectoryEntry _rootEntry; // clone of parent entry object
+ private readonly DirectoryEntry _rootEntry; // clone of parent entry object
private const string ADS_DIRSYNC_COOKIE = "fc8cb04d-311d-406c-8cb9-1ae8b843b418";
private IntPtr _adsDirsynCookieName = Marshal.StringToCoTaskMemUni(ADS_DIRSYNC_COOKIE);
private const string ADS_VLV_RESPONSE = "fc8cb04d-311d-406c-8cb9-1ae8b843b419";
private IntPtr _adsVLVResponseName = Marshal.StringToCoTaskMemUni(ADS_VLV_RESPONSE);
internal DirectorySearcher srch = null;
- ///<internalonly/>
internal SearchResultCollection(DirectoryEntry root, IntPtr searchHandle, string[] propertiesLoaded, DirectorySearcher srch)
{
_handle = searchHandle;
- _properties = propertiesLoaded;
- _filter = srch.Filter;
+ PropertiesLoaded = propertiesLoaded;
+ Filter = srch.Filter;
_rootEntry = root;
this.srch = srch;
}
- /// <include file='doc\SearchResultCollection.uex' path='docs/doc[@for="SearchResultCollection.this"]/*' />
- /// <devdoc>
- /// <para>[To be supplied.]</para>
- /// </devdoc>
- public SearchResult this[int index]
- {
- get
- {
- return (SearchResult)InnerList[index];
- }
- }
+ public SearchResult this[int index] => (SearchResult)InnerList[index];
- /// <include file='doc\SearchResultCollection.uex' path='docs/doc[@for="SearchResultCollection.Count"]/*' />
- /// <devdoc>
- /// <para>[To be supplied.]</para>
- /// </devdoc>
- public int Count
- {
- get
- {
- return InnerList.Count;
- }
- }
+ public int Count => InnerList.Count;
+
+ internal string Filter { get; }
- ///<internalonly/>
- internal string Filter
- {
- get
- {
- return _filter;
- }
- }
-
- ///<internalonly/>
private ArrayList InnerList
{
get
@@ -101,7 +63,6 @@ namespace System.DirectoryServices
}
}
- ///<internalonly/>
internal UnsafeNativeMethods.IDirectorySearch SearchObject
{
get
@@ -114,10 +75,9 @@ namespace System.DirectoryServices
}
}
- /// <include file='doc\SearchResultCollection.uex' path='docs/doc[@for="SearchResultCollection.Handle"]/*' />
/// <devdoc>
- /// <para>Gets the handle returned by IDirectorySearch::ExecuteSearch, which was called
- /// by the DirectorySearcher that created this object.</para>
+ /// Gets the handle returned by IDirectorySearch::ExecuteSearch, which was called
+ /// by the DirectorySearcher that created this object
/// </devdoc>
public IntPtr Handle
{
@@ -131,37 +91,17 @@ namespace System.DirectoryServices
}
}
- /// <include file='doc\SearchResultCollection.uex' path='docs/doc[@for="SearchResultCollection.PropertiesLoaded"]/*' />
/// <devdoc>
- /// <para>Gets a read-only collection of the properties
- /// specified on <see cref='System.DirectoryServices.DirectorySearcher'/> before the
- /// search was executed.</para>
+ /// Gets a read-only collection of the properties specified on <see cref='System.DirectoryServices.DirectorySearcher'/> before the
+ /// search was executed.
/// </devdoc>
- public string[] PropertiesLoaded
- {
- get
- {
- return _properties;
- }
- }
+ public string[] PropertiesLoaded { get; }
- internal byte[] DirsyncCookie
- {
- get
- {
- return RetrieveDirectorySynchronizationCookie();
- }
- }
+ internal byte[] DirsyncCookie => RetrieveDirectorySynchronizationCookie();
- internal DirectoryVirtualListView VLVResponse
- {
- get
- {
- return RetrieveVLVResponse();
- }
- }
+ internal DirectoryVirtualListView VLVResponse => RetrieveVLVResponse();
- internal unsafe byte[] RetrieveDirectorySynchronizationCookie()
+ private unsafe byte[] RetrieveDirectorySynchronizationCookie()
{
if (_disposed)
throw new ObjectDisposedException(GetType().Name);
@@ -189,7 +129,7 @@ namespace System.DirectoryServices
}
}
- internal unsafe DirectoryVirtualListView RetrieveVLVResponse()
+ private unsafe DirectoryVirtualListView RetrieveVLVResponse()
{
if (_disposed)
throw new ObjectDisposedException(GetType().Name);
@@ -216,18 +156,12 @@ namespace System.DirectoryServices
}
}
- /// <include file='doc\SearchResultCollection.uex' path='docs/doc[@for="SearchResultCollection.Dispose"]/*' />
- /// <devdoc>
- /// </devdoc>
public void Dispose()
{
Dispose(true);
GC.SuppressFinalize(this);
}
- /// <include file='doc\SearchResultCollection.uex' path='docs/doc[@for="SearchResultCollection.Dispose1"]/*' />
- /// <devdoc>
- /// </devdoc>
protected virtual void Dispose(bool disposing)
{
if (!_disposed)
@@ -260,16 +194,8 @@ namespace System.DirectoryServices
}
}
- /// <include file='doc\SearchResultCollection.uex' path='docs/doc[@for=".Finalize"]/*' />
- ~SearchResultCollection()
- {
- Dispose(false); // finalizer is called => Dispose has not been called yet.
- }
+ ~SearchResultCollection() => Dispose(false);
- /// <include file='doc\SearchResultCollection.uex' path='docs/doc[@for="SearchResultCollection.GetEnumerator"]/*' />
- /// <devdoc>
- /// <para>[To be supplied.]</para>
- /// </devdoc>
public IEnumerator GetEnumerator()
{
// Two ResultsEnumerators can't exist at the same time over the
@@ -280,63 +206,26 @@ namespace System.DirectoryServices
_rootEntry.AuthenticationType);
}
- /// <include file='doc\SearchResultCollection.uex' path='docs/doc[@for="SearchResultCollection.Contains"]/*' />
- /// <devdoc>
- /// <para>[To be supplied.]</para>
- /// </devdoc>
- public bool Contains(SearchResult result)
- {
- return InnerList.Contains(result);
- }
+ public bool Contains(SearchResult result) => InnerList.Contains(result);
- /// <include file='doc\SearchResultCollection.uex' path='docs/doc[@for="SearchResultCollection.CopyTo"]/*' />
- /// <devdoc>
- /// <para>[To be supplied.]</para>
- /// </devdoc>
public void CopyTo(SearchResult[] results, int index)
{
InnerList.CopyTo(results, index);
}
- /// <include file='doc\SearchResultCollection.uex' path='docs/doc[@for="SearchResultCollection.IndexOf"]/*' />
- /// <devdoc>
- /// <para>[To be supplied.]</para>
- /// </devdoc>
- public int IndexOf(SearchResult result)
- {
- return InnerList.IndexOf(result);
- }
+ public int IndexOf(SearchResult result) => InnerList.IndexOf(result);
- /// <include file='doc\SearchResultCollection.uex' path='docs/doc[@for="SearchResultCollection.ICollection.IsSynchronized"]/*' />
- ///<internalonly/>
- bool ICollection.IsSynchronized
- {
- get
- {
- return false;
- }
- }
+ bool ICollection.IsSynchronized => false;
- /// <include file='doc\SearchResultCollection.uex' path='docs/doc[@for="SearchResultCollection.ICollection.SyncRoot"]/*' />
- ///<internalonly/>
- object ICollection.SyncRoot
- {
- get
- {
- return this;
- }
- }
+ object ICollection.SyncRoot => this;
- /// <include file='doc\SearchResultCollection.uex' path='docs/doc[@for="SearchResultCollection.ICollection.CopyTo"]/*' />
- /// <internalonly/>
void ICollection.CopyTo(Array array, int index)
{
InnerList.CopyTo(array, index);
}
/// <devdoc>
- /// <para> Supports a simple
- /// ForEach-style iteration over a collection.</para>
+ /// Supports a simple ForEach-style iteration over a collection.
/// </devdoc>
private class ResultsEnumerator : IEnumerator
{
@@ -356,17 +245,10 @@ namespace System.DirectoryServices
_parentAuthenticationType = parentAuthenticationType;
_results = results;
_initialized = false;
-
- // get the app configuration information
- //object o = PrivilegedConfigurationManager.GetSection("system.directoryservices");
- //if (o != null && o is bool)
- //{
- // _waitForResult = (bool)o;
- //}
}
/// <devdoc>
- /// <para>Gets the current element in the collection.</para>
+ /// Gets the current element in the collection.
/// </devdoc>
public SearchResult Current
{
@@ -428,12 +310,10 @@ namespace System.DirectoryServices
return entry;
}
- /// <include file='doc\SearchResultCollection.uex' path='docs/doc[@for="SearchResultCollection.ResultsEnumerator.MoveNext"]/*' />
/// <devdoc>
- /// <para>Advances
- /// the enumerator to the next element of the collection
- /// and returns a Boolean value indicating whether a valid element is available.</para>
- /// </devdoc>
+ /// Advances the enumerator to the next element of the collection
+ /// and returns a Boolean value indicating whether a valid element is available.
+ /// </devdoc>
public bool MoveNext()
{
DirectorySynchronization tempsync = null;
@@ -452,7 +332,7 @@ namespace System.DirectoryServices
{
//throw a clearer exception if the filter was invalid
if (hr == UnsafeNativeMethods.INVALID_FILTER)
- throw new ArgumentException(String.Format(CultureInfo.CurrentCulture, SR.DSInvalidSearchFilter , _results.Filter));
+ throw new ArgumentException(SR.Format(SR.DSInvalidSearchFilter , _results.Filter));
if (hr != 0)
throw COMExceptionHelper.CreateFormattedComException(hr);
@@ -517,7 +397,7 @@ namespace System.DirectoryServices
}
//throw a clearer exception if the filter was invalid
if (hr == UnsafeNativeMethods.INVALID_FILTER)
- throw new ArgumentException(String.Format(CultureInfo.CurrentCulture, SR.DSInvalidSearchFilter , _results.Filter));
+ throw new ArgumentException(SR.Format(SR.DSInvalidSearchFilter , _results.Filter));
if (hr != 0)
throw COMExceptionHelper.CreateFormattedComException(hr);
@@ -527,7 +407,7 @@ namespace System.DirectoryServices
}
/// <devdoc>
- /// <para>Resets the enumerator back to its initial position before the first element in the collection.</para>
+ /// Resets the enumerator back to its initial position before the first element in the collection.
/// </devdoc>
public void Reset()
{
@@ -535,13 +415,7 @@ namespace System.DirectoryServices
_initialized = false;
}
- object IEnumerator.Current
- {
- get
- {
- return Current;
- }
- }
+ object IEnumerator.Current => Current;
private void CleanLastError()
{
diff --git a/src/System.DirectoryServices/src/System/DirectoryServices/SearchScope.cs b/src/System.DirectoryServices/src/System/DirectoryServices/SearchScope.cs
index dae91782ba..2553a79ab5 100644
--- a/src/System.DirectoryServices/src/System/DirectoryServices/SearchScope.cs
+++ b/src/System.DirectoryServices/src/System/DirectoryServices/SearchScope.cs
@@ -4,26 +4,23 @@
namespace System.DirectoryServices
{
- /// <include file='doc\SearchScope.uex' path='docs/doc[@for="SearchScope"]/*' />
/// <devdoc>
- /// <para>Specifies the scope of a directory search.</para>
+ /// Specifies the scope of a directory search.
/// </devdoc>
public enum SearchScope
{
- /// <include file='doc\SearchScope.uex' path='docs/doc[@for="SearchScope.Base"]/*' />
/// <devdoc>
- /// <para>Limits the search to the base object. The result contains at most one object. </para>
+ /// Limits the search to the base object. The result contains at most one object.
/// </devdoc>
Base = 0,
- /// <include file='doc\SearchScope.uex' path='docs/doc[@for="SearchScope.OneLevel"]/*' />
+
/// <devdoc>
- /// <para>Searched one level of the immediate children, excluding the base object.</para>
+ /// Searched one level of the immediate children, excluding the base object.
/// </devdoc>
OneLevel = 1,
- /// <include file='doc\SearchScope.uex' path='docs/doc[@for="SearchScope.Subtree"]/*' />
+
/// <devdoc>
- /// <para>Searches the whole subtree, including all the children and the base object
- /// itself.</para>
+ /// Searches the whole subtree, including all the children and the base object itself.
/// </devdoc>
Subtree = 2
}
diff --git a/src/System.DirectoryServices/src/System/DirectoryServices/SearchWaitHandler.cs b/src/System.DirectoryServices/src/System/DirectoryServices/SearchWaitHandler.cs
deleted file mode 100644
index a02863b9ed..0000000000
--- a/src/System.DirectoryServices/src/System/DirectoryServices/SearchWaitHandler.cs
+++ /dev/null
@@ -1,70 +0,0 @@
-// Licensed to the .NET Foundation under one or more agreements.
-// The .NET Foundation licenses this file to you under the MIT license.
-// See the LICENSE file in the project root for more information.
-
-using INTPTR_INTCAST = System.Int32;
-using INTPTR_INTPTRCAST = System.IntPtr;
-
-namespace System.DirectoryServices
-{
- using System;
- using System.Collections;
- using System.Diagnostics;
- using System.Xml;
- using System.Configuration;
- using System.Reflection;
- using System.Security.Permissions;
- using System.Globalization;
- // https://support.microsoft.com/en-us/kb/833789
- //internal class SearchWaitHandler : IConfigurationSectionHandler
- //{
- // public virtual object Create(object parent, object configContext, XmlNode section)
- // {
- // bool foundWaitStatus = false;
- // bool waitForSearchResult = false;
-
- // foreach (XmlNode child in section.ChildNodes)
- // {
- // switch (child.Name)
- // {
- // case "DirectorySearcher":
- // if (foundWaitStatus)
- // throw new ConfigurationErrorsException(String.Format(CultureInfo.CurrentCulture, SR.ConfigSectionsUnique , "DirectorySearcher"));
- // HandlerBase.RemoveBooleanAttribute(child, "waitForPagedSearchData", ref waitForSearchResult);
- // foundWaitStatus = true;
- // break;
-
- // default:
- // break;
- // } // switch(child.Name)
- // }
-
- // object o = waitForSearchResult;
- // return o;
- // }
- //}
-
- internal class HandlerBase
- {
- private HandlerBase()
- {
- }
-
- static internal void RemoveBooleanAttribute(XmlNode node, string name, ref bool value)
- {
- //value = false;
- //XmlNode attribute = node.Attributes.RemoveNamedItem(name);
- //if (null != attribute)
- //{
- // try
- // {
- // value = bool.Parse(attribute.Value);
- // }
- // catch (FormatException)
- // {
- // throw new ConfigurationErrorsException(String.Format(CultureInfo.CurrentCulture, SR.Invalid, _boolean_attribute, name));
- // }
- //}
- }
- }
-}
diff --git a/src/System.DirectoryServices/src/System/DirectoryServices/SecurityMasks.cs b/src/System.DirectoryServices/src/System/DirectoryServices/SecurityMasks.cs
index a06ea8f503..736f6b281b 100644
--- a/src/System.DirectoryServices/src/System/DirectoryServices/SecurityMasks.cs
+++ b/src/System.DirectoryServices/src/System/DirectoryServices/SecurityMasks.cs
@@ -4,28 +4,16 @@
namespace System.DirectoryServices
{
- /// <include file='doc\SecurityMasks.uex' path='docs/doc[@for="SecurityMasks"]/*' />
/// <devdoc>
- /// <para>
- /// Specifies the available options for examining security information of an object.
- /// </para>
+ /// Specifies the available options for examining security information of an object.
/// </devdoc>
[Flags]
public enum SecurityMasks
{
- /// <include file='doc\SecurityMasks.uex' path='docs/doc[@for="SecurityMasks.None"]/*' />
None = 0,
-
- /// <include file='doc\SecurityMasks.uex' path='docs/doc[@for="SecurityMasks.Owner"]/*' />
Owner = 1,
-
- /// <include file='doc\SecurityMasks.uex' path='docs/doc[@for="SecurityMasks.Group"]/*' />
Group = 2,
-
- /// <include file='doc\SecurityMasks.uex' path='docs/doc[@for="SecurityMasks.DACL"]/*' />
Dacl = 4,
-
- /// <include file='doc\SecurityMasks.uex' path='docs/doc[@for="SecurityMasks.SACL"]/*' />
Sacl = 8
}
}
diff --git a/src/System.DirectoryServices/src/System/DirectoryServices/SortDirection.cs b/src/System.DirectoryServices/src/System/DirectoryServices/SortDirection.cs
index bc3d4be2c2..9052874915 100644
--- a/src/System.DirectoryServices/src/System/DirectoryServices/SortDirection.cs
+++ b/src/System.DirectoryServices/src/System/DirectoryServices/SortDirection.cs
@@ -4,20 +4,9 @@
namespace System.DirectoryServices
{
- /// <include file='doc\SortDirection.uex' path='docs/doc[@for="SortDirection"]/*' />
- /// <devdoc>
- /// </devdoc>
public enum SortDirection
{
- /// <include file='doc\SortDirection.uex' path='docs/doc[@for="SortDirection.Ascending"]/*' />
- /// <devdoc>
- /// <para>[To be supplied.]</para>
- /// </devdoc>
Ascending = 0,
- /// <include file='doc\SortDirection.uex' path='docs/doc[@for="SortDirection.Descending"]/*' />
- /// <devdoc>
- /// <para>[To be supplied.]</para>
- /// </devdoc>
Descending = 1
}
}
diff --git a/src/System.DirectoryServices/tests/System.DirectoryServices.Tests.csproj b/src/System.DirectoryServices/tests/System.DirectoryServices.Tests.csproj
index b1b844d2b4..a5ee49348b 100644
--- a/src/System.DirectoryServices/tests/System.DirectoryServices.Tests.csproj
+++ b/src/System.DirectoryServices/tests/System.DirectoryServices.Tests.csproj
@@ -18,9 +18,6 @@
<Compile Include="System\DirectoryServices\ActiveDirectory\ActiveDirectoryInterSiteTransportTests.cs" />
<Compile Include="System\DirectoryServices\ActiveDirectory\DirectoryContextTests.cs" />
<Compile Include="System\DirectoryServices\ActiveDirectory\ForestTests.cs" />
- <Compile Include="$(CommonTestPath)\System\AssertExtensions.cs">
- <Link>Common\System\AssertExtensions.cs</Link>
- </Compile>
<Compile Include="$(CommonTestPath)\System\PlatformDetection.cs">
<Link>Common\System\PlatformDetection.cs</Link>
</Compile>
diff --git a/src/System.DirectoryServices/tests/System/DirectoryServices/ActiveDirectory/ActiveDirectoryInterSiteTransportTests.cs b/src/System.DirectoryServices/tests/System/DirectoryServices/ActiveDirectory/ActiveDirectoryInterSiteTransportTests.cs
index 0019663feb..bc038fd891 100644
--- a/src/System.DirectoryServices/tests/System/DirectoryServices/ActiveDirectory/ActiveDirectoryInterSiteTransportTests.cs
+++ b/src/System.DirectoryServices/tests/System/DirectoryServices/ActiveDirectory/ActiveDirectoryInterSiteTransportTests.cs
@@ -16,6 +16,7 @@ namespace System.DirectoryServices.ActiveDirectory.Tests
}
[Fact]
+ [OuterLoop]
[SkipOnTargetFramework(TargetFrameworkMonikers.Uap, "Getting information about domain is denied inside App")]
[ActiveIssue("https://github.com/dotnet/corefx/issues/21553", TargetFrameworkMonikers.UapAot)]
public void FindByTransportType_ForestNoDomainAssociatedWithoutName_ThrowsActiveDirectoryOperationException()
@@ -47,6 +48,7 @@ namespace System.DirectoryServices.ActiveDirectory.Tests
}
[ConditionalTheory(nameof(PlatformDetection) + "." + nameof(PlatformDetection.IsNotWindowsNanoServer))]
+ [OuterLoop("Takes too long on domain joined machines")]
[InlineData(DirectoryContextType.ApplicationPartition)]
[InlineData(DirectoryContextType.DirectoryServer)]
[InlineData(DirectoryContextType.Domain)]
@@ -58,6 +60,7 @@ namespace System.DirectoryServices.ActiveDirectory.Tests
}
[Fact]
+ [OuterLoop]
[SkipOnTargetFramework(TargetFrameworkMonikers.Uap, "Getting information about domain is denied inside App")]
[ActiveIssue("https://github.com/dotnet/corefx/issues/21553", TargetFrameworkMonikers.UapAot)]
public void FindByTransportType_ConfigurationSetTypeWithName_Throws()
diff --git a/src/System.DirectoryServices/tests/System/DirectoryServices/ActiveDirectory/DomainControllerTests.cs b/src/System.DirectoryServices/tests/System/DirectoryServices/ActiveDirectory/DomainControllerTests.cs
index 1e39aaa998..489de1aa5a 100644
--- a/src/System.DirectoryServices/tests/System/DirectoryServices/ActiveDirectory/DomainControllerTests.cs
+++ b/src/System.DirectoryServices/tests/System/DirectoryServices/ActiveDirectory/DomainControllerTests.cs
@@ -27,6 +27,7 @@ namespace System.DirectoryServices.ActiveDirectory.Tests
}
[ConditionalTheory(nameof(PlatformDetection) + "." + nameof(PlatformDetection.IsNotWindowsNanoServer))]
+ [OuterLoop("Takes too long on domain joined machines")]
[InlineData("\0")]
[InlineData("server:port")]
[InlineData("[")]
@@ -39,10 +40,10 @@ namespace System.DirectoryServices.ActiveDirectory.Tests
[ConditionalFact(nameof(PlatformDetection) + "." + nameof(PlatformDetection.IsNotWindowsNanoServer))]
[SkipOnTargetFramework(TargetFrameworkMonikers.Uap, "Access to path is denied when in App container")]
- public void GetDomainController_InvalidIPV6_ThrowsInvalidCastException()
+ public void GetDomainController_InvalidIPV6_ThrowsActiveDirectoryObjectNotFoundException()
{
var context = new DirectoryContext(DirectoryContextType.DirectoryServer, "[::1]:port");
- Assert.Throws<InvalidCastException>(() => DomainController.GetDomainController(context));
+ Assert.Throws<ActiveDirectoryObjectNotFoundException>(() => DomainController.GetDomainController(context));
}
[Fact]
@@ -114,6 +115,7 @@ namespace System.DirectoryServices.ActiveDirectory.Tests
}
[Fact]
+ [OuterLoop]
[SkipOnTargetFramework(TargetFrameworkMonikers.Uap, "Getting information about domain is denied inside App")]
[ActiveIssue("https://github.com/dotnet/corefx/issues/21553", TargetFrameworkMonikers.UapAot)]
public void FindAll_NullName_ThrowsActiveDirectoryOperationException()
diff --git a/src/System.DirectoryServices/tests/System/DirectoryServices/ActiveDirectory/ForestTests.cs b/src/System.DirectoryServices/tests/System/DirectoryServices/ActiveDirectory/ForestTests.cs
index 2286064c89..d51e67d33b 100644
--- a/src/System.DirectoryServices/tests/System/DirectoryServices/ActiveDirectory/ForestTests.cs
+++ b/src/System.DirectoryServices/tests/System/DirectoryServices/ActiveDirectory/ForestTests.cs
@@ -25,6 +25,7 @@ namespace System.DirectoryServices.ActiveDirectory.Tests
}
[Fact]
+ [OuterLoop]
[SkipOnTargetFramework(TargetFrameworkMonikers.Uap, "Not approved COM object for app")]
public void GetForest_NullNameAndNotRootedDomain_ThrowsActiveDirectoryOperationException()
{
@@ -46,6 +47,7 @@ namespace System.DirectoryServices.ActiveDirectory.Tests
}
[ConditionalTheory(nameof(PlatformDetection) + "." + nameof(PlatformDetection.IsNotWindowsNanoServer))]
+ [OuterLoop("Takes too long on domain joined machines")]
[InlineData(DirectoryContextType.Forest, "\0")]
[InlineData(DirectoryContextType.DirectoryServer, "server:port")]
[SkipOnTargetFramework(TargetFrameworkMonikers.Uap, "Not approved COM object for app")]
diff --git a/src/System.Drawing.Common/ref/System.Drawing.Common.cs b/src/System.Drawing.Common/ref/System.Drawing.Common.cs
index 9d520831b1..9de05cbc0b 100644
--- a/src/System.Drawing.Common/ref/System.Drawing.Common.cs
+++ b/src/System.Drawing.Common/ref/System.Drawing.Common.cs
@@ -3157,15 +3157,5 @@ namespace System.Drawing.Design
public delegate void ToolboxComponentsCreatingEventHandler(object sender, System.Drawing.Design.ToolboxComponentsCreatingEventArgs e);
}
-namespace System.Drawing.Configuration
-{
- public sealed partial class SystemDrawingSection : System.Configuration.ConfigurationSection
- {
- public SystemDrawingSection() { }
- [System.Configuration.ConfigurationPropertyAttribute("bitmapSuffix")]
- public string BitmapSuffix { get { throw null; } set { } }
- protected override System.Configuration.ConfigurationPropertyCollection Properties { get { throw null; } }
- }
-}
*/ \ No newline at end of file
diff --git a/src/System.Drawing.Common/src/System.Drawing.Common.csproj b/src/System.Drawing.Common/src/System.Drawing.Common.csproj
index d572f14fd2..b2299babe8 100644
--- a/src/System.Drawing.Common/src/System.Drawing.Common.csproj
+++ b/src/System.Drawing.Common/src/System.Drawing.Common.csproj
@@ -49,8 +49,8 @@
<Compile Include="System\Drawing\BufferedGraphics.cs" />
<Compile Include="System\Drawing\BufferedGraphicsContext.cs" />
<Compile Include="System\Drawing\BufferedGraphicsManager.cs" />
+ <Compile Include="System\Drawing\ClientUtils.cs" />
<Compile Include="System\Drawing\ColorTranslator.cs" />
- <Compile Include="System\Drawing\Configuration\SystemDrawingSection.cs" />
<Compile Include="System\Drawing\ContentAlignment.cs" />
<Compile Include="System\Drawing\CopyPixelOperation.cs" />
<Compile Include="System\Drawing\DashCap.cs" />
@@ -147,7 +147,6 @@
<Compile Include="System\Drawing\Internal\GPRECTF.cs" />
<Compile Include="System\Drawing\Internal\GPStream.cs" />
<Compile Include="System\Drawing\Internal\ISystemEventTracker.cs" />
- <Compile Include="System\Drawing\Internal\RectangleFEx.cs" />
<Compile Include="System\Drawing\Internal\SystemColorTracker.cs" />
<Compile Include="System\Drawing\LocalAppContextSwitches.cs" />
<Compile Include="System\Drawing\NativeMethods.cs" />
@@ -209,19 +208,15 @@
<Compile Include="System\Drawing\ToolboxBitmapAttribute.cs" />
<Compile Include="System\Drawing\Unit.cs" />
<Compile Include="System\Drawing\UnsafeNativeMethods.cs" />
- <Compile Include="misc\ClientUtils.cs" />
<Compile Include="misc\CompModSwitches.cs" />
- <Compile Include="misc\CoreSwitches.cs" />
<Compile Include="misc\DbgUtil.cs" />
<Compile Include="misc\DebugHandleTracker.cs" />
<Compile Include="misc\DpiHelper.cs" />
<Compile Include="misc\ExternDll.cs" />
<Compile Include="misc\GDI\ApplyGraphicsProperties.cs" />
<Compile Include="misc\GDI\DeviceContext.cs" />
- <Compile Include="misc\GDI\DeviceContextGraphicsMode.cs" />
<Compile Include="misc\GDI\DeviceContexts.cs" />
<Compile Include="misc\GDI\DeviceContextType.cs" />
- <Compile Include="misc\GDI\GdiObjectType.cs" />
<Compile Include="misc\GDI\NativeMethods.cs" />
<Compile Include="misc\GDI\SafeNativeMethods.cs" />
<Compile Include="misc\GDI\UnsafeNativeMethods.cs" />
diff --git a/src/System.Drawing.Common/src/System/Drawing/ClientUtils.cs b/src/System.Drawing.Common/src/System/Drawing/ClientUtils.cs
new file mode 100644
index 0000000000..8fb59d2b50
--- /dev/null
+++ b/src/System.Drawing.Common/src/System/Drawing/ClientUtils.cs
@@ -0,0 +1,272 @@
+// Licensed to the .NET Foundation under one or more agreements.
+// The .NET Foundation licenses this file to you under the MIT license.
+// See the LICENSE file in the project root for more information.
+
+using System.Collections;
+using System.Diagnostics;
+using System.Security;
+
+namespace System.Drawing
+{
+ internal static class ClientUtils
+ {
+ // ExecutionEngineException is obsolete and shouldn't be used (to catch, throw or reference) anymore.
+ // Pragma added to prevent converting the "type is obsolete" warning into build error.
+#pragma warning disable 618
+ public static bool IsCriticalException(Exception ex)
+ {
+ return ex is NullReferenceException
+ || ex is StackOverflowException
+ || ex is OutOfMemoryException
+ || ex is System.Threading.ThreadAbortException
+ || ex is ExecutionEngineException
+ || ex is IndexOutOfRangeException
+ || ex is AccessViolationException;
+ }
+#pragma warning restore 618
+
+ public static bool IsSecurityOrCriticalException(Exception ex)
+ {
+ return (ex is SecurityException) || IsCriticalException(ex);
+ }
+
+ /// <summary>
+ /// WeakRefCollection - a collection that holds onto weak references.
+ ///
+ /// Essentially you pass in the object as it is, and under the covers
+ /// we only hold a weak reference to the object.
+ ///
+ /// -----------------------------------------------------------------
+ /// !!!IMPORTANT USAGE NOTE!!!
+ /// Users of this class should set the RefCheckThreshold property
+ /// explicitly or call ScavengeReferences every once in a while to
+ /// remove dead references.
+ /// Also avoid calling Remove(item). Instead call RemoveByHashCode(item)
+ /// to make sure dead refs are removed.
+ /// </summary>
+ internal class WeakRefCollection : IList
+ {
+ internal WeakRefCollection() : this(4) { }
+
+ internal WeakRefCollection(int size) => InnerList = new ArrayList(size);
+
+ internal ArrayList InnerList { get; }
+
+ /// <summary>
+ /// Indicates the value where the collection should check its items to remove dead weakref left over.
+ /// Note: When GC collects weak refs from this collection the WeakRefObject identity changes since its
+ /// Target becomes null. This makes the item unrecognizable by the collection and cannot be
+ /// removed - Remove(item) and Contains(item) will not find it anymore.
+ /// A value of int.MaxValue means disabled by default.
+ /// </summary>
+ public int RefCheckThreshold { get; set; } = int.MaxValue;
+
+ public object this[int index]
+ {
+ get
+ {
+ if (InnerList[index] is WeakRefObject weakRef && weakRef.IsAlive)
+ {
+ return weakRef.Target;
+ }
+
+ return null;
+ }
+ set => InnerList[index] = CreateWeakRefObject(value);
+ }
+
+ public void ScavengeReferences()
+ {
+ int currentIndex = 0;
+ int currentCount = Count;
+ for (int i = 0; i < currentCount; i++)
+ {
+ object item = this[currentIndex];
+
+ if (item == null)
+ {
+ InnerList.RemoveAt(currentIndex);
+ }
+ else
+ {
+ // Only incriment if we have not removed the item.
+ currentIndex++;
+ }
+ }
+ }
+
+ public override bool Equals(object obj)
+ {
+ if (!(obj is WeakRefCollection other))
+ {
+ return true;
+ }
+
+ if (other == null || Count != other.Count)
+ {
+ return false;
+ }
+
+ for (int i = 0; i < Count; i++)
+ {
+ if (InnerList[i] != other.InnerList[i])
+ {
+ if (InnerList[i] == null || !InnerList[i].Equals(other.InnerList[i]))
+ {
+ return false;
+ }
+ }
+ }
+
+ return true;
+ }
+
+ public override int GetHashCode() => base.GetHashCode();
+
+ private WeakRefObject CreateWeakRefObject(object value)
+ {
+ if (value == null)
+ {
+ return null;
+ }
+
+ return new WeakRefObject(value);
+ }
+
+ private static void Copy(WeakRefCollection sourceList, int sourceIndex, WeakRefCollection destinationList, int destinationIndex, int length)
+ {
+ if (sourceIndex < destinationIndex)
+ {
+ // We need to copy from the back forward to prevent overwrite if source and
+ // destination lists are the same, so we need to flip the source/dest indices
+ // to point at the end of the spans to be copied.
+ sourceIndex = sourceIndex + length;
+ destinationIndex = destinationIndex + length;
+ for (; length > 0; length--)
+ {
+ destinationList.InnerList[--destinationIndex] = sourceList.InnerList[--sourceIndex];
+ }
+ }
+ else
+ {
+ for (; length > 0; length--)
+ {
+ destinationList.InnerList[destinationIndex++] = sourceList.InnerList[sourceIndex++];
+ }
+ }
+ }
+
+ /// <summary>
+ /// Removes the value using its hash code as its identity.
+ /// This is needed because the underlying item in the collection may have already been collected changing
+ /// the identity of the WeakRefObject making it impossible for the collection to identify it.
+ /// See WeakRefObject for more info.
+ /// </summary>
+ public void RemoveByHashCode(object value)
+ {
+ if (value == null)
+ {
+ return;
+ }
+
+ int hash = value.GetHashCode();
+
+ for (int idx = 0; idx < InnerList.Count; idx++)
+ {
+ if (InnerList[idx] != null && InnerList[idx].GetHashCode() == hash)
+ {
+ RemoveAt(idx);
+ return;
+ }
+ }
+ }
+
+ public void Clear() => InnerList.Clear();
+
+ public bool IsFixedSize => InnerList.IsFixedSize;
+
+ public bool Contains(object value) => InnerList.Contains(CreateWeakRefObject(value));
+
+ public void RemoveAt(int index) => InnerList.RemoveAt(index);
+
+ public void Remove(object value) => InnerList.Remove(CreateWeakRefObject(value));
+
+ public int IndexOf(object value) => InnerList.IndexOf(CreateWeakRefObject(value));
+
+ public void Insert(int index, object value) => InnerList.Insert(index, CreateWeakRefObject(value));
+
+ public int Add(object value)
+ {
+ if (Count > RefCheckThreshold)
+ {
+ ScavengeReferences();
+ }
+
+ return InnerList.Add(CreateWeakRefObject(value));
+ }
+
+ public int Count => InnerList.Count;
+
+ object ICollection.SyncRoot => InnerList.SyncRoot;
+
+ public bool IsReadOnly => InnerList.IsReadOnly;
+
+ public void CopyTo(Array array, int index) => InnerList.CopyTo(array, index);
+
+ bool ICollection.IsSynchronized => InnerList.IsSynchronized;
+
+ public IEnumerator GetEnumerator() => InnerList.GetEnumerator();
+
+ /// <summary>
+ /// Wraps a weak ref object.
+ /// WARNING: Use this class carefully!
+ /// When the weak ref is collected, this object looses its identity. This is bad when the object has been
+ /// added to a collection since Contains(WeakRef(item)) and Remove(WeakRef(item)) would not be able to
+ /// identify the item.
+ /// </summary>
+ internal class WeakRefObject
+ {
+ private int _hash;
+ private WeakReference _weakHolder;
+
+ internal WeakRefObject(object obj)
+ {
+ Debug.Assert(obj != null, "Unexpected null object!");
+ _weakHolder = new WeakReference(obj);
+ _hash = obj.GetHashCode();
+ }
+
+ internal bool IsAlive => _weakHolder.IsAlive;
+
+ internal object Target => _weakHolder.Target;
+
+ public override int GetHashCode() => _hash;
+
+ public override bool Equals(object obj)
+ {
+ WeakRefObject other = obj as WeakRefObject;
+
+ if (other == this)
+ {
+ return true;
+ }
+
+ if (other == null)
+ {
+ return false;
+ }
+
+ if (other.Target != Target)
+ {
+ if (Target == null || !Target.Equals(other.Target))
+ {
+ return false;
+ }
+ }
+
+ return true;
+ }
+ }
+ }
+ }
+}
diff --git a/src/System.Drawing.Common/src/System/Drawing/Drawing2D/AdjustableArrowCap.cs b/src/System.Drawing.Common/src/System/Drawing/Drawing2D/AdjustableArrowCap.cs
index 9568662f04..9aacda85d8 100644
--- a/src/System.Drawing.Common/src/System/Drawing/Drawing2D/AdjustableArrowCap.cs
+++ b/src/System.Drawing.Common/src/System/Drawing/Drawing2D/AdjustableArrowCap.cs
@@ -16,10 +16,7 @@ namespace System.Drawing.Drawing2D
{
IntPtr nativeCap;
int status = SafeNativeMethods.Gdip.GdipCreateAdjustableArrowCap(height, width, isFilled, out nativeCap);
-
- if (status != SafeNativeMethods.Gdip.Ok)
- throw SafeNativeMethods.Gdip.StatusException(status);
-
+ SafeNativeMethods.Gdip.CheckStatus(status);
SetNativeLineCap(nativeCap);
}
@@ -28,18 +25,13 @@ namespace System.Drawing.Drawing2D
get
{
int status = SafeNativeMethods.Gdip.GdipGetAdjustableArrowCapHeight(new HandleRef(this, nativeCap), out float height);
-
- if (status != SafeNativeMethods.Gdip.Ok)
- throw SafeNativeMethods.Gdip.StatusException(status);
-
+ SafeNativeMethods.Gdip.CheckStatus(status);
return height;
}
set
{
int status = SafeNativeMethods.Gdip.GdipSetAdjustableArrowCapHeight(new HandleRef(this, nativeCap), value);
-
- if (status != SafeNativeMethods.Gdip.Ok)
- throw SafeNativeMethods.Gdip.StatusException(status);
+ SafeNativeMethods.Gdip.CheckStatus(status);
}
}
@@ -48,18 +40,13 @@ namespace System.Drawing.Drawing2D
get
{
int status = SafeNativeMethods.Gdip.GdipGetAdjustableArrowCapWidth(new HandleRef(this, nativeCap), out float width);
-
- if (status != SafeNativeMethods.Gdip.Ok)
- throw SafeNativeMethods.Gdip.StatusException(status);
-
+ SafeNativeMethods.Gdip.CheckStatus(status);
return width;
}
set
{
int status = SafeNativeMethods.Gdip.GdipSetAdjustableArrowCapWidth(new HandleRef(this, nativeCap), value);
-
- if (status != SafeNativeMethods.Gdip.Ok)
- throw SafeNativeMethods.Gdip.StatusException(status);
+ SafeNativeMethods.Gdip.CheckStatus(status);
}
}
@@ -68,18 +55,13 @@ namespace System.Drawing.Drawing2D
get
{
int status = SafeNativeMethods.Gdip.GdipGetAdjustableArrowCapMiddleInset(new HandleRef(this, nativeCap), out float middleInset);
-
- if (status != SafeNativeMethods.Gdip.Ok)
- throw SafeNativeMethods.Gdip.StatusException(status);
-
+ SafeNativeMethods.Gdip.CheckStatus(status);
return middleInset;
}
set
{
int status = SafeNativeMethods.Gdip.GdipSetAdjustableArrowCapMiddleInset(new HandleRef(this, nativeCap), value);
-
- if (status != SafeNativeMethods.Gdip.Ok)
- throw SafeNativeMethods.Gdip.StatusException(status);
+ SafeNativeMethods.Gdip.CheckStatus(status);
}
}
@@ -88,18 +70,13 @@ namespace System.Drawing.Drawing2D
get
{
int status = SafeNativeMethods.Gdip.GdipGetAdjustableArrowCapFillState(new HandleRef(this, nativeCap), out bool isFilled);
-
- if (status != SafeNativeMethods.Gdip.Ok)
- throw SafeNativeMethods.Gdip.StatusException(status);
-
+ SafeNativeMethods.Gdip.CheckStatus(status);
return isFilled;
}
set
{
int status = SafeNativeMethods.Gdip.GdipSetAdjustableArrowCapFillState(new HandleRef(this, nativeCap), value);
-
- if (status != SafeNativeMethods.Gdip.Ok)
- throw SafeNativeMethods.Gdip.StatusException(status);
+ SafeNativeMethods.Gdip.CheckStatus(status);
}
}
}
diff --git a/src/System.Drawing.Common/src/System/Drawing/Drawing2D/GraphicsPath.cs b/src/System.Drawing.Common/src/System/Drawing/Drawing2D/GraphicsPath.cs
index 2b47d6c8e5..b819ec198c 100644
--- a/src/System.Drawing.Common/src/System/Drawing/Drawing2D/GraphicsPath.cs
+++ b/src/System.Drawing.Common/src/System/Drawing/Drawing2D/GraphicsPath.cs
@@ -171,11 +171,9 @@ namespace System.Drawing.Drawing2D
}
set
{
- //validate the FillMode enum
- //valid values are 0x0 to 0x1
- if (!ClientUtils.IsEnumValid(value, unchecked((int)value), (int)FillMode.Alternate, (int)FillMode.Winding))
+ if (value < FillMode.Alternate || value > FillMode.Winding)
{
- throw new InvalidEnumArgumentException("value", unchecked((int)value), typeof(FillMode));
+ throw new InvalidEnumArgumentException(nameof(value), unchecked((int)value), typeof(FillMode));
}
int status = SafeNativeMethods.Gdip.GdipSetPathFillMode(new HandleRef(this, nativePath), (int)value);
@@ -886,7 +884,7 @@ namespace System.Drawing.Drawing2D
public void AddString(string s, FontFamily family, int style, float emSize,
Point origin, StringFormat format)
{
- GPRECT rect = new GPRECT(origin.X, origin.Y, 0, 0);
+ var rect = new GPRECT(origin.X, origin.Y, 0, 0);
int status = SafeNativeMethods.Gdip.GdipAddPathStringI(new HandleRef(this, nativePath),
s,
diff --git a/src/System.Drawing.Common/src/System/Drawing/Drawing2D/LinearGradientBrush.cs b/src/System.Drawing.Common/src/System/Drawing/Drawing2D/LinearGradientBrush.cs
index 2b459c2abc..974fb906b7 100644
--- a/src/System.Drawing.Common/src/System/Drawing/Drawing2D/LinearGradientBrush.cs
+++ b/src/System.Drawing.Common/src/System/Drawing/Drawing2D/LinearGradientBrush.cs
@@ -43,8 +43,7 @@ namespace System.Drawing.Drawing2D
public LinearGradientBrush(RectangleF rect, Color color1, Color color2, LinearGradientMode linearGradientMode)
{
- // The valid values for LinearGgradientMode are 0 to 3.
- if (!ClientUtils.IsEnumValid(linearGradientMode, unchecked((int)linearGradientMode), (int)LinearGradientMode.Horizontal, (int)LinearGradientMode.BackwardDiagonal))
+ if (linearGradientMode < LinearGradientMode.Horizontal || linearGradientMode > LinearGradientMode.BackwardDiagonal)
{
throw new InvalidEnumArgumentException(nameof(linearGradientMode), unchecked((int)linearGradientMode), typeof(LinearGradientMode));
}
@@ -69,8 +68,7 @@ namespace System.Drawing.Drawing2D
public LinearGradientBrush(Rectangle rect, Color color1, Color color2, LinearGradientMode linearGradientMode)
{
- // The valid values for LinearGgradientMode are 0 to 3.
- if (!ClientUtils.IsEnumValid(linearGradientMode, unchecked((int)linearGradientMode), (int)LinearGradientMode.Horizontal, (int)LinearGradientMode.BackwardDiagonal))
+ if (linearGradientMode < LinearGradientMode.Horizontal || linearGradientMode > LinearGradientMode.BackwardDiagonal)
{
throw new InvalidEnumArgumentException(nameof(linearGradientMode), unchecked((int)linearGradientMode), typeof(LinearGradientMode));
}
@@ -460,8 +458,7 @@ namespace System.Drawing.Drawing2D
}
set
{
- // Valid values of WrapMode are 0 to 4.
- if (!ClientUtils.IsEnumValid(value, unchecked((int)value), (int)WrapMode.Tile, (int)WrapMode.Clamp))
+ if (value < WrapMode.Tile || value > WrapMode.Clamp)
{
throw new InvalidEnumArgumentException(nameof(value), unchecked((int)value), typeof(WrapMode));
}
diff --git a/src/System.Drawing.Common/src/System/Drawing/Drawing2D/PathGradientBrush.cs b/src/System.Drawing.Common/src/System/Drawing/Drawing2D/PathGradientBrush.cs
index 04cdcede57..c0b91f93e3 100644
--- a/src/System.Drawing.Common/src/System/Drawing/Drawing2D/PathGradientBrush.cs
+++ b/src/System.Drawing.Common/src/System/Drawing/Drawing2D/PathGradientBrush.cs
@@ -16,13 +16,13 @@ namespace System.Drawing.Drawing2D
public PathGradientBrush(PointF[] points, WrapMode wrapMode)
{
if (points == null)
- throw new ArgumentNullException("points");
-
- //validate the WrapMode enum
- //valid values are 0x0 to 0x4
- if (!ClientUtils.IsEnumValid(wrapMode, unchecked((int)wrapMode), (int)WrapMode.Tile, (int)WrapMode.Clamp))
{
- throw new InvalidEnumArgumentException("wrapMode", unchecked((int)wrapMode), typeof(WrapMode));
+ throw new ArgumentNullException(nameof(points));
+ }
+
+ if (wrapMode < WrapMode.Tile || wrapMode > WrapMode.Clamp)
+ {
+ throw new InvalidEnumArgumentException(nameof(wrapMode), unchecked((int)wrapMode), typeof(WrapMode));
}
IntPtr pointsBuf = SafeNativeMethods.Gdip.ConvertPointToMemory(points);
@@ -56,12 +56,13 @@ namespace System.Drawing.Drawing2D
public PathGradientBrush(Point[] points, WrapMode wrapMode)
{
if (points == null)
- throw new ArgumentNullException("points");
+ {
+ throw new ArgumentNullException(nameof(points));
+ }
- //validate the WrapMode enum
- if (!ClientUtils.IsEnumValid(wrapMode, unchecked((int)wrapMode), (int)WrapMode.Tile, (int)WrapMode.Clamp))
+ if (wrapMode < WrapMode.Tile || wrapMode > WrapMode.Clamp)
{
- throw new InvalidEnumArgumentException("wrapMode", unchecked((int)wrapMode), typeof(WrapMode));
+ throw new InvalidEnumArgumentException(nameof(wrapMode), unchecked((int)wrapMode), typeof(WrapMode));
}
IntPtr pointsBuf = SafeNativeMethods.Gdip.ConvertPointToMemory(points);
@@ -93,7 +94,9 @@ namespace System.Drawing.Drawing2D
public PathGradientBrush(GraphicsPath path)
{
if (path == null)
- throw new ArgumentNullException("path");
+ {
+ throw new ArgumentNullException(nameof(path));
+ }
IntPtr nativeBrush;
int status = SafeNativeMethods.Gdip.GdipCreatePathGradientFromPath(new HandleRef(path, path.nativePath), out nativeBrush);
@@ -584,10 +587,9 @@ namespace System.Drawing.Drawing2D
}
set
{
- //validate the WrapMode enum
- if (!ClientUtils.IsEnumValid(value, unchecked((int)value), (int)WrapMode.Tile, (int)WrapMode.Clamp))
+ if (value < WrapMode.Tile || value > WrapMode.Clamp)
{
- throw new InvalidEnumArgumentException("value", unchecked((int)value), typeof(WrapMode));
+ throw new InvalidEnumArgumentException(nameof(value), unchecked((int)value), typeof(WrapMode));
}
int status = SafeNativeMethods.Gdip.GdipSetPathGradientWrapMode(new HandleRef(this, NativeBrush), unchecked((int)value));
diff --git a/src/System.Drawing.Common/src/System/Drawing/Font.cs b/src/System.Drawing.Common/src/System/Drawing/Font.cs
index bc464d53ea..763165287d 100644
--- a/src/System.Drawing.Common/src/System/Drawing/Font.cs
+++ b/src/System.Drawing.Common/src/System/Drawing/Font.cs
@@ -100,7 +100,6 @@ namespace System.Drawing
Initialize(familyName, emSize, style, unit, gdiCharSet, IsVerticalName(familyName));
}
-
/// <summary>
/// Initializes a new instance of the <see cref='Font'/> class with the specified attributes.
/// </summary>
@@ -187,27 +186,18 @@ namespace System.Drawing
_nativeFont = nativeFont;
status = SafeNativeMethods.Gdip.GdipGetFontUnit(new HandleRef(this, nativeFont), out unit);
-
- if (status != SafeNativeMethods.Gdip.Ok)
- throw SafeNativeMethods.Gdip.StatusException(status);
+ SafeNativeMethods.Gdip.CheckStatus(status);
status = SafeNativeMethods.Gdip.GdipGetFontSize(new HandleRef(this, nativeFont), out size);
-
- if (status != SafeNativeMethods.Gdip.Ok)
- throw SafeNativeMethods.Gdip.StatusException(status);
+ SafeNativeMethods.Gdip.CheckStatus(status);
status = SafeNativeMethods.Gdip.GdipGetFontStyle(new HandleRef(this, nativeFont), out style);
-
- if (status != SafeNativeMethods.Gdip.Ok)
- throw SafeNativeMethods.Gdip.StatusException(status);
+ SafeNativeMethods.Gdip.CheckStatus(status);
status = SafeNativeMethods.Gdip.GdipGetFamily(new HandleRef(this, nativeFont), out nativeFamily);
-
- if (status != SafeNativeMethods.Gdip.Ok)
- throw SafeNativeMethods.Gdip.StatusException(status);
+ SafeNativeMethods.Gdip.CheckStatus(status);
SetFontFamily(new FontFamily(nativeFamily));
-
Initialize(_fontFamily, size, style, unit, gdiCharSet, gdiVerticalFont);
}
@@ -218,7 +208,7 @@ namespace System.Drawing
{
_originalFontName = familyName;
- SetFontFamily(new FontFamily(StripVerticalName(familyName), true /* createDefaultOnFail */ ));
+ SetFontFamily(new FontFamily(StripVerticalName(familyName), createDefaultOnFail: true));
Initialize(_fontFamily, emSize, style, unit, gdiCharSet, gdiVerticalFont);
}
@@ -229,12 +219,12 @@ namespace System.Drawing
{
if (family == null)
{
- throw new ArgumentNullException("family");
+ throw new ArgumentNullException(nameof(family));
}
if (float.IsNaN(emSize) || float.IsInfinity(emSize) || emSize <= 0)
{
- throw new ArgumentException(SR.Format(SR.InvalidBoundArgument, "emSize", emSize, 0, "System.Single.MaxValue"), "emSize");
+ throw new ArgumentException(SR.Format(SR.InvalidBoundArgument, nameof(emSize), emSize, 0, "System.Single.MaxValue"), nameof(emSize));
}
int status;
@@ -258,9 +248,7 @@ namespace System.Drawing
// Get actual size.
status = SafeNativeMethods.Gdip.GdipGetFontSize(new HandleRef(this, _nativeFont), out _fontSize);
-
- if (status != SafeNativeMethods.Gdip.Ok)
- throw SafeNativeMethods.Gdip.StatusException(status);
+ SafeNativeMethods.Gdip.CheckStatus(status);
}
/// <summary>
@@ -268,36 +256,31 @@ namespace System.Drawing
/// </summary>
public static Font FromHfont(IntPtr hfont)
{
- SafeNativeMethods.LOGFONT lf = new SafeNativeMethods.LOGFONT();
+ var lf = new SafeNativeMethods.LOGFONT();
SafeNativeMethods.GetObject(new HandleRef(null, hfont), lf);
-
- Font result;
+
IntPtr screenDC = UnsafeNativeMethods.GetDC(NativeMethods.NullHandleRef);
try
{
- result = Font.FromLogFont(lf, screenDC);
+ return FromLogFont(lf, screenDC);
}
finally
{
UnsafeNativeMethods.ReleaseDC(NativeMethods.NullHandleRef, new HandleRef(null, screenDC));
}
-
- return result;
}
public static Font FromLogFont(object lf)
{
IntPtr screenDC = UnsafeNativeMethods.GetDC(NativeMethods.NullHandleRef);
- Font result;
try
{
- result = Font.FromLogFont(lf, screenDC);
+ return FromLogFont(lf, screenDC);
}
finally
{
UnsafeNativeMethods.ReleaseDC(NativeMethods.NullHandleRef, new HandleRef(null, screenDC));
}
- return result;
}
public static Font FromLogFont(object lf, IntPtr hdc)
@@ -307,13 +290,19 @@ namespace System.Drawing
// Special case this incredibly common error message to give more information
if (status == SafeNativeMethods.Gdip.NotTrueTypeFont)
+ {
throw new ArgumentException(SR.Format(SR.GdiplusNotTrueTypeFont_NoName));
+ }
else if (status != SafeNativeMethods.Gdip.Ok)
+ {
throw SafeNativeMethods.Gdip.StatusException(status);
+ }
// GDI+ returns font = 0 even though the status is Ok.
if (font == IntPtr.Zero)
+ {
throw new ArgumentException(SR.Format(SR.GdiplusNotTrueTypeFont, lf.ToString()));
+ }
#pragma warning disable 0618
bool gdiVerticalFont = (Marshal.ReadInt16(lf, LogFontNameOffset) == (short)'@');
@@ -327,48 +316,37 @@ namespace System.Drawing
public static Font FromHdc(IntPtr hdc)
{
IntPtr font = IntPtr.Zero;
-
int status = SafeNativeMethods.Gdip.GdipCreateFontFromDC(new HandleRef(null, hdc), ref font);
// Special case this incredibly common error message to give more information
if (status == SafeNativeMethods.Gdip.NotTrueTypeFont)
+ {
throw new ArgumentException(SR.Format(SR.GdiplusNotTrueTypeFont_NoName));
+ }
else if (status != SafeNativeMethods.Gdip.Ok)
+ {
throw SafeNativeMethods.Gdip.StatusException(status);
+ }
return new Font(font, 0, false);
}
-
/// <summary>
/// Creates an exact copy of this <see cref='Font'/>.
/// </summary>
public object Clone()
{
- IntPtr cloneFont = IntPtr.Zero;
+ IntPtr clonedFont = IntPtr.Zero;
+ int status = SafeNativeMethods.Gdip.GdipCloneFont(new HandleRef(this, _nativeFont), out clonedFont);
+ SafeNativeMethods.Gdip.CheckStatus(status);
- int status = SafeNativeMethods.Gdip.GdipCloneFont(new HandleRef(this, _nativeFont), out cloneFont);
-
- if (status != SafeNativeMethods.Gdip.Ok)
- throw SafeNativeMethods.Gdip.StatusException(status);
-
- Font newCloneFont = new Font(cloneFont, _gdiCharSet, _gdiVerticalFont);
-
- return newCloneFont;
+ return new Font(clonedFont, _gdiCharSet, _gdiVerticalFont);
}
-
/// <summary>
/// Get native GDI+ object pointer. This property triggers the creation of the GDI+ native object if not initialized yet.
/// </summary>
- internal IntPtr NativeFont
- {
- get
- {
- Debug.Assert(_nativeFont != IntPtr.Zero, "this.nativeFont == IntPtr.Zero.");
- return _nativeFont;
- }
- }
+ internal IntPtr NativeFont => _nativeFont;
/// <summary>
/// Gets the <see cref='Drawing.FontFamily'/> of this <see cref='Font'/>.
@@ -397,10 +375,7 @@ namespace System.Drawing
/// <summary>
/// Cleans up Windows resources for this <see cref='Font'/>.
/// </summary>
- ~Font()
- {
- Dispose(false);
- }
+ ~Font() => Dispose(false);
/// <summary>
/// Cleans up Windows resources for this <see cref='Font'/>.
@@ -425,14 +400,8 @@ namespace System.Drawing
Debug.Assert(status == SafeNativeMethods.Gdip.Ok, "GDI+ returned an error status: " + status.ToString(CultureInfo.InvariantCulture));
#endif
}
- catch (Exception ex)
+ catch (Exception ex) when (!ClientUtils.IsCriticalException(ex))
{
- if (ClientUtils.IsCriticalException(ex))
- {
- throw;
- }
-
- Debug.Fail("Exception thrown during Dispose: " + ex.ToString());
}
finally
{
@@ -441,39 +410,24 @@ namespace System.Drawing
}
}
- private static bool IsVerticalName(string familyName)
- {
- return familyName != null && familyName.Length > 0 && familyName[0] == '@';
- }
+ private static bool IsVerticalName(string familyName) => familyName?.Length > 0 && familyName[0] == '@';
/// <summary>
/// Gets a value indicating whether this <see cref='System.Drawing.Font'/> is bold.
/// </summary>
[DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)]
- public bool Bold
- {
- get
- {
- return (Style & FontStyle.Bold) != 0;
- }
- }
+ public bool Bold => (Style & FontStyle.Bold) != 0;
/// <summary>
- /// Returns the GDI char set for this instance of a font. This will only
- /// be valid if this font was created from a classic GDI font definition,
- /// like a LOGFONT or HFONT, or it was passed into the constructor.
+ /// Returns the GDI char set for this instance of a font. This will only
+ /// be valid if this font was created from a classic GDI font definition,
+ /// like a LOGFONT or HFONT, or it was passed into the constructor.
///
- /// This is here for compatability with native Win32 intrinsic controls
- /// on non-Unicode platforms.
+ /// This is here for compatability with native Win32 intrinsic controls
+ /// on non-Unicode platforms.
/// </summary>
[DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)]
- public byte GdiCharSet
- {
- get
- {
- return _gdiCharSet;
- }
- }
+ public byte GdiCharSet => _gdiCharSet;
/// <summary>
/// Determines if this font was created to represt a GDI vertical font. This will only be valid if this font
@@ -482,67 +436,37 @@ namespace System.Drawing
/// This is here for compatability with native Win32 intrinsic controls on non-Unicode platforms.
/// </summary>
[DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)]
- public bool GdiVerticalFont
- {
- get
- {
- return _gdiVerticalFont;
- }
- }
+ public bool GdiVerticalFont => _gdiVerticalFont;
/// <summary>
/// Gets a value indicating whether this <see cref='Font'/> is Italic.
/// </summary>
[DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)]
- public bool Italic
- {
- get
- {
- return (Style & FontStyle.Italic) != 0;
- }
- }
+ public bool Italic => (Style & FontStyle.Italic) != 0;
/// <summary>
/// Gets the face name of this <see cref='Font'/> .
/// </summary>
[DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)]
- public string Name
- {
- get { return FontFamily.Name; }
- }
+ public string Name => FontFamily.Name;
/// <summary>
/// This property is required by the framework and not intended to be used directly.
/// </summary>
[Browsable(false)]
- public string OriginalFontName
- {
- get { return _originalFontName; }
- }
+ public string OriginalFontName => _originalFontName;
/// <summary>
/// Gets a value indicating whether this <see cref='Font'/> is strikeout (has a line through it).
/// </summary>
[DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)]
- public bool Strikeout
- {
- get
- {
- return (Style & FontStyle.Strikeout) != 0;
- }
- }
+ public bool Strikeout => (Style & FontStyle.Strikeout) != 0;
/// <summary>
/// Gets a value indicating whether this <see cref='Font'/> is underlined.
/// </summary>
[DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)]
- public bool Underline
- {
- get
- {
- return (Style & FontStyle.Underline) != 0;
- }
- }
+ public bool Underline => (Style & FontStyle.Underline) != 0;
/// <summary>
/// Returns a value indicating whether the specified object is a <see cref='Font'/> equivalent to this
@@ -554,17 +478,14 @@ namespace System.Drawing
{
return true;
}
-
- Font font = obj as Font;
-
- if (font == null)
+
+ if (!(obj is Font font))
{
return false;
}
// Note: If this and/or the passed-in font are disposed, this method can still return true since we check for cached properties
// here.
-
// We need to call properties on the passed-in object since it could be a proxy in a remoting scenario and proxies don't
// have access to private/internal fields.
return font.FontFamily.Equals(FontFamily) &&
@@ -575,24 +496,23 @@ namespace System.Drawing
font.Unit == Unit;
}
-
-
/// <summary>
/// Gets the hash code for this <see cref='Font'/>.
/// </summary>
public override int GetHashCode()
{
- return unchecked((int)((((UInt32)_fontStyle << 13) | ((UInt32)_fontStyle >> 19)) ^
- (((UInt32)_fontUnit << 26) | ((UInt32)_fontUnit >> 6)) ^
- (((UInt32)_fontSize << 7) | ((UInt32)_fontSize >> 25))));
+ return unchecked((int)((((uint)_fontStyle << 13) | ((uint)_fontStyle >> 19)) ^
+ (((uint)_fontUnit << 26) | ((uint)_fontUnit >> 6)) ^
+ (((uint)_fontSize << 7) | ((uint)_fontSize >> 25))));
}
private static string StripVerticalName(string familyName)
{
- if (familyName != null && familyName.Length > 1 && familyName[0] == '@')
+ if (familyName?.Length > 1 && familyName[0] == '@')
{
return familyName.Substring(1);
}
+
return familyName;
}
@@ -616,7 +536,6 @@ namespace System.Drawing
try
{
Graphics graphics = Graphics.FromHdcInternal(screenDC);
-
try
{
ToLogFont(logFont, graphics);
@@ -635,7 +554,9 @@ namespace System.Drawing
public unsafe void ToLogFont(object logFont, Graphics graphics)
{
if (graphics == null)
- throw new ArgumentNullException("graphics");
+ {
+ throw new ArgumentNullException(nameof(graphics));
+ }
int status = SafeNativeMethods.Gdip.GdipGetLogFontW(new HandleRef(this, NativeFont), new HandleRef(graphics, graphics.NativeGraphics), logFont);
@@ -660,8 +581,7 @@ namespace System.Drawing
}
#pragma warning restore 0618
- if (status != SafeNativeMethods.Gdip.Ok)
- throw SafeNativeMethods.Gdip.StatusException(status);
+ SafeNativeMethods.Gdip.CheckStatus(status);
}
/// <summary>
@@ -669,12 +589,10 @@ namespace System.Drawing
/// </summary>
public IntPtr ToHfont()
{
- SafeNativeMethods.LOGFONT lf = new SafeNativeMethods.LOGFONT();
-
+ var lf = new SafeNativeMethods.LOGFONT();
ToLogFont(lf);
IntPtr handle = IntUnsafeNativeMethods.IntCreateFontIndirect(lf);
-
if (handle == IntPtr.Zero)
{
throw new Win32Exception();
@@ -689,74 +607,53 @@ namespace System.Drawing
public float GetHeight(Graphics graphics)
{
if (graphics == null)
- throw new ArgumentNullException("graphics");
-
- float ht;
-
- int status = SafeNativeMethods.Gdip.GdipGetFontHeight(new HandleRef(this, NativeFont), new HandleRef(graphics, graphics.NativeGraphics), out ht);
+ {
+ throw new ArgumentNullException(nameof(graphics));
+ }
- if (status != SafeNativeMethods.Gdip.Ok)
- throw SafeNativeMethods.Gdip.StatusException(status);
+ float height;
+ int status = SafeNativeMethods.Gdip.GdipGetFontHeight(new HandleRef(this, NativeFont), new HandleRef(graphics, graphics.NativeGraphics), out height);
+ SafeNativeMethods.Gdip.CheckStatus(status);
- return ht;
+ return height;
}
public float GetHeight()
{
IntPtr screenDC = UnsafeNativeMethods.GetDC(NativeMethods.NullHandleRef);
- float height = 0.0f;
try
{
using (Graphics graphics = Graphics.FromHdcInternal(screenDC))
{
- height = GetHeight(graphics);
+ return GetHeight(graphics);
}
}
finally
{
UnsafeNativeMethods.ReleaseDC(NativeMethods.NullHandleRef, new HandleRef(null, screenDC));
}
-
- return height;
}
public float GetHeight(float dpi)
{
- float ht;
-
- int status = SafeNativeMethods.Gdip.GdipGetFontHeightGivenDPI(new HandleRef(this, NativeFont), dpi, out ht);
-
- if (status != SafeNativeMethods.Gdip.Ok)
- throw SafeNativeMethods.Gdip.StatusException(status);
+ float height;
+ int status = SafeNativeMethods.Gdip.GdipGetFontHeightGivenDPI(new HandleRef(this, NativeFont), dpi, out height);
+ SafeNativeMethods.Gdip.CheckStatus(status);
- return ht;
+ return height;
}
/// <summary>
/// Gets style information for this <see cref='Font'/>.
/// </summary>
- [
- Browsable(false)
- ]
- public FontStyle Style
- {
- get
- {
- return _fontStyle;
- }
- }
+ [Browsable(false)]
+ public FontStyle Style => _fontStyle;
// Return value is in Unit (the unit the font was created in)
/// <summary>
/// Gets the size of this <see cref='Font'/>.
/// </summary>
- public float Size
- {
- get
- {
- return _fontSize;
- }
- }
+ public float Size => _fontSize;
/// <summary>
/// Gets the size, in points, of this <see cref='Font'/>.
@@ -767,30 +664,25 @@ namespace System.Drawing
get
{
if (Unit == GraphicsUnit.Point)
- return Size;
- else
{
- float emHeightInPoints;
-
- IntPtr screenDC = UnsafeNativeMethods.GetDC(NativeMethods.NullHandleRef);
+ return Size;
+ }
- try
- {
- using (Graphics graphics = Graphics.FromHdcInternal(screenDC))
- {
- float pixelsPerPoint = (float)(graphics.DpiY / 72.0);
- float lineSpacingInPixels = GetHeight(graphics);
- float emHeightInPixels = lineSpacingInPixels * FontFamily.GetEmHeight(Style) / FontFamily.GetLineSpacing(Style);
-
- emHeightInPoints = emHeightInPixels / pixelsPerPoint;
- }
- }
- finally
+ IntPtr screenDC = UnsafeNativeMethods.GetDC(NativeMethods.NullHandleRef);
+ try
+ {
+ using (Graphics graphics = Graphics.FromHdcInternal(screenDC))
{
- UnsafeNativeMethods.ReleaseDC(NativeMethods.NullHandleRef, new HandleRef(null, screenDC));
- }
+ float pixelsPerPoint = (float)(graphics.DpiY / 72.0);
+ float lineSpacingInPixels = GetHeight(graphics);
+ float emHeightInPixels = lineSpacingInPixels * FontFamily.GetEmHeight(Style) / FontFamily.GetLineSpacing(Style);
- return emHeightInPoints;
+ return emHeightInPixels / pixelsPerPoint;
+ }
+ }
+ finally
+ {
+ UnsafeNativeMethods.ReleaseDC(NativeMethods.NullHandleRef, new HandleRef(null, screenDC));
}
}
}
@@ -798,60 +690,27 @@ namespace System.Drawing
/// <summary>
/// Gets the unit of measure for this <see cref='Font'/>.
/// </summary>
- public GraphicsUnit Unit
- {
- get
- {
- return _fontUnit;
- }
- }
+ public GraphicsUnit Unit => _fontUnit;
/// <summary>
/// Gets the height of this <see cref='Font'/>.
/// </summary>
- [
- Browsable(false)
- ]
- public int Height
- {
- get
- {
- return (int)Math.Ceiling(GetHeight());
- }
- }
+ [Browsable(false)]
+ public int Height => (int)Math.Ceiling(GetHeight());
/// <summary>
/// Returns true if this <see cref='Font'/> is a SystemFont.
/// </summary>
- [
- Browsable(false)
- ]
- public bool IsSystemFont
- {
- get
- {
- return !String.IsNullOrEmpty(_systemFontName);
- }
- }
+ [Browsable(false)]
+ public bool IsSystemFont => !string.IsNullOrEmpty(_systemFontName);
/// <summary>
/// Gets the name of this <see cref='Drawing.SystemFont'/>.
/// </summary>
- [
- Browsable(false)
- ]
- public string SystemFontName
- {
- get
- {
- return _systemFontName;
- }
- }
+ [Browsable(false)]
+ public string SystemFontName => _systemFontName;
// This is used by SystemFonts when constructing a system Font objects.
- internal void SetSystemFontName(string systemFontName)
- {
- _systemFontName = systemFontName;
- }
+ internal void SetSystemFontName(string systemFontName) => _systemFontName = systemFontName;
}
}
diff --git a/src/System.Drawing.Common/src/System/Drawing/FontFamily.cs b/src/System.Drawing.Common/src/System/Drawing/FontFamily.cs
index 2ee595af32..dbb2d2ee6d 100644
--- a/src/System.Drawing.Common/src/System/Drawing/FontFamily.cs
+++ b/src/System.Drawing.Common/src/System/Drawing/FontFamily.cs
@@ -30,7 +30,6 @@ namespace System.Drawing
private void SetNativeFamily(IntPtr family)
{
Debug.Assert(_nativeFamily == IntPtr.Zero, "Setting GDI+ native font family when already initialized.");
- Debug.Assert(family != IntPtr.Zero, "Setting GDI+ native font family to null.");
_nativeFamily = family;
#if DEBUG
diff --git a/src/System.Drawing.Common/src/System/Drawing/Gdiplus.cs b/src/System.Drawing.Common/src/System/Drawing/Gdiplus.cs
index 165ebcf7d3..b7a2c6e61f 100644
--- a/src/System.Drawing.Common/src/System/Drawing/Gdiplus.cs
+++ b/src/System.Drawing.Common/src/System/Drawing/Gdiplus.cs
@@ -6,74 +6,68 @@ using System.Internal;
using System.Text;
using System.Collections;
using System.Runtime.InteropServices;
-using System.ComponentModel;
using System.Diagnostics;
using System.Diagnostics.CodeAnalysis;
-using System;
using System.IO;
-using Microsoft.Win32;
-using System.Drawing;
using System.Drawing.Internal;
using System.Drawing.Imaging;
using System.Drawing.Text;
using System.Drawing.Drawing2D;
using System.Threading;
-using System.Security.Permissions;
using System.Security;
using System.Runtime.ConstrainedExecution;
-using System.Globalization;
-using System.Runtime.Versioning;
-
-[assembly: System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Reliability", "CA2006:UseSafeHandleToEncapsulateNativeResources", Scope = "member", Target = "System.Drawing.SafeNativeMethods+BITMAP.bmBits")]
-[assembly: System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Reliability", "CA2006:UseSafeHandleToEncapsulateNativeResources", Scope = "member", Target = "System.Drawing.SafeNativeMethods+DIBSECTION.dshSection")]
-[assembly: System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Reliability", "CA2006:UseSafeHandleToEncapsulateNativeResources", Scope = "member", Target = "System.Drawing.SafeNativeMethods+Gdip.initToken")]
-[assembly: System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Reliability", "CA2006:UseSafeHandleToEncapsulateNativeResources", Scope = "member", Target = "System.Drawing.SafeNativeMethods+Gdip+StartupInput.DebugEventCallback")]
-[assembly: System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Reliability", "CA2006:UseSafeHandleToEncapsulateNativeResources", Scope = "member", Target = "System.Drawing.SafeNativeMethods+Gdip+StartupOutput.hook")]
-[assembly: System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Reliability", "CA2006:UseSafeHandleToEncapsulateNativeResources", Scope = "member", Target = "System.Drawing.SafeNativeMethods+Gdip+StartupOutput.unhook")]
-[assembly: System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Reliability", "CA2006:UseSafeHandleToEncapsulateNativeResources", Scope = "member", Target = "System.Drawing.SafeNativeMethods+ICONINFO.hbmColor")]
-[assembly: System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Reliability", "CA2006:UseSafeHandleToEncapsulateNativeResources", Scope = "member", Target = "System.Drawing.SafeNativeMethods+ICONINFO.hbmMask")]
-[assembly: System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Reliability", "CA2006:UseSafeHandleToEncapsulateNativeResources", Scope = "member", Target = "System.Drawing.SafeNativeMethods+MSG.hwnd")]
-[assembly: System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Reliability", "CA2006:UseSafeHandleToEncapsulateNativeResources", Scope = "member", Target = "System.Drawing.SafeNativeMethods+MSG.lParam")]
-[assembly: System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Reliability", "CA2006:UseSafeHandleToEncapsulateNativeResources", Scope = "member", Target = "System.Drawing.SafeNativeMethods+MSG.wParam")]
-[assembly: System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Reliability", "CA2006:UseSafeHandleToEncapsulateNativeResources", Scope = "member", Target = "System.Drawing.SafeNativeMethods+OBJECTHEADER.pInfo")]
-[assembly: System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Reliability", "CA2006:UseSafeHandleToEncapsulateNativeResources", Scope = "member", Target = "System.Drawing.SafeNativeMethods+PICTDESC.union1")]
-[assembly: System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Reliability", "CA2006:UseSafeHandleToEncapsulateNativeResources", Scope = "member", Target = "System.Drawing.SafeNativeMethods+PRINTDLG.hDC")]
-[assembly: System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Reliability", "CA2006:UseSafeHandleToEncapsulateNativeResources", Scope = "member", Target = "System.Drawing.SafeNativeMethods+PRINTDLG.hDevMode")]
-[assembly: System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Reliability", "CA2006:UseSafeHandleToEncapsulateNativeResources", Scope = "member", Target = "System.Drawing.SafeNativeMethods+PRINTDLG.hDevNames")]
-[assembly: System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Reliability", "CA2006:UseSafeHandleToEncapsulateNativeResources", Scope = "member", Target = "System.Drawing.SafeNativeMethods+PRINTDLG.hInstance")]
-[assembly: System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Reliability", "CA2006:UseSafeHandleToEncapsulateNativeResources", Scope = "member", Target = "System.Drawing.SafeNativeMethods+PRINTDLG.hPrintTemplate")]
-[assembly: System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Reliability", "CA2006:UseSafeHandleToEncapsulateNativeResources", Scope = "member", Target = "System.Drawing.SafeNativeMethods+PRINTDLG.hSetupTemplate")]
-[assembly: System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Reliability", "CA2006:UseSafeHandleToEncapsulateNativeResources", Scope = "member", Target = "System.Drawing.SafeNativeMethods+PRINTDLG.hwndOwner")]
-[assembly: System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Reliability", "CA2006:UseSafeHandleToEncapsulateNativeResources", Scope = "member", Target = "System.Drawing.SafeNativeMethods+PRINTDLG.lCustData")]
-[assembly: System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Reliability", "CA2006:UseSafeHandleToEncapsulateNativeResources", Scope = "member", Target = "System.Drawing.SafeNativeMethods+PRINTDLGX86.hDC")]
-[assembly: System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Reliability", "CA2006:UseSafeHandleToEncapsulateNativeResources", Scope = "member", Target = "System.Drawing.SafeNativeMethods+PRINTDLGX86.hDevMode")]
-[assembly: System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Reliability", "CA2006:UseSafeHandleToEncapsulateNativeResources", Scope = "member", Target = "System.Drawing.SafeNativeMethods+PRINTDLGX86.hDevNames")]
-[assembly: System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Reliability", "CA2006:UseSafeHandleToEncapsulateNativeResources", Scope = "member", Target = "System.Drawing.SafeNativeMethods+PRINTDLGX86.hInstance")]
-[assembly: System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Reliability", "CA2006:UseSafeHandleToEncapsulateNativeResources", Scope = "member", Target = "System.Drawing.SafeNativeMethods+PRINTDLGX86.hPrintTemplate")]
-[assembly: System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Reliability", "CA2006:UseSafeHandleToEncapsulateNativeResources", Scope = "member", Target = "System.Drawing.SafeNativeMethods+PRINTDLGX86.hSetupTemplate")]
-[assembly: System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Reliability", "CA2006:UseSafeHandleToEncapsulateNativeResources", Scope = "member", Target = "System.Drawing.SafeNativeMethods+PRINTDLGX86.hwndOwner")]
-[assembly: System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Reliability", "CA2006:UseSafeHandleToEncapsulateNativeResources", Scope = "member", Target = "System.Drawing.SafeNativeMethods+PRINTDLGX86.lCustData")]
-[assembly: System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Performance", "CA1811:AvoidUncalledPrivateCode", Scope = "member", Target = "System.Drawing.SafeNativeMethods+StreamConsts..ctor()")]
-[assembly: System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Performance", "CA1811:AvoidUncalledPrivateCode", Scope = "member", Target = "System.Drawing.SafeNativeMethods+POINT..ctor()")]
-[assembly: System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Performance", "CA1811:AvoidUncalledPrivateCode", Scope = "member", Target = "System.Drawing.SafeNativeMethods+LOGPEN..ctor()")]
-[assembly: System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Performance", "CA1811:AvoidUncalledPrivateCode", Scope = "member", Target = "System.Drawing.SafeNativeMethods+DIBSECTION..ctor()")]
-[assembly: System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Performance", "CA1811:AvoidUncalledPrivateCode", Scope = "member", Target = "System.Drawing.SafeNativeMethods..ctor()")]
-[assembly: System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Performance", "CA1811:AvoidUncalledPrivateCode", Scope = "member", Target = "System.Drawing.SafeNativeMethods+Ole..ctor()")]
-[assembly: System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Performance", "CA1811:AvoidUncalledPrivateCode", Scope = "member", Target = "System.Drawing.SafeNativeMethods+CommonHandles..ctor()")]
-[assembly: System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Performance", "CA1812:AvoidUninstantiatedInternalClasses", Scope = "type", Target = "System.Drawing.SafeNativeMethods+CommonHandles")]
-[assembly: System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Performance", "CA1812:AvoidUninstantiatedInternalClasses", Scope = "type", Target = "System.Drawing.SafeNativeMethods+ENHMETAHEADER")]
-[assembly: System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Performance", "CA1812:AvoidUninstantiatedInternalClasses", Scope = "type", Target = "System.Drawing.SafeNativeMethods+StreamConsts")]
-[assembly: System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Performance", "CA1812:AvoidUninstantiatedInternalClasses", Scope = "type", Target = "System.Drawing.SafeNativeMethods+Ole")]
-[assembly: System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Performance", "CA1812:AvoidUninstantiatedInternalClasses", Scope = "type", Target = "System.Drawing.SafeNativeMethods+Gdip")]
-[assembly: System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Performance", "CA1811:AvoidUncalledPrivateCode", Scope = "member", Target = "System.Drawing.SafeNativeMethods+ENHMETAHEADER..ctor()")]
+using System.Runtime.CompilerServices;
+
+[assembly: SuppressMessage("Microsoft.Reliability", "CA2006:UseSafeHandleToEncapsulateNativeResources", Scope = "member", Target = "System.Drawing.SafeNativeMethods+BITMAP.bmBits")]
+[assembly: SuppressMessage("Microsoft.Reliability", "CA2006:UseSafeHandleToEncapsulateNativeResources", Scope = "member", Target = "System.Drawing.SafeNativeMethods+DIBSECTION.dshSection")]
+[assembly: SuppressMessage("Microsoft.Reliability", "CA2006:UseSafeHandleToEncapsulateNativeResources", Scope = "member", Target = "System.Drawing.SafeNativeMethods+Gdip.initToken")]
+[assembly: SuppressMessage("Microsoft.Reliability", "CA2006:UseSafeHandleToEncapsulateNativeResources", Scope = "member", Target = "System.Drawing.SafeNativeMethods+Gdip+StartupInput.DebugEventCallback")]
+[assembly: SuppressMessage("Microsoft.Reliability", "CA2006:UseSafeHandleToEncapsulateNativeResources", Scope = "member", Target = "System.Drawing.SafeNativeMethods+Gdip+StartupOutput.hook")]
+[assembly: SuppressMessage("Microsoft.Reliability", "CA2006:UseSafeHandleToEncapsulateNativeResources", Scope = "member", Target = "System.Drawing.SafeNativeMethods+Gdip+StartupOutput.unhook")]
+[assembly: SuppressMessage("Microsoft.Reliability", "CA2006:UseSafeHandleToEncapsulateNativeResources", Scope = "member", Target = "System.Drawing.SafeNativeMethods+ICONINFO.hbmColor")]
+[assembly: SuppressMessage("Microsoft.Reliability", "CA2006:UseSafeHandleToEncapsulateNativeResources", Scope = "member", Target = "System.Drawing.SafeNativeMethods+ICONINFO.hbmMask")]
+[assembly: SuppressMessage("Microsoft.Reliability", "CA2006:UseSafeHandleToEncapsulateNativeResources", Scope = "member", Target = "System.Drawing.SafeNativeMethods+MSG.hwnd")]
+[assembly: SuppressMessage("Microsoft.Reliability", "CA2006:UseSafeHandleToEncapsulateNativeResources", Scope = "member", Target = "System.Drawing.SafeNativeMethods+MSG.lParam")]
+[assembly: SuppressMessage("Microsoft.Reliability", "CA2006:UseSafeHandleToEncapsulateNativeResources", Scope = "member", Target = "System.Drawing.SafeNativeMethods+MSG.wParam")]
+[assembly: SuppressMessage("Microsoft.Reliability", "CA2006:UseSafeHandleToEncapsulateNativeResources", Scope = "member", Target = "System.Drawing.SafeNativeMethods+OBJECTHEADER.pInfo")]
+[assembly: SuppressMessage("Microsoft.Reliability", "CA2006:UseSafeHandleToEncapsulateNativeResources", Scope = "member", Target = "System.Drawing.SafeNativeMethods+PICTDESC.union1")]
+[assembly: SuppressMessage("Microsoft.Reliability", "CA2006:UseSafeHandleToEncapsulateNativeResources", Scope = "member", Target = "System.Drawing.SafeNativeMethods+PRINTDLG.hDC")]
+[assembly: SuppressMessage("Microsoft.Reliability", "CA2006:UseSafeHandleToEncapsulateNativeResources", Scope = "member", Target = "System.Drawing.SafeNativeMethods+PRINTDLG.hDevMode")]
+[assembly: SuppressMessage("Microsoft.Reliability", "CA2006:UseSafeHandleToEncapsulateNativeResources", Scope = "member", Target = "System.Drawing.SafeNativeMethods+PRINTDLG.hDevNames")]
+[assembly: SuppressMessage("Microsoft.Reliability", "CA2006:UseSafeHandleToEncapsulateNativeResources", Scope = "member", Target = "System.Drawing.SafeNativeMethods+PRINTDLG.hInstance")]
+[assembly: SuppressMessage("Microsoft.Reliability", "CA2006:UseSafeHandleToEncapsulateNativeResources", Scope = "member", Target = "System.Drawing.SafeNativeMethods+PRINTDLG.hPrintTemplate")]
+[assembly: SuppressMessage("Microsoft.Reliability", "CA2006:UseSafeHandleToEncapsulateNativeResources", Scope = "member", Target = "System.Drawing.SafeNativeMethods+PRINTDLG.hSetupTemplate")]
+[assembly: SuppressMessage("Microsoft.Reliability", "CA2006:UseSafeHandleToEncapsulateNativeResources", Scope = "member", Target = "System.Drawing.SafeNativeMethods+PRINTDLG.hwndOwner")]
+[assembly: SuppressMessage("Microsoft.Reliability", "CA2006:UseSafeHandleToEncapsulateNativeResources", Scope = "member", Target = "System.Drawing.SafeNativeMethods+PRINTDLG.lCustData")]
+[assembly: SuppressMessage("Microsoft.Reliability", "CA2006:UseSafeHandleToEncapsulateNativeResources", Scope = "member", Target = "System.Drawing.SafeNativeMethods+PRINTDLGX86.hDC")]
+[assembly: SuppressMessage("Microsoft.Reliability", "CA2006:UseSafeHandleToEncapsulateNativeResources", Scope = "member", Target = "System.Drawing.SafeNativeMethods+PRINTDLGX86.hDevMode")]
+[assembly: SuppressMessage("Microsoft.Reliability", "CA2006:UseSafeHandleToEncapsulateNativeResources", Scope = "member", Target = "System.Drawing.SafeNativeMethods+PRINTDLGX86.hDevNames")]
+[assembly: SuppressMessage("Microsoft.Reliability", "CA2006:UseSafeHandleToEncapsulateNativeResources", Scope = "member", Target = "System.Drawing.SafeNativeMethods+PRINTDLGX86.hInstance")]
+[assembly: SuppressMessage("Microsoft.Reliability", "CA2006:UseSafeHandleToEncapsulateNativeResources", Scope = "member", Target = "System.Drawing.SafeNativeMethods+PRINTDLGX86.hPrintTemplate")]
+[assembly: SuppressMessage("Microsoft.Reliability", "CA2006:UseSafeHandleToEncapsulateNativeResources", Scope = "member", Target = "System.Drawing.SafeNativeMethods+PRINTDLGX86.hSetupTemplate")]
+[assembly: SuppressMessage("Microsoft.Reliability", "CA2006:UseSafeHandleToEncapsulateNativeResources", Scope = "member", Target = "System.Drawing.SafeNativeMethods+PRINTDLGX86.hwndOwner")]
+[assembly: SuppressMessage("Microsoft.Reliability", "CA2006:UseSafeHandleToEncapsulateNativeResources", Scope = "member", Target = "System.Drawing.SafeNativeMethods+PRINTDLGX86.lCustData")]
+[assembly: SuppressMessage("Microsoft.Performance", "CA1811:AvoidUncalledPrivateCode", Scope = "member", Target = "System.Drawing.SafeNativeMethods+StreamConsts..ctor()")]
+[assembly: SuppressMessage("Microsoft.Performance", "CA1811:AvoidUncalledPrivateCode", Scope = "member", Target = "System.Drawing.SafeNativeMethods+POINT..ctor()")]
+[assembly: SuppressMessage("Microsoft.Performance", "CA1811:AvoidUncalledPrivateCode", Scope = "member", Target = "System.Drawing.SafeNativeMethods+LOGPEN..ctor()")]
+[assembly: SuppressMessage("Microsoft.Performance", "CA1811:AvoidUncalledPrivateCode", Scope = "member", Target = "System.Drawing.SafeNativeMethods+DIBSECTION..ctor()")]
+[assembly: SuppressMessage("Microsoft.Performance", "CA1811:AvoidUncalledPrivateCode", Scope = "member", Target = "System.Drawing.SafeNativeMethods..ctor()")]
+[assembly: SuppressMessage("Microsoft.Performance", "CA1811:AvoidUncalledPrivateCode", Scope = "member", Target = "System.Drawing.SafeNativeMethods+Ole..ctor()")]
+[assembly: SuppressMessage("Microsoft.Performance", "CA1811:AvoidUncalledPrivateCode", Scope = "member", Target = "System.Drawing.SafeNativeMethods+CommonHandles..ctor()")]
+[assembly: SuppressMessage("Microsoft.Performance", "CA1812:AvoidUninstantiatedInternalClasses", Scope = "type", Target = "System.Drawing.SafeNativeMethods+CommonHandles")]
+[assembly: SuppressMessage("Microsoft.Performance", "CA1812:AvoidUninstantiatedInternalClasses", Scope = "type", Target = "System.Drawing.SafeNativeMethods+ENHMETAHEADER")]
+[assembly: SuppressMessage("Microsoft.Performance", "CA1812:AvoidUninstantiatedInternalClasses", Scope = "type", Target = "System.Drawing.SafeNativeMethods+StreamConsts")]
+[assembly: SuppressMessage("Microsoft.Performance", "CA1812:AvoidUninstantiatedInternalClasses", Scope = "type", Target = "System.Drawing.SafeNativeMethods+Ole")]
+[assembly: SuppressMessage("Microsoft.Performance", "CA1812:AvoidUninstantiatedInternalClasses", Scope = "type", Target = "System.Drawing.SafeNativeMethods+Gdip")]
+[assembly: SuppressMessage("Microsoft.Performance", "CA1811:AvoidUncalledPrivateCode", Scope = "member", Target = "System.Drawing.SafeNativeMethods+ENHMETAHEADER..ctor()")]
namespace System.Drawing
{
- [System.Security.SuppressUnmanagedCodeSecurityAttribute()]
+ [SuppressUnmanagedCodeSecurity]
internal class SafeNativeMethods
{
- // we make this a nested class so that we don't have to initialize GDI+ to access SafeNativeMethods (mostly gdi/user32)
- [System.Security.SuppressUnmanagedCodeSecurityAttribute()]
+ // We make this a nested class so that we don't have to initialize GDI+ to access SafeNativeMethods (mostly gdi/user32).
+ [SuppressUnmanagedCodeSecurityAttribute]
internal class Gdip
{
private static readonly TraceSwitch s_gdiPlusInitialization = new TraceSwitch("GdiPlusInitialization", "Tracks GDI+ initialization and teardown");
@@ -81,21 +75,12 @@ namespace System.Drawing
private static IntPtr s_initToken;
private const string ThreadDataSlotName = "system.drawing.threaddata";
- static Gdip()
- {
- Initialize();
- }
+ static Gdip() => Initialize();
/// <summary>
/// Returns true if GDI+ has been started, but not shut down
/// </summary>
- private static bool Initialized
- {
- get
- {
- return s_initToken != IntPtr.Zero;
- }
- }
+ private static bool Initialized => s_initToken != IntPtr.Zero;
/// <summary>
/// This property will give us back a hashtable we can use to store all of our static brushes and pens on
@@ -113,12 +98,13 @@ namespace System.Drawing
threadData = new Hashtable();
Thread.SetData(slot, threadData);
}
+
return threadData;
}
}
// Clean up thread data
- [System.Runtime.CompilerServices.MethodImpl(System.Runtime.CompilerServices.MethodImplOptions.NoInlining)]
+ [MethodImpl(MethodImplOptions.NoInlining)]
private static void ClearThreadData()
{
Debug.WriteLineIf(s_gdiPlusInitialization.TraceVerbose, "Releasing TLS data");
@@ -130,7 +116,7 @@ namespace System.Drawing
/// Initializes GDI+
/// This should only be called by our constructor (static), we do not expect multiple calls per domain
/// </summary>
- [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Performance", "CA1804:RemoveUnusedLocals")]
+ [SuppressMessage("Microsoft.Performance", "CA1804:RemoveUnusedLocals")]
private static void Initialize()
{
Debug.Assert(s_initToken == IntPtr.Zero, "GdiplusInitialization: Initialize should not be called more than once in the same domain!");
@@ -143,24 +129,20 @@ namespace System.Drawing
// GDI+ ref counts multiple calls to Startup in the same process, so calls from multiple
// domains are ok, just make sure to pair each w/GdiplusShutdown
int status = GdiplusStartup(out s_initToken, ref input, out output);
-
- if (status != SafeNativeMethods.Gdip.Ok)
- {
- throw SafeNativeMethods.Gdip.StatusException(status);
- }
+ CheckStatus(status);
Debug.Unindent();
// Sync to event for handling shutdown
AppDomain currentDomain = AppDomain.CurrentDomain;
- currentDomain.ProcessExit += new EventHandler(SafeNativeMethods.Gdip.OnProcessExit);
+ currentDomain.ProcessExit += new EventHandler(OnProcessExit);
// Also sync to DomainUnload for non-default domains since they will not get a ProcessExit if
// they are unloaded prior to ProcessExit (and this object's static fields are scoped to AppDomains,
// so we must cleanup on AppDomain shutdown)
if (!currentDomain.IsDefaultAppDomain())
{
- currentDomain.DomainUnload += new EventHandler(SafeNativeMethods.Gdip.OnProcessExit);
+ currentDomain.DomainUnload += new EventHandler(OnProcessExit);
}
}
@@ -203,10 +185,10 @@ namespace System.Drawing
// unhook our shutdown handlers as we do not need to shut down more than once
AppDomain currentDomain = AppDomain.CurrentDomain;
- currentDomain.ProcessExit -= new EventHandler(SafeNativeMethods.Gdip.OnProcessExit);
+ currentDomain.ProcessExit -= new EventHandler(OnProcessExit);
if (!currentDomain.IsDefaultAppDomain())
{
- currentDomain.DomainUnload -= new EventHandler(SafeNativeMethods.Gdip.OnProcessExit);
+ currentDomain.DomainUnload -= new EventHandler(OnProcessExit);
}
}
Debug.Unindent();
@@ -215,7 +197,6 @@ namespace System.Drawing
// When we get notification that the process/domain is terminating, we will
// try to shutdown GDI+ if we haven't already.
- //
[PrePrepareMethod]
private static void OnProcessExit(object sender, EventArgs e)
{
@@ -232,12 +213,9 @@ namespace System.Drawing
// Initialization methods (GdiplusInit.h)
//----------------------------------------------------------------------------------------
- [DllImport(ExternDll.Gdiplus, SetLastError = true, ExactSpelling = true, CharSet = System.Runtime.InteropServices.CharSet.Unicode)] // 3 = Unicode
+ [DllImport(ExternDll.Gdiplus, SetLastError = true, ExactSpelling = true, CharSet = CharSet.Unicode)]
private static extern int GdiplusStartup(out IntPtr token, ref StartupInput input, out StartupOutput output);
- [DllImport(ExternDll.Gdiplus, SetLastError = true, ExactSpelling = true, CharSet = System.Runtime.InteropServices.CharSet.Unicode)] // 3 = Unicode
- private static extern void GdiplusShutdown(HandleRef token);
-
[StructLayout(LayoutKind.Sequential)]
private struct StartupInput
{
@@ -274,301 +252,283 @@ namespace System.Drawing
public IntPtr hook;//not used
public IntPtr unhook;//not used.
}
-
- private enum DebugEventLevel
- {
- Fatal,
- Warning,
- }
-
-
- // private delegate void DebugEventProc(DebugEventLevel level, /* char* */ string message);
-
+
//----------------------------------------------------------------------------------------
// Path methods
//----------------------------------------------------------------------------------------
- [DllImport(ExternDll.Gdiplus, SetLastError = true, ExactSpelling = true, CharSet = System.Runtime.InteropServices.CharSet.Unicode)] // 3 = Unicode
+ [DllImport(ExternDll.Gdiplus, SetLastError = true, ExactSpelling = true, CharSet = CharSet.Unicode)]
internal static extern int GdipCreatePath(int brushMode, out IntPtr path);
- [DllImport(ExternDll.Gdiplus, SetLastError = true, ExactSpelling = true, CharSet = System.Runtime.InteropServices.CharSet.Unicode)] // 3 = Unicode
+ [DllImport(ExternDll.Gdiplus, SetLastError = true, ExactSpelling = true, CharSet = CharSet.Unicode)]
internal static extern int GdipCreatePath2(HandleRef points, HandleRef types, int count, int brushMode, out IntPtr path);
- [DllImport(ExternDll.Gdiplus, SetLastError = true, ExactSpelling = true, CharSet = System.Runtime.InteropServices.CharSet.Unicode)] // 3 = Unicode
+ [DllImport(ExternDll.Gdiplus, SetLastError = true, ExactSpelling = true, CharSet = CharSet.Unicode)]
internal static extern int GdipCreatePath2I(HandleRef points, HandleRef types, int count, int brushMode, out IntPtr path);
- [DllImport(ExternDll.Gdiplus, SetLastError = true, ExactSpelling = true, CharSet = System.Runtime.InteropServices.CharSet.Unicode)] // 3 = Unicode
+ [DllImport(ExternDll.Gdiplus, SetLastError = true, ExactSpelling = true, CharSet = CharSet.Unicode)]
internal static extern int GdipClonePath(HandleRef path, out IntPtr clonepath);
- [DllImport(ExternDll.Gdiplus, SetLastError = true, ExactSpelling = true, EntryPoint = "GdipDeletePath", CharSet = System.Runtime.InteropServices.CharSet.Unicode)] // 3 = Unicode
+ [DllImport(ExternDll.Gdiplus, SetLastError = true, ExactSpelling = true, EntryPoint = "GdipDeletePath", CharSet = CharSet.Unicode)]
private static extern int IntGdipDeletePath(HandleRef path);
- internal static int GdipDeletePath(HandleRef path)
- {
- if (!Initialized) return SafeNativeMethods.Gdip.Ok;
- int result = IntGdipDeletePath(path);
- return result;
- }
+ internal static int GdipDeletePath(HandleRef path) => Initialized ? IntGdipDeletePath(path) : Ok;
- [DllImport(ExternDll.Gdiplus, SetLastError = true, ExactSpelling = true, CharSet = System.Runtime.InteropServices.CharSet.Unicode)] // 3 = Unicode
+ [DllImport(ExternDll.Gdiplus, SetLastError = true, ExactSpelling = true, CharSet = CharSet.Unicode)]
internal static extern int GdipResetPath(HandleRef path);
- [DllImport(ExternDll.Gdiplus, SetLastError = true, ExactSpelling = true, CharSet = System.Runtime.InteropServices.CharSet.Unicode)] // 3 = Unicode
+ [DllImport(ExternDll.Gdiplus, SetLastError = true, ExactSpelling = true, CharSet = CharSet.Unicode)]
internal static extern int GdipGetPointCount(HandleRef path, out int count);
- [DllImport(ExternDll.Gdiplus, SetLastError = true, ExactSpelling = true, CharSet = System.Runtime.InteropServices.CharSet.Unicode)] // 3 = Unicode
+ [DllImport(ExternDll.Gdiplus, SetLastError = true, ExactSpelling = true, CharSet = CharSet.Unicode)]
internal static extern int GdipGetPathTypes(HandleRef path, byte[] types, int count);
- [DllImport(ExternDll.Gdiplus, SetLastError = true, ExactSpelling = true, CharSet = System.Runtime.InteropServices.CharSet.Unicode)] // 3 = Unicode
+ [DllImport(ExternDll.Gdiplus, SetLastError = true, ExactSpelling = true, CharSet = CharSet.Unicode)]
internal static extern int GdipGetPathPoints(HandleRef path, HandleRef points, int count);
- [DllImport(ExternDll.Gdiplus, SetLastError = true, ExactSpelling = true, CharSet = System.Runtime.InteropServices.CharSet.Unicode)] // 3 = Unicode
+ [DllImport(ExternDll.Gdiplus, SetLastError = true, ExactSpelling = true, CharSet = CharSet.Unicode)]
internal static extern int GdipGetPathFillMode(HandleRef path, out int fillmode);
- [DllImport(ExternDll.Gdiplus, SetLastError = true, ExactSpelling = true, CharSet = System.Runtime.InteropServices.CharSet.Unicode)] // 3 = Unicode
+ [DllImport(ExternDll.Gdiplus, SetLastError = true, ExactSpelling = true, CharSet = CharSet.Unicode)]
internal static extern int GdipSetPathFillMode(HandleRef path, int fillmode);
- [DllImport(ExternDll.Gdiplus, SetLastError = true, ExactSpelling = true, CharSet = System.Runtime.InteropServices.CharSet.Unicode)] // 3 = Unicode
+ [DllImport(ExternDll.Gdiplus, SetLastError = true, ExactSpelling = true, CharSet = CharSet.Unicode)]
internal static extern int GdipGetPathData(HandleRef path, IntPtr pathData);
- [DllImport(ExternDll.Gdiplus, SetLastError = true, ExactSpelling = true, CharSet = System.Runtime.InteropServices.CharSet.Unicode)] // 3 = Unicode
+ [DllImport(ExternDll.Gdiplus, SetLastError = true, ExactSpelling = true, CharSet = CharSet.Unicode)]
internal static extern int GdipStartPathFigure(HandleRef path);
- [DllImport(ExternDll.Gdiplus, SetLastError = true, ExactSpelling = true, CharSet = System.Runtime.InteropServices.CharSet.Unicode)] // 3 = Unicode
+ [DllImport(ExternDll.Gdiplus, SetLastError = true, ExactSpelling = true, CharSet = CharSet.Unicode)]
internal static extern int GdipClosePathFigure(HandleRef path);
- [DllImport(ExternDll.Gdiplus, SetLastError = true, ExactSpelling = true, CharSet = System.Runtime.InteropServices.CharSet.Unicode)] // 3 = Unicode
+ [DllImport(ExternDll.Gdiplus, SetLastError = true, ExactSpelling = true, CharSet = CharSet.Unicode)]
internal static extern int GdipClosePathFigures(HandleRef path);
- [DllImport(ExternDll.Gdiplus, SetLastError = true, ExactSpelling = true, CharSet = System.Runtime.InteropServices.CharSet.Unicode)] // 3 = Unicode
+ [DllImport(ExternDll.Gdiplus, SetLastError = true, ExactSpelling = true, CharSet = CharSet.Unicode)]
internal static extern int GdipSetPathMarker(HandleRef path);
- [DllImport(ExternDll.Gdiplus, SetLastError = true, ExactSpelling = true, CharSet = System.Runtime.InteropServices.CharSet.Unicode)] // 3 = Unicode
+ [DllImport(ExternDll.Gdiplus, SetLastError = true, ExactSpelling = true, CharSet = CharSet.Unicode)]
internal static extern int GdipClearPathMarkers(HandleRef path);
- [DllImport(ExternDll.Gdiplus, SetLastError = true, ExactSpelling = true, CharSet = System.Runtime.InteropServices.CharSet.Unicode)] // 3 = Unicode
+ [DllImport(ExternDll.Gdiplus, SetLastError = true, ExactSpelling = true, CharSet = CharSet.Unicode)]
internal static extern int GdipReversePath(HandleRef path);
- [DllImport(ExternDll.Gdiplus, SetLastError = true, ExactSpelling = true, CharSet = System.Runtime.InteropServices.CharSet.Unicode)] // 3 = Unicode
+ [DllImport(ExternDll.Gdiplus, SetLastError = true, ExactSpelling = true, CharSet = CharSet.Unicode)]
internal static extern int GdipGetPathLastPoint(HandleRef path, GPPOINTF lastPoint);
- [DllImport(ExternDll.Gdiplus, SetLastError = true, ExactSpelling = true, CharSet = System.Runtime.InteropServices.CharSet.Unicode)] // 3 = Unicode
+ [DllImport(ExternDll.Gdiplus, SetLastError = true, ExactSpelling = true, CharSet = CharSet.Unicode)]
internal static extern int GdipAddPathLine(HandleRef path, float x1, float y1, float x2,
float y2);
- [DllImport(ExternDll.Gdiplus, SetLastError = true, ExactSpelling = true, CharSet = System.Runtime.InteropServices.CharSet.Unicode)] // 3 = Unicode
+ [DllImport(ExternDll.Gdiplus, SetLastError = true, ExactSpelling = true, CharSet = CharSet.Unicode)]
internal static extern int GdipAddPathLine2(HandleRef path, HandleRef memorypts, int count);
- [DllImport(ExternDll.Gdiplus, SetLastError = true, ExactSpelling = true, CharSet = System.Runtime.InteropServices.CharSet.Unicode)] // 3 = Unicode
+ [DllImport(ExternDll.Gdiplus, SetLastError = true, ExactSpelling = true, CharSet = CharSet.Unicode)]
internal static extern int GdipAddPathArc(HandleRef path, float x, float y, float width,
float height, float startAngle,
float sweepAngle);
- [DllImport(ExternDll.Gdiplus, SetLastError = true, ExactSpelling = true, CharSet = System.Runtime.InteropServices.CharSet.Unicode)] // 3 = Unicode
+ [DllImport(ExternDll.Gdiplus, SetLastError = true, ExactSpelling = true, CharSet = CharSet.Unicode)]
internal static extern int GdipAddPathBezier(HandleRef path, float x1, float y1, float x2,
float y2, float x3, float y3, float x4,
float y4);
- [DllImport(ExternDll.Gdiplus, SetLastError = true, ExactSpelling = true, CharSet = System.Runtime.InteropServices.CharSet.Unicode)] // 3 = Unicode
+ [DllImport(ExternDll.Gdiplus, SetLastError = true, ExactSpelling = true, CharSet = CharSet.Unicode)]
internal static extern int GdipAddPathBeziers(HandleRef path, HandleRef memorypts, int count);
- [DllImport(ExternDll.Gdiplus, SetLastError = true, ExactSpelling = true, CharSet = System.Runtime.InteropServices.CharSet.Unicode)] // 3 = Unicode
+ [DllImport(ExternDll.Gdiplus, SetLastError = true, ExactSpelling = true, CharSet = CharSet.Unicode)]
internal static extern int GdipAddPathCurve(HandleRef path, HandleRef memorypts, int count);
- [DllImport(ExternDll.Gdiplus, SetLastError = true, ExactSpelling = true, CharSet = System.Runtime.InteropServices.CharSet.Unicode)] // 3 = Unicode
+ [DllImport(ExternDll.Gdiplus, SetLastError = true, ExactSpelling = true, CharSet = CharSet.Unicode)]
internal static extern int GdipAddPathCurve2(HandleRef path, HandleRef memorypts, int count,
float tension);
- [DllImport(ExternDll.Gdiplus, SetLastError = true, ExactSpelling = true, CharSet = System.Runtime.InteropServices.CharSet.Unicode)] // 3 = Unicode
+ [DllImport(ExternDll.Gdiplus, SetLastError = true, ExactSpelling = true, CharSet = CharSet.Unicode)]
internal static extern int GdipAddPathCurve3(HandleRef path, HandleRef memorypts, int count,
int offset, int numberOfSegments,
float tension);
- [DllImport(ExternDll.Gdiplus, SetLastError = true, ExactSpelling = true, CharSet = System.Runtime.InteropServices.CharSet.Unicode)] // 3 = Unicode
+ [DllImport(ExternDll.Gdiplus, SetLastError = true, ExactSpelling = true, CharSet = CharSet.Unicode)]
internal static extern int GdipAddPathClosedCurve(HandleRef path, HandleRef memorypts,
int count);
- [DllImport(ExternDll.Gdiplus, SetLastError = true, ExactSpelling = true, CharSet = System.Runtime.InteropServices.CharSet.Unicode)] // 3 = Unicode
+ [DllImport(ExternDll.Gdiplus, SetLastError = true, ExactSpelling = true, CharSet = CharSet.Unicode)]
internal static extern int GdipAddPathClosedCurve2(HandleRef path, HandleRef memorypts,
int count, float tension);
- [DllImport(ExternDll.Gdiplus, SetLastError = true, ExactSpelling = true, CharSet = System.Runtime.InteropServices.CharSet.Unicode)] // 3 = Unicode
+ [DllImport(ExternDll.Gdiplus, SetLastError = true, ExactSpelling = true, CharSet = CharSet.Unicode)]
internal static extern int GdipAddPathRectangle(HandleRef path, float x, float y, float width,
float height);
- [DllImport(ExternDll.Gdiplus, SetLastError = true, ExactSpelling = true, CharSet = System.Runtime.InteropServices.CharSet.Unicode)] // 3 = Unicode
+ [DllImport(ExternDll.Gdiplus, SetLastError = true, ExactSpelling = true, CharSet = CharSet.Unicode)]
internal static extern int GdipAddPathRectangles(HandleRef path, HandleRef rects, int count);
- [DllImport(ExternDll.Gdiplus, SetLastError = true, ExactSpelling = true, CharSet = System.Runtime.InteropServices.CharSet.Unicode)] // 3 = Unicode
+ [DllImport(ExternDll.Gdiplus, SetLastError = true, ExactSpelling = true, CharSet = CharSet.Unicode)]
internal static extern int GdipAddPathEllipse(HandleRef path, float x, float y,
float width, float height);
- [DllImport(ExternDll.Gdiplus, SetLastError = true, ExactSpelling = true, CharSet = System.Runtime.InteropServices.CharSet.Unicode)] // 3 = Unicode
+ [DllImport(ExternDll.Gdiplus, SetLastError = true, ExactSpelling = true, CharSet = CharSet.Unicode)]
internal static extern int GdipAddPathPie(HandleRef path, float x, float y, float width,
float height, float startAngle,
float sweepAngle);
- [DllImport(ExternDll.Gdiplus, SetLastError = true, ExactSpelling = true, CharSet = System.Runtime.InteropServices.CharSet.Unicode)] // 3 = Unicode
+ [DllImport(ExternDll.Gdiplus, SetLastError = true, ExactSpelling = true, CharSet = CharSet.Unicode)]
internal static extern int GdipAddPathPolygon(HandleRef path, HandleRef memorypts, int count);
- [DllImport(ExternDll.Gdiplus, SetLastError = true, ExactSpelling = true, CharSet = System.Runtime.InteropServices.CharSet.Unicode)] // 3 = Unicode
+ [DllImport(ExternDll.Gdiplus, SetLastError = true, ExactSpelling = true, CharSet = CharSet.Unicode)]
internal static extern int GdipAddPathPath(HandleRef path, HandleRef addingPath, bool connect);
- [DllImport(ExternDll.Gdiplus, SetLastError = true, ExactSpelling = true, CharSet = System.Runtime.InteropServices.CharSet.Unicode)] // 3 = Unicode
+ [DllImport(ExternDll.Gdiplus, SetLastError = true, ExactSpelling = true, CharSet = CharSet.Unicode)]
internal static extern int GdipAddPathString(HandleRef path, string s, int length,
HandleRef fontFamily, int style, float emSize,
ref GPRECTF layoutRect, HandleRef format);
- [DllImport(ExternDll.Gdiplus, SetLastError = true, ExactSpelling = true, CharSet = System.Runtime.InteropServices.CharSet.Unicode)] // 3 = Unicode
+ [DllImport(ExternDll.Gdiplus, SetLastError = true, ExactSpelling = true, CharSet = CharSet.Unicode)]
internal static extern int GdipAddPathStringI(HandleRef path, string s, int length,
HandleRef fontFamily, int style, float emSize,
ref GPRECT layoutRect, HandleRef format);
- [DllImport(ExternDll.Gdiplus, SetLastError = true, ExactSpelling = true, CharSet = System.Runtime.InteropServices.CharSet.Unicode)] // 3 = Unicode
+ [DllImport(ExternDll.Gdiplus, SetLastError = true, ExactSpelling = true, CharSet = CharSet.Unicode)]
internal static extern int GdipAddPathLineI(HandleRef path, int x1, int y1, int x2,
int y2);
- [DllImport(ExternDll.Gdiplus, SetLastError = true, ExactSpelling = true, CharSet = System.Runtime.InteropServices.CharSet.Unicode)] // 3 = Unicode
+ [DllImport(ExternDll.Gdiplus, SetLastError = true, ExactSpelling = true, CharSet = CharSet.Unicode)]
internal static extern int GdipAddPathLine2I(HandleRef path, HandleRef memorypts, int count);
- [DllImport(ExternDll.Gdiplus, SetLastError = true, ExactSpelling = true, CharSet = System.Runtime.InteropServices.CharSet.Unicode)] // 3 = Unicode
+ [DllImport(ExternDll.Gdiplus, SetLastError = true, ExactSpelling = true, CharSet = CharSet.Unicode)]
internal static extern int GdipAddPathArcI(HandleRef path, int x, int y, int width,
int height, float startAngle,
float sweepAngle);
- [DllImport(ExternDll.Gdiplus, SetLastError = true, ExactSpelling = true, CharSet = System.Runtime.InteropServices.CharSet.Unicode)] // 3 = Unicode
+ [DllImport(ExternDll.Gdiplus, SetLastError = true, ExactSpelling = true, CharSet = CharSet.Unicode)]
internal static extern int GdipAddPathBezierI(HandleRef path, int x1, int y1, int x2,
int y2, int x3, int y3, int x4,
int y4);
- [DllImport(ExternDll.Gdiplus, SetLastError = true, ExactSpelling = true, CharSet = System.Runtime.InteropServices.CharSet.Unicode)] // 3 = Unicode
+ [DllImport(ExternDll.Gdiplus, SetLastError = true, ExactSpelling = true, CharSet = CharSet.Unicode)]
internal static extern int GdipAddPathBeziersI(HandleRef path, HandleRef memorypts, int count);
- [DllImport(ExternDll.Gdiplus, SetLastError = true, ExactSpelling = true, CharSet = System.Runtime.InteropServices.CharSet.Unicode)] // 3 = Unicode
+ [DllImport(ExternDll.Gdiplus, SetLastError = true, ExactSpelling = true, CharSet = CharSet.Unicode)]
internal static extern int GdipAddPathCurveI(HandleRef path, HandleRef memorypts, int count);
- [DllImport(ExternDll.Gdiplus, SetLastError = true, ExactSpelling = true, CharSet = System.Runtime.InteropServices.CharSet.Unicode)] // 3 = Unicode
+ [DllImport(ExternDll.Gdiplus, SetLastError = true, ExactSpelling = true, CharSet = CharSet.Unicode)]
internal static extern int GdipAddPathCurve2I(HandleRef path, HandleRef memorypts, int count,
float tension);
- [DllImport(ExternDll.Gdiplus, SetLastError = true, ExactSpelling = true, CharSet = System.Runtime.InteropServices.CharSet.Unicode)] // 3 = Unicode
+ [DllImport(ExternDll.Gdiplus, SetLastError = true, ExactSpelling = true, CharSet = CharSet.Unicode)]
internal static extern int GdipAddPathCurve3I(HandleRef path, HandleRef memorypts, int count,
int offset, int numberOfSegments,
float tension);
- [DllImport(ExternDll.Gdiplus, SetLastError = true, ExactSpelling = true, CharSet = System.Runtime.InteropServices.CharSet.Unicode)] // 3 = Unicode
+ [DllImport(ExternDll.Gdiplus, SetLastError = true, ExactSpelling = true, CharSet = CharSet.Unicode)]
internal static extern int GdipAddPathClosedCurveI(HandleRef path, HandleRef memorypts,
int count);
- [DllImport(ExternDll.Gdiplus, SetLastError = true, ExactSpelling = true, CharSet = System.Runtime.InteropServices.CharSet.Unicode)] // 3 = Unicode
+ [DllImport(ExternDll.Gdiplus, SetLastError = true, ExactSpelling = true, CharSet = CharSet.Unicode)]
internal static extern int GdipAddPathClosedCurve2I(HandleRef path, HandleRef memorypts,
int count, float tension);
- [DllImport(ExternDll.Gdiplus, SetLastError = true, ExactSpelling = true, CharSet = System.Runtime.InteropServices.CharSet.Unicode)] // 3 = Unicode
+ [DllImport(ExternDll.Gdiplus, SetLastError = true, ExactSpelling = true, CharSet = CharSet.Unicode)]
internal static extern int GdipAddPathRectangleI(HandleRef path, int x, int y, int width,
int height);
- [DllImport(ExternDll.Gdiplus, SetLastError = true, ExactSpelling = true, CharSet = System.Runtime.InteropServices.CharSet.Unicode)] // 3 = Unicode
+ [DllImport(ExternDll.Gdiplus, SetLastError = true, ExactSpelling = true, CharSet = CharSet.Unicode)]
internal static extern int GdipAddPathRectanglesI(HandleRef path, HandleRef rects, int count);
- [DllImport(ExternDll.Gdiplus, SetLastError = true, ExactSpelling = true, CharSet = System.Runtime.InteropServices.CharSet.Unicode)] // 3 = Unicode
+ [DllImport(ExternDll.Gdiplus, SetLastError = true, ExactSpelling = true, CharSet = CharSet.Unicode)]
internal static extern int GdipAddPathEllipseI(HandleRef path, int x, int y,
int width, int height);
- [DllImport(ExternDll.Gdiplus, SetLastError = true, ExactSpelling = true, CharSet = System.Runtime.InteropServices.CharSet.Unicode)] // 3 = Unicode
+ [DllImport(ExternDll.Gdiplus, SetLastError = true, ExactSpelling = true, CharSet = CharSet.Unicode)]
internal static extern int GdipAddPathPieI(HandleRef path, int x, int y, int width,
int height, float startAngle,
float sweepAngle);
- [DllImport(ExternDll.Gdiplus, SetLastError = true, ExactSpelling = true, CharSet = System.Runtime.InteropServices.CharSet.Unicode)] // 3 = Unicode
+ [DllImport(ExternDll.Gdiplus, SetLastError = true, ExactSpelling = true, CharSet = CharSet.Unicode)]
internal static extern int GdipAddPathPolygonI(HandleRef path, HandleRef memorypts, int count);
- [DllImport(ExternDll.Gdiplus, SetLastError = true, ExactSpelling = true, CharSet = System.Runtime.InteropServices.CharSet.Unicode)] // 3 = Unicode
+ [DllImport(ExternDll.Gdiplus, SetLastError = true, ExactSpelling = true, CharSet = CharSet.Unicode)]
internal static extern int GdipFlattenPath(HandleRef path, HandleRef matrixfloat, float flatness);
- [DllImport(ExternDll.Gdiplus, SetLastError = true, ExactSpelling = true, CharSet = System.Runtime.InteropServices.CharSet.Unicode)] // 3 = Unicode
+ [DllImport(ExternDll.Gdiplus, SetLastError = true, ExactSpelling = true, CharSet = CharSet.Unicode)]
internal static extern int GdipWidenPath(HandleRef path, HandleRef pen, HandleRef matrix, float flatness);
- [DllImport(ExternDll.Gdiplus, SetLastError = true, ExactSpelling = true, CharSet = System.Runtime.InteropServices.CharSet.Unicode)] // 3 = Unicode
+ [DllImport(ExternDll.Gdiplus, SetLastError = true, ExactSpelling = true, CharSet = CharSet.Unicode)]
internal static extern int GdipWarpPath(HandleRef path, HandleRef matrix, HandleRef points, int count,
float srcX, float srcY, float srcWidth, float srcHeight,
WarpMode warpMode, float flatness);
- [DllImport(ExternDll.Gdiplus, SetLastError = true, ExactSpelling = true, CharSet = System.Runtime.InteropServices.CharSet.Unicode)] // 3 = Unicode
+ [DllImport(ExternDll.Gdiplus, SetLastError = true, ExactSpelling = true, CharSet = CharSet.Unicode)]
internal static extern int GdipTransformPath(HandleRef path, HandleRef matrix);
- [DllImport(ExternDll.Gdiplus, SetLastError = true, ExactSpelling = true, CharSet = System.Runtime.InteropServices.CharSet.Unicode)] // 3 = Unicode
+ [DllImport(ExternDll.Gdiplus, SetLastError = true, ExactSpelling = true, CharSet = CharSet.Unicode)]
internal static extern int GdipGetPathWorldBounds(HandleRef path, ref GPRECTF gprectf, HandleRef matrix, HandleRef pen);
- [DllImport(ExternDll.Gdiplus, SetLastError = true, ExactSpelling = true, CharSet = System.Runtime.InteropServices.CharSet.Unicode)] // 3 = Unicode
+ [DllImport(ExternDll.Gdiplus, SetLastError = true, ExactSpelling = true, CharSet = CharSet.Unicode)]
internal static extern int GdipIsVisiblePathPoint(HandleRef path, float x, float y,
HandleRef graphics, out int boolean);
- [DllImport(ExternDll.Gdiplus, SetLastError = true, ExactSpelling = true, CharSet = System.Runtime.InteropServices.CharSet.Unicode)] // 3 = Unicode
+ [DllImport(ExternDll.Gdiplus, SetLastError = true, ExactSpelling = true, CharSet = CharSet.Unicode)]
internal static extern int GdipIsVisiblePathPointI(HandleRef path, int x, int y,
HandleRef graphics, out int boolean);
- [DllImport(ExternDll.Gdiplus, SetLastError = true, ExactSpelling = true, CharSet = System.Runtime.InteropServices.CharSet.Unicode)] // 3 = Unicode
+ [DllImport(ExternDll.Gdiplus, SetLastError = true, ExactSpelling = true, CharSet = CharSet.Unicode)]
internal static extern int GdipIsOutlineVisiblePathPoint(HandleRef path, float x, float y, HandleRef pen,
HandleRef graphics, out int boolean);
- [DllImport(ExternDll.Gdiplus, SetLastError = true, ExactSpelling = true, CharSet = System.Runtime.InteropServices.CharSet.Unicode)] // 3 = Unicode
+ [DllImport(ExternDll.Gdiplus, SetLastError = true, ExactSpelling = true, CharSet = CharSet.Unicode)]
internal static extern int GdipIsOutlineVisiblePathPointI(HandleRef path, int x, int y, HandleRef pen,
HandleRef graphics, out int boolean);
//----------------------------------------------------------------------------------------
// GraphicsPath Enumeration methods
//----------------------------------------------------------------------------------------
- [DllImport(ExternDll.Gdiplus, SetLastError = true, ExactSpelling = true, CharSet = System.Runtime.InteropServices.CharSet.Unicode)] // 3 = Unicode
+ [DllImport(ExternDll.Gdiplus, SetLastError = true, ExactSpelling = true, CharSet = CharSet.Unicode)]
internal static extern int GdipCreatePathIter(out IntPtr pathIter, HandleRef path);
- [DllImport(ExternDll.Gdiplus, SetLastError = true, ExactSpelling = true, EntryPoint = "GdipDeletePathIter", CharSet = System.Runtime.InteropServices.CharSet.Unicode)] // 3 = Unicode
+ [DllImport(ExternDll.Gdiplus, SetLastError = true, ExactSpelling = true, EntryPoint = "GdipDeletePathIter", CharSet = CharSet.Unicode)]
private static extern int IntGdipDeletePathIter(HandleRef pathIter);
- internal static int GdipDeletePathIter(HandleRef pathIter)
- {
- if (!Initialized) return SafeNativeMethods.Gdip.Ok;
- int result = IntGdipDeletePathIter(pathIter);
- return result;
- }
- [DllImport(ExternDll.Gdiplus, SetLastError = true, ExactSpelling = true, CharSet = System.Runtime.InteropServices.CharSet.Unicode)] // 3 = Unicode
+ internal static int GdipDeletePathIter(HandleRef pathIter) => Initialized ? IntGdipDeletePathIter(pathIter) : Ok;
+
+ [DllImport(ExternDll.Gdiplus, SetLastError = true, ExactSpelling = true, CharSet = CharSet.Unicode)]
internal static extern int GdipPathIterNextSubpath(HandleRef pathIter, out int resultCount,
out int startIndex, out int endIndex, out bool isClosed);
- [DllImport(ExternDll.Gdiplus, SetLastError = true, ExactSpelling = true, CharSet = System.Runtime.InteropServices.CharSet.Unicode)] // 3 = Unicode
+ [DllImport(ExternDll.Gdiplus, SetLastError = true, ExactSpelling = true, CharSet = CharSet.Unicode)]
internal static extern int GdipPathIterNextSubpathPath(HandleRef pathIter, out int resultCount,
HandleRef path, out bool isClosed);
- [DllImport(ExternDll.Gdiplus, SetLastError = true, ExactSpelling = true, CharSet = System.Runtime.InteropServices.CharSet.Unicode)] // 3 = Unicode
+ [DllImport(ExternDll.Gdiplus, SetLastError = true, ExactSpelling = true, CharSet = CharSet.Unicode)]
internal static extern int GdipPathIterNextPathType(HandleRef pathIter, out int resultCount,
out byte pathType, out int startIndex,
out int endIndex);
- [DllImport(ExternDll.Gdiplus, SetLastError = true, ExactSpelling = true, CharSet = System.Runtime.InteropServices.CharSet.Unicode)] // 3 = Unicode
+ [DllImport(ExternDll.Gdiplus, SetLastError = true, ExactSpelling = true, CharSet = CharSet.Unicode)]
internal static extern int GdipPathIterNextMarker(HandleRef pathIter, out int resultCount,
out int startIndex, out int endIndex);
- [DllImport(ExternDll.Gdiplus, SetLastError = true, ExactSpelling = true, CharSet = System.Runtime.InteropServices.CharSet.Unicode)] // 3 = Unicode
+ [DllImport(ExternDll.Gdiplus, SetLastError = true, ExactSpelling = true, CharSet = CharSet.Unicode)]
internal static extern int GdipPathIterNextMarkerPath(HandleRef pathIter, out int resultCount,
HandleRef path);
- [DllImport(ExternDll.Gdiplus, SetLastError = true, ExactSpelling = true, CharSet = System.Runtime.InteropServices.CharSet.Unicode)] // 3 = Unicode
+ [DllImport(ExternDll.Gdiplus, SetLastError = true, ExactSpelling = true, CharSet = CharSet.Unicode)]
internal static extern int GdipPathIterGetCount(HandleRef pathIter, out int count);
- [DllImport(ExternDll.Gdiplus, SetLastError = true, ExactSpelling = true, CharSet = System.Runtime.InteropServices.CharSet.Unicode)] // 3 = Unicode
+ [DllImport(ExternDll.Gdiplus, SetLastError = true, ExactSpelling = true, CharSet = CharSet.Unicode)]
internal static extern int GdipPathIterGetSubpathCount(HandleRef pathIter, out int count);
- [DllImport(ExternDll.Gdiplus, SetLastError = true, ExactSpelling = true, CharSet = System.Runtime.InteropServices.CharSet.Unicode)] // 3 = Unicode
+ [DllImport(ExternDll.Gdiplus, SetLastError = true, ExactSpelling = true, CharSet = CharSet.Unicode)]
internal static extern int GdipPathIterHasCurve(HandleRef pathIter, out bool hasCurve);
- [DllImport(ExternDll.Gdiplus, SetLastError = true, ExactSpelling = true, CharSet = System.Runtime.InteropServices.CharSet.Unicode)] // 3 = Unicode
+ [DllImport(ExternDll.Gdiplus, SetLastError = true, ExactSpelling = true, CharSet = CharSet.Unicode)]
internal static extern int GdipPathIterRewind(HandleRef pathIter);
- [DllImport(ExternDll.Gdiplus, SetLastError = true, ExactSpelling = true, CharSet = System.Runtime.InteropServices.CharSet.Unicode)] // 3 = Unicode
+ [DllImport(ExternDll.Gdiplus, SetLastError = true, ExactSpelling = true, CharSet = CharSet.Unicode)]
internal static extern int GdipPathIterEnumerate(HandleRef pathIter, out int resultCount,
IntPtr memoryPts, [In, Out] byte[] types, int count);
- [DllImport(ExternDll.Gdiplus, SetLastError = true, ExactSpelling = true, CharSet = System.Runtime.InteropServices.CharSet.Unicode)] // 3 = Unicode
+ [DllImport(ExternDll.Gdiplus, SetLastError = true, ExactSpelling = true, CharSet = CharSet.Unicode)]
internal static extern int GdipPathIterCopyData(HandleRef pathIter, out int resultCount,
IntPtr memoryPts, [In, Out] byte[] types, int startIndex,
int endIndex);
@@ -577,80 +537,76 @@ namespace System.Drawing
// Matrix methods
//----------------------------------------------------------------------------------------
- [DllImport(ExternDll.Gdiplus, SetLastError = true, ExactSpelling = true, CharSet = System.Runtime.InteropServices.CharSet.Unicode)] // 3 = Unicode
+ [DllImport(ExternDll.Gdiplus, SetLastError = true, ExactSpelling = true, CharSet = CharSet.Unicode)]
internal static extern int GdipCreateMatrix(out IntPtr matrix);
- [DllImport(ExternDll.Gdiplus, SetLastError = true, ExactSpelling = true, CharSet = System.Runtime.InteropServices.CharSet.Unicode)] // 3 = Unicode
+ [DllImport(ExternDll.Gdiplus, SetLastError = true, ExactSpelling = true, CharSet = CharSet.Unicode)]
internal static extern int GdipCreateMatrix2(float m11, float m12,
float m21, float m22, float dx,
float dy, out IntPtr matrix);
- [DllImport(ExternDll.Gdiplus, SetLastError = true, ExactSpelling = true, CharSet = System.Runtime.InteropServices.CharSet.Unicode)] // 3 = Unicode
+ [DllImport(ExternDll.Gdiplus, SetLastError = true, ExactSpelling = true, CharSet = CharSet.Unicode)]
internal static extern int GdipCreateMatrix3(ref GPRECTF rect, HandleRef dstplg, out IntPtr matrix);
- [DllImport(ExternDll.Gdiplus, SetLastError = true, ExactSpelling = true, CharSet = System.Runtime.InteropServices.CharSet.Unicode)] // 3 = Unicode
+ [DllImport(ExternDll.Gdiplus, SetLastError = true, ExactSpelling = true, CharSet = CharSet.Unicode)]
internal static extern int GdipCreateMatrix3I(ref GPRECT rect, HandleRef dstplg, out IntPtr matrix);
- [DllImport(ExternDll.Gdiplus, SetLastError = true, ExactSpelling = true, CharSet = System.Runtime.InteropServices.CharSet.Unicode)] // 3 = Unicode
+ [DllImport(ExternDll.Gdiplus, SetLastError = true, ExactSpelling = true, CharSet = CharSet.Unicode)]
internal static extern int GdipCloneMatrix(HandleRef matrix, out IntPtr cloneMatrix);
- [DllImport(ExternDll.Gdiplus, SetLastError = true, ExactSpelling = true, EntryPoint = "GdipDeleteMatrix", CharSet = System.Runtime.InteropServices.CharSet.Unicode)] // 3 = Unicode
+ [DllImport(ExternDll.Gdiplus, SetLastError = true, ExactSpelling = true, EntryPoint = "GdipDeleteMatrix", CharSet = CharSet.Unicode)]
private static extern int IntGdipDeleteMatrix(HandleRef matrix);
- internal static int GdipDeleteMatrix(HandleRef matrix)
- {
- if (!Initialized) return SafeNativeMethods.Gdip.Ok;
- int result = IntGdipDeleteMatrix(matrix);
- return result;
- }
- [DllImport(ExternDll.Gdiplus, SetLastError = true, ExactSpelling = true, CharSet = System.Runtime.InteropServices.CharSet.Unicode)] // 3 = Unicode
+ internal static int GdipDeleteMatrix(HandleRef matrix) => Initialized ? IntGdipDeleteMatrix(matrix) : Ok;
+
+ [DllImport(ExternDll.Gdiplus, SetLastError = true, ExactSpelling = true, CharSet = CharSet.Unicode)]
internal static extern int GdipSetMatrixElements(HandleRef matrix, float m11,
float m12, float m21,
float m22, float dx, float dy);
- [DllImport(ExternDll.Gdiplus, SetLastError = true, ExactSpelling = true, CharSet = System.Runtime.InteropServices.CharSet.Unicode)] // 3 = Unicode
+ [DllImport(ExternDll.Gdiplus, SetLastError = true, ExactSpelling = true, CharSet = CharSet.Unicode)]
internal static extern int GdipMultiplyMatrix(HandleRef matrix, HandleRef matrix2, MatrixOrder order);
- [DllImport(ExternDll.Gdiplus, SetLastError = true, ExactSpelling = true, CharSet = System.Runtime.InteropServices.CharSet.Unicode)] // 3 = Unicode
+ [DllImport(ExternDll.Gdiplus, SetLastError = true, ExactSpelling = true, CharSet = CharSet.Unicode)]
internal static extern int GdipTranslateMatrix(HandleRef matrix, float offsetX,
float offsetY, MatrixOrder order);
- [DllImport(ExternDll.Gdiplus, SetLastError = true, ExactSpelling = true, CharSet = System.Runtime.InteropServices.CharSet.Unicode)] // 3 = Unicode
+ [DllImport(ExternDll.Gdiplus, SetLastError = true, ExactSpelling = true, CharSet = CharSet.Unicode)]
internal static extern int GdipScaleMatrix(HandleRef matrix, float scaleX, float scaleY, MatrixOrder order);
- [DllImport(ExternDll.Gdiplus, SetLastError = true, ExactSpelling = true, CharSet = System.Runtime.InteropServices.CharSet.Unicode)] // 3 = Unicode
+ [DllImport(ExternDll.Gdiplus, SetLastError = true, ExactSpelling = true, CharSet = CharSet.Unicode)]
internal static extern int GdipRotateMatrix(HandleRef matrix, float angle, MatrixOrder order);
- [DllImport(ExternDll.Gdiplus, SetLastError = true, ExactSpelling = true, CharSet = System.Runtime.InteropServices.CharSet.Unicode)] // 3 = Unicode
+ [DllImport(ExternDll.Gdiplus, SetLastError = true, ExactSpelling = true, CharSet = CharSet.Unicode)]
internal static extern int GdipShearMatrix(HandleRef matrix, float shearX, float shearY, MatrixOrder order);
- [DllImport(ExternDll.Gdiplus, SetLastError = true, ExactSpelling = true, CharSet = System.Runtime.InteropServices.CharSet.Unicode)] // 3 = Unicode
+ [DllImport(ExternDll.Gdiplus, SetLastError = true, ExactSpelling = true, CharSet = CharSet.Unicode)]
internal static extern int GdipInvertMatrix(HandleRef matrix);
- [DllImport(ExternDll.Gdiplus, SetLastError = true, ExactSpelling = true, CharSet = System.Runtime.InteropServices.CharSet.Unicode)] // 3 = Unicode
+ [DllImport(ExternDll.Gdiplus, SetLastError = true, ExactSpelling = true, CharSet = CharSet.Unicode)]
internal static extern int GdipTransformMatrixPoints(HandleRef matrix, HandleRef pts, int count);
- [DllImport(ExternDll.Gdiplus, SetLastError = true, ExactSpelling = true, CharSet = System.Runtime.InteropServices.CharSet.Unicode)] // 3 = Unicode
+ [DllImport(ExternDll.Gdiplus, SetLastError = true, ExactSpelling = true, CharSet = CharSet.Unicode)]
internal static extern int GdipTransformMatrixPointsI(HandleRef matrix, HandleRef pts, int count);
- [DllImport(ExternDll.Gdiplus, SetLastError = true, ExactSpelling = true, CharSet = System.Runtime.InteropServices.CharSet.Unicode)] // 3 = Unicode
+ [DllImport(ExternDll.Gdiplus, SetLastError = true, ExactSpelling = true, CharSet = CharSet.Unicode)]
internal static extern int GdipVectorTransformMatrixPoints(HandleRef matrix, HandleRef pts,
int count);
- [DllImport(ExternDll.Gdiplus, SetLastError = true, ExactSpelling = true, CharSet = System.Runtime.InteropServices.CharSet.Unicode)] // 3 = Unicode
+ [DllImport(ExternDll.Gdiplus, SetLastError = true, ExactSpelling = true, CharSet = CharSet.Unicode)]
internal static extern int GdipVectorTransformMatrixPointsI(HandleRef matrix, HandleRef pts,
int count);
- [DllImport(ExternDll.Gdiplus, SetLastError = true, ExactSpelling = true, CharSet = System.Runtime.InteropServices.CharSet.Unicode)] // 3 = Unicode
+ [DllImport(ExternDll.Gdiplus, SetLastError = true, ExactSpelling = true, CharSet = CharSet.Unicode)]
internal static extern int GdipGetMatrixElements(HandleRef matrix, IntPtr m);
- [DllImport(ExternDll.Gdiplus, SetLastError = true, ExactSpelling = true, CharSet = System.Runtime.InteropServices.CharSet.Unicode)] // 3 = Unicode
+ [DllImport(ExternDll.Gdiplus, SetLastError = true, ExactSpelling = true, CharSet = CharSet.Unicode)]
internal static extern int GdipIsMatrixInvertible(HandleRef matrix, out int boolean);
- [DllImport(ExternDll.Gdiplus, SetLastError = true, ExactSpelling = true, CharSet = System.Runtime.InteropServices.CharSet.Unicode)] // 3 = Unicode
+ [DllImport(ExternDll.Gdiplus, SetLastError = true, ExactSpelling = true, CharSet = CharSet.Unicode)]
internal static extern int GdipIsMatrixIdentity(HandleRef matrix, out int boolean);
- [DllImport(ExternDll.Gdiplus, SetLastError = true, ExactSpelling = true, CharSet = System.Runtime.InteropServices.CharSet.Unicode)] // 3 = Unicode
+ [DllImport(ExternDll.Gdiplus, SetLastError = true, ExactSpelling = true, CharSet = CharSet.Unicode)]
internal static extern int GdipIsMatrixEqual(HandleRef matrix, HandleRef matrix2,
out int boolean);
@@ -658,110 +614,106 @@ namespace System.Drawing
// Region methods
//----------------------------------------------------------------------------------------
- [DllImport(ExternDll.Gdiplus, SetLastError = true, ExactSpelling = true, CharSet = System.Runtime.InteropServices.CharSet.Unicode)] // 3 = Unicode
+ [DllImport(ExternDll.Gdiplus, SetLastError = true, ExactSpelling = true, CharSet = CharSet.Unicode)]
internal static extern int GdipCreateRegion(out IntPtr region);
- [DllImport(ExternDll.Gdiplus, SetLastError = true, ExactSpelling = true, CharSet = System.Runtime.InteropServices.CharSet.Unicode)] // 3 = Unicode
+ [DllImport(ExternDll.Gdiplus, SetLastError = true, ExactSpelling = true, CharSet = CharSet.Unicode)]
internal static extern int GdipCreateRegionRect(ref GPRECTF gprectf, out IntPtr region);
- [DllImport(ExternDll.Gdiplus, SetLastError = true, ExactSpelling = true, CharSet = System.Runtime.InteropServices.CharSet.Unicode)] // 3 = Unicode
+ [DllImport(ExternDll.Gdiplus, SetLastError = true, ExactSpelling = true, CharSet = CharSet.Unicode)]
internal static extern int GdipCreateRegionRectI(ref GPRECT gprect, out IntPtr region);
- [DllImport(ExternDll.Gdiplus, SetLastError = true, ExactSpelling = true, CharSet = System.Runtime.InteropServices.CharSet.Unicode)] // 3 = Unicode
+ [DllImport(ExternDll.Gdiplus, SetLastError = true, ExactSpelling = true, CharSet = CharSet.Unicode)]
internal static extern int GdipCreateRegionPath(HandleRef path, out IntPtr region);
- [DllImport(ExternDll.Gdiplus, SetLastError = true, ExactSpelling = true, CharSet = System.Runtime.InteropServices.CharSet.Unicode)] // 3 = Unicode
+ [DllImport(ExternDll.Gdiplus, SetLastError = true, ExactSpelling = true, CharSet = CharSet.Unicode)]
internal static extern int GdipCreateRegionRgnData(byte[] rgndata, int size, out IntPtr region);
- [DllImport(ExternDll.Gdiplus, SetLastError = true, ExactSpelling = true, CharSet = System.Runtime.InteropServices.CharSet.Unicode)] // 3 = Unicode
+ [DllImport(ExternDll.Gdiplus, SetLastError = true, ExactSpelling = true, CharSet = CharSet.Unicode)]
internal static extern int GdipCreateRegionHrgn(HandleRef hRgn, out IntPtr region);
- [DllImport(ExternDll.Gdiplus, SetLastError = true, ExactSpelling = true, CharSet = System.Runtime.InteropServices.CharSet.Unicode)] // 3 = Unicode
+ [DllImport(ExternDll.Gdiplus, SetLastError = true, ExactSpelling = true, CharSet = CharSet.Unicode)]
internal static extern int GdipCloneRegion(HandleRef region, out IntPtr cloneregion);
- [DllImport(ExternDll.Gdiplus, SetLastError = true, ExactSpelling = true, EntryPoint = "GdipDeleteRegion", CharSet = System.Runtime.InteropServices.CharSet.Unicode)] // 3 = Unicode
+ [DllImport(ExternDll.Gdiplus, SetLastError = true, ExactSpelling = true, EntryPoint = "GdipDeleteRegion", CharSet = CharSet.Unicode)]
private static extern int IntGdipDeleteRegion(HandleRef region);
- internal static int GdipDeleteRegion(HandleRef region)
- {
- if (!Initialized) return SafeNativeMethods.Gdip.Ok;
- int result = IntGdipDeleteRegion(region);
- return result;
- }
- [DllImport(ExternDll.Gdiplus, SetLastError = true, ExactSpelling = true, CharSet = System.Runtime.InteropServices.CharSet.Unicode)] // 3 = Unicode
+ internal static int GdipDeleteRegion(HandleRef region) => Initialized ? IntGdipDeleteRegion(region) : Ok;
+
+ [DllImport(ExternDll.Gdiplus, SetLastError = true, ExactSpelling = true, CharSet = CharSet.Unicode)]
internal static extern int GdipSetInfinite(HandleRef region);
- [DllImport(ExternDll.Gdiplus, SetLastError = true, ExactSpelling = true, CharSet = System.Runtime.InteropServices.CharSet.Unicode)] // 3 = Unicode
+ [DllImport(ExternDll.Gdiplus, SetLastError = true, ExactSpelling = true, CharSet = CharSet.Unicode)]
internal static extern int GdipSetEmpty(HandleRef region);
- [DllImport(ExternDll.Gdiplus, SetLastError = true, ExactSpelling = true, CharSet = System.Runtime.InteropServices.CharSet.Unicode)] // 3 = Unicode
+ [DllImport(ExternDll.Gdiplus, SetLastError = true, ExactSpelling = true, CharSet = CharSet.Unicode)]
internal static extern int GdipCombineRegionRect(HandleRef region, ref GPRECTF gprectf, CombineMode mode);
- [DllImport(ExternDll.Gdiplus, SetLastError = true, ExactSpelling = true, CharSet = System.Runtime.InteropServices.CharSet.Unicode)] // 3 = Unicode
+ [DllImport(ExternDll.Gdiplus, SetLastError = true, ExactSpelling = true, CharSet = CharSet.Unicode)]
internal static extern int GdipCombineRegionRectI(HandleRef region, ref GPRECT gprect, CombineMode mode);
- [DllImport(ExternDll.Gdiplus, SetLastError = true, ExactSpelling = true, CharSet = System.Runtime.InteropServices.CharSet.Unicode)] // 3 = Unicode
+ [DllImport(ExternDll.Gdiplus, SetLastError = true, ExactSpelling = true, CharSet = CharSet.Unicode)]
internal static extern int GdipCombineRegionPath(HandleRef region, HandleRef path, CombineMode mode);
- [DllImport(ExternDll.Gdiplus, SetLastError = true, ExactSpelling = true, CharSet = System.Runtime.InteropServices.CharSet.Unicode)] // 3 = Unicode
+ [DllImport(ExternDll.Gdiplus, SetLastError = true, ExactSpelling = true, CharSet = CharSet.Unicode)]
internal static extern int GdipCombineRegionRegion(HandleRef region, HandleRef region2, CombineMode mode);
- [DllImport(ExternDll.Gdiplus, SetLastError = true, ExactSpelling = true, CharSet = System.Runtime.InteropServices.CharSet.Unicode)] // 3 = Unicode
+ [DllImport(ExternDll.Gdiplus, SetLastError = true, ExactSpelling = true, CharSet = CharSet.Unicode)]
internal static extern int GdipTranslateRegion(HandleRef region, float dx, float dy);
- [DllImport(ExternDll.Gdiplus, SetLastError = true, ExactSpelling = true, CharSet = System.Runtime.InteropServices.CharSet.Unicode)] // 3 = Unicode
+ [DllImport(ExternDll.Gdiplus, SetLastError = true, ExactSpelling = true, CharSet = CharSet.Unicode)]
internal static extern int GdipTranslateRegionI(HandleRef region, int dx, int dy);
- [DllImport(ExternDll.Gdiplus, SetLastError = true, ExactSpelling = true, CharSet = System.Runtime.InteropServices.CharSet.Unicode)] // 3 = Unicode
+ [DllImport(ExternDll.Gdiplus, SetLastError = true, ExactSpelling = true, CharSet = CharSet.Unicode)]
internal static extern int GdipTransformRegion(HandleRef region, HandleRef matrix);
- [DllImport(ExternDll.Gdiplus, SetLastError = true, ExactSpelling = true, CharSet = System.Runtime.InteropServices.CharSet.Unicode)] // 3 = Unicode
+ [DllImport(ExternDll.Gdiplus, SetLastError = true, ExactSpelling = true, CharSet = CharSet.Unicode)]
internal static extern int GdipGetRegionBounds(HandleRef region, HandleRef graphics, ref GPRECTF gprectf);
- [DllImport(ExternDll.Gdiplus, SetLastError = true, ExactSpelling = true, CharSet = System.Runtime.InteropServices.CharSet.Unicode)] // 3 = Unicode
+ [DllImport(ExternDll.Gdiplus, SetLastError = true, ExactSpelling = true, CharSet = CharSet.Unicode)]
internal static extern int GdipGetRegionHRgn(HandleRef region, HandleRef graphics, out IntPtr hrgn);
- [DllImport(ExternDll.Gdiplus, SetLastError = true, ExactSpelling = true, CharSet = System.Runtime.InteropServices.CharSet.Unicode)] // 3 = Unicode
+ [DllImport(ExternDll.Gdiplus, SetLastError = true, ExactSpelling = true, CharSet = CharSet.Unicode)]
internal static extern int GdipIsEmptyRegion(HandleRef region, HandleRef graphics, out int boolean);
- [DllImport(ExternDll.Gdiplus, SetLastError = true, ExactSpelling = true, CharSet = System.Runtime.InteropServices.CharSet.Unicode)] // 3 = Unicode
+ [DllImport(ExternDll.Gdiplus, SetLastError = true, ExactSpelling = true, CharSet = CharSet.Unicode)]
internal static extern int GdipIsInfiniteRegion(HandleRef region, HandleRef graphics, out int boolean);
- [DllImport(ExternDll.Gdiplus, SetLastError = true, ExactSpelling = true, CharSet = System.Runtime.InteropServices.CharSet.Unicode)] // 3 = Unicode
+ [DllImport(ExternDll.Gdiplus, SetLastError = true, ExactSpelling = true, CharSet = CharSet.Unicode)]
internal static extern int GdipIsEqualRegion(HandleRef region, HandleRef region2, HandleRef graphics,
out int boolean);
- [DllImport(ExternDll.Gdiplus, SetLastError = true, ExactSpelling = true, CharSet = System.Runtime.InteropServices.CharSet.Unicode)] // 3 = Unicode
+ [DllImport(ExternDll.Gdiplus, SetLastError = true, ExactSpelling = true, CharSet = CharSet.Unicode)]
internal static extern int GdipGetRegionDataSize(HandleRef region, out int bufferSize);
- [DllImport(ExternDll.Gdiplus, SetLastError = true, ExactSpelling = true, CharSet = System.Runtime.InteropServices.CharSet.Unicode)] // 3 = Unicode
+ [DllImport(ExternDll.Gdiplus, SetLastError = true, ExactSpelling = true, CharSet = CharSet.Unicode)]
internal static extern int GdipGetRegionData(HandleRef region,
byte[] regionData,
int bufferSize,
out int sizeFilled);
- [DllImport(ExternDll.Gdiplus, SetLastError = true, ExactSpelling = true, CharSet = System.Runtime.InteropServices.CharSet.Unicode)] // 3 = Unicode
+ [DllImport(ExternDll.Gdiplus, SetLastError = true, ExactSpelling = true, CharSet = CharSet.Unicode)]
internal static extern int GdipIsVisibleRegionPoint(HandleRef region, float X, float Y,
HandleRef graphics, out int boolean);
- [DllImport(ExternDll.Gdiplus, SetLastError = true, ExactSpelling = true, CharSet = System.Runtime.InteropServices.CharSet.Unicode)] // 3 = Unicode
+ [DllImport(ExternDll.Gdiplus, SetLastError = true, ExactSpelling = true, CharSet = CharSet.Unicode)]
internal static extern int GdipIsVisibleRegionPointI(HandleRef region, int X, int Y,
HandleRef graphics, out int boolean);
- [DllImport(ExternDll.Gdiplus, SetLastError = true, ExactSpelling = true, CharSet = System.Runtime.InteropServices.CharSet.Unicode)] // 3 = Unicode
+ [DllImport(ExternDll.Gdiplus, SetLastError = true, ExactSpelling = true, CharSet = CharSet.Unicode)]
internal static extern int GdipIsVisibleRegionRect(HandleRef region, float X, float Y,
float width, float height,
HandleRef graphics, out int boolean);
- [DllImport(ExternDll.Gdiplus, SetLastError = true, ExactSpelling = true, CharSet = System.Runtime.InteropServices.CharSet.Unicode)] // 3 = Unicode
+ [DllImport(ExternDll.Gdiplus, SetLastError = true, ExactSpelling = true, CharSet = CharSet.Unicode)]
internal static extern int GdipIsVisibleRegionRectI(HandleRef region, int X, int Y,
int width, int height,
HandleRef graphics, out int boolean);
- [DllImport(ExternDll.Gdiplus, SetLastError = true, ExactSpelling = true, CharSet = System.Runtime.InteropServices.CharSet.Unicode)] // 3 = Unicode
+ [DllImport(ExternDll.Gdiplus, SetLastError = true, ExactSpelling = true, CharSet = CharSet.Unicode)]
internal static extern int GdipGetRegionScansCount(HandleRef region, out int count, HandleRef matrix);
- [DllImport(ExternDll.Gdiplus, SetLastError = true, ExactSpelling = true, CharSet = System.Runtime.InteropServices.CharSet.Unicode)] // 3 = Unicode
+ [DllImport(ExternDll.Gdiplus, SetLastError = true, ExactSpelling = true, CharSet = CharSet.Unicode)]
internal static extern int GdipGetRegionScans(HandleRef region, IntPtr rects, out int count, HandleRef matrix);
@@ -769,324 +721,320 @@ namespace System.Drawing
// Brush methods
//----------------------------------------------------------------------------------------
- [DllImport(ExternDll.Gdiplus, SetLastError = true, ExactSpelling = true, CharSet = System.Runtime.InteropServices.CharSet.Unicode)] // 3 = Unicode
+ [DllImport(ExternDll.Gdiplus, SetLastError = true, ExactSpelling = true, CharSet = CharSet.Unicode)]
internal static extern int GdipCloneBrush(HandleRef brush, out IntPtr clonebrush);
- [DllImport(ExternDll.Gdiplus, SetLastError = true, ExactSpelling = true, EntryPoint = "GdipDeleteBrush", CharSet = System.Runtime.InteropServices.CharSet.Unicode)] // 3 = Unicode
+ [DllImport(ExternDll.Gdiplus, SetLastError = true, ExactSpelling = true, EntryPoint = "GdipDeleteBrush", CharSet = CharSet.Unicode)]
private static extern int IntGdipDeleteBrush(HandleRef brush);
- internal static int GdipDeleteBrush(HandleRef brush)
- {
- if (!Initialized) return SafeNativeMethods.Gdip.Ok;
- int result = IntGdipDeleteBrush(brush);
- return result;
- }
+
+ internal static int GdipDeleteBrush(HandleRef brush) => Initialized ? IntGdipDeleteBrush(brush) : Ok;
//----------------------------------------------------------------------------------------
// Hatch Brush
//----------------------------------------------------------------------------------------
- [DllImport(ExternDll.Gdiplus, SetLastError = true, ExactSpelling = true, CharSet = System.Runtime.InteropServices.CharSet.Unicode)] // 3 = Unicode
+ [DllImport(ExternDll.Gdiplus, SetLastError = true, ExactSpelling = true, CharSet = CharSet.Unicode)]
internal static extern int GdipCreateHatchBrush(int hatchstyle, int forecol, int backcol, out IntPtr brush);
- [DllImport(ExternDll.Gdiplus, SetLastError = true, ExactSpelling = true, CharSet = System.Runtime.InteropServices.CharSet.Unicode)] // 3 = Unicode
+ [DllImport(ExternDll.Gdiplus, SetLastError = true, ExactSpelling = true, CharSet = CharSet.Unicode)]
internal static extern int GdipGetHatchStyle(HandleRef brush, out int hatchstyle);
- [DllImport(ExternDll.Gdiplus, SetLastError = true, ExactSpelling = true, CharSet = System.Runtime.InteropServices.CharSet.Unicode)] // 3 = Unicode
+ [DllImport(ExternDll.Gdiplus, SetLastError = true, ExactSpelling = true, CharSet = CharSet.Unicode)]
internal static extern int GdipGetHatchForegroundColor(HandleRef brush, out int forecol);
- [DllImport(ExternDll.Gdiplus, SetLastError = true, ExactSpelling = true, CharSet = System.Runtime.InteropServices.CharSet.Unicode)] // 3 = Unicode
+ [DllImport(ExternDll.Gdiplus, SetLastError = true, ExactSpelling = true, CharSet = CharSet.Unicode)]
internal static extern int GdipGetHatchBackgroundColor(HandleRef brush, out int backcol);
- [DllImport(ExternDll.Gdiplus, SetLastError = true, ExactSpelling = true, CharSet = System.Runtime.InteropServices.CharSet.Unicode)] // 3 = Unicode
+ [DllImport(ExternDll.Gdiplus, SetLastError = true, ExactSpelling = true, CharSet = CharSet.Unicode)]
internal static extern int GdipCreateTexture(HandleRef bitmap, int wrapmode, out IntPtr texture);
- [DllImport(ExternDll.Gdiplus, SetLastError = true, ExactSpelling = true, CharSet = System.Runtime.InteropServices.CharSet.Unicode)] // 3 = Unicode
+ [DllImport(ExternDll.Gdiplus, SetLastError = true, ExactSpelling = true, CharSet = CharSet.Unicode)]
internal static extern int GdipCreateTexture2(HandleRef bitmap, int wrapmode, float x,
float y, float width, float height,
out IntPtr texture);
- [DllImport(ExternDll.Gdiplus, SetLastError = true, ExactSpelling = true, CharSet = System.Runtime.InteropServices.CharSet.Unicode)] // 3 = Unicode
+ [DllImport(ExternDll.Gdiplus, SetLastError = true, ExactSpelling = true, CharSet = CharSet.Unicode)]
internal static extern int GdipCreateTextureIA(HandleRef bitmap, HandleRef imageAttrib,
float x, float y, float width, float height,
out IntPtr texture);
- [DllImport(ExternDll.Gdiplus, SetLastError = true, ExactSpelling = true, CharSet = System.Runtime.InteropServices.CharSet.Unicode)] // 3 = Unicode
+ [DllImport(ExternDll.Gdiplus, SetLastError = true, ExactSpelling = true, CharSet = CharSet.Unicode)]
internal static extern int GdipCreateTexture2I(HandleRef bitmap, int wrapmode, int x,
int y, int width, int height,
out IntPtr texture);
- [DllImport(ExternDll.Gdiplus, SetLastError = true, ExactSpelling = true, CharSet = System.Runtime.InteropServices.CharSet.Unicode)] // 3 = Unicode
+ [DllImport(ExternDll.Gdiplus, SetLastError = true, ExactSpelling = true, CharSet = CharSet.Unicode)]
internal static extern int GdipCreateTextureIAI(HandleRef bitmap, HandleRef imageAttrib,
int x, int y, int width, int height,
out IntPtr texture);
- [DllImport(ExternDll.Gdiplus, SetLastError = true, ExactSpelling = true, CharSet = System.Runtime.InteropServices.CharSet.Unicode)] // 3 = Unicode
+ [DllImport(ExternDll.Gdiplus, SetLastError = true, ExactSpelling = true, CharSet = CharSet.Unicode)]
internal static extern int GdipSetTextureTransform(HandleRef brush, HandleRef matrix);
- [DllImport(ExternDll.Gdiplus, SetLastError = true, ExactSpelling = true, CharSet = System.Runtime.InteropServices.CharSet.Unicode)] // 3 = Unicode
+ [DllImport(ExternDll.Gdiplus, SetLastError = true, ExactSpelling = true, CharSet = CharSet.Unicode)]
internal static extern int GdipGetTextureTransform(HandleRef brush, HandleRef matrix);
- [DllImport(ExternDll.Gdiplus, SetLastError = true, ExactSpelling = true, CharSet = System.Runtime.InteropServices.CharSet.Unicode)] // 3 = Unicode
+ [DllImport(ExternDll.Gdiplus, SetLastError = true, ExactSpelling = true, CharSet = CharSet.Unicode)]
internal static extern int GdipResetTextureTransform(HandleRef brush);
- [DllImport(ExternDll.Gdiplus, SetLastError = true, ExactSpelling = true, CharSet = System.Runtime.InteropServices.CharSet.Unicode)] // 3 = Unicode
+ [DllImport(ExternDll.Gdiplus, SetLastError = true, ExactSpelling = true, CharSet = CharSet.Unicode)]
internal static extern int GdipMultiplyTextureTransform(HandleRef brush,
HandleRef matrix,
MatrixOrder order);
- [DllImport(ExternDll.Gdiplus, SetLastError = true, ExactSpelling = true, CharSet = System.Runtime.InteropServices.CharSet.Unicode)] // 3 = Unicode
+ [DllImport(ExternDll.Gdiplus, SetLastError = true, ExactSpelling = true, CharSet = CharSet.Unicode)]
internal static extern int GdipTranslateTextureTransform(HandleRef brush,
float dx,
float dy,
MatrixOrder order);
- [DllImport(ExternDll.Gdiplus, SetLastError = true, ExactSpelling = true, CharSet = System.Runtime.InteropServices.CharSet.Unicode)] // 3 = Unicode
+ [DllImport(ExternDll.Gdiplus, SetLastError = true, ExactSpelling = true, CharSet = CharSet.Unicode)]
internal static extern int GdipScaleTextureTransform(HandleRef brush,
float sx,
float sy,
MatrixOrder order);
- [DllImport(ExternDll.Gdiplus, SetLastError = true, ExactSpelling = true, CharSet = System.Runtime.InteropServices.CharSet.Unicode)] // 3 = Unicode
+ [DllImport(ExternDll.Gdiplus, SetLastError = true, ExactSpelling = true, CharSet = CharSet.Unicode)]
internal static extern int GdipRotateTextureTransform(HandleRef brush,
float angle,
MatrixOrder order);
- [DllImport(ExternDll.Gdiplus, SetLastError = true, ExactSpelling = true, CharSet = System.Runtime.InteropServices.CharSet.Unicode)] // 3 = Unicode
+ [DllImport(ExternDll.Gdiplus, SetLastError = true, ExactSpelling = true, CharSet = CharSet.Unicode)]
internal static extern int GdipSetTextureWrapMode(HandleRef brush, int wrapMode);
- [DllImport(ExternDll.Gdiplus, SetLastError = true, ExactSpelling = true, CharSet = System.Runtime.InteropServices.CharSet.Unicode)] // 3 = Unicode
+ [DllImport(ExternDll.Gdiplus, SetLastError = true, ExactSpelling = true, CharSet = CharSet.Unicode)]
internal static extern int GdipGetTextureWrapMode(HandleRef brush, out int wrapMode);
- [DllImport(ExternDll.Gdiplus, SetLastError = true, ExactSpelling = true, CharSet = System.Runtime.InteropServices.CharSet.Unicode)] // 3 = Unicode
+ [DllImport(ExternDll.Gdiplus, SetLastError = true, ExactSpelling = true, CharSet = CharSet.Unicode)]
internal static extern int GdipGetTextureImage(HandleRef brush, out IntPtr image);
- [DllImport(ExternDll.Gdiplus, SetLastError = true, ExactSpelling = true, CharSet = System.Runtime.InteropServices.CharSet.Unicode)] // 3 = Unicode
+ [DllImport(ExternDll.Gdiplus, SetLastError = true, ExactSpelling = true, CharSet = CharSet.Unicode)]
internal static extern int GdipCreateSolidFill(int color, out IntPtr brush);
- [DllImport(ExternDll.Gdiplus, SetLastError = true, ExactSpelling = true, CharSet = System.Runtime.InteropServices.CharSet.Unicode)] // 3 = Unicode
+ [DllImport(ExternDll.Gdiplus, SetLastError = true, ExactSpelling = true, CharSet = CharSet.Unicode)]
internal static extern int GdipSetSolidFillColor(HandleRef brush, int color);
- [DllImport(ExternDll.Gdiplus, SetLastError = true, ExactSpelling = true, CharSet = System.Runtime.InteropServices.CharSet.Unicode)] // 3 = Unicode
+ [DllImport(ExternDll.Gdiplus, SetLastError = true, ExactSpelling = true, CharSet = CharSet.Unicode)]
internal static extern int GdipGetSolidFillColor(HandleRef brush, out int color);
//----------------------------------------------------------------------------------------
// Linear Gradient Brush
//----------------------------------------------------------------------------------------
- [DllImport(ExternDll.Gdiplus, SetLastError = true, ExactSpelling = true, CharSet = System.Runtime.InteropServices.CharSet.Unicode)] // 3 = Unicode
+ [DllImport(ExternDll.Gdiplus, SetLastError = true, ExactSpelling = true, CharSet = CharSet.Unicode)]
internal static extern int GdipCreateLineBrush(GPPOINTF point1, GPPOINTF point2, int color1, int color2, int wrapMode, out IntPtr lineGradient);
- [DllImport(ExternDll.Gdiplus, SetLastError = true, ExactSpelling = true, CharSet = System.Runtime.InteropServices.CharSet.Unicode)] // 3 = Unicode
+ [DllImport(ExternDll.Gdiplus, SetLastError = true, ExactSpelling = true, CharSet = CharSet.Unicode)]
internal static extern int GdipCreateLineBrushI(GPPOINT point1, GPPOINT point2, int color1, int color2, int wrapMode, out IntPtr lineGradient);
- [DllImport(ExternDll.Gdiplus, SetLastError = true, ExactSpelling = true, CharSet = System.Runtime.InteropServices.CharSet.Unicode)] // 3 = Unicode
+ [DllImport(ExternDll.Gdiplus, SetLastError = true, ExactSpelling = true, CharSet = CharSet.Unicode)]
internal static extern int GdipCreateLineBrushFromRect(ref GPRECTF rect, int color1, int color2, int lineGradientMode, int wrapMode,
out IntPtr lineGradient);
- [DllImport(ExternDll.Gdiplus, SetLastError = true, ExactSpelling = true, CharSet = System.Runtime.InteropServices.CharSet.Unicode)] // 3 = Unicode
+ [DllImport(ExternDll.Gdiplus, SetLastError = true, ExactSpelling = true, CharSet = CharSet.Unicode)]
internal static extern int GdipCreateLineBrushFromRectI(ref GPRECT rect, int color1, int color2, int lineGradientMode, int wrapMode,
out IntPtr lineGradient);
- [DllImport(ExternDll.Gdiplus, SetLastError = true, ExactSpelling = true, CharSet = System.Runtime.InteropServices.CharSet.Unicode)] // 3 = Unicode
+ [DllImport(ExternDll.Gdiplus, SetLastError = true, ExactSpelling = true, CharSet = CharSet.Unicode)]
internal static extern int GdipCreateLineBrushFromRectWithAngle(ref GPRECTF rect, int color1, int color2, float angle, bool isAngleScaleable,
int wrapMode, out IntPtr lineGradient);
- [DllImport(ExternDll.Gdiplus, SetLastError = true, ExactSpelling = true, CharSet = System.Runtime.InteropServices.CharSet.Unicode)] // 3 = Unicode
+ [DllImport(ExternDll.Gdiplus, SetLastError = true, ExactSpelling = true, CharSet = CharSet.Unicode)]
internal static extern int GdipCreateLineBrushFromRectWithAngleI(ref GPRECT rect, int color1, int color2, float angle, bool isAngleScaleable,
int wrapMode, out IntPtr lineGradient);
- [DllImport(ExternDll.Gdiplus, SetLastError = true, ExactSpelling = true, CharSet = System.Runtime.InteropServices.CharSet.Unicode)] // 3 = Unicode
+ [DllImport(ExternDll.Gdiplus, SetLastError = true, ExactSpelling = true, CharSet = CharSet.Unicode)]
internal static extern int GdipSetLineColors(HandleRef brush, int color1, int color2);
- [DllImport(ExternDll.Gdiplus, SetLastError = true, ExactSpelling = true, CharSet = System.Runtime.InteropServices.CharSet.Unicode)] // 3 = Unicode
+ [DllImport(ExternDll.Gdiplus, SetLastError = true, ExactSpelling = true, CharSet = CharSet.Unicode)]
internal static extern int GdipGetLineColors(HandleRef brush, int[] colors);
- [DllImport(ExternDll.Gdiplus, SetLastError = true, ExactSpelling = true, CharSet = System.Runtime.InteropServices.CharSet.Unicode)] // 3 = Unicode
+ [DllImport(ExternDll.Gdiplus, SetLastError = true, ExactSpelling = true, CharSet = CharSet.Unicode)]
internal static extern int GdipGetLineRect(HandleRef brush, ref GPRECTF gprectf);
- [DllImport(ExternDll.Gdiplus, SetLastError = true, ExactSpelling = true, CharSet = System.Runtime.InteropServices.CharSet.Unicode)] // 3 = Unicode
+ [DllImport(ExternDll.Gdiplus, SetLastError = true, ExactSpelling = true, CharSet = CharSet.Unicode)]
internal static extern int GdipGetLineGammaCorrection(HandleRef brush, out bool useGammaCorrection);
- [DllImport(ExternDll.Gdiplus, SetLastError = true, ExactSpelling = true, CharSet = System.Runtime.InteropServices.CharSet.Unicode)] // 3 = Unicode
+ [DllImport(ExternDll.Gdiplus, SetLastError = true, ExactSpelling = true, CharSet = CharSet.Unicode)]
internal static extern int GdipSetLineGammaCorrection(HandleRef brush, bool useGammaCorrection);
- [DllImport(ExternDll.Gdiplus, SetLastError = true, ExactSpelling = true, CharSet = System.Runtime.InteropServices.CharSet.Unicode)] // 3 = Unicode
+ [DllImport(ExternDll.Gdiplus, SetLastError = true, ExactSpelling = true, CharSet = CharSet.Unicode)]
internal static extern int GdipSetLineSigmaBlend(HandleRef brush, float focus, float scale);
- [DllImport(ExternDll.Gdiplus, SetLastError = true, ExactSpelling = true, CharSet = System.Runtime.InteropServices.CharSet.Unicode)] // 3 = Unicode
+ [DllImport(ExternDll.Gdiplus, SetLastError = true, ExactSpelling = true, CharSet = CharSet.Unicode)]
internal static extern int GdipSetLineLinearBlend(HandleRef brush, float focus, float scale);
- [DllImport(ExternDll.Gdiplus, SetLastError = true, ExactSpelling = true, CharSet = System.Runtime.InteropServices.CharSet.Unicode)] // 3 = Unicode
+ [DllImport(ExternDll.Gdiplus, SetLastError = true, ExactSpelling = true, CharSet = CharSet.Unicode)]
internal static extern int GdipGetLineBlendCount(HandleRef brush, out int count);
- [DllImport(ExternDll.Gdiplus, SetLastError = true, ExactSpelling = true, CharSet = System.Runtime.InteropServices.CharSet.Unicode)] // 3 = Unicode
+ [DllImport(ExternDll.Gdiplus, SetLastError = true, ExactSpelling = true, CharSet = CharSet.Unicode)]
internal static extern int GdipGetLineBlend(HandleRef brush, IntPtr blend, IntPtr positions, int count);
- [DllImport(ExternDll.Gdiplus, SetLastError = true, ExactSpelling = true, CharSet = System.Runtime.InteropServices.CharSet.Unicode)] // 3 = Unicode
+ [DllImport(ExternDll.Gdiplus, SetLastError = true, ExactSpelling = true, CharSet = CharSet.Unicode)]
internal static extern int GdipSetLineBlend(HandleRef brush, HandleRef blend, HandleRef positions, int count);
- [DllImport(ExternDll.Gdiplus, SetLastError = true, ExactSpelling = true, CharSet = System.Runtime.InteropServices.CharSet.Unicode)] // 3 = Unicode
+ [DllImport(ExternDll.Gdiplus, SetLastError = true, ExactSpelling = true, CharSet = CharSet.Unicode)]
internal static extern int GdipGetLinePresetBlendCount(HandleRef brush, out int count);
- [DllImport(ExternDll.Gdiplus, SetLastError = true, ExactSpelling = true, CharSet = System.Runtime.InteropServices.CharSet.Unicode)] // 3 = Unicode
+ [DllImport(ExternDll.Gdiplus, SetLastError = true, ExactSpelling = true, CharSet = CharSet.Unicode)]
internal static extern int GdipGetLinePresetBlend(HandleRef brush, IntPtr blend, IntPtr positions, int count);
- [DllImport(ExternDll.Gdiplus, SetLastError = true, ExactSpelling = true, CharSet = System.Runtime.InteropServices.CharSet.Unicode)] // 3 = Unicode
+ [DllImport(ExternDll.Gdiplus, SetLastError = true, ExactSpelling = true, CharSet = CharSet.Unicode)]
internal static extern int GdipSetLinePresetBlend(HandleRef brush, HandleRef blend, HandleRef positions, int count);
- [DllImport(ExternDll.Gdiplus, SetLastError = true, ExactSpelling = true, CharSet = System.Runtime.InteropServices.CharSet.Unicode)] // 3 = Unicode
+ [DllImport(ExternDll.Gdiplus, SetLastError = true, ExactSpelling = true, CharSet = CharSet.Unicode)]
internal static extern int GdipSetLineWrapMode(HandleRef brush, int wrapMode);
- [DllImport(ExternDll.Gdiplus, SetLastError = true, ExactSpelling = true, CharSet = System.Runtime.InteropServices.CharSet.Unicode)] // 3 = Unicode
+ [DllImport(ExternDll.Gdiplus, SetLastError = true, ExactSpelling = true, CharSet = CharSet.Unicode)]
internal static extern int GdipGetLineWrapMode(HandleRef brush, out int wrapMode);
- [DllImport(ExternDll.Gdiplus, SetLastError = true, ExactSpelling = true, CharSet = System.Runtime.InteropServices.CharSet.Unicode)] // 3 = Unicode
+ [DllImport(ExternDll.Gdiplus, SetLastError = true, ExactSpelling = true, CharSet = CharSet.Unicode)]
internal static extern int GdipResetLineTransform(HandleRef brush);
- [DllImport(ExternDll.Gdiplus, SetLastError = true, ExactSpelling = true, CharSet = System.Runtime.InteropServices.CharSet.Unicode)] // 3 = Unicode
+ [DllImport(ExternDll.Gdiplus, SetLastError = true, ExactSpelling = true, CharSet = CharSet.Unicode)]
internal static extern int GdipMultiplyLineTransform(HandleRef brush, HandleRef matrix, MatrixOrder order);
- [DllImport(ExternDll.Gdiplus, SetLastError = true, ExactSpelling = true, CharSet = System.Runtime.InteropServices.CharSet.Unicode)] // 3 = Unicode
+ [DllImport(ExternDll.Gdiplus, SetLastError = true, ExactSpelling = true, CharSet = CharSet.Unicode)]
internal static extern int GdipGetLineTransform(HandleRef brush, HandleRef matrix);
- [DllImport(ExternDll.Gdiplus, SetLastError = true, ExactSpelling = true, CharSet = System.Runtime.InteropServices.CharSet.Unicode)] // 3 = Unicode
+ [DllImport(ExternDll.Gdiplus, SetLastError = true, ExactSpelling = true, CharSet = CharSet.Unicode)]
internal static extern int GdipSetLineTransform(HandleRef brush, HandleRef matrix);
- [DllImport(ExternDll.Gdiplus, SetLastError = true, ExactSpelling = true, CharSet = System.Runtime.InteropServices.CharSet.Unicode)] // 3 = Unicode
+ [DllImport(ExternDll.Gdiplus, SetLastError = true, ExactSpelling = true, CharSet = CharSet.Unicode)]
internal static extern int GdipTranslateLineTransform(HandleRef brush, float dx, float dy, MatrixOrder order);
- [DllImport(ExternDll.Gdiplus, SetLastError = true, ExactSpelling = true, CharSet = System.Runtime.InteropServices.CharSet.Unicode)] // 3 = Unicode
+ [DllImport(ExternDll.Gdiplus, SetLastError = true, ExactSpelling = true, CharSet = CharSet.Unicode)]
internal static extern int GdipScaleLineTransform(HandleRef brush, float sx, float sy, MatrixOrder order);
- [DllImport(ExternDll.Gdiplus, SetLastError = true, ExactSpelling = true, CharSet = System.Runtime.InteropServices.CharSet.Unicode)] // 3 = Unicode
+ [DllImport(ExternDll.Gdiplus, SetLastError = true, ExactSpelling = true, CharSet = CharSet.Unicode)]
internal static extern int GdipRotateLineTransform(HandleRef brush, float angle, MatrixOrder order);
//----------------------------------------------------------------------------------------
// Path Gradient Brush
//----------------------------------------------------------------------------------------
- [DllImport(ExternDll.Gdiplus, SetLastError = true, ExactSpelling = true, CharSet = System.Runtime.InteropServices.CharSet.Unicode)] // 3 = Unicode
+ [DllImport(ExternDll.Gdiplus, SetLastError = true, ExactSpelling = true, CharSet = CharSet.Unicode)]
internal static extern int GdipCreatePathGradient(HandleRef points, int count, int wrapMode, out IntPtr brush);
- [DllImport(ExternDll.Gdiplus, SetLastError = true, ExactSpelling = true, CharSet = System.Runtime.InteropServices.CharSet.Unicode)] // 3 = Unicode
+ [DllImport(ExternDll.Gdiplus, SetLastError = true, ExactSpelling = true, CharSet = CharSet.Unicode)]
internal static extern int GdipCreatePathGradientI(HandleRef points, int count, int wrapMode, out IntPtr brush);
- [DllImport(ExternDll.Gdiplus, SetLastError = true, ExactSpelling = true, CharSet = System.Runtime.InteropServices.CharSet.Unicode)] // 3 = Unicode
+ [DllImport(ExternDll.Gdiplus, SetLastError = true, ExactSpelling = true, CharSet = CharSet.Unicode)]
internal static extern int GdipCreatePathGradientFromPath(HandleRef path, out IntPtr brush);
- [DllImport(ExternDll.Gdiplus, SetLastError = true, ExactSpelling = true, CharSet = System.Runtime.InteropServices.CharSet.Unicode)] // 3 = Unicode
+ [DllImport(ExternDll.Gdiplus, SetLastError = true, ExactSpelling = true, CharSet = CharSet.Unicode)]
internal static extern int GdipGetPathGradientCenterColor(HandleRef brush,
out int color);
- [DllImport(ExternDll.Gdiplus, SetLastError = true, ExactSpelling = true, CharSet = System.Runtime.InteropServices.CharSet.Unicode)] // 3 = Unicode
+ [DllImport(ExternDll.Gdiplus, SetLastError = true, ExactSpelling = true, CharSet = CharSet.Unicode)]
internal static extern int GdipSetPathGradientCenterColor(HandleRef brush,
int color);
- [DllImport(ExternDll.Gdiplus, SetLastError = true, ExactSpelling = true, CharSet = System.Runtime.InteropServices.CharSet.Unicode)] // 3 = Unicode
+ [DllImport(ExternDll.Gdiplus, SetLastError = true, ExactSpelling = true, CharSet = CharSet.Unicode)]
internal static extern int GdipGetPathGradientSurroundColorsWithCount(HandleRef brush,
int[] color,
ref int count);
- [DllImport(ExternDll.Gdiplus, SetLastError = true, ExactSpelling = true, CharSet = System.Runtime.InteropServices.CharSet.Unicode)] // 3 = Unicode
+ [DllImport(ExternDll.Gdiplus, SetLastError = true, ExactSpelling = true, CharSet = CharSet.Unicode)]
internal static extern int GdipSetPathGradientSurroundColorsWithCount(HandleRef brush,
int[] argb,
ref int count);
- [DllImport(ExternDll.Gdiplus, SetLastError = true, ExactSpelling = true, CharSet = System.Runtime.InteropServices.CharSet.Unicode)] // 3 = Unicode
+ [DllImport(ExternDll.Gdiplus, SetLastError = true, ExactSpelling = true, CharSet = CharSet.Unicode)]
internal static extern int GdipGetPathGradientCenterPoint(HandleRef brush,
GPPOINTF point);
- [DllImport(ExternDll.Gdiplus, SetLastError = true, ExactSpelling = true, CharSet = System.Runtime.InteropServices.CharSet.Unicode)] // 3 = Unicode
+ [DllImport(ExternDll.Gdiplus, SetLastError = true, ExactSpelling = true, CharSet = CharSet.Unicode)]
internal static extern int GdipSetPathGradientCenterPoint(HandleRef brush,
GPPOINTF point);
- [DllImport(ExternDll.Gdiplus, SetLastError = true, ExactSpelling = true, CharSet = System.Runtime.InteropServices.CharSet.Unicode)] // 3 = Unicode
+ [DllImport(ExternDll.Gdiplus, SetLastError = true, ExactSpelling = true, CharSet = CharSet.Unicode)]
internal static extern int GdipGetPathGradientRect(HandleRef brush,
ref GPRECTF gprectf);
- [DllImport(ExternDll.Gdiplus, SetLastError = true, ExactSpelling = true, CharSet = System.Runtime.InteropServices.CharSet.Unicode)] // 3 = Unicode
+ [DllImport(ExternDll.Gdiplus, SetLastError = true, ExactSpelling = true, CharSet = CharSet.Unicode)]
internal static extern int GdipGetPathGradientPointCount(HandleRef brush,
out int count);
- [DllImport(ExternDll.Gdiplus, SetLastError = true, ExactSpelling = true, CharSet = System.Runtime.InteropServices.CharSet.Unicode)] // 3 = Unicode
+ [DllImport(ExternDll.Gdiplus, SetLastError = true, ExactSpelling = true, CharSet = CharSet.Unicode)]
internal static extern int GdipGetPathGradientSurroundColorCount(HandleRef brush,
out int count);
- [DllImport(ExternDll.Gdiplus, SetLastError = true, ExactSpelling = true, CharSet = System.Runtime.InteropServices.CharSet.Unicode)] // 3 = Unicode
+ [DllImport(ExternDll.Gdiplus, SetLastError = true, ExactSpelling = true, CharSet = CharSet.Unicode)]
internal static extern int GdipGetPathGradientBlendCount(HandleRef brush,
out int count);
- [DllImport(ExternDll.Gdiplus, SetLastError = true, ExactSpelling = true, CharSet = System.Runtime.InteropServices.CharSet.Unicode)] // 3 = Unicode
+ [DllImport(ExternDll.Gdiplus, SetLastError = true, ExactSpelling = true, CharSet = CharSet.Unicode)]
internal static extern int GdipGetPathGradientBlend(HandleRef brush,
IntPtr blend,
IntPtr positions,
int count);
- [DllImport(ExternDll.Gdiplus, SetLastError = true, ExactSpelling = true, CharSet = System.Runtime.InteropServices.CharSet.Unicode)] // 3 = Unicode
+ [DllImport(ExternDll.Gdiplus, SetLastError = true, ExactSpelling = true, CharSet = CharSet.Unicode)]
internal static extern int GdipSetPathGradientBlend(HandleRef brush,
HandleRef blend,
HandleRef positions,
int count);
- [DllImport(ExternDll.Gdiplus, SetLastError = true, ExactSpelling = true, CharSet = System.Runtime.InteropServices.CharSet.Unicode)] // 3 = Unicode
+ [DllImport(ExternDll.Gdiplus, SetLastError = true, ExactSpelling = true, CharSet = CharSet.Unicode)]
internal static extern int GdipGetPathGradientPresetBlendCount(HandleRef brush, out int count);
- [DllImport(ExternDll.Gdiplus, SetLastError = true, ExactSpelling = true, CharSet = System.Runtime.InteropServices.CharSet.Unicode)] // 3 = Unicode
+ [DllImport(ExternDll.Gdiplus, SetLastError = true, ExactSpelling = true, CharSet = CharSet.Unicode)]
internal static extern int GdipGetPathGradientPresetBlend(HandleRef brush, IntPtr blend,
IntPtr positions, int count);
- [DllImport(ExternDll.Gdiplus, SetLastError = true, ExactSpelling = true, CharSet = System.Runtime.InteropServices.CharSet.Unicode)] // 3 = Unicode
+ [DllImport(ExternDll.Gdiplus, SetLastError = true, ExactSpelling = true, CharSet = CharSet.Unicode)]
internal static extern int GdipSetPathGradientPresetBlend(HandleRef brush, HandleRef blend,
HandleRef positions, int count);
- [DllImport(ExternDll.Gdiplus, SetLastError = true, ExactSpelling = true, CharSet = System.Runtime.InteropServices.CharSet.Unicode)] // 3 = Unicode
+ [DllImport(ExternDll.Gdiplus, SetLastError = true, ExactSpelling = true, CharSet = CharSet.Unicode)]
internal static extern int GdipSetPathGradientSigmaBlend(HandleRef brush,
float focus,
float scale);
- [DllImport(ExternDll.Gdiplus, SetLastError = true, ExactSpelling = true, CharSet = System.Runtime.InteropServices.CharSet.Unicode)] // 3 = Unicode
+ [DllImport(ExternDll.Gdiplus, SetLastError = true, ExactSpelling = true, CharSet = CharSet.Unicode)]
internal static extern int GdipSetPathGradientLinearBlend(HandleRef brush,
float focus,
float scale);
- [DllImport(ExternDll.Gdiplus, SetLastError = true, ExactSpelling = true, CharSet = System.Runtime.InteropServices.CharSet.Unicode)] // 3 = Unicode
+ [DllImport(ExternDll.Gdiplus, SetLastError = true, ExactSpelling = true, CharSet = CharSet.Unicode)]
internal static extern int GdipSetPathGradientWrapMode(HandleRef brush,
int wrapmode);
- [DllImport(ExternDll.Gdiplus, SetLastError = true, ExactSpelling = true, CharSet = System.Runtime.InteropServices.CharSet.Unicode)] // 3 = Unicode
+ [DllImport(ExternDll.Gdiplus, SetLastError = true, ExactSpelling = true, CharSet = CharSet.Unicode)]
internal static extern int GdipGetPathGradientWrapMode(HandleRef brush,
out int wrapmode);
- [DllImport(ExternDll.Gdiplus, SetLastError = true, ExactSpelling = true, CharSet = System.Runtime.InteropServices.CharSet.Unicode)] // 3 = Unicode
+ [DllImport(ExternDll.Gdiplus, SetLastError = true, ExactSpelling = true, CharSet = CharSet.Unicode)]
internal static extern int GdipSetPathGradientTransform(HandleRef brush,
HandleRef matrix);
- [DllImport(ExternDll.Gdiplus, SetLastError = true, ExactSpelling = true, CharSet = System.Runtime.InteropServices.CharSet.Unicode)] // 3 = Unicode
+ [DllImport(ExternDll.Gdiplus, SetLastError = true, ExactSpelling = true, CharSet = CharSet.Unicode)]
internal static extern int GdipGetPathGradientTransform(HandleRef brush,
HandleRef matrix);
- [DllImport(ExternDll.Gdiplus, SetLastError = true, ExactSpelling = true, CharSet = System.Runtime.InteropServices.CharSet.Unicode)] // 3 = Unicode
+ [DllImport(ExternDll.Gdiplus, SetLastError = true, ExactSpelling = true, CharSet = CharSet.Unicode)]
internal static extern int GdipResetPathGradientTransform(HandleRef brush);
- [DllImport(ExternDll.Gdiplus, SetLastError = true, ExactSpelling = true, CharSet = System.Runtime.InteropServices.CharSet.Unicode)] // 3 = Unicode
+ [DllImport(ExternDll.Gdiplus, SetLastError = true, ExactSpelling = true, CharSet = CharSet.Unicode)]
internal static extern int GdipMultiplyPathGradientTransform(HandleRef brush, HandleRef matrix, MatrixOrder order);
- [DllImport(ExternDll.Gdiplus, SetLastError = true, ExactSpelling = true, CharSet = System.Runtime.InteropServices.CharSet.Unicode)] // 3 = Unicode
+ [DllImport(ExternDll.Gdiplus, SetLastError = true, ExactSpelling = true, CharSet = CharSet.Unicode)]
internal static extern int GdipTranslatePathGradientTransform(HandleRef brush, float dx, float dy, MatrixOrder order);
- [DllImport(ExternDll.Gdiplus, SetLastError = true, ExactSpelling = true, CharSet = System.Runtime.InteropServices.CharSet.Unicode)] // 3 = Unicode
+ [DllImport(ExternDll.Gdiplus, SetLastError = true, ExactSpelling = true, CharSet = CharSet.Unicode)]
internal static extern int GdipScalePathGradientTransform(HandleRef brush, float sx, float sy, MatrixOrder order);
- [DllImport(ExternDll.Gdiplus, SetLastError = true, ExactSpelling = true, CharSet = System.Runtime.InteropServices.CharSet.Unicode)] // 3 = Unicode
+ [DllImport(ExternDll.Gdiplus, SetLastError = true, ExactSpelling = true, CharSet = CharSet.Unicode)]
internal static extern int GdipRotatePathGradientTransform(HandleRef brush, float angle, MatrixOrder order);
- [DllImport(ExternDll.Gdiplus, SetLastError = true, ExactSpelling = true, CharSet = System.Runtime.InteropServices.CharSet.Unicode)] // 3 = Unicode
+ [DllImport(ExternDll.Gdiplus, SetLastError = true, ExactSpelling = true, CharSet = CharSet.Unicode)]
internal static extern int GdipGetPathGradientFocusScales(HandleRef brush,
float[] xScale,
float[] yScale);
- [DllImport(ExternDll.Gdiplus, SetLastError = true, ExactSpelling = true, CharSet = System.Runtime.InteropServices.CharSet.Unicode)] // 3 = Unicode
+ [DllImport(ExternDll.Gdiplus, SetLastError = true, ExactSpelling = true, CharSet = CharSet.Unicode)]
internal static extern int GdipSetPathGradientFocusScales(HandleRef brush,
float xScale,
float yScale);
@@ -1095,211 +1043,203 @@ namespace System.Drawing
// Pen methods
//----------------------------------------------------------------------------------------
- [DllImport(ExternDll.Gdiplus, SetLastError = true, ExactSpelling = true, CharSet = System.Runtime.InteropServices.CharSet.Unicode)] // 3 = Unicode
+ [DllImport(ExternDll.Gdiplus, SetLastError = true, ExactSpelling = true, CharSet = CharSet.Unicode)]
internal static extern int GdipCreatePen1(int argb, float width, int unit,
out IntPtr pen);
- [DllImport(ExternDll.Gdiplus, SetLastError = true, ExactSpelling = true, CharSet = System.Runtime.InteropServices.CharSet.Unicode)] // 3 = Unicode
+ [DllImport(ExternDll.Gdiplus, SetLastError = true, ExactSpelling = true, CharSet = CharSet.Unicode)]
internal static extern int GdipCreatePen2(HandleRef brush, float width, int unit,
out IntPtr pen);
- [DllImport(ExternDll.Gdiplus, SetLastError = true, ExactSpelling = true, CharSet = System.Runtime.InteropServices.CharSet.Unicode)] // 3 = Unicode
+ [DllImport(ExternDll.Gdiplus, SetLastError = true, ExactSpelling = true, CharSet = CharSet.Unicode)]
internal static extern int GdipClonePen(HandleRef pen, out IntPtr clonepen);
- [DllImport(ExternDll.Gdiplus, SetLastError = true, ExactSpelling = true, EntryPoint = "GdipDeletePen", CharSet = System.Runtime.InteropServices.CharSet.Unicode)] // 3 = Unicode
+ [DllImport(ExternDll.Gdiplus, SetLastError = true, ExactSpelling = true, EntryPoint = "GdipDeletePen", CharSet = CharSet.Unicode)]
private static extern int IntGdipDeletePen(HandleRef Pen);
- internal static int GdipDeletePen(HandleRef pen)
- {
- if (!Initialized) return SafeNativeMethods.Gdip.Ok;
- int result = IntGdipDeletePen(pen);
- return result;
- }
- [DllImport(ExternDll.Gdiplus, SetLastError = true, ExactSpelling = true, CharSet = System.Runtime.InteropServices.CharSet.Unicode)] // 3 = Unicode
+ internal static int GdipDeletePen(HandleRef pen) => Initialized ? IntGdipDeletePen(pen) : Ok;
+
+ [DllImport(ExternDll.Gdiplus, SetLastError = true, ExactSpelling = true, CharSet = CharSet.Unicode)]
internal static extern int GdipSetPenMode(HandleRef pen, PenAlignment penAlign);
- [DllImport(ExternDll.Gdiplus, SetLastError = true, ExactSpelling = true, CharSet = System.Runtime.InteropServices.CharSet.Unicode)] // 3 = Unicode
+ [DllImport(ExternDll.Gdiplus, SetLastError = true, ExactSpelling = true, CharSet = CharSet.Unicode)]
internal static extern int GdipGetPenMode(HandleRef pen, out PenAlignment penAlign);
- [DllImport(ExternDll.Gdiplus, SetLastError = true, ExactSpelling = true, CharSet = System.Runtime.InteropServices.CharSet.Unicode)] // 3 = Unicode
+ [DllImport(ExternDll.Gdiplus, SetLastError = true, ExactSpelling = true, CharSet = CharSet.Unicode)]
internal static extern int GdipSetPenWidth(HandleRef pen, float width);
- [DllImport(ExternDll.Gdiplus, SetLastError = true, ExactSpelling = true, CharSet = System.Runtime.InteropServices.CharSet.Unicode)] // 3 = Unicode
+ [DllImport(ExternDll.Gdiplus, SetLastError = true, ExactSpelling = true, CharSet = CharSet.Unicode)]
internal static extern int GdipGetPenWidth(HandleRef pen, float[] width);
- [DllImport(ExternDll.Gdiplus, SetLastError = true, ExactSpelling = true, CharSet = System.Runtime.InteropServices.CharSet.Unicode)] // 3 = Unicode
+ [DllImport(ExternDll.Gdiplus, SetLastError = true, ExactSpelling = true, CharSet = CharSet.Unicode)]
internal static extern int GdipSetPenLineCap197819(HandleRef pen, int startCap, int endCap, int dashCap);
- [DllImport(ExternDll.Gdiplus, SetLastError = true, ExactSpelling = true, CharSet = System.Runtime.InteropServices.CharSet.Unicode)] // 3 = Unicode
+ [DllImport(ExternDll.Gdiplus, SetLastError = true, ExactSpelling = true, CharSet = CharSet.Unicode)]
internal static extern int GdipSetPenStartCap(HandleRef pen, int startCap);
- [DllImport(ExternDll.Gdiplus, SetLastError = true, ExactSpelling = true, CharSet = System.Runtime.InteropServices.CharSet.Unicode)] // 3 = Unicode
+ [DllImport(ExternDll.Gdiplus, SetLastError = true, ExactSpelling = true, CharSet = CharSet.Unicode)]
internal static extern int GdipSetPenEndCap(HandleRef pen, int endCap);
- [DllImport(ExternDll.Gdiplus, SetLastError = true, ExactSpelling = true, CharSet = System.Runtime.InteropServices.CharSet.Unicode)] // 3 = Unicode
+ [DllImport(ExternDll.Gdiplus, SetLastError = true, ExactSpelling = true, CharSet = CharSet.Unicode)]
internal static extern int GdipGetPenStartCap(HandleRef pen, out int startCap);
- [DllImport(ExternDll.Gdiplus, SetLastError = true, ExactSpelling = true, CharSet = System.Runtime.InteropServices.CharSet.Unicode)] // 3 = Unicode
+ [DllImport(ExternDll.Gdiplus, SetLastError = true, ExactSpelling = true, CharSet = CharSet.Unicode)]
internal static extern int GdipGetPenEndCap(HandleRef pen, out int endCap);
- [DllImport(ExternDll.Gdiplus, SetLastError = true, ExactSpelling = true, CharSet = System.Runtime.InteropServices.CharSet.Unicode)] // 3 = Unicode
+ [DllImport(ExternDll.Gdiplus, SetLastError = true, ExactSpelling = true, CharSet = CharSet.Unicode)]
internal static extern int GdipGetPenDashCap197819(HandleRef pen, out int dashCap);
- [DllImport(ExternDll.Gdiplus, SetLastError = true, ExactSpelling = true, CharSet = System.Runtime.InteropServices.CharSet.Unicode)] // 3 = Unicode
+ [DllImport(ExternDll.Gdiplus, SetLastError = true, ExactSpelling = true, CharSet = CharSet.Unicode)]
internal static extern int GdipSetPenDashCap197819(HandleRef pen, int dashCap);
- [DllImport(ExternDll.Gdiplus, SetLastError = true, ExactSpelling = true, CharSet = System.Runtime.InteropServices.CharSet.Unicode)] // 3 = Unicode
+ [DllImport(ExternDll.Gdiplus, SetLastError = true, ExactSpelling = true, CharSet = CharSet.Unicode)]
internal static extern int GdipSetPenLineJoin(HandleRef pen, int lineJoin);
- [DllImport(ExternDll.Gdiplus, SetLastError = true, ExactSpelling = true, CharSet = System.Runtime.InteropServices.CharSet.Unicode)] // 3 = Unicode
+ [DllImport(ExternDll.Gdiplus, SetLastError = true, ExactSpelling = true, CharSet = CharSet.Unicode)]
internal static extern int GdipGetPenLineJoin(HandleRef pen, out int lineJoin);
- [DllImport(ExternDll.Gdiplus, SetLastError = true, ExactSpelling = true, CharSet = System.Runtime.InteropServices.CharSet.Unicode)] // 3 = Unicode
+ [DllImport(ExternDll.Gdiplus, SetLastError = true, ExactSpelling = true, CharSet = CharSet.Unicode)]
internal static extern int GdipSetPenCustomStartCap(HandleRef pen, HandleRef customCap);
- [DllImport(ExternDll.Gdiplus, SetLastError = true, ExactSpelling = true, CharSet = System.Runtime.InteropServices.CharSet.Unicode)] // 3 = Unicode
+ [DllImport(ExternDll.Gdiplus, SetLastError = true, ExactSpelling = true, CharSet = CharSet.Unicode)]
internal static extern int GdipGetPenCustomStartCap(HandleRef pen, out IntPtr customCap);
- [DllImport(ExternDll.Gdiplus, SetLastError = true, ExactSpelling = true, CharSet = System.Runtime.InteropServices.CharSet.Unicode)] // 3 = Unicode
+ [DllImport(ExternDll.Gdiplus, SetLastError = true, ExactSpelling = true, CharSet = CharSet.Unicode)]
internal static extern int GdipSetPenCustomEndCap(HandleRef pen, HandleRef customCap);
- [DllImport(ExternDll.Gdiplus, SetLastError = true, ExactSpelling = true, CharSet = System.Runtime.InteropServices.CharSet.Unicode)] // 3 = Unicode
+ [DllImport(ExternDll.Gdiplus, SetLastError = true, ExactSpelling = true, CharSet = CharSet.Unicode)]
internal static extern int GdipGetPenCustomEndCap(HandleRef pen, out IntPtr customCap);
- [DllImport(ExternDll.Gdiplus, SetLastError = true, ExactSpelling = true, CharSet = System.Runtime.InteropServices.CharSet.Unicode)] // 3 = Unicode
+ [DllImport(ExternDll.Gdiplus, SetLastError = true, ExactSpelling = true, CharSet = CharSet.Unicode)]
internal static extern int GdipSetPenMiterLimit(HandleRef pen, float miterLimit);
- [DllImport(ExternDll.Gdiplus, SetLastError = true, ExactSpelling = true, CharSet = System.Runtime.InteropServices.CharSet.Unicode)] // 3 = Unicode
+ [DllImport(ExternDll.Gdiplus, SetLastError = true, ExactSpelling = true, CharSet = CharSet.Unicode)]
internal static extern int GdipGetPenMiterLimit(HandleRef pen, float[] miterLimit);
- [DllImport(ExternDll.Gdiplus, SetLastError = true, ExactSpelling = true, CharSet = System.Runtime.InteropServices.CharSet.Unicode)] // 3 = Unicode
+ [DllImport(ExternDll.Gdiplus, SetLastError = true, ExactSpelling = true, CharSet = CharSet.Unicode)]
internal static extern int GdipSetPenTransform(HandleRef pen, HandleRef matrix);
- [DllImport(ExternDll.Gdiplus, SetLastError = true, ExactSpelling = true, CharSet = System.Runtime.InteropServices.CharSet.Unicode)] // 3 = Unicode
+ [DllImport(ExternDll.Gdiplus, SetLastError = true, ExactSpelling = true, CharSet = CharSet.Unicode)]
internal static extern int GdipGetPenTransform(HandleRef pen, HandleRef matrix);
- [DllImport(ExternDll.Gdiplus, SetLastError = true, ExactSpelling = true, CharSet = System.Runtime.InteropServices.CharSet.Unicode)] // 3 = Unicode
+ [DllImport(ExternDll.Gdiplus, SetLastError = true, ExactSpelling = true, CharSet = CharSet.Unicode)]
internal static extern int GdipResetPenTransform(HandleRef brush);
- [DllImport(ExternDll.Gdiplus, SetLastError = true, ExactSpelling = true, CharSet = System.Runtime.InteropServices.CharSet.Unicode)] // 3 = Unicode
+ [DllImport(ExternDll.Gdiplus, SetLastError = true, ExactSpelling = true, CharSet = CharSet.Unicode)]
internal static extern int GdipMultiplyPenTransform(HandleRef brush, HandleRef matrix, MatrixOrder order);
- [DllImport(ExternDll.Gdiplus, SetLastError = true, ExactSpelling = true, CharSet = System.Runtime.InteropServices.CharSet.Unicode)] // 3 = Unicode
+ [DllImport(ExternDll.Gdiplus, SetLastError = true, ExactSpelling = true, CharSet = CharSet.Unicode)]
internal static extern int GdipTranslatePenTransform(HandleRef brush, float dx, float dy, MatrixOrder order);
- [DllImport(ExternDll.Gdiplus, SetLastError = true, ExactSpelling = true, CharSet = System.Runtime.InteropServices.CharSet.Unicode)] // 3 = Unicode
+ [DllImport(ExternDll.Gdiplus, SetLastError = true, ExactSpelling = true, CharSet = CharSet.Unicode)]
internal static extern int GdipScalePenTransform(HandleRef brush, float sx, float sy, MatrixOrder order);
- [DllImport(ExternDll.Gdiplus, SetLastError = true, ExactSpelling = true, CharSet = System.Runtime.InteropServices.CharSet.Unicode)] // 3 = Unicode
+ [DllImport(ExternDll.Gdiplus, SetLastError = true, ExactSpelling = true, CharSet = CharSet.Unicode)]
internal static extern int GdipRotatePenTransform(HandleRef brush, float angle, MatrixOrder order);
- [DllImport(ExternDll.Gdiplus, SetLastError = true, ExactSpelling = true, CharSet = System.Runtime.InteropServices.CharSet.Unicode)] // 3 = Unicode
+ [DllImport(ExternDll.Gdiplus, SetLastError = true, ExactSpelling = true, CharSet = CharSet.Unicode)]
internal static extern int GdipSetPenColor(HandleRef pen, int argb);
- [DllImport(ExternDll.Gdiplus, SetLastError = true, ExactSpelling = true, CharSet = System.Runtime.InteropServices.CharSet.Unicode)] // 3 = Unicode
+ [DllImport(ExternDll.Gdiplus, SetLastError = true, ExactSpelling = true, CharSet = CharSet.Unicode)]
internal static extern int GdipGetPenColor(HandleRef pen, out int argb);
- [DllImport(ExternDll.Gdiplus, SetLastError = true, ExactSpelling = true, CharSet = System.Runtime.InteropServices.CharSet.Unicode)] // 3 = Unicode
+ [DllImport(ExternDll.Gdiplus, SetLastError = true, ExactSpelling = true, CharSet = CharSet.Unicode)]
internal static extern int GdipSetPenBrushFill(HandleRef pen, HandleRef brush);
- [DllImport(ExternDll.Gdiplus, SetLastError = true, ExactSpelling = true, CharSet = System.Runtime.InteropServices.CharSet.Unicode)] // 3 = Unicode
+ [DllImport(ExternDll.Gdiplus, SetLastError = true, ExactSpelling = true, CharSet = CharSet.Unicode)]
internal static extern int GdipGetPenBrushFill(HandleRef pen, out IntPtr brush);
- [DllImport(ExternDll.Gdiplus, SetLastError = true, ExactSpelling = true, CharSet = System.Runtime.InteropServices.CharSet.Unicode)] // 3 = Unicode
+ [DllImport(ExternDll.Gdiplus, SetLastError = true, ExactSpelling = true, CharSet = CharSet.Unicode)]
internal static extern int GdipGetPenFillType(HandleRef pen, out int pentype);
- [DllImport(ExternDll.Gdiplus, SetLastError = true, ExactSpelling = true, CharSet = System.Runtime.InteropServices.CharSet.Unicode)] // 3 = Unicode
+ [DllImport(ExternDll.Gdiplus, SetLastError = true, ExactSpelling = true, CharSet = CharSet.Unicode)]
internal static extern int GdipGetPenDashStyle(HandleRef pen, out int dashstyle);
- [DllImport(ExternDll.Gdiplus, SetLastError = true, ExactSpelling = true, CharSet = System.Runtime.InteropServices.CharSet.Unicode)] // 3 = Unicode
+ [DllImport(ExternDll.Gdiplus, SetLastError = true, ExactSpelling = true, CharSet = CharSet.Unicode)]
internal static extern int GdipSetPenDashStyle(HandleRef pen, int dashstyle);
- [DllImport(ExternDll.Gdiplus, SetLastError = true, ExactSpelling = true, CharSet = System.Runtime.InteropServices.CharSet.Unicode)] // 3 = Unicode
+ [DllImport(ExternDll.Gdiplus, SetLastError = true, ExactSpelling = true, CharSet = CharSet.Unicode)]
internal static extern int GdipSetPenDashArray(HandleRef pen, HandleRef memorydash, int count);
- [DllImport(ExternDll.Gdiplus, SetLastError = true, ExactSpelling = true, CharSet = System.Runtime.InteropServices.CharSet.Unicode)] // 3 = Unicode
+ [DllImport(ExternDll.Gdiplus, SetLastError = true, ExactSpelling = true, CharSet = CharSet.Unicode)]
internal static extern int GdipGetPenDashOffset(HandleRef pen, float[] dashoffset);
- [DllImport(ExternDll.Gdiplus, SetLastError = true, ExactSpelling = true, CharSet = System.Runtime.InteropServices.CharSet.Unicode)] // 3 = Unicode
+ [DllImport(ExternDll.Gdiplus, SetLastError = true, ExactSpelling = true, CharSet = CharSet.Unicode)]
internal static extern int GdipSetPenDashOffset(HandleRef pen, float dashoffset);
- [DllImport(ExternDll.Gdiplus, SetLastError = true, ExactSpelling = true, CharSet = System.Runtime.InteropServices.CharSet.Unicode)] // 3 = Unicode
+ [DllImport(ExternDll.Gdiplus, SetLastError = true, ExactSpelling = true, CharSet = CharSet.Unicode)]
internal static extern int GdipGetPenDashCount(HandleRef pen, out int dashcount);
- [DllImport(ExternDll.Gdiplus, SetLastError = true, ExactSpelling = true, CharSet = System.Runtime.InteropServices.CharSet.Unicode)] // 3 = Unicode
+ [DllImport(ExternDll.Gdiplus, SetLastError = true, ExactSpelling = true, CharSet = CharSet.Unicode)]
internal static extern int GdipGetPenDashArray(HandleRef pen, IntPtr memorydash, int count);
- [DllImport(ExternDll.Gdiplus, SetLastError = true, ExactSpelling = true, CharSet = System.Runtime.InteropServices.CharSet.Unicode)] // 3 = Unicode
+ [DllImport(ExternDll.Gdiplus, SetLastError = true, ExactSpelling = true, CharSet = CharSet.Unicode)]
internal static extern int GdipGetPenCompoundCount(HandleRef pen, out int count);
- [DllImport(ExternDll.Gdiplus, SetLastError = true, ExactSpelling = true, CharSet = System.Runtime.InteropServices.CharSet.Unicode)] // 3 = Unicode
+ [DllImport(ExternDll.Gdiplus, SetLastError = true, ExactSpelling = true, CharSet = CharSet.Unicode)]
internal static extern int GdipSetPenCompoundArray(HandleRef pen, float[] array, int count);
- [DllImport(ExternDll.Gdiplus, SetLastError = true, ExactSpelling = true, CharSet = System.Runtime.InteropServices.CharSet.Unicode)] // 3 = Unicode
+ [DllImport(ExternDll.Gdiplus, SetLastError = true, ExactSpelling = true, CharSet = CharSet.Unicode)]
internal static extern int GdipGetPenCompoundArray(HandleRef pen, float[] array, int count);
//----------------------------------------------------------------------------------------
// CustomLineCap methods
//----------------------------------------------------------------------------------------
- [DllImport(ExternDll.Gdiplus, SetLastError = true, ExactSpelling = true, CharSet = System.Runtime.InteropServices.CharSet.Unicode)] // 3 = Unicode
+ [DllImport(ExternDll.Gdiplus, SetLastError = true, ExactSpelling = true, CharSet = CharSet.Unicode)]
internal static extern int GdipCreateCustomLineCap(HandleRef fillpath, HandleRef strokepath, LineCap baseCap, float baseInset, out IntPtr customCap);
- [DllImport(ExternDll.Gdiplus, SetLastError = true, ExactSpelling = true, EntryPoint = "GdipDeleteCustomLineCap", CharSet = System.Runtime.InteropServices.CharSet.Unicode)] // 3 = Unicode
+ [DllImport(ExternDll.Gdiplus, SetLastError = true, ExactSpelling = true, EntryPoint = "GdipDeleteCustomLineCap", CharSet = CharSet.Unicode)]
private static extern int IntGdipDeleteCustomLineCap(HandleRef customCap);
- internal static int GdipDeleteCustomLineCap(HandleRef customCap)
- {
- if (!Initialized) return SafeNativeMethods.Gdip.Ok;
- int result = IntGdipDeleteCustomLineCap(customCap);
- return result;
- }
- [DllImport(ExternDll.Gdiplus, SetLastError = true, ExactSpelling = true, CharSet = System.Runtime.InteropServices.CharSet.Unicode)] // 3 = Unicode
+ internal static int GdipDeleteCustomLineCap(HandleRef customCap) => Initialized ? IntGdipDeleteCustomLineCap(customCap) : Ok;
+
+ [DllImport(ExternDll.Gdiplus, SetLastError = true, ExactSpelling = true, CharSet = CharSet.Unicode)]
internal static extern int GdipCloneCustomLineCap(HandleRef customCap, out IntPtr clonedCap);
- [DllImport(ExternDll.Gdiplus, SetLastError = true, ExactSpelling = true, CharSet = System.Runtime.InteropServices.CharSet.Unicode)] // 3 = Unicode
+ [DllImport(ExternDll.Gdiplus, SetLastError = true, ExactSpelling = true, CharSet = CharSet.Unicode)]
internal static extern int GdipGetCustomLineCapType(HandleRef customCap,
out CustomLineCapType capType);
- [DllImport(ExternDll.Gdiplus, SetLastError = true, ExactSpelling = true, CharSet = System.Runtime.InteropServices.CharSet.Unicode)] // 3 = Unicode
+ [DllImport(ExternDll.Gdiplus, SetLastError = true, ExactSpelling = true, CharSet = CharSet.Unicode)]
internal static extern int GdipSetCustomLineCapStrokeCaps(HandleRef customCap,
LineCap startCap,
LineCap endCap);
- [DllImport(ExternDll.Gdiplus, SetLastError = true, ExactSpelling = true, CharSet = System.Runtime.InteropServices.CharSet.Unicode)] // 3 = Unicode
+ [DllImport(ExternDll.Gdiplus, SetLastError = true, ExactSpelling = true, CharSet = CharSet.Unicode)]
internal static extern int GdipGetCustomLineCapStrokeCaps(HandleRef customCap,
out LineCap startCap,
out LineCap endCap);
- [DllImport(ExternDll.Gdiplus, SetLastError = true, ExactSpelling = true, CharSet = System.Runtime.InteropServices.CharSet.Unicode)] // 3 = Unicode
+ [DllImport(ExternDll.Gdiplus, SetLastError = true, ExactSpelling = true, CharSet = CharSet.Unicode)]
internal static extern int GdipSetCustomLineCapStrokeJoin(HandleRef customCap,
LineJoin lineJoin);
- [DllImport(ExternDll.Gdiplus, SetLastError = true, ExactSpelling = true, CharSet = System.Runtime.InteropServices.CharSet.Unicode)] // 3 = Unicode
+ [DllImport(ExternDll.Gdiplus, SetLastError = true, ExactSpelling = true, CharSet = CharSet.Unicode)]
internal static extern int GdipGetCustomLineCapStrokeJoin(HandleRef customCap,
out LineJoin lineJoin);
- [DllImport(ExternDll.Gdiplus, SetLastError = true, ExactSpelling = true, CharSet = System.Runtime.InteropServices.CharSet.Unicode)] // 3 = Unicode
+ [DllImport(ExternDll.Gdiplus, SetLastError = true, ExactSpelling = true, CharSet = CharSet.Unicode)]
internal static extern int GdipSetCustomLineCapBaseCap(HandleRef customCap,
LineCap baseCap);
- [DllImport(ExternDll.Gdiplus, SetLastError = true, ExactSpelling = true, CharSet = System.Runtime.InteropServices.CharSet.Unicode)] // 3 = Unicode
+ [DllImport(ExternDll.Gdiplus, SetLastError = true, ExactSpelling = true, CharSet = CharSet.Unicode)]
internal static extern int GdipGetCustomLineCapBaseCap(HandleRef customCap,
out LineCap baseCap);
- [DllImport(ExternDll.Gdiplus, SetLastError = true, ExactSpelling = true, CharSet = System.Runtime.InteropServices.CharSet.Unicode)] // 3 = Unicode
+ [DllImport(ExternDll.Gdiplus, SetLastError = true, ExactSpelling = true, CharSet = CharSet.Unicode)]
internal static extern int GdipSetCustomLineCapBaseInset(HandleRef customCap,
float inset);
- [DllImport(ExternDll.Gdiplus, SetLastError = true, ExactSpelling = true, CharSet = System.Runtime.InteropServices.CharSet.Unicode)] // 3 = Unicode
+ [DllImport(ExternDll.Gdiplus, SetLastError = true, ExactSpelling = true, CharSet = CharSet.Unicode)]
internal static extern int GdipGetCustomLineCapBaseInset(HandleRef customCap,
out float inset);
- [DllImport(ExternDll.Gdiplus, SetLastError = true, ExactSpelling = true, CharSet = System.Runtime.InteropServices.CharSet.Unicode)] // 3 = Unicode
+ [DllImport(ExternDll.Gdiplus, SetLastError = true, ExactSpelling = true, CharSet = CharSet.Unicode)]
internal static extern int GdipSetCustomLineCapWidthScale(HandleRef customCap,
float widthScale);
- [DllImport(ExternDll.Gdiplus, SetLastError = true, ExactSpelling = true, CharSet = System.Runtime.InteropServices.CharSet.Unicode)] // 3 = Unicode
+ [DllImport(ExternDll.Gdiplus, SetLastError = true, ExactSpelling = true, CharSet = CharSet.Unicode)]
internal static extern int GdipGetCustomLineCapWidthScale(HandleRef customCap,
out float widthScale);
@@ -1307,38 +1247,38 @@ namespace System.Drawing
// AdjustableArrowCap methods
//----------------------------------------------------------------------------------------
- [DllImport(ExternDll.Gdiplus, SetLastError = true, ExactSpelling = true, CharSet = System.Runtime.InteropServices.CharSet.Unicode)] // 3 = Unicode
+ [DllImport(ExternDll.Gdiplus, SetLastError = true, ExactSpelling = true, CharSet = CharSet.Unicode)]
internal static extern int GdipCreateAdjustableArrowCap(float height, float width, bool isFilled, out IntPtr adjustableArrowCap);
- [DllImport(ExternDll.Gdiplus, SetLastError = true, ExactSpelling = true, CharSet = System.Runtime.InteropServices.CharSet.Unicode)] // 3 = Unicode
+ [DllImport(ExternDll.Gdiplus, SetLastError = true, ExactSpelling = true, CharSet = CharSet.Unicode)]
internal static extern int GdipSetAdjustableArrowCapHeight(HandleRef adjustableArrowCap,
float height);
- [DllImport(ExternDll.Gdiplus, SetLastError = true, ExactSpelling = true, CharSet = System.Runtime.InteropServices.CharSet.Unicode)] // 3 = Unicode
+ [DllImport(ExternDll.Gdiplus, SetLastError = true, ExactSpelling = true, CharSet = CharSet.Unicode)]
internal static extern int GdipGetAdjustableArrowCapHeight(HandleRef adjustableArrowCap,
out float height);
- [DllImport(ExternDll.Gdiplus, SetLastError = true, ExactSpelling = true, CharSet = System.Runtime.InteropServices.CharSet.Unicode)] // 3 = Unicode
+ [DllImport(ExternDll.Gdiplus, SetLastError = true, ExactSpelling = true, CharSet = CharSet.Unicode)]
internal static extern int GdipSetAdjustableArrowCapWidth(HandleRef adjustableArrowCap,
float width);
- [DllImport(ExternDll.Gdiplus, SetLastError = true, ExactSpelling = true, CharSet = System.Runtime.InteropServices.CharSet.Unicode)] // 3 = Unicode
+ [DllImport(ExternDll.Gdiplus, SetLastError = true, ExactSpelling = true, CharSet = CharSet.Unicode)]
internal static extern int GdipGetAdjustableArrowCapWidth(HandleRef adjustableArrowCap,
out float width);
- [DllImport(ExternDll.Gdiplus, SetLastError = true, ExactSpelling = true, CharSet = System.Runtime.InteropServices.CharSet.Unicode)] // 3 = Unicode
+ [DllImport(ExternDll.Gdiplus, SetLastError = true, ExactSpelling = true, CharSet = CharSet.Unicode)]
internal static extern int GdipSetAdjustableArrowCapMiddleInset(HandleRef adjustableArrowCap,
float middleInset);
- [DllImport(ExternDll.Gdiplus, SetLastError = true, ExactSpelling = true, CharSet = System.Runtime.InteropServices.CharSet.Unicode)] // 3 = Unicode
+ [DllImport(ExternDll.Gdiplus, SetLastError = true, ExactSpelling = true, CharSet = CharSet.Unicode)]
internal static extern int GdipGetAdjustableArrowCapMiddleInset(HandleRef adjustableArrowCap,
out float middleInset);
- [DllImport(ExternDll.Gdiplus, SetLastError = true, ExactSpelling = true, CharSet = System.Runtime.InteropServices.CharSet.Unicode)] // 3 = Unicode
+ [DllImport(ExternDll.Gdiplus, SetLastError = true, ExactSpelling = true, CharSet = CharSet.Unicode)]
internal static extern int GdipSetAdjustableArrowCapFillState(HandleRef adjustableArrowCap,
bool fillState);
- [DllImport(ExternDll.Gdiplus, SetLastError = true, ExactSpelling = true, CharSet = System.Runtime.InteropServices.CharSet.Unicode)] // 3 = Unicode
+ [DllImport(ExternDll.Gdiplus, SetLastError = true, ExactSpelling = true, CharSet = CharSet.Unicode)]
internal static extern int GdipGetAdjustableArrowCapFillState(HandleRef adjustableArrowCap,
out bool fillState);
@@ -1346,239 +1286,231 @@ namespace System.Drawing
// Image methods
//----------------------------------------------------------------------------------------
- [DllImport(ExternDll.Gdiplus, SetLastError = true, ExactSpelling = true, CharSet = System.Runtime.InteropServices.CharSet.Unicode)] // 3 = Unicode
+ [DllImport(ExternDll.Gdiplus, SetLastError = true, ExactSpelling = true, CharSet = CharSet.Unicode)]
internal static extern int GdipLoadImageFromStream(UnsafeNativeMethods.IStream stream, out IntPtr image);
- [DllImport(ExternDll.Gdiplus, SetLastError = true, ExactSpelling = true, CharSet = System.Runtime.InteropServices.CharSet.Unicode)] // 3 = Unicode
+ [DllImport(ExternDll.Gdiplus, SetLastError = true, ExactSpelling = true, CharSet = CharSet.Unicode)]
internal static extern int GdipLoadImageFromFile(string filename, out IntPtr image);
- [DllImport(ExternDll.Gdiplus, SetLastError = true, ExactSpelling = true, CharSet = System.Runtime.InteropServices.CharSet.Unicode)] // 3 = Unicode
+ [DllImport(ExternDll.Gdiplus, SetLastError = true, ExactSpelling = true, CharSet = CharSet.Unicode)]
internal static extern int GdipLoadImageFromStreamICM(UnsafeNativeMethods.IStream stream, out IntPtr image);
- [DllImport(ExternDll.Gdiplus, SetLastError = true, ExactSpelling = true, CharSet = System.Runtime.InteropServices.CharSet.Unicode)] // 3 = Unicode
+ [DllImport(ExternDll.Gdiplus, SetLastError = true, ExactSpelling = true, CharSet = CharSet.Unicode)]
internal static extern int GdipLoadImageFromFileICM(string filename, out IntPtr image);
- [DllImport(ExternDll.Gdiplus, SetLastError = true, ExactSpelling = true, CharSet = System.Runtime.InteropServices.CharSet.Unicode)] // 3 = Unicode
+ [DllImport(ExternDll.Gdiplus, SetLastError = true, ExactSpelling = true, CharSet = CharSet.Unicode)]
internal static extern int GdipCloneImage(HandleRef image, out IntPtr cloneimage);
- [DllImport(ExternDll.Gdiplus, SetLastError = true, ExactSpelling = true, EntryPoint = "GdipDisposeImage", CharSet = System.Runtime.InteropServices.CharSet.Unicode)] // 3 = Unicode
+ [DllImport(ExternDll.Gdiplus, SetLastError = true, ExactSpelling = true, EntryPoint = "GdipDisposeImage", CharSet = CharSet.Unicode)]
private static extern int IntGdipDisposeImage(HandleRef image);
- internal static int GdipDisposeImage(HandleRef image)
- {
- if (!Initialized) return SafeNativeMethods.Gdip.Ok;
- int result = IntGdipDisposeImage(image);
- return result;
- }
- [DllImport(ExternDll.Gdiplus, SetLastError = true, ExactSpelling = true, CharSet = System.Runtime.InteropServices.CharSet.Unicode)] // 3 = Unicode
+ internal static int GdipDisposeImage(HandleRef image) => Initialized ? IntGdipDisposeImage(image) : Ok;
+
+ [DllImport(ExternDll.Gdiplus, SetLastError = true, ExactSpelling = true, CharSet = CharSet.Unicode)]
internal static extern int GdipSaveImageToFile(HandleRef image, string filename,
ref Guid classId, HandleRef encoderParams);
- [DllImport(ExternDll.Gdiplus, SetLastError = true, ExactSpelling = true, CharSet = System.Runtime.InteropServices.CharSet.Unicode)] // 3 = Unicode
+ [DllImport(ExternDll.Gdiplus, SetLastError = true, ExactSpelling = true, CharSet = CharSet.Unicode)]
internal static extern int GdipSaveImageToStream(HandleRef image, UnsafeNativeMethods.IStream stream,
ref Guid classId, HandleRef encoderParams);
- [DllImport(ExternDll.Gdiplus, SetLastError = true, ExactSpelling = true, CharSet = System.Runtime.InteropServices.CharSet.Unicode)] // 3 = Unicode
+ [DllImport(ExternDll.Gdiplus, SetLastError = true, ExactSpelling = true, CharSet = CharSet.Unicode)]
internal static extern int GdipSaveAdd(HandleRef image, HandleRef encoderParams);
- [DllImport(ExternDll.Gdiplus, SetLastError = true, ExactSpelling = true, CharSet = System.Runtime.InteropServices.CharSet.Unicode)] // 3 = Unicode
+ [DllImport(ExternDll.Gdiplus, SetLastError = true, ExactSpelling = true, CharSet = CharSet.Unicode)]
internal static extern int GdipSaveAddImage(HandleRef image, HandleRef newImage, HandleRef encoderParams);
- [DllImport(ExternDll.Gdiplus, SetLastError = true, ExactSpelling = true, CharSet = System.Runtime.InteropServices.CharSet.Unicode)] // 3 = Unicode
+ [DllImport(ExternDll.Gdiplus, SetLastError = true, ExactSpelling = true, CharSet = CharSet.Unicode)]
internal static extern int GdipGetImageGraphicsContext(HandleRef image, out IntPtr graphics);
- [DllImport(ExternDll.Gdiplus, SetLastError = true, ExactSpelling = true, CharSet = System.Runtime.InteropServices.CharSet.Unicode)] // 3 = Unicode
+ [DllImport(ExternDll.Gdiplus, SetLastError = true, ExactSpelling = true, CharSet = CharSet.Unicode)]
internal static extern int GdipGetImageBounds(HandleRef image, ref GPRECTF gprectf, out GraphicsUnit unit);
- [DllImport(ExternDll.Gdiplus, SetLastError = true, ExactSpelling = true, CharSet = System.Runtime.InteropServices.CharSet.Unicode)] // 3 = Unicode
+ [DllImport(ExternDll.Gdiplus, SetLastError = true, ExactSpelling = true, CharSet = CharSet.Unicode)]
internal static extern int GdipGetImageDimension(HandleRef image, out float width, out float height);
- [DllImport(ExternDll.Gdiplus, SetLastError = true, ExactSpelling = true, CharSet = System.Runtime.InteropServices.CharSet.Unicode)] // 3 = Unicode
+ [DllImport(ExternDll.Gdiplus, SetLastError = true, ExactSpelling = true, CharSet = CharSet.Unicode)]
internal static extern int GdipGetImageType(HandleRef image, out int type);
- [DllImport(ExternDll.Gdiplus, SetLastError = true, ExactSpelling = true, CharSet = System.Runtime.InteropServices.CharSet.Unicode)] // 3 = Unicode
+ [DllImport(ExternDll.Gdiplus, SetLastError = true, ExactSpelling = true, CharSet = CharSet.Unicode)]
internal static extern int GdipGetImageWidth(HandleRef image, out int width);
- [DllImport(ExternDll.Gdiplus, SetLastError = true, ExactSpelling = true, CharSet = System.Runtime.InteropServices.CharSet.Unicode)] // 3 = Unicode
+ [DllImport(ExternDll.Gdiplus, SetLastError = true, ExactSpelling = true, CharSet = CharSet.Unicode)]
internal static extern int GdipGetImageHeight(HandleRef image, out int height);
- [DllImport(ExternDll.Gdiplus, SetLastError = true, ExactSpelling = true, CharSet = System.Runtime.InteropServices.CharSet.Unicode)] // 3 = Unicode
+ [DllImport(ExternDll.Gdiplus, SetLastError = true, ExactSpelling = true, CharSet = CharSet.Unicode)]
internal static extern int GdipGetImageHorizontalResolution(HandleRef image, out float horzRes);
- [DllImport(ExternDll.Gdiplus, SetLastError = true, ExactSpelling = true, CharSet = System.Runtime.InteropServices.CharSet.Unicode)] // 3 = Unicode
+ [DllImport(ExternDll.Gdiplus, SetLastError = true, ExactSpelling = true, CharSet = CharSet.Unicode)]
internal static extern int GdipGetImageVerticalResolution(HandleRef image, out float vertRes);
- [DllImport(ExternDll.Gdiplus, SetLastError = true, ExactSpelling = true, CharSet = System.Runtime.InteropServices.CharSet.Unicode)] // 3 = Unicode
+ [DllImport(ExternDll.Gdiplus, SetLastError = true, ExactSpelling = true, CharSet = CharSet.Unicode)]
internal static extern int GdipGetImageFlags(HandleRef image, out int flags);
- [DllImport(ExternDll.Gdiplus, SetLastError = true, ExactSpelling = true, CharSet = System.Runtime.InteropServices.CharSet.Unicode)] // 3 = Unicode
+ [DllImport(ExternDll.Gdiplus, SetLastError = true, ExactSpelling = true, CharSet = CharSet.Unicode)]
internal static extern int GdipGetImageRawFormat(HandleRef image, ref Guid format);
- [DllImport(ExternDll.Gdiplus, SetLastError = true, ExactSpelling = true, CharSet = System.Runtime.InteropServices.CharSet.Unicode)] // 3 = Unicode
+ [DllImport(ExternDll.Gdiplus, SetLastError = true, ExactSpelling = true, CharSet = CharSet.Unicode)]
internal static extern int GdipGetImagePixelFormat(HandleRef image, out int format);
- [DllImport(ExternDll.Gdiplus, SetLastError = true, ExactSpelling = true, CharSet = System.Runtime.InteropServices.CharSet.Unicode)] // 3 = Unicode
+ [DllImport(ExternDll.Gdiplus, SetLastError = true, ExactSpelling = true, CharSet = CharSet.Unicode)]
internal static extern int GdipGetImageThumbnail(HandleRef image, int thumbWidth, int thumbHeight,
out IntPtr thumbImage,
Image.GetThumbnailImageAbort callback,
IntPtr callbackdata);
- [DllImport(ExternDll.Gdiplus, SetLastError = true, ExactSpelling = true, CharSet = System.Runtime.InteropServices.CharSet.Unicode)] // 3 = Unicode
+ [DllImport(ExternDll.Gdiplus, SetLastError = true, ExactSpelling = true, CharSet = CharSet.Unicode)]
internal static extern int GdipGetEncoderParameterListSize(HandleRef image, ref Guid clsid,
out int size);
- [DllImport(ExternDll.Gdiplus, SetLastError = true, ExactSpelling = true, CharSet = System.Runtime.InteropServices.CharSet.Unicode)] // 3 = Unicode
+ [DllImport(ExternDll.Gdiplus, SetLastError = true, ExactSpelling = true, CharSet = CharSet.Unicode)]
internal static extern int GdipGetEncoderParameterList(HandleRef image, ref Guid clsid, int size,
IntPtr buffer);
- [DllImport(ExternDll.Gdiplus, SetLastError = true, ExactSpelling = true, CharSet = System.Runtime.InteropServices.CharSet.Unicode)] // 3 = Unicode
+ [DllImport(ExternDll.Gdiplus, SetLastError = true, ExactSpelling = true, CharSet = CharSet.Unicode)]
internal static extern int GdipImageGetFrameDimensionsCount(HandleRef image, out int count);
- [DllImport(ExternDll.Gdiplus, SetLastError = true, ExactSpelling = true, CharSet = System.Runtime.InteropServices.CharSet.Unicode)] // 3 = Unicode
+ [DllImport(ExternDll.Gdiplus, SetLastError = true, ExactSpelling = true, CharSet = CharSet.Unicode)]
internal static extern int GdipImageGetFrameDimensionsList(HandleRef image,
IntPtr buffer,
int count);
- [DllImport(ExternDll.Gdiplus, SetLastError = true, ExactSpelling = true, CharSet = System.Runtime.InteropServices.CharSet.Unicode)] // 3 = Unicode
+ [DllImport(ExternDll.Gdiplus, SetLastError = true, ExactSpelling = true, CharSet = CharSet.Unicode)]
internal static extern int GdipImageGetFrameCount(HandleRef image, ref Guid dimensionID, int[] count);
- [DllImport(ExternDll.Gdiplus, SetLastError = true, ExactSpelling = true, CharSet = System.Runtime.InteropServices.CharSet.Unicode)] // 3 = Unicode
+ [DllImport(ExternDll.Gdiplus, SetLastError = true, ExactSpelling = true, CharSet = CharSet.Unicode)]
internal static extern int GdipImageSelectActiveFrame(HandleRef image, ref Guid dimensionID, int frameIndex);
- [DllImport(ExternDll.Gdiplus, SetLastError = true, ExactSpelling = true, CharSet = System.Runtime.InteropServices.CharSet.Unicode)] // 3 = Unicode
+ [DllImport(ExternDll.Gdiplus, SetLastError = true, ExactSpelling = true, CharSet = CharSet.Unicode)]
internal static extern int GdipImageRotateFlip(HandleRef image, int rotateFlipType);
- [DllImport(ExternDll.Gdiplus, SetLastError = true, ExactSpelling = true, CharSet = System.Runtime.InteropServices.CharSet.Unicode)] // 3 = Unicode
+ [DllImport(ExternDll.Gdiplus, SetLastError = true, ExactSpelling = true, CharSet = CharSet.Unicode)]
internal static extern int GdipGetImagePalette(HandleRef image, IntPtr palette, int size);
- [DllImport(ExternDll.Gdiplus, SetLastError = true, ExactSpelling = true, CharSet = System.Runtime.InteropServices.CharSet.Unicode)] // 3 = Unicode
+ [DllImport(ExternDll.Gdiplus, SetLastError = true, ExactSpelling = true, CharSet = CharSet.Unicode)]
internal static extern int GdipSetImagePalette(HandleRef image, IntPtr palette);
- [DllImport(ExternDll.Gdiplus, SetLastError = true, ExactSpelling = true, CharSet = System.Runtime.InteropServices.CharSet.Unicode)] // 3 = Unicode
+ [DllImport(ExternDll.Gdiplus, SetLastError = true, ExactSpelling = true, CharSet = CharSet.Unicode)]
internal static extern int GdipGetImagePaletteSize(HandleRef image, out int size);
- [DllImport(ExternDll.Gdiplus, SetLastError = true, ExactSpelling = true, CharSet = System.Runtime.InteropServices.CharSet.Unicode)] // 3 = Unicode
+ [DllImport(ExternDll.Gdiplus, SetLastError = true, ExactSpelling = true, CharSet = CharSet.Unicode)]
internal static extern int GdipGetPropertyCount(HandleRef image, out int count);
- [DllImport(ExternDll.Gdiplus, SetLastError = true, ExactSpelling = true, CharSet = System.Runtime.InteropServices.CharSet.Unicode)] // 3 = Unicode
+ [DllImport(ExternDll.Gdiplus, SetLastError = true, ExactSpelling = true, CharSet = CharSet.Unicode)]
internal static extern int GdipGetPropertyIdList(HandleRef image, int count, int[] list);
- [DllImport(ExternDll.Gdiplus, SetLastError = true, ExactSpelling = true, CharSet = System.Runtime.InteropServices.CharSet.Unicode)] // 3 = Unicode
+ [DllImport(ExternDll.Gdiplus, SetLastError = true, ExactSpelling = true, CharSet = CharSet.Unicode)]
internal static extern int GdipGetPropertyItemSize(HandleRef image, int propid, out int size);
- [DllImport(ExternDll.Gdiplus, SetLastError = true, ExactSpelling = true, CharSet = System.Runtime.InteropServices.CharSet.Unicode)] // 3 = Unicode
+ [DllImport(ExternDll.Gdiplus, SetLastError = true, ExactSpelling = true, CharSet = CharSet.Unicode)]
internal static extern int GdipGetPropertyItem(HandleRef image, int propid, int size, IntPtr buffer);
- [DllImport(ExternDll.Gdiplus, SetLastError = true, ExactSpelling = true, CharSet = System.Runtime.InteropServices.CharSet.Unicode)] // 3 = Unicode
+ [DllImport(ExternDll.Gdiplus, SetLastError = true, ExactSpelling = true, CharSet = CharSet.Unicode)]
internal static extern int GdipGetPropertySize(HandleRef image, out int totalSize, ref int count);
- [DllImport(ExternDll.Gdiplus, SetLastError = true, ExactSpelling = true, CharSet = System.Runtime.InteropServices.CharSet.Unicode)] // 3 = Unicode
+ [DllImport(ExternDll.Gdiplus, SetLastError = true, ExactSpelling = true, CharSet = CharSet.Unicode)]
internal static extern int GdipGetAllPropertyItems(HandleRef image, int totalSize, int count, IntPtr buffer);
- [DllImport(ExternDll.Gdiplus, SetLastError = true, ExactSpelling = true, CharSet = System.Runtime.InteropServices.CharSet.Unicode)] // 3 = Unicode
+ [DllImport(ExternDll.Gdiplus, SetLastError = true, ExactSpelling = true, CharSet = CharSet.Unicode)]
internal static extern int GdipRemovePropertyItem(HandleRef image, int propid);
- [DllImport(ExternDll.Gdiplus, SetLastError = true, ExactSpelling = true, CharSet = System.Runtime.InteropServices.CharSet.Unicode)] // 3 = Unicode
+ [DllImport(ExternDll.Gdiplus, SetLastError = true, ExactSpelling = true, CharSet = CharSet.Unicode)]
internal static extern int GdipSetPropertyItem(HandleRef image, PropertyItemInternal propitem);
- [DllImport(ExternDll.Gdiplus, SetLastError = true, ExactSpelling = true, CharSet = System.Runtime.InteropServices.CharSet.Unicode)] // 3 = Unicode
+ [DllImport(ExternDll.Gdiplus, SetLastError = true, ExactSpelling = true, CharSet = CharSet.Unicode)]
internal static extern int GdipImageForceValidation(HandleRef image);
- [DllImport(ExternDll.Gdiplus, SetLastError = true, ExactSpelling = true, CharSet = System.Runtime.InteropServices.CharSet.Unicode)] // 3 = Unicode
+ [DllImport(ExternDll.Gdiplus, SetLastError = true, ExactSpelling = true, CharSet = CharSet.Unicode)]
internal static extern int GdipGetImageDecodersSize(out int numDecoders, out int size);
- [DllImport(ExternDll.Gdiplus, SetLastError = true, ExactSpelling = true, CharSet = System.Runtime.InteropServices.CharSet.Unicode)] // 3 = Unicode
+ [DllImport(ExternDll.Gdiplus, SetLastError = true, ExactSpelling = true, CharSet = CharSet.Unicode)]
internal static extern int GdipGetImageDecoders(int numDecoders, int size, IntPtr decoders);
- [DllImport(ExternDll.Gdiplus, SetLastError = true, ExactSpelling = true, CharSet = System.Runtime.InteropServices.CharSet.Unicode)] // 3 = Unicode
+ [DllImport(ExternDll.Gdiplus, SetLastError = true, ExactSpelling = true, CharSet = CharSet.Unicode)]
internal static extern int GdipGetImageEncodersSize(out int numEncoders, out int size);
- [DllImport(ExternDll.Gdiplus, SetLastError = true, ExactSpelling = true, CharSet = System.Runtime.InteropServices.CharSet.Unicode)] // 3 = Unicode
+ [DllImport(ExternDll.Gdiplus, SetLastError = true, ExactSpelling = true, CharSet = CharSet.Unicode)]
internal static extern int GdipGetImageEncoders(int numEncoders, int size, IntPtr encoders);
//----------------------------------------------------------------------------------------
// Bitmap methods
//----------------------------------------------------------------------------------------
- [DllImport(ExternDll.Gdiplus, SetLastError = true, ExactSpelling = true, CharSet = System.Runtime.InteropServices.CharSet.Unicode)] // 3 = Unicode
+ [DllImport(ExternDll.Gdiplus, SetLastError = true, ExactSpelling = true, CharSet = CharSet.Unicode)]
internal static extern int GdipCreateBitmapFromStream(UnsafeNativeMethods.IStream stream, out IntPtr bitmap);
- [DllImport(ExternDll.Gdiplus, SetLastError = true, ExactSpelling = true, CharSet = System.Runtime.InteropServices.CharSet.Unicode)] // 3 = Unicode
+ [DllImport(ExternDll.Gdiplus, SetLastError = true, ExactSpelling = true, CharSet = CharSet.Unicode)]
internal static extern int GdipCreateBitmapFromFile(string filename, out IntPtr bitmap);
- [DllImport(ExternDll.Gdiplus, SetLastError = true, ExactSpelling = true, CharSet = System.Runtime.InteropServices.CharSet.Unicode)] // 3 = Unicode
+ [DllImport(ExternDll.Gdiplus, SetLastError = true, ExactSpelling = true, CharSet = CharSet.Unicode)]
internal static extern int GdipCreateBitmapFromStreamICM(UnsafeNativeMethods.IStream stream, out IntPtr bitmap);
- [DllImport(ExternDll.Gdiplus, SetLastError = true, ExactSpelling = true, CharSet = System.Runtime.InteropServices.CharSet.Unicode)] // 3 = Unicode
+ [DllImport(ExternDll.Gdiplus, SetLastError = true, ExactSpelling = true, CharSet = CharSet.Unicode)]
internal static extern int GdipCreateBitmapFromFileICM(string filename, out IntPtr bitmap);
- [DllImport(ExternDll.Gdiplus, SetLastError = true, ExactSpelling = true, CharSet = System.Runtime.InteropServices.CharSet.Unicode)] // 3 = Unicode
+ [DllImport(ExternDll.Gdiplus, SetLastError = true, ExactSpelling = true, CharSet = CharSet.Unicode)]
internal static extern int GdipCreateBitmapFromScan0(int width, int height, int stride, int format, HandleRef scan0, out IntPtr bitmap);
- [DllImport(ExternDll.Gdiplus, SetLastError = true, ExactSpelling = true, CharSet = System.Runtime.InteropServices.CharSet.Unicode)] // 3 = Unicode
+ [DllImport(ExternDll.Gdiplus, SetLastError = true, ExactSpelling = true, CharSet = CharSet.Unicode)]
internal static extern int GdipCreateBitmapFromGraphics(int width, int height, HandleRef graphics, out IntPtr bitmap);
- [DllImport(ExternDll.Gdiplus, SetLastError = true, ExactSpelling = true, CharSet = System.Runtime.InteropServices.CharSet.Unicode)] // 3 = Unicode
+ [DllImport(ExternDll.Gdiplus, SetLastError = true, ExactSpelling = true, CharSet = CharSet.Unicode)]
internal static extern int GdipCreateBitmapFromHBITMAP(HandleRef hbitmap, HandleRef hpalette, out IntPtr bitmap);
- [DllImport(ExternDll.Gdiplus, SetLastError = true, ExactSpelling = true, CharSet = System.Runtime.InteropServices.CharSet.Unicode)] // 3 = Unicode
+ [DllImport(ExternDll.Gdiplus, SetLastError = true, ExactSpelling = true, CharSet = CharSet.Unicode)]
internal static extern int GdipCreateBitmapFromHICON(HandleRef hicon, out IntPtr bitmap);
- [DllImport(ExternDll.Gdiplus, SetLastError = true, ExactSpelling = true, CharSet = System.Runtime.InteropServices.CharSet.Unicode)] // 3 = Unicode
+ [DllImport(ExternDll.Gdiplus, SetLastError = true, ExactSpelling = true, CharSet = CharSet.Unicode)]
internal static extern int GdipCreateBitmapFromResource(HandleRef hresource, HandleRef name, out IntPtr bitmap);
- [DllImport(ExternDll.Gdiplus, SetLastError = true, ExactSpelling = true, CharSet = System.Runtime.InteropServices.CharSet.Unicode)] // 3 = Unicode
+ [DllImport(ExternDll.Gdiplus, SetLastError = true, ExactSpelling = true, CharSet = CharSet.Unicode)]
internal static extern int GdipCreateHBITMAPFromBitmap(HandleRef nativeBitmap, out IntPtr hbitmap, int argbBackground);
- [DllImport(ExternDll.Gdiplus, SetLastError = true, ExactSpelling = true, CharSet = System.Runtime.InteropServices.CharSet.Unicode)] // 3 = Unicode
+ [DllImport(ExternDll.Gdiplus, SetLastError = true, ExactSpelling = true, CharSet = CharSet.Unicode)]
internal static extern int GdipCreateHICONFromBitmap(HandleRef nativeBitmap, out IntPtr hicon);
- [DllImport(ExternDll.Gdiplus, SetLastError = true, ExactSpelling = true, CharSet = System.Runtime.InteropServices.CharSet.Unicode)] // 3 = Unicode
+ [DllImport(ExternDll.Gdiplus, SetLastError = true, ExactSpelling = true, CharSet = CharSet.Unicode)]
internal static extern int GdipCloneBitmapArea(float x, float y, float width, float height, int format, HandleRef srcbitmap, out IntPtr dstbitmap);
- [DllImport(ExternDll.Gdiplus, SetLastError = true, ExactSpelling = true, CharSet = System.Runtime.InteropServices.CharSet.Unicode)] // 3 = Unicode
+ [DllImport(ExternDll.Gdiplus, SetLastError = true, ExactSpelling = true, CharSet = CharSet.Unicode)]
internal static extern int GdipCloneBitmapAreaI(int x, int y, int width, int height, int format, HandleRef srcbitmap, out IntPtr dstbitmap);
- [DllImport(ExternDll.Gdiplus, SetLastError = true, ExactSpelling = true, CharSet = System.Runtime.InteropServices.CharSet.Unicode)] // 3 = Unicode
+ [DllImport(ExternDll.Gdiplus, SetLastError = true, ExactSpelling = true, CharSet = CharSet.Unicode)]
internal static extern int GdipBitmapLockBits(HandleRef bitmap,
ref GPRECT rect,
ImageLockMode flags, // ImageLockMode
PixelFormat format, // PixelFormat
[In, Out] BitmapData lockedBitmapData);
- [DllImport(ExternDll.Gdiplus, SetLastError = true, ExactSpelling = true, CharSet = System.Runtime.InteropServices.CharSet.Unicode)] // 3 = Unicode
+ [DllImport(ExternDll.Gdiplus, SetLastError = true, ExactSpelling = true, CharSet = CharSet.Unicode)]
internal static extern int GdipBitmapUnlockBits(HandleRef bitmap,
BitmapData lockedBitmapData);
- [DllImport(ExternDll.Gdiplus, SetLastError = true, ExactSpelling = true, CharSet = System.Runtime.InteropServices.CharSet.Unicode)] // 3 = Unicode
+ [DllImport(ExternDll.Gdiplus, SetLastError = true, ExactSpelling = true, CharSet = CharSet.Unicode)]
internal static extern int GdipBitmapGetPixel(HandleRef bitmap, int x, int y, out int argb);
- [DllImport(ExternDll.Gdiplus, SetLastError = true, ExactSpelling = true, CharSet = System.Runtime.InteropServices.CharSet.Unicode)] // 3 = Unicode
+ [DllImport(ExternDll.Gdiplus, SetLastError = true, ExactSpelling = true, CharSet = CharSet.Unicode)]
internal static extern int GdipBitmapSetPixel(HandleRef bitmap, int x, int y, int argb);
- [DllImport(ExternDll.Gdiplus, SetLastError = true, ExactSpelling = true, CharSet = System.Runtime.InteropServices.CharSet.Unicode)] // 3 = Unicode
+ [DllImport(ExternDll.Gdiplus, SetLastError = true, ExactSpelling = true, CharSet = CharSet.Unicode)]
internal static extern int GdipBitmapSetResolution(HandleRef bitmap, float dpix, float dpiy);
//----------------------------------------------------------------------------------------
// ImageAttributes methods
//----------------------------------------------------------------------------------------
- [DllImport(ExternDll.Gdiplus, SetLastError = true, ExactSpelling = true, CharSet = System.Runtime.InteropServices.CharSet.Unicode)] // 3 = Unicode
+ [DllImport(ExternDll.Gdiplus, SetLastError = true, ExactSpelling = true, CharSet = CharSet.Unicode)]
internal static extern int GdipCreateImageAttributes(out IntPtr imageattr);
- [DllImport(ExternDll.Gdiplus, SetLastError = true, ExactSpelling = true, CharSet = System.Runtime.InteropServices.CharSet.Unicode)] // 3 = Unicode
+ [DllImport(ExternDll.Gdiplus, SetLastError = true, ExactSpelling = true, CharSet = CharSet.Unicode)]
internal static extern int GdipCloneImageAttributes(HandleRef imageattr, out IntPtr cloneImageattr);
- [DllImport(ExternDll.Gdiplus, SetLastError = true, ExactSpelling = true, EntryPoint = "GdipDisposeImageAttributes", CharSet = System.Runtime.InteropServices.CharSet.Unicode)] // 3 = Unicode
+ [DllImport(ExternDll.Gdiplus, SetLastError = true, ExactSpelling = true, EntryPoint = "GdipDisposeImageAttributes", CharSet = CharSet.Unicode)]
private static extern int IntGdipDisposeImageAttributes(HandleRef imageattr);
- internal static int GdipDisposeImageAttributes(HandleRef imageattr)
- {
- if (!Initialized) return SafeNativeMethods.Gdip.Ok;
- int result = IntGdipDisposeImageAttributes(imageattr);
- return result;
- }
- [DllImport(ExternDll.Gdiplus, SetLastError = true, ExactSpelling = true, CharSet = System.Runtime.InteropServices.CharSet.Unicode)] // 3 = Unicode
+ internal static int GdipDisposeImageAttributes(HandleRef imageattr) => Initialized ? IntGdipDisposeImageAttributes(imageattr) : Ok;
+
+ [DllImport(ExternDll.Gdiplus, SetLastError = true, ExactSpelling = true, CharSet = CharSet.Unicode)]
internal static extern int GdipSetImageAttributesColorMatrix(HandleRef imageattr,
ColorAdjustType type,
bool enableFlag,
@@ -1586,57 +1518,57 @@ namespace System.Drawing
ColorMatrix grayMatrix,
ColorMatrixFlag flags);
- [DllImport(ExternDll.Gdiplus, SetLastError = true, ExactSpelling = true, CharSet = System.Runtime.InteropServices.CharSet.Unicode)] // 3 = Unicode
+ [DllImport(ExternDll.Gdiplus, SetLastError = true, ExactSpelling = true, CharSet = CharSet.Unicode)]
internal static extern int GdipSetImageAttributesThreshold(HandleRef imageattr,
ColorAdjustType type,
bool enableFlag,
float threshold);
- [DllImport(ExternDll.Gdiplus, SetLastError = true, ExactSpelling = true, CharSet = System.Runtime.InteropServices.CharSet.Unicode)] // 3 = Unicode
+ [DllImport(ExternDll.Gdiplus, SetLastError = true, ExactSpelling = true, CharSet = CharSet.Unicode)]
internal static extern int GdipSetImageAttributesGamma(HandleRef imageattr,
ColorAdjustType type,
bool enableFlag,
float gamma);
- [DllImport(ExternDll.Gdiplus, SetLastError = true, ExactSpelling = true, CharSet = System.Runtime.InteropServices.CharSet.Unicode)] // 3 = Unicode
+ [DllImport(ExternDll.Gdiplus, SetLastError = true, ExactSpelling = true, CharSet = CharSet.Unicode)]
internal static extern int GdipSetImageAttributesNoOp(HandleRef imageattr,
ColorAdjustType type,
bool enableFlag);
- [DllImport(ExternDll.Gdiplus, SetLastError = true, ExactSpelling = true, CharSet = System.Runtime.InteropServices.CharSet.Unicode)] // 3 = Unicode
+ [DllImport(ExternDll.Gdiplus, SetLastError = true, ExactSpelling = true, CharSet = CharSet.Unicode)]
internal static extern int GdipSetImageAttributesColorKeys(HandleRef imageattr,
ColorAdjustType type,
bool enableFlag,
int colorLow, // yes, ref, not out
int colorHigh);
- [DllImport(ExternDll.Gdiplus, SetLastError = true, ExactSpelling = true, CharSet = System.Runtime.InteropServices.CharSet.Unicode)] // 3 = Unicode
+ [DllImport(ExternDll.Gdiplus, SetLastError = true, ExactSpelling = true, CharSet = CharSet.Unicode)]
internal static extern int GdipSetImageAttributesOutputChannel(HandleRef imageattr,
ColorAdjustType type,
bool enableFlag,
ColorChannelFlag flags);
- [DllImport(ExternDll.Gdiplus, SetLastError = true, ExactSpelling = true, CharSet = System.Runtime.InteropServices.CharSet.Unicode)] // 3 = Unicode
+ [DllImport(ExternDll.Gdiplus, SetLastError = true, ExactSpelling = true, CharSet = CharSet.Unicode)]
internal static extern int GdipSetImageAttributesOutputChannelColorProfile(
HandleRef imageattr,
ColorAdjustType type,
bool enableFlag,
string colorProfileFilename);
- [DllImport(ExternDll.Gdiplus, SetLastError = true, ExactSpelling = true, CharSet = System.Runtime.InteropServices.CharSet.Unicode)] // 3 = Unicode
+ [DllImport(ExternDll.Gdiplus, SetLastError = true, ExactSpelling = true, CharSet = CharSet.Unicode)]
internal static extern int GdipSetImageAttributesRemapTable(HandleRef imageattr,
ColorAdjustType type,
bool enableFlag,
int mapSize,
HandleRef map);
- [DllImport(ExternDll.Gdiplus, SetLastError = true, ExactSpelling = true, CharSet = System.Runtime.InteropServices.CharSet.Unicode)] // 3 = Unicode
+ [DllImport(ExternDll.Gdiplus, SetLastError = true, ExactSpelling = true, CharSet = CharSet.Unicode)]
internal static extern int GdipSetImageAttributesWrapMode(HandleRef imageattr,
int wrapmode,
int argb,
bool clamp);
- [DllImport(ExternDll.Gdiplus, SetLastError = true, ExactSpelling = true, CharSet = System.Runtime.InteropServices.CharSet.Unicode)] // 3 = Unicode
+ [DllImport(ExternDll.Gdiplus, SetLastError = true, ExactSpelling = true, CharSet = CharSet.Unicode)]
internal static extern int GdipGetImageAttributesAdjustedPalette(HandleRef imageattr,
HandleRef palette,
ColorAdjustType type);
@@ -1645,373 +1577,365 @@ namespace System.Drawing
// Graphics methods
//----------------------------------------------------------------------------------------
- [DllImport(ExternDll.Gdiplus, SetLastError = true, ExactSpelling = true, CharSet = System.Runtime.InteropServices.CharSet.Unicode)] // 3 = Unicode
+ [DllImport(ExternDll.Gdiplus, SetLastError = true, ExactSpelling = true, CharSet = CharSet.Unicode)]
internal static extern int GdipFlush(HandleRef graphics, FlushIntention intention);
- [DllImport(ExternDll.Gdiplus, SetLastError = true, ExactSpelling = true, CharSet = System.Runtime.InteropServices.CharSet.Unicode)] // 3 = Unicode
+ [DllImport(ExternDll.Gdiplus, SetLastError = true, ExactSpelling = true, CharSet = CharSet.Unicode)]
internal static extern int GdipCreateFromHDC(HandleRef hdc, out IntPtr graphics);
- [DllImport(ExternDll.Gdiplus, SetLastError = true, ExactSpelling = true, CharSet = System.Runtime.InteropServices.CharSet.Unicode)] // 3 = Unicode
+ [DllImport(ExternDll.Gdiplus, SetLastError = true, ExactSpelling = true, CharSet = CharSet.Unicode)]
internal static extern int GdipCreateFromHDC2(HandleRef hdc, HandleRef hdevice, out IntPtr graphics);
- [DllImport(ExternDll.Gdiplus, SetLastError = true, ExactSpelling = true, CharSet = System.Runtime.InteropServices.CharSet.Unicode)] // 3 = Unicode
+ [DllImport(ExternDll.Gdiplus, SetLastError = true, ExactSpelling = true, CharSet = CharSet.Unicode)]
internal static extern int GdipCreateFromHWND(HandleRef hwnd, out IntPtr graphics);
- [DllImport(ExternDll.Gdiplus, SetLastError = true, ExactSpelling = true, EntryPoint = "GdipDeleteGraphics", CharSet = System.Runtime.InteropServices.CharSet.Unicode)] // 3 = Unicode
+ [DllImport(ExternDll.Gdiplus, SetLastError = true, ExactSpelling = true, EntryPoint = "GdipDeleteGraphics", CharSet = CharSet.Unicode)]
private static extern int IntGdipDeleteGraphics(HandleRef graphics);
- internal static int GdipDeleteGraphics(HandleRef graphics)
- {
- if (!Initialized) return SafeNativeMethods.Gdip.Ok;
- int result = IntGdipDeleteGraphics(graphics);
- return result;
- }
- [DllImport(ExternDll.Gdiplus, SetLastError = true, ExactSpelling = true, CharSet = System.Runtime.InteropServices.CharSet.Unicode)] // 3 = Unicode
+ internal static int GdipDeleteGraphics(HandleRef graphics) => Initialized ? IntGdipDeleteGraphics(graphics) : Ok;
+
+ [DllImport(ExternDll.Gdiplus, SetLastError = true, ExactSpelling = true, CharSet = CharSet.Unicode)]
internal static extern int GdipGetDC(HandleRef graphics, out IntPtr hdc);
- [DllImport(ExternDll.Gdiplus, SetLastError = true, ExactSpelling = true, EntryPoint = "GdipReleaseDC", CharSet = System.Runtime.InteropServices.CharSet.Unicode)] // 3 = Unicode
+ [DllImport(ExternDll.Gdiplus, SetLastError = true, ExactSpelling = true, EntryPoint = "GdipReleaseDC", CharSet = CharSet.Unicode)]
private static extern int IntGdipReleaseDC(HandleRef graphics, HandleRef hdc);
- internal static int GdipReleaseDC(HandleRef graphics, HandleRef hdc)
- {
- if (!Initialized) return SafeNativeMethods.Gdip.Ok;
- int result = IntGdipReleaseDC(graphics, hdc);
- return result;
- }
- [DllImport(ExternDll.Gdiplus, SetLastError = true, ExactSpelling = true, CharSet = System.Runtime.InteropServices.CharSet.Unicode)] // 3 = Unicode
+ internal static int GdipReleaseDC(HandleRef graphics, HandleRef hdc) => Initialized ? IntGdipReleaseDC(graphics, hdc) : Ok;
+
+ [DllImport(ExternDll.Gdiplus, SetLastError = true, ExactSpelling = true, CharSet = CharSet.Unicode)]
internal static extern int GdipSetCompositingMode(HandleRef graphics, int compositeMode);
- [DllImport(ExternDll.Gdiplus, SetLastError = true, ExactSpelling = true, CharSet = System.Runtime.InteropServices.CharSet.Unicode)] // 3 = Unicode
+ [DllImport(ExternDll.Gdiplus, SetLastError = true, ExactSpelling = true, CharSet = CharSet.Unicode)]
internal static extern int GdipSetTextRenderingHint(HandleRef graphics, TextRenderingHint textRenderingHint);
- [DllImport(ExternDll.Gdiplus, SetLastError = true, ExactSpelling = true, CharSet = System.Runtime.InteropServices.CharSet.Unicode)] // 3 = Unicode
+ [DllImport(ExternDll.Gdiplus, SetLastError = true, ExactSpelling = true, CharSet = CharSet.Unicode)]
internal static extern int GdipSetTextContrast(HandleRef graphics, int textContrast);
- [DllImport(ExternDll.Gdiplus, SetLastError = true, ExactSpelling = true, CharSet = System.Runtime.InteropServices.CharSet.Unicode)] // 3 = Unicode
+ [DllImport(ExternDll.Gdiplus, SetLastError = true, ExactSpelling = true, CharSet = CharSet.Unicode)]
internal static extern int GdipSetInterpolationMode(HandleRef graphics, int mode);
- [DllImport(ExternDll.Gdiplus, SetLastError = true, ExactSpelling = true, CharSet = System.Runtime.InteropServices.CharSet.Unicode)] // 3 = Unicode
+ [DllImport(ExternDll.Gdiplus, SetLastError = true, ExactSpelling = true, CharSet = CharSet.Unicode)]
internal static extern int GdipGetCompositingMode(HandleRef graphics, out int compositeMode);
- [DllImport(ExternDll.Gdiplus, SetLastError = true, ExactSpelling = true, CharSet = System.Runtime.InteropServices.CharSet.Unicode)] // 3 = Unicode
+ [DllImport(ExternDll.Gdiplus, SetLastError = true, ExactSpelling = true, CharSet = CharSet.Unicode)]
internal static extern int GdipSetRenderingOrigin(HandleRef graphics, int x, int y);
- [DllImport(ExternDll.Gdiplus, SetLastError = true, ExactSpelling = true, CharSet = System.Runtime.InteropServices.CharSet.Unicode)] // 3 = Unicode
+ [DllImport(ExternDll.Gdiplus, SetLastError = true, ExactSpelling = true, CharSet = CharSet.Unicode)]
internal static extern int GdipGetRenderingOrigin(HandleRef graphics, out int x, out int y);
- [DllImport(ExternDll.Gdiplus, SetLastError = true, ExactSpelling = true, CharSet = System.Runtime.InteropServices.CharSet.Unicode)] // 3 = Unicode
+ [DllImport(ExternDll.Gdiplus, SetLastError = true, ExactSpelling = true, CharSet = CharSet.Unicode)]
internal static extern int GdipSetCompositingQuality(HandleRef graphics, CompositingQuality quality);
- [DllImport(ExternDll.Gdiplus, SetLastError = true, ExactSpelling = true, CharSet = System.Runtime.InteropServices.CharSet.Unicode)] // 3 = Unicode
+ [DllImport(ExternDll.Gdiplus, SetLastError = true, ExactSpelling = true, CharSet = CharSet.Unicode)]
internal static extern int GdipGetCompositingQuality(HandleRef graphics, out CompositingQuality quality);
- [DllImport(ExternDll.Gdiplus, SetLastError = true, ExactSpelling = true, CharSet = System.Runtime.InteropServices.CharSet.Unicode)] // 3 = Unicode
+ [DllImport(ExternDll.Gdiplus, SetLastError = true, ExactSpelling = true, CharSet = CharSet.Unicode)]
internal static extern int GdipSetSmoothingMode(HandleRef graphics, SmoothingMode smoothingMode);
- [DllImport(ExternDll.Gdiplus, SetLastError = true, ExactSpelling = true, CharSet = System.Runtime.InteropServices.CharSet.Unicode)] // 3 = Unicode
+ [DllImport(ExternDll.Gdiplus, SetLastError = true, ExactSpelling = true, CharSet = CharSet.Unicode)]
internal static extern int GdipGetSmoothingMode(HandleRef graphics, out SmoothingMode smoothingMode);
- [DllImport(ExternDll.Gdiplus, SetLastError = true, ExactSpelling = true, CharSet = System.Runtime.InteropServices.CharSet.Unicode)] // 3 = Unicode
+ [DllImport(ExternDll.Gdiplus, SetLastError = true, ExactSpelling = true, CharSet = CharSet.Unicode)]
internal static extern int GdipSetPixelOffsetMode(HandleRef graphics, PixelOffsetMode pixelOffsetMode);
- [DllImport(ExternDll.Gdiplus, SetLastError = true, ExactSpelling = true, CharSet = System.Runtime.InteropServices.CharSet.Unicode)] // 3 = Unicode
+ [DllImport(ExternDll.Gdiplus, SetLastError = true, ExactSpelling = true, CharSet = CharSet.Unicode)]
internal static extern int GdipGetPixelOffsetMode(HandleRef graphics, out PixelOffsetMode pixelOffsetMode);
- [DllImport(ExternDll.Gdiplus, SetLastError = true, ExactSpelling = true, CharSet = System.Runtime.InteropServices.CharSet.Unicode)] // 3 = Unicode
+ [DllImport(ExternDll.Gdiplus, SetLastError = true, ExactSpelling = true, CharSet = CharSet.Unicode)]
internal static extern int GdipGetTextRenderingHint(HandleRef graphics, out TextRenderingHint textRenderingHint);
- [DllImport(ExternDll.Gdiplus, SetLastError = true, ExactSpelling = true, CharSet = System.Runtime.InteropServices.CharSet.Unicode)] // 3 = Unicode
+ [DllImport(ExternDll.Gdiplus, SetLastError = true, ExactSpelling = true, CharSet = CharSet.Unicode)]
internal static extern int GdipGetTextContrast(HandleRef graphics, out int textContrast);
- [DllImport(ExternDll.Gdiplus, SetLastError = true, ExactSpelling = true, CharSet = System.Runtime.InteropServices.CharSet.Unicode)] // 3 = Unicode
+ [DllImport(ExternDll.Gdiplus, SetLastError = true, ExactSpelling = true, CharSet = CharSet.Unicode)]
internal static extern int GdipGetInterpolationMode(HandleRef graphics, out int mode);
- [DllImport(ExternDll.Gdiplus, SetLastError = true, ExactSpelling = true, CharSet = System.Runtime.InteropServices.CharSet.Unicode)] // 3 = Unicode
+ [DllImport(ExternDll.Gdiplus, SetLastError = true, ExactSpelling = true, CharSet = CharSet.Unicode)]
internal static extern int GdipSetWorldTransform(HandleRef graphics, HandleRef matrix);
- [DllImport(ExternDll.Gdiplus, SetLastError = true, ExactSpelling = true, CharSet = System.Runtime.InteropServices.CharSet.Unicode)] // 3 = Unicode
+ [DllImport(ExternDll.Gdiplus, SetLastError = true, ExactSpelling = true, CharSet = CharSet.Unicode)]
internal static extern int GdipResetWorldTransform(HandleRef graphics);
- [DllImport(ExternDll.Gdiplus, SetLastError = true, ExactSpelling = true, CharSet = System.Runtime.InteropServices.CharSet.Unicode)] // 3 = Unicode
+ [DllImport(ExternDll.Gdiplus, SetLastError = true, ExactSpelling = true, CharSet = CharSet.Unicode)]
internal static extern int GdipMultiplyWorldTransform(HandleRef graphics, HandleRef matrix, MatrixOrder order);
- [DllImport(ExternDll.Gdiplus, SetLastError = true, ExactSpelling = true, CharSet = System.Runtime.InteropServices.CharSet.Unicode)] // 3 = Unicode
+ [DllImport(ExternDll.Gdiplus, SetLastError = true, ExactSpelling = true, CharSet = CharSet.Unicode)]
internal static extern int GdipTranslateWorldTransform(HandleRef graphics, float dx, float dy, MatrixOrder order);
- [DllImport(ExternDll.Gdiplus, SetLastError = true, ExactSpelling = true, CharSet = System.Runtime.InteropServices.CharSet.Unicode)] // 3 = Unicode
+ [DllImport(ExternDll.Gdiplus, SetLastError = true, ExactSpelling = true, CharSet = CharSet.Unicode)]
internal static extern int GdipScaleWorldTransform(HandleRef graphics, float sx, float sy, MatrixOrder order);
- [DllImport(ExternDll.Gdiplus, SetLastError = true, ExactSpelling = true, CharSet = System.Runtime.InteropServices.CharSet.Unicode)] // 3 = Unicode
+ [DllImport(ExternDll.Gdiplus, SetLastError = true, ExactSpelling = true, CharSet = CharSet.Unicode)]
internal static extern int GdipRotateWorldTransform(HandleRef graphics, float angle, MatrixOrder order);
- [DllImport(ExternDll.Gdiplus, SetLastError = true, ExactSpelling = true, CharSet = System.Runtime.InteropServices.CharSet.Unicode)] // 3 = Unicode
+ [DllImport(ExternDll.Gdiplus, SetLastError = true, ExactSpelling = true, CharSet = CharSet.Unicode)]
internal static extern int GdipGetWorldTransform(HandleRef graphics, HandleRef matrix);
- [DllImport(ExternDll.Gdiplus, SetLastError = true, ExactSpelling = true, CharSet = System.Runtime.InteropServices.CharSet.Unicode)] // 3 = Unicode
+ [DllImport(ExternDll.Gdiplus, SetLastError = true, ExactSpelling = true, CharSet = CharSet.Unicode)]
internal static extern int GdipGetPageUnit(HandleRef graphics, out int unit);
- [DllImport(ExternDll.Gdiplus, SetLastError = true, ExactSpelling = true, CharSet = System.Runtime.InteropServices.CharSet.Unicode)] // 3 = Unicode
+ [DllImport(ExternDll.Gdiplus, SetLastError = true, ExactSpelling = true, CharSet = CharSet.Unicode)]
internal static extern int GdipGetPageScale(HandleRef graphics, float[] scale);
- [DllImport(ExternDll.Gdiplus, SetLastError = true, ExactSpelling = true, CharSet = System.Runtime.InteropServices.CharSet.Unicode)] // 3 = Unicode
+ [DllImport(ExternDll.Gdiplus, SetLastError = true, ExactSpelling = true, CharSet = CharSet.Unicode)]
internal static extern int GdipSetPageUnit(HandleRef graphics, int unit);
- [DllImport(ExternDll.Gdiplus, SetLastError = true, ExactSpelling = true, CharSet = System.Runtime.InteropServices.CharSet.Unicode)] // 3 = Unicode
+ [DllImport(ExternDll.Gdiplus, SetLastError = true, ExactSpelling = true, CharSet = CharSet.Unicode)]
internal static extern int GdipSetPageScale(HandleRef graphics, float scale);
- [DllImport(ExternDll.Gdiplus, SetLastError = true, ExactSpelling = true, CharSet = System.Runtime.InteropServices.CharSet.Unicode)] // 3 = Unicode
+ [DllImport(ExternDll.Gdiplus, SetLastError = true, ExactSpelling = true, CharSet = CharSet.Unicode)]
internal static extern int GdipGetDpiX(HandleRef graphics, float[] dpi);
- [DllImport(ExternDll.Gdiplus, SetLastError = true, ExactSpelling = true, CharSet = System.Runtime.InteropServices.CharSet.Unicode)] // 3 = Unicode
+ [DllImport(ExternDll.Gdiplus, SetLastError = true, ExactSpelling = true, CharSet = CharSet.Unicode)]
internal static extern int GdipGetDpiY(HandleRef graphics, float[] dpi);
- [DllImport(ExternDll.Gdiplus, SetLastError = true, ExactSpelling = true, CharSet = System.Runtime.InteropServices.CharSet.Unicode)] // 3 = Unicode
+ [DllImport(ExternDll.Gdiplus, SetLastError = true, ExactSpelling = true, CharSet = CharSet.Unicode)]
internal static extern int GdipTransformPoints(HandleRef graphics, int destSpace,
int srcSpace, IntPtr points, int count);
- [DllImport(ExternDll.Gdiplus, SetLastError = true, ExactSpelling = true, CharSet = System.Runtime.InteropServices.CharSet.Unicode)] // 3 = Unicode
+ [DllImport(ExternDll.Gdiplus, SetLastError = true, ExactSpelling = true, CharSet = CharSet.Unicode)]
internal static extern int GdipTransformPointsI(HandleRef graphics, int destSpace,
int srcSpace, IntPtr points, int count);
- [DllImport(ExternDll.Gdiplus, SetLastError = true, ExactSpelling = true, CharSet = System.Runtime.InteropServices.CharSet.Unicode)] // 3 = Unicode
+ [DllImport(ExternDll.Gdiplus, SetLastError = true, ExactSpelling = true, CharSet = CharSet.Unicode)]
internal static extern int GdipGetNearestColor(HandleRef graphics, ref int color);
// Create the Win9x Halftone Palette (even on NT) with correct Desktop colors
- [DllImport(ExternDll.Gdiplus, SetLastError = true, ExactSpelling = true, CharSet = System.Runtime.InteropServices.CharSet.Unicode)] // 3 = Unicode
+ [DllImport(ExternDll.Gdiplus, SetLastError = true, ExactSpelling = true, CharSet = CharSet.Unicode)]
internal static extern IntPtr GdipCreateHalftonePalette();
- [DllImport(ExternDll.Gdiplus, SetLastError = true, ExactSpelling = true, CharSet = System.Runtime.InteropServices.CharSet.Unicode)] // 3 = Unicode
+ [DllImport(ExternDll.Gdiplus, SetLastError = true, ExactSpelling = true, CharSet = CharSet.Unicode)]
internal static extern int GdipDrawLine(HandleRef graphics, HandleRef pen, float x1, float y1,
float x2, float y2);
- [DllImport(ExternDll.Gdiplus, SetLastError = true, ExactSpelling = true, CharSet = System.Runtime.InteropServices.CharSet.Unicode)] // 3 = Unicode
+ [DllImport(ExternDll.Gdiplus, SetLastError = true, ExactSpelling = true, CharSet = CharSet.Unicode)]
internal static extern int GdipDrawLineI(HandleRef graphics, HandleRef pen, int x1, int y1,
int x2, int y2);
- [DllImport(ExternDll.Gdiplus, SetLastError = true, ExactSpelling = true, CharSet = System.Runtime.InteropServices.CharSet.Unicode)] // 3 = Unicode
+ [DllImport(ExternDll.Gdiplus, SetLastError = true, ExactSpelling = true, CharSet = CharSet.Unicode)]
internal static extern int GdipDrawLines(HandleRef graphics, HandleRef pen, HandleRef points,
int count);
- [DllImport(ExternDll.Gdiplus, SetLastError = true, ExactSpelling = true, CharSet = System.Runtime.InteropServices.CharSet.Unicode)] // 3 = Unicode
+ [DllImport(ExternDll.Gdiplus, SetLastError = true, ExactSpelling = true, CharSet = CharSet.Unicode)]
internal static extern int GdipDrawLinesI(HandleRef graphics, HandleRef pen, HandleRef points,
int count);
- [DllImport(ExternDll.Gdiplus, SetLastError = true, ExactSpelling = true, CharSet = System.Runtime.InteropServices.CharSet.Unicode)] // 3 = Unicode
+ [DllImport(ExternDll.Gdiplus, SetLastError = true, ExactSpelling = true, CharSet = CharSet.Unicode)]
internal static extern int GdipDrawArc(HandleRef graphics, HandleRef pen, float x, float y,
float width, float height, float startAngle,
float sweepAngle);
- [DllImport(ExternDll.Gdiplus, SetLastError = true, ExactSpelling = true, CharSet = System.Runtime.InteropServices.CharSet.Unicode)] // 3 = Unicode
+ [DllImport(ExternDll.Gdiplus, SetLastError = true, ExactSpelling = true, CharSet = CharSet.Unicode)]
internal static extern int GdipDrawArcI(HandleRef graphics, HandleRef pen, int x, int y,
int width, int height, float startAngle,
float sweepAngle);
- [DllImport(ExternDll.Gdiplus, SetLastError = true, ExactSpelling = true, CharSet = System.Runtime.InteropServices.CharSet.Unicode)] // 3 = Unicode
+ [DllImport(ExternDll.Gdiplus, SetLastError = true, ExactSpelling = true, CharSet = CharSet.Unicode)]
internal static extern int GdipDrawBezier(HandleRef graphics, HandleRef pen, float x1, float y1,
float x2, float y2, float x3, float y3,
float x4, float y4);
- [DllImport(ExternDll.Gdiplus, SetLastError = true, ExactSpelling = true, CharSet = System.Runtime.InteropServices.CharSet.Unicode)] // 3 = Unicode
+ [DllImport(ExternDll.Gdiplus, SetLastError = true, ExactSpelling = true, CharSet = CharSet.Unicode)]
internal static extern int GdipDrawBeziers(HandleRef graphics, HandleRef pen, HandleRef points,
int count);
- [DllImport(ExternDll.Gdiplus, SetLastError = true, ExactSpelling = true, CharSet = System.Runtime.InteropServices.CharSet.Unicode)] // 3 = Unicode
+ [DllImport(ExternDll.Gdiplus, SetLastError = true, ExactSpelling = true, CharSet = CharSet.Unicode)]
internal static extern int GdipDrawBeziersI(HandleRef graphics, HandleRef pen, HandleRef points,
int count);
- [DllImport(ExternDll.Gdiplus, SetLastError = true, ExactSpelling = true, CharSet = System.Runtime.InteropServices.CharSet.Unicode)] // 3 = Unicode
+ [DllImport(ExternDll.Gdiplus, SetLastError = true, ExactSpelling = true, CharSet = CharSet.Unicode)]
internal static extern int GdipDrawRectangle(HandleRef graphics, HandleRef pen, float x, float y,
float width, float height);
- [DllImport(ExternDll.Gdiplus, SetLastError = true, ExactSpelling = true, CharSet = System.Runtime.InteropServices.CharSet.Unicode)] // 3 = Unicode
+ [DllImport(ExternDll.Gdiplus, SetLastError = true, ExactSpelling = true, CharSet = CharSet.Unicode)]
internal static extern int GdipDrawRectangleI(HandleRef graphics, HandleRef pen, int x, int y,
int width, int height);
- [DllImport(ExternDll.Gdiplus, SetLastError = true, ExactSpelling = true, CharSet = System.Runtime.InteropServices.CharSet.Unicode)] // 3 = Unicode
+ [DllImport(ExternDll.Gdiplus, SetLastError = true, ExactSpelling = true, CharSet = CharSet.Unicode)]
internal static extern int GdipDrawRectangles(HandleRef graphics, HandleRef pen, HandleRef rects,
int count);
- [DllImport(ExternDll.Gdiplus, SetLastError = true, ExactSpelling = true, CharSet = System.Runtime.InteropServices.CharSet.Unicode)] // 3 = Unicode
+ [DllImport(ExternDll.Gdiplus, SetLastError = true, ExactSpelling = true, CharSet = CharSet.Unicode)]
internal static extern int GdipDrawRectanglesI(HandleRef graphics, HandleRef pen, HandleRef rects,
int count);
- [DllImport(ExternDll.Gdiplus, SetLastError = true, ExactSpelling = true, CharSet = System.Runtime.InteropServices.CharSet.Unicode)] // 3 = Unicode
+ [DllImport(ExternDll.Gdiplus, SetLastError = true, ExactSpelling = true, CharSet = CharSet.Unicode)]
internal static extern int GdipDrawEllipse(HandleRef graphics, HandleRef pen, float x, float y,
float width, float height);
- [DllImport(ExternDll.Gdiplus, SetLastError = true, ExactSpelling = true, CharSet = System.Runtime.InteropServices.CharSet.Unicode)] // 3 = Unicode
+ [DllImport(ExternDll.Gdiplus, SetLastError = true, ExactSpelling = true, CharSet = CharSet.Unicode)]
internal static extern int GdipDrawEllipseI(HandleRef graphics, HandleRef pen, int x, int y,
int width, int height);
- [DllImport(ExternDll.Gdiplus, SetLastError = true, ExactSpelling = true, CharSet = System.Runtime.InteropServices.CharSet.Unicode)] // 3 = Unicode
+ [DllImport(ExternDll.Gdiplus, SetLastError = true, ExactSpelling = true, CharSet = CharSet.Unicode)]
internal static extern int GdipDrawPie(HandleRef graphics, HandleRef pen, float x, float y,
float width, float height, float startAngle,
float sweepAngle);
- [DllImport(ExternDll.Gdiplus, SetLastError = true, ExactSpelling = true, CharSet = System.Runtime.InteropServices.CharSet.Unicode)] // 3 = Unicode
+ [DllImport(ExternDll.Gdiplus, SetLastError = true, ExactSpelling = true, CharSet = CharSet.Unicode)]
internal static extern int GdipDrawPieI(HandleRef graphics, HandleRef pen, int x, int y,
int width, int height, float startAngle,
float sweepAngle);
- [DllImport(ExternDll.Gdiplus, SetLastError = true, ExactSpelling = true, CharSet = System.Runtime.InteropServices.CharSet.Unicode)] // 3 = Unicode
+ [DllImport(ExternDll.Gdiplus, SetLastError = true, ExactSpelling = true, CharSet = CharSet.Unicode)]
internal static extern int GdipDrawPolygon(HandleRef graphics, HandleRef pen, HandleRef points,
int count);
- [DllImport(ExternDll.Gdiplus, SetLastError = true, ExactSpelling = true, CharSet = System.Runtime.InteropServices.CharSet.Unicode)] // 3 = Unicode
+ [DllImport(ExternDll.Gdiplus, SetLastError = true, ExactSpelling = true, CharSet = CharSet.Unicode)]
internal static extern int GdipDrawPolygonI(HandleRef graphics, HandleRef pen, HandleRef points,
int count);
- [DllImport(ExternDll.Gdiplus, SetLastError = true, ExactSpelling = true, CharSet = System.Runtime.InteropServices.CharSet.Unicode)] // 3 = Unicode
+ [DllImport(ExternDll.Gdiplus, SetLastError = true, ExactSpelling = true, CharSet = CharSet.Unicode)]
internal static extern int GdipDrawPath(HandleRef graphics, HandleRef pen, HandleRef path);
- [DllImport(ExternDll.Gdiplus, SetLastError = true, ExactSpelling = true, CharSet = System.Runtime.InteropServices.CharSet.Unicode)] // 3 = Unicode
+ [DllImport(ExternDll.Gdiplus, SetLastError = true, ExactSpelling = true, CharSet = CharSet.Unicode)]
internal static extern int GdipDrawCurve(HandleRef graphics, HandleRef pen, HandleRef points,
int count);
- [DllImport(ExternDll.Gdiplus, SetLastError = true, ExactSpelling = true, CharSet = System.Runtime.InteropServices.CharSet.Unicode)] // 3 = Unicode
+ [DllImport(ExternDll.Gdiplus, SetLastError = true, ExactSpelling = true, CharSet = CharSet.Unicode)]
internal static extern int GdipDrawCurveI(HandleRef graphics, HandleRef pen, HandleRef points,
int count);
- [DllImport(ExternDll.Gdiplus, SetLastError = true, ExactSpelling = true, CharSet = System.Runtime.InteropServices.CharSet.Unicode)] // 3 = Unicode
+ [DllImport(ExternDll.Gdiplus, SetLastError = true, ExactSpelling = true, CharSet = CharSet.Unicode)]
internal static extern int GdipDrawCurve2(HandleRef graphics, HandleRef pen, HandleRef points,
int count, float tension);
- [DllImport(ExternDll.Gdiplus, SetLastError = true, ExactSpelling = true, CharSet = System.Runtime.InteropServices.CharSet.Unicode)] // 3 = Unicode
+ [DllImport(ExternDll.Gdiplus, SetLastError = true, ExactSpelling = true, CharSet = CharSet.Unicode)]
internal static extern int GdipDrawCurve2I(HandleRef graphics, HandleRef pen, HandleRef points,
int count, float tension);
- [DllImport(ExternDll.Gdiplus, SetLastError = true, ExactSpelling = true, CharSet = System.Runtime.InteropServices.CharSet.Unicode)] // 3 = Unicode
+ [DllImport(ExternDll.Gdiplus, SetLastError = true, ExactSpelling = true, CharSet = CharSet.Unicode)]
internal static extern int GdipDrawCurve3(HandleRef graphics, HandleRef pen, HandleRef points,
int count, int offset,
int numberOfSegments, float tension);
- [DllImport(ExternDll.Gdiplus, SetLastError = true, ExactSpelling = true, CharSet = System.Runtime.InteropServices.CharSet.Unicode)] // 3 = Unicode
+ [DllImport(ExternDll.Gdiplus, SetLastError = true, ExactSpelling = true, CharSet = CharSet.Unicode)]
internal static extern int GdipDrawCurve3I(HandleRef graphics, HandleRef pen, HandleRef points,
int count, int offset,
int numberOfSegments, float tension);
- [DllImport(ExternDll.Gdiplus, SetLastError = true, ExactSpelling = true, CharSet = System.Runtime.InteropServices.CharSet.Unicode)] // 3 = Unicode
+ [DllImport(ExternDll.Gdiplus, SetLastError = true, ExactSpelling = true, CharSet = CharSet.Unicode)]
internal static extern int GdipDrawClosedCurve(HandleRef graphics, HandleRef pen, HandleRef points,
int count);
- [DllImport(ExternDll.Gdiplus, SetLastError = true, ExactSpelling = true, CharSet = System.Runtime.InteropServices.CharSet.Unicode)] // 3 = Unicode
+ [DllImport(ExternDll.Gdiplus, SetLastError = true, ExactSpelling = true, CharSet = CharSet.Unicode)]
internal static extern int GdipDrawClosedCurveI(HandleRef graphics, HandleRef pen, HandleRef points,
int count);
- [DllImport(ExternDll.Gdiplus, SetLastError = true, ExactSpelling = true, CharSet = System.Runtime.InteropServices.CharSet.Unicode)] // 3 = Unicode
+ [DllImport(ExternDll.Gdiplus, SetLastError = true, ExactSpelling = true, CharSet = CharSet.Unicode)]
internal static extern int GdipDrawClosedCurve2(HandleRef graphics, HandleRef pen, HandleRef points,
int count, float tension);
- [DllImport(ExternDll.Gdiplus, SetLastError = true, ExactSpelling = true, CharSet = System.Runtime.InteropServices.CharSet.Unicode)] // 3 = Unicode
+ [DllImport(ExternDll.Gdiplus, SetLastError = true, ExactSpelling = true, CharSet = CharSet.Unicode)]
internal static extern int GdipDrawClosedCurve2I(HandleRef graphics, HandleRef pen, HandleRef points,
int count, float tension);
- [DllImport(ExternDll.Gdiplus, SetLastError = true, ExactSpelling = true, CharSet = System.Runtime.InteropServices.CharSet.Unicode)] // 3 = Unicode
+ [DllImport(ExternDll.Gdiplus, SetLastError = true, ExactSpelling = true, CharSet = CharSet.Unicode)]
internal static extern int GdipGraphicsClear(HandleRef graphics, int argb);
- [DllImport(ExternDll.Gdiplus, SetLastError = true, ExactSpelling = true, CharSet = System.Runtime.InteropServices.CharSet.Unicode)] // 3 = Unicode
+ [DllImport(ExternDll.Gdiplus, SetLastError = true, ExactSpelling = true, CharSet = CharSet.Unicode)]
internal static extern int GdipFillRectangle(HandleRef graphics, HandleRef brush, float x, float y,
float width, float height);
- [DllImport(ExternDll.Gdiplus, SetLastError = true, ExactSpelling = true, CharSet = System.Runtime.InteropServices.CharSet.Unicode)] // 3 = Unicode
+ [DllImport(ExternDll.Gdiplus, SetLastError = true, ExactSpelling = true, CharSet = CharSet.Unicode)]
internal static extern int GdipFillRectangleI(HandleRef graphics, HandleRef brush, int x, int y,
int width, int height);
- [DllImport(ExternDll.Gdiplus, SetLastError = true, ExactSpelling = true, CharSet = System.Runtime.InteropServices.CharSet.Unicode)] // 3 = Unicode
+ [DllImport(ExternDll.Gdiplus, SetLastError = true, ExactSpelling = true, CharSet = CharSet.Unicode)]
internal static extern int GdipFillRectangles(HandleRef graphics, HandleRef brush, HandleRef rects,
int count);
- [DllImport(ExternDll.Gdiplus, SetLastError = true, ExactSpelling = true, CharSet = System.Runtime.InteropServices.CharSet.Unicode)] // 3 = Unicode
+ [DllImport(ExternDll.Gdiplus, SetLastError = true, ExactSpelling = true, CharSet = CharSet.Unicode)]
internal static extern int GdipFillRectanglesI(HandleRef graphics, HandleRef brush, HandleRef rects,
int count);
- [DllImport(ExternDll.Gdiplus, SetLastError = true, ExactSpelling = true, CharSet = System.Runtime.InteropServices.CharSet.Unicode)] // 3 = Unicode
+ [DllImport(ExternDll.Gdiplus, SetLastError = true, ExactSpelling = true, CharSet = CharSet.Unicode)]
internal static extern int GdipFillPolygon(HandleRef graphics, HandleRef brush, HandleRef points,
int count, int brushMode);
- [DllImport(ExternDll.Gdiplus, SetLastError = true, ExactSpelling = true, CharSet = System.Runtime.InteropServices.CharSet.Unicode)] // 3 = Unicode
+ [DllImport(ExternDll.Gdiplus, SetLastError = true, ExactSpelling = true, CharSet = CharSet.Unicode)]
internal static extern int GdipFillPolygonI(HandleRef graphics, HandleRef brush, HandleRef points,
int count, int brushMode);
- [DllImport(ExternDll.Gdiplus, SetLastError = true, ExactSpelling = true, CharSet = System.Runtime.InteropServices.CharSet.Unicode)] // 3 = Unicode
+ [DllImport(ExternDll.Gdiplus, SetLastError = true, ExactSpelling = true, CharSet = CharSet.Unicode)]
internal static extern int GdipFillEllipse(HandleRef graphics, HandleRef brush, float x, float y,
float width, float height);
- [DllImport(ExternDll.Gdiplus, SetLastError = true, ExactSpelling = true, CharSet = System.Runtime.InteropServices.CharSet.Unicode)] // 3 = Unicode
+ [DllImport(ExternDll.Gdiplus, SetLastError = true, ExactSpelling = true, CharSet = CharSet.Unicode)]
internal static extern int GdipFillEllipseI(HandleRef graphics, HandleRef brush, int x, int y,
int width, int height);
- [DllImport(ExternDll.Gdiplus, SetLastError = true, ExactSpelling = true, CharSet = System.Runtime.InteropServices.CharSet.Unicode)] // 3 = Unicode
+ [DllImport(ExternDll.Gdiplus, SetLastError = true, ExactSpelling = true, CharSet = CharSet.Unicode)]
internal static extern int GdipFillPie(HandleRef graphics, HandleRef brush, float x, float y,
float width, float height, float startAngle,
float sweepAngle);
- [DllImport(ExternDll.Gdiplus, SetLastError = true, ExactSpelling = true, CharSet = System.Runtime.InteropServices.CharSet.Unicode)] // 3 = Unicode
+ [DllImport(ExternDll.Gdiplus, SetLastError = true, ExactSpelling = true, CharSet = CharSet.Unicode)]
internal static extern int GdipFillPieI(HandleRef graphics, HandleRef brush, int x, int y,
int width, int height, float startAngle,
float sweepAngle);
- [DllImport(ExternDll.Gdiplus, SetLastError = true, ExactSpelling = true, CharSet = System.Runtime.InteropServices.CharSet.Unicode)] // 3 = Unicode
+ [DllImport(ExternDll.Gdiplus, SetLastError = true, ExactSpelling = true, CharSet = CharSet.Unicode)]
internal static extern int GdipFillPath(HandleRef graphics, HandleRef brush, HandleRef path);
- [DllImport(ExternDll.Gdiplus, SetLastError = true, ExactSpelling = true, CharSet = System.Runtime.InteropServices.CharSet.Unicode)] // 3 = Unicode
+ [DllImport(ExternDll.Gdiplus, SetLastError = true, ExactSpelling = true, CharSet = CharSet.Unicode)]
internal static extern int GdipFillClosedCurve(HandleRef graphics, HandleRef brush, HandleRef points,
int count);
- [DllImport(ExternDll.Gdiplus, SetLastError = true, ExactSpelling = true, CharSet = System.Runtime.InteropServices.CharSet.Unicode)] // 3 = Unicode
+ [DllImport(ExternDll.Gdiplus, SetLastError = true, ExactSpelling = true, CharSet = CharSet.Unicode)]
internal static extern int GdipFillClosedCurveI(HandleRef graphics, HandleRef brush, HandleRef points,
int count);
- [DllImport(ExternDll.Gdiplus, SetLastError = true, ExactSpelling = true, CharSet = System.Runtime.InteropServices.CharSet.Unicode)] // 3 = Unicode
+ [DllImport(ExternDll.Gdiplus, SetLastError = true, ExactSpelling = true, CharSet = CharSet.Unicode)]
internal static extern int GdipFillClosedCurve2(HandleRef graphics, HandleRef brush, HandleRef points,
int count, float tension,
int mode);
- [DllImport(ExternDll.Gdiplus, SetLastError = true, ExactSpelling = true, CharSet = System.Runtime.InteropServices.CharSet.Unicode)] // 3 = Unicode
+ [DllImport(ExternDll.Gdiplus, SetLastError = true, ExactSpelling = true, CharSet = CharSet.Unicode)]
internal static extern int GdipFillClosedCurve2I(HandleRef graphics, HandleRef brush, HandleRef points,
int count, float tension,
int mode);
- [DllImport(ExternDll.Gdiplus, SetLastError = true, ExactSpelling = true, CharSet = System.Runtime.InteropServices.CharSet.Unicode)] // 3 = Unicode
+ [DllImport(ExternDll.Gdiplus, SetLastError = true, ExactSpelling = true, CharSet = CharSet.Unicode)]
internal static extern int GdipFillRegion(HandleRef graphics, HandleRef brush, HandleRef region);
- [DllImport(ExternDll.Gdiplus, SetLastError = true, ExactSpelling = true, CharSet = System.Runtime.InteropServices.CharSet.Unicode)] // 3 = Unicode
+ [DllImport(ExternDll.Gdiplus, SetLastError = true, ExactSpelling = true, CharSet = CharSet.Unicode)]
internal static extern int GdipDrawImage(HandleRef graphics, HandleRef image, float x, float y);
- [DllImport(ExternDll.Gdiplus, SetLastError = true, ExactSpelling = true, CharSet = System.Runtime.InteropServices.CharSet.Unicode)] // 3 = Unicode
+ [DllImport(ExternDll.Gdiplus, SetLastError = true, ExactSpelling = true, CharSet = CharSet.Unicode)]
internal static extern int GdipDrawImageI(HandleRef graphics, HandleRef image, int x, int y);
- [DllImport(ExternDll.Gdiplus, SetLastError = true, ExactSpelling = true, CharSet = System.Runtime.InteropServices.CharSet.Unicode)] // 3 = Unicode
+ [DllImport(ExternDll.Gdiplus, SetLastError = true, ExactSpelling = true, CharSet = CharSet.Unicode)]
internal static extern int GdipDrawImageRect(HandleRef graphics, HandleRef image, float x,
float y, float width, float height);
- [DllImport(ExternDll.Gdiplus, SetLastError = true, ExactSpelling = true, CharSet = System.Runtime.InteropServices.CharSet.Unicode)] // 3 = Unicode
+ [DllImport(ExternDll.Gdiplus, SetLastError = true, ExactSpelling = true, CharSet = CharSet.Unicode)]
internal static extern int GdipDrawImageRectI(HandleRef graphics, HandleRef image, int x,
int y, int width, int height);
- [DllImport(ExternDll.Gdiplus, SetLastError = true, ExactSpelling = true, CharSet = System.Runtime.InteropServices.CharSet.Unicode)] // 3 = Unicode
+ [DllImport(ExternDll.Gdiplus, SetLastError = true, ExactSpelling = true, CharSet = CharSet.Unicode)]
internal static extern int GdipDrawImagePoints(HandleRef graphics, HandleRef image,
HandleRef points, int count);
- [DllImport(ExternDll.Gdiplus, SetLastError = true, ExactSpelling = true, CharSet = System.Runtime.InteropServices.CharSet.Unicode)] // 3 = Unicode
+ [DllImport(ExternDll.Gdiplus, SetLastError = true, ExactSpelling = true, CharSet = CharSet.Unicode)]
internal static extern int GdipDrawImagePointsI(HandleRef graphics, HandleRef image,
HandleRef points, int count);
- [DllImport(ExternDll.Gdiplus, SetLastError = true, ExactSpelling = true, CharSet = System.Runtime.InteropServices.CharSet.Unicode)] // 3 = Unicode
+ [DllImport(ExternDll.Gdiplus, SetLastError = true, ExactSpelling = true, CharSet = CharSet.Unicode)]
internal static extern int GdipDrawImagePointRect(HandleRef graphics, HandleRef image, float x,
float y, float srcx, float srcy,
float srcwidth, float srcheight,
int srcunit);
- [DllImport(ExternDll.Gdiplus, SetLastError = true, ExactSpelling = true, CharSet = System.Runtime.InteropServices.CharSet.Unicode)] // 3 = Unicode
+ [DllImport(ExternDll.Gdiplus, SetLastError = true, ExactSpelling = true, CharSet = CharSet.Unicode)]
internal static extern int GdipDrawImagePointRectI(HandleRef graphics, HandleRef image, int x,
int y, int srcx, int srcy,
int srcwidth, int srcheight,
int srcunit);
- [DllImport(ExternDll.Gdiplus, SetLastError = true, ExactSpelling = true, CharSet = System.Runtime.InteropServices.CharSet.Unicode)] // 3 = Unicode
+ [DllImport(ExternDll.Gdiplus, SetLastError = true, ExactSpelling = true, CharSet = CharSet.Unicode)]
internal static extern int GdipDrawImageRectRect(HandleRef graphics, HandleRef image,
float dstx, float dsty,
float dstwidth, float dstheight,
@@ -2020,7 +1944,7 @@ namespace System.Drawing
int srcunit, HandleRef imageAttributes,
Graphics.DrawImageAbort callback, HandleRef callbackdata);
- [DllImport(ExternDll.Gdiplus, SetLastError = true, ExactSpelling = true, CharSet = System.Runtime.InteropServices.CharSet.Unicode)] // 3 = Unicode
+ [DllImport(ExternDll.Gdiplus, SetLastError = true, ExactSpelling = true, CharSet = CharSet.Unicode)]
internal static extern int GdipDrawImageRectRectI(HandleRef graphics, HandleRef image,
int dstx, int dsty,
int dstwidth, int dstheight,
@@ -2029,7 +1953,7 @@ namespace System.Drawing
int srcunit, HandleRef imageAttributes,
Graphics.DrawImageAbort callback, HandleRef callbackdata);
- [DllImport(ExternDll.Gdiplus, SetLastError = true, ExactSpelling = true, CharSet = System.Runtime.InteropServices.CharSet.Unicode)] // 3 = Unicode
+ [DllImport(ExternDll.Gdiplus, SetLastError = true, ExactSpelling = true, CharSet = CharSet.Unicode)]
internal static extern int GdipDrawImagePointsRect(HandleRef graphics, HandleRef image,
HandleRef points, int count, float srcx,
float srcy, float srcwidth,
@@ -2037,7 +1961,7 @@ namespace System.Drawing
HandleRef imageAttributes,
Graphics.DrawImageAbort callback, HandleRef callbackdata);
- [DllImport(ExternDll.Gdiplus, SetLastError = true, ExactSpelling = true, CharSet = System.Runtime.InteropServices.CharSet.Unicode)] // 3 = Unicode
+ [DllImport(ExternDll.Gdiplus, SetLastError = true, ExactSpelling = true, CharSet = CharSet.Unicode)]
internal static extern int GdipDrawImagePointsRectI(HandleRef graphics, HandleRef image,
HandleRef points, int count, int srcx,
int srcy, int srcwidth,
@@ -2045,7 +1969,7 @@ namespace System.Drawing
HandleRef imageAttributes,
Graphics.DrawImageAbort callback, HandleRef callbackdata);
- [DllImport(ExternDll.Gdiplus, SetLastError = true, ExactSpelling = true, CharSet = System.Runtime.InteropServices.CharSet.Unicode)] // 3 = Unicode
+ [DllImport(ExternDll.Gdiplus, SetLastError = true, ExactSpelling = true, CharSet = CharSet.Unicode)]
internal static extern int GdipEnumerateMetafileDestPoint(HandleRef graphics,
HandleRef metafile,
GPPOINTF destPoint,
@@ -2053,7 +1977,7 @@ namespace System.Drawing
HandleRef callbackdata,
HandleRef imageattributes);
- [DllImport(ExternDll.Gdiplus, SetLastError = true, ExactSpelling = true, CharSet = System.Runtime.InteropServices.CharSet.Unicode)] // 3 = Unicode
+ [DllImport(ExternDll.Gdiplus, SetLastError = true, ExactSpelling = true, CharSet = CharSet.Unicode)]
internal static extern int GdipEnumerateMetafileDestPointI(HandleRef graphics,
HandleRef metafile,
GPPOINT destPoint,
@@ -2061,7 +1985,7 @@ namespace System.Drawing
HandleRef callbackdata,
HandleRef imageattributes);
- [DllImport(ExternDll.Gdiplus, SetLastError = true, ExactSpelling = true, CharSet = System.Runtime.InteropServices.CharSet.Unicode)] // 3 = Unicode
+ [DllImport(ExternDll.Gdiplus, SetLastError = true, ExactSpelling = true, CharSet = CharSet.Unicode)]
internal static extern int GdipEnumerateMetafileDestRect(HandleRef graphics,
HandleRef metafile,
ref GPRECTF destRect,
@@ -2069,7 +1993,7 @@ namespace System.Drawing
HandleRef callbackdata,
HandleRef imageattributes);
- [DllImport(ExternDll.Gdiplus, SetLastError = true, ExactSpelling = true, CharSet = System.Runtime.InteropServices.CharSet.Unicode)] // 3 = Unicode
+ [DllImport(ExternDll.Gdiplus, SetLastError = true, ExactSpelling = true, CharSet = CharSet.Unicode)]
internal static extern int GdipEnumerateMetafileDestRectI(HandleRef graphics,
HandleRef metafile,
ref GPRECT destRect,
@@ -2077,7 +2001,7 @@ namespace System.Drawing
HandleRef callbackdata,
HandleRef imageattributes);
- [DllImport(ExternDll.Gdiplus, SetLastError = true, ExactSpelling = true, CharSet = System.Runtime.InteropServices.CharSet.Unicode)] // 3 = Unicode
+ [DllImport(ExternDll.Gdiplus, SetLastError = true, ExactSpelling = true, CharSet = CharSet.Unicode)]
internal static extern int GdipEnumerateMetafileDestPoints(HandleRef graphics,
HandleRef metafile,
IntPtr destPoints,
@@ -2086,7 +2010,7 @@ namespace System.Drawing
HandleRef callbackdata,
HandleRef imageattributes);
- [DllImport(ExternDll.Gdiplus, SetLastError = true, ExactSpelling = true, CharSet = System.Runtime.InteropServices.CharSet.Unicode)] // 3 = Unicode
+ [DllImport(ExternDll.Gdiplus, SetLastError = true, ExactSpelling = true, CharSet = CharSet.Unicode)]
internal static extern int GdipEnumerateMetafileDestPointsI(HandleRef graphics,
HandleRef metafile,
IntPtr destPoints,
@@ -2095,7 +2019,7 @@ namespace System.Drawing
HandleRef callbackdata,
HandleRef imageattributes);
- [DllImport(ExternDll.Gdiplus, SetLastError = true, ExactSpelling = true, CharSet = System.Runtime.InteropServices.CharSet.Unicode)] // 3 = Unicode
+ [DllImport(ExternDll.Gdiplus, SetLastError = true, ExactSpelling = true, CharSet = CharSet.Unicode)]
internal static extern int GdipEnumerateMetafileSrcRectDestPoint(HandleRef graphics,
HandleRef metafile,
GPPOINTF destPoint,
@@ -2105,7 +2029,7 @@ namespace System.Drawing
HandleRef callbackdata,
HandleRef imageattributes);
- [DllImport(ExternDll.Gdiplus, SetLastError = true, ExactSpelling = true, CharSet = System.Runtime.InteropServices.CharSet.Unicode)] // 3 = Unicode
+ [DllImport(ExternDll.Gdiplus, SetLastError = true, ExactSpelling = true, CharSet = CharSet.Unicode)]
internal static extern int GdipEnumerateMetafileSrcRectDestPointI(HandleRef graphics,
HandleRef metafile,
GPPOINT destPoint,
@@ -2115,7 +2039,7 @@ namespace System.Drawing
HandleRef callbackdata,
HandleRef imageattributes);
- [DllImport(ExternDll.Gdiplus, SetLastError = true, ExactSpelling = true, CharSet = System.Runtime.InteropServices.CharSet.Unicode)] // 3 = Unicode
+ [DllImport(ExternDll.Gdiplus, SetLastError = true, ExactSpelling = true, CharSet = CharSet.Unicode)]
internal static extern int GdipEnumerateMetafileSrcRectDestRect(HandleRef graphics,
HandleRef metafile,
ref GPRECTF destRect,
@@ -2125,7 +2049,7 @@ namespace System.Drawing
HandleRef callbackdata,
HandleRef imageattributes);
- [DllImport(ExternDll.Gdiplus, SetLastError = true, ExactSpelling = true, CharSet = System.Runtime.InteropServices.CharSet.Unicode)] // 3 = Unicode
+ [DllImport(ExternDll.Gdiplus, SetLastError = true, ExactSpelling = true, CharSet = CharSet.Unicode)]
internal static extern int GdipEnumerateMetafileSrcRectDestRectI(HandleRef graphics,
HandleRef metafile,
ref GPRECT destRect,
@@ -2135,7 +2059,7 @@ namespace System.Drawing
HandleRef callbackdata,
HandleRef imageattributes);
- [DllImport(ExternDll.Gdiplus, SetLastError = true, ExactSpelling = true, CharSet = System.Runtime.InteropServices.CharSet.Unicode)] // 3 = Unicode
+ [DllImport(ExternDll.Gdiplus, SetLastError = true, ExactSpelling = true, CharSet = CharSet.Unicode)]
internal static extern int GdipEnumerateMetafileSrcRectDestPoints(HandleRef graphics,
HandleRef metafile,
IntPtr destPoints,
@@ -2146,7 +2070,7 @@ namespace System.Drawing
HandleRef callbackdata,
HandleRef imageattributes);
- [DllImport(ExternDll.Gdiplus, SetLastError = true, ExactSpelling = true, CharSet = System.Runtime.InteropServices.CharSet.Unicode)] // 3 = Unicode
+ [DllImport(ExternDll.Gdiplus, SetLastError = true, ExactSpelling = true, CharSet = CharSet.Unicode)]
internal static extern int GdipEnumerateMetafileSrcRectDestPointsI(HandleRef graphics,
HandleRef metafile,
IntPtr destPoints,
@@ -2157,131 +2081,131 @@ namespace System.Drawing
HandleRef callbackdata,
HandleRef imageattributes);
- [DllImport(ExternDll.Gdiplus, SetLastError = true, ExactSpelling = true, CharSet = System.Runtime.InteropServices.CharSet.Unicode)] // 3 = Unicode
+ [DllImport(ExternDll.Gdiplus, SetLastError = true, ExactSpelling = true, CharSet = CharSet.Unicode)]
internal static extern int GdipPlayMetafileRecord(HandleRef graphics,
EmfPlusRecordType recordType,
int flags,
int dataSize,
byte[] data);
- [DllImport(ExternDll.Gdiplus, SetLastError = true, ExactSpelling = true, CharSet = System.Runtime.InteropServices.CharSet.Unicode)] // 3 = Unicode
+ [DllImport(ExternDll.Gdiplus, SetLastError = true, ExactSpelling = true, CharSet = CharSet.Unicode)]
internal static extern int GdipSetClipGraphics(HandleRef graphics, HandleRef srcgraphics, CombineMode mode);
- [DllImport(ExternDll.Gdiplus, SetLastError = true, ExactSpelling = true, CharSet = System.Runtime.InteropServices.CharSet.Unicode)] // 3 = Unicode
+ [DllImport(ExternDll.Gdiplus, SetLastError = true, ExactSpelling = true, CharSet = CharSet.Unicode)]
internal static extern int GdipSetClipRect(HandleRef graphics, float x, float y,
float width, float height, CombineMode mode);
- [DllImport(ExternDll.Gdiplus, SetLastError = true, ExactSpelling = true, CharSet = System.Runtime.InteropServices.CharSet.Unicode)] // 3 = Unicode
+ [DllImport(ExternDll.Gdiplus, SetLastError = true, ExactSpelling = true, CharSet = CharSet.Unicode)]
internal static extern int GdipSetClipRectI(HandleRef graphics, int x, int y,
int width, int height, CombineMode mode);
- [DllImport(ExternDll.Gdiplus, SetLastError = true, ExactSpelling = true, CharSet = System.Runtime.InteropServices.CharSet.Unicode)] // 3 = Unicode
+ [DllImport(ExternDll.Gdiplus, SetLastError = true, ExactSpelling = true, CharSet = CharSet.Unicode)]
internal static extern int GdipSetClipPath(HandleRef graphics, HandleRef path, CombineMode mode);
- [DllImport(ExternDll.Gdiplus, SetLastError = true, ExactSpelling = true, CharSet = System.Runtime.InteropServices.CharSet.Unicode)] // 3 = Unicode
+ [DllImport(ExternDll.Gdiplus, SetLastError = true, ExactSpelling = true, CharSet = CharSet.Unicode)]
internal static extern int GdipSetClipRegion(HandleRef graphics, HandleRef region, CombineMode mode);
- [DllImport(ExternDll.Gdiplus, SetLastError = true, ExactSpelling = true, CharSet = System.Runtime.InteropServices.CharSet.Unicode)] // 3 = Unicode
+ [DllImport(ExternDll.Gdiplus, SetLastError = true, ExactSpelling = true, CharSet = CharSet.Unicode)]
internal static extern int GdipResetClip(HandleRef graphics);
- [DllImport(ExternDll.Gdiplus, SetLastError = true, ExactSpelling = true, CharSet = System.Runtime.InteropServices.CharSet.Unicode)] // 3 = Unicode
+ [DllImport(ExternDll.Gdiplus, SetLastError = true, ExactSpelling = true, CharSet = CharSet.Unicode)]
internal static extern int GdipTranslateClip(HandleRef graphics, float dx, float dy);
- [DllImport(ExternDll.Gdiplus, SetLastError = true, ExactSpelling = true, CharSet = System.Runtime.InteropServices.CharSet.Unicode)] // 3 = Unicode
+ [DllImport(ExternDll.Gdiplus, SetLastError = true, ExactSpelling = true, CharSet = CharSet.Unicode)]
internal static extern int GdipGetClip(HandleRef graphics, HandleRef region);
- [DllImport(ExternDll.Gdiplus, SetLastError = true, ExactSpelling = true, CharSet = System.Runtime.InteropServices.CharSet.Unicode)] // 3 = Unicode
+ [DllImport(ExternDll.Gdiplus, SetLastError = true, ExactSpelling = true, CharSet = CharSet.Unicode)]
internal static extern int GdipGetClipBounds(HandleRef graphics, ref GPRECTF rect);
- [DllImport(ExternDll.Gdiplus, SetLastError = true, ExactSpelling = true, CharSet = System.Runtime.InteropServices.CharSet.Unicode)] // 3 = Unicode
+ [DllImport(ExternDll.Gdiplus, SetLastError = true, ExactSpelling = true, CharSet = CharSet.Unicode)]
internal static extern int GdipIsClipEmpty(HandleRef graphics,
out int boolean);
- [DllImport(ExternDll.Gdiplus, SetLastError = true, ExactSpelling = true, CharSet = System.Runtime.InteropServices.CharSet.Unicode)] // 3 = Unicode
+ [DllImport(ExternDll.Gdiplus, SetLastError = true, ExactSpelling = true, CharSet = CharSet.Unicode)]
internal static extern int GdipGetVisibleClipBounds(HandleRef graphics, ref GPRECTF rect);
- [DllImport(ExternDll.Gdiplus, SetLastError = true, ExactSpelling = true, CharSet = System.Runtime.InteropServices.CharSet.Unicode)] // 3 = Unicode
+ [DllImport(ExternDll.Gdiplus, SetLastError = true, ExactSpelling = true, CharSet = CharSet.Unicode)]
internal static extern int GdipIsVisibleClipEmpty(HandleRef graphics,
out int boolean);
- [DllImport(ExternDll.Gdiplus, SetLastError = true, ExactSpelling = true, CharSet = System.Runtime.InteropServices.CharSet.Unicode)] // 3 = Unicode
+ [DllImport(ExternDll.Gdiplus, SetLastError = true, ExactSpelling = true, CharSet = CharSet.Unicode)]
internal static extern int GdipIsVisiblePoint(HandleRef graphics, float x, float y,
out int boolean);
- [DllImport(ExternDll.Gdiplus, SetLastError = true, ExactSpelling = true, CharSet = System.Runtime.InteropServices.CharSet.Unicode)] // 3 = Unicode
+ [DllImport(ExternDll.Gdiplus, SetLastError = true, ExactSpelling = true, CharSet = CharSet.Unicode)]
internal static extern int GdipIsVisiblePointI(HandleRef graphics, int x, int y,
out int boolean);
- [DllImport(ExternDll.Gdiplus, SetLastError = true, ExactSpelling = true, CharSet = System.Runtime.InteropServices.CharSet.Unicode)] // 3 = Unicode
+ [DllImport(ExternDll.Gdiplus, SetLastError = true, ExactSpelling = true, CharSet = CharSet.Unicode)]
internal static extern int GdipIsVisibleRect(HandleRef graphics, float x, float y,
float width, float height,
out int boolean);
- [DllImport(ExternDll.Gdiplus, SetLastError = true, ExactSpelling = true, CharSet = System.Runtime.InteropServices.CharSet.Unicode)] // 3 = Unicode
+ [DllImport(ExternDll.Gdiplus, SetLastError = true, ExactSpelling = true, CharSet = CharSet.Unicode)]
internal static extern int GdipIsVisibleRectI(HandleRef graphics, int x, int y,
int width, int height,
out int boolean);
- [DllImport(ExternDll.Gdiplus, SetLastError = true, ExactSpelling = true, CharSet = System.Runtime.InteropServices.CharSet.Unicode)] // 3 = Unicode
+ [DllImport(ExternDll.Gdiplus, SetLastError = true, ExactSpelling = true, CharSet = CharSet.Unicode)]
internal static extern int GdipSaveGraphics(HandleRef graphics, out int state);
- [DllImport(ExternDll.Gdiplus, SetLastError = true, ExactSpelling = true, CharSet = System.Runtime.InteropServices.CharSet.Unicode)] // 3 = Unicode
+ [DllImport(ExternDll.Gdiplus, SetLastError = true, ExactSpelling = true, CharSet = CharSet.Unicode)]
internal static extern int GdipRestoreGraphics(HandleRef graphics, int state);
- [DllImport(ExternDll.Gdiplus, SetLastError = true, ExactSpelling = true, CharSet = System.Runtime.InteropServices.CharSet.Unicode)] // 3 = Unicode
+ [DllImport(ExternDll.Gdiplus, SetLastError = true, ExactSpelling = true, CharSet = CharSet.Unicode)]
internal static extern int GdipBeginContainer(HandleRef graphics, ref GPRECTF dstRect,
ref GPRECTF srcRect, int unit,
out int state);
- [DllImport(ExternDll.Gdiplus, SetLastError = true, ExactSpelling = true, CharSet = System.Runtime.InteropServices.CharSet.Unicode)] // 3 = Unicode
+ [DllImport(ExternDll.Gdiplus, SetLastError = true, ExactSpelling = true, CharSet = CharSet.Unicode)]
internal static extern int GdipBeginContainer2(HandleRef graphics, out int state);
- [DllImport(ExternDll.Gdiplus, SetLastError = true, ExactSpelling = true, CharSet = System.Runtime.InteropServices.CharSet.Unicode)] // 3 = Unicode
+ [DllImport(ExternDll.Gdiplus, SetLastError = true, ExactSpelling = true, CharSet = CharSet.Unicode)]
internal static extern int GdipBeginContainerI(HandleRef graphics, ref GPRECT dstRect,
ref GPRECT srcRect, int unit,
out int state);
- [DllImport(ExternDll.Gdiplus, SetLastError = true, ExactSpelling = true, CharSet = System.Runtime.InteropServices.CharSet.Unicode)] // 3 = Unicode
+ [DllImport(ExternDll.Gdiplus, SetLastError = true, ExactSpelling = true, CharSet = CharSet.Unicode)]
internal static extern int GdipEndContainer(HandleRef graphics, int state);
- [DllImport(ExternDll.Gdiplus, SetLastError = true, ExactSpelling = true, CharSet = System.Runtime.InteropServices.CharSet.Unicode)] // 3 = Unicode
+ [DllImport(ExternDll.Gdiplus, SetLastError = true, ExactSpelling = true, CharSet = CharSet.Unicode)]
internal static extern int GdipGetMetafileHeaderFromWmf(HandleRef hMetafile, // WMF
WmfPlaceableFileHeader wmfplaceable,
[In, Out] MetafileHeaderWmf metafileHeaderWmf);
- [DllImport(ExternDll.Gdiplus, SetLastError = true, ExactSpelling = true, CharSet = System.Runtime.InteropServices.CharSet.Unicode)] // 3 = Unicode
+ [DllImport(ExternDll.Gdiplus, SetLastError = true, ExactSpelling = true, CharSet = CharSet.Unicode)]
internal static extern int GdipGetMetafileHeaderFromEmf(HandleRef hEnhMetafile, // EMF
[In, Out] MetafileHeaderEmf metafileHeaderEmf);
- [DllImport(ExternDll.Gdiplus, SetLastError = true, ExactSpelling = true, CharSet = System.Runtime.InteropServices.CharSet.Unicode)] // 3 = Unicode
+ [DllImport(ExternDll.Gdiplus, SetLastError = true, ExactSpelling = true, CharSet = CharSet.Unicode)]
internal static extern int GdipGetMetafileHeaderFromFile(string filename,
IntPtr header);
- [DllImport(ExternDll.Gdiplus, SetLastError = true, ExactSpelling = true, CharSet = System.Runtime.InteropServices.CharSet.Unicode)] // 3 = Unicode
+ [DllImport(ExternDll.Gdiplus, SetLastError = true, ExactSpelling = true, CharSet = CharSet.Unicode)]
internal static extern int GdipGetMetafileHeaderFromStream(UnsafeNativeMethods.IStream stream,
IntPtr header);
- [DllImport(ExternDll.Gdiplus, SetLastError = true, ExactSpelling = true, CharSet = System.Runtime.InteropServices.CharSet.Unicode)] // 3 = Unicode
+ [DllImport(ExternDll.Gdiplus, SetLastError = true, ExactSpelling = true, CharSet = CharSet.Unicode)]
internal static extern int GdipGetMetafileHeaderFromMetafile(HandleRef metafile,
IntPtr header);
- [DllImport(ExternDll.Gdiplus, SetLastError = true, ExactSpelling = true, CharSet = System.Runtime.InteropServices.CharSet.Unicode)] // 3 = Unicode
+ [DllImport(ExternDll.Gdiplus, SetLastError = true, ExactSpelling = true, CharSet = CharSet.Unicode)]
internal static extern int GdipGetHemfFromMetafile(HandleRef metafile,
out IntPtr hEnhMetafile);
- [DllImport(ExternDll.Gdiplus, SetLastError = true, ExactSpelling = true, CharSet = System.Runtime.InteropServices.CharSet.Unicode)] // 3 = Unicode
+ [DllImport(ExternDll.Gdiplus, SetLastError = true, ExactSpelling = true, CharSet = CharSet.Unicode)]
internal static extern int GdipCreateMetafileFromWmf(HandleRef hMetafile, [MarshalAs(UnmanagedType.Bool)]bool deleteWmf, WmfPlaceableFileHeader wmfplacealbeHeader, out IntPtr metafile);
- [DllImport(ExternDll.Gdiplus, SetLastError = true, ExactSpelling = true, CharSet = System.Runtime.InteropServices.CharSet.Unicode)] // 3 = Unicode
+ [DllImport(ExternDll.Gdiplus, SetLastError = true, ExactSpelling = true, CharSet = CharSet.Unicode)]
internal static extern int GdipCreateMetafileFromEmf(HandleRef hEnhMetafile, bool deleteEmf, out IntPtr metafile);
- [DllImport(ExternDll.Gdiplus, SetLastError = true, ExactSpelling = true, CharSet = System.Runtime.InteropServices.CharSet.Unicode)] // 3 = Unicode
+ [DllImport(ExternDll.Gdiplus, SetLastError = true, ExactSpelling = true, CharSet = CharSet.Unicode)]
internal static extern int GdipCreateMetafileFromFile(string file, out IntPtr metafile);
- [DllImport(ExternDll.Gdiplus, SetLastError = true, ExactSpelling = true, CharSet = System.Runtime.InteropServices.CharSet.Unicode)] // 3 = Unicode
+ [DllImport(ExternDll.Gdiplus, SetLastError = true, ExactSpelling = true, CharSet = CharSet.Unicode)]
internal static extern int GdipCreateMetafileFromStream(UnsafeNativeMethods.IStream stream, out IntPtr metafile);
- [DllImport(ExternDll.Gdiplus, SetLastError = true, ExactSpelling = true, CharSet = System.Runtime.InteropServices.CharSet.Unicode)] // 3 = Unicode
+ [DllImport(ExternDll.Gdiplus, SetLastError = true, ExactSpelling = true, CharSet = CharSet.Unicode)]
internal static extern int GdipRecordMetafile(HandleRef referenceHdc,
int emfType,
ref GPRECTF frameRect,
@@ -2289,7 +2213,7 @@ namespace System.Drawing
string description,
out IntPtr metafile);
- [DllImport(ExternDll.Gdiplus, SetLastError = true, ExactSpelling = true, CharSet = System.Runtime.InteropServices.CharSet.Unicode)] // 3 = Unicode
+ [DllImport(ExternDll.Gdiplus, SetLastError = true, ExactSpelling = true, CharSet = CharSet.Unicode)]
internal static extern int GdipRecordMetafile(HandleRef referenceHdc,
int emfType,
HandleRef pframeRect,
@@ -2297,7 +2221,7 @@ namespace System.Drawing
string description,
out IntPtr metafile);
- [DllImport(ExternDll.Gdiplus, SetLastError = true, ExactSpelling = true, CharSet = System.Runtime.InteropServices.CharSet.Unicode)] // 3 = Unicode
+ [DllImport(ExternDll.Gdiplus, SetLastError = true, ExactSpelling = true, CharSet = CharSet.Unicode)]
internal static extern int GdipRecordMetafileI(HandleRef referenceHdc,
int emfType,
ref GPRECT frameRect,
@@ -2305,7 +2229,7 @@ namespace System.Drawing
string description,
out IntPtr metafile);
- [DllImport(ExternDll.Gdiplus, SetLastError = true, ExactSpelling = true, CharSet = System.Runtime.InteropServices.CharSet.Unicode)] // 3 = Unicode
+ [DllImport(ExternDll.Gdiplus, SetLastError = true, ExactSpelling = true, CharSet = CharSet.Unicode)]
internal static extern int GdipRecordMetafileFileName(string fileName,
HandleRef referenceHdc,
int emfType,
@@ -2314,7 +2238,7 @@ namespace System.Drawing
string description,
out IntPtr metafile);
- [DllImport(ExternDll.Gdiplus, SetLastError = true, ExactSpelling = true, CharSet = System.Runtime.InteropServices.CharSet.Unicode)] // 3 = Unicode
+ [DllImport(ExternDll.Gdiplus, SetLastError = true, ExactSpelling = true, CharSet = CharSet.Unicode)]
internal static extern int GdipRecordMetafileFileName(string fileName,
HandleRef referenceHdc,
int emfType,
@@ -2323,7 +2247,7 @@ namespace System.Drawing
string description,
out IntPtr metafile);
- [DllImport(ExternDll.Gdiplus, SetLastError = true, ExactSpelling = true, CharSet = System.Runtime.InteropServices.CharSet.Unicode)] // 3 = Unicode
+ [DllImport(ExternDll.Gdiplus, SetLastError = true, ExactSpelling = true, CharSet = CharSet.Unicode)]
internal static extern int GdipRecordMetafileFileNameI(string fileName,
HandleRef referenceHdc,
int emfType,
@@ -2332,7 +2256,7 @@ namespace System.Drawing
string description,
out IntPtr metafile);
- [DllImport(ExternDll.Gdiplus, SetLastError = true, ExactSpelling = true, CharSet = System.Runtime.InteropServices.CharSet.Unicode)] // 3 = Unicode
+ [DllImport(ExternDll.Gdiplus, SetLastError = true, ExactSpelling = true, CharSet = CharSet.Unicode)]
internal static extern int GdipRecordMetafileStream(UnsafeNativeMethods.IStream stream,
HandleRef referenceHdc,
int emfType,
@@ -2341,7 +2265,7 @@ namespace System.Drawing
string description,
out IntPtr metafile);
- [DllImport(ExternDll.Gdiplus, SetLastError = true, ExactSpelling = true, CharSet = System.Runtime.InteropServices.CharSet.Unicode)] // 3 = Unicode
+ [DllImport(ExternDll.Gdiplus, SetLastError = true, ExactSpelling = true, CharSet = CharSet.Unicode)]
internal static extern int GdipRecordMetafileStream(UnsafeNativeMethods.IStream stream,
HandleRef referenceHdc,
int emfType,
@@ -2350,7 +2274,7 @@ namespace System.Drawing
string description,
out IntPtr metafile);
- [DllImport(ExternDll.Gdiplus, SetLastError = true, ExactSpelling = true, CharSet = System.Runtime.InteropServices.CharSet.Unicode)] // 3 = Unicode
+ [DllImport(ExternDll.Gdiplus, SetLastError = true, ExactSpelling = true, CharSet = CharSet.Unicode)]
internal static extern int GdipRecordMetafileStreamI(UnsafeNativeMethods.IStream stream,
HandleRef referenceHdc,
int emfType,
@@ -2361,227 +2285,216 @@ namespace System.Drawing
- [DllImport(ExternDll.Gdiplus, SetLastError = true, ExactSpelling = true, CharSet = System.Runtime.InteropServices.CharSet.Unicode)] // 3 = Unicode
+ [DllImport(ExternDll.Gdiplus, SetLastError = true, ExactSpelling = true, CharSet = CharSet.Unicode)]
internal static extern int GdipComment(HandleRef graphics, int sizeData, byte[] data);
//----------------------------------------------------------------------------------------
// Font Collection
//----------------------------------------------------------------------------------------
- [DllImport(ExternDll.Gdiplus, SetLastError = true, ExactSpelling = true, CharSet = System.Runtime.InteropServices.CharSet.Unicode)] // 3 = Unicode
+ [DllImport(ExternDll.Gdiplus, SetLastError = true, ExactSpelling = true, CharSet = CharSet.Unicode)]
internal static extern int GdipNewInstalledFontCollection(out IntPtr fontCollection);
- [DllImport(ExternDll.Gdiplus, SetLastError = true, ExactSpelling = true, CharSet = System.Runtime.InteropServices.CharSet.Unicode)] // 3 = Unicode
+ [DllImport(ExternDll.Gdiplus, SetLastError = true, ExactSpelling = true, CharSet = CharSet.Unicode)]
internal static extern int GdipNewPrivateFontCollection(out IntPtr fontCollection);
- [DllImport(ExternDll.Gdiplus, SetLastError = true, ExactSpelling = true, EntryPoint = "GdipDeletePrivateFontCollection", CharSet = System.Runtime.InteropServices.CharSet.Unicode)] // 3 = Unicode
+ [DllImport(ExternDll.Gdiplus, SetLastError = true, ExactSpelling = true, EntryPoint = "GdipDeletePrivateFontCollection", CharSet = CharSet.Unicode)]
private static extern int IntGdipDeletePrivateFontCollection(out IntPtr fontCollection);
+
internal static int GdipDeletePrivateFontCollection(out IntPtr fontCollection)
{
if (!Initialized)
{
fontCollection = IntPtr.Zero;
- return SafeNativeMethods.Gdip.Ok;
+ return Ok;
}
- int result = IntGdipDeletePrivateFontCollection(out fontCollection);
- return result;
+
+ return IntGdipDeletePrivateFontCollection(out fontCollection);
}
- [DllImport(ExternDll.Gdiplus, SetLastError = true, ExactSpelling = true, CharSet = System.Runtime.InteropServices.CharSet.Unicode)] // 3 = Unicode
+ [DllImport(ExternDll.Gdiplus, SetLastError = true, ExactSpelling = true, CharSet = CharSet.Unicode)]
internal static extern int GdipGetFontCollectionFamilyCount(HandleRef fontCollection, out int numFound);
// should be IntPtr
- [DllImport(ExternDll.Gdiplus, SetLastError = true, ExactSpelling = true, CharSet = System.Runtime.InteropServices.CharSet.Unicode)] // 3 = Unicode
+ [DllImport(ExternDll.Gdiplus, SetLastError = true, ExactSpelling = true, CharSet = CharSet.Unicode)]
internal static extern int GdipGetFontCollectionFamilyList(HandleRef fontCollection, int numSought, IntPtr[] gpfamilies,
out int numFound);
- [DllImport(ExternDll.Gdiplus, SetLastError = true, ExactSpelling = true, CharSet = System.Runtime.InteropServices.CharSet.Unicode)] // 3 = Unicode
+ [DllImport(ExternDll.Gdiplus, SetLastError = true, ExactSpelling = true, CharSet = CharSet.Unicode)]
internal static extern int GdipPrivateAddFontFile(HandleRef fontCollection, string filename);
- [DllImport(ExternDll.Gdiplus, SetLastError = true, ExactSpelling = true, CharSet = System.Runtime.InteropServices.CharSet.Unicode)] // 3 = Unicode
+ [DllImport(ExternDll.Gdiplus, SetLastError = true, ExactSpelling = true, CharSet = CharSet.Unicode)]
internal static extern int GdipPrivateAddMemoryFont(HandleRef fontCollection, HandleRef memory, int length);
//----------------------------------------------------------------------------------------
// FontFamily
//----------------------------------------------------------------------------------------
- [DllImport(ExternDll.Gdiplus, SetLastError = true, ExactSpelling = true, CharSet = System.Runtime.InteropServices.CharSet.Unicode)] // 3 = Unicode
+ [DllImport(ExternDll.Gdiplus, SetLastError = true, ExactSpelling = true, CharSet = CharSet.Unicode)]
internal static extern int GdipCreateFontFamilyFromName(string name, HandleRef fontCollection, out IntPtr FontFamily);
- [DllImport(ExternDll.Gdiplus, SetLastError = true, ExactSpelling = true, CharSet = System.Runtime.InteropServices.CharSet.Unicode)] // 3 = Unicode
+ [DllImport(ExternDll.Gdiplus, SetLastError = true, ExactSpelling = true, CharSet = CharSet.Unicode)]
internal static extern int GdipGetGenericFontFamilySansSerif(out IntPtr fontfamily);
- [DllImport(ExternDll.Gdiplus, SetLastError = true, ExactSpelling = true, CharSet = System.Runtime.InteropServices.CharSet.Unicode)] // 3 = Unicode
+ [DllImport(ExternDll.Gdiplus, SetLastError = true, ExactSpelling = true, CharSet = CharSet.Unicode)]
internal static extern int GdipGetGenericFontFamilySerif(out IntPtr fontfamily);
- [DllImport(ExternDll.Gdiplus, SetLastError = true, ExactSpelling = true, CharSet = System.Runtime.InteropServices.CharSet.Unicode)] // 3 = Unicode
+ [DllImport(ExternDll.Gdiplus, SetLastError = true, ExactSpelling = true, CharSet = CharSet.Unicode)]
internal static extern int GdipGetGenericFontFamilyMonospace(out IntPtr fontfamily);
- [DllImport(ExternDll.Gdiplus, SetLastError = true, ExactSpelling = true, EntryPoint = "GdipDeleteFontFamily", CharSet = System.Runtime.InteropServices.CharSet.Unicode)] // 3 = Unicode
+ [DllImport(ExternDll.Gdiplus, SetLastError = true, ExactSpelling = true, EntryPoint = "GdipDeleteFontFamily", CharSet = CharSet.Unicode)]
private static extern int IntGdipDeleteFontFamily(HandleRef fontFamily);
- internal static int GdipDeleteFontFamily(HandleRef fontFamily)
- {
- if (!Initialized) return SafeNativeMethods.Gdip.Ok;
- int result = IntGdipDeleteFontFamily(fontFamily);
- return result;
- }
- [DllImport(ExternDll.Gdiplus, SetLastError = true, ExactSpelling = true, CharSet = System.Runtime.InteropServices.CharSet.Unicode)] // 3 = Unicode
+ internal static int GdipDeleteFontFamily(HandleRef fontFamily) => Initialized ? IntGdipDeleteFontFamily(fontFamily) : Ok;
+
+ [DllImport(ExternDll.Gdiplus, SetLastError = true, ExactSpelling = true, CharSet = CharSet.Unicode)]
internal static extern int GdipCloneFontFamily(HandleRef fontfamily, out IntPtr clonefontfamily);
- [DllImport(ExternDll.Gdiplus, SetLastError = true, ExactSpelling = true, CharSet = System.Runtime.InteropServices.CharSet.Unicode)] // 3 = Unicode
+ [DllImport(ExternDll.Gdiplus, SetLastError = true, ExactSpelling = true, CharSet = CharSet.Unicode)]
internal static extern int GdipGetFamilyName(HandleRef family, StringBuilder name, int language);
- [DllImport(ExternDll.Gdiplus, SetLastError = true, ExactSpelling = true, CharSet = System.Runtime.InteropServices.CharSet.Unicode)] // 3 = Unicode
+ [DllImport(ExternDll.Gdiplus, SetLastError = true, ExactSpelling = true, CharSet = CharSet.Unicode)]
internal static extern int GdipIsStyleAvailable(HandleRef family, FontStyle style, out int isStyleAvailable);
- [DllImport(ExternDll.Gdiplus, SetLastError = true, ExactSpelling = true, CharSet = System.Runtime.InteropServices.CharSet.Unicode)] // 3 = Unicode
+ [DllImport(ExternDll.Gdiplus, SetLastError = true, ExactSpelling = true, CharSet = CharSet.Unicode)]
internal static extern int GdipGetEmHeight(HandleRef family, FontStyle style, out int EmHeight);
- [DllImport(ExternDll.Gdiplus, SetLastError = true, ExactSpelling = true, CharSet = System.Runtime.InteropServices.CharSet.Unicode)] // 3 = Unicode
+ [DllImport(ExternDll.Gdiplus, SetLastError = true, ExactSpelling = true, CharSet = CharSet.Unicode)]
internal static extern int GdipGetCellAscent(HandleRef family, FontStyle style, out int CellAscent);
- [DllImport(ExternDll.Gdiplus, SetLastError = true, ExactSpelling = true, CharSet = System.Runtime.InteropServices.CharSet.Unicode)] // 3 = Unicode
+ [DllImport(ExternDll.Gdiplus, SetLastError = true, ExactSpelling = true, CharSet = CharSet.Unicode)]
internal static extern int GdipGetCellDescent(HandleRef family, FontStyle style, out int CellDescent);
- [DllImport(ExternDll.Gdiplus, SetLastError = true, ExactSpelling = true, CharSet = System.Runtime.InteropServices.CharSet.Unicode)] // 3 = Unicode
+ [DllImport(ExternDll.Gdiplus, SetLastError = true, ExactSpelling = true, CharSet = CharSet.Unicode)]
internal static extern int GdipGetLineSpacing(HandleRef family, FontStyle style, out int LineSpaceing);
//----------------------------------------------------------------------------------------
// Font
//----------------------------------------------------------------------------------------
- [DllImport(ExternDll.Gdiplus, SetLastError = true, ExactSpelling = true, CharSet = System.Runtime.InteropServices.CharSet.Unicode)] // 3 = Unicode
+ [DllImport(ExternDll.Gdiplus, SetLastError = true, ExactSpelling = true, CharSet = CharSet.Unicode)]
internal static extern int GdipCreateFontFromDC(HandleRef hdc, ref IntPtr font);
- [DllImport(ExternDll.Gdiplus, SetLastError = true, ExactSpelling = true, CharSet = System.Runtime.InteropServices.CharSet.Unicode)] // 3 = Unicode
+ [DllImport(ExternDll.Gdiplus, SetLastError = true, ExactSpelling = true, CharSet = CharSet.Unicode)]
#pragma warning disable CS0618 // Legacy code: We don't care about using obsolete API's.
internal static extern int GdipCreateFontFromLogfontW(HandleRef hdc, [In, Out, MarshalAs(UnmanagedType.AsAny)] object lf, out IntPtr font);
#pragma warning restore CS0618
- [DllImport(ExternDll.Gdiplus, SetLastError = true, ExactSpelling = true, CharSet = System.Runtime.InteropServices.CharSet.Unicode)] // 3 = Unicode
+ [DllImport(ExternDll.Gdiplus, SetLastError = true, ExactSpelling = true, CharSet = CharSet.Unicode)]
internal static extern int GdipCreateFont(HandleRef fontFamily, float emSize, FontStyle style, GraphicsUnit unit, out IntPtr font);
- [DllImport(ExternDll.Gdiplus, SetLastError = true, ExactSpelling = true, CharSet = System.Runtime.InteropServices.CharSet.Unicode)] // 3 = Unicode
+ [DllImport(ExternDll.Gdiplus, SetLastError = true, ExactSpelling = true, CharSet = CharSet.Unicode)]
#pragma warning disable CS0618 // Legacy code: We don't care about using obsolete API's.
internal static extern int GdipGetLogFontW(HandleRef font, HandleRef graphics, [In, Out, MarshalAs(UnmanagedType.AsAny)] object lf);
#pragma warning restore CS0618
- [DllImport(ExternDll.Gdiplus, SetLastError = true, ExactSpelling = true, CharSet = System.Runtime.InteropServices.CharSet.Unicode)] // 3 = Unicode
- [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Security", "CA2118:ReviewSuppressUnmanagedCodeSecurityUsage")]
+ [DllImport(ExternDll.Gdiplus, SetLastError = true, ExactSpelling = true, CharSet = CharSet.Unicode)]
+ [SuppressMessage("Microsoft.Security", "CA2118:ReviewSuppressUnmanagedCodeSecurityUsage")]
internal static extern int GdipCloneFont(HandleRef font, out IntPtr cloneFont);
- [DllImport(ExternDll.Gdiplus, SetLastError = true, ExactSpelling = true, EntryPoint = "GdipDeleteFont", CharSet = System.Runtime.InteropServices.CharSet.Unicode)] // 3 = Unicode
+ [DllImport(ExternDll.Gdiplus, SetLastError = true, ExactSpelling = true, EntryPoint = "GdipDeleteFont", CharSet = CharSet.Unicode)]
private static extern int IntGdipDeleteFont(HandleRef font);
- internal static int GdipDeleteFont(HandleRef font)
- {
- if (!Initialized) return SafeNativeMethods.Gdip.Ok;
- int result = IntGdipDeleteFont(font);
- return result;
- }
- [DllImport(ExternDll.Gdiplus, SetLastError = true, ExactSpelling = true, CharSet = System.Runtime.InteropServices.CharSet.Unicode)] // 3 = Unicode
+ internal static int GdipDeleteFont(HandleRef font) => Initialized ? IntGdipDeleteFont(font) : Ok;
+
+ [DllImport(ExternDll.Gdiplus, SetLastError = true, ExactSpelling = true, CharSet = CharSet.Unicode)]
internal static extern int GdipGetFamily(HandleRef font, out IntPtr family);
- [DllImport(ExternDll.Gdiplus, SetLastError = true, ExactSpelling = true, CharSet = System.Runtime.InteropServices.CharSet.Unicode)] // 3 = Unicode
- [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Security", "CA2118:ReviewSuppressUnmanagedCodeSecurityUsage")]
+ [DllImport(ExternDll.Gdiplus, SetLastError = true, ExactSpelling = true, CharSet = CharSet.Unicode)]
+ [SuppressMessage("Microsoft.Security", "CA2118:ReviewSuppressUnmanagedCodeSecurityUsage")]
internal static extern int GdipGetFontStyle(HandleRef font, out FontStyle style);
- [DllImport(ExternDll.Gdiplus, SetLastError = true, ExactSpelling = true, CharSet = System.Runtime.InteropServices.CharSet.Unicode)] // 3 = Unicode
+ [DllImport(ExternDll.Gdiplus, SetLastError = true, ExactSpelling = true, CharSet = CharSet.Unicode)]
internal static extern int GdipGetFontSize(HandleRef font, out float size);
- [DllImport(ExternDll.Gdiplus, SetLastError = true, ExactSpelling = true, CharSet = System.Runtime.InteropServices.CharSet.Unicode)] // 3 = Unicode
+ [DllImport(ExternDll.Gdiplus, SetLastError = true, ExactSpelling = true, CharSet = CharSet.Unicode)]
internal static extern int GdipGetFontHeight(HandleRef font, HandleRef graphics, out float size);
- [DllImport(ExternDll.Gdiplus, SetLastError = true, ExactSpelling = true, CharSet = System.Runtime.InteropServices.CharSet.Unicode)] // 3 = Unicode
+ [DllImport(ExternDll.Gdiplus, SetLastError = true, ExactSpelling = true, CharSet = CharSet.Unicode)]
internal static extern int GdipGetFontHeightGivenDPI(HandleRef font, float dpi, out float size);
- [DllImport(ExternDll.Gdiplus, SetLastError = true, ExactSpelling = true, CharSet = System.Runtime.InteropServices.CharSet.Unicode)] // 3 = Unicode
- [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Security", "CA2118:ReviewSuppressUnmanagedCodeSecurityUsage")]
+ [DllImport(ExternDll.Gdiplus, SetLastError = true, ExactSpelling = true, CharSet = CharSet.Unicode)]
+ [SuppressMessage("Microsoft.Security", "CA2118:ReviewSuppressUnmanagedCodeSecurityUsage")]
internal static extern int GdipGetFontUnit(HandleRef font, out GraphicsUnit unit);
// Text
- [DllImport(ExternDll.Gdiplus, SetLastError = true, ExactSpelling = true, CharSet = System.Runtime.InteropServices.CharSet.Unicode)] // 3 = Unicode
+ [DllImport(ExternDll.Gdiplus, SetLastError = true, ExactSpelling = true, CharSet = CharSet.Unicode)]
internal static extern int GdipDrawString(HandleRef graphics, string textString, int length, HandleRef font, ref GPRECTF layoutRect,
HandleRef stringFormat, HandleRef brush);
- [DllImport(ExternDll.Gdiplus, SetLastError = true, ExactSpelling = true, CharSet = System.Runtime.InteropServices.CharSet.Unicode)] // 3 = Unicode
+ [DllImport(ExternDll.Gdiplus, SetLastError = true, ExactSpelling = true, CharSet = CharSet.Unicode)]
internal static extern int GdipMeasureString(HandleRef graphics, string textString, int length, HandleRef font, ref GPRECTF layoutRect,
HandleRef stringFormat, [In, Out] ref GPRECTF boundingBox, out int codepointsFitted, out int linesFilled);
- [DllImport(ExternDll.Gdiplus, SetLastError = true, ExactSpelling = true, CharSet = System.Runtime.InteropServices.CharSet.Unicode)] // 3 = Unicode
+ [DllImport(ExternDll.Gdiplus, SetLastError = true, ExactSpelling = true, CharSet = CharSet.Unicode)]
internal static extern int GdipMeasureCharacterRanges(HandleRef graphics, string textString, int length, HandleRef font, ref GPRECTF layoutRect, HandleRef stringFormat,
int characterCount, [In, Out] IntPtr[] region);
- [DllImport(ExternDll.Gdiplus, SetLastError = true, ExactSpelling = true, CharSet = System.Runtime.InteropServices.CharSet.Unicode)] // 3 = Unicode
+ [DllImport(ExternDll.Gdiplus, SetLastError = true, ExactSpelling = true, CharSet = CharSet.Unicode)]
internal static extern int GdipSetStringFormatMeasurableCharacterRanges(HandleRef format, int rangeCount, [In, Out] CharacterRange[] range);
- [DllImport(ExternDll.Gdiplus, SetLastError = true, ExactSpelling = true, CharSet = System.Runtime.InteropServices.CharSet.Unicode)] // 3 = Unicode
+ [DllImport(ExternDll.Gdiplus, SetLastError = true, ExactSpelling = true, CharSet = CharSet.Unicode)]
internal static extern int GdipCreateStringFormat(StringFormatFlags options, int language, out IntPtr format);
- [DllImport(ExternDll.Gdiplus, SetLastError = true, ExactSpelling = true, CharSet = System.Runtime.InteropServices.CharSet.Unicode)] // 3 = Unicode
+ [DllImport(ExternDll.Gdiplus, SetLastError = true, ExactSpelling = true, CharSet = CharSet.Unicode)]
internal static extern int GdipStringFormatGetGenericDefault(out IntPtr format);
- [DllImport(ExternDll.Gdiplus, SetLastError = true, ExactSpelling = true, CharSet = System.Runtime.InteropServices.CharSet.Unicode)] // 3 = Unicode
+ [DllImport(ExternDll.Gdiplus, SetLastError = true, ExactSpelling = true, CharSet = CharSet.Unicode)]
internal static extern int GdipStringFormatGetGenericTypographic(out IntPtr format);
- [DllImport(ExternDll.Gdiplus, SetLastError = true, ExactSpelling = true, EntryPoint = "GdipDeleteStringFormat", CharSet = System.Runtime.InteropServices.CharSet.Unicode)] // 3 = Unicode
+ [DllImport(ExternDll.Gdiplus, SetLastError = true, ExactSpelling = true, EntryPoint = "GdipDeleteStringFormat", CharSet = CharSet.Unicode)]
private static extern int IntGdipDeleteStringFormat(HandleRef format);
- internal static int GdipDeleteStringFormat(HandleRef format)
- {
- if (!Initialized) return SafeNativeMethods.Gdip.Ok;
- int result = IntGdipDeleteStringFormat(format);
- return result;
- }
- [DllImport(ExternDll.Gdiplus, SetLastError = true, ExactSpelling = true, CharSet = System.Runtime.InteropServices.CharSet.Unicode)] // 3 = Unicode
+ internal static int GdipDeleteStringFormat(HandleRef format) => Initialized ? IntGdipDeleteStringFormat(format) : Ok;
+
+ [DllImport(ExternDll.Gdiplus, SetLastError = true, ExactSpelling = true, CharSet = CharSet.Unicode)]
internal static extern int GdipCloneStringFormat(HandleRef format, out IntPtr newFormat);
- [DllImport(ExternDll.Gdiplus, SetLastError = true, ExactSpelling = true, CharSet = System.Runtime.InteropServices.CharSet.Unicode)] // 3 = Unicode
+ [DllImport(ExternDll.Gdiplus, SetLastError = true, ExactSpelling = true, CharSet = CharSet.Unicode)]
internal static extern int GdipSetStringFormatFlags(HandleRef format, StringFormatFlags options);
- [DllImport(ExternDll.Gdiplus, SetLastError = true, ExactSpelling = true, CharSet = System.Runtime.InteropServices.CharSet.Unicode)] // 3 = Unicode
+ [DllImport(ExternDll.Gdiplus, SetLastError = true, ExactSpelling = true, CharSet = CharSet.Unicode)]
internal static extern int GdipGetStringFormatFlags(HandleRef format, out StringFormatFlags result);
- [DllImport(ExternDll.Gdiplus, SetLastError = true, ExactSpelling = true, CharSet = System.Runtime.InteropServices.CharSet.Unicode)] // 3 = Unicode
+ [DllImport(ExternDll.Gdiplus, SetLastError = true, ExactSpelling = true, CharSet = CharSet.Unicode)]
internal static extern int GdipSetStringFormatAlign(HandleRef format, StringAlignment align);
- [DllImport(ExternDll.Gdiplus, SetLastError = true, ExactSpelling = true, CharSet = System.Runtime.InteropServices.CharSet.Unicode)] // 3 = Unicode
+ [DllImport(ExternDll.Gdiplus, SetLastError = true, ExactSpelling = true, CharSet = CharSet.Unicode)]
internal static extern int GdipGetStringFormatAlign(HandleRef format, out StringAlignment align);
- [DllImport(ExternDll.Gdiplus, SetLastError = true, ExactSpelling = true, CharSet = System.Runtime.InteropServices.CharSet.Unicode)] // 3 = Unicode
+ [DllImport(ExternDll.Gdiplus, SetLastError = true, ExactSpelling = true, CharSet = CharSet.Unicode)]
internal static extern int GdipSetStringFormatLineAlign(HandleRef format, StringAlignment align);
- [DllImport(ExternDll.Gdiplus, SetLastError = true, ExactSpelling = true, CharSet = System.Runtime.InteropServices.CharSet.Unicode)] // 3 = Unicode
+ [DllImport(ExternDll.Gdiplus, SetLastError = true, ExactSpelling = true, CharSet = CharSet.Unicode)]
internal static extern int GdipGetStringFormatLineAlign(HandleRef format, out StringAlignment align);
- [DllImport(ExternDll.Gdiplus, SetLastError = true, ExactSpelling = true, CharSet = System.Runtime.InteropServices.CharSet.Unicode)] // 3 = Unicode
+ [DllImport(ExternDll.Gdiplus, SetLastError = true, ExactSpelling = true, CharSet = CharSet.Unicode)]
internal static extern int GdipSetStringFormatHotkeyPrefix(HandleRef format, HotkeyPrefix hotkeyPrefix);
- [DllImport(ExternDll.Gdiplus, SetLastError = true, ExactSpelling = true, CharSet = System.Runtime.InteropServices.CharSet.Unicode)] // 3 = Unicode
+ [DllImport(ExternDll.Gdiplus, SetLastError = true, ExactSpelling = true, CharSet = CharSet.Unicode)]
internal static extern int GdipGetStringFormatHotkeyPrefix(HandleRef format, out HotkeyPrefix hotkeyPrefix);
- [DllImport(ExternDll.Gdiplus, SetLastError = true, ExactSpelling = true, CharSet = System.Runtime.InteropServices.CharSet.Unicode)] // 3 = Unicode
+ [DllImport(ExternDll.Gdiplus, SetLastError = true, ExactSpelling = true, CharSet = CharSet.Unicode)]
internal static extern int GdipSetStringFormatTabStops(HandleRef format, float firstTabOffset, int count, float[] tabStops);
- [DllImport(ExternDll.Gdiplus, SetLastError = true, ExactSpelling = true, CharSet = System.Runtime.InteropServices.CharSet.Unicode)] // 3 = Unicode
+ [DllImport(ExternDll.Gdiplus, SetLastError = true, ExactSpelling = true, CharSet = CharSet.Unicode)]
internal static extern int GdipGetStringFormatTabStops(HandleRef format, int count, out float firstTabOffset, [In, Out]float[] tabStops);
- [DllImport(ExternDll.Gdiplus, SetLastError = true, ExactSpelling = true, CharSet = System.Runtime.InteropServices.CharSet.Unicode)] // 3 = Unicode
+ [DllImport(ExternDll.Gdiplus, SetLastError = true, ExactSpelling = true, CharSet = CharSet.Unicode)]
internal static extern int GdipGetStringFormatTabStopCount(HandleRef format, out int count);
- [DllImport(ExternDll.Gdiplus, SetLastError = true, ExactSpelling = true, CharSet = System.Runtime.InteropServices.CharSet.Unicode)] // 3 = Unicode
+ [DllImport(ExternDll.Gdiplus, SetLastError = true, ExactSpelling = true, CharSet = CharSet.Unicode)]
internal static extern int GdipGetStringFormatMeasurableCharacterRangeCount(HandleRef format, out int count);
- [DllImport(ExternDll.Gdiplus, SetLastError = true, ExactSpelling = true, CharSet = System.Runtime.InteropServices.CharSet.Unicode)] // 3 = Unicode
+ [DllImport(ExternDll.Gdiplus, SetLastError = true, ExactSpelling = true, CharSet = CharSet.Unicode)]
internal static extern int GdipSetStringFormatTrimming(HandleRef format, StringTrimming trimming);
- [DllImport(ExternDll.Gdiplus, SetLastError = true, ExactSpelling = true, CharSet = System.Runtime.InteropServices.CharSet.Unicode)] // 3 = Unicode
+ [DllImport(ExternDll.Gdiplus, SetLastError = true, ExactSpelling = true, CharSet = CharSet.Unicode)]
internal static extern int GdipGetStringFormatTrimming(HandleRef format, out StringTrimming trimming);
- [DllImport(ExternDll.Gdiplus, SetLastError = true, ExactSpelling = true, CharSet = System.Runtime.InteropServices.CharSet.Unicode)] // 3 = Unicode
+ [DllImport(ExternDll.Gdiplus, SetLastError = true, ExactSpelling = true, CharSet = CharSet.Unicode)]
internal static extern int GdipSetStringFormatDigitSubstitution(HandleRef format, int langID, StringDigitSubstitute sds);
- [DllImport(ExternDll.Gdiplus, SetLastError = true, ExactSpelling = true, CharSet = System.Runtime.InteropServices.CharSet.Unicode)] // 3 = Unicode
+ [DllImport(ExternDll.Gdiplus, SetLastError = true, ExactSpelling = true, CharSet = CharSet.Unicode)]
internal static extern int GdipGetStringFormatDigitSubstitution(HandleRef format, out int langID, out StringDigitSubstitute sds);
//----------------------------------------------------------------------------------------
@@ -2639,7 +2552,6 @@ namespace System.Drawing
case PropertyNotFound: return new ArgumentException(SR.Format(SR.GdiplusPropertyNotFoundError));
case PropertyNotSupported: return new ArgumentException(SR.Format(SR.GdiplusPropertyNotSupportedError));
-
case FontFamilyNotFound:
Debug.Fail("We should be special casing FontFamilyNotFound so we can provide the font name");
return new ArgumentException(SR.Format(SR.GdiplusFontFamilyNotFound, "?"));
@@ -2668,18 +2580,17 @@ namespace System.Drawing
internal static PointF[] ConvertGPPOINTFArrayF(IntPtr memory, int count)
{
if (memory == IntPtr.Zero)
- throw new ArgumentNullException("memory");
-
- PointF[] points = new PointF[count];
-
- int index;
- GPPOINTF pt = new GPPOINTF();
+ {
+ throw new ArgumentNullException(nameof(memory));
+ }
- int size = (int)Marshal.SizeOf(pt.GetType());
+ var points = new PointF[count];
+ Type pointType = typeof(GPPOINTF);
+ int size = Marshal.SizeOf(pointType);
- for (index = 0; index < count; index++)
+ for (int index = 0; index < count; index++)
{
- pt = (GPPOINTF)UnsafeNativeMethods.PtrToStructure((IntPtr)((long)memory + index * size), pt.GetType());
+ var pt = (GPPOINTF)Marshal.PtrToStructure((IntPtr)((long)memory + index * size), pointType);
points[index] = new PointF(pt.X, pt.Y);
}
@@ -2692,19 +2603,19 @@ namespace System.Drawing
internal static Point[] ConvertGPPOINTArray(IntPtr memory, int count)
{
if (memory == IntPtr.Zero)
- throw new ArgumentNullException("memory");
-
- Point[] points = new Point[count];
+ {
+ throw new ArgumentNullException(nameof(memory));
+ }
- int index;
- GPPOINT pt = new GPPOINT();
+ var points = new Point[count];
+ Type pointType = typeof(GPPOINT);
- int size = (int)Marshal.SizeOf(pt.GetType());
+ int size = Marshal.SizeOf(pointType);
- for (index = 0; index < count; index++)
+ for (int index = 0; index < count; index++)
{
- pt = (GPPOINT)UnsafeNativeMethods.PtrToStructure((IntPtr)((long)memory + index * size), pt.GetType());
- points[index] = new Point((int)pt.X, (int)pt.Y);
+ var pt = (GPPOINT)Marshal.PtrToStructure((IntPtr)((long)memory + index * size), pointType);
+ points[index] = new Point(pt.X, pt.Y);
}
return points;
@@ -2716,16 +2627,15 @@ namespace System.Drawing
internal static IntPtr ConvertPointToMemory(PointF[] points)
{
if (points == null)
- throw new ArgumentNullException("points");
-
- int index;
+ {
+ throw new ArgumentNullException(nameof(points));
+ }
int size = (int)Marshal.SizeOf(typeof(GPPOINTF));
int count = points.Length;
-
IntPtr memory = Marshal.AllocHGlobal(checked(count * size));
- for (index = 0; index < count; index++)
+ for (int index = 0; index < count; index++)
{
Marshal.StructureToPtr(new GPPOINTF(points[index]), (IntPtr)(checked((long)memory + index * size)), false);
}
@@ -2739,16 +2649,15 @@ namespace System.Drawing
internal static IntPtr ConvertPointToMemory(Point[] points)
{
if (points == null)
- throw new ArgumentNullException("points");
-
- int index;
+ {
+ throw new ArgumentNullException(nameof(points));
+ }
- int size = (int)Marshal.SizeOf(typeof(GPPOINT));
+ int size = Marshal.SizeOf(typeof(GPPOINT));
int count = points.Length;
-
IntPtr memory = Marshal.AllocHGlobal(checked(count * size));
- for (index = 0; index < count; index++)
+ for (int index = 0; index < count; index++)
{
Marshal.StructureToPtr(new GPPOINT(points[index]), (IntPtr)(checked((long)memory + index * size)), false);
}
@@ -2762,16 +2671,15 @@ namespace System.Drawing
internal static IntPtr ConvertRectangleToMemory(RectangleF[] rect)
{
if (rect == null)
- throw new ArgumentNullException("rect");
-
- int index;
+ {
+ throw new ArgumentNullException(nameof(rect));
+ }
- int size = (int)Marshal.SizeOf(typeof(GPRECTF));
+ int size = Marshal.SizeOf(typeof(GPRECTF));
int count = rect.Length;
-
IntPtr memory = Marshal.AllocHGlobal(checked(count * size));
- for (index = 0; index < count; index++)
+ for (int index = 0; index < count; index++)
{
Marshal.StructureToPtr(new GPRECTF(rect[index]), (IntPtr)(checked((long)memory + index * size)), false);
}
@@ -2785,16 +2693,15 @@ namespace System.Drawing
internal static IntPtr ConvertRectangleToMemory(Rectangle[] rect)
{
if (rect == null)
- throw new ArgumentNullException("rect");
-
- int index;
+ {
+ throw new ArgumentNullException(nameof(rect));
+ }
int size = (int)Marshal.SizeOf(typeof(GPRECT));
int count = rect.Length;
-
IntPtr memory = Marshal.AllocHGlobal(checked(count * size));
- for (index = 0; index < count; index++)
+ for (int index = 0; index < count; index++)
{
Marshal.StructureToPtr(new GPRECT(rect[index]), (IntPtr)(checked((long)memory + index * size)), false);
}
@@ -2803,98 +2710,27 @@ namespace System.Drawing
}
}
- public static IntPtr InvalidIntPtr = ((IntPtr)((int)(-1)));
-
-
public const int ERROR_CANCELLED = 1223;
public const int
- RASTERCAPS = 38,
- RC_PALETTE = 0x0100,
- SIZEPALETTE = 104,
- SYSPAL_STATIC = 1,
-
- BS_SOLID = 0,
- HOLLOW_BRUSH = 5,
-
- // Binary raster operations.
- R2_BLACK = 1, /* 0 */
- R2_NOTMERGEPEN = 2, /* DPon */
- R2_MASKNOTPEN = 3, /* DPna */
- R2_NOTCOPYPEN = 4, /* PN */
- R2_MASKPENNOT = 5, /* PDna */
- R2_NOT = 6, /* Dn */
- R2_XORPEN = 7, /* DPx */
- R2_NOTMASKPEN = 8, /* DPan */
- R2_MASKPEN = 9, /* DPa */
- R2_NOTXORPEN = 10, /* DPxn */
- R2_NOP = 11, /* D */
- R2_MERGENOTPEN = 12, /* DPno */
- R2_COPYPEN = 13, /* P */
- R2_MERGEPENNOT = 14, /* PDno */
- R2_MERGEPEN = 15, /* DPo */
- R2_WHITE = 16, /* 1 */
-
- UOI_FLAGS = 1,
- WSF_VISIBLE = 0x0001,
E_UNEXPECTED = unchecked((int)0x8000FFFF),
E_NOTIMPL = unchecked((int)0x80004001),
- E_OUTOFMEMORY = unchecked((int)0x8007000E),
- E_INVALIDARG = unchecked((int)0x80070057),
- E_NOINTERFACE = unchecked((int)0x80004002),
- E_POINTER = unchecked((int)0x80004003),
- E_HANDLE = unchecked((int)0x80070006),
E_ABORT = unchecked((int)0x80004004),
E_FAIL = unchecked((int)0x80004005),
E_ACCESSDENIED = unchecked((int)0x80070005),
- PM_NOREMOVE = 0x0000,
- PM_REMOVE = 0x0001,
- PM_NOYIELD = 0x0002,
- GMEM_FIXED = 0x0000,
GMEM_MOVEABLE = 0x0002,
- GMEM_NOCOMPACT = 0x0010,
- GMEM_NODISCARD = 0x0020,
GMEM_ZEROINIT = 0x0040,
- GMEM_MODIFY = 0x0080,
- GMEM_DISCARDABLE = 0x0100,
- GMEM_NOT_BANKED = 0x1000,
- GMEM_SHARE = 0x2000,
- GMEM_DDESHARE = 0x2000,
- GMEM_NOTIFY = 0x4000,
- GMEM_LOWER = 0x1000,
- GMEM_VALID_FLAGS = 0x7F72,
- GMEM_INVALID_HANDLE = unchecked((int)0x8000),
- DM_UPDATE = 1,
- DM_COPY = 2,
- DM_PROMPT = 4,
- DM_MODIFY = 8,
DM_IN_BUFFER = 8,
- DM_IN_PROMPT = 4,
DM_OUT_BUFFER = 2,
- DM_OUT_DEFAULT = 1,
DT_PLOTTER = 0,
- DT_RASDISPLAY = 1,
DT_RASPRINTER = 2,
- DT_RASCAMERA = 3,
- DT_CHARSTREAM = 4,
- DT_METAFILE = 5,
- DT_DISPFILE = 6,
TECHNOLOGY = 2,
- DC_FIELDS = 1,
DC_PAPERS = 2,
DC_PAPERSIZE = 3,
- DC_MINEXTENT = 4,
- DC_MAXEXTENT = 5,
DC_BINS = 6,
DC_DUPLEX = 7,
- DC_SIZE = 8,
- DC_EXTRA = 9,
- DC_VERSION = 10,
- DC_DRIVER = 11,
DC_BINNAMES = 12,
DC_ENUMRESOLUTIONS = 13,
- DC_FILEDEPENDENCIES = 14,
- DC_TRUETYPE = 15,
DC_PAPERNAMES = 16,
DC_ORIENTATION = 17,
DC_COPIES = 18,
@@ -2902,52 +2738,9 @@ namespace System.Drawing
PD_SELECTION = 0x00000001,
PD_PAGENUMS = 0x00000002,
PD_CURRENTPAGE = 0x00400000,
- PD_NOSELECTION = 0x00000004,
- PD_NOPAGENUMS = 0x00000008,
- PD_NOCURRENTPAGE = 0x00800000,
- PD_COLLATE = 0x00000010,
- PD_PRINTTOFILE = 0x00000020,
- PD_PRINTSETUP = 0x00000040,
- PD_NOWARNING = 0x00000080,
- PD_RETURNDC = 0x00000100,
- PD_RETURNIC = 0x00000200,
- PD_RETURNDEFAULT = 0x00000400,
- PD_SHOWHELP = 0x00000800,
- PD_ENABLEPRINTHOOK = 0x00001000,
- PD_ENABLESETUPHOOK = 0x00002000,
- PD_ENABLEPRINTTEMPLATE = 0x00004000,
- PD_ENABLESETUPTEMPLATE = 0x00008000,
- PD_ENABLEPRINTTEMPLATEHANDLE = 0x00010000,
- PD_ENABLESETUPTEMPLATEHANDLE = 0x00020000,
- PD_USEDEVMODECOPIES = 0x00040000,
- PD_USEDEVMODECOPIESANDCOLLATE = 0x00040000,
- PD_DISABLEPRINTTOFILE = 0x00080000,
- PD_HIDEPRINTTOFILE = 0x00100000,
- PD_NONETWORKBUTTON = 0x00200000,
- DI_MASK = 0x0001,
- DI_IMAGE = 0x0002,
+ PD_RETURNDEFAULT = 0x00000400,
DI_NORMAL = 0x0003,
- DI_COMPAT = 0x0004,
- DI_DEFAULTSIZE = 0x0008,
- IDC_ARROW = 32512,
- IDC_IBEAM = 32513,
- IDC_WAIT = 32514,
- IDC_CROSS = 32515,
- IDC_UPARROW = 32516,
- IDC_SIZE = 32640,
- IDC_ICON = 32641,
- IDC_SIZENWSE = 32642,
- IDC_SIZENESW = 32643,
- IDC_SIZEWE = 32644,
- IDC_SIZENS = 32645,
- IDC_SIZEALL = 32646,
- IDC_NO = 32648,
- IDC_APPSTARTING = 32650,
- IDC_HELP = 32651,
- IMAGE_BITMAP = 0,
IMAGE_ICON = 1,
- IMAGE_CURSOR = 2,
- IMAGE_ENHMETAFILE = 3,
IDI_APPLICATION = 32512,
IDI_HAND = 32513,
IDI_QUESTION = 32514,
@@ -2957,70 +2750,28 @@ namespace System.Drawing
IDI_WARNING = 32515,
IDI_ERROR = 32513,
IDI_INFORMATION = 32516,
- IDI_SHIELD = 32518,
- SRCCOPY = 0x00CC0020,
+ SRCCOPY = 0x00CC0020,
PLANES = 14,
- PS_SOLID = 0,
- PS_DASH = 1,
- PS_DOT = 2,
- PS_DASHDOT = 3,
- PS_DASHDOTDOT = 4,
- PS_NULL = 5,
- PS_INSIDEFRAME = 6,
- PS_USERSTYLE = 7,
- PS_ALTERNATE = 8,
- PS_STYLE_MASK = 0x0000000F,
- PS_ENDCAP_ROUND = 0x00000000,
- PS_ENDCAP_SQUARE = 0x00000100,
- PS_ENDCAP_FLAT = 0x00000200,
- PS_ENDCAP_MASK = 0x00000F00,
- PS_JOIN_ROUND = 0x00000000,
- PS_JOIN_BEVEL = 0x00001000,
- PS_JOIN_MITER = 0x00002000,
- PS_JOIN_MASK = 0x0000F000,
- PS_COSMETIC = 0x00000000,
- PS_GEOMETRIC = 0x00010000,
- PS_TYPE_MASK = 0x000F0000,
BITSPIXEL = 12,
- ALTERNATE = 1,
LOGPIXELSX = 88,
LOGPIXELSY = 90,
PHYSICALWIDTH = 110,
PHYSICALHEIGHT = 111,
PHYSICALOFFSETX = 112,
PHYSICALOFFSETY = 113,
- WINDING = 2,
VERTRES = 10,
HORZRES = 8,
- DM_SPECVERSION = 0x0401,
DM_ORIENTATION = 0x00000001,
DM_PAPERSIZE = 0x00000002,
DM_PAPERLENGTH = 0x00000004,
DM_PAPERWIDTH = 0x00000008,
- DM_SCALE = 0x00000010,
DM_COPIES = 0x00000100,
DM_DEFAULTSOURCE = 0x00000200,
DM_PRINTQUALITY = 0x00000400,
DM_COLOR = 0x00000800,
DM_DUPLEX = 0x00001000,
DM_YRESOLUTION = 0x00002000,
- DM_TTOPTION = 0x00004000,
DM_COLLATE = 0x00008000,
- DM_FORMNAME = 0x00010000,
- DM_LOGPIXELS = 0x00020000,
- DM_BITSPERPEL = 0x00040000,
- DM_PELSWIDTH = 0x00080000,
- DM_PELSHEIGHT = 0x00100000,
- DM_DISPLAYFLAGS = 0x00200000,
- DM_DISPLAYFREQUENCY = 0x00400000,
- DM_PANNINGWIDTH = 0x00800000,
- DM_PANNINGHEIGHT = 0x01000000,
- DM_ICMMETHOD = 0x02000000,
- DM_ICMINTENT = 0x04000000,
- DM_MEDIATYPE = 0x08000000,
- DM_DITHERTYPE = 0x10000000,
- DM_ICCMANUFACTURER = 0x20000000,
- DM_ICCMODEL = 0x40000000,
DMORIENT_PORTRAIT = 1,
DMORIENT_LANDSCAPE = 2,
DMPAPER_LETTER = 1,
@@ -3145,10 +2896,8 @@ namespace System.Drawing
DMPAPER_PENV_10_ROTATED = 118, /* PRC Envelope #10 Rotated 458 x 324 mm */
DMPAPER_LAST = DMPAPER_PENV_10_ROTATED,
- DMPAPER_USER = 256,
DMBIN_UPPER = 1,
- DMBIN_ONLYONE = 1,
DMBIN_LOWER = 2,
DMBIN_MIDDLE = 3,
DMBIN_MANUAL = 4,
@@ -3172,67 +2921,11 @@ namespace System.Drawing
DMDUP_SIMPLEX = 1,
DMDUP_VERTICAL = 2,
DMDUP_HORIZONTAL = 3,
- DMTT_BITMAP = 1,
- DMTT_DOWNLOAD = 2,
- DMTT_SUBDEV = 3,
- DMTT_DOWNLOAD_OUTLINE = 4,
+
DMCOLLATE_FALSE = 0,
DMCOLLATE_TRUE = 1,
- DMDISPLAYFLAGS_TEXTMODE = 0x00000004,
- DMICMMETHOD_NONE = 1,
- DMICMMETHOD_SYSTEM = 2,
- DMICMMETHOD_DRIVER = 3,
- DMICMMETHOD_DEVICE = 4,
- DMICMMETHOD_USER = 256,
- DMICM_SATURATE = 1,
- DMICM_CONTRAST = 2,
- DMICM_COLORMETRIC = 3,
- DMICM_USER = 256,
- DMMEDIA_STANDARD = 1,
- DMMEDIA_TRANSPARENCY = 2,
- DMMEDIA_GLOSSY = 3,
- DMMEDIA_USER = 256,
- DMDITHER_NONE = 1,
- DMDITHER_COARSE = 2,
- DMDITHER_FINE = 3,
- DMDITHER_LINEART = 4,
- DMDITHER_GRAYSCALE = 5,
- DMDITHER_USER = 256,
- PRINTER_ENUM_DEFAULT = 0x00000001,
PRINTER_ENUM_LOCAL = 0x00000002,
PRINTER_ENUM_CONNECTIONS = 0x00000004,
- PRINTER_ENUM_FAVORITE = 0x00000004,
- PRINTER_ENUM_NAME = 0x00000008,
- PRINTER_ENUM_REMOTE = 0x00000010,
- PRINTER_ENUM_SHARED = 0x00000020,
- PRINTER_ENUM_NETWORK = 0x00000040,
- PRINTER_ENUM_EXPAND = 0x00004000,
- PRINTER_ENUM_CONTAINER = 0x00008000,
- PRINTER_ENUM_ICONMASK = 0x00ff0000,
- PRINTER_ENUM_ICON1 = 0x00010000,
- PRINTER_ENUM_ICON2 = 0x00020000,
- PRINTER_ENUM_ICON3 = 0x00040000,
- PRINTER_ENUM_ICON4 = 0x00080000,
- PRINTER_ENUM_ICON5 = 0x00100000,
- PRINTER_ENUM_ICON6 = 0x00200000,
- PRINTER_ENUM_ICON7 = 0x00400000,
- PRINTER_ENUM_ICON8 = 0x00800000,
- DC_BINADJUST = 19,
- DC_EMF_COMPLIANT = 20,
- DC_DATATYPE_PRODUCED = 21,
- DC_COLLATE = 22,
- DCTT_BITMAP = 0x0000001,
- DCTT_DOWNLOAD = 0x0000002,
- DCTT_SUBDEV = 0x0000004,
- DCTT_DOWNLOAD_OUTLINE = 0x0000008,
- DCBA_FACEUPNONE = 0x0000,
- DCBA_FACEUPCENTER = 0x0001,
- DCBA_FACEUPLEFT = 0x0002,
- DCBA_FACEUPRIGHT = 0x0003,
- DCBA_FACEDOWNNONE = 0x0100,
- DCBA_FACEDOWNCENTER = 0x0101,
- DCBA_FACEDOWNLEFT = 0x0102,
- DCBA_FACEDOWNRIGHT = 0x0103,
SRCPAINT = 0x00EE0086, /* dest = source OR dest */
SRCAND = 0x008800C6, /* dest = source AND dest */
SRCINVERT = 0x00660046, /* dest = source XOR dest */
@@ -3248,162 +2941,21 @@ namespace System.Drawing
BLACKNESS = 0x00000042, /* dest = BLACK */
WHITENESS = 0x00FF0062, /* dest = WHITE */
CAPTUREBLT = 0x40000000, /* Include layered windows */
- SM_CXSCREEN = 0,
- SM_CYSCREEN = 1,
- SM_CXVSCROLL = 2,
- SM_CYHSCROLL = 3,
- SM_CYCAPTION = 4,
- SM_CXBORDER = 5,
- SM_CYBORDER = 6,
- SM_CXDLGFRAME = 7,
- SM_CYDLGFRAME = 8,
- SM_CYVTHUMB = 9,
- SM_CXHTHUMB = 10,
SM_CXICON = 11,
SM_CYICON = 12,
- SM_CXCURSOR = 13,
- SM_CYCURSOR = 14,
- SM_CYMENU = 15,
- SM_CXFULLSCREEN = 16,
- SM_CYFULLSCREEN = 17,
- SM_CYKANJIWINDOW = 18,
- SM_MOUSEPRESENT = 19,
- SM_CYVSCROLL = 20,
- SM_CXHSCROLL = 21,
- SM_DEBUG = 22,
- SM_SWAPBUTTON = 23,
- SM_RESERVED1 = 24,
- SM_RESERVED2 = 25,
- SM_RESERVED3 = 26,
- SM_RESERVED4 = 27,
- SM_CXMIN = 28,
- SM_CYMIN = 29,
- SM_CXSIZE = 30,
- SM_CYSIZE = 31,
- SM_CXFRAME = 32,
- SM_CYFRAME = 33,
- SM_CXMINTRACK = 34,
- SM_CYMINTRACK = 35,
- SM_CXDOUBLECLK = 36,
- SM_CYDOUBLECLK = 37,
- SM_CXICONSPACING = 38,
- SM_CYICONSPACING = 39,
- SM_MENUDROPALIGNMENT = 40,
- SM_PENWINDOWS = 41,
- SM_DBCSENABLED = 42,
- SM_CMOUSEBUTTONS = 43,
- SM_CXFIXEDFRAME = 7,
- SM_CYFIXEDFRAME = 8,
- SM_CXSIZEFRAME = 32,
- SM_CYSIZEFRAME = 33,
- SM_SECURE = 44,
- SM_CXEDGE = 45,
- SM_CYEDGE = 46,
- SM_CXMINSPACING = 47,
- SM_CYMINSPACING = 48,
- SM_CXSMICON = 49,
- SM_CYSMICON = 50,
- SM_CYSMCAPTION = 51,
- SM_CXSMSIZE = 52,
- SM_CYSMSIZE = 53,
- SM_CXMENUSIZE = 54,
- SM_CYMENUSIZE = 55,
- SM_ARRANGE = 56,
- SM_CXMINIMIZED = 57,
- SM_CYMINIMIZED = 58,
- SM_CXMAXTRACK = 59,
- SM_CYMAXTRACK = 60,
- SM_CXMAXIMIZED = 61,
- SM_CYMAXIMIZED = 62,
- SM_NETWORK = 63,
- SM_CLEANBOOT = 67,
- SM_CXDRAG = 68,
- SM_CYDRAG = 69,
- SM_SHOWSOUNDS = 70,
- SM_CXMENUCHECK = 71,
- SM_CYMENUCHECK = 72,
- SM_SLOWMACHINE = 73,
- SM_MIDEASTENABLED = 74,
- SM_MOUSEWHEELPRESENT = 75,
- SM_XVIRTUALSCREEN = 76,
- SM_YVIRTUALSCREEN = 77,
- SM_CXVIRTUALSCREEN = 78,
- SM_CYVIRTUALSCREEN = 79,
- SM_CMONITORS = 80,
- SM_SAMEDISPLAYFORMAT = 81,
- SM_CMETRICS = 83,
-
- /* SetGraphicsMode(hdc, iMode ) */
- GM_COMPATIBLE = 1,
- GM_ADVANCED = 2,
- MWT_IDENTITY = 1,
-
- /* FONT WEIGHT (BOLD) VALUES */
- FW_DONTCARE = 0,
- FW_NORMAL = 400,
- FW_BOLD = 700,
- // some others...
-
- /* FONT CHARACTER SET */
- ANSI_CHARSET = 0,
- DEFAULT_CHARSET = 1,
- // plus others ....
-
- /* Font OutPrecision */
- OUT_DEFAULT_PRECIS = 0,
- OUT_TT_PRECIS = 4,
- OUT_TT_ONLY_PRECIS = 7,
- // some others...
-
- /* Font clip precision */
- CLIP_DEFAULT_PRECIS = 0,
- // some others...
-
- /* Font Quality */
- DEFAULT_QUALITY = 0,
-
- /* Mapping Modes */
- MM_TEXT = 1,
- // some others...
-
- /* Object Definitions for GetCurrentObject() and others. */
- OBJ_FONT = 6,
- // some others...
-
-
- /* Text Aligment */
- // TA_NOUPDATECP = 0,
- // TA_LEFT = 0,
- // TA_TOP = 0,
- TA_DEFAULT = 0,
-
- FORMAT_MESSAGE_ALLOCATE_BUFFER = 0x00000100,
- FORMAT_MESSAGE_IGNORE_INSERTS = 0x00000200,
- FORMAT_MESSAGE_FROM_SYSTEM = 0x00001000,
- FORMAT_MESSAGE_DEFAULT = FORMAT_MESSAGE_IGNORE_INSERTS | FORMAT_MESSAGE_FROM_SYSTEM;
- // some others...
-
+ DEFAULT_CHARSET = 1;
public const int NOMIRRORBITMAP = unchecked((int)0x80000000); /* Do not Mirror the bitmap in this call */
[DllImport(ExternDll.Gdi32, SetLastError = true, ExactSpelling = true, EntryPoint = "CreateCompatibleBitmap", CharSet = CharSet.Auto)]
public static extern IntPtr IntCreateCompatibleBitmap(HandleRef hDC, int width, int height);
- public static IntPtr CreateCompatibleBitmap(HandleRef hDC, int width, int height)
- {
- return System.Internal.HandleCollector.Add(IntCreateCompatibleBitmap(hDC, width, height), SafeNativeMethods.CommonHandles.GDI);
- }
-
-
- [DllImport(ExternDll.Gdi32, SetLastError = true, ExactSpelling = true, EntryPoint = "CreateBitmap", CharSet = CharSet.Auto)]
- [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Security", "CA2118:ReviewSuppressUnmanagedCodeSecurityUsage")]
- public static extern IntPtr IntCreateBitmap(int width, int height, int planes, int bpp, IntPtr bitmapData);
- public static IntPtr CreateBitmap(int width, int height, int planes, int bpp, IntPtr bitmapData)
+ public static IntPtr CreateCompatibleBitmap(HandleRef hDC, int width, int height)
{
- return System.Internal.HandleCollector.Add(IntCreateBitmap(width, height, planes, bpp, bitmapData), SafeNativeMethods.CommonHandles.GDI);
+ return System.Internal.HandleCollector.Add(IntCreateCompatibleBitmap(hDC, width, height), CommonHandles.GDI);
}
- [DllImport(ExternDll.Gdi32, SetLastError = true, ExactSpelling = true, CharSet = System.Runtime.InteropServices.CharSet.Auto)]
+ [DllImport(ExternDll.Gdi32, SetLastError = true, ExactSpelling = true, CharSet = CharSet.Auto)]
public static extern int BitBlt(HandleRef hDC, int x, int y, int nWidth, int nHeight,
HandleRef hSrcDC, int xSrc, int ySrc, int dwRop);
@@ -3415,64 +2967,74 @@ namespace System.Drawing
[DllImport(ExternDll.Gdi32, SetLastError = true, ExactSpelling = true, EntryPoint = "CreateDIBSection", CharSet = CharSet.Auto)]
public static extern IntPtr IntCreateDIBSection(HandleRef hdc, ref NativeMethods.BITMAPINFO_FLAT bmi, int iUsage, ref IntPtr ppvBits, IntPtr hSection, int dwOffset);
+
public static IntPtr CreateDIBSection(HandleRef hdc, ref NativeMethods.BITMAPINFO_FLAT bmi, int iUsage, ref IntPtr ppvBits, IntPtr hSection, int dwOffset)
{
return System.Internal.HandleCollector.Add(IntCreateDIBSection(hdc, ref bmi, iUsage, ref ppvBits, hSection, dwOffset), SafeNativeMethods.CommonHandles.GDI);
}
- [DllImport(ExternDll.Kernel32, SetLastError = true, ExactSpelling = true, CharSet = System.Runtime.InteropServices.CharSet.Auto)]
+ [DllImport(ExternDll.Kernel32, SetLastError = true, ExactSpelling = true, CharSet = CharSet.Auto)]
public static extern IntPtr GlobalFree(HandleRef handle);
- [DllImport(ExternDll.Gdi32, SetLastError = true, CharSet = System.Runtime.InteropServices.CharSet.Auto)]
+
+ [DllImport(ExternDll.Gdi32, SetLastError = true, CharSet = CharSet.Auto)]
public static extern int StartDoc(HandleRef hDC, DOCINFO lpDocInfo);
- [DllImport(ExternDll.Gdi32, SetLastError = true, ExactSpelling = true, CharSet = System.Runtime.InteropServices.CharSet.Auto)]
+
+ [DllImport(ExternDll.Gdi32, SetLastError = true, ExactSpelling = true, CharSet = CharSet.Auto)]
public static extern int StartPage(HandleRef hDC);
- [DllImport(ExternDll.Gdi32, SetLastError = true, ExactSpelling = true, CharSet = System.Runtime.InteropServices.CharSet.Auto)]
+
+ [DllImport(ExternDll.Gdi32, SetLastError = true, ExactSpelling = true, CharSet = CharSet.Auto)]
public static extern int EndPage(HandleRef hDC);
- // public static extern int SetAbortProc(m_hDC, (ABORTPROC)lpfn);
- [DllImport(ExternDll.Gdi32, SetLastError = true, ExactSpelling = true, CharSet = System.Runtime.InteropServices.CharSet.Auto)]
+
+ [DllImport(ExternDll.Gdi32, SetLastError = true, ExactSpelling = true, CharSet = CharSet.Auto)]
public static extern int AbortDoc(HandleRef hDC);
- [DllImport(ExternDll.Gdi32, SetLastError = true, ExactSpelling = true, CharSet = System.Runtime.InteropServices.CharSet.Auto)]
+
+ [DllImport(ExternDll.Gdi32, SetLastError = true, ExactSpelling = true, CharSet = CharSet.Auto)]
public static extern int EndDoc(HandleRef hDC);
- [DllImport(ExternDll.Comdlg32, SetLastError = true, CharSet = System.Runtime.InteropServices.CharSet.Auto)]
+ [DllImport(ExternDll.Comdlg32, SetLastError = true, CharSet = CharSet.Auto)]
public static extern bool PrintDlg([In, Out] PRINTDLG lppd);
- [DllImport(ExternDll.Comdlg32, SetLastError = true, CharSet = System.Runtime.InteropServices.CharSet.Auto)]
+ [DllImport(ExternDll.Comdlg32, SetLastError = true, CharSet = CharSet.Auto)]
public static extern bool PrintDlg([In, Out] PRINTDLGX86 lppd);
- [DllImport(ExternDll.Winspool, SetLastError = true, CharSet = System.Runtime.InteropServices.CharSet.Auto)]
+ [DllImport(ExternDll.Winspool, SetLastError = true, CharSet = CharSet.Auto)]
public static extern int DeviceCapabilities(string pDevice, string pPort, short fwCapabilities, IntPtr pOutput, IntPtr /*DEVMODE*/ pDevMode);
- [DllImport(ExternDll.Winspool, SetLastError = true, CharSet = System.Runtime.InteropServices.CharSet.Auto, BestFitMapping = false)]
+ [DllImport(ExternDll.Winspool, SetLastError = true, CharSet = CharSet.Auto, BestFitMapping = false)]
public static extern int DocumentProperties(HandleRef hwnd, HandleRef hPrinter, string pDeviceName, IntPtr /*DEVMODE*/ pDevModeOutput, HandleRef /*DEVMODE*/ pDevModeInput, int fMode);
- [DllImport(ExternDll.Winspool, SetLastError = true, CharSet = System.Runtime.InteropServices.CharSet.Auto, BestFitMapping = false)]
+ [DllImport(ExternDll.Winspool, SetLastError = true, CharSet = CharSet.Auto, BestFitMapping = false)]
public static extern int DocumentProperties(HandleRef hwnd, HandleRef hPrinter, string pDeviceName, IntPtr /*DEVMODE*/ pDevModeOutput, IntPtr /*DEVMODE*/ pDevModeInput, int fMode);
- [DllImport(ExternDll.Winspool, SetLastError = true, CharSet = System.Runtime.InteropServices.CharSet.Auto)]
+ [DllImport(ExternDll.Winspool, SetLastError = true, CharSet = CharSet.Auto)]
public static extern int EnumPrinters(int flags, string name, int level, IntPtr pPrinterEnum/*buffer*/,
int cbBuf, out int pcbNeeded, out int pcReturned);
- [DllImport(ExternDll.Kernel32, SetLastError = true, ExactSpelling = true, CharSet = System.Runtime.InteropServices.CharSet.Auto)]
+ [DllImport(ExternDll.Kernel32, SetLastError = true, ExactSpelling = true, CharSet = CharSet.Auto)]
public static extern IntPtr GlobalLock(HandleRef handle);
- [DllImport(ExternDll.Gdi32, SetLastError = true, CharSet = System.Runtime.InteropServices.CharSet.Auto)]
+
+ [DllImport(ExternDll.Gdi32, SetLastError = true, CharSet = CharSet.Auto)]
public static extern IntPtr /*HDC*/ ResetDC(HandleRef hDC, HandleRef /*DEVMODE*/ lpDevMode);
- [DllImport(ExternDll.Kernel32, SetLastError = true, ExactSpelling = true, CharSet = System.Runtime.InteropServices.CharSet.Auto)]
+
+ [DllImport(ExternDll.Kernel32, SetLastError = true, ExactSpelling = true, CharSet = CharSet.Auto)]
public static extern bool GlobalUnlock(HandleRef handle);
- [DllImport(ExternDll.Gdi32, SetLastError = true, ExactSpelling = true, EntryPoint = "CreateRectRgn", CharSet = System.Runtime.InteropServices.CharSet.Auto)]
+ [DllImport(ExternDll.Gdi32, SetLastError = true, ExactSpelling = true, EntryPoint = "CreateRectRgn", CharSet = CharSet.Auto)]
private static extern IntPtr IntCreateRectRgn(int x1, int y1, int x2, int y2);
+
public static IntPtr CreateRectRgn(int x1, int y1, int x2, int y2)
{
return System.Internal.HandleCollector.Add(IntCreateRectRgn(x1, y1, x2, y2), SafeNativeMethods.CommonHandles.GDI);
}
- [DllImport(ExternDll.Gdi32, SetLastError = true, ExactSpelling = true, CharSet = System.Runtime.InteropServices.CharSet.Auto)]
+
+ [DllImport(ExternDll.Gdi32, SetLastError = true, ExactSpelling = true, CharSet = CharSet.Auto)]
public static extern int GetClipRgn(HandleRef hDC, HandleRef hRgn);
- [DllImport(ExternDll.Gdi32, SetLastError = true, ExactSpelling = true, CharSet = System.Runtime.InteropServices.CharSet.Auto)]
+
+ [DllImport(ExternDll.Gdi32, SetLastError = true, ExactSpelling = true, CharSet = CharSet.Auto)]
public static extern int SelectClipRgn(HandleRef hDC, HandleRef hRgn);
- [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Security", "CA2101:SpecifyMarshalingForPInvokeStringArguments")]
- [DllImport(ExternDll.Gdi32, SetLastError = true, CharSet = System.Runtime.InteropServices.CharSet.Auto)]
+ [SuppressMessage("Microsoft.Security", "CA2101:SpecifyMarshalingForPInvokeStringArguments")]
+ [DllImport(ExternDll.Gdi32, SetLastError = true, CharSet = CharSet.Auto)]
public static extern int AddFontResourceEx(string lpszFilename, int fl, IntPtr pdv);
public static int AddFontFile(string fileName)
@@ -3496,8 +3058,11 @@ namespace System.Drawing
finally
{
if (hTempRgn != IntPtr.Zero)
+ {
DeleteObject(new HandleRef(null, hTempRgn));
+ }
}
+
return hSaveRgn;
}
@@ -3510,24 +3075,31 @@ namespace System.Drawing
finally
{
if (hRgn != IntPtr.Zero)
+ {
DeleteObject(new HandleRef(null, hRgn));
+ }
}
}
- [DllImport(ExternDll.Gdi32, SetLastError = true, ExactSpelling = true, CharSet = System.Runtime.InteropServices.CharSet.Auto)]
+ [DllImport(ExternDll.Gdi32, SetLastError = true, ExactSpelling = true, CharSet = CharSet.Auto)]
public static extern int ExtEscape(HandleRef hDC, int nEscape, int cbInput, ref int inData, int cbOutput, [Out] out int outData);
- [DllImport(ExternDll.Gdi32, SetLastError = true, ExactSpelling = true, CharSet = System.Runtime.InteropServices.CharSet.Auto)]
+
+ [DllImport(ExternDll.Gdi32, SetLastError = true, ExactSpelling = true, CharSet = CharSet.Auto)]
public static extern int ExtEscape(HandleRef hDC, int nEscape, int cbInput, byte[] inData, int cbOutput, [Out] out int outData);
+
public const int QUERYESCSUPPORT = 8, CHECKJPEGFORMAT = 4119, CHECKPNGFORMAT = 4120;
- [DllImport(ExternDll.Gdi32, SetLastError = true, ExactSpelling = true, CharSet = System.Runtime.InteropServices.CharSet.Auto)]
+ [DllImport(ExternDll.Gdi32, SetLastError = true, ExactSpelling = true, CharSet = CharSet.Auto)]
public static extern int IntersectClipRect(HandleRef hDC, int x1, int y1, int x2, int y2);
- [DllImport(ExternDll.Kernel32, SetLastError = true, ExactSpelling = true, EntryPoint = "GlobalAlloc", CharSet = System.Runtime.InteropServices.CharSet.Auto)]
+
+ [DllImport(ExternDll.Kernel32, SetLastError = true, ExactSpelling = true, EntryPoint = "GlobalAlloc", CharSet = CharSet.Auto)]
public static extern IntPtr IntGlobalAlloc(int uFlags, UIntPtr dwBytes); // size should be 32/64bits compatible
+
public static IntPtr GlobalAlloc(int uFlags, uint dwBytes)
{
return IntGlobalAlloc(uFlags, new UIntPtr(dwBytes));
}
+
[DllImport(ExternDll.Kernel32)]
static internal extern void ZeroMemory(IntPtr destination, UIntPtr length);
@@ -3536,7 +3108,7 @@ namespace System.Drawing
public const int ERROR_PROC_NOT_FOUND = 127;
- [System.Runtime.InteropServices.StructLayout(LayoutKind.Sequential)]
+ [StructLayout(LayoutKind.Sequential)]
public class ENHMETAHEADER
{
/// The ENHMETAHEADER structure is defined natively as a union with WmfHeader.
@@ -3578,10 +3150,10 @@ namespace System.Drawing
[StructLayout(LayoutKind.Sequential, CharSet = CharSet.Auto)]
public class DOCINFO
{
- public int cbSize = 20; //ndirect.DllLib.sizeOf(this);
- public String lpszDocName;
- public String lpszOutput;
- public String lpszDatatype;
+ public int cbSize = 20;
+ public string lpszDocName;
+ public string lpszOutput;
+ public string lpszDatatype;
public int fwType;
}
@@ -3633,36 +3205,6 @@ namespace System.Drawing
public IntPtr hSetupTemplate;
}
-
-
- public enum StructFormat
- {
- Ansi = 1,
- Unicode = 2,
- Auto = 3,
- }
-
- [StructLayout(LayoutKind.Sequential)]
- public struct RECT
- {
- public int left;
- public int top;
- public int right;
- public int bottom;
- }
-
- [StructLayout(LayoutKind.Sequential)]
- public struct MSG
- {
- public IntPtr hwnd;
- public int message;
- public IntPtr wParam;
- public IntPtr lParam;
- public int time;
- // pt was a by-value POINT structure
- public int pt_x;
- public int pt_y;
- }
[StructLayout(LayoutKind.Sequential)]
public class ICONINFO
{
@@ -3672,6 +3214,7 @@ namespace System.Drawing
public IntPtr hbmMask = IntPtr.Zero;
public IntPtr hbmColor = IntPtr.Zero;
}
+
[StructLayout(LayoutKind.Sequential)]
public class BITMAP
{
@@ -3687,7 +3230,7 @@ namespace System.Drawing
[StructLayout(LayoutKind.Sequential)]
public class BITMAPINFOHEADER
{
- public int biSize = 40; // ndirect.DllLib.sizeOf( this );
+ public int biSize = 40;
public int biWidth;
public int biHeight;
public short biPlanes;
@@ -3700,7 +3243,6 @@ namespace System.Drawing
public int biClrImportant;
}
-
[StructLayout(LayoutKind.Sequential, CharSet = CharSet.Auto)]
public class LOGFONT
{
@@ -3717,33 +3259,9 @@ namespace System.Drawing
public byte lfClipPrecision;
public byte lfQuality;
public byte lfPitchAndFamily;
- [MarshalAs(System.Runtime.InteropServices.UnmanagedType.ByValTStr, SizeConst = 32)]
+ [MarshalAs(UnmanagedType.ByValTStr, SizeConst = 32)]
public string lfFaceName;
- public LOGFONT()
- {
- }
-
- public LOGFONT(LOGFONT lf)
- {
- Debug.Assert(lf != null, "lf is null");
-
- lfHeight = lf.lfHeight;
- lfWidth = lf.lfWidth;
- lfEscapement = lf.lfEscapement;
- lfOrientation = lf.lfOrientation;
- lfWeight = lf.lfWeight;
- lfItalic = lf.lfItalic;
- lfUnderline = lf.lfUnderline;
- lfStrikeOut = lf.lfStrikeOut;
- lfCharSet = lf.lfCharSet;
- lfOutPrecision = lf.lfOutPrecision;
- lfClipPrecision = lf.lfClipPrecision;
- lfQuality = lf.lfQuality;
- lfPitchAndFamily = lf.lfPitchAndFamily;
- lfFaceName = lf.lfFaceName;
- }
-
public override string ToString()
{
return
@@ -3764,56 +3282,6 @@ namespace System.Drawing
}
}
- [StructLayout(LayoutKind.Sequential, CharSet = CharSet.Unicode)]
- public struct TEXTMETRIC
- {
- public int tmHeight;
- public int tmAscent;
- public int tmDescent;
- public int tmInternalLeading;
- public int tmExternalLeading;
- public int tmAveCharWidth;
- public int tmMaxCharWidth;
- public int tmWeight;
- public int tmOverhang;
- public int tmDigitizedAspectX;
- public int tmDigitizedAspectY;
- public char tmFirstChar;
- public char tmLastChar;
- public char tmDefaultChar;
- public char tmBreakChar;
- public byte tmItalic;
- public byte tmUnderlined;
- public byte tmStruckOut;
- public byte tmPitchAndFamily;
- public byte tmCharSet;
- }
-
- [StructLayout(LayoutKind.Sequential, CharSet = CharSet.Ansi)]
- public struct TEXTMETRICA
- {
- public int tmHeight;
- public int tmAscent;
- public int tmDescent;
- public int tmInternalLeading;
- public int tmExternalLeading;
- public int tmAveCharWidth;
- public int tmMaxCharWidth;
- public int tmWeight;
- public int tmOverhang;
- public int tmDigitizedAspectX;
- public int tmDigitizedAspectY;
- public byte tmFirstChar;
- public byte tmLastChar;
- public byte tmDefaultChar;
- public byte tmBreakChar;
- public byte tmItalic;
- public byte tmUnderlined;
- public byte tmStruckOut;
- public byte tmPitchAndFamily;
- public byte tmCharSet;
- }
-
[StructLayout(LayoutKind.Sequential, Pack = 2)]
public struct ICONDIR
{
@@ -3838,21 +3306,9 @@ namespace System.Drawing
public class Ole
{
- /*
- * Pictypes
- */
- public const int PICTYPE_UNINITIALIZED = -1;
- public const int PICTYPE_NONE = 0;
- public const int PICTYPE_BITMAP = 1;
- public const int PICTYPE_METAFILE = 2;
public const int PICTYPE_ICON = 3;
- public const int PICTYPE_ENHMETAFILE = 4;
-
- public const int STATFLAG_DEFAULT = 0;
- public const int STATFLAG_NONAME = 1;
}
-
[StructLayout(LayoutKind.Sequential)]
public class PICTDESC
{
@@ -3864,23 +3320,19 @@ namespace System.Drawing
public static PICTDESC CreateIconPICTDESC(IntPtr hicon)
{
- PICTDESC pictdesc = new PICTDESC();
- pictdesc.cbSizeOfStruct = 12;
- pictdesc.picType = Ole.PICTYPE_ICON;
- pictdesc.union1 = hicon;
- return pictdesc;
- }
-
- public virtual IntPtr GetHandle()
- {
- return union1;
+ return new PICTDESC()
+ {
+ cbSizeOfStruct = 12,
+ picType = Ole.PICTYPE_ICON,
+ union1 = hicon
+ };
}
}
[StructLayout(LayoutKind.Sequential, CharSet = CharSet.Auto)]
public class DEVMODE
{
- [MarshalAs(System.Runtime.InteropServices.UnmanagedType.ByValTStr, SizeConst = 32)]
+ [MarshalAs(UnmanagedType.ByValTStr, SizeConst = 32)]
public string dmDeviceName;
public short dmSpecVersion;
public short dmDriverVersion;
@@ -3900,7 +3352,7 @@ namespace System.Drawing
public short dmYResolution;
public short dmTTOption;
public short dmCollate;
- [MarshalAs(System.Runtime.InteropServices.UnmanagedType.ByValTStr, SizeConst = 32)]
+ [MarshalAs(UnmanagedType.ByValTStr, SizeConst = 32)]
public string dmFormName;
public short dmLogPixels;
public int dmBitsPerPel;
@@ -3965,32 +3417,12 @@ namespace System.Drawing
{
#if DEBUG
// Setup the DebugHandleTracker
- System.Internal.DebugHandleTracker.Initialize();
+ DebugHandleTracker.Initialize();
AppDomain.CurrentDomain.DomainUnload += new EventHandler(CurrentDomain_DomainUnload);
AppDomain.CurrentDomain.ProcessExit += new EventHandler(CurrentDomain_ProcessExit);
#endif
}
-
- /// <summary>
- /// Handle type for accelerator tables.
- /// </summary>
- public static readonly int Accelerator = System.Internal.HandleCollector.RegisterType("Accelerator", 80, 50);
-
- /// <summary>
- /// Handle type for cursors.
- /// </summary>
- public static readonly int Cursor = System.Internal.HandleCollector.RegisterType("Cursor", 20, 500);
-
- /// <summary>
- /// Handle type for enhanced metafiles.
- /// </summary>
- public static readonly int EMF = System.Internal.HandleCollector.RegisterType("EnhancedMetaFile", 20, 500);
-
- /// <summary>
- /// Handle type for file find handles.
- /// </summary>
- public static readonly int Find = System.Internal.HandleCollector.RegisterType("Find", 0, 1000);
-
+
/// <summary>
/// Handle type for GDI objects.
/// </summary>
@@ -4012,52 +3444,32 @@ namespace System.Drawing
/// </summary>
public static readonly int Kernel = System.Internal.HandleCollector.RegisterType("Kernel", 0, 1000);
- /// <summary>
- /// Handle type for files.
- /// </summary>
- public static readonly int Menu = System.Internal.HandleCollector.RegisterType("Menu", 30, 1000);
-
- /// <summary>
- /// Handle type for windows.
- /// </summary>
- public static readonly int Window = System.Internal.HandleCollector.RegisterType("Window", 5, 1000);
-
#if DEBUG
private static void CurrentDomain_DomainUnload(object sender, EventArgs e)
{
- System.Internal.DebugHandleTracker.CheckLeaks();
+ DebugHandleTracker.CheckLeaks();
}
private static void CurrentDomain_ProcessExit(object sender, EventArgs e)
{
- System.Internal.DebugHandleTracker.CheckLeaks();
+ DebugHandleTracker.CheckLeaks();
}
#endif
}
-
public class StreamConsts
{
- public const int LOCK_WRITE = 0x1;
- public const int LOCK_EXCLUSIVE = 0x2;
- public const int LOCK_ONLYONCE = 0x4;
- public const int STATFLAG_DEFAULT = 0x0;
- public const int STATFLAG_NONAME = 0x1;
- public const int STATFLAG_NOOPEN = 0x2;
- public const int STGC_DEFAULT = 0x0;
- public const int STGC_OVERWRITE = 0x1;
- public const int STGC_ONLYIFCURRENT = 0x2;
- public const int STGC_DANGEROUSLYCOMMITMERELYTODISKCACHE = 0x4;
public const int STREAM_SEEK_SET = 0x0;
public const int STREAM_SEEK_CUR = 0x1;
public const int STREAM_SEEK_END = 0x2;
}
- [DllImport(ExternDll.Gdi32, SetLastError = true, ExactSpelling = true, EntryPoint = "DeleteObject", CharSet = System.Runtime.InteropServices.CharSet.Auto)]
+ [DllImport(ExternDll.Gdi32, SetLastError = true, ExactSpelling = true, EntryPoint = "DeleteObject", CharSet = CharSet.Auto)]
internal static extern int IntDeleteObject(HandleRef hObject);
+
public static int DeleteObject(HandleRef hObject)
{
- System.Internal.HandleCollector.Remove((IntPtr)hObject, SafeNativeMethods.CommonHandles.GDI);
+ System.Internal.HandleCollector.Remove((IntPtr)hObject, CommonHandles.GDI);
return IntDeleteObject(hObject);
}
@@ -4072,71 +3484,66 @@ namespace System.Drawing
return System.Internal.HandleCollector.Add(IntCreateIconFromResourceEx(pbIconBits, cbIconBits, fIcon, dwVersion, csDesired, cyDesired, flags), SafeNativeMethods.CommonHandles.Icon);
}
- [DllImport(ExternDll.Shell32, CharSet = System.Runtime.InteropServices.CharSet.Auto, BestFitMapping = false, EntryPoint = "ExtractAssociatedIcon")]
+ [DllImport(ExternDll.Shell32, CharSet = CharSet.Auto, BestFitMapping = false, EntryPoint = "ExtractAssociatedIcon")]
public unsafe static extern IntPtr IntExtractAssociatedIcon(HandleRef hInst, StringBuilder iconPath, ref int index);
public unsafe static IntPtr ExtractAssociatedIcon(HandleRef hInst, StringBuilder iconPath, ref int index)
{
- return System.Internal.HandleCollector.Add(IntExtractAssociatedIcon(hInst, iconPath, ref index), SafeNativeMethods.CommonHandles.Icon);
+ return System.Internal.HandleCollector.Add(IntExtractAssociatedIcon(hInst, iconPath, ref index), CommonHandles.Icon);
}
- [DllImport(ExternDll.User32, SetLastError = true, EntryPoint = "LoadIcon", CharSet = System.Runtime.InteropServices.CharSet.Auto)]
+ [DllImport(ExternDll.User32, SetLastError = true, EntryPoint = "LoadIcon", CharSet = CharSet.Auto)]
private static extern IntPtr IntLoadIcon(HandleRef hInst, IntPtr iconId);
- public static IntPtr LoadIcon(HandleRef hInst, int iconId)
- { // we only use the case were the low word of the IntPtr is used a resource id but it still has to be an intptr
- return IntLoadIcon(hInst, new IntPtr(iconId)); // on 32bits it'll be the same size, wider on 64bits
- }
- [DllImport(ExternDll.Comctl32, SetLastError = true, EntryPoint = "LoadIconWithScaleDown", CharSet = System.Runtime.InteropServices.CharSet.Auto)]
- private static extern int IntLoadIconWithScaleDown(HandleRef hInst, IntPtr iconId, int cx, int cy, ref IntPtr phico);
- public static int LoadIconWithScaleDown(HandleRef hInst, int iconId, int cx, int cy, ref IntPtr phico)
- { // we only use the case were the low word of the IntPtr is used a resource id but it still has to be an intptr
- return IntLoadIconWithScaleDown(hInst, new IntPtr(iconId), cx, cy, ref phico); // on 32bits it'll be the same size, wider on 64bits
+ public static IntPtr LoadIcon(HandleRef hInst, int iconId)
+ {
+ // We only use the case were the low word of the IntPtr is used a resource id but it still has to be an intptr.
+ return IntLoadIcon(hInst, new IntPtr(iconId));
}
- [DllImport(ExternDll.User32, SetLastError = true, ExactSpelling = true, EntryPoint = "DestroyIcon", CharSet = System.Runtime.InteropServices.CharSet.Auto)]
+ [DllImport(ExternDll.User32, SetLastError = true, ExactSpelling = true, EntryPoint = "DestroyIcon", CharSet = CharSet.Auto)]
private static extern bool IntDestroyIcon(HandleRef hIcon);
+
public static bool DestroyIcon(HandleRef hIcon)
{
System.Internal.HandleCollector.Remove((IntPtr)hIcon, SafeNativeMethods.CommonHandles.Icon);
return IntDestroyIcon(hIcon);
}
- [DllImport(ExternDll.User32, SetLastError = true, ExactSpelling = true, EntryPoint = "CopyImage", CharSet = System.Runtime.InteropServices.CharSet.Auto)]
+ [DllImport(ExternDll.User32, SetLastError = true, ExactSpelling = true, EntryPoint = "CopyImage", CharSet = CharSet.Auto)]
private static extern IntPtr IntCopyImage(HandleRef hImage, int uType, int cxDesired, int cyDesired, int fuFlags);
+
public static IntPtr CopyImage(HandleRef hImage, int uType, int cxDesired, int cyDesired, int fuFlags)
{
int handleType;
switch (uType)
{
- case SafeNativeMethods.IMAGE_ICON:
- handleType = SafeNativeMethods.CommonHandles.Icon;
+ case IMAGE_ICON:
+ handleType = CommonHandles.Icon;
break;
default:
- handleType = SafeNativeMethods.CommonHandles.GDI;
+ handleType = CommonHandles.GDI;
break;
}
return System.Internal.HandleCollector.Add(IntCopyImage(hImage, uType, cxDesired, cyDesired, fuFlags), handleType);
}
// GetObject stuff
- [DllImport(ExternDll.Gdi32, SetLastError = true, CharSet = System.Runtime.InteropServices.CharSet.Auto)]
- public static extern int GetObject(HandleRef hObject, int nSize, [In, Out] SafeNativeMethods.BITMAP bm);
+ [DllImport(ExternDll.Gdi32, SetLastError = true, CharSet = CharSet.Auto)]
+ public static extern int GetObject(HandleRef hObject, int nSize, [In, Out] BITMAP bm);
+
+ [DllImport(ExternDll.Gdi32, SetLastError = true, CharSet = CharSet.Auto)]
+ public static extern int GetObject(HandleRef hObject, int nSize, [In, Out] LOGFONT lf);
- [DllImport(ExternDll.Gdi32, SetLastError = true, CharSet = System.Runtime.InteropServices.CharSet.Auto)]
- public static extern int GetObject(HandleRef hObject, int nSize, [In, Out] SafeNativeMethods.LOGFONT lf);
- public static int GetObject(HandleRef hObject, SafeNativeMethods.LOGFONT lp)
+ public static int GetObject(HandleRef hObject, LOGFONT lp)
{
- return GetObject(hObject, System.Runtime.InteropServices.Marshal.SizeOf(typeof(SafeNativeMethods.LOGFONT)), lp);
+ return GetObject(hObject, Marshal.SizeOf(typeof(LOGFONT)), lp);
}
- [DllImport(ExternDll.User32, SetLastError = true, ExactSpelling = true, CharSet = System.Runtime.InteropServices.CharSet.Auto)]
- public static extern bool GetIconInfo(HandleRef hIcon, [In, Out] SafeNativeMethods.ICONINFO info);
+ [DllImport(ExternDll.User32, SetLastError = true, ExactSpelling = true, CharSet = CharSet.Auto)]
+ public static extern bool GetIconInfo(HandleRef hIcon, [In, Out] ICONINFO info);
- [DllImport(ExternDll.User32, SetLastError = true, CharSet = System.Runtime.InteropServices.CharSet.Auto)]
- public static extern int GetSysColor(int nIndex);
-
- [DllImport(ExternDll.User32, SetLastError = true, ExactSpelling = true, CharSet = System.Runtime.InteropServices.CharSet.Auto)]
+ [DllImport(ExternDll.User32, SetLastError = true, ExactSpelling = true, CharSet = CharSet.Auto)]
public static extern bool DrawIconEx(HandleRef hDC, int x, int y, HandleRef hIcon, int width, int height, int iStepIfAniCursor, HandleRef hBrushFlickerFree, int diFlags);
#if CUSTOM_MARSHALING_ISTREAM
@@ -4150,147 +3557,62 @@ namespace System.Drawing
[DllImport(ExternDll.Oleaut32, PreserveSig = false)]
public static extern IPicture OleCreatePictureIndirect(SafeNativeMethods.PICTDESC pictdesc, [In]ref Guid refiid, bool fOwn);
- [
- ComImport(),
- Guid("7BF80980-BF32-101A-8BBB-00AA00300CAB"),
- InterfaceType(ComInterfaceType.InterfaceIsIUnknown),
-
- ]
+ [ComImport()]
+ [Guid("7BF80980-BF32-101A-8BBB-00AA00300CAB")]
+ [InterfaceType(ComInterfaceType.InterfaceIsIUnknown)]
public interface IPicture
{
- [SuppressUnmanagedCodeSecurity()]
+ [SuppressUnmanagedCodeSecurity]
IntPtr GetHandle();
- [SuppressUnmanagedCodeSecurity()]
+ [SuppressUnmanagedCodeSecurity]
IntPtr GetHPal();
[return: MarshalAs(UnmanagedType.I2)]
- [SuppressUnmanagedCodeSecurity()]
+ [SuppressUnmanagedCodeSecurity]
short GetPictureType();
- [SuppressUnmanagedCodeSecurity()]
+ [SuppressUnmanagedCodeSecurity]
int GetWidth();
- [SuppressUnmanagedCodeSecurity()]
+ [SuppressUnmanagedCodeSecurity]
int GetHeight();
- [SuppressUnmanagedCodeSecurity()]
+ [SuppressUnmanagedCodeSecurity]
void Render();
- [SuppressUnmanagedCodeSecurity()]
- void SetHPal(
- [In]
- IntPtr phpal);
+ [SuppressUnmanagedCodeSecurity]
+ void SetHPal([In] IntPtr phpal);
- [SuppressUnmanagedCodeSecurity()]
+ [SuppressUnmanagedCodeSecurity]
IntPtr GetCurDC();
- [SuppressUnmanagedCodeSecurity()]
- void SelectPicture(
- [In]
- IntPtr hdcIn,
- [Out, MarshalAs(UnmanagedType.LPArray)]
- int[] phdcOut,
- [Out, MarshalAs(UnmanagedType.LPArray)]
- int[] phbmpOut);
+ [SuppressUnmanagedCodeSecurity]
+ void SelectPicture([In] IntPtr hdcIn,
+ [Out, MarshalAs(UnmanagedType.LPArray)] int[] phdcOut,
+ [Out, MarshalAs(UnmanagedType.LPArray)] int[] phbmpOut);
[return: MarshalAs(UnmanagedType.Bool)]
- [SuppressUnmanagedCodeSecurity()]
+ [SuppressUnmanagedCodeSecurity]
bool GetKeepOriginalFormat();
- [SuppressUnmanagedCodeSecurity()]
- void SetKeepOriginalFormat(
- [In, MarshalAs(UnmanagedType.Bool)]
- bool pfkeep);
+ [SuppressUnmanagedCodeSecurity]
+ void SetKeepOriginalFormat([In, MarshalAs(UnmanagedType.Bool)] bool pfkeep);
- [SuppressUnmanagedCodeSecurity()]
+ [SuppressUnmanagedCodeSecurity]
void PictureChanged();
- [SuppressUnmanagedCodeSecurity()]
- [System.Runtime.InteropServices.PreserveSig]
- int SaveAsFile(
- [In, MarshalAs(UnmanagedType.Interface)]
- UnsafeNativeMethods.IStream pstm,
- [In]
- int fSaveMemCopy,
- [Out]
- out int pcbSize);
-
- [SuppressUnmanagedCodeSecurity()]
- int GetAttributes();
-
- [SuppressUnmanagedCodeSecurity()]
- void SetHdc(
- [In]
- IntPtr hdc);
- }
-
+ [SuppressUnmanagedCodeSecurity]
+ [PreserveSig]
+ int SaveAsFile([In, MarshalAs(UnmanagedType.Interface)] UnsafeNativeMethods.IStream pstm,
+ [In] int fSaveMemCopy,
+ [Out] out int pcbSize);
- // for pulling encoded IPictures out of Access Databases
- //
- [StructLayout(LayoutKind.Sequential)]
- public struct OBJECTHEADER
- {
- public short signature; // this looks like it's always 0x1c15
- public short headersize; // how big all this goo ends up being. after this is the actual object data.
- public short objectType; // we don't care about anything else...they don't seem to be meaningful anyway.
- public short nameLen;
- public short classLen;
- public short nameOffset;
- public short classOffset;
- public short width;
- public short height;
- public IntPtr pInfo;
- }
-
-
- //values used in our known colortable
- internal enum Win32SystemColors
- {
- ActiveBorder = 0x0A,
- ActiveCaption = 0x02,
- ActiveCaptionText = 0x09,
- AppWorkspace = 0x0C,
- ButtonFace = 0x0F,
- ButtonHighlight = 0x14,
- ButtonShadow = 0x10,
- Control = 0x0F,
- ControlDark = 0x10,
- ControlDarkDark = 0x15,
- ControlLight = 0x16,
- ControlLightLight = 0x14,
- ControlText = 0x12,
- Desktop = 0x01,
- GradientActiveCaption = 0x1B,
- GradientInactiveCaption = 0x1C,
- GrayText = 0x11,
- Highlight = 0x0D,
- HighlightText = 0x0E,
- HotTrack = 0x1A,
- InactiveBorder = 0x0B,
- InactiveCaption = 0x03,
- InactiveCaptionText = 0x13,
- Info = 0x18,
- InfoText = 0x17,
- Menu = 0x04,
- MenuBar = 0x1E,
- MenuHighlight = 0x1D,
- MenuText = 0x07,
- ScrollBar = 0x00,
- Window = 0x05,
- WindowFrame = 0x06,
- WindowText = 0x08
- }
-
-
- // GDI stuff
+ [SuppressUnmanagedCodeSecurity]
+ int GetAttributes();
- // see wingdi.h
- public enum BackgroundMode : int
- {
- TRANSPARENT = 1,
- OPAQUE = 2
+ [SuppressUnmanagedCodeSecurity]
+ void SetHdc([In] IntPtr hdc);
}
}
}
-
diff --git a/src/System.Drawing.Common/src/System/Drawing/Graphics.cs b/src/System.Drawing.Common/src/System/Drawing/Graphics.cs
index 39132ce635..f023e12817 100644
--- a/src/System.Drawing.Common/src/System/Drawing/Graphics.cs
+++ b/src/System.Drawing.Common/src/System/Drawing/Graphics.cs
@@ -4,6 +4,7 @@
using System.ComponentModel;
using System.Diagnostics;
+using System.Diagnostics.CodeAnalysis;
using System.Diagnostics.Contracts;
using System.Drawing.Drawing2D;
using System.Drawing.Imaging;
@@ -44,7 +45,7 @@ namespace System.Drawing
private static readonly object s_syncObject = new object();
/// <summary>
- /// Handle to native GDI+ graphics object. This object is created on demand.
+ /// Handle to native GDI+ graphics object. This object is created on demand.
/// </summary>
private IntPtr _nativeGraphics;
@@ -64,12 +65,9 @@ namespace System.Drawing
// pointer back to the Image backing a specific graphic object
private Image _backingImage;
- /// <include file='doc\Graphics.uex' path='docs/doc[@for="Graphics.DrawImageAbort"]/*' />
- /// <summary>
- /// </summary>
public delegate bool DrawImageAbort(IntPtr callbackdata);
- // Callback for EnumerateMetafile methods. The parameters are:
+ // Callback for EnumerateMetafile methods. The parameters are:
// recordType (if >= MinRecordType, it's an EMF+ record)
// flags (always 0 for EMF records)
@@ -78,9 +76,8 @@ namespace System.Drawing
// callbackData pointer to callbackData, if any
// This method can then call Metafile.PlayRecord to play the
- // record that was just enumerated. If this method returns
- // FALSE, the enumeration process is aborted. Otherwise, it continues.
-
+ // record that was just enumerated. If this method returns
+ // FALSE, the enumeration process is aborted. Otherwise, it continues.
public delegate bool EnumerateMetafileProc(EmfPlusRecordType recordType,
int flags,
int dataSize,
@@ -299,7 +296,7 @@ namespace System.Drawing
}
set
{
- if (!ClientUtils.IsEnumValid(value, unchecked((int)value), (int)CompositingMode.SourceOver, (int)CompositingMode.SourceCopy))
+ if (value < CompositingMode.SourceOver || value > CompositingMode.SourceCopy)
{
throw new InvalidEnumArgumentException(nameof(value), unchecked((int)value), typeof(CompositingMode));
}
@@ -338,7 +335,7 @@ namespace System.Drawing
}
set
{
- if (!ClientUtils.IsEnumValid(value, unchecked((int)value), unchecked((int)CompositingQuality.Invalid), unchecked((int)CompositingQuality.AssumeLinear)))
+ if (value < CompositingQuality.Invalid || value > CompositingQuality.AssumeLinear)
{
throw new InvalidEnumArgumentException(nameof(value), unchecked((int)value), typeof(CompositingQuality));
}
@@ -364,7 +361,7 @@ namespace System.Drawing
}
set
{
- if (!ClientUtils.IsEnumValid(value, unchecked((int)value), (int)TextRenderingHint.SystemDefault, unchecked((int)TextRenderingHint.ClearTypeGridFit)))
+ if (value < TextRenderingHint.SystemDefault || value > TextRenderingHint.ClearTypeGridFit)
{
throw new InvalidEnumArgumentException(nameof(value), unchecked((int)value), typeof(TextRenderingHint));
}
@@ -403,7 +400,7 @@ namespace System.Drawing
}
set
{
- if (!ClientUtils.IsEnumValid(value, unchecked((int)value), unchecked((int)SmoothingMode.Invalid), unchecked((int)SmoothingMode.AntiAlias)))
+ if (value < SmoothingMode.Invalid || value > SmoothingMode.AntiAlias)
{
throw new InvalidEnumArgumentException(nameof(value), unchecked((int)value), typeof(SmoothingMode));
}
@@ -425,7 +422,7 @@ namespace System.Drawing
}
set
{
- if (!ClientUtils.IsEnumValid(value, unchecked((int)value), unchecked((int)PixelOffsetMode.Invalid), unchecked((int)PixelOffsetMode.Half)))
+ if (value < PixelOffsetMode.Invalid || value > PixelOffsetMode.Half)
{
throw new InvalidEnumArgumentException(nameof(value), unchecked((int)value), typeof(PixelOffsetMode));
}
@@ -464,7 +461,7 @@ namespace System.Drawing
}
set
{
- if (!ClientUtils.IsEnumValid(value, unchecked((int)value), unchecked((int)InterpolationMode.Invalid), unchecked((int)InterpolationMode.HighQualityBicubic)))
+ if (value < InterpolationMode.Invalid || value > InterpolationMode.HighQualityBicubic)
{
throw new InvalidEnumArgumentException(nameof(value), unchecked((int)value), typeof(InterpolationMode));
}
@@ -508,7 +505,7 @@ namespace System.Drawing
}
set
{
- if (!ClientUtils.IsEnumValid(value, unchecked((int)value), (int)GraphicsUnit.World, (int)GraphicsUnit.Millimeter))
+ if (value < GraphicsUnit.World || value > GraphicsUnit.Millimeter)
{
throw new InvalidEnumArgumentException(nameof(value), unchecked((int)value), typeof(GraphicsUnit));
}
@@ -612,16 +609,19 @@ namespace System.Drawing
case CopyPixelOperation.NoMirrorBitmap:
break;
default:
- throw new InvalidEnumArgumentException("value", unchecked((int)copyPixelOperation), typeof(CopyPixelOperation));
+ throw new InvalidEnumArgumentException(nameof(copyPixelOperation), unchecked((int)copyPixelOperation), typeof(CopyPixelOperation));
}
int destWidth = blockRegionSize.Width;
int destHeight = blockRegionSize.Height;
using (DeviceContext dc = DeviceContext.FromHwnd(IntPtr.Zero))
- { // screen DC
+ {
+ // The DC of the screen.
HandleRef screenDC = new HandleRef(null, dc.Hdc);
- HandleRef targetDC = new HandleRef(null, GetHdc()); // this DC
+
+ // The DC of the current graphics object.
+ HandleRef targetDC = new HandleRef(null, GetHdc());
try
{
@@ -647,20 +647,13 @@ namespace System.Drawing
public void ResetTransform()
{
int status = SafeNativeMethods.Gdip.GdipResetWorldTransform(new HandleRef(this, NativeGraphics));
-
- if (status != SafeNativeMethods.Gdip.Ok)
- {
- throw SafeNativeMethods.Gdip.StatusException(status);
- }
+ SafeNativeMethods.Gdip.CheckStatus(status);
}
/// <summary>
/// Multiplies the <see cref='Matrix'/> that represents the world transform and <paramref name="matrix"/>.
/// </summary>
- public void MultiplyTransform(Matrix matrix)
- {
- MultiplyTransform(matrix, MatrixOrder.Prepend);
- }
+ public void MultiplyTransform(Matrix matrix) => MultiplyTransform(matrix, MatrixOrder.Prepend);
/// <summary>
/// Multiplies the <see cref='Matrix'/> that represents the world transform and <paramref name="matrix"/>.
@@ -669,86 +662,55 @@ namespace System.Drawing
{
if (matrix == null)
{
- throw new ArgumentNullException("matrix");
+ throw new ArgumentNullException(nameof(matrix));
}
int status = SafeNativeMethods.Gdip.GdipMultiplyWorldTransform(new HandleRef(this, NativeGraphics),
new HandleRef(matrix, matrix.nativeMatrix),
order);
- if (status != SafeNativeMethods.Gdip.Ok)
- {
- throw SafeNativeMethods.Gdip.StatusException(status);
- }
+ SafeNativeMethods.Gdip.CheckStatus(status);
}
- public void TranslateTransform(float dx, float dy)
- {
- TranslateTransform(dx, dy, MatrixOrder.Prepend);
- }
+ public void TranslateTransform(float dx, float dy) => TranslateTransform(dx, dy, MatrixOrder.Prepend);
public void TranslateTransform(float dx, float dy, MatrixOrder order)
{
int status = SafeNativeMethods.Gdip.GdipTranslateWorldTransform(new HandleRef(this, NativeGraphics), dx, dy, order);
-
- if (status != SafeNativeMethods.Gdip.Ok)
- {
- throw SafeNativeMethods.Gdip.StatusException(status);
- }
+ SafeNativeMethods.Gdip.CheckStatus(status);
}
- public void ScaleTransform(float sx, float sy)
- {
- ScaleTransform(sx, sy, MatrixOrder.Prepend);
- }
+ public void ScaleTransform(float sx, float sy) => ScaleTransform(sx, sy, MatrixOrder.Prepend);
public void ScaleTransform(float sx, float sy, MatrixOrder order)
{
int status = SafeNativeMethods.Gdip.GdipScaleWorldTransform(new HandleRef(this, NativeGraphics), sx, sy, order);
-
- if (status != SafeNativeMethods.Gdip.Ok)
- {
- throw SafeNativeMethods.Gdip.StatusException(status);
- }
+ SafeNativeMethods.Gdip.CheckStatus(status);
}
- public void RotateTransform(float angle)
- {
- RotateTransform(angle, MatrixOrder.Prepend);
- }
+ public void RotateTransform(float angle) => RotateTransform(angle, MatrixOrder.Prepend);
public void RotateTransform(float angle, MatrixOrder order)
{
int status = SafeNativeMethods.Gdip.GdipRotateWorldTransform(new HandleRef(this, NativeGraphics), angle, order);
-
- if (status != SafeNativeMethods.Gdip.Ok)
- {
- throw SafeNativeMethods.Gdip.StatusException(status);
- }
+ SafeNativeMethods.Gdip.CheckStatus(status);
}
- public void TransformPoints(CoordinateSpace destSpace,
- CoordinateSpace srcSpace,
- PointF[] pts)
+ public void TransformPoints(CoordinateSpace destSpace, CoordinateSpace srcSpace, PointF[] pts)
{
if (pts == null)
{
- throw new ArgumentNullException("pts");
+ throw new ArgumentNullException(nameof(pts));
}
IntPtr buf = SafeNativeMethods.Gdip.ConvertPointToMemory(pts);
- int status = SafeNativeMethods.Gdip.GdipTransformPoints(new HandleRef(this, NativeGraphics), unchecked((int)destSpace),
- unchecked((int)srcSpace), buf, pts.Length);
-
try
{
- if (status != SafeNativeMethods.Gdip.Ok)
- {
- throw SafeNativeMethods.Gdip.StatusException(status);
- }
+ int status = SafeNativeMethods.Gdip.GdipTransformPoints(new HandleRef(this, NativeGraphics), unchecked((int)destSpace),
+ unchecked((int)srcSpace), buf, pts.Length);
+ SafeNativeMethods.Gdip.CheckStatus(status);
// must do an in-place copy because we only have a reference
PointF[] newPts = SafeNativeMethods.Gdip.ConvertGPPOINTFArrayF(buf, pts.Length);
-
for (int i = 0; i < pts.Length; i++)
{
pts[i] = newPts[i];
@@ -760,29 +722,22 @@ namespace System.Drawing
}
}
- [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Naming", "CA1704:IdentifiersShouldBeSpelledCorrectly")]
- public void TransformPoints(CoordinateSpace destSpace,
- CoordinateSpace srcSpace,
- Point[] pts)
+ [SuppressMessage("Microsoft.Naming", "CA1704:IdentifiersShouldBeSpelledCorrectly")]
+ public void TransformPoints(CoordinateSpace destSpace, CoordinateSpace srcSpace, Point[] pts)
{
if (pts == null)
{
- throw new ArgumentNullException("pts");
+ throw new ArgumentNullException(nameof(pts));
}
IntPtr buf = SafeNativeMethods.Gdip.ConvertPointToMemory(pts);
- int status = SafeNativeMethods.Gdip.GdipTransformPointsI(new HandleRef(this, NativeGraphics), unchecked((int)destSpace),
- unchecked((int)srcSpace), buf, pts.Length);
-
try
{
- if (status != SafeNativeMethods.Gdip.Ok)
- {
- throw SafeNativeMethods.Gdip.StatusException(status);
- }
+ int status = SafeNativeMethods.Gdip.GdipTransformPointsI(new HandleRef(this, NativeGraphics), unchecked((int)destSpace),
+ unchecked((int)srcSpace), buf, pts.Length);
+ SafeNativeMethods.Gdip.CheckStatus(status);
Point[] newPts = SafeNativeMethods.Gdip.ConvertGPPOINTArray(buf, pts.Length);
-
for (int i = 0; i < pts.Length; i++)
{
pts[i] = newPts[i];
@@ -797,13 +752,8 @@ namespace System.Drawing
public Color GetNearestColor(Color color)
{
int nearest = color.ToArgb();
-
int status = SafeNativeMethods.Gdip.GdipGetNearestColor(new HandleRef(this, NativeGraphics), ref nearest);
-
- if (status != SafeNativeMethods.Gdip.Ok)
- {
- throw SafeNativeMethods.Gdip.StatusException(status);
- }
+ SafeNativeMethods.Gdip.CheckStatus(status);
return Color.FromArgb(nearest);
}
@@ -814,11 +764,11 @@ namespace System.Drawing
public void DrawLine(Pen pen, float x1, float y1, float x2, float y2)
{
if (pen == null)
- throw new ArgumentNullException("pen");
+ {
+ throw new ArgumentNullException(nameof(pen));
+ }
int status = SafeNativeMethods.Gdip.GdipDrawLine(new HandleRef(this, NativeGraphics), new HandleRef(pen, pen.NativePen), x1, y1, x2, y2);
-
- //check error status sensitive to TS problems
CheckErrorStatus(status);
}
@@ -836,18 +786,26 @@ namespace System.Drawing
public void DrawLines(Pen pen, PointF[] points)
{
if (pen == null)
- throw new ArgumentNullException("pen");
+ {
+ throw new ArgumentNullException(nameof(pen));
+ }
+
if (points == null)
- throw new ArgumentNullException("points");
+ {
+ throw new ArgumentNullException(nameof(points));
+ }
IntPtr buf = SafeNativeMethods.Gdip.ConvertPointToMemory(points);
- int status = SafeNativeMethods.Gdip.GdipDrawLines(new HandleRef(this, NativeGraphics), new HandleRef(pen, pen.NativePen),
- new HandleRef(this, buf), points.Length);
-
- Marshal.FreeHGlobal(buf);
-
- //check error status sensitive to TS problems
- CheckErrorStatus(status);
+ try
+ {
+ int status = SafeNativeMethods.Gdip.GdipDrawLines(new HandleRef(this, NativeGraphics), new HandleRef(pen, pen.NativePen),
+ new HandleRef(this, buf), points.Length);
+ CheckErrorStatus(status);
+ }
+ finally
+ {
+ Marshal.FreeHGlobal(buf);
+ }
}
@@ -857,11 +815,11 @@ namespace System.Drawing
public void DrawLine(Pen pen, int x1, int y1, int x2, int y2)
{
if (pen == null)
- throw new ArgumentNullException("pen");
+ {
+ throw new ArgumentNullException(nameof(pen));
+ }
int status = SafeNativeMethods.Gdip.GdipDrawLineI(new HandleRef(this, NativeGraphics), new HandleRef(pen, pen.NativePen), x1, y1, x2, y2);
-
- //check error status sensitive to TS problems
CheckErrorStatus(status);
}
@@ -879,18 +837,26 @@ namespace System.Drawing
public void DrawLines(Pen pen, Point[] points)
{
if (pen == null)
- throw new ArgumentNullException("pen");
+ {
+ throw new ArgumentNullException(nameof(pen));
+ }
+
if (points == null)
- throw new ArgumentNullException("points");
+ {
+ throw new ArgumentNullException(nameof(points));
+ }
IntPtr buf = SafeNativeMethods.Gdip.ConvertPointToMemory(points);
- int status = SafeNativeMethods.Gdip.GdipDrawLinesI(new HandleRef(this, NativeGraphics), new HandleRef(pen, pen.NativePen),
- new HandleRef(this, buf), points.Length);
-
- Marshal.FreeHGlobal(buf);
-
- //check error status sensitive to TS problems
- CheckErrorStatus(status);
+ try
+ {
+ int status = SafeNativeMethods.Gdip.GdipDrawLinesI(new HandleRef(this, NativeGraphics), new HandleRef(pen, pen.NativePen),
+ new HandleRef(this, buf), points.Length);
+ CheckErrorStatus(status);
+ }
+ finally
+ {
+ Marshal.FreeHGlobal(buf);
+ }
}
/// <summary>
@@ -900,7 +866,9 @@ namespace System.Drawing
float startAngle, float sweepAngle)
{
if (pen == null)
- throw new ArgumentNullException("pen");
+ {
+ throw new ArgumentNullException(nameof(pen));
+ }
int status = SafeNativeMethods.Gdip.GdipDrawArc(new HandleRef(this, NativeGraphics), new HandleRef(pen, pen.NativePen), x, y,
width, height, startAngle, sweepAngle);
@@ -924,7 +892,7 @@ namespace System.Drawing
int startAngle, int sweepAngle)
{
if (pen == null)
- throw new ArgumentNullException("pen");
+ throw new ArgumentNullException(nameof(pen));
int status = SafeNativeMethods.Gdip.GdipDrawArcI(new HandleRef(this, NativeGraphics), new HandleRef(pen, pen.NativePen), x, y,
width, height, startAngle, sweepAngle);
@@ -948,7 +916,7 @@ namespace System.Drawing
float x3, float y3, float x4, float y4)
{
if (pen == null)
- throw new ArgumentNullException("pen");
+ throw new ArgumentNullException(nameof(pen));
int status = SafeNativeMethods.Gdip.GdipDrawBezier(new HandleRef(this, NativeGraphics), new HandleRef(pen, pen.NativePen), x1, y1,
x2, y2, x3, y3, x4, y4);
@@ -971,18 +939,26 @@ namespace System.Drawing
public void DrawBeziers(Pen pen, PointF[] points)
{
if (pen == null)
- throw new ArgumentNullException("pen");
+ {
+ throw new ArgumentNullException(nameof(pen));
+ }
+
if (points == null)
- throw new ArgumentNullException("points");
+ {
+ throw new ArgumentNullException(nameof(points));
+ }
IntPtr buf = SafeNativeMethods.Gdip.ConvertPointToMemory(points);
- int status = SafeNativeMethods.Gdip.GdipDrawBeziers(new HandleRef(this, NativeGraphics), new HandleRef(pen, pen.NativePen),
- new HandleRef(this, buf), points.Length);
-
- Marshal.FreeHGlobal(buf);
-
- //check error status sensitive to TS problems
- CheckErrorStatus(status);
+ try
+ {
+ int status = SafeNativeMethods.Gdip.GdipDrawBeziers(new HandleRef(this, NativeGraphics), new HandleRef(pen, pen.NativePen),
+ new HandleRef(this, buf), points.Length);
+ CheckErrorStatus(status);
+ }
+ finally
+ {
+ Marshal.FreeHGlobal(buf);
+ }
}
/// <summary>
@@ -999,17 +975,26 @@ namespace System.Drawing
public void DrawBeziers(Pen pen, Point[] points)
{
if (pen == null)
- throw new ArgumentNullException("pen");
+ {
+ throw new ArgumentNullException(nameof(pen));
+ }
+
if (points == null)
- throw new ArgumentNullException("points");
+ {
+ throw new ArgumentNullException(nameof(points));
+ }
IntPtr buf = SafeNativeMethods.Gdip.ConvertPointToMemory(points);
- int status = SafeNativeMethods.Gdip.GdipDrawBeziersI(new HandleRef(this, NativeGraphics), new HandleRef(pen, pen.NativePen),
- new HandleRef(this, buf), points.Length);
- Marshal.FreeHGlobal(buf);
-
- //check error status sensitive to TS problems
- CheckErrorStatus(status);
+ try
+ {
+ int status = SafeNativeMethods.Gdip.GdipDrawBeziersI(new HandleRef(this, NativeGraphics), new HandleRef(pen, pen.NativePen),
+ new HandleRef(this, buf), points.Length);
+ CheckErrorStatus(status);
+ }
+ finally
+ {
+ Marshal.FreeHGlobal(buf);
+ }
}
/// <summary>
@@ -1027,13 +1012,11 @@ namespace System.Drawing
{
if (pen == null)
{
- throw new ArgumentNullException("pen");
+ throw new ArgumentNullException(nameof(pen));
}
int status = SafeNativeMethods.Gdip.GdipDrawRectangle(new HandleRef(this, NativeGraphics), new HandleRef(pen, pen.NativePen), x, y,
width, height);
-
- //check error status sensitive to TS problems
CheckErrorStatus(status);
}
@@ -1044,12 +1027,10 @@ namespace System.Drawing
{
if (pen == null)
{
- throw new ArgumentNullException("pen");
+ throw new ArgumentNullException(nameof(pen));
}
int status = SafeNativeMethods.Gdip.GdipDrawRectangleI(new HandleRef(this, NativeGraphics), new HandleRef(pen, pen.NativePen), x, y, width, height);
-
- //check error status sensitive to TS problems
CheckErrorStatus(status);
}
@@ -1060,21 +1041,25 @@ namespace System.Drawing
{
if (pen == null)
{
- throw new ArgumentNullException("pen");
+ throw new ArgumentNullException(nameof(pen));
}
+
if (rects == null)
{
- throw new ArgumentNullException("rects");
+ throw new ArgumentNullException(nameof(rects));
}
IntPtr buf = SafeNativeMethods.Gdip.ConvertRectangleToMemory(rects);
- int status = SafeNativeMethods.Gdip.GdipDrawRectangles(new HandleRef(this, NativeGraphics), new HandleRef(pen, pen.NativePen),
- new HandleRef(this, buf), rects.Length);
-
- Marshal.FreeHGlobal(buf);
-
- //check error status sensitive to TS problems
- CheckErrorStatus(status);
+ try
+ {
+ int status = SafeNativeMethods.Gdip.GdipDrawRectangles(new HandleRef(this, NativeGraphics), new HandleRef(pen, pen.NativePen),
+ new HandleRef(this, buf), rects.Length);
+ CheckErrorStatus(status);
+ }
+ finally
+ {
+ Marshal.FreeHGlobal(buf);
+ }
}
/// <summary>
@@ -1084,21 +1069,25 @@ namespace System.Drawing
{
if (pen == null)
{
- throw new ArgumentNullException("pen");
+ throw new ArgumentNullException(nameof(pen));
}
+
if (rects == null)
{
- throw new ArgumentNullException("rects");
+ throw new ArgumentNullException(nameof(rects));
}
IntPtr buf = SafeNativeMethods.Gdip.ConvertRectangleToMemory(rects);
- int status = SafeNativeMethods.Gdip.GdipDrawRectanglesI(new HandleRef(this, NativeGraphics), new HandleRef(pen, pen.NativePen),
- new HandleRef(this, buf), rects.Length);
-
- Marshal.FreeHGlobal(buf);
-
- //check error status sensitive to TS problems
- CheckErrorStatus(status);
+ try
+ {
+ int status = SafeNativeMethods.Gdip.GdipDrawRectanglesI(new HandleRef(this, NativeGraphics), new HandleRef(pen, pen.NativePen),
+ new HandleRef(this, buf), rects.Length);
+ CheckErrorStatus(status);
+ }
+ finally
+ {
+ Marshal.FreeHGlobal(buf);
+ }
}
/// <summary>
@@ -1115,12 +1104,12 @@ namespace System.Drawing
public void DrawEllipse(Pen pen, float x, float y, float width, float height)
{
if (pen == null)
- throw new ArgumentNullException("pen");
+ {
+ throw new ArgumentNullException(nameof(pen));
+ }
int status = SafeNativeMethods.Gdip.GdipDrawEllipse(new HandleRef(this, NativeGraphics), new HandleRef(pen, pen.NativePen), x, y,
width, height);
-
- //check error status sensitive to TS problems
CheckErrorStatus(status);
}
@@ -1138,12 +1127,12 @@ namespace System.Drawing
public void DrawEllipse(Pen pen, int x, int y, int width, int height)
{
if (pen == null)
- throw new ArgumentNullException("pen");
+ {
+ throw new ArgumentNullException(nameof(pen));
+ }
int status = SafeNativeMethods.Gdip.GdipDrawEllipseI(new HandleRef(this, NativeGraphics), new HandleRef(pen, pen.NativePen), x, y,
width, height);
-
- //check error status sensitive to TS problems
CheckErrorStatus(status);
}
@@ -1152,8 +1141,7 @@ namespace System.Drawing
/// </summary>
public void DrawPie(Pen pen, RectangleF rect, float startAngle, float sweepAngle)
{
- DrawPie(pen, rect.X, rect.Y, rect.Width, rect.Height, startAngle,
- sweepAngle);
+ DrawPie(pen, rect.X, rect.Y, rect.Width, rect.Height, startAngle, sweepAngle);
}
/// <summary>
@@ -1163,12 +1151,12 @@ namespace System.Drawing
float height, float startAngle, float sweepAngle)
{
if (pen == null)
- throw new ArgumentNullException("pen");
+ {
+ throw new ArgumentNullException(nameof(pen));
+ }
int status = SafeNativeMethods.Gdip.GdipDrawPie(new HandleRef(this, NativeGraphics), new HandleRef(pen, pen.NativePen), x, y, width,
height, startAngle, sweepAngle);
-
- //check error status sensitive to TS problems
CheckErrorStatus(status);
}
@@ -1177,8 +1165,7 @@ namespace System.Drawing
/// </summary>
public void DrawPie(Pen pen, Rectangle rect, float startAngle, float sweepAngle)
{
- DrawPie(pen, rect.X, rect.Y, rect.Width, rect.Height, startAngle,
- sweepAngle);
+ DrawPie(pen, rect.X, rect.Y, rect.Width, rect.Height, startAngle, sweepAngle);
}
/// <summary>
@@ -1188,12 +1175,12 @@ namespace System.Drawing
int startAngle, int sweepAngle)
{
if (pen == null)
- throw new ArgumentNullException("pen");
+ {
+ throw new ArgumentNullException(nameof(pen));
+ }
int status = SafeNativeMethods.Gdip.GdipDrawPieI(new HandleRef(this, NativeGraphics), new HandleRef(pen, pen.NativePen), x, y, width,
height, startAngle, sweepAngle);
-
- //check error status sensitive to TS problems
CheckErrorStatus(status);
}
@@ -1203,18 +1190,26 @@ namespace System.Drawing
public void DrawPolygon(Pen pen, PointF[] points)
{
if (pen == null)
- throw new ArgumentNullException("pen");
+ {
+ throw new ArgumentNullException(nameof(pen));
+ }
+
if (points == null)
- throw new ArgumentNullException("points");
+ {
+ throw new ArgumentNullException(nameof(points));
+ }
IntPtr buf = SafeNativeMethods.Gdip.ConvertPointToMemory(points);
- int status = SafeNativeMethods.Gdip.GdipDrawPolygon(new HandleRef(this, NativeGraphics), new HandleRef(pen, pen.NativePen),
- new HandleRef(this, buf), points.Length);
-
- Marshal.FreeHGlobal(buf);
-
- //check error status sensitive to TS problems
- CheckErrorStatus(status);
+ try
+ {
+ int status = SafeNativeMethods.Gdip.GdipDrawPolygon(new HandleRef(this, NativeGraphics), new HandleRef(pen, pen.NativePen),
+ new HandleRef(this, buf), points.Length);
+ CheckErrorStatus(status);
+ }
+ finally
+ {
+ Marshal.FreeHGlobal(buf);
+ }
}
/// <summary>
@@ -1223,18 +1218,26 @@ namespace System.Drawing
public void DrawPolygon(Pen pen, Point[] points)
{
if (pen == null)
- throw new ArgumentNullException("pen");
+ {
+ throw new ArgumentNullException(nameof(pen));
+ }
+
if (points == null)
- throw new ArgumentNullException("points");
+ {
+ throw new ArgumentNullException(nameof(points));
+ }
IntPtr buf = SafeNativeMethods.Gdip.ConvertPointToMemory(points);
- int status = SafeNativeMethods.Gdip.GdipDrawPolygonI(new HandleRef(this, NativeGraphics), new HandleRef(pen, pen.NativePen),
- new HandleRef(this, buf), points.Length);
-
- Marshal.FreeHGlobal(buf);
-
- //check error status sensitive to TS problems
- CheckErrorStatus(status);
+ try
+ {
+ int status = SafeNativeMethods.Gdip.GdipDrawPolygonI(new HandleRef(this, NativeGraphics), new HandleRef(pen, pen.NativePen),
+ new HandleRef(this, buf), points.Length);
+ CheckErrorStatus(status);
+ }
+ finally
+ {
+ Marshal.FreeHGlobal(buf);
+ }
}
/// <summary>
@@ -1243,14 +1246,17 @@ namespace System.Drawing
public void DrawPath(Pen pen, GraphicsPath path)
{
if (pen == null)
- throw new ArgumentNullException("pen");
+ {
+ throw new ArgumentNullException(nameof(pen));
+ }
+
if (path == null)
- throw new ArgumentNullException("path");
+ {
+ throw new ArgumentNullException(nameof(path));
+ }
int status = SafeNativeMethods.Gdip.GdipDrawPath(new HandleRef(this, NativeGraphics), new HandleRef(pen, pen.NativePen),
new HandleRef(path, path.nativePath));
-
- //check error status sensitive to TS problems
CheckErrorStatus(status);
}
@@ -1260,18 +1266,26 @@ namespace System.Drawing
public void DrawCurve(Pen pen, PointF[] points)
{
if (pen == null)
- throw new ArgumentNullException("pen");
+ {
+ throw new ArgumentNullException(nameof(pen));
+ }
+
if (points == null)
- throw new ArgumentNullException("points");
+ {
+ throw new ArgumentNullException(nameof(points));
+ }
IntPtr buf = SafeNativeMethods.Gdip.ConvertPointToMemory(points);
- int status = SafeNativeMethods.Gdip.GdipDrawCurve(new HandleRef(this, NativeGraphics), new HandleRef(pen, pen.NativePen), new HandleRef(this, buf),
- points.Length);
-
- Marshal.FreeHGlobal(buf);
-
- //check error status sensitive to TS problems
- CheckErrorStatus(status);
+ try
+ {
+ int status = SafeNativeMethods.Gdip.GdipDrawCurve(new HandleRef(this, NativeGraphics), new HandleRef(pen, pen.NativePen), new HandleRef(this, buf),
+ points.Length);
+ CheckErrorStatus(status);
+ }
+ finally
+ {
+ Marshal.FreeHGlobal(buf);
+ }
}
/// <summary>
@@ -1280,18 +1294,26 @@ namespace System.Drawing
public void DrawCurve(Pen pen, PointF[] points, float tension)
{
if (pen == null)
- throw new ArgumentNullException("pen");
+ {
+ throw new ArgumentNullException(nameof(pen));
+ }
+
if (points == null)
- throw new ArgumentNullException("points");
+ {
+ throw new ArgumentNullException(nameof(points));
+ }
IntPtr buf = SafeNativeMethods.Gdip.ConvertPointToMemory(points);
- int status = SafeNativeMethods.Gdip.GdipDrawCurve2(new HandleRef(this, NativeGraphics), new HandleRef(pen, pen.NativePen), new HandleRef(this, buf),
- points.Length, tension);
-
- Marshal.FreeHGlobal(buf);
-
- //check error status sensitive to TS problems
- CheckErrorStatus(status);
+ try
+ {
+ int status = SafeNativeMethods.Gdip.GdipDrawCurve2(new HandleRef(this, NativeGraphics), new HandleRef(pen, pen.NativePen), new HandleRef(this, buf),
+ points.Length, tension);
+ CheckErrorStatus(status);
+ }
+ finally
+ {
+ Marshal.FreeHGlobal(buf);
+ }
}
public void DrawCurve(Pen pen, PointF[] points, int offset, int numberOfSegments)
@@ -1306,19 +1328,27 @@ namespace System.Drawing
float tension)
{
if (pen == null)
- throw new ArgumentNullException("pen");
+ {
+ throw new ArgumentNullException(nameof(pen));
+ }
+
if (points == null)
- throw new ArgumentNullException("points");
+ {
+ throw new ArgumentNullException(nameof(points));
+ }
IntPtr buf = SafeNativeMethods.Gdip.ConvertPointToMemory(points);
- int status = SafeNativeMethods.Gdip.GdipDrawCurve3(new HandleRef(this, NativeGraphics), new HandleRef(pen, pen.NativePen), new HandleRef(this, buf),
- points.Length, offset, numberOfSegments,
- tension);
-
- Marshal.FreeHGlobal(buf);
-
- //check error status sensitive to TS problems
- CheckErrorStatus(status);
+ try
+ {
+ int status = SafeNativeMethods.Gdip.GdipDrawCurve3(new HandleRef(this, NativeGraphics), new HandleRef(pen, pen.NativePen), new HandleRef(this, buf),
+ points.Length, offset, numberOfSegments,
+ tension);
+ CheckErrorStatus(status);
+ }
+ finally
+ {
+ Marshal.FreeHGlobal(buf);
+ }
}
/// <summary>
@@ -1327,18 +1357,26 @@ namespace System.Drawing
public void DrawCurve(Pen pen, Point[] points)
{
if (pen == null)
- throw new ArgumentNullException("pen");
+ {
+ throw new ArgumentNullException(nameof(pen));
+ }
+
if (points == null)
- throw new ArgumentNullException("points");
+ {
+ throw new ArgumentNullException(nameof(points));
+ }
IntPtr buf = SafeNativeMethods.Gdip.ConvertPointToMemory(points);
- int status = SafeNativeMethods.Gdip.GdipDrawCurveI(new HandleRef(this, NativeGraphics), new HandleRef(pen, pen.NativePen), new HandleRef(this, buf),
- points.Length);
-
- Marshal.FreeHGlobal(buf);
-
- //check error status sensitive to TS problems
- CheckErrorStatus(status);
+ try
+ {
+ int status = SafeNativeMethods.Gdip.GdipDrawCurveI(new HandleRef(this, NativeGraphics), new HandleRef(pen, pen.NativePen), new HandleRef(this, buf),
+ points.Length);
+ CheckErrorStatus(status);
+ }
+ finally
+ {
+ Marshal.FreeHGlobal(buf);
+ }
}
/// <summary>
@@ -1347,18 +1385,26 @@ namespace System.Drawing
public void DrawCurve(Pen pen, Point[] points, float tension)
{
if (pen == null)
- throw new ArgumentNullException("pen");
+ {
+ throw new ArgumentNullException(nameof(pen));
+ }
+
if (points == null)
- throw new ArgumentNullException("points");
+ {
+ throw new ArgumentNullException(nameof(points));
+ }
IntPtr buf = SafeNativeMethods.Gdip.ConvertPointToMemory(points);
- int status = SafeNativeMethods.Gdip.GdipDrawCurve2I(new HandleRef(this, NativeGraphics), new HandleRef(pen, pen.NativePen), new HandleRef(this, buf),
- points.Length, tension);
-
- Marshal.FreeHGlobal(buf);
-
- //check error status sensitive to TS problems
- CheckErrorStatus(status);
+ try
+ {
+ int status = SafeNativeMethods.Gdip.GdipDrawCurve2I(new HandleRef(this, NativeGraphics), new HandleRef(pen, pen.NativePen), new HandleRef(this, buf),
+ points.Length, tension);
+ CheckErrorStatus(status);
+ }
+ finally
+ {
+ Marshal.FreeHGlobal(buf);
+ }
}
/// <summary>
@@ -1368,19 +1414,27 @@ namespace System.Drawing
float tension)
{
if (pen == null)
- throw new ArgumentNullException("pen");
+ {
+ throw new ArgumentNullException(nameof(pen));
+ }
+
if (points == null)
- throw new ArgumentNullException("points");
+ {
+ throw new ArgumentNullException(nameof(points));
+ }
IntPtr buf = SafeNativeMethods.Gdip.ConvertPointToMemory(points);
- int status = SafeNativeMethods.Gdip.GdipDrawCurve3I(new HandleRef(this, NativeGraphics), new HandleRef(pen, pen.NativePen), new HandleRef(this, buf),
- points.Length, offset, numberOfSegments,
- tension);
-
- Marshal.FreeHGlobal(buf);
-
- //check error status sensitive to TS problems
- CheckErrorStatus(status);
+ try
+ {
+ int status = SafeNativeMethods.Gdip.GdipDrawCurve3I(new HandleRef(this, NativeGraphics), new HandleRef(pen, pen.NativePen), new HandleRef(this, buf),
+ points.Length, offset, numberOfSegments,
+ tension);
+ CheckErrorStatus(status);
+ }
+ finally
+ {
+ Marshal.FreeHGlobal(buf);
+ }
}
/// <summary>
@@ -1389,18 +1443,26 @@ namespace System.Drawing
public void DrawClosedCurve(Pen pen, PointF[] points)
{
if (pen == null)
- throw new ArgumentNullException("pen");
+ {
+ throw new ArgumentNullException(nameof(pen));
+ }
+
if (points == null)
- throw new ArgumentNullException("points");
+ {
+ throw new ArgumentNullException(nameof(points));
+ }
IntPtr buf = SafeNativeMethods.Gdip.ConvertPointToMemory(points);
- int status = SafeNativeMethods.Gdip.GdipDrawClosedCurve(new HandleRef(this, NativeGraphics), new HandleRef(pen, pen.NativePen), new HandleRef(this, buf),
- points.Length);
-
- Marshal.FreeHGlobal(buf);
-
- //check error status sensitive to TS problems
- CheckErrorStatus(status);
+ try
+ {
+ int status = SafeNativeMethods.Gdip.GdipDrawClosedCurve(new HandleRef(this, NativeGraphics), new HandleRef(pen, pen.NativePen), new HandleRef(this, buf),
+ points.Length);
+ CheckErrorStatus(status);
+ }
+ finally
+ {
+ Marshal.FreeHGlobal(buf);
+ }
}
/// <summary>
@@ -1409,18 +1471,26 @@ namespace System.Drawing
public void DrawClosedCurve(Pen pen, PointF[] points, float tension, FillMode fillmode)
{
if (pen == null)
- throw new ArgumentNullException("pen");
+ {
+ throw new ArgumentNullException(nameof(pen));
+ }
+
if (points == null)
- throw new ArgumentNullException("points");
+ {
+ throw new ArgumentNullException(nameof(points));
+ }
IntPtr buf = SafeNativeMethods.Gdip.ConvertPointToMemory(points);
- int status = SafeNativeMethods.Gdip.GdipDrawClosedCurve2(new HandleRef(this, NativeGraphics), new HandleRef(pen, pen.NativePen), new HandleRef(this, buf),
- points.Length, tension);
-
- Marshal.FreeHGlobal(buf);
-
- //check error status sensitive to TS problems
- CheckErrorStatus(status);
+ try
+ {
+ int status = SafeNativeMethods.Gdip.GdipDrawClosedCurve2(new HandleRef(this, NativeGraphics), new HandleRef(pen, pen.NativePen), new HandleRef(this, buf),
+ points.Length, tension);
+ CheckErrorStatus(status);
+ }
+ finally
+ {
+ Marshal.FreeHGlobal(buf);
+ }
}
/// <summary>
@@ -1429,18 +1499,26 @@ namespace System.Drawing
public void DrawClosedCurve(Pen pen, Point[] points)
{
if (pen == null)
- throw new ArgumentNullException("pen");
+ {
+ throw new ArgumentNullException(nameof(pen));
+ }
+
if (points == null)
- throw new ArgumentNullException("points");
+ {
+ throw new ArgumentNullException(nameof(points));
+ }
IntPtr buf = SafeNativeMethods.Gdip.ConvertPointToMemory(points);
- int status = SafeNativeMethods.Gdip.GdipDrawClosedCurveI(new HandleRef(this, NativeGraphics), new HandleRef(pen, pen.NativePen), new HandleRef(this, buf),
- points.Length);
-
- Marshal.FreeHGlobal(buf);
-
- //check error status sensitive to TS problems
- CheckErrorStatus(status);
+ try
+ {
+ int status = SafeNativeMethods.Gdip.GdipDrawClosedCurveI(new HandleRef(this, NativeGraphics), new HandleRef(pen, pen.NativePen), new HandleRef(this, buf),
+ points.Length);
+ CheckErrorStatus(status);
+ }
+ finally
+ {
+ Marshal.FreeHGlobal(buf);
+ }
}
/// <summary>
@@ -1449,18 +1527,27 @@ namespace System.Drawing
public void DrawClosedCurve(Pen pen, Point[] points, float tension, FillMode fillmode)
{
if (pen == null)
- throw new ArgumentNullException("pen");
+ {
+ throw new ArgumentNullException(nameof(pen));
+ }
+
if (points == null)
- throw new ArgumentNullException("points");
+ {
+ throw new ArgumentNullException(nameof(points));
+ }
IntPtr buf = SafeNativeMethods.Gdip.ConvertPointToMemory(points);
- int status = SafeNativeMethods.Gdip.GdipDrawClosedCurve2I(new HandleRef(this, NativeGraphics), new HandleRef(pen, pen.NativePen), new HandleRef(this, buf),
- points.Length, tension);
-
- Marshal.FreeHGlobal(buf);
+ try
+ {
+ int status = SafeNativeMethods.Gdip.GdipDrawClosedCurve2I(new HandleRef(this, NativeGraphics), new HandleRef(pen, pen.NativePen), new HandleRef(this, buf),
+ points.Length, tension);
+ CheckErrorStatus(status);
+ }
+ finally
+ {
+ Marshal.FreeHGlobal(buf);
+ }
- //check error status sensitive to TS problems
- CheckErrorStatus(status);
}
/// <summary>
@@ -1469,11 +1556,7 @@ namespace System.Drawing
public void Clear(Color color)
{
int status = SafeNativeMethods.Gdip.GdipGraphicsClear(new HandleRef(this, NativeGraphics), color.ToArgb());
-
- if (status != SafeNativeMethods.Gdip.Ok)
- {
- throw SafeNativeMethods.Gdip.StatusException(status);
- }
+ SafeNativeMethods.Gdip.CheckStatus(status);
}
/// <summary>
@@ -1491,13 +1574,11 @@ namespace System.Drawing
{
if (brush == null)
{
- throw new ArgumentNullException("brush");
+ throw new ArgumentNullException(nameof(brush));
}
int status = SafeNativeMethods.Gdip.GdipFillRectangle(new HandleRef(this, NativeGraphics), new HandleRef(brush, brush.NativeBrush), x, y,
width, height);
-
- //check error status sensitive to TS problems
CheckErrorStatus(status);
}
@@ -1516,12 +1597,10 @@ namespace System.Drawing
{
if (brush == null)
{
- throw new ArgumentNullException("brush");
+ throw new ArgumentNullException(nameof(brush));
}
int status = SafeNativeMethods.Gdip.GdipFillRectangleI(new HandleRef(this, NativeGraphics), new HandleRef(brush, brush.NativeBrush), x, y, width, height);
-
- //check error status sensitive to TS problems
CheckErrorStatus(status);
}
@@ -1532,21 +1611,24 @@ namespace System.Drawing
{
if (brush == null)
{
- throw new ArgumentNullException("brush");
+ throw new ArgumentNullException(nameof(brush));
}
if (rects == null)
{
- throw new ArgumentNullException("rects");
+ throw new ArgumentNullException(nameof(rects));
}
IntPtr buf = SafeNativeMethods.Gdip.ConvertRectangleToMemory(rects);
- int status = SafeNativeMethods.Gdip.GdipFillRectangles(new HandleRef(this, NativeGraphics), new HandleRef(brush, brush.NativeBrush),
- new HandleRef(this, buf), rects.Length);
-
- Marshal.FreeHGlobal(buf);
-
- //check error status sensitive to TS problems
- CheckErrorStatus(status);
+ try
+ {
+ int status = SafeNativeMethods.Gdip.GdipFillRectangles(new HandleRef(this, NativeGraphics), new HandleRef(brush, brush.NativeBrush),
+ new HandleRef(this, buf), rects.Length);
+ CheckErrorStatus(status);
+ }
+ finally
+ {
+ Marshal.FreeHGlobal(buf);
+ }
}
/// <summary>
@@ -1556,21 +1638,24 @@ namespace System.Drawing
{
if (brush == null)
{
- throw new ArgumentNullException("brush");
+ throw new ArgumentNullException(nameof(brush));
}
if (rects == null)
{
- throw new ArgumentNullException("rects");
+ throw new ArgumentNullException(nameof(rects));
}
IntPtr buf = SafeNativeMethods.Gdip.ConvertRectangleToMemory(rects);
- int status = SafeNativeMethods.Gdip.GdipFillRectanglesI(new HandleRef(this, NativeGraphics), new HandleRef(brush, brush.NativeBrush),
- new HandleRef(this, buf), rects.Length);
-
- Marshal.FreeHGlobal(buf);
-
- //check error status sensitive to TS problems
- CheckErrorStatus(status);
+ try
+ {
+ int status = SafeNativeMethods.Gdip.GdipFillRectanglesI(new HandleRef(this, NativeGraphics), new HandleRef(brush, brush.NativeBrush),
+ new HandleRef(this, buf), rects.Length);
+ CheckErrorStatus(status);
+ }
+ finally
+ {
+ Marshal.FreeHGlobal(buf);
+ }
}
/// <summary>
@@ -1587,18 +1672,26 @@ namespace System.Drawing
public void FillPolygon(Brush brush, PointF[] points, FillMode fillMode)
{
if (brush == null)
- throw new ArgumentNullException("brush");
+ {
+ throw new ArgumentNullException(nameof(brush));
+ }
+
if (points == null)
- throw new ArgumentNullException("points");
+ {
+ throw new ArgumentNullException(nameof(points));
+ }
IntPtr buf = SafeNativeMethods.Gdip.ConvertPointToMemory(points);
- int status = SafeNativeMethods.Gdip.GdipFillPolygon(new HandleRef(this, NativeGraphics), new HandleRef(brush, brush.NativeBrush),
- new HandleRef(this, buf), points.Length, unchecked((int)fillMode));
-
- Marshal.FreeHGlobal(buf);
-
- //check error status sensitive to TS problems
- CheckErrorStatus(status);
+ try
+ {
+ int status = SafeNativeMethods.Gdip.GdipFillPolygon(new HandleRef(this, NativeGraphics), new HandleRef(brush, brush.NativeBrush),
+ new HandleRef(this, buf), points.Length, unchecked((int)fillMode));
+ CheckErrorStatus(status);
+ }
+ finally
+ {
+ Marshal.FreeHGlobal(buf);
+ }
}
/// <summary>
@@ -1615,18 +1708,26 @@ namespace System.Drawing
public void FillPolygon(Brush brush, Point[] points, FillMode fillMode)
{
if (brush == null)
- throw new ArgumentNullException("brush");
+ {
+ throw new ArgumentNullException(nameof(brush));
+ }
+
if (points == null)
- throw new ArgumentNullException("points");
+ {
+ throw new ArgumentNullException(nameof(points));
+ }
IntPtr buf = SafeNativeMethods.Gdip.ConvertPointToMemory(points);
- int status = SafeNativeMethods.Gdip.GdipFillPolygonI(new HandleRef(this, NativeGraphics), new HandleRef(brush, brush.NativeBrush),
- new HandleRef(this, buf), points.Length, unchecked((int)fillMode));
-
- Marshal.FreeHGlobal(buf);
-
- //check error status sensitive to TS problems
- CheckErrorStatus(status);
+ try
+ {
+ int status = SafeNativeMethods.Gdip.GdipFillPolygonI(new HandleRef(this, NativeGraphics), new HandleRef(brush, brush.NativeBrush),
+ new HandleRef(this, buf), points.Length, unchecked((int)fillMode));
+ CheckErrorStatus(status);
+ }
+ finally
+ {
+ Marshal.FreeHGlobal(buf);
+ }
}
/// <summary>
@@ -1644,12 +1745,12 @@ namespace System.Drawing
float height)
{
if (brush == null)
- throw new ArgumentNullException("brush");
+ {
+ throw new ArgumentNullException(nameof(brush));
+ }
int status = SafeNativeMethods.Gdip.GdipFillEllipse(new HandleRef(this, NativeGraphics), new HandleRef(brush, brush.NativeBrush), x, y,
width, height);
-
- //check error status sensitive to TS problems
CheckErrorStatus(status);
}
@@ -1667,12 +1768,12 @@ namespace System.Drawing
public void FillEllipse(Brush brush, int x, int y, int width, int height)
{
if (brush == null)
- throw new ArgumentNullException("brush");
+ {
+ throw new ArgumentNullException(nameof(brush));
+ }
int status = SafeNativeMethods.Gdip.GdipFillEllipseI(new HandleRef(this, NativeGraphics), new HandleRef(brush, brush.NativeBrush), x, y,
width, height);
-
- //check error status sensitive to TS problems
CheckErrorStatus(status);
}
@@ -1682,8 +1783,7 @@ namespace System.Drawing
public void FillPie(Brush brush, Rectangle rect, float startAngle,
float sweepAngle)
{
- FillPie(brush, rect.X, rect.Y, rect.Width, rect.Height, startAngle,
- sweepAngle);
+ FillPie(brush, rect.X, rect.Y, rect.Width, rect.Height, startAngle, sweepAngle);
}
/// <summary>
@@ -1693,12 +1793,12 @@ namespace System.Drawing
float height, float startAngle, float sweepAngle)
{
if (brush == null)
- throw new ArgumentNullException("brush");
+ {
+ throw new ArgumentNullException(nameof(brush));
+ }
int status = SafeNativeMethods.Gdip.GdipFillPie(new HandleRef(this, NativeGraphics), new HandleRef(brush, brush.NativeBrush), x, y,
width, height, startAngle, sweepAngle);
-
- //check error status sensitive to TS problems
CheckErrorStatus(status);
}
@@ -1709,12 +1809,12 @@ namespace System.Drawing
int height, int startAngle, int sweepAngle)
{
if (brush == null)
- throw new ArgumentNullException("brush");
+ {
+ throw new ArgumentNullException(nameof(brush));
+ }
int status = SafeNativeMethods.Gdip.GdipFillPieI(new HandleRef(this, NativeGraphics), new HandleRef(brush, brush.NativeBrush), x, y,
width, height, startAngle, sweepAngle);
-
- //check error status sensitive to TS problems
CheckErrorStatus(status);
}
@@ -1724,14 +1824,17 @@ namespace System.Drawing
public void FillPath(Brush brush, GraphicsPath path)
{
if (brush == null)
- throw new ArgumentNullException("brush");
+ {
+ throw new ArgumentNullException(nameof(brush));
+ }
+
if (path == null)
- throw new ArgumentNullException("path");
+ {
+ throw new ArgumentNullException(nameof(path));
+ }
int status = SafeNativeMethods.Gdip.GdipFillPath(new HandleRef(this, NativeGraphics), new HandleRef(brush, brush.NativeBrush),
new HandleRef(path, path.nativePath));
-
- //check error status sensitive to TS problems
CheckErrorStatus(status);
}
@@ -1741,18 +1844,26 @@ namespace System.Drawing
public void FillClosedCurve(Brush brush, PointF[] points)
{
if (brush == null)
- throw new ArgumentNullException("brush");
+ {
+ throw new ArgumentNullException(nameof(brush));
+ }
+
if (points == null)
- throw new ArgumentNullException("points");
+ {
+ throw new ArgumentNullException(nameof(points));
+ }
IntPtr buf = SafeNativeMethods.Gdip.ConvertPointToMemory(points);
- int status = SafeNativeMethods.Gdip.GdipFillClosedCurve(new HandleRef(this, NativeGraphics), new HandleRef(brush, brush.NativeBrush),
- new HandleRef(this, buf), points.Length);
-
- Marshal.FreeHGlobal(buf);
-
- //check error status sensitive to TS problems
- CheckErrorStatus(status);
+ try
+ {
+ int status = SafeNativeMethods.Gdip.GdipFillClosedCurve(new HandleRef(this, NativeGraphics), new HandleRef(brush, brush.NativeBrush),
+ new HandleRef(this, buf), points.Length);
+ CheckErrorStatus(status);
+ }
+ finally
+ {
+ Marshal.FreeHGlobal(buf);
+ }
}
/// <summary>
@@ -1766,19 +1877,27 @@ namespace System.Drawing
public void FillClosedCurve(Brush brush, PointF[] points, FillMode fillmode, float tension)
{
if (brush == null)
- throw new ArgumentNullException("brush");
+ {
+ throw new ArgumentNullException(nameof(brush));
+ }
+
if (points == null)
- throw new ArgumentNullException("points");
+ {
+ throw new ArgumentNullException(nameof(points));
+ }
IntPtr buf = SafeNativeMethods.Gdip.ConvertPointToMemory(points);
- int status = SafeNativeMethods.Gdip.GdipFillClosedCurve2(new HandleRef(this, NativeGraphics), new HandleRef(brush, brush.NativeBrush),
- new HandleRef(this, buf), points.Length,
- tension, unchecked((int)fillmode));
-
- Marshal.FreeHGlobal(buf);
-
- //check error status sensitive to TS problems
- CheckErrorStatus(status);
+ try
+ {
+ int status = SafeNativeMethods.Gdip.GdipFillClosedCurve2(new HandleRef(this, NativeGraphics), new HandleRef(brush, brush.NativeBrush),
+ new HandleRef(this, buf), points.Length,
+ tension, unchecked((int)fillmode));
+ CheckErrorStatus(status);
+ }
+ finally
+ {
+ Marshal.FreeHGlobal(buf);
+ }
}
/// <summary>
@@ -1787,18 +1906,26 @@ namespace System.Drawing
public void FillClosedCurve(Brush brush, Point[] points)
{
if (brush == null)
- throw new ArgumentNullException("brush");
+ {
+ throw new ArgumentNullException(nameof(brush));
+ }
+
if (points == null)
- throw new ArgumentNullException("points");
+ {
+ throw new ArgumentNullException(nameof(points));
+ }
IntPtr buf = SafeNativeMethods.Gdip.ConvertPointToMemory(points);
- int status = SafeNativeMethods.Gdip.GdipFillClosedCurveI(new HandleRef(this, NativeGraphics), new HandleRef(brush, brush.NativeBrush),
- new HandleRef(this, buf), points.Length);
-
- Marshal.FreeHGlobal(buf);
-
- //check error status sensitive to TS problems
- CheckErrorStatus(status);
+ try
+ {
+ int status = SafeNativeMethods.Gdip.GdipFillClosedCurveI(new HandleRef(this, NativeGraphics), new HandleRef(brush, brush.NativeBrush),
+ new HandleRef(this, buf), points.Length);
+ CheckErrorStatus(status);
+ }
+ finally
+ {
+ Marshal.FreeHGlobal(buf);
+ }
}
public void FillClosedCurve(Brush brush, Point[] points, FillMode fillmode)
@@ -1809,19 +1936,27 @@ namespace System.Drawing
public void FillClosedCurve(Brush brush, Point[] points, FillMode fillmode, float tension)
{
if (brush == null)
- throw new ArgumentNullException("brush");
+ {
+ throw new ArgumentNullException(nameof(brush));
+ }
+
if (points == null)
- throw new ArgumentNullException("points");
+ {
+ throw new ArgumentNullException(nameof(points));
+ }
IntPtr buf = SafeNativeMethods.Gdip.ConvertPointToMemory(points);
- int status = SafeNativeMethods.Gdip.GdipFillClosedCurve2I(new HandleRef(this, NativeGraphics), new HandleRef(brush, brush.NativeBrush),
- new HandleRef(this, buf), points.Length,
- tension, unchecked((int)fillmode));
-
- Marshal.FreeHGlobal(buf);
-
- //check error status sensitive to TS problems
- CheckErrorStatus(status);
+ try
+ {
+ int status = SafeNativeMethods.Gdip.GdipFillClosedCurve2I(new HandleRef(this, NativeGraphics), new HandleRef(brush, brush.NativeBrush),
+ new HandleRef(this, buf), points.Length,
+ tension, unchecked((int)fillmode));
+ CheckErrorStatus(status);
+ }
+ finally
+ {
+ Marshal.FreeHGlobal(buf);
+ }
}
/// <summary>
@@ -1830,214 +1965,200 @@ namespace System.Drawing
public void FillRegion(Brush brush, Region region)
{
if (brush == null)
- throw new ArgumentNullException("brush");
+ {
+ throw new ArgumentNullException(nameof(brush));
+ }
if (region == null)
- throw new ArgumentNullException("region");
+ {
+ throw new ArgumentNullException(nameof(region));
+ }
int status = SafeNativeMethods.Gdip.GdipFillRegion(new HandleRef(this, NativeGraphics), new HandleRef(brush, brush.NativeBrush),
new HandleRef(region, region._nativeRegion));
-
- //check error status sensitive to TS problems
CheckErrorStatus(status);
}
/// <summary>
/// Draws a string with the specified font.
/// </summary>
- public void DrawString(String s, Font font, Brush brush, float x, float y)
+ public void DrawString(string s, Font font, Brush brush, float x, float y)
{
DrawString(s, font, brush, new RectangleF(x, y, 0, 0), null);
}
- public void DrawString(String s, Font font, Brush brush, PointF point)
+ public void DrawString(string s, Font font, Brush brush, PointF point)
{
DrawString(s, font, brush, new RectangleF(point.X, point.Y, 0, 0), null);
}
- public void DrawString(String s, Font font, Brush brush, float x, float y, StringFormat format)
+ public void DrawString(string s, Font font, Brush brush, float x, float y, StringFormat format)
{
DrawString(s, font, brush, new RectangleF(x, y, 0, 0), format);
}
- public void DrawString(String s, Font font, Brush brush, PointF point, StringFormat format)
+ public void DrawString(string s, Font font, Brush brush, PointF point, StringFormat format)
{
DrawString(s, font, brush, new RectangleF(point.X, point.Y, 0, 0), format);
}
- public void DrawString(String s, Font font, Brush brush, RectangleF layoutRectangle)
+ public void DrawString(string s, Font font, Brush brush, RectangleF layoutRectangle)
{
DrawString(s, font, brush, layoutRectangle, null);
}
- public void DrawString(String s, Font font, Brush brush,
+ public void DrawString(string s, Font font, Brush brush,
RectangleF layoutRectangle, StringFormat format)
{
if (brush == null)
- throw new ArgumentNullException("brush");
+ {
+ throw new ArgumentNullException(nameof(brush));
+ }
- if (s == null || s.Length == 0)
+ if (string.IsNullOrEmpty(s))
+ {
return;
+ }
+
if (font == null)
- throw new ArgumentNullException("font");
+ {
+ throw new ArgumentNullException(nameof(font));
+ }
- GPRECTF grf = new GPRECTF(layoutRectangle);
+ var grf = new GPRECTF(layoutRectangle);
IntPtr nativeStringFormat = (format == null) ? IntPtr.Zero : format.nativeFormat;
int status = SafeNativeMethods.Gdip.GdipDrawString(new HandleRef(this, NativeGraphics), s, s.Length, new HandleRef(font, font.NativeFont), ref grf, new HandleRef(format, nativeStringFormat), new HandleRef(brush, brush.NativeBrush));
-
- //check error status sensitive to TS problems
CheckErrorStatus(status);
}
- public SizeF MeasureString(String text, Font font, SizeF layoutArea, StringFormat stringFormat,
+ public SizeF MeasureString(string text, Font font, SizeF layoutArea, StringFormat stringFormat,
out int charactersFitted, out int linesFilled)
{
if (text == null || text.Length == 0)
{
charactersFitted = 0;
linesFilled = 0;
- return new SizeF(0, 0);
+ return SizeF.Empty;
}
+
if (font == null)
{
- throw new ArgumentNullException("font");
+ throw new ArgumentNullException(nameof(font));
}
- GPRECTF grfLayout = new GPRECTF(0, 0, layoutArea.Width, layoutArea.Height);
- GPRECTF grfboundingBox = new GPRECTF();
+ var grfLayout = new GPRECTF(0, 0, layoutArea.Width, layoutArea.Height);
+ var grfboundingBox = new GPRECTF();
int status = SafeNativeMethods.Gdip.GdipMeasureString(new HandleRef(this, NativeGraphics), text, text.Length, new HandleRef(font, font.NativeFont), ref grfLayout,
new HandleRef(stringFormat, (stringFormat == null) ? IntPtr.Zero : stringFormat.nativeFormat),
ref grfboundingBox,
out charactersFitted, out linesFilled);
-
- if (status != SafeNativeMethods.Gdip.Ok)
- {
- throw SafeNativeMethods.Gdip.StatusException(status);
- }
+ SafeNativeMethods.Gdip.CheckStatus(status);
return grfboundingBox.SizeF;
}
- public SizeF MeasureString(String text, Font font, PointF origin, StringFormat stringFormat)
+ public SizeF MeasureString(string text, Font font, PointF origin, StringFormat stringFormat)
{
- if (text == null || text.Length == 0)
- return new SizeF(0, 0);
- if (font == null)
- throw new ArgumentNullException("font");
+ if (string.IsNullOrEmpty(text))
+ {
+ return SizeF.Empty;
+ }
- GPRECTF grf = new GPRECTF();
- GPRECTF grfboundingBox = new GPRECTF();
+ if (font == null)
+ {
+ throw new ArgumentNullException(nameof(font));
+ }
- grf.X = origin.X;
- grf.Y = origin.Y;
- grf.Width = 0;
- grf.Height = 0;
+ var grf = new GPRECTF(origin.X, origin.Y, 0, 0);
+ var grfboundingBox = new GPRECTF();
int a, b;
int status = SafeNativeMethods.Gdip.GdipMeasureString(new HandleRef(this, NativeGraphics), text, text.Length, new HandleRef(font, font.NativeFont),
ref grf,
new HandleRef(stringFormat, (stringFormat == null) ? IntPtr.Zero : stringFormat.nativeFormat),
ref grfboundingBox, out a, out b);
-
- if (status != SafeNativeMethods.Gdip.Ok)
- {
- throw SafeNativeMethods.Gdip.StatusException(status);
- }
+ SafeNativeMethods.Gdip.CheckStatus(status);
return grfboundingBox.SizeF;
}
- public SizeF MeasureString(String text, Font font, SizeF layoutArea)
+ public SizeF MeasureString(string text, Font font, SizeF layoutArea)
{
return MeasureString(text, font, layoutArea, null);
}
- public SizeF MeasureString(String text, Font font, SizeF layoutArea, StringFormat stringFormat)
+ public SizeF MeasureString(string text, Font font, SizeF layoutArea, StringFormat stringFormat)
{
- if (text == null || text.Length == 0)
+ if (string.IsNullOrEmpty(text))
{
- return new SizeF(0, 0);
+ return SizeF.Empty;
}
if (font == null)
{
- throw new ArgumentNullException("font");
+ throw new ArgumentNullException(nameof(font));
}
- GPRECTF grfLayout = new GPRECTF(0, 0, layoutArea.Width, layoutArea.Height);
- GPRECTF grfboundingBox = new GPRECTF();
+ var grfLayout = new GPRECTF(0, 0, layoutArea.Width, layoutArea.Height);
+ var grfboundingBox = new GPRECTF();
int a, b;
int status = SafeNativeMethods.Gdip.GdipMeasureString(new HandleRef(this, NativeGraphics), text, text.Length, new HandleRef(font, font.NativeFont),
ref grfLayout,
new HandleRef(stringFormat, (stringFormat == null) ? IntPtr.Zero : stringFormat.nativeFormat),
ref grfboundingBox, out a, out b);
-
- if (status != SafeNativeMethods.Gdip.Ok)
- {
- throw SafeNativeMethods.Gdip.StatusException(status);
- }
+ SafeNativeMethods.Gdip.CheckStatus(status);
return grfboundingBox.SizeF;
}
- public SizeF MeasureString(String text, Font font)
+ public SizeF MeasureString(string text, Font font)
{
return MeasureString(text, font, new SizeF(0, 0));
}
- public SizeF MeasureString(String text, Font font, int width)
+ public SizeF MeasureString(string text, Font font, int width)
{
return MeasureString(text, font, new SizeF(width, 999999));
}
- public SizeF MeasureString(String text, Font font, int width, StringFormat format)
+ public SizeF MeasureString(string text, Font font, int width, StringFormat format)
{
return MeasureString(text, font, new SizeF(width, 999999), format);
}
- public Region[] MeasureCharacterRanges(String text, Font font, RectangleF layoutRect,
- StringFormat stringFormat)
+ public Region[] MeasureCharacterRanges(string text, Font font, RectangleF layoutRect,
+ StringFormat stringFormat)
{
- if (text == null || text.Length == 0)
+ if (string.IsNullOrEmpty(text))
{
- return new Region[] { };
+ return Array.Empty<Region>();
}
+
if (font == null)
{
- throw new ArgumentNullException("font");
+ throw new ArgumentNullException(nameof(font));
}
int count;
- int status = SafeNativeMethods.Gdip.GdipGetStringFormatMeasurableCharacterRangeCount(new HandleRef(stringFormat, (stringFormat == null) ? IntPtr.Zero : stringFormat.nativeFormat)
- , out count);
-
- if (status != SafeNativeMethods.Gdip.Ok)
- {
- throw SafeNativeMethods.Gdip.StatusException(status);
- }
-
- IntPtr[] gpRegions = new IntPtr[count];
-
- GPRECTF grf = new GPRECTF(layoutRect);
+ int status = SafeNativeMethods.Gdip.GdipGetStringFormatMeasurableCharacterRangeCount(new HandleRef(stringFormat, (stringFormat == null) ? IntPtr.Zero : stringFormat.nativeFormat),
+ out count);
+ SafeNativeMethods.Gdip.CheckStatus(status);
- Region[] regions = new Region[count];
+ var gpRegions = new IntPtr[count];
+ var grf = new GPRECTF(layoutRect);
+ var regions = new Region[count];
for (int f = 0; f < count; f++)
{
regions[f] = new Region();
- gpRegions[f] = (IntPtr)regions[f]._nativeRegion;
+ gpRegions[f] = regions[f]._nativeRegion;
}
status = SafeNativeMethods.Gdip.GdipMeasureCharacterRanges(new HandleRef(this, NativeGraphics), text, text.Length, new HandleRef(font, font.NativeFont), ref grf,
new HandleRef(stringFormat, (stringFormat == null) ? IntPtr.Zero : stringFormat.nativeFormat),
count, gpRegions);
-
-
- if (status != SafeNativeMethods.Gdip.Ok)
- {
- throw SafeNativeMethods.Gdip.StatusException(status);
- }
+ SafeNativeMethods.Gdip.CheckStatus(status);
return regions;
}
@@ -2046,14 +2167,14 @@ namespace System.Drawing
{
if (icon == null)
{
- throw new ArgumentNullException("icon");
+ throw new ArgumentNullException(nameof(icon));
}
if (_backingImage != null)
{
- // we don't call the icon directly because we want to stay in GDI+ all the time
+ // We don't call the icon directly because we want to stay in GDI+ all the time
// to avoid alpha channel interop issues between gdi and gdi+
- // so we do icon.ToBitmap() and then we call DrawImage. this is probably slower...
+ // so we do icon.ToBitmap() and then we call DrawImage. This is probably slower.
DrawImage(icon.ToBitmap(), x, y);
}
else
@@ -2063,23 +2184,23 @@ namespace System.Drawing
}
/// <summary>
- /// Draws this image to a graphics object. The drawing command originates on the graphics
- /// object, but a graphics object generally has no idea how to render a given image. So,
- /// it passes the call to the actual image. This version crops the image to the given
+ /// Draws this image to a graphics object. The drawing command originates on the graphics
+ /// object, but a graphics object generally has no idea how to render a given image. So,
+ /// it passes the call to the actual image. This version crops the image to the given
/// dimensions and allows the user to specify a rectangle within the image to draw.
/// </summary>
public void DrawIcon(Icon icon, Rectangle targetRect)
{
if (icon == null)
{
- throw new ArgumentNullException("icon");
+ throw new ArgumentNullException(nameof(icon));
}
if (_backingImage != null)
{
- // we don't call the icon directly because we want to stay in GDI+ all the time
+ // We don't call the icon directly because we want to stay in GDI+ all the time
// to avoid alpha channel interop issues between gdi and gdi+
- // so we do icon.ToBitmap() and then we call DrawImage. this is probably slower...
+ // so we do icon.ToBitmap() and then we call DrawImage. This is probably slower.
DrawImage(icon.ToBitmap(), targetRect);
}
else
@@ -2089,16 +2210,16 @@ namespace System.Drawing
}
/// <summary>
- /// Draws this image to a graphics object. The drawing command originates on the graphics
- /// object, but a graphics object generally has no idea how to render a given image. So,
- /// it passes the call to the actual image. This version stretches the image to the given
+ /// Draws this image to a graphics object. The drawing command originates on the graphics
+ /// object, but a graphics object generally has no idea how to render a given image. So,
+ /// it passes the call to the actual image. This version stretches the image to the given
/// dimensions and allows the user to specify a rectangle within the image to draw.
/// </summary>
public void DrawIconUnstretched(Icon icon, Rectangle targetRect)
{
if (icon == null)
{
- throw new ArgumentNullException("icon");
+ throw new ArgumentNullException(nameof(icon));
}
if (_backingImage != null)
@@ -2114,87 +2235,83 @@ namespace System.Drawing
/// <summary>
/// Draws the specified image at the specified location.
/// </summary>
- [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Naming", "CA1704:IdentifiersShouldBeSpelledCorrectly")]
+ [SuppressMessage("Microsoft.Naming", "CA1704:IdentifiersShouldBeSpelledCorrectly")]
public void DrawImage(Image image, PointF point)
{
DrawImage(image, point.X, point.Y);
}
- [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Naming", "CA1704:IdentifiersShouldBeSpelledCorrectly")]
+ [SuppressMessage("Microsoft.Naming", "CA1704:IdentifiersShouldBeSpelledCorrectly")]
public void DrawImage(Image image, float x, float y)
{
if (image == null)
- throw new ArgumentNullException("image");
+ {
+ throw new ArgumentNullException(nameof(image));
+ }
int status = SafeNativeMethods.Gdip.GdipDrawImage(new HandleRef(this, NativeGraphics), new HandleRef(image, image.nativeImage),
x, y);
-
- //ignore emf metafile error
+
IgnoreMetafileErrors(image, ref status);
-
- //check error status sensitive to TS problems
CheckErrorStatus(status);
}
- [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Naming", "CA1704:IdentifiersShouldBeSpelledCorrectly")]
+ [SuppressMessage("Microsoft.Naming", "CA1704:IdentifiersShouldBeSpelledCorrectly")]
public void DrawImage(Image image, RectangleF rect)
{
DrawImage(image, rect.X, rect.Y, rect.Width, rect.Height);
}
- [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Naming", "CA1704:IdentifiersShouldBeSpelledCorrectly")]
- public void DrawImage(Image image, float x, float y, float width,
- float height)
+ [SuppressMessage("Microsoft.Naming", "CA1704:IdentifiersShouldBeSpelledCorrectly")]
+ public void DrawImage(Image image, float x, float y, float width, float height)
{
if (image == null)
- throw new ArgumentNullException("image");
+ {
+ throw new ArgumentNullException(nameof(image));
+ }
int status = SafeNativeMethods.Gdip.GdipDrawImageRect(new HandleRef(this, NativeGraphics),
new HandleRef(image, image.nativeImage),
x, y,
width, height);
-
- //ignore emf metafile error
+
IgnoreMetafileErrors(image, ref status);
-
- //check error status sensitive to TS problems
CheckErrorStatus(status);
}
- [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Naming", "CA1704:IdentifiersShouldBeSpelledCorrectly")]
+ [SuppressMessage("Microsoft.Naming", "CA1704:IdentifiersShouldBeSpelledCorrectly")]
public void DrawImage(Image image, Point point)
{
DrawImage(image, point.X, point.Y);
}
- [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Naming", "CA1704:IdentifiersShouldBeSpelledCorrectly")]
+ [SuppressMessage("Microsoft.Naming", "CA1704:IdentifiersShouldBeSpelledCorrectly")]
public void DrawImage(Image image, int x, int y)
{
if (image == null)
- throw new ArgumentNullException("image");
+ {
+ throw new ArgumentNullException(nameof(image));
+ }
int status = SafeNativeMethods.Gdip.GdipDrawImageI(new HandleRef(this, NativeGraphics), new HandleRef(image, image.nativeImage),
x, y);
-
- //ignore emf metafile error
+
IgnoreMetafileErrors(image, ref status);
-
- //check error status sensitive to TS problems
CheckErrorStatus(status);
}
- [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Naming", "CA1704:IdentifiersShouldBeSpelledCorrectly")]
+ [SuppressMessage("Microsoft.Naming", "CA1704:IdentifiersShouldBeSpelledCorrectly")]
public void DrawImage(Image image, Rectangle rect)
{
DrawImage(image, rect.X, rect.Y, rect.Width, rect.Height);
}
- [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Naming", "CA1704:IdentifiersShouldBeSpelledCorrectly")]
+ [SuppressMessage("Microsoft.Naming", "CA1704:IdentifiersShouldBeSpelledCorrectly")]
public void DrawImage(Image image, int x, int y, int width, int height)
{
if (image == null)
{
- throw new ArgumentNullException("image");
+ throw new ArgumentNullException(nameof(image));
}
int status = SafeNativeMethods.Gdip.GdipDrawImageRectI(new HandleRef(this, NativeGraphics),
@@ -2202,10 +2319,7 @@ namespace System.Drawing
x, y,
width, height);
- //ignore emf metafile error
IgnoreMetafileErrors(image, ref status);
-
- //check error status sensitive to TS problems
CheckErrorStatus(status);
}
@@ -2235,13 +2349,14 @@ namespace System.Drawing
{
if (image == null)
{
- throw new ArgumentNullException("image");
+ throw new ArgumentNullException(nameof(image));
}
int width = Math.Min(rect.Width, image.Width);
int height = Math.Min(rect.Height, image.Height);
- //We could put centering logic here too for the case when the image is smaller than the rect
+ // We could put centering logic here too for the case when the image
+ // is smaller than the rect.
DrawImage(image, rect, 0, 0, width, height, GraphicsUnit.Pixel);
}
@@ -2256,66 +2371,81 @@ namespace System.Drawing
*
* @notes Perspective blt only works for bitmap images.
*/
- [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Naming", "CA1704:IdentifiersShouldBeSpelledCorrectly")]
+ [SuppressMessage("Microsoft.Naming", "CA1704:IdentifiersShouldBeSpelledCorrectly")]
public void DrawImage(Image image, PointF[] destPoints)
{
if (destPoints == null)
- throw new ArgumentNullException("destPoints");
+ {
+ throw new ArgumentNullException(nameof(destPoints));
+ }
+
if (image == null)
- throw new ArgumentNullException("image");
+ {
+ throw new ArgumentNullException(nameof(image));
+ }
int count = destPoints.Length;
-
if (count != 3 && count != 4)
+ {
throw new ArgumentException(SR.Format(SR.GdiplusDestPointsInvalidLength));
+ }
IntPtr buf = SafeNativeMethods.Gdip.ConvertPointToMemory(destPoints);
- int status = SafeNativeMethods.Gdip.GdipDrawImagePoints(new HandleRef(this, NativeGraphics),
- new HandleRef(image, image.nativeImage),
- new HandleRef(this, buf), count);
-
- Marshal.FreeHGlobal(buf);
-
- //ignore emf metafile error
- IgnoreMetafileErrors(image, ref status);
-
- //check error status sensitive to TS problems
- CheckErrorStatus(status);
+ try
+ {
+ int status = SafeNativeMethods.Gdip.GdipDrawImagePoints(new HandleRef(this, NativeGraphics),
+ new HandleRef(image, image.nativeImage),
+ new HandleRef(this, buf), count);
+ IgnoreMetafileErrors(image, ref status);
+ CheckErrorStatus(status);
+ }
+ finally
+ {
+ Marshal.FreeHGlobal(buf);
+ }
}
- [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Naming", "CA1704:IdentifiersShouldBeSpelledCorrectly")]
+ [SuppressMessage("Microsoft.Naming", "CA1704:IdentifiersShouldBeSpelledCorrectly")]
public void DrawImage(Image image, Point[] destPoints)
{
if (destPoints == null)
- throw new ArgumentNullException("destPoints");
+ {
+ throw new ArgumentNullException(nameof(destPoints));
+ }
+
if (image == null)
- throw new ArgumentNullException("image");
+ {
+ throw new ArgumentNullException(nameof(image));
+ }
int count = destPoints.Length;
-
if (count != 3 && count != 4)
+ {
throw new ArgumentException(SR.Format(SR.GdiplusDestPointsInvalidLength));
+ }
IntPtr buf = SafeNativeMethods.Gdip.ConvertPointToMemory(destPoints);
- int status = SafeNativeMethods.Gdip.GdipDrawImagePointsI(new HandleRef(this, NativeGraphics),
- new HandleRef(image, image.nativeImage),
- new HandleRef(this, buf), count);
-
- Marshal.FreeHGlobal(buf);
-
- //ignore emf metafile error
- IgnoreMetafileErrors(image, ref status);
-
- //check error status sensitive to TS problems
- CheckErrorStatus(status);
+ try
+ {
+ int status = SafeNativeMethods.Gdip.GdipDrawImagePointsI(new HandleRef(this, NativeGraphics),
+ new HandleRef(image, image.nativeImage),
+ new HandleRef(this, buf), count);
+ IgnoreMetafileErrors(image, ref status);
+ CheckErrorStatus(status);
+ }
+ finally
+ {
+ Marshal.FreeHGlobal(buf);
+ }
}
- [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Naming", "CA1704:IdentifiersShouldBeSpelledCorrectly")]
- public void DrawImage(Image image, float x, float y, RectangleF srcRect,
- GraphicsUnit srcUnit)
+ [SuppressMessage("Microsoft.Naming", "CA1704:IdentifiersShouldBeSpelledCorrectly")]
+ public void DrawImage(Image image, float x, float y, RectangleF srcRect, GraphicsUnit srcUnit)
{
if (image == null)
- throw new ArgumentNullException("image");
+ {
+ throw new ArgumentNullException(nameof(image));
+ }
int status = SafeNativeMethods.Gdip.GdipDrawImagePointRect(
new HandleRef(this, NativeGraphics),
@@ -2326,21 +2456,18 @@ namespace System.Drawing
srcRect.Y,
srcRect.Width,
srcRect.Height,
- unchecked((int)srcUnit));
-
- //ignore emf metafile error
+ unchecked((int)srcUnit));
IgnoreMetafileErrors(image, ref status);
-
- //check error status sensitive to TS problems
CheckErrorStatus(status);
}
- [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Naming", "CA1704:IdentifiersShouldBeSpelledCorrectly")]
- public void DrawImage(Image image, int x, int y, Rectangle srcRect,
- GraphicsUnit srcUnit)
+ [SuppressMessage("Microsoft.Naming", "CA1704:IdentifiersShouldBeSpelledCorrectly")]
+ public void DrawImage(Image image, int x, int y, Rectangle srcRect, GraphicsUnit srcUnit)
{
if (image == null)
- throw new ArgumentNullException("image");
+ {
+ throw new ArgumentNullException(nameof(image));
+ }
int status = SafeNativeMethods.Gdip.GdipDrawImagePointRectI(
new HandleRef(this, NativeGraphics),
@@ -2352,20 +2479,17 @@ namespace System.Drawing
srcRect.Width,
srcRect.Height,
unchecked((int)srcUnit));
-
- //ignore emf metafile error
IgnoreMetafileErrors(image, ref status);
-
- //check error status sensitive to TS problems
CheckErrorStatus(status);
}
- [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Naming", "CA1704:IdentifiersShouldBeSpelledCorrectly")]
- public void DrawImage(Image image, RectangleF destRect, RectangleF srcRect,
- GraphicsUnit srcUnit)
+ [SuppressMessage("Microsoft.Naming", "CA1704:IdentifiersShouldBeSpelledCorrectly")]
+ public void DrawImage(Image image, RectangleF destRect, RectangleF srcRect, GraphicsUnit srcUnit)
{
if (image == null)
- throw new ArgumentNullException("image");
+ {
+ throw new ArgumentNullException(nameof(image));
+ }
int status = SafeNativeMethods.Gdip.GdipDrawImageRectRect(
new HandleRef(this, NativeGraphics),
@@ -2381,22 +2505,18 @@ namespace System.Drawing
unchecked((int)srcUnit),
NativeMethods.NullHandleRef,
null,
- NativeMethods.NullHandleRef
- );
-
- //ignore emf metafile error
+ NativeMethods.NullHandleRef);
IgnoreMetafileErrors(image, ref status);
-
- //check error status sensitive to TS problems
CheckErrorStatus(status);
}
- [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Naming", "CA1704:IdentifiersShouldBeSpelledCorrectly")]
- public void DrawImage(Image image, Rectangle destRect, Rectangle srcRect,
- GraphicsUnit srcUnit)
+ [SuppressMessage("Microsoft.Naming", "CA1704:IdentifiersShouldBeSpelledCorrectly")]
+ public void DrawImage(Image image, Rectangle destRect, Rectangle srcRect, GraphicsUnit srcUnit)
{
if (image == null)
- throw new ArgumentNullException("image");
+ {
+ throw new ArgumentNullException(nameof(image));
+ }
int status = SafeNativeMethods.Gdip.GdipDrawImageRectRectI(
new HandleRef(this, NativeGraphics),
@@ -2413,61 +2533,62 @@ namespace System.Drawing
NativeMethods.NullHandleRef,
null,
NativeMethods.NullHandleRef);
-
- //ignore emf metafile error
IgnoreMetafileErrors(image, ref status);
-
- //check error status sensitive to TS problems
CheckErrorStatus(status);
}
- [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Naming", "CA1704:IdentifiersShouldBeSpelledCorrectly")]
- public void DrawImage(Image image, PointF[] destPoints, RectangleF srcRect,
- GraphicsUnit srcUnit)
+ [SuppressMessage("Microsoft.Naming", "CA1704:IdentifiersShouldBeSpelledCorrectly")]
+ public void DrawImage(Image image, PointF[] destPoints, RectangleF srcRect, GraphicsUnit srcUnit)
{
if (destPoints == null)
- throw new ArgumentNullException("destPoints");
+ {
+ throw new ArgumentNullException(nameof(destPoints));
+ }
+
if (image == null)
- throw new ArgumentNullException("image");
+ {
+ throw new ArgumentNullException(nameof(image));
+ }
int count = destPoints.Length;
-
if (count != 3 && count != 4)
+ {
throw new ArgumentException(SR.Format(SR.GdiplusDestPointsInvalidLength));
+ }
IntPtr buf = SafeNativeMethods.Gdip.ConvertPointToMemory(destPoints);
-
- int status = SafeNativeMethods.Gdip.GdipDrawImagePointsRect(
- new HandleRef(this, NativeGraphics),
- new HandleRef(image, image.nativeImage),
- new HandleRef(this, buf),
- destPoints.Length,
- srcRect.X,
- srcRect.Y,
- srcRect.Width,
- srcRect.Height,
- unchecked((int)srcUnit),
- NativeMethods.NullHandleRef,
- null,
- NativeMethods.NullHandleRef);
-
- Marshal.FreeHGlobal(buf);
-
- //ignore emf metafile error
- IgnoreMetafileErrors(image, ref status);
-
- //check error status sensitive to TS problems
- CheckErrorStatus(status);
+ try
+ {
+ int status = SafeNativeMethods.Gdip.GdipDrawImagePointsRect(
+ new HandleRef(this, NativeGraphics),
+ new HandleRef(image, image.nativeImage),
+ new HandleRef(this, buf),
+ destPoints.Length,
+ srcRect.X,
+ srcRect.Y,
+ srcRect.Width,
+ srcRect.Height,
+ unchecked((int)srcUnit),
+ NativeMethods.NullHandleRef,
+ null,
+ NativeMethods.NullHandleRef);
+ IgnoreMetafileErrors(image, ref status);
+ CheckErrorStatus(status);
+ }
+ finally
+ {
+ Marshal.FreeHGlobal(buf);
+ }
}
- [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Naming", "CA1704:IdentifiersShouldBeSpelledCorrectly")]
+ [SuppressMessage("Microsoft.Naming", "CA1704:IdentifiersShouldBeSpelledCorrectly")]
public void DrawImage(Image image, PointF[] destPoints, RectangleF srcRect,
GraphicsUnit srcUnit, ImageAttributes imageAttr)
{
DrawImage(image, destPoints, srcRect, srcUnit, imageAttr, null, 0);
}
- [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Naming", "CA1704:IdentifiersShouldBeSpelledCorrectly")]
+ [SuppressMessage("Microsoft.Naming", "CA1704:IdentifiersShouldBeSpelledCorrectly")]
public void DrawImage(Image image, PointF[] destPoints, RectangleF srcRect,
GraphicsUnit srcUnit, ImageAttributes imageAttr,
DrawImageAbort callback)
@@ -2475,60 +2596,66 @@ namespace System.Drawing
DrawImage(image, destPoints, srcRect, srcUnit, imageAttr, callback, 0);
}
- [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Naming", "CA1704:IdentifiersShouldBeSpelledCorrectly")]
+ [SuppressMessage("Microsoft.Naming", "CA1704:IdentifiersShouldBeSpelledCorrectly")]
public void DrawImage(Image image, PointF[] destPoints, RectangleF srcRect,
GraphicsUnit srcUnit, ImageAttributes imageAttr,
DrawImageAbort callback, int callbackData)
{
if (destPoints == null)
- throw new ArgumentNullException("destPoints");
+ {
+ throw new ArgumentNullException(nameof(destPoints));
+ }
+
if (image == null)
- throw new ArgumentNullException("image");
+ {
+ throw new ArgumentNullException(nameof(image));
+ }
int count = destPoints.Length;
-
if (count != 3 && count != 4)
+ {
throw new ArgumentException(SR.Format(SR.GdiplusDestPointsInvalidLength));
+ }
IntPtr buf = SafeNativeMethods.Gdip.ConvertPointToMemory(destPoints);
-
- int status = SafeNativeMethods.Gdip.GdipDrawImagePointsRect(
- new HandleRef(this, NativeGraphics),
- new HandleRef(image, image.nativeImage),
- new HandleRef(this, buf),
- destPoints.Length,
- srcRect.X,
- srcRect.Y,
- srcRect.Width,
- srcRect.Height,
- unchecked((int)srcUnit),
- new HandleRef(imageAttr, (imageAttr != null ? imageAttr.nativeImageAttributes : IntPtr.Zero)),
- callback,
- new HandleRef(null, (IntPtr)callbackData));
-
- Marshal.FreeHGlobal(buf);
-
- //ignore emf metafile error
- IgnoreMetafileErrors(image, ref status);
-
- //check error status sensitive to TS problems
- CheckErrorStatus(status);
+ try
+ {
+ int status = SafeNativeMethods.Gdip.GdipDrawImagePointsRect(
+ new HandleRef(this, NativeGraphics),
+ new HandleRef(image, image.nativeImage),
+ new HandleRef(this, buf),
+ destPoints.Length,
+ srcRect.X,
+ srcRect.Y,
+ srcRect.Width,
+ srcRect.Height,
+ unchecked((int)srcUnit),
+ new HandleRef(imageAttr, (imageAttr != null ? imageAttr.nativeImageAttributes : IntPtr.Zero)),
+ callback,
+ new HandleRef(null, (IntPtr)callbackData));
+ IgnoreMetafileErrors(image, ref status);
+ CheckErrorStatus(status);
+ }
+ finally
+ {
+ Marshal.FreeHGlobal(buf);
+ }
}
- [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Naming", "CA1704:IdentifiersShouldBeSpelledCorrectly")]
+ [SuppressMessage("Microsoft.Naming", "CA1704:IdentifiersShouldBeSpelledCorrectly")]
public void DrawImage(Image image, Point[] destPoints, Rectangle srcRect, GraphicsUnit srcUnit)
{
DrawImage(image, destPoints, srcRect, srcUnit, null, null, 0);
}
- [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Naming", "CA1704:IdentifiersShouldBeSpelledCorrectly")]
+ [SuppressMessage("Microsoft.Naming", "CA1704:IdentifiersShouldBeSpelledCorrectly")]
public void DrawImage(Image image, Point[] destPoints, Rectangle srcRect,
GraphicsUnit srcUnit, ImageAttributes imageAttr)
{
DrawImage(image, destPoints, srcRect, srcUnit, imageAttr, null, 0);
}
- [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Naming", "CA1704:IdentifiersShouldBeSpelledCorrectly")]
+ [SuppressMessage("Microsoft.Naming", "CA1704:IdentifiersShouldBeSpelledCorrectly")]
public void DrawImage(Image image, Point[] destPoints, Rectangle srcRect,
GraphicsUnit srcUnit, ImageAttributes imageAttr,
DrawImageAbort callback)
@@ -2536,54 +2663,60 @@ namespace System.Drawing
DrawImage(image, destPoints, srcRect, srcUnit, imageAttr, callback, 0);
}
- [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Naming", "CA1704:IdentifiersShouldBeSpelledCorrectly")]
+ [SuppressMessage("Microsoft.Naming", "CA1704:IdentifiersShouldBeSpelledCorrectly")]
public void DrawImage(Image image, Point[] destPoints, Rectangle srcRect,
GraphicsUnit srcUnit, ImageAttributes imageAttr,
DrawImageAbort callback, int callbackData)
{
if (destPoints == null)
- throw new ArgumentNullException("destPoints");
+ {
+ throw new ArgumentNullException(nameof(destPoints));
+ }
+
if (image == null)
- throw new ArgumentNullException("image");
+ {
+ throw new ArgumentNullException(nameof(image));
+ }
int count = destPoints.Length;
-
if (count != 3 && count != 4)
+ {
throw new ArgumentException(SR.Format(SR.GdiplusDestPointsInvalidLength));
+ }
IntPtr buf = SafeNativeMethods.Gdip.ConvertPointToMemory(destPoints);
-
- int status = SafeNativeMethods.Gdip.GdipDrawImagePointsRectI(
- new HandleRef(this, NativeGraphics),
- new HandleRef(image, image.nativeImage),
- new HandleRef(this, buf),
- destPoints.Length,
- srcRect.X,
- srcRect.Y,
- srcRect.Width,
- srcRect.Height,
- unchecked((int)srcUnit),
- new HandleRef(imageAttr, (imageAttr != null ? imageAttr.nativeImageAttributes : IntPtr.Zero)),
- callback,
- new HandleRef(null, (IntPtr)callbackData));
-
- Marshal.FreeHGlobal(buf);
-
- //ignore emf metafile error
- IgnoreMetafileErrors(image, ref status);
-
- //check error status sensitive to TS problems
- CheckErrorStatus(status);
+ try
+ {
+ int status = SafeNativeMethods.Gdip.GdipDrawImagePointsRectI(
+ new HandleRef(this, NativeGraphics),
+ new HandleRef(image, image.nativeImage),
+ new HandleRef(this, buf),
+ destPoints.Length,
+ srcRect.X,
+ srcRect.Y,
+ srcRect.Width,
+ srcRect.Height,
+ unchecked((int)srcUnit),
+ new HandleRef(imageAttr, (imageAttr != null ? imageAttr.nativeImageAttributes : IntPtr.Zero)),
+ callback,
+ new HandleRef(null, (IntPtr)callbackData));
+ IgnoreMetafileErrors(image, ref status);
+ CheckErrorStatus(status);
+ }
+ finally
+ {
+ Marshal.FreeHGlobal(buf);
+ }
}
- [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Naming", "CA1704:IdentifiersShouldBeSpelledCorrectly")]
+ [SuppressMessage("Microsoft.Naming", "CA1704:IdentifiersShouldBeSpelledCorrectly")]
public void DrawImage(Image image, Rectangle destRect, float srcX, float srcY,
float srcWidth, float srcHeight, GraphicsUnit srcUnit)
{
DrawImage(image, destRect, srcX, srcY, srcWidth, srcHeight, srcUnit, null);
}
- [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Naming", "CA1704:IdentifiersShouldBeSpelledCorrectly")]
+ [SuppressMessage("Microsoft.Naming", "CA1704:IdentifiersShouldBeSpelledCorrectly")]
public void DrawImage(Image image, Rectangle destRect, float srcX, float srcY,
float srcWidth, float srcHeight, GraphicsUnit srcUnit,
ImageAttributes imageAttrs)
@@ -2591,7 +2724,7 @@ namespace System.Drawing
DrawImage(image, destRect, srcX, srcY, srcWidth, srcHeight, srcUnit, imageAttrs, null);
}
- [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Naming", "CA1704:IdentifiersShouldBeSpelledCorrectly")]
+ [SuppressMessage("Microsoft.Naming", "CA1704:IdentifiersShouldBeSpelledCorrectly")]
public void DrawImage(Image image, Rectangle destRect, float srcX, float srcY,
float srcWidth, float srcHeight, GraphicsUnit srcUnit,
ImageAttributes imageAttrs, DrawImageAbort callback)
@@ -2600,13 +2733,15 @@ namespace System.Drawing
}
- [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Naming", "CA1704:IdentifiersShouldBeSpelledCorrectly")]
+ [SuppressMessage("Microsoft.Naming", "CA1704:IdentifiersShouldBeSpelledCorrectly")]
public void DrawImage(Image image, Rectangle destRect, float srcX, float srcY,
float srcWidth, float srcHeight, GraphicsUnit srcUnit, ImageAttributes imageAttrs,
DrawImageAbort callback, IntPtr callbackData)
{
if (image == null)
- throw new ArgumentNullException("image");
+ {
+ throw new ArgumentNullException(nameof(image));
+ }
int status = SafeNativeMethods.Gdip.GdipDrawImageRectRect(
new HandleRef(this, NativeGraphics),
@@ -2623,22 +2758,18 @@ namespace System.Drawing
new HandleRef(imageAttrs, (imageAttrs != null ? imageAttrs.nativeImageAttributes : IntPtr.Zero)),
callback,
new HandleRef(null, callbackData));
-
- //ignore emf metafile error
IgnoreMetafileErrors(image, ref status);
-
- //check error status sensitive to TS problems
CheckErrorStatus(status);
}
- [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Naming", "CA1704:IdentifiersShouldBeSpelledCorrectly")]
+ [SuppressMessage("Microsoft.Naming", "CA1704:IdentifiersShouldBeSpelledCorrectly")]
public void DrawImage(Image image, Rectangle destRect, int srcX, int srcY,
int srcWidth, int srcHeight, GraphicsUnit srcUnit)
{
DrawImage(image, destRect, srcX, srcY, srcWidth, srcHeight, srcUnit, null);
}
- [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Naming", "CA1704:IdentifiersShouldBeSpelledCorrectly")]
+ [SuppressMessage("Microsoft.Naming", "CA1704:IdentifiersShouldBeSpelledCorrectly")]
public void DrawImage(Image image, Rectangle destRect, int srcX, int srcY,
int srcWidth, int srcHeight, GraphicsUnit srcUnit,
ImageAttributes imageAttr)
@@ -2646,7 +2777,7 @@ namespace System.Drawing
DrawImage(image, destRect, srcX, srcY, srcWidth, srcHeight, srcUnit, imageAttr, null);
}
- [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Naming", "CA1704:IdentifiersShouldBeSpelledCorrectly")]
+ [SuppressMessage("Microsoft.Naming", "CA1704:IdentifiersShouldBeSpelledCorrectly")]
public void DrawImage(Image image, Rectangle destRect, int srcX, int srcY,
int srcWidth, int srcHeight, GraphicsUnit srcUnit,
ImageAttributes imageAttr, DrawImageAbort callback)
@@ -2654,13 +2785,15 @@ namespace System.Drawing
DrawImage(image, destRect, srcX, srcY, srcWidth, srcHeight, srcUnit, imageAttr, callback, IntPtr.Zero);
}
- [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Naming", "CA1704:IdentifiersShouldBeSpelledCorrectly")]
+ [SuppressMessage("Microsoft.Naming", "CA1704:IdentifiersShouldBeSpelledCorrectly")]
public void DrawImage(Image image, Rectangle destRect, int srcX, int srcY,
int srcWidth, int srcHeight, GraphicsUnit srcUnit, ImageAttributes imageAttrs,
DrawImageAbort callback, IntPtr callbackData)
{
if (image == null)
- throw new ArgumentNullException("image");
+ {
+ throw new ArgumentNullException(nameof(image));
+ }
int status = SafeNativeMethods.Gdip.GdipDrawImageRectRectI(
new HandleRef(this, NativeGraphics),
@@ -2677,30 +2810,26 @@ namespace System.Drawing
new HandleRef(imageAttrs, (imageAttrs != null ? imageAttrs.nativeImageAttributes : IntPtr.Zero)),
callback,
new HandleRef(null, callbackData));
-
- //ignore emf metafile error
IgnoreMetafileErrors(image, ref status);
-
- //check error status sensitive to TS problems
CheckErrorStatus(status);
}
- [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Naming", "CA1704:IdentifiersShouldBeSpelledCorrectly")]
+ [SuppressMessage("Microsoft.Naming", "CA1704:IdentifiersShouldBeSpelledCorrectly")]
public void EnumerateMetafile(Metafile metafile, PointF destPoint,
EnumerateMetafileProc callback)
{
EnumerateMetafile(metafile, destPoint, callback, IntPtr.Zero);
}
- [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Naming", "CA1704:IdentifiersShouldBeSpelledCorrectly")]
+ [SuppressMessage("Microsoft.Naming", "CA1704:IdentifiersShouldBeSpelledCorrectly")]
public void EnumerateMetafile(Metafile metafile, PointF destPoint,
EnumerateMetafileProc callback, IntPtr callbackData)
{
EnumerateMetafile(metafile, destPoint, callback, callbackData, null);
}
- [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Naming", "CA1704:IdentifiersShouldBeSpelledCorrectly")]
- [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Design", "CA1011:ConsiderPassingBaseTypesAsParameters")]
+ [SuppressMessage("Microsoft.Naming", "CA1704:IdentifiersShouldBeSpelledCorrectly")]
+ [SuppressMessage("Microsoft.Design", "CA1011:ConsiderPassingBaseTypesAsParameters")]
public void EnumerateMetafile(Metafile metafile, PointF destPoint,
EnumerateMetafileProc callback, IntPtr callbackData,
ImageAttributes imageAttr)
@@ -2714,29 +2843,25 @@ namespace System.Drawing
callback,
new HandleRef(null, callbackData),
new HandleRef(imageAttr, ia));
-
- if (status != SafeNativeMethods.Gdip.Ok)
- {
- throw SafeNativeMethods.Gdip.StatusException(status);
- }
+ SafeNativeMethods.Gdip.CheckStatus(status);
}
- [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Naming", "CA1704:IdentifiersShouldBeSpelledCorrectly")]
+ [SuppressMessage("Microsoft.Naming", "CA1704:IdentifiersShouldBeSpelledCorrectly")]
public void EnumerateMetafile(Metafile metafile, Point destPoint,
EnumerateMetafileProc callback)
{
EnumerateMetafile(metafile, destPoint, callback, IntPtr.Zero);
}
- [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Naming", "CA1704:IdentifiersShouldBeSpelledCorrectly")]
+ [SuppressMessage("Microsoft.Naming", "CA1704:IdentifiersShouldBeSpelledCorrectly")]
public void EnumerateMetafile(Metafile metafile, Point destPoint,
EnumerateMetafileProc callback, IntPtr callbackData)
{
EnumerateMetafile(metafile, destPoint, callback, callbackData, null);
}
- [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Naming", "CA1704:IdentifiersShouldBeSpelledCorrectly")]
- [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Design", "CA1011:ConsiderPassingBaseTypesAsParameters")]
+ [SuppressMessage("Microsoft.Naming", "CA1704:IdentifiersShouldBeSpelledCorrectly")]
+ [SuppressMessage("Microsoft.Design", "CA1011:ConsiderPassingBaseTypesAsParameters")]
public void EnumerateMetafile(Metafile metafile, Point destPoint,
EnumerateMetafileProc callback, IntPtr callbackData,
ImageAttributes imageAttr)
@@ -2750,29 +2875,25 @@ namespace System.Drawing
callback,
new HandleRef(null, callbackData),
new HandleRef(imageAttr, ia));
-
- if (status != SafeNativeMethods.Gdip.Ok)
- {
- throw SafeNativeMethods.Gdip.StatusException(status);
- }
+ SafeNativeMethods.Gdip.CheckStatus(status);
}
- [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Naming", "CA1704:IdentifiersShouldBeSpelledCorrectly")]
+ [SuppressMessage("Microsoft.Naming", "CA1704:IdentifiersShouldBeSpelledCorrectly")]
public void EnumerateMetafile(Metafile metafile, RectangleF destRect,
EnumerateMetafileProc callback)
{
EnumerateMetafile(metafile, destRect, callback, IntPtr.Zero);
}
- [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Naming", "CA1704:IdentifiersShouldBeSpelledCorrectly")]
+ [SuppressMessage("Microsoft.Naming", "CA1704:IdentifiersShouldBeSpelledCorrectly")]
public void EnumerateMetafile(Metafile metafile, RectangleF destRect,
EnumerateMetafileProc callback, IntPtr callbackData)
{
EnumerateMetafile(metafile, destRect, callback, callbackData, null);
}
- [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Naming", "CA1704:IdentifiersShouldBeSpelledCorrectly")]
- [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Design", "CA1011:ConsiderPassingBaseTypesAsParameters")]
+ [SuppressMessage("Microsoft.Naming", "CA1704:IdentifiersShouldBeSpelledCorrectly")]
+ [SuppressMessage("Microsoft.Design", "CA1011:ConsiderPassingBaseTypesAsParameters")]
public void EnumerateMetafile(Metafile metafile, RectangleF destRect,
EnumerateMetafileProc callback, IntPtr callbackData,
ImageAttributes imageAttr)
@@ -2780,8 +2901,7 @@ namespace System.Drawing
IntPtr mf = (metafile == null ? IntPtr.Zero : metafile.nativeImage);
IntPtr ia = (imageAttr == null ? IntPtr.Zero : imageAttr.nativeImageAttributes);
- GPRECTF grf = new GPRECTF(destRect);
-
+ var grf = new GPRECTF(destRect);
int status = SafeNativeMethods.Gdip.GdipEnumerateMetafileDestRect(
new HandleRef(this, NativeGraphics),
new HandleRef(metafile, mf),
@@ -2789,29 +2909,25 @@ namespace System.Drawing
callback,
new HandleRef(null, callbackData),
new HandleRef(imageAttr, ia));
-
- if (status != SafeNativeMethods.Gdip.Ok)
- {
- throw SafeNativeMethods.Gdip.StatusException(status);
- }
+ SafeNativeMethods.Gdip.CheckStatus(status);
}
- [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Naming", "CA1704:IdentifiersShouldBeSpelledCorrectly")]
+ [SuppressMessage("Microsoft.Naming", "CA1704:IdentifiersShouldBeSpelledCorrectly")]
public void EnumerateMetafile(Metafile metafile, Rectangle destRect,
EnumerateMetafileProc callback)
{
EnumerateMetafile(metafile, destRect, callback, IntPtr.Zero);
}
- [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Naming", "CA1704:IdentifiersShouldBeSpelledCorrectly")]
+ [SuppressMessage("Microsoft.Naming", "CA1704:IdentifiersShouldBeSpelledCorrectly")]
public void EnumerateMetafile(Metafile metafile, Rectangle destRect,
EnumerateMetafileProc callback, IntPtr callbackData)
{
EnumerateMetafile(metafile, destRect, callback, callbackData, null);
}
- [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Naming", "CA1704:IdentifiersShouldBeSpelledCorrectly")]
- [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Design", "CA1011:ConsiderPassingBaseTypesAsParameters")]
+ [SuppressMessage("Microsoft.Naming", "CA1704:IdentifiersShouldBeSpelledCorrectly")]
+ [SuppressMessage("Microsoft.Design", "CA1011:ConsiderPassingBaseTypesAsParameters")]
public void EnumerateMetafile(Metafile metafile, Rectangle destRect,
EnumerateMetafileProc callback, IntPtr callbackData,
ImageAttributes imageAttr)
@@ -2819,42 +2935,41 @@ namespace System.Drawing
IntPtr mf = (metafile == null ? IntPtr.Zero : metafile.nativeImage);
IntPtr ia = (imageAttr == null ? IntPtr.Zero : imageAttr.nativeImageAttributes);
- GPRECT gprect = new GPRECT(destRect);
+ var gprect = new GPRECT(destRect);
int status = SafeNativeMethods.Gdip.GdipEnumerateMetafileDestRectI(new HandleRef(this, NativeGraphics),
new HandleRef(metafile, mf),
ref gprect,
callback,
new HandleRef(null, callbackData),
new HandleRef(imageAttr, ia));
-
- if (status != SafeNativeMethods.Gdip.Ok)
- {
- throw SafeNativeMethods.Gdip.StatusException(status);
- }
+ SafeNativeMethods.Gdip.CheckStatus(status);
}
- [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Naming", "CA1704:IdentifiersShouldBeSpelledCorrectly")]
+ [SuppressMessage("Microsoft.Naming", "CA1704:IdentifiersShouldBeSpelledCorrectly")]
public void EnumerateMetafile(Metafile metafile, PointF[] destPoints,
EnumerateMetafileProc callback)
{
EnumerateMetafile(metafile, destPoints, callback, IntPtr.Zero);
}
- [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Naming", "CA1704:IdentifiersShouldBeSpelledCorrectly")]
+ [SuppressMessage("Microsoft.Naming", "CA1704:IdentifiersShouldBeSpelledCorrectly")]
public void EnumerateMetafile(Metafile metafile, PointF[] destPoints,
EnumerateMetafileProc callback, IntPtr callbackData)
{
EnumerateMetafile(metafile, destPoints, callback, IntPtr.Zero, null);
}
- [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Naming", "CA1704:IdentifiersShouldBeSpelledCorrectly")]
- [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Design", "CA1011:ConsiderPassingBaseTypesAsParameters")]
+ [SuppressMessage("Microsoft.Naming", "CA1704:IdentifiersShouldBeSpelledCorrectly")]
+ [SuppressMessage("Microsoft.Design", "CA1011:ConsiderPassingBaseTypesAsParameters")]
public void EnumerateMetafile(Metafile metafile, PointF[] destPoints,
EnumerateMetafileProc callback, IntPtr callbackData,
ImageAttributes imageAttr)
{
if (destPoints == null)
- throw new ArgumentNullException("destPoints");
+ {
+ throw new ArgumentNullException(nameof(destPoints));
+ }
+
if (destPoints.Length != 3)
{
throw new ArgumentException(SR.Format(SR.GdiplusDestPointsInvalidParallelogram));
@@ -2864,45 +2979,48 @@ namespace System.Drawing
IntPtr ia = (imageAttr == null ? IntPtr.Zero : imageAttr.nativeImageAttributes);
IntPtr points = SafeNativeMethods.Gdip.ConvertPointToMemory(destPoints);
-
- int status = SafeNativeMethods.Gdip.GdipEnumerateMetafileDestPoints(new HandleRef(this, NativeGraphics),
- new HandleRef(metafile, mf),
- points,
- destPoints.Length,
- callback,
- new HandleRef(null, callbackData),
- new HandleRef(imageAttr, ia));
- Marshal.FreeHGlobal(points);
-
- if (status != SafeNativeMethods.Gdip.Ok)
+ try
{
- throw SafeNativeMethods.Gdip.StatusException(status);
+ int status = SafeNativeMethods.Gdip.GdipEnumerateMetafileDestPoints(new HandleRef(this, NativeGraphics),
+ new HandleRef(metafile, mf),
+ points,
+ destPoints.Length,
+ callback,
+ new HandleRef(null, callbackData),
+ new HandleRef(imageAttr, ia));
+ SafeNativeMethods.Gdip.CheckStatus(status);
+ }
+ finally
+ {
+ Marshal.FreeHGlobal(points);
}
}
-
- [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Naming", "CA1704:IdentifiersShouldBeSpelledCorrectly")]
+ [SuppressMessage("Microsoft.Naming", "CA1704:IdentifiersShouldBeSpelledCorrectly")]
public void EnumerateMetafile(Metafile metafile, Point[] destPoints,
EnumerateMetafileProc callback)
{
EnumerateMetafile(metafile, destPoints, callback, IntPtr.Zero);
}
- [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Naming", "CA1704:IdentifiersShouldBeSpelledCorrectly")]
+ [SuppressMessage("Microsoft.Naming", "CA1704:IdentifiersShouldBeSpelledCorrectly")]
public void EnumerateMetafile(Metafile metafile, Point[] destPoints,
EnumerateMetafileProc callback, IntPtr callbackData)
{
EnumerateMetafile(metafile, destPoints, callback, callbackData, null);
}
- [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Naming", "CA1704:IdentifiersShouldBeSpelledCorrectly")]
- [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Design", "CA1011:ConsiderPassingBaseTypesAsParameters")]
+ [SuppressMessage("Microsoft.Naming", "CA1704:IdentifiersShouldBeSpelledCorrectly")]
+ [SuppressMessage("Microsoft.Design", "CA1011:ConsiderPassingBaseTypesAsParameters")]
public void EnumerateMetafile(Metafile metafile, Point[] destPoints,
EnumerateMetafileProc callback, IntPtr callbackData,
ImageAttributes imageAttr)
{
if (destPoints == null)
- throw new ArgumentNullException("destPoints");
+ {
+ throw new ArgumentNullException(nameof(destPoints));
+ }
+
if (destPoints.Length != 3)
{
throw new ArgumentException(SR.Format(SR.GdiplusDestPointsInvalidParallelogram));
@@ -2912,23 +3030,24 @@ namespace System.Drawing
IntPtr ia = (imageAttr == null ? IntPtr.Zero : imageAttr.nativeImageAttributes);
IntPtr points = SafeNativeMethods.Gdip.ConvertPointToMemory(destPoints);
-
- int status = SafeNativeMethods.Gdip.GdipEnumerateMetafileDestPointsI(new HandleRef(this, NativeGraphics),
- new HandleRef(metafile, mf),
- points,
- destPoints.Length,
- callback,
- new HandleRef(null, callbackData),
- new HandleRef(imageAttr, ia));
- Marshal.FreeHGlobal(points);
-
- if (status != SafeNativeMethods.Gdip.Ok)
+ try
{
- throw SafeNativeMethods.Gdip.StatusException(status);
+ int status = SafeNativeMethods.Gdip.GdipEnumerateMetafileDestPointsI(new HandleRef(this, NativeGraphics),
+ new HandleRef(metafile, mf),
+ points,
+ destPoints.Length,
+ callback,
+ new HandleRef(null, callbackData),
+ new HandleRef(imageAttr, ia));
+ SafeNativeMethods.Gdip.CheckStatus(status);
+ }
+ finally
+ {
+ Marshal.FreeHGlobal(points);
}
}
- [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Naming", "CA1704:IdentifiersShouldBeSpelledCorrectly")]
+ [SuppressMessage("Microsoft.Naming", "CA1704:IdentifiersShouldBeSpelledCorrectly")]
public void EnumerateMetafile(Metafile metafile, PointF destPoint,
RectangleF srcRect, GraphicsUnit srcUnit,
EnumerateMetafileProc callback)
@@ -2936,7 +3055,7 @@ namespace System.Drawing
EnumerateMetafile(metafile, destPoint, srcRect, srcUnit, callback, IntPtr.Zero);
}
- [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Naming", "CA1704:IdentifiersShouldBeSpelledCorrectly")]
+ [SuppressMessage("Microsoft.Naming", "CA1704:IdentifiersShouldBeSpelledCorrectly")]
public void EnumerateMetafile(Metafile metafile, PointF destPoint,
RectangleF srcRect, GraphicsUnit srcUnit,
EnumerateMetafileProc callback, IntPtr callbackData)
@@ -2944,8 +3063,8 @@ namespace System.Drawing
EnumerateMetafile(metafile, destPoint, srcRect, srcUnit, callback, callbackData, null);
}
- [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Naming", "CA1704:IdentifiersShouldBeSpelledCorrectly")]
- [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Design", "CA1011:ConsiderPassingBaseTypesAsParameters")]
+ [SuppressMessage("Microsoft.Naming", "CA1704:IdentifiersShouldBeSpelledCorrectly")]
+ [SuppressMessage("Microsoft.Design", "CA1011:ConsiderPassingBaseTypesAsParameters")]
public void EnumerateMetafile(Metafile metafile, PointF destPoint,
RectangleF srcRect, GraphicsUnit unit,
EnumerateMetafileProc callback, IntPtr callbackData,
@@ -2954,8 +3073,7 @@ namespace System.Drawing
IntPtr mf = (metafile == null ? IntPtr.Zero : metafile.nativeImage);
IntPtr ia = (imageAttr == null ? IntPtr.Zero : imageAttr.nativeImageAttributes);
- GPRECTF grf = new GPRECTF(srcRect);
-
+ var grf = new GPRECTF(srcRect);
int status = SafeNativeMethods.Gdip.GdipEnumerateMetafileSrcRectDestPoint(new HandleRef(this, NativeGraphics),
new HandleRef(metafile, mf),
new GPPOINTF(destPoint),
@@ -2964,14 +3082,10 @@ namespace System.Drawing
callback,
new HandleRef(null, callbackData),
new HandleRef(imageAttr, ia));
-
- if (status != SafeNativeMethods.Gdip.Ok)
- {
- throw SafeNativeMethods.Gdip.StatusException(status);
- }
+ SafeNativeMethods.Gdip.CheckStatus(status);
}
- [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Naming", "CA1704:IdentifiersShouldBeSpelledCorrectly")]
+ [SuppressMessage("Microsoft.Naming", "CA1704:IdentifiersShouldBeSpelledCorrectly")]
public void EnumerateMetafile(Metafile metafile, Point destPoint,
Rectangle srcRect, GraphicsUnit srcUnit,
EnumerateMetafileProc callback)
@@ -2979,7 +3093,7 @@ namespace System.Drawing
EnumerateMetafile(metafile, destPoint, srcRect, srcUnit, callback, IntPtr.Zero);
}
- [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Naming", "CA1704:IdentifiersShouldBeSpelledCorrectly")]
+ [SuppressMessage("Microsoft.Naming", "CA1704:IdentifiersShouldBeSpelledCorrectly")]
public void EnumerateMetafile(Metafile metafile, Point destPoint,
Rectangle srcRect, GraphicsUnit srcUnit,
EnumerateMetafileProc callback, IntPtr callbackData)
@@ -2987,8 +3101,8 @@ namespace System.Drawing
EnumerateMetafile(metafile, destPoint, srcRect, srcUnit, callback, callbackData, null);
}
- [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Naming", "CA1704:IdentifiersShouldBeSpelledCorrectly")]
- [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Design", "CA1011:ConsiderPassingBaseTypesAsParameters")]
+ [SuppressMessage("Microsoft.Naming", "CA1704:IdentifiersShouldBeSpelledCorrectly")]
+ [SuppressMessage("Microsoft.Design", "CA1011:ConsiderPassingBaseTypesAsParameters")]
public void EnumerateMetafile(Metafile metafile, Point destPoint,
Rectangle srcRect, GraphicsUnit unit,
EnumerateMetafileProc callback, IntPtr callbackData,
@@ -2997,9 +3111,8 @@ namespace System.Drawing
IntPtr mf = (metafile == null ? IntPtr.Zero : metafile.nativeImage);
IntPtr ia = (imageAttr == null ? IntPtr.Zero : imageAttr.nativeImageAttributes);
- GPPOINT gppoint = new GPPOINT(destPoint);
- GPRECT gprect = new GPRECT(srcRect);
-
+ var gppoint = new GPPOINT(destPoint);
+ var gprect = new GPRECT(srcRect);
int status = SafeNativeMethods.Gdip.GdipEnumerateMetafileSrcRectDestPointI(new HandleRef(this, NativeGraphics),
new HandleRef(metafile, mf),
gppoint,
@@ -3008,14 +3121,10 @@ namespace System.Drawing
callback,
new HandleRef(null, callbackData),
new HandleRef(imageAttr, ia));
-
- if (status != SafeNativeMethods.Gdip.Ok)
- {
- throw SafeNativeMethods.Gdip.StatusException(status);
- }
+ SafeNativeMethods.Gdip.CheckStatus(status);
}
- [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Naming", "CA1704:IdentifiersShouldBeSpelledCorrectly")]
+ [SuppressMessage("Microsoft.Naming", "CA1704:IdentifiersShouldBeSpelledCorrectly")]
public void EnumerateMetafile(Metafile metafile, RectangleF destRect,
RectangleF srcRect, GraphicsUnit srcUnit,
EnumerateMetafileProc callback)
@@ -3023,7 +3132,7 @@ namespace System.Drawing
EnumerateMetafile(metafile, destRect, srcRect, srcUnit, callback, IntPtr.Zero);
}
- [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Naming", "CA1704:IdentifiersShouldBeSpelledCorrectly")]
+ [SuppressMessage("Microsoft.Naming", "CA1704:IdentifiersShouldBeSpelledCorrectly")]
public void EnumerateMetafile(Metafile metafile, RectangleF destRect,
RectangleF srcRect, GraphicsUnit srcUnit,
EnumerateMetafileProc callback, IntPtr callbackData)
@@ -3031,8 +3140,8 @@ namespace System.Drawing
EnumerateMetafile(metafile, destRect, srcRect, srcUnit, callback, callbackData, null);
}
- [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Naming", "CA1704:IdentifiersShouldBeSpelledCorrectly")]
- [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Design", "CA1011:ConsiderPassingBaseTypesAsParameters")]
+ [SuppressMessage("Microsoft.Naming", "CA1704:IdentifiersShouldBeSpelledCorrectly")]
+ [SuppressMessage("Microsoft.Design", "CA1011:ConsiderPassingBaseTypesAsParameters")]
public void EnumerateMetafile(Metafile metafile, RectangleF destRect,
RectangleF srcRect, GraphicsUnit unit,
EnumerateMetafileProc callback, IntPtr callbackData,
@@ -3041,9 +3150,8 @@ namespace System.Drawing
IntPtr mf = (metafile == null ? IntPtr.Zero : metafile.nativeImage);
IntPtr ia = (imageAttr == null ? IntPtr.Zero : imageAttr.nativeImageAttributes);
- GPRECTF grfdest = new GPRECTF(destRect);
- GPRECTF grfsrc = new GPRECTF(srcRect);
-
+ var grfdest = new GPRECTF(destRect);
+ var grfsrc = new GPRECTF(srcRect);
int status = SafeNativeMethods.Gdip.GdipEnumerateMetafileSrcRectDestRect(
new HandleRef(this, NativeGraphics),
new HandleRef(metafile, mf),
@@ -3053,14 +3161,10 @@ namespace System.Drawing
callback,
new HandleRef(null, callbackData),
new HandleRef(imageAttr, ia));
-
- if (status != SafeNativeMethods.Gdip.Ok)
- {
- throw SafeNativeMethods.Gdip.StatusException(status);
- }
+ SafeNativeMethods.Gdip.CheckStatus(status);
}
- [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Naming", "CA1704:IdentifiersShouldBeSpelledCorrectly")]
+ [SuppressMessage("Microsoft.Naming", "CA1704:IdentifiersShouldBeSpelledCorrectly")]
public void EnumerateMetafile(Metafile metafile, Rectangle destRect,
Rectangle srcRect, GraphicsUnit srcUnit,
EnumerateMetafileProc callback)
@@ -3068,7 +3172,7 @@ namespace System.Drawing
EnumerateMetafile(metafile, destRect, srcRect, srcUnit, callback, IntPtr.Zero);
}
- [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Naming", "CA1704:IdentifiersShouldBeSpelledCorrectly")]
+ [SuppressMessage("Microsoft.Naming", "CA1704:IdentifiersShouldBeSpelledCorrectly")]
public void EnumerateMetafile(Metafile metafile, Rectangle destRect,
Rectangle srcRect, GraphicsUnit srcUnit,
EnumerateMetafileProc callback, IntPtr callbackData)
@@ -3076,8 +3180,8 @@ namespace System.Drawing
EnumerateMetafile(metafile, destRect, srcRect, srcUnit, callback, callbackData, null);
}
- [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Design", "CA1011:ConsiderPassingBaseTypesAsParameters")]
- [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Naming", "CA1704:IdentifiersShouldBeSpelledCorrectly")]
+ [SuppressMessage("Microsoft.Design", "CA1011:ConsiderPassingBaseTypesAsParameters")]
+ [SuppressMessage("Microsoft.Naming", "CA1704:IdentifiersShouldBeSpelledCorrectly")]
public void EnumerateMetafile(Metafile metafile, Rectangle destRect,
Rectangle srcRect, GraphicsUnit unit,
EnumerateMetafileProc callback, IntPtr callbackData,
@@ -3086,9 +3190,8 @@ namespace System.Drawing
IntPtr mf = (metafile == null ? IntPtr.Zero : metafile.nativeImage);
IntPtr ia = (imageAttr == null ? IntPtr.Zero : imageAttr.nativeImageAttributes);
- GPRECT gpDest = new GPRECT(destRect);
- GPRECT gpSrc = new GPRECT(srcRect);
-
+ var gpDest = new GPRECT(destRect);
+ var gpSrc = new GPRECT(srcRect);
int status = SafeNativeMethods.Gdip.GdipEnumerateMetafileSrcRectDestRectI(new HandleRef(this, NativeGraphics),
new HandleRef(metafile, mf),
ref gpDest,
@@ -3097,14 +3200,10 @@ namespace System.Drawing
callback,
new HandleRef(null, callbackData),
new HandleRef(imageAttr, ia));
-
- if (status != SafeNativeMethods.Gdip.Ok)
- {
- throw SafeNativeMethods.Gdip.StatusException(status);
- }
+ SafeNativeMethods.Gdip.CheckStatus(status);
}
- [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Naming", "CA1704:IdentifiersShouldBeSpelledCorrectly")]
+ [SuppressMessage("Microsoft.Naming", "CA1704:IdentifiersShouldBeSpelledCorrectly")]
public void EnumerateMetafile(Metafile metafile, PointF[] destPoints,
RectangleF srcRect, GraphicsUnit srcUnit,
EnumerateMetafileProc callback)
@@ -3112,7 +3211,7 @@ namespace System.Drawing
EnumerateMetafile(metafile, destPoints, srcRect, srcUnit, callback, IntPtr.Zero);
}
- [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Naming", "CA1704:IdentifiersShouldBeSpelledCorrectly")]
+ [SuppressMessage("Microsoft.Naming", "CA1704:IdentifiersShouldBeSpelledCorrectly")]
public void EnumerateMetafile(Metafile metafile, PointF[] destPoints,
RectangleF srcRect, GraphicsUnit srcUnit,
EnumerateMetafileProc callback, IntPtr callbackData)
@@ -3120,15 +3219,17 @@ namespace System.Drawing
EnumerateMetafile(metafile, destPoints, srcRect, srcUnit, callback, callbackData, null);
}
- [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Design", "CA1011:ConsiderPassingBaseTypesAsParameters")]
- [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Naming", "CA1704:IdentifiersShouldBeSpelledCorrectly")]
+ [SuppressMessage("Microsoft.Design", "CA1011:ConsiderPassingBaseTypesAsParameters")]
+ [SuppressMessage("Microsoft.Naming", "CA1704:IdentifiersShouldBeSpelledCorrectly")]
public void EnumerateMetafile(Metafile metafile, PointF[] destPoints,
RectangleF srcRect, GraphicsUnit unit,
EnumerateMetafileProc callback, IntPtr callbackData,
ImageAttributes imageAttr)
{
if (destPoints == null)
- throw new ArgumentNullException("destPoints");
+ {
+ throw new ArgumentNullException(nameof(destPoints));
+ }
if (destPoints.Length != 3)
{
throw new ArgumentException(SR.Format(SR.GdiplusDestPointsInvalidParallelogram));
@@ -3138,27 +3239,28 @@ namespace System.Drawing
IntPtr ia = (imageAttr == null ? IntPtr.Zero : imageAttr.nativeImageAttributes);
IntPtr buffer = SafeNativeMethods.Gdip.ConvertPointToMemory(destPoints);
-
- GPRECTF grf = new GPRECTF(srcRect);
-
- int status = SafeNativeMethods.Gdip.GdipEnumerateMetafileSrcRectDestPoints(new HandleRef(this, NativeGraphics),
- new HandleRef(metafile, mf),
- buffer,
- destPoints.Length,
- ref grf,
- unchecked((int)unit),
- callback,
- new HandleRef(null, callbackData),
- new HandleRef(imageAttr, ia));
- Marshal.FreeHGlobal(buffer);
-
- if (status != SafeNativeMethods.Gdip.Ok)
+ try
{
- throw SafeNativeMethods.Gdip.StatusException(status);
+ var grf = new GPRECTF(srcRect);
+
+ int status = SafeNativeMethods.Gdip.GdipEnumerateMetafileSrcRectDestPoints(new HandleRef(this, NativeGraphics),
+ new HandleRef(metafile, mf),
+ buffer,
+ destPoints.Length,
+ ref grf,
+ unchecked((int)unit),
+ callback,
+ new HandleRef(null, callbackData),
+ new HandleRef(imageAttr, ia));
+ SafeNativeMethods.Gdip.CheckStatus(status);
+ }
+ finally
+ {
+ Marshal.FreeHGlobal(buffer);
}
}
- [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Naming", "CA1704:IdentifiersShouldBeSpelledCorrectly")]
+ [SuppressMessage("Microsoft.Naming", "CA1704:IdentifiersShouldBeSpelledCorrectly")]
public void EnumerateMetafile(Metafile metafile, Point[] destPoints,
Rectangle srcRect, GraphicsUnit srcUnit,
EnumerateMetafileProc callback)
@@ -3166,7 +3268,7 @@ namespace System.Drawing
EnumerateMetafile(metafile, destPoints, srcRect, srcUnit, callback, IntPtr.Zero);
}
- [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Naming", "CA1704:IdentifiersShouldBeSpelledCorrectly")]
+ [SuppressMessage("Microsoft.Naming", "CA1704:IdentifiersShouldBeSpelledCorrectly")]
public void EnumerateMetafile(Metafile metafile, Point[] destPoints,
Rectangle srcRect, GraphicsUnit srcUnit,
EnumerateMetafileProc callback, IntPtr callbackData)
@@ -3174,15 +3276,18 @@ namespace System.Drawing
EnumerateMetafile(metafile, destPoints, srcRect, srcUnit, callback, callbackData, null);
}
- [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Design", "CA1011:ConsiderPassingBaseTypesAsParameters")]
- [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Naming", "CA1704:IdentifiersShouldBeSpelledCorrectly")]
+ [SuppressMessage("Microsoft.Design", "CA1011:ConsiderPassingBaseTypesAsParameters")]
+ [SuppressMessage("Microsoft.Naming", "CA1704:IdentifiersShouldBeSpelledCorrectly")]
public void EnumerateMetafile(Metafile metafile, Point[] destPoints,
Rectangle srcRect, GraphicsUnit unit,
EnumerateMetafileProc callback, IntPtr callbackData,
ImageAttributes imageAttr)
{
if (destPoints == null)
- throw new ArgumentNullException("destPoints");
+ {
+ throw new ArgumentNullException(nameof(destPoints));
+ }
+
if (destPoints.Length != 3)
{
throw new ArgumentException(SR.Format(SR.GdiplusDestPointsInvalidParallelogram));
@@ -3192,203 +3297,143 @@ namespace System.Drawing
IntPtr ia = (imageAttr == null ? IntPtr.Zero : imageAttr.nativeImageAttributes);
IntPtr buffer = SafeNativeMethods.Gdip.ConvertPointToMemory(destPoints);
-
- GPRECT gpSrc = new GPRECT(srcRect);
-
- int status = SafeNativeMethods.Gdip.GdipEnumerateMetafileSrcRectDestPointsI(new HandleRef(this, NativeGraphics),
- new HandleRef(metafile, mf),
- buffer,
- destPoints.Length,
- ref gpSrc,
- unchecked((int)unit),
- callback,
- new HandleRef(null, callbackData),
- new HandleRef(imageAttr, ia));
- Marshal.FreeHGlobal(buffer);
-
- if (status != SafeNativeMethods.Gdip.Ok)
+ try
{
- throw SafeNativeMethods.Gdip.StatusException(status);
+ var gpSrc = new GPRECT(srcRect);
+ int status = SafeNativeMethods.Gdip.GdipEnumerateMetafileSrcRectDestPointsI(new HandleRef(this, NativeGraphics),
+ new HandleRef(metafile, mf),
+ buffer,
+ destPoints.Length,
+ ref gpSrc,
+ unchecked((int)unit),
+ callback,
+ new HandleRef(null, callbackData),
+ new HandleRef(imageAttr, ia));
+ SafeNativeMethods.Gdip.CheckStatus(status);
+ }
+ finally
+ {
+ Marshal.FreeHGlobal(buffer);
}
}
-
- public void SetClip(Graphics g)
- {
- SetClip(g, CombineMode.Replace);
- }
+ public void SetClip(Graphics g) => SetClip(g, CombineMode.Replace);
public void SetClip(Graphics g, CombineMode combineMode)
{
if (g == null)
{
- throw new ArgumentNullException("g");
+ throw new ArgumentNullException(nameof(g));
}
int status = SafeNativeMethods.Gdip.GdipSetClipGraphics(new HandleRef(this, NativeGraphics), new HandleRef(g, g.NativeGraphics), combineMode);
-
- if (status != SafeNativeMethods.Gdip.Ok)
- {
- throw SafeNativeMethods.Gdip.StatusException(status);
- }
+ SafeNativeMethods.Gdip.CheckStatus(status);
}
- public void SetClip(Rectangle rect)
- {
- SetClip(rect, CombineMode.Replace);
- }
+ public void SetClip(Rectangle rect) => SetClip(rect, CombineMode.Replace);
public void SetClip(Rectangle rect, CombineMode combineMode)
{
int status = SafeNativeMethods.Gdip.GdipSetClipRectI(new HandleRef(this, NativeGraphics), rect.X, rect.Y,
rect.Width, rect.Height, combineMode);
-
- if (status != SafeNativeMethods.Gdip.Ok)
- {
- throw SafeNativeMethods.Gdip.StatusException(status);
- }
+ SafeNativeMethods.Gdip.CheckStatus(status);
}
- public void SetClip(RectangleF rect)
- {
- SetClip(rect, CombineMode.Replace);
- }
+ public void SetClip(RectangleF rect) => SetClip(rect, CombineMode.Replace);
public void SetClip(RectangleF rect, CombineMode combineMode)
{
int status = SafeNativeMethods.Gdip.GdipSetClipRect(new HandleRef(this, NativeGraphics), rect.X, rect.Y,
rect.Width, rect.Height, combineMode);
-
- if (status != SafeNativeMethods.Gdip.Ok)
- {
- throw SafeNativeMethods.Gdip.StatusException(status);
- }
+ SafeNativeMethods.Gdip.CheckStatus(status);
}
- public void SetClip(GraphicsPath path)
- {
- SetClip(path, CombineMode.Replace);
- }
+ public void SetClip(GraphicsPath path) => SetClip(path, CombineMode.Replace);
public void SetClip(GraphicsPath path, CombineMode combineMode)
{
if (path == null)
{
- throw new ArgumentNullException("path");
+ throw new ArgumentNullException(nameof(path));
}
- int status = SafeNativeMethods.Gdip.GdipSetClipPath(new HandleRef(this, NativeGraphics), new HandleRef(path, path.nativePath), combineMode);
- if (status != SafeNativeMethods.Gdip.Ok)
- {
- throw SafeNativeMethods.Gdip.StatusException(status);
- }
+ int status = SafeNativeMethods.Gdip.GdipSetClipPath(new HandleRef(this, NativeGraphics), new HandleRef(path, path.nativePath), combineMode);
+ SafeNativeMethods.Gdip.CheckStatus(status);
}
public void SetClip(Region region, CombineMode combineMode)
{
if (region == null)
{
- throw new ArgumentNullException("region");
+ throw new ArgumentNullException(nameof(region));
}
int status = SafeNativeMethods.Gdip.GdipSetClipRegion(new HandleRef(this, NativeGraphics), new HandleRef(region, region._nativeRegion), combineMode);
-
- if (status != SafeNativeMethods.Gdip.Ok)
- {
- throw SafeNativeMethods.Gdip.StatusException(status);
- }
+ SafeNativeMethods.Gdip.CheckStatus(status);
}
public void IntersectClip(Rectangle rect)
{
int status = SafeNativeMethods.Gdip.GdipSetClipRectI(new HandleRef(this, NativeGraphics), rect.X, rect.Y,
rect.Width, rect.Height, CombineMode.Intersect);
-
- if (status != SafeNativeMethods.Gdip.Ok)
- {
- throw SafeNativeMethods.Gdip.StatusException(status);
- }
+ SafeNativeMethods.Gdip.CheckStatus(status);
}
public void IntersectClip(RectangleF rect)
{
int status = SafeNativeMethods.Gdip.GdipSetClipRect(new HandleRef(this, NativeGraphics), rect.X, rect.Y,
rect.Width, rect.Height, CombineMode.Intersect);
-
- if (status != SafeNativeMethods.Gdip.Ok)
- {
- throw SafeNativeMethods.Gdip.StatusException(status);
- }
+ SafeNativeMethods.Gdip.CheckStatus(status);
}
public void IntersectClip(Region region)
{
if (region == null)
- throw new ArgumentNullException("region");
+ {
+ throw new ArgumentNullException(nameof(region));
+ }
int status = SafeNativeMethods.Gdip.GdipSetClipRegion(new HandleRef(this, NativeGraphics), new HandleRef(region, region._nativeRegion),
CombineMode.Intersect);
-
- if (status != SafeNativeMethods.Gdip.Ok)
- {
- throw SafeNativeMethods.Gdip.StatusException(status);
- }
+ SafeNativeMethods.Gdip.CheckStatus(status);
}
public void ExcludeClip(Rectangle rect)
{
int status = SafeNativeMethods.Gdip.GdipSetClipRectI(new HandleRef(this, NativeGraphics), rect.X, rect.Y,
rect.Width, rect.Height, CombineMode.Exclude);
-
- if (status != SafeNativeMethods.Gdip.Ok)
- {
- throw SafeNativeMethods.Gdip.StatusException(status);
- }
+ SafeNativeMethods.Gdip.CheckStatus(status);
}
public void ExcludeClip(Region region)
{
if (region == null)
- throw new ArgumentNullException("region");
+ {
+ throw new ArgumentNullException(nameof(region));
+ }
int status = SafeNativeMethods.Gdip.GdipSetClipRegion(new HandleRef(this, NativeGraphics),
new HandleRef(region, region._nativeRegion),
CombineMode.Exclude);
-
- if (status != SafeNativeMethods.Gdip.Ok)
- {
- throw SafeNativeMethods.Gdip.StatusException(status);
- }
+ SafeNativeMethods.Gdip.CheckStatus(status);
}
public void ResetClip()
{
int status = SafeNativeMethods.Gdip.GdipResetClip(new HandleRef(this, NativeGraphics));
-
- if (status != SafeNativeMethods.Gdip.Ok)
- {
- throw SafeNativeMethods.Gdip.StatusException(status);
- }
+ SafeNativeMethods.Gdip.CheckStatus(status);
}
public void TranslateClip(float dx, float dy)
{
int status = SafeNativeMethods.Gdip.GdipTranslateClip(new HandleRef(this, NativeGraphics), dx, dy);
-
- if (status != SafeNativeMethods.Gdip.Ok)
- {
- throw SafeNativeMethods.Gdip.StatusException(status);
- }
+ SafeNativeMethods.Gdip.CheckStatus(status);
}
public void TranslateClip(int dx, int dy)
{
int status = SafeNativeMethods.Gdip.GdipTranslateClip(new HandleRef(this, NativeGraphics), dx, dy);
-
- if (status != SafeNativeMethods.Gdip.Ok)
- {
- throw SafeNativeMethods.Gdip.StatusException(status);
- }
+ SafeNativeMethods.Gdip.CheckStatus(status);
}
/// <summary>
@@ -3396,13 +3441,13 @@ namespace System.Drawing
/// When BeginContainer() is called, a copy of the current context is pushed into the GDI+ context stack, it keeps track of the
/// absolute clipping and transform but reset the public properties so it looks like a brand new context.
/// When Save() is called, a copy of the current context is also pushed in the GDI+ stack but the public clipping and transform
- /// properties are not reset (cumulative). Consecutive Save context are ignored with the exception of the top one which contains
+ /// properties are not reset (cumulative). Consecutive Save context are ignored with the exception of the top one which contains
/// all previous information.
/// The return value is an object array where the first element contains the cumulative clip region and the second the cumulative
/// translate transform matrix.
/// WARNING: This method is for internal FX support only.
/// </summary>
- [StrongNameIdentityPermissionAttribute(SecurityAction.LinkDemand, Name = "System.Windows.Forms", PublicKey = "0x00000000000000000400000000000000")]
+ [StrongNameIdentityPermission(SecurityAction.LinkDemand, Name = "System.Windows.Forms", PublicKey = "0x00000000000000000400000000000000")]
[EditorBrowsable(EditorBrowsableState.Never)]
public object GetContextInfo()
{
@@ -3430,7 +3475,7 @@ namespace System.Drawing
if (!currentOffset.IsEmpty)
{
// The location of the GDI+ clip region is relative to the coordinate origin after any translate transform
- // has been applied. We need to intersect regions using the same coordinate origin relative to the previous
+ // has been applied. We need to intersect regions using the same coordinate origin relative to the previous
// context.
cumulClip.Translate(currentOffset.X, currentOffset.Y);
totalOffset.X += currentOffset.X;
@@ -3471,35 +3516,22 @@ namespace System.Drawing
{
get
{
- Region region = new Region();
-
+ var region = new Region();
int status = SafeNativeMethods.Gdip.GdipGetClip(new HandleRef(this, NativeGraphics), new HandleRef(region, region._nativeRegion));
-
- if (status != SafeNativeMethods.Gdip.Ok)
- {
- throw SafeNativeMethods.Gdip.StatusException(status);
- }
+ SafeNativeMethods.Gdip.CheckStatus(status);
return region;
}
- set
- {
- SetClip(value, CombineMode.Replace);
- }
+ set => SetClip(value, CombineMode.Replace);
}
public RectangleF ClipBounds
{
get
{
- GPRECTF rect = new GPRECTF();
-
+ var rect = new GPRECTF();
int status = SafeNativeMethods.Gdip.GdipGetClipBounds(new HandleRef(this, NativeGraphics), ref rect);
-
- if (status != SafeNativeMethods.Gdip.Ok)
- {
- throw SafeNativeMethods.Gdip.StatusException(status);
- }
+ SafeNativeMethods.Gdip.CheckStatus(status);
return rect.ToRectangleF();
}
@@ -3510,13 +3542,8 @@ namespace System.Drawing
get
{
int isEmpty;
-
int status = SafeNativeMethods.Gdip.GdipIsClipEmpty(new HandleRef(this, NativeGraphics), out isEmpty);
-
- if (status != SafeNativeMethods.Gdip.Ok)
- {
- throw SafeNativeMethods.Gdip.StatusException(status);
- }
+ SafeNativeMethods.Gdip.CheckStatus(status);
return isEmpty != 0;
}
@@ -3526,23 +3553,14 @@ namespace System.Drawing
{
get
{
- if (PrintingHelper != null)
+ if (PrintingHelper is PrintPreviewGraphics ppGraphics)
{
- PrintPreviewGraphics ppGraphics = PrintingHelper as PrintPreviewGraphics;
- if (ppGraphics != null)
- {
- return ppGraphics.VisibleClipBounds;
- }
+ return ppGraphics.VisibleClipBounds;
}
- GPRECTF rect = new GPRECTF();
-
+ var rect = new GPRECTF();
int status = SafeNativeMethods.Gdip.GdipGetVisibleClipBounds(new HandleRef(this, NativeGraphics), ref rect);
-
- if (status != SafeNativeMethods.Gdip.Ok)
- {
- throw SafeNativeMethods.Gdip.StatusException(status);
- }
+ SafeNativeMethods.Gdip.CheckStatus(status);
return rect.ToRectangleF();
}
@@ -3553,53 +3571,32 @@ namespace System.Drawing
get
{
int isEmpty;
-
int status = SafeNativeMethods.Gdip.GdipIsVisibleClipEmpty(new HandleRef(this, NativeGraphics), out isEmpty);
-
- if (status != SafeNativeMethods.Gdip.Ok)
- {
- throw SafeNativeMethods.Gdip.StatusException(status);
- }
+ SafeNativeMethods.Gdip.CheckStatus(status);
return isEmpty != 0;
}
}
- public bool IsVisible(int x, int y)
- {
- return IsVisible(new Point(x, y));
- }
+ public bool IsVisible(int x, int y) => IsVisible(new Point(x, y));
public bool IsVisible(Point point)
{
int isVisible;
-
int status = SafeNativeMethods.Gdip.GdipIsVisiblePointI(new HandleRef(this, NativeGraphics), point.X, point.Y, out isVisible);
-
- if (status != SafeNativeMethods.Gdip.Ok)
- {
- throw SafeNativeMethods.Gdip.StatusException(status);
- }
+ SafeNativeMethods.Gdip.CheckStatus(status);
return isVisible != 0;
}
- public bool IsVisible(float x, float y)
- {
- return IsVisible(new PointF(x, y));
- }
+ public bool IsVisible(float x, float y) => IsVisible(new PointF(x, y));
public bool IsVisible(PointF point)
{
int isVisible;
-
int status = SafeNativeMethods.Gdip.GdipIsVisiblePoint(new HandleRef(this, NativeGraphics), point.X, point.Y, out isVisible);
-
- if (status != SafeNativeMethods.Gdip.Ok)
- {
- throw SafeNativeMethods.Gdip.StatusException(status);
- }
+ SafeNativeMethods.Gdip.CheckStatus(status);
return isVisible != 0;
}
@@ -3612,14 +3609,9 @@ namespace System.Drawing
public bool IsVisible(Rectangle rect)
{
int isVisible;
-
int status = SafeNativeMethods.Gdip.GdipIsVisibleRectI(new HandleRef(this, NativeGraphics), rect.X, rect.Y,
rect.Width, rect.Height, out isVisible);
-
- if (status != SafeNativeMethods.Gdip.Ok)
- {
- throw SafeNativeMethods.Gdip.StatusException(status);
- }
+ SafeNativeMethods.Gdip.CheckStatus(status);
return isVisible != 0;
}
@@ -3632,14 +3624,9 @@ namespace System.Drawing
public bool IsVisible(RectangleF rect)
{
int isVisible;
-
int status = SafeNativeMethods.Gdip.GdipIsVisibleRect(new HandleRef(this, NativeGraphics), rect.X, rect.Y,
rect.Width, rect.Height, out isVisible);
-
- if (status != SafeNativeMethods.Gdip.Ok)
- {
- throw SafeNativeMethods.Gdip.StatusException(status);
- }
+ SafeNativeMethods.Gdip.CheckStatus(status);
return isVisible != 0;
}
@@ -3661,7 +3648,7 @@ namespace System.Drawing
}
/// <summary>
- /// Pops all contexts from the specified one included. The specified context is becoming the current context.
+ /// Pops all contexts from the specified one included. The specified context is becoming the current context.
/// </summary>
private void PopContext(int currentContextState)
{
@@ -3684,9 +3671,8 @@ namespace System.Drawing
public GraphicsState Save()
{
- GraphicsContext context = new GraphicsContext(this);
+ var context = new GraphicsContext(this);
int state = 0;
-
int status = SafeNativeMethods.Gdip.GdipSaveGraphics(new HandleRef(this, NativeGraphics), out state);
if (status != SafeNativeMethods.Gdip.Ok)
@@ -3705,22 +3691,18 @@ namespace System.Drawing
public void Restore(GraphicsState gstate)
{
int status = SafeNativeMethods.Gdip.GdipRestoreGraphics(new HandleRef(this, NativeGraphics), gstate.nativeState);
-
- if (status != SafeNativeMethods.Gdip.Ok)
- {
- throw SafeNativeMethods.Gdip.StatusException(status);
- }
+ SafeNativeMethods.Gdip.CheckStatus(status);
PopContext(gstate.nativeState);
}
public GraphicsContainer BeginContainer(RectangleF dstrect, RectangleF srcrect, GraphicsUnit unit)
{
- GraphicsContext context = new GraphicsContext(this);
+ var context = new GraphicsContext(this);
int state = 0;
- GPRECTF dstf = dstrect.ToGPRECTF();
- GPRECTF srcf = srcrect.ToGPRECTF();
+ var dstf = new GPRECTF(dstrect);
+ var srcf = new GPRECTF(srcrect);
int status = SafeNativeMethods.Gdip.GdipBeginContainer(new HandleRef(this, NativeGraphics), ref dstf,
ref srcf, unchecked((int)unit), out state);
@@ -3739,9 +3721,8 @@ namespace System.Drawing
public GraphicsContainer BeginContainer()
{
- GraphicsContext context = new GraphicsContext(this);
+ var context = new GraphicsContext(this);
int state = 0;
-
int status = SafeNativeMethods.Gdip.GdipBeginContainer2(new HandleRef(this, NativeGraphics), out state);
if (status != SafeNativeMethods.Gdip.Ok)
@@ -3760,26 +3741,22 @@ namespace System.Drawing
{
if (container == null)
{
- throw new ArgumentNullException("container");
+ throw new ArgumentNullException(nameof(container));
}
int status = SafeNativeMethods.Gdip.GdipEndContainer(new HandleRef(this, NativeGraphics), container.nativeGraphicsContainer);
-
- if (status != SafeNativeMethods.Gdip.Ok)
- {
- throw SafeNativeMethods.Gdip.StatusException(status);
- }
+ SafeNativeMethods.Gdip.CheckStatus(status);
PopContext(container.nativeGraphicsContainer);
}
public GraphicsContainer BeginContainer(Rectangle dstrect, Rectangle srcrect, GraphicsUnit unit)
{
- GraphicsContext context = new GraphicsContext(this);
+ var context = new GraphicsContext(this);
int state = 0;
- GPRECT gpDest = new GPRECT(dstrect);
- GPRECT gpSrc = new GPRECT(srcrect);
+ var gpDest = new GPRECT(dstrect);
+ var gpSrc = new GPRECT(srcrect);
int status = SafeNativeMethods.Gdip.GdipBeginContainerI(new HandleRef(this, NativeGraphics), ref gpDest,
ref gpSrc, unchecked((int)unit), out state);
@@ -3800,15 +3777,11 @@ namespace System.Drawing
{
if (data == null)
{
- throw new ArgumentNullException("data");
+ throw new ArgumentNullException(nameof(data));
}
int status = SafeNativeMethods.Gdip.GdipComment(new HandleRef(this, NativeGraphics), data.Length, data);
-
- if (status != SafeNativeMethods.Gdip.Ok)
- {
- throw SafeNativeMethods.Gdip.StatusException(status);
- }
+ SafeNativeMethods.Gdip.CheckStatus(status);
}
public static IntPtr GetHalftonePalette()
@@ -3840,10 +3813,9 @@ namespace System.Drawing
}
}
-
/// <summary>
/// GDI+ will return a 'generic error' with specific win32 last error codes when
- /// a terminal server session has been closed, minimized, etc... We don't want
+ /// a terminal server session has been closed, minimized, etc... We don't want
/// to throw when this happens, so we'll guard against this by looking at the
/// 'last win32 error code' and checking to see if it is either 1) access denied
/// or 2) proc not found and then ignore it.
@@ -3856,29 +3828,31 @@ namespace System.Drawing
/// </summary>
private void CheckErrorStatus(int status)
{
- if (status != SafeNativeMethods.Gdip.Ok)
+ if (status == SafeNativeMethods.Gdip.Ok)
+ {
+ return;
+ }
+
+ // Generic error from GDI+ can be GenericError or Win32Error.
+ if (status == SafeNativeMethods.Gdip.GenericError || status == SafeNativeMethods.Gdip.Win32Error)
{
- // Generic error from GDI+ can be GenericError or Win32Error.
- if (status == SafeNativeMethods.Gdip.GenericError || status == SafeNativeMethods.Gdip.Win32Error)
+ int error = Marshal.GetLastWin32Error();
+ if (error == SafeNativeMethods.ERROR_ACCESS_DENIED || error == SafeNativeMethods.ERROR_PROC_NOT_FOUND ||
+ //here, we'll check to see if we are in a term. session...
+ (((UnsafeNativeMethods.GetSystemMetrics(NativeMethods.SM_REMOTESESSION) & 0x00000001) != 0) && (error == 0)))
{
- int error = Marshal.GetLastWin32Error();
- if (error == SafeNativeMethods.ERROR_ACCESS_DENIED || error == SafeNativeMethods.ERROR_PROC_NOT_FOUND ||
- //here, we'll check to see if we are in a term. session...
- (((UnsafeNativeMethods.GetSystemMetrics(NativeMethods.SM_REMOTESESSION) & 0x00000001) != 0) && (error == 0)))
- {
- return;
- }
+ return;
}
-
- //legitimate error, throw our status exception
- throw SafeNativeMethods.Gdip.StatusException(status);
}
+
+ // Legitimate error, throw our status exception.
+ throw SafeNativeMethods.Gdip.StatusException(status);
}
/// <summary>
/// GDI+ will return a 'generic error' when we attempt to draw an Emf
- /// image with width/height == 1. Here, we will hack around this by
- /// resetting the errorstatus. Note that we don't do simple arg checking
+ /// image with width/height == 1. Here, we will hack around this by
+ /// resetting the errorstatus. Note that we don't do simple arg checking
/// for height || width == 1 here because transforms can be applied to
/// the Graphics object making it difficult to identify this scenario.
/// </summary>
@@ -3893,4 +3867,4 @@ namespace System.Drawing
}
}
}
-} \ No newline at end of file
+}
diff --git a/src/System.Drawing.Common/src/System/Drawing/Image.cs b/src/System.Drawing.Common/src/System/Drawing/Image.cs
index efb1efa209..450e474fba 100644
--- a/src/System.Drawing.Common/src/System/Drawing/Image.cs
+++ b/src/System.Drawing.Common/src/System/Drawing/Image.cs
@@ -981,7 +981,7 @@ namespace System.Drawing
{
for (int i = 0; i < count; i++)
{
- guids[i] = (Guid)UnsafeNativeMethods.PtrToStructure((IntPtr)((long)buffer + size * i), typeof(Guid));
+ guids[i] = (Guid)Marshal.PtrToStructure((IntPtr)((long)buffer + size * i), typeof(Guid));
}
}
finally
diff --git a/src/System.Drawing.Common/src/System/Drawing/Imaging/EncoderParameters.cs b/src/System.Drawing.Common/src/System/Drawing/Imaging/EncoderParameters.cs
index 7d739f25f0..93f0c0249a 100644
--- a/src/System.Drawing.Common/src/System/Drawing/Imaging/EncoderParameters.cs
+++ b/src/System.Drawing.Common/src/System/Drawing/Imaging/EncoderParameters.cs
@@ -94,7 +94,7 @@ namespace System.Drawing.Imaging
for (int i = 0; i < count; i++)
{
- Guid guid = (Guid)UnsafeNativeMethods.PtrToStructure((IntPtr)(i * size + arrayOffset), typeof(Guid));
+ Guid guid = (Guid)Marshal.PtrToStructure((IntPtr)(i * size + arrayOffset), typeof(Guid));
int numberOfValues = Marshal.ReadInt32((IntPtr)(i * size + arrayOffset + 16));
EncoderParameterValueType type = (EncoderParameterValueType)Marshal.ReadInt32((IntPtr)(i * size + arrayOffset + 20));
IntPtr value = Marshal.ReadIntPtr((IntPtr)(i * size + arrayOffset + 24));
diff --git a/src/System.Drawing.Common/src/System/Drawing/Imaging/ImageCodecInfo.cs b/src/System.Drawing.Common/src/System/Drawing/Imaging/ImageCodecInfo.cs
index 38cace65cd..1bbacc370a 100644
--- a/src/System.Drawing.Common/src/System/Drawing/Imaging/ImageCodecInfo.cs
+++ b/src/System.Drawing.Common/src/System/Drawing/Imaging/ImageCodecInfo.cs
@@ -179,7 +179,7 @@ namespace System.Drawing.Imaging
{
IntPtr curcodec = (IntPtr)((long)memoryStart + (int)Marshal.SizeOf(typeof(ImageCodecInfoPrivate)) * index);
ImageCodecInfoPrivate codecp = new ImageCodecInfoPrivate();
- UnsafeNativeMethods.PtrToStructure(curcodec, codecp);
+ Marshal.PtrToStructure(curcodec, codecp);
codecs[index] = new ImageCodecInfo();
codecs[index].Clsid = codecp.Clsid;
diff --git a/src/System.Drawing.Common/src/System/Drawing/Imaging/Metafile.cs b/src/System.Drawing.Common/src/System/Drawing/Imaging/Metafile.cs
index 9983e78344..53f07e73dd 100644
--- a/src/System.Drawing.Common/src/System/Drawing/Imaging/Metafile.cs
+++ b/src/System.Drawing.Common/src/System/Drawing/Imaging/Metafile.cs
@@ -578,14 +578,14 @@ namespace System.Drawing.Imaging
metafileType == MetafileType.WmfPlaceable)
{
// WMF header
- header.wmf = (MetafileHeaderWmf)UnsafeNativeMethods.PtrToStructure(memory, typeof(MetafileHeaderWmf));
+ header.wmf = (MetafileHeaderWmf)Marshal.PtrToStructure(memory, typeof(MetafileHeaderWmf));
header.emf = null;
}
else
{
// EMF header
header.wmf = null;
- header.emf = (MetafileHeaderEmf)UnsafeNativeMethods.PtrToStructure(memory, typeof(MetafileHeaderEmf));
+ header.emf = (MetafileHeaderEmf)Marshal.PtrToStructure(memory, typeof(MetafileHeaderEmf));
}
}
finally
@@ -626,14 +626,14 @@ namespace System.Drawing.Imaging
metafileType == MetafileType.WmfPlaceable)
{
// WMF header
- header.wmf = (MetafileHeaderWmf)UnsafeNativeMethods.PtrToStructure(memory, typeof(MetafileHeaderWmf));
+ header.wmf = (MetafileHeaderWmf)Marshal.PtrToStructure(memory, typeof(MetafileHeaderWmf));
header.emf = null;
}
else
{
// EMF header
header.wmf = null;
- header.emf = (MetafileHeaderEmf)UnsafeNativeMethods.PtrToStructure(memory, typeof(MetafileHeaderEmf));
+ header.emf = (MetafileHeaderEmf)Marshal.PtrToStructure(memory, typeof(MetafileHeaderEmf));
}
}
finally
@@ -674,14 +674,14 @@ namespace System.Drawing.Imaging
metafileType == MetafileType.WmfPlaceable)
{
// WMF header
- header.wmf = (MetafileHeaderWmf)UnsafeNativeMethods.PtrToStructure(memory, typeof(MetafileHeaderWmf));
+ header.wmf = (MetafileHeaderWmf)Marshal.PtrToStructure(memory, typeof(MetafileHeaderWmf));
header.emf = null;
}
else
{
// EMF header
header.wmf = null;
- header.emf = (MetafileHeaderEmf)UnsafeNativeMethods.PtrToStructure(memory, typeof(MetafileHeaderEmf));
+ header.emf = (MetafileHeaderEmf)Marshal.PtrToStructure(memory, typeof(MetafileHeaderEmf));
}
}
finally
diff --git a/src/System.Drawing.Common/src/System/Drawing/Internal/GPPOINT.cs b/src/System.Drawing.Common/src/System/Drawing/Internal/GPPOINT.cs
index a356967aae..5621eb0837 100644
--- a/src/System.Drawing.Common/src/System/Drawing/Internal/GPPOINT.cs
+++ b/src/System.Drawing.Common/src/System/Drawing/Internal/GPPOINT.cs
@@ -2,10 +2,10 @@
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
+using System.Runtime.InteropServices;
+
namespace System.Drawing.Internal
{
- using System.Runtime.InteropServices;
-
[StructLayout(LayoutKind.Sequential)]
internal class GPPOINT
{
@@ -16,21 +16,10 @@ namespace System.Drawing.Internal
{
}
- internal GPPOINT(PointF pt)
- {
- X = (int)pt.X;
- Y = (int)pt.Y;
- }
-
internal GPPOINT(Point pt)
{
X = pt.X;
Y = pt.Y;
}
-
- internal PointF ToPoint()
- {
- return new PointF(X, Y);
- }
}
}
diff --git a/src/System.Drawing.Common/src/System/Drawing/Internal/GPPOINTF.cs b/src/System.Drawing.Common/src/System/Drawing/Internal/GPPOINTF.cs
index 2265b13dc3..29416f6b0c 100644
--- a/src/System.Drawing.Common/src/System/Drawing/Internal/GPPOINTF.cs
+++ b/src/System.Drawing.Common/src/System/Drawing/Internal/GPPOINTF.cs
@@ -2,10 +2,10 @@
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
+using System.Runtime.InteropServices;
+
namespace System.Drawing.Internal
{
- using System.Runtime.InteropServices;
-
[StructLayout(LayoutKind.Sequential)]
internal class GPPOINTF
{
@@ -22,12 +22,6 @@ namespace System.Drawing.Internal
Y = pt.Y;
}
- internal GPPOINTF(Point pt)
- {
- X = (float)pt.X;
- Y = (float)pt.Y;
- }
-
internal PointF ToPoint()
{
return new PointF(X, Y);
diff --git a/src/System.Drawing.Common/src/System/Drawing/Internal/GPRECT.cs b/src/System.Drawing.Common/src/System/Drawing/Internal/GPRECT.cs
index 321316f08d..f5a2c7f69d 100644
--- a/src/System.Drawing.Common/src/System/Drawing/Internal/GPRECT.cs
+++ b/src/System.Drawing.Common/src/System/Drawing/Internal/GPRECT.cs
@@ -2,10 +2,10 @@
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
+using System.Runtime.InteropServices;
+
namespace System.Drawing.Internal
{
- using System.Runtime.InteropServices;
-
[StructLayout(LayoutKind.Sequential)]
internal struct GPRECT
{
@@ -29,10 +29,5 @@ namespace System.Drawing.Internal
Width = rect.Width;
Height = rect.Height;
}
-
- internal Rectangle ToRectangle()
- {
- return new Rectangle(X, Y, Width, Height);
- }
}
}
diff --git a/src/System.Drawing.Common/src/System/Drawing/Internal/GPRECTF.cs b/src/System.Drawing.Common/src/System/Drawing/Internal/GPRECTF.cs
index 59805efa30..4026aeef1a 100644
--- a/src/System.Drawing.Common/src/System/Drawing/Internal/GPRECTF.cs
+++ b/src/System.Drawing.Common/src/System/Drawing/Internal/GPRECTF.cs
@@ -2,9 +2,10 @@
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
+using System.Runtime.InteropServices;
+
namespace System.Drawing.Internal
{
- using System.Runtime.InteropServices;
[StructLayout(LayoutKind.Sequential)]
internal struct GPRECTF
@@ -30,17 +31,8 @@ namespace System.Drawing.Internal
Height = rect.Height;
}
- internal SizeF SizeF
- {
- get
- {
- return new SizeF(Width, Height);
- }
- }
+ internal SizeF SizeF => new SizeF(Width, Height);
- internal RectangleF ToRectangleF()
- {
- return new RectangleF(X, Y, Width, Height);
- }
+ internal RectangleF ToRectangleF() => new RectangleF(X, Y, Width, Height);
}
}
diff --git a/src/System.Drawing.Common/src/System/Drawing/Internal/GPStream.cs b/src/System.Drawing.Common/src/System/Drawing/Internal/GPStream.cs
index 32bbb36d7b..17e5e3eedd 100644
--- a/src/System.Drawing.Common/src/System/Drawing/Internal/GPStream.cs
+++ b/src/System.Drawing.Common/src/System/Drawing/Internal/GPStream.cs
@@ -2,12 +2,12 @@
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
+using System.IO;
+using System.Runtime.InteropServices;
+using System.Security.Permissions;
+
namespace System.Drawing.Internal
{
- using System.IO;
- using System.Runtime.InteropServices;
- using System.Security.Permissions;
-
internal class GPStream : UnsafeNativeMethods.IStream
{
protected Stream dataStream;
@@ -31,6 +31,7 @@ namespace System.Drawing.Internal
Array.Copy(bytes, newData, bytes.Length);
bytes = newData;
}
+
readLen = stream.Read(bytes, current, ReadBlock);
current += readLen;
} while (readLen != 0);
@@ -45,10 +46,15 @@ namespace System.Drawing.Internal
private void ActualizeVirtualPosition()
{
- if (_virtualPosition == -1) return;
+ if (_virtualPosition == -1)
+ {
+ return;
+ }
if (_virtualPosition > dataStream.Length)
+ {
dataStream.SetLength(_virtualPosition);
+ }
dataStream.Position = _virtualPosition;
@@ -68,28 +74,39 @@ namespace System.Drawing.Internal
ActualizeVirtualPosition();
}
- [
- UIPermission(SecurityAction.Demand, Window = UIPermissionWindow.AllWindows),
- SecurityPermission(SecurityAction.Assert, Flags = SecurityPermissionFlag.UnmanagedCode)
- ]
+ [UIPermission(SecurityAction.Demand, Window = UIPermissionWindow.AllWindows)]
+ [SecurityPermission(SecurityAction.Assert, Flags = SecurityPermissionFlag.UnmanagedCode)]
public virtual long CopyTo(UnsafeNativeMethods.IStream pstm, long cb, long[] pcbRead)
{
int bufsize = 4096; // one page
IntPtr buffer = Marshal.AllocHGlobal(bufsize);
- if (buffer == IntPtr.Zero) throw new OutOfMemoryException();
+ if (buffer == IntPtr.Zero)
+ {
+ throw new OutOfMemoryException();
+ }
+
long written = 0;
try
{
while (written < cb)
{
int toRead = bufsize;
- if (written + toRead > cb) toRead = (int)(cb - written);
+ if (written + toRead > cb)
+ {
+ toRead = (int)(cb - written);
+ }
+
int read = Read(buffer, toRead);
- if (read == 0) break;
+ if (read == 0)
+ {
+ break;
+ }
+
if (pstm.Write(buffer, read) != read)
{
throw EFail("Wrote an incorrect number of bytes");
}
+
written += read;
}
}
@@ -105,11 +122,6 @@ namespace System.Drawing.Internal
return written;
}
- public virtual Stream GetDataStream()
- {
- return dataStream;
- }
-
public virtual void LockRegion(long libOffset, long cb, int dwLockType)
{
}
@@ -124,34 +136,30 @@ namespace System.Drawing.Internal
throw new ExternalException(SR.Format(SR.NotImplemented), SafeNativeMethods.E_NOTIMPL);
}
- public virtual int Read(IntPtr buf, /* cpr: int offset,*/ int length)
+ public virtual int Read(IntPtr buf, int length)
{
- // System.Text.Out.WriteLine("IStream::Read(" + length + ")");
byte[] buffer = new byte[length];
int count = Read(buffer, length);
Marshal.Copy(buffer, 0, buf, length);
return count;
}
- public virtual int Read(byte[] buffer, /* cpr: int offset,*/ int length)
+ public virtual int Read(byte[] buffer, int length)
{
ActualizeVirtualPosition();
return dataStream.Read(buffer, 0, length);
}
- public virtual void Revert()
- {
- NotImplemented();
- }
+ public virtual void Revert() => NotImplemented();
public virtual long Seek(long offset, int origin)
{
- // Console.WriteLine("IStream::Seek("+ offset + ", " + origin + ")");
long pos = _virtualPosition;
if (_virtualPosition == -1)
{
pos = dataStream.Position;
}
+
long len = dataStream.Length;
switch (origin)
{
@@ -189,6 +197,7 @@ namespace System.Drawing.Internal
}
break;
}
+
if (_virtualPosition != -1)
{
return _virtualPosition;
@@ -199,15 +208,11 @@ namespace System.Drawing.Internal
}
}
- public virtual void SetSize(long value)
- {
- dataStream.SetLength(value);
- }
+ public virtual void SetSize(long value) => dataStream.SetLength(value);
public void Stat(IntPtr pstatstg, int grfStatFlag)
{
- STATSTG stats = new STATSTG();
- stats.cbSize = dataStream.Length;
+ var stats = new STATSTG { cbSize = dataStream.Length };
Marshal.StructureToPtr(stats, pstatstg, true);
}
@@ -215,14 +220,14 @@ namespace System.Drawing.Internal
{
}
- public virtual int Write(IntPtr buf, /* cpr: int offset,*/ int length)
+ public virtual int Write(IntPtr buf, int length)
{
byte[] buffer = new byte[length];
Marshal.Copy(buf, buffer, 0, length);
return Write(buffer, length);
}
- public virtual int Write(byte[] buffer, /* cpr: int offset,*/ int length)
+ public virtual int Write(byte[] buffer, int length)
{
ActualizeVirtualPosition();
dataStream.Write(buffer, 0, length);
diff --git a/src/System.Drawing.Common/src/System/Drawing/Internal/ISystemEventTracker.cs b/src/System.Drawing.Common/src/System/Drawing/Internal/ISystemEventTracker.cs
index 3fd555f575..9e2f7b9c2a 100644
--- a/src/System.Drawing.Common/src/System/Drawing/Internal/ISystemEventTracker.cs
+++ b/src/System.Drawing.Common/src/System/Drawing/Internal/ISystemEventTracker.cs
@@ -4,10 +4,8 @@
namespace System.Drawing.Internal
{
- // See SystemColorTracker
internal interface ISystemColorTracker
{
void OnSystemColorChanged();
}
}
-
diff --git a/src/System.Drawing.Common/src/System/Drawing/Internal/RectangleFEx.cs b/src/System.Drawing.Common/src/System/Drawing/Internal/RectangleFEx.cs
deleted file mode 100644
index 16cf97b958..0000000000
--- a/src/System.Drawing.Common/src/System/Drawing/Internal/RectangleFEx.cs
+++ /dev/null
@@ -1,14 +0,0 @@
-// Licensed to the .NET Foundation under one or more agreements.
-// The .NET Foundation licenses this file to you under the MIT license.
-// See the LICENSE file in the project root for more information.
-
-namespace System.Drawing.Internal
-{
- internal static class RectangleFEx
- {
- public static GPRECTF ToGPRECTF(this RectangleF rect)
- {
- return new GPRECTF(rect.X, rect.Y, rect.Width, rect.Height);
- }
- }
-}
diff --git a/src/System.Drawing.Common/src/System/Drawing/Internal/SystemColorTracker.cs b/src/System.Drawing.Common/src/System/Drawing/Internal/SystemColorTracker.cs
index e2ff0fcd7f..5d8937dbf3 100644
--- a/src/System.Drawing.Common/src/System/Drawing/Internal/SystemColorTracker.cs
+++ b/src/System.Drawing.Common/src/System/Drawing/Internal/SystemColorTracker.cs
@@ -3,16 +3,14 @@
// See the LICENSE file in the project root for more information.
#if FEATURE_SYSTEM_EVENTS
+using System.ComponentModel;
+using System.Diagnostics;
+using System.Diagnostics.CodeAnalysis;
+using System.Runtime.InteropServices;
+using Microsoft.Win32;
+
namespace System.Drawing.Internal
{
- using System.Diagnostics;
- using System.Diagnostics.CodeAnalysis;
- using System;
- using System.Drawing;
- using Microsoft.Win32;
- using System.Runtime.InteropServices;
- using System.ComponentModel;
-
// Keeps track of objects that need to be notified of system color change events.
// Mostly this means maintaining a list of weak references.
internal class SystemColorTracker
diff --git a/src/System.Drawing.Common/src/System/Drawing/NativeMethods.cs b/src/System.Drawing.Common/src/System/Drawing/NativeMethods.cs
index ac7a5a67b8..5ff4b7d32a 100644
--- a/src/System.Drawing.Common/src/System/Drawing/NativeMethods.cs
+++ b/src/System.Drawing.Common/src/System/Drawing/NativeMethods.cs
@@ -2,27 +2,17 @@
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
-[assembly: System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Performance", "CA1811:AvoidUncalledPrivateCode", Scope = "member", Target = "System.Drawing.NativeMethods..ctor()")]
+using System.Diagnostics.CodeAnalysis;
+using System.Runtime.InteropServices;
+
+[assembly: SuppressMessage("Microsoft.Performance", "CA1811:AvoidUncalledPrivateCode", Scope = "member", Target = "System.Drawing.NativeMethods..ctor()")]
namespace System.Drawing
{
- using System.Runtime.InteropServices;
-
internal class NativeMethods
{
internal static HandleRef NullHandleRef = new HandleRef(null, IntPtr.Zero);
- public enum RegionFlags
- {
- ERROR = 0,
- NULLREGION = 1,
- SIMPLEREGION = 2,
- COMPLEXREGION = 3,
- }
-
- public const byte PC_NOCOLLAPSE = 0x04;
-
-
public const int MAX_PATH = 260;
internal const int SM_REMOTESESSION = 0x1000;
@@ -38,7 +28,6 @@ namespace System.Drawing
SPI_GETNONCLIENTMETRICS = 41,
DEFAULT_GUI_FONT = 17;
-
[StructLayout(LayoutKind.Sequential)]
internal struct BITMAPINFO_FLAT
{
@@ -54,14 +43,14 @@ namespace System.Drawing
public int bmiHeader_biClrUsed;
public int bmiHeader_biClrImportant;
- [MarshalAs(System.Runtime.InteropServices.UnmanagedType.ByValArray, SizeConst = BITMAPINFO_MAX_COLORSIZE * 4)]
+ [MarshalAs(UnmanagedType.ByValArray, SizeConst = BITMAPINFO_MAX_COLORSIZE * 4)]
public byte[] bmiColors; // RGBQUAD structs... Blue-Green-Red-Reserved, repeat...
}
[StructLayout(LayoutKind.Sequential)]
internal class BITMAPINFOHEADER
{
- public int biSize = 40; // ndirect.DllLib.sizeOf( this );
+ public int biSize = 40;
public int biWidth;
public int biHeight;
public short biPlanes;
@@ -74,8 +63,6 @@ namespace System.Drawing
public int biClrImportant;
}
-
-
[StructLayout(LayoutKind.Sequential)]
internal struct PALETTEENTRY
{
@@ -130,289 +117,5 @@ namespace System.Drawing
#pragma warning restore CS0618
public SafeNativeMethods.LOGFONT lfMessageFont;
}
-
- /* FxCop rule 'AvoidBuildingNonCallableCode' - Left here in case it is needed in the future.
- public static byte[] Win9xHalfTonePalette {
- get {
-
-
- return new byte[] {
- // The first 10 system colors
- 0x00, 0x00, 0x00, 0x00, // 0 Sys Black, gray 0
- 0x80, 0x00, 0x00, 0x00, // 1 Sys Dk Red
- 0x00, 0x80, 0x00, 0x00, // 2 Sys Dk Green
- 0x80, 0x80, 0x00, 0x00, // 3 Sys Dk Yellow
- 0x00, 0x00, 0x80, 0x00, // 4 Sys Dk Blue
- 0x80, 0x00, 0x80, 0x00, // 5 Sys Dk Violet
- 0x00, 0x80, 0x80, 0x00, // 6 Sys Dk Cyan
- 0xC0, 0xC0, 0xC0, 0x00, // 7 Sys Lt Gray, gray 192
-
- // The following two system entries are modified for the desktop.
- 0xC0, 0xDC, 0xC0, 0x00, // 8 Sys 8 - VARIABLE
- 0xA6, 0xCA, 0xF0, 0x00, // 9 Sys 9 - VARIABLE
-
- // Gray scale entries (dark)
- 0x04, 0x04, 0x04, PC_NOCOLLAPSE, // 10 Gray 4
- 0x08, 0x08, 0x08, PC_NOCOLLAPSE, // 11 Gray 8
- 0x0C, 0x0C, 0x0C, PC_NOCOLLAPSE, // 12 Gray 12
- 0x11, 0x11, 0x11, PC_NOCOLLAPSE, // 13 Gray 17
- 0x16, 0x16, 0x16, PC_NOCOLLAPSE, // 14 Gray 22
- 0x1C, 0x1C, 0x1C, PC_NOCOLLAPSE, // 15 Gray 28
- 0x22, 0x22, 0x22, PC_NOCOLLAPSE, // 16 Gray 34
- 0x29, 0x29, 0x29, PC_NOCOLLAPSE, // 17 Gray 41
- 0x55, 0x55, 0x55, PC_NOCOLLAPSE, // 18 Gray 85
- 0x4D, 0x4D, 0x4D, PC_NOCOLLAPSE, // 19 Gray 77
- 0x42, 0x42, 0x42, PC_NOCOLLAPSE, // 20 Gray 66
- 0x39, 0x39, 0x39, PC_NOCOLLAPSE, // 21 Gray 57
-
- // Custom app/OS entries
- 0xFF, 0x7C, 0x80, PC_NOCOLLAPSE, // 22 Salmon
- 0xFF, 0x50, 0x50, PC_NOCOLLAPSE, // 23 Red
- 0xD6, 0x00, 0x93, PC_NOCOLLAPSE, // 24 Purple
- 0xCC, 0xEC, 0xFF, PC_NOCOLLAPSE, // 25 Lt Blue
- 0xEF, 0xD6, 0xC6, PC_NOCOLLAPSE, // 26 Win95 Tan
- 0xE7, 0xE7, 0xD6, PC_NOCOLLAPSE, // 27 Win95 Tan
- 0xAD, 0xA9, 0x90, PC_NOCOLLAPSE, // 28 Win95 Grayish
-
- // Halftone palette entries
- 0x33, 0x00, 0x00, PC_NOCOLLAPSE, // 29
- 0x66, 0x00, 0x00, PC_NOCOLLAPSE, // 30
- 0x99, 0x00, 0x00, PC_NOCOLLAPSE, // 31
- 0xCC, 0x00, 0x00, PC_NOCOLLAPSE, // 32
- 0x00, 0x33, 0x00, PC_NOCOLLAPSE, // 33
- 0x33, 0x33, 0x00, PC_NOCOLLAPSE, // 34
- 0x66, 0x33, 0x00, PC_NOCOLLAPSE, // 35
- 0x99, 0x33, 0x00, PC_NOCOLLAPSE, // 36
- 0xCC, 0x33, 0x00, PC_NOCOLLAPSE, // 37
- 0xFF, 0x33, 0x00, PC_NOCOLLAPSE, // 38
- 0x00, 0x66, 0x00, PC_NOCOLLAPSE, // 39
- 0x33, 0x66, 0x00, PC_NOCOLLAPSE, // 40
- 0x66, 0x66, 0x00, PC_NOCOLLAPSE, // 41
- 0x99, 0x66, 0x00, PC_NOCOLLAPSE, // 42
- 0xCC, 0x66, 0x00, PC_NOCOLLAPSE, // 43
- 0xFF, 0x66, 0x00, PC_NOCOLLAPSE, // 44
- 0x00, 0x99, 0x00, PC_NOCOLLAPSE, // 45
- 0x33, 0x99, 0x00, PC_NOCOLLAPSE, // 46
- 0x66, 0x99, 0x00, PC_NOCOLLAPSE, // 47
- 0x99, 0x99, 0x00, PC_NOCOLLAPSE, // 48
- 0xCC, 0x99, 0x00, PC_NOCOLLAPSE, // 49
- 0xFF, 0x99, 0x00, PC_NOCOLLAPSE, // 50
- 0x00, 0xCC, 0x00, PC_NOCOLLAPSE, // 51
- 0x33, 0xCC, 0x00, PC_NOCOLLAPSE, // 52
- 0x66, 0xCC, 0x00, PC_NOCOLLAPSE, // 53
- 0x99, 0xCC, 0x00, PC_NOCOLLAPSE, // 54
- 0xCC, 0xCC, 0x00, PC_NOCOLLAPSE, // 55
- 0xFF, 0xCC, 0x00, PC_NOCOLLAPSE, // 56
- 0x66, 0xFF, 0x00, PC_NOCOLLAPSE, // 57
- 0x99, 0xFF, 0x00, PC_NOCOLLAPSE, // 58
- 0xCC, 0xFF, 0x00, PC_NOCOLLAPSE, // 59
- 0x00, 0x00, 0x33, PC_NOCOLLAPSE, // 60
- 0x33, 0x00, 0x33, PC_NOCOLLAPSE, // 61
- 0x66, 0x00, 0x33, PC_NOCOLLAPSE, // 62
- 0x99, 0x00, 0x33, PC_NOCOLLAPSE, // 63
- 0xCC, 0x00, 0x33, PC_NOCOLLAPSE, // 64
- 0xFF, 0x00, 0x33, PC_NOCOLLAPSE, // 65
- 0x00, 0x33, 0x33, PC_NOCOLLAPSE, // 66
- 0x33, 0x33, 0x33, PC_NOCOLLAPSE, // 67 Gray 51
- 0x66, 0x33, 0x33, PC_NOCOLLAPSE, // 68
- 0x99, 0x33, 0x33, PC_NOCOLLAPSE, // 69
- 0xCC, 0x33, 0x33, PC_NOCOLLAPSE, // 70
- 0xFF, 0x33, 0x33, PC_NOCOLLAPSE, // 71
- 0x00, 0x66, 0x33, PC_NOCOLLAPSE, // 72
- 0x33, 0x66, 0x33, PC_NOCOLLAPSE, // 73
- 0x66, 0x66, 0x33, PC_NOCOLLAPSE, // 74
- 0x99, 0x66, 0x33, PC_NOCOLLAPSE, // 75
- 0xCC, 0x66, 0x33, PC_NOCOLLAPSE, // 76
- 0xFF, 0x66, 0x33, PC_NOCOLLAPSE, // 77
- 0x00, 0x99, 0x33, PC_NOCOLLAPSE, // 78
- 0x33, 0x99, 0x33, PC_NOCOLLAPSE, // 79
- 0x66, 0x99, 0x33, PC_NOCOLLAPSE, // 80
- 0x99, 0x99, 0x33, PC_NOCOLLAPSE, // 81
- 0xCC, 0x99, 0x33, PC_NOCOLLAPSE, // 82
- 0xFF, 0x99, 0x33, PC_NOCOLLAPSE, // 83
- 0x00, 0xCC, 0x33, PC_NOCOLLAPSE, // 84
- 0x33, 0xCC, 0x33, PC_NOCOLLAPSE, // 85
- 0x66, 0xCC, 0x33, PC_NOCOLLAPSE, // 86
- 0x99, 0xCC, 0x33, PC_NOCOLLAPSE, // 87
- 0xCC, 0xCC, 0x33, PC_NOCOLLAPSE, // 88
- 0xFF, 0xCC, 0x33, PC_NOCOLLAPSE, // 89
- 0x33, 0xFF, 0x33, PC_NOCOLLAPSE, // 90
- 0x66, 0xFF, 0x33, PC_NOCOLLAPSE, // 91
- 0x99, 0xFF, 0x33, PC_NOCOLLAPSE, // 92
- 0xCC, 0xFF, 0x33, PC_NOCOLLAPSE, // 93
- 0xFF, 0xFF, 0x33, PC_NOCOLLAPSE, // 94
- 0x00, 0x00, 0x66, PC_NOCOLLAPSE, // 95
- 0x33, 0x00, 0x66, PC_NOCOLLAPSE, // 96
- 0x66, 0x00, 0x66, PC_NOCOLLAPSE, // 97
- 0x99, 0x00, 0x66, PC_NOCOLLAPSE, // 98
- 0xCC, 0x00, 0x66, PC_NOCOLLAPSE, // 99
- 0xFF, 0x00, 0x66, PC_NOCOLLAPSE, // 100
- 0x00, 0x33, 0x66, PC_NOCOLLAPSE, // 101
- 0x33, 0x33, 0x66, PC_NOCOLLAPSE, // 102
- 0x66, 0x33, 0x66, PC_NOCOLLAPSE, // 103
- 0x99, 0x33, 0x66, PC_NOCOLLAPSE, // 104
- 0xCC, 0x33, 0x66, PC_NOCOLLAPSE, // 105
- 0xFF, 0x33, 0x66, PC_NOCOLLAPSE, // 106
- 0x00, 0x66, 0x66, PC_NOCOLLAPSE, // 107
- 0x33, 0x66, 0x66, PC_NOCOLLAPSE, // 108
- 0x66, 0x66, 0x66, PC_NOCOLLAPSE, // 109 Gray 102
- 0x99, 0x66, 0x66, PC_NOCOLLAPSE, // 110
- 0xCC, 0x66, 0x66, PC_NOCOLLAPSE, // 111
- 0x00, 0x99, 0x66, PC_NOCOLLAPSE, // 112
- 0x33, 0x99, 0x66, PC_NOCOLLAPSE, // 113
- 0x66, 0x99, 0x66, PC_NOCOLLAPSE, // 114
- 0x99, 0x99, 0x66, PC_NOCOLLAPSE, // 115
- 0xCC, 0x99, 0x66, PC_NOCOLLAPSE, // 116
- 0xFF, 0x99, 0x66, PC_NOCOLLAPSE, // 117
- 0x00, 0xCC, 0x66, PC_NOCOLLAPSE, // 118
- 0x33, 0xCC, 0x66, PC_NOCOLLAPSE, // 119
- 0x99, 0xCC, 0x66, PC_NOCOLLAPSE, // 120
- 0xCC, 0xCC, 0x66, PC_NOCOLLAPSE, // 121
- 0xFF, 0xCC, 0x66, PC_NOCOLLAPSE, // 122
- 0x00, 0xFF, 0x66, PC_NOCOLLAPSE, // 123
- 0x33, 0xFF, 0x66, PC_NOCOLLAPSE, // 124
- 0x99, 0xFF, 0x66, PC_NOCOLLAPSE, // 125
- 0xCC, 0xFF, 0x66, PC_NOCOLLAPSE, // 126
- 0xFF, 0x00, 0xCC, PC_NOCOLLAPSE, // 127
- 0xCC, 0x00, 0xFF, PC_NOCOLLAPSE, // 128
- 0x00, 0x99, 0x99, PC_NOCOLLAPSE, // 129
- 0x99, 0x33, 0x99, PC_NOCOLLAPSE, // 130
- 0x99, 0x00, 0x99, PC_NOCOLLAPSE, // 131
- 0xCC, 0x00, 0x99, PC_NOCOLLAPSE, // 132
- 0x00, 0x00, 0x99, PC_NOCOLLAPSE, // 133
- 0x33, 0x33, 0x99, PC_NOCOLLAPSE, // 134
- 0x66, 0x00, 0x99, PC_NOCOLLAPSE, // 135
- 0xCC, 0x33, 0x99, PC_NOCOLLAPSE, // 136
- 0xFF, 0x00, 0x99, PC_NOCOLLAPSE, // 137
- 0x00, 0x66, 0x99, PC_NOCOLLAPSE, // 138
- 0x33, 0x66, 0x99, PC_NOCOLLAPSE, // 139
- 0x66, 0x33, 0x99, PC_NOCOLLAPSE, // 140
- 0x99, 0x66, 0x99, PC_NOCOLLAPSE, // 141
- 0xCC, 0x66, 0x99, PC_NOCOLLAPSE, // 142
- 0xFF, 0x33, 0x99, PC_NOCOLLAPSE, // 143
- 0x33, 0x99, 0x99, PC_NOCOLLAPSE, // 144
- 0x66, 0x99, 0x99, PC_NOCOLLAPSE, // 145
- 0x99, 0x99, 0x99, PC_NOCOLLAPSE, // 146 Gray 153
- 0xCC, 0x99, 0x99, PC_NOCOLLAPSE, // 147
- 0xFF, 0x99, 0x99, PC_NOCOLLAPSE, // 148
- 0x00, 0xCC, 0x99, PC_NOCOLLAPSE, // 149
- 0x33, 0xCC, 0x99, PC_NOCOLLAPSE, // 150
- 0x66, 0xCC, 0x66, PC_NOCOLLAPSE, // 151
- 0x99, 0xCC, 0x99, PC_NOCOLLAPSE, // 152
- 0xCC, 0xCC, 0x99, PC_NOCOLLAPSE, // 153
- 0xFF, 0xCC, 0x99, PC_NOCOLLAPSE, // 154
- 0x00, 0xFF, 0x99, PC_NOCOLLAPSE, // 155
- 0x33, 0xFF, 0x99, PC_NOCOLLAPSE, // 156
- 0x66, 0xCC, 0x99, PC_NOCOLLAPSE, // 157
- 0x99, 0xFF, 0x99, PC_NOCOLLAPSE, // 158
- 0xCC, 0xFF, 0x99, PC_NOCOLLAPSE, // 159
- 0xFF, 0xFF, 0x99, PC_NOCOLLAPSE, // 160
- 0x00, 0x00, 0xCC, PC_NOCOLLAPSE, // 161
- 0x33, 0x00, 0x99, PC_NOCOLLAPSE, // 162
- 0x66, 0x00, 0xCC, PC_NOCOLLAPSE, // 163
- 0x99, 0x00, 0xCC, PC_NOCOLLAPSE, // 164
- 0xCC, 0x00, 0xCC, PC_NOCOLLAPSE, // 165
- 0x00, 0x33, 0x99, PC_NOCOLLAPSE, // 166
- 0x33, 0x33, 0xCC, PC_NOCOLLAPSE, // 167
- 0x66, 0x33, 0xCC, PC_NOCOLLAPSE, // 168
- 0x99, 0x33, 0xCC, PC_NOCOLLAPSE, // 169
- 0xCC, 0x33, 0xCC, PC_NOCOLLAPSE, // 170
- 0xFF, 0x33, 0xCC, PC_NOCOLLAPSE, // 171
- 0x00, 0x66, 0xCC, PC_NOCOLLAPSE, // 172
- 0x33, 0x66, 0xCC, PC_NOCOLLAPSE, // 173
- 0x66, 0x66, 0x99, PC_NOCOLLAPSE, // 174
- 0x99, 0x66, 0xCC, PC_NOCOLLAPSE, // 175
- 0xCC, 0x66, 0xCC, PC_NOCOLLAPSE, // 176
- 0xFF, 0x66, 0x99, PC_NOCOLLAPSE, // 177
- 0x00, 0x99, 0xCC, PC_NOCOLLAPSE, // 178
- 0x33, 0x99, 0xCC, PC_NOCOLLAPSE, // 179
- 0x66, 0x99, 0xCC, PC_NOCOLLAPSE, // 180
- 0x99, 0x99, 0xCC, PC_NOCOLLAPSE, // 181
- 0xCC, 0x99, 0xCC, PC_NOCOLLAPSE, // 182
- 0xFF, 0x99, 0xCC, PC_NOCOLLAPSE, // 183
- 0x00, 0xCC, 0xCC, PC_NOCOLLAPSE, // 184
- 0x33, 0xCC, 0xCC, PC_NOCOLLAPSE, // 185
- 0x66, 0xCC, 0xCC, PC_NOCOLLAPSE, // 186
- 0x99, 0xCC, 0xCC, PC_NOCOLLAPSE, // 187
- 0xCC, 0xCC, 0xCC, PC_NOCOLLAPSE, // 188 Gray 204
- 0xFF, 0xCC, 0xCC, PC_NOCOLLAPSE, // 189
- 0x00, 0xFF, 0xCC, PC_NOCOLLAPSE, // 190
- 0x33, 0xFF, 0xCC, PC_NOCOLLAPSE, // 191
- 0x66, 0xFF, 0x99, PC_NOCOLLAPSE, // 192
- 0x99, 0xFF, 0xCC, PC_NOCOLLAPSE, // 193
- 0xCC, 0xFF, 0xCC, PC_NOCOLLAPSE, // 194
- 0xFF, 0xFF, 0xCC, PC_NOCOLLAPSE, // 195
- 0x33, 0x00, 0xCC, PC_NOCOLLAPSE, // 196
- 0x66, 0x00, 0xFF, PC_NOCOLLAPSE, // 197
- 0x99, 0x00, 0xFF, PC_NOCOLLAPSE, // 198
- 0x00, 0x33, 0xCC, PC_NOCOLLAPSE, // 199
- 0x33, 0x33, 0xFF, PC_NOCOLLAPSE, // 200
- 0x66, 0x33, 0xFF, PC_NOCOLLAPSE, // 201
- 0x99, 0x33, 0xFF, PC_NOCOLLAPSE, // 202
- 0xCC, 0x33, 0xFF, PC_NOCOLLAPSE, // 203
- 0xFF, 0x33, 0xFF, PC_NOCOLLAPSE, // 204
- 0x00, 0x66, 0xFF, PC_NOCOLLAPSE, // 205
- 0x33, 0x66, 0xFF, PC_NOCOLLAPSE, // 206
- 0x66, 0x66, 0xCC, PC_NOCOLLAPSE, // 207
- 0x99, 0x66, 0xFF, PC_NOCOLLAPSE, // 208
- 0xCC, 0x66, 0xFF, PC_NOCOLLAPSE, // 209
- 0xFF, 0x66, 0xCC, PC_NOCOLLAPSE, // 210
- 0x00, 0x99, 0xFF, PC_NOCOLLAPSE, // 211
- 0x33, 0x99, 0xFF, PC_NOCOLLAPSE, // 212
- 0x66, 0x99, 0xFF, PC_NOCOLLAPSE, // 213
- 0x99, 0x99, 0xFF, PC_NOCOLLAPSE, // 214
- 0xCC, 0x99, 0xFF, PC_NOCOLLAPSE, // 215
- 0xFF, 0x99, 0xFF, PC_NOCOLLAPSE, // 216
- 0x00, 0xCC, 0xFF, PC_NOCOLLAPSE, // 217
- 0x33, 0xCC, 0xFF, PC_NOCOLLAPSE, // 218
- 0x66, 0xCC, 0xFF, PC_NOCOLLAPSE, // 219
- 0x99, 0xCC, 0xFF, PC_NOCOLLAPSE, // 220
- 0xCC, 0xCC, 0xFF, PC_NOCOLLAPSE, // 221
- 0xFF, 0xCC, 0xFF, PC_NOCOLLAPSE, // 222
- 0x33, 0xFF, 0xFF, PC_NOCOLLAPSE, // 223
- 0x66, 0xFF, 0xCC, PC_NOCOLLAPSE, // 224
- 0x99, 0xFF, 0xFF, PC_NOCOLLAPSE, // 225
- 0xCC, 0xFF, 0xFF, PC_NOCOLLAPSE, // 226
- 0xFF, 0x66, 0x66, PC_NOCOLLAPSE, // 227
- 0x66, 0xFF, 0x66, PC_NOCOLLAPSE, // 228
- 0xFF, 0xFF, 0x66, PC_NOCOLLAPSE, // 229
- 0x66, 0x66, 0xFF, PC_NOCOLLAPSE, // 230
- 0xFF, 0x66, 0xFF, PC_NOCOLLAPSE, // 231
- 0x66, 0xFF, 0xFF, PC_NOCOLLAPSE, // 232
-
- // App custom colors
- 0xA5, 0x00, 0x21, PC_NOCOLLAPSE, // 233 Brick red
-
- // Gray palette
- 0x5F, 0x5F, 0x5F, PC_NOCOLLAPSE, // 234 Gray 95
- 0x77, 0x77, 0x77, PC_NOCOLLAPSE, // 235 Gray 119
- 0x86, 0x86, 0x86, PC_NOCOLLAPSE, // 236 Gray 134
- 0x96, 0x96, 0x96, PC_NOCOLLAPSE, // 237 Gray 150
- 0xCB, 0xCB, 0xCB, PC_NOCOLLAPSE, // 238 Gray 203
- 0xB2, 0xB2, 0xB2, PC_NOCOLLAPSE, // 239 Gray 178
- 0xD7, 0xD7, 0xD7, PC_NOCOLLAPSE, // 240 Gray 215
- 0xDD, 0xDD, 0xDD, PC_NOCOLLAPSE, // 241 Gray 221
- 0xE3, 0xE3, 0xE3, PC_NOCOLLAPSE, // 242 Gray 227
- 0xEA, 0xEA, 0xEA, PC_NOCOLLAPSE, // 243 Gray 234
- 0xF1, 0xF1, 0xF1, PC_NOCOLLAPSE, // 244 Gray 241
- 0xF8, 0xF8, 0xF8, PC_NOCOLLAPSE, // 245 Gray 248
-
- // The last 10 system colors
-
- // The following two system entries are modified for the desktop.
- 0xFF, 0xFB, 0xF0, 0x00, // 246 Sys 246 - VARIABLE
- 0xA0, 0xA0, 0xA4, 0x00, // 247 Sys 247 - VARIABLE
-
- 0x80, 0x80, 0x80, 0x00, // 248 Sys Lt Gray, gray 128
- 0xFF, 0x00, 0x00, 0x00, // 249 Sys Red
- 0x00, 0xFF, 0x00, 0x00, // 250 Sys Green
- 0xFF, 0xFF, 0x00, 0x00, // 251 Sys Yellow
- 0x00, 0x00, 0xFF, 0x00, // 252 Sys Blue
- 0xFF, 0x00, 0xFF, 0x00, // 253 Sys Violet
- 0x00, 0xFF, 0xFF, 0x00, // 254 Sys Cyan
- 0xFF, 0xFF, 0xFF, 0x00, // 255 Sys White, gray 255
- };
- }
- }*/
}
}
diff --git a/src/System.Drawing.Common/src/System/Drawing/Pen.cs b/src/System.Drawing.Common/src/System/Drawing/Pen.cs
index be4f0fda5d..a6bf180a62 100644
--- a/src/System.Drawing.Common/src/System/Drawing/Pen.cs
+++ b/src/System.Drawing.Common/src/System/Drawing/Pen.cs
@@ -314,10 +314,7 @@ namespace System.Drawing
}
set
{
- if (!ClientUtils.IsEnumValid_NotSequential(value, unchecked((int)value),
- (int)DashCap.Flat,
- (int)DashCap.Round,
- (int)DashCap.Triangle))
+ if (value != DashCap.Flat && value != DashCap.Round && value != DashCap.Triangle)
{
throw new InvalidEnumArgumentException(nameof(value), unchecked((int)value), typeof(DashCap));
}
@@ -347,7 +344,7 @@ namespace System.Drawing
}
set
{
- if (!ClientUtils.IsEnumValid(value, unchecked((int)value), (int)LineJoin.Miter, (int)LineJoin.MiterClipped))
+ if (value < LineJoin.Miter || value > LineJoin.MiterClipped)
{
throw new InvalidEnumArgumentException(nameof(value), unchecked((int)value), typeof(LineJoin));
}
@@ -450,11 +447,11 @@ namespace System.Drawing
int status = SafeNativeMethods.Gdip.GdipGetPenMode(new HandleRef(this, NativePen), out penMode);
SafeNativeMethods.Gdip.CheckStatus(status);
- return (PenAlignment)penMode;
+ return penMode;
}
set
{
- if (!ClientUtils.IsEnumValid(value, unchecked((int)value), (int)PenAlignment.Center, (int)PenAlignment.Right))
+ if (value < PenAlignment.Center || value > PenAlignment.Right)
{
throw new InvalidEnumArgumentException(nameof(value), unchecked((int)value), typeof(PenAlignment));
}
@@ -718,8 +715,7 @@ namespace System.Drawing
}
set
{
- //valid values are 0x0 to 0x5
- if (!ClientUtils.IsEnumValid(value, unchecked((int)value), (int)DashStyle.Solid, (int)DashStyle.Custom))
+ if (value < DashStyle.Solid || value > DashStyle.Custom)
{
throw new InvalidEnumArgumentException(nameof(value), unchecked((int)value), typeof(DashStyle));
}
diff --git a/src/System.Drawing.Common/src/System/Drawing/Printing/PageSettings.cs b/src/System.Drawing.Common/src/System/Drawing/Printing/PageSettings.cs
index 497729cdac..8635c234b0 100644
--- a/src/System.Drawing.Common/src/System/Drawing/Printing/PageSettings.cs
+++ b/src/System.Drawing.Common/src/System/Drawing/Printing/PageSettings.cs
@@ -165,7 +165,7 @@ namespace System.Drawing.Printing
{
IntPtr modeHandle = printerSettings.GetHdevmode();
IntPtr modePointer = SafeNativeMethods.GlobalLock(new HandleRef(this, modeHandle));
- SafeNativeMethods.DEVMODE mode = (SafeNativeMethods.DEVMODE)UnsafeNativeMethods.PtrToStructure(modePointer, typeof(SafeNativeMethods.DEVMODE));
+ SafeNativeMethods.DEVMODE mode = (SafeNativeMethods.DEVMODE)Marshal.PtrToStructure(modePointer, typeof(SafeNativeMethods.DEVMODE));
PaperSource result = PaperSourceFromMode(mode);
@@ -234,7 +234,7 @@ namespace System.Drawing.Printing
{
IntPtr modeHandle = printerSettings.GetHdevmode();
IntPtr modePointer = SafeNativeMethods.GlobalLock(new HandleRef(this, modeHandle));
- SafeNativeMethods.DEVMODE mode = (SafeNativeMethods.DEVMODE)UnsafeNativeMethods.PtrToStructure(modePointer, typeof(SafeNativeMethods.DEVMODE));
+ SafeNativeMethods.DEVMODE mode = (SafeNativeMethods.DEVMODE)Marshal.PtrToStructure(modePointer, typeof(SafeNativeMethods.DEVMODE));
PrinterResolution result = PrinterResolutionFromMode(mode);
@@ -282,7 +282,7 @@ namespace System.Drawing.Printing
public void CopyToHdevmode(IntPtr hdevmode)
{
IntPtr modePointer = SafeNativeMethods.GlobalLock(new HandleRef(null, hdevmode));
- SafeNativeMethods.DEVMODE mode = (SafeNativeMethods.DEVMODE)UnsafeNativeMethods.PtrToStructure(modePointer, typeof(SafeNativeMethods.DEVMODE));
+ SafeNativeMethods.DEVMODE mode = (SafeNativeMethods.DEVMODE)Marshal.PtrToStructure(modePointer, typeof(SafeNativeMethods.DEVMODE));
if (_color.IsNotDefault && ((mode.dmFields & SafeNativeMethods.DM_COLOR) == SafeNativeMethods.DM_COLOR))
mode.dmColor = unchecked((short)(((bool)_color) ? SafeNativeMethods.DMCOLOR_COLOR : SafeNativeMethods.DMCOLOR_MONOCHROME));
@@ -383,7 +383,7 @@ namespace System.Drawing.Printing
{
IntPtr modeHandle = printerSettings.GetHdevmodeInternal();
IntPtr modePointer = SafeNativeMethods.GlobalLock(new HandleRef(this, modeHandle));
- SafeNativeMethods.DEVMODE mode = (SafeNativeMethods.DEVMODE)UnsafeNativeMethods.PtrToStructure(modePointer, typeof(SafeNativeMethods.DEVMODE));
+ SafeNativeMethods.DEVMODE mode = (SafeNativeMethods.DEVMODE)Marshal.PtrToStructure(modePointer, typeof(SafeNativeMethods.DEVMODE));
short result = mode.dmDriverExtra;
@@ -428,7 +428,7 @@ namespace System.Drawing.Printing
}
IntPtr modePointer = SafeNativeMethods.GlobalLock(new HandleRef(null, modeHandle));
- SafeNativeMethods.DEVMODE mode = (SafeNativeMethods.DEVMODE)UnsafeNativeMethods.PtrToStructure(modePointer, typeof(SafeNativeMethods.DEVMODE));
+ SafeNativeMethods.DEVMODE mode = (SafeNativeMethods.DEVMODE)Marshal.PtrToStructure(modePointer, typeof(SafeNativeMethods.DEVMODE));
PaperSize result = PaperSizeFromMode(mode);
@@ -512,7 +512,7 @@ namespace System.Drawing.Printing
throw new ArgumentException(SR.Format(SR.InvalidPrinterHandle, hdevmode));
IntPtr pointer = SafeNativeMethods.GlobalLock(new HandleRef(null, hdevmode));
- SafeNativeMethods.DEVMODE mode = (SafeNativeMethods.DEVMODE)UnsafeNativeMethods.PtrToStructure(pointer, typeof(SafeNativeMethods.DEVMODE));
+ SafeNativeMethods.DEVMODE mode = (SafeNativeMethods.DEVMODE)Marshal.PtrToStructure(pointer, typeof(SafeNativeMethods.DEVMODE));
if ((mode.dmFields & SafeNativeMethods.DM_COLOR) == SafeNativeMethods.DM_COLOR)
{
diff --git a/src/System.Drawing.Common/src/System/Drawing/Printing/PrinterResolution.cs b/src/System.Drawing.Common/src/System/Drawing/Printing/PrinterResolution.cs
index 64189d8df7..fd84dd32e6 100644
--- a/src/System.Drawing.Common/src/System/Drawing/Printing/PrinterResolution.cs
+++ b/src/System.Drawing.Common/src/System/Drawing/Printing/PrinterResolution.cs
@@ -39,10 +39,9 @@ namespace System.Drawing.Printing
get { return _kind; }
set
{
- //valid values are 0xfffffffc to 0x0
- if (!ClientUtils.IsEnumValid(value, unchecked((int)value), unchecked((int)PrinterResolutionKind.High), unchecked((int)PrinterResolutionKind.Custom)))
+ if (value < PrinterResolutionKind.High || value > PrinterResolutionKind.Custom)
{
- throw new InvalidEnumArgumentException("value", unchecked((int)value), typeof(PrinterResolutionKind));
+ throw new InvalidEnumArgumentException(nameof(value), unchecked((int)value), typeof(PrinterResolutionKind));
}
_kind = value;
diff --git a/src/System.Drawing.Common/src/System/Drawing/Printing/PrinterSettings.cs b/src/System.Drawing.Common/src/System/Drawing/Printing/PrinterSettings.cs
index 592c0ac0a8..4c7a42bbb7 100644
--- a/src/System.Drawing.Common/src/System/Drawing/Printing/PrinterSettings.cs
+++ b/src/System.Drawing.Common/src/System/Drawing/Printing/PrinterSettings.cs
@@ -132,17 +132,19 @@ namespace System.Drawing.Printing
get
{
if (_duplex != Duplex.Default)
+ {
return _duplex;
- else
- return (Duplex)GetModeField(ModeField.Duplex, SafeNativeMethods.DMDUP_SIMPLEX);
+ }
+
+ return (Duplex)GetModeField(ModeField.Duplex, SafeNativeMethods.DMDUP_SIMPLEX);
}
set
{
- //valid values are 0xffffffff to 0x3
- if (!ClientUtils.IsEnumValid(value, unchecked((int)value), unchecked((int)Duplex.Default), unchecked((int)Duplex.Horizontal)))
+ if (value < Duplex.Default || value > Duplex.Horizontal)
{
- throw new InvalidEnumArgumentException("value", unchecked((int)value), typeof(Duplex));
+ throw new InvalidEnumArgumentException(nameof(value), unchecked((int)value), typeof(Duplex));
}
+
_duplex = value;
}
}
@@ -895,7 +897,7 @@ namespace System.Drawing.Printing
}
}
- SafeNativeMethods.DEVMODE mode = (SafeNativeMethods.DEVMODE)UnsafeNativeMethods.PtrToStructure(pointer, typeof(SafeNativeMethods.DEVMODE));
+ SafeNativeMethods.DEVMODE mode = (SafeNativeMethods.DEVMODE)Marshal.PtrToStructure(pointer, typeof(SafeNativeMethods.DEVMODE));
if (_extrainfo != null)
@@ -1015,7 +1017,7 @@ namespace System.Drawing.Printing
}
IntPtr modePointer = SafeNativeMethods.GlobalLock(new HandleRef(this, modeHandle));
- SafeNativeMethods.DEVMODE mode = (SafeNativeMethods.DEVMODE)UnsafeNativeMethods.PtrToStructure(modePointer, typeof(SafeNativeMethods.DEVMODE));
+ SafeNativeMethods.DEVMODE mode = (SafeNativeMethods.DEVMODE)Marshal.PtrToStructure(modePointer, typeof(SafeNativeMethods.DEVMODE));
switch (field)
{
case ModeField.Orientation:
@@ -1208,7 +1210,7 @@ namespace System.Drawing.Printing
throw new ArgumentException(SR.Format(SR.InvalidPrinterHandle, hdevmode));
IntPtr pointer = SafeNativeMethods.GlobalLock(new HandleRef(null, hdevmode));
- SafeNativeMethods.DEVMODE mode = (SafeNativeMethods.DEVMODE)UnsafeNativeMethods.PtrToStructure(pointer, typeof(SafeNativeMethods.DEVMODE));
+ SafeNativeMethods.DEVMODE mode = (SafeNativeMethods.DEVMODE)Marshal.PtrToStructure(pointer, typeof(SafeNativeMethods.DEVMODE));
//Copy entire public devmode as a byte array...
_devmodebytes = mode.dmSize;
diff --git a/src/System.Drawing.Common/src/System/Drawing/PropertyItemInternal.cs b/src/System.Drawing.Common/src/System/Drawing/PropertyItemInternal.cs
index 39e58f5edb..2e6d1209a9 100644
--- a/src/System.Drawing.Common/src/System/Drawing/PropertyItemInternal.cs
+++ b/src/System.Drawing.Common/src/System/Drawing/PropertyItemInternal.cs
@@ -71,7 +71,7 @@ namespace System.Drawing.Imaging
PropertyItemInternal propcopy = null;
try
{
- propcopy = (PropertyItemInternal)UnsafeNativeMethods.PtrToStructure(propdata,
+ propcopy = (PropertyItemInternal)Marshal.PtrToStructure(propdata,
typeof(PropertyItemInternal));
props[i] = new PropertyItem();
diff --git a/src/System.Drawing.Common/src/System/Drawing/Region.cs b/src/System.Drawing.Common/src/System/Drawing/Region.cs
index 2da8b430c5..4889bbc7b1 100644
--- a/src/System.Drawing.Common/src/System/Drawing/Region.cs
+++ b/src/System.Drawing.Common/src/System/Drawing/Region.cs
@@ -29,7 +29,7 @@ namespace System.Drawing
public Region(RectangleF rect)
{
IntPtr region = IntPtr.Zero;
- GPRECTF gprectf = rect.ToGPRECTF();
+ var gprectf = new GPRECTF(rect);
int status = SafeNativeMethods.Gdip.GdipCreateRegionRect(ref gprectf, out region);
SafeNativeMethods.Gdip.CheckStatus(status);
@@ -156,7 +156,7 @@ namespace System.Drawing
public void Intersect(RectangleF rect)
{
- GPRECTF gprectf = rect.ToGPRECTF();
+ var gprectf = new GPRECTF(rect);
int status = SafeNativeMethods.Gdip.GdipCombineRegionRect(new HandleRef(this, _nativeRegion), ref gprectf, CombineMode.Intersect);
SafeNativeMethods.Gdip.CheckStatus(status);
}
@@ -313,7 +313,7 @@ namespace System.Drawing
public void Complement(RectangleF rect)
{
- GPRECTF gprectf = rect.ToGPRECTF();
+ var gprectf = new GPRECTF(rect);
int status = SafeNativeMethods.Gdip.GdipCombineRegionRect(new HandleRef(this, _nativeRegion), ref gprectf, CombineMode.Complement);
SafeNativeMethods.Gdip.CheckStatus(status);
}
@@ -561,7 +561,7 @@ namespace System.Drawing
var rectangles = new RectangleF[count];
for (int index = 0; index < count; index++)
{
- gprectf = (GPRECTF)UnsafeNativeMethods.PtrToStructure((IntPtr)(checked((long)memoryRects + rectsize * index)), typeof(GPRECTF));
+ gprectf = (GPRECTF)Marshal.PtrToStructure((IntPtr)(checked((long)memoryRects + rectsize * index)), typeof(GPRECTF));
rectangles[index] = gprectf.ToRectangleF();
}
diff --git a/src/System.Drawing.Common/src/System/Drawing/StringFormat.cs b/src/System.Drawing.Common/src/System/Drawing/StringFormat.cs
index a0914da6a8..22c00f5600 100644
--- a/src/System.Drawing.Common/src/System/Drawing/StringFormat.cs
+++ b/src/System.Drawing.Common/src/System/Drawing/StringFormat.cs
@@ -249,10 +249,9 @@ namespace System.Drawing
}
set
{
- //valid values are 0x0 to 0x2
- if (!ClientUtils.IsEnumValid(value, unchecked((int)value), (int)StringAlignment.Near, (int)StringAlignment.Far))
+ if (value < StringAlignment.Near || value > StringAlignment.Far)
{
- throw new InvalidEnumArgumentException("value", unchecked((int)value), typeof(StringAlignment));
+ throw new InvalidEnumArgumentException(nameof(value), unchecked((int)value), typeof(StringAlignment));
}
int status = SafeNativeMethods.Gdip.GdipSetStringFormatAlign(new HandleRef(this, nativeFormat), value);
@@ -309,10 +308,9 @@ namespace System.Drawing
}
set
{
- //valid values are 0x0 to 0x2
- if (!ClientUtils.IsEnumValid(value, unchecked((int)value), (int)HotkeyPrefix.None, (int)HotkeyPrefix.Hide))
+ if (value < HotkeyPrefix.None || value > HotkeyPrefix.Hide)
{
- throw new InvalidEnumArgumentException("value", unchecked((int)value), typeof(HotkeyPrefix));
+ throw new InvalidEnumArgumentException(nameof(value), unchecked((int)value), typeof(HotkeyPrefix));
}
int status = SafeNativeMethods.Gdip.GdipSetStringFormatHotkeyPrefix(new HandleRef(this, nativeFormat), value);
@@ -377,10 +375,9 @@ namespace System.Drawing
set
{
- //valid values are 0x0 to 0x5
- if (!ClientUtils.IsEnumValid(value, unchecked((int)value), (int)StringTrimming.None, (int)StringTrimming.EllipsisPath))
+ if (value < StringTrimming.None || value > StringTrimming.EllipsisPath)
{
- throw new InvalidEnumArgumentException("value", unchecked((int)value), typeof(StringTrimming));
+ throw new InvalidEnumArgumentException(nameof(value), unchecked((int)value), typeof(StringTrimming));
}
int status = SafeNativeMethods.Gdip.GdipSetStringFormatTrimming(new HandleRef(this, nativeFormat), value);
diff --git a/src/System.Drawing.Common/src/System/Drawing/SystemFonts.cs b/src/System.Drawing.Common/src/System/Drawing/SystemFonts.cs
index c8d4b78871..a4d417f1f3 100644
--- a/src/System.Drawing.Common/src/System/Drawing/SystemFonts.cs
+++ b/src/System.Drawing.Common/src/System/Drawing/SystemFonts.cs
@@ -10,8 +10,6 @@ namespace System.Drawing
{
public static class SystemFonts
{
- private static readonly object s_systemFontsKey = new object();
-
public static Font CaptionFont
{
get
@@ -21,31 +19,12 @@ namespace System.Drawing
var data = new NativeMethods.NONCLIENTMETRICS();
bool result = UnsafeNativeMethods.SystemParametersInfo(NativeMethods.SPI_GETNONCLIENTMETRICS, data.cbSize, data, 0);
- if (result && data.lfCaptionFont != null)
+ if (result)
{
- try
- {
- captionFont = Font.FromLogFont(data.lfCaptionFont);
- }
- catch (Exception ex)
- {
- if (IsCriticalFontException(ex))
- {
- throw;
- }
- }
-
- if (captionFont == null)
- {
- captionFont = DefaultFont;
- }
- else if (captionFont.Unit != GraphicsUnit.Point)
- {
- captionFont = FontInPoints(captionFont);
- }
+ captionFont = GetFontFromData(data.lfCaptionFont);
}
- captionFont.SetSystemFontName("CaptionFont");
+ captionFont.SetSystemFontName(nameof(CaptionFont));
return captionFont;
}
}
@@ -59,31 +38,12 @@ namespace System.Drawing
var data = new NativeMethods.NONCLIENTMETRICS();
bool result = UnsafeNativeMethods.SystemParametersInfo(NativeMethods.SPI_GETNONCLIENTMETRICS, data.cbSize, data, 0);
- if (result && data.lfSmCaptionFont != null)
+ if (result)
{
- try
- {
- smcaptionFont = Font.FromLogFont(data.lfSmCaptionFont);
- }
- catch (Exception ex)
- {
- if (IsCriticalFontException(ex))
- {
- throw;
- }
- }
-
- if (smcaptionFont == null)
- {
- smcaptionFont = DefaultFont;
- }
- else if (smcaptionFont.Unit != GraphicsUnit.Point)
- {
- smcaptionFont = FontInPoints(smcaptionFont);
- }
+ smcaptionFont = GetFontFromData(data.lfSmCaptionFont);
}
- smcaptionFont.SetSystemFontName("SmallCaptionFont");
+ smcaptionFont.SetSystemFontName(nameof(SmallCaptionFont));
return smcaptionFont;
}
}
@@ -97,31 +57,12 @@ namespace System.Drawing
var data = new NativeMethods.NONCLIENTMETRICS();
bool result = UnsafeNativeMethods.SystemParametersInfo(NativeMethods.SPI_GETNONCLIENTMETRICS, data.cbSize, data, 0);
- if (result && data.lfMenuFont != null)
+ if (result)
{
- try
- {
- menuFont = Font.FromLogFont(data.lfMenuFont);
- }
- catch (Exception ex)
- {
- if (IsCriticalFontException(ex))
- {
- throw;
- }
- }
-
- if (menuFont == null)
- {
- menuFont = DefaultFont;
- }
- else if (menuFont.Unit != GraphicsUnit.Point)
- {
- menuFont = FontInPoints(menuFont);
- }
+ menuFont = GetFontFromData(data.lfMenuFont);
}
- menuFont.SetSystemFontName("MenuFont");
+ menuFont.SetSystemFontName(nameof(MenuFont));
return menuFont;
}
}
@@ -135,31 +76,12 @@ namespace System.Drawing
var data = new NativeMethods.NONCLIENTMETRICS();
bool result = UnsafeNativeMethods.SystemParametersInfo(NativeMethods.SPI_GETNONCLIENTMETRICS, data.cbSize, data, 0);
- if (result && data.lfStatusFont != null)
+ if (result)
{
- try
- {
- statusFont = Font.FromLogFont(data.lfStatusFont);
- }
- catch (Exception ex)
- {
- if (IsCriticalFontException(ex))
- {
- throw;
- }
- }
-
- if (statusFont == null)
- {
- statusFont = DefaultFont;
- }
- else if (statusFont.Unit != GraphicsUnit.Point)
- {
- statusFont = FontInPoints(statusFont);
- }
+ statusFont = GetFontFromData(data.lfStatusFont);
}
- statusFont.SetSystemFontName("StatusFont");
+ statusFont.SetSystemFontName(nameof(StatusFont));
return statusFont;
}
}
@@ -168,37 +90,18 @@ namespace System.Drawing
{
get
{
- Font messageboxFont = null;
+ Font messageBoxFont = null;
var data = new NativeMethods.NONCLIENTMETRICS();
bool result = UnsafeNativeMethods.SystemParametersInfo(NativeMethods.SPI_GETNONCLIENTMETRICS, data.cbSize, data, 0);
- if (result && data.lfMessageFont != null)
+ if (result)
{
- try
- {
- messageboxFont = Font.FromLogFont(data.lfMessageFont);
- }
- catch (Exception ex)
- {
- if (IsCriticalFontException(ex))
- {
- throw;
- }
- }
-
- if (messageboxFont == null)
- {
- messageboxFont = DefaultFont;
- }
- else if (messageboxFont.Unit != GraphicsUnit.Point)
- {
- messageboxFont = FontInPoints(messageboxFont);
- }
+ messageBoxFont = GetFontFromData(data.lfMessageFont);
}
- messageboxFont.SetSystemFontName("MessageBoxFont");
- return messageboxFont;
+ messageBoxFont.SetSystemFontName(nameof(MessageBoxFont));
+ return messageBoxFont;
}
}
@@ -218,37 +121,18 @@ namespace System.Drawing
{
get
{
- Font icontitleFont = null;
+ Font iconTitleFont = null;
var itfont = new SafeNativeMethods.LOGFONT();
bool result = UnsafeNativeMethods.SystemParametersInfo(NativeMethods.SPI_GETICONTITLELOGFONT, Marshal.SizeOf(itfont), itfont, 0);
- if (result && itfont != null)
+ if (result)
{
- try
- {
- icontitleFont = Font.FromLogFont(itfont);
- }
- catch (Exception ex)
- {
- if (IsCriticalFontException(ex))
- {
- throw;
- }
- }
-
- if (icontitleFont == null)
- {
- icontitleFont = DefaultFont;
- }
- else if (icontitleFont.Unit != GraphicsUnit.Point)
- {
- icontitleFont = FontInPoints(icontitleFont);
- }
+ iconTitleFont = GetFontFromData(itfont);
}
- icontitleFont.SetSystemFontName("IconTitleFont");
- return icontitleFont;
+ iconTitleFont.SetSystemFontName(nameof(IconTitleFont));
+ return iconTitleFont;
}
}
@@ -257,51 +141,35 @@ namespace System.Drawing
get
{
Font defaultFont = null;
-
- // Special case DefaultFont for Arabic systems.
+
+ // For Arabic systems, always return Tahoma 8.
bool systemDefaultLCIDIsArabic = (UnsafeNativeMethods.GetSystemDefaultLCID() & 0x3ff) == 0x0001;
-
-
- // For Arabic systems, regardless of the platform, always return Tahoma 8.
if (systemDefaultLCIDIsArabic)
{
try
{
defaultFont = new Font("Tahoma", 8);
}
- catch (Exception ex)
- {
- if (IsCriticalFontException(ex))
- {
- throw;
- }
- }
+ catch (Exception ex) when (!IsCriticalFontException(ex)) { }
}
-
- // Not Arabic.
- // First try DEFAULT_GUI, then Tahoma 8, then GenericSansSerif 8.
+
+ // First try DEFAULT_GUI.
if (defaultFont == null)
{
IntPtr handle = UnsafeNativeMethods.GetStockObject(NativeMethods.DEFAULT_GUI_FONT);
try
{
- Font fontInWorldUnits = Font.FromHfont(handle);
-
- try
+ using (Font fontInWorldUnits = Font.FromHfont(handle))
{
defaultFont = FontInPoints(fontInWorldUnits);
}
- finally
- {
- fontInWorldUnits.Dispose();
- }
}
catch (ArgumentException)
{
}
}
- // If DEFAULT_GUI didn't work, we try Tahoma.
+ // If DEFAULT_GUI didn't work, try Tahoma.
if (defaultFont == null)
{
try
@@ -313,7 +181,7 @@ namespace System.Drawing
}
}
- // Last resort, we use the GenericSansSerif - this will always work.
+ // Use GenericSansSerif as a last resort - this will always work.
if (defaultFont == null)
{
defaultFont = new Font(FontFamily.GenericSansSerif, 8);
@@ -324,9 +192,9 @@ namespace System.Drawing
defaultFont = FontInPoints(defaultFont);
}
- Debug.Assert(defaultFont != null, "defaultFont wasn't set!");
+ Debug.Assert(defaultFont != null, "defaultFont wasn't set.");
- defaultFont.SetSystemFontName("DefaultFont");
+ defaultFont.SetSystemFontName(nameof(DefaultFont));
return defaultFont;
}
}
@@ -365,7 +233,7 @@ namespace System.Drawing
// For Japanese cultures, SystemFonts.DefaultFont returns a new Font object every time it is invoked.
// So for Japanese we return the DefaultFont with its SystemFontName set to DialogFont.
- dialogFont.SetSystemFontName("DialogFont");
+ dialogFont.SetSystemFontName(nameof(DialogFont));
return dialogFont;
}
}
@@ -377,43 +245,60 @@ namespace System.Drawing
public static Font GetFontByName(string systemFontName)
{
- if ("CaptionFont".Equals(systemFontName))
+ if (nameof(CaptionFont).Equals(systemFontName))
{
return CaptionFont;
}
- else if ("DefaultFont".Equals(systemFontName))
+ else if (nameof(DefaultFont).Equals(systemFontName))
{
return DefaultFont;
}
- else if ("DialogFont".Equals(systemFontName))
+ else if (nameof(DialogFont).Equals(systemFontName))
{
return DialogFont;
}
- else if ("IconTitleFont".Equals(systemFontName))
+ else if (nameof(IconTitleFont).Equals(systemFontName))
{
return IconTitleFont;
}
- else if ("MenuFont".Equals(systemFontName))
+ else if (nameof(MenuFont).Equals(systemFontName))
{
return MenuFont;
}
- else if ("MessageBoxFont".Equals(systemFontName))
+ else if (nameof(MessageBoxFont).Equals(systemFontName))
{
return MessageBoxFont;
}
- else if ("SmallCaptionFont".Equals(systemFontName))
+ else if (nameof(SmallCaptionFont).Equals(systemFontName))
{
return SmallCaptionFont;
}
- else if ("StatusFont".Equals(systemFontName))
+ else if (nameof(StatusFont).Equals(systemFontName))
{
return StatusFont;
}
- else
+
+ return null;
+ }
+
+ private static Font GetFontFromData(SafeNativeMethods.LOGFONT logFont)
+ {
+ if (logFont == null)
{
return null;
}
+
+ Font font = null;
+ try
+ {
+ font = Font.FromLogFont(logFont);
+ }
+ catch (Exception ex) when (!IsCriticalFontException(ex)) { }
+
+ return
+ font == null ? DefaultFont :
+ font.Unit != GraphicsUnit.Point ? FontInPoints(font) :
+ font;
}
}
}
-
diff --git a/src/System.Drawing.Common/src/System/Drawing/Text/PrivateFontCollection.cs b/src/System.Drawing.Common/src/System/Drawing/Text/PrivateFontCollection.cs
index 23887c4035..063398986b 100644
--- a/src/System.Drawing.Common/src/System/Drawing/Text/PrivateFontCollection.cs
+++ b/src/System.Drawing.Common/src/System/Drawing/Text/PrivateFontCollection.cs
@@ -5,6 +5,7 @@
using System.Diagnostics;
using System.Runtime.InteropServices;
using System.Globalization;
+using System.IO;
namespace System.Drawing.Text
{
@@ -56,6 +57,8 @@ namespace System.Drawing.Text
/// </summary>
public void AddFontFile(string filename)
{
+ Path.GetFullPath(filename);
+
int status = SafeNativeMethods.Gdip.GdipPrivateAddFontFile(new HandleRef(this, _nativeFontCollection), filename);
SafeNativeMethods.Gdip.CheckStatus(status);
diff --git a/src/System.Drawing.Common/src/System/Drawing/TextureBrush.cs b/src/System.Drawing.Common/src/System/Drawing/TextureBrush.cs
index 81a8f05f1e..c39f329afc 100644
--- a/src/System.Drawing.Common/src/System/Drawing/TextureBrush.cs
+++ b/src/System.Drawing.Common/src/System/Drawing/TextureBrush.cs
@@ -29,7 +29,7 @@ namespace System.Drawing
throw new ArgumentNullException(nameof(image));
}
- if (!ClientUtils.IsEnumValid(wrapMode, unchecked((int)wrapMode), (int)WrapMode.Tile, (int)WrapMode.Clamp))
+ if (wrapMode < WrapMode.Tile || wrapMode > WrapMode.Clamp)
{
throw new InvalidEnumArgumentException(nameof(wrapMode), unchecked((int)wrapMode), typeof(WrapMode));
}
@@ -50,7 +50,7 @@ namespace System.Drawing
throw new ArgumentNullException(nameof(image));
}
- if (!ClientUtils.IsEnumValid(wrapMode, unchecked((int)wrapMode), (int)WrapMode.Tile, (int)WrapMode.Clamp))
+ if (wrapMode < WrapMode.Tile || wrapMode > WrapMode.Clamp)
{
throw new InvalidEnumArgumentException(nameof(wrapMode), unchecked((int)wrapMode), typeof(WrapMode));
}
@@ -75,7 +75,7 @@ namespace System.Drawing
throw new ArgumentNullException(nameof(image));
}
- if (!ClientUtils.IsEnumValid(wrapMode, unchecked((int)wrapMode), (int)WrapMode.Tile, (int)WrapMode.Clamp))
+ if (wrapMode < WrapMode.Tile || wrapMode > WrapMode.Clamp)
{
throw new InvalidEnumArgumentException(nameof(wrapMode), unchecked((int)wrapMode), typeof(WrapMode));
}
@@ -188,7 +188,7 @@ namespace System.Drawing
}
set
{
- if (!ClientUtils.IsEnumValid(value, unchecked((int)value), (int)WrapMode.Tile, (int)WrapMode.Clamp))
+ if (value < WrapMode.Tile || value > WrapMode.Clamp)
{
throw new InvalidEnumArgumentException(nameof(value), unchecked((int)value), typeof(WrapMode));
}
diff --git a/src/System.Drawing.Common/src/System/Drawing/ToolboxBitmapAttribute.cs b/src/System.Drawing.Common/src/System/Drawing/ToolboxBitmapAttribute.cs
index 33df91e1cd..648a530d0e 100644
--- a/src/System.Drawing.Common/src/System/Drawing/ToolboxBitmapAttribute.cs
+++ b/src/System.Drawing.Common/src/System/Drawing/ToolboxBitmapAttribute.cs
@@ -186,8 +186,7 @@ namespace System.Drawing
if (ext != null && string.Equals(ext, ".ico", StringComparison.OrdinalIgnoreCase))
{
//ico files support both large and small, so we respect the large flag here.
-
- using (FileStream reader = File.Open(imageFile, FileMode.Open))
+ using (FileStream reader = File.OpenRead(imageFile))
{
image = GetIconFromStream(reader, large, scaled);
}
diff --git a/src/System.Drawing.Common/src/System/Drawing/UnsafeNativeMethods.cs b/src/System.Drawing.Common/src/System/Drawing/UnsafeNativeMethods.cs
index 0355ed1945..7d3987ce04 100644
--- a/src/System.Drawing.Common/src/System/Drawing/UnsafeNativeMethods.cs
+++ b/src/System.Drawing.Common/src/System/Drawing/UnsafeNativeMethods.cs
@@ -2,22 +2,21 @@
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
+using System.IO;
+using System.Runtime.InteropServices;
+using System.Security;
+
namespace System.Drawing
{
- using System.IO;
- using System.Runtime.InteropServices;
- using System.Security.Permissions;
-
- [
- System.Security.SuppressUnmanagedCodeSecurityAttribute()
- ]
+ [SuppressUnmanagedCodeSecurity]
internal class UnsafeNativeMethods
{
- [DllImport(ExternDll.Kernel32, SetLastError = true, ExactSpelling = true, EntryPoint = "RtlMoveMemory", CharSet = System.Runtime.InteropServices.CharSet.Auto)]
+ [DllImport(ExternDll.Kernel32, SetLastError = true, ExactSpelling = true, EntryPoint = "RtlMoveMemory", CharSet = CharSet.Auto)]
public static extern void CopyMemory(HandleRef destData, HandleRef srcData, int size);
- [DllImport(ExternDll.User32, SetLastError = true, ExactSpelling = true, EntryPoint = "GetDC", CharSet = System.Runtime.InteropServices.CharSet.Auto)]
+ [DllImport(ExternDll.User32, SetLastError = true, ExactSpelling = true, EntryPoint = "GetDC", CharSet = CharSet.Auto)]
private static extern IntPtr IntGetDC(HandleRef hWnd);
+
public static IntPtr GetDC(HandleRef hWnd)
{
return System.Internal.HandleCollector.Add(IntGetDC(hWnd), SafeNativeMethods.CommonHandles.HDC);
@@ -25,14 +24,16 @@ namespace System.Drawing
[DllImport(ExternDll.Gdi32, SetLastError = true, ExactSpelling = true, EntryPoint = "DeleteDC", CharSet = CharSet.Auto)]
private static extern bool IntDeleteDC(HandleRef hDC);
+
public static bool DeleteDC(HandleRef hDC)
{
System.Internal.HandleCollector.Remove((IntPtr)hDC, SafeNativeMethods.CommonHandles.GDI);
return IntDeleteDC(hDC);
}
- [DllImport(ExternDll.User32, SetLastError = true, ExactSpelling = true, EntryPoint = "ReleaseDC", CharSet = System.Runtime.InteropServices.CharSet.Auto)]
+ [DllImport(ExternDll.User32, SetLastError = true, ExactSpelling = true, EntryPoint = "ReleaseDC", CharSet = CharSet.Auto)]
private static extern int IntReleaseDC(HandleRef hWnd, HandleRef hDC);
+
public static int ReleaseDC(HandleRef hWnd, HandleRef hDC)
{
System.Internal.HandleCollector.Remove((IntPtr)hDC, SafeNativeMethods.CommonHandles.HDC);
@@ -41,6 +42,7 @@ namespace System.Drawing
[DllImport(ExternDll.Gdi32, SetLastError = true, ExactSpelling = true, EntryPoint = "CreateCompatibleDC", CharSet = CharSet.Auto)]
private static extern IntPtr IntCreateCompatibleDC(HandleRef hDC);
+
public static IntPtr CreateCompatibleDC(HandleRef hDC)
{
return System.Internal.HandleCollector.Add(IntCreateCompatibleDC(hDC), SafeNativeMethods.CommonHandles.GDI);
@@ -49,10 +51,10 @@ namespace System.Drawing
[DllImport(ExternDll.Gdi32, SetLastError = true, ExactSpelling = true, CharSet = CharSet.Auto)]
public static extern IntPtr GetStockObject(int nIndex);
- [DllImport(ExternDll.Kernel32, SetLastError = true, CharSet = System.Runtime.InteropServices.CharSet.Auto)]
+ [DllImport(ExternDll.Kernel32, SetLastError = true, CharSet = CharSet.Auto)]
public static extern int GetSystemDefaultLCID();
- [DllImport(ExternDll.User32, SetLastError = true, ExactSpelling = true, CharSet = System.Runtime.InteropServices.CharSet.Auto)]
+ [DllImport(ExternDll.User32, SetLastError = true, ExactSpelling = true, CharSet = CharSet.Auto)]
public static extern int GetSystemMetrics(int nIndex);
[DllImport(ExternDll.User32, SetLastError = true, CharSet = CharSet.Auto, BestFitMapping = false)]
@@ -61,104 +63,49 @@ namespace System.Drawing
[DllImport(ExternDll.User32, SetLastError = true, CharSet = CharSet.Auto, BestFitMapping = false)]
public static extern bool SystemParametersInfo(int uiAction, int uiParam, [In, Out] SafeNativeMethods.LOGFONT pvParam, int fWinIni);
- [DllImport(ExternDll.Gdi32, SetLastError = true, ExactSpelling = true, CharSet = System.Runtime.InteropServices.CharSet.Auto)]
+ [DllImport(ExternDll.Gdi32, SetLastError = true, ExactSpelling = true, CharSet = CharSet.Auto)]
public static extern int GetDeviceCaps(HandleRef hDC, int nIndex);
[DllImport(ExternDll.Gdi32, SetLastError = true, ExactSpelling = true, CharSet = CharSet.Auto)]
public static extern int GetObjectType(HandleRef hObject);
- // SECUNDONE : For some reason "PtrToStructure" requires super high permission.. put this
- // : assert here until we can get a resolution on this.
- // : this is ok as long as the lparam is not obtained from external code.
- [ReflectionPermission(SecurityAction.Assert, Unrestricted = true),
- SecurityPermission(SecurityAction.Assert, Flags = SecurityPermissionFlag.UnmanagedCode)]
- public static object PtrToStructure(IntPtr lparam, Type cls)
- {
- return Marshal.PtrToStructure(lparam, cls);
- }
-
- // SECUNDONE : For some reason "PtrToStructure" requires super high permission.. put this
- // : assert here until we can get a resolution on this.
- // : this is ok as long as the lparam is not obtained from external code.
- [ReflectionPermission(SecurityAction.Assert, Unrestricted = true),
- SecurityPermission(SecurityAction.Assert, Flags = SecurityPermissionFlag.UnmanagedCode)]
- public static void PtrToStructure(IntPtr lparam, object data)
- {
- Marshal.PtrToStructure(lparam, data);
- }
-
- [ComImport(), Guid("0000000C-0000-0000-C000-000000000046"), System.Runtime.InteropServices.InterfaceTypeAttribute(System.Runtime.InteropServices.ComInterfaceType.InterfaceIsIUnknown)]
+ [ComImport]
+ [Guid("0000000C-0000-0000-C000-000000000046"), InterfaceType(ComInterfaceType.InterfaceIsIUnknown)]
public interface IStream
{
- int Read(
- [In]
- IntPtr buf,
- [In]
- int len);
-
+ int Read([In] IntPtr buf, [In] int len);
- int Write(
- [In]
- IntPtr buf,
- [In]
- int len);
+ int Write([In] IntPtr buf, [In] int len);
[return: MarshalAs(UnmanagedType.I8)]
- long Seek(
- [In, MarshalAs(UnmanagedType.I8)]
- long dlibMove,
- [In]
- int dwOrigin);
-
+ long Seek([In, MarshalAs(UnmanagedType.I8)] long dlibMove, [In] int dwOrigin);
- void SetSize(
- [In, MarshalAs(UnmanagedType.I8)]
- long libNewSize);
+ void SetSize([In, MarshalAs(UnmanagedType.I8)] long libNewSize);
[return: MarshalAs(UnmanagedType.I8)]
- long CopyTo(
- [In, MarshalAs(UnmanagedType.Interface)]
- UnsafeNativeMethods.IStream pstm,
- [In, MarshalAs(UnmanagedType.I8)]
- long cb,
- [Out, MarshalAs(UnmanagedType.LPArray)]
- long[] pcbRead);
+ long CopyTo([In, MarshalAs(UnmanagedType.Interface)] IStream pstm,
+ [In, MarshalAs(UnmanagedType.I8)] long cb,
+ [Out, MarshalAs(UnmanagedType.LPArray)] long[] pcbRead);
- void Commit(
- [In]
- int grfCommitFlags);
-
+ void Commit([In] int grfCommitFlags);
void Revert();
-
- void LockRegion(
- [In, MarshalAs(UnmanagedType.I8)]
- long libOffset,
- [In, MarshalAs(UnmanagedType.I8)]
- long cb,
- [In]
- int dwLockType);
+ void LockRegion([In, MarshalAs(UnmanagedType.I8)] long libOffset,
+ [In, MarshalAs(UnmanagedType.I8)] long cb,
+ [In] int dwLockType);
- void UnlockRegion(
- [In, MarshalAs(UnmanagedType.I8)]
- long libOffset,
- [In, MarshalAs(UnmanagedType.I8)]
- long cb,
- [In]
- int dwLockType);
+ void UnlockRegion([In, MarshalAs(UnmanagedType.I8)]long libOffset,
+ [In, MarshalAs(UnmanagedType.I8)] long cb,
+ [In] int dwLockType);
- void Stat(
- [In]
- IntPtr pStatstg,
- [In]
- int grfStatFlag);
+ void Stat([In] IntPtr pStatstg, [In] int grfStatFlag);
[return: MarshalAs(UnmanagedType.Interface)]
- UnsafeNativeMethods.IStream Clone();
+ IStream Clone();
}
internal class ComStreamFromDataStream : IStream
@@ -170,16 +117,20 @@ namespace System.Drawing
internal ComStreamFromDataStream(Stream dataStream)
{
- if (dataStream == null) throw new ArgumentNullException("dataStream");
- this.dataStream = dataStream;
+ this.dataStream = dataStream ?? throw new ArgumentNullException("dataStream");
}
private void ActualizeVirtualPosition()
{
- if (_virtualPosition == -1) return;
+ if (_virtualPosition == -1)
+ {
+ return;
+ }
if (_virtualPosition > dataStream.Length)
+ {
dataStream.SetLength(_virtualPosition);
+ }
dataStream.Position = _virtualPosition;
@@ -203,20 +154,33 @@ namespace System.Drawing
{
int bufsize = 4096; // one page
IntPtr buffer = Marshal.AllocHGlobal(bufsize);
- if (buffer == IntPtr.Zero) throw new OutOfMemoryException();
+ if (buffer == IntPtr.Zero)
+ {
+ throw new OutOfMemoryException();
+ }
+
long written = 0;
try
{
while (written < cb)
{
int toRead = bufsize;
- if (written + toRead > cb) toRead = (int)(cb - written);
+ if (written + toRead > cb)
+ {
+ toRead = (int)(cb - written);
+ }
+
int read = Read(buffer, toRead);
- if (read == 0) break;
+ if (read == 0)
+ {
+ break;
+ }
+
if (pstm.Write(buffer, read) != read)
{
throw EFail("Wrote an incorrect number of bytes");
}
+
written += read;
}
}
@@ -224,6 +188,7 @@ namespace System.Drawing
{
Marshal.FreeHGlobal(buffer);
}
+
if (pcbRead != null && pcbRead.Length > 0)
{
pcbRead[0] = written;
@@ -232,11 +197,6 @@ namespace System.Drawing
return written;
}
- public virtual Stream GetDataStream()
- {
- return dataStream;
- }
-
public virtual void LockRegion(long libOffset, long cb, int dwLockType)
{
}
@@ -251,34 +211,30 @@ namespace System.Drawing
throw new ExternalException(SR.Format(SR.NotImplemented), SafeNativeMethods.E_NOTIMPL);
}
- public virtual int Read(IntPtr buf, /* cpr: int offset,*/ int length)
+ public virtual int Read(IntPtr buf, int length)
{
- // System.Text.Out.WriteLine("IStream::Read(" + length + ")");
byte[] buffer = new byte[length];
int count = Read(buffer, length);
Marshal.Copy(buffer, 0, buf, length);
return count;
}
- public virtual int Read(byte[] buffer, /* cpr: int offset,*/ int length)
+ public virtual int Read(byte[] buffer, int length)
{
ActualizeVirtualPosition();
return dataStream.Read(buffer, 0, length);
}
- public virtual void Revert()
- {
- NotImplemented();
- }
+ public virtual void Revert() => NotImplemented();
public virtual long Seek(long offset, int origin)
{
- // Console.WriteLine("IStream::Seek("+ offset + ", " + origin + ")");
long pos = _virtualPosition;
if (_virtualPosition == -1)
{
pos = dataStream.Position;
}
+
long len = dataStream.Length;
switch (origin)
{
@@ -316,6 +272,7 @@ namespace System.Drawing
}
break;
}
+
if (_virtualPosition != -1)
{
return _virtualPosition;
@@ -326,30 +283,26 @@ namespace System.Drawing
}
}
- public virtual void SetSize(long value)
- {
- dataStream.SetLength(value);
- }
+ public virtual void SetSize(long value) => dataStream.SetLength(value);
- public virtual void Stat(IntPtr pstatstg, int grfStatFlag)
- {
- // GpStream has a partial implementation, but it's so partial rather
- // restrict it to use with GDI+
- NotImplemented();
- }
+ /// <summary>
+ /// GpStream has a partial implementation, but it's so partial rather
+ /// restrict it to use with GDI+.
+ /// </summary>
+ public virtual void Stat(IntPtr pstatstg, int grfStatFlag) => NotImplemented();
public virtual void UnlockRegion(long libOffset, long cb, int dwLockType)
{
}
- public virtual int Write(IntPtr buf, /* cpr: int offset,*/ int length)
+ public virtual int Write(IntPtr buf, int length)
{
byte[] buffer = new byte[length];
Marshal.Copy(buf, buffer, 0, length);
return Write(buffer, length);
}
- public virtual int Write(byte[] buffer, /* cpr: int offset,*/ int length)
+ public virtual int Write(byte[] buffer, int length)
{
ActualizeVirtualPosition();
dataStream.Write(buffer, 0, length);
@@ -358,4 +311,3 @@ namespace System.Drawing
}
}
}
-
diff --git a/src/System.Drawing.Common/src/misc/ClientUtils.cs b/src/System.Drawing.Common/src/misc/ClientUtils.cs
deleted file mode 100644
index 7b0c738efc..0000000000
--- a/src/System.Drawing.Common/src/misc/ClientUtils.cs
+++ /dev/null
@@ -1,490 +0,0 @@
-// Licensed to the .NET Foundation under one or more agreements.
-// The .NET Foundation licenses this file to you under the MIT license.
-// See the LICENSE file in the project root for more information.
-
-using System.Collections;
-using System.Diagnostics;
-using System.Globalization;
-
-namespace System.Drawing
-{
- // Miscellaneous utilities
- internal static class ClientUtils
- {
- // ExecutionEngineException is obsolete and shouldn't be used (to catch, throw or reference) anymore.
- // Pragma added to prevent converting the "type is obsolete" warning into build error.
- // File owner should fix this.
-#pragma warning disable 618
- public static bool IsCriticalException(Exception ex)
- {
- return ex is NullReferenceException
- || ex is StackOverflowException
- || ex is OutOfMemoryException
- || ex is System.Threading.ThreadAbortException
- || ex is ExecutionEngineException
- || ex is IndexOutOfRangeException
- || ex is AccessViolationException;
- }
-#pragma warning restore 618
-
- public static bool IsSecurityOrCriticalException(Exception ex)
- {
- return (ex is System.Security.SecurityException) || IsCriticalException(ex);
- }
-
- public static int GetBitCount(uint x)
- {
- int count = 0;
- while (x > 0)
- {
- x &= x - 1;
- count++;
- }
- return count;
- }
-
-
- // Sequential version
- // assumes sequential enum members 0,1,2,3,4 -etc.
- //
- public static bool IsEnumValid(Enum enumValue, int value, int minValue, int maxValue)
- {
- bool valid = (value >= minValue) && (value <= maxValue);
-#if DEBUG
- Debug_SequentialEnumIsDefinedCheck(enumValue, minValue, maxValue);
-#endif
- return valid;
- }
-
- // Useful for sequential enum values which only use powers of two 0,1,2,4,8 etc: IsEnumValid(val, min, max, 1)
- // Valid example: TextImageRelation 0,1,2,4,8 - only one bit can ever be on, and the value is between 0 and 8.
- //
- // ClientUtils.IsEnumValid((int)(relation), /*min*/(int)TextImageRelation.None, (int)TextImageRelation.TextBeforeImage,1);
- //
- public static bool IsEnumValid(Enum enumValue, int value, int minValue, int maxValue, int maxNumberOfBitsOn)
- {
- System.Diagnostics.Debug.Assert(maxNumberOfBitsOn >= 0 && maxNumberOfBitsOn < 32, "expect this to be greater than zero and less than 32");
-
- bool valid = (value >= minValue) && (value <= maxValue);
- //Note: if it's 0, it'll have no bits on. If it's a power of 2, it'll have 1.
- valid = (valid && GetBitCount((uint)value) <= maxNumberOfBitsOn);
-#if DEBUG
- Debug_NonSequentialEnumIsDefinedCheck(enumValue, minValue, maxValue, maxNumberOfBitsOn, valid);
-#endif
- return valid;
- }
-
- // Useful for enums that are a subset of a bitmask
- // Valid example: EdgeEffects 0, 0x800 (FillInterior), 0x1000 (Flat), 0x4000(Soft), 0x8000(Mono)
- //
- // ClientUtils.IsEnumValid((int)(effects), /*mask*/ FillInterior | Flat | Soft | Mono,
- // ,2);
- //
- public static bool IsEnumValid_Masked(Enum enumValue, int value, UInt32 mask)
- {
- bool valid = ((value & mask) == value);
-
-#if DEBUG
- Debug_ValidateMask(enumValue, mask);
-#endif
-
- return valid;
- }
-
- // Useful for cases where you have discontiguous members of the enum.
- // Valid example: AutoComplete source.
- // if (!ClientUtils.IsEnumValid(value, AutoCompleteSource.None,
- // AutoCompleteSource.AllSystemSources
- // AutoCompleteSource.AllUrl,
- // AutoCompleteSource.CustomSource,
- // AutoCompleteSource.FileSystem,
- // AutoCompleteSource.FileSystemDirectories,
- // AutoCompleteSource.HistoryList,
- // AutoCompleteSource.ListItems,
- // AutoCompleteSource.RecentlyUsedList))
- //
- // PERF tip: put the default value in the enum towards the front of the argument list.
- [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Performance", "CA1811:AvoidUncalledPrivateCode")]
- public static bool IsEnumValid_NotSequential(System.Enum enumValue, int value, params int[] enumValues)
- {
- System.Diagnostics.Debug.Assert(Enum.GetValues(enumValue.GetType()).Length == enumValues.Length, "Not all the enum members were passed in.");
- for (int i = 0; i < enumValues.Length; i++)
- {
- if (enumValues[i] == value)
- {
- return true;
- }
- }
- return false;
- }
-
-#if DEBUG
- [ThreadStatic]
- private static Hashtable t_enumValueInfo;
- public const int MaxCache = 300; // we think we're going to get O(100) of these, put in a tripwire if it gets larger.
-
- private class SequentialEnumInfo
- {
- public SequentialEnumInfo(Type t)
- {
- int actualMinimum = int.MaxValue;
- int actualMaximum = int.MinValue;
- int countEnumVals = 0;
-
- foreach (int iVal in Enum.GetValues(t))
- {
- actualMinimum = Math.Min(actualMinimum, iVal);
- actualMaximum = Math.Max(actualMaximum, iVal);
- countEnumVals++;
- }
-
- Debug.Assert(countEnumVals - 1 == actualMaximum - actualMinimum);
- MinValue = actualMinimum;
- MaxValue = actualMaximum;
- }
- public int MinValue;
- public int MaxValue;
- }
-
- private static void Debug_SequentialEnumIsDefinedCheck(Enum value, int minVal, int maxVal)
- {
- Type enumType = value.GetType();
-
- if (t_enumValueInfo == null)
- {
- t_enumValueInfo = new Hashtable();
- }
-
- SequentialEnumInfo sequentialEnumInfo = null;
-
- if (t_enumValueInfo.ContainsKey(enumType))
- {
- sequentialEnumInfo = t_enumValueInfo[enumType] as SequentialEnumInfo;
- }
- if (sequentialEnumInfo == null)
- {
- sequentialEnumInfo = new SequentialEnumInfo(enumType);
- Debug.Assert(t_enumValueInfo.Count <= MaxCache);
- t_enumValueInfo[enumType] = sequentialEnumInfo;
- }
- Debug.Assert(minVal == sequentialEnumInfo.MinValue, "Minimum passed in is not the actual minimum for the enum. Consider changing the parameters or using a different function.");
- Debug.Assert(maxVal == sequentialEnumInfo.MaxValue, "Maximum passed in is not the actual maximum for the enum. Consider changing the parameters or using a different function.");
- }
-
- private static void Debug_ValidateMask(Enum value, uint mask)
- {
- Type enumType = value.GetType();
- uint newMask = 0;
- foreach (int iVal in Enum.GetValues(enumType))
- {
- newMask = newMask | (uint)iVal;
- }
- Debug.Assert(newMask == mask, "Mask not valid in IsEnumValid!");
- }
-
- private static void Debug_NonSequentialEnumIsDefinedCheck(Enum value, int minVal, int maxVal, int maxBitsOn, bool isValid)
- {
- Type enumType = value.GetType();
- int actualMinimum = int.MaxValue;
- int actualMaximum = int.MinValue;
- int checkedValue = Convert.ToInt32(value, CultureInfo.InvariantCulture);
- int maxBitsFound = 0;
- bool foundValue = false;
- foreach (int iVal in Enum.GetValues(enumType))
- {
- actualMinimum = Math.Min(actualMinimum, iVal);
- actualMaximum = Math.Max(actualMaximum, iVal);
- maxBitsFound = Math.Max(maxBitsFound, GetBitCount((uint)iVal));
- if (checkedValue == iVal)
- {
- foundValue = true;
- }
- }
-
- Debug.Assert(minVal == actualMinimum, "Minimum passed in is not the actual minimum for the enum. Consider changing the parameters or using a different function.");
- Debug.Assert(minVal == actualMinimum, "Maximum passed in is not the actual maximum for the enum. Consider changing the parameters or using a different function.");
- Debug.Assert(maxBitsFound == maxBitsOn, "Incorrect usage of IsEnumValid function. The bits set to 1 in this enum was found to be: " + maxBitsFound.ToString(CultureInfo.InvariantCulture) + "this does not match what's passed in: " + maxBitsOn.ToString(CultureInfo.InvariantCulture));
- Debug.Assert(foundValue == isValid, string.Format(CultureInfo.InvariantCulture, "Returning {0} but we actually {1} found the value in the enum! Consider using a different overload to IsValidEnum.", isValid, ((foundValue) ? "have" : "have not")));
- }
-#endif
-
- /// <summary>
- /// WeakRefCollection - a collection that holds onto weak references
- ///
- /// Essentially you pass in the object as it is, and under the covers
- /// we only hold a weak reference to the object.
- ///
- /// -----------------------------------------------------------------
- /// !!!IMPORTANT USAGE NOTE!!!
- /// Users of this class should set the RefCheckThreshold property
- /// explicitly or call ScavengeReferences every once in a while to
- /// remove dead references.
- /// Also avoid calling Remove(item). Instead call RemoveByHashCode(item)
- /// to make sure dead refs are removed.
- /// -----------------------------------------------------------------
- ///
- /// </summary>
- internal class WeakRefCollection : IList
- {
- private int _refCheckThreshold = Int32.MaxValue; // this means this is disabled by default.
- private ArrayList _innerList;
-
- internal WeakRefCollection()
- {
- _innerList = new ArrayList(4);
- }
-
- internal WeakRefCollection(int size)
- {
- _innerList = new ArrayList(size);
- }
-
- internal ArrayList InnerList
- {
- get { return _innerList; }
- }
-
- /// <summary>
- /// Indicates the value where the collection should check its items to remove dead weakref left over.
- /// Note: When GC collects weak refs from this collection the WeakRefObject identity changes since its
- /// Target becomes null. This makes the item unrecognizable by the collection and cannot be
- /// removed - Remove(item) and Contains(item) will not find it anymore.
- /// </summary>
- public int RefCheckThreshold
- {
- get
- {
- return _refCheckThreshold;
- }
- set
- {
- _refCheckThreshold = value;
- }
- }
-
- public object this[int index]
- {
- get
- {
- WeakRefObject weakRef = InnerList[index] as WeakRefObject;
-
- if ((weakRef != null) && (weakRef.IsAlive))
- {
- return weakRef.Target;
- }
-
- return null;
- }
- set
- {
- InnerList[index] = CreateWeakRefObject(value);
- }
- }
-
- public void ScavengeReferences()
- {
- int currentIndex = 0;
- int currentCount = Count;
- for (int i = 0; i < currentCount; i++)
- {
- object item = this[currentIndex];
-
- if (item == null)
- {
- InnerList.RemoveAt(currentIndex);
- }
- else
- { // only incriment if we have not removed the item
- currentIndex++;
- }
- }
- }
-
- public override bool Equals(object obj)
- {
- WeakRefCollection other = obj as WeakRefCollection;
-
- if (other == this)
- {
- return true;
- }
-
- if (other == null || Count != other.Count)
- {
- return false;
- }
-
- for (int i = 0; i < Count; i++)
- {
- if (InnerList[i] != other.InnerList[i])
- {
- if (InnerList[i] == null || !InnerList[i].Equals(other.InnerList[i]))
- {
- return false;
- }
- }
- }
-
- return true;
- }
-
- public override int GetHashCode()
- {
- return base.GetHashCode();
- }
-
- private WeakRefObject CreateWeakRefObject(object value)
- {
- if (value == null)
- {
- return null;
- }
- return new WeakRefObject(value);
- }
-
- private static void Copy(WeakRefCollection sourceList, int sourceIndex, WeakRefCollection destinationList, int destinationIndex, int length)
- {
- if (sourceIndex < destinationIndex)
- {
- // We need to copy from the back forward to prevent overwrite if source and
- // destination lists are the same, so we need to flip the source/dest indices
- // to point at the end of the spans to be copied.
- sourceIndex = sourceIndex + length;
- destinationIndex = destinationIndex + length;
- for (; length > 0; length--)
- {
- destinationList.InnerList[--destinationIndex] = sourceList.InnerList[--sourceIndex];
- }
- }
- else
- {
- for (; length > 0; length--)
- {
- destinationList.InnerList[destinationIndex++] = sourceList.InnerList[sourceIndex++];
- }
- }
- }
-
- /// <summary>
- /// Removes the value using its hash code as its identity.
- /// This is needed because the underlying item in the collection may have already been collected changing
- /// the identity of the WeakRefObject making it impossible for the collection to identify it.
- /// See WeakRefObject for more info.
- /// </summary>
- public void RemoveByHashCode(object value)
- {
- if (value == null)
- {
- return;
- }
-
- int hash = value.GetHashCode();
-
- for (int idx = 0; idx < InnerList.Count; idx++)
- {
- if (InnerList[idx] != null && InnerList[idx].GetHashCode() == hash)
- {
- RemoveAt(idx);
- return;
- }
- }
- }
-
- #region IList Members
- public void Clear() { InnerList.Clear(); }
- public bool IsFixedSize { get { return InnerList.IsFixedSize; } }
- public bool Contains(object value) { return InnerList.Contains(CreateWeakRefObject(value)); }
- public void RemoveAt(int index) { InnerList.RemoveAt(index); }
- public void Remove(object value) { InnerList.Remove(CreateWeakRefObject(value)); }
- public int IndexOf(object value) { return InnerList.IndexOf(CreateWeakRefObject(value)); }
- public void Insert(int index, object value) { InnerList.Insert(index, CreateWeakRefObject(value)); }
- public int Add(object value)
- {
- if (Count > RefCheckThreshold)
- {
- ScavengeReferences();
- }
- return InnerList.Add(CreateWeakRefObject(value));
- }
- #endregion
-
- #region ICollection Members
- public int Count { get { return InnerList.Count; } }
- object ICollection.SyncRoot { get { return InnerList.SyncRoot; } }
- public bool IsReadOnly { get { return InnerList.IsReadOnly; } }
- public void CopyTo(Array array, int index) { InnerList.CopyTo(array, index); }
- bool ICollection.IsSynchronized { get { return InnerList.IsSynchronized; } }
- #endregion
-
- #region IEnumerable Members
- public IEnumerator GetEnumerator()
- {
- return InnerList.GetEnumerator();
- }
- #endregion
-
- /// <summary>
- /// Wraps a weak ref object.
- /// WARNING: Use this class carefully!
- /// When the weak ref is collected, this object looses its identity. This is bad when the object has been
- /// added to a collection since Contains(WeakRef(item)) and Remove(WeakRef(item)) would not be able to
- /// identify the item.
- /// </summary>
- internal class WeakRefObject
- {
- private int _hash;
- private WeakReference _weakHolder;
-
- internal WeakRefObject(object obj)
- {
- Debug.Assert(obj != null, "Unexpected null object!");
- _weakHolder = new WeakReference(obj);
- _hash = obj.GetHashCode();
- }
-
- internal bool IsAlive
- {
- get { return _weakHolder.IsAlive; }
- }
-
- internal object Target
- {
- get
- {
- return _weakHolder.Target;
- }
- }
-
- public override int GetHashCode()
- {
- return _hash;
- }
-
- public override bool Equals(object obj)
- {
- WeakRefObject other = obj as WeakRefObject;
-
- if (other == this)
- {
- return true;
- }
-
- if (other == null)
- {
- return false;
- }
-
- if (other.Target != Target)
- {
- if (Target == null || !Target.Equals(other.Target))
- {
- return false;
- }
- }
-
- return true;
- }
- }
- }
- }
-}
diff --git a/src/System.Drawing.Common/src/misc/CompModSwitches.cs b/src/System.Drawing.Common/src/misc/CompModSwitches.cs
index 88549705d1..962fe080b1 100644
--- a/src/System.Drawing.Common/src/misc/CompModSwitches.cs
+++ b/src/System.Drawing.Common/src/misc/CompModSwitches.cs
@@ -2,13 +2,14 @@
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
-[assembly: System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Performance", "CA1811:AvoidUncalledPrivateCode", Scope = "member", Target = "System.ComponentModel.CompModSwitches.get_DGEditColumnEditing():System.Diagnostics.TraceSwitch")]
-[assembly: System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Performance", "CA1811:AvoidUncalledPrivateCode", Scope = "member", Target = "System.ComponentModel.CompModSwitches.get_LayoutPerformance():System.Diagnostics.TraceSwitch")]
+using System.Diagnostics;
+using System.Diagnostics.CodeAnalysis;
+
+[assembly: SuppressMessage("Microsoft.Performance", "CA1811:AvoidUncalledPrivateCode", Scope = "member", Target = "System.ComponentModel.CompModSwitches.get_DGEditColumnEditing():System.Diagnostics.TraceSwitch")]
+[assembly: SuppressMessage("Microsoft.Performance", "CA1811:AvoidUncalledPrivateCode", Scope = "member", Target = "System.ComponentModel.CompModSwitches.get_LayoutPerformance():System.Diagnostics.TraceSwitch")]
namespace System.ComponentModel
{
- using System.Diagnostics;
-
internal static class CompModSwitches
{
private static TraceSwitch s_handleLeak;
@@ -21,11 +22,13 @@ namespace System.ComponentModel
{
s_handleLeak = new TraceSwitch("HANDLELEAK", "HandleCollector: Track Win32 Handle Leaks");
}
+
return s_handleLeak;
}
}
private static BooleanSwitch s_traceCollect;
+
public static BooleanSwitch TraceCollect
{
get
@@ -34,6 +37,7 @@ namespace System.ComponentModel
{
s_traceCollect = new BooleanSwitch("TRACECOLLECT", "HandleCollector: Trace HandleCollector operations");
}
+
return s_traceCollect;
}
}
diff --git a/src/System.Drawing.Common/src/misc/CoreSwitches.cs b/src/System.Drawing.Common/src/misc/CoreSwitches.cs
deleted file mode 100644
index 7c219b8840..0000000000
--- a/src/System.Drawing.Common/src/misc/CoreSwitches.cs
+++ /dev/null
@@ -1,26 +0,0 @@
-// Licensed to the .NET Foundation under one or more agreements.
-// The .NET Foundation licenses this file to you under the MIT license.
-// See the LICENSE file in the project root for more information.
-
-namespace System.ComponentModel
-{
- using System.Diagnostics;
-
- internal static class CoreSwitches
- {
- private static BooleanSwitch s_perfTrack;
-
- public static BooleanSwitch PerfTrack
- {
- get
- {
- if (s_perfTrack == null)
- {
- s_perfTrack = new BooleanSwitch("PERFTRACK", "Debug performance critical sections.");
- }
- return s_perfTrack;
- }
- }
- }
-}
-
diff --git a/src/System.Drawing.Common/src/misc/DbgUtil.cs b/src/System.Drawing.Common/src/misc/DbgUtil.cs
index 0273440bba..57ba6fbc24 100644
--- a/src/System.Drawing.Common/src/misc/DbgUtil.cs
+++ b/src/System.Drawing.Common/src/misc/DbgUtil.cs
@@ -4,42 +4,30 @@
using System.Diagnostics;
using System.Globalization;
-using System.Reflection;
using System.Runtime.InteropServices;
using System.Security.Permissions;
using System.Text;
+using System.Threading;
namespace System.Drawing.Internal
{
- /// <summary>
- /// Debug help utility.
- /// </summary>
- [
- ReflectionPermission(SecurityAction.Assert, MemberAccess = true),
- EnvironmentPermission(SecurityAction.Assert, Unrestricted = true),
- FileIOPermission(SecurityAction.Assert, Unrestricted = true),
- SecurityPermission(SecurityAction.Assert, Flags = SecurityPermissionFlag.UnmanagedCode),
- UIPermission(SecurityAction.Assert, Unrestricted = true)
- ]
+ [ReflectionPermission(SecurityAction.Assert, MemberAccess = true)]
+ [EnvironmentPermission(SecurityAction.Assert, Unrestricted = true)]
+ [FileIOPermission(SecurityAction.Assert, Unrestricted = true)]
+ [SecurityPermission(SecurityAction.Assert, Flags = SecurityPermissionFlag.UnmanagedCode)]
+ [UIPermission(SecurityAction.Assert, Unrestricted = true)]
internal sealed class DbgUtil
{
public const int
- FORMAT_MESSAGE_ALLOCATE_BUFFER = 0x00000100,
FORMAT_MESSAGE_IGNORE_INSERTS = 0x00000200,
FORMAT_MESSAGE_FROM_SYSTEM = 0x00001000,
FORMAT_MESSAGE_DEFAULT = FORMAT_MESSAGE_IGNORE_INSERTS | FORMAT_MESSAGE_FROM_SYSTEM;
- [DllImport(ExternDll.Kernel32, SetLastError = true, CharSet = System.Runtime.InteropServices.CharSet.Auto)]
+ [DllImport(ExternDll.Kernel32, SetLastError = true, CharSet = CharSet.Auto)]
public static extern int GetUserDefaultLCID();
- [DllImport(ExternDll.Kernel32, SetLastError = true, CharSet = System.Runtime.InteropServices.CharSet.Auto)]
- public static extern int FormatMessage(int dwFlags, HandleRef lpSource, int dwMessageId, int dwLanguageId, StringBuilder lpBuffer, int nSize, HandleRef arguments);
- public static int gdipInitMaxFrameCount = 8;
- // disable csharp compiler warning #0414: field assigned unused value
-#pragma warning disable 0414
- public static int gdiUseMaxFrameCount = 8;
- public static int finalizeMaxFrameCount = 5;
-#pragma warning restore 0414
+ [DllImport(ExternDll.Kernel32, SetLastError = true, CharSet = CharSet.Auto)]
+ public static extern int FormatMessage(int dwFlags, HandleRef lpSource, int dwMessageId, int dwLanguageId, StringBuilder lpBuffer, int nSize, HandleRef arguments);
/// <summary>
/// Call this method from your Dispose(bool) to assert that unmanaged resources has been explicitly disposed.
@@ -82,17 +70,6 @@ namespace System.Drawing.Internal
}
[Conditional("DEBUG")]
- public static void AssertWin32(bool expression, string message)
- {
-#if DEBUG
- if (!expression)
- {
- Debug.Fail(message + "\r\nError: " + DbgUtil.GetLastErrorStr());
- }
-#endif
- }
-
- [Conditional("DEBUG")]
public static void AssertWin32(bool expression, string format, object arg1)
{
#if DEBUG
@@ -107,61 +84,51 @@ namespace System.Drawing.Internal
[Conditional("DEBUG")]
public static void AssertWin32(bool expression, string format, object arg1, object arg2)
{
-#if DEBUG
if (!expression)
{
object[] args = new object[] { arg1, arg2 };
AssertWin32Impl(expression, format, args);
}
-#endif
}
[Conditional("DEBUG")]
public static void AssertWin32(bool expression, string format, object arg1, object arg2, object arg3)
{
-#if DEBUG
if (!expression)
{
object[] args = new object[] { arg1, arg2, arg3 };
AssertWin32Impl(expression, format, args);
}
-#endif
}
[Conditional("DEBUG")]
public static void AssertWin32(bool expression, string format, object arg1, object arg2, object arg3, object arg4)
{
-#if DEBUG
if (!expression)
{
object[] args = new object[] { arg1, arg2, arg3, arg4 };
AssertWin32Impl(expression, format, args);
}
-#endif
}
[Conditional("DEBUG")]
public static void AssertWin32(bool expression, string format, object arg1, object arg2, object arg3, object arg4, object arg5)
{
-#if DEBUG
if (!expression)
{
object[] args = new object[] { arg1, arg2, arg3, arg4, arg5 };
AssertWin32Impl(expression, format, args);
}
-#endif
}
[Conditional("DEBUG")]
private static void AssertWin32Impl(bool expression, string format, object[] args)
{
-#if DEBUG
if (!expression)
{
string message = string.Format(CultureInfo.CurrentCulture, format, args);
- Debug.Fail(message + "\r\nError: " + DbgUtil.GetLastErrorStr());
+ Debug.Fail($"{message}\r\nError: {GetLastErrorStr()}");
}
-#endif
}
// WARNING: Your PInvoke function needs to have the DllImport.SetLastError=true for this method
@@ -176,9 +143,9 @@ namespace System.Drawing.Internal
// to the method signature and set the SetLastError field to true.
public static string GetLastErrorStr()
{
- int MAX_SIZE = 255;
- StringBuilder buffer = new StringBuilder(MAX_SIZE);
- string message = String.Empty;
+ int MaxSize = 255;
+ var buffer = new StringBuilder(MaxSize);
+ string message = string.Empty;
int err = 0;
try
@@ -191,21 +158,17 @@ namespace System.Drawing.Internal
err,
GetUserDefaultLCID(),
buffer,
- MAX_SIZE,
+ MaxSize,
new HandleRef(null, IntPtr.Zero));
message = retVal != 0 ? buffer.ToString() : "<error returned>";
}
- catch (Exception ex)
+ catch (Exception ex) when (!IsCriticalException(ex))
{
- if (DbgUtil.IsCriticalException(ex))
- {
- throw; //rethrow critical exception.
- }
message = ex.ToString();
}
- return String.Format(CultureInfo.CurrentCulture, "0x{0:x8} - {1}", err, message);
+ return $"0x{err:x8} - {message}";
}
/// <summary>
@@ -217,128 +180,7 @@ namespace System.Drawing.Internal
return
ex is StackOverflowException ||
ex is OutOfMemoryException ||
- ex is System.Threading.ThreadAbortException;
- }
-
- public static string StackTrace
- {
- get
- {
- return Environment.StackTrace;
- }
- }
-
- /// <summary>
- /// Returns information about the top stack frames in a string format. The input param determines the number of
- /// frames to include.
- /// </summary>
- public static string StackFramesToStr(int maxFrameCount)
- {
- string trace = String.Empty;
-
- try
- {
- StackTrace st = new StackTrace(true);
- int dbgUtilFrameCount = 0;
-
- //
- // Ignore frames for methods on this library.
- // Note: The stack frame holds the latest frame at index 0.
- //
- while (dbgUtilFrameCount < st.FrameCount)
- {
- StackFrame sf = st.GetFrame(dbgUtilFrameCount);
-
- if (sf == null || sf.GetMethod().DeclaringType != typeof(DbgUtil))
- {
- break;
- }
-
- dbgUtilFrameCount++;
- }
-
- maxFrameCount += dbgUtilFrameCount; // add ignored frames.
-
- if (maxFrameCount > st.FrameCount)
- {
- maxFrameCount = st.FrameCount;
- }
-
- for (int i = dbgUtilFrameCount; i < maxFrameCount; i++)
- {
- StackFrame sf = st.GetFrame(i);
-
- if (sf == null)
- {
- continue;
- }
-
- MethodBase mi = sf.GetMethod();
-
- if (mi == null)
- {
- continue;
- }
-
- string args = String.Empty;
- string fileName = sf.GetFileName();
-
- int backSlashIndex = fileName == null ? -1 : fileName.LastIndexOf('\\');
-
- if (backSlashIndex != -1)
- {
- fileName = fileName.Substring(backSlashIndex + 1, fileName.Length - backSlashIndex - 1);
- }
-
- foreach (ParameterInfo pi in mi.GetParameters())
- {
- args += pi.ParameterType.Name + ", ";
- }
-
- if (args.Length > 0) // remove last comma.
- {
- args = args.Substring(0, args.Length - 2);
- }
-
- trace += String.Format(CultureInfo.CurrentCulture, "at {0} {1}.{2}({3})\r\n", fileName, mi.DeclaringType, mi.Name, args);
- }
- }
- catch (Exception ex)
- {
- if (IsCriticalException(ex))
- {
- throw; //rethrow critical exception.
- }
- trace += ex.ToString();
- }
-
- return trace.ToString();
- }
-
- /// <summary>
- /// Returns information about the top stack frames in a string format.
- /// </summary>
- public static string StackFramesToStr()
- {
- return StackFramesToStr(gdipInitMaxFrameCount);
- }
-
- /// <summary>
- /// Returns information about the top stack frames in a string format. The input param determines the number of
- /// frames to include. The 'message' parameter is used as the header of the returned string.
- /// </summary>
- public static string StackTraceToStr(string message, int frameCount)
- {
- return String.Format(CultureInfo.CurrentCulture, "{0}\r\nTop Stack Trace:\r\n{1}", message, DbgUtil.StackFramesToStr(frameCount));
- }
-
- /// <summary>
- /// Returns information about the top stack frames in a string format. The 'message' parameter is used as the header of the returned string.
- /// </summary>
- public static string StackTraceToStr(string message)
- {
- return StackTraceToStr(message, DbgUtil.gdipInitMaxFrameCount);
+ ex is ThreadAbortException;
}
}
}
-
diff --git a/src/System.Drawing.Common/src/misc/DebugHandleTracker.cs b/src/System.Drawing.Common/src/misc/DebugHandleTracker.cs
index 123406f3a4..3125f3797d 100644
--- a/src/System.Drawing.Common/src/misc/DebugHandleTracker.cs
+++ b/src/System.Drawing.Common/src/misc/DebugHandleTracker.cs
@@ -2,11 +2,10 @@
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
+using System.Collections;
using System.ComponentModel;
using System.Diagnostics;
-using Hashtable = System.Collections.Hashtable;
-
namespace System.Internal
{
/// <summary>
@@ -30,8 +29,8 @@ namespace System.Internal
if (CompModSwitches.HandleLeak.Level > TraceLevel.Off || CompModSwitches.TraceCollect.Enabled)
{
- System.Internal.HandleCollector.HandleAdded += new System.Internal.HandleChangeEventHandler(s_tracker.OnHandleAdd);
- System.Internal.HandleCollector.HandleRemoved += new System.Internal.HandleChangeEventHandler(s_tracker.OnHandleRemove);
+ HandleCollector.HandleAdded += new HandleChangeEventHandler(s_tracker.OnHandleAdd);
+ HandleCollector.HandleRemoved += new HandleChangeEventHandler(s_tracker.OnHandleRemove);
}
}
@@ -55,10 +54,7 @@ namespace System.Internal
for (int i = 0; i < types.Length; i++)
{
- if (types[i] != null)
- {
- types[i].IgnoreCurrentHandlesAsLeaks();
- }
+ types[i]?.IgnoreCurrentHandlesAsLeaks();
}
}
}
@@ -82,10 +78,7 @@ namespace System.Internal
Debug.WriteLine("------------Begin--CheckLeaks--------------------");
for (int i = 0; i < types.Length; i++)
{
- if (types[i] != null)
- {
- types[i].CheckLeaks();
- }
+ types[i]?.CheckLeaks();
}
Debug.WriteLine("-------------End--CheckLeaks---------------------");
}
@@ -154,7 +147,7 @@ namespace System.Internal
private int _handleCount;
private HandleEntry[] _buckets;
- private const int BUCKETS = 10;
+ private const int NumberOfBuckets = 10;
/// <summary>
/// Creates a new handle type.
@@ -162,7 +155,7 @@ namespace System.Internal
public HandleType(string name)
{
this.name = name;
- _buckets = new HandleEntry[BUCKETS];
+ _buckets = new HandleEntry[NumberOfBuckets];
}
/// <summary>
@@ -205,7 +198,7 @@ namespace System.Internal
bool reportedFirstLeak = false;
if (_handleCount > 0)
{
- for (int i = 0; i < BUCKETS; i++)
+ for (int i = 0; i < NumberOfBuckets; i++)
{
HandleEntry e = _buckets[i];
while (e != null)
@@ -235,7 +228,7 @@ namespace System.Internal
{
if (_handleCount > 0)
{
- for (int i = 0; i < BUCKETS; i++)
+ for (int i = 0; i < NumberOfBuckets; i++)
{
HandleEntry e = _buckets[i];
while (e != null)
@@ -253,7 +246,7 @@ namespace System.Internal
/// </summary>
private int ComputeHash(IntPtr handle)
{
- return (unchecked((int)handle) & 0xFFFF) % BUCKETS;
+ return (unchecked((int)handle) & 0xFFFF) % NumberOfBuckets;
}
/// <summary>
diff --git a/src/System.Drawing.Common/src/misc/DpiHelper.cs b/src/System.Drawing.Common/src/misc/DpiHelper.cs
index 45f18d756d..a883a2e9b2 100644
--- a/src/System.Drawing.Common/src/misc/DpiHelper.cs
+++ b/src/System.Drawing.Common/src/misc/DpiHelper.cs
@@ -7,8 +7,6 @@ using System.Drawing;
using System.Drawing.Drawing2D;
using System.Runtime.InteropServices;
-using CAPS = System.Drawing.SafeNativeMethods;
-
namespace System.Windows.Forms
{
/// <summary>
@@ -40,6 +38,7 @@ namespace System.Windows.Forms
{
return;
}
+
try
{
string value = ConfigurationManager.AppSettings.Get(EnableHighDpiConfigurationValueName);
@@ -51,17 +50,19 @@ namespace System.Windows.Forms
catch
{
}
+
if (s_enableHighDpi)
{
IntPtr hDC = UnsafeNativeMethods.GetDC(NativeMethods.NullHandleRef);
if (hDC != IntPtr.Zero)
{
- s_deviceDpiX = UnsafeNativeMethods.GetDeviceCaps(new HandleRef(null, hDC), CAPS.LOGPIXELSX);
- s_deviceDpiY = UnsafeNativeMethods.GetDeviceCaps(new HandleRef(null, hDC), CAPS.LOGPIXELSY);
+ s_deviceDpiX = UnsafeNativeMethods.GetDeviceCaps(new HandleRef(null, hDC), SafeNativeMethods.LOGPIXELSX);
+ s_deviceDpiY = UnsafeNativeMethods.GetDeviceCaps(new HandleRef(null, hDC), SafeNativeMethods.LOGPIXELSY);
UnsafeNativeMethods.ReleaseDC(NativeMethods.NullHandleRef, new HandleRef(null, hDC));
}
}
+
s_isInitialized = true;
}
@@ -74,6 +75,7 @@ namespace System.Windows.Forms
Initialize();
s_logicalToDeviceUnitsScalingFactorX = s_deviceDpiX / LogicalDpi;
}
+
return s_logicalToDeviceUnitsScalingFactorX;
}
}
@@ -87,6 +89,7 @@ namespace System.Windows.Forms
Initialize();
s_logicalToDeviceUnitsScalingFactorY = s_deviceDpiY / LogicalDpi;
}
+
return s_logicalToDeviceUnitsScalingFactorY;
}
}
@@ -124,8 +127,7 @@ namespace System.Windows.Forms
private static Bitmap ScaleBitmapToSize(Bitmap logicalImage, Size deviceImageSize)
{
- Bitmap deviceImage;
- deviceImage = new Bitmap(deviceImageSize.Width, deviceImageSize.Height, logicalImage.PixelFormat);
+ Bitmap deviceImage = new Bitmap(deviceImageSize.Width, deviceImageSize.Height, logicalImage.PixelFormat);
using (Graphics graphics = Graphics.FromImage(deviceImage))
{
@@ -149,7 +151,7 @@ namespace System.Windows.Forms
private static Bitmap CreateScaledBitmap(Bitmap logicalImage)
{
- Size deviceImageSize = DpiHelper.LogicalToDeviceUnits(logicalImage.Size);
+ Size deviceImageSize = LogicalToDeviceUnits(logicalImage.Size);
return ScaleBitmapToSize(logicalImage, deviceImageSize);
}
@@ -231,6 +233,7 @@ namespace System.Windows.Forms
{
return;
}
+
Bitmap deviceBitmap = CreateScaledBitmap(logicalBitmap);
if (deviceBitmap != null)
{
diff --git a/src/System.Drawing.Common/src/misc/ExternDll.cs b/src/System.Drawing.Common/src/misc/ExternDll.cs
index c2810fee30..85975da2cb 100644
--- a/src/System.Drawing.Common/src/misc/ExternDll.cs
+++ b/src/System.Drawing.Common/src/misc/ExternDll.cs
@@ -6,46 +6,13 @@ namespace System
{
internal static class ExternDll
{
- public const string Activeds = "activeds.dll";
- public const string Advapi32 = "advapi32.dll";
- public const string Comctl32 = "comctl32.dll";
public const string Comdlg32 = "comdlg32.dll";
public const string Gdi32 = "gdi32.dll";
public const string Gdiplus = "gdiplus.dll";
- public const string Hhctrl = "hhctrl.ocx";
- public const string Imm32 = "imm32.dll";
public const string Kernel32 = "kernel32.dll";
- public const string Loadperf = "Loadperf.dll";
- public const string Mscoree = "mscoree.dll";
- public const string Clr = "clr.dll";
- public const string Msi = "msi.dll";
- public const string Mqrt = "mqrt.dll";
- public const string Ntdll = "ntdll.dll";
- public const string Ole32 = "ole32.dll";
- public const string Oleacc = "oleacc.dll";
public const string Oleaut32 = "oleaut32.dll";
- public const string Olepro32 = "olepro32.dll";
- public const string PerfCounter = "perfcounter.dll";
- public const string Powrprof = "Powrprof.dll";
- public const string Psapi = "psapi.dll";
public const string Shell32 = "shell32.dll";
public const string User32 = "user32.dll";
- public const string Uxtheme = "uxtheme.dll";
- public const string WinMM = "winmm.dll";
public const string Winspool = "winspool.drv";
- public const string Wtsapi32 = "wtsapi32.dll";
- public const string Version = "version.dll";
- public const string Vsassert = "vsassert.dll";
- public const string Fxassert = "Fxassert.dll";
- public const string Shlwapi = "shlwapi.dll";
- public const string Crypt32 = "crypt32.dll";
-
- // system.data specific
- internal const string Odbc32 = "odbc32.dll";
- internal const string SNI = "System.Data.dll";
-
- // system.data.oracleclient specific
- internal const string OciDll = "oci.dll";
- internal const string OraMtsDll = "oramts.dll";
}
}
diff --git a/src/System.Drawing.Common/src/misc/GDI/DeviceContext.cs b/src/System.Drawing.Common/src/misc/GDI/DeviceContext.cs
index dfa1a80222..ed003cdcbf 100644
--- a/src/System.Drawing.Common/src/misc/GDI/DeviceContext.cs
+++ b/src/System.Drawing.Common/src/misc/GDI/DeviceContext.cs
@@ -86,22 +86,6 @@ namespace System.Drawing.Internal
#endif
/// <summary>
- /// Specifies whether a modification has been applied to the dc, like setting the clipping area or a coordinate
- /// transform.
- /// </summary>
-
- /// <summary>
- /// The device type the context refers to.
- /// </summary>
- public DeviceContextType DeviceContextType
- {
- get
- {
- return _dcType;
- }
- }
-
- /// <summary>
/// This object's hdc. If this property is called, then the object will be used as an HDC wrapper, so the hdc
/// is cached and calls to GetHdc/ReleaseHdc won't PInvoke into GDI. Call Dispose to properly release the hdc.
/// </summary>
@@ -146,42 +130,6 @@ namespace System.Drawing.Internal
_hCurrentFont = _hInitialFont = IntUnsafeNativeMethods.GetCurrentObject(new HandleRef(this, _hDC), IntNativeMethods.OBJ_FONT);
}
- public void DeleteObject(IntPtr handle, GdiObjectType type)
- {
- IntPtr handleToDelete = IntPtr.Zero;
- switch (type)
- {
- case GdiObjectType.Pen:
- if (handle == _hCurrentPen)
- {
- IntPtr currentPen = IntUnsafeNativeMethods.SelectObject(new HandleRef(this, Hdc), new HandleRef(this, _hInitialPen));
- Debug.Assert(currentPen == _hCurrentPen, "DeviceContext thinks a different pen is selected than the HDC");
- _hCurrentPen = IntPtr.Zero;
- }
- handleToDelete = handle;
- break;
- case GdiObjectType.Brush:
- if (handle == _hCurrentBrush)
- {
- IntPtr currentBrush = IntUnsafeNativeMethods.SelectObject(new HandleRef(this, Hdc), new HandleRef(this, _hInitialBrush));
- Debug.Assert(currentBrush == _hCurrentBrush, "DeviceContext thinks a different brush is selected than the HDC");
- _hCurrentBrush = IntPtr.Zero;
- }
- handleToDelete = handle;
- break;
- case GdiObjectType.Bitmap:
- if (handle == _hCurrentBmp)
- {
- IntPtr currentBmp = IntUnsafeNativeMethods.SelectObject(new HandleRef(this, Hdc), new HandleRef(this, _hInitialBmp));
- Debug.Assert(currentBmp == _hCurrentBmp, "DeviceContext thinks a different brush is selected than the HDC");
- _hCurrentBmp = IntPtr.Zero;
- }
- handleToDelete = handle;
- break;
- }
-
- IntUnsafeNativeMethods.DeleteObject(new HandleRef(this, handleToDelete));
- }
/// <summary>
/// Constructor to contruct a DeviceContext object from an window handle.
@@ -271,16 +219,9 @@ namespace System.Drawing.Internal
/// <summary>
/// When hwnd is null, we are getting the screen DC.
/// </summary>
- public static DeviceContext FromHwnd(IntPtr hwnd)
- {
- return new DeviceContext(hwnd);
- }
-
+ public static DeviceContext FromHwnd(IntPtr hwnd) => new DeviceContext(hwnd);
- ~DeviceContext()
- {
- Dispose(false);
- }
+ ~DeviceContext() => Dispose(false);
public void Dispose()
{
@@ -295,10 +236,7 @@ namespace System.Drawing.Internal
return;
}
- if (Disposing != null)
- {
- Disposing(this, EventArgs.Empty);
- }
+ Disposing?.Invoke(this, EventArgs.Empty);
_disposed = true;
@@ -389,27 +327,6 @@ namespace System.Drawing.Internal
}
}
-
- /// <summary>
- /// Specifies whether the DC is in GM_ADVANCE mode (supported only in NT platforms). If false, it is in
- /// GM_COMPATIBLE mode.
- /// </summary>
- public DeviceContextGraphicsMode GraphicsMode
- {
- get
- {
- return (DeviceContextGraphicsMode)IntUnsafeNativeMethods.GetGraphicsMode(new HandleRef(this, _hDC));
- }
- }
-
- /// <summary>
- /// Sets the dc graphics mode and returns the old value.
- /// </summary>
- public DeviceContextGraphicsMode SetGraphicsMode(DeviceContextGraphicsMode newMode)
- {
- return (DeviceContextGraphicsMode)IntUnsafeNativeMethods.SetGraphicsMode(new HandleRef(this, _hDC), unchecked((int)newMode));
- }
-
/// <summary>
/// Restores the device context to the specified state. The DC is restored by popping state information off a
/// stack created by earlier calls to the SaveHdc function.
@@ -564,11 +481,7 @@ namespace System.Drawing.Internal
/// <summary>
/// This allows collections to treat DeviceContext objects wrapping the same HDC as the same objects.
/// </summary>
- public override int GetHashCode()
- {
- return _hDC.GetHashCode();
- }
-
+ public override int GetHashCode() => _hDC.GetHashCode();
internal class GraphicsState
{
diff --git a/src/System.Drawing.Common/src/misc/GDI/DeviceContextGraphicsMode.cs b/src/System.Drawing.Common/src/misc/GDI/DeviceContextGraphicsMode.cs
deleted file mode 100644
index c7fd9c0125..0000000000
--- a/src/System.Drawing.Common/src/misc/GDI/DeviceContextGraphicsMode.cs
+++ /dev/null
@@ -1,39 +0,0 @@
-// Licensed to the .NET Foundation under one or more agreements.
-// The .NET Foundation licenses this file to you under the MIT license.
-// See the LICENSE file in the project root for more information.
-
-namespace System.Drawing.Internal
-{
- /// <summary>
- /// Specifies the graphics mode of a device context.
- /// </summary>
- internal enum DeviceContextGraphicsMode
- {
- /*
- Sets the graphics mode that is compatible with 16-bit Windows. This is the default mode.
- If this value is specified, the application can only modify the world-to-device transform
- by calling functions that set window and viewport extents and origins, but not by using
- SetWorldTransform or ModifyWorldTransform; calls to those functions will fail.
- Examples of functions that set window and viewport extents and origins are SetViewportExtEx
- and SetWindowExtEx.
- */
- Compatible = 1,
-
- /*
- Windows NT/2000/XP: Sets the advanced graphics mode that allows world transformations. This value
- must be specified if the application will set or modify the world transformation for the specified
- device context. In this mode all graphics, including text output, fully conform to the world-to-device
- transformation specified in the device context.
- Windows 95/98/Me:The GM_ADVANCED value is not supported. When playing enhanced metafiles, the system
- attempts to make enhanced metafiles look the same as they do on Windows NT/2000/XP. To accomplish this,
- the system may simulate GM_ADVANCED mode when playing specific enhanced metafile records.
- */
- Advanced = 2,
-
- /*
- Resets the current world transformation by using the identity matrix. If this mode is specified,
- the XFORM structure pointed to by lpXform is ignored.
- */
- ModifyWorldIdentity = 1
- }
-}
diff --git a/src/System.Drawing.Common/src/misc/GDI/DeviceContexts.cs b/src/System.Drawing.Common/src/misc/GDI/DeviceContexts.cs
index ba149662bf..d39d5bf25e 100644
--- a/src/System.Drawing.Common/src/misc/GDI/DeviceContexts.cs
+++ b/src/System.Drawing.Common/src/misc/GDI/DeviceContexts.cs
@@ -20,8 +20,10 @@ namespace System.Drawing.Internal
{
if (t_activeDeviceContexts == null)
{
- t_activeDeviceContexts = new ClientUtils.WeakRefCollection();
- t_activeDeviceContexts.RefCheckThreshold = 20;
+ t_activeDeviceContexts = new ClientUtils.WeakRefCollection()
+ {
+ RefCheckThreshold = 20
+ };
}
if (!t_activeDeviceContexts.Contains(dc))
@@ -33,9 +35,7 @@ namespace System.Drawing.Internal
private static void OnDcDisposing(object sender, EventArgs e)
{
- DeviceContext dc = sender as DeviceContext;
-
- if (dc != null)
+ if (sender is DeviceContext dc)
{
dc.Disposing -= new EventHandler(OnDcDisposing);
RemoveDeviceContext(dc);
@@ -44,11 +44,7 @@ namespace System.Drawing.Internal
internal static void RemoveDeviceContext(DeviceContext dc)
{
- if (t_activeDeviceContexts == null)
- {
- return;
- }
- t_activeDeviceContexts.RemoveByHashCode(dc);
+ t_activeDeviceContexts?.RemoveByHashCode(dc);
}
}
}
diff --git a/src/System.Drawing.Common/src/misc/GDI/GdiObjectType.cs b/src/System.Drawing.Common/src/misc/GDI/GdiObjectType.cs
deleted file mode 100644
index 906f2cf235..0000000000
--- a/src/System.Drawing.Common/src/misc/GDI/GdiObjectType.cs
+++ /dev/null
@@ -1,27 +0,0 @@
-// Licensed to the .NET Foundation under one or more agreements.
-// The .NET Foundation licenses this file to you under the MIT license.
-// See the LICENSE file in the project root for more information.
-
-namespace System.Drawing.Internal
-{
- /// <summary>
- /// Specifies the the type of a GDI object.
- /// </summary>
- internal enum GdiObjectType
- {
- Pen = 1,
- Brush = 2,
- DisplayDC = 3,
- MetafileDC = 4,
- Palette = 5,
- Font = 6,
- Bitmap = 7,
- Region = 8,
- Metafile = 9,
- MemoryDC = 10,
- ExtendedPen = 11,
- EnhancedMetafileDC = 12,
- EnhMetafile = 13,
- ColorSpace = 14
- }
-}
diff --git a/src/System.Drawing.Common/src/misc/GDI/NativeMethods.cs b/src/System.Drawing.Common/src/misc/GDI/NativeMethods.cs
index aac76cc6e0..1eb799cb14 100644
--- a/src/System.Drawing.Common/src/misc/GDI/NativeMethods.cs
+++ b/src/System.Drawing.Common/src/misc/GDI/NativeMethods.cs
@@ -2,7 +2,6 @@
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
-using System.Diagnostics;
using System.Diagnostics.CodeAnalysis;
using System.Runtime.InteropServices;
@@ -12,124 +11,10 @@ namespace System.Drawing.Internal
{
[SuppressMessage("Microsoft.Reliability", "CA2006:UseSafeHandleToEncapsulateNativeResources")]
- public const int
- DT_TOP = 0x00000000,
- DT_LEFT = 0x00000000,
- DT_CENTER = 0x00000001,
- DT_RIGHT = 0x00000002,
- DT_VCENTER = 0x00000004,
- DT_BOTTOM = 0x00000008,
- DT_WORDBREAK = 0x00000010,
- DT_SINGLELINE = 0x00000020,
- DT_EXPANDTABS = 0x00000040,
- DT_TABSTOP = 0x00000080,
- DT_NOCLIP = 0x00000100,
- DT_EXTERNALLEADING = 0x00000200,
- DT_CALCRECT = 0x00000400,
- DT_NOPREFIX = 0x00000800,
- DT_INTERNAL = 0x00001000,
- DT_EDITCONTROL = 0x00002000,
- DT_PATH_ELLIPSIS = 0x00004000,
- DT_END_ELLIPSIS = 0x00008000,
- DT_MODIFYSTRING = 0x00010000,
- DT_RTLREADING = 0x00020000,
- DT_WORD_ELLIPSIS = 0x00040000,
- DT_NOFULLWIDTHCHARBREAK = 0x00080000,
- DT_HIDEPREFIX = 0x00100000,
- DT_PREFIXONLY = 0x00200000,
-
- DIB_RGB_COLORS = 0,
- BI_BITFIELDS = 3,
- BI_RGB = 0,
- BITMAPINFO_MAX_COLORSIZE = 256,
- SPI_GETICONTITLELOGFONT = 0x001F,
- SPI_GETNONCLIENTMETRICS = 41,
- DEFAULT_GUI_FONT = 17,
- HOLLOW_BRUSH = 5,
-
- BITSPIXEL = 12,
- ALTERNATE = 1,
- WINDING = 2,
-
- SRCCOPY = 0x00CC0020,
- SRCPAINT = 0x00EE0086, /* dest = source OR dest */
- SRCAND = 0x008800C6, /* dest = source AND dest */
- SRCINVERT = 0x00660046, /* dest = source XOR dest */
- SRCERASE = 0x00440328, /* dest = source AND (NOT dest ) */
- NOTSRCCOPY = 0x00330008, /* dest = (NOT source) */
- NOTSRCERASE = 0x001100A6, /* dest = (NOT src) AND (NOT dest) */
- MERGECOPY = 0x00C000CA, /* dest = (source AND pattern) */
- MERGEPAINT = 0x00BB0226, /* dest = (NOT source) OR dest */
- PATCOPY = 0x00F00021, /* dest = pattern */
- PATPAINT = 0x00FB0A09, /* dest = DPSnoo */
- PATINVERT = 0x005A0049, /* dest = pattern XOR dest */
- DSTINVERT = 0x00550009, /* dest = (NOT dest) */
- BLACKNESS = 0x00000042, /* dest = BLACK */
- WHITENESS = 0x00FF0062, /* dest = WHITE */
- CAPTUREBLT = 0x40000000, /* Include layered windows */
-
-
- /* FONT WEIGHT (BOLD) VALUES */
- FW_DONTCARE = 0,
- FW_NORMAL = 400,
- FW_BOLD = 700,
- // some others...
-
- /* FONT CHARACTER SET */
- ANSI_CHARSET = 0,
- DEFAULT_CHARSET = 1,
- // plus others ....
-
- /* Font OutPrecision */
- OUT_DEFAULT_PRECIS = 0,
- OUT_TT_PRECIS = 4,
- OUT_TT_ONLY_PRECIS = 7,
- // some others...
-
- /* Font clip precision */
- CLIP_DEFAULT_PRECIS = 0,
- // some others...
-
- /* Font Quality */
- DEFAULT_QUALITY = 0,
- DRAFT_QUALITY = 1,
- PROOF_QUALITY = 2,
- NONANTIALIASED_QUALITY = 3,
- ANTIALIASED_QUALITY = 4,
- CLEARTYPE_QUALITY = 5,
- CLEARTYPE_NATURAL_QUALITY = 6,
-
- /* Object Definitions for GetCurrentObject() and others. */
- OBJ_PEN = 1,
- OBJ_BRUSH = 2,
- OBJ_DC = 3,
- OBJ_METADC = 4,
- // OBJ_PAL = 5,
- OBJ_FONT = 6,
- OBJ_BITMAP = 7,
- // OBJ_REGION = 8,
- // OBJ_METAFILE = 9,
- OBJ_MEMDC = 10,
- OBJ_EXTPEN = 11,
- OBJ_ENHMETADC = 12,
- // OBJ_ENHMETAFILE = 13,
- // OBJ_COLORSPACE = 14
-
- // Brush styles
- BS_SOLID = 0,
- BS_HATCHED = 2,
- // BS_PATTERN = 3,
- // some others...
-
- // Code page
- CP_ACP = 0, // ANSI
-
-
- FORMAT_MESSAGE_ALLOCATE_BUFFER = 0x00000100,
- FORMAT_MESSAGE_IGNORE_INSERTS = 0x00000200,
- FORMAT_MESSAGE_FROM_SYSTEM = 0x00001000,
- FORMAT_MESSAGE_DEFAULT = FORMAT_MESSAGE_IGNORE_INSERTS | FORMAT_MESSAGE_FROM_SYSTEM;
- // some others...
+ public const int OBJ_PEN = 1;
+ public const int OBJ_BRUSH = 2;
+ public const int OBJ_FONT = 6;
+ public const int OBJ_BITMAP = 7;
public enum RegionFlags
{
@@ -147,47 +32,7 @@ namespace System.Drawing.Internal
public int right;
public int bottom;
- public RECT(int left, int top, int right, int bottom)
- {
- this.left = left;
- this.top = top;
- this.right = right;
- this.bottom = bottom;
- }
-
- public RECT(System.Drawing.Rectangle r)
- {
- left = r.Left;
- top = r.Top;
- right = r.Right;
- bottom = r.Bottom;
- }
-
- public static RECT FromXYWH(int x, int y, int width, int height)
- {
- return new RECT(
- x,
- y,
- x + width,
- y + height);
- }
-
- public Size Size
- {
- get
- {
- return new Size(right - left, bottom - top);
- }
- }
-
- public System.Drawing.Rectangle ToRectangle()
- {
- return new Rectangle(
- left,
- top,
- right - left,
- bottom - top);
- }
+ public Size Size => new Size(right - left, bottom - top);
}
[StructLayout(LayoutKind.Sequential)]
@@ -195,61 +40,6 @@ namespace System.Drawing.Internal
{
public int x;
public int y;
-
- public POINT()
- {
- }
-
- public POINT(int x, int y)
- {
- this.x = x;
- this.y = y;
- }
-
- public System.Drawing.Point ToPoint()
- {
- return new System.Drawing.Point(x, y);
- }
- }
-
- [StructLayout(LayoutKind.Sequential)]
- public class DRAWTEXTPARAMS
- {
- private int _cbSize = Marshal.SizeOf(typeof(DRAWTEXTPARAMS));
- public int iTabLength;
- public int iLeftMargin;
- public int iRightMargin;
-
- /// <devdoc>
- /// Receives the number of characters processed by DrawTextEx, including white-space characters.
- /// The number can be the length of the string or the index of the first line that falls below the drawing area.
- /// Note that DrawTextEx always processes the entire string if the DT_NOCLIP formatting flag is specified.
- /// </devdoc>
- public int uiLengthDrawn;
-
- public DRAWTEXTPARAMS()
- {
- }
- public DRAWTEXTPARAMS(DRAWTEXTPARAMS original)
- {
- iLeftMargin = original.iLeftMargin;
- iRightMargin = original.iRightMargin;
- iTabLength = original.iTabLength;
- }
-
- public DRAWTEXTPARAMS(int leftMargin, int rightMargin)
- {
- iLeftMargin = leftMargin;
- iRightMargin = rightMargin;
- }
- }
-
- [StructLayout(LayoutKind.Sequential)]
- public class LOGBRUSH
- {
- public int lbStyle;
- public int lbColor;
- public int lbHatch;
}
[StructLayout(LayoutKind.Sequential, CharSet = CharSet.Auto)]
@@ -268,104 +58,8 @@ namespace System.Drawing.Internal
public byte lfClipPrecision;
public byte lfQuality;
public byte lfPitchAndFamily;
- [MarshalAs(System.Runtime.InteropServices.UnmanagedType.ByValTStr, SizeConst = 32)]
+ [MarshalAs(UnmanagedType.ByValTStr, SizeConst = 32)]
public string lfFaceName;
-
- public LOGFONT()
- {
- }
-
- public LOGFONT(LOGFONT lf)
- {
- Debug.Assert(lf != null, "lf is null");
-
- lfHeight = lf.lfHeight;
- lfWidth = lf.lfWidth;
- lfEscapement = lf.lfEscapement;
- lfOrientation = lf.lfOrientation;
- lfWeight = lf.lfWeight;
- lfItalic = lf.lfItalic;
- lfUnderline = lf.lfUnderline;
- lfStrikeOut = lf.lfStrikeOut;
- lfCharSet = lf.lfCharSet;
- lfOutPrecision = lf.lfOutPrecision;
- lfClipPrecision = lf.lfClipPrecision;
- lfQuality = lf.lfQuality;
- lfPitchAndFamily = lf.lfPitchAndFamily;
- lfFaceName = lf.lfFaceName;
- }
- }
-
- [StructLayout(LayoutKind.Sequential, CharSet = CharSet.Unicode)]
- public struct TEXTMETRIC
- {
- public int tmHeight;
- public int tmAscent;
- public int tmDescent;
- public int tmInternalLeading;
- public int tmExternalLeading;
- public int tmAveCharWidth;
- public int tmMaxCharWidth;
- public int tmWeight;
- public int tmOverhang;
- public int tmDigitizedAspectX;
- public int tmDigitizedAspectY;
- public char tmFirstChar;
- public char tmLastChar;
- public char tmDefaultChar;
- public char tmBreakChar;
- public byte tmItalic;
- public byte tmUnderlined;
- public byte tmStruckOut;
- public byte tmPitchAndFamily;
- public byte tmCharSet;
- }
-
- [StructLayout(LayoutKind.Sequential, CharSet = CharSet.Ansi)]
- public struct TEXTMETRICA
- {
- public int tmHeight;
- public int tmAscent;
- public int tmDescent;
- public int tmInternalLeading;
- public int tmExternalLeading;
- public int tmAveCharWidth;
- public int tmMaxCharWidth;
- public int tmWeight;
- public int tmOverhang;
- public int tmDigitizedAspectX;
- public int tmDigitizedAspectY;
- public byte tmFirstChar;
- public byte tmLastChar;
- public byte tmDefaultChar;
- public byte tmBreakChar;
- public byte tmItalic;
- public byte tmUnderlined;
- public byte tmStruckOut;
- public byte tmPitchAndFamily;
- public byte tmCharSet;
- }
-
- [StructLayout(LayoutKind.Sequential)]
- public class SIZE
- {
- public int cx;
- public int cy;
-
- public SIZE()
- {
- }
-
- public SIZE(int cx, int cy)
- {
- this.cx = cx;
- this.cy = cy;
- }
-
- public System.Drawing.Size ToSize()
- {
- return new System.Drawing.Size(cx, cy);
- }
}
}
}
diff --git a/src/System.Drawing.Common/src/misc/GDI/SafeNativeMethods.cs b/src/System.Drawing.Common/src/misc/GDI/SafeNativeMethods.cs
index 979b23efa8..c25dcd7ae3 100644
--- a/src/System.Drawing.Common/src/misc/GDI/SafeNativeMethods.cs
+++ b/src/System.Drawing.Common/src/misc/GDI/SafeNativeMethods.cs
@@ -2,26 +2,22 @@
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
+using System.Runtime.InteropServices;
+using System.Security;
+
namespace System.Drawing.Internal
{
- using System.Runtime.InteropServices;
-
/// <summary>
/// This is an extract of the System.Drawing IntNativeMethods in the CommonUI tree.
/// This is done to be able to compile the GDI code in both assemblies System.Drawing and System.Windows.Forms.
/// </summary>
- [System.Security.SuppressUnmanagedCodeSecurityAttribute()]
+ [SuppressUnmanagedCodeSecurity]
internal static partial class IntSafeNativeMethods
{
public sealed class CommonHandles
{
static CommonHandles() { }
-
- /// <summary>
- /// Handle type for enhanced metafiles.
- /// </summary>
- public static readonly int EMF = System.Internal.HandleCollector.RegisterType("EnhancedMetaFile", 20, 500);
-
+
/// <summary>
/// Handle type for GDI objects.
/// </summary>
@@ -34,55 +30,14 @@ namespace System.Drawing.Internal
public static readonly int HDC = System.Internal.HandleCollector.RegisterType("HDC", 100, 2); // wait for 2 dc's before collecting
}
- // Brush.
-
- [DllImport(ExternDll.Gdi32, SetLastError = true, ExactSpelling = true, EntryPoint = "CreateSolidBrush", CharSet = System.Runtime.InteropServices.CharSet.Auto)]
- private static extern IntPtr IntCreateSolidBrush(int crColor);
- public static IntPtr CreateSolidBrush(int crColor)
- {
- IntPtr hBrush = System.Internal.HandleCollector.Add(IntCreateSolidBrush(crColor), IntSafeNativeMethods.CommonHandles.GDI);
- DbgUtil.AssertWin32(hBrush != IntPtr.Zero, "IntCreateSolidBrush(color={0}) failed.", crColor);
- return hBrush;
- }
-
- // Pen.
-
- [DllImport(ExternDll.Gdi32, SetLastError = true, ExactSpelling = true, EntryPoint = "CreatePen", CharSet = System.Runtime.InteropServices.CharSet.Auto)]
- private static extern IntPtr IntCreatePen(int fnStyle, int nWidth, int crColor);
- public static IntPtr CreatePen(int fnStyle, int nWidth, int crColor)
- {
- IntPtr hPen = System.Internal.HandleCollector.Add(IntCreatePen(fnStyle, nWidth, crColor), IntSafeNativeMethods.CommonHandles.GDI);
- DbgUtil.AssertWin32(hPen != IntPtr.Zero, "IntCreatePen(style={0}, width={1}, color=[{2}]) failed.", fnStyle, nWidth, crColor);
- return hPen;
- }
-
- [DllImport(ExternDll.Gdi32, SetLastError = true, ExactSpelling = true, EntryPoint = "ExtCreatePen", CharSet = System.Runtime.InteropServices.CharSet.Auto)]
- private static extern IntPtr IntExtCreatePen(int fnStyle, int dwWidth, IntNativeMethods.LOGBRUSH lplb, int dwStyleCount, [MarshalAs(UnmanagedType.LPArray)] int[] lpStyle);
- public static IntPtr ExtCreatePen(int fnStyle, int dwWidth, IntNativeMethods.LOGBRUSH lplb, int dwStyleCount, int[] lpStyle)
- {
- IntPtr hPen = System.Internal.HandleCollector.Add(IntExtCreatePen(fnStyle, dwWidth, lplb, dwStyleCount, lpStyle), IntSafeNativeMethods.CommonHandles.GDI);
- DbgUtil.AssertWin32(hPen != IntPtr.Zero, "IntExtCreatePen(style={0}, width={1}, brush={2}, styleCount={3}, styles={4}) failed.", fnStyle, dwWidth, lplb, dwStyleCount, lpStyle);
- return hPen;
- }
-
- // Region
-
- [DllImport(ExternDll.Gdi32, SetLastError = true, ExactSpelling = true, EntryPoint = "CreateRectRgn", CharSet = System.Runtime.InteropServices.CharSet.Auto)]
+ [DllImport(ExternDll.Gdi32, SetLastError = true, ExactSpelling = true, EntryPoint = "CreateRectRgn", CharSet = CharSet.Auto)]
public static extern IntPtr IntCreateRectRgn(int x1, int y1, int x2, int y2);
+
public static IntPtr CreateRectRgn(int x1, int y1, int x2, int y2)
{
- IntPtr hRgn = System.Internal.HandleCollector.Add(IntCreateRectRgn(x1, y1, x2, y2), IntSafeNativeMethods.CommonHandles.GDI);
+ IntPtr hRgn = System.Internal.HandleCollector.Add(IntCreateRectRgn(x1, y1, x2, y2), CommonHandles.GDI);
DbgUtil.AssertWin32(hRgn != IntPtr.Zero, "IntCreateRectRgn([x1={0}, y1={1}, x2={2}, y2={3}]) failed.", x1, y1, x2, y2);
return hRgn;
}
-
- // Misc.
-
- [DllImport(ExternDll.Kernel32, SetLastError = true, CharSet = System.Runtime.InteropServices.CharSet.Auto)]
- public static extern int GetUserDefaultLCID();
-
- [DllImport(ExternDll.Gdi32, SetLastError = true, ExactSpelling = true, CharSet = System.Runtime.InteropServices.CharSet.Auto)]
- public static extern bool GdiFlush();
}
}
-
diff --git a/src/System.Drawing.Common/src/misc/GDI/UnsafeNativeMethods.cs b/src/System.Drawing.Common/src/misc/GDI/UnsafeNativeMethods.cs
index 311eda515c..dd91040e8a 100644
--- a/src/System.Drawing.Common/src/misc/GDI/UnsafeNativeMethods.cs
+++ b/src/System.Drawing.Common/src/misc/GDI/UnsafeNativeMethods.cs
@@ -4,14 +4,16 @@
using System.Diagnostics;
using System.Runtime.InteropServices;
+using System.Security;
namespace System.Drawing.Internal
{
- [System.Security.SuppressUnmanagedCodeSecurityAttribute]
+ [SuppressUnmanagedCodeSecurity]
internal static partial class IntUnsafeNativeMethods
{
- [DllImport(ExternDll.User32, SetLastError = true, ExactSpelling = true, EntryPoint = "GetDC", CharSet = System.Runtime.InteropServices.CharSet.Auto)]
+ [DllImport(ExternDll.User32, SetLastError = true, ExactSpelling = true, EntryPoint = "GetDC", CharSet = CharSet.Auto)]
public static extern IntPtr IntGetDC(HandleRef hWnd);
+
public static IntPtr GetDC(HandleRef hWnd)
{
IntPtr hdc = System.Internal.HandleCollector.Add(IntGetDC(hWnd), IntSafeNativeMethods.CommonHandles.HDC);
@@ -25,6 +27,7 @@ namespace System.Drawing.Internal
/// </summary>
[DllImport(ExternDll.Gdi32, SetLastError = true, ExactSpelling = true, EntryPoint = "DeleteDC", CharSet = CharSet.Auto)]
public static extern bool IntDeleteDC(HandleRef hDC);
+
public static bool DeleteDC(HandleRef hDC)
{
System.Internal.HandleCollector.Remove((IntPtr)hDC, IntSafeNativeMethods.CommonHandles.GDI);
@@ -32,6 +35,7 @@ namespace System.Drawing.Internal
DbgUtil.AssertWin32(retVal, "DeleteDC([hdc=0x{0:X8}]) failed.", hDC.Handle);
return retVal;
}
+
public static bool DeleteHDC(HandleRef hDC)
{
System.Internal.HandleCollector.Remove((IntPtr)hDC, IntSafeNativeMethods.CommonHandles.HDC);
@@ -40,8 +44,9 @@ namespace System.Drawing.Internal
return retVal;
}
- [DllImport(ExternDll.User32, SetLastError = true, ExactSpelling = true, EntryPoint = "ReleaseDC", CharSet = System.Runtime.InteropServices.CharSet.Auto)]
+ [DllImport(ExternDll.User32, SetLastError = true, ExactSpelling = true, EntryPoint = "ReleaseDC", CharSet = CharSet.Auto)]
public static extern int IntReleaseDC(HandleRef hWnd, HandleRef hDC);
+
public static int ReleaseDC(HandleRef hWnd, HandleRef hDC)
{
System.Internal.HandleCollector.Remove((IntPtr)hDC, IntSafeNativeMethods.CommonHandles.HDC);
@@ -49,17 +54,19 @@ namespace System.Drawing.Internal
return IntReleaseDC(hWnd, hDC);
}
- [DllImport(ExternDll.Gdi32, SetLastError = true, EntryPoint = "CreateDC", CharSet = System.Runtime.InteropServices.CharSet.Auto)]
+ [DllImport(ExternDll.Gdi32, SetLastError = true, EntryPoint = "CreateDC", CharSet = CharSet.Auto)]
public static extern IntPtr IntCreateDC(string lpszDriverName, string lpszDeviceName, string lpszOutput, HandleRef /*DEVMODE*/ lpInitData);
- public static IntPtr CreateDC(String lpszDriverName, string lpszDeviceName, string lpszOutput, HandleRef /*DEVMODE*/ lpInitData)
+
+ public static IntPtr CreateDC(string lpszDriverName, string lpszDeviceName, string lpszOutput, HandleRef /*DEVMODE*/ lpInitData)
{
IntPtr hdc = System.Internal.HandleCollector.Add(IntCreateDC(lpszDriverName, lpszDeviceName, lpszOutput, lpInitData), IntSafeNativeMethods.CommonHandles.HDC);
DbgUtil.AssertWin32(hdc != IntPtr.Zero, "CreateDC([driverName={0}], [deviceName={1}], [fileName={2}], [devMode={3}]) failed.", lpszDriverName, lpszDeviceName, lpszOutput, lpInitData.Handle);
return hdc;
}
- [DllImport(ExternDll.Gdi32, SetLastError = true, EntryPoint = "CreateIC", CharSet = System.Runtime.InteropServices.CharSet.Auto)]
+ [DllImport(ExternDll.Gdi32, SetLastError = true, EntryPoint = "CreateIC", CharSet = CharSet.Auto)]
public static extern IntPtr IntCreateIC(string lpszDriverName, string lpszDeviceName, string lpszOutput, HandleRef /*DEVMODE*/ lpInitData);
+
public static IntPtr CreateIC(string lpszDriverName, string lpszDeviceName, string lpszOutput, HandleRef /*DEVMODE*/ lpInitData)
{
IntPtr hdc = System.Internal.HandleCollector.Add(IntCreateIC(lpszDriverName, lpszDeviceName, lpszOutput, lpInitData), IntSafeNativeMethods.CommonHandles.HDC);
@@ -73,6 +80,7 @@ namespace System.Drawing.Internal
/// </summary>
[DllImport(ExternDll.Gdi32, SetLastError = true, ExactSpelling = true, EntryPoint = "CreateCompatibleDC", CharSet = CharSet.Auto)]
public static extern IntPtr IntCreateCompatibleDC(HandleRef hDC);
+
public static IntPtr CreateCompatibleDC(HandleRef hDC)
{
IntPtr compatibleDc = System.Internal.HandleCollector.Add(IntCreateCompatibleDC(hDC), IntSafeNativeMethods.CommonHandles.GDI);
@@ -81,8 +89,9 @@ namespace System.Drawing.Internal
}
- [DllImport(ExternDll.Gdi32, SetLastError = true, ExactSpelling = true, EntryPoint = "SaveDC", CharSet = System.Runtime.InteropServices.CharSet.Auto)]
+ [DllImport(ExternDll.Gdi32, SetLastError = true, ExactSpelling = true, EntryPoint = "SaveDC", CharSet = CharSet.Auto)]
public static extern int IntSaveDC(HandleRef hDC);
+
public static int SaveDC(HandleRef hDC)
{
int state = IntSaveDC(hDC);
@@ -90,8 +99,9 @@ namespace System.Drawing.Internal
return state;
}
- [DllImport(ExternDll.Gdi32, SetLastError = true, ExactSpelling = true, EntryPoint = "RestoreDC", CharSet = System.Runtime.InteropServices.CharSet.Auto)]
+ [DllImport(ExternDll.Gdi32, SetLastError = true, ExactSpelling = true, EntryPoint = "RestoreDC", CharSet = CharSet.Auto)]
public static extern bool IntRestoreDC(HandleRef hDC, int nSavedDC);
+
public static bool RestoreDC(HandleRef hDC, int nSavedDC)
{
bool retVal = IntRestoreDC(hDC, nSavedDC);
@@ -105,11 +115,9 @@ namespace System.Drawing.Internal
[DllImport(ExternDll.User32, SetLastError = true, ExactSpelling = true)]
public static extern IntPtr WindowFromDC(HandleRef hDC);
- [DllImport(ExternDll.Gdi32, SetLastError = true, ExactSpelling = true, CharSet = CharSet.Auto)]
- public static extern int GetDeviceCaps(HandleRef hDC, int nIndex);
-
- [DllImport(ExternDll.Gdi32, SetLastError = true, ExactSpelling = true, EntryPoint = "OffsetViewportOrgEx", CharSet = System.Runtime.InteropServices.CharSet.Auto)]
+ [DllImport(ExternDll.Gdi32, SetLastError = true, ExactSpelling = true, EntryPoint = "OffsetViewportOrgEx", CharSet = CharSet.Auto)]
public static extern bool IntOffsetViewportOrgEx(HandleRef hDC, int nXOffset, int nYOffset, [In, Out] IntNativeMethods.POINT point);
+
public static bool OffsetViewportOrgEx(HandleRef hDC, int nXOffset, int nYOffset, [In, Out] IntNativeMethods.POINT point)
{
bool retVal = IntOffsetViewportOrgEx(hDC, nXOffset, nYOffset, point);
@@ -117,28 +125,10 @@ namespace System.Drawing.Internal
return retVal;
}
- [DllImport(ExternDll.Gdi32, SetLastError = true, ExactSpelling = true, EntryPoint = "SetGraphicsMode", CharSet = System.Runtime.InteropServices.CharSet.Auto)]
- public static extern int IntSetGraphicsMode(HandleRef hDC, int iMode);
- public static int SetGraphicsMode(HandleRef hDC, int iMode)
- {
- iMode = IntSetGraphicsMode(hDC, iMode);
- DbgUtil.AssertWin32(iMode != 0, "SetGraphicsMode([hdc=0x{0:X8}], [GM_ADVANCED]) failed.", hDC.Handle);
- return iMode;
- }
-
- [DllImport(ExternDll.Gdi32, SetLastError = true, ExactSpelling = true, CharSet = System.Runtime.InteropServices.CharSet.Auto)]
- public static extern int GetGraphicsMode(HandleRef hDC);
-
- [DllImport(ExternDll.Gdi32, SetLastError = true, ExactSpelling = true)]
- public static extern int GetROP2(HandleRef hdc);
-
- [DllImport(ExternDll.Gdi32, SetLastError = true, ExactSpelling = true, CharSet = System.Runtime.InteropServices.CharSet.Auto)]
- public static extern int SetROP2(HandleRef hDC, int nDrawMode);
-
-
// Region.
- [DllImport(ExternDll.Gdi32, SetLastError = true, ExactSpelling = true, EntryPoint = "CombineRgn", CharSet = System.Runtime.InteropServices.CharSet.Auto)]
+ [DllImport(ExternDll.Gdi32, SetLastError = true, ExactSpelling = true, EntryPoint = "CombineRgn", CharSet = CharSet.Auto)]
public static extern IntNativeMethods.RegionFlags IntCombineRgn(HandleRef hRgnDest, HandleRef hRgnSrc1, HandleRef hRgnSrc2, RegionCombineMode combineMode);
+
public static IntNativeMethods.RegionFlags CombineRgn(HandleRef hRgnDest, HandleRef hRgnSrc1, HandleRef hRgnSrc2, RegionCombineMode combineMode)
{
Debug.Assert(hRgnDest.Wrapper != null && hRgnDest.Handle != IntPtr.Zero, "Destination region is invalid");
@@ -154,8 +144,9 @@ namespace System.Drawing.Internal
return IntCombineRgn(hRgnDest, hRgnSrc1, hRgnSrc2, combineMode);
}
- [DllImport(ExternDll.Gdi32, SetLastError = true, ExactSpelling = true, EntryPoint = "GetClipRgn", CharSet = System.Runtime.InteropServices.CharSet.Auto)]
+ [DllImport(ExternDll.Gdi32, SetLastError = true, ExactSpelling = true, EntryPoint = "GetClipRgn", CharSet = CharSet.Auto)]
public static extern int IntGetClipRgn(HandleRef hDC, HandleRef hRgn);
+
public static int GetClipRgn(HandleRef hDC, HandleRef hRgn)
{
int retVal = IntGetClipRgn(hDC, hRgn);
@@ -163,8 +154,9 @@ namespace System.Drawing.Internal
return retVal;
}
- [DllImport(ExternDll.Gdi32, SetLastError = true, ExactSpelling = true, EntryPoint = "SelectClipRgn", CharSet = System.Runtime.InteropServices.CharSet.Auto)]
+ [DllImport(ExternDll.Gdi32, SetLastError = true, ExactSpelling = true, EntryPoint = "SelectClipRgn", CharSet = CharSet.Auto)]
public static extern IntNativeMethods.RegionFlags IntSelectClipRgn(HandleRef hDC, HandleRef hRgn);
+
public static IntNativeMethods.RegionFlags SelectClipRgn(HandleRef hDC, HandleRef hRgn)
{
IntNativeMethods.RegionFlags result = IntSelectClipRgn(hDC, hRgn);
@@ -172,8 +164,9 @@ namespace System.Drawing.Internal
return result;
}
- [DllImport(ExternDll.Gdi32, SetLastError = true, ExactSpelling = true, EntryPoint = "GetRgnBox", CharSet = System.Runtime.InteropServices.CharSet.Auto)]
+ [DllImport(ExternDll.Gdi32, SetLastError = true, ExactSpelling = true, EntryPoint = "GetRgnBox", CharSet = CharSet.Auto)]
public static extern IntNativeMethods.RegionFlags IntGetRgnBox(HandleRef hRgn, [In, Out] ref IntNativeMethods.RECT clipRect);
+
public static IntNativeMethods.RegionFlags GetRgnBox(HandleRef hRgn, [In, Out] ref IntNativeMethods.RECT clipRect)
{
IntNativeMethods.RegionFlags result = IntGetRgnBox(hRgn, ref clipRect);
@@ -183,20 +176,15 @@ namespace System.Drawing.Internal
// Font.
- [DllImport(ExternDll.Gdi32, SetLastError = true, EntryPoint = "CreateFontIndirect", CharSet = System.Runtime.InteropServices.CharSet.Auto)]
+ [DllImport(ExternDll.Gdi32, SetLastError = true, EntryPoint = "CreateFontIndirect", CharSet = CharSet.Auto)]
#pragma warning disable CS0618 // Legacy code: We don't care about using obsolete API's.
public static extern IntPtr IntCreateFontIndirect([In, Out, MarshalAs(UnmanagedType.AsAny)] object lf); // need object here since LOGFONT is not public.
#pragma warning restore CS0618
- public static IntPtr CreateFontIndirect(/*IntNativeMethods.LOGFONT*/ object lf)
- {
- IntPtr hFont = System.Internal.HandleCollector.Add(IntCreateFontIndirect(lf), IntSafeNativeMethods.CommonHandles.GDI);
- DbgUtil.AssertWin32(hFont != IntPtr.Zero, "CreateFontIndirect(logFont) failed.");
- return hFont;
- }
// Common.
- [DllImport(ExternDll.Gdi32, SetLastError = true, ExactSpelling = true, EntryPoint = "DeleteObject", CharSet = System.Runtime.InteropServices.CharSet.Auto)]
+ [DllImport(ExternDll.Gdi32, SetLastError = true, ExactSpelling = true, EntryPoint = "DeleteObject", CharSet = CharSet.Auto)]
public static extern bool IntDeleteObject(HandleRef hObject);
+
public static bool DeleteObject(HandleRef hObject)
{
System.Internal.HandleCollector.Remove((IntPtr)hObject, IntSafeNativeMethods.CommonHandles.GDI);
@@ -205,35 +193,9 @@ namespace System.Drawing.Internal
return retVal;
}
- [DllImport(ExternDll.Gdi32, SetLastError = true, EntryPoint = "GetObject", ExactSpelling = false, CharSet = System.Runtime.InteropServices.CharSet.Auto)]
- public static extern int IntGetObject(HandleRef hBrush, int nSize, [In, Out] IntNativeMethods.LOGBRUSH lb);
- public static int GetObject(HandleRef hBrush, IntNativeMethods.LOGBRUSH lb)
- {
- int retVal = IntGetObject(hBrush, System.Runtime.InteropServices.Marshal.SizeOf(typeof(IntNativeMethods.LOGBRUSH)), lb);
- DbgUtil.AssertWin32(retVal != 0, "GetObject(hObj=[0x{0:X8}], [LOGBRUSH]) failed.", hBrush.Handle);
- return retVal;
- }
-
- [DllImport(ExternDll.Gdi32, SetLastError = true, EntryPoint = "GetObject", ExactSpelling = false, CharSet = System.Runtime.InteropServices.CharSet.Auto)]
- public static extern int IntGetObject(HandleRef hFont, int nSize, [In, Out] IntNativeMethods.LOGFONT lf);
- public static int GetObject(HandleRef hFont, IntNativeMethods.LOGFONT lp)
- {
- int retVal = IntGetObject(hFont, System.Runtime.InteropServices.Marshal.SizeOf(typeof(IntNativeMethods.LOGFONT)), lp);
- DbgUtil.AssertWin32(retVal != 0, "GetObject(hObj=[0x{0:X8}], [LOGFONT]) failed.", hFont.Handle);
- return retVal;
- }
-
- [DllImport(ExternDll.Gdi32, SetLastError = true, ExactSpelling = true, EntryPoint = "SelectObject", CharSet = CharSet.Auto)]
- public static extern IntPtr IntSelectObject(HandleRef hdc, HandleRef obj);
- public static IntPtr SelectObject(HandleRef hdc, HandleRef obj)
- {
- IntPtr oldObj = IntSelectObject(hdc, obj);
- DbgUtil.AssertWin32(oldObj != IntPtr.Zero, "SelectObject(hdc=hObj=[0x{0:X8}], hObj=[0x{1:X8}]) failed.", hdc.Handle, obj.Handle);
- return oldObj;
- }
-
- [DllImport(ExternDll.Gdi32, SetLastError = true, ExactSpelling = true, EntryPoint = "GetCurrentObject", CharSet = System.Runtime.InteropServices.CharSet.Auto)]
+ [DllImport(ExternDll.Gdi32, SetLastError = true, ExactSpelling = true, EntryPoint = "GetCurrentObject", CharSet = CharSet.Auto)]
public static extern IntPtr IntGetCurrentObject(HandleRef hDC, int uObjectType);
+
public static IntPtr GetCurrentObject(HandleRef hDC, int uObjectType)
{
IntPtr hGdiObj = IntGetCurrentObject(hDC, uObjectType);
@@ -241,284 +203,5 @@ namespace System.Drawing.Internal
DbgUtil.AssertWin32(hGdiObj != IntPtr.Zero, "GetObject(hdc=[0x{0:X8}], type=[{1}]) failed.", hDC, uObjectType);
return hGdiObj;
}
-
- [DllImport(ExternDll.Gdi32, SetLastError = true, ExactSpelling = true, EntryPoint = "GetStockObject", CharSet = CharSet.Auto)]
- public static extern IntPtr IntGetStockObject(int nIndex);
- public static IntPtr GetStockObject(int nIndex)
- {
- IntPtr hGdiObj = IntGetStockObject(nIndex);
- DbgUtil.AssertWin32(hGdiObj != IntPtr.Zero, "GetStockObject({0}) failed.", nIndex);
- return hGdiObj;
- }
-
-
- // Drawing.
-
- [DllImport(ExternDll.Gdi32, SetLastError = true, ExactSpelling = true, CharSet = System.Runtime.InteropServices.CharSet.Auto)]
- public static extern int GetNearestColor(HandleRef hDC, int color);
-
- [DllImport(ExternDll.Gdi32, SetLastError = true, ExactSpelling = true, CharSet = System.Runtime.InteropServices.CharSet.Auto)]
- public static extern int /*COLORREF*/ SetTextColor(HandleRef hDC, int crColor);
-
- [DllImport(ExternDll.Gdi32, SetLastError = true, ExactSpelling = true, CharSet = System.Runtime.InteropServices.CharSet.Auto)]
- public static extern int GetTextAlign(HandleRef hdc);
-
- [DllImport(ExternDll.Gdi32, SetLastError = true, ExactSpelling = true, CharSet = System.Runtime.InteropServices.CharSet.Auto)]
- public static extern int /*COLORREF*/ GetTextColor(HandleRef hDC);
-
- [DllImport(ExternDll.Gdi32, SetLastError = true, ExactSpelling = true, CharSet = System.Runtime.InteropServices.CharSet.Auto)]
- public static extern int SetBkColor(HandleRef hDC, int clr);
-
- [DllImport(ExternDll.Gdi32, SetLastError = true, ExactSpelling = true, EntryPoint = "SetBkMode", CharSet = System.Runtime.InteropServices.CharSet.Auto)]
- public static extern int IntSetBkMode(HandleRef hDC, int nBkMode);
- public static int SetBkMode(HandleRef hDC, int nBkMode)
- {
- int oldMode = IntSetBkMode(hDC, nBkMode);
- DbgUtil.AssertWin32(oldMode != 0, "SetBkMode(hdc=[0x{0:X8}], Mode=[{1}]) failed.", hDC.Handle, nBkMode);
- return oldMode;
- }
-
- [DllImport(ExternDll.Gdi32, SetLastError = true, ExactSpelling = true, EntryPoint = "GetBkMode", CharSet = System.Runtime.InteropServices.CharSet.Auto)]
- public static extern int IntGetBkMode(HandleRef hDC);
- public static int GetBkMode(HandleRef hDC)
- {
- int mode = IntGetBkMode(hDC);
- DbgUtil.AssertWin32(mode != 0, "GetBkMode(hdc=[0x{0:X8}]) failed.", hDC.Handle);
- return mode;
- }
-
- [DllImport(ExternDll.Gdi32, SetLastError = true, ExactSpelling = true, CharSet = System.Runtime.InteropServices.CharSet.Auto)]
- public static extern int GetBkColor(HandleRef hDC);
-
-
- [DllImport(ExternDll.User32, SetLastError = true, ExactSpelling = true, CharSet = System.Runtime.InteropServices.CharSet.Unicode)]
- public static extern int DrawTextW(HandleRef hDC, string lpszString, int nCount, ref IntNativeMethods.RECT lpRect, int nFormat);
-
- public static int DrawText(HandleRef hDC, string text, ref IntNativeMethods.RECT lpRect, int nFormat)
- {
- int retVal = DrawTextW(hDC, text, text.Length, ref lpRect, nFormat);
-
- DbgUtil.AssertWin32(retVal != 0, "DrawText(hdc=[0x{0:X8}], text=[{1}], rect=[{2}], flags=[{3}] failed.", hDC.Handle, text, lpRect, nFormat);
- return retVal;
- }
-
- [DllImport(ExternDll.User32, SetLastError = true, CharSet = System.Runtime.InteropServices.CharSet.Unicode)]
- public static extern int DrawTextExW(HandleRef hDC, string lpszString, int nCount, ref IntNativeMethods.RECT lpRect, int nFormat, [In, Out] IntNativeMethods.DRAWTEXTPARAMS lpDTParams);
-
- public static int DrawTextEx(HandleRef hDC, string text, ref IntNativeMethods.RECT lpRect, int nFormat, [In, Out] IntNativeMethods.DRAWTEXTPARAMS lpDTParams)
- {
- int retVal = DrawTextExW(hDC, text, text.Length, ref lpRect, nFormat, lpDTParams);
-
- DbgUtil.AssertWin32(retVal != 0, "DrawTextEx(hdc=[0x{0:X8}], text=[{1}], rect=[{2}], flags=[{3}] failed.", hDC.Handle, text, lpRect, nFormat);
- return retVal;
- }
-
- [DllImport(ExternDll.Gdi32, SetLastError = true, ExactSpelling = true, CharSet = System.Runtime.InteropServices.CharSet.Unicode)]
- public static extern int GetTextExtentPoint32W(HandleRef hDC, string text, int len, [In, Out] IntNativeMethods.SIZE size);
-
- public static int GetTextExtentPoint32(HandleRef hDC, string text, [In, Out] IntNativeMethods.SIZE size)
- {
- int byteCount = text.Length;
- int retVal = GetTextExtentPoint32W(hDC, text, text.Length, size);
-
- DbgUtil.AssertWin32(retVal != 0, "GetTextExtentPoint32(hdc=[0x{0:X8}], text=[{1}], size=[{2}] failed.", hDC.Handle, text, size);
- return retVal;
- }
-
- // WARNING: This method is currently used just for drawing the text background (ComponentEditorForm.cs) and not for rendering text.
- // Prefer using DrawText over this method if possible, it handles Win9x issues properly. Ideally, we should remove this method
- // but to avoid issues at this point I'm leaving it here.
- [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Security", "CA2101:SpecifyMarshalingForPInvokeStringArguments")]
- [DllImport(ExternDll.Gdi32, SetLastError = true, ExactSpelling = false, CharSet = CharSet.Auto)]
- internal static extern bool ExtTextOut(HandleRef hdc, int x, int y, int options, ref IntNativeMethods.RECT rect, string str, int length, int[] spacing);
-
- [DllImport(ExternDll.Gdi32, SetLastError = true, ExactSpelling = true, EntryPoint = "LineTo", CharSet = CharSet.Auto)]
- public static extern bool IntLineTo(HandleRef hdc, int x, int y);
- public static bool LineTo(HandleRef hdc, int x, int y)
- {
- bool retVal = IntLineTo(hdc, x, y);
- DbgUtil.AssertWin32(retVal, "LineTo(hdc=[0x{0:X8}], x=[{1}], y=[{2}] failed.", hdc.Handle, x, y);
- return retVal;
- }
-
- [DllImport(ExternDll.Gdi32, SetLastError = true, ExactSpelling = true, EntryPoint = "MoveToEx", CharSet = CharSet.Auto)]
- public static extern bool IntMoveToEx(HandleRef hdc, int x, int y, IntNativeMethods.POINT pt);
- public static bool MoveToEx(HandleRef hdc, int x, int y, IntNativeMethods.POINT pt)
- {
- bool retVal = IntMoveToEx(hdc, x, y, pt);
- DbgUtil.AssertWin32(retVal, "MoveToEx(hdc=[0x{0:X8}], x=[{1}], y=[{2}], pt=[{3}] failed.", hdc.Handle, x, y, pt);
- return retVal;
- }
-
- [DllImport(ExternDll.Gdi32, SetLastError = true, ExactSpelling = true, EntryPoint = "Rectangle", CharSet = CharSet.Auto)]
- public static extern bool IntRectangle(HandleRef hdc, int left, int top, int right, int bottom);
- public static bool Rectangle(HandleRef hdc, int left, int top, int right, int bottom)
- {
- bool retVal = IntRectangle(hdc, left, top, right, bottom);
- DbgUtil.AssertWin32(retVal, "Rectangle(hdc=[0x{0:X8}], left=[{1}], top=[{2}], right=[{3}], bottom=[{4}] failed.", hdc.Handle, left, top, right, bottom);
- return retVal;
- }
-
- [DllImport(ExternDll.User32, SetLastError = true, ExactSpelling = true, EntryPoint = "FillRect", CharSet = System.Runtime.InteropServices.CharSet.Auto)]
- public static extern bool IntFillRect(HandleRef hdc, [In] ref IntNativeMethods.RECT rect, HandleRef hbrush);
- public static bool FillRect(HandleRef hDC, [In] ref IntNativeMethods.RECT rect, HandleRef hbrush)
- {
- bool retVal = IntFillRect(hDC, ref rect, hbrush);
- DbgUtil.AssertWin32(retVal, "FillRect(hdc=[0x{0:X8}], rect=[{1}], hbrush=[{2}]", hDC.Handle, rect, hbrush.Handle);
- return retVal;
- }
-
- [DllImport(ExternDll.Gdi32, SetLastError = true, ExactSpelling = true, EntryPoint = "SetMapMode", CharSet = System.Runtime.InteropServices.CharSet.Auto)]
- public static extern int IntSetMapMode(HandleRef hDC, int nMapMode);
- public static int SetMapMode(HandleRef hDC, int nMapMode)
- {
- int oldMapMode = IntSetMapMode(hDC, nMapMode);
- DbgUtil.AssertWin32(oldMapMode != 0, "SetMapMode(hdc=[0x{0:X8}], MapMode=[{1}]", hDC.Handle, nMapMode);
- return oldMapMode;
- }
-
- [DllImport(ExternDll.Gdi32, SetLastError = true, ExactSpelling = true, EntryPoint = "GetMapMode", CharSet = System.Runtime.InteropServices.CharSet.Auto)]
- public static extern int IntGetMapMode(HandleRef hDC);
- public static int GetMapMode(HandleRef hDC)
- {
- int mapMode = IntGetMapMode(hDC);
- DbgUtil.AssertWin32(mapMode != 0, "GetMapMode(hdc=[0x{0:X8}]", hDC.Handle);
- return mapMode;
- }
-
- [DllImport(ExternDll.Gdi32, SetLastError = true, ExactSpelling = true, EntryPoint = "GetViewportExtEx")]
- public static extern bool IntGetViewportExtEx(HandleRef hdc, [In, Out] IntNativeMethods.SIZE lpSize);
- public static bool GetViewportExtEx(HandleRef hdc, [In, Out] IntNativeMethods.SIZE lpSize)
- {
- bool retVal = IntGetViewportExtEx(hdc, lpSize);
- DbgUtil.AssertWin32(retVal, "GetViewportExtEx([hdc=0x{0:X8}], [out size]) failed.", hdc.Handle);
- return retVal;
- }
-
- [DllImport(ExternDll.Gdi32, SetLastError = true, ExactSpelling = true, EntryPoint = "GetViewportOrgEx")]
- public static extern bool IntGetViewportOrgEx(HandleRef hdc, [In, Out] IntNativeMethods.POINT lpPoint);
- public static bool GetViewportOrgEx(HandleRef hdc, [In, Out] IntNativeMethods.POINT lpPoint)
- {
- bool retVal = IntGetViewportOrgEx(hdc, lpPoint);
- DbgUtil.AssertWin32(retVal, "GetViewportOrgEx([hdc=0x{0:X8}], [out point]) failed.", hdc.Handle);
- return retVal;
- }
-
- [DllImport(ExternDll.Gdi32, SetLastError = true, ExactSpelling = true, EntryPoint = "SetViewportExtEx", CharSet = System.Runtime.InteropServices.CharSet.Auto)]
- public static extern bool IntSetViewportExtEx(HandleRef hDC, int x, int y, [In, Out] IntNativeMethods.SIZE size);
- public static bool SetViewportExtEx(HandleRef hDC, int x, int y, [In, Out] IntNativeMethods.SIZE size)
- {
- bool retVal = IntSetViewportExtEx(hDC, x, y, size);
- DbgUtil.AssertWin32(retVal, "SetViewportExtEx([hdc=0x{0:X8}], x=[{1}], y=[{2}], [out size]) failed.", hDC.Handle, x, y);
- return retVal;
- }
- [DllImport(ExternDll.Gdi32, SetLastError = true, ExactSpelling = true, EntryPoint = "SetViewportOrgEx", CharSet = System.Runtime.InteropServices.CharSet.Auto)]
- public static extern bool IntSetViewportOrgEx(HandleRef hDC, int x, int y, [In, Out] IntNativeMethods.POINT point);
- public static bool SetViewportOrgEx(HandleRef hDC, int x, int y, [In, Out] IntNativeMethods.POINT point)
- {
- bool retVal = IntSetViewportOrgEx(hDC, x, y, point);
- DbgUtil.AssertWin32(retVal, "SetViewportOrgEx([hdc=0x{0:X8}], x=[{1}], y=[{2}], [out point]) failed.", hDC.Handle, x, y);
- return retVal;
- }
-
-
-
- [DllImport(ExternDll.Gdi32, SetLastError = true, ExactSpelling = true, CharSet = System.Runtime.InteropServices.CharSet.Unicode)]
- public static extern int GetTextMetricsW(HandleRef hDC, [In, Out] ref IntNativeMethods.TEXTMETRIC lptm);
-
- public static int GetTextMetrics(HandleRef hDC, ref IntNativeMethods.TEXTMETRIC lptm)
- {
- int retVal = GetTextMetricsW(hDC, ref lptm);
-
- DbgUtil.AssertWin32(retVal != 0, "GetTextMetrics(hdc=[0x{0:X8}], [out TEXTMETRIC] failed.", hDC.Handle);
- return retVal;
- }
-
- [DllImport(ExternDll.Gdi32, SetLastError = true, ExactSpelling = true, EntryPoint = "BeginPath", CharSet = System.Runtime.InteropServices.CharSet.Auto)]
- public static extern bool IntBeginPath(HandleRef hDC);
- public static bool BeginPath(HandleRef hDC)
- {
- bool retVal = IntBeginPath(hDC);
- DbgUtil.AssertWin32(retVal, "BeginPath(hdc=[0x{0:X8}]failed.", hDC.Handle);
- return retVal;
- }
-
- [DllImport(ExternDll.Gdi32, SetLastError = true, ExactSpelling = true, EntryPoint = "EndPath", CharSet = System.Runtime.InteropServices.CharSet.Auto)]
- public static extern bool IntEndPath(HandleRef hDC);
- public static bool EndPath(HandleRef hDC)
- {
- bool retVal = IntEndPath(hDC);
- DbgUtil.AssertWin32(retVal, "EndPath(hdc=[0x{0:X8}]failed.", hDC.Handle);
- return retVal;
- }
-
- [DllImport(ExternDll.Gdi32, SetLastError = true, ExactSpelling = true, EntryPoint = "StrokePath", CharSet = System.Runtime.InteropServices.CharSet.Auto)]
- public static extern bool IntStrokePath(HandleRef hDC);
- public static bool StrokePath(HandleRef hDC)
- {
- bool retVal = IntStrokePath(hDC);
- DbgUtil.AssertWin32(retVal, "StrokePath(hdc=[0x{0:X8}]failed.", hDC.Handle);
- return retVal;
- }
-
- [DllImport(ExternDll.Gdi32, SetLastError = true, ExactSpelling = true, EntryPoint = "AngleArc", CharSet = System.Runtime.InteropServices.CharSet.Auto)]
- public static extern bool IntAngleArc(HandleRef hDC, int x, int y, int radius, float startAngle, float endAngle);
- public static bool AngleArc(HandleRef hDC, int x, int y, int radius, float startAngle, float endAngle)
- {
- bool retVal = IntAngleArc(hDC, x, y, radius, startAngle, endAngle);
- DbgUtil.AssertWin32(retVal, "AngleArc(hdc=[0x{0:X8}], ...) failed.", hDC.Handle);
- return retVal;
- }
-
- [DllImport(ExternDll.Gdi32, SetLastError = true, ExactSpelling = true, EntryPoint = "Arc", CharSet = System.Runtime.InteropServices.CharSet.Auto)]
- public static extern bool IntArc(
- HandleRef hDC,
- int nLeftRect, // x-coord of rectangle's upper-left corner
- int nTopRect, // y-coord of rectangle's upper-left corner
- int nRightRect, // x-coord of rectangle's lower-right corner
- int nBottomRect, // y-coord of rectangle's lower-right corner
- int nXStartArc, // x-coord of first radial ending point
- int nYStartArc, // y-coord of first radial ending point
- int nXEndArc, // x-coord of second radial ending point
- int nYEndArc // y-coord of second radial ending point
- );
- public static bool Arc(
- HandleRef hDC,
- int nLeftRect, // x-coord of rectangle's upper-left corner
- int nTopRect, // y-coord of rectangle's upper-left corner
- int nRightRect, // x-coord of rectangle's lower-right corner
- int nBottomRect, // y-coord of rectangle's lower-right corner
- int nXStartArc, // x-coord of first radial ending point
- int nYStartArc, // y-coord of first radial ending point
- int nXEndArc, // x-coord of second radial ending point
- int nYEndArc // y-coord of second radial ending point
- )
- {
- bool retVal = IntArc(hDC, nLeftRect, nTopRect, nRightRect, nBottomRect, nXStartArc, nYStartArc, nXEndArc, nYEndArc);
- DbgUtil.AssertWin32(retVal, "Arc(hdc=[0x{0:X8}], ...) failed.", hDC.Handle);
- return retVal;
- }
-
- // Misc.
-
- [DllImport(ExternDll.Gdi32, SetLastError = true, ExactSpelling = true, CharSet = System.Runtime.InteropServices.CharSet.Auto)]
- public static extern int SetTextAlign(HandleRef hDC, int nMode);
-
- [DllImport(ExternDll.Gdi32, SetLastError = true, ExactSpelling = true, EntryPoint = "Ellipse", CharSet = System.Runtime.InteropServices.CharSet.Auto)]
- public static extern bool IntEllipse(HandleRef hDc, int x1, int y1, int x2, int y2);
- public static bool Ellipse(HandleRef hDc, int x1, int y1, int x2, int y2)
- {
- bool retVal = IntEllipse(hDc, x1, y1, x2, y2);
- DbgUtil.AssertWin32(retVal, "Ellipse(hdc=[0x{0:X8}], x1=[{1}], y1=[{2}], x2=[{3}], y2=[{4}]) failed.", hDc.Handle, x1, y1, x2, y2);
- return retVal;
- }
-
- // From MSDN: Using the MultiByteToWideChar/WideCharToMultiByte function incorrectly can compromise the security of your application.
- // Calling the WideCharToMultiByte function can easily cause a buffer overrun because the size of the In buffer equals the number
- // of WCHARs in the string, while the size of the Out buffer equals the number of bytes. To avoid a buffer overrun, be sure to specify
- // a buffer size appropriate for the data type the buffer receives. For more information, see Security Considerations: International Features.
- // Always call these functions passing a null destination buffer to get its size and the create the buffer with the exact size.
- [DllImport(ExternDll.Kernel32, ExactSpelling = true, CharSet = CharSet.Unicode)]
- public static extern int WideCharToMultiByte(int codePage, int flags, [MarshalAs(UnmanagedType.LPWStr)]string wideStr, int chars, [In, Out]byte[] pOutBytes, int bufferBytes, IntPtr defaultChar, IntPtr pDefaultUsed);
}
}
diff --git a/src/System.Drawing.Common/src/misc/GDI/WindowsGraphics.cs b/src/System.Drawing.Common/src/misc/GDI/WindowsGraphics.cs
index 65abae4bad..860e9a692d 100644
--- a/src/System.Drawing.Common/src/misc/GDI/WindowsGraphics.cs
+++ b/src/System.Drawing.Common/src/misc/GDI/WindowsGraphics.cs
@@ -38,67 +38,16 @@ namespace System.Drawing.Internal
_dc.SaveHdc();
}
- /// <summary>
- /// Creates a WindowsGraphics from a memory DeviceContext object compatible with the primary screen device.
- /// This object is suitable for performing text measuring but not for drawing into it because it does not have
- /// a backup bitmap.
- /// </summary>
- public static WindowsGraphics CreateMeasurementWindowsGraphics()
- {
- DeviceContext dc = DeviceContext.FromCompatibleDC(IntPtr.Zero);
- WindowsGraphics wg = new WindowsGraphics(dc);
- wg._disposeDc = true; // we create it, we dispose it.
-
- return wg;
- }
-
- public static WindowsGraphics FromHwnd(IntPtr hWnd)
- {
- DeviceContext dc = DeviceContext.FromHwnd(hWnd);
- WindowsGraphics wg = new WindowsGraphics(dc);
- wg._disposeDc = true; // we create it, we dispose it.
-
- return wg;
- }
-
public static WindowsGraphics FromHdc(IntPtr hDc)
{
Debug.Assert(hDc != IntPtr.Zero, "null hDc");
-
DeviceContext dc = DeviceContext.FromHdc(hDc);
- WindowsGraphics wg = new WindowsGraphics(dc);
- wg._disposeDc = true; // we create it, we dispose it.
-
- return wg;
- }
- /// <summary>
- /// Creates a WindowsGraphics object from a Graphics object. Clipping and coordinate transforms
- /// are preserved.
- ///
- /// Notes:
- /// - The passed Graphics object cannot be used until the WindowsGraphics is disposed
- /// since it borrows the hdc from the Graphics object locking it.
- /// - Changes to the hdc using the WindowsGraphics object are not preserved into the Graphics object;
- /// the hdc is returned to the Graphics object intact.
- ///
- /// Some background about how Graphics uses the internal hdc when created from an existing one
- /// (mail from GillesK from GDI+ team):
- /// User has an HDC with a particular state:
- /// Graphics object gets created based on that HDC. We query the HDC for its state and apply it to the Graphics.
- /// At this stage, we do a SaveHDC and clear everything out of it.
- /// User calls GetHdc. We restore the HDC to the state it was in and give it to the user.
- /// User calls ReleaseHdc, we save the current state of the HDC and clear everything
- /// (so that the graphics state gets applied next time we use it).
- /// Next time the user calls GetHdc we give him back the state after the second ReleaseHdc.
- /// (But the state changes between the GetHdc and ReleaseHdc are not applied to the Graphics).
- /// Please note that this only applies the HDC created graphics, for Bitmap derived graphics, GetHdc creates a new DIBSection and
- /// things get a lot more complicated.
- /// </summary>
- public static WindowsGraphics FromGraphics(Graphics g)
- {
- ApplyGraphicsProperties properties = ApplyGraphicsProperties.All;
- return WindowsGraphics.FromGraphics(g, properties);
+ // we create it, we dispose it.
+ return new WindowsGraphics(dc)
+ {
+ _disposeDc = true
+ };
}
public static WindowsGraphics FromGraphics(Graphics g, ApplyGraphicsProperties properties)
@@ -113,9 +62,7 @@ namespace System.Drawing.Internal
if ((properties & ApplyGraphicsProperties.TranslateTransform) != 0 || (properties & ApplyGraphicsProperties.Clipping) != 0)
{
- object[] data = g.GetContextInfo() as object[];
-
- if (data != null && data.Length == 2)
+ if (g.GetContextInfo() is object[] data && data.Length == 2)
{
clipRgn = data[0] as Region;
worldTransf = data[1] as Matrix;
@@ -127,6 +74,7 @@ namespace System.Drawing.Internal
{
elements = worldTransf.Elements;
}
+
worldTransf.Dispose();
}
@@ -143,11 +91,12 @@ namespace System.Drawing.Internal
wr = WindowsRegion.FromRegion(clipRgn, g); // WindowsRegion will take ownership of the hRegion.
}
}
+
clipRgn.Dispose(); // Disposing the Region object doesn't destroy the hRegion.
}
}
- WindowsGraphics wg = WindowsGraphics.FromHdc(g.GetHdc()); // This locks the Graphics object.
+ WindowsGraphics wg = FromHdc(g.GetHdc()); // This locks the Graphics object.
wg._graphics = g;
// Apply transform and clip
@@ -171,19 +120,9 @@ namespace System.Drawing.Internal
return wg;
}
- ~WindowsGraphics()
- {
- Dispose(false);
- }
-
- public DeviceContext DeviceContext
- {
- get
- {
- return _dc;
- }
- }
+ ~WindowsGraphics() => Dispose(false);
+ public DeviceContext DeviceContext => _dc;
// Okay to suppress.
// "WindowsGraphics object does not own the Graphics object. For instance in a control’s Paint event we pass
@@ -217,12 +156,8 @@ namespace System.Drawing.Internal
_graphics = null;
}
}
- catch (Exception ex)
+ catch (Exception ex) when (!ClientUtils.IsSecurityOrCriticalException(ex))
{
- if (ClientUtils.IsSecurityOrCriticalException(ex))
- {
- throw; // rethrow the original exception.
- }
Debug.Fail("Exception thrown during disposing: \r\n" + ex.ToString());
}
finally
@@ -232,14 +167,8 @@ namespace System.Drawing.Internal
}
}
- public IntPtr GetHdc()
- {
- return _dc.Hdc;
- }
+ public IntPtr GetHdc() => _dc.Hdc;
- public void ReleaseHdc()
- {
- _dc.Dispose();
- }
+ public void ReleaseHdc() => _dc.Dispose();
}
}
diff --git a/src/System.Drawing.Common/src/misc/GDI/WindowsRegion.cs b/src/System.Drawing.Common/src/misc/GDI/WindowsRegion.cs
index 638c923d16..70fe1925ff 100644
--- a/src/System.Drawing.Common/src/misc/GDI/WindowsRegion.cs
+++ b/src/System.Drawing.Common/src/misc/GDI/WindowsRegion.cs
@@ -75,7 +75,7 @@ namespace System.Drawing.Internal
return new WindowsRegion();
}
- return WindowsRegion.FromHregion(region.GetHrgn(g), true);
+ return FromHregion(region.GetHrgn(g), true);
}
public object Clone()
@@ -104,10 +104,7 @@ namespace System.Drawing.Internal
_ownHandle = true;
}
- public void Dispose()
- {
- Dispose(true);
- }
+ public void Dispose() => Dispose(true);
public void Dispose(bool disposing)
{
@@ -129,29 +126,14 @@ namespace System.Drawing.Internal
}
}
- ~WindowsRegion()
- {
- Dispose(false);
- }
+ ~WindowsRegion() => Dispose(false);
/// <summary>
/// The native region handle.
/// </summary>
- public IntPtr HRegion
- {
- get
- {
- return _nativeHandle;
- }
- }
+ public IntPtr HRegion => _nativeHandle;
- public bool IsInfinite
- {
- get
- {
- return _nativeHandle == IntPtr.Zero;
- }
- }
+ public bool IsInfinite => _nativeHandle == IntPtr.Zero;
/// <summary>
/// A rectangle representing the window region set with the SetWindowRgn function.
@@ -160,10 +142,10 @@ namespace System.Drawing.Internal
{
if (IsInfinite)
{
- return new Rectangle(-Int32.MaxValue, -Int32.MaxValue, Int32.MaxValue, Int32.MaxValue);
+ return new Rectangle(-int.MaxValue, -int.MaxValue, int.MaxValue, int.MaxValue);
}
- IntNativeMethods.RECT rect = new IntNativeMethods.RECT();
+ var rect = new IntNativeMethods.RECT();
IntUnsafeNativeMethods.GetRgnBox(new HandleRef(this, _nativeHandle), ref rect);
return new Rectangle(new Point(rect.left, rect.top), rect.Size);
}
diff --git a/src/System.Drawing.Common/src/misc/HandleCollector.cs b/src/System.Drawing.Common/src/misc/HandleCollector.cs
index 1f3313d35b..08c054ba6b 100644
--- a/src/System.Drawing.Common/src/misc/HandleCollector.cs
+++ b/src/System.Drawing.Common/src/misc/HandleCollector.cs
@@ -2,11 +2,9 @@
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
-#if DEBUG_HANDLECOLLECTOR
- using System.Diagnostics;
-#endif
-
+using System.Diagnostics;
using System.Diagnostics.CodeAnalysis;
+
[module: SuppressMessage("Microsoft.Design", "CA1020:AvoidNamespacesWithFewTypes", Scope = "namespace", Target = "System.Internal")]
namespace System.Internal
@@ -15,7 +13,6 @@ namespace System.Internal
{
private static HandleType[] s_handleTypes;
private static int s_handleTypeCount;
- private static int s_suspendCount;
internal static event HandleChangeEventHandler HandleAdded;
@@ -34,51 +31,6 @@ namespace System.Internal
}
/// <summary>
- /// Suspends GC.Collect
- /// </summary>
- internal static void SuspendCollect()
- {
- lock (s_internalSyncObject)
- {
- s_suspendCount++;
- }
- }
-
- /// <summary>
- /// Resumes GC.Collect
- /// </summary>
- internal static void ResumeCollect()
- {
- bool performCollect = false;
- lock (s_internalSyncObject)
- {
- if (s_suspendCount > 0)
- {
- s_suspendCount--;
- }
-
- if (s_suspendCount == 0)
- {
- for (int i = 0; i < s_handleTypeCount; i++)
- {
- lock (s_handleTypes[i])
- {
- if (s_handleTypes[i].NeedCollection())
- {
- performCollect = true;
- }
- }
- }
- }
- }
-
- if (performCollect)
- {
- GC.Collect();
- }
- }
-
- /// <summary>
/// Registers a new type of handle with the handle collector.
/// </summary>
internal static int RegisterType(string typeName, int expense, int initialThreshold)
@@ -92,6 +44,7 @@ namespace System.Internal
{
Array.Copy(s_handleTypes, 0, newTypes, 0, s_handleTypeCount);
}
+
s_handleTypes = newTypes;
}
@@ -161,10 +114,7 @@ namespace System.Internal
}
lock (s_internalSyncObject)
{
- if (HandleCollector.HandleAdded != null)
- {
- HandleCollector.HandleAdded(name, handle, currentCount);
- }
+ HandleAdded?.Invoke(name, handle, currentCount);
}
if (!performCollect)
@@ -196,27 +146,11 @@ namespace System.Internal
}
}
-
- /// <summary>
- /// Retrieves the outstanding handle count for this handle type.
- /// </summary>
- internal int GetHandleCount()
- {
- lock (this)
- {
- return _handleCount;
- }
- }
-
/// <summary>
/// Determines if this handle type needs a garbage collection pass.
/// </summary>
internal bool NeedCollection()
{
- if (s_suspendCount > 0)
- {
- return false;
- }
if (_handleCount > _threshHold)
{
_threshHold = _handleCount + ((_handleCount * _deltaPercent) / 100);
@@ -261,17 +195,14 @@ namespace System.Internal
#endif
if (_handleCount < 0)
{
- System.Diagnostics.Debug.Fail("Handle collector underflow for type '" + name + "'");
+ Debug.Fail("Handle collector underflow for type '" + name + "'");
_handleCount = 0;
}
currentCount = _handleCount;
}
lock (s_internalSyncObject)
{
- if (HandleCollector.HandleRemoved != null)
- {
- HandleCollector.HandleRemoved(name, handle, currentCount);
- }
+ HandleRemoved?.Invoke(name, handle, currentCount);
}
return handle;
}
diff --git a/src/System.Drawing.Common/tests/BrushesTests.cs b/src/System.Drawing.Common/tests/BrushesTests.cs
index 458c30f517..f549d62ef2 100644
--- a/src/System.Drawing.Common/tests/BrushesTests.cs
+++ b/src/System.Drawing.Common/tests/BrushesTests.cs
@@ -155,16 +155,16 @@ namespace System.Drawing.Tests
yield return Brush(() => Brushes.YellowGreen, Color.YellowGreen);
}
- public static object[] Brush(Func<Brush> brushThunk, Color expectedColor) => new object[] { brushThunk, expectedColor };
+ public static object[] Brush(Func<Brush> getBrush, Color expectedColor) => new object[] { getBrush, expectedColor };
[ConditionalTheory(nameof(PlatformDetection) + "." + nameof(PlatformDetection.IsNotWindowsNanoServer))]
[MemberData(nameof(Brushes_TestData))]
- public void Brushes_Get_ReturnsExpected(Func<Brush> brushThunk, Color expectedColor)
+ public void Brushes_Get_ReturnsExpected(Func<Brush> getBrush, Color expectedColor)
{
- SolidBrush brush = Assert.IsType<SolidBrush>(brushThunk());
+ SolidBrush brush = Assert.IsType<SolidBrush>(getBrush());
Assert.Equal(expectedColor, brush.Color);
- Assert.Same(brush, brushThunk());
+ Assert.Same(brush, getBrush());
// Brushes are not immutable.
Color color = brush.Color;
diff --git a/src/System.Drawing.Common/tests/Drawing2D/AdjustableArrowCapTests.cs b/src/System.Drawing.Common/tests/Drawing2D/AdjustableArrowCapTests.cs
new file mode 100644
index 0000000000..a8066ade1f
--- /dev/null
+++ b/src/System.Drawing.Common/tests/Drawing2D/AdjustableArrowCapTests.cs
@@ -0,0 +1,140 @@
+// Licensed to the .NET Foundation under one or more agreements.
+// The .NET Foundation licenses this file to you under the MIT license.
+// See the LICENSE file in the project root for more information.
+
+using System.Collections.Generic;
+using Xunit;
+
+namespace System.Drawing.Drawing2D.Tests
+{
+ public class AdjustableArrowCapTests
+ {
+ public static IEnumerable<object[]> Ctor_Float_Float_TestData()
+ {
+ yield return new object[] { 1f, 1f };
+ yield return new object[] { 50f, 50f };
+ yield return new object[] { float.MaxValue, float.MaxValue };
+ // Nonsensical values -- but still permitted.
+ yield return new object[] { -1f, 1f };
+ yield return new object[] { float.PositiveInfinity, 1f };
+ yield return new object[] { float.NegativeInfinity, 1f };
+ yield return new object[] { float.NaN, 1f };
+ yield return new object[] { 0f, 1f };
+ yield return new object[] { 0f, 0f };
+ yield return new object[] { 1f, -1f };
+ }
+
+ [ConditionalTheory(nameof(PlatformDetection) + "." + nameof(PlatformDetection.IsNotWindowsNanoServer))]
+ [MemberData(nameof(Ctor_Float_Float_TestData))]
+ public void Ctor_Float_Float(float width, float height)
+ {
+ using (AdjustableArrowCap arrowCap = new AdjustableArrowCap(width, height))
+ {
+ Assert.Equal(width, arrowCap.Width);
+ Assert.Equal(height, arrowCap.Height);
+ Assert.Equal(true, arrowCap.Filled);
+ }
+ }
+
+ public static IEnumerable<object[]> Ctor_Float_Float_Bool_TestData()
+ {
+ foreach (object[] data in Ctor_Float_Float_TestData())
+ {
+ yield return new object[] { data[0], data[1], true };
+ yield return new object[] { data[0], data[1], false };
+ }
+ }
+
+ [ConditionalTheory(nameof(PlatformDetection) + "." + nameof(PlatformDetection.IsNotWindowsNanoServer))]
+ [MemberData(nameof(Ctor_Float_Float_Bool_TestData))]
+ public void Ctor_Float_Float_Bool(float width, float height, bool filled)
+ {
+ using (AdjustableArrowCap arrowCap = new AdjustableArrowCap(width, height, filled))
+ {
+ Assert.Equal(width, arrowCap.Width);
+ Assert.Equal(height, arrowCap.Height);
+ Assert.Equal(filled, arrowCap.Filled);
+ }
+ }
+
+ public static IEnumerable<object[]> Properties_TestData()
+ {
+ yield return new object[] { -1 };
+ yield return new object[] { 0 };
+ yield return new object[] { 10 };
+ yield return new object[] { 5000 };
+ yield return new object[] { float.MaxValue };
+ yield return new object[] { float.PositiveInfinity };
+ yield return new object[] { float.NegativeInfinity };
+ yield return new object[] { float.NaN };
+ }
+
+ [ConditionalTheory(nameof(PlatformDetection) + "." + nameof(PlatformDetection.IsNotWindowsNanoServer))]
+ [MemberData(nameof(Properties_TestData))]
+ public void Width_Set_GetReturnsExpected(float width)
+ {
+ using (AdjustableArrowCap arrowCap = new AdjustableArrowCap(1, 1))
+ {
+ arrowCap.Width = width;
+ Assert.Equal(width, arrowCap.Width);
+ }
+ }
+
+ [ConditionalTheory(nameof(PlatformDetection) + "." + nameof(PlatformDetection.IsNotWindowsNanoServer))]
+ [MemberData(nameof(Properties_TestData))]
+ public void Height_Set_GetReturnsExpected(float height)
+ {
+ using (AdjustableArrowCap arrowCap = new AdjustableArrowCap(1, 1))
+ {
+ arrowCap.Height = height;
+ Assert.Equal(height, arrowCap.Height);
+ }
+ }
+
+ [ConditionalTheory(nameof(PlatformDetection) + "." + nameof(PlatformDetection.IsNotWindowsNanoServer))]
+ [MemberData(nameof(Properties_TestData))]
+ public void MiddleInset_Set_GetReturnsExpected(float middleInset)
+ {
+ using (AdjustableArrowCap arrowCap = new AdjustableArrowCap(1, 1))
+ {
+ arrowCap.MiddleInset = middleInset;
+ Assert.Equal(middleInset, arrowCap.MiddleInset);
+ }
+ }
+
+ [ConditionalTheory(nameof(PlatformDetection) + "." + nameof(PlatformDetection.IsNotWindowsNanoServer))]
+ [InlineData(true)]
+ [InlineData(false)]
+ public void Filled_Set_GetReturnsExpected(bool filled)
+ {
+ using (AdjustableArrowCap arrowCap = new AdjustableArrowCap(1, 1))
+ {
+ arrowCap.Filled = filled;
+ Assert.Equal(filled, arrowCap.Filled);
+ }
+ }
+
+ [ConditionalFact(nameof(PlatformDetection) + "." + nameof(PlatformDetection.IsNotWindowsNanoServer))]
+ public void Clone_Success()
+ {
+ using (AdjustableArrowCap arrowCap = new AdjustableArrowCap(1, 1))
+ using (AdjustableArrowCap clone = Assert.IsType<AdjustableArrowCap>(arrowCap.Clone()))
+ {
+ Assert.NotSame(clone, arrowCap);
+ Assert.Equal(clone.Width, arrowCap.Width);
+ Assert.Equal(clone.Height, arrowCap.Height);
+ Assert.Equal(clone.MiddleInset, arrowCap.MiddleInset);
+ Assert.Equal(clone.Filled, arrowCap.Filled);
+ }
+ }
+
+ [ConditionalFact(nameof(PlatformDetection) + "." + nameof(PlatformDetection.IsNotWindowsNanoServer))]
+ public void BaseCap_ReturnsTriangle()
+ {
+ using (AdjustableArrowCap arrowCap = new AdjustableArrowCap(1, 1))
+ {
+ Assert.Equal(LineCap.Triangle, arrowCap.BaseCap);
+ }
+ }
+ }
+}
diff --git a/src/System.Drawing.Common/tests/Drawing2D/CustomLineCapTests.cs b/src/System.Drawing.Common/tests/Drawing2D/CustomLineCapTests.cs
new file mode 100644
index 0000000000..709a0dd897
--- /dev/null
+++ b/src/System.Drawing.Common/tests/Drawing2D/CustomLineCapTests.cs
@@ -0,0 +1,247 @@
+// Licensed to the .NET Foundation under one or more agreements.
+// The .NET Foundation licenses this file to you under the MIT license.
+// See the LICENSE file in the project root for more information.
+
+using System.Collections.Generic;
+using Xunit;
+
+namespace System.Drawing.Drawing2D.Tests
+{
+ public class CustomLineCapTests
+ {
+ public static IEnumerable<object[]> Ctor_Path_Path_LineCap_Float_TestData()
+ {
+ yield return new object[] { new GraphicsPath(), null, LineCap.Flat, 0f, LineCap.Flat };
+ yield return new object[] { new GraphicsPath(), null, LineCap.Square, 1f, LineCap.Square };
+ yield return new object[] { new GraphicsPath(), null, LineCap.Round, -1f, LineCap.Round };
+ yield return new object[] { new GraphicsPath(), null, LineCap.Triangle, float.MaxValue, LineCap.Triangle };
+ // All of these "anchor" values yield a "Flat" LineCap.
+ yield return new object[] { new GraphicsPath(), null, LineCap.NoAnchor, 0f, LineCap.Flat };
+ yield return new object[] { new GraphicsPath(), null, LineCap.SquareAnchor, 0f, LineCap.Flat };
+ yield return new object[] { new GraphicsPath(), null, LineCap.DiamondAnchor, 0f, LineCap.Flat };
+ yield return new object[] { new GraphicsPath(), null, LineCap.ArrowAnchor, 0f, LineCap.Flat };
+
+ // Boxy cap
+ GraphicsPath strokePath = new GraphicsPath();
+ strokePath.AddRectangle(new Rectangle(0, 0, 10, 10));
+ yield return new object[] { null, strokePath, LineCap.Square, 0f, LineCap.Square };
+
+ // Hook-shaped cap
+ strokePath = new GraphicsPath();
+ strokePath.AddLine(new Point(0, 0), new Point(0, 5));
+ strokePath.AddLine(new Point(0, 5), new Point(5, 1));
+ strokePath.AddLine(new Point(5, 1), new Point(3, 1));
+ yield return new object[] { null, strokePath, LineCap.Flat, 0f, LineCap.Flat };
+
+ // Fill path -- Must intercept the Y-axis.
+ GraphicsPath fillPath = new GraphicsPath();
+ fillPath.AddLine(new Point(-5, -10), new Point(0, 10));
+ fillPath.AddLine(new Point(0, 10), new Point(5, -10));
+ fillPath.AddLine(new Point(5, -10), new Point(-5, -10));
+ yield return new object[] { fillPath, null, LineCap.Flat, 0f, LineCap.Flat };
+ }
+
+ [ConditionalTheory(nameof(PlatformDetection) + "." + nameof(PlatformDetection.IsNotWindowsNanoServer))]
+ [MemberData(nameof(Ctor_Path_Path_LineCap_Float_TestData))]
+ public void Ctor_Path_Path_LineCap_Float(GraphicsPath fillPath, GraphicsPath strokePath, LineCap baseCap, float baseInset, LineCap expectedCap)
+ {
+ using (fillPath)
+ using (strokePath)
+ using (CustomLineCap customLineCap = new CustomLineCap(fillPath, strokePath, baseCap, baseInset))
+ {
+ Assert.Equal(expectedCap, customLineCap.BaseCap);
+ Assert.Equal(baseInset, customLineCap.BaseInset);
+ Assert.Equal(LineJoin.Miter, customLineCap.StrokeJoin);
+ Assert.Equal(1f, customLineCap.WidthScale);
+ }
+ }
+
+ [ConditionalTheory(nameof(PlatformDetection) + "." + nameof(PlatformDetection.IsNotWindowsNanoServer))]
+ // These values are outside the valid range of the LineCap enum.
+ [InlineData(LineCap.Flat - 1)]
+ [InlineData(LineCap.Custom + 1)]
+ public void Ctor_InvalidLineCap_ReturnsFlat(LineCap baseCap)
+ {
+ using (GraphicsPath fillPath = new GraphicsPath())
+ using (GraphicsPath strokePath = new GraphicsPath())
+ using (CustomLineCap customLineCap = new CustomLineCap(fillPath, strokePath, baseCap, 0f))
+ {
+ Assert.Equal(LineCap.Flat, customLineCap.BaseCap);
+ }
+ }
+
+ [ConditionalFact(nameof(PlatformDetection) + "." + nameof(PlatformDetection.IsNotWindowsNanoServer))]
+ public void Ctor_FillPath_Incomplete_ThrowsArgumentException()
+ {
+ using (GraphicsPath fillPath = new GraphicsPath())
+ {
+ fillPath.AddLine(new Point(0, -10), new Point(0, 10));
+ AssertExtensions.Throws<ArgumentException>(null, () => new CustomLineCap(fillPath, null));
+ }
+ }
+
+ [ConditionalFact(nameof(PlatformDetection) + "." + nameof(PlatformDetection.IsNotWindowsNanoServer))]
+ public void Ctor_FillPath_DoesNotCrossYAxis_ThrowsNotImplementedException()
+ {
+ // Closed fillPath, but does not cross the Y-axis.
+ using (GraphicsPath fillPath = new GraphicsPath())
+ {
+ fillPath.AddLine(new Point(-5, 5), new Point(5, 5));
+ fillPath.AddLine(new Point(5, 5), new Point(5, 1));
+ fillPath.AddLine(new Point(5, 1), new Point(-5, 5));
+ Assert.Throws<NotImplementedException>(() => new CustomLineCap(fillPath, null));
+ }
+ }
+
+ [ConditionalTheory(nameof(PlatformDetection) + "." + nameof(PlatformDetection.IsNotWindowsNanoServer))]
+ [InlineData(LineCap.Square, LineCap.Square)]
+ [InlineData(LineCap.Round, LineCap.Round)]
+ [InlineData(LineCap.Triangle, LineCap.Triangle)]
+ public void SetThenGetStrokeCaps_Success(LineCap startCap, LineCap endCap)
+ {
+ using (GraphicsPath strokePath = new GraphicsPath())
+ using (CustomLineCap customLineCap = new CustomLineCap(null, strokePath))
+ {
+ customLineCap.SetStrokeCaps(startCap, endCap);
+ customLineCap.GetStrokeCaps(out LineCap retrievedStartCap, out LineCap retrievedEndCap);
+
+ Assert.Equal(startCap, retrievedStartCap);
+ Assert.Equal(endCap, retrievedEndCap);
+ }
+ }
+
+ [ConditionalTheory(nameof(PlatformDetection) + "." + nameof(PlatformDetection.IsNotWindowsNanoServer))]
+ [InlineData(LineCap.SquareAnchor, LineCap.SquareAnchor)]
+ [InlineData(LineCap.Custom, LineCap.Custom)]
+ [InlineData(LineCap.Square, LineCap.Custom)]
+ [InlineData(LineCap.Custom, LineCap.SquareAnchor)]
+ [InlineData(LineCap.Flat - 1, LineCap.Flat)] // Below valid enum range
+ [InlineData(LineCap.Custom + 1, LineCap.Flat)] // Above valid enum range
+ public void SetStrokeCaps_InvalidLineCap_ThrowsArgumentException(LineCap startCap, LineCap endCap)
+ {
+ using (GraphicsPath strokePath = new GraphicsPath())
+ using (CustomLineCap customLineCap = new CustomLineCap(null, strokePath))
+ {
+ AssertExtensions.Throws<ArgumentException>(null, () => customLineCap.SetStrokeCaps(startCap, endCap));
+
+ // start and end cap should be unchanged.
+ customLineCap.GetStrokeCaps(out LineCap retrievedStartCap, out LineCap retrievedEndCap);
+ Assert.Equal(LineCap.Flat, retrievedStartCap);
+ Assert.Equal(LineCap.Flat, retrievedEndCap);
+ }
+ }
+
+ [ConditionalTheory(nameof(PlatformDetection) + "." + nameof(PlatformDetection.IsNotWindowsNanoServer))]
+ [InlineData(LineJoin.Miter)] // Default value
+ [InlineData(LineJoin.Bevel)]
+ [InlineData(LineJoin.Round)]
+ [InlineData(LineJoin.MiterClipped)]
+ // Invalid (non-enum) values are allowed. Their values are stored and returned unchanged.
+ [InlineData(LineJoin.Miter - 1)]
+ [InlineData(LineJoin.MiterClipped + 1)]
+ public void StrokeJoin_SetThenGet_Success(LineJoin lineJoin)
+ {
+ using (GraphicsPath strokePath = new GraphicsPath())
+ using (CustomLineCap customLineCap = new CustomLineCap(null, strokePath))
+ {
+ customLineCap.StrokeJoin = lineJoin;
+ Assert.Equal(lineJoin, customLineCap.StrokeJoin);
+ }
+ }
+
+ [ConditionalTheory(nameof(PlatformDetection) + "." + nameof(PlatformDetection.IsNotWindowsNanoServer))]
+ [InlineData(LineCap.Flat)] // Default value
+ [InlineData(LineCap.Square)]
+ [InlineData(LineCap.Round)]
+ [InlineData(LineCap.Triangle)]
+ public void BaseCap_SetThenGet_Success(LineCap baseCap)
+ {
+ using (GraphicsPath strokePath = new GraphicsPath())
+ using (CustomLineCap customLineCap = new CustomLineCap(null, strokePath))
+ {
+ customLineCap.BaseCap = baseCap;
+ Assert.Equal(baseCap, customLineCap.BaseCap);
+ }
+ }
+
+ [InlineData(LineCap.NoAnchor)]
+ [InlineData(LineCap.SquareAnchor)]
+ [InlineData(LineCap.RoundAnchor)]
+ [InlineData(LineCap.DiamondAnchor)]
+ [InlineData(LineCap.Custom)]
+ [InlineData(LineCap.Flat - 1)]
+ [InlineData(LineCap.Custom + 1)]
+ public void BaseCap_Set_InvalidLineCap_ThrowsArgumentException(LineCap baseCap)
+ {
+ using (GraphicsPath strokePath = new GraphicsPath())
+ using (CustomLineCap customLineCap = new CustomLineCap(null, strokePath))
+ {
+ AssertExtensions.Throws<ArgumentException>(null, () => customLineCap.BaseCap = baseCap);
+ Assert.Equal(LineCap.Flat, customLineCap.BaseCap);
+ }
+ }
+
+ [ConditionalTheory(nameof(PlatformDetection) + "." + nameof(PlatformDetection.IsNotWindowsNanoServer))]
+ [InlineData(0f)]
+ [InlineData(1f)]
+ [InlineData(10f)]
+ [InlineData(10000f)]
+ [InlineData(-1f)]
+ [InlineData(-10f)]
+ [InlineData(-10000f)]
+ [InlineData(float.MaxValue)]
+ [InlineData(float.MinValue)]
+ [InlineData(float.PositiveInfinity)]
+ [InlineData(float.NegativeInfinity)]
+ [InlineData(float.NaN)]
+ public void BaseInset_SetThenGet_Success(float value)
+ {
+ using (GraphicsPath strokePath = new GraphicsPath())
+ using (CustomLineCap customLineCap = new CustomLineCap(null, strokePath))
+ {
+ customLineCap.BaseInset = value;
+ Assert.Equal(value, customLineCap.BaseInset);
+ }
+ }
+
+ [ConditionalTheory(nameof(PlatformDetection) + "." + nameof(PlatformDetection.IsNotWindowsNanoServer))]
+ [InlineData(0f)]
+ [InlineData(1f)]
+ [InlineData(10f)]
+ [InlineData(10000f)]
+ [InlineData(-1f)]
+ [InlineData(-10f)]
+ [InlineData(-10000f)]
+ [InlineData(float.MaxValue)]
+ [InlineData(float.MinValue)]
+ [InlineData(float.PositiveInfinity)]
+ [InlineData(float.NegativeInfinity)]
+ [InlineData(float.NaN)]
+ public void WidthScale_SetThenGet_Success(float value)
+ {
+ using (GraphicsPath strokePath = new GraphicsPath())
+ using (CustomLineCap customLineCap = new CustomLineCap(null, strokePath))
+ {
+ customLineCap.WidthScale = value;
+ Assert.Equal(value, customLineCap.WidthScale);
+ }
+ }
+
+ [ConditionalFact(nameof(PlatformDetection) + "." + nameof(PlatformDetection.IsNotWindowsNanoServer))]
+ public void Disposed_MembersThrow()
+ {
+ using (GraphicsPath strokePath = new GraphicsPath())
+ using (CustomLineCap customLineCap = new CustomLineCap(null, strokePath))
+ {
+ customLineCap.Dispose();
+ AssertExtensions.Throws<ArgumentException>(null, () => customLineCap.StrokeJoin);
+ AssertExtensions.Throws<ArgumentException>(null, () => customLineCap.BaseCap);
+ AssertExtensions.Throws<ArgumentException>(null, () => customLineCap.BaseInset);
+ AssertExtensions.Throws<ArgumentException>(null, () => customLineCap.WidthScale);
+ AssertExtensions.Throws<ArgumentException>(null, () => customLineCap.Clone());
+ AssertExtensions.Throws<ArgumentException>(null, () => customLineCap.SetStrokeCaps(LineCap.Flat, LineCap.Flat));
+ AssertExtensions.Throws<ArgumentException>(null, () => customLineCap.GetStrokeCaps(out LineCap startCap, out LineCap endCap));
+ }
+ }
+ }
+}
diff --git a/src/System.Drawing.Common/tests/Drawing2D/GraphicsPathIteratorTests.cs b/src/System.Drawing.Common/tests/Drawing2D/GraphicsPathIteratorTests.cs
new file mode 100644
index 0000000000..cc6196f7a0
--- /dev/null
+++ b/src/System.Drawing.Common/tests/Drawing2D/GraphicsPathIteratorTests.cs
@@ -0,0 +1,427 @@
+// Licensed to the .NET Foundation under one or more agreements.
+// See the LICENSE file in the project root for more information.
+//
+// Copyright (C) 2006-2007 Novell, Inc (http://www.novell.com)
+//
+// Permission is hereby granted, free of charge, to any person obtaining
+// a copy of this software and associated documentation files (the
+// "Software"), to deal in the Software without restriction, including
+// without limitation the rights to use, copy, modify, merge, publish,
+// distribute, sublicense, and/or sell copies of the Software, and to
+// permit persons to whom the Software is furnished to do so, subject to
+// the following conditions:
+//
+// The above copyright notice and this permission notice shall be
+// included in all copies or substantial portions of the Software.
+//
+// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
+// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
+// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
+// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
+// LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
+// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
+// WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
+//
+
+using System.Collections.Generic;
+using System.Security.Permissions;
+using Xunit;
+
+namespace System.Drawing.Drawing2D.Tests
+{
+ public class GraphicsPathIteratorTests
+ {
+ private readonly PointF[] _twoPoints = new PointF[2] { new PointF(1, 2), new PointF(20, 30) };
+
+ [ConditionalFact(nameof(PlatformDetection) + "." + nameof(PlatformDetection.IsNotWindowsNanoServer))]
+ public void Ctor_Path_Success()
+ {
+ byte[] types = new byte[] { 0, 1 };
+
+ using (GraphicsPath gp = new GraphicsPath(_twoPoints, types))
+ using (GraphicsPathIterator gpi = new GraphicsPathIterator(gp))
+ {
+ Assert.Equal(2, gpi.Count);
+ }
+ }
+
+ [ConditionalFact(nameof(PlatformDetection) + "." + nameof(PlatformDetection.IsNotWindowsNanoServer))]
+ public void Ctor_EmptyPath_Success()
+ {
+ using (GraphicsPath gp = new GraphicsPath())
+ using (GraphicsPathIterator gpi = new GraphicsPathIterator(gp))
+ {
+ Assert.Equal(0, gpi.Count);
+ }
+ }
+
+ [ConditionalFact(nameof(PlatformDetection) + "." + nameof(PlatformDetection.IsNotWindowsNanoServer))]
+ public void Ctor_NullPath_Success()
+ {
+ using (GraphicsPathIterator gpi = new GraphicsPathIterator(null))
+ {
+ Assert.Equal(0, gpi.Count);
+ }
+ }
+
+ [ConditionalFact(nameof(PlatformDetection) + "." + nameof(PlatformDetection.IsNotWindowsNanoServer))]
+ public void NextSubpath_PathFigureNotClosed_ReturnsExpeced()
+ {
+ using (GraphicsPath gp = new GraphicsPath())
+ using (GraphicsPathIterator gpi = new GraphicsPathIterator(gp))
+ {
+ gp.AddLines(_twoPoints);
+ Assert.Equal(0, gpi.NextSubpath(gp, out bool isClosed));
+ Assert.False(isClosed);
+ }
+ }
+
+ [ConditionalFact(nameof(PlatformDetection) + "." + nameof(PlatformDetection.IsNotWindowsNanoServer))]
+ public void NextSubpath_PathFigureClosed_ReturnsExpeced()
+ {
+ using (GraphicsPath gp = new GraphicsPath(_twoPoints, new byte[] { 0, 129 }))
+ using (GraphicsPathIterator gpi = new GraphicsPathIterator(gp))
+ {
+ Assert.Equal(2, gpi.NextSubpath(gp, out bool isClosed));
+ Assert.True(isClosed);
+ }
+ }
+
+ [ConditionalFact(nameof(PlatformDetection) + "." + nameof(PlatformDetection.IsNotWindowsNanoServer))]
+ public void NextSubpath_NullPath_ReturnsExpected()
+ {
+ using (GraphicsPathIterator gpi = new GraphicsPathIterator(null))
+ {
+ Assert.Equal(0, gpi.NextSubpath(null, out bool isClosed));
+ Assert.False(isClosed);
+ }
+ }
+
+ [ConditionalFact(nameof(PlatformDetection) + "." + nameof(PlatformDetection.IsNotWindowsNanoServer))]
+ public void NextSubpath_FigureNotClosed_ReturnsExpeced()
+ {
+ using (GraphicsPath gp = new GraphicsPath())
+ using (GraphicsPathIterator gpi = new GraphicsPathIterator(gp))
+ {
+ gp.AddLines(_twoPoints);
+ Assert.Equal(0, gpi.NextSubpath(out int startIndex, out int endIndex, out bool isClosed));
+ Assert.False(isClosed);
+ Assert.Equal(0, startIndex);
+ Assert.Equal(0, endIndex);
+ }
+ }
+
+ [ConditionalFact(nameof(PlatformDetection) + "." + nameof(PlatformDetection.IsNotWindowsNanoServer))]
+ public void NextSubpath_FigureClosed_ReturnsExpeced()
+ {
+ using (GraphicsPath gp = new GraphicsPath(_twoPoints, new byte[] { 0, 129 }))
+ using (GraphicsPathIterator gpi = new GraphicsPathIterator(gp))
+ {
+ Assert.Equal(2, gpi.NextSubpath(out int startIndex, out int endIndex, out bool isClosed));
+ Assert.True(isClosed);
+ Assert.Equal(0, startIndex);
+ Assert.Equal(1, endIndex);
+ }
+ }
+
+ [ConditionalFact(nameof(PlatformDetection) + "." + nameof(PlatformDetection.IsNotWindowsNanoServer))]
+ public void NextMarker_ReturnsExpected()
+ {
+ using (GraphicsPath gp = new GraphicsPath(_twoPoints, new byte[] { 0, 1 }))
+ using (GraphicsPathIterator gpi = new GraphicsPathIterator(gp))
+ {
+ Assert.Equal(2, gpi.NextMarker(out int startIndex, out int endIndex));
+ Assert.Equal(0, startIndex);
+ Assert.Equal(1, endIndex);
+ }
+ }
+
+ [ConditionalFact(nameof(PlatformDetection) + "." + nameof(PlatformDetection.IsNotWindowsNanoServer))]
+ public void NextMarker_Empty_ReturnsExpected()
+ {
+ using (GraphicsPath gp = new GraphicsPath())
+ using (GraphicsPathIterator gpi = new GraphicsPathIterator(gp))
+ {
+ gp.AddLines(_twoPoints);
+ Assert.Equal(0, gpi.NextMarker(out int startIndex, out int endIndex));
+ Assert.Equal(0, startIndex);
+ Assert.Equal(0, endIndex);
+ }
+ }
+
+ [ConditionalFact(nameof(PlatformDetection) + "." + nameof(PlatformDetection.IsNotWindowsNanoServer))]
+ public void NextMarker_NullPath_ReturnsExpected()
+ {
+ using (GraphicsPath gp = new GraphicsPath())
+ using (GraphicsPathIterator gpi = new GraphicsPathIterator(gp))
+ {
+ gp.AddLines(_twoPoints);
+ Assert.Equal(0, gpi.NextMarker(null));
+ }
+ }
+
+ [ConditionalFact(nameof(PlatformDetection) + "." + nameof(PlatformDetection.IsNotWindowsNanoServer))]
+ public void NextMarker_EmptyPath_ReturnsExpected()
+ {
+ using (GraphicsPath gp = new GraphicsPath())
+ using (GraphicsPathIterator gpi = new GraphicsPathIterator(gp))
+ {
+ gp.AddLines(_twoPoints);
+ Assert.Equal(0, gpi.NextMarker(gp));
+ }
+ }
+
+ [ConditionalFact(nameof(PlatformDetection) + "." + nameof(PlatformDetection.IsNotWindowsNanoServer))]
+ public void NextMarker_Path_ReturnsExpected()
+ {
+ using (GraphicsPath gp = new GraphicsPath(_twoPoints, new byte[] { 0, 1 }))
+ using (GraphicsPathIterator gpi = new GraphicsPathIterator(gp))
+ {
+ Assert.Equal(2, gpi.NextMarker(gp));
+ }
+ }
+
+ [ConditionalFact(nameof(PlatformDetection) + "." + nameof(PlatformDetection.IsNotWindowsNanoServer))]
+ public void Count_ReturnsExpected()
+ {
+ using (GraphicsPath gp = new GraphicsPath(_twoPoints, new byte[] { 0, 1 }))
+ using (GraphicsPath gpEmpty = new GraphicsPath())
+ using (GraphicsPathIterator gpi = new GraphicsPathIterator(gp))
+ using (GraphicsPathIterator gpiEmpty = new GraphicsPathIterator(gpEmpty))
+ using (GraphicsPathIterator gpiNull = new GraphicsPathIterator(null))
+ {
+ Assert.Equal(2, gpi.Count);
+ Assert.Equal(0, gpiEmpty.Count);
+ Assert.Equal(0, gpiNull.Count);
+ }
+ }
+
+ [ConditionalFact(nameof(PlatformDetection) + "." + nameof(PlatformDetection.IsNotWindowsNanoServer))]
+ public void SubpathCount_ReturnsExpected()
+ {
+ using (GraphicsPath gp = new GraphicsPath())
+ using (GraphicsPathIterator gpi = new GraphicsPathIterator(gp))
+ using (GraphicsPathIterator gpiNull = new GraphicsPathIterator(null))
+ {
+ Assert.Equal(0, gpi.SubpathCount);
+ Assert.Equal(0, gpiNull.SubpathCount);
+
+ gp.AddLine(0, 1, 2, 3);
+ gp.SetMarkers();
+ gp.StartFigure();
+ gp.AddLine(20, 21, 22, 23);
+ gp.AddBezier(5, 6, 7, 8, 9, 10, 11, 12);
+
+ using (GraphicsPathIterator gpiWithSubpaths = new GraphicsPathIterator(gp))
+ {
+ Assert.Equal(2, gpiWithSubpaths.SubpathCount);
+ }
+ }
+ }
+
+ [ConditionalFact(nameof(PlatformDetection) + "." + nameof(PlatformDetection.IsNotWindowsNanoServer))]
+ public void HasCurve_ReturnsExpected()
+ {
+ Point[] points = new Point[] { new Point(1, 1), new Point(2, 2), new Point(3, 3), new Point(4, 4) };
+ byte[] types = new byte[] { 0, 3, 3, 3 };
+
+ using (GraphicsPath gp = new GraphicsPath(points, types))
+ using (GraphicsPath gpEmpty = new GraphicsPath())
+ using (GraphicsPathIterator gpi = new GraphicsPathIterator(gp))
+ using (GraphicsPathIterator gpiEmpty = new GraphicsPathIterator(gpEmpty))
+ using (GraphicsPathIterator gpiNull = new GraphicsPathIterator(null))
+ {
+ Assert.True(gpi.HasCurve());
+ Assert.False(gpiEmpty.HasCurve());
+ Assert.False(gpiNull.HasCurve());
+ }
+ }
+
+ [ConditionalFact(nameof(PlatformDetection) + "." + nameof(PlatformDetection.IsNotWindowsNanoServer))]
+ public void Rewind_Succes()
+ {
+ using (GraphicsPath gp = new GraphicsPath())
+ using (GraphicsPath inner = new GraphicsPath())
+ {
+ gp.AddLine(0, 1, 2, 3);
+ gp.SetMarkers();
+ gp.StartFigure();
+ gp.AddLine(20, 21, 22, 23);
+ gp.AddBezier(5, 6, 7, 8, 9, 10, 11, 12);
+ byte[] types = new byte[] { 0, 3, 3, 3, 1, 33, 0, 1 };
+
+ using (GraphicsPathIterator gpi = new GraphicsPathIterator(gp))
+ {
+ Assert.Equal(2, gpi.SubpathCount);
+ Assert.Equal(2, gpi.NextMarker(gp));
+ Assert.Equal(6, gpi.NextMarker(gp));
+ Assert.Equal(0, gpi.NextMarker(gp));
+ gpi.Rewind();
+ Assert.Equal(8, gpi.NextMarker(gp));
+ Assert.Equal(0, gpi.NextMarker(gp));
+ }
+ }
+ }
+
+ [ConditionalFact(nameof(PlatformDetection) + "." + nameof(PlatformDetection.IsNotWindowsNanoServer))]
+ public void Enumerate_ZeroPoints_ReturnsExpected()
+ {
+ PointF[] points = new PointF[0];
+ byte[] types = new byte[0];
+
+ using (GraphicsPath gp = new GraphicsPath())
+ using (GraphicsPathIterator gpi = new GraphicsPathIterator(gp))
+ {
+ Assert.Equal(0, gpi.Enumerate(ref points, ref types));
+ Assert.Equal(0, points.Length);
+ Assert.Equal(0, types.Length);
+ }
+ }
+
+ [ConditionalFact(nameof(PlatformDetection) + "." + nameof(PlatformDetection.IsNotWindowsNanoServer))]
+ public void Enumerate_ReturnsExpected()
+ {
+ PointF[] points = new PointF[] { new PointF(1f, 1f), new PointF(2f, 2f), new PointF(3f, 3f), new PointF(4f, 4f) };
+ byte[] types = new byte[] { 0, 3, 3, 3 };
+
+ PointF[] actualPoints = new PointF[4];
+ byte[] actualTypes = new byte[4];
+
+ using (GraphicsPath gp = new GraphicsPath(points, types))
+ using (GraphicsPathIterator gpi = new GraphicsPathIterator(gp))
+ {
+ Assert.Equal(4, gpi.Enumerate(ref actualPoints, ref actualTypes));
+ Assert.Equal(gp.PathPoints, actualPoints);
+ Assert.Equal(gp.PathTypes, actualTypes);
+ }
+ }
+
+ private static IEnumerable<object[]> PointsTypesLenghtMismatch_TestData()
+ {
+ yield return new object[] { new PointF[1], new byte[2] };
+ yield return new object[] { new PointF[2], new byte[1] };
+ }
+
+ [ConditionalTheory(nameof(PlatformDetection) + "." + nameof(PlatformDetection.IsNotWindowsNanoServer))]
+ [MemberData(nameof(PointsTypesLenghtMismatch_TestData))]
+ public void Enumerate_PointsTypesMismatch_ThrowsArgumentException(PointF[] points, byte[] types)
+ {
+ using (GraphicsPath gp = new GraphicsPath())
+ using (GraphicsPathIterator gpi = new GraphicsPathIterator(gp))
+ {
+ AssertExtensions.Throws<ArgumentException>(null, () => gpi.Enumerate(ref points, ref types));
+ }
+ }
+
+ private static IEnumerable<object[]> NullPointsTypes_TestData()
+ {
+ yield return new object[] { null, new byte[1] };
+ yield return new object[] { new PointF[1], null };
+ yield return new object[] { null, null };
+ }
+
+ [ConditionalTheory(nameof(PlatformDetection) + "." + nameof(PlatformDetection.IsNotWindowsNanoServer))]
+ [MemberData(nameof(NullPointsTypes_TestData))]
+ public void Enumerate_NullPointsTypes_ThrowsNullReferenceException(PointF[] points, byte[] types)
+ {
+ using (GraphicsPath gp = new GraphicsPath())
+ using (GraphicsPathIterator gpi = new GraphicsPathIterator(gp))
+ {
+ Assert.Throws<NullReferenceException>(() => gpi.Enumerate(ref points, ref types));
+ }
+ }
+
+ [ConditionalTheory(nameof(PlatformDetection) + "." + nameof(PlatformDetection.IsNotWindowsNanoServer))]
+ [MemberData(nameof(PointsTypesLenghtMismatch_TestData))]
+ public void CopyData_PointsTypesMismatch_ThrowsArgumentException(PointF[] points, byte[] types)
+ {
+ using (GraphicsPath gp = new GraphicsPath())
+ using (GraphicsPathIterator gpi = new GraphicsPathIterator(gp))
+ {
+ AssertExtensions.Throws<ArgumentException>(null, () => gpi.CopyData(ref points, ref types, 0, points.Length));
+ }
+ }
+
+ [ConditionalTheory(nameof(PlatformDetection) + "." + nameof(PlatformDetection.IsNotWindowsNanoServer))]
+ [MemberData(nameof(NullPointsTypes_TestData))]
+ public void CopyData_NullPointsTypes_ThrowsNullReferenceException(PointF[] points, byte[] types)
+ {
+ using (GraphicsPath gp = new GraphicsPath())
+ using (GraphicsPathIterator gpi = new GraphicsPathIterator(gp))
+ {
+ Assert.Throws<NullReferenceException>(() => gpi.CopyData(ref points, ref types, 0, 1));
+ }
+ }
+
+ [ConditionalTheory(nameof(PlatformDetection) + "." + nameof(PlatformDetection.IsNotWindowsNanoServer))]
+ [InlineData(-1, 2)]
+ [InlineData(0, 3)]
+ public void CopyData_StartEndIndexesOutOfRange_ThrowsArgumentException(int startIndex, int endIndex)
+ {
+ PointF[] resultPoints = new PointF[0];
+ byte[] resultTypes = new byte[0];
+
+ using (GraphicsPath gp = new GraphicsPath())
+ using (GraphicsPathIterator gpi = new GraphicsPathIterator(gp))
+ {
+ AssertExtensions.Throws<ArgumentException>(null, () => gpi.CopyData(ref resultPoints, ref resultTypes, startIndex, endIndex));
+ }
+ }
+
+ public static IEnumerable<object[]> CopyData_StartEndIndexesOutOfRange_TestData()
+ {
+ yield return new object[] { new PointF[3], new byte[3], int.MinValue, 2 };
+ yield return new object[] { new PointF[3], new byte[3], 0, int.MaxValue };
+ yield return new object[] { new PointF[3], new byte[3], 2, 0 };
+ }
+
+ [ActiveIssue(22026)]
+ [ConditionalTheory(nameof(PlatformDetection) + "." + nameof(PlatformDetection.IsNotWindowsNanoServer))]
+ [MemberData(nameof(CopyData_StartEndIndexesOutOfRange_TestData))]
+ public void CopyData_StartEndIndexesOutOfRange_ReturnsExpeced(PointF[] points, byte[] types, int startIndex, int endIndex)
+ {
+ PointF[] resultPoints = new PointF[points.Length];
+ byte[] resultTypes = new byte[points.Length];
+
+ using (GraphicsPath gp = new GraphicsPath(points, types))
+ using (GraphicsPathIterator gpi = new GraphicsPathIterator(gp))
+ {
+ Assert.Equal(0, gpi.CopyData(ref resultPoints, ref resultTypes, startIndex, endIndex));
+ }
+ }
+
+ [ConditionalFact(nameof(PlatformDetection) + "." + nameof(PlatformDetection.IsNotWindowsNanoServer))]
+ public void CopyData_EqualStartEndIndexes_ReturnsExpeced()
+ {
+ PointF[] points = new PointF[] { new PointF(1f, 1f), new PointF(2f, 2f), new PointF(3f, 3f), new PointF(4f, 4f) };
+ byte[] types = new byte[] { 0, 3, 3, 3 };
+
+ PointF[] actualPoints = new PointF[1];
+ byte[] actualTypes = new byte[1];
+
+ using (GraphicsPath gp = new GraphicsPath(points, types))
+ using (GraphicsPathIterator gpi = new GraphicsPathIterator(gp))
+ {
+ Assert.Equal(1, gpi.CopyData(ref actualPoints, ref actualTypes, 0, 0));
+ Assert.Equal(gp.PathPoints[0], actualPoints[0]);
+ Assert.Equal(gp.PathTypes[0], actualTypes[0]);
+ }
+ }
+
+ [ConditionalFact(nameof(PlatformDetection) + "." + nameof(PlatformDetection.IsNotWindowsNanoServer))]
+ public void CopyData_ReturnsExpected()
+ {
+ PointF[] points = new PointF[] { new PointF(1f, 1f), new PointF(2f, 2f), new PointF(3f, 3f), new PointF(4f, 4f) };
+ byte[] types = new byte[] { 0, 3, 3, 3 };
+
+ PointF[] actualPoints = new PointF[3];
+ byte[] actualTypes = new byte[3];
+
+ using (GraphicsPath gp = new GraphicsPath(points, types))
+ using (GraphicsPathIterator gpi = new GraphicsPathIterator(gp))
+ {
+ Assert.Equal(3, gpi.CopyData(ref actualPoints, ref actualTypes, 0, 2));
+ }
+ }
+ }
+}
diff --git a/src/System.Drawing.Common/tests/Drawing2D/GraphicsPathTests.cs b/src/System.Drawing.Common/tests/Drawing2D/GraphicsPathTests.cs
new file mode 100644
index 0000000000..5f617dc172
--- /dev/null
+++ b/src/System.Drawing.Common/tests/Drawing2D/GraphicsPathTests.cs
@@ -0,0 +1,2684 @@
+// Licensed to the .NET Foundation under one or more agreements.
+// See the LICENSE file in the project root for more information.
+//
+// Copyright (C) 2006-2007 Novell, Inc (http://www.novell.com)
+//
+// Permission is hereby granted, free of charge, to any person obtaining
+// a copy of this software and associated documentation files (the
+// "Software"), to deal in the Software without restriction, including
+// without limitation the rights to use, copy, modify, merge, publish,
+// distribute, sublicense, and/or sell copies of the Software, and to
+// permit persons to whom the Software is furnished to do so, subject to
+// the following conditions:
+//
+// The above copyright notice and this permission notice shall be
+// included in all copies or substantial portions of the Software.
+//
+// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
+// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
+// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
+// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
+// LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
+// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
+// WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
+//
+
+using System.Collections.Generic;
+using System.ComponentModel;
+using Xunit;
+
+namespace System.Drawing.Drawing2D.Tests
+{
+ public class GraphicsPathTests
+ {
+ private const float Pi4 = (float)(Math.PI / 4);
+ private const float Delta = 0.0003f;
+
+ [ConditionalFact(nameof(PlatformDetection) + "." + nameof(PlatformDetection.IsNotWindowsNanoServer))]
+ public void Ctor_Default_Success()
+ {
+ using (GraphicsPath gp = new GraphicsPath())
+ {
+ Assert.Equal(FillMode.Alternate, gp.FillMode);
+ AssertEmptyGrahicsPath(gp);
+ }
+ }
+
+ [ConditionalFact(nameof(PlatformDetection) + "." + nameof(PlatformDetection.IsNotWindowsNanoServer))]
+ public void Ctor_FillMode_Success()
+ {
+ using (GraphicsPath gpa = new GraphicsPath(FillMode.Alternate))
+ using (GraphicsPath gpw = new GraphicsPath(FillMode.Winding))
+ {
+ Assert.Equal(FillMode.Alternate, gpa.FillMode);
+ AssertEmptyGrahicsPath(gpa);
+ Assert.Equal(FillMode.Winding, gpw.FillMode);
+ AssertEmptyGrahicsPath(gpw);
+ }
+ }
+
+ [ConditionalFact(nameof(PlatformDetection) + "." + nameof(PlatformDetection.IsNotWindowsNanoServer))]
+ public void Ctor_SamePoints_Success()
+ {
+ byte[] types = new byte[6] { 0, 1, 1, 1, 1, 1 };
+ Point[] points = new Point[]
+ {
+ new Point (1, 1), new Point (1, 1), new Point (1, 1),
+ new Point (1, 1), new Point (1, 1), new Point (1, 1),
+ };
+
+ PointF[] fPoints = new PointF[]
+ {
+ new PointF (1f, 1f), new PointF (1f, 1f), new PointF (1f, 1f),
+ new PointF (1f, 1f), new PointF (1f, 1f), new PointF (1f, 1f),
+ };
+
+ using (GraphicsPath gp = new GraphicsPath(points, types))
+ using (GraphicsPath gpf = new GraphicsPath(fPoints, types))
+ {
+ Assert.Equal(FillMode.Alternate, gp.FillMode);
+ Assert.Equal(6, gp.PointCount);
+ Assert.Equal(FillMode.Alternate, gpf.FillMode);
+ Assert.Equal(6, gpf.PointCount);
+ types[0] = 1;
+ Assert.Equal(FillMode.Alternate, gp.FillMode);
+ Assert.Equal(6, gp.PointCount);
+ Assert.Equal(FillMode.Alternate, gpf.FillMode);
+ Assert.Equal(6, gpf.PointCount);
+ }
+ }
+
+ [ConditionalFact(nameof(PlatformDetection) + "." + nameof(PlatformDetection.IsNotWindowsNanoServer))]
+ public void Ctor_PointsNull_ThrowsArgumentNullException()
+ {
+ AssertExtensions.Throws<ArgumentNullException>("pts", () => new GraphicsPath((Point[])null, new byte[1]));
+ }
+
+ private static IEnumerable<object[]> AddCurve_PointsTypesLengthMismatch_TestData()
+ {
+ yield return new object[] { 1, 2 };
+ yield return new object[] { 2, 1 };
+ }
+
+ [ConditionalTheory(nameof(PlatformDetection) + "." + nameof(PlatformDetection.IsNotWindowsNanoServer))]
+ [MemberData(nameof(AddCurve_PointsTypesLengthMismatch_TestData))]
+ public void Ctor_PointsTypesLengthMismatch_ThrowsArgumentException(int pointsLength, int typesLength)
+ {
+ AssertExtensions.Throws<ArgumentException>(null, () => new GraphicsPath(new Point[pointsLength], new byte[typesLength]));
+ AssertExtensions.Throws<ArgumentException>(null, () => new GraphicsPath(new PointF[pointsLength], new byte[typesLength]));
+ }
+
+ [ConditionalFact(nameof(PlatformDetection) + "." + nameof(PlatformDetection.IsNotWindowsNanoServer))]
+ public void Clone_Success()
+ {
+ using (GraphicsPath gp = new GraphicsPath())
+ using (GraphicsPath clone = Assert.IsType<GraphicsPath>(gp.Clone()))
+ {
+ Assert.Equal(FillMode.Alternate, clone.FillMode);
+ AssertEmptyGrahicsPath(clone);
+ }
+ }
+
+ [ConditionalFact(nameof(PlatformDetection) + "." + nameof(PlatformDetection.IsNotWindowsNanoServer))]
+ public void Reset_Success()
+ {
+ using (GraphicsPath gp = new GraphicsPath())
+ {
+ gp.Reset();
+
+ Assert.Equal(FillMode.Alternate, gp.FillMode);
+ AssertEmptyGrahicsPath(gp);
+ }
+ }
+
+ [ConditionalFact(nameof(PlatformDetection) + "." + nameof(PlatformDetection.IsNotWindowsNanoServer))]
+ public void GraphicsPath_FillModeChange()
+ {
+ using (GraphicsPath gp = new GraphicsPath())
+ {
+ gp.FillMode = FillMode.Winding;
+ Assert.Equal(FillMode.Winding, gp.FillMode);
+ }
+ }
+
+ [ConditionalTheory(nameof(PlatformDetection) + "." + nameof(PlatformDetection.IsNotWindowsNanoServer))]
+ [InlineData(FillMode.Alternate - 1)]
+ [InlineData(FillMode.Winding + 1)]
+ public void GraphicsPath_InvalidFillMode_ThrowsInvalidEnumArgumentException(FillMode fillMode)
+ {
+ using (GraphicsPath gp = new GraphicsPath())
+ {
+ AssertExtensions.Throws<InvalidEnumArgumentException>("value", () => gp.FillMode = fillMode);
+ }
+ }
+
+ [ConditionalFact(nameof(PlatformDetection) + "." + nameof(PlatformDetection.IsNotWindowsNanoServer))]
+ public void PathData_ReturnsExpected()
+ {
+ using (GraphicsPath gp = new GraphicsPath())
+ {
+ Assert.Equal(0, gp.PathData.Points.Length);
+ Assert.Equal(0, gp.PathData.Types.Length);
+ }
+ }
+
+ [ConditionalFact(nameof(PlatformDetection) + "." + nameof(PlatformDetection.IsNotWindowsNanoServer))]
+ public void PathData_CannotChange()
+ {
+ using (GraphicsPath gp = new GraphicsPath())
+ {
+ gp.AddRectangle(new Rectangle(1, 1, 2, 2));
+ Assert.Equal(1f, gp.PathData.Points[0].X);
+ Assert.Equal(1f, gp.PathData.Points[0].Y);
+
+ gp.PathData.Points[0] = new Point(0, 0);
+ Assert.Equal(1f, gp.PathData.Points[0].X);
+ Assert.Equal(1f, gp.PathData.Points[0].Y);
+ }
+ }
+
+ [ConditionalFact(nameof(PlatformDetection) + "." + nameof(PlatformDetection.IsNotWindowsNanoServer))]
+ public void PathPoints_CannotChange()
+ {
+ using (GraphicsPath gp = new GraphicsPath())
+ {
+ gp.AddRectangle(new Rectangle(1, 1, 2, 2));
+ Assert.Equal(1f, gp.PathPoints[0].X);
+ Assert.Equal(1f, gp.PathPoints[0].Y);
+
+ gp.PathPoints[0] = new Point(0, 0);
+ Assert.Equal(1f, gp.PathPoints[0].X);
+ Assert.Equal(1f, gp.PathPoints[0].Y);
+ }
+ }
+
+ [ConditionalFact(nameof(PlatformDetection) + "." + nameof(PlatformDetection.IsNotWindowsNanoServer))]
+ public void PathPoints_EmptyPath_ThrowsArgumentException()
+ {
+ using (GraphicsPath gp = new GraphicsPath())
+ {
+ Assert.Throws<ArgumentException>(() => gp.PathPoints);
+ }
+ }
+
+ [ConditionalFact(nameof(PlatformDetection) + "." + nameof(PlatformDetection.IsNotWindowsNanoServer))]
+ public void PathTypes_CannotChange()
+ {
+ using (GraphicsPath gp = new GraphicsPath())
+ {
+ gp.AddRectangle(new Rectangle(1, 1, 2, 2));
+ Assert.Equal(0, gp.PathTypes[0]);
+
+ gp.PathTypes[0] = 1;
+ Assert.Equal(0, gp.PathTypes[0]);
+ }
+ }
+
+ [ConditionalFact(nameof(PlatformDetection) + "." + nameof(PlatformDetection.IsNotWindowsNanoServer))]
+ public void PathTypes_EmptyPath_ThrowsArgumentException()
+ {
+ using (GraphicsPath gp = new GraphicsPath())
+ {
+ Assert.Throws<ArgumentException>(() => gp.PathTypes);
+ }
+ }
+
+ [ConditionalFact(nameof(PlatformDetection) + "." + nameof(PlatformDetection.IsNotWindowsNanoServer))]
+ public void GetLastPoint_ReturnsExpected()
+ {
+ byte[] types = new byte[3] { 0, 1, 1 };
+ PointF[] points = new PointF[]
+ {
+ new PointF (1f, 1f), new PointF (2f, 2f), new PointF (3f, 3f),
+ };
+
+ using (GraphicsPath gp = new GraphicsPath(points, types))
+ {
+ Assert.Equal(gp.GetLastPoint(), points[2]);
+ }
+ }
+
+ [ConditionalFact(nameof(PlatformDetection) + "." + nameof(PlatformDetection.IsNotWindowsNanoServer))]
+ public void AddLine_Success()
+ {
+ using (GraphicsPath gpInt = new GraphicsPath())
+ using (GraphicsPath gpFloat = new GraphicsPath())
+ using (GraphicsPath gpPointsInt = new GraphicsPath())
+ using (GraphicsPath gpfPointsloat = new GraphicsPath())
+ {
+ gpInt.AddLine(1, 1, 2, 2);
+ // AssertLine() method expects line drawn between points with coordinates 1, 1 and 2, 2, here and below.
+ AssertLine(gpInt);
+
+ gpFloat.AddLine(1, 1, 2, 2);
+ AssertLine(gpFloat);
+
+ gpPointsInt.AddLine(new Point(1, 1), new Point(2, 2));
+ AssertLine(gpPointsInt);
+
+ gpfPointsloat.AddLine(new PointF(1, 1), new PointF(2, 2));
+ AssertLine(gpfPointsloat);
+ }
+ }
+
+ [ConditionalFact(nameof(PlatformDetection) + "." + nameof(PlatformDetection.IsNotWindowsNanoServer))]
+ public void AddLine_SamePoints_Success()
+ {
+ using (GraphicsPath gpi = new GraphicsPath())
+ using (GraphicsPath gpf = new GraphicsPath())
+ {
+ gpi.AddLine(new Point(49, 157), new Point(75, 196));
+ gpi.AddLine(new Point(75, 196), new Point(102, 209));
+ Assert.Equal(3, gpi.PointCount);
+ Assert.Equal(new byte[] { 0, 1, 1 }, gpi.PathTypes);
+
+ gpi.AddLine(new Point(102, 209), new Point(75, 196));
+ Assert.Equal(4, gpi.PointCount);
+ Assert.Equal(new byte[] { 0, 1, 1, 1 }, gpi.PathTypes);
+
+ gpf.AddLine(new PointF(49, 157), new PointF(75, 196));
+ gpf.AddLine(new PointF(75, 196), new PointF(102, 209));
+ Assert.Equal(3, gpf.PointCount);
+ Assert.Equal(new byte[] { 0, 1, 1 }, gpf.PathTypes);
+
+ gpf.AddLine(new PointF(102, 209), new PointF(75, 196));
+ Assert.Equal(4, gpf.PointCount);
+ Assert.Equal(new byte[] { 0, 1, 1, 1 }, gpf.PathTypes);
+ }
+ }
+
+ [ConditionalFact(nameof(PlatformDetection) + "." + nameof(PlatformDetection.IsNotWindowsNanoServer))]
+ public void AddLines_Success()
+ {
+ using (GraphicsPath gpi = new GraphicsPath())
+ using (GraphicsPath gpf = new GraphicsPath())
+ {
+ gpi.AddLines(new Point[] { new Point(1, 1), new Point(2, 2) });
+ AssertLine(gpi);
+
+ gpf.AddLines(new PointF[] { new PointF(1, 1), new PointF(2, 2) });
+ AssertLine(gpf);
+ }
+ }
+
+ [ConditionalFact(nameof(PlatformDetection) + "." + nameof(PlatformDetection.IsNotWindowsNanoServer))]
+ public void AddLines_SinglePoint_Success()
+ {
+ using (GraphicsPath gpi = new GraphicsPath())
+ using (GraphicsPath gpf = new GraphicsPath())
+ {
+ gpi.AddLines(new PointF[] { new PointF(1, 1) });
+ Assert.Equal(1, gpi.PointCount);
+ Assert.Equal(0, gpi.PathTypes[0]);
+
+ gpf.AddLines(new PointF[] { new PointF(1, 1) });
+ Assert.Equal(1, gpf.PointCount);
+ Assert.Equal(0, gpf.PathTypes[0]);
+ }
+ }
+
+ [ConditionalFact(nameof(PlatformDetection) + "." + nameof(PlatformDetection.IsNotWindowsNanoServer))]
+ public void AddLines_SamePoint_Success()
+ {
+ Point[] intPoints = new Point[]
+ {
+ new Point(49, 157), new Point(49, 157)
+ };
+
+ PointF[] floatPoints = new PointF[]
+ {
+ new PointF(49, 57), new PointF(49, 57),
+ new PointF(49, 57), new PointF(49, 57)
+ };
+
+ using (GraphicsPath gpi = new GraphicsPath())
+ using (GraphicsPath gpf = new GraphicsPath())
+ {
+ gpi.AddLines(intPoints);
+ Assert.Equal(2, gpi.PointCount);
+ Assert.Equal(new byte[] { 0, 1 }, gpi.PathTypes);
+
+ gpi.AddLines(intPoints);
+ Assert.Equal(3, gpi.PointCount);
+ Assert.Equal(new byte[] { 0, 1, 1 }, gpi.PathTypes);
+
+ gpi.AddLines(intPoints);
+ Assert.Equal(4, gpi.PointCount);
+ Assert.Equal(new byte[] { 0, 1, 1, 1 }, gpi.PathTypes);
+
+ gpf.AddLines(floatPoints);
+ Assert.Equal(4, gpf.PointCount);
+ Assert.Equal(new byte[] { 0, 1, 1, 1 }, gpf.PathTypes);
+
+ gpf.AddLines(floatPoints);
+ Assert.Equal(7, gpf.PointCount);
+ Assert.Equal(new byte[] { 0, 1, 1, 1, 1, 1, 1 }, gpf.PathTypes);
+ }
+ }
+
+ [ConditionalFact(nameof(PlatformDetection) + "." + nameof(PlatformDetection.IsNotWindowsNanoServer))]
+ public void AddLines_PointsNull_ThrowsArgumentNullException()
+ {
+ using (GraphicsPath gp = new GraphicsPath())
+ {
+ AssertExtensions.Throws<ArgumentNullException>("points", () => new GraphicsPath().AddLines((Point[])null));
+ AssertExtensions.Throws<ArgumentNullException>("points", () => new GraphicsPath().AddLines((PointF[])null));
+ }
+ }
+
+ [ConditionalFact(nameof(PlatformDetection) + "." + nameof(PlatformDetection.IsNotWindowsNanoServer))]
+ public void AddLines_ZeroPoints_ThrowsArgumentException()
+ {
+ AssertExtensions.Throws<ArgumentException>(null, () => new GraphicsPath().AddLines(new Point[0]));
+ AssertExtensions.Throws<ArgumentException>(null, () => new GraphicsPath().AddLines(new PointF[0]));
+ }
+
+ [ConditionalFact(nameof(PlatformDetection) + "." + nameof(PlatformDetection.IsNotWindowsNanoServer))]
+ public void AddArc_Values_Success()
+ {
+ using (GraphicsPath gpi = new GraphicsPath())
+ using (GraphicsPath gpf = new GraphicsPath())
+ {
+ gpi.AddArc(1, 1, 2, 2, Pi4, Pi4);
+ // AssertArc() method expects added Arc with parameters
+ // x=1, y=1, width=2, height=2, startAngle=Pi4, seewpAngle=Pi4 here and below.
+ AssertArc(gpi);
+
+ gpf.AddArc(1f, 1f, 2f, 2f, Pi4, Pi4);
+ AssertArc(gpf);
+ }
+ }
+
+ [ConditionalFact(nameof(PlatformDetection) + "." + nameof(PlatformDetection.IsNotWindowsNanoServer))]
+ public void AddArc_Rectangle_Success()
+ {
+ using (GraphicsPath gpi = new GraphicsPath())
+ using (GraphicsPath gpf = new GraphicsPath())
+ {
+ gpi.AddArc(new Rectangle(1, 1, 2, 2), Pi4, Pi4);
+ AssertArc(gpi);
+
+ gpf.AddArc(new RectangleF(1, 1, 2, 2), Pi4, Pi4);
+ AssertArc(gpf);
+ }
+ }
+
+ [ConditionalTheory(nameof(PlatformDetection) + "." + nameof(PlatformDetection.IsNotWindowsNanoServer))]
+ [InlineData(0, 0)]
+ [InlineData(1, 0)]
+ [InlineData(0, 1)]
+ public void AddArc_ZeroWidthHeight_ThrowsArgumentException(int width, int height)
+ {
+ using (GraphicsPath gp = new GraphicsPath())
+ {
+ AssertExtensions.Throws<ArgumentException>(null, () => gp.AddArc(1, 1, width, height, Pi4, Pi4));
+ AssertExtensions.Throws<ArgumentException>(null, () => gp.AddArc(1.0f, 1.0f, (float)width, (float)height, Pi4, Pi4));
+ }
+ }
+
+ [ConditionalFact(nameof(PlatformDetection) + "." + nameof(PlatformDetection.IsNotWindowsNanoServer))]
+ public void AddBezier_Points_Success()
+ {
+ using (GraphicsPath gpi = new GraphicsPath())
+ using (GraphicsPath gpf = new GraphicsPath())
+ {
+ gpi.AddBezier(new Point(1, 1), new Point(2, 2), new Point(3, 3), new Point(4, 4));
+ // AssertBezier() method expects added Bezier with points (1, 1), (2, 2), (3, 3), (4, 4), here and below.
+ AssertBezier(gpi);
+
+ gpf.AddBezier(new PointF(1, 1), new PointF(2, 2), new PointF(3, 3), new PointF(4, 4));
+ AssertBezier(gpf);
+ }
+ }
+
+ [ConditionalFact(nameof(PlatformDetection) + "." + nameof(PlatformDetection.IsNotWindowsNanoServer))]
+ public void AddBezier_SamePoints_Success()
+ {
+ using (GraphicsPath gp = new GraphicsPath())
+ using (GraphicsPath gpf = new GraphicsPath())
+ {
+ gp.AddBezier(new Point(0, 0), new Point(0, 0), new Point(0, 0), new Point(0, 0));
+ Assert.Equal(4, gp.PointCount);
+ Assert.Equal(new byte[] { 0, 3, 3, 3 }, gp.PathTypes);
+
+ gp.AddBezier(new Point(0, 0), new Point(0, 0), new Point(0, 0), new Point(0, 0));
+ Assert.Equal(7, gp.PointCount);
+ Assert.Equal(new byte[] { 0, 3, 3, 3, 3, 3, 3 }, gp.PathTypes);
+
+ gpf.AddBezier(new PointF(0, 0), new PointF(0, 0), new PointF(0, 0), new PointF(0, 0));
+ Assert.Equal(4, gpf.PointCount);
+ Assert.Equal(new byte[] { 0, 3, 3, 3 }, gpf.PathTypes);
+
+ gpf.AddBezier(new PointF(0, 0), new PointF(0, 0), new PointF(0, 0), new PointF(0, 0));
+ Assert.Equal(7, gpf.PointCount);
+ Assert.Equal(new byte[] { 0, 3, 3, 3, 3, 3, 3 }, gpf.PathTypes);
+ }
+ }
+
+ [ConditionalFact(nameof(PlatformDetection) + "." + nameof(PlatformDetection.IsNotWindowsNanoServer))]
+ public void AddBezier_Values_Success()
+ {
+ using (GraphicsPath gpi = new GraphicsPath())
+ using (GraphicsPath gpf = new GraphicsPath())
+ {
+ gpi.AddBezier(1, 1, 2, 2, 3, 3, 4, 4);
+ AssertBezier(gpi);
+
+ gpf.AddBezier(1f, 1f, 2f, 2f, 3f, 3f, 4f, 4f);
+ AssertBezier(gpf);
+ }
+ }
+
+ [ConditionalFact(nameof(PlatformDetection) + "." + nameof(PlatformDetection.IsNotWindowsNanoServer))]
+ public void AddBeziers_Points_Success()
+ {
+ PointF[] points = new PointF[]
+ {
+ new PointF(1, 1), new PointF(2, 2), new PointF(3, 3), new PointF(4, 4)
+ };
+
+ using (GraphicsPath gpf = new GraphicsPath())
+ {
+ gpf.AddBeziers(points);
+ AssertBezier(gpf);
+ }
+ }
+
+ [ConditionalFact(nameof(PlatformDetection) + "." + nameof(PlatformDetection.IsNotWindowsNanoServer))]
+ public void AddBeziers_PointsNull_ThrowsArgumentNullException()
+ {
+ using (GraphicsPath gp = new GraphicsPath())
+ {
+ AssertExtensions.Throws<ArgumentNullException>("points", () => gp.AddBeziers((PointF[])null));
+ AssertExtensions.Throws<ArgumentNullException>("points", () => gp.AddBeziers((Point[])null));
+ }
+ }
+
+ private static IEnumerable<object[]> AddBeziers_InvalidFloatPointsLength_TestData()
+ {
+ yield return new object[] { new PointF[0] };
+ yield return new object[] { new PointF[1] { new PointF(1f, 1f) } };
+ yield return new object[] { new PointF[2] { new PointF(1f, 1f), new PointF(2f, 2f) } };
+ yield return new object[] { new PointF[3] { new PointF(1f, 1f), new PointF(2f, 2f), new PointF(3f, 3f) } };
+ }
+
+ [ConditionalTheory(nameof(PlatformDetection) + "." + nameof(PlatformDetection.IsNotWindowsNanoServer))]
+ [MemberData(nameof(AddBeziers_InvalidFloatPointsLength_TestData))]
+ public void AddBeziers_InvalidFloatPointsLength_ThrowsArgumentException(PointF[] points)
+ {
+ using (GraphicsPath gp = new GraphicsPath())
+ {
+ AssertExtensions.Throws<ArgumentException>(null, () => gp.AddBeziers(points));
+ }
+ }
+
+
+ [ConditionalFact(nameof(PlatformDetection) + "." + nameof(PlatformDetection.IsNotWindowsNanoServer))]
+ public void AddCurve_TwoPoints_Success()
+ {
+ Point[] intPoints = new Point[] { new Point(1, 1), new Point(2, 2) };
+ PointF[] floatPoints = new PointF[] { new PointF(1, 1), new PointF(2, 2) };
+
+ using (GraphicsPath gpi = new GraphicsPath())
+ using (GraphicsPath gpf = new GraphicsPath())
+ {
+ gpf.AddCurve(floatPoints);
+ // AssertCurve() method expects added Curve with points (1, 1), (2, 2), here and below.
+ AssertCurve(gpf);
+
+ gpi.AddCurve(intPoints);
+ AssertCurve(gpi);
+ }
+ }
+
+ [ConditionalFact(nameof(PlatformDetection) + "." + nameof(PlatformDetection.IsNotWindowsNanoServer))]
+ public void AddCurve_TwoPointsWithTension_Success()
+ {
+ Point[] intPoints = new Point[] { new Point(1, 1), new Point(2, 2) };
+ PointF[] floatPoints = new PointF[] { new PointF(1, 1), new PointF(2, 2) };
+
+ using (GraphicsPath gpi = new GraphicsPath())
+ using (GraphicsPath gpf = new GraphicsPath())
+ {
+ gpi.AddCurve(intPoints, 0.5f);
+ AssertCurve(gpi);
+
+ gpf.AddCurve(floatPoints, 0.5f);
+ AssertCurve(gpf);
+ }
+ }
+
+ [ConditionalFact(nameof(PlatformDetection) + "." + nameof(PlatformDetection.IsNotWindowsNanoServer))]
+ public void AddCurve_SamePoints_Success()
+ {
+ Point[] intPoints = new Point[] { new Point(1, 1), new Point(1, 1) };
+ PointF[] floatPoints = new PointF[] { new PointF(1, 1), new PointF(1, 1) };
+
+ using (GraphicsPath gpi = new GraphicsPath())
+ using (GraphicsPath gpf = new GraphicsPath())
+ {
+ gpi.AddCurve(intPoints);
+ Assert.Equal(4, gpi.PointCount);
+ gpi.AddCurve(intPoints);
+ Assert.Equal(7, gpi.PointCount);
+
+ gpf.AddCurve(floatPoints);
+ Assert.Equal(4, gpf.PointCount);
+ gpf.AddCurve(floatPoints);
+ Assert.Equal(7, gpf.PointCount);
+ }
+ }
+
+ [ConditionalFact(nameof(PlatformDetection) + "." + nameof(PlatformDetection.IsNotWindowsNanoServer))]
+ public void AddCurve_LargeTension_Success()
+ {
+ Point[] intPoints = new Point[] { new Point(1, 1), new Point(2, 2) };
+ PointF[] floatPoints = new PointF[] { new PointF(1, 1), new PointF(2, 2) };
+
+ using (GraphicsPath gpi = new GraphicsPath())
+ using (GraphicsPath gpf = new GraphicsPath())
+ {
+ gpi.AddCurve(intPoints, float.MaxValue);
+ Assert.Equal(4, gpi.PointCount);
+
+ gpf.AddCurve(floatPoints, float.MaxValue);
+ Assert.Equal(4, gpf.PointCount);
+ }
+ }
+
+ [ConditionalFact(nameof(PlatformDetection) + "." + nameof(PlatformDetection.IsNotWindowsNanoServer))]
+ public void AddCurve_Success()
+ {
+ PointF[] points = new PointF[]
+ {
+ new PointF (37f, 185f),
+ new PointF (99f, 185f),
+ new PointF (161f, 159f),
+ new PointF (223f, 185f),
+ new PointF (285f, 54f),
+ };
+
+ PointF[] expectedPoints = new PointF[]
+ {
+ new PointF (37f, 185f),
+ new PointF (47.33333f, 185f),
+ new PointF (78.3333f, 189.3333f),
+ new PointF (99f, 185f),
+ new PointF (119.6667f, 180.6667f),
+ new PointF (140.3333f, 159f),
+ new PointF (161f, 159f),
+ new PointF (181.6667f, 159f),
+ new PointF (202.3333f, 202.5f),
+ new PointF (223f, 185f),
+ new PointF (243.6667f, 167.5f),
+ new PointF (274.6667f, 75.8333f),
+ new PointF (285f, 54f),
+ };
+
+ byte[] expectedTypes = new byte[] { 0, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3 };
+ int[] pointsCount = { 4, 7, 10, 13 };
+ using (GraphicsPath gp = new GraphicsPath())
+ {
+ for (int i = 0; i < points.Length - 1; i++)
+ {
+ gp.AddCurve(points, i, 1, 0.5f);
+ Assert.Equal(pointsCount[i], gp.PointCount);
+ }
+
+ AssertPointsSequenceEqual(expectedPoints, gp.PathPoints, Delta);
+ Assert.Equal(expectedTypes, gp.PathTypes);
+ }
+ }
+
+ [ConditionalFact(nameof(PlatformDetection) + "." + nameof(PlatformDetection.IsNotWindowsNanoServer))]
+ public void AddCurve_PointsNull_ThrowsArgumentNullException()
+ {
+ using (GraphicsPath gp = new GraphicsPath())
+ {
+ AssertExtensions.Throws<ArgumentNullException>("points", () => gp.AddCurve((PointF[])null));
+ AssertExtensions.Throws<ArgumentNullException>("points", () => gp.AddCurve((Point[])null));
+ }
+ }
+
+ private static IEnumerable<object[]> AddCurve_InvalidFloatPointsLength_TestData()
+ {
+ yield return new object[] { new PointF[0] };
+ yield return new object[] { new PointF[1] { new PointF(1f, 1f) } };
+ }
+
+ [ConditionalTheory(nameof(PlatformDetection) + "." + nameof(PlatformDetection.IsNotWindowsNanoServer))]
+ [MemberData(nameof(AddCurve_InvalidFloatPointsLength_TestData))]
+ public void AddCurve_InvalidFloatPointsLength_ThrowsArgumentException(PointF[] points)
+ {
+ using (GraphicsPath gp = new GraphicsPath())
+ {
+ AssertExtensions.Throws<ArgumentException>(null, () => gp.AddCurve(points));
+ AssertExtensions.Throws<ArgumentException>(null, () => gp.AddCurve(points, 0, 2, 0.5f));
+ }
+ }
+
+ private static IEnumerable<object[]> AddCurve_InvalidPointsLength_TestData()
+ {
+ yield return new object[] { new Point[0] };
+ yield return new object[] { new Point[1] { new Point(1, 1) } };
+ }
+
+ [ConditionalTheory(nameof(PlatformDetection) + "." + nameof(PlatformDetection.IsNotWindowsNanoServer))]
+ [MemberData(nameof(AddCurve_InvalidPointsLength_TestData))]
+ public void AddCurve_InvalidPointsLength_ThrowsArgumentException(Point[] points)
+ {
+ using (GraphicsPath gp = new GraphicsPath())
+ {
+ AssertExtensions.Throws<ArgumentException>(null, () => gp.AddCurve(points));
+ AssertExtensions.Throws<ArgumentException>(null, () => gp.AddCurve(points, 0, 2, 0.5f));
+ }
+ }
+
+ private static IEnumerable<object[]> AddCurve_InvalidSegment_TestData()
+ {
+ yield return new object[] { 0 };
+ yield return new object[] { -1 };
+ }
+
+ [ConditionalTheory(nameof(PlatformDetection) + "." + nameof(PlatformDetection.IsNotWindowsNanoServer))]
+ [MemberData(nameof(AddCurve_InvalidSegment_TestData))]
+ public void AddCurve_InvalidSegment_ThrowsArgumentException(int segment)
+ {
+ using (GraphicsPath gp = new GraphicsPath())
+ {
+ AssertExtensions.Throws<ArgumentException>(null, () => gp.AddCurve(
+ new PointF[2] { new PointF(1f, 1f), new PointF(2f, 2f) }, 0, segment, 0.5f));
+
+ AssertExtensions.Throws<ArgumentException>(null, () => gp.AddCurve(
+ new Point[2] { new Point(1, 1), new Point(2, 2) }, 0, segment, 0.5f));
+ }
+ }
+
+ [ConditionalFact(nameof(PlatformDetection) + "." + nameof(PlatformDetection.IsNotWindowsNanoServer))]
+ public void AddCurve_OffsetTooLarge_ThrowsArgumentException()
+ {
+ using (GraphicsPath gp = new GraphicsPath())
+ {
+ AssertExtensions.Throws<ArgumentException>(null, () => gp.AddCurve(
+ new PointF[3] { new PointF(1f, 1f), new PointF(0f, 20f), new PointF(20f, 0f) }, 1, 2, 0.5f));
+
+ AssertExtensions.Throws<ArgumentException>(null, () => gp.AddCurve(
+ new Point[3] { new Point(1, 1), new Point(0, 20), new Point(20, 0) }, 1, 2, 0.5f));
+ }
+ }
+
+ [ConditionalFact(nameof(PlatformDetection) + "." + nameof(PlatformDetection.IsNotWindowsNanoServer))]
+ public void AddClosedCurve_Points_Success()
+ {
+ using (GraphicsPath gpi = new GraphicsPath())
+ using (GraphicsPath gpf = new GraphicsPath())
+ {
+ gpi.AddClosedCurve(new Point[3] { new Point(1, 1), new Point(2, 2), new Point(3, 3) });
+ // AssertClosedCurve() method expects added ClosedCurve with points (1, 1), (2, 2), (3, 3), here and below.
+ AssertClosedCurve(gpi);
+
+ gpf.AddClosedCurve(new PointF[3] { new PointF(1, 1), new PointF(2, 2), new PointF(3, 3) });
+ AssertClosedCurve(gpf);
+ }
+ }
+
+ [ConditionalFact(nameof(PlatformDetection) + "." + nameof(PlatformDetection.IsNotWindowsNanoServer))]
+ public void AddClosedCurve_SamePoints_Success()
+ {
+ using (GraphicsPath gpi = new GraphicsPath())
+ using (GraphicsPath gpf = new GraphicsPath())
+ {
+ gpi.AddClosedCurve(new Point[3] { new Point(1, 1), new Point(1, 1), new Point(1, 1) });
+ Assert.Equal(10, gpi.PointCount);
+ gpi.AddClosedCurve(new Point[3] { new Point(1, 1), new Point(1, 1), new Point(1, 1) });
+ Assert.Equal(20, gpi.PointCount);
+
+ gpf.AddClosedCurve(new PointF[3] { new PointF(1, 1), new PointF(1, 1), new PointF(1, 1) });
+ Assert.Equal(10, gpf.PointCount);
+ gpf.AddClosedCurve(new PointF[3] { new PointF(1, 1), new PointF(1, 1), new PointF(1, 1) });
+ Assert.Equal(20, gpf.PointCount);
+ }
+ }
+
+ [ConditionalFact(nameof(PlatformDetection) + "." + nameof(PlatformDetection.IsNotWindowsNanoServer))]
+ public void AddClosedCurve_Tension_Success()
+ {
+ using (GraphicsPath gpi = new GraphicsPath())
+ using (GraphicsPath gpf = new GraphicsPath())
+ {
+ gpi.AddClosedCurve(new Point[3] { new Point(1, 1), new Point(2, 2), new Point(3, 3) }, 0.5f);
+ AssertClosedCurve(gpi);
+
+ gpf.AddClosedCurve(new PointF[3] { new PointF(1, 1), new PointF(2, 2), new PointF(3, 3) }, 0.5f);
+ AssertClosedCurve(gpf);
+ }
+ }
+
+ [ConditionalFact(nameof(PlatformDetection) + "." + nameof(PlatformDetection.IsNotWindowsNanoServer))]
+ public void AddClosedCurve_PointsNull_ThrowsArgumentNullException()
+ {
+ using (GraphicsPath gp = new GraphicsPath())
+ {
+ AssertExtensions.Throws<ArgumentNullException>("points", () => gp.AddClosedCurve((PointF[])null));
+ AssertExtensions.Throws<ArgumentNullException>("points", () => gp.AddClosedCurve((Point[])null));
+ }
+ }
+
+ private static IEnumerable<object[]> AddClosedCurve_InvalidPointsLength_TestData()
+ {
+ yield return new object[] { new Point[0] };
+ yield return new object[] { new Point[1] { new Point(1, 1) } };
+ yield return new object[] { new Point[2] { new Point(1, 1), new Point(2, 2) } };
+ }
+
+ [ConditionalTheory(nameof(PlatformDetection) + "." + nameof(PlatformDetection.IsNotWindowsNanoServer))]
+ [MemberData(nameof(AddCurve_InvalidPointsLength_TestData))]
+ public void AddClosedCurve_InvalidPointsLength_ThrowsArgumentException(Point[] points)
+ {
+ using (GraphicsPath gp = new GraphicsPath())
+ {
+ AssertExtensions.Throws<ArgumentException>(null, () => gp.AddClosedCurve(points));
+ }
+ }
+
+ private static IEnumerable<object[]> AddClosedCurve_InvalidFloatPointsLength_TestData()
+ {
+ yield return new object[] { new PointF[0] };
+ yield return new object[] { new PointF[1] { new PointF(1f, 1f) } };
+ yield return new object[] { new PointF[2] { new PointF(1f, 1f), new PointF(2f, 2f) } };
+ }
+
+ [ConditionalTheory(nameof(PlatformDetection) + "." + nameof(PlatformDetection.IsNotWindowsNanoServer))]
+ [MemberData(nameof(AddClosedCurve_InvalidFloatPointsLength_TestData))]
+ public void AddClosedCurve_InvalidFloatPointsLength_ThrowsArgumentException(PointF[] points)
+ {
+ using (GraphicsPath gp = new GraphicsPath())
+ {
+ AssertExtensions.Throws<ArgumentException>(null, () => gp.AddClosedCurve(points));
+ }
+ }
+
+ [ConditionalFact(nameof(PlatformDetection) + "." + nameof(PlatformDetection.IsNotWindowsNanoServer))]
+ public void AddRectangle_Success()
+ {
+ using (GraphicsPath gpi = new GraphicsPath())
+ using (GraphicsPath gpf = new GraphicsPath())
+ {
+ gpi.AddRectangle(new Rectangle(1, 1, 2, 2));
+ // AssertRectangle() method expects added Rectangle with parameters x=1, y=1, width=2, height=2, here and below.
+ AssertRectangle(gpi);
+
+ gpf.AddRectangle(new RectangleF(1, 1, 2, 2));
+ AssertRectangle(gpf);
+ }
+ }
+
+ [ConditionalFact(nameof(PlatformDetection) + "." + nameof(PlatformDetection.IsNotWindowsNanoServer))]
+ public void AddRectangle_SameRectangles_Success()
+ {
+ using (GraphicsPath gpi = new GraphicsPath())
+ using (GraphicsPath gpf = new GraphicsPath())
+ {
+ gpi.AddRectangle(new Rectangle(1, 1, 1, 1));
+ Assert.Equal(4, gpi.PointCount);
+ Assert.Equal(new byte[] { 0, 1, 1, 129 }, gpi.PathTypes);
+
+ PointF endI = gpi.PathPoints[3];
+
+ gpi.AddRectangle(new Rectangle((int)endI.X, (int)endI.Y, 1, 1));
+ Assert.Equal(8, gpi.PointCount);
+ Assert.Equal(new byte[] { 0, 1, 1, 129, 0, 1, 1, 129 }, gpi.PathTypes);
+
+ gpf.AddRectangle(new RectangleF(1, 1, 1, 1));
+ Assert.Equal(4, gpf.PointCount);
+ Assert.Equal(new byte[] { 0, 1, 1, 129 }, gpf.PathTypes);
+ Assert.Equal(129, gpf.PathTypes[3]);
+
+ PointF endF = gpf.PathPoints[3];
+
+ gpf.AddRectangle(new RectangleF(endF.X, endF.Y, 1, 1));
+ Assert.Equal(8, gpf.PointCount);
+ Assert.Equal(new byte[] { 0, 1, 1, 129, 0, 1, 1, 129 }, gpf.PathTypes);
+ }
+ }
+
+ [ConditionalTheory(nameof(PlatformDetection) + "." + nameof(PlatformDetection.IsNotWindowsNanoServer))]
+ [InlineData(0, 0)]
+ [InlineData(3, 0)]
+ [InlineData(0, 4)]
+ public void AddRectangle_ZeroWidthHeight_Success(int width, int height)
+ {
+ using (GraphicsPath gpi = new GraphicsPath())
+ using (GraphicsPath gpf = new GraphicsPath())
+ {
+ gpi.AddRectangle(new Rectangle(1, 2, width, height));
+ Assert.Equal(0, gpi.PathData.Points.Length);
+
+ gpf.AddRectangle(new RectangleF(1f, 2f, (float)width, (float)height));
+ Assert.Equal(0, gpf.PathData.Points.Length);
+ }
+ }
+
+ [ConditionalFact(nameof(PlatformDetection) + "." + nameof(PlatformDetection.IsNotWindowsNanoServer))]
+ public void AddRectangles_Success()
+ {
+ Rectangle[] rectInt = new Rectangle[] { new Rectangle(1, 1, 2, 2), new Rectangle(3, 3, 4, 4) };
+ RectangleF[] rectFloat = new RectangleF[] { new RectangleF(1, 1, 2, 2), new RectangleF(3, 3, 4, 4) };
+
+ using (GraphicsPath gpi = new GraphicsPath())
+ using (GraphicsPath gpf = new GraphicsPath())
+ {
+ gpi.AddRectangles(rectInt);
+ Assert.Equal(8, gpi.PathPoints.Length);
+ Assert.Equal(8, gpi.PathTypes.Length);
+ Assert.Equal(8, gpi.PathData.Points.Length);
+
+ gpf.AddRectangles(rectFloat);
+ Assert.Equal(8, gpf.PathPoints.Length);
+ Assert.Equal(8, gpf.PathTypes.Length);
+ Assert.Equal(8, gpf.PathData.Points.Length);
+ }
+ }
+
+ [ConditionalFact(nameof(PlatformDetection) + "." + nameof(PlatformDetection.IsNotWindowsNanoServer))]
+ public void AddRectangles_SamePoints_Success()
+ {
+ Rectangle[] rectInt = new Rectangle[]
+ {
+ new Rectangle(1, 1, 0, 0),
+ new Rectangle(1, 1, 2, 2),
+ new Rectangle(1, 1, 2, 2)
+ };
+
+ RectangleF[] rectFloat = new RectangleF[]
+ {
+ new RectangleF(1, 1, 0f, 0f),
+ new RectangleF(1, 1, 2, 2),
+ new RectangleF(1, 1, 2, 2)
+ };
+
+ using (GraphicsPath gpi = new GraphicsPath())
+ using (GraphicsPath gpf = new GraphicsPath())
+ {
+ gpi.AddRectangles(rectInt);
+ Assert.Equal(8, gpi.PathPoints.Length);
+ Assert.Equal(8, gpi.PathTypes.Length);
+ Assert.Equal(8, gpi.PathData.Points.Length);
+
+ gpf.AddRectangles(rectFloat);
+ Assert.Equal(8, gpf.PathPoints.Length);
+ Assert.Equal(8, gpf.PathTypes.Length);
+ Assert.Equal(8, gpf.PathData.Points.Length);
+ }
+ }
+
+ [ConditionalFact(nameof(PlatformDetection) + "." + nameof(PlatformDetection.IsNotWindowsNanoServer))]
+ public void AddRectangles_RectangleNull_ThrowsArgumentNullException()
+ {
+ using (GraphicsPath gp = new GraphicsPath())
+ {
+ AssertExtensions.Throws<ArgumentNullException>("rects", () => gp.AddRectangles((RectangleF[])null));
+ AssertExtensions.Throws<ArgumentNullException>("rects", () => gp.AddRectangles((Rectangle[])null));
+ }
+ }
+
+ [ConditionalFact(nameof(PlatformDetection) + "." + nameof(PlatformDetection.IsNotWindowsNanoServer))]
+ public void AddEllipse_Rectangle_Success()
+ {
+ using (GraphicsPath gpi = new GraphicsPath())
+ using (GraphicsPath gpf = new GraphicsPath())
+ {
+ gpi.AddEllipse(new Rectangle(1, 1, 2, 2));
+ // AssertEllipse() method expects added Ellipse with parameters x=1, y=1, width=2, height=2, here and below.
+ AssertEllipse(gpi);
+
+ gpf.AddEllipse(new RectangleF(1, 1, 2, 2));
+ AssertEllipse(gpf);
+ }
+ }
+
+ [ConditionalFact(nameof(PlatformDetection) + "." + nameof(PlatformDetection.IsNotWindowsNanoServer))]
+ public void AddEllipse_Values_Success()
+ {
+ using (GraphicsPath gpi = new GraphicsPath())
+ using (GraphicsPath gpf = new GraphicsPath())
+ {
+ gpi.AddEllipse(1, 1, 2, 2);
+ AssertEllipse(gpi);
+
+ gpf.AddEllipse(1f, 1f, 2f, 2f);
+ AssertEllipse(gpf);
+ }
+ }
+
+ [ConditionalTheory(nameof(PlatformDetection) + "." + nameof(PlatformDetection.IsNotWindowsNanoServer))]
+ [InlineData(0, 0)]
+ [InlineData(2, 0)]
+ [InlineData(0, 2)]
+ public void AddEllipse_ZeroWidthHeight_Success(int width, int height)
+ {
+ using (GraphicsPath gpi = new GraphicsPath())
+ using (GraphicsPath gpf = new GraphicsPath())
+ {
+ gpi.AddEllipse(1, 1, width, height);
+ Assert.Equal(13, gpi.PathData.Points.Length);
+
+ gpf.AddEllipse(1f, 2f, (float)width, (float)height);
+ Assert.Equal(13, gpf.PathData.Points.Length);
+ }
+ }
+
+ [ConditionalFact(nameof(PlatformDetection) + "." + nameof(PlatformDetection.IsNotWindowsNanoServer))]
+ public void AddPie_Rectangle_Success()
+ {
+ using (GraphicsPath gpi = new GraphicsPath())
+ {
+ gpi.AddPie(new Rectangle(1, 1, 2, 2), Pi4, Pi4);
+ // AssertPie() method expects added Pie with parameters
+ // x=1, y=1, width=2, height=2, startAngle=Pi4, seewpAngle=Pi4 here and below.
+ AssertPie(gpi);
+ }
+ }
+
+ [ConditionalFact(nameof(PlatformDetection) + "." + nameof(PlatformDetection.IsNotWindowsNanoServer))]
+ public void AddPie_Values_Success()
+ {
+ using (GraphicsPath gpi = new GraphicsPath())
+ using (GraphicsPath gpf = new GraphicsPath())
+ {
+ gpi.AddPie(1, 1, 2, 2, Pi4, Pi4);
+ AssertPie(gpi);
+
+ gpf.AddPie(1f, 1f, 2f, 2f, Pi4, Pi4);
+ AssertPie(gpf);
+ }
+ }
+
+ [ConditionalTheory(nameof(PlatformDetection) + "." + nameof(PlatformDetection.IsNotWindowsNanoServer))]
+ [InlineData(0, 0)]
+ [InlineData(2, 0)]
+ [InlineData(0, 2)]
+ public void AddPie_ZeroWidthHeight_ThrowsArgumentException(int width, int height)
+ {
+ using (GraphicsPath gp = new GraphicsPath())
+ {
+ AssertExtensions.Throws<ArgumentException>(null, () => gp.AddPie(1, 1, height, width, Pi4, Pi4));
+ AssertExtensions.Throws<ArgumentException>(null, () => gp.AddPie(1f, 1f, height, width, Pi4, Pi4));
+ AssertExtensions.Throws<ArgumentException>(null, () => gp.AddPie(new Rectangle(1, 1, height, width), Pi4, Pi4));
+ }
+ }
+
+ [ConditionalFact(nameof(PlatformDetection) + "." + nameof(PlatformDetection.IsNotWindowsNanoServer))]
+ public void AddPolygon_Points_Success()
+ {
+ using (GraphicsPath gpi = new GraphicsPath())
+ using (GraphicsPath gpf = new GraphicsPath())
+ {
+ gpi.AddPolygon(new Point[3] { new Point(1, 1), new Point(2, 2), new Point(3, 3) });
+ // AssertPolygon() method expects added Polygon with points (1, 1), (2, 2), (3, 3), here and below.
+ AssertPolygon(gpi);
+
+ gpf.AddPolygon(new PointF[3] { new PointF(1, 1), new PointF(2, 2), new PointF(3, 3) });
+ AssertPolygon(gpf);
+ }
+ }
+
+ [ConditionalFact(nameof(PlatformDetection) + "." + nameof(PlatformDetection.IsNotWindowsNanoServer))]
+ public void AddPolygon_SamePoints_Success()
+ {
+ using (GraphicsPath gpi = new GraphicsPath())
+ using (GraphicsPath gpf = new GraphicsPath())
+ {
+ gpi.AddPolygon(new Point[3] { new Point(1, 1), new Point(2, 2), new Point(3, 3) });
+ Assert.Equal(3, gpi.PointCount);
+ Assert.Equal(new byte[] { 0, 1, 129 }, gpi.PathTypes);
+
+ gpi.AddPolygon(new Point[3] { new Point(1, 1), new Point(2, 2), new Point(3, 3) });
+ Assert.Equal(6, gpi.PointCount);
+ Assert.Equal(new byte[] { 0, 1, 129, 0, 1, 129 }, gpi.PathTypes);
+
+ gpi.AddPolygon(new Point[3] { new Point(1, 1), new Point(2, 2), new Point(3, 3) });
+ Assert.Equal(9, gpi.PointCount);
+ Assert.Equal(new byte[] { 0, 1, 129, 0, 1, 129, 0, 1, 129 }, gpi.PathTypes);
+
+ gpi.AddPolygon(new Point[3] { new Point(1, 1), new Point(2, 2), new Point(3, 3) });
+ Assert.Equal(12, gpi.PointCount);
+ Assert.Equal(new byte[] { 0, 1, 129, 0, 1, 129, 0, 1, 129, 0, 1, 129 }, gpi.PathTypes);
+
+ gpf.AddPolygon(new PointF[3] { new PointF(1, 1), new PointF(2, 2), new PointF(3, 3) });
+ Assert.Equal(3, gpf.PointCount);
+ Assert.Equal(new byte[] { 0, 1, 129 }, gpf.PathTypes);
+
+ gpf.AddPolygon(new PointF[3] { new PointF(1, 1), new PointF(2, 2), new PointF(3, 3) });
+ Assert.Equal(6, gpf.PointCount);
+ Assert.Equal(new byte[] { 0, 1, 129, 0, 1, 129 }, gpf.PathTypes);
+
+ gpf.AddPolygon(new PointF[3] { new PointF(1, 1), new PointF(2, 2), new PointF(3, 3) });
+ Assert.Equal(9, gpf.PointCount);
+ Assert.Equal(new byte[] { 0, 1, 129, 0, 1, 129, 0, 1, 129 }, gpf.PathTypes);
+
+ gpf.AddPolygon(new PointF[3] { new PointF(1, 1), new PointF(2, 2), new PointF(3, 3) });
+ Assert.Equal(12, gpf.PointCount);
+ Assert.Equal(new byte[] { 0, 1, 129, 0, 1, 129, 0, 1, 129, 0, 1, 129 }, gpf.PathTypes);
+ }
+ }
+
+ [ConditionalFact(nameof(PlatformDetection) + "." + nameof(PlatformDetection.IsNotWindowsNanoServer))]
+ public void AddPolygon_PointsNull_ThrowsArgumentNullException()
+ {
+ using (GraphicsPath gp = new GraphicsPath())
+ {
+ AssertExtensions.Throws<ArgumentNullException>("points", () => new GraphicsPath().AddPolygon((Point[])null));
+ AssertExtensions.Throws<ArgumentNullException>("points", () => new GraphicsPath().AddPolygon((PointF[])null));
+ }
+ }
+
+ private static IEnumerable<object[]> AddPolygon_InvalidFloadPointsLength_TestData()
+ {
+ yield return new object[] { new PointF[0] };
+ yield return new object[] { new PointF[1] { new PointF(1f, 1f) } };
+ yield return new object[] { new PointF[2] { new PointF(1f, 1f), new PointF(2f, 2f) } };
+ }
+
+ [ConditionalTheory(nameof(PlatformDetection) + "." + nameof(PlatformDetection.IsNotWindowsNanoServer))]
+ [MemberData(nameof(AddPolygon_InvalidFloadPointsLength_TestData))]
+ public void AddPolygon_InvalidFloadPointsLength_ThrowsArgumentException(PointF[] points)
+ {
+ using (GraphicsPath gp = new GraphicsPath())
+ {
+ AssertExtensions.Throws<ArgumentException>(null, () => gp.AddPolygon(points));
+ }
+ }
+
+ private static IEnumerable<object[]> AddPolygon_InvalidPointsLength_TestData()
+ {
+ yield return new object[] { new Point[0] };
+ yield return new object[] { new Point[1] { new Point(1, 1) } };
+ yield return new object[] { new Point[2] { new Point(1, 1), new Point(2, 2) } };
+ }
+
+ [ConditionalTheory(nameof(PlatformDetection) + "." + nameof(PlatformDetection.IsNotWindowsNanoServer))]
+ [MemberData(nameof(AddPolygon_InvalidPointsLength_TestData))]
+ public void AddPolygon_InvalidPointsLength_ThrowsArgumentException(Point[] points)
+ {
+ using (GraphicsPath gp = new GraphicsPath())
+ {
+ AssertExtensions.Throws<ArgumentException>(null, () => gp.AddPolygon(points));
+ }
+ }
+
+ [ConditionalFact(nameof(PlatformDetection) + "." + nameof(PlatformDetection.IsNotWindowsNanoServer))]
+ public void AddPath_Success()
+ {
+ using (GraphicsPath inner = new GraphicsPath())
+ using (GraphicsPath gp = new GraphicsPath())
+ {
+ inner.AddRectangle(new Rectangle(1, 1, 2, 2));
+ gp.AddPath(inner, true);
+ AssertRectangle(gp);
+ }
+ }
+
+ [ConditionalFact(nameof(PlatformDetection) + "." + nameof(PlatformDetection.IsNotWindowsNanoServer))]
+ public void AddPath_PathNull_ThrowsArgumentNullException()
+ {
+ using (GraphicsPath gp = new GraphicsPath())
+ {
+ AssertExtensions.Throws<ArgumentNullException>("addingPath", () => new GraphicsPath().AddPath(null, false));
+ }
+ }
+
+ [ConditionalFact(nameof(PlatformDetection) + "." + nameof(PlatformDetection.IsNotWindowsNanoServer))]
+ public void AddString_Point_Success()
+ {
+ using (GraphicsPath gpi = new GraphicsPath())
+ using (GraphicsPath gpf = new GraphicsPath())
+ {
+ gpi.AddString("mono", FontFamily.GenericMonospace, 0, 10, new Point(10, 10), StringFormat.GenericDefault);
+ AssertExtensions.GreaterThan(gpi.PointCount, 0);
+
+ gpf.AddString("mono", FontFamily.GenericMonospace, 0, 10, new PointF(10f, 10f), StringFormat.GenericDefault);
+ AssertExtensions.GreaterThan(gpf.PointCount, 0);
+ }
+ }
+
+ [ConditionalFact(nameof(PlatformDetection) + "." + nameof(PlatformDetection.IsNotWindowsNanoServer))]
+ public void AddString_Rectangle_Success()
+ {
+ using (GraphicsPath gpi = new GraphicsPath())
+ using (GraphicsPath gpf = new GraphicsPath())
+ {
+ gpi.AddString("mono", FontFamily.GenericMonospace, 0, 10, new Rectangle(10, 10, 10, 10), StringFormat.GenericDefault);
+ AssertExtensions.GreaterThan(gpi.PointCount, 0);
+
+ gpf.AddString("mono", FontFamily.GenericMonospace, 0, 10, new RectangleF(10f, 10f, 10f, 10f), StringFormat.GenericDefault);
+ AssertExtensions.GreaterThan(gpf.PointCount, 0);
+ }
+ }
+
+ [ConditionalFact(nameof(PlatformDetection) + "." + nameof(PlatformDetection.IsNotWindowsNanoServer))]
+ public void AddString_NegativeSize_Success()
+ {
+ using (GraphicsPath gpi = new GraphicsPath())
+ using (GraphicsPath gpf = new GraphicsPath())
+ {
+ gpi.AddString("mono", FontFamily.GenericMonospace, 0, -10, new Point(10, 10), StringFormat.GenericDefault);
+ AssertExtensions.GreaterThan(gpi.PointCount, 0);
+
+ int gpiLenghtOld = gpi.PathPoints.Length;
+ gpi.AddString("mono", FontFamily.GenericMonospace, 0, -10, new Rectangle(10, 10, 10, 10), StringFormat.GenericDefault);
+ AssertExtensions.GreaterThan(gpi.PointCount, gpiLenghtOld);
+
+ gpf.AddString("mono", FontFamily.GenericMonospace, 0, -10, new PointF(10f, 10f), StringFormat.GenericDefault);
+ AssertExtensions.GreaterThan(gpf.PointCount, 0);
+
+ int pgfLenghtOld = gpf.PathPoints.Length;
+ gpf.AddString("mono", FontFamily.GenericMonospace, 0, -10, new RectangleF(10f, 10f, 10f, 10f), StringFormat.GenericDefault);
+ AssertExtensions.GreaterThan(gpf.PointCount, pgfLenghtOld);
+ }
+ }
+
+ [ConditionalFact(nameof(PlatformDetection) + "." + nameof(PlatformDetection.IsNotWindowsNanoServer))]
+ public void AddString_StringFormat_Success()
+ {
+ using (GraphicsPath gp1 = new GraphicsPath())
+ using (GraphicsPath gp2 = new GraphicsPath())
+ using (GraphicsPath gp3 = new GraphicsPath())
+ {
+ gp1.AddString("mono", FontFamily.GenericMonospace, 0, 10, new RectangleF(10f, 10f, 10f, 10f), null);
+ AssertExtensions.GreaterThan(gp1.PointCount, 0);
+
+ gp2.AddString("mono", FontFamily.GenericMonospace, 0, 10, new RectangleF(10f, 10f, 10f, 10f), StringFormat.GenericDefault);
+ Assert.Equal(gp1.PointCount, gp2.PointCount);
+
+ gp3.AddString("mono", FontFamily.GenericMonospace, 0, 10, new RectangleF(10f, 10f, 10f, 10f), StringFormat.GenericTypographic);
+ Assert.NotEqual(gp1.PointCount, gp3.PointCount);
+ }
+ }
+
+ [ConditionalFact(nameof(PlatformDetection) + "." + nameof(PlatformDetection.IsNotWindowsNanoServer))]
+ public void AddString_EmptyString_Success()
+ {
+ using (GraphicsPath gpi = new GraphicsPath())
+ using (GraphicsPath gpf = new GraphicsPath())
+ {
+ gpi.AddString(string.Empty, FontFamily.GenericMonospace, 0, 10, new Point(10, 10), StringFormat.GenericDefault);
+ Assert.Equal(0, gpi.PointCount);
+
+ gpi.AddString(string.Empty, FontFamily.GenericMonospace, 0, 10, new PointF(10f, 10f), StringFormat.GenericDefault);
+ Assert.Equal(0, gpf.PointCount);
+ }
+ }
+
+ [ConditionalFact(nameof(PlatformDetection) + "." + nameof(PlatformDetection.IsNotWindowsNanoServer))]
+ public void AddString_StringNull_ThrowsNullReferenceException()
+ {
+ using (GraphicsPath gp = new GraphicsPath())
+ {
+ Assert.Throws<NullReferenceException>(() =>
+ gp.AddString(null, FontFamily.GenericMonospace, 0, 10, new Point(10, 10), StringFormat.GenericDefault));
+ Assert.Throws<NullReferenceException>(() =>
+ gp.AddString(null, FontFamily.GenericMonospace, 0, 10, new PointF(10f, 10f), StringFormat.GenericDefault));
+ Assert.Throws<NullReferenceException>(() =>
+ gp.AddString(null, FontFamily.GenericMonospace, 0, 10, new Rectangle(10, 10, 10, 10), StringFormat.GenericDefault));
+ Assert.Throws<NullReferenceException>(() =>
+ gp.AddString(null, FontFamily.GenericMonospace, 0, 10, new RectangleF(10f, 10f, 10f, 10f), StringFormat.GenericDefault));
+ }
+ }
+
+ [ConditionalFact(nameof(PlatformDetection) + "." + nameof(PlatformDetection.IsNotWindowsNanoServer))]
+ public void AddString_FontFamilyNull_ThrowsArgumentException()
+ {
+ using (GraphicsPath gp = new GraphicsPath())
+ {
+ AssertExtensions.Throws<ArgumentException>(null, () =>
+ new GraphicsPath().AddString("mono", null, 0, 10, new Point(10, 10), StringFormat.GenericDefault));
+ }
+ }
+
+ [ConditionalFact(nameof(PlatformDetection) + "." + nameof(PlatformDetection.IsNotWindowsNanoServer))]
+ public void Transform_Success()
+ {
+ using (GraphicsPath gp = new GraphicsPath())
+ using (Matrix matrix = new Matrix(1f, 1f, 2f, 2f, 3f, 3f))
+ {
+ gp.AddRectangle(new Rectangle(1, 1, 2, 2));
+ AssertRectangle(gp);
+ gp.Transform(matrix);
+ Assert.Equal(new float[] { 1f, 1f, 2f, 2f, 3f, 3f }, matrix.Elements);
+ Assert.Equal(new RectangleF(6f, 6f, 6f, 6f), gp.GetBounds());
+ Assert.Equal(new PointF[] { new PointF(6f, 6f), new PointF(8f, 8f), new PointF(12f, 12f), new PointF(10f, 10f) }, gp.PathPoints);
+ Assert.Equal(new byte[] { 0, 1, 1, 129 }, gp.PathTypes);
+ }
+ }
+
+ [ConditionalFact(nameof(PlatformDetection) + "." + nameof(PlatformDetection.IsNotWindowsNanoServer))]
+ public void Transform_PathEmpty_Success()
+ {
+ using (GraphicsPath gp = new GraphicsPath())
+ using (Matrix matrix = new Matrix(1f, 1f, 2f, 2f, 3f, 3f))
+ {
+ gp.Transform(matrix);
+ Assert.Equal(new float[] { 1f, 1f, 2f, 2f, 3f, 3f }, matrix.Elements);
+ AssertEmptyGrahicsPath(gp);
+ }
+ }
+
+ [ConditionalFact(nameof(PlatformDetection) + "." + nameof(PlatformDetection.IsNotWindowsNanoServer))]
+ public void Transform_MatrixNull_ThrowsArgumentNullException()
+ {
+ using (GraphicsPath gp = new GraphicsPath())
+ {
+ AssertExtensions.Throws<ArgumentNullException>("matrix", () => gp.Transform(null));
+ }
+ }
+
+ [ConditionalFact(nameof(PlatformDetection) + "." + nameof(PlatformDetection.IsNotWindowsNanoServer))]
+ public void GetBounds_PathEmpty_ReturnsExpected()
+ {
+ using (GraphicsPath gp = new GraphicsPath())
+ {
+ Assert.Equal(new RectangleF(0f, 0f, 0f, 0f), gp.GetBounds());
+ }
+ }
+
+ [ConditionalFact(nameof(PlatformDetection) + "." + nameof(PlatformDetection.IsNotWindowsNanoServer))]
+ public void GetBounds_Rectangle_ReturnsExpected()
+ {
+ using (GraphicsPath gp = new GraphicsPath())
+ using (Matrix matrix = new Matrix())
+ {
+ RectangleF rectangle = new RectangleF(1f, 1f, 2f, 2f);
+ gp.AddRectangle(rectangle);
+ Assert.Equal(rectangle, gp.GetBounds());
+ Assert.Equal(rectangle, gp.GetBounds(null));
+ Assert.Equal(rectangle, gp.GetBounds(matrix));
+ Assert.Equal(rectangle, gp.GetBounds(null, null));
+ }
+ }
+
+ [ConditionalFact(nameof(PlatformDetection) + "." + nameof(PlatformDetection.IsNotWindowsNanoServer))]
+ public void GetBounds_Pie_ReturnsExpected()
+ {
+ using (GraphicsPath gp = new GraphicsPath())
+ using (Matrix matrix = new Matrix())
+ {
+ Rectangle rectangle = new Rectangle(10, 10, 100, 100);
+ gp.AddPie(rectangle, 30, 45);
+ AssertRectangleEqual(new RectangleF(60f, 60f, 43.3f, 48.3f), gp.GetBounds(), 0.1f);
+ }
+ }
+
+ [ConditionalFact(nameof(PlatformDetection) + "." + nameof(PlatformDetection.IsNotWindowsNanoServer))]
+ public void Flatten_Empty_Success()
+ {
+ using (GraphicsPath gp = new GraphicsPath())
+ using (GraphicsPath clone = Assert.IsType<GraphicsPath>(gp.Clone()))
+ {
+ gp.Flatten();
+ Assert.Equal(gp.PointCount, clone.PointCount);
+ }
+ }
+
+ [ConditionalFact(nameof(PlatformDetection) + "." + nameof(PlatformDetection.IsNotWindowsNanoServer))]
+ public void Flatten_MatrixNull_Success()
+ {
+ using (GraphicsPath gp = new GraphicsPath())
+ using (GraphicsPath clone = Assert.IsType<GraphicsPath>(gp.Clone()))
+ {
+ gp.Flatten(null);
+ Assert.Equal(gp.PointCount, clone.PointCount);
+ }
+ }
+
+ [ConditionalFact(nameof(PlatformDetection) + "." + nameof(PlatformDetection.IsNotWindowsNanoServer))]
+ public void Flatten_MatrixNullFloat_Success()
+ {
+ using (GraphicsPath gp = new GraphicsPath())
+ using (GraphicsPath clone = Assert.IsType<GraphicsPath>(gp.Clone()))
+ {
+ gp.Flatten(null, 1f);
+ Assert.Equal(gp.PointCount, clone.PointCount);
+ }
+ }
+
+ [ConditionalFact(nameof(PlatformDetection) + "." + nameof(PlatformDetection.IsNotWindowsNanoServer))]
+ public void Flatten_Arc_Success()
+ {
+ using (GraphicsPath gp = new GraphicsPath())
+ using (GraphicsPath clone = Assert.IsType<GraphicsPath>(gp.Clone()))
+ {
+ gp.AddArc(0f, 0f, 100f, 100f, 30, 30);
+ gp.Flatten();
+ AssertFlats(gp, clone);
+ }
+ }
+
+ [ConditionalFact(nameof(PlatformDetection) + "." + nameof(PlatformDetection.IsNotWindowsNanoServer))]
+ public void Flatten_Bezier_Success()
+ {
+ using (GraphicsPath gp = new GraphicsPath())
+ using (GraphicsPath clone = Assert.IsType<GraphicsPath>(gp.Clone()))
+ {
+ gp.AddBezier(0, 0, 100, 100, 30, 30, 60, 60);
+ gp.Flatten();
+ AssertFlats(gp, clone);
+ }
+ }
+
+ [ConditionalFact(nameof(PlatformDetection) + "." + nameof(PlatformDetection.IsNotWindowsNanoServer))]
+ public void Flatten_ClosedCurve_Success()
+ {
+ using (GraphicsPath gp = new GraphicsPath())
+ using (GraphicsPath clone = Assert.IsType<GraphicsPath>(gp.Clone()))
+ {
+ gp.AddClosedCurve(new Point[4]
+ {
+ new Point (0, 0), new Point (40, 20),
+ new Point (20, 40), new Point (40, 40)
+ });
+
+ gp.Flatten();
+ AssertFlats(gp, clone);
+ }
+ }
+
+ [ConditionalFact(nameof(PlatformDetection) + "." + nameof(PlatformDetection.IsNotWindowsNanoServer))]
+ public void Flatten_Curve_Success()
+ {
+ using (GraphicsPath gp = new GraphicsPath())
+ using (GraphicsPath clone = Assert.IsType<GraphicsPath>(gp.Clone()))
+ {
+ gp.AddCurve(new Point[4]
+ {
+ new Point (0, 0), new Point (40, 20),
+ new Point (20, 40), new Point (40, 40)
+ });
+
+ gp.Flatten();
+ AssertFlats(gp, clone);
+ }
+ }
+
+ [ConditionalFact(nameof(PlatformDetection) + "." + nameof(PlatformDetection.IsNotWindowsNanoServer))]
+ public void Flatten_Ellipse_Success()
+ {
+ using (GraphicsPath gp = new GraphicsPath())
+ using (GraphicsPath clone = Assert.IsType<GraphicsPath>(gp.Clone()))
+ {
+ gp.AddEllipse(10f, 10f, 100f, 100f);
+ gp.Flatten();
+ AssertFlats(gp, clone);
+ }
+ }
+
+ [ConditionalFact(nameof(PlatformDetection) + "." + nameof(PlatformDetection.IsNotWindowsNanoServer))]
+ public void Flatten_Line_Success()
+ {
+ using (GraphicsPath gp = new GraphicsPath())
+ using (GraphicsPath clone = Assert.IsType<GraphicsPath>(gp.Clone()))
+ {
+ gp.AddLine(10f, 10f, 100f, 100f);
+ gp.Flatten();
+ AssertFlats(gp, clone);
+ }
+ }
+
+ [ConditionalFact(nameof(PlatformDetection) + "." + nameof(PlatformDetection.IsNotWindowsNanoServer))]
+ public void Flatten_Pie_Success()
+ {
+ using (GraphicsPath gp = new GraphicsPath())
+ using (GraphicsPath clone = Assert.IsType<GraphicsPath>(gp.Clone()))
+ {
+ gp.AddPie(0, 0, 100, 100, 30, 30);
+ gp.Flatten();
+ AssertFlats(gp, clone);
+ }
+ }
+
+ [ConditionalFact(nameof(PlatformDetection) + "." + nameof(PlatformDetection.IsNotWindowsNanoServer))]
+ public void Flatten_Polygon_Success()
+ {
+ using (GraphicsPath gp = new GraphicsPath())
+ using (GraphicsPath clone = Assert.IsType<GraphicsPath>(gp.Clone()))
+ {
+ gp.AddPolygon(new Point[4]
+ {
+ new Point (0, 0), new Point (10, 10),
+ new Point (20, 20), new Point (40, 40)
+ });
+
+ gp.Flatten();
+ AssertFlats(gp, clone);
+ }
+ }
+
+ [ConditionalFact(nameof(PlatformDetection) + "." + nameof(PlatformDetection.IsNotWindowsNanoServer))]
+ public void Flatten_Rectangle_Success()
+ {
+ using (GraphicsPath gp = new GraphicsPath())
+ using (GraphicsPath clone = Assert.IsType<GraphicsPath>(gp.Clone()))
+ {
+ gp.AddRectangle(new Rectangle(0, 0, 100, 100));
+ gp.Flatten();
+ AssertFlats(gp, clone);
+ }
+ }
+
+ [ConditionalFact(nameof(PlatformDetection) + "." + nameof(PlatformDetection.IsNotWindowsNanoServer))]
+ public void Warp_DestinationPointsNull_ThrowsArgumentNullException()
+ {
+ using (GraphicsPath gp = new GraphicsPath())
+ {
+ AssertExtensions.Throws<ArgumentNullException>("destPoints", () => gp.Warp(null, new RectangleF()));
+ }
+ }
+
+ [ConditionalFact(nameof(PlatformDetection) + "." + nameof(PlatformDetection.IsNotWindowsNanoServer))]
+ public void Warp_DestinationPointsZero_ThrowsArgumentException()
+ {
+ using (GraphicsPath gp = new GraphicsPath())
+ {
+ AssertExtensions.Throws<ArgumentException>(null, () => new GraphicsPath().Warp(new PointF[0], new RectangleF()));
+ }
+ }
+
+ [ConditionalFact(nameof(PlatformDetection) + "." + nameof(PlatformDetection.IsNotWindowsNanoServer))]
+ public void Warp_PathEmpty_Success()
+ {
+ using (GraphicsPath gp = new GraphicsPath())
+ using (Matrix matrix = new Matrix())
+ {
+ Assert.Equal(0, gp.PointCount);
+ gp.Warp(new PointF[1] { new PointF(0, 0) }, new RectangleF(10, 20, 30, 40), matrix);
+ Assert.Equal(0, gp.PointCount);
+ }
+ }
+
+ [ConditionalFact(nameof(PlatformDetection) + "." + nameof(PlatformDetection.IsNotWindowsNanoServer))]
+ public void Warp_WarpModeInvalid_Success()
+ {
+ using (GraphicsPath gp = new GraphicsPath())
+ using (Matrix matrix = new Matrix())
+ {
+ gp.AddPolygon(new Point[3] { new Point(5, 5), new Point(15, 5), new Point(10, 15) });
+ gp.Warp(new PointF[1] { new PointF(0, 0) }, new RectangleF(10, 20, 30, 40), matrix, (WarpMode)int.MinValue);
+ Assert.Equal(0, gp.PointCount);
+ }
+ }
+
+ [ConditionalFact(nameof(PlatformDetection) + "." + nameof(PlatformDetection.IsNotWindowsNanoServer))]
+ public void Warp_RectangleEmpty_Success()
+ {
+ using (GraphicsPath gp = new GraphicsPath())
+ {
+ gp.AddPolygon(new Point[3] { new Point(5, 5), new Point(15, 5), new Point(10, 15) });
+ gp.Warp(new PointF[1] { new PointF(0, 0) }, new Rectangle(), null);
+ AssertWrapNaN(gp);
+ }
+ }
+
+
+ [ConditionalFact(nameof(PlatformDetection) + "." + nameof(PlatformDetection.IsNotWindowsNanoServer))]
+ public void SetMarkers_EmptyPath_Success()
+ {
+ using (GraphicsPath gp = new GraphicsPath())
+ {
+ gp.SetMarkers();
+ }
+ }
+
+ [ConditionalFact(nameof(PlatformDetection) + "." + nameof(PlatformDetection.IsNotWindowsNanoServer))]
+ public void SetMarkers_Success()
+ {
+ using (GraphicsPath gp = new GraphicsPath())
+ {
+ gp.AddLine(new Point(1, 1), new Point(2, 2));
+ Assert.Equal(1, gp.PathTypes[1]);
+
+ gp.SetMarkers();
+ Assert.Equal(33, gp.PathTypes[1]);
+ }
+ }
+
+ [ConditionalFact(nameof(PlatformDetection) + "." + nameof(PlatformDetection.IsNotWindowsNanoServer))]
+ public void ClearMarkers_Success()
+ {
+ using (GraphicsPath gp = new GraphicsPath())
+ {
+ gp.AddLine(new Point(1, 1), new Point(2, 2));
+ Assert.Equal(1, gp.PathTypes[1]);
+
+ gp.SetMarkers();
+ Assert.Equal(33, gp.PathTypes[1]);
+
+ gp.ClearMarkers();
+ Assert.Equal(1, gp.PathTypes[1]);
+ }
+ }
+
+ [ConditionalFact(nameof(PlatformDetection) + "." + nameof(PlatformDetection.IsNotWindowsNanoServer))]
+ public void ClearMarkers_EmptyPath_Success()
+ {
+ using (GraphicsPath gp = new GraphicsPath())
+ {
+ gp.ClearMarkers();
+ }
+ }
+
+ [ConditionalFact(nameof(PlatformDetection) + "." + nameof(PlatformDetection.IsNotWindowsNanoServer))]
+ public void CloseFigure_Success()
+ {
+ using (GraphicsPath gp = new GraphicsPath())
+ {
+ gp.AddLine(new Point(1, 1), new Point(2, 2));
+ Assert.Equal(1, gp.PathTypes[1]);
+
+ gp.CloseFigure();
+ Assert.Equal(129, gp.PathTypes[1]);
+ }
+ }
+
+ [ConditionalFact(nameof(PlatformDetection) + "." + nameof(PlatformDetection.IsNotWindowsNanoServer))]
+ public void CloseFigure_EmptyPath_Success()
+ {
+ using (GraphicsPath gp = new GraphicsPath())
+ {
+ gp.CloseFigure();
+ }
+ }
+
+ [ConditionalFact(nameof(PlatformDetection) + "." + nameof(PlatformDetection.IsNotWindowsNanoServer))]
+ public void CloseAllFigures_Success()
+ {
+ using (GraphicsPath gp = new GraphicsPath())
+ {
+ gp.AddLine(new Point(1, 1), new Point(2, 2));
+ gp.StartFigure();
+ gp.AddLine(new Point(3, 3), new Point(4, 4));
+ Assert.Equal(1, gp.PathTypes[1]);
+ Assert.Equal(1, gp.PathTypes[3]);
+
+ gp.CloseAllFigures();
+ Assert.Equal(129, gp.PathTypes[1]);
+ Assert.Equal(129, gp.PathTypes[3]);
+ }
+ }
+
+ [ConditionalFact(nameof(PlatformDetection) + "." + nameof(PlatformDetection.IsNotWindowsNanoServer))]
+ public void CloseAllFigures_EmptyPath_Success()
+ {
+ using (GraphicsPath gp = new GraphicsPath())
+ {
+ gp.CloseAllFigures();
+ }
+ }
+
+ [ConditionalFact(nameof(PlatformDetection) + "." + nameof(PlatformDetection.IsNotWindowsNanoServer))]
+ public void StartClose_AddArc()
+ {
+ using (GraphicsPath gp = new GraphicsPath())
+ {
+ gp.AddLine(1, 1, 2, 2);
+ gp.AddArc(10, 10, 100, 100, 90, 180);
+ gp.AddLine(10, 10, 20, 20);
+ byte[] types = gp.PathTypes;
+
+ Assert.Equal(0, types[0]);
+ Assert.Equal(1, types[2]);
+ Assert.Equal(3, types[gp.PointCount - 3]);
+ Assert.Equal(1, types[gp.PointCount - 1]);
+ }
+ }
+
+ [ConditionalFact(nameof(PlatformDetection) + "." + nameof(PlatformDetection.IsNotWindowsNanoServer))]
+ public void StartClose_AddBezier()
+ {
+ using (GraphicsPath gp = new GraphicsPath())
+ {
+ gp.AddLine(1, 1, 2, 2);
+ gp.AddBezier(10, 10, 100, 100, 20, 20, 200, 200);
+ gp.AddLine(10, 10, 20, 20);
+ byte[] types = gp.PathTypes;
+
+ Assert.Equal(0, types[0]);
+ Assert.Equal(1, types[2]);
+ Assert.Equal(3, types[gp.PointCount - 3]);
+ Assert.Equal(1, types[gp.PointCount - 1]);
+ }
+ }
+
+ [ConditionalFact(nameof(PlatformDetection) + "." + nameof(PlatformDetection.IsNotWindowsNanoServer))]
+ public void StartClose_AddBeziers()
+ {
+ using (GraphicsPath gp = new GraphicsPath())
+ {
+ gp.AddLine(1, 1, 2, 2);
+ gp.AddBeziers(new Point[7]
+ {
+ new Point (10, 10), new Point (20, 10), new Point (20, 20),
+ new Point (30, 20), new Point (40, 40), new Point (50, 40),
+ new Point (50, 50)
+ });
+
+ gp.AddLine(10, 10, 20, 20);
+ byte[] types = gp.PathTypes;
+
+ Assert.Equal(0, types[0]);
+ Assert.Equal(1, types[2]);
+ Assert.Equal(3, types[gp.PointCount - 3]);
+ Assert.Equal(1, types[gp.PointCount - 1]);
+ }
+ }
+
+ [ConditionalFact(nameof(PlatformDetection) + "." + nameof(PlatformDetection.IsNotWindowsNanoServer))]
+ public void StartClose_AddClosedCurve()
+ {
+ using (GraphicsPath gp = new GraphicsPath())
+ {
+ gp.AddLine(1, 1, 2, 2);
+ gp.AddClosedCurve(new Point[3] { new Point(1, 1), new Point(2, 2), new Point(3, 3) });
+ gp.AddLine(10, 10, 20, 20);
+ byte[] types = gp.PathTypes;
+
+ Assert.Equal(0, types[0]);
+ Assert.Equal(0, types[2]);
+ Assert.Equal(131, types[gp.PointCount - 3]);
+ Assert.Equal(0, types[gp.PointCount - 2]);
+ Assert.Equal(1, types[gp.PointCount - 1]);
+ }
+ }
+
+ [ConditionalFact(nameof(PlatformDetection) + "." + nameof(PlatformDetection.IsNotWindowsNanoServer))]
+ public void StartClose_AddCurve()
+ {
+ GraphicsPath path = new GraphicsPath();
+ path.AddLine(1, 1, 2, 2);
+ path.AddCurve(new Point[3] { new Point(1, 1), new Point(2, 2), new Point(3, 3) });
+ path.AddLine(10, 10, 20, 20);
+ byte[] types = path.PathTypes;
+
+ Assert.Equal(0, types[0]);
+ Assert.Equal(1, types[2]);
+ Assert.Equal(3, types[path.PointCount - 3]);
+ Assert.Equal(1, types[path.PointCount - 1]);
+ }
+
+ [ConditionalFact(nameof(PlatformDetection) + "." + nameof(PlatformDetection.IsNotWindowsNanoServer))]
+ public void StartClose_AddEllipse()
+ {
+ using (GraphicsPath gp = new GraphicsPath())
+ {
+ gp.AddLine(1, 1, 2, 2);
+ gp.AddEllipse(10, 10, 100, 100);
+ gp.AddLine(10, 10, 20, 20);
+ byte[] types = gp.PathTypes;
+
+ Assert.Equal(0, types[0]);
+ Assert.Equal(0, types[2]);
+ Assert.Equal(131, types[gp.PointCount - 3]);
+ Assert.Equal(0, types[gp.PointCount - 2]);
+ Assert.Equal(1, types[gp.PointCount - 1]);
+ }
+ }
+
+ [ConditionalFact(nameof(PlatformDetection) + "." + nameof(PlatformDetection.IsNotWindowsNanoServer))]
+ public void StartClose_AddLine()
+ {
+ GraphicsPath path = new GraphicsPath();
+ path.AddLine(1, 1, 2, 2);
+ path.AddLine(5, 5, 10, 10);
+ path.AddLine(10, 10, 20, 20);
+ byte[] types = path.PathTypes;
+
+ Assert.Equal(0, types[0]);
+ Assert.Equal(1, types[2]);
+ Assert.Equal(1, types[path.PointCount - 3]);
+ Assert.Equal(1, types[path.PointCount - 1]);
+ }
+
+ [ConditionalFact(nameof(PlatformDetection) + "." + nameof(PlatformDetection.IsNotWindowsNanoServer))]
+ public void StartClose_AddLines()
+ {
+ using (GraphicsPath gp = new GraphicsPath())
+ {
+ gp.AddLine(1, 1, 2, 2);
+ gp.AddLines(new Point[4] { new Point(10, 10), new Point(20, 10), new Point(20, 20), new Point(30, 20) });
+ gp.AddLine(10, 10, 20, 20);
+ byte[] types = gp.PathTypes;
+
+ Assert.Equal(0, types[0]);
+ Assert.Equal(1, types[2]);
+ Assert.Equal(1, types[gp.PointCount - 3]);
+ Assert.Equal(1, types[gp.PointCount - 1]);
+ }
+ }
+
+ [ConditionalFact(nameof(PlatformDetection) + "." + nameof(PlatformDetection.IsNotWindowsNanoServer))]
+ public void StartClose_AddPath_Connect()
+ {
+ using (GraphicsPath gp = new GraphicsPath())
+ using (GraphicsPath inner = new GraphicsPath())
+ {
+ inner.AddArc(10, 10, 100, 100, 90, 180);
+ gp.AddLine(1, 1, 2, 2);
+ gp.AddPath(inner, true);
+ gp.AddLine(10, 10, 20, 20);
+ byte[] types = gp.PathTypes;
+
+ Assert.Equal(0, types[0]);
+ Assert.Equal(1, types[2]);
+ Assert.Equal(3, types[gp.PointCount - 3]);
+ Assert.Equal(1, types[gp.PointCount - 1]);
+ }
+ }
+
+ [ConditionalFact(nameof(PlatformDetection) + "." + nameof(PlatformDetection.IsNotWindowsNanoServer))]
+ public void StartClose_AddPath_NoConnect()
+ {
+ GraphicsPath inner = new GraphicsPath();
+ inner.AddArc(10, 10, 100, 100, 90, 180);
+ GraphicsPath path = new GraphicsPath();
+ path.AddLine(1, 1, 2, 2);
+ path.AddPath(inner, false);
+ path.AddLine(10, 10, 20, 20);
+ byte[] types = path.PathTypes;
+
+ Assert.Equal(0, types[0]);
+ Assert.Equal(0, types[2]);
+ Assert.Equal(3, types[path.PointCount - 3]);
+ Assert.Equal(1, types[path.PointCount - 1]);
+ }
+
+ [ConditionalFact(nameof(PlatformDetection) + "." + nameof(PlatformDetection.IsNotWindowsNanoServer))]
+ public void StartClose_AddPie()
+ {
+ GraphicsPath path = new GraphicsPath();
+ path.AddLine(1, 1, 2, 2);
+ path.AddPie(10, 10, 10, 10, 90, 180);
+ path.AddLine(10, 10, 20, 20);
+ byte[] types = path.PathTypes;
+
+ Assert.Equal(0, types[0]);
+ Assert.Equal(0, types[2]);
+
+ Assert.Equal((types[path.PointCount - 3] & 128), 128);
+ Assert.Equal(0, types[path.PointCount - 2]);
+ Assert.Equal(1, types[path.PointCount - 1]);
+ }
+
+ [ConditionalFact(nameof(PlatformDetection) + "." + nameof(PlatformDetection.IsNotWindowsNanoServer))]
+ public void StartClose_AddPolygon()
+ {
+ using (GraphicsPath gp = new GraphicsPath())
+ {
+ gp.AddLine(1, 1, 2, 2);
+ gp.AddPolygon(new Point[3] { new Point(1, 1), new Point(2, 2), new Point(3, 3) });
+ gp.AddLine(10, 10, 20, 20);
+ byte[] types = gp.PathTypes;
+
+ Assert.Equal(0, types[0]);
+ Assert.Equal(0, types[2]);
+ Assert.Equal(129, types[gp.PointCount - 3]);
+ Assert.Equal(0, types[gp.PointCount - 2]);
+ Assert.Equal(1, types[gp.PointCount - 1]);
+ }
+ }
+
+ [ConditionalFact(nameof(PlatformDetection) + "." + nameof(PlatformDetection.IsNotWindowsNanoServer))]
+ public void StartClose_AddRectangle()
+ {
+ using (GraphicsPath gp = new GraphicsPath())
+ {
+ gp.AddLine(1, 1, 2, 2);
+ gp.AddRectangle(new RectangleF(10, 10, 20, 20));
+ gp.AddLine(10, 10, 20, 20);
+ byte[] types = gp.PathTypes;
+
+ Assert.Equal(0, types[0]);
+ Assert.Equal(0, types[2]);
+ Assert.Equal(129, types[gp.PointCount - 3]);
+ Assert.Equal(0, types[gp.PointCount - 2]);
+ Assert.Equal(1, types[gp.PointCount - 1]);
+ }
+ }
+
+ [ConditionalFact(nameof(PlatformDetection) + "." + nameof(PlatformDetection.IsNotWindowsNanoServer))]
+ public void StartClose_AddRectangles()
+ {
+ using (GraphicsPath gp = new GraphicsPath())
+ {
+ gp.AddLine(1, 1, 2, 2);
+ gp.AddRectangles(new RectangleF[2]
+ {
+ new RectangleF (10, 10, 20, 20),
+ new RectangleF (20, 20, 10, 10)
+ });
+
+ gp.AddLine(10, 10, 20, 20);
+ byte[] types = gp.PathTypes;
+
+ Assert.Equal(0, types[0]);
+ Assert.Equal(0, types[2]);
+ Assert.Equal(129, types[gp.PointCount - 3]);
+ Assert.Equal(0, types[gp.PointCount - 2]);
+ Assert.Equal(1, types[gp.PointCount - 1]);
+ }
+ }
+
+ [ConditionalFact(nameof(PlatformDetection) + "." + nameof(PlatformDetection.IsNotWindowsNanoServer))]
+ public void StartClose_AddString()
+ {
+ using (GraphicsPath gp = new GraphicsPath())
+ {
+ gp.AddLine(1, 1, 2, 2);
+ gp.AddString("mono", FontFamily.GenericMonospace, 0, 10, new Point(20, 20), StringFormat.GenericDefault);
+ gp.AddLine(10, 10, 20, 20);
+ byte[] types = gp.PathTypes;
+
+ Assert.Equal(0, types[0]);
+ Assert.Equal(0, types[2]);
+ Assert.Equal(163, types[gp.PointCount - 3]);
+ Assert.Equal(1, types[gp.PointCount - 2]);
+ Assert.Equal(1, types[gp.PointCount - 1]);
+ }
+ }
+
+ [ConditionalFact(nameof(PlatformDetection) + "." + nameof(PlatformDetection.IsNotWindowsNanoServer))]
+ public void Widen_Pen_Success()
+ {
+ PointF[] expectedPoints = new PointF[]
+ {
+ new PointF(0.5f, 0.5f), new PointF(3.5f, 0.5f), new PointF(3.5f, 3.5f),
+ new PointF(0.5f, 3.5f), new PointF(1.5f, 3.0f), new PointF(1.0f, 2.5f),
+ new PointF(3.0f, 2.5f), new PointF(2.5f, 3.0f), new PointF(2.5f, 1.0f),
+ new PointF(3.0f, 1.5f), new PointF(1.0f, 1.5f), new PointF(1.5f, 1.0f),
+ };
+
+ byte[] expectedTypes = new byte[] { 0, 1, 1, 129, 0, 1, 1, 1, 1, 1, 1, 129 };
+
+ using (GraphicsPath gp = new GraphicsPath())
+ using (Pen pen = new Pen(Color.Blue))
+ {
+ gp.AddRectangle(new Rectangle(1, 1, 2, 2));
+ Assert.Equal(4, gp.PointCount);
+ gp.Widen(pen);
+ Assert.Equal(12, gp.PointCount);
+ AssertPointsSequenceEqual(expectedPoints, gp.PathPoints, Delta);
+ Assert.Equal(expectedTypes, gp.PathTypes);
+ }
+ }
+
+ [ConditionalFact(nameof(PlatformDetection) + "." + nameof(PlatformDetection.IsNotWindowsNanoServer))]
+ public void Widen_EmptyPath_Success()
+ {
+ using (GraphicsPath gp = new GraphicsPath())
+ using (Pen pen = new Pen(Color.Blue))
+ {
+ Assert.Equal(0, gp.PointCount);
+ gp.Widen(pen);
+ Assert.Equal(0, gp.PointCount);
+ }
+ }
+
+ [ConditionalFact(nameof(PlatformDetection) + "." + nameof(PlatformDetection.IsNotWindowsNanoServer))]
+ public void Widen_PenNull_ThrowsArgumentNullException()
+ {
+ using (GraphicsPath gp = new GraphicsPath())
+ {
+ AssertExtensions.Throws<ArgumentNullException>("pen", () => gp.Widen(null));
+ AssertExtensions.Throws<ArgumentNullException>("pen", () => gp.Widen(null, new Matrix()));
+ AssertExtensions.Throws<ArgumentNullException>("pen", () => gp.Widen(null, new Matrix(), 0.67f));
+ }
+ }
+
+ [ConditionalFact(nameof(PlatformDetection) + "." + nameof(PlatformDetection.IsNotWindowsNanoServer))]
+ public void Widen_MatrixNull_Success()
+ {
+ using (GraphicsPath gp = new GraphicsPath())
+ using (Pen pen = new Pen(Color.Blue))
+ {
+ gp.AddPolygon(new Point[3] { new Point(5, 5), new Point(15, 5), new Point(10, 15) });
+ gp.Widen(pen, null);
+ Assert.Equal(9, gp.PointCount);
+ AssertWiden3(gp);
+ }
+ }
+
+ [ConditionalFact(nameof(PlatformDetection) + "." + nameof(PlatformDetection.IsNotWindowsNanoServer))]
+ public void Widen_MatrixEmpty_Success()
+ {
+ using (GraphicsPath gp = new GraphicsPath())
+ using (Pen pen = new Pen(Color.Blue))
+ using (Matrix matrix = new Matrix())
+ {
+ gp.AddPolygon(new Point[3] { new Point(5, 5), new Point(15, 5), new Point(10, 15) });
+ gp.Widen(pen, new Matrix());
+ Assert.Equal(9, gp.PointCount);
+ AssertWiden3(gp);
+ }
+
+ }
+
+ private static IEnumerable<object[]> Widen_PenSmallWidth_TestData()
+ {
+ yield return new object[] { new Rectangle(1, 1, 2, 2), 0f, new RectangleF(0.5f, 0.5f, 3.0f, 3.0f) };
+ yield return new object[] { new Rectangle(1, 1, 2, 2), 0.5f, new RectangleF(0.5f, 0.5f, 3.0f, 3.0f) };
+ yield return new object[] { new Rectangle(1, 1, 2, 2), 1.0f, new RectangleF(0.5f, 0.5f, 3.0f, 3.0f) };
+ yield return new object[] { new Rectangle(1, 1, 2, 2), 1.1f, new RectangleF(0.45f, 0.45f, 3.10f, 3.10f) };
+ }
+
+ [ConditionalTheory(nameof(PlatformDetection) + "." + nameof(PlatformDetection.IsNotWindowsNanoServer))]
+ [MemberData(nameof(Widen_PenSmallWidth_TestData))]
+ public void Widen_Pen_SmallWidth_Succes(
+ Rectangle rectangle, float penWidth, RectangleF expectedBounds)
+ {
+ using (GraphicsPath gp = new GraphicsPath())
+ using (Pen pen = new Pen(Color.Aqua, 0))
+ using (Matrix matrix = new Matrix())
+ {
+ pen.Width = penWidth;
+ gp.AddRectangle(rectangle);
+ gp.Widen(pen);
+ AssertRectangleEqual(expectedBounds, gp.GetBounds(null), Delta);
+ AssertRectangleEqual(expectedBounds, gp.GetBounds(matrix), Delta);
+ }
+ }
+
+ [ConditionalFact(nameof(PlatformDetection) + "." + nameof(PlatformDetection.IsNotWindowsNanoServer))]
+ public void IsOutlineVisible_PenNull_ThrowsArgumentNullException()
+ {
+ using (GraphicsPath gp = new GraphicsPath())
+ {
+ AssertExtensions.Throws<ArgumentNullException>("pen", () => gp.IsOutlineVisible(1, 1, null));
+ AssertExtensions.Throws<ArgumentNullException>("pen", () => gp.IsOutlineVisible(1.0f, 1.0f, null));
+ AssertExtensions.Throws<ArgumentNullException>("pen", () => gp.IsOutlineVisible(new Point(), null));
+ AssertExtensions.Throws<ArgumentNullException>("pen", () => gp.IsOutlineVisible(new PointF(), null));
+ }
+ }
+
+ [ConditionalFact(nameof(PlatformDetection) + "." + nameof(PlatformDetection.IsNotWindowsNanoServer))]
+ public void IsOutlineVisible_LineWithoutGraphics_ReturnsExpected()
+ {
+ AssertIsOutlineVisibleLine(null);
+ }
+
+ [ConditionalFact(nameof(PlatformDetection) + "." + nameof(PlatformDetection.IsNotWindowsNanoServer))]
+ public void IsOutlineVisible_LineInsideGraphics_ReturnsExpected()
+ {
+ using (Bitmap bitmap = new Bitmap(20, 20))
+ using (Graphics graphics = Graphics.FromImage(bitmap))
+ {
+ AssertIsOutlineVisibleLine(graphics);
+ }
+ }
+
+ [ConditionalFact(nameof(PlatformDetection) + "." + nameof(PlatformDetection.IsNotWindowsNanoServer))]
+ public void IsOutlineVisible_LineOutsideGraphics_ReturnsExpected()
+ {
+ using (Bitmap bitmap = new Bitmap(5, 5))
+ using (Graphics graphics = Graphics.FromImage(bitmap))
+ {
+ AssertIsOutlineVisibleLine(graphics);
+ }
+ }
+
+ [ConditionalFact(nameof(PlatformDetection) + "." + nameof(PlatformDetection.IsNotWindowsNanoServer))]
+ public void IsOutlineVisible_LineWithGraphicsTransform_ReturnsExpected()
+ {
+ using (Bitmap bitmap = new Bitmap(20, 20))
+ using (Graphics graphics = Graphics.FromImage(bitmap))
+ using (Matrix matrix = new Matrix(2, 0, 0, 2, 50, -50))
+ {
+ graphics.Transform = matrix;
+ AssertIsOutlineVisibleLine(graphics);
+ }
+ }
+
+ [ConditionalFact(nameof(PlatformDetection) + "." + nameof(PlatformDetection.IsNotWindowsNanoServer))]
+ public void IsOutlineVisible_LineWithGraphicsPageUnit_ReturnsExpected()
+ {
+ using (Bitmap bitmap = new Bitmap(20, 20))
+ using (Graphics graphics = Graphics.FromImage(bitmap))
+ {
+ graphics.PageUnit = GraphicsUnit.Millimeter;
+ AssertIsOutlineVisibleLine(graphics);
+ }
+ }
+
+ [ConditionalFact(nameof(PlatformDetection) + "." + nameof(PlatformDetection.IsNotWindowsNanoServer))]
+ public void IsOutlineVisible_LineWithGraphicsPageScale_ReturnsExpected()
+ {
+ using (Bitmap bitmap = new Bitmap(20, 20))
+ using (Graphics graphics = Graphics.FromImage(bitmap))
+ {
+ graphics.PageScale = 2.0f;
+ AssertIsOutlineVisibleLine(graphics);
+ }
+ }
+
+ [ConditionalFact(nameof(PlatformDetection) + "." + nameof(PlatformDetection.IsNotWindowsNanoServer))]
+ public void IsOutlineVisible_RectangleWithoutGraphics_ReturnsExpected()
+ {
+ AssertIsOutlineVisibleRectangle(null);
+ }
+
+ [ConditionalFact(nameof(PlatformDetection) + "." + nameof(PlatformDetection.IsNotWindowsNanoServer))]
+ public void IsVisible_RectangleWithoutGraphics_ReturnsExpected()
+ {
+ AssertIsVisibleRectangle(null);
+ }
+
+ [ConditionalFact(nameof(PlatformDetection) + "." + nameof(PlatformDetection.IsNotWindowsNanoServer))]
+ public void IsVisible_RectangleWithGraphics_ReturnsExpected()
+ {
+ using (Bitmap bitmap = new Bitmap(40, 40))
+ using (Graphics graphics = Graphics.FromImage(bitmap))
+ {
+ AssertIsVisibleRectangle(graphics);
+ }
+ }
+
+ [ConditionalFact(nameof(PlatformDetection) + "." + nameof(PlatformDetection.IsNotWindowsNanoServer))]
+ public void IsVisible_EllipseWithoutGraphics_ReturnsExpected()
+ {
+ AssertIsVisibleEllipse(null);
+ }
+
+ [ConditionalFact(nameof(PlatformDetection) + "." + nameof(PlatformDetection.IsNotWindowsNanoServer))]
+ public void IsVisible_EllipseWithGraphics_ReturnsExpected()
+ {
+ using (Bitmap bitmap = new Bitmap(40, 40))
+ using (Graphics graphics = Graphics.FromImage(bitmap))
+ {
+ AssertIsVisibleEllipse(graphics);
+ }
+ }
+
+ [ConditionalFact(nameof(PlatformDetection) + "." + nameof(PlatformDetection.IsNotWindowsNanoServer))]
+ public void Reverse_Arc_Succes()
+ {
+ using (GraphicsPath gp = new GraphicsPath())
+ {
+ gp.AddArc(1f, 1f, 2f, 2f, Pi4, Pi4);
+ AssertReverse(gp, gp.PathPoints, gp.PathTypes);
+ }
+ }
+
+ [ConditionalFact(nameof(PlatformDetection) + "." + nameof(PlatformDetection.IsNotWindowsNanoServer))]
+ public void Reverse_Bezier_Succes()
+ {
+ using (GraphicsPath gp = new GraphicsPath())
+ {
+ gp.AddBezier(1, 2, 3, 4, 5, 6, 7, 8);
+ AssertReverse(gp, gp.PathPoints, gp.PathTypes);
+ }
+ }
+
+ private static IEnumerable<object[]> Reverse_TestData()
+ {
+ yield return new object[]
+ {
+ new Point[]
+ {
+ new Point (1,2), new Point (3,4), new Point (5,6), new Point (7,8),
+ new Point (9,10), new Point (11,12), new Point (13,14)
+ }
+ };
+ }
+
+ [ConditionalTheory(nameof(PlatformDetection) + "." + nameof(PlatformDetection.IsNotWindowsNanoServer))]
+ [MemberData(nameof(Reverse_TestData))]
+ public void Reverse_Beziers_Succes(Point[] points)
+ {
+ using (GraphicsPath gp = new GraphicsPath())
+ {
+ gp.AddBeziers(points);
+ AssertReverse(gp, gp.PathPoints, gp.PathTypes);
+ }
+ }
+
+ [ConditionalTheory(nameof(PlatformDetection) + "." + nameof(PlatformDetection.IsNotWindowsNanoServer))]
+ [MemberData(nameof(Reverse_TestData))]
+ public void Reverse_ClosedCurve_Succes(Point[] points)
+ {
+ using (GraphicsPath gp = new GraphicsPath())
+ {
+ gp.AddClosedCurve(points);
+ AssertReverse(gp, gp.PathPoints, gp.PathTypes);
+ }
+ }
+
+ [ConditionalTheory(nameof(PlatformDetection) + "." + nameof(PlatformDetection.IsNotWindowsNanoServer))]
+ [MemberData(nameof(Reverse_TestData))]
+ public void Reverse_Curve_Succes(Point[] points)
+ {
+ using (GraphicsPath gp = new GraphicsPath())
+ {
+ gp.AddCurve(points);
+ AssertReverse(gp, gp.PathPoints, gp.PathTypes);
+ }
+ }
+
+ [ConditionalFact(nameof(PlatformDetection) + "." + nameof(PlatformDetection.IsNotWindowsNanoServer))]
+ public void Reverse_Ellipse_Succes()
+ {
+ using (GraphicsPath gp = new GraphicsPath())
+ {
+ gp.AddEllipse(1, 2, 3, 4);
+ AssertReverse(gp, gp.PathPoints, gp.PathTypes);
+ }
+ }
+
+ [ConditionalFact(nameof(PlatformDetection) + "." + nameof(PlatformDetection.IsNotWindowsNanoServer))]
+ public void Reverse_Line_Succes()
+ {
+ using (GraphicsPath gp = new GraphicsPath())
+ {
+ gp.AddLine(1, 2, 3, 4);
+ AssertReverse(gp, gp.PathPoints, gp.PathTypes);
+ }
+ }
+
+ [ConditionalFact(nameof(PlatformDetection) + "." + nameof(PlatformDetection.IsNotWindowsNanoServer))]
+ public void Reverse_LineClosed_Succes()
+ {
+ using (GraphicsPath gp = new GraphicsPath())
+ {
+ gp.AddLine(1, 2, 3, 4);
+ gp.CloseFigure();
+ AssertReverse(gp, gp.PathPoints, gp.PathTypes);
+ }
+ }
+
+ [ConditionalTheory(nameof(PlatformDetection) + "." + nameof(PlatformDetection.IsNotWindowsNanoServer))]
+ [MemberData(nameof(Reverse_TestData))]
+ public void Reverse_Lines_Succes(Point[] points)
+ {
+ using (GraphicsPath gp = new GraphicsPath())
+ {
+ gp.AddLines(points);
+ AssertReverse(gp, gp.PathPoints, gp.PathTypes);
+ }
+ }
+
+ [ConditionalTheory(nameof(PlatformDetection) + "." + nameof(PlatformDetection.IsNotWindowsNanoServer))]
+ [MemberData(nameof(Reverse_TestData))]
+ public void Reverse_Polygon_Succes(Point[] points)
+ {
+ using (GraphicsPath gp = new GraphicsPath())
+ {
+ gp.AddPolygon(points);
+ AssertReverse(gp, gp.PathPoints, gp.PathTypes);
+ }
+ }
+
+ [ConditionalFact(nameof(PlatformDetection) + "." + nameof(PlatformDetection.IsNotWindowsNanoServer))]
+ public void Reverse_Rectangle_Succes()
+ {
+ using (GraphicsPath gp = new GraphicsPath())
+ {
+ gp.AddRectangle(new Rectangle(1, 2, 3, 4));
+ AssertReverse(gp, gp.PathPoints, gp.PathTypes);
+ }
+ }
+
+ [ConditionalFact(nameof(PlatformDetection) + "." + nameof(PlatformDetection.IsNotWindowsNanoServer))]
+ public void Reverse_Rectangles_Succes()
+ {
+ using (GraphicsPath gp = new GraphicsPath())
+ {
+ Rectangle[] rects = new Rectangle[] { new Rectangle(1, 2, 3, 4), new Rectangle(5, 6, 7, 8) };
+ gp.AddRectangles(rects);
+ AssertReverse(gp, gp.PathPoints, gp.PathTypes);
+ }
+ }
+
+ [ConditionalFact(nameof(PlatformDetection) + "." + nameof(PlatformDetection.IsNotWindowsNanoServer))]
+ public void Reverse_Pie_Succes()
+ {
+ using (GraphicsPath gp = new GraphicsPath())
+ {
+ gp.AddPie(1, 2, 3, 4, 10, 20);
+ byte[] expectedTypes = new byte[] { 0, 3, 3, 3, 129 };
+ AssertReverse(gp, gp.PathPoints, expectedTypes);
+ }
+ }
+
+ [ConditionalFact(nameof(PlatformDetection) + "." + nameof(PlatformDetection.IsNotWindowsNanoServer))]
+ public void Reverse_ArcLineInnerPath_Succes()
+ {
+ using (GraphicsPath inner = new GraphicsPath())
+ using (GraphicsPath gp = new GraphicsPath())
+ {
+ inner.AddArc(1f, 1f, 2f, 2f, Pi4, Pi4);
+ inner.AddLine(1, 2, 3, 4);
+ byte[] expectedTypes = new byte[] { 0, 1, 1, 3, 3, 3 };
+ gp.AddPath(inner, true);
+ AssertReverse(gp, gp.PathPoints, expectedTypes);
+ }
+ }
+
+ [ConditionalFact(nameof(PlatformDetection) + "." + nameof(PlatformDetection.IsNotWindowsNanoServer))]
+ public void Reverse_EllipseRectangle_Succes()
+ {
+ using (GraphicsPath gp = new GraphicsPath())
+ {
+ gp.AddEllipse(50, 51, 50, 100);
+ gp.AddRectangle(new Rectangle(200, 201, 60, 61));
+ byte[] expectedTypes = new byte[] { 0, 1, 1, 129, 0, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 131 };
+ AssertReverse(gp, gp.PathPoints, expectedTypes);
+ }
+ }
+
+ [ConditionalFact(nameof(PlatformDetection) + "." + nameof(PlatformDetection.IsNotWindowsNanoServer))]
+ public void Reverse_String_Succes()
+ {
+ using (GraphicsPath gp = new GraphicsPath())
+ {
+ gp.AddString("Mono::", FontFamily.GenericMonospace, 0, 10, new Point(10, 10), StringFormat.GenericDefault);
+ byte[] expectedTypes = new byte[]
+ {
+ 0,3,3,3,3,3,3,3,3,3,3,3,3,1,3,3,3,3,3,3,3,3,3,3,3,3,129,
+ 0,3,3,3,3,3,3,3,3,3,3,3,3,1,3,3,3,3,3,3,3,3,3,3,3,3,161,
+ 0,3,3,3,3,3,3,3,3,3,3,3,3,1,3,3,3,3,3,3,3,3,3,3,3,3,129,
+ 0,3,3,3,3,3,3,3,3,3,3,3,3,1,3,3,3,3,3,3,3,3,3,3,3,3,161,
+ 0,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,131,0,3,
+ 3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,163,0,3,3,3,
+ 3,3,3,3,3,3,3,3,3,1,1,1,3,3,3,3,3,3,3,3,3,3,3,3,1,3,3,3,
+ 3,3,3,3,3,3,3,3,3,1,1,3,3,3,3,3,3,3,3,3,3,3,3,1,1,3,3,3,
+ 3,3,3,3,3,3,3,3,3,1,3,3,3,3,3,3,3,3,3,3,3,3,1,1,3,3,3,3,
+ 3,3,3,3,3,3,3,3,3,3,3,161,0,3,3,3,3,3,3,3,3,3,3,3,3,3,3,
+ 3,3,3,3,3,3,3,3,3,131,0,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,
+ 3,3,3,3,3,3,3,163,0,1,1,1,3,3,3,3,3,3,3,3,3,3,3,3,1,3,3,
+ 3,3,3,3,3,3,3,3,3,3,1,1,1,3,3,3,3,3,3,3,3,3,3,3,3,1,1,1,
+ 1,3,3,3,3,3,3,3,3,3,3,3,3,1,1,1,3,3,3,3,3,3,3,3,3,3,3,3,
+ 1,3,3,3,3,3,3,3,3,3,3,3,3,1,1,1,1,129
+ };
+
+ AssertReverse(gp, gp.PathPoints, expectedTypes);
+ }
+ }
+
+ [ConditionalFact(nameof(PlatformDetection) + "." + nameof(PlatformDetection.IsNotWindowsNanoServer))]
+ public void Reverse_Marker_Succes()
+ {
+ using (GraphicsPath gp = new GraphicsPath())
+ {
+ gp.AddRectangle(new Rectangle(200, 201, 60, 61));
+ gp.SetMarkers();
+ byte[] expectedTypes = new byte[] { 0, 1, 1, 129 };
+ AssertReverse(gp, gp.PathPoints, expectedTypes);
+ }
+ }
+
+ [ConditionalFact(nameof(PlatformDetection) + "." + nameof(PlatformDetection.IsNotWindowsNanoServer))]
+ public void Reverse_SubpathMarker_Succes()
+ {
+ using (GraphicsPath gp = new GraphicsPath())
+ {
+ gp.AddLine(0, 1, 2, 3);
+ gp.SetMarkers();
+ gp.CloseFigure();
+ gp.AddBezier(5, 6, 7, 8, 9, 10, 11, 12);
+ gp.CloseFigure();
+ byte[] expectedTypes = new byte[] { 0, 3, 3, 163, 0, 129 };
+ AssertReverse(gp, gp.PathPoints, expectedTypes);
+ }
+
+ using (GraphicsPath gp = new GraphicsPath())
+ {
+ gp.AddLine(0, 1, 2, 3);
+ gp.SetMarkers();
+ gp.StartFigure();
+ gp.AddLine(20, 21, 22, 23);
+ gp.AddBezier(5, 6, 7, 8, 9, 10, 11, 12);
+ byte[] expectedTypes = new byte[] { 0, 3, 3, 3, 1, 33, 0, 1 };
+ AssertReverse(gp, gp.PathPoints, expectedTypes);
+ }
+ }
+
+ [ConditionalFact(nameof(PlatformDetection) + "." + nameof(PlatformDetection.IsNotWindowsNanoServer))]
+ public void Ctor_PointsTypes_Succes()
+ {
+ int dX = 520;
+ int dY = 320;
+ Point[] expectedPoints = new Point[]
+ {
+ new Point(dX-64, dY-24), new Point(dX-59, dY-34), new Point(dX-52, dY-54),
+ new Point(dX-18, dY-66), new Point(dX-34, dY-47), new Point(dX-43, dY-27),
+ new Point(dX-44, dY-8),
+ };
+
+ byte[] expectedTypes = new byte[]
+ {
+ (byte)PathPointType.Start, (byte)PathPointType.Bezier, (byte)PathPointType.Bezier,
+ (byte)PathPointType.Bezier, (byte)PathPointType.Bezier, (byte)PathPointType.Bezier,
+ (byte)PathPointType.Bezier
+ };
+
+ using (GraphicsPath path = new GraphicsPath(expectedPoints, expectedTypes))
+ {
+ Assert.Equal(7, path.PointCount);
+ byte[] actualTypes = path.PathTypes;
+ Assert.Equal(expectedTypes, actualTypes);
+ }
+ }
+
+ private void AssertEmptyGrahicsPath(GraphicsPath gp)
+ {
+ Assert.Equal(0, gp.PathData.Points.Length);
+ Assert.Equal(0, gp.PathData.Types.Length);
+ Assert.Equal(0, gp.PointCount);
+ }
+
+ private void AssertEqual(float expexted, float actual, float tollerance)
+ {
+ AssertExtensions.LessThanOrEqualTo(Math.Abs(expexted - actual), tollerance);
+ }
+
+ private void AssertLine(GraphicsPath path)
+ {
+ PointF[] expectedPoints = new PointF[]
+ {
+ new PointF(1f, 1f), new PointF(2f, 2f)
+ };
+
+ Assert.Equal(2, path.PathPoints.Length);
+ Assert.Equal(2, path.PathTypes.Length);
+ Assert.Equal(2, path.PathData.Points.Length);
+ Assert.Equal(new RectangleF(1f, 1f, 1f, 1f), path.GetBounds());
+ Assert.Equal(expectedPoints, path.PathPoints);
+ Assert.Equal(new byte[] { 0, 1 }, path.PathTypes);
+ }
+
+ private void AssertArc(GraphicsPath path)
+ {
+ PointF[] expectedPoints = new PointF[]
+ {
+ new PointF(2.99990582f, 2.01370716f), new PointF(2.99984312f, 2.018276f),
+ new PointF(2.99974918f, 2.02284455f), new PointF(2.999624f, 2.027412f),
+ };
+
+ Assert.Equal(4, path.PathPoints.Length);
+ Assert.Equal(4, path.PathTypes.Length);
+ Assert.Equal(4, path.PathData.Points.Length);
+ Assert.Equal(new RectangleF(2.99962401f, 2.01370716f, 0f, 0.0137047768f), path.GetBounds());
+ Assert.Equal(expectedPoints, path.PathPoints);
+ Assert.Equal(new byte[] { 0, 3, 3, 3 }, path.PathTypes);
+ }
+
+ private void AssertBezier(GraphicsPath path)
+ {
+ PointF[] expectedPoints = new PointF[]
+ {
+ new PointF(1f, 1f), new PointF(2f, 2f),
+ new PointF(3f, 3f), new PointF(4f, 4f),
+ };
+
+ Assert.Equal(4, path.PointCount);
+ Assert.Equal(4, path.PathPoints.Length);
+ Assert.Equal(4, path.PathTypes.Length);
+ Assert.Equal(4, path.PathData.Points.Length);
+ Assert.Equal(new RectangleF(1f, 1f, 3f, 3f), path.GetBounds());
+ Assert.Equal(expectedPoints, path.PathPoints);
+ Assert.Equal(new byte[] { 0, 3, 3, 3 }, path.PathTypes);
+ }
+
+ private void AssertCurve(GraphicsPath path)
+ {
+ PointF[] expectedPoints = new PointF[]
+ {
+ new PointF(1f, 1f), new PointF(1.16666663f, 1.16666663f),
+ new PointF(1.83333325f, 1.83333325f), new PointF(2f, 2f)
+ };
+
+ Assert.Equal(4, path.PathPoints.Length);
+ Assert.Equal(4, path.PathTypes.Length);
+ Assert.Equal(4, path.PathData.Points.Length);
+ Assert.Equal(new RectangleF(1f, 1f, 1f, 1f), path.GetBounds());
+ AssertPointsSequenceEqual(expectedPoints, path.PathPoints, Delta);
+ Assert.Equal(new byte[] { 0, 3, 3, 3 }, path.PathTypes);
+ }
+
+ private void AssertClosedCurve(GraphicsPath path)
+ {
+ Assert.Equal(10, path.PathPoints.Length);
+ Assert.Equal(10, path.PathTypes.Length);
+ Assert.Equal(10, path.PathData.Points.Length);
+ Assert.Equal(new RectangleF(0.8333333f, 0.8333333f, 2.33333278f, 2.33333278f), path.GetBounds());
+ Assert.Equal(new byte[] { 0, 3, 3, 3, 3, 3, 3, 3, 3, 131 }, path.PathTypes);
+ }
+
+ private void AssertRectangle(GraphicsPath path)
+ {
+ PointF[] expectedPoints = new PointF[]
+ {
+ new PointF(1f, 1f), new PointF(3f, 1f),
+ new PointF(3f, 3f), new PointF(1f, 3f)
+ };
+
+ Assert.Equal(4, path.PathPoints.Length);
+ Assert.Equal(4, path.PathTypes.Length);
+ Assert.Equal(4, path.PathData.Points.Length);
+ Assert.Equal(new RectangleF(1f, 1f, 2f, 2f), path.GetBounds());
+ Assert.Equal(expectedPoints, path.PathPoints);
+ Assert.Equal(new byte[] { 0, 1, 1, 129 }, path.PathTypes);
+ }
+
+ private void AssertEllipse(GraphicsPath path)
+ {
+ Assert.Equal(13, path.PathPoints.Length);
+ Assert.Equal(13, path.PathTypes.Length);
+ Assert.Equal(13, path.PathData.Points.Length);
+ Assert.Equal(new RectangleF(1f, 1f, 2f, 2f), path.GetBounds());
+ Assert.Equal(new byte[] { 0, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 131 }, path.PathTypes);
+ }
+
+ private void AssertPie(GraphicsPath path)
+ {
+ PointF[] expectedPoints = new PointF[]
+ {
+ new PointF(2f, 2f), new PointF(2.99990582f, 2.01370716f),
+ new PointF(2.99984312f, 2.018276f), new PointF(2.99974918f, 2.02284455f),
+ new PointF(2.999624f, 2.027412f)
+ };
+
+ Assert.Equal(5, path.PathPoints.Length);
+ Assert.Equal(5, path.PathTypes.Length);
+ Assert.Equal(5, path.PathData.Points.Length);
+ AssertRectangleEqual(new RectangleF(2f, 2f, 0.9999058f, 0.0274119377f), path.GetBounds(), Delta);
+ AssertPointsSequenceEqual(expectedPoints, path.PathPoints, Delta);
+ Assert.Equal(new byte[] { 0, 1, 3, 3, 131 }, path.PathTypes);
+ }
+
+ private void AssertPolygon(GraphicsPath path)
+ {
+ PointF[] expectedPoints = new PointF[]
+ {
+ new PointF(1f, 1f),
+ new PointF(2f, 2f),
+ new PointF(3f, 3f)
+ };
+
+ Assert.Equal(3, path.PathPoints.Length);
+ Assert.Equal(3, path.PathTypes.Length);
+ Assert.Equal(3, path.PathData.Points.Length);
+ Assert.Equal(new RectangleF(1f, 1f, 2f, 2f), path.GetBounds());
+ Assert.Equal(expectedPoints, path.PathPoints);
+ Assert.Equal(new byte[] { 0, 1, 129 }, path.PathTypes);
+ }
+
+ private void AssertFlats(GraphicsPath flat, GraphicsPath original)
+ {
+ AssertExtensions.GreaterThanOrEqualTo(flat.PointCount, original.PointCount);
+ for (int i = 0; i < flat.PointCount; i++)
+ {
+ Assert.NotEqual(flat.PathTypes[i], 3);
+ }
+ }
+
+ private void AssertWrapNaN(GraphicsPath path)
+ {
+ byte[] expectedTypes = new byte[] { 0, 1, 129 };
+
+ Assert.Equal(3, path.PointCount);
+ Assert.Equal(float.NaN, path.PathPoints[0].X);
+ Assert.Equal(float.NaN, path.PathPoints[0].Y);
+ Assert.Equal(float.NaN, path.PathPoints[1].X);
+ Assert.Equal(float.NaN, path.PathPoints[1].Y);
+ Assert.Equal(float.NaN, path.PathPoints[2].X);
+ Assert.Equal(float.NaN, path.PathPoints[2].Y);
+ Assert.Equal(expectedTypes, path.PathTypes);
+ }
+
+ private void AssertWiden3(GraphicsPath path)
+ {
+ PointF[] expectedPoints = new PointF[]
+ {
+ new PointF(4.2f, 4.5f), new PointF(15.8f, 4.5f),
+ new PointF(10.0f, 16.1f), new PointF(10.4f, 14.8f),
+ new PointF(9.6f, 14.8f), new PointF(14.6f, 4.8f),
+ new PointF(15.0f, 5.5f), new PointF(5.0f, 5.5f),
+ new PointF(5.4f, 4.8f)
+ };
+
+ AssertPointsSequenceEqual(expectedPoints, path.PathPoints, 0.25f);
+ Assert.Equal(new byte[] { 0, 1, 129, 0, 1, 1, 1, 1, 129 }, path.PathTypes);
+ }
+
+ private void AssertIsOutlineVisibleLine(Graphics graphics)
+ {
+ using (GraphicsPath gp = new GraphicsPath())
+ using (Pen pen = new Pen(Color.Red, 3.0f))
+ {
+ gp.AddLine(10, 1, 14, 1);
+ Assert.True(gp.IsOutlineVisible(10, 1, Pens.Red, graphics));
+ Assert.True(gp.IsOutlineVisible(10, 2, pen, graphics));
+ Assert.False(gp.IsOutlineVisible(10, 2, Pens.Red, graphics));
+
+ Assert.True(gp.IsOutlineVisible(11.0f, 1.0f, Pens.Red, graphics));
+ Assert.True(gp.IsOutlineVisible(11.0f, 1.0f, pen, graphics));
+ Assert.False(gp.IsOutlineVisible(11.0f, 2.0f, Pens.Red, graphics));
+
+ Point point = new Point(12, 2);
+ Assert.False(gp.IsOutlineVisible(point, Pens.Red, graphics));
+ Assert.True(gp.IsOutlineVisible(point, pen, graphics));
+
+ point.Y = 1;
+ Assert.True(gp.IsOutlineVisible(point, Pens.Red, graphics));
+
+ PointF fPoint = new PointF(13.0f, 2.0f);
+ Assert.False(gp.IsOutlineVisible(fPoint, Pens.Red, graphics));
+ Assert.True(gp.IsOutlineVisible(fPoint, pen, graphics));
+
+ fPoint.Y = 1;
+ Assert.True(gp.IsOutlineVisible(fPoint, Pens.Red, graphics));
+ }
+ }
+
+ private void AssertIsOutlineVisibleRectangle(Graphics graphics)
+ {
+ using (Pen pen = new Pen(Color.Red, 3.0f))
+ using (GraphicsPath gp = new GraphicsPath())
+ {
+ gp.AddRectangle(new Rectangle(10, 10, 20, 20));
+ Assert.True(gp.IsOutlineVisible(10, 10, Pens.Red, graphics));
+ Assert.True(gp.IsOutlineVisible(10, 11, pen, graphics));
+ Assert.False(gp.IsOutlineVisible(11, 11, Pens.Red, graphics));
+
+ Assert.True(gp.IsOutlineVisible(11.0f, 10.0f, Pens.Red, graphics));
+ Assert.True(gp.IsOutlineVisible(11.0f, 11.0f, pen, graphics));
+ Assert.False(gp.IsOutlineVisible(11.0f, 11.0f, Pens.Red, graphics));
+
+ Point point = new Point(15, 10);
+ Assert.True(gp.IsOutlineVisible(point, Pens.Red, graphics));
+ Assert.True(gp.IsOutlineVisible(point, pen, graphics));
+
+ point.Y = 15;
+ Assert.False(gp.IsOutlineVisible(point, Pens.Red, graphics));
+
+ PointF fPoint = new PointF(29.0f, 29.0f);
+ Assert.False(gp.IsOutlineVisible(fPoint, Pens.Red, graphics));
+ Assert.True(gp.IsOutlineVisible(fPoint, pen, graphics));
+
+ fPoint.Y = 31.0f;
+ Assert.True(gp.IsOutlineVisible(fPoint, pen, graphics));
+ }
+ }
+
+ private void AssertIsVisibleRectangle(Graphics graphics)
+ {
+ using (GraphicsPath gp = new GraphicsPath())
+ {
+ gp.AddRectangle(new Rectangle(10, 10, 20, 20));
+ Assert.False(gp.IsVisible(9, 9, graphics));
+ Assert.True(gp.IsVisible(10, 10, graphics));
+ Assert.True(gp.IsVisible(20, 20, graphics));
+ Assert.True(gp.IsVisible(29, 29, graphics));
+ Assert.False(gp.IsVisible(30, 29, graphics));
+ Assert.False(gp.IsVisible(29, 30, graphics));
+ Assert.False(gp.IsVisible(30, 30, graphics));
+ Assert.False(gp.IsVisible(9.4f, 9.4f, graphics));
+ Assert.True(gp.IsVisible(9.5f, 9.5f, graphics));
+ Assert.True(gp.IsVisible(10f, 10f, graphics));
+ Assert.True(gp.IsVisible(20f, 20f, graphics));
+ Assert.True(gp.IsVisible(29.4f, 29.4f, graphics));
+ Assert.False(gp.IsVisible(29.5f, 29.5f, graphics));
+ Assert.False(gp.IsVisible(29.5f, 29.4f, graphics));
+ Assert.False(gp.IsVisible(29.4f, 29.5f, graphics));
+ }
+ }
+
+ private void AssertIsVisibleEllipse(Graphics graphics)
+ {
+ using (GraphicsPath gp = new GraphicsPath())
+ {
+ gp.AddEllipse(new Rectangle(10, 10, 20, 20));
+ Assert.False(gp.IsVisible(10, 10, graphics));
+ Assert.True(gp.IsVisible(20, 20, graphics));
+ Assert.False(gp.IsVisible(29, 29, graphics));
+ Assert.False(gp.IsVisible(10f, 10f, graphics));
+ Assert.True(gp.IsVisible(20f, 20f, graphics));
+ Assert.False(gp.IsVisible(29.4f, 29.4f, graphics));
+ }
+ }
+
+ private void AssertReverse(GraphicsPath gp, PointF[] expectedPoints, byte[] expectedTypes)
+ {
+ gp.Reverse();
+ PointF[] reversedPoints = gp.PathPoints;
+ byte[] reversedTypes = gp.PathTypes;
+
+ int count = gp.PointCount;
+ Assert.Equal(expectedPoints.Length, gp.PointCount);
+ Assert.Equal(expectedTypes, gp.PathTypes);
+ for (int i = 0; i < count; i++)
+ {
+ Assert.Equal(expectedPoints[i], reversedPoints[count - i - 1]);
+ Assert.Equal(expectedTypes[i], reversedTypes[i]);
+ }
+ }
+
+ private void AssertPointsSequenceEqual(PointF[] expected, PointF[] actual, float tolerance)
+ {
+ int count = expected.Length;
+ Assert.Equal(expected.Length, actual.Length);
+ for (int i = 0; i < count; i++)
+ {
+ AssertExtensions.LessThanOrEqualTo(Math.Abs(expected[i].X - actual[i].X), tolerance);
+ AssertExtensions.LessThanOrEqualTo(Math.Abs(expected[i].Y - actual[i].Y), tolerance);
+ }
+ }
+
+ private void AssertRectangleEqual(RectangleF expected, RectangleF actual, float tolerance)
+ {
+ AssertExtensions.LessThanOrEqualTo(Math.Abs(expected.X - actual.X), tolerance);
+ AssertExtensions.LessThanOrEqualTo(Math.Abs(expected.Y - actual.Y), tolerance);
+ AssertExtensions.LessThanOrEqualTo(Math.Abs(expected.Width - actual.Width), tolerance);
+ AssertExtensions.LessThanOrEqualTo(Math.Abs(expected.Height - actual.Height), tolerance);
+ }
+ }
+}
+
+
diff --git a/src/System.Drawing.Common/tests/Drawing2D/PathGradientBrushTests.cs b/src/System.Drawing.Common/tests/Drawing2D/PathGradientBrushTests.cs
new file mode 100644
index 0000000000..c7bf4a0f9f
--- /dev/null
+++ b/src/System.Drawing.Common/tests/Drawing2D/PathGradientBrushTests.cs
@@ -0,0 +1,1071 @@
+// Licensed to the .NET Foundation under one or more agreements.
+// See the LICENSE file in the project root for more information.
+//
+// Copyright (C) 2005-2006 Novell, Inc (http://www.novell.com)
+//
+// Permission is hereby granted, free of charge, to any person obtaining
+// a copy of this software and associated documentation files (the
+// "Software"), to deal in the Software without restriction, including
+// without limitation the rights to use, copy, modify, merge, publish,
+// distribute, sublicense, and/or sell copies of the Software, and to
+// permit persons to whom the Software is furnished to do so, subject to
+// the following conditions:
+//
+// The above copyright notice and this permission notice shall be
+// included in all copies or substantial portions of the Software.
+//
+// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
+// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
+// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
+// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
+// LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
+// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
+// WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
+//
+
+using System.Collections.Generic;
+using System.ComponentModel;
+using System.Linq;
+using Xunit;
+
+namespace System.Drawing.Drawing2D.Tests
+{
+ public class PathGradientBrushTests
+ {
+ private readonly Point[] _defaultIntPoints = new Point[2] { new Point(1, 2), new Point(20, 30) };
+ private readonly PointF[] _defaultFloatPoints = new PointF[2] { new PointF(1, 2), new PointF(20, 30) };
+ private readonly RectangleF _defaultRectangle = new RectangleF(1, 2, 19, 28);
+
+ [ConditionalFact(nameof(PlatformDetection) + "." + nameof(PlatformDetection.IsNotWindowsNanoServer))]
+ public void Ctor_Points_ReturnsExpected()
+ {
+ using (PathGradientBrush bi = new PathGradientBrush(_defaultIntPoints))
+ using (PathGradientBrush bf = new PathGradientBrush(_defaultFloatPoints))
+ {
+ AssertDefaults(bi);
+ Assert.Equal(WrapMode.Clamp, bi.WrapMode);
+ AssertDefaults(bf);
+ Assert.Equal(WrapMode.Clamp, bf.WrapMode);
+ }
+ }
+
+ public static IEnumerable<object[]> WrapMode_TestData()
+ {
+ yield return new object[] { WrapMode.Clamp };
+ yield return new object[] { WrapMode.Tile };
+ yield return new object[] { WrapMode.TileFlipX };
+ yield return new object[] { WrapMode.TileFlipXY };
+ yield return new object[] { WrapMode.TileFlipY };
+ }
+
+ [ConditionalTheory(nameof(PlatformDetection) + "." + nameof(PlatformDetection.IsNotWindowsNanoServer))]
+ [MemberData(nameof(WrapMode_TestData))]
+ public void Ctor_PointsWrapMode_ReturnsExpected(WrapMode wrapMode)
+ {
+ using (PathGradientBrush brushInt = new PathGradientBrush(_defaultIntPoints, wrapMode))
+ using (PathGradientBrush brushFloat = new PathGradientBrush(_defaultFloatPoints, wrapMode))
+ {
+ AssertDefaults(brushInt);
+ Assert.Equal(wrapMode, brushInt.WrapMode);
+ AssertDefaults(brushFloat);
+ Assert.Equal(wrapMode, brushFloat.WrapMode);
+ }
+ }
+
+ [ConditionalFact(nameof(PlatformDetection) + "." + nameof(PlatformDetection.IsNotWindowsNanoServer))]
+ public void Ctor_PointsNull_ThrowsArgumentNullException()
+ {
+ AssertExtensions.Throws<ArgumentNullException>("points", () => new PathGradientBrush((Point[])null));
+ AssertExtensions.Throws<ArgumentNullException>("points", () => new PathGradientBrush((PointF[])null));
+ }
+
+ [ConditionalTheory(nameof(PlatformDetection) + "." + nameof(PlatformDetection.IsNotWindowsNanoServer))]
+ [InlineData(0)]
+ [InlineData(1)]
+ public void Ctor_PointsLengthLessThenTwo_ThrowsOutOfMemoryException(int pointsLength)
+ {
+ Assert.Throws<OutOfMemoryException>(() => new PathGradientBrush(new Point[pointsLength]));
+ Assert.Throws<OutOfMemoryException>(() => new PathGradientBrush(new Point[pointsLength], WrapMode.Clamp));
+ Assert.Throws<OutOfMemoryException>(() => new PathGradientBrush(new PointF[pointsLength]));
+ Assert.Throws<OutOfMemoryException>(() => new PathGradientBrush(new PointF[pointsLength], WrapMode.Clamp));
+ }
+
+ [ConditionalFact(nameof(PlatformDetection) + "." + nameof(PlatformDetection.IsNotWindowsNanoServer))]
+ public void Ctor_InvalidWrapMode_ThrowsInvalidEnumArgumentException()
+ {
+ AssertExtensions.Throws<InvalidEnumArgumentException>("wrapMode", () =>
+ new PathGradientBrush(_defaultIntPoints, (WrapMode)int.MaxValue));
+
+ AssertExtensions.Throws<InvalidEnumArgumentException>("wrapMode", () =>
+ new PathGradientBrush(_defaultFloatPoints, (WrapMode)int.MaxValue));
+ }
+
+ [ConditionalFact(nameof(PlatformDetection) + "." + nameof(PlatformDetection.IsNotWindowsNanoServer))]
+ public void Ctor_Path_ReturnsExpected()
+ {
+ using (GraphicsPath path = new GraphicsPath(_defaultFloatPoints, new byte[] { 0, 1 }))
+ using (PathGradientBrush brush = new PathGradientBrush(path))
+ {
+ AssertDefaults(brush);
+ Assert.Equal(WrapMode.Clamp, brush.WrapMode);
+ }
+ }
+
+ [ConditionalFact(nameof(PlatformDetection) + "." + nameof(PlatformDetection.IsNotWindowsNanoServer))]
+ public void Ctor_Path_ThrowsArgumentNullException()
+ {
+ AssertExtensions.Throws<ArgumentNullException>("path", () => new PathGradientBrush((GraphicsPath)null));
+ }
+
+ [ConditionalFact(nameof(PlatformDetection) + "." + nameof(PlatformDetection.IsNotWindowsNanoServer))]
+ public void Ctor_PathWithLessThenTwoPoints_ThrowsOutOfMemoryException()
+ {
+ using (GraphicsPath path = new GraphicsPath())
+ {
+ Assert.Throws<OutOfMemoryException>(() => new PathGradientBrush(path));
+ path.AddLines(new PointF[] { new PointF(1, 1) });
+ Assert.Throws<OutOfMemoryException>(() => new PathGradientBrush(path));
+ }
+ }
+
+ [ConditionalFact(nameof(PlatformDetection) + "." + nameof(PlatformDetection.IsNotWindowsNanoServer))]
+ public void Clone_ReturnsExpected()
+ {
+ using (GraphicsPath path = new GraphicsPath(_defaultFloatPoints, new byte[] { 0, 1 }))
+ using (PathGradientBrush brush = new PathGradientBrush(path))
+ using (PathGradientBrush clone = Assert.IsType<PathGradientBrush>(brush.Clone()))
+ {
+ AssertDefaults(clone);
+ Assert.Equal(WrapMode.Clamp, clone.WrapMode);
+ }
+ }
+
+ [ConditionalFact(nameof(PlatformDetection) + "." + nameof(PlatformDetection.IsNotWindowsNanoServer))]
+ public void Clone_Disposed_ThrowsArgumentException()
+ {
+ PathGradientBrush brush = new PathGradientBrush(_defaultFloatPoints);
+ brush.Dispose();
+
+ AssertExtensions.Throws<ArgumentException>(null, () => brush.Clone());
+ }
+
+ [ConditionalFact(nameof(PlatformDetection) + "." + nameof(PlatformDetection.IsNotWindowsNanoServer))]
+ public void CenterColor_ReturnsExpected()
+ {
+ using (PathGradientBrush brush = new PathGradientBrush(_defaultFloatPoints))
+ {
+ Assert.Equal(Color.Black.ToArgb(), brush.CenterColor.ToArgb());
+ brush.CenterColor = Color.Blue;
+ Assert.Equal(Color.Blue.ToArgb(), brush.CenterColor.ToArgb());
+ brush.CenterColor = Color.Transparent;
+ Assert.Equal(Color.Transparent.ToArgb(), brush.CenterColor.ToArgb());
+ }
+ }
+
+ [ConditionalFact(nameof(PlatformDetection) + "." + nameof(PlatformDetection.IsNotWindowsNanoServer))]
+ public void CenterColor_Disposed_ThrowsArgumentException()
+ {
+ PathGradientBrush brush = new PathGradientBrush(_defaultFloatPoints);
+ brush.Dispose();
+
+ AssertExtensions.Throws<ArgumentException>(null, () => brush.CenterColor = Color.Blue);
+ }
+
+ [ConditionalFact(nameof(PlatformDetection) + "." + nameof(PlatformDetection.IsNotWindowsNanoServer))]
+ public void SurroundColors_ReturnsExpected()
+ {
+ Color[] expectedColors = new Color[2] { Color.FromArgb(255, 0, 0, 255), Color.FromArgb(255, 255, 0, 0) };
+ Color[] sameColors = new Color[2] { Color.FromArgb(255, 255, 255, 0), Color.FromArgb(255, 255, 255, 0) };
+ Color[] expectedSameColors = new Color[1] { Color.FromArgb(255, 255, 255, 0) };
+
+ using (PathGradientBrush brush = new PathGradientBrush(_defaultFloatPoints))
+ {
+ brush.SurroundColors = expectedColors;
+ Assert.Equal(expectedColors, brush.SurroundColors);
+ brush.SurroundColors = sameColors;
+ Assert.Equal(expectedSameColors, brush.SurroundColors);
+ }
+ }
+
+ [ConditionalFact(nameof(PlatformDetection) + "." + nameof(PlatformDetection.IsNotWindowsNanoServer))]
+ public void SurroundColors_CannotChange()
+ {
+ Color[] colors = new Color[2] { Color.FromArgb(255, 0, 0, 255), Color.FromArgb(255, 255, 0, 0) };
+ Color[] defaultColors = new Color[1] { Color.FromArgb(255, 255, 255, 255) };
+
+ using (PathGradientBrush brush = new PathGradientBrush(_defaultFloatPoints))
+ {
+ brush.SurroundColors.ToList().AddRange(colors);
+ Assert.Equal(defaultColors, brush.SurroundColors);
+ brush.SurroundColors[0] = Color.FromArgb(255, 0, 0, 255);
+ Assert.NotEqual(Color.FromArgb(255, 0, 0, 255), brush.SurroundColors[0]);
+ Assert.Equal(defaultColors, brush.SurroundColors);
+ }
+ }
+
+ [ConditionalFact(nameof(PlatformDetection) + "." + nameof(PlatformDetection.IsNotWindowsNanoServer))]
+ public void SurroundColors_Disposed_ThrowsArgumentException()
+ {
+ Color[] colors = new Color[2] { Color.FromArgb(255, 0, 0, 255), Color.FromArgb(255, 255, 0, 0) };
+ PathGradientBrush brush = new PathGradientBrush(_defaultFloatPoints);
+ brush.Dispose();
+
+ AssertExtensions.Throws<ArgumentException>(null, () => brush.SurroundColors = colors);
+ }
+
+ public static IEnumerable<object[]> SurroundColors_InvalidColorsLength_TestData()
+ {
+ yield return new object[] { new Point[2] { new Point(1, 1), new Point(2, 2) }, new Color[0] };
+ yield return new object[] { new Point[2] { new Point(1, 1), new Point(2, 2) }, new Color[3] };
+ }
+
+ [ConditionalTheory(nameof(PlatformDetection) + "." + nameof(PlatformDetection.IsNotWindowsNanoServer))]
+ [MemberData(nameof(SurroundColors_InvalidColorsLength_TestData))]
+ public void SurroundColors_InvalidColorsLength_ThrowsArgumentException(Point[] points, Color[] colors)
+ {
+ using (PathGradientBrush brush = new PathGradientBrush(points))
+ {
+ AssertExtensions.Throws<ArgumentException>(null, () => brush.SurroundColors = colors);
+ }
+ }
+
+ [ConditionalTheory(nameof(PlatformDetection) + "." + nameof(PlatformDetection.IsNotWindowsNanoServer))]
+ public void SurroundColors_Null_ThrowsArgumentNullException()
+ {
+ using (PathGradientBrush brush = new PathGradientBrush(_defaultFloatPoints))
+ {
+ AssertExtensions.Throws<ArgumentNullException>(null, () => brush.SurroundColors = null);
+ }
+ }
+
+ [ConditionalFact(nameof(PlatformDetection) + "." + nameof(PlatformDetection.IsNotWindowsNanoServer))]
+ public void CenterPoint_ReturnsExpected()
+ {
+ PointF centralPoint = new PointF(float.MaxValue, float.MinValue);
+ PointF defaultCentralPoint = new PointF(10.5f, 16f);
+
+ using (PathGradientBrush brush = new PathGradientBrush(_defaultFloatPoints, WrapMode.TileFlipXY))
+ {
+ Assert.Equal(defaultCentralPoint, brush.CenterPoint);
+ brush.CenterPoint = centralPoint;
+ Assert.Equal(centralPoint, brush.CenterPoint);
+
+ centralPoint.X = float.NaN;
+ centralPoint.Y = float.NegativeInfinity;
+ brush.CenterPoint = centralPoint;
+ Assert.Equal(float.NaN, brush.CenterPoint.X);
+ Assert.Equal(float.NegativeInfinity, brush.CenterPoint.Y);
+ }
+ }
+
+ [ConditionalFact(nameof(PlatformDetection) + "." + nameof(PlatformDetection.IsNotWindowsNanoServer))]
+ public void CenterPoint_Disposed_ThrowsArgumentException()
+ {
+ PathGradientBrush brush = new PathGradientBrush(_defaultFloatPoints);
+ brush.Dispose();
+
+ AssertExtensions.Throws<ArgumentException>(null, () => brush.CenterPoint);
+ }
+
+ public static IEnumerable<object[]> Blend_FactorsPositions_TestData()
+ {
+ yield return new object[] { new float[1] { 1 }, new float[1] { 0 } };
+ yield return new object[] { new float[2] { 1, 1 }, new float[2] { 0, 1 } };
+ yield return new object[] { new float[3] { 1, 0, 1 }, new float[3] { 0, 3, 1 } };
+ yield return new object[] { new float[1] { 1 }, new float[3] { 0, 3, 1 } };
+ }
+
+ [ConditionalTheory(nameof(PlatformDetection) + "." + nameof(PlatformDetection.IsNotWindowsNanoServer))]
+ [MemberData(nameof(Blend_FactorsPositions_TestData))]
+ public void Blend_ReturnsExpected(float[] factors, float[] positions)
+ {
+ int expectedSize = factors.Length;
+
+ using (PathGradientBrush brush = new PathGradientBrush(_defaultFloatPoints, WrapMode.TileFlipXY))
+ {
+ brush.Blend = new Blend { Factors = factors, Positions = positions };
+ Assert.Equal(factors, brush.Blend.Factors);
+ Assert.Equal(expectedSize, brush.Blend.Positions.Length);
+ if (expectedSize == positions.Length && expectedSize != 1)
+ {
+ Assert.Equal(factors, brush.Blend.Factors);
+ Assert.Equal(positions, brush.Blend.Positions);
+ }
+ else
+ {
+ Assert.Equal(factors, brush.Blend.Factors);
+ Assert.Equal(1, brush.Blend.Positions.Length);
+ }
+ }
+ }
+
+ [ConditionalFact(nameof(PlatformDetection) + "." + nameof(PlatformDetection.IsNotWindowsNanoServer))]
+ public void Blend_CannotChange()
+ {
+ using (PathGradientBrush brush = new PathGradientBrush(_defaultFloatPoints, WrapMode.TileFlipXY))
+ {
+ brush.Blend.Factors = new float[0];
+ Assert.Equal(1, brush.Blend.Factors.Length);
+ brush.Blend.Factors = new float[2];
+ Assert.Equal(1, brush.Blend.Factors.Length);
+ brush.Blend.Positions = new float[0];
+ Assert.Equal(1, brush.Blend.Positions.Length);
+ brush.Blend.Positions = new float[2];
+ Assert.Equal(1, brush.Blend.Positions.Length);
+ }
+ }
+
+ [ConditionalFact(nameof(PlatformDetection) + "." + nameof(PlatformDetection.IsNotWindowsNanoServer))]
+ public void Blend_Disposed_ThrowsArgumentException()
+ {
+ PathGradientBrush brush = new PathGradientBrush(_defaultFloatPoints);
+ brush.Dispose();
+
+ AssertExtensions.Throws<ArgumentException>(null, () => brush.Blend);
+ }
+
+ public static IEnumerable<object[]> Blend_InvalidFactorsPositions_TestData()
+ {
+ yield return new object[] { new Blend() { Factors = new float[0], Positions = new float[0] } };
+ yield return new object[] { new Blend() { Factors = new float[2], Positions = new float[2] { 1, 1 } } };
+ yield return new object[] { new Blend() { Factors = new float[2], Positions = new float[2] { 0, 5 } } };
+ yield return new object[] { new Blend() { Factors = new float[3], Positions = new float[3] { 0, 1, 5 } } };
+ yield return new object[] { new Blend() { Factors = new float[3], Positions = new float[3] { 1, 1, 1 } } };
+ }
+
+ [ConditionalTheory(nameof(PlatformDetection) + "." + nameof(PlatformDetection.IsNotWindowsNanoServer))]
+ [MemberData(nameof(Blend_InvalidFactorsPositions_TestData))]
+ public void Blend_InvalidFactorPositions_ThrowsArgumentException(Blend blend)
+ {
+ using (PathGradientBrush brush = new PathGradientBrush(_defaultFloatPoints))
+ {
+ AssertExtensions.Throws<ArgumentException>(null, () => brush.Blend = blend);
+ }
+ }
+
+ [ConditionalFact(nameof(PlatformDetection) + "." + nameof(PlatformDetection.IsNotWindowsNanoServer))]
+ public void Blend_InvalidFactorPositionsLengthMismatch_ThrowsArgumentOutOfRangeException()
+ {
+ Blend invalidBlend = new Blend() { Factors = new float[2], Positions = new float[1] };
+
+ using (PathGradientBrush brush = new PathGradientBrush(_defaultFloatPoints))
+ {
+ AssertExtensions.Throws<ArgumentOutOfRangeException>(null, () => brush.Blend = invalidBlend);
+ }
+ }
+
+ [ConditionalFact(nameof(PlatformDetection) + "." + nameof(PlatformDetection.IsNotWindowsNanoServer))]
+ public void Blend_Null_ThrowsNullReferenceException()
+ {
+ using (PathGradientBrush brush = new PathGradientBrush(_defaultFloatPoints))
+ {
+ Assert.Throws<NullReferenceException>(() => brush.Blend = null);
+ Assert.Throws<NullReferenceException>(() => brush.Blend = new Blend() { Factors = null, Positions = null});
+ Assert.Throws<NullReferenceException>(() => brush.Blend = new Blend() { Factors = null, Positions = new float[0] });
+ }
+ }
+
+ [ConditionalFact(nameof(PlatformDetection) + "." + nameof(PlatformDetection.IsNotWindowsNanoServer))]
+ public void Blend_NullBlendProperites_ThrowsArgumentNullException()
+ {
+ using (PathGradientBrush brush = new PathGradientBrush(_defaultFloatPoints))
+ {
+ AssertExtensions.Throws<ArgumentNullException>("source", () =>
+ brush.Blend = new Blend() { Factors = new float[0], Positions = null });
+ }
+ }
+
+ [ConditionalTheory(nameof(PlatformDetection) + "." + nameof(PlatformDetection.IsNotWindowsNanoServer))]
+ [InlineData(1f)]
+ [InlineData(0f)]
+ [InlineData(0.5f)]
+ public void SetSigmaBellShape_Focus_Success(float focus)
+ {
+ float defaultScale = 1f;
+
+ using (PathGradientBrush brush = new PathGradientBrush(_defaultFloatPoints))
+ {
+ brush.SetSigmaBellShape(focus);
+ Assert.True(brush.Transform.IsIdentity);
+ if (focus == 0f)
+ {
+ Assert.Equal(focus, brush.Blend.Positions[0]);
+ Assert.Equal(defaultScale, brush.Blend.Factors[0]);
+ Assert.Equal(1f, brush.Blend.Positions[brush.Blend.Positions.Length - 1]);
+ Assert.Equal(0f, brush.Blend.Factors[brush.Blend.Factors.Length - 1]);
+ }
+ else if (focus == 1f)
+ {
+ Assert.Equal(0f, brush.Blend.Positions[0]);
+ Assert.Equal(0f, brush.Blend.Factors[0]);
+ Assert.Equal(focus, brush.Blend.Positions[brush.Blend.Positions.Length - 1]);
+ Assert.Equal(defaultScale, brush.Blend.Factors[brush.Blend.Factors.Length - 1]);
+ }
+ else
+ {
+ Assert.Equal(0f, brush.Blend.Positions[0]);
+ Assert.Equal(0f, brush.Blend.Factors[0]);
+ Assert.Equal(1f, brush.Blend.Positions[brush.Blend.Positions.Length - 1]);
+ Assert.Equal(0f, brush.Blend.Factors[brush.Blend.Factors.Length - 1]);
+ }
+ }
+ }
+
+ [ConditionalTheory(nameof(PlatformDetection) + "." + nameof(PlatformDetection.IsNotWindowsNanoServer))]
+ [InlineData(1f, 1f)]
+ [InlineData(0f, 1f)]
+ [InlineData(0.5f, 1f)]
+ [InlineData(1f, 0f)]
+ [InlineData(0f, 0f)]
+ [InlineData(0.5f, 0f)]
+ [InlineData(1f, 0.5f)]
+ [InlineData(0f, 0.5f)]
+ [InlineData(0.5f, 0.5f)]
+ public void SetSigmaBellShape_FocusScale_Success(float focus, float scale)
+ {
+ using (PathGradientBrush brush = new PathGradientBrush(_defaultFloatPoints))
+ {
+ brush.SetSigmaBellShape(focus);
+ Assert.True(brush.Transform.IsIdentity);
+ if (focus == 0f)
+ {
+ Assert.Equal(256, brush.Blend.Positions.Length);
+ Assert.Equal(256, brush.Blend.Factors.Length);
+ Assert.Equal(focus, brush.Blend.Positions[0]);
+ Assert.Equal(1f, brush.Blend.Factors[0]);
+ Assert.Equal(1f, brush.Blend.Positions[brush.Blend.Positions.Length - 1]);
+ Assert.Equal(0f, brush.Blend.Factors[brush.Blend.Factors.Length - 1]);
+ }
+ else if (focus == 1f)
+ {
+ Assert.Equal(256, brush.Blend.Positions.Length);
+ Assert.Equal(256, brush.Blend.Factors.Length);
+ Assert.Equal(0f, brush.Blend.Positions[0]);
+ Assert.Equal(0f, brush.Blend.Factors[0]);
+ Assert.Equal(focus, brush.Blend.Positions[brush.Blend.Positions.Length - 1]);
+ Assert.Equal(1f, brush.Blend.Factors[brush.Blend.Factors.Length - 1]);
+ }
+ else
+ {
+ Assert.Equal(511, brush.Blend.Positions.Length);
+ Assert.Equal(511, brush.Blend.Factors.Length);
+ Assert.Equal(0f, brush.Blend.Positions[0]);
+ Assert.Equal(0f, brush.Blend.Factors[0]);
+ Assert.Equal(focus, brush.Blend.Positions[255]);
+ Assert.Equal(1f, brush.Blend.Factors[255]);
+ Assert.Equal(1f, brush.Blend.Positions[brush.Blend.Positions.Length - 1]);
+ Assert.Equal(0f, brush.Blend.Factors[brush.Blend.Factors.Length - 1]);
+ }
+ }
+ }
+
+ [ConditionalFact(nameof(PlatformDetection) + "." + nameof(PlatformDetection.IsNotWindowsNanoServer))]
+ public void SetSigmaBellShape_Disposed_ThrowsArgumentException()
+ {
+ PathGradientBrush brush = new PathGradientBrush(_defaultFloatPoints);
+ brush.Dispose();
+
+ AssertExtensions.Throws<ArgumentException>(null, () => brush.SetSigmaBellShape(1f));
+ AssertExtensions.Throws<ArgumentException>(null, () => brush.SetSigmaBellShape(1f, 1f));
+ }
+
+ [ConditionalTheory(nameof(PlatformDetection) + "." + nameof(PlatformDetection.IsNotWindowsNanoServer))]
+ [InlineData(-1)]
+ [InlineData(1.1f)]
+ public void SetSigmaBellShape_InvalidFocus_ThrowsArgumentException(float focus)
+ {
+ using (PathGradientBrush brush = new PathGradientBrush(_defaultFloatPoints))
+ {
+ AssertExtensions.Throws<ArgumentException>(null, () => brush.SetSigmaBellShape(focus));
+ AssertExtensions.Throws<ArgumentException>(null, () => brush.SetSigmaBellShape(focus, 1f));
+ }
+ }
+
+ [ConditionalTheory(nameof(PlatformDetection) + "." + nameof(PlatformDetection.IsNotWindowsNanoServer))]
+ [InlineData(-1)]
+ [InlineData(1.1f)]
+ public void SetSigmaBellShape_InvalidScale_ThrowsArgumentException(float scale)
+ {
+ using (PathGradientBrush brush = new PathGradientBrush(_defaultFloatPoints))
+ {
+ AssertExtensions.Throws<ArgumentException>(null, () => brush.SetSigmaBellShape(1f, scale));
+ }
+ }
+
+ [ConditionalTheory(nameof(PlatformDetection) + "." + nameof(PlatformDetection.IsNotWindowsNanoServer))]
+ [InlineData(1f)]
+ [InlineData(0f)]
+ [InlineData(0.5f)]
+ public void SetBlendTriangularShape_Focus_Success(float focus)
+ {
+ float defaultScale = 1f;
+
+ using (PathGradientBrush brush = new PathGradientBrush(_defaultFloatPoints))
+ {
+ brush.SetBlendTriangularShape(focus);
+ Assert.True(brush.Transform.IsIdentity);
+ if (focus == 0f)
+ {
+ Assert.Equal(new float[2] { defaultScale, 0f }, brush.Blend.Factors);
+ Assert.Equal(new float[2] { focus, 1f }, brush.Blend.Positions);
+ }
+ else if (focus == 1f)
+ {
+ Assert.Equal(new float[2] { 0f, defaultScale }, brush.Blend.Factors);
+ Assert.Equal(new float[2] { 0f, focus }, brush.Blend.Positions);
+ }
+ else
+ {
+ Assert.Equal(new float[3] { 0f, defaultScale, 0f }, brush.Blend.Factors);
+ Assert.Equal(new float[3] { 0f, focus, 1f }, brush.Blend.Positions);
+ }
+ }
+ }
+
+ [ConditionalTheory(nameof(PlatformDetection) + "." + nameof(PlatformDetection.IsNotWindowsNanoServer))]
+ [InlineData(1f, 1f)]
+ [InlineData(0f, 1f)]
+ [InlineData(0.5f, 1f)]
+ [InlineData(1f, 0f)]
+ [InlineData(0f, 0f)]
+ [InlineData(0.5f, 0f)]
+ [InlineData(1f, 0.5f)]
+ [InlineData(0f, 0.5f)]
+ [InlineData(0.5f, 0.5f)]
+ public void SetBlendTriangularShape_FocusScale_Success(float focus, float scale)
+ {
+ using (PathGradientBrush brush = new PathGradientBrush(_defaultFloatPoints))
+ {
+ brush.SetBlendTriangularShape(focus);
+ Assert.True(brush.Transform.IsIdentity);
+ Assert.True(brush.Transform.IsIdentity);
+ if (focus == 0f)
+ {
+ Assert.Equal(new float[2] { 1f, 0f }, brush.Blend.Factors);
+ Assert.Equal(new float[2] { focus, 1f }, brush.Blend.Positions);
+ }
+ else if (focus == 1f)
+ {
+ Assert.Equal(new float[2] { 0f, 1f }, brush.Blend.Factors);
+ Assert.Equal(new float[2] { 0f, focus }, brush.Blend.Positions);
+ }
+ else
+ {
+ Assert.Equal(new float[3] { 0f, 1f, 0f }, brush.Blend.Factors);
+ Assert.Equal(new float[3] { 0f, focus, 1f }, brush.Blend.Positions);
+ }
+ }
+ }
+
+ [ConditionalFact(nameof(PlatformDetection) + "." + nameof(PlatformDetection.IsNotWindowsNanoServer))]
+ public void SetBlendTriangularShape_Disposed_ThrowsArgumentException()
+ {
+ PathGradientBrush brush = new PathGradientBrush(_defaultFloatPoints);
+ brush.Dispose();
+
+ AssertExtensions.Throws<ArgumentException>(null, () => brush.SetBlendTriangularShape(1f));
+ AssertExtensions.Throws<ArgumentException>(null, () => brush.SetBlendTriangularShape(1f, 1f));
+ }
+
+ [ConditionalTheory(nameof(PlatformDetection) + "." + nameof(PlatformDetection.IsNotWindowsNanoServer))]
+ [InlineData(-1)]
+ [InlineData(1.1f)]
+ public void SetBlendTriangularShape_InvalidFocus_ThrowsArgumentException(float focus)
+ {
+ using (PathGradientBrush brush = new PathGradientBrush(_defaultFloatPoints))
+ {
+ AssertExtensions.Throws<ArgumentException>(null, () => brush.SetBlendTriangularShape(focus));
+ AssertExtensions.Throws<ArgumentException>(null, () => brush.SetBlendTriangularShape(focus, 1f));
+ }
+ }
+
+ [ConditionalTheory(nameof(PlatformDetection) + "." + nameof(PlatformDetection.IsNotWindowsNanoServer))]
+ [InlineData(-1)]
+ [InlineData(1.1f)]
+ public void SetBlendTriangularShape_InvalidScale_ThrowsArgumentException(float scale)
+ {
+ using (PathGradientBrush brush = new PathGradientBrush(_defaultFloatPoints))
+ {
+ AssertExtensions.Throws<ArgumentException>(null, () => brush.SetBlendTriangularShape(1f, scale));
+ }
+ }
+
+ [ConditionalFact(nameof(PlatformDetection) + "." + nameof(PlatformDetection.IsNotWindowsNanoServer))]
+ public void InterpolationColors_ReturnsExpected()
+ {
+ Color[] expectedColors = new Color[2] { Color.FromArgb(255, 0, 0, 255), Color.FromArgb(255, 255, 0, 0) };
+ float[] expectedPositions = new float[] { 0, 1 };
+ Color[] sameColors = new Color[2] { Color.FromArgb(255, 255, 255, 0), Color.FromArgb(255, 255, 255, 0) };
+
+ using (PathGradientBrush brush = new PathGradientBrush(_defaultFloatPoints))
+ {
+ brush.InterpolationColors = new ColorBlend() { Colors = expectedColors, Positions = expectedPositions };
+ Assert.Equal(expectedColors, brush.InterpolationColors.Colors);
+ Assert.Equal(expectedPositions, brush.InterpolationColors.Positions);
+
+ brush.InterpolationColors = new ColorBlend() { Colors = sameColors, Positions = expectedPositions };
+ Assert.Equal(sameColors, brush.InterpolationColors.Colors);
+ Assert.Equal(expectedPositions, brush.InterpolationColors.Positions);
+ }
+ }
+
+ [ConditionalFact(nameof(PlatformDetection) + "." + nameof(PlatformDetection.IsNotWindowsNanoServer))]
+ public void InterpolationColors_CannotChange()
+ {
+ Color[] colors = new Color[2] { Color.FromArgb(255, 0, 0, 255), Color.FromArgb(255, 255, 0, 0) };
+ Color[] defaultColors = new Color[1] { Color.Empty };
+
+ using (PathGradientBrush brush = new PathGradientBrush(_defaultFloatPoints))
+ {
+ brush.InterpolationColors.Colors.ToList().AddRange(colors);
+ Assert.Equal(defaultColors, brush.InterpolationColors.Colors);
+ brush.InterpolationColors.Colors = colors;
+ Assert.Equal(defaultColors, brush.InterpolationColors.Colors);
+ brush.InterpolationColors.Colors[0] = Color.Pink;
+ Assert.NotEqual(Color.Pink, brush.InterpolationColors.Colors[0]);
+ Assert.Equal(defaultColors, brush.InterpolationColors.Colors);
+ brush.InterpolationColors.Positions = new float[0];
+ Assert.Equal(1, brush.InterpolationColors.Positions.Length);
+ brush.InterpolationColors.Positions = new float[2];
+ Assert.Equal(1, brush.InterpolationColors.Positions.Length);
+ }
+ }
+
+ [ConditionalFact(nameof(PlatformDetection) + "." + nameof(PlatformDetection.IsNotWindowsNanoServer))]
+ public void InterpolationColors_Disposed_ThrowsArgumentException()
+ {
+ PathGradientBrush brush = new PathGradientBrush(_defaultFloatPoints);
+ brush.Dispose();
+
+ AssertExtensions.Throws<ArgumentException>(null, () => brush.InterpolationColors);
+ }
+
+ [ConditionalFact(nameof(PlatformDetection) + "." + nameof(PlatformDetection.IsNotWindowsNanoServer))]
+ public void InterpolationColors_Null_ThrowsNullReferenceException()
+ {
+ using (PathGradientBrush brush = new PathGradientBrush(_defaultFloatPoints))
+ {
+ Assert.Throws<NullReferenceException>(() => brush.InterpolationColors = null);
+ }
+ }
+
+ [ConditionalFact(nameof(PlatformDetection) + "." + nameof(PlatformDetection.IsNotWindowsNanoServer))]
+ public void InterpolationColors_NullColors_ThrowsNullReferenceException()
+ {
+ using (PathGradientBrush brush = new PathGradientBrush(_defaultFloatPoints))
+ {
+ Assert.Throws<NullReferenceException>(() =>
+ brush.InterpolationColors = new ColorBlend() { Colors = null, Positions = null });
+
+ Assert.Throws<NullReferenceException>(() =>
+ brush.InterpolationColors = new ColorBlend() { Colors = null, Positions = new float[2] });
+ }
+ }
+
+ [ConditionalFact(nameof(PlatformDetection) + "." + nameof(PlatformDetection.IsNotWindowsNanoServer))]
+ public void InterpolationColors_NullPoints_ArgumentNullException()
+ {
+ using (PathGradientBrush brush = new PathGradientBrush(_defaultFloatPoints))
+ {
+ AssertExtensions.Throws<ArgumentNullException>("source", () =>
+ brush.InterpolationColors = new ColorBlend() { Colors = new Color[1], Positions = null });
+ }
+ }
+
+ [ConditionalFact(nameof(PlatformDetection) + "." + nameof(PlatformDetection.IsNotWindowsNanoServer))]
+ public void InterpolationColors_Empty_ArgumentException()
+ {
+ using (PathGradientBrush brush = new PathGradientBrush(_defaultFloatPoints))
+ {
+ AssertExtensions.Throws<ArgumentException>(null, () => brush.InterpolationColors = new ColorBlend());
+ }
+ }
+
+ [ConditionalFact(nameof(PlatformDetection) + "." + nameof(PlatformDetection.IsNotWindowsNanoServer))]
+ public void InterpolationColors_EmptyColors_ArgumentException()
+ {
+ using (PathGradientBrush brush = new PathGradientBrush(_defaultFloatPoints))
+ {
+ AssertExtensions.Throws<ArgumentException>(null, () =>
+ brush.InterpolationColors = new ColorBlend() { Colors = new Color[0], Positions = new float[0] });
+ }
+ }
+
+ [ConditionalFact(nameof(PlatformDetection) + "." + nameof(PlatformDetection.IsNotWindowsNanoServer))]
+ public void InterpolationColors_PointsLengthGreaterThenColorsLength_ArgumentException()
+ {
+ using (PathGradientBrush brush = new PathGradientBrush(_defaultFloatPoints))
+ {
+ AssertExtensions.Throws<ArgumentException>(null, () =>
+ brush.InterpolationColors = new ColorBlend() { Colors = new Color[1], Positions = new float[2] });
+ }
+ }
+
+ [ConditionalFact(nameof(PlatformDetection) + "." + nameof(PlatformDetection.IsNotWindowsNanoServer))]
+ public void InterpolationColors_ColorsLengthGreaterThenPointsLength_ThrowsArgumentOutOfRangeException()
+ {
+ using (PathGradientBrush brush = new PathGradientBrush(_defaultFloatPoints))
+ {
+ Assert.Throws<ArgumentOutOfRangeException>(() =>
+ brush.InterpolationColors = new ColorBlend() { Colors = new Color[2], Positions = new float[1] });
+ }
+ }
+
+ [ConditionalFact(nameof(PlatformDetection) + "." + nameof(PlatformDetection.IsNotWindowsNanoServer))]
+ public void Transform_ReturnsExpected()
+ {
+ using (PathGradientBrush brush = new PathGradientBrush(_defaultFloatPoints))
+ using (Matrix defaultMatrix = new Matrix(1, 0, 0, 1, 0, 0))
+ using (Matrix matrix = new Matrix(1, 0, 0, 1, 1, 1))
+ {
+ Assert.Equal(defaultMatrix, brush.Transform);
+ brush.Transform = matrix;
+ Assert.Equal(matrix, brush.Transform);
+ }
+ }
+
+ [ConditionalFact(nameof(PlatformDetection) + "." + nameof(PlatformDetection.IsNotWindowsNanoServer))]
+ public void Transform_EmptyMatrix_ReturnsExpected()
+ {
+ using (PathGradientBrush brush = new PathGradientBrush(_defaultFloatPoints))
+ using (Matrix matrix = new Matrix())
+ {
+ brush.Transform = matrix;
+ Assert.True(brush.Transform.IsIdentity);
+ }
+ }
+
+ [ConditionalFact(nameof(PlatformDetection) + "." + nameof(PlatformDetection.IsNotWindowsNanoServer))]
+ public void Transform_Disposed_ThrowsArgumentException()
+ {
+ PathGradientBrush brush = new PathGradientBrush(_defaultFloatPoints);
+ brush.Dispose();
+
+ AssertExtensions.Throws<ArgumentException>(null, () => brush.Transform);
+ }
+
+ [ConditionalFact(nameof(PlatformDetection) + "." + nameof(PlatformDetection.IsNotWindowsNanoServer))]
+ public void Transform_Null_ArgumentNullException()
+ {
+ using (PathGradientBrush brush = new PathGradientBrush(_defaultFloatPoints))
+ {
+ AssertExtensions.Throws<ArgumentNullException>("matrix", () => brush.Transform = null);
+ }
+ }
+
+ [ConditionalFact(nameof(PlatformDetection) + "." + nameof(PlatformDetection.IsNotWindowsNanoServer))]
+ public void Transform_NonInvertible_ArgumentException()
+ {
+ using (PathGradientBrush brush = new PathGradientBrush(_defaultFloatPoints))
+ using (Matrix nonInvertible = new Matrix(123, 24, 82, 16, 47, 30))
+ {
+ AssertExtensions.Throws<ArgumentException>(null, () => brush.Transform = nonInvertible);
+ }
+ }
+
+ [ConditionalFact(nameof(PlatformDetection) + "." + nameof(PlatformDetection.IsNotWindowsNanoServer))]
+ public void ResetTransform_Success()
+ {
+ using (PathGradientBrush brush = new PathGradientBrush(_defaultFloatPoints))
+ using (Matrix defaultMatrix = new Matrix(1, 0, 0, 1, 0, 0))
+ using (Matrix matrix = new Matrix(1, 0, 0, 1, 1, 1))
+ {
+ Assert.Equal(defaultMatrix, brush.Transform);
+ brush.Transform = matrix;
+ Assert.Equal(matrix, brush.Transform);
+ brush.ResetTransform();
+ Assert.Equal(defaultMatrix, brush.Transform);
+ }
+ }
+
+ [ConditionalFact(nameof(PlatformDetection) + "." + nameof(PlatformDetection.IsNotWindowsNanoServer))]
+ public void ResetTransform_Disposed_ThrowsArgumentException()
+ {
+ PathGradientBrush brush = new PathGradientBrush(_defaultFloatPoints);
+ brush.Dispose();
+
+ AssertExtensions.Throws<ArgumentException>(null, () => brush.ResetTransform());
+ }
+
+ [ConditionalFact(nameof(PlatformDetection) + "." + nameof(PlatformDetection.IsNotWindowsNanoServer))]
+ public void MultiplyTransform_Matrix_Success()
+ {
+ using (PathGradientBrush brush = new PathGradientBrush(_defaultFloatPoints))
+ using (Matrix defaultMatrix = new Matrix(1, 0, 0, 1, 0, 0))
+ using (Matrix matrix = new Matrix(1, 0, 0, 1, 1, 1))
+ {
+ defaultMatrix.Multiply(matrix, MatrixOrder.Prepend);
+ brush.MultiplyTransform(matrix);
+ Assert.Equal(defaultMatrix, brush.Transform);
+ }
+ }
+
+ [ConditionalTheory(nameof(PlatformDetection) + "." + nameof(PlatformDetection.IsNotWindowsNanoServer))]
+ [InlineData(MatrixOrder.Append)]
+ [InlineData(MatrixOrder.Prepend)]
+ public void MultiplyTransform_MatrixMatrixOrder_Success(MatrixOrder matrixOrder)
+ {
+ using (PathGradientBrush brush = new PathGradientBrush(_defaultFloatPoints))
+ using (Matrix defaultMatrix = new Matrix(1, 0, 0, 1, 0, 0))
+ using (Matrix matrix = new Matrix(1, 0, 0, 1, 1, 1))
+ {
+ defaultMatrix.Multiply(matrix, matrixOrder);
+ brush.MultiplyTransform(matrix, matrixOrder);
+ Assert.Equal(defaultMatrix, brush.Transform);
+ }
+ }
+
+ [ConditionalFact(nameof(PlatformDetection) + "." + nameof(PlatformDetection.IsNotWindowsNanoServer))]
+ public void MultiplyTransform_Disposed_ThrowsArgumentException()
+ {
+ using (Matrix matrix = new Matrix(1, 0, 0, 1, 1, 1))
+ {
+ PathGradientBrush brush = new PathGradientBrush(_defaultFloatPoints);
+ brush.Dispose();
+
+ AssertExtensions.Throws<ArgumentException>(null, () => brush.MultiplyTransform(matrix, MatrixOrder.Append));
+ }
+ }
+
+ [ConditionalFact(nameof(PlatformDetection) + "." + nameof(PlatformDetection.IsNotWindowsNanoServer))]
+ public void MultiplyTransform_Null_ArgumentNullException()
+ {
+ using (PathGradientBrush brush = new PathGradientBrush(_defaultFloatPoints))
+ {
+ AssertExtensions.Throws<ArgumentNullException>("matrix", () => brush.MultiplyTransform(null));
+ AssertExtensions.Throws<ArgumentNullException>("matrix", () => brush.MultiplyTransform(null, MatrixOrder.Append));
+ }
+ }
+
+ [ConditionalFact(nameof(PlatformDetection) + "." + nameof(PlatformDetection.IsNotWindowsNanoServer))]
+ public void MultiplyTransform_InvalidMatrixOrder_ArgumentException()
+ {
+ using (PathGradientBrush brush = new PathGradientBrush(_defaultFloatPoints))
+ using (Matrix matrix = new Matrix(1, 1, 1, 1, 1, 1))
+ {
+ AssertExtensions.Throws<ArgumentException>(null, () => brush.MultiplyTransform(matrix, (MatrixOrder)int.MinValue));
+ }
+ }
+
+ [ConditionalFact(nameof(PlatformDetection) + "." + nameof(PlatformDetection.IsNotWindowsNanoServer))]
+ public void MultiplyTransform_NonInvertible_ArgumentException()
+ {
+ using (PathGradientBrush brush = new PathGradientBrush(_defaultFloatPoints))
+ using (Matrix nonInvertible = new Matrix(123, 24, 82, 16, 47, 30))
+ {
+ AssertExtensions.Throws<ArgumentException>(null, () => brush.MultiplyTransform(nonInvertible));
+ AssertExtensions.Throws<ArgumentException>(null, () => brush.MultiplyTransform(nonInvertible, MatrixOrder.Append));
+ }
+ }
+
+ [ConditionalFact(nameof(PlatformDetection) + "." + nameof(PlatformDetection.IsNotWindowsNanoServer))]
+ public void TranslateTransform_Offset_Success()
+ {
+ using (PathGradientBrush brush = new PathGradientBrush(_defaultFloatPoints))
+ using (Matrix matrix = new Matrix(1, 0, 0, 1, 0, 0))
+ {
+ matrix.Translate(20f, 30f, MatrixOrder.Prepend);
+ brush.TranslateTransform(20f, 30f);
+ Assert.Equal(matrix, brush.Transform);
+ }
+ }
+
+ [ConditionalTheory(nameof(PlatformDetection) + "." + nameof(PlatformDetection.IsNotWindowsNanoServer))]
+ [InlineData(MatrixOrder.Append)]
+ [InlineData(MatrixOrder.Prepend)]
+ public void TranslateTransform_OffsetMatrixOrder_Success(MatrixOrder matrixOrder)
+ {
+ using (PathGradientBrush brush = new PathGradientBrush(_defaultFloatPoints))
+ using (Matrix matrix = new Matrix(1, 0, 0, 1, 0, 0))
+ {
+ matrix.Translate(20f, 30f, matrixOrder);
+ brush.TranslateTransform(20f, 30f, matrixOrder);
+ Assert.Equal(matrix, brush.Transform);
+ }
+ }
+
+ [ConditionalFact(nameof(PlatformDetection) + "." + nameof(PlatformDetection.IsNotWindowsNanoServer))]
+ public void TranslateTransform_Disposed_ThrowsArgumentException()
+ {
+ PathGradientBrush brush = new PathGradientBrush(_defaultFloatPoints);
+ brush.Dispose();
+
+ AssertExtensions.Throws<ArgumentException>(null, () => brush.TranslateTransform(20f, 30f, MatrixOrder.Append));
+ }
+
+ [ConditionalFact(nameof(PlatformDetection) + "." + nameof(PlatformDetection.IsNotWindowsNanoServer))]
+ public void TranslateTransform_InvalidMatrixOrder_ArgumentException()
+ {
+ using (PathGradientBrush brush = new PathGradientBrush(_defaultFloatPoints))
+ {
+ AssertExtensions.Throws<ArgumentException>(null, () => brush.TranslateTransform(20f, 30f, (MatrixOrder)int.MinValue));
+ }
+ }
+
+ [ConditionalFact(nameof(PlatformDetection) + "." + nameof(PlatformDetection.IsNotWindowsNanoServer))]
+ public void ScaleTransform_Scale_Success()
+ {
+ using (PathGradientBrush brush = new PathGradientBrush(_defaultFloatPoints))
+ using (Matrix matrix = new Matrix(1, 0, 0, 1, 0, 0))
+ {
+ matrix.Scale(2, 4, MatrixOrder.Prepend);
+ brush.ScaleTransform(2, 4);
+ Assert.Equal(matrix, brush.Transform);
+
+ matrix.Scale(0.5f, 0.25f, MatrixOrder.Prepend);
+ brush.ScaleTransform(0.5f, 0.25f);
+ Assert.True(brush.Transform.IsIdentity);
+
+ matrix.Scale(float.MaxValue, float.MinValue, MatrixOrder.Prepend);
+ brush.ScaleTransform(float.MaxValue, float.MinValue);
+ Assert.Equal(matrix, brush.Transform);
+
+ matrix.Scale(float.MinValue, float.MaxValue, MatrixOrder.Prepend);
+ brush.ScaleTransform(float.MinValue, float.MaxValue);
+ Assert.Equal(matrix, brush.Transform);
+ }
+ }
+
+ [ConditionalTheory(nameof(PlatformDetection) + "." + nameof(PlatformDetection.IsNotWindowsNanoServer))]
+ [InlineData(MatrixOrder.Append)]
+ [InlineData(MatrixOrder.Prepend)]
+ public void ScaleTransform_ScaleMatrixOrder_Success(MatrixOrder matrixOrder)
+ {
+ using (PathGradientBrush brush = new PathGradientBrush(_defaultFloatPoints))
+ using (Matrix matrix = new Matrix(1, 0, 0, 1, 0, 0))
+ {
+ matrix.Scale(0.25f, 2, matrixOrder);
+ brush.ScaleTransform(0.25f, 2, matrixOrder);
+ Assert.Equal(matrix, brush.Transform);
+ }
+ }
+
+ [ConditionalFact(nameof(PlatformDetection) + "." + nameof(PlatformDetection.IsNotWindowsNanoServer))]
+ public void ScaleTransform_Disposed_ThrowsArgumentException()
+ {
+ PathGradientBrush brush = new PathGradientBrush(_defaultFloatPoints);
+ brush.Dispose();
+
+ AssertExtensions.Throws<ArgumentException>(null, () => brush.ScaleTransform(0.25f, 2, MatrixOrder.Append));
+ }
+
+ [ConditionalFact(nameof(PlatformDetection) + "." + nameof(PlatformDetection.IsNotWindowsNanoServer))]
+ public void ScaleTransform_InvalidMatrixOrder_ArgumentException()
+ {
+ using (PathGradientBrush brush = new PathGradientBrush(_defaultFloatPoints))
+ {
+ AssertExtensions.Throws<ArgumentException>(null, () => brush.ScaleTransform(1, 1, (MatrixOrder)int.MinValue));
+ }
+ }
+
+ [ConditionalFact(nameof(PlatformDetection) + "." + nameof(PlatformDetection.IsNotWindowsNanoServer))]
+ public void RotateTransform_Angle_Success()
+ {
+ using (PathGradientBrush brush = new PathGradientBrush(_defaultFloatPoints))
+ using (Matrix matrix = new Matrix(1, 0, 0, 1, 0, 0))
+ {
+ matrix.Rotate(90, MatrixOrder.Prepend);
+ brush.RotateTransform(90);
+ Assert.Equal(matrix, brush.Transform);
+
+ brush.RotateTransform(270);
+ Assert.True(brush.Transform.IsIdentity);
+ }
+ }
+
+ [ConditionalTheory(nameof(PlatformDetection) + "." + nameof(PlatformDetection.IsNotWindowsNanoServer))]
+ [InlineData(MatrixOrder.Append)]
+ [InlineData(MatrixOrder.Prepend)]
+ public void RotateTransform_AngleMatrixOrder_Success(MatrixOrder matrixOrder)
+ {
+ using (PathGradientBrush brush = new PathGradientBrush(_defaultFloatPoints))
+ using (Matrix matrix = new Matrix(1, 0, 0, 1, 0, 0))
+ {
+ matrix.Rotate(45, matrixOrder);
+ brush.RotateTransform(45, matrixOrder);
+ Assert.Equal(matrix, brush.Transform);
+ }
+ }
+
+ [ConditionalFact(nameof(PlatformDetection) + "." + nameof(PlatformDetection.IsNotWindowsNanoServer))]
+ public void RotateTransform_Disposed_ThrowsArgumentException()
+ {
+ PathGradientBrush brush = new PathGradientBrush(_defaultFloatPoints);
+ brush.Dispose();
+
+ AssertExtensions.Throws<ArgumentException>(null, () => brush.RotateTransform(45, MatrixOrder.Append));
+ }
+
+ [ConditionalFact(nameof(PlatformDetection) + "." + nameof(PlatformDetection.IsNotWindowsNanoServer))]
+ public void RotateTransform_InvalidMatrixOrder_ArgumentException()
+ {
+ using (PathGradientBrush brush = new PathGradientBrush(_defaultFloatPoints))
+ {
+ AssertExtensions.Throws<ArgumentException>(null, () => brush.RotateTransform(45, (MatrixOrder)int.MinValue));
+ }
+ }
+
+ [ConditionalFact(nameof(PlatformDetection) + "." + nameof(PlatformDetection.IsNotWindowsNanoServer))]
+ public void FocusScales_ReturnsExpected()
+ {
+ var point = new PointF(2.5f, 3.4f);
+
+ using (PathGradientBrush brush = new PathGradientBrush(_defaultFloatPoints))
+ {
+ brush.FocusScales = point;
+ Assert.Equal(point, brush.FocusScales);
+ }
+ }
+
+ [ConditionalFact(nameof(PlatformDetection) + "." + nameof(PlatformDetection.IsNotWindowsNanoServer))]
+ public void FocusScales_Disposed_ThrowsArgumentException()
+ {
+ PathGradientBrush brush = new PathGradientBrush(_defaultFloatPoints);
+ brush.Dispose();
+
+ AssertExtensions.Throws<ArgumentException>(null, () => brush.FocusScales);
+ }
+
+ [ConditionalTheory(nameof(PlatformDetection) + "." + nameof(PlatformDetection.IsNotWindowsNanoServer))]
+ [MemberData(nameof(WrapMode_TestData))]
+ public void WrapMode_ReturnsExpected(WrapMode wrapMode)
+ {
+ using (PathGradientBrush brush = new PathGradientBrush(_defaultFloatPoints))
+ {
+ brush.WrapMode = wrapMode;
+ Assert.Equal(wrapMode, brush.WrapMode);
+ }
+ }
+
+ [ConditionalFact(nameof(PlatformDetection) + "." + nameof(PlatformDetection.IsNotWindowsNanoServer))]
+ public void WrapMode_Disposed_ThrowsArgumentException()
+ {
+ PathGradientBrush brush = new PathGradientBrush(_defaultFloatPoints);
+ brush.Dispose();
+
+ AssertExtensions.Throws<ArgumentException>(null, () => brush.WrapMode);
+ }
+
+ [ConditionalFact(nameof(PlatformDetection) + "." + nameof(PlatformDetection.IsNotWindowsNanoServer))]
+ public void WrapMode_Invalid_InvalidEnumArgumentException()
+ {
+ using (PathGradientBrush brush = new PathGradientBrush(_defaultFloatPoints))
+ {
+ AssertExtensions.Throws<InvalidEnumArgumentException>("value", () => brush.WrapMode = (WrapMode)int.MinValue);
+ }
+ }
+
+ private void AssertDefaults(PathGradientBrush brush)
+ {
+ Assert.Equal(_defaultRectangle, brush.Rectangle);
+ Assert.Equal(new float[] { 1 }, brush.Blend.Factors);
+ Assert.Equal(1, brush.Blend.Positions.Length);
+ Assert.Equal(new PointF(10.5f, 16f), brush.CenterPoint);
+ Assert.Equal(new Color[] { Color.Empty }, brush.InterpolationColors.Colors);
+ Assert.Equal(new Color[] { Color.FromArgb(255, 255, 255, 255) }, brush.SurroundColors);
+ Assert.Equal(new float[] { 0 }, brush.InterpolationColors.Positions);
+ Assert.True(brush.Transform.IsIdentity);
+ Assert.True(brush.FocusScales.IsEmpty);
+ }
+ }
+}
diff --git a/src/System.Drawing.Common/tests/FontTests.cs b/src/System.Drawing.Common/tests/FontTests.cs
index f6e4cc75ad..725adeadee 100644
--- a/src/System.Drawing.Common/tests/FontTests.cs
+++ b/src/System.Drawing.Common/tests/FontTests.cs
@@ -1,12 +1,294 @@
// Licensed to the .NET Foundation under one or more agreements.
// See the LICENSE file in the project root for more information.
+using System.Collections.Generic;
+using System.Drawing.Text;
+using System.Runtime.InteropServices;
using Xunit;
namespace System.Drawing.Tests
{
public class FontTests
{
+ public static IEnumerable<object[]> Ctor_Family_Size_TestData()
+ {
+ yield return new object[] { FontFamily.GenericMonospace, 1 };
+ yield return new object[] { FontFamily.GenericSerif, float.MaxValue };
+ }
+
+ [ConditionalTheory(nameof(PlatformDetection) + "." + nameof(PlatformDetection.IsNotWindowsNanoServer))]
+ [MemberData(nameof(Ctor_Family_Size_TestData))]
+ public void Ctor_Family_Size(FontFamily fontFamily, float emSize)
+ {
+ try
+ {
+ using (var font = new Font(fontFamily, emSize))
+ {
+ VerifyFont(font, fontFamily.Name, emSize, FontStyle.Regular, GraphicsUnit.Point, 1, false);
+ }
+ }
+ finally
+ {
+ fontFamily.Dispose();
+ }
+ }
+
+ [ConditionalTheory(nameof(PlatformDetection) + "." + nameof(PlatformDetection.IsNotWindowsNanoServer))]
+ [MemberData(nameof(Ctor_Family_Size_TestData))]
+ public void Ctor_FamilyName_Size(FontFamily fontFamily, float emSize)
+ {
+ try
+ {
+ using (var font = new Font(fontFamily.Name, emSize))
+ {
+ VerifyFont(font, fontFamily.Name, emSize, FontStyle.Regular, GraphicsUnit.Point, 1, false);
+ }
+ }
+ finally
+ {
+ fontFamily.Dispose();
+ }
+ }
+
+ public static IEnumerable<object[]> Ctor_Family_Size_Style_TestData()
+ {
+ yield return new object[] { FontFamily.GenericMonospace, 1, FontStyle.Bold };
+ yield return new object[] { FontFamily.GenericSerif, 2, FontStyle.Italic };
+ yield return new object[] { FontFamily.GenericSansSerif, 3, FontStyle.Regular };
+ yield return new object[] { FontFamily.GenericSerif, 4, FontStyle.Strikeout };
+ yield return new object[] { FontFamily.GenericSerif, float.MaxValue, FontStyle.Underline };
+ yield return new object[] { FontFamily.GenericSerif, 16, (FontStyle)(-1) };
+ yield return new object[] { FontFamily.GenericSerif, 16, (FontStyle)int.MinValue };
+ yield return new object[] { FontFamily.GenericSerif, 16, (FontStyle)int.MaxValue };
+ }
+
+ [ConditionalTheory(nameof(PlatformDetection) + "." + nameof(PlatformDetection.IsNotWindowsNanoServer))]
+ [MemberData(nameof(Ctor_Family_Size_Style_TestData))]
+ public void Ctor_Family_Size_Style(FontFamily fontFamily, float emSize, FontStyle style)
+ {
+ try
+ {
+ using (var font = new Font(fontFamily, emSize, style))
+ {
+ VerifyFont(font, fontFamily.Name, emSize, style, GraphicsUnit.Point, 1, false);
+ }
+ }
+ finally
+ {
+ fontFamily.Dispose();
+ }
+ }
+
+ [ConditionalTheory(nameof(PlatformDetection) + "." + nameof(PlatformDetection.IsNotWindowsNanoServer))]
+ [MemberData(nameof(Ctor_Family_Size_Style_TestData))]
+ public void Ctor_FamilyName_Size_Style(FontFamily fontFamily, float emSize, FontStyle style)
+ {
+ try
+ {
+ using (var font = new Font(fontFamily.Name, emSize, style))
+ {
+ VerifyFont(font, fontFamily.Name, emSize, style, GraphicsUnit.Point, 1, false);
+ }
+ }
+ finally
+ {
+ fontFamily.Dispose();
+ }
+ }
+
+ public static IEnumerable<object[]> Ctor_Family_Size_Unit_TestData()
+ {
+ yield return new object[] { FontFamily.GenericMonospace, 1, GraphicsUnit.Document };
+ yield return new object[] { FontFamily.GenericSerif, 2, GraphicsUnit.Inch };
+ yield return new object[] { FontFamily.GenericSansSerif, 3, GraphicsUnit.Millimeter };
+ yield return new object[] { FontFamily.GenericSerif, 4, GraphicsUnit.Point };
+ yield return new object[] { FontFamily.GenericSerif, float.MaxValue, GraphicsUnit.Pixel };
+ yield return new object[] { FontFamily.GenericSerif, 16, GraphicsUnit.World };
+ }
+
+ [ConditionalTheory(nameof(PlatformDetection) + "." + nameof(PlatformDetection.IsNotWindowsNanoServer))]
+ [MemberData(nameof(Ctor_Family_Size_Unit_TestData))]
+ public void Ctor_Family_Size_Unit(FontFamily fontFamily, float emSize, GraphicsUnit unit)
+ {
+ try
+ {
+ using (var font = new Font(fontFamily, emSize, unit))
+ {
+ VerifyFont(font, fontFamily.Name, emSize, FontStyle.Regular, unit, 1, false);
+ }
+ }
+ finally
+ {
+ fontFamily.Dispose();
+ }
+ }
+
+ [ConditionalTheory(nameof(PlatformDetection) + "." + nameof(PlatformDetection.IsNotWindowsNanoServer))]
+ [MemberData(nameof(Ctor_Family_Size_Unit_TestData))]
+ public void Ctor_FamilyName_Size_Unit(FontFamily fontFamily, float emSize, GraphicsUnit unit)
+ {
+ try
+ {
+ using (var font = new Font(fontFamily.Name, emSize, unit))
+ {
+ VerifyFont(font, fontFamily.Name, emSize, FontStyle.Regular, unit, 1, false);
+ }
+ }
+ finally
+ {
+ fontFamily.Dispose();
+ }
+ }
+
+ public static IEnumerable<object[]> Ctor_Family_Size_Style_Unit_TestData()
+ {
+ yield return new object[] { FontFamily.GenericMonospace, 1, FontStyle.Bold, GraphicsUnit.Document };
+ yield return new object[] { FontFamily.GenericSerif, 2, FontStyle.Italic, GraphicsUnit.Inch };
+ yield return new object[] { FontFamily.GenericSansSerif, 3, FontStyle.Regular, GraphicsUnit.Millimeter };
+ yield return new object[] { FontFamily.GenericSerif, 4, FontStyle.Strikeout, GraphicsUnit.Point };
+ yield return new object[] { FontFamily.GenericSerif, float.MaxValue, FontStyle.Underline, GraphicsUnit.Pixel };
+ yield return new object[] { FontFamily.GenericSerif, 16, (FontStyle)(-1), GraphicsUnit.World };
+ yield return new object[] { FontFamily.GenericSerif, 16, (FontStyle)int.MinValue, GraphicsUnit.Millimeter };
+ yield return new object[] { FontFamily.GenericSerif, 16, (FontStyle)int.MaxValue, GraphicsUnit.Millimeter };
+ }
+
+ [ConditionalTheory(nameof(PlatformDetection) + "." + nameof(PlatformDetection.IsNotWindowsNanoServer))]
+ [MemberData(nameof(Ctor_Family_Size_Style_Unit_TestData))]
+ public void Ctor_Family_Size_Style_Unit(FontFamily fontFamily, float emSize, FontStyle style, GraphicsUnit unit)
+ {
+ try
+ {
+ using (var font = new Font(fontFamily, emSize, style, unit))
+ {
+ VerifyFont(font, fontFamily.Name, emSize, style, unit, 1, false);
+ }
+ }
+ finally
+ {
+ fontFamily.Dispose();
+ }
+ }
+
+ [ConditionalTheory(nameof(PlatformDetection) + "." + nameof(PlatformDetection.IsNotWindowsNanoServer))]
+ [MemberData(nameof(Ctor_Family_Size_Style_Unit_TestData))]
+ public void Ctor_FamilyName_Size_Style_Unit(FontFamily fontFamily, float emSize, FontStyle style, GraphicsUnit unit)
+ {
+ try
+ {
+ using (var font = new Font(fontFamily.Name, emSize, style, unit))
+ {
+ VerifyFont(font, fontFamily.Name, emSize, style, unit, 1, false);
+ }
+ }
+ finally
+ {
+ fontFamily.Dispose();
+ }
+ }
+
+ public static IEnumerable<object[]> Ctor_Family_Size_Style_Unit_GdiCharSet_TestData()
+ {
+ yield return new object[] { FontFamily.GenericMonospace, 1, FontStyle.Bold, GraphicsUnit.Document, 0 };
+ yield return new object[] { FontFamily.GenericSerif, 2, FontStyle.Italic, GraphicsUnit.Inch, 1 };
+ yield return new object[] { FontFamily.GenericSansSerif, 3, FontStyle.Regular, GraphicsUnit.Millimeter, 255 };
+ yield return new object[] { FontFamily.GenericSerif, 4, FontStyle.Strikeout, GraphicsUnit.Point, 10 };
+ yield return new object[] { FontFamily.GenericSerif, float.MaxValue, FontStyle.Underline, GraphicsUnit.Pixel, 10 };
+ yield return new object[] { FontFamily.GenericSerif, 16, (FontStyle)(-1), GraphicsUnit.World, 8 };
+ yield return new object[] { FontFamily.GenericSerif, 16, (FontStyle)int.MinValue, GraphicsUnit.Millimeter, 127 };
+ yield return new object[] { FontFamily.GenericSerif, 16, (FontStyle)int.MaxValue, GraphicsUnit.Millimeter, 200 };
+ }
+
+ [ConditionalTheory(nameof(PlatformDetection) + "." + nameof(PlatformDetection.IsNotWindowsNanoServer))]
+ [MemberData(nameof(Ctor_Family_Size_Style_Unit_GdiCharSet_TestData))]
+ public void Ctor_Family_Size_Style_Unit_GdiCharSet(FontFamily fontFamily, float emSize, FontStyle style, GraphicsUnit unit, byte gdiCharSet)
+ {
+ try
+ {
+ using (var font = new Font(fontFamily, emSize, style, unit, gdiCharSet))
+ {
+ VerifyFont(font, fontFamily.Name, emSize, style, unit, gdiCharSet, false);
+ }
+ }
+ finally
+ {
+ fontFamily.Dispose();
+ }
+ }
+
+ [ConditionalTheory(nameof(PlatformDetection) + "." + nameof(PlatformDetection.IsNotWindowsNanoServer))]
+ [MemberData(nameof(Ctor_Family_Size_Style_Unit_GdiCharSet_TestData))]
+ public void Ctor_FamilyName_Size_Style_Unit_GdiCharSet(FontFamily fontFamily, float emSize, FontStyle style, GraphicsUnit unit, byte gdiCharSet)
+ {
+ try
+ {
+ using (var font = new Font(fontFamily.Name, emSize, style, unit, gdiCharSet))
+ {
+ VerifyFont(font, fontFamily.Name, emSize, style, unit, gdiCharSet, false);
+ }
+ }
+ finally
+ {
+ fontFamily.Dispose();
+ }
+ }
+
+ public static IEnumerable<object[]> Ctor_Family_Size_Style_Unit_GdiCharSet_GdiVerticalFont_TestData()
+ {
+ yield return new object[] { FontFamily.GenericMonospace, 1, FontStyle.Bold, GraphicsUnit.Document, 0, true };
+ yield return new object[] { FontFamily.GenericSerif, 2, FontStyle.Italic, GraphicsUnit.Inch, 1, false };
+ yield return new object[] { FontFamily.GenericSansSerif, 3, FontStyle.Regular, GraphicsUnit.Millimeter, 255, true };
+ yield return new object[] { FontFamily.GenericSerif, 4, FontStyle.Strikeout, GraphicsUnit.Point, 10, false };
+ yield return new object[] { FontFamily.GenericSerif, float.MaxValue, FontStyle.Underline, GraphicsUnit.Pixel, 10, true };
+ yield return new object[] { FontFamily.GenericSerif, 16, (FontStyle)(-1), GraphicsUnit.World, 8, false };
+ yield return new object[] { FontFamily.GenericSerif, 16, (FontStyle)int.MinValue, GraphicsUnit.Millimeter, 127, true };
+ yield return new object[] { FontFamily.GenericSerif, 16, (FontStyle)int.MaxValue, GraphicsUnit.Millimeter, 200, false };
+ }
+
+ [ConditionalTheory(nameof(PlatformDetection) + "." + nameof(PlatformDetection.IsNotWindowsNanoServer))]
+ [MemberData(nameof(Ctor_Family_Size_Style_Unit_GdiCharSet_GdiVerticalFont_TestData))]
+ public void Ctor_Family_Size_Style_Unit_GdiCharSet_GdiVerticalFont(FontFamily fontFamily, float emSize, FontStyle style, GraphicsUnit unit, byte gdiCharSet, bool gdiVerticalFont)
+ {
+ try
+ {
+ using (var font = new Font(fontFamily, emSize, style, unit, gdiCharSet, gdiVerticalFont))
+ {
+ VerifyFont(font, fontFamily.Name, emSize, style, unit, gdiCharSet, gdiVerticalFont);
+ }
+ }
+ finally
+ {
+ fontFamily.Dispose();
+ }
+ }
+
+ [ConditionalTheory(nameof(PlatformDetection) + "." + nameof(PlatformDetection.IsNotWindowsNanoServer))]
+ [MemberData(nameof(Ctor_Family_Size_Style_Unit_GdiCharSet_GdiVerticalFont_TestData))]
+ public void Ctor_FamilyName_Size_Style_Unit_GdiCharSet_GdiVerticalFont(FontFamily fontFamily, float emSize, FontStyle style, GraphicsUnit unit, byte gdiCharSet, bool gdiVerticalFont)
+ {
+ try
+ {
+ using (var font = new Font(fontFamily.Name, emSize, style, unit, gdiCharSet, gdiVerticalFont))
+ {
+ VerifyFont(font, fontFamily.Name, emSize, style, unit, gdiCharSet, gdiVerticalFont);
+ }
+ }
+ finally
+ {
+ fontFamily.Dispose();
+ }
+ }
+
+ [ConditionalFact(nameof(PlatformDetection) + "." + nameof(PlatformDetection.IsNotWindowsNanoServer))]
+ public void Ctor_FamilyNamePrefixedWithAtSign_StripsSign()
+ {
+ using (FontFamily family = FontFamily.GenericMonospace)
+ using (var font = new Font($"@{family.Name}", 10))
+ {
+ Assert.Equal(family.Name, font.Name);
+ Assert.Equal($"@{family.Name}", font.OriginalFontName);
+ }
+ }
+
[ConditionalTheory(nameof(PlatformDetection) + "." + nameof(PlatformDetection.IsNotWindowsNanoServer))]
[InlineData(null)]
[InlineData("")]
@@ -19,5 +301,575 @@ namespace System.Drawing.Tests
Assert.Equal("Microsoft Sans Serif", font.FontFamily.Name);
}
}
+
+ [ConditionalFact(nameof(PlatformDetection) + "." + nameof(PlatformDetection.IsNotWindowsNanoServer))]
+ public void Ctor_NullFont_ThrowsNullReferenceException()
+ {
+ Assert.Throws<NullReferenceException>(() => new Font(null, FontStyle.Regular));
+ }
+
+ [ConditionalFact(nameof(PlatformDetection) + "." + nameof(PlatformDetection.IsNotWindowsNanoServer))]
+ public void Ctor_DisposedFont_Success()
+ {
+ using (FontFamily family = FontFamily.GenericSerif)
+ {
+ var font = new Font(family, 10);
+ font.Dispose();
+
+ using (var copy = new Font(font, FontStyle.Italic))
+ {
+ Assert.Equal(FontStyle.Italic, copy.Style);
+ Assert.Equal(family.Name, copy.Name);
+ }
+ }
+ }
+
+ [ConditionalFact(nameof(PlatformDetection) + "." + nameof(PlatformDetection.IsNotWindowsNanoServer))]
+ public void Ctor_NullFamily_ThrowsArgumentNullException()
+ {
+ AssertExtensions.Throws<ArgumentNullException>("family", () => new Font((FontFamily)null, 10));
+ AssertExtensions.Throws<ArgumentNullException>("family", () => new Font((FontFamily)null, 10, FontStyle.Italic));
+ AssertExtensions.Throws<ArgumentNullException>("family", () => new Font((FontFamily)null, 10, GraphicsUnit.Display));
+ AssertExtensions.Throws<ArgumentNullException>("family", () => new Font((FontFamily)null, 10, FontStyle.Italic, GraphicsUnit.Display));
+ AssertExtensions.Throws<ArgumentNullException>("family", () => new Font((FontFamily)null, 10, FontStyle.Italic, GraphicsUnit.Display, 10));
+ AssertExtensions.Throws<ArgumentNullException>("family", () => new Font((FontFamily)null, 10, FontStyle.Italic, GraphicsUnit.Display, 10, gdiVerticalFont: true));
+ }
+
+ [ConditionalFact(nameof(PlatformDetection) + "." + nameof(PlatformDetection.IsNotWindowsNanoServer))]
+ public void Ctor_DisposedFamily_ThrowsArgumentException()
+ {
+ FontFamily family = FontFamily.GenericSansSerif;
+ family.Dispose();
+
+ AssertExtensions.Throws<ArgumentException>(null, () => new Font(family, 10));
+ AssertExtensions.Throws<ArgumentException>(null, () => new Font(family, 10, FontStyle.Italic));
+ AssertExtensions.Throws<ArgumentException>(null, () => new Font(family, 10, GraphicsUnit.Display));
+ AssertExtensions.Throws<ArgumentException>(null, () => new Font(family, 10, FontStyle.Italic, GraphicsUnit.Display));
+ AssertExtensions.Throws<ArgumentException>(null, () => new Font(family, 10, FontStyle.Italic, GraphicsUnit.Display, 10));
+ AssertExtensions.Throws<ArgumentException>(null, () => new Font(family, 10, FontStyle.Italic, GraphicsUnit.Display, 10, gdiVerticalFont: true));
+ }
+
+ [ConditionalTheory(nameof(PlatformDetection) + "." + nameof(PlatformDetection.IsNotWindowsNanoServer))]
+ [InlineData(-1)]
+ [InlineData(0)]
+ [InlineData(float.NaN)]
+ [InlineData(float.NegativeInfinity)]
+ [InlineData(float.PositiveInfinity)]
+ public void Ctor_InvalidEmSize_ThrowsArgumentException(float emSize)
+ {
+ using (FontFamily family = FontFamily.GenericSansSerif)
+ {
+ AssertExtensions.Throws<ArgumentException>("emSize", () => new Font(family, emSize));
+ AssertExtensions.Throws<ArgumentException>("emSize", () => new Font(family.Name, emSize));
+ AssertExtensions.Throws<ArgumentException>("emSize", () => new Font(family, emSize, FontStyle.Italic));
+ AssertExtensions.Throws<ArgumentException>("emSize", () => new Font(family.Name, emSize, FontStyle.Italic));
+ AssertExtensions.Throws<ArgumentException>("emSize", () => new Font(family, emSize, GraphicsUnit.Document));
+ AssertExtensions.Throws<ArgumentException>("emSize", () => new Font(family.Name, emSize, GraphicsUnit.Document));
+ AssertExtensions.Throws<ArgumentException>("emSize", () => new Font(family, emSize, FontStyle.Italic, GraphicsUnit.Document));
+ AssertExtensions.Throws<ArgumentException>("emSize", () => new Font(family.Name, emSize, FontStyle.Italic, GraphicsUnit.Document));
+ AssertExtensions.Throws<ArgumentException>("emSize", () => new Font(family, emSize, FontStyle.Italic, GraphicsUnit.Document, 10));
+ AssertExtensions.Throws<ArgumentException>("emSize", () => new Font(family.Name, emSize, FontStyle.Italic, GraphicsUnit.Document, 10));
+ AssertExtensions.Throws<ArgumentException>("emSize", () => new Font(family, emSize, FontStyle.Italic, GraphicsUnit.Document, 10, gdiVerticalFont: true));
+ AssertExtensions.Throws<ArgumentException>("emSize", () => new Font(family.Name, emSize, FontStyle.Italic, GraphicsUnit.Document, 10, gdiVerticalFont: true));
+ }
+ }
+
+ [ConditionalTheory(nameof(PlatformDetection) + "." + nameof(PlatformDetection.IsNotWindowsNanoServer))]
+ [InlineData(GraphicsUnit.Display)]
+ [InlineData(GraphicsUnit.World - 1)]
+ [InlineData(GraphicsUnit.Millimeter + 1)]
+ public void Ctor_InvalidUnit_ThrowsArgumentException(GraphicsUnit unit)
+ {
+ using (FontFamily family = FontFamily.GenericSansSerif)
+ {
+ AssertExtensions.Throws<ArgumentException>(null, () => new Font(family, 10, unit));
+ AssertExtensions.Throws<ArgumentException>(null, () => new Font(family.Name, 10, unit));
+ AssertExtensions.Throws<ArgumentException>(null, () => new Font(family, 10, FontStyle.Italic, unit));
+ AssertExtensions.Throws<ArgumentException>(null, () => new Font(family.Name, 10, FontStyle.Italic, unit));
+ AssertExtensions.Throws<ArgumentException>(null, () => new Font(family, 10, FontStyle.Italic, unit, 10));
+ AssertExtensions.Throws<ArgumentException>(null, () => new Font(family.Name, 10, FontStyle.Italic, unit, 10));
+ AssertExtensions.Throws<ArgumentException>(null, () => new Font(family, 10, FontStyle.Italic, unit, 10, gdiVerticalFont: true));
+ AssertExtensions.Throws<ArgumentException>(null, () => new Font(family.Name, 10, FontStyle.Italic, unit, 10, gdiVerticalFont: true));
+ }
+ }
+
+ [ConditionalFact(nameof(PlatformDetection) + "." + nameof(PlatformDetection.IsNotWindowsNanoServer))]
+ public void Clone_Invoke_ReturnsExpected()
+ {
+ using (FontFamily family = FontFamily.GenericSansSerif)
+ using (var font = new Font(family, 10, FontStyle.Bold, GraphicsUnit.Inch, 10, gdiVerticalFont: true))
+ {
+ Font clone = Assert.IsType<Font>(font.Clone());
+ Assert.NotSame(font, clone);
+
+ Assert.Equal(font.Name, clone.FontFamily.Name);
+ Assert.Equal(font.Size, clone.Size);
+ Assert.Equal(font.Style, clone.Style);
+ Assert.Equal(font.Unit, clone.Unit);
+ Assert.Equal(font.GdiCharSet, clone.GdiCharSet);
+ Assert.Equal(font.GdiVerticalFont, clone.GdiVerticalFont);
+ }
+ }
+
+ [ConditionalFact(nameof(PlatformDetection) + "." + nameof(PlatformDetection.IsNotWindowsNanoServer))]
+ public void Clone_DisposedFont_ThrowsArgumentException()
+ {
+ using (FontFamily family = FontFamily.GenericSansSerif)
+ {
+ var font = new Font(family, 10);
+ font.Dispose();
+
+ AssertExtensions.Throws<ArgumentException>(null, () => font.Clone());
+ }
+ }
+
+ public static IEnumerable<object[]> Equals_TestData()
+ {
+ FontFamily family = FontFamily.GenericSansSerif;
+ var font = new Font(family, 10, FontStyle.Bold, GraphicsUnit.Inch, 10, gdiVerticalFont: true);
+
+ yield return new object[] { font, font, true };
+ yield return new object[] { font.Clone(), new Font(family, 10, FontStyle.Bold, GraphicsUnit.Inch, 10, gdiVerticalFont: true), false };
+ yield return new object[] { font.Clone(), new Font(family, 9, FontStyle.Bold, GraphicsUnit.Inch, 10, gdiVerticalFont: true), false };
+ yield return new object[] { font.Clone(), new Font(family, 10, FontStyle.Italic, GraphicsUnit.Millimeter, 10, gdiVerticalFont: true), false };
+ yield return new object[] { font.Clone(), new Font(family, 10, FontStyle.Bold, GraphicsUnit.Inch, 9, gdiVerticalFont: true), false };
+ yield return new object[] { font.Clone(), new Font(family, 10, FontStyle.Bold, GraphicsUnit.Inch, 10, gdiVerticalFont: false), false };
+
+ yield return new object[] { new Font(family, 10), new object(), false };
+ yield return new object[] { new Font(family, 10), null, false };
+ }
+
+ [ConditionalTheory(nameof(PlatformDetection) + "." + nameof(PlatformDetection.IsNotWindowsNanoServer))]
+ [MemberData(nameof(Equals_TestData))]
+ public void Equals_Other_ReturnsExpected(Font font, object other, bool expected)
+ {
+ // Windows7 GDI+ returns different results than later versions of Windows.
+ if (PlatformDetection.IsWindows7)
+ {
+ return;
+ }
+
+ try
+ {
+ Assert.Equal(expected, font.Equals(other));
+ Assert.Equal(font.GetHashCode(), font.GetHashCode());
+ }
+ finally
+ {
+ font.Dispose();
+ if (other is Font otherFont && !ReferenceEquals(font, otherFont))
+ {
+ otherFont.Dispose();
+ }
+ }
+ }
+
+ [ConditionalFact(nameof(PlatformDetection) + "." + nameof(PlatformDetection.IsNotWindowsNanoServer))]
+ public void FromHdc_ZeroHdc_ThrowsArgumentException()
+ {
+ AssertExtensions.Throws<ArgumentException>(null, () => Font.FromHdc(IntPtr.Zero));
+ }
+
+ [ConditionalFact(nameof(PlatformDetection) + "." + nameof(PlatformDetection.IsNotWindowsNanoServer))]
+ public void FromHdc_GraphicsHdc_ThrowsArgumentException()
+ {
+ using (var image = new Bitmap(10, 10))
+ using (Graphics graphics = Graphics.FromImage(image))
+ {
+ IntPtr hdc = graphics.GetHdc();
+ try
+ {
+ AssertExtensions.Throws<ArgumentException>(null, () => Font.FromHdc(hdc));
+ }
+ finally
+ {
+ graphics.ReleaseHdc();
+ }
+ }
+ }
+
+ [ConditionalFact(nameof(PlatformDetection) + "." + nameof(PlatformDetection.IsNotWindowsNanoServer))]
+ public void FromHfont_Zero_ThrowsArgumentException()
+ {
+ AssertExtensions.Throws<ArgumentException>(null, () => Font.FromHfont(IntPtr.Zero));
+ }
+
+ [ConditionalFact(nameof(PlatformDetection) + "." + nameof(PlatformDetection.IsNotWindowsNanoServer))]
+ public void GetHeight_Parameterless_ReturnsExpected()
+ {
+ using (FontFamily family = FontFamily.GenericSansSerif)
+ using (var font = new Font(family, 10))
+ {
+ float height = font.GetHeight();
+ AssertExtensions.GreaterThan(height, 0);
+
+ Assert.Equal((int)Math.Ceiling(height), font.Height);
+ }
+ }
+
+ [ConditionalFact(nameof(PlatformDetection) + "." + nameof(PlatformDetection.IsNotWindowsNanoServer))]
+ public void GetHeight_Graphics_ReturnsExpected()
+ {
+ using (FontFamily family = FontFamily.GenericSansSerif)
+ using (var font = new Font(family, 10))
+ using (var image = new Bitmap(10, 10))
+ using (Graphics graphics = Graphics.FromImage(image))
+ {
+ Assert.Equal(font.GetHeight(graphics.DpiY), font.GetHeight(graphics), 5);
+ }
+ }
+
+ [ConditionalTheory(nameof(PlatformDetection) + "." + nameof(PlatformDetection.IsNotWindowsNanoServer))]
+ [InlineData(0, 0)]
+ [InlineData(-1, -0.1571995)]
+ [InlineData(1, 0.1571995)]
+ [InlineData(float.NaN, float.NaN)]
+ [InlineData(float.PositiveInfinity, float.PositiveInfinity)]
+ [InlineData(float.NegativeInfinity, float.NegativeInfinity)]
+ public void GetHeight_Dpi_ReturnsExpected(float dpi, float expected)
+ {
+ using (FontFamily family = FontFamily.GenericSansSerif)
+ using (var font = new Font(family, 10))
+ {
+ Assert.Equal(expected, font.GetHeight(dpi), 5);
+ }
+ }
+
+ [ConditionalFact(nameof(PlatformDetection) + "." + nameof(PlatformDetection.IsNotWindowsNanoServer))]
+ public void GetHeight_NullGraphics_ThrowsArgumentNullException()
+ {
+ using (FontFamily family = FontFamily.GenericSansSerif)
+ using (var font = new Font(family, 10))
+ {
+ AssertExtensions.Throws<ArgumentNullException>("graphics", () => font.GetHeight(null));
+ }
+ }
+
+ // This causes an AccessViolation in GDI+.
+ // [ConditionalFact(nameof(PlatformDetection) + "." + nameof(PlatformDetection.IsNotWindowsNanoServer))]
+ public void GetHeight_DisposedGraphics_ThrowsArgumentException()
+ {
+ using (FontFamily family = FontFamily.GenericMonospace)
+ using (var font = new Font(family, 10))
+ using (var image = new Bitmap(10, 10))
+ {
+ Graphics graphics = Graphics.FromImage(image);
+ graphics.Dispose();
+
+ AssertExtensions.Throws<ArgumentException>(null, () => font.GetHeight(graphics));
+ }
+ }
+
+ [ConditionalFact(nameof(PlatformDetection) + "." + nameof(PlatformDetection.IsNotWindowsNanoServer))]
+ public void GetHeight_Disposed_ThrowsArgumentException()
+ {
+ using (FontFamily family = FontFamily.GenericSansSerif)
+ using (var image = new Bitmap(10, 10))
+ using (Graphics graphics = Graphics.FromImage(image))
+ {
+ var font = new Font(family, 10);
+ font.Dispose();
+
+ AssertExtensions.Throws<ArgumentException>(null, () => font.GetHeight());
+ AssertExtensions.Throws<ArgumentException>(null, () => font.GetHeight(10));
+ AssertExtensions.Throws<ArgumentException>(null, () => font.GetHeight(graphics));
+ }
+ }
+
+ [ConditionalTheory(nameof(PlatformDetection) + "." + nameof(PlatformDetection.IsNotWindowsNanoServer))]
+ [InlineData(FontStyle.Bold, int.MinValue, 0)]
+ [InlineData(FontStyle.Bold, -2147483099, 0)]
+ [InlineData(FontStyle.Regular, -2147483098, 0)]
+ [InlineData(FontStyle.Regular, -1, 0)]
+ [InlineData(FontStyle.Regular, 0, 0)]
+ [InlineData(FontStyle.Regular, 300, 0)]
+ [InlineData(FontStyle.Regular, 400, 0)]
+ [InlineData(FontStyle.Strikeout | FontStyle.Underline | FontStyle.Italic, 549, 1)]
+ [InlineData(FontStyle.Strikeout | FontStyle.Underline | FontStyle.Italic | FontStyle.Bold, 550, 1)]
+ [InlineData(FontStyle.Strikeout | FontStyle.Underline | FontStyle.Bold | FontStyle.Italic, int.MaxValue, 1)]
+ public void FromLogFont_ValidLogFont_ReturnsExpected(FontStyle fontStyle, int weight, byte charSet)
+ {
+ // The boundary values of the weight that is considered Bold are different between Windows 7 and Windows 8.
+ if (PlatformDetection.IsWindows7 || PlatformDetection.IsWindows8x)
+ {
+ return;
+ }
+
+ using (FontFamily family = FontFamily.GenericMonospace)
+ {
+ var logFont = new LOGFONT
+ {
+ lfFaceName = family.Name,
+ lfWeight = weight,
+ lfItalic = (fontStyle & FontStyle.Italic) != 0 ? (byte)1 : (byte)0,
+ lfStrikeOut = (fontStyle & FontStyle.Strikeout) != 0 ? (byte)1 : (byte)0,
+ lfUnderline = (fontStyle & FontStyle.Underline) != 0 ? (byte)1 : (byte)0,
+ lfCharSet = charSet
+ };
+ using (Font font = Font.FromLogFont(logFont))
+ {
+ VerifyFont(font, family.Name, 16, fontStyle, GraphicsUnit.World, charSet, expectedGdiVerticalFont: false);
+ }
+ }
+ }
+
+ [ConditionalFact(nameof(PlatformDetection) + "." + nameof(PlatformDetection.IsNotWindowsNanoServer))]
+ public void FromLogFont_NullLogFont_ThrowsArgumentException()
+ {
+ using (var image = new Bitmap(10, 10))
+ using (Graphics graphics = Graphics.FromImage(image))
+ {
+ IntPtr hdc = graphics.GetHdc();
+ try
+ {
+ AssertExtensions.Throws<ArgumentException>(null, () => Font.FromLogFont(null));
+ AssertExtensions.Throws<ArgumentException>(null, () => Font.FromLogFont(null, hdc));
+ }
+ finally
+ {
+ graphics.ReleaseHdc();
+ }
+ }
+ }
+
+ [ConditionalFact(nameof(PlatformDetection) + "." + nameof(PlatformDetection.IsNotWindowsNanoServer))]
+ public void FromLogFont_InvalidLogFont_ThrowsArgumentException()
+ {
+ using (var image = new Bitmap(10, 10))
+ using (Graphics graphics = Graphics.FromImage(image))
+ {
+ IntPtr hdc = graphics.GetHdc();
+ try
+ {
+ var logFont = new LOGFONT();
+ AssertExtensions.Throws<ArgumentException>(null, () => Font.FromLogFont(logFont));
+ AssertExtensions.Throws<ArgumentException>(null, () => Font.FromLogFont(logFont, hdc));
+ }
+ finally
+ {
+ graphics.ReleaseHdc();
+ }
+ }
+ }
+
+ [ConditionalTheory(nameof(PlatformDetection) + "." + nameof(PlatformDetection.IsNotWindowsNanoServer))]
+ [InlineData(GraphicsUnit.Document)]
+ [InlineData(GraphicsUnit.Inch)]
+ [InlineData(GraphicsUnit.Millimeter)]
+ [InlineData(GraphicsUnit.Pixel)]
+ [InlineData(GraphicsUnit.Point)]
+ [InlineData(GraphicsUnit.World)]
+ public void SizeInPoints_Get_ReturnsExpected(GraphicsUnit unit)
+ {
+ using (FontFamily family = FontFamily.GenericMonospace)
+ using (var font = new Font(family, 10, unit))
+ {
+ float sizeInPoints = font.SizeInPoints;
+ if (unit == GraphicsUnit.Point)
+ {
+ Assert.Equal(font.Size, sizeInPoints);
+ }
+ else
+ {
+ Assert.True(sizeInPoints > 0);
+ }
+ }
+ }
+
+ [ConditionalTheory(nameof(PlatformDetection) + "." + nameof(PlatformDetection.IsNotWindowsNanoServer))]
+ [InlineData(FontStyle.Strikeout | FontStyle.Bold | FontStyle.Italic, true, 255, "@", 700)]
+ [InlineData(FontStyle.Regular, 0, false, "", 400)]
+ [InlineData(FontStyle.Regular, 10, false, "", 400)]
+ public void ToLogFont_Invoke_ReturnsExpected(FontStyle fontStyle, byte gdiCharSet, bool gdiVerticalFont, string expectedNamePrefix, int expectedWeight)
+ {
+ using (FontFamily family = FontFamily.GenericMonospace)
+ using (var font = new Font(family, 10, fontStyle, GraphicsUnit.Point, gdiCharSet, gdiVerticalFont))
+ {
+ var logFont = new LOGFONT();
+ font.ToLogFont(logFont);
+
+ Assert.Equal(-13, logFont.lfHeight);
+ Assert.Equal(0, logFont.lfWidth);
+ Assert.Equal(0, logFont.lfEscapement);
+ Assert.Equal(0, logFont.lfOrientation);
+ Assert.Equal(expectedWeight, logFont.lfWeight);
+ Assert.Equal(font.Italic ? 1 : 0, logFont.lfItalic);
+ Assert.Equal(font.Underline ? 1 : 0, logFont.lfUnderline);
+ Assert.Equal(font.Strikeout ? 1 : 0, logFont.lfStrikeOut);
+ Assert.Equal(font.GdiCharSet, logFont.lfCharSet);
+ Assert.Equal(0, logFont.lfOutPrecision);
+ Assert.Equal(0, logFont.lfClipPrecision);
+ Assert.Equal(0, logFont.lfQuality);
+ Assert.Equal(0, logFont.lfPitchAndFamily);
+ Assert.Equal($"{expectedNamePrefix}{family.Name}", logFont.lfFaceName);
+ }
+ }
+
+ [ConditionalTheory(nameof(PlatformDetection) + "." + nameof(PlatformDetection.IsNotWindowsNanoServer))]
+ [InlineData(TextRenderingHint.SystemDefault, 0)]
+ [InlineData(TextRenderingHint.AntiAlias, 3)]
+ [InlineData(TextRenderingHint.AntiAliasGridFit, 3)]
+ [InlineData(TextRenderingHint.SingleBitPerPixel, 3)]
+ [InlineData(TextRenderingHint.SingleBitPerPixelGridFit, 3)]
+ [InlineData(TextRenderingHint.ClearTypeGridFit, 5)]
+ public void ToLogFont_InvokeGraphics_ReturnsExpected(TextRenderingHint textRenderingHint, int expectedQuality)
+ {
+ using (FontFamily family = FontFamily.GenericMonospace)
+ using (var font = new Font(family, 10))
+ using (var image = new Bitmap(10, 10))
+ using (Graphics graphics = Graphics.FromImage(image))
+ {
+ graphics.TextRenderingHint = textRenderingHint;
+
+ var logFont = new LOGFONT();
+ font.ToLogFont(logFont, graphics);
+
+ Assert.Equal(-13, logFont.lfHeight);
+ Assert.Equal(0, logFont.lfWidth);
+ Assert.Equal(0, logFont.lfEscapement);
+ Assert.Equal(0, logFont.lfOrientation);
+ Assert.Equal(400, logFont.lfWeight);
+ Assert.Equal(0, logFont.lfItalic);
+ Assert.Equal(0, logFont.lfUnderline);
+ Assert.Equal(0, logFont.lfStrikeOut);
+ Assert.Equal(1, logFont.lfCharSet);
+ Assert.Equal(0, logFont.lfOutPrecision);
+ Assert.Equal(0, logFont.lfClipPrecision);
+ Assert.Equal(0, logFont.lfQuality);
+ Assert.Equal(0, logFont.lfPitchAndFamily);
+ Assert.Equal(family.Name, logFont.lfFaceName);
+ }
+ }
+
+ [ConditionalFact(nameof(PlatformDetection) + "." + nameof(PlatformDetection.IsNotWindowsNanoServer))]
+ [SkipOnTargetFramework(TargetFrameworkMonikers.NetFramework, "Throws an AccessViolationException in the .NET Framework.")]
+ public void ToLogFont_NullLogFont_ThrowsArgumentNullException()
+ {
+ using (FontFamily family = FontFamily.GenericMonospace)
+ using (var font = new Font(family, 10))
+ using (var image = new Bitmap(10, 10))
+ using (Graphics graphics = Graphics.FromImage(image))
+ {
+ AssertExtensions.Throws<ArgumentNullException>("ptr", () => font.ToLogFont(null));
+ AssertExtensions.Throws<ArgumentNullException>("ptr", () => font.ToLogFont(null, graphics));
+ }
+ }
+
+ [ConditionalFact(nameof(PlatformDetection) + "." + nameof(PlatformDetection.IsNotWindowsNanoServer))]
+ public void ToLogFont_NullGraphics_ThrowsArgumentNullException()
+ {
+ using (FontFamily family = FontFamily.GenericMonospace)
+ using (var font = new Font(family, 10))
+ {
+ AssertExtensions.Throws<ArgumentNullException>("graphics", () => font.ToLogFont(new LOGFONT(), null));
+ }
+ }
+
+ [ConditionalFact(nameof(PlatformDetection) + "." + nameof(PlatformDetection.IsNotWindowsNanoServer))]
+ public void ToLogFont_DisposedGraphics_ThrowsArgumentException()
+ {
+ using (FontFamily family = FontFamily.GenericMonospace)
+ using (var font = new Font(family, 10))
+ using (var image = new Bitmap(10, 10))
+ {
+ Graphics graphics = Graphics.FromImage(image);
+ graphics.Dispose();
+
+ AssertExtensions.Throws<ArgumentException>(null, () => font.ToLogFont(new LOGFONT(), graphics));
+ }
+ }
+
+ [StructLayout(LayoutKind.Sequential, CharSet = CharSet.Auto)]
+ public class LOGFONT
+ {
+ public int lfHeight;
+ public int lfWidth;
+ public int lfEscapement;
+ public int lfOrientation;
+ public int lfWeight;
+ public byte lfItalic;
+ public byte lfUnderline;
+ public byte lfStrikeOut;
+ public byte lfCharSet;
+ public byte lfOutPrecision;
+ public byte lfClipPrecision;
+ public byte lfQuality;
+ public byte lfPitchAndFamily;
+ [MarshalAs(UnmanagedType.ByValTStr, SizeConst = 32)]
+ public string lfFaceName;
+ }
+
+ [ConditionalFact(nameof(PlatformDetection) + "." + nameof(PlatformDetection.IsNotWindowsNanoServer))]
+ public void ToHfont_SimpleFont_Roundtrips()
+ {
+ using (FontFamily family = FontFamily.GenericSansSerif)
+ using (var font = new Font(family, 10))
+ {
+ IntPtr hfont = font.ToHfont();
+ Assert.NotEqual(IntPtr.Zero, hfont);
+ Assert.NotEqual(hfont, font.ToHfont());
+
+ Font newFont = Font.FromHfont(hfont);
+ Assert.Equal(font.Name, newFont.Name);
+ }
+ }
+
+ [ConditionalFact(nameof(PlatformDetection) + "." + nameof(PlatformDetection.IsNotWindowsNanoServer))]
+ public void ToHfont_ComplicatedFont_DoesNotRoundtrip()
+ {
+ using (FontFamily family = FontFamily.GenericSansSerif)
+ using (var font = new Font(family, 10, FontStyle.Bold, GraphicsUnit.Inch, 10, gdiVerticalFont: true))
+ {
+ IntPtr hfont = font.ToHfont();
+ Assert.NotEqual(IntPtr.Zero, hfont);
+ Assert.NotEqual(hfont, font.ToHfont());
+
+ Font newFont = Font.FromHfont(hfont);
+ Assert.NotEqual(font.Name, newFont.Name);
+ }
+ }
+
+ [ConditionalFact(nameof(PlatformDetection) + "." + nameof(PlatformDetection.IsNotWindowsNanoServer))]
+ public void ToHfont_Disposed_ThrowsArgumentException()
+ {
+ using (FontFamily family = FontFamily.GenericSansSerif)
+ using (var image = new Bitmap(10, 10))
+ using (Graphics graphics = Graphics.FromImage(image))
+ {
+ var font = new Font(family, 10);
+ font.Dispose();
+
+ AssertExtensions.Throws<ArgumentException>(null, () => font.ToHfont());
+ }
+ }
+
+ [ConditionalFact(nameof(PlatformDetection) + "." + nameof(PlatformDetection.IsNotWindowsNanoServer))]
+ public void ToString_Invoke_ReturnsExpected()
+ {
+ using (FontFamily family = FontFamily.GenericSansSerif)
+ using (var font = new Font(family, 10, FontStyle.Bold, GraphicsUnit.Inch, 10, gdiVerticalFont: true))
+ {
+ Assert.Equal($"[Font: Name={family.Name}, Size=10, Units=4, GdiCharSet=10, GdiVerticalFont=True]", font.ToString());
+ }
+ }
+
+ private static void VerifyFont(Font font, string expectedName, float expectedEmSize, FontStyle expectedStyle, GraphicsUnit expectedUnit, byte expectedGdiCharset, bool expectedGdiVerticalFont)
+ {
+ Assert.Equal(expectedName, font.Name);
+ Assert.Equal(expectedEmSize, font.Size);
+
+ Assert.Equal(expectedStyle, font.Style);
+ Assert.Equal((expectedStyle & FontStyle.Bold) != 0, font.Bold);
+ Assert.Equal((expectedStyle & FontStyle.Italic) != 0, font.Italic);
+ Assert.Equal((expectedStyle & FontStyle.Strikeout) != 0, font.Strikeout);
+ Assert.Equal((expectedStyle & FontStyle.Underline) != 0, font.Underline);
+
+ Assert.Equal(expectedUnit, font.Unit);
+ Assert.Equal(expectedGdiCharset, font.GdiCharSet);
+ Assert.Equal(expectedGdiVerticalFont, font.GdiVerticalFont);
+
+ Assert.False(font.IsSystemFont);
+ Assert.Empty(font.SystemFontName);
+ }
}
}
diff --git a/src/System.Drawing.Common/tests/GraphicsTests.cs b/src/System.Drawing.Common/tests/GraphicsTests.cs
index 1f56a7e958..3af65ef656 100644
--- a/src/System.Drawing.Common/tests/GraphicsTests.cs
+++ b/src/System.Drawing.Common/tests/GraphicsTests.cs
@@ -6,6 +6,7 @@ using System.ComponentModel;
using System.Drawing.Drawing2D;
using System.Drawing.Imaging;
using System.Drawing.Text;
+using System.Linq;
using Xunit;
namespace System.Drawing.Tests
@@ -1301,6 +1302,2064 @@ namespace System.Drawing.Tests
}
}
+ [ConditionalFact(nameof(PlatformDetection) + "." + nameof(PlatformDetection.IsNotWindowsNanoServer))]
+ public void ResetTransform_Invoke_SetsTransformToIdentity()
+ {
+ using (var image = new Bitmap(10, 10))
+ using (Graphics graphics = Graphics.FromImage(image))
+ using (var transform = new Matrix(1, 2, 3, 4, 5, 6))
+ {
+ graphics.Transform = transform;
+ Assert.False(graphics.Transform.IsIdentity);
+
+ graphics.ResetTransform();
+ Assert.True(graphics.Transform.IsIdentity);
+ }
+ }
+
+ [ConditionalFact(nameof(PlatformDetection) + "." + nameof(PlatformDetection.IsNotWindowsNanoServer))]
+ public void ResetTransform_Busy_ThrowsInvalidOperationException()
+ {
+ using (var image = new Bitmap(10, 10))
+ using (Graphics graphics = Graphics.FromImage(image))
+ {
+ IntPtr hdc = graphics.GetHdc();
+ try
+ {
+ Assert.Throws<InvalidOperationException>(() => graphics.ResetTransform());
+ }
+ finally
+ {
+ graphics.ReleaseHdc();
+ }
+ }
+ }
+
+ [ConditionalFact(nameof(PlatformDetection) + "." + nameof(PlatformDetection.IsNotWindowsNanoServer))]
+ public void ResetTransform_Disposed_ThrowsArgumentException()
+ {
+ using (var image = new Bitmap(10, 10))
+ {
+ Graphics graphics = Graphics.FromImage(image);
+ graphics.Dispose();
+
+ AssertExtensions.Throws<ArgumentException>(null, () => graphics.ResetTransform());
+ }
+ }
+
+ [ConditionalFact(nameof(PlatformDetection) + "." + nameof(PlatformDetection.IsNotWindowsNanoServer))]
+ public void MultiplyTransform_NoOrder_Success()
+ {
+ using (var image = new Bitmap(10, 10))
+ using (Graphics graphics = Graphics.FromImage(image))
+ using (var transform = new Matrix(1, 2, 3, 4, 5, 6))
+ using (var matrix = new Matrix(1, 2, 3, 4, 5, 6))
+ {
+ graphics.Transform = transform;
+ Matrix expectedTransform = graphics.Transform;
+ expectedTransform.Multiply(matrix);
+
+ graphics.MultiplyTransform(matrix);
+ Assert.Equal(expectedTransform, graphics.Transform);
+ }
+ }
+
+ [ConditionalTheory(nameof(PlatformDetection) + "." + nameof(PlatformDetection.IsNotWindowsNanoServer))]
+ [InlineData(MatrixOrder.Prepend)]
+ [InlineData(MatrixOrder.Append)]
+ public void MultiplyTransform_Order_Success(MatrixOrder order)
+ {
+ using (var image = new Bitmap(10, 10))
+ using (Graphics graphics = Graphics.FromImage(image))
+ using (var transform = new Matrix(1, 2, 3, 4, 5, 6))
+ using (var matrix = new Matrix(1, 2, 3, 4, 5, 6))
+ {
+ graphics.Transform = transform;
+ Matrix expectedTransform = graphics.Transform;
+ expectedTransform.Multiply(matrix, order);
+
+ graphics.MultiplyTransform(matrix, order);
+ Assert.Equal(expectedTransform, graphics.Transform);
+ }
+ }
+
+ [ConditionalFact(nameof(PlatformDetection) + "." + nameof(PlatformDetection.IsNotWindowsNanoServer))]
+ public void MultiplyTransform_NullMatrix_ThrowsArgumentNullException()
+ {
+ using (var image = new Bitmap(10, 10))
+ using (Graphics graphics = Graphics.FromImage(image))
+ {
+ AssertExtensions.Throws<ArgumentNullException>("matrix", () => graphics.MultiplyTransform(null));
+ AssertExtensions.Throws<ArgumentNullException>("matrix", () => graphics.MultiplyTransform(null, MatrixOrder.Append));
+ }
+ }
+
+ [ConditionalFact(nameof(PlatformDetection) + "." + nameof(PlatformDetection.IsNotWindowsNanoServer))]
+ public void MultiplyTransform_DisposedMatrix_Nop()
+ {
+ var brush = new LinearGradientBrush(new Rectangle(1, 2, 3, 4), Color.Plum, Color.Red, 45, true);
+ Matrix transform = brush.Transform;
+
+ var matrix = new Matrix();
+ matrix.Dispose();
+
+ brush.MultiplyTransform(matrix);
+ brush.MultiplyTransform(matrix, MatrixOrder.Append);
+
+ Assert.Equal(transform, brush.Transform);
+ }
+
+ [ConditionalFact(nameof(PlatformDetection) + "." + nameof(PlatformDetection.IsNotWindowsNanoServer))]
+ public void MultiplyTransform_NonInvertibleMatrix_ThrowsArgumentException()
+ {
+ using (var image = new Bitmap(10, 10))
+ using (Graphics graphics = Graphics.FromImage(image))
+ using (var matrix = new Matrix(123, 24, 82, 16, 47, 30))
+ {
+ AssertExtensions.Throws<ArgumentException>(null, () => graphics.MultiplyTransform(matrix));
+ AssertExtensions.Throws<ArgumentException>(null, () => graphics.MultiplyTransform(matrix, MatrixOrder.Append));
+ }
+ }
+
+ [ConditionalTheory(nameof(PlatformDetection) + "." + nameof(PlatformDetection.IsNotWindowsNanoServer))]
+ [InlineData(MatrixOrder.Prepend - 1)]
+ [InlineData(MatrixOrder.Append + 1)]
+ public void MultiplyTransform_InvalidOrder_ThrowsArgumentException(MatrixOrder order)
+ {
+ using (var image = new Bitmap(10, 10))
+ using (Graphics graphics = Graphics.FromImage(image))
+ using (var matrix = new Matrix())
+ {
+ AssertExtensions.Throws<ArgumentException>(null, () => graphics.MultiplyTransform(matrix, order));
+ }
+ }
+
+ [ConditionalFact(nameof(PlatformDetection) + "." + nameof(PlatformDetection.IsNotWindowsNanoServer))]
+ public void MultiplyTransform_Busy_ThrowsInvalidOperationException()
+ {
+ using (var image = new Bitmap(10, 10))
+ using (Graphics graphics = Graphics.FromImage(image))
+ using (var matrix = new Matrix())
+ {
+ IntPtr hdc = graphics.GetHdc();
+ try
+ {
+ Assert.Throws<InvalidOperationException>(() => graphics.MultiplyTransform(matrix));
+ Assert.Throws<InvalidOperationException>(() => graphics.MultiplyTransform(matrix, MatrixOrder.Append));
+ }
+ finally
+ {
+ graphics.ReleaseHdc();
+ }
+ }
+ }
+
+ [ConditionalFact(nameof(PlatformDetection) + "." + nameof(PlatformDetection.IsNotWindowsNanoServer))]
+ public void MultiplyTransform_Disposed_ThrowsArgumentException()
+ {
+ using (var image = new Bitmap(10, 10))
+ using (var matrix = new Matrix())
+ {
+ Graphics graphics = Graphics.FromImage(image);
+ graphics.Dispose();
+
+ AssertExtensions.Throws<ArgumentException>(null, () => graphics.MultiplyTransform(matrix));
+ AssertExtensions.Throws<ArgumentException>(null, () => graphics.MultiplyTransform(matrix, MatrixOrder.Prepend));
+ }
+ }
+
+ [ConditionalTheory(nameof(PlatformDetection) + "." + nameof(PlatformDetection.IsNotWindowsNanoServer))]
+ [InlineData(-1, -2)]
+ [InlineData(0, 0)]
+ [InlineData(1, 2)]
+ public void TranslateTransform_NoOrder_Success(float dx, float dy)
+ {
+ using (var image = new Bitmap(10, 10))
+ using (Graphics graphics = Graphics.FromImage(image))
+ using (var transform = new Matrix(1, 2, 3, 4, 5, 6))
+ {
+ graphics.Transform = transform;
+ Matrix expectedTransform = graphics.Transform;
+ expectedTransform.Translate(dx, dy);
+
+ graphics.TranslateTransform(dx, dy);
+ Assert.Equal(expectedTransform, graphics.Transform);
+ }
+ }
+
+ [ConditionalTheory(nameof(PlatformDetection) + "." + nameof(PlatformDetection.IsNotWindowsNanoServer))]
+ [InlineData(1, 1, MatrixOrder.Prepend)]
+ [InlineData(1, 1, MatrixOrder.Append)]
+ [InlineData(0, 0, MatrixOrder.Prepend)]
+ [InlineData(0, 0, MatrixOrder.Append)]
+ [InlineData(-1, -1, MatrixOrder.Prepend)]
+ [InlineData(-1, -1, MatrixOrder.Append)]
+ public void TranslateTransform_Order_Success(float dx, float dy, MatrixOrder order)
+ {
+ using (var image = new Bitmap(10, 10))
+ using (Graphics graphics = Graphics.FromImage(image))
+ using (var transform = new Matrix(1, 2, 3, 4, 5, 6))
+ {
+ graphics.Transform = transform;
+ Matrix expectedTransform = graphics.Transform;
+ expectedTransform.Translate(dx, dy, order);
+
+ graphics.TranslateTransform(dx, dy, order);
+ Assert.Equal(expectedTransform, graphics.Transform);
+ }
+ }
+
+ [ConditionalTheory(nameof(PlatformDetection) + "." + nameof(PlatformDetection.IsNotWindowsNanoServer))]
+ [InlineData(MatrixOrder.Prepend - 1)]
+ [InlineData(MatrixOrder.Append + 1)]
+ public void TranslateTransform_InvalidOrder_ThrowsArgumentException(MatrixOrder order)
+ {
+ using (var image = new Bitmap(10, 10))
+ using (Graphics graphics = Graphics.FromImage(image))
+ {
+ AssertExtensions.Throws<ArgumentException>(null, () => graphics.TranslateTransform(0, 0, order));
+ }
+ }
+
+ [ConditionalFact(nameof(PlatformDetection) + "." + nameof(PlatformDetection.IsNotWindowsNanoServer))]
+ public void TranslateTransform_Busy_ThrowsInvalidOperationException()
+ {
+ using (var image = new Bitmap(10, 10))
+ using (Graphics graphics = Graphics.FromImage(image))
+ {
+ IntPtr hdc = graphics.GetHdc();
+ try
+ {
+ Assert.Throws<InvalidOperationException>(() => graphics.TranslateTransform(0, 0));
+ Assert.Throws<InvalidOperationException>(() => graphics.TranslateTransform(0, 0, MatrixOrder.Append));
+ }
+ finally
+ {
+ graphics.ReleaseHdc();
+ }
+ }
+ }
+
+ [ConditionalFact(nameof(PlatformDetection) + "." + nameof(PlatformDetection.IsNotWindowsNanoServer))]
+ public void TranslateTransform_Disposed_ThrowsArgumentException()
+ {
+ using (var image = new Bitmap(10, 10))
+ {
+ Graphics graphics = Graphics.FromImage(image);
+ graphics.Dispose();
+
+ AssertExtensions.Throws<ArgumentException>(null, () => graphics.TranslateTransform(0, 0));
+ AssertExtensions.Throws<ArgumentException>(null, () => graphics.TranslateTransform(0, 0, MatrixOrder.Append));
+ }
+ }
+
+ [ConditionalTheory(nameof(PlatformDetection) + "." + nameof(PlatformDetection.IsNotWindowsNanoServer))]
+ [InlineData(-1, -2)]
+ [InlineData(1, 2)]
+ public void ScaleTransform_NoOrder_Success(float sx, float sy)
+ {
+ using (var image = new Bitmap(10, 10))
+ using (Graphics graphics = Graphics.FromImage(image))
+ using (var transform = new Matrix(1, 2, 3, 4, 5, 6))
+ {
+ graphics.Transform = transform;
+ Matrix expectedTransform = graphics.Transform;
+ expectedTransform.Scale(sx, sy);
+
+ graphics.ScaleTransform(sx, sy);
+ Assert.Equal(expectedTransform, graphics.Transform);
+ }
+ }
+
+ [ConditionalTheory(nameof(PlatformDetection) + "." + nameof(PlatformDetection.IsNotWindowsNanoServer))]
+ [InlineData(1, 1, MatrixOrder.Prepend)]
+ [InlineData(1, 1, MatrixOrder.Append)]
+ [InlineData(-1, -1, MatrixOrder.Prepend)]
+ [InlineData(-1, -1, MatrixOrder.Append)]
+ public void ScaleTransform_Order_Success(float sx, float sy, MatrixOrder order)
+ {
+ using (var image = new Bitmap(10, 10))
+ using (Graphics graphics = Graphics.FromImage(image))
+ using (var transform = new Matrix(1, 2, 3, 4, 5, 6))
+ {
+ graphics.Transform = transform;
+ Matrix expectedTransform = graphics.Transform;
+ expectedTransform.Scale(sx, sy, order);
+
+ graphics.ScaleTransform(sx, sy, order);
+ Assert.Equal(expectedTransform, graphics.Transform);
+ }
+ }
+
+ [ConditionalTheory(nameof(PlatformDetection) + "." + nameof(PlatformDetection.IsNotWindowsNanoServer))]
+ public void ScaleTransform_ZeroZero_ThrowsArgumentException()
+ {
+ using (var image = new Bitmap(10, 10))
+ using (Graphics graphics = Graphics.FromImage(image))
+ {
+ AssertExtensions.Throws<ArgumentException>(null, () => graphics.ScaleTransform(0, 0));
+ AssertExtensions.Throws<ArgumentException>(null, () => graphics.ScaleTransform(0, 0, MatrixOrder.Append));
+ }
+ }
+
+ [ConditionalTheory(nameof(PlatformDetection) + "." + nameof(PlatformDetection.IsNotWindowsNanoServer))]
+ [InlineData(MatrixOrder.Prepend - 1)]
+ [InlineData(MatrixOrder.Append + 1)]
+ public void ScaleTransform_InvalidOrder_ThrowsArgumentException(MatrixOrder order)
+ {
+ using (var image = new Bitmap(10, 10))
+ using (Graphics graphics = Graphics.FromImage(image))
+ {
+ AssertExtensions.Throws<ArgumentException>(null, () => graphics.ScaleTransform(0, 0, order));
+ }
+ }
+
+ [ConditionalFact(nameof(PlatformDetection) + "." + nameof(PlatformDetection.IsNotWindowsNanoServer))]
+ public void ScaleTransform_Busy_ThrowsInvalidOperationException()
+ {
+ using (var image = new Bitmap(10, 10))
+ using (Graphics graphics = Graphics.FromImage(image))
+ {
+ IntPtr hdc = graphics.GetHdc();
+ try
+ {
+ Assert.Throws<InvalidOperationException>(() => graphics.ScaleTransform(0, 0));
+ Assert.Throws<InvalidOperationException>(() => graphics.ScaleTransform(0, 0, MatrixOrder.Append));
+ }
+ finally
+ {
+ graphics.ReleaseHdc();
+ }
+ }
+ }
+
+ [ConditionalFact(nameof(PlatformDetection) + "." + nameof(PlatformDetection.IsNotWindowsNanoServer))]
+ public void ScaleTransform_Disposed_ThrowsArgumentException()
+ {
+ using (var image = new Bitmap(10, 10))
+ {
+ Graphics graphics = Graphics.FromImage(image);
+ graphics.Dispose();
+
+ AssertExtensions.Throws<ArgumentException>(null, () => graphics.ScaleTransform(0, 0));
+ AssertExtensions.Throws<ArgumentException>(null, () => graphics.ScaleTransform(0, 0, MatrixOrder.Append));
+ }
+ }
+
+ [ConditionalTheory(nameof(PlatformDetection) + "." + nameof(PlatformDetection.IsNotWindowsNanoServer))]
+ [InlineData(-1)]
+ [InlineData(0)]
+ [InlineData(1)]
+ [InlineData(360)]
+ public void RotateTransform_NoOrder_Success(float angle)
+ {
+ using (var image = new Bitmap(10, 10))
+ using (Graphics graphics = Graphics.FromImage(image))
+ using (var transform = new Matrix(1, 2, 3, 4, 5, 6))
+ {
+ graphics.Transform = transform;
+ Matrix expectedTransform = graphics.Transform;
+ expectedTransform.Rotate(angle);
+
+ graphics.RotateTransform(angle);
+ Assert.Equal(expectedTransform, graphics.Transform);
+ }
+ }
+
+ [ConditionalTheory(nameof(PlatformDetection) + "." + nameof(PlatformDetection.IsNotWindowsNanoServer))]
+ [InlineData(1, MatrixOrder.Prepend)]
+ [InlineData(1, MatrixOrder.Append)]
+ [InlineData(0, MatrixOrder.Prepend)]
+ [InlineData(360, MatrixOrder.Append)]
+ [InlineData(-1, MatrixOrder.Prepend)]
+ [InlineData(-1, MatrixOrder.Append)]
+ public void RotateTransform_Order_Success(float angle, MatrixOrder order)
+ {
+ using (var image = new Bitmap(10, 10))
+ using (Graphics graphics = Graphics.FromImage(image))
+ using (var transform = new Matrix(1, 2, 3, 4, 5, 6))
+ {
+ graphics.Transform = transform;
+ Matrix expectedTransform = graphics.Transform;
+ expectedTransform.Rotate(angle, order);
+
+ graphics.RotateTransform(angle, order);
+ Assert.Equal(expectedTransform, graphics.Transform);
+ }
+ }
+
+ [ConditionalTheory(nameof(PlatformDetection) + "." + nameof(PlatformDetection.IsNotWindowsNanoServer))]
+ [InlineData(MatrixOrder.Prepend - 1)]
+ [InlineData(MatrixOrder.Append + 1)]
+ public void RotateTransform_InvalidOrder_ThrowsArgumentException(MatrixOrder order)
+ {
+ using (var image = new Bitmap(10, 10))
+ using (Graphics graphics = Graphics.FromImage(image))
+ {
+ AssertExtensions.Throws<ArgumentException>(null, () => graphics.RotateTransform(0, order));
+ }
+ }
+
+ [ConditionalFact(nameof(PlatformDetection) + "." + nameof(PlatformDetection.IsNotWindowsNanoServer))]
+ public void RotateTransform_Busy_ThrowsInvalidOperationException()
+ {
+ using (var image = new Bitmap(10, 10))
+ using (Graphics graphics = Graphics.FromImage(image))
+ {
+ IntPtr hdc = graphics.GetHdc();
+ try
+ {
+ Assert.Throws<InvalidOperationException>(() => graphics.RotateTransform(0));
+ Assert.Throws<InvalidOperationException>(() => graphics.RotateTransform(0, MatrixOrder.Append));
+ }
+ finally
+ {
+ graphics.ReleaseHdc();
+ }
+ }
+ }
+
+ [ConditionalFact(nameof(PlatformDetection) + "." + nameof(PlatformDetection.IsNotWindowsNanoServer))]
+ public void RotateTransform_Disposed_ThrowsArgumentException()
+ {
+ using (var image = new Bitmap(10, 10))
+ {
+ Graphics graphics = Graphics.FromImage(image);
+ graphics.Dispose();
+
+ AssertExtensions.Throws<ArgumentException>(null, () => graphics.RotateTransform(0));
+ AssertExtensions.Throws<ArgumentException>(null, () => graphics.RotateTransform(0, MatrixOrder.Append));
+ }
+ }
+
+ public static IEnumerable<object[]> CopyFromScreen_TestData()
+ {
+ yield return new object[] { 0, 0, 0, 0, new Size(0, 0) };
+ yield return new object[] { -1, -1, 0, 0, new Size(1, 1) };
+ yield return new object[] { int.MaxValue, int.MaxValue, 0, 0, new Size(1, 1) };
+ yield return new object[] { int.MaxValue, int.MaxValue, 0, 0, new Size(1, 1) };
+ yield return new object[] { 0, 0, -1, -1, new Size(1, 1) };
+ yield return new object[] { 0, 0, int.MaxValue, int.MaxValue, new Size(1, 1) };
+ yield return new object[] { 0, 0, 0, 0, new Size(-1, -1) };
+ }
+
+ [ConditionalTheory(nameof(PlatformDetection) + "." + nameof(PlatformDetection.IsNotWindowsNanoServer))]
+ [MemberData(nameof(CopyFromScreen_TestData))]
+ public void CopyFromScreen_OutOfRange_DoesNotAffectGraphics(int sourceX, int sourceY, int destinationX, int destinationY, Size size)
+ {
+ using (var image = new Bitmap(10, 10))
+ using (Graphics graphics = Graphics.FromImage(image))
+ {
+ Color plum = Color.FromArgb(Color.Plum.ToArgb());
+ image.SetPixel(0, 0, plum);
+
+ graphics.CopyFromScreen(sourceX, sourceY, destinationX, destinationY, size);
+ graphics.CopyFromScreen(new Point(sourceX, sourceY), new Point(destinationX, destinationY), size);
+ Assert.Equal(plum, image.GetPixel(0, 0));
+ }
+ }
+
+ [ConditionalTheory(nameof(PlatformDetection) + "." + nameof(PlatformDetection.IsNotWindowsNanoServer))]
+ [InlineData(0, 0, 0, 0, 10, 10)]
+ [InlineData(0, 0, 0, 0, int.MaxValue, int.MaxValue)]
+ [InlineData(1, 1, 2, 2, 3, 3)]
+ public void CopyFromScreen_ValidRange_AffectsGraphics(int sourceX, int sourceY, int destinationX, int destinationY, int width, int height)
+ {
+ Size screenSize = Helpers.GetHWndRect(IntPtr.Zero).Size;
+
+ Color color = Color.FromArgb(2, 3, 4);
+ using (var image = new Bitmap(10, 10))
+ using (Graphics graphics = Graphics.FromImage(image))
+ using (SolidBrush brush = new SolidBrush(color))
+ {
+ graphics.FillRectangle(brush, new Rectangle(0, 0, 10, 10));
+ graphics.CopyFromScreen(sourceX, sourceY, destinationX, destinationY, new Size(width, height));
+
+ Rectangle drawnRect = new Rectangle(destinationX, destinationY, width, height);
+ for (int y = 0; y < image.Height; y++)
+ {
+ for (int x = 0; x < image.Width; x++)
+ {
+ Color imageColor = image.GetPixel(x, y);
+ if (!drawnRect.Contains(x, y))
+ {
+ Assert.Equal(color, imageColor);
+ }
+ else
+ {
+ Assert.NotEqual(color, imageColor);
+ }
+ }
+ }
+ }
+ }
+
+ public static IEnumerable<object[]> CopyPixelOperation_TestData()
+ {
+ yield return new object[] { CopyPixelOperation.NoMirrorBitmap };
+ yield return new object[] { CopyPixelOperation.Blackness };
+ yield return new object[] { CopyPixelOperation.NotSourceErase };
+ yield return new object[] { CopyPixelOperation.NotSourceCopy };
+ yield return new object[] { CopyPixelOperation.SourceErase };
+ yield return new object[] { CopyPixelOperation.DestinationInvert };
+ yield return new object[] { CopyPixelOperation.PatInvert };
+ yield return new object[] { CopyPixelOperation.SourceInvert };
+ yield return new object[] { CopyPixelOperation.SourceAnd };
+ yield return new object[] { CopyPixelOperation.MergePaint };
+ yield return new object[] { CopyPixelOperation.MergeCopy };
+ yield return new object[] { CopyPixelOperation.SourceCopy };
+ yield return new object[] { CopyPixelOperation.SourcePaint };
+ yield return new object[] { CopyPixelOperation.SourceCopy };
+ yield return new object[] { CopyPixelOperation.PatCopy };
+ yield return new object[] { CopyPixelOperation.PatPaint };
+ yield return new object[] { CopyPixelOperation.Whiteness };
+ yield return new object[] { CopyPixelOperation.CaptureBlt };
+ yield return new object[] { CopyPixelOperation.CaptureBlt };
+ }
+
+ [ConditionalTheory(nameof(PlatformDetection) + "." + nameof(PlatformDetection.IsNotWindowsNanoServer))]
+ [MemberData(nameof(CopyPixelOperation_TestData))]
+ public void CopyFromScreen_IntsAndValidCopyPixelOperation_Success(CopyPixelOperation copyPixelOperation)
+ {
+ using (var image = new Bitmap(10, 10))
+ using (Graphics graphics = Graphics.FromImage(image))
+ {
+ // We don't know what the screen looks like at this point in time, so
+ // just make sure that this doesn't fail.
+ graphics.CopyFromScreen(0, 0, 0, 0, new Size(1, 1), copyPixelOperation);
+ }
+ }
+
+ [ConditionalTheory(nameof(PlatformDetection) + "." + nameof(PlatformDetection.IsNotWindowsNanoServer))]
+ [MemberData(nameof(CopyPixelOperation_TestData))]
+ public void CopyFromScreen_PointsAndValidCopyPixelOperation_Success(CopyPixelOperation copyPixelOperation)
+ {
+ using (var image = new Bitmap(10, 10))
+ using (Graphics graphics = Graphics.FromImage(image))
+ {
+ // We don't know what the screen looks like at this point in time, so
+ // just make sure that this doesn't fail.
+ graphics.CopyFromScreen(Point.Empty, Point.Empty, new Size(1, 1), copyPixelOperation);
+ }
+ }
+
+ [ConditionalTheory(nameof(PlatformDetection) + "." + nameof(PlatformDetection.IsNotWindowsNanoServer))]
+ [InlineData(CopyPixelOperation.NoMirrorBitmap + 1)]
+ [InlineData(CopyPixelOperation.Blackness - 1)]
+ [InlineData(CopyPixelOperation.NotSourceErase - 1)]
+ [InlineData(CopyPixelOperation.NotSourceCopy - 1)]
+ [InlineData(CopyPixelOperation.SourceErase - 1)]
+ [InlineData(CopyPixelOperation.DestinationInvert - 1)]
+ [InlineData(CopyPixelOperation.PatInvert - 1)]
+ [InlineData(CopyPixelOperation.SourceInvert - 1)]
+ [InlineData(CopyPixelOperation.SourceAnd - 1)]
+ [InlineData(CopyPixelOperation.MergePaint - 1)]
+ [InlineData(CopyPixelOperation.MergeCopy - 1)]
+ [InlineData(CopyPixelOperation.SourceCopy - 1)]
+ [InlineData(CopyPixelOperation.SourcePaint - 1)]
+ [InlineData(CopyPixelOperation.PatCopy - 1)]
+ [InlineData(CopyPixelOperation.PatPaint - 1)]
+ [InlineData(CopyPixelOperation.Whiteness - 1)]
+ [InlineData(CopyPixelOperation.CaptureBlt - 1)]
+ [InlineData(CopyPixelOperation.CaptureBlt + 1)]
+ public void CopyFromScreen_InvalidCopyPixelOperation_ThrowsInvalidEnumArgumentException(CopyPixelOperation copyPixelOperation)
+ {
+ using (var image = new Bitmap(10, 10))
+ using (Graphics graphics = Graphics.FromImage(image))
+ {
+ AssertExtensions.Throws<InvalidEnumArgumentException>("copyPixelOperation", "value", () => graphics.CopyFromScreen(1, 2, 3, 4, Size.Empty, copyPixelOperation));
+ }
+ }
+
+ [ConditionalFact(nameof(PlatformDetection) + "." + nameof(PlatformDetection.IsNotWindowsNanoServer))]
+ public void CopyFromScreen_Busy_ThrowsInvalidOperationException()
+ {
+ using (var image = new Bitmap(10, 10))
+ using (Graphics graphics = Graphics.FromImage(image))
+ {
+ IntPtr hdc = graphics.GetHdc();
+ try
+ {
+ Assert.Throws<InvalidOperationException>(() => graphics.CopyFromScreen(0, 0, 0, 0, Size.Empty));
+ Assert.Throws<InvalidOperationException>(() => graphics.CopyFromScreen(0, 0, 0, 0, Size.Empty, CopyPixelOperation.DestinationInvert));
+ Assert.Throws<InvalidOperationException>(() => graphics.CopyFromScreen(Point.Empty, Point.Empty, Size.Empty));
+ Assert.Throws<InvalidOperationException>(() => graphics.CopyFromScreen(Point.Empty, Point.Empty, Size.Empty, CopyPixelOperation.DestinationInvert));
+ }
+ finally
+ {
+ graphics.ReleaseHdc();
+ }
+ }
+ }
+
+ [ConditionalFact(nameof(PlatformDetection) + "." + nameof(PlatformDetection.IsNotWindowsNanoServer))]
+ public void CopyFromScreen_Disposed_ThrowsArgumentException()
+ {
+ using (var image = new Bitmap(10, 10))
+ {
+ Graphics graphics = Graphics.FromImage(image);
+ graphics.Dispose();
+
+ AssertExtensions.Throws<ArgumentException>(null, () => graphics.CopyFromScreen(0, 0, 0, 0, Size.Empty));
+ AssertExtensions.Throws<ArgumentException>(null, () => graphics.CopyFromScreen(0, 0, 0, 0, Size.Empty, CopyPixelOperation.MergeCopy));
+ AssertExtensions.Throws<ArgumentException>(null, () => graphics.CopyFromScreen(Point.Empty, Point.Empty, Size.Empty));
+ AssertExtensions.Throws<ArgumentException>(null, () => graphics.CopyFromScreen(Point.Empty, Point.Empty, Size.Empty, CopyPixelOperation.MergeCopy));
+ }
+ }
+
+ public static IEnumerable<object[]> TransformPoints_TestData()
+ {
+ yield return new object[]
+ {
+ CoordinateSpace.Device,
+ CoordinateSpace.Page,
+ new Point[] { new Point(1, 1), new Point(2, 2) },
+ new Point[] { new Point(1, 1), new Point(2, 2) }
+ };
+
+ yield return new object[]
+ {
+ CoordinateSpace.Device,
+ CoordinateSpace.World,
+ new Point[] { new Point(1, 1), new Point(2, 2) },
+ new Point[] { new Point(9, 12), new Point(13, 18) }
+ };
+
+ yield return new object[]
+ {
+ CoordinateSpace.Page,
+ CoordinateSpace.Device,
+ new Point[] { new Point(1, 1), new Point(2, 2) },
+ new Point[] { new Point(1, 1), new Point(2, 2) }
+ };
+
+ yield return new object[]
+ {
+ CoordinateSpace.Page,
+ CoordinateSpace.World,
+ new Point[] { new Point(1, 1), new Point(2, 2) },
+ new Point[] { new Point(9, 12), new Point(13, 18) }
+ };
+
+ yield return new object[]
+ {
+ CoordinateSpace.World,
+ CoordinateSpace.Device,
+ new Point[] { new Point(1, 1), new Point(2, 2) },
+ new Point[] { new Point(1, -1), new Point(0, -1) }
+ };
+
+ yield return new object[]
+ {
+ CoordinateSpace.World,
+ CoordinateSpace.Page,
+ new Point[] { new Point(1, 1), new Point(2, 2) },
+ new Point[] { new Point(1, -1), new Point(0, -1) }
+ };
+ }
+
+ [ConditionalTheory(nameof(PlatformDetection) + "." + nameof(PlatformDetection.IsNotWindowsNanoServer))]
+ [MemberData(nameof(TransformPoints_TestData))]
+ public void TransformPoints_Points_Success(CoordinateSpace destSpace, CoordinateSpace srcSpace, Point[] points, Point[] expected)
+ {
+ using (var image = new Bitmap(10, 10))
+ using (Graphics graphics = Graphics.FromImage(image))
+ using (var transform = new Matrix(1, 2, 3, 4, 5, 6))
+ {
+ graphics.PageScale = 10;
+ graphics.Transform = transform;
+
+ graphics.TransformPoints(destSpace, srcSpace, points);
+ Assert.Equal(expected, points);
+ }
+ }
+
+ public static IEnumerable<object[]> TransformPointFs_TestData()
+ {
+ yield return new object[]
+ {
+ CoordinateSpace.Device,
+ CoordinateSpace.Page,
+ new PointF[] { new Point(1, 1), new Point(2, 2) },
+ new PointF[] { new Point(1, 1), new Point(2, 2) }
+ };
+
+ yield return new object[]
+ {
+ CoordinateSpace.Device,
+ CoordinateSpace.World,
+ new PointF[] { new Point(1, 1), new Point(2, 2) },
+ new PointF[] { new Point(9, 12), new Point(13, 18) }
+ };
+
+ yield return new object[]
+ {
+ CoordinateSpace.Page,
+ CoordinateSpace.Device,
+ new PointF[] { new Point(1, 1), new Point(2, 2) },
+ new PointF[] { new Point(1, 1), new Point(2, 2) }
+ };
+
+ yield return new object[]
+ {
+ CoordinateSpace.Page,
+ CoordinateSpace.World,
+ new PointF[] { new Point(1, 1), new Point(2, 2) },
+ new PointF[] { new Point(9, 12), new Point(13, 18) }
+ };
+
+ yield return new object[]
+ {
+ CoordinateSpace.World,
+ CoordinateSpace.Device,
+ new PointF[] { new Point(1, 1), new Point(2, 2) },
+ new PointF[] { new PointF(0.5f, -1.5f), new Point(0, -1) }
+ };
+
+ yield return new object[]
+ {
+ CoordinateSpace.World,
+ CoordinateSpace.Page,
+ new PointF[] { new Point(1, 1), new Point(2, 2) },
+ new PointF[] { new PointF(0.5f, -1.5f), new Point(0, -1) }
+ };
+ }
+
+ [ConditionalTheory(nameof(PlatformDetection) + "." + nameof(PlatformDetection.IsNotWindowsNanoServer))]
+ [MemberData(nameof(TransformPointFs_TestData))]
+ public void TransformPoints_PointFs_Success(CoordinateSpace destSpace, CoordinateSpace srcSpace, PointF[] points, PointF[] expected)
+ {
+ using (var image = new Bitmap(10, 10))
+ using (Graphics graphics = Graphics.FromImage(image))
+ using (var transform = new Matrix(1, 2, 3, 4, 5, 6))
+ {
+ graphics.PageScale = 10;
+ graphics.Transform = transform;
+
+ graphics.TransformPoints(destSpace, srcSpace, points);
+ Assert.Equal(expected, points);
+ }
+ }
+
+ [ConditionalTheory(nameof(PlatformDetection) + "." + nameof(PlatformDetection.IsNotWindowsNanoServer))]
+ [InlineData(CoordinateSpace.Device)]
+ [InlineData(CoordinateSpace.World)]
+ [InlineData(CoordinateSpace.Page)]
+ public void TransformPoints_PointsAndSameCoordinateSpace_DoesNothing(CoordinateSpace space)
+ {
+ using (var image = new Bitmap(10, 10))
+ using (Graphics graphics = Graphics.FromImage(image))
+ using (var transform = new Matrix(1, 2, 3, 4, 5, 6))
+ {
+ graphics.Transform = transform;
+
+ var points = new Point[] { new Point(1, 1) };
+ graphics.TransformPoints(space, space, points);
+ Assert.Equal(new Point[] { new Point(1, 1) }, points);
+ }
+ }
+
+ [ConditionalTheory(nameof(PlatformDetection) + "." + nameof(PlatformDetection.IsNotWindowsNanoServer))]
+ [InlineData(CoordinateSpace.Device)]
+ [InlineData(CoordinateSpace.World)]
+ [InlineData(CoordinateSpace.Page)]
+ public void TransformPoints_PointFsAndSameCoordinateSpace_DoesNothing(CoordinateSpace space)
+ {
+ using (var image = new Bitmap(10, 10))
+ using (Graphics graphics = Graphics.FromImage(image))
+ using (var transform = new Matrix(1, 2, 3, 4, 5, 6))
+ {
+ graphics.Transform = transform;
+
+ var points = new PointF[] { new PointF(1, 1) };
+ graphics.TransformPoints(space, space, points);
+ Assert.Equal(new PointF[] { new PointF(1, 1) }, points);
+ }
+ }
+
+ [ConditionalTheory(nameof(PlatformDetection) + "." + nameof(PlatformDetection.IsNotWindowsNanoServer))]
+ [InlineData(CoordinateSpace.World - 1)]
+ [InlineData(CoordinateSpace.Device + 1)]
+ public void TransformPoints_InvalidDestSpace_ThrowsArgumentException(CoordinateSpace destSpace)
+ {
+ using (var image = new Bitmap(10, 10))
+ using (Graphics graphics = Graphics.FromImage(image))
+ {
+ AssertExtensions.Throws<ArgumentException>(null, () => graphics.TransformPoints(destSpace, CoordinateSpace.World, new Point[] { new Point(1, 1) }));
+ AssertExtensions.Throws<ArgumentException>(null, () => graphics.TransformPoints(destSpace, CoordinateSpace.World, new PointF[] { new PointF(1, 1) }));
+ }
+ }
+
+ [ConditionalTheory(nameof(PlatformDetection) + "." + nameof(PlatformDetection.IsNotWindowsNanoServer))]
+ [InlineData(CoordinateSpace.World - 1)]
+ [InlineData(CoordinateSpace.Device + 1)]
+ public void TransformPoints_InvalidSourceSpace_ThrowsArgumentException(CoordinateSpace srcSpace)
+ {
+ using (var image = new Bitmap(10, 10))
+ using (Graphics graphics = Graphics.FromImage(image))
+ {
+ AssertExtensions.Throws<ArgumentException>(null, () => graphics.TransformPoints(CoordinateSpace.World, srcSpace, new Point[] { new Point(1, 1) }));
+ AssertExtensions.Throws<ArgumentException>(null, () => graphics.TransformPoints(CoordinateSpace.World, srcSpace, new PointF[] { new PointF(1, 1) }));
+ }
+ }
+
+ [ConditionalFact(nameof(PlatformDetection) + "." + nameof(PlatformDetection.IsNotWindowsNanoServer))]
+ public void TransformPoints_NullPoints_ThrowsArgumentNullException()
+ {
+ using (var image = new Bitmap(10, 10))
+ using (Graphics graphics = Graphics.FromImage(image))
+ {
+ AssertExtensions.Throws<ArgumentNullException>("pts", () => graphics.TransformPoints(CoordinateSpace.Page, CoordinateSpace.Page, (Point[])null));
+ AssertExtensions.Throws<ArgumentNullException>("pts", () => graphics.TransformPoints(CoordinateSpace.Page, CoordinateSpace.Page, (PointF[])null));
+ }
+ }
+
+ [ConditionalFact(nameof(PlatformDetection) + "." + nameof(PlatformDetection.IsNotWindowsNanoServer))]
+ public void TransformPoints_EmptyPoints_ThrowsArgumentException()
+ {
+ using (var image = new Bitmap(10, 10))
+ using (Graphics graphics = Graphics.FromImage(image))
+ {
+ AssertExtensions.Throws<ArgumentException>(null, () => graphics.TransformPoints(CoordinateSpace.Page, CoordinateSpace.Page, new Point[0]));
+ AssertExtensions.Throws<ArgumentException>(null, () => graphics.TransformPoints(CoordinateSpace.Page, CoordinateSpace.Page, new PointF[0]));
+ }
+ }
+
+ [ConditionalFact(nameof(PlatformDetection) + "." + nameof(PlatformDetection.IsNotWindowsNanoServer))]
+ public void TransformPoints_Busy_ThrowsInvalidOperationException()
+ {
+ using (var image = new Bitmap(10, 10))
+ using (Graphics graphics = Graphics.FromImage(image))
+ {
+ IntPtr hdc = graphics.GetHdc();
+ try
+ {
+ Assert.Throws<InvalidOperationException>(() => graphics.TransformPoints(CoordinateSpace.Page, CoordinateSpace.Page, new Point[] { Point.Empty }));
+ Assert.Throws<InvalidOperationException>(() => graphics.TransformPoints(CoordinateSpace.Page, CoordinateSpace.Page, new PointF[] { PointF.Empty }));
+ }
+ finally
+ {
+ graphics.ReleaseHdc();
+ }
+ }
+ }
+
+ [ConditionalFact(nameof(PlatformDetection) + "." + nameof(PlatformDetection.IsNotWindowsNanoServer))]
+ public void TransformPoints_Disposed_ThrowsArgumentException()
+ {
+ using (var image = new Bitmap(10, 10))
+ {
+ Graphics graphics = Graphics.FromImage(image);
+ graphics.Dispose();
+
+ AssertExtensions.Throws<ArgumentException>(null, () => graphics.TransformPoints(CoordinateSpace.Page, CoordinateSpace.Page, new Point[] { Point.Empty }));
+ AssertExtensions.Throws<ArgumentException>(null, () => graphics.TransformPoints(CoordinateSpace.Page, CoordinateSpace.Page, new PointF[] { PointF.Empty }));
+ }
+ }
+
+ public static IEnumerable<object[]> GetNearestColor_TestData()
+ {
+ yield return new object[] { PixelFormat.Format32bppArgb, Color.Red, Color.FromArgb(Color.Red.ToArgb()) };
+ yield return new object[] { PixelFormat.Format16bppRgb555, Color.Red, Color.FromArgb(255, 248, 0, 0) };
+ }
+
+ [ConditionalTheory(nameof(PlatformDetection) + "." + nameof(PlatformDetection.IsNotWindowsNanoServer))]
+ [MemberData(nameof(GetNearestColor_TestData))]
+ public void GetNearestColor_Color_ReturnsExpected(PixelFormat pixelFormat, Color color, Color expected)
+ {
+ using (var image = new Bitmap(10, 10, pixelFormat))
+ using (Graphics graphics = Graphics.FromImage(image))
+ {
+ Assert.Equal(expected, graphics.GetNearestColor(color));
+ }
+ }
+
+ [ConditionalFact(nameof(PlatformDetection) + "." + nameof(PlatformDetection.IsNotWindowsNanoServer))]
+ public void GetNearestColor_Busy_ThrowsInvalidOperationException()
+ {
+ using (var image = new Bitmap(10, 10))
+ using (Graphics graphics = Graphics.FromImage(image))
+ {
+ IntPtr hdc = graphics.GetHdc();
+ try
+ {
+ Assert.Throws<InvalidOperationException>(() => graphics.GetNearestColor(Color.Red));
+ }
+ finally
+ {
+ graphics.ReleaseHdc();
+ }
+ }
+ }
+
+ [ConditionalFact(nameof(PlatformDetection) + "." + nameof(PlatformDetection.IsNotWindowsNanoServer))]
+ public void GetNearestColor_Disposed_ThrowsArgumentException()
+ {
+ using (var image = new Bitmap(10, 10))
+ {
+ Graphics graphics = Graphics.FromImage(image);
+ graphics.Dispose();
+
+ AssertExtensions.Throws<ArgumentException>(null, () => graphics.GetNearestColor(Color.Red));
+ }
+ }
+
+ [ConditionalFact(nameof(PlatformDetection) + "." + nameof(PlatformDetection.IsNotWindowsNanoServer))]
+ public void DrawLine_NullPen_ThrowsArgumentNullException()
+ {
+ using (var image = new Bitmap(10, 10))
+ using (Graphics graphics = Graphics.FromImage(image))
+ {
+ AssertExtensions.Throws<ArgumentNullException>("pen", () => graphics.DrawLine(null, Point.Empty, Point.Empty));
+ AssertExtensions.Throws<ArgumentNullException>("pen", () => graphics.DrawLine(null, 0, 0, 0, 0));
+ AssertExtensions.Throws<ArgumentNullException>("pen", () => graphics.DrawLine(null, PointF.Empty, PointF.Empty));
+ AssertExtensions.Throws<ArgumentNullException>("pen", () => graphics.DrawLine(null, 0f, 0f, 0f, 0f));
+ }
+ }
+
+ [ConditionalFact(nameof(PlatformDetection) + "." + nameof(PlatformDetection.IsNotWindowsNanoServer))]
+ public void DrawLine_DisposedPen_ThrowsArgumentException()
+ {
+ using (var image = new Bitmap(10, 10))
+ using (Graphics graphics = Graphics.FromImage(image))
+ {
+ var pen = new Pen(Color.Red);
+ pen.Dispose();
+
+ AssertExtensions.Throws<ArgumentException>(null, () => graphics.DrawLine(pen, Point.Empty, Point.Empty));
+ AssertExtensions.Throws<ArgumentException>(null, () => graphics.DrawLine(pen, 0, 0, 0, 0));
+ AssertExtensions.Throws<ArgumentException>(null, () => graphics.DrawLine(pen, PointF.Empty, PointF.Empty));
+ AssertExtensions.Throws<ArgumentException>(null, () => graphics.DrawLine(pen, 0f, 0f, 0f, 0f));
+ }
+ }
+
+ [ConditionalFact(nameof(PlatformDetection) + "." + nameof(PlatformDetection.IsNotWindowsNanoServer))]
+ public void DrawLine_Busy_ThrowsInvalidOperationException()
+ {
+ using (var image = new Bitmap(10, 10))
+ using (Graphics graphics = Graphics.FromImage(image))
+ using (var pen = new Pen(Color.Red))
+ {
+ IntPtr hdc = graphics.GetHdc();
+ try
+ {
+ Assert.Throws<InvalidOperationException>(() => graphics.DrawLine(pen, Point.Empty, Point.Empty));
+ Assert.Throws<InvalidOperationException>(() => graphics.DrawLine(pen, 0, 0, 0, 0));
+ Assert.Throws<InvalidOperationException>(() => graphics.DrawLine(pen, PointF.Empty, PointF.Empty));
+ Assert.Throws<InvalidOperationException>(() => graphics.DrawLine(pen, 0f, 0f, 0f, 0f));
+ }
+ finally
+ {
+ graphics.ReleaseHdc();
+ }
+ }
+ }
+
+ [ConditionalFact(nameof(PlatformDetection) + "." + nameof(PlatformDetection.IsNotWindowsNanoServer))]
+ public void DrawLine_Disposed_ThrowsArgumentException()
+ {
+ using (var image = new Bitmap(10, 10))
+ using (var pen = new Pen(Color.Red))
+ {
+ Graphics graphics = Graphics.FromImage(image);
+ graphics.Dispose();
+
+ AssertExtensions.Throws<ArgumentException>(null, () => graphics.DrawLine(pen, Point.Empty, Point.Empty));
+ AssertExtensions.Throws<ArgumentException>(null, () => graphics.DrawLine(pen, 0, 0, 0, 0));
+ AssertExtensions.Throws<ArgumentException>(null, () => graphics.DrawLine(pen, PointF.Empty, PointF.Empty));
+ AssertExtensions.Throws<ArgumentException>(null, () => graphics.DrawLine(pen, 0f, 0f, 0f, 0f));
+ }
+ }
+
+ [ConditionalFact(nameof(PlatformDetection) + "." + nameof(PlatformDetection.IsNotWindowsNanoServer))]
+ public void DrawLines_NullPen_ThrowsArgumentNullException()
+ {
+ using (var image = new Bitmap(10, 10))
+ using (Graphics graphics = Graphics.FromImage(image))
+ {
+ AssertExtensions.Throws<ArgumentNullException>("pen", () => graphics.DrawLines(null, new Point[2]));
+ AssertExtensions.Throws<ArgumentNullException>("pen", () => graphics.DrawLines(null, new PointF[2]));
+ }
+ }
+
+ [ConditionalFact(nameof(PlatformDetection) + "." + nameof(PlatformDetection.IsNotWindowsNanoServer))]
+ public void DrawLines_DisposedPen_ThrowsArgumentException()
+ {
+ using (var image = new Bitmap(10, 10))
+ using (Graphics graphics = Graphics.FromImage(image))
+ {
+ var pen = new Pen(Color.Red);
+ pen.Dispose();
+
+ AssertExtensions.Throws<ArgumentException>(null, () => graphics.DrawLines(pen, new Point[2]));
+ AssertExtensions.Throws<ArgumentException>(null, () => graphics.DrawLines(pen, new PointF[2]));
+ }
+ }
+
+ [ConditionalFact(nameof(PlatformDetection) + "." + nameof(PlatformDetection.IsNotWindowsNanoServer))]
+ public void DrawLines_NullPoints_ThrowsArgumentNullException()
+ {
+ using (var image = new Bitmap(10, 10))
+ using (Graphics graphics = Graphics.FromImage(image))
+ using (var pen = new Pen(Color.Red))
+ {
+ AssertExtensions.Throws<ArgumentNullException>("points", () => graphics.DrawLines(pen, (Point[])null));
+ AssertExtensions.Throws<ArgumentNullException>("points", () => graphics.DrawLines(pen, (PointF[])null));
+ }
+ }
+
+ [ConditionalTheory(nameof(PlatformDetection) + "." + nameof(PlatformDetection.IsNotWindowsNanoServer))]
+ [InlineData(0)]
+ [InlineData(1)]
+ public void DrawLines_InvalidPointsLength_ThrowsArgumentException(int length)
+ {
+ using (var image = new Bitmap(10, 10))
+ using (Graphics graphics = Graphics.FromImage(image))
+ using (var pen = new Pen(Color.Red))
+ {
+ AssertExtensions.Throws<ArgumentException>(null, () => graphics.DrawLines(pen, new Point[length]));
+ AssertExtensions.Throws<ArgumentException>(null, () => graphics.DrawLines(pen, new PointF[length]));
+ }
+ }
+
+ [ConditionalFact(nameof(PlatformDetection) + "." + nameof(PlatformDetection.IsNotWindowsNanoServer))]
+ public void DrawLines_Busy_ThrowsInvalidOperationException()
+ {
+ using (var image = new Bitmap(10, 10))
+ using (Graphics graphics = Graphics.FromImage(image))
+ using (var pen = new Pen(Color.Red))
+ {
+ IntPtr hdc = graphics.GetHdc();
+ try
+ {
+ Assert.Throws<InvalidOperationException>(() => graphics.DrawLines(pen, new Point[2]));
+ Assert.Throws<InvalidOperationException>(() => graphics.DrawLines(pen, new PointF[2]));
+ }
+ finally
+ {
+ graphics.ReleaseHdc();
+ }
+ }
+ }
+
+ [ConditionalFact(nameof(PlatformDetection) + "." + nameof(PlatformDetection.IsNotWindowsNanoServer))]
+ public void DrawLines_Disposed_ThrowsArgumentException()
+ {
+ using (var image = new Bitmap(10, 10))
+ using (var pen = new Pen(Color.Red))
+ {
+ Graphics graphics = Graphics.FromImage(image);
+ graphics.Dispose();
+
+ AssertExtensions.Throws<ArgumentException>(null, () => graphics.DrawLines(pen, new Point[2]));
+ AssertExtensions.Throws<ArgumentException>(null, () => graphics.DrawLines(pen, new PointF[2]));
+ }
+ }
+
+ [ConditionalFact(nameof(PlatformDetection) + "." + nameof(PlatformDetection.IsNotWindowsNanoServer))]
+ public void DrawArc_NullPen_ThrowsArgumentNullException()
+ {
+ using (var image = new Bitmap(10, 10))
+ using (Graphics graphics = Graphics.FromImage(image))
+ {
+ AssertExtensions.Throws<ArgumentNullException>("pen", () => graphics.DrawArc(null, new Rectangle(0, 0, 1, 1), 0, 90));
+ AssertExtensions.Throws<ArgumentNullException>("pen", () => graphics.DrawArc(null, 0, 0, 1, 1, 0, 90));
+ AssertExtensions.Throws<ArgumentNullException>("pen", () => graphics.DrawArc(null, new RectangleF(0, 0, 1, 1), 0, 90));
+ AssertExtensions.Throws<ArgumentNullException>("pen", () => graphics.DrawArc(null, 0f, 0f, 1f, 1f, 0, 90));
+ }
+ }
+
+ [ConditionalFact(nameof(PlatformDetection) + "." + nameof(PlatformDetection.IsNotWindowsNanoServer))]
+ public void DrawArc_DisposedPen_ThrowsArgumentException()
+ {
+ using (var image = new Bitmap(10, 10))
+ using (Graphics graphics = Graphics.FromImage(image))
+ {
+ var pen = new Pen(Color.Red);
+ pen.Dispose();
+
+ AssertExtensions.Throws<ArgumentException>(null, () => graphics.DrawArc(pen, new Rectangle(0, 0, 1, 1), 0, 90));
+ AssertExtensions.Throws<ArgumentException>(null, () => graphics.DrawArc(pen, 0, 0, 1, 1, 0, 90));
+ AssertExtensions.Throws<ArgumentException>(null, () => graphics.DrawArc(pen, new RectangleF(0, 0, 1, 1), 0, 90));
+ AssertExtensions.Throws<ArgumentException>(null, () => graphics.DrawArc(pen, 0f, 0f, 1f, 1f, 0, 90));
+ }
+ }
+
+ [ConditionalFact(nameof(PlatformDetection) + "." + nameof(PlatformDetection.IsNotWindowsNanoServer))]
+ public void DrawArc_ZeroWidth_ThrowsArgumentException()
+ {
+ using (var image = new Bitmap(10, 10))
+ using (Graphics graphics = Graphics.FromImage(image))
+ using (var pen = new Pen(Color.Red))
+ {
+ AssertExtensions.Throws<ArgumentException>(null, () => graphics.DrawArc(pen, new Rectangle(0, 0, 0, 1), 0, 90));
+ AssertExtensions.Throws<ArgumentException>(null, () => graphics.DrawArc(pen, 0, 0, 0, 1, 0, 90));
+ AssertExtensions.Throws<ArgumentException>(null, () => graphics.DrawArc(pen, new RectangleF(0, 0, 0, 1), 0, 90));
+ AssertExtensions.Throws<ArgumentException>(null, () => graphics.DrawArc(pen, 0f, 0f, 0f, 1f, 0, 90));
+ }
+ }
+
+ [ConditionalFact(nameof(PlatformDetection) + "." + nameof(PlatformDetection.IsNotWindowsNanoServer))]
+ public void DrawArc_ZeroHeight_ThrowsArgumentException()
+ {
+ using (var image = new Bitmap(10, 10))
+ using (Graphics graphics = Graphics.FromImage(image))
+ using (var pen = new Pen(Color.Red))
+ {
+ AssertExtensions.Throws<ArgumentException>(null, () => graphics.DrawArc(pen, new Rectangle(0, 0, 1, 0), 0, 90));
+ AssertExtensions.Throws<ArgumentException>(null, () => graphics.DrawArc(pen, 0, 0, 1, 0, 0, 90));
+ AssertExtensions.Throws<ArgumentException>(null, () => graphics.DrawArc(pen, new RectangleF(0, 0, 1, 0), 0, 90));
+ AssertExtensions.Throws<ArgumentException>(null, () => graphics.DrawArc(pen, 0f, 0f, 1f, 0f, 0, 90));
+ }
+ }
+
+ [ConditionalFact(nameof(PlatformDetection) + "." + nameof(PlatformDetection.IsNotWindowsNanoServer))]
+ public void DrawArc_Busy_ThrowsInvalidOperationException()
+ {
+ using (var image = new Bitmap(10, 10))
+ using (Graphics graphics = Graphics.FromImage(image))
+ using (var pen = new Pen(Color.Red))
+ {
+ IntPtr hdc = graphics.GetHdc();
+ try
+ {
+ Assert.Throws<InvalidOperationException>(() => graphics.DrawArc(pen, new Rectangle(0, 0, 1, 1), 0, 90));
+ Assert.Throws<InvalidOperationException>(() => graphics.DrawArc(pen, 0, 0, 1, 1, 0, 90));
+ Assert.Throws<InvalidOperationException>(() => graphics.DrawArc(pen, new RectangleF(0, 0, 1, 1), 0, 90));
+ Assert.Throws<InvalidOperationException>(() => graphics.DrawArc(pen, 0f, 0f, 1f, 1f, 0, 90));
+ }
+ finally
+ {
+ graphics.ReleaseHdc();
+ }
+ }
+ }
+
+ [ConditionalFact(nameof(PlatformDetection) + "." + nameof(PlatformDetection.IsNotWindowsNanoServer))]
+ public void DrawArc_Disposed_ThrowsArgumentException()
+ {
+ using (var image = new Bitmap(10, 10))
+ using (var pen = new Pen(Color.Red))
+ {
+ Graphics graphics = Graphics.FromImage(image);
+ graphics.Dispose();
+
+ AssertExtensions.Throws<ArgumentException>(null, () => graphics.DrawArc(pen, new Rectangle(0, 0, 1, 1), 0, 90));
+ AssertExtensions.Throws<ArgumentException>(null, () => graphics.DrawArc(pen, 0, 0, 1, 1, 0, 90));
+ AssertExtensions.Throws<ArgumentException>(null, () => graphics.DrawArc(pen, new RectangleF(0, 0, 1, 1), 0, 90));
+ AssertExtensions.Throws<ArgumentException>(null, () => graphics.DrawArc(pen, 0f, 0f, 1f, 1f, 0, 90));
+ }
+ }
+
+ [ConditionalFact(nameof(PlatformDetection) + "." + nameof(PlatformDetection.IsNotWindowsNanoServer))]
+ public void DrawBezier_NullPen_ThrowsArgumentNullException()
+ {
+ using (var image = new Bitmap(10, 10))
+ using (Graphics graphics = Graphics.FromImage(image))
+ {
+ AssertExtensions.Throws<ArgumentNullException>("pen", () => graphics.DrawBezier(null, 1, 2, 3, 4, 5, 6, 7, 8));
+ AssertExtensions.Throws<ArgumentNullException>("pen", () => graphics.DrawBezier(null, Point.Empty, Point.Empty, Point.Empty, Point.Empty));
+ AssertExtensions.Throws<ArgumentNullException>("pen", () => graphics.DrawBezier(null, PointF.Empty, PointF.Empty, PointF.Empty, PointF.Empty));
+ }
+ }
+
+ [ConditionalFact(nameof(PlatformDetection) + "." + nameof(PlatformDetection.IsNotWindowsNanoServer))]
+ public void DrawBezier_DisposedPen_ThrowsArgumentException()
+ {
+ using (var image = new Bitmap(10, 10))
+ using (Graphics graphics = Graphics.FromImage(image))
+ {
+ var pen = new Pen(Color.Red);
+ pen.Dispose();
+
+ AssertExtensions.Throws<ArgumentException>(null, () => graphics.DrawBezier(pen, 1, 2, 3, 4, 5, 6, 7, 8));
+ AssertExtensions.Throws<ArgumentException>(null, () => graphics.DrawBezier(pen, Point.Empty, Point.Empty, Point.Empty, Point.Empty));
+ AssertExtensions.Throws<ArgumentException>(null, () => graphics.DrawBezier(pen, PointF.Empty, PointF.Empty, PointF.Empty, PointF.Empty));
+ }
+ }
+
+ [ConditionalFact(nameof(PlatformDetection) + "." + nameof(PlatformDetection.IsNotWindowsNanoServer))]
+ public void DrawBezier_Busy_ThrowsInvalidOperationException()
+ {
+ using (var image = new Bitmap(10, 10))
+ using (Graphics graphics = Graphics.FromImage(image))
+ using (var pen = new Pen(Color.Red))
+ {
+ IntPtr hdc = graphics.GetHdc();
+ try
+ {
+ Assert.Throws<InvalidOperationException>(() => graphics.DrawBezier(pen, 1, 2, 3, 4, 5, 6, 7, 8));
+ Assert.Throws<InvalidOperationException>(() => graphics.DrawBezier(pen, Point.Empty, Point.Empty, Point.Empty, Point.Empty));
+ Assert.Throws<InvalidOperationException>(() => graphics.DrawBezier(pen, PointF.Empty, PointF.Empty, PointF.Empty, PointF.Empty));
+ }
+ finally
+ {
+ graphics.ReleaseHdc();
+ }
+ }
+ }
+
+ [ConditionalFact(nameof(PlatformDetection) + "." + nameof(PlatformDetection.IsNotWindowsNanoServer))]
+ public void DrawBezier_Disposed_ThrowsArgumentException()
+ {
+ using (var image = new Bitmap(10, 10))
+ using (var pen = new Pen(Color.Red))
+ {
+ Graphics graphics = Graphics.FromImage(image);
+ graphics.Dispose();
+
+ AssertExtensions.Throws<ArgumentException>(null, () => graphics.DrawArc(pen, new Rectangle(0, 0, 1, 1), 0, 90));
+ AssertExtensions.Throws<ArgumentException>(null, () => graphics.DrawArc(pen, 0, 0, 1, 1, 0, 90));
+ AssertExtensions.Throws<ArgumentException>(null, () => graphics.DrawArc(pen, new RectangleF(0, 0, 1, 1), 0, 90));
+ AssertExtensions.Throws<ArgumentException>(null, () => graphics.DrawArc(pen, 0f, 0f, 1f, 1f, 0, 90));
+ }
+ }
+
+ [ConditionalFact(nameof(PlatformDetection) + "." + nameof(PlatformDetection.IsNotWindowsNanoServer))]
+ public void DrawBeziers_NullPen_ThrowsArgumentNullException()
+ {
+ using (var image = new Bitmap(10, 10))
+ using (Graphics graphics = Graphics.FromImage(image))
+ {
+ AssertExtensions.Throws<ArgumentNullException>("pen", () => graphics.DrawBeziers(null, new Point[2]));
+ AssertExtensions.Throws<ArgumentNullException>("pen", () => graphics.DrawBeziers(null, new PointF[2]));
+ }
+ }
+
+ [ConditionalFact(nameof(PlatformDetection) + "." + nameof(PlatformDetection.IsNotWindowsNanoServer))]
+ public void DrawBeziers_DisposedPen_ThrowsArgumentException()
+ {
+ using (var image = new Bitmap(10, 10))
+ using (Graphics graphics = Graphics.FromImage(image))
+ {
+ var pen = new Pen(Color.Red);
+ pen.Dispose();
+
+ AssertExtensions.Throws<ArgumentException>(null, () => graphics.DrawBeziers(pen, new Point[2]));
+ AssertExtensions.Throws<ArgumentException>(null, () => graphics.DrawBeziers(pen, new PointF[2]));
+ }
+ }
+
+ [ConditionalFact(nameof(PlatformDetection) + "." + nameof(PlatformDetection.IsNotWindowsNanoServer))]
+ public void DrawBeziers_NullPoints_ThrowsArgumentNullException()
+ {
+ using (var image = new Bitmap(10, 10))
+ using (Graphics graphics = Graphics.FromImage(image))
+ using (var pen = new Pen(Color.Red))
+ {
+ AssertExtensions.Throws<ArgumentNullException>("points", () => graphics.DrawBeziers(pen, (Point[])null));
+ AssertExtensions.Throws<ArgumentNullException>("points", () => graphics.DrawBeziers(pen, (PointF[])null));
+ }
+ }
+
+ [ConditionalFact(nameof(PlatformDetection) + "." + nameof(PlatformDetection.IsNotWindowsNanoServer))]
+ public void DrawBeziers_EmptyPoints_ThrowsArgumentException()
+ {
+ using (var image = new Bitmap(10, 10))
+ using (Graphics graphics = Graphics.FromImage(image))
+ using (var pen = new Pen(Color.Red))
+ {
+ AssertExtensions.Throws<ArgumentException>(null, () => graphics.DrawBeziers(pen, new Point[0]));
+ AssertExtensions.Throws<ArgumentException>(null, () => graphics.DrawBeziers(pen, new PointF[0]));
+ }
+ }
+
+ [ConditionalFact(nameof(PlatformDetection) + "." + nameof(PlatformDetection.IsNotWindowsNanoServer))]
+ public void DrawBeziers_Busy_ThrowsInvalidOperationException()
+ {
+ using (var image = new Bitmap(10, 10))
+ using (Graphics graphics = Graphics.FromImage(image))
+ using (var pen = new Pen(Color.Red))
+ {
+ IntPtr hdc = graphics.GetHdc();
+ try
+ {
+ Assert.Throws<InvalidOperationException>(() => graphics.DrawBeziers(pen, new Point[2]));
+ Assert.Throws<InvalidOperationException>(() => graphics.DrawBeziers(pen, new PointF[2]));
+ }
+ finally
+ {
+ graphics.ReleaseHdc();
+ }
+ }
+ }
+
+ [ConditionalFact(nameof(PlatformDetection) + "." + nameof(PlatformDetection.IsNotWindowsNanoServer))]
+ public void DrawBeziers_Disposed_ThrowsArgumentException()
+ {
+ using (var image = new Bitmap(10, 10))
+ using (var pen = new Pen(Color.Red))
+ {
+ Graphics graphics = Graphics.FromImage(image);
+ graphics.Dispose();
+
+ AssertExtensions.Throws<ArgumentException>(null, () => graphics.DrawBeziers(pen, new Point[2]));
+ AssertExtensions.Throws<ArgumentException>(null, () => graphics.DrawBeziers(pen, new PointF[2]));
+ }
+ }
+
+ [ConditionalFact(nameof(PlatformDetection) + "." + nameof(PlatformDetection.IsNotWindowsNanoServer))]
+ public void DrawRectangle_NullPen_ThrowsArgumentNullException()
+ {
+ using (var image = new Bitmap(10, 10))
+ using (Graphics graphics = Graphics.FromImage(image))
+ {
+ AssertExtensions.Throws<ArgumentNullException>("pen", () => graphics.DrawRectangle(null, new Rectangle(0, 0, 1, 1)));
+ AssertExtensions.Throws<ArgumentNullException>("pen", () => graphics.DrawRectangle(null, 0, 0, 1, 1));
+ AssertExtensions.Throws<ArgumentNullException>("pen", () => graphics.DrawRectangle(null, 0f, 0f, 1f, 1f));
+ }
+ }
+
+ [ConditionalFact(nameof(PlatformDetection) + "." + nameof(PlatformDetection.IsNotWindowsNanoServer))]
+ public void DrawRectangle_DisposedPen_ThrowsArgumentException()
+ {
+ using (var image = new Bitmap(10, 10))
+ using (Graphics graphics = Graphics.FromImage(image))
+ {
+ var pen = new Pen(Color.Red);
+ pen.Dispose();
+
+
+ AssertExtensions.Throws<ArgumentException>(null, () => graphics.DrawRectangle(pen, new Rectangle(0, 0, 1, 1)));
+ AssertExtensions.Throws<ArgumentException>(null, () => graphics.DrawRectangle(pen, 0, 0, 1, 1));
+ AssertExtensions.Throws<ArgumentException>(null, () => graphics.DrawRectangle(pen, 0f, 0f, 1f, 1f));
+ }
+ }
+
+ [ConditionalFact(nameof(PlatformDetection) + "." + nameof(PlatformDetection.IsNotWindowsNanoServer))]
+ public void DrawRectangle_Busy_ThrowsInvalidOperationException()
+ {
+ using (var image = new Bitmap(10, 10))
+ using (Graphics graphics = Graphics.FromImage(image))
+ using (var pen = new Pen(Color.Red))
+ {
+ IntPtr hdc = graphics.GetHdc();
+ try
+ {
+ Assert.Throws<InvalidOperationException>(() => graphics.DrawRectangle(pen, new Rectangle(0, 0, 1, 1)));
+ Assert.Throws<InvalidOperationException>(() => graphics.DrawRectangle(pen, 0, 0, 1, 1));
+ Assert.Throws<InvalidOperationException>(() => graphics.DrawRectangle(pen, 0f, 0f, 1f, 1f));
+ }
+ finally
+ {
+ graphics.ReleaseHdc();
+ }
+ }
+ }
+
+ [ConditionalFact(nameof(PlatformDetection) + "." + nameof(PlatformDetection.IsNotWindowsNanoServer))]
+ public void DrawRectangle_Disposed_ThrowsArgumentException()
+ {
+ using (var image = new Bitmap(10, 10))
+ using (var pen = new Pen(Color.Red))
+ {
+ Graphics graphics = Graphics.FromImage(image);
+ graphics.Dispose();
+
+ AssertExtensions.Throws<ArgumentException>(null, () => graphics.DrawRectangle(pen, new Rectangle(0, 0, 1, 1)));
+ AssertExtensions.Throws<ArgumentException>(null, () => graphics.DrawRectangle(pen, 0, 0, 1, 1));
+ AssertExtensions.Throws<ArgumentException>(null, () => graphics.DrawRectangle(pen, 0f, 0f, 1f, 1f));
+ }
+ }
+
+ [ConditionalFact(nameof(PlatformDetection) + "." + nameof(PlatformDetection.IsNotWindowsNanoServer))]
+ public void DrawRectangles_NullPen_ThrowsArgumentNullException()
+ {
+ using (var image = new Bitmap(10, 10))
+ using (Graphics graphics = Graphics.FromImage(image))
+ {
+ AssertExtensions.Throws<ArgumentNullException>("pen", () => graphics.DrawRectangles(null, new Rectangle[2]));
+ AssertExtensions.Throws<ArgumentNullException>("pen", () => graphics.DrawRectangles(null, new RectangleF[2]));
+ }
+ }
+
+ [ConditionalFact(nameof(PlatformDetection) + "." + nameof(PlatformDetection.IsNotWindowsNanoServer))]
+ public void DrawRectangles_DisposedPen_ThrowsArgumentException()
+ {
+ using (var image = new Bitmap(10, 10))
+ using (Graphics graphics = Graphics.FromImage(image))
+ {
+ var pen = new Pen(Color.Red);
+ pen.Dispose();
+
+ AssertExtensions.Throws<ArgumentException>(null, () => graphics.DrawRectangles(pen, new Rectangle[2]));
+ AssertExtensions.Throws<ArgumentException>(null, () => graphics.DrawRectangles(pen, new RectangleF[2]));
+ }
+ }
+
+ [ConditionalFact(nameof(PlatformDetection) + "." + nameof(PlatformDetection.IsNotWindowsNanoServer))]
+ public void DrawRectangles_NullRectangles_ThrowsArgumentNullException()
+ {
+ using (var image = new Bitmap(10, 10))
+ using (Graphics graphics = Graphics.FromImage(image))
+ using (var pen = new Pen(Color.Red))
+ {
+ AssertExtensions.Throws<ArgumentNullException>("rects", () => graphics.DrawRectangles(pen, (Rectangle[])null));
+ AssertExtensions.Throws<ArgumentNullException>("rects", () => graphics.DrawRectangles(pen, (RectangleF[])null));
+ }
+ }
+
+ [ConditionalFact(nameof(PlatformDetection) + "." + nameof(PlatformDetection.IsNotWindowsNanoServer))]
+ public void DrawRectangles_EmptyRectangles_ThrowsArgumentException()
+ {
+ using (var image = new Bitmap(10, 10))
+ using (Graphics graphics = Graphics.FromImage(image))
+ using (var pen = new Pen(Color.Red))
+ {
+ AssertExtensions.Throws<ArgumentException>(null, () => graphics.DrawRectangles(pen, new Rectangle[0]));
+ AssertExtensions.Throws<ArgumentException>(null, () => graphics.DrawRectangles(pen, new RectangleF[0]));
+ }
+ }
+
+ [ConditionalFact(nameof(PlatformDetection) + "." + nameof(PlatformDetection.IsNotWindowsNanoServer))]
+ public void DrawRectangles_Busy_ThrowsInvalidOperationException()
+ {
+ using (var image = new Bitmap(10, 10))
+ using (Graphics graphics = Graphics.FromImage(image))
+ using (var pen = new Pen(Color.Red))
+ {
+ IntPtr hdc = graphics.GetHdc();
+ try
+ {
+ Assert.Throws<InvalidOperationException>(() => graphics.DrawRectangles(pen, new Rectangle[2]));
+ Assert.Throws<InvalidOperationException>(() => graphics.DrawRectangles(pen, new RectangleF[2]));
+ }
+ finally
+ {
+ graphics.ReleaseHdc();
+ }
+ }
+ }
+
+ [ConditionalFact(nameof(PlatformDetection) + "." + nameof(PlatformDetection.IsNotWindowsNanoServer))]
+ public void DrawRectangles_Disposed_ThrowsArgumentException()
+ {
+ using (var image = new Bitmap(10, 10))
+ using (var pen = new Pen(Color.Red))
+ {
+ Graphics graphics = Graphics.FromImage(image);
+ graphics.Dispose();
+
+ AssertExtensions.Throws<ArgumentException>(null, () => graphics.DrawRectangles(pen, new Rectangle[2]));
+ AssertExtensions.Throws<ArgumentException>(null, () => graphics.DrawRectangles(pen, new RectangleF[2]));
+ }
+ }
+
+ [ConditionalFact(nameof(PlatformDetection) + "." + nameof(PlatformDetection.IsNotWindowsNanoServer))]
+ public void DrawEllipse_NullPen_ThrowsArgumentNullException()
+ {
+ using (var image = new Bitmap(10, 10))
+ using (Graphics graphics = Graphics.FromImage(image))
+ {
+ AssertExtensions.Throws<ArgumentNullException>("pen", () => graphics.DrawEllipse(null, new Rectangle(0, 0, 1, 1)));
+ AssertExtensions.Throws<ArgumentNullException>("pen", () => graphics.DrawEllipse(null, 0, 0, 1, 1));
+ AssertExtensions.Throws<ArgumentNullException>("pen", () => graphics.DrawEllipse(null, new RectangleF(0, 0, 1, 1)));
+ AssertExtensions.Throws<ArgumentNullException>("pen", () => graphics.DrawEllipse(null, 0f, 0f, 1f, 1f));
+ }
+ }
+
+ [ConditionalFact(nameof(PlatformDetection) + "." + nameof(PlatformDetection.IsNotWindowsNanoServer))]
+ public void DrawEllipse_DisposedPen_ThrowsArgumentException()
+ {
+ using (var image = new Bitmap(10, 10))
+ using (Graphics graphics = Graphics.FromImage(image))
+ {
+ var pen = new Pen(Color.Red);
+ pen.Dispose();
+
+
+ AssertExtensions.Throws<ArgumentException>(null, () => graphics.DrawEllipse(pen, new Rectangle(0, 0, 1, 1)));
+ AssertExtensions.Throws<ArgumentException>(null, () => graphics.DrawEllipse(pen, 0, 0, 1, 1));
+ AssertExtensions.Throws<ArgumentException>(null, () => graphics.DrawEllipse(pen, new RectangleF(0, 0, 1, 1)));
+ AssertExtensions.Throws<ArgumentException>(null, () => graphics.DrawEllipse(pen, 0f, 0f, 1f, 1f));
+ }
+ }
+
+ [ConditionalFact(nameof(PlatformDetection) + "." + nameof(PlatformDetection.IsNotWindowsNanoServer))]
+ public void DrawEllipse_Busy_ThrowsInvalidOperationException()
+ {
+ using (var image = new Bitmap(10, 10))
+ using (Graphics graphics = Graphics.FromImage(image))
+ using (var pen = new Pen(Color.Red))
+ {
+ IntPtr hdc = graphics.GetHdc();
+ try
+ {
+ Assert.Throws<InvalidOperationException>(() => graphics.DrawEllipse(pen, new Rectangle(0, 0, 1, 1)));
+ Assert.Throws<InvalidOperationException>(() => graphics.DrawEllipse(pen, 0, 0, 1, 1));
+ Assert.Throws<InvalidOperationException>(() => graphics.DrawEllipse(pen, new RectangleF(0, 0, 1, 1)));
+ Assert.Throws<InvalidOperationException>(() => graphics.DrawEllipse(pen, 0f, 0f, 1f, 1f));
+ }
+ finally
+ {
+ graphics.ReleaseHdc();
+ }
+ }
+ }
+
+ [ConditionalFact(nameof(PlatformDetection) + "." + nameof(PlatformDetection.IsNotWindowsNanoServer))]
+ public void DrawEllipse_Disposed_ThrowsArgumentException()
+ {
+ using (var image = new Bitmap(10, 10))
+ using (var pen = new Pen(Color.Red))
+ {
+ Graphics graphics = Graphics.FromImage(image);
+ graphics.Dispose();
+
+ AssertExtensions.Throws<ArgumentException>(null, () => graphics.DrawEllipse(pen, new Rectangle(0, 0, 1, 1)));
+ AssertExtensions.Throws<ArgumentException>(null, () => graphics.DrawEllipse(pen, 0, 0, 1, 1));
+ AssertExtensions.Throws<ArgumentException>(null, () => graphics.DrawEllipse(pen, new RectangleF(0, 0, 1, 1)));
+ AssertExtensions.Throws<ArgumentException>(null, () => graphics.DrawEllipse(pen, 0f, 0f, 1f, 1f));
+ }
+ }
+
+ [ConditionalFact(nameof(PlatformDetection) + "." + nameof(PlatformDetection.IsNotWindowsNanoServer))]
+ public void DrawPie_NullPen_ThrowsArgumentNullException()
+ {
+ using (var image = new Bitmap(10, 10))
+ using (Graphics graphics = Graphics.FromImage(image))
+ {
+ AssertExtensions.Throws<ArgumentNullException>("pen", () => graphics.DrawPie(null, new Rectangle(0, 0, 1, 1), 0, 90));
+ AssertExtensions.Throws<ArgumentNullException>("pen", () => graphics.DrawPie(null, 0, 0, 1, 1, 0, 90));
+ AssertExtensions.Throws<ArgumentNullException>("pen", () => graphics.DrawPie(null, new RectangleF(0, 0, 1, 1), 0, 90));
+ AssertExtensions.Throws<ArgumentNullException>("pen", () => graphics.DrawPie(null, 0f, 0f, 1f, 1f, 0, 90));
+ }
+ }
+
+ [ConditionalFact(nameof(PlatformDetection) + "." + nameof(PlatformDetection.IsNotWindowsNanoServer))]
+ public void DrawPie_DisposedPen_ThrowsArgumentException()
+ {
+ using (var image = new Bitmap(10, 10))
+ using (Graphics graphics = Graphics.FromImage(image))
+ {
+ var pen = new Pen(Color.Red);
+ pen.Dispose();
+
+ AssertExtensions.Throws<ArgumentException>(null, () => graphics.DrawPie(pen, new Rectangle(0, 0, 1, 1), 0, 90));
+ AssertExtensions.Throws<ArgumentException>(null, () => graphics.DrawPie(pen, 0, 0, 1, 1, 0, 90));
+ AssertExtensions.Throws<ArgumentException>(null, () => graphics.DrawPie(pen, new RectangleF(0, 0, 1, 1), 0, 90));
+ AssertExtensions.Throws<ArgumentException>(null, () => graphics.DrawPie(pen, 0f, 0f, 1f, 1f, 0, 90));
+ }
+ }
+
+ [ConditionalFact(nameof(PlatformDetection) + "." + nameof(PlatformDetection.IsNotWindowsNanoServer))]
+ public void DrawPie_ZeroWidth_ThrowsArgumentException()
+ {
+ using (var image = new Bitmap(10, 10))
+ using (Graphics graphics = Graphics.FromImage(image))
+ using (var pen = new Pen(Color.Red))
+ {
+ AssertExtensions.Throws<ArgumentException>(null, () => graphics.DrawPie(pen, new Rectangle(0, 0, 0, 1), 0, 90));
+ AssertExtensions.Throws<ArgumentException>(null, () => graphics.DrawPie(pen, 0, 0, 0, 1, 0, 90));
+ AssertExtensions.Throws<ArgumentException>(null, () => graphics.DrawPie(pen, new RectangleF(0, 0, 0, 1), 0, 90));
+ AssertExtensions.Throws<ArgumentException>(null, () => graphics.DrawPie(pen, 0f, 0f, 0f, 1f, 0, 90));
+ }
+ }
+
+ [ConditionalFact(nameof(PlatformDetection) + "." + nameof(PlatformDetection.IsNotWindowsNanoServer))]
+ public void DrawPie_ZeroHeight_ThrowsArgumentException()
+ {
+ using (var image = new Bitmap(10, 10))
+ using (Graphics graphics = Graphics.FromImage(image))
+ using (var pen = new Pen(Color.Red))
+ {
+ AssertExtensions.Throws<ArgumentException>(null, () => graphics.DrawArc(pen, new Rectangle(0, 0, 1, 0), 0, 90));
+ AssertExtensions.Throws<ArgumentException>(null, () => graphics.DrawArc(pen, 0, 0, 1, 0, 0, 90));
+ AssertExtensions.Throws<ArgumentException>(null, () => graphics.DrawArc(pen, new RectangleF(0, 0, 1, 0), 0, 90));
+ AssertExtensions.Throws<ArgumentException>(null, () => graphics.DrawArc(pen, 0f, 0f, 1f, 0f, 0, 90));
+ }
+ }
+
+ [ConditionalFact(nameof(PlatformDetection) + "." + nameof(PlatformDetection.IsNotWindowsNanoServer))]
+ public void DrawPie_Busy_ThrowsInvalidOperationException()
+ {
+ using (var image = new Bitmap(10, 10))
+ using (Graphics graphics = Graphics.FromImage(image))
+ using (var pen = new Pen(Color.Red))
+ {
+ IntPtr hdc = graphics.GetHdc();
+ try
+ {
+ Assert.Throws<InvalidOperationException>(() => graphics.DrawPie(pen, new Rectangle(0, 0, 1, 1), 0, 90));
+ Assert.Throws<InvalidOperationException>(() => graphics.DrawPie(pen, 0, 0, 1, 1, 0, 90));
+ Assert.Throws<InvalidOperationException>(() => graphics.DrawPie(pen, new RectangleF(0, 0, 1, 1), 0, 90));
+ Assert.Throws<InvalidOperationException>(() => graphics.DrawPie(pen, 0f, 0f, 1f, 1f, 0, 90));
+ }
+ finally
+ {
+ graphics.ReleaseHdc();
+ }
+ }
+ }
+
+ [ConditionalFact(nameof(PlatformDetection) + "." + nameof(PlatformDetection.IsNotWindowsNanoServer))]
+ public void DrawPie_Disposed_ThrowsArgumentException()
+ {
+ using (var image = new Bitmap(10, 10))
+ using (var pen = new Pen(Color.Red))
+ {
+ Graphics graphics = Graphics.FromImage(image);
+ graphics.Dispose();
+
+ AssertExtensions.Throws<ArgumentException>(null, () => graphics.DrawPie(pen, new Rectangle(0, 0, 1, 1), 0, 90));
+ AssertExtensions.Throws<ArgumentException>(null, () => graphics.DrawPie(pen, 0, 0, 1, 1, 0, 90));
+ AssertExtensions.Throws<ArgumentException>(null, () => graphics.DrawPie(pen, new RectangleF(0, 0, 1, 1), 0, 90));
+ AssertExtensions.Throws<ArgumentException>(null, () => graphics.DrawPie(pen, 0f, 0f, 1f, 1f, 0, 90));
+ }
+ }
+
+ [ConditionalFact(nameof(PlatformDetection) + "." + nameof(PlatformDetection.IsNotWindowsNanoServer))]
+ public void DrawPolygon_NullPen_ThrowsArgumentNullException()
+ {
+ using (var image = new Bitmap(10, 10))
+ using (Graphics graphics = Graphics.FromImage(image))
+ {
+ AssertExtensions.Throws<ArgumentNullException>("pen", () => graphics.DrawPolygon(null, new Point[2]));
+ AssertExtensions.Throws<ArgumentNullException>("pen", () => graphics.DrawPolygon(null, new PointF[2]));
+ }
+ }
+
+ [ConditionalFact(nameof(PlatformDetection) + "." + nameof(PlatformDetection.IsNotWindowsNanoServer))]
+ public void DrawPolygon_DisposedPen_ThrowsArgumentException()
+ {
+ using (var image = new Bitmap(10, 10))
+ using (Graphics graphics = Graphics.FromImage(image))
+ {
+ var pen = new Pen(Color.Red);
+ pen.Dispose();
+
+ AssertExtensions.Throws<ArgumentException>(null, () => graphics.DrawPolygon(pen, new Point[2]));
+ AssertExtensions.Throws<ArgumentException>(null, () => graphics.DrawPolygon(pen, new PointF[2]));
+ }
+ }
+
+ [ConditionalFact(nameof(PlatformDetection) + "." + nameof(PlatformDetection.IsNotWindowsNanoServer))]
+ public void DrawPolygon_NullPoints_ThrowsArgumentNullException()
+ {
+ using (var image = new Bitmap(10, 10))
+ using (Graphics graphics = Graphics.FromImage(image))
+ using (var pen = new Pen(Color.Red))
+ {
+ AssertExtensions.Throws<ArgumentNullException>("points", () => graphics.DrawPolygon(pen, (Point[])null));
+ AssertExtensions.Throws<ArgumentNullException>("points", () => graphics.DrawPolygon(pen, (PointF[])null));
+ }
+ }
+
+ [ConditionalTheory(nameof(PlatformDetection) + "." + nameof(PlatformDetection.IsNotWindowsNanoServer))]
+ [InlineData(0)]
+ [InlineData(1)]
+ public void DrawPolygon_InvalidPointsLength_ThrowsArgumentException(int length)
+ {
+ using (var image = new Bitmap(10, 10))
+ using (Graphics graphics = Graphics.FromImage(image))
+ using (var pen = new Pen(Color.Red))
+ {
+ AssertExtensions.Throws<ArgumentException>(null, () => graphics.DrawPolygon(pen, new Point[length]));
+ AssertExtensions.Throws<ArgumentException>(null, () => graphics.DrawPolygon(pen, new PointF[length]));
+ }
+ }
+
+ [ConditionalFact(nameof(PlatformDetection) + "." + nameof(PlatformDetection.IsNotWindowsNanoServer))]
+ public void DrawPolygon_Busy_ThrowsInvalidOperationException()
+ {
+ using (var image = new Bitmap(10, 10))
+ using (Graphics graphics = Graphics.FromImage(image))
+ using (var pen = new Pen(Color.Red))
+ {
+ IntPtr hdc = graphics.GetHdc();
+ try
+ {
+ Assert.Throws<InvalidOperationException>(() => graphics.DrawPolygon(pen, new Point[2]));
+ Assert.Throws<InvalidOperationException>(() => graphics.DrawPolygon(pen, new PointF[2]));
+ }
+ finally
+ {
+ graphics.ReleaseHdc();
+ }
+ }
+ }
+
+ [ConditionalFact(nameof(PlatformDetection) + "." + nameof(PlatformDetection.IsNotWindowsNanoServer))]
+ public void DrawPolygon_Disposed_ThrowsArgumentException()
+ {
+ using (var image = new Bitmap(10, 10))
+ using (var pen = new Pen(Color.Red))
+ {
+ Graphics graphics = Graphics.FromImage(image);
+ graphics.Dispose();
+
+ AssertExtensions.Throws<ArgumentException>(null, () => graphics.DrawPolygon(pen, new Point[2]));
+ AssertExtensions.Throws<ArgumentException>(null, () => graphics.DrawPolygon(pen, new PointF[2]));
+ }
+ }
+
+ [ConditionalFact(nameof(PlatformDetection) + "." + nameof(PlatformDetection.IsNotWindowsNanoServer))]
+ public void DrawPath_NullPen_ThrowsArgumentNullException()
+ {
+ using (var image = new Bitmap(10, 10))
+ using (Graphics graphics = Graphics.FromImage(image))
+ using (var graphicsPath = new GraphicsPath())
+ {
+ AssertExtensions.Throws<ArgumentNullException>("pen", () => graphics.DrawPath(null, graphicsPath));
+ }
+ }
+
+ [ConditionalFact(nameof(PlatformDetection) + "." + nameof(PlatformDetection.IsNotWindowsNanoServer))]
+ public void DrawPath_DisposedPen_ThrowsArgumentException()
+ {
+ using (var image = new Bitmap(10, 10))
+ using (Graphics graphics = Graphics.FromImage(image))
+ using (var graphicsPath = new GraphicsPath())
+ {
+ var pen = new Pen(Color.Red);
+ pen.Dispose();
+
+ AssertExtensions.Throws<ArgumentException>(null, () => graphics.DrawPath(pen, graphicsPath));
+ }
+ }
+
+ [ConditionalFact(nameof(PlatformDetection) + "." + nameof(PlatformDetection.IsNotWindowsNanoServer))]
+ public void DrawPath_NullPath_ThrowsArgumentNullException()
+ {
+ using (var image = new Bitmap(10, 10))
+ using (Graphics graphics = Graphics.FromImage(image))
+ using (var pen = new Pen(Color.Red))
+ {
+ AssertExtensions.Throws<ArgumentNullException>("path", () => graphics.DrawPath(pen, null));
+ }
+ }
+
+ [ConditionalFact(nameof(PlatformDetection) + "." + nameof(PlatformDetection.IsNotWindowsNanoServer))]
+ public void DrawPath_DisposedPath_ThrowsArgumentException()
+ {
+ using (var image = new Bitmap(10, 10))
+ using (Graphics graphics = Graphics.FromImage(image))
+ using (var pen = new Pen(Color.Red))
+ {
+ var graphicsPath = new GraphicsPath();
+ graphicsPath.Dispose();
+
+ AssertExtensions.Throws<ArgumentException>(null, () => graphics.DrawPath(pen, graphicsPath));
+ }
+ }
+
+ [ConditionalFact(nameof(PlatformDetection) + "." + nameof(PlatformDetection.IsNotWindowsNanoServer))]
+ public void DrawPath_Busy_ThrowsInvalidOperationException()
+ {
+ using (var image = new Bitmap(10, 10))
+ using (Graphics graphics = Graphics.FromImage(image))
+ using (var pen = new Pen(Color.Red))
+ using (var graphicsPath = new GraphicsPath())
+ {
+ IntPtr hdc = graphics.GetHdc();
+ try
+ {
+ Assert.Throws<InvalidOperationException>(() => graphics.DrawPath(pen, graphicsPath));
+ }
+ finally
+ {
+ graphics.ReleaseHdc();
+ }
+ }
+ }
+
+ [ConditionalFact(nameof(PlatformDetection) + "." + nameof(PlatformDetection.IsNotWindowsNanoServer))]
+ public void DrawPath_Disposed_ThrowsArgumentException()
+ {
+ using (var image = new Bitmap(10, 10))
+ using (var pen = new Pen(Color.Red))
+ using (var graphicsPath = new GraphicsPath())
+ {
+ Graphics graphics = Graphics.FromImage(image);
+ graphics.Dispose();
+
+ AssertExtensions.Throws<ArgumentException>(null, () => graphics.DrawPath(pen, graphicsPath));
+ }
+ }
+
+ [ConditionalFact(nameof(PlatformDetection) + "." + nameof(PlatformDetection.IsNotWindowsNanoServer))]
+ public void DrawCurve_NullPen_ThrowsArgumentNullException()
+ {
+ using (var image = new Bitmap(10, 10))
+ using (Graphics graphics = Graphics.FromImage(image))
+ {
+ AssertExtensions.Throws<ArgumentNullException>("pen", () => graphics.DrawCurve(null, new Point[2]));
+ AssertExtensions.Throws<ArgumentNullException>("pen", () => graphics.DrawCurve(null, new PointF[2]));
+ AssertExtensions.Throws<ArgumentNullException>("pen", () => graphics.DrawCurve(null, new Point[2], 1));
+ AssertExtensions.Throws<ArgumentNullException>("pen", () => graphics.DrawCurve(null, new PointF[2], 1));
+ AssertExtensions.Throws<ArgumentNullException>("pen", () => graphics.DrawCurve(null, new PointF[2], 0, 2));
+ AssertExtensions.Throws<ArgumentNullException>("pen", () => graphics.DrawCurve(null, new Point[2], 0, 2, 1));
+ AssertExtensions.Throws<ArgumentNullException>("pen", () => graphics.DrawCurve(null, new PointF[2], 0, 2, 1));
+ }
+ }
+
+ [ConditionalFact(nameof(PlatformDetection) + "." + nameof(PlatformDetection.IsNotWindowsNanoServer))]
+ public void DrawCurve_DisposedPen_ThrowsArgumentException()
+ {
+ using (var image = new Bitmap(10, 10))
+ using (Graphics graphics = Graphics.FromImage(image))
+ {
+ var pen = new Pen(Color.Red);
+ pen.Dispose();
+
+ AssertExtensions.Throws<ArgumentException>(null, () => graphics.DrawCurve(pen, new Point[2]));
+ AssertExtensions.Throws<ArgumentException>(null, () => graphics.DrawCurve(pen, new PointF[2]));
+ AssertExtensions.Throws<ArgumentException>(null, () => graphics.DrawCurve(pen, new Point[2], 1));
+ AssertExtensions.Throws<ArgumentException>(null, () => graphics.DrawCurve(pen, new PointF[2], 1));
+ AssertExtensions.Throws<ArgumentException>(null, () => graphics.DrawCurve(pen, new PointF[2], 0, 2));
+ AssertExtensions.Throws<ArgumentException>(null, () => graphics.DrawCurve(pen, new Point[2], 0, 2, 1));
+ AssertExtensions.Throws<ArgumentException>(null, () => graphics.DrawCurve(pen, new PointF[2], 0, 2, 1));
+ }
+ }
+
+ [ConditionalFact(nameof(PlatformDetection) + "." + nameof(PlatformDetection.IsNotWindowsNanoServer))]
+ public void DrawCurve_NullPoints_ThrowsArgumentNullException()
+ {
+ using (var image = new Bitmap(10, 10))
+ using (Graphics graphics = Graphics.FromImage(image))
+ using (var pen = new Pen(Color.Red))
+ {
+ AssertExtensions.Throws<ArgumentNullException>("points", () => graphics.DrawCurve(pen, (Point[])null));
+ AssertExtensions.Throws<ArgumentNullException>("points", () => graphics.DrawCurve(pen, (PointF[])null));
+ AssertExtensions.Throws<ArgumentNullException>("points", () => graphics.DrawCurve(pen, (Point[])null, 1));
+ AssertExtensions.Throws<ArgumentNullException>("points", () => graphics.DrawCurve(pen, (PointF[])null, 1));
+ AssertExtensions.Throws<ArgumentNullException>("points", () => graphics.DrawCurve(pen, (PointF[])null, 0, 2));
+ AssertExtensions.Throws<ArgumentNullException>("points", () => graphics.DrawCurve(pen, (Point[])null, 0, 2, 1));
+ AssertExtensions.Throws<ArgumentNullException>("points", () => graphics.DrawCurve(pen, (PointF[])null, 0, 2, 1));
+ }
+ }
+
+ [ConditionalTheory(nameof(PlatformDetection) + "." + nameof(PlatformDetection.IsNotWindowsNanoServer))]
+ [InlineData(0)]
+ [InlineData(1)]
+ public void DrawCurve_InvalidPointsLength_ThrowsArgumentException(int length)
+ {
+ using (var image = new Bitmap(10, 10))
+ using (Graphics graphics = Graphics.FromImage(image))
+ using (var pen = new Pen(Color.Red))
+ {
+ AssertExtensions.Throws<ArgumentException>(null, () => graphics.DrawCurve(pen, new Point[length]));
+ AssertExtensions.Throws<ArgumentException>(null, () => graphics.DrawCurve(pen, new PointF[length]));
+ AssertExtensions.Throws<ArgumentException>(null, () => graphics.DrawCurve(pen, new Point[length], 1));
+ AssertExtensions.Throws<ArgumentException>(null, () => graphics.DrawCurve(pen, new PointF[length], 1));
+ AssertExtensions.Throws<ArgumentException>(null, () => graphics.DrawCurve(pen, new PointF[length], 0, length));
+ AssertExtensions.Throws<ArgumentException>(null, () => graphics.DrawCurve(pen, new Point[length], 0, length, 1));
+ AssertExtensions.Throws<ArgumentException>(null, () => graphics.DrawCurve(pen, new PointF[length], 0, length, 1));
+ }
+ }
+
+ [ConditionalTheory(nameof(PlatformDetection) + "." + nameof(PlatformDetection.IsNotWindowsNanoServer))]
+ [InlineData(4, -1, 4)]
+ [InlineData(4, 0, -1)]
+ [InlineData(4, 4, 0)]
+ [InlineData(4, 0, 5)]
+ [InlineData(4, 3, 2)]
+ public void DrawCurve_InvalidOffsetCount_ThrowsArgumentException(int length, int offset, int numberOfSegments)
+ {
+ using (var image = new Bitmap(10, 10))
+ using (Graphics graphics = Graphics.FromImage(image))
+ using (var pen = new Pen(Color.Red))
+ {
+ AssertExtensions.Throws<ArgumentException>(null, () => graphics.DrawCurve(pen, new PointF[length], offset, numberOfSegments));
+ AssertExtensions.Throws<ArgumentException>(null, () => graphics.DrawCurve(pen, new Point[length], offset, numberOfSegments, 1));
+ AssertExtensions.Throws<ArgumentException>(null, () => graphics.DrawCurve(pen, new PointF[length], offset, numberOfSegments, 1));
+ }
+ }
+
+ [ConditionalFact(nameof(PlatformDetection) + "." + nameof(PlatformDetection.IsNotWindowsNanoServer))]
+ public void DrawCurve_Busy_ThrowsInvalidOperationException()
+ {
+ using (var image = new Bitmap(10, 10))
+ using (Graphics graphics = Graphics.FromImage(image))
+ using (var pen = new Pen(Color.Red))
+ {
+ IntPtr hdc = graphics.GetHdc();
+ try
+ {
+ Assert.Throws<InvalidOperationException>(() => graphics.DrawCurve(pen, new Point[2]));
+ Assert.Throws<InvalidOperationException>(() => graphics.DrawCurve(pen, new PointF[2]));
+ Assert.Throws<InvalidOperationException>(() => graphics.DrawCurve(pen, new Point[2], 1));
+ Assert.Throws<InvalidOperationException>(() => graphics.DrawCurve(pen, new PointF[2], 1));
+ Assert.Throws<InvalidOperationException>(() => graphics.DrawCurve(pen, new PointF[2], 0, 2));
+ Assert.Throws<InvalidOperationException>(() => graphics.DrawCurve(pen, new Point[2], 0, 2, 1));
+ Assert.Throws<InvalidOperationException>(() => graphics.DrawCurve(pen, new PointF[2], 0, 2, 1));
+ }
+ finally
+ {
+ graphics.ReleaseHdc();
+ }
+ }
+ }
+
+ [ConditionalFact(nameof(PlatformDetection) + "." + nameof(PlatformDetection.IsNotWindowsNanoServer))]
+ public void DrawCurve_Disposed_ThrowsArgumentException()
+ {
+ using (var image = new Bitmap(10, 10))
+ using (var pen = new Pen(Color.Red))
+ {
+ Graphics graphics = Graphics.FromImage(image);
+ graphics.Dispose();
+
+ AssertExtensions.Throws<ArgumentException>(null, () => graphics.DrawCurve(pen, new Point[2]));
+ AssertExtensions.Throws<ArgumentException>(null, () => graphics.DrawCurve(pen, new PointF[2]));
+ AssertExtensions.Throws<ArgumentException>(null, () => graphics.DrawCurve(pen, new Point[2], 1));
+ AssertExtensions.Throws<ArgumentException>(null, () => graphics.DrawCurve(pen, new PointF[2], 1));
+ AssertExtensions.Throws<ArgumentException>(null, () => graphics.DrawCurve(pen, new PointF[2], 0, 2));
+ AssertExtensions.Throws<ArgumentException>(null, () => graphics.DrawCurve(pen, new Point[2], 0, 2, 1));
+ AssertExtensions.Throws<ArgumentException>(null, () => graphics.DrawCurve(pen, new PointF[2], 0, 2, 1));
+ }
+ }
+
+ [ConditionalFact(nameof(PlatformDetection) + "." + nameof(PlatformDetection.IsNotWindowsNanoServer))]
+ public void DrawClosedCurve_NullPen_ThrowsArgumentNullException()
+ {
+ using (var image = new Bitmap(10, 10))
+ using (Graphics graphics = Graphics.FromImage(image))
+ {
+ AssertExtensions.Throws<ArgumentNullException>("pen", () => graphics.DrawClosedCurve(null, new Point[3]));
+ AssertExtensions.Throws<ArgumentNullException>("pen", () => graphics.DrawClosedCurve(null, new Point[3], 1, FillMode.Winding));
+ AssertExtensions.Throws<ArgumentNullException>("pen", () => graphics.DrawClosedCurve(null, new PointF[3]));
+ AssertExtensions.Throws<ArgumentNullException>("pen", () => graphics.DrawClosedCurve(null, new PointF[3], 1, FillMode.Winding));
+ }
+ }
+
+ [ConditionalFact(nameof(PlatformDetection) + "." + nameof(PlatformDetection.IsNotWindowsNanoServer))]
+ public void DrawClosedCurve_DisposedPen_ThrowsArgumentException()
+ {
+ using (var image = new Bitmap(10, 10))
+ using (Graphics graphics = Graphics.FromImage(image))
+ {
+ var pen = new Pen(Color.Red);
+ pen.Dispose();
+
+ AssertExtensions.Throws<ArgumentException>(null, () => graphics.DrawClosedCurve(pen, new Point[3]));
+ AssertExtensions.Throws<ArgumentException>(null, () => graphics.DrawClosedCurve(pen, new Point[3], 1, FillMode.Winding));
+ AssertExtensions.Throws<ArgumentException>(null, () => graphics.DrawClosedCurve(pen, new PointF[3]));
+ AssertExtensions.Throws<ArgumentException>(null, () => graphics.DrawClosedCurve(pen, new PointF[3], 1, FillMode.Winding));
+ }
+ }
+
+ [ConditionalFact(nameof(PlatformDetection) + "." + nameof(PlatformDetection.IsNotWindowsNanoServer))]
+ public void DrawClosedCurve_NullPoints_ThrowsArgumentNullException()
+ {
+ using (var image = new Bitmap(10, 10))
+ using (Graphics graphics = Graphics.FromImage(image))
+ using (var pen = new Pen(Color.Red))
+ {
+ AssertExtensions.Throws<ArgumentNullException>("points", () => graphics.DrawClosedCurve(pen, (Point[])null));
+ AssertExtensions.Throws<ArgumentNullException>("points", () => graphics.DrawClosedCurve(pen, (Point[])null, 1, FillMode.Winding));
+ AssertExtensions.Throws<ArgumentNullException>("points", () => graphics.DrawClosedCurve(pen, (PointF[])null));
+ AssertExtensions.Throws<ArgumentNullException>("points", () => graphics.DrawClosedCurve(pen, (PointF[])null, 1, FillMode.Winding));
+ }
+ }
+
+ [ConditionalTheory(nameof(PlatformDetection) + "." + nameof(PlatformDetection.IsNotWindowsNanoServer))]
+ [InlineData(0)]
+ [InlineData(1)]
+ [InlineData(2)]
+ public void DrawClosedCurve_InvalidPointsLength_ThrowsArgumentException(int length)
+ {
+ using (var image = new Bitmap(10, 10))
+ using (Graphics graphics = Graphics.FromImage(image))
+ using (var pen = new Pen(Color.Red))
+ {
+ AssertExtensions.Throws<ArgumentException>(null, () => graphics.DrawClosedCurve(pen, new Point[length]));
+ AssertExtensions.Throws<ArgumentException>(null, () => graphics.DrawClosedCurve(pen, new Point[length], 1, FillMode.Winding));
+ AssertExtensions.Throws<ArgumentException>(null, () => graphics.DrawClosedCurve(pen, new PointF[length]));
+ AssertExtensions.Throws<ArgumentException>(null, () => graphics.DrawClosedCurve(pen, new PointF[length], 1, FillMode.Winding));
+ }
+ }
+
+ [ConditionalFact(nameof(PlatformDetection) + "." + nameof(PlatformDetection.IsNotWindowsNanoServer))]
+ public void DrawClosedCurve_Busy_ThrowsInvalidOperationException()
+ {
+ using (var image = new Bitmap(10, 10))
+ using (Graphics graphics = Graphics.FromImage(image))
+ using (var pen = new Pen(Color.Red))
+ {
+ IntPtr hdc = graphics.GetHdc();
+ try
+ {
+ Assert.Throws<InvalidOperationException>(() => graphics.DrawClosedCurve(pen, new Point[3]));
+ Assert.Throws<InvalidOperationException>(() => graphics.DrawClosedCurve(pen, new Point[3], 1, FillMode.Winding));
+ Assert.Throws<InvalidOperationException>(() => graphics.DrawClosedCurve(pen, new PointF[3]));
+ Assert.Throws<InvalidOperationException>(() => graphics.DrawClosedCurve(pen, new PointF[3], 1, FillMode.Winding));
+ }
+ finally
+ {
+ graphics.ReleaseHdc();
+ }
+ }
+ }
+
+ [ConditionalFact(nameof(PlatformDetection) + "." + nameof(PlatformDetection.IsNotWindowsNanoServer))]
+ public void DrawClosedCurve_Disposed_ThrowsArgumentException()
+ {
+ using (var image = new Bitmap(10, 10))
+ using (var pen = new Pen(Color.Red))
+ {
+ Graphics graphics = Graphics.FromImage(image);
+ graphics.Dispose();
+
+ AssertExtensions.Throws<ArgumentException>(null, () => graphics.DrawClosedCurve(pen, new Point[3]));
+ AssertExtensions.Throws<ArgumentException>(null, () => graphics.DrawClosedCurve(pen, new Point[3], 1, FillMode.Alternate));
+ AssertExtensions.Throws<ArgumentException>(null, () => graphics.DrawClosedCurve(pen, new PointF[3]));
+ AssertExtensions.Throws<ArgumentException>(null, () => graphics.DrawClosedCurve(pen, new PointF[3], 1, FillMode.Alternate));
+ }
+ }
+
+ [ConditionalFact(nameof(PlatformDetection) + "." + nameof(PlatformDetection.IsNotWindowsNanoServer))]
+ public void Clear_Color_Success()
+ {
+ Color color = Color.FromArgb(Color.Plum.ToArgb());
+
+ using (var image = new Bitmap(2, 2))
+ using (Graphics graphics = Graphics.FromImage(image))
+ using (var brush = new SolidBrush(color))
+ {
+ graphics.FillRectangle(brush, new Rectangle(0, 0, 2, 2));
+
+ graphics.Clear(color);
+ Helpers.VerifyBitmap(image, new Color[][]
+ {
+ new Color[] { color, color },
+ new Color[] { color, color }
+ });
+ }
+ }
+
+ [ConditionalFact(nameof(PlatformDetection) + "." + nameof(PlatformDetection.IsNotWindowsNanoServer))]
+ public void Clear_Busy_ThrowsInvalidOperationException()
+ {
+ using (var image = new Bitmap(10, 10))
+ using (Graphics graphics = Graphics.FromImage(image))
+ using (var pen = new Pen(Color.Red))
+ {
+ IntPtr hdc = graphics.GetHdc();
+ try
+ {
+ Assert.Throws<InvalidOperationException>(() => graphics.Clear(Color.Red));
+ }
+ finally
+ {
+ graphics.ReleaseHdc();
+ }
+ }
+ }
+
+ [ConditionalFact(nameof(PlatformDetection) + "." + nameof(PlatformDetection.IsNotWindowsNanoServer))]
+ public void Clear_Disposed_ThrowsArgumentException()
+ {
+ using (var image = new Bitmap(10, 10))
+ using (var pen = new Pen(Color.Red))
+ {
+ Graphics graphics = Graphics.FromImage(image);
+ graphics.Dispose();
+
+ AssertExtensions.Throws<ArgumentException>(null, () => graphics.Clear(Color.Red));
+ }
+ }
+
private static void VerifyGraphics(Graphics graphics, RectangleF expectedVisibleClipBounds)
{
Assert.NotNull(graphics.Clip);
diff --git a/src/System.Drawing.Common/tests/IconTests.cs b/src/System.Drawing.Common/tests/IconTests.cs
index 269cde9aca..6c72becdd0 100644
--- a/src/System.Drawing.Common/tests/IconTests.cs
+++ b/src/System.Drawing.Common/tests/IconTests.cs
@@ -104,7 +104,7 @@ namespace System.Drawing.Tests
[ConditionalFact(nameof(PlatformDetection) + "." + nameof(PlatformDetection.IsNotWindowsNanoServer))]
public void Ctor_Stream()
{
- using (var stream = new FileStream(Helpers.GetTestBitmapPath("48x48_multiple_entries_4bit.ico"), FileMode.Open))
+ using (var stream = File.OpenRead(Helpers.GetTestBitmapPath("48x48_multiple_entries_4bit.ico")))
{
var icon = new Icon(stream);
Assert.Equal(32, icon.Width);
@@ -117,7 +117,7 @@ namespace System.Drawing.Tests
[MemberData(nameof(Size_TestData))]
public void Ctor_Stream_Width_Height(string fileName, Size size, Size expectedSize)
{
- using (var stream = new FileStream(Helpers.GetTestBitmapPath(fileName), FileMode.Open))
+ using (var stream = File.OpenRead(Helpers.GetTestBitmapPath(fileName)))
using (var icon = new Icon(stream, size.Width, size.Height))
{
Assert.Equal(expectedSize.Width, icon.Width);
@@ -130,7 +130,7 @@ namespace System.Drawing.Tests
[MemberData(nameof(Size_TestData))]
public void Ctor_Stream_Size(string fileName, Size size, Size expectedSize)
{
- using (var stream = new FileStream(Helpers.GetTestBitmapPath(fileName), FileMode.Open))
+ using (var stream = File.OpenRead(Helpers.GetTestBitmapPath(fileName)))
using (var icon = new Icon(stream, size))
{
Assert.Equal(expectedSize.Width, icon.Width);
diff --git a/src/System.Drawing.Common/tests/Imaging/EncoderParameterTests.cs b/src/System.Drawing.Common/tests/Imaging/EncoderParameterTests.cs
new file mode 100644
index 0000000000..e8cf6422d5
--- /dev/null
+++ b/src/System.Drawing.Common/tests/Imaging/EncoderParameterTests.cs
@@ -0,0 +1,326 @@
+// Licensed to the .NET Foundation under one or more agreements.
+// The .NET Foundation licenses this file to you under the MIT license.
+// See the LICENSE file in the project root for more information.
+
+using System.Collections.Generic;
+using Xunit;
+
+namespace System.Drawing.Imaging.Tests
+{
+ public class EncoderParameterTests
+ {
+ private static readonly Encoder s_anyEncoder = Encoder.ChrominanceTable;
+
+ private void CheckEncoderParameter(EncoderParameter encoderParameter, Encoder expectedEncoder, EncoderParameterValueType expectedType, int expectedNumberOfValues)
+ {
+ Assert.Equal(expectedEncoder.Guid, encoderParameter.Encoder.Guid);
+ Assert.Equal(expectedType, encoderParameter.ValueType);
+ Assert.Equal(expectedType, encoderParameter.Type);
+ Assert.Equal(expectedNumberOfValues, encoderParameter.NumberOfValues);
+ }
+
+ public static IEnumerable<object[]> Ctor_Encoder_Byte_TestData
+ {
+ get
+ {
+ yield return new object[] { Encoder.ChrominanceTable, byte.MinValue };
+ yield return new object[] { Encoder.ColorDepth, byte.MinValue };
+ yield return new object[] { Encoder.Compression, byte.MinValue };
+ yield return new object[] { Encoder.LuminanceTable, byte.MinValue };
+ yield return new object[] { Encoder.Quality, byte.MinValue };
+ yield return new object[] { Encoder.RenderMethod, byte.MinValue };
+ yield return new object[] { Encoder.SaveFlag, byte.MinValue };
+ yield return new object[] { Encoder.ScanMethod, byte.MinValue };
+ yield return new object[] { Encoder.Transformation, byte.MinValue };
+ yield return new object[] { Encoder.Version, byte.MinValue };
+ yield return new object[] { new Encoder(Guid.NewGuid()), byte.MinValue };
+ yield return new object[] { new Encoder(Guid.NewGuid()), 1 };
+ yield return new object[] { new Encoder(Guid.NewGuid()), byte.MaxValue };
+ }
+ }
+
+ [ConditionalTheory(nameof(PlatformDetection) + "." + nameof(PlatformDetection.IsNotWindowsNanoServer))]
+ [MemberData(nameof(Ctor_Encoder_Byte_TestData))]
+ public void Ctor_Encoder_Byte(Encoder encoder, byte value)
+ {
+ EncoderParameter ep = new EncoderParameter(encoder, value);
+ CheckEncoderParameter(ep, encoder, EncoderParameterValueType.ValueTypeByte, 1);
+ }
+
+ [ConditionalTheory(nameof(PlatformDetection) + "." + nameof(PlatformDetection.IsNotWindowsNanoServer))]
+ [InlineData(false, EncoderParameterValueType.ValueTypeByte)]
+ [InlineData(true, EncoderParameterValueType.ValueTypeUndefined)]
+ public void Ctor_Encoder_ByteValue_Bool(bool undefined, EncoderParameterValueType expected)
+ {
+ EncoderParameter ep = new EncoderParameter(s_anyEncoder, 0, undefined);
+ CheckEncoderParameter(ep, s_anyEncoder, expected, 1);
+ }
+
+ [ConditionalTheory(nameof(PlatformDetection) + "." + nameof(PlatformDetection.IsNotWindowsNanoServer))]
+ [InlineData(0)]
+ [InlineData(short.MinValue)]
+ [InlineData(short.MaxValue)]
+ public void Ctor_Encoder_Short(short value)
+ {
+ EncoderParameter ep = new EncoderParameter(s_anyEncoder, value);
+ CheckEncoderParameter(ep, s_anyEncoder, EncoderParameterValueType.ValueTypeShort, 1);
+ }
+
+ [ConditionalTheory(nameof(PlatformDetection) + "." + nameof(PlatformDetection.IsNotWindowsNanoServer))]
+ [InlineData(0)]
+ [InlineData(long.MinValue)]
+ [InlineData(long.MaxValue)]
+ public void Ctor_Encoder_Long(long value)
+ {
+ EncoderParameter ep = new EncoderParameter(s_anyEncoder, value);
+ CheckEncoderParameter(ep, s_anyEncoder, EncoderParameterValueType.ValueTypeLong, 1);
+ }
+
+ [ConditionalTheory(nameof(PlatformDetection) + "." + nameof(PlatformDetection.IsNotWindowsNanoServer))]
+ [InlineData(int.MaxValue, int.MaxValue)]
+ [InlineData(10, 5)]
+ [InlineData(-10, -5)]
+ public void Ctor_Encoder_Numerator_Denominator(int numerator, int denominator)
+ {
+ EncoderParameter ep = new EncoderParameter(s_anyEncoder, numerator, denominator);
+ CheckEncoderParameter(ep, s_anyEncoder, EncoderParameterValueType.ValueTypeRational, 1);
+ }
+
+ [ConditionalTheory(nameof(PlatformDetection) + "." + nameof(PlatformDetection.IsNotWindowsNanoServer))]
+ [InlineData(0, 0, 0, 0)]
+ [InlineData(1, 2, 3, 4)]
+ public void Ctor_Encoder_Numerator1_Denominator1_Numerator2_Denominator2(int numerator1, int denominator1, int numerator2, int denominator2)
+ {
+ EncoderParameter ep = new EncoderParameter(s_anyEncoder, numerator1, denominator1, numerator2, denominator2);
+ CheckEncoderParameter(ep, s_anyEncoder, EncoderParameterValueType.ValueTypeRationalRange, 1);
+ }
+
+ [ConditionalTheory(nameof(PlatformDetection) + "." + nameof(PlatformDetection.IsNotWindowsNanoServer))]
+ [InlineData(0, 0)]
+ [InlineData(1, 2)]
+ public void Ctor_Encoder_RangeBegin_RangeEnd(long rangeBegin, long rangeEnd)
+ {
+ EncoderParameter ep = new EncoderParameter(s_anyEncoder, rangeBegin, rangeEnd);
+ CheckEncoderParameter(ep, s_anyEncoder, EncoderParameterValueType.ValueTypeLongRange, 1);
+ }
+
+ [ConditionalTheory(nameof(PlatformDetection) + "." + nameof(PlatformDetection.IsNotWindowsNanoServer))]
+ [InlineData("someStringValue")]
+ [InlineData("")]
+ public void Ctor_Encoder_String(string value)
+ {
+ EncoderParameter ep = new EncoderParameter(s_anyEncoder, value);
+ CheckEncoderParameter(ep, s_anyEncoder, EncoderParameterValueType.ValueTypeAscii, value.Length);
+ }
+
+ [ConditionalTheory(nameof(PlatformDetection) + "." + nameof(PlatformDetection.IsNotWindowsNanoServer))]
+ [InlineData(new byte[] { })]
+ [InlineData(new byte[] { 0, 1, 2, 3 })]
+ public void Ctor_Encoder_ByteArray(byte[] value)
+ {
+ EncoderParameter ep = new EncoderParameter(s_anyEncoder, value);
+ CheckEncoderParameter(ep, s_anyEncoder, EncoderParameterValueType.ValueTypeByte, value.Length);
+ }
+
+ [ConditionalTheory(nameof(PlatformDetection) + "." + nameof(PlatformDetection.IsNotWindowsNanoServer))]
+ [InlineData(new byte[] { 1, 2 }, false, EncoderParameterValueType.ValueTypeByte)]
+ [InlineData(new byte[] { 1, 2 }, true, EncoderParameterValueType.ValueTypeUndefined)]
+ public void Ctor_Encoder_ByteArray_Bool(byte[] value, bool undefined, EncoderParameterValueType expected)
+ {
+ EncoderParameter ep = new EncoderParameter(s_anyEncoder, value, undefined);
+ CheckEncoderParameter(ep, s_anyEncoder, expected, value.Length);
+ }
+
+ [ConditionalTheory(nameof(PlatformDetection) + "." + nameof(PlatformDetection.IsNotWindowsNanoServer))]
+ [InlineData(new short[] { })]
+ [InlineData(new short[] { 0, 1, 2, 3 })]
+ public void Ctor_Encoder_ShortArray(short[] value)
+ {
+ EncoderParameter ep = new EncoderParameter(s_anyEncoder, value);
+ CheckEncoderParameter(ep, s_anyEncoder, EncoderParameterValueType.ValueTypeShort, value.Length);
+ }
+
+ [ConditionalTheory(nameof(PlatformDetection) + "." + nameof(PlatformDetection.IsNotWindowsNanoServer))]
+ [InlineData(new long[] { })]
+ [InlineData(new long[] { 0, 1, 2, 3 })]
+ public void Ctor_Encoder_LongArray(long[] value)
+ {
+ EncoderParameter ep = new EncoderParameter(s_anyEncoder, value);
+ CheckEncoderParameter(ep, s_anyEncoder, EncoderParameterValueType.ValueTypeLong, value.Length);
+ }
+
+ [ConditionalTheory(nameof(PlatformDetection) + "." + nameof(PlatformDetection.IsNotWindowsNanoServer))]
+ [InlineData(new int[] { 0, 1, 2, 3 }, new int[] { 5, 6, 7, 8 })]
+ public void Ctor_Encoder_NumeratorArray_DenominatorArray(int[] numerator, int[] denominator)
+ {
+ EncoderParameter ep = new EncoderParameter(s_anyEncoder, numerator, denominator);
+ CheckEncoderParameter(ep, s_anyEncoder, EncoderParameterValueType.ValueTypeRational, numerator.Length);
+ }
+
+ [ConditionalTheory(nameof(PlatformDetection) + "." + nameof(PlatformDetection.IsNotWindowsNanoServer))]
+ [InlineData(new long[] { 0, 1, 2, 3 }, new long[] { 5, 6, 7, 8 })]
+ public void Ctor_Encoder_RangeBeginArray_RangeEndArray(long[] rangeBegin, long[] rangeEnd)
+ {
+ EncoderParameter ep = new EncoderParameter(s_anyEncoder, rangeBegin, rangeEnd);
+ CheckEncoderParameter(ep, s_anyEncoder, EncoderParameterValueType.ValueTypeLongRange, rangeBegin.Length);
+ }
+
+ [ConditionalTheory(nameof(PlatformDetection) + "." + nameof(PlatformDetection.IsNotWindowsNanoServer))]
+ [InlineData(new int[] { 0, 1, 2, 3 }, new int[] { 4, 5, 6, 7 }, new int[] { 8, 9, 10, 11 }, new int[] { 12, 13, 14, 15 })]
+ public void Ctor_Encoder_Numerator1Array_Denominator1Array_Numerator2Array_Denominator2Array(int[] numerator1, int[] denominator1, int[] numerator2, int[] denominator2)
+ {
+ EncoderParameter ep = new EncoderParameter(s_anyEncoder, numerator1, denominator1, numerator2, denominator2);
+ CheckEncoderParameter(ep, s_anyEncoder, EncoderParameterValueType.ValueTypeRationalRange, numerator1.Length);
+ }
+
+ public static IEnumerable<object[]> Encoder_NumberOfValues_TestData
+ {
+ get
+ {
+ yield return new object[] { 0, EncoderParameterValueType.ValueTypeAscii, IntPtr.Zero };
+ yield return new object[] { 0, EncoderParameterValueType.ValueTypeByte, IntPtr.Zero };
+ yield return new object[] { 0, EncoderParameterValueType.ValueTypeLong, IntPtr.Zero };
+ yield return new object[] { 0, EncoderParameterValueType.ValueTypeLongRange, IntPtr.Zero };
+ yield return new object[] { 0, EncoderParameterValueType.ValueTypeRational, IntPtr.Zero };
+ yield return new object[] { 0, EncoderParameterValueType.ValueTypeRationalRange, IntPtr.Zero };
+ yield return new object[] { 0, EncoderParameterValueType.ValueTypeShort, IntPtr.Zero };
+ yield return new object[] { 0, EncoderParameterValueType.ValueTypeUndefined, IntPtr.Zero };
+ yield return new object[] { 0, EncoderParameterValueType.ValueTypeUndefined, IntPtr.Zero };
+ }
+ }
+
+ [ConditionalTheory(nameof(PlatformDetection) + "." + nameof(PlatformDetection.IsNotWindowsNanoServer))]
+ [MemberData(nameof(Encoder_NumberOfValues_TestData))]
+ public void Ctor_Encoder_NumberOfValues_Type_Value(int numberOfValues, EncoderParameterValueType type, IntPtr value)
+ {
+ EncoderParameter ep = new EncoderParameter(s_anyEncoder, numberOfValues, type, value);
+ CheckEncoderParameter(ep, s_anyEncoder, type, numberOfValues);
+ }
+
+ [ConditionalFact(nameof(PlatformDetection) + "." + nameof(PlatformDetection.IsNotWindowsNanoServer))]
+ public void Encoder_ReturnsExpecetd()
+ {
+ Encoder encoder = new Encoder(Guid.NewGuid());
+ EncoderParameter ep = new EncoderParameter(s_anyEncoder, 0);
+ ep.Encoder = encoder;
+
+ Assert.Equal(encoder.Guid, ep.Encoder.Guid);
+ }
+
+ [ConditionalFact(nameof(PlatformDetection) + "." + nameof(PlatformDetection.IsNotWindowsNanoServer))]
+ public void Ctor_Encoder_NumberOfValues_NotExistingType_ThrowsInvalidOperationException()
+ {
+ Assert.Throws<InvalidOperationException>(() => new EncoderParameter(s_anyEncoder, 1, (EncoderParameterValueType)999, IntPtr.Zero));
+ }
+
+ [ConditionalTheory(nameof(PlatformDetection) + "." + nameof(PlatformDetection.IsNotWindowsNanoServer))]
+ [InlineData(new int[] { 1, 2 }, new int[] { 1 }, new int[] { 1 }, new int[] { 1 }, typeof(ArgumentException))]
+ [InlineData(new int[] { 1 }, new int[] { 1, 2 }, new int[] { 1 }, new int[] { 1 }, typeof(ArgumentException))]
+ [InlineData(null, new int[] { 1 }, new int[] { 1 }, new int[] { 1 }, typeof(NullReferenceException))]
+ [InlineData(new int[] { 1 }, null, new int[] { 1 }, new int[] { 1 }, typeof(NullReferenceException))]
+ [InlineData(new int[] { 1 }, new int[] { 1 }, null, new int[] { 1 }, typeof(NullReferenceException))]
+ [InlineData(new int[] { 1 }, new int[] { 1 }, new int[] { 1 }, null, typeof(NullReferenceException))]
+ public void Ctor_Encoder_Numerator1Array_Denominator1Array_Numerator2Array_Denominator2Array_InvalidParameters_ThrowsExpected(int[] numerator1, int[] denominator1, int[] numerator2, int[] denominator2, Type expected)
+ {
+ Assert.Throws(expected, () => new EncoderParameter(s_anyEncoder, numerator1, denominator1, numerator2, denominator2));
+ }
+
+ [ConditionalFact(nameof(PlatformDetection) + "." + nameof(PlatformDetection.IsNotWindowsNanoServer))]
+ public void Encoder_Null_ThrowsNullReferenceException()
+ {
+ EncoderParameter ep = new EncoderParameter(s_anyEncoder, 0);
+ Assert.Throws<NullReferenceException>(() => ep.Encoder = null);
+ }
+
+ [ConditionalTheory(nameof(PlatformDetection) + "." + nameof(PlatformDetection.IsNotWindowsNanoServer))]
+ [InlineData(new int[] { 0 }, new int[] { 0, 1 }, typeof(ArgumentException))]
+ [InlineData(new int[] { 0, 1 }, new int[] { 0 }, typeof(ArgumentException))]
+ [InlineData(new int[] { 0, 1 }, null, typeof(NullReferenceException))]
+ [InlineData(null, new int[] { 0, 1 }, typeof(NullReferenceException))]
+ public void Ctor_Numerator_Denominator_IvalidValues_ThrowsExpected(int[] numerator, int[] denominator, Type expected)
+ {
+ Assert.Throws(expected, () => new EncoderParameter(s_anyEncoder, numerator, denominator));
+ }
+
+ [ConditionalTheory(nameof(PlatformDetection) + "." + nameof(PlatformDetection.IsNotWindowsNanoServer))]
+ [InlineData(new long[] { 0 }, new long[] { 0, 1 }, typeof(ArgumentException))]
+ [InlineData(new long[] { 0, 1 }, new long[] { 0 }, typeof(ArgumentException))]
+ [InlineData(new long[] { 0, 1 }, null, typeof(NullReferenceException))]
+ [InlineData(null, new long[] { 0, 1 }, typeof(NullReferenceException))]
+ public void Ctor_RangeBegin_RangeEnd_InvalidValues_ThrowsExpected(long[] rangeBegin, long[] rangeEnd, Type expected)
+ {
+ Assert.Throws(expected, () => new EncoderParameter(s_anyEncoder, rangeBegin, rangeEnd));
+ }
+
+ [ConditionalFact(nameof(PlatformDetection) + "." + nameof(PlatformDetection.IsNotWindowsNanoServer))]
+ public void Ctor_Encoder_NullString_ThrowsNullReferenceException()
+ {
+ Assert.Throws<NullReferenceException>(() => new EncoderParameter(s_anyEncoder, (string)null));
+ }
+
+ [ConditionalFact(nameof(PlatformDetection) + "." + nameof(PlatformDetection.IsNotWindowsNanoServer))]
+ public void Ctor_Encoder_ByteArray_ThrowsNullReferenceException()
+ {
+ Assert.Throws<NullReferenceException>(() => new EncoderParameter(s_anyEncoder, (byte[])null));
+ }
+
+ public static IEnumerable<object[]> EncoderParameterCtor_NullEncoder_TestData
+ {
+ get
+ {
+ yield return new object[] { new Action(() => new EncoderParameter(null, (byte)0)) };
+ yield return new object[] { new Action(() => new EncoderParameter(null, (byte)0, false)) };
+ yield return new object[] { new Action(() => new EncoderParameter(null, (short)0)) };
+ yield return new object[] { new Action(() => new EncoderParameter(null, numerator: 0, denominator: 0)) };
+ yield return new object[] { new Action(() => new EncoderParameter(null, rangebegin: 0, rangeend: 0)) };
+ yield return new object[] { new Action(() => new EncoderParameter(null, 0, 0, 0, 0)) };
+ yield return new object[] { new Action(() => new EncoderParameter(null, "anyString")) };
+ yield return new object[] { new Action(() => new EncoderParameter(null, new byte[] { })) };
+ yield return new object[] { new Action(() => new EncoderParameter(null, new byte[] { }, false)) };
+ yield return new object[] { new Action(() => new EncoderParameter(null, new short[] { })) };
+ yield return new object[] { new Action(() => new EncoderParameter(null, new long[] { })) };
+ yield return new object[] { new Action(() => new EncoderParameter(null, new int[] { }, new int[] { })) };
+ yield return new object[] { new Action(() => new EncoderParameter(null, new long[] { }, new long[] { })) };
+ }
+ }
+
+ [ConditionalFact(nameof(PlatformDetection) + "." + nameof(PlatformDetection.IsNotWindowsNanoServer))]
+ public void Ctor_NullEncoder_ThrowsNullReferenceException()
+ {
+ Assert.Throws<NullReferenceException>(() => new EncoderParameter(null, (byte)0));
+ Assert.Throws<NullReferenceException>(() => new EncoderParameter(null, (byte)0, false));
+ Assert.Throws<NullReferenceException>(() => new EncoderParameter(null, (short)0));
+ Assert.Throws<NullReferenceException>(() => new EncoderParameter(null, numerator: 0, denominator: 0));
+ Assert.Throws<NullReferenceException>(() => new EncoderParameter(null, rangebegin: 0, rangeend: 0));
+ Assert.Throws<NullReferenceException>(() => new EncoderParameter(null, 0, 0, 0, 0));
+ Assert.Throws<NullReferenceException>(() => new EncoderParameter(null, "anyString"));
+ Assert.Throws<NullReferenceException>(() => new EncoderParameter(null, new byte[] { }));
+ Assert.Throws<NullReferenceException>(() => new EncoderParameter(null, new byte[] { }, false));
+ Assert.Throws<NullReferenceException>(() => new EncoderParameter(null, new short[] { }));
+ Assert.Throws<NullReferenceException>(() => new EncoderParameter(null, new long[] { }));
+ Assert.Throws<NullReferenceException>(() => new EncoderParameter(null, new int[] { }, new int[] { }));
+ Assert.Throws<NullReferenceException>(() => new EncoderParameter(null, new long[] { }, new long[] { }));
+ }
+
+ [ConditionalTheory(nameof(PlatformDetection) + "." + nameof(PlatformDetection.IsNotWindowsNanoServer))]
+ [InlineData(EncoderParameterValueType.ValueTypeShort, (int.MaxValue / 2) + 1, typeof(OverflowException))]
+ [InlineData(EncoderParameterValueType.ValueTypeLong, (int.MaxValue / 4) + 1, typeof(OverflowException))]
+ [InlineData(EncoderParameterValueType.ValueTypeRational, (int.MaxValue / 8) + 1, typeof(OverflowException))]
+ [InlineData(EncoderParameterValueType.ValueTypeLongRange, (int.MaxValue / 8) + 1, typeof(OverflowException))]
+ [InlineData(EncoderParameterValueType.ValueTypeRationalRange, (int.MaxValue / 16) + 1, typeof(OverflowException))]
+ public void Ctor_Encoder_TooBigNumberOfValues_Type_Value_AccessViolationException(EncoderParameterValueType type, int numberOfValues, Type expected)
+ {
+ Assert.Throws(expected, () => new EncoderParameter(s_anyEncoder, numberOfValues, type, IntPtr.Zero));
+ }
+
+ [ConditionalTheory(nameof(PlatformDetection) + "." + nameof(PlatformDetection.IsNotWindowsNanoServer))]
+ [InlineData(-1)]
+ [InlineData(int.MinValue)]
+ public void Ctor_Encoder_NegativeNumberOfValues_Type_Value_OutOfMemoryException(int numberOfValues)
+ {
+ IntPtr anyValue = IntPtr.Zero;
+ EncoderParameterValueType anyTypw = EncoderParameterValueType.ValueTypeAscii;
+ Assert.Throws<OutOfMemoryException>(() => new EncoderParameter(s_anyEncoder, numberOfValues, anyTypw, anyValue));
+ }
+ }
+}
diff --git a/src/System.Drawing.Common/tests/Imaging/EncoderParametersTests.cs b/src/System.Drawing.Common/tests/Imaging/EncoderParametersTests.cs
new file mode 100644
index 0000000000..c9c8d7d747
--- /dev/null
+++ b/src/System.Drawing.Common/tests/Imaging/EncoderParametersTests.cs
@@ -0,0 +1,58 @@
+// Licensed to the .NET Foundation under one or more agreements.
+// The .NET Foundation licenses this file to you under the MIT license.
+// See the LICENSE file in the project root for more information.
+
+using System.Collections.Generic;
+using Xunit;
+
+namespace System.Drawing.Imaging.Tests
+{
+ public class EncoderParametersTests
+ {
+ [ConditionalFact(nameof(PlatformDetection) + "." + nameof(PlatformDetection.IsNotWindowsNanoServer))]
+ public void Ctor_Default()
+ {
+ EncoderParameters ep = new EncoderParameters();
+ Assert.NotNull(ep.Param);
+ Assert.Equal(new EncoderParameter[1], ep.Param);
+ }
+
+ [ConditionalTheory(nameof(PlatformDetection) + "." + nameof(PlatformDetection.IsNotWindowsNanoServer))]
+ [InlineData(1)]
+ public void Ctor_Count_Default(int count)
+ {
+ EncoderParameters ep = new EncoderParameters(count);
+ Assert.NotNull(ep.Param);
+ Assert.Equal(new EncoderParameter[count], ep.Param);
+ }
+
+ public static IEnumerable<object[]> Param_TestData
+ {
+ get
+ {
+ yield return new object[] { new EncoderParameter[1] };
+ yield return new object[] { new EncoderParameter[1] { new EncoderParameter(Encoder.ChrominanceTable, 0) } };
+ yield return new object[] { new EncoderParameter[1] { null } };
+ }
+ }
+
+ [ConditionalTheory(nameof(PlatformDetection) + "." + nameof(PlatformDetection.IsNotWindowsNanoServer))]
+ [MemberData(nameof(Param_TestData))]
+ public void Param_Success(EncoderParameter[] param)
+ {
+ EncoderParameters ep = new EncoderParameters();
+ ep.Param = param;
+ Assert.Equal(param, ep.Param);
+ }
+
+ [ConditionalTheory(nameof(PlatformDetection) + "." + nameof(PlatformDetection.IsNotWindowsNanoServer))]
+ [MemberData(nameof(Param_TestData))]
+ public void Dispose_Success(EncoderParameter[] param)
+ {
+ EncoderParameters ep = new EncoderParameters();
+ ep.Param = param;
+ ep.Dispose();
+ Assert.Null(ep.Param);
+ }
+ }
+}
diff --git a/src/System.Drawing.Common/tests/PenTests.cs b/src/System.Drawing.Common/tests/PenTests.cs
index 64cd9cb6e7..7210e14d87 100644
--- a/src/System.Drawing.Common/tests/PenTests.cs
+++ b/src/System.Drawing.Common/tests/PenTests.cs
@@ -552,6 +552,7 @@ namespace System.Drawing.Tests
[ConditionalTheory(nameof(PlatformDetection) + "." + nameof(PlatformDetection.IsNotWindowsNanoServer))]
[InlineData(DashCap.Flat - 1)]
+ [InlineData(DashCap.Round - 1)]
[InlineData(DashCap.Triangle + 1)]
public void DashCap_SetInvalid_ThrowsInvalidEnumArgumentException(DashCap dashCap)
{
diff --git a/src/System.Drawing.Common/tests/PensTests.cs b/src/System.Drawing.Common/tests/PensTests.cs
index 9d80e897cf..74abc41b03 100644
--- a/src/System.Drawing.Common/tests/PensTests.cs
+++ b/src/System.Drawing.Common/tests/PensTests.cs
@@ -155,18 +155,18 @@ namespace System.Drawing.Tests
yield return Pen(() => Pens.YellowGreen, Color.YellowGreen);
}
- public static object[] Pen(Func<Pen> penThunk, Color expectedColor) => new object[] { penThunk, expectedColor };
+ public static object[] Pen(Func<Pen> getPen, Color expectedColor) => new object[] { getPen, expectedColor };
[ConditionalTheory(nameof(PlatformDetection) + "." + nameof(PlatformDetection.IsNotWindowsNanoServer))]
[MemberData(nameof(Pens_TestData))]
- public void Pens_Get_ReturnsExpected(Func<Pen> penThunk, Color expectedColor)
+ public void Pens_Get_ReturnsExpected(Func<Pen> getPen, Color expectedColor)
{
- Pen pen = penThunk();
+ Pen pen = getPen();
Assert.Equal(expectedColor, pen.Color);
Assert.Equal(PenType.SolidColor, pen.PenType);
AssertExtensions.Throws<ArgumentException>(null, () => pen.Color = Color.AliceBlue);
- Assert.Same(pen, penThunk());
+ Assert.Same(pen, getPen());
}
}
}
diff --git a/src/System.Drawing.Common/tests/System.Drawing.Common.Tests.csproj b/src/System.Drawing.Common/tests/System.Drawing.Common.Tests.csproj
index 93e080586a..95f3b45fc5 100644
--- a/src/System.Drawing.Common/tests/System.Drawing.Common.Tests.csproj
+++ b/src/System.Drawing.Common/tests/System.Drawing.Common.Tests.csproj
@@ -14,6 +14,11 @@
<Compile Include="BrushesTests.cs" />
<Compile Include="CharacterRangeTests.cs" />
<Compile Include="ColorTranslatorTests.cs" />
+ <Compile Include="Drawing2D\AdjustableArrowCapTests.cs" />
+ <Compile Include="Drawing2D\CustomLineCapTests.cs" />
+ <Compile Include="Drawing2D\GraphicsPathIteratorTests.cs" />
+ <Compile Include="Drawing2D\GraphicsPathTests.cs" />
+ <Compile Include="Drawing2D\PathGradientBrushTests.cs" />
<Compile Include="FontTests.cs" />
<Compile Include="FontFamilyTests.cs" />
<Compile Include="GraphicsTests.cs" />
@@ -25,6 +30,8 @@
<Compile Include="Imaging\BitmapDataTests.cs" />
<Compile Include="Imaging\ColorMapTests.cs" />
<Compile Include="Imaging\ColorMatrixTests.cs" />
+ <Compile Include="Imaging\EncoderParametersTests.cs" />
+ <Compile Include="Imaging\EncoderParameterTests.cs" />
<Compile Include="Imaging\EncoderTests.cs" />
<Compile Include="Imaging\FrameDimensionTests.cs" />
<Compile Include="Imaging\ImageCodecInfoTests.cs" />
@@ -35,6 +42,7 @@
<Compile Include="SolidBrushTests.cs" />
<Compile Include="StringFormatTests.cs" />
<Compile Include="SystemBrushesTests.cs" />
+ <Compile Include="SystemFontsTests.cs" />
<Compile Include="SystemIconsTests.cs" />
<Compile Include="SystemPensTest.cs" />
<Compile Include="TextureBrushTests.cs" />
@@ -50,9 +58,6 @@
<Compile Include="$(CommonTestPath)\System\Diagnostics\DebuggerAttributes.cs">
<Link>Common\System\Diagnostics\DebuggerAttributes.cs</Link>
</Compile>
- <Compile Include="$(CommonTestPath)\System\AssertExtensions.cs">
- <Link>Common\System\AssertExtensions.cs</Link>
- </Compile>
<Compile Include="$(CommonTestPath)\System\PlatformDetection.cs">
<Link>Common\System\PlatformDetection.cs</Link>
</Compile>
diff --git a/src/System.Drawing.Common/tests/SystemBrushesTests.cs b/src/System.Drawing.Common/tests/SystemBrushesTests.cs
index 39df67f58f..33c3bf2430 100644
--- a/src/System.Drawing.Common/tests/SystemBrushesTests.cs
+++ b/src/System.Drawing.Common/tests/SystemBrushesTests.cs
@@ -47,17 +47,17 @@ namespace System.Drawing.Tests
yield return Brush(() => SystemBrushes.WindowText, SystemColors.WindowText);
}
- public static object[] Brush(Func<Brush> brushThunk, Color expectedColor) => new object[] { brushThunk, expectedColor };
+ public static object[] Brush(Func<Brush> getBrush, Color expectedColor) => new object[] { getBrush, expectedColor };
[ConditionalTheory(nameof(PlatformDetection) + "." + nameof(PlatformDetection.IsNotWindowsNanoServer))]
[MemberData(nameof(SystemBrushes_TestData))]
- public void SystemBrushes_Get_ReturnsExpected(Func<Brush> brushThunk, Color expectedColor)
+ public void SystemBrushes_Get_ReturnsExpected(Func<Brush> getBrush, Color expectedColor)
{
- SolidBrush brush = Assert.IsType<SolidBrush>(brushThunk());
+ SolidBrush brush = Assert.IsType<SolidBrush>(getBrush());
Assert.Equal(expectedColor, brush.Color);
AssertExtensions.Throws<ArgumentException>(null, () => brush.Color = Color.Red);
- Assert.Same(brush, brushThunk());
+ Assert.Same(brush, getBrush());
}
[Fact]
diff --git a/src/System.Drawing.Common/tests/SystemFontsTests.cs b/src/System.Drawing.Common/tests/SystemFontsTests.cs
new file mode 100644
index 0000000000..ce33e27b47
--- /dev/null
+++ b/src/System.Drawing.Common/tests/SystemFontsTests.cs
@@ -0,0 +1,64 @@
+// Licensed to the .NET Foundation under one or more agreements.
+// See the LICENSE file in the project root for more information.
+
+using System.Collections.Generic;
+using System.Runtime.InteropServices;
+using Xunit;
+
+namespace System.Drawing.Tests
+{
+ public class SystemFontsTests
+ {
+ public static IEnumerable<object[]> SystemFonts_TestData()
+ {
+ yield return Font(() => SystemFonts.CaptionFont, "CaptionFont", "Segoe UI");
+ yield return Font(() => SystemFonts.IconTitleFont, "IconTitleFont", "Segoe UI");
+ yield return Font(() => SystemFonts.MenuFont, "MenuFont", "Segoe UI");
+ yield return Font(() => SystemFonts.MessageBoxFont, "MessageBoxFont", "Segoe UI");
+ yield return Font(() => SystemFonts.SmallCaptionFont, "SmallCaptionFont", "Segoe UI");
+ yield return Font(() => SystemFonts.StatusFont, "StatusFont", "Segoe UI");
+
+ bool isArabic = (GetSystemDefaultLCID() & 0x3ff) == 0x0001;
+ yield return Font(() => SystemFonts.DefaultFont, "DefaultFont", isArabic ? "Tahoma" : "Microsoft Sans Serif");
+
+ bool isJapanese = (GetSystemDefaultLCID() & 0x3ff) == 0x0011;
+ yield return Font(() => SystemFonts.DialogFont, "DialogFont", isJapanese ? "Microsoft Sans Serif" : "Tahoma");
+ }
+
+ public static object[] Font(Func<Font> getFont, string systemFontName, string windowsFontName) => new object[] { getFont, systemFontName, windowsFontName };
+
+ [ConditionalTheory(nameof(PlatformDetection) + "." + nameof(PlatformDetection.IsNotWindowsNanoServer))]
+ [MemberData(nameof(SystemFonts_TestData))]
+ public void SystemFont_Get_ReturnsExpected(Func<Font> getFont, string systemFontName, string windowsFontName)
+ {
+ using (Font font = getFont())
+ using (Font otherFont = getFont())
+ using (Font fontFromName = SystemFonts.GetFontByName(systemFontName))
+ {
+ Assert.NotSame(font, otherFont);
+ Assert.Equal(font, otherFont);
+ Assert.Equal(font, fontFromName);
+
+ Assert.Equal(systemFontName, font.SystemFontName);
+
+ // Windows 8 updated some system fonts.
+ if (!PlatformDetection.IsWindows7)
+ {
+ Assert.Equal(windowsFontName, font.Name);
+ }
+ }
+ }
+
+ [Theory]
+ [InlineData(null)]
+ [InlineData("")]
+ [InlineData("captionfont")]
+ public void GetFontByName_NoSuchName_ReturnsNull(string systemFontName)
+ {
+ Assert.Null(SystemFonts.GetFontByName(systemFontName));
+ }
+
+ [DllImport("kernel32.dll", SetLastError = true, CharSet = CharSet.Auto)]
+ public static extern int GetSystemDefaultLCID();
+ }
+}
diff --git a/src/System.Drawing.Common/tests/SystemIconsTests.cs b/src/System.Drawing.Common/tests/SystemIconsTests.cs
index 4bd1f2036f..b232c6c05e 100644
--- a/src/System.Drawing.Common/tests/SystemIconsTests.cs
+++ b/src/System.Drawing.Common/tests/SystemIconsTests.cs
@@ -22,14 +22,14 @@ namespace System.Drawing.Tests
yield return Icon(() => SystemIcons.WinLogo);
}
- public static object[] Icon(Func<Icon> iconThunk) => new object[] { iconThunk };
+ public static object[] Icon(Func<Icon> getIcon) => new object[] { getIcon };
[ConditionalTheory(nameof(PlatformDetection) + "." + nameof(PlatformDetection.IsNotWindowsNanoServer))]
[MemberData(nameof(SystemIcons_TestData))]
- public void SystemIcons_Get_ReturnsExpected(Func<Icon> iconThunk)
+ public void SystemIcons_Get_ReturnsExpected(Func<Icon> getIcon)
{
- Icon icon = iconThunk();
- Assert.Same(icon, iconThunk());
+ Icon icon = getIcon();
+ Assert.Same(icon, getIcon());
}
}
}
diff --git a/src/System.Drawing.Common/tests/SystemPensTest.cs b/src/System.Drawing.Common/tests/SystemPensTest.cs
index 2649fa9beb..4d367e212e 100644
--- a/src/System.Drawing.Common/tests/SystemPensTest.cs
+++ b/src/System.Drawing.Common/tests/SystemPensTest.cs
@@ -47,16 +47,16 @@ namespace System.Drawing.Tests
yield return Pen(() => SystemPens.WindowText, SystemColors.WindowText);
}
- public static object[] Pen(Func<Pen> penThunk, Color expectedColor) => new object[] { penThunk, expectedColor };
+ public static object[] Pen(Func<Pen> getPen, Color expectedColor) => new object[] { getPen, expectedColor };
[ConditionalTheory(nameof(PlatformDetection) + "." + nameof(PlatformDetection.IsNotWindowsNanoServer))]
[MemberData(nameof(SystemPens_TestData))]
- public void SystemPens_Get_ReturnsExpected(Func<Pen> penThunk, Color expectedColor)
+ public void SystemPens_Get_ReturnsExpected(Func<Pen> getPen, Color expectedColor)
{
- Pen pen = penThunk();
+ Pen pen = getPen();
Assert.Equal(expectedColor, pen.Color);
Assert.Equal(PenType.SolidColor, pen.PenType);
- Assert.Same(pen, penThunk());
+ Assert.Same(pen, getPen());
AssertExtensions.Throws<ArgumentException>(null, () => pen.Dispose());
AssertExtensions.Throws<ArgumentException>(null, () => pen.SetLineCap(LineCap.ArrowAnchor, LineCap.Custom, DashCap.Round));
diff --git a/src/System.Drawing.Common/tests/Text/PrivateFontCollectionTests.cs b/src/System.Drawing.Common/tests/Text/PrivateFontCollectionTests.cs
index b9ebd9bcad..61917ab4bb 100644
--- a/src/System.Drawing.Common/tests/Text/PrivateFontCollectionTests.cs
+++ b/src/System.Drawing.Common/tests/Text/PrivateFontCollectionTests.cs
@@ -5,6 +5,7 @@ using System.Collections.Generic;
using System.Drawing.Tests;
using System.IO;
using System.Runtime.InteropServices;
+using System.Security.Permissions;
using Xunit;
namespace System.Drawing.Text.Tests
@@ -21,7 +22,7 @@ namespace System.Drawing.Text.Tests
}
[ConditionalFact(nameof(PlatformDetection) + "." + nameof(PlatformDetection.IsNotWindowsNanoServer))]
- public void AddFontFile_FontFile_Success()
+ public void AddFontFile_AbsolutePath_Success()
{
// GDI+ on Windows 7 incorrectly throws a FileNotFoundException.
if (PlatformDetection.IsWindows7)
@@ -34,13 +35,73 @@ namespace System.Drawing.Text.Tests
fontCollection.AddFontFile(Helpers.GetTestBitmapPath("empty.file"));
fontCollection.AddFontFile(Helpers.GetTestFontPath("CodeNewRoman.otf"));
- FontFamily font = Assert.Single(fontCollection.Families);
- Assert.Equal("Code New Roman", font.Name);
+ FontFamily fontFamily = Assert.Single(fontCollection.Families);
+ Assert.Equal("Code New Roman", fontFamily.Name);
+ }
+ }
+
+ [ConditionalFact(nameof(PlatformDetection) + "." + nameof(PlatformDetection.IsNotWindowsNanoServer))]
+ public void AddFontFile_RelativePath_Success()
+ {
+ // GDI+ on Windows 7 incorrectly throws a FileNotFoundException.
+ if (PlatformDetection.IsWindows7)
+ {
+ return;
+ }
+
+ using (var fontCollection = new PrivateFontCollection())
+ {
+ string relativePath = Path.Combine("fonts", "CodeNewRoman.ttf");
+ fontCollection.AddFontFile(relativePath);
+
+ FontFamily fontFamily = Assert.Single(fontCollection.Families);
+ Assert.Equal("Code New Roman", fontFamily.Name);
+ }
+ }
+
+ [ConditionalFact(nameof(PlatformDetection) + "." + nameof(PlatformDetection.IsNotWindowsNanoServer))]
+ public void AddFontFile_SamePathMultipleTimes_FamiliesContainsOnlyOneFont()
+ {
+ // GDI+ on Windows 7 incorrectly throws a FileNotFoundException.
+ if (PlatformDetection.IsWindows7)
+ {
+ return;
+ }
+
+ using (var fontCollection = new PrivateFontCollection())
+ {
+ fontCollection.AddFontFile(Helpers.GetTestFontPath("CodeNewRoman.ttf"));
+ fontCollection.AddFontFile(Helpers.GetTestFontPath("CodeNewRoman.ttf"));
+
+ FontFamily fontFamily = Assert.Single(fontCollection.Families);
+ Assert.Equal("Code New Roman", fontFamily.Name);
+ }
+ }
+
+ [ConditionalFact(nameof(PlatformDetection) + "." + nameof(PlatformDetection.IsNotWindowsNanoServer))]
+ public void AddFontFile_SameNameMultipleTimes_FamiliesContainsFirstFontOnly()
+ {
+ // GDI+ on Windows 7 incorrectly throws a FileNotFoundException.
+ if (PlatformDetection.IsWindows7)
+ {
+ return;
+ }
+
+ using (var fontCollection = new PrivateFontCollection())
+ {
+ fontCollection.AddFontFile(Helpers.GetTestFontPath("CodeNewRoman.ttf"));
+ fontCollection.AddFontFile(Helpers.GetTestFontPath("CodeNewRoman.otf"));
+
+ // Verify that the first file is used by checking that it contains metadata
+ // associated with CodeNewRoman.ttf.
+ const int FrenchLCID = 1036;
+ FontFamily fontFamily = Assert.Single(fontCollection.Families);
+ Assert.Equal("Code New Roman", fontFamily.Name);
+ Assert.Equal("Bonjour", fontFamily.GetName(FrenchLCID));
}
}
[ConditionalFact(nameof(PlatformDetection) + "." + nameof(PlatformDetection.IsNotWindowsNanoServer))]
- [ActiveIssue(21558, TargetFrameworkMonikers.Netcoreapp)]
public void AddFontFile_NullFileName_ThrowsArgumentNullException()
{
using (var fontCollection = new PrivateFontCollection())
@@ -50,18 +111,16 @@ namespace System.Drawing.Text.Tests
}
[ConditionalFact(nameof(PlatformDetection) + "." + nameof(PlatformDetection.IsNotWindowsNanoServer))]
- [ActiveIssue(21558, TargetFrameworkMonikers.Netcoreapp)]
public void AddFontFile_InvalidPath_ThrowsArgumentException()
{
using (var fontCollection = new PrivateFontCollection())
{
- AssertExtensions.Throws<ArgumentException>(null, () => fontCollection.AddFontFile(string.Empty));
+ AssertExtensions.Throws<ArgumentException>("path", null, () => fontCollection.AddFontFile(string.Empty));
}
}
[ConditionalFact(nameof(PlatformDetection) + "." + nameof(PlatformDetection.IsNotWindowsNanoServer))]
- [ActiveIssue(21558, TargetFrameworkMonikers.Netcoreapp)]
- public void AddFontFile_NoSuchFilePath_ThrowsArgumentException()
+ public void AddFontFile_NoSuchFilePath_ThrowsFileNotFoundException()
{
using (var fontCollection = new PrivateFontCollection())
{
@@ -70,7 +129,6 @@ namespace System.Drawing.Text.Tests
}
[ConditionalFact(nameof(PlatformDetection) + "." + nameof(PlatformDetection.IsNotWindowsNanoServer))]
- [ActiveIssue(21558, TargetFrameworkMonikers.Netcoreapp)]
public void AddFontFile_LongFilePath_ThrowsPathTooLongException()
{
using (var fontCollection = new PrivateFontCollection())
diff --git a/src/System.Drawing.Primitives/tests/System.Drawing.Primitives.Tests.csproj b/src/System.Drawing.Primitives/tests/System.Drawing.Primitives.Tests.csproj
index fa5c15ceac..29a26cc198 100644
--- a/src/System.Drawing.Primitives/tests/System.Drawing.Primitives.Tests.csproj
+++ b/src/System.Drawing.Primitives/tests/System.Drawing.Primitives.Tests.csproj
@@ -20,9 +20,6 @@
<Compile Include="SizeTests.cs" />
<Compile Include="ColorTests.cs" />
<Compile Include="SerializationTests.cs" />
- <Compile Include="$(CommonTestPath)\System\AssertExtensions.cs">
- <Link>Common\System\AssertExtensions.cs</Link>
- </Compile>
<Compile Include="$(CommonTestPath)\System\PlatformDetection.cs">
<Link>Common\System\PlatformDetection.cs</Link>
</Compile>
diff --git a/src/System.Dynamic.Runtime/tests/System.Dynamic.Runtime.Tests.csproj b/src/System.Dynamic.Runtime/tests/System.Dynamic.Runtime.Tests.csproj
index 38f8521361..c847b00e46 100644
--- a/src/System.Dynamic.Runtime/tests/System.Dynamic.Runtime.Tests.csproj
+++ b/src/System.Dynamic.Runtime/tests/System.Dynamic.Runtime.Tests.csproj
@@ -156,9 +156,6 @@
<Compile Include="Dynamic.Variance\Conformance.dynamic.Variance.implem.cs" />
<Compile Include="Common.cs" />
<Compile Include="ErrorVerifier.cs" />
- <Compile Include="$(CommonTestPath)\System\AssertExtensions.cs">
- <Link>Common\System\AssertExtensions.cs</Link>
- </Compile>
<Compile Include="$(CommonTestPath)\System\PlatformDetection.cs">
<Link>Common\System\PlatformDetection.cs</Link>
</Compile>
diff --git a/src/System.Globalization.Calendars/tests/System.Globalization.Calendars.Tests.csproj b/src/System.Globalization.Calendars/tests/System.Globalization.Calendars.Tests.csproj
index 6cb9a8e88c..ed9fddc213 100644
--- a/src/System.Globalization.Calendars/tests/System.Globalization.Calendars.Tests.csproj
+++ b/src/System.Globalization.Calendars/tests/System.Globalization.Calendars.Tests.csproj
@@ -109,9 +109,6 @@
<Compile Include="ThaiBuddhistCalendar\ThaiBuddhistCalendarTwoDigitYearMax.cs" />
<Compile Include="$(CommonTestPath)\System\RandomDataGenerator.cs" />
<!-- Helpers -->
- <Compile Include="$(CommonTestPath)\System\AssertExtensions.cs">
- <Link>Common\System\AssertExtensions.cs</Link>
- </Compile>
<Compile Include="$(CommonTestPath)\System\PlatformDetection.cs">
<Link>Common\System\PlatformDetection.cs</Link>
</Compile>
diff --git a/src/System.Globalization.Extensions/tests/System.Globalization.Extensions.Tests.csproj b/src/System.Globalization.Extensions/tests/System.Globalization.Extensions.Tests.csproj
index 2fad06f171..86c311de54 100644
--- a/src/System.Globalization.Extensions/tests/System.Globalization.Extensions.Tests.csproj
+++ b/src/System.Globalization.Extensions/tests/System.Globalization.Extensions.Tests.csproj
@@ -22,9 +22,6 @@
<Compile Include="IdnMapping\IdnMappingUseStd3AsciiRulesTests.cs" />
<Compile Include="Normalization\StringNormalizationTests.cs" />
<Compile Include="Normalization\NormalizationAll.cs" />
- <Compile Include="$(CommonTestPath)\System\AssertExtensions.cs">
- <Link>Common\System\AssertExtensions.cs</Link>
- </Compile>
<Compile Include="$(CommonTestPath)\System\PlatformDetection.cs">
<Link>Common\System\PlatformDetection.cs</Link>
</Compile>
diff --git a/src/System.Globalization/tests/System.Globalization.Tests.csproj b/src/System.Globalization/tests/System.Globalization.Tests.csproj
index ff7eb68ae4..dde763ee8b 100644
--- a/src/System.Globalization/tests/System.Globalization.Tests.csproj
+++ b/src/System.Globalization/tests/System.Globalization.Tests.csproj
@@ -131,9 +131,6 @@
<Compile Include="TextInfo\TextInfoToUpper.cs" />
<Compile Include="UnicodeCategory\UnicodeCategoryTests.cs" />
<!-- Helpers -->
- <Compile Include="$(CommonTestPath)\System\AssertExtensions.cs">
- <Link>Common\System\AssertExtensions.cs</Link>
- </Compile>
<Compile Include="$(CommonTestPath)\System\PlatformDetection.cs">
<Link>Common\System\PlatformDetection.cs</Link>
</Compile>
diff --git a/src/System.IO.Compression.ZipFile/tests/System.IO.Compression.ZipFile.Tests.csproj b/src/System.IO.Compression.ZipFile/tests/System.IO.Compression.ZipFile.Tests.csproj
index c61ecbcd70..0c1a87fcef 100644
--- a/src/System.IO.Compression.ZipFile/tests/System.IO.Compression.ZipFile.Tests.csproj
+++ b/src/System.IO.Compression.ZipFile/tests/System.IO.Compression.ZipFile.Tests.csproj
@@ -12,9 +12,6 @@
<Compile Include="ZipFileConvenienceMethods.cs" />
<Compile Include="ZipFileInvalidFileTests.cs" />
<Compile Include="ZipFileReadOpenUpdateTests.cs" />
- <Compile Include="$(CommonTestPath)\System\AssertExtensions.cs">
- <Link>Common\System\AssertExtensions.cs</Link>
- </Compile>
<Compile Include="$(CommonTestPath)\System\IO\TempFile.cs">
<Link>Common\System\IO\TempFile.cs</Link>
</Compile>
diff --git a/src/System.IO.Compression/tests/System.IO.Compression.Tests.csproj b/src/System.IO.Compression/tests/System.IO.Compression.Tests.csproj
index 64e2dfde30..22ad61d3bc 100644
--- a/src/System.IO.Compression/tests/System.IO.Compression.Tests.csproj
+++ b/src/System.IO.Compression/tests/System.IO.Compression.Tests.csproj
@@ -24,9 +24,6 @@
<Compile Include="ZipArchive\zip_UpdateTests.cs" />
<Compile Include="Utilities\StripHeaderAndFooter.cs" />
<Compile Include="Utilities\WrappedStream.cs" />
- <Compile Include="$(CommonTestPath)\System\AssertExtensions.cs">
- <Link>Common\System\AssertExtensions.cs</Link>
- </Compile>
<Compile Include="$(CommonTestPath)\System\IO\PathFeatures.cs">
<Link>Common\System\IO\PathFeatures.cs</Link>
</Compile>
diff --git a/src/System.IO.FileSystem.AccessControl/tests/System.IO.FileSystem.AccessControl.Tests.csproj b/src/System.IO.FileSystem.AccessControl/tests/System.IO.FileSystem.AccessControl.Tests.csproj
index da14afb185..3a42f3e7b1 100644
--- a/src/System.IO.FileSystem.AccessControl/tests/System.IO.FileSystem.AccessControl.Tests.csproj
+++ b/src/System.IO.FileSystem.AccessControl/tests/System.IO.FileSystem.AccessControl.Tests.csproj
@@ -12,9 +12,6 @@
<Compile Include="DirectoryObjectSecurityTests.cs" />
<Compile Include="FileSystemAccessRuleTests.cs" />
<Compile Include="FileSystemAclExtensionsTests.cs" />
- <Compile Include="$(CommonTestPath)\System\AssertExtensions.cs">
- <Link>Common\System\AssertExtensions.cs</Link>
- </Compile>
<Compile Include="$(CommonTestPath)\System\IO\TempFile.cs">
<Link>Common\System\IO\TempFile.cs</Link>
</Compile>
diff --git a/src/System.IO.FileSystem.DriveInfo/tests/System.IO.FileSystem.DriveInfo.Tests.csproj b/src/System.IO.FileSystem.DriveInfo/tests/System.IO.FileSystem.DriveInfo.Tests.csproj
index 3dd3032330..8faded10c4 100644
--- a/src/System.IO.FileSystem.DriveInfo/tests/System.IO.FileSystem.DriveInfo.Tests.csproj
+++ b/src/System.IO.FileSystem.DriveInfo/tests/System.IO.FileSystem.DriveInfo.Tests.csproj
@@ -10,9 +10,6 @@
<PropertyGroup Condition="'$(Configuration)|$(Platform)' == 'netstandard-Windows_NT-Debug|AnyCPU'" />
<PropertyGroup Condition="'$(Configuration)|$(Platform)' == 'netstandard-Windows_NT-Release|AnyCPU'" />
<ItemGroup>
- <Compile Include="$(CommonTestPath)\System\AssertExtensions.cs">
- <Link>Common\System\AssertExtensions.cs</Link>
- </Compile>
<Compile Include="DriveInfo.Unix.Tests.cs" Condition="'$(TargetsUnix)' == 'true'" />
<Compile Include="DriveInfo.Windows.Tests.cs" Condition="'$(TargetsWindows)' == 'true'" />
<Compile Include="$(CommonTestPath)\System\PlatformDetection.cs">
diff --git a/src/System.IO.FileSystem.Watcher/tests/System.IO.FileSystem.Watcher.Tests.csproj b/src/System.IO.FileSystem.Watcher/tests/System.IO.FileSystem.Watcher.Tests.csproj
index f6ee7a174d..4f6c267837 100644
--- a/src/System.IO.FileSystem.Watcher/tests/System.IO.FileSystem.Watcher.Tests.csproj
+++ b/src/System.IO.FileSystem.Watcher/tests/System.IO.FileSystem.Watcher.Tests.csproj
@@ -37,9 +37,6 @@
<SubType>Component</SubType>
</Compile>
<Compile Include="Utility\FileSystemWatcherTest.cs" />
- <Compile Include="$(CommonTestPath)\System\AssertExtensions.cs">
- <Link>Common\System\AssertExtensions.cs</Link>
- </Compile>
<Compile Include="$(CommonTestPath)\System\IO\TempFile.cs">
<Link>Common\System\IO\TempFile.cs</Link>
</Compile>
diff --git a/src/System.IO.FileSystem/src/System/IO/Directory.cs b/src/System.IO.FileSystem/src/System/IO/Directory.cs
index 8039cc6a83..9c5095540f 100644
--- a/src/System.IO.FileSystem/src/System/IO/Directory.cs
+++ b/src/System.IO.FileSystem/src/System/IO/Directory.cs
@@ -512,8 +512,6 @@ namespace System.IO
if (path.Length == 0)
throw new ArgumentException(SR.Argument_PathEmpty, nameof(path));
Contract.EndContractBlock();
- if (PathInternal.IsPathTooLong(path))
- throw new PathTooLongException(SR.IO_PathTooLong);
string fulldestDirName = Path.GetFullPath(path);
@@ -537,13 +535,8 @@ namespace System.IO
string fullsourceDirName = Path.GetFullPath(sourceDirName);
string sourcePath = EnsureTrailingDirectorySeparator(fullsourceDirName);
- if (PathInternal.IsDirectoryTooLong(sourcePath))
- throw new PathTooLongException(SR.IO_PathTooLong);
-
string fulldestDirName = Path.GetFullPath(destDirName);
string destPath = EnsureTrailingDirectorySeparator(fulldestDirName);
- if (PathInternal.IsDirectoryTooLong(destPath))
- throw new PathTooLongException(SR.IO_PathTooLong);
StringComparison pathComparison = PathInternal.StringComparison;
diff --git a/src/System.IO.FileSystem/src/System/IO/DirectoryInfo.cs b/src/System.IO.FileSystem/src/System/IO/DirectoryInfo.cs
index 9842c70f87..ff23b11046 100644
--- a/src/System.IO.FileSystem/src/System/IO/DirectoryInfo.cs
+++ b/src/System.IO.FileSystem/src/System/IO/DirectoryInfo.cs
@@ -392,12 +392,6 @@ namespace System.IO
else
fullSourcePath = FullPath + PathHelpers.DirectorySeparatorCharAsString;
- if (PathInternal.IsDirectoryTooLong(fullSourcePath))
- throw new PathTooLongException(SR.IO_PathTooLong);
-
- if (PathInternal.IsDirectoryTooLong(destinationWithSeparator))
- throw new PathTooLongException(SR.IO_PathTooLong);
-
StringComparison pathComparison = PathInternal.StringComparison;
if (string.Equals(fullSourcePath, destinationWithSeparator, pathComparison))
throw new IOException(SR.IO_SourceDestMustBeDifferent);
diff --git a/src/System.IO.FileSystem/src/System/IO/PathHelpers.Windows.cs b/src/System.IO.FileSystem/src/System/IO/PathHelpers.Windows.cs
index a8da668317..126c7e3836 100644
--- a/src/System.IO.FileSystem/src/System/IO/PathHelpers.Windows.cs
+++ b/src/System.IO.FileSystem/src/System/IO/PathHelpers.Windows.cs
@@ -36,11 +36,6 @@ namespace System.IO
throw new ArgumentException(SR.Arg_InvalidSearchPattern, nameof(searchPattern));
}
}
-
- if (searchPattern.Length >= PathInternal.MaxComponentLength)
- {
- throw new PathTooLongException(SR.IO_PathTooLong);
- }
}
// this is a lightweight version of GetDirectoryName that doesn't renormalize
diff --git a/src/System.IO.FileSystem/src/System/IO/UnixFileSystem.cs b/src/System.IO.FileSystem/src/System/IO/UnixFileSystem.cs
index 3ebbf07d57..253a3ed2a8 100644
--- a/src/System.IO.FileSystem/src/System/IO/UnixFileSystem.cs
+++ b/src/System.IO.FileSystem/src/System/IO/UnixFileSystem.cs
@@ -248,10 +248,6 @@ namespace System.IO
while (stackDir.Count > 0)
{
string name = stackDir.Pop();
- if (name.Length >= Interop.Sys.MaxPath)
- {
- throw new PathTooLongException(SR.IO_PathTooLong);
- }
// The mkdir command uses 0777 by default (it'll be AND'd with the process umask internally).
// We do the same.
@@ -503,7 +499,7 @@ namespace System.IO
{
throw new ArgumentNullException("path");
}
- if (string.IsNullOrWhiteSpace(userPath))
+ if (string.IsNullOrEmpty(userPath))
{
throw new ArgumentException(SR.Argument_EmptyPath, "path");
}
diff --git a/src/System.IO.FileSystem/src/System/IO/Win32FileSystem.cs b/src/System.IO.FileSystem/src/System/IO/Win32FileSystem.cs
index 7342c9c401..8e5b9d13bd 100644
--- a/src/System.IO.FileSystem/src/System/IO/Win32FileSystem.cs
+++ b/src/System.IO.FileSystem/src/System/IO/Win32FileSystem.cs
@@ -61,9 +61,6 @@ namespace System.IO
[System.Security.SecuritySafeCritical]
public override void CreateDirectory(string fullPath)
{
- if (PathInternal.IsDirectoryTooLong(fullPath))
- throw new PathTooLongException(SR.IO_PathTooLong);
-
// We can save a bunch of work if the directory we want to create already exists. This also
// saves us in the case where sub paths are inaccessible (due to ERROR_ACCESS_DENIED) but the
// final path is accessible and the directory already exists. For example, consider trying
diff --git a/src/System.IO.FileSystem/tests/Directory/CreateDirectory.cs b/src/System.IO.FileSystem/tests/Directory/CreateDirectory.cs
index ea4dd447d0..415a31ac27 100644
--- a/src/System.IO.FileSystem/tests/Directory/CreateDirectory.cs
+++ b/src/System.IO.FileSystem/tests/Directory/CreateDirectory.cs
@@ -9,6 +9,7 @@ namespace System.IO.Tests
{
public class Directory_CreateDirectory : FileSystemTest
{
+ public static TheoryData ReservedDeviceNames = IOInputs.GetReservedDeviceNames().ToTheoryData();
#region Utilities
public virtual DirectoryInfo Create(string path)
@@ -122,38 +123,34 @@ namespace System.IO.Tests
Assert.True(result.Exists);
}
- [ConditionalFact(nameof(UsingNewNormalization))]
+ [ConditionalTheory(nameof(UsingNewNormalization)),
+ MemberData(nameof(ValidPathComponentNames))]
[ActiveIssue(20117, TargetFrameworkMonikers.Uap)]
[PlatformSpecific(TestPlatforms.Windows)] // trailing slash
- public void ValidExtendedPathWithTrailingSlash()
+ public void ValidExtendedPathWithTrailingSlash(string component)
{
DirectoryInfo testDir = Directory.CreateDirectory(GetTestFilePath());
- var components = IOInputs.GetValidPathComponentNames();
- Assert.All(components, (component) =>
- {
- string path = IOInputs.ExtendedPrefix + IOServices.AddTrailingSlashIfNeeded(Path.Combine(testDir.FullName, component));
- DirectoryInfo result = Create(path);
+ string path = IOInputs.ExtendedPrefix + IOServices.AddTrailingSlashIfNeeded(Path.Combine(testDir.FullName, component));
+ DirectoryInfo result = Create(path);
+
+ Assert.Equal(path, result.FullName);
+ Assert.True(result.Exists);
- Assert.Equal(path, result.FullName);
- Assert.True(result.Exists);
- });
}
- [Fact]
- public void ValidPathWithoutTrailingSlash()
+ [Theory,
+ MemberData(nameof(ValidPathComponentNames))]
+ public void ValidPathWithoutTrailingSlash(string component)
{
DirectoryInfo testDir = Directory.CreateDirectory(GetTestFilePath());
- var components = IOInputs.GetValidPathComponentNames();
- Assert.All(components, (component) =>
- {
- string path = testDir.FullName + Path.DirectorySeparatorChar + component;
- DirectoryInfo result = Create(path);
+ string path = testDir.FullName + Path.DirectorySeparatorChar + component;
+ DirectoryInfo result = Create(path);
+
+ Assert.Equal(path, result.FullName);
+ Assert.True(Directory.Exists(result.FullName));
- Assert.Equal(path, result.FullName);
- Assert.True(Directory.Exists(result.FullName));
- });
}
[Fact]
@@ -199,17 +196,13 @@ namespace System.IO.Tests
Assert.True(Directory.Exists(result.FullName));
}
- [Fact]
- public void DirectoryWithComponentLongerThanMaxComponentAsPath_ThrowsPathTooLongException()
+ [Theory,
+ MemberData(nameof(PathsWithComponentLongerThanMaxComponent))]
+ public void DirectoryWithComponentLongerThanMaxComponentAsPath_ThrowsPathTooLongException(string path)
{
// While paths themselves can be up to 260 characters including trailing null, file systems
// limit each components of the path to a total of 255 characters.
- var paths = IOInputs.GetPathsWithComponentLongerThanMaxComponent();
-
- Assert.All(paths, (path) =>
- {
- Assert.Throws<PathTooLongException>(() => Create(path));
- });
+ Assert.Throws<PathTooLongException>(() => Create(path));
}
#endregion
@@ -250,14 +243,27 @@ namespace System.IO.Tests
[ConditionalFact(nameof(LongPathsAreNotBlocked), nameof(UsingNewNormalization))]
[ActiveIssue(20117, TargetFrameworkMonikers.Uap)]
- [PlatformSpecific(TestPlatforms.Windows)] // long directory path with extended syntax throws PathTooLongException
- public void DirectoryLongerThanMaxLongPathWithExtendedSyntax_ThrowsPathTooLongException()
+ [PlatformSpecific(TestPlatforms.Windows)]
+ public void DirectoryLongerThanMaxLongPathWithExtendedSyntax_ThrowsException()
{
var paths = IOInputs.GetPathsLongerThanMaxLongPath(GetTestFilePath(), useExtendedSyntax: true);
- Assert.All(paths, (path) =>
+
+ // Long directory path with extended syntax throws PathTooLongException on Desktop.
+ // Everywhere else, it may be either PathTooLongException or DirectoryNotFoundException
+ if (PlatformDetection.IsFullFramework)
{
- Assert.Throws<PathTooLongException>(() => Create(path));
- });
+ Assert.All(paths, path => { Assert.Throws<PathTooLongException>(() => Create(path)); });
+ }
+ else
+ {
+ Assert.All(paths,
+ path =>
+ {
+ AssertExtensions
+ .ThrowsAny<PathTooLongException, DirectoryNotFoundException>(
+ () => Create(path));
+ });
+ }
}
[ConditionalFact(nameof(LongPathsAreNotBlocked), nameof(UsingNewNormalization))]
@@ -308,122 +314,97 @@ namespace System.IO.Tests
}
}
- [Fact]
+ [Theory,
+ MemberData(nameof(WhiteSpace))]
[PlatformSpecific(TestPlatforms.Windows)] // whitespace as path throws ArgumentException on Windows
- public void WindowsWhiteSpaceAsPath_ThrowsArgumentException()
+ public void WindowsWhiteSpaceAsPath_ThrowsArgumentException(string path)
{
- var paths = IOInputs.GetWhiteSpace();
- Assert.All(paths, (path) =>
- {
- Assert.Throws<ArgumentException>(() => Create(path));
- });
+ Assert.Throws<ArgumentException>(() => Create(path));
}
- [Fact]
+ [Theory,
+ MemberData(nameof(WhiteSpace))]
[PlatformSpecific(TestPlatforms.AnyUnix)] // whitespace as path allowed
- public void UnixWhiteSpaceAsPath_Allowed()
+ public void UnixWhiteSpaceAsPath_Allowed(string path)
{
- var paths = IOInputs.GetWhiteSpace();
- Assert.All(paths, (path) =>
- {
- Create(Path.Combine(TestDirectory, path));
- Assert.True(Directory.Exists(Path.Combine(TestDirectory, path)));
- });
+ Create(Path.Combine(TestDirectory, path));
+ Assert.True(Directory.Exists(Path.Combine(TestDirectory, path)));
+
}
- [Fact]
+ [Theory,
+ MemberData(nameof(WhiteSpace))]
[PlatformSpecific(TestPlatforms.Windows)] // trailing whitespace in path is removed on Windows
- public void WindowsTrailingWhiteSpace()
+ public void WindowsTrailingWhiteSpace(string component)
{
// Windows will remove all non-significant whitespace in a path
DirectoryInfo testDir = Create(GetTestFilePath());
- var components = IOInputs.GetWhiteSpace();
-
- Assert.All(components, (component) =>
- {
- string path = IOServices.RemoveTrailingSlash(testDir.FullName) + component;
- DirectoryInfo result = Create(path);
+ string path = IOServices.RemoveTrailingSlash(testDir.FullName) + component;
+ DirectoryInfo result = Create(path);
- Assert.True(Directory.Exists(result.FullName));
- Assert.Equal(testDir.FullName, IOServices.RemoveTrailingSlash(result.FullName));
- });
+ Assert.True(Directory.Exists(result.FullName));
+ Assert.Equal(testDir.FullName, IOServices.RemoveTrailingSlash(result.FullName));
}
- [ConditionalFact(nameof(UsingNewNormalization))]
+ [ConditionalTheory(nameof(UsingNewNormalization)),
+ MemberData(nameof(SimpleWhiteSpace))]
[ActiveIssue(20117, TargetFrameworkMonikers.Uap)]
[PlatformSpecific(TestPlatforms.Windows)] // extended syntax with whitespace
- public void WindowsExtendedSyntaxWhiteSpace()
+ public void WindowsExtendedSyntaxWhiteSpace(string path)
{
- var paths = IOInputs.GetSimpleWhiteSpace();
- foreach (var path in paths)
- {
- string extendedPath = Path.Combine(IOInputs.ExtendedPrefix + TestDirectory, path);
- Directory.CreateDirectory(extendedPath);
- Assert.True(Directory.Exists(extendedPath), extendedPath);
- }
+ string extendedPath = Path.Combine(IOInputs.ExtendedPrefix + TestDirectory, path);
+ Directory.CreateDirectory(extendedPath);
+ Assert.True(Directory.Exists(extendedPath), extendedPath);
}
- [Fact]
+ [Theory,
+ MemberData(nameof(WhiteSpace))]
[PlatformSpecific(TestPlatforms.AnyUnix)] // trailing whitespace in path treated as significant on Unix
- public void UnixNonSignificantTrailingWhiteSpace()
+ public void UnixNonSignificantTrailingWhiteSpace(string component)
{
// Unix treats trailing/prename whitespace as significant and a part of the name.
DirectoryInfo testDir = Create(GetTestFilePath());
- var components = IOInputs.GetWhiteSpace();
- Assert.All(components, (component) =>
- {
- string path = IOServices.RemoveTrailingSlash(testDir.FullName) + component;
- DirectoryInfo result = Create(path);
+ string path = IOServices.RemoveTrailingSlash(testDir.FullName) + component;
+ DirectoryInfo result = Create(path);
+
+ Assert.True(Directory.Exists(result.FullName));
+ Assert.NotEqual(testDir.FullName, IOServices.RemoveTrailingSlash(result.FullName));
- Assert.True(Directory.Exists(result.FullName));
- Assert.NotEqual(testDir.FullName, IOServices.RemoveTrailingSlash(result.FullName));
- });
}
- [Fact]
+ [Theory,
+ MemberData(nameof(PathsWithAlternativeDataStreams))]
[PlatformSpecific(TestPlatforms.Windows)] // alternate data streams
- public void PathWithAlternateDataStreams_ThrowsNotSupportedException()
+ public void PathWithAlternateDataStreams_ThrowsNotSupportedException(string path)
{
- var paths = IOInputs.GetPathsWithAlternativeDataStreams();
- Assert.All(paths, (path) =>
- {
- Assert.Throws<NotSupportedException>(() => Create(path));
- });
+ Assert.Throws<NotSupportedException>(() => Create(path));
}
- [Fact]
+ [Theory,
+ MemberData(nameof(PathsWithReservedDeviceNames))]
[PlatformSpecific(TestPlatforms.Windows)] // device name prefixes
- public void PathWithReservedDeviceNameAsPath_ThrowsDirectoryNotFoundException()
- { // Throws DirectoryNotFoundException, when the behavior really should be an invalid path
- var paths = IOInputs.GetPathsWithReservedDeviceNames();
- Assert.All(paths, (path) =>
- {
- Assert.Throws<DirectoryNotFoundException>(() => Create(path));
- });
+ public void PathWithReservedDeviceNameAsPath_ThrowsDirectoryNotFoundException(string path)
+ {
+ // Throws DirectoryNotFoundException, when the behavior really should be an invalid path
+ Assert.Throws<DirectoryNotFoundException>(() => Create(path));
}
- [ConditionalFact(nameof(UsingNewNormalization))]
+ [ConditionalTheory(nameof(UsingNewNormalization)),
+ MemberData(nameof(ReservedDeviceNames))]
[ActiveIssue(20117, TargetFrameworkMonikers.Uap)]
[PlatformSpecific(TestPlatforms.Windows)] // device name prefixes
- public void PathWithReservedDeviceNameAsExtendedPath()
+ public void PathWithReservedDeviceNameAsExtendedPath(string path)
{
- var paths = IOInputs.GetReservedDeviceNames();
- Assert.All(paths, (path) =>
- {
- Assert.True(Create(IOInputs.ExtendedPrefix + Path.Combine(TestDirectory, path)).Exists, path);
- });
+ Assert.True(Create(IOInputs.ExtendedPrefix + Path.Combine(TestDirectory, path)).Exists, path);
}
- [Fact]
+ [Theory,
+ MemberData(nameof(UncPathsWithoutShareName))]
[PlatformSpecific(TestPlatforms.Windows)] // UNC shares
- public void UncPathWithoutShareNameAsPath_ThrowsArgumentException()
+ public void UncPathWithoutShareNameAsPath_ThrowsArgumentException(string path)
{
- var paths = IOInputs.GetUncPathsWithoutShareName();
- foreach (var path in paths)
- {
- Assert.Throws<ArgumentException>(() => Create(path));
- }
+ Assert.Throws<ArgumentException>(() => Create(path));
}
[Fact]
diff --git a/src/System.IO.FileSystem/tests/Directory/Exists.cs b/src/System.IO.FileSystem/tests/Directory/Exists.cs
index 10f08bd133..59286e5ea3 100644
--- a/src/System.IO.FileSystem/tests/Directory/Exists.cs
+++ b/src/System.IO.FileSystem/tests/Directory/Exists.cs
@@ -33,24 +33,20 @@ namespace System.IO.Tests
Assert.False(Exists(string.Empty));
}
- [Fact]
- public void NonExistentValidPath_ReturnsFalse()
+ [Theory,
+ MemberData(nameof(ValidPathComponentNames))]
+ public void NonExistentValidPath_ReturnsFalse(string path)
{
- Assert.All((IOInputs.GetValidPathComponentNames()), (path) =>
- {
- Assert.False(Exists(path), path);
- });
+ Assert.False(Exists(path), path);
}
- [Fact]
- public void ValidPathExists_ReturnsTrue()
+ [Theory,
+ MemberData(nameof(ValidPathComponentNames))]
+ public void ValidPathExists_ReturnsTrue(string component)
{
- Assert.All((IOInputs.GetValidPathComponentNames()), (component) =>
- {
- string path = Path.Combine(TestDirectory, component);
- DirectoryInfo testDir = Directory.CreateDirectory(path);
- Assert.True(Exists(path));
- });
+ string path = Path.Combine(TestDirectory, component);
+ DirectoryInfo testDir = Directory.CreateDirectory(path);
+ Assert.True(Exists(path));
}
[Theory, MemberData(nameof(PathsWithInvalidCharacters))]
@@ -176,17 +172,15 @@ namespace System.IO.Tests
#region PlatformSpecific
- [ConditionalFact(nameof(UsingNewNormalization))]
+ [ConditionalTheory(nameof(UsingNewNormalization)),
+ MemberData(nameof(ValidPathComponentNames))]
[ActiveIssue(20117, TargetFrameworkMonikers.Uap)]
[PlatformSpecific(TestPlatforms.Windows)] // Extended path exists
- public void ValidExtendedPathExists_ReturnsTrue()
+ public void ValidExtendedPathExists_ReturnsTrue(string component)
{
- Assert.All((IOInputs.GetValidPathComponentNames()), (component) =>
- {
- string path = IOInputs.ExtendedPrefix + Path.Combine(TestDirectory, "extended", component);
- DirectoryInfo testDir = Directory.CreateDirectory(path);
- Assert.True(Exists(path));
- });
+ string path = IOInputs.ExtendedPrefix + Path.Combine(TestDirectory, "extended", component);
+ DirectoryInfo testDir = Directory.CreateDirectory(path);
+ Assert.True(Exists(path));
}
[ConditionalFact(nameof(UsingNewNormalization))]
@@ -226,15 +220,14 @@ namespace System.IO.Tests
});
}
- [Fact]
+ [Theory,
+ MemberData(nameof(WhiteSpace))]
[PlatformSpecific(TestPlatforms.Windows)] // Unix equivalent tested already in CreateDirectory
- public void WindowsWhiteSpaceAsPath_ReturnsFalse()
+ public void WindowsWhiteSpaceAsPath_ReturnsFalse(string component)
{
// Checks that errors aren't thrown when calling Exists() on impossible paths
- Assert.All(IOInputs.GetWhiteSpace(), (component) =>
- {
- Assert.False(Exists(component));
- });
+ Assert.False(Exists(component));
+
}
[Fact]
@@ -257,58 +250,61 @@ namespace System.IO.Tests
Assert.False(Exists(testDir.FullName.ToLowerInvariant()));
}
- [ConditionalFact(nameof(UsingNewNormalization))]
+ [ConditionalTheory(nameof(UsingNewNormalization)),
+ MemberData(nameof(SimpleWhiteSpace))]
[ActiveIssue(20117, TargetFrameworkMonikers.Uap)]
[PlatformSpecific(TestPlatforms.Windows)] // In Windows, trailing whitespace in a path is trimmed appropriately
- public void TrailingWhitespaceExistence()
+ public void TrailingWhitespaceExistence_SimpleWhiteSpace(string component)
{
// This test relies on \\?\ support
DirectoryInfo testDir = Directory.CreateDirectory(GetTestFilePath());
- Assert.All(IOInputs.GetWhiteSpace(), (component) =>
- {
- string path = testDir.FullName + component;
- Assert.True(Exists(path), path); // string concat in case Path.Combine() trims whitespace before Exists gets to it
- Assert.False(Exists(IOInputs.ExtendedPrefix + path), path);
- });
- Assert.All(IOInputs.GetSimpleWhiteSpace(), (component) =>
- {
- string path = GetTestFilePath(memberName: "Extended") + component;
- testDir = Directory.CreateDirectory(IOInputs.ExtendedPrefix + path);
- Assert.False(Exists(path), path);
- Assert.True(Exists(testDir.FullName));
- });
+ string path = GetTestFilePath(memberName: "Extended") + component;
+ testDir = Directory.CreateDirectory(IOInputs.ExtendedPrefix + path);
+ Assert.False(Exists(path), path);
+ Assert.True(Exists(testDir.FullName));
}
- [Fact]
+ [ConditionalTheory(nameof(UsingNewNormalization)),
+ MemberData(nameof(WhiteSpace))]
+ [ActiveIssue(20117, TargetFrameworkMonikers.Uap)]
+ [PlatformSpecific(TestPlatforms.Windows)] // In Windows, trailing whitespace in a path is trimmed appropriately
+ public void TrailingWhitespaceExistence_WhiteSpace(string component)
+ {
+ // This test relies on \\?\ support
+
+ DirectoryInfo testDir = Directory.CreateDirectory(GetTestFilePath());
+
+ string path = testDir.FullName + component;
+ Assert.True(Exists(path), path); // string concat in case Path.Combine() trims whitespace before Exists gets to it
+ Assert.False(Exists(IOInputs.ExtendedPrefix + path), path);
+
+ }
+
+ [Theory,
+ MemberData(nameof(WhiteSpace))]
[PlatformSpecific(TestPlatforms.Windows)] // alternate data stream
- public void PathWithAlternateDataStreams_ReturnsFalse()
+ public void PathWithAlternateDataStreams_ReturnsFalse(string component)
{
- Assert.All(IOInputs.GetWhiteSpace(), (component) =>
- {
- Assert.False(Exists(component));
- });
+ Assert.False(Exists(component));
+
}
- [Fact]
+ [Theory,
+ MemberData(nameof(PathsWithReservedDeviceNames))]
[OuterLoop]
[PlatformSpecific(TestPlatforms.Windows)] // device names
- public void PathWithReservedDeviceNameAsPath_ReturnsFalse()
+ public void PathWithReservedDeviceNameAsPath_ReturnsFalse(string component)
{
- Assert.All((IOInputs.GetPathsWithReservedDeviceNames()), (component) =>
- {
- Assert.False(Exists(component));
- });
+ Assert.False(Exists(component));
}
- [Fact]
- public void UncPathWithoutShareNameAsPath_ReturnsFalse()
+ [Theory,
+ MemberData(nameof(UncPathsWithoutShareName))]
+ public void UncPathWithoutShareNameAsPath_ReturnsFalse(string component)
{
- Assert.All((IOInputs.GetUncPathsWithoutShareName()), (component) =>
- {
- Assert.False(Exists(component));
- });
+ Assert.False(Exists(component));
}
[Fact]
@@ -322,14 +318,12 @@ namespace System.IO.Tests
Assert.True(Exists(path.FullPath));
}
- [Fact]
+ [Theory,
+ MemberData(nameof(PathsWithComponentLongerThanMaxComponent))]
[PlatformSpecific(TestPlatforms.Windows)] // max directory length not fixed on Unix
- public void DirectoryWithComponentLongerThanMaxComponentAsPath_ReturnsFalse()
+ public void DirectoryWithComponentLongerThanMaxComponentAsPath_ReturnsFalse(string component)
{
- Assert.All((IOInputs.GetPathsWithComponentLongerThanMaxComponent()), (component) =>
- {
- Assert.False(Exists(component));
- });
+ Assert.False(Exists(component));
}
[Fact]
diff --git a/src/System.IO.FileSystem/tests/Directory/GetFileSystemEntries_str.cs b/src/System.IO.FileSystem/tests/Directory/GetFileSystemEntries_str.cs
index 9ce508d08f..8a4175705a 100644
--- a/src/System.IO.FileSystem/tests/Directory/GetFileSystemEntries_str.cs
+++ b/src/System.IO.FileSystem/tests/Directory/GetFileSystemEntries_str.cs
@@ -11,7 +11,7 @@ namespace System.IO.Tests
{
#region Utilities
- public static string[] WindowsInvalidUnixValid = new string[] { " ", " ", "\n", ">", "<", "\t" };
+ public static TheoryData WindowsInvalidUnixValid = new TheoryData<string> { " ", " ", "\n", ">", "<", "\t" };
protected virtual bool TestFiles { get { return true; } } // True if the virtual GetEntries mmethod returns files
protected virtual bool TestDirectories { get { return true; } } // True if the virtual GetEntries mmethod returns Directories
@@ -200,43 +200,45 @@ namespace System.IO.Tests
}
}
- [Fact]
+ [Theory,
+ MemberData(nameof(WindowsInvalidUnixValid))]
[PlatformSpecific(TestPlatforms.Windows)] // Windows-only Invalid chars in path
- public void WindowsInvalidCharsPath()
+ public void WindowsInvalidCharsPath(string invalid)
{
- Assert.All(WindowsInvalidUnixValid, invalid =>
- Assert.Throws<ArgumentException>(() => GetEntries(invalid)));
+
+ Assert.Throws<ArgumentException>(() => GetEntries(invalid));
}
- [Fact]
+ [Theory,
+ MemberData(nameof(WindowsInvalidUnixValid))]
[PlatformSpecific(TestPlatforms.AnyUnix)] // Unix-only valid chars in file path
- public void UnixValidCharsFilePath()
+ public void UnixValidCharsFilePath(string valid)
{
if (TestFiles)
{
DirectoryInfo testDir = Directory.CreateDirectory(GetTestFilePath());
- foreach (string valid in WindowsInvalidUnixValid)
- File.Create(Path.Combine(testDir.FullName, valid)).Dispose();
+
+ File.Create(Path.Combine(testDir.FullName, valid)).Dispose();
string[] results = GetEntries(testDir.FullName);
- Assert.All(WindowsInvalidUnixValid, valid =>
- Assert.Contains(Path.Combine(testDir.FullName, valid), results));
+ Assert.Contains(Path.Combine(testDir.FullName, valid), results);
}
}
- [Fact]
+ [Theory,
+ MemberData(nameof(WindowsInvalidUnixValid))]
[PlatformSpecific(TestPlatforms.AnyUnix)] // Windows-only invalid chars in directory path
- public void UnixValidCharsDirectoryPath()
+ public void UnixValidCharsDirectoryPath(string valid)
{
if (TestDirectories)
{
DirectoryInfo testDir = Directory.CreateDirectory(GetTestFilePath());
- foreach (string valid in WindowsInvalidUnixValid)
- testDir.CreateSubdirectory(valid);
+
+ testDir.CreateSubdirectory(valid);
string[] results = GetEntries(testDir.FullName);
- Assert.All(WindowsInvalidUnixValid, valid =>
- Assert.Contains(Path.Combine(testDir.FullName, valid), results));
+
+ Assert.Contains(Path.Combine(testDir.FullName, valid), results);
}
}
diff --git a/src/System.IO.FileSystem/tests/Directory/GetFileSystemEntries_str_str.cs b/src/System.IO.FileSystem/tests/Directory/GetFileSystemEntries_str_str.cs
index 05913dd4b3..3c61204a61 100644
--- a/src/System.IO.FileSystem/tests/Directory/GetFileSystemEntries_str_str.cs
+++ b/src/System.IO.FileSystem/tests/Directory/GetFileSystemEntries_str_str.cs
@@ -607,14 +607,25 @@ namespace System.IO.Tests
}
[Fact]
- [PlatformSpecific(TestPlatforms.Windows)] // Long path segment in search pattern throws PathTooLongException
+ [PlatformSpecific(TestPlatforms.Windows)]
public void WindowsSearchPatternLongSegment()
{
// Create a path segment longer than the normal max of 255
DirectoryInfo testDir = Directory.CreateDirectory(GetTestFilePath());
string longName = new string('k', 257);
-
- Assert.Throws<PathTooLongException>(() => GetEntries(testDir.FullName, longName));
+
+ // Long path segment in search pattern throws PathTooLongException on Desktop,
+ // otherwise it is an IOException.
+ if (PlatformDetection.IsFullFramework)
+ {
+ Assert.Throws<PathTooLongException>(() => GetEntries(testDir.FullName, longName));
+ }
+ else
+ {
+ var exception = Assert.Throws<IOException>(() => GetEntries(testDir.FullName, longName));
+ // Should be Interop.Errors.ERROR_INVALID_PARAMETER converted to a HResult
+ Assert.Equal(unchecked((int)0x80070057), exception.HResult);
+ }
}
[ConditionalFact(nameof(AreAllLongPathsAvailable))]
@@ -801,33 +812,32 @@ namespace System.IO.Tests
}
}
- [Fact]
+ [Theory,
+ MemberData(nameof(WindowsInvalidUnixValid))]
[PlatformSpecific(TestPlatforms.AnyUnix)] // Unix-valid chars in file search patterns
- public void UnixSearchPatternFileValidChar()
+ public void UnixSearchPatternFileValidChar(string valid)
{
if (TestFiles)
{
DirectoryInfo testDir = Directory.CreateDirectory(GetTestFilePath());
- foreach (string valid in WindowsInvalidUnixValid)
- File.Create(Path.Combine(testDir.FullName, valid)).Dispose();
+ File.Create(Path.Combine(testDir.FullName, valid)).Dispose();
- foreach (string valid in WindowsInvalidUnixValid)
- Assert.Contains(Path.Combine(testDir.FullName, valid), GetEntries(testDir.FullName, valid));
+ Assert.Contains(Path.Combine(testDir.FullName, valid), GetEntries(testDir.FullName, valid));
}
}
- [Fact]
+ [Theory,
+ MemberData(nameof(WindowsInvalidUnixValid))]
[PlatformSpecific(TestPlatforms.AnyUnix)] // Unix-valid chars in directory search patterns
- public void UnixSearchPatternDirectoryValidChar()
+ public void UnixSearchPatternDirectoryValidChar(string valid)
{
if (TestDirectories)
{
DirectoryInfo testDir = Directory.CreateDirectory(GetTestFilePath());
- foreach (string valid in WindowsInvalidUnixValid)
- testDir.CreateSubdirectory(valid);
- foreach (string valid in WindowsInvalidUnixValid)
- Assert.Contains(Path.Combine(testDir.FullName, valid), GetEntries(testDir.FullName, valid));
+ testDir.CreateSubdirectory(valid);
+
+ Assert.Contains(Path.Combine(testDir.FullName, valid), GetEntries(testDir.FullName, valid));
}
}
diff --git a/src/System.IO.FileSystem/tests/DirectoryInfo/CreateSubdirectory.cs b/src/System.IO.FileSystem/tests/DirectoryInfo/CreateSubdirectory.cs
index e777626d47..a8484a4dfd 100644
--- a/src/System.IO.FileSystem/tests/DirectoryInfo/CreateSubdirectory.cs
+++ b/src/System.IO.FileSystem/tests/DirectoryInfo/CreateSubdirectory.cs
@@ -8,6 +8,7 @@ namespace System.IO.Tests
{
public class DirectoryInfo_CreateSubDirectory : FileSystemTest
{
+ public static TheoryData ControlWhiteSpace = IOInputs.GetControlWhiteSpace().ToTheoryData();
#region UniversalTests
[Fact]
@@ -89,36 +90,31 @@ namespace System.IO.Tests
Assert.Throws<ArgumentException>(() => new DirectoryInfo(TestDirectory + "/path").CreateSubdirectory("../../path2"));
}
- [Fact]
- public void ValidPathWithTrailingSlash()
+ [Theory,
+ MemberData(nameof(ValidPathComponentNames))]
+ public void ValidPathWithTrailingSlash(string component)
{
DirectoryInfo testDir = Directory.CreateDirectory(GetTestFilePath());
- var components = IOInputs.GetValidPathComponentNames();
- Assert.All(components, (component) =>
- {
- string path = IOServices.AddTrailingSlashIfNeeded(component);
- DirectoryInfo result = new DirectoryInfo(testDir.FullName).CreateSubdirectory(path);
+ string path = IOServices.AddTrailingSlashIfNeeded(component);
+ DirectoryInfo result = new DirectoryInfo(testDir.FullName).CreateSubdirectory(path);
- Assert.Equal(Path.Combine(testDir.FullName, path), result.FullName);
- Assert.True(Directory.Exists(result.FullName));
- });
+ Assert.Equal(Path.Combine(testDir.FullName, path), result.FullName);
+ Assert.True(Directory.Exists(result.FullName));
}
- [Fact]
- public void ValidPathWithoutTrailingSlash()
+ [Theory,
+ MemberData(nameof(ValidPathComponentNames))]
+ public void ValidPathWithoutTrailingSlash(string component)
{
DirectoryInfo testDir = Directory.CreateDirectory(GetTestFilePath());
- var components = IOInputs.GetValidPathComponentNames();
- Assert.All(components, (component) =>
- {
- string path = component;
- DirectoryInfo result = new DirectoryInfo(testDir.FullName).CreateSubdirectory(path);
+ string path = component;
+ DirectoryInfo result = new DirectoryInfo(testDir.FullName).CreateSubdirectory(path);
+
+ Assert.Equal(Path.Combine(testDir.FullName, path), result.FullName);
+ Assert.True(Directory.Exists(result.FullName));
- Assert.Equal(Path.Combine(testDir.FullName, path), result.FullName);
- Assert.True(Directory.Exists(result.FullName));
- });
}
[Fact]
@@ -143,65 +139,54 @@ namespace System.IO.Tests
#region PlatformSpecific
- [Fact]
+ [Theory,
+ MemberData(nameof(ControlWhiteSpace))]
[PlatformSpecific(TestPlatforms.Windows)] // Control whitespace in path throws ArgumentException
- public void WindowsControlWhiteSpace()
+ public void WindowsControlWhiteSpace(string component)
{
// CreateSubdirectory will throw when passed a path with control whitespace e.g. "\t"
- var components = IOInputs.GetControlWhiteSpace();
- Assert.All(components, (component) =>
- {
- string path = IOServices.RemoveTrailingSlash(GetTestFileName());
- Assert.Throws<ArgumentException>(() => new DirectoryInfo(TestDirectory).CreateSubdirectory(component));
- });
+ string path = IOServices.RemoveTrailingSlash(GetTestFileName());
+ Assert.Throws<ArgumentException>(() => new DirectoryInfo(TestDirectory).CreateSubdirectory(component));
}
- [Fact]
+ [Theory,
+ MemberData(nameof(SimpleWhiteSpace))]
[PlatformSpecific(TestPlatforms.Windows)] // Simple whitespace is trimmed in path
- public void WindowsSimpleWhiteSpace()
+ public void WindowsSimpleWhiteSpace(string component)
{
// CreateSubdirectory trims all simple whitespace, returning us the parent directory
// that called CreateSubdirectory
- var components = IOInputs.GetSimpleWhiteSpace();
+ string path = IOServices.RemoveTrailingSlash(GetTestFileName());
+ DirectoryInfo result = new DirectoryInfo(TestDirectory).CreateSubdirectory(component);
- Assert.All(components, (component) =>
- {
- string path = IOServices.RemoveTrailingSlash(GetTestFileName());
- DirectoryInfo result = new DirectoryInfo(TestDirectory).CreateSubdirectory(component);
+ Assert.True(Directory.Exists(result.FullName));
+ Assert.Equal(TestDirectory, IOServices.RemoveTrailingSlash(result.FullName));
- Assert.True(Directory.Exists(result.FullName));
- Assert.Equal(TestDirectory, IOServices.RemoveTrailingSlash(result.FullName));
- });
}
- [Fact]
+ [Theory,
+ MemberData(nameof(WhiteSpace))]
[PlatformSpecific(TestPlatforms.AnyUnix)] // Whitespace as path allowed
- public void UnixWhiteSpaceAsPath_Allowed()
+ public void UnixWhiteSpaceAsPath_Allowed(string path)
{
- var paths = IOInputs.GetWhiteSpace();
- Assert.All(paths, (path) =>
- {
- new DirectoryInfo(TestDirectory).CreateSubdirectory(path);
- Assert.True(Directory.Exists(Path.Combine(TestDirectory, path)));
- });
+ new DirectoryInfo(TestDirectory).CreateSubdirectory(path);
+ Assert.True(Directory.Exists(Path.Combine(TestDirectory, path)));
+
}
- [Fact]
+ [Theory,
+ MemberData(nameof(WhiteSpace))]
[PlatformSpecific(TestPlatforms.AnyUnix)] // Trailing whitespace in path treated as significant
- public void UnixNonSignificantTrailingWhiteSpace()
+ public void UnixNonSignificantTrailingWhiteSpace(string component)
{
// Unix treats trailing/prename whitespace as significant and a part of the name.
DirectoryInfo testDir = Directory.CreateDirectory(GetTestFilePath());
- var components = IOInputs.GetWhiteSpace();
- Assert.All(components, (component) =>
- {
- string path = IOServices.RemoveTrailingSlash(testDir.Name) + component;
- DirectoryInfo result = new DirectoryInfo(TestDirectory).CreateSubdirectory(path);
+ string path = IOServices.RemoveTrailingSlash(testDir.Name) + component;
+ DirectoryInfo result = new DirectoryInfo(TestDirectory).CreateSubdirectory(path);
- Assert.True(Directory.Exists(result.FullName));
- Assert.NotEqual(testDir.FullName, IOServices.RemoveTrailingSlash(result.FullName));
- });
+ Assert.True(Directory.Exists(result.FullName));
+ Assert.NotEqual(testDir.FullName, IOServices.RemoveTrailingSlash(result.FullName));
}
[ConditionalFact(nameof(UsingNewNormalization))]
diff --git a/src/System.IO.FileSystem/tests/File/Copy.cs b/src/System.IO.FileSystem/tests/File/Copy.cs
index 8c69e076f6..5f567f967c 100644
--- a/src/System.IO.FileSystem/tests/File/Copy.cs
+++ b/src/System.IO.FileSystem/tests/File/Copy.cs
@@ -13,7 +13,7 @@ namespace System.IO.Tests
{
#region Utilities
- public static string[] WindowsInvalidUnixValid = new string[] { " ", " ", "\n", ">", "<", "\t" };
+ public static TheoryData WindowsInvalidUnixValid = new TheoryData<string> { " ", " ", "\n", ">", "<", "\t" };
public virtual void Copy(string source, string dest)
{
File.Copy(source, dest);
@@ -160,31 +160,29 @@ namespace System.IO.Tests
#region PlatformSpecific
- [Fact]
+ [Theory,
+ MemberData(nameof(WindowsInvalidUnixValid))]
[PlatformSpecific(TestPlatforms.Windows)] // Whitespace path throws ArgumentException
- public void WindowsWhitespacePath()
+ public void WindowsWhitespacePath(string invalid)
{
string testFile = GetTestFilePath();
File.Create(testFile).Dispose();
- foreach (string invalid in WindowsInvalidUnixValid)
- {
- Assert.Throws<ArgumentException>(() => Copy(testFile, invalid));
- Assert.Throws<ArgumentException>(() => Copy(invalid, testFile));
- }
+
+ Assert.Throws<ArgumentException>(() => Copy(testFile, invalid));
+ Assert.Throws<ArgumentException>(() => Copy(invalid, testFile));
}
- [Fact]
+ [Theory,
+ MemberData(nameof(WindowsInvalidUnixValid))]
[PlatformSpecific(TestPlatforms.AnyUnix)] // Whitespace path allowed
- public void UnixWhitespacePath()
+ public void UnixWhitespacePath(string valid)
{
string testFile = GetTestFilePath();
File.Create(testFile).Dispose();
- foreach (string valid in WindowsInvalidUnixValid)
- {
- Copy(testFile, Path.Combine(TestDirectory, valid));
- Assert.True(File.Exists(testFile));
- Assert.True(File.Exists(Path.Combine(TestDirectory, valid)));
- }
+
+ Copy(testFile, Path.Combine(TestDirectory, valid));
+ Assert.True(File.Exists(testFile));
+ Assert.True(File.Exists(Path.Combine(TestDirectory, valid)));
}
#endregion
diff --git a/src/System.IO.FileSystem/tests/File/Create.cs b/src/System.IO.FileSystem/tests/File/Create.cs
index 0083e6163e..d287467923 100644
--- a/src/System.IO.FileSystem/tests/File/Create.cs
+++ b/src/System.IO.FileSystem/tests/File/Create.cs
@@ -207,38 +207,41 @@ namespace System.IO.Tests
Assert.Throws<ArgumentException>(() => Create(Path.Combine(testDir.FullName, "*Tes*t")));
}
- [Fact]
+ [Theory,
+ InlineData(" "),
+ InlineData(" "),
+ InlineData("\n"),
+ InlineData(">"),
+ InlineData("<"),
+ InlineData("\0"),
+ InlineData("\t")]
[PlatformSpecific(TestPlatforms.Windows)] // Invalid file name with whitespace on Windows
- public void WindowsWhitespacePath()
+ public void WindowsWhitespacePath(string path)
{
- Assert.Throws<ArgumentException>(() => Create(" "));
- Assert.Throws<ArgumentException>(() => Create(" "));
- Assert.Throws<ArgumentException>(() => Create("\n"));
- Assert.Throws<ArgumentException>(() => Create(">"));
- Assert.Throws<ArgumentException>(() => Create("<"));
- Assert.Throws<ArgumentException>(() => Create("\0"));
- Assert.Throws<ArgumentException>(() => Create("\t"));
+ Assert.Throws<ArgumentException>(() => Create(path));
}
[Fact]
+ [PlatformSpecific(TestPlatforms.AnyUnix)]
+ public void CreateNullThrows_Unix()
+ {
+ Assert.Throws<ArgumentException>(() => Create("\0"));
+ }
+
+ [Theory,
+ InlineData(" "),
+ InlineData(" "),
+ InlineData("\n"),
+ InlineData(">"),
+ InlineData("<"),
+ InlineData("\t")]
[PlatformSpecific(TestPlatforms.AnyUnix)] // Valid file name with Whitespace on Unix
- public void UnixWhitespacePath()
+ public void UnixWhitespacePath(string path)
{
DirectoryInfo testDir = Directory.CreateDirectory(GetTestFilePath());
- Assert.Throws<ArgumentException>(() => Create("\0"));
- using (Create(Path.Combine(testDir.FullName, " ")))
- using (Create(Path.Combine(testDir.FullName, " ")))
- using (Create(Path.Combine(testDir.FullName, "\n")))
- using (Create(Path.Combine(testDir.FullName, ">")))
- using (Create(Path.Combine(testDir.FullName, "<")))
- using (Create(Path.Combine(testDir.FullName, "\t")))
+ using (Create(Path.Combine(testDir.FullName, path)))
{
- Assert.True(File.Exists(Path.Combine(testDir.FullName, " ")));
- Assert.True(File.Exists(Path.Combine(testDir.FullName, " ")));
- Assert.True(File.Exists(Path.Combine(testDir.FullName, "\n")));
- Assert.True(File.Exists(Path.Combine(testDir.FullName, ">")));
- Assert.True(File.Exists(Path.Combine(testDir.FullName, "<")));
- Assert.True(File.Exists(Path.Combine(testDir.FullName, "\t")));
+ Assert.True(File.Exists(Path.Combine(testDir.FullName, path)));
}
}
diff --git a/src/System.IO.FileSystem/tests/File/Exists.cs b/src/System.IO.FileSystem/tests/File/Exists.cs
index 5b4acf26f3..c9b8be7156 100644
--- a/src/System.IO.FileSystem/tests/File/Exists.cs
+++ b/src/System.IO.FileSystem/tests/File/Exists.cs
@@ -31,25 +31,21 @@ namespace System.IO.Tests
Assert.False(Exists(string.Empty));
}
- [Fact]
- public void NonExistentValidPath_ReturnsFalse()
+ [Theory,
+ MemberData(nameof(ValidPathComponentNames))]
+ public void NonExistentValidPath_ReturnsFalse(string path)
{
- Assert.All((IOInputs.GetValidPathComponentNames()), (path) =>
- {
- Assert.False(Exists(path), path);
- });
+ Assert.False(Exists(path), path);
}
- [Fact]
- public void ValidPathExists_ReturnsTrue()
+ [Theory,
+ MemberData(nameof(ValidPathComponentNames))]
+ public void ValidPathExists_ReturnsTrue(string component)
{
- Assert.All((IOInputs.GetValidPathComponentNames()), (component) =>
- {
- string path = Path.Combine(TestDirectory, component);
- FileInfo testFile = new FileInfo(path);
- testFile.Create().Dispose();
- Assert.True(Exists(path));
- });
+ string path = Path.Combine(TestDirectory, component);
+ FileInfo testFile = new FileInfo(path);
+ testFile.Create().Dispose();
+ Assert.True(Exists(path));
}
[Theory, MemberData(nameof(PathsWithInvalidCharacters))]
@@ -161,15 +157,14 @@ namespace System.IO.Tests
#region PlatformSpecific
- [Fact]
+ [Theory,
+ MemberData(nameof(WhiteSpace))]
[PlatformSpecific(TestPlatforms.Windows)] // Unix equivalent tested already in CreateDirectory
- public void WindowsNonSignificantWhiteSpaceAsPath_ReturnsFalse()
+ public void WindowsNonSignificantWhiteSpaceAsPath_ReturnsFalse(string component)
{
// Checks that errors aren't thrown when calling Exists() on impossible paths
- Assert.All((IOInputs.GetWhiteSpace()), (component) =>
- {
- Assert.False(Exists(component));
- });
+ Assert.False(Exists(component));
+
}
[Fact]
@@ -194,56 +189,48 @@ namespace System.IO.Tests
Assert.False(Exists(testFile.FullName.ToLowerInvariant()));
}
- [Fact]
+ [Theory,
+ MemberData(nameof(WhiteSpace))]
[PlatformSpecific(TestPlatforms.Windows)] // In Windows, trailing whitespace in a path is trimmed
- public void TrimTrailingWhitespacePath()
+ public void TrimTrailingWhitespacePath(string component)
{
FileInfo testFile = new FileInfo(GetTestFilePath());
testFile.Create().Dispose();
- Assert.All((IOInputs.GetWhiteSpace()), (component) =>
- {
- Assert.True(Exists(testFile.FullName + component)); // string concat in case Path.Combine() trims whitespace before Exists gets to it
- });
+
+ Assert.True(Exists(testFile.FullName + component)); // string concat in case Path.Combine() trims whitespace before Exists gets to it
+
}
- [Fact]
+ [Theory,
+ MemberData(nameof(PathsWithAlternativeDataStreams))]
[PlatformSpecific(TestPlatforms.Windows)] // alternate data stream
- public void PathWithAlternateDataStreams_ReturnsFalse()
+ public void PathWithAlternateDataStreams_ReturnsFalse(string component)
{
- Assert.All((IOInputs.GetPathsWithAlternativeDataStreams()), (component) =>
- {
- Assert.False(Exists(component));
- });
+ Assert.False(Exists(component));
}
- [Fact]
+ [Theory,
+ MemberData(nameof(PathsWithReservedDeviceNames))]
[OuterLoop]
[PlatformSpecific(TestPlatforms.Windows)] // device names
- public void PathWithReservedDeviceNameAsPath_ReturnsFalse()
+ public void PathWithReservedDeviceNameAsPath_ReturnsFalse(string component)
{
- Assert.All((IOInputs.GetPathsWithReservedDeviceNames()), (component) =>
- {
- Assert.False(Exists(component));
- });
+ Assert.False(Exists(component));
}
- [Fact]
- public void UncPathWithoutShareNameAsPath_ReturnsFalse()
+ [Theory,
+ MemberData(nameof(UncPathsWithoutShareName))]
+ public void UncPathWithoutShareNameAsPath_ReturnsFalse(string component)
{
- Assert.All((IOInputs.GetUncPathsWithoutShareName()), (component) =>
- {
- Assert.False(Exists(component));
- });
+ Assert.False(Exists(component));
}
- [Fact]
+ [Theory,
+ MemberData(nameof(PathsWithComponentLongerThanMaxComponent))]
[PlatformSpecific(TestPlatforms.Windows)] // max directory length not fixed on Unix
- public void DirectoryWithComponentLongerThanMaxComponentAsPath_ReturnsFalse()
+ public void DirectoryWithComponentLongerThanMaxComponentAsPath_ReturnsFalse(string component)
{
- Assert.All((IOInputs.GetPathsWithComponentLongerThanMaxComponent()), (component) =>
- {
- Assert.False(Exists(component));
- });
+ Assert.False(Exists(component));
}
[Fact]
diff --git a/src/System.IO.FileSystem/tests/File/Move.cs b/src/System.IO.FileSystem/tests/File/Move.cs
index c59b65ea04..2f467c8cd1 100644
--- a/src/System.IO.FileSystem/tests/File/Move.cs
+++ b/src/System.IO.FileSystem/tests/File/Move.cs
@@ -269,28 +269,26 @@ namespace System.IO.Tests
Assert.True(File.Exists(testFileShouldntMove));
}
- [Fact]
+ [Theory,
+ MemberData(nameof(WhiteSpace))]
[PlatformSpecific(TestPlatforms.Windows)] // Whitespace in path throws ArgumentException
- public void WindowsWhitespacePath()
+ public void WindowsWhitespacePath(string whitespace)
{
FileInfo testFile = new FileInfo(GetTestFilePath());
- Assert.All(IOInputs.GetWhiteSpace(), (whitespace) =>
- {
- Assert.Throws<ArgumentException>(() => Move(testFile.FullName, whitespace));
- });
+ Assert.Throws<ArgumentException>(() => Move(testFile.FullName, whitespace));
}
- [Fact]
+ [Theory,
+ MemberData(nameof(WhiteSpace))]
[PlatformSpecific(TestPlatforms.AnyUnix)] // Whitespace in path allowed
- public void UnixWhitespacePath()
+ public void UnixWhitespacePath(string whitespace)
{
FileInfo testFileSource = new FileInfo(GetTestFilePath());
testFileSource.Create().Dispose();
- Assert.All(IOInputs.GetWhiteSpace(), (whitespace) =>
- {
- Move(testFileSource.FullName, Path.Combine(TestDirectory, whitespace));
- Move(Path.Combine(TestDirectory, whitespace), testFileSource.FullName);
- });
+
+ Move(testFileSource.FullName, Path.Combine(TestDirectory, whitespace));
+ Move(Path.Combine(TestDirectory, whitespace), testFileSource.FullName);
+
}
#endregion
diff --git a/src/System.IO.FileSystem/tests/FileSystemTest.cs b/src/System.IO.FileSystem/tests/FileSystemTest.cs
index d74d2a21cf..3c3abc4926 100644
--- a/src/System.IO.FileSystem/tests/FileSystemTest.cs
+++ b/src/System.IO.FileSystem/tests/FileSystemTest.cs
@@ -24,6 +24,12 @@ namespace System.IO.Tests
public static TheoryData<string> PathsWithInvalidCharacters = TestData.PathsWithInvalidCharacters;
public static TheoryData<char> TrailingCharacters = TestData.TrailingCharacters;
public static TheoryData ValidPathComponentNames = IOInputs.GetValidPathComponentNames().ToTheoryData();
+ public static TheoryData SimpleWhiteSpace = IOInputs.GetSimpleWhiteSpace().ToTheoryData();
+ public static TheoryData WhiteSpace = IOInputs.GetWhiteSpace().ToTheoryData();
+ public static TheoryData UncPathsWithoutShareName = IOInputs.GetUncPathsWithoutShareName().ToTheoryData();
+ public static TheoryData PathsWithReservedDeviceNames = IOInputs.GetPathsWithReservedDeviceNames().ToTheoryData();
+ public static TheoryData PathsWithAlternativeDataStreams = IOInputs.GetPathsWithAlternativeDataStreams().ToTheoryData();
+ public static TheoryData PathsWithComponentLongerThanMaxComponent = IOInputs.GetPathsWithComponentLongerThanMaxComponent().ToTheoryData();
/// <summary>
/// In some cases (such as when running without elevated privileges),
@@ -66,7 +72,7 @@ namespace System.IO.Tests
using (Process process = Process.Start(startInfo))
{
- Assert.True(process.WaitForExit(3000));
+ Assert.True(process.WaitForExit(30000));
return process.ExitCode;
}
}
diff --git a/src/System.IO.FileSystem/tests/PortedCommon/IOInputs.cs b/src/System.IO.FileSystem/tests/PortedCommon/IOInputs.cs
index 7499de7aac..0e265b644b 100644
--- a/src/System.IO.FileSystem/tests/PortedCommon/IOInputs.cs
+++ b/src/System.IO.FileSystem/tests/PortedCommon/IOInputs.cs
@@ -16,6 +16,9 @@ internal static class IOInputs
// Max path length (minus trailing \0). Unix values vary system to system; just using really long values here likely to be more than on the average system.
public static readonly int MaxPath = RuntimeInformation.IsOSPlatform(OSPlatform.Windows) ? 259 : 10000;
+ // Windows specific, this is the maximum length that can be passed using extended syntax. Does not include the trailing \0.
+ public static readonly int MaxExtendedPath = short.MaxValue - 1;
+
// Same as MaxPath on Unix
public static readonly int MaxLongPath = RuntimeInformation.IsOSPlatform(OSPlatform.Windows) ? MaxExtendedPath : MaxPath;
@@ -23,11 +26,7 @@ internal static class IOInputs
// Does not include the trailing \0.
// We now do the appropriate wrapping to allow creating longer directories. Like MaxPath, this is a legacy restriction.
public static readonly int MaxDirectory = 247;
-
- // Windows specific, this is the maximum length that can be passed using extended syntax. Does not include the trailing \0.
- public static readonly int MaxExtendedPath = short.MaxValue - 1;
-
-
+
public const int MaxComponent = 255;
public const string ExtendedPrefix = @"\\?\";
@@ -149,13 +148,13 @@ internal static class IOInputs
string component = new string('s', MaxComponent + 1);
- yield return String.Format(@"C:\{0}", component);
- yield return String.Format(@"C:\{0}\Filename.txt", component);
- yield return String.Format(@"C:\{0}\Filename.txt\", component);
- yield return String.Format(@"\\{0}\Share", component);
- yield return String.Format(@"\\LOCALHOST\{0}", component);
- yield return String.Format(@"\\LOCALHOST\{0}\FileName.txt", component);
- yield return String.Format(@"\\LOCALHOST\Share\{0}", component);
+ yield return string.Format(@"C:\{0}", component);
+ yield return string.Format(@"C:\{0}\Filename.txt", component);
+ yield return string.Format(@"C:\{0}\Filename.txt\", component);
+ yield return string.Format(@"\\{0}\Share", component);
+ yield return string.Format(@"\\LOCALHOST\{0}", component);
+ yield return string.Format(@"\\LOCALHOST\{0}\FileName.txt", component);
+ yield return string.Format(@"\\LOCALHOST\Share\{0}", component);
}
public static IEnumerable<string> GetPathsLongerThanMaxDirectory(string rootPath)
diff --git a/src/System.IO.FileSystem/tests/System.IO.FileSystem.Tests.csproj b/src/System.IO.FileSystem/tests/System.IO.FileSystem.Tests.csproj
index b57b70ef61..0f878bfa16 100644
--- a/src/System.IO.FileSystem/tests/System.IO.FileSystem.Tests.csproj
+++ b/src/System.IO.FileSystem/tests/System.IO.FileSystem.Tests.csproj
@@ -168,9 +168,6 @@
<Compile Include="$(CommonTestPath)\System\PlatformDetection.cs">
<Link>Common\System\PlatformDetection.cs</Link>
</Compile>
- <Compile Include="$(CommonTestPath)\System\AssertExtensions.cs">
- <Link>Common\System\AssertExtensions.cs</Link>
- </Compile>
<ProjectReference Include="$(CommonTestPath)\System\Diagnostics\RemoteExecutorConsoleApp\RemoteExecutorConsoleApp.csproj">
<Project>{69e46a6f-9966-45a5-8945-2559fe337827}</Project>
<Name>RemoteExecutorConsoleApp</Name>
diff --git a/src/System.IO.IsolatedStorage/tests/System.IO.IsolatedStorage.Tests.csproj b/src/System.IO.IsolatedStorage/tests/System.IO.IsolatedStorage.Tests.csproj
index aad7f57330..09c047a542 100644
--- a/src/System.IO.IsolatedStorage/tests/System.IO.IsolatedStorage.Tests.csproj
+++ b/src/System.IO.IsolatedStorage/tests/System.IO.IsolatedStorage.Tests.csproj
@@ -41,9 +41,6 @@
</Compile>
</ItemGroup>
<ItemGroup>
- <Compile Include="$(CommonTestPath)\System\AssertExtensions.cs">
- <Link>Common\System\AssertExtensions.cs</Link>
- </Compile>
<Compile Include="$(CommonTestPath)\System\IO\TempDirectory.cs">
<Link>Common\System\IO\TempDirectory.cs</Link>
</Compile>
diff --git a/src/System.IO.MemoryMappedFiles/tests/System.IO.MemoryMappedFiles.Tests.csproj b/src/System.IO.MemoryMappedFiles/tests/System.IO.MemoryMappedFiles.Tests.csproj
index a18106f2fb..272fbf3c64 100644
--- a/src/System.IO.MemoryMappedFiles/tests/System.IO.MemoryMappedFiles.Tests.csproj
+++ b/src/System.IO.MemoryMappedFiles/tests/System.IO.MemoryMappedFiles.Tests.csproj
@@ -26,9 +26,6 @@
<Compile Include="$(CommonTestPath)\System\IO\TempFile.cs">
<Link>Common\System\IO\TempFile.cs</Link>
</Compile>
- <Compile Include="$(CommonTestPath)\System\AssertExtensions.cs">
- <Link>Common\System\AssertExtensions.cs</Link>
- </Compile>
<Compile Include="$(CommonTestPath)\System\PlatformDetection.cs">
<Link>Common\System\PlatformDetection.cs</Link>
</Compile>
diff --git a/src/System.IO.Packaging/src/System.IO.Packaging.csproj b/src/System.IO.Packaging/src/System.IO.Packaging.csproj
index f30527a9e7..df0b4051c0 100644
--- a/src/System.IO.Packaging/src/System.IO.Packaging.csproj
+++ b/src/System.IO.Packaging/src/System.IO.Packaging.csproj
@@ -7,8 +7,8 @@
<AssemblyName>System.IO.Packaging</AssemblyName>
<AllowUnsafeBlocks>true</AllowUnsafeBlocks>
<IsPartialFacadeAssembly Condition="'$(TargetGroup)'=='netfx' OR '$(TargetGroup)'=='net46'">true</IsPartialFacadeAssembly>
- <!-- UAP10.1 is not yet mapped to netstandard2.0, manually duplicate this ref -->
- <PackageTargetFramework Condition="'$(TargetGroup)' == 'netstandard'">netstandard2.0;uap10.1</PackageTargetFramework>
+ <!-- UAPvNext is not yet mapped to netstandard2.0, manually duplicate this ref -->
+ <PackageTargetFramework Condition="'$(TargetGroup)' == 'netstandard'">netstandard2.0;$(UAPvNextTFM)</PackageTargetFramework>
</PropertyGroup>
<!-- Default configurations to help VS understand the options -->
<PropertyGroup Condition="'$(Configuration)|$(Platform)' == 'net46-Debug|AnyCPU'" />
@@ -20,7 +20,7 @@
<PropertyGroup Condition="'$(Configuration)|$(Platform)' == 'netstandard1.3-Debug|AnyCPU'" />
<PropertyGroup Condition="'$(Configuration)|$(Platform)' == 'netstandard1.3-Release|AnyCPU'" />
<ItemGroup Condition="'$(TargetGroup)' == 'netstandard'">
- <SuppressPackageTargetFrameworkCompatibility Include="uap10.1" />
+ <SuppressPackageTargetFrameworkCompatibility Include="$(UAPvNextTFM)" />
</ItemGroup>
<ItemGroup Condition="'$(TargetGroup)'=='netstandard1.3'">
<Reference Include="System.Collections" />
diff --git a/src/System.IO.Packaging/tests/System.IO.Packaging.Tests.csproj b/src/System.IO.Packaging/tests/System.IO.Packaging.Tests.csproj
index 84ffe56008..e2a2ecbbe0 100644
--- a/src/System.IO.Packaging/tests/System.IO.Packaging.Tests.csproj
+++ b/src/System.IO.Packaging/tests/System.IO.Packaging.Tests.csproj
@@ -8,9 +8,6 @@
<PropertyGroup Condition="'$(Configuration)|$(Platform)' == 'netstandard-Release|AnyCPU'" />
<ItemGroup>
<Compile Include="Tests.cs" />
- <Compile Include="$(CommonTestPath)\System\AssertExtensions.cs">
- <Link>Common\System\AssertExtensions.cs</Link>
- </Compile>
</ItemGroup>
<ItemGroup>
<SupplementalTestData Include="$(PackagesDir)system.io.packaging.testdata\1.0.0-prerelease\content\**\*.*" />
diff --git a/src/System.IO.Pipes/tests/System.IO.Pipes.Tests.csproj b/src/System.IO.Pipes/tests/System.IO.Pipes.Tests.csproj
index 33fc1ef8a1..1c8c200b42 100644
--- a/src/System.IO.Pipes/tests/System.IO.Pipes.Tests.csproj
+++ b/src/System.IO.Pipes/tests/System.IO.Pipes.Tests.csproj
@@ -33,9 +33,6 @@
<Compile Include="PipeTest.Read.cs" />
<Compile Include="PipeTest.Write.cs" />
<Compile Include="XunitAssemblyAttributes.cs" />
- <Compile Include="$(CommonTestPath)\System\AssertExtensions.cs">
- <Link>Common\System\AssertExtensions.cs</Link>
- </Compile>
<Compile Include="$(CommonTestPath)\System\PlatformDetection.cs">
<Link>Common\System\PlatformDetection.cs</Link>
</Compile>
diff --git a/src/System.IO.Ports/tests/System.IO.Ports.Tests.csproj b/src/System.IO.Ports/tests/System.IO.Ports.Tests.csproj
index e10d9f2ac5..f0412cb9ab 100644
--- a/src/System.IO.Ports/tests/System.IO.Ports.Tests.csproj
+++ b/src/System.IO.Ports/tests/System.IO.Ports.Tests.csproj
@@ -118,9 +118,6 @@
<Compile Include="Support\TCSupport.cs" />
<Compile Include="Support\PortsTest.cs" />
<Compile Include="Support\TestEventHandler.cs" />
- <Compile Include="$(CommonTestPath)\System\AssertExtensions.cs">
- <Link>Common\System\AssertExtensions.cs</Link>
- </Compile>
<Compile Include="$(CommonTestPath)\System\PlatformDetection.cs">
<Link>CommonTest\System\PlatformDetection.cs</Link>
</Compile>
diff --git a/src/System.IO.UnmanagedMemoryStream/tests/System.IO.UnmanagedMemoryStream.Tests.csproj b/src/System.IO.UnmanagedMemoryStream/tests/System.IO.UnmanagedMemoryStream.Tests.csproj
index effa092477..935064fd8b 100644
--- a/src/System.IO.UnmanagedMemoryStream/tests/System.IO.UnmanagedMemoryStream.Tests.csproj
+++ b/src/System.IO.UnmanagedMemoryStream/tests/System.IO.UnmanagedMemoryStream.Tests.csproj
@@ -26,9 +26,6 @@
<Compile Include="UmsTests.cs" />
<Compile Include="UmsManager.cs" />
<Compile Include="UmsSecurityTest.cs" />
- <Compile Include="$(CommonTestPath)\System\AssertExtensions.cs">
- <Link>Common\System\AssertExtensions.cs</Link>
- </Compile>
</ItemGroup>
<Import Project="$([MSBuild]::GetDirectoryNameOfFileAbove($(MSBuildThisFileDirectory), dir.targets))\dir.targets" />
</Project> \ No newline at end of file
diff --git a/src/System.IO.UnmanagedMemoryStream/tests/Uma.ReadWriteStructArray.cs b/src/System.IO.UnmanagedMemoryStream/tests/Uma.ReadWriteStructArray.cs
index 09470cd4ce..52c9b2ea8a 100644
--- a/src/System.IO.UnmanagedMemoryStream/tests/Uma.ReadWriteStructArray.cs
+++ b/src/System.IO.UnmanagedMemoryStream/tests/Uma.ReadWriteStructArray.cs
@@ -10,7 +10,6 @@ namespace System.IO.Tests
public class Uma_ReadWriteStructArray : Uma_TestStructs
{
[Fact]
- [ActiveIssue("https://github.com/dotnet/corefx/issues/20522", TargetFrameworkMonikers.UapAot)]
public static void UmaReadWriteStructArray_InvalidParameters()
{
const int capacity = 100;
diff --git a/src/System.IO/tests/BufferedStream/BufferedStreamTests.cs b/src/System.IO/tests/BufferedStream/BufferedStreamTests.cs
index 2fc5972261..b8a9cf44f0 100644
--- a/src/System.IO/tests/BufferedStream/BufferedStreamTests.cs
+++ b/src/System.IO/tests/BufferedStream/BufferedStreamTests.cs
@@ -113,6 +113,20 @@ namespace System.IO.Tests
{
return new BufferedStream(new MemoryStream(), bufferSize);
}
+
+ [Fact]
+ public void ReadByte_ThenRead_EndOfStreamCorrectlyFound()
+ {
+ using (var s = new BufferedStream(new MemoryStream(new byte[] { 1, 2 }), 2))
+ {
+ Assert.Equal(1, s.ReadByte());
+ Assert.Equal(2, s.ReadByte());
+ Assert.Equal(-1, s.ReadByte());
+
+ Assert.Equal(0, s.Read(new byte[1], 0, 1));
+ Assert.Equal(0, s.Read(new byte[1], 0, 1));
+ }
+ }
}
public class BufferedStream_TestLeaveOpen : TestLeaveOpen
diff --git a/src/System.IO/tests/Resources/System.IO.Tests.rd.xml b/src/System.IO/tests/Resources/System.IO.Tests.rd.xml
new file mode 100644
index 0000000000..ba20e5f275
--- /dev/null
+++ b/src/System.IO/tests/Resources/System.IO.Tests.rd.xml
@@ -0,0 +1,6 @@
+<Directives xmlns="http://schemas.microsoft.com/netfx/2013/01/metadata">
+ <Library>
+ <!-- Needed because of theory data which causes xunit to reflect on its ToString() -->
+ <Type Name="System.Text.UTF32Encoding" Dynamic="Required Public" />
+ </Library>
+</Directives>
diff --git a/src/System.IO/tests/StreamReader/StreamReader.cs b/src/System.IO/tests/StreamReader/StreamReader.cs
index b3672f7ce4..b612a3d3ce 100644
--- a/src/System.IO/tests/StreamReader/StreamReader.cs
+++ b/src/System.IO/tests/StreamReader/StreamReader.cs
@@ -2,11 +2,13 @@
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
+using System.Collections.Generic;
+using System.Text;
using Xunit;
namespace System.IO.Tests
{
- public partial class StreamReaderTests
+ public partial class StreamReaderTests : FileCleanupTestBase
{
[Fact]
public void ObjectClosedReadLine()
@@ -41,5 +43,35 @@ namespace System.IO.Tests
Assert.NotEqual(res1, res2);
}
}
+
+ public static IEnumerable<object[]> DetectEncoding_EncodingRoundtrips_MemberData()
+ {
+ yield return new object[] { new UTF8Encoding(encoderShouldEmitUTF8Identifier:true) };
+ yield return new object[] { new UTF32Encoding(bigEndian:false, byteOrderMark:true) };
+ yield return new object[] { new UTF32Encoding(bigEndian:true, byteOrderMark:true) };
+ yield return new object[] { new UnicodeEncoding(bigEndian:false, byteOrderMark:true) };
+ yield return new object[] { new UnicodeEncoding(bigEndian:true, byteOrderMark:true) };
+ }
+
+ [Theory]
+ [MemberData(nameof(DetectEncoding_EncodingRoundtrips_MemberData))]
+ public void DetectEncoding_EncodingRoundtrips(Encoding encoding)
+ {
+ const string Text = "This is some text for testing.";
+ string path = GetTestFilePath();
+
+ using (var stream = File.OpenWrite(path))
+ using (var writer = new StreamWriter(stream, encoding))
+ {
+ writer.Write(Text);
+ }
+
+ using (var stream = File.OpenRead(path))
+ using (var reader = new StreamReader(stream, detectEncodingFromByteOrderMarks:true))
+ {
+ Assert.Equal(Text, reader.ReadToEnd());
+ Assert.Equal(encoding.EncodingName, reader.CurrentEncoding.EncodingName);
+ }
+ }
}
}
diff --git a/src/System.IO/tests/System.IO.Tests.csproj b/src/System.IO/tests/System.IO.Tests.csproj
index 2c72f0b882..c677a92cfb 100644
--- a/src/System.IO/tests/System.IO.Tests.csproj
+++ b/src/System.IO/tests/System.IO.Tests.csproj
@@ -47,9 +47,6 @@
<Compile Include="Stream\Stream.TimeoutTests.cs" />
<Compile Include="StringReader\StringReader.CtorTests.cs" />
<Compile Include="StringWriter\StringWriterTests.cs" />
- <Compile Include="$(CommonTestPath)\System\AssertExtensions.cs">
- <Link>Common\System\AssertExtensions.cs</Link>
- </Compile>
<Compile Include="$(CommonTestPath)\System\IO\CallTrackingStream.cs">
<Link>Common\System\IO\CallTrackingStream.cs</Link>
</Compile>
@@ -60,5 +57,8 @@
<Link>Common\System\IO\WrappedMemoryStream.cs</Link>
</Compile>
</ItemGroup>
+ <ItemGroup>
+ <EmbeddedResource Include="Resources\$(AssemblyName).rd.xml" />
+ </ItemGroup>
<Import Project="$([MSBuild]::GetDirectoryNameOfFileAbove($(MSBuildThisFileDirectory), dir.targets))\dir.targets" />
</Project>
diff --git a/src/System.Json/tests/System.Json.Tests.csproj b/src/System.Json/tests/System.Json.Tests.csproj
index 68a2d7653c..9656c70c54 100644
--- a/src/System.Json/tests/System.Json.Tests.csproj
+++ b/src/System.Json/tests/System.Json.Tests.csproj
@@ -13,9 +13,6 @@
<Compile Include="JsonObjectTests.cs" />
<Compile Include="JsonPrimitiveTests.cs" />
<Compile Include="JsonValueTests.cs" />
- <Compile Include="$(CommonTestPath)\System\AssertExtensions.cs">
- <Link>Common\System\AssertExtensions.cs</Link>
- </Compile>
</ItemGroup>
<Import Project="$([MSBuild]::GetDirectoryNameOfFileAbove($(MSBuildThisFileDirectory), dir.targets))\dir.targets" />
</Project> \ No newline at end of file
diff --git a/src/System.Linq.Expressions/src/Resources/System.Linq.Expressions.rd.xml b/src/System.Linq.Expressions/src/Resources/System.Linq.Expressions.rd.xml
index eb031f3972..b906d4ce6c 100644
--- a/src/System.Linq.Expressions/src/Resources/System.Linq.Expressions.rd.xml
+++ b/src/System.Linq.Expressions/src/Resources/System.Linq.Expressions.rd.xml
@@ -155,7 +155,7 @@
</Type>
</Namespace>
<Namespace Name="System.Collections.Generic">
- <Type Name="IEnumerable&lt;&gt;" Dynamic="Required">
+ <Type Name="IEnumerable&lt;&gt;">
<Method Name="GetEnumerator" Dynamic="Required"/>
</Type>
<Type Name="IEnumerator&lt;&gt;">
diff --git a/src/System.Linq.Expressions/src/System/Linq/Expressions/Interpreter/ArrayOperations.cs b/src/System.Linq.Expressions/src/System/Linq/Expressions/Interpreter/ArrayOperations.cs
index e9a10b5edf..8f04749a73 100644
--- a/src/System.Linq.Expressions/src/System/Linq/Expressions/Interpreter/ArrayOperations.cs
+++ b/src/System.Linq.Expressions/src/System/Linq/Expressions/Interpreter/ArrayOperations.cs
@@ -47,12 +47,10 @@ namespace System.Linq.Expressions.Interpreter
public override int Run(InterpretedFrame frame)
{
int length = ConvertHelper.ToInt32NoNull(frame.Pop());
- if (length < 0)
- {
- // to make behavior aligned with array creation emitted by C# compiler
- throw new OverflowException();
- }
- frame.Push(Array.CreateInstance(_elementType, length));
+ // To make behavior aligned with array creation emitted by C# compiler if length is less than
+ // zero we try to use it to create an array, which will throw an OverflowException with the
+ // correct localized error message.
+ frame.Push(length < 0 ? new int[length] : Array.CreateInstance(_elementType, length));
return 1;
}
}
diff --git a/src/System.Linq.Expressions/tests/Array/NewArrayBoundsTests.cs b/src/System.Linq.Expressions/tests/Array/NewArrayBoundsTests.cs
index 190366fc67..50d61b632d 100644
--- a/src/System.Linq.Expressions/tests/Array/NewArrayBoundsTests.cs
+++ b/src/System.Linq.Expressions/tests/Array/NewArrayBoundsTests.cs
@@ -285,5 +285,50 @@ namespace System.Linq.Expressions.Tests
NewArrayExpression newArrayExpression = Expression.NewArrayBounds(typeof(string), bound0, bound1);
AssertExtensions.Throws<ArgumentNullException>("expressions", () => newArrayExpression.Update(null));
}
+
+ [Theory, ClassData(typeof(CompilationTypes))]
+ public static void SingleNegativeBoundErrorMessage(bool useInterpreter)
+ {
+ string localizedMessage = null;
+ try
+ {
+ int[] dummy = new int["".Length - 2];
+ }
+ catch (OverflowException oe)
+ {
+ localizedMessage = oe.Message;
+ }
+
+ Expression<Func<int[]>> lambda =
+ Expression.Lambda<Func<int[]>>(Expression.NewArrayBounds(typeof(int), Expression.Constant(-2)));
+ var func = lambda.Compile(useInterpreter);
+ OverflowException ex = Assert.Throws<OverflowException>(() => func());
+
+ if (!PlatformDetection.IsNetNative) // Exceptions do not always have messages
+ Assert.Equal(localizedMessage, ex.Message);
+ }
+
+ [Theory, ClassData(typeof(CompilationTypes))]
+ public static void MultipleNegativeBoundErrorMessage(bool useInterpreter)
+ {
+ string localizedMessage = null;
+ try
+ {
+ int[,,] dummy = new int[1, 1, "".Length - 2];
+ }
+ catch (OverflowException oe)
+ {
+ localizedMessage = oe.Message;
+ }
+
+ Expression<Func<int[,,]>> lambda = Expression.Lambda<Func<int[,,]>>(
+ Expression.NewArrayBounds(
+ typeof(int), Expression.Constant(0), Expression.Constant(0), Expression.Constant(-2)));
+ var func = lambda.Compile(useInterpreter);
+ OverflowException ex = Assert.Throws<OverflowException>(() => func());
+
+ if (!PlatformDetection.IsNetNative) // Exceptions do not always have messages
+ Assert.Equal(localizedMessage, ex.Message);
+ }
}
}
diff --git a/src/System.Linq.Expressions/tests/System.Linq.Expressions.Tests.csproj b/src/System.Linq.Expressions/tests/System.Linq.Expressions.Tests.csproj
index 21efdad84d..3d5fc211d9 100644
--- a/src/System.Linq.Expressions/tests/System.Linq.Expressions.Tests.csproj
+++ b/src/System.Linq.Expressions/tests/System.Linq.Expressions.Tests.csproj
@@ -25,6 +25,7 @@
</ItemGroup>
<ItemGroup Condition="'$(TargetGroup)' == 'uapaot'">
<ReferenceFromRuntime Include="System.Private.CoreLib" />
+ <ReferenceFromRuntime Include="CoreFx.Private.TestUtilities" />
<ReferenceFromRuntime Include="xunit.core" />
<ReferenceFromRuntime Include="Xunit.NetCore.Extensions" />
<ReferenceFromRuntime Include="xunit.assert" />
@@ -260,9 +261,6 @@
<Compile Include="Variables\RuntimeVariablesTests.cs" />
<Compile Include="Variables\VariableTests.cs" />
<Compile Include="Visitor\VisitorTests.cs" />
- <Compile Include="$(CommonTestPath)\System\AssertExtensions.cs">
- <Link>Common\System\AssertExtensions.cs</Link>
- </Compile>
<Compile Include="$(CommonTestPath)\System\PlatformDetection.cs">
<Link>Common\System\PlatformDetection.cs</Link>
</Compile>
diff --git a/src/System.Linq.Parallel/tests/System.Linq.Parallel.Tests.csproj b/src/System.Linq.Parallel/tests/System.Linq.Parallel.Tests.csproj
index 32f697e6ce..92f719aaa6 100644
--- a/src/System.Linq.Parallel/tests/System.Linq.Parallel.Tests.csproj
+++ b/src/System.Linq.Parallel/tests/System.Linq.Parallel.Tests.csproj
@@ -13,9 +13,6 @@
<PropertyGroup Condition="'$(Configuration)|$(Platform)' == 'uap-Debug|AnyCPU'" />
<PropertyGroup Condition="'$(Configuration)|$(Platform)' == 'uap-Release|AnyCPU'" />
<ItemGroup>
- <Compile Include="$(CommonTestPath)\System\AssertExtensions.cs">
- <Link>Common\System\AssertExtensions.cs</Link>
- </Compile>
<Compile Include="$(CommonTestPath)\System\Diagnostics\Tracing\TestEventListener.cs">
<Link>Common\System\Diagnostics\Tracing\TestEventListener.cs</Link>
</Compile>
diff --git a/src/System.Linq.Queryable/tests/System.Linq.Queryable.Tests.csproj b/src/System.Linq.Queryable/tests/System.Linq.Queryable.Tests.csproj
index c111bc6b72..ac7af6fb2e 100644
--- a/src/System.Linq.Queryable/tests/System.Linq.Queryable.Tests.csproj
+++ b/src/System.Linq.Queryable/tests/System.Linq.Queryable.Tests.csproj
@@ -62,9 +62,6 @@
<Compile Include="UnionTests.cs" />
<Compile Include="WhereTests.cs" />
<Compile Include="ZipTests.cs" />
- <Compile Include="$(CommonTestPath)\System\AssertExtensions.cs">
- <Link>Common\System\AssertExtensions.cs</Link>
- </Compile>
<Compile Include="$(CommonTestPath)\System\Linq\SkipTakeData.cs">
<Link>Common\System\Linq\SkipTakeData.cs</Link>
</Compile>
diff --git a/src/System.Linq/src/System/Linq/AppendPrepend.cs b/src/System.Linq/src/System/Linq/AppendPrepend.cs
index ec12deb43e..e0bb2bf634 100644
--- a/src/System.Linq/src/System/Linq/AppendPrepend.cs
+++ b/src/System.Linq/src/System/Linq/AppendPrepend.cs
@@ -16,13 +16,9 @@ namespace System.Linq
throw Error.ArgumentNull(nameof(source));
}
- AppendPrependIterator<TSource> appendable = source as AppendPrependIterator<TSource>;
- if (appendable != null)
- {
- return appendable.Append(element);
- }
-
- return new AppendPrepend1Iterator<TSource>(source, element, appending: true);
+ return source is AppendPrependIterator<TSource> appendable
+ ? appendable.Append(element)
+ : new AppendPrepend1Iterator<TSource>(source, element, appending: true);
}
public static IEnumerable<TSource> Prepend<TSource>(this IEnumerable<TSource> source, TSource element)
@@ -32,13 +28,9 @@ namespace System.Linq
throw Error.ArgumentNull(nameof(source));
}
- AppendPrependIterator<TSource> appendable = source as AppendPrependIterator<TSource>;
- if (appendable != null)
- {
- return appendable.Prepend(element);
- }
-
- return new AppendPrepend1Iterator<TSource>(source, element, appending: false);
+ return source is AppendPrependIterator<TSource> appendable
+ ? appendable.Prepend(element)
+ : new AppendPrepend1Iterator<TSource>(source, element, appending: false);
}
/// <summary>
@@ -245,8 +237,7 @@ namespace System.Linq
public override int GetCount(bool onlyIfCheap)
{
- IIListProvider<TSource> listProv = _source as IIListProvider<TSource>;
- if (listProv != null)
+ if (_source is IIListProvider<TSource> listProv)
{
int count = listProv.GetCount(onlyIfCheap);
return count == -1 ? -1 : count + 1;
@@ -389,8 +380,7 @@ namespace System.Linq
++index;
}
- ICollection<TSource> sourceCollection = _source as ICollection<TSource>;
- if (sourceCollection != null)
+ if (_source is ICollection<TSource> sourceCollection)
{
sourceCollection.CopyTo(array, index);
}
@@ -437,8 +427,7 @@ namespace System.Linq
public override int GetCount(bool onlyIfCheap)
{
- IIListProvider<TSource> listProv = _source as IIListProvider<TSource>;
- if (listProv != null)
+ if (_source is IIListProvider<TSource> listProv)
{
int count = listProv.GetCount(onlyIfCheap);
return count == -1 ? -1 : count + _appendCount + _prependCount;
diff --git a/src/System.Linq/src/System/Linq/Buffer.cs b/src/System.Linq/src/System/Linq/Buffer.cs
index 16d5cc1ee4..88aa3a3650 100644
--- a/src/System.Linq/src/System/Linq/Buffer.cs
+++ b/src/System.Linq/src/System/Linq/Buffer.cs
@@ -28,8 +28,7 @@ namespace System.Linq
/// <param name="source">The enumerable to be store.</param>
internal Buffer(IEnumerable<TElement> source)
{
- IIListProvider<TElement> iterator = source as IIListProvider<TElement>;
- if (iterator != null)
+ if (source is IIListProvider<TElement> iterator)
{
TElement[] array = iterator.ToArray();
_items = array;
diff --git a/src/System.Linq/src/System/Linq/Cast.cs b/src/System.Linq/src/System/Linq/Cast.cs
index 38e879cc80..c51fde3736 100644
--- a/src/System.Linq/src/System/Linq/Cast.cs
+++ b/src/System.Linq/src/System/Linq/Cast.cs
@@ -37,15 +37,14 @@ namespace System.Linq
{
return typedSource;
}
-
+
if (source == null)
{
throw Error.ArgumentNull(nameof(source));
}
-
+
return CastIterator<TResult>(source);
}
-
private static IEnumerable<TResult> CastIterator<TResult>(IEnumerable source)
{
foreach (object obj in source)
diff --git a/src/System.Linq/src/System/Linq/Concat.cs b/src/System.Linq/src/System/Linq/Concat.cs
index abdac7856e..11b1bf9084 100644
--- a/src/System.Linq/src/System/Linq/Concat.cs
+++ b/src/System.Linq/src/System/Linq/Concat.cs
@@ -21,10 +21,9 @@ namespace System.Linq
throw Error.ArgumentNull(nameof(second));
}
- var firstConcat = first as ConcatIterator<TSource>;
- return firstConcat != null ?
- firstConcat.Concat(second) :
- new Concat2Iterator<TSource>(first, second);
+ return first is ConcatIterator<TSource> firstConcat
+ ? firstConcat.Concat(second)
+ : new Concat2Iterator<TSource>(first, second);
}
/// <summary>
@@ -61,9 +60,9 @@ namespace System.Linq
internal override ConcatIterator<TSource> Concat(IEnumerable<TSource> next)
{
- bool hasOnlyCollections = _first is ICollection<TSource> &&
- _second is ICollection<TSource> &&
- next is ICollection<TSource>;
+ bool hasOnlyCollections = next is ICollection<TSource> &&
+ _first is ICollection<TSource> &&
+ _second is ICollection<TSource>;
return new ConcatNIterator<TSource>(this, next, 2, hasOnlyCollections);
}
diff --git a/src/System.Linq/src/System/Linq/Contains.cs b/src/System.Linq/src/System/Linq/Contains.cs
index e3eed6e36f..b356960c14 100644
--- a/src/System.Linq/src/System/Linq/Contains.cs
+++ b/src/System.Linq/src/System/Linq/Contains.cs
@@ -8,16 +8,10 @@ namespace System.Linq
{
public static partial class Enumerable
{
- public static bool Contains<TSource>(this IEnumerable<TSource> source, TSource value)
- {
- ICollection<TSource> collection = source as ICollection<TSource>;
- if (collection != null)
- {
- return collection.Contains(value);
- }
-
- return Contains(source, value, null);
- }
+ public static bool Contains<TSource>(this IEnumerable<TSource> source, TSource value) =>
+ source is ICollection<TSource> collection
+ ? collection.Contains(value)
+ : Contains(source, value, null);
public static bool Contains<TSource>(this IEnumerable<TSource> source, TSource value, IEqualityComparer<TSource> comparer)
{
diff --git a/src/System.Linq/src/System/Linq/Count.cs b/src/System.Linq/src/System/Linq/Count.cs
index 1efe8aafdd..01434cbe19 100644
--- a/src/System.Linq/src/System/Linq/Count.cs
+++ b/src/System.Linq/src/System/Linq/Count.cs
@@ -16,20 +16,17 @@ namespace System.Linq
throw Error.ArgumentNull(nameof(source));
}
- ICollection<TSource> collectionoft = source as ICollection<TSource>;
- if (collectionoft != null)
+ if (source is ICollection<TSource> collectionoft)
{
return collectionoft.Count;
}
- IIListProvider<TSource> listProv = source as IIListProvider<TSource>;
- if (listProv != null)
+ if (source is IIListProvider<TSource> listProv)
{
return listProv.GetCount(onlyIfCheap: false);
}
- ICollection collection = source as ICollection;
- if (collection != null)
+ if (source is ICollection collection)
{
return collection.Count;
}
diff --git a/src/System.Linq/src/System/Linq/DebugView.cs b/src/System.Linq/src/System/Linq/DebugView.cs
index be8e8615aa..1957cd9b9d 100644
--- a/src/System.Linq/src/System/Linq/DebugView.cs
+++ b/src/System.Linq/src/System/Linq/DebugView.cs
@@ -24,12 +24,7 @@ namespace System.Linq
{
public SystemCore_EnumerableDebugView(IEnumerable<T> enumerable)
{
- if (enumerable == null)
- {
- throw new ArgumentNullException(nameof(enumerable));
- }
-
- _enumerable = enumerable;
+ _enumerable = enumerable ?? throw Error.ArgumentNull(nameof(enumerable));
}
[DebuggerBrowsable(DebuggerBrowsableState.RootHidden)]
@@ -53,25 +48,14 @@ namespace System.Linq
internal sealed class SystemCore_EnumerableDebugViewEmptyException : Exception
{
- public string Empty
- {
- get
- {
- return SR.EmptyEnumerable;
- }
- }
+ public string Empty => SR.EmptyEnumerable;
}
internal sealed class SystemCore_EnumerableDebugView
{
public SystemCore_EnumerableDebugView(IEnumerable enumerable)
{
- if (enumerable == null)
- {
- throw new ArgumentNullException(nameof(enumerable));
- }
-
- _enumerable = enumerable;
+ _enumerable = enumerable ?? throw Error.ArgumentNull(nameof(enumerable));
}
[DebuggerBrowsable(DebuggerBrowsableState.RootHidden)]
diff --git a/src/System.Linq/src/System/Linq/DefaultIfEmpty.cs b/src/System.Linq/src/System/Linq/DefaultIfEmpty.cs
index a1da4a8e0e..b98f659877 100644
--- a/src/System.Linq/src/System/Linq/DefaultIfEmpty.cs
+++ b/src/System.Linq/src/System/Linq/DefaultIfEmpty.cs
@@ -10,10 +10,8 @@ namespace System.Linq
{
public static partial class Enumerable
{
- public static IEnumerable<TSource> DefaultIfEmpty<TSource>(this IEnumerable<TSource> source)
- {
- return DefaultIfEmpty(source, default(TSource));
- }
+ public static IEnumerable<TSource> DefaultIfEmpty<TSource>(this IEnumerable<TSource> source) =>
+ DefaultIfEmpty(source, default(TSource));
public static IEnumerable<TSource> DefaultIfEmpty<TSource>(this IEnumerable<TSource> source, TSource defaultValue)
{
@@ -38,10 +36,7 @@ namespace System.Linq
_default = defaultValue;
}
- public override Iterator<TSource> Clone()
- {
- return new DefaultIfEmptyIterator<TSource>(_source, _default);
- }
+ public override Iterator<TSource> Clone() => new DefaultIfEmptyIterator<TSource>(_source, _default);
public override bool MoveNext()
{
@@ -112,8 +107,7 @@ namespace System.Linq
}
else
{
- IIListProvider<TSource> listProv = _source as IIListProvider<TSource>;
- count = listProv == null ? -1 : listProv.GetCount(onlyIfCheap: true);
+ count = _source is IIListProvider<TSource> listProv ? listProv.GetCount(onlyIfCheap: true) : -1;
}
return count == 0 ? 1 : count;
diff --git a/src/System.Linq/src/System/Linq/Distinct.cs b/src/System.Linq/src/System/Linq/Distinct.cs
index c9870a8c4f..e01d319ab3 100644
--- a/src/System.Linq/src/System/Linq/Distinct.cs
+++ b/src/System.Linq/src/System/Linq/Distinct.cs
@@ -9,10 +9,7 @@ namespace System.Linq
{
public static partial class Enumerable
{
- public static IEnumerable<TSource> Distinct<TSource>(this IEnumerable<TSource> source)
- {
- return Distinct(source, null);
- }
+ public static IEnumerable<TSource> Distinct<TSource>(this IEnumerable<TSource> source) => Distinct(source, null);
public static IEnumerable<TSource> Distinct<TSource>(this IEnumerable<TSource> source, IEqualityComparer<TSource> comparer)
{
@@ -42,10 +39,7 @@ namespace System.Linq
_comparer = comparer;
}
- public override Iterator<TSource> Clone()
- {
- return new DistinctIterator<TSource>(_source, _comparer);
- }
+ public override Iterator<TSource> Clone() => new DistinctIterator<TSource>(_source, _comparer);
public override bool MoveNext()
{
@@ -102,20 +96,11 @@ namespace System.Linq
return set;
}
- public TSource[] ToArray()
- {
- return FillSet().ToArray();
- }
+ public TSource[] ToArray() => FillSet().ToArray();
- public List<TSource> ToList()
- {
- return FillSet().ToList();
- }
+ public List<TSource> ToList() => FillSet().ToList();
- public int GetCount(bool onlyIfCheap)
- {
- return onlyIfCheap ? -1 : FillSet().Count;
- }
+ public int GetCount(bool onlyIfCheap) => onlyIfCheap ? -1 : FillSet().Count;
}
}
}
diff --git a/src/System.Linq/src/System/Linq/ElementAt.cs b/src/System.Linq/src/System/Linq/ElementAt.cs
index 367a8f0cac..75f37dfada 100644
--- a/src/System.Linq/src/System/Linq/ElementAt.cs
+++ b/src/System.Linq/src/System/Linq/ElementAt.cs
@@ -15,11 +15,9 @@ namespace System.Linq
throw Error.ArgumentNull(nameof(source));
}
- IPartition<TSource> partition = source as IPartition<TSource>;
- if (partition != null)
+ if (source is IPartition<TSource> partition)
{
- bool found;
- TSource element = partition.TryGetElementAt(index, out found);
+ TSource element = partition.TryGetElementAt(index, out bool found);
if (found)
{
return element;
@@ -27,8 +25,7 @@ namespace System.Linq
}
else
{
- IList<TSource> list = source as IList<TSource>;
- if (list != null)
+ if (source is IList<TSource> list)
{
return list[index];
}
@@ -60,17 +57,14 @@ namespace System.Linq
throw Error.ArgumentNull(nameof(source));
}
- IPartition<TSource> partition = source as IPartition<TSource>;
- if (partition != null)
+ if (source is IPartition<TSource> partition)
{
- bool found;
- return partition.TryGetElementAt(index, out found);
+ return partition.TryGetElementAt(index, out bool _);
}
if (index >= 0)
{
- IList<TSource> list = source as IList<TSource>;
- if (list != null)
+ if (source is IList<TSource> list)
{
if (index < list.Count)
{
diff --git a/src/System.Linq/src/System/Linq/Enumerable.cs b/src/System.Linq/src/System/Linq/Enumerable.cs
index 9366b3269b..2ea06da58c 100644
--- a/src/System.Linq/src/System/Linq/Enumerable.cs
+++ b/src/System.Linq/src/System/Linq/Enumerable.cs
@@ -8,14 +8,8 @@ namespace System.Linq
{
public static partial class Enumerable
{
- public static IEnumerable<TSource> AsEnumerable<TSource>(this IEnumerable<TSource> source)
- {
- return source;
- }
+ public static IEnumerable<TSource> AsEnumerable<TSource>(this IEnumerable<TSource> source) => source;
- public static IEnumerable<TResult> Empty<TResult>()
- {
- return Array.Empty<TResult>();
- }
+ public static IEnumerable<TResult> Empty<TResult>() => Array.Empty<TResult>();
}
}
diff --git a/src/System.Linq/src/System/Linq/First.cs b/src/System.Linq/src/System/Linq/First.cs
index 7abe939014..190ba96a8a 100644
--- a/src/System.Linq/src/System/Linq/First.cs
+++ b/src/System.Linq/src/System/Linq/First.cs
@@ -10,9 +10,7 @@ namespace System.Linq
{
public static TSource First<TSource>(this IEnumerable<TSource> source)
{
- bool found;
- TSource first = source.TryGetFirst(out found);
-
+ TSource first = source.TryGetFirst(out bool found);
if (!found)
{
throw Error.NoElements();
@@ -23,9 +21,7 @@ namespace System.Linq
public static TSource First<TSource>(this IEnumerable<TSource> source, Func<TSource, bool> predicate)
{
- bool found;
- TSource first = source.TryGetFirst(predicate, out found);
-
+ TSource first = source.TryGetFirst(predicate, out bool found);
if (!found)
{
throw Error.NoMatch();
@@ -34,33 +30,25 @@ namespace System.Linq
return first;
}
- public static TSource FirstOrDefault<TSource>(this IEnumerable<TSource> source)
- {
- bool found;
- return source.TryGetFirst(out found);
- }
+ public static TSource FirstOrDefault<TSource>(this IEnumerable<TSource> source) =>
+ source.TryGetFirst(out bool _);
- public static TSource FirstOrDefault<TSource>(this IEnumerable<TSource> source, Func<TSource, bool> predicate)
- {
- bool found;
- return source.TryGetFirst(predicate, out found);
- }
+ public static TSource FirstOrDefault<TSource>(this IEnumerable<TSource> source, Func<TSource, bool> predicate) =>
+ source.TryGetFirst(predicate, out bool _);
- internal static TSource TryGetFirst<TSource>(this IEnumerable<TSource> source, out bool found)
+ private static TSource TryGetFirst<TSource>(this IEnumerable<TSource> source, out bool found)
{
if (source == null)
{
throw Error.ArgumentNull(nameof(source));
}
- IPartition<TSource> partition = source as IPartition<TSource>;
- if (partition != null)
+ if (source is IPartition<TSource> partition)
{
return partition.TryGetFirst(out found);
}
-
- IList<TSource> list = source as IList<TSource>;
- if (list != null)
+
+ if (source is IList<TSource> list)
{
if (list.Count > 0)
{
@@ -84,7 +72,7 @@ namespace System.Linq
return default(TSource);
}
- internal static TSource TryGetFirst<TSource>(this IEnumerable<TSource> source, Func<TSource, bool> predicate, out bool found)
+ private static TSource TryGetFirst<TSource>(this IEnumerable<TSource> source, Func<TSource, bool> predicate, out bool found)
{
if (source == null)
{
@@ -96,8 +84,7 @@ namespace System.Linq
throw Error.ArgumentNull(nameof(predicate));
}
- OrderedEnumerable<TSource> ordered = source as OrderedEnumerable<TSource>;
- if (ordered != null)
+ if (source is OrderedEnumerable<TSource> ordered)
{
return ordered.TryGetFirst(predicate, out found);
}
diff --git a/src/System.Linq/src/System/Linq/Grouping.cs b/src/System.Linq/src/System/Linq/Grouping.cs
index a04eaedea4..030f01f2c1 100644
--- a/src/System.Linq/src/System/Linq/Grouping.cs
+++ b/src/System.Linq/src/System/Linq/Grouping.cs
@@ -10,45 +10,29 @@ namespace System.Linq
{
public static partial class Enumerable
{
- public static IEnumerable<IGrouping<TKey, TSource>> GroupBy<TSource, TKey>(this IEnumerable<TSource> source, Func<TSource, TKey> keySelector)
- {
- return new GroupedEnumerable<TSource, TKey>(source, keySelector, null);
- }
+ public static IEnumerable<IGrouping<TKey, TSource>> GroupBy<TSource, TKey>(this IEnumerable<TSource> source, Func<TSource, TKey> keySelector) =>
+ new GroupedEnumerable<TSource, TKey>(source, keySelector, null);
- public static IEnumerable<IGrouping<TKey, TSource>> GroupBy<TSource, TKey>(this IEnumerable<TSource> source, Func<TSource, TKey> keySelector, IEqualityComparer<TKey> comparer)
- {
- return new GroupedEnumerable<TSource, TKey>(source, keySelector, comparer);
- }
+ public static IEnumerable<IGrouping<TKey, TSource>> GroupBy<TSource, TKey>(this IEnumerable<TSource> source, Func<TSource, TKey> keySelector, IEqualityComparer<TKey> comparer) =>
+ new GroupedEnumerable<TSource, TKey>(source, keySelector, comparer);
- public static IEnumerable<IGrouping<TKey, TElement>> GroupBy<TSource, TKey, TElement>(this IEnumerable<TSource> source, Func<TSource, TKey> keySelector, Func<TSource, TElement> elementSelector)
- {
- return new GroupedEnumerable<TSource, TKey, TElement>(source, keySelector, elementSelector, null);
- }
+ public static IEnumerable<IGrouping<TKey, TElement>> GroupBy<TSource, TKey, TElement>(this IEnumerable<TSource> source, Func<TSource, TKey> keySelector, Func<TSource, TElement> elementSelector) =>
+ new GroupedEnumerable<TSource, TKey, TElement>(source, keySelector, elementSelector, null);
- public static IEnumerable<IGrouping<TKey, TElement>> GroupBy<TSource, TKey, TElement>(this IEnumerable<TSource> source, Func<TSource, TKey> keySelector, Func<TSource, TElement> elementSelector, IEqualityComparer<TKey> comparer)
- {
- return new GroupedEnumerable<TSource, TKey, TElement>(source, keySelector, elementSelector, comparer);
- }
+ public static IEnumerable<IGrouping<TKey, TElement>> GroupBy<TSource, TKey, TElement>(this IEnumerable<TSource> source, Func<TSource, TKey> keySelector, Func<TSource, TElement> elementSelector, IEqualityComparer<TKey> comparer) =>
+ new GroupedEnumerable<TSource, TKey, TElement>(source, keySelector, elementSelector, comparer);
- public static IEnumerable<TResult> GroupBy<TSource, TKey, TResult>(this IEnumerable<TSource> source, Func<TSource, TKey> keySelector, Func<TKey, IEnumerable<TSource>, TResult> resultSelector)
- {
- return new GroupedResultEnumerable<TSource, TKey, TResult>(source, keySelector, resultSelector, null);
- }
+ public static IEnumerable<TResult> GroupBy<TSource, TKey, TResult>(this IEnumerable<TSource> source, Func<TSource, TKey> keySelector, Func<TKey, IEnumerable<TSource>, TResult> resultSelector) =>
+ new GroupedResultEnumerable<TSource, TKey, TResult>(source, keySelector, resultSelector, null);
- public static IEnumerable<TResult> GroupBy<TSource, TKey, TElement, TResult>(this IEnumerable<TSource> source, Func<TSource, TKey> keySelector, Func<TSource, TElement> elementSelector, Func<TKey, IEnumerable<TElement>, TResult> resultSelector)
- {
- return new GroupedResultEnumerable<TSource, TKey, TElement, TResult>(source, keySelector, elementSelector, resultSelector, null);
- }
+ public static IEnumerable<TResult> GroupBy<TSource, TKey, TElement, TResult>(this IEnumerable<TSource> source, Func<TSource, TKey> keySelector, Func<TSource, TElement> elementSelector, Func<TKey, IEnumerable<TElement>, TResult> resultSelector) =>
+ new GroupedResultEnumerable<TSource, TKey, TElement, TResult>(source, keySelector, elementSelector, resultSelector, null);
- public static IEnumerable<TResult> GroupBy<TSource, TKey, TResult>(this IEnumerable<TSource> source, Func<TSource, TKey> keySelector, Func<TKey, IEnumerable<TSource>, TResult> resultSelector, IEqualityComparer<TKey> comparer)
- {
- return new GroupedResultEnumerable<TSource, TKey, TResult>(source, keySelector, resultSelector, comparer);
- }
+ public static IEnumerable<TResult> GroupBy<TSource, TKey, TResult>(this IEnumerable<TSource> source, Func<TSource, TKey> keySelector, Func<TKey, IEnumerable<TSource>, TResult> resultSelector, IEqualityComparer<TKey> comparer) =>
+ new GroupedResultEnumerable<TSource, TKey, TResult>(source, keySelector, resultSelector, comparer);
- public static IEnumerable<TResult> GroupBy<TSource, TKey, TElement, TResult>(this IEnumerable<TSource> source, Func<TSource, TKey> keySelector, Func<TSource, TElement> elementSelector, Func<TKey, IEnumerable<TElement>, TResult> resultSelector, IEqualityComparer<TKey> comparer)
- {
- return new GroupedResultEnumerable<TSource, TKey, TElement, TResult>(source, keySelector, elementSelector, resultSelector, comparer);
- }
+ public static IEnumerable<TResult> GroupBy<TSource, TKey, TElement, TResult>(this IEnumerable<TSource> source, Func<TSource, TKey> keySelector, Func<TSource, TElement> elementSelector, Func<TKey, IEnumerable<TElement>, TResult> resultSelector, IEqualityComparer<TKey> comparer) =>
+ new GroupedResultEnumerable<TSource, TKey, TElement, TResult>(source, keySelector, elementSelector, resultSelector, comparer);
}
public interface IGrouping<out TKey, out TElement> : IEnumerable<TElement>
@@ -107,67 +91,32 @@ namespace System.Linq
}
}
- IEnumerator IEnumerable.GetEnumerator()
- {
- return GetEnumerator();
- }
+ IEnumerator IEnumerable.GetEnumerator() => GetEnumerator();
// DDB195907: implement IGrouping<>.Key implicitly
// so that WPF binding works on this property.
- public TKey Key
- {
- get { return _key; }
- }
+ public TKey Key => _key;
- int ICollection<TElement>.Count
- {
- get { return _count; }
- }
+ int ICollection<TElement>.Count => _count;
- bool ICollection<TElement>.IsReadOnly
- {
- get { return true; }
- }
+ bool ICollection<TElement>.IsReadOnly => true;
- void ICollection<TElement>.Add(TElement item)
- {
- throw Error.NotSupported();
- }
+ void ICollection<TElement>.Add(TElement item) => throw Error.NotSupported();
- void ICollection<TElement>.Clear()
- {
- throw Error.NotSupported();
- }
+ void ICollection<TElement>.Clear() => throw Error.NotSupported();
- bool ICollection<TElement>.Contains(TElement item)
- {
- return Array.IndexOf(_elements, item, 0, _count) >= 0;
- }
+ bool ICollection<TElement>.Contains(TElement item) => Array.IndexOf(_elements, item, 0, _count) >= 0;
- void ICollection<TElement>.CopyTo(TElement[] array, int arrayIndex)
- {
+ void ICollection<TElement>.CopyTo(TElement[] array, int arrayIndex) =>
Array.Copy(_elements, 0, array, arrayIndex, _count);
- }
- bool ICollection<TElement>.Remove(TElement item)
- {
- throw Error.NotSupported();
- }
+ bool ICollection<TElement>.Remove(TElement item) => throw Error.NotSupported();
- int IList<TElement>.IndexOf(TElement item)
- {
- return Array.IndexOf(_elements, item, 0, _count);
- }
+ int IList<TElement>.IndexOf(TElement item) => Array.IndexOf(_elements, item, 0, _count);
- void IList<TElement>.Insert(int index, TElement item)
- {
- throw Error.NotSupported();
- }
+ void IList<TElement>.Insert(int index, TElement item) => throw Error.NotSupported();
- void IList<TElement>.RemoveAt(int index)
- {
- throw Error.NotSupported();
- }
+ void IList<TElement>.RemoveAt(int index) => throw Error.NotSupported();
TElement IList<TElement>.this[int index]
{
@@ -198,31 +147,11 @@ namespace System.Linq
public GroupedResultEnumerable(IEnumerable<TSource> source, Func<TSource, TKey> keySelector, Func<TSource, TElement> elementSelector, Func<TKey, IEnumerable<TElement>, TResult> resultSelector, IEqualityComparer<TKey> comparer)
{
- if (source == null)
- {
- throw Error.ArgumentNull(nameof(source));
- }
-
- if (keySelector == null)
- {
- throw Error.ArgumentNull(nameof(keySelector));
- }
-
- if (elementSelector == null)
- {
- throw Error.ArgumentNull(nameof(elementSelector));
- }
-
- if (resultSelector == null)
- {
- throw Error.ArgumentNull(nameof(resultSelector));
- }
-
- _source = source;
- _keySelector = keySelector;
- _elementSelector = elementSelector;
+ _source = source ?? throw Error.ArgumentNull(nameof(source));
+ _keySelector = keySelector ?? throw Error.ArgumentNull(nameof(keySelector));
+ _elementSelector = elementSelector ?? throw Error.ArgumentNull(nameof(elementSelector));
_comparer = comparer;
- _resultSelector = resultSelector;
+ _resultSelector = resultSelector ?? throw Error.ArgumentNull(nameof(resultSelector));
}
public IEnumerator<TResult> GetEnumerator()
@@ -231,25 +160,16 @@ namespace System.Linq
return lookup.ApplyResultSelector(_resultSelector).GetEnumerator();
}
- IEnumerator IEnumerable.GetEnumerator()
- {
- return GetEnumerator();
- }
+ IEnumerator IEnumerable.GetEnumerator() => GetEnumerator();
- public TResult[] ToArray()
- {
- return Lookup<TKey, TElement>.Create(_source, _keySelector, _elementSelector, _comparer).ToArray(_resultSelector);
- }
+ public TResult[] ToArray() =>
+ Lookup<TKey, TElement>.Create(_source, _keySelector, _elementSelector, _comparer).ToArray(_resultSelector);
- public List<TResult> ToList()
- {
- return Lookup<TKey, TElement>.Create(_source, _keySelector, _elementSelector, _comparer).ToList(_resultSelector);
- }
+ public List<TResult> ToList() =>
+ Lookup<TKey, TElement>.Create(_source, _keySelector, _elementSelector, _comparer).ToList(_resultSelector);
- public int GetCount(bool onlyIfCheap)
- {
- return onlyIfCheap ? -1 : Lookup<TKey, TElement>.Create(_source, _keySelector, _elementSelector, _comparer).Count;
- }
+ public int GetCount(bool onlyIfCheap) =>
+ onlyIfCheap ? -1 : Lookup<TKey, TElement>.Create(_source, _keySelector, _elementSelector, _comparer).Count;
}
internal sealed class GroupedResultEnumerable<TSource, TKey, TResult> : IIListProvider<TResult>
@@ -261,24 +181,9 @@ namespace System.Linq
public GroupedResultEnumerable(IEnumerable<TSource> source, Func<TSource, TKey> keySelector, Func<TKey, IEnumerable<TSource>, TResult> resultSelector, IEqualityComparer<TKey> comparer)
{
- if (source == null)
- {
- throw Error.ArgumentNull(nameof(source));
- }
-
- if (keySelector == null)
- {
- throw Error.ArgumentNull(nameof(keySelector));
- }
-
- if (resultSelector == null)
- {
- throw Error.ArgumentNull(nameof(resultSelector));
- }
-
- _source = source;
- _keySelector = keySelector;
- _resultSelector = resultSelector;
+ _source = source ?? throw Error.ArgumentNull(nameof(source));
+ _keySelector = keySelector ?? throw Error.ArgumentNull(nameof(keySelector));
+ _resultSelector = resultSelector ?? throw Error.ArgumentNull(nameof(resultSelector));
_comparer = comparer;
}
@@ -288,25 +193,16 @@ namespace System.Linq
return lookup.ApplyResultSelector(_resultSelector).GetEnumerator();
}
- IEnumerator IEnumerable.GetEnumerator()
- {
- return GetEnumerator();
- }
+ IEnumerator IEnumerable.GetEnumerator() => GetEnumerator();
- public TResult[] ToArray()
- {
- return Lookup<TKey, TSource>.Create(_source, _keySelector, _comparer).ToArray(_resultSelector);
- }
+ public TResult[] ToArray() =>
+ Lookup<TKey, TSource>.Create(_source, _keySelector, _comparer).ToArray(_resultSelector);
- public List<TResult> ToList()
- {
- return Lookup<TKey, TSource>.Create(_source, _keySelector, _comparer).ToList(_resultSelector);
- }
+ public List<TResult> ToList() =>
+ Lookup<TKey, TSource>.Create(_source, _keySelector, _comparer).ToList(_resultSelector);
- public int GetCount(bool onlyIfCheap)
- {
- return onlyIfCheap ? -1 : Lookup<TKey, TSource>.Create(_source, _keySelector, _comparer).Count;
- }
+ public int GetCount(bool onlyIfCheap) =>
+ onlyIfCheap ? -1 : Lookup<TKey, TSource>.Create(_source, _keySelector, _comparer).Count;
}
internal sealed class GroupedEnumerable<TSource, TKey, TElement> : IIListProvider<IGrouping<TKey, TElement>>
@@ -318,36 +214,16 @@ namespace System.Linq
public GroupedEnumerable(IEnumerable<TSource> source, Func<TSource, TKey> keySelector, Func<TSource, TElement> elementSelector, IEqualityComparer<TKey> comparer)
{
- if (source == null)
- {
- throw Error.ArgumentNull(nameof(source));
- }
-
- if (keySelector == null)
- {
- throw Error.ArgumentNull(nameof(keySelector));
- }
-
- if (elementSelector == null)
- {
- throw Error.ArgumentNull(nameof(elementSelector));
- }
-
- _source = source;
- _keySelector = keySelector;
- _elementSelector = elementSelector;
+ _source = source ?? throw Error.ArgumentNull(nameof(source));
+ _keySelector = keySelector ?? throw Error.ArgumentNull(nameof(keySelector));
+ _elementSelector = elementSelector ?? throw Error.ArgumentNull(nameof(elementSelector));
_comparer = comparer;
}
- public IEnumerator<IGrouping<TKey, TElement>> GetEnumerator()
- {
- return Lookup<TKey, TElement>.Create(_source, _keySelector, _elementSelector, _comparer).GetEnumerator();
- }
+ public IEnumerator<IGrouping<TKey, TElement>> GetEnumerator() =>
+ Lookup<TKey, TElement>.Create(_source, _keySelector, _elementSelector, _comparer).GetEnumerator();
- IEnumerator IEnumerable.GetEnumerator()
- {
- return GetEnumerator();
- }
+ IEnumerator IEnumerable.GetEnumerator() => GetEnumerator();
public IGrouping<TKey, TElement>[] ToArray()
{
@@ -361,10 +237,8 @@ namespace System.Linq
return lookup.ToList();
}
- public int GetCount(bool onlyIfCheap)
- {
- return onlyIfCheap ? -1 : Lookup<TKey, TElement>.Create(_source, _keySelector, _elementSelector, _comparer).Count;
- }
+ public int GetCount(bool onlyIfCheap) =>
+ onlyIfCheap ? -1 : Lookup<TKey, TElement>.Create(_source, _keySelector, _elementSelector, _comparer).Count;
}
internal sealed class GroupedEnumerable<TSource, TKey> : IIListProvider<IGrouping<TKey, TSource>>
@@ -375,30 +249,15 @@ namespace System.Linq
public GroupedEnumerable(IEnumerable<TSource> source, Func<TSource, TKey> keySelector, IEqualityComparer<TKey> comparer)
{
- if (source == null)
- {
- throw Error.ArgumentNull(nameof(source));
- }
-
- if (keySelector == null)
- {
- throw Error.ArgumentNull(nameof(keySelector));
- }
-
- _source = source;
- _keySelector = keySelector;
+ _source = source ?? throw Error.ArgumentNull(nameof(source));
+ _keySelector = keySelector ?? throw Error.ArgumentNull(nameof(keySelector));
_comparer = comparer;
}
- public IEnumerator<IGrouping<TKey, TSource>> GetEnumerator()
- {
- return Lookup<TKey, TSource>.Create(_source, _keySelector, _comparer).GetEnumerator();
- }
+ public IEnumerator<IGrouping<TKey, TSource>> GetEnumerator() =>
+ Lookup<TKey, TSource>.Create(_source, _keySelector, _comparer).GetEnumerator();
- IEnumerator IEnumerable.GetEnumerator()
- {
- return GetEnumerator();
- }
+ IEnumerator IEnumerable.GetEnumerator() => GetEnumerator();
public IGrouping<TKey, TSource>[] ToArray()
{
@@ -412,9 +271,7 @@ namespace System.Linq
return lookup.ToList();
}
- public int GetCount(bool onlyIfCheap)
- {
- return onlyIfCheap ? -1 : Lookup<TKey, TSource>.Create(_source, _keySelector, _comparer).Count;
- }
+ public int GetCount(bool onlyIfCheap) =>
+ onlyIfCheap ? -1 : Lookup<TKey, TSource>.Create(_source, _keySelector, _comparer).Count;
}
}
diff --git a/src/System.Linq/src/System/Linq/Iterator.cs b/src/System.Linq/src/System/Linq/Iterator.cs
index 27a15c2e42..76466e6628 100644
--- a/src/System.Linq/src/System/Linq/Iterator.cs
+++ b/src/System.Linq/src/System/Linq/Iterator.cs
@@ -113,10 +113,7 @@ namespace System.Linq
IEnumerator IEnumerable.GetEnumerator() => GetEnumerator();
- void IEnumerator.Reset()
- {
- throw Error.NotSupported();
- }
+ void IEnumerator.Reset() => throw Error.NotSupported();
}
}
}
diff --git a/src/System.Linq/src/System/Linq/Last.cs b/src/System.Linq/src/System/Linq/Last.cs
index d57048efcd..c6be8e13b2 100644
--- a/src/System.Linq/src/System/Linq/Last.cs
+++ b/src/System.Linq/src/System/Linq/Last.cs
@@ -10,9 +10,7 @@ namespace System.Linq
{
public static TSource Last<TSource>(this IEnumerable<TSource> source)
{
- bool found;
- TSource last = source.TryGetLast(out found);
-
+ TSource last = source.TryGetLast(out bool found);
if (!found)
{
throw Error.NoElements();
@@ -23,9 +21,7 @@ namespace System.Linq
public static TSource Last<TSource>(this IEnumerable<TSource> source, Func<TSource, bool> predicate)
{
- bool found;
- TSource last = source.TryGetLast(predicate, out found);
-
+ TSource last = source.TryGetLast(predicate, out bool found);
if (!found)
{
throw Error.NoMatch();
@@ -34,33 +30,25 @@ namespace System.Linq
return last;
}
- public static TSource LastOrDefault<TSource>(this IEnumerable<TSource> source)
- {
- bool found;
- return source.TryGetLast(out found);
- }
+ public static TSource LastOrDefault<TSource>(this IEnumerable<TSource> source) =>
+ source.TryGetLast(out bool _);
- public static TSource LastOrDefault<TSource>(this IEnumerable<TSource> source, Func<TSource, bool> predicate)
- {
- bool found;
- return source.TryGetLast(predicate, out found);
- }
+ public static TSource LastOrDefault<TSource>(this IEnumerable<TSource> source, Func<TSource, bool> predicate) =>
+ source.TryGetLast(predicate, out bool _);
- internal static TSource TryGetLast<TSource>(this IEnumerable<TSource> source, out bool found)
+ private static TSource TryGetLast<TSource>(this IEnumerable<TSource> source, out bool found)
{
if (source == null)
{
throw Error.ArgumentNull(nameof(source));
}
- IPartition<TSource> partition = source as IPartition<TSource>;
- if (partition != null)
+ if (source is IPartition<TSource> partition)
{
return partition.TryGetLast(out found);
}
-
- IList<TSource> list = source as IList<TSource>;
- if (list != null)
+
+ if (source is IList<TSource> list)
{
int count = list.Count;
if (count > 0)
@@ -87,12 +75,12 @@ namespace System.Linq
}
}
}
-
+
found = false;
return default(TSource);
}
- internal static TSource TryGetLast<TSource>(this IEnumerable<TSource> source, Func<TSource, bool> predicate, out bool found)
+ private static TSource TryGetLast<TSource>(this IEnumerable<TSource> source, Func<TSource, bool> predicate, out bool found)
{
if (source == null)
{
@@ -104,14 +92,12 @@ namespace System.Linq
throw Error.ArgumentNull(nameof(predicate));
}
- OrderedEnumerable<TSource> ordered = source as OrderedEnumerable<TSource>;
- if (ordered != null)
+ if (source is OrderedEnumerable<TSource> ordered)
{
return ordered.TryGetLast(predicate, out found);
}
- IList<TSource> list = source as IList<TSource>;
- if (list != null)
+ if (source is IList<TSource> list)
{
for (int i = list.Count - 1; i >= 0; --i)
{
diff --git a/src/System.Linq/src/System/Linq/Lookup.cs b/src/System.Linq/src/System/Linq/Lookup.cs
index 6e32caa9d8..638a369782 100644
--- a/src/System.Linq/src/System/Linq/Lookup.cs
+++ b/src/System.Linq/src/System/Linq/Lookup.cs
@@ -10,10 +10,8 @@ namespace System.Linq
{
public static partial class Enumerable
{
- public static ILookup<TKey, TSource> ToLookup<TSource, TKey>(this IEnumerable<TSource> source, Func<TSource, TKey> keySelector)
- {
- return ToLookup(source, keySelector, null);
- }
+ public static ILookup<TKey, TSource> ToLookup<TSource, TKey>(this IEnumerable<TSource> source, Func<TSource, TKey> keySelector) =>
+ ToLookup(source, keySelector, null);
public static ILookup<TKey, TSource> ToLookup<TSource, TKey>(this IEnumerable<TSource> source, Func<TSource, TKey> keySelector, IEqualityComparer<TKey> comparer)
{
@@ -30,10 +28,8 @@ namespace System.Linq
return Lookup<TKey, TSource>.Create(source, keySelector, comparer);
}
- public static ILookup<TKey, TElement> ToLookup<TSource, TKey, TElement>(this IEnumerable<TSource> source, Func<TSource, TKey> keySelector, Func<TSource, TElement> elementSelector)
- {
- return ToLookup(source, keySelector, elementSelector, null);
- }
+ public static ILookup<TKey, TElement> ToLookup<TSource, TKey, TElement>(this IEnumerable<TSource> source, Func<TSource, TKey> keySelector, Func<TSource, TElement> elementSelector) =>
+ ToLookup(source, keySelector, elementSelector, null);
public static ILookup<TKey, TElement> ToLookup<TSource, TKey, TElement>(this IEnumerable<TSource> source, Func<TSource, TKey> keySelector, Func<TSource, TElement> elementSelector, IEqualityComparer<TKey> comparer)
{
@@ -124,10 +120,7 @@ namespace System.Linq
_groupings = new Grouping<TKey, TElement>[7];
}
- public int Count
- {
- get { return _count; }
- }
+ public int Count => _count;
public IEnumerable<TElement> this[TKey key]
{
@@ -143,10 +136,7 @@ namespace System.Linq
}
}
- public bool Contains(TKey key)
- {
- return GetGrouping(key, create: false) != null;
- }
+ public bool Contains(TKey key) => GetGrouping(key, create: false) != null;
public IEnumerator<IGrouping<TKey, TElement>> GetEnumerator()
{
@@ -236,10 +226,7 @@ namespace System.Linq
return list;
}
- int IIListProvider<IGrouping<TKey, TElement>>.GetCount(bool onlyIfCheap)
- {
- return _count;
- }
+ int IIListProvider<IGrouping<TKey, TElement>>.GetCount(bool onlyIfCheap) => _count;
public IEnumerable<TResult> ApplyResultSelector<TResult>(Func<TKey, IEnumerable<TElement>, TResult> resultSelector)
{
@@ -256,12 +243,9 @@ namespace System.Linq
}
}
- IEnumerator IEnumerable.GetEnumerator()
- {
- return GetEnumerator();
- }
+ IEnumerator IEnumerable.GetEnumerator() => GetEnumerator();
- internal int InternalGetHashCode(TKey key)
+ private int InternalGetHashCode(TKey key)
{
// Handle comparer implementations that throw when passed null
return (key == null) ? 0 : _comparer.GetHashCode(key) & 0x7FFFFFFF;
diff --git a/src/System.Linq/src/System/Linq/OrderBy.cs b/src/System.Linq/src/System/Linq/OrderBy.cs
index 1ba58cab46..b2dbbf0b4e 100644
--- a/src/System.Linq/src/System/Linq/OrderBy.cs
+++ b/src/System.Linq/src/System/Linq/OrderBy.cs
@@ -8,25 +8,17 @@ namespace System.Linq
{
public static partial class Enumerable
{
- public static IOrderedEnumerable<TSource> OrderBy<TSource, TKey>(this IEnumerable<TSource> source, Func<TSource, TKey> keySelector)
- {
- return new OrderedEnumerable<TSource, TKey>(source, keySelector, null, false, null);
- }
+ public static IOrderedEnumerable<TSource> OrderBy<TSource, TKey>(this IEnumerable<TSource> source, Func<TSource, TKey> keySelector) =>
+ new OrderedEnumerable<TSource, TKey>(source, keySelector, null, false, null);
- public static IOrderedEnumerable<TSource> OrderBy<TSource, TKey>(this IEnumerable<TSource> source, Func<TSource, TKey> keySelector, IComparer<TKey> comparer)
- {
- return new OrderedEnumerable<TSource, TKey>(source, keySelector, comparer, false, null);
- }
+ public static IOrderedEnumerable<TSource> OrderBy<TSource, TKey>(this IEnumerable<TSource> source, Func<TSource, TKey> keySelector, IComparer<TKey> comparer) =>
+ new OrderedEnumerable<TSource, TKey>(source, keySelector, comparer, false, null);
- public static IOrderedEnumerable<TSource> OrderByDescending<TSource, TKey>(this IEnumerable<TSource> source, Func<TSource, TKey> keySelector)
- {
- return new OrderedEnumerable<TSource, TKey>(source, keySelector, null, true, null);
- }
+ public static IOrderedEnumerable<TSource> OrderByDescending<TSource, TKey>(this IEnumerable<TSource> source, Func<TSource, TKey> keySelector) =>
+ new OrderedEnumerable<TSource, TKey>(source, keySelector, null, true, null);
- public static IOrderedEnumerable<TSource> OrderByDescending<TSource, TKey>(this IEnumerable<TSource> source, Func<TSource, TKey> keySelector, IComparer<TKey> comparer)
- {
- return new OrderedEnumerable<TSource, TKey>(source, keySelector, comparer, true, null);
- }
+ public static IOrderedEnumerable<TSource> OrderByDescending<TSource, TKey>(this IEnumerable<TSource> source, Func<TSource, TKey> keySelector, IComparer<TKey> comparer) =>
+ new OrderedEnumerable<TSource, TKey>(source, keySelector, comparer, true, null);
public static IOrderedEnumerable<TSource> ThenBy<TSource, TKey>(this IOrderedEnumerable<TSource> source, Func<TSource, TKey> keySelector)
{
diff --git a/src/System.Linq/src/System/Linq/OrderedEnumerable.cs b/src/System.Linq/src/System/Linq/OrderedEnumerable.cs
index 18b1bed5d2..d07b0dc515 100644
--- a/src/System.Linq/src/System/Linq/OrderedEnumerable.cs
+++ b/src/System.Linq/src/System/Linq/OrderedEnumerable.cs
@@ -11,15 +11,10 @@ namespace System.Linq
{
internal IEnumerable<TElement> _source;
- private int[] SortedMap(Buffer<TElement> buffer)
- {
- return GetEnumerableSorter().Sort(buffer._items, buffer._count);
- }
+ private int[] SortedMap(Buffer<TElement> buffer) => GetEnumerableSorter().Sort(buffer._items, buffer._count);
- private int[] SortedMap(Buffer<TElement> buffer, int minIdx, int maxIdx)
- {
- return GetEnumerableSorter().Sort(buffer._items, buffer._count, minIdx, maxIdx);
- }
+ private int[] SortedMap(Buffer<TElement> buffer, int minIdx, int maxIdx) =>
+ GetEnumerableSorter().Sort(buffer._items, buffer._count, minIdx, maxIdx);
public IEnumerator<TElement> GetEnumerator()
{
@@ -73,8 +68,7 @@ namespace System.Linq
public int GetCount(bool onlyIfCheap)
{
- IIListProvider<TElement> listProv = _source as IIListProvider<TElement>;
- if (listProv != null)
+ if (_source is IIListProvider<TElement> listProv)
{
return listProv.GetCount(onlyIfCheap);
}
@@ -187,39 +181,22 @@ namespace System.Linq
return (count <= maxIdx ? count : maxIdx + 1) - minIdx;
}
- private EnumerableSorter<TElement> GetEnumerableSorter()
- {
- return GetEnumerableSorter(null);
- }
+ private EnumerableSorter<TElement> GetEnumerableSorter() => GetEnumerableSorter(null);
internal abstract EnumerableSorter<TElement> GetEnumerableSorter(EnumerableSorter<TElement> next);
- internal CachingComparer<TElement> GetComparer()
- {
- return GetComparer(null);
- }
+ private CachingComparer<TElement> GetComparer() => GetComparer(null);
internal abstract CachingComparer<TElement> GetComparer(CachingComparer<TElement> childComparer);
- IEnumerator IEnumerable.GetEnumerator()
- {
- return GetEnumerator();
- }
+ IEnumerator IEnumerable.GetEnumerator() => GetEnumerator();
- IOrderedEnumerable<TElement> IOrderedEnumerable<TElement>.CreateOrderedEnumerable<TKey>(Func<TElement, TKey> keySelector, IComparer<TKey> comparer, bool descending)
- {
- return new OrderedEnumerable<TElement, TKey>(_source, keySelector, comparer, descending, this);
- }
+ IOrderedEnumerable<TElement> IOrderedEnumerable<TElement>.CreateOrderedEnumerable<TKey>(Func<TElement, TKey> keySelector, IComparer<TKey> comparer, bool descending) =>
+ new OrderedEnumerable<TElement, TKey>(_source, keySelector, comparer, @descending, this);
- public IPartition<TElement> Skip(int count)
- {
- return new OrderedPartition<TElement>(this, count, int.MaxValue);
- }
+ public IPartition<TElement> Skip(int count) => new OrderedPartition<TElement>(this, count, int.MaxValue);
- public IPartition<TElement> Take(int count)
- {
- return new OrderedPartition<TElement>(this, 0, count - 1);
- }
+ public IPartition<TElement> Take(int count) => new OrderedPartition<TElement>(this, 0, count - 1);
public TElement TryGetElementAt(int index, out bool found)
{
@@ -399,26 +376,16 @@ namespace System.Linq
internal sealed class OrderedEnumerable<TElement, TKey> : OrderedEnumerable<TElement>
{
- internal readonly OrderedEnumerable<TElement> _parent;
- internal readonly Func<TElement, TKey> _keySelector;
- internal readonly IComparer<TKey> _comparer;
- internal readonly bool _descending;
+ private readonly OrderedEnumerable<TElement> _parent;
+ private readonly Func<TElement, TKey> _keySelector;
+ private readonly IComparer<TKey> _comparer;
+ private readonly bool _descending;
internal OrderedEnumerable(IEnumerable<TElement> source, Func<TElement, TKey> keySelector, IComparer<TKey> comparer, bool descending, OrderedEnumerable<TElement> parent)
{
- if (source == null)
- {
- throw Error.ArgumentNull(nameof(source));
- }
-
- if (keySelector == null)
- {
- throw Error.ArgumentNull(nameof(keySelector));
- }
-
- _source = source;
+ _source = source ?? throw Error.ArgumentNull(nameof(source));
_parent = parent;
- _keySelector = keySelector;
+ _keySelector = keySelector ?? throw Error.ArgumentNull(nameof(keySelector));
_comparer = comparer ?? Comparer<TKey>.Default;
_descending = descending;
}
@@ -552,15 +519,10 @@ namespace System.Linq
return map;
}
- internal TElement ElementAt(TElement[] elements, int count, int idx)
- {
- return elements[QuickSelect(ComputeMap(elements, count), count - 1, idx)];
- }
+ internal TElement ElementAt(TElement[] elements, int count, int idx) =>
+ elements[QuickSelect(ComputeMap(elements, count), count - 1, idx)];
- private int CompareKeys(int index1, int index2)
- {
- return index1 == index2 ? 0 : CompareAnyKeys(index1, index2);
- }
+ private int CompareKeys(int index1, int index2) => index1 == index2 ? 0 : CompareAnyKeys(index1, index2);
private void QuickSort(int[] map, int left, int right)
{
@@ -764,11 +726,11 @@ namespace System.Linq
internal sealed class EnumerableSorter<TElement, TKey> : EnumerableSorter<TElement>
{
- internal readonly Func<TElement, TKey> _keySelector;
- internal readonly IComparer<TKey> _comparer;
- internal readonly bool _descending;
- internal readonly EnumerableSorter<TElement> _next;
- internal TKey[] _keys;
+ private readonly Func<TElement, TKey> _keySelector;
+ private readonly IComparer<TKey> _comparer;
+ private readonly bool _descending;
+ private readonly EnumerableSorter<TElement> _next;
+ private TKey[] _keys;
internal EnumerableSorter(Func<TElement, TKey> keySelector, IComparer<TKey> comparer, bool descending, EnumerableSorter<TElement> next)
{
@@ -786,10 +748,7 @@ namespace System.Linq
_keys[i] = _keySelector(elements[i]);
}
- if (_next != null)
- {
- _next.ComputeKeys(elements, count);
- }
+ _next?.ComputeKeys(elements, count);
}
internal override int CompareAnyKeys(int index1, int index2)
diff --git a/src/System.Linq/src/System/Linq/Partition.cs b/src/System.Linq/src/System/Linq/Partition.cs
index e5f70e15be..422b8ed9d2 100644
--- a/src/System.Linq/src/System/Linq/Partition.cs
+++ b/src/System.Linq/src/System/Linq/Partition.cs
@@ -108,10 +108,7 @@ namespace System.Linq
[ExcludeFromCodeCoverage] // Shouldn't be called, and as undefined can return or throw anything anyway.
object IEnumerator.Current => default(TElement);
- void IEnumerator.Reset()
- {
- throw Error.NotSupported();
- }
+ void IEnumerator.Reset() => throw Error.NotSupported();
void IDisposable.Dispose()
{
@@ -160,15 +157,9 @@ namespace System.Linq
_maxIndexInclusive = maxIdxInclusive;
}
- public IEnumerator<TElement> GetEnumerator()
- {
- return _source.GetEnumerator(_minIndexInclusive, _maxIndexInclusive);
- }
+ public IEnumerator<TElement> GetEnumerator() => _source.GetEnumerator(_minIndexInclusive, _maxIndexInclusive);
- IEnumerator IEnumerable.GetEnumerator()
- {
- return GetEnumerator();
- }
+ IEnumerator IEnumerable.GetEnumerator() => GetEnumerator();
public IPartition<TElement> Skip(int count)
{
@@ -198,30 +189,16 @@ namespace System.Linq
return default(TElement);
}
- public TElement TryGetFirst(out bool found)
- {
- return _source.TryGetElementAt(_minIndexInclusive, out found);
- }
+ public TElement TryGetFirst(out bool found) => _source.TryGetElementAt(_minIndexInclusive, out found);
- public TElement TryGetLast(out bool found)
- {
- return _source.TryGetLast(_minIndexInclusive, _maxIndexInclusive, out found);
- }
+ public TElement TryGetLast(out bool found) =>
+ _source.TryGetLast(_minIndexInclusive, _maxIndexInclusive, out found);
- public TElement[] ToArray()
- {
- return _source.ToArray(_minIndexInclusive, _maxIndexInclusive);
- }
+ public TElement[] ToArray() => _source.ToArray(_minIndexInclusive, _maxIndexInclusive);
- public List<TElement> ToList()
- {
- return _source.ToList(_minIndexInclusive, _maxIndexInclusive);
- }
+ public List<TElement> ToList() => _source.ToList(_minIndexInclusive, _maxIndexInclusive);
- public int GetCount(bool onlyIfCheap)
- {
- return _source.GetCount(_minIndexInclusive, _maxIndexInclusive, onlyIfCheap);
- }
+ public int GetCount(bool onlyIfCheap) => _source.GetCount(_minIndexInclusive, _maxIndexInclusive, onlyIfCheap);
}
public static partial class Enumerable
@@ -246,10 +223,8 @@ namespace System.Linq
_maxIndexInclusive = maxIndexInclusive;
}
- public override Iterator<TSource> Clone()
- {
- return new ListPartition<TSource>(_source, _minIndexInclusive, _maxIndexInclusive);
- }
+ public override Iterator<TSource> Clone() =>
+ new ListPartition<TSource>(_source, _minIndexInclusive, _maxIndexInclusive);
public override bool MoveNext()
{
@@ -268,10 +243,8 @@ namespace System.Linq
return false;
}
- public override IEnumerable<TResult> Select<TResult>(Func<TSource, TResult> selector)
- {
- return new SelectListPartitionIterator<TSource, TResult>(_source, selector, _minIndexInclusive, _maxIndexInclusive);
- }
+ public override IEnumerable<TResult> Select<TResult>(Func<TSource, TResult> selector) =>
+ new SelectListPartitionIterator<TSource, TResult>(_source, selector, _minIndexInclusive, _maxIndexInclusive);
public IPartition<TSource> Skip(int count)
{
@@ -371,10 +344,7 @@ namespace System.Linq
return list;
}
- public int GetCount(bool onlyIfCheap)
- {
- return Count;
- }
+ public int GetCount(bool onlyIfCheap) => Count;
}
/// <summary>
@@ -412,10 +382,8 @@ namespace System.Linq
private int Limit => unchecked((_maxIndexInclusive + 1) - _minIndexInclusive); // This is that upper bound.
- public override Iterator<TSource> Clone()
- {
- return new EnumerablePartition<TSource>(_source, _minIndexInclusive, _maxIndexInclusive);
- }
+ public override Iterator<TSource> Clone() =>
+ new EnumerablePartition<TSource>(_source, _minIndexInclusive, _maxIndexInclusive);
public override void Dispose()
{
@@ -507,10 +475,8 @@ namespace System.Linq
return false;
}
- public override IEnumerable<TResult> Select<TResult>(Func<TSource, TResult> selector)
- {
- return new SelectIPartitionIterator<TSource, TResult>(this, selector);
- }
+ public override IEnumerable<TResult> Select<TResult>(Func<TSource, TResult> selector) =>
+ new SelectIPartitionIterator<TSource, TResult>(this, selector);
public IPartition<TSource> Skip(int count)
{
diff --git a/src/System.Linq/src/System/Linq/Range.cs b/src/System.Linq/src/System/Linq/Range.cs
index 4050eac292..a0fe4622de 100644
--- a/src/System.Linq/src/System/Linq/Range.cs
+++ b/src/System.Linq/src/System/Linq/Range.cs
@@ -40,10 +40,7 @@ namespace System.Linq
_end = unchecked(start + count);
}
- public override Iterator<int> Clone()
- {
- return new RangeIterator(_start, _end - _start);
- }
+ public override Iterator<int> Clone() => new RangeIterator(_start, _end - _start);
public override bool MoveNext()
{
@@ -101,10 +98,7 @@ namespace System.Linq
return list;
}
- public int GetCount(bool onlyIfCheap)
- {
- return unchecked(_end - _start);
- }
+ public int GetCount(bool onlyIfCheap) => unchecked(_end - _start);
public IPartition<int> Skip(int count)
{
diff --git a/src/System.Linq/src/System/Linq/Repeat.cs b/src/System.Linq/src/System/Linq/Repeat.cs
index 9581876997..0eeab785a7 100644
--- a/src/System.Linq/src/System/Linq/Repeat.cs
+++ b/src/System.Linq/src/System/Linq/Repeat.cs
@@ -69,10 +69,8 @@ namespace System.Linq
return false;
}
- public override IEnumerable<TResult2> Select<TResult2>(Func<TResult, TResult2> selector)
- {
- return new SelectIPartitionIterator<TResult, TResult2>(this, selector);
- }
+ public override IEnumerable<TResult2> Select<TResult2>(Func<TResult, TResult2> selector) =>
+ new SelectIPartitionIterator<TResult, TResult2>(this, selector);
public TResult[] ToArray()
{
@@ -96,10 +94,7 @@ namespace System.Linq
return list;
}
- public int GetCount(bool onlyIfCheap)
- {
- return _count;
- }
+ public int GetCount(bool onlyIfCheap) => _count;
public IPartition<TResult> Skip(int count)
{
diff --git a/src/System.Linq/src/System/Linq/Reverse.cs b/src/System.Linq/src/System/Linq/Reverse.cs
index 237393b527..e68a4f42ee 100644
--- a/src/System.Linq/src/System/Linq/Reverse.cs
+++ b/src/System.Linq/src/System/Linq/Reverse.cs
@@ -35,10 +35,7 @@ namespace System.Linq
_source = source;
}
- public override Iterator<TSource> Clone()
- {
- return new ReverseIterator<TSource>(_source);
- }
+ public override Iterator<TSource> Clone() => new ReverseIterator<TSource>(_source);
public override bool MoveNext()
{
@@ -91,7 +88,7 @@ namespace System.Linq
public TSource[] ToArray()
{
TSource[] array = _source.ToArray();
- Array.Reverse<TSource>(array);
+ Array.Reverse(array);
return array;
}
@@ -106,15 +103,19 @@ namespace System.Linq
{
if (onlyIfCheap)
{
- IIListProvider<TSource> listProv = _source as IIListProvider<TSource>;
- if (listProv != null)
+ switch (_source)
{
- return listProv.GetCount(onlyIfCheap: true);
- }
+ case IIListProvider<TSource> listProv:
+ return listProv.GetCount(onlyIfCheap: true);
- if (!(_source is ICollection<TSource>) && !(_source is ICollection))
- {
- return -1;
+ case ICollection<TSource> colT:
+ return colT.Count;
+
+ case ICollection col:
+ return col.Count;
+
+ default:
+ return -1;
}
}
diff --git a/src/System.Linq/src/System/Linq/Select.cs b/src/System.Linq/src/System/Linq/Select.cs
index 179f894a77..b1c9ae5c95 100644
--- a/src/System.Linq/src/System/Linq/Select.cs
+++ b/src/System.Linq/src/System/Linq/Select.cs
@@ -10,7 +10,8 @@ namespace System.Linq
{
public static partial class Enumerable
{
- public static IEnumerable<TResult> Select<TSource, TResult>(this IEnumerable<TSource> source, Func<TSource, TResult> selector)
+ public static IEnumerable<TResult> Select<TSource, TResult>(
+ this IEnumerable<TSource> source, Func<TSource, TResult> selector)
{
if (source == null)
{
@@ -22,25 +23,21 @@ namespace System.Linq
throw Error.ArgumentNull(nameof(selector));
}
- Iterator<TSource> iterator = source as Iterator<TSource>;
- if (iterator != null)
+ if (source is Iterator<TSource> iterator)
{
return iterator.Select(selector);
}
- IList<TSource> ilist = source as IList<TSource>;
- if (ilist != null)
+ if (source is IList<TSource> ilist)
{
- TSource[] array = source as TSource[];
- if (array != null)
+ if (source is TSource[] array)
{
return array.Length == 0 ?
EmptyPartition<TResult>.Instance :
new SelectArrayIterator<TSource, TResult>(array, selector);
}
- List<TSource> list = source as List<TSource>;
- if (list != null)
+ if (source is List<TSource> list)
{
return new SelectListIterator<TSource, TResult>(list, selector);
}
@@ -48,10 +45,11 @@ namespace System.Linq
return new SelectIListIterator<TSource, TResult>(ilist, selector);
}
- IPartition<TSource> partition = source as IPartition<TSource>;
- if (partition != null)
+ if (source is IPartition<TSource> partition)
{
- return new SelectIPartitionIterator<TSource, TResult>(partition, selector);
+ return partition is EmptyPartition<TSource>
+ ? EmptyPartition<TResult>.Instance
+ : new SelectIPartitionIterator<TSource, TResult>(partition, selector);
}
return new SelectEnumerableIterator<TSource, TResult>(source, selector);
@@ -91,7 +89,7 @@ namespace System.Linq
/// </summary>
/// <typeparam name="TSource">The type of the source enumerable.</typeparam>
/// <typeparam name="TResult">The type of the mapped items.</typeparam>
- internal sealed class SelectEnumerableIterator<TSource, TResult> : Iterator<TResult>, IIListProvider<TResult>
+ private sealed class SelectEnumerableIterator<TSource, TResult> : Iterator<TResult>, IIListProvider<TResult>
{
private readonly IEnumerable<TSource> _source;
private readonly Func<TSource, TResult> _selector;
@@ -105,10 +103,8 @@ namespace System.Linq
_selector = selector;
}
- public override Iterator<TResult> Clone()
- {
- return new SelectEnumerableIterator<TSource, TResult>(_source, _selector);
- }
+ public override Iterator<TResult> Clone() =>
+ new SelectEnumerableIterator<TSource, TResult>(_source, _selector);
public override void Dispose()
{
@@ -143,10 +139,8 @@ namespace System.Linq
return false;
}
- public override IEnumerable<TResult2> Select<TResult2>(Func<TResult, TResult2> selector)
- {
- return new SelectEnumerableIterator<TSource, TResult2>(_source, CombineSelectors(_selector, selector));
- }
+ public override IEnumerable<TResult2> Select<TResult2>(Func<TResult, TResult2> selector) =>
+ new SelectEnumerableIterator<TSource, TResult2>(_source, CombineSelectors(_selector, selector));
public TResult[] ToArray()
{
@@ -202,7 +196,7 @@ namespace System.Linq
/// </summary>
/// <typeparam name="TSource">The type of the source array.</typeparam>
/// <typeparam name="TResult">The type of the mapped items.</typeparam>
- internal sealed class SelectArrayIterator<TSource, TResult> : Iterator<TResult>, IPartition<TResult>
+ private sealed class SelectArrayIterator<TSource, TResult> : Iterator<TResult>, IPartition<TResult>
{
private readonly TSource[] _source;
private readonly Func<TSource, TResult> _selector;
@@ -216,10 +210,7 @@ namespace System.Linq
_selector = selector;
}
- public override Iterator<TResult> Clone()
- {
- return new SelectArrayIterator<TSource, TResult>(_source, _selector);
- }
+ public override Iterator<TResult> Clone() => new SelectArrayIterator<TSource, TResult>(_source, _selector);
public override bool MoveNext()
{
@@ -234,10 +225,8 @@ namespace System.Linq
return true;
}
- public override IEnumerable<TResult2> Select<TResult2>(Func<TResult, TResult2> selector)
- {
- return new SelectArrayIterator<TSource, TResult2>(_source, CombineSelectors(_selector, selector));
- }
+ public override IEnumerable<TResult2> Select<TResult2>(Func<TResult, TResult2> selector) =>
+ new SelectArrayIterator<TSource, TResult2>(_source, CombineSelectors(_selector, selector));
public TResult[] ToArray()
{
@@ -293,10 +282,8 @@ namespace System.Linq
return new SelectListPartitionIterator<TSource, TResult>(_source, _selector, count, int.MaxValue);
}
- public IPartition<TResult> Take(int count)
- {
- return count >= _source.Length ? (IPartition<TResult>)this : new SelectListPartitionIterator<TSource, TResult>(_source, _selector, 0, count - 1);
- }
+ public IPartition<TResult> Take(int count) =>
+ count >= _source.Length ? (IPartition<TResult>)this : new SelectListPartitionIterator<TSource, TResult>(_source, _selector, 0, count - 1);
public TResult TryGetElementAt(int index, out bool found)
{
@@ -332,7 +319,7 @@ namespace System.Linq
/// </summary>
/// <typeparam name="TSource">The type of the source list.</typeparam>
/// <typeparam name="TResult">The type of the mapped items.</typeparam>
- internal sealed class SelectListIterator<TSource, TResult> : Iterator<TResult>, IPartition<TResult>
+ private sealed class SelectListIterator<TSource, TResult> : Iterator<TResult>, IPartition<TResult>
{
private readonly List<TSource> _source;
private readonly Func<TSource, TResult> _selector;
@@ -346,10 +333,7 @@ namespace System.Linq
_selector = selector;
}
- public override Iterator<TResult> Clone()
- {
- return new SelectListIterator<TSource, TResult>(_source, _selector);
- }
+ public override Iterator<TResult> Clone() => new SelectListIterator<TSource, TResult>(_source, _selector);
public override bool MoveNext()
{
@@ -373,10 +357,8 @@ namespace System.Linq
return false;
}
- public override IEnumerable<TResult2> Select<TResult2>(Func<TResult, TResult2> selector)
- {
- return new SelectListIterator<TSource, TResult2>(_source, CombineSelectors(_selector, selector));
- }
+ public override IEnumerable<TResult2> Select<TResult2>(Func<TResult, TResult2> selector) =>
+ new SelectListIterator<TSource, TResult2>(_source, CombineSelectors(_selector, selector));
public TResult[] ToArray()
{
@@ -431,10 +413,8 @@ namespace System.Linq
return new SelectListPartitionIterator<TSource, TResult>(_source, _selector, count, int.MaxValue);
}
- public IPartition<TResult> Take(int count)
- {
- return new SelectListPartitionIterator<TSource, TResult>(_source, _selector, 0, count - 1);
- }
+ public IPartition<TResult> Take(int count) =>
+ new SelectListPartitionIterator<TSource, TResult>(_source, _selector, 0, count - 1);
public TResult TryGetElementAt(int index, out bool found)
{
@@ -479,7 +459,7 @@ namespace System.Linq
/// </summary>
/// <typeparam name="TSource">The type of the source list.</typeparam>
/// <typeparam name="TResult">The type of the mapped items.</typeparam>
- internal sealed class SelectIListIterator<TSource, TResult> : Iterator<TResult>, IPartition<TResult>
+ private sealed class SelectIListIterator<TSource, TResult> : Iterator<TResult>, IPartition<TResult>
{
private readonly IList<TSource> _source;
private readonly Func<TSource, TResult> _selector;
@@ -493,10 +473,7 @@ namespace System.Linq
_selector = selector;
}
- public override Iterator<TResult> Clone()
- {
- return new SelectIListIterator<TSource, TResult>(_source, _selector);
- }
+ public override Iterator<TResult> Clone() => new SelectIListIterator<TSource, TResult>(_source, _selector);
public override bool MoveNext()
{
@@ -531,10 +508,8 @@ namespace System.Linq
base.Dispose();
}
- public override IEnumerable<TResult2> Select<TResult2>(Func<TResult, TResult2> selector)
- {
- return new SelectIListIterator<TSource, TResult2>(_source, CombineSelectors(_selector, selector));
- }
+ public override IEnumerable<TResult2> Select<TResult2>(Func<TResult, TResult2> selector) =>
+ new SelectIListIterator<TSource, TResult2>(_source, CombineSelectors(_selector, selector));
public TResult[] ToArray()
{
@@ -589,10 +564,8 @@ namespace System.Linq
return new SelectListPartitionIterator<TSource, TResult>(_source, _selector, count, int.MaxValue);
}
- public IPartition<TResult> Take(int count)
- {
- return new SelectListPartitionIterator<TSource, TResult>(_source, _selector, 0, count - 1);
- }
+ public IPartition<TResult> Take(int count) =>
+ new SelectListPartitionIterator<TSource, TResult>(_source, _selector, 0, count - 1);
public TResult TryGetElementAt(int index, out bool found)
{
@@ -637,7 +610,7 @@ namespace System.Linq
/// </summary>
/// <typeparam name="TSource">The type of the source partition.</typeparam>
/// <typeparam name="TResult">The type of the mapped items.</typeparam>
- internal sealed class SelectIPartitionIterator<TSource, TResult> : Iterator<TResult>, IPartition<TResult>
+ private sealed class SelectIPartitionIterator<TSource, TResult> : Iterator<TResult>, IPartition<TResult>
{
private readonly IPartition<TSource> _source;
private readonly Func<TSource, TResult> _selector;
@@ -651,10 +624,8 @@ namespace System.Linq
_selector = selector;
}
- public override Iterator<TResult> Clone()
- {
- return new SelectIPartitionIterator<TSource, TResult>(_source, _selector);
- }
+ public override Iterator<TResult> Clone() =>
+ new SelectIPartitionIterator<TSource, TResult>(_source, _selector);
public override bool MoveNext()
{
@@ -689,10 +660,8 @@ namespace System.Linq
base.Dispose();
}
- public override IEnumerable<TResult2> Select<TResult2>(Func<TResult, TResult2> selector)
- {
- return new SelectIPartitionIterator<TSource, TResult2>(_source, CombineSelectors(_selector, selector));
- }
+ public override IEnumerable<TResult2> Select<TResult2>(Func<TResult, TResult2> selector) =>
+ new SelectIPartitionIterator<TSource, TResult2>(_source, CombineSelectors(_selector, selector));
public IPartition<TResult> Skip(int count)
{
@@ -700,10 +669,8 @@ namespace System.Linq
return new SelectIPartitionIterator<TSource, TResult>(_source.Skip(count), _selector);
}
- public IPartition<TResult> Take(int count)
- {
- return new SelectIPartitionIterator<TSource, TResult>(_source.Take(count), _selector);
- }
+ public IPartition<TResult> Take(int count) =>
+ new SelectIPartitionIterator<TSource, TResult>(_source.Take(count), _selector);
public TResult TryGetElementAt(int index, out bool found)
{
@@ -836,10 +803,8 @@ namespace System.Linq
_maxIndexInclusive = maxIndexInclusive;
}
- public override Iterator<TResult> Clone()
- {
- return new SelectListPartitionIterator<TSource, TResult>(_source, _selector, _minIndexInclusive, _maxIndexInclusive);
- }
+ public override Iterator<TResult> Clone() =>
+ new SelectListPartitionIterator<TSource, TResult>(_source, _selector, _minIndexInclusive, _maxIndexInclusive);
public override bool MoveNext()
{
@@ -858,10 +823,8 @@ namespace System.Linq
return false;
}
- public override IEnumerable<TResult2> Select<TResult2>(Func<TResult, TResult2> selector)
- {
- return new SelectListPartitionIterator<TSource, TResult2>(_source, CombineSelectors(_selector, selector), _minIndexInclusive, _maxIndexInclusive);
- }
+ public override IEnumerable<TResult2> Select<TResult2>(Func<TResult, TResult2> selector) =>
+ new SelectListPartitionIterator<TSource, TResult2>(_source, CombineSelectors(_selector, selector), _minIndexInclusive, _maxIndexInclusive);
public IPartition<TResult> Skip(int count)
{
diff --git a/src/System.Linq/src/System/Linq/SequenceEqual.cs b/src/System.Linq/src/System/Linq/SequenceEqual.cs
index aafee79781..aa4aaf31e2 100644
--- a/src/System.Linq/src/System/Linq/SequenceEqual.cs
+++ b/src/System.Linq/src/System/Linq/SequenceEqual.cs
@@ -8,10 +8,8 @@ namespace System.Linq
{
public static partial class Enumerable
{
- public static bool SequenceEqual<TSource>(this IEnumerable<TSource> first, IEnumerable<TSource> second)
- {
- return SequenceEqual(first, second, null);
- }
+ public static bool SequenceEqual<TSource>(this IEnumerable<TSource> first, IEnumerable<TSource> second) =>
+ SequenceEqual(first, second, null);
public static bool SequenceEqual<TSource>(this IEnumerable<TSource> first, IEnumerable<TSource> second, IEqualityComparer<TSource> comparer)
{
@@ -30,14 +28,9 @@ namespace System.Linq
throw Error.ArgumentNull(nameof(second));
}
- ICollection<TSource> firstCol = first as ICollection<TSource>;
- if (firstCol != null)
+ if (first is ICollection<TSource> firstCol && second is ICollection<TSource> secondCol && firstCol.Count != secondCol.Count)
{
- ICollection<TSource> secondCol = second as ICollection<TSource>;
- if (secondCol != null && firstCol.Count != secondCol.Count)
- {
- return false;
- }
+ return false;
}
using (IEnumerator<TSource> e1 = first.GetEnumerator())
diff --git a/src/System.Linq/src/System/Linq/Set.cs b/src/System.Linq/src/System/Linq/Set.cs
index 4945369649..b34ccd15d7 100644
--- a/src/System.Linq/src/System/Linq/Set.cs
+++ b/src/System.Linq/src/System/Linq/Set.cs
@@ -214,16 +214,12 @@ namespace System.Linq
/// </summary>
/// <param name="value">The value to hash.</param>
/// <returns>The lower 31 bits of the value's hash code.</returns>
- private int InternalGetHashCode(TElement value)
- {
- // Handle comparer implementations that throw when passed null
- return (value == null) ? 0 : _comparer.GetHashCode(value) & 0x7FFFFFFF;
- }
+ private int InternalGetHashCode(TElement value) => value == null ? 0 : _comparer.GetHashCode(value) & 0x7FFFFFFF;
/// <summary>
/// An entry in the hash set.
/// </summary>
- internal struct Slot
+ private struct Slot
{
/// <summary>
/// The hash code of the item.
diff --git a/src/System.Linq/src/System/Linq/Single.cs b/src/System.Linq/src/System/Linq/Single.cs
index a8e4005e78..3874f81042 100644
--- a/src/System.Linq/src/System/Linq/Single.cs
+++ b/src/System.Linq/src/System/Linq/Single.cs
@@ -15,13 +15,14 @@ namespace System.Linq
throw Error.ArgumentNull(nameof(source));
}
- IList<TSource> list = source as IList<TSource>;
- if (list != null)
+ if (source is IList<TSource> list)
{
switch (list.Count)
{
- case 0: throw Error.NoElements();
- case 1: return list[0];
+ case 0:
+ throw Error.NoElements();
+ case 1:
+ return list[0];
}
}
else
@@ -86,13 +87,14 @@ namespace System.Linq
throw Error.ArgumentNull(nameof(source));
}
- IList<TSource> list = source as IList<TSource>;
- if (list != null)
+ if (source is IList<TSource> list)
{
switch (list.Count)
{
- case 0: return default(TSource);
- case 1: return list[0];
+ case 0:
+ return default(TSource);
+ case 1:
+ return list[0];
}
}
else
diff --git a/src/System.Linq/src/System/Linq/SingleLinkedNode.cs b/src/System.Linq/src/System/Linq/SingleLinkedNode.cs
index 79976bab8e..dd85bd86e8 100644
--- a/src/System.Linq/src/System/Linq/SingleLinkedNode.cs
+++ b/src/System.Linq/src/System/Linq/SingleLinkedNode.cs
@@ -98,7 +98,7 @@ namespace System.Linq
/// Returns an <see cref="T:TSource[]"/> that contains the items of this node's singly-linked list in reverse.
/// </summary>
/// <param name="count">The number of items in this node.</param>
- public TSource[] ToArray(int count)
+ private TSource[] ToArray(int count)
{
Debug.Assert(count == GetCount());
diff --git a/src/System.Linq/src/System/Linq/Skip.cs b/src/System.Linq/src/System/Linq/Skip.cs
index 2edd30ca59..8431a90d45 100644
--- a/src/System.Linq/src/System/Linq/Skip.cs
+++ b/src/System.Linq/src/System/Linq/Skip.cs
@@ -27,17 +27,12 @@ namespace System.Linq
count = 0;
}
- else
+ else if (source is IPartition<TSource> partition)
{
- IPartition<TSource> partition = source as IPartition<TSource>;
- if (partition != null)
- {
- return partition.Skip(count);
- }
+ return partition.Skip(count);
}
- IList<TSource> sourceList = source as IList<TSource>;
- if (sourceList != null)
+ if (source is IList<TSource> sourceList)
{
return new ListPartition<TSource>(sourceList, count, int.MaxValue);
}
diff --git a/src/System.Linq/src/System/Linq/Take.cs b/src/System.Linq/src/System/Linq/Take.cs
index a975dd4614..7a53ece2b1 100644
--- a/src/System.Linq/src/System/Linq/Take.cs
+++ b/src/System.Linq/src/System/Linq/Take.cs
@@ -21,14 +21,12 @@ namespace System.Linq
return EmptyPartition<TSource>.Instance;
}
- IPartition<TSource> partition = source as IPartition<TSource>;
- if (partition != null)
+ if (source is IPartition<TSource> partition)
{
return partition.Take(count);
}
- IList<TSource> sourceList = source as IList<TSource>;
- if (sourceList != null)
+ if (source is IList<TSource> sourceList)
{
return new ListPartition<TSource>(sourceList, 0, count - 1);
}
diff --git a/src/System.Linq/src/System/Linq/ToCollection.cs b/src/System.Linq/src/System/Linq/ToCollection.cs
index c9e343156d..0ed6184b1a 100644
--- a/src/System.Linq/src/System/Linq/ToCollection.cs
+++ b/src/System.Linq/src/System/Linq/ToCollection.cs
@@ -15,8 +15,9 @@ namespace System.Linq
throw Error.ArgumentNull(nameof(source));
}
- IIListProvider<TSource> arrayProvider = source as IIListProvider<TSource>;
- return arrayProvider != null ? arrayProvider.ToArray() : EnumerableHelpers.ToArray(source);
+ return source is IIListProvider<TSource> arrayProvider
+ ? arrayProvider.ToArray()
+ : EnumerableHelpers.ToArray(source);
}
public static List<TSource> ToList<TSource>(this IEnumerable<TSource> source)
@@ -26,14 +27,11 @@ namespace System.Linq
throw Error.ArgumentNull(nameof(source));
}
- IIListProvider<TSource> listProvider = source as IIListProvider<TSource>;
- return listProvider != null ? listProvider.ToList() : new List<TSource>(source);
+ return source is IIListProvider<TSource> listProvider ? listProvider.ToList() : new List<TSource>(source);
}
- public static Dictionary<TKey, TSource> ToDictionary<TSource, TKey>(this IEnumerable<TSource> source, Func<TSource, TKey> keySelector)
- {
- return ToDictionary(source, keySelector, null);
- }
+ public static Dictionary<TKey, TSource> ToDictionary<TSource, TKey>(this IEnumerable<TSource> source, Func<TSource, TKey> keySelector) =>
+ ToDictionary(source, keySelector, null);
public static Dictionary<TKey, TSource> ToDictionary<TSource, TKey>(this IEnumerable<TSource> source, Func<TSource, TKey> keySelector, IEqualityComparer<TKey> comparer)
{
@@ -48,8 +46,7 @@ namespace System.Linq
}
int capacity = 0;
- ICollection<TSource> collection = source as ICollection<TSource>;
- if (collection != null)
+ if (source is ICollection<TSource> collection)
{
capacity = collection.Count;
if (capacity == 0)
@@ -57,14 +54,12 @@ namespace System.Linq
return new Dictionary<TKey, TSource>(comparer);
}
- TSource[] array = collection as TSource[];
- if (array != null)
+ if (collection is TSource[] array)
{
return ToDictionary(array, keySelector, comparer);
}
- List<TSource> list = collection as List<TSource>;
- if (list != null)
+ if (collection is List<TSource> list)
{
return ToDictionary(list, keySelector, comparer);
}
@@ -101,10 +96,8 @@ namespace System.Linq
return d;
}
- public static Dictionary<TKey, TElement> ToDictionary<TSource, TKey, TElement>(this IEnumerable<TSource> source, Func<TSource, TKey> keySelector, Func<TSource, TElement> elementSelector)
- {
- return ToDictionary(source, keySelector, elementSelector, null);
- }
+ public static Dictionary<TKey, TElement> ToDictionary<TSource, TKey, TElement>(this IEnumerable<TSource> source, Func<TSource, TKey> keySelector, Func<TSource, TElement> elementSelector) =>
+ ToDictionary(source, keySelector, elementSelector, null);
public static Dictionary<TKey, TElement> ToDictionary<TSource, TKey, TElement>(this IEnumerable<TSource> source, Func<TSource, TKey> keySelector, Func<TSource, TElement> elementSelector, IEqualityComparer<TKey> comparer)
{
@@ -124,8 +117,7 @@ namespace System.Linq
}
int capacity = 0;
- ICollection<TSource> collection = source as ICollection<TSource>;
- if (collection != null)
+ if (source is ICollection<TSource> collection)
{
capacity = collection.Count;
if (capacity == 0)
@@ -133,14 +125,12 @@ namespace System.Linq
return new Dictionary<TKey, TElement>(comparer);
}
- TSource[] array = collection as TSource[];
- if (array != null)
+ if (collection is TSource[] array)
{
return ToDictionary(array, keySelector, elementSelector, comparer);
}
- List<TSource> list = collection as List<TSource>;
- if (list != null)
+ if (collection is List<TSource> list)
{
return ToDictionary(list, keySelector, elementSelector, comparer);
}
@@ -183,7 +173,7 @@ namespace System.Linq
{
if (source == null)
{
- throw new ArgumentNullException(nameof(source));
+ throw Error.ArgumentNull(nameof(source));
}
// Don't pre-allocate based on knowledge of size, as potentially many elements will be dropped.
diff --git a/src/System.Linq/src/System/Linq/Union.cs b/src/System.Linq/src/System/Linq/Union.cs
index 6862d374b3..6136f93ea8 100644
--- a/src/System.Linq/src/System/Linq/Union.cs
+++ b/src/System.Linq/src/System/Linq/Union.cs
@@ -24,8 +24,7 @@ namespace System.Linq
throw Error.ArgumentNull(nameof(second));
}
- UnionIterator<TSource> union = first as UnionIterator<TSource>;
- return union != null && AreEqualityComparersEqual(comparer, union._comparer) ? union.Union(second) : new UnionIterator2<TSource>(first, second, comparer);
+ return first is UnionIterator<TSource> union && AreEqualityComparersEqual(comparer, union._comparer) ? union.Union(second) : new UnionIterator2<TSource>(first, second, comparer);
}
/// <summary>
@@ -38,12 +37,12 @@ namespace System.Linq
private IEnumerator<TSource> _enumerator;
private Set<TSource> _set;
- public UnionIterator(IEqualityComparer<TSource> comparer)
+ protected UnionIterator(IEqualityComparer<TSource> comparer)
{
_comparer = comparer;
}
- public override sealed void Dispose()
+ public sealed override void Dispose()
{
if (_enumerator != null)
{
@@ -59,17 +58,14 @@ namespace System.Linq
internal abstract UnionIterator<TSource> Union(IEnumerable<TSource> next);
- protected void SetEnumerator(IEnumerator<TSource> enumerator)
+ private void SetEnumerator(IEnumerator<TSource> enumerator)
{
- if (_enumerator != null)
- {
- _enumerator.Dispose();
- }
+ _enumerator?.Dispose();
_enumerator = enumerator;
}
- protected void StoreFirst()
+ private void StoreFirst()
{
Set<TSource> set = new Set<TSource>(_comparer);
TSource element = _enumerator.Current;
@@ -78,7 +74,7 @@ namespace System.Linq
_set = set;
}
- protected bool GetNext()
+ private bool GetNext()
{
Set<TSource> set = _set;
Debug.Assert(set != null);
@@ -151,20 +147,11 @@ namespace System.Linq
}
}
- public TSource[] ToArray()
- {
- return FillSet().ToArray();
- }
+ public TSource[] ToArray() => FillSet().ToArray();
- public List<TSource> ToList()
- {
- return FillSet().ToList();
- }
+ public List<TSource> ToList() => FillSet().ToList();
- public int GetCount(bool onlyIfCheap)
- {
- return onlyIfCheap ? -1 : FillSet().Count;
- }
+ public int GetCount(bool onlyIfCheap) => onlyIfCheap ? -1 : FillSet().Count;
}
/// <summary>
diff --git a/src/System.Linq/src/System/Linq/Utilities.cs b/src/System.Linq/src/System/Linq/Utilities.cs
index 7c226f0a52..c6fb888bc8 100644
--- a/src/System.Linq/src/System/Linq/Utilities.cs
+++ b/src/System.Linq/src/System/Linq/Utilities.cs
@@ -54,10 +54,8 @@ namespace System.Linq
/// second predicates return true. If the first predicate returns <c>false</c>,
/// the second predicate will not be run.
/// </returns>
- public static Func<TSource, bool> CombinePredicates<TSource>(Func<TSource, bool> predicate1, Func<TSource, bool> predicate2)
- {
- return x => predicate1(x) && predicate2(x);
- }
+ public static Func<TSource, bool> CombinePredicates<TSource>(Func<TSource, bool> predicate1, Func<TSource, bool> predicate2) =>
+ x => predicate1(x) && predicate2(x);
/// <summary>
/// Combines two selectors.
@@ -70,9 +68,7 @@ namespace System.Linq
/// <returns>
/// A new selector that represents the composition of the first selector with the second selector.
/// </returns>
- public static Func<TSource, TResult> CombineSelectors<TSource, TMiddle, TResult>(Func<TSource, TMiddle> selector1, Func<TMiddle, TResult> selector2)
- {
- return x => selector2(selector1(x));
- }
+ public static Func<TSource, TResult> CombineSelectors<TSource, TMiddle, TResult>(Func<TSource, TMiddle> selector1, Func<TMiddle, TResult> selector2) =>
+ x => selector2(selector1(x));
}
}
diff --git a/src/System.Linq/src/System/Linq/Where.cs b/src/System.Linq/src/System/Linq/Where.cs
index be64d0345e..34124d1167 100644
--- a/src/System.Linq/src/System/Linq/Where.cs
+++ b/src/System.Linq/src/System/Linq/Where.cs
@@ -22,22 +22,19 @@ namespace System.Linq
throw Error.ArgumentNull(nameof(predicate));
}
- Iterator<TSource> iterator = source as Iterator<TSource>;
- if (iterator != null)
+ if (source is Iterator<TSource> iterator)
{
return iterator.Where(predicate);
}
- TSource[] array = source as TSource[];
- if (array != null)
+ if (source is TSource[] array)
{
return array.Length == 0 ?
(IEnumerable<TSource>)EmptyPartition<TSource>.Instance :
new WhereArrayIterator<TSource>(array, predicate);
}
- List<TSource> list = source as List<TSource>;
- if (list != null)
+ if (source is List<TSource> list)
{
return new WhereListIterator<TSource>(list, predicate);
}
@@ -81,7 +78,7 @@ namespace System.Linq
/// An iterator that filters each item of an <see cref="IEnumerable{TSource}"/>.
/// </summary>
/// <typeparam name="TSource">The type of the source enumerable.</typeparam>
- internal sealed class WhereEnumerableIterator<TSource> : Iterator<TSource>, IIListProvider<TSource>
+ private sealed class WhereEnumerableIterator<TSource> : Iterator<TSource>, IIListProvider<TSource>
{
private readonly IEnumerable<TSource> _source;
private readonly Func<TSource, bool> _predicate;
@@ -95,10 +92,7 @@ namespace System.Linq
_predicate = predicate;
}
- public override Iterator<TSource> Clone()
- {
- return new WhereEnumerableIterator<TSource>(_source, _predicate);
- }
+ public override Iterator<TSource> Clone() => new WhereEnumerableIterator<TSource>(_source, _predicate);
public override void Dispose()
{
@@ -160,10 +154,8 @@ namespace System.Linq
return false;
}
- public override IEnumerable<TResult> Select<TResult>(Func<TSource, TResult> selector)
- {
- return new WhereSelectEnumerableIterator<TSource, TResult>(_source, _predicate, selector);
- }
+ public override IEnumerable<TResult> Select<TResult>(Func<TSource, TResult> selector) =>
+ new WhereSelectEnumerableIterator<TSource, TResult>(_source, _predicate, selector);
public TSource[] ToArray()
{
@@ -195,10 +187,8 @@ namespace System.Linq
return list;
}
- public override IEnumerable<TSource> Where(Func<TSource, bool> predicate)
- {
- return new WhereEnumerableIterator<TSource>(_source, CombinePredicates(_predicate, predicate));
- }
+ public override IEnumerable<TSource> Where(Func<TSource, bool> predicate) =>
+ new WhereEnumerableIterator<TSource>(_source, CombinePredicates(_predicate, predicate));
}
/// <summary>
@@ -218,10 +208,8 @@ namespace System.Linq
_predicate = predicate;
}
- public override Iterator<TSource> Clone()
- {
- return new WhereArrayIterator<TSource>(_source, _predicate);
- }
+ public override Iterator<TSource> Clone() =>
+ new WhereArrayIterator<TSource>(_source, _predicate);
public int GetCount(bool onlyIfCheap)
{
@@ -266,10 +254,8 @@ namespace System.Linq
return false;
}
- public override IEnumerable<TResult> Select<TResult>(Func<TSource, TResult> selector)
- {
- return new WhereSelectArrayIterator<TSource, TResult>(_source, _predicate, selector);
- }
+ public override IEnumerable<TResult> Select<TResult>(Func<TSource, TResult> selector) =>
+ new WhereSelectArrayIterator<TSource, TResult>(_source, _predicate, selector);
public TSource[] ToArray()
{
@@ -301,17 +287,15 @@ namespace System.Linq
return list;
}
- public override IEnumerable<TSource> Where(Func<TSource, bool> predicate)
- {
- return new WhereArrayIterator<TSource>(_source, CombinePredicates(_predicate, predicate));
- }
+ public override IEnumerable<TSource> Where(Func<TSource, bool> predicate) =>
+ new WhereArrayIterator<TSource>(_source, CombinePredicates(_predicate, predicate));
}
/// <summary>
/// An iterator that filters each item of a <see cref="List{TSource}"/>.
/// </summary>
/// <typeparam name="TSource">The type of the source list.</typeparam>
- internal sealed class WhereListIterator<TSource> : Iterator<TSource>, IIListProvider<TSource>
+ private sealed class WhereListIterator<TSource> : Iterator<TSource>, IIListProvider<TSource>
{
private readonly List<TSource> _source;
private readonly Func<TSource, bool> _predicate;
@@ -325,10 +309,8 @@ namespace System.Linq
_predicate = predicate;
}
- public override Iterator<TSource> Clone()
- {
- return new WhereListIterator<TSource>(_source, _predicate);
- }
+ public override Iterator<TSource> Clone() =>
+ new WhereListIterator<TSource>(_source, _predicate);
public int GetCount(bool onlyIfCheap)
{
@@ -380,10 +362,8 @@ namespace System.Linq
return false;
}
- public override IEnumerable<TResult> Select<TResult>(Func<TSource, TResult> selector)
- {
- return new WhereSelectListIterator<TSource, TResult>(_source, _predicate, selector);
- }
+ public override IEnumerable<TResult> Select<TResult>(Func<TSource, TResult> selector) =>
+ new WhereSelectListIterator<TSource, TResult>(_source, _predicate, selector);
public TSource[] ToArray()
{
@@ -417,10 +397,8 @@ namespace System.Linq
return list;
}
- public override IEnumerable<TSource> Where(Func<TSource, bool> predicate)
- {
- return new WhereListIterator<TSource>(_source, CombinePredicates(_predicate, predicate));
- }
+ public override IEnumerable<TSource> Where(Func<TSource, bool> predicate) =>
+ new WhereListIterator<TSource>(_source, CombinePredicates(_predicate, predicate));
}
/// <summary>
@@ -428,7 +406,7 @@ namespace System.Linq
/// </summary>
/// <typeparam name="TSource">The type of the source array.</typeparam>
/// <typeparam name="TResult">The type of the mapped items.</typeparam>
- internal sealed class WhereSelectArrayIterator<TSource, TResult> : Iterator<TResult>, IIListProvider<TResult>
+ private sealed class WhereSelectArrayIterator<TSource, TResult> : Iterator<TResult>, IIListProvider<TResult>
{
private readonly TSource[] _source;
private readonly Func<TSource, bool> _predicate;
@@ -444,10 +422,8 @@ namespace System.Linq
_selector = selector;
}
- public override Iterator<TResult> Clone()
- {
- return new WhereSelectArrayIterator<TSource, TResult>(_source, _predicate, _selector);
- }
+ public override Iterator<TResult> Clone() =>
+ new WhereSelectArrayIterator<TSource, TResult>(_source, _predicate, _selector);
public int GetCount(bool onlyIfCheap)
{
@@ -496,10 +472,8 @@ namespace System.Linq
return false;
}
- public override IEnumerable<TResult2> Select<TResult2>(Func<TResult, TResult2> selector)
- {
- return new WhereSelectArrayIterator<TSource, TResult2>(_source, _predicate, CombineSelectors(_selector, selector));
- }
+ public override IEnumerable<TResult2> Select<TResult2>(Func<TResult, TResult2> selector) =>
+ new WhereSelectArrayIterator<TSource, TResult2>(_source, _predicate, CombineSelectors(_selector, selector));
public TResult[] ToArray()
{
@@ -537,7 +511,7 @@ namespace System.Linq
/// </summary>
/// <typeparam name="TSource">The type of the source list.</typeparam>
/// <typeparam name="TResult">The type of the mapped items.</typeparam>
- internal sealed class WhereSelectListIterator<TSource, TResult> : Iterator<TResult>, IIListProvider<TResult>
+ private sealed class WhereSelectListIterator<TSource, TResult> : Iterator<TResult>, IIListProvider<TResult>
{
private readonly List<TSource> _source;
private readonly Func<TSource, bool> _predicate;
@@ -554,10 +528,8 @@ namespace System.Linq
_selector = selector;
}
- public override Iterator<TResult> Clone()
- {
- return new WhereSelectListIterator<TSource, TResult>(_source, _predicate, _selector);
- }
+ public override Iterator<TResult> Clone() =>
+ new WhereSelectListIterator<TSource, TResult>(_source, _predicate, _selector);
public int GetCount(bool onlyIfCheap)
{
@@ -613,10 +585,8 @@ namespace System.Linq
return false;
}
- public override IEnumerable<TResult2> Select<TResult2>(Func<TResult, TResult2> selector)
- {
- return new WhereSelectListIterator<TSource, TResult2>(_source, _predicate, CombineSelectors(_selector, selector));
- }
+ public override IEnumerable<TResult2> Select<TResult2>(Func<TResult, TResult2> selector) =>
+ new WhereSelectListIterator<TSource, TResult2>(_source, _predicate, CombineSelectors(_selector, selector));
public TResult[] ToArray()
{
@@ -656,7 +626,7 @@ namespace System.Linq
/// </summary>
/// <typeparam name="TSource">The type of the source enumerable.</typeparam>
/// <typeparam name="TResult">The type of the mapped items.</typeparam>
- internal sealed class WhereSelectEnumerableIterator<TSource, TResult> : Iterator<TResult>, IIListProvider<TResult>
+ private sealed class WhereSelectEnumerableIterator<TSource, TResult> : Iterator<TResult>, IIListProvider<TResult>
{
private readonly IEnumerable<TSource> _source;
private readonly Func<TSource, bool> _predicate;
@@ -673,10 +643,8 @@ namespace System.Linq
_selector = selector;
}
- public override Iterator<TResult> Clone()
- {
- return new WhereSelectEnumerableIterator<TSource, TResult>(_source, _predicate, _selector);
- }
+ public override Iterator<TResult> Clone() =>
+ new WhereSelectEnumerableIterator<TSource, TResult>(_source, _predicate, _selector);
public override void Dispose()
{
@@ -742,10 +710,8 @@ namespace System.Linq
return false;
}
- public override IEnumerable<TResult2> Select<TResult2>(Func<TResult, TResult2> selector)
- {
- return new WhereSelectEnumerableIterator<TSource, TResult2>(_source, _predicate, CombineSelectors(_selector, selector));
- }
+ public override IEnumerable<TResult2> Select<TResult2>(Func<TResult, TResult2> selector) =>
+ new WhereSelectEnumerableIterator<TSource, TResult2>(_source, _predicate, CombineSelectors(_selector, selector));
public TResult[] ToArray()
{
diff --git a/src/System.Linq/tests/System.Linq.Tests.csproj b/src/System.Linq/tests/System.Linq.Tests.csproj
index ff1790ac32..f9da3173ae 100644
--- a/src/System.Linq/tests/System.Linq.Tests.csproj
+++ b/src/System.Linq/tests/System.Linq.Tests.csproj
@@ -77,9 +77,6 @@
<Compile Include="UnionTests.cs" />
<Compile Include="WhereTests.cs" />
<Compile Include="ZipTests.cs" />
- <Compile Include="$(CommonTestPath)\System\AssertExtensions.cs">
- <Link>Common\System\AssertExtensions.cs</Link>
- </Compile>
<Compile Include="$(CommonTestPath)\System\PlatformDetection.cs">
<Link>Common\System\PlatformDetection.cs</Link>
</Compile>
diff --git a/src/System.Linq/tests/ToArrayTests.cs b/src/System.Linq/tests/ToArrayTests.cs
index da956675dc..81ad50f35d 100644
--- a/src/System.Linq/tests/ToArrayTests.cs
+++ b/src/System.Linq/tests/ToArrayTests.cs
@@ -350,6 +350,33 @@ namespace System.Linq.Tests
Assert.Equal(range, lazyEnumerable.ToArray());
}
+ // Consider that two very similar enums is not unheard of, if e.g. two assemblies map the
+ // same external source of numbers (codes, response codes, colour codes, etc.) to values.
+ private enum Enum0
+ {
+ First,
+ Second,
+ Third
+ }
+
+ private enum Enum1
+ {
+ First,
+ Second,
+ Third
+ }
+
+ [Fact, SkipOnTargetFramework(TargetFrameworkMonikers.NetFramework, "The full .NET framework disallows copying assignable value types. See corefx#13816")]
+ public void ToArray_Cast()
+ {
+ Enum0[] source = { Enum0.First, Enum0.Second, Enum0.Third };
+ var cast = source.Cast<Enum1>();
+ Assert.IsType<Enum0[]>(cast);
+ var castArray = cast.ToArray();
+ Assert.IsType<Enum1[]>(castArray);
+ Assert.Equal(new[] { Enum1.First, Enum1.Second, Enum1.Third }, castArray);
+ }
+
public static IEnumerable<object[]> JustBelowPowersOfTwoLengths()
{
return SmallPowersOfTwo.Select(p => new object[] { p - 1 });
diff --git a/src/System.Memory/tests/System.Memory.Tests.csproj b/src/System.Memory/tests/System.Memory.Tests.csproj
index 3c98e4f75b..156b5a9edb 100644
--- a/src/System.Memory/tests/System.Memory.Tests.csproj
+++ b/src/System.Memory/tests/System.Memory.Tests.csproj
@@ -76,9 +76,6 @@
<Compile Include="ReadOnlySpan\StartsWith.byte.cs" />
<Compile Include="ReadOnlySpan\TestHelpers.cs" />
<Compile Include="ReadOnlySpan\ToArray.cs" />
- <Compile Include="$(CommonTestPath)\System\AssertExtensions.cs">
- <Link>Common\System\AssertExtensions.cs</Link>
- </Compile>
</ItemGroup>
<Import Project="$([MSBuild]::GetDirectoryNameOfFileAbove($(MSBuildThisFileDirectory), dir.targets))\dir.targets" />
</Project> \ No newline at end of file
diff --git a/src/System.Net.Http.WinHttpHandler/src/System.Net.Http.WinHttpHandler.msbuild b/src/System.Net.Http.WinHttpHandler/src/System.Net.Http.WinHttpHandler.msbuild
index b36dadda85..2661bfcf9b 100644
--- a/src/System.Net.Http.WinHttpHandler/src/System.Net.Http.WinHttpHandler.msbuild
+++ b/src/System.Net.Http.WinHttpHandler/src/System.Net.Http.WinHttpHandler.msbuild
@@ -22,6 +22,8 @@
<CompileItem Include="$(CommonPath)\System\Net\Http\HttpHandlerDefaults.cs" />
<CompileItem Include="$(CommonPath)\System\Net\Http\NoWriteNoSeekStreamContent.cs" />
<CompileItem Include="$(CommonPath)\System\Net\Http\WinHttpException.cs" />
+ <CompileItem Include="$(CommonPath)\System\Net\Security\CertificateHelper.cs" />
+ <CompileItem Include="$(CommonPath)\System\Net\Security\CertificateHelper.Windows.cs" />
<CompileItem Include="$(CommonPath)\System\Runtime\ExceptionServices\ExceptionStackTrace.cs" />
<CompileItem Include="$(CommonPath)\System\Threading\Tasks\RendezvousAwaitable.cs" />
<CompileItem Include="$(CommonPath)\System\Threading\Tasks\TaskToApm.cs" />
diff --git a/src/System.Net.Http.WinHttpHandler/src/System/Net/Http/WinHttpCertificateHelper.cs b/src/System.Net.Http.WinHttpHandler/src/System/Net/Http/WinHttpCertificateHelper.cs
index e75fca09d1..6868120114 100644
--- a/src/System.Net.Http.WinHttpHandler/src/System/Net/Http/WinHttpCertificateHelper.cs
+++ b/src/System.Net.Http.WinHttpHandler/src/System/Net/Http/WinHttpCertificateHelper.cs
@@ -11,8 +11,7 @@ namespace System.Net.Http
{
internal static class WinHttpCertificateHelper
{
- private const string ClientAuthenticationOID = "1.3.6.1.5.5.7.3.2";
- private static readonly Oid s_serverAuthOid = new Oid("1.3.6.1.5.5.7.3.1");
+ private static readonly Oid s_serverAuthOid = new Oid("1.3.6.1.5.5.7.3.1", "1.3.6.1.5.5.7.3.1");
// TODO: Issue #2165. Merge with similar code used in System.Net.Security move to Common/src//System/Net.
public static void BuildChain(
@@ -81,51 +80,7 @@ namespace System.Net.Http
}
}
- public static X509Certificate2 GetEligibleClientCertificate()
- {
- // Get initial list of client certificates from the MY store.
- X509Certificate2Collection candidateCerts;
- using (var myStore = new X509Store(StoreName.My, StoreLocation.CurrentUser))
- {
- myStore.Open(OpenFlags.OpenExistingOnly | OpenFlags.ReadOnly);
- candidateCerts = myStore.Certificates;
- }
-
- return GetEligibleClientCertificate(candidateCerts);
- }
-
// TODO: Issue #3891. Get the Trusted Issuers List from WinHTTP and use that to help narrow down
// the list of eligible client certificates.
- public static X509Certificate2 GetEligibleClientCertificate(X509Certificate2Collection candidateCerts)
- {
- if (candidateCerts.Count == 0)
- {
- return null;
- }
-
- // Reduce the set of certificates to match the proper 'Client Authentication' criteria.
- candidateCerts = candidateCerts.Find(X509FindType.FindByKeyUsage, X509KeyUsageFlags.DigitalSignature, false);
- candidateCerts = candidateCerts.Find(X509FindType.FindByApplicationPolicy, ClientAuthenticationOID, false);
-
- // Build a new collection with certs that have a private key. Need to do this
- // manually because there is no X509FindType to match this criteria.
- var eligibleCerts = new X509Certificate2Collection();
- foreach (X509Certificate2 cert in candidateCerts)
- {
- if (cert.HasPrivateKey)
- {
- eligibleCerts.Add(cert);
- }
- }
-
- if (eligibleCerts.Count > 0)
- {
- return eligibleCerts[0];
- }
- else
- {
- return null;
- }
- }
}
}
diff --git a/src/System.Net.Http.WinHttpHandler/src/System/Net/Http/WinHttpHandler.cs b/src/System.Net.Http.WinHttpHandler/src/System/Net/Http/WinHttpHandler.cs
index 2fafb99d87..fb4ea89503 100644
--- a/src/System.Net.Http.WinHttpHandler/src/System/Net/Http/WinHttpHandler.cs
+++ b/src/System.Net.Http.WinHttpHandler/src/System/Net/Http/WinHttpHandler.cs
@@ -1125,11 +1125,11 @@ namespace System.Net.Http
X509Certificate2 clientCertificate = null;
if (_clientCertificateOption == ClientCertificateOption.Manual)
{
- clientCertificate = WinHttpCertificateHelper.GetEligibleClientCertificate(ClientCertificates);
+ clientCertificate = CertificateHelper.GetEligibleClientCertificate(ClientCertificates);
}
else
{
- clientCertificate = WinHttpCertificateHelper.GetEligibleClientCertificate();
+ clientCertificate = CertificateHelper.GetEligibleClientCertificate();
}
if (clientCertificate != null)
diff --git a/src/System.Net.Http.WinHttpHandler/src/System/Net/Http/WinHttpRequestCallback.cs b/src/System.Net.Http.WinHttpHandler/src/System/Net/Http/WinHttpRequestCallback.cs
index 7a80bb75b0..636229ad3f 100644
--- a/src/System.Net.Http.WinHttpHandler/src/System/Net/Http/WinHttpRequestCallback.cs
+++ b/src/System.Net.Http.WinHttpHandler/src/System/Net/Http/WinHttpRequestCallback.cs
@@ -350,7 +350,7 @@ namespace System.Net.Http
{
// TODO: Issue #2165. We need to pass in the cancellation token from the
// user's ReadAsync() call into the TrySetCanceled().
- Debug.WriteLine("RequestCallback: QUERY_DATA_AVAILABLE - ERROR_WINHTTP_OPERATION_CANCELLED");
+ WinHttpTraceHelper.Trace("RequestCallback: QUERY_DATA_AVAILABLE - ERROR_WINHTTP_OPERATION_CANCELLED");
state.LifecycleAwaitable.SetCanceled();
}
else
@@ -365,7 +365,7 @@ namespace System.Net.Http
{
// TODO: Issue #2165. We need to pass in the cancellation token from the
// user's ReadAsync() call into the TrySetCanceled().
- Debug.WriteLine("RequestCallback: API_READ_DATA - ERROR_WINHTTP_OPERATION_CANCELLED");
+ WinHttpTraceHelper.Trace("RequestCallback: API_READ_DATA - ERROR_WINHTTP_OPERATION_CANCELLED");
state.LifecycleAwaitable.SetCanceled();
}
else
@@ -379,7 +379,7 @@ namespace System.Net.Http
{
// TODO: Issue #2165. We need to pass in the cancellation token from the
// user's WriteAsync() call into the TrySetCanceled().
- Debug.WriteLine("RequestCallback: API_WRITE_DATA - ERROR_WINHTTP_OPERATION_CANCELLED");
+ WinHttpTraceHelper.Trace("RequestCallback: API_WRITE_DATA - ERROR_WINHTTP_OPERATION_CANCELLED");
state.TcsInternalWriteDataToRequestStream.TrySetCanceled();
}
else
diff --git a/src/System.Net.Http.WinHttpHandler/src/System/Net/Http/WinHttpResponseStream.cs b/src/System.Net.Http.WinHttpHandler/src/System/Net/Http/WinHttpResponseStream.cs
index 20730e5189..2c3af3458c 100644
--- a/src/System.Net.Http.WinHttpHandler/src/System/Net/Http/WinHttpResponseStream.cs
+++ b/src/System.Net.Http.WinHttpHandler/src/System/Net/Http/WinHttpResponseStream.cs
@@ -314,11 +314,8 @@ namespace System.Net.Http
{
if (_state.AsyncReadInProgress)
{
- Debug.Assert(_requestHandle != null);
- Debug.Assert(!_requestHandle.IsInvalid);
-
WinHttpTraceHelper.Trace("WinHttpResponseStream.CancelPendingResponseStreamReadOperation: before dispose");
- _requestHandle.Dispose();
+ _requestHandle?.Dispose(); // null check necessary to handle race condition between stream disposal and cancellation
WinHttpTraceHelper.Trace("WinHttpResponseStream.CancelPendingResponseStreamReadOperation: after dispose");
}
}
diff --git a/src/System.Net.Http.WinHttpHandler/tests/UnitTests/FakeX509Certificates.cs b/src/System.Net.Http.WinHttpHandler/tests/UnitTests/FakeX509Certificates.cs
index cda60bd847..c3d63d62a5 100644
--- a/src/System.Net.Http.WinHttpHandler/tests/UnitTests/FakeX509Certificates.cs
+++ b/src/System.Net.Http.WinHttpHandler/tests/UnitTests/FakeX509Certificates.cs
@@ -6,7 +6,7 @@ using System.Diagnostics;
using System.Net.Http.WinHttpHandlerUnitTests;
using System.Security.Cryptography.X509Certificates;
-namespace System.Net.Http
+namespace System.Security.Cryptography.X509Certificates
{
public class X509Store : IDisposable
{
diff --git a/src/System.Net.Http.WinHttpHandler/tests/UnitTests/System.Net.Http.WinHttpHandler.Unit.Tests.csproj b/src/System.Net.Http.WinHttpHandler/tests/UnitTests/System.Net.Http.WinHttpHandler.Unit.Tests.csproj
index 73218e5737..9892003c2a 100644
--- a/src/System.Net.Http.WinHttpHandler/tests/UnitTests/System.Net.Http.WinHttpHandler.Unit.Tests.csproj
+++ b/src/System.Net.Http.WinHttpHandler/tests/UnitTests/System.Net.Http.WinHttpHandler.Unit.Tests.csproj
@@ -3,6 +3,7 @@
<Import Project="$([MSBuild]::GetDirectoryNameOfFileAbove($(MSBuildThisFileDirectory), dir.props))\dir.props" />
<PropertyGroup>
<ProjectGuid>{A2ECDEDB-12B7-402C-9230-152B7601179F}</ProjectGuid>
+ <NoWarn>$(NoWarn);0436</NoWarn>
<AllowUnsafeBlocks>true</AllowUnsafeBlocks>
<StringResourcesPath>../../src/Resources/Strings.resx</StringResourcesPath>
</PropertyGroup>
@@ -66,6 +67,12 @@
<Compile Include="$(CommonPath)\System\Net\Http\WinHttpException.cs">
<Link>Common\System\Net\Http\WinHttpException.cs</Link>
</Compile>
+ <Compile Include="$(CommonPath)\System\Net\Security\CertificateHelper.cs">
+ <Link>Common\System\Net\Security\CertificateHelper.cs</Link>
+ </Compile>
+ <Compile Include="$(CommonPath)\System\Net\Security\CertificateHelper.Windows.cs">
+ <Link>Common\System\Net\Security\CertificateHelper.Windows.cs</Link>
+ </Compile>
<Compile Include="$(CommonPath)\System\Runtime\ExceptionServices\ExceptionStackTrace.cs">
<Link>Common\System\Runtime\ExceptionServices\ExceptionStackTrace.cs</Link>
</Compile>
@@ -134,9 +141,6 @@
<Compile Include="WinHttpResponseHeaderReaderTest.cs" />
<Compile Include="WinHttpResponseStreamTest.cs" />
<Compile Include="XunitTestAssemblyAtrributes.cs" />
- <Compile Include="$(CommonTestPath)\System\AssertExtensions.cs">
- <Link>Common\System\AssertExtensions.cs</Link>
- </Compile>
</ItemGroup>
<Import Project="$([MSBuild]::GetDirectoryNameOfFileAbove($(MSBuildThisFileDirectory), dir.targets))\dir.targets" />
</Project> \ No newline at end of file
diff --git a/src/System.Net.Http/src/Resources/Strings.resx b/src/System.Net.Http/src/Resources/Strings.resx
index 39e9575ced..4419c29e3a 100644
--- a/src/System.Net.Http/src/Resources/Strings.resx
+++ b/src/System.Net.Http/src/Resources/Strings.resx
@@ -298,4 +298,10 @@
<data name="net_http_libcurl_revocation_notsupported" xml:space="preserve">
<value>The handler does not support changing revocation settings with this combination of libcurl ({0}) and its SSL backend ("{1}").</value>
</data>
+ <data name="net_http_feature_requires_Windows10Version1607" xml:space="preserve">
+ <value>Using this feature requires Windows 10 Version 1607.</value>
+ </data>
+ <data name="net_http_feature_UWPClientCertSupportRequiresCertInPersonalCertificateStore" xml:space="preserve">
+ <value>Client certificate was not found in the personal (\"MY\") certificate store. In UWP, client certificates are only supported if they have been added to that certificate store.</value>
+ </data>
</root>
diff --git a/src/System.Net.Http/src/System.Net.Http.csproj b/src/System.Net.Http/src/System.Net.Http.csproj
index 47e8b4e056..0336861bb1 100644
--- a/src/System.Net.Http/src/System.Net.Http.csproj
+++ b/src/System.Net.Http/src/System.Net.Http.csproj
@@ -372,7 +372,9 @@
<ItemGroup Condition="'$(TargetGroup)' == 'uap'">
<Reference Include="Windows" />
<Reference Include="mscorlib" />
+ <Reference Include="System.Runtime.InteropServices.WindowsRuntime" />
<Reference Include="System.Runtime.WindowsRuntime" />
+ <Reference Include="System.Security.Cryptography.X509Certificates" />
<Reference Include="System.Text.Encoding.Extensions" />
<Compile Include="$(CommonPath)\System\NotImplemented.cs">
<Link>Common\System\NotImplemented.cs</Link>
@@ -383,17 +385,27 @@
<Compile Include="$(CommonPath)\System\Net\HttpStatusDescription.cs">
<Link>Common\System\Net\HttpStatusDescription.cs</Link>
</Compile>
+ <Compile Include="$(CommonPath)\System\Net\Security\CertificateHelper.cs">
+ <Link>Common\System\Net\Security\CertificateHelper.cs</Link>
+ </Compile>
+ <Compile Include="$(CommonPath)\System\Net\Security\CertificateHelper.Uap.cs">
+ <Link>Common\System\Net\Security\CertificateHelper.Uap.cs</Link>
+ </Compile>
+ <Compile Include="$(CommonPath)\System\Net\Security\CertificateHelper.Windows.cs">
+ <Link>Common\System\Net\Security\CertificateHelper.Windows.cs</Link>
+ </Compile>
<Compile Include="$(CommonPath)\System\StringExtensions.cs">
<Link>Common\System\StringExtensions.cs</Link>
</Compile>
<Compile Include="$(CommonPath)\System\Threading\Tasks\TaskToApm.cs">
<Link>Common\System\Threading\Tasks\TaskToApm.cs</Link>
</Compile>
- <Compile Include="netcore50\System\Net\cookie.cs" />
- <Compile Include="netcore50\System\Net\cookieexception.cs" />
- <Compile Include="netcore50\System\Net\CookieHelper.cs" />
- <Compile Include="netcore50\System\Net\HttpHandlerToFilter.cs" />
- <Compile Include="netcore50\System\Net\HttpClientHandler.cs" />
+ <Compile Include="uap\System\Net\cookie.cs" />
+ <Compile Include="uap\System\Net\cookieexception.cs" />
+ <Compile Include="uap\System\Net\CookieHelper.cs" />
+ <Compile Include="uap\System\Net\HttpHandlerToFilter.cs" />
+ <Compile Include="System\Net\Http\HttpClientHandler.Core.cs" />
+ <Compile Include="uap\System\Net\HttpClientHandler.cs" />
</ItemGroup>
<ItemGroup Condition="'$(TargetGroup)' == 'netcoreapp' OR '$(TargetGroup)' == 'uap'">
<Reference Include="Microsoft.Win32.Primitives" />
diff --git a/src/System.Net.Http/src/System/Net/Http/Headers/ContentRangeHeaderValue.cs b/src/System.Net.Http/src/System/Net/Http/Headers/ContentRangeHeaderValue.cs
index 5cd7d67b4c..7991b19768 100644
--- a/src/System.Net.Http/src/System/Net/Http/Headers/ContentRangeHeaderValue.cs
+++ b/src/System.Net.Http/src/System/Net/Http/Headers/ContentRangeHeaderValue.cs
@@ -363,13 +363,13 @@ namespace System.Net.Http.Headers
parsedValue = null;
long from = 0;
- if ((fromLength > 0) && !HeaderUtilities.TryParseInt64(input.Substring(fromStartIndex, fromLength), out from))
+ if ((fromLength > 0) && !HeaderUtilities.TryParseInt64(input, fromStartIndex, fromLength, out from))
{
return false;
}
long to = 0;
- if ((toLength > 0) && !HeaderUtilities.TryParseInt64(input.Substring(toStartIndex, toLength), out to))
+ if ((toLength > 0) && !HeaderUtilities.TryParseInt64(input, toStartIndex, toLength, out to))
{
return false;
}
@@ -381,8 +381,7 @@ namespace System.Net.Http.Headers
}
long length = 0;
- if ((lengthLength > 0) && !HeaderUtilities.TryParseInt64(input.Substring(lengthStartIndex, lengthLength),
- out length))
+ if ((lengthLength > 0) && !HeaderUtilities.TryParseInt64(input, lengthStartIndex, lengthLength, out length))
{
return false;
}
diff --git a/src/System.Net.Http/src/System/Net/Http/Headers/HeaderUtilities.cs b/src/System.Net.Http/src/System/Net/Http/Headers/HeaderUtilities.cs
index de509b9521..4c67343974 100644
--- a/src/System.Net.Http/src/System/Net/Http/Headers/HeaderUtilities.cs
+++ b/src/System.Net.Http/src/System/Net/Http/Headers/HeaderUtilities.cs
@@ -249,14 +249,69 @@ namespace System.Net.Http.Headers
return null;
}
- internal static bool TryParseInt32(string value, out int result)
+ internal static bool TryParseInt32(string value, out int result) =>
+ TryParseInt32(value, 0, value.Length, out result);
+
+ internal static bool TryParseInt32(string value, int offset, int length, out int result) // TODO #21281: Replace with int.TryParse(Span<char>) once it's available
{
- return int.TryParse(value, NumberStyles.None, NumberFormatInfo.InvariantInfo, out result);
+ if (offset < 0 || length < 0 || offset > value.Length - length)
+ {
+ result = 0;
+ return false;
+ }
+
+ int tmpResult = 0;
+ int pos = offset, endPos = offset + length;
+ while (pos < endPos)
+ {
+ char c = value[pos++];
+ int digit = c - '0';
+ if ((uint)digit > 9 || // invalid digit
+ tmpResult > int.MaxValue / 10 || // will overflow when shifting digits
+ (tmpResult == int.MaxValue / 10 && digit > 7)) // will overflow when adding in digit
+ {
+ goto ReturnFalse; // Remove goto once https://github.com/dotnet/coreclr/issues/9692 is addressed
+ }
+ tmpResult = (tmpResult * 10) + digit;
+ }
+
+ result = tmpResult;
+ return true;
+
+ ReturnFalse:
+ result = 0;
+ return false;
}
- internal static bool TryParseInt64(string value, out long result)
+ internal static bool TryParseInt64(string value, int offset, int length, out long result) // TODO #21281: Replace with int.TryParse(Span<char>) once it's available
{
- return long.TryParse(value, NumberStyles.None, NumberFormatInfo.InvariantInfo, out result);
+ if (offset < 0 || length < 0 || offset > value.Length - length)
+ {
+ result = 0;
+ return false;
+ }
+
+ long tmpResult = 0;
+ int pos = offset, endPos = offset + length;
+ while (pos < endPos)
+ {
+ char c = value[pos++];
+ int digit = c - '0';
+ if ((uint)digit > 9 || // invalid digit
+ tmpResult > long.MaxValue / 10 || // will overflow when shifting digits
+ (tmpResult == long.MaxValue / 10 && digit > 7)) // will overflow when adding in digit
+ {
+ goto ReturnFalse; // Remove goto once https://github.com/dotnet/coreclr/issues/9692 is addressed
+ }
+ tmpResult = (tmpResult * 10) + digit;
+ }
+
+ result = tmpResult;
+ return true;
+
+ ReturnFalse:
+ result = 0;
+ return false;
}
internal static string DumpHeaders(params HttpHeaders[] headers)
diff --git a/src/System.Net.Http/src/System/Net/Http/Headers/HttpGeneralHeaders.cs b/src/System.Net.Http/src/System/Net/Http/Headers/HttpGeneralHeaders.cs
index 4e9b011069..16cbbfec2f 100644
--- a/src/System.Net.Http/src/System/Net/Http/Headers/HttpGeneralHeaders.cs
+++ b/src/System.Net.Http/src/System/Net/Http/Headers/HttpGeneralHeaders.cs
@@ -37,26 +37,10 @@ namespace System.Net.Http.Headers
{
get
{
- // If we've already initialized the connection header value collection
- // and it contains the special value, or if we haven't and the headers contain
- // the parsed special value, return true. We don't just access ConnectionCore,
- // as doing so will unnecessarily initialize the collection even if it's not needed.
- if (_connection != null)
- {
- if (_connection.IsSpecialValueSet)
- {
- return true;
- }
- }
- else if (_parent.ContainsParsedValue(HttpKnownHeaderNames.Connection, HeaderUtilities.ConnectionClose))
- {
- return true;
- }
- if (_connectionCloseSet)
- {
- return false;
- }
- return null;
+ // Separated out into a static to enable access to TransferEncodingChunked
+ // without the caller needing to force the creation of HttpGeneralHeaders
+ // if it wasn't created for other reasons.
+ return GetConnectionClose(_parent, this);
}
set
{
@@ -73,6 +57,30 @@ namespace System.Net.Http.Headers
}
}
+ internal static bool? GetConnectionClose(HttpHeaders parent, HttpGeneralHeaders headers)
+ {
+ // If we've already initialized the connection header value collection
+ // and it contains the special value, or if we haven't and the headers contain
+ // the parsed special value, return true. We don't just access ConnectionCore,
+ // as doing so will unnecessarily initialize the collection even if it's not needed.
+ if (headers?._connection != null)
+ {
+ if (headers._connection.IsSpecialValueSet)
+ {
+ return true;
+ }
+ }
+ else if (parent.ContainsParsedValue(HttpKnownHeaderNames.Connection, HeaderUtilities.ConnectionClose))
+ {
+ return true;
+ }
+ if (headers != null && headers._connectionCloseSet)
+ {
+ return false;
+ }
+ return null;
+ }
+
public DateTimeOffset? Date
{
get { return HeaderUtilities.GetDateTimeOffsetValue(HttpKnownHeaderNames.Date, _parent); }
@@ -115,7 +123,7 @@ namespace System.Net.Http.Headers
// and it contains the special value, or if we haven't and the headers contain
// the parsed special value, return true. We don't just access TransferEncodingCore,
// as doing so will unnecessarily initialize the collection even if it's not needed.
- if (headers != null && headers._transferEncoding != null)
+ if (headers?._transferEncoding != null)
{
if (headers._transferEncoding.IsSpecialValueSet)
{
diff --git a/src/System.Net.Http/src/System/Net/Http/Headers/HttpRequestHeaders.cs b/src/System.Net.Http/src/System/Net/Http/Headers/HttpRequestHeaders.cs
index 64f6856ed0..b547aa1f37 100644
--- a/src/System.Net.Http/src/System/Net/Http/Headers/HttpRequestHeaders.cs
+++ b/src/System.Net.Http/src/System/Net/Http/Headers/HttpRequestHeaders.cs
@@ -221,7 +221,7 @@ namespace System.Net.Http.Headers
public bool? ConnectionClose
{
- get { return GeneralHeaders.ConnectionClose; }
+ get { return HttpGeneralHeaders.GetConnectionClose(this, _generalHeaders); } // special-cased to avoid forcing _generalHeaders initialization
set { GeneralHeaders.ConnectionClose = value; }
}
diff --git a/src/System.Net.Http/src/System/Net/Http/Headers/HttpResponseHeaders.cs b/src/System.Net.Http/src/System/Net/Http/Headers/HttpResponseHeaders.cs
index 954fcc5590..ed8d9b60af 100644
--- a/src/System.Net.Http/src/System/Net/Http/Headers/HttpResponseHeaders.cs
+++ b/src/System.Net.Http/src/System/Net/Http/Headers/HttpResponseHeaders.cs
@@ -97,7 +97,7 @@ namespace System.Net.Http.Headers
public bool? ConnectionClose
{
- get { return GeneralHeaders.ConnectionClose; }
+ get { return HttpGeneralHeaders.GetConnectionClose(this, _generalHeaders); } // special-cased to avoid forcing _generalHeaders initialization
set { GeneralHeaders.ConnectionClose = value; }
}
diff --git a/src/System.Net.Http/src/System/Net/Http/Headers/Int32NumberHeaderParser.cs b/src/System.Net.Http/src/System/Net/Http/Headers/Int32NumberHeaderParser.cs
index bdb626be44..4723528b30 100644
--- a/src/System.Net.Http/src/System/Net/Http/Headers/Int32NumberHeaderParser.cs
+++ b/src/System.Net.Http/src/System/Net/Http/Headers/Int32NumberHeaderParser.cs
@@ -42,7 +42,7 @@ namespace System.Net.Http.Headers
}
int result = 0;
- if (!HeaderUtilities.TryParseInt32(value.Substring(startIndex, numberLength), out result))
+ if (!HeaderUtilities.TryParseInt32(value, startIndex, numberLength, out result))
{
return 0;
}
diff --git a/src/System.Net.Http/src/System/Net/Http/Headers/Int64NumberHeaderParser.cs b/src/System.Net.Http/src/System/Net/Http/Headers/Int64NumberHeaderParser.cs
index 856c1bb353..b722073d31 100644
--- a/src/System.Net.Http/src/System/Net/Http/Headers/Int64NumberHeaderParser.cs
+++ b/src/System.Net.Http/src/System/Net/Http/Headers/Int64NumberHeaderParser.cs
@@ -42,7 +42,7 @@ namespace System.Net.Http.Headers
}
long result = 0;
- if (!HeaderUtilities.TryParseInt64(value.Substring(startIndex, numberLength), out result))
+ if (!HeaderUtilities.TryParseInt64(value, startIndex, numberLength, out result))
{
return 0;
}
diff --git a/src/System.Net.Http/src/System/Net/Http/Headers/RangeItemHeaderValue.cs b/src/System.Net.Http/src/System/Net/Http/Headers/RangeItemHeaderValue.cs
index 190e9d4554..8ff4c6b1fe 100644
--- a/src/System.Net.Http/src/System/Net/Http/Headers/RangeItemHeaderValue.cs
+++ b/src/System.Net.Http/src/System/Net/Http/Headers/RangeItemHeaderValue.cs
@@ -209,14 +209,14 @@ namespace System.Net.Http.Headers
// Try convert first value to int64
long from = 0;
- if ((fromLength > 0) && !HeaderUtilities.TryParseInt64(input.Substring(fromStartIndex, fromLength), out from))
+ if ((fromLength > 0) && !HeaderUtilities.TryParseInt64(input, fromStartIndex, fromLength, out from))
{
return 0;
}
// Try convert second value to int64
long to = 0;
- if ((toLength > 0) && !HeaderUtilities.TryParseInt64(input.Substring(toStartIndex, toLength), out to))
+ if ((toLength > 0) && !HeaderUtilities.TryParseInt64(input, toStartIndex, toLength, out to))
{
return 0;
}
diff --git a/src/System.Net.Http/src/System/Net/Http/Headers/RetryConditionHeaderValue.cs b/src/System.Net.Http/src/System/Net/Http/Headers/RetryConditionHeaderValue.cs
index 93470db89b..f539a71fe4 100644
--- a/src/System.Net.Http/src/System/Net/Http/Headers/RetryConditionHeaderValue.cs
+++ b/src/System.Net.Http/src/System/Net/Http/Headers/RetryConditionHeaderValue.cs
@@ -148,7 +148,7 @@ namespace System.Net.Http.Headers
return 0;
}
- if (!HeaderUtilities.TryParseInt32(input.Substring(deltaStartIndex, deltaLength), out deltaSeconds))
+ if (!HeaderUtilities.TryParseInt32(input, deltaStartIndex, deltaLength, out deltaSeconds))
{
return 0; // int.TryParse() may return 'false' if the value has 10 digits and is > Int32.MaxValue.
}
diff --git a/src/System.Net.Http/src/System/Net/Http/Headers/TimeSpanHeaderParser.cs b/src/System.Net.Http/src/System/Net/Http/Headers/TimeSpanHeaderParser.cs
index 6f91009860..99cd0d192b 100644
--- a/src/System.Net.Http/src/System/Net/Http/Headers/TimeSpanHeaderParser.cs
+++ b/src/System.Net.Http/src/System/Net/Http/Headers/TimeSpanHeaderParser.cs
@@ -36,7 +36,7 @@ namespace System.Net.Http.Headers
}
int result = 0;
- if (!HeaderUtilities.TryParseInt32(value.Substring(startIndex, numberLength), out result))
+ if (!HeaderUtilities.TryParseInt32(value, startIndex, numberLength, out result))
{
return 0;
}
diff --git a/src/System.Net.Http/src/System/Net/Http/Headers/WarningHeaderValue.cs b/src/System.Net.Http/src/System/Net/Http/Headers/WarningHeaderValue.cs
index 32c12aabf8..e6805834c2 100644
--- a/src/System.Net.Http/src/System/Net/Http/Headers/WarningHeaderValue.cs
+++ b/src/System.Net.Http/src/System/Net/Http/Headers/WarningHeaderValue.cs
@@ -245,7 +245,7 @@ namespace System.Net.Http.Headers
return false;
}
- if (!HeaderUtilities.TryParseInt32(input.Substring(current, codeLength), out code))
+ if (!HeaderUtilities.TryParseInt32(input, current, codeLength, out code))
{
Debug.Assert(false, "Unable to parse value even though it was parsed as <=3 digits string. Input: '" +
input + "', Current: " + current + ", CodeLength: " + codeLength);
diff --git a/src/System.Net.Http/src/System/Net/Http/HttpClientHandler.Core.cs b/src/System.Net.Http/src/System/Net/Http/HttpClientHandler.Core.cs
index 6180e3af1a..9c1bb25657 100644
--- a/src/System.Net.Http/src/System/Net/Http/HttpClientHandler.Core.cs
+++ b/src/System.Net.Http/src/System/Net/Http/HttpClientHandler.Core.cs
@@ -2,25 +2,65 @@
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
+using System.Globalization;
+
namespace System.Net.Http
{
public partial class HttpClientHandler : HttpMessageHandler
{
// This partial implementation contains members common to Windows and Unix running on .NET Core.
+ private volatile bool _operationStarted = false;
+ private volatile bool _disposed = false;
+
public long MaxRequestContentBufferSize
{
- // This property has been deprecated. In the .NET Desktop it was only used when the handler needed to
+ // This property is not supported. In the .NET Framework it was only used when the handler needed to
// automatically buffer the request content. That only happened if neither 'Content-Length' nor
// 'Transfer-Encoding: chunked' request headers were specified. So, the handler thus needed to buffer
// in the request content to determine its length and then would choose 'Content-Length' semantics when
- // POST'ing. In CoreCLR and .NETNative, the handler will resolve the ambiguity by always choosing
+ // POST'ing. In .NET Core and UAP platforms, the handler will resolve the ambiguity by always choosing
// 'Transfer-Encoding: chunked'. The handler will never automatically buffer in the request content.
- get { return 0; }
+ get
+ {
+ return 0; // Returning zero is appropriate since in .NET Framework it means no limit.
+ }
+
+ set
+ {
+ if (value < 0)
+ {
+ throw new ArgumentOutOfRangeException(nameof(value));
+ }
- // TODO (#7879): Add message/link to exception explaining the deprecation.
- // Update corresponding exception in HttpClientHandler.Unix.cs if/when this is updated.
- set { throw new PlatformNotSupportedException(); }
+ if (value > HttpContent.MaxBufferSize)
+ {
+ throw new ArgumentOutOfRangeException(nameof(value), value,
+ string.Format(CultureInfo.InvariantCulture, SR.net_http_content_buffersize_limit,
+ HttpContent.MaxBufferSize));
+ }
+
+ CheckDisposedOrStarted();
+
+ // No-op on property setter.
+ }
+ }
+
+ private void CheckDisposed()
+ {
+ if (_disposed)
+ {
+ throw new ObjectDisposedException(GetType().ToString());
+ }
+ }
+
+ private void CheckDisposedOrStarted()
+ {
+ CheckDisposed();
+ if (_operationStarted)
+ {
+ throw new InvalidOperationException(SR.net_http_operation_started);
+ }
}
}
}
diff --git a/src/System.Net.Http/src/System/Net/Http/HttpClientHandler.Windows.cs b/src/System.Net.Http/src/System/Net/Http/HttpClientHandler.Windows.cs
index 61b32268f5..7893fba575 100644
--- a/src/System.Net.Http/src/System/Net/Http/HttpClientHandler.Windows.cs
+++ b/src/System.Net.Http/src/System/Net/Http/HttpClientHandler.Windows.cs
@@ -21,7 +21,6 @@ namespace System.Net.Http
private readonly ManagedHandler _managedHandler;
private readonly DiagnosticsHandler _diagnosticsHandler;
private bool _useProxy;
- private bool _disposed;
public HttpClientHandler()
{
diff --git a/src/System.Net.Http/src/System/Net/Http/Managed/ConnectHelper.cs b/src/System.Net.Http/src/System/Net/Http/Managed/ConnectHelper.cs
index fc0a58c844..aca4b488af 100644
--- a/src/System.Net.Http/src/System/Net/Http/Managed/ConnectHelper.cs
+++ b/src/System.Net.Http/src/System/Net/Http/Managed/ConnectHelper.cs
@@ -11,48 +11,31 @@ namespace System.Net.Http
{
public static async ValueTask<NetworkStream> ConnectAsync(string host, int port)
{
- TcpClient client;
+ var socket = new Socket(SocketType.Stream, ProtocolType.Tcp) { NoDelay = true };
try
{
- // You would think TcpClient.Connect would just do this, but apparently not.
- // It works for IPv4 addresses but seems to barf on IPv6.
- // I need to explicitly invoke the constructor with AddressFamily = IPv6.
- // TODO #21452: Does this mean that connecting by name will only work with IPv4
- // (since that's the default)? If so, need to rework this logic
- // to resolve the IPAddress ourselves. Yuck.
// TODO #21452: No cancellationToken on ConnectAsync?
- IPAddress ipAddress;
- if (IPAddress.TryParse(host, out ipAddress))
- {
- client = new TcpClient(ipAddress.AddressFamily);
- await client.ConnectAsync(ipAddress, port).ConfigureAwait(false);
- }
- else
- {
- client = new TcpClient();
- await client.ConnectAsync(host, port).ConfigureAwait(false);
- }
+ await (IPAddress.TryParse(host, out IPAddress address) ?
+ socket.ConnectAsync(address, port) :
+ socket.ConnectAsync(host, port)).ConfigureAwait(false);
}
catch (SocketException se)
{
- throw new HttpRequestException("could not connect", se);
+ socket.Dispose();
+ throw new HttpRequestException(se.Message, se);
}
- client.NoDelay = true;
-
- NetworkStream networkStream = client.GetStream();
-
- // TODO #21452: Timeouts?
- // Default timeout should be something less than infinity (the Socket default)
- // Timeouts probably need to be configurable
- // However, timeouts are also a huge pain when debugging, so consider that too.
+ return new NetworkStream(socket, ownsSocket: true)
+ {
#if false
- // Set default read/write timeouts of 5 seconds.
- networkStream.ReadTimeout = 5000;
- networkStream.WriteTimeout = 5000;
+ // TODO #21452: Timeouts?
+ // Default timeout should be something less than infinity (the Socket default)
+ // Timeouts probably need to be configurable
+ // However, timeouts are also a huge pain when debugging, so consider that too.
+ ReadTimeout = 5000,
+ WriteTimeout = 5000
#endif
-
- return networkStream;
+ };
}
}
}
diff --git a/src/System.Net.Http/src/System/Net/Http/Managed/HttpConnection.cs b/src/System.Net.Http/src/System/Net/Http/Managed/HttpConnection.cs
index e835136afc..fd00f475f9 100644
--- a/src/System.Net.Http/src/System/Net/Http/Managed/HttpConnection.cs
+++ b/src/System.Net.Http/src/System/Net/Http/Managed/HttpConnection.cs
@@ -31,16 +31,20 @@ namespace System.Net.Http
private readonly Stream _stream;
private readonly TransportContext _transportContext;
private readonly bool _usingProxy;
+ private readonly byte[] _idnHostAsciiBytes;
private ValueStringBuilder _sb; // mutable struct, do not make this readonly
private readonly byte[] _writeBuffer;
private int _writeOffset;
+ private Task<int> _readAheadTask;
private readonly byte[] _readBuffer;
private int _readOffset;
private int _readLength;
+ private bool _connectionClose; // Connection: close was seen on last response
+
private bool _disposed;
private sealed class HttpConnectionContent : HttpContent
@@ -532,8 +536,9 @@ namespace System.Net.Http
}
public HttpConnection(
- HttpConnectionPool pool,
- HttpConnectionKey key,
+ HttpConnectionPool pool,
+ HttpConnectionKey key,
+ string requestIdnHost,
Stream stream,
TransportContext transportContext,
bool usingProxy)
@@ -543,6 +548,10 @@ namespace System.Net.Http
_stream = stream;
_transportContext = transportContext;
_usingProxy = usingProxy;
+ if (requestIdnHost != null)
+ {
+ _idnHostAsciiBytes = Encoding.ASCII.GetBytes(requestIdnHost);
+ }
const int DefaultCapacity = 16;
_sb = new ValueStringBuilder(DefaultCapacity);
@@ -554,6 +563,9 @@ namespace System.Net.Http
_readLength = 0;
_readOffset = 0;
+ _connectionClose = false;
+ _disposed = false;
+
_pool.AddConnection(this);
}
@@ -572,6 +584,15 @@ namespace System.Net.Http
}
}
+ public bool ReadAheadCompleted
+ {
+ get
+ {
+ Debug.Assert(_readAheadTask != null, $"{nameof(_readAheadTask)} should have been initialized");
+ return _readAheadTask.IsCompleted;
+ }
+ }
+
private async Task WriteHeadersAsync(HttpHeaders headers, CancellationToken cancellationToken)
{
foreach (KeyValuePair<string, IEnumerable<string>> header in headers)
@@ -599,7 +620,10 @@ namespace System.Net.Http
{
await WriteBytesAsync(s_hostKeyAndSeparator, cancellationToken).ConfigureAwait(false);
- await WriteStringAsync(uri.Host, cancellationToken).ConfigureAwait(false);
+ await (_idnHostAsciiBytes != null ?
+ WriteBytesAsync(_idnHostAsciiBytes, cancellationToken) :
+ WriteAsciiStringAsync(uri.IdnHost, cancellationToken)).ConfigureAwait(false);
+
if (!uri.IsDefaultPort)
{
await WriteByteAsync((byte)':', cancellationToken).ConfigureAwait(false);
@@ -767,15 +791,18 @@ namespace System.Net.Http
int status = 100 * (status1 - '0') + 10 * (status2 - '0') + (status3 - '0');
response.StatusCode = (HttpStatusCode)status;
- if (await ReadCharAsync(cancellationToken).ConfigureAwait(false) != ' ')
+ // Parse (optional) reason phrase
+ _sb.Clear();
+ char c = await ReadCharAsync(cancellationToken).ConfigureAwait(false);
+ if (c == ' ')
+ {
+ c = await ReadCharAsync(cancellationToken).ConfigureAwait(false);
+ }
+ else if (c != '\r')
{
throw new HttpRequestException("Invalid characters in response line");
}
- _sb.Clear();
-
- // Parse reason phrase
- char c = await ReadCharAsync(cancellationToken).ConfigureAwait(false);
while (c != '\r')
{
_sb.Append(c);
@@ -788,7 +815,7 @@ namespace System.Net.Http
}
string knownReasonPhrase = HttpStatusDescription.Get(response.StatusCode);
- response.ReasonPhrase = CharArrayHelpers.EqualsOrdinal(knownReasonPhrase, _sb.Chars, 0, _sb.Length) ?
+ response.ReasonPhrase = knownReasonPhrase != null && CharArrayHelpers.EqualsOrdinal(knownReasonPhrase, _sb.Chars, 0, _sb.Length) ?
knownReasonPhrase :
_sb.ToString();
@@ -862,6 +889,11 @@ namespace System.Net.Http
c = await ReadCharAsync(cancellationToken).ConfigureAwait(false);
}
+ if (response.Headers.ConnectionClose ?? false)
+ {
+ _connectionClose = true;
+ }
+
// Instantiate responseStream
HttpContentReadStream responseStream =
request.Method == HttpMethod.Head || status == 204 || status == 304 ? new ContentLengthReadStream(this, 0) : // no response body
@@ -1072,7 +1104,22 @@ namespace System.Net.Http
Debug.Assert(_readOffset == _readLength);
_readOffset = 0;
- Task<int> t = _stream.ReadAsync(_readBuffer, 0, BufferSize, cancellationToken);
+ Task<int> t;
+ if (_readAheadTask != null)
+ {
+ // When the connection is put back into the pool, a pre-emptive read is performed
+ // into the read buffer. That read should not complete prior to us using the
+ // connection again, as that would mean the connection was either closed or had
+ // erroneous data sent on it by the server in response to no request from us.
+ // We need to consume that read prior to issuing another read request.
+ t = _readAheadTask;
+ _readAheadTask = null;
+ }
+ else
+ {
+ t = _stream.ReadAsync(_readBuffer, 0, BufferSize, cancellationToken);
+ }
+
if (t.IsCompleted)
{
_readLength = t.GetAwaiter().GetResult();
@@ -1182,6 +1229,7 @@ namespace System.Net.Http
// Large read size, and no buffered data.
// Do an unbuffered read directly against the underlying stream.
+ Debug.Assert(_readAheadTask == null, "Read ahead task should have been consumed as part of the headers.");
count = await _stream.ReadAsync(buffer, offset, count, cancellationToken).ConfigureAwait(false);
return count;
}
@@ -1260,6 +1308,32 @@ namespace System.Net.Http
// Make sure there's nothing in the write buffer that should have been flushed
Debug.Assert(_writeOffset == 0);
+ if (_connectionClose)
+ {
+ // Server told us it's closing the connection, so don't put this back in the pool.
+ Dispose();
+ return;
+ }
+
+ try
+ {
+ // When putting a connection back into the pool, we initiate a pre-emptive
+ // read on the stream. When the connection is subsequently taken out of the
+ // pool, this can be used in place of the first read on the stream that would
+ // otherwise be done. But by doing it now, we can check the status of the read
+ // at any point to understand if the connection has been closed or if errant data
+ // has been sent on the connection by the server, either of which would mean we
+ // should close the connection and not use it for subsequent requests.
+ Debug.Assert(_readAheadTask == null, $"Expected a previous initial read to already be consumed");
+ _readAheadTask = _stream.ReadAsync(_readBuffer, 0, _readBuffer.Length);
+ }
+ catch
+ {
+ // If reading throws, eat the error but don't pool the connection.
+ Dispose();
+ return;
+ }
+
_pool.PutConnection(this);
}
diff --git a/src/System.Net.Http/src/System/Net/Http/Managed/HttpConnectionHandler.cs b/src/System.Net.Http/src/System/Net/Http/Managed/HttpConnectionHandler.cs
index 3b4d6b54e0..e37b1d5662 100644
--- a/src/System.Net.Http/src/System/Net/Http/Managed/HttpConnectionHandler.cs
+++ b/src/System.Net.Http/src/System/Net/Http/Managed/HttpConnectionHandler.cs
@@ -96,13 +96,13 @@ namespace System.Net.Http
{
Uri uri = request.RequestUri;
- Stream stream = await ConnectHelper.ConnectAsync(uri.Host, uri.Port).ConfigureAwait(false);
+ Stream stream = await ConnectHelper.ConnectAsync(uri.IdnHost, uri.Port).ConfigureAwait(false);
TransportContext transportContext = null;
if (uri.Scheme == UriScheme.Https)
{
- SslStream sslStream = await EstablishSslConnection(uri.Host, request, stream).ConfigureAwait(false);
+ SslStream sslStream = await EstablishSslConnection(uri.IdnHost, request, stream).ConfigureAwait(false);
stream = sslStream;
transportContext = sslStream.TransportContext;
@@ -113,7 +113,7 @@ namespace System.Net.Http
pool = _connectionPoolTable.GetOrAdd(key, _ => new HttpConnectionPool());
}
- var connection = new HttpConnection(pool, key, stream, transportContext, false);
+ var connection = new HttpConnection(pool, key, uri.IdnHost, stream, transportContext, false);
return connection;
}
diff --git a/src/System.Net.Http/src/System/Net/Http/Managed/HttpConnectionPool.cs b/src/System.Net.Http/src/System/Net/Http/Managed/HttpConnectionPool.cs
index 0a4e838ddc..3d118a1a14 100644
--- a/src/System.Net.Http/src/System/Net/Http/Managed/HttpConnectionPool.cs
+++ b/src/System.Net.Http/src/System/Net/Http/Managed/HttpConnectionPool.cs
@@ -21,9 +21,16 @@ namespace System.Net.Http
public HttpConnection GetConnection()
{
- HttpConnection connection;
- if (_idleConnections.TryTake(out connection))
+ while (_idleConnections.TryTake(out HttpConnection connection))
{
+ if (connection.ReadAheadCompleted)
+ {
+ // We got a connection, but it was either already closed by the server or the
+ // server sent unexpected data. Either way, we can't use the connection.
+ connection.Dispose();
+ continue;
+ }
+
if (!_activeConnections.TryAdd(connection))
{
throw new InvalidOperationException();
diff --git a/src/System.Net.Http/src/System/Net/Http/Managed/HttpProxyConnectionHandler.cs b/src/System.Net.Http/src/System/Net/Http/Managed/HttpProxyConnectionHandler.cs
index 1a119232e3..7901aa512c 100644
--- a/src/System.Net.Http/src/System/Net/Http/Managed/HttpProxyConnectionHandler.cs
+++ b/src/System.Net.Http/src/System/Net/Http/Managed/HttpProxyConnectionHandler.cs
@@ -116,14 +116,14 @@ namespace System.Net.Http
}
}
- Stream stream = await ConnectHelper.ConnectAsync(proxyUri.Host, proxyUri.Port).ConfigureAwait(false);
+ Stream stream = await ConnectHelper.ConnectAsync(proxyUri.IdnHost, proxyUri.Port).ConfigureAwait(false);
if (pool == null)
{
pool = _connectionPoolTable.GetOrAdd(key, _ => new HttpConnectionPool());
}
- return new HttpConnection(pool, key, stream, null, true);
+ return new HttpConnection(pool, key, null, stream, null, true);
}
protected override void Dispose(bool disposing)
diff --git a/src/System.Net.Http/src/System/Net/Http/OSX/CurlHandler.SslProvider.cs b/src/System.Net.Http/src/System/Net/Http/OSX/CurlHandler.SslProvider.cs
index 8f7f509a2e..3e9b3e1f6d 100644
--- a/src/System.Net.Http/src/System/Net/Http/OSX/CurlHandler.SslProvider.cs
+++ b/src/System.Net.Http/src/System/Net/Http/OSX/CurlHandler.SslProvider.cs
@@ -12,6 +12,19 @@ namespace System.Net.Http
{
internal partial class CurlHandler : HttpMessageHandler
{
+ static partial void UseSingletonMultiAgent(ref bool result)
+ {
+ // Some backends other than OpenSSL need locks initialized in order to use them in a
+ // multithreaded context, which would happen with multiple HttpClients and thus multiple
+ // MultiAgents. Since we don't currently have the ability to do so initialization, instead we
+ // restrict all HttpClients to use the same MultiAgent instance in this case. We know LibreSSL
+ // is in this camp, so we currently special-case it.
+ string curlSslVersion = Interop.Http.GetSslVersionDescription();
+ result =
+ !string.IsNullOrEmpty(curlSslVersion) &&
+ curlSslVersion.StartsWith(Interop.Http.LibreSslDescription, StringComparison.OrdinalIgnoreCase);
+ }
+
private static class SslProvider
{
internal static void SetSslOptions(EasyRequest easy, ClientCertificateOption clientCertOption)
@@ -78,7 +91,12 @@ namespace System.Net.Http
{
EventSourceTrace("Warning: Disabling peer verification per {0}", nameof(HttpClientHandler.DangerousAcceptAnyServerCertificateValidator), easy: easy);
easy.SetCurlOption(Interop.Http.CURLoption.CURLOPT_SSL_VERIFYPEER, 0); // don't verify the peer
- // Don't set CURLOPT_SSL_VERIFHOST to 0; doing so disables SNI.
+
+ // Don't set CURLOPT_SSL_VERIFHOST to 0; doing so disables SNI with SecureTransport backend.
+ if (!CurlSslVersionDescription.Equals(Interop.Http.SecureTransportDescription))
+ {
+ easy.SetCurlOption(Interop.Http.CURLoption.CURLOPT_SSL_VERIFYHOST, 0); // don't verify the hostname
+ }
}
else
{
diff --git a/src/System.Net.Http/src/System/Net/Http/Unix/CurlException.cs b/src/System.Net.Http/src/System/Net/Http/Unix/CurlException.cs
index cdf114b3ad..67da37e89d 100644
--- a/src/System.Net.Http/src/System/Net/Http/Unix/CurlException.cs
+++ b/src/System.Net.Http/src/System/Net/Http/Unix/CurlException.cs
@@ -13,6 +13,11 @@ namespace System.Net.Http
HResult = error;
}
+ internal CurlException(int error, Exception innerException) : base(GetCurlErrorString(error, isMulti:false), innerException)
+ {
+ HResult = error;
+ }
+
internal CurlException(int error, bool isMulti) : this(error, GetCurlErrorString(error, isMulti))
{
}
diff --git a/src/System.Net.Http/src/System/Net/Http/Unix/CurlHandler.MultiAgent.cs b/src/System.Net.Http/src/System/Net/Http/Unix/CurlHandler.MultiAgent.cs
index 63358976c2..db20c778a3 100644
--- a/src/System.Net.Http/src/System/Net/Http/Unix/CurlHandler.MultiAgent.cs
+++ b/src/System.Net.Http/src/System/Net/Http/Unix/CurlHandler.MultiAgent.cs
@@ -37,8 +37,8 @@ namespace System.Net.Http
private static readonly Interop.Http.ReadWriteCallback s_receiveBodyCallback = CurlReceiveBodyCallback;
private static readonly Interop.Http.DebugCallback s_debugCallback = CurlDebugFunction;
- /// <summary>CurlHandler that owns this MultiAgent.</summary>
- private readonly CurlHandler _associatedHandler;
+ /// <summary>CurlHandler that created this MultiAgent. If null, this is a shared handler.</summary>
+ private readonly CurlHandler _creatingHandler;
/// <summary>
/// A collection of not-yet-processed incoming requests for work to be done
@@ -79,18 +79,21 @@ namespace System.Net.Http
/// </summary>
private Interop.Http.SafeCurlMultiHandle _multiHandle;
+ /// <summary>Set when Dispose has been called.</summary>
+ private bool _disposed;
+
/// <summary>Initializes the MultiAgent.</summary>
- /// <param name="handler">The handler that owns this agent.</param>
+ /// <param name="handler">The handler that created this agent, or null if it's shared.</param>
public MultiAgent(CurlHandler handler)
{
- Debug.Assert(handler != null, "Expected non-null handler");
- _associatedHandler = handler;
+ _creatingHandler = handler;
}
/// <summary>Disposes of the agent.</summary>
public void Dispose()
{
EventSourceTrace(null);
+ _disposed = true;
QueueIfRunning(new IncomingRequest { Type = IncomingRequestType.Shutdown });
_multiHandle?.Dispose();
}
@@ -247,20 +250,25 @@ namespace System.Net.Http
EventSourceTrace("Set multiplexing on multi handle");
}
- // Configure max connections per host if it was changed from the default
- int maxConnections = _associatedHandler.MaxConnectionsPerServer;
- if (maxConnections < int.MaxValue) // int.MaxValue considered infinite, mapping to libcurl default of 0
+ // Configure max connections per host if it was changed from the default. In shared mode,
+ // this will be pulled from the handler that first created the agent; the setting from subsequent
+ // handlers that use this will be ignored.
+ if (_creatingHandler != null)
{
- CURLMcode code = Interop.Http.MultiSetOptionLong(multiHandle, Interop.Http.CURLMoption.CURLMOPT_MAX_HOST_CONNECTIONS, maxConnections);
- switch (code)
+ int maxConnections = _creatingHandler.MaxConnectionsPerServer;
+ if (maxConnections < int.MaxValue) // int.MaxValue considered infinite, mapping to libcurl default of 0
{
- case CURLMcode.CURLM_OK:
- EventSourceTrace("Set max host connections to {0}", maxConnections);
- break;
- default:
- // Treat failures as non-fatal in release; worst case is we employ more connections than desired.
- EventSourceTrace("Setting CURLMOPT_MAX_HOST_CONNECTIONS failed: {0}. Ignoring option.", code);
- break;
+ CURLMcode code = Interop.Http.MultiSetOptionLong(multiHandle, Interop.Http.CURLMoption.CURLMOPT_MAX_HOST_CONNECTIONS, maxConnections);
+ switch (code)
+ {
+ case CURLMcode.CURLM_OK:
+ EventSourceTrace("Set max host connections to {0}", maxConnections);
+ break;
+ default:
+ // Treat failures as non-fatal in release; worst case is we employ more connections than desired.
+ EventSourceTrace("Setting CURLMOPT_MAX_HOST_CONNECTIONS failed: {0}. Ignoring option.", code);
+ break;
+ }
}
}
@@ -306,7 +314,7 @@ namespace System.Net.Http
// more requests could have been added. If they were,
// kick off another processing loop.
_runningWorker = null;
- if (_incomingRequests.Count > 0 && !_associatedHandler._disposed)
+ if (_incomingRequests.Count > 0 && !_disposed)
{
EnsureWorkerIsRunning();
}
diff --git a/src/System.Net.Http/src/System/Net/Http/Unix/CurlHandler.SslProvider.cs b/src/System.Net.Http/src/System/Net/Http/Unix/CurlHandler.SslProvider.cs
index bf4625b878..d66abc7b04 100644
--- a/src/System.Net.Http/src/System/Net/Http/Unix/CurlHandler.SslProvider.cs
+++ b/src/System.Net.Http/src/System/Net/Http/Unix/CurlHandler.SslProvider.cs
@@ -249,113 +249,124 @@ namespace System.Net.Http
private static int VerifyCertChain(IntPtr storeCtxPtr, IntPtr curlPtr)
{
+ const int SuccessResult = 1, FailureResult = 0;
+
EasyRequest easy;
if (!TryGetEasyRequest(curlPtr, out easy))
{
EventSourceTrace("Could not find associated easy request: {0}", curlPtr);
- return 0;
+ return FailureResult;
}
- using (var storeCtx = new SafeX509StoreCtxHandle(storeCtxPtr, ownsHandle: false))
+ var storeCtx = new SafeX509StoreCtxHandle(storeCtxPtr, ownsHandle: false);
+ try
{
- IntPtr leafCertPtr = Interop.Crypto.X509StoreCtxGetTargetCert(storeCtx);
- if (IntPtr.Zero == leafCertPtr)
- {
- EventSourceTrace("Invalid certificate pointer", easy: easy);
- return 0;
- }
+ return VerifyCertChain(storeCtx, easy) ? SuccessResult : FailureResult;
+ }
+ catch (Exception exc)
+ {
+ EventSourceTrace("Unexpected exception: {0}", exc, easy: easy);
+ easy.FailRequest(CreateHttpRequestException(new CurlException((int)CURLcode.CURLE_ABORTED_BY_CALLBACK, exc)));
+ return FailureResult;
+ }
+ finally
+ {
+ storeCtx.Dispose();
+ }
+ }
- using (X509Certificate2 leafCert = new X509Certificate2(leafCertPtr))
+ private static bool VerifyCertChain(SafeX509StoreCtxHandle storeCtx, EasyRequest easy)
+ {
+ IntPtr leafCertPtr = Interop.Crypto.X509StoreCtxGetTargetCert(storeCtx);
+ if (leafCertPtr == IntPtr.Zero)
+ {
+ EventSourceTrace("Invalid certificate pointer", easy: easy);
+ return false;
+ }
+
+ X509Certificate2[] otherCerts = null;
+ int otherCertsCount = 0;
+ var leafCert = new X509Certificate2(leafCertPtr);
+ try
+ {
+ // We need to respect the user's server validation callback if there is one. If there isn't one,
+ // we can start by first trying to use OpenSSL's verification, though only if CRL checking is disabled,
+ // as OpenSSL doesn't do that.
+ if (easy._handler.ServerCertificateCustomValidationCallback == null &&
+ !easy._handler.CheckCertificateRevocationList)
{
- // We need to respect the user's server validation callback if there is one. If there isn't one,
- // we can start by first trying to use OpenSSL's verification, though only if CRL checking is disabled,
- // as OpenSSL doesn't do that.
- if (easy._handler.ServerCertificateCustomValidationCallback == null &&
- !easy._handler.CheckCertificateRevocationList)
+ // Start by using the default verification provided directly by OpenSSL.
+ // If it succeeds in verifying the cert chain, we're done. Employing this instead of
+ // our custom implementation will need to be revisited if we ever decide to introduce a
+ // "disallowed" store that enables users to "untrust" certs the system trusts.
+ int sslResult = Interop.Crypto.X509VerifyCert(storeCtx);
+ if (sslResult == 1)
{
- // Start by using the default verification provided directly by OpenSSL.
- // If it succeeds in verifying the cert chain, we're done. Employing this instead of
- // our custom implementation will need to be revisited if we ever decide to introduce a
- // "disallowed" store that enables users to "untrust" certs the system trusts.
- int sslResult = Interop.Crypto.X509VerifyCert(storeCtx);
- if (sslResult == 1)
- {
- return 1;
- }
-
- // X509_verify_cert can return < 0 in the case of programmer error
- Debug.Assert(sslResult == 0, "Unexpected error from X509_verify_cert: " + sslResult);
+ return true;
}
- // Either OpenSSL verification failed, or there was a server validation callback.
- // Either way, fall back to manual and more expensive verification that includes
- // checking the user's certs (not just the system store ones as OpenSSL does).
- X509Certificate2[] otherCerts;
- int otherCertsCount = 0;
- bool success;
- using (X509Chain chain = new X509Chain())
- {
- chain.ChainPolicy.RevocationMode = easy._handler.CheckCertificateRevocationList ? X509RevocationMode.Online : X509RevocationMode.NoCheck;
- chain.ChainPolicy.RevocationFlag = X509RevocationFlag.ExcludeRoot;
-
- using (SafeSharedX509StackHandle extraStack = Interop.Crypto.X509StoreCtxGetSharedUntrusted(storeCtx))
- {
- if (extraStack.IsInvalid)
- {
- otherCerts = Array.Empty<X509Certificate2>();
- }
- else
- {
- int extraSize = Interop.Crypto.GetX509StackFieldCount(extraStack);
- otherCerts = new X509Certificate2[extraSize];
+ // X509_verify_cert can return < 0 in the case of programmer error
+ Debug.Assert(sslResult == 0, "Unexpected error from X509_verify_cert: " + sslResult);
+ }
- for (int i = 0; i < extraSize; i++)
- {
- IntPtr certPtr = Interop.Crypto.GetX509StackField(extraStack, i);
- if (certPtr != IntPtr.Zero)
- {
- X509Certificate2 cert = new X509Certificate2(certPtr);
- otherCerts[otherCertsCount++] = cert;
- chain.ChainPolicy.ExtraStore.Add(cert);
- }
- }
- }
- }
+ // Either OpenSSL verification failed, or there was a server validation callback
+ // or certificate revocation checking was enabled. Either way, fall back to manual
+ // and more expensive verification that includes checking the user's certs (not
+ // just the system store ones as OpenSSL does).
+ using (var chain = new X509Chain())
+ {
+ chain.ChainPolicy.RevocationMode = easy._handler.CheckCertificateRevocationList ? X509RevocationMode.Online : X509RevocationMode.NoCheck;
+ chain.ChainPolicy.RevocationFlag = X509RevocationFlag.ExcludeRoot;
- var serverCallback = easy._handler._serverCertificateValidationCallback;
- if (serverCallback == null)
+ using (SafeSharedX509StackHandle extraStack = Interop.Crypto.X509StoreCtxGetSharedUntrusted(storeCtx))
+ {
+ if (extraStack.IsInvalid)
{
- SslPolicyErrors errors = CertificateValidation.BuildChainAndVerifyProperties(chain, leafCert,
- checkCertName: false, hostName: null); // libcurl already verifies the host name
- success = errors == SslPolicyErrors.None;
+ otherCerts = Array.Empty<X509Certificate2>();
}
else
{
- // Authenticate the remote party: (e.g. when operating in client mode, authenticate the server).
- chain.ChainPolicy.ApplicationPolicy.Add(s_serverAuthOid);
+ int extraSize = Interop.Crypto.GetX509StackFieldCount(extraStack);
+ otherCerts = new X509Certificate2[extraSize];
- SslPolicyErrors errors = CertificateValidation.BuildChainAndVerifyProperties(chain, leafCert,
- checkCertName: true, hostName: easy._requestMessage.RequestUri.Host); // we disabled automatic host verification, so we do it here
- try
+ for (int i = 0; i < extraSize; i++)
{
- success = serverCallback(easy._requestMessage, leafCert, chain, errors);
- }
- catch (Exception exc)
- {
- EventSourceTrace("Server validation callback threw exception: {0}", exc, easy: easy);
- easy.FailRequest(exc);
- success = false;
+ IntPtr certPtr = Interop.Crypto.GetX509StackField(extraStack, i);
+ if (certPtr != IntPtr.Zero)
+ {
+ X509Certificate2 cert = new X509Certificate2(certPtr);
+ otherCerts[otherCertsCount++] = cert;
+ chain.ChainPolicy.ExtraStore.Add(cert);
+ }
}
}
}
- for (int i = 0; i < otherCertsCount; i++)
+ var serverCallback = easy._handler._serverCertificateValidationCallback;
+ if (serverCallback == null)
{
- otherCerts[i].Dispose();
+ SslPolicyErrors errors = CertificateValidation.BuildChainAndVerifyProperties(chain, leafCert,
+ checkCertName: false, hostName: null); // libcurl already verifies the host name
+ return errors == SslPolicyErrors.None;
}
+ else
+ {
+ // Authenticate the remote party: (e.g. when operating in client mode, authenticate the server).
+ chain.ChainPolicy.ApplicationPolicy.Add(s_serverAuthOid);
- return success ? 1 : 0;
+ SslPolicyErrors errors = CertificateValidation.BuildChainAndVerifyProperties(chain, leafCert,
+ checkCertName: true, hostName: easy._requestMessage.RequestUri.Host); // we disabled automatic host verification, so we do it here
+ return serverCallback(easy._requestMessage, leafCert, chain, errors);
+ }
+ }
+ }
+ finally
+ {
+ for (int i = 0; i < otherCertsCount; i++)
+ {
+ otherCerts[i].Dispose();
}
+ leafCert.Dispose();
}
}
}
diff --git a/src/System.Net.Http/src/System/Net/Http/Unix/CurlHandler.cs b/src/System.Net.Http/src/System/Net/Http/Unix/CurlHandler.cs
index b962ca7529..a9e4e35791 100644
--- a/src/System.Net.Http/src/System/Net/Http/Unix/CurlHandler.cs
+++ b/src/System.Net.Http/src/System/Net/Http/Unix/CurlHandler.cs
@@ -126,6 +126,7 @@ namespace System.Net.Http
private static string s_curlVersionDescription;
private static string s_curlSslVersionDescription;
+ private static readonly MultiAgent s_singletonSharedAgent;
private readonly MultiAgent _agent;
private volatile bool _anyOperationStarted;
private volatile bool _disposed;
@@ -169,13 +170,28 @@ namespace System.Net.Http
{
EventSourceTrace($"libcurl: {CurlVersionDescription} {CurlSslVersionDescription} {features}");
}
+
+ // By default every CurlHandler gets its own MultiAgent. But for some backends,
+ // we need to restrict the number of threads involved in processing libcurl work,
+ // so we create a single MultiAgent that's used by all handlers.
+ bool useSingleton = false;
+ UseSingletonMultiAgent(ref useSingleton);
+ if (useSingleton)
+ {
+ s_singletonSharedAgent = new MultiAgent(null);
+ }
}
public CurlHandler()
{
- _agent = new MultiAgent(this);
+ // If the shared MultiAgent was initialized, use it.
+ // Otherwise, create a new MultiAgent for this handler.
+ _agent = s_singletonSharedAgent ?? new MultiAgent(this);
}
+ /// <summary>Overridden by another partial implementation to set <see cref="result"/> to true if a single MultiAgent should be used.</summary>
+ static partial void UseSingletonMultiAgent(ref bool result);
+
#region Properties
private static string CurlVersionDescription => s_curlVersionDescription ?? (s_curlVersionDescription = Interop.Http.GetVersionDescription() ?? string.Empty);
@@ -409,7 +425,7 @@ namespace System.Net.Http
protected override void Dispose(bool disposing)
{
_disposed = true;
- if (disposing)
+ if (disposing && _agent != s_singletonSharedAgent)
{
_agent.Dispose();
}
diff --git a/src/System.Net.Http/src/netcore50/System/Net/CookieHelper.cs b/src/System.Net.Http/src/uap/System/Net/CookieHelper.cs
index 19064500eb..19064500eb 100644
--- a/src/System.Net.Http/src/netcore50/System/Net/CookieHelper.cs
+++ b/src/System.Net.Http/src/uap/System/Net/CookieHelper.cs
diff --git a/src/System.Net.Http/src/netcore50/System/Net/HttpClientHandler.cs b/src/System.Net.Http/src/uap/System/Net/HttpClientHandler.cs
index 5a0717e35c..50147daaef 100644
--- a/src/System.Net.Http/src/netcore50/System/Net/HttpClientHandler.cs
+++ b/src/System.Net.Http/src/uap/System/Net/HttpClientHandler.cs
@@ -8,9 +8,12 @@ using System.Globalization;
using System.Net;
using System.Net.Http.Headers;
using System.Net.Security;
+using System.Runtime.ExceptionServices;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
+using System.Runtime.InteropServices.WindowsRuntime;
using System.Security.Authentication;
+using System.Security.Cryptography;
using System.Security.Cryptography.X509Certificates;
using System.Threading;
using System.Threading.Tasks;
@@ -20,22 +23,29 @@ using RTHttpBaseProtocolFilter = Windows.Web.Http.Filters.HttpBaseProtocolFilter
using RTHttpCacheReadBehavior = Windows.Web.Http.Filters.HttpCacheReadBehavior;
using RTHttpCacheWriteBehavior = Windows.Web.Http.Filters.HttpCacheWriteBehavior;
using RTHttpCookieUsageBehavior = Windows.Web.Http.Filters.HttpCookieUsageBehavior;
+using RTHttpRequestMessage = Windows.Web.Http.HttpRequestMessage;
using RTPasswordCredential = Windows.Security.Credentials.PasswordCredential;
using RTCertificate = Windows.Security.Cryptography.Certificates.Certificate;
-using RTCertificateQuery = Windows.Security.Cryptography.Certificates.CertificateQuery;
-using RTCertificateStores = Windows.Security.Cryptography.Certificates.CertificateStores;
+using RTChainValidationResult = Windows.Security.Cryptography.Certificates.ChainValidationResult;
+using RTHttpServerCustomValidationRequestedEventArgs = Windows.Web.Http.Filters.HttpServerCustomValidationRequestedEventArgs;
namespace System.Net.Http
{
public partial class HttpClientHandler : HttpMessageHandler
{
+ private const string RequestMessageLookupKey = "System.Net.Http.HttpRequestMessage";
+ private const string SavedExceptionDispatchInfoLookupKey = "System.Runtime.ExceptionServices.ExceptionDispatchInfo";
private const string ClientAuthenticationOID = "1.3.6.1.5.5.7.3.2";
+ private static Oid s_serverAuthOid = new Oid("1.3.6.1.5.5.7.3.1", "1.3.6.1.5.5.7.3.1");
private static readonly Lazy<bool> s_RTCookieUsageBehaviorSupported =
new Lazy<bool>(InitRTCookieUsageBehaviorSupported);
private static bool RTCookieUsageBehaviorSupported => s_RTCookieUsageBehaviorSupported.Value;
private static readonly Lazy<bool> s_RTNoCacheSupported =
new Lazy<bool>(InitRTNoCacheSupported);
private static bool RTNoCacheSupported => s_RTNoCacheSupported.Value;
+ private static readonly Lazy<bool> s_RTServerCustomValidationRequestedSupported =
+ new Lazy<bool>(InitRTServerCustomValidationRequestedSupported);
+ private static bool RTServerCustomValidationRequestedSupported => s_RTServerCustomValidationRequestedSupported.Value;
#region Fields
@@ -43,9 +53,6 @@ namespace System.Net.Http
private readonly HttpHandlerToFilter _handlerToFilter;
private readonly HttpMessageHandler _diagnosticsPipeline;
- private volatile bool _operationStarted;
- private volatile bool _disposed;
-
private ClientCertificateOption _clientCertificateOptions;
private CookieContainer _cookieContainer;
private bool _useCookies;
@@ -55,6 +62,7 @@ namespace System.Net.Http
private IWebProxy _proxy;
private X509Certificate2Collection _clientCertificates;
private IDictionary<String, Object> _properties; // Only create dictionary when required.
+ private Func<HttpRequestMessage, X509Certificate2, X509Chain, SslPolicyErrors, bool> _serverCertificateCustomValidationCallback;
#endregion Fields
@@ -245,23 +253,6 @@ namespace System.Net.Http
_rtFilter.MaxConnectionsPerServer = (uint)value;
}
}
-
- public long MaxRequestContentBufferSize
- {
- get { return HttpContent.MaxBufferSize; }
- set
- {
- // .NET Native port note: We don't have an easy way to implement the MaxRequestContentBufferSize property. To maximize the chance of app compat,
- // we will "succeed" as long as the requested buffer size doesn't exceed the max. However, no actual
- // enforcement of the max buffer size occurs.
- if (value > MaxRequestContentBufferSize)
- {
- throw new PlatformNotSupportedException(String.Format(CultureInfo.InvariantCulture,
- SR.net_http_value_not_supported, value, nameof(MaxRequestContentBufferSize)));
- }
- CheckDisposedOrStarted();
- }
- }
public int MaxResponseHeadersLength
{
@@ -277,9 +268,16 @@ namespace System.Net.Http
public X509CertificateCollection ClientCertificates
{
- // TODO: Not yet implemented. Issue #7623.
get
{
+ if (_clientCertificateOptions != ClientCertificateOption.Manual)
+ {
+ throw new InvalidOperationException(SR.Format(
+ SR.net_http_invalid_enable_first,
+ nameof(ClientCertificateOptions),
+ nameof(ClientCertificateOption.Manual)));
+ }
+
if (_clientCertificates == null)
{
_clientCertificates = new X509Certificate2Collection();
@@ -291,18 +289,23 @@ namespace System.Net.Http
public Func<HttpRequestMessage, X509Certificate2, X509Chain, SslPolicyErrors, bool> ServerCertificateCustomValidationCallback
{
- // TODO: Not yet implemented. Issue #7623.
- get{ return null; }
+ get
+ {
+ return _serverCertificateCustomValidationCallback;
+ }
set
{
CheckDisposedOrStarted();
if (value != null)
{
- /*
- throw new PlatformNotSupportedException(String.Format(CultureInfo.InvariantCulture,
- SR.net_http_value_not_supported, value, nameof(ServerCertificateCustomValidationCallback)));
- */
+ if (!RTServerCustomValidationRequestedSupported)
+ {
+ throw new PlatformNotSupportedException(string.Format(CultureInfo.InvariantCulture,
+ SR.net_http_feature_requires_Windows10Version1607));
+ }
}
+
+ _serverCertificateCustomValidationCallback = value;
}
}
@@ -349,6 +352,8 @@ namespace System.Net.Http
{
_rtFilter = new RTHttpBaseProtocolFilter();
_handlerToFilter = new HttpHandlerToFilter(_rtFilter);
+ _handlerToFilter.RequestMessageLookupKey = RequestMessageLookupKey;
+ _handlerToFilter.SavedExceptionDispatchInfoLookupKey = SavedExceptionDispatchInfoLookupKey;
_diagnosticsPipeline = new DiagnosticsHandler(_handlerToFilter);
_clientCertificateOptions = ClientCertificateOption.Manual;
@@ -456,18 +461,40 @@ namespace System.Net.Http
{
if (ClientCertificateOptions == ClientCertificateOption.Manual)
{
- return;
- }
+ if (_clientCertificates != null && _clientCertificates.Count > 0)
+ {
+ X509Certificate2 clientCert = CertificateHelper.GetEligibleClientCertificate(_clientCertificates);
+ if (clientCert == null)
+ {
+ return;
+ }
- // Get the certs that can be used for Client Authentication.
- var query = new RTCertificateQuery();
- var ekus = query.EnhancedKeyUsages;
- ekus.Add(ClientAuthenticationOID);
- var clientCertificates = await RTCertificateStores.FindAllAsync(query).AsTask().ConfigureAwait(false);
+ RTCertificate rtClientCert = await CertificateHelper.ConvertDotNetClientCertToWinRtClientCertAsync(clientCert);
+ if (rtClientCert == null)
+ {
+ throw new PlatformNotSupportedException(string.Format(CultureInfo.InvariantCulture,
+ SR.net_http_feature_UWPClientCertSupportRequiresCertInPersonalCertificateStore));
+ }
- if (clientCertificates.Count > 0)
+ _rtFilter.ClientCertificate = rtClientCert;
+ }
+
+ return;
+ }
+ else
{
- _rtFilter.ClientCertificate = clientCertificates[0];
+ X509Certificate2 clientCert = CertificateHelper.GetEligibleClientCertificate();
+ if (clientCert == null)
+ {
+ return;
+ }
+
+ // Unlike in the .Manual case above, the conversion to WinRT Certificate should always work;
+ // so we just use an Assert. All the possible client certs were enumerated from that store and
+ // filtered down to a single client cert.
+ RTCertificate rtClientCert = await CertificateHelper.ConvertDotNetClientCertToWinRtClientCertAsync(clientCert);
+ Debug.Assert(rtClientCert != null);
+ _rtFilter.ClientCertificate = rtClientCert;
}
}
@@ -573,7 +600,7 @@ namespace System.Net.Http
}
catch (Exception ex)
{
- // Convert back to the expected exception type
+ // Convert back to the expected exception type.
throw new HttpRequestException(SR.net_http_client_execution_error, ex);
}
@@ -645,28 +672,38 @@ namespace System.Net.Http
{
if (!_operationStarted)
{
- // Since this is the first operation, we set the proxy and server credentials on the
- // WinRT filter based on the .NET handler's property settings.
+ // Since this is the first operation, we set all the necessary WinRT filter properties.
SetFilterProxyCredential();
SetFilterServerCredential();
- _operationStarted = true;
- }
- }
-
- private void CheckDisposed()
- {
- if (_disposed)
- {
- throw new ObjectDisposedException(GetType().ToString());
- }
- }
+ if (_serverCertificateCustomValidationCallback != null)
+ {
+ Debug.Assert(RTServerCustomValidationRequestedSupported);
+
+ // The WinRT layer uses a different model for the certificate callback. The callback is
+ // considered "extra" validation. We need to explicitly ignore errors so that the callback
+ // will get called.
+ //
+ // In addition, the WinRT layer restricts some errors so that they cannot be ignored, such
+ // as "Revoked". This will result in behavior differences between UWP and other platforms.
+ // The following errors cannot be ignored right now in the WinRT layer:
+ //
+ // ChainValidationResult.BasicConstraintsError
+ // ChainValidationResult.InvalidCertificateAuthorityPolicy
+ // ChainValidationResult.InvalidSignature
+ // ChainValidationResult.OtherErrors
+ // ChainValidationResult.Revoked
+ // ChainValidationResult.UnknownCriticalExtension
+ _rtFilter.IgnorableServerCertificateErrors.Add(RTChainValidationResult.Expired);
+ _rtFilter.IgnorableServerCertificateErrors.Add(RTChainValidationResult.IncompleteChain);
+ _rtFilter.IgnorableServerCertificateErrors.Add(RTChainValidationResult.InvalidName);
+ _rtFilter.IgnorableServerCertificateErrors.Add(RTChainValidationResult.RevocationFailure);
+ _rtFilter.IgnorableServerCertificateErrors.Add(RTChainValidationResult.RevocationInformationMissing);
+ _rtFilter.IgnorableServerCertificateErrors.Add(RTChainValidationResult.Untrusted);
+ _rtFilter.IgnorableServerCertificateErrors.Add(RTChainValidationResult.WrongUsage);
+ _rtFilter.ServerCustomValidationRequested += RTServerCertificateCallback;
+ }
- private void CheckDisposedOrStarted()
- {
- CheckDisposed();
- if (_operationStarted)
- {
- throw new InvalidOperationException(SR.net_http_operation_started);
+ _operationStarted = true;
}
}
@@ -684,6 +721,89 @@ namespace System.Net.Http
"NoCache");
}
+ private static bool InitRTServerCustomValidationRequestedSupported()
+ {
+ return RTApiInformation.IsEventPresent(
+ "Windows.Web.Http.Filters.HttpBaseProtocolFilter",
+ "ServerCustomValidationRequested");
+ }
+
+ private void RTServerCertificateCallback(RTHttpBaseProtocolFilter sender, RTHttpServerCustomValidationRequestedEventArgs args)
+ {
+ bool success = RTServerCertificateCallbackHelper(
+ args.RequestMessage,
+ args.ServerCertificate,
+ args.ServerIntermediateCertificates,
+ args.ServerCertificateErrors);
+
+ if (!success)
+ {
+ args.Reject();
+ }
+ }
+
+ private bool RTServerCertificateCallbackHelper(
+ RTHttpRequestMessage requestMessage,
+ RTCertificate cert,
+ IReadOnlyList<RTCertificate> intermediateCerts,
+ IReadOnlyList<RTChainValidationResult> certErrors)
+ {
+ // Convert WinRT certificate to .NET certificate.
+ X509Certificate2 serverCert = CertificateHelper.ConvertPublicKeyCertificate(cert);
+
+ // Create .NET X509Chain from the WinRT information. We need to rebuild the chain since WinRT only
+ // gives us an array of intermediate certificates and not a X509Chain object.
+ var serverChain = new X509Chain();
+ SslPolicyErrors sslPolicyErrors = SslPolicyErrors.None;
+ foreach (RTCertificate intermediateCert in intermediateCerts)
+ {
+ serverChain.ChainPolicy.ExtraStore.Add(CertificateHelper.ConvertPublicKeyCertificate(cert));
+ }
+ serverChain.ChainPolicy.RevocationMode = X509RevocationMode.Online; // WinRT always checks revocation.
+ serverChain.ChainPolicy.RevocationFlag = X509RevocationFlag.ExcludeRoot;
+ // Authenticate the remote party: (e.g. when operating in client mode, authenticate the server).
+ serverChain.ChainPolicy.ApplicationPolicy.Add(s_serverAuthOid);
+ if (!serverChain.Build(serverCert))
+ {
+ sslPolicyErrors |= SslPolicyErrors.RemoteCertificateChainErrors;
+ }
+
+ // Determine name-mismatch error from the existing WinRT information since .NET X509Chain.Build does not
+ // return that in the X509Chain.ChainStatus fields.
+ foreach (RTChainValidationResult result in certErrors)
+ {
+ if (result == RTChainValidationResult.InvalidName)
+ {
+ sslPolicyErrors |= SslPolicyErrors.RemoteCertificateNameMismatch;
+ break;
+ }
+ }
+
+ // Get the .NET HttpRequestMessage we saved in the property bag of the WinRT HttpRequestMessage.
+ HttpRequestMessage request = (HttpRequestMessage)requestMessage.Properties[RequestMessageLookupKey];
+
+ // Call the .NET callback.
+ bool success = false;
+ try
+ {
+ success = _serverCertificateCustomValidationCallback(request, serverCert, serverChain, sslPolicyErrors);
+ }
+ catch (Exception ex)
+ {
+ // Save the exception info. We will return it later via the SendAsync response processing.
+ requestMessage.Properties.Add(
+ SavedExceptionDispatchInfoLookupKey,
+ ExceptionDispatchInfo.Capture(ex));
+ }
+ finally
+ {
+ serverChain.Dispose();
+ serverCert.Dispose();
+ }
+
+ return success;
+ }
+
#endregion Helpers
}
}
diff --git a/src/System.Net.Http/src/netcore50/System/Net/HttpHandlerToFilter.cs b/src/System.Net.Http/src/uap/System/Net/HttpHandlerToFilter.cs
index 322f0227e1..dc75083cd6 100644
--- a/src/System.Net.Http/src/netcore50/System/Net/HttpHandlerToFilter.cs
+++ b/src/System.Net.Http/src/uap/System/Net/HttpHandlerToFilter.cs
@@ -5,6 +5,7 @@
using System.Collections.Generic;
using System.Diagnostics;
using System.IO;
+using System.Runtime.ExceptionServices;
using System.Runtime.InteropServices.WindowsRuntime;
using System.Threading;
using System.Threading.Tasks;
@@ -39,6 +40,9 @@ namespace System.Net.Http
_filterMaxVersionSet = 0;
}
+ internal string RequestMessageLookupKey { get; set; }
+ internal string SavedExceptionDispatchInfoLookupKey { get; set; }
+
protected internal override async Task<HttpResponseMessage> SendAsync(HttpRequestMessage request, CancellationToken cancel)
{
if (request == null)
@@ -47,9 +51,27 @@ namespace System.Net.Http
}
cancel.ThrowIfCancellationRequested();
-
RTHttpRequestMessage rtRequest = await ConvertRequestAsync(request).ConfigureAwait(false);
- RTHttpResponseMessage rtResponse = await _next.SendRequestAsync(rtRequest).AsTask(cancel).ConfigureAwait(false);
+
+ RTHttpResponseMessage rtResponse;
+ try
+ {
+ rtResponse = await _next.SendRequestAsync(rtRequest).AsTask(cancel).ConfigureAwait(false);
+ }
+ catch (TaskCanceledException)
+ {
+ throw;
+ }
+ catch (Exception)
+ {
+ object info;
+ if (rtRequest.Properties.TryGetValue(SavedExceptionDispatchInfoLookupKey, out info))
+ {
+ ((ExceptionDispatchInfo)info).Throw();
+ }
+
+ throw;
+ }
// Update in case of redirects
request.RequestUri = rtRequest.RequestUri;
@@ -64,6 +86,9 @@ namespace System.Net.Http
{
RTHttpRequestMessage rtRequest = new RTHttpRequestMessage(new RTHttpMethod(request.Method.Method), request.RequestUri);
+ // Add a reference from the WinRT object back to the .NET object.
+ rtRequest.Properties.Add(RequestMessageLookupKey, request);
+
// We can only control the Version on the first request message since the WinRT API
// has this property designed as a filter/handler property. In addition the overall design
// of HTTP/2.0 is such that once the first request is using it, all the other requests
diff --git a/src/System.Net.Http/src/netcore50/System/Net/cookie.cs b/src/System.Net.Http/src/uap/System/Net/cookie.cs
index 9a94a76e79..9a94a76e79 100644
--- a/src/System.Net.Http/src/netcore50/System/Net/cookie.cs
+++ b/src/System.Net.Http/src/uap/System/Net/cookie.cs
diff --git a/src/System.Net.Http/src/netcore50/System/Net/cookieexception.cs b/src/System.Net.Http/src/uap/System/Net/cookieexception.cs
index c497d0c42b..c497d0c42b 100644
--- a/src/System.Net.Http/src/netcore50/System/Net/cookieexception.cs
+++ b/src/System.Net.Http/src/uap/System/Net/cookieexception.cs
diff --git a/src/System.Net.Http/tests/FunctionalTests/HttpClientHandlerTest.AcceptAllCerts.cs b/src/System.Net.Http/tests/FunctionalTests/HttpClientHandlerTest.AcceptAllCerts.cs
index 69ce6fff37..d041d0f0dd 100644
--- a/src/System.Net.Http/tests/FunctionalTests/HttpClientHandlerTest.AcceptAllCerts.cs
+++ b/src/System.Net.Http/tests/FunctionalTests/HttpClientHandlerTest.AcceptAllCerts.cs
@@ -15,6 +15,9 @@ namespace System.Net.Http.Functional.Tests
public class HttpClientHandler_DangerousAcceptAllCertificatesValidator_Test
{
+ // TODO: https://github.com/dotnet/corefx/issues/7812
+ private static bool ClientSupportsDHECipherSuites => (!PlatformDetection.IsWindows || PlatformDetection.IsWindows10Version1607OrGreater);
+
[Fact]
public void SingletonReturnsTrue()
{
@@ -35,7 +38,11 @@ namespace System.Net.Http.Functional.Tests
using (var handler = new HttpClientHandler() { ServerCertificateCustomValidationCallback = HttpClientHandler.DangerousAcceptAnyServerCertificateValidator })
using (var client = new HttpClient(handler))
{
- if (requestOnlyThisProtocol)
+ // Refer issue: #22089
+ // When the server uses SslProtocols.Tls, on MacOS, SecureTransport ends up picking a cipher suite
+ // for TLS1.2, even though server said it was only using TLS1.0. LibreSsl throws error that
+ // wrong cipher is used for TLs1.0.
+ if (requestOnlyThisProtocol || (PlatformDetection.IsMacOsHighSierra && acceptedProtocol == SslProtocols.Tls))
{
handler.SslProtocols = acceptedProtocol;
}
@@ -57,9 +64,8 @@ namespace System.Net.Http.Functional.Tests
new object[] { Configuration.Http.WrongHostNameCertRemoteServer },
};
- [ActiveIssue(7812, TestPlatforms.Windows)]
[OuterLoop] // TODO: Issue #11345
- [Theory]
+ [ConditionalTheory(nameof(ClientSupportsDHECipherSuites))]
[MemberData(nameof(InvalidCertificateServers))]
public async Task InvalidCertificateServers_CertificateValidationDisabled_Succeeds(string url)
{
diff --git a/src/System.Net.Http/tests/FunctionalTests/HttpClientHandlerTest.ClientCertificates.cs b/src/System.Net.Http/tests/FunctionalTests/HttpClientHandlerTest.ClientCertificates.cs
index 19a05df905..2b8dd5aca9 100644
--- a/src/System.Net.Http/tests/FunctionalTests/HttpClientHandlerTest.ClientCertificates.cs
+++ b/src/System.Net.Http/tests/FunctionalTests/HttpClientHandlerTest.ClientCertificates.cs
@@ -2,21 +2,34 @@
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
+using System.Diagnostics;
using System.Net.Security;
using System.Net.Sockets;
using System.Net.Test.Common;
-using System.Runtime.InteropServices;
using System.Security.Cryptography.X509Certificates;
using System.Threading.Tasks;
using Xunit;
+using Xunit.Abstractions;
namespace System.Net.Http.Functional.Tests
{
using Configuration = System.Net.Test.Common.Configuration;
- [SkipOnTargetFramework(TargetFrameworkMonikers.Uap, "dotnet/corefx #20010")]
- public class HttpClientHandler_ClientCertificates_Test
+ public class HttpClientHandler_ClientCertificates_Test : RemoteExecutorTestBase
{
+ public static bool CanTestCertificates =>
+ Capability.IsTrustedRootCertificateInstalled() &&
+ (BackendSupportsCustomCertificateHandling || Capability.AreHostsFileNamesInstalled());
+
+ public static bool CanTestClientCertificates =>
+ CanTestCertificates && BackendSupportsCustomCertificateHandling;
+
+ public HttpClientHandler_ClientCertificates_Test(ITestOutputHelper output)
+ {
+ _output = output;
+ }
+
+ private readonly ITestOutputHelper _output;
[Fact]
public void ClientCertificateOptions_Default()
{
@@ -60,9 +73,14 @@ namespace System.Net.Http.Functional.Tests
}
[OuterLoop] // TODO: Issue #11345
- [ConditionalFact(nameof(BackendDoesNotSupportCustomCertificateHandling))]
+ [Fact]
public async Task Automatic_SSLBackendNotSupported_ThrowsPlatformNotSupportedException()
{
+ if (BackendSupportsCustomCertificateHandling) // can't use [Conditional*] right now as it's evaluated at the wrong time for the managed handler
+ {
+ return;
+ }
+
using (var client = new HttpClient(new HttpClientHandler() { ClientCertificateOptions = ClientCertificateOption.Automatic }))
{
await Assert.ThrowsAsync<PlatformNotSupportedException>(() => client.GetAsync(Configuration.Http.SecureRemoteEchoServer));
@@ -70,9 +88,14 @@ namespace System.Net.Http.Functional.Tests
}
[OuterLoop] // TODO: Issue #11345
- [ConditionalFact(nameof(BackendDoesNotSupportCustomCertificateHandling))]
+ [Fact]
public async Task Manual_SSLBackendNotSupported_ThrowsPlatformNotSupportedException()
{
+ if (BackendSupportsCustomCertificateHandling) // can't use [Conditional*] right now as it's evaluated at the wrong time for the managed handler
+ {
+ return;
+ }
+
var handler = new HttpClientHandler();
handler.ClientCertificates.Add(Configuration.Certificates.GetClientCertificate());
using (var client = new HttpClient(handler))
@@ -82,14 +105,121 @@ namespace System.Net.Http.Functional.Tests
}
[OuterLoop] // TODO: Issue #11345
+ [Fact]
+ public void Manual_SendClientCertificateWithClientAuthEKUToRemoteServer_OK()
+ {
+ if (!CanTestClientCertificates) // can't use [Conditional*] right now as it's evaluated at the wrong time for the managed handler
+ {
+ _output.WriteLine($"Skipping {nameof(Manual_SendClientCertificateWithClientAuthEKUToRemoteServer_OK)}()");
+ return;
+ }
+
+ // UAP HTTP stack caches connections per-process. This causes interference when these tests run in
+ // the same process as the other tests. Each test needs to be isolated to its own process.
+ // See dicussion: https://github.com/dotnet/corefx/issues/21945
+ RemoteInvoke(async () =>
+ {
+ var cert = Configuration.Certificates.GetClientCertificate();
+ var handler = new HttpClientHandler();
+ handler.ClientCertificates.Add(cert);
+ using (var client = new HttpClient(handler))
+ {
+ HttpResponseMessage response = await client.GetAsync(Configuration.Http.EchoClientCertificateRemoteServer);
+ Assert.Equal(HttpStatusCode.OK, response.StatusCode);
+
+ string body = await response.Content.ReadAsStringAsync();
+ byte[] bytes = Convert.FromBase64String(body);
+ var receivedCert = new X509Certificate2(bytes);
+ Assert.Equal(cert, receivedCert);
+
+ return SuccessExitCode;
+ }
+ }).Dispose();
+ }
+
+ [OuterLoop] // TODO: Issue #11345
+ [Fact]
+ public void Manual_SendClientCertificateWithServerAuthEKUToRemoteServer_Forbidden()
+ {
+ if (ManagedHandlerTestHelpers.IsEnabled)
+ {
+ // TODO #21452: The managed handler is currently sending out client certificates when it shouldn't.
+ return;
+ }
+
+ if (!CanTestClientCertificates) // can't use [Conditional*] right now as it's evaluated at the wrong time for the managed handler
+ {
+ _output.WriteLine($"Skipping {nameof(Manual_SendClientCertificateWithServerAuthEKUToRemoteServer_Forbidden)}()");
+ return;
+ }
+
+ // UAP HTTP stack caches connections per-process. This causes interference when these tests run in
+ // the same process as the other tests. Each test needs to be isolated to its own process.
+ // See dicussion: https://github.com/dotnet/corefx/issues/21945
+ RemoteInvoke(async () =>
+ {
+ var cert = Configuration.Certificates.GetServerCertificate();
+ var handler = new HttpClientHandler();
+ handler.ClientCertificates.Add(cert);
+ using (var client = new HttpClient(handler))
+ {
+ HttpResponseMessage response = await client.GetAsync(Configuration.Http.EchoClientCertificateRemoteServer);
+ Assert.Equal(HttpStatusCode.Forbidden, response.StatusCode);
+
+ return SuccessExitCode;
+ }
+ }).Dispose();
+ }
+
+ [OuterLoop] // TODO: Issue #11345
+ [Fact]
+ public void Manual_SendClientCertificateWithNoEKUToRemoteServer_OK()
+ {
+ if (!CanTestClientCertificates) // can't use [Conditional*] right now as it's evaluated at the wrong time for the managed handler
+ {
+ _output.WriteLine($"Skipping {nameof(Manual_SendClientCertificateWithNoEKUToRemoteServer_OK)}()");
+ return;
+ }
+
+ // UAP HTTP stack caches connections per-process. This causes interference when these tests run in
+ // the same process as the other tests. Each test needs to be isolated to its own process.
+ // See dicussion: https://github.com/dotnet/corefx/issues/21945
+ RemoteInvoke(async () =>
+ {
+ var cert = Configuration.Certificates.GetNoEKUCertificate();
+ var handler = new HttpClientHandler();
+ handler.ClientCertificates.Add(cert);
+ using (var client = new HttpClient(handler))
+ {
+ HttpResponseMessage response = await client.GetAsync(Configuration.Http.EchoClientCertificateRemoteServer);
+ Assert.Equal(HttpStatusCode.OK, response.StatusCode);
+
+ string body = await response.Content.ReadAsStringAsync();
+ byte[] bytes = Convert.FromBase64String(body);
+ var receivedCert = new X509Certificate2(bytes);
+ Assert.Equal(cert, receivedCert);
+
+ return SuccessExitCode;
+ }
+ }).Dispose();
+ }
+
+ [SkipOnTargetFramework(TargetFrameworkMonikers.Uap, "dotnet/corefx #20010")]
+ [OuterLoop] // TODO: Issue #11345
[ActiveIssue(9543)] // fails sporadically with 'WinHttpException : The server returned an invalid or unrecognized response' or 'TaskCanceledException : A task was canceled'
- [ConditionalTheory(nameof(BackendSupportsCustomCertificateHandling))]
+ [Theory]
[InlineData(6, false)]
[InlineData(3, true)]
public async Task Manual_CertificateSentMatchesCertificateReceived_Success(
int numberOfRequests,
bool reuseClient) // validate behavior with and without connection pooling, which impacts client cert usage
{
+ if (BackendDoesNotSupportCustomCertificateHandling) // can't use [Conditional*] right now as it's evaluated at the wrong time for the managed handler
+ {
+ _output.WriteLine($"Skipping {nameof(Manual_CertificateSentMatchesCertificateReceived_Success)}()");
+ return;
+ }
+
var options = new LoopbackServer.Options { UseSsl = true };
Func<X509Certificate2, HttpClient> createClient = (cert) =>
diff --git a/src/System.Net.Http/tests/FunctionalTests/HttpClientHandlerTest.ServerCertificates.Unix.cs b/src/System.Net.Http/tests/FunctionalTests/HttpClientHandlerTest.ServerCertificates.Unix.cs
index 424b4cbb9a..bb9d8e4901 100644
--- a/src/System.Net.Http/tests/FunctionalTests/HttpClientHandlerTest.ServerCertificates.Unix.cs
+++ b/src/System.Net.Http/tests/FunctionalTests/HttpClientHandlerTest.ServerCertificates.Unix.cs
@@ -3,6 +3,7 @@
// See the LICENSE file in the project root for more information.
using System.Collections.Generic;
+using System.Diagnostics;
using System.Net.Security;
using System.Net.Test.Common;
using System.Runtime.InteropServices;
@@ -13,12 +14,17 @@ using Xunit;
namespace System.Net.Http.Functional.Tests
{
- public partial class HttpClientHandler_ServerCertificates_Test
+ public partial class HttpClientHandler_ServerCertificates_Test : RemoteExecutorTestBase
{
private static bool ShouldSuppressRevocationException
{
get
{
+ if (ManagedHandlerTestHelpers.IsEnabled)
+ {
+ return false;
+ }
+
if (!RuntimeInformation.IsOSPlatform(OSPlatform.OSX))
{
return false;
@@ -51,6 +57,11 @@ namespace System.Net.Http.Functional.Tests
{
get
{
+ if (ManagedHandlerTestHelpers.IsEnabled)
+ {
+ return true;
+ }
+
if (RuntimeInformation.IsOSPlatform(OSPlatform.OSX))
{
return false;
diff --git a/src/System.Net.Http/tests/FunctionalTests/HttpClientHandlerTest.ServerCertificates.Windows.cs b/src/System.Net.Http/tests/FunctionalTests/HttpClientHandlerTest.ServerCertificates.Windows.cs
index c857c52996..b44163a41e 100644
--- a/src/System.Net.Http/tests/FunctionalTests/HttpClientHandlerTest.ServerCertificates.Windows.cs
+++ b/src/System.Net.Http/tests/FunctionalTests/HttpClientHandlerTest.ServerCertificates.Windows.cs
@@ -3,6 +3,7 @@
// See the LICENSE file in the project root for more information.
using System.Collections.Generic;
+using System.Diagnostics;
using System.Net.Security;
using System.Net.Test.Common;
using System.Runtime.InteropServices;
@@ -13,7 +14,7 @@ using Xunit;
namespace System.Net.Http.Functional.Tests
{
- public partial class HttpClientHandler_ServerCertificates_Test
+ public partial class HttpClientHandler_ServerCertificates_Test : RemoteExecutorTestBase
{
private static bool ShouldSuppressRevocationException => false;
diff --git a/src/System.Net.Http/tests/FunctionalTests/HttpClientHandlerTest.ServerCertificates.cs b/src/System.Net.Http/tests/FunctionalTests/HttpClientHandlerTest.ServerCertificates.cs
index a055138899..0bc4842695 100644
--- a/src/System.Net.Http/tests/FunctionalTests/HttpClientHandlerTest.ServerCertificates.cs
+++ b/src/System.Net.Http/tests/FunctionalTests/HttpClientHandlerTest.ServerCertificates.cs
@@ -3,9 +3,9 @@
// See the LICENSE file in the project root for more information.
using System.Collections.Generic;
+using System.Diagnostics;
using System.Net.Security;
using System.Net.Test.Common;
-using System.Runtime.InteropServices;
using System.Security.Authentication.ExtendedProtection;
using System.Security.Cryptography.X509Certificates;
using System.Threading.Tasks;
@@ -15,19 +15,43 @@ namespace System.Net.Http.Functional.Tests
{
using Configuration = System.Net.Test.Common.Configuration;
- [SkipOnTargetFramework(TargetFrameworkMonikers.Uap | TargetFrameworkMonikers.NetFramework, "uap: dotnet/corefx #20010, netfx: dotnet/corefx #16805")]
- public partial class HttpClientHandler_ServerCertificates_Test
+ [SkipOnTargetFramework(TargetFrameworkMonikers.NetFramework, ".NET Framework throws PNSE for ServerCertificateCustomValidationCallback")]
+ public partial class HttpClientHandler_ServerCertificates_Test : RemoteExecutorTestBase
{
- [OuterLoop] // TODO: Issue #11345
+ // TODO: https://github.com/dotnet/corefx/issues/7812
+ private static bool ClientSupportsDHECipherSuites => (!PlatformDetection.IsWindows || PlatformDetection.IsWindows10Version1607OrGreater);
+ private static bool BackendSupportsCustomCertificateHandlingAndClientSupportsDHECipherSuites =>
+ (BackendSupportsCustomCertificateHandling && ClientSupportsDHECipherSuites);
+
[Fact]
- public async Task NoCallback_ValidCertificate_CallbackNotCalled()
+ [SkipOnTargetFramework(~TargetFrameworkMonikers.Uap)]
+ public void Ctor_ExpectedDefaultPropertyValues_UapPlatform()
{
- var handler = new HttpClientHandler();
- using (var client = new HttpClient(handler))
+ using (var handler = new HttpClientHandler())
+ {
+ Assert.Null(handler.ServerCertificateCustomValidationCallback);
+ Assert.True(handler.CheckCertificateRevocationList);
+ }
+ }
+
+ [Fact]
+ [SkipOnTargetFramework(TargetFrameworkMonikers.Uap)]
+ public void Ctor_ExpectedDefaultValues_NotUapPlatform()
+ {
+ using (var handler = new HttpClientHandler())
{
Assert.Null(handler.ServerCertificateCustomValidationCallback);
Assert.False(handler.CheckCertificateRevocationList);
+ }
+ }
+ [OuterLoop] // TODO: Issue #11345
+ [Fact]
+ public async Task NoCallback_ValidCertificate_SuccessAndExpectedPropertyBehavior()
+ {
+ var handler = new HttpClientHandler();
+ using (var client = new HttpClient(handler))
+ {
using (HttpResponseMessage response = await client.GetAsync(Configuration.Http.SecureRemoteEchoServer))
{
Assert.Equal(HttpStatusCode.OK, response.StatusCode);
@@ -38,6 +62,7 @@ namespace System.Net.Http.Functional.Tests
}
}
+ [SkipOnTargetFramework(TargetFrameworkMonikers.Uap, "UAP won't send requests through a custom proxy")]
[OuterLoop] // TODO: Issue #11345
[ConditionalFact(nameof(BackendSupportsCustomCertificateHandling))]
public async Task UseCallback_HaveNoCredsAndUseAuthenticatedCustomProxyAndPostToSecureServer_ProxyAuthenticationRequiredStatusCode()
@@ -69,11 +94,17 @@ namespace System.Net.Http.Functional.Tests
}
}
}
-
+
[OuterLoop] // TODO: Issue #11345
- [ConditionalFact(nameof(BackendSupportsCustomCertificateHandling))]
+ [Fact]
public async Task UseCallback_NotSecureConnection_CallbackNotCalled()
{
+ if (BackendDoesNotSupportCustomCertificateHandling) // can't use [Conditional*] right now as it's evaluated at the wrong time for the managed handler
+ {
+ Console.WriteLine($"Skipping {nameof(UseCallback_NotSecureConnection_CallbackNotCalled)}()");
+ return;
+ }
+
var handler = new HttpClientHandler();
using (var client = new HttpClient(handler))
{
@@ -105,10 +136,16 @@ namespace System.Net.Http.Functional.Tests
}
[OuterLoop] // TODO: Issue #11345
- [ConditionalTheory(nameof(BackendSupportsCustomCertificateHandling))]
+ [Theory]
[MemberData(nameof(UseCallback_ValidCertificate_ExpectedValuesDuringCallback_Urls))]
public async Task UseCallback_ValidCertificate_ExpectedValuesDuringCallback(Uri url, bool checkRevocation)
{
+ if (BackendDoesNotSupportCustomCertificateHandling) // can't use [Conditional*] right now as it's evaluated at the wrong time for the managed handler
+ {
+ Console.WriteLine($"Skipping {nameof(UseCallback_ValidCertificate_ExpectedValuesDuringCallback)}({url}, {checkRevocation})");
+ return;
+ }
+
var handler = new HttpClientHandler();
using (var client = new HttpClient(handler))
{
@@ -120,7 +157,13 @@ namespace System.Net.Http.Functional.Tests
Assert.Equal(SslPolicyErrors.None, errors);
Assert.True(chain.ChainElements.Count > 0);
Assert.NotEmpty(cert.Subject);
- Assert.Equal(checkRevocation ? X509RevocationMode.Online : X509RevocationMode.NoCheck, chain.ChainPolicy.RevocationMode);
+
+ // UWP always uses CheckCertificateRevocationList=true regardless of setting the property and
+ // the getter always returns true. So, for this next Assert, it is better to get the property
+ // value back from the handler instead of using the parameter value of the test.
+ Assert.Equal(
+ handler.CheckCertificateRevocationList ? X509RevocationMode.Online : X509RevocationMode.NoCheck,
+ chain.ChainPolicy.RevocationMode);
return true;
};
@@ -134,9 +177,15 @@ namespace System.Net.Http.Functional.Tests
}
[OuterLoop] // TODO: Issue #11345
- [ConditionalFact(nameof(BackendSupportsCustomCertificateHandling))]
+ [Fact]
public async Task UseCallback_CallbackReturnsFailure_ThrowsException()
{
+ if (BackendDoesNotSupportCustomCertificateHandling) // can't use [Conditional*] right now as it's evaluated at the wrong time for the managed handler
+ {
+ Console.WriteLine($"Skipping {nameof(UseCallback_CallbackReturnsFailure_ThrowsException)}()");
+ return;
+ }
+
var handler = new HttpClientHandler();
using (var client = new HttpClient(handler))
{
@@ -145,16 +194,25 @@ namespace System.Net.Http.Functional.Tests
}
}
+ [ActiveIssue(21904, ~TargetFrameworkMonikers.Uap)]
[OuterLoop] // TODO: Issue #11345
[ConditionalFact(nameof(BackendSupportsCustomCertificateHandling))]
- public async Task UseCallback_CallbackThrowsException_ExceptionPropagates()
+ public async Task UseCallback_CallbackThrowsException_ExceptionPropagatesAsInnerException()
{
+ if (BackendDoesNotSupportCustomCertificateHandling) // can't use [Conditional*] right now as it's evaluated at the wrong time for the managed handler
+ {
+ Console.WriteLine($"Skipping {nameof(UseCallback_CallbackThrowsException_ExceptionPropagatesAsInnerException)}()");
+ return;
+ }
+
var handler = new HttpClientHandler();
using (var client = new HttpClient(handler))
{
var e = new DivideByZeroException();
handler.ServerCertificateCustomValidationCallback = delegate { throw e; };
- Assert.Same(e, await Assert.ThrowsAsync<DivideByZeroException>(() => client.GetAsync(Configuration.Http.SecureRemoteEchoServer)));
+
+ HttpRequestException ex = await Assert.ThrowsAsync<HttpRequestException>(() => client.GetAsync(Configuration.Http.SecureRemoteEchoServer));
+ Assert.Same(e, ex.InnerException);
}
}
@@ -165,9 +223,8 @@ namespace System.Net.Http.Functional.Tests
new object[] { Configuration.Http.WrongHostNameCertRemoteServer },
};
- [ActiveIssue(7812, TestPlatforms.Windows)]
[OuterLoop] // TODO: Issue #11345
- [Theory]
+ [ConditionalTheory(nameof(ClientSupportsDHECipherSuites))]
[MemberData(nameof(CertificateValidationServers))]
public async Task NoCallback_BadCertificate_ThrowsException(string url)
{
@@ -177,8 +234,9 @@ namespace System.Net.Http.Functional.Tests
}
}
+ [SkipOnTargetFramework(TargetFrameworkMonikers.Uap, "UAP doesn't allow revocation checking to be turned off")]
[OuterLoop] // TODO: Issue #11345
- [Fact]
+ [ConditionalFact(nameof(ClientSupportsDHECipherSuites))]
public async Task NoCallback_RevokedCertificate_NoRevocationChecking_Succeeds()
{
// On macOS (libcurl+darwinssl) we cannot turn revocation off.
@@ -200,9 +258,15 @@ namespace System.Net.Http.Functional.Tests
}
[OuterLoop] // TODO: Issue #11345
- [ConditionalFact(nameof(BackendSupportsCustomCertificateHandling))]
+ [Fact]
public async Task NoCallback_RevokedCertificate_RevocationChecking_Fails()
{
+ if (BackendDoesNotSupportCustomCertificateHandling) // can't use [Conditional*] right now as it's evaluated at the wrong time for the managed handler
+ {
+ Console.WriteLine($"Skipping {nameof(NoCallback_RevokedCertificate_RevocationChecking_Fails)}()");
+ return;
+ }
+
var handler = new HttpClientHandler() { CheckCertificateRevocationList = true };
using (var client = new HttpClient(handler))
{
@@ -217,12 +281,14 @@ namespace System.Net.Http.Functional.Tests
new object[] { Configuration.Http.WrongHostNameCertRemoteServer , SslPolicyErrors.RemoteCertificateNameMismatch},
};
- [ActiveIssue(7812, TestPlatforms.Windows)]
- [OuterLoop] // TODO: Issue #11345
- [ConditionalTheory(nameof(BackendSupportsCustomCertificateHandling))]
- [MemberData(nameof(CertificateValidationServersAndExpectedPolicies))]
- public async Task UseCallback_BadCertificate_ExpectedPolicyErrors(string url, SslPolicyErrors expectedErrors)
+ public async Task UseCallback_BadCertificate_ExpectedPolicyErrors_Helper(string url, SslPolicyErrors expectedErrors)
{
+ if (BackendDoesNotSupportCustomCertificateHandling) // can't use [Conditional*] right now as it's evaluated at the wrong time for the managed handler
+ {
+ Console.WriteLine($"Skipping {nameof(UseCallback_BadCertificate_ExpectedPolicyErrors)}({url}, {expectedErrors})");
+ return;
+ }
+
var handler = new HttpClientHandler();
using (var client = new HttpClient(handler))
{
@@ -254,9 +320,39 @@ namespace System.Net.Http.Functional.Tests
}
[OuterLoop] // TODO: Issue #11345
- [ConditionalFact(nameof(BackendDoesNotSupportCustomCertificateHandling))]
+ [ConditionalTheory(nameof(BackendSupportsCustomCertificateHandlingAndClientSupportsDHECipherSuites))]
+ [MemberData(nameof(CertificateValidationServersAndExpectedPolicies))]
+ public async Task UseCallback_BadCertificate_ExpectedPolicyErrors(string url, SslPolicyErrors expectedErrors)
+ {
+ if (PlatformDetection.IsUap)
+ {
+ // UAP HTTP stack caches connections per-process. This causes interference when these tests run in
+ // the same process as the other tests. Each test needs to be isolated to its own process.
+ // See dicussion: https://github.com/dotnet/corefx/issues/21945
+ RemoteInvoke((remoteUrl, remoteExpectedErrors) =>
+ {
+ UseCallback_BadCertificate_ExpectedPolicyErrors_Helper(
+ remoteUrl,
+ (SslPolicyErrors)Enum.Parse(typeof(SslPolicyErrors), remoteExpectedErrors)).Wait();
+
+ return SuccessExitCode;
+ }, url, expectedErrors.ToString()).Dispose();
+ }
+ else
+ {
+ await UseCallback_BadCertificate_ExpectedPolicyErrors_Helper(url, expectedErrors);
+ }
+ }
+
+ [OuterLoop] // TODO: Issue #11345
+ [Fact]
public async Task SSLBackendNotSupported_Callback_ThrowsPlatformNotSupportedException()
{
+ if (BackendSupportsCustomCertificateHandling) // can't use [Conditional*] right now as it's evaluated at the wrong time for the managed handler
+ {
+ return;
+ }
+
using (var client = new HttpClient(new HttpClientHandler() { ServerCertificateCustomValidationCallback = delegate { return true; } }))
{
await Assert.ThrowsAsync<PlatformNotSupportedException>(() => client.GetAsync(Configuration.Http.SecureRemoteEchoServer));
@@ -264,11 +360,16 @@ namespace System.Net.Http.Functional.Tests
}
[OuterLoop] // TODO: Issue #11345
- [ConditionalFact(nameof(BackendDoesNotSupportCustomCertificateHandling))]
+ [Fact]
// For macOS the "custom handling" means that revocation can't be *disabled*. So this test does not apply.
[PlatformSpecific(~TestPlatforms.OSX)]
public async Task SSLBackendNotSupported_Revocation_ThrowsPlatformNotSupportedException()
{
+ if (BackendSupportsCustomCertificateHandling) // can't use [Conditional*] right now as it's evaluated at the wrong time for the managed handler
+ {
+ return;
+ }
+
using (var client = new HttpClient(new HttpClientHandler() { CheckCertificateRevocationList = true }))
{
await Assert.ThrowsAsync<PlatformNotSupportedException>(() => client.GetAsync(Configuration.Http.SecureRemoteEchoServer));
@@ -289,38 +390,46 @@ namespace System.Net.Http.Functional.Tests
// Validate the ChannelBinding object exists.
ChannelBinding channelBinding = content.ChannelBinding;
- Assert.NotNull(channelBinding);
-
- // Validate the ChannelBinding's validity.
- if (BackendSupportsCustomCertificateHandling)
+ if (PlatformDetection.IsUap)
{
- Assert.False(channelBinding.IsInvalid, "Expected valid binding");
- Assert.NotEqual(IntPtr.Zero, channelBinding.DangerousGetHandle());
-
- // Validate the ChannelBinding's description.
- string channelBindingDescription = channelBinding.ToString();
- Assert.NotNull(channelBindingDescription);
- Assert.NotEmpty(channelBindingDescription);
- Assert.True((channelBindingDescription.Length + 1) % 3 == 0, $"Unexpected length {channelBindingDescription.Length}");
- for (int i = 0; i < channelBindingDescription.Length; i++)
- {
- char c = channelBindingDescription[i];
- if (i % 3 == 2)
- {
- Assert.Equal(' ', c);
- }
- else
- {
- Assert.True((c >= '0' && c <= '9') || (c >= 'A' && c <= 'F'), $"Expected hex, got {c}");
- }
- }
+ // UAP currently doesn't expose channel binding information.
+ Assert.Null(channelBinding);
}
else
{
- // Backend doesn't support getting the details to create the CBT.
- Assert.True(channelBinding.IsInvalid, "Expected invalid binding");
- Assert.Equal(IntPtr.Zero, channelBinding.DangerousGetHandle());
- Assert.Null(channelBinding.ToString());
+ Assert.NotNull(channelBinding);
+
+ // Validate the ChannelBinding's validity.
+ if (BackendSupportsCustomCertificateHandling)
+ {
+ Assert.False(channelBinding.IsInvalid, "Expected valid binding");
+ Assert.NotEqual(IntPtr.Zero, channelBinding.DangerousGetHandle());
+
+ // Validate the ChannelBinding's description.
+ string channelBindingDescription = channelBinding.ToString();
+ Assert.NotNull(channelBindingDescription);
+ Assert.NotEmpty(channelBindingDescription);
+ Assert.True((channelBindingDescription.Length + 1) % 3 == 0, $"Unexpected length {channelBindingDescription.Length}");
+ for (int i = 0; i < channelBindingDescription.Length; i++)
+ {
+ char c = channelBindingDescription[i];
+ if (i % 3 == 2)
+ {
+ Assert.Equal(' ', c);
+ }
+ else
+ {
+ Assert.True((c >= '0' && c <= '9') || (c >= 'A' && c <= 'F'), $"Expected hex, got {c}");
+ }
+ }
+ }
+ else
+ {
+ // Backend doesn't support getting the details to create the CBT.
+ Assert.True(channelBinding.IsInvalid, "Expected invalid binding");
+ Assert.Equal(IntPtr.Zero, channelBinding.DangerousGetHandle());
+ Assert.Null(channelBinding.ToString());
+ }
}
}
}
diff --git a/src/System.Net.Http/tests/FunctionalTests/HttpClientHandlerTest.SslProtocols.Unix.cs b/src/System.Net.Http/tests/FunctionalTests/HttpClientHandlerTest.SslProtocols.Unix.cs
index ea636b8d21..83b32ec77f 100644
--- a/src/System.Net.Http/tests/FunctionalTests/HttpClientHandlerTest.SslProtocols.Unix.cs
+++ b/src/System.Net.Http/tests/FunctionalTests/HttpClientHandlerTest.SslProtocols.Unix.cs
@@ -17,7 +17,8 @@ namespace System.Net.Http.Functional.Tests
public partial class HttpClientHandler_SslProtocols_Test
{
private static bool BackendSupportsSslConfiguration =>
- CurlSslVersionDescription()?.StartsWith("OpenSSL") ?? false;
+ ManagedHandlerTestHelpers.IsEnabled ||
+ (CurlSslVersionDescription()?.StartsWith("OpenSSL") ?? false);
private static bool SSLv3DisabledByDefault =>
BackendSupportsSslConfiguration ||
diff --git a/src/System.Net.Http/tests/FunctionalTests/HttpClientHandlerTest.SslProtocols.cs b/src/System.Net.Http/tests/FunctionalTests/HttpClientHandlerTest.SslProtocols.cs
index 50d6154080..aa8b5d6f36 100644
--- a/src/System.Net.Http/tests/FunctionalTests/HttpClientHandlerTest.SslProtocols.cs
+++ b/src/System.Net.Http/tests/FunctionalTests/HttpClientHandlerTest.SslProtocols.cs
@@ -91,6 +91,12 @@ namespace System.Net.Http.Functional.Tests
[InlineData(SslProtocols.Tls12, true)]
public async Task GetAsync_AllowedSSLVersion_Succeeds(SslProtocols acceptedProtocol, bool requestOnlyThisProtocol)
{
+ if (ManagedHandlerTestHelpers.IsEnabled)
+ {
+ // TODO #21452: The managed handler is failing.
+ return;
+ }
+
using (var handler = new HttpClientHandler() { ServerCertificateCustomValidationCallback = LoopbackServer.AllowAllCertificates })
using (var client = new HttpClient(handler))
{
@@ -124,6 +130,12 @@ namespace System.Net.Http.Functional.Tests
[MemberData(nameof(SupportedSSLVersionServers))]
public async Task GetAsync_SupportedSSLVersion_Succeeds(SslProtocols sslProtocols, string url)
{
+ if (ManagedHandlerTestHelpers.IsEnabled)
+ {
+ // TODO #21452: The managed handler is failing.
+ return;
+ }
+
using (HttpClientHandler handler = new HttpClientHandler())
{
if (PlatformDetection.IsCentos7)
@@ -154,6 +166,13 @@ namespace System.Net.Http.Functional.Tests
[MemberData(nameof(NotSupportedSSLVersionServers))]
public async Task GetAsync_UnsupportedSSLVersion_Throws(string name, string url)
{
+ if (ManagedHandlerTestHelpers.IsEnabled && !PlatformDetection.IsWindows10Version1607OrGreater)
+ {
+ // On Windows, https://github.com/dotnet/corefx/issues/21925#issuecomment-313408314
+ // On Linux, an older version of OpenSSL may permit negotiating SSLv3.
+ return;
+ }
+
using (var client = new HttpClient())
{
await Assert.ThrowsAsync<HttpRequestException>(() => client.GetAsync(url));
diff --git a/src/System.Net.Http/tests/FunctionalTests/HttpClientHandlerTest.cs b/src/System.Net.Http/tests/FunctionalTests/HttpClientHandlerTest.cs
index 54269af096..f6036491af 100644
--- a/src/System.Net.Http/tests/FunctionalTests/HttpClientHandlerTest.cs
+++ b/src/System.Net.Http/tests/FunctionalTests/HttpClientHandlerTest.cs
@@ -26,7 +26,7 @@ namespace System.Net.Http.Functional.Tests
// Note: Disposing the HttpClient object automatically disposes the handler within. So, it is not necessary
// to separately Dispose (or have a 'using' statement) for the handler.
- public class HttpClientHandlerTest
+ public class HttpClientHandlerTest : RemoteExecutorTestBase
{
readonly ITestOutputHelper _output;
private const string ExpectedContent = "Test contest";
@@ -42,12 +42,14 @@ namespace System.Net.Http.Functional.Tests
public static readonly object[][] CompressedServers = Configuration.Http.CompressedServers;
public static readonly object[][] HeaderValueAndUris = {
new object[] { "X-CustomHeader", "x-value", Configuration.Http.RemoteEchoServer },
- new object[] { "X-Cust-Header-NoValue", "" , Configuration.Http.RemoteEchoServer },
new object[] { "X-CustomHeader", "x-value", Configuration.Http.RedirectUriForDestinationUri(
secure:false,
statusCode:302,
destinationUri:Configuration.Http.RemoteEchoServer,
hops:1) },
+ };
+ public static readonly object[][] HeaderWithEmptyValueAndUris = {
+ new object[] { "X-Cust-Header-NoValue", "" , Configuration.Http.RemoteEchoServer },
new object[] { "X-Cust-Header-NoValue", "" , Configuration.Http.RedirectUriForDestinationUri(
secure:false,
statusCode:302,
@@ -151,6 +153,7 @@ namespace System.Net.Http.Functional.Tests
{
Assert.True(handler.CheckCertificateRevocationList);
Assert.Equal(10, handler.MaxAutomaticRedirections);
+ Assert.Equal(0, handler.MaxRequestContentBufferSize);
Assert.Equal(-1, handler.MaxResponseHeadersLength);
Assert.True(handler.PreAuthenticate);
Assert.Equal(SslProtocols.None, handler.SslProtocols);
@@ -177,29 +180,18 @@ namespace System.Net.Http.Functional.Tests
}
}
- [ActiveIssue(20010, TargetFrameworkMonikers.Uap)]
- [SkipOnTargetFramework(TargetFrameworkMonikers.NetFramework, "MaxRequestContentBufferSize not used on .NET Core due to architecture differences")]
- [Fact]
- public void MaxRequestContentBufferSize_Get_ReturnsZero()
- {
- using (var handler = new HttpClientHandler())
- {
- Assert.Equal(0, handler.MaxRequestContentBufferSize);
- }
- }
-
- [ActiveIssue(20010, TargetFrameworkMonikers.Uap)]
- [SkipOnTargetFramework(TargetFrameworkMonikers.NetFramework, "MaxRequestContentBufferSize not used on .NET Core due to architecture differences")]
- [Fact]
- public void MaxRequestContentBufferSize_Set_ThrowsPlatformNotSupportedException()
+ [Theory]
+ [InlineData(-1)]
+ [InlineData((long)int.MaxValue + (long)1)]
+ public void MaxRequestContentBufferSize_SetInvalidValue_ThrowsArgumentOutOfRangeException(long value)
{
using (var handler = new HttpClientHandler())
{
- Assert.Throws<PlatformNotSupportedException>(() => handler.MaxRequestContentBufferSize = 1024);
+ Assert.Throws<ArgumentOutOfRangeException>(() => handler.MaxRequestContentBufferSize = value);
}
}
- [ActiveIssue(20010, TargetFrameworkMonikers.Uap)]
+ [SkipOnTargetFramework(TargetFrameworkMonikers.Uap, "UAP will send default credentials based on other criteria.")]
[Theory]
[InlineData(false)]
[InlineData(true)]
@@ -246,7 +238,6 @@ namespace System.Net.Http.Functional.Tests
}
}
- [ActiveIssue(20010, TargetFrameworkMonikers.Uap)]
[OuterLoop] // TODO: Issue #11345
[Theory, MemberData(nameof(EchoServers))]
public async Task SendAsync_SimpleGet_Success(Uri remoteServer)
@@ -264,7 +255,24 @@ namespace System.Net.Http.Functional.Tests
}
}
- [ActiveIssue(20010, TargetFrameworkMonikers.Uap)]
+ [ActiveIssue(22158, TargetFrameworkMonikers.Uap)]
+ [OuterLoop] // TODO: Issue #11345
+ [Fact]
+ public async Task GetAsync_IPv6LinkLocalAddressUri_Success()
+ {
+ using (var client = new HttpClient())
+ {
+ var options = new LoopbackServer.Options { Address = LoopbackServer.GetIPv6LinkLocalAddress() };
+ await LoopbackServer.CreateServerAsync(async (server, url) =>
+ {
+ _output.WriteLine(url.ToString());
+ await TestHelper.WhenAllCompletedOrAnyFailed(
+ LoopbackServer.ReadRequestAndSendResponseAsync(server, options: options),
+ client.GetAsync(url));
+ }, options);
+ }
+ }
+
[OuterLoop] // TODO: Issue #11345
[Theory]
[MemberData(nameof(GetAsync_IPBasedUri_Success_MemberData))]
@@ -275,6 +283,7 @@ namespace System.Net.Http.Functional.Tests
var options = new LoopbackServer.Options { Address = address };
await LoopbackServer.CreateServerAsync(async (server, url) =>
{
+ _output.WriteLine(url.ToString());
await TestHelper.WhenAllCompletedOrAnyFailed(
LoopbackServer.ReadRequestAndSendResponseAsync(server, options: options),
client.GetAsync(url));
@@ -284,7 +293,7 @@ namespace System.Net.Http.Functional.Tests
public static IEnumerable<object[]> GetAsync_IPBasedUri_Success_MemberData()
{
- foreach (var addr in new[] { IPAddress.Loopback, IPAddress.IPv6Loopback, LoopbackServer.GetIPv6LinkLocalAddress() })
+ foreach (var addr in new[] { IPAddress.Loopback, IPAddress.IPv6Loopback })
{
if (addr != null)
{
@@ -293,7 +302,6 @@ namespace System.Net.Http.Functional.Tests
}
}
- [ActiveIssue(20010, TargetFrameworkMonikers.Uap)]
[OuterLoop] // TODO: Issue #11345
[Fact]
public async Task SendAsync_MultipleRequestsReusingSameClient_Success()
@@ -310,7 +318,6 @@ namespace System.Net.Http.Functional.Tests
}
}
- [ActiveIssue(20010, TargetFrameworkMonikers.Uap)]
[OuterLoop] // TODO: Issue #11345
[Fact]
public async Task GetAsync_ResponseContentAfterClientAndHandlerDispose_Success()
@@ -326,7 +333,6 @@ namespace System.Net.Http.Functional.Tests
}
}
- [ActiveIssue(20010, TargetFrameworkMonikers.Uap)]
[OuterLoop] // TODO: Issue #11345
[Fact]
public async Task SendAsync_Cancel_CancellationTokenPropagates()
@@ -336,7 +342,7 @@ namespace System.Net.Http.Functional.Tests
using (var client = new HttpClient())
{
var request = new HttpRequestMessage(HttpMethod.Post, Configuration.Http.RemoteEchoServer);
- TaskCanceledException ex = await Assert.ThrowsAsync<TaskCanceledException>(() =>
+ OperationCanceledException ex = await Assert.ThrowsAnyAsync<OperationCanceledException>(() =>
client.SendAsync(request, cts.Token));
Assert.True(cts.Token.IsCancellationRequested, "cts token IsCancellationRequested");
if (!PlatformDetection.IsFullFramework)
@@ -347,7 +353,6 @@ namespace System.Net.Http.Functional.Tests
}
}
- [ActiveIssue(20010, TargetFrameworkMonikers.Uap)]
[OuterLoop] // TODO: Issue #11345
[Theory, MemberData(nameof(CompressedServers))]
public async Task GetAsync_SetAutomaticDecompression_ContentDecompressed(Uri server)
@@ -370,7 +375,6 @@ namespace System.Net.Http.Functional.Tests
}
}
- [ActiveIssue(20010, TargetFrameworkMonikers.Uap)]
[OuterLoop] // TODO: Issue #11345
[Theory, MemberData(nameof(CompressedServers))]
public async Task GetAsync_SetAutomaticDecompression_HeadersRemoved(Uri server)
@@ -387,7 +391,6 @@ namespace System.Net.Http.Functional.Tests
}
}
- [ActiveIssue(20010, TargetFrameworkMonikers.Uap)]
[OuterLoop] // TODO: Issue #11345
[Fact]
public async Task GetAsync_ServerNeedsBasicAuthAndSetDefaultCredentials_StatusCodeUnauthorized()
@@ -404,7 +407,6 @@ namespace System.Net.Http.Functional.Tests
}
}
- [ActiveIssue(20010, TargetFrameworkMonikers.Uap)]
[OuterLoop] // TODO: Issue #11345
[Fact]
public async Task GetAsync_ServerNeedsAuthAndSetCredential_StatusCodeOK()
@@ -421,22 +423,28 @@ namespace System.Net.Http.Functional.Tests
}
}
- [ActiveIssue(20010, TargetFrameworkMonikers.Uap)]
[OuterLoop] // TODO: Issue #11345
[Fact]
- public async Task GetAsync_ServerNeedsAuthAndNoCredential_StatusCodeUnauthorized()
+ public void GetAsync_ServerNeedsAuthAndNoCredential_StatusCodeUnauthorized()
{
- using (var client = new HttpClient())
+ // UAP HTTP stack caches connections per-process. This causes interference when these tests run in
+ // the same process as the other tests. Each test needs to be isolated to its own process.
+ // See dicussion: https://github.com/dotnet/corefx/issues/21945
+ RemoteInvoke(async () =>
{
- Uri uri = Configuration.Http.BasicAuthUriForCreds(secure: false, userName: Username, password: Password);
- using (HttpResponseMessage response = await client.GetAsync(uri))
+ using (var client = new HttpClient())
{
- Assert.Equal(HttpStatusCode.Unauthorized, response.StatusCode);
+ Uri uri = Configuration.Http.BasicAuthUriForCreds(secure: false, userName: Username, password: Password);
+ using (HttpResponseMessage response = await client.GetAsync(uri))
+ {
+ Assert.Equal(HttpStatusCode.Unauthorized, response.StatusCode);
+ }
+
+ return SuccessExitCode;
}
- }
+ }).Dispose();
}
- [ActiveIssue(20010, TargetFrameworkMonikers.Uap)]
[OuterLoop] // TODO: Issue #11345
[Theory]
[InlineData("WWW-Authenticate: CustomAuth\r\n")]
@@ -464,7 +472,6 @@ namespace System.Net.Http.Functional.Tests
});
}
- [ActiveIssue(20010, TargetFrameworkMonikers.Uap)]
[OuterLoop] // TODO: Issue #11345
[Theory, MemberData(nameof(RedirectStatusCodes))]
public async Task GetAsync_AllowAutoRedirectFalse_RedirectFromHttpToHttp_StatusCodeRedirect(int statusCode)
@@ -487,7 +494,6 @@ namespace System.Net.Http.Functional.Tests
}
}
- [ActiveIssue(20010, TargetFrameworkMonikers.Uap)]
[OuterLoop] // TODO: Issue #11345
[Theory, MemberData(nameof(RedirectStatusCodes))]
public async Task GetAsync_AllowAutoRedirectTrue_RedirectFromHttpToHttp_StatusCodeOK(int statusCode)
@@ -510,7 +516,6 @@ namespace System.Net.Http.Functional.Tests
}
}
- [ActiveIssue(20010, TargetFrameworkMonikers.Uap)]
[OuterLoop] // TODO: Issue #11345
[Fact]
public async Task GetAsync_AllowAutoRedirectTrue_RedirectFromHttpToHttps_StatusCodeOK()
@@ -533,7 +538,6 @@ namespace System.Net.Http.Functional.Tests
}
}
- [ActiveIssue(20010, TargetFrameworkMonikers.Uap)]
[SkipOnTargetFramework(TargetFrameworkMonikers.NetFramework, ".NET Framework allows HTTPS to HTTP redirection")]
[OuterLoop] // TODO: Issue #11345
[Fact]
@@ -549,15 +553,27 @@ namespace System.Net.Http.Functional.Tests
destinationUri: Configuration.Http.RemoteEchoServer,
hops: 1);
_output.WriteLine("Uri: {0}", uri);
- using (HttpResponseMessage response = await client.GetAsync(uri))
+
+ if (PlatformDetection.IsUap)
{
- Assert.Equal(HttpStatusCode.Redirect, response.StatusCode);
- Assert.Equal(uri, response.RequestMessage.RequestUri);
+ // UAP platform does not allow redirecting from HTTPS to HTTP (same as .NET Core).
+ // But in addition, it will throw an exception
+ //
+ // HttpRequestException: "An error occurred while sending the request."
+ // COMException: "A redirect request will change a secure to a non-secure connection"
+ await Assert.ThrowsAsync<HttpRequestException>(() => client.GetAsync(uri));
+ }
+ else
+ {
+ using (HttpResponseMessage response = await client.GetAsync(uri))
+ {
+ Assert.Equal(HttpStatusCode.Redirect, response.StatusCode);
+ Assert.Equal(uri, response.RequestMessage.RequestUri);
+ }
}
}
}
- [ActiveIssue(20010, TargetFrameworkMonikers.Uap)]
[OuterLoop] // TODO: Issue #11345
[Fact]
public async Task GetAsync_AllowAutoRedirectTrue_RedirectToUriWithParams_RequestMsgUriSet()
@@ -626,7 +642,6 @@ namespace System.Net.Http.Functional.Tests
}
}
- [ActiveIssue(20010, TargetFrameworkMonikers.Uap)]
[OuterLoop] // TODO: Issue #11345
[Fact]
public async Task GetAsync_AllowAutoRedirectTrue_RedirectWithRelativeLocation()
@@ -649,7 +664,6 @@ namespace System.Net.Http.Functional.Tests
}
}
- [ActiveIssue(20010, TargetFrameworkMonikers.Uap)]
[OuterLoop] // TODO: Issue #11345
[Theory]
[InlineData(200)]
@@ -685,7 +699,6 @@ namespace System.Net.Http.Functional.Tests
}
}
- [ActiveIssue(20010, TargetFrameworkMonikers.Uap)]
[OuterLoop] // TODO: Issue #11345
[ConditionalTheory(nameof(IsNotWindows7))] // Skip test on Win7 since WinHTTP has bugs w/ fragments.
[InlineData("#origFragment", "", "#origFragment", false)]
@@ -731,11 +744,16 @@ namespace System.Net.Http.Functional.Tests
}
}
- [ActiveIssue(20010, TargetFrameworkMonikers.Uap)]
[OuterLoop] // TODO: Issue #11345
[Fact]
public async Task GetAsync_CredentialIsNetworkCredentialUriRedirect_StatusCodeUnauthorized()
{
+ if (ManagedHandlerTestHelpers.IsEnabled)
+ {
+ // TODO #21452: The managed handler is currently getting Ok when it should be getting Unauthorized.
+ return;
+ }
+
var handler = new HttpClientHandler();
handler.Credentials = _credential;
using (var client = new HttpClient(handler))
@@ -752,7 +770,6 @@ namespace System.Net.Http.Functional.Tests
}
}
- [ActiveIssue(20010, TargetFrameworkMonikers.Uap)]
[OuterLoop] // TODO: Issue #11345
[Theory, MemberData(nameof(RedirectStatusCodes))]
public async Task GetAsync_CredentialIsCredentialCacheUriRedirect_StatusCodeOK(int statusCode)
@@ -769,18 +786,25 @@ namespace System.Net.Http.Functional.Tests
credentialCache.Add(uri, "Basic", _credential);
var handler = new HttpClientHandler();
- handler.Credentials = credentialCache;
- using (var client = new HttpClient(handler))
+ if (PlatformDetection.IsUap)
+ {
+ // UAP does not support CredentialCache for Credentials.
+ Assert.Throws<PlatformNotSupportedException>(() => handler.Credentials = credentialCache);
+ }
+ else
{
- using (HttpResponseMessage response = await client.GetAsync(redirectUri))
+ handler.Credentials = credentialCache;
+ using (var client = new HttpClient(handler))
{
- Assert.Equal(HttpStatusCode.OK, response.StatusCode);
- Assert.Equal(uri, response.RequestMessage.RequestUri);
+ using (HttpResponseMessage response = await client.GetAsync(redirectUri))
+ {
+ Assert.Equal(HttpStatusCode.OK, response.StatusCode);
+ Assert.Equal(uri, response.RequestMessage.RequestUri);
+ }
}
}
}
- [ActiveIssue(20010, TargetFrameworkMonikers.Uap)]
[OuterLoop] // TODO: Issue #11345
[Fact]
public async Task GetAsync_DefaultCoookieContainer_NoCookieSent()
@@ -796,7 +820,6 @@ namespace System.Net.Http.Functional.Tests
}
}
- [ActiveIssue(20010, TargetFrameworkMonikers.Uap)]
[OuterLoop] // TODO: Issue #11345
[Theory]
[InlineData("cookieName1", "cookieValue1")]
@@ -818,7 +841,7 @@ namespace System.Net.Http.Functional.Tests
}
}
- [ActiveIssue(20010, TargetFrameworkMonikers.Uap)]
+ [ActiveIssue(9003, TargetFrameworkMonikers.Uap)]
[OuterLoop] // TODO: Issue #11345
[Theory]
[InlineData("cookieName1", "cookieValue1")]
@@ -843,18 +866,38 @@ namespace System.Net.Http.Functional.Tests
}
}
- [ActiveIssue(20010, TargetFrameworkMonikers.Uap)]
+ [ActiveIssue(22187, TargetFrameworkMonikers.Uap)]
+ [OuterLoop] // TODO: Issue #11345
+ [Theory, MemberData(nameof(HeaderWithEmptyValueAndUris))]
+ public async Task GetAsync_RequestHeadersAddCustomHeaders_HeaderAndEmptyValueSent(string name, string value, Uri uri)
+ {
+ using (var client = new HttpClient())
+ {
+ _output.WriteLine($"name={name}, value={value}");
+ client.DefaultRequestHeaders.Add(name, value);
+ using (HttpResponseMessage httpResponse = await client.GetAsync(uri))
+ {
+ Assert.Equal(HttpStatusCode.OK, httpResponse.StatusCode);
+ string responseText = await httpResponse.Content.ReadAsStringAsync();
+ _output.WriteLine(responseText);
+ Assert.True(TestHelper.JsonMessageContainsKeyValue(responseText, name, value));
+ }
+ }
+ }
+
[OuterLoop] // TODO: Issue #11345
[Theory, MemberData(nameof(HeaderValueAndUris))]
public async Task GetAsync_RequestHeadersAddCustomHeaders_HeaderAndValueSent(string name, string value, Uri uri)
{
using (var client = new HttpClient())
{
+ _output.WriteLine($"name={name}, value={value}");
client.DefaultRequestHeaders.Add(name, value);
using (HttpResponseMessage httpResponse = await client.GetAsync(uri))
{
Assert.Equal(HttpStatusCode.OK, httpResponse.StatusCode);
string responseText = await httpResponse.Content.ReadAsStringAsync();
+ _output.WriteLine(responseText);
Assert.True(TestHelper.JsonMessageContainsKeyValue(responseText, name, value));
}
}
@@ -906,7 +949,6 @@ namespace System.Net.Http.Functional.Tests
}
};
- [ActiveIssue(20010, TargetFrameworkMonikers.Uap)]
[OuterLoop] // TODO: Issue #11345
[Theory]
[MemberData(nameof(CookieNameValues))]
@@ -944,7 +986,6 @@ namespace System.Net.Http.Functional.Tests
});
}
- [ActiveIssue(20010, TargetFrameworkMonikers.Uap)]
[OuterLoop] // TODO: Issue #11345
[ActiveIssue(17174, TestPlatforms.AnyUnix)] // https://github.com/curl/curl/issues/1354
[Theory]
@@ -952,6 +993,12 @@ namespace System.Net.Http.Functional.Tests
[InlineData(true)]
public async Task GetAsync_TrailingHeaders_Ignored(bool includeTrailerHeader)
{
+ if (ManagedHandlerTestHelpers.IsEnabled)
+ {
+ // TODO #21452: The managed handler isn't correctly handling trailing headers.
+ return;
+ }
+
await LoopbackServer.CreateServerAsync(async (server, url) =>
{
using (var handler = new HttpClientHandler())
@@ -983,7 +1030,6 @@ namespace System.Net.Http.Functional.Tests
});
}
- [ActiveIssue(20010, TargetFrameworkMonikers.Uap)]
[OuterLoop] // TODO: Issue #11345
[Fact]
public async Task GetAsync_ResponseHeadersRead_ReadFromEachIterativelyDoesntDeadlock()
@@ -1009,7 +1055,6 @@ namespace System.Net.Http.Functional.Tests
}
}
- [ActiveIssue(20010, TargetFrameworkMonikers.Uap)]
[OuterLoop] // TODO: Issue #11345
[Fact]
public async Task SendAsync_HttpRequestMsgResponseHeadersRead_StatusCodeOK()
@@ -1030,7 +1075,6 @@ namespace System.Net.Http.Functional.Tests
}
}
- [ActiveIssue(20010, TargetFrameworkMonikers.Uap)]
[SkipOnTargetFramework(TargetFrameworkMonikers.NetFramework, "netfx's ConnectStream.ReadAsync tries to read beyond data already buffered, causing hangs #18864")]
[OuterLoop] // TODO: Issue #11345
[Fact]
@@ -1069,11 +1113,18 @@ namespace System.Net.Http.Functional.Tests
});
}
- [ActiveIssue(20010, TargetFrameworkMonikers.Uap)]
[OuterLoop] // TODO: Issue #11345
[Fact]
public async Task Dispose_DisposingHandlerCancelsActiveOperationsWithoutResponses()
{
+ if (ManagedHandlerTestHelpers.IsEnabled)
+ {
+ // TODO #21452: The ManagedHandler isn't correctly handling disposal of the handler.
+ // It should cause the outstanding requests to be canceled with OperationCanceledExceptions,
+ // whereas currently it's resulting in ObjectDisposedExceptions.
+ return;
+ }
+
await LoopbackServer.CreateServerAsync(async (socket1, url1) =>
{
await LoopbackServer.CreateServerAsync(async (socket2, url2) =>
@@ -1118,7 +1169,7 @@ namespace System.Net.Http.Functional.Tests
get1 = client.GetAsync(url1, HttpCompletionOption.ResponseHeadersRead);
get2 = client.GetAsync(url2, HttpCompletionOption.ResponseHeadersRead);
response3 = await client.GetAsync(url3, HttpCompletionOption.ResponseHeadersRead);
- }
+ } // Dispose the handler while requests are still outstanding
// Requests 1 and 2 should be canceled as we haven't finished receiving their headers
await Assert.ThrowsAnyAsync<OperationCanceledException>(() => get1);
@@ -1135,7 +1186,6 @@ namespace System.Net.Http.Functional.Tests
});
}
- [ActiveIssue(20010, TargetFrameworkMonikers.Uap)]
[OuterLoop] // TODO: Issue #11345
[Theory]
[InlineData(200)]
@@ -1162,13 +1212,18 @@ namespace System.Net.Http.Functional.Tests
});
}
- [ActiveIssue(20010, TargetFrameworkMonikers.Uap)]
[OuterLoop] // TODO: Issue #11345
[Theory]
[InlineData(99)]
[InlineData(1000)]
public async Task GetAsync_StatusCodeOutOfRange_ExpectedException(int statusCode)
{
+ if (PlatformDetection.IsUap && statusCode == 99)
+ {
+ // UAP platform allows this status code due to historical reasons.
+ return;
+ }
+
await LoopbackServer.CreateServerAsync(async (server, url) =>
{
using (var client = new HttpClient())
@@ -1186,7 +1241,6 @@ namespace System.Net.Http.Functional.Tests
#region Post Methods Tests
- [ActiveIssue(20010, TargetFrameworkMonikers.Uap)]
[OuterLoop] // TODO: Issue #11345
[Theory, MemberData(nameof(VerifyUploadServers))]
public async Task PostAsync_CallMethodTwice_StringContent(Uri remoteServer)
@@ -1212,7 +1266,6 @@ namespace System.Net.Http.Functional.Tests
}
}
- [ActiveIssue(20010, TargetFrameworkMonikers.Uap)]
[OuterLoop] // TODO: Issue #11345
[Theory, MemberData(nameof(VerifyUploadServers))]
public async Task PostAsync_CallMethod_UnicodeStringContent(Uri remoteServer)
@@ -1230,7 +1283,6 @@ namespace System.Net.Http.Functional.Tests
}
}
- [ActiveIssue(20010, TargetFrameworkMonikers.Uap)]
[OuterLoop] // TODO: Issue #11345
[Theory, MemberData(nameof(VerifyUploadServersStreamsAndExpectedData))]
public async Task PostAsync_CallMethod_StreamContent(Uri remoteServer, HttpContent content, byte[] expectedData)
@@ -1372,7 +1424,6 @@ namespace System.Net.Http.Functional.Tests
}
}
- [ActiveIssue(20010, TargetFrameworkMonikers.Uap)]
[OuterLoop] // TODO: Issue #11345
[Theory, MemberData(nameof(EchoServers))]
public async Task PostAsync_CallMethod_NullContent(Uri remoteServer)
@@ -1394,7 +1445,6 @@ namespace System.Net.Http.Functional.Tests
}
}
- [ActiveIssue(20010, TargetFrameworkMonikers.Uap)]
[OuterLoop] // TODO: Issue #11345
[Theory, MemberData(nameof(EchoServers))]
public async Task PostAsync_CallMethod_EmptyContent(Uri remoteServer)
@@ -1417,7 +1467,6 @@ namespace System.Net.Http.Functional.Tests
}
}
- [ActiveIssue(20010, TargetFrameworkMonikers.Uap)]
[OuterLoop] // TODO: Issue #11345
[Theory]
[InlineData(false)]
@@ -1442,12 +1491,22 @@ namespace System.Net.Http.Functional.Tests
}
}
- [ActiveIssue(20010, TargetFrameworkMonikers.Uap)]
+ [ActiveIssue(22191, TargetFrameworkMonikers.Uap)]
[OuterLoop] // takes several seconds
- [Theory]
- [InlineData(302, false)]
- [InlineData(307, true)]
- public async Task PostAsync_Redirect_LargePayload(int statusCode, bool expectRedirectToPost)
+ [Fact]
+ public async Task PostAsync_RedirectWith307_LargePayload()
+ {
+ await PostAsync_Redirect_LargePayload_Helper(307, true);
+ }
+
+ [OuterLoop] // takes several seconds
+ [Fact]
+ public async Task PostAsync_RedirectWith302_LargePayload()
+ {
+ await PostAsync_Redirect_LargePayload_Helper(302, false);
+ }
+
+ public async Task PostAsync_Redirect_LargePayload_Helper(int statusCode, bool expectRedirectToPost)
{
using (var fs = new FileStream(Path.Combine(Path.GetTempPath(), Path.GetTempFileName()), FileMode.Create, FileAccess.ReadWrite, FileShare.None, 0x1000, FileOptions.DeleteOnClose))
{
@@ -1471,7 +1530,6 @@ namespace System.Net.Http.Functional.Tests
}
}
- [ActiveIssue(20010, TargetFrameworkMonikers.Uap)]
[OuterLoop] // TODO: Issue #11345
[Theory, MemberData(nameof(EchoServers))] // NOTE: will not work for in-box System.Net.Http.dll due to disposal of request content
public async Task PostAsync_ReuseRequestContent_Success(Uri remoteServer)
@@ -1510,32 +1568,11 @@ namespace System.Net.Http.Functional.Tests
}
}
- [ActiveIssue(20010, TargetFrameworkMonikers.Uap)]
- [OuterLoop] // TODO: Issue #11345
- [PlatformSpecific(TestPlatforms.Windows)] // CopyToAsync(Stream, TransportContext) isn't used on unix
- [Fact]
- public async Task PostAsync_Post_ChannelBindingHasExpectedValue()
- {
- using (var client = new HttpClient())
- {
- string expectedContent = "Test contest";
- var content = new ChannelBindingAwareContent(expectedContent);
- using (HttpResponseMessage response = await client.PostAsync(Configuration.Http.SecureRemoteEchoServer, content))
- {
- Assert.Equal(HttpStatusCode.OK, response.StatusCode);
-
- ChannelBinding channelBinding = content.ChannelBinding;
- Assert.NotNull(channelBinding);
- _output.WriteLine("Channel Binding: {0}", channelBinding);
- }
- }
- }
-
#endregion
#region Various HTTP Method Tests
- [ActiveIssue(20010, TargetFrameworkMonikers.Uap)]
+ [ActiveIssue(22161, TargetFrameworkMonikers.Uap)]
[OuterLoop] // TODO: Issue #11345
[Theory, MemberData(nameof(HttpMethods))]
public async Task SendAsync_SendRequestUsingMethodToEchoServerWithNoContent_MethodCorrectlySent(
@@ -1561,14 +1598,11 @@ namespace System.Net.Http.Functional.Tests
string method,
bool secureServer)
{
- if (PlatformDetection.IsFullFramework)
+ if (PlatformDetection.IsFullFramework && method == "GET")
{
// .NET Framework doesn't allow a content body with this HTTP verb.
// It will throw a System.Net.ProtocolViolation exception.
- if (method == "GET")
- {
- return;
- }
+ return;
}
using (var client = new HttpClient())
@@ -1594,7 +1628,7 @@ namespace System.Net.Http.Functional.Tests
}
}
- [ActiveIssue(20010, TargetFrameworkMonikers.Uap)]
+ [ActiveIssue(20010, TargetFrameworkMonikers.Uap)] // Test hangs. But this test seems invalid. An HttpRequestMessage can only be sent once.
[OuterLoop] // TODO: Issue #11345
[Theory]
[InlineData("12345678910", 0)]
@@ -1629,21 +1663,25 @@ namespace System.Net.Http.Functional.Tests
}
}
- [ActiveIssue(20010, TargetFrameworkMonikers.Uap)]
[OuterLoop] // TODO: Issue #11345
[Theory, MemberData(nameof(HttpMethodsThatDontAllowContent))]
public async Task SendAsync_SendRequestUsingNoBodyMethodToEchoServerWithContent_NoBodySent(
string method,
bool secureServer)
{
- if (PlatformDetection.IsFullFramework)
+ if (PlatformDetection.IsFullFramework && method == "HEAD")
{
// .NET Framework doesn't allow a content body with this HTTP verb.
// It will throw a System.Net.ProtocolViolation exception.
- if (method == "HEAD")
- {
- return;
- }
+ return;
+ }
+
+ if (PlatformDetection.IsUap && method == "TRACE")
+ {
+ // UAP platform doesn't allow a content body with this HTTP verb.
+ // It will throw an exception HttpRequestException/COMException
+ // with "The requested operation is invalid" message.
+ return;
}
using (var client = new HttpClient())
@@ -1657,7 +1695,7 @@ namespace System.Net.Http.Functional.Tests
using (HttpResponseMessage response = await client.SendAsync(request))
{
- if (RuntimeInformation.IsOSPlatform(OSPlatform.Windows) && method == "TRACE")
+ if (method == "TRACE" && (RuntimeInformation.IsOSPlatform(OSPlatform.Windows) || ManagedHandlerTestHelpers.IsEnabled))
{
// .NET Framework also allows the HttpWebRequest and HttpClient APIs to send a request using 'TRACE'
// verb and a request body. The usual response from a server is "400 Bad Request".
@@ -1677,11 +1715,17 @@ namespace System.Net.Http.Functional.Tests
#endregion
#region Version tests
- [ActiveIssue(20010, TargetFrameworkMonikers.Uap)]
+ [SkipOnTargetFramework(TargetFrameworkMonikers.Uap, "UAP does not allow HTTP/1.0 requests.")]
[OuterLoop] // TODO: Issue #11345
[Fact]
public async Task SendAsync_RequestVersion10_ServerReceivesVersion10Request()
{
+ if (ManagedHandlerTestHelpers.IsEnabled)
+ {
+ // TODO #21452: The test is hanging with the managed handler.
+ return;
+ }
+
Version receivedRequestVersion = await SendRequestAndGetRequestVersionAsync(new Version(1, 0));
Assert.Equal(new Version(1, 0), receivedRequestVersion);
}
@@ -1699,6 +1743,12 @@ namespace System.Net.Http.Functional.Tests
[Fact]
public async Task SendAsync_RequestVersionNotSpecified_ServerReceivesVersion11Request()
{
+ if (ManagedHandlerTestHelpers.IsEnabled)
+ {
+ // TODO #21452: The test is hanging with the managed handler.
+ return;
+ }
+
// The default value for HttpRequestMessage.Version is Version(1,1).
// So, we need to set something different (0,0), to test the "unknown" version.
Version receivedRequestVersion = await SendRequestAndGetRequestVersionAsync(new Version(0, 0));
@@ -1717,6 +1767,11 @@ namespace System.Net.Http.Functional.Tests
_output.WriteLine("Skipping test due to Windows 10 version prior to Version 1703.");
return;
}
+ if (ManagedHandlerTestHelpers.IsEnabled)
+ {
+ // TODO #21452: The managed handler doesn't yet support HTTP/2.
+ return;
+ }
// We don't currently have a good way to test whether HTTP/2 is supported without
// using the same mechanism we're trying to test, so for now we allow both 2.0 and 1.1 responses.
@@ -1759,12 +1814,17 @@ namespace System.Net.Http.Functional.Tests
}
}
- [ActiveIssue(20010, TargetFrameworkMonikers.Uap)]
[SkipOnTargetFramework(TargetFrameworkMonikers.NetFramework, "Specifying Version(2,0) throws exception on netfx")]
[OuterLoop] // TODO: Issue #11345
[ConditionalTheory(nameof(IsWindows10Version1607OrGreater)), MemberData(nameof(Http2NoPushServers))]
public async Task SendAsync_RequestVersion20_ResponseVersion20(Uri server)
{
+ if (ManagedHandlerTestHelpers.IsEnabled)
+ {
+ // TODO #21452: The managed handler doesn't yet support HTTP/2.
+ return;
+ }
+
_output.WriteLine(server.AbsoluteUri.ToString());
var request = new HttpRequestMessage(HttpMethod.Get, server);
request.Version = new Version(2, 0);
@@ -1822,12 +1882,18 @@ namespace System.Net.Http.Functional.Tests
#endregion
#region Proxy tests
- [ActiveIssue(20010, TargetFrameworkMonikers.Uap)]
+ [SkipOnTargetFramework(TargetFrameworkMonikers.Uap, "UAP does not support custom proxies.")]
[OuterLoop] // TODO: Issue #11345
[Theory]
[MemberData(nameof(CredentialsForProxy))]
public void Proxy_BypassFalse_GetRequestGoesThroughCustomProxy(ICredentials creds, bool wrapCredsInCache)
{
+ if (ManagedHandlerTestHelpers.IsEnabled)
+ {
+ // TODO #21452: The test is hanging with the managed handler for some of the theory inputs.
+ return;
+ }
+
int port;
Task<LoopbackGetRequestHttpProxy.ProxyResult> proxyTask = LoopbackGetRequestHttpProxy.StartAsync(
out port,
@@ -1866,7 +1932,7 @@ namespace System.Net.Http.Functional.Tests
}
}
- [ActiveIssue(20010, TargetFrameworkMonikers.Uap)]
+ [SkipOnTargetFramework(TargetFrameworkMonikers.Uap, "UAP does not support custom proxies.")]
[OuterLoop] // TODO: Issue #11345
[Theory]
[MemberData(nameof(BypassedProxies))]
@@ -1883,7 +1949,7 @@ namespace System.Net.Http.Functional.Tests
}
}
- [ActiveIssue(20010, TargetFrameworkMonikers.Uap)]
+ [SkipOnTargetFramework(TargetFrameworkMonikers.Uap, "UAP does not support custom proxies.")]
[OuterLoop] // TODO: Issue #11345
[Fact]
public void Proxy_HaveNoCredsAndUseAuthenticatedCustomProxy_ProxyAuthenticationRequiredStatusCode()
@@ -1925,7 +1991,6 @@ namespace System.Net.Http.Functional.Tests
#endregion
#region Uri wire transmission encoding tests
- [ActiveIssue(20010, TargetFrameworkMonikers.Uap)]
[OuterLoop] // TODO: Issue #11345
[Fact]
public async Task SendRequest_UriPathHasReservedChars_ServerReceivedExpectedPath()
diff --git a/src/System.Net.Http/tests/FunctionalTests/HttpClientMiniStressTest.cs b/src/System.Net.Http/tests/FunctionalTests/HttpClientMiniStressTest.cs
index 1843959c96..2d4d07b15b 100644
--- a/src/System.Net.Http/tests/FunctionalTests/HttpClientMiniStressTest.cs
+++ b/src/System.Net.Http/tests/FunctionalTests/HttpClientMiniStressTest.cs
@@ -96,7 +96,8 @@ namespace System.Net.Http.Functional.Tests
select client.GetStringAsync($"http://{ep.Address}:{ep.Port}"))
.ToArray();
- Assert.All(tasks, t => Assert.Equal(TaskStatus.WaitingForActivation, t.Status));
+ Assert.All(tasks, t =>
+ Assert.True(t.IsFaulted || t.Status == TaskStatus.WaitingForActivation, $"Unexpected status {t.Status}"));
server.Dispose();
diff --git a/src/System.Net.Http/tests/FunctionalTests/ManagedHandlerTest.cs b/src/System.Net.Http/tests/FunctionalTests/ManagedHandlerTest.cs
index 87cd39eb30..d658a3c270 100644
--- a/src/System.Net.Http/tests/FunctionalTests/ManagedHandlerTest.cs
+++ b/src/System.Net.Http/tests/FunctionalTests/ManagedHandlerTest.cs
@@ -2,6 +2,10 @@
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
+using System.IO;
+using System.Net.Sockets;
+using System.Text;
+using System.Threading.Tasks;
using Xunit;
using Xunit.Abstractions;
@@ -38,23 +42,28 @@ namespace System.Net.Http.Functional.Tests
}
}
- public sealed class ManagedHandler_HttpClientEKUTest : HttpClientEKUTest, IDisposable
- {
- public ManagedHandler_HttpClientEKUTest() => ManagedHandlerTestHelpers.SetEnvVar();
- public void Dispose() => ManagedHandlerTestHelpers.RemoveEnvVar();
- }
-
+ // TODO #21452: Tests on this class fail when the associated condition is enabled.
+ //public sealed class ManagedHandler_HttpClientEKUTest : HttpClientEKUTest, IDisposable
+ //{
+ // public ManagedHandler_HttpClientEKUTest() => ManagedHandlerTestHelpers.SetEnvVar();
+ // public void Dispose() => ManagedHandlerTestHelpers.RemoveEnvVar();
+ //}
+
public sealed class ManagedHandler_HttpClientHandler_DangerousAcceptAllCertificatesValidator_Test : HttpClientHandler_DangerousAcceptAllCertificatesValidator_Test, IDisposable
{
public ManagedHandler_HttpClientHandler_DangerousAcceptAllCertificatesValidator_Test() => ManagedHandlerTestHelpers.SetEnvVar();
public void Dispose() => ManagedHandlerTestHelpers.RemoveEnvVar();
}
- //public sealed class ManagedHandler_HttpClientHandler_ClientCertificates_Test : HttpClientHandler_ClientCertificates_Test, IDisposable
- //{
- // public ManagedHandler_HttpClientHandler_ClientCertificates_Test() => ManagedHandlerTestHelpers.SetEnvVar();
- // public void Dispose() => ManagedHandlerTestHelpers.RemoveEnvVar();
- //}
+ public sealed class ManagedHandler_HttpClientHandler_ClientCertificates_Test : HttpClientHandler_ClientCertificates_Test, IDisposable
+ {
+ public ManagedHandler_HttpClientHandler_ClientCertificates_Test(ITestOutputHelper output) : base(output) => ManagedHandlerTestHelpers.SetEnvVar();
+ public new void Dispose()
+ {
+ ManagedHandlerTestHelpers.RemoveEnvVar();
+ base.Dispose();
+ }
+ }
public sealed class ManagedHandler_HttpClientHandler_DefaultProxyCredentials_Test : HttpClientHandler_DefaultProxyCredentials_Test, IDisposable
{
@@ -72,11 +81,15 @@ namespace System.Net.Http.Functional.Tests
public void Dispose() => ManagedHandlerTestHelpers.RemoveEnvVar();
}
- //public sealed class ManagedHandler_HttpClientHandler_ServerCertificates_Test : HttpClientHandler_ServerCertificates_Test, IDisposable
- //{
- // public ManagedHandler_HttpClientHandler_ServerCertificates_Test() => ManagedHandlerTestHelpers.SetEnvVar();
- // public void Dispose() => ManagedHandlerTestHelpers.RemoveEnvVar();
- //}
+ public sealed class ManagedHandler_HttpClientHandler_ServerCertificates_Test : HttpClientHandler_ServerCertificates_Test, IDisposable
+ {
+ public ManagedHandler_HttpClientHandler_ServerCertificates_Test() => ManagedHandlerTestHelpers.SetEnvVar();
+ public new void Dispose()
+ {
+ ManagedHandlerTestHelpers.RemoveEnvVar();
+ base.Dispose();
+ }
+ }
public sealed class ManagedHandler_PostScenarioTest : PostScenarioTest, IDisposable
{
@@ -89,27 +102,54 @@ namespace System.Net.Http.Functional.Tests
public ManagedHandler_ResponseStreamTest(ITestOutputHelper output) : base(output) => ManagedHandlerTestHelpers.SetEnvVar();
public void Dispose() => ManagedHandlerTestHelpers.RemoveEnvVar();
}
+
+ public sealed class ManagedHandler_HttpClientHandler_SslProtocols_Test : HttpClientHandler_SslProtocols_Test, IDisposable
+ {
+ public ManagedHandler_HttpClientHandler_SslProtocols_Test() => ManagedHandlerTestHelpers.SetEnvVar();
+ public void Dispose() => ManagedHandlerTestHelpers.RemoveEnvVar();
+ }
- // TODO #21452: Uncomment once tests are fixed
+ public sealed class ManagedHandler_SchSendAuxRecordHttpTest : SchSendAuxRecordHttpTest, IDisposable
+ {
+ public ManagedHandler_SchSendAuxRecordHttpTest(ITestOutputHelper output) : base(output) => ManagedHandlerTestHelpers.SetEnvVar();
+ public void Dispose() => ManagedHandlerTestHelpers.RemoveEnvVar();
+ }
- //public sealed class ManagedHandler_HttpClientHandler_SslProtocols_Test : HttpClientHandler_SslProtocols_Test, IDisposable
- //{
- // public ManagedHandler_HttpClientHandler_SslProtocols_Test() => ManagedHandlerTestHelpers.SetEnvVar();
- // public void Dispose() => ManagedHandlerTestHelpers.RemoveEnvVar();
- //}
+ public sealed class ManagedHandler_HttpClientMiniStress : HttpClientMiniStress, IDisposable
+ {
+ public ManagedHandler_HttpClientMiniStress() => ManagedHandlerTestHelpers.SetEnvVar();
+ public void Dispose() => ManagedHandlerTestHelpers.RemoveEnvVar();
+ }
- //public sealed class ManagedHandler_SchSendAuxRecordHttpTest : SchSendAuxRecordHttpTest, IDisposable
+ // TODO #21452:
+ //public sealed class ManagedHandler_DefaultCredentialsTest : DefaultCredentialsTest, IDisposable
//{
- // public ManagedHandler_SchSendAuxRecordHttpTest(ITestOutputHelper output) : base(output) => ManagedHandlerTestHelpers.SetEnvVar();
+ // public ManagedHandler_DefaultCredentialsTest(ITestOutputHelper output) : base(output) => ManagedHandlerTestHelpers.SetEnvVar();
// public void Dispose() => ManagedHandlerTestHelpers.RemoveEnvVar();
//}
+ public sealed class ManagedHandler_HttpClientHandlerTest : HttpClientHandlerTest, IDisposable
+ {
+ public ManagedHandler_HttpClientHandlerTest(ITestOutputHelper output) : base(output) => ManagedHandlerTestHelpers.SetEnvVar();
+ public new void Dispose()
+ {
+ ManagedHandlerTestHelpers.RemoveEnvVar();
+ base.Dispose();
+ }
+ }
+
+ // TODO #21452: Socket's don't support canceling individual operations, so ReadStream on NetworkStream
+ // isn't cancelable once the operation has started. We either need to wrap the operation with one that's
+ // "cancelable", meaning that the underlying operation will still be running even though we've returned "canceled",
+ // or we need to just recognize that cancellation in such situations can be left up to the caller to do the
+ // same thing if it's really important.
//public sealed class ManagedHandler_CancellationTest : CancellationTest, IDisposable
//{
// public ManagedHandler_CancellationTest(ITestOutputHelper output) : base(output) => ManagedHandlerTestHelpers.SetEnvVar();
// public void Dispose() => ManagedHandlerTestHelpers.RemoveEnvVar();
//}
+ // TODO #21452: The managed handler doesn't currently track how much data was written for the response headers.
//public sealed class ManagedHandler_HttpClientHandler_MaxResponseHeadersLength_Test : HttpClientHandler_MaxResponseHeadersLength_Test, IDisposable
//{
// public ManagedHandler_HttpClientHandler_MaxResponseHeadersLength_Test() => ManagedHandlerTestHelpers.SetEnvVar();
@@ -119,4 +159,102 @@ namespace System.Net.Http.Functional.Tests
// base.Dispose();
// }
//}
+
+ public sealed class ManagedHandler_HttpClientHandler_ConnectionPooling_Test : IDisposable
+ {
+ public ManagedHandler_HttpClientHandler_ConnectionPooling_Test() => ManagedHandlerTestHelpers.SetEnvVar();
+ public void Dispose() => ManagedHandlerTestHelpers.RemoveEnvVar();
+
+ // TODO: Currently the subsequent tests sometimes fail/hang with WinHttpHandler / CurlHandler.
+ // In theory they should pass with any handler that does appropriate connection pooling.
+ // We should understand why they sometimes fail there and ideally move them to be
+ // used by all handlers this test project tests.
+
+ [Fact]
+ public async Task MultipleIterativeRequests_SameConnectionReused()
+ {
+ using (var client = new HttpClient())
+ using (var listener = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp))
+ {
+ listener.Bind(new IPEndPoint(IPAddress.Loopback, 0));
+ listener.Listen(1);
+ var ep = (IPEndPoint)listener.LocalEndPoint;
+ var uri = new Uri($"http://{ep.Address}:{ep.Port}/");
+
+ string responseBody =
+ "HTTP/1.1 200 OK\r\n" +
+ $"Date: {DateTimeOffset.UtcNow:R}\r\n" +
+ "Content-Length: 0\r\n" +
+ "\r\n";
+
+ Task<string> firstRequest = client.GetStringAsync(uri);
+ using (Socket server = await listener.AcceptAsync())
+ using (var serverStream = new NetworkStream(server, ownsSocket: false))
+ using (var serverReader = new StreamReader(serverStream))
+ using (var serverWriter = new StreamWriter(serverStream))
+ {
+ await serverReader.ReadLineAsync(); // GET line
+ await serverReader.ReadLineAsync(); // blank line
+ await serverWriter.WriteAsync(responseBody);
+ await serverWriter.FlushAsync();
+ await firstRequest;
+
+ Task<Socket> secondAccept = listener.AcceptAsync(); // shouldn't complete
+
+ Task<string> additionalRequest = client.GetStringAsync(uri);
+ await serverReader.ReadLineAsync(); // GET line
+ await serverReader.ReadLineAsync(); // blank line
+ await serverWriter.WriteAsync(responseBody);
+ await serverWriter.FlushAsync();
+ await additionalRequest;
+
+ Assert.False(secondAccept.IsCompleted, $"Second accept should never complete");
+ }
+ }
+ }
+
+ [OuterLoop("Incurs a delay")]
+ [Fact]
+ public async Task ServerDisconnectsAfterInitialRequest_SubsequentRequestUsesDifferentConnection()
+ {
+ using (var client = new HttpClient())
+ using (var listener = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp))
+ {
+ listener.Bind(new IPEndPoint(IPAddress.Loopback, 0));
+ listener.Listen(100);
+ var ep = (IPEndPoint)listener.LocalEndPoint;
+ var uri = new Uri($"http://{ep.Address}:{ep.Port}/");
+
+ string responseBody =
+ "HTTP/1.1 200 OK\r\n" +
+ $"Date: {DateTimeOffset.UtcNow:R}\r\n" +
+ "Content-Length: 0\r\n" +
+ "\r\n";
+
+ // Make multiple requests iteratively.
+ for (int i = 0; i < 2; i++)
+ {
+ Task<string> request = client.GetStringAsync(uri);
+ using (Socket server = await listener.AcceptAsync())
+ using (var serverStream = new NetworkStream(server, ownsSocket: false))
+ using (var serverReader = new StreamReader(serverStream))
+ using (var serverWriter = new StreamWriter(serverStream))
+ {
+ await serverReader.ReadLineAsync(); // GET line
+ await serverReader.ReadLineAsync(); // blank line
+
+ await server.SendAsync(new ArraySegment<byte>(Encoding.ASCII.GetBytes(responseBody)), SocketFlags.None);
+
+ await request;
+
+ server.Shutdown(SocketShutdown.Both);
+ if (i == 0)
+ {
+ await Task.Delay(2000); // give client time to see the closing before next connect
+ }
+ }
+ }
+ }
+ }
+ }
}
diff --git a/src/System.Net.Http/tests/FunctionalTests/MultiInterfaceNonRewindableReadOnlyStream.cs b/src/System.Net.Http/tests/FunctionalTests/MultiInterfaceNonRewindableReadOnlyStream.cs
new file mode 100644
index 0000000000..c44a25878f
--- /dev/null
+++ b/src/System.Net.Http/tests/FunctionalTests/MultiInterfaceNonRewindableReadOnlyStream.cs
@@ -0,0 +1,132 @@
+// Licensed to the .NET Foundation under one or more agreements.
+// The .NET Foundation licenses this file to you under the MIT license.
+// See the LICENSE file in the project root for more information.
+
+using System;
+using System.IO;
+using System.Runtime.InteropServices.WindowsRuntime;
+using System.Text;
+using System.Threading;
+using System.Threading.Tasks;
+using Windows.Foundation;
+using Windows.Storage.Streams;
+
+namespace System.Net.Http.Functional.Tests
+{
+ public class MultiInterfaceNonRewindableReadOnlyStream : Stream, IInputStream
+ {
+ byte[] _bytes;
+ int _position;
+
+ public MultiInterfaceNonRewindableReadOnlyStream(byte[] bytes)
+ {
+ _bytes = bytes;
+ _position = 0;
+ }
+
+ public MultiInterfaceNonRewindableReadOnlyStream(string content)
+ {
+ _bytes = Encoding.UTF8.GetBytes(content);
+ _position = 0;
+ }
+
+ public override bool CanRead
+ {
+ get { return true; }
+ }
+
+ public override bool CanSeek
+ {
+ get { return false; }
+ }
+
+ public override bool CanWrite
+ {
+ get { return false; }
+ }
+
+ public override void Flush()
+ {
+ }
+
+ public override long Length
+ {
+ get { return _bytes.Length; }
+ }
+
+ public override long Position
+ {
+ get
+ {
+ return _position;
+ }
+ set
+ {
+ throw new NotSupportedException();
+ }
+ }
+
+ public override int Read(byte[] buffer, int offset, int count)
+ {
+ byte[] dataBytes = ReadInternal(count);
+
+ for (int i = 0; i < dataBytes.Length; i++)
+ {
+ buffer[offset + i] = dataBytes[i];
+ }
+
+ return dataBytes.Length;
+ }
+
+ public override long Seek(long offset, SeekOrigin origin)
+ {
+ throw new NotSupportedException();
+ }
+
+ public override void SetLength(long value)
+ {
+ throw new NotSupportedException();
+ }
+
+ public override void Write(byte[] buffer, int offset, int count)
+ {
+ throw new NotSupportedException();
+ }
+
+ void IDisposable.Dispose()
+ {
+ }
+
+ byte[] ReadInternal(int count)
+ {
+ byte[] dataBytes;
+
+ if (_position == _bytes.Length)
+ {
+ dataBytes = new byte[0];
+ }
+ else
+ {
+ int numBytes = Math.Min(_bytes.Length - _position, count);
+ var stream = new MemoryStream(_bytes, _position, numBytes);
+ _position += numBytes;
+ dataBytes = stream.ToArray();
+ }
+
+ return dataBytes;
+ }
+
+ IAsyncOperationWithProgress<IBuffer, uint> IInputStream.ReadAsync(IBuffer buffer, uint count, InputStreamOptions options)
+ {
+ byte[] dataBytes = ReadInternal((int)count);
+
+ var ibuffer = dataBytes.AsBuffer();
+
+ return AsyncInfo.Run(
+ delegate (CancellationToken cancellationToken, IProgress<uint> progress)
+ {
+ return Task.FromResult<IBuffer>(ibuffer);
+ });
+ }
+ }
+}
diff --git a/src/System.Net.Http/tests/FunctionalTests/MultiInterfaceReadOnlyStream.cs b/src/System.Net.Http/tests/FunctionalTests/MultiInterfaceReadOnlyStream.cs
new file mode 100644
index 0000000000..f9d03bd5ac
--- /dev/null
+++ b/src/System.Net.Http/tests/FunctionalTests/MultiInterfaceReadOnlyStream.cs
@@ -0,0 +1,210 @@
+// Licensed to the .NET Foundation under one or more agreements.
+// The .NET Foundation licenses this file to you under the MIT license.
+// See the LICENSE file in the project root for more information.
+
+using System;
+using System.IO;
+using System.Runtime.InteropServices.WindowsRuntime;
+using System.Text;
+using System.Threading;
+using System.Threading.Tasks;
+using Windows.Foundation;
+using Windows.Storage.Streams;
+
+namespace System.Net.Http.Functional.Tests
+{
+ public class MultiInterfaceReadOnlyStream : Stream, IRandomAccessStream
+ {
+ byte[] _bytes;
+ long _position;
+
+ public MultiInterfaceReadOnlyStream(byte[] bytes)
+ {
+ _bytes = bytes;
+ _position = 0;
+ }
+
+ public MultiInterfaceReadOnlyStream(string content)
+ {
+ _bytes = Encoding.UTF8.GetBytes(content);
+ _position = 0;
+ }
+
+ public override bool CanRead
+ {
+ get { return true; }
+ }
+
+ public override bool CanSeek
+ {
+ get { return true; }
+ }
+
+ public override bool CanWrite
+ {
+ get { return false; }
+ }
+
+ public override void Flush()
+ {
+ }
+
+ public override long Length
+ {
+ get { return _bytes.Length; }
+ }
+
+ public override long Position
+ {
+ get
+ {
+ return _position;
+ }
+ set
+ {
+ throw new NotSupportedException();
+ }
+ }
+
+ public override int Read(byte[] buffer, int offset, int count)
+ {
+ byte[] dataBytes = ReadInternal(count);
+
+ for (int i = 0; i < dataBytes.Length; i++)
+ {
+ buffer[offset + i] = dataBytes[i];
+ }
+
+ return dataBytes.Length;
+ }
+
+ public override long Seek(long offset, SeekOrigin origin)
+ {
+ if (origin == SeekOrigin.Begin)
+ {
+ _position = offset;
+ }
+ else if (origin == SeekOrigin.Current)
+ {
+ _position += offset;
+ }
+ else if (origin == SeekOrigin.End)
+ {
+ _position = _bytes.Length - offset;
+ }
+ else
+ {
+ throw new ArgumentException("Invalid seek origin.");
+ }
+
+ return _position;
+ }
+
+ public override void SetLength(long value)
+ {
+ throw new NotSupportedException();
+ }
+
+ public override void Write(byte[] buffer, int offset, int count)
+ {
+ throw new NotSupportedException();
+ }
+
+ bool IRandomAccessStream.CanRead
+ {
+ get { return true; }
+ }
+
+ bool IRandomAccessStream.CanWrite
+ {
+ get { return false; }
+ }
+
+ IRandomAccessStream IRandomAccessStream.CloneStream()
+ {
+ throw new NotImplementedException();
+ }
+
+ IInputStream IRandomAccessStream.GetInputStreamAt(ulong position)
+ {
+ _position = 0;
+ return this;
+ }
+
+ IOutputStream IRandomAccessStream.GetOutputStreamAt(ulong position)
+ {
+ throw new NotImplementedException();
+ }
+
+ ulong IRandomAccessStream.Position
+ {
+ get
+ {
+ return (ulong)_position;
+ }
+ }
+
+ void IRandomAccessStream.Seek(ulong position)
+ {
+ _position = (int)position;
+ }
+
+ ulong IRandomAccessStream.Size
+ {
+ get
+ {
+ return (ulong)_bytes.Length;
+ }
+ set
+ {
+ throw new NotImplementedException();
+ }
+ }
+
+ void IDisposable.Dispose()
+ {
+ }
+
+ byte[] ReadInternal(int count)
+ {
+ byte[] dataBytes;
+
+ if (_position == _bytes.Length)
+ {
+ dataBytes = new byte[0];
+ }
+ else
+ {
+ long numBytes = Math.Min(_bytes.Length - _position, count);
+ var stream = new MemoryStream(_bytes, (int)_position, (int)numBytes);
+ _position += numBytes;
+ dataBytes = stream.ToArray();
+ }
+
+ return dataBytes;
+ }
+
+ IAsyncOperationWithProgress<IBuffer, uint> IInputStream.ReadAsync(IBuffer buffer, uint count, InputStreamOptions options)
+ {
+ byte[] dataBytes = ReadInternal((int)count);
+
+ var ibuffer = dataBytes.AsBuffer();
+
+ return AsyncInfo.Run(
+ delegate (CancellationToken cancellationToken, IProgress<uint> progress)
+ {
+ return Task.FromResult<IBuffer>(ibuffer);
+ });
+ }
+
+ IAsyncOperation<bool> IOutputStream.FlushAsync()
+ {
+ throw new NotImplementedException();
+ }
+
+ IAsyncOperationWithProgress<uint, uint> IOutputStream.WriteAsync(IBuffer buffer)
+ {
+ throw new NotImplementedException();
+ }
+ }
+}
diff --git a/src/System.Net.Http/tests/FunctionalTests/MultiInterfaceStreamContent.cs b/src/System.Net.Http/tests/FunctionalTests/MultiInterfaceStreamContent.cs
new file mode 100644
index 0000000000..18bba4dac0
--- /dev/null
+++ b/src/System.Net.Http/tests/FunctionalTests/MultiInterfaceStreamContent.cs
@@ -0,0 +1,24 @@
+// Licensed to the .NET Foundation under one or more agreements.
+// The .NET Foundation licenses this file to you under the MIT license.
+// See the LICENSE file in the project root for more information.
+
+using System.IO;
+using System.Threading.Tasks;
+
+namespace System.Net.Http.Functional.Tests
+{
+ public class MultiInterfaceStreamContent : StreamContent
+ {
+ Stream _content;
+
+ public MultiInterfaceStreamContent(Stream content) : base(content)
+ {
+ _content = content;
+ }
+
+ protected override Task<Stream> CreateContentReadStreamAsync()
+ {
+ return Task.FromResult<Stream>(_content);
+ }
+ }
+}
diff --git a/src/System.Net.Http/tests/FunctionalTests/PostScenarioUWPTest.cs b/src/System.Net.Http/tests/FunctionalTests/PostScenarioUWPTest.cs
new file mode 100644
index 0000000000..1cce398e2b
--- /dev/null
+++ b/src/System.Net.Http/tests/FunctionalTests/PostScenarioUWPTest.cs
@@ -0,0 +1,162 @@
+// Licensed to the .NET Foundation under one or more agreements.
+// The .NET Foundation licenses this file to you under the MIT license.
+// See the LICENSE file in the project root for more information.
+
+using System;
+using System.Diagnostics;
+using System.IO;
+using System.Net.Http;
+using System.Text;
+using System.Threading.Tasks;
+using Xunit;
+using Xunit.Abstractions;
+
+namespace System.Net.Http.Functional.Tests
+{
+ using Configuration = System.Net.Test.Common.Configuration;
+
+ public class PostScenarioUWPTest : RemoteExecutorTestBase
+ {
+ private readonly ITestOutputHelper _output;
+
+ public PostScenarioUWPTest(ITestOutputHelper output)
+ {
+ _output = output;
+ }
+
+ [Fact]
+ public void Authentication_UseStreamContent_Throws()
+ {
+ RemoteInvoke(async () =>
+ {
+ // This test validates the current limitation of CoreFx's NetFxToWinRtStreamAdapter
+ // which throws exceptions when trying to rewind a .NET Stream when it needs to be
+ // re-POST'd to the server.
+ string username = "testuser";
+ string password = "password";
+ Uri uri = Configuration.Http.BasicAuthUriForCreds(secure: false, userName: username, password: password);
+ var handler = new HttpClientHandler();
+ handler.Credentials = new NetworkCredential(username, password);
+
+ using (var client = new HttpClient(handler))
+ {
+ byte[] postData = Encoding.UTF8.GetBytes("This is data to post.");
+ var stream = new MemoryStream(postData, false);
+ var content = new StreamContent(stream);
+
+ await Assert.ThrowsAsync<HttpRequestException>(() => client.PostAsync(uri, content));
+ }
+
+ return SuccessExitCode;
+ }).Dispose();
+ }
+
+ [Fact]
+ public void Authentication_UseMultiInterfaceNonRewindableStreamContent_Throws()
+ {
+ RemoteInvoke(async () =>
+ {
+ string username = "testuser";
+ string password = "password";
+ Uri uri = Configuration.Http.BasicAuthUriForCreds(secure: false, userName: username, password: password);
+ var handler = new HttpClientHandler();
+ handler.Credentials = new NetworkCredential(username, password);
+
+ using (var client = new HttpClient(handler))
+ {
+ byte[] postData = Encoding.UTF8.GetBytes("This is data to post.");
+ var stream = new MultiInterfaceNonRewindableReadOnlyStream(postData);
+ var content = new MultiInterfaceStreamContent(stream);
+
+ await Assert.ThrowsAsync<HttpRequestException>(() => client.PostAsync(uri, content));
+ }
+
+ return SuccessExitCode;
+ }).Dispose();
+ }
+
+ [Fact]
+ public void Authentication_UseMultiInterfaceStreamContent_Success()
+ {
+ RemoteInvoke(async () =>
+ {
+ string username = "testuser";
+ string password = "password";
+ Uri uri = Configuration.Http.BasicAuthUriForCreds(secure: false, userName: username, password: password);
+ var handler = new HttpClientHandler();
+ handler.Credentials = new NetworkCredential(username, password);
+
+ using (var client = new HttpClient(handler))
+ {
+ byte[] postData = Encoding.UTF8.GetBytes("This is data to post.");
+ var stream = new MultiInterfaceReadOnlyStream(postData);
+ var content = new MultiInterfaceStreamContent(stream);
+
+ using (HttpResponseMessage response = await client.PostAsync(uri, content))
+ {
+ Assert.Equal(HttpStatusCode.OK, response.StatusCode);
+ string responseContent = await response.Content.ReadAsStringAsync();
+ }
+ }
+
+ return SuccessExitCode;
+ }).Dispose();
+ }
+
+ [Fact]
+ public void Authentication_UseMemoryStreamVisibleBufferContent_Success()
+ {
+ RemoteInvoke(async () =>
+ {
+ string username = "testuser";
+ string password = "password";
+ Uri uri = Configuration.Http.BasicAuthUriForCreds(secure: false, userName: username, password: password);
+ var handler = new HttpClientHandler();
+ handler.Credentials = new NetworkCredential(username, password);
+
+ using (var client = new HttpClient(handler))
+ {
+ byte[] postData = Encoding.UTF8.GetBytes("This is data to post.");
+ var stream = new MemoryStream(postData, 0, postData.Length, false, true);
+ var content = new MultiInterfaceStreamContent(stream);
+
+ using (HttpResponseMessage response = await client.PostAsync(uri, content))
+ {
+ Assert.Equal(HttpStatusCode.OK, response.StatusCode);
+ string responseContent = await response.Content.ReadAsStringAsync();
+ }
+ }
+
+ return SuccessExitCode;
+ }).Dispose();
+ }
+
+ [Fact]
+ public void Authentication_UseMemoryStreamNotVisibleBufferContent_Success()
+ {
+ RemoteInvoke(async () =>
+ {
+ string username = "testuser";
+ string password = "password";
+ Uri uri = Configuration.Http.BasicAuthUriForCreds(secure: false, userName: username, password: password);
+ var handler = new HttpClientHandler();
+ handler.Credentials = new NetworkCredential(username, password);
+
+ using (var client = new HttpClient(handler))
+ {
+ byte[] postData = Encoding.UTF8.GetBytes("This is data to post.");
+ var stream = new MemoryStream(postData, 0, postData.Length, false, false);
+ var content = new MultiInterfaceStreamContent(stream);
+
+ using (HttpResponseMessage response = await client.PostAsync(uri, content))
+ {
+ Assert.Equal(HttpStatusCode.OK, response.StatusCode);
+ string responseContent = await response.Content.ReadAsStringAsync();
+ }
+ }
+
+ return SuccessExitCode;
+ }).Dispose();
+ }
+ }
+}
diff --git a/src/System.Net.Http/tests/FunctionalTests/System.Net.Http.Functional.Tests.csproj b/src/System.Net.Http/tests/FunctionalTests/System.Net.Http.Functional.Tests.csproj
index 3d9f663f39..e6aeb07908 100644
--- a/src/System.Net.Http/tests/FunctionalTests/System.Net.Http.Functional.Tests.csproj
+++ b/src/System.Net.Http/tests/FunctionalTests/System.Net.Http.Functional.Tests.csproj
@@ -17,9 +17,6 @@
<PropertyGroup Condition="'$(Configuration)|$(Platform)' == 'uap-Windows_NT-Debug|AnyCPU'" />
<PropertyGroup Condition="'$(Configuration)|$(Platform)' == 'uap-Windows_NT-Release|AnyCPU'" />
<ItemGroup>
- <Compile Include="$(CommonTestPath)\System\AssertExtensions.cs">
- <Link>Common\System\AssertExtensions.cs</Link>
- </Compile>
<Compile Include="$(CommonTestPath)\System\PlatformDetection.cs">
<Link>Common\System\PlatformDetection.cs</Link>
</Compile>
@@ -110,6 +107,13 @@
<Compile Include="ManagedHandlerTest.cs" />
<Compile Include="HttpClientHandlerTest.AcceptAllCerts.cs" />
</ItemGroup>
+ <ItemGroup Condition="'$(TargetGroup)' == 'uap'">
+ <Reference Include="Windows" />
+ <Compile Include="MultiInterfaceNonRewindableReadOnlyStream.cs" />
+ <Compile Include="MultiInterfaceReadOnlyStream.cs" />
+ <Compile Include="MultiInterfaceStreamContent.cs" />
+ <Compile Include="PostScenarioUWPTest.cs" />
+ </ItemGroup>
<ItemGroup>
<ProjectReference Include="$(CommonTestPath)\System\Diagnostics\RemoteExecutorConsoleApp\RemoteExecutorConsoleApp.csproj">
<Project>{69e46a6f-9966-45a5-8945-2559fe337827}</Project>
diff --git a/src/System.Net.Http/tests/UnitTests/System.Net.Http.Unit.Tests.csproj b/src/System.Net.Http/tests/UnitTests/System.Net.Http.Unit.Tests.csproj
index dd0715f318..5152dcdd79 100644
--- a/src/System.Net.Http/tests/UnitTests/System.Net.Http.Unit.Tests.csproj
+++ b/src/System.Net.Http/tests/UnitTests/System.Net.Http.Unit.Tests.csproj
@@ -394,9 +394,6 @@
<Compile Include="HttpRuleParserTest.cs" />
<Compile Include="MockContent.cs" />
<Compile Include="StreamToStreamCopyTest.cs" />
- <Compile Include="$(CommonTestPath)\System\AssertExtensions.cs">
- <Link>Common\System\AssertExtensions.cs</Link>
- </Compile>
</ItemGroup>
<ItemGroup Condition="'$(TargetGroup)' != 'netstandard' And '$(TargetGroup)' != 'netcoreapp'">
<Compile Include="$(CommonPath)\System\SerializableAttribute.cs">
diff --git a/src/System.Net.HttpListener/src/System.Net.HttpListener.csproj b/src/System.Net.HttpListener/src/System.Net.HttpListener.csproj
index ae13f1b8ac..16307ee5c9 100644
--- a/src/System.Net.HttpListener/src/System.Net.HttpListener.csproj
+++ b/src/System.Net.HttpListener/src/System.Net.HttpListener.csproj
@@ -4,10 +4,11 @@
<PropertyGroup>
<ProjectGuid>{31E8D18B-9E7D-4924-AFD8-5BD8D75C31FB}</ProjectGuid>
<AllowUnsafeBlocks>true</AllowUnsafeBlocks>
- <!-- Although we have a NS configuration, the actual UWP implementation will be fully managed, so just validate against OneCore -->
- <UWPCompatible>false</UWPCompatible>
<ForceManagedImplementation>false</ForceManagedImplementation>
</PropertyGroup>
+ <PropertyGroup>
+ <DefineConstants Condition="'$(TargetGroup)' == 'uap'">$(DefineConstants);uap</DefineConstants>
+ </PropertyGroup>
<!-- Default configurations to help VS understand the options -->
<PropertyGroup Condition="'$(Configuration)|$(Platform)' == 'netcoreapp-Unix-Debug|AnyCPU'" />
<PropertyGroup Condition="'$(Configuration)|$(Platform)' == 'netcoreapp-Unix-Release|AnyCPU'" />
@@ -108,7 +109,7 @@
</Compile>
<Compile Include="System\Net\Windows\CookieExtensions.cs" />
</ItemGroup>
- <ItemGroup Condition="'$(TargetsWindows)' == 'true' AND '$(ForceManagedImplementation)' != 'true'">
+ <ItemGroup Condition="'$(TargetsWindows)' == 'true' AND '$(ForceManagedImplementation)' != 'true' AND '$(TargetGroup)' != 'uap'">
<Compile Include="System\Net\Windows\HttpListener.Windows.cs" />
<Compile Include="System\Net\Windows\HttpListenerContext.Windows.cs" />
<Compile Include="System\Net\Windows\HttpListenerRequest.Windows.cs" />
@@ -337,7 +338,7 @@
<Link>Common\Interop\Windows\sspicli\SSPIWrapper.cs</Link>
</Compile>
</ItemGroup>
- <ItemGroup Condition="'$(TargetsUnix)' == 'true' OR '$(ForceManagedImplementation)' == 'true'">
+ <ItemGroup Condition="'$(TargetsUnix)' == 'true' OR '$(ForceManagedImplementation)' == 'true' OR ('$(TargetsWindows)' == 'true' AND '$(TargetGroup)' == 'uap')">
<Compile Include="System\Net\Managed\HttpEndPointListener.cs" />
<Compile Include="System\Net\Managed\HttpEndPointManager.cs" />
<Compile Include="System\Net\Managed\HttpConnection.cs" />
diff --git a/src/System.Net.HttpListener/src/System/Net/Windows/CookieExtensions.cs b/src/System.Net.HttpListener/src/System/Net/Windows/CookieExtensions.cs
index 816f90e498..a343cb0555 100644
--- a/src/System.Net.HttpListener/src/System/Net/Windows/CookieExtensions.cs
+++ b/src/System.Net.HttpListener/src/System/Net/Windows/CookieExtensions.cs
@@ -2,6 +2,7 @@
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
+using System.Diagnostics;
using System.Reflection;
namespace System.Net
@@ -15,8 +16,16 @@ namespace System.Net
{
if (s_toServerStringFunc == null)
{
- s_toServerStringFunc = (Func<Cookie, string>)typeof(Cookie).GetMethod("ToServerString", BindingFlags.NonPublic | BindingFlags.Instance).CreateDelegate(typeof(Func<Cookie, string>));
+ BindingFlags flags = BindingFlags.Instance;
+#if uap
+ flags |= BindingFlags.Public;
+#else
+ flags |= BindingFlags.NonPublic;
+#endif
+ s_toServerStringFunc = (Func<Cookie, string>)typeof(Cookie).GetMethod("ToServerString", flags).CreateDelegate(typeof(Func<Cookie, string>));
}
+
+ Debug.Assert(s_toServerStringFunc != null, "Reflection failed for Cookie.ToServerString().");
return s_toServerStringFunc(cookie);
}
@@ -26,8 +35,16 @@ namespace System.Net
{
if (s_cloneFunc == null)
{
- s_cloneFunc = (Func<Cookie, Cookie>)typeof(Cookie).GetMethod("Clone", BindingFlags.NonPublic | BindingFlags.Instance).CreateDelegate(typeof(Func<Cookie, Cookie>));
+ BindingFlags flags = BindingFlags.Instance;
+#if uap
+ flags |= BindingFlags.Public;
+#else
+ flags |= BindingFlags.NonPublic;
+#endif
+ s_cloneFunc = (Func<Cookie, Cookie>)typeof(Cookie).GetMethod("Clone", flags).CreateDelegate(typeof(Func<Cookie, Cookie>));
}
+
+ Debug.Assert(s_cloneFunc != null, "Reflection failed for Cookie.Clone().");
return s_cloneFunc(cookie);
}
@@ -46,9 +63,16 @@ namespace System.Net
{
if (s_getVariantFunc == null)
{
- s_getVariantFunc = (Func<Cookie, CookieVariant>)typeof(Cookie).GetProperty("Variant", BindingFlags.NonPublic | BindingFlags.Instance).GetGetMethod(true).CreateDelegate(typeof(Func<Cookie, CookieVariant>));
+ BindingFlags flags = BindingFlags.Instance;
+#if uap
+ flags |= BindingFlags.Public;
+#else
+ flags |= BindingFlags.NonPublic;
+#endif
+ s_getVariantFunc = (Func<Cookie, CookieVariant>)typeof(Cookie).GetProperty("Variant", flags).GetGetMethod(true).CreateDelegate(typeof(Func<Cookie, CookieVariant>));
}
+ Debug.Assert(s_getVariantFunc != null, "Reflection failed for Cookie.Variant.");
CookieVariant variant = s_getVariantFunc(cookie);
return variant == CookieVariant.Rfc2965;
@@ -63,9 +87,16 @@ namespace System.Net
{
if (s_internalAddFunc == null)
{
- s_internalAddFunc = (Func<CookieCollection, Cookie, bool, int>)typeof(CookieCollection).GetMethod("InternalAdd", BindingFlags.NonPublic | BindingFlags.Instance).CreateDelegate(typeof(Func<CookieCollection, Cookie, bool, int>));
+ BindingFlags flags = BindingFlags.Instance;
+#if uap
+ flags |= BindingFlags.Public;
+#else
+ flags |= BindingFlags.NonPublic;
+#endif
+ s_internalAddFunc = (Func<CookieCollection, Cookie, bool, int>)typeof(CookieCollection).GetMethod("InternalAdd", flags).CreateDelegate(typeof(Func<CookieCollection, Cookie, bool, int>));
}
+ Debug.Assert(s_internalAddFunc != null, "Reflection failed for CookieCollection.InternalAdd().");
return s_internalAddFunc(cookieCollection, cookie, isStrict);
}
}
diff --git a/src/System.Net.HttpListener/tests/HttpListenerAuthenticationTests.cs b/src/System.Net.HttpListener/tests/HttpListenerAuthenticationTests.cs
index 6d78d3e62f..6b69a391cf 100644
--- a/src/System.Net.HttpListener/tests/HttpListenerAuthenticationTests.cs
+++ b/src/System.Net.HttpListener/tests/HttpListenerAuthenticationTests.cs
@@ -32,7 +32,6 @@ namespace System.Net.Tests
// [ActiveIssue(20840, TestPlatforms.Unix)] // Managed implementation connects successfully.
[ConditionalTheory(nameof(Helpers) + "." + nameof(Helpers.IsWindowsImplementation))]
- [ActiveIssue(17462, TargetFrameworkMonikers.Uap)]
[InlineData("Basic")]
[InlineData("NTLM")]
[InlineData("Negotiate")]
@@ -50,7 +49,6 @@ namespace System.Net.Tests
// [ActiveIssue(20840, TestPlatforms.Unix)] Managed implementation connects successfully.
[ConditionalTheory(nameof(Helpers) + "." + nameof(Helpers.IsWindowsImplementation))]
- [ActiveIssue(17462, TargetFrameworkMonikers.Uap)]
[InlineData("Basic")]
[InlineData("NTLM")]
[InlineData("Negotiate")]
@@ -67,7 +65,6 @@ namespace System.Net.Tests
}
[Theory]
- [ActiveIssue(17462, TargetFrameworkMonikers.Uap)]
[InlineData(AuthenticationSchemes.Basic)]
[InlineData(AuthenticationSchemes.Basic | AuthenticationSchemes.None)]
[InlineData(AuthenticationSchemes.Basic | AuthenticationSchemes.Anonymous)]
@@ -79,7 +76,6 @@ namespace System.Net.Tests
[ActiveIssue(19967, TargetFrameworkMonikers.NetFramework)]
[Theory]
- [ActiveIssue(17462, TargetFrameworkMonikers.Uap)]
[MemberData(nameof(BasicAuthenticationHeader_TestData))]
public async Task BasicAuthentication_InvalidRequest_SendsStatusCodeClient(string header, HttpStatusCode statusCode)
{
@@ -112,7 +108,6 @@ namespace System.Net.Tests
[ActiveIssue(19967, TargetFrameworkMonikers.NetFramework)]
[ConditionalTheory(nameof(Helpers) + "." + nameof(Helpers.IsWindowsImplementation))] // [ActiveIssue(20098, TestPlatforms.Unix)]
- [ActiveIssue(17462, TargetFrameworkMonikers.Uap)]
[InlineData("ExampleRealm")]
[InlineData(" ExampleRealm ")]
[InlineData("")]
@@ -131,7 +126,6 @@ namespace System.Net.Tests
}
[Fact]
- [ActiveIssue(17462, TargetFrameworkMonikers.Uap)]
public async Task TestAnonymousAuthentication()
{
_listener.AuthenticationSchemes = AuthenticationSchemes.Anonymous;
@@ -139,7 +133,6 @@ namespace System.Net.Tests
}
[Fact]
- [ActiveIssue(17462, TargetFrameworkMonikers.Uap)]
public async Task TestBasicAuthenticationWithDelegate()
{
_listener.AuthenticationSchemes = AuthenticationSchemes.None;
@@ -150,7 +143,6 @@ namespace System.Net.Tests
}
[Theory]
- [ActiveIssue(17462, TargetFrameworkMonikers.Uap)]
[InlineData("somename:somepassword", "somename", "somepassword")]
[InlineData("somename:", "somename", "")]
[InlineData(":somepassword", "", "somepassword")]
@@ -163,7 +155,6 @@ namespace System.Net.Tests
}
[Fact]
- [ActiveIssue(17462, TargetFrameworkMonikers.Uap)]
public async Task TestAnonymousAuthenticationWithDelegate()
{
_listener.AuthenticationSchemes = AuthenticationSchemes.None;
@@ -174,7 +165,6 @@ namespace System.Net.Tests
}
[ConditionalFact(nameof(Helpers) + "." + nameof(Helpers.IsWindowsImplementation))] // [PlatformSpecific(TestPlatforms.Windows, "Managed impl doesn't support NTLM")]
- [ActiveIssue(17462, TargetFrameworkMonikers.Uap)]
[ActiveIssue(20604)]
public async Task NtlmAuthentication_Conversation_ReturnsExpectedType2Message()
{
@@ -198,7 +188,6 @@ namespace System.Net.Tests
}
[ConditionalFact(nameof(Helpers) + "." + nameof(Helpers.IsWindowsImplementation))] // [PlatformSpecific(TestPlatforms.Windows, "Managed impl doesn't support NTLM")]
- [ActiveIssue(17462, TargetFrameworkMonikers.Uap)]
[ActiveIssue(20604)]
[MemberData(nameof(InvalidNtlmNegotiateAuthentication_TestData))]
public async Task NtlmAuthentication_InvalidRequestHeaders_ReturnsExpectedStatusCode(string header, HttpStatusCode statusCode)
@@ -222,7 +211,6 @@ namespace System.Net.Tests
}
[ConditionalFact(nameof(Helpers) + "." + nameof(Helpers.IsWindowsImplementation))] // [PlatformSpecific(TestPlatforms.Windows, "Managed impl doesn't support Negotiate")]
- [ActiveIssue(17462, TargetFrameworkMonikers.Uap)]
[ActiveIssue(20604)]
public async Task NegotiateAuthentication_Conversation_ReturnsExpectedType2Message()
{
@@ -238,7 +226,6 @@ namespace System.Net.Tests
}
[ConditionalFact(nameof(Helpers) + "." + nameof(Helpers.IsWindowsImplementation))] // [PlatformSpecific(TestPlatforms.Windows, "Managed impl doesn't support Negotiate")]
- [ActiveIssue(17462, TargetFrameworkMonikers.Uap)]
[ActiveIssue(20604)]
[MemberData(nameof(InvalidNtlmNegotiateAuthentication_TestData))]
public async Task NegotiateAuthentication_InvalidRequestHeaders_ReturnsExpectedStatusCode(string header, HttpStatusCode statusCode)
@@ -255,7 +242,6 @@ namespace System.Net.Tests
}
[Fact]
- [ActiveIssue(17462, TargetFrameworkMonikers.Uap)]
public async Task AuthenticationSchemeSelectorDelegate_ReturnsInvalidAuthenticationScheme_PerformsNoAuthentication()
{
_listener.AuthenticationSchemes = AuthenticationSchemes.Basic;
@@ -274,7 +260,6 @@ namespace System.Net.Tests
}
[Fact]
- [ActiveIssue(17462, TargetFrameworkMonikers.Uap)]
public async Task AuthenticationSchemeSelectorDelegate_ThrowsException_SendsInternalServerErrorToClient()
{
_listener.AuthenticationSchemes = AuthenticationSchemes.Basic;
@@ -287,7 +272,6 @@ namespace System.Net.Tests
}
[Fact]
- [ActiveIssue(17462, TargetFrameworkMonikers.Uap)]
public void AuthenticationSchemeSelectorDelegate_ThrowsOutOfMemoryException_RethrowsException()
{
_listener.AuthenticationSchemes = AuthenticationSchemes.Basic;
@@ -301,7 +285,6 @@ namespace System.Net.Tests
}
[Fact]
- [ActiveIssue(17462, TargetFrameworkMonikers.Uap)]
public void AuthenticationSchemeSelectorDelegate_SetDisposed_ThrowsObjectDisposedException()
{
var listener = new HttpListener();
@@ -311,7 +294,6 @@ namespace System.Net.Tests
}
[Fact]
- [ActiveIssue(17462, TargetFrameworkMonikers.Uap)]
public void AuthenticationSchemes_SetDisposed_ThrowsObjectDisposedException()
{
var listener = new HttpListener();
@@ -321,7 +303,6 @@ namespace System.Net.Tests
}
[Fact]
- [ActiveIssue(17462, TargetFrameworkMonikers.Uap)]
public void ExtendedProtectionPolicy_SetNull_ThrowsArgumentNullException()
{
using (var listener = new HttpListener())
@@ -331,7 +312,6 @@ namespace System.Net.Tests
}
[Fact]
- [ActiveIssue(17462, TargetFrameworkMonikers.Uap)]
public void ExtendedProtectionPolicy_SetDisposed_ThrowsObjectDisposedException()
{
var listener = new HttpListener();
@@ -341,7 +321,6 @@ namespace System.Net.Tests
}
[Fact]
- [ActiveIssue(17462, TargetFrameworkMonikers.Uap)]
public void ExtendedProtectionPolicy_SetCustomChannelBinding_ThrowsObjectDisposedException()
{
using (var listener = new HttpListener())
@@ -352,7 +331,6 @@ namespace System.Net.Tests
}
[Fact]
- [ActiveIssue(17462, TargetFrameworkMonikers.Uap)]
public void UnsafeConnectionNtlmAuthentication_SetGet_ReturnsExpected()
{
using (var listener = new HttpListener())
@@ -371,7 +349,6 @@ namespace System.Net.Tests
}
[Fact]
- [ActiveIssue(17462, TargetFrameworkMonikers.Uap)]
public void UnsafeConnectionNtlmAuthentication_SetDisposed_ThrowsObjectDisposedException()
{
var listener = new HttpListener();
@@ -381,7 +358,6 @@ namespace System.Net.Tests
}
[Fact]
- [ActiveIssue(17462, TargetFrameworkMonikers.Uap)]
public void ExtendedProtectionSelectorDelegate_SetNull_ThrowsArgumentNullException()
{
using (var listener = new HttpListener())
@@ -391,7 +367,6 @@ namespace System.Net.Tests
}
[Fact]
- [ActiveIssue(17462, TargetFrameworkMonikers.Uap)]
public void ExtendedProtectionSelectorDelegate_SetDisposed_ThrowsObjectDisposedException()
{
var listener = new HttpListener();
@@ -401,7 +376,6 @@ namespace System.Net.Tests
}
[Fact]
- [ActiveIssue(17462, TargetFrameworkMonikers.Uap)]
public async Task Realm_SetWithoutBasicAuthenticationScheme_SendsNoChallengeToClient()
{
_listener.Realm = "ExampleRealm";
@@ -418,7 +392,6 @@ namespace System.Net.Tests
}
[Fact]
- [ActiveIssue(17462, TargetFrameworkMonikers.Uap)]
public void Realm_SetDisposed_ThrowsObjectDisposedException()
{
var listener = new HttpListener();
diff --git a/src/System.Net.HttpListener/tests/HttpListenerContextTests.cs b/src/System.Net.HttpListener/tests/HttpListenerContextTests.cs
index 915ffedd0b..27ff628926 100644
--- a/src/System.Net.HttpListener/tests/HttpListenerContextTests.cs
+++ b/src/System.Net.HttpListener/tests/HttpListenerContextTests.cs
@@ -46,7 +46,6 @@ namespace System.Net.Tests
}
[ConditionalTheory(nameof(IsNotWindows7))]
- [ActiveIssue(17462, TargetFrameworkMonikers.Uap)]
[MemberData(nameof(SubProtocol_TestData))]
public async Task AcceptWebSocketAsync_ValidSubProtocol_Success(string[] clientProtocols, string serverProtocol)
{
@@ -56,7 +55,6 @@ namespace System.Net.Tests
}
[ConditionalTheory(nameof(IsNotWindows7))]
- [ActiveIssue(17462, TargetFrameworkMonikers.Uap)]
public async Task AcceptWebSocketAsync_ValidWebSocket_SetsUpHeadersInResponse()
{
HttpListenerContext context = await GetWebSocketContext(new string[] { "SubProtocol", "SubProtocol2" });
@@ -81,7 +79,6 @@ namespace System.Net.Tests
}
[ConditionalFact(nameof(IsNotWindows7))]
- [ActiveIssue(17462, TargetFrameworkMonikers.Uap)]
public async Task AcceptWebSocketAsync_ValidWebSocket_SetsUpContextProperties()
{
Socket.Options.SetRequestHeader("origin", "Browser");
@@ -100,7 +97,6 @@ namespace System.Net.Tests
}
[ConditionalFact(nameof(IsNotWindows7))]
- [ActiveIssue(17462, TargetFrameworkMonikers.Uap)]
public async Task AcceptWebSocketAsync_AuthorizationInHeaders_ThrowsNotImplementedException()
{
Socket.Options.SetRequestHeader("Authorization", "Basic " + Convert.ToBase64String(Encoding.ASCII.GetBytes("user:password")));
@@ -120,7 +116,6 @@ namespace System.Net.Tests
}
[ConditionalFact(nameof(IsNotWindows7))]
- [ActiveIssue(17462, TargetFrameworkMonikers.Uap)]
public async Task AcceptWebSocketAsync_UnsupportedProtocol_ThrowsWebSocketException()
{
HttpListenerContext context = await GetWebSocketContext(new string[] { "MyProtocol" });
@@ -128,7 +123,6 @@ namespace System.Net.Tests
}
[ConditionalFact(nameof(IsNotWindows7))]
- [ActiveIssue(17462, TargetFrameworkMonikers.Uap)]
public async Task AcceptWebSocketAsync_NoClientSubProtocol_ThrowsWebSocketException()
{
HttpListenerContext context = await GetWebSocketContext();
@@ -136,7 +130,6 @@ namespace System.Net.Tests
}
[ConditionalTheory(nameof(IsNotWindows7))]
- [ActiveIssue(17462, TargetFrameworkMonikers.Uap)]
[InlineData("Connection: ")]
[InlineData("Connection: Connection\r\nUpgrade: ")]
[InlineData("Connection: Test1\r\nUpgrade: Test2")]
@@ -157,7 +150,6 @@ namespace System.Net.Tests
}
[ConditionalTheory(nameof(IsNotWindows7))]
- [ActiveIssue(17462, TargetFrameworkMonikers.Uap)]
[InlineData("")]
[InlineData(" ")]
[InlineData("random(text")]
@@ -186,7 +178,6 @@ namespace System.Net.Tests
}
[ConditionalTheory(nameof(IsNotWindows7))]
- [ActiveIssue(17462, TargetFrameworkMonikers.Uap)]
[InlineData("!")]
[InlineData("#")]
[InlineData("YouDontKnowMe")]
@@ -197,7 +188,6 @@ namespace System.Net.Tests
}
[ConditionalFact(nameof(IsNotWindows7))]
- [ActiveIssue(17462, TargetFrameworkMonikers.Uap)]
public async Task AcceptWebSocketAsync_InvalidKeepAlive_ThrowsWebSocketException()
{
HttpListenerContext context = await GetWebSocketContext();
@@ -207,7 +197,6 @@ namespace System.Net.Tests
}
[ConditionalTheory(nameof(IsNotWindows7))]
- [ActiveIssue(17462, TargetFrameworkMonikers.Uap)]
[InlineData(-1)]
[InlineData(0)]
[InlineData(255)]
@@ -219,7 +208,6 @@ namespace System.Net.Tests
}
[ConditionalFact(nameof(IsNotWindows7))]
- [ActiveIssue(17462, TargetFrameworkMonikers.Uap)]
public async Task AcceptWebSocketAsync_NullArrayInArraySegment_ThrowsArgumentNullException()
{
HttpListenerContext context = await GetWebSocketContext();
@@ -229,7 +217,6 @@ namespace System.Net.Tests
}
[ConditionalTheory(nameof(IsNotWindows7))]
- [ActiveIssue(17462, TargetFrameworkMonikers.Uap)]
[InlineData(-1)]
[InlineData(11)]
public async Task AcceptWebSocketAsync_InvalidOffsetInArraySegment_ThrowsArgumentNullException(int offset)
@@ -241,7 +228,6 @@ namespace System.Net.Tests
}
[ConditionalTheory(nameof(IsNotWindows7))]
- [ActiveIssue(17462, TargetFrameworkMonikers.Uap)]
[InlineData(0, -1)]
[InlineData(0, 11)]
[InlineData(10, 1)]
diff --git a/src/System.Net.HttpListener/tests/HttpListenerFactory.cs b/src/System.Net.HttpListener/tests/HttpListenerFactory.cs
index 762804e50f..289cd1b97a 100644
--- a/src/System.Net.HttpListener/tests/HttpListenerFactory.cs
+++ b/src/System.Net.HttpListener/tests/HttpListenerFactory.cs
@@ -13,9 +13,10 @@ namespace System.Net.Tests
// Utilities for generating URL prefixes for HttpListener
public class HttpListenerFactory : IDisposable
{
- const int MinPort = 1025;
- private static readonly object s_createListenerLock = new object();
- private static int s_nextPort = MinPort;
+ const int StartPort = 1025;
+ const int MaxStartAttempts = IPEndPoint.MaxPort - StartPort + 1;
+ private static readonly object s_nextPortLock = new object();
+ private static int s_nextPort = StartPort;
private readonly HttpListener _processPrefixListener;
private readonly Exception _processPrefixException;
@@ -33,54 +34,45 @@ namespace System.Net.Tests
_path = path ?? Guid.NewGuid().ToString("N");
string pathComponent = string.IsNullOrEmpty(_path) ? _path : $"{_path}/";
- lock (s_createListenerLock)
+ for (int attempt = 0; attempt < MaxStartAttempts; attempt++)
{
- foreach (int port in Enumerable.Range(s_nextPort, IPEndPoint.MaxPort - s_nextPort + 1).Concat(Enumerable.Range(MinPort, s_nextPort - MinPort)))
+ int port = GetNextPort();
+ string prefix = $"http://{hostname}:{port}/{pathComponent}";
+
+ var listener = new HttpListener();
+ try
{
- string prefix = $"http://{hostname}:{port}/{pathComponent}";
+ listener.Prefixes.Add(prefix);
+ listener.Start();
- var listener = new HttpListener();
- try
- {
- listener.Prefixes.Add(prefix);
- listener.Start();
+ _processPrefixListener = listener;
+ _processPrefix = prefix;
+ _port = port;
+ break;
+ }
+ catch (Exception e)
+ {
+ // can't use this prefix
+ listener.Close();
+
+ // Remember the exception for later
+ _processPrefixException = e;
- _processPrefixListener = listener;
- _processPrefix = prefix;
- _port = port;
- if (RuntimeInformation.IsOSPlatform(OSPlatform.Windows) && Helpers.IsManagedImplementation)
+ if (e is HttpListenerException listenerException)
+ {
+ // If we can't access the host (e.g. if it is '+' or '*' and the current user is the administrator)
+ // then throw.
+ const int ERROR_ACCESS_DENIED = 5;
+ if (listenerException.ErrorCode == ERROR_ACCESS_DENIED && (hostname == "*" || hostname == "+"))
{
- // Try to avoid reusing the same port from test to test if we're using
- // the WinHttp ClientWebSocket against the managed HttpListener.
- // https://github.com/dotnet/corefx/issues/20439
- s_nextPort = port + 1;
+ throw new InvalidOperationException($"Access denied for host {hostname}");
}
- break;
}
- catch (Exception e)
+ else if (!(e is SocketException))
{
- // can't use this prefix
- listener.Close();
-
- // Remember the exception for later
- _processPrefixException = e;
-
- if (e is HttpListenerException listenerException)
- {
- // If we can't access the host (e.g. if it is '+' or '*' and the current user is the administrator)
- // then throw.
- const int ERROR_ACCESS_DENIED = 5;
- if (listenerException.ErrorCode == ERROR_ACCESS_DENIED && (hostname == "*" || hostname == "+"))
- {
- throw new InvalidOperationException($"Access denied for host {hostname}");
- }
- }
- else if (!(e is SocketException))
- {
- // If this is not an HttpListenerException or SocketException, something very wrong has happened, and there's no point
- // in trying again.
- break;
- }
+ // If this is not an HttpListenerException or SocketException, something very wrong has happened, and there's no point
+ // in trying again.
+ break;
}
}
}
@@ -203,6 +195,19 @@ namespace System.Net.Tests
{
return GetContent("1.1", requestType, query: null, text: text, headers: null, headerOnly: headerOnly);
}
+
+ private static int GetNextPort()
+ {
+ lock (s_nextPortLock)
+ {
+ int port = s_nextPort++;
+ if (s_nextPort > IPEndPoint.MaxPort)
+ {
+ s_nextPort = StartPort;
+ }
+ return port;
+ }
+ }
}
public static class RequestTypes
diff --git a/src/System.Net.HttpListener/tests/HttpListenerPrefixCollectionTests.cs b/src/System.Net.HttpListener/tests/HttpListenerPrefixCollectionTests.cs
index 69d64a92df..664fe167a2 100644
--- a/src/System.Net.HttpListener/tests/HttpListenerPrefixCollectionTests.cs
+++ b/src/System.Net.HttpListener/tests/HttpListenerPrefixCollectionTests.cs
@@ -11,8 +11,9 @@ namespace System.Net.Tests
{
public class HttpListenerPrefixCollectionTests
{
+ public static bool IsNonZeroLowerBoundArraySupported => PlatformDetection.IsNonZeroLowerBoundArraySupported;
+
[Fact]
- [ActiveIssue(17462, TargetFrameworkMonikers.Uap)]
public void Prefixes_Get_ReturnsEmpty()
{
var listener = new HttpListener();
@@ -24,7 +25,6 @@ namespace System.Net.Tests
}
[Theory]
- [ActiveIssue(17462, TargetFrameworkMonikers.Uap)]
[InlineData(0)]
[InlineData(1)]
public void CopyTo_StringArray_ReturnsExpected(int offset)
@@ -46,7 +46,6 @@ namespace System.Net.Tests
}
[Theory]
- [ActiveIssue(17462, TargetFrameworkMonikers.Uap)]
[InlineData(0)]
[InlineData(1)]
public void CopyTo_Array_ReturnsExpected(int offset)
@@ -68,7 +67,6 @@ namespace System.Net.Tests
}
[Fact]
- [ActiveIssue(17462, TargetFrameworkMonikers.Uap)]
public void CopyTo_DisposedListener_ThrowsObjectDisposedException()
{
var listener = new HttpListener();
@@ -80,7 +78,6 @@ namespace System.Net.Tests
}
[Fact]
- [ActiveIssue(17462, TargetFrameworkMonikers.Uap)]
[SkipOnTargetFramework(TargetFrameworkMonikers.NetFramework, ".NET Core fixes a bug where HttpListenerPrefixCollection.CopyTo(null) throws an NRE.")]
public void CopyTo_NullArray_ThrowsArgumentNullExceptionOnNetCore()
{
@@ -90,7 +87,6 @@ namespace System.Net.Tests
}
[Fact]
- [ActiveIssue(17462, TargetFrameworkMonikers.Uap)]
[SkipOnTargetFramework(~TargetFrameworkMonikers.NetFramework, ".NET Core fixes a bug where HttpListenerPrefixCollection.CopyTo(null) throws an NRE.")]
public void CopyTo_NullArray_ThrowsNullReferenceExceptionOnNetFx()
{
@@ -100,7 +96,6 @@ namespace System.Net.Tests
}
[Fact]
- [ActiveIssue(17462, TargetFrameworkMonikers.Uap)]
public void CopyTo_MultidimensionalArray_ThrowsIndexOutOfRangeException()
{
var listener = new HttpListener();
@@ -113,8 +108,7 @@ namespace System.Net.Tests
AssertExtensions.Throws<ArgumentException>(null, () => listener.Prefixes.CopyTo(new object[1, 1], 0));
}
- [Fact]
- [ActiveIssue(17462, TargetFrameworkMonikers.UapAot)]
+ [ConditionalFact(nameof(IsNonZeroLowerBoundArraySupported))]
public void CopyTo_NonZeroLowerBoundArray_ThrowsIndexOutOfRangeException()
{
var listener = new HttpListener();
@@ -129,7 +123,6 @@ namespace System.Net.Tests
}
[Fact]
- [ActiveIssue(17462, TargetFrameworkMonikers.Uap)]
public void CopyTo_InvalidArrayType_ThrowsInvalidCastException()
{
var listener = new HttpListener();
@@ -143,7 +136,6 @@ namespace System.Net.Tests
}
[Fact]
- [ActiveIssue(17462, TargetFrameworkMonikers.Uap)]
public void CopyTo_ArrayTooSmall_ThrowsArgumentOutOfRangeException()
{
var listener = new HttpListener();
@@ -153,7 +145,6 @@ namespace System.Net.Tests
}
[Theory]
- [ActiveIssue(17462, TargetFrameworkMonikers.Uap)]
[InlineData(1)]
[InlineData(2)]
public void CopyTo_InvalidOffset_ThrowsArgumentOutOfRangeException(int offset)
@@ -165,7 +156,6 @@ namespace System.Net.Tests
}
[Fact]
- [ActiveIssue(17462, TargetFrameworkMonikers.Uap)]
public void IsSynchronized_Get_ReturnsFalse()
{
var listener = new HttpListener();
@@ -173,7 +163,6 @@ namespace System.Net.Tests
}
[Fact]
- [ActiveIssue(17462, TargetFrameworkMonikers.Uap)]
public void IsReadOnly_Get_ReturnsFalse()
{
var listener = new HttpListener();
@@ -181,7 +170,6 @@ namespace System.Net.Tests
}
[Theory]
- [ActiveIssue(17462, TargetFrameworkMonikers.Uap)]
[InlineData("http://*/")]
[InlineData("http://+/")]
[InlineData("http://localhost/")]
@@ -202,7 +190,6 @@ namespace System.Net.Tests
}
[Fact]
- [ActiveIssue(17462, TargetFrameworkMonikers.Uap)]
public void Add_AlreadyStarted_ReturnsExpected()
{
using (var factory = new HttpListenerFactory())
@@ -231,7 +218,6 @@ namespace System.Net.Tests
}
[Theory]
- [ActiveIssue(17462, TargetFrameworkMonikers.Uap)]
[MemberData(nameof(Hosts_TestData))]
public void Add_PrefixAlreadyRegisteredAndNotStarted_ThrowsHttpListenerException(string hostname)
{
@@ -247,7 +233,6 @@ namespace System.Net.Tests
}
[Theory]
- [ActiveIssue(17462, TargetFrameworkMonikers.Uap)]
[MemberData(nameof(Hosts_TestData))]
public void Add_PrefixAlreadyRegisteredWithDifferentPathAndNotStarted_Works(string hostname)
{
@@ -265,7 +250,6 @@ namespace System.Net.Tests
}
[Theory]
- [ActiveIssue(17462, TargetFrameworkMonikers.Uap)]
[MemberData(nameof(Hosts_TestData))]
public void Add_PrefixAlreadyRegisteredAndStarted_ThrowsHttpListenerException(string hostname)
{
@@ -292,7 +276,6 @@ namespace System.Net.Tests
}
[Theory]
- [ActiveIssue(17462, TargetFrameworkMonikers.Uap)]
[MemberData(nameof(Hosts_TestData))]
public void Add_SamePortDifferentPathDifferentListenerNotStarted_Works(string host)
{
@@ -312,7 +295,6 @@ namespace System.Net.Tests
}
[Theory]
- [ActiveIssue(17462, TargetFrameworkMonikers.Uap)]
[MemberData(nameof(Hosts_TestData))]
public void Add_SamePortDifferentPathDifferentListenerStarted_Works(string host)
{
@@ -341,7 +323,6 @@ namespace System.Net.Tests
}
[Theory]
- [ActiveIssue(17462, TargetFrameworkMonikers.Uap)]
[MemberData(nameof(Hosts_TestData))]
public void Add_SamePortDifferentPathMultipleStarted_Success(string host)
{
@@ -388,7 +369,6 @@ namespace System.Net.Tests
[SkipOnTargetFramework(TargetFrameworkMonikers.NetFramework)] // Issue #19619
[Theory]
- [ActiveIssue(17462, TargetFrameworkMonikers.Uap)]
[MemberData(nameof(InvalidPrefix_TestData))]
public void Add_InvalidPrefixNotStarted_ThrowsHttpListenerExceptionOnStart(string uriPrefix)
{
@@ -402,7 +382,6 @@ namespace System.Net.Tests
[SkipOnTargetFramework(TargetFrameworkMonikers.NetFramework)] // Issue #19619
[Theory]
- [ActiveIssue(17462, TargetFrameworkMonikers.Uap)]
[MemberData(nameof(InvalidPrefix_TestData))]
public void Add_InvalidPrefixAlreadyStarted_ThrowsHttpListenerExceptionOnAdd(string uriPrefix)
{
@@ -416,7 +395,6 @@ namespace System.Net.Tests
}
[Theory]
- [ActiveIssue(17462, TargetFrameworkMonikers.Uap)]
[InlineData("")]
[InlineData("http")]
[InlineData("https")]
@@ -440,7 +418,6 @@ namespace System.Net.Tests
}
[Fact]
- [ActiveIssue(17462, TargetFrameworkMonikers.Uap)]
public void Add_NullPrefix_ThrowsArgumentNullException()
{
var listener = new HttpListener();
@@ -448,7 +425,6 @@ namespace System.Net.Tests
}
[Fact]
- [ActiveIssue(17462, TargetFrameworkMonikers.Uap)]
public void Add_LongHost_ThrowsArgumentOutOfRangeException()
{
var listener = new HttpListener();
@@ -464,7 +440,6 @@ namespace System.Net.Tests
}
[Fact]
- [ActiveIssue(17462, TargetFrameworkMonikers.Uap)]
public void Add_DisposedListener_ThrowsObjectDisposedException()
{
var listener = new HttpListener();
@@ -476,7 +451,6 @@ namespace System.Net.Tests
}
[Theory]
- [ActiveIssue(17462, TargetFrameworkMonikers.Uap)]
[InlineData("")]
[InlineData("http://localhost:80/")]
[InlineData("http://localhost:9200")]
@@ -490,7 +464,6 @@ namespace System.Net.Tests
}
[Fact]
- [ActiveIssue(17462, TargetFrameworkMonikers.Uap)]
public void Contains_NullPrefix_ThrowsArgumentNullException()
{
var listener = new HttpListener();
@@ -498,7 +471,6 @@ namespace System.Net.Tests
}
[Fact]
- [ActiveIssue(17462, TargetFrameworkMonikers.Uap)]
public void Remove_PrefixExistsNotStarted_ReturnsTrue()
{
var listener = new HttpListener();
@@ -510,7 +482,6 @@ namespace System.Net.Tests
}
[Fact]
- [ActiveIssue(17462, TargetFrameworkMonikers.Uap)]
public void Remove_PrefixExistsStarted_ReturnsTrue()
{
using (var factory = new HttpListenerFactory())
@@ -528,7 +499,6 @@ namespace System.Net.Tests
}
[Theory]
- [ActiveIssue(17462, TargetFrameworkMonikers.Uap)]
[InlineData("")]
[InlineData("http://localhost:80/")]
[InlineData("http://localhost:9200")]
@@ -542,7 +512,6 @@ namespace System.Net.Tests
}
[Fact]
- [ActiveIssue(17462, TargetFrameworkMonikers.Uap)]
public void Remove_DisposedListener_ThrowsObjectDisposedException()
{
var listener = new HttpListener();
@@ -553,7 +522,6 @@ namespace System.Net.Tests
}
[Fact]
- [ActiveIssue(17462, TargetFrameworkMonikers.Uap)]
public void Remove_NullPrefix_ThrowsArgumentNullException()
{
var listener = new HttpListener();
@@ -561,7 +529,6 @@ namespace System.Net.Tests
}
[Fact]
- [ActiveIssue(17462, TargetFrameworkMonikers.Uap)]
public void Clear_NonEmpty_Success()
{
var listener = new HttpListener();
@@ -573,7 +540,6 @@ namespace System.Net.Tests
}
[Fact]
- [ActiveIssue(17462, TargetFrameworkMonikers.Uap)]
public void Clear_DisposedListener_ThrowsObjectDisposedException()
{
var listener = new HttpListener();
@@ -584,7 +550,6 @@ namespace System.Net.Tests
}
[Fact]
- [ActiveIssue(17462, TargetFrameworkMonikers.Uap)]
public void GetEnumeratorGeneric_ResetMultipleTimes_ReturnsExpected()
{
var listener = new HttpListener();
@@ -610,7 +575,6 @@ namespace System.Net.Tests
}
[Fact]
- [ActiveIssue(17462, TargetFrameworkMonikers.Uap)]
public void GetEnumeratorNonGeneric_ResetMultipleTimes_ReturnsExpected()
{
var listener = new HttpListener();
diff --git a/src/System.Net.HttpListener/tests/HttpListenerRequestTests.cs b/src/System.Net.HttpListener/tests/HttpListenerRequestTests.cs
index e06b335351..c06e5115ee 100644
--- a/src/System.Net.HttpListener/tests/HttpListenerRequestTests.cs
+++ b/src/System.Net.HttpListener/tests/HttpListenerRequestTests.cs
@@ -30,7 +30,6 @@ namespace System.Net.Tests
}
[Theory]
- [ActiveIssue(17462, TargetFrameworkMonikers.Uap)]
[InlineData("Accept: Test", new string[] { "Test" })]
[InlineData("Accept: Test, Test2,Test3 , Test4", new string[] { "Test", "Test2", "Test3 ", " Test4" })]
[InlineData("Accept: Test", new string[] { "Test" })]
@@ -89,7 +88,6 @@ namespace System.Net.Tests
}
[Theory]
- [ActiveIssue(17462, TargetFrameworkMonikers.Uap)]
[MemberData(nameof(ContentEncoding_TestData))]
public async Task ContentEncoding_GetProperty_ReturnsExpected(string header, Encoding expected)
{
@@ -98,7 +96,6 @@ namespace System.Net.Tests
}
[Fact]
- [ActiveIssue(17462, TargetFrameworkMonikers.Uap)]
public async Task ContentEncoding_NoBody_ReturnsDefault()
{
HttpListenerRequest request = await GetRequest("POST", "", new string[] { "Content-Length: 0", "Content-Type:application/json;charset=unicode" }, content: null);
@@ -106,7 +103,6 @@ namespace System.Net.Tests
}
[Theory]
- [ActiveIssue(17462, TargetFrameworkMonikers.Uap)]
[InlineData("POST", "Content-Length: 9223372036854775807", 9223372036854775807, true)] // long.MaxValue
[InlineData("POST", "Content-Length: 9223372036854775808", 0, false)] // long.MaxValue + 1
[InlineData("POST", "Content-Length: 18446744073709551615 ", 0, false)] // ulong.MaxValue
@@ -127,7 +123,6 @@ namespace System.Net.Tests
}
[Theory]
- [ActiveIssue(17462, TargetFrameworkMonikers.Uap)]
[InlineData(100)]
[InlineData("-100")]
[InlineData("")]
@@ -147,7 +142,6 @@ namespace System.Net.Tests
}
[Fact]
- [ActiveIssue(17462, TargetFrameworkMonikers.Uap)]
[ActiveIssue(20294, TargetFrameworkMonikers.Netcoreapp)]
public async Task ContentLength_ManuallyRemovedFromHeaders_DoesNotAffect()
{
@@ -161,7 +155,6 @@ namespace System.Net.Tests
}
[Fact]
- [ActiveIssue(17462, TargetFrameworkMonikers.Uap)]
public async Task ContentLength_SetInHeadersAfterAccessingProperty_DoesNothing()
{
HttpListenerRequest request = await GetRequest("POST", null, new string[] { "Content-Length: 1" }, content: "\r\n");
@@ -176,7 +169,6 @@ namespace System.Net.Tests
}
[Theory]
- [ActiveIssue(17462, TargetFrameworkMonikers.Uap)]
[InlineData("Referer: http://microsoft.com", "http://microsoft.com/")]
[InlineData("referer: /relativePath", "/relativePath")]
[InlineData("Referer: NoSuchSite", "NoSuchSite")]
@@ -190,7 +182,6 @@ namespace System.Net.Tests
}
[Theory]
- [ActiveIssue(17462, TargetFrameworkMonikers.Uap)]
[InlineData("User-Agent: Test", "Test")]
[InlineData("user-agent: Test", "Test")]
[InlineData("User-Agent: ", "")]
@@ -202,7 +193,6 @@ namespace System.Net.Tests
}
[Fact]
- [ActiveIssue(17462, TargetFrameworkMonikers.Uap)]
public async Task UserHostName_GetProperty_ReturnsExpected()
{
HttpListenerRequest request = await GetRequest("POST", null, null);
@@ -210,7 +200,6 @@ namespace System.Net.Tests
}
[Fact]
- [ActiveIssue(17462, TargetFrameworkMonikers.Uap)]
public async Task EndPointProperties_GetProperty_ReturnsExpected()
{
HttpListenerRequest request = await GetRequest("POST", "", null);
@@ -229,7 +218,6 @@ namespace System.Net.Tests
}
[Fact]
- [ActiveIssue(17462, TargetFrameworkMonikers.Uap)]
public async Task ServiceName_GetNoSpn_ReturnsExpected()
{
HttpListenerRequest request = await GetRequest("POST", null, null);
@@ -237,14 +225,12 @@ namespace System.Net.Tests
}
[Fact]
- [ActiveIssue(17462, TargetFrameworkMonikers.Uap)]
public async Task RequestTraceIdentifier_GetWindows_ReturnsExpected()
{
HttpListenerRequest request = await GetRequest("POST", null, null);
Assert.NotEqual(Guid.Empty, request.RequestTraceIdentifier);
}
- [ActiveIssue(17462, TargetFrameworkMonikers.Uap)]
[Theory]
[InlineData("Connection: ", false)]
[InlineData("Connection: Connection\r\nUpgrade: ", false)]
@@ -254,8 +240,7 @@ namespace System.Net.Tests
[InlineData("Unknown-Header: Test", false)]
public async Task IsWebSocketRequest_GetProperty_ReturnsExpected(string webSocketString, bool expected)
{
- // Skip on Windows 7 or UAP platforms. WebSocket support is not present.
- if (PlatformDetection.IsWindows7 || !PlatformDetection.IsNotOneCoreUAP)
+ if (PlatformDetection.IsWindows7)
{
return;
}
@@ -265,7 +250,6 @@ namespace System.Net.Tests
}
[Theory]
- [ActiveIssue(17462, TargetFrameworkMonikers.Uap)]
[InlineData("Accept-Language: Lang1,Lang2,Lang3", new string[] { "Lang1", "Lang2", "Lang3" })]
[InlineData("Accept-Language: Lang1, Lang2, Lang3", new string[] { "Lang1", "Lang2", "Lang3" })]
[InlineData("Accept-Language: Lang1,,Lang3", new string[] { "Lang1", "", "Lang3" })]
@@ -285,7 +269,6 @@ namespace System.Net.Tests
}
[Fact]
- [ActiveIssue(17462, TargetFrameworkMonikers.Uap)]
public async Task ClientCertificateError_GetNotInitialized_ThrowsInvalidOperationException()
{
HttpListenerRequest request = await GetRequest("POST", null, null);
@@ -293,7 +276,6 @@ namespace System.Net.Tests
}
[Fact]
- [ActiveIssue(17462, TargetFrameworkMonikers.Uap)]
public async Task GetClientCertificate_NoCertificate_ReturnsNull()
{
HttpListenerRequest request = await GetRequest("POST", null, null);
@@ -302,7 +284,6 @@ namespace System.Net.Tests
}
[Fact]
- [ActiveIssue(17462, TargetFrameworkMonikers.Uap)]
public async Task GetClientCertificateAsync_NoCertificate_ReturnsNull()
{
HttpListenerRequest request = await GetRequest("POST", null, null);
@@ -310,7 +291,6 @@ namespace System.Net.Tests
}
[Fact]
- [ActiveIssue(17462, TargetFrameworkMonikers.Uap)]
public async Task EndGetClientCertificate_NullAsyncResult_ThrowsArgumentException()
{
HttpListenerRequest request = await GetRequest("POST", null, null);
@@ -318,7 +298,6 @@ namespace System.Net.Tests
}
[Fact]
- [ActiveIssue(17462, TargetFrameworkMonikers.Uap)]
public async Task EndGetClientCertificate_InvalidAsyncResult_ThrowsArgumentException()
{
HttpListenerRequest request1 = await GetRequest("POST", null, null);
@@ -333,7 +312,6 @@ namespace System.Net.Tests
}
[Fact]
- [ActiveIssue(17462, TargetFrameworkMonikers.Uap)]
public async Task EndGetClientCertificate_AlreadyCalled_ThrowsInvalidOperationException()
{
HttpListenerRequest request = await GetRequest("POST", null, null);
@@ -344,7 +322,6 @@ namespace System.Net.Tests
}
[Fact]
- [ActiveIssue(17462, TargetFrameworkMonikers.Uap)]
public async Task TransportContext_GetChannelBinding_ReturnsExpected()
{
// This might not work on other devices:
@@ -355,7 +332,6 @@ namespace System.Net.Tests
}
[Theory]
- [ActiveIssue(17462, TargetFrameworkMonikers.Uap)]
[InlineData(ChannelBindingKind.Unique)]
public async Task TransportContext_GetChannelBindingInvalid_ThrowsNotSupportedException(ChannelBindingKind kind)
{
@@ -450,7 +426,6 @@ namespace System.Net.Tests
}
[Theory]
- [ActiveIssue(17462, TargetFrameworkMonikers.Uap)]
[MemberData(nameof(QueryString_TestData))]
public async Task QueryString_GetProperty_ReturnsExpected(string query, NameValueCollection expected)
{
@@ -466,7 +441,6 @@ namespace System.Net.Tests
}
[Theory]
- [ActiveIssue(17462, TargetFrameworkMonikers.Uap)]
[InlineData("POST")]
[InlineData("PATCH")]
[InlineData("get")]
@@ -479,7 +453,6 @@ namespace System.Net.Tests
}
[Theory]
- [ActiveIssue(17462, TargetFrameworkMonikers.Uap)]
[InlineData("1.1", new string[] { "Proxy-Connection: random" }, true)]
[InlineData("1.1", new string[] { "Proxy-Connection: close" }, false)]
[InlineData("1.1", new string[] { "proxy-connection: CLOSE" }, false)]
@@ -505,7 +478,6 @@ namespace System.Net.Tests
Assert.Equal(expected, request.KeepAlive);
}
- [ActiveIssue(17462, TargetFrameworkMonikers.Uap)]
[Theory]
[InlineData("1.0")]
[InlineData("1.1")]
@@ -616,7 +588,6 @@ namespace System.Net.Tests
}
[Theory]
- [ActiveIssue(17462, TargetFrameworkMonikers.Uap)]
[MemberData(nameof(Cookies_TestData))]
public async Task Cookies_GetProperty_ReturnsExpected(string cookieString, CookieCollection expected)
{
@@ -640,7 +611,6 @@ namespace System.Net.Tests
}
[Theory]
- [ActiveIssue(17462, TargetFrameworkMonikers.Uap)]
[MemberData(nameof(Headers_TestData))]
public async Task Headers_Get_ReturnsExpected(string[] headers, WebHeaderCollection expected)
{
diff --git a/src/System.Net.HttpListener/tests/HttpListenerResponseTests.Cookies.cs b/src/System.Net.HttpListener/tests/HttpListenerResponseTests.Cookies.cs
index fb1943619a..b52204e16e 100644
--- a/src/System.Net.HttpListener/tests/HttpListenerResponseTests.Cookies.cs
+++ b/src/System.Net.HttpListener/tests/HttpListenerResponseTests.Cookies.cs
@@ -12,7 +12,6 @@ namespace System.Net.Tests
public class HttpListenerResponseCookiesTests : HttpListenerResponseTestBase
{
[Fact]
- [ActiveIssue(17462, TargetFrameworkMonikers.Uap)]
public async Task Cookies_GetSet_ReturnsExpected()
{
HttpListenerResponse response = await GetResponse();
@@ -89,7 +88,6 @@ namespace System.Net.Tests
}
[Theory]
- [ActiveIssue(17462, TargetFrameworkMonikers.Uap)]
[MemberData(nameof(Cookies_TestData))]
public async Task Cookies_SetAndSend_ClientReceivesExpectedHeaders(CookieCollection cookies, int expectedBytes, string expectedSetCookie, string expectedSetCookie2)
{
@@ -122,7 +120,6 @@ namespace System.Net.Tests
}
[Fact]
- [ActiveIssue(17462, TargetFrameworkMonikers.Uap)]
public async Task Cookies_SetInHeader_ClientReceivesExpectedHeaders()
{
HttpListenerResponse response = await GetResponse();
@@ -137,7 +134,6 @@ namespace System.Net.Tests
}
[Fact]
- [ActiveIssue(17462, TargetFrameworkMonikers.Uap)]
public async Task Cookies_SetCookie2InHeadersButNotInCookies_RemovesFromHeaders()
{
HttpListenerResponse response = await GetResponse();
@@ -157,7 +153,6 @@ namespace System.Net.Tests
}
[Fact]
- [ActiveIssue(17462, TargetFrameworkMonikers.Uap)]
public async Task Cookies_SetCookieInHeadersButNotInCookies_RemovesFromHeaders()
{
HttpListenerResponse response = await GetResponse();
@@ -177,7 +172,6 @@ namespace System.Net.Tests
}
[Fact]
- [ActiveIssue(17462, TargetFrameworkMonikers.Uap)]
public async Task AppendCookie_ValidCookie_AddsCookieToCollection()
{
HttpListenerResponse response = await GetResponse();
@@ -199,7 +193,6 @@ namespace System.Net.Tests
}
[Fact]
- [ActiveIssue(17462, TargetFrameworkMonikers.Uap)]
public async Task AppendCookie_NullCookie_ThrowsArgumentNullException()
{
HttpListenerResponse response = await GetResponse();
@@ -207,7 +200,6 @@ namespace System.Net.Tests
}
[Fact]
- [ActiveIssue(17462, TargetFrameworkMonikers.Uap)]
public async Task SetCookie_ValidCookie_AddsCookieToCollection()
{
HttpListenerResponse response = await GetResponse();
@@ -221,7 +213,6 @@ namespace System.Net.Tests
}
[Fact]
- [ActiveIssue(17462, TargetFrameworkMonikers.Uap)]
public async Task SetCookie_ValidCookie_ClonesCookie()
{
HttpListenerResponse response = await GetResponse();
@@ -234,7 +225,6 @@ namespace System.Net.Tests
}
[Fact]
- [ActiveIssue(17462, TargetFrameworkMonikers.Uap)]
public async Task SetCookie_NullCookie_ThrowsArgumentNullException()
{
HttpListenerResponse response = await GetResponse();
@@ -242,7 +232,6 @@ namespace System.Net.Tests
}
[Fact]
- [ActiveIssue(17462, TargetFrameworkMonikers.Uap)]
public async Task SetCookie_CookieDoesntExist_ThrowsArgumentException()
{
HttpListenerResponse response = await GetResponse();
diff --git a/src/System.Net.HttpListener/tests/HttpListenerResponseTests.Headers.cs b/src/System.Net.HttpListener/tests/HttpListenerResponseTests.Headers.cs
index 98453b3c94..65a70f6e41 100644
--- a/src/System.Net.HttpListener/tests/HttpListenerResponseTests.Headers.cs
+++ b/src/System.Net.HttpListener/tests/HttpListenerResponseTests.Headers.cs
@@ -9,12 +9,12 @@ using Xunit;
namespace System.Net.Tests
{
+ [ActiveIssue(18784, TargetFrameworkMonikers.Uap)]
public class HttpListenerResponseHeadersTests : HttpListenerResponseTestBase
{
private static string s_longString = new string('a', ushort.MaxValue + 1);
[Fact]
- [ActiveIssue(17462, TargetFrameworkMonikers.Uap)]
public async Task AddHeader_ValidValue_ReplacesHeaderInCollection()
{
HttpListenerResponse response = await GetResponse();
@@ -27,7 +27,6 @@ namespace System.Net.Tests
}
[Fact]
- [ActiveIssue(17462, TargetFrameworkMonikers.Uap)]
public async Task AddHeader_NullOrEmptyName_ThrowsArgumentNullException()
{
HttpListenerResponse response = await GetResponse();
@@ -36,8 +35,7 @@ namespace System.Net.Tests
}
[Fact]
- [ActiveIssue(17462, TargetFrameworkMonikers.Uap)]
- [ActiveIssue(17462, TargetFrameworkMonikers.Netcoreapp)]
+ [ActiveIssue(22057, TargetFrameworkMonikers.Netcoreapp)]
public async Task AddHeader_LongName_ThrowsArgumentOutOfRangeException()
{
HttpListenerResponse response = await GetResponse();
@@ -45,7 +43,6 @@ namespace System.Net.Tests
}
[Fact]
- [ActiveIssue(17462, TargetFrameworkMonikers.Uap)]
public async Task AddHeader_InvalidNameOrValue_ThrowsArgumentException()
{
HttpListenerResponse response = await GetResponse();
@@ -55,7 +52,6 @@ namespace System.Net.Tests
}
[Fact]
- [ActiveIssue(17462, TargetFrameworkMonikers.Uap)]
public async Task AppendHeader_ValidValue_AddsHeaderToCollection()
{
HttpListenerResponse response = await GetResponse();
@@ -68,7 +64,6 @@ namespace System.Net.Tests
}
[Theory]
- [ActiveIssue(17462, TargetFrameworkMonikers.Uap)]
[InlineData(null)]
[InlineData("")]
public async Task AppendHeader_NullOrEmptyName_ThrowsArgumentNullException(string name)
@@ -78,8 +73,7 @@ namespace System.Net.Tests
}
[Fact]
- [ActiveIssue(17462, TargetFrameworkMonikers.Uap)]
- [ActiveIssue(17462, TargetFrameworkMonikers.Netcoreapp)]
+ [ActiveIssue(22057, TargetFrameworkMonikers.Netcoreapp)]
public async Task AppendHeader_LongName_ThrowsArgumentOutOfRangeException()
{
HttpListenerResponse response = await GetResponse();
@@ -87,7 +81,6 @@ namespace System.Net.Tests
}
[Fact]
- [ActiveIssue(17462, TargetFrameworkMonikers.Uap)]
public async Task AppendHeader_InvalidNameOrValue_ThrowsArgumentException()
{
HttpListenerResponse response = await GetResponse();
@@ -97,7 +90,6 @@ namespace System.Net.Tests
}
[Fact]
- [ActiveIssue(17462, TargetFrameworkMonikers.Uap)]
public async Task ContentEncoding_SetCustom_DoesNothing()
{
// Setting HttpListenerResponse.ContentEncoding does nothing - it is never used.
@@ -113,7 +105,6 @@ namespace System.Net.Tests
}
[Fact]
- [ActiveIssue(17462, TargetFrameworkMonikers.Uap)]
public async Task ContentEncoding_SetDisposed_DoesNothing()
{
HttpListenerResponse response = await GetResponse();
@@ -127,7 +118,6 @@ namespace System.Net.Tests
}
[Fact]
- [ActiveIssue(17462, TargetFrameworkMonikers.Uap)]
public async Task ContentEncoding_SetAfterHeadersSent_DoesNothing()
{
using (HttpListenerResponse response = await GetResponse())
@@ -144,7 +134,6 @@ namespace System.Net.Tests
}
[Theory]
- [ActiveIssue(17462, TargetFrameworkMonikers.Uap)]
[InlineData("application/json", 152)]
[InlineData(" applICATion/jSOn ", 152)]
[InlineData("garbage", 143)]
@@ -162,7 +151,6 @@ namespace System.Net.Tests
}
[Theory]
- [ActiveIssue(17462, TargetFrameworkMonikers.Uap)]
[InlineData(null, null)]
[InlineData("", null)]
[InlineData("\r \t \n", "")]
@@ -183,7 +171,6 @@ namespace System.Net.Tests
}
[Fact]
- [ActiveIssue(17462, TargetFrameworkMonikers.Uap)]
public async Task ContentType_SetDisposed_ThrowsObjectDisposedException()
{
HttpListenerResponse response = await GetResponse();
@@ -194,7 +181,6 @@ namespace System.Net.Tests
}
[Fact]
- [ActiveIssue(17462, TargetFrameworkMonikers.Uap)]
public async Task ContentType_SetAfterHeadersSent_DoesNothing()
{
using (HttpListenerResponse response = await GetResponse())
@@ -211,7 +197,6 @@ namespace System.Net.Tests
}
[Fact]
- [ActiveIssue(17462, TargetFrameworkMonikers.Uap)]
public async Task OutputStream_GetDisposed_ThrowsObjectDisposedException()
{
HttpListenerResponse response = await GetResponse();
@@ -221,7 +206,6 @@ namespace System.Net.Tests
}
[Theory]
- [ActiveIssue(17462, TargetFrameworkMonikers.Uap)]
[InlineData("http://microsoft.com", 152)]
[InlineData(" http://MICROSOFT.com ", 152)]
[InlineData("garbage", 139)]
@@ -240,7 +224,6 @@ namespace System.Net.Tests
}
[Theory]
- [ActiveIssue(17462, TargetFrameworkMonikers.Uap)]
[InlineData(null, null)]
[InlineData("", null)]
[InlineData("\r \t \n", "")]
@@ -264,7 +247,6 @@ namespace System.Net.Tests
}
[Fact]
- [ActiveIssue(17462, TargetFrameworkMonikers.Uap)]
public async Task RedirectLocation_SetDisposed_ThrowsObjectDisposedException()
{
HttpListenerResponse response = await GetResponse();
@@ -275,7 +257,6 @@ namespace System.Net.Tests
}
[Fact]
- [ActiveIssue(17462, TargetFrameworkMonikers.Uap)]
public async Task RedirectLocation_SetAfterHeadersSent_DoesNothing()
{
using (HttpListenerResponse response = await GetResponse())
@@ -292,7 +273,6 @@ namespace System.Net.Tests
}
[Theory]
- [ActiveIssue(17462, TargetFrameworkMonikers.Uap)]
[InlineData(100, "HTTP/1.1 100 Continue", 112)]
[InlineData(404, "HTTP/1.1 404 Not Found", 127)]
[InlineData(401, "HTTP/1.1 401 Unauthorized", 130)]
@@ -312,7 +292,6 @@ namespace System.Net.Tests
}
[Fact]
- [ActiveIssue(17462, TargetFrameworkMonikers.Uap)]
public async Task StatusCode_SetDisposed_ThrowsObjectDisposedException()
{
HttpListenerResponse response = await GetResponse();
@@ -323,7 +302,6 @@ namespace System.Net.Tests
}
[Fact]
- [ActiveIssue(17462, TargetFrameworkMonikers.Uap)]
public async Task StatusCode_SetAfterHeadersSent_DoesNothing()
{
using (HttpListenerResponse response = await GetResponse())
@@ -340,7 +318,6 @@ namespace System.Net.Tests
}
[Theory]
- [ActiveIssue(17462, TargetFrameworkMonikers.Uap)]
[InlineData(99)]
[InlineData(1000)]
public async Task StatusCode_SetInvalid_ThrowsProtocolViolationException(int statusCode)
@@ -353,7 +330,6 @@ namespace System.Net.Tests
}
[Theory]
- [ActiveIssue(17462, TargetFrameworkMonikers.Uap)]
[InlineData(100, "Continue")]
[InlineData(101, "Switching Protocols")]
[InlineData(102, "Processing")]
@@ -419,7 +395,6 @@ namespace System.Net.Tests
}
[Theory]
- [ActiveIssue(17462, TargetFrameworkMonikers.Uap)]
[InlineData("", "", 118)]
[InlineData("A !#\t1\u1234", "A !#\t14", 125)] //
[InlineData("StatusDescription", "StatusDescription", 135)]
@@ -437,7 +412,6 @@ namespace System.Net.Tests
}
[Fact]
- [ActiveIssue(17462, TargetFrameworkMonikers.Uap)]
public async Task StatusDescription_SetNull_ThrowsArgumentNullException()
{
using (HttpListenerResponse response = await GetResponse())
@@ -448,7 +422,6 @@ namespace System.Net.Tests
}
[Theory]
- [ActiveIssue(17462, TargetFrameworkMonikers.Uap)]
[InlineData("\0abc")]
[InlineData("\u007F")]
[InlineData("\r")]
@@ -463,7 +436,6 @@ namespace System.Net.Tests
}
[Fact]
- [ActiveIssue(17462, TargetFrameworkMonikers.Uap)]
public async Task StatusDescription_SetDisposed_ThrowsObjectDisposedException()
{
HttpListenerResponse response = await GetResponse();
@@ -474,7 +446,6 @@ namespace System.Net.Tests
}
[Fact]
- [ActiveIssue(17462, TargetFrameworkMonikers.Uap)]
public async Task StatusDescription_SetAfterHeadersSent_DoesNothing()
{
using (HttpListenerResponse response = await GetResponse())
@@ -491,7 +462,6 @@ namespace System.Net.Tests
}
[Theory]
- [ActiveIssue(17462, TargetFrameworkMonikers.Uap)]
[InlineData(true, 120)]
[InlineData(false, 106)]
public async Task SendChunked_GetSet_ReturnsExpected(bool sendChunked, int expectedNumberOfBytes)
@@ -527,7 +497,6 @@ namespace System.Net.Tests
}
[Fact]
- [ActiveIssue(17462, TargetFrameworkMonikers.Uap)]
public async Task SendChunked_SetDisposed_ThrowsObjectDisposedException()
{
HttpListenerResponse response = await GetResponse();
@@ -541,7 +510,6 @@ namespace System.Net.Tests
}
[Fact]
- [ActiveIssue(17462, TargetFrameworkMonikers.Uap)]
public async Task SendChunked_SetAfterHeadersSent_ThrowsInvalidOperationException()
{
using (HttpListenerResponse response = await GetResponse())
@@ -558,7 +526,6 @@ namespace System.Net.Tests
}
[Fact]
- [ActiveIssue(17462, TargetFrameworkMonikers.Uap)]
public async Task SendChunked_SetTrueAndRequestHttpVersionMinorIsZero_ThrowsInvalidOperationException()
{
using (HttpListenerResponse response = await GetResponse("1.0"))
@@ -575,7 +542,6 @@ namespace System.Net.Tests
}
[Theory]
- [ActiveIssue(17462, TargetFrameworkMonikers.Uap)]
[InlineData(true, 120)]
[InlineData(false, 139)]
public async Task KeepAlive_GetSet_ReturnsExpected(bool keepAlive, int expectedNumberOfBytes)
@@ -613,7 +579,6 @@ namespace System.Net.Tests
}
[Fact]
- [ActiveIssue(17462, TargetFrameworkMonikers.Uap)]
public async Task KeepAlive_SetDisposed_ThrowsObjectDisposedException()
{
HttpListenerResponse response = await GetResponse();
@@ -630,7 +595,6 @@ namespace System.Net.Tests
}
[Fact]
- [ActiveIssue(17462, TargetFrameworkMonikers.Uap)]
public async Task KeepAlive_SetAfterHeadersSent_DoesNothing()
{
using (HttpListenerResponse response = await GetResponse())
@@ -647,7 +611,6 @@ namespace System.Net.Tests
}
[Fact]
- [ActiveIssue(17462, TargetFrameworkMonikers.Uap)]
public async Task KeepAlive_NoBoundaryAndRequestHttpRequestVersionMinorIsZero_SetsToFalseWhenSendingHeaders()
{
using (HttpListenerResponse response = await GetResponse("1.0"))
@@ -663,7 +626,6 @@ namespace System.Net.Tests
}
[Fact]
- [ActiveIssue(17462, TargetFrameworkMonikers.Uap)]
public async Task KeepAlive_ContentLengthBoundaryAndRequestHttpVersionMinorIsZero_DoesNotChangeWhenSendingHeaders()
{
using (HttpListenerResponse response = await GetResponse("1.0"))
@@ -682,7 +644,6 @@ namespace System.Net.Tests
}
[Theory]
- [ActiveIssue(17462, TargetFrameworkMonikers.Uap)]
[InlineData(0, 106)]
[InlineData(10, 117)]
public async Task ContentLength64_GetSet_ReturnsExpected(int contentLength64, int expectedNumberOfBytes)
@@ -713,7 +674,6 @@ namespace System.Net.Tests
}
[Theory]
- [ActiveIssue(17462, TargetFrameworkMonikers.Uap)]
[InlineData(100, 0, 112)]
[InlineData(101, 0, 123)]
[InlineData(204, 0, 114)]
@@ -742,7 +702,6 @@ namespace System.Net.Tests
}
[Fact]
- [ActiveIssue(17462, TargetFrameworkMonikers.Uap)]
public async Task ContentLength64_SetDisposed_ThrowsObjectDisposedException()
{
HttpListenerResponse response = await GetResponse();
@@ -757,7 +716,6 @@ namespace System.Net.Tests
}
[Fact]
- [ActiveIssue(17462, TargetFrameworkMonikers.Uap)]
public async Task ContentLength64_SetAfterHeadersSent_ThrowsInvalidOperationException()
{
using (HttpListenerResponse response = await GetResponse())
@@ -774,7 +732,6 @@ namespace System.Net.Tests
}
[Fact]
- [ActiveIssue(17462, TargetFrameworkMonikers.Uap)]
public async Task ContentLength64_SetNegative_ThrowsArgumentOutOfRangeException()
{
using (HttpListenerResponse response = await GetResponse())
@@ -799,7 +756,6 @@ namespace System.Net.Tests
}
[Theory]
- [ActiveIssue(17462, TargetFrameworkMonikers.Uap)]
[MemberData(nameof(ProtocolVersion_Set_TestData))]
public async Task ProtocolVersion_SetValid_ReturnsExpected(Version version)
{
@@ -816,7 +772,6 @@ namespace System.Net.Tests
}
[Fact]
- [ActiveIssue(17462, TargetFrameworkMonikers.Uap)]
public async Task ProtocolVersion_SetNull_ThrowsArgumentNullException()
{
using (HttpListenerResponse response = await GetResponse())
@@ -827,7 +782,6 @@ namespace System.Net.Tests
}
[Theory]
- [ActiveIssue(17462, TargetFrameworkMonikers.Uap)]
[InlineData(0, 0)]
[InlineData(1, 2)]
[InlineData(2, 0)]
@@ -841,7 +795,6 @@ namespace System.Net.Tests
}
[Fact]
- [ActiveIssue(17462, TargetFrameworkMonikers.Uap)]
public async Task Headers_GetSet_ReturnsExpected()
{
using (HttpListenerResponse response = await GetResponse())
@@ -865,7 +818,6 @@ namespace System.Net.Tests
}
[Fact]
- [ActiveIssue(17462, TargetFrameworkMonikers.Uap)]
public async Task Headers_SetCollectionWithRequestHeaders_Works()
{
HttpListenerResponse response = await GetResponse();
@@ -880,9 +832,8 @@ namespace System.Net.Tests
}
[Theory]
- [ActiveIssue(17462, TargetFrameworkMonikers.Uap)]
[InlineData("Transfer-Encoding")]
- [ActiveIssue(17462, TargetFrameworkMonikers.Netcoreapp)]
+ [ActiveIssue(22057, TargetFrameworkMonikers.Netcoreapp)]
public async Task Headers_SetRestricted_ThrowsArgumentException(string name)
{
HttpListenerResponse response = await GetResponse();
@@ -891,7 +842,6 @@ namespace System.Net.Tests
}
[Fact]
- [ActiveIssue(17462, TargetFrameworkMonikers.Uap)]
public async Task Headers_SetNull_ThrowsNullReferenceException()
{
using (HttpListenerResponse response = await GetResponse())
@@ -904,8 +854,7 @@ namespace System.Net.Tests
}
[Fact]
- [ActiveIssue(17462, TargetFrameworkMonikers.Uap)]
- [ActiveIssue(17462, TargetFrameworkMonikers.Netcoreapp)]
+ [ActiveIssue(22057, TargetFrameworkMonikers.Netcoreapp)]
public async Task Headers_SetLongName_ThrowsArgumentOutOfRangeException()
{
HttpListenerResponse response = await GetResponse();
@@ -917,8 +866,7 @@ namespace System.Net.Tests
}
[Fact]
- [ActiveIssue(17462, TargetFrameworkMonikers.Uap)]
- [ActiveIssue(17462, TargetFrameworkMonikers.Netcoreapp)]
+ [ActiveIssue(22057, TargetFrameworkMonikers.Netcoreapp)]
public async Task Headers_SetRequestHeader_ThrowsInvalidOperationException()
{
HttpListenerResponse response = await GetResponse();
diff --git a/src/System.Net.HttpListener/tests/HttpListenerResponseTests.cs b/src/System.Net.HttpListener/tests/HttpListenerResponseTests.cs
index 8df8a9d4be..d9ead7c0bb 100644
--- a/src/System.Net.HttpListener/tests/HttpListenerResponseTests.cs
+++ b/src/System.Net.HttpListener/tests/HttpListenerResponseTests.cs
@@ -60,7 +60,6 @@ namespace System.Net.Tests
public class HttpListenerResponseTests : HttpListenerResponseTestBase
{
[Fact]
- [ActiveIssue(17462, TargetFrameworkMonikers.Uap)]
public async Task CopyFrom_AllValues_ReturnsClone()
{
using (HttpListenerResponse response1 = await GetResponse())
@@ -98,7 +97,6 @@ namespace System.Net.Tests
}
[Fact]
- [ActiveIssue(17462, TargetFrameworkMonikers.Uap)]
public async Task CopyFrom_NullTemplateResponse_ThrowsNullReferenceException()
{
using (HttpListenerResponse response = await GetResponse())
@@ -108,7 +106,6 @@ namespace System.Net.Tests
}
[Theory]
- [ActiveIssue(17462, TargetFrameworkMonikers.Uap)]
[InlineData(null, 123)]
[InlineData("", 123)]
[InlineData(" \r \t \n", 123)]
@@ -141,7 +138,6 @@ namespace System.Net.Tests
}
[Fact]
- [ActiveIssue(17462, TargetFrameworkMonikers.Uap)]
public async Task Redirect_Disposed_ThrowsObjectDisposedException()
{
HttpListenerResponse response = await GetResponse();
@@ -157,7 +153,6 @@ namespace System.Net.Tests
// The managed implementation should also dispose the OutputStream after calling Abort.
[ConditionalFact(nameof(Helpers) + "." + nameof(Helpers.IsWindowsImplementation))] // [ActiveIssue(19975, TestPlatforms.AnyUnix)]
- [ActiveIssue(17462, TargetFrameworkMonikers.Uap)]
public async Task Abort_Invoke_ForciblyTerminatesConnection()
{
Client.Send(Factory.GetContent("1.1", "POST", null, "Give me a context, please", null, headerOnly: false));
@@ -193,7 +188,6 @@ namespace System.Net.Tests
}
[Fact]
- [ActiveIssue(17462, TargetFrameworkMonikers.Uap)]
public async Task Close_Invoke_ClosesConnection()
{
using (HttpListenerResponse response = await GetResponse())
@@ -219,7 +213,6 @@ namespace System.Net.Tests
}
[Fact]
- [ActiveIssue(17462, TargetFrameworkMonikers.Uap)]
public async Task Dispose_Invoke_ClosesConnection()
{
using (HttpListenerResponse response = await GetResponse())
@@ -245,7 +238,6 @@ namespace System.Net.Tests
}
[Theory]
- [ActiveIssue(17462, TargetFrameworkMonikers.Uap)]
[InlineData(true)]
[InlineData(false)]
public async Task CloseResponseEntity_EmptyResponseEntity_Success(bool willBlock)
@@ -272,7 +264,6 @@ namespace System.Net.Tests
}
[ConditionalTheory(nameof(Helpers) + "." + nameof(Helpers.IsWindowsImplementation))] // [ActiveIssue(20201, TestPlatforms.AnyUnix)]
- [ActiveIssue(17462, TargetFrameworkMonikers.Uap)]
[InlineData(true)]
[InlineData(false)]
public async Task CloseResponseEntity_AllContentLengthAlreadySent_DoesNotSendEntity(bool willBlock)
@@ -292,7 +283,6 @@ namespace System.Net.Tests
}
[Theory]
- [ActiveIssue(17462, TargetFrameworkMonikers.Uap)]
[InlineData(true)]
[InlineData(false)]
[OuterLoop("Investigating reliability in CI.")]
@@ -313,7 +303,6 @@ namespace System.Net.Tests
}
[Theory]
- [ActiveIssue(17462, TargetFrameworkMonikers.Uap)]
[InlineData(true)]
[InlineData(false)]
[OuterLoop("Investigating reliability in CI.")]
@@ -332,7 +321,6 @@ namespace System.Net.Tests
}
[Theory]
- [ActiveIssue(17462, TargetFrameworkMonikers.Uap)]
[InlineData(true)]
[InlineData(false)]
[OuterLoop("Investigating reliability in CI.")]
@@ -352,7 +340,6 @@ namespace System.Net.Tests
}
[Fact]
- [ActiveIssue(17462, TargetFrameworkMonikers.Uap)]
public async Task CloseResponseEntity_AlreadyDisposed_ThrowsObjectDisposedException()
{
HttpListenerResponse response = await GetResponse();
@@ -362,7 +349,6 @@ namespace System.Net.Tests
}
[Fact]
- [ActiveIssue(17462, TargetFrameworkMonikers.Uap)]
public async Task CloseResponseEntity_NullResponseEntity_ThrowsArgumentNullException()
{
using (HttpListenerResponse response = await GetResponse())
@@ -372,7 +358,6 @@ namespace System.Net.Tests
}
[ConditionalTheory(nameof(Helpers) + "." + nameof(Helpers.IsWindowsImplementation))] // [ActiveIssue(20201, TestPlatforms.AnyUnix)]
- [ActiveIssue(17462, TargetFrameworkMonikers.Uap)]
[InlineData(true)]
[InlineData(false)]
public async Task CloseResponseEntity_SendMoreThanContentLength_ThrowsInvalidOperationException(bool willBlock)
@@ -418,7 +403,6 @@ namespace System.Net.Tests
}
[Theory]
- [ActiveIssue(17462, TargetFrameworkMonikers.Uap)]
[InlineData(true)]
[InlineData(false)]
public async Task CloseResponseEntity_SendToClosedConnection_DoesNotThrow(bool willBlock)
diff --git a/src/System.Net.HttpListener/tests/HttpListenerTests.cs b/src/System.Net.HttpListener/tests/HttpListenerTests.cs
index a934443d35..8301d844f4 100644
--- a/src/System.Net.HttpListener/tests/HttpListenerTests.cs
+++ b/src/System.Net.HttpListener/tests/HttpListenerTests.cs
@@ -14,7 +14,6 @@ namespace System.Net.Tests
public class HttpListenerTests
{
[Fact]
- [ActiveIssue(17462, TargetFrameworkMonikers.Uap)]
public void IgnoreWriteExceptions_SetDisposed_ThrowsObjectDisposedException()
{
var listener = new HttpListener();
@@ -24,7 +23,6 @@ namespace System.Net.Tests
}
[Fact]
- [ActiveIssue(17462, TargetFrameworkMonikers.Uap)]
public void Stop_Disposed_ThrowsObjectDisposedException()
{
var listener = new HttpListener();
@@ -34,7 +32,6 @@ namespace System.Net.Tests
}
[Fact]
- [ActiveIssue(17462, TargetFrameworkMonikers.Uap)]
public void IsListening_NotStarted_ReturnsFalse()
{
using (var listener = new HttpListener())
@@ -44,7 +41,6 @@ namespace System.Net.Tests
}
[Fact]
- [ActiveIssue(17462, TargetFrameworkMonikers.Uap)]
public void IsListening_Disposed_ReturnsFalse()
{
var listener = new HttpListener();
@@ -56,7 +52,6 @@ namespace System.Net.Tests
}
[Fact]
- [ActiveIssue(17462, TargetFrameworkMonikers.Uap)]
public void IsListening_Aborted_ReturnsFalse()
{
var listener = new HttpListener();
@@ -68,7 +63,6 @@ namespace System.Net.Tests
}
[Fact]
- [ActiveIssue(17462, TargetFrameworkMonikers.Uap)]
public void IsListening_Stopped_ReturnsFalse()
{
var listener = new HttpListener();
@@ -80,7 +74,6 @@ namespace System.Net.Tests
}
[Fact]
- [ActiveIssue(17462, TargetFrameworkMonikers.Uap)]
public void Start_Disposed_ThrowsObjectDisposedException()
{
var listener = new HttpListener();
@@ -90,7 +83,6 @@ namespace System.Net.Tests
}
[Fact]
- [ActiveIssue(17462, TargetFrameworkMonikers.Uap)]
public void GetContext_Disposed_ThrowsObjectDisposedException()
{
var listener = new HttpListener();
@@ -101,7 +93,6 @@ namespace System.Net.Tests
}
[Fact]
- [ActiveIssue(17462, TargetFrameworkMonikers.Uap)]
public void GetContext_NotStarted_ThrowsInvalidOperationException()
{
using (var listener = new HttpListener())
@@ -112,7 +103,6 @@ namespace System.Net.Tests
}
[Fact]
- [ActiveIssue(17462, TargetFrameworkMonikers.Uap)]
public void GetContext_NoPrefixes_ThrowsInvalidOperationException()
{
using (var listener = new HttpListener())
@@ -124,7 +114,6 @@ namespace System.Net.Tests
}
[Fact]
- [ActiveIssue(17462, TargetFrameworkMonikers.Uap)]
public void EndGetContext_NullAsyncResult_ThrowsArgumentNullException()
{
using (var listener = new HttpListener())
@@ -134,7 +123,6 @@ namespace System.Net.Tests
}
[Fact]
- [ActiveIssue(17462, TargetFrameworkMonikers.Uap)]
public void EndGetContext_InvalidAsyncResult_ThrowsArgumentException()
{
using (var listener1 = new HttpListener())
@@ -150,7 +138,6 @@ namespace System.Net.Tests
}
[Fact]
- [ActiveIssue(17462, TargetFrameworkMonikers.Uap)]
public void EndGetContext_AlreadyCalled_ThrowsInvalidOperationException()
{
using (var listenerFactory = new HttpListenerFactory())
diff --git a/src/System.Net.HttpListener/tests/HttpListenerTimeoutManagerTests.cs b/src/System.Net.HttpListener/tests/HttpListenerTimeoutManagerTests.cs
index 00dd5c2377..5d2d20a4ed 100644
--- a/src/System.Net.HttpListener/tests/HttpListenerTimeoutManagerTests.cs
+++ b/src/System.Net.HttpListener/tests/HttpListenerTimeoutManagerTests.cs
@@ -11,7 +11,6 @@ namespace System.Net.Tests
public class HttpListenerTimeoutManagerTests
{
[Theory]
- [ActiveIssue(17462, TargetFrameworkMonikers.Uap)]
[InlineData(-1)]
[InlineData((long)uint.MaxValue + 1)]
public void MinSendBytesPerSecond_NotUInt_ThrowsArgumentOutOfRangeException(long value)
@@ -23,7 +22,6 @@ namespace System.Net.Tests
}
[Theory]
- [ActiveIssue(17462, TargetFrameworkMonikers.Uap)]
[InlineData(-1)]
[InlineData((uint)ushort.MaxValue + 1)]
public void TimeoutValue_NotUShort_ThrowsArgumentOutOfRangeException(long totalSeconds)
@@ -40,7 +38,6 @@ namespace System.Net.Tests
}
[Fact]
- [ActiveIssue(17462, TargetFrameworkMonikers.Uap)]
public void Get_Disposed_ThrowsObjectDisposedException()
{
var listener = new HttpListener();
@@ -127,7 +124,6 @@ namespace System.Net.Tests
public void Dispose() => _listener.Close();
[ConditionalFact(nameof(Helpers) + "." + nameof(Helpers.IsWindowsImplementation))]
- [ActiveIssue(17462, TargetFrameworkMonikers.Uap)]
public void TimeoutManager_AccessNoStart_Success()
{
// Access the TimeoutManager without calling Start and make sure it is initialized.
@@ -139,7 +135,6 @@ namespace System.Net.Tests
}
[ConditionalFact(nameof(Helpers) + "." + nameof(Helpers.IsWindowsImplementation))]
- [ActiveIssue(17462, TargetFrameworkMonikers.Uap)]
public void TimeoutManager_AccessAfterStart_Success()
{
// Access the TimeoutManager after calling Start and make sure it is initialized.
@@ -152,7 +147,6 @@ namespace System.Net.Tests
}
[ConditionalFact(nameof(Helpers) + "." + nameof(Helpers.IsWindowsImplementation))]
- [ActiveIssue(17462, TargetFrameworkMonikers.Uap)]
public void TimeoutManager_AccessAfterClose_GetObjectDisposedException()
{
// Access the TimeoutManager after calling Close and make sure it is not accessible.
@@ -162,7 +156,6 @@ namespace System.Net.Tests
}
[ConditionalFact(nameof(Helpers) + "." + nameof(Helpers.IsWindowsImplementation))]
- [ActiveIssue(17462, TargetFrameworkMonikers.Uap)]
public void TimeoutManager_AccessBeforeAndAfterClose_GetObjectDisposedException()
{
// Access the TimeoutManager after calling Close and make sure it is not accessible.
@@ -174,7 +167,6 @@ namespace System.Net.Tests
}
[ConditionalFact(nameof(Helpers) + "." + nameof(Helpers.IsWindowsImplementation))]
- [ActiveIssue(17462, TargetFrameworkMonikers.Uap)]
public void TimeoutManager_AccessAfterStop_Success()
{
// Access the TimeoutManager after calling Stop and make sure it is accessible.
@@ -189,7 +181,6 @@ namespace System.Net.Tests
}
[ConditionalFact(nameof(Helpers) + "." + nameof(Helpers.IsWindowsImplementation))]
- [ActiveIssue(17462, TargetFrameworkMonikers.Uap)]
public void DrainEntityBody_SetTimeoutNoStart_GetReturnsNewValue()
{
// Set the DrainEntityBody timeout without calling Start and make sure that native layer return new value.
@@ -200,7 +191,6 @@ namespace System.Net.Tests
}
[ConditionalFact(nameof(Helpers) + "." + nameof(Helpers.IsWindowsImplementation))]
- [ActiveIssue(17462, TargetFrameworkMonikers.Uap)]
public void DrainEntityBody_SetTimeoutAfterStart_GetReturnsNewValue()
{
// Set the DrainEntityBody timeout after calling Start and make sure that native layer return new value.
@@ -212,7 +202,6 @@ namespace System.Net.Tests
}
[ConditionalFact(nameof(Helpers) + "." + nameof(Helpers.IsWindowsImplementation))]
- [ActiveIssue(17462, TargetFrameworkMonikers.Uap)]
public void EntityBody_SetTimeoutNoStart_GetReturnsNewValue()
{
// Set the DrainEntityBody timeout without calling Start and make sure that native layer return new value.
@@ -223,7 +212,6 @@ namespace System.Net.Tests
}
[ConditionalFact(nameof(Helpers) + "." + nameof(Helpers.IsWindowsImplementation))]
- [ActiveIssue(17462, TargetFrameworkMonikers.Uap)]
public void EntityBody_SetTimeoutAfterStart_GetReturnsNewValue()
{
// Set the EntityBody timeout after calling Start and make sure that native layer return new value.
@@ -235,7 +223,6 @@ namespace System.Net.Tests
}
[ConditionalFact(nameof(Helpers) + "." + nameof(Helpers.IsWindowsImplementation))]
- [ActiveIssue(17462, TargetFrameworkMonikers.Uap)]
public void HeaderWait_SetTimeoutNoStart_GetReturnsNewValue()
{
// Set the HeaderWait timeout without calling Start and make sure that native layer return new value.
@@ -246,7 +233,6 @@ namespace System.Net.Tests
}
[ConditionalFact(nameof(Helpers) + "." + nameof(Helpers.IsWindowsImplementation))]
- [ActiveIssue(17462, TargetFrameworkMonikers.Uap)]
public void HeaderWait_SetTimeoutAfterStart_GetReturnsNewValue()
{
// Set the HeaderWait timeout after calling Start and make sure that native layer return new value.
@@ -258,7 +244,6 @@ namespace System.Net.Tests
}
[ConditionalFact(nameof(Helpers) + "." + nameof(Helpers.IsWindowsImplementation))]
- [ActiveIssue(17462, TargetFrameworkMonikers.Uap)]
public void RequestQueue_SetTimeoutNoStart_GetReturnsNewValue()
{
// Set the DrainEntityBody timeout without calling Start and make sure that native layer return new value.
@@ -269,7 +254,6 @@ namespace System.Net.Tests
}
[ConditionalFact(nameof(Helpers) + "." + nameof(Helpers.IsWindowsImplementation))]
- [ActiveIssue(17462, TargetFrameworkMonikers.Uap)]
public void RequestQueue_SetTimeoutAfterStart_GetReturnsNewValue()
{
// Set the RequestQueue timeout after calling Start and make sure that native layer return new value.
@@ -281,7 +265,6 @@ namespace System.Net.Tests
}
[ConditionalFact(nameof(Helpers) + "." + nameof(Helpers.IsWindowsImplementation))]
- [ActiveIssue(17462, TargetFrameworkMonikers.Uap)]
public void IdleConnection_SetTimeoutNoStart_GetReturnsNewValue()
{
// Set the IdleConnection timeout without calling Start and make sure that native layer return new value.
@@ -292,7 +275,6 @@ namespace System.Net.Tests
}
[ConditionalFact(nameof(Helpers) + "." + nameof(Helpers.IsWindowsImplementation))]
- [ActiveIssue(17462, TargetFrameworkMonikers.Uap)]
public void IdleConnection_SetTimeoutAfterStart_GetReturnsNewValue()
{
// Set the IdleConnection timeout after calling Start and make sure that native layer return new value.
@@ -304,7 +286,6 @@ namespace System.Net.Tests
}
[ConditionalFact(nameof(Helpers) + "." + nameof(Helpers.IsWindowsImplementation))]
- [ActiveIssue(17462, TargetFrameworkMonikers.Uap)]
public void MinSendBytesPerSecond_SetNoStart_GetReturnsNewValue()
{
// Set the MinSendBytesPerSecond timeout without calling Start and make sure that native layer
@@ -316,7 +297,6 @@ namespace System.Net.Tests
}
[ConditionalFact(nameof(Helpers) + "." + nameof(Helpers.IsWindowsImplementation))]
- [ActiveIssue(17462, TargetFrameworkMonikers.Uap)]
public void MinSendBytesPerSecond_SetAfterStart_GetReturnsNewValue()
{
// Set the MinSendBytesPerSecond timeout after calling Start and make sure that native
@@ -329,7 +309,6 @@ namespace System.Net.Tests
}
[ConditionalFact(nameof(Helpers) + "." + nameof(Helpers.IsWindowsImplementation))]
- [ActiveIssue(17462, TargetFrameworkMonikers.Uap)]
public void MinSendBytesPerSecond_SetAfterClose_GetObjectDisposedException()
{
// Set the MinSendBytesPerSecond timeout after calling Close and make sure that we get the exception.
@@ -339,7 +318,6 @@ namespace System.Net.Tests
}
[ConditionalFact(nameof(Helpers) + "." + nameof(Helpers.IsWindowsImplementation))]
- [ActiveIssue(17462, TargetFrameworkMonikers.Uap)]
public void MinSendBytesPerSecond_SetAfterStop_GetReturnsNewValue()
{
// Set the MinSendBytesPerSecond timeout after calling Stop and make sure that native
@@ -401,7 +379,6 @@ namespace System.Net.Tests
[ConditionalTheory(nameof(Helpers) + "." + nameof(Helpers.IsWindowsImplementation))]
- [ActiveIssue(17462, TargetFrameworkMonikers.Uap)]
[InlineData(1.3, 1)]
[InlineData(1.6, 2)]
public void TimeoutValue_Double_Truncates(double seconds, int expected)
@@ -418,7 +395,6 @@ namespace System.Net.Tests
public class HttpListenerTimeoutManagerUnixTests
{
[ConditionalFact(nameof(Helpers) + "." + nameof(Helpers.IsManagedImplementation))] // [PlatformSpecific(TestPlatforms.AnyUnix)] // managed implementation doesn't support all members
- [ActiveIssue(17462, TargetFrameworkMonikers.Uap)]
public void Properties_DefaultValues()
{
using (var listener = new HttpListener())
@@ -435,7 +411,6 @@ namespace System.Net.Tests
}
[ConditionalFact(nameof(Helpers) + "." + nameof(Helpers.IsManagedImplementation))] // [PlatformSpecific(TestPlatforms.AnyUnix)] // managed implementation doesn't support all members
- [ActiveIssue(17462, TargetFrameworkMonikers.Uap)]
public void UnsupportedProperties_Throw()
{
using (var listener = new HttpListener())
@@ -449,7 +424,6 @@ namespace System.Net.Tests
}
[ConditionalFact(nameof(Helpers) + "." + nameof(Helpers.IsManagedImplementation))] // [PlatformSpecific(TestPlatforms.AnyUnix)] // managed implementation doesn't support all members
- [ActiveIssue(17462, TargetFrameworkMonikers.Uap)]
public void DrainEntityBody_Roundtrips()
{
using (var listener = new HttpListener())
@@ -464,7 +438,6 @@ namespace System.Net.Tests
}
[ConditionalFact(nameof(Helpers) + "." + nameof(Helpers.IsManagedImplementation))] // [PlatformSpecific(TestPlatforms.AnyUnix)] // managed implementation doesn't support all members
- [ActiveIssue(17462, TargetFrameworkMonikers.Uap)]
public void IdleConnection_Roundtrips()
{
using (var listener = new HttpListener())
diff --git a/src/System.Net.HttpListener/tests/HttpListenerWebSocketTests.cs b/src/System.Net.HttpListener/tests/HttpListenerWebSocketTests.cs
index 9ea4d936cb..4e061dd255 100644
--- a/src/System.Net.HttpListener/tests/HttpListenerWebSocketTests.cs
+++ b/src/System.Net.HttpListener/tests/HttpListenerWebSocketTests.cs
@@ -13,8 +13,9 @@ namespace System.Net.Tests
{
public class HttpListenerWebSocketTests : IDisposable
{
+ public static bool PartialMessagesSupported => PlatformDetection.ClientWebSocketPartialMessagesSupported;
public static bool IsNotWindows7 { get; } = !PlatformDetection.IsWindows7;
- public static bool IsNotWindows7AndIsWindowsImplementation { get; } = IsNotWindows7 && Helpers.IsWindowsImplementation;
+ public static bool IsNotWindows7AndIsWindowsImplementation => IsNotWindows7 && Helpers.IsWindowsImplementation;
private HttpListenerFactory Factory { get; }
private HttpListener Listener { get; }
@@ -34,8 +35,7 @@ namespace System.Net.Tests
Client.Dispose();
}
- [ConditionalTheory(nameof(IsNotWindows7))]
- [ActiveIssue(17462, TargetFrameworkMonikers.Uap)]
+ [ConditionalTheory(nameof(PartialMessagesSupported), nameof(IsNotWindows7))]
[InlineData(WebSocketMessageType.Text, false)]
[InlineData(WebSocketMessageType.Binary, false)]
[InlineData(WebSocketMessageType.Text, true)]
@@ -61,26 +61,23 @@ namespace System.Net.Tests
}
[ConditionalFact(nameof(IsNotWindows7))]
- [ActiveIssue(17462, TargetFrameworkMonikers.Uap)]
public async Task SendAsync_NoInnerBuffer_ThrowsArgumentNullException()
{
HttpListenerWebSocketContext context = await GetWebSocketContext();
- await Assert.ThrowsAsync<ArgumentNullException>("buffer.Array", () => context.WebSocket.SendAsync(new ArraySegment<byte>(), WebSocketMessageType.Text, false, new CancellationToken()));
+ await AssertExtensions.ThrowsAsync<ArgumentNullException>("buffer.Array", () => context.WebSocket.SendAsync(new ArraySegment<byte>(), WebSocketMessageType.Text, false, new CancellationToken()));
}
[ConditionalTheory(nameof(IsNotWindows7))]
- [ActiveIssue(17462, TargetFrameworkMonikers.Uap)]
[InlineData(WebSocketMessageType.Close)]
[InlineData(WebSocketMessageType.Text - 1)]
[InlineData(WebSocketMessageType.Binary + 1)]
public async Task SendAsync_InvalidMessageType_ThrowsArgumentNullException(WebSocketMessageType messageType)
{
HttpListenerWebSocketContext context = await GetWebSocketContext();
- await Assert.ThrowsAsync<ArgumentException>("messageType", () => context.WebSocket.SendAsync(new ArraySegment<byte>(), messageType, false, new CancellationToken()));
+ await AssertExtensions.ThrowsAsync<ArgumentException>("messageType", () => context.WebSocket.SendAsync(new ArraySegment<byte>(), messageType, false, new CancellationToken()));
}
[ConditionalFact(nameof(IsNotWindows7AndIsWindowsImplementation))] // [ActiveIssue(20395, TestPlatforms.AnyUnix)]
- [ActiveIssue(17462, TargetFrameworkMonikers.Uap)]
public async Task SendAsync_Disposed_ThrowsObjectDisposedException()
{
HttpListenerWebSocketContext context = await GetWebSocketContext();
@@ -89,8 +86,8 @@ namespace System.Net.Tests
await Assert.ThrowsAsync<ObjectDisposedException>(() => context.WebSocket.SendAsync(new ArraySegment<byte>(new byte[10]), WebSocketMessageType.Text, false, new CancellationToken()));
}
+ [SkipOnTargetFramework(TargetFrameworkMonikers.Uap, "WebSocket partial send is not supported on UAP. (#22053)")]
[ConditionalTheory(nameof(IsNotWindows7))]
- [ActiveIssue(17462, TargetFrameworkMonikers.Uap)]
[InlineData(WebSocketMessageType.Text, false)]
[InlineData(WebSocketMessageType.Binary, false)]
[InlineData(WebSocketMessageType.Text, true)]
@@ -116,17 +113,15 @@ namespace System.Net.Tests
}
[ConditionalFact(nameof(IsNotWindows7))]
- [ActiveIssue(17462, TargetFrameworkMonikers.Uap)]
public async Task ReceiveAsync_NoInnerBuffer_ThrowsArgumentNullException()
{
HttpListenerWebSocketContext context = await GetWebSocketContext();
await ClientConnectTask;
- await Assert.ThrowsAsync<ArgumentNullException>("buffer.Array", () => context.WebSocket.ReceiveAsync(new ArraySegment<byte>(), new CancellationToken()));
+ await AssertExtensions.ThrowsAsync<ArgumentNullException>("buffer.Array", () => context.WebSocket.ReceiveAsync(new ArraySegment<byte>(), new CancellationToken()));
}
[ConditionalFact(nameof(IsNotWindows7AndIsWindowsImplementation))] // [ActiveIssue(20395, TestPlatforms.AnyUnix)]
- [ActiveIssue(17462, TargetFrameworkMonikers.Uap)]
public async Task ReceiveAsync_Disposed_ThrowsObjectDisposedException()
{
HttpListenerWebSocketContext context = await GetWebSocketContext();
@@ -145,7 +140,6 @@ namespace System.Net.Tests
}
[ConditionalTheory(nameof(IsNotWindows7AndIsWindowsImplementation))] // [ActiveIssue(20396, TestPlatforms.AnyUnix)]
- [ActiveIssue(17462, TargetFrameworkMonikers.Uap)]
[MemberData(nameof(CloseStatus_Valid_TestData))]
public async Task CloseOutputAsync_HandshakeStartedFromClient_Success(WebSocketCloseStatus status, string statusDescription, WebSocketCloseStatus expectedCloseStatus)
{
@@ -209,7 +203,6 @@ namespace System.Net.Tests
}
[ConditionalTheory(nameof(IsNotWindows7AndIsWindowsImplementation))] // [ActiveIssue(20396, TestPlatforms.AnyUnix)]
- [ActiveIssue(17462, TargetFrameworkMonikers.Uap)]
[MemberData(nameof(CloseStatus_Valid_TestData))]
public async Task CloseAsync_HandshakeStartedFromClient_Success(WebSocketCloseStatus status, string statusDescription, WebSocketCloseStatus expectedCloseStatus)
{
@@ -283,7 +276,6 @@ namespace System.Net.Tests
}
[ConditionalTheory(nameof(IsNotWindows7))]
- [ActiveIssue(17462, TargetFrameworkMonikers.Uap)]
[MemberData(nameof(CloseStatus_Invalid_TestData))]
public async Task CloseAsync_InvalidCloseStatus_ThrowsArgumentException(WebSocketCloseStatus status, string statusDescription, string paramName)
{
@@ -294,7 +286,6 @@ namespace System.Net.Tests
}
[ConditionalFact(nameof(IsNotWindows7AndIsWindowsImplementation))] // [ActiveIssue(20394, TestPlatforms.AnyUnix)]
- [ActiveIssue(17462, TargetFrameworkMonikers.Uap)]
public async Task CloseAsync_AfterDisposed_Nop()
{
HttpListenerWebSocketContext context = await GetWebSocketContext();
@@ -305,7 +296,6 @@ namespace System.Net.Tests
}
[ConditionalFact(nameof(IsNotWindows7AndIsWindowsImplementation))] // [ActiveIssue(20394, TestPlatforms.AnyUnix)]
- [ActiveIssue(17462, TargetFrameworkMonikers.Uap)]
public async Task CloseAsync_AfterAborted_Nop()
{
HttpListenerWebSocketContext context = await GetWebSocketContext();
@@ -316,7 +306,6 @@ namespace System.Net.Tests
}
[ConditionalFact(nameof(IsNotWindows7AndIsWindowsImplementation))] // [ActiveIssue(20397, TestPlatforms.AnyUnix)]
- [ActiveIssue(17462, TargetFrameworkMonikers.Uap)]
public async Task Dispose_CallAfterDisposed_Nop()
{
HttpListenerWebSocketContext context = await GetWebSocketContext();
@@ -331,7 +320,6 @@ namespace System.Net.Tests
}
[ConditionalFact(nameof(IsNotWindows7))]
- [ActiveIssue(17462, TargetFrameworkMonikers.Uap)]
public async Task Abort_CallAfterAborted_Nop()
{
HttpListenerWebSocketContext context = await GetWebSocketContext();
diff --git a/src/System.Net.HttpListener/tests/HttpRequestStreamTests.cs b/src/System.Net.HttpListener/tests/HttpRequestStreamTests.cs
index 403c56c789..e8d781a0c6 100644
--- a/src/System.Net.HttpListener/tests/HttpRequestStreamTests.cs
+++ b/src/System.Net.HttpListener/tests/HttpRequestStreamTests.cs
@@ -33,7 +33,6 @@ namespace System.Net.Tests
}
[Theory]
- [ActiveIssue(17462, TargetFrameworkMonikers.Uap)]
[InlineData(true, "")]
[InlineData(false, "")]
[InlineData(true, "Non-Empty")]
@@ -77,8 +76,8 @@ namespace System.Net.Tests
}
}
+ [ActiveIssue(22110, TargetFrameworkMonikers.UapAot)]
[Theory]
- [ActiveIssue(17462, TargetFrameworkMonikers.Uap)]
[InlineData(true, "")]
[InlineData(false, "")]
[InlineData(true, "Non-Empty")]
@@ -125,7 +124,6 @@ namespace System.Net.Tests
}
[Theory]
- [ActiveIssue(17462, TargetFrameworkMonikers.Uap)]
[InlineData(true, "")]
[InlineData(false, "")]
[InlineData(true, "Non-Empty")]
@@ -170,7 +168,6 @@ namespace System.Net.Tests
}
[Theory]
- [ActiveIssue(17462, TargetFrameworkMonikers.Uap)]
[InlineData(true)]
[InlineData(false)]
public async Task Read_LargeLengthAsynchronous_Success(bool transferEncodingChunked)
@@ -210,7 +207,6 @@ namespace System.Net.Tests
}
[Theory]
- [ActiveIssue(17462, TargetFrameworkMonikers.Uap)]
[InlineData(true)]
[InlineData(false)]
public async Task Read_LargeLengthSynchronous_Success(bool transferEncodingChunked)
@@ -248,9 +244,9 @@ namespace System.Net.Tests
context.Response.Close();
}
}
-
+
+ [ActiveIssue(22110, TargetFrameworkMonikers.UapAot)]
[Theory]
- [ActiveIssue(17462, TargetFrameworkMonikers.Uap)]
[InlineData(true)]
[InlineData(false)]
public async Task Read_TooMuchAsynchronous_Success(bool transferEncodingChunked)
@@ -275,8 +271,8 @@ namespace System.Net.Tests
}
}
+ [ActiveIssue(22110, TargetFrameworkMonikers.UapAot)]
[Theory]
- [ActiveIssue(17462, TargetFrameworkMonikers.Uap)]
[InlineData(true)]
[InlineData(false)]
public async Task Read_TooMuchSynchronous_Success(bool transferEncodingChunked)
@@ -302,7 +298,6 @@ namespace System.Net.Tests
}
[Theory]
- [ActiveIssue(17462, TargetFrameworkMonikers.Uap)]
[InlineData(true)]
[InlineData(false)]
public async Task Read_NotEnoughThenCloseAsynchronous_Success(bool transferEncodingChunked)
@@ -326,8 +321,8 @@ namespace System.Net.Tests
}
}
+ [ActiveIssue(22110, TargetFrameworkMonikers.UapAot)]
[Theory]
- [ActiveIssue(17462, TargetFrameworkMonikers.Uap)]
[InlineData(true)]
[InlineData(false)]
public async Task Read_Disposed_ReturnsZero(bool transferEncodingChunked)
@@ -356,7 +351,6 @@ namespace System.Net.Tests
}
[Fact]
- [ActiveIssue(17462, TargetFrameworkMonikers.Uap)]
public async Task CanSeek_Get_ReturnsFalse()
{
HttpListenerRequest response = await _helper.GetRequest(chunked: true);
@@ -374,8 +368,8 @@ namespace System.Net.Tests
}
}
+ [ActiveIssue(22110, TargetFrameworkMonikers.UapAot)]
[Fact]
- [ActiveIssue(17462, TargetFrameworkMonikers.Uap)]
public async Task CanRead_Get_ReturnsTrue()
{
HttpListenerRequest request = await _helper.GetRequest(chunked: true);
@@ -385,8 +379,8 @@ namespace System.Net.Tests
}
}
+ [ActiveIssue(22066, TargetFrameworkMonikers.UapAot)]
[Fact]
- [ActiveIssue(17462, TargetFrameworkMonikers.Uap)]
public async Task CanWrite_Get_ReturnsFalse()
{
HttpListenerRequest request = await _helper.GetRequest(chunked: true);
@@ -405,7 +399,6 @@ namespace System.Net.Tests
}
[Theory]
- [ActiveIssue(17462, TargetFrameworkMonikers.Uap)]
[InlineData(true)]
[InlineData(false)]
public async Task Read_NullBuffer_ThrowsArgumentNullException(bool chunked)
@@ -414,12 +407,12 @@ namespace System.Net.Tests
using (Stream inputStream = request.InputStream)
{
AssertExtensions.Throws<ArgumentNullException>("buffer", () => inputStream.Read(null, 0, 0));
- await Assert.ThrowsAsync<ArgumentNullException>("buffer", () => inputStream.ReadAsync(null, 0, 0));
+ await AssertExtensions.ThrowsAsync<ArgumentNullException>("buffer", () => inputStream.ReadAsync(null, 0, 0));
}
}
+ [ActiveIssue(22110, TargetFrameworkMonikers.UapAot)]
[Theory]
- [ActiveIssue(17462, TargetFrameworkMonikers.Uap)]
[InlineData(-1, true)]
[InlineData(3, true)]
[InlineData(-1, false)]
@@ -430,12 +423,12 @@ namespace System.Net.Tests
using (Stream inputStream = request.InputStream)
{
AssertExtensions.Throws<ArgumentOutOfRangeException>("offset", () => inputStream.Read(new byte[2], offset, 0));
- await Assert.ThrowsAsync<ArgumentOutOfRangeException>("offset", () => inputStream.ReadAsync(new byte[2], offset, 0));
+ await AssertExtensions.ThrowsAsync<ArgumentOutOfRangeException>("offset", () => inputStream.ReadAsync(new byte[2], offset, 0));
}
}
+ [ActiveIssue(22110, TargetFrameworkMonikers.UapAot)]
[Theory]
- [ActiveIssue(17462, TargetFrameworkMonikers.Uap)]
[InlineData(0, 3, true)]
[InlineData(1, 2, true)]
[InlineData(2, 1, true)]
@@ -448,12 +441,11 @@ namespace System.Net.Tests
using (Stream inputStream = request.InputStream)
{
AssertExtensions.Throws<ArgumentOutOfRangeException>("size", () => inputStream.Read(new byte[2], offset, size));
- await Assert.ThrowsAsync<ArgumentOutOfRangeException>("size", () => inputStream.ReadAsync(new byte[2], offset, size));
+ await AssertExtensions.ThrowsAsync<ArgumentOutOfRangeException>("size", () => inputStream.ReadAsync(new byte[2], offset, size));
}
}
[Theory]
- [ActiveIssue(17462, TargetFrameworkMonikers.Uap)]
[InlineData(true)]
[InlineData(false)]
public async Task EndRead_NullAsyncResult_ThrowsArgumentNullException(bool chunked)
@@ -466,7 +458,6 @@ namespace System.Net.Tests
}
[Theory]
- [ActiveIssue(17462, TargetFrameworkMonikers.Uap)]
[InlineData(true)]
[InlineData(false)]
public async Task EndRead_InvalidAsyncResult_ThrowsArgumentException(bool chunked)
@@ -485,7 +476,6 @@ namespace System.Net.Tests
}
[Theory]
- [ActiveIssue(17462, TargetFrameworkMonikers.Uap)]
[InlineData(true)]
[InlineData(false)]
public async Task EndRead_CalledTwice_ThrowsInvalidOperationException(bool chunked)
@@ -501,7 +491,6 @@ namespace System.Net.Tests
}
[Fact]
- [ActiveIssue(17462, TargetFrameworkMonikers.Uap)]
public async Task Read_FromClosedConnectionAsynchronously_ThrowsHttpListenerException()
{
const string Text = "Some-String";
@@ -528,7 +517,6 @@ namespace System.Net.Tests
}
[Fact]
- [ActiveIssue(17462, TargetFrameworkMonikers.Uap)]
public async Task Read_FromClosedConnectionSynchronously_ThrowsHttpListenerException()
{
const string Text = "Some-String";
diff --git a/src/System.Net.HttpListener/tests/HttpResponseStreamTests.cs b/src/System.Net.HttpListener/tests/HttpResponseStreamTests.cs
index 03ee1d6125..7ef9b23f01 100644
--- a/src/System.Net.HttpListener/tests/HttpResponseStreamTests.cs
+++ b/src/System.Net.HttpListener/tests/HttpResponseStreamTests.cs
@@ -33,7 +33,6 @@ namespace System.Net.Tests
}
[Theory]
- [ActiveIssue(17462, TargetFrameworkMonikers.Uap)]
[InlineData(true)]
[InlineData(false)]
public async Task SimpleRequest_WriteAsynchronously_Succeeds(bool sendChunked)
@@ -72,7 +71,6 @@ namespace System.Net.Tests
}
[Theory]
- [ActiveIssue(17462, TargetFrameworkMonikers.Uap)]
[InlineData(true)]
[InlineData(false)]
public async Task SimpleRequest_WriteSynchronouslyNonEmpty_Succeeds(bool sendChunked)
@@ -111,7 +109,6 @@ namespace System.Net.Tests
}
[Fact]
- [ActiveIssue(17462, TargetFrameworkMonikers.Uap)]
public async Task SimpleRequest_WriteAsynchronouslyInParts_Succeeds()
{
const string expectedResponse = "hello from HttpListener";
@@ -140,8 +137,8 @@ namespace System.Net.Tests
}
}
+ [ActiveIssue(22110, TargetFrameworkMonikers.UapAot)]
[Fact]
- [ActiveIssue(17462, TargetFrameworkMonikers.Uap)]
public async Task SimpleRequest_WriteSynchronouslyInParts_Succeeds()
{
const string expectedResponse = "hello from HttpListener";
@@ -170,8 +167,8 @@ namespace System.Net.Tests
}
}
+ [ActiveIssue(22110, TargetFrameworkMonikers.UapAot)]
[Fact]
- [ActiveIssue(17462, TargetFrameworkMonikers.Uap)]
public async Task SimpleRequest_WriteAynchronouslyEmpty_Succeeds()
{
Task<HttpListenerContext> serverContextTask = _listener.GetContextAsync();
@@ -195,7 +192,6 @@ namespace System.Net.Tests
}
[Fact]
- [ActiveIssue(17462, TargetFrameworkMonikers.Uap)]
public async Task SimpleRequest_WriteSynchronouslyEmpty_Succeeds()
{
Task<HttpListenerContext> serverContextTask = _listener.GetContextAsync();
@@ -219,7 +215,6 @@ namespace System.Net.Tests
}
[Fact]
- [ActiveIssue(17462, TargetFrameworkMonikers.Uap)]
public async Task CanSeek_Get_ReturnsFalse()
{
using (HttpListenerResponse response = await _helper.GetResponse())
@@ -237,8 +232,8 @@ namespace System.Net.Tests
}
}
+ [ActiveIssue(22066, TargetFrameworkMonikers.UapAot)]
[Fact]
- [ActiveIssue(17462, TargetFrameworkMonikers.Uap)]
public async Task CanRead_Get_ReturnsFalse()
{
using (HttpListenerResponse response = await _helper.GetResponse())
@@ -253,7 +248,6 @@ namespace System.Net.Tests
}
[Fact]
- [ActiveIssue(17462, TargetFrameworkMonikers.Uap)]
public async Task CanWrite_Get_ReturnsTrue()
{
using (HttpListenerResponse response = await _helper.GetResponse())
@@ -268,18 +262,16 @@ namespace System.Net.Tests
}
[Fact]
- [ActiveIssue(17462, TargetFrameworkMonikers.Uap)]
public async Task Write_NullBuffer_ThrowsArgumentNullException()
{
using (HttpListenerResponse response = await _helper.GetResponse())
using (Stream outputStream = response.OutputStream)
{
AssertExtensions.Throws<ArgumentNullException>("buffer", () => outputStream.Write(null, 0, 0));
- await Assert.ThrowsAsync<ArgumentNullException>("buffer", () => outputStream.WriteAsync(null, 0, 0));
+ await AssertExtensions.ThrowsAsync<ArgumentNullException>("buffer", () => outputStream.WriteAsync(null, 0, 0));
}
}
- [ActiveIssue(17462, TargetFrameworkMonikers.Uap)]
[Theory]
[InlineData(-1)]
[InlineData(3)]
@@ -289,11 +281,11 @@ namespace System.Net.Tests
using (Stream outputStream = response.OutputStream)
{
AssertExtensions.Throws<ArgumentOutOfRangeException>("offset", () => outputStream.Write(new byte[2], offset, 0));
- await Assert.ThrowsAsync<ArgumentOutOfRangeException>("offset", () => outputStream.WriteAsync(new byte[2], offset, 0));
+ await AssertExtensions.ThrowsAsync<ArgumentOutOfRangeException>("offset", () => outputStream.WriteAsync(new byte[2], offset, 0));
}
}
- [ActiveIssue(17462, TargetFrameworkMonikers.Uap)]
+ [ActiveIssue(22110, TargetFrameworkMonikers.UapAot)]
[Theory]
[InlineData(0, 3)]
[InlineData(1, 2)]
@@ -304,12 +296,11 @@ namespace System.Net.Tests
using (Stream outputStream = response.OutputStream)
{
AssertExtensions.Throws<ArgumentOutOfRangeException>("size", () => outputStream.Write(new byte[2], offset, size));
- await Assert.ThrowsAsync<ArgumentOutOfRangeException>("size", () => outputStream.WriteAsync(new byte[2], offset, size));
+ await AssertExtensions.ThrowsAsync<ArgumentOutOfRangeException>("size", () => outputStream.WriteAsync(new byte[2], offset, size));
}
}
[ConditionalFact(nameof(Helpers) + "." + nameof(Helpers.IsWindowsImplementation))] // [ActiveIssue(20201, TestPlatforms.AnyUnix)]
- [ActiveIssue(17462, TargetFrameworkMonikers.Uap)]
public async Task Write_TooMuch_ThrowsProtocolViolationException()
{
using (HttpClient client = new HttpClient())
@@ -338,7 +329,6 @@ namespace System.Net.Tests
}
[ConditionalFact(nameof(Helpers) + "." + nameof(Helpers.IsWindowsImplementation))] // [ActiveIssue(20201, TestPlatforms.AnyUnix)]
- [ActiveIssue(17462, TargetFrameworkMonikers.Uap)]
public async Task Write_TooLittleAsynchronouslyAndClose_ThrowsInvalidOperationException()
{
using (HttpClient client = new HttpClient())
@@ -365,7 +355,6 @@ namespace System.Net.Tests
}
[ConditionalFact(nameof(Helpers) + "." + nameof(Helpers.IsWindowsImplementation))] // [ActiveIssue(20201, TestPlatforms.AnyUnix)]
- [ActiveIssue(17462, TargetFrameworkMonikers.Uap)]
public async Task Write_TooLittleSynchronouslyAndClose_ThrowsInvalidOperationException()
{
using (HttpClient client = new HttpClient())
@@ -394,7 +383,6 @@ namespace System.Net.Tests
[ActiveIssue(20246)] // CI hanging frequently
[ActiveIssue(19534, TestPlatforms.OSX)]
[Theory]
- [ActiveIssue(17462, TargetFrameworkMonikers.Uap)]
[InlineData(true)]
[InlineData(false)]
public async Task Write_HeadersToClosedConnectionAsynchronously_ThrowsHttpListenerException(bool ignoreWriteExceptions)
@@ -434,7 +422,6 @@ namespace System.Net.Tests
[ActiveIssue(20246)] // CI hanging frequently
[ActiveIssue(19534, TestPlatforms.OSX)]
[Theory]
- [ActiveIssue(17462, TargetFrameworkMonikers.Uap)]
[InlineData(true)]
[InlineData(false)]
public async Task Write_HeadersToClosedConnectionSynchronously_ThrowsHttpListenerException(bool ignoreWriteExceptions)
@@ -474,7 +461,6 @@ namespace System.Net.Tests
[ActiveIssue(19534, TestPlatforms.OSX)]
[Theory]
- [ActiveIssue(17462, TargetFrameworkMonikers.Uap)]
[InlineData(true)]
[InlineData(false)]
[ActiveIssue(18188, platforms: TestPlatforms.Windows)] // Indeterminate failure - socket not always fully disconnected.
@@ -515,7 +501,6 @@ namespace System.Net.Tests
[ActiveIssue(19534, TestPlatforms.OSX)]
[Theory]
- [ActiveIssue(17462, TargetFrameworkMonikers.Uap)]
[InlineData(true)]
[InlineData(false)]
[ActiveIssue(18188, platforms: TestPlatforms.Windows)] // Indeterminate failure - socket not always fully disconnected.
@@ -554,7 +539,7 @@ namespace System.Net.Tests
}
}
- [ActiveIssue(17462, TargetFrameworkMonikers.Uap)]
+ [ActiveIssue(22110, TargetFrameworkMonikers.UapAot)]
[Theory]
[InlineData(true)]
[InlineData(false)]
@@ -568,7 +553,7 @@ namespace System.Net.Tests
}
}
- [ActiveIssue(17462, TargetFrameworkMonikers.Uap)]
+ [ActiveIssue(22110, TargetFrameworkMonikers.UapAot)]
[Fact]
public async Task EndWrite_InvalidAsyncResult_ThrowsArgumentException()
{
@@ -584,7 +569,6 @@ namespace System.Net.Tests
}
}
- [ActiveIssue(17462, TargetFrameworkMonikers.Uap)]
[Fact]
public async Task EndWrite_CalledTwice_ThrowsInvalidOperationException()
{
diff --git a/src/System.Net.HttpListener/tests/InvalidClientRequestTests.cs b/src/System.Net.HttpListener/tests/InvalidClientRequestTests.cs
index 48c784cf04..f38c54d57a 100644
--- a/src/System.Net.HttpListener/tests/InvalidClientRequestTests.cs
+++ b/src/System.Net.HttpListener/tests/InvalidClientRequestTests.cs
@@ -92,7 +92,6 @@ namespace System.Net.Tests
}
[Fact]
- [ActiveIssue(17462, TargetFrameworkMonikers.Uap)]
public async Task GetContext_InvalidRequest_DoesNotGetContext()
{
// These tests take upwards of 20s if this uses [Theory].
diff --git a/src/System.Net.HttpListener/tests/Resources/System.Net.HttpListener.Tests.rd.xml b/src/System.Net.HttpListener/tests/Resources/System.Net.HttpListener.Tests.rd.xml
new file mode 100644
index 0000000000..9378152e1d
--- /dev/null
+++ b/src/System.Net.HttpListener/tests/Resources/System.Net.HttpListener.Tests.rd.xml
@@ -0,0 +1,6 @@
+<?xml version="1.0" encoding="utf-8" ?>
+<Directives xmlns="http://schemas.microsoft.com/netfx/2013/01/metadata">
+ <Library Name="System.Net.Tests.HttpListenerRequestTests">
+ <Type Name="System.Text.UTF8Encoding" Dynamic="Required All" />
+ </Library>
+</Directives>
diff --git a/src/System.Net.HttpListener/tests/SimpleHttpTests.cs b/src/System.Net.HttpListener/tests/SimpleHttpTests.cs
index 4d702a27ca..c6a939fa8a 100644
--- a/src/System.Net.HttpListener/tests/SimpleHttpTests.cs
+++ b/src/System.Net.HttpListener/tests/SimpleHttpTests.cs
@@ -22,14 +22,12 @@ namespace System.Net.Tests
public void Dispose() => _factory.Dispose();
[Fact]
- [ActiveIssue(17462, TargetFrameworkMonikers.Uap)]
public static void Supported_True()
{
Assert.True(HttpListener.IsSupported);
}
[Fact]
- [ActiveIssue(17462, TargetFrameworkMonikers.Uap)]
public void BasicTest_StartStop_NoException()
{
HttpListener listener = new HttpListener();
@@ -46,7 +44,6 @@ namespace System.Net.Tests
}
[Fact]
- [ActiveIssue(17462, TargetFrameworkMonikers.Uap)]
public void BasicTest_StartCloseAbort_NoException()
{
HttpListener listener = new HttpListener();
@@ -63,7 +60,6 @@ namespace System.Net.Tests
}
[Fact]
- [ActiveIssue(17462, TargetFrameworkMonikers.Uap)]
public void BasicTest_StartAbortClose_NoException()
{
HttpListener listener = new HttpListener();
@@ -80,7 +76,6 @@ namespace System.Net.Tests
}
[Fact]
- [ActiveIssue(17462, TargetFrameworkMonikers.Uap)]
public void BasicTest_StopNoStart_NoException()
{
HttpListener listener = new HttpListener();
@@ -89,7 +84,6 @@ namespace System.Net.Tests
}
[Fact]
- [ActiveIssue(17462, TargetFrameworkMonikers.Uap)]
public void BasicTest_CloseNoStart_NoException()
{
HttpListener listener = new HttpListener();
@@ -97,7 +91,6 @@ namespace System.Net.Tests
}
[Fact]
- [ActiveIssue(17462, TargetFrameworkMonikers.Uap)]
public void BasicTest_AbortNoStart_NoException()
{
HttpListener listener = new HttpListener();
@@ -105,7 +98,6 @@ namespace System.Net.Tests
}
[Fact]
- [ActiveIssue(17462, TargetFrameworkMonikers.Uap)]
public void BasicTest_StartThrowsAbortCalledInFinally_AbortDoesntThrow()
{
HttpListener listener = new HttpListener();
@@ -125,13 +117,10 @@ namespace System.Net.Tests
}
}
- [ActiveIssue(19754)] // Recombine into UnknownHeaders_Success when fixed
[Theory]
- [ActiveIssue(17462, TargetFrameworkMonikers.Uap)]
public Task UnknownHeaders_Success_Large() => UnknownHeaders_Success(1000);
[Theory]
- [ActiveIssue(17462, TargetFrameworkMonikers.Uap)]
[InlineData(100)]
public async Task UnknownHeaders_Success(int numHeaders)
{
diff --git a/src/System.Net.HttpListener/tests/System.Net.HttpListener.Tests.csproj b/src/System.Net.HttpListener/tests/System.Net.HttpListener.Tests.csproj
index 4626f9b3be..bd3cf4d740 100644
--- a/src/System.Net.HttpListener/tests/System.Net.HttpListener.Tests.csproj
+++ b/src/System.Net.HttpListener/tests/System.Net.HttpListener.Tests.csproj
@@ -10,29 +10,35 @@
<PropertyGroup Condition="'$(Configuration)|$(Platform)'=='netstandard-Release|AnyCPU'" />
<ItemGroup>
<Compile Include="GetContextHelper.cs" />
+ <Compile Include="HttpListenerFactory.cs" />
<Compile Include="HttpListenerAuthenticationTests.cs" />
<Compile Include="HttpListenerContextTests.cs" />
<Compile Include="HttpListenerPrefixCollectionTests.cs" />
+ <Compile Include="HttpListenerResponseTests.cs" />
<Compile Include="HttpListenerResponseTests.Cookies.cs" />
<Compile Include="HttpListenerResponseTests.Headers.cs" />
- <Compile Include="HttpListenerResponseTests.cs" />
<Compile Include="HttpListenerRequestTests.cs" />
<Compile Include="HttpListenerTests.cs" />
+ <Compile Include="HttpListenerTimeoutManagerTests.cs" />
+ <Compile Include="HttpListenerWebSocketTests.cs" />
<Compile Include="HttpRequestStreamTests.cs" />
<Compile Include="HttpResponseStreamTests.cs" />
<Compile Include="InvalidClientRequestTests.cs" />
<Compile Include="SimpleHttpTests.cs" />
- <Compile Include="HttpListenerFactory.cs" />
- <Compile Include="HttpListenerWebSocketTests.cs" />
<Compile Include="WebSocketTests.cs" />
<Compile Include="XUnitAssemblyAttributes.cs" />
- <Compile Include="$(CommonTestPath)\System\AssertExtensions.cs">
- <Link>Common\System\AssertExtensions.cs</Link>
- </Compile>
<Compile Include="$(CommonTestPath)\System\PlatformDetection.cs">
<Link>Common\tests\System\PlatformDetection.cs</Link>
</Compile>
- <Compile Include="HttpListenerTimeoutManagerTests.cs" />
+ <Compile Include="$(CommonTestPath)\System\Net\PlatformDetection.Networking.cs">
+ <Link>Common\tests\System\Net\PlatformDetection.Networking.cs</Link>
+ </Compile>
+ </ItemGroup>
+ <ItemGroup>
+ <EmbeddedResource Include="Resources\System.Net.HttpListener.Tests.rd.xml" />
+ </ItemGroup>
+ <ItemGroup Condition="'$(TargetsOSX)'=='true'">
+ <TestCommandLines Include="ulimit -n 70000" />
</ItemGroup>
<Import Project="$([MSBuild]::GetDirectoryNameOfFileAbove($(MSBuildThisFileDirectory), dir.targets))\dir.targets" />
-</Project> \ No newline at end of file
+</Project>
diff --git a/src/System.Net.HttpListener/tests/WebSocketTests.cs b/src/System.Net.HttpListener/tests/WebSocketTests.cs
index c2d593d6ac..7665e2ab66 100644
--- a/src/System.Net.HttpListener/tests/WebSocketTests.cs
+++ b/src/System.Net.HttpListener/tests/WebSocketTests.cs
@@ -24,7 +24,6 @@ namespace System.Net.Tests
public void Dispose() => _factory.Dispose();
[Fact]
- [ActiveIssue(17462, TargetFrameworkMonikers.Uap)]
public async Task AcceptWebSocketAsync_NullSubProtocol_Succeeds()
{
if (PlatformDetection.IsWindows7)
diff --git a/src/System.Net.Mail/src/System/Net/Mail/SmtpClient.cs b/src/System.Net.Mail/src/System/Net/Mail/SmtpClient.cs
index 28d15ff2a3..1d720f93f2 100644
--- a/src/System.Net.Mail/src/System/Net/Mail/SmtpClient.cs
+++ b/src/System.Net.Mail/src/System/Net/Mail/SmtpClient.cs
@@ -136,21 +136,7 @@ namespace System.Net.Mail
// machine connecting to public server).
// SMTP RFC's require ASCII only host names in the HELO/EHLO message.
-
- // TODO: https://github.com/dotnet/corefx/issues/19605
- //
- // Catching NotSupportedException here because HostName is currently PNSE
- // on UapAot. HostName is planned to be restored for .NetCore 2.1
- // so once that's done, the try-catch can be removed.
- string clientDomainRaw;
- try
- {
- clientDomainRaw = IPGlobalProperties.GetIPGlobalProperties().HostName;
- }
- catch (NotSupportedException)
- {
- clientDomainRaw = "LocalHost";
- }
+ string clientDomainRaw = IPGlobalProperties.GetIPGlobalProperties().HostName;
IdnMapping mapping = new IdnMapping();
try
diff --git a/src/System.Net.Mail/tests/Functional/SmtpClientTest.cs b/src/System.Net.Mail/tests/Functional/SmtpClientTest.cs
index 9604f91651..8b0ca8cbe9 100644
--- a/src/System.Net.Mail/tests/Functional/SmtpClientTest.cs
+++ b/src/System.Net.Mail/tests/Functional/SmtpClientTest.cs
@@ -10,6 +10,7 @@
//
using System.IO;
+using System.Net.NetworkInformation;
using System.Threading;
using System.Threading.Tasks;
using Xunit;
@@ -277,6 +278,7 @@ namespace System.Net.Mail.Tests
SmtpClient client = new SmtpClient("localhost", server.EndPoint.Port);
client.Credentials = new NetworkCredential("user", "password");
MailMessage msg = new MailMessage("foo@example.com", "bar@example.com", "hello", "howdydoo");
+ string clientDomain = IPGlobalProperties.GetIPGlobalProperties().HostName.Trim().ToLower();
try
{
@@ -289,6 +291,7 @@ namespace System.Net.Mail.Tests
Assert.Equal("<bar@example.com>", server.MailTo);
Assert.Equal("hello", server.Subject);
Assert.Equal("howdydoo", server.Body);
+ Assert.Equal(clientDomain, server.ClientDomain);
}
finally
{
@@ -302,6 +305,7 @@ namespace System.Net.Mail.Tests
SmtpServer server = new SmtpServer();
SmtpClient client = new SmtpClient("localhost", server.EndPoint.Port);
MailMessage msg = new MailMessage("foo@example.com", "bar@example.com", "hello", "howdydoo");
+ string clientDomain = IPGlobalProperties.GetIPGlobalProperties().HostName.Trim().ToLower();
try
{
@@ -314,6 +318,7 @@ namespace System.Net.Mail.Tests
Assert.Equal("<bar@example.com>", server.MailTo);
Assert.Equal("hello", server.Subject);
Assert.Equal("howdydoo", server.Body);
+ Assert.Equal(clientDomain, server.ClientDomain);
}
finally
{
@@ -327,6 +332,7 @@ namespace System.Net.Mail.Tests
SmtpServer server = new SmtpServer();
SmtpClient client = new SmtpClient("localhost", server.EndPoint.Port);
MailMessage msg = new MailMessage("foo@example.com", "bar@example.com", "hello", "howdydoo");
+ string clientDomain = IPGlobalProperties.GetIPGlobalProperties().HostName.Trim().ToLower();
CredentialCache cache = new CredentialCache();
cache.Add("localhost", server.EndPoint.Port, "NTLM", CredentialCache.DefaultNetworkCredentials);
@@ -344,6 +350,7 @@ namespace System.Net.Mail.Tests
Assert.Equal("<bar@example.com>", server.MailTo);
Assert.Equal("hello", server.Subject);
Assert.Equal("howdydoo", server.Body);
+ Assert.Equal(clientDomain, server.ClientDomain);
}
finally
{
diff --git a/src/System.Net.Mail/tests/Functional/SmtpServer.cs b/src/System.Net.Mail/tests/Functional/SmtpServer.cs
index ed40ec1cd9..467ef5a4a6 100644
--- a/src/System.Net.Mail/tests/Functional/SmtpServer.cs
+++ b/src/System.Net.Mail/tests/Functional/SmtpServer.cs
@@ -16,12 +16,13 @@ namespace System.Net.Mail.Tests
{
public class SmtpServer
{
- private string _mailfrom, _mailto, _subject, _body;
+ private string _mailfrom, _mailto, _subject, _body, _clientdomain;
public string MailFrom => _mailfrom;
public string MailTo => _mailto;
public string Subject => _subject;
public string Body => _body;
+ public string ClientDomain => _clientdomain;
private readonly TcpListener _server;
@@ -90,8 +91,10 @@ namespace System.Net.Mail.Tests
switch (s.Substring(0, 4))
{
case "HELO":
+ _clientdomain = s.Substring(5).Trim().ToLower();
break;
case "EHLO":
+ _clientdomain = s.Substring(5).Trim().ToLower();
WriteNS(ns, "250-localhost Hello" + s.Substring(5, s.Length - 5) + "\r\n");
WriteNS(ns, "250-AUTH PLAIN\r\n");
break;
diff --git a/src/System.Net.Mail/tests/Functional/System.Net.Mail.Functional.Tests.csproj b/src/System.Net.Mail/tests/Functional/System.Net.Mail.Functional.Tests.csproj
index 1075c5a8be..da55bbae70 100644
--- a/src/System.Net.Mail/tests/Functional/System.Net.Mail.Functional.Tests.csproj
+++ b/src/System.Net.Mail/tests/Functional/System.Net.Mail.Functional.Tests.csproj
@@ -22,14 +22,14 @@
<Compile Include="SmtpClientTest.cs" />
<Compile Include="SmtpExceptionTest.cs" />
<Compile Include="SmtpServer.cs" />
- <Compile Include="$(CommonTestPath)\System\AssertExtensions.cs">
- <Link>Common\System\AssertExtensions.cs</Link>
- </Compile>
<Compile Include="$(CommonTestPath)\System\Diagnostics\Tracing\TestEventListener.cs">
<Link>Common\System\Diagnostics\Tracing\TestEventListener.cs</Link>
</Compile>
</ItemGroup>
<ItemGroup>
+ <Reference Include="System.Net.NetworkInformation" />
+ </ItemGroup>
+ <ItemGroup>
<ProjectReference Include="$(CommonTestPath)\System\Diagnostics\RemoteExecutorConsoleApp\RemoteExecutorConsoleApp.csproj">
<Project>{69e46a6f-9966-45a5-8945-2559fe337827}</Project>
<Name>RemoteExecutorConsoleApp</Name>
diff --git a/src/System.Net.NameResolution/tests/UnitTests/InitializationTest.cs b/src/System.Net.NameResolution/tests/UnitTests/InitializationTest.cs
index 7188de64de..1e93337ea6 100644
--- a/src/System.Net.NameResolution/tests/UnitTests/InitializationTest.cs
+++ b/src/System.Net.NameResolution/tests/UnitTests/InitializationTest.cs
@@ -13,7 +13,6 @@ namespace System.Net.NameResolution.Tests
public class InitializationTests
{
[Fact]
- [SkipOnTargetFramework(TargetFrameworkMonikers.NetFramework, "dotnet/corefx #17990")]
public void Dns_BeginGetHostAddresses_CallSocketInit_Ok()
{
NameResolutionPal.FakesReset();
diff --git a/src/System.Net.NetworkInformation/src/System.Net.NetworkInformation.csproj b/src/System.Net.NetworkInformation/src/System.Net.NetworkInformation.csproj
index 1155ca67b7..01cebd9657 100644
--- a/src/System.Net.NetworkInformation/src/System.Net.NetworkInformation.csproj
+++ b/src/System.Net.NetworkInformation/src/System.Net.NetworkInformation.csproj
@@ -7,9 +7,6 @@
<ProjectGuid>{3CA89D6C-F8D1-4813-9775-F8D249686E31}</ProjectGuid>
<AllowUnsafeBlocks>true</AllowUnsafeBlocks>
</PropertyGroup>
- <PropertyGroup>
- <DefineConstants Condition="'$(TargetGroup)' == 'uap'">$(DefineConstants);uap</DefineConstants>
- </PropertyGroup>
<PropertyGroup Condition="'$(Configuration)|$(Platform)'=='uap-Windows_NT-Debug|AnyCPU'" />
<PropertyGroup Condition="'$(Configuration)|$(Platform)'=='uap-Windows_NT-Release|AnyCPU'" />
<PropertyGroup Condition="'$(Configuration)|$(Platform)'=='netcoreapp-Linux-Debug|AnyCPU'" />
@@ -349,11 +346,6 @@
<Compile Include="System\Net\NetworkInformation\NetworkInterfacePal.UnknownUnix.cs" />
<Compile Include="System\Net\NetworkInformation\NetworkAddressChange.UnknownUnix.cs" />
</ItemGroup>
- <ItemGroup Condition="'$(TargetGroup)' == 'uap'">
- <Reference Include="Windows" />
- <Reference Include="mscorlib" />
- <Reference Include="System.Runtime.InteropServices.WindowsRuntime" />
- </ItemGroup>
<ItemGroup>
<Reference Include="Microsoft.Win32.Primitives" />
<Reference Include="System.Collections" />
diff --git a/src/System.Net.Ping/tests/FunctionalTests/PingTest.cs b/src/System.Net.Ping/tests/FunctionalTests/PingTest.cs
index bedf071bf5..947e7a346e 100644
--- a/src/System.Net.Ping/tests/FunctionalTests/PingTest.cs
+++ b/src/System.Net.Ping/tests/FunctionalTests/PingTest.cs
@@ -81,7 +81,7 @@ namespace System.Net.NetworkInformation.Tests
}
[Fact]
- [ActiveIssue(20130, TargetFrameworkMonikers.Uap)]
+ [ActiveIssue(19583, TargetFrameworkMonikers.Uap)]
public async Task SendPingAsyncWithIPAddress()
{
IPAddress localIpAddress = await TestSettings.GetLocalIPAddress();
@@ -96,7 +96,7 @@ namespace System.Net.NetworkInformation.Tests
}
[Fact]
- [ActiveIssue(20130, TargetFrameworkMonikers.Uap)]
+ [ActiveIssue(19583, TargetFrameworkMonikers.Uap)]
public async Task SendPingAsyncWithIPAddress_AddressAsString()
{
IPAddress localIpAddress = await TestSettings.GetLocalIPAddress();
@@ -111,7 +111,7 @@ namespace System.Net.NetworkInformation.Tests
}
[Fact]
- [ActiveIssue(20130, TargetFrameworkMonikers.Uap)]
+ [ActiveIssue(19583, TargetFrameworkMonikers.Uap)]
public async Task SendPingAsyncWithIPAddressAndTimeout()
{
IPAddress localIpAddress = await TestSettings.GetLocalIPAddress();
@@ -126,7 +126,7 @@ namespace System.Net.NetworkInformation.Tests
}
[PlatformSpecific(TestPlatforms.Windows)] // On Unix, Non-root pings cannot send arbitrary data in the buffer, and do not receive it back in the PingReply.
- [ActiveIssue(20130, TargetFrameworkMonikers.Uap)]
+ [ActiveIssue(19583, TargetFrameworkMonikers.Uap)]
[Fact]
public async Task SendPingAsyncWithIPAddressAndTimeoutAndBuffer()
{
@@ -171,7 +171,7 @@ namespace System.Net.NetworkInformation.Tests
}
[PlatformSpecific(TestPlatforms.Windows)] // On Unix, Non-root pings cannot send arbitrary data in the buffer, and do not receive it back in the PingReply.
- [ActiveIssue(20130, TargetFrameworkMonikers.Uap)]
+ [ActiveIssue(19583, TargetFrameworkMonikers.Uap)]
[Fact]
public async Task SendPingAsyncWithIPAddressAndTimeoutAndBufferAndPingOptions()
{
@@ -217,7 +217,7 @@ namespace System.Net.NetworkInformation.Tests
}
[Fact]
- [ActiveIssue(20130, TargetFrameworkMonikers.Uap)]
+ [ActiveIssue(19583, TargetFrameworkMonikers.Uap)]
public async Task SendPingAsyncWithHost()
{
IPAddress localIpAddress = await TestSettings.GetLocalIPAddress();
@@ -232,7 +232,7 @@ namespace System.Net.NetworkInformation.Tests
}
[Fact]
- [ActiveIssue(20130, TargetFrameworkMonikers.Uap)]
+ [ActiveIssue(19583, TargetFrameworkMonikers.Uap)]
public async Task SendPingAsyncWithHostAndTimeout()
{
IPAddress localIpAddress = await TestSettings.GetLocalIPAddress();
@@ -247,7 +247,7 @@ namespace System.Net.NetworkInformation.Tests
}
[PlatformSpecific(TestPlatforms.Windows)] // On Unix, Non-root pings cannot send arbitrary data in the buffer, and do not receive it back in the PingReply.
- [ActiveIssue(20130, TargetFrameworkMonikers.Uap)]
+ [ActiveIssue(19583, TargetFrameworkMonikers.Uap)]
[Fact]
public async Task SendPingAsyncWithHostAndTimeoutAndBuffer()
{
@@ -292,7 +292,7 @@ namespace System.Net.NetworkInformation.Tests
}
[PlatformSpecific(TestPlatforms.Windows)] // On Unix, Non-root pings cannot send arbitrary data in the buffer, and do not receive it back in the PingReply.
- [ActiveIssue(20130, TargetFrameworkMonikers.Uap)]
+ [ActiveIssue(19583, TargetFrameworkMonikers.Uap)]
[Fact]
public async Task SendPingAsyncWithHostAndTimeoutAndBufferAndPingOptions()
{
@@ -337,7 +337,7 @@ namespace System.Net.NetworkInformation.Tests
}
[Fact]
- [ActiveIssue(20130, TargetFrameworkMonikers.Uap)]
+ [ActiveIssue(19583, TargetFrameworkMonikers.Uap)]
public static async Task SendPings_ReuseInstance_Hostname()
{
IPAddress localIpAddress = await TestSettings.GetLocalIPAddress();
@@ -354,7 +354,7 @@ namespace System.Net.NetworkInformation.Tests
}
[Fact]
- [ActiveIssue(20130, TargetFrameworkMonikers.Uap)]
+ [ActiveIssue(19583, TargetFrameworkMonikers.Uap)]
public static async Task Sends_ReuseInstance_Hostname()
{
IPAddress localIpAddress = await TestSettings.GetLocalIPAddress();
@@ -371,7 +371,7 @@ namespace System.Net.NetworkInformation.Tests
}
[Fact]
- [ActiveIssue(20130, TargetFrameworkMonikers.Uap)]
+ [ActiveIssue(19583, TargetFrameworkMonikers.Uap)]
public static async Task SendAsyncs_ReuseInstance_Hostname()
{
IPAddress localIpAddress = await TestSettings.GetLocalIPAddress();
@@ -423,7 +423,7 @@ namespace System.Net.NetworkInformation.Tests
}
[Fact]
- [ActiveIssue(20130, TargetFrameworkMonikers.Uap)]
+ [ActiveIssue(19583, TargetFrameworkMonikers.Uap)]
public static async Task Ping_DisposeAfterSend_Success()
{
Ping p = new Ping();
@@ -432,7 +432,7 @@ namespace System.Net.NetworkInformation.Tests
}
[Fact]
- [ActiveIssue(20130, TargetFrameworkMonikers.Uap)]
+ [ActiveIssue(19583, TargetFrameworkMonikers.Uap)]
public static void Ping_DisposeMultipletimes_Success()
{
Ping p = new Ping();
@@ -441,7 +441,7 @@ namespace System.Net.NetworkInformation.Tests
}
[Fact]
- [ActiveIssue(20130, TargetFrameworkMonikers.Uap)]
+ [ActiveIssue(19583, TargetFrameworkMonikers.Uap)]
public static void Ping_SendAfterDispose_ThrowsSynchronously()
{
Ping p = new Ping();
diff --git a/src/System.Net.Ping/tests/FunctionalTests/System.Net.Ping.Functional.Tests.csproj b/src/System.Net.Ping/tests/FunctionalTests/System.Net.Ping.Functional.Tests.csproj
index 9da4f07543..5cb412390a 100644
--- a/src/System.Net.Ping/tests/FunctionalTests/System.Net.Ping.Functional.Tests.csproj
+++ b/src/System.Net.Ping/tests/FunctionalTests/System.Net.Ping.Functional.Tests.csproj
@@ -23,9 +23,6 @@
<Compile Include="$(CommonPath)\System\Net\NetworkInformation\UnixCommandLinePing.cs">
<Link>Common\System\Net\NetworkInformation\UnixCommandLinePing.cs</Link>
</Compile>
- <Compile Include="$(CommonTestPath)\System\AssertExtensions.cs">
- <Link>Common\System\AssertExtensions.cs</Link>
- </Compile>
<Compile Include="$(CommonTestPath)\System\Net\Capability.RawSocketPermissions.cs">
<Link>Common\System\Net\Capability.RawSocketPermissions.cs</Link>
</Compile>
diff --git a/src/System.Net.Primitives/src/Resources/System.Net.Primitives.rd.xml b/src/System.Net.Primitives/src/Resources/System.Net.Primitives.rd.xml
new file mode 100644
index 0000000000..a5ee5cd1df
--- /dev/null
+++ b/src/System.Net.Primitives/src/Resources/System.Net.Primitives.rd.xml
@@ -0,0 +1,22 @@
+<?xml version="1.0" encoding="utf-8" ?>
+<Directives xmlns="http://schemas.microsoft.com/netfx/2013/01/metadata">
+ <Library Name="*System.Net.Primitives*">
+ <Assembly Name="System.Net.Primitives">
+ <!-- VSO 449560 The following types are used by HttpListener. -->
+ <Type Name="System.Net.Cookie">
+ <!-- Used by CookieParser -->
+ <Method Name="InternalSetName" Dynamic="Required" />
+ <Field Name="IsQuotedDomain" Dynamic="Required" />
+ <Field Name="IsQuotedVersion" Dynamic="Required" />
+
+ <!-- Used by CookieExtensions -->
+ <Method Name="ToServerString" Dynamic="Required" />
+ <Method Name="Clone" Dynamic="Required" />
+ <Property Name="Variant" Dynamic="Required" />
+ </Type>
+ <Type Name="System.Net.CookieCollection">
+ <Method Name="InternalAdd" Dynamic="Required" />
+ </Type>
+ </Assembly>
+ </Library>
+</Directives>
diff --git a/src/System.Net.Primitives/src/System.Net.Primitives.csproj b/src/System.Net.Primitives/src/System.Net.Primitives.csproj
index fc322c7798..be78612c07 100644
--- a/src/System.Net.Primitives/src/System.Net.Primitives.csproj
+++ b/src/System.Net.Primitives/src/System.Net.Primitives.csproj
@@ -187,6 +187,9 @@
<Link>Interop\Unix\System.Native\Interop.SocketAddress.cs</Link>
</Compile>
</ItemGroup>
+ <ItemGroup Condition=" '$(TargetGroup)' == 'uap'">
+ <EmbeddedResource Include="Resources\$(AssemblyName).rd.xml" />
+ </ItemGroup>
<ItemGroup>
<Reference Include="Microsoft.Win32.Primitives" />
<Reference Include="System.Collections" />
diff --git a/src/System.Net.Primitives/src/System/Net/Cookie.cs b/src/System.Net.Primitives/src/System/Net/Cookie.cs
index 204f398075..5252ff538d 100644
--- a/src/System.Net.Primitives/src/System/Net/Cookie.cs
+++ b/src/System.Net.Primitives/src/System/Net/Cookie.cs
@@ -67,8 +67,34 @@ namespace System.Net
private int m_version = 0; // Do not rename (binary serialization)
private string m_domainKey = string.Empty; // Do not rename (binary serialization)
- internal bool IsQuotedVersion = false;
- internal bool IsQuotedDomain = false;
+
+/*
+ TODO: #13607
+ VSO 449560
+ Reflecting on internal method won't work on AOT without rd.xml and DisableReflection
+ block in toolchain.Networking team will be working on exposing methods from S.Net.Primitive
+ public, this is a temporary workaround till that happens.
+*/
+#if uap
+ public
+#else
+ internal
+#endif
+ bool IsQuotedVersion = false;
+
+/*
+ TODO: #13607
+ VSO 449560
+ Reflecting on internal method won't work on AOT without rd.xml and DisableReflection
+ block in toolchain.Networking team will be working on exposing methods from S.Net.Primitive
+ public, this is a temporary workaround till that happens.
+*/
+#if uap
+ public
+#else
+ internal
+#endif
+ bool IsQuotedDomain = false;
#if DEBUG
static Cookie()
@@ -218,10 +244,11 @@ namespace System.Net
}
/*
- VSO 449560
- Reflecting on internal method wont work on AOT without rd.xml and DisableReflection
- block in toolchain.Networking team will be working on exposing methods from S.Net.Primitive
- public,this is a temporary workaround till that happens.
+ TODO: #13607
+ VSO 449560
+ Reflecting on internal method won't work on AOT without rd.xml and DisableReflection
+ block in toolchain.Networking team will be working on exposing methods from S.Net.Primitive
+ public, this is a temporary workaround till that happens.
*/
#if uap
public
@@ -260,7 +287,19 @@ namespace System.Net
}
}
- internal Cookie Clone()
+/*
+ TODO: #13607
+ VSO 449560
+ Reflecting on internal method won't work on AOT without rd.xml and DisableReflection
+ block in toolchain.Networking team will be working on exposing methods from S.Net.Primitive
+ public, this is a temporary workaround till that happens.
+*/
+#if uap
+ public
+#else
+ internal
+#endif
+ Cookie Clone()
{
Cookie clonedCookie = new Cookie(m_name, m_value);
@@ -665,7 +704,19 @@ namespace System.Net
}
}
- internal CookieVariant Variant
+/*
+ TODO: #13607
+ VSO 449560
+ Reflecting on internal method won't work on AOT without rd.xml and DisableReflection
+ block in toolchain.Networking team will be working on exposing methods from S.Net.Primitive
+ public, this is a temporary workaround till that happens.
+*/
+#if uap
+ public
+#else
+ internal
+#endif
+ CookieVariant Variant
{
get
{
@@ -794,7 +845,19 @@ namespace System.Net
}
}
- internal string ToServerString()
+/*
+ TODO: #13607
+ VSO 449560
+ Reflecting on internal method won't work on AOT without rd.xml and DisableReflection
+ block in toolchain.Networking team will be working on exposing methods from S.Net.Primitive
+ public, this is a temporary workaround till that happens.
+*/
+#if uap
+ public
+#else
+ internal
+#endif
+ string ToServerString()
{
string result = Name + EqualsLiteral + Value;
if (m_comment != null && m_comment.Length > 0)
diff --git a/src/System.Net.Primitives/src/System/Net/CookieCollection.cs b/src/System.Net.Primitives/src/System/Net/CookieCollection.cs
index 5bbd7b6bf3..732aad4857 100644
--- a/src/System.Net.Primitives/src/System/Net/CookieCollection.cs
+++ b/src/System.Net.Primitives/src/System/Net/CookieCollection.cs
@@ -170,10 +170,24 @@ namespace System.Net
}
}
+
// If isStrict == false, assumes that incoming cookie is unique.
// If isStrict == true, replace the cookie if found same with newest Variant.
// Returns 1 if added, 0 if replaced or rejected.
- internal int InternalAdd(Cookie cookie, bool isStrict)
+
+/*
+ TODO: #13607
+ VSO 449560
+ Reflecting on internal method won't work on AOT without rd.xml and DisableReflection
+ block in toolchain.Networking team will be working on exposing methods from S.Net.Primitive
+ public, this is a temporary workaround till that happens.
+*/
+#if uap
+ public
+#else
+ internal
+#endif
+ int InternalAdd(Cookie cookie, bool isStrict)
{
int ret = 1;
if (isStrict)
diff --git a/src/System.Net.Primitives/tests/FunctionalTests/System.Net.Primitives.Functional.Tests.csproj b/src/System.Net.Primitives/tests/FunctionalTests/System.Net.Primitives.Functional.Tests.csproj
index c3be1073ea..83b231ede5 100644
--- a/src/System.Net.Primitives/tests/FunctionalTests/System.Net.Primitives.Functional.Tests.csproj
+++ b/src/System.Net.Primitives/tests/FunctionalTests/System.Net.Primitives.Functional.Tests.csproj
@@ -27,9 +27,6 @@
<Compile Include="SerializationTest.cs" />
<Compile Include="RequestCachePolicyTest.cs" />
<Compile Include="CookieContainerAddTest.cs" />
- <Compile Include="$(CommonTestPath)\System\AssertExtensions.cs">
- <Link>Common\System\AssertExtensions.cs</Link>
- </Compile>
<Compile Include="$(CommonTestPath)\System\PlatformDetection.cs">
<Link>Common\System\PlatformDetection.cs</Link>
</Compile>
diff --git a/src/System.Net.Primitives/tests/UnitTests/System.Net.Primitives.UnitTests.Tests.csproj b/src/System.Net.Primitives/tests/UnitTests/System.Net.Primitives.UnitTests.Tests.csproj
index 1641d03c14..775697471f 100644
--- a/src/System.Net.Primitives/tests/UnitTests/System.Net.Primitives.UnitTests.Tests.csproj
+++ b/src/System.Net.Primitives/tests/UnitTests/System.Net.Primitives.UnitTests.Tests.csproj
@@ -77,9 +77,6 @@
<Compile Include="Fakes\IPv4AddressHelper.cs" />
<Compile Include="Fakes\IPv6AddressHelper.cs" />
<Compile Include="Fakes\Serialization.cs" Condition="'$(TargetGroup)' != 'netstandard' And '$(TargetGroup)' != 'netcoreapp'" />
- <Compile Include="$(CommonTestPath)\System\AssertExtensions.cs">
- <Link>Common\System\AssertExtensions.cs</Link>
- </Compile>
<Compile Include="$(CommonPath)\System\StringExtensions.cs">
<Link>Common\System\StringExtensions.cs</Link>
</Compile>
diff --git a/src/System.Net.Requests/tests/System.Net.Requests.Tests.csproj b/src/System.Net.Requests/tests/System.Net.Requests.Tests.csproj
index f74fa454cc..3f2b042ec9 100644
--- a/src/System.Net.Requests/tests/System.Net.Requests.Tests.csproj
+++ b/src/System.Net.Requests/tests/System.Net.Requests.Tests.csproj
@@ -12,9 +12,6 @@
<Compile Include="HttpWebResponseTest.cs" />
<Compile Include="RequestStreamTest.cs" />
<Compile Include="WebRequestTest.cs" />
- <Compile Include="$(CommonTestPath)\System\AssertExtensions.cs">
- <Link>Common\System\AssertExtensions.cs</Link>
- </Compile>
<Compile Include="$(CommonTestPath)\System\PlatformDetection.cs">
<Link>Common\System\PlatformDetection.cs</Link>
</Compile>
diff --git a/src/System.Net.Security/src/System/Net/Security/SecureChannel.cs b/src/System.Net.Security/src/System/Net/Security/SecureChannel.cs
index f197c375e0..a1e7e8137c 100644
--- a/src/System.Net.Security/src/System/Net/Security/SecureChannel.cs
+++ b/src/System.Net.Security/src/System/Net/Security/SecureChannel.cs
@@ -20,6 +20,7 @@ namespace System.Net.Security
{
// When reading a frame from the wire first read this many bytes for the header.
internal const int ReadHeaderSize = 5;
+
private SafeFreeCredentials _credentialsHandle;
private SafeDeleteContext _securityContext;
private readonly string _destination;
@@ -48,8 +49,8 @@ namespace System.Net.Security
private bool _refreshCredentialNeeded;
- private readonly Oid _serverAuthOid = new Oid("1.3.6.1.5.5.7.3.1");
- private readonly Oid _clientAuthOid = new Oid("1.3.6.1.5.5.7.3.2");
+ private readonly Oid _serverAuthOid = new Oid("1.3.6.1.5.5.7.3.1", "1.3.6.1.5.5.7.3.1");
+ private readonly Oid _clientAuthOid = new Oid("1.3.6.1.5.5.7.3.2", "1.3.6.1.5.5.7.3.2");
internal SecureChannel(string hostname, bool serverMode, SslProtocols sslProtocols, X509Certificate serverCertificate, X509CertificateCollection clientCertificates, bool remoteCertRequired, bool checkCertName,
bool checkCertRevocationStatus, EncryptionPolicy encryptionPolicy, LocalCertSelectionCallback certSelectionDelegate)
diff --git a/src/System.Net.Security/tests/FunctionalTests/NegotiateStreamStreamToStreamTest.cs b/src/System.Net.Security/tests/FunctionalTests/NegotiateStreamStreamToStreamTest.cs
index 235d8027ba..eff991e320 100644
--- a/src/System.Net.Security/tests/FunctionalTests/NegotiateStreamStreamToStreamTest.cs
+++ b/src/System.Net.Security/tests/FunctionalTests/NegotiateStreamStreamToStreamTest.cs
@@ -21,7 +21,6 @@ namespace System.Net.Security.Tests
protected abstract Task AuthenticateAsClientAsync(NegotiateStream client, NetworkCredential credential, string targetName);
protected abstract Task AuthenticateAsServerAsync(NegotiateStream server);
- [ActiveIssue(18760, TargetFrameworkMonikers.UapAot)] // In order to properly test this, we need UWP-AOT to run within an App Container.
[Fact]
public void NegotiateStream_StreamToStream_Authentication_Success()
{
@@ -68,21 +67,12 @@ namespace System.Net.Security.Tests
IIdentity clientIdentity = server.RemoteIdentity;
Assert.Equal("NTLM", clientIdentity.AuthenticationType);
- if (PlatformDetection.IsUap)
- {
- // TODO #21282: UWP AppContainer issue - clientIdentity.IsAuthenticated == false.
- Assert.Equal(false, clientIdentity.IsAuthenticated);
- }
- else
- {
- Assert.Equal(true, clientIdentity.IsAuthenticated);
- }
+ Assert.Equal(true, clientIdentity.IsAuthenticated);
IdentityValidator.AssertIsCurrentIdentity(clientIdentity);
}
}
- [ActiveIssue(18760, TargetFrameworkMonikers.UapAot)] // In order to properly test this, we need UWP-AOT to run within an App Container.
[Fact]
public void NegotiateStream_StreamToStream_Authentication_TargetName_Success()
{
@@ -132,15 +122,7 @@ namespace System.Net.Security.Tests
IIdentity clientIdentity = server.RemoteIdentity;
Assert.Equal("NTLM", clientIdentity.AuthenticationType);
- if (PlatformDetection.IsUap)
- {
- // TODO #21282: UWP issue - clientIdentity.IsAuthenticated == false.
- Assert.Equal(false, clientIdentity.IsAuthenticated);
- }
- else
- {
- Assert.Equal(true, clientIdentity.IsAuthenticated);
- }
+ Assert.Equal(true, clientIdentity.IsAuthenticated);
IdentityValidator.AssertIsCurrentIdentity(clientIdentity);
}
diff --git a/src/System.Net.Security/tests/FunctionalTests/SslStreamSystemDefaultsTest.cs b/src/System.Net.Security/tests/FunctionalTests/SslStreamSystemDefaultsTest.cs
index 8736d090b3..95018f55fd 100644
--- a/src/System.Net.Security/tests/FunctionalTests/SslStreamSystemDefaultsTest.cs
+++ b/src/System.Net.Security/tests/FunctionalTests/SslStreamSystemDefaultsTest.cs
@@ -13,167 +13,158 @@ namespace System.Net.Security.Tests
{
using Configuration = System.Net.Test.Common.Configuration;
- public class SslStreamSystemDefaultTest
+ public abstract class SslStreamSystemDefaultTest
{
- [Fact]
- public async Task SslStream_DefaultTlsConfigurationSync_Ok()
+ protected readonly SslStream _clientStream;
+ protected readonly SslStream _serverStream;
+
+ public SslStreamSystemDefaultTest()
{
- using (var test = new SyncTest())
- {
- await test.RunTest();
- }
+ var network = new VirtualNetwork();
+ var clientNet = new VirtualNetworkStream(network, isServer:false);
+ var serverNet = new VirtualNetworkStream(network, isServer: true);
+
+ _clientStream = new SslStream(clientNet, false, ClientCertCallback);
+ _serverStream = new SslStream(serverNet, false, ServerCertCallback);
}
- [Fact]
- public async Task SslStream_DefaultTlsConfigurationApm_Ok()
+ protected abstract Task AuthenticateClientAsync(string targetHost, X509CertificateCollection clientCertificates, bool checkCertificateRevocation, SslProtocols? protocols = null);
+ protected abstract Task AuthenticateServerAsync(X509Certificate serverCertificate, bool clientCertificateRequired, bool checkCertificateRevocation, SslProtocols? protocols = null);
+
+ [ActiveIssue(7812, TestPlatforms.Windows)]
+ [Theory]
+ [InlineData(null, null)]
+ [InlineData(SslProtocols.None, null)]
+ [InlineData(null, SslProtocols.None)]
+ [InlineData(SslProtocols.None, SslProtocols.None)]
+ [InlineData(null, SslProtocols.Tls11)]
+ [InlineData(SslProtocols.Tls11, null)]
+ [InlineData(null, SslProtocols.Tls12)]
+ [InlineData(SslProtocols.Tls12, null)]
+ [InlineData(SslProtocols.Tls | SslProtocols.Tls11 | SslProtocols.Tls12, null)]
+ [InlineData(null, SslProtocols.Tls | SslProtocols.Tls11 | SslProtocols.Tls12)]
+ public async Task ClientAndServer_OneOrBothUseDefault_Ok(SslProtocols? clientProtocols, SslProtocols? serverProtocols)
{
- using (var test = new ApmTest())
+ X509Certificate2 serverCertificate = Configuration.Certificates.GetServerCertificate();
+ string serverHost = serverCertificate.GetNameInfo(X509NameType.SimpleName, false);
+ var clientCertificates = new X509CertificateCollection();
+ clientCertificates.Add(Configuration.Certificates.GetClientCertificate());
+
+ var tasks = new Task[2];
+ tasks[0] = AuthenticateClientAsync(serverHost, clientCertificates, checkCertificateRevocation: false, protocols: clientProtocols);
+ tasks[1] = AuthenticateServerAsync(serverCertificate, clientCertificateRequired: true, checkCertificateRevocation: false, protocols: serverProtocols);
+ await await Task.WhenAny(tasks);
+ await Task.WhenAll(tasks);
+
+ if (PlatformDetection.IsWindows && PlatformDetection.WindowsVersion >= 10)
{
- await test.RunTest();
+ Assert.True(_clientStream.HashAlgorithm == HashAlgorithmType.Sha256 ||
+ _clientStream.HashAlgorithm == HashAlgorithmType.Sha384 ||
+ _clientStream.HashAlgorithm == HashAlgorithmType.Sha512);
}
}
- [Fact]
- public async Task SslStream_DefaultTlsConfigurationAsync_Ok()
+ private bool ClientCertCallback(object sender, X509Certificate certificate, X509Chain chain, SslPolicyErrors sslPolicyErrors)
{
- using (var test = new AsyncTest())
+ switch (sslPolicyErrors)
{
- await test.RunTest();
+ case SslPolicyErrors.None:
+ case SslPolicyErrors.RemoteCertificateChainErrors:
+ case SslPolicyErrors.RemoteCertificateNameMismatch:
+ return true;
+ case SslPolicyErrors.RemoteCertificateNotAvailable:
+ default:
+ return false;
}
}
- public abstract class TestBase : IDisposable
+ private bool ServerCertCallback(object sender, X509Certificate certificate, X509Chain chain, SslPolicyErrors sslPolicyErrors)
{
- protected SslStream _clientStream;
- protected SslStream _serverStream;
-
- public TestBase()
+ switch (sslPolicyErrors)
{
- var network = new VirtualNetwork();
- var clientNet = new VirtualNetworkStream(network, false);
- var serverNet = new VirtualNetworkStream(network, true);
-
- _clientStream = new SslStream(clientNet, false, ClientCertCallback);
- _serverStream = new SslStream(serverNet, false, ServerCertCallback);
+ case SslPolicyErrors.None:
+ case SslPolicyErrors.RemoteCertificateChainErrors:
+ case SslPolicyErrors.RemoteCertificateNameMismatch:
+ return true;
+ case SslPolicyErrors.RemoteCertificateNotAvailable:
+ // https://technet.microsoft.com/en-us/library/hh831771.aspx#BKMK_Changes2012R2
+ // Starting with Windows 8, the "Management of trusted issuers for client authentication" has changed:
+ // The behavior to send the Trusted Issuers List by default is off.
+ //
+ // In Windows 7 the Trusted Issuers List is sent within the Server Hello TLS record. This list is built
+ // by the server using certificates from the Trusted Root Authorities certificate store.
+ // The client side will use the Trusted Issuers List, if not empty, to filter proposed certificates.
+ return PlatformDetection.IsWindows7 && !Capability.IsTrustedRootCertificateInstalled();
+ default:
+ return false;
}
+ }
- public async Task RunTest()
- {
- X509Certificate2 serverCertificate = Configuration.Certificates.GetServerCertificate();
- string serverHost = serverCertificate.GetNameInfo(X509NameType.SimpleName, false);
- X509CertificateCollection clientCertificates = new X509CertificateCollection();
- clientCertificates.Add(Configuration.Certificates.GetClientCertificate());
-
- var tasks = new Task[2];
- tasks[0] = AuthenticateClient(serverHost, clientCertificates, checkCertificateRevocation: false);
- tasks[1] = AuthenticateServer(serverCertificate, clientCertificateRequired: true, checkCertificateRevocation: false);
- await Task.WhenAll(tasks);
-
- if (PlatformDetection.IsWindows && PlatformDetection.WindowsVersion >= 10)
- {
- Assert.True(_clientStream.HashAlgorithm == HashAlgorithmType.Sha256 ||
- _clientStream.HashAlgorithm == HashAlgorithmType.Sha384 ||
- _clientStream.HashAlgorithm == HashAlgorithmType.Sha512);
- }
- }
+ public void Dispose()
+ {
+ _clientStream?.Dispose();
+ _serverStream?.Dispose();
+ }
+ }
- private bool ClientCertCallback(object sender, X509Certificate certificate, X509Chain chain, SslPolicyErrors sslPolicyErrors)
+ public sealed class SyncSslStreamSystemDefaultTest : SslStreamSystemDefaultTest
+ {
+ protected override Task AuthenticateClientAsync(string targetHost, X509CertificateCollection clientCertificates, bool checkCertificateRevocation, SslProtocols? protocols) =>
+ Task.Run(() =>
{
- switch (sslPolicyErrors)
+ if (protocols.HasValue)
{
- case SslPolicyErrors.None:
- case SslPolicyErrors.RemoteCertificateChainErrors:
- case SslPolicyErrors.RemoteCertificateNameMismatch:
- return true;
- case SslPolicyErrors.RemoteCertificateNotAvailable:
- default:
- return false;
+ _clientStream.AuthenticateAsClient(targetHost, clientCertificates, protocols.Value, checkCertificateRevocation);
}
- }
-
- private bool ServerCertCallback(object sender, X509Certificate certificate, X509Chain chain, SslPolicyErrors sslPolicyErrors)
- {
- switch (sslPolicyErrors)
+ else
{
- case SslPolicyErrors.None:
- case SslPolicyErrors.RemoteCertificateChainErrors:
- case SslPolicyErrors.RemoteCertificateNameMismatch:
- return true;
- case SslPolicyErrors.RemoteCertificateNotAvailable:
- // https://technet.microsoft.com/en-us/library/hh831771.aspx#BKMK_Changes2012R2
- // Starting with Windows 8, the "Management of trusted issuers for client authentication" has changed:
- // The behavior to send the Trusted Issuers List by default is off.
- //
- // In Windows 7 the Trusted Issuers List is sent within the Server Hello TLS record. This list is built
- // by the server using certificates from the Trusted Root Authorities certificate store.
- // The client side will use the Trusted Issuers List, if not empty, to filter proposed certificates.
- return PlatformDetection.IsWindows7 && !Capability.IsTrustedRootCertificateInstalled();
- default:
- return false;
+ _clientStream.AuthenticateAsClient(targetHost, clientCertificates, checkCertificateRevocation);
}
- }
-
- protected abstract Task AuthenticateClient(string targetHost, X509CertificateCollection clientCertificates, bool checkCertificateRevocation);
-
- protected abstract Task AuthenticateServer(X509Certificate serverCertificate, bool clientCertificateRequired, bool checkCertificateRevocation);
+ });
- public void Dispose()
+ protected override Task AuthenticateServerAsync(X509Certificate serverCertificate, bool clientCertificateRequired, bool checkCertificateRevocation, SslProtocols? protocols) =>
+ Task.Run(() =>
{
- if (_clientStream != null)
+ if (protocols.HasValue)
{
- _clientStream.Dispose();
+ _serverStream.AuthenticateAsServer(serverCertificate, clientCertificateRequired, protocols.Value, checkCertificateRevocation);
}
-
- if (_serverStream != null)
+ else
{
- _serverStream.Dispose();
+ _serverStream.AuthenticateAsServer(serverCertificate, clientCertificateRequired, checkCertificateRevocation);
}
- }
- }
-
- public class SyncTest : TestBase
- {
- protected override Task AuthenticateClient(string targetHost, X509CertificateCollection clientCertificates, bool checkCertificateRevocation)
- {
- return Task.Run( () => { _clientStream.AuthenticateAsClient(targetHost, clientCertificates, checkCertificateRevocation); });
- }
-
- protected override Task AuthenticateServer(X509Certificate serverCertificate, bool clientCertificateRequired, bool checkCertificateRevocation)
- {
- return Task.Run( () => { _serverStream.AuthenticateAsServer(serverCertificate, clientCertificateRequired, checkCertificateRevocation); });
- }
- }
-
- public class ApmTest : TestBase
- {
- protected override Task AuthenticateClient(string targetHost, X509CertificateCollection clientCertificates, bool checkCertificateRevocation)
- {
- return Task.Factory.FromAsync(
- (callback, state) => _clientStream.BeginAuthenticateAsClient(targetHost, clientCertificates, checkCertificateRevocation, callback, state),
- _clientStream.EndAuthenticateAsClient,
- state:null);
- }
-
- protected override Task AuthenticateServer(X509Certificate serverCertificate, bool clientCertificateRequired, bool checkCertificateRevocation)
- {
- return Task.Factory.FromAsync(
- (callback, state) => _serverStream.BeginAuthenticateAsServer(serverCertificate, clientCertificateRequired, checkCertificateRevocation, callback, state),
- _serverStream.EndAuthenticateAsServer,
- state:null);
- }
- }
+ });
+ }
- public class AsyncTest : TestBase
- {
- protected override Task AuthenticateClient(string targetHost, X509CertificateCollection clientCertificates, bool checkCertificateRevocation)
- {
- return _clientStream.AuthenticateAsClientAsync(targetHost, clientCertificates, checkCertificateRevocation);
- }
+ public sealed class ApmSslStreamSystemDefaultTest : SslStreamSystemDefaultTest
+ {
+ protected override Task AuthenticateClientAsync(string targetHost, X509CertificateCollection clientCertificates, bool checkCertificateRevocation, SslProtocols? protocols) =>
+ Task.Factory.FromAsync(
+ (callback, state) => protocols.HasValue ?
+ _clientStream.BeginAuthenticateAsClient(targetHost, clientCertificates, protocols.Value, checkCertificateRevocation, callback, state) :
+ _clientStream.BeginAuthenticateAsClient(targetHost, clientCertificates, checkCertificateRevocation, callback, state),
+ _clientStream.EndAuthenticateAsClient,
+ state: null);
+
+ protected override Task AuthenticateServerAsync(X509Certificate serverCertificate, bool clientCertificateRequired, bool checkCertificateRevocation, SslProtocols? protocols) =>
+ Task.Factory.FromAsync(
+ (callback, state) => protocols.HasValue ?
+ _serverStream.BeginAuthenticateAsServer(serverCertificate, clientCertificateRequired, protocols.Value, checkCertificateRevocation, callback, state) :
+ _serverStream.BeginAuthenticateAsServer(serverCertificate, clientCertificateRequired, checkCertificateRevocation, callback, state),
+ _serverStream.EndAuthenticateAsServer,
+ state: null);
+ }
- protected override Task AuthenticateServer(X509Certificate serverCertificate, bool clientCertificateRequired, bool checkCertificateRevocation)
- {
- return _serverStream.AuthenticateAsServerAsync(serverCertificate, clientCertificateRequired, checkCertificateRevocation);
- }
- }
+ public sealed class AsyncSslStreamSystemDefaultTest : SslStreamSystemDefaultTest
+ {
+ protected override Task AuthenticateClientAsync(string targetHost, X509CertificateCollection clientCertificates, bool checkCertificateRevocation, SslProtocols? protocols) =>
+ protocols.HasValue ?
+ _clientStream.AuthenticateAsClientAsync(targetHost, clientCertificates, protocols.Value, checkCertificateRevocation) :
+ _clientStream.AuthenticateAsClientAsync(targetHost, clientCertificates, checkCertificateRevocation);
+
+ protected override Task AuthenticateServerAsync(X509Certificate serverCertificate, bool clientCertificateRequired, bool checkCertificateRevocation, SslProtocols? protocols) =>
+ protocols.HasValue ?
+ _serverStream.AuthenticateAsServerAsync(serverCertificate, clientCertificateRequired, protocols.Value, checkCertificateRevocation) :
+ _serverStream.AuthenticateAsServerAsync(serverCertificate, clientCertificateRequired, checkCertificateRevocation);
}
}
diff --git a/src/System.Net.Security/tests/FunctionalTests/System.Net.Security.Tests.csproj b/src/System.Net.Security/tests/FunctionalTests/System.Net.Security.Tests.csproj
index 70f26f4c9c..42bfbd468b 100644
--- a/src/System.Net.Security/tests/FunctionalTests/System.Net.Security.Tests.csproj
+++ b/src/System.Net.Security/tests/FunctionalTests/System.Net.Security.Tests.csproj
@@ -47,9 +47,6 @@
<Compile Include="NegotiateStreamKerberosTest.cs" />
<!-- Common test files -->
- <Compile Include="$(CommonTestPath)\System\AssertExtensions.cs">
- <Link>Common\System\AssertExtensions.cs</Link>
- </Compile>
<Compile Include="$(CommonTestPath)\System\PlatformDetection.cs">
<Link>Common\System\PlatformDetection.cs</Link>
</Compile>
diff --git a/src/System.Net.Security/tests/UnitTests/System.Net.Security.Unit.Tests.csproj b/src/System.Net.Security/tests/UnitTests/System.Net.Security.Unit.Tests.csproj
index 19230b7c38..fd8c1b14f2 100644
--- a/src/System.Net.Security/tests/UnitTests/System.Net.Security.Unit.Tests.csproj
+++ b/src/System.Net.Security/tests/UnitTests/System.Net.Security.Unit.Tests.csproj
@@ -27,9 +27,6 @@
<Compile Include="Fakes\FakeAuthenticatedStream.cs" />
<Compile Include="Fakes\FakeLazyAsyncResult.cs" />
<!-- Common test files -->
- <Compile Include="$(CommonTestPath)\System\AssertExtensions.cs">
- <Link>Common\System\AssertExtensions.cs</Link>
- </Compile>
<Compile Include="$(CommonTestPath)\System\Net\SslProtocolSupport.cs">
<Link>CommonTest\System\Net\SslProtocolSupport.cs</Link>
</Compile>
diff --git a/src/System.Net.ServicePoint/tests/System.Net.ServicePoint.Tests.csproj b/src/System.Net.ServicePoint/tests/System.Net.ServicePoint.Tests.csproj
index c87dafdc5e..de1881acca 100644
--- a/src/System.Net.ServicePoint/tests/System.Net.ServicePoint.Tests.csproj
+++ b/src/System.Net.ServicePoint/tests/System.Net.ServicePoint.Tests.csproj
@@ -10,9 +10,6 @@
<PropertyGroup Condition="'$(Configuration)|$(Platform)'=='netcoreapp-Release|AnyCPU'" />
<ItemGroup>
<Compile Include="ServicePointManagerTest.cs" />
- <Compile Include="$(CommonTestPath)\System\AssertExtensions.cs">
- <Link>Common\System\AssertExtensions.cs</Link>
- </Compile>
</ItemGroup>
<ItemGroup Condition="'$(TargetGroup)'=='netcoreapp'">
<!-- TODO #13070: Add net463 to the condition after the TFM gets updated to the actual .Net 4.6.3.-->
diff --git a/src/System.Net.Sockets/src/System.Net.Sockets.csproj b/src/System.Net.Sockets/src/System.Net.Sockets.csproj
index f830d33009..ea149da00b 100644
--- a/src/System.Net.Sockets/src/System.Net.Sockets.csproj
+++ b/src/System.Net.Sockets/src/System.Net.Sockets.csproj
@@ -5,7 +5,6 @@
<AssemblyName>System.Net.Sockets</AssemblyName>
<ProjectGuid>{43311AFB-D7C4-4E5A-B1DE-855407F90D1B}</ProjectGuid>
<AllowUnsafeBlocks>true</AllowUnsafeBlocks>
- <DefineConstants Condition="'$(TargetGroup)' == 'uap'">$(DefineConstants);uap</DefineConstants>
<IsPartialFacadeAssembly Condition="'$(TargetGroup)' == 'netfx'">true</IsPartialFacadeAssembly>
<OmitResources Condition="'$(TargetGroup)' == 'netfx'">true</OmitResources>
</PropertyGroup>
@@ -150,6 +149,9 @@
<Compile Include="$(CommonPath)\System\Net\SafeCloseSocket.Windows.cs">
<Link>Common\System\Net\SafeCloseSocket.Windows.cs</Link>
</Compile>
+ <Compile Include="$(CommonPath)\System\Net\ContextAwareResult.Windows.cs">
+ <Link>Common\System\Net\ContextAwareResult.Windows.cs</Link>
+ </Compile>
<Compile Include="$(CommonPath)\System\Net\SocketAddressPal.Windows.cs">
<Link>Common\System\Net\SocketAddressPal.Windows.cs</Link>
</Compile>
@@ -247,28 +249,13 @@
<Compile Include="$(CommonPath)\Interop\Windows\Winsock\WSABuffer.cs">
<Link>Interop\Windows\Winsock\WSABuffer.cs</Link>
</Compile>
- </ItemGroup>
- <!-- Windows : Win32 only -->
- <ItemGroup Condition="'$(TargetsWindows)' == 'true' AND '$(TargetGroup)' != 'uap' AND '$(TargetGroup)' != 'netfx'">
<Compile Include="$(CommonPath)\Interop\Windows\kernel32\Interop.SetFileCompletionNotificationModes.cs">
<Link>Interop\Windows\kernel32\Interop.SetFileCompletionNotificationModes.cs</Link>
</Compile>
- <Compile Include="$(CommonPath)\System\Net\ContextAwareResult.Windows.cs">
- <Link>Common\System\Net\ContextAwareResult.Windows.cs</Link>
- </Compile>
<Compile Include="$(CommonPath)\System\Net\CompletionPortHelper.Windows.cs">
<Link>Common\System\Net\CompletionPortHelper.Windows.cs</Link>
</Compile>
</ItemGroup>
- <!-- Windows : Win32 + WinRT -->
- <ItemGroup Condition="'$(TargetsWindows)' == 'true' AND '$(TargetGroup)' == 'uap'">
- <Compile Include="$(CommonPath)\System\Net\ContextAwareResult.Uap.cs">
- <Link>Common\System\Net\ContextAwareResult.Uap.cs</Link>
- </Compile>
- <Compile Include="$(CommonPath)\System\Net\CompletionPortHelper.Uap.cs">
- <Link>Common\System\Net\CompletionPortHelper.Uap.cs</Link>
- </Compile>
- </ItemGroup>
<ItemGroup Condition=" '$(TargetsUnix)' == 'true' ">
<Compile Include="System\Net\Sockets\AcceptOverlappedAsyncResult.Unix.cs" />
<Compile Include="System\Net\Sockets\BaseOverlappedAsyncResult.Unix.cs" />
diff --git a/src/System.Net.Sockets/src/System/Net/Sockets/SocketAsyncEventArgs.Windows.cs b/src/System.Net.Sockets/src/System/Net/Sockets/SocketAsyncEventArgs.Windows.cs
index 7998edc9ff..feadd0b32a 100644
--- a/src/System.Net.Sockets/src/System/Net/Sockets/SocketAsyncEventArgs.Windows.cs
+++ b/src/System.Net.Sockets/src/System/Net/Sockets/SocketAsyncEventArgs.Windows.cs
@@ -25,13 +25,10 @@ namespace System.Net.Sockets
// Internal buffers for WSARecvMsg
private byte[] _wsaMessageBuffer;
private GCHandle _wsaMessageBufferGCHandle;
- private IntPtr _ptrWSAMessageBuffer;
private byte[] _controlBuffer;
private GCHandle _controlBufferGCHandle;
- private IntPtr _ptrControlBuffer;
private WSABuffer[] _wsaRecvMsgWSABufferArray;
private GCHandle _wsaRecvMsgWSABufferArrayGCHandle;
- private IntPtr _ptrWSARecvMsgWSABufferArray;
// Internal buffer for AcceptEx when Buffer not supplied.
private IntPtr _ptrAcceptBuffer;
@@ -39,8 +36,6 @@ namespace System.Net.Sockets
// Internal SocketAddress buffer
private GCHandle _socketAddressGCHandle;
private Internals.SocketAddress _pinnedSocketAddress;
- private IntPtr _ptrSocketAddressBuffer;
- private IntPtr _ptrSocketAddressBufferSize;
// SendPacketsElements property variables.
private SendPacketsElement[] _sendPacketsElementsInternal;
@@ -51,7 +46,6 @@ namespace System.Net.Sockets
// Internal variables for SendPackets
private FileStream[] _sendPacketsFileStreams;
private SafeHandle[] _sendPacketsFileHandles;
- private IntPtr _ptrSendPacketsDescriptor;
// Overlapped object related variables.
private PreAllocatedOverlapped _preAllocatedOverlapped;
@@ -228,7 +222,7 @@ namespace System.Net.Sockets
bool success = socket.ConnectEx(
handle,
- _ptrSocketAddressBuffer,
+ PtrSocketAddressBuffer,
_socketAddress.Size,
_ptrSingleBuffer,
Count,
@@ -370,8 +364,8 @@ namespace System.Net.Sockets
1,
out bytesTransferred,
ref flags,
- _ptrSocketAddressBuffer,
- _ptrSocketAddressBufferSize,
+ PtrSocketAddressBuffer,
+ PtrSocketAddressBufferSize,
overlapped,
IntPtr.Zero);
}
@@ -383,8 +377,8 @@ namespace System.Net.Sockets
_bufferListInternal.Count,
out bytesTransferred,
ref flags,
- _ptrSocketAddressBuffer,
- _ptrSocketAddressBufferSize,
+ PtrSocketAddressBuffer,
+ PtrSocketAddressBufferSize,
overlapped,
IntPtr.Zero);
}
@@ -409,12 +403,18 @@ namespace System.Net.Sockets
// WSAMsg also contains a single WSABuffer describing a control buffer.
PinSocketAddressBuffer();
- // Create and pin a WSAMessageBuffer if none already.
+ // Create a WSAMessageBuffer if none exists yet.
if (_wsaMessageBuffer == null)
{
+ Debug.Assert(!_wsaMessageBufferGCHandle.IsAllocated);
_wsaMessageBuffer = new byte[sizeof(Interop.Winsock.WSAMsg)];
+ }
+
+ // And ensure the WSAMessageBuffer is appropriately pinned.
+ Debug.Assert(!_wsaMessageBufferGCHandle.IsAllocated || _wsaMessageBufferGCHandle.Target == _wsaMessageBuffer);
+ if (!_wsaMessageBufferGCHandle.IsAllocated)
+ {
_wsaMessageBufferGCHandle = GCHandle.Alloc(_wsaMessageBuffer, GCHandleType.Pinned);
- _ptrWSAMessageBuffer = Marshal.UnsafeAddrOfPinnedArrayElement(_wsaMessageBuffer, 0);
}
// Create and pin an appropriately sized control buffer if none already
@@ -438,13 +438,10 @@ namespace System.Net.Sockets
}
_controlBuffer = new byte[sizeof(Interop.Winsock.ControlDataIPv6)];
}
- if (!_controlBufferGCHandle.IsAllocated)
- {
- _controlBufferGCHandle = GCHandle.Alloc(_controlBuffer, GCHandleType.Pinned);
- _ptrControlBuffer = Marshal.UnsafeAddrOfPinnedArrayElement(_controlBuffer, 0);
- }
- // If single buffer we need a pinned 1 element WSABuffer.
+ // If single buffer we need a single element WSABuffer.
+ WSABuffer[] wsaRecvMsgWSABufferArray;
+ uint wsaRecvMsgWSABufferCount;
if (_buffer != null)
{
if (_wsaRecvMsgWSABufferArray == null)
@@ -453,41 +450,69 @@ namespace System.Net.Sockets
}
_wsaRecvMsgWSABufferArray[0].Pointer = _ptrSingleBuffer;
_wsaRecvMsgWSABufferArray[0].Length = _count;
- _wsaRecvMsgWSABufferArrayGCHandle = GCHandle.Alloc(_wsaRecvMsgWSABufferArray, GCHandleType.Pinned);
- _ptrWSARecvMsgWSABufferArray = Marshal.UnsafeAddrOfPinnedArrayElement(_wsaRecvMsgWSABufferArray, 0);
+ wsaRecvMsgWSABufferArray = _wsaRecvMsgWSABufferArray;
+ wsaRecvMsgWSABufferCount = 1;
}
else
{
- // Just pin the multi-buffer WSABuffer.
- _wsaRecvMsgWSABufferArrayGCHandle = GCHandle.Alloc(_wsaBufferArray, GCHandleType.Pinned);
- _ptrWSARecvMsgWSABufferArray = Marshal.UnsafeAddrOfPinnedArrayElement(_wsaBufferArray, 0);
+ // Use the multi-buffer WSABuffer.
+ wsaRecvMsgWSABufferArray = _wsaBufferArray;
+ wsaRecvMsgWSABufferCount = (uint)_bufferListInternal.Count;
+ }
+
+ // Ensure the array is pinned.
+ Debug.Assert(!_wsaRecvMsgWSABufferArrayGCHandle.IsAllocated || _wsaRecvMsgWSABufferArrayGCHandle.Target == wsaRecvMsgWSABufferArray);
+ if (!_wsaRecvMsgWSABufferArrayGCHandle.IsAllocated)
+ {
+ _wsaRecvMsgWSABufferArrayGCHandle = GCHandle.Alloc(wsaRecvMsgWSABufferArray, GCHandleType.Pinned);
}
// Fill in WSAMessageBuffer.
unsafe
{
- Interop.Winsock.WSAMsg* pMessage = (Interop.Winsock.WSAMsg*)_ptrWSAMessageBuffer; ;
- pMessage->socketAddress = _ptrSocketAddressBuffer;
+ Interop.Winsock.WSAMsg* pMessage = (Interop.Winsock.WSAMsg*)PtrWSAMessageBuffer;
+ pMessage->socketAddress = PtrSocketAddressBuffer;
pMessage->addressLength = (uint)_socketAddress.Size;
- pMessage->buffers = _ptrWSARecvMsgWSABufferArray;
- if (_buffer != null)
+ fixed (void* ptrWSARecvMsgWSABufferArray = &wsaRecvMsgWSABufferArray[0])
{
- pMessage->count = (uint)1;
- }
- else
- {
- pMessage->count = (uint)_bufferListInternal.Count;
+ pMessage->buffers = (IntPtr)ptrWSARecvMsgWSABufferArray;
}
+ pMessage->count = wsaRecvMsgWSABufferCount;
if (_controlBuffer != null)
{
- pMessage->controlBuffer.Pointer = _ptrControlBuffer;
+ Debug.Assert(_controlBuffer.Length > 0);
+ Debug.Assert(!_controlBufferGCHandle.IsAllocated || _controlBufferGCHandle.Target == _controlBuffer);
+ if (!_controlBufferGCHandle.IsAllocated)
+ {
+ _controlBufferGCHandle = GCHandle.Alloc(_controlBuffer, GCHandleType.Pinned);
+ }
+
+ fixed (void* ptrControlBuffer = &_controlBuffer[0])
+ {
+ pMessage->controlBuffer.Pointer = (IntPtr)ptrControlBuffer;
+ }
pMessage->controlBuffer.Length = _controlBuffer.Length;
}
pMessage->flags = _socketFlags;
}
}
+ private unsafe IntPtr PtrWSAMessageBuffer
+ {
+ get
+ {
+ Debug.Assert(_wsaMessageBuffer != null);
+ Debug.Assert(_wsaMessageBuffer.Length == sizeof(Interop.Winsock.WSAMsg));
+ Debug.Assert(_wsaMessageBufferGCHandle.IsAllocated);
+ Debug.Assert(_wsaMessageBufferGCHandle.Target == _wsaMessageBuffer);
+ fixed (void* ptrWSAMessageBuffer = &_wsaMessageBuffer[0])
+ {
+ return (IntPtr)ptrWSAMessageBuffer;
+ }
+ }
+ }
+
internal unsafe SocketError DoOperationReceiveMessageFrom(Socket socket, SafeCloseSocket handle)
{
SocketError socketError = SocketError.Success;
@@ -498,7 +523,7 @@ namespace System.Net.Sockets
socketError = socket.WSARecvMsg(
handle,
- _ptrWSAMessageBuffer,
+ PtrWSAMessageBuffer,
out bytesTransferred,
overlapped,
IntPtr.Zero);
@@ -663,13 +688,24 @@ namespace System.Net.Sockets
internal unsafe SocketError DoOperationSendPackets(Socket socket, SafeCloseSocket handle)
{
+ Debug.Assert(_sendPacketsDescriptor != null);
+ Debug.Assert(_sendPacketsDescriptor.Length > 0);
+ Debug.Assert(_multipleBufferGCHandles != null);
+ Debug.Assert(_multipleBufferGCHandles[0].IsAllocated);
+ Debug.Assert(_multipleBufferGCHandles[0].Target == _sendPacketsDescriptor);
+ IntPtr ptrSendPacketsDescriptor;
+ fixed (void* p = &_sendPacketsDescriptor[0])
+ {
+ ptrSendPacketsDescriptor = (IntPtr)p;
+ }
+
SocketError socketError = SocketError.Success;
NativeOverlapped* overlapped = AllocateNativeOverlapped();
try
{
bool result = socket.TransmitPackets(
handle,
- _ptrSendPacketsDescriptor,
+ ptrSendPacketsDescriptor,
_sendPacketsDescriptor.Length,
_sendPacketsSendSize,
overlapped,
@@ -721,7 +757,7 @@ namespace System.Net.Sockets
1,
out bytesTransferred,
_socketFlags,
- _ptrSocketAddressBuffer,
+ PtrSocketAddressBuffer,
_socketAddress.Size,
overlapped,
IntPtr.Zero);
@@ -734,7 +770,7 @@ namespace System.Net.Sockets
_bufferListInternal.Count,
out bytesTransferred,
_socketFlags,
- _ptrSocketAddressBuffer,
+ PtrSocketAddressBuffer,
_socketAddress.Size,
overlapped,
IntPtr.Zero);
@@ -865,11 +901,27 @@ namespace System.Net.Sockets
// Pin down the new one.
_socketAddressGCHandle = GCHandle.Alloc(_socketAddress.Buffer, GCHandleType.Pinned);
_socketAddress.CopyAddressSizeIntoBuffer();
- _ptrSocketAddressBuffer = Marshal.UnsafeAddrOfPinnedArrayElement(_socketAddress.Buffer, 0);
- _ptrSocketAddressBufferSize = Marshal.UnsafeAddrOfPinnedArrayElement(_socketAddress.Buffer, _socketAddress.GetAddressSizeOffset());
_pinnedSocketAddress = _socketAddress;
}
+ private unsafe IntPtr PtrSocketAddressBuffer
+ {
+ get
+ {
+ Debug.Assert(_pinnedSocketAddress != null);
+ Debug.Assert(_pinnedSocketAddress.Buffer != null);
+ Debug.Assert(_pinnedSocketAddress.Buffer.Length > 0);
+ Debug.Assert(_socketAddressGCHandle.IsAllocated);
+ Debug.Assert(_socketAddressGCHandle.Target == _pinnedSocketAddress.Buffer);
+ fixed (void* ptrSocketAddressBuffer = &_pinnedSocketAddress.Buffer[0])
+ {
+ return (IntPtr)ptrSocketAddressBuffer;
+ }
+ }
+ }
+
+ private IntPtr PtrSocketAddressBufferSize => PtrSocketAddressBuffer + _socketAddress.GetAddressSizeOffset();
+
// Cleans up any existing Overlapped object and related state variables.
private void FreeOverlapped()
{
@@ -917,19 +969,16 @@ namespace System.Net.Sockets
if (_wsaMessageBufferGCHandle.IsAllocated)
{
_wsaMessageBufferGCHandle.Free();
- _ptrWSAMessageBuffer = IntPtr.Zero;
}
if (_wsaRecvMsgWSABufferArrayGCHandle.IsAllocated)
{
_wsaRecvMsgWSABufferArrayGCHandle.Free();
- _ptrWSARecvMsgWSABufferArray = IntPtr.Zero;
}
if (_controlBufferGCHandle.IsAllocated)
{
_controlBufferGCHandle.Free();
- _ptrControlBuffer = IntPtr.Zero;
}
}
@@ -1061,9 +1110,6 @@ namespace System.Net.Sockets
}
}
- // Get pointer to native descriptor.
- _ptrSendPacketsDescriptor = Marshal.UnsafeAddrOfPinnedArrayElement(_sendPacketsDescriptor, 0);
-
// Fill in native descriptor.
int descriptorIndex = 0;
int fileIndex = 0;
@@ -1223,7 +1269,7 @@ namespace System.Net.Sockets
private unsafe int GetSocketAddressSize()
{
- return *(int*)_ptrSocketAddressBufferSize;
+ return *(int*)PtrSocketAddressBufferSize;
}
private unsafe void FinishOperationReceiveMessageFrom()
diff --git a/src/System.Net.Sockets/src/System/Net/Sockets/SocketPal.Unix.cs b/src/System.Net.Sockets/src/System/Net/Sockets/SocketPal.Unix.cs
index c5c2153707..213d99916a 100644
--- a/src/System.Net.Sockets/src/System/Net/Sockets/SocketPal.Unix.cs
+++ b/src/System.Net.Sockets/src/System/Net/Sockets/SocketPal.Unix.cs
@@ -16,6 +16,7 @@ namespace System.Net.Sockets
{
public const bool SupportsMultipleConnectAttempts = false;
private static readonly bool SupportsDualModeIPv4PacketInfo = GetPlatformSupportsDualModeIPv4PacketInfo();
+ private static readonly byte[] s_peekBuffer = new byte[1];
private static bool GetPlatformSupportsDualModeIPv4PacketInfo()
{
@@ -620,23 +621,13 @@ namespace System.Net.Sockets
{
// Special case a receive of 0 bytes into a single buffer. A common pattern is to ReceiveAsync 0 bytes in order
// to be asynchronously notified when data is available, without needing to dedicate a buffer. Some platforms (e.g. macOS),
- // however, special-case a receive of 0 to always succeed immediately even if data isn't available. As such, we treat 0
- // specially, checking whether any bytes are available rather than doing an actual receive.
- receivedFlags = SocketFlags.None;
- received = -1;
-
- int available = 0;
- errno = Interop.Sys.GetBytesAvailable(socket, &available);
- if (errno == Interop.Error.SUCCESS)
+ // however complete a 0-byte read successfully when data isn't available, as the request can logically be satisfied
+ // synchronously. As such, we treat 0 specially, and perform a 1-byte peek.
+ received = Receive(socket, flags | SocketFlags.Peek, s_peekBuffer, 0, s_peekBuffer.Length, socketAddress, ref socketAddressLen, out receivedFlags, out errno);
+ if (received > 0)
{
- if (available > 0)
- {
- bytesReceived = 0;
- errorCode = SocketError.Success;
- return true;
- }
-
- errno = Interop.Error.EAGAIN; // simulate a receive with no data available
+ // Peeked for 1-byte, but the actual request was for 0.
+ received = 0;
}
}
else
diff --git a/src/System.Net.Sockets/tests/FunctionalTests/ReceiveMessageFromAsync.cs b/src/System.Net.Sockets/tests/FunctionalTests/ReceiveMessageFromAsync.cs
index 248569ebab..64b6d19363 100644
--- a/src/System.Net.Sockets/tests/FunctionalTests/ReceiveMessageFromAsync.cs
+++ b/src/System.Net.Sockets/tests/FunctionalTests/ReceiveMessageFromAsync.cs
@@ -10,96 +10,52 @@ namespace System.Net.Sockets.Tests
{
public class ReceiveMessageFromAsync
{
- public void OnCompleted(object sender, SocketAsyncEventArgs args)
- {
- EventWaitHandle handle = (EventWaitHandle)args.UserToken;
- handle.Set();
- }
-
[OuterLoop] // TODO: Issue #11345
- [Fact]
- public void Success_IPv4()
+ [Theory]
+ [InlineData(false, false)]
+ [InlineData(false, true)]
+ [InlineData(true, false)]
+ [InlineData(true, true)]
+ public void ReceiveSentMessages_SocketAsyncEventArgs_Success(bool ipv4, bool changeReceiveBufferEachCall)
{
- ManualResetEvent completed = new ManualResetEvent(false);
+ const int DataLength = 1024;
+ AddressFamily family = ipv4 ? AddressFamily.InterNetwork : AddressFamily.InterNetworkV6;
+ IPAddress loopback = ipv4 ? IPAddress.Loopback : IPAddress.IPv6Loopback;
- if (Socket.OSSupportsIPv4)
+ var completed = new ManualResetEventSlim(false);
+ using (var sender = new Socket(family, SocketType.Dgram, ProtocolType.Udp))
+ using (var receiver = new Socket(family, SocketType.Dgram, ProtocolType.Udp))
{
- using (Socket receiver = new Socket(AddressFamily.InterNetwork, SocketType.Dgram, ProtocolType.Udp))
- {
- int port = receiver.BindToAnonymousPort(IPAddress.Loopback);
- receiver.SetSocketOption(SocketOptionLevel.IP, SocketOptionName.PacketInformation, true);
+ sender.Bind(new IPEndPoint(loopback, 0));
+ receiver.SetSocketOption(ipv4 ? SocketOptionLevel.IP : SocketOptionLevel.IPv6, SocketOptionName.PacketInformation, true);
+ int port = receiver.BindToAnonymousPort(loopback);
- Socket sender = new Socket(AddressFamily.InterNetwork, SocketType.Dgram, ProtocolType.Udp);
- sender.Bind(new IPEndPoint(IPAddress.Loopback, 0));
+ var args = new SocketAsyncEventArgs() { RemoteEndPoint = new IPEndPoint(ipv4 ? IPAddress.Any : IPAddress.IPv6Any, 0) };
+ args.Completed += (s,e) => completed.Set();
+ args.SetBuffer(new byte[DataLength], 0, DataLength);
+ for (int iters = 0; iters < 5; iters++)
+ {
for (int i = 0; i < TestSettings.UDPRedundancy; i++)
{
- sender.SendTo(new byte[1024], new IPEndPoint(IPAddress.Loopback, port));
+ sender.SendTo(new byte[DataLength], new IPEndPoint(loopback, port));
}
- SocketAsyncEventArgs args = new SocketAsyncEventArgs();
- args.RemoteEndPoint = new IPEndPoint(IPAddress.Any, 0);
- args.SetBuffer(new byte[1024], 0, 1024);
- args.Completed += OnCompleted;
- args.UserToken = completed;
-
- bool pending = receiver.ReceiveMessageFromAsync(args);
- if (!pending)
- {
- OnCompleted(null, args);
- }
-
- Assert.True(completed.WaitOne(TestSettings.PassingTestTimeout), "Timeout while waiting for connection");
-
- Assert.Equal(1024, args.BytesTransferred);
- Assert.Equal(sender.LocalEndPoint, args.RemoteEndPoint);
- Assert.Equal(((IPEndPoint)sender.LocalEndPoint).Address, args.ReceiveMessageFromPacketInfo.Address);
-
- sender.Dispose();
- }
- }
- }
-
- [OuterLoop] // TODO: Issue #11345
- [Fact]
- public void Success_IPv6()
- {
- ManualResetEvent completed = new ManualResetEvent(false);
-
- if (Socket.OSSupportsIPv6)
- {
- using (Socket receiver = new Socket(AddressFamily.InterNetworkV6, SocketType.Dgram, ProtocolType.Udp))
- {
- int port = receiver.BindToAnonymousPort(IPAddress.IPv6Loopback);
- receiver.SetSocketOption(SocketOptionLevel.IPv6, SocketOptionName.PacketInformation, true);
-
- Socket sender = new Socket(AddressFamily.InterNetworkV6, SocketType.Dgram, ProtocolType.Udp);
- sender.Bind(new IPEndPoint(IPAddress.IPv6Loopback, 0));
-
- for (int i = 0; i < TestSettings.UDPRedundancy; i++)
+ if (changeReceiveBufferEachCall)
{
- sender.SendTo(new byte[1024], new IPEndPoint(IPAddress.IPv6Loopback, port));
+ args.SetBuffer(new byte[DataLength], 0, DataLength);
}
- SocketAsyncEventArgs args = new SocketAsyncEventArgs();
- args.RemoteEndPoint = new IPEndPoint(IPAddress.IPv6Any, 0);
- args.SetBuffer(new byte[1024], 0, 1024);
- args.Completed += OnCompleted;
- args.UserToken = completed;
-
- bool pending = receiver.ReceiveMessageFromAsync(args);
- if (!pending)
+ if (!receiver.ReceiveMessageFromAsync(args))
{
- OnCompleted(null, args);
+ completed.Set();
}
+ Assert.True(completed.Wait(TestSettings.PassingTestTimeout), "Timeout while waiting for connection");
+ completed.Reset();
- Assert.True(completed.WaitOne(TestSettings.PassingTestTimeout), "Timeout while waiting for connection");
-
- Assert.Equal(1024, args.BytesTransferred);
+ Assert.Equal(DataLength, args.BytesTransferred);
Assert.Equal(sender.LocalEndPoint, args.RemoteEndPoint);
Assert.Equal(((IPEndPoint)sender.LocalEndPoint).Address, args.ReceiveMessageFromPacketInfo.Address);
-
- sender.Dispose();
}
}
}
@@ -108,30 +64,33 @@ namespace System.Net.Sockets.Tests
[Theory]
[InlineData(false)]
[InlineData(true)]
- public async Task Task_Success(bool ipv4)
+ public async Task ReceiveSentMessages_Tasks_Success(bool ipv4)
{
+ const int DataLength = 1024;
AddressFamily family = ipv4 ? AddressFamily.InterNetwork : AddressFamily.InterNetworkV6;
IPAddress loopback = ipv4 ? IPAddress.Loopback : IPAddress.IPv6Loopback;
- using (Socket receiver = new Socket(family, SocketType.Dgram, ProtocolType.Udp))
- using (Socket sender = new Socket(family, SocketType.Dgram, ProtocolType.Udp))
+ using (var receiver = new Socket(family, SocketType.Dgram, ProtocolType.Udp))
+ using (var sender = new Socket(family, SocketType.Dgram, ProtocolType.Udp))
{
- int port = receiver.BindToAnonymousPort(loopback);
- receiver.SetSocketOption(ipv4 ? SocketOptionLevel.IP : SocketOptionLevel.IPv6, SocketOptionName.PacketInformation, true);
-
sender.Bind(new IPEndPoint(loopback, 0));
+ receiver.SetSocketOption(ipv4 ? SocketOptionLevel.IP : SocketOptionLevel.IPv6, SocketOptionName.PacketInformation, true);
+ int port = receiver.BindToAnonymousPort(loopback);
- for (int i = 0; i < TestSettings.UDPRedundancy; i++)
+ for (int iters = 0; iters < 5; iters++)
{
- sender.SendTo(new byte[1024], new IPEndPoint(loopback, port));
- }
+ for (int i = 0; i < TestSettings.UDPRedundancy; i++)
+ {
+ sender.SendTo(new byte[DataLength], new IPEndPoint(loopback, port));
+ }
- SocketReceiveMessageFromResult result = await receiver.ReceiveMessageFromAsync(
- new ArraySegment<byte>(new byte[1024], 0, 1024), SocketFlags.None,
- new IPEndPoint(ipv4 ? IPAddress.Any : IPAddress.IPv6Any, 0));
- Assert.Equal(1024, result.ReceivedBytes);
- Assert.Equal(sender.LocalEndPoint, result.RemoteEndPoint);
- Assert.Equal(((IPEndPoint)sender.LocalEndPoint).Address, result.PacketInformation.Address);
+ SocketReceiveMessageFromResult result = await receiver.ReceiveMessageFromAsync(
+ new ArraySegment<byte>(new byte[DataLength], 0, DataLength), SocketFlags.None,
+ new IPEndPoint(ipv4 ? IPAddress.Any : IPAddress.IPv6Any, 0));
+ Assert.Equal(DataLength, result.ReceivedBytes);
+ Assert.Equal(sender.LocalEndPoint, result.RemoteEndPoint);
+ Assert.Equal(((IPEndPoint)sender.LocalEndPoint).Address, result.PacketInformation.Address);
+ }
}
}
}
diff --git a/src/System.Net.Sockets/tests/FunctionalTests/SendReceive.cs b/src/System.Net.Sockets/tests/FunctionalTests/SendReceive.cs
index 200947a1db..0ca741d082 100644
--- a/src/System.Net.Sockets/tests/FunctionalTests/SendReceive.cs
+++ b/src/System.Net.Sockets/tests/FunctionalTests/SendReceive.cs
@@ -699,6 +699,35 @@ namespace System.Net.Sockets.Tests
}
}
+ [Fact]
+ public async Task Receive0ByteReturns_WhenPeerDisconnects()
+ {
+ using (Socket listener = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp))
+ using (Socket client = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp))
+ {
+ listener.Bind(new IPEndPoint(IPAddress.Loopback, 0));
+ listener.Listen(1);
+
+ Task<Socket> acceptTask = AcceptAsync(listener);
+ await Task.WhenAll(
+ acceptTask,
+ ConnectAsync(client, new IPEndPoint(IPAddress.Loopback, ((IPEndPoint)listener.LocalEndPoint).Port)));
+
+ using (Socket server = await acceptTask)
+ {
+ // Have the client do a 0-byte receive. No data is available, so this should pend.
+ Task<int> receive = ReceiveAsync(client, new ArraySegment<byte>(Array.Empty<byte>()));
+ Assert.False(receive.IsCompleted, $"Task should not have been completed, was {receive.Status}");
+
+ // Disconnect the client
+ server.Close();
+
+ // The client should now wake up
+ Assert.Equal(0, await receive);
+ }
+ }
+ }
+
[Theory]
[InlineData(false, 1)]
[InlineData(true, 1)]
diff --git a/src/System.Net.Sockets/tests/FunctionalTests/System.Net.Sockets.Tests.csproj b/src/System.Net.Sockets/tests/FunctionalTests/System.Net.Sockets.Tests.csproj
index 2d5baf01d5..96e6f63ae0 100644
--- a/src/System.Net.Sockets/tests/FunctionalTests/System.Net.Sockets.Tests.csproj
+++ b/src/System.Net.Sockets/tests/FunctionalTests/System.Net.Sockets.Tests.csproj
@@ -71,9 +71,6 @@
<Link>SocketCommon\SocketImplementationType.cs</Link>
</Compile>
<!-- Common test files -->
- <Compile Include="$(CommonTestPath)\System\AssertExtensions.cs">
- <Link>Common\System\AssertExtensions.cs</Link>
- </Compile>
<Compile Include="$(CommonTestPath)\System\PlatformDetection.cs">
<Link>Common\System\PlatformDetection.cs</Link>
</Compile>
diff --git a/src/System.Net.WebClient/tests/System.Net.WebClient.Tests.csproj b/src/System.Net.WebClient/tests/System.Net.WebClient.Tests.csproj
index 74a4827cb6..7d65e9ca30 100644
--- a/src/System.Net.WebClient/tests/System.Net.WebClient.Tests.csproj
+++ b/src/System.Net.WebClient/tests/System.Net.WebClient.Tests.csproj
@@ -8,9 +8,6 @@
<PropertyGroup Condition="'$(Configuration)|$(Platform)'=='netstandard-Release|AnyCPU'" />
<ItemGroup>
<Compile Include="WebClientTest.cs" />
- <Compile Include="$(CommonTestPath)\System\AssertExtensions.cs">
- <Link>Common\System\AssertExtensions.cs</Link>
- </Compile>
<Compile Include="$(CommonTestPath)\System\PlatformDetection.cs">
<Link>Common\System\PlatformDetection.cs</Link>
</Compile>
diff --git a/src/System.Net.WebClient/tests/WebClientTest.cs b/src/System.Net.WebClient/tests/WebClientTest.cs
index b12ce47b30..64efdb0509 100644
--- a/src/System.Net.WebClient/tests/WebClientTest.cs
+++ b/src/System.Net.WebClient/tests/WebClientTest.cs
@@ -364,7 +364,6 @@ namespace System.Net.Tests
}
}
- [ActiveIssue(20141, TargetFrameworkMonikers.UapAot)]
[Fact]
public static async Task ResponseHeaders_ContainsHeadersAfterOperation()
{
@@ -388,8 +387,6 @@ namespace System.Net.Tests
Assert.Equal("ArbitraryValue", wc.ResponseHeaders["ArbitraryHeader"]);
}
- [ActiveIssue(20141, TargetFrameworkMonikers.UapAot)]
- [ActiveIssue(18680)]
[OuterLoop("Networking test talking to remote server: issue #11345")]
[Theory]
[InlineData("Connection", "close")]
@@ -401,7 +398,6 @@ namespace System.Net.Tests
await Assert.ThrowsAsync<WebException>(() => wc.DownloadStringTaskAsync(System.Net.Test.Common.Configuration.Http.RemoteEchoServer));
}
- [ActiveIssue(20141, TargetFrameworkMonikers.UapAot)]
[OuterLoop("Networking test talking to remote server: issue #11345")]
[Theory]
[InlineData("http://localhost", true)]
@@ -420,7 +416,6 @@ namespace System.Net.Tests
}
}
- [ActiveIssue(20141, TargetFrameworkMonikers.UapAot)]
[Fact]
public static async Task RequestHeaders_SpecialHeaders_RequestSucceeds()
{
@@ -444,7 +439,6 @@ namespace System.Net.Tests
});
}
- [ActiveIssue(20141, TargetFrameworkMonikers.UapAot)]
[Fact]
public static async Task ConcurrentOperations_Throw()
{
@@ -511,7 +505,6 @@ namespace System.Net.Tests
protected abstract Task<Stream> OpenReadAsync(WebClient wc, string address);
protected abstract Task<Stream> OpenWriteAsync(WebClient wc, string address);
- [ActiveIssue(20141, TargetFrameworkMonikers.UapAot)]
[Theory]
[InlineData(null)]
[InlineData("text/html; charset=utf-8")]
@@ -537,7 +530,6 @@ namespace System.Net.Tests
});
}
- [ActiveIssue(20141, TargetFrameworkMonikers.UapAot)]
[Fact]
public async Task DownloadData_Success()
{
@@ -560,7 +552,6 @@ namespace System.Net.Tests
});
}
- [ActiveIssue(20141, TargetFrameworkMonikers.UapAot)]
[Fact]
public async Task DownloadData_LargeData_Success()
{
@@ -580,7 +571,6 @@ namespace System.Net.Tests
});
}
- [ActiveIssue(20141, TargetFrameworkMonikers.UapAot)]
[Fact]
public async Task DownloadFile_Success()
{
@@ -608,7 +598,6 @@ namespace System.Net.Tests
});
}
- [ActiveIssue(20141, TargetFrameworkMonikers.UapAot)]
[Fact]
public async Task OpenRead_Success()
{
@@ -630,7 +619,6 @@ namespace System.Net.Tests
});
}
- [ActiveIssue(20141, TargetFrameworkMonikers.UapAot)]
[OuterLoop("Networking test talking to remote server: issue #11345")]
[Theory]
[MemberData(nameof(EchoServers))]
@@ -644,7 +632,6 @@ namespace System.Net.Tests
}
}
- [ActiveIssue(20141, TargetFrameworkMonikers.UapAot)]
[OuterLoop("Networking test talking to remote server: issue #11345")]
[Theory]
[MemberData(nameof(EchoServers))]
@@ -660,7 +647,6 @@ namespace System.Net.Tests
Assert.True(!IsAsync || await uploadProgressInvoked.Task, "Expected upload progress callback to be invoked");
}
- [ActiveIssue(20141, TargetFrameworkMonikers.UapAot)]
[OuterLoop("Networking test talking to remote server: issue #11345")]
[Theory]
[MemberData(nameof(EchoServers))]
@@ -678,7 +664,6 @@ namespace System.Net.Tests
return new string(Enumerable.Range(0, 512 * 1024).Select(_ => (char)('a' + rand.Next(0, 26))).ToArray());
}
- [ActiveIssue(20141, TargetFrameworkMonikers.UapAot)]
[OuterLoop("Networking test talking to remote server: issue #11345")]
[Theory]
[MemberData(nameof(EchoServers))]
@@ -698,7 +683,6 @@ namespace System.Net.Tests
}
}
- [ActiveIssue(20141, TargetFrameworkMonikers.UapAot)]
[OuterLoop("Networking test talking to remote server: issue #11345")]
[Theory]
[MemberData(nameof(EchoServers))]
@@ -709,7 +693,6 @@ namespace System.Net.Tests
Assert.Contains(ExpectedText, result);
}
- [ActiveIssue(20141, TargetFrameworkMonikers.UapAot)]
[OuterLoop("Networking test talking to remote server: issue #11345")]
[Theory]
[MemberData(nameof(EchoServers))]
diff --git a/src/System.Net.WebHeaderCollection/tests/System.Net.WebHeaderCollection.Tests.csproj b/src/System.Net.WebHeaderCollection/tests/System.Net.WebHeaderCollection.Tests.csproj
index 485b63935a..08c6465bc7 100644
--- a/src/System.Net.WebHeaderCollection/tests/System.Net.WebHeaderCollection.Tests.csproj
+++ b/src/System.Net.WebHeaderCollection/tests/System.Net.WebHeaderCollection.Tests.csproj
@@ -9,9 +9,6 @@
<ItemGroup>
<Compile Include="WebHeaderCollectionTest.cs" />
<Compile Include="LoggingTest.cs" />
- <Compile Include="$(CommonTestPath)\System\AssertExtensions.cs">
- <Link>Common\System\AssertExtensions.cs</Link>
- </Compile>
<Compile Include="$(CommonTestPath)\System\PlatformDetection.cs">
<Link>CommonTest\System\PlatformDetection.cs</Link>
</Compile>
diff --git a/src/System.Net.WebProxy/tests/System.Net.WebProxy.Tests.csproj b/src/System.Net.WebProxy/tests/System.Net.WebProxy.Tests.csproj
index 61a0265ff7..8054e9b358 100644
--- a/src/System.Net.WebProxy/tests/System.Net.WebProxy.Tests.csproj
+++ b/src/System.Net.WebProxy/tests/System.Net.WebProxy.Tests.csproj
@@ -8,9 +8,6 @@
<PropertyGroup Condition="'$(Configuration)|$(Platform)'=='netstandard-Release|AnyCPU'" />
<ItemGroup>
<Compile Include="WebProxyTest.cs" />
- <Compile Include="$(CommonTestPath)\System\AssertExtensions.cs">
- <Link>Common\System\AssertExtensions.cs</Link>
- </Compile>
</ItemGroup>
<Import Project="$([MSBuild]::GetDirectoryNameOfFileAbove($(MSBuildThisFileDirectory), dir.targets))\dir.targets" />
</Project> \ No newline at end of file
diff --git a/src/System.Net.WebSockets.Client/src/Resources/Strings.resx b/src/System.Net.WebSockets.Client/src/Resources/Strings.resx
index 5f61cf5d8d..7cb546b8a2 100644
--- a/src/System.Net.WebSockets.Client/src/Resources/Strings.resx
+++ b/src/System.Net.WebSockets.Client/src/Resources/Strings.resx
@@ -121,4 +121,10 @@
<data name="net_securityprotocolnotsupported" xml:space="preserve">
<value>The requested security protocol is not supported.</value>
</data>
+ <data name="net_WebSockets_UWPClientCertSupportRequiresWindows10GreaterThan1703" xml:space="preserve">
+ <value>Client certificates in UWP are unsupported in Windows 10 version 1703 and earlier versions. Please upgrade Windows 10 to a later release.</value>
+ </data>
+ <data name="net_WebSockets_UWPClientCertSupportRequiresCertInPersonalCertificateStore" xml:space="preserve">
+ <value>Client certificate was not found in the personal (\"MY\") certificate store. In UWP, client certificates are only supported if they have been added to that certificate store.</value>
+ </data>
</root>
diff --git a/src/System.Net.WebSockets.Client/src/System.Net.WebSockets.Client.csproj b/src/System.Net.WebSockets.Client/src/System.Net.WebSockets.Client.csproj
index 33fb2a06a1..ef0b4a6ea7 100644
--- a/src/System.Net.WebSockets.Client/src/System.Net.WebSockets.Client.csproj
+++ b/src/System.Net.WebSockets.Client/src/System.Net.WebSockets.Client.csproj
@@ -87,6 +87,12 @@
</ItemGroup>
<!-- Windows : Win32 + WinRT -->
<ItemGroup Condition="'$(TargetsWindows)' == 'true' AND '$(TargetGroup)' == 'uap'">
+ <Compile Include="$(CommonPath)\System\Net\Security\CertificateHelper.cs">
+ <Link>Common\System\Net\Security\CertificateHelper.cs</Link>
+ </Compile>
+ <Compile Include="$(CommonPath)\System\Net\Security\CertificateHelper.Uap.cs">
+ <Link>Common\System\Net\Security\CertificateHelper.Uap.cs</Link>
+ </Compile>
<Compile Include="System\Net\WebSockets\WebSocketHandle.WinRT.cs" />
<Compile Include="System\Net\WebSockets\WinRTWebSocket.cs" />
</ItemGroup>
diff --git a/src/System.Net.WebSockets.Client/src/System/Net/WebSockets/WinRTWebSocket.cs b/src/System.Net.WebSockets.Client/src/System/Net/WebSockets/WinRTWebSocket.cs
index bbf057a259..8eb116315b 100644
--- a/src/System.Net.WebSockets.Client/src/System/Net/WebSockets/WinRTWebSocket.cs
+++ b/src/System.Net.WebSockets.Client/src/System/Net/WebSockets/WinRTWebSocket.cs
@@ -6,15 +6,22 @@ using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Globalization;
+using System.Net.Security;
+using System.Runtime.CompilerServices;
using System.Runtime.InteropServices.WindowsRuntime;
+using System.Security.Cryptography.X509Certificates;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
+using Windows.Foundation.Metadata;
using Windows.Networking.Sockets;
using Windows.Storage.Streams;
using Windows.Web;
+using RTCertificate = Windows.Security.Cryptography.Certificates.Certificate;
+using RTCertificateQuery = Windows.Security.Cryptography.Certificates.CertificateQuery;
+using RTCertificateStores = Windows.Security.Cryptography.Certificates.CertificateStores;
using RTWeb​Socket​Error = Windows.Networking.Sockets.Web​Socket​Error;
namespace System.Net.WebSockets
@@ -23,8 +30,16 @@ namespace System.Net.WebSockets
{
#region Constants
private const string HeaderNameCookie = "Cookie";
+ private const string ClientAuthenticationOID = "1.3.6.1.5.5.7.3.2";
#endregion
+ private static readonly Lazy<bool> s_MessageWebSocketClientCertificateSupported =
+ new Lazy<bool>(InitMessageWebSocketClientCertificateSupported);
+ private static bool MessageWebSocketClientCertificateSupported => s_MessageWebSocketClientCertificateSupported.Value;
+ private static readonly Lazy<bool> s_MessageWebSocketReceiveModeSupported =
+ new Lazy<bool>(InitMessageWebSocketReceiveModeSupported);
+ private static bool MessageWebSocketReceiveModeSupported => s_MessageWebSocketReceiveModeSupported.Value;
+
private WebSocketCloseStatus? _closeStatus = null;
private string _closeStatusDescription = null;
private string _subProtocol = null;
@@ -105,6 +120,39 @@ namespace System.Net.WebSockets
websocketControl.SupportedProtocols.Add(subProtocol);
}
+ if (options.ClientCertificates.Count > 0)
+ {
+ if (!MessageWebSocketClientCertificateSupported)
+ {
+ throw new PlatformNotSupportedException(string.Format(CultureInfo.InvariantCulture,
+ SR.net_WebSockets_UWPClientCertSupportRequiresWindows10GreaterThan1703));
+ }
+
+ X509Certificate2 dotNetClientCert = CertificateHelper.GetEligibleClientCertificate(options.ClientCertificates);
+ if (dotNetClientCert != null)
+ {
+ RTCertificate winRtClientCert = await CertificateHelper.ConvertDotNetClientCertToWinRtClientCertAsync(dotNetClientCert);
+ if (winRtClientCert == null)
+ {
+ throw new PlatformNotSupportedException(string.Format(
+ CultureInfo.InvariantCulture,
+ SR.net_WebSockets_UWPClientCertSupportRequiresCertInPersonalCertificateStore));
+ }
+
+ websocketControl.ClientCertificate = winRtClientCert;
+ }
+ }
+
+ // Try to opt into PartialMessage receive mode so that we can hand partial data back to the app as it arrives.
+ // If the MessageWebSocketControl.ReceiveMode API surface is not available, the MessageWebSocket.MessageReceived
+ // event will only get triggered when an entire WebSocket message has been received. This results in large memory
+ // footprint and prevents "streaming" scenarios (e.g., WCF) from working properly.
+ if (MessageWebSocketReceiveModeSupported)
+ {
+ // Always enable partial message receive mode if the WinRT API supports it.
+ _messageWebSocket.Control.ReceiveMode = MessageWebSocketReceiveMode.PartialMessage;
+ }
+
try
{
_receiveAsyncBufferTcs = new TaskCompletionSource<ArraySegment<byte>>();
@@ -129,7 +177,7 @@ namespace System.Net.WebSockets
AbortInternal();
}
- private void AbortInternal(WebSocketException customException = null)
+ private void AbortInternal(Exception customException = null)
{
lock (_stateLock)
{
@@ -148,7 +196,7 @@ namespace System.Net.WebSockets
Dispose();
}
- private void CancelAllOperations(WebSocketException customException)
+ private void CancelAllOperations(Exception customException)
{
if (_receiveAsyncBufferTcs != null)
{
@@ -340,7 +388,7 @@ namespace System.Net.WebSockets
dataBuffer.CopyTo(0, buffer.Array, buffer.Offset, (int) readCount);
if (dataAvailable == readCount)
{
- endOfMessage = true;
+ endOfMessage = !IsPartialMessageEvent(args);
}
WebSocketReceiveResult recvResult = new WebSocketReceiveResult((int) readCount, messageType,
@@ -364,7 +412,7 @@ namespace System.Net.WebSockets
break;
}
- // Propagate a custom exception to any pending SendAsync/ReceiveAsync operations and close the socket.
+ // Propagate a custom exception to any pending ReceiveAsync/CloseAsync operations and close the socket.
WebSocketException customException = new WebSocketException(actualError, exc);
AbortInternal(customException);
}
@@ -421,7 +469,14 @@ namespace System.Net.WebSockets
}
CancellationTokenRegistration cancellationRegistration =
- cancellationToken.Register(s => ((WinRTWebSocket)s).Abort(), this);
+ cancellationToken.Register(s =>
+ {
+ var thisRef = (WinRTWebSocket)s;
+
+ // Propagate a custom exception to any pending ReceiveAsync/CloseAsync operations and close the socket.
+ var customException = new OperationCanceledException(nameof(WebSocketState.Aborted));
+ thisRef.AbortInternal(customException);
+ }, this);
return cancellationRegistration;
}
@@ -499,21 +554,35 @@ namespace System.Net.WebSockets
_state = value;
}
}
+ #endregion
- private void UpdateStateCloseReceived()
+ #region Helpers
+ private static bool InitMessageWebSocketClientCertificateSupported()
{
- lock (_stateLock)
+ return ApiInformation.IsPropertyPresent(
+ "Windows.Networking.Sockets.MessageWebSocketControl",
+ "ClientCertificate");
+ }
+
+ private static bool InitMessageWebSocketReceiveModeSupported()
+ {
+ return ApiInformation.IsPropertyPresent(
+ "Windows.Networking.Sockets.MessageWebSocketControl",
+ "ReceiveMode");
+ }
+
+ private bool IsPartialMessageEvent(MessageWebSocketMessageReceivedEventArgs eventArgs)
+ {
+ if (MessageWebSocketReceiveModeSupported)
{
- if (_state == WebSocketState.CloseSent)
- {
- UpdateState(WebSocketState.Closed);
- }
- else if (_state == WebSocketState.Open)
- {
- UpdateState(WebSocketState.CloseReceived);
- }
+ return !eventArgs.IsMessageComplete;
}
+
+ // When MessageWebSocketMessageReceivedEventArgs.IsMessageComplete is not available, WinRT's behavior
+ // is always to wait for the entire WebSocket message to arrive before raising a MessageReceived event.
+ return false;
}
- #endregion
+ #endregion Helpers
+
}
}
diff --git a/src/System.Net.WebSockets.Client/tests/CancelTest.cs b/src/System.Net.WebSockets.Client/tests/CancelTest.cs
index c6248addfa..9bc3015aab 100644
--- a/src/System.Net.WebSockets.Client/tests/CancelTest.cs
+++ b/src/System.Net.WebSockets.Client/tests/CancelTest.cs
@@ -10,7 +10,6 @@ using Xunit.Abstractions;
namespace System.Net.WebSockets.Client.Tests
{
- [ActiveIssue(20132, TargetFrameworkMonikers.Uap)]
public class CancelTest : ClientWebSocketTestBase
{
public CancelTest(ITestOutputHelper output) : base(output) { }
diff --git a/src/System.Net.WebSockets.Client/tests/ClientWebSocketOptionsTests.cs b/src/System.Net.WebSockets.Client/tests/ClientWebSocketOptionsTests.cs
index c1bdc10375..844d022fa2 100644
--- a/src/System.Net.WebSockets.Client/tests/ClientWebSocketOptionsTests.cs
+++ b/src/System.Net.WebSockets.Client/tests/ClientWebSocketOptionsTests.cs
@@ -25,6 +25,11 @@ namespace System.Net.WebSockets.Client.Tests
public static bool CanTestClientCertificates =>
CanTestCertificates && BackendSupportsCustomCertificateHandling;
+ // Windows 10 Insider Preview Build 16215 introduced the necessary APIs for the UAP version of
+ // ClientWebSocket.ConnectAsync to carry out mutual TLS authentication.
+ public static bool ClientCertificatesSupported =>
+ !PlatformDetection.IsUap || PlatformDetection.IsWindows10InsiderPreviewBuild16215OrGreater;
+
public ClientWebSocketOptionsTests(ITestOutputHelper output) : base(output) { }
[ConditionalFact(nameof(WebSocketsSupported))]
@@ -72,9 +77,8 @@ namespace System.Net.WebSockets.Client.Tests
}
[OuterLoop] // TODO: Issue #11345
- [ActiveIssue(21393, TargetFrameworkMonikers.Uap)]
[ActiveIssue(5120, TargetFrameworkMonikers.Netcoreapp)]
- [ConditionalFact(nameof(WebSocketsSupported), nameof(CanTestClientCertificates))]
+ [ConditionalFact(nameof(WebSocketsSupported), nameof(CanTestClientCertificates), nameof(ClientCertificatesSupported))]
public async Task ClientCertificates_ValidCertificate_ServerReceivesCertificateAndConnectAsyncSucceeds()
{
var options = new LoopbackServer.Options { UseSsl = true, WebSocketEndpoint = true };
diff --git a/src/System.Net.WebSockets.Client/tests/ClientWebSocketUnitTest.cs b/src/System.Net.WebSockets.Client/tests/ClientWebSocketUnitTest.cs
index bf75a6aa0e..44fcf82070 100644
--- a/src/System.Net.WebSockets.Client/tests/ClientWebSocketUnitTest.cs
+++ b/src/System.Net.WebSockets.Client/tests/ClientWebSocketUnitTest.cs
@@ -57,17 +57,21 @@ namespace System.Net.WebSockets.Client.Tests
}
}
- [ActiveIssue(20132, TargetFrameworkMonikers.Uap)]
[OuterLoop] // TODO: Issue #11345
[ConditionalFact(nameof(WebSocketsSupported))]
- public void CloseAsync_CreateAndCloseOutput_ThrowsInvalidOperationExceptionWithMessage()
+ public async Task CloseAsync_CreateAndCloseOutput_ThrowsInvalidOperationExceptionWithMessage()
{
using (var cws = new ClientWebSocket())
{
- AssertExtensions.Throws<InvalidOperationException>(
- () =>
- cws.CloseOutputAsync(WebSocketCloseStatus.Empty, "", new CancellationToken()).GetAwaiter().GetResult(),
- ResourceHelper.GetExceptionMessage("net_WebSockets_NotConnected"));
+ var exception = await Assert.ThrowsAsync<InvalidOperationException>(
+ () => cws.CloseOutputAsync(WebSocketCloseStatus.Empty, "", new CancellationToken()));
+
+ // The .Net Native toolchain optimizes away exception messages.
+ if (!PlatformDetection.IsNetNative)
+ {
+ string expectedMessage = ResourceHelper.GetExceptionMessage("net_WebSockets_NotConnected");
+ Assert.Equal(expectedMessage, exception.Message);
+ }
Assert.Equal(WebSocketState.None, cws.State);
}
@@ -90,10 +94,9 @@ namespace System.Net.WebSockets.Client.Tests
}
}
- [ActiveIssue(20132, TargetFrameworkMonikers.Uap)]
[OuterLoop] // TODO: Issue #11345
[ConditionalFact(nameof(WebSocketsSupported))]
- public void CloseAsync_CreateAndReceive_ThrowsInvalidOperationExceptionWithMessage()
+ public async Task CloseAsync_CreateAndReceive_ThrowsInvalidOperationExceptionWithMessage()
{
using (var cws = new ClientWebSocket())
{
@@ -101,9 +104,15 @@ namespace System.Net.WebSockets.Client.Tests
var segment = new ArraySegment<byte>(buffer);
var ct = new CancellationToken();
- AssertExtensions.Throws<InvalidOperationException>(
- () => cws.ReceiveAsync(segment, ct).GetAwaiter().GetResult(),
- ResourceHelper.GetExceptionMessage("net_WebSockets_NotConnected"));
+ var exception = await Assert.ThrowsAsync<InvalidOperationException>(
+ () => cws.ReceiveAsync(segment, ct));
+
+ // The .Net Native toolchain optimizes away exception messages.
+ if (!PlatformDetection.IsNetNative)
+ {
+ string expectedMessage = ResourceHelper.GetExceptionMessage("net_WebSockets_NotConnected");
+ Assert.Equal(expectedMessage, exception.Message);
+ }
Assert.Equal(WebSocketState.None, cws.State);
}
@@ -126,10 +135,9 @@ namespace System.Net.WebSockets.Client.Tests
}
}
- [ActiveIssue(20132, TargetFrameworkMonikers.Uap)]
[OuterLoop] // TODO: Issue #11345
[ConditionalFact(nameof(WebSocketsSupported))]
- public void CloseAsync_CreateAndSend_ThrowsInvalidOperationExceptionWithMessage()
+ public async Task CloseAsync_CreateAndSend_ThrowsInvalidOperationExceptionWithMessage()
{
using (var cws = new ClientWebSocket())
{
@@ -137,9 +145,15 @@ namespace System.Net.WebSockets.Client.Tests
var segment = new ArraySegment<byte>(buffer);
var ct = new CancellationToken();
- AssertExtensions.Throws<InvalidOperationException>(
- () => cws.SendAsync(segment, WebSocketMessageType.Text, false, ct).GetAwaiter().GetResult(),
- ResourceHelper.GetExceptionMessage("net_WebSockets_NotConnected"));
+ var exception = await Assert.ThrowsAsync<InvalidOperationException>(
+ () => cws.SendAsync(segment, WebSocketMessageType.Text, false, ct));
+
+ // The .Net Native toolchain optimizes away exception messages.
+ if (!PlatformDetection.IsNetNative)
+ {
+ string expectedMessage = ResourceHelper.GetExceptionMessage("net_WebSockets_NotConnected");
+ Assert.Equal(expectedMessage, exception.Message);
+ }
Assert.Equal(WebSocketState.None, cws.State);
}
@@ -184,7 +198,6 @@ namespace System.Net.WebSockets.Client.Tests
Assert.Equal(WebSocketState.Closed, cws.State);
}
- [ActiveIssue(20132, TargetFrameworkMonikers.Uap)]
[OuterLoop] // TODO: Issue #11345
[ConditionalFact(nameof(WebSocketsSupported))]
public void CloseAsync_DisposeAndCloseOutput_ThrowsObjectDisposedExceptionWithMessage()
@@ -202,7 +215,6 @@ namespace System.Net.WebSockets.Client.Tests
Assert.Equal(WebSocketState.Closed, cws.State);
}
- [ActiveIssue(20132, TargetFrameworkMonikers.Uap)]
[OuterLoop] // TODO: Issue #11345
[ConditionalFact(nameof(WebSocketsSupported))]
public void ReceiveAsync_CreateAndDisposeAndReceive_ThrowsObjectDisposedExceptionWithMessage()
@@ -223,7 +235,6 @@ namespace System.Net.WebSockets.Client.Tests
Assert.Equal(WebSocketState.Closed, cws.State);
}
- [ActiveIssue(20132, TargetFrameworkMonikers.Uap)]
[OuterLoop] // TODO: Issue #11345
[ConditionalFact(nameof(WebSocketsSupported))]
public void SendAsync_CreateAndDisposeAndSend_ThrowsObjectDisposedExceptionWithMessage()
diff --git a/src/System.Net.WebSockets.Client/tests/CloseTest.cs b/src/System.Net.WebSockets.Client/tests/CloseTest.cs
index b8168bb1ca..732bd97607 100644
--- a/src/System.Net.WebSockets.Client/tests/CloseTest.cs
+++ b/src/System.Net.WebSockets.Client/tests/CloseTest.cs
@@ -13,7 +13,6 @@ using Xunit.Abstractions;
namespace System.Net.WebSockets.Client.Tests
{
- [ActiveIssue(20132, TargetFrameworkMonikers.Uap)]
public class CloseTest : ClientWebSocketTestBase
{
public CloseTest(ITestOutputHelper output) : base(output) { }
@@ -257,7 +256,7 @@ namespace System.Net.WebSockets.Client.Tests
}
}
- [ActiveIssue(20362, TargetFrameworkMonikers.NetFramework)]
+ [ActiveIssue(20362, TargetFrameworkMonikers.Netcoreapp)]
[OuterLoop] // TODO: Issue #11345
[ConditionalTheory(nameof(WebSocketsSupported)), MemberData(nameof(EchoServers))]
public async Task CloseOutputAsync_DuringConcurrentReceiveAsync_ExpectedStates(Uri server)
@@ -270,29 +269,28 @@ namespace System.Net.WebSockets.Client.Tests
Assert.False(t.IsCompleted);
Assert.Equal(WebSocketState.Open, cws.State);
- // Send a close frame. After this completes, the state could be CloseSent if we haven't
- // yet received the server response close frame, or it could be CloseReceived if we have.
+ // Send a close frame. After this completes, the state could be CloseSent if we haven't
+ // yet received the server's response close frame, or it could be Closed if we have.
await cws.CloseOutputAsync(WebSocketCloseStatus.NormalClosure, "", CancellationToken.None);
Assert.True(
- cws.State == WebSocketState.CloseSent || cws.State == WebSocketState.CloseReceived,
- $"Expected CloseSent or CloseReceived, got {cws.State}");
+ cws.State == WebSocketState.CloseSent || cws.State == WebSocketState.Closed,
+ $"Expected CloseSent or Closed, got {cws.State}");
- // Then wait for the receive. After this completes, the state is most likely CloseReceived,
- // however there is a race condition between the our realizing that the send has completed
- // and a fast server sending back a close frame, such that we could end up noticing the
- // receive completion before we notice the send completion.
+ // Now wait for the receive. It will complete once the server's close frame arrives,
+ // at which point the ClientWebSocket's state should automatically transition to Closed.
WebSocketReceiveResult r = await t;
Assert.Equal(WebSocketMessageType.Close, r.MessageType);
- Assert.True(
- cws.State == WebSocketState.CloseSent || cws.State == WebSocketState.CloseReceived,
- $"Expected CloseSent or CloseReceived, got {cws.State}");
+ Assert.Equal(WebSocketState.Closed, cws.State);
- // Then close
+ // Closing an already-closed ClientWebSocket should be a no-op. Any other behavior (e.g., throwing exception)
+ // would give way to race conditions between (1) CloseAsync being called and (2) the server's response close
+ // frame being received after CloseOutputAsync.
await cws.CloseAsync(WebSocketCloseStatus.NormalClosure, "", CancellationToken.None);
Assert.Equal(WebSocketState.Closed, cws.State);
- // Another close should fail
- await Assert.ThrowsAsync<WebSocketException>(() => cws.CloseAsync(WebSocketCloseStatus.NormalClosure, "", CancellationToken.None));
+ // Call CloseAsync one more time on the already-closed ClientWebSocket for good measure. Again, this should be a no-op.
+ await cws.CloseAsync(WebSocketCloseStatus.NormalClosure, "", CancellationToken.None);
+ Assert.Equal(WebSocketState.Closed, cws.State);
}
}
diff --git a/src/System.Net.WebSockets.Client/tests/SendReceiveTest.cs b/src/System.Net.WebSockets.Client/tests/SendReceiveTest.cs
index 264c5da0a9..d05b3e5bb0 100644
--- a/src/System.Net.WebSockets.Client/tests/SendReceiveTest.cs
+++ b/src/System.Net.WebSockets.Client/tests/SendReceiveTest.cs
@@ -16,6 +16,8 @@ namespace System.Net.WebSockets.Client.Tests
{
public class SendReceiveTest : ClientWebSocketTestBase
{
+ public static bool PartialMessagesSupported => PlatformDetection.ClientWebSocketPartialMessagesSupported;
+
public SendReceiveTest(ITestOutputHelper output) : base(output) { }
[OuterLoop] // TODO: Issue #11345
@@ -54,9 +56,8 @@ namespace System.Net.WebSockets.Client.Tests
}
}
- [ActiveIssue(21102, TargetFrameworkMonikers.Uap)]
[OuterLoop] // TODO: Issue #11345
- [ConditionalTheory(nameof(WebSocketsSupported)), MemberData(nameof(EchoServers))]
+ [ConditionalTheory(nameof(WebSocketsSupported), nameof(PartialMessagesSupported)), MemberData(nameof(EchoServers))]
public async Task SendReceive_PartialMessageBeforeCompleteMessageArrives_Success(Uri server)
{
var rand = new Random();
diff --git a/src/System.Net.WebSockets.Client/tests/System.Net.WebSockets.Client.Tests.csproj b/src/System.Net.WebSockets.Client/tests/System.Net.WebSockets.Client.Tests.csproj
index bc0a2240fd..414c600604 100644
--- a/src/System.Net.WebSockets.Client/tests/System.Net.WebSockets.Client.Tests.csproj
+++ b/src/System.Net.WebSockets.Client/tests/System.Net.WebSockets.Client.Tests.csproj
@@ -14,12 +14,12 @@
<TargetingPackExclusions Include="System.Configuration" />
</ItemGroup>
<ItemGroup>
- <Compile Include="$(CommonTestPath)\System\AssertExtensions.cs">
- <Link>Common\System\AssertExtensions.cs</Link>
- </Compile>
<Compile Include="$(CommonTestPath)\System\PlatformDetection.cs">
<Link>Common\System\PlatformDetection.cs</Link>
</Compile>
+ <Compile Include="$(CommonTestPath)\System\Net\PlatformDetection.Networking.cs">
+ <Link>Common\System\Net\PlatformDetection.Networking.cs</Link>
+ </Compile>
<Compile Include="$(CommonTestPath)\System\Net\Capability.Security.cs">
<Link>Common\System\Net\Capability.Security.cs</Link>
</Compile>
diff --git a/src/System.Net.WebSockets/tests/System.Net.WebSockets.Tests.csproj b/src/System.Net.WebSockets/tests/System.Net.WebSockets.Tests.csproj
index 5d80272dcc..32f323ad22 100644
--- a/src/System.Net.WebSockets/tests/System.Net.WebSockets.Tests.csproj
+++ b/src/System.Net.WebSockets/tests/System.Net.WebSockets.Tests.csproj
@@ -13,9 +13,6 @@
<Compile Include="WebSocketTests.cs" />
<Compile Include="WebSocketExceptionTests.cs" />
<Compile Include="WebSocketReceiveResultTests.cs" />
- <Compile Include="$(CommonTestPath)\System\AssertExtensions.cs">
- <Link>Common\System\AssertExtensions.cs</Link>
- </Compile>
<Compile Include="$(CommonTestPath)\System\PlatformDetection.cs">
<Link>Common\System\PlatformDetection.cs</Link>
</Compile>
diff --git a/src/System.Numerics.Vectors/pkg/System.Numerics.Vectors.pkgproj b/src/System.Numerics.Vectors/pkg/System.Numerics.Vectors.pkgproj
index b7c8ef8f2f..0a8bbc7c0c 100644
--- a/src/System.Numerics.Vectors/pkg/System.Numerics.Vectors.pkgproj
+++ b/src/System.Numerics.Vectors/pkg/System.Numerics.Vectors.pkgproj
@@ -16,7 +16,7 @@
</ItemGroup>
<ItemGroup>
<InboxOnTargetFramework Include="netcoreapp2.0" />
- <InboxOnTargetFramework Include="uap10.1" />
+ <InboxOnTargetFramework Include="$(UAPvNextTFM)" />
<InboxOnTargetFramework Include="MonoAndroid10" />
<InboxOnTargetFramework Include="MonoTouch10" />
<InboxOnTargetFramework Include="xamarinios10" />
diff --git a/src/System.Numerics.Vectors/src/System.Numerics.Vectors.csproj b/src/System.Numerics.Vectors/src/System.Numerics.Vectors.csproj
index 437be1c4e8..2af29cb031 100644
--- a/src/System.Numerics.Vectors/src/System.Numerics.Vectors.csproj
+++ b/src/System.Numerics.Vectors/src/System.Numerics.Vectors.csproj
@@ -46,7 +46,9 @@
</ItemGroup>
<!-- Carry a copy of MathF where not available -->
<ItemGroup Condition="'$(IsPartialFacadeAssembly)' == 'true' OR $(TargetGroup.StartsWith('netstandard'))">
- <Compile Include="System\MathF.cs" />
+ <Compile Include="..\..\Common\src\System\MathF.netstandard.cs">
+ <Link>System\MathF.netstandard.cs</Link>
+ </Compile>
</ItemGroup>
<!-- Portable version only -->
<ItemGroup Condition="'$(IsPartialFacadeAssembly)' != 'true'">
diff --git a/src/System.Numerics.Vectors/tests/GenericVectorTests.cs b/src/System.Numerics.Vectors/tests/GenericVectorTests.cs
index 88e11b93e4..e03022a216 100644
--- a/src/System.Numerics.Vectors/tests/GenericVectorTests.cs
+++ b/src/System.Numerics.Vectors/tests/GenericVectorTests.cs
@@ -7,6 +7,7 @@ using System.Globalization;
using System.Linq;
using System.Reflection;
using Xunit;
+using Xunit.Sdk;
namespace System.Numerics.Tests
{
@@ -1880,26 +1881,26 @@ namespace System.Numerics.Tests
}
[Fact]
- public void SquareRootByte() { TestSquareRoot<Byte>(); }
+ public void SquareRootByte() { TestSquareRoot<Byte>(-1); }
[Fact]
- public void SquareRootSByte() { TestSquareRoot<SByte>(); }
+ public void SquareRootSByte() { TestSquareRoot<SByte>(-1); }
[Fact]
- public void SquareRootUInt16() { TestSquareRoot<UInt16>(); }
+ public void SquareRootUInt16() { TestSquareRoot<UInt16>(-1); }
[Fact]
- public void SquareRootInt16() { TestSquareRoot<Int16>(); }
+ public void SquareRootInt16() { TestSquareRoot<Int16>(-1); }
[Fact]
- public void SquareRootUInt32() { TestSquareRoot<UInt32>(); }
+ public void SquareRootUInt32() { TestSquareRoot<UInt32>(-1); }
[Fact]
- public void SquareRootInt32() { TestSquareRoot<Int32>(); }
+ public void SquareRootInt32() { TestSquareRoot<Int32>(-1); }
[Fact]
- public void SquareRootUInt64() { TestSquareRoot<UInt64>(); }
+ public void SquareRootUInt64() { TestSquareRoot<UInt64>(-1); }
[Fact]
- public void SquareRootInt64() { TestSquareRoot<Int64>(); }
+ public void SquareRootInt64() { TestSquareRoot<Int64>(-1); }
[Fact]
- public void SquareRootSingle() { TestSquareRoot<Single>(); }
+ public void SquareRootSingle() { TestSquareRoot<Single>(6); }
[Fact]
- public void SquareRootDouble() { TestSquareRoot<Double>(); }
- private void TestSquareRoot<T>() where T : struct
+ public void SquareRootDouble() { TestSquareRoot<Double>(15); }
+ private void TestSquareRoot<T>(int precision = -1) where T : struct, IEquatable<T>
{
T[] values = GenerateRandomValuesForVector<T>();
Vector<T> vector = new Vector<T>(values);
@@ -1909,7 +1910,7 @@ namespace System.Numerics.Tests
(index, val) =>
{
T expected = Util.Sqrt(values[index]);
- Assert.Equal(expected, val);
+ AssertEqual(expected, val, $"SquareRoot( {FullString(values[index])} )", precision);
});
}
@@ -2610,6 +2611,86 @@ namespace System.Numerics.Tests
#endregion Narrow / Widen
#region Helper Methods
+ private static void AssertEqual<T>(T expected, T actual, string operation, int precision = -1) where T : IEquatable<T>
+ {
+ if (typeof(T) == typeof(float))
+ {
+ if (!IsDiffTolerable((float)(object)expected, (float)(object)actual, precision))
+ {
+ throw new XunitException($"AssertEqual failed for operation {operation}. Expected: {expected,10:G9}, Actual: {actual,10:G9}.");
+ }
+ }
+ else if (typeof(T) == typeof(double))
+ {
+ if (!IsDiffTolerable((double)(object)expected, (double)(object)actual, precision))
+ {
+ throw new XunitException($"AssertEqual failed for operation {operation}. Expected: {expected,20:G17}, Actual: {actual,20:G17}.");
+ }
+ }
+ else
+ {
+ if (!expected.Equals(actual))
+ {
+ throw new XunitException($"AssertEqual failed for operation {operation}. Expected: {expected}, Actual: {actual}.");
+ }
+ }
+ }
+
+ private static bool IsDiffTolerable(double d1, double d2, int precision)
+ {
+ if (double.IsNaN(d1))
+ {
+ return double.IsNaN(d2);
+ }
+ if (double.IsInfinity(d1) || double.IsInfinity(d2))
+ {
+ return AreSameInfinity(d1, d2);
+ }
+
+ double diffRatio = (d1 - d2) / d1;
+ diffRatio *= Math.Pow(10, precision);
+ return Math.Abs(diffRatio) < 1;
+ }
+
+ private static bool IsDiffTolerable(float f1, float f2, int precision)
+ {
+ if (float.IsNaN(f1))
+ {
+ return float.IsNaN(f2);
+ }
+ if (float.IsInfinity(f1) || float.IsInfinity(f2))
+ {
+ return AreSameInfinity(f1, f2);
+ }
+
+ float diffRatio = (f1 - f2) / f1;
+ diffRatio *= MathF.Pow(10, precision);
+ return Math.Abs(diffRatio) < 1;
+ }
+
+ private static string FullString<T>(T value)
+ {
+ if (typeof(T) == typeof(float))
+ {
+ return ((float)(object)value).ToString("G9");
+ }
+ else if (typeof(T) == typeof(double))
+ {
+ return ((double)(object)value).ToString("G17");
+ }
+ else
+ {
+ return value.ToString();
+ }
+ }
+
+ private static bool AreSameInfinity(double d1, double d2)
+ {
+ return
+ double.IsNegativeInfinity(d1) == double.IsNegativeInfinity(d2) &&
+ double.IsPositiveInfinity(d1) == double.IsPositiveInfinity(d2);
+ }
+
private static void ValidateVector<T>(Vector<T> vector, Action<int, T> indexValidationFunc) where T : struct
{
for (int g = 0; g < Vector<T>.Count; g++)
@@ -2695,4 +2776,4 @@ namespace System.Numerics.Tests
}
#endregion
}
-}
+} \ No newline at end of file
diff --git a/src/System.Numerics.Vectors/tests/GenericVectorTests.tt b/src/System.Numerics.Vectors/tests/GenericVectorTests.tt
index 1aa946d685..4790b1ac50 100644
--- a/src/System.Numerics.Vectors/tests/GenericVectorTests.tt
+++ b/src/System.Numerics.Vectors/tests/GenericVectorTests.tt
@@ -12,6 +12,7 @@ using System.Globalization;
using System.Linq;
using System.Reflection;
using Xunit;
+using Xunit.Sdk;
namespace System.Numerics.Tests
{
@@ -216,7 +217,7 @@ namespace System.Numerics.Tests
Assert.Throws<NullReferenceException>(() => vector.CopyTo(null, 0));
Assert.Throws<ArgumentOutOfRangeException>(() => vector.CopyTo(array, -1));
Assert.Throws<ArgumentOutOfRangeException>(() => vector.CopyTo(array, array.Length));
- Assert.Throws<ArgumentException>(() => vector.CopyTo(array, array.Length - 1));
+ AssertExtensions.Throws<ArgumentException>(null, () => vector.CopyTo(array, array.Length - 1));
vector.CopyTo(array);
for (int g = 0; g < array.Length; g++)
@@ -1383,13 +1384,14 @@ namespace System.Numerics.Tests
<#
foreach (var type in supportedTypes)
{
+ int precision = type == typeof(float) ? 6 : type == typeof(double) ? 15 : -1;
#>
[Fact]
- public void SquareRoot<#=type.Name#>() { TestSquareRoot<<#=type.Name#>>(); }
+ public void SquareRoot<#=type.Name#>() { TestSquareRoot<<#=type.Name#>>(<#=precision#>); }
<#
}
#>
- private void TestSquareRoot<T>() where T : struct
+ private void TestSquareRoot<T>(int precision = -1) where T : struct, IEquatable<T>
{
T[] values = GenerateRandomValuesForVector<T>();
Vector<T> vector = new Vector<T>(values);
@@ -1399,7 +1401,7 @@ namespace System.Numerics.Tests
(index, val) =>
{
T expected = Util.Sqrt(values[index]);
- Assert.Equal(expected, val);
+ AssertEqual(expected, val, $"SquareRoot( {FullString(values[index])} )", precision);
});
}
@@ -1702,6 +1704,86 @@ namespace System.Numerics.Tests
#endregion Narrow / Widen
#region Helper Methods
+ private static void AssertEqual<T>(T expected, T actual, string operation, int precision = -1) where T : IEquatable<T>
+ {
+ if (typeof(T) == typeof(float))
+ {
+ if (!IsDiffTolerable((float)(object)expected, (float)(object)actual, precision))
+ {
+ throw new XunitException($"AssertEqual failed for operation {operation}. Expected: {expected,10:G9}, Actual: {actual,10:G9}.");
+ }
+ }
+ else if (typeof(T) == typeof(double))
+ {
+ if (!IsDiffTolerable((double)(object)expected, (double)(object)actual, precision))
+ {
+ throw new XunitException($"AssertEqual failed for operation {operation}. Expected: {expected,20:G17}, Actual: {actual,20:G17}.");
+ }
+ }
+ else
+ {
+ if (!expected.Equals(actual))
+ {
+ throw new XunitException($"AssertEqual failed for operation {operation}. Expected: {expected}, Actual: {actual}.");
+ }
+ }
+ }
+
+ private static bool IsDiffTolerable(double d1, double d2, int precision)
+ {
+ if (double.IsNaN(d1))
+ {
+ return double.IsNaN(d2);
+ }
+ if (double.IsInfinity(d1) || double.IsInfinity(d2))
+ {
+ return AreSameInfinity(d1, d2);
+ }
+
+ double diffRatio = (d1 - d2) / d1;
+ diffRatio *= Math.Pow(10, precision);
+ return Math.Abs(diffRatio) < 1;
+ }
+
+ private static bool IsDiffTolerable(float f1, float f2, int precision)
+ {
+ if (float.IsNaN(f1))
+ {
+ return float.IsNaN(f2);
+ }
+ if (float.IsInfinity(f1) || float.IsInfinity(f2))
+ {
+ return AreSameInfinity(f1, f2);
+ }
+
+ float diffRatio = (f1 - f2) / f1;
+ diffRatio *= MathF.Pow(10, precision);
+ return Math.Abs(diffRatio) < 1;
+ }
+
+ private static string FullString<T>(T value)
+ {
+ if (typeof(T) == typeof(float))
+ {
+ return ((float)(object)value).ToString("G9");
+ }
+ else if (typeof(T) == typeof(double))
+ {
+ return ((double)(object)value).ToString("G17");
+ }
+ else
+ {
+ return value.ToString();
+ }
+ }
+
+ private static bool AreSameInfinity(double d1, double d2)
+ {
+ return
+ double.IsNegativeInfinity(d1) == double.IsNegativeInfinity(d2) &&
+ double.IsPositiveInfinity(d1) == double.IsPositiveInfinity(d2);
+ }
+
private static void ValidateVector<T>(Vector<T> vector, Action<int, T> indexValidationFunc) where T : struct
{
for (int g = 0; g < Vector<T>.Count; g++)
diff --git a/src/System.Numerics.Vectors/tests/System.Numerics.Vectors.Tests.csproj b/src/System.Numerics.Vectors/tests/System.Numerics.Vectors.Tests.csproj
index 6a6d6ac63a..d952677904 100644
--- a/src/System.Numerics.Vectors/tests/System.Numerics.Vectors.Tests.csproj
+++ b/src/System.Numerics.Vectors/tests/System.Numerics.Vectors.Tests.csproj
@@ -32,12 +32,12 @@
<Compile Include="Matrix4x4Tests.cs" />
<Compile Include="PlaneTests.cs" />
<Compile Include="QuaternionTests.cs" />
- <Compile Include="$(CommonTestPath)\System\AssertExtensions.cs">
- <Link>Common\System\AssertExtensions.cs</Link>
- </Compile>
<Compile Include="$(CommonTestPath)\System\PlatformDetection.cs">
<Link>Common\System\PlatformDetection.cs</Link>
</Compile>
+ <Compile Condition="'$(TargetGroup)' == 'netfx'" Include="..\..\Common\src\System\MathF.netstandard.cs">
+ <Link>System\MathF.netstandard.cs</Link>
+ </Compile>
</ItemGroup>
<ItemGroup>
<None Include="..\src\System\Numerics\ConstantHelper.tt">
diff --git a/src/System.ObjectModel/src/System/Collections/ObjectModel/ObservableCollection.cs b/src/System.ObjectModel/src/System/Collections/ObjectModel/ObservableCollection.cs
index b1154f4d18..b4111394da 100644
--- a/src/System.ObjectModel/src/System/Collections/ObjectModel/ObservableCollection.cs
+++ b/src/System.ObjectModel/src/System/Collections/ObjectModel/ObservableCollection.cs
@@ -19,7 +19,7 @@ namespace System.Collections.ObjectModel
[DebuggerTypeProxy(typeof(CollectionDebugView<>))]
[DebuggerDisplay("Count = {Count}")]
#if !MONO
- [System.Runtime.CompilerServices.TypeForwardedFrom("WindowsBase, Version=3.0.0.0, Culture=Neutral, PublicKeyToken=31bf3856ad364e35")]
+ [System.Runtime.CompilerServices.TypeForwardedFrom("WindowsBase, Version=3.0.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35")]
#endif
public class ObservableCollection<T> : Collection<T>, INotifyCollectionChanged, INotifyPropertyChanged
{
@@ -395,7 +395,7 @@ namespace System.Collections.ObjectModel
[Serializable]
#if !MONO
- [System.Runtime.CompilerServices.TypeForwardedFrom("WindowsBase, Version=3.0.0.0, Culture=Neutral, PublicKeyToken=31bf3856ad364e35")]
+ [System.Runtime.CompilerServices.TypeForwardedFrom("WindowsBase, Version=3.0.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35")]
#endif
private sealed class SimpleMonitor : IDisposable
{
diff --git a/src/System.ObjectModel/src/System/Collections/ObjectModel/ReadOnlyObservableCollection.cs b/src/System.ObjectModel/src/System/Collections/ObjectModel/ReadOnlyObservableCollection.cs
index d967c545c1..16a6841ec7 100644
--- a/src/System.ObjectModel/src/System/Collections/ObjectModel/ReadOnlyObservableCollection.cs
+++ b/src/System.ObjectModel/src/System/Collections/ObjectModel/ReadOnlyObservableCollection.cs
@@ -19,7 +19,7 @@ namespace System.Collections.ObjectModel
[DebuggerTypeProxy(typeof(CollectionDebugView<>))]
[DebuggerDisplay("Count = {Count}")]
#if !MONO
- [System.Runtime.CompilerServices.TypeForwardedFrom("WindowsBase, Version=3.0.0.0, Culture=Neutral, PublicKeyToken=31bf3856ad364e35")]
+ [System.Runtime.CompilerServices.TypeForwardedFrom("WindowsBase, Version=3.0.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35")]
#endif
public class ReadOnlyObservableCollection<T> : ReadOnlyCollection<T>, INotifyCollectionChanged, INotifyPropertyChanged
{
diff --git a/src/System.ObjectModel/tests/System.ObjectModel.Tests.csproj b/src/System.ObjectModel/tests/System.ObjectModel.Tests.csproj
index 42064347a9..c7dada54f2 100644
--- a/src/System.ObjectModel/tests/System.ObjectModel.Tests.csproj
+++ b/src/System.ObjectModel/tests/System.ObjectModel.Tests.csproj
@@ -9,9 +9,6 @@
<PropertyGroup Condition="'$(Configuration)|$(Platform)' == 'netstandard-Debug|AnyCPU'" />
<PropertyGroup Condition="'$(Configuration)|$(Platform)' == 'netstandard-Release|AnyCPU'" />
<ItemGroup>
- <Compile Include="$(CommonTestPath)\System\AssertExtensions.cs">
- <Link>Common\System\AssertExtensions.cs</Link>
- </Compile>
<Compile Include="$(CommonTestPath)\System\Collections\IEnumerableTest.cs">
<Link>Common\System\CollectionsIEnumerableTest.cs</Link>
</Compile>
diff --git a/src/System.Private.Reflection.Metadata.Ecma335/src/Shims/Marshal.cs b/src/System.Private.Reflection.Metadata.Ecma335/src/Shims/Marshal.cs
index 75c0f62955..26af3e5a2f 100644
--- a/src/System.Private.Reflection.Metadata.Ecma335/src/Shims/Marshal.cs
+++ b/src/System.Private.Reflection.Metadata.Ecma335/src/Shims/Marshal.cs
@@ -12,22 +12,22 @@ namespace System.Runtime.InteropServices
{
public static void Copy(IntPtr source, byte[] destination, int startIndex, int length)
{
- InteropExtensions.CopyToManaged(source, destination, startIndex, length);
+ PInvokeMarshal.CopyToManaged(source, destination, startIndex, length);
}
public static void Copy(byte[] array, int startIndex, IntPtr destination, int length)
{
- InteropExtensions.CopyToNative(array, startIndex, destination, length);
+ PInvokeMarshal.CopyToNative(array, startIndex, destination, length);
}
public static IntPtr AllocHGlobal(int cb)
{
- return InteropExtensions.MemAlloc(new UIntPtr((uint)cb));
+ return PInvokeMarshal.AllocHGlobal(cb);
}
public static void FreeHGlobal(IntPtr hglobal)
{
- InteropExtensions.MemFree(hglobal);
+ PInvokeMarshal.FreeHGlobal(hglobal);
}
}
-} \ No newline at end of file
+}
diff --git a/src/System.Private.Uri/tests/ExtendedFunctionalTests/System.Private.Uri.ExtendedFunctional.Tests.csproj b/src/System.Private.Uri/tests/ExtendedFunctionalTests/System.Private.Uri.ExtendedFunctional.Tests.csproj
index 72cbc1f508..6461573454 100644
--- a/src/System.Private.Uri/tests/ExtendedFunctionalTests/System.Private.Uri.ExtendedFunctional.Tests.csproj
+++ b/src/System.Private.Uri/tests/ExtendedFunctionalTests/System.Private.Uri.ExtendedFunctional.Tests.csproj
@@ -10,9 +10,6 @@
<Compile Include="UriRelativeResolutionTest.cs" />
<Compile Include="UriTests.cs" />
<!-- Test common -->
- <Compile Include="$(CommonTestPath)\System\AssertExtensions.cs">
- <Link>Common\System\AssertExtensions.cs</Link>
- </Compile>
<Compile Include="$(CommonTestPath)\System\ThreadCultureChange.cs">
<Link>Common\System\ThreadCultureChange.cs</Link>
</Compile>
diff --git a/src/System.Private.Uri/tests/FunctionalTests/System.Private.Uri.Functional.Tests.csproj b/src/System.Private.Uri/tests/FunctionalTests/System.Private.Uri.Functional.Tests.csproj
index 238c92c160..dafeadbd56 100644
--- a/src/System.Private.Uri/tests/FunctionalTests/System.Private.Uri.Functional.Tests.csproj
+++ b/src/System.Private.Uri/tests/FunctionalTests/System.Private.Uri.Functional.Tests.csproj
@@ -27,9 +27,6 @@
<Compile Include="UriTests.cs" />
<Compile Include="WebSocketsUriParserTest.cs" />
<!-- Test common -->
- <Compile Include="$(CommonTestPath)\System\AssertExtensions.cs">
- <Link>Common\System\AssertExtensions.cs</Link>
- </Compile>
<Compile Include="$(CommonTestPath)\System\ThreadCultureChange.cs">
<Link>Common\System\ThreadCultureChange.cs</Link>
</Compile>
diff --git a/src/System.Private.Xml.Linq/tests/Properties/System.Xml.Linq.Properties.Tests.csproj b/src/System.Private.Xml.Linq/tests/Properties/System.Xml.Linq.Properties.Tests.csproj
index 578b5720fb..772734494a 100644
--- a/src/System.Private.Xml.Linq/tests/Properties/System.Xml.Linq.Properties.Tests.csproj
+++ b/src/System.Private.Xml.Linq/tests/Properties/System.Xml.Linq.Properties.Tests.csproj
@@ -18,9 +18,6 @@
<Compile Include="IXmlLineInfo.cs" />
<Compile Include="NamespaceAccessors.cs" />
<Compile Include="XElement_Value.cs" />
- <Compile Include="$(CommonTestPath)\System\AssertExtensions.cs">
- <Link>Common\System\AssertExtensions.cs</Link>
- </Compile>
</ItemGroup>
<ItemGroup>
<ProjectReference Include="$(CommonTestPath)\System\Xml\XmlCoreTest\XmlCoreTest.csproj" />
diff --git a/src/System.Private.Xml.Linq/tests/SDMSample/System.Xml.Linq.SDMSample.Tests.csproj b/src/System.Private.Xml.Linq/tests/SDMSample/System.Xml.Linq.SDMSample.Tests.csproj
index a1346c0047..efa7daccce 100644
--- a/src/System.Private.Xml.Linq/tests/SDMSample/System.Xml.Linq.SDMSample.Tests.csproj
+++ b/src/System.Private.Xml.Linq/tests/SDMSample/System.Xml.Linq.SDMSample.Tests.csproj
@@ -21,9 +21,6 @@
<Compile Include="SDMNode.cs" />
<Compile Include="SDMPI.cs" />
<Compile Include="SDMXName.cs" />
- <Compile Include="$(CommonTestPath)\System\AssertExtensions.cs">
- <Link>Common\System\AssertExtensions.cs</Link>
- </Compile>
</ItemGroup>
<Import Project="$([MSBuild]::GetDirectoryNameOfFileAbove($(MSBuildThisFileDirectory), dir.targets))\dir.targets" />
</Project> \ No newline at end of file
diff --git a/src/System.Private.Xml.Linq/tests/Streaming/System.Xml.Linq.Streaming.Tests.csproj b/src/System.Private.Xml.Linq/tests/Streaming/System.Xml.Linq.Streaming.Tests.csproj
index e47da7e696..3e8d88ec48 100644
--- a/src/System.Private.Xml.Linq/tests/Streaming/System.Xml.Linq.Streaming.Tests.csproj
+++ b/src/System.Private.Xml.Linq/tests/Streaming/System.Xml.Linq.Streaming.Tests.csproj
@@ -12,9 +12,6 @@
<ItemGroup>
<Compile Include="StreamExtensions.cs" />
<Compile Include="StreamingOutput.cs" />
- <Compile Include="$(CommonTestPath)\System\AssertExtensions.cs">
- <Link>Common\System\AssertExtensions.cs</Link>
- </Compile>
</ItemGroup>
<ItemGroup>
<ProjectReference Include="$(CommonTestPath)\System\Xml\XmlDiff\XmlDiff.csproj" />
diff --git a/src/System.Private.Xml.Linq/tests/XDocument.Test.ModuleCore/testexception.cs b/src/System.Private.Xml.Linq/tests/XDocument.Test.ModuleCore/testexception.cs
index 37b05465b3..08639070d7 100644
--- a/src/System.Private.Xml.Linq/tests/XDocument.Test.ModuleCore/testexception.cs
+++ b/src/System.Private.Xml.Linq/tests/XDocument.Test.ModuleCore/testexception.cs
@@ -93,8 +93,8 @@ namespace Microsoft.Test.ModuleCore
public override string ToString()
{
- var expected = "Expected: " + Expected + " (" + Expected.GetType() + ")\n";
- var actual = "Actual : " + Actual + " (" + Actual.GetType() + ")\n";
+ var expected = "Expected: " + Expected + " (" + Expected?.GetType() + ")\n";
+ var actual = "Actual : " + Actual + " (" + Actual?.GetType() + ")\n";
return expected + actual + "\n" + base.ToString();
}
diff --git a/src/System.Private.Xml.Linq/tests/axes/System.Xml.Linq.Axes.Tests.csproj b/src/System.Private.Xml.Linq/tests/axes/System.Xml.Linq.Axes.Tests.csproj
index 47d22b02b8..574b48d62c 100644
--- a/src/System.Private.Xml.Linq/tests/axes/System.Xml.Linq.Axes.Tests.csproj
+++ b/src/System.Private.Xml.Linq/tests/axes/System.Xml.Linq.Axes.Tests.csproj
@@ -14,9 +14,6 @@
<Compile Include="Utils.cs" />
<Compile Include="TestData.cs" />
<Compile Include="InvalidParamValidation.cs" />
- <Compile Include="$(CommonTestPath)\System\AssertExtensions.cs">
- <Link>Common\System\AssertExtensions.cs</Link>
- </Compile>
</ItemGroup>
<Import Project="$([MSBuild]::GetDirectoryNameOfFileAbove($(MSBuildThisFileDirectory), dir.targets))\dir.targets" />
</Project> \ No newline at end of file
diff --git a/src/System.Private.Xml.Linq/tests/misc/System.Xml.Linq.Misc.Tests.csproj b/src/System.Private.Xml.Linq/tests/misc/System.Xml.Linq.Misc.Tests.csproj
index 8c45c26a47..ef13353846 100644
--- a/src/System.Private.Xml.Linq/tests/misc/System.Xml.Linq.Misc.Tests.csproj
+++ b/src/System.Private.Xml.Linq/tests/misc/System.Xml.Linq.Misc.Tests.csproj
@@ -18,9 +18,6 @@
<Compile Include="XLinqErrata4.cs" />
<Compile Include="XNameAPI.cs" />
<Compile Include="LoadSaveAsyncTests.cs" Condition="'$(TargetGroup)'=='netcoreapp'" />
- <Compile Include="$(CommonTestPath)\System\AssertExtensions.cs">
- <Link>Common\System\AssertExtensions.cs</Link>
- </Compile>
</ItemGroup>
<ItemGroup>
<ProjectReference Include="$(CommonTestPath)\System\Xml\ModuleCore\ModuleCore.csproj" />
diff --git a/src/System.Private.Xml.Linq/tests/xNodeBuilder/ErrorConditions.cs b/src/System.Private.Xml.Linq/tests/xNodeBuilder/ErrorConditions.cs
index 6823c47012..0ba81aafde 100644
--- a/src/System.Private.Xml.Linq/tests/xNodeBuilder/ErrorConditions.cs
+++ b/src/System.Private.Xml.Linq/tests/xNodeBuilder/ErrorConditions.cs
@@ -28,7 +28,7 @@ namespace CoreXml.Test.XLinq
}
catch (ArgumentNullException e)
{
- TestLog.Compare(e.ParamName, "ns", "prefix mismatch");
+ CompareParamName(e.ParamName, "ns", "prefix mismatch");
try
{
TestLog.Compare(w.WriteState, WriteState.Error, "Error");
@@ -37,7 +37,7 @@ namespace CoreXml.Test.XLinq
catch (ArgumentNullException ae)
{
TestLog.Compare(w.WriteState, WriteState.Error, "Error");
- TestLog.Compare(ae.ParamName, "ns", "prefix mismatch");
+ CompareParamName(ae.ParamName, "ns", "prefix mismatch");
return;
}
}
@@ -60,7 +60,7 @@ namespace CoreXml.Test.XLinq
}
catch (ArgumentNullException e)
{
- TestLog.Compare(e.ParamName, "reader", "mismatch");
+ CompareParamName(e.ParamName, "reader", "mismatch");
try
{
TestLog.Compare(w.WriteState, WriteState.Start, "Error");
@@ -69,7 +69,7 @@ namespace CoreXml.Test.XLinq
catch (ArgumentNullException ae)
{
TestLog.Compare(w.WriteState, WriteState.Start, "Error");
- TestLog.Compare(ae.ParamName, "reader", "mismatch");
+ CompareParamName(ae.ParamName, "reader", "mismatch");
return;
}
}
@@ -92,7 +92,7 @@ namespace CoreXml.Test.XLinq
}
catch (ArgumentException e)
{
- TestLog.Compare(e.ParamName, null, "mismatch");
+ CompareParamName(e.ParamName, null, "mismatch");
try
{
TestLog.Compare(w.WriteState, WriteState.Error, "Error");
@@ -101,7 +101,7 @@ namespace CoreXml.Test.XLinq
catch (ArgumentException)
{
TestLog.Compare(w.WriteState, WriteState.Error, "Error");
- TestLog.Compare(e.ParamName, null, "mismatch");
+ CompareParamName(e.ParamName, null, "mismatch");
return;
}
}
@@ -122,7 +122,7 @@ namespace CoreXml.Test.XLinq
}
catch (ArgumentNullException e)
{
- TestLog.Compare(e.ParamName, "buffer", "mismatch");
+ CompareParamName(e.ParamName, "buffer", "mismatch");
try
{
TestLog.Compare(w.WriteState, WriteState.Error, "Error");
@@ -131,7 +131,7 @@ namespace CoreXml.Test.XLinq
catch (ArgumentNullException ae)
{
TestLog.Compare(w.WriteState, WriteState.Error, "Error");
- TestLog.Compare(ae.ParamName, "buffer", "mismatch");
+ CompareParamName(ae.ParamName, "buffer", "mismatch");
return;
}
}
@@ -154,7 +154,7 @@ namespace CoreXml.Test.XLinq
}
catch (ArgumentNullException e)
{
- TestLog.Compare(e.ParamName, "buffer", "mismatch");
+ CompareParamName(e.ParamName, "buffer", "mismatch");
try
{
TestLog.Compare(w.WriteState, WriteState.Error, "Error");
@@ -278,7 +278,7 @@ namespace CoreXml.Test.XLinq
}
catch (ArgumentException e)
{
- TestLog.Compare(e.ParamName, null, "mismatch");
+ CompareParamName(e.ParamName, null, "mismatch");
try
{
TestLog.Compare(w.WriteState, WriteState.Error, "Error");
@@ -287,7 +287,7 @@ namespace CoreXml.Test.XLinq
catch (ArgumentException ae)
{
TestLog.Compare(w.WriteState, WriteState.Error, "Error");
- TestLog.Compare(ae.ParamName, null, "mismatch");
+ CompareParamName(ae.ParamName, null, "mismatch");
return;
}
}
@@ -449,7 +449,7 @@ namespace CoreXml.Test.XLinq
}
catch (ArgumentException e)
{
- TestLog.Compare(e.ParamName, "name", "mismatch");
+ CompareParamName(e.ParamName, "name", "mismatch");
try
{
TestLog.Compare(w.WriteState, WriteState.Start, "Error");
@@ -458,7 +458,7 @@ namespace CoreXml.Test.XLinq
catch (ArgumentException ae)
{
TestLog.Compare(w.WriteState, WriteState.Start, "Error");
- TestLog.Compare(ae.ParamName, "name", "mismatch");
+ CompareParamName(ae.ParamName, "name", "mismatch");
return;
}
}
@@ -481,7 +481,7 @@ namespace CoreXml.Test.XLinq
}
catch (ArgumentException e)
{
- TestLog.Compare(e.ParamName, null, "mismatch");
+ CompareParamName(e.ParamName, null, "mismatch");
try
{
TestLog.Compare(w.WriteState, WriteState.Start, "Error");
@@ -490,7 +490,7 @@ namespace CoreXml.Test.XLinq
catch (ArgumentException ae)
{
TestLog.Compare(w.WriteState, WriteState.Start, "Error");
- TestLog.Compare(ae.ParamName, null, "mismatch");
+ CompareParamName(ae.ParamName, null, "mismatch");
return;
}
}
@@ -524,10 +524,10 @@ namespace CoreXml.Test.XLinq
switch (param1)
{
case ("reader"):
- TestLog.Compare(e.ParamName, "reader", "mismatch");
+ CompareParamName(e.ParamName, "reader", "mismatch");
break;
case ("navigator"):
- TestLog.Compare(e.ParamName, "navigator", "mismatch");
+ CompareParamName(e.ParamName, "navigator", "mismatch");
break;
}
try
@@ -545,7 +545,7 @@ namespace CoreXml.Test.XLinq
switch (param1)
{
case ("reader"):
- TestLog.Compare(e.ParamName, "reader", "mismatch");
+ CompareParamName(e.ParamName, "reader", "mismatch");
break;
}
return;
@@ -570,7 +570,7 @@ namespace CoreXml.Test.XLinq
}
catch (ArgumentException e)
{
- TestLog.Compare(e.ParamName, null, "mismatch");
+ CompareParamName(e.ParamName, null, "mismatch");
try
{
TestLog.Compare(w.WriteState, WriteState.Error, "Error");
@@ -579,7 +579,7 @@ namespace CoreXml.Test.XLinq
catch (ArgumentException ae)
{
TestLog.Compare(w.WriteState, WriteState.Error, "Error");
- TestLog.Compare(ae.ParamName, null, "mismatch");
+ CompareParamName(ae.ParamName, null, "mismatch");
return;
}
}
@@ -602,7 +602,7 @@ namespace CoreXml.Test.XLinq
}
catch (ArgumentException e)
{
- TestLog.Compare(e.ParamName, null, "mismatch");
+ CompareParamName(e.ParamName, null, "mismatch");
try
{
TestLog.Compare(w.WriteState, WriteState.Error, "Error");
@@ -611,7 +611,7 @@ namespace CoreXml.Test.XLinq
catch (ArgumentException ae)
{
TestLog.Compare(w.WriteState, WriteState.Error, "Error");
- TestLog.Compare(ae.ParamName, null, "mismatch");
+ CompareParamName(ae.ParamName, null, "mismatch");
return;
}
}
@@ -632,7 +632,7 @@ namespace CoreXml.Test.XLinq
}
catch (ArgumentNullException e)
{
- TestLog.Compare(e.ParamName, "buffer", "mismatch");
+ CompareParamName(e.ParamName, "buffer", "mismatch");
try
{
TestLog.Compare(w.WriteState, WriteState.Error, "Error");
@@ -641,7 +641,7 @@ namespace CoreXml.Test.XLinq
catch (ArgumentNullException ae)
{
TestLog.Compare(w.WriteState, WriteState.Error, "Error");
- TestLog.Compare(ae.ParamName, "buffer", "mismatch");
+ CompareParamName(ae.ParamName, "buffer", "mismatch");
return;
}
}
@@ -664,7 +664,7 @@ namespace CoreXml.Test.XLinq
}
catch (ArgumentException e)
{
- TestLog.Compare(e.ParamName, null, "mismatch");
+ CompareParamName(e.ParamName, null, "mismatch");
try
{
TestLog.Compare(w.WriteState, WriteState.Error, "Error");
@@ -673,7 +673,7 @@ namespace CoreXml.Test.XLinq
catch (ArgumentException ae)
{
TestLog.Compare(w.WriteState, WriteState.Error, "Error");
- TestLog.Compare(ae.ParamName, null, "mismatch");
+ CompareParamName(ae.ParamName, null, "mismatch");
return;
}
}
@@ -696,7 +696,7 @@ namespace CoreXml.Test.XLinq
}
catch (ArgumentException e)
{
- TestLog.Compare(e.ParamName, null, "mismatch");
+ CompareParamName(e.ParamName, null, "mismatch");
try
{
TestLog.Compare(w.WriteState, WriteState.Error, "Error");
@@ -705,7 +705,7 @@ namespace CoreXml.Test.XLinq
catch (ArgumentException ae)
{
TestLog.Compare(w.WriteState, WriteState.Error, "Error");
- TestLog.Compare(ae.ParamName, null, "mismatch");
+ CompareParamName(ae.ParamName, null, "mismatch");
return;
}
}
@@ -1181,6 +1181,14 @@ namespace CoreXml.Test.XLinq
}
throw new TestException(TestResult.Failed, "");
}
+
+ private void CompareParamName(string actual, string expected, string message)
+ {
+ if (PlatformDetection.IsNetNative) // ILC optimization sets ParamName always to null.
+ return;
+
+ TestLog.Compare(actual, expected, message);
+ }
}
}
}
diff --git a/src/System.Private.Xml.Linq/tests/xNodeBuilder/System.Xml.Linq.xNodeBuilder.Tests.csproj b/src/System.Private.Xml.Linq/tests/xNodeBuilder/System.Xml.Linq.xNodeBuilder.Tests.csproj
index 5d852f9271..993626a53f 100644
--- a/src/System.Private.Xml.Linq/tests/xNodeBuilder/System.Xml.Linq.xNodeBuilder.Tests.csproj
+++ b/src/System.Private.Xml.Linq/tests/xNodeBuilder/System.Xml.Linq.xNodeBuilder.Tests.csproj
@@ -13,9 +13,6 @@
<Compile Include="$(CommonTestPath)\System\Collections\DictionaryExtensions.cs">
<Link>Common\System\Collections\DictionaryExtensions.cs</Link>
</Compile>
- <Compile Include="$(CommonTestPath)\System\AssertExtensions.cs">
- <Link>Common\System\AssertExtensions.cs</Link>
- </Compile>
<Compile Include="$(CommonTestPath)\System\PlatformDetection.cs">
<Link>Common\System\PlatformDetection.cs</Link>
</Compile>
diff --git a/src/System.Private.Xml/src/System.Private.Xml.csproj b/src/System.Private.Xml/src/System.Private.Xml.csproj
index 98c3b6a1ab..cf2a04bbd9 100644
--- a/src/System.Private.Xml/src/System.Private.Xml.csproj
+++ b/src/System.Private.Xml/src/System.Private.Xml.csproj
@@ -9,7 +9,7 @@
<NoWarn>$(NoWarn),649</NoWarn>
<FeatureCompiledXsl Condition="'$(TargetGroup)' != 'uap' AND '$(TargetGroup)' != 'uapaot'">true</FeatureCompiledXsl>
<DefineConstants Condition="'$(FeatureCompiledXsl)' == 'true'">$(DefineConstants);FEATURE_COMPILED_XSL</DefineConstants>
- <DefineConstants Condition="'$(TargetGroup)' == 'uapaot'">$(DefineConstants);FEATURE_SERIALIZATION_UAPAOT</DefineConstants>
+ <DefineConstants Condition="'$(TargetGroup)' == 'uapaot'">$(DefineConstants);FEATURE_SERIALIZATION_UAPAOT;UAPAOT</DefineConstants>
</PropertyGroup>
<!-- Default configurations to help VS understand the configurations -->
<PropertyGroup Condition="'$(Configuration)|$(Platform)' == 'netcoreapp-Unix-Debug|AnyCPU'" />
diff --git a/src/System.Private.Xml/src/System/Xml/Core/XmlReader.cs b/src/System.Private.Xml/src/System/Xml/Core/XmlReader.cs
index 07d74c168c..93e3a743b1 100644
--- a/src/System.Private.Xml/src/System/Xml/Core/XmlReader.cs
+++ b/src/System.Private.Xml/src/System/Xml/Core/XmlReader.cs
@@ -1849,7 +1849,11 @@ namespace System.Xml
// NOTE: This method is called via reflection from System.Data.dll and from Analysis Services in Yukon.
// Do not change its signature without notifying the appropriate teams!
// !!!!!!
+#if UAPAOT
+ public static XmlReader CreateSqlReader(Stream input, XmlReaderSettings settings, XmlParserContext inputContext)
+#else
internal static XmlReader CreateSqlReader(Stream input, XmlReaderSettings settings, XmlParserContext inputContext)
+#endif
{
if (input == null)
{
diff --git a/src/System.Private.Xml/src/System/Xml/Schema/XmlSchema.cs b/src/System.Private.Xml/src/System/Xml/Schema/XmlSchema.cs
index a91e76bfd1..23df11a251 100644
--- a/src/System.Private.Xml/src/System/Xml/Schema/XmlSchema.cs
+++ b/src/System.Private.Xml/src/System/Xml/Schema/XmlSchema.cs
@@ -181,7 +181,7 @@ namespace System.Xml.Schema
bool ignoreXS = false;
if (this.Namespaces != null)
{ //User may have set both nsManager and Namespaces property on the XmlSchema object
- ignoreXS = this.Namespaces.Namespaces["xs"] != null || this.Namespaces.Namespaces.ContainsValue(XmlReservedNs.NsXs);
+ ignoreXS = this.Namespaces.Namespaces.ContainsKey("xs") || this.Namespaces.Namespaces.ContainsValue(XmlReservedNs.NsXs);
}
if (!ignoreXS && namespaceManager.LookupPrefix(XmlReservedNs.NsXs) == null &&
namespaceManager.LookupNamespace("xs") == null)
diff --git a/src/System.Private.Xml/src/System/Xml/Serialization/ReflectionXmlSerializationWriter.cs b/src/System.Private.Xml/src/System/Xml/Serialization/ReflectionXmlSerializationWriter.cs
index 3ce10d1f8f..a19d017d6d 100644
--- a/src/System.Private.Xml/src/System/Xml/Serialization/ReflectionXmlSerializationWriter.cs
+++ b/src/System.Private.Xml/src/System/Xml/Serialization/ReflectionXmlSerializationWriter.cs
@@ -1400,7 +1400,26 @@ namespace System.Xml.Serialization
MemberInfo[] memberInfos = declaringType.GetMember(memberName);
if (memberInfos == null || memberInfos.Length == 0)
{
- throw new InvalidOperationException(SR.Format(SR.XmlInternalErrorDetails, $"Could not find member named {memberName} of type {declaringType.ToString()}"));
+ bool foundMatchedMember = false;
+ Type currentType = declaringType.BaseType;
+ while (currentType != null)
+ {
+ memberInfos = currentType.GetMember(memberName);
+ if (memberInfos != null && memberInfos.Length != 0)
+ {
+ foundMatchedMember = true;
+ break;
+ }
+
+ currentType = currentType.BaseType;
+ }
+
+ if (!foundMatchedMember)
+ {
+ throw new InvalidOperationException(SR.Format(SR.XmlInternalErrorDetails, $"Could not find member named {memberName} of type {declaringType.ToString()}"));
+ }
+
+ declaringType = currentType;
}
MemberInfo memberInfo = memberInfos[0];
diff --git a/src/System.Private.Xml/src/System/Xml/Serialization/Types.cs b/src/System.Private.Xml/src/System/Xml/Serialization/Types.cs
index 264c7a7478..5d0e51d811 100644
--- a/src/System.Private.Xml/src/System/Xml/Serialization/Types.cs
+++ b/src/System.Private.Xml/src/System/Xml/Serialization/Types.cs
@@ -1194,21 +1194,19 @@ namespace System.Xml.Serialization
replacedInfo = info;
if (replacedInfo != memberInfoToBeReplaced)
{
- if (!info.GetMethod.IsPublic)
+ if (!info.GetMethod.IsPublic
+ && memberInfoToBeReplaced is PropertyInfo
+ && ((PropertyInfo)memberInfoToBeReplaced).GetMethod.IsPublic
+ )
{
- if (memberInfoToBeReplaced is PropertyInfo propertyInfoToBeReplaced)
- {
- if (propertyInfoToBeReplaced.GetMethod.IsPublic)
- {
- return false;
- }
- }
+ break;
}
return true;
}
}
}
+
foreach (FieldInfo info in currentInfo.DeclaredFields)
{
if (info.Name == memberInfoToBeReplaced.Name)
@@ -1401,8 +1399,8 @@ namespace System.Xml.Serialization
{
if (parent.Namespaces != null)
{
- string wsdlNs = (string)parent.Namespaces.Namespaces[ns];
- if (wsdlNs != null)
+ string wsdlNs;
+ if (parent.Namespaces.Namespaces.TryGetValue(ns, out wsdlNs) && wsdlNs != null)
{
ns = wsdlNs;
break;
diff --git a/src/System.Private.Xml/src/System/Xml/Serialization/XmlSerializationWriter.cs b/src/System.Private.Xml/src/System/Xml/Serialization/XmlSerializationWriter.cs
index 29985069d5..db54775549 100644
--- a/src/System.Private.Xml/src/System/Xml/Serialization/XmlSerializationWriter.cs
+++ b/src/System.Private.Xml/src/System/Xml/Serialization/XmlSerializationWriter.cs
@@ -1402,8 +1402,8 @@ namespace System.Xml.Serialization
string ns = (string)entry.Value;
if (_namespaces != null)
{
- string oldNs = _namespaces.Namespaces[prefix] as string;
- if (oldNs != null && oldNs != ns)
+ string oldNs;
+ if (_namespaces.Namespaces.TryGetValue(prefix, out oldNs) && oldNs != null && oldNs != ns)
{
throw new InvalidOperationException(SR.Format(SR.XmlDuplicateNs, prefix, ns));
}
diff --git a/src/System.Private.Xml/src/System/Xml/XmlResolver.cs b/src/System.Private.Xml/src/System/Xml/XmlResolver.cs
index a34a902fc4..a994b1b67b 100644
--- a/src/System.Private.Xml/src/System/Xml/XmlResolver.cs
+++ b/src/System.Private.Xml/src/System/Xml/XmlResolver.cs
@@ -40,7 +40,7 @@ namespace System.Xml
Uri uri = new Uri(relativeUri, UriKind.RelativeOrAbsolute);
if (!uri.IsAbsoluteUri && uri.OriginalString.Length > 0)
{
- uri = new Uri(Uri.UriSchemeFile + Uri.SchemeDelimiter + Path.GetFullPath(relativeUri));
+ uri = new Uri(Path.GetFullPath(relativeUri));
}
return uri;
}
diff --git a/src/System.Private.Xml/tests/Writers/XmlWriterApi/TCXmlWriterTestModule.cs b/src/System.Private.Xml/tests/Writers/XmlWriterApi/TCXmlWriterTestModule.cs
index 128b0a0154..b2a39a83d8 100644
--- a/src/System.Private.Xml/tests/Writers/XmlWriterApi/TCXmlWriterTestModule.cs
+++ b/src/System.Private.Xml/tests/Writers/XmlWriterApi/TCXmlWriterTestModule.cs
@@ -97,6 +97,7 @@ namespace System.Xml.Tests
[Fact]
[OuterLoop]
+ [ActiveIssue(22042, TargetFrameworkMonikers.UapNotUapAot)]
public static void TCFullEndElement()
{
RunTest(() => new TCFullEndElement() { Attribute = new TestCase() { Name = "WriteFullEndElement" } });
diff --git a/src/System.Private.Xml/tests/XmlDocument/System.Xml.XmlDocument.Tests.csproj b/src/System.Private.Xml/tests/XmlDocument/System.Xml.XmlDocument.Tests.csproj
index a7db6c2642..4c9179e286 100644
--- a/src/System.Private.Xml/tests/XmlDocument/System.Xml.XmlDocument.Tests.csproj
+++ b/src/System.Private.Xml/tests/XmlDocument/System.Xml.XmlDocument.Tests.csproj
@@ -99,9 +99,6 @@
<Compile Include="XmlProcessingInstructionTests\DataTests.cs" />
<Compile Include="XmlProcessingInstructionTests\TargetTests.cs" />
<Compile Include="XmlTextTests\SplitTextTests.cs" />
- <Compile Include="$(CommonTestPath)\System\AssertExtensions.cs">
- <Link>Common\System\AssertExtensions.cs</Link>
- </Compile>
<!-- Performance Tests -->
<Compile Include="Performance\Perf.XmlDocument.cs" />
<Compile Include="Performance\Perf.XmlNode.cs" />
diff --git a/src/System.Private.Xml/tests/XmlReader/Tests/BaseUriTests.cs b/src/System.Private.Xml/tests/XmlReader/Tests/BaseUriTests.cs
index 7a159155dd..4d084ca80b 100644
--- a/src/System.Private.Xml/tests/XmlReader/Tests/BaseUriTests.cs
+++ b/src/System.Private.Xml/tests/XmlReader/Tests/BaseUriTests.cs
@@ -32,7 +32,7 @@ namespace System.Xml.Tests
File.WriteAllText(tempPath, DummyXml);
using (XmlReader reader = factory(tempPath))
{
- Assert.True(new Uri(reader.BaseURI).IsAbsoluteUri);
+ Assert.True(new Uri(reader.BaseURI, UriKind.RelativeOrAbsolute).IsAbsoluteUri);
}
}
}
diff --git a/src/System.Private.Xml/tests/XmlReader/XmlResolver/XmlSystemPathResolverTests.cs b/src/System.Private.Xml/tests/XmlReader/XmlResolver/XmlSystemPathResolverTests.cs
index 43eac03613..4404f5fb9c 100644
--- a/src/System.Private.Xml/tests/XmlReader/XmlResolver/XmlSystemPathResolverTests.cs
+++ b/src/System.Private.Xml/tests/XmlReader/XmlResolver/XmlSystemPathResolverTests.cs
@@ -92,7 +92,7 @@ namespace System.Xml.Tests
[Fact]
public static void TestResolveInvalidPath()
{
- Assert.Throws<System.Net.WebException>(() => XmlReader.Create("ftp://www.bing.com"));
+ Assert.Throws<System.Net.WebException>(() => XmlReader.Create("ftp://host.invalid"));
}
[Fact]
diff --git a/src/System.Private.Xml/tests/XmlSchema/XmlSchemaSet/System.Xml.XmlSchemaSet.Tests.csproj b/src/System.Private.Xml/tests/XmlSchema/XmlSchemaSet/System.Xml.XmlSchemaSet.Tests.csproj
index 022eaf1683..9c732c3815 100644
--- a/src/System.Private.Xml/tests/XmlSchema/XmlSchemaSet/System.Xml.XmlSchemaSet.Tests.csproj
+++ b/src/System.Private.Xml/tests/XmlSchema/XmlSchemaSet/System.Xml.XmlSchemaSet.Tests.csproj
@@ -17,6 +17,7 @@
<Compile Include="TC_SchemaSet_Add_SchemaSet.cs" />
<Compile Include="TC_SchemaSet_Add_URL.cs" />
<Compile Include="TC_SchemaSet_AllowXmlAttributes.cs" />
+ <Compile Include="TC_SchemaSet_AnyAttribute.cs" />
<Compile Include="TC_SchemaSet_Compile.cs" />
<Compile Include="TC_SchemaSet_Constructors.cs" />
<Compile Include="TC_SchemaSet_Contains_ns.cs" />
diff --git a/src/System.Private.Xml/tests/XmlSchema/XmlSchemaSet/TC_SchemaSet_AnyAttribute.cs b/src/System.Private.Xml/tests/XmlSchema/XmlSchemaSet/TC_SchemaSet_AnyAttribute.cs
new file mode 100644
index 0000000000..9b63d6e217
--- /dev/null
+++ b/src/System.Private.Xml/tests/XmlSchema/XmlSchemaSet/TC_SchemaSet_AnyAttribute.cs
@@ -0,0 +1,193 @@
+// Licensed to the .NET Foundation under one or more agreements.
+// The .NET Foundation licenses this file to you under the MIT license.
+// See the LICENSE file in the project root for more information.
+
+using Xunit;
+using Xunit.Abstractions;
+using System.IO;
+using System.Xml.Schema;
+
+namespace System.Xml.Tests
+{
+ public class TC_SchemaSet_AnyAttribute : TC_SchemaSetBase
+ {
+ private readonly ITestOutputHelper _output;
+ private int _errorCount;
+ private int _warningCount;
+ private bool _warningInnerExceptionSet;
+ private bool _errorInnerExceptionSet;
+
+ public TC_SchemaSet_AnyAttribute(ITestOutputHelper output)
+ {
+ _output = output;
+ }
+
+ //hook up validaton callback
+ public void ValidationCallback(object sender, ValidationEventArgs args)
+ {
+ if (args.Severity == XmlSeverityType.Warning)
+ {
+ _output.WriteLine("WARNING: ");
+ _warningCount++;
+ _warningInnerExceptionSet = (args.Exception.InnerException != null);
+ _output.WriteLine("\nInnerExceptionSet : " + _warningInnerExceptionSet + "\n");
+ }
+ else if (args.Severity == XmlSeverityType.Error)
+ {
+ _output.WriteLine("ERROR: ");
+ _errorCount++;
+ _errorInnerExceptionSet = (args.Exception.InnerException != null);
+ _output.WriteLine("\nInnerExceptionSet : " + _errorInnerExceptionSet + "\n");
+ }
+
+ _output.WriteLine(args.Message);
+ }
+
+ public XmlSchema GetUnionSchema(string ns1, string ns2, string attrNs)
+ {
+ var xsd = @"<xs:schema xmlns:xs='http://www.w3.org/2001/XMLSchema' targetNamespace='" + attrNs + @"' xmlns='" + attrNs + @"'>
+ <xs:attribute name='baseattribute'>
+ <xs:simpleType >
+ <xs:restriction base = 'xs:int' >
+ <xs:maxInclusive value = '1000' />
+ </xs:restriction >
+ </xs:simpleType >
+ </xs:attribute >
+ <xs:complexType name = 't'>
+ <xs:sequence >
+ <xs:element name = 'e1' type = 'xs:string' />
+ </xs:sequence >
+ <xs:anyAttribute namespace='" + ns2 + @"'/>
+ </xs:complexType>
+ <xs:complexType name = 't1'>
+ <xs:complexContent>
+ <xs:extension base='t'>
+ <xs:sequence >
+ <xs:element name = 'e2' type = 'xs:string' />
+ </xs:sequence>
+ <xs:anyAttribute namespace='" + ns1 + @"'/>
+ </xs:extension>
+ </xs:complexContent>
+ </xs:complexType>
+ <xs:complexType name = 't2'>
+ <xs:complexContent>
+ <xs:restriction base='t1'>
+ <xs:sequence >
+ <xs:element name = 'e1' type = 'xs:string' fixed='name'/>
+ <xs:element name = 'e2' type = 'xs:string' fixed='name'/>
+ </xs:sequence >
+ <xs:attribute ref='baseattribute'/>
+ </xs:restriction>
+ </xs:complexContent>
+ </xs:complexType>
+ </xs:schema>";
+
+ return XmlSchema.Read(new StringReader(xsd), null);
+ }
+
+ public XmlSchema GetIntersectionSchema(string ns1, string ns2, string attrNs)
+ {
+ var xsd = @"<xs:schema xmlns:xs='http://www.w3.org/2001/XMLSchema' targetNamespace='" + attrNs + @"' xmlns='" + attrNs + @"'>
+ <xs:attribute name='baseattribute'>
+ <xs:simpleType >
+ <xs:restriction base = 'xs:int' >
+ <xs:maxInclusive value = '1000' />
+ </xs:restriction >
+ </xs:simpleType >
+ </xs:attribute >
+ <xs:attributeGroup name = 'attr-gr' >
+ <xs:attribute name = 'a1' type = 'xs:int' />
+ <xs:anyAttribute namespace='" + ns2 + @"'/>
+ </xs:attributeGroup >
+ <xs:complexType name = 't'>
+ <xs:sequence >
+ <xs:element name = 'e1' type = 'xs:string' />
+ </xs:sequence >
+ <xs:attributeGroup ref='attr-gr' />
+ <xs:anyAttribute namespace='" + ns1 + @"'/>
+ </xs:complexType>
+ <xs:complexType name = 't1'>
+ <xs:complexContent>
+ <xs:restriction base='t'>
+ <xs:sequence >
+ <xs:element name = 'e1' type = 'xs:string' fixed='name'/>
+ </xs:sequence >
+ <xs:attribute ref='baseattribute'/>
+ </xs:restriction>
+ </xs:complexContent>
+ </xs:complexType>
+ </xs:schema>";
+
+ return XmlSchema.Read(new StringReader(xsd), null);
+ }
+
+ //Intersection namespaces
+ [Theory]
+ //[Variation(Desc = "complextype Any ns - ##any, attrgroup Any ns2, allow ns2 attribute")]
+ [InlineData("##any", "ns2", "ns2", 0)]
+ //[Variation(Desc = "complextype Any ns - ##any, attrgroup Any ns2, not allow ns1 attribute")]
+ [InlineData("##any", "ns2", "ns1", 1)]
+ //[Variation(Desc = "complextype Any ns - ns2, attrgroup Any ##any, allow ns2 attribute")]
+ [InlineData("ns2", "##any", "ns2", 0)]
+ //[Variation(Desc = "complextype Any ns - ns2, attrgroup Any ##any, not allow ns1 attribute")]
+ [InlineData("ns2", "##any", "ns1", 1)]
+ //[Variation(Desc = "complextype Any ns - ns1 ns2, attrgroup Any ##other, not allow ns1 attribute")]
+ [InlineData("ns1 ns2", "##other", "ns1", 1)]
+ //[Variation(Desc = "complextype Any ns - ns1 ns2, attrgroup Any ##other, not allow ns2 attribute")]
+ [InlineData("ns1 ns2", "##other", "ns2", 1)]
+ //[Variation(Desc = "complextype Any ns - ns1 ns2, attrgroup Any #other, not allow ns3 attribute")]
+ [InlineData("ns1 ns2", "##other", "ns3", 1)]
+ //[Variation(Desc = "complextype Any ns - ##other, attrgroup Any ns1 ns2, not allow ns1 attribute")]
+ [InlineData("##other", "ns1 ns2", "ns1", 1)]
+ //[Variation(Desc = "complextype Any ns - ##other, attrgroup Any ns1 ns2, not allow ns2 attribute")]
+ [InlineData("##other", "ns1 ns2", "ns2", 1)]
+ //[Variation(Desc = "complextype Any ns - ##other, attrgroup Any ns1 ns2, not allow ns3 attribute")]
+ [InlineData("##other", "ns1 ns2", "ns3", 1)]
+ //[Variation(Desc = "complextype Any ns - ns1 ns3, attrgroup Any ns1 ns2, not allow ns3 attribute")]
+ [InlineData("ns1 ns3", "ns1 ns2", "ns3", 1)]
+ //[Variation(Desc = "complextype Any ns - ns1 ns3, attrgroup Any ns1 ns2, not allow ns2 attribute")]
+ [InlineData("ns1 ns3", "ns1 ns2", "ns2", 1)]
+ //[Variation(Desc = "complextype Any ns - ns1 ns3, attrgroup Any ns1 ns2, allow ns1 attribute")]
+ [InlineData("ns1 ns3", "ns1 ns2", "ns1", 0)]
+ //[Variation(Desc = "complextype Any ns - ##other, attrgroup Any ##other, not allow ns1 attribute")]
+ [InlineData("##other", "##other", "ns1", 1)]
+ public void v1(string ns1, string ns2, string attrNs, int expectedError)
+ {
+ XmlSchemaSet xss = new XmlSchemaSet();
+ xss.XmlResolver = new XmlUrlResolver();
+ xss.ValidationEventHandler += new ValidationEventHandler(ValidationCallback);
+ xss.Add(GetIntersectionSchema(ns1, ns2, attrNs));
+ xss.Compile();
+
+ Assert.Equal(expectedError, _errorCount);
+ }
+
+ [Theory]
+ //[Variation(Desc = "basetype Any ns - ##any, derivedType Any ns - ns1, allow ns2 attribute")]
+ [InlineData("##any", "ns1", "ns2", 0)]
+ //[Variation(Desc = "basetype Any ns - ns1, derivedType Any ns - ##any, allow ns2 attribute")]
+ [InlineData("ns1", "##any", "ns2", 0)]
+ //[Variation(Desc = "basetype Any ns - ns1 ns2, derivedType Any ns - ns2 ns3 , allow ns3 attribute")]
+ [InlineData("ns1 ns2", "ns2 ns3", "ns3", 0)]
+ //[Variation(Desc = "basetype Any ns - ##other, derivedType Any ns - ##other , not allow current ns")]
+ [InlineData("##other", "##other", "ns1", 1)]
+ //[Variation(Desc = "basetype Any ns - ns1 ns2, derivedType Any ns - ##other , allow ns1")]
+ [InlineData("ns1 ns2", "##other", "ns1", 0)]
+ //[Variation(Desc = "basetype Any ns - ns1 ns2, derivedType Any ns - ##other , allow ns2")]
+ [InlineData("ns1 ns2", "##other", "ns2", 0)]
+ //[Variation(Desc = "basetype Any ns - ##other, derivedType Any ns - ns1 ns2 , allow ns2")]
+ [InlineData("##other", "ns1 ns2", "ns1", 0)]
+ //[Variation(Desc = "basetype Any ns - ##other, derivedType Any ns - ns1 ns2 , allow ns2")]
+ [InlineData("##other", "ns1 ns2", "ns2", 0)]
+ public void v2(string ns1, string ns2, string attrNs, int expectedError)
+ {
+ XmlSchemaSet xss = new XmlSchemaSet();
+ xss.XmlResolver = new XmlUrlResolver();
+ xss.ValidationEventHandler += new ValidationEventHandler(ValidationCallback);
+ xss.Add(GetUnionSchema(ns1, ns2, attrNs));
+ xss.Compile();
+
+ Assert.Equal(expectedError, _errorCount);
+ }
+ }
+}
diff --git a/src/System.Private.Xml/tests/XmlSerializer/ReflectionOnly/System.Xml.XmlSerializer.ReflectionOnly.Tests.csproj b/src/System.Private.Xml/tests/XmlSerializer/ReflectionOnly/System.Xml.XmlSerializer.ReflectionOnly.Tests.csproj
index 7a31b6c5d9..5880a07733 100644
--- a/src/System.Private.Xml/tests/XmlSerializer/ReflectionOnly/System.Xml.XmlSerializer.ReflectionOnly.Tests.csproj
+++ b/src/System.Private.Xml/tests/XmlSerializer/ReflectionOnly/System.Xml.XmlSerializer.ReflectionOnly.Tests.csproj
@@ -16,9 +16,6 @@
<Compile Include="$(TestSourceFolder)..\..\..\..\System.Runtime.Serialization.Xml\tests\Performance\PerformanceTestsCommon.cs" />
<Compile Include="$(TestSourceFolder)..\XmlSerializerTests.cs" />
<Compile Include="$(TestSourceFolder)..\Performance\XsPerformanceTest.cs" />
- <Compile Include="$(CommonTestPath)\System\AssertExtensions.cs">
- <Link>Common\System\AssertExtensions.cs</Link>
- </Compile>
<Compile Include="$(CommonTestPath)\System\PlatformDetection.cs">
<Link>CommonTest\System\PlatformDetection.cs</Link>
</Compile>
diff --git a/src/System.Private.Xml/tests/XmlSerializer/System.Xml.XmlSerializer.Tests.csproj b/src/System.Private.Xml/tests/XmlSerializer/System.Xml.XmlSerializer.Tests.csproj
index eaf78c28c7..fb06113c7e 100644
--- a/src/System.Private.Xml/tests/XmlSerializer/System.Xml.XmlSerializer.Tests.csproj
+++ b/src/System.Private.Xml/tests/XmlSerializer/System.Xml.XmlSerializer.Tests.csproj
@@ -14,9 +14,6 @@
<Compile Include="$(TestSourceFolder)..\..\..\System.Runtime.Serialization.Xml\tests\Utils.cs" />
<Compile Include="$(TestSourceFolder)..\..\..\System.Runtime.Serialization.Xml\tests\SerializationTypes.cs" />
<Compile Include="$(TestSourceFolder)XmlSerializerTests.cs" />
- <Compile Include="$(CommonTestPath)\System\AssertExtensions.cs">
- <Link>Common\System\AssertExtensions.cs</Link>
- </Compile>
<Compile Include="$(CommonTestPath)\System\PlatformDetection.cs">
<Link>CommonTest\System\PlatformDetection.cs</Link>
</Compile>
diff --git a/src/System.Private.Xml/tests/XmlSerializer/XmlSerializerTests.cs b/src/System.Private.Xml/tests/XmlSerializer/XmlSerializerTests.cs
index 9a0b869d2f..0dd5ef1c0b 100644
--- a/src/System.Private.Xml/tests/XmlSerializer/XmlSerializerTests.cs
+++ b/src/System.Private.Xml/tests/XmlSerializer/XmlSerializerTests.cs
@@ -13,6 +13,7 @@ using System.Text;
using System.Threading;
using System.Xml;
using System.Xml.Linq;
+using System.Xml.Schema;
using System.Xml.Serialization;
using Xunit;
@@ -1219,6 +1220,35 @@ string.Format(@"<?xml version=""1.0"" encoding=""utf-8""?>
}
[Fact]
+ public static void XML_TypeWithMemberWithXmlNamespaceDeclarationsAttribute_WithInitialValue()
+ {
+ var ns = new XmlQualifiedName("ns", "http://tempuri.org");
+ var original = new TypeWithMemberWithXmlNamespaceDeclarationsAttribute() { header = "foo", body = "bar", xmlns = new XmlSerializerNamespaces(new[] { ns }) };
+
+ var actual = SerializeAndDeserialize<TypeWithMemberWithXmlNamespaceDeclarationsAttribute>(original,
+ @"<?xml version=""1.0""?>
+<Envelope xmlns:xsi=""http://www.w3.org/2001/XMLSchema-instance"" xmlns:xsd=""http://www.w3.org/2001/XMLSchema"" xmlns=""http://www.w3.org/2003/05/soap-envelope"" xmlns:ns=""http://tempuri.org"">
+ <header>foo</header>
+ <body>bar</body>
+</Envelope>");
+
+ Assert.StrictEqual(original.header, actual.header);
+ Assert.StrictEqual(original.body, actual.body);
+ Assert.NotNull(actual.xmlns);
+ Assert.Contains(ns, actual.xmlns.ToArray());
+ }
+
+ [Fact]
+ public static void XML_XmlSchemaWithNamespacesWriteWithNamespaceManager()
+ {
+ var schema = new XmlSchema();
+ schema.Namespaces = new XmlSerializerNamespaces();
+
+ using (var memStream = new MemoryStream())
+ schema.Write(memStream, new XmlNamespaceManager(new NameTable()));
+ }
+
+ [Fact]
public static void XML_TypeWithXmlTextAttributeOnArray()
{
var original = new TypeWithXmlTextAttributeOnArray() { Text = new string[] { "val1", "val2" } };
@@ -3279,7 +3309,6 @@ string.Format(@"<?xml version=""1.0"" encoding=""utf-8""?>
Assert.Equal(value.value, ((DerivedClass)actual).value);
}
-#if !uapaot
[Fact]
public static void Xml_DefaultValueAttributeSetToNaNTest()
{
@@ -3295,7 +3324,6 @@ string.Format(@"<?xml version=""1.0"" encoding=""utf-8""?>
Assert.NotNull(actual);
Assert.Equal(value, actual);
}
-#endif
[Fact]
public static void Xml_NullRefInXmlSerializerCtorTest()
@@ -4380,7 +4408,6 @@ string.Format(@"<?xml version=""1.0"" encoding=""utf-8""?>
Assert.StrictEqual(deserializedValue.IsFirstRun, value.IsFirstRun);
}
-#if !ReflectionOnly
[Fact]
[SkipOnTargetFramework(TargetFrameworkMonikers.NetFramework, "dotnet/corefx #21724")]
public static void DerivedTypeWithDifferentOverrides()
@@ -4393,7 +4420,96 @@ string.Format(@"<?xml version=""1.0"" encoding=""utf-8""?>
Assert.Null(actual.Name4);
Assert.StrictEqual(value.Name5, actual.Name5);
}
-#endif
+
+ [Fact]
+ [SkipOnTargetFramework(TargetFrameworkMonikers.NetFramework, "dotnet/corefx #21724")]
+ public static void DerivedTypeWithDifferentOverrides2()
+ {
+ DerivedTypeWithDifferentOverrides2 value = new DerivedTypeWithDifferentOverrides2() { Name1 = "Name1", Name2 = "Name2", Name3 = "Name3", Name4 = "Name4", Name5 = "Name5", Name6 = "Name6" };
+ ((DerivedTypeWithDifferentOverrides)value).Name5 = "MidLevelName5";
+ ((DerivedTypeWithDifferentOverrides)value).Name4 = "MidLevelName4";
+ ((SerializationTypes.BaseType)value).Name4 = "BaseLevelName4";
+ ((DerivedTypeWithDifferentOverrides)value).Name6 = "MidLevelName6";
+ ((SerializationTypes.BaseType)value).Name6 = "BaseLevelName6";
+ DerivedTypeWithDifferentOverrides2 actual = SerializeAndDeserialize<DerivedTypeWithDifferentOverrides2>(value, @"<?xml version=""1.0""?><DerivedTypeWithDifferentOverrides2 xmlns:xsi=""http://www.w3.org/2001/XMLSchema-instance"" xmlns:xsd=""http://www.w3.org/2001/XMLSchema""><Name1>Name1</Name1><Name2>Name2</Name2><Name3>Name3</Name3><Name4>BaseLevelName4</Name4><Name5>MidLevelName5</Name5><Name6>BaseLevelName6</Name6></DerivedTypeWithDifferentOverrides2>");
+ Assert.StrictEqual(value.Name1, actual.Name1);
+ Assert.StrictEqual(value.Name2, actual.Name2);
+ Assert.StrictEqual(value.Name3, actual.Name3);
+ Assert.Null(actual.Name4);
+ Assert.Null(((DerivedTypeWithDifferentOverrides)actual).Name4);
+ Assert.StrictEqual(((SerializationTypes.BaseType)value).Name4, ((SerializationTypes.BaseType)actual).Name4);
+ Assert.Null(actual.Name5);
+ Assert.StrictEqual(((DerivedTypeWithDifferentOverrides)value).Name5, ((DerivedTypeWithDifferentOverrides)actual).Name5);
+ Assert.Null(((SerializationTypes.BaseType)actual).Name5);
+ Assert.Null(actual.Name6);
+ Assert.StrictEqual(((DerivedTypeWithDifferentOverrides)actual).Name6, ((SerializationTypes.BaseType)actual).Name6);
+ Assert.StrictEqual(((SerializationTypes.BaseType)actual).Name6, ((SerializationTypes.BaseType)actual).Name6);
+ }
+
+ [Fact]
+ public static void Xml_DefaultNamespaceChange_SimpleArray_ObjectAsRoot()
+ {
+ SimpleType[] x = new SimpleType[] { new SimpleType { P1 = "abc", P2 = 11 }, new SimpleType { P1 = "def", P2 = 12 } };
+ Func<XmlSerializer> serializerFactory = () => { return new XmlSerializer(typeof(object), new Type[] { typeof(SimpleType[]) }); };
+
+ SimpleType[] y = SerializeAndDeserialize(x,
+@"<?xml version=""1.0""?>
+<anyType d1p1:type=""ArrayOfSimpleType"" xmlns:d1p1=""http://www.w3.org/2001/XMLSchema-instance"" >
+ <SimpleType xmlns:xsd=""http://www.w3.org/2001/XMLSchema"">
+ <P1>abc</P1>
+ <P2>11</P2>
+ </SimpleType>
+ <SimpleType>
+ <P1>def</P1>
+ <P2>12</P2>
+ </SimpleType>
+</anyType>", serializerFactory);
+
+ Utils.Equal(x, y, (a, b) => { return SimpleType.AreEqual(a, b); });
+ }
+
+ [Fact]
+ public static void Xml_ValidateExceptionOnUnspecifiedRootSerializationType()
+ {
+ var value = new UnspecifiedRootSerializationType();
+ var actual = SerializeAndDeserialize(value, "<?xml version=\"1.0\"?>\r\n<UnspecifiedRootSerializationType xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\" xmlns:xsd=\"http://www.w3.org/2001/XMLSchema\">\r\n <MyIntProperty>0</MyIntProperty>\r\n</UnspecifiedRootSerializationType>", () => { return new XmlSerializer(Type.GetType(typeof(UnspecifiedRootSerializationType).FullName)); });
+ Assert.StrictEqual(value.MyIntProperty, actual.MyIntProperty);
+ Assert.StrictEqual(value.MyStringProperty, actual.MyStringProperty);
+ }
+
+ [Fact]
+ public static void Xml_VerifyCompilationIssueOnly()
+ {
+ AssertSerializationFailure<TypeWithEnumerableMembers, InvalidOperationException>();
+ AssertSerializationFailure<TypeWithoutPublicSetter, InvalidOperationException>();
+ AssertSerializationFailure<TypeWithCompilerGeneratedAttributeButWithoutPublicSetter, InvalidOperationException>();
+ AssertSerializationFailure<InvalidDerivedClass, InvalidOperationException>();
+ AssertSerializationFailure<AnotherInvalidDerivedClass, InvalidOperationException>();
+ AssertSerializationFailure<InternalTypeWithNestedPublicType.LevelData, InvalidOperationException>();
+ AssertSerializationFailure<InternalTypeWithNestedPublicTypeWithNestedPublicType.NestedPublicType.LevelData, InvalidOperationException>();
+
+ var value1 = new DuplicateTypeNamesTest.ns1.ClassA();
+ var actual = SerializeAndDeserialize(value1, "<?xml version=\"1.0\"?>\r\n<ClassA xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\" xmlns:xsd=\"http://www.w3.org/2001/XMLSchema\" />");
+ Assert.Equal(value1.Name, actual.Name);
+
+ var value2 = new DuplicateTypeNamesTest.ns2.ClassA();
+ var actual2 = SerializeAndDeserialize(value2, "<?xml version=\"1.0\"?>\r\n<ClassA xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\" xmlns:xsd=\"http://www.w3.org/2001/XMLSchema\" />");
+ Assert.Equal(value2.Nombre, actual2.Nombre);
+ }
+
+ [Fact]
+ public static void Xml_DefaultNamespaceChange_ObjectAsRoot()
+ {
+ object value = ItemChoiceType.DecimalNumber;
+ Func<XmlSerializer> serializerFactory = () => { return new XmlSerializer(typeof(object), new Type[] { typeof(ItemChoiceType[]) }); };
+
+ var actual = SerializeAndDeserialize(value,
+ @"<?xml version=""1.0""?>
+<anyType d1p1:type=""ItemChoiceType"" xmlns:d1p1=""http://www.w3.org/2001/XMLSchema-instance"">DecimalNumber</anyType>",
+ serializerFactory);
+
+ Assert.StrictEqual(value, actual);
+ }
private static readonly string s_defaultNs = "http://tempuri.org/";
private static T RoundTripWithXmlMembersMapping<T>(object requestBodyValue, string memberName, string baseline, bool skipStringCompare = false, string wrapperName = null)
@@ -4577,4 +4693,17 @@ string.Format(@"<?xml version=""1.0"" encoding=""utf-8""?>
return actual;
}
+
+ private static void AssertSerializationFailure<T, ExceptionType>() where T : new() where ExceptionType : Exception
+ {
+ try
+ {
+ SerializeAndDeserialize(new T(), string.Empty, skipStringCompare: true);
+ Assert.True(false, $"Assert.True failed for {typeof(T)}. The above operation should have thrown, but it didn't.");
+ }
+ catch(Exception e)
+ {
+ Assert.True(e is ExceptionType, $"Assert.True failed for {typeof(T)}. Expected: {typeof(ExceptionType)}; Actual: {e.GetType()}");
+ }
+ }
}
diff --git a/src/System.Private.Xml/tests/XmlWriter/System.Xml.RW.XmlWriter.Tests.csproj b/src/System.Private.Xml/tests/XmlWriter/System.Xml.RW.XmlWriter.Tests.csproj
index 1abf82be51..eeb5cac4be 100644
--- a/src/System.Private.Xml/tests/XmlWriter/System.Xml.RW.XmlWriter.Tests.csproj
+++ b/src/System.Private.Xml/tests/XmlWriter/System.Xml.RW.XmlWriter.Tests.csproj
@@ -14,9 +14,6 @@
<Compile Include="WriteWithEncoding.cs" />
<Compile Include="WriteWithEncodingWithFallback.cs" />
<Compile Include="WriteWithInvalidSurrogate.cs" />
- <Compile Include="$(CommonTestPath)\System\AssertExtensions.cs">
- <Link>Common\System\AssertExtensions.cs</Link>
- </Compile>
</ItemGroup>
<Import Project="$([MSBuild]::GetDirectoryNameOfFileAbove($(MSBuildThisFileDirectory), dir.targets))\dir.targets" />
</Project> \ No newline at end of file
diff --git a/src/System.Reflection.DispatchProxy/pkg/System.Reflection.DispatchProxy.pkgproj b/src/System.Reflection.DispatchProxy/pkg/System.Reflection.DispatchProxy.pkgproj
index 5927e310e6..c7b214e621 100644
--- a/src/System.Reflection.DispatchProxy/pkg/System.Reflection.DispatchProxy.pkgproj
+++ b/src/System.Reflection.DispatchProxy/pkg/System.Reflection.DispatchProxy.pkgproj
@@ -14,9 +14,9 @@
</ItemGroup>
<ItemGroup>
<InboxOnTargetFramework Include="netcoreapp2.0" />
- <InboxOnTargetFramework Include="uap10.1" />
+ <InboxOnTargetFramework Include="$(UAPvNextTFM)" />
<File Include="$(PlaceholderFile)">
- <TargetPath>runtimes/aot/lib/uap10.1</TargetPath>
+ <TargetPath>runtimes/aot/lib/$(UAPvNextTFM)</TargetPath>
</File>
<InboxOnTargetFramework Include="MonoAndroid10" />
<InboxOnTargetFramework Include="MonoTouch10" />
diff --git a/src/System.Reflection.DispatchProxy/tests/System.Reflection.DispatchProxy.Tests.csproj b/src/System.Reflection.DispatchProxy/tests/System.Reflection.DispatchProxy.Tests.csproj
index 3044af44c1..d94ee6f8d1 100644
--- a/src/System.Reflection.DispatchProxy/tests/System.Reflection.DispatchProxy.Tests.csproj
+++ b/src/System.Reflection.DispatchProxy/tests/System.Reflection.DispatchProxy.Tests.csproj
@@ -13,9 +13,6 @@
<ItemGroup>
<Compile Include="DispatchProxyTests.cs" />
<Compile Include="TestTypes.cs" />
- <Compile Include="$(CommonTestPath)\System\AssertExtensions.cs">
- <Link>Common\System\AssertExtensions.cs</Link>
- </Compile>
</ItemGroup>
<Import Project="$([MSBuild]::GetDirectoryNameOfFileAbove($(MSBuildThisFileDirectory), dir.targets))\dir.targets" />
</Project> \ No newline at end of file
diff --git a/src/System.Reflection.Emit.ILGeneration/tests/System.Reflection.Emit.ILGeneration.Tests.csproj b/src/System.Reflection.Emit.ILGeneration/tests/System.Reflection.Emit.ILGeneration.Tests.csproj
index 9ffcbaa613..081ff1781a 100644
--- a/src/System.Reflection.Emit.ILGeneration/tests/System.Reflection.Emit.ILGeneration.Tests.csproj
+++ b/src/System.Reflection.Emit.ILGeneration/tests/System.Reflection.Emit.ILGeneration.Tests.csproj
@@ -35,9 +35,6 @@
<Compile Include="SignatureHelper\SignatureHelperToString.cs" />
<Compile Include="CustomAttributeBuilderTests.cs" />
<Compile Include="Utilities.cs" />
- <Compile Include="$(CommonTestPath)\System\AssertExtensions.cs">
- <Link>Common\System\AssertExtensions.cs</Link>
- </Compile>
</ItemGroup>
<Import Project="$([MSBuild]::GetDirectoryNameOfFileAbove($(MSBuildThisFileDirectory), dir.targets))\dir.targets" />
</Project> \ No newline at end of file
diff --git a/src/System.Reflection.Emit.Lightweight/tests/System.Reflection.Emit.Lightweight.Tests.csproj b/src/System.Reflection.Emit.Lightweight/tests/System.Reflection.Emit.Lightweight.Tests.csproj
index 17dcf0acb5..e197c108e9 100644
--- a/src/System.Reflection.Emit.Lightweight/tests/System.Reflection.Emit.Lightweight.Tests.csproj
+++ b/src/System.Reflection.Emit.Lightweight/tests/System.Reflection.Emit.Lightweight.Tests.csproj
@@ -15,9 +15,6 @@
<Compile Include="DynamicMethodInitLocals.cs" />
<Compile Include="DynamicMethodToString.cs" />
<Compile Include="Utilities.cs" />
- <Compile Include="$(CommonTestPath)\System\AssertExtensions.cs">
- <Link>Common\System\AssertExtensions.cs</Link>
- </Compile>
</ItemGroup>
<Import Project="$([MSBuild]::GetDirectoryNameOfFileAbove($(MSBuildThisFileDirectory), dir.targets))\dir.targets" />
</Project> \ No newline at end of file
diff --git a/src/System.Reflection.Emit/tests/System.Reflection.Emit.Tests.csproj b/src/System.Reflection.Emit/tests/System.Reflection.Emit.Tests.csproj
index 88fdc7cb7d..5ed63ea17d 100644
--- a/src/System.Reflection.Emit/tests/System.Reflection.Emit.Tests.csproj
+++ b/src/System.Reflection.Emit/tests/System.Reflection.Emit.Tests.csproj
@@ -8,9 +8,6 @@
<PropertyGroup Condition="'$(Configuration)|$(Platform)' == 'netcoreapp-Debug|AnyCPU'" />
<PropertyGroup Condition="'$(Configuration)|$(Platform)' == 'netcoreapp-Release|AnyCPU'" />
<ItemGroup>
- <Compile Include="$(CommonTestPath)\System\AssertExtensions.cs">
- <Link>Common\System\AssertExtensions.cs</Link>
- </Compile>
<Compile Include="$(CommonTestPath)\System\PlatformDetection.cs">
<Link>Common\tests\System\PlatformDetection.cs</Link>
</Compile>
diff --git a/src/System.Reflection.Extensions/tests/System.Reflection.Extensions.Tests.csproj b/src/System.Reflection.Extensions/tests/System.Reflection.Extensions.Tests.csproj
index 4c5d443cdc..e0d45e8fa0 100644
--- a/src/System.Reflection.Extensions/tests/System.Reflection.Extensions.Tests.csproj
+++ b/src/System.Reflection.Extensions/tests/System.Reflection.Extensions.Tests.csproj
@@ -20,9 +20,6 @@
<Compile Include="ReflectionTestExtensions.cs" />
<Compile Include="RuntimeReflectionExtensionTests.cs" />
<Compile Include="RuntimeReflectionExtensionTestsWithQuirks.cs" />
- <Compile Include="$(CommonTestPath)\System\AssertExtensions.cs">
- <Link>Common\System\AssertExtensions.cs</Link>
- </Compile>
</ItemGroup>
<Import Project="$([MSBuild]::GetDirectoryNameOfFileAbove($(MSBuildThisFileDirectory), dir.targets))\dir.targets" />
</Project> \ No newline at end of file
diff --git a/src/System.Reflection.Metadata/pkg/System.Reflection.Metadata.pkgproj b/src/System.Reflection.Metadata/pkg/System.Reflection.Metadata.pkgproj
index 1706b98631..ebaecb569b 100644
--- a/src/System.Reflection.Metadata/pkg/System.Reflection.Metadata.pkgproj
+++ b/src/System.Reflection.Metadata/pkg/System.Reflection.Metadata.pkgproj
@@ -14,7 +14,7 @@
<Version>1.1.37</Version>
</FilePackageDependency>
<InboxOnTargetFramework Include="netcoreapp2.0" />
- <InboxOnTargetFramework Include="uap10.1" />
+ <InboxOnTargetFramework Include="$(UAPvNextTFM)" />
</ItemGroup>
<Import Project="$([MSBuild]::GetDirectoryNameOfFileAbove($(MSBuildThisFileDirectory), dir.targets))\dir.targets" />
</Project> \ No newline at end of file
diff --git a/src/System.Reflection.Metadata/src/System/Reflection/Metadata/TypeSystem/ModuleDefinition.cs b/src/System.Reflection.Metadata/src/System/Reflection/Metadata/TypeSystem/ModuleDefinition.cs
index a3b374e8e9..67756922bd 100644
--- a/src/System.Reflection.Metadata/src/System/Reflection/Metadata/TypeSystem/ModuleDefinition.cs
+++ b/src/System.Reflection.Metadata/src/System/Reflection/Metadata/TypeSystem/ModuleDefinition.cs
@@ -55,5 +55,10 @@ namespace System.Reflection.Metadata
return _reader.ModuleTable.GetEncBaseId();
}
}
+
+ public CustomAttributeHandleCollection GetCustomAttributes()
+ {
+ return new CustomAttributeHandleCollection(_reader, EntityHandle.ModuleDefinition);
+ }
}
}
diff --git a/src/System.Reflection.Metadata/tests/System.Reflection.Metadata.Tests.csproj b/src/System.Reflection.Metadata/tests/System.Reflection.Metadata.Tests.csproj
index f7053832c8..f79be12e9d 100644
--- a/src/System.Reflection.Metadata/tests/System.Reflection.Metadata.Tests.csproj
+++ b/src/System.Reflection.Metadata/tests/System.Reflection.Metadata.Tests.csproj
@@ -90,9 +90,6 @@
<Compile Include="Utilities\ImmutableByteArrayInteropTest.cs" />
<Compile Include="Utilities\MemoryBlockTests.cs" />
<Compile Include="Utilities\OrderByTests.cs" />
- <Compile Include="$(CommonTestPath)\System\AssertExtensions.cs">
- <Link>Common\System\AssertExtensions.cs</Link>
- </Compile>
</ItemGroup>
<ItemGroup>
<None Include="Resources\Namespace\NamespaceForwardedCS.cs" />
diff --git a/src/System.Reflection.TypeExtensions/pkg/System.Reflection.TypeExtensions.pkgproj b/src/System.Reflection.TypeExtensions/pkg/System.Reflection.TypeExtensions.pkgproj
index 445004a897..cb624f57ca 100644
--- a/src/System.Reflection.TypeExtensions/pkg/System.Reflection.TypeExtensions.pkgproj
+++ b/src/System.Reflection.TypeExtensions/pkg/System.Reflection.TypeExtensions.pkgproj
@@ -17,9 +17,9 @@
</ItemGroup>
<ItemGroup>
<InboxOnTargetFramework Include="netcoreapp2.0" />
- <InboxOnTargetFramework Include="uap10.1" />
+ <InboxOnTargetFramework Include="$(UAPvNextTFM)" />
<File Include="$(PlaceholderFile)">
- <TargetPath>runtimes/aot/lib/uap10.1</TargetPath>
+ <TargetPath>runtimes/aot/lib/$(UAPvNextTFM)</TargetPath>
</File>
<InboxOnTargetFramework Include="MonoAndroid10" />
<InboxOnTargetFramework Include="MonoTouch10" />
diff --git a/src/System.Reflection.TypeExtensions/tests/System.Reflection.TypeExtensions.Tests.csproj b/src/System.Reflection.TypeExtensions/tests/System.Reflection.TypeExtensions.Tests.csproj
index c00dd6107e..a92a78b24d 100644
--- a/src/System.Reflection.TypeExtensions/tests/System.Reflection.TypeExtensions.Tests.csproj
+++ b/src/System.Reflection.TypeExtensions/tests/System.Reflection.TypeExtensions.Tests.csproj
@@ -26,9 +26,6 @@
<Compile Include="MethodBaseTests.cs" />
</ItemGroup>
<ItemGroup>
- <Compile Include="$(CommonTestPath)\System\AssertExtensions.cs">
- <Link>Common\System\AssertExtensions.cs</Link>
- </Compile>
<Compile Include="$(CommonTestPath)\System\PlatformDetection.cs">
<Link>Common\System\PlatformDetection.cs</Link>
</Compile>
diff --git a/src/System.Reflection/tests/System.Reflection.Tests.csproj b/src/System.Reflection/tests/System.Reflection.Tests.csproj
index 68769fed63..6da89a1074 100644
--- a/src/System.Reflection/tests/System.Reflection.Tests.csproj
+++ b/src/System.Reflection/tests/System.Reflection.Tests.csproj
@@ -26,9 +26,6 @@
<Compile Include="ExceptionTests.cs" />
</ItemGroup>
<ItemGroup>
- <Compile Include="$(CommonTestPath)\System\AssertExtensions.cs">
- <Link>Common\System\AssertExtensions.cs</Link>
- </Compile>
<Compile Include="$(CommonTestPath)\System\PlatformDetection.cs">
<Link>Common\System\PlatformDetection.cs</Link>
</Compile>
diff --git a/src/System.Resources.Reader/tests/System.Resources.Reader.Tests.csproj b/src/System.Resources.Reader/tests/System.Resources.Reader.Tests.csproj
index 6ee67a8a18..8711032818 100644
--- a/src/System.Resources.Reader/tests/System.Resources.Reader.Tests.csproj
+++ b/src/System.Resources.Reader/tests/System.Resources.Reader.Tests.csproj
@@ -10,9 +10,6 @@
<PropertyGroup Condition="'$(Configuration)|$(Platform)' == 'netstandard-Release|AnyCPU'" />
<ItemGroup>
<Compile Include="ResourceReaderUnitTest.cs" />
- <Compile Include="$(CommonTestPath)\System\AssertExtensions.cs">
- <Link>Common\System\AssertExtensions.cs</Link>
- </Compile>
</ItemGroup>
<Import Project="$([MSBuild]::GetDirectoryNameOfFileAbove($(MSBuildThisFileDirectory), dir.targets))\dir.targets" />
</Project> \ No newline at end of file
diff --git a/src/System.Resources.Writer/tests/System.Resources.Writer.Tests.csproj b/src/System.Resources.Writer/tests/System.Resources.Writer.Tests.csproj
index e21fc128cf..22dab774ab 100644
--- a/src/System.Resources.Writer/tests/System.Resources.Writer.Tests.csproj
+++ b/src/System.Resources.Writer/tests/System.Resources.Writer.Tests.csproj
@@ -10,9 +10,6 @@
<PropertyGroup Condition="'$(Configuration)|$(Platform)' == 'netstandard-Release|AnyCPU'" />
<ItemGroup>
<Compile Include="ResourceWriterUnitTest.cs" />
- <Compile Include="$(CommonTestPath)\System\AssertExtensions.cs">
- <Link>Common\System\AssertExtensions.cs</Link>
- </Compile>
</ItemGroup>
<Import Project="$([MSBuild]::GetDirectoryNameOfFileAbove($(MSBuildThisFileDirectory), dir.targets))\dir.targets" />
</Project> \ No newline at end of file
diff --git a/src/System.Runtime.Extensions/src/System/Environment.cs b/src/System.Runtime.Extensions/src/System/Environment.cs
index ca2f9bfa49..a725f2145a 100644
--- a/src/System.Runtime.Extensions/src/System/Environment.cs
+++ b/src/System.Runtime.Extensions/src/System/Environment.cs
@@ -204,6 +204,13 @@ namespace System
object result = processType.GetTypeInfo().GetDeclaredProperty("WorkingSet64")?.GetMethod?.Invoke(currentProcess, null);
if (result is long) return (long)result;
}
+ catch (TargetInvocationException tie)
+ {
+ if(tie.InnerException != null)
+ throw tie.InnerException;
+
+ throw tie;
+ }
finally { currentProcess.Dispose(); }
}
diff --git a/src/System.Runtime.Extensions/src/System/IO/BufferedStream.cs b/src/System.Runtime.Extensions/src/System/IO/BufferedStream.cs
index 32aa4db3e6..4c88123687 100644
--- a/src/System.Runtime.Extensions/src/System/IO/BufferedStream.cs
+++ b/src/System.Runtime.Extensions/src/System/IO/BufferedStream.cs
@@ -690,10 +690,11 @@ namespace System.IO
EnsureBufferAllocated();
_readLen = _stream.Read(_buffer, 0, _bufferSize);
+ _readPos = 0;
+
if (_readLen == 0)
return -1;
- _readPos = 0;
return _buffer[_readPos++];
}
diff --git a/src/System.Runtime.Extensions/src/System/IO/StreamReader.cs b/src/System.Runtime.Extensions/src/System/IO/StreamReader.cs
index 819d5e34a5..0493600c2a 100644
--- a/src/System.Runtime.Extensions/src/System/IO/StreamReader.cs
+++ b/src/System.Runtime.Extensions/src/System/IO/StreamReader.cs
@@ -541,8 +541,12 @@ namespace System.IO
if (changedEncoding)
{
_decoder = _encoding.GetDecoder();
- _maxCharsPerBuffer = _encoding.GetMaxCharCount(_byteBuffer.Length);
- _charBuffer = new char[_maxCharsPerBuffer];
+ int newMaxCharsPerBuffer = _encoding.GetMaxCharCount(_byteBuffer.Length);
+ if (newMaxCharsPerBuffer > _maxCharsPerBuffer)
+ {
+ _charBuffer = new char[newMaxCharsPerBuffer];
+ }
+ _maxCharsPerBuffer = newMaxCharsPerBuffer;
}
}
diff --git a/src/System.Runtime.Extensions/tests/System.Runtime.Extensions.Tests.csproj b/src/System.Runtime.Extensions/tests/System.Runtime.Extensions.Tests.csproj
index 08dc833192..24ff6e91aa 100644
--- a/src/System.Runtime.Extensions/tests/System.Runtime.Extensions.Tests.csproj
+++ b/src/System.Runtime.Extensions/tests/System.Runtime.Extensions.Tests.csproj
@@ -87,9 +87,6 @@
<Compile Include="$(CommonPath)\Interop\Unix\Interop.Libraries.cs">
<Link>Common\Interop\Unix\Interop.Libraries.cs</Link>
</Compile>
- <Compile Include="$(CommonTestPath)\System\AssertExtensions.cs">
- <Link>Common\System\AssertExtensions.cs</Link>
- </Compile>
<Compile Include="$(CommonTestPath)\System\IO\PathFeatures.cs">
<Link>Common\System\IO\PathFeatures.cs</Link>
</Compile>
diff --git a/src/System.Runtime.Extensions/tests/System/AppDomainTests.cs b/src/System.Runtime.Extensions/tests/System/AppDomainTests.cs
index 1c95c222d2..7f284cf633 100644
--- a/src/System.Runtime.Extensions/tests/System/AppDomainTests.cs
+++ b/src/System.Runtime.Extensions/tests/System/AppDomainTests.cs
@@ -292,7 +292,6 @@ namespace System.Tests
}
[Fact]
- [ActiveIssue(21680, TargetFrameworkMonikers.UapAot)]
public void SetData_SameKeyMultipleTimes_ReplacesOldValue()
{
RemoteInvoke(() => {
diff --git a/src/System.Runtime.Extensions/tests/System/EnvironmentTests.cs b/src/System.Runtime.Extensions/tests/System/EnvironmentTests.cs
index 8a8be81295..4a7e8a3368 100644
--- a/src/System.Runtime.Extensions/tests/System/EnvironmentTests.cs
+++ b/src/System.Runtime.Extensions/tests/System/EnvironmentTests.cs
@@ -7,6 +7,7 @@ using System.Collections.Generic;
using System.Diagnostics;
using System.IO;
using System.Linq;
+using System.Reflection;
using System.Runtime.InteropServices;
using System.Security;
using System.Threading;
@@ -175,10 +176,18 @@ namespace System.Tests
}
[Fact]
+ [SkipOnTargetFramework(TargetFrameworkMonikers.Uap)] // Throws InvalidOperationException in Uap as NtQuerySystemInformation Pinvoke is not available
public void WorkingSet_Valid()
{
Assert.True(Environment.WorkingSet > 0, "Expected positive WorkingSet value");
}
+
+ [Fact]
+ [SkipOnTargetFramework(~TargetFrameworkMonikers.Uap)]
+ public void WorkingSet_Valid_Uap()
+ {
+ Assert.Throws<PlatformNotSupportedException>(() => Environment.WorkingSet);
+ }
[Trait(XunitConstants.Category, XunitConstants.IgnoreForCI)] // fail fast crashes the process
[OuterLoop]
diff --git a/src/System.Runtime.InteropServices.RuntimeInformation/tests/System.Runtime.InteropServices.RuntimeInformation.Tests.csproj b/src/System.Runtime.InteropServices.RuntimeInformation/tests/System.Runtime.InteropServices.RuntimeInformation.Tests.csproj
index 93c116a0ce..760bafe99d 100644
--- a/src/System.Runtime.InteropServices.RuntimeInformation/tests/System.Runtime.InteropServices.RuntimeInformation.Tests.csproj
+++ b/src/System.Runtime.InteropServices.RuntimeInformation/tests/System.Runtime.InteropServices.RuntimeInformation.Tests.csproj
@@ -14,9 +14,6 @@
<Compile Include="CheckArchitectureTests.cs" />
<Compile Include="CheckPlatformTests.cs" />
<Compile Include="DescriptionNameTests.cs" />
- <Compile Include="$(CommonTestPath)\System\AssertExtensions.cs">
- <Link>Common\System\AssertExtensions.cs</Link>
- </Compile>
<Compile Include="$(CommonTestPath)\System\PlatformDetection.cs">
<Link>Common\System\PlatformDetection.cs</Link>
</Compile>
diff --git a/src/System.Runtime.InteropServices.WindowsRuntime/tests/System.Runtime.InteropServices.WindowsRuntime.Tests.csproj b/src/System.Runtime.InteropServices.WindowsRuntime/tests/System.Runtime.InteropServices.WindowsRuntime.Tests.csproj
index 1d4480fb5d..91c5cc86d7 100644
--- a/src/System.Runtime.InteropServices.WindowsRuntime/tests/System.Runtime.InteropServices.WindowsRuntime.Tests.csproj
+++ b/src/System.Runtime.InteropServices.WindowsRuntime/tests/System.Runtime.InteropServices.WindowsRuntime.Tests.csproj
@@ -21,9 +21,6 @@
<Compile Include="System\Runtime\InteropServices\WindowsRuntime\InterfaceImplementedInVersionAttributeTests.cs" />
<Compile Include="System\Runtime\InteropServices\WindowsRuntime\ReturnValueNameAttributeTests.cs" />
<Compile Include="System\Runtime\InteropServices\WindowsRuntime\WindowsRuntimeMarshalTests.cs" />
- <Compile Include="$(CommonTestPath)\System\AssertExtensions.cs">
- <Link>Common\System\AssertExtensions.cs</Link>
- </Compile>
<Compile Include="$(CommonTestPath)\System\PlatformDetection.cs">
<Link>Common\System\PlatformDetection.cs</Link>
</Compile>
diff --git a/src/System.Runtime.InteropServices/tests/System.Runtime.InteropServices.Tests.csproj b/src/System.Runtime.InteropServices/tests/System.Runtime.InteropServices.Tests.csproj
index 1f9b332dfa..003e959ba9 100644
--- a/src/System.Runtime.InteropServices/tests/System.Runtime.InteropServices.Tests.csproj
+++ b/src/System.Runtime.InteropServices/tests/System.Runtime.InteropServices.Tests.csproj
@@ -61,9 +61,6 @@
<Compile Include="System\Runtime\InteropServices\UnknownWrapperTests.cs" />
<Compile Include="System\Runtime\InteropServices\UnmanagedFunctionPointerAttributeTests.cs" />
<Compile Include="System\Runtime\InteropServices\VariantWrapperTests.cs" />
- <Compile Include="$(CommonTestPath)\System\AssertExtensions.cs">
- <Link>Common\System\AssertExtensions.cs</Link>
- </Compile>
<Compile Include="$(CommonTestPath)\System\PlatformDetection.cs">
<Link>Common\System\PlatformDetection.cs</Link>
</Compile>
diff --git a/src/System.Runtime.Loader/tests/DefaultContext/DefaultLoadContextTest.cs b/src/System.Runtime.Loader/tests/DefaultContext/DefaultLoadContextTest.cs
index 5f5bd1293d..7726d9bd51 100644
--- a/src/System.Runtime.Loader/tests/DefaultContext/DefaultLoadContextTest.cs
+++ b/src/System.Runtime.Loader/tests/DefaultContext/DefaultLoadContextTest.cs
@@ -32,100 +32,63 @@ namespace System.Runtime.Loader.Tests
public class OverrideDefaultLoadContext : AssemblyLoadContext
{
- private bool m_fLoadedFromContext = false;
+ public bool LoadedFromContext { get; set; } = false;
protected override Assembly Load(AssemblyName assemblyName)
{
// Override the assembly that was loaded in DefaultContext.
string assemblyPath = Path.Combine(Path.GetDirectoryName(typeof(string).Assembly.Location), assemblyName.Name + ".dll");
Assembly assembly = LoadFromAssemblyPath(assemblyPath);
- m_fLoadedFromContext = true;
+ LoadedFromContext = true;
return assembly;
}
-
- public bool LoadedFromContext
- {
- get
- {
- return m_fLoadedFromContext;
- }
- set
- {
- m_fLoadedFromContext = value;
- }
- }
}
[SkipOnTargetFramework(TargetFrameworkMonikers.UapAot, "AssemblyLoadContext not supported on .Net Native")]
public class DefaultLoadContextTests
{
- private static string s_loadFromPath = null;
+ private const string TestAssemblyName = "System.Runtime.Loader.Noop.Assembly";
+ private string _assemblyPath;
+ private string _defaultLoadDirectory;
// Since the first non-Null returning callback should stop Resolving event processing,
// this counter is used to assert the same.
- private static int s_NumNonNullResolutions = 0;
+ private int _numNonNullResolutions = 0;
- private static Assembly ResolveAssembly(AssemblyLoadContext sender, AssemblyName assembly)
+ public DefaultLoadContextTests()
{
- string assemblyFilename = assembly.Name + ".dll";
- s_NumNonNullResolutions++;
+ _defaultLoadDirectory = GetDefaultAssemblyLoadDirectory();
+ _assemblyPath = Path.Combine(_defaultLoadDirectory, "System.Runtime.Loader.Noop.Assembly_test.dll");
+ }
- return sender.LoadFromAssemblyPath(Path.Combine(s_loadFromPath, assemblyFilename));
+ private static string GetDefaultAssemblyLoadDirectory()
+ {
+ return Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location);
}
- private static Assembly ResolveAssemblyAgain(AssemblyLoadContext sender, AssemblyName assembly)
+ private Assembly ResolveAssembly(AssemblyLoadContext sender, AssemblyName assembly)
{
- string assemblyFilename = assembly.Name + ".dll";
- s_NumNonNullResolutions++;
+ string resolvedAssemblyPath = Path.Combine(_defaultLoadDirectory, assembly.Name + "_test.dll");
+ _numNonNullResolutions++;
- return sender.LoadFromAssemblyPath(Path.Combine(s_loadFromPath, assemblyFilename));
+ return sender.LoadFromAssemblyPath(resolvedAssemblyPath);
}
- private static Assembly ResolveNullAssembly(AssemblyLoadContext sender, AssemblyName assembly)
+ private Assembly ResolveAssemblyAgain(AssemblyLoadContext sender, AssemblyName assembly)
{
- return null;
+ return ResolveAssembly(sender, assembly);
}
- private static void Init()
+ private Assembly ResolveNullAssembly(AssemblyLoadContext sender, AssemblyName assembly)
{
- // Delete the assembly from the temp location if it exists.
- var assemblyFilename = "System.Runtime.Loader.Noop.Assembly.dll";
- s_NumNonNullResolutions = 0;
-
- // Form the dynamic path that would not collide if another instance of this test is running.
- s_loadFromPath = Path.Combine(Path.GetTempPath(), Guid.NewGuid().ToString());
-
- // Create the folder
- Directory.CreateDirectory(s_loadFromPath);
-
- var targetPath = Path.Combine(s_loadFromPath, assemblyFilename);
-
- // Rename the file local to the test folder.
- var sourcePath = Path.Combine(Directory.GetCurrentDirectory(),assemblyFilename);
- var targetRenamedPath = Path.Combine(Directory.GetCurrentDirectory(), "System.Runtime.Loader.Noop.Assembly_test.dll");
- if (File.Exists(sourcePath))
- {
- if (File.Exists(targetRenamedPath))
- {
- File.Delete(targetRenamedPath);
- }
-
- File.Move(sourcePath, targetRenamedPath);
- }
-
- // Finally, copy the file to the temp location from where we expect to load it
- File.Copy(targetRenamedPath, targetPath);
+ return null;
}
[Fact]
- [ActiveIssue("https://github.com/dotnet/corefx/issues/20303", TargetFrameworkMonikers.Uap)]
- public static void LoadInDefaultContext()
+ public void LoadInDefaultContext()
{
- Init();
-
// This will attempt to load an assembly, by path, in the Default Load context via the Resolving event
- var assemblyNameStr = "System.Runtime.Loader.Noop.Assembly";
- var assemblyName = new AssemblyName(assemblyNameStr);
+ var assemblyName = new AssemblyName(TestAssemblyName);
// By default, the assembly should not be found in DefaultContext at all
Assert.Throws(typeof(FileNotFoundException), () => Assembly.Load(assemblyName));
@@ -141,15 +104,15 @@ namespace System.Runtime.Loader.Tests
Assert.NotNull(slcLoadedAssembly);
// And make sure the simple name matches
- Assert.Equal(assemblyNameStr, slcLoadedAssembly.GetName().Name);
+ Assert.Equal(TestAssemblyName, slcLoadedAssembly.GetName().Name);
// We should have only invoked non-Null returning handler once
- Assert.Equal(1, s_NumNonNullResolutions);
+ Assert.Equal(1, _numNonNullResolutions);
slc.Resolving -= ResolveAssembly;
// Reset the non-Null resolution counter
- s_NumNonNullResolutions = 0;
+ _numNonNullResolutions = 0;
// Now, wireup the Resolving event of default context to locate the assembly via multiple handlers
AssemblyLoadContext.Default.Resolving += ResolveNullAssembly;
@@ -163,20 +126,20 @@ namespace System.Runtime.Loader.Tests
Assert.NotNull(assemblyExpectedFromLoad);
// We should have only invoked non-Null returning handler once
- Assert.Equal(1, s_NumNonNullResolutions);
+ Assert.Equal(1, _numNonNullResolutions);
// And make sure the simple name matches
- Assert.Equal(assemblyNameStr, assemblyExpectedFromLoad.GetName().Name);
+ Assert.Equal(TestAssemblyName, assemblyExpectedFromLoad.GetName().Name);
// The assembly loaded in DefaultContext should have a different reference from the one in secondary load context
Assert.NotEqual(slcLoadedAssembly, assemblyExpectedFromLoad);
// Reset the non-Null resolution counter
- s_NumNonNullResolutions = 0;
+ _numNonNullResolutions = 0;
// Since the assembly is already loaded in TPA Binder, we will get that back without invoking any Resolving event handlers
var assemblyExpected = AssemblyLoadContext.Default.LoadFromAssemblyName(assemblyName);
- Assert.Equal(0, s_NumNonNullResolutions);
+ Assert.Equal(0, _numNonNullResolutions);
// We should have successfully loaded the assembly in default context.
Assert.NotNull(assemblyExpected);
@@ -185,7 +148,7 @@ namespace System.Runtime.Loader.Tests
Assert.Equal(assemblyExpected, assemblyExpectedFromLoad);
// And make sure the simple name matches
- Assert.Equal(assemblyExpected.GetName().Name, assemblyNameStr);
+ Assert.Equal(assemblyExpected.GetName().Name, TestAssemblyName);
// Unwire the Resolving event.
AssemblyLoadContext.Default.Resolving -= ResolveAssemblyAgain;
@@ -194,7 +157,7 @@ namespace System.Runtime.Loader.Tests
// Unwire the Resolving event and attempt to load the assembly again. This time
// it should be found in the Default Load Context.
- var assemblyLoaded = Assembly.Load(new AssemblyName(assemblyNameStr));
+ var assemblyLoaded = Assembly.Load(new AssemblyName(TestAssemblyName));
// We should have successfully found the assembly in default context.
Assert.NotNull(assemblyLoaded);
@@ -217,14 +180,13 @@ namespace System.Runtime.Loader.Tests
() => AssemblyLoadContext.Default.LoadFromAssemblyName(new AssemblyName("System.Runtime.Loader.NonExistent.Assembly")));
}
- public static void DefaultContextFallback()
+ public void DefaultContextFallback()
{
- var assemblyNameStr = "System.Runtime.Loader.Noop.Assembly.dll";
var lcDefault = AssemblyLoadContext.Default;
// Load the assembly in custom load context
FallbackLoadContext flc = new FallbackLoadContext();
- var asmTargetAsm = flc.LoadFromAssemblyPath(Path.Combine(s_loadFromPath, assemblyNameStr));
+ var asmTargetAsm = flc.LoadFromAssemblyPath(_assemblyPath);
var loadedContext = AssemblyLoadContext.GetLoadContext(asmTargetAsm);
// LoadContext of the assembly should be the custom context and not DefaultContext
@@ -249,7 +211,7 @@ namespace System.Runtime.Loader.Tests
// Now, do the same from an assembly that we explicitly had loaded in DefaultContext
// in the caller of this method. We should get it from FallbackLoadContext since we
// explicitly loaded it there as well.
- assemblyName = "System.Runtime.Loader.Noop.Assembly";
+ assemblyName = TestAssemblyName;
Assembly asmLoaded2 = (Assembly)method.Invoke(null, new object[] {assemblyName});
loadedContext = AssemblyLoadContext.GetLoadContext(asmLoaded2);
@@ -273,14 +235,13 @@ namespace System.Runtime.Loader.Tests
Assert.Equal(typeof(FileNotFoundException), ex.GetType());
}
- public static void DefaultContextOverrideTPA()
+ public void DefaultContextOverrideTPA()
{
- var assemblyNameStr = "System.Runtime.Loader.Noop.Assembly.dll";
var lcDefault = AssemblyLoadContext.Default;
// Load the assembly in custom load context
OverrideDefaultLoadContext olc = new OverrideDefaultLoadContext();
- var asmTargetAsm = olc.LoadFromAssemblyPath(Path.Combine(s_loadFromPath, assemblyNameStr));
+ var asmTargetAsm = olc.LoadFromAssemblyPath(_assemblyPath);
var loadedContext = AssemblyLoadContext.GetLoadContext(asmTargetAsm);
// LoadContext of the assembly should be the custom context and not DefaultContext
@@ -307,7 +268,7 @@ namespace System.Runtime.Loader.Tests
// Now, do the same for an assembly that we explicitly had loaded in DefaultContext
// in the caller of this method and ALSO loaded in the current load context. We should get it from our LoadContext,
// without invoking the Load override, since it is already loaded.
- assemblyName = "System.Runtime.Loader.Noop.Assembly";
+ assemblyName = TestAssemblyName;
olc.LoadedFromContext = false;
Assembly asmLoaded2 = (Assembly)method.Invoke(null, new object[] {assemblyName});
loadedContext = AssemblyLoadContext.GetLoadContext(asmLoaded2);
diff --git a/src/System.Runtime.Loader/tests/DefaultContext/System.Runtime.Loader.DefaultContext.Tests.csproj b/src/System.Runtime.Loader/tests/DefaultContext/System.Runtime.Loader.DefaultContext.Tests.csproj
index 06370d4314..6863d1c5d3 100644
--- a/src/System.Runtime.Loader/tests/DefaultContext/System.Runtime.Loader.DefaultContext.Tests.csproj
+++ b/src/System.Runtime.Loader/tests/DefaultContext/System.Runtime.Loader.DefaultContext.Tests.csproj
@@ -19,5 +19,8 @@
<CopyToOutputDirectory>PreserveNewest</CopyToOutputDirectory>
</ProjectReference>
</ItemGroup>
+ <Target Name="RenameTestAssembly" AfterTargets="AfterBuild">
+ <Move SourceFiles="$(OutputPath)\System.Runtime.Loader.Noop.Assembly.dll" DestinationFiles="$(OutputPath)\System.Runtime.Loader.Noop.Assembly_test.dll" />
+ </Target>
<Import Project="$([MSBuild]::GetDirectoryNameOfFileAbove($(MSBuildThisFileDirectory), dir.targets))\dir.targets" />
</Project> \ No newline at end of file
diff --git a/src/System.Runtime.Numerics/tests/System.Runtime.Numerics.Tests.csproj b/src/System.Runtime.Numerics/tests/System.Runtime.Numerics.Tests.csproj
index bc8d22dcc4..3e90f7e24e 100644
--- a/src/System.Runtime.Numerics/tests/System.Runtime.Numerics.Tests.csproj
+++ b/src/System.Runtime.Numerics/tests/System.Runtime.Numerics.Tests.csproj
@@ -53,9 +53,6 @@
<Compile Include="BigInteger\stackcalculator.cs" />
<Compile Include="BigInteger\ToByteArray.cs" />
<Compile Include="ComplexTests.cs" />
- <Compile Include="$(CommonTestPath)\System\AssertExtensions.cs">
- <Link>Common\System\AssertExtensions.cs</Link>
- </Compile>
<Compile Include="$(CommonTestPath)\System\PlatformDetection.cs">
<Link>Common\System\PlatformDetection.cs</Link>
</Compile>
diff --git a/src/System.Runtime.Serialization.Formatters/tests/BinaryFormatterTestData.cs b/src/System.Runtime.Serialization.Formatters/tests/BinaryFormatterTestData.cs
index a3c6c1af3c..b34fa7cdc0 100644
--- a/src/System.Runtime.Serialization.Formatters/tests/BinaryFormatterTestData.cs
+++ b/src/System.Runtime.Serialization.Formatters/tests/BinaryFormatterTestData.cs
@@ -103,7 +103,7 @@ namespace System.Runtime.Serialization.Formatters.Tests
yield return new object[] { UIntPtr.Zero, new string[] { "AAEAAAD/////AQAAAAAAAAAEAQAAAA5TeXN0ZW0uVUludFB0cgEAAAAFdmFsdWUAEAAAAAAAAAAACw==", "AAEAAAD/////AQAAAAAAAAAEAQAAAA5TeXN0ZW0uVUludFB0cgEAAAAFdmFsdWUAEAAAAAAAAAAACw==" } };
yield return new object[] { new DateTime(1990, 11, 23), new string[] { "AAEAAAD/////AQAAAAAAAAAEAQAAAA9TeXN0ZW0uRGF0ZVRpbWUCAAAABXRpY2tzCGRhdGVEYXRhAAAJEADA9z1t7LYIAMD3PW3stggL", "AAEAAAD/////AQAAAAAAAAAEAQAAAA9TeXN0ZW0uRGF0ZVRpbWUCAAAABXRpY2tzCGRhdGVEYXRhAAAJEADA9z1t7LYIAMD3PW3stggL" } };
yield return new object[] { new DateTimeOffset(1990, 11, 23, 03, 30, 00, 00, TimeSpan.FromMinutes(30)), new string[] { "AAEAAAD/////AQAAAAAAAAAEAQAAABVTeXN0ZW0uRGF0ZVRpbWVPZmZzZXQCAAAACERhdGVUaW1lDU9mZnNldE1pbnV0ZXMAAA0HAPhEY4bstggeAAs=", "AAEAAAD/////AQAAAAAAAAAEAQAAABVTeXN0ZW0uRGF0ZVRpbWVPZmZzZXQCAAAACERhdGVUaW1lDU9mZnNldE1pbnV0ZXMAAA0HAPhEY4bstggeAAs=" } };
- yield return new object[] { TimeZoneInfo.Utc, new string[] { "AAEAAAD/////AQAAAAAAAAAMAgAAAE5TeXN0ZW0uQ29yZSwgVmVyc2lvbj0zLjUuMC4wLCBDdWx0dXJlPU5ldXRyYWwsIFB1YmxpY0tleVRva2VuPWI3N2E1YzU2MTkzNGUwODkFAQAAABNTeXN0ZW0uVGltZVpvbmVJbmZvBwAAAAJJZAtEaXNwbGF5TmFtZQxTdGFuZGFyZE5hbWUMRGF5bGlnaHROYW1lDUJhc2VVdGNPZmZzZXQPQWRqdXN0bWVudFJ1bGVzGlN1cHBvcnRzRGF5bGlnaHRTYXZpbmdUaW1lAQEBAQACAAwBAgAAAAYDAAAAA1VUQwkDAAAACQMAAAAJAwAAAAAAAAAAAAAACgAL", "AAEAAAD/////AQAAAAAAAAAMAgAAAE5TeXN0ZW0uQ29yZSwgVmVyc2lvbj0zLjUuMC4wLCBDdWx0dXJlPU5ldXRyYWwsIFB1YmxpY0tleVRva2VuPWI3N2E1YzU2MTkzNGUwODkFAQAAABNTeXN0ZW0uVGltZVpvbmVJbmZvBwAAAAJJZAtEaXNwbGF5TmFtZQxTdGFuZGFyZE5hbWUMRGF5bGlnaHROYW1lDUJhc2VVdGNPZmZzZXQPQWRqdXN0bWVudFJ1bGVzGlN1cHBvcnRzRGF5bGlnaHRTYXZpbmdUaW1lAQEBAQACAAwBAgAAAAYDAAAAA1VUQwkDAAAACQMAAAAJAwAAAAAAAAAAAAAACgAL" } };
+ yield return new object[] { TimeZoneInfo.Utc, new string[] { "AAEAAAD/////AQAAAAAAAAAMAgAAAE5TeXN0ZW0uQ29yZSwgVmVyc2lvbj0zLjUuMC4wLCBDdWx0dXJlPW5ldXRyYWwsIFB1YmxpY0tleVRva2VuPWI3N2E1YzU2MTkzNGUwODkFAQAAABNTeXN0ZW0uVGltZVpvbmVJbmZvBwAAAAJJZAtEaXNwbGF5TmFtZQxTdGFuZGFyZE5hbWUMRGF5bGlnaHROYW1lDUJhc2VVdGNPZmZzZXQPQWRqdXN0bWVudFJ1bGVzGlN1cHBvcnRzRGF5bGlnaHRTYXZpbmdUaW1lAQEBAQACAAwBAgAAAAYDAAAAA1VUQwkDAAAACQMAAAAJAwAAAAAAAAAAAAAACgAL", "AAEAAAD/////AQAAAAAAAAAMAgAAAE5TeXN0ZW0uQ29yZSwgVmVyc2lvbj0zLjUuMC4wLCBDdWx0dXJlPU5ldXRyYWwsIFB1YmxpY0tleVRva2VuPWI3N2E1YzU2MTkzNGUwODkFAQAAABNTeXN0ZW0uVGltZVpvbmVJbmZvBwAAAAJJZAtEaXNwbGF5TmFtZQxTdGFuZGFyZE5hbWUMRGF5bGlnaHROYW1lDUJhc2VVdGNPZmZzZXQPQWRqdXN0bWVudFJ1bGVzGlN1cHBvcnRzRGF5bGlnaHRTYXZpbmdUaW1lAQEBAQACAAwBAgAAAAYDAAAAA1VUQwkDAAAACQMAAAAJAwAAAAAAAAAAAAAACgAL" } };
yield return new object[] { TimeZoneInfo.TransitionTime.CreateFixedDateRule(new DateTime(1, 1, 1, 2, 0, 0), 3, 15), new string[] { "AAEAAAD/////AQAAAAAAAAAEAQAAACJTeXN0ZW0uVGltZVpvbmVJbmZvK1RyYW5zaXRpb25UaW1lBgAAAAlUaW1lT2ZEYXkFTW9udGgEV2VlawNEYXkJRGF5T2ZXZWVrD0lzRml4ZWREYXRlUnVsZQAAAAADAA0CAgIQU3lzdGVtLkRheU9mV2VlawEA0IjDEAAAAAMBDwT+////EFN5c3RlbS5EYXlPZldlZWsBAAAAB3ZhbHVlX18ACAAAAAABCw==", "AAEAAAD/////AQAAAAAAAAAMAgAAAE5TeXN0ZW0uQ29yZSwgVmVyc2lvbj0zLjUuMC4wLCBDdWx0dXJlPU5ldXRyYWwsIFB1YmxpY0tleVRva2VuPWI3N2E1YzU2MTkzNGUwODkFAQAAACJTeXN0ZW0uVGltZVpvbmVJbmZvK1RyYW5zaXRpb25UaW1lBgAAAAlUaW1lT2ZEYXkFTW9udGgEV2VlawNEYXkJRGF5T2ZXZWVrD0lzRml4ZWREYXRlUnVsZQAAAAADAA0CAgIQU3lzdGVtLkRheU9mV2VlawECAAAAANCIwxAAAAADAQ8E/f///xBTeXN0ZW0uRGF5T2ZXZWVrAQAAAAd2YWx1ZV9fAAgAAAAAAQs=" } };
var adjustmentRule = TimeZoneInfo.AdjustmentRule.CreateAdjustmentRule(
@@ -362,13 +362,13 @@ namespace System.Runtime.Serialization.Formatters.Tests
yield return new object[] { new HybridDictionary(), new string[] { "AAEAAAD/////AQAAAAAAAAAMAgAAAElTeXN0ZW0sIFZlcnNpb249NC4wLjAuMCwgQ3VsdHVyZT1uZXV0cmFsLCBQdWJsaWNLZXlUb2tlbj1iNzdhNWM1NjE5MzRlMDg5BQEAAAAvU3lzdGVtLkNvbGxlY3Rpb25zLlNwZWNpYWxpemVkLkh5YnJpZERpY3Rpb25hcnkDAAAABGxpc3QJaGFzaHRhYmxlD2Nhc2VJbnNlbnNpdGl2ZQQDAC1TeXN0ZW0uQ29sbGVjdGlvbnMuU3BlY2lhbGl6ZWQuTGlzdERpY3Rpb25hcnkCAAAAHFN5c3RlbS5Db2xsZWN0aW9ucy5IYXNodGFibGUBAgAAAAoKAAs=", "AAEAAAD/////AQAAAAAAAAAMAgAAAElTeXN0ZW0sIFZlcnNpb249NC4wLjAuMCwgQ3VsdHVyZT1uZXV0cmFsLCBQdWJsaWNLZXlUb2tlbj1iNzdhNWM1NjE5MzRlMDg5BQEAAAAvU3lzdGVtLkNvbGxlY3Rpb25zLlNwZWNpYWxpemVkLkh5YnJpZERpY3Rpb25hcnkDAAAABGxpc3QJaGFzaHRhYmxlD2Nhc2VJbnNlbnNpdGl2ZQQDAC1TeXN0ZW0uQ29sbGVjdGlvbnMuU3BlY2lhbGl6ZWQuTGlzdERpY3Rpb25hcnkCAAAAHFN5c3RlbS5Db2xsZWN0aW9ucy5IYXNodGFibGUBAgAAAAoKAAs=" } };
yield return new object[] { new HybridDictionary(127, true), new string[] { "AAEAAAD/////AQAAAAAAAAAMAgAAAElTeXN0ZW0sIFZlcnNpb249NC4wLjAuMCwgQ3VsdHVyZT1uZXV0cmFsLCBQdWJsaWNLZXlUb2tlbj1iNzdhNWM1NjE5MzRlMDg5BQEAAAAvU3lzdGVtLkNvbGxlY3Rpb25zLlNwZWNpYWxpemVkLkh5YnJpZERpY3Rpb25hcnkDAAAABGxpc3QJaGFzaHRhYmxlD2Nhc2VJbnNlbnNpdGl2ZQQDAC1TeXN0ZW0uQ29sbGVjdGlvbnMuU3BlY2lhbGl6ZWQuTGlzdERpY3Rpb25hcnkCAAAAHFN5c3RlbS5Db2xsZWN0aW9ucy5IYXNodGFibGUBAgAAAAoJAwAAAAEEAwAAABxTeXN0ZW0uQ29sbGVjdGlvbnMuSGFzaHRhYmxlBgAAAApMb2FkRmFjdG9yB1ZlcnNpb24LS2V5Q29tcGFyZXIISGFzaFNpemUES2V5cwZWYWx1ZXMAAAMABQULCBZTeXN0ZW0uT3JkaW5hbENvbXBhcmVyCOxROD8AAAAACQQAAADFAAAACQUAAAAJBgAAAAQEAAAAFlN5c3RlbS5PcmRpbmFsQ29tcGFyZXIBAAAAC19pZ25vcmVDYXNlAAEBEAUAAAAAAAAAEAYAAAAAAAAACw==", "AAEAAAD/////AQAAAAAAAAAMAgAAAElTeXN0ZW0sIFZlcnNpb249NC4wLjAuMCwgQ3VsdHVyZT1uZXV0cmFsLCBQdWJsaWNLZXlUb2tlbj1iNzdhNWM1NjE5MzRlMDg5BQEAAAAvU3lzdGVtLkNvbGxlY3Rpb25zLlNwZWNpYWxpemVkLkh5YnJpZERpY3Rpb25hcnkDAAAABGxpc3QJaGFzaHRhYmxlD2Nhc2VJbnNlbnNpdGl2ZQQDAC1TeXN0ZW0uQ29sbGVjdGlvbnMuU3BlY2lhbGl6ZWQuTGlzdERpY3Rpb25hcnkCAAAAHFN5c3RlbS5Db2xsZWN0aW9ucy5IYXNodGFibGUBAgAAAAoJAwAAAAEEAwAAABxTeXN0ZW0uQ29sbGVjdGlvbnMuSGFzaHRhYmxlBgAAAApMb2FkRmFjdG9yB1ZlcnNpb24LS2V5Q29tcGFyZXIISGFzaFNpemUES2V5cwZWYWx1ZXMAAAMABQULCBZTeXN0ZW0uT3JkaW5hbENvbXBhcmVyCOxROD8AAAAACQQAAADFAAAACQUAAAAJBgAAAAQEAAAAFlN5c3RlbS5PcmRpbmFsQ29tcGFyZXIBAAAAC19pZ25vcmVDYXNlAAEBEAUAAAAAAAAAEAYAAAAAAAAACw==" } };
- yield return new object[] { new ObservableCollection<int>(), new string[] { "AAEAAAD/////AQAAAAAAAAAMAgAAAE5XaW5kb3dzQmFzZSwgVmVyc2lvbj0zLjAuMC4wLCBDdWx0dXJlPU5ldXRyYWwsIFB1YmxpY0tleVRva2VuPTMxYmYzODU2YWQzNjRlMzUFAQAAAJIBU3lzdGVtLkNvbGxlY3Rpb25zLk9iamVjdE1vZGVsLk9ic2VydmFibGVDb2xsZWN0aW9uYDFbW1N5c3RlbS5JbnQzMiwgbXNjb3JsaWIsIFZlcnNpb249NC4wLjAuMCwgQ3VsdHVyZT1uZXV0cmFsLCBQdWJsaWNLZXlUb2tlbj1iNzdhNWM1NjE5MzRlMDg5XV0CAAAACF9tb25pdG9yEkNvbGxlY3Rpb25gMStpdGVtcwQDoAFTeXN0ZW0uQ29sbGVjdGlvbnMuT2JqZWN0TW9kZWwuT2JzZXJ2YWJsZUNvbGxlY3Rpb25gMStTaW1wbGVNb25pdG9yW1tTeXN0ZW0uSW50MzIsIG1zY29ybGliLCBWZXJzaW9uPTQuMC4wLjAsIEN1bHR1cmU9bmV1dHJhbCwgUHVibGljS2V5VG9rZW49Yjc3YTVjNTYxOTM0ZTA4OV1dAgAAAH5TeXN0ZW0uQ29sbGVjdGlvbnMuR2VuZXJpYy5MaXN0YDFbW1N5c3RlbS5JbnQzMiwgbXNjb3JsaWIsIFZlcnNpb249NC4wLjAuMCwgQ3VsdHVyZT1uZXV0cmFsLCBQdWJsaWNLZXlUb2tlbj1iNzdhNWM1NjE5MzRlMDg5XV0CAAAACQMAAAAJBAAAAAUDAAAAoAFTeXN0ZW0uQ29sbGVjdGlvbnMuT2JqZWN0TW9kZWwuT2JzZXJ2YWJsZUNvbGxlY3Rpb25gMStTaW1wbGVNb25pdG9yW1tTeXN0ZW0uSW50MzIsIG1zY29ybGliLCBWZXJzaW9uPTQuMC4wLjAsIEN1bHR1cmU9bmV1dHJhbCwgUHVibGljS2V5VG9rZW49Yjc3YTVjNTYxOTM0ZTA4OV1dAQAAAApfYnVzeUNvdW50AAgCAAAAAAAAAAQEAAAAflN5c3RlbS5Db2xsZWN0aW9ucy5HZW5lcmljLkxpc3RgMVtbU3lzdGVtLkludDMyLCBtc2NvcmxpYiwgVmVyc2lvbj00LjAuMC4wLCBDdWx0dXJlPW5ldXRyYWwsIFB1YmxpY0tleVRva2VuPWI3N2E1YzU2MTkzNGUwODldXQMAAAAGX2l0ZW1zBV9zaXplCF92ZXJzaW9uBwAACAgICQUAAAAAAAAAAAAAAA8FAAAAAAAAAAgL", "AAEAAAD/////AQAAAAAAAAAMAgAAAE5XaW5kb3dzQmFzZSwgVmVyc2lvbj0zLjAuMC4wLCBDdWx0dXJlPU5ldXRyYWwsIFB1YmxpY0tleVRva2VuPTMxYmYzODU2YWQzNjRlMzUFAQAAAJIBU3lzdGVtLkNvbGxlY3Rpb25zLk9iamVjdE1vZGVsLk9ic2VydmFibGVDb2xsZWN0aW9uYDFbW1N5c3RlbS5JbnQzMiwgbXNjb3JsaWIsIFZlcnNpb249NC4wLjAuMCwgQ3VsdHVyZT1uZXV0cmFsLCBQdWJsaWNLZXlUb2tlbj1iNzdhNWM1NjE5MzRlMDg5XV0CAAAACF9tb25pdG9yEkNvbGxlY3Rpb25gMStpdGVtcwQDoAFTeXN0ZW0uQ29sbGVjdGlvbnMuT2JqZWN0TW9kZWwuT2JzZXJ2YWJsZUNvbGxlY3Rpb25gMStTaW1wbGVNb25pdG9yW1tTeXN0ZW0uSW50MzIsIG1zY29ybGliLCBWZXJzaW9uPTQuMC4wLjAsIEN1bHR1cmU9bmV1dHJhbCwgUHVibGljS2V5VG9rZW49Yjc3YTVjNTYxOTM0ZTA4OV1dAgAAAH5TeXN0ZW0uQ29sbGVjdGlvbnMuR2VuZXJpYy5MaXN0YDFbW1N5c3RlbS5JbnQzMiwgbXNjb3JsaWIsIFZlcnNpb249NC4wLjAuMCwgQ3VsdHVyZT1uZXV0cmFsLCBQdWJsaWNLZXlUb2tlbj1iNzdhNWM1NjE5MzRlMDg5XV0CAAAACQMAAAAJBAAAAAUDAAAAoAFTeXN0ZW0uQ29sbGVjdGlvbnMuT2JqZWN0TW9kZWwuT2JzZXJ2YWJsZUNvbGxlY3Rpb25gMStTaW1wbGVNb25pdG9yW1tTeXN0ZW0uSW50MzIsIG1zY29ybGliLCBWZXJzaW9uPTQuMC4wLjAsIEN1bHR1cmU9bmV1dHJhbCwgUHVibGljS2V5VG9rZW49Yjc3YTVjNTYxOTM0ZTA4OV1dAQAAAApfYnVzeUNvdW50AAgCAAAAAAAAAAQEAAAAflN5c3RlbS5Db2xsZWN0aW9ucy5HZW5lcmljLkxpc3RgMVtbU3lzdGVtLkludDMyLCBtc2NvcmxpYiwgVmVyc2lvbj00LjAuMC4wLCBDdWx0dXJlPW5ldXRyYWwsIFB1YmxpY0tleVRva2VuPWI3N2E1YzU2MTkzNGUwODldXQMAAAAGX2l0ZW1zBV9zaXplCF92ZXJzaW9uBwAACAgICQUAAAAAAAAAAAAAAA8FAAAAAAAAAAgL" } };
- yield return new object[] { new ObservableCollection<int>(Enumerable.Range(0, 123)), new string[] { "AAEAAAD/////AQAAAAAAAAAMAgAAAE5XaW5kb3dzQmFzZSwgVmVyc2lvbj0zLjAuMC4wLCBDdWx0dXJlPU5ldXRyYWwsIFB1YmxpY0tleVRva2VuPTMxYmYzODU2YWQzNjRlMzUFAQAAAJIBU3lzdGVtLkNvbGxlY3Rpb25zLk9iamVjdE1vZGVsLk9ic2VydmFibGVDb2xsZWN0aW9uYDFbW1N5c3RlbS5JbnQzMiwgbXNjb3JsaWIsIFZlcnNpb249NC4wLjAuMCwgQ3VsdHVyZT1uZXV0cmFsLCBQdWJsaWNLZXlUb2tlbj1iNzdhNWM1NjE5MzRlMDg5XV0CAAAACF9tb25pdG9yEkNvbGxlY3Rpb25gMStpdGVtcwQDoAFTeXN0ZW0uQ29sbGVjdGlvbnMuT2JqZWN0TW9kZWwuT2JzZXJ2YWJsZUNvbGxlY3Rpb25gMStTaW1wbGVNb25pdG9yW1tTeXN0ZW0uSW50MzIsIG1zY29ybGliLCBWZXJzaW9uPTQuMC4wLjAsIEN1bHR1cmU9bmV1dHJhbCwgUHVibGljS2V5VG9rZW49Yjc3YTVjNTYxOTM0ZTA4OV1dAgAAAH5TeXN0ZW0uQ29sbGVjdGlvbnMuR2VuZXJpYy5MaXN0YDFbW1N5c3RlbS5JbnQzMiwgbXNjb3JsaWIsIFZlcnNpb249NC4wLjAuMCwgQ3VsdHVyZT1uZXV0cmFsLCBQdWJsaWNLZXlUb2tlbj1iNzdhNWM1NjE5MzRlMDg5XV0CAAAACQMAAAAJBAAAAAUDAAAAoAFTeXN0ZW0uQ29sbGVjdGlvbnMuT2JqZWN0TW9kZWwuT2JzZXJ2YWJsZUNvbGxlY3Rpb25gMStTaW1wbGVNb25pdG9yW1tTeXN0ZW0uSW50MzIsIG1zY29ybGliLCBWZXJzaW9uPTQuMC4wLjAsIEN1bHR1cmU9bmV1dHJhbCwgUHVibGljS2V5VG9rZW49Yjc3YTVjNTYxOTM0ZTA4OV1dAQAAAApfYnVzeUNvdW50AAgCAAAAAAAAAAQEAAAAflN5c3RlbS5Db2xsZWN0aW9ucy5HZW5lcmljLkxpc3RgMVtbU3lzdGVtLkludDMyLCBtc2NvcmxpYiwgVmVyc2lvbj00LjAuMC4wLCBDdWx0dXJlPW5ldXRyYWwsIFB1YmxpY0tleVRva2VuPWI3N2E1YzU2MTkzNGUwODldXQMAAAAGX2l0ZW1zBV9zaXplCF92ZXJzaW9uBwAACAgICQUAAAB7AAAAAQAAAA8FAAAAgAAAAAgAAAAAAQAAAAIAAAADAAAABAAAAAUAAAAGAAAABwAAAAgAAAAJAAAACgAAAAsAAAAMAAAADQAAAA4AAAAPAAAAEAAAABEAAAASAAAAEwAAABQAAAAVAAAAFgAAABcAAAAYAAAAGQAAABoAAAAbAAAAHAAAAB0AAAAeAAAAHwAAACAAAAAhAAAAIgAAACMAAAAkAAAAJQAAACYAAAAnAAAAKAAAACkAAAAqAAAAKwAAACwAAAAtAAAALgAAAC8AAAAwAAAAMQAAADIAAAAzAAAANAAAADUAAAA2AAAANwAAADgAAAA5AAAAOgAAADsAAAA8AAAAPQAAAD4AAAA/AAAAQAAAAEEAAABCAAAAQwAAAEQAAABFAAAARgAAAEcAAABIAAAASQAAAEoAAABLAAAATAAAAE0AAABOAAAATwAAAFAAAABRAAAAUgAAAFMAAABUAAAAVQAAAFYAAABXAAAAWAAAAFkAAABaAAAAWwAAAFwAAABdAAAAXgAAAF8AAABgAAAAYQAAAGIAAABjAAAAZAAAAGUAAABmAAAAZwAAAGgAAABpAAAAagAAAGsAAABsAAAAbQAAAG4AAABvAAAAcAAAAHEAAAByAAAAcwAAAHQAAAB1AAAAdgAAAHcAAAB4AAAAeQAAAHoAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAs=", "AAEAAAD/////AQAAAAAAAAAMAgAAAE5XaW5kb3dzQmFzZSwgVmVyc2lvbj0zLjAuMC4wLCBDdWx0dXJlPU5ldXRyYWwsIFB1YmxpY0tleVRva2VuPTMxYmYzODU2YWQzNjRlMzUFAQAAAJIBU3lzdGVtLkNvbGxlY3Rpb25zLk9iamVjdE1vZGVsLk9ic2VydmFibGVDb2xsZWN0aW9uYDFbW1N5c3RlbS5JbnQzMiwgbXNjb3JsaWIsIFZlcnNpb249NC4wLjAuMCwgQ3VsdHVyZT1uZXV0cmFsLCBQdWJsaWNLZXlUb2tlbj1iNzdhNWM1NjE5MzRlMDg5XV0CAAAACF9tb25pdG9yEkNvbGxlY3Rpb25gMStpdGVtcwQDoAFTeXN0ZW0uQ29sbGVjdGlvbnMuT2JqZWN0TW9kZWwuT2JzZXJ2YWJsZUNvbGxlY3Rpb25gMStTaW1wbGVNb25pdG9yW1tTeXN0ZW0uSW50MzIsIG1zY29ybGliLCBWZXJzaW9uPTQuMC4wLjAsIEN1bHR1cmU9bmV1dHJhbCwgUHVibGljS2V5VG9rZW49Yjc3YTVjNTYxOTM0ZTA4OV1dAgAAAH5TeXN0ZW0uQ29sbGVjdGlvbnMuR2VuZXJpYy5MaXN0YDFbW1N5c3RlbS5JbnQzMiwgbXNjb3JsaWIsIFZlcnNpb249NC4wLjAuMCwgQ3VsdHVyZT1uZXV0cmFsLCBQdWJsaWNLZXlUb2tlbj1iNzdhNWM1NjE5MzRlMDg5XV0CAAAACQMAAAAJBAAAAAUDAAAAoAFTeXN0ZW0uQ29sbGVjdGlvbnMuT2JqZWN0TW9kZWwuT2JzZXJ2YWJsZUNvbGxlY3Rpb25gMStTaW1wbGVNb25pdG9yW1tTeXN0ZW0uSW50MzIsIG1zY29ybGliLCBWZXJzaW9uPTQuMC4wLjAsIEN1bHR1cmU9bmV1dHJhbCwgUHVibGljS2V5VG9rZW49Yjc3YTVjNTYxOTM0ZTA4OV1dAQAAAApfYnVzeUNvdW50AAgCAAAAAAAAAAQEAAAAflN5c3RlbS5Db2xsZWN0aW9ucy5HZW5lcmljLkxpc3RgMVtbU3lzdGVtLkludDMyLCBtc2NvcmxpYiwgVmVyc2lvbj00LjAuMC4wLCBDdWx0dXJlPW5ldXRyYWwsIFB1YmxpY0tleVRva2VuPWI3N2E1YzU2MTkzNGUwODldXQMAAAAGX2l0ZW1zBV9zaXplCF92ZXJzaW9uBwAACAgICQUAAAB7AAAAewAAAA8FAAAAgAAAAAgAAAAAAQAAAAIAAAADAAAABAAAAAUAAAAGAAAABwAAAAgAAAAJAAAACgAAAAsAAAAMAAAADQAAAA4AAAAPAAAAEAAAABEAAAASAAAAEwAAABQAAAAVAAAAFgAAABcAAAAYAAAAGQAAABoAAAAbAAAAHAAAAB0AAAAeAAAAHwAAACAAAAAhAAAAIgAAACMAAAAkAAAAJQAAACYAAAAnAAAAKAAAACkAAAAqAAAAKwAAACwAAAAtAAAALgAAAC8AAAAwAAAAMQAAADIAAAAzAAAANAAAADUAAAA2AAAANwAAADgAAAA5AAAAOgAAADsAAAA8AAAAPQAAAD4AAAA/AAAAQAAAAEEAAABCAAAAQwAAAEQAAABFAAAARgAAAEcAAABIAAAASQAAAEoAAABLAAAATAAAAE0AAABOAAAATwAAAFAAAABRAAAAUgAAAFMAAABUAAAAVQAAAFYAAABXAAAAWAAAAFkAAABaAAAAWwAAAFwAAABdAAAAXgAAAF8AAABgAAAAYQAAAGIAAABjAAAAZAAAAGUAAABmAAAAZwAAAGgAAABpAAAAagAAAGsAAABsAAAAbQAAAG4AAABvAAAAcAAAAHEAAAByAAAAcwAAAHQAAAB1AAAAdgAAAHcAAAB4AAAAeQAAAHoAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAs=" } };
- yield return new object[] { new ObservableCollection<int>(new int[] { 5, 7, 9 }), new string[] { "AAEAAAD/////AQAAAAAAAAAMAgAAAE5XaW5kb3dzQmFzZSwgVmVyc2lvbj0zLjAuMC4wLCBDdWx0dXJlPU5ldXRyYWwsIFB1YmxpY0tleVRva2VuPTMxYmYzODU2YWQzNjRlMzUFAQAAAJIBU3lzdGVtLkNvbGxlY3Rpb25zLk9iamVjdE1vZGVsLk9ic2VydmFibGVDb2xsZWN0aW9uYDFbW1N5c3RlbS5JbnQzMiwgbXNjb3JsaWIsIFZlcnNpb249NC4wLjAuMCwgQ3VsdHVyZT1uZXV0cmFsLCBQdWJsaWNLZXlUb2tlbj1iNzdhNWM1NjE5MzRlMDg5XV0CAAAACF9tb25pdG9yEkNvbGxlY3Rpb25gMStpdGVtcwQDoAFTeXN0ZW0uQ29sbGVjdGlvbnMuT2JqZWN0TW9kZWwuT2JzZXJ2YWJsZUNvbGxlY3Rpb25gMStTaW1wbGVNb25pdG9yW1tTeXN0ZW0uSW50MzIsIG1zY29ybGliLCBWZXJzaW9uPTQuMC4wLjAsIEN1bHR1cmU9bmV1dHJhbCwgUHVibGljS2V5VG9rZW49Yjc3YTVjNTYxOTM0ZTA4OV1dAgAAAH5TeXN0ZW0uQ29sbGVjdGlvbnMuR2VuZXJpYy5MaXN0YDFbW1N5c3RlbS5JbnQzMiwgbXNjb3JsaWIsIFZlcnNpb249NC4wLjAuMCwgQ3VsdHVyZT1uZXV0cmFsLCBQdWJsaWNLZXlUb2tlbj1iNzdhNWM1NjE5MzRlMDg5XV0CAAAACQMAAAAJBAAAAAUDAAAAoAFTeXN0ZW0uQ29sbGVjdGlvbnMuT2JqZWN0TW9kZWwuT2JzZXJ2YWJsZUNvbGxlY3Rpb25gMStTaW1wbGVNb25pdG9yW1tTeXN0ZW0uSW50MzIsIG1zY29ybGliLCBWZXJzaW9uPTQuMC4wLjAsIEN1bHR1cmU9bmV1dHJhbCwgUHVibGljS2V5VG9rZW49Yjc3YTVjNTYxOTM0ZTA4OV1dAQAAAApfYnVzeUNvdW50AAgCAAAAAAAAAAQEAAAAflN5c3RlbS5Db2xsZWN0aW9ucy5HZW5lcmljLkxpc3RgMVtbU3lzdGVtLkludDMyLCBtc2NvcmxpYiwgVmVyc2lvbj00LjAuMC4wLCBDdWx0dXJlPW5ldXRyYWwsIFB1YmxpY0tleVRva2VuPWI3N2E1YzU2MTkzNGUwODldXQMAAAAGX2l0ZW1zBV9zaXplCF92ZXJzaW9uBwAACAgICQUAAAADAAAAAAAAAA8FAAAAAwAAAAgFAAAABwAAAAkAAAAL", "AAEAAAD/////AQAAAAAAAAAMAgAAAE5XaW5kb3dzQmFzZSwgVmVyc2lvbj0zLjAuMC4wLCBDdWx0dXJlPU5ldXRyYWwsIFB1YmxpY0tleVRva2VuPTMxYmYzODU2YWQzNjRlMzUFAQAAAJIBU3lzdGVtLkNvbGxlY3Rpb25zLk9iamVjdE1vZGVsLk9ic2VydmFibGVDb2xsZWN0aW9uYDFbW1N5c3RlbS5JbnQzMiwgbXNjb3JsaWIsIFZlcnNpb249NC4wLjAuMCwgQ3VsdHVyZT1uZXV0cmFsLCBQdWJsaWNLZXlUb2tlbj1iNzdhNWM1NjE5MzRlMDg5XV0CAAAACF9tb25pdG9yEkNvbGxlY3Rpb25gMStpdGVtcwQDoAFTeXN0ZW0uQ29sbGVjdGlvbnMuT2JqZWN0TW9kZWwuT2JzZXJ2YWJsZUNvbGxlY3Rpb25gMStTaW1wbGVNb25pdG9yW1tTeXN0ZW0uSW50MzIsIG1zY29ybGliLCBWZXJzaW9uPTQuMC4wLjAsIEN1bHR1cmU9bmV1dHJhbCwgUHVibGljS2V5VG9rZW49Yjc3YTVjNTYxOTM0ZTA4OV1dAgAAAH5TeXN0ZW0uQ29sbGVjdGlvbnMuR2VuZXJpYy5MaXN0YDFbW1N5c3RlbS5JbnQzMiwgbXNjb3JsaWIsIFZlcnNpb249NC4wLjAuMCwgQ3VsdHVyZT1uZXV0cmFsLCBQdWJsaWNLZXlUb2tlbj1iNzdhNWM1NjE5MzRlMDg5XV0CAAAACQMAAAAJBAAAAAUDAAAAoAFTeXN0ZW0uQ29sbGVjdGlvbnMuT2JqZWN0TW9kZWwuT2JzZXJ2YWJsZUNvbGxlY3Rpb25gMStTaW1wbGVNb25pdG9yW1tTeXN0ZW0uSW50MzIsIG1zY29ybGliLCBWZXJzaW9uPTQuMC4wLjAsIEN1bHR1cmU9bmV1dHJhbCwgUHVibGljS2V5VG9rZW49Yjc3YTVjNTYxOTM0ZTA4OV1dAQAAAApfYnVzeUNvdW50AAgCAAAAAAAAAAQEAAAAflN5c3RlbS5Db2xsZWN0aW9ucy5HZW5lcmljLkxpc3RgMVtbU3lzdGVtLkludDMyLCBtc2NvcmxpYiwgVmVyc2lvbj00LjAuMC4wLCBDdWx0dXJlPW5ldXRyYWwsIFB1YmxpY0tleVRva2VuPWI3N2E1YzU2MTkzNGUwODldXQMAAAAGX2l0ZW1zBV9zaXplCF92ZXJzaW9uBwAACAgICQUAAAADAAAAAwAAAA8FAAAABAAAAAgFAAAABwAAAAkAAAAAAAAACw==" } };
- yield return new object[] { new ObservableCollection<Point>(), new string[] { "AAEAAAD/////AQAAAAAAAAAMAgAAAE5XaW5kb3dzQmFzZSwgVmVyc2lvbj0zLjAuMC4wLCBDdWx0dXJlPU5ldXRyYWwsIFB1YmxpY0tleVRva2VuPTMxYmYzODU2YWQzNjRlMzUFAQAAAN4BU3lzdGVtLkNvbGxlY3Rpb25zLk9iamVjdE1vZGVsLk9ic2VydmFibGVDb2xsZWN0aW9uYDFbW1N5c3RlbS5SdW50aW1lLlNlcmlhbGl6YXRpb24uRm9ybWF0dGVycy5UZXN0cy5Qb2ludCwgU3lzdGVtLlJ1bnRpbWUuU2VyaWFsaXphdGlvbi5Gb3JtYXR0ZXJzLlRlc3RzLCBWZXJzaW9uPTQuMC4zLjAsIEN1bHR1cmU9bmV1dHJhbCwgUHVibGljS2V5VG9rZW49OWQ3N2NjN2FkMzliNjhlYl1dAgAAAAhfbW9uaXRvchJDb2xsZWN0aW9uYDEraXRlbXMEA+wBU3lzdGVtLkNvbGxlY3Rpb25zLk9iamVjdE1vZGVsLk9ic2VydmFibGVDb2xsZWN0aW9uYDErU2ltcGxlTW9uaXRvcltbU3lzdGVtLlJ1bnRpbWUuU2VyaWFsaXphdGlvbi5Gb3JtYXR0ZXJzLlRlc3RzLlBvaW50LCBTeXN0ZW0uUnVudGltZS5TZXJpYWxpemF0aW9uLkZvcm1hdHRlcnMuVGVzdHMsIFZlcnNpb249NC4wLjMuMCwgQ3VsdHVyZT1uZXV0cmFsLCBQdWJsaWNLZXlUb2tlbj05ZDc3Y2M3YWQzOWI2OGViXV0CAAAAygFTeXN0ZW0uQ29sbGVjdGlvbnMuR2VuZXJpYy5MaXN0YDFbW1N5c3RlbS5SdW50aW1lLlNlcmlhbGl6YXRpb24uRm9ybWF0dGVycy5UZXN0cy5Qb2ludCwgU3lzdGVtLlJ1bnRpbWUuU2VyaWFsaXphdGlvbi5Gb3JtYXR0ZXJzLlRlc3RzLCBWZXJzaW9uPTQuMC4zLjAsIEN1bHR1cmU9bmV1dHJhbCwgUHVibGljS2V5VG9rZW49OWQ3N2NjN2FkMzliNjhlYl1dAgAAAAkDAAAACQQAAAAFAwAAAOwBU3lzdGVtLkNvbGxlY3Rpb25zLk9iamVjdE1vZGVsLk9ic2VydmFibGVDb2xsZWN0aW9uYDErU2ltcGxlTW9uaXRvcltbU3lzdGVtLlJ1bnRpbWUuU2VyaWFsaXphdGlvbi5Gb3JtYXR0ZXJzLlRlc3RzLlBvaW50LCBTeXN0ZW0uUnVudGltZS5TZXJpYWxpemF0aW9uLkZvcm1hdHRlcnMuVGVzdHMsIFZlcnNpb249NC4wLjMuMCwgQ3VsdHVyZT1uZXV0cmFsLCBQdWJsaWNLZXlUb2tlbj05ZDc3Y2M3YWQzOWI2OGViXV0BAAAACl9idXN5Q291bnQACAIAAAAAAAAADAUAAABwU3lzdGVtLlJ1bnRpbWUuU2VyaWFsaXphdGlvbi5Gb3JtYXR0ZXJzLlRlc3RzLCBWZXJzaW9uPTQuMC4zLjAsIEN1bHR1cmU9bmV1dHJhbCwgUHVibGljS2V5VG9rZW49OWQ3N2NjN2FkMzliNjhlYgQEAAAAygFTeXN0ZW0uQ29sbGVjdGlvbnMuR2VuZXJpYy5MaXN0YDFbW1N5c3RlbS5SdW50aW1lLlNlcmlhbGl6YXRpb24uRm9ybWF0dGVycy5UZXN0cy5Qb2ludCwgU3lzdGVtLlJ1bnRpbWUuU2VyaWFsaXphdGlvbi5Gb3JtYXR0ZXJzLlRlc3RzLCBWZXJzaW9uPTQuMC4zLjAsIEN1bHR1cmU9bmV1dHJhbCwgUHVibGljS2V5VG9rZW49OWQ3N2NjN2FkMzliNjhlYl1dAwAAAAZfaXRlbXMFX3NpemUIX3ZlcnNpb24EAAA1U3lzdGVtLlJ1bnRpbWUuU2VyaWFsaXphdGlvbi5Gb3JtYXR0ZXJzLlRlc3RzLlBvaW50W10FAAAACAgJBgAAAAAAAAAAAAAABwYAAAAAAQAAAAAAAAAEM1N5c3RlbS5SdW50aW1lLlNlcmlhbGl6YXRpb24uRm9ybWF0dGVycy5UZXN0cy5Qb2ludAUAAAAL", "AAEAAAD/////AQAAAAAAAAAMAgAAAE5XaW5kb3dzQmFzZSwgVmVyc2lvbj0zLjAuMC4wLCBDdWx0dXJlPU5ldXRyYWwsIFB1YmxpY0tleVRva2VuPTMxYmYzODU2YWQzNjRlMzUFAQAAAN4BU3lzdGVtLkNvbGxlY3Rpb25zLk9iamVjdE1vZGVsLk9ic2VydmFibGVDb2xsZWN0aW9uYDFbW1N5c3RlbS5SdW50aW1lLlNlcmlhbGl6YXRpb24uRm9ybWF0dGVycy5UZXN0cy5Qb2ludCwgU3lzdGVtLlJ1bnRpbWUuU2VyaWFsaXphdGlvbi5Gb3JtYXR0ZXJzLlRlc3RzLCBWZXJzaW9uPTQuMC4zLjAsIEN1bHR1cmU9bmV1dHJhbCwgUHVibGljS2V5VG9rZW49OWQ3N2NjN2FkMzliNjhlYl1dAgAAAAhfbW9uaXRvchJDb2xsZWN0aW9uYDEraXRlbXMEA+wBU3lzdGVtLkNvbGxlY3Rpb25zLk9iamVjdE1vZGVsLk9ic2VydmFibGVDb2xsZWN0aW9uYDErU2ltcGxlTW9uaXRvcltbU3lzdGVtLlJ1bnRpbWUuU2VyaWFsaXphdGlvbi5Gb3JtYXR0ZXJzLlRlc3RzLlBvaW50LCBTeXN0ZW0uUnVudGltZS5TZXJpYWxpemF0aW9uLkZvcm1hdHRlcnMuVGVzdHMsIFZlcnNpb249NC4wLjMuMCwgQ3VsdHVyZT1uZXV0cmFsLCBQdWJsaWNLZXlUb2tlbj05ZDc3Y2M3YWQzOWI2OGViXV0CAAAAygFTeXN0ZW0uQ29sbGVjdGlvbnMuR2VuZXJpYy5MaXN0YDFbW1N5c3RlbS5SdW50aW1lLlNlcmlhbGl6YXRpb24uRm9ybWF0dGVycy5UZXN0cy5Qb2ludCwgU3lzdGVtLlJ1bnRpbWUuU2VyaWFsaXphdGlvbi5Gb3JtYXR0ZXJzLlRlc3RzLCBWZXJzaW9uPTQuMC4zLjAsIEN1bHR1cmU9bmV1dHJhbCwgUHVibGljS2V5VG9rZW49OWQ3N2NjN2FkMzliNjhlYl1dAgAAAAkDAAAACQQAAAAFAwAAAOwBU3lzdGVtLkNvbGxlY3Rpb25zLk9iamVjdE1vZGVsLk9ic2VydmFibGVDb2xsZWN0aW9uYDErU2ltcGxlTW9uaXRvcltbU3lzdGVtLlJ1bnRpbWUuU2VyaWFsaXphdGlvbi5Gb3JtYXR0ZXJzLlRlc3RzLlBvaW50LCBTeXN0ZW0uUnVudGltZS5TZXJpYWxpemF0aW9uLkZvcm1hdHRlcnMuVGVzdHMsIFZlcnNpb249NC4wLjMuMCwgQ3VsdHVyZT1uZXV0cmFsLCBQdWJsaWNLZXlUb2tlbj05ZDc3Y2M3YWQzOWI2OGViXV0BAAAACl9idXN5Q291bnQACAIAAAAAAAAADAUAAABwU3lzdGVtLlJ1bnRpbWUuU2VyaWFsaXphdGlvbi5Gb3JtYXR0ZXJzLlRlc3RzLCBWZXJzaW9uPTQuMC4zLjAsIEN1bHR1cmU9bmV1dHJhbCwgUHVibGljS2V5VG9rZW49OWQ3N2NjN2FkMzliNjhlYgQEAAAAygFTeXN0ZW0uQ29sbGVjdGlvbnMuR2VuZXJpYy5MaXN0YDFbW1N5c3RlbS5SdW50aW1lLlNlcmlhbGl6YXRpb24uRm9ybWF0dGVycy5UZXN0cy5Qb2ludCwgU3lzdGVtLlJ1bnRpbWUuU2VyaWFsaXphdGlvbi5Gb3JtYXR0ZXJzLlRlc3RzLCBWZXJzaW9uPTQuMC4zLjAsIEN1bHR1cmU9bmV1dHJhbCwgUHVibGljS2V5VG9rZW49OWQ3N2NjN2FkMzliNjhlYl1dAwAAAAZfaXRlbXMFX3NpemUIX3ZlcnNpb24EAAA1U3lzdGVtLlJ1bnRpbWUuU2VyaWFsaXphdGlvbi5Gb3JtYXR0ZXJzLlRlc3RzLlBvaW50W10FAAAACAgJBgAAAAAAAAAAAAAABwYAAAAAAQAAAAAAAAAEM1N5c3RlbS5SdW50aW1lLlNlcmlhbGl6YXRpb24uRm9ybWF0dGVycy5UZXN0cy5Qb2ludAUAAAAL" } };
- yield return new object[] { new ObservableCollection<Point>(new Point[] { new Point(1, 2), new Point(4, 3) }), new string[] { "AAEAAAD/////AQAAAAAAAAAMAgAAAE5XaW5kb3dzQmFzZSwgVmVyc2lvbj0zLjAuMC4wLCBDdWx0dXJlPU5ldXRyYWwsIFB1YmxpY0tleVRva2VuPTMxYmYzODU2YWQzNjRlMzUFAQAAAN4BU3lzdGVtLkNvbGxlY3Rpb25zLk9iamVjdE1vZGVsLk9ic2VydmFibGVDb2xsZWN0aW9uYDFbW1N5c3RlbS5SdW50aW1lLlNlcmlhbGl6YXRpb24uRm9ybWF0dGVycy5UZXN0cy5Qb2ludCwgU3lzdGVtLlJ1bnRpbWUuU2VyaWFsaXphdGlvbi5Gb3JtYXR0ZXJzLlRlc3RzLCBWZXJzaW9uPTQuMC4zLjAsIEN1bHR1cmU9bmV1dHJhbCwgUHVibGljS2V5VG9rZW49OWQ3N2NjN2FkMzliNjhlYl1dAgAAAAhfbW9uaXRvchJDb2xsZWN0aW9uYDEraXRlbXMEA+wBU3lzdGVtLkNvbGxlY3Rpb25zLk9iamVjdE1vZGVsLk9ic2VydmFibGVDb2xsZWN0aW9uYDErU2ltcGxlTW9uaXRvcltbU3lzdGVtLlJ1bnRpbWUuU2VyaWFsaXphdGlvbi5Gb3JtYXR0ZXJzLlRlc3RzLlBvaW50LCBTeXN0ZW0uUnVudGltZS5TZXJpYWxpemF0aW9uLkZvcm1hdHRlcnMuVGVzdHMsIFZlcnNpb249NC4wLjMuMCwgQ3VsdHVyZT1uZXV0cmFsLCBQdWJsaWNLZXlUb2tlbj05ZDc3Y2M3YWQzOWI2OGViXV0CAAAAygFTeXN0ZW0uQ29sbGVjdGlvbnMuR2VuZXJpYy5MaXN0YDFbW1N5c3RlbS5SdW50aW1lLlNlcmlhbGl6YXRpb24uRm9ybWF0dGVycy5UZXN0cy5Qb2ludCwgU3lzdGVtLlJ1bnRpbWUuU2VyaWFsaXphdGlvbi5Gb3JtYXR0ZXJzLlRlc3RzLCBWZXJzaW9uPTQuMC4zLjAsIEN1bHR1cmU9bmV1dHJhbCwgUHVibGljS2V5VG9rZW49OWQ3N2NjN2FkMzliNjhlYl1dAgAAAAkDAAAACQQAAAAFAwAAAOwBU3lzdGVtLkNvbGxlY3Rpb25zLk9iamVjdE1vZGVsLk9ic2VydmFibGVDb2xsZWN0aW9uYDErU2ltcGxlTW9uaXRvcltbU3lzdGVtLlJ1bnRpbWUuU2VyaWFsaXphdGlvbi5Gb3JtYXR0ZXJzLlRlc3RzLlBvaW50LCBTeXN0ZW0uUnVudGltZS5TZXJpYWxpemF0aW9uLkZvcm1hdHRlcnMuVGVzdHMsIFZlcnNpb249NC4wLjMuMCwgQ3VsdHVyZT1uZXV0cmFsLCBQdWJsaWNLZXlUb2tlbj05ZDc3Y2M3YWQzOWI2OGViXV0BAAAACl9idXN5Q291bnQACAIAAAAAAAAADAUAAABwU3lzdGVtLlJ1bnRpbWUuU2VyaWFsaXphdGlvbi5Gb3JtYXR0ZXJzLlRlc3RzLCBWZXJzaW9uPTQuMC4zLjAsIEN1bHR1cmU9bmV1dHJhbCwgUHVibGljS2V5VG9rZW49OWQ3N2NjN2FkMzliNjhlYgQEAAAAygFTeXN0ZW0uQ29sbGVjdGlvbnMuR2VuZXJpYy5MaXN0YDFbW1N5c3RlbS5SdW50aW1lLlNlcmlhbGl6YXRpb24uRm9ybWF0dGVycy5UZXN0cy5Qb2ludCwgU3lzdGVtLlJ1bnRpbWUuU2VyaWFsaXphdGlvbi5Gb3JtYXR0ZXJzLlRlc3RzLCBWZXJzaW9uPTQuMC4zLjAsIEN1bHR1cmU9bmV1dHJhbCwgUHVibGljS2V5VG9rZW49OWQ3N2NjN2FkMzliNjhlYl1dAwAAAAZfaXRlbXMFX3NpemUIX3ZlcnNpb24EAAA1U3lzdGVtLlJ1bnRpbWUuU2VyaWFsaXphdGlvbi5Gb3JtYXR0ZXJzLlRlc3RzLlBvaW50W10FAAAACAgJBgAAAAIAAAAAAAAABwYAAAAAAQAAAAIAAAAEM1N5c3RlbS5SdW50aW1lLlNlcmlhbGl6YXRpb24uRm9ybWF0dGVycy5UZXN0cy5Qb2ludAUAAAAJBwAAAAkIAAAABQcAAAAzU3lzdGVtLlJ1bnRpbWUuU2VyaWFsaXphdGlvbi5Gb3JtYXR0ZXJzLlRlc3RzLlBvaW50AgAAAAFYAVkAAAgIBQAAAAEAAAACAAAAAQgAAAAHAAAABAAAAAMAAAAL", "AAEAAAD/////AQAAAAAAAAAMAgAAAE5XaW5kb3dzQmFzZSwgVmVyc2lvbj0zLjAuMC4wLCBDdWx0dXJlPU5ldXRyYWwsIFB1YmxpY0tleVRva2VuPTMxYmYzODU2YWQzNjRlMzUFAQAAAN4BU3lzdGVtLkNvbGxlY3Rpb25zLk9iamVjdE1vZGVsLk9ic2VydmFibGVDb2xsZWN0aW9uYDFbW1N5c3RlbS5SdW50aW1lLlNlcmlhbGl6YXRpb24uRm9ybWF0dGVycy5UZXN0cy5Qb2ludCwgU3lzdGVtLlJ1bnRpbWUuU2VyaWFsaXphdGlvbi5Gb3JtYXR0ZXJzLlRlc3RzLCBWZXJzaW9uPTQuMC4zLjAsIEN1bHR1cmU9bmV1dHJhbCwgUHVibGljS2V5VG9rZW49OWQ3N2NjN2FkMzliNjhlYl1dAgAAAAhfbW9uaXRvchJDb2xsZWN0aW9uYDEraXRlbXMEA+wBU3lzdGVtLkNvbGxlY3Rpb25zLk9iamVjdE1vZGVsLk9ic2VydmFibGVDb2xsZWN0aW9uYDErU2ltcGxlTW9uaXRvcltbU3lzdGVtLlJ1bnRpbWUuU2VyaWFsaXphdGlvbi5Gb3JtYXR0ZXJzLlRlc3RzLlBvaW50LCBTeXN0ZW0uUnVudGltZS5TZXJpYWxpemF0aW9uLkZvcm1hdHRlcnMuVGVzdHMsIFZlcnNpb249NC4wLjMuMCwgQ3VsdHVyZT1uZXV0cmFsLCBQdWJsaWNLZXlUb2tlbj05ZDc3Y2M3YWQzOWI2OGViXV0CAAAAygFTeXN0ZW0uQ29sbGVjdGlvbnMuR2VuZXJpYy5MaXN0YDFbW1N5c3RlbS5SdW50aW1lLlNlcmlhbGl6YXRpb24uRm9ybWF0dGVycy5UZXN0cy5Qb2ludCwgU3lzdGVtLlJ1bnRpbWUuU2VyaWFsaXphdGlvbi5Gb3JtYXR0ZXJzLlRlc3RzLCBWZXJzaW9uPTQuMC4zLjAsIEN1bHR1cmU9bmV1dHJhbCwgUHVibGljS2V5VG9rZW49OWQ3N2NjN2FkMzliNjhlYl1dAgAAAAkDAAAACQQAAAAFAwAAAOwBU3lzdGVtLkNvbGxlY3Rpb25zLk9iamVjdE1vZGVsLk9ic2VydmFibGVDb2xsZWN0aW9uYDErU2ltcGxlTW9uaXRvcltbU3lzdGVtLlJ1bnRpbWUuU2VyaWFsaXphdGlvbi5Gb3JtYXR0ZXJzLlRlc3RzLlBvaW50LCBTeXN0ZW0uUnVudGltZS5TZXJpYWxpemF0aW9uLkZvcm1hdHRlcnMuVGVzdHMsIFZlcnNpb249NC4wLjMuMCwgQ3VsdHVyZT1uZXV0cmFsLCBQdWJsaWNLZXlUb2tlbj05ZDc3Y2M3YWQzOWI2OGViXV0BAAAACl9idXN5Q291bnQACAIAAAAAAAAADAUAAABwU3lzdGVtLlJ1bnRpbWUuU2VyaWFsaXphdGlvbi5Gb3JtYXR0ZXJzLlRlc3RzLCBWZXJzaW9uPTQuMC4zLjAsIEN1bHR1cmU9bmV1dHJhbCwgUHVibGljS2V5VG9rZW49OWQ3N2NjN2FkMzliNjhlYgQEAAAAygFTeXN0ZW0uQ29sbGVjdGlvbnMuR2VuZXJpYy5MaXN0YDFbW1N5c3RlbS5SdW50aW1lLlNlcmlhbGl6YXRpb24uRm9ybWF0dGVycy5UZXN0cy5Qb2ludCwgU3lzdGVtLlJ1bnRpbWUuU2VyaWFsaXphdGlvbi5Gb3JtYXR0ZXJzLlRlc3RzLCBWZXJzaW9uPTQuMC4zLjAsIEN1bHR1cmU9bmV1dHJhbCwgUHVibGljS2V5VG9rZW49OWQ3N2NjN2FkMzliNjhlYl1dAwAAAAZfaXRlbXMFX3NpemUIX3ZlcnNpb24EAAA1U3lzdGVtLlJ1bnRpbWUuU2VyaWFsaXphdGlvbi5Gb3JtYXR0ZXJzLlRlc3RzLlBvaW50W10FAAAACAgJBgAAAAIAAAACAAAABwYAAAAAAQAAAAQAAAAEM1N5c3RlbS5SdW50aW1lLlNlcmlhbGl6YXRpb24uRm9ybWF0dGVycy5UZXN0cy5Qb2ludAUAAAAJBwAAAAkIAAAADQIFBwAAADNTeXN0ZW0uUnVudGltZS5TZXJpYWxpemF0aW9uLkZvcm1hdHRlcnMuVGVzdHMuUG9pbnQCAAAAAVgBWQAACAgFAAAAAQAAAAIAAAABCAAAAAcAAAAEAAAAAwAAAAs=" } };
- yield return new object[] { new ObservableCollection<Tuple<int, Graph<int>>>(), new string[] { "AAEAAAD/////AQAAAAAAAAAMAgAAAE5XaW5kb3dzQmFzZSwgVmVyc2lvbj0zLjAuMC4wLCBDdWx0dXJlPU5ldXRyYWwsIFB1YmxpY0tleVRva2VuPTMxYmYzODU2YWQzNjRlMzUFAQAAAPgDU3lzdGVtLkNvbGxlY3Rpb25zLk9iamVjdE1vZGVsLk9ic2VydmFibGVDb2xsZWN0aW9uYDFbW1N5c3RlbS5UdXBsZWAyW1tTeXN0ZW0uSW50MzIsIG1zY29ybGliLCBWZXJzaW9uPTQuMC4wLjAsIEN1bHR1cmU9bmV1dHJhbCwgUHVibGljS2V5VG9rZW49Yjc3YTVjNTYxOTM0ZTA4OV0sW1N5c3RlbS5SdW50aW1lLlNlcmlhbGl6YXRpb24uRm9ybWF0dGVycy5UZXN0cy5HcmFwaGAxW1tTeXN0ZW0uSW50MzIsIG1zY29ybGliLCBWZXJzaW9uPTQuMC4wLjAsIEN1bHR1cmU9bmV1dHJhbCwgUHVibGljS2V5VG9rZW49Yjc3YTVjNTYxOTM0ZTA4OV1dLCBTeXN0ZW0uUnVudGltZS5TZXJpYWxpemF0aW9uLkZvcm1hdHRlcnMuVGVzdHMsIFZlcnNpb249NC4wLjMuMCwgQ3VsdHVyZT1uZXV0cmFsLCBQdWJsaWNLZXlUb2tlbj05ZDc3Y2M3YWQzOWI2OGViXV0sIG1zY29ybGliLCBWZXJzaW9uPTQuMC4wLjAsIEN1bHR1cmU9bmV1dHJhbCwgUHVibGljS2V5VG9rZW49Yjc3YTVjNTYxOTM0ZTA4OV1dAgAAAAhfbW9uaXRvchJDb2xsZWN0aW9uYDEraXRlbXMEA4YEU3lzdGVtLkNvbGxlY3Rpb25zLk9iamVjdE1vZGVsLk9ic2VydmFibGVDb2xsZWN0aW9uYDErU2ltcGxlTW9uaXRvcltbU3lzdGVtLlR1cGxlYDJbW1N5c3RlbS5JbnQzMiwgbXNjb3JsaWIsIFZlcnNpb249NC4wLjAuMCwgQ3VsdHVyZT1uZXV0cmFsLCBQdWJsaWNLZXlUb2tlbj1iNzdhNWM1NjE5MzRlMDg5XSxbU3lzdGVtLlJ1bnRpbWUuU2VyaWFsaXphdGlvbi5Gb3JtYXR0ZXJzLlRlc3RzLkdyYXBoYDFbW1N5c3RlbS5JbnQzMiwgbXNjb3JsaWIsIFZlcnNpb249NC4wLjAuMCwgQ3VsdHVyZT1uZXV0cmFsLCBQdWJsaWNLZXlUb2tlbj1iNzdhNWM1NjE5MzRlMDg5XV0sIFN5c3RlbS5SdW50aW1lLlNlcmlhbGl6YXRpb24uRm9ybWF0dGVycy5UZXN0cywgVmVyc2lvbj00LjAuMy4wLCBDdWx0dXJlPW5ldXRyYWwsIFB1YmxpY0tleVRva2VuPTlkNzdjYzdhZDM5YjY4ZWJdXSwgbXNjb3JsaWIsIFZlcnNpb249NC4wLjAuMCwgQ3VsdHVyZT1uZXV0cmFsLCBQdWJsaWNLZXlUb2tlbj1iNzdhNWM1NjE5MzRlMDg5XV0CAAAA5ANTeXN0ZW0uQ29sbGVjdGlvbnMuR2VuZXJpYy5MaXN0YDFbW1N5c3RlbS5UdXBsZWAyW1tTeXN0ZW0uSW50MzIsIG1zY29ybGliLCBWZXJzaW9uPTQuMC4wLjAsIEN1bHR1cmU9bmV1dHJhbCwgUHVibGljS2V5VG9rZW49Yjc3YTVjNTYxOTM0ZTA4OV0sW1N5c3RlbS5SdW50aW1lLlNlcmlhbGl6YXRpb24uRm9ybWF0dGVycy5UZXN0cy5HcmFwaGAxW1tTeXN0ZW0uSW50MzIsIG1zY29ybGliLCBWZXJzaW9uPTQuMC4wLjAsIEN1bHR1cmU9bmV1dHJhbCwgUHVibGljS2V5VG9rZW49Yjc3YTVjNTYxOTM0ZTA4OV1dLCBTeXN0ZW0uUnVudGltZS5TZXJpYWxpemF0aW9uLkZvcm1hdHRlcnMuVGVzdHMsIFZlcnNpb249NC4wLjMuMCwgQ3VsdHVyZT1uZXV0cmFsLCBQdWJsaWNLZXlUb2tlbj05ZDc3Y2M3YWQzOWI2OGViXV0sIG1zY29ybGliLCBWZXJzaW9uPTQuMC4wLjAsIEN1bHR1cmU9bmV1dHJhbCwgUHVibGljS2V5VG9rZW49Yjc3YTVjNTYxOTM0ZTA4OV1dAgAAAAkDAAAACQQAAAAFAwAAAIYEU3lzdGVtLkNvbGxlY3Rpb25zLk9iamVjdE1vZGVsLk9ic2VydmFibGVDb2xsZWN0aW9uYDErU2ltcGxlTW9uaXRvcltbU3lzdGVtLlR1cGxlYDJbW1N5c3RlbS5JbnQzMiwgbXNjb3JsaWIsIFZlcnNpb249NC4wLjAuMCwgQ3VsdHVyZT1uZXV0cmFsLCBQdWJsaWNLZXlUb2tlbj1iNzdhNWM1NjE5MzRlMDg5XSxbU3lzdGVtLlJ1bnRpbWUuU2VyaWFsaXphdGlvbi5Gb3JtYXR0ZXJzLlRlc3RzLkdyYXBoYDFbW1N5c3RlbS5JbnQzMiwgbXNjb3JsaWIsIFZlcnNpb249NC4wLjAuMCwgQ3VsdHVyZT1uZXV0cmFsLCBQdWJsaWNLZXlUb2tlbj1iNzdhNWM1NjE5MzRlMDg5XV0sIFN5c3RlbS5SdW50aW1lLlNlcmlhbGl6YXRpb24uRm9ybWF0dGVycy5UZXN0cywgVmVyc2lvbj00LjAuMy4wLCBDdWx0dXJlPW5ldXRyYWwsIFB1YmxpY0tleVRva2VuPTlkNzdjYzdhZDM5YjY4ZWJdXSwgbXNjb3JsaWIsIFZlcnNpb249NC4wLjAuMCwgQ3VsdHVyZT1uZXV0cmFsLCBQdWJsaWNLZXlUb2tlbj1iNzdhNWM1NjE5MzRlMDg5XV0BAAAACl9idXN5Q291bnQACAIAAAAAAAAABAQAAADkA1N5c3RlbS5Db2xsZWN0aW9ucy5HZW5lcmljLkxpc3RgMVtbU3lzdGVtLlR1cGxlYDJbW1N5c3RlbS5JbnQzMiwgbXNjb3JsaWIsIFZlcnNpb249NC4wLjAuMCwgQ3VsdHVyZT1uZXV0cmFsLCBQdWJsaWNLZXlUb2tlbj1iNzdhNWM1NjE5MzRlMDg5XSxbU3lzdGVtLlJ1bnRpbWUuU2VyaWFsaXphdGlvbi5Gb3JtYXR0ZXJzLlRlc3RzLkdyYXBoYDFbW1N5c3RlbS5JbnQzMiwgbXNjb3JsaWIsIFZlcnNpb249NC4wLjAuMCwgQ3VsdHVyZT1uZXV0cmFsLCBQdWJsaWNLZXlUb2tlbj1iNzdhNWM1NjE5MzRlMDg5XV0sIFN5c3RlbS5SdW50aW1lLlNlcmlhbGl6YXRpb24uRm9ybWF0dGVycy5UZXN0cywgVmVyc2lvbj00LjAuMy4wLCBDdWx0dXJlPW5ldXRyYWwsIFB1YmxpY0tleVRva2VuPTlkNzdjYzdhZDM5YjY4ZWJdXSwgbXNjb3JsaWIsIFZlcnNpb249NC4wLjAuMCwgQ3VsdHVyZT1uZXV0cmFsLCBQdWJsaWNLZXlUb2tlbj1iNzdhNWM1NjE5MzRlMDg5XV0DAAAABl9pdGVtcwVfc2l6ZQhfdmVyc2lvbgMAAPQCU3lzdGVtLlR1cGxlYDJbW1N5c3RlbS5JbnQzMiwgbXNjb3JsaWIsIFZlcnNpb249NC4wLjAuMCwgQ3VsdHVyZT1uZXV0cmFsLCBQdWJsaWNLZXlUb2tlbj1iNzdhNWM1NjE5MzRlMDg5XSxbU3lzdGVtLlJ1bnRpbWUuU2VyaWFsaXphdGlvbi5Gb3JtYXR0ZXJzLlRlc3RzLkdyYXBoYDFbW1N5c3RlbS5JbnQzMiwgbXNjb3JsaWIsIFZlcnNpb249NC4wLjAuMCwgQ3VsdHVyZT1uZXV0cmFsLCBQdWJsaWNLZXlUb2tlbj1iNzdhNWM1NjE5MzRlMDg5XV0sIFN5c3RlbS5SdW50aW1lLlNlcmlhbGl6YXRpb24uRm9ybWF0dGVycy5UZXN0cywgVmVyc2lvbj00LjAuMy4wLCBDdWx0dXJlPW5ldXRyYWwsIFB1YmxpY0tleVRva2VuPTlkNzdjYzdhZDM5YjY4ZWJdXVtdCAgJBQAAAAAAAAAAAAAABwUAAAAAAQAAAAAAAAAD8gJTeXN0ZW0uVHVwbGVgMltbU3lzdGVtLkludDMyLCBtc2NvcmxpYiwgVmVyc2lvbj00LjAuMC4wLCBDdWx0dXJlPW5ldXRyYWwsIFB1YmxpY0tleVRva2VuPWI3N2E1YzU2MTkzNGUwODldLFtTeXN0ZW0uUnVudGltZS5TZXJpYWxpemF0aW9uLkZvcm1hdHRlcnMuVGVzdHMuR3JhcGhgMVtbU3lzdGVtLkludDMyLCBtc2NvcmxpYiwgVmVyc2lvbj00LjAuMC4wLCBDdWx0dXJlPW5ldXRyYWwsIFB1YmxpY0tleVRva2VuPWI3N2E1YzU2MTkzNGUwODldXSwgU3lzdGVtLlJ1bnRpbWUuU2VyaWFsaXphdGlvbi5Gb3JtYXR0ZXJzLlRlc3RzLCBWZXJzaW9uPTQuMC4zLjAsIEN1bHR1cmU9bmV1dHJhbCwgUHVibGljS2V5VG9rZW49OWQ3N2NjN2FkMzliNjhlYl1dCw==", "AAEAAAD/////AQAAAAAAAAAMAgAAAE5XaW5kb3dzQmFzZSwgVmVyc2lvbj0zLjAuMC4wLCBDdWx0dXJlPU5ldXRyYWwsIFB1YmxpY0tleVRva2VuPTMxYmYzODU2YWQzNjRlMzUFAQAAAPgDU3lzdGVtLkNvbGxlY3Rpb25zLk9iamVjdE1vZGVsLk9ic2VydmFibGVDb2xsZWN0aW9uYDFbW1N5c3RlbS5UdXBsZWAyW1tTeXN0ZW0uSW50MzIsIG1zY29ybGliLCBWZXJzaW9uPTQuMC4wLjAsIEN1bHR1cmU9bmV1dHJhbCwgUHVibGljS2V5VG9rZW49Yjc3YTVjNTYxOTM0ZTA4OV0sW1N5c3RlbS5SdW50aW1lLlNlcmlhbGl6YXRpb24uRm9ybWF0dGVycy5UZXN0cy5HcmFwaGAxW1tTeXN0ZW0uSW50MzIsIG1zY29ybGliLCBWZXJzaW9uPTQuMC4wLjAsIEN1bHR1cmU9bmV1dHJhbCwgUHVibGljS2V5VG9rZW49Yjc3YTVjNTYxOTM0ZTA4OV1dLCBTeXN0ZW0uUnVudGltZS5TZXJpYWxpemF0aW9uLkZvcm1hdHRlcnMuVGVzdHMsIFZlcnNpb249NC4wLjMuMCwgQ3VsdHVyZT1uZXV0cmFsLCBQdWJsaWNLZXlUb2tlbj05ZDc3Y2M3YWQzOWI2OGViXV0sIG1zY29ybGliLCBWZXJzaW9uPTQuMC4wLjAsIEN1bHR1cmU9bmV1dHJhbCwgUHVibGljS2V5VG9rZW49Yjc3YTVjNTYxOTM0ZTA4OV1dAgAAAAhfbW9uaXRvchJDb2xsZWN0aW9uYDEraXRlbXMEA4YEU3lzdGVtLkNvbGxlY3Rpb25zLk9iamVjdE1vZGVsLk9ic2VydmFibGVDb2xsZWN0aW9uYDErU2ltcGxlTW9uaXRvcltbU3lzdGVtLlR1cGxlYDJbW1N5c3RlbS5JbnQzMiwgbXNjb3JsaWIsIFZlcnNpb249NC4wLjAuMCwgQ3VsdHVyZT1uZXV0cmFsLCBQdWJsaWNLZXlUb2tlbj1iNzdhNWM1NjE5MzRlMDg5XSxbU3lzdGVtLlJ1bnRpbWUuU2VyaWFsaXphdGlvbi5Gb3JtYXR0ZXJzLlRlc3RzLkdyYXBoYDFbW1N5c3RlbS5JbnQzMiwgbXNjb3JsaWIsIFZlcnNpb249NC4wLjAuMCwgQ3VsdHVyZT1uZXV0cmFsLCBQdWJsaWNLZXlUb2tlbj1iNzdhNWM1NjE5MzRlMDg5XV0sIFN5c3RlbS5SdW50aW1lLlNlcmlhbGl6YXRpb24uRm9ybWF0dGVycy5UZXN0cywgVmVyc2lvbj00LjAuMy4wLCBDdWx0dXJlPW5ldXRyYWwsIFB1YmxpY0tleVRva2VuPTlkNzdjYzdhZDM5YjY4ZWJdXSwgbXNjb3JsaWIsIFZlcnNpb249NC4wLjAuMCwgQ3VsdHVyZT1uZXV0cmFsLCBQdWJsaWNLZXlUb2tlbj1iNzdhNWM1NjE5MzRlMDg5XV0CAAAA5ANTeXN0ZW0uQ29sbGVjdGlvbnMuR2VuZXJpYy5MaXN0YDFbW1N5c3RlbS5UdXBsZWAyW1tTeXN0ZW0uSW50MzIsIG1zY29ybGliLCBWZXJzaW9uPTQuMC4wLjAsIEN1bHR1cmU9bmV1dHJhbCwgUHVibGljS2V5VG9rZW49Yjc3YTVjNTYxOTM0ZTA4OV0sW1N5c3RlbS5SdW50aW1lLlNlcmlhbGl6YXRpb24uRm9ybWF0dGVycy5UZXN0cy5HcmFwaGAxW1tTeXN0ZW0uSW50MzIsIG1zY29ybGliLCBWZXJzaW9uPTQuMC4wLjAsIEN1bHR1cmU9bmV1dHJhbCwgUHVibGljS2V5VG9rZW49Yjc3YTVjNTYxOTM0ZTA4OV1dLCBTeXN0ZW0uUnVudGltZS5TZXJpYWxpemF0aW9uLkZvcm1hdHRlcnMuVGVzdHMsIFZlcnNpb249NC4wLjMuMCwgQ3VsdHVyZT1uZXV0cmFsLCBQdWJsaWNLZXlUb2tlbj05ZDc3Y2M3YWQzOWI2OGViXV0sIG1zY29ybGliLCBWZXJzaW9uPTQuMC4wLjAsIEN1bHR1cmU9bmV1dHJhbCwgUHVibGljS2V5VG9rZW49Yjc3YTVjNTYxOTM0ZTA4OV1dAgAAAAkDAAAACQQAAAAFAwAAAIYEU3lzdGVtLkNvbGxlY3Rpb25zLk9iamVjdE1vZGVsLk9ic2VydmFibGVDb2xsZWN0aW9uYDErU2ltcGxlTW9uaXRvcltbU3lzdGVtLlR1cGxlYDJbW1N5c3RlbS5JbnQzMiwgbXNjb3JsaWIsIFZlcnNpb249NC4wLjAuMCwgQ3VsdHVyZT1uZXV0cmFsLCBQdWJsaWNLZXlUb2tlbj1iNzdhNWM1NjE5MzRlMDg5XSxbU3lzdGVtLlJ1bnRpbWUuU2VyaWFsaXphdGlvbi5Gb3JtYXR0ZXJzLlRlc3RzLkdyYXBoYDFbW1N5c3RlbS5JbnQzMiwgbXNjb3JsaWIsIFZlcnNpb249NC4wLjAuMCwgQ3VsdHVyZT1uZXV0cmFsLCBQdWJsaWNLZXlUb2tlbj1iNzdhNWM1NjE5MzRlMDg5XV0sIFN5c3RlbS5SdW50aW1lLlNlcmlhbGl6YXRpb24uRm9ybWF0dGVycy5UZXN0cywgVmVyc2lvbj00LjAuMy4wLCBDdWx0dXJlPW5ldXRyYWwsIFB1YmxpY0tleVRva2VuPTlkNzdjYzdhZDM5YjY4ZWJdXSwgbXNjb3JsaWIsIFZlcnNpb249NC4wLjAuMCwgQ3VsdHVyZT1uZXV0cmFsLCBQdWJsaWNLZXlUb2tlbj1iNzdhNWM1NjE5MzRlMDg5XV0BAAAACl9idXN5Q291bnQACAIAAAAAAAAABAQAAADkA1N5c3RlbS5Db2xsZWN0aW9ucy5HZW5lcmljLkxpc3RgMVtbU3lzdGVtLlR1cGxlYDJbW1N5c3RlbS5JbnQzMiwgbXNjb3JsaWIsIFZlcnNpb249NC4wLjAuMCwgQ3VsdHVyZT1uZXV0cmFsLCBQdWJsaWNLZXlUb2tlbj1iNzdhNWM1NjE5MzRlMDg5XSxbU3lzdGVtLlJ1bnRpbWUuU2VyaWFsaXphdGlvbi5Gb3JtYXR0ZXJzLlRlc3RzLkdyYXBoYDFbW1N5c3RlbS5JbnQzMiwgbXNjb3JsaWIsIFZlcnNpb249NC4wLjAuMCwgQ3VsdHVyZT1uZXV0cmFsLCBQdWJsaWNLZXlUb2tlbj1iNzdhNWM1NjE5MzRlMDg5XV0sIFN5c3RlbS5SdW50aW1lLlNlcmlhbGl6YXRpb24uRm9ybWF0dGVycy5UZXN0cywgVmVyc2lvbj00LjAuMy4wLCBDdWx0dXJlPW5ldXRyYWwsIFB1YmxpY0tleVRva2VuPTlkNzdjYzdhZDM5YjY4ZWJdXSwgbXNjb3JsaWIsIFZlcnNpb249NC4wLjAuMCwgQ3VsdHVyZT1uZXV0cmFsLCBQdWJsaWNLZXlUb2tlbj1iNzdhNWM1NjE5MzRlMDg5XV0DAAAABl9pdGVtcwVfc2l6ZQhfdmVyc2lvbgMAAPQCU3lzdGVtLlR1cGxlYDJbW1N5c3RlbS5JbnQzMiwgbXNjb3JsaWIsIFZlcnNpb249NC4wLjAuMCwgQ3VsdHVyZT1uZXV0cmFsLCBQdWJsaWNLZXlUb2tlbj1iNzdhNWM1NjE5MzRlMDg5XSxbU3lzdGVtLlJ1bnRpbWUuU2VyaWFsaXphdGlvbi5Gb3JtYXR0ZXJzLlRlc3RzLkdyYXBoYDFbW1N5c3RlbS5JbnQzMiwgbXNjb3JsaWIsIFZlcnNpb249NC4wLjAuMCwgQ3VsdHVyZT1uZXV0cmFsLCBQdWJsaWNLZXlUb2tlbj1iNzdhNWM1NjE5MzRlMDg5XV0sIFN5c3RlbS5SdW50aW1lLlNlcmlhbGl6YXRpb24uRm9ybWF0dGVycy5UZXN0cywgVmVyc2lvbj00LjAuMy4wLCBDdWx0dXJlPW5ldXRyYWwsIFB1YmxpY0tleVRva2VuPTlkNzdjYzdhZDM5YjY4ZWJdXVtdCAgJBQAAAAAAAAAAAAAABwUAAAAAAQAAAAAAAAAD8gJTeXN0ZW0uVHVwbGVgMltbU3lzdGVtLkludDMyLCBtc2NvcmxpYiwgVmVyc2lvbj00LjAuMC4wLCBDdWx0dXJlPW5ldXRyYWwsIFB1YmxpY0tleVRva2VuPWI3N2E1YzU2MTkzNGUwODldLFtTeXN0ZW0uUnVudGltZS5TZXJpYWxpemF0aW9uLkZvcm1hdHRlcnMuVGVzdHMuR3JhcGhgMVtbU3lzdGVtLkludDMyLCBtc2NvcmxpYiwgVmVyc2lvbj00LjAuMC4wLCBDdWx0dXJlPW5ldXRyYWwsIFB1YmxpY0tleVRva2VuPWI3N2E1YzU2MTkzNGUwODldXSwgU3lzdGVtLlJ1bnRpbWUuU2VyaWFsaXphdGlvbi5Gb3JtYXR0ZXJzLlRlc3RzLCBWZXJzaW9uPTQuMC4zLjAsIEN1bHR1cmU9bmV1dHJhbCwgUHVibGljS2V5VG9rZW49OWQ3N2NjN2FkMzliNjhlYl1dCw==" } };
- yield return new object[] { new ObservableCollection<Tuple<int, Graph<int>>>(new Tuple<int, Graph<int>>[] { Tuple.Create(1, new Graph<int>()), Tuple.Create(5, new Graph<int>()) }), new string[] { "AAEAAAD/////AQAAAAAAAAAMAgAAAE5XaW5kb3dzQmFzZSwgVmVyc2lvbj0zLjAuMC4wLCBDdWx0dXJlPU5ldXRyYWwsIFB1YmxpY0tleVRva2VuPTMxYmYzODU2YWQzNjRlMzUFAQAAAPgDU3lzdGVtLkNvbGxlY3Rpb25zLk9iamVjdE1vZGVsLk9ic2VydmFibGVDb2xsZWN0aW9uYDFbW1N5c3RlbS5UdXBsZWAyW1tTeXN0ZW0uSW50MzIsIG1zY29ybGliLCBWZXJzaW9uPTQuMC4wLjAsIEN1bHR1cmU9bmV1dHJhbCwgUHVibGljS2V5VG9rZW49Yjc3YTVjNTYxOTM0ZTA4OV0sW1N5c3RlbS5SdW50aW1lLlNlcmlhbGl6YXRpb24uRm9ybWF0dGVycy5UZXN0cy5HcmFwaGAxW1tTeXN0ZW0uSW50MzIsIG1zY29ybGliLCBWZXJzaW9uPTQuMC4wLjAsIEN1bHR1cmU9bmV1dHJhbCwgUHVibGljS2V5VG9rZW49Yjc3YTVjNTYxOTM0ZTA4OV1dLCBTeXN0ZW0uUnVudGltZS5TZXJpYWxpemF0aW9uLkZvcm1hdHRlcnMuVGVzdHMsIFZlcnNpb249NC4wLjMuMCwgQ3VsdHVyZT1uZXV0cmFsLCBQdWJsaWNLZXlUb2tlbj05ZDc3Y2M3YWQzOWI2OGViXV0sIG1zY29ybGliLCBWZXJzaW9uPTQuMC4wLjAsIEN1bHR1cmU9bmV1dHJhbCwgUHVibGljS2V5VG9rZW49Yjc3YTVjNTYxOTM0ZTA4OV1dAgAAAAhfbW9uaXRvchJDb2xsZWN0aW9uYDEraXRlbXMEA4YEU3lzdGVtLkNvbGxlY3Rpb25zLk9iamVjdE1vZGVsLk9ic2VydmFibGVDb2xsZWN0aW9uYDErU2ltcGxlTW9uaXRvcltbU3lzdGVtLlR1cGxlYDJbW1N5c3RlbS5JbnQzMiwgbXNjb3JsaWIsIFZlcnNpb249NC4wLjAuMCwgQ3VsdHVyZT1uZXV0cmFsLCBQdWJsaWNLZXlUb2tlbj1iNzdhNWM1NjE5MzRlMDg5XSxbU3lzdGVtLlJ1bnRpbWUuU2VyaWFsaXphdGlvbi5Gb3JtYXR0ZXJzLlRlc3RzLkdyYXBoYDFbW1N5c3RlbS5JbnQzMiwgbXNjb3JsaWIsIFZlcnNpb249NC4wLjAuMCwgQ3VsdHVyZT1uZXV0cmFsLCBQdWJsaWNLZXlUb2tlbj1iNzdhNWM1NjE5MzRlMDg5XV0sIFN5c3RlbS5SdW50aW1lLlNlcmlhbGl6YXRpb24uRm9ybWF0dGVycy5UZXN0cywgVmVyc2lvbj00LjAuMy4wLCBDdWx0dXJlPW5ldXRyYWwsIFB1YmxpY0tleVRva2VuPTlkNzdjYzdhZDM5YjY4ZWJdXSwgbXNjb3JsaWIsIFZlcnNpb249NC4wLjAuMCwgQ3VsdHVyZT1uZXV0cmFsLCBQdWJsaWNLZXlUb2tlbj1iNzdhNWM1NjE5MzRlMDg5XV0CAAAA5ANTeXN0ZW0uQ29sbGVjdGlvbnMuR2VuZXJpYy5MaXN0YDFbW1N5c3RlbS5UdXBsZWAyW1tTeXN0ZW0uSW50MzIsIG1zY29ybGliLCBWZXJzaW9uPTQuMC4wLjAsIEN1bHR1cmU9bmV1dHJhbCwgUHVibGljS2V5VG9rZW49Yjc3YTVjNTYxOTM0ZTA4OV0sW1N5c3RlbS5SdW50aW1lLlNlcmlhbGl6YXRpb24uRm9ybWF0dGVycy5UZXN0cy5HcmFwaGAxW1tTeXN0ZW0uSW50MzIsIG1zY29ybGliLCBWZXJzaW9uPTQuMC4wLjAsIEN1bHR1cmU9bmV1dHJhbCwgUHVibGljS2V5VG9rZW49Yjc3YTVjNTYxOTM0ZTA4OV1dLCBTeXN0ZW0uUnVudGltZS5TZXJpYWxpemF0aW9uLkZvcm1hdHRlcnMuVGVzdHMsIFZlcnNpb249NC4wLjMuMCwgQ3VsdHVyZT1uZXV0cmFsLCBQdWJsaWNLZXlUb2tlbj05ZDc3Y2M3YWQzOWI2OGViXV0sIG1zY29ybGliLCBWZXJzaW9uPTQuMC4wLjAsIEN1bHR1cmU9bmV1dHJhbCwgUHVibGljS2V5VG9rZW49Yjc3YTVjNTYxOTM0ZTA4OV1dAgAAAAkDAAAACQQAAAAFAwAAAIYEU3lzdGVtLkNvbGxlY3Rpb25zLk9iamVjdE1vZGVsLk9ic2VydmFibGVDb2xsZWN0aW9uYDErU2ltcGxlTW9uaXRvcltbU3lzdGVtLlR1cGxlYDJbW1N5c3RlbS5JbnQzMiwgbXNjb3JsaWIsIFZlcnNpb249NC4wLjAuMCwgQ3VsdHVyZT1uZXV0cmFsLCBQdWJsaWNLZXlUb2tlbj1iNzdhNWM1NjE5MzRlMDg5XSxbU3lzdGVtLlJ1bnRpbWUuU2VyaWFsaXphdGlvbi5Gb3JtYXR0ZXJzLlRlc3RzLkdyYXBoYDFbW1N5c3RlbS5JbnQzMiwgbXNjb3JsaWIsIFZlcnNpb249NC4wLjAuMCwgQ3VsdHVyZT1uZXV0cmFsLCBQdWJsaWNLZXlUb2tlbj1iNzdhNWM1NjE5MzRlMDg5XV0sIFN5c3RlbS5SdW50aW1lLlNlcmlhbGl6YXRpb24uRm9ybWF0dGVycy5UZXN0cywgVmVyc2lvbj00LjAuMy4wLCBDdWx0dXJlPW5ldXRyYWwsIFB1YmxpY0tleVRva2VuPTlkNzdjYzdhZDM5YjY4ZWJdXSwgbXNjb3JsaWIsIFZlcnNpb249NC4wLjAuMCwgQ3VsdHVyZT1uZXV0cmFsLCBQdWJsaWNLZXlUb2tlbj1iNzdhNWM1NjE5MzRlMDg5XV0BAAAACl9idXN5Q291bnQACAIAAAAAAAAABAQAAADkA1N5c3RlbS5Db2xsZWN0aW9ucy5HZW5lcmljLkxpc3RgMVtbU3lzdGVtLlR1cGxlYDJbW1N5c3RlbS5JbnQzMiwgbXNjb3JsaWIsIFZlcnNpb249NC4wLjAuMCwgQ3VsdHVyZT1uZXV0cmFsLCBQdWJsaWNLZXlUb2tlbj1iNzdhNWM1NjE5MzRlMDg5XSxbU3lzdGVtLlJ1bnRpbWUuU2VyaWFsaXphdGlvbi5Gb3JtYXR0ZXJzLlRlc3RzLkdyYXBoYDFbW1N5c3RlbS5JbnQzMiwgbXNjb3JsaWIsIFZlcnNpb249NC4wLjAuMCwgQ3VsdHVyZT1uZXV0cmFsLCBQdWJsaWNLZXlUb2tlbj1iNzdhNWM1NjE5MzRlMDg5XV0sIFN5c3RlbS5SdW50aW1lLlNlcmlhbGl6YXRpb24uRm9ybWF0dGVycy5UZXN0cywgVmVyc2lvbj00LjAuMy4wLCBDdWx0dXJlPW5ldXRyYWwsIFB1YmxpY0tleVRva2VuPTlkNzdjYzdhZDM5YjY4ZWJdXSwgbXNjb3JsaWIsIFZlcnNpb249NC4wLjAuMCwgQ3VsdHVyZT1uZXV0cmFsLCBQdWJsaWNLZXlUb2tlbj1iNzdhNWM1NjE5MzRlMDg5XV0DAAAABl9pdGVtcwVfc2l6ZQhfdmVyc2lvbgMAAPQCU3lzdGVtLlR1cGxlYDJbW1N5c3RlbS5JbnQzMiwgbXNjb3JsaWIsIFZlcnNpb249NC4wLjAuMCwgQ3VsdHVyZT1uZXV0cmFsLCBQdWJsaWNLZXlUb2tlbj1iNzdhNWM1NjE5MzRlMDg5XSxbU3lzdGVtLlJ1bnRpbWUuU2VyaWFsaXphdGlvbi5Gb3JtYXR0ZXJzLlRlc3RzLkdyYXBoYDFbW1N5c3RlbS5JbnQzMiwgbXNjb3JsaWIsIFZlcnNpb249NC4wLjAuMCwgQ3VsdHVyZT1uZXV0cmFsLCBQdWJsaWNLZXlUb2tlbj1iNzdhNWM1NjE5MzRlMDg5XV0sIFN5c3RlbS5SdW50aW1lLlNlcmlhbGl6YXRpb24uRm9ybWF0dGVycy5UZXN0cywgVmVyc2lvbj00LjAuMy4wLCBDdWx0dXJlPW5ldXRyYWwsIFB1YmxpY0tleVRva2VuPTlkNzdjYzdhZDM5YjY4ZWJdXVtdCAgJBQAAAAIAAAAAAAAABwUAAAAAAQAAAAIAAAAD8gJTeXN0ZW0uVHVwbGVgMltbU3lzdGVtLkludDMyLCBtc2NvcmxpYiwgVmVyc2lvbj00LjAuMC4wLCBDdWx0dXJlPW5ldXRyYWwsIFB1YmxpY0tleVRva2VuPWI3N2E1YzU2MTkzNGUwODldLFtTeXN0ZW0uUnVudGltZS5TZXJpYWxpemF0aW9uLkZvcm1hdHRlcnMuVGVzdHMuR3JhcGhgMVtbU3lzdGVtLkludDMyLCBtc2NvcmxpYiwgVmVyc2lvbj00LjAuMC4wLCBDdWx0dXJlPW5ldXRyYWwsIFB1YmxpY0tleVRva2VuPWI3N2E1YzU2MTkzNGUwODldXSwgU3lzdGVtLlJ1bnRpbWUuU2VyaWFsaXphdGlvbi5Gb3JtYXR0ZXJzLlRlc3RzLCBWZXJzaW9uPTQuMC4zLjAsIEN1bHR1cmU9bmV1dHJhbCwgUHVibGljS2V5VG9rZW49OWQ3N2NjN2FkMzliNjhlYl1dCQYAAAAJBwAAAAwIAAAAcFN5c3RlbS5SdW50aW1lLlNlcmlhbGl6YXRpb24uRm9ybWF0dGVycy5UZXN0cywgVmVyc2lvbj00LjAuMy4wLCBDdWx0dXJlPW5ldXRyYWwsIFB1YmxpY0tleVRva2VuPTlkNzdjYzdhZDM5YjY4ZWIEBgAAAPICU3lzdGVtLlR1cGxlYDJbW1N5c3RlbS5JbnQzMiwgbXNjb3JsaWIsIFZlcnNpb249NC4wLjAuMCwgQ3VsdHVyZT1uZXV0cmFsLCBQdWJsaWNLZXlUb2tlbj1iNzdhNWM1NjE5MzRlMDg5XSxbU3lzdGVtLlJ1bnRpbWUuU2VyaWFsaXphdGlvbi5Gb3JtYXR0ZXJzLlRlc3RzLkdyYXBoYDFbW1N5c3RlbS5JbnQzMiwgbXNjb3JsaWIsIFZlcnNpb249NC4wLjAuMCwgQ3VsdHVyZT1uZXV0cmFsLCBQdWJsaWNLZXlUb2tlbj1iNzdhNWM1NjE5MzRlMDg5XV0sIFN5c3RlbS5SdW50aW1lLlNlcmlhbGl6YXRpb24uRm9ybWF0dGVycy5UZXN0cywgVmVyc2lvbj00LjAuMy4wLCBDdWx0dXJlPW5ldXRyYWwsIFB1YmxpY0tleVRva2VuPTlkNzdjYzdhZDM5YjY4ZWJdXQIAAAAHbV9JdGVtMQdtX0l0ZW0yAAQIkgFTeXN0ZW0uUnVudGltZS5TZXJpYWxpemF0aW9uLkZvcm1hdHRlcnMuVGVzdHMuR3JhcGhgMVtbU3lzdGVtLkludDMyLCBtc2NvcmxpYiwgVmVyc2lvbj00LjAuMC4wLCBDdWx0dXJlPW5ldXRyYWwsIFB1YmxpY0tleVRva2VuPWI3N2E1YzU2MTkzNGUwODldXQgAAAABAAAACQkAAAABBwAAAAYAAAAFAAAACQoAAAAFCQAAAJIBU3lzdGVtLlJ1bnRpbWUuU2VyaWFsaXphdGlvbi5Gb3JtYXR0ZXJzLlRlc3RzLkdyYXBoYDFbW1N5c3RlbS5JbnQzMiwgbXNjb3JsaWIsIFZlcnNpb249NC4wLjAuMCwgQ3VsdHVyZT1uZXV0cmFsLCBQdWJsaWNLZXlUb2tlbj1iNzdhNWM1NjE5MzRlMDg5XV0CAAAABVZhbHVlBUxpbmtzAAQIlAFTeXN0ZW0uUnVudGltZS5TZXJpYWxpemF0aW9uLkZvcm1hdHRlcnMuVGVzdHMuR3JhcGhgMVtbU3lzdGVtLkludDMyLCBtc2NvcmxpYiwgVmVyc2lvbj00LjAuMC4wLCBDdWx0dXJlPW5ldXRyYWwsIFB1YmxpY0tleVRva2VuPWI3N2E1YzU2MTkzNGUwODldXVtdCAAAAAgAAAAAAAAACgEKAAAACQAAAAAAAAAKCw==", "AAEAAAD/////AQAAAAAAAAAMAgAAAE5XaW5kb3dzQmFzZSwgVmVyc2lvbj0zLjAuMC4wLCBDdWx0dXJlPU5ldXRyYWwsIFB1YmxpY0tleVRva2VuPTMxYmYzODU2YWQzNjRlMzUFAQAAAPgDU3lzdGVtLkNvbGxlY3Rpb25zLk9iamVjdE1vZGVsLk9ic2VydmFibGVDb2xsZWN0aW9uYDFbW1N5c3RlbS5UdXBsZWAyW1tTeXN0ZW0uSW50MzIsIG1zY29ybGliLCBWZXJzaW9uPTQuMC4wLjAsIEN1bHR1cmU9bmV1dHJhbCwgUHVibGljS2V5VG9rZW49Yjc3YTVjNTYxOTM0ZTA4OV0sW1N5c3RlbS5SdW50aW1lLlNlcmlhbGl6YXRpb24uRm9ybWF0dGVycy5UZXN0cy5HcmFwaGAxW1tTeXN0ZW0uSW50MzIsIG1zY29ybGliLCBWZXJzaW9uPTQuMC4wLjAsIEN1bHR1cmU9bmV1dHJhbCwgUHVibGljS2V5VG9rZW49Yjc3YTVjNTYxOTM0ZTA4OV1dLCBTeXN0ZW0uUnVudGltZS5TZXJpYWxpemF0aW9uLkZvcm1hdHRlcnMuVGVzdHMsIFZlcnNpb249NC4wLjMuMCwgQ3VsdHVyZT1uZXV0cmFsLCBQdWJsaWNLZXlUb2tlbj05ZDc3Y2M3YWQzOWI2OGViXV0sIG1zY29ybGliLCBWZXJzaW9uPTQuMC4wLjAsIEN1bHR1cmU9bmV1dHJhbCwgUHVibGljS2V5VG9rZW49Yjc3YTVjNTYxOTM0ZTA4OV1dAgAAAAhfbW9uaXRvchJDb2xsZWN0aW9uYDEraXRlbXMEA4YEU3lzdGVtLkNvbGxlY3Rpb25zLk9iamVjdE1vZGVsLk9ic2VydmFibGVDb2xsZWN0aW9uYDErU2ltcGxlTW9uaXRvcltbU3lzdGVtLlR1cGxlYDJbW1N5c3RlbS5JbnQzMiwgbXNjb3JsaWIsIFZlcnNpb249NC4wLjAuMCwgQ3VsdHVyZT1uZXV0cmFsLCBQdWJsaWNLZXlUb2tlbj1iNzdhNWM1NjE5MzRlMDg5XSxbU3lzdGVtLlJ1bnRpbWUuU2VyaWFsaXphdGlvbi5Gb3JtYXR0ZXJzLlRlc3RzLkdyYXBoYDFbW1N5c3RlbS5JbnQzMiwgbXNjb3JsaWIsIFZlcnNpb249NC4wLjAuMCwgQ3VsdHVyZT1uZXV0cmFsLCBQdWJsaWNLZXlUb2tlbj1iNzdhNWM1NjE5MzRlMDg5XV0sIFN5c3RlbS5SdW50aW1lLlNlcmlhbGl6YXRpb24uRm9ybWF0dGVycy5UZXN0cywgVmVyc2lvbj00LjAuMy4wLCBDdWx0dXJlPW5ldXRyYWwsIFB1YmxpY0tleVRva2VuPTlkNzdjYzdhZDM5YjY4ZWJdXSwgbXNjb3JsaWIsIFZlcnNpb249NC4wLjAuMCwgQ3VsdHVyZT1uZXV0cmFsLCBQdWJsaWNLZXlUb2tlbj1iNzdhNWM1NjE5MzRlMDg5XV0CAAAA5ANTeXN0ZW0uQ29sbGVjdGlvbnMuR2VuZXJpYy5MaXN0YDFbW1N5c3RlbS5UdXBsZWAyW1tTeXN0ZW0uSW50MzIsIG1zY29ybGliLCBWZXJzaW9uPTQuMC4wLjAsIEN1bHR1cmU9bmV1dHJhbCwgUHVibGljS2V5VG9rZW49Yjc3YTVjNTYxOTM0ZTA4OV0sW1N5c3RlbS5SdW50aW1lLlNlcmlhbGl6YXRpb24uRm9ybWF0dGVycy5UZXN0cy5HcmFwaGAxW1tTeXN0ZW0uSW50MzIsIG1zY29ybGliLCBWZXJzaW9uPTQuMC4wLjAsIEN1bHR1cmU9bmV1dHJhbCwgUHVibGljS2V5VG9rZW49Yjc3YTVjNTYxOTM0ZTA4OV1dLCBTeXN0ZW0uUnVudGltZS5TZXJpYWxpemF0aW9uLkZvcm1hdHRlcnMuVGVzdHMsIFZlcnNpb249NC4wLjMuMCwgQ3VsdHVyZT1uZXV0cmFsLCBQdWJsaWNLZXlUb2tlbj05ZDc3Y2M3YWQzOWI2OGViXV0sIG1zY29ybGliLCBWZXJzaW9uPTQuMC4wLjAsIEN1bHR1cmU9bmV1dHJhbCwgUHVibGljS2V5VG9rZW49Yjc3YTVjNTYxOTM0ZTA4OV1dAgAAAAkDAAAACQQAAAAFAwAAAIYEU3lzdGVtLkNvbGxlY3Rpb25zLk9iamVjdE1vZGVsLk9ic2VydmFibGVDb2xsZWN0aW9uYDErU2ltcGxlTW9uaXRvcltbU3lzdGVtLlR1cGxlYDJbW1N5c3RlbS5JbnQzMiwgbXNjb3JsaWIsIFZlcnNpb249NC4wLjAuMCwgQ3VsdHVyZT1uZXV0cmFsLCBQdWJsaWNLZXlUb2tlbj1iNzdhNWM1NjE5MzRlMDg5XSxbU3lzdGVtLlJ1bnRpbWUuU2VyaWFsaXphdGlvbi5Gb3JtYXR0ZXJzLlRlc3RzLkdyYXBoYDFbW1N5c3RlbS5JbnQzMiwgbXNjb3JsaWIsIFZlcnNpb249NC4wLjAuMCwgQ3VsdHVyZT1uZXV0cmFsLCBQdWJsaWNLZXlUb2tlbj1iNzdhNWM1NjE5MzRlMDg5XV0sIFN5c3RlbS5SdW50aW1lLlNlcmlhbGl6YXRpb24uRm9ybWF0dGVycy5UZXN0cywgVmVyc2lvbj00LjAuMy4wLCBDdWx0dXJlPW5ldXRyYWwsIFB1YmxpY0tleVRva2VuPTlkNzdjYzdhZDM5YjY4ZWJdXSwgbXNjb3JsaWIsIFZlcnNpb249NC4wLjAuMCwgQ3VsdHVyZT1uZXV0cmFsLCBQdWJsaWNLZXlUb2tlbj1iNzdhNWM1NjE5MzRlMDg5XV0BAAAACl9idXN5Q291bnQACAIAAAAAAAAABAQAAADkA1N5c3RlbS5Db2xsZWN0aW9ucy5HZW5lcmljLkxpc3RgMVtbU3lzdGVtLlR1cGxlYDJbW1N5c3RlbS5JbnQzMiwgbXNjb3JsaWIsIFZlcnNpb249NC4wLjAuMCwgQ3VsdHVyZT1uZXV0cmFsLCBQdWJsaWNLZXlUb2tlbj1iNzdhNWM1NjE5MzRlMDg5XSxbU3lzdGVtLlJ1bnRpbWUuU2VyaWFsaXphdGlvbi5Gb3JtYXR0ZXJzLlRlc3RzLkdyYXBoYDFbW1N5c3RlbS5JbnQzMiwgbXNjb3JsaWIsIFZlcnNpb249NC4wLjAuMCwgQ3VsdHVyZT1uZXV0cmFsLCBQdWJsaWNLZXlUb2tlbj1iNzdhNWM1NjE5MzRlMDg5XV0sIFN5c3RlbS5SdW50aW1lLlNlcmlhbGl6YXRpb24uRm9ybWF0dGVycy5UZXN0cywgVmVyc2lvbj00LjAuMy4wLCBDdWx0dXJlPW5ldXRyYWwsIFB1YmxpY0tleVRva2VuPTlkNzdjYzdhZDM5YjY4ZWJdXSwgbXNjb3JsaWIsIFZlcnNpb249NC4wLjAuMCwgQ3VsdHVyZT1uZXV0cmFsLCBQdWJsaWNLZXlUb2tlbj1iNzdhNWM1NjE5MzRlMDg5XV0DAAAABl9pdGVtcwVfc2l6ZQhfdmVyc2lvbgMAAPQCU3lzdGVtLlR1cGxlYDJbW1N5c3RlbS5JbnQzMiwgbXNjb3JsaWIsIFZlcnNpb249NC4wLjAuMCwgQ3VsdHVyZT1uZXV0cmFsLCBQdWJsaWNLZXlUb2tlbj1iNzdhNWM1NjE5MzRlMDg5XSxbU3lzdGVtLlJ1bnRpbWUuU2VyaWFsaXphdGlvbi5Gb3JtYXR0ZXJzLlRlc3RzLkdyYXBoYDFbW1N5c3RlbS5JbnQzMiwgbXNjb3JsaWIsIFZlcnNpb249NC4wLjAuMCwgQ3VsdHVyZT1uZXV0cmFsLCBQdWJsaWNLZXlUb2tlbj1iNzdhNWM1NjE5MzRlMDg5XV0sIFN5c3RlbS5SdW50aW1lLlNlcmlhbGl6YXRpb24uRm9ybWF0dGVycy5UZXN0cywgVmVyc2lvbj00LjAuMy4wLCBDdWx0dXJlPW5ldXRyYWwsIFB1YmxpY0tleVRva2VuPTlkNzdjYzdhZDM5YjY4ZWJdXVtdCAgJBQAAAAIAAAACAAAABwUAAAAAAQAAAAQAAAAD8gJTeXN0ZW0uVHVwbGVgMltbU3lzdGVtLkludDMyLCBtc2NvcmxpYiwgVmVyc2lvbj00LjAuMC4wLCBDdWx0dXJlPW5ldXRyYWwsIFB1YmxpY0tleVRva2VuPWI3N2E1YzU2MTkzNGUwODldLFtTeXN0ZW0uUnVudGltZS5TZXJpYWxpemF0aW9uLkZvcm1hdHRlcnMuVGVzdHMuR3JhcGhgMVtbU3lzdGVtLkludDMyLCBtc2NvcmxpYiwgVmVyc2lvbj00LjAuMC4wLCBDdWx0dXJlPW5ldXRyYWwsIFB1YmxpY0tleVRva2VuPWI3N2E1YzU2MTkzNGUwODldXSwgU3lzdGVtLlJ1bnRpbWUuU2VyaWFsaXphdGlvbi5Gb3JtYXR0ZXJzLlRlc3RzLCBWZXJzaW9uPTQuMC4zLjAsIEN1bHR1cmU9bmV1dHJhbCwgUHVibGljS2V5VG9rZW49OWQ3N2NjN2FkMzliNjhlYl1dCQYAAAAJBwAAAA0CDAgAAABwU3lzdGVtLlJ1bnRpbWUuU2VyaWFsaXphdGlvbi5Gb3JtYXR0ZXJzLlRlc3RzLCBWZXJzaW9uPTQuMC4zLjAsIEN1bHR1cmU9bmV1dHJhbCwgUHVibGljS2V5VG9rZW49OWQ3N2NjN2FkMzliNjhlYgQGAAAA8gJTeXN0ZW0uVHVwbGVgMltbU3lzdGVtLkludDMyLCBtc2NvcmxpYiwgVmVyc2lvbj00LjAuMC4wLCBDdWx0dXJlPW5ldXRyYWwsIFB1YmxpY0tleVRva2VuPWI3N2E1YzU2MTkzNGUwODldLFtTeXN0ZW0uUnVudGltZS5TZXJpYWxpemF0aW9uLkZvcm1hdHRlcnMuVGVzdHMuR3JhcGhgMVtbU3lzdGVtLkludDMyLCBtc2NvcmxpYiwgVmVyc2lvbj00LjAuMC4wLCBDdWx0dXJlPW5ldXRyYWwsIFB1YmxpY0tleVRva2VuPWI3N2E1YzU2MTkzNGUwODldXSwgU3lzdGVtLlJ1bnRpbWUuU2VyaWFsaXphdGlvbi5Gb3JtYXR0ZXJzLlRlc3RzLCBWZXJzaW9uPTQuMC4zLjAsIEN1bHR1cmU9bmV1dHJhbCwgUHVibGljS2V5VG9rZW49OWQ3N2NjN2FkMzliNjhlYl1dAgAAAAdtX0l0ZW0xB21fSXRlbTIABAiSAVN5c3RlbS5SdW50aW1lLlNlcmlhbGl6YXRpb24uRm9ybWF0dGVycy5UZXN0cy5HcmFwaGAxW1tTeXN0ZW0uSW50MzIsIG1zY29ybGliLCBWZXJzaW9uPTQuMC4wLjAsIEN1bHR1cmU9bmV1dHJhbCwgUHVibGljS2V5VG9rZW49Yjc3YTVjNTYxOTM0ZTA4OV1dCAAAAAEAAAAJCQAAAAEHAAAABgAAAAUAAAAJCgAAAAUJAAAAkgFTeXN0ZW0uUnVudGltZS5TZXJpYWxpemF0aW9uLkZvcm1hdHRlcnMuVGVzdHMuR3JhcGhgMVtbU3lzdGVtLkludDMyLCBtc2NvcmxpYiwgVmVyc2lvbj00LjAuMC4wLCBDdWx0dXJlPW5ldXRyYWwsIFB1YmxpY0tleVRva2VuPWI3N2E1YzU2MTkzNGUwODldXQIAAAAFVmFsdWUFTGlua3MABAiUAVN5c3RlbS5SdW50aW1lLlNlcmlhbGl6YXRpb24uRm9ybWF0dGVycy5UZXN0cy5HcmFwaGAxW1tTeXN0ZW0uSW50MzIsIG1zY29ybGliLCBWZXJzaW9uPTQuMC4wLjAsIEN1bHR1cmU9bmV1dHJhbCwgUHVibGljS2V5VG9rZW49Yjc3YTVjNTYxOTM0ZTA4OV1dW10IAAAACAAAAAAAAAAKAQoAAAAJAAAAAAAAAAoL" } };
+ yield return new object[] { new ObservableCollection<int>(), new string[] { "AAEAAAD/////AQAAAAAAAAAMAgAAAE5XaW5kb3dzQmFzZSwgVmVyc2lvbj0zLjAuMC4wLCBDdWx0dXJlPW5ldXRyYWwsIFB1YmxpY0tleVRva2VuPTMxYmYzODU2YWQzNjRlMzUFAQAAAJIBU3lzdGVtLkNvbGxlY3Rpb25zLk9iamVjdE1vZGVsLk9ic2VydmFibGVDb2xsZWN0aW9uYDFbW1N5c3RlbS5JbnQzMiwgbXNjb3JsaWIsIFZlcnNpb249NC4wLjAuMCwgQ3VsdHVyZT1uZXV0cmFsLCBQdWJsaWNLZXlUb2tlbj1iNzdhNWM1NjE5MzRlMDg5XV0CAAAACF9tb25pdG9yEkNvbGxlY3Rpb25gMStpdGVtcwQDoAFTeXN0ZW0uQ29sbGVjdGlvbnMuT2JqZWN0TW9kZWwuT2JzZXJ2YWJsZUNvbGxlY3Rpb25gMStTaW1wbGVNb25pdG9yW1tTeXN0ZW0uSW50MzIsIG1zY29ybGliLCBWZXJzaW9uPTQuMC4wLjAsIEN1bHR1cmU9bmV1dHJhbCwgUHVibGljS2V5VG9rZW49Yjc3YTVjNTYxOTM0ZTA4OV1dAgAAAH5TeXN0ZW0uQ29sbGVjdGlvbnMuR2VuZXJpYy5MaXN0YDFbW1N5c3RlbS5JbnQzMiwgbXNjb3JsaWIsIFZlcnNpb249NC4wLjAuMCwgQ3VsdHVyZT1uZXV0cmFsLCBQdWJsaWNLZXlUb2tlbj1iNzdhNWM1NjE5MzRlMDg5XV0CAAAACQMAAAAJBAAAAAUDAAAAoAFTeXN0ZW0uQ29sbGVjdGlvbnMuT2JqZWN0TW9kZWwuT2JzZXJ2YWJsZUNvbGxlY3Rpb25gMStTaW1wbGVNb25pdG9yW1tTeXN0ZW0uSW50MzIsIG1zY29ybGliLCBWZXJzaW9uPTQuMC4wLjAsIEN1bHR1cmU9bmV1dHJhbCwgUHVibGljS2V5VG9rZW49Yjc3YTVjNTYxOTM0ZTA4OV1dAQAAAApfYnVzeUNvdW50AAgCAAAAAAAAAAQEAAAAflN5c3RlbS5Db2xsZWN0aW9ucy5HZW5lcmljLkxpc3RgMVtbU3lzdGVtLkludDMyLCBtc2NvcmxpYiwgVmVyc2lvbj00LjAuMC4wLCBDdWx0dXJlPW5ldXRyYWwsIFB1YmxpY0tleVRva2VuPWI3N2E1YzU2MTkzNGUwODldXQMAAAAGX2l0ZW1zBV9zaXplCF92ZXJzaW9uBwAACAgICQUAAAAAAAAAAAAAAA8FAAAAAAAAAAgL", "AAEAAAD/////AQAAAAAAAAAMAgAAAE5XaW5kb3dzQmFzZSwgVmVyc2lvbj0zLjAuMC4wLCBDdWx0dXJlPU5ldXRyYWwsIFB1YmxpY0tleVRva2VuPTMxYmYzODU2YWQzNjRlMzUFAQAAAJIBU3lzdGVtLkNvbGxlY3Rpb25zLk9iamVjdE1vZGVsLk9ic2VydmFibGVDb2xsZWN0aW9uYDFbW1N5c3RlbS5JbnQzMiwgbXNjb3JsaWIsIFZlcnNpb249NC4wLjAuMCwgQ3VsdHVyZT1uZXV0cmFsLCBQdWJsaWNLZXlUb2tlbj1iNzdhNWM1NjE5MzRlMDg5XV0CAAAACF9tb25pdG9yEkNvbGxlY3Rpb25gMStpdGVtcwQDoAFTeXN0ZW0uQ29sbGVjdGlvbnMuT2JqZWN0TW9kZWwuT2JzZXJ2YWJsZUNvbGxlY3Rpb25gMStTaW1wbGVNb25pdG9yW1tTeXN0ZW0uSW50MzIsIG1zY29ybGliLCBWZXJzaW9uPTQuMC4wLjAsIEN1bHR1cmU9bmV1dHJhbCwgUHVibGljS2V5VG9rZW49Yjc3YTVjNTYxOTM0ZTA4OV1dAgAAAH5TeXN0ZW0uQ29sbGVjdGlvbnMuR2VuZXJpYy5MaXN0YDFbW1N5c3RlbS5JbnQzMiwgbXNjb3JsaWIsIFZlcnNpb249NC4wLjAuMCwgQ3VsdHVyZT1uZXV0cmFsLCBQdWJsaWNLZXlUb2tlbj1iNzdhNWM1NjE5MzRlMDg5XV0CAAAACQMAAAAJBAAAAAUDAAAAoAFTeXN0ZW0uQ29sbGVjdGlvbnMuT2JqZWN0TW9kZWwuT2JzZXJ2YWJsZUNvbGxlY3Rpb25gMStTaW1wbGVNb25pdG9yW1tTeXN0ZW0uSW50MzIsIG1zY29ybGliLCBWZXJzaW9uPTQuMC4wLjAsIEN1bHR1cmU9bmV1dHJhbCwgUHVibGljS2V5VG9rZW49Yjc3YTVjNTYxOTM0ZTA4OV1dAQAAAApfYnVzeUNvdW50AAgCAAAAAAAAAAQEAAAAflN5c3RlbS5Db2xsZWN0aW9ucy5HZW5lcmljLkxpc3RgMVtbU3lzdGVtLkludDMyLCBtc2NvcmxpYiwgVmVyc2lvbj00LjAuMC4wLCBDdWx0dXJlPW5ldXRyYWwsIFB1YmxpY0tleVRva2VuPWI3N2E1YzU2MTkzNGUwODldXQMAAAAGX2l0ZW1zBV9zaXplCF92ZXJzaW9uBwAACAgICQUAAAAAAAAAAAAAAA8FAAAAAAAAAAgL" } };
+ yield return new object[] { new ObservableCollection<int>(Enumerable.Range(0, 123)), new string[] { "AAEAAAD/////AQAAAAAAAAAMAgAAAE5XaW5kb3dzQmFzZSwgVmVyc2lvbj0zLjAuMC4wLCBDdWx0dXJlPW5ldXRyYWwsIFB1YmxpY0tleVRva2VuPTMxYmYzODU2YWQzNjRlMzUFAQAAAJIBU3lzdGVtLkNvbGxlY3Rpb25zLk9iamVjdE1vZGVsLk9ic2VydmFibGVDb2xsZWN0aW9uYDFbW1N5c3RlbS5JbnQzMiwgbXNjb3JsaWIsIFZlcnNpb249NC4wLjAuMCwgQ3VsdHVyZT1uZXV0cmFsLCBQdWJsaWNLZXlUb2tlbj1iNzdhNWM1NjE5MzRlMDg5XV0CAAAACF9tb25pdG9yEkNvbGxlY3Rpb25gMStpdGVtcwQDoAFTeXN0ZW0uQ29sbGVjdGlvbnMuT2JqZWN0TW9kZWwuT2JzZXJ2YWJsZUNvbGxlY3Rpb25gMStTaW1wbGVNb25pdG9yW1tTeXN0ZW0uSW50MzIsIG1zY29ybGliLCBWZXJzaW9uPTQuMC4wLjAsIEN1bHR1cmU9bmV1dHJhbCwgUHVibGljS2V5VG9rZW49Yjc3YTVjNTYxOTM0ZTA4OV1dAgAAAH5TeXN0ZW0uQ29sbGVjdGlvbnMuR2VuZXJpYy5MaXN0YDFbW1N5c3RlbS5JbnQzMiwgbXNjb3JsaWIsIFZlcnNpb249NC4wLjAuMCwgQ3VsdHVyZT1uZXV0cmFsLCBQdWJsaWNLZXlUb2tlbj1iNzdhNWM1NjE5MzRlMDg5XV0CAAAACQMAAAAJBAAAAAUDAAAAoAFTeXN0ZW0uQ29sbGVjdGlvbnMuT2JqZWN0TW9kZWwuT2JzZXJ2YWJsZUNvbGxlY3Rpb25gMStTaW1wbGVNb25pdG9yW1tTeXN0ZW0uSW50MzIsIG1zY29ybGliLCBWZXJzaW9uPTQuMC4wLjAsIEN1bHR1cmU9bmV1dHJhbCwgUHVibGljS2V5VG9rZW49Yjc3YTVjNTYxOTM0ZTA4OV1dAQAAAApfYnVzeUNvdW50AAgCAAAAAAAAAAQEAAAAflN5c3RlbS5Db2xsZWN0aW9ucy5HZW5lcmljLkxpc3RgMVtbU3lzdGVtLkludDMyLCBtc2NvcmxpYiwgVmVyc2lvbj00LjAuMC4wLCBDdWx0dXJlPW5ldXRyYWwsIFB1YmxpY0tleVRva2VuPWI3N2E1YzU2MTkzNGUwODldXQMAAAAGX2l0ZW1zBV9zaXplCF92ZXJzaW9uBwAACAgICQUAAAB7AAAAAQAAAA8FAAAAgAAAAAgAAAAAAQAAAAIAAAADAAAABAAAAAUAAAAGAAAABwAAAAgAAAAJAAAACgAAAAsAAAAMAAAADQAAAA4AAAAPAAAAEAAAABEAAAASAAAAEwAAABQAAAAVAAAAFgAAABcAAAAYAAAAGQAAABoAAAAbAAAAHAAAAB0AAAAeAAAAHwAAACAAAAAhAAAAIgAAACMAAAAkAAAAJQAAACYAAAAnAAAAKAAAACkAAAAqAAAAKwAAACwAAAAtAAAALgAAAC8AAAAwAAAAMQAAADIAAAAzAAAANAAAADUAAAA2AAAANwAAADgAAAA5AAAAOgAAADsAAAA8AAAAPQAAAD4AAAA/AAAAQAAAAEEAAABCAAAAQwAAAEQAAABFAAAARgAAAEcAAABIAAAASQAAAEoAAABLAAAATAAAAE0AAABOAAAATwAAAFAAAABRAAAAUgAAAFMAAABUAAAAVQAAAFYAAABXAAAAWAAAAFkAAABaAAAAWwAAAFwAAABdAAAAXgAAAF8AAABgAAAAYQAAAGIAAABjAAAAZAAAAGUAAABmAAAAZwAAAGgAAABpAAAAagAAAGsAAABsAAAAbQAAAG4AAABvAAAAcAAAAHEAAAByAAAAcwAAAHQAAAB1AAAAdgAAAHcAAAB4AAAAeQAAAHoAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAs=", "AAEAAAD/////AQAAAAAAAAAMAgAAAE5XaW5kb3dzQmFzZSwgVmVyc2lvbj0zLjAuMC4wLCBDdWx0dXJlPU5ldXRyYWwsIFB1YmxpY0tleVRva2VuPTMxYmYzODU2YWQzNjRlMzUFAQAAAJIBU3lzdGVtLkNvbGxlY3Rpb25zLk9iamVjdE1vZGVsLk9ic2VydmFibGVDb2xsZWN0aW9uYDFbW1N5c3RlbS5JbnQzMiwgbXNjb3JsaWIsIFZlcnNpb249NC4wLjAuMCwgQ3VsdHVyZT1uZXV0cmFsLCBQdWJsaWNLZXlUb2tlbj1iNzdhNWM1NjE5MzRlMDg5XV0CAAAACF9tb25pdG9yEkNvbGxlY3Rpb25gMStpdGVtcwQDoAFTeXN0ZW0uQ29sbGVjdGlvbnMuT2JqZWN0TW9kZWwuT2JzZXJ2YWJsZUNvbGxlY3Rpb25gMStTaW1wbGVNb25pdG9yW1tTeXN0ZW0uSW50MzIsIG1zY29ybGliLCBWZXJzaW9uPTQuMC4wLjAsIEN1bHR1cmU9bmV1dHJhbCwgUHVibGljS2V5VG9rZW49Yjc3YTVjNTYxOTM0ZTA4OV1dAgAAAH5TeXN0ZW0uQ29sbGVjdGlvbnMuR2VuZXJpYy5MaXN0YDFbW1N5c3RlbS5JbnQzMiwgbXNjb3JsaWIsIFZlcnNpb249NC4wLjAuMCwgQ3VsdHVyZT1uZXV0cmFsLCBQdWJsaWNLZXlUb2tlbj1iNzdhNWM1NjE5MzRlMDg5XV0CAAAACQMAAAAJBAAAAAUDAAAAoAFTeXN0ZW0uQ29sbGVjdGlvbnMuT2JqZWN0TW9kZWwuT2JzZXJ2YWJsZUNvbGxlY3Rpb25gMStTaW1wbGVNb25pdG9yW1tTeXN0ZW0uSW50MzIsIG1zY29ybGliLCBWZXJzaW9uPTQuMC4wLjAsIEN1bHR1cmU9bmV1dHJhbCwgUHVibGljS2V5VG9rZW49Yjc3YTVjNTYxOTM0ZTA4OV1dAQAAAApfYnVzeUNvdW50AAgCAAAAAAAAAAQEAAAAflN5c3RlbS5Db2xsZWN0aW9ucy5HZW5lcmljLkxpc3RgMVtbU3lzdGVtLkludDMyLCBtc2NvcmxpYiwgVmVyc2lvbj00LjAuMC4wLCBDdWx0dXJlPW5ldXRyYWwsIFB1YmxpY0tleVRva2VuPWI3N2E1YzU2MTkzNGUwODldXQMAAAAGX2l0ZW1zBV9zaXplCF92ZXJzaW9uBwAACAgICQUAAAB7AAAAewAAAA8FAAAAgAAAAAgAAAAAAQAAAAIAAAADAAAABAAAAAUAAAAGAAAABwAAAAgAAAAJAAAACgAAAAsAAAAMAAAADQAAAA4AAAAPAAAAEAAAABEAAAASAAAAEwAAABQAAAAVAAAAFgAAABcAAAAYAAAAGQAAABoAAAAbAAAAHAAAAB0AAAAeAAAAHwAAACAAAAAhAAAAIgAAACMAAAAkAAAAJQAAACYAAAAnAAAAKAAAACkAAAAqAAAAKwAAACwAAAAtAAAALgAAAC8AAAAwAAAAMQAAADIAAAAzAAAANAAAADUAAAA2AAAANwAAADgAAAA5AAAAOgAAADsAAAA8AAAAPQAAAD4AAAA/AAAAQAAAAEEAAABCAAAAQwAAAEQAAABFAAAARgAAAEcAAABIAAAASQAAAEoAAABLAAAATAAAAE0AAABOAAAATwAAAFAAAABRAAAAUgAAAFMAAABUAAAAVQAAAFYAAABXAAAAWAAAAFkAAABaAAAAWwAAAFwAAABdAAAAXgAAAF8AAABgAAAAYQAAAGIAAABjAAAAZAAAAGUAAABmAAAAZwAAAGgAAABpAAAAagAAAGsAAABsAAAAbQAAAG4AAABvAAAAcAAAAHEAAAByAAAAcwAAAHQAAAB1AAAAdgAAAHcAAAB4AAAAeQAAAHoAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAs=" } };
+ yield return new object[] { new ObservableCollection<int>(new int[] { 5, 7, 9 }), new string[] { "AAEAAAD/////AQAAAAAAAAAMAgAAAE5XaW5kb3dzQmFzZSwgVmVyc2lvbj0zLjAuMC4wLCBDdWx0dXJlPW5ldXRyYWwsIFB1YmxpY0tleVRva2VuPTMxYmYzODU2YWQzNjRlMzUFAQAAAJIBU3lzdGVtLkNvbGxlY3Rpb25zLk9iamVjdE1vZGVsLk9ic2VydmFibGVDb2xsZWN0aW9uYDFbW1N5c3RlbS5JbnQzMiwgbXNjb3JsaWIsIFZlcnNpb249NC4wLjAuMCwgQ3VsdHVyZT1uZXV0cmFsLCBQdWJsaWNLZXlUb2tlbj1iNzdhNWM1NjE5MzRlMDg5XV0CAAAACF9tb25pdG9yEkNvbGxlY3Rpb25gMStpdGVtcwQDoAFTeXN0ZW0uQ29sbGVjdGlvbnMuT2JqZWN0TW9kZWwuT2JzZXJ2YWJsZUNvbGxlY3Rpb25gMStTaW1wbGVNb25pdG9yW1tTeXN0ZW0uSW50MzIsIG1zY29ybGliLCBWZXJzaW9uPTQuMC4wLjAsIEN1bHR1cmU9bmV1dHJhbCwgUHVibGljS2V5VG9rZW49Yjc3YTVjNTYxOTM0ZTA4OV1dAgAAAH5TeXN0ZW0uQ29sbGVjdGlvbnMuR2VuZXJpYy5MaXN0YDFbW1N5c3RlbS5JbnQzMiwgbXNjb3JsaWIsIFZlcnNpb249NC4wLjAuMCwgQ3VsdHVyZT1uZXV0cmFsLCBQdWJsaWNLZXlUb2tlbj1iNzdhNWM1NjE5MzRlMDg5XV0CAAAACQMAAAAJBAAAAAUDAAAAoAFTeXN0ZW0uQ29sbGVjdGlvbnMuT2JqZWN0TW9kZWwuT2JzZXJ2YWJsZUNvbGxlY3Rpb25gMStTaW1wbGVNb25pdG9yW1tTeXN0ZW0uSW50MzIsIG1zY29ybGliLCBWZXJzaW9uPTQuMC4wLjAsIEN1bHR1cmU9bmV1dHJhbCwgUHVibGljS2V5VG9rZW49Yjc3YTVjNTYxOTM0ZTA4OV1dAQAAAApfYnVzeUNvdW50AAgCAAAAAAAAAAQEAAAAflN5c3RlbS5Db2xsZWN0aW9ucy5HZW5lcmljLkxpc3RgMVtbU3lzdGVtLkludDMyLCBtc2NvcmxpYiwgVmVyc2lvbj00LjAuMC4wLCBDdWx0dXJlPW5ldXRyYWwsIFB1YmxpY0tleVRva2VuPWI3N2E1YzU2MTkzNGUwODldXQMAAAAGX2l0ZW1zBV9zaXplCF92ZXJzaW9uBwAACAgICQUAAAADAAAAAAAAAA8FAAAAAwAAAAgFAAAABwAAAAkAAAAL", "AAEAAAD/////AQAAAAAAAAAMAgAAAE5XaW5kb3dzQmFzZSwgVmVyc2lvbj0zLjAuMC4wLCBDdWx0dXJlPU5ldXRyYWwsIFB1YmxpY0tleVRva2VuPTMxYmYzODU2YWQzNjRlMzUFAQAAAJIBU3lzdGVtLkNvbGxlY3Rpb25zLk9iamVjdE1vZGVsLk9ic2VydmFibGVDb2xsZWN0aW9uYDFbW1N5c3RlbS5JbnQzMiwgbXNjb3JsaWIsIFZlcnNpb249NC4wLjAuMCwgQ3VsdHVyZT1uZXV0cmFsLCBQdWJsaWNLZXlUb2tlbj1iNzdhNWM1NjE5MzRlMDg5XV0CAAAACF9tb25pdG9yEkNvbGxlY3Rpb25gMStpdGVtcwQDoAFTeXN0ZW0uQ29sbGVjdGlvbnMuT2JqZWN0TW9kZWwuT2JzZXJ2YWJsZUNvbGxlY3Rpb25gMStTaW1wbGVNb25pdG9yW1tTeXN0ZW0uSW50MzIsIG1zY29ybGliLCBWZXJzaW9uPTQuMC4wLjAsIEN1bHR1cmU9bmV1dHJhbCwgUHVibGljS2V5VG9rZW49Yjc3YTVjNTYxOTM0ZTA4OV1dAgAAAH5TeXN0ZW0uQ29sbGVjdGlvbnMuR2VuZXJpYy5MaXN0YDFbW1N5c3RlbS5JbnQzMiwgbXNjb3JsaWIsIFZlcnNpb249NC4wLjAuMCwgQ3VsdHVyZT1uZXV0cmFsLCBQdWJsaWNLZXlUb2tlbj1iNzdhNWM1NjE5MzRlMDg5XV0CAAAACQMAAAAJBAAAAAUDAAAAoAFTeXN0ZW0uQ29sbGVjdGlvbnMuT2JqZWN0TW9kZWwuT2JzZXJ2YWJsZUNvbGxlY3Rpb25gMStTaW1wbGVNb25pdG9yW1tTeXN0ZW0uSW50MzIsIG1zY29ybGliLCBWZXJzaW9uPTQuMC4wLjAsIEN1bHR1cmU9bmV1dHJhbCwgUHVibGljS2V5VG9rZW49Yjc3YTVjNTYxOTM0ZTA4OV1dAQAAAApfYnVzeUNvdW50AAgCAAAAAAAAAAQEAAAAflN5c3RlbS5Db2xsZWN0aW9ucy5HZW5lcmljLkxpc3RgMVtbU3lzdGVtLkludDMyLCBtc2NvcmxpYiwgVmVyc2lvbj00LjAuMC4wLCBDdWx0dXJlPW5ldXRyYWwsIFB1YmxpY0tleVRva2VuPWI3N2E1YzU2MTkzNGUwODldXQMAAAAGX2l0ZW1zBV9zaXplCF92ZXJzaW9uBwAACAgICQUAAAADAAAAAwAAAA8FAAAABAAAAAgFAAAABwAAAAkAAAAAAAAACw==" } };
+ yield return new object[] { new ObservableCollection<Point>(), new string[] { "AAEAAAD/////AQAAAAAAAAAMAgAAAE5XaW5kb3dzQmFzZSwgVmVyc2lvbj0zLjAuMC4wLCBDdWx0dXJlPW5ldXRyYWwsIFB1YmxpY0tleVRva2VuPTMxYmYzODU2YWQzNjRlMzUFAQAAAN4BU3lzdGVtLkNvbGxlY3Rpb25zLk9iamVjdE1vZGVsLk9ic2VydmFibGVDb2xsZWN0aW9uYDFbW1N5c3RlbS5SdW50aW1lLlNlcmlhbGl6YXRpb24uRm9ybWF0dGVycy5UZXN0cy5Qb2ludCwgU3lzdGVtLlJ1bnRpbWUuU2VyaWFsaXphdGlvbi5Gb3JtYXR0ZXJzLlRlc3RzLCBWZXJzaW9uPTQuMC4zLjAsIEN1bHR1cmU9bmV1dHJhbCwgUHVibGljS2V5VG9rZW49OWQ3N2NjN2FkMzliNjhlYl1dAgAAAAhfbW9uaXRvchJDb2xsZWN0aW9uYDEraXRlbXMEA+wBU3lzdGVtLkNvbGxlY3Rpb25zLk9iamVjdE1vZGVsLk9ic2VydmFibGVDb2xsZWN0aW9uYDErU2ltcGxlTW9uaXRvcltbU3lzdGVtLlJ1bnRpbWUuU2VyaWFsaXphdGlvbi5Gb3JtYXR0ZXJzLlRlc3RzLlBvaW50LCBTeXN0ZW0uUnVudGltZS5TZXJpYWxpemF0aW9uLkZvcm1hdHRlcnMuVGVzdHMsIFZlcnNpb249NC4wLjMuMCwgQ3VsdHVyZT1uZXV0cmFsLCBQdWJsaWNLZXlUb2tlbj05ZDc3Y2M3YWQzOWI2OGViXV0CAAAAygFTeXN0ZW0uQ29sbGVjdGlvbnMuR2VuZXJpYy5MaXN0YDFbW1N5c3RlbS5SdW50aW1lLlNlcmlhbGl6YXRpb24uRm9ybWF0dGVycy5UZXN0cy5Qb2ludCwgU3lzdGVtLlJ1bnRpbWUuU2VyaWFsaXphdGlvbi5Gb3JtYXR0ZXJzLlRlc3RzLCBWZXJzaW9uPTQuMC4zLjAsIEN1bHR1cmU9bmV1dHJhbCwgUHVibGljS2V5VG9rZW49OWQ3N2NjN2FkMzliNjhlYl1dAgAAAAkDAAAACQQAAAAFAwAAAOwBU3lzdGVtLkNvbGxlY3Rpb25zLk9iamVjdE1vZGVsLk9ic2VydmFibGVDb2xsZWN0aW9uYDErU2ltcGxlTW9uaXRvcltbU3lzdGVtLlJ1bnRpbWUuU2VyaWFsaXphdGlvbi5Gb3JtYXR0ZXJzLlRlc3RzLlBvaW50LCBTeXN0ZW0uUnVudGltZS5TZXJpYWxpemF0aW9uLkZvcm1hdHRlcnMuVGVzdHMsIFZlcnNpb249NC4wLjMuMCwgQ3VsdHVyZT1uZXV0cmFsLCBQdWJsaWNLZXlUb2tlbj05ZDc3Y2M3YWQzOWI2OGViXV0BAAAACl9idXN5Q291bnQACAIAAAAAAAAADAUAAABwU3lzdGVtLlJ1bnRpbWUuU2VyaWFsaXphdGlvbi5Gb3JtYXR0ZXJzLlRlc3RzLCBWZXJzaW9uPTQuMC4zLjAsIEN1bHR1cmU9bmV1dHJhbCwgUHVibGljS2V5VG9rZW49OWQ3N2NjN2FkMzliNjhlYgQEAAAAygFTeXN0ZW0uQ29sbGVjdGlvbnMuR2VuZXJpYy5MaXN0YDFbW1N5c3RlbS5SdW50aW1lLlNlcmlhbGl6YXRpb24uRm9ybWF0dGVycy5UZXN0cy5Qb2ludCwgU3lzdGVtLlJ1bnRpbWUuU2VyaWFsaXphdGlvbi5Gb3JtYXR0ZXJzLlRlc3RzLCBWZXJzaW9uPTQuMC4zLjAsIEN1bHR1cmU9bmV1dHJhbCwgUHVibGljS2V5VG9rZW49OWQ3N2NjN2FkMzliNjhlYl1dAwAAAAZfaXRlbXMFX3NpemUIX3ZlcnNpb24EAAA1U3lzdGVtLlJ1bnRpbWUuU2VyaWFsaXphdGlvbi5Gb3JtYXR0ZXJzLlRlc3RzLlBvaW50W10FAAAACAgJBgAAAAAAAAAAAAAABwYAAAAAAQAAAAAAAAAEM1N5c3RlbS5SdW50aW1lLlNlcmlhbGl6YXRpb24uRm9ybWF0dGVycy5UZXN0cy5Qb2ludAUAAAAL", "AAEAAAD/////AQAAAAAAAAAMAgAAAE5XaW5kb3dzQmFzZSwgVmVyc2lvbj0zLjAuMC4wLCBDdWx0dXJlPU5ldXRyYWwsIFB1YmxpY0tleVRva2VuPTMxYmYzODU2YWQzNjRlMzUFAQAAAN4BU3lzdGVtLkNvbGxlY3Rpb25zLk9iamVjdE1vZGVsLk9ic2VydmFibGVDb2xsZWN0aW9uYDFbW1N5c3RlbS5SdW50aW1lLlNlcmlhbGl6YXRpb24uRm9ybWF0dGVycy5UZXN0cy5Qb2ludCwgU3lzdGVtLlJ1bnRpbWUuU2VyaWFsaXphdGlvbi5Gb3JtYXR0ZXJzLlRlc3RzLCBWZXJzaW9uPTQuMC4zLjAsIEN1bHR1cmU9bmV1dHJhbCwgUHVibGljS2V5VG9rZW49OWQ3N2NjN2FkMzliNjhlYl1dAgAAAAhfbW9uaXRvchJDb2xsZWN0aW9uYDEraXRlbXMEA+wBU3lzdGVtLkNvbGxlY3Rpb25zLk9iamVjdE1vZGVsLk9ic2VydmFibGVDb2xsZWN0aW9uYDErU2ltcGxlTW9uaXRvcltbU3lzdGVtLlJ1bnRpbWUuU2VyaWFsaXphdGlvbi5Gb3JtYXR0ZXJzLlRlc3RzLlBvaW50LCBTeXN0ZW0uUnVudGltZS5TZXJpYWxpemF0aW9uLkZvcm1hdHRlcnMuVGVzdHMsIFZlcnNpb249NC4wLjMuMCwgQ3VsdHVyZT1uZXV0cmFsLCBQdWJsaWNLZXlUb2tlbj05ZDc3Y2M3YWQzOWI2OGViXV0CAAAAygFTeXN0ZW0uQ29sbGVjdGlvbnMuR2VuZXJpYy5MaXN0YDFbW1N5c3RlbS5SdW50aW1lLlNlcmlhbGl6YXRpb24uRm9ybWF0dGVycy5UZXN0cy5Qb2ludCwgU3lzdGVtLlJ1bnRpbWUuU2VyaWFsaXphdGlvbi5Gb3JtYXR0ZXJzLlRlc3RzLCBWZXJzaW9uPTQuMC4zLjAsIEN1bHR1cmU9bmV1dHJhbCwgUHVibGljS2V5VG9rZW49OWQ3N2NjN2FkMzliNjhlYl1dAgAAAAkDAAAACQQAAAAFAwAAAOwBU3lzdGVtLkNvbGxlY3Rpb25zLk9iamVjdE1vZGVsLk9ic2VydmFibGVDb2xsZWN0aW9uYDErU2ltcGxlTW9uaXRvcltbU3lzdGVtLlJ1bnRpbWUuU2VyaWFsaXphdGlvbi5Gb3JtYXR0ZXJzLlRlc3RzLlBvaW50LCBTeXN0ZW0uUnVudGltZS5TZXJpYWxpemF0aW9uLkZvcm1hdHRlcnMuVGVzdHMsIFZlcnNpb249NC4wLjMuMCwgQ3VsdHVyZT1uZXV0cmFsLCBQdWJsaWNLZXlUb2tlbj05ZDc3Y2M3YWQzOWI2OGViXV0BAAAACl9idXN5Q291bnQACAIAAAAAAAAADAUAAABwU3lzdGVtLlJ1bnRpbWUuU2VyaWFsaXphdGlvbi5Gb3JtYXR0ZXJzLlRlc3RzLCBWZXJzaW9uPTQuMC4zLjAsIEN1bHR1cmU9bmV1dHJhbCwgUHVibGljS2V5VG9rZW49OWQ3N2NjN2FkMzliNjhlYgQEAAAAygFTeXN0ZW0uQ29sbGVjdGlvbnMuR2VuZXJpYy5MaXN0YDFbW1N5c3RlbS5SdW50aW1lLlNlcmlhbGl6YXRpb24uRm9ybWF0dGVycy5UZXN0cy5Qb2ludCwgU3lzdGVtLlJ1bnRpbWUuU2VyaWFsaXphdGlvbi5Gb3JtYXR0ZXJzLlRlc3RzLCBWZXJzaW9uPTQuMC4zLjAsIEN1bHR1cmU9bmV1dHJhbCwgUHVibGljS2V5VG9rZW49OWQ3N2NjN2FkMzliNjhlYl1dAwAAAAZfaXRlbXMFX3NpemUIX3ZlcnNpb24EAAA1U3lzdGVtLlJ1bnRpbWUuU2VyaWFsaXphdGlvbi5Gb3JtYXR0ZXJzLlRlc3RzLlBvaW50W10FAAAACAgJBgAAAAAAAAAAAAAABwYAAAAAAQAAAAAAAAAEM1N5c3RlbS5SdW50aW1lLlNlcmlhbGl6YXRpb24uRm9ybWF0dGVycy5UZXN0cy5Qb2ludAUAAAAL" } };
+ yield return new object[] { new ObservableCollection<Point>(new Point[] { new Point(1, 2), new Point(4, 3) }), new string[] { "AAEAAAD/////AQAAAAAAAAAMAgAAAE5XaW5kb3dzQmFzZSwgVmVyc2lvbj0zLjAuMC4wLCBDdWx0dXJlPW5ldXRyYWwsIFB1YmxpY0tleVRva2VuPTMxYmYzODU2YWQzNjRlMzUFAQAAAN4BU3lzdGVtLkNvbGxlY3Rpb25zLk9iamVjdE1vZGVsLk9ic2VydmFibGVDb2xsZWN0aW9uYDFbW1N5c3RlbS5SdW50aW1lLlNlcmlhbGl6YXRpb24uRm9ybWF0dGVycy5UZXN0cy5Qb2ludCwgU3lzdGVtLlJ1bnRpbWUuU2VyaWFsaXphdGlvbi5Gb3JtYXR0ZXJzLlRlc3RzLCBWZXJzaW9uPTQuMC4zLjAsIEN1bHR1cmU9bmV1dHJhbCwgUHVibGljS2V5VG9rZW49OWQ3N2NjN2FkMzliNjhlYl1dAgAAAAhfbW9uaXRvchJDb2xsZWN0aW9uYDEraXRlbXMEA+wBU3lzdGVtLkNvbGxlY3Rpb25zLk9iamVjdE1vZGVsLk9ic2VydmFibGVDb2xsZWN0aW9uYDErU2ltcGxlTW9uaXRvcltbU3lzdGVtLlJ1bnRpbWUuU2VyaWFsaXphdGlvbi5Gb3JtYXR0ZXJzLlRlc3RzLlBvaW50LCBTeXN0ZW0uUnVudGltZS5TZXJpYWxpemF0aW9uLkZvcm1hdHRlcnMuVGVzdHMsIFZlcnNpb249NC4wLjMuMCwgQ3VsdHVyZT1uZXV0cmFsLCBQdWJsaWNLZXlUb2tlbj05ZDc3Y2M3YWQzOWI2OGViXV0CAAAAygFTeXN0ZW0uQ29sbGVjdGlvbnMuR2VuZXJpYy5MaXN0YDFbW1N5c3RlbS5SdW50aW1lLlNlcmlhbGl6YXRpb24uRm9ybWF0dGVycy5UZXN0cy5Qb2ludCwgU3lzdGVtLlJ1bnRpbWUuU2VyaWFsaXphdGlvbi5Gb3JtYXR0ZXJzLlRlc3RzLCBWZXJzaW9uPTQuMC4zLjAsIEN1bHR1cmU9bmV1dHJhbCwgUHVibGljS2V5VG9rZW49OWQ3N2NjN2FkMzliNjhlYl1dAgAAAAkDAAAACQQAAAAFAwAAAOwBU3lzdGVtLkNvbGxlY3Rpb25zLk9iamVjdE1vZGVsLk9ic2VydmFibGVDb2xsZWN0aW9uYDErU2ltcGxlTW9uaXRvcltbU3lzdGVtLlJ1bnRpbWUuU2VyaWFsaXphdGlvbi5Gb3JtYXR0ZXJzLlRlc3RzLlBvaW50LCBTeXN0ZW0uUnVudGltZS5TZXJpYWxpemF0aW9uLkZvcm1hdHRlcnMuVGVzdHMsIFZlcnNpb249NC4wLjMuMCwgQ3VsdHVyZT1uZXV0cmFsLCBQdWJsaWNLZXlUb2tlbj05ZDc3Y2M3YWQzOWI2OGViXV0BAAAACl9idXN5Q291bnQACAIAAAAAAAAADAUAAABwU3lzdGVtLlJ1bnRpbWUuU2VyaWFsaXphdGlvbi5Gb3JtYXR0ZXJzLlRlc3RzLCBWZXJzaW9uPTQuMC4zLjAsIEN1bHR1cmU9bmV1dHJhbCwgUHVibGljS2V5VG9rZW49OWQ3N2NjN2FkMzliNjhlYgQEAAAAygFTeXN0ZW0uQ29sbGVjdGlvbnMuR2VuZXJpYy5MaXN0YDFbW1N5c3RlbS5SdW50aW1lLlNlcmlhbGl6YXRpb24uRm9ybWF0dGVycy5UZXN0cy5Qb2ludCwgU3lzdGVtLlJ1bnRpbWUuU2VyaWFsaXphdGlvbi5Gb3JtYXR0ZXJzLlRlc3RzLCBWZXJzaW9uPTQuMC4zLjAsIEN1bHR1cmU9bmV1dHJhbCwgUHVibGljS2V5VG9rZW49OWQ3N2NjN2FkMzliNjhlYl1dAwAAAAZfaXRlbXMFX3NpemUIX3ZlcnNpb24EAAA1U3lzdGVtLlJ1bnRpbWUuU2VyaWFsaXphdGlvbi5Gb3JtYXR0ZXJzLlRlc3RzLlBvaW50W10FAAAACAgJBgAAAAIAAAAAAAAABwYAAAAAAQAAAAIAAAAEM1N5c3RlbS5SdW50aW1lLlNlcmlhbGl6YXRpb24uRm9ybWF0dGVycy5UZXN0cy5Qb2ludAUAAAAJBwAAAAkIAAAABQcAAAAzU3lzdGVtLlJ1bnRpbWUuU2VyaWFsaXphdGlvbi5Gb3JtYXR0ZXJzLlRlc3RzLlBvaW50AgAAAAFYAVkAAAgIBQAAAAEAAAACAAAAAQgAAAAHAAAABAAAAAMAAAAL", "AAEAAAD/////AQAAAAAAAAAMAgAAAE5XaW5kb3dzQmFzZSwgVmVyc2lvbj0zLjAuMC4wLCBDdWx0dXJlPU5ldXRyYWwsIFB1YmxpY0tleVRva2VuPTMxYmYzODU2YWQzNjRlMzUFAQAAAN4BU3lzdGVtLkNvbGxlY3Rpb25zLk9iamVjdE1vZGVsLk9ic2VydmFibGVDb2xsZWN0aW9uYDFbW1N5c3RlbS5SdW50aW1lLlNlcmlhbGl6YXRpb24uRm9ybWF0dGVycy5UZXN0cy5Qb2ludCwgU3lzdGVtLlJ1bnRpbWUuU2VyaWFsaXphdGlvbi5Gb3JtYXR0ZXJzLlRlc3RzLCBWZXJzaW9uPTQuMC4zLjAsIEN1bHR1cmU9bmV1dHJhbCwgUHVibGljS2V5VG9rZW49OWQ3N2NjN2FkMzliNjhlYl1dAgAAAAhfbW9uaXRvchJDb2xsZWN0aW9uYDEraXRlbXMEA+wBU3lzdGVtLkNvbGxlY3Rpb25zLk9iamVjdE1vZGVsLk9ic2VydmFibGVDb2xsZWN0aW9uYDErU2ltcGxlTW9uaXRvcltbU3lzdGVtLlJ1bnRpbWUuU2VyaWFsaXphdGlvbi5Gb3JtYXR0ZXJzLlRlc3RzLlBvaW50LCBTeXN0ZW0uUnVudGltZS5TZXJpYWxpemF0aW9uLkZvcm1hdHRlcnMuVGVzdHMsIFZlcnNpb249NC4wLjMuMCwgQ3VsdHVyZT1uZXV0cmFsLCBQdWJsaWNLZXlUb2tlbj05ZDc3Y2M3YWQzOWI2OGViXV0CAAAAygFTeXN0ZW0uQ29sbGVjdGlvbnMuR2VuZXJpYy5MaXN0YDFbW1N5c3RlbS5SdW50aW1lLlNlcmlhbGl6YXRpb24uRm9ybWF0dGVycy5UZXN0cy5Qb2ludCwgU3lzdGVtLlJ1bnRpbWUuU2VyaWFsaXphdGlvbi5Gb3JtYXR0ZXJzLlRlc3RzLCBWZXJzaW9uPTQuMC4zLjAsIEN1bHR1cmU9bmV1dHJhbCwgUHVibGljS2V5VG9rZW49OWQ3N2NjN2FkMzliNjhlYl1dAgAAAAkDAAAACQQAAAAFAwAAAOwBU3lzdGVtLkNvbGxlY3Rpb25zLk9iamVjdE1vZGVsLk9ic2VydmFibGVDb2xsZWN0aW9uYDErU2ltcGxlTW9uaXRvcltbU3lzdGVtLlJ1bnRpbWUuU2VyaWFsaXphdGlvbi5Gb3JtYXR0ZXJzLlRlc3RzLlBvaW50LCBTeXN0ZW0uUnVudGltZS5TZXJpYWxpemF0aW9uLkZvcm1hdHRlcnMuVGVzdHMsIFZlcnNpb249NC4wLjMuMCwgQ3VsdHVyZT1uZXV0cmFsLCBQdWJsaWNLZXlUb2tlbj05ZDc3Y2M3YWQzOWI2OGViXV0BAAAACl9idXN5Q291bnQACAIAAAAAAAAADAUAAABwU3lzdGVtLlJ1bnRpbWUuU2VyaWFsaXphdGlvbi5Gb3JtYXR0ZXJzLlRlc3RzLCBWZXJzaW9uPTQuMC4zLjAsIEN1bHR1cmU9bmV1dHJhbCwgUHVibGljS2V5VG9rZW49OWQ3N2NjN2FkMzliNjhlYgQEAAAAygFTeXN0ZW0uQ29sbGVjdGlvbnMuR2VuZXJpYy5MaXN0YDFbW1N5c3RlbS5SdW50aW1lLlNlcmlhbGl6YXRpb24uRm9ybWF0dGVycy5UZXN0cy5Qb2ludCwgU3lzdGVtLlJ1bnRpbWUuU2VyaWFsaXphdGlvbi5Gb3JtYXR0ZXJzLlRlc3RzLCBWZXJzaW9uPTQuMC4zLjAsIEN1bHR1cmU9bmV1dHJhbCwgUHVibGljS2V5VG9rZW49OWQ3N2NjN2FkMzliNjhlYl1dAwAAAAZfaXRlbXMFX3NpemUIX3ZlcnNpb24EAAA1U3lzdGVtLlJ1bnRpbWUuU2VyaWFsaXphdGlvbi5Gb3JtYXR0ZXJzLlRlc3RzLlBvaW50W10FAAAACAgJBgAAAAIAAAACAAAABwYAAAAAAQAAAAQAAAAEM1N5c3RlbS5SdW50aW1lLlNlcmlhbGl6YXRpb24uRm9ybWF0dGVycy5UZXN0cy5Qb2ludAUAAAAJBwAAAAkIAAAADQIFBwAAADNTeXN0ZW0uUnVudGltZS5TZXJpYWxpemF0aW9uLkZvcm1hdHRlcnMuVGVzdHMuUG9pbnQCAAAAAVgBWQAACAgFAAAAAQAAAAIAAAABCAAAAAcAAAAEAAAAAwAAAAs=" } };
+ yield return new object[] { new ObservableCollection<Tuple<int, Graph<int>>>(), new string[] { "AAEAAAD/////AQAAAAAAAAAMAgAAAE5XaW5kb3dzQmFzZSwgVmVyc2lvbj0zLjAuMC4wLCBDdWx0dXJlPW5ldXRyYWwsIFB1YmxpY0tleVRva2VuPTMxYmYzODU2YWQzNjRlMzUFAQAAAPgDU3lzdGVtLkNvbGxlY3Rpb25zLk9iamVjdE1vZGVsLk9ic2VydmFibGVDb2xsZWN0aW9uYDFbW1N5c3RlbS5UdXBsZWAyW1tTeXN0ZW0uSW50MzIsIG1zY29ybGliLCBWZXJzaW9uPTQuMC4wLjAsIEN1bHR1cmU9bmV1dHJhbCwgUHVibGljS2V5VG9rZW49Yjc3YTVjNTYxOTM0ZTA4OV0sW1N5c3RlbS5SdW50aW1lLlNlcmlhbGl6YXRpb24uRm9ybWF0dGVycy5UZXN0cy5HcmFwaGAxW1tTeXN0ZW0uSW50MzIsIG1zY29ybGliLCBWZXJzaW9uPTQuMC4wLjAsIEN1bHR1cmU9bmV1dHJhbCwgUHVibGljS2V5VG9rZW49Yjc3YTVjNTYxOTM0ZTA4OV1dLCBTeXN0ZW0uUnVudGltZS5TZXJpYWxpemF0aW9uLkZvcm1hdHRlcnMuVGVzdHMsIFZlcnNpb249NC4wLjMuMCwgQ3VsdHVyZT1uZXV0cmFsLCBQdWJsaWNLZXlUb2tlbj05ZDc3Y2M3YWQzOWI2OGViXV0sIG1zY29ybGliLCBWZXJzaW9uPTQuMC4wLjAsIEN1bHR1cmU9bmV1dHJhbCwgUHVibGljS2V5VG9rZW49Yjc3YTVjNTYxOTM0ZTA4OV1dAgAAAAhfbW9uaXRvchJDb2xsZWN0aW9uYDEraXRlbXMEA4YEU3lzdGVtLkNvbGxlY3Rpb25zLk9iamVjdE1vZGVsLk9ic2VydmFibGVDb2xsZWN0aW9uYDErU2ltcGxlTW9uaXRvcltbU3lzdGVtLlR1cGxlYDJbW1N5c3RlbS5JbnQzMiwgbXNjb3JsaWIsIFZlcnNpb249NC4wLjAuMCwgQ3VsdHVyZT1uZXV0cmFsLCBQdWJsaWNLZXlUb2tlbj1iNzdhNWM1NjE5MzRlMDg5XSxbU3lzdGVtLlJ1bnRpbWUuU2VyaWFsaXphdGlvbi5Gb3JtYXR0ZXJzLlRlc3RzLkdyYXBoYDFbW1N5c3RlbS5JbnQzMiwgbXNjb3JsaWIsIFZlcnNpb249NC4wLjAuMCwgQ3VsdHVyZT1uZXV0cmFsLCBQdWJsaWNLZXlUb2tlbj1iNzdhNWM1NjE5MzRlMDg5XV0sIFN5c3RlbS5SdW50aW1lLlNlcmlhbGl6YXRpb24uRm9ybWF0dGVycy5UZXN0cywgVmVyc2lvbj00LjAuMy4wLCBDdWx0dXJlPW5ldXRyYWwsIFB1YmxpY0tleVRva2VuPTlkNzdjYzdhZDM5YjY4ZWJdXSwgbXNjb3JsaWIsIFZlcnNpb249NC4wLjAuMCwgQ3VsdHVyZT1uZXV0cmFsLCBQdWJsaWNLZXlUb2tlbj1iNzdhNWM1NjE5MzRlMDg5XV0CAAAA5ANTeXN0ZW0uQ29sbGVjdGlvbnMuR2VuZXJpYy5MaXN0YDFbW1N5c3RlbS5UdXBsZWAyW1tTeXN0ZW0uSW50MzIsIG1zY29ybGliLCBWZXJzaW9uPTQuMC4wLjAsIEN1bHR1cmU9bmV1dHJhbCwgUHVibGljS2V5VG9rZW49Yjc3YTVjNTYxOTM0ZTA4OV0sW1N5c3RlbS5SdW50aW1lLlNlcmlhbGl6YXRpb24uRm9ybWF0dGVycy5UZXN0cy5HcmFwaGAxW1tTeXN0ZW0uSW50MzIsIG1zY29ybGliLCBWZXJzaW9uPTQuMC4wLjAsIEN1bHR1cmU9bmV1dHJhbCwgUHVibGljS2V5VG9rZW49Yjc3YTVjNTYxOTM0ZTA4OV1dLCBTeXN0ZW0uUnVudGltZS5TZXJpYWxpemF0aW9uLkZvcm1hdHRlcnMuVGVzdHMsIFZlcnNpb249NC4wLjMuMCwgQ3VsdHVyZT1uZXV0cmFsLCBQdWJsaWNLZXlUb2tlbj05ZDc3Y2M3YWQzOWI2OGViXV0sIG1zY29ybGliLCBWZXJzaW9uPTQuMC4wLjAsIEN1bHR1cmU9bmV1dHJhbCwgUHVibGljS2V5VG9rZW49Yjc3YTVjNTYxOTM0ZTA4OV1dAgAAAAkDAAAACQQAAAAFAwAAAIYEU3lzdGVtLkNvbGxlY3Rpb25zLk9iamVjdE1vZGVsLk9ic2VydmFibGVDb2xsZWN0aW9uYDErU2ltcGxlTW9uaXRvcltbU3lzdGVtLlR1cGxlYDJbW1N5c3RlbS5JbnQzMiwgbXNjb3JsaWIsIFZlcnNpb249NC4wLjAuMCwgQ3VsdHVyZT1uZXV0cmFsLCBQdWJsaWNLZXlUb2tlbj1iNzdhNWM1NjE5MzRlMDg5XSxbU3lzdGVtLlJ1bnRpbWUuU2VyaWFsaXphdGlvbi5Gb3JtYXR0ZXJzLlRlc3RzLkdyYXBoYDFbW1N5c3RlbS5JbnQzMiwgbXNjb3JsaWIsIFZlcnNpb249NC4wLjAuMCwgQ3VsdHVyZT1uZXV0cmFsLCBQdWJsaWNLZXlUb2tlbj1iNzdhNWM1NjE5MzRlMDg5XV0sIFN5c3RlbS5SdW50aW1lLlNlcmlhbGl6YXRpb24uRm9ybWF0dGVycy5UZXN0cywgVmVyc2lvbj00LjAuMy4wLCBDdWx0dXJlPW5ldXRyYWwsIFB1YmxpY0tleVRva2VuPTlkNzdjYzdhZDM5YjY4ZWJdXSwgbXNjb3JsaWIsIFZlcnNpb249NC4wLjAuMCwgQ3VsdHVyZT1uZXV0cmFsLCBQdWJsaWNLZXlUb2tlbj1iNzdhNWM1NjE5MzRlMDg5XV0BAAAACl9idXN5Q291bnQACAIAAAAAAAAABAQAAADkA1N5c3RlbS5Db2xsZWN0aW9ucy5HZW5lcmljLkxpc3RgMVtbU3lzdGVtLlR1cGxlYDJbW1N5c3RlbS5JbnQzMiwgbXNjb3JsaWIsIFZlcnNpb249NC4wLjAuMCwgQ3VsdHVyZT1uZXV0cmFsLCBQdWJsaWNLZXlUb2tlbj1iNzdhNWM1NjE5MzRlMDg5XSxbU3lzdGVtLlJ1bnRpbWUuU2VyaWFsaXphdGlvbi5Gb3JtYXR0ZXJzLlRlc3RzLkdyYXBoYDFbW1N5c3RlbS5JbnQzMiwgbXNjb3JsaWIsIFZlcnNpb249NC4wLjAuMCwgQ3VsdHVyZT1uZXV0cmFsLCBQdWJsaWNLZXlUb2tlbj1iNzdhNWM1NjE5MzRlMDg5XV0sIFN5c3RlbS5SdW50aW1lLlNlcmlhbGl6YXRpb24uRm9ybWF0dGVycy5UZXN0cywgVmVyc2lvbj00LjAuMy4wLCBDdWx0dXJlPW5ldXRyYWwsIFB1YmxpY0tleVRva2VuPTlkNzdjYzdhZDM5YjY4ZWJdXSwgbXNjb3JsaWIsIFZlcnNpb249NC4wLjAuMCwgQ3VsdHVyZT1uZXV0cmFsLCBQdWJsaWNLZXlUb2tlbj1iNzdhNWM1NjE5MzRlMDg5XV0DAAAABl9pdGVtcwVfc2l6ZQhfdmVyc2lvbgMAAPQCU3lzdGVtLlR1cGxlYDJbW1N5c3RlbS5JbnQzMiwgbXNjb3JsaWIsIFZlcnNpb249NC4wLjAuMCwgQ3VsdHVyZT1uZXV0cmFsLCBQdWJsaWNLZXlUb2tlbj1iNzdhNWM1NjE5MzRlMDg5XSxbU3lzdGVtLlJ1bnRpbWUuU2VyaWFsaXphdGlvbi5Gb3JtYXR0ZXJzLlRlc3RzLkdyYXBoYDFbW1N5c3RlbS5JbnQzMiwgbXNjb3JsaWIsIFZlcnNpb249NC4wLjAuMCwgQ3VsdHVyZT1uZXV0cmFsLCBQdWJsaWNLZXlUb2tlbj1iNzdhNWM1NjE5MzRlMDg5XV0sIFN5c3RlbS5SdW50aW1lLlNlcmlhbGl6YXRpb24uRm9ybWF0dGVycy5UZXN0cywgVmVyc2lvbj00LjAuMy4wLCBDdWx0dXJlPW5ldXRyYWwsIFB1YmxpY0tleVRva2VuPTlkNzdjYzdhZDM5YjY4ZWJdXVtdCAgJBQAAAAAAAAAAAAAABwUAAAAAAQAAAAAAAAAD8gJTeXN0ZW0uVHVwbGVgMltbU3lzdGVtLkludDMyLCBtc2NvcmxpYiwgVmVyc2lvbj00LjAuMC4wLCBDdWx0dXJlPW5ldXRyYWwsIFB1YmxpY0tleVRva2VuPWI3N2E1YzU2MTkzNGUwODldLFtTeXN0ZW0uUnVudGltZS5TZXJpYWxpemF0aW9uLkZvcm1hdHRlcnMuVGVzdHMuR3JhcGhgMVtbU3lzdGVtLkludDMyLCBtc2NvcmxpYiwgVmVyc2lvbj00LjAuMC4wLCBDdWx0dXJlPW5ldXRyYWwsIFB1YmxpY0tleVRva2VuPWI3N2E1YzU2MTkzNGUwODldXSwgU3lzdGVtLlJ1bnRpbWUuU2VyaWFsaXphdGlvbi5Gb3JtYXR0ZXJzLlRlc3RzLCBWZXJzaW9uPTQuMC4zLjAsIEN1bHR1cmU9bmV1dHJhbCwgUHVibGljS2V5VG9rZW49OWQ3N2NjN2FkMzliNjhlYl1dCw==", "AAEAAAD/////AQAAAAAAAAAMAgAAAE5XaW5kb3dzQmFzZSwgVmVyc2lvbj0zLjAuMC4wLCBDdWx0dXJlPU5ldXRyYWwsIFB1YmxpY0tleVRva2VuPTMxYmYzODU2YWQzNjRlMzUFAQAAAPgDU3lzdGVtLkNvbGxlY3Rpb25zLk9iamVjdE1vZGVsLk9ic2VydmFibGVDb2xsZWN0aW9uYDFbW1N5c3RlbS5UdXBsZWAyW1tTeXN0ZW0uSW50MzIsIG1zY29ybGliLCBWZXJzaW9uPTQuMC4wLjAsIEN1bHR1cmU9bmV1dHJhbCwgUHVibGljS2V5VG9rZW49Yjc3YTVjNTYxOTM0ZTA4OV0sW1N5c3RlbS5SdW50aW1lLlNlcmlhbGl6YXRpb24uRm9ybWF0dGVycy5UZXN0cy5HcmFwaGAxW1tTeXN0ZW0uSW50MzIsIG1zY29ybGliLCBWZXJzaW9uPTQuMC4wLjAsIEN1bHR1cmU9bmV1dHJhbCwgUHVibGljS2V5VG9rZW49Yjc3YTVjNTYxOTM0ZTA4OV1dLCBTeXN0ZW0uUnVudGltZS5TZXJpYWxpemF0aW9uLkZvcm1hdHRlcnMuVGVzdHMsIFZlcnNpb249NC4wLjMuMCwgQ3VsdHVyZT1uZXV0cmFsLCBQdWJsaWNLZXlUb2tlbj05ZDc3Y2M3YWQzOWI2OGViXV0sIG1zY29ybGliLCBWZXJzaW9uPTQuMC4wLjAsIEN1bHR1cmU9bmV1dHJhbCwgUHVibGljS2V5VG9rZW49Yjc3YTVjNTYxOTM0ZTA4OV1dAgAAAAhfbW9uaXRvchJDb2xsZWN0aW9uYDEraXRlbXMEA4YEU3lzdGVtLkNvbGxlY3Rpb25zLk9iamVjdE1vZGVsLk9ic2VydmFibGVDb2xsZWN0aW9uYDErU2ltcGxlTW9uaXRvcltbU3lzdGVtLlR1cGxlYDJbW1N5c3RlbS5JbnQzMiwgbXNjb3JsaWIsIFZlcnNpb249NC4wLjAuMCwgQ3VsdHVyZT1uZXV0cmFsLCBQdWJsaWNLZXlUb2tlbj1iNzdhNWM1NjE5MzRlMDg5XSxbU3lzdGVtLlJ1bnRpbWUuU2VyaWFsaXphdGlvbi5Gb3JtYXR0ZXJzLlRlc3RzLkdyYXBoYDFbW1N5c3RlbS5JbnQzMiwgbXNjb3JsaWIsIFZlcnNpb249NC4wLjAuMCwgQ3VsdHVyZT1uZXV0cmFsLCBQdWJsaWNLZXlUb2tlbj1iNzdhNWM1NjE5MzRlMDg5XV0sIFN5c3RlbS5SdW50aW1lLlNlcmlhbGl6YXRpb24uRm9ybWF0dGVycy5UZXN0cywgVmVyc2lvbj00LjAuMy4wLCBDdWx0dXJlPW5ldXRyYWwsIFB1YmxpY0tleVRva2VuPTlkNzdjYzdhZDM5YjY4ZWJdXSwgbXNjb3JsaWIsIFZlcnNpb249NC4wLjAuMCwgQ3VsdHVyZT1uZXV0cmFsLCBQdWJsaWNLZXlUb2tlbj1iNzdhNWM1NjE5MzRlMDg5XV0CAAAA5ANTeXN0ZW0uQ29sbGVjdGlvbnMuR2VuZXJpYy5MaXN0YDFbW1N5c3RlbS5UdXBsZWAyW1tTeXN0ZW0uSW50MzIsIG1zY29ybGliLCBWZXJzaW9uPTQuMC4wLjAsIEN1bHR1cmU9bmV1dHJhbCwgUHVibGljS2V5VG9rZW49Yjc3YTVjNTYxOTM0ZTA4OV0sW1N5c3RlbS5SdW50aW1lLlNlcmlhbGl6YXRpb24uRm9ybWF0dGVycy5UZXN0cy5HcmFwaGAxW1tTeXN0ZW0uSW50MzIsIG1zY29ybGliLCBWZXJzaW9uPTQuMC4wLjAsIEN1bHR1cmU9bmV1dHJhbCwgUHVibGljS2V5VG9rZW49Yjc3YTVjNTYxOTM0ZTA4OV1dLCBTeXN0ZW0uUnVudGltZS5TZXJpYWxpemF0aW9uLkZvcm1hdHRlcnMuVGVzdHMsIFZlcnNpb249NC4wLjMuMCwgQ3VsdHVyZT1uZXV0cmFsLCBQdWJsaWNLZXlUb2tlbj05ZDc3Y2M3YWQzOWI2OGViXV0sIG1zY29ybGliLCBWZXJzaW9uPTQuMC4wLjAsIEN1bHR1cmU9bmV1dHJhbCwgUHVibGljS2V5VG9rZW49Yjc3YTVjNTYxOTM0ZTA4OV1dAgAAAAkDAAAACQQAAAAFAwAAAIYEU3lzdGVtLkNvbGxlY3Rpb25zLk9iamVjdE1vZGVsLk9ic2VydmFibGVDb2xsZWN0aW9uYDErU2ltcGxlTW9uaXRvcltbU3lzdGVtLlR1cGxlYDJbW1N5c3RlbS5JbnQzMiwgbXNjb3JsaWIsIFZlcnNpb249NC4wLjAuMCwgQ3VsdHVyZT1uZXV0cmFsLCBQdWJsaWNLZXlUb2tlbj1iNzdhNWM1NjE5MzRlMDg5XSxbU3lzdGVtLlJ1bnRpbWUuU2VyaWFsaXphdGlvbi5Gb3JtYXR0ZXJzLlRlc3RzLkdyYXBoYDFbW1N5c3RlbS5JbnQzMiwgbXNjb3JsaWIsIFZlcnNpb249NC4wLjAuMCwgQ3VsdHVyZT1uZXV0cmFsLCBQdWJsaWNLZXlUb2tlbj1iNzdhNWM1NjE5MzRlMDg5XV0sIFN5c3RlbS5SdW50aW1lLlNlcmlhbGl6YXRpb24uRm9ybWF0dGVycy5UZXN0cywgVmVyc2lvbj00LjAuMy4wLCBDdWx0dXJlPW5ldXRyYWwsIFB1YmxpY0tleVRva2VuPTlkNzdjYzdhZDM5YjY4ZWJdXSwgbXNjb3JsaWIsIFZlcnNpb249NC4wLjAuMCwgQ3VsdHVyZT1uZXV0cmFsLCBQdWJsaWNLZXlUb2tlbj1iNzdhNWM1NjE5MzRlMDg5XV0BAAAACl9idXN5Q291bnQACAIAAAAAAAAABAQAAADkA1N5c3RlbS5Db2xsZWN0aW9ucy5HZW5lcmljLkxpc3RgMVtbU3lzdGVtLlR1cGxlYDJbW1N5c3RlbS5JbnQzMiwgbXNjb3JsaWIsIFZlcnNpb249NC4wLjAuMCwgQ3VsdHVyZT1uZXV0cmFsLCBQdWJsaWNLZXlUb2tlbj1iNzdhNWM1NjE5MzRlMDg5XSxbU3lzdGVtLlJ1bnRpbWUuU2VyaWFsaXphdGlvbi5Gb3JtYXR0ZXJzLlRlc3RzLkdyYXBoYDFbW1N5c3RlbS5JbnQzMiwgbXNjb3JsaWIsIFZlcnNpb249NC4wLjAuMCwgQ3VsdHVyZT1uZXV0cmFsLCBQdWJsaWNLZXlUb2tlbj1iNzdhNWM1NjE5MzRlMDg5XV0sIFN5c3RlbS5SdW50aW1lLlNlcmlhbGl6YXRpb24uRm9ybWF0dGVycy5UZXN0cywgVmVyc2lvbj00LjAuMy4wLCBDdWx0dXJlPW5ldXRyYWwsIFB1YmxpY0tleVRva2VuPTlkNzdjYzdhZDM5YjY4ZWJdXSwgbXNjb3JsaWIsIFZlcnNpb249NC4wLjAuMCwgQ3VsdHVyZT1uZXV0cmFsLCBQdWJsaWNLZXlUb2tlbj1iNzdhNWM1NjE5MzRlMDg5XV0DAAAABl9pdGVtcwVfc2l6ZQhfdmVyc2lvbgMAAPQCU3lzdGVtLlR1cGxlYDJbW1N5c3RlbS5JbnQzMiwgbXNjb3JsaWIsIFZlcnNpb249NC4wLjAuMCwgQ3VsdHVyZT1uZXV0cmFsLCBQdWJsaWNLZXlUb2tlbj1iNzdhNWM1NjE5MzRlMDg5XSxbU3lzdGVtLlJ1bnRpbWUuU2VyaWFsaXphdGlvbi5Gb3JtYXR0ZXJzLlRlc3RzLkdyYXBoYDFbW1N5c3RlbS5JbnQzMiwgbXNjb3JsaWIsIFZlcnNpb249NC4wLjAuMCwgQ3VsdHVyZT1uZXV0cmFsLCBQdWJsaWNLZXlUb2tlbj1iNzdhNWM1NjE5MzRlMDg5XV0sIFN5c3RlbS5SdW50aW1lLlNlcmlhbGl6YXRpb24uRm9ybWF0dGVycy5UZXN0cywgVmVyc2lvbj00LjAuMy4wLCBDdWx0dXJlPW5ldXRyYWwsIFB1YmxpY0tleVRva2VuPTlkNzdjYzdhZDM5YjY4ZWJdXVtdCAgJBQAAAAAAAAAAAAAABwUAAAAAAQAAAAAAAAAD8gJTeXN0ZW0uVHVwbGVgMltbU3lzdGVtLkludDMyLCBtc2NvcmxpYiwgVmVyc2lvbj00LjAuMC4wLCBDdWx0dXJlPW5ldXRyYWwsIFB1YmxpY0tleVRva2VuPWI3N2E1YzU2MTkzNGUwODldLFtTeXN0ZW0uUnVudGltZS5TZXJpYWxpemF0aW9uLkZvcm1hdHRlcnMuVGVzdHMuR3JhcGhgMVtbU3lzdGVtLkludDMyLCBtc2NvcmxpYiwgVmVyc2lvbj00LjAuMC4wLCBDdWx0dXJlPW5ldXRyYWwsIFB1YmxpY0tleVRva2VuPWI3N2E1YzU2MTkzNGUwODldXSwgU3lzdGVtLlJ1bnRpbWUuU2VyaWFsaXphdGlvbi5Gb3JtYXR0ZXJzLlRlc3RzLCBWZXJzaW9uPTQuMC4zLjAsIEN1bHR1cmU9bmV1dHJhbCwgUHVibGljS2V5VG9rZW49OWQ3N2NjN2FkMzliNjhlYl1dCw==" } };
+ yield return new object[] { new ObservableCollection<Tuple<int, Graph<int>>>(new Tuple<int, Graph<int>>[] { Tuple.Create(1, new Graph<int>()), Tuple.Create(5, new Graph<int>()) }), new string[] { "AAEAAAD/////AQAAAAAAAAAMAgAAAE5XaW5kb3dzQmFzZSwgVmVyc2lvbj0zLjAuMC4wLCBDdWx0dXJlPW5ldXRyYWwsIFB1YmxpY0tleVRva2VuPTMxYmYzODU2YWQzNjRlMzUFAQAAAPgDU3lzdGVtLkNvbGxlY3Rpb25zLk9iamVjdE1vZGVsLk9ic2VydmFibGVDb2xsZWN0aW9uYDFbW1N5c3RlbS5UdXBsZWAyW1tTeXN0ZW0uSW50MzIsIG1zY29ybGliLCBWZXJzaW9uPTQuMC4wLjAsIEN1bHR1cmU9bmV1dHJhbCwgUHVibGljS2V5VG9rZW49Yjc3YTVjNTYxOTM0ZTA4OV0sW1N5c3RlbS5SdW50aW1lLlNlcmlhbGl6YXRpb24uRm9ybWF0dGVycy5UZXN0cy5HcmFwaGAxW1tTeXN0ZW0uSW50MzIsIG1zY29ybGliLCBWZXJzaW9uPTQuMC4wLjAsIEN1bHR1cmU9bmV1dHJhbCwgUHVibGljS2V5VG9rZW49Yjc3YTVjNTYxOTM0ZTA4OV1dLCBTeXN0ZW0uUnVudGltZS5TZXJpYWxpemF0aW9uLkZvcm1hdHRlcnMuVGVzdHMsIFZlcnNpb249NC4wLjMuMCwgQ3VsdHVyZT1uZXV0cmFsLCBQdWJsaWNLZXlUb2tlbj05ZDc3Y2M3YWQzOWI2OGViXV0sIG1zY29ybGliLCBWZXJzaW9uPTQuMC4wLjAsIEN1bHR1cmU9bmV1dHJhbCwgUHVibGljS2V5VG9rZW49Yjc3YTVjNTYxOTM0ZTA4OV1dAgAAAAhfbW9uaXRvchJDb2xsZWN0aW9uYDEraXRlbXMEA4YEU3lzdGVtLkNvbGxlY3Rpb25zLk9iamVjdE1vZGVsLk9ic2VydmFibGVDb2xsZWN0aW9uYDErU2ltcGxlTW9uaXRvcltbU3lzdGVtLlR1cGxlYDJbW1N5c3RlbS5JbnQzMiwgbXNjb3JsaWIsIFZlcnNpb249NC4wLjAuMCwgQ3VsdHVyZT1uZXV0cmFsLCBQdWJsaWNLZXlUb2tlbj1iNzdhNWM1NjE5MzRlMDg5XSxbU3lzdGVtLlJ1bnRpbWUuU2VyaWFsaXphdGlvbi5Gb3JtYXR0ZXJzLlRlc3RzLkdyYXBoYDFbW1N5c3RlbS5JbnQzMiwgbXNjb3JsaWIsIFZlcnNpb249NC4wLjAuMCwgQ3VsdHVyZT1uZXV0cmFsLCBQdWJsaWNLZXlUb2tlbj1iNzdhNWM1NjE5MzRlMDg5XV0sIFN5c3RlbS5SdW50aW1lLlNlcmlhbGl6YXRpb24uRm9ybWF0dGVycy5UZXN0cywgVmVyc2lvbj00LjAuMy4wLCBDdWx0dXJlPW5ldXRyYWwsIFB1YmxpY0tleVRva2VuPTlkNzdjYzdhZDM5YjY4ZWJdXSwgbXNjb3JsaWIsIFZlcnNpb249NC4wLjAuMCwgQ3VsdHVyZT1uZXV0cmFsLCBQdWJsaWNLZXlUb2tlbj1iNzdhNWM1NjE5MzRlMDg5XV0CAAAA5ANTeXN0ZW0uQ29sbGVjdGlvbnMuR2VuZXJpYy5MaXN0YDFbW1N5c3RlbS5UdXBsZWAyW1tTeXN0ZW0uSW50MzIsIG1zY29ybGliLCBWZXJzaW9uPTQuMC4wLjAsIEN1bHR1cmU9bmV1dHJhbCwgUHVibGljS2V5VG9rZW49Yjc3YTVjNTYxOTM0ZTA4OV0sW1N5c3RlbS5SdW50aW1lLlNlcmlhbGl6YXRpb24uRm9ybWF0dGVycy5UZXN0cy5HcmFwaGAxW1tTeXN0ZW0uSW50MzIsIG1zY29ybGliLCBWZXJzaW9uPTQuMC4wLjAsIEN1bHR1cmU9bmV1dHJhbCwgUHVibGljS2V5VG9rZW49Yjc3YTVjNTYxOTM0ZTA4OV1dLCBTeXN0ZW0uUnVudGltZS5TZXJpYWxpemF0aW9uLkZvcm1hdHRlcnMuVGVzdHMsIFZlcnNpb249NC4wLjMuMCwgQ3VsdHVyZT1uZXV0cmFsLCBQdWJsaWNLZXlUb2tlbj05ZDc3Y2M3YWQzOWI2OGViXV0sIG1zY29ybGliLCBWZXJzaW9uPTQuMC4wLjAsIEN1bHR1cmU9bmV1dHJhbCwgUHVibGljS2V5VG9rZW49Yjc3YTVjNTYxOTM0ZTA4OV1dAgAAAAkDAAAACQQAAAAFAwAAAIYEU3lzdGVtLkNvbGxlY3Rpb25zLk9iamVjdE1vZGVsLk9ic2VydmFibGVDb2xsZWN0aW9uYDErU2ltcGxlTW9uaXRvcltbU3lzdGVtLlR1cGxlYDJbW1N5c3RlbS5JbnQzMiwgbXNjb3JsaWIsIFZlcnNpb249NC4wLjAuMCwgQ3VsdHVyZT1uZXV0cmFsLCBQdWJsaWNLZXlUb2tlbj1iNzdhNWM1NjE5MzRlMDg5XSxbU3lzdGVtLlJ1bnRpbWUuU2VyaWFsaXphdGlvbi5Gb3JtYXR0ZXJzLlRlc3RzLkdyYXBoYDFbW1N5c3RlbS5JbnQzMiwgbXNjb3JsaWIsIFZlcnNpb249NC4wLjAuMCwgQ3VsdHVyZT1uZXV0cmFsLCBQdWJsaWNLZXlUb2tlbj1iNzdhNWM1NjE5MzRlMDg5XV0sIFN5c3RlbS5SdW50aW1lLlNlcmlhbGl6YXRpb24uRm9ybWF0dGVycy5UZXN0cywgVmVyc2lvbj00LjAuMy4wLCBDdWx0dXJlPW5ldXRyYWwsIFB1YmxpY0tleVRva2VuPTlkNzdjYzdhZDM5YjY4ZWJdXSwgbXNjb3JsaWIsIFZlcnNpb249NC4wLjAuMCwgQ3VsdHVyZT1uZXV0cmFsLCBQdWJsaWNLZXlUb2tlbj1iNzdhNWM1NjE5MzRlMDg5XV0BAAAACl9idXN5Q291bnQACAIAAAAAAAAABAQAAADkA1N5c3RlbS5Db2xsZWN0aW9ucy5HZW5lcmljLkxpc3RgMVtbU3lzdGVtLlR1cGxlYDJbW1N5c3RlbS5JbnQzMiwgbXNjb3JsaWIsIFZlcnNpb249NC4wLjAuMCwgQ3VsdHVyZT1uZXV0cmFsLCBQdWJsaWNLZXlUb2tlbj1iNzdhNWM1NjE5MzRlMDg5XSxbU3lzdGVtLlJ1bnRpbWUuU2VyaWFsaXphdGlvbi5Gb3JtYXR0ZXJzLlRlc3RzLkdyYXBoYDFbW1N5c3RlbS5JbnQzMiwgbXNjb3JsaWIsIFZlcnNpb249NC4wLjAuMCwgQ3VsdHVyZT1uZXV0cmFsLCBQdWJsaWNLZXlUb2tlbj1iNzdhNWM1NjE5MzRlMDg5XV0sIFN5c3RlbS5SdW50aW1lLlNlcmlhbGl6YXRpb24uRm9ybWF0dGVycy5UZXN0cywgVmVyc2lvbj00LjAuMy4wLCBDdWx0dXJlPW5ldXRyYWwsIFB1YmxpY0tleVRva2VuPTlkNzdjYzdhZDM5YjY4ZWJdXSwgbXNjb3JsaWIsIFZlcnNpb249NC4wLjAuMCwgQ3VsdHVyZT1uZXV0cmFsLCBQdWJsaWNLZXlUb2tlbj1iNzdhNWM1NjE5MzRlMDg5XV0DAAAABl9pdGVtcwVfc2l6ZQhfdmVyc2lvbgMAAPQCU3lzdGVtLlR1cGxlYDJbW1N5c3RlbS5JbnQzMiwgbXNjb3JsaWIsIFZlcnNpb249NC4wLjAuMCwgQ3VsdHVyZT1uZXV0cmFsLCBQdWJsaWNLZXlUb2tlbj1iNzdhNWM1NjE5MzRlMDg5XSxbU3lzdGVtLlJ1bnRpbWUuU2VyaWFsaXphdGlvbi5Gb3JtYXR0ZXJzLlRlc3RzLkdyYXBoYDFbW1N5c3RlbS5JbnQzMiwgbXNjb3JsaWIsIFZlcnNpb249NC4wLjAuMCwgQ3VsdHVyZT1uZXV0cmFsLCBQdWJsaWNLZXlUb2tlbj1iNzdhNWM1NjE5MzRlMDg5XV0sIFN5c3RlbS5SdW50aW1lLlNlcmlhbGl6YXRpb24uRm9ybWF0dGVycy5UZXN0cywgVmVyc2lvbj00LjAuMy4wLCBDdWx0dXJlPW5ldXRyYWwsIFB1YmxpY0tleVRva2VuPTlkNzdjYzdhZDM5YjY4ZWJdXVtdCAgJBQAAAAIAAAAAAAAABwUAAAAAAQAAAAIAAAAD8gJTeXN0ZW0uVHVwbGVgMltbU3lzdGVtLkludDMyLCBtc2NvcmxpYiwgVmVyc2lvbj00LjAuMC4wLCBDdWx0dXJlPW5ldXRyYWwsIFB1YmxpY0tleVRva2VuPWI3N2E1YzU2MTkzNGUwODldLFtTeXN0ZW0uUnVudGltZS5TZXJpYWxpemF0aW9uLkZvcm1hdHRlcnMuVGVzdHMuR3JhcGhgMVtbU3lzdGVtLkludDMyLCBtc2NvcmxpYiwgVmVyc2lvbj00LjAuMC4wLCBDdWx0dXJlPW5ldXRyYWwsIFB1YmxpY0tleVRva2VuPWI3N2E1YzU2MTkzNGUwODldXSwgU3lzdGVtLlJ1bnRpbWUuU2VyaWFsaXphdGlvbi5Gb3JtYXR0ZXJzLlRlc3RzLCBWZXJzaW9uPTQuMC4zLjAsIEN1bHR1cmU9bmV1dHJhbCwgUHVibGljS2V5VG9rZW49OWQ3N2NjN2FkMzliNjhlYl1dCQYAAAAJBwAAAAwIAAAAcFN5c3RlbS5SdW50aW1lLlNlcmlhbGl6YXRpb24uRm9ybWF0dGVycy5UZXN0cywgVmVyc2lvbj00LjAuMy4wLCBDdWx0dXJlPW5ldXRyYWwsIFB1YmxpY0tleVRva2VuPTlkNzdjYzdhZDM5YjY4ZWIEBgAAAPICU3lzdGVtLlR1cGxlYDJbW1N5c3RlbS5JbnQzMiwgbXNjb3JsaWIsIFZlcnNpb249NC4wLjAuMCwgQ3VsdHVyZT1uZXV0cmFsLCBQdWJsaWNLZXlUb2tlbj1iNzdhNWM1NjE5MzRlMDg5XSxbU3lzdGVtLlJ1bnRpbWUuU2VyaWFsaXphdGlvbi5Gb3JtYXR0ZXJzLlRlc3RzLkdyYXBoYDFbW1N5c3RlbS5JbnQzMiwgbXNjb3JsaWIsIFZlcnNpb249NC4wLjAuMCwgQ3VsdHVyZT1uZXV0cmFsLCBQdWJsaWNLZXlUb2tlbj1iNzdhNWM1NjE5MzRlMDg5XV0sIFN5c3RlbS5SdW50aW1lLlNlcmlhbGl6YXRpb24uRm9ybWF0dGVycy5UZXN0cywgVmVyc2lvbj00LjAuMy4wLCBDdWx0dXJlPW5ldXRyYWwsIFB1YmxpY0tleVRva2VuPTlkNzdjYzdhZDM5YjY4ZWJdXQIAAAAHbV9JdGVtMQdtX0l0ZW0yAAQIkgFTeXN0ZW0uUnVudGltZS5TZXJpYWxpemF0aW9uLkZvcm1hdHRlcnMuVGVzdHMuR3JhcGhgMVtbU3lzdGVtLkludDMyLCBtc2NvcmxpYiwgVmVyc2lvbj00LjAuMC4wLCBDdWx0dXJlPW5ldXRyYWwsIFB1YmxpY0tleVRva2VuPWI3N2E1YzU2MTkzNGUwODldXQgAAAABAAAACQkAAAABBwAAAAYAAAAFAAAACQoAAAAFCQAAAJIBU3lzdGVtLlJ1bnRpbWUuU2VyaWFsaXphdGlvbi5Gb3JtYXR0ZXJzLlRlc3RzLkdyYXBoYDFbW1N5c3RlbS5JbnQzMiwgbXNjb3JsaWIsIFZlcnNpb249NC4wLjAuMCwgQ3VsdHVyZT1uZXV0cmFsLCBQdWJsaWNLZXlUb2tlbj1iNzdhNWM1NjE5MzRlMDg5XV0CAAAABVZhbHVlBUxpbmtzAAQIlAFTeXN0ZW0uUnVudGltZS5TZXJpYWxpemF0aW9uLkZvcm1hdHRlcnMuVGVzdHMuR3JhcGhgMVtbU3lzdGVtLkludDMyLCBtc2NvcmxpYiwgVmVyc2lvbj00LjAuMC4wLCBDdWx0dXJlPW5ldXRyYWwsIFB1YmxpY0tleVRva2VuPWI3N2E1YzU2MTkzNGUwODldXVtdCAAAAAgAAAAAAAAACgEKAAAACQAAAAAAAAAKCw==", "AAEAAAD/////AQAAAAAAAAAMAgAAAE5XaW5kb3dzQmFzZSwgVmVyc2lvbj0zLjAuMC4wLCBDdWx0dXJlPU5ldXRyYWwsIFB1YmxpY0tleVRva2VuPTMxYmYzODU2YWQzNjRlMzUFAQAAAPgDU3lzdGVtLkNvbGxlY3Rpb25zLk9iamVjdE1vZGVsLk9ic2VydmFibGVDb2xsZWN0aW9uYDFbW1N5c3RlbS5UdXBsZWAyW1tTeXN0ZW0uSW50MzIsIG1zY29ybGliLCBWZXJzaW9uPTQuMC4wLjAsIEN1bHR1cmU9bmV1dHJhbCwgUHVibGljS2V5VG9rZW49Yjc3YTVjNTYxOTM0ZTA4OV0sW1N5c3RlbS5SdW50aW1lLlNlcmlhbGl6YXRpb24uRm9ybWF0dGVycy5UZXN0cy5HcmFwaGAxW1tTeXN0ZW0uSW50MzIsIG1zY29ybGliLCBWZXJzaW9uPTQuMC4wLjAsIEN1bHR1cmU9bmV1dHJhbCwgUHVibGljS2V5VG9rZW49Yjc3YTVjNTYxOTM0ZTA4OV1dLCBTeXN0ZW0uUnVudGltZS5TZXJpYWxpemF0aW9uLkZvcm1hdHRlcnMuVGVzdHMsIFZlcnNpb249NC4wLjMuMCwgQ3VsdHVyZT1uZXV0cmFsLCBQdWJsaWNLZXlUb2tlbj05ZDc3Y2M3YWQzOWI2OGViXV0sIG1zY29ybGliLCBWZXJzaW9uPTQuMC4wLjAsIEN1bHR1cmU9bmV1dHJhbCwgUHVibGljS2V5VG9rZW49Yjc3YTVjNTYxOTM0ZTA4OV1dAgAAAAhfbW9uaXRvchJDb2xsZWN0aW9uYDEraXRlbXMEA4YEU3lzdGVtLkNvbGxlY3Rpb25zLk9iamVjdE1vZGVsLk9ic2VydmFibGVDb2xsZWN0aW9uYDErU2ltcGxlTW9uaXRvcltbU3lzdGVtLlR1cGxlYDJbW1N5c3RlbS5JbnQzMiwgbXNjb3JsaWIsIFZlcnNpb249NC4wLjAuMCwgQ3VsdHVyZT1uZXV0cmFsLCBQdWJsaWNLZXlUb2tlbj1iNzdhNWM1NjE5MzRlMDg5XSxbU3lzdGVtLlJ1bnRpbWUuU2VyaWFsaXphdGlvbi5Gb3JtYXR0ZXJzLlRlc3RzLkdyYXBoYDFbW1N5c3RlbS5JbnQzMiwgbXNjb3JsaWIsIFZlcnNpb249NC4wLjAuMCwgQ3VsdHVyZT1uZXV0cmFsLCBQdWJsaWNLZXlUb2tlbj1iNzdhNWM1NjE5MzRlMDg5XV0sIFN5c3RlbS5SdW50aW1lLlNlcmlhbGl6YXRpb24uRm9ybWF0dGVycy5UZXN0cywgVmVyc2lvbj00LjAuMy4wLCBDdWx0dXJlPW5ldXRyYWwsIFB1YmxpY0tleVRva2VuPTlkNzdjYzdhZDM5YjY4ZWJdXSwgbXNjb3JsaWIsIFZlcnNpb249NC4wLjAuMCwgQ3VsdHVyZT1uZXV0cmFsLCBQdWJsaWNLZXlUb2tlbj1iNzdhNWM1NjE5MzRlMDg5XV0CAAAA5ANTeXN0ZW0uQ29sbGVjdGlvbnMuR2VuZXJpYy5MaXN0YDFbW1N5c3RlbS5UdXBsZWAyW1tTeXN0ZW0uSW50MzIsIG1zY29ybGliLCBWZXJzaW9uPTQuMC4wLjAsIEN1bHR1cmU9bmV1dHJhbCwgUHVibGljS2V5VG9rZW49Yjc3YTVjNTYxOTM0ZTA4OV0sW1N5c3RlbS5SdW50aW1lLlNlcmlhbGl6YXRpb24uRm9ybWF0dGVycy5UZXN0cy5HcmFwaGAxW1tTeXN0ZW0uSW50MzIsIG1zY29ybGliLCBWZXJzaW9uPTQuMC4wLjAsIEN1bHR1cmU9bmV1dHJhbCwgUHVibGljS2V5VG9rZW49Yjc3YTVjNTYxOTM0ZTA4OV1dLCBTeXN0ZW0uUnVudGltZS5TZXJpYWxpemF0aW9uLkZvcm1hdHRlcnMuVGVzdHMsIFZlcnNpb249NC4wLjMuMCwgQ3VsdHVyZT1uZXV0cmFsLCBQdWJsaWNLZXlUb2tlbj05ZDc3Y2M3YWQzOWI2OGViXV0sIG1zY29ybGliLCBWZXJzaW9uPTQuMC4wLjAsIEN1bHR1cmU9bmV1dHJhbCwgUHVibGljS2V5VG9rZW49Yjc3YTVjNTYxOTM0ZTA4OV1dAgAAAAkDAAAACQQAAAAFAwAAAIYEU3lzdGVtLkNvbGxlY3Rpb25zLk9iamVjdE1vZGVsLk9ic2VydmFibGVDb2xsZWN0aW9uYDErU2ltcGxlTW9uaXRvcltbU3lzdGVtLlR1cGxlYDJbW1N5c3RlbS5JbnQzMiwgbXNjb3JsaWIsIFZlcnNpb249NC4wLjAuMCwgQ3VsdHVyZT1uZXV0cmFsLCBQdWJsaWNLZXlUb2tlbj1iNzdhNWM1NjE5MzRlMDg5XSxbU3lzdGVtLlJ1bnRpbWUuU2VyaWFsaXphdGlvbi5Gb3JtYXR0ZXJzLlRlc3RzLkdyYXBoYDFbW1N5c3RlbS5JbnQzMiwgbXNjb3JsaWIsIFZlcnNpb249NC4wLjAuMCwgQ3VsdHVyZT1uZXV0cmFsLCBQdWJsaWNLZXlUb2tlbj1iNzdhNWM1NjE5MzRlMDg5XV0sIFN5c3RlbS5SdW50aW1lLlNlcmlhbGl6YXRpb24uRm9ybWF0dGVycy5UZXN0cywgVmVyc2lvbj00LjAuMy4wLCBDdWx0dXJlPW5ldXRyYWwsIFB1YmxpY0tleVRva2VuPTlkNzdjYzdhZDM5YjY4ZWJdXSwgbXNjb3JsaWIsIFZlcnNpb249NC4wLjAuMCwgQ3VsdHVyZT1uZXV0cmFsLCBQdWJsaWNLZXlUb2tlbj1iNzdhNWM1NjE5MzRlMDg5XV0BAAAACl9idXN5Q291bnQACAIAAAAAAAAABAQAAADkA1N5c3RlbS5Db2xsZWN0aW9ucy5HZW5lcmljLkxpc3RgMVtbU3lzdGVtLlR1cGxlYDJbW1N5c3RlbS5JbnQzMiwgbXNjb3JsaWIsIFZlcnNpb249NC4wLjAuMCwgQ3VsdHVyZT1uZXV0cmFsLCBQdWJsaWNLZXlUb2tlbj1iNzdhNWM1NjE5MzRlMDg5XSxbU3lzdGVtLlJ1bnRpbWUuU2VyaWFsaXphdGlvbi5Gb3JtYXR0ZXJzLlRlc3RzLkdyYXBoYDFbW1N5c3RlbS5JbnQzMiwgbXNjb3JsaWIsIFZlcnNpb249NC4wLjAuMCwgQ3VsdHVyZT1uZXV0cmFsLCBQdWJsaWNLZXlUb2tlbj1iNzdhNWM1NjE5MzRlMDg5XV0sIFN5c3RlbS5SdW50aW1lLlNlcmlhbGl6YXRpb24uRm9ybWF0dGVycy5UZXN0cywgVmVyc2lvbj00LjAuMy4wLCBDdWx0dXJlPW5ldXRyYWwsIFB1YmxpY0tleVRva2VuPTlkNzdjYzdhZDM5YjY4ZWJdXSwgbXNjb3JsaWIsIFZlcnNpb249NC4wLjAuMCwgQ3VsdHVyZT1uZXV0cmFsLCBQdWJsaWNLZXlUb2tlbj1iNzdhNWM1NjE5MzRlMDg5XV0DAAAABl9pdGVtcwVfc2l6ZQhfdmVyc2lvbgMAAPQCU3lzdGVtLlR1cGxlYDJbW1N5c3RlbS5JbnQzMiwgbXNjb3JsaWIsIFZlcnNpb249NC4wLjAuMCwgQ3VsdHVyZT1uZXV0cmFsLCBQdWJsaWNLZXlUb2tlbj1iNzdhNWM1NjE5MzRlMDg5XSxbU3lzdGVtLlJ1bnRpbWUuU2VyaWFsaXphdGlvbi5Gb3JtYXR0ZXJzLlRlc3RzLkdyYXBoYDFbW1N5c3RlbS5JbnQzMiwgbXNjb3JsaWIsIFZlcnNpb249NC4wLjAuMCwgQ3VsdHVyZT1uZXV0cmFsLCBQdWJsaWNLZXlUb2tlbj1iNzdhNWM1NjE5MzRlMDg5XV0sIFN5c3RlbS5SdW50aW1lLlNlcmlhbGl6YXRpb24uRm9ybWF0dGVycy5UZXN0cywgVmVyc2lvbj00LjAuMy4wLCBDdWx0dXJlPW5ldXRyYWwsIFB1YmxpY0tleVRva2VuPTlkNzdjYzdhZDM5YjY4ZWJdXVtdCAgJBQAAAAIAAAACAAAABwUAAAAAAQAAAAQAAAAD8gJTeXN0ZW0uVHVwbGVgMltbU3lzdGVtLkludDMyLCBtc2NvcmxpYiwgVmVyc2lvbj00LjAuMC4wLCBDdWx0dXJlPW5ldXRyYWwsIFB1YmxpY0tleVRva2VuPWI3N2E1YzU2MTkzNGUwODldLFtTeXN0ZW0uUnVudGltZS5TZXJpYWxpemF0aW9uLkZvcm1hdHRlcnMuVGVzdHMuR3JhcGhgMVtbU3lzdGVtLkludDMyLCBtc2NvcmxpYiwgVmVyc2lvbj00LjAuMC4wLCBDdWx0dXJlPW5ldXRyYWwsIFB1YmxpY0tleVRva2VuPWI3N2E1YzU2MTkzNGUwODldXSwgU3lzdGVtLlJ1bnRpbWUuU2VyaWFsaXphdGlvbi5Gb3JtYXR0ZXJzLlRlc3RzLCBWZXJzaW9uPTQuMC4zLjAsIEN1bHR1cmU9bmV1dHJhbCwgUHVibGljS2V5VG9rZW49OWQ3N2NjN2FkMzliNjhlYl1dCQYAAAAJBwAAAA0CDAgAAABwU3lzdGVtLlJ1bnRpbWUuU2VyaWFsaXphdGlvbi5Gb3JtYXR0ZXJzLlRlc3RzLCBWZXJzaW9uPTQuMC4zLjAsIEN1bHR1cmU9bmV1dHJhbCwgUHVibGljS2V5VG9rZW49OWQ3N2NjN2FkMzliNjhlYgQGAAAA8gJTeXN0ZW0uVHVwbGVgMltbU3lzdGVtLkludDMyLCBtc2NvcmxpYiwgVmVyc2lvbj00LjAuMC4wLCBDdWx0dXJlPW5ldXRyYWwsIFB1YmxpY0tleVRva2VuPWI3N2E1YzU2MTkzNGUwODldLFtTeXN0ZW0uUnVudGltZS5TZXJpYWxpemF0aW9uLkZvcm1hdHRlcnMuVGVzdHMuR3JhcGhgMVtbU3lzdGVtLkludDMyLCBtc2NvcmxpYiwgVmVyc2lvbj00LjAuMC4wLCBDdWx0dXJlPW5ldXRyYWwsIFB1YmxpY0tleVRva2VuPWI3N2E1YzU2MTkzNGUwODldXSwgU3lzdGVtLlJ1bnRpbWUuU2VyaWFsaXphdGlvbi5Gb3JtYXR0ZXJzLlRlc3RzLCBWZXJzaW9uPTQuMC4zLjAsIEN1bHR1cmU9bmV1dHJhbCwgUHVibGljS2V5VG9rZW49OWQ3N2NjN2FkMzliNjhlYl1dAgAAAAdtX0l0ZW0xB21fSXRlbTIABAiSAVN5c3RlbS5SdW50aW1lLlNlcmlhbGl6YXRpb24uRm9ybWF0dGVycy5UZXN0cy5HcmFwaGAxW1tTeXN0ZW0uSW50MzIsIG1zY29ybGliLCBWZXJzaW9uPTQuMC4wLjAsIEN1bHR1cmU9bmV1dHJhbCwgUHVibGljS2V5VG9rZW49Yjc3YTVjNTYxOTM0ZTA4OV1dCAAAAAEAAAAJCQAAAAEHAAAABgAAAAUAAAAJCgAAAAUJAAAAkgFTeXN0ZW0uUnVudGltZS5TZXJpYWxpemF0aW9uLkZvcm1hdHRlcnMuVGVzdHMuR3JhcGhgMVtbU3lzdGVtLkludDMyLCBtc2NvcmxpYiwgVmVyc2lvbj00LjAuMC4wLCBDdWx0dXJlPW5ldXRyYWwsIFB1YmxpY0tleVRva2VuPWI3N2E1YzU2MTkzNGUwODldXQIAAAAFVmFsdWUFTGlua3MABAiUAVN5c3RlbS5SdW50aW1lLlNlcmlhbGl6YXRpb24uRm9ybWF0dGVycy5UZXN0cy5HcmFwaGAxW1tTeXN0ZW0uSW50MzIsIG1zY29ybGliLCBWZXJzaW9uPTQuMC4wLjAsIEN1bHR1cmU9bmV1dHJhbCwgUHVibGljS2V5VG9rZW49Yjc3YTVjNTYxOTM0ZTA4OV1dW10IAAAACAAAAAAAAAAKAQoAAAAJAAAAAAAAAAoL" } };
yield return new object[] { new SimpleKeyedCollection(), new string[] { "AAEAAAD/////AQAAAAAAAAAMAgAAAHBTeXN0ZW0uUnVudGltZS5TZXJpYWxpemF0aW9uLkZvcm1hdHRlcnMuVGVzdHMsIFZlcnNpb249NC4wLjMuMCwgQ3VsdHVyZT1uZXV0cmFsLCBQdWJsaWNLZXlUb2tlbj05ZDc3Y2M3YWQzOWI2OGViBQEAAABDU3lzdGVtLlJ1bnRpbWUuU2VyaWFsaXphdGlvbi5Gb3JtYXR0ZXJzLlRlc3RzLlNpbXBsZUtleWVkQ29sbGVjdGlvbgUAAAAaS2V5ZWRDb2xsZWN0aW9uYDIrY29tcGFyZXIWS2V5ZWRDb2xsZWN0aW9uYDIrZGljdBpLZXllZENvbGxlY3Rpb25gMitrZXlDb3VudBtLZXllZENvbGxlY3Rpb25gMit0aHJlc2hvbGQSQ29sbGVjdGlvbmAxK2l0ZW1zAwMAAAORAVN5c3RlbS5Db2xsZWN0aW9ucy5HZW5lcmljLkdlbmVyaWNFcXVhbGl0eUNvbXBhcmVyYDFbW1N5c3RlbS5JbnQzMiwgbXNjb3JsaWIsIFZlcnNpb249NC4wLjAuMCwgQ3VsdHVyZT1uZXV0cmFsLCBQdWJsaWNLZXlUb2tlbj1iNzdhNWM1NjE5MzRlMDg5XV2sAlN5c3RlbS5Db2xsZWN0aW9ucy5HZW5lcmljLkRpY3Rpb25hcnlgMltbU3lzdGVtLkludDMyLCBtc2NvcmxpYiwgVmVyc2lvbj00LjAuMC4wLCBDdWx0dXJlPW5ldXRyYWwsIFB1YmxpY0tleVRva2VuPWI3N2E1YzU2MTkzNGUwODldLFtTeXN0ZW0uUnVudGltZS5TZXJpYWxpemF0aW9uLkZvcm1hdHRlcnMuVGVzdHMuUG9pbnQsIFN5c3RlbS5SdW50aW1lLlNlcmlhbGl6YXRpb24uRm9ybWF0dGVycy5UZXN0cywgVmVyc2lvbj00LjAuMy4wLCBDdWx0dXJlPW5ldXRyYWwsIFB1YmxpY0tleVRva2VuPTlkNzdjYzdhZDM5YjY4ZWJdXQgIygFTeXN0ZW0uQ29sbGVjdGlvbnMuR2VuZXJpYy5MaXN0YDFbW1N5c3RlbS5SdW50aW1lLlNlcmlhbGl6YXRpb24uRm9ybWF0dGVycy5UZXN0cy5Qb2ludCwgU3lzdGVtLlJ1bnRpbWUuU2VyaWFsaXphdGlvbi5Gb3JtYXR0ZXJzLlRlc3RzLCBWZXJzaW9uPTQuMC4zLjAsIEN1bHR1cmU9bmV1dHJhbCwgUHVibGljS2V5VG9rZW49OWQ3N2NjN2FkMzliNjhlYl1dAgAAAAkDAAAACgAAAAAAAAAACQQAAAAEAwAAAJEBU3lzdGVtLkNvbGxlY3Rpb25zLkdlbmVyaWMuR2VuZXJpY0VxdWFsaXR5Q29tcGFyZXJgMVtbU3lzdGVtLkludDMyLCBtc2NvcmxpYiwgVmVyc2lvbj00LjAuMC4wLCBDdWx0dXJlPW5ldXRyYWwsIFB1YmxpY0tleVRva2VuPWI3N2E1YzU2MTkzNGUwODldXQAAAAAEBAAAAMoBU3lzdGVtLkNvbGxlY3Rpb25zLkdlbmVyaWMuTGlzdGAxW1tTeXN0ZW0uUnVudGltZS5TZXJpYWxpemF0aW9uLkZvcm1hdHRlcnMuVGVzdHMuUG9pbnQsIFN5c3RlbS5SdW50aW1lLlNlcmlhbGl6YXRpb24uRm9ybWF0dGVycy5UZXN0cywgVmVyc2lvbj00LjAuMy4wLCBDdWx0dXJlPW5ldXRyYWwsIFB1YmxpY0tleVRva2VuPTlkNzdjYzdhZDM5YjY4ZWJdXQMAAAAGX2l0ZW1zBV9zaXplCF92ZXJzaW9uBAAANVN5c3RlbS5SdW50aW1lLlNlcmlhbGl6YXRpb24uRm9ybWF0dGVycy5UZXN0cy5Qb2ludFtdAgAAAAgICQUAAAAAAAAAAAAAAAcFAAAAAAEAAAAAAAAABDNTeXN0ZW0uUnVudGltZS5TZXJpYWxpemF0aW9uLkZvcm1hdHRlcnMuVGVzdHMuUG9pbnQCAAAACw==", "AAEAAAD/////AQAAAAAAAAAMAgAAAHBTeXN0ZW0uUnVudGltZS5TZXJpYWxpemF0aW9uLkZvcm1hdHRlcnMuVGVzdHMsIFZlcnNpb249NC4wLjMuMCwgQ3VsdHVyZT1uZXV0cmFsLCBQdWJsaWNLZXlUb2tlbj05ZDc3Y2M3YWQzOWI2OGViBQEAAABDU3lzdGVtLlJ1bnRpbWUuU2VyaWFsaXphdGlvbi5Gb3JtYXR0ZXJzLlRlc3RzLlNpbXBsZUtleWVkQ29sbGVjdGlvbgUAAAAaS2V5ZWRDb2xsZWN0aW9uYDIrY29tcGFyZXIWS2V5ZWRDb2xsZWN0aW9uYDIrZGljdBpLZXllZENvbGxlY3Rpb25gMitrZXlDb3VudBtLZXllZENvbGxlY3Rpb25gMit0aHJlc2hvbGQSQ29sbGVjdGlvbmAxK2l0ZW1zAwMAAAORAVN5c3RlbS5Db2xsZWN0aW9ucy5HZW5lcmljLkdlbmVyaWNFcXVhbGl0eUNvbXBhcmVyYDFbW1N5c3RlbS5JbnQzMiwgbXNjb3JsaWIsIFZlcnNpb249NC4wLjAuMCwgQ3VsdHVyZT1uZXV0cmFsLCBQdWJsaWNLZXlUb2tlbj1iNzdhNWM1NjE5MzRlMDg5XV2sAlN5c3RlbS5Db2xsZWN0aW9ucy5HZW5lcmljLkRpY3Rpb25hcnlgMltbU3lzdGVtLkludDMyLCBtc2NvcmxpYiwgVmVyc2lvbj00LjAuMC4wLCBDdWx0dXJlPW5ldXRyYWwsIFB1YmxpY0tleVRva2VuPWI3N2E1YzU2MTkzNGUwODldLFtTeXN0ZW0uUnVudGltZS5TZXJpYWxpemF0aW9uLkZvcm1hdHRlcnMuVGVzdHMuUG9pbnQsIFN5c3RlbS5SdW50aW1lLlNlcmlhbGl6YXRpb24uRm9ybWF0dGVycy5UZXN0cywgVmVyc2lvbj00LjAuMy4wLCBDdWx0dXJlPW5ldXRyYWwsIFB1YmxpY0tleVRva2VuPTlkNzdjYzdhZDM5YjY4ZWJdXQgIygFTeXN0ZW0uQ29sbGVjdGlvbnMuR2VuZXJpYy5MaXN0YDFbW1N5c3RlbS5SdW50aW1lLlNlcmlhbGl6YXRpb24uRm9ybWF0dGVycy5UZXN0cy5Qb2ludCwgU3lzdGVtLlJ1bnRpbWUuU2VyaWFsaXphdGlvbi5Gb3JtYXR0ZXJzLlRlc3RzLCBWZXJzaW9uPTQuMC4zLjAsIEN1bHR1cmU9bmV1dHJhbCwgUHVibGljS2V5VG9rZW49OWQ3N2NjN2FkMzliNjhlYl1dAgAAAAkDAAAACgAAAAAAAAAACQQAAAAEAwAAAJEBU3lzdGVtLkNvbGxlY3Rpb25zLkdlbmVyaWMuR2VuZXJpY0VxdWFsaXR5Q29tcGFyZXJgMVtbU3lzdGVtLkludDMyLCBtc2NvcmxpYiwgVmVyc2lvbj00LjAuMC4wLCBDdWx0dXJlPW5ldXRyYWwsIFB1YmxpY0tleVRva2VuPWI3N2E1YzU2MTkzNGUwODldXQAAAAAEBAAAAMoBU3lzdGVtLkNvbGxlY3Rpb25zLkdlbmVyaWMuTGlzdGAxW1tTeXN0ZW0uUnVudGltZS5TZXJpYWxpemF0aW9uLkZvcm1hdHRlcnMuVGVzdHMuUG9pbnQsIFN5c3RlbS5SdW50aW1lLlNlcmlhbGl6YXRpb24uRm9ybWF0dGVycy5UZXN0cywgVmVyc2lvbj00LjAuMy4wLCBDdWx0dXJlPW5ldXRyYWwsIFB1YmxpY0tleVRva2VuPTlkNzdjYzdhZDM5YjY4ZWJdXQMAAAAGX2l0ZW1zBV9zaXplCF92ZXJzaW9uBAAANVN5c3RlbS5SdW50aW1lLlNlcmlhbGl6YXRpb24uRm9ybWF0dGVycy5UZXN0cy5Qb2ludFtdAgAAAAgICQUAAAAAAAAAAAAAAAcFAAAAAAEAAAAAAAAABDNTeXN0ZW0uUnVudGltZS5TZXJpYWxpemF0aW9uLkZvcm1hdHRlcnMuVGVzdHMuUG9pbnQCAAAACw==" } };
@@ -530,8 +530,8 @@ namespace System.Runtime.Serialization.Formatters.Tests
yield return new object[] { new SortedList<int, string>(dictionary, Comparer<int>.Default), new string[] { "AAEAAAD/////AQAAAAAAAAAMAgAAAElTeXN0ZW0sIFZlcnNpb249NC4wLjAuMCwgQ3VsdHVyZT1uZXV0cmFsLCBQdWJsaWNLZXlUb2tlbj1iNzdhNWM1NjE5MzRlMDg5DAMAAABVU3lzdGVtLkNvbGxlY3Rpb25zLCBWZXJzaW9uPTQuMS4xLjAsIEN1bHR1cmU9bmV1dHJhbCwgUHVibGljS2V5VG9rZW49YjAzZjVmN2YxMWQ1MGEzYQUBAAAA4QFTeXN0ZW0uQ29sbGVjdGlvbnMuR2VuZXJpYy5Tb3J0ZWRMaXN0YDJbW1N5c3RlbS5JbnQzMiwgbXNjb3JsaWIsIFZlcnNpb249NC4wLjAuMCwgQ3VsdHVyZT1uZXV0cmFsLCBQdWJsaWNLZXlUb2tlbj1iNzdhNWM1NjE5MzRlMDg5XSxbU3lzdGVtLlN0cmluZywgbXNjb3JsaWIsIFZlcnNpb249NC4wLjAuMCwgQ3VsdHVyZT1uZXV0cmFsLCBQdWJsaWNLZXlUb2tlbj1iNzdhNWM1NjE5MzRlMDg5XV0HAAAABGtleXMGdmFsdWVzBV9zaXplB3ZlcnNpb24IY29tcGFyZXIHa2V5TGlzdAl2YWx1ZUxpc3QHBgAAAwQECAgIiQFTeXN0ZW0uQ29sbGVjdGlvbnMuR2VuZXJpYy5HZW5lcmljQ29tcGFyZXJgMVtbU3lzdGVtLkludDMyLCBtc2NvcmxpYiwgVmVyc2lvbj00LjAuMC4wLCBDdWx0dXJlPW5ldXRyYWwsIFB1YmxpY0tleVRva2VuPWI3N2E1YzU2MTkzNGUwODldXekBU3lzdGVtLkNvbGxlY3Rpb25zLkdlbmVyaWMuU29ydGVkTGlzdGAyK0tleUxpc3RbW1N5c3RlbS5JbnQzMiwgbXNjb3JsaWIsIFZlcnNpb249NC4wLjAuMCwgQ3VsdHVyZT1uZXV0cmFsLCBQdWJsaWNLZXlUb2tlbj1iNzdhNWM1NjE5MzRlMDg5XSxbU3lzdGVtLlN0cmluZywgbXNjb3JsaWIsIFZlcnNpb249NC4wLjAuMCwgQ3VsdHVyZT1uZXV0cmFsLCBQdWJsaWNLZXlUb2tlbj1iNzdhNWM1NjE5MzRlMDg5XV0DAAAA6wFTeXN0ZW0uQ29sbGVjdGlvbnMuR2VuZXJpYy5Tb3J0ZWRMaXN0YDIrVmFsdWVMaXN0W1tTeXN0ZW0uSW50MzIsIG1zY29ybGliLCBWZXJzaW9uPTQuMC4wLjAsIEN1bHR1cmU9bmV1dHJhbCwgUHVibGljS2V5VG9rZW49Yjc3YTVjNTYxOTM0ZTA4OV0sW1N5c3RlbS5TdHJpbmcsIG1zY29ybGliLCBWZXJzaW9uPTQuMC4wLjAsIEN1bHR1cmU9bmV1dHJhbCwgUHVibGljS2V5VG9rZW49Yjc3YTVjNTYxOTM0ZTA4OV1dAwAAAAIAAAAJBAAAAAkFAAAAAgAAAAAAAAAJBgAAAAoKDwQAAAACAAAACAEAAAACAAAAEQUAAAACAAAABgcAAAAEdGVzdAYIAAAADGFub3RoZXIgdGVzdAQGAAAAiQFTeXN0ZW0uQ29sbGVjdGlvbnMuR2VuZXJpYy5HZW5lcmljQ29tcGFyZXJgMVtbU3lzdGVtLkludDMyLCBtc2NvcmxpYiwgVmVyc2lvbj00LjAuMC4wLCBDdWx0dXJlPW5ldXRyYWwsIFB1YmxpY0tleVRva2VuPWI3N2E1YzU2MTkzNGUwODldXQAAAAAL", "AAEAAAD/////AQAAAAAAAAAMAgAAAElTeXN0ZW0sIFZlcnNpb249NC4wLjAuMCwgQ3VsdHVyZT1uZXV0cmFsLCBQdWJsaWNLZXlUb2tlbj1iNzdhNWM1NjE5MzRlMDg5BQEAAADhAVN5c3RlbS5Db2xsZWN0aW9ucy5HZW5lcmljLlNvcnRlZExpc3RgMltbU3lzdGVtLkludDMyLCBtc2NvcmxpYiwgVmVyc2lvbj00LjAuMC4wLCBDdWx0dXJlPW5ldXRyYWwsIFB1YmxpY0tleVRva2VuPWI3N2E1YzU2MTkzNGUwODldLFtTeXN0ZW0uU3RyaW5nLCBtc2NvcmxpYiwgVmVyc2lvbj00LjAuMC4wLCBDdWx0dXJlPW5ldXRyYWwsIFB1YmxpY0tleVRva2VuPWI3N2E1YzU2MTkzNGUwODldXQcAAAAEa2V5cwZ2YWx1ZXMFX3NpemUHdmVyc2lvbghjb21wYXJlcgdrZXlMaXN0CXZhbHVlTGlzdAcGAAADBAQICAiJAVN5c3RlbS5Db2xsZWN0aW9ucy5HZW5lcmljLkdlbmVyaWNDb21wYXJlcmAxW1tTeXN0ZW0uSW50MzIsIG1zY29ybGliLCBWZXJzaW9uPTQuMC4wLjAsIEN1bHR1cmU9bmV1dHJhbCwgUHVibGljS2V5VG9rZW49Yjc3YTVjNTYxOTM0ZTA4OV1d6QFTeXN0ZW0uQ29sbGVjdGlvbnMuR2VuZXJpYy5Tb3J0ZWRMaXN0YDIrS2V5TGlzdFtbU3lzdGVtLkludDMyLCBtc2NvcmxpYiwgVmVyc2lvbj00LjAuMC4wLCBDdWx0dXJlPW5ldXRyYWwsIFB1YmxpY0tleVRva2VuPWI3N2E1YzU2MTkzNGUwODldLFtTeXN0ZW0uU3RyaW5nLCBtc2NvcmxpYiwgVmVyc2lvbj00LjAuMC4wLCBDdWx0dXJlPW5ldXRyYWwsIFB1YmxpY0tleVRva2VuPWI3N2E1YzU2MTkzNGUwODldXQIAAADrAVN5c3RlbS5Db2xsZWN0aW9ucy5HZW5lcmljLlNvcnRlZExpc3RgMitWYWx1ZUxpc3RbW1N5c3RlbS5JbnQzMiwgbXNjb3JsaWIsIFZlcnNpb249NC4wLjAuMCwgQ3VsdHVyZT1uZXV0cmFsLCBQdWJsaWNLZXlUb2tlbj1iNzdhNWM1NjE5MzRlMDg5XSxbU3lzdGVtLlN0cmluZywgbXNjb3JsaWIsIFZlcnNpb249NC4wLjAuMCwgQ3VsdHVyZT1uZXV0cmFsLCBQdWJsaWNLZXlUb2tlbj1iNzdhNWM1NjE5MzRlMDg5XV0CAAAAAgAAAAkDAAAACQQAAAACAAAAAAAAAAkFAAAACgoPAwAAAAIAAAAIAQAAAAIAAAARBAAAAAIAAAAGBgAAAAR0ZXN0BgcAAAAMYW5vdGhlciB0ZXN0BAUAAACJAVN5c3RlbS5Db2xsZWN0aW9ucy5HZW5lcmljLkdlbmVyaWNDb21wYXJlcmAxW1tTeXN0ZW0uSW50MzIsIG1zY29ybGliLCBWZXJzaW9uPTQuMC4wLjAsIEN1bHR1cmU9bmV1dHJhbCwgUHVibGljS2V5VG9rZW49Yjc3YTVjNTYxOTM0ZTA4OV1dAAAAAAs=" } };
yield return new object[] { new Queue<int>(Enumerable.Range(1, 10)), new string[] { "AAEAAAD/////AQAAAAAAAAAMAgAAAElTeXN0ZW0sIFZlcnNpb249NC4wLjAuMCwgQ3VsdHVyZT1uZXV0cmFsLCBQdWJsaWNLZXlUb2tlbj1iNzdhNWM1NjE5MzRlMDg5BQEAAAB/U3lzdGVtLkNvbGxlY3Rpb25zLkdlbmVyaWMuUXVldWVgMVtbU3lzdGVtLkludDMyLCBtc2NvcmxpYiwgVmVyc2lvbj00LjAuMC4wLCBDdWx0dXJlPW5ldXRyYWwsIFB1YmxpY0tleVRva2VuPWI3N2E1YzU2MTkzNGUwODldXQUAAAAGX2FycmF5BV9oZWFkBV90YWlsBV9zaXplCF92ZXJzaW9uBwAAAAAICAgICAIAAAAJAwAAAAAAAAAKAAAACgAAAAAAAAAPAwAAABAAAAAIAQAAAAIAAAADAAAABAAAAAUAAAAGAAAABwAAAAgAAAAJAAAACgAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAs=", "AAEAAAD/////AQAAAAAAAAAMAgAAAElTeXN0ZW0sIFZlcnNpb249NC4wLjAuMCwgQ3VsdHVyZT1uZXV0cmFsLCBQdWJsaWNLZXlUb2tlbj1iNzdhNWM1NjE5MzRlMDg5BQEAAAB/U3lzdGVtLkNvbGxlY3Rpb25zLkdlbmVyaWMuUXVldWVgMVtbU3lzdGVtLkludDMyLCBtc2NvcmxpYiwgVmVyc2lvbj00LjAuMC4wLCBDdWx0dXJlPW5ldXRyYWwsIFB1YmxpY0tleVRva2VuPWI3N2E1YzU2MTkzNGUwODldXQUAAAAGX2FycmF5BV9oZWFkBV90YWlsBV9zaXplCF92ZXJzaW9uBwAAAAAICAgICAIAAAAJAwAAAAAAAAAKAAAACgAAAAwAAAAPAwAAABAAAAAIAQAAAAIAAAADAAAABAAAAAUAAAAGAAAABwAAAAgAAAAJAAAACgAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAs=" } };
var observableCollection = new System.Collections.ObjectModel.ObservableCollection<int>(Enumerable.Range(1, 5));
- yield return new object[] { observableCollection, new string[] { "AAEAAAD/////AQAAAAAAAAAMAgAAAE5XaW5kb3dzQmFzZSwgVmVyc2lvbj0zLjAuMC4wLCBDdWx0dXJlPU5ldXRyYWwsIFB1YmxpY0tleVRva2VuPTMxYmYzODU2YWQzNjRlMzUFAQAAAJIBU3lzdGVtLkNvbGxlY3Rpb25zLk9iamVjdE1vZGVsLk9ic2VydmFibGVDb2xsZWN0aW9uYDFbW1N5c3RlbS5JbnQzMiwgbXNjb3JsaWIsIFZlcnNpb249NC4wLjAuMCwgQ3VsdHVyZT1uZXV0cmFsLCBQdWJsaWNLZXlUb2tlbj1iNzdhNWM1NjE5MzRlMDg5XV0CAAAACF9tb25pdG9yEkNvbGxlY3Rpb25gMStpdGVtcwQDoAFTeXN0ZW0uQ29sbGVjdGlvbnMuT2JqZWN0TW9kZWwuT2JzZXJ2YWJsZUNvbGxlY3Rpb25gMStTaW1wbGVNb25pdG9yW1tTeXN0ZW0uSW50MzIsIG1zY29ybGliLCBWZXJzaW9uPTQuMC4wLjAsIEN1bHR1cmU9bmV1dHJhbCwgUHVibGljS2V5VG9rZW49Yjc3YTVjNTYxOTM0ZTA4OV1dAgAAAH5TeXN0ZW0uQ29sbGVjdGlvbnMuR2VuZXJpYy5MaXN0YDFbW1N5c3RlbS5JbnQzMiwgbXNjb3JsaWIsIFZlcnNpb249NC4wLjAuMCwgQ3VsdHVyZT1uZXV0cmFsLCBQdWJsaWNLZXlUb2tlbj1iNzdhNWM1NjE5MzRlMDg5XV0CAAAACQMAAAAJBAAAAAUDAAAAoAFTeXN0ZW0uQ29sbGVjdGlvbnMuT2JqZWN0TW9kZWwuT2JzZXJ2YWJsZUNvbGxlY3Rpb25gMStTaW1wbGVNb25pdG9yW1tTeXN0ZW0uSW50MzIsIG1zY29ybGliLCBWZXJzaW9uPTQuMC4wLjAsIEN1bHR1cmU9bmV1dHJhbCwgUHVibGljS2V5VG9rZW49Yjc3YTVjNTYxOTM0ZTA4OV1dAQAAAApfYnVzeUNvdW50AAgCAAAAAAAAAAQEAAAAflN5c3RlbS5Db2xsZWN0aW9ucy5HZW5lcmljLkxpc3RgMVtbU3lzdGVtLkludDMyLCBtc2NvcmxpYiwgVmVyc2lvbj00LjAuMC4wLCBDdWx0dXJlPW5ldXRyYWwsIFB1YmxpY0tleVRva2VuPWI3N2E1YzU2MTkzNGUwODldXQMAAAAGX2l0ZW1zBV9zaXplCF92ZXJzaW9uBwAACAgICQUAAAAFAAAAAQAAAA8FAAAACAAAAAgBAAAAAgAAAAMAAAAEAAAABQAAAAAAAAAAAAAAAAAAAAs=", "AAEAAAD/////AQAAAAAAAAAMAgAAAE5XaW5kb3dzQmFzZSwgVmVyc2lvbj0zLjAuMC4wLCBDdWx0dXJlPU5ldXRyYWwsIFB1YmxpY0tleVRva2VuPTMxYmYzODU2YWQzNjRlMzUFAQAAAJIBU3lzdGVtLkNvbGxlY3Rpb25zLk9iamVjdE1vZGVsLk9ic2VydmFibGVDb2xsZWN0aW9uYDFbW1N5c3RlbS5JbnQzMiwgbXNjb3JsaWIsIFZlcnNpb249NC4wLjAuMCwgQ3VsdHVyZT1uZXV0cmFsLCBQdWJsaWNLZXlUb2tlbj1iNzdhNWM1NjE5MzRlMDg5XV0CAAAACF9tb25pdG9yEkNvbGxlY3Rpb25gMStpdGVtcwQDoAFTeXN0ZW0uQ29sbGVjdGlvbnMuT2JqZWN0TW9kZWwuT2JzZXJ2YWJsZUNvbGxlY3Rpb25gMStTaW1wbGVNb25pdG9yW1tTeXN0ZW0uSW50MzIsIG1zY29ybGliLCBWZXJzaW9uPTQuMC4wLjAsIEN1bHR1cmU9bmV1dHJhbCwgUHVibGljS2V5VG9rZW49Yjc3YTVjNTYxOTM0ZTA4OV1dAgAAAH5TeXN0ZW0uQ29sbGVjdGlvbnMuR2VuZXJpYy5MaXN0YDFbW1N5c3RlbS5JbnQzMiwgbXNjb3JsaWIsIFZlcnNpb249NC4wLjAuMCwgQ3VsdHVyZT1uZXV0cmFsLCBQdWJsaWNLZXlUb2tlbj1iNzdhNWM1NjE5MzRlMDg5XV0CAAAACQMAAAAJBAAAAAUDAAAAoAFTeXN0ZW0uQ29sbGVjdGlvbnMuT2JqZWN0TW9kZWwuT2JzZXJ2YWJsZUNvbGxlY3Rpb25gMStTaW1wbGVNb25pdG9yW1tTeXN0ZW0uSW50MzIsIG1zY29ybGliLCBWZXJzaW9uPTQuMC4wLjAsIEN1bHR1cmU9bmV1dHJhbCwgUHVibGljS2V5VG9rZW49Yjc3YTVjNTYxOTM0ZTA4OV1dAQAAAApfYnVzeUNvdW50AAgCAAAAAAAAAAQEAAAAflN5c3RlbS5Db2xsZWN0aW9ucy5HZW5lcmljLkxpc3RgMVtbU3lzdGVtLkludDMyLCBtc2NvcmxpYiwgVmVyc2lvbj00LjAuMC4wLCBDdWx0dXJlPW5ldXRyYWwsIFB1YmxpY0tleVRva2VuPWI3N2E1YzU2MTkzNGUwODldXQMAAAAGX2l0ZW1zBV9zaXplCF92ZXJzaW9uBwAACAgICQUAAAAFAAAABQAAAA8FAAAACAAAAAgBAAAAAgAAAAMAAAAEAAAABQAAAAAAAAAAAAAAAAAAAAs=" } };
- yield return new object[] { new System.Collections.ObjectModel.ReadOnlyObservableCollection<int>(observableCollection), new string[] { "AAEAAAD/////AQAAAAAAAAAMAgAAAE5XaW5kb3dzQmFzZSwgVmVyc2lvbj0zLjAuMC4wLCBDdWx0dXJlPU5ldXRyYWwsIFB1YmxpY0tleVRva2VuPTMxYmYzODU2YWQzNjRlMzUFAQAAAJoBU3lzdGVtLkNvbGxlY3Rpb25zLk9iamVjdE1vZGVsLlJlYWRPbmx5T2JzZXJ2YWJsZUNvbGxlY3Rpb25gMVtbU3lzdGVtLkludDMyLCBtc2NvcmxpYiwgVmVyc2lvbj00LjAuMC4wLCBDdWx0dXJlPW5ldXRyYWwsIFB1YmxpY0tleVRva2VuPWI3N2E1YzU2MTkzNGUwODldXQEAAAAZUmVhZE9ubHlDb2xsZWN0aW9uYDErbGlzdASSAVN5c3RlbS5Db2xsZWN0aW9ucy5PYmplY3RNb2RlbC5PYnNlcnZhYmxlQ29sbGVjdGlvbmAxW1tTeXN0ZW0uSW50MzIsIG1zY29ybGliLCBWZXJzaW9uPTQuMC4wLjAsIEN1bHR1cmU9bmV1dHJhbCwgUHVibGljS2V5VG9rZW49Yjc3YTVjNTYxOTM0ZTA4OV1dAgAAAAIAAAAJAwAAAAUDAAAAkgFTeXN0ZW0uQ29sbGVjdGlvbnMuT2JqZWN0TW9kZWwuT2JzZXJ2YWJsZUNvbGxlY3Rpb25gMVtbU3lzdGVtLkludDMyLCBtc2NvcmxpYiwgVmVyc2lvbj00LjAuMC4wLCBDdWx0dXJlPW5ldXRyYWwsIFB1YmxpY0tleVRva2VuPWI3N2E1YzU2MTkzNGUwODldXQIAAAAIX21vbml0b3ISQ29sbGVjdGlvbmAxK2l0ZW1zBAOgAVN5c3RlbS5Db2xsZWN0aW9ucy5PYmplY3RNb2RlbC5PYnNlcnZhYmxlQ29sbGVjdGlvbmAxK1NpbXBsZU1vbml0b3JbW1N5c3RlbS5JbnQzMiwgbXNjb3JsaWIsIFZlcnNpb249NC4wLjAuMCwgQ3VsdHVyZT1uZXV0cmFsLCBQdWJsaWNLZXlUb2tlbj1iNzdhNWM1NjE5MzRlMDg5XV0CAAAAflN5c3RlbS5Db2xsZWN0aW9ucy5HZW5lcmljLkxpc3RgMVtbU3lzdGVtLkludDMyLCBtc2NvcmxpYiwgVmVyc2lvbj00LjAuMC4wLCBDdWx0dXJlPW5ldXRyYWwsIFB1YmxpY0tleVRva2VuPWI3N2E1YzU2MTkzNGUwODldXQIAAAAJBAAAAAkFAAAABQQAAACgAVN5c3RlbS5Db2xsZWN0aW9ucy5PYmplY3RNb2RlbC5PYnNlcnZhYmxlQ29sbGVjdGlvbmAxK1NpbXBsZU1vbml0b3JbW1N5c3RlbS5JbnQzMiwgbXNjb3JsaWIsIFZlcnNpb249NC4wLjAuMCwgQ3VsdHVyZT1uZXV0cmFsLCBQdWJsaWNLZXlUb2tlbj1iNzdhNWM1NjE5MzRlMDg5XV0BAAAACl9idXN5Q291bnQACAIAAAAAAAAABAUAAAB+U3lzdGVtLkNvbGxlY3Rpb25zLkdlbmVyaWMuTGlzdGAxW1tTeXN0ZW0uSW50MzIsIG1zY29ybGliLCBWZXJzaW9uPTQuMC4wLjAsIEN1bHR1cmU9bmV1dHJhbCwgUHVibGljS2V5VG9rZW49Yjc3YTVjNTYxOTM0ZTA4OV1dAwAAAAZfaXRlbXMFX3NpemUIX3ZlcnNpb24HAAAICAgJBgAAAAUAAAABAAAADwYAAAAIAAAACAEAAAACAAAAAwAAAAQAAAAFAAAAAAAAAAAAAAAAAAAACw==", "AAEAAAD/////AQAAAAAAAAAMAgAAAE5XaW5kb3dzQmFzZSwgVmVyc2lvbj0zLjAuMC4wLCBDdWx0dXJlPU5ldXRyYWwsIFB1YmxpY0tleVRva2VuPTMxYmYzODU2YWQzNjRlMzUFAQAAAJoBU3lzdGVtLkNvbGxlY3Rpb25zLk9iamVjdE1vZGVsLlJlYWRPbmx5T2JzZXJ2YWJsZUNvbGxlY3Rpb25gMVtbU3lzdGVtLkludDMyLCBtc2NvcmxpYiwgVmVyc2lvbj00LjAuMC4wLCBDdWx0dXJlPW5ldXRyYWwsIFB1YmxpY0tleVRva2VuPWI3N2E1YzU2MTkzNGUwODldXQEAAAAZUmVhZE9ubHlDb2xsZWN0aW9uYDErbGlzdASSAVN5c3RlbS5Db2xsZWN0aW9ucy5PYmplY3RNb2RlbC5PYnNlcnZhYmxlQ29sbGVjdGlvbmAxW1tTeXN0ZW0uSW50MzIsIG1zY29ybGliLCBWZXJzaW9uPTQuMC4wLjAsIEN1bHR1cmU9bmV1dHJhbCwgUHVibGljS2V5VG9rZW49Yjc3YTVjNTYxOTM0ZTA4OV1dAgAAAAIAAAAJAwAAAAUDAAAAkgFTeXN0ZW0uQ29sbGVjdGlvbnMuT2JqZWN0TW9kZWwuT2JzZXJ2YWJsZUNvbGxlY3Rpb25gMVtbU3lzdGVtLkludDMyLCBtc2NvcmxpYiwgVmVyc2lvbj00LjAuMC4wLCBDdWx0dXJlPW5ldXRyYWwsIFB1YmxpY0tleVRva2VuPWI3N2E1YzU2MTkzNGUwODldXQIAAAAIX21vbml0b3ISQ29sbGVjdGlvbmAxK2l0ZW1zBAOgAVN5c3RlbS5Db2xsZWN0aW9ucy5PYmplY3RNb2RlbC5PYnNlcnZhYmxlQ29sbGVjdGlvbmAxK1NpbXBsZU1vbml0b3JbW1N5c3RlbS5JbnQzMiwgbXNjb3JsaWIsIFZlcnNpb249NC4wLjAuMCwgQ3VsdHVyZT1uZXV0cmFsLCBQdWJsaWNLZXlUb2tlbj1iNzdhNWM1NjE5MzRlMDg5XV0CAAAAflN5c3RlbS5Db2xsZWN0aW9ucy5HZW5lcmljLkxpc3RgMVtbU3lzdGVtLkludDMyLCBtc2NvcmxpYiwgVmVyc2lvbj00LjAuMC4wLCBDdWx0dXJlPW5ldXRyYWwsIFB1YmxpY0tleVRva2VuPWI3N2E1YzU2MTkzNGUwODldXQIAAAAJBAAAAAkFAAAABQQAAACgAVN5c3RlbS5Db2xsZWN0aW9ucy5PYmplY3RNb2RlbC5PYnNlcnZhYmxlQ29sbGVjdGlvbmAxK1NpbXBsZU1vbml0b3JbW1N5c3RlbS5JbnQzMiwgbXNjb3JsaWIsIFZlcnNpb249NC4wLjAuMCwgQ3VsdHVyZT1uZXV0cmFsLCBQdWJsaWNLZXlUb2tlbj1iNzdhNWM1NjE5MzRlMDg5XV0BAAAACl9idXN5Q291bnQACAIAAAAAAAAABAUAAAB+U3lzdGVtLkNvbGxlY3Rpb25zLkdlbmVyaWMuTGlzdGAxW1tTeXN0ZW0uSW50MzIsIG1zY29ybGliLCBWZXJzaW9uPTQuMC4wLjAsIEN1bHR1cmU9bmV1dHJhbCwgUHVibGljS2V5VG9rZW49Yjc3YTVjNTYxOTM0ZTA4OV1dAwAAAAZfaXRlbXMFX3NpemUIX3ZlcnNpb24HAAAICAgJBgAAAAUAAAAFAAAADwYAAAAIAAAACAEAAAACAAAAAwAAAAQAAAAFAAAAAAAAAAAAAAAAAAAACw==" } };
+ yield return new object[] { observableCollection, new string[] { "AAEAAAD/////AQAAAAAAAAAMAgAAAE5XaW5kb3dzQmFzZSwgVmVyc2lvbj0zLjAuMC4wLCBDdWx0dXJlPW5ldXRyYWwsIFB1YmxpY0tleVRva2VuPTMxYmYzODU2YWQzNjRlMzUFAQAAAJIBU3lzdGVtLkNvbGxlY3Rpb25zLk9iamVjdE1vZGVsLk9ic2VydmFibGVDb2xsZWN0aW9uYDFbW1N5c3RlbS5JbnQzMiwgbXNjb3JsaWIsIFZlcnNpb249NC4wLjAuMCwgQ3VsdHVyZT1uZXV0cmFsLCBQdWJsaWNLZXlUb2tlbj1iNzdhNWM1NjE5MzRlMDg5XV0CAAAACF9tb25pdG9yEkNvbGxlY3Rpb25gMStpdGVtcwQDoAFTeXN0ZW0uQ29sbGVjdGlvbnMuT2JqZWN0TW9kZWwuT2JzZXJ2YWJsZUNvbGxlY3Rpb25gMStTaW1wbGVNb25pdG9yW1tTeXN0ZW0uSW50MzIsIG1zY29ybGliLCBWZXJzaW9uPTQuMC4wLjAsIEN1bHR1cmU9bmV1dHJhbCwgUHVibGljS2V5VG9rZW49Yjc3YTVjNTYxOTM0ZTA4OV1dAgAAAH5TeXN0ZW0uQ29sbGVjdGlvbnMuR2VuZXJpYy5MaXN0YDFbW1N5c3RlbS5JbnQzMiwgbXNjb3JsaWIsIFZlcnNpb249NC4wLjAuMCwgQ3VsdHVyZT1uZXV0cmFsLCBQdWJsaWNLZXlUb2tlbj1iNzdhNWM1NjE5MzRlMDg5XV0CAAAACQMAAAAJBAAAAAUDAAAAoAFTeXN0ZW0uQ29sbGVjdGlvbnMuT2JqZWN0TW9kZWwuT2JzZXJ2YWJsZUNvbGxlY3Rpb25gMStTaW1wbGVNb25pdG9yW1tTeXN0ZW0uSW50MzIsIG1zY29ybGliLCBWZXJzaW9uPTQuMC4wLjAsIEN1bHR1cmU9bmV1dHJhbCwgUHVibGljS2V5VG9rZW49Yjc3YTVjNTYxOTM0ZTA4OV1dAQAAAApfYnVzeUNvdW50AAgCAAAAAAAAAAQEAAAAflN5c3RlbS5Db2xsZWN0aW9ucy5HZW5lcmljLkxpc3RgMVtbU3lzdGVtLkludDMyLCBtc2NvcmxpYiwgVmVyc2lvbj00LjAuMC4wLCBDdWx0dXJlPW5ldXRyYWwsIFB1YmxpY0tleVRva2VuPWI3N2E1YzU2MTkzNGUwODldXQMAAAAGX2l0ZW1zBV9zaXplCF92ZXJzaW9uBwAACAgICQUAAAAFAAAAAQAAAA8FAAAACAAAAAgBAAAAAgAAAAMAAAAEAAAABQAAAAAAAAAAAAAAAAAAAAs=", "AAEAAAD/////AQAAAAAAAAAMAgAAAE5XaW5kb3dzQmFzZSwgVmVyc2lvbj0zLjAuMC4wLCBDdWx0dXJlPU5ldXRyYWwsIFB1YmxpY0tleVRva2VuPTMxYmYzODU2YWQzNjRlMzUFAQAAAJIBU3lzdGVtLkNvbGxlY3Rpb25zLk9iamVjdE1vZGVsLk9ic2VydmFibGVDb2xsZWN0aW9uYDFbW1N5c3RlbS5JbnQzMiwgbXNjb3JsaWIsIFZlcnNpb249NC4wLjAuMCwgQ3VsdHVyZT1uZXV0cmFsLCBQdWJsaWNLZXlUb2tlbj1iNzdhNWM1NjE5MzRlMDg5XV0CAAAACF9tb25pdG9yEkNvbGxlY3Rpb25gMStpdGVtcwQDoAFTeXN0ZW0uQ29sbGVjdGlvbnMuT2JqZWN0TW9kZWwuT2JzZXJ2YWJsZUNvbGxlY3Rpb25gMStTaW1wbGVNb25pdG9yW1tTeXN0ZW0uSW50MzIsIG1zY29ybGliLCBWZXJzaW9uPTQuMC4wLjAsIEN1bHR1cmU9bmV1dHJhbCwgUHVibGljS2V5VG9rZW49Yjc3YTVjNTYxOTM0ZTA4OV1dAgAAAH5TeXN0ZW0uQ29sbGVjdGlvbnMuR2VuZXJpYy5MaXN0YDFbW1N5c3RlbS5JbnQzMiwgbXNjb3JsaWIsIFZlcnNpb249NC4wLjAuMCwgQ3VsdHVyZT1uZXV0cmFsLCBQdWJsaWNLZXlUb2tlbj1iNzdhNWM1NjE5MzRlMDg5XV0CAAAACQMAAAAJBAAAAAUDAAAAoAFTeXN0ZW0uQ29sbGVjdGlvbnMuT2JqZWN0TW9kZWwuT2JzZXJ2YWJsZUNvbGxlY3Rpb25gMStTaW1wbGVNb25pdG9yW1tTeXN0ZW0uSW50MzIsIG1zY29ybGliLCBWZXJzaW9uPTQuMC4wLjAsIEN1bHR1cmU9bmV1dHJhbCwgUHVibGljS2V5VG9rZW49Yjc3YTVjNTYxOTM0ZTA4OV1dAQAAAApfYnVzeUNvdW50AAgCAAAAAAAAAAQEAAAAflN5c3RlbS5Db2xsZWN0aW9ucy5HZW5lcmljLkxpc3RgMVtbU3lzdGVtLkludDMyLCBtc2NvcmxpYiwgVmVyc2lvbj00LjAuMC4wLCBDdWx0dXJlPW5ldXRyYWwsIFB1YmxpY0tleVRva2VuPWI3N2E1YzU2MTkzNGUwODldXQMAAAAGX2l0ZW1zBV9zaXplCF92ZXJzaW9uBwAACAgICQUAAAAFAAAABQAAAA8FAAAACAAAAAgBAAAAAgAAAAMAAAAEAAAABQAAAAAAAAAAAAAAAAAAAAs=" } };
+ yield return new object[] { new System.Collections.ObjectModel.ReadOnlyObservableCollection<int>(observableCollection), new string[] { "AAEAAAD/////AQAAAAAAAAAMAgAAAE5XaW5kb3dzQmFzZSwgVmVyc2lvbj0zLjAuMC4wLCBDdWx0dXJlPW5ldXRyYWwsIFB1YmxpY0tleVRva2VuPTMxYmYzODU2YWQzNjRlMzUFAQAAAJoBU3lzdGVtLkNvbGxlY3Rpb25zLk9iamVjdE1vZGVsLlJlYWRPbmx5T2JzZXJ2YWJsZUNvbGxlY3Rpb25gMVtbU3lzdGVtLkludDMyLCBtc2NvcmxpYiwgVmVyc2lvbj00LjAuMC4wLCBDdWx0dXJlPW5ldXRyYWwsIFB1YmxpY0tleVRva2VuPWI3N2E1YzU2MTkzNGUwODldXQEAAAAZUmVhZE9ubHlDb2xsZWN0aW9uYDErbGlzdASSAVN5c3RlbS5Db2xsZWN0aW9ucy5PYmplY3RNb2RlbC5PYnNlcnZhYmxlQ29sbGVjdGlvbmAxW1tTeXN0ZW0uSW50MzIsIG1zY29ybGliLCBWZXJzaW9uPTQuMC4wLjAsIEN1bHR1cmU9bmV1dHJhbCwgUHVibGljS2V5VG9rZW49Yjc3YTVjNTYxOTM0ZTA4OV1dAgAAAAIAAAAJAwAAAAUDAAAAkgFTeXN0ZW0uQ29sbGVjdGlvbnMuT2JqZWN0TW9kZWwuT2JzZXJ2YWJsZUNvbGxlY3Rpb25gMVtbU3lzdGVtLkludDMyLCBtc2NvcmxpYiwgVmVyc2lvbj00LjAuMC4wLCBDdWx0dXJlPW5ldXRyYWwsIFB1YmxpY0tleVRva2VuPWI3N2E1YzU2MTkzNGUwODldXQIAAAAIX21vbml0b3ISQ29sbGVjdGlvbmAxK2l0ZW1zBAOgAVN5c3RlbS5Db2xsZWN0aW9ucy5PYmplY3RNb2RlbC5PYnNlcnZhYmxlQ29sbGVjdGlvbmAxK1NpbXBsZU1vbml0b3JbW1N5c3RlbS5JbnQzMiwgbXNjb3JsaWIsIFZlcnNpb249NC4wLjAuMCwgQ3VsdHVyZT1uZXV0cmFsLCBQdWJsaWNLZXlUb2tlbj1iNzdhNWM1NjE5MzRlMDg5XV0CAAAAflN5c3RlbS5Db2xsZWN0aW9ucy5HZW5lcmljLkxpc3RgMVtbU3lzdGVtLkludDMyLCBtc2NvcmxpYiwgVmVyc2lvbj00LjAuMC4wLCBDdWx0dXJlPW5ldXRyYWwsIFB1YmxpY0tleVRva2VuPWI3N2E1YzU2MTkzNGUwODldXQIAAAAJBAAAAAkFAAAABQQAAACgAVN5c3RlbS5Db2xsZWN0aW9ucy5PYmplY3RNb2RlbC5PYnNlcnZhYmxlQ29sbGVjdGlvbmAxK1NpbXBsZU1vbml0b3JbW1N5c3RlbS5JbnQzMiwgbXNjb3JsaWIsIFZlcnNpb249NC4wLjAuMCwgQ3VsdHVyZT1uZXV0cmFsLCBQdWJsaWNLZXlUb2tlbj1iNzdhNWM1NjE5MzRlMDg5XV0BAAAACl9idXN5Q291bnQACAIAAAAAAAAABAUAAAB+U3lzdGVtLkNvbGxlY3Rpb25zLkdlbmVyaWMuTGlzdGAxW1tTeXN0ZW0uSW50MzIsIG1zY29ybGliLCBWZXJzaW9uPTQuMC4wLjAsIEN1bHR1cmU9bmV1dHJhbCwgUHVibGljS2V5VG9rZW49Yjc3YTVjNTYxOTM0ZTA4OV1dAwAAAAZfaXRlbXMFX3NpemUIX3ZlcnNpb24HAAAICAgJBgAAAAUAAAABAAAADwYAAAAIAAAACAEAAAACAAAAAwAAAAQAAAAFAAAAAAAAAAAAAAAAAAAACw==", "AAEAAAD/////AQAAAAAAAAAMAgAAAE5XaW5kb3dzQmFzZSwgVmVyc2lvbj0zLjAuMC4wLCBDdWx0dXJlPU5ldXRyYWwsIFB1YmxpY0tleVRva2VuPTMxYmYzODU2YWQzNjRlMzUFAQAAAJoBU3lzdGVtLkNvbGxlY3Rpb25zLk9iamVjdE1vZGVsLlJlYWRPbmx5T2JzZXJ2YWJsZUNvbGxlY3Rpb25gMVtbU3lzdGVtLkludDMyLCBtc2NvcmxpYiwgVmVyc2lvbj00LjAuMC4wLCBDdWx0dXJlPW5ldXRyYWwsIFB1YmxpY0tleVRva2VuPWI3N2E1YzU2MTkzNGUwODldXQEAAAAZUmVhZE9ubHlDb2xsZWN0aW9uYDErbGlzdASSAVN5c3RlbS5Db2xsZWN0aW9ucy5PYmplY3RNb2RlbC5PYnNlcnZhYmxlQ29sbGVjdGlvbmAxW1tTeXN0ZW0uSW50MzIsIG1zY29ybGliLCBWZXJzaW9uPTQuMC4wLjAsIEN1bHR1cmU9bmV1dHJhbCwgUHVibGljS2V5VG9rZW49Yjc3YTVjNTYxOTM0ZTA4OV1dAgAAAAIAAAAJAwAAAAUDAAAAkgFTeXN0ZW0uQ29sbGVjdGlvbnMuT2JqZWN0TW9kZWwuT2JzZXJ2YWJsZUNvbGxlY3Rpb25gMVtbU3lzdGVtLkludDMyLCBtc2NvcmxpYiwgVmVyc2lvbj00LjAuMC4wLCBDdWx0dXJlPW5ldXRyYWwsIFB1YmxpY0tleVRva2VuPWI3N2E1YzU2MTkzNGUwODldXQIAAAAIX21vbml0b3ISQ29sbGVjdGlvbmAxK2l0ZW1zBAOgAVN5c3RlbS5Db2xsZWN0aW9ucy5PYmplY3RNb2RlbC5PYnNlcnZhYmxlQ29sbGVjdGlvbmAxK1NpbXBsZU1vbml0b3JbW1N5c3RlbS5JbnQzMiwgbXNjb3JsaWIsIFZlcnNpb249NC4wLjAuMCwgQ3VsdHVyZT1uZXV0cmFsLCBQdWJsaWNLZXlUb2tlbj1iNzdhNWM1NjE5MzRlMDg5XV0CAAAAflN5c3RlbS5Db2xsZWN0aW9ucy5HZW5lcmljLkxpc3RgMVtbU3lzdGVtLkludDMyLCBtc2NvcmxpYiwgVmVyc2lvbj00LjAuMC4wLCBDdWx0dXJlPW5ldXRyYWwsIFB1YmxpY0tleVRva2VuPWI3N2E1YzU2MTkzNGUwODldXQIAAAAJBAAAAAkFAAAABQQAAACgAVN5c3RlbS5Db2xsZWN0aW9ucy5PYmplY3RNb2RlbC5PYnNlcnZhYmxlQ29sbGVjdGlvbmAxK1NpbXBsZU1vbml0b3JbW1N5c3RlbS5JbnQzMiwgbXNjb3JsaWIsIFZlcnNpb249NC4wLjAuMCwgQ3VsdHVyZT1uZXV0cmFsLCBQdWJsaWNLZXlUb2tlbj1iNzdhNWM1NjE5MzRlMDg5XV0BAAAACl9idXN5Q291bnQACAIAAAAAAAAABAUAAAB+U3lzdGVtLkNvbGxlY3Rpb25zLkdlbmVyaWMuTGlzdGAxW1tTeXN0ZW0uSW50MzIsIG1zY29ybGliLCBWZXJzaW9uPTQuMC4wLjAsIEN1bHR1cmU9bmV1dHJhbCwgUHVibGljS2V5VG9rZW49Yjc3YTVjNTYxOTM0ZTA4OV1dAwAAAAZfaXRlbXMFX3NpemUIX3ZlcnNpb24HAAAICAgJBgAAAAUAAAAFAAAADwYAAAAIAAAACAEAAAACAAAAAwAAAAQAAAAFAAAAAAAAAAAAAAAAAAAACw==" } };
yield return new object[] { new System.Collections.ObjectModel.ReadOnlyCollection<int>(Enumerable.Range(1, 15).ToList()), new string[] { "AAEAAAD/////AQAAAAAAAAAEAQAAAJABU3lzdGVtLkNvbGxlY3Rpb25zLk9iamVjdE1vZGVsLlJlYWRPbmx5Q29sbGVjdGlvbmAxW1tTeXN0ZW0uSW50MzIsIG1zY29ybGliLCBWZXJzaW9uPTQuMC4wLjAsIEN1bHR1cmU9bmV1dHJhbCwgUHVibGljS2V5VG9rZW49Yjc3YTVjNTYxOTM0ZTA4OV1dAQAAAARsaXN0A35TeXN0ZW0uQ29sbGVjdGlvbnMuR2VuZXJpYy5MaXN0YDFbW1N5c3RlbS5JbnQzMiwgbXNjb3JsaWIsIFZlcnNpb249NC4wLjAuMCwgQ3VsdHVyZT1uZXV0cmFsLCBQdWJsaWNLZXlUb2tlbj1iNzdhNWM1NjE5MzRlMDg5XV0JAgAAAAQCAAAAflN5c3RlbS5Db2xsZWN0aW9ucy5HZW5lcmljLkxpc3RgMVtbU3lzdGVtLkludDMyLCBtc2NvcmxpYiwgVmVyc2lvbj00LjAuMC4wLCBDdWx0dXJlPW5ldXRyYWwsIFB1YmxpY0tleVRva2VuPWI3N2E1YzU2MTkzNGUwODldXQMAAAAGX2l0ZW1zBV9zaXplCF92ZXJzaW9uBwAACAgICQMAAAAPAAAADwAAAA8DAAAADwAAAAgBAAAAAgAAAAMAAAAEAAAABQAAAAYAAAAHAAAACAAAAAkAAAAKAAAACwAAAAwAAAANAAAADgAAAA8AAAAL", "AAEAAAD/////AQAAAAAAAAAEAQAAAJABU3lzdGVtLkNvbGxlY3Rpb25zLk9iamVjdE1vZGVsLlJlYWRPbmx5Q29sbGVjdGlvbmAxW1tTeXN0ZW0uSW50MzIsIG1zY29ybGliLCBWZXJzaW9uPTQuMC4wLjAsIEN1bHR1cmU9bmV1dHJhbCwgUHVibGljS2V5VG9rZW49Yjc3YTVjNTYxOTM0ZTA4OV1dAQAAAARsaXN0A35TeXN0ZW0uQ29sbGVjdGlvbnMuR2VuZXJpYy5MaXN0YDFbW1N5c3RlbS5JbnQzMiwgbXNjb3JsaWIsIFZlcnNpb249NC4wLjAuMCwgQ3VsdHVyZT1uZXV0cmFsLCBQdWJsaWNLZXlUb2tlbj1iNzdhNWM1NjE5MzRlMDg5XV0JAgAAAAQCAAAAflN5c3RlbS5Db2xsZWN0aW9ucy5HZW5lcmljLkxpc3RgMVtbU3lzdGVtLkludDMyLCBtc2NvcmxpYiwgVmVyc2lvbj00LjAuMC4wLCBDdWx0dXJlPW5ldXRyYWwsIFB1YmxpY0tleVRva2VuPWI3N2E1YzU2MTkzNGUwODldXQMAAAAGX2l0ZW1zBV9zaXplCF92ZXJzaW9uBwAACAgICQMAAAAPAAAADwAAAA8DAAAAEAAAAAgBAAAAAgAAAAMAAAAEAAAABQAAAAYAAAAHAAAACAAAAAkAAAAKAAAACwAAAAwAAAANAAAADgAAAA8AAAAAAAAACw==" } };
yield return new object[] { new System.Collections.ObjectModel.ReadOnlyDictionary<int, string>(dictionary), new string[] { "AAEAAAD/////AQAAAAAAAAAEAQAAAO0BU3lzdGVtLkNvbGxlY3Rpb25zLk9iamVjdE1vZGVsLlJlYWRPbmx5RGljdGlvbmFyeWAyW1tTeXN0ZW0uSW50MzIsIG1zY29ybGliLCBWZXJzaW9uPTQuMC4wLjAsIEN1bHR1cmU9bmV1dHJhbCwgUHVibGljS2V5VG9rZW49Yjc3YTVjNTYxOTM0ZTA4OV0sW1N5c3RlbS5TdHJpbmcsIG1zY29ybGliLCBWZXJzaW9uPTQuMC4wLjAsIEN1bHR1cmU9bmV1dHJhbCwgUHVibGljS2V5VG9rZW49Yjc3YTVjNTYxOTM0ZTA4OV1dAQAAAAxtX2RpY3Rpb25hcnkD4QFTeXN0ZW0uQ29sbGVjdGlvbnMuR2VuZXJpYy5EaWN0aW9uYXJ5YDJbW1N5c3RlbS5JbnQzMiwgbXNjb3JsaWIsIFZlcnNpb249NC4wLjAuMCwgQ3VsdHVyZT1uZXV0cmFsLCBQdWJsaWNLZXlUb2tlbj1iNzdhNWM1NjE5MzRlMDg5XSxbU3lzdGVtLlN0cmluZywgbXNjb3JsaWIsIFZlcnNpb249NC4wLjAuMCwgQ3VsdHVyZT1uZXV0cmFsLCBQdWJsaWNLZXlUb2tlbj1iNzdhNWM1NjE5MzRlMDg5XV0JAgAAAAQCAAAA4QFTeXN0ZW0uQ29sbGVjdGlvbnMuR2VuZXJpYy5EaWN0aW9uYXJ5YDJbW1N5c3RlbS5JbnQzMiwgbXNjb3JsaWIsIFZlcnNpb249NC4wLjAuMCwgQ3VsdHVyZT1uZXV0cmFsLCBQdWJsaWNLZXlUb2tlbj1iNzdhNWM1NjE5MzRlMDg5XSxbU3lzdGVtLlN0cmluZywgbXNjb3JsaWIsIFZlcnNpb249NC4wLjAuMCwgQ3VsdHVyZT1uZXV0cmFsLCBQdWJsaWNLZXlUb2tlbj1iNzdhNWM1NjE5MzRlMDg5XV0EAAAAB1ZlcnNpb24IQ29tcGFyZXIISGFzaFNpemUNS2V5VmFsdWVQYWlycwADAAMIkQFTeXN0ZW0uQ29sbGVjdGlvbnMuR2VuZXJpYy5HZW5lcmljRXF1YWxpdHlDb21wYXJlcmAxW1tTeXN0ZW0uSW50MzIsIG1zY29ybGliLCBWZXJzaW9uPTQuMC4wLjAsIEN1bHR1cmU9bmV1dHJhbCwgUHVibGljS2V5VG9rZW49Yjc3YTVjNTYxOTM0ZTA4OV1dCOUBU3lzdGVtLkNvbGxlY3Rpb25zLkdlbmVyaWMuS2V5VmFsdWVQYWlyYDJbW1N5c3RlbS5JbnQzMiwgbXNjb3JsaWIsIFZlcnNpb249NC4wLjAuMCwgQ3VsdHVyZT1uZXV0cmFsLCBQdWJsaWNLZXlUb2tlbj1iNzdhNWM1NjE5MzRlMDg5XSxbU3lzdGVtLlN0cmluZywgbXNjb3JsaWIsIFZlcnNpb249NC4wLjAuMCwgQ3VsdHVyZT1uZXV0cmFsLCBQdWJsaWNLZXlUb2tlbj1iNzdhNWM1NjE5MzRlMDg5XV1bXQIAAAAJAwAAAAMAAAAJBAAAAAQDAAAAkQFTeXN0ZW0uQ29sbGVjdGlvbnMuR2VuZXJpYy5HZW5lcmljRXF1YWxpdHlDb21wYXJlcmAxW1tTeXN0ZW0uSW50MzIsIG1zY29ybGliLCBWZXJzaW9uPTQuMC4wLjAsIEN1bHR1cmU9bmV1dHJhbCwgUHVibGljS2V5VG9rZW49Yjc3YTVjNTYxOTM0ZTA4OV1dAAAAAAcEAAAAAAEAAAACAAAAA+MBU3lzdGVtLkNvbGxlY3Rpb25zLkdlbmVyaWMuS2V5VmFsdWVQYWlyYDJbW1N5c3RlbS5JbnQzMiwgbXNjb3JsaWIsIFZlcnNpb249NC4wLjAuMCwgQ3VsdHVyZT1uZXV0cmFsLCBQdWJsaWNLZXlUb2tlbj1iNzdhNWM1NjE5MzRlMDg5XSxbU3lzdGVtLlN0cmluZywgbXNjb3JsaWIsIFZlcnNpb249NC4wLjAuMCwgQ3VsdHVyZT1uZXV0cmFsLCBQdWJsaWNLZXlUb2tlbj1iNzdhNWM1NjE5MzRlMDg5XV0E+////+MBU3lzdGVtLkNvbGxlY3Rpb25zLkdlbmVyaWMuS2V5VmFsdWVQYWlyYDJbW1N5c3RlbS5JbnQzMiwgbXNjb3JsaWIsIFZlcnNpb249NC4wLjAuMCwgQ3VsdHVyZT1uZXV0cmFsLCBQdWJsaWNLZXlUb2tlbj1iNzdhNWM1NjE5MzRlMDg5XSxbU3lzdGVtLlN0cmluZywgbXNjb3JsaWIsIFZlcnNpb249NC4wLjAuMCwgQ3VsdHVyZT1uZXV0cmFsLCBQdWJsaWNLZXlUb2tlbj1iNzdhNWM1NjE5MzRlMDg5XV0CAAAAA2tleQV2YWx1ZQABCAEAAAAGBgAAAAR0ZXN0Afn////7////AgAAAAYIAAAADGFub3RoZXIgdGVzdAs=", "AAEAAAD/////AQAAAAAAAAAEAQAAAO0BU3lzdGVtLkNvbGxlY3Rpb25zLk9iamVjdE1vZGVsLlJlYWRPbmx5RGljdGlvbmFyeWAyW1tTeXN0ZW0uSW50MzIsIG1zY29ybGliLCBWZXJzaW9uPTQuMC4wLjAsIEN1bHR1cmU9bmV1dHJhbCwgUHVibGljS2V5VG9rZW49Yjc3YTVjNTYxOTM0ZTA4OV0sW1N5c3RlbS5TdHJpbmcsIG1zY29ybGliLCBWZXJzaW9uPTQuMC4wLjAsIEN1bHR1cmU9bmV1dHJhbCwgUHVibGljS2V5VG9rZW49Yjc3YTVjNTYxOTM0ZTA4OV1dAQAAAAxtX2RpY3Rpb25hcnkD4QFTeXN0ZW0uQ29sbGVjdGlvbnMuR2VuZXJpYy5EaWN0aW9uYXJ5YDJbW1N5c3RlbS5JbnQzMiwgbXNjb3JsaWIsIFZlcnNpb249NC4wLjAuMCwgQ3VsdHVyZT1uZXV0cmFsLCBQdWJsaWNLZXlUb2tlbj1iNzdhNWM1NjE5MzRlMDg5XSxbU3lzdGVtLlN0cmluZywgbXNjb3JsaWIsIFZlcnNpb249NC4wLjAuMCwgQ3VsdHVyZT1uZXV0cmFsLCBQdWJsaWNLZXlUb2tlbj1iNzdhNWM1NjE5MzRlMDg5XV0JAgAAAAQCAAAA4QFTeXN0ZW0uQ29sbGVjdGlvbnMuR2VuZXJpYy5EaWN0aW9uYXJ5YDJbW1N5c3RlbS5JbnQzMiwgbXNjb3JsaWIsIFZlcnNpb249NC4wLjAuMCwgQ3VsdHVyZT1uZXV0cmFsLCBQdWJsaWNLZXlUb2tlbj1iNzdhNWM1NjE5MzRlMDg5XSxbU3lzdGVtLlN0cmluZywgbXNjb3JsaWIsIFZlcnNpb249NC4wLjAuMCwgQ3VsdHVyZT1uZXV0cmFsLCBQdWJsaWNLZXlUb2tlbj1iNzdhNWM1NjE5MzRlMDg5XV0EAAAAB1ZlcnNpb24IQ29tcGFyZXIISGFzaFNpemUNS2V5VmFsdWVQYWlycwADAAMIkQFTeXN0ZW0uQ29sbGVjdGlvbnMuR2VuZXJpYy5HZW5lcmljRXF1YWxpdHlDb21wYXJlcmAxW1tTeXN0ZW0uSW50MzIsIG1zY29ybGliLCBWZXJzaW9uPTQuMC4wLjAsIEN1bHR1cmU9bmV1dHJhbCwgUHVibGljS2V5VG9rZW49Yjc3YTVjNTYxOTM0ZTA4OV1dCOUBU3lzdGVtLkNvbGxlY3Rpb25zLkdlbmVyaWMuS2V5VmFsdWVQYWlyYDJbW1N5c3RlbS5JbnQzMiwgbXNjb3JsaWIsIFZlcnNpb249NC4wLjAuMCwgQ3VsdHVyZT1uZXV0cmFsLCBQdWJsaWNLZXlUb2tlbj1iNzdhNWM1NjE5MzRlMDg5XSxbU3lzdGVtLlN0cmluZywgbXNjb3JsaWIsIFZlcnNpb249NC4wLjAuMCwgQ3VsdHVyZT1uZXV0cmFsLCBQdWJsaWNLZXlUb2tlbj1iNzdhNWM1NjE5MzRlMDg5XV1bXQIAAAAJAwAAAAMAAAAJBAAAAAQDAAAAkQFTeXN0ZW0uQ29sbGVjdGlvbnMuR2VuZXJpYy5HZW5lcmljRXF1YWxpdHlDb21wYXJlcmAxW1tTeXN0ZW0uSW50MzIsIG1zY29ybGliLCBWZXJzaW9uPTQuMC4wLjAsIEN1bHR1cmU9bmV1dHJhbCwgUHVibGljS2V5VG9rZW49Yjc3YTVjNTYxOTM0ZTA4OV1dAAAAAAcEAAAAAAEAAAACAAAAA+MBU3lzdGVtLkNvbGxlY3Rpb25zLkdlbmVyaWMuS2V5VmFsdWVQYWlyYDJbW1N5c3RlbS5JbnQzMiwgbXNjb3JsaWIsIFZlcnNpb249NC4wLjAuMCwgQ3VsdHVyZT1uZXV0cmFsLCBQdWJsaWNLZXlUb2tlbj1iNzdhNWM1NjE5MzRlMDg5XSxbU3lzdGVtLlN0cmluZywgbXNjb3JsaWIsIFZlcnNpb249NC4wLjAuMCwgQ3VsdHVyZT1uZXV0cmFsLCBQdWJsaWNLZXlUb2tlbj1iNzdhNWM1NjE5MzRlMDg5XV0E+////+MBU3lzdGVtLkNvbGxlY3Rpb25zLkdlbmVyaWMuS2V5VmFsdWVQYWlyYDJbW1N5c3RlbS5JbnQzMiwgbXNjb3JsaWIsIFZlcnNpb249NC4wLjAuMCwgQ3VsdHVyZT1uZXV0cmFsLCBQdWJsaWNLZXlUb2tlbj1iNzdhNWM1NjE5MzRlMDg5XSxbU3lzdGVtLlN0cmluZywgbXNjb3JsaWIsIFZlcnNpb249NC4wLjAuMCwgQ3VsdHVyZT1uZXV0cmFsLCBQdWJsaWNLZXlUb2tlbj1iNzdhNWM1NjE5MzRlMDg5XV0CAAAAA2tleQV2YWx1ZQABCAEAAAAGBgAAAAR0ZXN0Afn////7////AgAAAAYIAAAADGFub3RoZXIgdGVzdAs=" } };
diff --git a/src/System.Runtime.Serialization.Formatters/tests/FormatterServicesTests.cs b/src/System.Runtime.Serialization.Formatters/tests/FormatterServicesTests.cs
index 92e4b55d0f..7dd48e984d 100644
--- a/src/System.Runtime.Serialization.Formatters/tests/FormatterServicesTests.cs
+++ b/src/System.Runtime.Serialization.Formatters/tests/FormatterServicesTests.cs
@@ -127,6 +127,7 @@ namespace System.Runtime.Serialization.Formatters.Tests
}
#pragma warning disable 0169 // The private field 'class member' is never used
+ [System.Runtime.CompilerServices.IsByRefLike]
private struct StructWithSpanField
{
Span<byte> _bytes;
@@ -321,3 +322,15 @@ namespace System.Runtime.Serialization.Formatters.Tests
}
}
}
+
+namespace System.Runtime.CompilerServices
+{
+ // Local definition of IsByRefLikeAttribute while the real one becomes available in corefx
+ [AttributeUsage(AttributeTargets.Struct)]
+ public sealed class IsByRefLikeAttribute : Attribute
+ {
+ public IsByRefLikeAttribute()
+ {
+ }
+ }
+}
diff --git a/src/System.Runtime.Serialization.Formatters/tests/System.Runtime.Serialization.Formatters.Tests.csproj b/src/System.Runtime.Serialization.Formatters/tests/System.Runtime.Serialization.Formatters.Tests.csproj
index 9eb51250ba..09b8d01e08 100644
--- a/src/System.Runtime.Serialization.Formatters/tests/System.Runtime.Serialization.Formatters.Tests.csproj
+++ b/src/System.Runtime.Serialization.Formatters/tests/System.Runtime.Serialization.Formatters.Tests.csproj
@@ -23,9 +23,6 @@
<Compile Include="SerializationInfoTests.cs" />
<Compile Include="SerializationTypes.cs" />
<Compile Include="SurrogateSelectorTests.cs" />
- <Compile Include="$(CommonTestPath)\System\AssertExtensions.cs">
- <Link>Common\System\AssertExtensions.cs</Link>
- </Compile>
<Compile Include="$(CommonTestPath)\System\NonRuntimeType.cs">
<Link>Common\System\NonRuntimeType.cs</Link>
</Compile>
diff --git a/src/System.Runtime.Serialization.Json/tests/DataContractJsonSerializer.cs b/src/System.Runtime.Serialization.Json/tests/DataContractJsonSerializer.cs
index e20626688e..2d7b6341dd 100644
--- a/src/System.Runtime.Serialization.Json/tests/DataContractJsonSerializer.cs
+++ b/src/System.Runtime.Serialization.Json/tests/DataContractJsonSerializer.cs
@@ -2883,6 +2883,32 @@ public static partial class DataContractJsonSerializerTests
Assert.StrictEqual(value["Bar"], deserializedValue["Bar"]);
}
+ [Fact]
+ public static void DCJS_InvalidDataContract_Write_Invalid_Types_Throws()
+ {
+ foreach (NativeJsonTestData td in NativeJsonTestData.Json_InvalidTypes)
+ {
+ Assert.Throws<InvalidDataContractException>(() =>
+ {
+ object o = td.Instantiate();
+ DataContractJsonSerializer dcs = new DataContractJsonSerializer(o.GetType());
+ MemoryStream ms = new MemoryStream();
+ dcs.WriteObject(ms, o);
+ });
+ }
+ }
+
+ [Fact]
+ public static void DCJS_ValidateExceptionOnUnspecifiedRootSerializationType()
+ {
+ var value = new UnspecifiedRootSerializationType();
+ string baseline = "{\"MyIntProperty\":0,\"MyStringProperty\":null}";
+ var actual = SerializeAndDeserialize(value, baseline);
+
+ Assert.Equal(value.MyIntProperty, actual.MyIntProperty);
+ Assert.Equal(value.MyStringProperty, actual.MyStringProperty);
+ }
+
private static T SerializeAndDeserialize<T>(T value, string baseline, DataContractJsonSerializerSettings settings = null, Func<DataContractJsonSerializer> serializerFactory = null, bool skipStringCompare = false)
{
DataContractJsonSerializer dcjs;
diff --git a/src/System.Runtime.Serialization.Json/tests/ReflectionOnly/System.Runtime.Serialization.Json.ReflectionOnly.Tests.csproj b/src/System.Runtime.Serialization.Json/tests/ReflectionOnly/System.Runtime.Serialization.Json.ReflectionOnly.Tests.csproj
index f0035b5149..b5b20ca402 100644
--- a/src/System.Runtime.Serialization.Json/tests/ReflectionOnly/System.Runtime.Serialization.Json.ReflectionOnly.Tests.csproj
+++ b/src/System.Runtime.Serialization.Json/tests/ReflectionOnly/System.Runtime.Serialization.Json.ReflectionOnly.Tests.csproj
@@ -13,9 +13,6 @@
<Compile Include="$(TestSourceFolder)..\..\..\System.Runtime.Serialization.Xml\tests\Utils.cs" />
<Compile Include="$(TestSourceFolder)..\..\..\System.Runtime.Serialization.Xml\tests\SerializationTypes.cs" />
<Compile Include="$(TestSourceFolder)..\DataContractJsonSerializer.cs" />
- <Compile Include="$(CommonTestPath)\System\AssertExtensions.cs">
- <Link>Common\System\AssertExtensions.cs</Link>
- </Compile>
<Compile Include="$(CommonTestPath)\System\PlatformDetection.cs">
<Link>CommonTest\System\PlatformDetection.cs</Link>
</Compile>
diff --git a/src/System.Runtime.Serialization.Json/tests/System.Runtime.Serialization.Json.Tests.csproj b/src/System.Runtime.Serialization.Json/tests/System.Runtime.Serialization.Json.Tests.csproj
index b317f148d2..9da2683c92 100644
--- a/src/System.Runtime.Serialization.Json/tests/System.Runtime.Serialization.Json.Tests.csproj
+++ b/src/System.Runtime.Serialization.Json/tests/System.Runtime.Serialization.Json.Tests.csproj
@@ -16,9 +16,6 @@
<Compile Include="$(TestSourceFolder)..\..\System.Runtime.Serialization.Xml\tests\Utils.cs" />
<Compile Include="$(TestSourceFolder)..\..\System.Runtime.Serialization.Xml\tests\SerializationTypes.cs" />
<Compile Include="$(TestSourceFolder)DataContractJsonSerializer.cs" />
- <Compile Include="$(CommonTestPath)\System\AssertExtensions.cs">
- <Link>Common\System\AssertExtensions.cs</Link>
- </Compile>
<Compile Include="$(CommonTestPath)\System\PlatformDetection.cs">
<Link>CommonTest\System\PlatformDetection.cs</Link>
</Compile>
diff --git a/src/System.Runtime.Serialization.Xml/tests/DataContractSerializer.cs b/src/System.Runtime.Serialization.Xml/tests/DataContractSerializer.cs
index f29a4aadaf..12ca06d9a7 100644
--- a/src/System.Runtime.Serialization.Xml/tests/DataContractSerializer.cs
+++ b/src/System.Runtime.Serialization.Xml/tests/DataContractSerializer.cs
@@ -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.
// See the LICENSE file in the project root for more information.
@@ -1055,7 +1055,7 @@ public static partial class DataContractSerializerTests
public static void DCS_DerivedTypeWithDifferentOverrides()
{
var x = new DerivedTypeWithDifferentOverrides() { Name1 = "Name1", Name2 = "Name2", Name3 = "Name3", Name4 = "Name4", Name5 = "Name5" };
- var y = SerializeAndDeserialize<DerivedTypeWithDifferentOverrides>(x, @"<DerivedTypeWithDifferentOverrides xmlns=""http://schemas.datacontract.org/2004/07/SerializationTypes"" xmlns:i=""http://www.w3.org/2001/XMLSchema-instance""><Name1>Name1</Name1><Name2 i:nil=""true""/><Name3 i:nil=""true""/><Name4 i:nil=""true""/><Name5 i:nil=""true""/><Name2>Name2</Name2><Name3>Name3</Name3><Name5>Name5</Name5></DerivedTypeWithDifferentOverrides>");
+ var y = SerializeAndDeserialize<DerivedTypeWithDifferentOverrides>(x, @"<DerivedTypeWithDifferentOverrides xmlns=""http://schemas.datacontract.org/2004/07/SerializationTypes"" xmlns:i=""http://www.w3.org/2001/XMLSchema-instance""><Name1>Name1</Name1><Name2 i:nil=""true""/><Name3 i:nil=""true""/><Name4 i:nil=""true""/><Name5 i:nil=""true""/><Name6 i:nil=""true""/><Name2>Name2</Name2><Name3>Name3</Name3><Name5>Name5</Name5></DerivedTypeWithDifferentOverrides>");
Assert.StrictEqual(x.Name1, y.Name1);
Assert.StrictEqual(x.Name2, y.Name2);
@@ -1436,7 +1436,6 @@ public static partial class DataContractSerializerTests
}
[Fact]
- [ActiveIssue("dotnet/corefx #19585", TargetFrameworkMonikers.UapAot)]
public static void DCS_ExceptionObject()
{
var value = new Exception("Test Exception");
@@ -1450,7 +1449,6 @@ public static partial class DataContractSerializerTests
}
[Fact]
- [ActiveIssue("dotnet/corefx #19585", TargetFrameworkMonikers.UapAot)]
public static void DCS_MyArgumentExceptionObject()
{
var value = new MyArgumentException("Test Exception", "paramName");
@@ -1465,7 +1463,6 @@ public static partial class DataContractSerializerTests
}
[Fact]
- [ActiveIssue("dotnet/corefx #19585", TargetFrameworkMonikers.UapAot)]
public static void DCS_ExceptionMessageWithSpecialChars()
{
var value = new Exception("Test Exception<>&'\"");
@@ -1479,7 +1476,6 @@ public static partial class DataContractSerializerTests
}
[Fact]
- [ActiveIssue("dotnet/corefx #19585", TargetFrameworkMonikers.UapAot)]
public static void DCS_InnerExceptionMessageWithSpecialChars()
{
var value = new Exception("", new Exception("Test Exception<>&'\""));
@@ -3172,6 +3168,60 @@ public static partial class DataContractSerializerTests
ComparisonHelper.CompareRecursively(value, deserializedDesktopObject);
}
+ [Fact]
+ public static void DCS_InvalidDataContract_Write_Invalid_Types_Throws()
+ {
+ // Attempting to serialize any invalid type should create an InvalidDataContract that throws
+ foreach (NetNativeTestData td in NetNativeTestData.InvalidTypes)
+ {
+ object o = td.Instantiate();
+ DataContractSerializer dcs = new DataContractSerializer(o.GetType());
+ MemoryStream ms = new MemoryStream();
+ Assert.Throws<InvalidDataContractException>(() =>
+ {
+ dcs.WriteObject(ms, o);
+ });
+ }
+ }
+
+ [Fact]
+ public static void DCS_InvalidDataContract_Read_Invalid_Types_Throws()
+ {
+ // Attempting to deserialize any invalid type should create an InvalidDataContract that throws
+ foreach (NetNativeTestData td in NetNativeTestData.InvalidTypes)
+ {
+ DataContractSerializer dcs = new DataContractSerializer(td.Type);
+ MemoryStream ms = new MemoryStream();
+ new DataContractSerializer(typeof(string)).WriteObject(ms, "test");
+ ms.Seek(0L, SeekOrigin.Begin);
+ if (td.Type.Equals(typeof(Invalid_Class_KnownType_Invalid_Type)))
+ {
+ Assert.Throws<SerializationException>(() =>
+ {
+ dcs.ReadObject(ms);
+ });
+ }
+ else
+ {
+ Assert.Throws<InvalidDataContractException>(() =>
+ {
+ dcs.ReadObject(ms);
+ });
+ }
+ }
+ }
+
+ [Fact]
+ public static void DCS_ValidateExceptionOnUnspecifiedRootSerializationType()
+ {
+ var value = new UnspecifiedRootSerializationType();
+ string baseline = @"<UnspecifiedRootSerializationType xmlns=""http://schemas.datacontract.org/2004/07/SerializationTypes"" xmlns:i=""http://www.w3.org/2001/XMLSchema-instance""><MyIntProperty>0</MyIntProperty><MyStringProperty i:nil=""true""/></UnspecifiedRootSerializationType>";
+ var actual = SerializeAndDeserialize(value, baseline);
+
+ Assert.Equal(value.MyIntProperty, actual.MyIntProperty);
+ Assert.Equal(value.MyStringProperty, actual.MyStringProperty);
+ }
+
private static T SerializeAndDeserialize<T>(T value, string baseline, DataContractSerializerSettings settings = null, Func<DataContractSerializer> serializerFactory = null, bool skipStringCompare = false)
{
DataContractSerializer dcs;
diff --git a/src/System.Runtime.Serialization.Xml/tests/DataContractSerializerTestData.cs b/src/System.Runtime.Serialization.Xml/tests/DataContractSerializerTestData.cs
deleted file mode 100644
index 66a991f942..0000000000
--- a/src/System.Runtime.Serialization.Xml/tests/DataContractSerializerTestData.cs
+++ /dev/null
@@ -1,21 +0,0 @@
-// Licensed to the .NET Foundation under one or more agreements.
-// The .NET Foundation licenses this file to you under the MIT license.
-// See the LICENSE file in the project root for more information.
-
-using System;
-using System.Collections.Generic;
-using System.Linq;
-using System.Runtime.Serialization;
-using System.Text;
-using System.Threading.Tasks;
-
-
-// Invalid because there is no parameterless ctor
-public class Invalid_Class_No_Parameterless_Ctor
-{
- public Invalid_Class_No_Parameterless_Ctor(string id)
- {
- ID = id;
- }
- public string ID { get; set; }
-}
diff --git a/src/System.Runtime.Serialization.Xml/tests/ReflectionOnly/System.Runtime.Serialization.Xml.ReflectionOnly.Tests.csproj b/src/System.Runtime.Serialization.Xml/tests/ReflectionOnly/System.Runtime.Serialization.Xml.ReflectionOnly.Tests.csproj
index 23090ab9b4..f3756d6307 100644
--- a/src/System.Runtime.Serialization.Xml/tests/ReflectionOnly/System.Runtime.Serialization.Xml.ReflectionOnly.Tests.csproj
+++ b/src/System.Runtime.Serialization.Xml/tests/ReflectionOnly/System.Runtime.Serialization.Xml.ReflectionOnly.Tests.csproj
@@ -15,7 +15,6 @@
<Compile Include="$(TestSourceFolder)..\Utils.cs" />
<Compile Include="$(TestSourceFolder)..\SerializationTypes.cs" />
<Compile Include="$(TestSourceFolder)..\DataContractSerializer.cs" />
- <Compile Include="$(TestSourceFolder)..\DataContractSerializerTestData.cs" />
<Compile Include="$(TestSourceFolder)..\MyResolver.cs" />
<Compile Include="$(TestSourceFolder)..\XmlDictionaryReaderTests.cs" />
<Compile Include="$(TestSourceFolder)..\XmlDictionaryWriterTest.cs" />
diff --git a/src/System.Runtime.Serialization.Xml/tests/SerializationTypes.cs b/src/System.Runtime.Serialization.Xml/tests/SerializationTypes.cs
index 04e870ab38..a789c45e14 100644
--- a/src/System.Runtime.Serialization.Xml/tests/SerializationTypes.cs
+++ b/src/System.Runtime.Serialization.Xml/tests/SerializationTypes.cs
@@ -17,6 +17,7 @@ using System.IO;
using System.Text;
using System.Reflection;
using System.Threading.Tasks;
+using System.Runtime.Serialization.Json;
namespace SerializationTypes
{
@@ -1159,6 +1160,8 @@ namespace SerializationTypes
public string Name4 { get; set; }
public string @Name5 { get; set; }
+
+ public virtual string Name6 { get; set; }
}
public class DerivedTypeWithDifferentOverrides : BaseType
@@ -1172,6 +1175,23 @@ namespace SerializationTypes
new internal string Name4 { get; set; }
new public string Name5 { get; set; }
+
+ public override string Name6 { get; set; }
+ }
+
+ public class DerivedTypeWithDifferentOverrides2 : DerivedTypeWithDifferentOverrides
+ {
+ public override string Name1 { get; set; }
+
+ new public string Name2 { get; set; }
+
+ new public string Name3 { get; set; }
+
+ new internal string Name4 { get; set; }
+
+ new internal string Name5 { get; set; }
+
+ new internal string Name6 { get; set; }
}
public class __TypeNameWithSpecialCharacters漢ñ
@@ -5353,3 +5373,107 @@ public class SampleICollectionTExplicitWithoutDC : ICollection<DC>
return _internalList.GetEnumerator();
}
}
+
+public class NetNativeTestData
+{
+ public static NetNativeTestData[] InvalidTypes = new NetNativeTestData[] {
+ new NetNativeTestData(typeof(Invalid_Class_No_Parameterless_Ctor),
+ () => new Invalid_Class_No_Parameterless_Ctor("test"),
+ "Type 'Invalid_Class_No_Parameterless_Ctor' cannot be serialized. Consider marking it with the DataContractAttribute attribute, and marking all of its members you want serialized with the DataMemberAttribute attribute. If the type is a collection, consider marking it with the CollectionDataContractAttribute. See the Microsoft .NET Framework documentation for other supported types."),
+ new NetNativeTestData(typeof(Invalid_Class_Derived_With_DataContract),
+ () => new Invalid_Class_Derived_With_DataContract(),
+ "Type 'Invalid_Class_Derived_With_DataContract' cannot inherit from a type that is not marked with DataContractAttribute or SerializableAttribute. Consider marking the base type 'Invalid_Class_Base_Without_DataContract' with DataContractAttribute or SerializableAttribute, or removing them from the derived type." ),
+ new NetNativeTestData(typeof(Invalid_Class_KnownType_Invalid_Type),
+ () => new Invalid_Class_KnownType_Invalid_Type(),
+ "Type 'Invalid_Class_No_Parameterless_Ctor' cannot be serialized. Consider marking it with the DataContractAttribute attribute, and marking all of its members you want serialized with the DataMemberAttribute attribute. If the type is a collection, consider marking it with the CollectionDataContractAttribute. See the Microsoft .NET Framework documentation for other supported types." ),
+ };
+
+ // This list exists solely to expose all the root objects being serialized.
+ // Without this ILC removes our test data types
+ // All new test data types *must* be added to one of these lists to appear to the ILC.
+ // Test data now added here will result in "serializer not found" exception at runtime.
+ public static DataContractSerializer[] Serializers = new DataContractSerializer[]
+ {
+ new DataContractSerializer(typeof(Invalid_Class_No_Parameterless_Ctor)),
+ new DataContractSerializer(typeof(List<Invalid_Class_No_Parameterless_Ctor>)),
+ new DataContractSerializer(typeof(Invalid_Class_Derived_With_DataContract)),
+ new DataContractSerializer(typeof(Invalid_Class_KnownType_Invalid_Type))
+ };
+
+ public NetNativeTestData(Type type, Func<object> instantiate, string errorMessage)
+ {
+ Type = type;
+ ErrorMessage = errorMessage;
+ Instantiate = instantiate;
+ }
+
+ public Type Type { get; set; }
+
+ public String ErrorMessage { get; set; }
+
+ public Func<object> Instantiate
+ {
+ get; set;
+ }
+}
+public abstract class Invalid_Class_Base_Without_DataContract
+{
+
+}
+
+// Invalid because it is a derived [DataContract] class whose base class is not
+[DataContract]
+public class Invalid_Class_Derived_With_DataContract : Invalid_Class_Base_Without_DataContract
+{
+
+}
+
+// Invalid because its [KnownType] is an invalid type
+[KnownType(typeof(Invalid_Class_No_Parameterless_Ctor))]
+public class Invalid_Class_KnownType_Invalid_Type
+{
+ public Invalid_Class_KnownType_Invalid_Type()
+ {
+
+ }
+}
+
+public class Invalid_Class_No_Parameterless_Ctor
+{
+ public Invalid_Class_No_Parameterless_Ctor(string id)
+ {
+ ID = id;
+ }
+
+ public string ID { get; set; }
+}
+
+public class NativeJsonTestData
+{
+ public static NativeJsonTestData[] Json_InvalidTypes = new NativeJsonTestData[] {
+ new NativeJsonTestData(typeof(Invalid_Class_No_Parameterless_Ctor),
+ () => new Invalid_Class_No_Parameterless_Ctor("test")),
+ new NativeJsonTestData(typeof(Invalid_Class_Derived_With_DataContract),
+ () => new Invalid_Class_Derived_With_DataContract()),
+ };
+
+ // This list exists solely to expose all the root objects being serialized.
+ // Without this ILC removes our test data types
+ // All new test data types *must* be added to one of these lists to appear to the ILC.
+ // Test data now added here will result in "serializer not found" exception at runtime.
+ public static DataContractJsonSerializer[] JsonSerializers = new DataContractJsonSerializer[]
+ {
+ new DataContractJsonSerializer(typeof(Invalid_Class_No_Parameterless_Ctor)),
+ new DataContractJsonSerializer(typeof(List<Invalid_Class_No_Parameterless_Ctor>)),
+ new DataContractJsonSerializer(typeof(Invalid_Class_Derived_With_DataContract)),
+ };
+
+ public NativeJsonTestData(Type type, Func<object> instantiate)
+ {
+ Type = type;
+ Instantiate = instantiate;
+ }
+
+ public Type Type { get; set; }
+ public Func<object> Instantiate { get; set; }
+} \ No newline at end of file
diff --git a/src/System.Runtime.Serialization.Xml/tests/System.Runtime.Serialization.Xml.Tests.csproj b/src/System.Runtime.Serialization.Xml/tests/System.Runtime.Serialization.Xml.Tests.csproj
index b49d33ee33..959dbaa00d 100644
--- a/src/System.Runtime.Serialization.Xml/tests/System.Runtime.Serialization.Xml.Tests.csproj
+++ b/src/System.Runtime.Serialization.Xml/tests/System.Runtime.Serialization.Xml.Tests.csproj
@@ -14,7 +14,6 @@
<Compile Include="$(TestSourceFolder)Utils.cs" />
<Compile Include="$(TestSourceFolder)SerializationTypes.cs" />
<Compile Include="$(TestSourceFolder)DataContractSerializer.cs" />
- <Compile Include="$(TestSourceFolder)DataContractSerializerTestData.cs" />
<Compile Include="$(TestSourceFolder)MyResolver.cs" />
<Compile Include="$(TestSourceFolder)XmlDictionaryReaderTests.cs" />
<Compile Include="$(TestSourceFolder)XmlDictionaryWriterTest.cs" />
diff --git a/src/System.Runtime.WindowsRuntime.UI.Xaml/tests/System.Runtime.WindowsRuntime.UI.Xaml.Tests.csproj b/src/System.Runtime.WindowsRuntime.UI.Xaml/tests/System.Runtime.WindowsRuntime.UI.Xaml.Tests.csproj
index 0b2cdec325..4dfe433f89 100644
--- a/src/System.Runtime.WindowsRuntime.UI.Xaml/tests/System.Runtime.WindowsRuntime.UI.Xaml.Tests.csproj
+++ b/src/System.Runtime.WindowsRuntime.UI.Xaml/tests/System.Runtime.WindowsRuntime.UI.Xaml.Tests.csproj
@@ -20,9 +20,6 @@
<Compile Include="Windows\UI\Xaml\Media\Animation\KeyTimeTests.cs" />
<Compile Include="Windows\UI\Xaml\Media\Animation\RepeatBehaviorTests.cs" />
<Compile Include="Windows\UI\Xaml\Media3D\Matrix3DTests.cs" />
- <Compile Include="$(CommonTestPath)\System\AssertExtensions.cs">
- <Link>Common\System\AssertExtensions.cs</Link>
- </Compile>
</ItemGroup>
<ItemGroup>
<ProjectReference Include="..\src\System.Runtime.WindowsRuntime.UI.Xaml.csproj">
diff --git a/src/System.Runtime.WindowsRuntime.UI.Xaml/tests/Windows/UI/Xaml/Media/Animation/RepeatBehaviorTests.cs b/src/System.Runtime.WindowsRuntime.UI.Xaml/tests/Windows/UI/Xaml/Media/Animation/RepeatBehaviorTests.cs
index 22216af637..b98cc8aebf 100644
--- a/src/System.Runtime.WindowsRuntime.UI.Xaml/tests/Windows/UI/Xaml/Media/Animation/RepeatBehaviorTests.cs
+++ b/src/System.Runtime.WindowsRuntime.UI.Xaml/tests/Windows/UI/Xaml/Media/Animation/RepeatBehaviorTests.cs
@@ -157,7 +157,6 @@ namespace Windows.UI.Xaml.Media.Animation.Tests
[Theory]
[MemberData(nameof(Equals_TestData))]
- [ActiveIssue(21351, TargetFrameworkMonikers.UapAot)]
public void Equals_Object_ReturnsExpected(RepeatBehavior repeatBehaviour, object other, bool expected)
{
Assert.Equal(expected, repeatBehaviour.Equals(other));
@@ -172,9 +171,9 @@ namespace Windows.UI.Xaml.Media.Animation.Tests
{
Assert.Equal(expected, repeatBehaviour.GetHashCode().Equals(otherRepeatBehaviour.GetHashCode()));
}
- else
+ else if (repeatBehaviour.Type == otherRepeatBehaviour.Type)
{
- Assert.Equal(repeatBehaviour.Type == otherRepeatBehaviour.Type, repeatBehaviour.GetHashCode().Equals(otherRepeatBehaviour.GetHashCode()));
+ Assert.Equal(repeatBehaviour.GetHashCode(), otherRepeatBehaviour.GetHashCode());
}
}
}
diff --git a/src/System.Runtime.WindowsRuntime/src/System/Resources/WindowsRuntimeResourceManager.cs b/src/System.Runtime.WindowsRuntime/src/System/Resources/WindowsRuntimeResourceManager.cs
index 45c8b426cd..6e3f67857b 100644
--- a/src/System.Runtime.WindowsRuntime/src/System/Resources/WindowsRuntimeResourceManager.cs
+++ b/src/System.Runtime.WindowsRuntime/src/System/Resources/WindowsRuntimeResourceManager.cs
@@ -23,6 +23,10 @@ namespace System.Resources
// of Initialize() and GetString() below.
internal sealed class WindowsRuntimeResourceManager : WindowsRuntimeResourceManagerBase
{
+ // Setting invariant culture to Windows Runtime doesn't work because Windows Runtime expects language name in the form of BCP-47 tags while
+ // invariant name is an empty string. We will use the private invariant culture name x-VL instead.
+ private const string c_InvariantCulturePrivateName = "x-VL";
+
private ResourceMap _resourceMap;
private ResourceContext _clonedResourceContext;
private string _clonedResourceContextFallBackList;
@@ -227,8 +231,26 @@ namespace System.Resources
Debug.Assert(s_globalResourceContextFallBackList != null);
Debug.Assert(s_globalResourceContext != null);
- List<String> languages = new List<string>(s_globalResourceContext.Languages);
+ IReadOnlyList<string> langs;
+
+ try
+ {
+ langs = s_globalResourceContext.Languages;
+ }
+ catch (ArgumentException)
+ {
+ // Sometimes Windows Runtime fails and we get Argument Exception which can fail fast the whole app
+ // to avoid that we ignore the exception.
+ return;
+ }
+ List<String> languages = new List<string>(langs);
+
+ if (languages.Count > 0 && languages[0] == c_InvariantCulturePrivateName)
+ {
+ languages[0] = CultureInfo.InvariantCulture.Name;
+ }
+
s_globalResourceContextBestFitCultureInfo = GetBestFitCultureFromLanguageList(languages);
s_globalResourceContextFallBackList = ReadOnlyListToString(languages);
}
@@ -448,7 +470,7 @@ namespace System.Resources
}
List<String> languages = new List<String>(s_globalResourceContext.Languages);
- languages.Insert(0, ci.Name);
+ languages.Insert(0, ci.Name == CultureInfo.InvariantCulture.Name ? c_InvariantCulturePrivateName : ci.Name);
// remove any duplication in the list
int i = languages.Count - 1;
diff --git a/src/System.Runtime.WindowsRuntime/tests/System.Runtime.WindowsRuntime.Tests.csproj b/src/System.Runtime.WindowsRuntime/tests/System.Runtime.WindowsRuntime.Tests.csproj
index f4db6d339e..b318075ac0 100644
--- a/src/System.Runtime.WindowsRuntime/tests/System.Runtime.WindowsRuntime.Tests.csproj
+++ b/src/System.Runtime.WindowsRuntime/tests/System.Runtime.WindowsRuntime.Tests.csproj
@@ -20,9 +20,6 @@
<Compile Include="Windows\Foundation\RectTests.cs" />
<Compile Include="Windows\Foundation\SizeTests.cs" />
<Compile Include="Windows\UI\ColorTests.cs" />
- <Compile Include="$(CommonTestPath)\System\AssertExtensions.cs">
- <Link>Common\System\AssertExtensions.cs</Link>
- </Compile>
</ItemGroup>
<ItemGroup>
<Reference Include="Windows" />
diff --git a/src/System.Runtime/tests/ArrayTests.cs b/src/System.Runtime/tests/ArrayTests.cs
index 53a37a915d..6f4c26aafa 100644
--- a/src/System.Runtime/tests/ArrayTests.cs
+++ b/src/System.Runtime/tests/ArrayTests.cs
@@ -13,117 +13,6 @@ namespace System.Tests
public static class Array17Tests
{
[Fact]
- public static void AsReadOnly()
- {
- var array = new string[] { "a", "b" };
- System.Collections.ObjectModel.ReadOnlyCollection<string> ro = Array.AsReadOnly(array);
- Assert.Equal(array, ro);
- Assert.Equal(new System.Collections.ObjectModel.ReadOnlyCollection<string>(array), ro);
- }
-
- [Fact]
- public static void Construction()
- {
- // Check a number of the simple APIs on Array for dimensions up to 4.
- Array array = new int[] { 1, 2, 3 };
- VerifyArray(array, 1, new int[] { 3 }, new int[] { 0 }, new int[] { 2 }, true);
-
- array = new int[,] { { 1, 2, 3 }, { 4, 5, 6 } };
- VerifyArray(array, 2, new int[] { 2, 3 }, new int[] { 0, 0 }, new int[] { 1, 2 }, true);
-
- array = new int[2, 3, 4];
- VerifyArray(array, 3, new int[] { 2, 3, 4 }, new int[] { 0, 0, 0 }, new int[] { 1, 2, 3 }, true);
-
- array = new int[2, 3, 4, 5];
- VerifyArray(array, 4, new int[] { 2, 3, 4, 5 }, new int[] { 0, 0, 0, 0 }, new int[] { 1, 2, 3, 4 }, true);
- }
-
- [Theory]
- public static void ForEach()
- {
- Array.ForEach<int>(new int[] { }, new Action<int>(i => { throw new InvalidOperationException(); }));
- // Did not throw; no items
-
- int counter = 0;
- int exp = 0;
- Array.ForEach<int>(new int[] { 1, 2, 3 }, new Action<int>(i => { counter += i; exp = (i==1)?1:(i==2)?3:6; Assert.Equal(exp, counter); }));
- }
-
- [Fact]
- public static void ForEach_Invalid()
- {
- AssertExtensions.Throws<ArgumentNullException>("array", () => { Array.ForEach<short>(null, new Action<short>(i => i++)); }); // Array is null
- AssertExtensions.Throws<ArgumentNullException>("action", () => { Array.ForEach<string>(new string[] { }, null); }); // Action is null
- Assert.Throws<InvalidOperationException>(() => {
- Array.ForEach<string>(new string[] { "a" }, i => { throw new InvalidOperationException(); }); // Action throws
- });
- }
-
- public static IEnumerable<object[]> Copy_TestData()
- {
- yield return new object[] { new int[] { 0x12345678, 0x22334455, 0x778899aa }, 0, new int[3], 0, 3, new int[] { 0x12345678, 0x22334455, 0x778899aa } };
-
- int[] intArray1 = new int[] { 0x12345678, 0x22334455, 0x778899aa, 0x55443322, 0x33445566 };
- yield return new object[] { intArray1, 3, intArray1, 2, 2, new int[] { 0x12345678, 0x22334455, 0x55443322, 0x33445566, 0x33445566 } };
-
- int[] intArray2 = new int[] { 0x12345678, 0x22334455, 0x778899aa, 0x55443322, 0x33445566 };
- yield return new object[] { intArray2, 2, intArray2, 3, 2, new int[] { 0x12345678, 0x22334455, 0x778899aa, 0x778899aa, 0x55443322 } };
-
- yield return new object[] { new string[] { "Red", "Green", null, "Blue" }, 0, new string[] { "X", "X", "X", "X" }, 0, 4, new string[] { "Red", "Green", null, "Blue" } };
-
- string[] stringArray = new string[] { "Red", "Green", null, "Blue" };
- yield return new object[] { stringArray, 1, stringArray, 2, 2, new string[] { "Red", "Green", "Green", null } };
-
- // Value type array to reference type array
- yield return new object[] { new int[] { 0, 1, 2, 3, 4, 5, 6, 7, 8, 9 }, 2, new object[10], 5, 3, new object[] { null, null, null, null, null, 2, 3, 4, null, null } };
- yield return new object[] { new int[] { 0, 1, 2, 3, 4, 5, 6, 7, 8, 9 }, 2, new IEquatable<int>[10], 5, 3, new IEquatable<int>[] { null, null, null, null, null, 2, 3, 4, null, null } };
- yield return new object[] { new int?[] { 0, 1, 2, default(int?), 4, 5, 6, 7, 8, 9 }, 2, new object[10], 5, 3, new object[] { null, null, null, null, null, 2, null, 4, null, null } };
-
- // Reference type array to value type array
- yield return new object[] { new object[] { 0, 1, 2, 3, 4, 5, 6, 7, 8, 9 }, 2, new int[] { 0xcc, 0xcc, 0xcc, 0xcc, 0xcc, 0xcc, 0xcc, 0xcc, 0xcc, 0xcc }, 5, 3, new int[] { 0xcc, 0xcc, 0xcc, 0xcc, 0xcc, 2, 3, 4, 0xcc, 0xcc } };
- yield return new object[] { new IEquatable<int>[] { 0, 1, 2, 3, 4, 5, 6, 7, 8, 9 }, 2, new int[] { 0xcc, 0xcc, 0xcc, 0xcc, 0xcc, 0xcc, 0xcc, 0xcc, 0xcc, 0xcc }, 5, 3, new int[] { 0xcc, 0xcc, 0xcc, 0xcc, 0xcc, 2, 3, 4, 0xcc, 0xcc } };
- yield return new object[] { new IEquatable<int>[] { 0, new NotInt32(), 2, 3, 4, new NotInt32(), 6, 7, 8, 9 }, 2, new int[] { 0xcc, 0xcc, 0xcc, 0xcc, 0xcc, 0xcc, 0xcc, 0xcc, 0xcc, 0xcc }, 5, 3, new int[] { 0xcc, 0xcc, 0xcc, 0xcc, 0xcc, 2, 3, 4, 0xcc, 0xcc } };
-
- yield return new object[] { new object[] { 0, 1, 2, 3, null, 5, 6, 7, 8, 9 }, 2, new int?[] { 0xcc, 0xcc, 0xcc, 0xcc, 0xcc, 0xcc, 0xcc, 0xcc, 0xcc, 0xcc }, 5, 3, new int?[] { 0xcc, 0xcc, 0xcc, 0xcc, 0xcc, 2, 3, null, 0xcc, 0xcc } };
- }
-
- [Theory]
- [MemberData(nameof(Copy_TestData))]
- public static void Copy_Long(Array sourceArray, int sourceIndex, Array destinationArray, int destinationIndex, int length, Array expected)
- {
- if (sourceIndex == 0 && destinationIndex == 0)
- {
- // Use Copy(Array, Array, long)
- Array testArray = (Array)sourceArray.Clone();
- Array.Copy(sourceArray, destinationArray, (long)length);
- Assert.Equal(expected, destinationArray);
- }
- // Use Copy(Array, long, Array, long, long)
- Array.Copy(sourceArray, (long)sourceIndex, destinationArray, (long)destinationIndex, (long)length);
- Assert.Equal(expected, destinationArray);
- }
-
- public static IEnumerable<object[]> CopyTo_TestData()
- {
- yield return new object[] { new B1[10], new D1[10], 0, new D1[10] };
- yield return new object[] { new D1[10], new B1[10], 0, new B1[10] };
- yield return new object[] { new B1[10], new I1[10], 0, new I1[10] };
- yield return new object[] { new I1[10], new B1[10], 0, new B1[10] };
-
- yield return new object[] { new int[] { 0, 1, 2, 3 }, new int[4], 0, new int[] { 0, 1, 2, 3 } };
- yield return new object[] { new int[] { 0, 1, 2, 3 }, new int[7], 2, new int[] { 0, 0, 0, 1, 2, 3, 0 } };
- }
-
- [Theory]
- [MemberData(nameof(CopyTo_TestData))]
- public static void CopyTo_Long(Array source, Array destination, long index, Array expected)
- {
- source.CopyTo(destination, index);
- Assert.Equal(expected, destination);
- }
-
- [Fact]
- [SkipOnTargetFramework(TargetFrameworkMonikers.UapAot, "Linked to spurious fail-fast on UapAot: https://github.com/dotnet/corefx/issues/18584")]
public static void CreateInstance_Type_Int_Int()
{
int[,] intArray2 = (int[,])Array.CreateInstance(typeof(int), 1, 2);
@@ -133,7 +22,6 @@ namespace System.Tests
}
[Fact]
- [SkipOnTargetFramework(TargetFrameworkMonikers.UapAot, "Linked to spurious fail-fast on UapAot: https://github.com/dotnet/corefx/issues/18584")]
public static void CreateInstance_Type_Int_Invalid()
{
AssertExtensions.Throws<ArgumentNullException>("elementType", () => Array.CreateInstance(null, 0)); // Element type is null
@@ -146,7 +34,6 @@ namespace System.Tests
}
[Fact]
- [SkipOnTargetFramework(TargetFrameworkMonikers.UapAot, "Linked to spurious fail-fast on UapAot: https://github.com/dotnet/corefx/issues/18584")]
public static void CreateInstance_Type_Int_Int_Invalid()
{
AssertExtensions.Throws<ArgumentNullException>("elementType", () => Array.CreateInstance(null, 0, 1)); // Element type is null
@@ -159,7 +46,6 @@ namespace System.Tests
}
[Fact]
- [SkipOnTargetFramework(TargetFrameworkMonikers.UapAot, "Linked to spurious fail-fast on UapAot: https://github.com/dotnet/corefx/issues/18584")]
public static void CreateInstance_Type_Int_Int_Int()
{
int[,,] intArray3 = (int[,,])Array.CreateInstance(typeof(int), 1, 2, 3);
@@ -169,7 +55,6 @@ namespace System.Tests
}
[Fact]
- [SkipOnTargetFramework(TargetFrameworkMonikers.UapAot, "Linked to spurious fail-fast on UapAot: https://github.com/dotnet/corefx/issues/18584")]
public static void CreateInstance_Type_Int_Int_Int_Invalid()
{
AssertExtensions.Throws<ArgumentNullException>("elementType", () => Array.CreateInstance(null, 0, 1, 2)); // Element type is null
@@ -182,7 +67,6 @@ namespace System.Tests
}
[Fact]
- [SkipOnTargetFramework(TargetFrameworkMonikers.UapAot, "Linked to spurious fail-fast on UapAot: https://github.com/dotnet/corefx/issues/18584")]
public static void CreateInstance_Type_IntArray()
{
string[] stringArray = (string[])Array.CreateInstance(typeof(string), new int[] { 10 });
@@ -212,176 +96,18 @@ namespace System.Tests
}
[Fact]
- [SkipOnTargetFramework(TargetFrameworkMonikers.UapAot, "Linked to spurious fail-fast on UapAot: https://github.com/dotnet/corefx/issues/18584")]
public static void CreateInstance_Type_IntArray_IntArray()
{
int[] intArray1 = (int[])Array.CreateInstance(typeof(int), new int[] { 5 }, new int[] { 0 });
Assert.Equal(intArray1, new int[5]);
VerifyArray(intArray1, 1, new int[] { 5 }, new int[] { 0 }, new int[] { 4 }, false);
- int[,,] intArray2 = (int[,,])Array.CreateInstance(typeof(int), new int[] { 7, 8, 9 }, new int[] { 1, 2, 3 });
- Assert.Equal(intArray2, new int[7, 8, 9]);
- VerifyArray(intArray2, 3, new int[] { 7, 8, 9 }, new int[] { 1, 2, 3 }, new int[] { 7, 9, 11 }, false);
- }
-
- [Theory]
- public static void ConvertAll()
- {
- var result = Array.ConvertAll<int, int>(new int[] { }, new Converter<int, int>(i => { throw new InvalidOperationException(); }));
- // Does not throw - no entries
- Assert.Equal(new int[] { }, result);
-
- var result2 = Array.ConvertAll<int, string>(new int[] { 1 }, new Converter<int, string>(i => i++.ToString()));
- Assert.Equal(new string[] { "2" }, result2);
-
- result2 = Array.ConvertAll<int, string>(new int[] { 1, 2 }, new Converter<int, string>(i => i++.ToString()));
- Assert.Equal(new string[] { "2", "3" }, result2);
-
- result2 = Array.ConvertAll<int, string>(new int[] { 1 }, new Converter<int, string>(i => null));
- Assert.Equal(new string[] { null }, result2);
- }
-
- [Fact]
- public static void ConvertAll_Invalid()
- {
- AssertExtensions.Throws<ArgumentNullException>("array", () => { Array.ConvertAll<short, short>(null, i => i); }); // Array is null
- AssertExtensions.Throws<ArgumentNullException>("converter", () => { Array.ConvertAll<string, string>(new string[] { }, null); }); // Converter is null
- Assert.Throws<InvalidOperationException>(() => {
- Array.ConvertAll<string, string>(new string[] { "x" }, i => { throw new InvalidOperationException(); }); // Converter throws
- });
- }
-
- [Fact]
- public static void IsFixedSize()
- {
- Assert.Equal(true, new string[] { }.IsFixedSize);
- }
-
- [Fact]
- public static void IsReadOnly()
- {
- Assert.Equal(false, new int[] { }.IsReadOnly);
- }
-
- [Fact]
- public static void IsSynchronized()
- {
- Assert.Equal(false, new int[] { }.IsSynchronized);
- }
-
- public static IEnumerable<object[]> Length_TestData()
- {
- yield return new object[] { new object[] { }, 0 };
- yield return new object[] { new object[] { 1, 2 }, 2 };
- }
-
- [Theory]
- [MemberData(nameof(Length_TestData))]
- public static void Length(Array array, int expected)
- {
- Assert.Equal(expected, array.Length);
- Assert.Equal(expected, array.LongLength);
- }
-
- [Fact]
- public static void SyncRoot_Equals_This()
- {
- var array = new string[] { };
- Assert.Same(array, array.SyncRoot);
- }
-
- internal static void VerifyArray(Array array, int rank, int[] lengths, int[] lowerBounds, int[] upperBounds, bool checkIList)
- {
- Assert.Equal(rank, array.Rank);
-
- for (int i = 0; i < lengths.Length; i++)
+ if (PlatformDetection.IsNonZeroLowerBoundArraySupported)
{
- Assert.Equal(lengths[i], array.GetLength(i));
- Assert.Equal(lengths[i], array.GetLongLength(i));
- }
-
- for (int i = 0; i < lowerBounds.Length; i++)
- Assert.Equal(lowerBounds[i], array.GetLowerBound(i));
-
- for (int i = 0; i < upperBounds.Length; i++)
- Assert.Equal(upperBounds[i], array.GetUpperBound(i));
-
-
- Assert.Throws<IndexOutOfRangeException>(() => array.GetLength(-1)); // Dimension < 0
- Assert.Throws<IndexOutOfRangeException>(() => array.GetLength(array.Rank)); // Dimension >= array.Rank
-
- Assert.Throws<IndexOutOfRangeException>(() => array.GetLowerBound(-1)); // Dimension < 0
- Assert.Throws<IndexOutOfRangeException>(() => array.GetLowerBound(array.Rank)); // Dimension >= array.Rank
-
- Assert.Throws<IndexOutOfRangeException>(() => array.GetUpperBound(-1)); // Dimension < 0
- Assert.Throws<IndexOutOfRangeException>(() => array.GetUpperBound(array.Rank)); // Dimension >= array.Rank
-
- if (checkIList)
- {
- VerifyArrayAsIList(array);
- }
-
- Assert.Equal(array, array.SyncRoot);
-
- Assert.False(array.IsSynchronized);
- Assert.True(array.IsFixedSize);
- Assert.False(array.IsReadOnly);
- }
-
- private static void VerifyArrayAsIList(Array array)
- {
- IList ils = array;
- Assert.Equal(array.Length, ils.Count);
-
- Assert.Equal(array, ils.SyncRoot);
-
- Assert.False(ils.IsSynchronized);
- Assert.True(ils.IsFixedSize);
- Assert.False(ils.IsReadOnly);
-
- Assert.Throws<NotSupportedException>(() => ils.Add(2));
- Assert.Throws<NotSupportedException>(() => ils.Insert(0, 2));
- Assert.Throws<NotSupportedException>(() => ils.Remove(0));
- Assert.Throws<NotSupportedException>(() => ils.RemoveAt(0));
-
- if (array.Rank == 1)
- {
- for (int i = 0; i < array.Length; i++)
- {
- object obj = ils[i];
- Assert.Equal(array.GetValue(i), obj);
- Assert.True(ils.Contains(obj));
- Assert.Equal(i, ils.IndexOf(obj));
- }
-
- Assert.False(ils.Contains(null));
- Assert.False(ils.Contains(999));
- Assert.Equal(-1, ils.IndexOf(null));
- Assert.Equal(-1, ils.IndexOf(999));
-
- ils[1] = 10;
- Assert.Equal(10, ils[1]);
- }
- else
- {
- Assert.Throws<RankException>(() => ils.Contains(null));
- Assert.Throws<RankException>(() => ils.IndexOf(null));
+ int[,,] intArray2a = (int[,,])Array.CreateInstance(typeof(int), new int[] { 7, 8, 9 }, new int[] { 1, 2, 3 });
+ Assert.Equal(intArray2a, new int[7, 8, 9]);
+ VerifyArray(intArray2a, 3, new int[] { 7, 8, 9 }, new int[] { 1, 2, 3 }, new int[] { 7, 9, 11 }, false);
}
}
-
- private class NotInt32 : IEquatable<int>
- {
- public bool Equals(int other)
- {
- throw new NotImplementedException();
- }
- }
-
- private class B1 { }
- private class D1 : B1 { }
- private class B2 { }
- private class D2 : B2 { }
- private interface I1 { }
- private interface I2 { }
}
}
diff --git a/src/System.Runtime/tests/ArrayTests.netcoreapp.cs b/src/System.Runtime/tests/ArrayTests.netcoreapp.cs
index f9b86ad6ac..d3e15dfd95 100644
--- a/src/System.Runtime/tests/ArrayTests.netcoreapp.cs
+++ b/src/System.Runtime/tests/ArrayTests.netcoreapp.cs
@@ -13,7 +13,6 @@ namespace System.Tests
public static class ArrayNetcoreappTests
{
[Fact]
- [ActiveIssue("https://github.com/dotnet/corert/issues/3650 - Wrong exception thrown", TargetFrameworkMonikers.UapAot)]
public static void CreateInstance_Type_Int_Invalid()
{
foreach (Type nonRuntimeType in Helpers.NonRuntimeTypes)
@@ -24,7 +23,6 @@ namespace System.Tests
}
[Fact]
- [ActiveIssue("https://github.com/dotnet/corert/issues/3650 - Wrong exception thrown", TargetFrameworkMonikers.UapAot)]
public static void CreateInstance_Type_Int_Int_Invalid()
{
foreach (Type nonRuntimeType in Helpers.NonRuntimeTypes)
@@ -35,7 +33,6 @@ namespace System.Tests
}
[Fact]
- [ActiveIssue("https://github.com/dotnet/corert/issues/3650 - Wrong exception thrown", TargetFrameworkMonikers.UapAot)]
public static void CreateInstance_Type_Int_Int_Int_Invalid()
{
foreach (Type nonRuntimeType in Helpers.NonRuntimeTypes)
diff --git a/src/System.Runtime/tests/DBNullTests.cs b/src/System.Runtime/tests/DBNullTests.cs
deleted file mode 100644
index 526fc216ac..0000000000
--- a/src/System.Runtime/tests/DBNullTests.cs
+++ /dev/null
@@ -1,83 +0,0 @@
-// Licensed to the .NET Foundation under one or more agreements.
-// The .NET Foundation licenses this file to you under the MIT license.
-// See the LICENSE file in the project root for more information.
-
-using Xunit;
-
-namespace System.Tests
-{
- public static partial class DBNullTests
- {
- [Fact]
- public static void TestToString()
- {
- Assert.Equal(string.Empty, DBNull.Value.ToString());
- }
-
- [Fact]
- public static void TestToUInt64_Invalid()
- {
- Assert.Throws<InvalidCastException>(() => ((IConvertible)DBNull.Value).ToUInt64(null));
- }
-
- [Fact]
- public static void TestToChar_Invalid()
- {
- Assert.Throws<InvalidCastException>(() => ((IConvertible)DBNull.Value).ToChar(null));
- }
-
- [Fact]
- public static void TestToDateTime_Invalid()
- {
- Assert.Throws<InvalidCastException>(() => ((IConvertible)DBNull.Value).ToDateTime(null));
- }
-
- [Fact]
- public static void TestGetTypeCode()
- {
- Assert.Equal(TypeCode.DBNull, DBNull.Value.GetTypeCode());
- }
-
- [Fact]
- public static void TestEquals()
- {
- DBNull MyNull = DBNull.Value;
- Assert.True(DBNull.Value.Equals(MyNull));
- }
-
- [Fact]
- public static void TestEquals_Invalid()
- {
- DBNull MyNull = null;
- Assert.False(DBNull.Value.Equals(MyNull));
- }
-
- [Fact]
- public static void Test_ToType()
- {
- Type typeParam = Type.GetType("System.String");
- Assert.Equal(string.Empty, ((IConvertible)DBNull.Value).ToType(typeParam, null));
- }
-
- [Fact]
- public static void Test_ToType_Invalid()
- {
- Type typeParam = Type.GetType("System.Int32");
- Assert.Throws<InvalidCastException>(() => ((IConvertible)DBNull.Value).ToType(typeParam, null));
- }
-
- [Fact]
- public static void Test_ConvertIsDBNull()
- {
- Assert.Equal(true, Convert.IsDBNull(DBNull.Value));
- Assert.Equal(false, Convert.IsDBNull((Int32)6678));
- Assert.Equal(false, Convert.IsDBNull(new object()));
- }
-
- [Fact]
- public static void Test_ConvertDBNUll()
- {
- Assert.Equal(Convert.DBNull, DBNull.Value);
- }
- }
-} \ No newline at end of file
diff --git a/src/System.Runtime/tests/EnumTests.cs b/src/System.Runtime/tests/EnumTests.cs
deleted file mode 100644
index 947d1ee709..0000000000
--- a/src/System.Runtime/tests/EnumTests.cs
+++ /dev/null
@@ -1,45 +0,0 @@
-// Licensed to the .NET Foundation under one or more agreements.
-// The .NET Foundation licenses this file to you under the MIT license.
-// See the LICENSE file in the project root for more information.
-
-using System;
-using System.Globalization;
-using Xunit;
-
-namespace System.Tests
-{
- public static partial class EnumTests
- {
- [Theory]
- [InlineData(SimpleEnum.Blue, TypeCode.Int32)]
- [InlineData(ByteEnum.Max, TypeCode.Byte)]
- [InlineData(SByteEnum.Min, TypeCode.SByte)]
- [InlineData(UInt16Enum.Max, TypeCode.UInt16)]
- [InlineData(Int16Enum.Min, TypeCode.Int16)]
- [InlineData(UInt32Enum.Max, TypeCode.UInt32)]
- [InlineData(Int32Enum.Min, TypeCode.Int32)]
- [InlineData(UInt64Enum.Max, TypeCode.UInt64)]
- [InlineData(Int64Enum.Min, TypeCode.Int64)]
- public static void GetTypeCode(Enum e, TypeCode expected)
- {
- Assert.Equal(expected, e.GetTypeCode());
- }
-
-#pragma warning disable 618
- [Fact]
- public static void ToString_FormatProvider()
- {
- // FormatProvider parameter is ignored
- Assert.Equal("Blue", SimpleEnum.Blue.ToString(CultureInfo.CurrentCulture));
- }
-
- [Theory]
- [MemberData(nameof(ToString_Format_TestData))]
- public static void ToString_FormatProvider2(Enum e, string format, string expected)
- {
- // FormatProvider parameter is ignored
- Assert.Equal(expected, e.ToString(format, CultureInfo.CurrentCulture));
- }
-#pragma warning restore 618
- }
-}
diff --git a/src/System.Runtime/tests/GetTypeCodeTests.cs b/src/System.Runtime/tests/GetTypeCodeTests.cs
deleted file mode 100644
index 3e53be6d03..0000000000
--- a/src/System.Runtime/tests/GetTypeCodeTests.cs
+++ /dev/null
@@ -1,36 +0,0 @@
-// Licensed to the .NET Foundation under one or more agreements.
-// The .NET Foundation licenses this file to you under the MIT license.
-// See the LICENSE file in the project root for more information.
-
-using System;
-using Xunit;
-
-namespace System.Tests
-{
- public static partial class GetTypeCodeTests
- {
- [Theory]
- [InlineData(TypeCode.Boolean, false)]
- [InlineData(TypeCode.Char, 'x')]
- [InlineData(TypeCode.Double, 42.0)]
- [InlineData(TypeCode.Int32, 42)]
- [InlineData(TypeCode.Int64, 42L)]
- [InlineData(TypeCode.Single, 42f)]
- [InlineData(TypeCode.UInt32, 42u)]
- [InlineData(TypeCode.UInt64, 42ul)]
- [InlineData(TypeCode.Byte, (byte)1)]
- [InlineData(TypeCode.Int16, (short)1)]
- [InlineData(TypeCode.SByte, (sbyte)1)]
- [InlineData(TypeCode.UInt16, (ushort)1)]
- public static void GetTypeCode_Primitives(TypeCode expected, IConvertible convertible)
- {
- Assert.Equal(expected, convertible.GetTypeCode());
- }
-
- [Fact]
- public static void FromDecimal()
- {
- Assert.Equal(TypeCode.Decimal, decimal.MinValue.GetTypeCode());
- }
- }
-}
diff --git a/src/System.Runtime/tests/Resources/System.Runtime.Tests.rd.xml b/src/System.Runtime/tests/Resources/System.Runtime.Tests.rd.xml
new file mode 100644
index 0000000000..8c50934a34
--- /dev/null
+++ b/src/System.Runtime/tests/Resources/System.Runtime.Tests.rd.xml
@@ -0,0 +1,7 @@
+<Directives xmlns="http://schemas.microsoft.com/netfx/2013/01/metadata">
+ <Library>
+ <!-- Needed because of objects in [Theory] data which causes xunit to reflect on its ToString() -->
+ <Type Name="System.DBNull" Dynamic="Required Public" />
+ </Library>
+</Directives>
+
diff --git a/src/System.Runtime/tests/System.Runtime.Tests.csproj b/src/System.Runtime/tests/System.Runtime.Tests.csproj
index 4a1c406ee7..3d7021a239 100644
--- a/src/System.Runtime/tests/System.Runtime.Tests.csproj
+++ b/src/System.Runtime/tests/System.Runtime.Tests.csproj
@@ -18,9 +18,6 @@
<PropertyGroup Condition="'$(Configuration)|$(Platform)' == 'uapaot-Debug|AnyCPU'" />
<PropertyGroup Condition="'$(Configuration)|$(Platform)' == 'uapaot-Release|AnyCPU'" />
<ItemGroup>
- <Compile Include="$(CommonTestPath)\System\AssertExtensions.cs">
- <Link>Common\System\AssertExtensions.cs</Link>
- </Compile>
<Compile Include="$(CommonTestPath)\System\EnumTypes.cs">
<Link>Common\System\EnumTypes.cs</Link>
</Compile>
@@ -51,64 +48,64 @@
<Compile Include="$(CommonTestPath)\System\Reflection\MockParameterInfo.cs">
<Link>Common\System\Reflection\MockParameterInfo.cs</Link>
</Compile>
+ <Compile Include="TimeZoneInfoTests.cs" />
+ <Compile Include="Microsoft\Win32\SafeHandles\CriticalHandleZeroOrMinusOneIsInvalid.cs" />
+ <Compile Include="Microsoft\Win32\SafeHandles\SafeHandleZeroOrMinusOneIsInvalid.cs" />
+ <Compile Include="System\AccessViolationExceptionTests.cs" />
<Compile Include="System\ActivatorTests.cs" />
<Compile Include="System\ArrayTests.cs" />
- <Compile Include="System\AttributeTests.cs" />
<Compile Include="System\ArraySegmentTests.cs" />
+ <Compile Include="System\ApplicationExceptionTests.cs" />
+ <Compile Include="System\AttributeTests.cs" />
+ <Compile Include="System\Attributes.cs" />
+ <Compile Include="System\BadImageFormatExceptionTests.cs" />
<Compile Include="System\BooleanTests.cs" />
<Compile Include="System\BufferTests.cs" />
<Compile Include="System\ByteTests.cs" />
<Compile Include="System\CharTests.cs" />
- <Compile Include="System\Collections\Generic\KeyValuePairTests.cs" />
- <Compile Include="System\Collections\ObjectModel\CollectionTests.cs" />
- <Compile Include="System\Collections\ObjectModel\CollectionTestBase.cs" />
- <Compile Include="System\Collections\ObjectModel\ReadOnlyCollectionTests.cs" />
- <Compile Include="System\ComponentModel\EditorBrowsableAttributeTests.cs" />
- <Compile Include="System\ComponentModel\DefaultValueAttributeTests.cs" />
<Compile Include="System\DateTimeTests.cs" />
<Compile Include="System\DateTimeOffsetTests.cs" />
+ <Compile Include="System\DBNullTests.cs" />
<Compile Include="System\DecimalTests.cs" />
<Compile Include="System\DelegateTests.cs" />
<Compile Include="System\DoubleTests.cs" />
+ <Compile Include="System\DuplicateWaitObjectExceptionTests.cs" />
+ <Compile Include="System\EntryPointNotFoundExceptionTests.cs" />
<Compile Include="System\EnumTests.cs" />
+ <Compile Include="System\ExceptionTests.cs" />
+ <Compile Include="System\ExecutionEngineExceptionTests.cs" />
+ <Compile Include="System\ExternalExceptionTests.cs" />
<Compile Include="System\FieldAccessExceptionTests.cs" />
<Compile Include="System\GCTests.cs" />
<Compile Include="System\GuidTests.cs" />
+ <Compile Include="System\HandleTests.cs" />
<Compile Include="System\Int16Tests.cs" />
<Compile Include="System\Int32Tests.cs" />
<Compile Include="System\Int64Tests.cs" />
<Compile Include="System\IntPtrTests.cs" />
- <Compile Include="System\IO\DirectoryNotFoundExceptionTests.cs" />
- <Compile Include="System\IO\DirectoryNotFoundException.InteropTests.cs" />
- <Compile Include="System\IO\EndOfStreamExceptionTests.cs" />
- <Compile Include="System\IO\Exceptions.HResults.cs" />
- <Compile Include="System\IO\Exceptions.Utility.cs" />
- <Compile Include="System\IO\FileLoadExceptionTests.cs" />
- <Compile Include="System\IO\FileLoadException.InteropTests.cs" />
- <Compile Include="System\IO\FileNotFoundException.InteropTests.cs" />
- <Compile Include="System\IO\FileNotFoundExceptionTests.cs" />
- <Compile Include="System\IO\PathTooLongExceptionTests.cs" />
- <Compile Include="System\IO\PathTooLongException.InteropTests.cs" />
<Compile Include="System\LazyTests.cs" />
<Compile Include="System\LazyOfTMetadataTests.cs" />
+ <Compile Include="System\MarshalByRefObjectTests.cs" />
<Compile Include="System\MethodAccessExceptionTests.cs" />
<Compile Include="System\MissingFieldExceptionTests.cs" />
+ <Compile Include="System\MissingMemberExceptionTests.cs" />
<Compile Include="System\MissingMethodExceptionTests.cs" />
<Compile Include="System\MulticastDelegateTests.cs" />
+ <Compile Include="System\NotFiniteNumberExceptionTests.cs" />
<Compile Include="System\NullableTests.cs" />
<Compile Include="System\NullReferenceExceptionTests.cs" />
<Compile Include="System\ObjectTests.cs" />
- <Compile Include="System\Runtime\CompilerServices\ConditionalWeakTableTests.cs" />
- <Compile Include="System\Runtime\CompilerServices\StrongBoxTests.cs" />
- <Compile Include="System\Runtime\CompilerServices\RuntimeHelpersTests.cs" />
<Compile Include="System\SByteTests.cs" />
<Compile Include="System\SingleTests.cs" />
+ <Compile Include="System\StackOverflowExceptionTests.cs" />
<Compile Include="System\StringTests.cs" />
<Compile Include="System\String.SplitTests.cs" />
- <Compile Include="System\Text\StringBuilderTests.cs" />
- <Compile Include="System\Threading\WaitHandleTests.cs" />
+ <Compile Include="System\SystemExceptionTests.cs" />
<Compile Include="System\TimeSpanTests.cs" />
<Compile Include="System\TimeZoneInfoTests.cs" />
+ <Compile Include="System\TimeZoneTests.cs" />
+ <Compile Include="System\TimeZoneNotFoundExceptionTests.cs" />
+ <Compile Include="System\TypeUnloadedExceptionTests.cs" />
<Compile Include="System\TupleTests.cs" />
<Compile Include="System\TypeTests.cs" />
<Compile Include="System\UInt16Tests.cs" />
@@ -121,6 +118,57 @@
<Compile Include="System\ValueTypeTests.cs" />
<Compile Include="System\VersionTests.cs" />
<Compile Include="System\WeakReferenceTests.cs" />
+ <Compile Include="System\AppContext\AppContext.Switch.cs" />
+ <Compile Include="System\AppContext\AppContext.Switch.Validation.cs" />
+ <Compile Include="System\Collections\Generic\KeyValuePairTests.cs" />
+ <Compile Include="System\Collections\ObjectModel\CollectionTests.cs" />
+ <Compile Include="System\Collections\ObjectModel\CollectionTestBase.cs" />
+ <Compile Include="System\Collections\ObjectModel\ReadOnlyCollectionTests.cs" />
+ <Compile Include="System\ComponentModel\DefaultValueAttributeTests.cs" />
+ <Compile Include="System\ComponentModel\EditorBrowsableAttributeTests.cs" />
+ <Compile Include="System\IO\DirectoryNotFoundExceptionTests.cs" />
+ <Compile Include="System\IO\DirectoryNotFoundException.InteropTests.cs" />
+ <Compile Include="System\IO\EndOfStreamExceptionTests.cs" />
+ <Compile Include="System\IO\Exceptions.HResults.cs" />
+ <Compile Include="System\IO\Exceptions.Utility.cs" />
+ <Compile Include="System\IO\FileLoadExceptionTests.cs" />
+ <Compile Include="System\IO\FileLoadException.InteropTests.cs" />
+ <Compile Include="System\IO\FileNotFoundExceptionTests.cs" />
+ <Compile Include="System\IO\FileNotFoundException.InteropTests.cs" />
+ <Compile Include="System\IO\PathTooLongExceptionTests.cs" />
+ <Compile Include="System\IO\PathTooLongException.InteropTests.cs" />
+ <Compile Include="System\Reflection\AssemblyTests.cs" />
+ <Compile Include="System\Reflection\AssemblyNameTests.cs" />
+ <Compile Include="System\Reflection\ConstructorInfoTests.cs" />
+ <Compile Include="System\Reflection\CustomAttributeDataTests.cs" />
+ <Compile Include="System\Reflection\CustomAttributesTestData.cs" />
+ <Compile Include="System\Reflection\CustomAttribute_Named_Typed_ArgumentTests.cs" />
+ <Compile Include="System\Reflection\EventInfoTests.cs" />
+ <Compile Include="System\Reflection\FieldInfoTests.cs" />
+ <Compile Include="System\Reflection\MemberInfoTests.cs" />
+ <Compile Include="System\Reflection\MethodBaseTests.cs" />
+ <Compile Include="System\Reflection\MethodBodyTests.cs" />
+ <Compile Include="System\Reflection\MethodInfoTests.cs" />
+ <Compile Include="System\Reflection\ModuleTests.cs" />
+ <Compile Include="System\Reflection\ParameterInfoTests.cs" />
+ <Compile Include="System\Reflection\PointerTests.cs" />
+ <Compile Include="System\Reflection\PropertyInfoTests.cs" />
+ <Compile Include="System\Reflection\RuntimeReflectionExtensionsTests.cs" />
+ <Compile Include="System\Reflection\StrongNameKeyPairTests.cs" />
+ <Compile Include="System\Reflection\TypeDelegatorTests.cs" />
+ <Compile Include="System\Reflection\TypeInfoTests.cs" />
+ <Compile Include="System\Reflection\TypeTests.Get.CornerCases.cs" />
+ <Compile Include="System\Reflection\TypeTests.GetInterface.cs" />
+ <Compile Include="System\Reflection\TypeTests.GetMember.cs" />
+ <Compile Include="System\Runtime\MemoryFailPointTests.cs" />
+ <Compile Include="System\Runtime\NgenServicingAttributesTests.cs" />
+ <Compile Include="System\Runtime\CompilerServices\ConditionalWeakTableTests.cs" />
+ <Compile Include="System\Runtime\CompilerServices\StrongBoxTests.cs" />
+ <Compile Include="System\Runtime\CompilerServices\RuntimeHelpersTests.cs" />
+ <Compile Include="System\Runtime\ExceptionServices\HandleProcessCorruptedStateExceptions.cs" />
+ <Compile Include="System\Security\SecurityAttributeTests.cs" />
+ <Compile Include="System\Text\StringBuilderTests.cs" />
+ <Compile Include="System\Threading\WaitHandleTests.cs" />
<Compile Include="$(CommonTestPath)\System\RandomDataGenerator.cs">
<Link>Common\System\RandomDataGenerator.cs</Link>
</Compile>
@@ -129,9 +177,6 @@
</Compile>
</ItemGroup>
<ItemGroup Condition="'$(TargetGroup)' == 'netcoreapp' or '$(TargetGroup)' == 'uapaot'">
- <Compile Include="System\TypeTests.netcoreapp.cs" />
- <Compile Include="System\Reflection\MethodBaseTests.netcoreapp.cs" />
- <Compile Include="ArrayTests.netcoreapp.cs" />
<Compile Include="Helpers.netcoreapp.cs" />
<Compile Include="System\ActivatorTests.netcoreapp.cs" />
<Compile Include="System\ArrayTests.netcoreapp.cs" />
@@ -143,16 +188,18 @@
<Compile Include="System\LazyTests.netcoreapp.cs" />
<Compile Include="System\StringTests.netcoreapp.cs" />
<Compile Include="System\TimeSpanTests.netcoreapp.cs" />
+ <Compile Include="System\TypeTests.netcoreapp.cs" />
+ <Compile Include="System\TypedReferenceTests.cs" />
+ <Compile Include="System\UIntPtrTests.netcoreapp.cs" />
+ <Compile Include="System\ComponentModel\DefaultValueAttributeTests.netcoreapp.cs" />
+ <Compile Include="System\Reflection\MethodBaseTests.netcoreapp.cs" />
<Compile Include="System\Reflection\MemberInfoTests.netcoreapp.cs" />
<Compile Include="System\Reflection\TypeDelegatorTests.netcoreapp.cs" />
<Compile Include="System\Reflection\TypeInfoTests.netcoreapp.cs" />
- <Compile Include="System\Runtime\CompilerServices\RuntimeHelpersTests.netcoreapp.cs" />
<Compile Include="System\Runtime\CompilerServices\ConditionalWeakTableTests.netcoreapp.cs" />
+ <Compile Include="System\Runtime\CompilerServices\RuntimeHelpersTests.netcoreapp.cs" />
<Compile Include="System\Runtime\ExceptionServices\ExceptionDispatchInfoTests.netcoreapp.cs" />
<Compile Include="System\Text\StringBuilderTests.netcoreapp.cs" />
- <Compile Include="System\UIntPtrTests.netcoreapp.cs" />
- <Compile Include="System\ComponentModel\DefaultValueAttributeTests.netcoreapp.cs" />
- <Compile Include="System\TypedReferenceTests.cs" />
</ItemGroup>
<ItemGroup Condition="'$(TargetGroup)' != 'netcoreapp'">
<Compile Include="System\StringSplitExtensions.cs" />
@@ -161,72 +208,15 @@
<Compile Include="$(CommonTestPath)\System\Collections\IEnumerable.Generic.Serialization.Tests.cs">
<Link>Common\System\Collections\IEnumerable.Generic.Serialization.Tests.cs</Link>
</Compile>
- <Compile Include="ArrayTests.cs" />
- <Compile Include="CompareToTests.cs" />
- <Compile Include="DBNullTests.cs" />
- <Compile Include="DecimalTests.cs" />
- <Compile Include="EnumTests.cs" />
- <Compile Include="GetTypeCodeTests.cs" />
- <Compile Include="System\AccessViolationExceptionTests.cs" />
- <Compile Include="System\BadImageFormatExceptionTests.cs" />
- <Compile Include="System\DuplicateWaitObjectExceptionTests.cs" />
- <Compile Include="System\ExternalExceptionTests.cs" />
- <Compile Include="System\ApplicationExceptionTests.cs" />
- <Compile Include="System\EntryPointNotFoundExceptionTests.cs" />
- <Compile Include="System\ExceptionTests.cs" />
- <Compile Include="System\ExecutionEngineExceptionTests.cs" />
- <Compile Include="System\MarshalByRefObjectTests.cs" />
- <Compile Include="System\MissingMemberExceptionTests.cs" />
- <Compile Include="System\NotFiniteNumberExceptionTests.cs" />
- <Compile Include="System\Security\SecurityAttributeTests.cs" />
- <Compile Include="System\StackOverflowExceptionTests.cs" />
- <Compile Include="System\SystemExceptionTests.cs" />
- <Compile Include="System\TypeUnloadedExceptionTests.cs" />
- <Compile Include="TimeZoneTests.cs" />
- <Compile Include="TimeZoneInfoTests.cs" />
- <Compile Include="TimeZoneNotFoundExceptionTests.cs" />
- <Compile Include="VersionTests.cs" />
- <Compile Include="System\Reflection\AssemblyTests.cs" />
- <Compile Include="System\Reflection\AssemblyNameTests.cs" />
- <Compile Include="System\Reflection\ConstructorInfoTests.cs" />
- <Compile Include="System\Reflection\CustomAttributeDataTests.cs" />
- <Compile Include="System\Reflection\CustomAttribute_Named_Typed_ArgumentTests.cs" />
- <Compile Include="System\Reflection\EventInfoTests.cs" />
- <Compile Include="System\Reflection\FieldInfoTests.cs" />
- <Compile Include="System\Reflection\MemberInfoTests.cs" />
- <Compile Include="System\Reflection\MethodBaseTests.cs" />
- <Compile Include="System\Reflection\MethodBodyTests.cs" />
- <Compile Include="System\Reflection\MethodInfoTests.cs" />
- <Compile Include="System\Reflection\ParameterInfoTests.cs" />
- <Compile Include="System\Reflection\PropertyInfoTests.cs" />
- <Compile Include="System\Reflection\TypeTests.Get.CornerCases.cs" />
- <Compile Include="System\Reflection\TypeTests.GetInterface.cs" />
- <Compile Include="System\Reflection\TypeTests.GetMember.cs" />
- <Compile Include="System\Reflection\CustomAttributesTestData.cs" />
<EmbeddedResource Include="System\Reflection\EmbeddedImage.png">
<LogicalName>System.Reflection.Tests.EmbeddedImage.png</LogicalName>
</EmbeddedResource>
<EmbeddedResource Include="System\Reflection\EmbeddedTextFile.txt">
<LogicalName>System.Reflection.Tests.EmbeddedTextFile.txt</LogicalName>
</EmbeddedResource>
- <Compile Include="Microsoft\Win32\SafeHandles\CriticalHandleZeroOrMinusOneIsInvalid.cs" />
- <Compile Include="Microsoft\Win32\SafeHandles\SafeHandleZeroOrMinusOneIsInvalid.cs" />
- <Compile Include="System\Reflection\ModuleTests.cs" />
- <Compile Include="System\Reflection\PointerTests.cs" />
- <Compile Include="System\Reflection\RuntimeReflectionExtensionsTests.cs" />
- <Compile Include="System\Reflection\TypeDelegatorTests.cs" />
- <Compile Include="System\Reflection\TypeInfoTests.cs" />
<Compile Include="$(CommonTestPath)\System\Runtime\Serialization\Formatters\BinaryFormatterHelpers.cs">
<Link>System\Runtime\Serialization\Formatters\BinaryFormatterHelpers.cs</Link>
</Compile>
- <Compile Include="System\Runtime\NgenServicingAttributesTests.cs" />
- <Compile Include="System\Runtime\ExceptionServices\HandleProcessCorruptedStateExceptions.cs" />
- <Compile Include="System\Attributes.cs" />
- <Compile Include="System\HandleTests.cs" />
- <Compile Include="System\AppContext\AppContext.Switch.cs" />
- <Compile Include="System\AppContext\AppContext.Switch.Validation.cs" />
- <Compile Include="System\Reflection\StrongNameKeyPairTests.cs" />
- <Compile Include="System\Runtime\Tests.netstandard.1.7.cs" />
<ProjectReference Include="$(CommonTestPath)\System\Diagnostics\RemoteExecutorConsoleApp\RemoteExecutorConsoleApp.csproj">
<Project>{69e46a6f-9966-45a5-8945-2559fe337827}</Project>
<Name>RemoteExecutorConsoleApp</Name>
@@ -244,5 +234,8 @@
<Reference Include="TestModule\System.Reflection.TestModule.dll">
</Reference>
</ItemGroup>
+ <ItemGroup>
+ <EmbeddedResource Include="Resources\$(AssemblyName).rd.xml" />
+ </ItemGroup>
<Import Project="$([MSBuild]::GetDirectoryNameOfFileAbove($(MSBuildThisFileDirectory), dir.targets))\dir.targets" />
</Project>
diff --git a/src/System.Runtime/tests/System/ArrayTests.cs b/src/System.Runtime/tests/System/ArrayTests.cs
index 57b1d38022..b22bcf41b5 100644
--- a/src/System.Runtime/tests/System/ArrayTests.cs
+++ b/src/System.Runtime/tests/System/ArrayTests.cs
@@ -4,6 +4,7 @@
using System.Collections;
using System.Collections.Generic;
+using System.Collections.ObjectModel;
using System.Linq;
using System.Reflection;
using Xunit;
@@ -104,6 +105,21 @@ namespace System.Tests
Assert.Equal(array.GetValue(0, 0, 0, 2), 3);
}
+ [Fact]
+ public void AsReadOnly_ValidArray_ReturnsExpected()
+ {
+ var array = new string[] { "a", "b" };
+ ReadOnlyCollection<string> readOnlyCollection = Array.AsReadOnly(array);
+ Assert.Equal(array, readOnlyCollection);
+ Assert.Equal(new ReadOnlyCollection<string>(array), readOnlyCollection);
+ }
+
+ [Fact]
+ public void AsReadOnly_NullArray_ThrowsArgumentNullException()
+ {
+ AssertExtensions.Throws<ArgumentNullException>("array", () => Array.AsReadOnly<int>(null));
+ }
+
public static IEnumerable<object[]> BinarySearch_SZArray_TestData()
{
string[] stringArray = new string[] { null, "aa", "bb", "bb", "cc", "dd", "ee" };
@@ -684,6 +700,40 @@ namespace System.Tests
Assert.Equal(0, clone[0, 0]);
}
+ [Fact]
+ public void ConvertAll()
+ {
+ int[] result = Array.ConvertAll(new int[] { }, new Converter<int, int>(i => { throw new InvalidOperationException(); }));
+ Assert.Equal(new int[] { }, result);
+
+ string[] result2 = Array.ConvertAll(new int[] { 1 }, new Converter<int, string>(i => (i + 1).ToString()));
+ Assert.Equal(new string[] { "2" }, result2);
+
+ result2 = Array.ConvertAll(new int[] { 1, 2 }, new Converter<int, string>(i => (i + 1).ToString()));
+ Assert.Equal(new string[] { "2", "3" }, result2);
+
+ result2 = Array.ConvertAll(new int[] { 1 }, new Converter<int, string>(i => null));
+ Assert.Equal(new string[] { null }, result2);
+ }
+
+ [Fact]
+ public void ConvertAll_NullArray_ThrowsArgumentNullException()
+ {
+ AssertExtensions.Throws<ArgumentNullException>("array", () => Array.ConvertAll<short, short>(null, i => i));
+ }
+
+ [Fact]
+ public void ConvertAll_NullConverter_ThrowsArgumentNullException()
+ {
+ AssertExtensions.Throws<ArgumentNullException>("converter", () => Array.ConvertAll<string, string>(new string[] { }, null));
+ }
+
+ [Fact]
+ public void ConvertAll_ConverterActionThrows_RethrowsException()
+ {
+ Assert.Throws<DivideByZeroException>(() => Array.ConvertAll<string, string>(new string[1], element => { throw new DivideByZeroException(); }));
+ }
+
public static IEnumerable<object[]> Copy_Array_Reliable_TestData()
{
if (s_NonZeroLowerBoundsAvailable)
@@ -979,10 +1029,16 @@ namespace System.Tests
if (sourceIndex == 0 && length == sourceArray.Length)
{
// CopyTo(Array, int)
- Array sourceClone = (Array)sourceArray.Clone();
- Array destinationArrayClone = sourceArray == destinationArray ? sourceClone : (Array)destinationArray.Clone();
- sourceClone.CopyTo(destinationArrayClone, destinationIndex);
- Assert.Equal(expected, destinationArrayClone);
+ Array sourceClone1 = (Array)sourceArray.Clone();
+ Array destinationArrayClone1 = sourceArray == destinationArray ? sourceClone1 : (Array)destinationArray.Clone();
+ sourceClone1.CopyTo(destinationArrayClone1, destinationIndex);
+ Assert.Equal(expected, destinationArrayClone1);
+
+ // CopyTo(Array, long)
+ Array sourceClone2 = (Array)sourceArray.Clone();
+ Array destinationArrayClone2 = sourceArray == destinationArray ? sourceClone2 : (Array)destinationArray.Clone();
+ sourceClone2.CopyTo(destinationArrayClone2, (long)destinationIndex);
+ Assert.Equal(expected, destinationArrayClone2);
}
}
@@ -999,12 +1055,24 @@ namespace System.Tests
Array destinationArrayClone1 = overlaps ? sourceArrayClone1 : (Array)destinationArray.Clone();
Array.Copy(sourceArrayClone1, destinationArrayClone1, length);
Assert.Equal(expected, destinationArrayClone1);
+
+ // Use Copy(Array, Array, long)
+ Array sourceArrayClone2 = (Array)sourceArray.Clone();
+ Array destinationArrayClone2 = overlaps ? sourceArrayClone1 : (Array)destinationArray.Clone();
+ Array.Copy(sourceArrayClone2, destinationArrayClone2, (long)length);
+ Assert.Equal(expected, destinationArrayClone2);
}
// Use Copy(Array, int, Array, int, int)
- Array sourceArrayClone2 = (Array)sourceArray.Clone();
- Array destinationArrayClone2 = overlaps ? sourceArrayClone2 : (Array)destinationArray.Clone();
- Array.Copy(sourceArrayClone2, sourceIndex, destinationArrayClone2, destinationIndex, length);
- Assert.Equal(expected, destinationArrayClone2);
+ Array sourceArrayClone3 = (Array)sourceArray.Clone();
+ Array destinationArrayClone3 = overlaps ? sourceArrayClone3 : (Array)destinationArray.Clone();
+ Array.Copy(sourceArrayClone3, sourceIndex, destinationArrayClone3, destinationIndex, length);
+ Assert.Equal(expected, destinationArrayClone3);
+
+ // Use Copy(Array, long, Array, long, long)
+ Array sourceArrayClone4 = (Array)sourceArray.Clone();
+ Array destinationArrayClone4 = overlaps ? sourceArrayClone4 : (Array)destinationArray.Clone();
+ Array.Copy(sourceArrayClone4, (long)sourceIndex, destinationArrayClone4, destinationIndex, length);
+ Assert.Equal(expected, destinationArrayClone4);
}
[Theory]
@@ -1022,8 +1090,11 @@ namespace System.Tests
public static void Copy_NullSourceArray_ThrowsArgumentNullException()
{
AssertExtensions.Throws<ArgumentNullException>("sourceArray", () => Array.Copy(null, new string[10], 0));
+ AssertExtensions.Throws<ArgumentNullException>("sourceArray", () => Array.Copy(null, new string[10], (long)0));
AssertExtensions.Throws<ArgumentNullException>("sourceArray", "source", () => Array.Copy(null, 0, new string[10], 0, 0));
+ AssertExtensions.Throws<ArgumentNullException>("sourceArray", "source", () => Array.Copy(null, (long)0, new string[10], 0, 0));
+
AssertExtensions.Throws<ArgumentNullException>("sourceArray", "source", () => Array.ConstrainedCopy(null, 0, new string[10], 0, 0));
}
@@ -1031,18 +1102,26 @@ namespace System.Tests
public static void Copy_NullDestinationArray_ThrowsArgumentNullException()
{
AssertExtensions.Throws<ArgumentNullException>("destinationArray", () => Array.Copy(new string[10], null, 0));
+ AssertExtensions.Throws<ArgumentNullException>("destinationArray", () => Array.Copy(new string[10], null, (long)0));
AssertExtensions.Throws<ArgumentNullException>("destinationArray", "dest", () => Array.Copy(new string[10], 0, null, 0, 0));
+ AssertExtensions.Throws<ArgumentNullException>("destinationArray", "dest", () => Array.Copy(new string[10], (long)0, null, 0, 0));
+
AssertExtensions.Throws<ArgumentNullException>("destinationArray", "dest", () => Array.ConstrainedCopy(new string[10], 0, null, 0, 0));
AssertExtensions.Throws<ArgumentNullException>("destinationArray", "dest", () => new string[10].CopyTo(null, 0));
+ AssertExtensions.Throws<ArgumentNullException>("destinationArray", "dest", () => new string[10].CopyTo(null, (long)0));
}
[Fact]
public static void Copy_SourceAndDestinationArrayHaveDifferentRanks_ThrowsRankException()
{
Assert.Throws<RankException>(() => Array.Copy(new string[10, 10], new string[10], 0));
+ Assert.Throws<RankException>(() => Array.Copy(new string[10, 10], new string[10], (long)0));
+
Assert.Throws<RankException>(() => Array.Copy(new string[10, 10], 0, new string[10], 0, 0));
+ Assert.Throws<RankException>(() => Array.Copy(new string[10, 10], (long)0, new string[10], 0, 0));
+
Assert.Throws<RankException>(() => Array.ConstrainedCopy(new string[10, 10], 0, new string[10], 0, 0));
}
@@ -1230,8 +1309,13 @@ namespace System.Tests
public static void Copy_SourceAndDestinationNeverConvertible_ThrowsArrayTypeMismatchException(Array sourceArray, Array destinationArray)
{
Assert.Throws<ArrayTypeMismatchException>(() => Array.Copy(sourceArray, destinationArray, 0));
+ Assert.Throws<ArrayTypeMismatchException>(() => Array.Copy(sourceArray, destinationArray, (long)0));
+
Assert.Throws<ArrayTypeMismatchException>(() => Array.Copy(sourceArray, sourceArray.GetLowerBound(0), destinationArray, destinationArray.GetLowerBound(0), 0));
+ Assert.Throws<ArrayTypeMismatchException>(() => Array.Copy(sourceArray, (long)sourceArray.GetLowerBound(0), destinationArray, destinationArray.GetLowerBound(0), 0));
+
Assert.Throws<ArrayTypeMismatchException>(() => sourceArray.CopyTo(destinationArray, destinationArray.GetLowerBound(0)));
+ Assert.Throws<ArrayTypeMismatchException>(() => sourceArray.CopyTo(destinationArray, (long)destinationArray.GetLowerBound(0)));
}
[Fact]
@@ -1274,9 +1358,13 @@ namespace System.Tests
{
int length = Math.Min(sourceArray.Length, destinationArray.Length);
Assert.Throws<InvalidCastException>(() => Array.Copy(sourceArray, destinationArray, length));
+ Assert.Throws<InvalidCastException>(() => Array.Copy(sourceArray, destinationArray, (long)length));
+
Assert.Throws<InvalidCastException>(() => Array.Copy(sourceArray, sourceArray.GetLowerBound(0), destinationArray, destinationArray.GetLowerBound(0), length));
+ Assert.Throws<InvalidCastException>(() => Array.Copy(sourceArray, (long)sourceArray.GetLowerBound(0), destinationArray, destinationArray.GetLowerBound(0), length));
Assert.Throws<InvalidCastException>(() => sourceArray.CopyTo(destinationArray, destinationArray.GetLowerBound(0)));
+ Assert.Throws<InvalidCastException>(() => sourceArray.CopyTo(destinationArray, (long)destinationArray.GetLowerBound(0)));
// No exception is thrown if length == 0, as conversion error checking occurs during, not before copying
Array.Copy(sourceArray, sourceArray.GetLowerBound(0), destinationArray, destinationArray.GetLowerBound(0), 0);
@@ -1303,11 +1391,24 @@ namespace System.Tests
public static void Copy_NegativeLength_ThrowsArgumentOutOfRangeException()
{
AssertExtensions.Throws<ArgumentOutOfRangeException>("length", () => Array.Copy(new string[10], new string[10], -1));
+ AssertExtensions.Throws<ArgumentOutOfRangeException>("length", () => Array.Copy(new string[10], new string[10], (long)-1));
+
AssertExtensions.Throws<ArgumentOutOfRangeException>("length", () => Array.Copy(new string[10], 0, new string[10], 0, -1));
+ AssertExtensions.Throws<ArgumentOutOfRangeException>("length", () => Array.Copy(new string[10], 0, new string[10], 0, (long)-1));
+
AssertExtensions.Throws<ArgumentOutOfRangeException>("length", () => Array.ConstrainedCopy(new string[10], 0, new string[10], 0, -1));
}
[Theory]
+ [InlineData((long)int.MinValue - 1)]
+ [InlineData((long)int.MaxValue + 1)]
+ public void Copy_LongLengthNotValidInt_ThrowsArgumentOutOfRangeException(long length)
+ {
+ AssertExtensions.Throws<ArgumentOutOfRangeException>("length", () => Array.Copy(new string[10], new string[10], length));
+ AssertExtensions.Throws<ArgumentOutOfRangeException>("length", () => Array.Copy(new string[10], 0, new string[10], 0, length));
+ }
+
+ [Theory]
[InlineData(8, 0, 10, 0, 9)]
[InlineData(8, 8, 10, 0, 1)]
[InlineData(8, 9, 10, 0, 0)]
@@ -1316,8 +1417,12 @@ namespace System.Tests
if (sourceIndex == 0 && destinationIndex == 0)
{
AssertExtensions.Throws<ArgumentException>("sourceArray", "", () => Array.Copy(new string[sourceCount], new string[destinationCount], count));
+ AssertExtensions.Throws<ArgumentException>("sourceArray", "", () => Array.Copy(new string[sourceCount], new string[destinationCount], (long)count));
}
+
AssertExtensions.Throws<ArgumentException>("sourceArray", "", () => Array.Copy(new string[sourceCount], sourceIndex, new string[destinationCount], destinationIndex, count));
+ AssertExtensions.Throws<ArgumentException>("sourceArray", "", () => Array.Copy(new string[sourceCount], (long)sourceIndex, new string[destinationCount], destinationIndex, count));
+
AssertExtensions.Throws<ArgumentException>("sourceArray", "", () => Array.ConstrainedCopy(new string[sourceCount], sourceIndex, new string[destinationCount], destinationIndex, count));
}
@@ -1330,8 +1435,12 @@ namespace System.Tests
if (sourceIndex == 0 && destinationIndex == 0)
{
AssertExtensions.Throws<ArgumentException>("destinationArray", "", () => Array.Copy(new string[sourceCount], new string[destinationCount], count));
+ AssertExtensions.Throws<ArgumentException>("destinationArray", "", () => Array.Copy(new string[sourceCount], new string[destinationCount], (long)count));
}
+
AssertExtensions.Throws<ArgumentException>("destinationArray", "", () => Array.Copy(new string[sourceCount], sourceIndex, new string[destinationCount], destinationIndex, count));
+ AssertExtensions.Throws<ArgumentException>("destinationArray", "", () => Array.Copy(new string[sourceCount], (long)sourceIndex, new string[destinationCount], destinationIndex, count));
+
AssertExtensions.Throws<ArgumentException>("destinationArray", "", () => Array.ConstrainedCopy(new string[sourceCount], sourceIndex, new string[destinationCount], destinationIndex, count));
}
@@ -1339,34 +1448,58 @@ namespace System.Tests
public static void Copy_StartIndexNegative_ThrowsArgumentOutOfRangeException()
{
AssertExtensions.Throws<ArgumentOutOfRangeException>("sourceIndex", "srcIndex", () => Array.Copy(new string[10], -1, new string[10], 0, 0));
+ AssertExtensions.Throws<ArgumentOutOfRangeException>("sourceIndex", "srcIndex", () => Array.Copy(new string[10], (long)-1, new string[10], 0, 0));
+
AssertExtensions.Throws<ArgumentOutOfRangeException>("sourceIndex", "srcIndex", () => Array.ConstrainedCopy(new string[10], -1, new string[10], 0, 0));
}
+ [Theory]
+ [InlineData((long)int.MinValue - 1)]
+ [InlineData((long)int.MaxValue + 1)]
+ public void Copy_LongSourceIndexNotValidInt_ThrowsArgumentException(long sourceIndex)
+ {
+ AssertExtensions.Throws<ArgumentOutOfRangeException>("sourceIndex", () => Array.Copy(new string[10], sourceIndex, new string[10], 0, 0));
+ }
+
[Fact]
public static void Copy_DestinationIndexNegative_ThrowsArgumentOutOfRangeException()
{
AssertExtensions.Throws<ArgumentOutOfRangeException>("destinationIndex", "dstIndex", () => Array.Copy(new string[10], 0, new string[10], -1, 0));
+ AssertExtensions.Throws<ArgumentOutOfRangeException>("destinationIndex", "dstIndex", () => Array.Copy(new string[10], 0, new string[10], (long)-1, 0));
+
AssertExtensions.Throws<ArgumentOutOfRangeException>("destinationIndex", "dstIndex", () => Array.ConstrainedCopy(new string[10], 0, new string[10], -1, 0));
+
AssertExtensions.Throws<ArgumentOutOfRangeException>("destinationIndex", "dstIndex", () => new string[10].CopyTo(new string[10], -1));
}
+ [Theory]
+ [InlineData((long)int.MinValue - 1)]
+ [InlineData((long)int.MaxValue + 1)]
+ public void Copy_LongDestinationIndexNotValidInt_ThrowsArgumentOutOfRangeException(long destinationIndex)
+ {
+ AssertExtensions.Throws<ArgumentOutOfRangeException>("destinationIndex", () => Array.Copy(new string[10], 0, new string[10], destinationIndex, 0));
+ AssertExtensions.Throws<ArgumentOutOfRangeException>("index", () => new string[10].CopyTo(new string[10], destinationIndex));
+ }
+
[Fact]
public static void CopyTo_SourceMultiDimensional_ThrowsRankException()
{
Assert.Throws<RankException>(() => new int[3, 3].CopyTo(new int[3], 0));
+ Assert.Throws<RankException>(() => new int[3, 3].CopyTo(new int[3], (long)0));
}
[Fact]
public static void CopyTo_DestinationMultiDimensional_ThrowsArgumentException()
{
AssertExtensions.Throws<ArgumentException>(null, () => new int[3].CopyTo(new int[10, 10], 0));
+ AssertExtensions.Throws<ArgumentException>(null, () => new int[3].CopyTo(new int[10, 10], (long)0));
}
[Fact]
- public static void CopyTo_IndexInvalid_ThrowsArgumentException()
+ public static void CopyTo_IndexGreaterThanDestinationArrayLength_ThrowsArgumentException()
{
- // Index > destination.Length
AssertExtensions.Throws<ArgumentException>("destinationArray", "", () => new int[3].CopyTo(new int[10], 10));
+ AssertExtensions.Throws<ArgumentException>("destinationArray", "", () => new int[3].CopyTo(new int[10], (long)10));
}
public static unsafe IEnumerable<object[]> CreateInstance_TestData()
@@ -1409,7 +1542,6 @@ namespace System.Tests
[Theory]
[MemberData(nameof(CreateInstance_TestData))]
- [ActiveIssue("https://github.com/dotnet/corefx/issues/18584", TargetFrameworkMonikers.UapAot)]
public static void CreateInstance(Type elementType, object repeatedValue)
{
CreateInstance(elementType, new int[] { 10 }, new int[1], repeatedValue);
@@ -1419,14 +1551,20 @@ namespace System.Tests
}
[Theory]
+ [InlineData(typeof(int), new int[] { 1 }, new int[] { 0 }, default(int))]
[InlineData(typeof(int), new int[] { 1, 2 }, new int[] { 0, 0 }, default(int))]
[InlineData(typeof(int), new int[] { 1, 2, 3 }, new int[] { 0, 0, 0 }, default(int))]
[InlineData(typeof(int), new int[] { 1, 2, 3, 4 }, new int[] { 0, 0, 0, 0 }, default(int))]
+ [InlineData(typeof(int), new int[] { 1, 2, 3, 4 }, new int[] { -2, 3, -4, -5 }, default(int))]
+ [InlineData(typeof(int), new int[] { 7 }, new int[] { 1 }, default(int))]
+ [InlineData(typeof(int), new int[] { 7, 8 }, new int[] { 1, 2 }, default(int))]
[InlineData(typeof(int), new int[] { 7, 8, 9 }, new int[] { 1, 2, 3 }, default(int))]
- [ActiveIssue("https://github.com/dotnet/corefx/issues/18584", TargetFrameworkMonikers.UapAot)]
public static void CreateInstance(Type elementType, int[] lengths, int[] lowerBounds, object repeatedValue)
{
- if (lowerBounds.All(lowerBound => lowerBound == 0))
+ bool lowerBoundsAreAllZero = lowerBounds.All(lowerBound => lowerBound == 0);
+ if ((!lowerBoundsAreAllZero) && !PlatformDetection.IsNonZeroLowerBoundArraySupported)
+ return;
+ if (lowerBoundsAreAllZero)
{
if (lengths.Length == 1)
{
@@ -1434,21 +1572,41 @@ namespace System.Tests
Array array1 = Array.CreateInstance(elementType, lengths[0]);
VerifyArray(array1, elementType, lengths, lowerBounds, repeatedValue);
}
+ else if (lengths.Length == 2)
+ {
+ // Use CreateInstance(Type, int, int)
+ Array array2 = Array.CreateInstance(elementType, lengths[0], lengths[1]);
+ VerifyArray(array2, elementType, lengths, lowerBounds, repeatedValue);
+ }
+ else if (lengths.Length == 3)
+ {
+ // Use CreateInstance(Type, int, int, int)
+ Array array3 = Array.CreateInstance(elementType, lengths[0], lengths[1], lengths[2]);
+ VerifyArray(array3, elementType, lengths, lowerBounds, repeatedValue);
+ }
+
// Use CreateInstance(Type, int[])
- Array array2 = Array.CreateInstance(elementType, lengths);
- VerifyArray(array2, elementType, lengths, lowerBounds, repeatedValue);
+ Array array4 = Array.CreateInstance(elementType, lengths);
+ VerifyArray(array4, elementType, lengths, lowerBounds, repeatedValue);
+
+ // Use CreateInstance(Type, long[])
+ Array array5 = Array.CreateInstance(elementType, lengths.Select(length => (long)length).ToArray());
+ VerifyArray(array5, elementType, lengths, lowerBounds, repeatedValue);
+
}
// Use CreateInstance(Type, int[], int[])
- Array array3 = Array.CreateInstance(elementType, lengths, lowerBounds);
- VerifyArray(array3, elementType, lengths, lowerBounds, repeatedValue);
+ Array array6 = Array.CreateInstance(elementType, lengths, lowerBounds);
+ VerifyArray(array6, elementType, lengths, lowerBounds, repeatedValue);
}
[Fact]
- [ActiveIssue("https://github.com/dotnet/corefx/issues/18584", TargetFrameworkMonikers.UapAot)]
public static void CreateInstance_NullElementType_ThrowsArgumentNullException()
{
AssertExtensions.Throws<ArgumentNullException>("elementType", () => Array.CreateInstance(null, 0));
+ AssertExtensions.Throws<ArgumentNullException>("elementType", () => Array.CreateInstance(null, 0, 0));
+ AssertExtensions.Throws<ArgumentNullException>("elementType", () => Array.CreateInstance(null, 0, 0, 0));
AssertExtensions.Throws<ArgumentNullException>("elementType", () => Array.CreateInstance(null, new int[1]));
+ AssertExtensions.Throws<ArgumentNullException>("elementType", () => Array.CreateInstance(null, new long[1]));
AssertExtensions.Throws<ArgumentNullException>("elementType", () => Array.CreateInstance(null, new int[1], new int[1]));
}
@@ -1463,57 +1621,80 @@ namespace System.Tests
[Theory]
[MemberData(nameof(CreateInstance_NotSupportedType_TestData))]
- [ActiveIssue("https://github.com/dotnet/corefx/issues/18584", TargetFrameworkMonikers.UapAot)]
- public static void CreateInstance_NotSupportedType_ThrowsNotSupportedException(Type elementType)
+ public void CreateInstance_NotSupportedType_ThrowsNotSupportedException(Type elementType)
{
Assert.Throws<NotSupportedException>(() => Array.CreateInstance(elementType, 0));
+ Assert.Throws<NotSupportedException>(() => Array.CreateInstance(elementType, 0, 0));
+ Assert.Throws<NotSupportedException>(() => Array.CreateInstance(elementType, 0, 0, 0));
Assert.Throws<NotSupportedException>(() => Array.CreateInstance(elementType, new int[1]));
+ Assert.Throws<NotSupportedException>(() => Array.CreateInstance(elementType, new long[1]));
Assert.Throws<NotSupportedException>(() => Array.CreateInstance(elementType, new int[1], new int[1]));
}
[Fact]
- [ActiveIssue("https://github.com/dotnet/corefx/issues/18584", TargetFrameworkMonikers.UapAot)]
- public static void CreateInstance_NegativeLength_ThrowsArgumentOutOfRangeException()
+ public void CreateInstance_NegativeLength_ThrowsArgumentOutOfRangeException()
{
AssertExtensions.Throws<ArgumentOutOfRangeException>("length", () => Array.CreateInstance(typeof(int), -1));
+ AssertExtensions.Throws<ArgumentOutOfRangeException>("length1", () => Array.CreateInstance(typeof(int), -1, 0));
+ AssertExtensions.Throws<ArgumentOutOfRangeException>("length1", () => Array.CreateInstance(typeof(int), -1, 0, 0));
AssertExtensions.Throws<ArgumentOutOfRangeException>("lengths[0]", () => Array.CreateInstance(typeof(int), new int[] { -1 }));
+ AssertExtensions.Throws<ArgumentOutOfRangeException>("lengths[0]", () => Array.CreateInstance(typeof(int), new long[] { -1 }));
AssertExtensions.Throws<ArgumentOutOfRangeException>("lengths[0]", () => Array.CreateInstance(typeof(int), new int[] { -1 }, new int[1]));
}
[Fact]
- [ActiveIssue("https://github.com/dotnet/corefx/issues/18584", TargetFrameworkMonikers.UapAot)]
- public static void CreateInstance_LengthsNull_ThrowsArgumentNullException()
+ public void CreateInstance_NegativeLength2_ThrowsArgumentOutOfRangeException()
+ {
+ AssertExtensions.Throws<ArgumentOutOfRangeException>("length2", () => Array.CreateInstance(typeof(int), 0, -1));
+ AssertExtensions.Throws<ArgumentOutOfRangeException>("length2", () => Array.CreateInstance(typeof(int), 0, -1, 0));
+ }
+
+ [Fact]
+ public void CreateInstance_NegativeLength3_ThrowsArgumentOutOfRangeException()
{
+ AssertExtensions.Throws<ArgumentOutOfRangeException>("length3", () => Array.CreateInstance(typeof(int), 0, 0, -1));
+ }
+
+ [Fact]
+ public void CreateInstance_LengthsNull_ThrowsArgumentNullException()
+ {
+ AssertExtensions.Throws<ArgumentNullException>("lengths", () => Array.CreateInstance(typeof(int), (int[])null));
+ AssertExtensions.Throws<ArgumentNullException>("lengths", () => Array.CreateInstance(typeof(int), (long[])null));
AssertExtensions.Throws<ArgumentNullException>("lengths", () => Array.CreateInstance(typeof(int), null, new int[1]));
}
[Fact]
- [ActiveIssue("https://github.com/dotnet/corefx/issues/18584", TargetFrameworkMonikers.UapAot)]
- public static void CreateInstance_LengthsEmpty_ThrowsArgumentException()
+ public void CreateInstance_LengthsEmpty_ThrowsArgumentException()
{
AssertExtensions.Throws<ArgumentException>(null, () => Array.CreateInstance(typeof(int), new int[0]));
+ AssertExtensions.Throws<ArgumentException>(null, () => Array.CreateInstance(typeof(int), new long[0]));
AssertExtensions.Throws<ArgumentException>(null, () => Array.CreateInstance(typeof(int), new int[0], new int[1]));
}
[Fact]
- [ActiveIssue("https://github.com/dotnet/corefx/issues/18584", TargetFrameworkMonikers.UapAot)]
- public static void CreateInstance_LowerBoundNull_ThrowsArgumentNullException()
+ public void CreateInstance_LowerBoundNull_ThrowsArgumentNullException()
{
AssertExtensions.Throws<ArgumentNullException>("lowerBounds", () => Array.CreateInstance(typeof(int), new int[] { 1 }, null));
}
[Theory]
+ [InlineData((long)int.MaxValue + 1)]
+ [InlineData((long)int.MinValue - 1)]
+ public void CreateInstance_InvalidLengthInLongLength_ThrowsArgumentOutOfRangeException(long length)
+ {
+ AssertExtensions.Throws<ArgumentOutOfRangeException>("len", () => Array.CreateInstance(typeof(int), new long[] { length }));
+ }
+
+ [Theory]
[InlineData(0)]
[InlineData(2)]
- [ActiveIssue("https://github.com/dotnet/corefx/issues/18584", TargetFrameworkMonikers.UapAot)]
- public static void CreateInstance_LengthsAndLowerBoundsHaveDifferentLengths_ThrowsArgumentException(int length)
+ public void CreateInstance_LengthsAndLowerBoundsHaveDifferentLengths_ThrowsArgumentException(int length)
{
AssertExtensions.Throws<ArgumentException>(null, () => Array.CreateInstance(typeof(int), new int[1], new int[length]));
}
- [Fact]
- [ActiveIssue("https://github.com/dotnet/corefx/issues/18584", TargetFrameworkMonikers.UapAot)]
- public static void CreateInstance_Type_LengthsPlusLowerBoundOverflows_ThrowsArgumentOutOfRangeException()
+ [ConditionalFact(nameof(PlatformDetection) + "." + nameof(PlatformDetection.IsNonZeroLowerBoundArraySupported))]
+ public void CreateInstance_Type_LengthsPlusLowerBoundOverflows_ThrowsArgumentOutOfRangeException()
{
AssertExtensions.Throws<ArgumentOutOfRangeException>(null, () => Array.CreateInstance(typeof(int), new int[] { int.MaxValue }, new int[] { 2 }));
}
@@ -1662,6 +1843,35 @@ namespace System.Tests
AssertExtensions.Throws<ArgumentOutOfRangeException>("startIndex", () => Array.FindLastIndex(new int[3], 3, 1, i => i == 43));
}
+ [Theory]
+ [InlineData(new int[0])]
+ [InlineData(new int[] { 1, 2, 3 })]
+ public void ForEach_Array_EvaluatesActionForEachElement(int[] array)
+ {
+ var elements = new List<int>();
+ Array.ForEach((int[])array.Clone(), element => elements.Add(element));
+ Assert.Equal(array, elements);
+ Assert.Equal(array, array);
+ }
+
+ [Fact]
+ public void ForEach_NullArray_ThrowsArgumentNullException()
+ {
+ AssertExtensions.Throws<ArgumentNullException>("array", () => Array.ForEach<int>(null, element => { }));
+ }
+
+ [Fact]
+ public void ForEach_NullAction_ThrowsArgumentNullException()
+ {
+ AssertExtensions.Throws<ArgumentNullException>("action", () => Array.ForEach(new int[1], null));
+ }
+
+ [Fact]
+ public void ForEach_ActionThrows_RethrowsException()
+ {
+ Assert.Throws<DivideByZeroException>(() => Array.ForEach(new int[1], element => { throw new DivideByZeroException(); }));
+ }
+
public static IEnumerable<object[]> GetEnumerator_TestData()
{
yield return new object[] { new int[0] };
@@ -3434,8 +3644,9 @@ namespace System.Tests
for (int dimension = 0; dimension < array.Rank; dimension++)
{
Assert.Equal(lengths[dimension], array.GetLength(dimension));
- Assert.Equal(lowerBounds[dimension], array.GetLowerBound(dimension));
+ Assert.Equal(lengths[dimension], array.GetLongLength(dimension));
+ Assert.Equal(lowerBounds[dimension], array.GetLowerBound(dimension));
Assert.Equal(lowerBounds[dimension] + lengths[dimension] - 1, array.GetUpperBound(dimension));
}
@@ -3452,6 +3663,12 @@ namespace System.Tests
{
VerifyArrayAsIList(array);
}
+
+ Assert.Same(array, array.SyncRoot);
+
+ Assert.False(array.IsSynchronized);
+ Assert.True(array.IsFixedSize);
+ Assert.False(array.IsReadOnly);
}
private static void VerifyArrayAsIList(Array array)
diff --git a/src/System.Runtime/tests/System/ArrayTests.netcoreapp.cs b/src/System.Runtime/tests/System/ArrayTests.netcoreapp.cs
index 8368ff432f..6f2bbd7217 100644
--- a/src/System.Runtime/tests/System/ArrayTests.netcoreapp.cs
+++ b/src/System.Runtime/tests/System/ArrayTests.netcoreapp.cs
@@ -141,14 +141,17 @@ namespace System.Tests
}
[Fact]
- [ActiveIssue("https://github.com/dotnet/corert/issues/3650 - Wrong exception thrown", TargetFrameworkMonikers.UapAot)]
- public static void CreateInstance_TypeNotRuntimeType_ThrowsArgumentException()
+ public void CreateInstance_TypeNotRuntimeType_ThrowsArgumentException()
{
- foreach (Type nonRuntimeType in Helpers.NonRuntimeTypes)
+ // This cannot be a [Theory] due to https://github.com/xunit/xunit/issues/1325.
+ foreach (Type elementType in Helpers.NonRuntimeTypes)
{
- AssertExtensions.Throws<ArgumentException>("elementType", () => Array.CreateInstance(nonRuntimeType, 0));
- AssertExtensions.Throws<ArgumentException>("elementType", () => Array.CreateInstance(nonRuntimeType, new int[1]));
- AssertExtensions.Throws<ArgumentException>("elementType", () => Array.CreateInstance(nonRuntimeType, new int[1], new int[1]));
+ AssertExtensions.Throws<ArgumentException>("elementType", () => Array.CreateInstance(elementType, 1));
+ AssertExtensions.Throws<ArgumentException>("elementType", () => Array.CreateInstance(elementType, 1, 1));
+ AssertExtensions.Throws<ArgumentException>("elementType", () => Array.CreateInstance(elementType, 1, 1, 1));
+ AssertExtensions.Throws<ArgumentException>("elementType", () => Array.CreateInstance(elementType, new int[1]));
+ AssertExtensions.Throws<ArgumentException>("elementType", () => Array.CreateInstance(elementType, new long[1]));
+ AssertExtensions.Throws<ArgumentException>("elementType", () => Array.CreateInstance(elementType, new int[1], new int[1]));
}
}
}
diff --git a/src/System.Runtime/tests/System/BooleanTests.cs b/src/System.Runtime/tests/System/BooleanTests.cs
index 706acf1801..d4d02c9055 100644
--- a/src/System.Runtime/tests/System/BooleanTests.cs
+++ b/src/System.Runtime/tests/System/BooleanTests.cs
@@ -2,21 +2,20 @@
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
-using System;
using Xunit;
namespace System.Tests
{
- public static class BooleanTests
+ public class BooleanTests
{
[Fact]
- public static void TrueString()
+ public void TrueString_Get_ReturnsTrue()
{
Assert.Equal("True", bool.TrueString);
}
[Fact]
- public static void FalseString()
+ public void FalseString_Get_ReturnsFalse()
{
Assert.Equal("False", bool.FalseString);
}
@@ -36,10 +35,9 @@ namespace System.Tests
[InlineData("False ", false)]
[InlineData("False\0", false)]
[InlineData(" False \0\0\0 ", false)]
- public static void Parse(string value, bool expected)
+ public void Parse_ValidValue_ReturnsExpected(string value, bool expected)
{
- bool result;
- Assert.True(bool.TryParse(value, out result));
+ Assert.True(bool.TryParse(value, out bool result));
Assert.Equal(expected, result);
Assert.Equal(expected, bool.Parse(value));
@@ -59,20 +57,20 @@ namespace System.Tests
[InlineData("T", typeof(FormatException))]
[InlineData("0", typeof(FormatException))]
[InlineData("1", typeof(FormatException))]
- public static void Parse_Invalid(string value, Type exceptionType)
+ public void Parse_InvalidValue_ThrowsException(string value, Type exceptionType)
{
Assert.Throws(exceptionType, () => bool.Parse(value));
- bool result;
- Assert.False(bool.TryParse(value, out result));
+ Assert.False(bool.TryParse(value, out bool result));
Assert.False(result);
}
- [Fact]
- public static void ToStringTest()
+ [Theory]
+ [InlineData(true, "True")]
+ [InlineData(false, "False")]
+ public void ToString_Invoke_ReturnsExpected(bool value, string expected)
{
- Assert.Equal(bool.TrueString, true.ToString());
- Assert.Equal(bool.FalseString, false.ToString());
+ Assert.Equal(expected, value.ToString());
}
[Theory]
@@ -82,15 +80,14 @@ namespace System.Tests
[InlineData(false, false, 0)]
[InlineData(false, true, -1)]
[InlineData(false, null, 1)]
- public static void CompareTo(bool b, object obj, int expected)
+ public void CompareTo_Other_ReturnsExpected(bool b, object obj, int expected)
{
- if (obj is bool)
+ if (obj is bool boolValue)
{
- Assert.Equal(expected, Math.Sign(b.CompareTo((bool)obj)));
+ Assert.Equal(expected, Math.Sign(b.CompareTo(boolValue)));
}
- IComparable comparable = b;
- Assert.Equal(expected, Math.Sign(comparable.CompareTo(obj)));
+ Assert.Equal(expected, Math.Sign(b.CompareTo(obj)));
}
[Theory]
@@ -98,7 +95,7 @@ namespace System.Tests
[InlineData(true, "true")]
[InlineData(false, 0)]
[InlineData(false, "false")]
- private static void CompareTo_ObjectNotBool_ThrowsArgumentException(IComparable b, object obj)
+ private void CompareTo_ObjectNotBool_ThrowsArgumentException(bool b, object obj)
{
AssertExtensions.Throws<ArgumentException>(null, () => b.CompareTo(obj));
}
@@ -114,21 +111,29 @@ namespace System.Tests
[InlineData(false, "0", false)]
[InlineData(false, "False", false)]
[InlineData(false, null, false)]
- public static void Equals(bool b1, object obj, bool expected)
+ public void Equals_Other_ReturnsExpected(bool b1, object obj, bool expected)
{
- if (obj is bool)
+ if (obj is bool boolValue)
{
- Assert.Equal(expected, b1.Equals((bool)obj));
+ Assert.Equal(expected, b1.Equals(boolValue));
Assert.Equal(expected, b1.GetHashCode().Equals(obj.GetHashCode()));
}
+
Assert.Equal(expected, b1.Equals(obj));
}
+ [Theory]
+ [InlineData(true, 1)]
+ [InlineData(false, 0)]
+ public void GetHashCode_Invoke_ReturnsExpected(bool value, int expected)
+ {
+ Assert.Equal(expected, value.GetHashCode());
+ }
+
[Fact]
- public static void GetHashCodeTest()
+ public void GetTypeCode_Invoke_ReturnsBoolean()
{
- Assert.Equal(1, true.GetHashCode());
- Assert.Equal(0, false.GetHashCode());
+ Assert.Equal(TypeCode.Boolean, true.GetTypeCode());
}
}
}
diff --git a/src/System.Runtime/tests/System/ByteTests.cs b/src/System.Runtime/tests/System/ByteTests.cs
index 3bfc218d26..0068338b80 100644
--- a/src/System.Runtime/tests/System/ByteTests.cs
+++ b/src/System.Runtime/tests/System/ByteTests.cs
@@ -2,14 +2,13 @@
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
-using System;
using System.Collections.Generic;
using System.Globalization;
using Xunit;
namespace System.Tests
{
- public static class ByteTests
+ public class ByteTests
{
[Fact]
public static void Ctor_Empty()
@@ -45,22 +44,22 @@ namespace System.Tests
[InlineData((byte)234, (byte)235, -1)]
[InlineData((byte)234, byte.MaxValue, -1)]
[InlineData((byte)234, null, 1)]
- public static void CompareTo(byte b, object value, int expected)
+ public void CompareTo_Other_ReturnsExpected(byte i, object value, int expected)
{
- if (value is byte)
+ if (value is byte byteValue)
{
- Assert.Equal(expected, Math.Sign(b.CompareTo((byte)value)));
+ Assert.Equal(expected, Math.Sign(i.CompareTo(byteValue)));
}
- IComparable comparable = b;
- Assert.Equal(expected, Math.Sign(comparable.CompareTo(value)));
+
+ Assert.Equal(expected, Math.Sign(i.CompareTo(value)));
}
- [Fact]
- public static void CompareTo_ObjectNotByte_ThrowsArgumentException()
+ [Theory]
+ [InlineData("a")]
+ [InlineData(234)]
+ public void CompareTo_ObjectNotByte_ThrowsArgumentException(object value)
{
- IComparable comparable = (byte)234;
- AssertExtensions.Throws<ArgumentException>(null, () => comparable.CompareTo("a")); // Obj is not a byte
- AssertExtensions.Throws<ArgumentException>(null, () => comparable.CompareTo(234)); // Obj is not a byte
+ AssertExtensions.Throws<ArgumentException>(null, () => ((byte)123).CompareTo(value));
}
[Theory]
@@ -72,9 +71,8 @@ namespace System.Tests
[InlineData((byte)78, 78, false)]
public static void Equals(byte b, object obj, bool expected)
{
- if (obj is byte)
+ if (obj is byte b2)
{
- byte b2 = (byte)obj;
Assert.Equal(expected, b.Equals(b2));
Assert.Equal(expected, b.GetHashCode().Equals(b2.GetHashCode()));
Assert.Equal(b, b.GetHashCode());
@@ -82,6 +80,12 @@ namespace System.Tests
Assert.Equal(expected, b.Equals(obj));
}
+ [Fact]
+ public void GetTypeCode_Invoke_ReturnsByte()
+ {
+ Assert.Equal(TypeCode.Byte, ((byte)1).GetTypeCode());
+ }
+
public static IEnumerable<object[]> ToString_TestData()
{
NumberFormatInfo emptyFormat = NumberFormatInfo.CurrentInfo;
diff --git a/src/System.Runtime/tests/System/CharTests.cs b/src/System.Runtime/tests/System/CharTests.cs
index 153907ca69..99e226ffb6 100644
--- a/src/System.Runtime/tests/System/CharTests.cs
+++ b/src/System.Runtime/tests/System/CharTests.cs
@@ -9,28 +9,29 @@ using Xunit;
namespace System.Tests
{
- public static class CharTests
+ public class CharTests
{
[Theory]
[InlineData('h', 'h', 0)]
[InlineData('h', 'a', 1)]
[InlineData('h', 'z', -1)]
[InlineData('h', null, 1)]
- public static void CompareTo(char c, object value, int expected)
+ public void CompareTo_Other_ReturnsExpected(char c, object value, int expected)
{
- if (value is char)
+ if (value is char charValue)
{
- Assert.Equal(expected, Math.Sign(c.CompareTo((char)value)));
+ Assert.Equal(expected, Math.Sign(c.CompareTo(charValue)));
}
- IComparable comparable = c;
- Assert.Equal(expected, Math.Sign(comparable.CompareTo(value)));
+
+ Assert.Equal(expected, Math.Sign(c.CompareTo(value)));
}
- [Fact]
- public static void CompareTo_ObjectNotChar_ThrowsArgumentException()
+ [Theory]
+ [InlineData("a")]
+ [InlineData(234)]
+ public void CompareTo_ObjectNotDouble_ThrowsArgumentException(object value)
{
- IComparable comparable = 'h';
- AssertExtensions.Throws<ArgumentException>(null, () => comparable.CompareTo("H")); // Value not a char
+ AssertExtensions.Throws<ArgumentException>(null, () => ((char)123).CompareTo(value));
}
public static IEnumerable<object[]> ConvertFromUtf32_TestData()
@@ -194,6 +195,12 @@ namespace System.Tests
}
[Fact]
+ public void GetTypeCode_Invoke_ReturnsBoolean()
+ {
+ Assert.Equal(TypeCode.Char, 'a'.GetTypeCode());
+ }
+
+ [Fact]
public static void IsControl_Char()
{
foreach (char c in GetTestChars(UnicodeCategory.Control))
diff --git a/src/System.Runtime/tests/System/DBNullTests.cs b/src/System.Runtime/tests/System/DBNullTests.cs
new file mode 100644
index 0000000000..ae7c07318b
--- /dev/null
+++ b/src/System.Runtime/tests/System/DBNullTests.cs
@@ -0,0 +1,148 @@
+// Licensed to the .NET Foundation under one or more agreements.
+// The .NET Foundation licenses this file to you under the MIT license.
+// See the LICENSE file in the project root for more information.
+
+using System.Collections.Generic;
+using Xunit;
+
+namespace System.Tests
+{
+ public class DBNullTests
+ {
+ [Fact]
+ public void ToString_Invoke_ReturnsEmptyString()
+ {
+ Assert.Equal(string.Empty, DBNull.Value.ToString());
+ }
+
+ [Fact]
+ public void ToBoolean_Invoke_ThrowsInvalidCastException()
+ {
+ Assert.Throws<InvalidCastException>(() => ((IConvertible)DBNull.Value).ToBoolean(null));
+ }
+
+ [Fact]
+ public void ToChar_Invoke_ThrowsInvalidCastException()
+ {
+ Assert.Throws<InvalidCastException>(() => ((IConvertible)DBNull.Value).ToChar(null));
+ }
+
+ [Fact]
+ public void ToSByte_Invoke_ThrowsInvalidCastException()
+ {
+ Assert.Throws<InvalidCastException>(() => ((IConvertible)DBNull.Value).ToSByte(null));
+ }
+
+ [Fact]
+ public void ToByte_Invoke_ThrowsInvalidCastException()
+ {
+ Assert.Throws<InvalidCastException>(() => ((IConvertible)DBNull.Value).ToByte(null));
+ }
+
+ [Fact]
+ public void ToInt16_Invoke_ThrowsInvalidCastException()
+ {
+ Assert.Throws<InvalidCastException>(() => ((IConvertible)DBNull.Value).ToInt16(null));
+ }
+
+ [Fact]
+ public void ToUInt16_Invoke_ThrowsInvalidCastException()
+ {
+ Assert.Throws<InvalidCastException>(() => ((IConvertible)DBNull.Value).ToUInt16(null));
+ }
+
+ [Fact]
+ public void ToInt32_Invoke_ThrowsInvalidCastException()
+ {
+ Assert.Throws<InvalidCastException>(() => ((IConvertible)DBNull.Value).ToInt32(null));
+ }
+
+ [Fact]
+ public void ToUInt32_Invoke_ThrowsInvalidCastException()
+ {
+ Assert.Throws<InvalidCastException>(() => ((IConvertible)DBNull.Value).ToUInt32(null));
+ }
+
+ [Fact]
+ public void ToInt64_Invoke_ThrowsInvalidCastException()
+ {
+ Assert.Throws<InvalidCastException>(() => ((IConvertible)DBNull.Value).ToInt64(null));
+ }
+
+ [Fact]
+ public void ToUInt64_Invoke_ThrowsInvalidCastException()
+ {
+ Assert.Throws<InvalidCastException>(() => ((IConvertible)DBNull.Value).ToUInt64(null));
+ }
+
+ [Fact]
+ public void ToSingle_Invoke_ThrowsInvalidCastException()
+ {
+ Assert.Throws<InvalidCastException>(() => ((IConvertible)DBNull.Value).ToSingle(null));
+ }
+
+ [Fact]
+ public void ToDouble_Invoke_ThrowsInvalidCastException()
+ {
+ Assert.Throws<InvalidCastException>(() => ((IConvertible)DBNull.Value).ToDouble(null));
+ }
+
+ [Fact]
+ public void ToDecimal_Invoke_ThrowsInvalidCastException()
+ {
+ Assert.Throws<InvalidCastException>(() => ((IConvertible)DBNull.Value).ToDecimal(null));
+ }
+
+ [Fact]
+ public void ToDateTime_Invoke_ThrowsInvalidCastException()
+ {
+ Assert.Throws<InvalidCastException>(() => ((IConvertible)DBNull.Value).ToDateTime(null));
+ }
+
+ [Fact]
+ public static void GetTypeCode_Invoke_ReturnsDBNull()
+ {
+ Assert.Equal(TypeCode.DBNull, DBNull.Value.GetTypeCode());
+ }
+
+ public static IEnumerable<object[]> Equals_TestData()
+ {
+ yield return new object[] { DBNull.Value, DBNull.Value, true };
+ yield return new object[] { Convert.DBNull, DBNull.Value, true };
+ yield return new object[] { DBNull.Value, null, false };
+ }
+
+ [Theory]
+ [MemberData(nameof(Equals_TestData))]
+ public void Equals_Other_ReturnsExpected(DBNull dbNull, object other, bool expected)
+ {
+ Assert.Equal(expected, dbNull.Equals(other));
+ }
+
+ [Fact]
+ public void ToType_ValidType_ReturnsEmptyString()
+ {
+ Assert.Equal(string.Empty, ((IConvertible)DBNull.Value).ToType(typeof(string), null));
+ }
+
+ [Fact]
+ public void ToType_InvalidType_ThrowsInvalidCastException()
+ {
+ Assert.Throws<InvalidCastException>(() => ((IConvertible)DBNull.Value).ToType(typeof(int), null));
+ }
+
+ public static IEnumerable<object[]> IsDBNull_TestData()
+ {
+ yield return new object[] { DBNull.Value, true };
+ yield return new object[] { 6689, false };
+ yield return new object[] { new object(), false };
+ }
+
+ [Theory]
+ [MemberData(nameof(IsDBNull_TestData))]
+ public void Convert_IsDBNull_ReturnsExpected(object value, bool expected)
+ {
+ Assert.Equal(expected, Convert.IsDBNull(value));
+ }
+ }
+}
diff --git a/src/System.Runtime/tests/System/DecimalTests.cs b/src/System.Runtime/tests/System/DecimalTests.cs
index 058a9ebab9..1c7738a8ac 100644
--- a/src/System.Runtime/tests/System/DecimalTests.cs
+++ b/src/System.Runtime/tests/System/DecimalTests.cs
@@ -190,11 +190,10 @@ namespace System.Tests
[Theory]
[MemberData(nameof(Compare_TestData))]
- public static void Compare(decimal d1, object obj, int expected)
+ public void CompareTo_Other_ReturnsExpected(decimal d1, object obj, int expected)
{
- if (obj is decimal)
+ if (obj is decimal d2)
{
- decimal d2 = (decimal)obj;
Assert.Equal(expected, Math.Sign(d1.CompareTo(d2)));
if (expected >= 0)
{
@@ -218,16 +217,16 @@ namespace System.Tests
}
Assert.Equal(expected, Math.Sign(decimal.Compare(d1, d2)));
}
- IComparable comparable = d1;
- Assert.Equal(expected, Math.Sign(comparable.CompareTo(obj)));
+
+ Assert.Equal(expected, Math.Sign(d1.CompareTo(obj)));
}
- [Fact]
- public static void CompareTo_ObjectNotDecimal_ThrowsArgumentException()
+ [Theory]
+ [InlineData("a")]
+ [InlineData(234)]
+ public void CompareTo_ObjectNotDouble_ThrowsArgumentException(object value)
{
- IComparable comparable = 248m;
- AssertExtensions.Throws<ArgumentException>(null, () => comparable.CompareTo("248")); // Obj is not a decimal
- AssertExtensions.Throws<ArgumentException>(null, () => comparable.CompareTo(248)); // Obj is not a decimal
+ AssertExtensions.Throws<ArgumentException>(null, () => ((decimal)123).CompareTo(value));
}
public static IEnumerable<object[]> Divide_Valid_TestData()
@@ -375,12 +374,10 @@ namespace System.Tests
[MemberData(nameof(Equals_TestData))]
public static void Equals(object obj1, object obj2, bool expected)
{
- if (obj1 is decimal)
+ if (obj1 is decimal d1)
{
- decimal d1 = (decimal)obj1;
- if (obj2 is decimal)
+ if (obj2 is decimal d2)
{
- decimal d2 = (decimal)obj2;
Assert.Equal(expected, d1.Equals(d2));
Assert.Equal(expected, decimal.Equals(d1, d2));
Assert.Equal(expected, d1 == d2);
@@ -397,6 +394,28 @@ namespace System.Tests
Assert.Equal(expected, Equals(obj1, obj2));
}
+ public static IEnumerable<object[]> FromOACurrency_TestData()
+ {
+ yield return new object[] { 0L, 0m };
+ yield return new object[] { 1L, 0.0001m };
+ yield return new object[] { 100000L, 10m };
+ yield return new object[] { 10000000000L, 1000000m };
+ yield return new object[] { 1000000000000000000L, 100000000000000m };
+ yield return new object[] { 9223372036854775807L, 922337203685477.5807m };
+ yield return new object[] { -9223372036854775808L, -922337203685477.5808m };
+ yield return new object[] { 123456789L, 12345.6789m };
+ yield return new object[] { 1234567890000L, 123456789m };
+ yield return new object[] { 1234567890987654321L, 123456789098765.4321m };
+ yield return new object[] { 4294967295L, 429496.7295m };
+ }
+
+ [Theory]
+ [MemberData(nameof(FromOACurrency_TestData))]
+ public static void FromOACurrency(long oac, decimal expected)
+ {
+ Assert.Equal(expected, decimal.FromOACurrency(oac));
+ }
+
public static IEnumerable<object[]> Floor_TestData()
{
yield return new object[] { 123m, 123m };
@@ -445,6 +464,12 @@ namespace System.Tests
Assert.Equal(input, newValue);
}
+ [Fact]
+ public void GetTypeCode_Invoke_ReturnsDecimal()
+ {
+ Assert.Equal(TypeCode.Decimal, decimal.MaxValue.GetTypeCode());
+ }
+
public static IEnumerable<object[]> Multiply_Valid_TestData()
{
yield return new object[] { decimal.One, decimal.One, decimal.One };
@@ -532,7 +557,7 @@ namespace System.Tests
{
NumberStyles defaultStyle = NumberStyles.Float;
- var emptyFormat = NumberFormatInfo.CurrentInfo;
+ NumberFormatInfo emptyFormat = NumberFormatInfo.CurrentInfo;
var customFormat1 = new NumberFormatInfo();
customFormat1.CurrencySymbol = "$";
@@ -753,6 +778,132 @@ namespace System.Tests
Assert.Throws(exceptionType, () => decimal.Remainder(d1, d2));
}
+ public static IEnumerable<object[]> Round_Valid_TestData()
+ {
+ yield return new object[] { 0m, 0m };
+ yield return new object[] { 0.1m, 0m };
+ yield return new object[] { 0.5m, 0m };
+ yield return new object[] { 0.7m, 1m };
+ yield return new object[] { 1.3m, 1m };
+ yield return new object[] { 1.5m, 2m };
+ yield return new object[] { -0.1m, 0m };
+ yield return new object[] { -0.5m, 0m };
+ yield return new object[] { -0.7m, -1m };
+ yield return new object[] { -1.3m, -1m };
+ yield return new object[] { -1.5m, -2m };
+ }
+
+ [Theory]
+ [MemberData(nameof(Round_Valid_TestData))]
+ public static void Round(decimal d1, decimal expected)
+ {
+ Assert.Equal(expected, decimal.Round(d1));
+ }
+
+ public static IEnumerable<object[]> Round_Digit_Valid_TestData()
+ {
+ yield return new object[] { 1.45m, 1, 1.4m };
+ yield return new object[] { 1.55m, 1, 1.6m };
+ yield return new object[] { 123.456789m, 4, 123.4568m };
+ yield return new object[] { 123.456789m, 6, 123.456789m };
+ yield return new object[] { 123.456789m, 8, 123.456789m };
+ yield return new object[] { -123.456m, 0, -123m };
+ yield return new object[] { -123.0000000m, 3, -123.000m };
+ yield return new object[] { -123.0000000m, 11, -123.0000000m };
+ yield return new object[] { -9999999999.9999999999, 9, -10000000000.000000000m };
+ yield return new object[] { -9999999999.9999999999, 10, -9999999999.9999999999 };
+ }
+
+ [Theory]
+ [MemberData(nameof(Round_Digit_Valid_TestData))]
+ public static void Round_Digits_ReturnsExpected(decimal d, int digits, decimal expected)
+ {
+ Assert.Equal(expected, decimal.Round(d, digits));
+ }
+
+ public static IEnumerable<object[]> Round_Digit_Mid_Valid_TestData()
+ {
+ yield return new object[] { 1.45m, 1, MidpointRounding.ToEven, 1.4m };
+ yield return new object[] { 1.45m, 1, MidpointRounding.AwayFromZero, 1.5m };
+ yield return new object[] { 1.55m, 1, MidpointRounding.ToEven, 1.6m };
+ yield return new object[] { 1.55m, 1, MidpointRounding.AwayFromZero, 1.6m };
+ yield return new object[] { -1.45m, 1, MidpointRounding.ToEven, -1.4m };
+ yield return new object[] { -1.45m, 1, MidpointRounding.AwayFromZero, -1.5m };
+ yield return new object[] { 123.456789m, 4, MidpointRounding.ToEven, 123.4568m };
+ yield return new object[] { 123.456789m, 4, MidpointRounding.AwayFromZero, 123.4568m };
+ yield return new object[] { 123.456789m, 6, MidpointRounding.ToEven, 123.456789m };
+ yield return new object[] { 123.456789m, 6, MidpointRounding.AwayFromZero, 123.456789m };
+ yield return new object[] { 123.456789m, 8, MidpointRounding.ToEven, 123.456789m };
+ yield return new object[] { 123.456789m, 8, MidpointRounding.AwayFromZero, 123.456789m };
+ yield return new object[] { -123.456m, 0, MidpointRounding.ToEven, -123m };
+ yield return new object[] { -123.456m, 0, MidpointRounding.AwayFromZero, -123m };
+ yield return new object[] { -123.0000000m, 3, MidpointRounding.ToEven, -123.000m };
+ yield return new object[] { -123.0000000m, 3, MidpointRounding.AwayFromZero, -123.000m };
+ yield return new object[] { -123.0000000m, 11, MidpointRounding.ToEven, -123.0000000m };
+ yield return new object[] { -123.0000000m, 11, MidpointRounding.AwayFromZero, -123.0000000m };
+ yield return new object[] { -9999999999.9999999999, 9, MidpointRounding.ToEven, -10000000000.000000000m };
+ yield return new object[] { -9999999999.9999999999, 9, MidpointRounding.AwayFromZero, -10000000000.000000000m };
+ yield return new object[] { -9999999999.9999999999, 10, MidpointRounding.ToEven, -9999999999.9999999999 };
+ yield return new object[] { -9999999999.9999999999, 10, MidpointRounding.AwayFromZero, -9999999999.9999999999 };
+ }
+
+ [Theory]
+ [MemberData(nameof(Round_Digit_Mid_Valid_TestData))]
+ public static void Round_DigitsMode_ReturnsExpected(decimal d, int digits, MidpointRounding mode, decimal expected)
+ {
+ Assert.Equal(expected, decimal.Round(d, digits, mode));
+ }
+
+ public static IEnumerable<object[]> Round_Mid_Valid_TestData()
+ {
+ yield return new object[] { 0m, MidpointRounding.ToEven, 0m };
+ yield return new object[] { 0m, MidpointRounding.AwayFromZero, 0m };
+ yield return new object[] { 0.1m, MidpointRounding.ToEven, 0m };
+ yield return new object[] { 0.1m, MidpointRounding.AwayFromZero, 0m };
+ yield return new object[] { 0.5m, MidpointRounding.ToEven, 0m };
+ yield return new object[] { 0.5m, MidpointRounding.AwayFromZero, 1m };
+ yield return new object[] { 0.7m, MidpointRounding.ToEven, 1m };
+ yield return new object[] { 0.7m, MidpointRounding.AwayFromZero, 1m };
+ yield return new object[] { 1.3m, MidpointRounding.ToEven, 1m };
+ yield return new object[] { 1.3m, MidpointRounding.AwayFromZero, 1m };
+ yield return new object[] { 1.5m, MidpointRounding.ToEven, 2m };
+ yield return new object[] { 1.5m, MidpointRounding.AwayFromZero, 2m };
+ yield return new object[] { -0.1m, MidpointRounding.ToEven, 0m };
+ yield return new object[] { -0.1m, MidpointRounding.AwayFromZero, 0m };
+ yield return new object[] { -0.5m, MidpointRounding.ToEven, 0m };
+ yield return new object[] { -0.5m, MidpointRounding.AwayFromZero, -1m };
+ yield return new object[] { -0.7m, MidpointRounding.ToEven, -1m };
+ yield return new object[] { -0.7m, MidpointRounding.AwayFromZero, -1m };
+ yield return new object[] { -1.3m, MidpointRounding.ToEven, -1m };
+ yield return new object[] { -1.3m, MidpointRounding.AwayFromZero, -1m };
+ yield return new object[] { -1.5m, MidpointRounding.ToEven, -2m };
+ yield return new object[] { -1.5m, MidpointRounding.AwayFromZero, -2m };
+ }
+
+ [Theory]
+ [MemberData(nameof(Round_Mid_Valid_TestData))]
+ public void Round_MidpointRounding_ReturnsExpected(decimal d, MidpointRounding mode, decimal expected)
+ {
+ Assert.Equal(expected, decimal.Round(d, mode));
+ }
+
+ [Theory]
+ [InlineData(-1)]
+ [InlineData(29)]
+ public void Round_InvalidDecimals_ThrowsArgumentOutOfRangeException(int decimals)
+ {
+ AssertExtensions.Throws<ArgumentOutOfRangeException>("decimals", () => decimal.Round(1, decimals));
+ AssertExtensions.Throws<ArgumentOutOfRangeException>("decimals", () => decimal.Round(1, decimals, MidpointRounding.AwayFromZero));
+ }
+
+ [Theory]
+ [InlineData(MidpointRounding.ToEven - 1)]
+ [InlineData(MidpointRounding.AwayFromZero + 1)]
+ public void Round_InvalidMidpointRounding_ThrowsArgumentException(MidpointRounding mode)
+ {
+ AssertExtensions.Throws<ArgumentException>("mode", () => decimal.Round(1, 2, mode));
+ }
+
public static IEnumerable<object[]> Subtract_Valid_TestData()
{
yield return new object[] { 1m, 1m, 0m };
@@ -803,6 +954,35 @@ namespace System.Tests
Assert.Throws<OverflowException>(() => d3 -= d2);
}
+ public static IEnumerable<object[]> ToOACurrency_TestData()
+ {
+ yield return new object[] { 0m, 0L };
+ yield return new object[] { 1m, 10000L };
+ yield return new object[] { 1.000000000000000m, 10000L };
+ yield return new object[] { 10000000000m, 100000000000000L };
+ yield return new object[] { 10000000000.00000000000000000m, 100000000000000L };
+ yield return new object[] { 0.000000000123456789m, 0L };
+ yield return new object[] { 0.123456789m, 1235L };
+ yield return new object[] { 123456789m, 1234567890000L };
+ yield return new object[] { 4294967295m, 42949672950000L };
+ yield return new object[] { -79.228162514264337593543950335m, -792282L };
+ yield return new object[] { -79228162514264.337593543950335m, -792281625142643376L };
+ }
+
+ [Theory]
+ [MemberData(nameof(ToOACurrency_TestData))]
+ public void ToOACurrency_Value_ReturnsExpected(decimal value, long expected)
+ {
+ Assert.Equal(expected, decimal.ToOACurrency(value));
+ }
+
+ [Fact]
+ public void ToOACurrency_InvalidAsLong_ThrowsOverflowException()
+ {
+ Assert.Throws<OverflowException>(() => decimal.ToOACurrency(new decimal(long.MaxValue) + 1));
+ Assert.Throws<OverflowException>(() => decimal.ToOACurrency(new decimal(long.MinValue) - 1));
+ }
+
[Fact]
public static void ToByte()
{
diff --git a/src/System.Runtime/tests/System/DoubleTests.cs b/src/System.Runtime/tests/System/DoubleTests.cs
index f630bb8cd4..1e3b1ad54a 100644
--- a/src/System.Runtime/tests/System/DoubleTests.cs
+++ b/src/System.Runtime/tests/System/DoubleTests.cs
@@ -116,11 +116,10 @@ namespace System.Tests
[InlineData(double.NaN, double.NaN, 0)]
[InlineData(double.NaN, (double)0, -1)]
[InlineData((double)234, null, 1)]
- public static void CompareTo(double d1, object value, int expected)
+ public void CompareTo_Other_ReturnsExpected(double d1, object value, int expected)
{
- if (value is double)
+ if (value is double d2)
{
- double d2 = (double)value;
Assert.Equal(expected, Math.Sign(d1.CompareTo(d2)));
if (double.IsNaN(d1) || double.IsNaN(d2))
{
@@ -153,16 +152,16 @@ namespace System.Tests
}
}
}
- IComparable comparable = d1;
- Assert.Equal(expected, Math.Sign(comparable.CompareTo(value)));
+
+ Assert.Equal(expected, Math.Sign(d1.CompareTo(value)));
}
- [Fact]
- public static void CompareTo_ObjectNotDouble_ThrowsArgumentException()
+ [Theory]
+ [InlineData("a")]
+ [InlineData((float)234)]
+ public void CompareTo_ObjectNotDouble_ThrowsArgumentException(object value)
{
- IComparable comparable = (double)234;
- AssertExtensions.Throws<ArgumentException>(null, () => comparable.CompareTo((float)234)); // Obj is not a double
- AssertExtensions.Throws<ArgumentException>(null, () => comparable.CompareTo("234")); // Obj is not a double
+ AssertExtensions.Throws<ArgumentException>(null, () => ((double)123).CompareTo(value));
}
[Theory]
@@ -174,9 +173,8 @@ namespace System.Tests
[InlineData((double)789, "789", false)]
public static void Equals(double d1, object value, bool expected)
{
- if (value is double)
+ if (value is double d2)
{
- double d2 = (double)value;
Assert.Equal(expected, d1.Equals(d2));
if (double.IsNaN(d1) && double.IsNaN(d2))
@@ -194,6 +192,12 @@ namespace System.Tests
Assert.Equal(expected, d1.Equals(value));
}
+ [Fact]
+ public void GetTypeCode_Invoke_ReturnsDouble()
+ {
+ Assert.Equal(TypeCode.Double, 0.0.GetTypeCode());
+ }
+
public static IEnumerable<object[]> ToString_TestData()
{
yield return new object[] { double.MinValue, "G", null, "-1.79769313486232E+308" };
@@ -230,7 +234,7 @@ namespace System.Tests
};
yield return new object[] { (double)-2468, "N", customNegativeSignGroupSeparatorNegativePattern, "(2*468.00)" };
- var invariantFormat = NumberFormatInfo.InvariantInfo;
+ NumberFormatInfo invariantFormat = NumberFormatInfo.InvariantInfo;
yield return new object[] { double.Epsilon, "G", invariantFormat, "4.94065645841247E-324" };
yield return new object[] { double.NaN, "G", invariantFormat, "NaN" };
yield return new object[] { double.PositiveInfinity, "G", invariantFormat, "Infinity" };
@@ -289,7 +293,7 @@ namespace System.Tests
// Defaults: AllowLeadingWhite | AllowTrailingWhite | AllowLeadingSign | AllowDecimalPoint | AllowExponent | AllowThousands
NumberStyles defaultStyle = NumberStyles.Float;
- var emptyFormat = NumberFormatInfo.CurrentInfo;
+ NumberFormatInfo emptyFormat = NumberFormatInfo.CurrentInfo;
var dollarSignCommaSeparatorFormat = new NumberFormatInfo()
{
diff --git a/src/System.Runtime/tests/System/EnumTests.cs b/src/System.Runtime/tests/System/EnumTests.cs
index f8bf5e1ca4..fc90883a19 100644
--- a/src/System.Runtime/tests/System/EnumTests.cs
+++ b/src/System.Runtime/tests/System/EnumTests.cs
@@ -5,12 +5,11 @@
using System.Collections.Generic;
using System.Linq;
using System.Reflection;
-using System.Reflection.Emit;
using Xunit;
namespace System.Tests
{
- public static partial class EnumTests
+ public partial class EnumTests
{
public static IEnumerable<object[]> Parse_TestData()
{
@@ -367,6 +366,21 @@ namespace System.Tests
Assert.Equal(expected, Enum.GetName(enumType, value));
}
+ [Theory]
+ [InlineData(SimpleEnum.Blue, TypeCode.Int32)]
+ [InlineData(ByteEnum.Max, TypeCode.Byte)]
+ [InlineData(SByteEnum.Min, TypeCode.SByte)]
+ [InlineData(UInt16Enum.Max, TypeCode.UInt16)]
+ [InlineData(Int16Enum.Min, TypeCode.Int16)]
+ [InlineData(UInt32Enum.Max, TypeCode.UInt32)]
+ [InlineData(Int32Enum.Min, TypeCode.Int32)]
+ [InlineData(UInt64Enum.Max, TypeCode.UInt64)]
+ [InlineData(Int64Enum.Min, TypeCode.Int64)]
+ public static void GetTypeCode_Enum_ReturnsExpected(Enum e, TypeCode expected)
+ {
+ Assert.Equal(expected, e.GetTypeCode());
+ }
+
public static IEnumerable<object[]> IsDefined_TestData()
{
// SByte
@@ -1439,25 +1453,30 @@ namespace System.Tests
yield return new object[] { AttributeTargets.Class | AttributeTargets.Delegate, "G", "Class, Delegate" };
}
+#pragma warning disable 618 // ToString with IFormatProvider is marked as Obsolete.
[Theory]
[MemberData(nameof(ToString_Format_TestData))]
public static void ToString_Format(Enum e, string format, string expected)
{
if (format.ToUpperInvariant() == "G")
{
- string nullString = null;
-
Assert.Equal(expected, e.ToString());
- Assert.Equal(expected, e.ToString(""));
- Assert.Equal(expected, e.ToString(nullString));
+ Assert.Equal(expected, e.ToString(string.Empty));
+ Assert.Equal(expected, e.ToString((string)null));
+
+ Assert.Equal(expected, e.ToString((IFormatProvider)null));
}
- // Format string is non-case-sensitive
+
+ // Format string is case-insensitive.
Assert.Equal(expected, e.ToString(format));
Assert.Equal(expected, e.ToString(format.ToUpperInvariant()));
Assert.Equal(expected, e.ToString(format.ToLowerInvariant()));
+ Assert.Equal(expected, e.ToString(format, (IFormatProvider)null));
+
Format(e.GetType(), e, format, expected);
}
+#pragma warning restore 618
[Fact]
public static void ToString_Format_MultipleMatches()
diff --git a/src/System.Runtime/tests/System/EnumTests.netcoreapp.cs b/src/System.Runtime/tests/System/EnumTests.netcoreapp.cs
index 3478db8f86..4b110f2e63 100644
--- a/src/System.Runtime/tests/System/EnumTests.netcoreapp.cs
+++ b/src/System.Runtime/tests/System/EnumTests.netcoreapp.cs
@@ -9,7 +9,7 @@ using Xunit;
namespace System.Tests
{
- public static partial class EnumTests
+ public partial class EnumTests
{
[Theory]
[MemberData(nameof(Parse_TestData))]
@@ -32,7 +32,6 @@ namespace System.Tests
[Theory]
[MemberData(nameof(Parse_Invalid_TestData))]
- [ActiveIssue("https://github.com/dotnet/corert/issues/3651 Enum.Parse<T>() validation.", TargetFrameworkMonikers.UapAot)]
public static void Parse_Invalid_NetCoreApp11(Type enumType, string value, bool ignoreCase, Type exceptionType)
{
Type typeArgument = enumType == null || !enumType.GetTypeInfo().IsEnum ? typeof(SimpleEnum) : enumType;
diff --git a/src/System.Runtime/tests/System/GCTests.cs b/src/System.Runtime/tests/System/GCTests.cs
index b8db2de467..1b7a01c431 100644
--- a/src/System.Runtime/tests/System/GCTests.cs
+++ b/src/System.Runtime/tests/System/GCTests.cs
@@ -2,6 +2,7 @@
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
+using System.Runtime.CompilerServices;
using System.Diagnostics;
using System.Threading;
using System.Runtime;
@@ -423,6 +424,18 @@ namespace System.Tests
{
private const int TimeoutMilliseconds = 10 * 30 * 1000; //if full GC is triggered it may take a while
+ /// <summary>
+ /// NoGC regions will be automatically exited if more than the requested budget
+ /// is allocated while still in the region. In order to avoid this, the budget is set
+ /// to be higher than what the test should be allocating. When running on CoreCLR/DesktopCLR,
+ /// these tests generally do not allocate because they are implemented as fcalls into the runtime
+ /// itself, but the CoreRT runtime is written in mostly managed code and tends to allocate more.
+ ///
+ /// This budget should be high enough to avoid exiting no-gc regions when doing normal unit
+ /// tests, regardless of the runtime.
+ /// </summary>
+ private const int NoGCRequestedBudget = 8192;
+
[Fact]
[OuterLoop]
public static void GetGeneration_WeakReference()
@@ -437,7 +450,7 @@ namespace System.Tests
Version myobj = new Version();
var wkref = new WeakReference(myobj);
- Assert.True(GC.TryStartNoGCRegion(1024));
+ Assert.True(GC.TryStartNoGCRegion(NoGCRequestedBudget));
Assert.True(GC.GetGeneration(wkref) >= 0);
Assert.Equal(GC.GetGeneration(wkref), GC.GetGeneration(myobj));
GC.EndNoGCRegion();
@@ -508,6 +521,35 @@ namespace System.Tests
}, options).Dispose();
}
+ [MethodImpl(MethodImplOptions.NoOptimization)]
+ private static void AllocateALot()
+ {
+ for (int i = 0; i < 10000; i++)
+ {
+ var array = new long[NoGCRequestedBudget];
+ GC.KeepAlive(array);
+ }
+ }
+
+ [Fact]
+ [OuterLoop]
+ public static void TryStartNoGCRegion_ExitThroughAllocation()
+ {
+ RemoteInvokeOptions options = new RemoteInvokeOptions();
+ options.TimeOut = TimeoutMilliseconds;
+ RemoteInvoke(() =>
+ {
+ Assert.True(GC.TryStartNoGCRegion(1024));
+
+ AllocateALot();
+
+ // at this point, the GC should have booted us out of the no GC region
+ // since we allocated too much.
+ Assert.Throws<InvalidOperationException>(() => GC.EndNoGCRegion());
+ return SuccessExitCode;
+ }, options).Dispose();
+ }
+
[Fact]
[OuterLoop]
public static void TryStartNoGCRegion_StartWhileInNoGCRegion()
@@ -516,8 +558,8 @@ namespace System.Tests
options.TimeOut = TimeoutMilliseconds;
RemoteInvoke(() =>
{
- Assert.True(GC.TryStartNoGCRegion(1024));
- Assert.Throws<InvalidOperationException>(() => GC.TryStartNoGCRegion(1024));
+ Assert.True(GC.TryStartNoGCRegion(NoGCRequestedBudget));
+ Assert.Throws<InvalidOperationException>(() => GC.TryStartNoGCRegion(NoGCRequestedBudget));
Assert.Throws<InvalidOperationException>(() => GC.EndNoGCRegion());
@@ -533,8 +575,8 @@ namespace System.Tests
options.TimeOut = TimeoutMilliseconds;
RemoteInvoke(() =>
{
- Assert.True(GC.TryStartNoGCRegion(1024, true));
- Assert.Throws<InvalidOperationException>(() => GC.TryStartNoGCRegion(1024, true));
+ Assert.True(GC.TryStartNoGCRegion(NoGCRequestedBudget, true));
+ Assert.Throws<InvalidOperationException>(() => GC.TryStartNoGCRegion(NoGCRequestedBudget, true));
Assert.Throws<InvalidOperationException>(() => GC.EndNoGCRegion());
@@ -550,8 +592,8 @@ namespace System.Tests
options.TimeOut = TimeoutMilliseconds;
RemoteInvoke(() =>
{
- Assert.True(GC.TryStartNoGCRegion(1024, 1024));
- Assert.Throws<InvalidOperationException>(() => GC.TryStartNoGCRegion(1024, 1024));
+ Assert.True(GC.TryStartNoGCRegion(NoGCRequestedBudget, NoGCRequestedBudget));
+ Assert.Throws<InvalidOperationException>(() => GC.TryStartNoGCRegion(NoGCRequestedBudget, NoGCRequestedBudget));
Assert.Throws<InvalidOperationException>(() => GC.EndNoGCRegion());
@@ -567,8 +609,8 @@ namespace System.Tests
options.TimeOut = TimeoutMilliseconds;
RemoteInvoke(() =>
{
- Assert.True(GC.TryStartNoGCRegion(1024, 1024, true));
- Assert.Throws<InvalidOperationException>(() => GC.TryStartNoGCRegion(1024, 1024, true));
+ Assert.True(GC.TryStartNoGCRegion(NoGCRequestedBudget, NoGCRequestedBudget, true));
+ Assert.Throws<InvalidOperationException>(() => GC.TryStartNoGCRegion(NoGCRequestedBudget, NoGCRequestedBudget, true));
Assert.Throws<InvalidOperationException>(() => GC.EndNoGCRegion());
@@ -584,7 +626,7 @@ namespace System.Tests
options.TimeOut = TimeoutMilliseconds;
RemoteInvoke(() =>
{
- Assert.True(GC.TryStartNoGCRegion(1024, true));
+ Assert.True(GC.TryStartNoGCRegion(NoGCRequestedBudget, true));
Assert.Equal(GCSettings.LatencyMode, GCLatencyMode.NoGCRegion);
Assert.Throws<InvalidOperationException>(() => GCSettings.LatencyMode = GCLatencyMode.LowLatency);
@@ -603,7 +645,7 @@ namespace System.Tests
RemoteInvoke(() =>
{
- Assert.True(GC.TryStartNoGCRegion(1024));
+ Assert.True(GC.TryStartNoGCRegion(NoGCRequestedBudget));
Assert.Equal(GCSettings.LatencyMode, GCLatencyMode.NoGCRegion);
GC.EndNoGCRegion();
@@ -620,7 +662,7 @@ namespace System.Tests
options.TimeOut = TimeoutMilliseconds;
RemoteInvoke(() =>
{
- Assert.True(GC.TryStartNoGCRegion(1024, true));
+ Assert.True(GC.TryStartNoGCRegion(NoGCRequestedBudget, true));
Assert.Equal(GCSettings.LatencyMode, GCLatencyMode.NoGCRegion);
GC.EndNoGCRegion();
@@ -637,7 +679,7 @@ namespace System.Tests
options.TimeOut = TimeoutMilliseconds;
RemoteInvoke(() =>
{
- Assert.True(GC.TryStartNoGCRegion(1024, 1024));
+ Assert.True(GC.TryStartNoGCRegion(NoGCRequestedBudget, NoGCRequestedBudget));
Assert.Equal(GCSettings.LatencyMode, GCLatencyMode.NoGCRegion);
GC.EndNoGCRegion();
@@ -654,7 +696,7 @@ namespace System.Tests
options.TimeOut = TimeoutMilliseconds;
RemoteInvoke(() =>
{
- Assert.True(GC.TryStartNoGCRegion(1024, 1024, true));
+ Assert.True(GC.TryStartNoGCRegion(NoGCRequestedBudget, NoGCRequestedBudget, true));
Assert.Equal(GCSettings.LatencyMode, GCLatencyMode.NoGCRegion);
GC.EndNoGCRegion();
diff --git a/src/System.Runtime/tests/System/GCTests.netcoreapp.cs b/src/System.Runtime/tests/System/GCTests.netcoreapp.cs
index fb1b75b3e3..67035d2022 100644
--- a/src/System.Runtime/tests/System/GCTests.netcoreapp.cs
+++ b/src/System.Runtime/tests/System/GCTests.netcoreapp.cs
@@ -12,7 +12,6 @@ namespace System.Tests
[Theory]
[InlineData(1000)]
[InlineData(100000)]
- [ActiveIssue("https://github.com/dotnet/corert/issues/3648 - GC.GetAllocatedBytesForCurrentThread not yet ported to CoreRT", TargetFrameworkMonikers.UapAot)]
public static void GetAllocatedBytesForCurrentThread(int size)
{
long start = GC.GetAllocatedBytesForCurrentThread();
diff --git a/src/System.Runtime/tests/System/Int16Tests.cs b/src/System.Runtime/tests/System/Int16Tests.cs
index 66abc2ffbe..69ae4314ae 100644
--- a/src/System.Runtime/tests/System/Int16Tests.cs
+++ b/src/System.Runtime/tests/System/Int16Tests.cs
@@ -2,14 +2,13 @@
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
-using System;
using System.Collections.Generic;
using System.Globalization;
using Xunit;
namespace System.Tests
{
- public static class Int16Tests
+ public class Int16Tests
{
[Fact]
public static void Ctor_Empty()
@@ -49,22 +48,22 @@ namespace System.Tests
[InlineData((short)-234, (short)234, -1)]
[InlineData((short)-234, (short)-432, 1)]
[InlineData((short)234, null, 1)]
- public static void CompareTo(short i, object obj, int expected)
+ public void CompareTo_Other_ReturnsExpected(short i, object value, int expected)
{
- if (obj is short)
+ if (value is short shortValue)
{
- Assert.Equal(expected, Math.Sign(i.CompareTo((short)obj)));
+ Assert.Equal(expected, Math.Sign(i.CompareTo(shortValue)));
}
- IComparable comparable = i;
- Assert.Equal(expected, Math.Sign(comparable.CompareTo(obj)));
+
+ Assert.Equal(expected, Math.Sign(i.CompareTo(value)));
}
- [Fact]
- public static void CompareTo_ObjectNotShort_ThrowsArgumentException()
+ [Theory]
+ [InlineData("a")]
+ [InlineData(234)]
+ public void CompareTo_ObjectNotShort_ThrowsArgumentException(object value)
{
- IComparable comparable = (short)234;
- AssertExtensions.Throws<ArgumentException>(null, () => comparable.CompareTo("a")); // Obj is not a short
- AssertExtensions.Throws<ArgumentException>(null, () => comparable.CompareTo(234)); // Obj is not a short
+ AssertExtensions.Throws<ArgumentException>(null, () => ((short)123).CompareTo(value));
}
[Theory]
@@ -88,6 +87,12 @@ namespace System.Tests
Assert.Equal(expected, i1.Equals(obj));
}
+ [Fact]
+ public void GetTypeCode_Invoke_ReturnsInt16()
+ {
+ Assert.Equal(TypeCode.Int16, ((short)1).GetTypeCode());
+ }
+
public static IEnumerable<object[]> ToString_TestData()
{
NumberFormatInfo emptyFormat = NumberFormatInfo.CurrentInfo;
diff --git a/src/System.Runtime/tests/System/Int32Tests.cs b/src/System.Runtime/tests/System/Int32Tests.cs
index 03fd1e1280..73561d63d2 100644
--- a/src/System.Runtime/tests/System/Int32Tests.cs
+++ b/src/System.Runtime/tests/System/Int32Tests.cs
@@ -8,7 +8,7 @@ using Xunit;
namespace System.Tests
{
- public static class Int32Tests
+ public class Int32Tests
{
[Fact]
public static void Ctor_Empty()
@@ -48,22 +48,22 @@ namespace System.Tests
[InlineData(-234, 234, -1)]
[InlineData(-234, -432, 1)]
[InlineData(234, null, 1)]
- public static void CompareTo(int i, object value, int expected)
+ public void CompareTo_Other_ReturnsExpected(int i, object value, int expected)
{
- if (value is int)
+ if (value is int intValue)
{
- Assert.Equal(expected, Math.Sign(i.CompareTo((int)value)));
+ Assert.Equal(expected, Math.Sign(i.CompareTo(intValue)));
}
- IComparable comparable = i;
- Assert.Equal(expected, Math.Sign(comparable.CompareTo(value)));
+
+ Assert.Equal(expected, Math.Sign(i.CompareTo(value)));
}
- [Fact]
- public static void CompareTo_ObjectNotInt_ThrowsArgumentException()
+ [Theory]
+ [InlineData("a")]
+ [InlineData((long)234)]
+ public void CompareTo_ObjectNotInt_ThrowsArgumentException(object value)
{
- IComparable comparable = 234;
- AssertExtensions.Throws<ArgumentException>(null, () => comparable.CompareTo("a")); // Obj is not an int
- AssertExtensions.Throws<ArgumentException>(null, () => comparable.CompareTo((long)234)); // Obj is not an int
+ AssertExtensions.Throws<ArgumentException>(null, () => 123.CompareTo(value));
}
[Theory]
@@ -87,6 +87,12 @@ namespace System.Tests
Assert.Equal(expected, i1.Equals(obj));
}
+ [Fact]
+ public void GetTypeCode_Invoke_ReturnsInt32()
+ {
+ Assert.Equal(TypeCode.Int32, 1.GetTypeCode());
+ }
+
public static IEnumerable<object[]> ToString_TestData()
{
NumberFormatInfo emptyFormat = NumberFormatInfo.CurrentInfo;
diff --git a/src/System.Runtime/tests/System/Int64Tests.cs b/src/System.Runtime/tests/System/Int64Tests.cs
index ca87ca8b56..7d25d695f2 100644
--- a/src/System.Runtime/tests/System/Int64Tests.cs
+++ b/src/System.Runtime/tests/System/Int64Tests.cs
@@ -2,14 +2,13 @@
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
-using System;
using System.Collections.Generic;
using System.Globalization;
using Xunit;
namespace System.Tests
{
- public static class Int64Tests
+ public class Int64Tests
{
[Fact]
public static void Ctor_Empty()
@@ -49,22 +48,22 @@ namespace System.Tests
[InlineData((long)-234, (long)234, -1)]
[InlineData((long)-234, (long)-432, 1)]
[InlineData((long)234, null, 1)]
- public static void CompareTo(long i, object value, long expected)
+ public void CompareTo_Other_ReturnsExpected(long i, object value, int expected)
{
- if (value is long)
+ if (value is long longValue)
{
- Assert.Equal(expected, Math.Sign(i.CompareTo((long)value)));
+ Assert.Equal(expected, Math.Sign(i.CompareTo(longValue)));
}
- IComparable comparable = i;
- Assert.Equal(expected, Math.Sign(comparable.CompareTo(value)));
+
+ Assert.Equal(expected, Math.Sign(i.CompareTo(value)));
}
- [Fact]
- public static void CompareTo_ObjectNotLong_ThrowsArgumentException()
+ [Theory]
+ [InlineData("a")]
+ [InlineData(234)]
+ public void CompareTo_ObjectNotLong_ThrowsArgumentException(object value)
{
- IComparable comparable = (long)234;
- AssertExtensions.Throws<ArgumentException>(null, () => comparable.CompareTo("a")); // Obj is not a long
- AssertExtensions.Throws<ArgumentException>(null, () => comparable.CompareTo(234)); // Obj is not a long
+ AssertExtensions.Throws<ArgumentException>(null, () => ((long)123).CompareTo(value));
}
[Theory]
@@ -88,6 +87,12 @@ namespace System.Tests
Assert.Equal(expected, i1.Equals(obj));
}
+ [Fact]
+ public void GetTypeCode_Invoke_ReturnsInt64()
+ {
+ Assert.Equal(TypeCode.Int64, ((long)1).GetTypeCode());
+ }
+
public static IEnumerable<object[]> ToString_TestData()
{
NumberFormatInfo emptyFormat = NumberFormatInfo.CurrentInfo;
diff --git a/src/System.Runtime/tests/System/Runtime/MemoryFailPointTests.cs b/src/System.Runtime/tests/System/Runtime/MemoryFailPointTests.cs
new file mode 100644
index 0000000000..2c35f7af43
--- /dev/null
+++ b/src/System.Runtime/tests/System/Runtime/MemoryFailPointTests.cs
@@ -0,0 +1,36 @@
+// Licensed to the .NET Foundation under one or more agreements.
+// The .NET Foundation licenses this file to you under the MIT license.
+// See the LICENSE file in the project root for more information.
+
+using Xunit;
+
+namespace System.Runtime.Tests
+{
+ public class MemoryFailPointTests
+ {
+ [Theory]
+ [InlineData(1)]
+ [InlineData(2)]
+ public void Ctor_Dispose_Success(int sizeInMegabytes)
+ {
+ var memoryFailPoint = new MemoryFailPoint(sizeInMegabytes);
+ memoryFailPoint.Dispose();
+ memoryFailPoint.Dispose();
+ }
+
+ [Theory]
+ [InlineData(int.MinValue)]
+ [InlineData(0)]
+ public void Ctor_Negative_ThrowsArgumentOutOfRangeException(int sizeInMegabytes)
+ {
+ AssertExtensions.Throws<ArgumentOutOfRangeException>("sizeInMegabytes", () => new MemoryFailPoint(sizeInMegabytes));
+ }
+
+ [Fact]
+ [PlatformSpecific(TestPlatforms.Windows)] //https://github.com/dotnet/coreclr/issues/7807
+ public void Ctor_LargeSizeInMegabytes_ThrowsInsufficientMemoryException()
+ {
+ Assert.Throws<InsufficientMemoryException>(() => new MemoryFailPoint(int.MaxValue));
+ }
+ }
+} \ No newline at end of file
diff --git a/src/System.Runtime/tests/System/Runtime/Tests.netstandard.1.7.cs b/src/System.Runtime/tests/System/Runtime/Tests.netstandard.1.7.cs
deleted file mode 100644
index 14c0c8738b..0000000000
--- a/src/System.Runtime/tests/System/Runtime/Tests.netstandard.1.7.cs
+++ /dev/null
@@ -1,37 +0,0 @@
-// Licensed to the .NET Foundation under one or more agreements.
-// The .NET Foundation licenses this file to you under the MIT license.
-// See the LICENSE file in the project root for more information.
-using System;
-using System.Runtime;
-using Xunit;
-
-namespace System.Runtime.Tests
-{
- public static class RuntimeHelpersTests
- {
- [Fact]
- public static void MemoryFailPointTestNoThrow()
- {
- MemoryFailPoint memFailPoint = null;
-
- memFailPoint = new MemoryFailPoint(1);
- memFailPoint.Dispose();
- memFailPoint = new MemoryFailPoint(2);
- memFailPoint.Dispose();
- }
-
- [Fact]
- public static void MemoryFailPointTestThrow()
- {
- Assert.Throws<ArgumentOutOfRangeException>(() => new MemoryFailPoint(Int32.MinValue));
- Assert.Throws<ArgumentOutOfRangeException>(() => new MemoryFailPoint(0));
- }
-
- [Fact]
- [PlatformSpecific(TestPlatforms.Windows)] //https://github.com/dotnet/coreclr/issues/7807
- public static void MemoryFailPointMaxMemoryThrow()
- {
- Assert.Throws<InsufficientMemoryException>(() => new MemoryFailPoint(Int32.MaxValue));
- }
- }
-} \ No newline at end of file
diff --git a/src/System.Runtime/tests/System/SByteTests.cs b/src/System.Runtime/tests/System/SByteTests.cs
index 85f9cece0d..5a5600eb9d 100644
--- a/src/System.Runtime/tests/System/SByteTests.cs
+++ b/src/System.Runtime/tests/System/SByteTests.cs
@@ -2,14 +2,13 @@
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
-using System;
using System.Collections.Generic;
using System.Globalization;
using Xunit;
namespace System.Tests
{
- public static class SByteTests
+ public class SByteTests
{
[Fact]
public static void Ctor_Empty()
@@ -45,23 +44,22 @@ namespace System.Tests
[InlineData((sbyte)114, (sbyte)123, -1)]
[InlineData((sbyte)114, sbyte.MaxValue, -1)]
[InlineData((sbyte)114, null, 1)]
- public static void CompareTo(sbyte i, object value, int expected)
+ public void CompareTo_Other_ReturnsExpected(sbyte i, object value, int expected)
{
- if (value is sbyte)
+ if (value is sbyte sbyteValue)
{
- Assert.Equal(expected, Math.Sign(i.CompareTo((sbyte)value)));
+ Assert.Equal(expected, Math.Sign(i.CompareTo(sbyteValue)));
}
- IComparable comparable = i;
- Assert.Equal(expected, Math.Sign(comparable.CompareTo(value)));
+ Assert.Equal(expected, Math.Sign(i.CompareTo(value)));
}
- [Fact]
- public static void CompareTo_ObjectNotSByte_ThrowsArgumentException()
+ [Theory]
+ [InlineData("a")]
+ [InlineData(234)]
+ public void CompareTo_ObjectNotSByte_ThrowsArgumentException(object value)
{
- IComparable comparable = (sbyte)114;
- AssertExtensions.Throws<ArgumentException>(null, () => comparable.CompareTo("a")); // Obj is not a sbyte
- AssertExtensions.Throws<ArgumentException>(null, () => comparable.CompareTo(234)); // Obj is not a sbyte
+ AssertExtensions.Throws<ArgumentException>(null, () => ((sbyte)123).CompareTo(value));
}
[Theory]
@@ -85,6 +83,12 @@ namespace System.Tests
Assert.Equal(expected, i1.Equals(obj));
}
+ [Fact]
+ public void GetTypeCode_Invoke_ReturnsSByte()
+ {
+ Assert.Equal(TypeCode.SByte, ((sbyte)1).GetTypeCode());
+ }
+
public static IEnumerable<object[]> ToString_TestData()
{
NumberFormatInfo emptyFormat = NumberFormatInfo.CurrentInfo;
diff --git a/src/System.Runtime/tests/System/SingleTests.cs b/src/System.Runtime/tests/System/SingleTests.cs
index b8bc2d4f37..ec48475b66 100644
--- a/src/System.Runtime/tests/System/SingleTests.cs
+++ b/src/System.Runtime/tests/System/SingleTests.cs
@@ -2,7 +2,6 @@
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
-using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Globalization;
@@ -58,6 +57,12 @@ namespace System.Tests
}
[Fact]
+ public void GetTypeCode_Invoke_ReturnsSingle()
+ {
+ Assert.Equal(TypeCode.Single, 0.0f.GetTypeCode());
+ }
+
+ [Fact]
public static void NaN()
{
Assert.Equal((float)0.0 / (float)0.0, float.NaN);
@@ -117,11 +122,10 @@ namespace System.Tests
[InlineData(float.NaN, float.NaN, 0)]
[InlineData(float.NaN, (float)0, -1)]
[InlineData((float)234, null, 1)]
- public static void CompareTo(float f1, object value, int expected)
+ public void CompareTo_Other_ReturnsExpected(float f1, object value, int expected)
{
- if (value is float)
+ if (value is float f2)
{
- float f2 = (float)value;
Assert.Equal(expected, Math.Sign(f1.CompareTo(f2)));
if (float.IsNaN(f1) || float.IsNaN(f2))
{
@@ -154,16 +158,16 @@ namespace System.Tests
}
}
}
- IComparable comparable = f1;
- Assert.Equal(expected, Math.Sign(comparable.CompareTo(value)));
+
+ Assert.Equal(expected, Math.Sign(f1.CompareTo(value)));
}
- [Fact]
- public static void CompareTo_ObjectNotFloat_ThrowsArgumentException()
+ [Theory]
+ [InlineData("a")]
+ [InlineData((double)234)]
+ public void CompareTo_ObjectNotFloat_ThrowsArgumentException(object value)
{
- IComparable comparable = (float)234;
- AssertExtensions.Throws<ArgumentException>(null, () => comparable.CompareTo((double)234)); // Obj is not a float
- AssertExtensions.Throws<ArgumentException>(null, () => comparable.CompareTo("234")); // Obj is not a float
+ AssertExtensions.Throws<ArgumentException>(null, () => ((float)123).CompareTo(value));
}
[Theory]
@@ -175,9 +179,8 @@ namespace System.Tests
[InlineData((float)789, "789", false)]
public static void Equals(float f1, object value, bool expected)
{
- if (value is float)
+ if (value is float f2)
{
- float f2 = (float)value;
Assert.Equal(expected, f1.Equals(f2));
if (float.IsNaN(f1) && float.IsNaN(f2))
@@ -231,7 +234,7 @@ namespace System.Tests
};
yield return new object[] { (float)-2468, "N", customNegativeSignGroupSeparatorNegativePattern, "(2*468.00)" };
- var invariantFormat = NumberFormatInfo.InvariantInfo;
+ NumberFormatInfo invariantFormat = NumberFormatInfo.InvariantInfo;
yield return new object[] { float.Epsilon, "G", invariantFormat, "1.401298E-45" };
yield return new object[] { float.NaN, "G", invariantFormat, "NaN" };
yield return new object[] { float.PositiveInfinity, "G", invariantFormat, "Infinity" };
diff --git a/src/System.Runtime/tests/System/StringTests.cs b/src/System.Runtime/tests/System/StringTests.cs
index e64793ec7d..963d0a1ae7 100644
--- a/src/System.Runtime/tests/System/StringTests.cs
+++ b/src/System.Runtime/tests/System/StringTests.cs
@@ -1139,12 +1139,40 @@ namespace System.Tests
}
}
+ public static IEnumerable<object[]> Equals_EncyclopaediaData()
+ {
+ yield return new object[] { StringComparison.CurrentCulture, false };
+ yield return new object[] { StringComparison.CurrentCultureIgnoreCase, false };
+ yield return new object[] { StringComparison.Ordinal, false };
+ yield return new object[] { StringComparison.OrdinalIgnoreCase, false };
+
+ // Windows and ICU disagree about how these strings compare in the default locale.
+ yield return new object[] { StringComparison.InvariantCulture, PlatformDetection.IsWindows };
+ yield return new object[] { StringComparison.InvariantCultureIgnoreCase, PlatformDetection.IsWindows };
+ }
+
+ [Theory]
+ [MemberData(nameof(Equals_EncyclopaediaData))]
+ public void Equals_Encyclopaedia_ReturnsExpected(StringComparison comparison, bool expected)
+ {
+ RemoteInvoke((comparisonString, expectedString) =>
+ {
+ string source = "encyclop\u00e6dia";
+ string target = "encyclopaedia";
+
+ CultureInfo.CurrentCulture = new CultureInfo("se-SE");
+ StringComparison comparisonType = (StringComparison)Enum.Parse(typeof(StringComparison), comparisonString);
+ Assert.Equal(bool.Parse(expectedString), string.Equals(source, target, comparisonType));
+
+ return SuccessExitCode;
+ }, comparison.ToString(), expected.ToString());
+ }
+
[Theory]
[InlineData(StringComparison.CurrentCulture - 1)]
[InlineData(StringComparison.OrdinalIgnoreCase + 1)]
public static void Equals_InvalidComparisonType_ThrowsArgumentOutOfRangeException(StringComparison comparisonType)
{
- // Invalid comparison type
AssertExtensions.Throws<ArgumentException>("comparisonType", () => string.Equals("a", "b", comparisonType));
AssertExtensions.Throws<ArgumentException>("comparisonType", () => "a".Equals("a", comparisonType));
}
diff --git a/src/System.Runtime/tests/TimeZoneNotFoundExceptionTests.cs b/src/System.Runtime/tests/System/TimeZoneNotFoundExceptionTests.cs
index ed810273d1..ed810273d1 100644
--- a/src/System.Runtime/tests/TimeZoneNotFoundExceptionTests.cs
+++ b/src/System.Runtime/tests/System/TimeZoneNotFoundExceptionTests.cs
diff --git a/src/System.Runtime/tests/TimeZoneTests.cs b/src/System.Runtime/tests/System/TimeZoneTests.cs
index cfaafcc684..cfaafcc684 100644
--- a/src/System.Runtime/tests/TimeZoneTests.cs
+++ b/src/System.Runtime/tests/System/TimeZoneTests.cs
diff --git a/src/System.Runtime/tests/System/UInt16Tests.cs b/src/System.Runtime/tests/System/UInt16Tests.cs
index b3699927b9..c1b3517546 100644
--- a/src/System.Runtime/tests/System/UInt16Tests.cs
+++ b/src/System.Runtime/tests/System/UInt16Tests.cs
@@ -2,14 +2,13 @@
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
-using System;
using System.Collections.Generic;
using System.Globalization;
using Xunit;
namespace System.Tests
{
- public static class UInt16Tests
+ public class UInt16Tests
{
[Fact]
public static void Ctor_Empty()
@@ -45,22 +44,22 @@ namespace System.Tests
[InlineData((ushort)234, (ushort)456, -1)]
[InlineData((ushort)234, ushort.MaxValue, -1)]
[InlineData((ushort)234, null, 1)]
- public static void CompareTo(ushort i, object value, int expected)
+ public void CompareTo_Other_ReturnsExpected(ushort i, object value, int expected)
{
- if (value is ushort)
+ if (value is ushort ushortValue)
{
- Assert.Equal(expected, Math.Sign(i.CompareTo((ushort)value)));
+ Assert.Equal(expected, Math.Sign(i.CompareTo(ushortValue)));
}
- IComparable comparable = i;
- Assert.Equal(expected, Math.Sign(comparable.CompareTo(value)));
+
+ Assert.Equal(expected, Math.Sign(i.CompareTo(value)));
}
- [Fact]
- public static void CompareTo_ObjectNotUShort_ThrowsArgumentException()
+ [Theory]
+ [InlineData("a")]
+ [InlineData(234)]
+ public void CompareTo_ObjectNotUshort_ThrowsArgumentException(object value)
{
- IComparable comparable = (ushort)234;
- AssertExtensions.Throws<ArgumentException>(null, () => comparable.CompareTo("a")); // Obj is not a ushort
- AssertExtensions.Throws<ArgumentException>(null, () => comparable.CompareTo(234)); // Obj is not a ushort
+ AssertExtensions.Throws<ArgumentException>(null, () => ((ushort)123).CompareTo(value));
}
[Theory]
@@ -81,6 +80,12 @@ namespace System.Tests
Assert.Equal(expected, i1.Equals(obj));
}
+ [Fact]
+ public void GetTypeCode_Invoke_ReturnsUInt16()
+ {
+ Assert.Equal(TypeCode.UInt16, ((ushort)1).GetTypeCode());
+ }
+
public static IEnumerable<object[]> ToString_TestData()
{
NumberFormatInfo emptyFormat = NumberFormatInfo.CurrentInfo;
diff --git a/src/System.Runtime/tests/System/UInt32Tests.cs b/src/System.Runtime/tests/System/UInt32Tests.cs
index ab6f80960f..70f32d2bf5 100644
--- a/src/System.Runtime/tests/System/UInt32Tests.cs
+++ b/src/System.Runtime/tests/System/UInt32Tests.cs
@@ -2,14 +2,13 @@
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
-using System;
using System.Collections.Generic;
using System.Globalization;
using Xunit;
namespace System.Tests
{
- public static class UInt32Tests
+ public class UInt32Tests
{
[Fact]
public static void Ctor_Empty()
@@ -45,22 +44,22 @@ namespace System.Tests
[InlineData((uint)234, (uint)456, -1)]
[InlineData((uint)234, uint.MaxValue, -1)]
[InlineData((uint)234, null, 1)]
- public static void CompareTo(uint i, object value, int expected)
+ public void CompareTo_Other_ReturnsExpected(uint i, object value, int expected)
{
- if (value is uint)
+ if (value is uint uintValue)
{
- Assert.Equal(expected, Math.Sign(i.CompareTo((uint)value)));
+ Assert.Equal(expected, Math.Sign(i.CompareTo(uintValue)));
}
- IComparable comparable = i;
- Assert.Equal(expected, Math.Sign(comparable.CompareTo(value)));
+
+ Assert.Equal(expected, Math.Sign(i.CompareTo(value)));
}
- [Fact]
- public static void CompareTo_ObjectNotUInt_ThrowsArgumentException()
+ [Theory]
+ [InlineData("a")]
+ [InlineData(234)]
+ public void CompareTo_ObjectNotUint_ThrowsArgumentException(object value)
{
- IComparable comparable = (uint)234;
- AssertExtensions.Throws<ArgumentException>(null, () => comparable.CompareTo("a")); // Obj is not a uint
- AssertExtensions.Throws<ArgumentException>(null, () => comparable.CompareTo(234)); // Obj is not a uint
+ AssertExtensions.Throws<ArgumentException>(null, () => ((uint)123).CompareTo(value));
}
[Theory]
@@ -82,6 +81,12 @@ namespace System.Tests
Assert.Equal(expected, i1.Equals(obj));
}
+ [Fact]
+ public void GetTypeCode_Invoke_ReturnsUInt32()
+ {
+ Assert.Equal(TypeCode.UInt32, ((uint)1).GetTypeCode());
+ }
+
public static IEnumerable<object[]> ToString_TestData()
{
NumberFormatInfo emptyFormat = NumberFormatInfo.CurrentInfo;
diff --git a/src/System.Runtime/tests/System/UInt64Tests.cs b/src/System.Runtime/tests/System/UInt64Tests.cs
index e6fc44f96f..bf84ad9488 100644
--- a/src/System.Runtime/tests/System/UInt64Tests.cs
+++ b/src/System.Runtime/tests/System/UInt64Tests.cs
@@ -2,14 +2,13 @@
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
-using System;
using System.Collections.Generic;
using System.Globalization;
using Xunit;
namespace System.Tests
{
- public static class UInt64Tests
+ public class UInt64Tests
{
[Fact]
public static void Ctor_Empty()
@@ -45,22 +44,22 @@ namespace System.Tests
[InlineData((ulong)234, (ulong)456, -1)]
[InlineData((ulong)234, ulong.MaxValue, -1)]
[InlineData((ulong)234, null, 1)]
- public static void CompareTo(ulong i, object value, int expected)
+ public void CompareTo_Other_ReturnsExpected(ulong i, object value, int expected)
{
- if (value is ulong)
+ if (value is ulong ulongValue)
{
- Assert.Equal(expected, Math.Sign(i.CompareTo((ulong)value)));
+ Assert.Equal(expected, Math.Sign(i.CompareTo(ulongValue)));
}
- IComparable comparable = i;
- Assert.Equal(expected, Math.Sign(comparable.CompareTo(value)));
+
+ Assert.Equal(expected, Math.Sign(i.CompareTo(value)));
}
- [Fact]
- public static void CompareTo_ObjectNotULong_ThrowsArgumentException()
+ [Theory]
+ [InlineData("a")]
+ [InlineData(234)]
+ public void CompareTo_ObjectNotUlong_ThrowsArgumentException(object value)
{
- IComparable comparable = (ulong)234;
- AssertExtensions.Throws<ArgumentException>(null, () => comparable.CompareTo("a")); // Obj is not a ulong
- AssertExtensions.Throws<ArgumentException>(null, () => comparable.CompareTo(234)); // Obj is not a ulong
+ AssertExtensions.Throws<ArgumentException>(null, () => ((ulong)123).CompareTo(value));
}
[Theory]
@@ -72,9 +71,8 @@ namespace System.Tests
[InlineData((ulong)789, 789, false)]
public static void Equals(ulong i1, object obj, bool expected)
{
- if (obj is ulong)
+ if (obj is ulong i2)
{
- ulong i2 = (ulong)obj;
Assert.Equal(expected, i1.Equals(i2));
Assert.Equal(expected, i1.GetHashCode().Equals(i2.GetHashCode()));
Assert.Equal((int)i1, i1.GetHashCode());
@@ -82,6 +80,12 @@ namespace System.Tests
Assert.Equal(expected, i1.Equals(obj));
}
+ [Fact]
+ public void GetTypeCode_Invoke_ReturnsUInt64()
+ {
+ Assert.Equal(TypeCode.UInt64, ((ulong)1).GetTypeCode());
+ }
+
public static IEnumerable<object[]> ToStringTestData()
{
NumberFormatInfo emptyFormat = NumberFormatInfo.CurrentInfo;
diff --git a/src/System.Runtime/tests/System/VersionTests.cs b/src/System.Runtime/tests/System/VersionTests.cs
index 88b5cf4167..414bc52d9d 100644
--- a/src/System.Runtime/tests/System/VersionTests.cs
+++ b/src/System.Runtime/tests/System/VersionTests.cs
@@ -2,7 +2,6 @@
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
-using System;
using System.Collections.Generic;
using Xunit;
@@ -10,6 +9,12 @@ namespace System.Tests
{
public partial class VersionTests
{
+ [Fact]
+ public void Ctor_Default()
+ {
+ VerifyVersion(new Version(), 0, 0, -1, -1);
+ }
+
[Theory]
[MemberData(nameof(Parse_Valid_TestData))]
public static void Ctor_String(string input, Version expected)
@@ -19,9 +24,9 @@ namespace System.Tests
[Theory]
[MemberData(nameof(Parse_Invalid_TestData))]
- public static void Ctor_String_Invalid(string input, Type exceptionType)
+ public static void CtorInvalidVerionString_ThrowsException(string input, Type exceptionType)
{
- Assert.Throws(exceptionType, () => new Version(input)); // Input is invalid
+ Assert.Throws(exceptionType, () => new Version(input));
}
[Theory]
@@ -33,13 +38,6 @@ namespace System.Tests
VerifyVersion(new Version(major, minor), major, minor, -1, -1);
}
- [Fact]
- public static void Ctor_Int_Int_Invalid()
- {
- AssertExtensions.Throws<ArgumentOutOfRangeException>("major", () => new Version(-1, 0)); // Major < 0
- AssertExtensions.Throws<ArgumentOutOfRangeException>("minor", () => new Version(0, -1)); // Minor < 0
- }
-
[Theory]
[InlineData(0, 0, 0)]
[InlineData(2, 3, 4)]
@@ -49,14 +47,6 @@ namespace System.Tests
VerifyVersion(new Version(major, minor, build), major, minor, build, -1);
}
- [Fact]
- public static void Ctor_Int_Int_Int_Invalid()
- {
- AssertExtensions.Throws<ArgumentOutOfRangeException>("major", () => new Version(-1, 0, 0)); // Major < 0
- AssertExtensions.Throws<ArgumentOutOfRangeException>("minor", () => new Version(0, -1, 0)); // Minor < 0
- AssertExtensions.Throws<ArgumentOutOfRangeException>("build", () => new Version(0, 0, -1)); // Build < 0
- }
-
[Theory]
[InlineData(0, 0, 0, 0)]
[InlineData(2, 3, 4, 7)]
@@ -74,12 +64,32 @@ namespace System.Tests
}
[Fact]
- public static void Ctor_Int_Int_Int_Int_Invalid()
+ public void Ctor_NegativeMajor_ThrowsArgumentOutOfRangeException()
+ {
+ AssertExtensions.Throws<ArgumentOutOfRangeException>("major", () => new Version(-1, 0));
+ AssertExtensions.Throws<ArgumentOutOfRangeException>("major", () => new Version(-1, 0, 0));
+ AssertExtensions.Throws<ArgumentOutOfRangeException>("major", () => new Version(-1, 0, 0, 0));
+ }
+
+ [Fact]
+ public void Ctor_NegativeMinor_ThrowsArgumentOutOfRangeException()
{
- AssertExtensions.Throws<ArgumentOutOfRangeException>("major", () => new Version(-1, 0, 0, 0)); // Major < 0
- AssertExtensions.Throws<ArgumentOutOfRangeException>("minor", () => new Version(0, -1, 0, 0)); // Minor < 0
- AssertExtensions.Throws<ArgumentOutOfRangeException>("build", () => new Version(0, 0, -1, 0)); // Build < 0
- AssertExtensions.Throws<ArgumentOutOfRangeException>("revision", () => new Version(0, 0, 0, -1)); // Revision < 0
+ AssertExtensions.Throws<ArgumentOutOfRangeException>("minor", () => new Version(0, -1));
+ AssertExtensions.Throws<ArgumentOutOfRangeException>("minor", () => new Version(0, -1, 0));
+ AssertExtensions.Throws<ArgumentOutOfRangeException>("minor", () => new Version(0, -1, 0, 0));
+ }
+
+ [Fact]
+ public void Ctor_NegativeBuild_ThrowsArgumentOutOfRangeException()
+ {
+ AssertExtensions.Throws<ArgumentOutOfRangeException>("build", () => new Version(0, 0, -1));
+ AssertExtensions.Throws<ArgumentOutOfRangeException>("build", () => new Version(0, 0, -1, 0));
+ }
+
+ [Fact]
+ public void Ctor_NegativeRevision_ThrowsArgumentOutOfRangeException()
+ {
+ AssertExtensions.Throws<ArgumentOutOfRangeException>("revision", () => new Version(0, 0, 0, -1));
}
public static IEnumerable<object[]> CompareTo_TestData()
@@ -102,14 +112,15 @@ namespace System.Tests
yield return new object[] { new Version(1, 2, 3, 4), new Version(1, 2, 3, 4), 0 };
yield return new object[] { new Version(1, 2, 3, 4), new Version(1, 2, 3, 5), -1 };
yield return new object[] { new Version(1, 2, 3, 4), new Version(1, 2, 3, 3), 1 };
+
+ yield return new object[] { new Version(1, 2, 3, 4), null, 1 };
}
[Theory]
[MemberData(nameof(CompareTo_TestData))]
- public static void CompareTo(Version version1, Version version2, int expectedSign)
+ public void CompareTo_Other_ReturnsExpected(Version version1, object other, int expectedSign)
{
- Assert.Equal(expectedSign, Math.Sign(version1.CompareTo(version2)));
- if (version1 != null && version2 != null)
+ if (version1 != null && other is Version version2)
{
if (expectedSign >= 0)
{
@@ -134,22 +145,29 @@ namespace System.Tests
}
IComparable comparable = version1;
- Assert.Equal(expectedSign, Math.Sign(comparable.CompareTo(version2)));
+ Assert.Equal(expectedSign, Math.Sign(comparable.CompareTo(other)));
+ Assert.Equal(expectedSign, Math.Sign(version1.CompareTo(other)));
}
- [Fact]
- public static void CompareTo_Invalid()
+ [Theory]
+ [InlineData(1)]
+ [InlineData("1.1")]
+ public void CompareTo_ObjectNotAVersion_ThrowsArgumentException(object other)
{
- IComparable comparable = new Version(1, 1);
- AssertExtensions.Throws<ArgumentException>(null, () => comparable.CompareTo(1)); // Obj is not a version
- AssertExtensions.Throws<ArgumentException>(null, () => comparable.CompareTo("1.1")); // Obj is not a version
+ var version = new Version(1, 1);
+ AssertExtensions.Throws<ArgumentException>(null, () => version.CompareTo(other));
+ AssertExtensions.Throws<ArgumentException>(null, () => ((IComparable)version).CompareTo(other));
+ }
+ [Fact]
+ public void Comparisons_NullArgument_ThrowsArgumentNullException()
+ {
Version nullVersion = null;
- Version testVersion = new Version(1, 2);
- AssertExtensions.Throws<ArgumentNullException>("v1", () => testVersion >= nullVersion); // V2 is null
- AssertExtensions.Throws<ArgumentNullException>("v1", () => testVersion > nullVersion); // V2 is null
- AssertExtensions.Throws<ArgumentNullException>("v1", () => nullVersion < testVersion); // V1 is null
- AssertExtensions.Throws<ArgumentNullException>("v1", () => nullVersion <= testVersion); // V1 is null
+ Version nonNullVersion = new Version(1, 2);
+ AssertExtensions.Throws<ArgumentNullException>("v1", () => nonNullVersion >= nullVersion);
+ AssertExtensions.Throws<ArgumentNullException>("v1", () => nonNullVersion > nullVersion);
+ AssertExtensions.Throws<ArgumentNullException>("v1", () => nullVersion < nonNullVersion);
+ AssertExtensions.Throws<ArgumentNullException>("v1", () => nullVersion <= nonNullVersion);
}
private static IEnumerable<object[]> Equals_TestData()
@@ -176,7 +194,7 @@ namespace System.Tests
[Theory]
[MemberData(nameof(Equals_TestData))]
- public static void Equals(Version version1, object obj, bool expected)
+ public static void Equals_Other_ReturnsExpected(Version version1, object obj, bool expected)
{
Version version2 = obj as Version;
@@ -204,12 +222,11 @@ namespace System.Tests
[Theory]
[MemberData(nameof(Parse_Valid_TestData))]
- public static void Parse(string input, Version expected)
+ public static void Parse_ValidInput_ReturnsExpected(string input, Version expected)
{
Assert.Equal(expected, Version.Parse(input));
- Version version;
- Assert.True(Version.TryParse(input, out version));
+ Assert.True(Version.TryParse(input, out Version version));
Assert.Equal(expected, version);
}
@@ -246,12 +263,11 @@ namespace System.Tests
[Theory]
[MemberData(nameof(Parse_Invalid_TestData))]
- public static void Parse_Invalid(string input, Type exceptionType)
+ public static void Parse_InvalidInput_ThrowsException(string input, Type exceptionType)
{
Assert.Throws(exceptionType, () => Version.Parse(input));
- Version version;
- Assert.False(Version.TryParse(input, out version));
+ Assert.False(Version.TryParse(input, out Version version));
Assert.Null(version);
}
@@ -264,7 +280,7 @@ namespace System.Tests
[Theory]
[MemberData(nameof(ToString_TestData))]
- public static void ToString(Version version, string[] expected)
+ public static void ToString_Invoke_ReturnsExpected(Version version, string[] expected)
{
for (int i = 0; i < expected.Length; i++)
{
@@ -286,6 +302,13 @@ namespace System.Tests
Assert.Equal(revision, version.Revision);
Assert.Equal((short)(revision >> 16), version.MajorRevision);
Assert.Equal(unchecked((short)(revision & 0xFFFF)), version.MinorRevision);
+
+ Version clone = Assert.IsType<Version>(version.Clone());
+ Assert.NotSame(version, clone);
+ Assert.Equal(version.Major, clone.Major);
+ Assert.Equal(version.Minor, clone.Minor);
+ Assert.Equal(version.Build, clone.Build);
+ Assert.Equal(version.Revision, clone.Revision);
}
}
}
diff --git a/src/System.Runtime/tests/VersionTests.cs b/src/System.Runtime/tests/VersionTests.cs
deleted file mode 100644
index 63afecd32c..0000000000
--- a/src/System.Runtime/tests/VersionTests.cs
+++ /dev/null
@@ -1,39 +0,0 @@
-// Licensed to the .NET Foundation under one or more agreements.
-// The .NET Foundation licenses this file to you under the MIT license.
-// See the LICENSE file in the project root for more information.
-
-using System;
-using System.Collections.Generic;
-using Xunit;
-
-namespace System.Tests
-{
- public partial class VersionTests
- {
- [Fact]
- public static void Ctor()
- {
- Version version = new Version();
- Assert.Equal(0, version.Major);
- Assert.Equal(0, version.Minor);
- }
-
- [Theory]
- [MemberData(nameof(CompareTo_TestData))]
- public static void CompareTo_Object(Version version1, Version version2, int expectedSign)
- {
- Assert.Equal(expectedSign, Math.Sign(version1.CompareTo(version2)));
- }
-
- [Theory]
- [MemberData(nameof(Parse_Valid_TestData))]
- public static void Clone_EqualsOriginal(string input, Version expected)
- {
- var actual = new Version(input);
- Assert.Equal(expected, actual);
-
- var clone = (Version)actual.Clone();
- Assert.Equal(expected, clone);
- }
- }
-}
diff --git a/src/System.Runtime/tests/netstandard.1.7.Tests.cs b/src/System.Runtime/tests/netstandard.1.7.Tests.cs
deleted file mode 100644
index 9b813e8be6..0000000000
--- a/src/System.Runtime/tests/netstandard.1.7.Tests.cs
+++ /dev/null
@@ -1,43 +0,0 @@
-// Licensed to the .NET Foundation under one or more agreements.
-// The .NET Foundation licenses this file to you under the MIT license.
-// See the LICENSE file in the project root for more information.
-
-using System;
-using System.Collections;
-using System.Collections.Generic;
-using System.Globalization;
-using System.Runtime.InteropServices;
-using System.Threading;
-using System.Threading.Tasks;
-using Xunit;
-
-namespace System.Tests
-{
- public static class NetStandard17Tests
- {
- public static IEnumerable<object[]> Equals_EncyclopaediaData()
- {
- yield return new object[] { StringComparison.CurrentCulture, false };
- yield return new object[] { StringComparison.CurrentCultureIgnoreCase, false };
- yield return new object[] { StringComparison.Ordinal, false };
- yield return new object[] { StringComparison.OrdinalIgnoreCase, false };
-
- // Windows and ICU disagree about how these strings compare in the default locale.
- yield return new object[] { StringComparison.InvariantCulture, RuntimeInformation.IsOSPlatform(OSPlatform.Windows) };
- yield return new object[] { StringComparison.InvariantCultureIgnoreCase, RuntimeInformation.IsOSPlatform(OSPlatform.Windows) };
- }
-
- [Theory]
- [MemberData(nameof(Equals_EncyclopaediaData))]
- public static void Equals_Encyclopaedia(StringComparison comparison, bool expected)
- {
- string source = "encyclop\u00e6dia";
- string target = "encyclopaedia";
-
- Helpers.PerformActionWithCulture(new CultureInfo("se-SE"), () =>
- {
- Assert.Equal(expected, string.Equals(source, target, comparison));
- });
- }
- }
-}
diff --git a/src/System.Security.AccessControl/pkg/System.Security.AccessControl.pkgproj b/src/System.Security.AccessControl/pkg/System.Security.AccessControl.pkgproj
index afdd21fbcf..f05d73f778 100644
--- a/src/System.Security.AccessControl/pkg/System.Security.AccessControl.pkgproj
+++ b/src/System.Security.AccessControl/pkg/System.Security.AccessControl.pkgproj
@@ -3,7 +3,7 @@
<Import Project="$([MSBuild]::GetDirectoryNameOfFileAbove($(MSBuildThisFileDirectory), dir.props))\dir.props" />
<ItemGroup>
<ProjectReference Include="..\ref\System.Security.AccessControl.csproj">
- <SupportedFramework>net461;netcoreapp2.0;uap10.1;$(AllXamarinFrameworks)</SupportedFramework>
+ <SupportedFramework>net461;netcoreapp2.0;$(UAPvNextTFM);$(AllXamarinFrameworks)</SupportedFramework>
</ProjectReference>
<ProjectReference Include="..\src\System.Security.AccessControl.csproj" />
<HarvestIncludePaths Include="ref/net46;lib/net46;runtimes/win/lib/net46" />
diff --git a/src/System.Security.AccessControl/ref/System.Security.AccessControl.csproj b/src/System.Security.AccessControl/ref/System.Security.AccessControl.csproj
index 416539689f..8e967b026d 100644
--- a/src/System.Security.AccessControl/ref/System.Security.AccessControl.csproj
+++ b/src/System.Security.AccessControl/ref/System.Security.AccessControl.csproj
@@ -3,8 +3,8 @@
<Import Project="$([MSBuild]::GetDirectoryNameOfFileAbove($(MSBuildThisFileDirectory), dir.props))\dir.props" />
<PropertyGroup>
<ProjectGuid>{F80C478C-48EE-46A5-89C4-EE0CFB23A14F}</ProjectGuid>
- <!-- UAP10.1 is not yet mapped to netstandard2.0, manually duplicate this ref -->
- <PackageTargetFramework Condition="'$(TargetGroup)' == 'netstandard'">netstandard2.0;uap10.1</PackageTargetFramework>
+ <!-- UAPvNext is not yet mapped to netstandard2.0, manually duplicate this ref -->
+ <PackageTargetFramework Condition="'$(TargetGroup)' == 'netstandard'">netstandard2.0;$(UAPvNextTFM)</PackageTargetFramework>
<IsPartialFacadeAssembly Condition="'$(TargetGroup)' == 'netfx'">true</IsPartialFacadeAssembly>
</PropertyGroup>
<PropertyGroup Condition="'$(Configuration)|$(Platform)' == 'netfx-Debug|AnyCPU'" />
@@ -18,7 +18,7 @@
<Reference Include="mscorlib" />
</ItemGroup>
<ItemGroup Condition="'$(TargetGroup)' != 'netfx'">
- <SuppressPackageTargetFrameworkCompatibility Include="uap10.1" />
+ <SuppressPackageTargetFrameworkCompatibility Include="$(UAPvNextTFM)" />
<ProjectReference Include="..\..\System.Security.Principal.Windows\ref\System.Security.Principal.Windows.csproj" />
</ItemGroup>
<Import Project="$([MSBuild]::GetDirectoryNameOfFileAbove($(MSBuildThisFileDirectory), dir.targets))\dir.targets" />
diff --git a/src/System.Security.AccessControl/tests/System.Security.AccessControl.Tests.csproj b/src/System.Security.AccessControl/tests/System.Security.AccessControl.Tests.csproj
index 63ea73063f..bf4686ecee 100644
--- a/src/System.Security.AccessControl/tests/System.Security.AccessControl.Tests.csproj
+++ b/src/System.Security.AccessControl/tests/System.Security.AccessControl.Tests.csproj
@@ -72,9 +72,6 @@
<Compile Include="SystemAcl\SystemAcl_RemoveInheritedAces.cs" />
<Compile Include="SystemAcl\SystemAcl_SetAudit.cs" />
<Compile Include="Utils.cs" />
- <Compile Include="$(CommonTestPath)\System\AssertExtensions.cs">
- <Link>Common\System\AssertExtensions.cs</Link>
- </Compile>
</ItemGroup>
<ItemGroup>
<EmbeddedResource Include="Resources\$(AssemblyName).rd.xml" />
diff --git a/src/System.Security.Claims/tests/System.Security.Claims.Tests.csproj b/src/System.Security.Claims/tests/System.Security.Claims.Tests.csproj
index 5543d75178..7a60c9f59b 100644
--- a/src/System.Security.Claims/tests/System.Security.Claims.Tests.csproj
+++ b/src/System.Security.Claims/tests/System.Security.Claims.Tests.csproj
@@ -12,9 +12,6 @@
<Compile Include="GenericPrincipalTests.cs" />
<Compile Include="ClaimsPrincipalTests.cs" />
<Compile Include="ClaimTests.cs" />
- <Compile Include="$(CommonTestPath)\System\AssertExtensions.cs">
- <Link>Common\System\AssertExtensions.cs</Link>
- </Compile>
<Compile Include="$(CommonTestPath)\System\PlatformDetection.cs">
<Link>CommonTest\System\PlatformDetection.cs</Link>
</Compile>
diff --git a/src/System.Security.Cryptography.Algorithms/ref/Configurations.props b/src/System.Security.Cryptography.Algorithms/ref/Configurations.props
index 192309fce5..492def5c96 100644
--- a/src/System.Security.Cryptography.Algorithms/ref/Configurations.props
+++ b/src/System.Security.Cryptography.Algorithms/ref/Configurations.props
@@ -4,6 +4,7 @@
<BuildConfigurations>
netcoreapp;
netfx;
+ net47;
uap;
</BuildConfigurations>
</PropertyGroup>
diff --git a/src/System.Security.Cryptography.Algorithms/ref/System.Security.Cryptography.Algorithms.csproj b/src/System.Security.Cryptography.Algorithms/ref/System.Security.Cryptography.Algorithms.csproj
index f678c8a144..a7d4bac7df 100644
--- a/src/System.Security.Cryptography.Algorithms/ref/System.Security.Cryptography.Algorithms.csproj
+++ b/src/System.Security.Cryptography.Algorithms/ref/System.Security.Cryptography.Algorithms.csproj
@@ -3,8 +3,10 @@
<Import Project="$([MSBuild]::GetDirectoryNameOfFileAbove($(MSBuildThisFileDirectory), dir.props))\dir.props" />
<PropertyGroup>
<ProjectGuid>{102247C1-3DB9-4DB5-80B3-EE9F80DD4E8F}</ProjectGuid>
- <IsPartialFacadeAssembly Condition="'$(TargetGroup)' == 'netfx'">true</IsPartialFacadeAssembly>
+ <IsPartialFacadeAssembly Condition="'$(TargetGroup)' == 'netfx' or '$(TargetGroup)' == 'net47'">true</IsPartialFacadeAssembly>
</PropertyGroup>
+ <PropertyGroup Condition="'$(Configuration)|$(Platform)' == 'net47-Debug|AnyCPU'" />
+ <PropertyGroup Condition="'$(Configuration)|$(Platform)' == 'net47-Release|AnyCPU'" />
<PropertyGroup Condition="'$(Configuration)|$(Platform)' == 'netcoreapp-Debug|AnyCPU'" />
<PropertyGroup Condition="'$(Configuration)|$(Platform)' == 'netcoreapp-Release|AnyCPU'" />
<PropertyGroup Condition="'$(Configuration)|$(Platform)' == 'netfx-Debug|AnyCPU'" />
@@ -14,14 +16,14 @@
<ItemGroup>
<Compile Include="System.Security.Cryptography.Algorithms.cs" />
</ItemGroup>
- <ItemGroup Condition="'$(TargetGroup)' != 'netfx'">
+ <ItemGroup Condition="'$(IsPartialFacadeAssembly)' != 'true'">
<ProjectReference Include="..\..\System.Runtime\ref\System.Runtime.csproj" />
<ProjectReference Include="..\..\System.Runtime.Extensions\ref\System.Runtime.Extensions.csproj" />
<ProjectReference Include="..\..\System.IO\ref\System.IO.csproj" />
<ProjectReference Include="..\..\System.Security.Cryptography.Encoding\ref\System.Security.Cryptography.Encoding.csproj" />
<ProjectReference Include="..\..\System.Security.Cryptography.Primitives\ref\System.Security.Cryptography.Primitives.csproj" />
</ItemGroup>
- <ItemGroup Condition="'$(TargetGroup)' == 'netfx'">
+ <ItemGroup Condition="'$(IsPartialFacadeAssembly)' == 'true'">
<Reference Include="mscorlib" />
<Reference Include="System" />
<Reference Include="System.Core" />
diff --git a/src/System.Security.Cryptography.Algorithms/src/Configurations.props b/src/System.Security.Cryptography.Algorithms/src/Configurations.props
index b71c22879c..3c676b5a95 100644
--- a/src/System.Security.Cryptography.Algorithms/src/Configurations.props
+++ b/src/System.Security.Cryptography.Algorithms/src/Configurations.props
@@ -6,6 +6,7 @@
netcoreapp-OSX;
netcoreapp-Windows_NT;
netfx-Windows_NT;
+ net47-Windows_NT;
uap-Windows_NT;
</BuildConfigurations>
</PropertyGroup>
diff --git a/src/System.Security.Cryptography.Algorithms/src/System.Security.Cryptography.Algorithms.csproj b/src/System.Security.Cryptography.Algorithms/src/System.Security.Cryptography.Algorithms.csproj
index aa938347a7..e8912ca256 100644
--- a/src/System.Security.Cryptography.Algorithms/src/System.Security.Cryptography.Algorithms.csproj
+++ b/src/System.Security.Cryptography.Algorithms/src/System.Security.Cryptography.Algorithms.csproj
@@ -9,9 +9,11 @@
<DefineConstants>INTERNAL_ASYMMETRIC_IMPLEMENTATIONS</DefineConstants>
<NoWarn>CA5351;$(NoWarn)</NoWarn>
<DefineConstants Condition="'$(TargetGroup)' == 'uap'">$(DefineConstants);uap</DefineConstants>
- <IsPartialFacadeAssembly Condition="'$(TargetGroup)' == 'netfx'">true</IsPartialFacadeAssembly>
+ <IsPartialFacadeAssembly Condition="'$(TargetGroup)' == 'netfx' or '$(TargetGroup)' == 'net47'">true</IsPartialFacadeAssembly>
<GenFacadesIgnoreMissingTypes Condition="'$(TargetGroup)' == 'netfx'">true</GenFacadesIgnoreMissingTypes>
</PropertyGroup>
+ <PropertyGroup Condition="'$(Configuration)|$(Platform)' == 'net47-Windows_NT-Debug|AnyCPU'" />
+ <PropertyGroup Condition="'$(Configuration)|$(Platform)' == 'net47-Windows_NT-Release|AnyCPU'" />
<PropertyGroup Condition="'$(Configuration)|$(Platform)' == 'netcoreapp-OSX-Debug|AnyCPU'" />
<PropertyGroup Condition="'$(Configuration)|$(Platform)' == 'netcoreapp-OSX-Release|AnyCPU'" />
<PropertyGroup Condition="'$(Configuration)|$(Platform)' == 'netcoreapp-Unix-Debug|AnyCPU'" />
@@ -22,7 +24,7 @@
<PropertyGroup Condition="'$(Configuration)|$(Platform)' == 'netfx-Windows_NT-Release|AnyCPU'" />
<PropertyGroup Condition="'$(Configuration)|$(Platform)' == 'uap-Windows_NT-Debug|AnyCPU'" />
<PropertyGroup Condition="'$(Configuration)|$(Platform)' == 'uap-Windows_NT-Release|AnyCPU'" />
- <ItemGroup Condition="'$(TargetGroup)' != 'netfx'">
+ <ItemGroup Condition="'$(IsPartialFacadeAssembly)' != 'true'">
<Compile Include="Internal\Cryptography\AesImplementation.cs" />
<Compile Include="Internal\Cryptography\DesImplementation.cs" />
<Compile Include="Internal\Cryptography\Helpers.cs" />
@@ -107,7 +109,7 @@
<Link>Internal\Cryptography\UniversalCryptoDecryptor.cs</Link>
</Compile>
</ItemGroup>
- <ItemGroup Condition=" '$(TargetsWindows)' == 'true' AND '$(TargetGroup)' != 'netfx'">
+ <ItemGroup Condition=" '$(TargetsWindows)' == 'true' and '$(IsPartialFacadeAssembly)' != 'true'">
<Compile Include="System\Security\Cryptography\CngKeyLite.cs" />
<Compile Include="System\Security\Cryptography\DSACng.cs" />
<Compile Include="System\Security\Cryptography\ECDsaCng.cs" />
@@ -477,7 +479,7 @@
<Link>Common\System\Security\Cryptography\DerSequenceReader.cs</Link>
</Compile>
</ItemGroup>
- <ItemGroup Condition="'$(TargetGroup)' != 'netfx'">
+ <ItemGroup Condition="'$(IsPartialFacadeAssembly)' != 'true'">
<Reference Include="System.Collections" />
<Reference Include="System.Diagnostics.Contracts" />
<Reference Include="System.Diagnostics.Debug" />
@@ -494,11 +496,11 @@
<ItemGroup Condition="'$(TargetsUnix)' == 'true'">
<Reference Include="System.Runtime.Numerics" />
</ItemGroup>
- <ItemGroup Condition="'$(TargetGroup)' == 'netfx'">
+ <ItemGroup Condition="'$(IsPartialFacadeAssembly)' == 'true'">
<Reference Include="mscorlib" />
<Reference Include="System" />
<Reference Include="System.Core" />
<Compile Include="System\Security\Cryptography\IncrementalHash.net46.cs" />
</ItemGroup>
<Import Project="$([MSBuild]::GetDirectoryNameOfFileAbove($(MSBuildThisFileDirectory), dir.targets))\dir.targets" />
-</Project>
+</Project> \ No newline at end of file
diff --git a/src/System.Security.Cryptography.Algorithms/tests/System.Security.Cryptography.Algorithms.Tests.csproj b/src/System.Security.Cryptography.Algorithms/tests/System.Security.Cryptography.Algorithms.Tests.csproj
index 5fca732870..991afac459 100644
--- a/src/System.Security.Cryptography.Algorithms/tests/System.Security.Cryptography.Algorithms.Tests.csproj
+++ b/src/System.Security.Cryptography.Algorithms/tests/System.Security.Cryptography.Algorithms.Tests.csproj
@@ -16,9 +16,6 @@
<DefineConstants>$(DefineConstants);netcoreapp</DefineConstants>
</PropertyGroup>
<ItemGroup>
- <Compile Include="$(CommonTestPath)\System\AssertExtensions.cs">
- <Link>Common\System\AssertExtensions.cs</Link>
- </Compile>
<Compile Include="$(CommonTestPath)\System\PlatformDetection.cs">
<Link>CommonTest\System\PlatformDetection.cs</Link>
</Compile>
diff --git a/src/System.Security.Cryptography.Cng/pkg/System.Security.Cryptography.Cng.pkgproj b/src/System.Security.Cryptography.Cng/pkg/System.Security.Cryptography.Cng.pkgproj
index ae5a48cc7b..31f887a973 100644
--- a/src/System.Security.Cryptography.Cng/pkg/System.Security.Cryptography.Cng.pkgproj
+++ b/src/System.Security.Cryptography.Cng/pkg/System.Security.Cryptography.Cng.pkgproj
@@ -3,7 +3,7 @@
<Import Project="$([MSBuild]::GetDirectoryNameOfFileAbove($(MSBuildThisFileDirectory), dir.props))\dir.props" />
<ItemGroup>
<ProjectReference Include="..\ref\System.Security.Cryptography.Cng.csproj">
- <SupportedFramework>net461;netcoreapp2.0;uap10.1;$(AllXamarinFrameworks)</SupportedFramework>
+ <SupportedFramework>net461;netcoreapp2.0;$(UAPvNextTFM);$(AllXamarinFrameworks)</SupportedFramework>
</ProjectReference>
<ProjectReference Include="..\src\System.Security.Cryptography.Cng.csproj" />
diff --git a/src/System.Security.Cryptography.Cng/tests/System.Security.Cryptography.Cng.Tests.csproj b/src/System.Security.Cryptography.Cng/tests/System.Security.Cryptography.Cng.Tests.csproj
index 341c2746c9..725bc44b6e 100644
--- a/src/System.Security.Cryptography.Cng/tests/System.Security.Cryptography.Cng.Tests.csproj
+++ b/src/System.Security.Cryptography.Cng/tests/System.Security.Cryptography.Cng.Tests.csproj
@@ -25,9 +25,6 @@
<Compile Include="ECDsaCngTests.cs" />
<Compile Include="SymmetricCngTestHelpers.cs" />
<Compile Include="TestData.cs" />
- <Compile Include="$(CommonTestPath)\System\AssertExtensions.cs">
- <Link>Common\System\AssertExtensions.cs</Link>
- </Compile>
</ItemGroup>
<ItemGroup Condition="'$(TargetsWindows)' == 'true'">
<Compile Include="$(CommonTestPath)\System\PlatformDetection.cs">
diff --git a/src/System.Security.Cryptography.Csp/tests/System.Security.Cryptography.Csp.Tests.csproj b/src/System.Security.Cryptography.Csp/tests/System.Security.Cryptography.Csp.Tests.csproj
index 3f0673f558..ba2852e35a 100644
--- a/src/System.Security.Cryptography.Csp/tests/System.Security.Cryptography.Csp.Tests.csproj
+++ b/src/System.Security.Cryptography.Csp/tests/System.Security.Cryptography.Csp.Tests.csproj
@@ -20,9 +20,6 @@
<Compile Include="RSACryptoServiceProviderProvider.cs" />
<Compile Include="RSACryptoServiceProviderTests.cs" />
<Compile Include="ShimHelpers.cs" />
- <Compile Include="$(CommonTestPath)\System\AssertExtensions.cs">
- <Link>Common\System\AssertExtensions.cs</Link>
- </Compile>
<Compile Include="$(CommonTestPath)\System\PlatformDetection.cs">
<Link>Common\System\PlatformDetection.cs</Link>
</Compile>
diff --git a/src/System.Security.Cryptography.Encoding/tests/System.Security.Cryptography.Encoding.Tests.csproj b/src/System.Security.Cryptography.Encoding/tests/System.Security.Cryptography.Encoding.Tests.csproj
index 0d8ba0c6d0..7e1306e3af 100644
--- a/src/System.Security.Cryptography.Encoding/tests/System.Security.Cryptography.Encoding.Tests.csproj
+++ b/src/System.Security.Cryptography.Encoding/tests/System.Security.Cryptography.Encoding.Tests.csproj
@@ -23,9 +23,6 @@
<Compile Include="$(CommonPath)\System\Security\Cryptography\DerSequenceReader.cs">
<Link>Common\System\Security\Cryptography\DerSequenceReader.cs</Link>
</Compile>
- <Compile Include="$(CommonTestPath)\System\AssertExtensions.cs">
- <Link>Common\System\AssertExtensions.cs</Link>
- </Compile>
<Compile Include="$(CommonTestPath)\System\PlatformDetection.cs">
<Link>Common\System\PlatformDetection.cs</Link>
</Compile>
diff --git a/src/System.Security.Cryptography.OpenSsl/tests/System.Security.Cryptography.OpenSsl.Tests.csproj b/src/System.Security.Cryptography.OpenSsl/tests/System.Security.Cryptography.OpenSsl.Tests.csproj
index 278dc3a6f5..b523908332 100644
--- a/src/System.Security.Cryptography.OpenSsl/tests/System.Security.Cryptography.OpenSsl.Tests.csproj
+++ b/src/System.Security.Cryptography.OpenSsl/tests/System.Security.Cryptography.OpenSsl.Tests.csproj
@@ -16,9 +16,6 @@
<Compile Include="$(CommonPath)\Interop\Unix\Interop.Libraries.cs">
<Link>Common\Interop\Unix\Interop.Libraries.cs</Link>
</Compile>
- <Compile Include="$(CommonTestPath)\System\AssertExtensions.cs">
- <Link>Common\System\AssertExtensions.cs</Link>
- </Compile>
<Compile Include="$(CommonTestPath)\System\PlatformDetection.cs">
<Link>CommonTest\System\PlatformDetection.cs</Link>
</Compile>
diff --git a/src/System.Security.Cryptography.Pkcs/tests/System.Security.Cryptography.Pkcs.Tests.csproj b/src/System.Security.Cryptography.Pkcs/tests/System.Security.Cryptography.Pkcs.Tests.csproj
index b93ebb44d0..11e8cd7f7f 100644
--- a/src/System.Security.Cryptography.Pkcs/tests/System.Security.Cryptography.Pkcs.Tests.csproj
+++ b/src/System.Security.Cryptography.Pkcs/tests/System.Security.Cryptography.Pkcs.Tests.csproj
@@ -38,9 +38,6 @@
<Compile Include="Oids.cs" />
<Compile Include="Pkcs9AttributeTests.cs" />
<Compile Include="RecipientInfoCollectionTests.cs" />
- <Compile Include="$(CommonTestPath)\System\AssertExtensions.cs">
- <Link>Common\System\AssertExtensions.cs</Link>
- </Compile>
</ItemGroup>
<ItemGroup Condition="'$(TargetGroup)'=='netcoreapp'">
<Compile Include="EnvelopedCms\DecryptTests.KeyPersistence.cs" />
diff --git a/src/System.Security.Cryptography.Primitives/tests/System.Security.Cryptography.Primitives.Tests.csproj b/src/System.Security.Cryptography.Primitives/tests/System.Security.Cryptography.Primitives.Tests.csproj
index 9490a4224b..8cb9485960 100644
--- a/src/System.Security.Cryptography.Primitives/tests/System.Security.Cryptography.Primitives.Tests.csproj
+++ b/src/System.Security.Cryptography.Primitives/tests/System.Security.Cryptography.Primitives.Tests.csproj
@@ -24,9 +24,6 @@
<Compile Include="$(CommonTestPath)\System\IO\PositionValueStream.cs">
<Link>CommonTest\System\IO\PositionValueStream.cs</Link>
</Compile>
- <Compile Include="$(CommonTestPath)\System\AssertExtensions.cs">
- <Link>Common\System\AssertExtensions.cs</Link>
- </Compile>
<Compile Include="$(CommonTestPath)\System\PlatformDetection.cs">
<Link>CommonTest\System\PlatformDetection.cs</Link>
</Compile>
diff --git a/src/System.Security.Cryptography.X509Certificates/src/Internal/Cryptography/Pal.Unix/OpenSslX509ChainProcessor.cs b/src/System.Security.Cryptography.X509Certificates/src/Internal/Cryptography/Pal.Unix/OpenSslX509ChainProcessor.cs
index 4310913032..02c2247668 100644
--- a/src/System.Security.Cryptography.X509Certificates/src/Internal/Cryptography/Pal.Unix/OpenSslX509ChainProcessor.cs
+++ b/src/System.Security.Cryptography.X509Certificates/src/Internal/Cryptography/Pal.Unix/OpenSslX509ChainProcessor.cs
@@ -302,6 +302,7 @@ namespace Internal.Cryptography.Pal
case Interop.Crypto.X509VerifyStatusCode.X509_V_ERR_CERT_REVOKED:
return X509ChainStatusFlags.Revoked;
+ case Interop.Crypto.X509VerifyStatusCode.X509_V_ERR_UNABLE_TO_DECODE_ISSUER_PUBLIC_KEY:
case Interop.Crypto.X509VerifyStatusCode.X509_V_ERR_CERT_SIGNATURE_FAILURE:
return X509ChainStatusFlags.NotSignatureValid;
diff --git a/src/System.Security.Cryptography.X509Certificates/src/Internal/Cryptography/Pal.Windows/CertificatePal.Import.cs b/src/System.Security.Cryptography.X509Certificates/src/Internal/Cryptography/Pal.Windows/CertificatePal.Import.cs
index 6d7c8064b3..c5aa53f583 100644
--- a/src/System.Security.Cryptography.X509Certificates/src/Internal/Cryptography/Pal.Windows/CertificatePal.Import.cs
+++ b/src/System.Security.Cryptography.X509Certificates/src/Internal/Cryptography/Pal.Windows/CertificatePal.Import.cs
@@ -234,9 +234,6 @@ namespace Internal.Cryptography.Pal
// For .NET Native (UWP) the API used to delete the private key (if it wasn't added to a store) is not
// allowed to be called if the key is stored in CAPI. So for UWP force the key to be stored in the
// CNG Key Storage Provider, then deleting the key with CngKey.Delete will clean up the file on disk, too.
-#if uap
- pfxCertStoreFlags |= PfxCertStoreFlags.PKCS12_ALWAYS_CNG_KSP;
-#endif
return pfxCertStoreFlags;
}
diff --git a/src/System.Security.Cryptography.X509Certificates/src/Internal/Cryptography/Pal.Windows/CertificatePal.PrivateKey.cs b/src/System.Security.Cryptography.X509Certificates/src/Internal/Cryptography/Pal.Windows/CertificatePal.PrivateKey.cs
index 0a16fe7e44..e546d7c9e8 100644
--- a/src/System.Security.Cryptography.X509Certificates/src/Internal/Cryptography/Pal.Windows/CertificatePal.PrivateKey.cs
+++ b/src/System.Security.Cryptography.X509Certificates/src/Internal/Cryptography/Pal.Windows/CertificatePal.PrivateKey.cs
@@ -29,15 +29,7 @@ namespace Internal.Cryptography.Pal
return GetPrivateKey<RSA>(
delegate (CspParameters csp)
{
-#if uap
- // In .NET Native (UWP) we don't have access to CAPI, so it's CNG-or-nothing.
- // But we don't expect to get here, so it shouldn't be a problem.
-
- Debug.Fail("A CAPI provider type code was specified");
- return null;
-#else
return new RSACryptoServiceProvider(csp);
-#endif
},
delegate (CngKey cngKey)
{
@@ -51,15 +43,7 @@ namespace Internal.Cryptography.Pal
return GetPrivateKey<DSA>(
delegate (CspParameters csp)
{
-#if uap
- // In .NET Native (UWP) we don't have access to CAPI, so it's CNG-or-nothing.
- // But we don't expect to get here, so it shouldn't be a problem.
-
- Debug.Fail("A CAPI provider type code was specified");
- return null;
-#else
return new DSACryptoServiceProvider(csp);
-#endif
},
delegate (CngKey cngKey)
{
@@ -215,17 +199,9 @@ namespace Internal.Cryptography.Pal
else
{
// ProviderType being non-zero signifies that this is a CAPI key.
-#if uap
- // In .NET Native (UWP) we don't have access to CAPI, so it's CNG-or-nothing.
- // But we don't expect to get here, so it shouldn't be a problem.
-
- Debug.Fail("A CAPI provider type code was specified");
- return null;
-#else
// We never want to stomp over certificate private keys.
cspParameters.Flags |= CspProviderFlags.UseExistingKey;
return createCsp(cspParameters);
-#endif
}
}
diff --git a/src/System.Security.Cryptography.X509Certificates/src/Internal/Cryptography/Pal.Windows/CertificatePal.cs b/src/System.Security.Cryptography.X509Certificates/src/Internal/Cryptography/Pal.Windows/CertificatePal.cs
index 8856c21a78..2d76ca9b33 100644
--- a/src/System.Security.Cryptography.X509Certificates/src/Internal/Cryptography/Pal.Windows/CertificatePal.cs
+++ b/src/System.Security.Cryptography.X509Certificates/src/Internal/Cryptography/Pal.Windows/CertificatePal.cs
@@ -417,9 +417,6 @@ namespace Internal.Cryptography.Pal
sb.AppendLine();
sb.AppendLine("[Private Key]");
-#if uap
- // Similar to the Unix implementation, in UWP merely acknowledge that there -is- a private key.
-#else
CspKeyContainerInfo cspKeyContainerInfo = null;
try
{
@@ -482,7 +479,6 @@ namespace Internal.Cryptography.Pal
}
catch (CryptographicException) { }
catch (NotSupportedException) { }
-#endif // #if uap / #else
}
public void Dispose()
diff --git a/src/System.Security.Cryptography.X509Certificates/src/Internal/Cryptography/Pal.Windows/Native/Interop.crypt32.cs b/src/System.Security.Cryptography.X509Certificates/src/Internal/Cryptography/Pal.Windows/Native/Interop.crypt32.cs
index 52dc3ac85b..b66c8da43f 100644
--- a/src/System.Security.Cryptography.X509Certificates/src/Internal/Cryptography/Pal.Windows/Native/Interop.crypt32.cs
+++ b/src/System.Security.Cryptography.X509Certificates/src/Internal/Cryptography/Pal.Windows/Native/Interop.crypt32.cs
@@ -297,11 +297,9 @@ internal static partial class Interop
[DllImport(Libraries.Crypt32, CharSet = CharSet.Unicode, SetLastError = true)]
public static extern bool CryptMsgClose(IntPtr hCryptMsg);
-
-#if !uap
+
[DllImport(Libraries.Crypt32, CharSet = CharSet.Unicode, SetLastError = true)]
public static extern unsafe bool CryptImportPublicKeyInfoEx2(CertEncodingType dwCertEncodingType, CERT_PUBLIC_KEY_INFO* pInfo, int dwFlags, void* pvAuxInfo, out SafeBCryptKeyHandle phKey);
-#endif
[DllImport(Libraries.Crypt32, CharSet = CharSet.Unicode, SetLastError = true)]
public static extern bool CryptAcquireCertificatePrivateKey(SafeCertContextHandle pCert, CryptAcquireFlags dwFlags, IntPtr pvParameters, out SafeNCryptKeyHandle phCryptProvOrNCryptKey, out int pdwKeySpec, out bool pfCallerFreeProvOrNCryptKey);
diff --git a/src/System.Security.Cryptography.X509Certificates/src/Internal/Cryptography/Pal.Windows/Native/Interop.cryptoapi.cs b/src/System.Security.Cryptography.X509Certificates/src/Internal/Cryptography/Pal.Windows/Native/Interop.cryptoapi.cs
index 5ea7a05c02..246e1cd19d 100644
--- a/src/System.Security.Cryptography.X509Certificates/src/Internal/Cryptography/Pal.Windows/Native/Interop.cryptoapi.cs
+++ b/src/System.Security.Cryptography.X509Certificates/src/Internal/Cryptography/Pal.Windows/Native/Interop.cryptoapi.cs
@@ -15,11 +15,9 @@ internal static partial class Interop
{
public static partial class cryptoapi
{
-#if !uap
[DllImport(Libraries.Advapi32, SetLastError = true, CharSet = CharSet.Unicode, EntryPoint = "CryptAcquireContextW")]
[return: MarshalAs(UnmanagedType.Bool)]
public static extern unsafe bool CryptAcquireContext(out IntPtr psafeProvHandle, char* pszContainer, char* pszProvider, int dwProvType, CryptAcquireContextFlags dwFlags);
-#endif
}
}
diff --git a/src/System.Security.Cryptography.X509Certificates/src/Internal/Cryptography/Pal.Windows/Native/SafeHandles.cs b/src/System.Security.Cryptography.X509Certificates/src/Internal/Cryptography/Pal.Windows/Native/SafeHandles.cs
index 2c76c50d8b..c12344f753 100644
--- a/src/System.Security.Cryptography.X509Certificates/src/Internal/Cryptography/Pal.Windows/Native/SafeHandles.cs
+++ b/src/System.Security.Cryptography.X509Certificates/src/Internal/Cryptography/Pal.Windows/Native/SafeHandles.cs
@@ -183,7 +183,6 @@ namespace Internal.Cryptography.Pal.Native
}
else
{
-#if !uap // For UWP, CryptAcquireContext() is a disallowed api, even when being used for cleanup. CAPI keys should not exist on that platform, however...
CryptAcquireContextFlags flags = (pProvInfo->dwFlags & CryptAcquireContextFlags.CRYPT_MACHINE_KEYSET) | CryptAcquireContextFlags.CRYPT_DELETEKEYSET;
IntPtr hProv;
bool success = Interop.cryptoapi.CryptAcquireContext(out hProv, pProvInfo->pwszContainerName, pProvInfo->pwszProvName, pProvInfo->dwProvType, flags);
@@ -191,7 +190,6 @@ namespace Internal.Cryptography.Pal.Native
// Called CryptAcquireContext solely for the side effect of deleting the key containers. When called with these flags, no actual
// hProv is returned (so there's nothing to clean up.)
Debug.Assert(hProv == IntPtr.Zero);
-#endif
}
}
}
diff --git a/src/System.Security.Cryptography.X509Certificates/src/Internal/Cryptography/Pal.Windows/X509Pal.PublicKey.cs b/src/System.Security.Cryptography.X509Certificates/src/Internal/Cryptography/Pal.Windows/X509Pal.PublicKey.cs
index 103d7aea70..1dfa2171a7 100644
--- a/src/System.Security.Cryptography.X509Certificates/src/Internal/Cryptography/Pal.Windows/X509Pal.PublicKey.cs
+++ b/src/System.Security.Cryptography.X509Certificates/src/Internal/Cryptography/Pal.Windows/X509Pal.PublicKey.cs
@@ -42,8 +42,6 @@ namespace Internal.Cryptography.Pal
CngKey cngKey = CngKey.Import(keyBlob, CngKeyBlobFormat.GenericPublicBlob);
return new RSACng(cngKey);
}
-
-#if !uap
case AlgId.CALG_DSS_SIGN:
{
byte[] keyBlob = ConstructDSSPublicKeyCspBlob(encodedKeyValue, encodedParameters);
@@ -51,8 +49,6 @@ namespace Internal.Cryptography.Pal
dsa.ImportCspBlob(keyBlob);
return dsa;
}
-#endif
-
default:
throw new NotSupportedException(SR.NotSupported_KeyAlgorithm);
}
@@ -65,14 +61,6 @@ namespace Internal.Cryptography.Pal
{
CngKeyBlobFormat blobFormat;
byte[] keyBlob;
-#if uap
- blobFormat = CngKeyBlobFormat.EccPublicBlob;
- keyBlob = ExportKeyBlob(bCryptKeyHandle, blobFormat);
- using (CngKey cngKey = CngKey.Import(keyBlob, blobFormat))
- {
- ecdsa = new ECDsaCng(cngKey);
- }
-#else
string curveName = GetCurveName(bCryptKeyHandle);
if (curveName == null)
@@ -102,7 +90,6 @@ namespace Internal.Cryptography.Pal
ecdsa = new ECDsaCng();
ecdsa.ImportParameters(ecparams);
}
-#endif
}
return ecdsa;
@@ -110,10 +97,6 @@ namespace Internal.Cryptography.Pal
private static SafeBCryptKeyHandle ImportPublicKeyInfo(SafeCertContextHandle certContext)
{
-#if uap
- // CryptImportPublicKeyInfoEx2() not in the UWP api list.
- throw new PlatformNotSupportedException();
-#else
unsafe
{
SafeBCryptKeyHandle bCryptKeyHandle;
@@ -135,15 +118,10 @@ namespace Internal.Cryptography.Pal
certContext.DangerousRelease();
}
}
-#endif // uap
}
private static byte[] ExportKeyBlob(SafeBCryptKeyHandle bCryptKeyHandle, CngKeyBlobFormat blobFormat)
{
-#if uap
- // BCryptExportKey() not in the UWP api list.
- throw new PlatformNotSupportedException();
-#else
string blobFormatString = blobFormat.Format;
int numBytesNeeded = 0;
@@ -158,10 +136,8 @@ namespace Internal.Cryptography.Pal
Array.Resize(ref keyBlob, numBytesNeeded);
return keyBlob;
-#endif // uap
}
-
-#if !uap
+
private static void ExportNamedCurveParameters(ref ECParameters ecParams, byte[] ecBlob, bool includePrivateParameters)
{
// We now have a buffer laid out as follows:
@@ -194,7 +170,6 @@ namespace Internal.Cryptography.Pal
}
}
}
-#endif
private static byte[] DecodeKeyBlob(CryptDecodeObjectStructType lpszStructType, byte[] encodedKeyValue)
{
diff --git a/src/System.Security.Cryptography.X509Certificates/src/System.Security.Cryptography.X509Certificates.csproj b/src/System.Security.Cryptography.X509Certificates/src/System.Security.Cryptography.X509Certificates.csproj
index c45f5a7975..c235728e73 100644
--- a/src/System.Security.Cryptography.X509Certificates/src/System.Security.Cryptography.X509Certificates.csproj
+++ b/src/System.Security.Cryptography.X509Certificates/src/System.Security.Cryptography.X509Certificates.csproj
@@ -6,7 +6,6 @@
<OutputType>Library</OutputType>
<AssemblyName>System.Security.Cryptography.X509Certificates</AssemblyName>
<AllowUnsafeBlocks>true</AllowUnsafeBlocks>
- <DefineConstants Condition="'$(TargetGroup)' == 'uap'">$(DefineConstants);uap</DefineConstants>
</PropertyGroup>
<PropertyGroup Condition="'$(Configuration)|$(Platform)' == 'netcoreapp-OSX-Debug|AnyCPU'" />
<PropertyGroup Condition="'$(Configuration)|$(Platform)' == 'netcoreapp-OSX-Release|AnyCPU'" />
diff --git a/src/System.Security.Cryptography.X509Certificates/tests/Cert.cs b/src/System.Security.Cryptography.X509Certificates/tests/Cert.cs
index 5f180b0d78..49e6e7cfc6 100644
--- a/src/System.Security.Cryptography.X509Certificates/tests/Cert.cs
+++ b/src/System.Security.Cryptography.X509Certificates/tests/Cert.cs
@@ -17,9 +17,7 @@ namespace System.Security.Cryptography.X509Certificates.Tests
// netcoreapp-OSX: DefaultKeySet
// netcoreapp-other: EphemeralKeySet
internal static readonly X509KeyStorageFlags EphemeralIfPossible =
-#if netcoreapp
!RuntimeInformation.IsOSPlatform(OSPlatform.OSX) ? X509KeyStorageFlags.EphemeralKeySet :
-#endif
X509KeyStorageFlags.DefaultKeySet;
//
// The Import() methods have an overload for each X509Certificate2Collection.Import() overload.
diff --git a/src/System.Security.Cryptography.X509Certificates/tests/CertTests.cs b/src/System.Security.Cryptography.X509Certificates/tests/CertTests.cs
index 84c488ef75..6e007f1ca4 100644
--- a/src/System.Security.Cryptography.X509Certificates/tests/CertTests.cs
+++ b/src/System.Security.Cryptography.X509Certificates/tests/CertTests.cs
@@ -114,15 +114,20 @@ namespace System.Security.Cryptography.X509Certificates.Tests
Assert.True(success, "MicrosoftDotComIssuerBytes");
}
- using (var microsoftDotComRoot = new X509Certificate2(TestData.MicrosoftDotComRootBytes))
+ // High Sierra fails to build a chain for a self-signed certificate with revocation enabled.
+ // https://github.com/dotnet/corefx/issues/21875
+ if (!PlatformDetection.IsMacOsHighSierra)
{
- // NotAfter=7/17/2036
- success = microsoftDotComRoot.Verify();
- if (!success)
+ using (var microsoftDotComRoot = new X509Certificate2(TestData.MicrosoftDotComRootBytes))
{
- LogVerifyErrors(microsoftDotComRoot, "MicrosoftDotComRootBytes");
+ // NotAfter=7/17/2036
+ success = microsoftDotComRoot.Verify();
+ if (!success)
+ {
+ LogVerifyErrors(microsoftDotComRoot, "MicrosoftDotComRootBytes");
+ }
+ Assert.True(success, "MicrosoftDotComRootBytes");
}
- Assert.True(success, "MicrosoftDotComRootBytes");
}
}
diff --git a/src/System.Security.Cryptography.X509Certificates/tests/CertificateCreation/CertificateRequestApiTests.cs b/src/System.Security.Cryptography.X509Certificates/tests/CertificateCreation/CertificateRequestApiTests.cs
index 988f14866d..b08677b60a 100644
--- a/src/System.Security.Cryptography.X509Certificates/tests/CertificateCreation/CertificateRequestApiTests.cs
+++ b/src/System.Security.Cryptography.X509Certificates/tests/CertificateCreation/CertificateRequestApiTests.cs
@@ -62,7 +62,7 @@ namespace System.Security.Cryptography.X509Certificates.Tests.CertificateCreatio
HashAlgorithmName.SHA256,
RSASignaturePadding.Pkcs1);
- Assert.Throws<ArgumentNullException>(
+ AssertExtensions.Throws<ArgumentNullException>(
"generator",
() => request.Create(testRoot.SubjectName, null, DateTimeOffset.MinValue, DateTimeOffset.MinValue, null));
@@ -90,13 +90,13 @@ namespace System.Security.Cryptography.X509Certificates.Tests.CertificateCreatio
ECDsa key = null;
HashAlgorithmName hashAlgorithm = default(HashAlgorithmName);
- Assert.Throws<ArgumentNullException>(
+ AssertExtensions.Throws<ArgumentNullException>(
"subjectName",
() => new CertificateRequest(subjectName, key, hashAlgorithm));
subjectName = "";
- Assert.Throws<ArgumentNullException>(
+ AssertExtensions.Throws<ArgumentNullException>(
"key",
() => new CertificateRequest(subjectName, key, hashAlgorithm));
@@ -117,13 +117,13 @@ namespace System.Security.Cryptography.X509Certificates.Tests.CertificateCreatio
ECDsa key = null;
HashAlgorithmName hashAlgorithm = default(HashAlgorithmName);
- Assert.Throws<ArgumentNullException>(
+ AssertExtensions.Throws<ArgumentNullException>(
"subjectName",
() => new CertificateRequest(subjectName, key, hashAlgorithm));
subjectName = new X500DistinguishedName("");
- Assert.Throws<ArgumentNullException>(
+ AssertExtensions.Throws<ArgumentNullException>(
"key",
() => new CertificateRequest(subjectName, key, hashAlgorithm));
@@ -145,13 +145,13 @@ namespace System.Security.Cryptography.X509Certificates.Tests.CertificateCreatio
HashAlgorithmName hashAlgorithm = default(HashAlgorithmName);
RSASignaturePadding padding = null;
- Assert.Throws<ArgumentNullException>(
+ AssertExtensions.Throws<ArgumentNullException>(
"subjectName",
() => new CertificateRequest(subjectName, key, hashAlgorithm, padding));
subjectName = "";
- Assert.Throws<ArgumentNullException>(
+ AssertExtensions.Throws<ArgumentNullException>(
"key",
() => new CertificateRequest(subjectName, key, hashAlgorithm, padding));
@@ -165,7 +165,7 @@ namespace System.Security.Cryptography.X509Certificates.Tests.CertificateCreatio
hashAlgorithm = HashAlgorithmName.SHA256;
- Assert.Throws<ArgumentNullException>(
+ AssertExtensions.Throws<ArgumentNullException>(
"padding",
() => new CertificateRequest(subjectName, key, hashAlgorithm, padding));
}
@@ -179,13 +179,13 @@ namespace System.Security.Cryptography.X509Certificates.Tests.CertificateCreatio
HashAlgorithmName hashAlgorithm = default(HashAlgorithmName);
RSASignaturePadding padding = null;
- Assert.Throws<ArgumentNullException>(
+ AssertExtensions.Throws<ArgumentNullException>(
"subjectName",
() => new CertificateRequest(subjectName, key, hashAlgorithm, padding));
subjectName = new X500DistinguishedName("");
- Assert.Throws<ArgumentNullException>(
+ AssertExtensions.Throws<ArgumentNullException>(
"key",
() => new CertificateRequest(subjectName, key, hashAlgorithm, padding));
@@ -199,7 +199,7 @@ namespace System.Security.Cryptography.X509Certificates.Tests.CertificateCreatio
hashAlgorithm = HashAlgorithmName.SHA256;
- Assert.Throws<ArgumentNullException>(
+ AssertExtensions.Throws<ArgumentNullException>(
"padding",
() => new CertificateRequest(subjectName, key, hashAlgorithm, padding));
}
@@ -212,13 +212,13 @@ namespace System.Security.Cryptography.X509Certificates.Tests.CertificateCreatio
PublicKey publicKey = null;
HashAlgorithmName hashAlgorithm = default(HashAlgorithmName);
- Assert.Throws<ArgumentNullException>(
+ AssertExtensions.Throws<ArgumentNullException>(
"subjectName",
() => new CertificateRequest(subjectName, publicKey, hashAlgorithm));
subjectName = new X500DistinguishedName("");
- Assert.Throws<ArgumentNullException>(
+ AssertExtensions.Throws<ArgumentNullException>(
"publicKey",
() => new CertificateRequest(subjectName, publicKey, hashAlgorithm));
diff --git a/src/System.Security.Cryptography.X509Certificates/tests/CertificateCreation/CertificateRequestChainTests.cs b/src/System.Security.Cryptography.X509Certificates/tests/CertificateCreation/CertificateRequestChainTests.cs
index 95ee8af793..61ce09f442 100644
--- a/src/System.Security.Cryptography.X509Certificates/tests/CertificateCreation/CertificateRequestChainTests.cs
+++ b/src/System.Security.Cryptography.X509Certificates/tests/CertificateCreation/CertificateRequestChainTests.cs
@@ -179,6 +179,7 @@ namespace System.Security.Cryptography.X509Certificates.Tests.CertificateCreatio
chain.ChainPolicy.RevocationMode = X509RevocationMode.NoCheck;
chain.ChainPolicy.VerificationFlags = X509VerificationFlags.AllowUnknownCertificateAuthority;
chain.ChainPolicy.ExtraStore.Add(rootCert);
+ chain.ChainPolicy.VerificationTime = start.ToLocalTime().DateTime;
if (useIntermed)
{
@@ -426,6 +427,7 @@ namespace System.Security.Cryptography.X509Certificates.Tests.CertificateCreatio
chain.ChainPolicy.ExtraStore.Add(intermed1CertWithKey);
chain.ChainPolicy.ExtraStore.Add(intermed2CertWithKey);
chain.ChainPolicy.ExtraStore.Add(rootCertWithKey);
+ chain.ChainPolicy.VerificationTime = now.ToLocalTime().DateTime;
RunChain(chain, leafCert, true, "Initial chain build");
@@ -511,6 +513,7 @@ namespace System.Security.Cryptography.X509Certificates.Tests.CertificateCreatio
chain.ChainPolicy.VerificationFlags = X509VerificationFlags.AllowUnknownCertificateAuthority;
chain.ChainPolicy.ExtraStore.Add(intermedCertWithKey);
chain.ChainPolicy.ExtraStore.Add(rootCertWithKey);
+ chain.ChainPolicy.VerificationTime = notBefore.ToLocalTime().DateTime;
RunChain(chain, leafCert, true, "Chain build");
}
diff --git a/src/System.Security.Cryptography.X509Certificates/tests/CertificateCreation/CertificateRequestUsageTests.cs b/src/System.Security.Cryptography.X509Certificates/tests/CertificateCreation/CertificateRequestUsageTests.cs
index 10d237f33e..1f0d2855ad 100644
--- a/src/System.Security.Cryptography.X509Certificates/tests/CertificateCreation/CertificateRequestUsageTests.cs
+++ b/src/System.Security.Cryptography.X509Certificates/tests/CertificateCreation/CertificateRequestUsageTests.cs
@@ -519,11 +519,12 @@ namespace System.Security.Cryptography.X509Certificates.Tests.CertificateCreatio
Exception exception = Assert.Throws<CryptographicException>(
() =>
request.Create(request.SubjectName, generator, now, now.AddDays(1), new byte[1]));
-
+#if netcoreapp
if (CultureInfo.CurrentCulture.Name == "en-US")
{
Assert.Contains("ASN1", exception.Message);
}
+#endif
}
[Fact]
diff --git a/src/System.Security.Cryptography.X509Certificates/tests/CertificateCreation/ECDsaX509SignatureGeneratorTests.cs b/src/System.Security.Cryptography.X509Certificates/tests/CertificateCreation/ECDsaX509SignatureGeneratorTests.cs
index 5b4e664fd1..bb57abd8f3 100644
--- a/src/System.Security.Cryptography.X509Certificates/tests/CertificateCreation/ECDsaX509SignatureGeneratorTests.cs
+++ b/src/System.Security.Cryptography.X509Certificates/tests/CertificateCreation/ECDsaX509SignatureGeneratorTests.cs
@@ -14,7 +14,7 @@ namespace System.Security.Cryptography.X509Certificates.Tests.CertificateCreatio
[Fact]
public static void ECDsaX509SignatureGeneratorCtor_Exceptions()
{
- Assert.Throws<ArgumentNullException>(
+ AssertExtensions.Throws<ArgumentNullException>(
"key",
() => X509SignatureGenerator.CreateForECDsa(null));
}
diff --git a/src/System.Security.Cryptography.X509Certificates/tests/CertificateCreation/RSAPkcs1X509SignatureGeneratorTests.cs b/src/System.Security.Cryptography.X509Certificates/tests/CertificateCreation/RSAPkcs1X509SignatureGeneratorTests.cs
index 5fe946fa0d..59869e9470 100644
--- a/src/System.Security.Cryptography.X509Certificates/tests/CertificateCreation/RSAPkcs1X509SignatureGeneratorTests.cs
+++ b/src/System.Security.Cryptography.X509Certificates/tests/CertificateCreation/RSAPkcs1X509SignatureGeneratorTests.cs
@@ -12,7 +12,7 @@ namespace System.Security.Cryptography.X509Certificates.Tests.CertificateCreatio
[Fact]
public static void RsaPkcsSignatureGeneratorCtor_Exceptions()
{
- Assert.Throws<ArgumentNullException>(
+ AssertExtensions.Throws<ArgumentNullException>(
"key",
() => X509SignatureGenerator.CreateForRSA(null, RSASignaturePadding.Pkcs1));
}
diff --git a/src/System.Security.Cryptography.X509Certificates/tests/CertificateCreation/RSAPssX509SignatureGeneratorTests.cs b/src/System.Security.Cryptography.X509Certificates/tests/CertificateCreation/RSAPssX509SignatureGeneratorTests.cs
index f52110372c..500c6ef615 100644
--- a/src/System.Security.Cryptography.X509Certificates/tests/CertificateCreation/RSAPssX509SignatureGeneratorTests.cs
+++ b/src/System.Security.Cryptography.X509Certificates/tests/CertificateCreation/RSAPssX509SignatureGeneratorTests.cs
@@ -12,7 +12,7 @@ namespace System.Security.Cryptography.X509Certificates.Tests.CertificateCreatio
[Fact]
public static void RsaPssSignatureGeneratorCtor_Exceptions()
{
- Assert.Throws<ArgumentNullException>(
+ AssertExtensions.Throws<ArgumentNullException>(
"key",
() => X509SignatureGenerator.CreateForRSA(null, RSASignaturePadding.Pss));
}
diff --git a/src/System.Security.Cryptography.X509Certificates/tests/ChainTests.cs b/src/System.Security.Cryptography.X509Certificates/tests/ChainTests.cs
index d0c1947c3f..3d1d44ec5a 100644
--- a/src/System.Security.Cryptography.X509Certificates/tests/ChainTests.cs
+++ b/src/System.Security.Cryptography.X509Certificates/tests/ChainTests.cs
@@ -14,6 +14,7 @@ namespace System.Security.Cryptography.X509Certificates.Tests
public static class ChainTests
{
internal static bool CanModifyStores { get; } = TestEnvironmentConfiguration.CanModifyStores;
+ internal static bool CanBuildSelfSignedChainReliably { get; } = !PlatformDetection.IsMacOsHighSierra;
private static bool TrustsMicrosoftDotComRoot
{
@@ -164,9 +165,7 @@ namespace System.Security.Cryptography.X509Certificates.Tests
Assert.Equal(IntPtr.Zero, chain.ChainContext);
}
- [Fact]
- // Crashing on macOS 10.13 Beta
- [ActiveIssue(21436, TestPlatforms.OSX)]
+ [ConditionalFact(nameof(CanBuildSelfSignedChainReliably))]
public static void TestResetMethod()
{
using (var sampleCert = new X509Certificate2(TestData.DssCer))
@@ -583,6 +582,7 @@ namespace System.Security.Cryptography.X509Certificates.Tests
else if (!valid)
{
Console.WriteLine($"SKIP [{nameof(VerifyWithRevocation)}]: Chain failed to build within {RetryLimit} tries.");
+ return;
}
// Since the network was enabled, we should get the whole chain.
diff --git a/src/System.Security.Cryptography.X509Certificates/tests/CollectionImportTests.cs b/src/System.Security.Cryptography.X509Certificates/tests/CollectionImportTests.cs
index 02c43c6dc1..56a0f1e411 100644
--- a/src/System.Security.Cryptography.X509Certificates/tests/CollectionImportTests.cs
+++ b/src/System.Security.Cryptography.X509Certificates/tests/CollectionImportTests.cs
@@ -310,22 +310,6 @@ namespace System.Security.Cryptography.X509Certificates.Tests
}
}
-#if netcoreapp11
- [Fact]
- [PlatformSpecific(TestPlatforms.OSX)]
- public static void EphemeralKeySet_OSX()
- {
- // EphemeralKeySet fails when loading a PFX, and is ignored otherwise.
- using (ImportedCollection coll = Cert.Import(TestData.Pkcs7ChainDerBytes, null, X509KeyStorageFlags.EphemeralKeySet))
- {
- Assert.Equal(3, coll.Collection.Count);
- }
-
- Assert.Throws<PlatformNotSupportedException>(
- () => new X509Certificate2(TestData.EmptyPfx, string.Empty, X509KeyStorageFlags.EphemeralKeySet));
- }
-#endif
-
[Fact]
public static void InvalidStorageFlags()
{
@@ -343,8 +327,7 @@ namespace System.Security.Cryptography.X509Certificates.Tests
// No test is performed here for the ephemeral flag failing downlevel, because the live
// binary is always used by default, meaning it doesn't know EphemeralKeySet doesn't exist.
}
-
-#if netcoreapp
+
[Fact]
public static void InvalidStorageFlags_PersistedEphemeral()
{
@@ -362,18 +345,14 @@ namespace System.Security.Cryptography.X509Certificates.Tests
"keyStorageFlags",
() => coll.Import(string.Empty, string.Empty, PersistedEphemeral));
}
-#endif
public static IEnumerable<object[]> StorageFlags
{
get
{
yield return new object[] { X509KeyStorageFlags.DefaultKeySet };
-
-#if netcoreapp
if (!RuntimeInformation.IsOSPlatform(OSPlatform.OSX))
yield return new object[] { X509KeyStorageFlags.EphemeralKeySet };
-#endif
}
}
diff --git a/src/System.Security.Cryptography.X509Certificates/tests/CollectionTests.cs b/src/System.Security.Cryptography.X509Certificates/tests/CollectionTests.cs
index 56dee9af45..7530010331 100644
--- a/src/System.Security.Cryptography.X509Certificates/tests/CollectionTests.cs
+++ b/src/System.Security.Cryptography.X509Certificates/tests/CollectionTests.cs
@@ -653,14 +653,12 @@ namespace System.Security.Cryptography.X509Certificates.Tests
{
TestExportSingleCert(X509ContentType.Cert);
}
-
-#if netcoreapp
+
[Fact]
public static void ExportCert_SecureString()
{
TestExportSingleCert_SecureStringPassword(X509ContentType.Cert);
}
-#endif
[Fact]
[PlatformSpecific(TestPlatforms.Windows)] // SerializedCert not supported on Unix
@@ -912,6 +910,7 @@ namespace System.Security.Cryptography.X509Certificates.Tests
}
[Fact]
+ [SkipOnTargetFramework(TargetFrameworkMonikers.Uap, "Arrays with non-zero lower bounds are not supported.")]
public static void X509ExtensionCollection_CopyTo_NonZeroLowerBound_ThrowsIndexOutOfRangeException()
{
using (X509Certificate2 cert = new X509Certificate2(TestData.PfxData, TestData.PfxDataPassword, Cert.EphemeralIfPossible))
@@ -1405,8 +1404,7 @@ namespace System.Security.Cryptography.X509Certificates.Tests
Assert.Null(byFriendlyName);
}
}
-
-#if netcoreapp
+
private static void TestExportSingleCert_SecureStringPassword(X509ContentType ct)
{
using (var pfxCer = new X509Certificate2(TestData.PfxData, TestData.CreatePfxDataPasswordSecureString(), Cert.EphemeralIfPossible))
@@ -1414,7 +1412,6 @@ namespace System.Security.Cryptography.X509Certificates.Tests
TestExportSingleCert(ct, pfxCer);
}
}
-#endif
private static void TestExportSingleCert(X509ContentType ct)
{
diff --git a/src/System.Security.Cryptography.X509Certificates/tests/Configurations.props b/src/System.Security.Cryptography.X509Certificates/tests/Configurations.props
index 8c2fedd2ad..05d3ab66c3 100644
--- a/src/System.Security.Cryptography.X509Certificates/tests/Configurations.props
+++ b/src/System.Security.Cryptography.X509Certificates/tests/Configurations.props
@@ -5,6 +5,7 @@
netcoreapp-OSX;
netcoreapp-Unix;
netcoreapp-Windows_NT;
+ uap-Windows_NT;
</BuildConfigurations>
</PropertyGroup>
</Project>
diff --git a/src/System.Security.Cryptography.X509Certificates/tests/CtorTests.cs b/src/System.Security.Cryptography.X509Certificates/tests/CtorTests.cs
index 41717fd580..c35c454d1d 100644
--- a/src/System.Security.Cryptography.X509Certificates/tests/CtorTests.cs
+++ b/src/System.Security.Cryptography.X509Certificates/tests/CtorTests.cs
@@ -409,8 +409,7 @@ namespace System.Security.Cryptography.X509Certificates.Tests
// No test is performed here for the ephemeral flag failing downlevel, because the live
// binary is always used by default, meaning it doesn't know EphemeralKeySet doesn't exist.
}
-
-#if netcoreapp
+
[Fact]
public static void InvalidStorageFlags_PersistedEphemeral()
{
@@ -435,6 +434,5 @@ namespace System.Security.Cryptography.X509Certificates.Tests
"keyStorageFlags",
() => new X509Certificate2(string.Empty, string.Empty, PersistedEphemeral));
}
-#endif
}
}
diff --git a/src/System.Security.Cryptography.X509Certificates/tests/PfxTests.cs b/src/System.Security.Cryptography.X509Certificates/tests/PfxTests.cs
index d65a4ef5d7..f38308ddcd 100644
--- a/src/System.Security.Cryptography.X509Certificates/tests/PfxTests.cs
+++ b/src/System.Security.Cryptography.X509Certificates/tests/PfxTests.cs
@@ -15,12 +15,8 @@ namespace System.Security.Cryptography.X509Certificates.Tests
{
get
{
-#if uap
- yield break;
-#else
yield return new object[] { TestData.ECDsabrainpoolP160r1_Pfx };
yield return new object[] { TestData.ECDsabrainpoolP160r1_Explicit_Pfx };
-#endif
}
}
@@ -38,8 +34,7 @@ namespace System.Security.Cryptography.X509Certificates.Tests
Assert.Equal(expectedThumbprint, thumbPrint);
}
}
-
-#if netcoreapp
+
[Theory]
[MemberData(nameof(StorageFlags))]
public static void TestConstructor_SecureString(X509KeyStorageFlags keyStorageFlags)
@@ -55,7 +50,6 @@ namespace System.Security.Cryptography.X509Certificates.Tests
Assert.Equal(expectedThumbprint, thumbPrint);
}
}
-#endif
[Theory]
[MemberData(nameof(StorageFlags))]
@@ -119,8 +113,7 @@ namespace System.Security.Cryptography.X509Certificates.Tests
}
}
}
-
-#if netcoreapp
+
[Fact]
public static void TestPrivateKeyProperty()
{
@@ -140,7 +133,6 @@ namespace System.Security.Cryptography.X509Certificates.Tests
Assert.Throws<PlatformNotSupportedException>(() => c.PrivateKey = alg);
}
}
-#endif
private static void VerifyPrivateKey(RSA rsa)
{
@@ -179,8 +171,7 @@ namespace System.Security.Cryptography.X509Certificates.Tests
}
}
}
-
-#if netcoreapp
+
[Fact]
public static void ECDsaPrivateKeyProperty_WindowsPfx()
{
@@ -225,7 +216,6 @@ namespace System.Security.Cryptography.X509Certificates.Tests
Assert.False(dsa.VerifyData(data, sig, HashAlgorithmName.SHA1), "Key verifies tampered data signature");
}
}
-#endif
private static void Verify_ECDsaPrivateKey_WindowsPfx(ECDsa ecdsa)
{
@@ -289,8 +279,7 @@ namespace System.Security.Cryptography.X509Certificates.Tests
}
}
}
-
-#if netcoreapp
+
[Fact]
public static void ReadDSAPrivateKey()
{
@@ -360,7 +349,6 @@ namespace System.Security.Cryptography.X509Certificates.Tests
}
}
}
-#endif
[Fact]
[PlatformSpecific(TestPlatforms.Windows)] // Uses P/Invokes
diff --git a/src/System.Security.Cryptography.X509Certificates/tests/PublicKeyTests.cs b/src/System.Security.Cryptography.X509Certificates/tests/PublicKeyTests.cs
index 91536cd354..60c7e2b427 100644
--- a/src/System.Security.Cryptography.X509Certificates/tests/PublicKeyTests.cs
+++ b/src/System.Security.Cryptography.X509Certificates/tests/PublicKeyTests.cs
@@ -44,9 +44,6 @@ namespace System.Security.Cryptography.X509Certificates.Tests
{
get
{
-#if uap
- yield break;
-#else
yield return new object[] {
TestData.ECDsabrainpoolP160r1_CertificatePemBytes,
"9145C79DD4DF758EB377D13B0DB81F83CE1A63A4099DDC32FE228B06EB1F306423ED61B6B4AF4691".HexToByteArray() };
@@ -54,7 +51,6 @@ namespace System.Security.Cryptography.X509Certificates.Tests
yield return new object[] {
TestData.ECDsabrainpoolP160r1_ExplicitCertificatePemBytes,
"6D74F1C9BCBBA5A25F67E670B3DABDB36C24E8FAC3266847EB2EE7E3239208ADC696BB421AB380B4".HexToByteArray() };
-#endif
}
}
@@ -478,8 +474,7 @@ namespace System.Security.Cryptography.X509Certificates.Tests
}
}
}
-
-#if netcoreapp
+
[Fact]
public static void TestDSAPublicKey()
{
@@ -529,7 +524,6 @@ namespace System.Security.Cryptography.X509Certificates.Tests
Assert.Null(pubKey);
}
}
-#endif
[Fact]
[PlatformSpecific(TestPlatforms.Windows)] // Uses P/Invokes
@@ -564,7 +558,6 @@ namespace System.Security.Cryptography.X509Certificates.Tests
private static void TestKey_ECDsaCng(byte[] certBytes, TestData.ECDsaCngKeyValues expected)
{
-#if !uap
using (X509Certificate2 cert = new X509Certificate2(certBytes))
{
ECDsaCng e = (ECDsaCng)(cert.GetECDsaPublicKey());
@@ -582,7 +575,6 @@ namespace System.Security.Cryptography.X509Certificates.Tests
Assert.Equal<byte>(expected.QY, qy);
}
}
-#endif // !uap
}
}
}
diff --git a/src/System.Security.Cryptography.X509Certificates/tests/System.Security.Cryptography.X509Certificates.Tests.csproj b/src/System.Security.Cryptography.X509Certificates/tests/System.Security.Cryptography.X509Certificates.Tests.csproj
index 9a1fae43b1..8cc4d7f105 100644
--- a/src/System.Security.Cryptography.X509Certificates/tests/System.Security.Cryptography.X509Certificates.Tests.csproj
+++ b/src/System.Security.Cryptography.X509Certificates/tests/System.Security.Cryptography.X509Certificates.Tests.csproj
@@ -5,6 +5,7 @@
<ProjectGuid>{A28B0064-EFB2-4B77-B97C-DECF5DAB074E}</ProjectGuid>
<AllowUnsafeBlocks>true</AllowUnsafeBlocks>
<DefineConstants Condition="'$(TargetGroup)'=='netcoreapp'">$(DefineConstants);netcoreapp</DefineConstants>
+ <ILCBuildType Condition="'$(TargetGroup)' == 'uap'">chk</ILCBuildType>
</PropertyGroup>
<PropertyGroup Condition="'$(Configuration)|$(Platform)' == 'netcoreapp-OSX-Debug|AnyCPU'" />
<PropertyGroup Condition="'$(Configuration)|$(Platform)' == 'netcoreapp-OSX-Release|AnyCPU'" />
@@ -12,6 +13,8 @@
<PropertyGroup Condition="'$(Configuration)|$(Platform)' == 'netcoreapp-Unix-Release|AnyCPU'" />
<PropertyGroup Condition="'$(Configuration)|$(Platform)' == 'netcoreapp-Windows_NT-Debug|AnyCPU'" />
<PropertyGroup Condition="'$(Configuration)|$(Platform)' == 'netcoreapp-Windows_NT-Release|AnyCPU'" />
+ <PropertyGroup Condition="'$(Configuration)|$(Platform)' == 'uap-Windows_NT-Debug|AnyCPU'" />
+ <PropertyGroup Condition="'$(Configuration)|$(Platform)' == 'uap-Windows_NT-Release|AnyCPU'" />
<ItemGroup>
<Compile Include="Cert.cs" />
<Compile Include="CertificateCreation\CertificateRequestApiTests.cs" />
@@ -49,17 +52,12 @@
<Compile Include="X500DistinguishedNameTests.cs" />
<Compile Include="X509StoreMutableTests.OSX.cs" />
<Compile Include="X509StoreTests.cs" />
- <Compile Include="$(CommonTestPath)\System\AssertExtensions.cs">
- <Link>Common\System\AssertExtensions.cs</Link>
- </Compile>
<Compile Include="$(CommonTestPath)\System\Security\Cryptography\ByteUtils.cs">
<Link>CommonTest\System\Security\Cryptography\ByteUtils.cs</Link>
</Compile>
<Compile Include="$(CommonTestPath)\System\PlatformDetection.cs">
<Link>CommonTest\System\PlatformDetection.cs</Link>
</Compile>
- </ItemGroup>
- <ItemGroup Condition="'$(TargetGroup)'=='netstandard' OR '$(TargetGroup)'=='netcoreapp'">
<Compile Include="ImportTests.cs" />
<Compile Include="$(CommonTestPath)\System\Runtime\Serialization\Formatters\BinaryFormatterHelpers.cs">
<Link>Common\System\Runtime\Serialization\Formatters\BinaryFormatterHelpers.cs</Link>
diff --git a/src/System.Security.Cryptography.Xml/src/System/Security/Cryptography/Xml/CryptoHelpers.cs b/src/System.Security.Cryptography.Xml/src/System/Security/Cryptography/Xml/CryptoHelpers.cs
index a5bd594bf3..a857475d3e 100644
--- a/src/System.Security.Cryptography.Xml/src/System/Security/Cryptography/Xml/CryptoHelpers.cs
+++ b/src/System.Security.Cryptography.Xml/src/System/Security/Cryptography/Xml/CryptoHelpers.cs
@@ -2,18 +2,14 @@
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
-using System;
-using System.Collections.Generic;
-using System.Linq;
-using System.Text;
-using System.Threading.Tasks;
+using System.Diagnostics.CodeAnalysis;
namespace System.Security.Cryptography.Xml
{
internal static class CryptoHelpers
{
- [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Security", "CA5350", Justification = "SHA1 needed for compat.")]
- [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Security", "CA5351", Justification = "HMACMD5 needed for compat.")]
+ [SuppressMessage("Microsoft.Security", "CA5350", Justification = "SHA1 needed for compat.")]
+ [SuppressMessage("Microsoft.Security", "CA5351", Justification = "HMACMD5 needed for compat.")]
public static object CreateFromName(string name)
{
switch (name)
diff --git a/src/System.Security.Cryptography.Xml/src/System/Security/Cryptography/Xml/DSASignatureDescription.cs b/src/System.Security.Cryptography.Xml/src/System/Security/Cryptography/Xml/DSASignatureDescription.cs
index 8e90939cec..4c74f878f4 100644
--- a/src/System.Security.Cryptography.Xml/src/System/Security/Cryptography/Xml/DSASignatureDescription.cs
+++ b/src/System.Security.Cryptography.Xml/src/System/Security/Cryptography/Xml/DSASignatureDescription.cs
@@ -2,11 +2,7 @@
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
-using System;
-using System.Collections.Generic;
-using System.Linq;
-using System.Text;
-using System.Threading.Tasks;
+using System.Diagnostics.CodeAnalysis;
namespace System.Security.Cryptography.Xml
{
@@ -16,9 +12,9 @@ namespace System.Security.Cryptography.Xml
public DSASignatureDescription()
{
- KeyAlgorithm = typeof(System.Security.Cryptography.DSA).AssemblyQualifiedName;
- FormatterAlgorithm = typeof(System.Security.Cryptography.DSASignatureFormatter).AssemblyQualifiedName;
- DeformatterAlgorithm = typeof(System.Security.Cryptography.DSASignatureDeformatter).AssemblyQualifiedName;
+ KeyAlgorithm = typeof(DSA).AssemblyQualifiedName;
+ FormatterAlgorithm = typeof(DSASignatureFormatter).AssemblyQualifiedName;
+ DeformatterAlgorithm = typeof(DSASignatureDeformatter).AssemblyQualifiedName;
DigestAlgorithm = "SHA1";
}
@@ -38,7 +34,7 @@ namespace System.Security.Cryptography.Xml
return item;
}
- [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Security", "CA5350", Justification = "SHA1 needed for compat.")]
+ [SuppressMessage("Microsoft.Security", "CA5350", Justification = "SHA1 needed for compat.")]
public sealed override HashAlgorithm CreateDigest()
{
return SHA1.Create();
diff --git a/src/System.Security.Cryptography.Xml/src/System/Security/Cryptography/Xml/RSAPKCS1SHA1SignatureDescription.cs b/src/System.Security.Cryptography.Xml/src/System/Security/Cryptography/Xml/RSAPKCS1SHA1SignatureDescription.cs
index 3a7e618b00..efa9f7b8b6 100644
--- a/src/System.Security.Cryptography.Xml/src/System/Security/Cryptography/Xml/RSAPKCS1SHA1SignatureDescription.cs
+++ b/src/System.Security.Cryptography.Xml/src/System/Security/Cryptography/Xml/RSAPKCS1SHA1SignatureDescription.cs
@@ -2,11 +2,7 @@
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
-using System;
-using System.Collections.Generic;
-using System.Linq;
-using System.Text;
-using System.Threading.Tasks;
+using System.Diagnostics.CodeAnalysis;
namespace System.Security.Cryptography.Xml
{
@@ -16,7 +12,7 @@ namespace System.Security.Cryptography.Xml
{
}
- [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Security", "CA5350", Justification = "SHA1 needed for compat.")]
+ [SuppressMessage("Microsoft.Security", "CA5350", Justification = "SHA1 needed for compat.")]
public sealed override HashAlgorithm CreateDigest()
{
return SHA1.Create();
diff --git a/src/System.Security.Cryptography.Xml/src/System/Security/Cryptography/Xml/RSAPKCS1SHA256SignatureDescription.cs b/src/System.Security.Cryptography.Xml/src/System/Security/Cryptography/Xml/RSAPKCS1SHA256SignatureDescription.cs
index b797eab0cc..7306882187 100644
--- a/src/System.Security.Cryptography.Xml/src/System/Security/Cryptography/Xml/RSAPKCS1SHA256SignatureDescription.cs
+++ b/src/System.Security.Cryptography.Xml/src/System/Security/Cryptography/Xml/RSAPKCS1SHA256SignatureDescription.cs
@@ -2,12 +2,6 @@
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
-using System;
-using System.Collections.Generic;
-using System.Linq;
-using System.Text;
-using System.Threading.Tasks;
-
namespace System.Security.Cryptography.Xml
{
internal class RSAPKCS1SHA256SignatureDescription : RSAPKCS1SignatureDescription
diff --git a/src/System.Security.Cryptography.Xml/src/System/Security/Cryptography/Xml/RSAPKCS1SHA384SignatureDescription.cs b/src/System.Security.Cryptography.Xml/src/System/Security/Cryptography/Xml/RSAPKCS1SHA384SignatureDescription.cs
index 6d1c97923e..0c6586dc03 100644
--- a/src/System.Security.Cryptography.Xml/src/System/Security/Cryptography/Xml/RSAPKCS1SHA384SignatureDescription.cs
+++ b/src/System.Security.Cryptography.Xml/src/System/Security/Cryptography/Xml/RSAPKCS1SHA384SignatureDescription.cs
@@ -2,12 +2,6 @@
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
-using System;
-using System.Collections.Generic;
-using System.Linq;
-using System.Text;
-using System.Threading.Tasks;
-
namespace System.Security.Cryptography.Xml
{
internal class RSAPKCS1SHA384SignatureDescription : RSAPKCS1SignatureDescription
diff --git a/src/System.Security.Cryptography.Xml/src/System/Security/Cryptography/Xml/RSAPKCS1SHA512SignatureDescription.cs b/src/System.Security.Cryptography.Xml/src/System/Security/Cryptography/Xml/RSAPKCS1SHA512SignatureDescription.cs
index f0fdd0fa02..c832ef8835 100644
--- a/src/System.Security.Cryptography.Xml/src/System/Security/Cryptography/Xml/RSAPKCS1SHA512SignatureDescription.cs
+++ b/src/System.Security.Cryptography.Xml/src/System/Security/Cryptography/Xml/RSAPKCS1SHA512SignatureDescription.cs
@@ -2,12 +2,6 @@
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
-using System;
-using System.Collections.Generic;
-using System.Linq;
-using System.Text;
-using System.Threading.Tasks;
-
namespace System.Security.Cryptography.Xml
{
internal class RSAPKCS1SHA512SignatureDescription : RSAPKCS1SignatureDescription
diff --git a/src/System.Security.Cryptography.Xml/src/System/Security/Cryptography/Xml/RSAPKCS1SignatureDescription.cs b/src/System.Security.Cryptography.Xml/src/System/Security/Cryptography/Xml/RSAPKCS1SignatureDescription.cs
index c4a7f7105e..2fc6a3d810 100644
--- a/src/System.Security.Cryptography.Xml/src/System/Security/Cryptography/Xml/RSAPKCS1SignatureDescription.cs
+++ b/src/System.Security.Cryptography.Xml/src/System/Security/Cryptography/Xml/RSAPKCS1SignatureDescription.cs
@@ -2,21 +2,15 @@
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
-using System;
-using System.Collections.Generic;
-using System.Linq;
-using System.Text;
-using System.Threading.Tasks;
-
namespace System.Security.Cryptography.Xml
{
internal abstract class RSAPKCS1SignatureDescription : SignatureDescription
{
public RSAPKCS1SignatureDescription(string hashAlgorithmName)
{
- KeyAlgorithm = typeof(System.Security.Cryptography.RSA).AssemblyQualifiedName;
- FormatterAlgorithm = typeof(System.Security.Cryptography.RSAPKCS1SignatureFormatter).AssemblyQualifiedName;
- DeformatterAlgorithm = typeof(System.Security.Cryptography.RSAPKCS1SignatureDeformatter).AssemblyQualifiedName;
+ KeyAlgorithm = typeof(RSA).AssemblyQualifiedName;
+ FormatterAlgorithm = typeof(RSAPKCS1SignatureFormatter).AssemblyQualifiedName;
+ DeformatterAlgorithm = typeof(RSAPKCS1SignatureDeformatter).AssemblyQualifiedName;
DigestAlgorithm = hashAlgorithmName;
}
diff --git a/src/System.Security.Cryptography.Xml/tests/System.Security.Cryptography.Xml.Tests.csproj b/src/System.Security.Cryptography.Xml/tests/System.Security.Cryptography.Xml.Tests.csproj
index ffcabf8bf4..0ac3d109cb 100644
--- a/src/System.Security.Cryptography.Xml/tests/System.Security.Cryptography.Xml.Tests.csproj
+++ b/src/System.Security.Cryptography.Xml/tests/System.Security.Cryptography.Xml.Tests.csproj
@@ -54,9 +54,6 @@
<Compile Include="XmlDsigXsltTransformTest.cs" />
<Compile Include="XmlLicenseEncryptedRef.cs" />
<Compile Include="XmlLicenseTransformTest.cs" />
- <Compile Include="$(CommonTestPath)\System\AssertExtensions.cs">
- <Link>Common\System\AssertExtensions.cs</Link>
- </Compile>
<Compile Include="$(CommonTestPath)\System\PlatformDetection.cs">
<Link>Common\System\PlatformDetection.cs</Link>
</Compile>
diff --git a/src/System.Security.Permissions/ref/System.Security.Permissions.csproj b/src/System.Security.Permissions/ref/System.Security.Permissions.csproj
index 500235cd23..53bad00887 100644
--- a/src/System.Security.Permissions/ref/System.Security.Permissions.csproj
+++ b/src/System.Security.Permissions/ref/System.Security.Permissions.csproj
@@ -3,14 +3,14 @@
<Import Project="$([MSBuild]::GetDirectoryNameOfFileAbove($(MSBuildThisFileDirectory), dir.props))\dir.props" />
<PropertyGroup>
<ProjectGuid>{07CAF142-B259-418E-86EF-C4BD8B50253E}</ProjectGuid>
- <!-- UAP10.1 is not yet mapped to netstandard2.0, manually duplicate this ref -->
- <PackageTargetFramework>netstandard2.0;uap10.1</PackageTargetFramework>
+ <!-- UAPvNext is not yet mapped to netstandard2.0, manually duplicate this ref -->
+ <PackageTargetFramework>netstandard2.0;$(UAPvNextTFM)</PackageTargetFramework>
</PropertyGroup>
<PropertyGroup Condition="'$(Configuration)|$(Platform)' == 'netstandard-Debug|AnyCPU'" />
<PropertyGroup Condition="'$(Configuration)|$(Platform)' == 'netstandard-Release|AnyCPU'" />
<ItemGroup>
<Compile Include="System.Security.Permissions.cs" />
- <SuppressPackageTargetFrameworkCompatibility Include="uap10.1" />
+ <SuppressPackageTargetFrameworkCompatibility Include="$(UAPvNextTFM)" />
</ItemGroup>
<ItemGroup>
<ProjectReference Include="..\..\System.Security.AccessControl\ref\System.Security.AccessControl.csproj" />
diff --git a/src/System.Security.Permissions/tests/System.Security.Permissions.Tests.csproj b/src/System.Security.Permissions/tests/System.Security.Permissions.Tests.csproj
index f1e9ea44ab..2288f2250f 100644
--- a/src/System.Security.Permissions/tests/System.Security.Permissions.Tests.csproj
+++ b/src/System.Security.Permissions/tests/System.Security.Permissions.Tests.csproj
@@ -27,9 +27,6 @@
<Compile Include="SecurityElementTests.cs" />
<Compile Include="HostSecurityManagerTests.cs" />
<Compile Include="HostProtectionTests.cs" />
- <Compile Include="$(CommonTestPath)\System\AssertExtensions.cs">
- <Link>Common\System\AssertExtensions.cs</Link>
- </Compile>
<Compile Include="$(CommonTestPath)\System\PlatformDetection.cs">
<Link>CommonTest\System\PlatformDetection.cs</Link>
</Compile>
diff --git a/src/System.Security.Principal.Windows/pkg/System.Security.Principal.Windows.pkgproj b/src/System.Security.Principal.Windows/pkg/System.Security.Principal.Windows.pkgproj
index a6770a4acf..7fee70517a 100644
--- a/src/System.Security.Principal.Windows/pkg/System.Security.Principal.Windows.pkgproj
+++ b/src/System.Security.Principal.Windows/pkg/System.Security.Principal.Windows.pkgproj
@@ -3,7 +3,7 @@
<Import Project="$([MSBuild]::GetDirectoryNameOfFileAbove($(MSBuildThisFileDirectory), dir.props))\dir.props" />
<ItemGroup>
<ProjectReference Include="..\ref\System.Security.Principal.Windows.csproj">
- <SupportedFramework>net461;netcoreapp2.0;uap10.1;$(AllXamarinFrameworks)</SupportedFramework>
+ <SupportedFramework>net461;netcoreapp2.0;$(UAPvNextTFM);$(AllXamarinFrameworks)</SupportedFramework>
</ProjectReference>
<ProjectReference Include="..\src\System.Security.Principal.Windows.csproj" />
<HarvestIncludePaths Include="ref/net46;lib/net46;runtimes/win/lib/net46" />
diff --git a/src/System.Security.Principal.Windows/ref/System.Security.Principal.Windows.csproj b/src/System.Security.Principal.Windows/ref/System.Security.Principal.Windows.csproj
index acd447c2be..9b4a3ef544 100644
--- a/src/System.Security.Principal.Windows/ref/System.Security.Principal.Windows.csproj
+++ b/src/System.Security.Principal.Windows/ref/System.Security.Principal.Windows.csproj
@@ -3,8 +3,8 @@
<Import Project="$([MSBuild]::GetDirectoryNameOfFileAbove($(MSBuildThisFileDirectory), dir.props))\dir.props" />
<PropertyGroup>
<ProjectGuid>{25A02E40-D12C-4184-B599-E4F954D142DB}</ProjectGuid>
- <!-- UAP10.1 is not yet mapped to netstandard2.0, manually duplicate this ref -->
- <PackageTargetFramework Condition="'$(TargetGroup)' == 'netstandard'">netstandard2.0;uap10.1</PackageTargetFramework>
+ <!-- UAPvNext is not yet mapped to netstandard2.0, manually duplicate this ref -->
+ <PackageTargetFramework Condition="'$(TargetGroup)' == 'netstandard'">netstandard2.0;$(UAPvNextTFM)</PackageTargetFramework>
<IsPartialFacadeAssembly Condition="'$(TargetGroup)' == 'netfx'">true</IsPartialFacadeAssembly>
</PropertyGroup>
<PropertyGroup Condition="'$(Configuration)|$(Platform)' == 'netfx-Debug|AnyCPU'" />
@@ -12,7 +12,7 @@
<PropertyGroup Condition="'$(Configuration)|$(Platform)' == 'netstandard-Debug|AnyCPU'" />
<PropertyGroup Condition="'$(Configuration)|$(Platform)' == 'netstandard-Release|AnyCPU'" />
<ItemGroup>
- <SuppressPackageTargetFrameworkCompatibility Include="uap10.1" />
+ <SuppressPackageTargetFrameworkCompatibility Include="$(UAPvNextTFM)" />
<Compile Include="System.Security.Principal.Windows.cs" />
</ItemGroup>
<ItemGroup Condition="'$(TargetGroup)' == 'netfx'">
diff --git a/src/System.Security.Principal.Windows/src/PinvokeAnalyzerExceptionList.analyzerdata.uap b/src/System.Security.Principal.Windows/src/PinvokeAnalyzerExceptionList.analyzerdata.uap
index d3069c99c8..d1af57af03 100644
--- a/src/System.Security.Principal.Windows/src/PinvokeAnalyzerExceptionList.analyzerdata.uap
+++ b/src/System.Security.Principal.Windows/src/PinvokeAnalyzerExceptionList.analyzerdata.uap
@@ -6,6 +6,7 @@ advapi32.dll!LsaLookupSids
advapi32.dll!LsaNtStatusToWinError
advapi32.dll!LsaOpenPolicy
advapi32.dll!OpenProcessToken
+kernel32.dll!CheckTokenMembershipEx
ntdll.dll!RtlNtStatusToDosError
sspicli.dll!LsaConnectUntrusted
sspicli.dll!LsaDeregisterLogonProcess
diff --git a/src/System.Security.Principal.Windows/src/System.Security.Principal.Windows.csproj b/src/System.Security.Principal.Windows/src/System.Security.Principal.Windows.csproj
index 9cdf412cb7..c52b0d4dfd 100644
--- a/src/System.Security.Principal.Windows/src/System.Security.Principal.Windows.csproj
+++ b/src/System.Security.Principal.Windows/src/System.Security.Principal.Windows.csproj
@@ -9,6 +9,9 @@
<ResourcesSourceOutputDirectory Condition="'$(TargetGroup)' == 'netfx'">None</ResourcesSourceOutputDirectory>
<GeneratePlatformNotSupportedAssemblyMessage Condition="'$(TargetsWindows)' != 'true'">SR.PlatformNotSupported_Principal</GeneratePlatformNotSupportedAssemblyMessage>
</PropertyGroup>
+ <PropertyGroup Condition="'$(TargetGroup)' == 'uap'">
+ <DefineConstants>$(DefineConstants);uap</DefineConstants>
+ </PropertyGroup>
<!-- Default configurations to help VS understand the options -->
<PropertyGroup Condition="'$(Configuration)|$(Platform)' == 'netcoreapp-Unix-Debug|AnyCPU'" />
<PropertyGroup Condition="'$(Configuration)|$(Platform)' == 'netcoreapp-Unix-Release|AnyCPU'" />
@@ -65,9 +68,6 @@
<Compile Include="$(CommonPath)\Interop\Windows\advapi32\Interop.OpenProcessToken_SafeAccessTokenHandle.cs">
<Link>Common\Interop\Interop.OpenProcessToken.cs</Link>
</Compile>
- <Compile Include="$(CommonPath)\Interop\Windows\advapi32\Interop.CheckTokenMembership.cs">
- <Link>Common\Interop\Interop.CheckTokenMembership.cs</Link>
- </Compile>
<Compile Include="$(CommonPath)\Interop\Windows\advapi32\Interop.GetTokenInformation.cs">
<Link>Common\Interop\Interop.GetTokenInformation.cs</Link>
</Compile>
@@ -183,6 +183,16 @@
<Link>Common\Microsoft\Win32\SafeHandles\SafeLsaHandle.cs</Link>
</Compile>
</ItemGroup>
+ <ItemGroup Condition="'$(TargetGroup)' == 'netcoreapp' AND '$(TargetsWindows)' == 'true'">
+ <Compile Include="$(CommonPath)\Interop\Windows\advapi32\Interop.CheckTokenMembership.cs">
+ <Link>Common\Interop\Interop.CheckTokenMembership.cs</Link>
+ </Compile>
+ </ItemGroup>
+ <ItemGroup Condition="'$(TargetGroup)' == 'uap' AND '$(TargetsWindows)' == 'true'">
+ <Compile Include="$(CommonPath)\Interop\Windows\kernel32\Interop.CheckTokenMembershipEx.cs">
+ <Link>Common\Interop\Interop.CheckTokenMembershipEx.cs</Link>
+ </Compile>
+ </ItemGroup>
<ItemGroup Condition="'$(TargetGroup)' == 'netfx'">
<Reference Include="mscorlib" />
</ItemGroup>
diff --git a/src/System.Security.Principal.Windows/src/System/Security/Principal/WindowsIdentity.cs b/src/System.Security.Principal.Windows/src/System/Security/Principal/WindowsIdentity.cs
index e2bf472c13..22ad4cb35f 100644
--- a/src/System.Security.Principal.Windows/src/System/Security/Principal/WindowsIdentity.cs
+++ b/src/System.Security.Principal.Windows/src/System/Security/Principal/WindowsIdentity.cs
@@ -404,10 +404,20 @@ namespace System.Security.Principal
// CheckTokenMembership will check if the SID is both present and enabled in the access token.
+#if uap
+ if (!Interop.Kernel32.CheckTokenMembershipEx((til != TokenImpersonationLevel.None ? _safeTokenHandle : token),
+ sid.BinaryForm,
+ Interop.Kernel32.CTMF_INCLUDE_APPCONTAINER,
+ ref isMember))
+ throw new SecurityException(new Win32Exception().Message);
+#else
if (!Interop.Advapi32.CheckTokenMembership((til != TokenImpersonationLevel.None ? _safeTokenHandle : token),
sid.BinaryForm,
ref isMember))
throw new SecurityException(new Win32Exception().Message);
+#endif
+
+
}
finally
{
diff --git a/src/System.Security.Principal.Windows/src/System/Security/Principal/WindowsPrincipal.cs b/src/System.Security.Principal.Windows/src/System/Security/Principal/WindowsPrincipal.cs
index da945f84ce..06202b5ac1 100644
--- a/src/System.Security.Principal.Windows/src/System/Security/Principal/WindowsPrincipal.cs
+++ b/src/System.Security.Principal.Windows/src/System/Security/Principal/WindowsPrincipal.cs
@@ -195,11 +195,20 @@ namespace System.Security.Principal
}
bool isMember = false;
+
// CheckTokenMembership will check if the SID is both present and enabled in the access token.
+#if uap
+ if (!Interop.Kernel32.CheckTokenMembershipEx((_identity.ImpersonationLevel != TokenImpersonationLevel.None ? _identity.AccessToken : token),
+ sid.BinaryForm,
+ Interop.Kernel32.CTMF_INCLUDE_APPCONTAINER,
+ ref isMember))
+ throw new SecurityException(new Win32Exception().Message);
+#else
if (!Interop.Advapi32.CheckTokenMembership((_identity.ImpersonationLevel != TokenImpersonationLevel.None ? _identity.AccessToken : token),
sid.BinaryForm,
ref isMember))
throw new SecurityException(new Win32Exception().Message);
+#endif
token.Dispose();
return isMember;
diff --git a/src/System.Security.Principal.Windows/tests/System.Security.Principal.Windows.Tests.csproj b/src/System.Security.Principal.Windows/tests/System.Security.Principal.Windows.Tests.csproj
index fd3fefacdd..91f6f07fcf 100644
--- a/src/System.Security.Principal.Windows/tests/System.Security.Principal.Windows.Tests.csproj
+++ b/src/System.Security.Principal.Windows/tests/System.Security.Principal.Windows.Tests.csproj
@@ -10,9 +10,6 @@
<Compile Include="WindowsIdentityTests.cs" />
<Compile Include="WindowsPrincipalTests.cs" />
<Compile Include="WellKnownSidTypeTests.cs" />
- <Compile Include="$(CommonTestPath)\System\AssertExtensions.cs">
- <Link>Common\System\AssertExtensions.cs</Link>
- </Compile>
<Compile Include="$(CommonTestPath)\System\PlatformDetection.cs">
<Link>CommonTest\System\PlatformDetection.cs</Link>
</Compile>
diff --git a/src/System.Security.Principal.Windows/tests/WindowsIdentityTests.cs b/src/System.Security.Principal.Windows/tests/WindowsIdentityTests.cs
index 430807b213..0d3f1b08b3 100644
--- a/src/System.Security.Principal.Windows/tests/WindowsIdentityTests.cs
+++ b/src/System.Security.Principal.Windows/tests/WindowsIdentityTests.cs
@@ -39,15 +39,7 @@ public class WindowsIdentityTests
string authenticationType = "WindowsAuthentication";
WindowsIdentity windowsIdentity2 = new WindowsIdentity(logonToken, authenticationType);
Assert.NotNull(windowsIdentity2);
-
- if (PlatformDetection.IsWinRT)
- {
- Assert.False(windowsIdentity2.IsAuthenticated);
- }
- else
- {
- Assert.True(windowsIdentity2.IsAuthenticated);
- }
+ Assert.True(windowsIdentity2.IsAuthenticated);
Assert.Equal(authenticationType, windowsIdentity2.AuthenticationType);
CheckDispose(windowsIdentity2);
diff --git a/src/System.Security.Principal/src/System.Security.Principal.csproj b/src/System.Security.Principal/src/System.Security.Principal.csproj
index b4d1d95dd6..57df563035 100644
--- a/src/System.Security.Principal/src/System.Security.Principal.csproj
+++ b/src/System.Security.Principal/src/System.Security.Principal.csproj
@@ -5,7 +5,6 @@
<AssemblyName>System.Security.Principal</AssemblyName>
<ProjectGuid>{FBE16BC8-AE2D-422C-861E-861814F53AF7}</ProjectGuid>
<AllowUnsafeBlocks>true</AllowUnsafeBlocks>
- <!-- copy to uap10.1 until nuget makes the change to map that to ns1.7 -->
</PropertyGroup>
<!-- Default configurations to help VS understand the options -->
<PropertyGroup Condition="'$(Configuration)|$(Platform)' == 'netcoreapp-Debug|AnyCPU'" />
diff --git a/src/System.Security.SecureString/tests/System.Security.SecureString.Tests.csproj b/src/System.Security.SecureString/tests/System.Security.SecureString.Tests.csproj
index d354bca9be..a8086cee21 100644
--- a/src/System.Security.SecureString/tests/System.Security.SecureString.Tests.csproj
+++ b/src/System.Security.SecureString/tests/System.Security.SecureString.Tests.csproj
@@ -10,9 +10,6 @@
<PropertyGroup Condition="'$(Configuration)|$(Platform)' == 'netstandard-Release|AnyCPU'" />
<ItemGroup>
<Compile Include="SecureStringTests.cs" />
- <Compile Include="$(CommonTestPath)\System\AssertExtensions.cs">
- <Link>Common\System\AssertExtensions.cs</Link>
- </Compile>
</ItemGroup>
<Import Project="$([MSBuild]::GetDirectoryNameOfFileAbove($(MSBuildThisFileDirectory), dir.targets))\dir.targets" />
</Project> \ No newline at end of file
diff --git a/src/System.ServiceProcess.ServiceController/tests/System.ServiceProcess.ServiceController.Tests/System.ServiceProcess.ServiceController.Tests.csproj b/src/System.ServiceProcess.ServiceController/tests/System.ServiceProcess.ServiceController.Tests/System.ServiceProcess.ServiceController.Tests.csproj
index b859a0c90e..0e9d264310 100644
--- a/src/System.ServiceProcess.ServiceController/tests/System.ServiceProcess.ServiceController.Tests/System.ServiceProcess.ServiceController.Tests.csproj
+++ b/src/System.ServiceProcess.ServiceController/tests/System.ServiceProcess.ServiceController.Tests/System.ServiceProcess.ServiceController.Tests.csproj
@@ -10,9 +10,6 @@
<ItemGroup>
<Compile Include="SafeServiceControllerTests.cs" />
<Compile Include="ServiceControllerTests.cs" />
- <Compile Include="$(CommonTestPath)\System\AssertExtensions.cs">
- <Link>Common\System\AssertExtensions.cs</Link>
- </Compile>
<Compile Include="$(CommonTestPath)\System\PlatformDetection.cs">
<Link>CommonTest\System\PlatformDetection.cs</Link>
</Compile>
diff --git a/src/System.Text.Encoding.CodePages/pkg/System.Text.Encoding.CodePages.pkgproj b/src/System.Text.Encoding.CodePages/pkg/System.Text.Encoding.CodePages.pkgproj
index fe4d339d29..a61018ac85 100644
--- a/src/System.Text.Encoding.CodePages/pkg/System.Text.Encoding.CodePages.pkgproj
+++ b/src/System.Text.Encoding.CodePages/pkg/System.Text.Encoding.CodePages.pkgproj
@@ -14,7 +14,7 @@
</HarvestIncludePaths>
</ItemGroup>
<ItemGroup>
- <InboxOnTargetFramework Include="uap10.1">
+ <InboxOnTargetFramework Include="$(UAPvNextTFM)">
<PackageTargetRuntime>win</PackageTargetRuntime>
</InboxOnTargetFramework>
<InboxOnTargetFramework Include="MonoAndroid10" />
diff --git a/src/System.Text.Encoding.CodePages/tests/System.Text.Encoding.CodePages.Tests.csproj b/src/System.Text.Encoding.CodePages/tests/System.Text.Encoding.CodePages.Tests.csproj
index 10be8f1e68..94457ad1d3 100644
--- a/src/System.Text.Encoding.CodePages/tests/System.Text.Encoding.CodePages.Tests.csproj
+++ b/src/System.Text.Encoding.CodePages/tests/System.Text.Encoding.CodePages.Tests.csproj
@@ -9,9 +9,6 @@
<PropertyGroup Condition="'$(Configuration)|$(Platform)' == 'netstandard-Release|AnyCPU'" />
<ItemGroup>
<Compile Include="EncodingCodePages.cs" />
- <Compile Include="$(CommonTestPath)\System\AssertExtensions.cs">
- <Link>Common\System\AssertExtensions.cs</Link>
- </Compile>
<Compile Include="$(CommonTestPath)\System\PlatformDetection.cs">
<Link>CommonTest\System\PlatformDetection.cs</Link>
</Compile>
diff --git a/src/System.Text.Encoding/tests/Encoding/Encoding.cs b/src/System.Text.Encoding/tests/Encoding/Encoding.cs
index dfb5af4b6f..f34e48e65d 100644
--- a/src/System.Text.Encoding/tests/Encoding/Encoding.cs
+++ b/src/System.Text.Encoding/tests/Encoding/Encoding.cs
@@ -46,7 +46,6 @@ namespace System.Text.Encodings.Tests
[Fact]
[SkipOnTargetFramework(TargetFrameworkMonikers.NetFramework, "Full framework uses system ACP and not UTF8")]
- [ActiveIssue("https://github.com/dotnet/corefx/issues/20715 - Sync up Encoding code between CoreRT and CoreCLR", TargetFrameworkMonikers.UapAot)]
public static void DefaultEncodingBOMTest()
{
UTF8Encoding defaultEncoding = Encoding.Default as UTF8Encoding;
@@ -69,7 +68,6 @@ namespace System.Text.Encodings.Tests
[Theory]
[MemberData(nameof(Encoding_TestData))]
- [ActiveIssue("https://github.com/dotnet/corefx/issues/20715 - Sync up Encoding code between CoreRT and CoreCLR", TargetFrameworkMonikers.UapAot)]
public static void NormalizationTest(int codepage, string name, string bodyName, string headerName, bool isBrowserDisplay,
bool isBrowserSave, bool isMailNewsDisplay, bool isMailNewsSave, int windowsCodePage)
{
@@ -86,7 +84,6 @@ namespace System.Text.Encodings.Tests
[Theory]
[MemberData(nameof(Normalization_TestData))]
- [ActiveIssue("https://github.com/dotnet/corefx/issues/20715 - Sync up Encoding code between CoreRT and CoreCLR", TargetFrameworkMonikers.UapAot)]
public static void NormalizationTest(int codepage, bool normalized, bool normalizedC, bool normalizedD, bool normalizedKC, bool normalizedKD)
{
Encoding encoding = Encoding.GetEncoding(codepage);
diff --git a/src/System.Text.Encoding/tests/System.Text.Encoding.Tests.csproj b/src/System.Text.Encoding/tests/System.Text.Encoding.Tests.csproj
index 204e47f4e6..38004a0195 100644
--- a/src/System.Text.Encoding/tests/System.Text.Encoding.Tests.csproj
+++ b/src/System.Text.Encoding/tests/System.Text.Encoding.Tests.csproj
@@ -79,9 +79,6 @@
<Compile Include="UnicodeEncoding\UnicodeEncoding.cs" />
<Compile Include="Decoder\Decoder.cs" />
<Compile Include="Encoder\Encoder.cs" />
- <Compile Include="$(CommonTestPath)\System\AssertExtensions.cs">
- <Link>Common\System\AssertExtensions.cs</Link>
- </Compile>
</ItemGroup>
<Import Project="$([MSBuild]::GetDirectoryNameOfFileAbove($(MSBuildThisFileDirectory), dir.targets))\dir.targets" />
</Project>
diff --git a/src/System.Text.Encoding/tests/UTF32Encoding/UTF32EncodingTests.cs b/src/System.Text.Encoding/tests/UTF32Encoding/UTF32EncodingTests.cs
index 2c91772148..573b97fa1f 100644
--- a/src/System.Text.Encoding/tests/UTF32Encoding/UTF32EncodingTests.cs
+++ b/src/System.Text.Encoding/tests/UTF32Encoding/UTF32EncodingTests.cs
@@ -85,7 +85,6 @@ namespace System.Text.Tests
[Theory]
[MemberData(nameof(Encodings_TestData))]
- [ActiveIssue("https://github.com/dotnet/corefx/issues/20715 - Sync up Encoding code between CoreRT and CoreCLR", TargetFrameworkMonikers.UapAot)]
public void WebName(UTF32Encoding encoding, string webName)
{
Assert.Equal(webName, encoding.WebName);
diff --git a/src/System.Text.Encoding/tests/UnicodeEncoding/UnicodeEncodingDecode.cs b/src/System.Text.Encoding/tests/UnicodeEncoding/UnicodeEncodingDecode.cs
index 9cb07140e6..39a3c4a9b4 100644
--- a/src/System.Text.Encoding/tests/UnicodeEncoding/UnicodeEncodingDecode.cs
+++ b/src/System.Text.Encoding/tests/UnicodeEncoding/UnicodeEncodingDecode.cs
@@ -98,7 +98,7 @@ namespace System.Text.Tests
yield return new object[] { new byte[] { 84, 0, 101, 0, 115, 0, 116, 0, 84, 0, 101, 0, 115, 0, 116, 0, 117, 221 }, 0, 18, "TestTest\uFFFD" };
yield return new object[] { new byte[] { 84, 0, 101, 0, 115, 0, 116, 0, 84, 0, 101, 0, 115, 0, 116, 0, 3, 216 }, 0, 17, "TestTest\uFFFD" };
- yield return new object[] { new byte[] { 0, 0, 84, 0, 101, 0, 10, 0, 115, 0, 116, 0, 0, 0, 9, 0, 0, 0, 84, 0, 15, 0, 101, 0, 115, 0, 116, 0, 0, 0, 0 }, 0, 31, "\0Te\nst\0\t\0T\u000Fest\0\uFFFD" };
+ yield return new object[] { new byte[] { 84, 0, 0, 0, 84, 0, 101, 0, 10, 0, 115, 0, 116, 0, 0, 0, 9, 0, 0, 0, 84, 0, 15, 0, 101, 0, 115, 0, 116, 0, 0, 0, 0 }, 0, 33, "T\0Te\nst\0\t\0T\u000Fest\0\uFFFD" };
yield return new object[] { new byte[] { 3, 216, 84 }, 0, 3, "\uFFFD\uFFFD" };
@@ -130,7 +130,6 @@ namespace System.Text.Tests
[Theory]
[MemberData(nameof(Decode_InvalidBytes_TestData))]
- [ActiveIssue("https://github.com/dotnet/corefx/issues/20715", TargetFrameworkMonikers.UapAot)]
public void Decode_InvalidBytes(byte[] littleEndianBytes, int index, int count, string expected)
{
byte[] bigEndianBytes = GetBigEndianBytes(littleEndianBytes, index, count);
diff --git a/src/System.Text.Encoding/tests/UnicodeEncoding/UnicodeEncodingTests.cs b/src/System.Text.Encoding/tests/UnicodeEncoding/UnicodeEncodingTests.cs
index a6a13da532..b3d5672ea4 100644
--- a/src/System.Text.Encoding/tests/UnicodeEncoding/UnicodeEncodingTests.cs
+++ b/src/System.Text.Encoding/tests/UnicodeEncoding/UnicodeEncodingTests.cs
@@ -85,7 +85,6 @@ namespace System.Text.Tests
[Theory]
[MemberData(nameof(Encodings_TestData))]
- [ActiveIssue("https://github.com/dotnet/corefx/issues/20715 - Sync up Encoding code between CoreRT and CoreCLR", TargetFrameworkMonikers.UapAot)]
public void WebName(UnicodeEncoding encoding, string expected)
{
Assert.Equal(expected, encoding.WebName);
diff --git a/src/System.Text.Encodings.Web/tests/System.Text.Encodings.Web.Tests.csproj b/src/System.Text.Encodings.Web/tests/System.Text.Encodings.Web.Tests.csproj
index bfccf9c24b..ca3abfafba 100644
--- a/src/System.Text.Encodings.Web/tests/System.Text.Encodings.Web.Tests.csproj
+++ b/src/System.Text.Encodings.Web/tests/System.Text.Encodings.Web.Tests.csproj
@@ -44,9 +44,6 @@
<Compile Include="UrlEncoderTests.cs" />
</ItemGroup>
<ItemGroup>
- <Compile Include="$(CommonTestPath)\System\AssertExtensions.cs">
- <Link>Common\System\AssertExtensions.cs</Link>
- </Compile>
<Compile Include="$(CommonTestPath)\System\PlatformDetection.cs">
<Link>Common\System\PlatformDetection.cs</Link>
</Compile>
diff --git a/src/System.Text.RegularExpressions/tests/Regex.Groups.Tests.cs b/src/System.Text.RegularExpressions/tests/Regex.Groups.Tests.cs
index 9546e1069c..c28be6399f 100644
--- a/src/System.Text.RegularExpressions/tests/Regex.Groups.Tests.cs
+++ b/src/System.Text.RegularExpressions/tests/Regex.Groups.Tests.cs
@@ -594,83 +594,163 @@ namespace System.Text.RegularExpressions.Tests
yield return new object[] { @"(a*)+?$", "b", RegexOptions.None, new string[] { "", "" } };
}
- [Theory]
- [MemberData(nameof(Groups_Basic_TestData))]
- public void Groups(string pattern, string input, RegexOptions options, string[] expectedGroups) => Groups(pattern, input, options, null, expectedGroups);
+ public static IEnumerable<object[]> Groups_CustomCulture_TestData_enUS()
+ {
+ yield return new object[] { "CH", "Ch", RegexOptions.IgnoreCase, new string[] { "Ch" } };
+ yield return new object[] { "cH", "Ch", RegexOptions.IgnoreCase, new string[] { "Ch" } };
+ yield return new object[] { "AA", "Aa", RegexOptions.IgnoreCase, new string[] { "Aa" } };
+ yield return new object[] { "aA", "Aa", RegexOptions.IgnoreCase, new string[] { "Aa" } };
+ yield return new object[] { "\u0130", "\u0049", RegexOptions.IgnoreCase, new string[] { "\u0049" } };
+ yield return new object[] { "\u0130", "\u0069", RegexOptions.IgnoreCase, new string[] { "\u0069" } };
+ }
+
+ public static IEnumerable<object[]> Groups_CustomCulture_TestData_Czech()
+ {
+ yield return new object[] { "CH", "Ch", RegexOptions.IgnoreCase, new string[] { "Ch" } };
+ yield return new object[] { "cH", "Ch", RegexOptions.IgnoreCase, new string[] { "Ch" } };
+ }
+
+
+ public static IEnumerable<object[]> Groups_CustomCulture_TestData_Danish()
+ {
+ yield return new object[] { "AA", "Aa", RegexOptions.IgnoreCase, new string[] { "Aa" } };
+ yield return new object[] { "aA", "Aa", RegexOptions.IgnoreCase, new string[] { "Aa" } };
+ }
+
+ public static IEnumerable<object[]> Groups_CustomCulture_TestData_Turkish()
+ {
+ yield return new object[] { "\u0131", "\u0049", RegexOptions.IgnoreCase, new string[] { "\u0049" } };
+ yield return new object[] { "\u0130", "\u0069", RegexOptions.IgnoreCase, new string[] { "\u0069" } };
+ }
+
+ public static IEnumerable<object[]> Groups_CustomCulture_TestData_AzeriLatin()
+ {
+ yield return new object[] { "\u0131", "\u0049", RegexOptions.IgnoreCase, new string[] { "\u0049" } };
+ yield return new object[] { "\u0130", "\u0069", RegexOptions.IgnoreCase, new string[] { "\u0069" } };
+ }
- public static IEnumerable<object[]> Groups_CustomCulture_TestData()
+ private static CultureInfo GetDefaultCultureForTests()
{
- // Use special unicode characters
- yield return new object[] { "CH", "Ch", RegexOptions.IgnoreCase, s_enUSCulture, new string[] { "Ch" } };
- yield return new object[] { "CH", "Ch", RegexOptions.IgnoreCase, s_czechCulture, new string[] { "Ch" } };
- yield return new object[] { "cH", "Ch", RegexOptions.IgnoreCase, s_enUSCulture, new string[] { "Ch" } };
- yield return new object[] { "cH", "Ch", RegexOptions.IgnoreCase, s_czechCulture, new string[] { "Ch" } };
-
- yield return new object[] { "AA", "Aa", RegexOptions.IgnoreCase, s_enUSCulture, new string[] { "Aa" } };
- yield return new object[] { "AA", "Aa", RegexOptions.IgnoreCase, s_danishCulture, new string[] { "Aa" } };
- yield return new object[] { "aA", "Aa", RegexOptions.IgnoreCase, s_enUSCulture, new string[] { "Aa" } };
- yield return new object[] { "aA", "Aa", RegexOptions.IgnoreCase, s_danishCulture, new string[] { "Aa" } };
-
- yield return new object[] { "\u0131", "\u0049", RegexOptions.IgnoreCase, s_turkishCulture, new string[] { "\u0049" } };
- yield return new object[] { "\u0130", "\u0069", RegexOptions.IgnoreCase, s_turkishCulture, new string[] { "\u0069" } };
- yield return new object[] { "\u0131", "\u0049", RegexOptions.IgnoreCase, s_azeriLatinCulture, new string[] { "\u0049" } };
- yield return new object[] { "\u0130", "\u0069", RegexOptions.IgnoreCase, s_azeriLatinCulture, new string[] { "\u0069" } };
-
- yield return new object[] { "\u0130", "\u0049", RegexOptions.IgnoreCase, s_enUSCulture, new string[] { "\u0049" } };
- yield return new object[] { "\u0130", "\u0069", RegexOptions.IgnoreCase, s_enUSCulture, new string[] { "\u0069" } };
+ CultureInfo defaultCulture = CultureInfo.CurrentCulture;
+
+ // In invariant culture, the unicode char matches differ from expected values provided.
+ if (defaultCulture.Equals(CultureInfo.InvariantCulture))
+ {
+ defaultCulture = new CultureInfo("en-US");
+ }
+
+ return defaultCulture;
}
- [Theory]
- [MemberData(nameof(Groups_CustomCulture_TestData))]
- public void Groups(string pattern, string input, RegexOptions options, CultureInfo cultureInfo, string[] expectedGroups)
+ public void Groups(string pattern, string input, RegexOptions options, string[] expectedGroups)
{
- const string EmptyPlaceholder = "-";
- const char Separator = ';';
+ Regex regex = new Regex(pattern, options);
+ Match match = regex.Match(input);
+ Assert.True(match.Success, $"match.Success. pattern=/{pattern}/ input=[[[{input}]]] culture={CultureInfo.CurrentCulture.Name}");
- string outerPattern = Convert.ToBase64String(Encoding.UTF8.GetBytes(pattern));
- string outerInput = Convert.ToBase64String(Encoding.UTF8.GetBytes(input));
- string outerOptions = ((int)options).ToString();
- string outerCultureInfo = cultureInfo != null ? cultureInfo.ToString() : EmptyPlaceholder;
- string outerExpectedGroups = expectedGroups != null && expectedGroups.Length > 0 ? Convert.ToBase64String(Encoding.UTF8.GetBytes(string.Join(Separator.ToString(), expectedGroups.Select(s => s == string.Empty ? EmptyPlaceholder : s).ToArray()))) : EmptyPlaceholder;
+ Assert.Equal(expectedGroups.Length, match.Groups.Count);
+ Assert.True(expectedGroups[0] == match.Value, string.Format("Culture used: {0}", CultureInfo.CurrentCulture));
- RemoteInvoke((innerPatternEnc, innerInputEnc, innerOptionsEnc, innerCultureInfoEnc, innerExpectedGroupsEnc) =>
+ int[] groupNumbers = regex.GetGroupNumbers();
+ string[] groupNames = regex.GetGroupNames();
+ for (int i = 0; i < expectedGroups.Length; i++)
{
- string innerPattern = Encoding.UTF8.GetString(Convert.FromBase64String(innerPatternEnc));
- string innerInput = Encoding.UTF8.GetString(Convert.FromBase64String(innerInputEnc));
- RegexOptions innerOptions = (RegexOptions)int.Parse(innerOptionsEnc);
- CultureInfo innerCultureInfo = innerCultureInfoEnc != EmptyPlaceholder ? new CultureInfo(innerCultureInfoEnc) : null;
- string[] innerExpectedGroups = innerExpectedGroupsEnc != EmptyPlaceholder ? Encoding.UTF8.GetString(Convert.FromBase64String(innerExpectedGroupsEnc)).Split(Separator).Select(s => s == EmptyPlaceholder ? string.Empty : s).ToArray() : new string[] { };
-
- // In invariant culture, the unicode char matches differ from expected values provided.
- if (CultureInfo.CurrentCulture.Equals(CultureInfo.InvariantCulture))
+ Assert.Equal(expectedGroups[i], match.Groups[groupNumbers[i]].Value);
+ Assert.Equal(match.Groups[groupNumbers[i]], match.Groups[groupNames[i]]);
+
+ Assert.Equal(groupNumbers[i], regex.GroupNumberFromName(groupNames[i]));
+ Assert.Equal(groupNames[i], regex.GroupNameFromNumber(groupNumbers[i]));
+ }
+ }
+
+ private void GroupsTest(object[] testCase)
+ {
+ Groups((string)testCase[0], (string)testCase[1], (RegexOptions)testCase[2], (string[])testCase[3]);
+ }
+
+
+ [Fact]
+ public void GroupsEnUS()
+ {
+ RemoteInvoke(() => {
+ CultureInfo.CurrentCulture = s_enUSCulture;
+ foreach (object[] testCase in Groups_CustomCulture_TestData_enUS())
+ {
+ GroupsTest(testCase);
+ }
+
+ return SuccessExitCode;
+ }).Dispose();
+ }
+
+ [Fact]
+ public void GroupsCzech()
+ {
+ RemoteInvoke(() => {
+ CultureInfo.CurrentCulture = s_czechCulture;
+ foreach (object[] testCase in Groups_CustomCulture_TestData_Czech())
{
- CultureInfo.CurrentCulture = new CultureInfo("en-US");
+ GroupsTest(testCase);
}
- if (innerCultureInfo != null)
+
+ return SuccessExitCode;
+ }).Dispose();
+ }
+
+ [Fact]
+ public void GroupsDanish()
+ {
+ RemoteInvoke(() => {
+ CultureInfo.CurrentCulture = s_danishCulture;
+ foreach (object[] testCase in Groups_CustomCulture_TestData_Danish())
{
- CultureInfo.CurrentCulture = innerCultureInfo;
+ GroupsTest(testCase);
}
- Regex regex = new Regex(innerPattern, innerOptions);
- Match match = regex.Match(innerInput);
- Assert.True(match.Success);
+ return SuccessExitCode;
+ }).Dispose();
+ }
+
+ [Fact]
+ public void GroupsTurkish()
+ {
+ RemoteInvoke(() => {
+ CultureInfo.CurrentCulture = s_turkishCulture;
+ foreach (object[] testCase in Groups_CustomCulture_TestData_Turkish())
+ {
+ GroupsTest(testCase);
+ }
- Assert.Equal(innerExpectedGroups.Length, match.Groups.Count);
- Assert.True(innerExpectedGroups[0] == match.Value, string.Format("Culture used: {0}", CultureInfo.CurrentCulture));
+ return SuccessExitCode;
+ }).Dispose();
+ }
- int[] groupNumbers = regex.GetGroupNumbers();
- string[] groupNames = regex.GetGroupNames();
- for (int i = 0; i < innerExpectedGroups.Length; i++)
+ [Fact]
+ public void GroupsAzeriLatin()
+ {
+ RemoteInvoke(() => {
+ CultureInfo.CurrentCulture = s_azeriLatinCulture;
+ foreach (object[] testCase in Groups_CustomCulture_TestData_AzeriLatin())
{
- Assert.Equal(innerExpectedGroups[i], match.Groups[groupNumbers[i]].Value);
- Assert.Equal(match.Groups[groupNumbers[i]], match.Groups[groupNames[i]]);
+ GroupsTest(testCase);
+ }
+
+ return SuccessExitCode;
+ }).Dispose();
+ }
- Assert.Equal(groupNumbers[i], regex.GroupNumberFromName(groupNames[i]));
- Assert.Equal(groupNames[i], regex.GroupNameFromNumber(groupNumbers[i]));
+ [Fact]
+ public void GroupsBasic()
+ {
+ RemoteInvoke(() => {
+ CultureInfo.CurrentCulture = GetDefaultCultureForTests();
+ foreach (object[] testCase in Groups_Basic_TestData())
+ {
+ GroupsTest(testCase);
}
return SuccessExitCode;
- }, outerPattern, outerInput, outerOptions, outerCultureInfo, outerExpectedGroups).Dispose();
+ }).Dispose();
}
}
}
diff --git a/src/System.Text.RegularExpressions/tests/Regex.Match.Tests.cs b/src/System.Text.RegularExpressions/tests/Regex.Match.Tests.cs
index 765f2e0147..43d51f009b 100644
--- a/src/System.Text.RegularExpressions/tests/Regex.Match.Tests.cs
+++ b/src/System.Text.RegularExpressions/tests/Regex.Match.Tests.cs
@@ -691,7 +691,7 @@ namespace System.Text.RegularExpressions.Tests
}
[Fact]
- public void Match_SpecialUnicodeCharacters()
+ public void Match_SpecialUnicodeCharacters_enUS()
{
RemoteInvoke(() =>
{
@@ -699,6 +699,15 @@ namespace System.Text.RegularExpressions.Tests
Match("\u0131", "\u0049", RegexOptions.IgnoreCase, 0, 1, false, string.Empty);
Match("\u0131", "\u0069", RegexOptions.IgnoreCase, 0, 1, false, string.Empty);
+ return SuccessExitCode;
+ }).Dispose();
+ }
+
+ [Fact]
+ public void Match_SpecialUnicodeCharacters_Invariant()
+ {
+ RemoteInvoke(() =>
+ {
CultureInfo.CurrentCulture = CultureInfo.InvariantCulture;
Match("\u0131", "\u0049", RegexOptions.IgnoreCase, 0, 1, false, string.Empty);
Match("\u0131", "\u0069", RegexOptions.IgnoreCase, 0, 1, false, string.Empty);
diff --git a/src/System.Text.RegularExpressions/tests/System.Text.RegularExpressions.Tests.csproj b/src/System.Text.RegularExpressions/tests/System.Text.RegularExpressions.Tests.csproj
index 06a00b0eee..2c54d8de6e 100644
--- a/src/System.Text.RegularExpressions/tests/System.Text.RegularExpressions.Tests.csproj
+++ b/src/System.Text.RegularExpressions/tests/System.Text.RegularExpressions.Tests.csproj
@@ -11,8 +11,7 @@
<PropertyGroup Condition="'$(Configuration)|$(Platform)' == 'netstandard-Release|AnyCPU'" />
<PropertyGroup Condition="'$(Configuration)|$(Platform)' == 'uap-Debug|AnyCPU'" />
<PropertyGroup Condition="'$(Configuration)|$(Platform)' == 'uap-Release|AnyCPU'" />
- <!-- [ActiveIssue(https://github.com/dotnet/corefx/issues/21547)] times out in uap. -->
- <ItemGroup Condition="'$(TargetGroup)' != 'uap'">
+ <ItemGroup>
<Compile Include="$(CommonTestPath)\System\PlatformDetection.cs">
<Link>Common\tests\System\PlatformDetection.cs</Link>
</Compile>
@@ -30,9 +29,6 @@
<Compile Include="Regex.Split.Tests.cs" />
<Compile Include="Regex.Match.Tests.cs" />
<Compile Include="Regex.Tests.Common.cs" />
- <Compile Include="$(CommonTestPath)\System\AssertExtensions.cs">
- <Link>Common\System\AssertExtensions.cs</Link>
- </Compile>
<Compile Include="$(CommonTestPath)\System\Runtime\Serialization\Formatters\BinaryFormatterHelpers.cs">
<Link>System\Runtime\Serialization\Formatters\BinaryFormatterHelpers.cs</Link>
</Compile>
diff --git a/src/System.Threading.Overlapped/tests/System.Threading.Overlapped.Tests.csproj b/src/System.Threading.Overlapped/tests/System.Threading.Overlapped.Tests.csproj
index 5799281406..419323ec2a 100644
--- a/src/System.Threading.Overlapped/tests/System.Threading.Overlapped.Tests.csproj
+++ b/src/System.Threading.Overlapped/tests/System.Threading.Overlapped.Tests.csproj
@@ -26,9 +26,6 @@
<Compile Include="ThreadPoolBoundHandle_DisposeTests.cs" />
<Compile Include="ThreadPoolBoundHandle_BindHandleTests.cs" />
<Compile Include="OverlappedTests.cs" />
- <Compile Include="$(CommonTestPath)\System\AssertExtensions.cs">
- <Link>Common\System\AssertExtensions.cs</Link>
- </Compile>
</ItemGroup>
<Import Project="$([MSBuild]::GetDirectoryNameOfFileAbove($(MSBuildThisFileDirectory), dir.targets))\dir.targets" />
</Project>
diff --git a/src/System.Threading.Tasks.Dataflow/pkg/System.Threading.Tasks.Dataflow.pkgproj b/src/System.Threading.Tasks.Dataflow/pkg/System.Threading.Tasks.Dataflow.pkgproj
index 32121a8d74..c8942a024b 100644
--- a/src/System.Threading.Tasks.Dataflow/pkg/System.Threading.Tasks.Dataflow.pkgproj
+++ b/src/System.Threading.Tasks.Dataflow/pkg/System.Threading.Tasks.Dataflow.pkgproj
@@ -10,7 +10,7 @@
<SupportedFramework>net45;netcore45;wp8;wpa81;netcoreapp1.0;$(AllXamarinFrameworks)</SupportedFramework>
</ProjectReference>
<InboxOnTargetFramework Include="netcoreapp2.0" />
- <InboxOnTargetFramework Include="uap10.1" />
+ <InboxOnTargetFramework Include="$(UAPvNextTFM)" />
</ItemGroup>
<Import Project="$([MSBuild]::GetDirectoryNameOfFileAbove($(MSBuildThisFileDirectory), dir.targets))\dir.targets" />
</Project> \ No newline at end of file
diff --git a/src/System.Threading.Tasks.Dataflow/tests/System.Threading.Tasks.Dataflow.Tests.csproj b/src/System.Threading.Tasks.Dataflow/tests/System.Threading.Tasks.Dataflow.Tests.csproj
index e6bae02486..1c8adef64f 100644
--- a/src/System.Threading.Tasks.Dataflow/tests/System.Threading.Tasks.Dataflow.Tests.csproj
+++ b/src/System.Threading.Tasks.Dataflow/tests/System.Threading.Tasks.Dataflow.Tests.csproj
@@ -24,9 +24,6 @@
<Compile Include="Dataflow\TransformBlockTests.cs" />
<Compile Include="Dataflow\TransformManyBlockTests.cs" />
<Compile Include="Dataflow\WriteOnceBlockTests.cs" />
- <Compile Include="$(CommonTestPath)\System\AssertExtensions.cs">
- <Link>Common\System\AssertExtensions.cs</Link>
- </Compile>
<Compile Include="$(CommonTestPath)\System\Diagnostics\Tracing\TestEventListener.cs">
<Link>Common\System\Diagnostics\Tracing\TestEventListener.cs</Link>
</Compile>
diff --git a/src/System.Threading.Tasks.Extensions/src/System/Runtime/CompilerServices/AsyncMethodBuilderAttribute.cs b/src/System.Threading.Tasks.Extensions/src/System/Runtime/CompilerServices/AsyncMethodBuilderAttribute.cs
index 6f17e8b0fe..688a3a01ba 100644
--- a/src/System.Threading.Tasks.Extensions/src/System/Runtime/CompilerServices/AsyncMethodBuilderAttribute.cs
+++ b/src/System.Threading.Tasks.Extensions/src/System/Runtime/CompilerServices/AsyncMethodBuilderAttribute.cs
@@ -13,10 +13,7 @@ namespace System.Runtime.CompilerServices
{
/// <summary>Initializes the <see cref="AsyncMethodBuilderAttribute"/>.</summary>
/// <param name="builderType">The <see cref="Type"/> of the associated builder.</param>
- public AsyncMethodBuilderAttribute(Type builderType)
- {
- BuilderType = builderType;
- }
+ public AsyncMethodBuilderAttribute(Type builderType) => BuilderType = builderType;
/// <summary>Gets the <see cref="Type"/> of the associated builder.</summary>
public Type BuilderType { get; }
diff --git a/src/System.Threading.Tasks.Extensions/src/System/Runtime/CompilerServices/AsyncValueTaskMethodBuilder.cs b/src/System.Threading.Tasks.Extensions/src/System/Runtime/CompilerServices/AsyncValueTaskMethodBuilder.cs
index 6e1c3392ad..e4c40a2abb 100644
--- a/src/System.Threading.Tasks.Extensions/src/System/Runtime/CompilerServices/AsyncValueTaskMethodBuilder.cs
+++ b/src/System.Threading.Tasks.Extensions/src/System/Runtime/CompilerServices/AsyncValueTaskMethodBuilder.cs
@@ -30,10 +30,8 @@ namespace System.Runtime.CompilerServices
/// <summary>Begins running the builder with the associated state machine.</summary>
/// <typeparam name="TStateMachine">The type of the state machine.</typeparam>
/// <param name="stateMachine">The state machine instance, passed by reference.</param>
- public void Start<TStateMachine>(ref TStateMachine stateMachine) where TStateMachine : IAsyncStateMachine
- {
+ public void Start<TStateMachine>(ref TStateMachine stateMachine) where TStateMachine : IAsyncStateMachine =>
_methodBuilder.Start(ref stateMachine); // will provide the right ExecutionContext semantics
- }
/// <summary>Associates the builder with the specified state machine.</summary>
/// <param name="stateMachine">The state machine instance to associate with the builder.</param>
diff --git a/src/System.Threading.Tasks.Extensions/src/System/Runtime/CompilerServices/ConfiguredValueTaskAwaitable.cs b/src/System.Threading.Tasks.Extensions/src/System/Runtime/CompilerServices/ConfiguredValueTaskAwaitable.cs
index 870dac6e94..0c2d61db31 100644
--- a/src/System.Threading.Tasks.Extensions/src/System/Runtime/CompilerServices/ConfiguredValueTaskAwaitable.cs
+++ b/src/System.Threading.Tasks.Extensions/src/System/Runtime/CompilerServices/ConfiguredValueTaskAwaitable.cs
@@ -29,10 +29,8 @@ namespace System.Runtime.CompilerServices
}
/// <summary>Returns an awaiter for this <see cref="ConfiguredValueTaskAwaitable{TResult}"/> instance.</summary>
- public ConfiguredValueTaskAwaiter GetAwaiter()
- {
- return new ConfiguredValueTaskAwaiter(_value, _continueOnCapturedContext);
- }
+ public ConfiguredValueTaskAwaiter GetAwaiter() =>
+ new ConfiguredValueTaskAwaiter(_value, _continueOnCapturedContext);
/// <summary>Provides an awaiter for a <see cref="ConfiguredValueTaskAwaitable{TResult}"/>.</summary>
[StructLayout(LayoutKind.Auto)]
@@ -53,27 +51,21 @@ namespace System.Runtime.CompilerServices
}
/// <summary>Gets whether the <see cref="ConfiguredValueTaskAwaitable{TResult}"/> has completed.</summary>
- public bool IsCompleted { get { return _value.IsCompleted; } }
+ public bool IsCompleted => _value.IsCompleted;
/// <summary>Gets the result of the ValueTask.</summary>
- public TResult GetResult()
- {
- return _value._task == null ?
+ public TResult GetResult() =>
+ _value._task == null ?
_value._result :
_value._task.GetAwaiter().GetResult();
- }
/// <summary>Schedules the continuation action for the <see cref="ConfiguredValueTaskAwaitable{TResult}"/>.</summary>
- public void OnCompleted(Action continuation)
- {
+ public void OnCompleted(Action continuation) =>
_value.AsTask().ConfigureAwait(_continueOnCapturedContext).GetAwaiter().OnCompleted(continuation);
- }
/// <summary>Schedules the continuation action for the <see cref="ConfiguredValueTaskAwaitable{TResult}"/>.</summary>
- public void UnsafeOnCompleted(Action continuation)
- {
+ public void UnsafeOnCompleted(Action continuation) =>
_value.AsTask().ConfigureAwait(_continueOnCapturedContext).GetAwaiter().UnsafeOnCompleted(continuation);
- }
}
}
}
diff --git a/src/System.Threading.Tasks.Extensions/src/System/Runtime/CompilerServices/ValueTaskAwaiter.cs b/src/System.Threading.Tasks.Extensions/src/System/Runtime/CompilerServices/ValueTaskAwaiter.cs
index 39459067f8..ee9578c7cc 100644
--- a/src/System.Threading.Tasks.Extensions/src/System/Runtime/CompilerServices/ValueTaskAwaiter.cs
+++ b/src/System.Threading.Tasks.Extensions/src/System/Runtime/CompilerServices/ValueTaskAwaiter.cs
@@ -15,29 +15,23 @@ namespace System.Runtime.CompilerServices
/// <summary>Initializes the awaiter.</summary>
/// <param name="value">The value to be awaited.</param>
- internal ValueTaskAwaiter(ValueTask<TResult> value) { _value = value; }
+ internal ValueTaskAwaiter(ValueTask<TResult> value) => _value = value;
/// <summary>Gets whether the <see cref="ValueTask{TResult}"/> has completed.</summary>
- public bool IsCompleted { get { return _value.IsCompleted; } }
+ public bool IsCompleted => _value.IsCompleted;
/// <summary>Gets the result of the ValueTask.</summary>
- public TResult GetResult()
- {
- return _value._task == null ?
+ public TResult GetResult() =>
+ _value._task == null ?
_value._result :
_value._task.GetAwaiter().GetResult();
- }
/// <summary>Schedules the continuation action for this ValueTask.</summary>
- public void OnCompleted(Action continuation)
- {
+ public void OnCompleted(Action continuation) =>
_value.AsTask().ConfigureAwait(continueOnCapturedContext: true).GetAwaiter().OnCompleted(continuation);
- }
/// <summary>Schedules the continuation action for this ValueTask.</summary>
- public void UnsafeOnCompleted(Action continuation)
- {
+ public void UnsafeOnCompleted(Action continuation) =>
_value.AsTask().ConfigureAwait(continueOnCapturedContext: true).GetAwaiter().UnsafeOnCompleted(continuation);
- }
}
}
diff --git a/src/System.Threading.Tasks.Extensions/src/System/Threading/Tasks/ValueTask.cs b/src/System.Threading.Tasks.Extensions/src/System/Threading/Tasks/ValueTask.cs
index e3542aa8ba..452424a91a 100644
--- a/src/System.Threading.Tasks.Extensions/src/System/Threading/Tasks/ValueTask.cs
+++ b/src/System.Threading.Tasks.Extensions/src/System/Threading/Tasks/ValueTask.cs
@@ -71,94 +71,70 @@ namespace System.Threading.Tasks
/// <param name="task">The task.</param>
public ValueTask(Task<TResult> task)
{
- if (task == null)
- {
- throw new ArgumentNullException(nameof(task));
- }
-
- _task = task;
+ _task = task ?? throw new ArgumentNullException(nameof(task));
_result = default(TResult);
}
/// <summary>Returns the hash code for this instance.</summary>
- public override int GetHashCode()
- {
- return
- _task != null ? _task.GetHashCode() :
- _result != null ? _result.GetHashCode() :
- 0;
- }
+ public override int GetHashCode() =>
+ _task != null ? _task.GetHashCode() :
+ _result != null ? _result.GetHashCode() :
+ 0;
/// <summary>Returns a value indicating whether this value is equal to a specified <see cref="object"/>.</summary>
- public override bool Equals(object obj)
- {
- return
- obj is ValueTask<TResult> &&
- Equals((ValueTask<TResult>)obj);
- }
+ public override bool Equals(object obj) =>
+ obj is ValueTask<TResult> &&
+ Equals((ValueTask<TResult>)obj);
/// <summary>Returns a value indicating whether this value is equal to a specified <see cref="ValueTask{TResult}"/> value.</summary>
- public bool Equals(ValueTask<TResult> other)
- {
- return _task != null || other._task != null ?
+ public bool Equals(ValueTask<TResult> other) =>
+ _task != null || other._task != null ?
_task == other._task :
EqualityComparer<TResult>.Default.Equals(_result, other._result);
- }
/// <summary>Returns a value indicating whether two <see cref="ValueTask{TResult}"/> values are equal.</summary>
- public static bool operator==(ValueTask<TResult> left, ValueTask<TResult> right)
- {
- return left.Equals(right);
- }
+ public static bool operator==(ValueTask<TResult> left, ValueTask<TResult> right) =>
+ left.Equals(right);
/// <summary>Returns a value indicating whether two <see cref="ValueTask{TResult}"/> values are not equal.</summary>
- public static bool operator!=(ValueTask<TResult> left, ValueTask<TResult> right)
- {
- return !left.Equals(right);
- }
+ public static bool operator!=(ValueTask<TResult> left, ValueTask<TResult> right) =>
+ !left.Equals(right);
/// <summary>
/// Gets a <see cref="Task{TResult}"/> object to represent this ValueTask. It will
/// either return the wrapped task object if one exists, or it'll manufacture a new
/// task object to represent the result.
/// </summary>
- public Task<TResult> AsTask()
- {
+ public Task<TResult> AsTask() =>
// Return the task if we were constructed from one, otherwise manufacture one. We don't
// cache the generated task into _task as it would end up changing both equality comparison
// and the hash code we generate in GetHashCode.
- return _task ?? Task.FromResult(_result);
- }
+ _task ?? Task.FromResult(_result);
/// <summary>Gets whether the <see cref="ValueTask{TResult}"/> represents a completed operation.</summary>
- public bool IsCompleted { get { return _task == null || _task.IsCompleted; } }
+ public bool IsCompleted => _task == null || _task.IsCompleted;
/// <summary>Gets whether the <see cref="ValueTask{TResult}"/> represents a successfully completed operation.</summary>
- public bool IsCompletedSuccessfully { get { return _task == null || _task.Status == TaskStatus.RanToCompletion; } }
+ public bool IsCompletedSuccessfully => _task == null || _task.Status == TaskStatus.RanToCompletion;
/// <summary>Gets whether the <see cref="ValueTask{TResult}"/> represents a failed operation.</summary>
- public bool IsFaulted { get { return _task != null && _task.IsFaulted; } }
+ public bool IsFaulted => _task != null && _task.IsFaulted;
/// <summary>Gets whether the <see cref="ValueTask{TResult}"/> represents a canceled operation.</summary>
- public bool IsCanceled { get { return _task != null && _task.IsCanceled; } }
+ public bool IsCanceled => _task != null && _task.IsCanceled;
/// <summary>Gets the result.</summary>
- public TResult Result { get { return _task == null ? _result : _task.GetAwaiter().GetResult(); } }
+ public TResult Result => _task == null ? _result : _task.GetAwaiter().GetResult();
/// <summary>Gets an awaiter for this value.</summary>
- public ValueTaskAwaiter<TResult> GetAwaiter()
- {
- return new ValueTaskAwaiter<TResult>(this);
- }
+ public ValueTaskAwaiter<TResult> GetAwaiter() => new ValueTaskAwaiter<TResult>(this);
/// <summary>Configures an awaiter for this value.</summary>
/// <param name="continueOnCapturedContext">
/// true to attempt to marshal the continuation back to the captured context; otherwise, false.
/// </param>
- public ConfiguredValueTaskAwaitable<TResult> ConfigureAwait(bool continueOnCapturedContext)
- {
- return new ConfiguredValueTaskAwaitable<TResult>(this, continueOnCapturedContext: continueOnCapturedContext);
- }
+ public ConfiguredValueTaskAwaitable<TResult> ConfigureAwait(bool continueOnCapturedContext) =>
+ new ConfiguredValueTaskAwaitable<TResult>(this, continueOnCapturedContext: continueOnCapturedContext);
/// <summary>Gets a string-representation of this <see cref="ValueTask{TResult}"/>.</summary>
public override string ToString()
diff --git a/src/System.Threading.Tasks.Extensions/tests/System.Threading.Tasks.Extensions.Tests.csproj b/src/System.Threading.Tasks.Extensions/tests/System.Threading.Tasks.Extensions.Tests.csproj
index 25e74041ef..faeeaf7283 100644
--- a/src/System.Threading.Tasks.Extensions/tests/System.Threading.Tasks.Extensions.Tests.csproj
+++ b/src/System.Threading.Tasks.Extensions/tests/System.Threading.Tasks.Extensions.Tests.csproj
@@ -10,9 +10,6 @@
<Compile Include="AsyncMethodBuilderAttributeTests.cs" />
<Compile Include="AsyncValueTaskMethodBuilderTests.cs" />
<Compile Include="ValueTaskTests.cs" />
- <Compile Include="$(CommonTestPath)\System\AssertExtensions.cs">
- <Link>Common\System\AssertExtensions.cs</Link>
- </Compile>
</ItemGroup>
<Import Project="$([MSBuild]::GetDirectoryNameOfFileAbove($(MSBuildThisFileDirectory), dir.targets))\dir.targets" />
</Project> \ No newline at end of file
diff --git a/src/System.Threading.Tasks.Parallel/tests/System.Threading.Tasks.Parallel.Tests.csproj b/src/System.Threading.Tasks.Parallel/tests/System.Threading.Tasks.Parallel.Tests.csproj
index eabdde3b83..3289100ab1 100644
--- a/src/System.Threading.Tasks.Parallel/tests/System.Threading.Tasks.Parallel.Tests.csproj
+++ b/src/System.Threading.Tasks.Parallel/tests/System.Threading.Tasks.Parallel.Tests.csproj
@@ -11,9 +11,6 @@
<StartupObject />
</PropertyGroup>
<ItemGroup>
- <Compile Include="$(CommonTestPath)\System\AssertExtensions.cs">
- <Link>Common\System\AssertExtensions.cs</Link>
- </Compile>
<Compile Include="$(CommonTestPath)\System\Diagnostics\Tracing\TestEventListener.cs">
<Link>Common\System\Diagnostics\Tracing\TestEventListener.cs</Link>
</Compile>
diff --git a/src/System.Threading.Tasks/tests/System.Threading.Tasks.Tests.csproj b/src/System.Threading.Tasks/tests/System.Threading.Tasks.Tests.csproj
index 04caa71bc9..309bc20112 100644
--- a/src/System.Threading.Tasks/tests/System.Threading.Tasks.Tests.csproj
+++ b/src/System.Threading.Tasks/tests/System.Threading.Tasks.Tests.csproj
@@ -52,9 +52,6 @@
<Link>CommonTest\System\Threading\ThreadPoolHelpers.cs</Link>
</Compile>
<Compile Include="Task\TaskDisposeTests.cs" />
- <Compile Include="$(CommonTestPath)\System\AssertExtensions.cs">
- <Link>Common\System\AssertExtensions.cs</Link>
- </Compile>
</ItemGroup>
<ItemGroup Condition="'$(TargetGroup)' == 'netcoreapp'">
<Compile Include="Task\TaskStatusTest.netcoreapp.cs" />
diff --git a/src/System.Threading.Thread/tests/System.Threading.Thread.Tests.csproj b/src/System.Threading.Thread/tests/System.Threading.Thread.Tests.csproj
index f8fe4f8c0b..45a5c81583 100644
--- a/src/System.Threading.Thread/tests/System.Threading.Thread.Tests.csproj
+++ b/src/System.Threading.Thread/tests/System.Threading.Thread.Tests.csproj
@@ -15,9 +15,6 @@
<Compile Include="ThreadTests.cs" />
</ItemGroup>
<ItemGroup>
- <Compile Include="$(CommonTestPath)\System\AssertExtensions.cs">
- <Link>Common\System\AssertExtensions.cs</Link>
- </Compile>
<Compile Include="$(CommonTestPath)\System\PlatformDetection.cs">
<Link>Common\System\PlatformDetection.cs</Link>
</Compile>
diff --git a/src/System.Threading/src/System.Threading.csproj b/src/System.Threading/src/System.Threading.csproj
index 9129770a05..4ee6403b27 100644
--- a/src/System.Threading/src/System.Threading.csproj
+++ b/src/System.Threading/src/System.Threading.csproj
@@ -7,10 +7,6 @@
<AllowUnsafeBlocks>true</AllowUnsafeBlocks>
<IsPartialFacadeAssembly>true</IsPartialFacadeAssembly>
</PropertyGroup>
- <PropertyGroup Condition="'$(TargetGroup)' == 'uapaot'">
- <!-- Remove this define after enabling CdsSyncEtwBCLProvider (https://github.com/dotnet/corefx/issues/16881) -->
- <DefineConstants>$(DefineConstants);uapaot</DefineConstants>
- </PropertyGroup>
<!-- Default configurations to help VS understand the configurations -->
<PropertyGroup Condition="'$(Configuration)|$(Platform)' == 'netcoreapp-Unix-Debug|AnyCPU'" />
<PropertyGroup Condition="'$(Configuration)|$(Platform)' == 'netcoreapp-Unix-Release|AnyCPU'" />
@@ -22,7 +18,7 @@
<PropertyGroup Condition="'$(Configuration)|$(Platform)' == 'uapaot-Windows_NT-Release|AnyCPU'" />
<ItemGroup>
<Compile Include="System\Threading\Barrier.cs" />
- <Compile Include="System\Threading\CDSsyncETWBCLProvider.cs" Condition="'$(TargetGroup)'!='uapaot'" />
+ <Compile Include="System\Threading\CDSsyncETWBCLProvider.cs" />
<Compile Include="System\Threading\CountdownEvent.cs" />
<Compile Include="System\Threading\HostExecutionContext.cs" />
<Compile Include="System\Threading\HostExecutionContextManager.cs" />
@@ -40,4 +36,4 @@
<ReferenceFromRuntime Include="System.Private.CoreLib" />
</ItemGroup>
<Import Project="$([MSBuild]::GetDirectoryNameOfFileAbove($(MSBuildThisFileDirectory), dir.targets))\dir.targets" />
-</Project> \ No newline at end of file
+</Project>
diff --git a/src/System.Threading/src/System/Threading/Barrier.cs b/src/System.Threading/src/System/Threading/Barrier.cs
index 20101346d1..13bcad0480 100644
--- a/src/System.Threading/src/System/Threading/Barrier.cs
+++ b/src/System.Threading/src/System/Threading/Barrier.cs
@@ -662,12 +662,10 @@ namespace System.Threading
{
if (SetCurrentTotal(currentTotal, 0, total, !sense))
{
-#if !uapaot
if (CdsSyncEtwBCLProvider.Log.IsEnabled())
{
CdsSyncEtwBCLProvider.Log.Barrier_PhaseFinished(sense, CurrentPhaseNumber);
}
-#endif
FinishPhase(sense);
return true;
}
diff --git a/src/System.Threading/tests/BarrierTests.cs b/src/System.Threading/tests/BarrierTests.cs
index f693b187d7..ea70f1f2a5 100644
--- a/src/System.Threading/tests/BarrierTests.cs
+++ b/src/System.Threading/tests/BarrierTests.cs
@@ -151,6 +151,36 @@ namespace System.Threading.Tests
Assert.Throws<ArgumentOutOfRangeException>(() => b.RemoveParticipants(2));
}
+ [Fact]
+ public static async Task RemovingWaitingParticipants()
+ {
+ Barrier b = new Barrier(4);
+ Task t = Task.Run(() =>
+ {
+ b.SignalAndWait();
+ });
+
+ while (b.ParticipantsRemaining > 3)
+ {
+ await Task.Delay(100);
+ }
+
+ b.RemoveParticipants(2); // Legal. Succeeds.
+
+ Assert.Equal(1, b.ParticipantsRemaining);
+
+ Assert.Throws<ArgumentOutOfRangeException>(() => b.RemoveParticipants(20)); // Too few total to remove
+
+ Assert.Equal(1, b.ParticipantsRemaining);
+
+ Assert.Throws<InvalidOperationException>(() => b.RemoveParticipants(2)); // Too few remaining to remove
+
+ Assert.Equal(1, b.ParticipantsRemaining);
+ b.RemoveParticipant(); // Barrier survives the incorrect removals, and we can still remove correctly.
+
+ await t; // t can now complete.
+ }
+
/// <summary>
/// Test AddParticipants
/// </summary>
@@ -223,6 +253,15 @@ namespace System.Threading.Tests
}
[Fact]
+ public static void SignalBarrierWithoutParticipants()
+ {
+ using (Barrier b = new Barrier(0))
+ {
+ Assert.Throws<InvalidOperationException>(() => b.SignalAndWait());
+ }
+ }
+
+ [Fact]
public static void RunBarrierTest7a()
{
for (int j = 0; j < 100; j++)
diff --git a/src/System.Threading/tests/EtwTests.cs b/src/System.Threading/tests/EtwTests.cs
index 552931aee1..65337021e8 100644
--- a/src/System.Threading/tests/EtwTests.cs
+++ b/src/System.Threading/tests/EtwTests.cs
@@ -10,7 +10,6 @@ namespace System.Threading.Tests
public class EtwTests
{
[Fact]
- [ActiveIssue("https://github.com/dotnet/corefx/issues/20592", TargetFrameworkMonikers.UapAot)]
public void TestEtw()
{
using (var listener = new TestEventListener("System.Threading.SynchronizationEventSource", EventLevel.Verbose))
diff --git a/src/System.Threading/tests/MutexTests.cs b/src/System.Threading/tests/MutexTests.cs
index 89a04c3ab8..e312522e63 100644
--- a/src/System.Threading/tests/MutexTests.cs
+++ b/src/System.Threading/tests/MutexTests.cs
@@ -222,7 +222,6 @@ namespace System.Threading.Tests
[Theory]
[MemberData(nameof(CrossProcess_NamedMutex_ProtectedFileAccessAtomic_MemberData))]
- [ActiveIssue(21276, TargetFrameworkMonikers.Uap)]
public void CrossProcess_NamedMutex_ProtectedFileAccessAtomic(string prefix)
{
ThreadTestHelpers.RunTestInBackgroundThread(() =>
diff --git a/src/System.Threading/tests/ReaderWriterLockTests.cs b/src/System.Threading/tests/ReaderWriterLockTests.cs
index 5b0b4b6e4a..5cf9c2a639 100644
--- a/src/System.Threading/tests/ReaderWriterLockTests.cs
+++ b/src/System.Threading/tests/ReaderWriterLockTests.cs
@@ -744,6 +744,31 @@ namespace System.Threading.Tests
trwl.Dispose();
}
+ [Fact]
+ public static void OverflowOnExcessiveNestedReaderLock()
+ {
+ ReaderWriterLock rwl = new ReaderWriterLock();
+ for (int i = 0; i != ushort.MaxValue; ++i)
+ {
+ rwl.AcquireReaderLock(0);
+ }
+
+ Assert.Throws<OverflowException>(() => rwl.AcquireReaderLock(0));
+ }
+
+ [Fact]
+ public static void OverflowOnExcessiveNestedWriterLock()
+ {
+ ReaderWriterLock rwl = new ReaderWriterLock();
+ for (int i = 0; i != ushort.MaxValue; ++i)
+ {
+ rwl.AcquireWriterLock(0);
+ }
+
+ Assert.Throws<OverflowException>(() => rwl.AcquireWriterLock(0));
+ }
+
+
private class TestReaderWriterLock : IDisposable
{
private const int InvalidThreadID = -1;
diff --git a/src/System.Threading/tests/System.Threading.Tests.csproj b/src/System.Threading/tests/System.Threading.Tests.csproj
index c49ee97be1..173ba92d48 100644
--- a/src/System.Threading/tests/System.Threading.Tests.csproj
+++ b/src/System.Threading/tests/System.Threading.Tests.csproj
@@ -37,9 +37,6 @@
<Compile Include="XunitAssemblyAttributes.cs" />
<Compile Include="ExecutionContextTests.cs" />
<Compile Include="SynchronizationContextTests.cs" />
- <Compile Include="$(CommonTestPath)\System\AssertExtensions.cs">
- <Link>Common\System\AssertExtensions.cs</Link>
- </Compile>
<Compile Include="$(CommonTestPath)\System\Diagnostics\Tracing\TestEventListener.cs">
<Link>CommonTest\System\Diagnostics\Tracing\TestEventListener.cs</Link>
</Compile>
diff --git a/src/System.Transactions.Local/tests/System.Transactions.Local.Tests.csproj b/src/System.Transactions.Local/tests/System.Transactions.Local.Tests.csproj
index abba6dd7cf..097521406a 100644
--- a/src/System.Transactions.Local/tests/System.Transactions.Local.Tests.csproj
+++ b/src/System.Transactions.Local/tests/System.Transactions.Local.Tests.csproj
@@ -18,9 +18,6 @@
<Compile Include="HelperFunctions.cs" />
<Compile Include="TestEnlistments.cs" />
<Compile Include="TransactionTracingEventListener.cs" />
- <Compile Include="$(CommonTestPath)\System\AssertExtensions.cs">
- <Link>Common\System\AssertExtensions.cs</Link>
- </Compile>
</ItemGroup>
<ItemGroup>
<EmbeddedResource Include="Resources\$(AssemblyName).rd.xml" />
diff --git a/src/System.ValueTuple/pkg/System.ValueTuple.pkgproj b/src/System.ValueTuple/pkg/System.ValueTuple.pkgproj
index c4007e14f2..82167fa9be 100644
--- a/src/System.ValueTuple/pkg/System.ValueTuple.pkgproj
+++ b/src/System.ValueTuple/pkg/System.ValueTuple.pkgproj
@@ -8,7 +8,7 @@
<ProjectReference Include="..\src\System.ValueTuple.csproj" />
<InboxOnTargetFramework Include="netstandard2.0" />
<InboxOnTargetFramework Include="netcoreapp2.0" />
- <InboxOnTargetFramework Include="uap10.1" />
+ <InboxOnTargetFramework Include="$(UAPvNextTFM)" />
<InboxOnTargetFramework Include="$(AllXamarinFrameworks)" />
</ItemGroup>
<Import Project="$([MSBuild]::GetDirectoryNameOfFileAbove($(MSBuildThisFileDirectory), dir.targets))\dir.targets" />
diff --git a/src/System.ValueTuple/tests/System.ValueTuple.Tests.csproj b/src/System.ValueTuple/tests/System.ValueTuple.Tests.csproj
index f43c2518b4..b0fb644dc2 100644
--- a/src/System.ValueTuple/tests/System.ValueTuple.Tests.csproj
+++ b/src/System.ValueTuple/tests/System.ValueTuple.Tests.csproj
@@ -17,9 +17,6 @@
<Compile Include="ExtensionsTests.cs" />
<Compile Include="TupleTests.cs" />
<Compile Include="ValueTupleTests.cs" />
- <Compile Include="$(CommonTestPath)\System\AssertExtensions.cs">
- <Link>Common\System\AssertExtensions.cs</Link>
- </Compile>
<Compile Include="$(CommonTestPath)\System\PlatformDetection.cs">
<Link>CommonTest\System\PlatformDetection.cs</Link>
</Compile>
diff --git a/tools-local/targetgroups.props b/tools-local/targetgroups.props
index 730b39bf6d..6b65af586d 100644
--- a/tools-local/targetgroups.props
+++ b/tools-local/targetgroups.props
@@ -17,36 +17,36 @@
<Imports>netcore50</Imports>
<CompatibleWith>netstandard1.4</CompatibleWith>
</TargetGroups>
- <TargetGroups Include="uap101aot">
+ <TargetGroups Include="uapvnextaot">
<PackageTargetRuntimeSuffix>aot</PackageTargetRuntimeSuffix>
- <NuGetTargetMoniker>UAP,Version=v10.1</NuGetTargetMoniker>
- <NuGetTargetMonikerShort>uap10.1</NuGetTargetMonikerShort>
+ <NuGetTargetMoniker>$(UAPvNextTFMFull)</NuGetTargetMoniker>
+ <NuGetTargetMonikerShort>$(UAPvNextTFM)</NuGetTargetMonikerShort>
<UWPCompatible>true</UWPCompatible>
<Imports>netcore50aot</Imports>
- <CompatibleWith>uap101;netstandard2.0</CompatibleWith>
+ <CompatibleWith>uapvnext;netstandard2.0</CompatibleWith>
</TargetGroups>
- <TargetGroups Include="uap101">
- <NuGetTargetMoniker>UAP,Version=v10.1</NuGetTargetMoniker>
- <NuGetTargetMonikerShort>uap10.1</NuGetTargetMonikerShort>
+ <TargetGroups Include="uapvnext">
+ <NuGetTargetMoniker>$(UAPvNextTFMFull)</NuGetTargetMoniker>
+ <NuGetTargetMonikerShort>$(UAPvNextTFM)</NuGetTargetMonikerShort>
<UWPCompatible>true</UWPCompatible>
<Imports>netcore50</Imports>
<CompatibleWith>netstandard2.0</CompatibleWith>
</TargetGroups>
- <!-- uap is an alias for uap10.1 any/coreclr runtime -->
+ <!-- uap is an alias for uapvNext any/coreclr runtime -->
<TargetGroups Include="uap">
- <NuGetTargetMoniker>UAP,Version=v10.1</NuGetTargetMoniker>
- <NuGetTargetMonikerShort>uap10.1</NuGetTargetMonikerShort>
+ <NuGetTargetMoniker>$(UAPvNextTFMFull)</NuGetTargetMoniker>
+ <NuGetTargetMonikerShort>$(UAPvNextTFM)</NuGetTargetMonikerShort>
<UWPCompatible>true</UWPCompatible>
- <Imports>uap101</Imports>
+ <Imports>uapvnext</Imports>
<CompatibleWith>netstandard</CompatibleWith>
</TargetGroups>
- <!-- uapaot is an alias for uap10.1, aot runtime -->
+ <!-- uapaot is an alias for uapvNext, aot runtime -->
<TargetGroups Include="uapaot">
<PackageTargetRuntimeSuffix>aot</PackageTargetRuntimeSuffix>
- <NuGetTargetMoniker>UAP,Version=v10.1</NuGetTargetMoniker>
- <NuGetTargetMonikerShort>uap10.1</NuGetTargetMonikerShort>
+ <NuGetTargetMoniker>$(UAPvNextTFMFull)</NuGetTargetMoniker>
+ <NuGetTargetMonikerShort>$(UAPvNextTFM)</NuGetTargetMonikerShort>
<UWPCompatible>true</UWPCompatible>
- <Imports>uap101aot</Imports>
+ <Imports>uapvnextaot</Imports>
<CompatibleWith>uap;netstandard</CompatibleWith>
</TargetGroups>
<TargetGroups Include="netstandard1.0">