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
path: root/src
diff options
context:
space:
mode:
authorMarek Safar <marek.safar@gmail.com>2017-10-02 15:46:59 +0300
committerMarek Safar <marek.safar@gmail.com>2017-10-02 15:46:59 +0300
commit524e42629b39f500fb8ad5da467ece5256c38f31 (patch)
treeb60c4f5fdecb34aec2132f6338efed00179fafce /src
parenteed24cf38a93e59638405a4c92f610dca02be1ec (diff)
parent1525832151f05d790d7cd311ec87597e77fbf9fd (diff)
Merge remote-tracking branch 'upstream/master'
Diffstat (limited to 'src')
-rw-r--r--src/Common/src/Interop/Linux/procfs/Interop.ProcFsStat.cs11
-rw-r--r--src/Common/src/Interop/Unix/System.Native/Interop.ForkAndExecProcess.cs5
-rw-r--r--src/Common/src/Interop/Unix/System.Native/Interop.MountPoints.FormatInfo.cs162
-rw-r--r--src/Common/src/Interop/Windows/SChannel/UnmanagedCertificateContext.IntPtr.cs51
-rw-r--r--src/Common/src/Interop/Windows/SChannel/UnmanagedCertificateContext.cs33
-rw-r--r--src/Common/src/Interop/Windows/kernel32/Interop.CreateNamedPipeClient.Uap.cs46
-rw-r--r--src/Common/src/Interop/Windows/kernel32/Interop.FlushViewOfFile.cs4
-rw-r--r--src/Common/src/Interop/Windows/kernel32/Interop.UnmapViewOfFile.cs4
-rw-r--r--src/Common/src/System/Collections/Generic/LargeArrayBuilder.cs57
-rw-r--r--src/Common/src/System/Collections/Generic/SparseArrayBuilder.cs10
-rw-r--r--src/Common/src/System/Data/Common/MultipartIdentifier.cs2
-rw-r--r--src/Common/src/System/IO/ReadOnlyMemoryStream.cs155
-rw-r--r--src/Common/src/System/Net/Http/WinHttpException.cs12
-rw-r--r--src/Common/src/System/Net/Internals/IPAddressExtensions.cs8
-rw-r--r--src/Common/src/System/Net/SocketAddress.cs16
-rw-r--r--src/Common/src/System/Net/WebSockets/ManagedWebSocket.cs49
-rw-r--r--src/Common/src/System/Runtime/InteropServices/FunctionWrapper.Unix.cs12
-rw-r--r--src/Common/src/System/Runtime/InteropServices/FunctionWrapper.Windows.cs12
-rw-r--r--src/Common/src/System/Runtime/InteropServices/FunctionWrapper.cs78
-rw-r--r--src/Common/tests/System/Buffers/NativeOwnedMemory.cs110
-rw-r--r--src/Common/tests/System/DirectoryServices/LdapConfiguration.cs117
-rw-r--r--src/Common/tests/System/IO/DelegateStream.cs4
-rw-r--r--src/Common/tests/System/IO/StreamSpanExtensions.netstandard.cs19
-rw-r--r--src/Common/tests/System/Linq/SkipTakeData.cs5
-rw-r--r--src/Common/tests/System/Net/Sockets/TestSettings.cs2
-rw-r--r--src/Common/tests/System/Runtime/Serialization/Formatters/BinaryFormatterHelpers.cs37
-rw-r--r--src/Common/tests/System/Xml/DisableParallelization.cs6
-rw-r--r--src/Common/tests/System/Xml/ModuleCore/ModuleCore.csproj4
-rw-r--r--src/Common/tests/System/Xml/ModuleCore/XunitRunner.cs100
-rw-r--r--src/Common/tests/System/Xml/ModuleCore/XunitTestCase.cs36
-rw-r--r--src/Common/tests/System/Xml/ModuleCore/ctestbase.cs3
-rw-r--r--src/Common/tests/System/Xml/ModuleCore/ctestcase.cs38
-rw-r--r--src/Common/tests/System/Xml/ModuleCore/ctestmodule.cs23
-rw-r--r--src/Common/tests/System/Xml/ModuleCore/cvariation.cs15
-rw-r--r--src/Common/tests/System/Xml/XPath/FuncLocation/PathAxeComplexExprMatchesTests.cs2
-rw-r--r--src/CoreFx.Private.TestUtilities/ref/CoreFx.Private.TestUtilities.cs16
-rw-r--r--src/CoreFx.Private.TestUtilities/src/CoreFx.Private.TestUtilities.csproj1
-rw-r--r--src/CoreFx.Private.TestUtilities/src/System/Diagnostics/RemoteExecutorTestBase.cs11
-rw-r--r--src/CoreFx.Private.TestUtilities/src/System/PlatformDetection.Unix.cs87
-rw-r--r--src/CoreFx.Private.TestUtilities/src/System/PlatformDetection.Windows.cs87
-rw-r--r--src/CoreFx.Private.TestUtilities/src/System/PlatformDetection.cs10
-rw-r--r--src/Microsoft.CSharp/src/Microsoft.CSharp.csproj1
-rw-r--r--src/Microsoft.CSharp/src/Microsoft/CSharp/RuntimeBinder/Errors/ErrorCode.cs6
-rw-r--r--src/Microsoft.CSharp/src/Microsoft/CSharp/RuntimeBinder/Errors/ErrorFacts.cs18
-rw-r--r--src/Microsoft.CSharp/src/Microsoft/CSharp/RuntimeBinder/Errors/UserStringBuilder.cs32
-rw-r--r--src/Microsoft.CSharp/src/Microsoft/CSharp/RuntimeBinder/Semantics/Conversion.cs196
-rw-r--r--src/Microsoft.CSharp/src/Microsoft/CSharp/RuntimeBinder/Semantics/Declarations/AggregateDeclaration.cs2
-rw-r--r--src/Microsoft.CSharp/src/Microsoft/CSharp/RuntimeBinder/Semantics/ExprFactory.cs3
-rw-r--r--src/Microsoft.CSharp/src/Microsoft/CSharp/RuntimeBinder/Semantics/ExpressionKind.cs2
-rw-r--r--src/Microsoft.CSharp/src/Microsoft/CSharp/RuntimeBinder/Semantics/ImplicitConversion.cs11
-rw-r--r--src/Microsoft.CSharp/src/Microsoft/CSharp/RuntimeBinder/Semantics/MethodTypeInferrer.cs2
-rw-r--r--src/Microsoft.CSharp/src/Microsoft/CSharp/RuntimeBinder/Semantics/PredefinedMembers.cs45
-rw-r--r--src/Microsoft.CSharp/src/Microsoft/CSharp/RuntimeBinder/Semantics/Tree/MethodReference.cs24
-rw-r--r--src/Microsoft.CSharp/src/Microsoft/CSharp/RuntimeBinder/Semantics/Tree/Visitors/ExprVisitorBase.cs7
-rw-r--r--src/Microsoft.CSharp/src/Microsoft/CSharp/RuntimeBinder/Semantics/Tree/Visitors/ExpressionTreeRewriter.cs67
-rw-r--r--src/Microsoft.CSharp/src/Microsoft/CSharp/RuntimeBinder/Semantics/TypeBind.cs23
-rw-r--r--src/Microsoft.CSharp/src/Microsoft/CSharp/RuntimeBinder/Semantics/Types/ErrorType.cs18
-rw-r--r--src/Microsoft.CSharp/src/Microsoft/CSharp/RuntimeBinder/Semantics/Types/Type.cs5
-rw-r--r--src/Microsoft.CSharp/src/Microsoft/CSharp/RuntimeBinder/Semantics/Types/TypeFactory.cs4
-rw-r--r--src/Microsoft.CSharp/src/Microsoft/CSharp/RuntimeBinder/Semantics/Types/TypeManager.cs112
-rw-r--r--src/Microsoft.CSharp/src/Microsoft/CSharp/RuntimeBinder/Semantics/Types/TypeTable.cs41
-rw-r--r--src/Microsoft.CSharp/src/MultilingualResources/Microsoft.CSharp.de.xlf24
-rw-r--r--src/Microsoft.CSharp/src/MultilingualResources/Microsoft.CSharp.es.xlf24
-rw-r--r--src/Microsoft.CSharp/src/MultilingualResources/Microsoft.CSharp.fr.xlf24
-rw-r--r--src/Microsoft.CSharp/src/MultilingualResources/Microsoft.CSharp.it.xlf24
-rw-r--r--src/Microsoft.CSharp/src/MultilingualResources/Microsoft.CSharp.ja.xlf24
-rw-r--r--src/Microsoft.CSharp/src/MultilingualResources/Microsoft.CSharp.ko.xlf24
-rw-r--r--src/Microsoft.CSharp/src/MultilingualResources/Microsoft.CSharp.ru.xlf24
-rw-r--r--src/Microsoft.CSharp/src/MultilingualResources/Microsoft.CSharp.zh-Hans.xlf24
-rw-r--r--src/Microsoft.CSharp/src/MultilingualResources/Microsoft.CSharp.zh-Hant.xlf24
-rw-r--r--src/Microsoft.CSharp/src/Resources/Strings.de.resx18
-rw-r--r--src/Microsoft.CSharp/src/Resources/Strings.es.resx18
-rw-r--r--src/Microsoft.CSharp/src/Resources/Strings.fr.resx18
-rw-r--r--src/Microsoft.CSharp/src/Resources/Strings.it.resx18
-rw-r--r--src/Microsoft.CSharp/src/Resources/Strings.ja.resx18
-rw-r--r--src/Microsoft.CSharp/src/Resources/Strings.ko.resx18
-rw-r--r--src/Microsoft.CSharp/src/Resources/Strings.resx18
-rw-r--r--src/Microsoft.CSharp/src/Resources/Strings.ru.resx18
-rw-r--r--src/Microsoft.CSharp/src/Resources/Strings.zh-Hans.resx18
-rw-r--r--src/Microsoft.CSharp/src/Resources/Strings.zh-Hant.resx18
-rw-r--r--src/Microsoft.XmlSerializer.Generator/dir.props2
-rw-r--r--src/Microsoft.XmlSerializer.Generator/pkg/GenerateNupkgProps.targets32
-rw-r--r--src/Microsoft.XmlSerializer.Generator/pkg/Microsoft.XmlSerializer.Generator.pkgproj13
-rw-r--r--src/Microsoft.XmlSerializer.Generator/pkg/build/Microsoft.XmlSerializer.Generator.targets27
-rw-r--r--src/Microsoft.XmlSerializer.Generator/pkg/build/dotnet-Microsoft.XmlSerializer.Generator.runtimeconfig.json (renamed from src/Microsoft.XmlSerializer.Generator/src/Microsoft.XmlSerializer.Generator.runtimeconfig.json)3
-rw-r--r--src/Microsoft.XmlSerializer.Generator/pkg/build/prefercliruntime (renamed from src/Microsoft.XmlSerializer.Generator/src/prefercliruntime)0
-rw-r--r--src/Microsoft.XmlSerializer.Generator/src/GenerateThisAssemblyCs.targets52
-rw-r--r--src/Microsoft.XmlSerializer.Generator/src/Microsoft.XmlSerializer.Generator.csproj15
-rw-r--r--src/Microsoft.XmlSerializer.Generator/src/Resources/Microsoft.XmlSerializer.Generator.rd.xml11
-rw-r--r--src/Microsoft.XmlSerializer.Generator/src/Sgen.cs149
-rw-r--r--src/Microsoft.XmlSerializer.Generator/tests/Configurations.props2
-rw-r--r--src/Microsoft.XmlSerializer.Generator/tests/Microsoft.XmlSerializer.Generator.Tests.csproj57
-rw-r--r--src/Microsoft.XmlSerializer.Generator/tests/SGenTests.cs2
-rw-r--r--src/Native/Unix/System.Native/pal_networking.cpp25
-rw-r--r--src/Native/Unix/System.Security.Cryptography.Native/openssl.cpp3
-rw-r--r--src/Native/Unix/System.Security.Cryptography.Native/opensslshim.h2
-rw-r--r--src/Native/Unix/configure.cmake8
-rwxr-xr-xsrc/Native/build-native.sh18
-rw-r--r--src/System.Buffers/pkg/System.Buffers.pkgproj11
-rw-r--r--src/System.Buffers/src/Configurations.props6
-rw-r--r--src/System.CodeDom/src/Microsoft/CSharp/CSharpCodeGenerator.cs2
-rw-r--r--src/System.Collections.Concurrent/src/System/Collections/Concurrent/ConcurrentQueue.cs6
-rw-r--r--src/System.Collections.Immutable/pkg/System.Collections.Immutable.pkgproj11
-rw-r--r--src/System.Collections.Immutable/src/PEVerifyCompat.rsp1
-rw-r--r--src/System.Collections.Immutable/src/Resources/Strings.resx4
-rw-r--r--src/System.Collections.Immutable/src/System.Collections.Immutable.csproj1
-rw-r--r--src/System.Collections.Immutable/src/System/Collections/Immutable/ImmutableInterlocked.cs2
-rw-r--r--src/System.Collections/src/System/Collections/Generic/HashSet.cs34
-rw-r--r--src/System.Collections/src/System/Collections/Generic/SortedSet.cs593
-rw-r--r--src/System.Collections/tests/Generic/LinkedList/LinkedList.Generic.Tests.Find.cs10
-rw-r--r--src/System.Collections/tests/Generic/LinkedList/LinkedList.Generic.Tests.FindLast.cs10
-rw-r--r--src/System.ComponentModel.Annotations/ref/System.ComponentModel.Annotations.csproj5
-rw-r--r--src/System.ComponentModel.Annotations/src/System/ComponentModel/DataAnnotations/AssociationAttribute.cs53
-rw-r--r--src/System.ComponentModel.Annotations/src/System/ComponentModel/DataAnnotations/CompareAttribute.cs21
-rw-r--r--src/System.ComponentModel.Annotations/src/System/ComponentModel/DataAnnotations/CustomValidationAttribute.cs51
-rw-r--r--src/System.ComponentModel.Annotations/src/System/ComponentModel/DataAnnotations/DataTypeAttribute.cs4
-rw-r--r--src/System.ComponentModel.Annotations/src/System/ComponentModel/DataAnnotations/DisplayAttribute.cs105
-rw-r--r--src/System.ComponentModel.Annotations/src/System/ComponentModel/DataAnnotations/DisplayColumnAttribute.cs6
-rw-r--r--src/System.ComponentModel.Annotations/src/System/ComponentModel/DataAnnotations/DisplayFormatAttribute.cs13
-rw-r--r--src/System.ComponentModel.Annotations/src/System/ComponentModel/DataAnnotations/EditableAttribute.cs2
-rw-r--r--src/System.ComponentModel.Annotations/src/System/ComponentModel/DataAnnotations/EnumDataTypeAttribute.cs17
-rw-r--r--src/System.ComponentModel.Annotations/src/System/ComponentModel/DataAnnotations/FileExtensionsAttribute.cs27
-rw-r--r--src/System.ComponentModel.Annotations/src/System/ComponentModel/DataAnnotations/FilterUIHintAttribute.cs35
-rw-r--r--src/System.ComponentModel.Annotations/src/System/ComponentModel/DataAnnotations/LocalizableString.cs4
-rw-r--r--src/System.ComponentModel.Annotations/src/System/ComponentModel/DataAnnotations/MaxLengthAttribute.cs63
-rw-r--r--src/System.ComponentModel.Annotations/src/System/ComponentModel/DataAnnotations/MinLengthAttribute.cs22
-rw-r--r--src/System.ComponentModel.Annotations/src/System/ComponentModel/DataAnnotations/RangeAttribute.cs3
-rw-r--r--src/System.ComponentModel.Annotations/src/System/ComponentModel/DataAnnotations/RegularExpressionAttribute.cs2
-rw-r--r--src/System.ComponentModel.Annotations/src/System/ComponentModel/DataAnnotations/ScaffoldColumnAttribute.cs2
-rw-r--r--src/System.ComponentModel.Annotations/src/System/ComponentModel/DataAnnotations/Schema/ColumnAttribute.cs12
-rw-r--r--src/System.ComponentModel.Annotations/src/System/ComponentModel/DataAnnotations/Schema/DatabaseGeneratedAttribute.cs2
-rw-r--r--src/System.ComponentModel.Annotations/src/System/ComponentModel/DataAnnotations/Schema/ForeignKeyAttribute.cs9
-rw-r--r--src/System.ComponentModel.Annotations/src/System/ComponentModel/DataAnnotations/Schema/InversePropertyAttribute.cs10
-rw-r--r--src/System.ComponentModel.Annotations/src/System/ComponentModel/DataAnnotations/Schema/TableAttribute.cs12
-rw-r--r--src/System.ComponentModel.Annotations/src/System/ComponentModel/DataAnnotations/StringLengthAttribute.cs2
-rw-r--r--src/System.ComponentModel.Annotations/src/System/ComponentModel/DataAnnotations/UIHintAttribute.cs24
-rw-r--r--src/System.ComponentModel.Annotations/src/System/ComponentModel/DataAnnotations/ValidationAttribute.cs25
-rw-r--r--src/System.ComponentModel.Annotations/src/System/ComponentModel/DataAnnotations/ValidationAttributeStore.cs38
-rw-r--r--src/System.ComponentModel.Annotations/src/System/ComponentModel/DataAnnotations/ValidationContext.cs36
-rw-r--r--src/System.ComponentModel.Annotations/src/System/ComponentModel/DataAnnotations/ValidationException.cs4
-rw-r--r--src/System.ComponentModel.Annotations/src/System/ComponentModel/DataAnnotations/ValidationResult.cs27
-rw-r--r--src/System.ComponentModel.Annotations/src/System/ComponentModel/DataAnnotations/Validator.cs50
-rw-r--r--src/System.ComponentModel.Annotations/tests/MaxLengthAttributeTests.cs54
-rw-r--r--src/System.ComponentModel.Annotations/tests/MinLengthAttributeTests.cs19
-rw-r--r--src/System.ComponentModel.Annotations/tests/Schema/ColumnAttributeTests.cs1
-rw-r--r--src/System.ComponentModel.Annotations/tests/Schema/DatabaseGeneratedAttributeTests.cs1
-rw-r--r--src/System.ComponentModel.Primitives/src/System/ComponentModel/Component.cs2
-rw-r--r--src/System.ComponentModel.Primitives/src/System/ComponentModel/IComponent.cs2
-rw-r--r--src/System.ComponentModel.Primitives/tests/CategoryAttributeTests.cs1
-rw-r--r--src/System.ComponentModel.TypeConverter/src/System/ComponentModel/MarshalByValueComponent.cs2
-rw-r--r--src/System.ComponentModel.TypeConverter/src/System/ComponentModel/MaskedTextProvider.cs2
-rw-r--r--src/System.Configuration.ConfigurationManager/src/System/Configuration/ClientConfigPaths.cs2
-rw-r--r--src/System.Configuration.ConfigurationManager/src/System/Configuration/ConfigurationElement.cs2
-rw-r--r--src/System.Configuration.ConfigurationManager/src/System/Configuration/ConnectionStringSettingsCollection.cs4
-rw-r--r--src/System.Configuration.ConfigurationManager/src/System/Configuration/MgmtConfigurationRecord.cs4
-rw-r--r--src/System.Console/tests/NegativeTesting.cs4
-rw-r--r--src/System.Console/tests/WindowAndCursorProps.cs11
-rw-r--r--src/System.Data.Common/src/System/Data/DataTable.cs2
-rw-r--r--src/System.Data.Common/tests/System/Data/DataTableCollectionTest.cs4
-rw-r--r--src/System.Data.Common/tests/System/Data/DataTableReaderTest.cs2
-rw-r--r--src/System.Data.Common/tests/System/Data/SqlTypes/SqlMoneyTest.cs2
-rw-r--r--src/System.Data.DataSetExtensions/src/System/Data/TypedTableBase.cs2
-rw-r--r--src/System.Data.DataSetExtensions/tests/Mono/DataTableExtensionsTest.cs4
-rw-r--r--src/System.Data.DataSetExtensions/tests/Mono/EnumerableRowCollectionTest.cs14
-rw-r--r--src/System.Data.Odbc/dir.props2
-rw-r--r--src/System.Data.Odbc/pkg/System.Data.Odbc.pkgproj11
-rw-r--r--src/System.Data.Odbc/src/Configurations.props1
-rw-r--r--src/System.Data.Odbc/src/Resources/Strings.resx3
-rw-r--r--src/System.Data.Odbc/src/System.Data.Odbc.csproj3
-rw-r--r--src/System.Data.SqlClient/ref/System.Data.SqlClient.cs3
-rw-r--r--src/System.Data.SqlClient/ref/System.Data.SqlClient.csproj3
-rw-r--r--src/System.Data.SqlClient/src/System/Data/Common/DbConnectionOptions.cs6
-rw-r--r--src/System.Data.SqlClient/src/System/Data/ProviderBase/DbConnectionFactory.cs7
-rw-r--r--src/System.Data.SqlClient/src/System/Data/ProviderBase/DbConnectionPoolGroup.cs25
-rw-r--r--src/System.Data.SqlClient/src/System/Data/SqlClient/SqlCommand.cs4
-rw-r--r--src/System.Data.SqlClient/src/System/Data/SqlClient/SqlDataReader.cs4
-rw-r--r--src/System.Data.SqlClient/src/System/Data/SqlClient/SqlInternalConnectionTds.cs2
-rw-r--r--src/System.Data.SqlClient/src/System/Data/SqlClient/SqlParameter.cs21
-rw-r--r--src/System.Data.SqlClient/src/System/Data/SqlClient/TdsParser.cs6
-rw-r--r--src/System.Data.SqlClient/tests/FunctionalTests/SqlConnectionBasicTests.cs28
-rw-r--r--src/System.Data.SqlClient/tests/ManualTests/SQL/MirroringTest/ConnectionOnMirroringTest.cs97
-rw-r--r--src/System.Data.SqlClient/tests/ManualTests/SQL/ParameterTest/ParametersTest.cs32
-rw-r--r--src/System.Data.SqlClient/tests/ManualTests/SQL/UdtTest/UdtTest.cs20
-rw-r--r--src/System.Data.SqlClient/tests/ManualTests/System.Data.SqlClient.ManualTesting.Tests.csproj1
-rw-r--r--src/System.Data.SqlClient/tests/StressTests/System.Data.StressFramework/DataStressErrors.cs4
-rw-r--r--src/System.Diagnostics.DiagnosticSource/pkg/System.Diagnostics.DiagnosticSource.pkgproj10
-rw-r--r--src/System.Diagnostics.DiagnosticSource/src/DiagnosticSourceUsersGuide.md50
-rw-r--r--src/System.Diagnostics.DiagnosticSource/src/System/Diagnostics/DiagnosticSource.cs2
-rw-r--r--src/System.Diagnostics.DiagnosticSource/src/System/Diagnostics/DiagnosticSourceEventSource.cs2
-rw-r--r--src/System.Diagnostics.DiagnosticSource/tests/DiagnosticSourceTests.cs2
-rw-r--r--src/System.Diagnostics.DiagnosticSource/tests/HttpHandlerDiagnosticListenerTests.cs2
-rw-r--r--src/System.Diagnostics.FileVersionInfo/tests/System.Diagnostics.FileVersionInfo.Tests/System.Diagnostics.FileVersionInfo.Tests.csproj2
-rw-r--r--src/System.Diagnostics.Process/src/Resources/Strings.resx3
-rw-r--r--src/System.Diagnostics.Process/src/System/Diagnostics/Process.Linux.cs26
-rw-r--r--src/System.Diagnostics.Process/src/System/Diagnostics/Process.OSX.cs6
-rw-r--r--src/System.Diagnostics.Process/src/System/Diagnostics/Process.Unix.cs87
-rw-r--r--src/System.Diagnostics.Process/src/System/Diagnostics/ProcessManager.Linux.cs16
-rw-r--r--src/System.Diagnostics.Process/src/System/Diagnostics/ProcessModuleCollection.cs4
-rw-r--r--src/System.Diagnostics.Process/tests/ProcessTests.Unix.cs137
-rw-r--r--src/System.Diagnostics.Process/tests/ProcessTests.cs67
-rw-r--r--src/System.Diagnostics.Process/tests/System.Diagnostics.Process.Tests.csproj3
-rw-r--r--src/System.Diagnostics.StackTrace/tests/StackFrameTests.cs2
-rw-r--r--src/System.Diagnostics.Tracing/tests/BasicEventSourceTest/TestEventCounter.cs1
-rw-r--r--src/System.DirectoryServices.AccountManagement/src/System/DirectoryServices/AccountManagement/AD/ADStoreCtx.cs6
-rw-r--r--src/System.DirectoryServices.AccountManagement/src/System/DirectoryServices/AccountManagement/AD/ADStoreCtx_LoadStore.cs2
-rw-r--r--src/System.DirectoryServices.AccountManagement/src/System/DirectoryServices/AccountManagement/AD/SDSUtils.cs4
-rw-r--r--src/System.DirectoryServices.AccountManagement/src/System/DirectoryServices/AccountManagement/FindResultEnumerator.cs2
-rw-r--r--src/System.DirectoryServices.AccountManagement/src/System/DirectoryServices/AccountManagement/PrincipalCollection.cs2
-rw-r--r--src/System.DirectoryServices.AccountManagement/src/System/DirectoryServices/AccountManagement/SAM/SAMStoreCtx.cs6
-rw-r--r--src/System.DirectoryServices.AccountManagement/src/System/DirectoryServices/AccountManagement/SAM/SAMStoreCtx_LoadStore.cs2
-rw-r--r--src/System.DirectoryServices.AccountManagement/src/System/DirectoryServices/AccountManagement/StoreCtx.cs6
-rw-r--r--src/System.DirectoryServices.AccountManagement/src/System/DirectoryServices/AccountManagement/Utils.cs2
-rw-r--r--src/System.DirectoryServices.AccountManagement/tests/PrincipalContextTests.cs10
-rw-r--r--src/System.DirectoryServices.Protocols/src/System/DirectoryServices/Protocols/common/SearchResults.cs5
-rw-r--r--src/System.DirectoryServices/src/System/DirectoryServices/ActiveDirectory/Utils.cs2
-rw-r--r--src/System.DirectoryServices/tests/LDAP.Configuration.xml19
-rw-r--r--src/System.DirectoryServices/tests/System.DirectoryServices.Tests.csproj10
-rw-r--r--src/System.DirectoryServices/tests/System/DirectoryServices/ActiveDirectory/ActiveDirectoryInterSiteTransportTests.cs8
-rw-r--r--src/System.DirectoryServices/tests/System/DirectoryServices/ActiveDirectory/DomainControllerTests.cs10
-rw-r--r--src/System.DirectoryServices/tests/System/DirectoryServices/DirectoryServicesTests.cs155
-rw-r--r--src/System.Drawing.Common/System.Drawing.Common.sln11
-rw-r--r--src/System.Drawing.Common/src/MonoTODOAttribute.cs (renamed from src/System.Drawing.Common/src/Unix/MonoTODOAttribute.cs)0
-rw-r--r--src/System.Drawing.Common/src/System.Drawing.Common.csproj143
-rw-r--r--src/System.Drawing.Common/src/System/Drawing/Bitmap.Unix.cs (renamed from src/System.Drawing.Common/src/Unix/System.Drawing/Bitmap.cs)42
-rw-r--r--src/System.Drawing.Common/src/System/Drawing/Bitmap.Windows.cs (renamed from src/System.Drawing.Common/src/System/Drawing/Bitmap.cs)0
-rw-r--r--src/System.Drawing.Common/src/System/Drawing/BufferedGraphics.Unix.cs (renamed from src/System.Drawing.Common/src/Unix/System.Drawing/BufferedGraphics.cs)0
-rw-r--r--src/System.Drawing.Common/src/System/Drawing/BufferedGraphics.Windows.cs (renamed from src/System.Drawing.Common/src/System/Drawing/BufferedGraphics.cs)0
-rw-r--r--src/System.Drawing.Common/src/System/Drawing/BufferedGraphicsContext.Unix.cs (renamed from src/System.Drawing.Common/src/Unix/System.Drawing/BufferedGraphicsContext.cs)0
-rw-r--r--src/System.Drawing.Common/src/System/Drawing/BufferedGraphicsContext.Windows.cs (renamed from src/System.Drawing.Common/src/System/Drawing/BufferedGraphicsContext.cs)0
-rw-r--r--src/System.Drawing.Common/src/System/Drawing/BufferedGraphicsManager.Unix.cs (renamed from src/System.Drawing.Common/src/Unix/System.Drawing/BufferedGraphicsManager.cs)0
-rw-r--r--src/System.Drawing.Common/src/System/Drawing/BufferedGraphicsManager.Windows.cs (renamed from src/System.Drawing.Common/src/System/Drawing/BufferedGraphicsManager.cs)0
-rw-r--r--src/System.Drawing.Common/src/System/Drawing/Drawing2D/GraphicsPath.Unix.cs (renamed from src/System.Drawing.Common/src/Unix/System.Drawing.Drawing2D/GraphicsPath.cs)142
-rw-r--r--src/System.Drawing.Common/src/System/Drawing/Drawing2D/GraphicsPath.Windows.cs (renamed from src/System.Drawing.Common/src/System/Drawing/Drawing2D/GraphicsPath.cs)0
-rw-r--r--src/System.Drawing.Common/src/System/Drawing/Drawing2D/HatchBrush.cs5
-rw-r--r--src/System.Drawing.Common/src/System/Drawing/Drawing2D/LinearGradientBrush.cs27
-rw-r--r--src/System.Drawing.Common/src/System/Drawing/Drawing2D/Matrix.cs7
-rw-r--r--src/System.Drawing.Common/src/System/Drawing/Drawing2D/PathGradientBrush.cs232
-rw-r--r--src/System.Drawing.Common/src/System/Drawing/Font.Unix.cs (renamed from src/System.Drawing.Common/src/Unix/System.Drawing/Font.cs)108
-rw-r--r--src/System.Drawing.Common/src/System/Drawing/Font.Windows.cs (renamed from src/System.Drawing.Common/src/System/Drawing/Font.cs)0
-rw-r--r--src/System.Drawing.Common/src/System/Drawing/GdiPlusStreamHelper.Unix.cs330
-rw-r--r--src/System.Drawing.Common/src/System/Drawing/Gdiplus.cs2
-rw-r--r--src/System.Drawing.Common/src/System/Drawing/GdiplusNative.Unix.cs1669
-rw-r--r--src/System.Drawing.Common/src/System/Drawing/GdiplusNative.Windows.cs601
-rw-r--r--src/System.Drawing.Common/src/System/Drawing/GdiplusNative.cs699
-rw-r--r--src/System.Drawing.Common/src/System/Drawing/Graphics.Unix.cs319
-rw-r--r--src/System.Drawing.Common/src/System/Drawing/GraphicsUnit.cs (renamed from src/System.Drawing.Common/src/System/Drawing/Unit.cs)0
-rw-r--r--src/System.Drawing.Common/src/System/Drawing/Icon.Serializable.Unix.cs50
-rw-r--r--src/System.Drawing.Common/src/System/Drawing/Icon.Serializable.Windows.cs (renamed from src/System.Drawing.Common/src/System/Drawing/Icon.Serializable.cs)0
-rw-r--r--src/System.Drawing.Common/src/System/Drawing/Icon.Unix.cs (renamed from src/System.Drawing.Common/src/Unix/System.Drawing/Icon.cs)164
-rw-r--r--src/System.Drawing.Common/src/System/Drawing/Icon.Windows.cs (renamed from src/System.Drawing.Common/src/System/Drawing/Icon.cs)0
-rw-r--r--src/System.Drawing.Common/src/System/Drawing/Image.Unix.cs (renamed from src/System.Drawing.Common/src/Unix/System.Drawing/Image.cs)149
-rw-r--r--src/System.Drawing.Common/src/System/Drawing/Image.Windows.cs (renamed from src/System.Drawing.Common/src/System/Drawing/Image.cs)12
-rw-r--r--src/System.Drawing.Common/src/System/Drawing/ImageAnimator.Unix.cs (renamed from src/System.Drawing.Common/src/Unix/System.Drawing/ImageAnimator.cs)0
-rw-r--r--src/System.Drawing.Common/src/System/Drawing/ImageAnimator.Windows.cs (renamed from src/System.Drawing.Common/src/System/Drawing/ImageAnimator.cs)2
-rw-r--r--src/System.Drawing.Common/src/System/Drawing/ImageType.cs13
-rw-r--r--src/System.Drawing.Common/src/System/Drawing/Imaging/BitmapData.Unix.cs (renamed from src/System.Drawing.Common/src/Unix/System.Drawing.Imaging/BitmapData.cs)0
-rw-r--r--src/System.Drawing.Common/src/System/Drawing/Imaging/BitmapData.Windows.cs (renamed from src/System.Drawing.Common/src/System/Drawing/Imaging/BitmapData.cs)0
-rw-r--r--src/System.Drawing.Common/src/System/Drawing/Imaging/MetaHeader.Unix.cs (renamed from src/System.Drawing.Common/src/Unix/System.Drawing.Imaging/MetaHeader.cs)0
-rw-r--r--src/System.Drawing.Common/src/System/Drawing/Imaging/MetaHeader.Windows.cs (renamed from src/System.Drawing.Common/src/System/Drawing/Imaging/METAHEADER.cs)0
-rw-r--r--src/System.Drawing.Common/src/System/Drawing/Imaging/Metafile.Unix.cs (renamed from src/System.Drawing.Common/src/Unix/System.Drawing.Imaging/Metafile.cs)132
-rw-r--r--src/System.Drawing.Common/src/System/Drawing/Imaging/Metafile.Windows.cs (renamed from src/System.Drawing.Common/src/System/Drawing/Imaging/Metafile.cs)14
-rw-r--r--src/System.Drawing.Common/src/System/Drawing/Imaging/MetafileHeader.Unix.cs (renamed from src/System.Drawing.Common/src/Unix/System.Drawing.Imaging/MetafileHeader.cs)11
-rw-r--r--src/System.Drawing.Common/src/System/Drawing/Imaging/MetafileHeader.Windows.cs (renamed from src/System.Drawing.Common/src/System/Drawing/Imaging/MetafileHeader.cs)0
-rw-r--r--src/System.Drawing.Common/src/System/Drawing/LibX11Functions.cs50
-rw-r--r--src/System.Drawing.Common/src/System/Drawing/MarshallingHelpers.cs86
-rw-r--r--src/System.Drawing.Common/src/System/Drawing/NativeStructs.Unix.cs (renamed from src/System.Drawing.Common/src/Unix/System.Drawing/gdipStructs.cs)34
-rw-r--r--src/System.Drawing.Common/src/System/Drawing/Pen.cs47
-rw-r--r--src/System.Drawing.Common/src/System/Drawing/Printing/LibcupsNative.cs88
-rw-r--r--src/System.Drawing.Common/src/System/Drawing/Printing/PageSettings.Unix.cs (renamed from src/System.Drawing.Common/src/Unix/System.Drawing.Printing/PageSettings.cs)0
-rw-r--r--src/System.Drawing.Common/src/System/Drawing/Printing/PageSettings.Windows.cs (renamed from src/System.Drawing.Common/src/System/Drawing/Printing/PageSettings.cs)0
-rw-r--r--src/System.Drawing.Common/src/System/Drawing/Printing/PreviewPrintController.Unix.cs (renamed from src/System.Drawing.Common/src/Unix/System.Drawing.Printing/PreviewPrintController.cs)0
-rw-r--r--src/System.Drawing.Common/src/System/Drawing/Printing/PreviewPrintController.Windows.cs (renamed from src/System.Drawing.Common/src/System/Drawing/Printing/PreviewPrintController.cs)0
-rw-r--r--src/System.Drawing.Common/src/System/Drawing/Printing/PrintController.Unix.cs (renamed from src/System.Drawing.Common/src/Unix/System.Drawing.Printing/PrintController.cs)0
-rw-r--r--src/System.Drawing.Common/src/System/Drawing/Printing/PrintController.Windows.cs (renamed from src/System.Drawing.Common/src/System/Drawing/Printing/PrintController.cs)0
-rw-r--r--src/System.Drawing.Common/src/System/Drawing/Printing/PrintDocument.Unix.cs (renamed from src/System.Drawing.Common/src/Unix/System.Drawing.Printing/PrintDocument.cs)0
-rw-r--r--src/System.Drawing.Common/src/System/Drawing/Printing/PrintDocument.Windows.cs (renamed from src/System.Drawing.Common/src/System/Drawing/Printing/PrintDocument.cs)0
-rw-r--r--src/System.Drawing.Common/src/System/Drawing/Printing/PrintEventArgs.Unix.cs (renamed from src/System.Drawing.Common/src/Unix/System.Drawing.Printing/PrintEventArgs.cs)0
-rw-r--r--src/System.Drawing.Common/src/System/Drawing/Printing/PrintEventArgs.Windows.cs (renamed from src/System.Drawing.Common/src/System/Drawing/Printing/PrintEvent.cs)0
-rw-r--r--src/System.Drawing.Common/src/System/Drawing/Printing/PrintPageEventArgs.Unix.cs (renamed from src/System.Drawing.Common/src/Unix/System.Drawing.Printing/PrintPageEventArgs.cs)0
-rw-r--r--src/System.Drawing.Common/src/System/Drawing/Printing/PrintPageEventArgs.Windows.cs (renamed from src/System.Drawing.Common/src/System/Drawing/Printing/PrintPageEvent.cs)0
-rw-r--r--src/System.Drawing.Common/src/System/Drawing/Printing/PrinterSettings.Unix.cs (renamed from src/System.Drawing.Common/src/Unix/System.Drawing.Printing/PrinterSettings.cs)23
-rw-r--r--src/System.Drawing.Common/src/System/Drawing/Printing/PrinterSettings.Windows.cs (renamed from src/System.Drawing.Common/src/System/Drawing/Printing/PrinterSettings.cs)0
-rw-r--r--src/System.Drawing.Common/src/System/Drawing/Printing/PrintingServices.Unix.cs (renamed from src/System.Drawing.Common/src/Unix/System.Drawing.Printing/PrintingServicesUnix.cs)185
-rw-r--r--src/System.Drawing.Common/src/System/Drawing/Printing/StandardPrintController.Unix.cs (renamed from src/System.Drawing.Common/src/Unix/System.Drawing.Printing/StandardPrintController.cs)10
-rw-r--r--src/System.Drawing.Common/src/System/Drawing/SRDescriptionAttribute.cs (renamed from src/System.Drawing.Common/src/Unix/System.Drawing/SRDescriptionAttribute.cs)0
-rw-r--r--src/System.Drawing.Common/src/System/Drawing/SystemIcons.Unix.cs (renamed from src/System.Drawing.Common/src/Unix/System.Drawing/SystemIcons.cs)0
-rw-r--r--src/System.Drawing.Common/src/System/Drawing/SystemIcons.Windows.cs (renamed from src/System.Drawing.Common/src/System/Drawing/SystemIcons.cs)0
-rw-r--r--src/System.Drawing.Common/src/System/Drawing/TextureBrush.cs9
-rw-r--r--src/System.Drawing.Common/src/System/Drawing/ToolboxBitmapAttribute.Unix.cs (renamed from src/System.Drawing.Common/src/Unix/System.Drawing/ToolboxBitmapAttribute.cs)0
-rw-r--r--src/System.Drawing.Common/src/System/Drawing/macFunctions.cs (renamed from src/System.Drawing.Common/src/Unix/System.Drawing/macFunctions.cs)0
-rw-r--r--src/System.Drawing.Common/src/Unix/System.Drawing.Imaging/ImageFormat.cs259
-rw-r--r--src/System.Drawing.Common/src/Unix/System.Drawing.Printing/PrintingServices.cs162
-rw-r--r--src/System.Drawing.Common/src/Unix/System.Drawing.Printing/PrintingServicesWin32.cs743
-rw-r--r--src/System.Drawing.Common/src/Unix/System.Drawing/ColorTranslator.cs207
-rw-r--r--src/System.Drawing.Common/src/Unix/System.Drawing/ComIStreamMarshaler.cs718
-rw-r--r--src/System.Drawing.Common/src/Unix/System.Drawing/ComIStreamWrapper.cs199
-rw-r--r--src/System.Drawing.Common/src/Unix/System.Drawing/ContentAlignment.cs50
-rw-r--r--src/System.Drawing.Common/src/Unix/System.Drawing/FontFamily.cs245
-rw-r--r--src/System.Drawing.Common/src/Unix/System.Drawing/GraphicsUnit.cs44
-rw-r--r--src/System.Drawing.Common/src/Unix/System.Drawing/KnownColors.cs666
-rw-r--r--src/System.Drawing.Common/src/Unix/System.Drawing/SystemColors.cs208
-rw-r--r--src/System.Drawing.Common/src/Unix/System.Drawing/gdipEnums.cs120
-rw-r--r--src/System.Drawing.Common/src/Unix/System.Drawing/gdipFunctions.cs620
-rw-r--r--src/System.Drawing.Common/tests/BitmapTests.cs49
-rw-r--r--src/System.Drawing.Common/tests/ColorTranslatorTests.cs5
-rw-r--r--src/System.Drawing.Common/tests/Drawing2D/HatchBrushTests.cs7
-rw-r--r--src/System.Drawing.Common/tests/Drawing2D/LinearGradientBrushTests.cs75
-rw-r--r--src/System.Drawing.Common/tests/Drawing2D/MatrixTests.cs10
-rw-r--r--src/System.Drawing.Common/tests/Drawing2D/PathGradientBrushTests.cs41
-rw-r--r--src/System.Drawing.Common/tests/FontFamilyTests.cs10
-rw-r--r--src/System.Drawing.Common/tests/FontTests.cs2
-rw-r--r--src/System.Drawing.Common/tests/GraphicsTests.cs6
-rw-r--r--src/System.Drawing.Common/tests/Helpers.cs66
-rw-r--r--src/System.Drawing.Common/tests/IconTests.cs11
-rw-r--r--src/System.Drawing.Common/tests/Imaging/ImageAttributesTests.cs44
-rw-r--r--src/System.Drawing.Common/tests/Imaging/MetafileTests.cs290
-rw-r--r--src/System.Drawing.Common/tests/Printing/PrintDocumentTests.cs4
-rw-r--r--src/System.Drawing.Common/tests/Printing/PrinterSettingsTests.cs27
-rw-r--r--src/System.Drawing.Common/tests/System.Drawing.Common.Tests.csproj26
-rw-r--r--src/System.Drawing.Common/tests/SystemFontsTests.cs5
-rw-r--r--src/System.Drawing.Common/tests/Text/InstalledFontCollectionTests.cs6
-rw-r--r--src/System.Drawing.Common/tests/TextureBrushTests.cs4
-rw-r--r--src/System.Drawing.Common/tests/mono/System.Drawing.Imaging/BmpCodecTests.cs540
-rw-r--r--src/System.Drawing.Common/tests/mono/System.Drawing.Imaging/GifCodecTests.cs266
-rw-r--r--src/System.Drawing.Common/tests/mono/System.Drawing.Imaging/IconCodecTests.cs2103
-rw-r--r--src/System.Drawing.Common/tests/mono/System.Drawing.Imaging/JpegCodecTests.cs428
-rw-r--r--src/System.Drawing.Common/tests/mono/System.Drawing.Imaging/PngCodecTesst.cs686
-rw-r--r--src/System.Drawing.Common/tests/mono/System.Drawing.Imaging/TiffCodecTests.cs315
-rw-r--r--src/System.Drawing.Common/tests/mono/System.Drawing/BitmapTests.cs1583
-rw-r--r--src/System.Drawing.Common/tests/mono/System.Drawing/GraphicsTests.cs3251
-rw-r--r--src/System.Drawing.Common/tests/mono/System.Imaging/MetafileTest.cs485
-rw-r--r--src/System.Dynamic.Runtime/tests/Dynamic.NamedAndOptional/Conformance.dynamic.namedandoptional.decl.other.cs6
-rw-r--r--src/System.Globalization/tests/CultureInfo/CultureInfoCurrentCulture.cs4
-rw-r--r--src/System.Globalization/tests/NumberFormatInfo/NumberFormatInfoCurrencyDecimalDigits.cs4
-rw-r--r--src/System.Globalization/tests/NumberFormatInfo/NumberFormatInfoCurrencyGroupSizes.cs4
-rw-r--r--src/System.Globalization/tests/NumberFormatInfo/NumberFormatInfoCurrencyNegativePattern.cs4
-rw-r--r--src/System.Globalization/tests/NumberFormatInfo/NumberFormatInfoCurrencyPositivePattern.cs4
-rw-r--r--src/System.Globalization/tests/NumberFormatInfo/NumberFormatInfoCurrencySymbol.cs2
-rw-r--r--src/System.Globalization/tests/NumberFormatInfo/NumberFormatInfoCurrentInfo.cs10
-rw-r--r--src/System.Globalization/tests/NumberFormatInfo/NumberFormatInfoData.cs14
-rw-r--r--src/System.Globalization/tests/NumberFormatInfo/NumberFormatInfoGetInstance.cs4
-rw-r--r--src/System.Globalization/tests/NumberFormatInfo/NumberFormatInfoNegativeInfinitySymbol.cs4
-rw-r--r--src/System.Globalization/tests/NumberFormatInfo/NumberFormatInfoNegativeSign.cs2
-rw-r--r--src/System.Globalization/tests/NumberFormatInfo/NumberFormatInfoNumberDecimalDigits.cs2
-rw-r--r--src/System.Globalization/tests/NumberFormatInfo/NumberFormatInfoNumberGroupSizes.cs4
-rw-r--r--src/System.Globalization/tests/NumberFormatInfo/NumberFormatInfoNumberNegativePattern.cs2
-rw-r--r--src/System.Globalization/tests/NumberFormatInfo/NumberFormatInfoPercentGroupSizes.cs2
-rw-r--r--src/System.Globalization/tests/NumberFormatInfo/NumberFormatInfoPercentNegativePattern.cs6
-rw-r--r--src/System.Globalization/tests/NumberFormatInfo/NumberFormatInfoPercentPositivePattern.cs6
-rw-r--r--src/System.Globalization/tests/NumberFormatInfo/NumberFormatInfoPercentSymbol.cs2
-rw-r--r--src/System.Globalization/tests/NumberFormatInfo/NumberFormatInfoPositiveInfinitySymbol.cs4
-rw-r--r--src/System.Globalization/tests/NumberFormatInfo/NumberFormatInfoPositiveSign.cs2
-rw-r--r--src/System.IO.Compression/src/System/IO/Compression/DeflateManaged/OutputWindow.cs2
-rw-r--r--src/System.IO.Compression/src/System/IO/Compression/DeflateZLib/DeflateStream.cs88
-rw-r--r--src/System.IO.Compression/src/System/IO/Compression/DeflateZLib/Deflater.cs37
-rw-r--r--src/System.IO.Compression/src/System/IO/Compression/GZipStream.cs33
-rw-r--r--src/System.IO.Compression/src/System/IO/Compression/PositionPreservingWriteOnlyStreamWrapper.netcoreapp.cs9
-rw-r--r--src/System.IO.Compression/src/System/IO/Compression/ZipArchiveEntry.cs4
-rw-r--r--src/System.IO.Compression/tests/Configurations.props1
-rw-r--r--src/System.IO.Compression/tests/DeflateStreamTests.cs40
-rw-r--r--src/System.IO.Compression/tests/DeflateStreamTests.netcoreapp.cs24
-rw-r--r--src/System.IO.Compression/tests/System.IO.Compression.Tests.csproj5
-rw-r--r--src/System.IO.FileSystem.DriveInfo/tests/DriveInfo.Windows.Tests.cs6
-rw-r--r--src/System.IO.FileSystem.Watcher/src/PinvokeAnalyzerExceptionList.analyzerdata.uap3
-rw-r--r--src/System.IO.FileSystem.Watcher/src/System.IO.FileSystem.Watcher.csproj27
-rw-r--r--src/System.IO.FileSystem.Watcher/src/System/IO/FileSystemWatcher.Win32.cs2
-rw-r--r--src/System.IO.FileSystem.Watcher/tests/FileSystemWatcher.File.Create.cs3
-rw-r--r--src/System.IO.FileSystem.Watcher/tests/FileSystemWatcher.cs2
-rw-r--r--src/System.IO.FileSystem.Watcher/tests/FileSystemWatcher.unit.cs2
-rw-r--r--src/System.IO.FileSystem.Watcher/tests/Utility/FileSystemWatcherTest.cs4
-rw-r--r--src/System.IO.FileSystem/src/System.IO.FileSystem.csproj25
-rw-r--r--src/System.IO.FileSystem/src/System/IO/FromApp.Interop.cs150
-rw-r--r--src/System.IO.FileSystem/tests/Directory/Delete.cs5
-rw-r--r--src/System.IO.FileSystem/tests/File/Delete.cs6
-rw-r--r--src/System.IO.FileSystem/tests/FileStream/ReadWriteSpan.netcoreapp.cs147
-rw-r--r--src/System.IO.FileSystem/tests/FileSystemTest.cs2
-rw-r--r--src/System.IO.FileSystem/tests/PortedCommon/IOServices.cs2
-rw-r--r--src/System.IO.FileSystem/tests/System.IO.FileSystem.Tests.csproj3
-rw-r--r--src/System.IO.FileSystem/tests/WinRT_BrokeredFunctions.cs209
-rw-r--r--src/System.IO.IsolatedStorage/tests/System/IO/IsolatedStorage/HelperTests.cs2
-rw-r--r--src/System.IO.IsolatedStorage/tests/System/IO/IsolatedStorage/IsoStorageTest.cs2
-rw-r--r--src/System.IO.IsolatedStorage/tests/System/IO/IsolatedStorage/TestHelper.cs2
-rw-r--r--src/System.IO.MemoryMappedFiles/src/Microsoft/Win32/SafeMemoryMappedViewHandle.Windows.cs2
-rw-r--r--src/System.IO.MemoryMappedFiles/src/System.IO.MemoryMappedFiles.csproj1
-rw-r--r--src/System.IO.MemoryMappedFiles/src/System/IO/MemoryMappedFiles/MemoryMappedFile.Windows.cs10
-rw-r--r--src/System.IO.MemoryMappedFiles/src/System/IO/MemoryMappedFiles/MemoryMappedView.Windows.cs28
-rw-r--r--src/System.IO.MemoryMappedFiles/tests/MemoryMappedFile.CrossProcess.cs2
-rw-r--r--src/System.IO.Packaging/src/System/IO/Packaging/ContentType.cs2
-rw-r--r--src/System.IO.Pipes/src/PinvokeAnalyzerExceptionList.analyzerdata3
-rw-r--r--src/System.IO.Pipes/src/System.IO.Pipes.csproj18
-rw-r--r--src/System.IO.Pipes/src/System/IO/Pipes/ConnectionCompletionSource.cs2
-rw-r--r--src/System.IO.Pipes/src/System/IO/Pipes/PipeCompletionSource.cs13
-rw-r--r--src/System.IO.Pipes/src/System/IO/Pipes/PipeStream.Unix.cs72
-rw-r--r--src/System.IO.Pipes/src/System/IO/Pipes/PipeStream.Windows.cs8
-rw-r--r--src/System.IO.Pipes/src/System/IO/Pipes/PipeStream.cs59
-rw-r--r--src/System.IO.Pipes/src/System/IO/Pipes/ReadWriteCompletionSource.cs7
-rw-r--r--src/System.IO.Pipes/tests/AnonymousPipeTests/AnonymousPipeTest.Specific.cs2
-rw-r--r--src/System.IO.Pipes/tests/Configurations.props2
-rw-r--r--src/System.IO.Pipes/tests/NamedPipeTests/NamedPipeTest.CrossProcess.cs2
-rw-r--r--src/System.IO.Pipes/tests/NamedPipeTests/NamedPipeTest.Read.cs6
-rw-r--r--src/System.IO.Pipes/tests/NamedPipeTests/NamedPipeTest.RunAsClient.Windows.cs2
-rw-r--r--src/System.IO.Pipes/tests/NamedPipeTests/NamedPipeTest.Specific.cs103
-rw-r--r--src/System.IO.Pipes/tests/NamedPipeTests/NamedPipeTest.Write.cs2
-rw-r--r--src/System.IO.Pipes/tests/PipeTest.Read.cs9
-rw-r--r--src/System.IO.Pipes/tests/PipeTest.Read.netcoreapp.cs134
-rw-r--r--src/System.IO.Pipes/tests/PipeTest.Write.cs11
-rw-r--r--src/System.IO.Pipes/tests/PipeTest.Write.netcoreapp.cs84
-rw-r--r--src/System.IO.Pipes/tests/PipeTestBase.cs2
-rw-r--r--src/System.IO.Pipes/tests/System.IO.Pipes.Tests.csproj8
-rw-r--r--src/System.IO.Ports/ref/System.IO.Ports.csproj3
-rw-r--r--src/System.IO.Ports/src/PinvokeAnalyzerExceptionList.analyzerdata3
-rw-r--r--src/System.IO.Ports/src/PinvokeAnalyzerExceptionList.analyzerdata.netstandard2
-rw-r--r--src/System.IO.Ports/src/System.IO.Ports.csproj8
-rw-r--r--src/System.IO.Ports/tests/SerialPort/ReadTo.cs4
-rw-r--r--src/System.IO.Ports/tests/SerialPort/Read_byte_int_int.cs4
-rw-r--r--src/System.IO.Ports/tests/SerialPort/Read_char_int_int.cs4
-rw-r--r--src/System.IO.Ports/tests/SerialPort/Write_byte_int_int.cs4
-rw-r--r--src/System.IO.Ports/tests/SerialPort/Write_char_int_int.cs4
-rw-r--r--src/System.IO.Ports/tests/SerialStream/BeginRead.cs4
-rw-r--r--src/System.IO.Ports/tests/SerialStream/BeginWrite.cs4
-rw-r--r--src/System.IO.Ports/tests/SerialStream/Read_byte_int_int.cs4
-rw-r--r--src/System.IO.Ports/tests/SerialStream/Write_byte_int_int.cs4
-rw-r--r--src/System.IO.UnmanagedMemoryStream/tests/UmsReadWrite.netcoreapp.cs8
-rw-r--r--src/System.IO/tests/BinaryReader/BinaryReaderTests.cs60
-rw-r--r--src/System.IO/tests/BinaryReader/BinaryReaderTests.netcoreapp.cs97
-rw-r--r--src/System.IO/tests/BufferedStream/BufferedStreamTests.cs43
-rw-r--r--src/System.IO/tests/BufferedStream/BufferedStreamTests.netcoreapp.cs39
-rw-r--r--src/System.IO/tests/MemoryStream/MemoryStreamTests.netcoreapp.cs101
-rw-r--r--src/System.IO/tests/Stream/Stream.ReadWriteSpan.netcoreapp.cs127
-rw-r--r--src/System.IO/tests/StreamReader/StreamReaderTests.cs28
-rw-r--r--src/System.IO/tests/StreamWriter/StreamWriter.WriteTests.cs38
-rw-r--r--src/System.IO/tests/StringWriter/StringWriterTests.cs34
-rw-r--r--src/System.IO/tests/System.IO.Tests.csproj12
-rw-r--r--src/System.IO/tests/TestDataProvider/TestDataProvider.cs72
-rw-r--r--src/System.IO/tests/TextReader/CharArrayTextReader.cs37
-rw-r--r--src/System.IO/tests/TextReader/TextReaderTests.cs248
-rw-r--r--src/System.IO/tests/TextReader/TextReaderTests.netcoreapp.cs51
-rw-r--r--src/System.IO/tests/TextWriter/CharArrayTextWriter.cs29
-rw-r--r--src/System.IO/tests/TextWriter/TextWriterTests.cs543
-rw-r--r--src/System.IO/tests/TextWriter/TextWriterTests.netcoreapp.cs36
-rw-r--r--src/System.Linq.Expressions/src/System/Linq/Expressions/Compiler/LambdaCompiler.Expressions.cs2
-rw-r--r--src/System.Linq.Expressions/src/System/Linq/Expressions/ExpressionType.cs2
-rw-r--r--src/System.Linq/src/System/Linq/Take.cs10
-rw-r--r--src/System.Linq/tests/ConcatTests.cs118
-rw-r--r--src/System.Linq/tests/SelectManyTests.cs111
-rw-r--r--src/System.Memory/pkg/System.Memory.pkgproj13
-rw-r--r--src/System.Memory/ref/Configurations.props7
-rw-r--r--src/System.Memory/ref/System.Memory.cs93
-rw-r--r--src/System.Memory/ref/System.Memory.csproj8
-rw-r--r--src/System.Memory/src/Configurations.props7
-rw-r--r--src/System.Memory/src/Resources/Strings.resx67
-rw-r--r--src/System.Memory/src/System.Memory.csproj20
-rw-r--r--src/System.Memory/src/System/Buffers/IRetainable.cs27
-rw-r--r--src/System.Memory/src/System/Buffers/MemoryHandle.cs57
-rw-r--r--src/System.Memory/src/System/Buffers/OwnedMemory.cs97
-rw-r--r--src/System.Memory/src/System/Memory.cs304
-rw-r--r--src/System.Memory/src/System/ReadOnlyMemory.cs289
-rw-r--r--src/System.Memory/src/System/ReadOnlySpan.cs4
-rw-r--r--src/System.Memory/src/System/Span.cs4
-rw-r--r--src/System.Memory/src/System/SpanExtensions.Fast.cs2
-rw-r--r--src/System.Memory/src/System/SpanHelpers.byte.cs30
-rw-r--r--src/System.Memory/src/System/ThrowHelper.cs9
-rw-r--r--src/System.Memory/tests/Configurations.props3
-rw-r--r--src/System.Memory/tests/Memory/CtorArray.cs104
-rw-r--r--src/System.Memory/tests/Memory/CtorArrayIntInt.cs80
-rw-r--r--src/System.Memory/tests/Memory/CustomMemoryForTest.cs97
-rw-r--r--src/System.Memory/tests/Memory/Empty.cs27
-rw-r--r--src/System.Memory/tests/Memory/Equality.cs245
-rw-r--r--src/System.Memory/tests/Memory/GetHashCode.cs89
-rw-r--r--src/System.Memory/tests/Memory/ImplicitConversion.cs120
-rw-r--r--src/System.Memory/tests/Memory/OwnedMemory.cs96
-rw-r--r--src/System.Memory/tests/Memory/Retain.cs85
-rw-r--r--src/System.Memory/tests/Memory/Slice.cs112
-rw-r--r--src/System.Memory/tests/Memory/Span.cs99
-rw-r--r--src/System.Memory/tests/Memory/ToArray.cs29
-rw-r--r--src/System.Memory/tests/Memory/TryGetArray.cs41
-rw-r--r--src/System.Memory/tests/ReadOnlyMemory/CtorArray.cs121
-rw-r--r--src/System.Memory/tests/ReadOnlyMemory/CtorArrayIntInt.cs80
-rw-r--r--src/System.Memory/tests/ReadOnlyMemory/DangerousTryGetArray.cs41
-rw-r--r--src/System.Memory/tests/ReadOnlyMemory/Empty.cs27
-rw-r--r--src/System.Memory/tests/ReadOnlyMemory/Equality.cs163
-rw-r--r--src/System.Memory/tests/ReadOnlyMemory/GetHashCode.cs73
-rw-r--r--src/System.Memory/tests/ReadOnlyMemory/ImplicitConversion.cs80
-rw-r--r--src/System.Memory/tests/ReadOnlyMemory/Retain.cs85
-rw-r--r--src/System.Memory/tests/ReadOnlyMemory/Slice.cs112
-rw-r--r--src/System.Memory/tests/ReadOnlyMemory/Span.cs99
-rw-r--r--src/System.Memory/tests/ReadOnlyMemory/ToArray.cs29
-rw-r--r--src/System.Memory/tests/ReadOnlySpan/AsBytes.cs4
-rw-r--r--src/System.Memory/tests/ReadOnlySpan/AsReadOnlySpan.cs70
-rw-r--r--src/System.Memory/tests/ReadOnlySpan/AsSpan.cs37
-rw-r--r--src/System.Memory/tests/ReadOnlySpan/CopyTo.cs2
-rw-r--r--src/System.Memory/tests/ReadOnlySpan/CtorArray.cs35
-rw-r--r--src/System.Memory/tests/ReadOnlySpan/CtorArrayIntInt.cs8
-rw-r--r--src/System.Memory/tests/ReadOnlySpan/CtorPointerInt.cs8
-rw-r--r--src/System.Memory/tests/ReadOnlySpan/DangerousCreate.cs20
-rw-r--r--src/System.Memory/tests/ReadOnlySpan/DangerousGetPinnableReference.cs12
-rw-r--r--src/System.Memory/tests/ReadOnlySpan/Empty.cs2
-rw-r--r--src/System.Memory/tests/ReadOnlySpan/IndexOf.T.cs2
-rw-r--r--src/System.Memory/tests/ReadOnlySpan/IndexOf.byte.cs2
-rw-r--r--src/System.Memory/tests/ReadOnlySpan/NonPortableCast.cs4
-rw-r--r--src/System.Memory/tests/ReadOnlySpan/Overflow.cs3
-rw-r--r--src/System.Memory/tests/ReadOnlySpan/SequenceEqual.T.cs2
-rw-r--r--src/System.Memory/tests/ReadOnlySpan/Slice.cs10
-rw-r--r--src/System.Memory/tests/ReadOnlySpan/StartsWith.T.cs2
-rw-r--r--src/System.Memory/tests/ReadOnlySpan/TestHelpers.cs79
-rw-r--r--src/System.Memory/tests/ReadOnlySpan/ToArray.cs1
-rw-r--r--src/System.Memory/tests/Span/AsBytes.cs2
-rw-r--r--src/System.Memory/tests/Span/AsSpan.cs41
-rw-r--r--src/System.Memory/tests/Span/Clear.cs1
-rw-r--r--src/System.Memory/tests/Span/CopyTo.cs4
-rw-r--r--src/System.Memory/tests/Span/CtorArray.cs25
-rw-r--r--src/System.Memory/tests/Span/CtorArrayIntInt.cs8
-rw-r--r--src/System.Memory/tests/Span/CtorPointerInt.cs8
-rw-r--r--src/System.Memory/tests/Span/DangerousCreate.cs20
-rw-r--r--src/System.Memory/tests/Span/DangerousGetPinnableReference.cs12
-rw-r--r--src/System.Memory/tests/Span/Empty.cs2
-rw-r--r--src/System.Memory/tests/Span/Fill.cs1
-rw-r--r--src/System.Memory/tests/Span/IndexOf.T.cs2
-rw-r--r--src/System.Memory/tests/Span/IndexOf.byte.cs2
-rw-r--r--src/System.Memory/tests/Span/NonPortableCast.cs4
-rw-r--r--src/System.Memory/tests/Span/Overflow.cs3
-rw-r--r--src/System.Memory/tests/Span/SequenceEqual.T.cs2
-rw-r--r--src/System.Memory/tests/Span/Slice.cs10
-rw-r--r--src/System.Memory/tests/Span/StartsWith.T.cs2
-rw-r--r--src/System.Memory/tests/Span/TestHelpers.cs95
-rw-r--r--src/System.Memory/tests/Span/ToArray.cs1
-rw-r--r--src/System.Memory/tests/System.Memory.Tests.csproj32
-rw-r--r--src/System.Memory/tests/TInt.cs2
-rw-r--r--src/System.Memory/tests/TestHelpers.cs184
-rw-r--r--src/System.Net.Http.WinHttpHandler/src/System.Net.Http.WinHttpHandler.csproj3
-rw-r--r--src/System.Net.Http.WinHttpHandler/src/System.Net.Http.WinHttpHandler.msbuild4
-rw-r--r--src/System.Net.Http.WinHttpHandler/src/System/Net/Http/WinHttpCertificateHelper.cs14
-rw-r--r--src/System.Net.Http.WinHttpHandler/src/System/Net/Http/WinHttpRequestCallback.cs26
-rw-r--r--src/System.Net.Http.WinHttpHandler/tests/FunctionalTests/ServerCertificateTest.cs6
-rw-r--r--src/System.Net.Http.WinHttpHandler/tests/UnitTests/System.Net.Http.WinHttpHandler.Unit.Tests.csproj9
-rw-r--r--src/System.Net.Http/ref/System.Net.Http.cs6
-rw-r--r--src/System.Net.Http/src/HttpDiagnosticsGuide.md11
-rw-r--r--src/System.Net.Http/src/Resources/Strings.resx5
-rw-r--r--src/System.Net.Http/src/System.Net.Http.csproj9
-rw-r--r--src/System.Net.Http/src/System/Net/Http/Headers/ObjectCollection.cs12
-rw-r--r--src/System.Net.Http/src/System/Net/Http/HttpClientHandler.cs40
-rw-r--r--src/System.Net.Http/src/System/Net/Http/HttpUtilities.cs15
-rw-r--r--src/System.Net.Http/src/System/Net/Http/Managed/AuthenticationHandler.cs12
-rw-r--r--src/System.Net.Http/src/System/Net/Http/Managed/AuthenticationHelper.Digest.cs11
-rw-r--r--src/System.Net.Http/src/System/Net/Http/Managed/AutoRedirectHandler.cs64
-rw-r--r--src/System.Net.Http/src/System/Net/Http/Managed/ChunkedEncodingWriteStream.cs2
-rw-r--r--src/System.Net.Http/src/System/Net/Http/Managed/ConnectHelper.cs3
-rw-r--r--src/System.Net.Http/src/System/Net/Http/Managed/ConnectionCloseReadStream.cs19
-rw-r--r--src/System.Net.Http/src/System/Net/Http/Managed/HttpConnection.cs8
-rw-r--r--src/System.Net.Http/src/System/Net/Http/Managed/HttpConnectionContent.cs10
-rw-r--r--src/System.Net.Http/src/System/Net/Http/Managed/HttpConnectionHandler.cs11
-rw-r--r--src/System.Net.Http/src/System/Net/Http/Managed/HttpConnectionKey.cs6
-rw-r--r--src/System.Net.Http/src/System/Net/Http/Managed/HttpContentDuplexStream.cs31
-rw-r--r--src/System.Net.Http/src/System/Net/Http/Managed/HttpContentReadStream.cs32
-rw-r--r--src/System.Net.Http/src/System/Net/Http/Managed/HttpContentStream.cs49
-rw-r--r--src/System.Net.Http/src/System/Net/Http/Managed/HttpContentWriteStream.cs32
-rw-r--r--src/System.Net.Http/src/System/Net/Http/Managed/HttpProxyConnectionHandler.cs7
-rw-r--r--src/System.Net.Http/src/System/Net/Http/Managed/ManagedHandler.cs4
-rw-r--r--src/System.Net.Http/src/System/Net/Http/Managed/RawConnectionStream.cs72
-rw-r--r--src/System.Net.Http/src/System/Net/Http/ReadOnlyMemoryContent.cs40
-rw-r--r--src/System.Net.Http/src/uap/System/Net/cookie.cs11
-rw-r--r--src/System.Net.Http/tests/FunctionalTests/CancellationTest.cs8
-rw-r--r--src/System.Net.Http/tests/FunctionalTests/DefaultCredentialsTest.cs34
-rw-r--r--src/System.Net.Http/tests/FunctionalTests/DiagnosticsTests.cs77
-rw-r--r--src/System.Net.Http/tests/FunctionalTests/HttpClientEKUTest.cs10
-rw-r--r--src/System.Net.Http/tests/FunctionalTests/HttpClientHandlerTest.AcceptAllCerts.cs11
-rw-r--r--src/System.Net.Http/tests/FunctionalTests/HttpClientHandlerTest.ClientCertificates.cs53
-rw-r--r--src/System.Net.Http/tests/FunctionalTests/HttpClientHandlerTest.DefaultProxyCredentials.cs45
-rw-r--r--src/System.Net.Http/tests/FunctionalTests/HttpClientHandlerTest.MaxConnectionsPerServer.cs13
-rw-r--r--src/System.Net.Http/tests/FunctionalTests/HttpClientHandlerTest.MaxResponseHeadersLength.cs14
-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.cs16
-rw-r--r--src/System.Net.Http/tests/FunctionalTests/HttpClientHandlerTest.ServerCertificates.cs93
-rw-r--r--src/System.Net.Http/tests/FunctionalTests/HttpClientHandlerTest.SslProtocols.Unix.cs6
-rw-r--r--src/System.Net.Http/tests/FunctionalTests/HttpClientHandlerTest.SslProtocols.Windows.cs11
-rw-r--r--src/System.Net.Http/tests/FunctionalTests/HttpClientHandlerTest.SslProtocols.cs68
-rw-r--r--src/System.Net.Http/tests/FunctionalTests/HttpClientHandlerTest.cs184
-rw-r--r--src/System.Net.Http/tests/FunctionalTests/HttpClientMiniStressTest.cs16
-rw-r--r--src/System.Net.Http/tests/FunctionalTests/HttpClientTest.cs38
-rw-r--r--src/System.Net.Http/tests/FunctionalTests/HttpClientTestBase.cs60
-rw-r--r--src/System.Net.Http/tests/FunctionalTests/ManagedHandlerTest.cs123
-rw-r--r--src/System.Net.Http/tests/FunctionalTests/ManagedHandlerTestHelpers.cs17
-rw-r--r--src/System.Net.Http/tests/FunctionalTests/PostScenarioTest.cs14
-rw-r--r--src/System.Net.Http/tests/FunctionalTests/PostScenarioUWPTest.cs34
-rw-r--r--src/System.Net.Http/tests/FunctionalTests/ReadOnlyMemoryContentTest.cs404
-rw-r--r--src/System.Net.Http/tests/FunctionalTests/ResponseStreamTest.cs15
-rw-r--r--src/System.Net.Http/tests/FunctionalTests/SchSendAuxRecordHttpTest.cs7
-rw-r--r--src/System.Net.Http/tests/FunctionalTests/System.Net.Http.Functional.Tests.csproj12
-rw-r--r--src/System.Net.NameResolution/src/System/Net/NameResolutionPal.Unix.cs12
-rw-r--r--src/System.Net.NameResolution/tests/FunctionalTests/GetHostByNameTest.cs18
-rw-r--r--src/System.Net.NameResolution/tests/FunctionalTests/GetHostEntryTest.cs44
-rw-r--r--src/System.Net.NameResolution/tests/PalTests/Fakes/DnsFake.cs11
-rw-r--r--src/System.Net.NameResolution/tests/PalTests/System.Net.NameResolution.Pal.Tests.csproj3
-rw-r--r--src/System.Net.NetworkInformation/tests/FunctionalTests/FileUtil.cs11
-rw-r--r--src/System.Net.NetworkInformation/tests/FunctionalTests/MiscParsingTests.cs10
-rw-r--r--src/System.Net.Ping/tests/FunctionalTests/PingTest.cs65
-rw-r--r--src/System.Net.Ping/tests/FunctionalTests/UnixPingUtilityTests.cs10
-rw-r--r--src/System.Net.Primitives/src/System/Net/CookieContainer.cs4
-rw-r--r--src/System.Net.Primitives/src/System/Net/IPAddress.cs13
-rw-r--r--src/System.Net.Primitives/src/System/Net/IPv6AddressHelper.cs8
-rw-r--r--src/System.Net.Primitives/tests/FunctionalTests/IPAddressParsing.cs180
-rw-r--r--src/System.Net.Primitives/tests/FunctionalTests/IPAddressParsingSpan.cs162
-rw-r--r--src/System.Net.Primitives/tests/FunctionalTests/IPAddressTest.cs12
-rw-r--r--src/System.Net.Requests/src/System/Net/CommandStream.cs2
-rw-r--r--src/System.Net.Requests/tests/HttpWebRequestTest.cs1
-rw-r--r--src/System.Net.Security/src/System.Net.Security.csproj4
-rw-r--r--src/System.Net.Security/src/System/Net/Security/SslConnectionInfo.Unix.cs2
-rw-r--r--src/System.Net.Security/src/System/Net/Security/SslState.cs46
-rw-r--r--src/System.Net.Security/src/System/Net/Security/SslStreamInternal.Adapters.cs53
-rw-r--r--src/System.Net.Security/src/System/Net/Security/SslStreamInternal.cs328
-rw-r--r--src/System.Net.Security/tests/FunctionalTests/NegotiateStreamTestForUnix.cs35
-rw-r--r--src/System.Net.Sockets/src/System/Net/Sockets/Socket.cs2
-rw-r--r--src/System.Net.Sockets/src/System/Net/Sockets/SocketPal.Unix.cs26
-rw-r--r--src/System.Net.Sockets/tests/FunctionalTests/Accept.cs1
-rw-r--r--src/System.Net.Sockets/tests/FunctionalTests/DualModeSocketTest.cs7
-rw-r--r--src/System.Net.Sockets/tests/FunctionalTests/SendReceive.cs205
-rw-r--r--src/System.Net.Sockets/tests/FunctionalTests/Shutdown.cs1
-rw-r--r--src/System.Net.Sockets/tests/FunctionalTests/SocketOptionNameTest.cs10
-rw-r--r--src/System.Net.Sockets/tests/FunctionalTests/TimeoutTest.cs10
-rw-r--r--src/System.Net.Sockets/tests/FunctionalTests/UnixDomainSocketTest.cs59
-rw-r--r--src/System.Net.WebProxy/tests/WebProxyTest.cs1
-rw-r--r--src/System.Net.WebSockets.Client/src/System.Net.WebSockets.Client.csproj2
-rw-r--r--src/System.Net.WebSockets.Client/src/System/Net/WebSockets/ClientWebSocketOptions.cs26
-rw-r--r--src/System.Net.WebSockets.Client/src/System/Net/WebSockets/WebSocketHandle.Managed.cs434
-rw-r--r--src/System.Net.WebSockets.Client/src/System/Net/WebSockets/WinRTWebSocket.cs4
-rw-r--r--src/System.Net.WebSockets.Client/tests/AbortTest.cs5
-rw-r--r--src/System.Net.WebSockets.Client/tests/CancelTest.cs1
-rw-r--r--src/System.Net.WebSockets.Client/tests/ClientWebSocketTestBase.cs20
-rw-r--r--src/System.Net.WebSockets.Client/tests/ConnectTest.cs15
-rw-r--r--src/System.Net.WebSockets.Client/tests/KeepAliveTest.cs5
-rw-r--r--src/System.Net.WebSockets.Client/tests/SendReceiveTest.cs1
-rw-r--r--src/System.Numerics.Vectors/pkg/System.Numerics.Vectors.pkgproj11
-rw-r--r--src/System.ObjectModel/src/System/Collections/ObjectModel/ObservableCollection.cs2
-rw-r--r--src/System.Private.DataContractSerialization/src/System/Runtime/Serialization/CollectionDataContract.cs4
-rw-r--r--src/System.Private.DataContractSerialization/src/System/Runtime/Serialization/Json/XmlJsonWriter.cs80
-rw-r--r--src/System.Private.DataContractSerialization/src/System/Runtime/Serialization/XmlObjectSerializerWriteContext.cs6
-rw-r--r--src/System.Private.Reflection.Metadata.Ecma335/src/Resources/Strings.resx4
-rw-r--r--src/System.Private.Xml/src/Resources/Strings.resx64
-rw-r--r--src/System.Private.Xml/src/System/Xml/Core/XmlReaderSettings.cs62
-rw-r--r--src/System.Private.Xml/src/System/Xml/Core/XmlValidatingReaderImpl.cs2
-rw-r--r--src/System.Private.Xml/src/System/Xml/Core/XsdValidatingReader.cs2
-rw-r--r--src/System.Private.Xml/src/System/Xml/Schema/XdrBuilder.cs2
-rw-r--r--src/System.Private.Xml/src/System/Xml/Serialization/Compilation.cs6
-rw-r--r--src/System.Private.Xml/src/System/Xml/Serialization/XmlSerializer.cs28
-rw-r--r--src/System.Private.Xml/tests/Readers/CharCheckingReader/CharReaderTests.cs396
-rw-r--r--src/System.Private.Xml/tests/Readers/CharCheckingReader/System.Xml.RW.CharCheckingReader.Tests.csproj3
-rw-r--r--src/System.Private.Xml/tests/Readers/CustomReader/CReaderTestModule.cs27
-rw-r--r--src/System.Private.Xml/tests/Readers/CustomReader/System.Xml.RW.CustomReader.Tests.csproj1
-rw-r--r--src/System.Private.Xml/tests/Readers/FactoryReader/FactoryReaderTests.cs445
-rw-r--r--src/System.Private.Xml/tests/Readers/FactoryReader/System.Xml.RW.FactoryReader.Tests.csproj1
-rw-r--r--src/System.Private.Xml/tests/Readers/NameTable/CNameTableTestModule.cs105
-rw-r--r--src/System.Private.Xml/tests/Readers/NameTable/System.Xml.RW.NameTable.Tests.csproj1
-rw-r--r--src/System.Private.Xml/tests/Readers/ReaderSettings/CReaderTestModule.cs221
-rw-r--r--src/System.Private.Xml/tests/Readers/ReaderSettings/System.Xml.RW.ReaderSettings.Tests.csproj1
-rw-r--r--src/System.Private.Xml/tests/Readers/SubtreeReader/SubtreeReaderTests.cs395
-rw-r--r--src/System.Private.Xml/tests/Readers/SubtreeReader/System.Xml.RW.SubtreeReader.Tests.csproj1
-rw-r--r--src/System.Private.Xml/tests/Readers/WrappedReader/System.Xml.RW.WrappedReader.Tests.csproj1
-rw-r--r--src/System.Private.Xml/tests/Readers/WrappedReader/WrappedReaderTests.cs413
-rw-r--r--src/System.Private.Xml/tests/Writers/RwFactory/CFactoryModule.cs20
-rw-r--r--src/System.Private.Xml/tests/Writers/RwFactory/System.Xml.RW.RwFactory.Tests.csproj1
-rw-r--r--src/System.Private.Xml/tests/XmlConvert/System.Xml.RW.XmlConvert.Tests.csproj1
-rw-r--r--src/System.Private.Xml/tests/XmlConvert/XmlConvertTests.cs225
-rw-r--r--src/System.Private.Xml/tests/XmlReaderLib/System.Xml.RW.XmlReaderLib.csproj2
-rw-r--r--src/System.Private.Xml/tests/XmlSerializer/XmlSerializerTests.cs8
-rw-r--r--src/System.Reflection.DispatchProxy/pkg/System.Reflection.DispatchProxy.pkgproj14
-rw-r--r--src/System.Reflection.DispatchProxy/src/Configurations.props5
-rw-r--r--src/System.Reflection.Metadata/pkg/System.Reflection.Metadata.pkgproj11
-rw-r--r--src/System.Reflection.Metadata/ref/System.Reflection.Metadata.cs6
-rw-r--r--src/System.Reflection.Metadata/ref/System.Reflection.Metadata.csproj3
-rw-r--r--src/System.Reflection.Metadata/src/System.Reflection.Metadata.csproj3
-rw-r--r--src/System.Reflection.Metadata/src/System/Reflection/Metadata/MetadataReader.netstandard.cs62
-rw-r--r--src/System.Reflection.Metadata/src/System/Reflection/Metadata/TypeSystem/AssemblyDefinition.cs2
-rw-r--r--src/System.Reflection.Metadata/src/System/Reflection/Metadata/TypeSystem/AssemblyDefinition.netstandard.cs14
-rw-r--r--src/System.Reflection.Metadata/src/System/Reflection/Metadata/TypeSystem/AssemblyReference.cs2
-rw-r--r--src/System.Reflection.Metadata/src/System/Reflection/Metadata/TypeSystem/AssemblyReference.netstandard.cs14
-rw-r--r--src/System.Reflection.Metadata/tests/Metadata/Decoding/SignatureDecoderTests.cs2
-rw-r--r--src/System.Reflection.Metadata/tests/Metadata/TypeSystem/AssemblyDefinitionTests.cs126
-rw-r--r--src/System.Reflection.Metadata/tests/Metadata/TypeSystem/AssemblyReferenceTests.cs103
-rw-r--r--src/System.Reflection.Metadata/tests/Resources/Misc/SatelliteAssembly.resources.cs10
-rw-r--r--src/System.Reflection.Metadata/tests/Resources/Misc/SatelliteAssembly.resources.dllbin0 -> 3584 bytes
-rw-r--r--src/System.Reflection.Metadata/tests/Resources/TestResources.cs1
-rw-r--r--src/System.Reflection.Metadata/tests/System.Reflection.Metadata.Tests.csproj8
-rw-r--r--src/System.Reflection.TypeExtensions/ref/System.Reflection.TypeExtensions.csproj3
-rw-r--r--src/System.Runtime.CompilerServices.Unsafe/pkg/System.Runtime.CompilerServices.Unsafe.pkgproj11
-rw-r--r--src/System.Runtime.CompilerServices.Unsafe/src/Configurations.props5
-rw-r--r--src/System.Runtime.CompilerServices.Unsafe/tests/Configurations.props2
-rw-r--r--src/System.Runtime.CompilerServices.Unsafe/tests/UnsafeTests.cs1
-rw-r--r--src/System.Runtime.Extensions/ref/System.Runtime.Extensions.cs7
-rw-r--r--src/System.Runtime.Extensions/src/PinvokeAnalyzerExceptionList.analyzerdata.uap1
-rw-r--r--src/System.Runtime.Extensions/src/PinvokeAnalyzerExceptionList.analyzerdata.uapaot1
-rw-r--r--src/System.Runtime.Extensions/src/Resources/Strings.resx79
-rw-r--r--src/System.Runtime.Extensions/src/System/Collections/Hashtable.cs132
-rw-r--r--src/System.Runtime.Extensions/src/System/IO/BufferedStream.cs158
-rw-r--r--src/System.Runtime.Extensions/src/System/IO/TextReader.cs48
-rw-r--r--src/System.Runtime.Extensions/src/System/IO/TextWriter.cs33
-rw-r--r--src/System.Runtime.Extensions/tests/System.Runtime.Extensions.Tests.csproj5
-rw-r--r--src/System.Runtime.Extensions/tests/System/EnvironmentTests.cs6
-rw-r--r--src/System.Runtime.Extensions/tests/System/MathTests.netcoreapp.cs1
-rw-r--r--src/System.Runtime.Extensions/tests/System/Random.cs61
-rw-r--r--src/System.Runtime.Extensions/tests/System/Random.netcoreapp.cs56
-rw-r--r--src/System.Runtime.InteropServices/ref/System.Runtime.InteropServices.cs27
-rw-r--r--src/System.Runtime.Intrinsics.X86/System.Runtime.Intrinsics.X86.sln23
-rw-r--r--src/System.Runtime.Intrinsics.X86/dir.props8
-rw-r--r--src/System.Runtime.Intrinsics.X86/pkg/System.Runtime.Intrinsics.X86.pkgproj11
-rw-r--r--src/System.Runtime.Intrinsics.X86/ref/Configurations.props8
-rw-r--r--src/System.Runtime.Intrinsics.X86/ref/System.Runtime.Intrinsics.X86.cs1204
-rw-r--r--src/System.Runtime.Intrinsics.X86/ref/System.Runtime.Intrinsics.X86.csproj17
-rw-r--r--src/System.Runtime.Intrinsics.X86/src/Configurations.props9
-rw-r--r--src/System.Runtime.Intrinsics.X86/src/System.Runtime.Intrinsics.X86.csproj16
-rw-r--r--src/System.Runtime.Loader/tests/DefaultContext/System.Runtime.Loader.DefaultContext.Tests.csproj2
-rw-r--r--src/System.Runtime.Numerics/src/System/Numerics/BigInteger.cs44
-rw-r--r--src/System.Runtime.Numerics/tests/BigInteger/ctor.cs4
-rw-r--r--src/System.Runtime.Serialization.Formatters/tests/BinaryFormatterHelper.cs309
-rw-r--r--src/System.Runtime.Serialization.Formatters/tests/BinaryFormatterTestData.cs73
-rw-r--r--src/System.Runtime.Serialization.Formatters/tests/BinaryFormatterTests.cs223
-rw-r--r--src/System.Runtime.Serialization.Formatters/tests/EqualityExtensions.cs241
-rw-r--r--src/System.Runtime.Serialization.Formatters/tests/FormatterServicesTests.cs3
-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.cs36
-rw-r--r--src/System.Runtime.Serialization.Xml/tests/Canonicalization/XmlCanonicalizationTest.cs10
-rw-r--r--src/System.Runtime.Serialization.Xml/tests/DataContractSerializer.cs55
-rw-r--r--src/System.Runtime.Serialization.Xml/tests/ReflectionOnly/Resources/System.Runtime.Serialization.Xml.ReflectionOnly.Tests.rd.xml8
-rw-r--r--src/System.Runtime.Serialization.Xml/tests/Resources/System.Runtime.Serialization.Xml.Tests.rd.xml16
-rw-r--r--src/System.Runtime.Serialization.Xml/tests/SerializationTypes.RuntimeOnly.cs27
-rw-r--r--src/System.Runtime.Serialization.Xml/tests/System.Runtime.Serialization.Xml.Tests.csproj3
-rw-r--r--src/System.Runtime.WindowsRuntime/src/System/IO/NetFxToWinRtStreamAdapter.cs18
-rw-r--r--src/System.Runtime.WindowsRuntime/src/System/Runtime/InteropServices/HResults.cs2
-rw-r--r--src/System.Runtime.WindowsRuntime/src/System/Runtime/InteropServices/WindowsRuntime/MarshalingHelpers.cs32
-rw-r--r--src/System.Runtime.WindowsRuntime/src/System/Runtime/InteropServices/WindowsRuntime/WindowsRuntimeBuffer.cs4
-rw-r--r--src/System.Runtime.WindowsRuntime/src/System/Runtime/InteropServices/WindowsRuntime/WindowsRuntimeBufferExtensions.cs2
-rw-r--r--src/System.Runtime.WindowsRuntime/src/System/Threading/Tasks/TaskToAsyncInfoAdapter.cs10
-rw-r--r--src/System.Runtime.WindowsRuntime/tests/System/IO/AsWinRTStreamTests.cs4
-rw-r--r--src/System.Runtime/ref/System.Runtime.cs145
-rw-r--r--src/System.Runtime/ref/System.Runtime.csproj2
-rw-r--r--src/System.Runtime/src/System.Runtime.Forwards.cs6
-rw-r--r--src/System.Runtime/src/System.Runtime.csproj1
-rw-r--r--src/System.Runtime/tests/System.Runtime.Tests.csproj5
-rw-r--r--src/System.Runtime/tests/System/DateTimeTests.cs301
-rw-r--r--src/System.Runtime/tests/System/DecimalTests.cs385
-rw-r--r--src/System.Runtime/tests/System/GuidTests.cs23
-rw-r--r--src/System.Runtime/tests/System/GuidTests.netcoreapp.cs124
-rw-r--r--src/System.Runtime/tests/System/Reflection/BindingFlagsDoNotWrap.netcoreapp.cs174
-rw-r--r--src/System.Runtime/tests/System/Reflection/MemberInfoTests.netcoreapp.cs2
-rw-r--r--src/System.Runtime/tests/System/Reflection/SignatureTypes.netcoreapp.cs529
-rw-r--r--src/System.Runtime/tests/System/StringTests.netcoreapp.cs58
-rw-r--r--src/System.Runtime/tests/System/TimeSpanTests.cs289
-rw-r--r--src/System.Runtime/tests/System/TimeSpanTests.netcoreapp.cs124
-rw-r--r--src/System.Runtime/tests/System/TypeTests.netcoreapp.cs3
-rw-r--r--src/System.Runtime/tests/System/UnitySerializationHolderTests.cs20
-rw-r--r--src/System.Runtime/tests/System/VersionTests.netcoreapp.cs82
-rw-r--r--src/System.Security.AccessControl/ref/System.Security.AccessControl.csproj3
-rw-r--r--src/System.Security.Cryptography.Cng/ref/System.Security.Cryptography.Cng.csproj3
-rw-r--r--src/System.Security.Cryptography.Xml/ref/System.Security.Cryptography.Xml.cs2
-rw-r--r--src/System.Security.Cryptography.Xml/ref/System.Security.Cryptography.Xml.csproj7
-rw-r--r--src/System.Security.Cryptography.Xml/src/System.Security.Cryptography.Xml.csproj3
-rw-r--r--src/System.Security.Cryptography.Xml/src/System/Security/Cryptography/Xml/EncryptedXml.cs19
-rw-r--r--src/System.Security.Cryptography.Xml/tests/EncryptedXmlTest.cs45
-rw-r--r--src/System.Security.Principal.Windows/ref/System.Security.Principal.Windows.csproj3
-rw-r--r--src/System.ServiceModel.Syndication/System.ServiceModel.Syndication.sln31
-rw-r--r--src/System.ServiceModel.Syndication/dir.props8
-rw-r--r--src/System.ServiceModel.Syndication/src/Configurations.props8
-rw-r--r--src/System.ServiceModel.Syndication/src/Resources/Strings.resx7928
-rw-r--r--src/System.ServiceModel.Syndication/src/System.ServiceModel.Syndication.csproj15
-rw-r--r--src/System.ServiceModel.Syndication/src/System/ServiceModel/Channels/UriGenerator.cs44
-rw-r--r--src/System.ServiceModel.Syndication/src/System/ServiceModel/Syndication/App10Constants.cs20
-rw-r--r--src/System.ServiceModel.Syndication/src/System/ServiceModel/Syndication/Atom10Constants.cs53
-rw-r--r--src/System.ServiceModel.Syndication/src/System/ServiceModel/Syndication/Atom10FeedFormatter.cs1403
-rw-r--r--src/System.ServiceModel.Syndication/src/System/ServiceModel/Syndication/Atom10ItemFormatter.cs168
-rw-r--r--src/System.ServiceModel.Syndication/src/System/ServiceModel/Syndication/AtomPub10CategoriesDocumentFormatter.cs214
-rw-r--r--src/System.ServiceModel.Syndication/src/System/ServiceModel/Syndication/AtomPub10ServiceDocumentFormatter.cs792
-rw-r--r--src/System.ServiceModel.Syndication/src/System/ServiceModel/Syndication/CategoriesDocument.cs119
-rw-r--r--src/System.ServiceModel.Syndication/src/System/ServiceModel/Syndication/CategoriesDocumentFormatter.cs56
-rw-r--r--src/System.ServiceModel.Syndication/src/System/ServiceModel/Syndication/ExtensibleSyndicationObject.cs142
-rw-r--r--src/System.ServiceModel.Syndication/src/System/ServiceModel/Syndication/FeedUtils.cs144
-rw-r--r--src/System.ServiceModel.Syndication/src/System/ServiceModel/Syndication/IExtensibleSyndicationObject.cs17
-rw-r--r--src/System.ServiceModel.Syndication/src/System/ServiceModel/Syndication/InlineCategoriesDocument.cs74
-rw-r--r--src/System.ServiceModel.Syndication/src/System/ServiceModel/Syndication/NullNotAllowedCollection.cs36
-rw-r--r--src/System.ServiceModel.Syndication/src/System/ServiceModel/Syndication/ReferencedCategoriesDocument.cs39
-rw-r--r--src/System.ServiceModel.Syndication/src/System/ServiceModel/Syndication/ResourceCollectionInfo.cs182
-rw-r--r--src/System.ServiceModel.Syndication/src/System/ServiceModel/Syndication/Rss20Constants.cs46
-rw-r--r--src/System.ServiceModel.Syndication/src/System/ServiceModel/Syndication/Rss20FeedFormatter.cs1661
-rw-r--r--src/System.ServiceModel.Syndication/src/System/ServiceModel/Syndication/Rss20ItemFormatter.cs195
-rw-r--r--src/System.ServiceModel.Syndication/src/System/ServiceModel/Syndication/ServiceDocument.cs124
-rw-r--r--src/System.ServiceModel.Syndication/src/System/ServiceModel/Syndication/ServiceDocumentFormatter.cs329
-rw-r--r--src/System.ServiceModel.Syndication/src/System/ServiceModel/Syndication/SyndicationCategory.cs113
-rw-r--r--src/System.ServiceModel.Syndication/src/System/ServiceModel/Syndication/SyndicationContent.cs138
-rw-r--r--src/System.ServiceModel.Syndication/src/System/ServiceModel/Syndication/SyndicationElementExtension.cs348
-rw-r--r--src/System.ServiceModel.Syndication/src/System/ServiceModel/Syndication/SyndicationElementExtensionCollection.cs277
-rw-r--r--src/System.ServiceModel.Syndication/src/System/ServiceModel/Syndication/SyndicationElementExtensionKindHelper.cs23
-rw-r--r--src/System.ServiceModel.Syndication/src/System/ServiceModel/Syndication/SyndicationFeed.cs502
-rw-r--r--src/System.ServiceModel.Syndication/src/System/ServiceModel/Syndication/SyndicationFeedFormatter.cs555
-rw-r--r--src/System.ServiceModel.Syndication/src/System/ServiceModel/Syndication/SyndicationItem.cs318
-rw-r--r--src/System.ServiceModel.Syndication/src/System/ServiceModel/Syndication/SyndicationItemFormatter.cs220
-rw-r--r--src/System.ServiceModel.Syndication/src/System/ServiceModel/Syndication/SyndicationLink.cs199
-rw-r--r--src/System.ServiceModel.Syndication/src/System/ServiceModel/Syndication/SyndicationPerson.cs116
-rw-r--r--src/System.ServiceModel.Syndication/src/System/ServiceModel/Syndication/SyndicationTextInput.cs14
-rw-r--r--src/System.ServiceModel.Syndication/src/System/ServiceModel/Syndication/SyndicationVersions.cs14
-rw-r--r--src/System.ServiceModel.Syndication/src/System/ServiceModel/Syndication/TextSyndicationContent.cs81
-rw-r--r--src/System.ServiceModel.Syndication/src/System/ServiceModel/Syndication/TextSyndicationContentKind.cs15
-rw-r--r--src/System.ServiceModel.Syndication/src/System/ServiceModel/Syndication/TextSyndicationContentKindHelper.cs16
-rw-r--r--src/System.ServiceModel.Syndication/src/System/ServiceModel/Syndication/UrlSyndicationContent.cs58
-rw-r--r--src/System.ServiceModel.Syndication/src/System/ServiceModel/Syndication/Workspace.cs118
-rw-r--r--src/System.ServiceModel.Syndication/src/System/ServiceModel/Syndication/XmlReaderWrapper.cs549
-rw-r--r--src/System.ServiceModel.Syndication/src/System/ServiceModel/Syndication/XmlSyndicationContent.cs210
-rw-r--r--src/System.ServiceModel.Syndication/src/System/ServiceModel/Syndication/XmlWriterWrapper.cs268
-rw-r--r--src/System.ServiceModel.Syndication/src/System/ServiceModel/XmlBuffer.cs151
-rw-r--r--src/System.ServiceModel.Syndication/tests/BasicScenarioTests.cs702
-rw-r--r--src/System.ServiceModel.Syndication/tests/Configurations.props8
-rw-r--r--src/System.ServiceModel.Syndication/tests/System.ServiceModel.Syndication.Tests.csproj25
-rw-r--r--src/System.ServiceModel.Syndication/tests/TestFeeds/AtomDisjointItems.xml81
-rw-r--r--src/System.ServiceModel.Syndication/tests/TestFeeds/RssDisjointItems.xml38
-rw-r--r--src/System.ServiceModel.Syndication/tests/TestFeeds/RssFeedWithCustomImageName.xml30
-rw-r--r--src/System.ServiceModel.Syndication/tests/TestFeeds/SimpleAtomFeed.xml20
-rw-r--r--src/System.ServiceModel.Syndication/tests/TestFeeds/SimpleRssFeed.xml29
-rw-r--r--src/System.ServiceModel.Syndication/tests/TestFeeds/atom_spec_example.xml48
-rw-r--r--src/System.ServiceModel.Syndication/tests/TestFeeds/example_feed_xml_atom.xml187
-rw-r--r--src/System.ServiceModel.Syndication/tests/TestFeeds/rssSpecExample.xml69
-rw-r--r--src/System.ServiceModel.Syndication/tests/TestFeeds/rssSpecExampleWrongDateFormat.xml69
-rw-r--r--src/System.ServiceModel.Syndication/tests/TestFeeds/rssSpecExampleWrongSkipDays.xml70
-rw-r--r--src/System.ServiceProcess.ServiceController/tests/ServiceBaseTests.cs8
-rw-r--r--src/System.ServiceProcess.ServiceController/tests/ServiceControllerTests.cs7
-rw-r--r--src/System.ServiceProcess.ServiceController/tests/System.ServiceProcess.ServiceController.TestService/TestServiceInstaller.cs19
-rw-r--r--src/System.Text.Encoding.CodePages/pkg/System.Text.Encoding.CodePages.pkgproj12
-rw-r--r--src/System.Text.Encoding/tests/Decoder/DecoderConvert2.cs4
-rw-r--r--src/System.Text.Encoding/tests/Encoder/EncoderConvert2.cs2
-rw-r--r--src/System.Text.RegularExpressions/ref/System.Text.RegularExpressions.cs81
-rw-r--r--src/System.Text.RegularExpressions/ref/System.Text.RegularExpressions.csproj7
-rw-r--r--src/System.Text.RegularExpressions/ref/System.Text.RegularExpressions.netcoreapp.cs77
-rw-r--r--src/System.Text.RegularExpressions/src/Resources/Strings.resx14
-rw-r--r--src/System.Text.RegularExpressions/src/System.Text.RegularExpressions.csproj17
-rw-r--r--src/System.Text.RegularExpressions/src/System/Text/RegularExpressions/CompiledRegexRunner.cs37
-rw-r--r--src/System.Text.RegularExpressions/src/System/Text/RegularExpressions/CompiledRegexRunnerFactory.cs32
-rw-r--r--src/System.Text.RegularExpressions/src/System/Text/RegularExpressions/Regex.cs143
-rw-r--r--src/System.Text.RegularExpressions/src/System/Text/RegularExpressions/RegexBoyerMoore.cs14
-rw-r--r--src/System.Text.RegularExpressions/src/System/Text/RegularExpressions/RegexCode.cs2
-rw-r--r--src/System.Text.RegularExpressions/src/System/Text/RegularExpressions/RegexCompilationInfo.cs77
-rw-r--r--src/System.Text.RegularExpressions/src/System/Text/RegularExpressions/RegexCompiler.cs3092
-rw-r--r--src/System.Text.RegularExpressions/src/System/Text/RegularExpressions/RegexLWCGCompiler.cs68
-rw-r--r--src/System.Text.RegularExpressions/tests/CaptureCollectionTests2.cs (renamed from src/System.Text.RegularExpressions/tests/CaptureCollectionTests.netcoreapp.cs)2
-rw-r--r--src/System.Text.RegularExpressions/tests/GroupCollectionTests2.cs (renamed from src/System.Text.RegularExpressions/tests/GroupCollectionTests.netcoreapp.cs)2
-rw-r--r--src/System.Text.RegularExpressions/tests/MatchCollectionTests2.cs (renamed from src/System.Text.RegularExpressions/tests/MatchCollectionTests.netcoreapp.cs)2
-rw-r--r--src/System.Text.RegularExpressions/tests/Regex.Ctor.Tests.cs27
-rw-r--r--src/System.Text.RegularExpressions/tests/Regex.Match.Tests.cs19
-rw-r--r--src/System.Text.RegularExpressions/tests/Regex.Replace.Tests.cs3
-rw-r--r--src/System.Text.RegularExpressions/tests/Regex.Split.Tests.cs5
-rw-r--r--src/System.Text.RegularExpressions/tests/Regex.Tests.Common.cs2
-rw-r--r--src/System.Text.RegularExpressions/tests/RegexCompilationHelper.cs52
-rw-r--r--src/System.Text.RegularExpressions/tests/RegexCompilationInfoTests.cs119
-rw-r--r--src/System.Text.RegularExpressions/tests/System.Text.RegularExpressions.Tests.csproj15
-rw-r--r--src/System.Threading.Tasks.Dataflow/pkg/System.Threading.Tasks.Dataflow.pkgproj11
-rw-r--r--src/System.Threading.Tasks.Dataflow/src/Internal/ProducerConsumerQueues.cs2
-rw-r--r--src/System.Threading.Tasks.Extensions/pkg/System.Threading.Tasks.Extensions.pkgproj10
-rw-r--r--src/System.Threading.Tasks.Extensions/tests/AsyncValueTaskMethodBuilderTests.cs1
-rw-r--r--src/System.Threading.Tasks/tests/CESchedulerPairTests.cs4
-rw-r--r--src/System.Threading.Tasks/tests/Task/TaskRunSyncTests.cs2
-rw-r--r--src/System.Threading/tests/MutexTests.cs4
-rw-r--r--src/System.Transactions.Local/tests/TransactionScopeTest.cs2
-rw-r--r--src/System.ValueTuple/ref/System.ValueTuple.csproj3
-rw-r--r--src/System.Web.HttpUtility/src/System/Web/HttpUtility.cs89
-rw-r--r--src/System.Web.HttpUtility/tests/HttpUtility/HttpUtilityTest.cs163
-rw-r--r--src/shims/ApiCompatBaseline.netcoreapp.netfx461.ignore.txt29
-rw-r--r--src/shims/ApiCompatBaseline.netcoreapp.netfx461.txt74
-rw-r--r--src/shims/manual/mscorlib.forwards.cs1
-rw-r--r--src/src.builds1
864 files changed, 53561 insertions, 15263 deletions
diff --git a/src/Common/src/Interop/Linux/procfs/Interop.ProcFsStat.cs b/src/Common/src/Interop/Linux/procfs/Interop.ProcFsStat.cs
index d9d713d4c4..2b87afa3c7 100644
--- a/src/Common/src/Interop/Linux/procfs/Interop.ProcFsStat.cs
+++ b/src/Common/src/Interop/Linux/procfs/Interop.ProcFsStat.cs
@@ -14,13 +14,15 @@ internal static partial class Interop
internal static partial class procfs
{
internal const string RootPath = "/proc/";
- internal const string SelfExeFilePath = RootPath + "self/exe";
- internal const string ProcUptimeFilePath = RootPath + "uptime";
+ private const string ExeFileName = "/exe";
private const string StatFileName = "/stat";
private const string MapsFileName = "/maps";
private const string FileDescriptorDirectoryName = "/fd/";
private const string TaskDirectoryName = "/task/";
+ internal const string SelfExeFilePath = RootPath + "self" + ExeFileName;
+ internal const string ProcUptimeFilePath = RootPath + "uptime";
+
internal struct ParsedStat
{
// Commented out fields are available in the stat data file but
@@ -80,6 +82,11 @@ internal static partial class Interop
internal KeyValuePair<long, long> AddressRange;
}
+ internal static string GetExeFilePathForProcess(int pid)
+ {
+ return RootPath + pid.ToString(CultureInfo.InvariantCulture) + ExeFileName;
+ }
+
internal static string GetStatFilePathForProcess(int pid)
{
return RootPath + pid.ToString(CultureInfo.InvariantCulture) + StatFileName;
diff --git a/src/Common/src/Interop/Unix/System.Native/Interop.ForkAndExecProcess.cs b/src/Common/src/Interop/Unix/System.Native/Interop.ForkAndExecProcess.cs
index 1e01ac23ae..8667e21a9c 100644
--- a/src/Common/src/Interop/Unix/System.Native/Interop.ForkAndExecProcess.cs
+++ b/src/Common/src/Interop/Unix/System.Native/Interop.ForkAndExecProcess.cs
@@ -15,14 +15,15 @@ internal static partial class Interop
internal static unsafe void ForkAndExecProcess(
string filename, string[] argv, string[] envp, string cwd,
bool redirectStdin, bool redirectStdout, bool redirectStderr,
- out int lpChildPid, out int stdinFd, out int stdoutFd, out int stderrFd)
+ out int lpChildPid, out int stdinFd, out int stdoutFd, out int stderrFd, bool shouldThrow = true)
{
byte** argvPtr = null, envpPtr = null;
+ int result = -1;
try
{
AllocNullTerminatedArray(argv, ref argvPtr);
AllocNullTerminatedArray(envp, ref envpPtr);
- int result = ForkAndExecProcess(
+ result = ForkAndExecProcess(
filename, argvPtr, envpPtr, cwd,
redirectStdin ? 1 : 0, redirectStdout ? 1 : 0, redirectStderr ? 1 :0,
out lpChildPid, out stdinFd, out stdoutFd, out stderrFd);
diff --git a/src/Common/src/Interop/Unix/System.Native/Interop.MountPoints.FormatInfo.cs b/src/Common/src/Interop/Unix/System.Native/Interop.MountPoints.FormatInfo.cs
index a2f601eb43..b8a610af19 100644
--- a/src/Common/src/Interop/Unix/System.Native/Interop.MountPoints.FormatInfo.cs
+++ b/src/Common/src/Interop/Unix/System.Native/Interop.MountPoints.FormatInfo.cs
@@ -21,53 +21,101 @@ internal static partial class Interop
/// </remarks>
internal enum UnixFileSystemTypes : long
{
- adfs = 0xadf5,
+ adfs = 0xADF5,
affs = 0xADFF,
+ afs = 0x5346414F,
+ anoninode = 0x09041934,
+ aufs = 0x61756673,
+ autofs = 0x0187,
befs = 0x42465331,
+ bdevfs = 0x62646576,
bfs = 0x1BADFACE,
+ binfmt_misc = 0x42494E4D,
+ btrfs = 0x9123683E,
+ ceph = 0x00C36400,
+ cgroupfs = 0x0027E0EB,
cifs = 0xFF534D42,
coda = 0x73757245,
coherent = 0x012FF7B7,
- cramfs = 0x28cd3d45,
+ cramfs = 0x28CD3D45,
+ debugfs = 0x64626720,
devfs = 0x1373,
+ devpts = 0x1CD1,
+ ecryptfs = 0xF15F,
efs = 0x00414A53,
ext = 0x137D,
ext2_old = 0xEF51,
ext2 = 0xEF53,
ext3 = 0xEF53,
ext4 = 0xEF53,
+ fat = 0x4006,
+ fhgfs = 0x19830326,
+ fuseblk = 0x65735546,
+ fusectl = 0x65735543,
+ futexfs = 0x0BAD1DEA,
+ gfsgfs2 = 0x1161970,
+ gpfs = 0x47504653,
hfs = 0x4244,
hpfs = 0xF995E849,
- hugetlbfs = 0x958458f6,
+ hugetlbfs = 0x958458F6,
+ inodefs = 0x11307854,
+ inotifyfs = 0x2BAD1DEA,
isofs = 0x9660,
- jffs2 = 0x72b6,
- jfs = 0x3153464a,
+ // isofs = 0x4004, // R_WIN
+ // isofs = 0x4000, // WIN
+ jffs = 0x07C0,
+ jffs2 = 0x72B6,
+ jfs = 0x3153464A,
+ kafs = 0x6B414653,
+ lustre = 0x0BD00BD0,
minix_old = 0x137F, /* orig. minix */
minix = 0x138F, /* 30 char minix */
minix2 = 0x2468, /* minix V2 */
- minix2v2 = 0x2478, /* minix V2, 30 char names */
- msdos = 0x4d44,
- ncpfs = 0x564c,
+ minix2v2 = 0x2478, /* MINIX V2, 30 char names */
+ minix3 = 0x4D5A,
+ mqueue = 0x19800202,
+ msdos = 0x4D44,
nfs = 0x6969,
- ntfs = 0x5346544e,
- openprom = 0x9fa1,
- overlay = 0x794c7630,
- overlayfs = 0x794c764f,
- proc = 0x9fa0,
- qnx4 = 0x002f,
+ nfsd = 0x6E667364,
+ nilfs = 0x3434,
+ novell = 0x564C,
+ ntfs = 0x5346544E,
+ openprom = 0x9FA1,
+ ocfs2 = 0x7461636F,
+ overlay = 0x794C7630,
+ overlayfs = 0x794C764F,
+ panfs = 0xAAD7AAEA,
+ pipefs = 0x50495045,
+ proc = 0x9FA0,
+ pstorefs = 0x6165676C,
+ qnx4 = 0x002F,
+ qnx6 = 0x68191122,
+ ramfs = 0x858458F6,
reiserfs = 0x52654973,
romfs = 0x7275,
+ rpc_pipefs = 0x67596969,
+ securityfs = 0x73636673,
+ selinux = 0xF97CFF8C,
smb = 0x517B,
+ sockfs = 0x534F434B,
+ squashfs = 0x73717368,
+ sysfs = 0x62656572,
sysv2 = 0x012FF7B6,
sysv4 = 0x012FF7B5,
tmpfs = 0x01021994,
udf = 0x15013346,
ufs = 0x00011954,
- usbdevice = 0x9fa2,
- vxfs = 0xa501FCF5,
+ // ufs = 0x54190100, // byteswapped
+ usbdevice = 0x9FA2,
+ v9fs = 0x01021997,
+ vmhgfs = 0xBACBACBC,
+ vxfs = 0xA501FCF5,
+ vzfs = 0x565A4653,
+ xenfs = 0xABBA1974,
xenix = 0x012FF7B4,
xfs = 0x58465342,
- xiafs = 0x012FD16D,
+ xia = 0x012FD16D,
+ zfs = 0x2FC12FC1,
}
[StructLayout(LayoutKind.Sequential)]
@@ -130,7 +178,7 @@ internal static partial class Interop
/// <returns>The recognized drive type.</returns>
private static DriveType GetDriveType(string fileSystemName)
{
- // This list is based primarily on "man fs", "man mount", "mntent.h", "/proc/filesystems",
+ // This list is based primarily on "man fs", "man mount", "mntent.h", "/proc/filesystems", coreutils "stat.c",
// and "wiki.debian.org/FileSystem". It can be extended over time as we
// find additional file systems that should be recognized as a particular drive type.
switch (fileSystemName)
@@ -143,91 +191,154 @@ internal static partial class Interop
case "umview-mod-umfuseiso9660":
return DriveType.CDRom;
+ case "aafs":
case "adfs":
case "affs":
+ case "anoninode":
+ case "anon-inode FS":
case "apfs":
+ case "autofs":
+ case "balloon-kvm-fs":
+ case "bdevfs":
case "befs":
case "bfs":
+ case "bpf_fs":
case "btrfs":
+ case "btrfs_test":
+ case "cgroup2fs":
+ case "cgroupfs":
+ case "coh":
+ case "cramfs":
+ case "cramfs-wend":
+ case "daxfs":
case "drvfs":
case "ecryptfs":
+ case "efivarfs":
case "efs":
+ case "exofs":
case "ext":
case "ext2":
case "ext2_old":
case "ext3":
+ case "ext2/ext3":
case "ext4":
case "ext4dev":
+ case "f2fs":
case "fat":
- case "fuseblk":
case "fuseext2":
case "fusefat":
+ case "futexfs":
case "hfs":
+ case "hfs+":
case "hfsplus":
+ case "hfsx":
+ case "hostfs":
case "hpfs":
+ case "inodefs":
+ case "inotifyfs":
case "jbd":
case "jbd2":
- case "jfs":
case "jffs":
case "jffs2":
+ case "jfs":
+ case "logfs":
case "lxfs":
+ case "minix (30 char.)":
+ case "minix v2 (30 char.)":
+ case "minix v2":
case "minix":
case "minix_old":
case "minix2":
case "minix2v2":
+ case "minix3":
+ case "mlfs":
case "msdos":
+ case "nilfs":
+ case "nsfs":
+ case "ntfs":
case "ocfs2":
case "omfs":
case "openprom":
case "overlay":
case "overlayfs":
- case "ntfs":
+ case "pstorefs":
case "qnx4":
+ case "qnx6":
case "reiserfs":
+ case "rpc_pipefs":
+ case "selinux":
+ case "smackfs":
case "squashfs":
case "swap":
+ case "sysfs":
case "sysv":
+ case "sysv2":
+ case "sysv4":
+ case "tracefs":
case "ubifs":
case "udf":
case "ufs":
case "umsdos":
case "umview-mod-umfuseext2":
+ case "usbdevfs":
+ case "v9fs":
+ case "vzfs":
+ case "wslfs":
+ case "xenfs":
case "xenix":
case "xfs":
+ case "xia":
case "xiafs":
case "xmount":
+ case "zfs":
case "zfs-fuse":
+ case "zsmallocfs":
return DriveType.Fixed;
case "9p":
- case "autofs":
+ case "acfs":
+ case "afs":
+ case "aufs":
case "autofs4":
case "beaglefs":
+ case "ceph":
case "cifs":
case "coda":
case "coherent":
case "curlftpfs":
case "davfs2":
case "dlm":
+ case "fhgfs":
case "flickrfs":
+ case "fuseblk":
case "fusedav":
case "fusesmb":
+ case "gfsgfs2":
+ case "gfs/gfs2":
case "gfs2":
case "glusterfs-client":
case "gmailfs":
+ case "gpfs":
+ case "ibrix":
+ case "k-afs":
case "kafs":
case "ltspfs":
+ case "lustre":
case "ncpfs":
case "nfs":
case "nfs4":
+ case "nfsd":
+ case "novell":
case "obexfs":
+ case "panfs":
+ case "prl_fs":
case "s3ql":
case "smb":
+ case "smb2":
case "smbfs":
+ case "snfs":
case "sshfs":
- case "sysfs":
- case "sysv2":
- case "sysv4":
+ case "vmhgfs":
case "vxfs":
case "wikipediafs":
return DriveType.Network;
@@ -239,7 +350,6 @@ internal static partial class Interop
case "binfmt_misc":
case "cgroup":
case "configfs":
- case "cramfs":
case "cryptkeeper":
case "cpuset":
case "debugfs":
diff --git a/src/Common/src/Interop/Windows/SChannel/UnmanagedCertificateContext.IntPtr.cs b/src/Common/src/Interop/Windows/SChannel/UnmanagedCertificateContext.IntPtr.cs
new file mode 100644
index 0000000000..f3d53c92fc
--- /dev/null
+++ b/src/Common/src/Interop/Windows/SChannel/UnmanagedCertificateContext.IntPtr.cs
@@ -0,0 +1,51 @@
+// 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.Diagnostics;
+using System.Net.Security;
+using System.Runtime.InteropServices;
+using System.Security.Cryptography.X509Certificates;
+
+namespace System.Net
+{
+ internal static unsafe partial class UnmanagedCertificateContext
+ {
+ internal static X509Certificate2Collection GetRemoteCertificatesFromStoreContext(IntPtr certContext)
+ {
+ X509Certificate2Collection result = new X509Certificate2Collection();
+
+ if (certContext == IntPtr.Zero)
+ {
+ return result;
+ }
+
+ Interop.Crypt32.CERT_CONTEXT context =
+ Marshal.PtrToStructure<Interop.Crypt32.CERT_CONTEXT>(certContext);
+
+ if (context.hCertStore != IntPtr.Zero)
+ {
+ Interop.Crypt32.CERT_CONTEXT* last = null;
+
+ while (true)
+ {
+ Interop.Crypt32.CERT_CONTEXT* next =
+ Interop.Crypt32.CertEnumCertificatesInStore(context.hCertStore, last);
+
+ if (next == null)
+ {
+ break;
+ }
+
+ var cert = new X509Certificate2(new IntPtr(next));
+ if (NetEventSource.IsEnabled) NetEventSource.Info(certContext, $"Adding remote certificate:{cert}");
+
+ result.Add(cert);
+ last = next;
+ }
+ }
+
+ return result;
+ }
+ }
+}
diff --git a/src/Common/src/Interop/Windows/SChannel/UnmanagedCertificateContext.cs b/src/Common/src/Interop/Windows/SChannel/UnmanagedCertificateContext.cs
index 66c4a60c5d..73b856ff21 100644
--- a/src/Common/src/Interop/Windows/SChannel/UnmanagedCertificateContext.cs
+++ b/src/Common/src/Interop/Windows/SChannel/UnmanagedCertificateContext.cs
@@ -9,43 +9,16 @@ using System.Security.Cryptography.X509Certificates;
namespace System.Net
{
- internal static unsafe class UnmanagedCertificateContext
+ internal static unsafe partial class UnmanagedCertificateContext
{
internal static X509Certificate2Collection GetRemoteCertificatesFromStoreContext(SafeFreeCertContext certContext)
{
- X509Certificate2Collection result = new X509Certificate2Collection();
-
if (certContext.IsInvalid)
{
- return result;
- }
-
- Interop.Crypt32.CERT_CONTEXT context =
- Marshal.PtrToStructure<Interop.Crypt32.CERT_CONTEXT>(certContext.DangerousGetHandle());
-
- if (context.hCertStore != IntPtr.Zero)
- {
- Interop.Crypt32.CERT_CONTEXT* last = null;
-
- while (true)
- {
- Interop.Crypt32.CERT_CONTEXT* next =
- Interop.Crypt32.CertEnumCertificatesInStore(context.hCertStore, last);
-
- if (next == null)
- {
- break;
- }
-
- var cert = new X509Certificate2(new IntPtr(next));
- if (NetEventSource.IsEnabled) NetEventSource.Info(certContext, $"Adding remote certificate:{cert}");
-
- result.Add(cert);
- last = next;
- }
+ return new X509Certificate2Collection();
}
- return result;
+ return GetRemoteCertificatesFromStoreContext(certContext.DangerousGetHandle());
}
}
}
diff --git a/src/Common/src/Interop/Windows/kernel32/Interop.CreateNamedPipeClient.Uap.cs b/src/Common/src/Interop/Windows/kernel32/Interop.CreateNamedPipeClient.Uap.cs
new file mode 100644
index 0000000000..adb902dea1
--- /dev/null
+++ b/src/Common/src/Interop/Windows/kernel32/Interop.CreateNamedPipeClient.Uap.cs
@@ -0,0 +1,46 @@
+// 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.IO;
+using System.Runtime.InteropServices;
+
+internal partial class Interop
+{
+ internal partial class Kernel32
+ {
+ [DllImport(Libraries.Kernel32, EntryPoint = "CreateFile2", SetLastError = true, CharSet = CharSet.Unicode, BestFitMapping = false)]
+ private static extern SafePipeHandle CreateNamedPipeClientPrivate(
+ string lpFileName,
+ int dwDesiredAccess,
+ System.IO.FileShare dwShareMode,
+ System.IO.FileMode dwCreationDisposition,
+ [In] ref CREATEFILE2_EXTENDED_PARAMETERS parameters);
+
+ internal static unsafe SafePipeHandle CreateNamedPipeClient(
+ string lpFileName,
+ int dwDesiredAccess,
+ System.IO.FileShare dwShareMode,
+ ref SECURITY_ATTRIBUTES secAttrs,
+ FileMode dwCreationDisposition,
+ int dwFlagsAndAttributes,
+ IntPtr hTemplateFile)
+ {
+ Interop.Kernel32.CREATEFILE2_EXTENDED_PARAMETERS parameters;
+ parameters.dwSize = (uint)Marshal.SizeOf<Interop.Kernel32.CREATEFILE2_EXTENDED_PARAMETERS>();
+
+ parameters.dwFileAttributes = (uint)dwFlagsAndAttributes & 0x0000FFFF;
+ parameters.dwSecurityQosFlags = (uint)dwFlagsAndAttributes & 0x000F0000;
+ parameters.dwFileFlags = (uint)dwFlagsAndAttributes & 0xFFF00000;
+
+ parameters.hTemplateFile = hTemplateFile;
+ fixed (Interop.Kernel32.SECURITY_ATTRIBUTES* lpSecurityAttributes = &secAttrs)
+ {
+ parameters.lpSecurityAttributes = (IntPtr)lpSecurityAttributes;
+ return CreateNamedPipeClientPrivate(lpFileName, dwDesiredAccess, dwShareMode, dwCreationDisposition, ref parameters);
+ }
+ }
+ }
+}
diff --git a/src/Common/src/Interop/Windows/kernel32/Interop.FlushViewOfFile.cs b/src/Common/src/Interop/Windows/kernel32/Interop.FlushViewOfFile.cs
index c6ba2496be..053d7e824f 100644
--- a/src/Common/src/Interop/Windows/kernel32/Interop.FlushViewOfFile.cs
+++ b/src/Common/src/Interop/Windows/kernel32/Interop.FlushViewOfFile.cs
@@ -9,7 +9,7 @@ internal partial class Interop
{
internal partial class Kernel32
{
- [DllImport(Libraries.Kernel32)]
- internal extern static int FlushViewOfFile(IntPtr lpBaseAddress, UIntPtr dwNumberOfBytesToFlush);
+ [DllImport(Libraries.Kernel32, SetLastError = true)]
+ internal extern static bool FlushViewOfFile(IntPtr lpBaseAddress, UIntPtr dwNumberOfBytesToFlush);
}
}
diff --git a/src/Common/src/Interop/Windows/kernel32/Interop.UnmapViewOfFile.cs b/src/Common/src/Interop/Windows/kernel32/Interop.UnmapViewOfFile.cs
index 8895ac80e6..2a1879fa30 100644
--- a/src/Common/src/Interop/Windows/kernel32/Interop.UnmapViewOfFile.cs
+++ b/src/Common/src/Interop/Windows/kernel32/Interop.UnmapViewOfFile.cs
@@ -9,7 +9,7 @@ internal partial class Interop
{
internal partial class Kernel32
{
- [DllImport(Libraries.Kernel32)]
- internal extern static int UnmapViewOfFile(IntPtr lpBaseAddress);
+ [DllImport(Libraries.Kernel32, SetLastError = true)]
+ internal extern static bool UnmapViewOfFile(IntPtr lpBaseAddress);
}
}
diff --git a/src/Common/src/System/Collections/Generic/LargeArrayBuilder.cs b/src/Common/src/System/Collections/Generic/LargeArrayBuilder.cs
index fd17c34b10..b91a202922 100644
--- a/src/Common/src/System/Collections/Generic/LargeArrayBuilder.cs
+++ b/src/Common/src/System/Collections/Generic/LargeArrayBuilder.cs
@@ -43,6 +43,20 @@ namespace System.Collections.Generic
internal int Column { get; }
/// <summary>
+ /// If this position is at the end of the current buffer, returns the position
+ /// at the start of the next buffer. Otherwise, returns this position.
+ /// </summary>
+ /// <param name="endColumn">The length of the current buffer.</param>
+ public CopyPosition Normalize(int endColumn)
+ {
+ Debug.Assert(Column <= endColumn);
+
+ return Column == endColumn ?
+ new CopyPosition(Row + 1, 0) :
+ this;
+ }
+
+ /// <summary>
/// Gets a string suitable for display in the debugger.
/// </summary>
private string DebuggerDisplay => $"[{Row}, {Column}]";
@@ -197,9 +211,10 @@ namespace System.Collections.Generic
/// <returns>The position in this builder that was copied up to.</returns>
public CopyPosition CopyTo(CopyPosition position, T[] array, int arrayIndex, int count)
{
+ Debug.Assert(array != null);
Debug.Assert(arrayIndex >= 0);
- Debug.Assert(count >= 0 && count <= Count);
- Debug.Assert(array?.Length - arrayIndex >= count);
+ Debug.Assert(count > 0 && count <= Count);
+ Debug.Assert(array.Length - arrayIndex >= count);
// Go through each buffer, which contains one 'row' of items.
// The index in each buffer is referred to as the 'column'.
@@ -216,25 +231,35 @@ namespace System.Collections.Generic
int row = position.Row;
int column = position.Column;
- for (; count > 0; row++, column = 0)
+ T[] buffer = GetBuffer(row);
+ int copied = CopyToCore(buffer, column);
+
+ if (count == 0)
{
- T[] buffer = GetBuffer(index: row);
+ return new CopyPosition(row, column + copied).Normalize(buffer.Length);
+ }
- // During this iteration, copy until we satisfy `count` or reach the
- // end of the current buffer.
- int copyCount = Math.Min(buffer.Length, count);
+ do
+ {
+ buffer = GetBuffer(++row);
+ copied = CopyToCore(buffer, 0);
+ } while (count > 0);
- if (copyCount > 0)
- {
- Array.Copy(buffer, column, array, arrayIndex, copyCount);
+ return new CopyPosition(row, copied).Normalize(buffer.Length);
- arrayIndex += copyCount;
- count -= copyCount;
- column += copyCount;
- }
- }
+ int CopyToCore(T[] sourceBuffer, int sourceIndex)
+ {
+ Debug.Assert(sourceBuffer.Length > sourceIndex);
+
+ // Copy until we satisfy `count` or reach the end of the current buffer.
+ int copyCount = Math.Min(sourceBuffer.Length - sourceIndex, count);
+ Array.Copy(sourceBuffer, sourceIndex, array, arrayIndex, copyCount);
- return new CopyPosition(row: row, column: column);
+ arrayIndex += copyCount;
+ count -= copyCount;
+
+ return copyCount;
+ }
}
/// <summary>
diff --git a/src/Common/src/System/Collections/Generic/SparseArrayBuilder.cs b/src/Common/src/System/Collections/Generic/SparseArrayBuilder.cs
index 57eeeb90b6..4829a9ce46 100644
--- a/src/Common/src/System/Collections/Generic/SparseArrayBuilder.cs
+++ b/src/Common/src/System/Collections/Generic/SparseArrayBuilder.cs
@@ -113,9 +113,10 @@ namespace System.Collections.Generic
/// <param name="count">The number of items to copy.</param>
public void CopyTo(T[] array, int arrayIndex, int count)
{
+ Debug.Assert(array != null);
Debug.Assert(arrayIndex >= 0);
Debug.Assert(count >= 0 && count <= Count);
- Debug.Assert(array?.Length - arrayIndex >= count);
+ Debug.Assert(array.Length - arrayIndex >= count);
int copied = 0;
var position = CopyPosition.Start;
@@ -149,8 +150,11 @@ namespace System.Collections.Generic
count -= reservedCount;
}
- // Finish copying after the final marker.
- _builder.CopyTo(position, array, arrayIndex, count);
+ if (count > 0)
+ {
+ // Finish copying after the final marker.
+ _builder.CopyTo(position, array, arrayIndex, count);
+ }
}
/// <summary>
diff --git a/src/Common/src/System/Data/Common/MultipartIdentifier.cs b/src/Common/src/System/Data/Common/MultipartIdentifier.cs
index 7722345d89..4bf59ad4ab 100644
--- a/src/Common/src/System/Data/Common/MultipartIdentifier.cs
+++ b/src/Common/src/System/Data/Common/MultipartIdentifier.cs
@@ -208,7 +208,7 @@ namespace System.Data.Common
case MPIState.MPI_RightQuote:
{
if (testchar == rightQuoteChar)
- { // If the next char is a another right quote then we were escaping the right quote
+ { // If the next char is another right quote then we were escaping the right quote
sb.Append(testchar);
state = MPIState.MPI_ParseQuote;
}
diff --git a/src/Common/src/System/IO/ReadOnlyMemoryStream.cs b/src/Common/src/System/IO/ReadOnlyMemoryStream.cs
new file mode 100644
index 0000000000..9c240b8e56
--- /dev/null
+++ b/src/Common/src/System/IO/ReadOnlyMemoryStream.cs
@@ -0,0 +1,155 @@
+// 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.Threading.Tasks;
+
+namespace System.IO
+{
+ /// <summary>Provides a <see cref="Stream"/> for the contents of a <see cref="ReadOnlyMemory{byte}"/>.</summary>
+ internal sealed class ReadOnlyMemoryStream : Stream
+ {
+ private readonly ReadOnlyMemory<byte> _content;
+ private int _position;
+
+ public ReadOnlyMemoryStream(ReadOnlyMemory<byte> content)
+ {
+ _content = content;
+ }
+
+ public override bool CanRead => true;
+ public override bool CanSeek => true;
+ public override bool CanWrite => false;
+
+ public override long Length => _content.Length;
+
+ public override long Position
+ {
+ get => _position;
+ set
+ {
+ if (value < 0 || value > int.MaxValue)
+ {
+ throw new ArgumentOutOfRangeException(nameof(value));
+ }
+ _position = (int)value;
+ }
+ }
+
+ public override long Seek(long offset, SeekOrigin origin)
+ {
+ long pos =
+ origin == SeekOrigin.Begin ? offset :
+ origin == SeekOrigin.Current ? _position + offset :
+ origin == SeekOrigin.End ? _content.Length + offset :
+ throw new ArgumentOutOfRangeException(nameof(origin));
+
+ if (pos > int.MaxValue)
+ {
+ throw new ArgumentOutOfRangeException(nameof(offset));
+ }
+ else if (pos < 0)
+ {
+ throw new IOException(SR.IO_SeekBeforeBegin);
+ }
+
+ _position = (int)pos;
+ return _position;
+ }
+
+ public override int ReadByte()
+ {
+ ReadOnlySpan<byte> s = _content.Span;
+ return _position < s.Length ? s[_position++] : -1;
+ }
+
+ public override int Read(byte[] buffer, int offset, int count)
+ {
+ ValidateReadArrayArguments(buffer, offset, count);
+ return Read(new Span<byte>(buffer, offset, count));
+ }
+
+ public override int Read(Span<byte> destination)
+ {
+ int remaining = _content.Length - _position;
+
+ if (remaining <= 0 || destination.Length == 0)
+ {
+ return 0;
+ }
+ else if (remaining <= destination.Length)
+ {
+ _content.Span.Slice(_position).CopyTo(destination);
+ _position = _content.Length;
+ return remaining;
+ }
+ else
+ {
+ _content.Span.Slice(_position, destination.Length).CopyTo(destination);
+ _position += destination.Length;
+ return destination.Length;
+ }
+ }
+
+ public override Task<int> ReadAsync(byte[] buffer, int offset, int count, CancellationToken cancellationToken)
+ {
+ ValidateReadArrayArguments(buffer, offset, count);
+ return cancellationToken.IsCancellationRequested ?
+ Task.FromCanceled<int>(cancellationToken) :
+ Task.FromResult(Read(new Span<byte>(buffer, offset, count)));
+ }
+
+ public override ValueTask<int> ReadAsync(Memory<byte> destination, CancellationToken cancellationToken = default(CancellationToken)) =>
+ cancellationToken.IsCancellationRequested ?
+ new ValueTask<int>(Task.FromCanceled<int>(cancellationToken)) :
+ new ValueTask<int>(Read(destination.Span));
+
+ public override IAsyncResult BeginRead(byte[] buffer, int offset, int count, AsyncCallback callback, object state) =>
+ TaskToApm.Begin(ReadAsync(buffer, offset, count), callback, state);
+
+ public override int EndRead(IAsyncResult asyncResult) =>
+ TaskToApm.End<int>(asyncResult);
+
+ public override void CopyTo(Stream destination, int bufferSize)
+ {
+ StreamHelpers.ValidateCopyToArgs(this, destination, bufferSize);
+ if (_content.Length > _position)
+ {
+ destination.Write(_content.Span.Slice(_position));
+ }
+ }
+
+ public override Task CopyToAsync(Stream destination, int bufferSize, CancellationToken cancellationToken)
+ {
+ StreamHelpers.ValidateCopyToArgs(this, destination, bufferSize);
+ return _content.Length > _position ?
+ destination.WriteAsync(_content.Slice(_position), cancellationToken) :
+ Task.CompletedTask;
+ }
+
+ public override void Flush() { }
+
+ public override Task FlushAsync(CancellationToken cancellationToken) => Task.CompletedTask;
+
+ public override void SetLength(long value) => throw new NotSupportedException();
+
+ public override void Write(byte[] buffer, int offset, int count) => throw new NotSupportedException();
+
+ private static void ValidateReadArrayArguments(byte[] buffer, int offset, int count)
+ {
+ if (buffer == null)
+ {
+ throw new ArgumentNullException(nameof(buffer));
+ }
+ if (offset < 0)
+ {
+ throw new ArgumentOutOfRangeException(nameof(offset));
+ }
+ if (count < 0 || buffer.Length - offset < count)
+ {
+ throw new ArgumentOutOfRangeException(nameof(count));
+ }
+ }
+ }
+}
diff --git a/src/Common/src/System/Net/Http/WinHttpException.cs b/src/Common/src/System/Net/Http/WinHttpException.cs
index 1a4bcf8f52..d77e347135 100644
--- a/src/Common/src/System/Net/Http/WinHttpException.cs
+++ b/src/Common/src/System/Net/Http/WinHttpException.cs
@@ -15,6 +15,11 @@ namespace System.Net.Http
this.HResult = ConvertErrorCodeToHR(error);
}
+ public WinHttpException(int error, string message, Exception innerException) : base(message, innerException)
+ {
+ this.HResult = ConvertErrorCodeToHR(error);
+ }
+
public static int ConvertErrorCodeToHR(int error)
{
// This method allows common error detection code to be used by consumers
@@ -52,6 +57,13 @@ namespace System.Net.Http
return e;
}
+ public static WinHttpException CreateExceptionUsingError(int error, Exception innerException)
+ {
+ var e = new WinHttpException(error, GetErrorMessage(error), innerException);
+ ExceptionStackTrace.AddCurrentStack(e);
+ return e;
+ }
+
public static string GetErrorMessage(int error)
{
// Look up specific error message in WINHTTP.DLL since it is not listed in default system resources
diff --git a/src/Common/src/System/Net/Internals/IPAddressExtensions.cs b/src/Common/src/System/Net/Internals/IPAddressExtensions.cs
index e52af95df9..1ad0048d56 100644
--- a/src/Common/src/System/Net/Internals/IPAddressExtensions.cs
+++ b/src/Common/src/System/Net/Internals/IPAddressExtensions.cs
@@ -18,13 +18,7 @@ namespace System.Net.Sockets
#pragma warning restore CS0618
case AddressFamily.InterNetworkV6:
- Span<byte> addressBytes;
- unsafe
- {
- // TODO https://github.com/dotnet/roslyn/issues/17287: Clean up once we can stackalloc into a span
- byte* mem = stackalloc byte[IPAddressParserStatics.IPv6AddressBytes];
- addressBytes = new Span<byte>(mem, IPAddressParserStatics.IPv6AddressBytes);
- }
+ Span<byte> addressBytes = stackalloc byte[IPAddressParserStatics.IPv6AddressBytes];
original.TryWriteBytes(addressBytes, out int bytesWritten);
Debug.Assert(bytesWritten == IPAddressParserStatics.IPv6AddressBytes);
return new IPAddress(addressBytes, (uint)original.ScopeId);
diff --git a/src/Common/src/System/Net/SocketAddress.cs b/src/Common/src/System/Net/SocketAddress.cs
index 84166bd706..1115c84f15 100644
--- a/src/Common/src/System/Net/SocketAddress.cs
+++ b/src/Common/src/System/Net/SocketAddress.cs
@@ -103,13 +103,7 @@ namespace System.Net.Internals
if (ipAddress.AddressFamily == AddressFamily.InterNetworkV6)
{
- Span<byte> addressBytes;
- unsafe
- {
- // TODO https://github.com/dotnet/roslyn/issues/17287: Clean up once we can stackalloc into a span
- byte* mem = stackalloc byte[IPAddressParserStatics.IPv6AddressBytes];
- addressBytes = new Span<byte>(mem, IPAddressParserStatics.IPv6AddressBytes);
- }
+ Span<byte> addressBytes = stackalloc byte[IPAddressParserStatics.IPv6AddressBytes];
ipAddress.TryWriteBytes(addressBytes, out int bytesWritten);
Debug.Assert(bytesWritten == IPAddressParserStatics.IPv6AddressBytes);
@@ -138,13 +132,7 @@ namespace System.Net.Internals
{
Debug.Assert(Size >= IPv6AddressSize);
- Span<byte> address;
- unsafe
- {
- // TODO https://github.com/dotnet/roslyn/issues/17287: Clean up once we can stackalloc into a span
- byte* mem = stackalloc byte[IPAddressParserStatics.IPv6AddressBytes];
- address = new Span<byte>(mem, IPAddressParserStatics.IPv6AddressBytes);
- }
+ Span<byte> address = stackalloc byte[IPAddressParserStatics.IPv6AddressBytes];
uint scope;
SocketAddressPal.GetIPv6Address(Buffer, address, out scope);
diff --git a/src/Common/src/System/Net/WebSockets/ManagedWebSocket.cs b/src/Common/src/System/Net/WebSockets/ManagedWebSocket.cs
index 803d50acad..64eacaf881 100644
--- a/src/Common/src/System/Net/WebSockets/ManagedWebSocket.cs
+++ b/src/Common/src/System/Net/WebSockets/ManagedWebSocket.cs
@@ -80,8 +80,6 @@ namespace System.Net.WebSockets
private readonly CancellationTokenSource _abortSource = new CancellationTokenSource();
/// <summary>Buffer used for reading data from the network.</summary>
private byte[] _receiveBuffer;
- /// <summary>Gets whether the receive buffer came from the ArrayPool.</summary>
- private readonly bool _receiveBufferFromPool;
/// <summary>
/// Tracks the state of the validity of the UTF8 encoding of text payloads. Text may be split across fragments.
/// </summary>
@@ -197,8 +195,12 @@ namespace System.Net.WebSockets
}
else
{
- _receiveBufferFromPool = true;
- _receiveBuffer = ArrayPool<byte>.Shared.Rent(Math.Max(receiveBufferSize, MaxMessageHeaderLength));
+ // Just allocate the array. We avoid using the pool because often many web sockets will be used concurrently,
+ // and if each web socket rents a similarly sized buffer from the pool for its duration, we'll end up draining
+ // the pool, such that other web sockets will allocate anyway, as will anyone else in the process using the
+ // pool. If someone wants to pool, they can do so by passing in the buffer they want to use, and they can
+ // get it from whatever pool they like.
+ _receiveBuffer = new byte[Math.Max(receiveBufferSize, MaxMessageHeaderLength)];
}
// Set up the abort source so that if it's triggered, we transition the instance appropriately.
@@ -241,12 +243,6 @@ namespace System.Net.WebSockets
_disposed = true;
_keepAliveTimer?.Dispose();
_stream?.Dispose();
- if (_receiveBufferFromPool)
- {
- byte[] old = _receiveBuffer;
- _receiveBuffer = null;
- ArrayPool<byte>.Shared.Return(old);
- }
if (_state < WebSocketState.Aborted)
{
_state = WebSocketState.Closed;
@@ -399,12 +395,11 @@ namespace System.Net.WebSockets
writeTask = _stream.WriteAsync(_sendBuffer, 0, sendBytes, CancellationToken.None);
// If the operation happens to complete synchronously (or, more specifically, by
- // the time we get from the previous line to here, release the semaphore, propagate
- // exceptions, and we're done.
+ // the time we get from the previous line to here), release the semaphore, return
+ // the task, and we're done.
if (writeTask.IsCompleted)
{
- writeTask.GetAwaiter().GetResult(); // propagate any exceptions
- return Task.CompletedTask;
+ return writeTask;
}
// Up until this point, if an exception occurred (such as when accessing _stream or when
@@ -516,7 +511,16 @@ namespace System.Net.WebSockets
{
// This exists purely to keep the connection alive; don't wait for the result, and ignore any failures.
// The call will handle releasing the lock.
- SendFrameLockAcquiredNonCancelableAsync(MessageOpcode.Ping, true, new ArraySegment<byte>(Array.Empty<byte>()));
+ Task t = SendFrameLockAcquiredNonCancelableAsync(MessageOpcode.Ping, true, new ArraySegment<byte>(Array.Empty<byte>()));
+
+ // "Observe" any exception, ignoring it to prevent the unobserved exception event from being raised.
+ if (!t.IsCompletedSuccessfully)
+ {
+ t.ContinueWith(p => { Exception ignored = p.Exception; },
+ CancellationToken.None,
+ TaskContinuationOptions.OnlyOnFaulted | TaskContinuationOptions.ExecuteSynchronously,
+ TaskScheduler.Default);
+ }
}
else
{
@@ -681,25 +685,24 @@ namespace System.Net.WebSockets
Debug.Assert(header.Opcode == MessageOpcode.Binary || header.Opcode == MessageOpcode.Text, $"Unexpected opcode {header.Opcode}");
// If there's no data to read, return an appropriate result.
- int bytesToRead = (int)Math.Min(payloadBuffer.Count, header.PayloadLength);
- if (bytesToRead == 0)
+ if (header.PayloadLength == 0 || payloadBuffer.Count == 0)
{
_lastReceiveHeader = header;
return new WebSocketReceiveResult(
0,
header.Opcode == MessageOpcode.Text ? WebSocketMessageType.Text : WebSocketMessageType.Binary,
- header.PayloadLength == 0 ? header.Fin : false);
+ header.Fin && header.PayloadLength == 0);
}
// Otherwise, read as much of the payload as we can efficiently, and upate the header to reflect how much data
// remains for future reads.
-
- if (_receiveBufferCount == 0)
+ int bytesToCopy = Math.Min(payloadBuffer.Count, (int)Math.Min(header.PayloadLength, _receiveBuffer.Length));
+ Debug.Assert(bytesToCopy > 0, $"Expected {nameof(bytesToCopy)} > 0");
+ if (_receiveBufferCount < bytesToCopy)
{
- await EnsureBufferContainsAsync(1, cancellationToken, throwOnPrematureClosure: false).ConfigureAwait(false);
+ await EnsureBufferContainsAsync(bytesToCopy, cancellationToken, throwOnPrematureClosure: true).ConfigureAwait(false);
}
- int bytesToCopy = Math.Min(bytesToRead, _receiveBufferCount);
if (_isServer)
{
_receivedMaskOffsetOffset = ApplyMask(_receiveBuffer, _receiveBufferOffset, header.Mask, _receivedMaskOffsetOffset, bytesToCopy);
@@ -719,7 +722,7 @@ namespace System.Net.WebSockets
return new WebSocketReceiveResult(
bytesToCopy,
header.Opcode == MessageOpcode.Text ? WebSocketMessageType.Text : WebSocketMessageType.Binary,
- bytesToCopy == 0 || (header.Fin && header.PayloadLength == 0));
+ header.Fin && header.PayloadLength == 0);
}
}
catch (Exception exc)
diff --git a/src/Common/src/System/Runtime/InteropServices/FunctionWrapper.Unix.cs b/src/Common/src/System/Runtime/InteropServices/FunctionWrapper.Unix.cs
new file mode 100644
index 0000000000..244bab028d
--- /dev/null
+++ b/src/Common/src/System/Runtime/InteropServices/FunctionWrapper.Unix.cs
@@ -0,0 +1,12 @@
+// 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.Runtime.InteropServices
+{
+ internal static partial class FunctionWrapper
+ {
+ public static IntPtr LoadFunctionPointer(IntPtr nativeLibraryHandle, string functionName)
+ => Interop.Libdl.dlsym(nativeLibraryHandle, functionName);
+ }
+}
diff --git a/src/Common/src/System/Runtime/InteropServices/FunctionWrapper.Windows.cs b/src/Common/src/System/Runtime/InteropServices/FunctionWrapper.Windows.cs
new file mode 100644
index 0000000000..745821171e
--- /dev/null
+++ b/src/Common/src/System/Runtime/InteropServices/FunctionWrapper.Windows.cs
@@ -0,0 +1,12 @@
+// 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.Runtime.InteropServices
+{
+ internal static partial class FunctionWrapper
+ {
+ private static IntPtr LoadFunctionPointer(IntPtr nativeLibraryHandle, string functionName)
+ => Interop.Kernel32.GetProcAddress(nativeLibraryHandle, functionName);
+ }
+}
diff --git a/src/Common/src/System/Runtime/InteropServices/FunctionWrapper.cs b/src/Common/src/System/Runtime/InteropServices/FunctionWrapper.cs
new file mode 100644
index 0000000000..5e52a90bb4
--- /dev/null
+++ b/src/Common/src/System/Runtime/InteropServices/FunctionWrapper.cs
@@ -0,0 +1,78 @@
+// 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.Diagnostics;
+
+namespace System.Runtime.InteropServices
+{
+ /// <summary>
+ /// Utility class which lazily loads function pointers and throws a DllNotFoundException or
+ /// an EntryPointNotFoundException at usage-time if the function pointer can not be loaded.
+ /// </summary>
+ /// <typeparam name="T">The type of the function to wrap.</typeparam>
+ internal class FunctionWrapper<T> where T : class
+ {
+ private Lazy<FunctionLoadResult<T>> _lazyDelegate;
+
+ public FunctionWrapper(Lazy<FunctionLoadResult<T>> lazyDelegate)
+ {
+ _lazyDelegate = lazyDelegate;
+ }
+
+ public T Delegate
+ {
+ get
+ {
+ FunctionLoadResult<T> loadResult = _lazyDelegate.Value;
+ switch (loadResult.ResultKind)
+ {
+ case FunctionLoadResultKind.Success:
+ return loadResult.Delegate;
+ case FunctionLoadResultKind.LibraryNotFound:
+ throw new DllNotFoundException();
+ case FunctionLoadResultKind.FunctionNotFound:
+ throw new EntryPointNotFoundException();
+ default:
+ Debug.Fail("Illegal FunctionLoadResultKind: " + loadResult.ResultKind);
+ return null;
+ }
+ }
+ }
+ }
+
+ public enum FunctionLoadResultKind { Success, LibraryNotFound, FunctionNotFound }
+
+ public struct FunctionLoadResult<T>
+ {
+ public FunctionLoadResultKind ResultKind { get; }
+ public T Delegate { get; }
+ public FunctionLoadResult(FunctionLoadResultKind kind, T del) { ResultKind = kind; Delegate = del; }
+ }
+
+ internal static partial class FunctionWrapper
+ {
+ public static FunctionWrapper<T> Load<T>(IntPtr nativeLibraryHandle, string name) where T : class
+ {
+ Lazy<FunctionLoadResult<T>> lazyDelegate = new Lazy<FunctionLoadResult<T>>(() =>
+ {
+ if (nativeLibraryHandle == IntPtr.Zero)
+ {
+ return new FunctionLoadResult<T>(FunctionLoadResultKind.LibraryNotFound, null);
+ }
+
+ IntPtr funcPtr = LoadFunctionPointer(nativeLibraryHandle, name);
+ if (funcPtr == IntPtr.Zero)
+ {
+ return new FunctionLoadResult<T>(FunctionLoadResultKind.FunctionNotFound, null);
+ }
+ else
+ {
+ return new FunctionLoadResult<T>(FunctionLoadResultKind.Success, Marshal.GetDelegateForFunctionPointer<T>(funcPtr));
+ }
+ });
+
+ return new FunctionWrapper<T>(lazyDelegate);
+ }
+ }
+}
diff --git a/src/Common/tests/System/Buffers/NativeOwnedMemory.cs b/src/Common/tests/System/Buffers/NativeOwnedMemory.cs
new file mode 100644
index 0000000000..31d90b35bf
--- /dev/null
+++ b/src/Common/tests/System/Buffers/NativeOwnedMemory.cs
@@ -0,0 +1,110 @@
+// 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.Buffers;
+using System.Diagnostics;
+using System.Runtime.InteropServices;
+
+namespace System.IO.Tests
+{
+ internal sealed class NativeOwnedMemory : OwnedMemory<byte>
+ {
+ private readonly int _length;
+ private IntPtr _ptr;
+ private int _retainedCount;
+ private bool _disposed;
+
+ public NativeOwnedMemory(int length)
+ {
+ _length = length;
+ _ptr = Marshal.AllocHGlobal(length);
+ }
+
+ ~NativeOwnedMemory()
+ {
+ Debug.WriteLine($"{nameof(NativeOwnedMemory)} being finalized");
+ Dispose(false);
+ }
+
+ public override bool IsDisposed
+ {
+ get
+ {
+ lock (this)
+ {
+ return _disposed && _retainedCount == 0;
+ }
+ }
+ }
+
+ public override int Length => _length;
+
+ protected override bool IsRetained
+ {
+ get
+ {
+ lock (this)
+ {
+ return _retainedCount > 0;
+ }
+ }
+ }
+
+ public override unsafe Span<byte> Span => new Span<byte>((void*)_ptr, _length);
+
+ public override unsafe MemoryHandle Pin() => new MemoryHandle(this, (void*)_ptr);
+
+ public override bool Release()
+ {
+ lock (this)
+ {
+ if (_retainedCount > 0)
+ {
+ _retainedCount--;
+ if (_retainedCount == 0)
+ {
+ if (_disposed)
+ {
+ Marshal.FreeHGlobal(_ptr);
+ _ptr = IntPtr.Zero;
+ }
+ return true;
+ }
+ }
+ }
+ return false;
+ }
+
+ public override void Retain()
+ {
+ lock (this)
+ {
+ if (_retainedCount == 0 && _disposed)
+ {
+ throw new Exception();
+ }
+ _retainedCount++;
+ }
+ }
+
+ protected override void Dispose(bool disposing)
+ {
+ lock (this)
+ {
+ _disposed = true;
+ if (_retainedCount == 0)
+ {
+ Marshal.FreeHGlobal(_ptr);
+ _ptr = IntPtr.Zero;
+ }
+ }
+ }
+
+ protected override bool TryGetArray(out ArraySegment<byte> arraySegment)
+ {
+ arraySegment = default(ArraySegment<byte>);
+ return false;
+ }
+ }
+}
diff --git a/src/Common/tests/System/DirectoryServices/LdapConfiguration.cs b/src/Common/tests/System/DirectoryServices/LdapConfiguration.cs
new file mode 100644
index 0000000000..31f77a4171
--- /dev/null
+++ b/src/Common/tests/System/DirectoryServices/LdapConfiguration.cs
@@ -0,0 +1,117 @@
+// 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.Xml.Linq;
+
+namespace System.DirectoryServices.Tests
+{
+ internal class LdapConfiguration
+ {
+ private LdapConfiguration(string serverName, string domain, string userName, string password, string port, AuthenticationTypes at)
+ {
+ ServerName = serverName;
+ Domain = domain;
+ UserName = userName;
+ Password = password;
+ Port = port;
+ AuthenticationTypes = at;
+ }
+
+ private static LdapConfiguration s_ldapConfiguration = GetConfiguration("LDAP.Configuration.xml");
+
+ internal static LdapConfiguration Configuration => s_ldapConfiguration;
+
+ internal string ServerName { get; set; }
+ internal string UserName { get; set; }
+ internal string Password { get; set; }
+ internal string Port { get; set; }
+ internal string Domain { get; set; }
+ internal AuthenticationTypes AuthenticationTypes { get; set; }
+ internal string LdapPath => String.IsNullOrEmpty(Port) ? $"LDAP://{ServerName}/{Domain}" : $"LDAP://{ServerName}:{Port}/{Domain}";
+
+ internal string GetLdapPath(string prefix) // like "ou=something"
+ {
+ return String.IsNullOrEmpty(Port) ? $"LDAP://{ServerName}/{prefix},{Domain}" : $"LDAP://{ServerName}:{Port}/{prefix},{Domain}";
+ }
+
+ internal static LdapConfiguration GetConfiguration(string configFile)
+ {
+ if (!File.Exists(configFile))
+ return null;
+
+ LdapConfiguration ldapConfig = null;
+ try
+ {
+ string serverName = "";
+ string domain = "";
+ string port = "";
+ string user = "";
+ string password = "";
+ AuthenticationTypes at = AuthenticationTypes.None;
+
+ XElement config = XDocument.Load(configFile).Element("Configuration");
+ if (config != null)
+ {
+ XElement child = config.Element("ServerName");
+ if (child != null)
+ serverName = child.Value;
+
+ child = config.Element("Domain");
+ if (child != null)
+ domain = child.Value;
+
+ child = config.Element("Port");
+ if (child != null)
+ port = child.Value;
+
+ child = config.Element("User");
+ if (child != null)
+ user = child.Value;
+
+ child = config.Element("Password");
+ if (child != null)
+ password = child.Value;
+
+ child = config.Element("AuthenticationTypes");
+ if (child != null)
+ {
+ string[] parts = child.Value.Split(',');
+ foreach (string p in parts)
+ {
+ string s = p.Trim();
+ if (s.Equals("Anonymous", StringComparison.OrdinalIgnoreCase))
+ at |= AuthenticationTypes.Anonymous;
+ if (s.Equals("Delegation", StringComparison.OrdinalIgnoreCase))
+ at |= AuthenticationTypes.Delegation;
+ if (s.Equals("Encryption", StringComparison.OrdinalIgnoreCase))
+ at |= AuthenticationTypes.FastBind;
+ if (s.Equals("FastBind", StringComparison.OrdinalIgnoreCase))
+ at |= AuthenticationTypes.FastBind;
+ if (s.Equals("ReadonlyServer", StringComparison.OrdinalIgnoreCase))
+ at |= AuthenticationTypes.ReadonlyServer;
+ if (s.Equals("Sealing", StringComparison.OrdinalIgnoreCase))
+ at |= AuthenticationTypes.Sealing;
+ if (s.Equals("Secure", StringComparison.OrdinalIgnoreCase))
+ at |= AuthenticationTypes.Secure;
+ if (s.Equals("SecureSocketsLayer", StringComparison.OrdinalIgnoreCase))
+ at |= AuthenticationTypes.SecureSocketsLayer;
+ if (s.Equals("ServerBind", StringComparison.OrdinalIgnoreCase))
+ at |= AuthenticationTypes.ServerBind;
+ if (s.Equals("Signing", StringComparison.OrdinalIgnoreCase))
+ at |= AuthenticationTypes.Signing;
+ }
+ }
+
+ ldapConfig = new LdapConfiguration(serverName, domain, user, password, port, at);
+ }
+ }
+ catch
+ {
+ // Couldn't read the configurations, usually we'll skip the tests which depend on that
+ }
+ return ldapConfig;
+ }
+ }
+} \ No newline at end of file
diff --git a/src/Common/tests/System/IO/DelegateStream.cs b/src/Common/tests/System/IO/DelegateStream.cs
index 29aa5559ad..8af013cac9 100644
--- a/src/Common/tests/System/IO/DelegateStream.cs
+++ b/src/Common/tests/System/IO/DelegateStream.cs
@@ -52,16 +52,12 @@ namespace System.IO
_positionSetFunc = positionSetFunc ?? (_ => { throw new NotSupportedException(); });
_positionGetFunc = positionGetFunc ?? (() => { throw new NotSupportedException(); });
- if (readAsyncFunc != null && readFunc == null)
- throw new InvalidOperationException("If reads are supported, must provide a synchronous read implementation");
_readFunc = readFunc;
_readAsyncFunc = readAsyncFunc ?? ((buffer, offset, count, token) => base.ReadAsync(buffer, offset, count, token));
_seekFunc = seekFunc ?? ((_, __) => { throw new NotSupportedException(); });
_setLengthFunc = setLengthFunc ?? (_ => { throw new NotSupportedException(); });
- if (writeAsyncFunc != null && writeFunc == null)
- throw new InvalidOperationException("If writes are supported, must provide a synchronous write implementation");
_writeFunc = writeFunc;
_writeAsyncFunc = writeAsyncFunc ?? ((buffer, offset, count, token) => base.WriteAsync(buffer, offset, count, token));
}
diff --git a/src/Common/tests/System/IO/StreamSpanExtensions.netstandard.cs b/src/Common/tests/System/IO/StreamSpanExtensions.netstandard.cs
index a51d0c2321..f7520a3611 100644
--- a/src/Common/tests/System/IO/StreamSpanExtensions.netstandard.cs
+++ b/src/Common/tests/System/IO/StreamSpanExtensions.netstandard.cs
@@ -4,6 +4,8 @@
using System;
using System.IO;
+using System.Threading;
+using System.Threading.Tasks;
/// <summary>Extensions to enable the tests to use the span-based Read/Write methods that only exist in netcoreapp.</summary>
internal static class StreamSpanExtensions
@@ -18,9 +20,20 @@ internal static class StreamSpanExtensions
return bytesRead;
}
- public static void Write(this Stream stream, ReadOnlySpan<byte> source)
+ public static void Write(this Stream stream, ReadOnlySpan<byte> source) =>
+ stream.Write(source.ToArray(), 0, source.Length);
+
+ public static ValueTask<int> ReadAsync(this Stream stream, Memory<byte> destination, CancellationToken cancellationToken = default(CancellationToken))
{
- byte[] array = source.ToArray();
- stream.Write(array, 0, array.Length);
+ byte[] array = new byte[destination.Length];
+ return new ValueTask<int>(stream.ReadAsync(array, 0, array.Length, cancellationToken).ContinueWith(t =>
+ {
+ int bytesRead = t.GetAwaiter().GetResult();
+ new Span<byte>(array, 0, bytesRead).CopyTo(destination.Span);
+ return bytesRead;
+ }));
}
+
+ public static Task WriteAsync(this Stream stream, ReadOnlyMemory<byte> source, CancellationToken cancellationToken = default(CancellationToken)) =>
+ stream.WriteAsync(source.ToArray(), 0, source.Length, cancellationToken);
}
diff --git a/src/Common/tests/System/Linq/SkipTakeData.cs b/src/Common/tests/System/Linq/SkipTakeData.cs
index 4acd18b86f..b930eff7e3 100644
--- a/src/Common/tests/System/Linq/SkipTakeData.cs
+++ b/src/Common/tests/System/Linq/SkipTakeData.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.Collections;
using System.Collections.Generic;
namespace System.Linq.Tests
@@ -11,7 +10,7 @@ namespace System.Linq.Tests
{
public static IEnumerable<object[]> EnumerableData()
{
- IEnumerable<int> sourceCounts = new[] { 1, 2, 3, 5, 8, 13, 55, 100, 250 };
+ IEnumerable<int> sourceCounts = new[] { 0, 1, 2, 3, 5, 8, 13, 55, 100, 250 };
IEnumerable<int> counts = new[] { 1, 2, 3, 5, 8, 13, 21, 34, 55, 89, 100, 250, 500, int.MaxValue };
counts = counts.Concat(counts.Select(c => -c)).Append(0).Append(int.MinValue);
@@ -36,4 +35,4 @@ namespace System.Linq.Tests
});
}
}
-} \ No newline at end of file
+}
diff --git a/src/Common/tests/System/Net/Sockets/TestSettings.cs b/src/Common/tests/System/Net/Sockets/TestSettings.cs
index c0c7b9a270..1f20fc816e 100644
--- a/src/Common/tests/System/Net/Sockets/TestSettings.cs
+++ b/src/Common/tests/System/Net/Sockets/TestSettings.cs
@@ -7,7 +7,7 @@ namespace System.Net.Sockets.Tests
public static class TestSettings
{
// Timeout values in milliseconds.
- public const int PassingTestTimeout = 5000;
+ public const int PassingTestTimeout = 10000;
public const int FailingTestTimeout = 100;
// Number of redundant UDP packets to send to increase test reliability
diff --git a/src/Common/tests/System/Runtime/Serialization/Formatters/BinaryFormatterHelpers.cs b/src/Common/tests/System/Runtime/Serialization/Formatters/BinaryFormatterHelpers.cs
index 086f5a12e2..e3019a7842 100644
--- a/src/Common/tests/System/Runtime/Serialization/Formatters/BinaryFormatterHelpers.cs
+++ b/src/Common/tests/System/Runtime/Serialization/Formatters/BinaryFormatterHelpers.cs
@@ -88,5 +88,42 @@ namespace System.Runtime.Serialization.Formatters.Tests
Exception ex = Assert.Throws<TargetInvocationException>(() => constructor.Invoke(new object[] { info, new StreamingContext() }));
Assert.IsType<PlatformNotSupportedException>(ex.InnerException);
}
+
+ public static byte[] ToByteArray(object obj,
+ FormatterAssemblyStyle assemblyStyle = FormatterAssemblyStyle.Full)
+ {
+ BinaryFormatter bf = new BinaryFormatter();
+ bf.AssemblyFormat = assemblyStyle;
+ using (MemoryStream ms = new MemoryStream())
+ {
+ bf.Serialize(ms, obj);
+ return ms.ToArray();
+ }
+ }
+
+ public static string ToBase64String(object obj,
+ FormatterAssemblyStyle assemblyStyle = FormatterAssemblyStyle.Full)
+ {
+ byte[] raw = ToByteArray(obj, assemblyStyle);
+ return Convert.ToBase64String(raw);
+ }
+
+ public static object FromByteArray(byte[] raw,
+ FormatterAssemblyStyle assemblyStyle = FormatterAssemblyStyle.Full)
+ {
+ var binaryFormatter = new BinaryFormatter();
+ binaryFormatter.AssemblyFormat = assemblyStyle;
+ using (var serializedStream = new MemoryStream(raw))
+ {
+ return binaryFormatter.Deserialize(serializedStream);
+ }
+ }
+
+ public static object FromBase64String(string base64Str,
+ FormatterAssemblyStyle assemblyStyle = FormatterAssemblyStyle.Full)
+ {
+ byte[] raw = Convert.FromBase64String(base64Str);
+ return FromByteArray(raw, assemblyStyle);
+ }
}
}
diff --git a/src/Common/tests/System/Xml/DisableParallelization.cs b/src/Common/tests/System/Xml/DisableParallelization.cs
new file mode 100644
index 0000000000..5814b2aced
--- /dev/null
+++ b/src/Common/tests/System/Xml/DisableParallelization.cs
@@ -0,0 +1,6 @@
+// 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.
+
+// Tests are old and depend on the static state
+[assembly: Xunit.CollectionBehavior(DisableTestParallelization = true)]
diff --git a/src/Common/tests/System/Xml/ModuleCore/ModuleCore.csproj b/src/Common/tests/System/Xml/ModuleCore/ModuleCore.csproj
index fa46d46471..e1ca5c022f 100644
--- a/src/Common/tests/System/Xml/ModuleCore/ModuleCore.csproj
+++ b/src/Common/tests/System/Xml/ModuleCore/ModuleCore.csproj
@@ -22,6 +22,8 @@
<Compile Include="$(CommonPath)\System\Diagnostics\CodeAnalysis\ExcludeFromCodeCoverageAssemblyAttribute.cs">
<Link>Common\System\Diagnostics\CodeAnalysis\ExcludeFromCodeCoverageAssemblyAttribute.cs</Link>
</Compile>
+ <Compile Include="XunitRunner.cs" />
+ <Compile Include="XunitTestCase.cs" />
</ItemGroup>
<Import Project="$([MSBuild]::GetDirectoryNameOfFileAbove($(MSBuildThisFileDirectory), dir.targets))\dir.targets" />
-</Project> \ No newline at end of file
+</Project>
diff --git a/src/Common/tests/System/Xml/ModuleCore/XunitRunner.cs b/src/Common/tests/System/Xml/ModuleCore/XunitRunner.cs
new file mode 100644
index 0000000000..62526d2e0e
--- /dev/null
+++ b/src/Common/tests/System/Xml/ModuleCore/XunitRunner.cs
@@ -0,0 +1,100 @@
+// 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.Reflection;
+using System.Text;
+using System.Threading.Tasks;
+using Xunit.Abstractions;
+using Xunit.Sdk;
+
+namespace OLEDB.Test.ModuleCore
+{
+ public class XmlInlineDataDiscoverer : IDataDiscoverer
+ {
+ public static IEnumerable<object[]> GenerateTestCases(Func<CTestModule> moduleGenerator)
+ {
+ CModInfo.CommandLine = "";
+ foreach (object[] testCase in GenerateTestCasesForModule(moduleGenerator()))
+ {
+ yield return testCase;
+ }
+
+ CModInfo.CommandLine = "/async";
+ foreach (object[] testCase in GenerateTestCasesForModule(moduleGenerator()))
+ {
+ yield return testCase;
+ }
+ }
+
+ private static IEnumerable<object[]> GenerateTestCasesForModule(CTestModule module)
+ {
+ foreach (OLEDB.Test.ModuleCore.XunitTestCase testCase in module.TestCases())
+ {
+ yield return new object[] { testCase };
+ }
+ }
+
+ private static Type ToRuntimeType(ITypeInfo typeInfo)
+ {
+ var reflectionTypeInfo = typeInfo as IReflectionTypeInfo;
+ if (reflectionTypeInfo != null)
+ return reflectionTypeInfo.Type;
+
+ Assembly assembly = AppDomain.CurrentDomain.GetAssemblies().FirstOrDefault(a => a.FullName == typeInfo.Assembly.Name);
+ if (assembly != null)
+ {
+ return assembly.GetType(typeInfo.Name);
+ }
+
+ throw new Exception($"Could not find runtime type `{typeInfo.Name}`");
+ }
+
+ private static Type GetDeclaringType(IMethodInfo methodInfo)
+ {
+ var reflectionMethodInfo = methodInfo as IReflectionMethodInfo;
+ if (reflectionMethodInfo != null)
+ return reflectionMethodInfo.MethodInfo.DeclaringType;
+
+ return ToRuntimeType(methodInfo.Type);
+ }
+
+ public virtual IEnumerable<object[]> GetData(IAttributeInfo dataAttribute, IMethodInfo testMethod)
+ {
+ string methodName = (string)dataAttribute.GetConstructorArguments().Single();
+ Func<CTestModule> moduleGenerator = XmlTestsAttribute.GetGenerator(GetDeclaringType(testMethod), methodName);
+ return GenerateTestCases(moduleGenerator);
+ }
+
+ public virtual bool SupportsDiscoveryEnumeration(IAttributeInfo dataAttribute, IMethodInfo testMethod) => true;
+ }
+
+ [DataDiscoverer("OLEDB.Test.ModuleCore.XmlInlineDataDiscoverer", "ModuleCore")]
+ [AttributeUsage(AttributeTargets.Method, AllowMultiple = true)]
+ public sealed class XmlTestsAttribute : DataAttribute
+ {
+ private delegate CTestModule ModuleGenerator();
+
+ private string _methodName;
+
+ public XmlTestsAttribute(string methodName)
+ {
+ _methodName = methodName;
+ }
+
+ public static Func<CTestModule> GetGenerator(Type type, string methodName)
+ {
+ ModuleGenerator moduleGenerator = (ModuleGenerator)type.GetMethod(methodName).CreateDelegate(typeof(ModuleGenerator));
+ return new Func<CTestModule>(moduleGenerator);
+ }
+
+ public override IEnumerable<object[]> GetData(MethodInfo testMethod)
+ {
+ Func<CTestModule> moduleGenerator = GetGenerator(testMethod.DeclaringType, _methodName);
+ return XmlInlineDataDiscoverer.GenerateTestCases(moduleGenerator);
+ }
+ }
+}
diff --git a/src/Common/tests/System/Xml/ModuleCore/XunitTestCase.cs b/src/Common/tests/System/Xml/ModuleCore/XunitTestCase.cs
new file mode 100644
index 0000000000..f5bcaf0f86
--- /dev/null
+++ b/src/Common/tests/System/Xml/ModuleCore/XunitTestCase.cs
@@ -0,0 +1,36 @@
+using System;
+using System.Collections.Generic;
+using System.Linq;
+using System.Text;
+using System.Threading.Tasks;
+using Xunit;
+
+namespace OLEDB.Test.ModuleCore
+{
+ public class XunitTestCase
+ {
+ public string DisplayName { get; set; }
+ public Func<tagVARIATION_STATUS> Test { get; set; }
+
+ public XunitTestCase(string displayName, Func<tagVARIATION_STATUS> test)
+ {
+ DisplayName = displayName;
+ Test = test;
+ }
+
+ public override string ToString()
+ {
+ return DisplayName;
+ }
+
+ public void Run()
+ {
+ try
+ {
+ tagVARIATION_STATUS result = (tagVARIATION_STATUS)Test();
+ Assert.NotEqual(tagVARIATION_STATUS.eVariationStatusFailed, result);
+ }
+ catch (CTestSkippedException) { }
+ }
+ }
+}
diff --git a/src/Common/tests/System/Xml/ModuleCore/ctestbase.cs b/src/Common/tests/System/Xml/ModuleCore/ctestbase.cs
index 274b7d38c8..11899baec9 100644
--- a/src/Common/tests/System/Xml/ModuleCore/ctestbase.cs
+++ b/src/Common/tests/System/Xml/ModuleCore/ctestbase.cs
@@ -316,6 +316,9 @@ namespace OLEDB.Test.ModuleCore
{
return tagVARIATION_STATUS.eVariationStatusPassed;
}
+
+ public abstract IEnumerable<XunitTestCase> TestCases();
+
public int CompareTo(object o)
{
return this.id.CompareTo(((CTestBase)o).id);
diff --git a/src/Common/tests/System/Xml/ModuleCore/ctestcase.cs b/src/Common/tests/System/Xml/ModuleCore/ctestcase.cs
index 6c7f7bda5a..8e9a317fcd 100644
--- a/src/Common/tests/System/Xml/ModuleCore/ctestcase.cs
+++ b/src/Common/tests/System/Xml/ModuleCore/ctestcase.cs
@@ -101,6 +101,44 @@ namespace OLEDB.Test.ModuleCore
return tagVARIATION_STATUS.eVariationStatusPassed;
}
+ public override IEnumerable<XunitTestCase> TestCases()
+ {
+ List<object> children = Children;
+ if (children != null && children.Count > 0)
+ {
+ foreach (object child in children)
+ {
+ CTestCase childTc = child as CTestCase;
+ if (childTc != null)
+ {
+ childTc.Init();
+
+ foreach (XunitTestCase testCase in childTc.TestCases())
+ {
+ yield return testCase;
+ }
+
+ continue;
+ }
+
+ CVariation var = child as CVariation;
+ if (var != null && CModInfo.IsVariationSelected(var.Desc))
+ {
+ foreach (var testCase in var.TestCases())
+ {
+ Func<tagVARIATION_STATUS> test = testCase.Test;
+ testCase.Test = () => {
+ CurVariation = var;
+ return test();
+ };
+
+ yield return testCase;
+ }
+ }
+ }
+ }
+ }
+
public void RunVariation(dlgtTestVariation testmethod, Variation curVar)
{
if (!CModInfo.IsVariationSelected(curVar.Desc))
diff --git a/src/Common/tests/System/Xml/ModuleCore/ctestmodule.cs b/src/Common/tests/System/Xml/ModuleCore/ctestmodule.cs
index 935bb8a972..2762c4f23f 100644
--- a/src/Common/tests/System/Xml/ModuleCore/ctestmodule.cs
+++ b/src/Common/tests/System/Xml/ModuleCore/ctestmodule.cs
@@ -266,5 +266,28 @@ namespace OLEDB.Test.ModuleCore
Console.WriteLine("Pass:{0}, Fail:{1}, Skip:{2}", PassCount, FailCount, SkipCount);
return tagVARIATION_STATUS.eVariationStatusPassed;
}
+
+ public override IEnumerable<XunitTestCase> TestCases()
+ {
+ List<object> children = Children;
+ if (children != null && children.Count > 0)
+ {
+ foreach (object child in children)
+ {
+ CTestCase tc = child as CTestCase;
+ if (tc != null)
+ {
+ if (CModInfo.IsTestCaseSelected(tc.Name))
+ {
+ tc.Init();
+ foreach (XunitTestCase testCase in tc.TestCases())
+ {
+ yield return testCase;
+ }
+ }
+ }
+ }
+ }
+ }
}
}
diff --git a/src/Common/tests/System/Xml/ModuleCore/cvariation.cs b/src/Common/tests/System/Xml/ModuleCore/cvariation.cs
index d23a8884fd..03b2b2c2c2 100644
--- a/src/Common/tests/System/Xml/ModuleCore/cvariation.cs
+++ b/src/Common/tests/System/Xml/ModuleCore/cvariation.cs
@@ -3,7 +3,9 @@
// See the LICENSE file in the project root for more information.
using System;
+using System.Collections.Generic;
using System.Reflection;
+using System.Text;
namespace OLEDB.Test.ModuleCore
{
@@ -75,7 +77,20 @@ namespace OLEDB.Test.ModuleCore
int ret = _pfunc();
return (tagVARIATION_STATUS)ret;
}
+
throw new Exception("test method is null in CVariation");
}
+
+ public override IEnumerable<XunitTestCase> TestCases()
+ {
+ var sb = new StringBuilder();
+
+ if (!string.IsNullOrWhiteSpace(Name))
+ sb.Append(Name);
+
+ sb.Append(Desc);
+
+ yield return new XunitTestCase(sb.ToString(), Execute);
+ }
}
}
diff --git a/src/Common/tests/System/Xml/XPath/FuncLocation/PathAxeComplexExprMatchesTests.cs b/src/Common/tests/System/Xml/XPath/FuncLocation/PathAxeComplexExprMatchesTests.cs
index c9c60eefd5..1dde75d763 100644
--- a/src/Common/tests/System/Xml/XPath/FuncLocation/PathAxeComplexExprMatchesTests.cs
+++ b/src/Common/tests/System/Xml/XPath/FuncLocation/PathAxeComplexExprMatchesTests.cs
@@ -16,7 +16,7 @@ namespace XPathTests.FunctionalTests.Location.Paths.Axes.ComplexExpressions
public static partial class MatchesTests
{
/// <summary>
- /// Context node has a ancestor 'publication' so matches should return true
+ /// Context node has an ancestor 'publication' so matches should return true
/// node()[starts-with(string(name()),'p')]//node()[local-name()=""]
/// </summary>
[Fact]
diff --git a/src/CoreFx.Private.TestUtilities/ref/CoreFx.Private.TestUtilities.cs b/src/CoreFx.Private.TestUtilities/ref/CoreFx.Private.TestUtilities.cs
index c6ab660ed3..9f9f65465c 100644
--- a/src/CoreFx.Private.TestUtilities/ref/CoreFx.Private.TestUtilities.cs
+++ b/src/CoreFx.Private.TestUtilities/ref/CoreFx.Private.TestUtilities.cs
@@ -39,6 +39,7 @@ namespace System
public static bool IsReflectionEmitSupported;
public static bool ClientWebSocketPartialMessagesSupported { get { throw null; } }
public static System.PlatformDetection.Range[] FrameworkRanges { get { throw null; } }
+ public static bool HasWindowsShell { get { throw null; } }
public static bool IsArmProcess { get { throw null; } }
public static bool IsCentos7 { get { throw null; } }
public static bool IsDebian { get { throw null; } }
@@ -60,29 +61,39 @@ namespace System
public static bool IsNotWindows8x { get { throw null; } }
public static bool IsNotWindowsIoTCore { get { throw null; } }
public static bool IsNotWindowsNanoServer { get { throw null; } }
+ public static bool IsNotWindowsServerCore { get { throw null; } }
public static bool IsNotWindowsSubsystemForLinux { get { throw null; } }
- public static bool IsNotWinRT { get { throw null; } }
+ public static bool IsNotInAppContainer { get { throw null; } }
public static bool IsNotWinRTSupported { get { throw null; } }
public static bool IsOpenSUSE { get { throw null; } }
public static bool IsOSX { get { throw null; } }
public static bool IsSuperUser { get { throw null; } }
public static bool IsTizen { get { throw null; } }
+ public static bool IsRedHat { get { throw null; } }
+ public static bool IsNotRedHat { get { throw null; } }
+ public static bool IsRedHat69 { get { throw null; } }
+ public static bool IsNotRedHat69 { get { throw null; } }
public static bool IsUap { get { throw null; } }
public static Version ICUVersion { get { return null; } }
public static bool IsUbuntu { get { throw null; } }
public static bool IsUbuntu1404 { get { throw null; } }
+ public static bool IsUbuntu1604 { get { throw null; } }
+ public static bool IsUbuntu1704 { get { throw null; } }
+ public static bool IsUbuntu1710 { get { throw null; } }
public static bool IsWindows { get { throw null; } }
public static bool IsWindows10InsiderPreviewBuild16215OrGreater { get { throw null; } }
public static bool IsWindows10Version1607OrGreater { get { throw null; } }
public static bool IsWindows10Version16251OrGreater { get { throw null; } }
public static bool IsWindows10Version1703OrGreater { get { throw null; } }
+ public static bool IsWindowsRedStone2 { get { throw null; } }
public static bool IsWindows7 { get { throw null; } }
public static bool IsWindows8x { get { throw null; } }
public static bool IsWindowsAndElevated { get { throw null; } }
public static bool IsWindowsIoTCore { get { throw null; } }
public static bool IsWindowsNanoServer { get { throw null; } }
+ public static bool IsWindowsServerCore { get { throw null; } }
public static bool IsWindowsSubsystemForLinux { get { throw null; } }
- public static bool IsWinRT { get { throw null; } }
+ public static bool IsInAppContainer { get { throw null; } }
public static bool IsWinRTSupported { get { throw null; } }
public static bool IsXmlDsigXsltTransformSupported { get { throw null; } }
public static System.Version OSXKernelVersion { get { throw null; } }
@@ -123,6 +134,7 @@ namespace System.Diagnostics
public static System.Diagnostics.RemoteExecutorTestBase.RemoteInvokeHandle RemoteInvoke(System.Func<string, string, string, string, int> method, string arg1, string arg2, string arg3, string arg4, System.Diagnostics.RemoteInvokeOptions options=null) { throw null; }
public static System.Diagnostics.RemoteExecutorTestBase.RemoteInvokeHandle RemoteInvoke(System.Func<string, string, string, string, string, int> method, string arg1, string arg2, string arg3, string arg4, string arg5, System.Diagnostics.RemoteInvokeOptions options=null) { throw null; }
public static System.Diagnostics.RemoteExecutorTestBase.RemoteInvokeHandle RemoteInvoke(System.Func<System.Threading.Tasks.Task<int>> method, System.Diagnostics.RemoteInvokeOptions options=null) { throw null; }
+ public static System.Diagnostics.RemoteExecutorTestBase.RemoteInvokeHandle RemoteInvoke(System.Func<string, System.Threading.Tasks.Task<int>> method, string arg, System.Diagnostics.RemoteInvokeOptions options=null) { throw null; }
public static System.Diagnostics.RemoteExecutorTestBase.RemoteInvokeHandle RemoteInvokeRaw(System.Delegate method, string unparsedArg, System.Diagnostics.RemoteInvokeOptions options=null) { throw null; }
public sealed partial class RemoteInvokeHandle : System.IDisposable
{
diff --git a/src/CoreFx.Private.TestUtilities/src/CoreFx.Private.TestUtilities.csproj b/src/CoreFx.Private.TestUtilities/src/CoreFx.Private.TestUtilities.csproj
index f06e41b15d..92739a998d 100644
--- a/src/CoreFx.Private.TestUtilities/src/CoreFx.Private.TestUtilities.csproj
+++ b/src/CoreFx.Private.TestUtilities/src/CoreFx.Private.TestUtilities.csproj
@@ -40,6 +40,7 @@
<Compile Include="System\TheoryExtensions.cs" />
</ItemGroup>
<ItemGroup>
+ <Reference Include="Microsoft.Win32.Registry" />
<Reference Include="System.Runtime" />
<Reference Include="System.IO.FileSystem" />
<Reference Include="System.Linq" />
diff --git a/src/CoreFx.Private.TestUtilities/src/System/Diagnostics/RemoteExecutorTestBase.cs b/src/CoreFx.Private.TestUtilities/src/System/Diagnostics/RemoteExecutorTestBase.cs
index 78ceb4a997..9ff440256c 100644
--- a/src/CoreFx.Private.TestUtilities/src/System/Diagnostics/RemoteExecutorTestBase.cs
+++ b/src/CoreFx.Private.TestUtilities/src/System/Diagnostics/RemoteExecutorTestBase.cs
@@ -44,6 +44,17 @@ namespace System.Diagnostics
/// <summary>Invokes the method from this assembly in another process using the specified arguments.</summary>
/// <param name="method">The method to invoke.</param>
+ /// <param name="options">Options to use for the invocation.</param>
+ public static RemoteInvokeHandle RemoteInvoke(
+ Func<string, Task<int>> method,
+ string arg,
+ RemoteInvokeOptions options = null)
+ {
+ return RemoteInvoke(GetMethodInfo(method), new[] { arg }, options);
+ }
+
+ /// <summary>Invokes the method from this assembly in another process using the specified arguments.</summary>
+ /// <param name="method">The method to invoke.</param>
/// <param name="arg1">The first argument to pass to the method.</param>
/// <param name="options">Options to use for the invocation.</param>
public static RemoteInvokeHandle RemoteInvoke(
diff --git a/src/CoreFx.Private.TestUtilities/src/System/PlatformDetection.Unix.cs b/src/CoreFx.Private.TestUtilities/src/System/PlatformDetection.Unix.cs
index 44674d6cdc..abb86f9399 100644
--- a/src/CoreFx.Private.TestUtilities/src/System/PlatformDetection.Unix.cs
+++ b/src/CoreFx.Private.TestUtilities/src/System/PlatformDetection.Unix.cs
@@ -25,7 +25,7 @@ namespace System
public static bool IsNetfx462OrNewer() { return false; }
public static bool IsNetfx470OrNewer() { return false; }
public static bool IsNetfx471OrNewer() { return false; }
- public static bool IsWinRT => false;
+ public static bool IsInAppContainer => false;
public static int WindowsVersion => -1;
public static bool IsOpenSUSE => IsDistroAndVersion("opensuse");
@@ -33,20 +33,30 @@ namespace System
public static bool IsDebian => IsDistroAndVersion("debian");
public static bool IsDebian8 => IsDistroAndVersion("debian", "8");
public static bool IsUbuntu1404 => IsDistroAndVersion("ubuntu", "14.04");
+ public static bool IsUbuntu1604 => IsDistroAndVersion("ubuntu", "16.04");
+ public static bool IsUbuntu1704 => IsDistroAndVersion("ubuntu", "17.04");
+ public static bool IsUbuntu1710 => IsDistroAndVersion("ubuntu", "17.10");
public static bool IsCentos7 => IsDistroAndVersion("centos", "7");
public static bool IsTizen => IsDistroAndVersion("tizen");
public static bool IsNotFedoraOrRedHatOrCentos => !IsDistroAndVersion("fedora") && !IsDistroAndVersion("rhel") && !IsDistroAndVersion("centos");
public static bool IsFedora => IsDistroAndVersion("fedora");
public static bool IsWindowsNanoServer => false;
+ public static bool IsWindowsServerCore => false;
public static bool IsWindowsAndElevated => false;
+ public static bool IsWindowsRedStone2 => false;
+
+ public static bool IsRedHat => IsDistroAndVersion("rhel") || IsDistroAndVersion("rhl");
+ public static bool IsNotRedHat => !IsRedHat;
+ public static bool IsRedHat69 => IsDistroAndVersion("rhel", "6.9") || IsDistroAndVersion("rhl", "6.9");
+ public static bool IsNotRedHat69 => !IsRedHat69;
public static Version OSXKernelVersion { get; } = GetOSXKernelVersion();
public static string GetDistroVersionString()
{
- if (!RuntimeInformation.IsOSPlatform(OSPlatform.Linux))
+ if (RuntimeInformation.IsOSPlatform(OSPlatform.OSX))
{
- return "";
+ return "OSX Version=" + s_osxProductVersion.ToString();
}
DistroInfo v = ParseOsReleaseFile();
@@ -103,6 +113,77 @@ namespace System
}
}
}
+ else
+ {
+ string fileName = null;
+ if (File.Exists("/etc/redhat-release"))
+ fileName = "/etc/redhat-release";
+
+ if (fileName == null && File.Exists("/etc/system-release"))
+ fileName = "/etc/system-release";
+
+ if (fileName != null)
+ {
+ // Parse the format like the following line:
+ // Red Hat Enterprise Linux Server release 7.3 (Maipo)
+ using (StreamReader file = new StreamReader(fileName))
+ {
+ string line = file.ReadLine();
+ if (!String.IsNullOrEmpty(line))
+ {
+ if (line.StartsWith("Red Hat Enterprise Linux", StringComparison.OrdinalIgnoreCase))
+ {
+ ret.Id = "rhel";
+ }
+ else if (line.StartsWith("Centos", StringComparison.OrdinalIgnoreCase))
+ {
+ ret.Id = "centos";
+ }
+ else if (line.StartsWith("Red Hat", StringComparison.OrdinalIgnoreCase))
+ {
+ ret.Id = "rhl";
+ }
+ else
+ {
+ // automatically generate the distro label
+ string [] words = line.Split(' ');
+ StringBuilder sb = new StringBuilder();
+
+ foreach (string word in words)
+ {
+ if (word.Length > 0)
+ {
+ if (Char.IsNumber(word[0]) ||
+ word.Equals("release", StringComparison.OrdinalIgnoreCase) ||
+ word.Equals("server", StringComparison.OrdinalIgnoreCase))
+ {
+ break;
+ }
+ sb.Append(Char.ToLower(word[0]));
+ }
+ }
+ ret.Id = sb.ToString();
+ }
+
+ int i = 0;
+ while (i < line.Length && !Char.IsNumber(line[i])) // stop at first number
+ i++;
+
+ if (i < line.Length)
+ {
+ int j = i + 1;
+ while (j < line.Length && (Char.IsNumber(line[j]) || line[j] == '.'))
+ j++;
+
+ ret.VersionId = line.Substring(i, j - i);
+ ret.Version = line.Substring(i, line.Length - i);
+ }
+
+ ret.PrettyName = line;
+ }
+ }
+ }
+ }
return ret;
}
diff --git a/src/CoreFx.Private.TestUtilities/src/System/PlatformDetection.Windows.cs b/src/CoreFx.Private.TestUtilities/src/System/PlatformDetection.Windows.cs
index 47ad879a1c..ce31c9965a 100644
--- a/src/CoreFx.Private.TestUtilities/src/System/PlatformDetection.Windows.cs
+++ b/src/CoreFx.Private.TestUtilities/src/System/PlatformDetection.Windows.cs
@@ -2,9 +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 Microsoft.Win32;
using System.Diagnostics;
using System.IO;
using System.Runtime.InteropServices;
+using System.Security;
using System.Text;
using Xunit;
@@ -19,14 +21,22 @@ namespace System
public static bool IsDebian => false;
public static bool IsDebian8 => false;
public static bool IsUbuntu1404 => false;
+ public static bool IsUbuntu1604 => false;
+ public static bool IsUbuntu1704 => false;
+ public static bool IsUbuntu1710 => false;
public static bool IsCentos7 => false;
public static bool IsTizen => false;
public static bool IsNotFedoraOrRedHatOrCentos => true;
public static bool IsFedora => false;
- public static bool IsWindowsNanoServer => (IsNotWindowsIoTCore && !File.Exists(Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.Windows), "regedit.exe")));
+ public static bool IsWindowsNanoServer => (IsNotWindowsIoTCore && GetInstallationType().Equals("Nano Server", StringComparison.OrdinalIgnoreCase));
+ public static bool IsWindowsServerCore => GetInstallationType().Equals("Server Core", StringComparison.OrdinalIgnoreCase);
public static int WindowsVersion => GetWindowsVersion();
public static bool IsMacOsHighSierraOrHigher { get; } = false;
public static Version ICUVersion => new Version(0, 0, 0, 0);
+ public static bool IsRedHat => false;
+ public static bool IsNotRedHat => true;
+ public static bool IsRedHat69 => false;
+ public static bool IsNotRedHat69 => true;
public static bool IsWindows10Version1607OrGreater =>
GetWindowsVersion() == 10 && GetWindowsMinorVersion() == 0 && GetWindowsBuildNumber() >= 14393;
@@ -36,6 +46,8 @@ namespace System
GetWindowsVersion() == 10 && GetWindowsMinorVersion() == 0 && GetWindowsBuildNumber() >= 16215;
public static bool IsWindows10Version16251OrGreater =>
GetWindowsVersion() == 10 && GetWindowsMinorVersion() == 0 && GetWindowsBuildNumber() >= 16251;
+ public static bool IsWindowsRedStone2 => // Creators Update version
+ GetWindowsVersion() == 10 && (GetWindowsBuildNumber() / 1000) == 15; // any build with 15xxx. e.g 15063
// Windows OneCoreUAP SKU doesn't have httpapi.dll
public static bool IsNotOneCoreUAP =>
@@ -45,8 +57,7 @@ namespace System
{
get
{
- int productType;
- Assert.True(GetProductInfo(Environment.OSVersion.Version.Major, Environment.OSVersion.Version.Minor, 0, 0, out productType));
+ int productType = GetWindowsProductType();
if ((productType == PRODUCT_IOTUAPCOMMERCIAL) ||
(productType == PRODUCT_IOTUAP))
{
@@ -114,20 +125,24 @@ namespace System
return null;
}
- public static string GetDistroVersionString() { return ""; }
+ public static string GetDistroVersionString() { return "ProductType=" + GetWindowsProductType() + "InstallationType=" + GetInstallationType(); }
- private static int s_isWinRT = -1;
+ private static int s_isInAppContainer = -1;
- public static bool IsWinRT
+ public static bool IsInAppContainer
{
+ // This actually checks whether code is running in a modern app.
+ // Currently this is the only situation where we run in app container.
+ // If we want to distinguish the two cases in future,
+ // EnvironmentHelpers.IsAppContainerProcess in desktop code shows how to check for the AC token.
get
{
- if (s_isWinRT != -1)
- return s_isWinRT == 1;
+ if (s_isInAppContainer != -1)
+ return s_isInAppContainer == 1;
if (!IsWindows || IsWindows7)
{
- s_isWinRT = 0;
+ s_isInAppContainer = 0;
return false;
}
@@ -139,7 +154,7 @@ namespace System
switch (result)
{
case 15703: // APPMODEL_ERROR_NO_APPLICATION
- s_isWinRT = 0;
+ s_isInAppContainer = 0;
break;
case 0: // ERROR_SUCCESS
case 122: // ERROR_INSUFFICIENT_BUFFER
@@ -147,7 +162,7 @@ namespace System
// not NO_APPLICATION and we're not actually giving a buffer here. The
// API will always return NO_APPLICATION if we're not running under a
// WinRT process, no matter what size the buffer is.
- s_isWinRT = 1;
+ s_isInAppContainer = 1;
break;
default:
throw new InvalidOperationException($"Failed to get AppId, result was {result}.");
@@ -160,7 +175,7 @@ namespace System
if (e.GetType().FullName.Equals("System.EntryPointNotFoundException", StringComparison.Ordinal))
{
// API doesn't exist, likely pre Win8
- s_isWinRT = 0;
+ s_isInAppContainer = 0;
}
else
{
@@ -168,7 +183,7 @@ namespace System
}
}
- return s_isWinRT == 1;
+ return s_isInAppContainer == 1;
}
}
@@ -181,7 +196,7 @@ namespace System
if (s_isWindowsElevated != -1)
return s_isWindowsElevated == 1;
- if (!IsWindows || IsWinRT)
+ if (!IsWindows || IsInAppContainer)
{
s_isWindowsElevated = 0;
return false;
@@ -208,30 +223,42 @@ namespace System
}
}
- private static int GetWindowsMinorVersion()
+ private static string GetInstallationType()
{
- if (IsWindows)
+ string key = @"HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\Windows NT\CurrentVersion";
+ string value = "";
+
+ try
+ {
+ value = (string)Registry.GetValue(key, "InstallationType", defaultValue: "");
+ }
+ catch (Exception e) when (e is SecurityException || e is InvalidCastException || e is PlatformNotSupportedException /* UAP */)
{
- RTL_OSVERSIONINFOEX osvi = new RTL_OSVERSIONINFOEX();
- osvi.dwOSVersionInfoSize = (uint)Marshal.SizeOf(osvi);
- Assert.Equal(0, RtlGetVersion(out osvi));
- return (int)osvi.dwMinorVersion;
}
- return -1;
+ return value;
}
- private static int GetWindowsBuildNumber()
+ private static int GetWindowsProductType()
{
- if (IsWindows)
- {
- RTL_OSVERSIONINFOEX osvi = new RTL_OSVERSIONINFOEX();
- osvi.dwOSVersionInfoSize = (uint)Marshal.SizeOf(osvi);
- Assert.Equal(0, RtlGetVersion(out osvi));
- return (int)osvi.dwBuildNumber;
- }
+ Assert.True(GetProductInfo(Environment.OSVersion.Version.Major, Environment.OSVersion.Version.Minor, 0, 0, out int productType));
+ return productType;
+ }
+
+ private static int GetWindowsMinorVersion()
+ {
+ RTL_OSVERSIONINFOEX osvi = new RTL_OSVERSIONINFOEX();
+ osvi.dwOSVersionInfoSize = (uint)Marshal.SizeOf(osvi);
+ Assert.Equal(0, RtlGetVersion(out osvi));
+ return (int)osvi.dwMinorVersion;
+ }
- return -1;
+ private static int GetWindowsBuildNumber()
+ {
+ RTL_OSVERSIONINFOEX osvi = new RTL_OSVERSIONINFOEX();
+ osvi.dwOSVersionInfoSize = (uint)Marshal.SizeOf(osvi);
+ Assert.Equal(0, RtlGetVersion(out osvi));
+ return (int)osvi.dwBuildNumber;
}
private const uint TokenElevation = 20;
diff --git a/src/CoreFx.Private.TestUtilities/src/System/PlatformDetection.cs b/src/CoreFx.Private.TestUtilities/src/System/PlatformDetection.cs
index c5fed10f79..db9816cdd7 100644
--- a/src/CoreFx.Private.TestUtilities/src/System/PlatformDetection.cs
+++ b/src/CoreFx.Private.TestUtilities/src/System/PlatformDetection.cs
@@ -18,7 +18,8 @@ namespace System
// do it in a way that failures don't cascade.
//
- public static bool IsUap => IsWinRT || IsNetNative;
+ public static bool HasWindowsShell => IsNotWindowsServerCore && IsNotWindowsNanoServer && IsNotWindowsIoTCore;
+ public static bool IsUap => IsInAppContainer || 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);
@@ -26,13 +27,14 @@ namespace System
public static bool IsNetBSD => RuntimeInformation.IsOSPlatform(OSPlatform.Create("NETBSD"));
public static bool IsNotWindows8x => !IsWindows8x;
public static bool IsNotWindowsNanoServer => !IsWindowsNanoServer;
+ public static bool IsNotWindowsServerCore => !IsWindowsServerCore;
public static bool IsNotWindowsIoTCore => !IsWindowsIoTCore;
public static bool IsDrawingSupported => (IsNotWindowsNanoServer && IsNotWindowsIoTCore);
public static bool IsArmProcess => RuntimeInformation.ProcessArchitecture == Architecture.Arm;
public static bool IsNotArmProcess => !IsArmProcess;
- public static bool IsNotWinRT => !IsWinRT;
- public static bool IsWinRTSupported => IsWinRT || (IsWindows && !IsWindows7);
+ public static bool IsNotInAppContainer => !IsInAppContainer;
+ public static bool IsWinRTSupported => IsWindows && !IsWindows7;
public static bool IsNotWinRTSupported => !IsWinRTSupported;
public static bool IsNotMacOsHighSierraOrHigher => !IsMacOsHighSierraOrHigher;
@@ -40,7 +42,7 @@ namespace System
// in a normal Win32 process and we often do so as running in an AppContainer imposes a substantial tax in debuggability
// and investigatability. This predicate is used in ConditionalFacts to disable the specific tests that really need to be
// running in AppContainer when running on .NetNative.
- public static bool IsNotNetNativeRunningAsConsoleApp => !(IsNetNative && !IsWinRT);
+ public static bool IsNotNetNativeRunningAsConsoleApp => !(IsNetNative && !IsInAppContainer);
private static Lazy<bool> m_isWindowsSubsystemForLinux = new Lazy<bool>(GetIsWindowsSubsystemForLinux);
diff --git a/src/Microsoft.CSharp/src/Microsoft.CSharp.csproj b/src/Microsoft.CSharp/src/Microsoft.CSharp.csproj
index d66885a42e..c65e276ef8 100644
--- a/src/Microsoft.CSharp/src/Microsoft.CSharp.csproj
+++ b/src/Microsoft.CSharp/src/Microsoft.CSharp.csproj
@@ -129,7 +129,6 @@
<Compile Include="Microsoft\CSharp\RuntimeBinder\Semantics\Tree\LocalVariable.cs" />
<Compile Include="Microsoft\CSharp\RuntimeBinder\Semantics\Tree\MemberGroup.cs" />
<Compile Include="Microsoft\CSharp\RuntimeBinder\Semantics\Tree\MethodInfo.cs" />
- <Compile Include="Microsoft\CSharp\RuntimeBinder\Semantics\Tree\MethodReference.cs" />
<Compile Include="Microsoft\CSharp\RuntimeBinder\Semantics\Tree\NamedArgumentSpecification.cs" />
<Compile Include="Microsoft\CSharp\RuntimeBinder\Semantics\Tree\Property.cs" />
<Compile Include="Microsoft\CSharp\RuntimeBinder\Semantics\Tree\PropertyInfo.cs" />
diff --git a/src/Microsoft.CSharp/src/Microsoft/CSharp/RuntimeBinder/Errors/ErrorCode.cs b/src/Microsoft.CSharp/src/Microsoft/CSharp/RuntimeBinder/Errors/ErrorCode.cs
index 5279d0b586..0490b2b037 100644
--- a/src/Microsoft.CSharp/src/Microsoft/CSharp/RuntimeBinder/Errors/ErrorCode.cs
+++ b/src/Microsoft.CSharp/src/Microsoft/CSharp/RuntimeBinder/Errors/ErrorCode.cs
@@ -24,7 +24,6 @@ namespace Microsoft.CSharp.RuntimeBinder.Errors
ERR_MethDelegateMismatch = 123,
ERR_AssgLvalueExpected = 131,
ERR_NoConstructors = 143,
- ERR_BadDelegateConstructor = 148,
ERR_PropertyLacksGet = 154,
ERR_ObjectProhibited = 176,
ERR_AssgReadonly = 191,
@@ -42,7 +41,6 @@ namespace Microsoft.CSharp.RuntimeBinder.Errors
ERR_InaccessibleGetter = 271,
ERR_InaccessibleSetter = 272,
ERR_BadArity = 305,
- ERR_BadTypeArgument = 306,
ERR_TypeArgsNotAllowed = 307,
ERR_HasNoTypeVars = 308,
ERR_NewConstraintNotSatisfied = 310,
@@ -51,16 +49,13 @@ namespace Microsoft.CSharp.RuntimeBinder.Errors
ERR_GenericConstraintNotSatisfiedNullableInterface = 313,
ERR_GenericConstraintNotSatisfiedValType = 315,
ERR_TypeVarCantBeNull = 403,
- ERR_BadRetType = 407,
ERR_CantInferMethTypeArgs = 411,
- ERR_MethGrpToNonDel = 428,
ERR_RefConstraintNotSatisfied = 452,
ERR_ValConstraintNotSatisfied = 453,
ERR_AmbigUDConv = 457,
ERR_BindToBogus = 570,
ERR_CantCallSpecialMethod = 571,
ERR_ConvertToStaticClass = 716,
- ERR_GenericArgIsStaticClass = 718,
ERR_IncrementLvalueExpected = 1059,
ERR_BadArgCount = 1501,
ERR_BadArgTypes = 1502,
@@ -79,7 +74,6 @@ namespace Microsoft.CSharp.RuntimeBinder.Errors
ERR_RefReadonlyStatic2 = 1651,
ERR_AssgReadonlyLocalCause = 1656,
ERR_RefReadonlyLocalCause = 1657,
- ERR_DelegateOnNullable = 1728,
ERR_BadCtorArgCount = 1729,
ERR_NonInvocableMemberCalled = 1955,
ERR_NamedArgumentSpecificationBeforeFixedArgument = 5002,
diff --git a/src/Microsoft.CSharp/src/Microsoft/CSharp/RuntimeBinder/Errors/ErrorFacts.cs b/src/Microsoft.CSharp/src/Microsoft/CSharp/RuntimeBinder/Errors/ErrorFacts.cs
index 8e46385386..6a9538c382 100644
--- a/src/Microsoft.CSharp/src/Microsoft/CSharp/RuntimeBinder/Errors/ErrorFacts.cs
+++ b/src/Microsoft.CSharp/src/Microsoft/CSharp/RuntimeBinder/Errors/ErrorFacts.cs
@@ -68,9 +68,6 @@ namespace Microsoft.CSharp.RuntimeBinder.Errors
case ErrorCode.ERR_NoConstructors:
codeStr = SR.NoConstructors;
break;
- case ErrorCode.ERR_BadDelegateConstructor:
- codeStr = SR.BadDelegateConstructor;
- break;
case ErrorCode.ERR_PropertyLacksGet:
codeStr = SR.PropertyLacksGet;
break;
@@ -122,9 +119,6 @@ namespace Microsoft.CSharp.RuntimeBinder.Errors
case ErrorCode.ERR_BadArity:
codeStr = SR.BadArity;
break;
- case ErrorCode.ERR_BadTypeArgument:
- codeStr = SR.BadTypeArgument;
- break;
case ErrorCode.ERR_TypeArgsNotAllowed:
codeStr = SR.TypeArgsNotAllowed;
break;
@@ -149,15 +143,9 @@ namespace Microsoft.CSharp.RuntimeBinder.Errors
case ErrorCode.ERR_TypeVarCantBeNull:
codeStr = SR.TypeVarCantBeNull;
break;
- case ErrorCode.ERR_BadRetType:
- codeStr = SR.BadRetType;
- break;
case ErrorCode.ERR_CantInferMethTypeArgs:
codeStr = SR.CantInferMethTypeArgs;
break;
- case ErrorCode.ERR_MethGrpToNonDel:
- codeStr = SR.MethGrpToNonDel;
- break;
case ErrorCode.ERR_RefConstraintNotSatisfied:
codeStr = SR.RefConstraintNotSatisfied;
break;
@@ -176,9 +164,6 @@ namespace Microsoft.CSharp.RuntimeBinder.Errors
case ErrorCode.ERR_ConvertToStaticClass:
codeStr = SR.ConvertToStaticClass;
break;
- case ErrorCode.ERR_GenericArgIsStaticClass:
- codeStr = SR.GenericArgIsStaticClass;
- break;
case ErrorCode.ERR_IncrementLvalueExpected:
codeStr = SR.IncrementLvalueExpected;
break;
@@ -233,9 +218,6 @@ namespace Microsoft.CSharp.RuntimeBinder.Errors
case ErrorCode.ERR_RefReadonlyLocalCause:
codeStr = SR.RefReadonlyLocalCause;
break;
- case ErrorCode.ERR_DelegateOnNullable:
- codeStr = SR.DelegateOnNullable;
- break;
case ErrorCode.ERR_BadCtorArgCount:
codeStr = SR.BadCtorArgCount;
break;
diff --git a/src/Microsoft.CSharp/src/Microsoft/CSharp/RuntimeBinder/Errors/UserStringBuilder.cs b/src/Microsoft.CSharp/src/Microsoft/CSharp/RuntimeBinder/Errors/UserStringBuilder.cs
index 339881c19e..0c9b94e586 100644
--- a/src/Microsoft.CSharp/src/Microsoft/CSharp/RuntimeBinder/Errors/UserStringBuilder.cs
+++ b/src/Microsoft.CSharp/src/Microsoft/CSharp/RuntimeBinder/Errors/UserStringBuilder.cs
@@ -150,35 +150,6 @@ namespace Microsoft.CSharp.RuntimeBinder.Errors
ErrAppendParentCore(sym.parent, pctx);
}
- private void ErrAppendParentType(CType pType, SubstContext pctx)
- {
- if (pType is ErrorType err)
- {
- if (err.HasTypeParent())
- {
- ErrAppendType(err.GetTypeParent(), null);
- ErrAppendChar('.');
- }
- else
- {
- ErrAppendParentCore(err.GetNSParent(), pctx);
- }
- }
- else if (pType is AggregateType agg)
- {
- ErrAppendParentCore(agg.GetOwningAggregate(), pctx);
- }
- else
- {
- var part = pType.GetBaseOrParameterOrElementType();
- if (part != null)
- {
- ErrAppendType(part, null);
- ErrAppendChar('.');
- }
- }
- }
-
private void ErrAppendParentCore(Symbol parent, SubstContext pctx)
{
if (null == parent)
@@ -533,10 +504,9 @@ namespace Microsoft.CSharp.RuntimeBinder.Errors
case TypeKind.TK_ErrorType:
ErrorType err = (ErrorType)pType;
- if (err.HasParent())
+ if (err.HasParent)
{
Debug.Assert(err.nameText != null && err.typeArgs != null);
- ErrAppendParentType(pType, pctx);
ErrAppendName(err.nameText);
ErrAppendTypeParameters(err.typeArgs, pctx, true);
}
diff --git a/src/Microsoft.CSharp/src/Microsoft/CSharp/RuntimeBinder/Semantics/Conversion.cs b/src/Microsoft.CSharp/src/Microsoft/CSharp/RuntimeBinder/Semantics/Conversion.cs
index 4fa7c2079e..6a6c8866b1 100644
--- a/src/Microsoft.CSharp/src/Microsoft/CSharp/RuntimeBinder/Semantics/Conversion.cs
+++ b/src/Microsoft.CSharp/src/Microsoft/CSharp/RuntimeBinder/Semantics/Conversion.cs
@@ -363,6 +363,7 @@ namespace Microsoft.CSharp.RuntimeBinder.Semantics
private Expr mustConvertCore(Expr expr, ExprClass destExpr, CONVERTTYPE flags)
{
+ Debug.Assert(!(expr is ExprMemberGroup));
Expr exprResult;
CType dest = destExpr.Type;
@@ -400,11 +401,6 @@ namespace Microsoft.CSharp.RuntimeBinder.Semantics
throw ErrorContext.Error(dest is TypeParameterType ? ErrorCode.ERR_TypeVarCantBeNull : ErrorCode.ERR_ValueCantBeNull, dest);
}
- if (expr is ExprMemberGroup memGrp)
- {
- BindGrpConversion(memGrp, dest, true);
- }
-
// canCast => can't convert, but explicit exists and can be specified by the user (no anonymous types).
// !canCast => Generic "can't convert" error.
throw ErrorContext.Error(canCast(expr.Type, dest, flags) ? ErrorCode.ERR_NoImplicitConvCast : ErrorCode.ERR_NoImplicitConv, new ErrArg(expr.Type, ErrArgFlags.Unique), new ErrArg(dest, ErrArgFlags.Unique));
@@ -463,6 +459,7 @@ namespace Microsoft.CSharp.RuntimeBinder.Semantics
// performs an explicit conversion if its possible. otherwise displays an error.
private Expr mustCastCore(Expr expr, ExprClass destExpr, CONVERTTYPE flags)
{
+ Debug.Assert(!(expr is ExprMemberGroup));
Expr exprResult;
CType dest = destExpr.Type;
@@ -530,14 +527,8 @@ namespace Microsoft.CSharp.RuntimeBinder.Semantics
{
throw ErrorContext.Error(ErrorCode.ERR_ValueCantBeNull, dest);
}
- else if (expr is ExprMemberGroup memGrp)
- {
- BindGrpConversion(memGrp, dest, true);
- }
- else
- {
- CantConvert(expr, dest);
- }
+
+ CantConvert(expr, dest);
}
}
CANTCONVERT:
@@ -577,185 +568,6 @@ namespace Microsoft.CSharp.RuntimeBinder.Semantics
return BindExplicitConversion(null, src, destExpr, dest, flags);
}
- /***************************************************************************************************
- Convert a method group to a delegate type.
-
- NOTE: Currently it is not well defined when there is an implicit conversion from a method
- group to a delegate type. There are several possibilities. On the two extremes are:
-
- (1) (Most permissive) When there is at least one applicable method in the method group.
-
- (2) (Most restrictive) When all of the following are satisfied:
- * Overload resolution does not produce an error
- * The method's parameter types don't require any conversions other than implicit reference
- conversions.
- * The method's return type is compatible.
- * The method's constraints are satisfied.
- * The method is not conditional.
-
- For (1), it may be the case that an error is produced whenever the conversion is actually used.
- For example, if the result of overload resolution is ambiguous or if the result of overload
- resolution is a method with the wrong return result or with unsatisfied constraints.
-
- For (2), the intent is that if the answer is yes, then an error is never produced.
-
- Note that (2) is not monotone: adding a method to the method group may cause the answer
- to go from yes to no. This has a very odd effect in certain situations:
-
- Suppose:
- * I1 and J1 are interfaces with I1 : J1.
- * I2, J2 and K2 are interfaces with I2 : J2, K2.
- * Di is a delegate type with signature void Di(Ii).
- * A method group named F contains F(D1(I1)) and F(D2(I2)).
- * There is another method group named M containing a subset of:
- void M(J1)
- void M(J2)
- void M(K2)
-
- Under any of the definitions we're considering:
-
- * If M is { M(J1), M(J2) } then F(M) is an error (ambiguous between F(D1) and F(D2)).
- * If M is { M(J1), M(K2) } then F(M) is an error (ambiguous between F(D1) and F(D2)).
- * If M is { M(J2), M(K2) } then F(M) is an error (M -> D2 is ambiguous).
-
- If M is { M(J1), M(J2), M(K2) } what should F(M) be? It seems logical for F(M) to be ambiguous
- in this case as well. However, under definition (2), there is no implicit conversion from M
- to D2 (since overload resolution is ambiguous). Thus F(M) is unambiguously taken to mean
- F(D1) applied to M(J1). Note that the user has just made the situation more ambiguous by having
- all three methods in the method group, but we ignore this additional ambiguity and pick a
- winner (rather arbitrarily).
-
- We currently implement (1). The spec needs to be tightened up.
- ***************************************************************************************************/
- private bool BindGrpConversion(ExprMemberGroup grp, CType typeDst, bool fReportErrors)
- {
- ExprCall dummy;
- return BindGrpConversion(grp, typeDst, false, out dummy, fReportErrors);
- }
-
- private bool BindGrpConversion(ExprMemberGroup grp, CType typeDst, bool needDest, out ExprCall pexprDst, bool fReportErrors)
- {
- pexprDst = null;
-
- if (!typeDst.isDelegateType())
- {
- if (fReportErrors)
- {
- throw ErrorContext.Error(ErrorCode.ERR_MethGrpToNonDel, grp.Name, typeDst);
- }
-
- return false;
- }
- AggregateType type = typeDst as AggregateType;
- MethodSymbol methCtor = SymbolLoader.PredefinedMembers.FindDelegateConstructor(type.getAggregate(), fReportErrors);
- if (methCtor == null)
- return false;
- // Now, find the invoke function on the delegate.
- MethodSymbol methInvoke = SymbolLoader.LookupInvokeMeth(type.getAggregate());
- Debug.Assert(methInvoke != null && methInvoke.isInvoke());
- TypeArray @params = GetTypes().SubstTypeArray(methInvoke.Params, type);
- CType typeRet = GetTypes().SubstType(methInvoke.RetType, type);
- // Next, verify that the function has a suitable type for the invoke method.
- MethPropWithInst mpwiWrap;
- MethPropWithInst mpwiAmbig;
-
- if (!BindGrpConversionCore(out mpwiWrap, BindingFlag.BIND_NOPARAMS, grp, ref @params, type, fReportErrors, out mpwiAmbig))
- {
- return false;
- }
-
- MethWithInst mwiWrap = new MethWithInst(mpwiWrap);
- MethWithInst mwiAmbig = new MethWithInst(mpwiAmbig);
-
- // From here on we should only return true.
- if (!fReportErrors && !needDest)
- return true;
-
- // Note: We report errors below even if fReportErrors is false. Note however that we only
- // get here if pexprDst is non-null.
- if (mwiAmbig && !fReportErrors)
- {
- // Report the ambiguity, since BindGrpConversionCore didn't.
- throw ErrorContext.Error(ErrorCode.ERR_AmbigCall, mwiWrap, mwiAmbig);
- }
- CType typeRetReal = GetTypes().SubstType(mwiWrap.Meth().RetType, mwiWrap.Ats, mwiWrap.TypeArgs);
- if (typeRet != typeRetReal && !CConversions.FImpRefConv(GetSymbolLoader(), typeRetReal, typeRet))
- {
- throw ErrorContext.Error(ErrorCode.ERR_BadRetType, mwiWrap, typeRetReal);
- }
-
- TypeArray paramsReal = GetTypes().SubstTypeArray(mwiWrap.Meth().Params, mwiWrap.Ats, mwiWrap.TypeArgs);
- if (paramsReal != @params)
- {
- for (int i = 0; i < paramsReal.Count; i++)
- {
- CType param = @params[i];
- CType paramReal = paramsReal[i];
-
- if (param != paramReal && !CConversions.FImpRefConv(GetSymbolLoader(), param, paramReal))
- {
- throw ErrorContext.Error(ErrorCode.ERR_MethDelegateMismatch, mwiWrap, typeDst);
- }
- }
- }
-
- Expr obj = grp.OptionalObject;
- bool constrained;
- PostBindMethod(ref mwiWrap, obj);
- obj = AdjustMemberObject(mwiWrap, obj, out constrained);
-
- Debug.Assert(mwiWrap.Meth().getKind() == SYMKIND.SK_MethodSymbol);
- if (mwiWrap.TypeArgs.Count > 0)
- {
- // Check method type variable constraints.
- TypeBind.CheckMethConstraints(GetSemanticChecker(), GetErrorContext(), mwiWrap);
- }
-
- if (!needDest)
- return true;
-
- ExprFuncPtr funcPtr = ExprFactory.CreateFunctionPointer(0, getVoidType(), null, mwiWrap);
- if (!mwiWrap.Meth().isStatic)
- {
- if (mwiWrap.Meth().getClass().isPredefAgg(PredefinedType.PT_G_OPTIONAL))
- {
- throw ErrorContext.Error(ErrorCode.ERR_DelegateOnNullable, mwiWrap);
- }
- funcPtr.OptionalObject = obj;
- if (obj != null && obj.Type.fundType() != FUNDTYPE.FT_REF)
- {
- // Must box the object before creating a delegate to it.
- obj = mustConvert(obj, GetPredefindType(PredefinedType.PT_OBJECT));
- }
- }
- else
- {
- funcPtr.OptionalObject = null;
- obj = ExprFactory.CreateNull();
- }
-
- MethWithInst mwi = new MethWithInst(methCtor, type);
- grp.OptionalObject = null;
- ExprCall call = ExprFactory.CreateCall(EXPRFLAG.EXF_NEWOBJCALL | EXPRFLAG.EXF_CANTBENULL, type, ExprFactory.CreateList(obj, funcPtr), grp/*pMemGroup*/, mwi);
-
- pexprDst = call;
- return true;
- }
-
- private bool BindGrpConversionCore(out MethPropWithInst pmpwi, BindingFlag bindFlags, ExprMemberGroup grp, ref TypeArray args, AggregateType atsDelegate, bool fReportErrors, out MethPropWithInst pmpwiAmbig)
- {
- ArgInfos argParam = new ArgInfos();
- argParam.carg = args.Count;
- argParam.types = args;
- argParam.fHasExprs = false;
- GroupToArgsBinder binder = new GroupToArgsBinder(this, bindFlags, grp, argParam, null, false, atsDelegate);
- bool retval = binder.Bind(fReportErrors);
- GroupToArgsBinderResult result = binder.GetResultsOfBind();
- pmpwi = result.GetBestResult();
- pmpwiAmbig = result.GetAmbiguousResult();
- return retval;
- }
-
private bool BindImplicitConversion(Expr pSourceExpr, CType pSourceType, ExprClass pDestinationTypeExpr, CType pDestinationTypeForLambdaErrorReporting, CONVERTTYPE flags)
{
ImplicitConversion binder = new ImplicitConversion(this, pSourceExpr, pSourceType, pDestinationTypeExpr, false, flags);
diff --git a/src/Microsoft.CSharp/src/Microsoft/CSharp/RuntimeBinder/Semantics/Declarations/AggregateDeclaration.cs b/src/Microsoft.CSharp/src/Microsoft/CSharp/RuntimeBinder/Semantics/Declarations/AggregateDeclaration.cs
index 2d54082f1c..8dbc7213c6 100644
--- a/src/Microsoft.CSharp/src/Microsoft/CSharp/RuntimeBinder/Semantics/Declarations/AggregateDeclaration.cs
+++ b/src/Microsoft.CSharp/src/Microsoft/CSharp/RuntimeBinder/Semantics/Declarations/AggregateDeclaration.cs
@@ -10,7 +10,7 @@ namespace Microsoft.CSharp.RuntimeBinder.Semantics
//
// AggregateDeclaration
//
- // AggregateDeclaration - represents a declaration of a aggregate type. With partial classes,
+ // AggregateDeclaration - represents a declaration of an aggregate type. With partial classes,
// an aggregate type might be declared in multiple places. This symbol represents
// on of the declarations.
//
diff --git a/src/Microsoft.CSharp/src/Microsoft/CSharp/RuntimeBinder/Semantics/ExprFactory.cs b/src/Microsoft.CSharp/src/Microsoft/CSharp/RuntimeBinder/Semantics/ExprFactory.cs
index 7df63e860e..99814e51ea 100644
--- a/src/Microsoft.CSharp/src/Microsoft/CSharp/RuntimeBinder/Semantics/ExprFactory.cs
+++ b/src/Microsoft.CSharp/src/Microsoft/CSharp/RuntimeBinder/Semantics/ExprFactory.cs
@@ -27,9 +27,6 @@ namespace Microsoft.CSharp.RuntimeBinder.Semantics
public ExprField CreateField(CType type, Expr optionalObject, FieldWithType field, bool isLValue) =>
new ExprField(type, optionalObject, field, isLValue);
- public ExprFuncPtr CreateFunctionPointer(EXPRFLAG flags, CType type, Expr obj, MethWithInst method) =>
- new ExprFuncPtr(type, flags, obj, method);
-
public ExprArrayInit CreateArrayInit(CType type, Expr arguments, Expr argumentDimensions, int[] dimSizes, int dimSize) =>
new ExprArrayInit(type, arguments, argumentDimensions, dimSizes, dimSize);
diff --git a/src/Microsoft.CSharp/src/Microsoft/CSharp/RuntimeBinder/Semantics/ExpressionKind.cs b/src/Microsoft.CSharp/src/Microsoft/CSharp/RuntimeBinder/Semantics/ExpressionKind.cs
index d6ea6f4efd..ac62995cf8 100644
--- a/src/Microsoft.CSharp/src/Microsoft/CSharp/RuntimeBinder/Semantics/ExpressionKind.cs
+++ b/src/Microsoft.CSharp/src/Microsoft/CSharp/RuntimeBinder/Semantics/ExpressionKind.cs
@@ -64,7 +64,7 @@ namespace Microsoft.CSharp.RuntimeBinder.Semantics
//EK_ALIAS,
// End type exprs.
//EK_ERROR,
- FunctionPointer,
+ //FunctionPointer,
Property,
Multi,
MultiGet,
diff --git a/src/Microsoft.CSharp/src/Microsoft/CSharp/RuntimeBinder/Semantics/ImplicitConversion.cs b/src/Microsoft.CSharp/src/Microsoft/CSharp/RuntimeBinder/Semantics/ImplicitConversion.cs
index 363d8faa3b..5572f94280 100644
--- a/src/Microsoft.CSharp/src/Microsoft/CSharp/RuntimeBinder/Semantics/ImplicitConversion.cs
+++ b/src/Microsoft.CSharp/src/Microsoft/CSharp/RuntimeBinder/Semantics/ImplicitConversion.cs
@@ -93,7 +93,7 @@ namespace Microsoft.CSharp.RuntimeBinder.Semantics
switch (_typeDest.GetTypeKind())
{
case TypeKind.TK_ErrorType:
- Debug.Assert(((ErrorType)_typeDest).HasParent());
+ Debug.Assert(((ErrorType)_typeDest).HasParent);
if (_typeSrc != _typeDest)
{
return false;
@@ -170,15 +170,6 @@ namespace Microsoft.CSharp.RuntimeBinder.Semantics
default:
Debug.Fail($"Bad type symbol kind: {_typeSrc.GetTypeKind()}");
break;
- case TypeKind.TK_MethodGroupType:
- if (_exprSrc is ExprMemberGroup memGrp)
- {
- ExprCall outExpr;
- bool retVal = _binder.BindGrpConversion(memGrp, _typeDest, _needsExprDest, out outExpr, false);
- _exprDest = outExpr;
- return retVal;
- }
- return false;
case TypeKind.TK_VoidType:
case TypeKind.TK_ErrorType:
case TypeKind.TK_ParameterModifierType:
diff --git a/src/Microsoft.CSharp/src/Microsoft/CSharp/RuntimeBinder/Semantics/MethodTypeInferrer.cs b/src/Microsoft.CSharp/src/Microsoft/CSharp/RuntimeBinder/Semantics/MethodTypeInferrer.cs
index 8018189c93..016c112fea 100644
--- a/src/Microsoft.CSharp/src/Microsoft/CSharp/RuntimeBinder/Semantics/MethodTypeInferrer.cs
+++ b/src/Microsoft.CSharp/src/Microsoft/CSharp/RuntimeBinder/Semantics/MethodTypeInferrer.cs
@@ -195,8 +195,6 @@ namespace Microsoft.CSharp.RuntimeBinder.Semantics
}
_pFixedResults[iParam] = GetTypeManager().GetErrorType(
- null/*pParentType*/,
- null,
((TypeParameterType)_pMethodTypeParameters[iParam]).GetName(),
BSYMMGR.EmptyTypeArray());
}
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 8b37ff10e0..510b88a34f 100644
--- a/src/Microsoft.CSharp/src/Microsoft/CSharp/RuntimeBinder/Semantics/PredefinedMembers.cs
+++ b/src/Microsoft.CSharp/src/Microsoft/CSharp/RuntimeBinder/Semantics/PredefinedMembers.cs
@@ -101,7 +101,6 @@ namespace Microsoft.CSharp.RuntimeBinder.Semantics
PM_EXPRESSION_INVOKE,
- PM_METHODINFO_CREATEDELEGATE_TYPE_OBJECT,
PM_G_OPTIONAL_CTOR,
PM_G_OPTIONAL_GETVALUE,
@@ -214,46 +213,6 @@ namespace Microsoft.CSharp.RuntimeBinder.Semantics
return GetOptPredefAgg(GetMethPredefType(method));
}
- // delegate specific helpers
- private MethodSymbol FindDelegateConstructor(AggregateSymbol delegateType, int[] signature)
- {
- Debug.Assert(delegateType != null && delegateType.IsDelegate());
- Debug.Assert(signature != null);
-
- return LoadMethod(
- delegateType,
- signature,
- 0, // meth ty vars
- GetPredefName(PredefinedName.PN_CTOR),
- ACCESS.ACC_PUBLIC,
- false, // MethodCallingConventionEnum.Static
- false); // MethodCallingConventionEnum.Virtual
- }
-
- private MethodSymbol FindDelegateConstructor(AggregateSymbol delegateType)
- {
- Debug.Assert(delegateType != null && delegateType.IsDelegate());
-
- MethodSymbol ctor = FindDelegateConstructor(delegateType, s_DelegateCtorSignature1);
- if (ctor == null)
- {
- ctor = FindDelegateConstructor(delegateType, s_DelegateCtorSignature2);
- }
-
- return ctor;
- }
-
- public MethodSymbol FindDelegateConstructor(AggregateSymbol delegateType, bool fReportErrors)
- {
- MethodSymbol ctor = FindDelegateConstructor(delegateType);
- if (ctor == null && fReportErrors)
- {
- throw GetErrorContext().Error(ErrorCode.ERR_BadDelegateConstructor, delegateType);
- }
-
- return ctor;
- }
-
private PropertySymbol LoadProperty(PREDEFPROP property)
{
return LoadProperty(
@@ -515,9 +474,6 @@ namespace Microsoft.CSharp.RuntimeBinder.Semantics
IsMethVirtual(method));
}
- private static readonly int[] s_DelegateCtorSignature1 = { (int)PredefinedType.PT_VOID, 2, (int)PredefinedType.PT_OBJECT, (int)PredefinedType.PT_INTPTR };
- private static readonly int[] s_DelegateCtorSignature2 = { (int)PredefinedType.PT_VOID, 2, (int)PredefinedType.PT_OBJECT, (int)PredefinedType.PT_UINTPTR };
-
private static PredefinedName GetPropPredefName(PREDEFPROP property)
{
return GetPropInfo(property).name;
@@ -672,7 +628,6 @@ namespace Microsoft.CSharp.RuntimeBinder.Semantics
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_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_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 }),
diff --git a/src/Microsoft.CSharp/src/Microsoft/CSharp/RuntimeBinder/Semantics/Tree/MethodReference.cs b/src/Microsoft.CSharp/src/Microsoft/CSharp/RuntimeBinder/Semantics/Tree/MethodReference.cs
deleted file mode 100644
index a1ee23c3f7..0000000000
--- a/src/Microsoft.CSharp/src/Microsoft/CSharp/RuntimeBinder/Semantics/Tree/MethodReference.cs
+++ /dev/null
@@ -1,24 +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.Diagnostics;
-
-namespace Microsoft.CSharp.RuntimeBinder.Semantics
-{
- internal sealed class ExprFuncPtr : ExprWithType, IExprWithObject
- {
- public ExprFuncPtr(CType type, EXPRFLAG flags, Expr optionalObject, MethWithInst method)
- : base(ExpressionKind.FunctionPointer, type)
- {
- Debug.Assert(flags == 0);
- Flags = flags;
- OptionalObject = optionalObject;
- MethWithInst = new MethWithInst(method);
- }
-
- public MethWithInst MethWithInst { get; }
-
- public Expr OptionalObject { get; set; }
- }
-}
diff --git a/src/Microsoft.CSharp/src/Microsoft/CSharp/RuntimeBinder/Semantics/Tree/Visitors/ExprVisitorBase.cs b/src/Microsoft.CSharp/src/Microsoft/CSharp/RuntimeBinder/Semantics/Tree/Visitors/ExprVisitorBase.cs
index 2b74c03dbf..19642eccc4 100644
--- a/src/Microsoft.CSharp/src/Microsoft/CSharp/RuntimeBinder/Semantics/Tree/Visitors/ExprVisitorBase.cs
+++ b/src/Microsoft.CSharp/src/Microsoft/CSharp/RuntimeBinder/Semantics/Tree/Visitors/ExprVisitorBase.cs
@@ -122,8 +122,6 @@ namespace Microsoft.CSharp.RuntimeBinder.Semantics
return VisitCONSTANT(pExpr as ExprConstant);
case ExpressionKind.Class:
return VisitCLASS(pExpr as ExprClass);
- case ExpressionKind.FunctionPointer:
- return VisitFUNCPTR(pExpr as ExprFuncPtr);
case ExpressionKind.Property:
return VisitPROP(pExpr as ExprProperty);
case ExpressionKind.Multi:
@@ -457,7 +455,6 @@ namespace Microsoft.CSharp.RuntimeBinder.Semantics
case ExpressionKind.Local:
case ExpressionKind.Class:
- case ExpressionKind.FunctionPointer:
case ExpressionKind.MultiGet:
case ExpressionKind.Wrap:
case ExpressionKind.NoOp:
@@ -563,10 +560,6 @@ namespace Microsoft.CSharp.RuntimeBinder.Semantics
{
return VisitEXPR(pExpr);
}
- protected virtual Expr VisitFUNCPTR(ExprFuncPtr pExpr)
- {
- return VisitEXPR(pExpr);
- }
protected virtual Expr VisitMULTIGET(ExprMultiGet pExpr)
{
return VisitEXPR(pExpr);
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 c72ac87910..fff8ed3c4d 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
@@ -929,64 +929,12 @@ namespace Microsoft.CSharp.RuntimeBinder.Semantics
{
Debug.Assert(expr != null);
Debug.Assert(expr.MethWithInst.Meth().IsConstructor());
-
- // Realize a call to new DELEGATE(obj, FUNCPTR) as though it actually was
- // (DELEGATE)CreateDelegate(typeof(DELEGATE), obj, GetMethInfoFromHandle(FUNCPTR))
-
- if (IsDelegateConstructorCall(expr))
- {
- return GenerateDelegateConstructor(expr);
- }
Expr constructorInfo = GetExprFactory().CreateMethodInfo(expr.MethWithInst);
Expr args = GenerateArgsList(expr.OptionalArguments);
Expr Params = GenerateParamsArray(args, PredefinedType.PT_EXPRESSION);
return GenerateCall(PREDEFMETH.PM_EXPRESSION_NEW, constructorInfo, Params);
}
- private Expr GenerateDelegateConstructor(ExprCall expr)
- {
- // In:
- //
- // new DELEGATE(obj, &FUNC)
- //
- // Out:
- //
- // Cast(
- // Call(
- // null,
- // (MethodInfo)GetMethodFromHandle(&CreateDelegate),
- // new Expression[3]{
- // Constant(typeof(DELEGATE)),
- // transformed-object,
- // Constant((MethodInfo)GetMethodFromHandle(&FUNC)}),
- // typeof(DELEGATE))
- //
-
- Debug.Assert(expr != null);
- Debug.Assert(expr.MethWithInst.Meth().IsConstructor());
- Debug.Assert(expr.Type.isDelegateType());
-
- ExprList origArgs = (ExprList)expr.OptionalArguments;
- Debug.Assert(origArgs != null);
- Expr target = origArgs.OptionalElement;
- Debug.Assert(origArgs.OptionalNextListNode.Kind == ExpressionKind.FunctionPointer);
- ExprFuncPtr funcptr = (ExprFuncPtr)origArgs.OptionalNextListNode;
- Debug.Assert(funcptr != null);
- MethodSymbol createDelegateMethod = GetPreDefMethod(PREDEFMETH.PM_METHODINFO_CREATEDELEGATE_TYPE_OBJECT);
- AggregateType delegateType = GetSymbolLoader().GetPredefindType(PredefinedType.PT_DELEGATE);
- MethWithInst mwi = new MethWithInst(createDelegateMethod, delegateType);
-
- Expr instance = GenerateConstant(GetExprFactory().CreateMethodInfo(funcptr.MethWithInst));
- Expr methinfo = GetExprFactory().CreateMethodInfo(mwi);
- Expr param1 = GenerateConstant(CreateTypeOf(expr.Type));
- Expr param2 = Visit(target);
- Expr paramsList = GetExprFactory().CreateList(param1, param2);
- Expr Params = GenerateParamsArray(paramsList, PredefinedType.PT_EXPRESSION);
- Expr call = GenerateCall(PREDEFMETH.PM_EXPRESSION_CALL, instance, methinfo, Params);
- Expr pTypeOf = CreateTypeOf(expr.Type);
- return GenerateCall(PREDEFMETH.PM_EXPRESSION_CONVERT, call, pTypeOf);
- }
-
private Expr GenerateArgsList(Expr oldArgs)
{
Expr newArgs = null;
@@ -1165,21 +1113,6 @@ namespace Microsoft.CSharp.RuntimeBinder.Semantics
return pExpr is ExprProperty prop && prop.MemberGroup.OptionalObject == pObject && pObject.Type is NullableType;
}
- private bool IsDelegateConstructorCall(Expr pExpr)
- {
- Debug.Assert(pExpr != null);
- if (!(pExpr is ExprCall pCall))
- {
- return false;
- }
-
- return pCall.MethWithInst.Meth() != null &&
- pCall.MethWithInst.Meth().IsConstructor() &&
- pCall.Type.isDelegateType() &&
- pCall.OptionalArguments != null &&
- pCall.OptionalArguments is ExprList list &&
- list.OptionalNextListNode.Kind == ExpressionKind.FunctionPointer;
- }
private static bool isEnumToDecimalConversion(CType argtype, CType desttype) =>
argtype.StripNubs().isEnumType() && desttype.StripNubs().isPredefType(PredefinedType.PT_DECIMAL);
}
diff --git a/src/Microsoft.CSharp/src/Microsoft/CSharp/RuntimeBinder/Semantics/TypeBind.cs b/src/Microsoft.CSharp/src/Microsoft/CSharp/RuntimeBinder/Semantics/TypeBind.cs
index 717ae870fd..7b75b91031 100644
--- a/src/Microsoft.CSharp/src/Microsoft/CSharp/RuntimeBinder/Semantics/TypeBind.cs
+++ b/src/Microsoft.CSharp/src/Microsoft/CSharp/RuntimeBinder/Semantics/TypeBind.cs
@@ -141,6 +141,9 @@ namespace Microsoft.CSharp.RuntimeBinder.Semantics
private static bool CheckSingleConstraint(CSemanticChecker checker, ErrorHandling errHandling, Symbol symErr, TypeParameterType var, CType arg, TypeArray typeArgsCls, TypeArray typeArgsMeth, CheckConstraintsFlags flags)
{
+ Debug.Assert(!(arg is PointerType));
+ Debug.Assert(!arg.isStaticClass());
+
bool fReportErrors = 0 == (flags & CheckConstraintsFlags.NoErrors);
if (arg is ErrorType)
@@ -149,26 +152,6 @@ namespace Microsoft.CSharp.RuntimeBinder.Semantics
return false;
}
- if (arg is PointerType)
- {
- if (fReportErrors)
- {
- throw errHandling.Error(ErrorCode.ERR_BadTypeArgument, arg);
- }
-
- return false;
- }
-
- if (arg.isStaticClass())
- {
- if (fReportErrors)
- {
- checker.ReportStaticClassError(null, arg, ErrorCode.ERR_GenericArgIsStaticClass);
- }
-
- return false;
- }
-
bool fError = false;
if (var.HasRefConstraint() && !arg.IsRefType())
{
diff --git a/src/Microsoft.CSharp/src/Microsoft/CSharp/RuntimeBinder/Semantics/Types/ErrorType.cs b/src/Microsoft.CSharp/src/Microsoft/CSharp/RuntimeBinder/Semantics/Types/ErrorType.cs
index 0a68e5ee3d..7376f4ceaf 100644
--- a/src/Microsoft.CSharp/src/Microsoft/CSharp/RuntimeBinder/Semantics/Types/ErrorType.cs
+++ b/src/Microsoft.CSharp/src/Microsoft/CSharp/RuntimeBinder/Semantics/Types/ErrorType.cs
@@ -18,17 +18,11 @@ namespace Microsoft.CSharp.RuntimeBinder.Semantics
public Name nameText;
public TypeArray typeArgs;
- public bool HasParent() { return _pParentType != null || _pParentNS != null; }
-
- public bool HasTypeParent() { return _pParentType != null; }
- public CType GetTypeParent() { return _pParentType; }
- public void SetTypeParent(CType pType) { _pParentType = pType; }
-
- public bool HasNSParent() { return _pParentNS != null; }
- public AssemblyQualifiedNamespaceSymbol GetNSParent() { return _pParentNS; }
- public void SetNSParent(AssemblyQualifiedNamespaceSymbol pNS) { _pParentNS = pNS; }
-
- private CType _pParentType;
- private AssemblyQualifiedNamespaceSymbol _pParentNS;
+ // ErrorTypes are always either the per-TypeManager singleton ErrorType
+ // that has a null nameText and no namespace parent, or else have a
+ // non-null nameText and have the root namespace as the namespace parent,
+ // so checking that nameText isn't null is equivalent to checking if the
+ // type has a parent.
+ public bool HasParent => nameText != null;
}
}
diff --git a/src/Microsoft.CSharp/src/Microsoft/CSharp/RuntimeBinder/Semantics/Types/Type.cs b/src/Microsoft.CSharp/src/Microsoft/CSharp/RuntimeBinder/Semantics/Types/Type.cs
index d182dd9d8d..8a83c9a0d9 100644
--- a/src/Microsoft.CSharp/src/Microsoft/CSharp/RuntimeBinder/Semantics/Types/Type.cs
+++ b/src/Microsoft.CSharp/src/Microsoft/CSharp/RuntimeBinder/Semantics/Types/Type.cs
@@ -179,7 +179,8 @@ namespace Microsoft.CSharp.RuntimeBinder.Semantics
public void InitFromParent()
{
Debug.Assert(!(this is AggregateType));
- _fHasErrors = (this is ErrorType err ? err.GetTypeParent() : GetBaseOrParameterOrElementType()).HasErrors();
+ Debug.Assert(!(this is ErrorType));
+ _fHasErrors = GetBaseOrParameterOrElementType().HasErrors();
}
public bool HasErrors()
@@ -514,7 +515,7 @@ namespace Microsoft.CSharp.RuntimeBinder.Semantics
// be equivalent or convertible (like ANONMETHSYMs)
public bool IsNeverSameType()
{
- return this is MethodGroupType || this is ErrorType err && !err.HasParent();
+ return this is MethodGroupType || this is ErrorType err && !err.HasParent;
}
}
}
diff --git a/src/Microsoft.CSharp/src/Microsoft/CSharp/RuntimeBinder/Semantics/Types/TypeFactory.cs b/src/Microsoft.CSharp/src/Microsoft/CSharp/RuntimeBinder/Semantics/Types/TypeFactory.cs
index 33b3895ae0..f737321150 100644
--- a/src/Microsoft.CSharp/src/Microsoft/CSharp/RuntimeBinder/Semantics/Types/TypeFactory.cs
+++ b/src/Microsoft.CSharp/src/Microsoft/CSharp/RuntimeBinder/Semantics/Types/TypeFactory.cs
@@ -71,8 +71,6 @@ namespace Microsoft.CSharp.RuntimeBinder.Semantics
public ErrorType CreateError(
Name name,
- CType parent,
- AssemblyQualifiedNamespaceSymbol pParentNS,
Name nameText,
TypeArray typeArgs)
{
@@ -80,8 +78,6 @@ namespace Microsoft.CSharp.RuntimeBinder.Semantics
e.SetName(name);
e.nameText = nameText;
e.typeArgs = typeArgs;
- e.SetTypeParent(parent);
- e.SetNSParent(pParentNS);
e.SetTypeKind(TypeKind.TK_ErrorType);
return e;
diff --git a/src/Microsoft.CSharp/src/Microsoft/CSharp/RuntimeBinder/Semantics/Types/TypeManager.cs b/src/Microsoft.CSharp/src/Microsoft/CSharp/RuntimeBinder/Semantics/Types/TypeManager.cs
index 95b595e50b..f3113125dc 100644
--- a/src/Microsoft.CSharp/src/Microsoft/CSharp/RuntimeBinder/Semantics/Types/TypeManager.cs
+++ b/src/Microsoft.CSharp/src/Microsoft/CSharp/RuntimeBinder/Semantics/Types/TypeManager.cs
@@ -37,7 +37,7 @@ namespace Microsoft.CSharp.RuntimeBinder.Semantics
_typeTable = new TypeTable();
// special types with their own symbol kind.
- _errorType = _typeFactory.CreateError(null, null, null, null, null);
+ _errorType = _typeFactory.CreateError(null, null, null);
_voidType = _typeFactory.CreateVoid();
_nullType = _typeFactory.CreateNull();
_typeMethGrp = _typeFactory.CreateMethodGroup();
@@ -314,18 +314,10 @@ namespace Microsoft.CSharp.RuntimeBinder.Semantics
}
public ErrorType GetErrorType(
- CType pParentType,
- AssemblyQualifiedNamespaceSymbol pParentNS,
Name nameText,
TypeArray typeArgs)
{
Debug.Assert(nameText != null);
- Debug.Assert(pParentType == null || pParentNS == null);
- if (pParentType == null && pParentNS == null)
- {
- // Use the root namespace as the parent.
- pParentNS = _BSymmgr.GetRootNsAid();
- }
if (typeArgs == null)
{
typeArgs = BSYMMGR.EmptyTypeArray();
@@ -334,30 +326,14 @@ namespace Microsoft.CSharp.RuntimeBinder.Semantics
Name name = _BSymmgr.GetNameFromPtrs(nameText, typeArgs);
Debug.Assert(name != null);
- ErrorType pError = null;
- if (pParentType != null)
- {
- pError = _typeTable.LookupError(name, pParentType);
- }
- else
- {
- Debug.Assert(pParentNS != null);
- pError = _typeTable.LookupError(name, pParentNS);
- }
+ ErrorType pError = _typeTable.LookupError(name);
if (pError == null)
{
// No existing error symbol. Create a new one.
- pError = _typeFactory.CreateError(name, pParentType, pParentNS, nameText, typeArgs);
+ pError = _typeFactory.CreateError(name, nameText, typeArgs);
pError.SetErrors(true);
- if (pParentType != null)
- {
- _typeTable.InsertError(name, pParentType, pError);
- }
- else
- {
- _typeTable.InsertError(name, pParentNS, pError);
- }
+ _typeTable.InsertError(name, pError);
}
else
{
@@ -503,22 +479,16 @@ namespace Microsoft.CSharp.RuntimeBinder.Semantics
case TypeKind.TK_ErrorType:
ErrorType err = (ErrorType)type;
- if (err.HasParent())
+ if (err.HasParent)
{
Debug.Assert(err.nameText != null && err.typeArgs != null);
-
- CType pParentType = null;
- if (err.HasTypeParent())
- {
- pParentType = SubstTypeCore(err.GetTypeParent(), pctx);
- }
-
TypeArray typeArgs = SubstTypeArray(err.typeArgs, pctx);
- if (typeArgs != err.typeArgs || (err.HasTypeParent() && pParentType != err.GetTypeParent()))
+ if (typeArgs != err.typeArgs)
{
- return GetErrorType(pParentType, err.GetNSParent(), err.nameText, typeArgs);
+ return GetErrorType(err.nameText, typeArgs);
}
}
+
return type;
case TypeKind.TK_TypeParameterType:
@@ -658,45 +628,27 @@ namespace Microsoft.CSharp.RuntimeBinder.Semantics
case TypeKind.TK_ErrorType:
ErrorType errSrc = (ErrorType)typeSrc;
- if (!(typeDst is ErrorType errDst) || !errSrc.HasParent() || !errDst.HasParent())
+ if (!(typeDst is ErrorType errDst) || !errSrc.HasParent || !errDst.HasParent)
return false;
- {
- Debug.Assert(errSrc.nameText != null && errSrc.typeArgs != null);
- Debug.Assert(errDst.nameText != null && errDst.typeArgs != null);
- if (errSrc.nameText != errDst.nameText || errSrc.typeArgs.Count != errDst.typeArgs.Count)
- return false;
+ {
+ Debug.Assert(errSrc.nameText != null && errSrc.typeArgs != null);
+ Debug.Assert(errDst.nameText != null && errDst.typeArgs != null);
- if (errSrc.HasTypeParent() != errDst.HasTypeParent())
- {
- return false;
- }
- if (errSrc.HasTypeParent())
- {
- if (errSrc.GetTypeParent() != errDst.GetTypeParent())
- {
- return false;
- }
- if (!SubstEqualTypesCore(errDst.GetTypeParent(), errSrc.GetTypeParent(), pctx))
- {
- return false;
- }
- }
- else
- {
- if (errSrc.GetNSParent() != errDst.GetNSParent())
- {
- return false;
- }
- }
+ if (errSrc.nameText != errDst.nameText || errSrc.typeArgs.Count != errDst.typeArgs.Count
+ || errSrc.HasParent != errDst.HasParent)
+ {
+ return false;
+ }
- // All the args must unify.
- for (int i = 0; i < errSrc.typeArgs.Count; i++)
- {
- if (!SubstEqualTypesCore(errDst.typeArgs[i], errSrc.typeArgs[i], pctx))
- return false;
- }
+ // All the args must unify.
+ for (int i = 0; i < errSrc.typeArgs.Count; i++)
+ {
+ if (!SubstEqualTypesCore(errDst.typeArgs[i], errSrc.typeArgs[i], pctx))
+ return false;
}
+ }
+
return true;
case TypeKind.TK_TypeParameterType:
@@ -782,7 +734,7 @@ namespace Microsoft.CSharp.RuntimeBinder.Semantics
case TypeKind.TK_ErrorType:
ErrorType err = (ErrorType)type;
- if (err.HasParent())
+ if (err.HasParent)
{
Debug.Assert(err.nameText != null && err.typeArgs != null);
@@ -791,12 +743,8 @@ namespace Microsoft.CSharp.RuntimeBinder.Semantics
if (TypeContainsType(err.typeArgs[i], typeFind))
return true;
}
- if (err.HasTypeParent())
- {
- type = err.GetTypeParent();
- goto LRecurse;
- }
}
+
return false;
case TypeKind.TK_TypeParameterType:
@@ -841,7 +789,7 @@ namespace Microsoft.CSharp.RuntimeBinder.Semantics
case TypeKind.TK_ErrorType:
ErrorType err = (ErrorType)type;
- if (err.HasParent())
+ if (err.HasParent)
{
Debug.Assert(err.nameText != null && err.typeArgs != null);
@@ -852,12 +800,8 @@ namespace Microsoft.CSharp.RuntimeBinder.Semantics
return true;
}
}
- if (err.HasTypeParent())
- {
- type = err.GetTypeParent();
- goto LRecurse;
- }
}
+
return false;
case TypeKind.TK_TypeParameterType:
diff --git a/src/Microsoft.CSharp/src/Microsoft/CSharp/RuntimeBinder/Semantics/Types/TypeTable.cs b/src/Microsoft.CSharp/src/Microsoft/CSharp/RuntimeBinder/Semantics/Types/TypeTable.cs
index 63b89022ed..2329a3382d 100644
--- a/src/Microsoft.CSharp/src/Microsoft/CSharp/RuntimeBinder/Semantics/Types/TypeTable.cs
+++ b/src/Microsoft.CSharp/src/Microsoft/CSharp/RuntimeBinder/Semantics/Types/TypeTable.cs
@@ -48,12 +48,11 @@ namespace Microsoft.CSharp.RuntimeBinder.Semantics
{
// Two way hashes
private readonly Dictionary<KeyPair<AggregateSymbol, Name>, AggregateType> _pAggregateTable;
- private readonly Dictionary<KeyPair<CType, Name>, ErrorType> _pErrorWithTypeParentTable;
- private readonly Dictionary<KeyPair<AssemblyQualifiedNamespaceSymbol, Name>, ErrorType> _pErrorWithNamespaceParentTable;
private readonly Dictionary<KeyPair<CType, Name>, ArrayType> _pArrayTable;
private readonly Dictionary<KeyPair<CType, Name>, ParameterModifierType> _pParameterModifierTable;
// One way hashes
+ private readonly Dictionary<Name, ErrorType> _pErrorWithNamespaceParentTable;
private readonly Dictionary<CType, PointerType> _pPointerTable;
private readonly Dictionary<CType, NullableType> _pNullableTable;
private readonly Dictionary<TypeParameterSymbol, TypeParameterType> _pTypeParameterTable;
@@ -61,8 +60,7 @@ namespace Microsoft.CSharp.RuntimeBinder.Semantics
public TypeTable()
{
_pAggregateTable = new Dictionary<KeyPair<AggregateSymbol, Name>, AggregateType>();
- _pErrorWithNamespaceParentTable = new Dictionary<KeyPair<AssemblyQualifiedNamespaceSymbol, Name>, ErrorType>();
- _pErrorWithTypeParentTable = new Dictionary<KeyPair<CType, Name>, ErrorType>();
+ _pErrorWithNamespaceParentTable = new Dictionary<Name, ErrorType>();
_pArrayTable = new Dictionary<KeyPair<CType, Name>, ArrayType>();
_pParameterModifierTable = new Dictionary<KeyPair<CType, Name>, ParameterModifierType>();
_pPointerTable = new Dictionary<CType, PointerType>();
@@ -90,38 +88,13 @@ namespace Microsoft.CSharp.RuntimeBinder.Semantics
_pAggregateTable.Add(new KeyPair<AggregateSymbol, Name>(pAggregateSymbol, pName), pAggregate);
}
- public ErrorType LookupError(Name pName, CType pParentType)
- {
- var key = new KeyPair<CType, Name>(pParentType, pName);
- ErrorType result;
- if (_pErrorWithTypeParentTable.TryGetValue(key, out result))
- {
- return result;
- }
- return null;
- }
-
- public ErrorType LookupError(Name pName, AssemblyQualifiedNamespaceSymbol pParentNS)
- {
- var key = new KeyPair<AssemblyQualifiedNamespaceSymbol, Name>(pParentNS, pName);
- ErrorType result;
- if (_pErrorWithNamespaceParentTable.TryGetValue(key, out result))
- {
- return result;
- }
- return null;
- }
-
- public void InsertError(Name pName, CType pParentType, ErrorType pError)
- {
- Debug.Assert(LookupError(pName, pParentType) == null);
- _pErrorWithTypeParentTable.Add(new KeyPair<CType, Name>(pParentType, pName), pError);
- }
+ public ErrorType LookupError(Name pName) =>
+ _pErrorWithNamespaceParentTable.TryGetValue(pName, out ErrorType result) ? result : null;
- public void InsertError(Name pName, AssemblyQualifiedNamespaceSymbol pParentNS, ErrorType pError)
+ public void InsertError(Name pName, ErrorType pError)
{
- Debug.Assert(LookupError(pName, pParentNS) == null);
- _pErrorWithNamespaceParentTable.Add(new KeyPair<AssemblyQualifiedNamespaceSymbol, Name>(pParentNS, pName), pError);
+ Debug.Assert(LookupError(pName) == null);
+ _pErrorWithNamespaceParentTable.Add(pName, pError);
}
public ArrayType LookupArray(Name pName, CType pElementType)
diff --git a/src/Microsoft.CSharp/src/MultilingualResources/Microsoft.CSharp.de.xlf b/src/Microsoft.CSharp/src/MultilingualResources/Microsoft.CSharp.de.xlf
index 1c540dca8d..4c1eec98c6 100644
--- a/src/Microsoft.CSharp/src/MultilingualResources/Microsoft.CSharp.de.xlf
+++ b/src/Microsoft.CSharp/src/MultilingualResources/Microsoft.CSharp.de.xlf
@@ -130,10 +130,6 @@
<source>The type '{0}' has no constructors defined</source>
<target state="needs-review-translation" state-qualifier="tm-suggestion">Für den {0}-Typ sind keine Konstruktoren definiert.</target>
</trans-unit>
- <trans-unit id="BadDelegateConstructor" translate="yes" xml:space="preserve">
- <source>The delegate '{0}' does not have a valid constructor</source>
- <target state="needs-review-translation" state-qualifier="tm-suggestion">Der Delegat "{0}" enthält keinen gültigen Konstruktor.</target>
- </trans-unit>
<trans-unit id="PropertyLacksGet" translate="yes" xml:space="preserve">
<source>The property or indexer '{0}' cannot be used in this context because it lacks the get accessor</source>
<target state="needs-review-translation" state-qualifier="tm-suggestion">Die Eigenschaft oder der Indexer "{0}" kann in diesem Kontext nicht verwendet werden, weil der get-Accessor fehlt.</target>
@@ -202,10 +198,6 @@
<source>Using the generic {1} '{0}' requires '{2}' type arguments</source>
<target state="needs-review-translation" state-qualifier="tm-suggestion">Die Verwendung von {1} "{0}" (generisch) erfordert {2}-Typargumente.</target>
</trans-unit>
- <trans-unit id="BadTypeArgument" translate="yes" xml:space="preserve">
- <source>The type '{0}' may not be used as a type argument</source>
- <target state="needs-review-translation" state-qualifier="tm-suggestion">Der Typ "{0}" darf nicht als Typargument verwendet werden.</target>
- </trans-unit>
<trans-unit id="TypeArgsNotAllowed" translate="yes" xml:space="preserve">
<source>The {1} '{0}' cannot be used with type arguments</source>
<target state="needs-review-translation" state-qualifier="tm-suggestion">{1} "{0}" kann nicht mit Typargumenten verwendet werden.</target>
@@ -238,18 +230,10 @@
<source>Cannot convert null to type parameter '{0}' because it could be a non-nullable value type. Consider using 'default({0})' instead.</source>
<target state="needs-review-translation" state-qualifier="tm-suggestion">NULL kann nicht in den {0}-Typparameter konvertiert werden, da dieser Werttyp möglicherweise nicht auf NULL festgelegt werden kann. Verwenden Sie stattdessen ggf. default({0}).</target>
</trans-unit>
- <trans-unit id="BadRetType" translate="yes" xml:space="preserve">
- <source>'{1} {0}' has the wrong return type</source>
- <target state="needs-review-translation" state-qualifier="tm-suggestion">Der Rückgabetyp von {1} {0} ist falsch.</target>
- </trans-unit>
<trans-unit id="CantInferMethTypeArgs" translate="yes" xml:space="preserve">
<source>The type arguments for method '{0}' cannot be inferred from the usage. Try specifying the type arguments explicitly.</source>
<target state="needs-review-translation" state-qualifier="tm-suggestion">Die Typargumente der {0}-Methode können nicht per Rückschluss aus der Syntax abgeleitet werden. Geben Sie die Typargumente explizit an.</target>
</trans-unit>
- <trans-unit id="MethGrpToNonDel" translate="yes" xml:space="preserve">
- <source>Cannot convert method group '{0}' to non-delegate type '{1}'. Did you intend to invoke the method?</source>
- <target state="needs-review-translation" state-qualifier="tm-suggestion">Die {0}-Methodengruppe kann nicht in den Nichtdelegattyp "{1}" konvertiert werden. Wollten Sie die Methode aufrufen?</target>
- </trans-unit>
<trans-unit id="RefConstraintNotSatisfied" translate="yes" xml:space="preserve">
<source>The type '{2}' must be a reference type in order to use it as parameter '{1}' in the generic type or method '{0}'</source>
<target state="needs-review-translation" state-qualifier="tm-suggestion">Der {2}-Typ muss ein Referenztyp sein, damit er als {1}-Parameter im generischen Typ oder in der generischen {0}-Methode verwendet werden kann.</target>
@@ -274,10 +258,6 @@
<source>Cannot convert to static type '{0}'</source>
<target state="needs-review-translation" state-qualifier="tm-suggestion">Die Konvertierung in den statischen {0}-Typ ist nicht möglich.</target>
</trans-unit>
- <trans-unit id="GenericArgIsStaticClass" translate="yes" xml:space="preserve">
- <source>'{0}': static types cannot be used as type arguments</source>
- <target state="needs-review-translation" state-qualifier="tm-suggestion">{0}: Statische Typen können nicht als Typargumente verwendet werden.</target>
- </trans-unit>
<trans-unit id="IncrementLvalueExpected" translate="yes" xml:space="preserve">
<source>The operand of an increment or decrement operator must be a variable, property or indexer</source>
<target state="needs-review-translation" state-qualifier="tm-suggestion">Der Operand eines Inkrement- oder Dekrementoperators muss eine Variable, eine Eigenschaft oder ein Indexer sein.</target>
@@ -350,10 +330,6 @@
<source>Cannot pass '{0}' as a ref or out argument because it is a '{1}'</source>
<target state="needs-review-translation" state-qualifier="tm-suggestion">{0} ist ein(e) {1} und kann daher nicht als ref- oder out-Argument übergeben werden.</target>
</trans-unit>
- <trans-unit id="DelegateOnNullable" translate="yes" xml:space="preserve">
- <source>Cannot bind delegate to '{0}' because it is a member of 'System.Nullable<it id="1" pos="open">&lt;T&gt;</it>'</source>
- <target state="needs-review-translation" state-qualifier="mt-suggestion">Kann Delegaten "{0}" keine Bindung an weil es ein Mitglied von "System.Nullable<it id="1" pos="open">&lt;T&gt;</it>ist"</target>
- </trans-unit>
<trans-unit id="BadCtorArgCount" translate="yes" xml:space="preserve">
<source>'{0}' does not contain a constructor that takes '{1}' arguments</source>
<target state="needs-review-translation" state-qualifier="tm-suggestion">"{0}" enthält keinen Konstruktor, der {1}-Argumente akzeptiert.</target>
diff --git a/src/Microsoft.CSharp/src/MultilingualResources/Microsoft.CSharp.es.xlf b/src/Microsoft.CSharp/src/MultilingualResources/Microsoft.CSharp.es.xlf
index 083c1355e1..6e6a6c2f96 100644
--- a/src/Microsoft.CSharp/src/MultilingualResources/Microsoft.CSharp.es.xlf
+++ b/src/Microsoft.CSharp/src/MultilingualResources/Microsoft.CSharp.es.xlf
@@ -130,10 +130,6 @@
<source>The type '{0}' has no constructors defined</source>
<target state="needs-review-translation" state-qualifier="tm-suggestion">El tipo '{0}' no tiene constructores definidos.</target>
</trans-unit>
- <trans-unit id="BadDelegateConstructor" translate="yes" xml:space="preserve">
- <source>The delegate '{0}' does not have a valid constructor</source>
- <target state="needs-review-translation" state-qualifier="tm-suggestion">El delegado '{0}' no tiene un constructor válido</target>
- </trans-unit>
<trans-unit id="PropertyLacksGet" translate="yes" xml:space="preserve">
<source>The property or indexer '{0}' cannot be used in this context because it lacks the get accessor</source>
<target state="needs-review-translation" state-qualifier="tm-suggestion">La propiedad o el indizador '{0}' no se puede usar en este contexto porque carece del descriptor de acceso get.</target>
@@ -202,10 +198,6 @@
<source>Using the generic {1} '{0}' requires '{2}' type arguments</source>
<target state="needs-review-translation" state-qualifier="tm-suggestion">Uso de {1} de tipo genérico ('{0}'): requiere '{2}' argumentos de tipo</target>
</trans-unit>
- <trans-unit id="BadTypeArgument" translate="yes" xml:space="preserve">
- <source>The type '{0}' may not be used as a type argument</source>
- <target state="needs-review-translation" state-qualifier="tm-suggestion">El tipo '{0}' no se puede usar como argumento de tipo</target>
- </trans-unit>
<trans-unit id="TypeArgsNotAllowed" translate="yes" xml:space="preserve">
<source>The {1} '{0}' cannot be used with type arguments</source>
<target state="needs-review-translation" state-qualifier="tm-suggestion">{1} '{0}' no se puede usar con argumentos de tipo.</target>
@@ -238,18 +230,10 @@
<source>Cannot convert null to type parameter '{0}' because it could be a non-nullable value type. Consider using 'default({0})' instead.</source>
<target state="needs-review-translation" state-qualifier="tm-suggestion">No se puede convertir NULL en el parámetro de tipo '{0}' porque podría ser un tipo de valor que no acepta valores NULL. Use 'default({0})' en su lugar.</target>
</trans-unit>
- <trans-unit id="BadRetType" translate="yes" xml:space="preserve">
- <source>'{1} {0}' has the wrong return type</source>
- <target state="needs-review-translation" state-qualifier="tm-suggestion">'{1} {0}' es un tipo de valor devuelto equivocado</target>
- </trans-unit>
<trans-unit id="CantInferMethTypeArgs" translate="yes" xml:space="preserve">
<source>The type arguments for method '{0}' cannot be inferred from the usage. Try specifying the type arguments explicitly.</source>
<target state="needs-review-translation" state-qualifier="tm-suggestion">Los argumentos de tipo para el método '{0}' no se pueden inferir a partir del uso. Intente especificar los argumentos de tipo explícitamente.</target>
</trans-unit>
- <trans-unit id="MethGrpToNonDel" translate="yes" xml:space="preserve">
- <source>Cannot convert method group '{0}' to non-delegate type '{1}'. Did you intend to invoke the method?</source>
- <target state="needs-review-translation" state-qualifier="tm-suggestion">No se puede convertir el grupo de métodos '{0}' en tipo no delegado '{1}'. ¿Intentó invocar el método?</target>
- </trans-unit>
<trans-unit id="RefConstraintNotSatisfied" translate="yes" xml:space="preserve">
<source>The type '{2}' must be a reference type in order to use it as parameter '{1}' in the generic type or method '{0}'</source>
<target state="needs-review-translation" state-qualifier="tm-suggestion">El tipo '{2}' debe ser un tipo de referencia para poder usarlo como parámetro '{1}' en el tipo o método genérico '{0}'.</target>
@@ -274,10 +258,6 @@
<source>Cannot convert to static type '{0}'</source>
<target state="needs-review-translation" state-qualifier="tm-suggestion">No se puede convertir en el tipo estático '{0}'</target>
</trans-unit>
- <trans-unit id="GenericArgIsStaticClass" translate="yes" xml:space="preserve">
- <source>'{0}': static types cannot be used as type arguments</source>
- <target state="needs-review-translation" state-qualifier="tm-suggestion">'{0}': los tipos estáticos no se pueden usar como argumentos de tipo</target>
- </trans-unit>
<trans-unit id="IncrementLvalueExpected" translate="yes" xml:space="preserve">
<source>The operand of an increment or decrement operator must be a variable, property or indexer</source>
<target state="needs-review-translation" state-qualifier="tm-suggestion">El operando de un operador de incremento o decremento debe ser una variable, una propiedad o un indizador</target>
@@ -350,10 +330,6 @@
<source>Cannot pass '{0}' as a ref or out argument because it is a '{1}'</source>
<target state="needs-review-translation" state-qualifier="tm-suggestion">No se puede pasar '{0}' como argumento out o ref porque es '{1}'.</target>
</trans-unit>
- <trans-unit id="DelegateOnNullable" translate="yes" xml:space="preserve">
- <source>Cannot bind delegate to '{0}' because it is a member of 'System.Nullable<it id="1" pos="open">&lt;T&gt;</it>'</source>
- <target state="needs-review-translation" state-qualifier="mt-suggestion">No se puede enlazar el delegado para '{0}' porque es un miembro de 'System.Nullable<it id="1" pos="open">&lt;T&gt;</it>'</target>
- </trans-unit>
<trans-unit id="BadCtorArgCount" translate="yes" xml:space="preserve">
<source>'{0}' does not contain a constructor that takes '{1}' arguments</source>
<target state="needs-review-translation" state-qualifier="tm-suggestion">'{0}' no contiene un constructor que tome '{1}' argumentos</target>
diff --git a/src/Microsoft.CSharp/src/MultilingualResources/Microsoft.CSharp.fr.xlf b/src/Microsoft.CSharp/src/MultilingualResources/Microsoft.CSharp.fr.xlf
index 344eeb371a..7451594b00 100644
--- a/src/Microsoft.CSharp/src/MultilingualResources/Microsoft.CSharp.fr.xlf
+++ b/src/Microsoft.CSharp/src/MultilingualResources/Microsoft.CSharp.fr.xlf
@@ -130,10 +130,6 @@
<source>The type '{0}' has no constructors defined</source>
<target state="needs-review-translation" state-qualifier="tm-suggestion">Aucun constructeur n'est défini pour le type '{0}'</target>
</trans-unit>
- <trans-unit id="BadDelegateConstructor" translate="yes" xml:space="preserve">
- <source>The delegate '{0}' does not have a valid constructor</source>
- <target state="needs-review-translation" state-qualifier="tm-suggestion">Le délégué '{0}' n'a pas de constructeur valide</target>
- </trans-unit>
<trans-unit id="PropertyLacksGet" translate="yes" xml:space="preserve">
<source>The property or indexer '{0}' cannot be used in this context because it lacks the get accessor</source>
<target state="needs-review-translation" state-qualifier="tm-suggestion">Impossible d'utiliser la propriété ou l'indexeur '{0}' dans ce contexte, car il lui manque l'accesseur get</target>
@@ -202,10 +198,6 @@
<source>Using the generic {1} '{0}' requires '{2}' type arguments</source>
<target state="needs-review-translation" state-qualifier="tm-suggestion">L'utilisation du {1} '{0}' générique requiert les arguments de type '{2}'</target>
</trans-unit>
- <trans-unit id="BadTypeArgument" translate="yes" xml:space="preserve">
- <source>The type '{0}' may not be used as a type argument</source>
- <target state="needs-review-translation" state-qualifier="tm-suggestion">Le type '{0}' ne peut pas être utilisé comme argument de type</target>
- </trans-unit>
<trans-unit id="TypeArgsNotAllowed" translate="yes" xml:space="preserve">
<source>The {1} '{0}' cannot be used with type arguments</source>
<target state="needs-review-translation" state-qualifier="tm-suggestion">Impossible d'utiliser le {1} '{0}' avec des arguments de type</target>
@@ -238,18 +230,10 @@
<source>Cannot convert null to type parameter '{0}' because it could be a non-nullable value type. Consider using 'default({0})' instead.</source>
<target state="needs-review-translation" state-qualifier="tm-suggestion">Impossible de convertir null en paramètre de type '{0}' car il peut s'agir d'un type valeur qui n'autorise pas les valeurs null. Utilisez 'default({0})' à la place.</target>
</trans-unit>
- <trans-unit id="BadRetType" translate="yes" xml:space="preserve">
- <source>'{1} {0}' has the wrong return type</source>
- <target state="needs-review-translation" state-qualifier="tm-suggestion">'{1} {0}' n'a pas le type de retour correct</target>
- </trans-unit>
<trans-unit id="CantInferMethTypeArgs" translate="yes" xml:space="preserve">
<source>The type arguments for method '{0}' cannot be inferred from the usage. Try specifying the type arguments explicitly.</source>
<target state="needs-review-translation" state-qualifier="tm-suggestion">Impossible de déduire les arguments de type pour la méthode '{0}' à partir de l'utilisation. Essayez de spécifier les arguments de type de façon explicite.</target>
</trans-unit>
- <trans-unit id="MethGrpToNonDel" translate="yes" xml:space="preserve">
- <source>Cannot convert method group '{0}' to non-delegate type '{1}'. Did you intend to invoke the method?</source>
- <target state="needs-review-translation" state-qualifier="tm-suggestion">Impossible de convertir le groupe de méthodes '{0}' en type non-délégué '{1}'. Souhaitiez-vous appeler la méthode ?</target>
- </trans-unit>
<trans-unit id="RefConstraintNotSatisfied" translate="yes" xml:space="preserve">
<source>The type '{2}' must be a reference type in order to use it as parameter '{1}' in the generic type or method '{0}'</source>
<target state="needs-review-translation" state-qualifier="tm-suggestion">Le type '{2}' doit être un type référence afin d'être utilisé comme paramètre '{1}' dans le type ou la méthode générique '{0}'</target>
@@ -274,10 +258,6 @@
<source>Cannot convert to static type '{0}'</source>
<target state="needs-review-translation" state-qualifier="tm-suggestion">Impossible de convertir en type static '{0}'</target>
</trans-unit>
- <trans-unit id="GenericArgIsStaticClass" translate="yes" xml:space="preserve">
- <source>'{0}': static types cannot be used as type arguments</source>
- <target state="needs-review-translation" state-qualifier="tm-suggestion">'{0}' : impossible d'utiliser les types static en tant qu'arguments de type</target>
- </trans-unit>
<trans-unit id="IncrementLvalueExpected" translate="yes" xml:space="preserve">
<source>The operand of an increment or decrement operator must be a variable, property or indexer</source>
<target state="needs-review-translation" state-qualifier="tm-suggestion">L'opérande d'un opérateur d'incrémentation ou de décrémentation doit être une variable, une propriété ou un indexeur</target>
@@ -350,10 +330,6 @@
<source>Cannot pass '{0}' as a ref or out argument because it is a '{1}'</source>
<target state="needs-review-translation" state-qualifier="tm-suggestion">Impossible de passer '{0}' en tant qu'argument ref ou out, car il s'agit d'un '{1}'</target>
</trans-unit>
- <trans-unit id="DelegateOnNullable" translate="yes" xml:space="preserve">
- <source>Cannot bind delegate to '{0}' because it is a member of 'System.Nullable<it id="1" pos="open">&lt;T&gt;</it>'</source>
- <target state="needs-review-translation" state-qualifier="mt-suggestion">Impossible de lier délégué à « {0} » parce que c'est un membre de « System.Nullable<it id="1" pos="open">&lt;T&gt;</it>»</target>
- </trans-unit>
<trans-unit id="BadCtorArgCount" translate="yes" xml:space="preserve">
<source>'{0}' does not contain a constructor that takes '{1}' arguments</source>
<target state="needs-review-translation" state-qualifier="tm-suggestion">'{0}' ne contient pas de constructeur qui accepte des arguments '{1}'</target>
diff --git a/src/Microsoft.CSharp/src/MultilingualResources/Microsoft.CSharp.it.xlf b/src/Microsoft.CSharp/src/MultilingualResources/Microsoft.CSharp.it.xlf
index 755cfdf71c..db8953703d 100644
--- a/src/Microsoft.CSharp/src/MultilingualResources/Microsoft.CSharp.it.xlf
+++ b/src/Microsoft.CSharp/src/MultilingualResources/Microsoft.CSharp.it.xlf
@@ -130,10 +130,6 @@
<source>The type '{0}' has no constructors defined</source>
<target state="needs-review-translation" state-qualifier="tm-suggestion">Per il tipo '{0}' non sono definiti costruttori</target>
</trans-unit>
- <trans-unit id="BadDelegateConstructor" translate="yes" xml:space="preserve">
- <source>The delegate '{0}' does not have a valid constructor</source>
- <target state="needs-review-translation" state-qualifier="tm-suggestion">Il delegato '{0}' non presenta un costruttore valido</target>
- </trans-unit>
<trans-unit id="PropertyLacksGet" translate="yes" xml:space="preserve">
<source>The property or indexer '{0}' cannot be used in this context because it lacks the get accessor</source>
<target state="needs-review-translation" state-qualifier="tm-suggestion">Impossibile utilizzare la proprietà o l'indicizzatore '{0}' in questo contesto perché manca la funzione di accesso get.</target>
@@ -202,10 +198,6 @@
<source>Using the generic {1} '{0}' requires '{2}' type arguments</source>
<target state="needs-review-translation" state-qualifier="tm-suggestion">L'utilizzo del {1} generico '{0}' richiede argomenti di tipo '{2}'</target>
</trans-unit>
- <trans-unit id="BadTypeArgument" translate="yes" xml:space="preserve">
- <source>The type '{0}' may not be used as a type argument</source>
- <target state="needs-review-translation" state-qualifier="tm-suggestion">Il tipo '{0}' non può essere utilizzato come argomento di tipo</target>
- </trans-unit>
<trans-unit id="TypeArgsNotAllowed" translate="yes" xml:space="preserve">
<source>The {1} '{0}' cannot be used with type arguments</source>
<target state="needs-review-translation" state-qualifier="tm-suggestion">Impossibile utilizzare {1} '{0}' insieme ad argomenti di tipo</target>
@@ -238,18 +230,10 @@
<source>Cannot convert null to type parameter '{0}' because it could be a non-nullable value type. Consider using 'default({0})' instead.</source>
<target state="needs-review-translation" state-qualifier="tm-suggestion">Impossibile convertire il valore Null nel parametro di tipo '{0}' perché potrebbe essere un tipo di valore non nullable. Si consiglia di utilizzare 'default({0})'.</target>
</trans-unit>
- <trans-unit id="BadRetType" translate="yes" xml:space="preserve">
- <source>'{1} {0}' has the wrong return type</source>
- <target state="needs-review-translation" state-qualifier="tm-suggestion">Il tipo restituito di '{1} {0}' è errato</target>
- </trans-unit>
<trans-unit id="CantInferMethTypeArgs" translate="yes" xml:space="preserve">
<source>The type arguments for method '{0}' cannot be inferred from the usage. Try specifying the type arguments explicitly.</source>
<target state="needs-review-translation" state-qualifier="tm-suggestion">Impossibile dedurre gli argomenti di tipo per il metodo '{0}' dall'utilizzo. Provare a specificare gli argomenti di tipo in modo esplicito.</target>
</trans-unit>
- <trans-unit id="MethGrpToNonDel" translate="yes" xml:space="preserve">
- <source>Cannot convert method group '{0}' to non-delegate type '{1}'. Did you intend to invoke the method?</source>
- <target state="needs-review-translation" state-qualifier="tm-suggestion">Impossibile convertire il gruppo di metodi '{0}' nel tipo non delegato '{1}'. Si desiderava richiamare il metodo?</target>
- </trans-unit>
<trans-unit id="RefConstraintNotSatisfied" translate="yes" xml:space="preserve">
<source>The type '{2}' must be a reference type in order to use it as parameter '{1}' in the generic type or method '{0}'</source>
<target state="needs-review-translation" state-qualifier="tm-suggestion">È necessario che il tipo '{2}' sia un tipo di riferimento per essere utilizzato come parametro '{1}' nel tipo generico o nel metodo '{0}'</target>
@@ -274,10 +258,6 @@
<source>Cannot convert to static type '{0}'</source>
<target state="needs-review-translation" state-qualifier="tm-suggestion">Impossibile convertire nel tipo statico '{0}'</target>
</trans-unit>
- <trans-unit id="GenericArgIsStaticClass" translate="yes" xml:space="preserve">
- <source>'{0}': static types cannot be used as type arguments</source>
- <target state="needs-review-translation" state-qualifier="tm-suggestion">'{0}': i tipi statici non possono essere utilizzati come argomenti di tipi</target>
- </trans-unit>
<trans-unit id="IncrementLvalueExpected" translate="yes" xml:space="preserve">
<source>The operand of an increment or decrement operator must be a variable, property or indexer</source>
<target state="needs-review-translation" state-qualifier="tm-suggestion">L'operando di un operatore di incremento o decremento deve essere una variabile, una proprietà o un indicizzatore</target>
@@ -350,10 +330,6 @@
<source>Cannot pass '{0}' as a ref or out argument because it is a '{1}'</source>
<target state="needs-review-translation" state-qualifier="tm-suggestion">Impossibile passare '{0}' come argomento ref o out perché è '{1}'</target>
</trans-unit>
- <trans-unit id="DelegateOnNullable" translate="yes" xml:space="preserve">
- <source>Cannot bind delegate to '{0}' because it is a member of 'System.Nullable<it id="1" pos="open">&lt;T&gt;</it>'</source>
- <target state="needs-review-translation" state-qualifier="mt-suggestion">Non è possibile associare il delegato a '{0}' perché è un membro di 'System. Nullable<it id="1" pos="open">&lt;T&gt;</it>'</target>
- </trans-unit>
<trans-unit id="BadCtorArgCount" translate="yes" xml:space="preserve">
<source>'{0}' does not contain a constructor that takes '{1}' arguments</source>
<target state="needs-review-translation" state-qualifier="tm-suggestion">'{0}' non contiene un costruttore che accetta argomenti '{1}'</target>
diff --git a/src/Microsoft.CSharp/src/MultilingualResources/Microsoft.CSharp.ja.xlf b/src/Microsoft.CSharp/src/MultilingualResources/Microsoft.CSharp.ja.xlf
index f9d3326f72..dad6b14f71 100644
--- a/src/Microsoft.CSharp/src/MultilingualResources/Microsoft.CSharp.ja.xlf
+++ b/src/Microsoft.CSharp/src/MultilingualResources/Microsoft.CSharp.ja.xlf
@@ -130,10 +130,6 @@
<source>The type '{0}' has no constructors defined</source>
<target state="needs-review-translation" state-qualifier="tm-suggestion">型 '{0}' のコンストラクターが定義されていません</target>
</trans-unit>
- <trans-unit id="BadDelegateConstructor" translate="yes" xml:space="preserve">
- <source>The delegate '{0}' does not have a valid constructor</source>
- <target state="needs-review-translation" state-qualifier="tm-suggestion">デリゲート '{0}' には有効なコンストラクターがありません</target>
- </trans-unit>
<trans-unit id="PropertyLacksGet" translate="yes" xml:space="preserve">
<source>The property or indexer '{0}' cannot be used in this context because it lacks the get accessor</source>
<target state="needs-review-translation" state-qualifier="tm-suggestion">get アクセサーがないため、プロパティまたはインデクサー '{0}' をこのコンテキストで使用することはできません</target>
@@ -202,10 +198,6 @@
<source>Using the generic {1} '{0}' requires '{2}' type arguments</source>
<target state="needs-review-translation" state-qualifier="tm-suggestion">ジェネリック {1} '{0}' の使用には、'{2}' 型の引数が必要です</target>
</trans-unit>
- <trans-unit id="BadTypeArgument" translate="yes" xml:space="preserve">
- <source>The type '{0}' may not be used as a type argument</source>
- <target state="needs-review-translation" state-qualifier="mt-suggestion">型 '{0}' は型引数としては使えません</target>
- </trans-unit>
<trans-unit id="TypeArgsNotAllowed" translate="yes" xml:space="preserve">
<source>The {1} '{0}' cannot be used with type arguments</source>
<target state="needs-review-translation" state-qualifier="tm-suggestion">{1} '{0}' は型引数と一緒には使用できません</target>
@@ -238,18 +230,10 @@
<source>Cannot convert null to type parameter '{0}' because it could be a non-nullable value type. Consider using 'default({0})' instead.</source>
<target state="needs-review-translation" state-qualifier="tm-suggestion">Null 非許容の値型である可能性があるため、Null を型パラメーター '{0}' に変換できません。'default({0})' を使用してください。</target>
</trans-unit>
- <trans-unit id="BadRetType" translate="yes" xml:space="preserve">
- <source>'{1} {0}' has the wrong return type</source>
- <target state="needs-review-translation" state-qualifier="tm-suggestion">'{1} {0}' には、不適切な戻り値の型が指定されています</target>
- </trans-unit>
<trans-unit id="CantInferMethTypeArgs" translate="yes" xml:space="preserve">
<source>The type arguments for method '{0}' cannot be inferred from the usage. Try specifying the type arguments explicitly.</source>
<target state="needs-review-translation" state-qualifier="tm-suggestion">メソッド '{0}' の型引数を使い方から推論することはできません。型引数を明示的に指定してください。</target>
</trans-unit>
- <trans-unit id="MethGrpToNonDel" translate="yes" xml:space="preserve">
- <source>Cannot convert method group '{0}' to non-delegate type '{1}'. Did you intend to invoke the method?</source>
- <target state="needs-review-translation" state-qualifier="tm-suggestion">メソッド グループ '{0}' を非デリゲート型 '{1}' に変換することはできません。このメソッドを呼び出しますか?</target>
- </trans-unit>
<trans-unit id="RefConstraintNotSatisfied" translate="yes" xml:space="preserve">
<source>The type '{2}' must be a reference type in order to use it as parameter '{1}' in the generic type or method '{0}'</source>
<target state="needs-review-translation" state-qualifier="tm-suggestion">型 '{2}' は、ジェネリック型のパラメーター '{1}'、またはメソッド '{0}' として使用するために、参照型でなければなりません</target>
@@ -274,10 +258,6 @@
<source>Cannot convert to static type '{0}'</source>
<target state="needs-review-translation" state-qualifier="tm-suggestion">スタティック型 '{0}' へ変換できません</target>
</trans-unit>
- <trans-unit id="GenericArgIsStaticClass" translate="yes" xml:space="preserve">
- <source>'{0}': static types cannot be used as type arguments</source>
- <target state="needs-review-translation" state-qualifier="tm-suggestion">'{0}': スタティック型を型引数として使用することはできません</target>
- </trans-unit>
<trans-unit id="IncrementLvalueExpected" translate="yes" xml:space="preserve">
<source>The operand of an increment or decrement operator must be a variable, property or indexer</source>
<target state="needs-review-translation" state-qualifier="tm-suggestion">インクリメント演算子またはデクリメント演算子のオペランドには、変数、プロパティ、またはインデクサーを指定してください。</target>
@@ -350,10 +330,6 @@
<source>Cannot pass '{0}' as a ref or out argument because it is a '{1}'</source>
<target state="needs-review-translation" state-qualifier="tm-suggestion">'{1}' であるため、'{0}' は ref または out 引数として渡せません</target>
</trans-unit>
- <trans-unit id="DelegateOnNullable" translate="yes" xml:space="preserve">
- <source>Cannot bind delegate to '{0}' because it is a member of 'System.Nullable<it id="1" pos="open">&lt;T&gt;</it>'</source>
- <target state="needs-review-translation" state-qualifier="mt-suggestion">'System.Nullable<it id="1" pos="open">&lt;T&gt;</it>' のメンバーであるために、'{0}' のデリゲートをバインドできません。</target>
- </trans-unit>
<trans-unit id="BadCtorArgCount" translate="yes" xml:space="preserve">
<source>'{0}' does not contain a constructor that takes '{1}' arguments</source>
<target state="needs-review-translation" state-qualifier="tm-suggestion">'{0}' に、引数を '{1}' 個指定できるコンストラクターがありません</target>
diff --git a/src/Microsoft.CSharp/src/MultilingualResources/Microsoft.CSharp.ko.xlf b/src/Microsoft.CSharp/src/MultilingualResources/Microsoft.CSharp.ko.xlf
index 9e72f7378a..96bef67635 100644
--- a/src/Microsoft.CSharp/src/MultilingualResources/Microsoft.CSharp.ko.xlf
+++ b/src/Microsoft.CSharp/src/MultilingualResources/Microsoft.CSharp.ko.xlf
@@ -130,10 +130,6 @@
<source>The type '{0}' has no constructors defined</source>
<target state="needs-review-translation" state-qualifier="tm-suggestion">'{0}' 형식에 정의된 생성자가 없습니다.</target>
</trans-unit>
- <trans-unit id="BadDelegateConstructor" translate="yes" xml:space="preserve">
- <source>The delegate '{0}' does not have a valid constructor</source>
- <target state="needs-review-translation" state-qualifier="tm-suggestion">'{0}' 대리자에 올바른 생성자가 없습니다.</target>
- </trans-unit>
<trans-unit id="PropertyLacksGet" translate="yes" xml:space="preserve">
<source>The property or indexer '{0}' cannot be used in this context because it lacks the get accessor</source>
<target state="needs-review-translation" state-qualifier="tm-suggestion">'{0}' 속성 또는 인덱서는 get 접근자가 없으므로 이 컨텍스트에서 사용할 수 없습니다.</target>
@@ -202,10 +198,6 @@
<source>Using the generic {1} '{0}' requires '{2}' type arguments</source>
<target state="needs-review-translation" state-qualifier="tm-suggestion">제네릭 {1} '{0}'을(를) 사용하려면 '{2}' 형식 인수가 필요합니다.</target>
</trans-unit>
- <trans-unit id="BadTypeArgument" translate="yes" xml:space="preserve">
- <source>The type '{0}' may not be used as a type argument</source>
- <target state="needs-review-translation" state-qualifier="tm-suggestion">'{0}' 형식은 형식 인수로 사용할 수 없습니다.</target>
- </trans-unit>
<trans-unit id="TypeArgsNotAllowed" translate="yes" xml:space="preserve">
<source>The {1} '{0}' cannot be used with type arguments</source>
<target state="needs-review-translation" state-qualifier="tm-suggestion">{1} '{0}'은(는) 형식 인수와 함께 사용할 수 없습니다.</target>
@@ -238,18 +230,10 @@
<source>Cannot convert null to type parameter '{0}' because it could be a non-nullable value type. Consider using 'default({0})' instead.</source>
<target state="needs-review-translation" state-qualifier="tm-suggestion">null을 허용하지 않는 값 형식일 수 있으므로 null을 형식 매개 변수 '{0}'(으)로 변환할 수 없습니다. 대신 'default({0})'를 사용하십시오.</target>
</trans-unit>
- <trans-unit id="BadRetType" translate="yes" xml:space="preserve">
- <source>'{1} {0}' has the wrong return type</source>
- <target state="needs-review-translation" state-qualifier="tm-suggestion">'{1} {0}'에 잘못된 반환 형식이 있습니다.</target>
- </trans-unit>
<trans-unit id="CantInferMethTypeArgs" translate="yes" xml:space="preserve">
<source>The type arguments for method '{0}' cannot be inferred from the usage. Try specifying the type arguments explicitly.</source>
<target state="needs-review-translation" state-qualifier="tm-suggestion">'{0}' 메서드의 형식 인수를 유추할 수 없습니다. 형식 인수를 명시적으로 지정하십시오.</target>
</trans-unit>
- <trans-unit id="MethGrpToNonDel" translate="yes" xml:space="preserve">
- <source>Cannot convert method group '{0}' to non-delegate type '{1}'. Did you intend to invoke the method?</source>
- <target state="needs-review-translation" state-qualifier="tm-suggestion">'{0}' 메서드 그룹을 비대리자 형식 '{1}'(으)로 변환할 수 없습니다. 메서드를 호출하시겠습니까?</target>
- </trans-unit>
<trans-unit id="RefConstraintNotSatisfied" translate="yes" xml:space="preserve">
<source>The type '{2}' must be a reference type in order to use it as parameter '{1}' in the generic type or method '{0}'</source>
<target state="needs-review-translation" state-qualifier="tm-suggestion">제네릭 형식 또는 메서드 '{0}'에서 '{2}' 형식을 '{1}' 매개 변수로 사용하려면 해당 형식이 참조 형식이어야 합니다.</target>
@@ -274,10 +258,6 @@
<source>Cannot convert to static type '{0}'</source>
<target state="needs-review-translation" state-qualifier="tm-suggestion">'{0}' 정적 형식으로 변환할 수 없습니다.</target>
</trans-unit>
- <trans-unit id="GenericArgIsStaticClass" translate="yes" xml:space="preserve">
- <source>'{0}': static types cannot be used as type arguments</source>
- <target state="needs-review-translation" state-qualifier="tm-suggestion">'{0}': 정적 형식은 형식 인수로 사용할 수 없습니다.</target>
- </trans-unit>
<trans-unit id="IncrementLvalueExpected" translate="yes" xml:space="preserve">
<source>The operand of an increment or decrement operator must be a variable, property or indexer</source>
<target state="needs-review-translation" state-qualifier="tm-suggestion">증가 연산자 또는 감소 연산자의 피연산자는 변수, 속성 또는 인덱서여야 합니다.</target>
@@ -350,10 +330,6 @@
<source>Cannot pass '{0}' as a ref or out argument because it is a '{1}'</source>
<target state="needs-review-translation" state-qualifier="tm-suggestion">'{0}'은(는) '{1}'이므로 ref 또는 out 인수로 전달할 수 없습니다.</target>
</trans-unit>
- <trans-unit id="DelegateOnNullable" translate="yes" xml:space="preserve">
- <source>Cannot bind delegate to '{0}' because it is a member of 'System.Nullable<it id="1" pos="open">&lt;T&gt;</it>'</source>
- <target state="needs-review-translation" state-qualifier="mt-suggestion">그것 'System.Nullable<it id="1" pos="open">&lt;T&gt;</it>'의 멤버 이므로 ' (0) '에 대리자를 바인딩할 수 없습니다.</target>
- </trans-unit>
<trans-unit id="BadCtorArgCount" translate="yes" xml:space="preserve">
<source>'{0}' does not contain a constructor that takes '{1}' arguments</source>
<target state="needs-review-translation" state-qualifier="tm-suggestion">'{0}'에 '{1}'개의 인수를 사용하는 생성자가 없습니다.</target>
diff --git a/src/Microsoft.CSharp/src/MultilingualResources/Microsoft.CSharp.ru.xlf b/src/Microsoft.CSharp/src/MultilingualResources/Microsoft.CSharp.ru.xlf
index 9390223fff..bee9fc7cfb 100644
--- a/src/Microsoft.CSharp/src/MultilingualResources/Microsoft.CSharp.ru.xlf
+++ b/src/Microsoft.CSharp/src/MultilingualResources/Microsoft.CSharp.ru.xlf
@@ -130,10 +130,6 @@
<source>The type '{0}' has no constructors defined</source>
<target state="needs-review-translation" state-qualifier="tm-suggestion">Для типа "{0}" нет определенных конструкторов</target>
</trans-unit>
- <trans-unit id="BadDelegateConstructor" translate="yes" xml:space="preserve">
- <source>The delegate '{0}' does not have a valid constructor</source>
- <target state="needs-review-translation" state-qualifier="tm-suggestion">Делегат "{0}" не имеет допустимого конструктора</target>
- </trans-unit>
<trans-unit id="PropertyLacksGet" translate="yes" xml:space="preserve">
<source>The property or indexer '{0}' cannot be used in this context because it lacks the get accessor</source>
<target state="needs-review-translation" state-qualifier="tm-suggestion">The property or indexer "{0}" cannot be used in this context because it lacks the get accessor</target>
@@ -202,10 +198,6 @@
<source>Using the generic {1} '{0}' requires '{2}' type arguments</source>
<target state="needs-review-translation" state-qualifier="tm-suggestion">Использование универсального {1} "{0}" требует аргументов типа "{2}"</target>
</trans-unit>
- <trans-unit id="BadTypeArgument" translate="yes" xml:space="preserve">
- <source>The type '{0}' may not be used as a type argument</source>
- <target state="needs-review-translation" state-qualifier="mt-suggestion">Тип '{0}' не может использоваться в качестве аргумента типа</target>
- </trans-unit>
<trans-unit id="TypeArgsNotAllowed" translate="yes" xml:space="preserve">
<source>The {1} '{0}' cannot be used with type arguments</source>
<target state="needs-review-translation" state-qualifier="tm-suggestion">{1} "{0}" не может использоваться с аргументами типа</target>
@@ -238,18 +230,10 @@
<source>Cannot convert null to type parameter '{0}' because it could be a non-nullable value type. Consider using 'default({0})' instead.</source>
<target state="needs-review-translation" state-qualifier="tm-suggestion">Cannot convert null to type parameter "{0}" because it could be a non-nullable value type. Вместо этого рекомендуется использовать "default({0})".</target>
</trans-unit>
- <trans-unit id="BadRetType" translate="yes" xml:space="preserve">
- <source>'{1} {0}' has the wrong return type</source>
- <target state="needs-review-translation" state-qualifier="tm-suggestion">"{1} {0}" имеет неправильный возвращаемый тип</target>
- </trans-unit>
<trans-unit id="CantInferMethTypeArgs" translate="yes" xml:space="preserve">
<source>The type arguments for method '{0}' cannot be inferred from the usage. Try specifying the type arguments explicitly.</source>
<target state="needs-review-translation" state-qualifier="tm-suggestion">The type arguments for method "{0}" cannot be inferred from the usage. Попытайтесь явно определить аргументы-типы.</target>
</trans-unit>
- <trans-unit id="MethGrpToNonDel" translate="yes" xml:space="preserve">
- <source>Cannot convert method group '{0}' to non-delegate type '{1}'. Did you intend to invoke the method?</source>
- <target state="needs-review-translation" state-qualifier="tm-suggestion">Не удается преобразовать группу методов "{0}" в тип, не являющийся делегатом "{1}". Предполагается ли вызывать этот метод?</target>
- </trans-unit>
<trans-unit id="RefConstraintNotSatisfied" translate="yes" xml:space="preserve">
<source>The type '{2}' must be a reference type in order to use it as parameter '{1}' in the generic type or method '{0}'</source>
<target state="needs-review-translation" state-qualifier="tm-suggestion">Для использования в качестве параметра "{1}" в универсальном типе или методе "{0}" тип "{2}" должен быть ссылочным типом</target>
@@ -274,10 +258,6 @@
<source>Cannot convert to static type '{0}'</source>
<target state="needs-review-translation" state-qualifier="tm-suggestion">Не удается выполнить преобразование к статическому типу "{0}"</target>
</trans-unit>
- <trans-unit id="GenericArgIsStaticClass" translate="yes" xml:space="preserve">
- <source>'{0}': static types cannot be used as type arguments</source>
- <target state="needs-review-translation" state-qualifier="tm-suggestion">"{0}": нельзя использовать статические типы в качестве аргументов-типов</target>
- </trans-unit>
<trans-unit id="IncrementLvalueExpected" translate="yes" xml:space="preserve">
<source>The operand of an increment or decrement operator must be a variable, property or indexer</source>
<target state="needs-review-translation" state-qualifier="tm-suggestion">Операндом оператора инкремента или декремента должна быть переменная, свойство или индексатор</target>
@@ -350,10 +330,6 @@
<source>Cannot pass '{0}' as a ref or out argument because it is a '{1}'</source>
<target state="needs-review-translation" state-qualifier="tm-suggestion">Не удалось передать "{0}" как ссылку или аргумент out, так как это "{1}"</target>
</trans-unit>
- <trans-unit id="DelegateOnNullable" translate="yes" xml:space="preserve">
- <source>Cannot bind delegate to '{0}' because it is a member of 'System.Nullable<it id="1" pos="open">&lt;T&gt;</it>'</source>
- <target state="needs-review-translation" state-qualifier="mt-suggestion">Не удается привязать делегат '{0}', потому что он является членом «System.Nullable<it id="1" pos="open">&lt;T&gt;</it>»</target>
- </trans-unit>
<trans-unit id="BadCtorArgCount" translate="yes" xml:space="preserve">
<source>'{0}' does not contain a constructor that takes '{1}' arguments</source>
<target state="needs-review-translation" state-qualifier="tm-suggestion">"{0}" не содержит конструктор, принимающий аргументов: {1}</target>
diff --git a/src/Microsoft.CSharp/src/MultilingualResources/Microsoft.CSharp.zh-Hans.xlf b/src/Microsoft.CSharp/src/MultilingualResources/Microsoft.CSharp.zh-Hans.xlf
index 339f15978f..ae7fe863c0 100644
--- a/src/Microsoft.CSharp/src/MultilingualResources/Microsoft.CSharp.zh-Hans.xlf
+++ b/src/Microsoft.CSharp/src/MultilingualResources/Microsoft.CSharp.zh-Hans.xlf
@@ -130,10 +130,6 @@
<source>The type '{0}' has no constructors defined</source>
<target state="needs-review-translation" state-qualifier="tm-suggestion">类型“{0}”未定义构造函数</target>
</trans-unit>
- <trans-unit id="BadDelegateConstructor" translate="yes" xml:space="preserve">
- <source>The delegate '{0}' does not have a valid constructor</source>
- <target state="needs-review-translation" state-qualifier="tm-suggestion">委托“{0}”没有有效的构造函数</target>
- </trans-unit>
<trans-unit id="PropertyLacksGet" translate="yes" xml:space="preserve">
<source>The property or indexer '{0}' cannot be used in this context because it lacks the get accessor</source>
<target state="needs-review-translation" state-qualifier="tm-suggestion">属性或索引器“{0}”不能用在此上下文中,因为它缺少 get 访问器</target>
@@ -206,10 +202,6 @@
<source>Using the generic {1} '{0}' requires '{2}' type arguments</source>
<target state="needs-review-translation" state-qualifier="tm-suggestion">使用泛型 {1}“{0}”需要“{2}”个类型参数</target>
</trans-unit>
- <trans-unit id="BadTypeArgument" translate="yes" xml:space="preserve">
- <source>The type '{0}' may not be used as a type argument</source>
- <target state="needs-review-translation" state-qualifier="mt-suggestion">类型"{0}"不可能用作类型参数</target>
- </trans-unit>
<trans-unit id="TypeArgsNotAllowed" translate="yes" xml:space="preserve">
<source>The {1} '{0}' cannot be used with type arguments</source>
<target state="needs-review-translation" state-qualifier="tm-suggestion">{1}“{0}”不能与类型参数一起使用</target>
@@ -242,18 +234,10 @@
<source>Cannot convert null to type parameter '{0}' because it could be a non-nullable value type. Consider using 'default({0})' instead.</source>
<target state="needs-review-translation" state-qualifier="tm-suggestion">无法将 null 转换为类型参数“{0}”,因为它可能是不可以为 null 的值类型。请考虑改用“default({0})”。</target>
</trans-unit>
- <trans-unit id="BadRetType" translate="yes" xml:space="preserve">
- <source>'{1} {0}' has the wrong return type</source>
- <target state="needs-review-translation" state-qualifier="tm-suggestion">“{1} {0}”的返回类型错误</target>
- </trans-unit>
<trans-unit id="CantInferMethTypeArgs" translate="yes" xml:space="preserve">
<source>The type arguments for method '{0}' cannot be inferred from the usage. Try specifying the type arguments explicitly.</source>
<target state="needs-review-translation" state-qualifier="tm-suggestion">无法从用法中推断出方法“{0}”的类型参数。请尝试显式指定类型参数。</target>
</trans-unit>
- <trans-unit id="MethGrpToNonDel" translate="yes" xml:space="preserve">
- <source>Cannot convert method group '{0}' to non-delegate type '{1}'. Did you intend to invoke the method?</source>
- <target state="needs-review-translation" state-qualifier="tm-suggestion">无法将方法组“{0}”转换为非委托类型“{1}”。是否希望调用此方法?</target>
- </trans-unit>
<trans-unit id="RefConstraintNotSatisfied" translate="yes" xml:space="preserve">
<source>The type '{2}' must be a reference type in order to use it as parameter '{1}' in the generic type or method '{0}'</source>
<target state="needs-review-translation" state-qualifier="tm-suggestion">类型“{2}”必须是引用类型才能用作泛型类型或方法“{0}”中的参数“{1}”</target>
@@ -278,10 +262,6 @@
<source>Cannot convert to static type '{0}'</source>
<target state="needs-review-translation" state-qualifier="tm-suggestion">无法转换为静态类型“{0}”</target>
</trans-unit>
- <trans-unit id="GenericArgIsStaticClass" translate="yes" xml:space="preserve">
- <source>'{0}': static types cannot be used as type arguments</source>
- <target state="needs-review-translation" state-qualifier="tm-suggestion">“{0}”: 静态类型不能用作类型参数</target>
- </trans-unit>
<trans-unit id="IncrementLvalueExpected" translate="yes" xml:space="preserve">
<source>The operand of an increment or decrement operator must be a variable, property or indexer</source>
<target state="needs-review-translation" state-qualifier="tm-suggestion">递增或递减运算符的操作数必须是变量、属性或索引器</target>
@@ -354,10 +334,6 @@
<source>Cannot pass '{0}' as a ref or out argument because it is a '{1}'</source>
<target state="needs-review-translation" state-qualifier="tm-suggestion">“{0}”是一个“{1}”,无法作为 ref 或 out 参数进行传递</target>
</trans-unit>
- <trans-unit id="DelegateOnNullable" translate="yes" xml:space="preserve">
- <source>Cannot bind delegate to '{0}' because it is a member of 'System.Nullable<it id="1" pos="open">&lt;T&gt;</it>'</source>
- <target state="needs-review-translation" state-qualifier="mt-suggestion">不能将委托绑定到 '{0}',因为它是 'System.Nullable<it id="1" pos="open">&lt;T&gt;</it>' 成员</target>
- </trans-unit>
<trans-unit id="BadCtorArgCount" translate="yes" xml:space="preserve">
<source>'{0}' does not contain a constructor that takes '{1}' arguments</source>
<target state="needs-review-translation" state-qualifier="tm-suggestion">“{0}”不包含采用“{1}”个参数的构造函数</target>
diff --git a/src/Microsoft.CSharp/src/MultilingualResources/Microsoft.CSharp.zh-Hant.xlf b/src/Microsoft.CSharp/src/MultilingualResources/Microsoft.CSharp.zh-Hant.xlf
index c4bd6b8f5f..87f7bb93c6 100644
--- a/src/Microsoft.CSharp/src/MultilingualResources/Microsoft.CSharp.zh-Hant.xlf
+++ b/src/Microsoft.CSharp/src/MultilingualResources/Microsoft.CSharp.zh-Hant.xlf
@@ -130,10 +130,6 @@
<source>The type '{0}' has no constructors defined</source>
<target state="needs-review-translation" state-qualifier="tm-suggestion">型別 '{0}' 沒有已定義的建構函式</target>
</trans-unit>
- <trans-unit id="BadDelegateConstructor" translate="yes" xml:space="preserve">
- <source>The delegate '{0}' does not have a valid constructor</source>
- <target state="needs-review-translation" state-qualifier="tm-suggestion">委派 '{0}' 沒有有效的建構函式</target>
- </trans-unit>
<trans-unit id="PropertyLacksGet" translate="yes" xml:space="preserve">
<source>The property or indexer '{0}' cannot be used in this context because it lacks the get accessor</source>
<target state="needs-review-translation" state-qualifier="tm-suggestion">無法於此內容中使用屬性或索引子 '{0}',因為其欠缺 get 存取子</target>
@@ -202,10 +198,6 @@
<source>Using the generic {1} '{0}' requires '{2}' type arguments</source>
<target state="needs-review-translation" state-qualifier="tm-suggestion">使用泛型 {1} '{0}' 需要 '{2}' 個型別引數</target>
</trans-unit>
- <trans-unit id="BadTypeArgument" translate="yes" xml:space="preserve">
- <source>The type '{0}' may not be used as a type argument</source>
- <target state="needs-review-translation" state-qualifier="mt-suggestion">類型"{0}"不可能用作類型參數</target>
- </trans-unit>
<trans-unit id="TypeArgsNotAllowed" translate="yes" xml:space="preserve">
<source>The {1} '{0}' cannot be used with type arguments</source>
<target state="needs-review-translation" state-qualifier="tm-suggestion">{1} '{0}' 不能配合型別引數使用</target>
@@ -238,18 +230,10 @@
<source>Cannot convert null to type parameter '{0}' because it could be a non-nullable value type. Consider using 'default({0})' instead.</source>
<target state="needs-review-translation" state-qualifier="tm-suggestion">無法將 null 轉換成型別參數 '{0}',因為它是不可為 null 的實值型別。請考慮使用 'default({0})' 代替。</target>
</trans-unit>
- <trans-unit id="BadRetType" translate="yes" xml:space="preserve">
- <source>'{1} {0}' has the wrong return type</source>
- <target state="needs-review-translation" state-qualifier="tm-suggestion">'{1} {0}' 的傳回型別錯誤</target>
- </trans-unit>
<trans-unit id="CantInferMethTypeArgs" translate="yes" xml:space="preserve">
<source>The type arguments for method '{0}' cannot be inferred from the usage. Try specifying the type arguments explicitly.</source>
<target state="needs-review-translation" state-qualifier="tm-suggestion">方法 '{0}' 的型別引數不能從使用方式推斷。請嘗試明確指定型別引數。</target>
</trans-unit>
- <trans-unit id="MethGrpToNonDel" translate="yes" xml:space="preserve">
- <source>Cannot convert method group '{0}' to non-delegate type '{1}'. Did you intend to invoke the method?</source>
- <target state="needs-review-translation" state-qualifier="tm-suggestion">無法將方法群組 '{0}' 轉換為非委派型別 '{1}'。您是否想要叫用這個方法?</target>
- </trans-unit>
<trans-unit id="RefConstraintNotSatisfied" translate="yes" xml:space="preserve">
<source>The type '{2}' must be a reference type in order to use it as parameter '{1}' in the generic type or method '{0}'</source>
<target state="needs-review-translation" state-qualifier="tm-suggestion">型別 '{2}' 必須是參考型別,才能在泛型型別或方法 '{0}' 中做為參數 '{1}' 使用</target>
@@ -274,10 +258,6 @@
<source>Cannot convert to static type '{0}'</source>
<target state="needs-review-translation" state-qualifier="tm-suggestion">無法轉換為靜態型別 '{0}'</target>
</trans-unit>
- <trans-unit id="GenericArgIsStaticClass" translate="yes" xml:space="preserve">
- <source>'{0}': static types cannot be used as type arguments</source>
- <target state="needs-review-translation" state-qualifier="tm-suggestion">'{0}': 靜態型別不能當做型別引數使用</target>
- </trans-unit>
<trans-unit id="IncrementLvalueExpected" translate="yes" xml:space="preserve">
<source>The operand of an increment or decrement operator must be a variable, property or indexer</source>
<target state="needs-review-translation" state-qualifier="tm-suggestion">遞增或遞減運算子的運算元必須是變數、屬性或索引子。</target>
@@ -350,10 +330,6 @@
<source>Cannot pass '{0}' as a ref or out argument because it is a '{1}'</source>
<target state="needs-review-translation" state-qualifier="tm-suggestion">無法將 '{0}' 當做 ref 或 out 引數傳遞,因為它是 '{1}'</target>
</trans-unit>
- <trans-unit id="DelegateOnNullable" translate="yes" xml:space="preserve">
- <source>Cannot bind delegate to '{0}' because it is a member of 'System.Nullable<it id="1" pos="open">&lt;T&gt;</it>'</source>
- <target state="needs-review-translation" state-qualifier="mt-suggestion">不能將委託綁定到 '{0}',因為它是 'System.Nullable<it id="1" pos="open">&lt;T&gt;</it>' 成員</target>
- </trans-unit>
<trans-unit id="BadCtorArgCount" translate="yes" xml:space="preserve">
<source>'{0}' does not contain a constructor that takes '{1}' arguments</source>
<target state="needs-review-translation" state-qualifier="tm-suggestion">'{0}' 不包含接受 '{1}' 個引數的建構函式</target>
diff --git a/src/Microsoft.CSharp/src/Resources/Strings.de.resx b/src/Microsoft.CSharp/src/Resources/Strings.de.resx
index 455e6dc9e0..aa1cee3c65 100644
--- a/src/Microsoft.CSharp/src/Resources/Strings.de.resx
+++ b/src/Microsoft.CSharp/src/Resources/Strings.de.resx
@@ -105,9 +105,6 @@
<data name="NoConstructors" xml:space="preserve">
<value>Für den {0}-Typ sind keine Konstruktoren definiert.</value>
</data>
- <data name="BadDelegateConstructor" xml:space="preserve">
- <value>Der Delegat "{0}" enthält keinen gültigen Konstruktor.</value>
- </data>
<data name="PropertyLacksGet" xml:space="preserve">
<value>Die Eigenschaft oder der Indexer "{0}" kann in diesem Kontext nicht verwendet werden, weil der get-Accessor fehlt.</value>
</data>
@@ -159,9 +156,6 @@
<data name="BadArity" xml:space="preserve">
<value>Die Verwendung von {1} "{0}" (generisch) erfordert {2}-Typargumente.</value>
</data>
- <data name="BadTypeArgument" xml:space="preserve">
- <value>Der Typ "{0}" darf nicht als Typargument verwendet werden.</value>
- </data>
<data name="TypeArgsNotAllowed" xml:space="preserve">
<value>{1} "{0}" kann nicht mit Typargumenten verwendet werden.</value>
</data>
@@ -186,15 +180,9 @@
<data name="TypeVarCantBeNull" xml:space="preserve">
<value>NULL kann nicht in den {0}-Typparameter konvertiert werden, da dieser Werttyp möglicherweise nicht auf NULL festgelegt werden kann. Verwenden Sie stattdessen ggf. default({0}).</value>
</data>
- <data name="BadRetType" xml:space="preserve">
- <value>Der Rückgabetyp von {1} {0} ist falsch.</value>
- </data>
<data name="CantInferMethTypeArgs" xml:space="preserve">
<value>Die Typargumente der {0}-Methode können nicht per Rückschluss aus der Syntax abgeleitet werden. Geben Sie die Typargumente explizit an.</value>
</data>
- <data name="MethGrpToNonDel" xml:space="preserve">
- <value>Die {0}-Methodengruppe kann nicht in den Nichtdelegattyp "{1}" konvertiert werden. Wollten Sie die Methode aufrufen?</value>
- </data>
<data name="RefConstraintNotSatisfied" xml:space="preserve">
<value>Der {2}-Typ muss ein Referenztyp sein, damit er als {1}-Parameter im generischen Typ oder in der generischen {0}-Methode verwendet werden kann.</value>
</data>
@@ -213,9 +201,6 @@
<data name="ConvertToStaticClass" xml:space="preserve">
<value>Die Konvertierung in den statischen {0}-Typ ist nicht möglich.</value>
</data>
- <data name="GenericArgIsStaticClass" xml:space="preserve">
- <value>{0}: Statische Typen können nicht als Typargumente verwendet werden.</value>
- </data>
<data name="IncrementLvalueExpected" xml:space="preserve">
<value>Der Operand eines Inkrement- oder Dekrementoperators muss eine Variable, eine Eigenschaft oder ein Indexer sein.</value>
</data>
@@ -270,9 +255,6 @@
<data name="RefReadonlyLocalCause" xml:space="preserve">
<value>{0} ist ein(e) {1} und kann daher nicht als ref- oder out-Argument übergeben werden.</value>
</data>
- <data name="DelegateOnNullable" xml:space="preserve">
- <value>Kann Delegaten "{0}" keine Bindung an weil es ein Mitglied von "System.Nullable&lt;T&gt;ist"</value>
- </data>
<data name="BadCtorArgCount" xml:space="preserve">
<value>"{0}" enthält keinen Konstruktor, der {1}-Argumente akzeptiert.</value>
</data>
diff --git a/src/Microsoft.CSharp/src/Resources/Strings.es.resx b/src/Microsoft.CSharp/src/Resources/Strings.es.resx
index 4a53389201..f79029e3dc 100644
--- a/src/Microsoft.CSharp/src/Resources/Strings.es.resx
+++ b/src/Microsoft.CSharp/src/Resources/Strings.es.resx
@@ -105,9 +105,6 @@
<data name="NoConstructors" xml:space="preserve">
<value>El tipo '{0}' no tiene constructores definidos.</value>
</data>
- <data name="BadDelegateConstructor" xml:space="preserve">
- <value>El delegado '{0}' no tiene un constructor válido</value>
- </data>
<data name="PropertyLacksGet" xml:space="preserve">
<value>La propiedad o el indizador '{0}' no se puede usar en este contexto porque carece del descriptor de acceso get.</value>
</data>
@@ -159,9 +156,6 @@
<data name="BadArity" xml:space="preserve">
<value>Uso de {1} de tipo genérico ('{0}'): requiere '{2}' argumentos de tipo</value>
</data>
- <data name="BadTypeArgument" xml:space="preserve">
- <value>El tipo '{0}' no se puede usar como argumento de tipo</value>
- </data>
<data name="TypeArgsNotAllowed" xml:space="preserve">
<value>{1} '{0}' no se puede usar con argumentos de tipo.</value>
</data>
@@ -186,15 +180,9 @@
<data name="TypeVarCantBeNull" xml:space="preserve">
<value>No se puede convertir NULL en el parámetro de tipo '{0}' porque podría ser un tipo de valor que no acepta valores NULL. Use 'default({0})' en su lugar.</value>
</data>
- <data name="BadRetType" xml:space="preserve">
- <value>'{1} {0}' es un tipo de valor devuelto equivocado</value>
- </data>
<data name="CantInferMethTypeArgs" xml:space="preserve">
<value>Los argumentos de tipo para el método '{0}' no se pueden inferir a partir del uso. Intente especificar los argumentos de tipo explícitamente.</value>
</data>
- <data name="MethGrpToNonDel" xml:space="preserve">
- <value>No se puede convertir el grupo de métodos '{0}' en tipo no delegado '{1}'. ¿Intentó invocar el método?</value>
- </data>
<data name="RefConstraintNotSatisfied" xml:space="preserve">
<value>El tipo '{2}' debe ser un tipo de referencia para poder usarlo como parámetro '{1}' en el tipo o método genérico '{0}'.</value>
</data>
@@ -213,9 +201,6 @@
<data name="ConvertToStaticClass" xml:space="preserve">
<value>No se puede convertir en el tipo estático '{0}'</value>
</data>
- <data name="GenericArgIsStaticClass" xml:space="preserve">
- <value>'{0}': los tipos estáticos no se pueden usar como argumentos de tipo</value>
- </data>
<data name="IncrementLvalueExpected" xml:space="preserve">
<value>El operando de un operador de incremento o decremento debe ser una variable, una propiedad o un indizador</value>
</data>
@@ -270,9 +255,6 @@
<data name="RefReadonlyLocalCause" xml:space="preserve">
<value>No se puede pasar '{0}' como argumento out o ref porque es '{1}'.</value>
</data>
- <data name="DelegateOnNullable" xml:space="preserve">
- <value>No se puede enlazar el delegado para '{0}' porque es un miembro de 'System.Nullable&lt;T&gt;'</value>
- </data>
<data name="BadCtorArgCount" xml:space="preserve">
<value>'{0}' no contiene un constructor que tome '{1}' argumentos</value>
</data>
diff --git a/src/Microsoft.CSharp/src/Resources/Strings.fr.resx b/src/Microsoft.CSharp/src/Resources/Strings.fr.resx
index e777cb7763..730b032d7e 100644
--- a/src/Microsoft.CSharp/src/Resources/Strings.fr.resx
+++ b/src/Microsoft.CSharp/src/Resources/Strings.fr.resx
@@ -105,9 +105,6 @@
<data name="NoConstructors" xml:space="preserve">
<value>Aucun constructeur n'est défini pour le type '{0}'</value>
</data>
- <data name="BadDelegateConstructor" xml:space="preserve">
- <value>Le délégué '{0}' n'a pas de constructeur valide</value>
- </data>
<data name="PropertyLacksGet" xml:space="preserve">
<value>Impossible d'utiliser la propriété ou l'indexeur '{0}' dans ce contexte, car il lui manque l'accesseur get</value>
</data>
@@ -159,9 +156,6 @@
<data name="BadArity" xml:space="preserve">
<value>L'utilisation du {1} '{0}' générique requiert les arguments de type '{2}'</value>
</data>
- <data name="BadTypeArgument" xml:space="preserve">
- <value>Le type '{0}' ne peut pas être utilisé comme argument de type</value>
- </data>
<data name="TypeArgsNotAllowed" xml:space="preserve">
<value>Impossible d'utiliser le {1} '{0}' avec des arguments de type</value>
</data>
@@ -186,15 +180,9 @@
<data name="TypeVarCantBeNull" xml:space="preserve">
<value>Impossible de convertir null en paramètre de type '{0}' car il peut s'agir d'un type valeur qui n'autorise pas les valeurs null. Utilisez 'default({0})' à la place.</value>
</data>
- <data name="BadRetType" xml:space="preserve">
- <value>'{1} {0}' n'a pas le type de retour correct</value>
- </data>
<data name="CantInferMethTypeArgs" xml:space="preserve">
<value>Impossible de déduire les arguments de type pour la méthode '{0}' à partir de l'utilisation. Essayez de spécifier les arguments de type de façon explicite.</value>
</data>
- <data name="MethGrpToNonDel" xml:space="preserve">
- <value>Impossible de convertir le groupe de méthodes '{0}' en type non-délégué '{1}'. Souhaitiez-vous appeler la méthode ?</value>
- </data>
<data name="RefConstraintNotSatisfied" xml:space="preserve">
<value>Le type '{2}' doit être un type référence afin d'être utilisé comme paramètre '{1}' dans le type ou la méthode générique '{0}'</value>
</data>
@@ -213,9 +201,6 @@
<data name="ConvertToStaticClass" xml:space="preserve">
<value>Impossible de convertir en type static '{0}'</value>
</data>
- <data name="GenericArgIsStaticClass" xml:space="preserve">
- <value>'{0}' : impossible d'utiliser les types static en tant qu'arguments de type</value>
- </data>
<data name="IncrementLvalueExpected" xml:space="preserve">
<value>L'opérande d'un opérateur d'incrémentation ou de décrémentation doit être une variable, une propriété ou un indexeur</value>
</data>
@@ -270,9 +255,6 @@
<data name="RefReadonlyLocalCause" xml:space="preserve">
<value>Impossible de passer '{0}' en tant qu'argument ref ou out, car il s'agit d'un '{1}'</value>
</data>
- <data name="DelegateOnNullable" xml:space="preserve">
- <value>Impossible de lier délégué à « {0} » parce que c'est un membre de « System.Nullable&lt;T&gt;»</value>
- </data>
<data name="BadCtorArgCount" xml:space="preserve">
<value>'{0}' ne contient pas de constructeur qui accepte des arguments '{1}'</value>
</data>
diff --git a/src/Microsoft.CSharp/src/Resources/Strings.it.resx b/src/Microsoft.CSharp/src/Resources/Strings.it.resx
index a0d7cf2b0d..aa73c7837c 100644
--- a/src/Microsoft.CSharp/src/Resources/Strings.it.resx
+++ b/src/Microsoft.CSharp/src/Resources/Strings.it.resx
@@ -105,9 +105,6 @@
<data name="NoConstructors" xml:space="preserve">
<value>Per il tipo '{0}' non sono definiti costruttori</value>
</data>
- <data name="BadDelegateConstructor" xml:space="preserve">
- <value>Il delegato '{0}' non presenta un costruttore valido</value>
- </data>
<data name="PropertyLacksGet" xml:space="preserve">
<value>Impossibile utilizzare la proprietà o l'indicizzatore '{0}' in questo contesto perché manca la funzione di accesso get.</value>
</data>
@@ -159,9 +156,6 @@
<data name="BadArity" xml:space="preserve">
<value>L'utilizzo del {1} generico '{0}' richiede argomenti di tipo '{2}'</value>
</data>
- <data name="BadTypeArgument" xml:space="preserve">
- <value>Il tipo '{0}' non può essere utilizzato come argomento di tipo</value>
- </data>
<data name="TypeArgsNotAllowed" xml:space="preserve">
<value>Impossibile utilizzare {1} '{0}' insieme ad argomenti di tipo</value>
</data>
@@ -186,15 +180,9 @@
<data name="TypeVarCantBeNull" xml:space="preserve">
<value>Impossibile convertire il valore Null nel parametro di tipo '{0}' perché potrebbe essere un tipo di valore non nullable. Si consiglia di utilizzare 'default({0})'.</value>
</data>
- <data name="BadRetType" xml:space="preserve">
- <value>Il tipo restituito di '{1} {0}' è errato</value>
- </data>
<data name="CantInferMethTypeArgs" xml:space="preserve">
<value>Impossibile dedurre gli argomenti di tipo per il metodo '{0}' dall'utilizzo. Provare a specificare gli argomenti di tipo in modo esplicito.</value>
</data>
- <data name="MethGrpToNonDel" xml:space="preserve">
- <value>Impossibile convertire il gruppo di metodi '{0}' nel tipo non delegato '{1}'. Si desiderava richiamare il metodo?</value>
- </data>
<data name="RefConstraintNotSatisfied" xml:space="preserve">
<value>È necessario che il tipo '{2}' sia un tipo di riferimento per essere utilizzato come parametro '{1}' nel tipo generico o nel metodo '{0}'</value>
</data>
@@ -213,9 +201,6 @@
<data name="ConvertToStaticClass" xml:space="preserve">
<value>Impossibile convertire nel tipo statico '{0}'</value>
</data>
- <data name="GenericArgIsStaticClass" xml:space="preserve">
- <value>'{0}': i tipi statici non possono essere utilizzati come argomenti di tipi</value>
- </data>
<data name="IncrementLvalueExpected" xml:space="preserve">
<value>L'operando di un operatore di incremento o decremento deve essere una variabile, una proprietà o un indicizzatore</value>
</data>
@@ -270,9 +255,6 @@
<data name="RefReadonlyLocalCause" xml:space="preserve">
<value>Impossibile passare '{0}' come argomento ref o out perché è '{1}'</value>
</data>
- <data name="DelegateOnNullable" xml:space="preserve">
- <value>Non è possibile associare il delegato a '{0}' perché è un membro di 'System. Nullable&lt;T&gt;'</value>
- </data>
<data name="BadCtorArgCount" xml:space="preserve">
<value>'{0}' non contiene un costruttore che accetta argomenti '{1}'</value>
</data>
diff --git a/src/Microsoft.CSharp/src/Resources/Strings.ja.resx b/src/Microsoft.CSharp/src/Resources/Strings.ja.resx
index 7ec1e3b51a..7783f1963d 100644
--- a/src/Microsoft.CSharp/src/Resources/Strings.ja.resx
+++ b/src/Microsoft.CSharp/src/Resources/Strings.ja.resx
@@ -105,9 +105,6 @@
<data name="NoConstructors" xml:space="preserve">
<value>型 '{0}' のコンストラクターが定義されていません</value>
</data>
- <data name="BadDelegateConstructor" xml:space="preserve">
- <value>デリゲート '{0}' には有効なコンストラクターがありません</value>
- </data>
<data name="PropertyLacksGet" xml:space="preserve">
<value>get アクセサーがないため、プロパティまたはインデクサー '{0}' をこのコンテキストで使用することはできません</value>
</data>
@@ -159,9 +156,6 @@
<data name="BadArity" xml:space="preserve">
<value>ジェネリック {1} '{0}' の使用には、'{2}' 型の引数が必要です</value>
</data>
- <data name="BadTypeArgument" xml:space="preserve">
- <value>型 '{0}' は型引数としては使えません</value>
- </data>
<data name="TypeArgsNotAllowed" xml:space="preserve">
<value>{1} '{0}' は型引数と一緒には使用できません</value>
</data>
@@ -186,15 +180,9 @@
<data name="TypeVarCantBeNull" xml:space="preserve">
<value>Null 非許容の値型である可能性があるため、Null を型パラメーター '{0}' に変換できません。'default({0})' を使用してください。</value>
</data>
- <data name="BadRetType" xml:space="preserve">
- <value>'{1} {0}' には、不適切な戻り値の型が指定されています</value>
- </data>
<data name="CantInferMethTypeArgs" xml:space="preserve">
<value>メソッド '{0}' の型引数を使い方から推論することはできません。型引数を明示的に指定してください。</value>
</data>
- <data name="MethGrpToNonDel" xml:space="preserve">
- <value>メソッド グループ '{0}' を非デリゲート型 '{1}' に変換することはできません。このメソッドを呼び出しますか?</value>
- </data>
<data name="RefConstraintNotSatisfied" xml:space="preserve">
<value>型 '{2}' は、ジェネリック型のパラメーター '{1}'、またはメソッド '{0}' として使用するために、参照型でなければなりません</value>
</data>
@@ -213,9 +201,6 @@
<data name="ConvertToStaticClass" xml:space="preserve">
<value>スタティック型 '{0}' へ変換できません</value>
</data>
- <data name="GenericArgIsStaticClass" xml:space="preserve">
- <value>'{0}': スタティック型を型引数として使用することはできません</value>
- </data>
<data name="IncrementLvalueExpected" xml:space="preserve">
<value>インクリメント演算子またはデクリメント演算子のオペランドには、変数、プロパティ、またはインデクサーを指定してください。</value>
</data>
@@ -270,9 +255,6 @@
<data name="RefReadonlyLocalCause" xml:space="preserve">
<value>'{1}' であるため、'{0}' は ref または out 引数として渡せません</value>
</data>
- <data name="DelegateOnNullable" xml:space="preserve">
- <value>'System.Nullable&lt;T&gt;' のメンバーであるために、'{0}' のデリゲートをバインドできません。</value>
- </data>
<data name="BadCtorArgCount" xml:space="preserve">
<value>'{0}' に、引数を '{1}' 個指定できるコンストラクターがありません</value>
</data>
diff --git a/src/Microsoft.CSharp/src/Resources/Strings.ko.resx b/src/Microsoft.CSharp/src/Resources/Strings.ko.resx
index fa9a948032..1c42c74f98 100644
--- a/src/Microsoft.CSharp/src/Resources/Strings.ko.resx
+++ b/src/Microsoft.CSharp/src/Resources/Strings.ko.resx
@@ -105,9 +105,6 @@
<data name="NoConstructors" xml:space="preserve">
<value>'{0}' 형식에 정의된 생성자가 없습니다.</value>
</data>
- <data name="BadDelegateConstructor" xml:space="preserve">
- <value>'{0}' 대리자에 올바른 생성자가 없습니다.</value>
- </data>
<data name="PropertyLacksGet" xml:space="preserve">
<value>'{0}' 속성 또는 인덱서는 get 접근자가 없으므로 이 컨텍스트에서 사용할 수 없습니다.</value>
</data>
@@ -159,9 +156,6 @@
<data name="BadArity" xml:space="preserve">
<value>제네릭 {1} '{0}'을(를) 사용하려면 '{2}' 형식 인수가 필요합니다.</value>
</data>
- <data name="BadTypeArgument" xml:space="preserve">
- <value>'{0}' 형식은 형식 인수로 사용할 수 없습니다.</value>
- </data>
<data name="TypeArgsNotAllowed" xml:space="preserve">
<value>{1} '{0}'은(는) 형식 인수와 함께 사용할 수 없습니다.</value>
</data>
@@ -186,15 +180,9 @@
<data name="TypeVarCantBeNull" xml:space="preserve">
<value>null을 허용하지 않는 값 형식일 수 있으므로 null을 형식 매개 변수 '{0}'(으)로 변환할 수 없습니다. 대신 'default({0})'를 사용하십시오.</value>
</data>
- <data name="BadRetType" xml:space="preserve">
- <value>'{1} {0}'에 잘못된 반환 형식이 있습니다.</value>
- </data>
<data name="CantInferMethTypeArgs" xml:space="preserve">
<value>'{0}' 메서드의 형식 인수를 유추할 수 없습니다. 형식 인수를 명시적으로 지정하십시오.</value>
</data>
- <data name="MethGrpToNonDel" xml:space="preserve">
- <value>'{0}' 메서드 그룹을 비대리자 형식 '{1}'(으)로 변환할 수 없습니다. 메서드를 호출하시겠습니까?</value>
- </data>
<data name="RefConstraintNotSatisfied" xml:space="preserve">
<value>제네릭 형식 또는 메서드 '{0}'에서 '{2}' 형식을 '{1}' 매개 변수로 사용하려면 해당 형식이 참조 형식이어야 합니다.</value>
</data>
@@ -213,9 +201,6 @@
<data name="ConvertToStaticClass" xml:space="preserve">
<value>'{0}' 정적 형식으로 변환할 수 없습니다.</value>
</data>
- <data name="GenericArgIsStaticClass" xml:space="preserve">
- <value>'{0}': 정적 형식은 형식 인수로 사용할 수 없습니다.</value>
- </data>
<data name="IncrementLvalueExpected" xml:space="preserve">
<value>증가 연산자 또는 감소 연산자의 피연산자는 변수, 속성 또는 인덱서여야 합니다.</value>
</data>
@@ -270,9 +255,6 @@
<data name="RefReadonlyLocalCause" xml:space="preserve">
<value>'{0}'은(는) '{1}'이므로 ref 또는 out 인수로 전달할 수 없습니다.</value>
</data>
- <data name="DelegateOnNullable" xml:space="preserve">
- <value>그것 'System.Nullable&lt;T&gt;'의 멤버 이므로 ' (0) '에 대리자를 바인딩할 수 없습니다.</value>
- </data>
<data name="BadCtorArgCount" xml:space="preserve">
<value>'{0}'에 '{1}'개의 인수를 사용하는 생성자가 없습니다.</value>
</data>
diff --git a/src/Microsoft.CSharp/src/Resources/Strings.resx b/src/Microsoft.CSharp/src/Resources/Strings.resx
index 3dee1c7f7d..5ad03c794e 100644
--- a/src/Microsoft.CSharp/src/Resources/Strings.resx
+++ b/src/Microsoft.CSharp/src/Resources/Strings.resx
@@ -151,9 +151,6 @@
<data name="NoConstructors" xml:space="preserve">
<value>The type '{0}' has no constructors defined</value>
</data>
- <data name="BadDelegateConstructor" xml:space="preserve">
- <value>The delegate '{0}' does not have a valid constructor</value>
- </data>
<data name="PropertyLacksGet" xml:space="preserve">
<value>The property or indexer '{0}' cannot be used in this context because it lacks the get accessor</value>
</data>
@@ -205,9 +202,6 @@
<data name="BadArity" xml:space="preserve">
<value>Using the generic {1} '{0}' requires '{2}' type arguments</value>
</data>
- <data name="BadTypeArgument" xml:space="preserve">
- <value>The type '{0}' may not be used as a type argument</value>
- </data>
<data name="TypeArgsNotAllowed" xml:space="preserve">
<value>The {1} '{0}' cannot be used with type arguments</value>
</data>
@@ -232,15 +226,9 @@
<data name="TypeVarCantBeNull" xml:space="preserve">
<value>Cannot convert null to type parameter '{0}' because it could be a non-nullable value type. Consider using 'default({0})' instead.</value>
</data>
- <data name="BadRetType" xml:space="preserve">
- <value>'{1} {0}' has the wrong return type</value>
- </data>
<data name="CantInferMethTypeArgs" xml:space="preserve">
<value>The type arguments for method '{0}' cannot be inferred from the usage. Try specifying the type arguments explicitly.</value>
</data>
- <data name="MethGrpToNonDel" xml:space="preserve">
- <value>Cannot convert method group '{0}' to non-delegate type '{1}'. Did you intend to invoke the method?</value>
- </data>
<data name="RefConstraintNotSatisfied" xml:space="preserve">
<value>The type '{2}' must be a reference type in order to use it as parameter '{1}' in the generic type or method '{0}'</value>
</data>
@@ -259,9 +247,6 @@
<data name="ConvertToStaticClass" xml:space="preserve">
<value>Cannot convert to static type '{0}'</value>
</data>
- <data name="GenericArgIsStaticClass" xml:space="preserve">
- <value>'{0}': static types cannot be used as type arguments</value>
- </data>
<data name="IncrementLvalueExpected" xml:space="preserve">
<value>The operand of an increment or decrement operator must be a variable, property or indexer</value>
</data>
@@ -316,9 +301,6 @@
<data name="RefReadonlyLocalCause" xml:space="preserve">
<value>Cannot pass '{0}' as a ref or out argument because it is a '{1}'</value>
</data>
- <data name="DelegateOnNullable" xml:space="preserve">
- <value>Cannot bind delegate to '{0}' because it is a member of 'System.Nullable&lt;T&gt;'</value>
- </data>
<data name="BadCtorArgCount" xml:space="preserve">
<value>'{0}' does not contain a constructor that takes '{1}' arguments</value>
</data>
diff --git a/src/Microsoft.CSharp/src/Resources/Strings.ru.resx b/src/Microsoft.CSharp/src/Resources/Strings.ru.resx
index 05c39d2376..8a2e9bba1d 100644
--- a/src/Microsoft.CSharp/src/Resources/Strings.ru.resx
+++ b/src/Microsoft.CSharp/src/Resources/Strings.ru.resx
@@ -105,9 +105,6 @@
<data name="NoConstructors" xml:space="preserve">
<value>Для типа "{0}" нет определенных конструкторов</value>
</data>
- <data name="BadDelegateConstructor" xml:space="preserve">
- <value>Делегат "{0}" не имеет допустимого конструктора</value>
- </data>
<data name="PropertyLacksGet" xml:space="preserve">
<value>The property or indexer "{0}" cannot be used in this context because it lacks the get accessor</value>
</data>
@@ -159,9 +156,6 @@
<data name="BadArity" xml:space="preserve">
<value>Использование универсального {1} "{0}" требует аргументов типа "{2}"</value>
</data>
- <data name="BadTypeArgument" xml:space="preserve">
- <value>Тип '{0}' не может использоваться в качестве аргумента типа</value>
- </data>
<data name="TypeArgsNotAllowed" xml:space="preserve">
<value>{1} "{0}" не может использоваться с аргументами типа</value>
</data>
@@ -186,15 +180,9 @@
<data name="TypeVarCantBeNull" xml:space="preserve">
<value>Cannot convert null to type parameter "{0}" because it could be a non-nullable value type. Вместо этого рекомендуется использовать "default({0})".</value>
</data>
- <data name="BadRetType" xml:space="preserve">
- <value>"{1} {0}" имеет неправильный возвращаемый тип</value>
- </data>
<data name="CantInferMethTypeArgs" xml:space="preserve">
<value>The type arguments for method "{0}" cannot be inferred from the usage. Попытайтесь явно определить аргументы-типы.</value>
</data>
- <data name="MethGrpToNonDel" xml:space="preserve">
- <value>Не удается преобразовать группу методов "{0}" в тип, не являющийся делегатом "{1}". Предполагается ли вызывать этот метод?</value>
- </data>
<data name="RefConstraintNotSatisfied" xml:space="preserve">
<value>Для использования в качестве параметра "{1}" в универсальном типе или методе "{0}" тип "{2}" должен быть ссылочным типом</value>
</data>
@@ -213,9 +201,6 @@
<data name="ConvertToStaticClass" xml:space="preserve">
<value>Не удается выполнить преобразование к статическому типу "{0}"</value>
</data>
- <data name="GenericArgIsStaticClass" xml:space="preserve">
- <value>"{0}": нельзя использовать статические типы в качестве аргументов-типов</value>
- </data>
<data name="IncrementLvalueExpected" xml:space="preserve">
<value>Операндом оператора инкремента или декремента должна быть переменная, свойство или индексатор</value>
</data>
@@ -270,9 +255,6 @@
<data name="RefReadonlyLocalCause" xml:space="preserve">
<value>Не удалось передать "{0}" как ссылку или аргумент out, так как это "{1}"</value>
</data>
- <data name="DelegateOnNullable" xml:space="preserve">
- <value>Не удается привязать делегат '{0}', потому что он является членом «System.Nullable&lt;T&gt;»</value>
- </data>
<data name="BadCtorArgCount" xml:space="preserve">
<value>"{0}" не содержит конструктор, принимающий аргументов: {1}</value>
</data>
diff --git a/src/Microsoft.CSharp/src/Resources/Strings.zh-Hans.resx b/src/Microsoft.CSharp/src/Resources/Strings.zh-Hans.resx
index 40ecdc190f..0787825ccd 100644
--- a/src/Microsoft.CSharp/src/Resources/Strings.zh-Hans.resx
+++ b/src/Microsoft.CSharp/src/Resources/Strings.zh-Hans.resx
@@ -105,9 +105,6 @@
<data name="NoConstructors" xml:space="preserve">
<value>类型“{0}”未定义构造函数</value>
</data>
- <data name="BadDelegateConstructor" xml:space="preserve">
- <value>委托“{0}”没有有效的构造函数</value>
- </data>
<data name="PropertyLacksGet" xml:space="preserve">
<value>属性或索引器“{0}”不能用在此上下文中,因为它缺少 get 访问器</value>
</data>
@@ -159,9 +156,6 @@
<data name="BadArity" xml:space="preserve">
<value>使用泛型 {1}“{0}”需要“{2}”个类型参数</value>
</data>
- <data name="BadTypeArgument" xml:space="preserve">
- <value>类型"{0}"不可能用作类型参数</value>
- </data>
<data name="TypeArgsNotAllowed" xml:space="preserve">
<value>{1}“{0}”不能与类型参数一起使用</value>
</data>
@@ -186,15 +180,9 @@
<data name="TypeVarCantBeNull" xml:space="preserve">
<value>无法将 null 转换为类型参数“{0}”,因为它可能是不可以为 null 的值类型。请考虑改用“default({0})”。</value>
</data>
- <data name="BadRetType" xml:space="preserve">
- <value>“{1} {0}”的返回类型错误</value>
- </data>
<data name="CantInferMethTypeArgs" xml:space="preserve">
<value>无法从用法中推断出方法“{0}”的类型参数。请尝试显式指定类型参数。</value>
</data>
- <data name="MethGrpToNonDel" xml:space="preserve">
- <value>无法将方法组“{0}”转换为非委托类型“{1}”。是否希望调用此方法?</value>
- </data>
<data name="RefConstraintNotSatisfied" xml:space="preserve">
<value>类型“{2}”必须是引用类型才能用作泛型类型或方法“{0}”中的参数“{1}”</value>
</data>
@@ -213,9 +201,6 @@
<data name="ConvertToStaticClass" xml:space="preserve">
<value>无法转换为静态类型“{0}”</value>
</data>
- <data name="GenericArgIsStaticClass" xml:space="preserve">
- <value>“{0}”: 静态类型不能用作类型参数</value>
- </data>
<data name="IncrementLvalueExpected" xml:space="preserve">
<value>递增或递减运算符的操作数必须是变量、属性或索引器</value>
</data>
@@ -270,9 +255,6 @@
<data name="RefReadonlyLocalCause" xml:space="preserve">
<value>“{0}”是一个“{1}”,无法作为 ref 或 out 参数进行传递</value>
</data>
- <data name="DelegateOnNullable" xml:space="preserve">
- <value>不能将委托绑定到 '{0}',因为它是 'System.Nullable&lt;T&gt;' 成员</value>
- </data>
<data name="BadCtorArgCount" xml:space="preserve">
<value>“{0}”不包含采用“{1}”个参数的构造函数</value>
</data>
diff --git a/src/Microsoft.CSharp/src/Resources/Strings.zh-Hant.resx b/src/Microsoft.CSharp/src/Resources/Strings.zh-Hant.resx
index 08c64355c4..ab73e5bf2f 100644
--- a/src/Microsoft.CSharp/src/Resources/Strings.zh-Hant.resx
+++ b/src/Microsoft.CSharp/src/Resources/Strings.zh-Hant.resx
@@ -105,9 +105,6 @@
<data name="NoConstructors" xml:space="preserve">
<value>型別 '{0}' 沒有已定義的建構函式</value>
</data>
- <data name="BadDelegateConstructor" xml:space="preserve">
- <value>委派 '{0}' 沒有有效的建構函式</value>
- </data>
<data name="PropertyLacksGet" xml:space="preserve">
<value>無法於此內容中使用屬性或索引子 '{0}',因為其欠缺 get 存取子</value>
</data>
@@ -159,9 +156,6 @@
<data name="BadArity" xml:space="preserve">
<value>使用泛型 {1} '{0}' 需要 '{2}' 個型別引數</value>
</data>
- <data name="BadTypeArgument" xml:space="preserve">
- <value>類型"{0}"不可能用作類型參數</value>
- </data>
<data name="TypeArgsNotAllowed" xml:space="preserve">
<value>{1} '{0}' 不能配合型別引數使用</value>
</data>
@@ -186,15 +180,9 @@
<data name="TypeVarCantBeNull" xml:space="preserve">
<value>無法將 null 轉換成型別參數 '{0}',因為它是不可為 null 的實值型別。請考慮使用 'default({0})' 代替。</value>
</data>
- <data name="BadRetType" xml:space="preserve">
- <value>'{1} {0}' 的傳回型別錯誤</value>
- </data>
<data name="CantInferMethTypeArgs" xml:space="preserve">
<value>方法 '{0}' 的型別引數不能從使用方式推斷。請嘗試明確指定型別引數。</value>
</data>
- <data name="MethGrpToNonDel" xml:space="preserve">
- <value>無法將方法群組 '{0}' 轉換為非委派型別 '{1}'。您是否想要叫用這個方法?</value>
- </data>
<data name="RefConstraintNotSatisfied" xml:space="preserve">
<value>型別 '{2}' 必須是參考型別,才能在泛型型別或方法 '{0}' 中做為參數 '{1}' 使用</value>
</data>
@@ -213,9 +201,6 @@
<data name="ConvertToStaticClass" xml:space="preserve">
<value>無法轉換為靜態型別 '{0}'</value>
</data>
- <data name="GenericArgIsStaticClass" xml:space="preserve">
- <value>'{0}': 靜態型別不能當做型別引數使用</value>
- </data>
<data name="IncrementLvalueExpected" xml:space="preserve">
<value>遞增或遞減運算子的運算元必須是變數、屬性或索引子。</value>
</data>
@@ -270,9 +255,6 @@
<data name="RefReadonlyLocalCause" xml:space="preserve">
<value>無法將 '{0}' 當做 ref 或 out 引數傳遞,因為它是 '{1}'</value>
</data>
- <data name="DelegateOnNullable" xml:space="preserve">
- <value>不能將委託綁定到 '{0}',因為它是 'System.Nullable&lt;T&gt;' 成員</value>
- </data>
<data name="BadCtorArgCount" xml:space="preserve">
<value>'{0}' 不包含接受 '{1}' 個引數的建構函式</value>
</data>
diff --git a/src/Microsoft.XmlSerializer.Generator/dir.props b/src/Microsoft.XmlSerializer.Generator/dir.props
index 4c94be0e4d..b090298bf1 100644
--- a/src/Microsoft.XmlSerializer.Generator/dir.props
+++ b/src/Microsoft.XmlSerializer.Generator/dir.props
@@ -2,9 +2,11 @@
<Project ToolsVersion="14.0" DefaultTargets="Build" xmlns="http://schemas.microsoft.com/developer/msbuild/2003">
<Import Project="..\dir.props" />
<PropertyGroup>
+ <PreReleaseLabel>preview1</PreReleaseLabel>
<PackageVersion>1.0.0</PackageVersion>
<SkipValidatePackage>true</SkipValidatePackage>
<AssemblyVersion>1.0.0.0</AssemblyVersion>
+ <AssemblyFileVersion>$(AssemblyVersion)</AssemblyFileVersion>
<AssemblyKey>Open</AssemblyKey>
</PropertyGroup>
</Project>
diff --git a/src/Microsoft.XmlSerializer.Generator/pkg/GenerateNupkgProps.targets b/src/Microsoft.XmlSerializer.Generator/pkg/GenerateNupkgProps.targets
new file mode 100644
index 0000000000..ce4649910d
--- /dev/null
+++ b/src/Microsoft.XmlSerializer.Generator/pkg/GenerateNupkgProps.targets
@@ -0,0 +1,32 @@
+<?xml version="1.0" encoding="utf-8"?>
+<Project xmlns="http://schemas.microsoft.com/developer/msbuild/2003">
+ <PropertyGroup>
+ <BuildDependsOn>
+ GenerateNupkgProps;
+ $(BuildDependsOn)
+ </BuildDependsOn>
+ <PackageBuildPath>$(PackageOutputPath)build/</PackageBuildPath>
+ <PropsFilePath>$(PackageBuildPath)$(Id).props</PropsFilePath>
+ </PropertyGroup>
+ <ItemGroup>
+ <PackageFile Include="$(PropsFilePath)">
+ <TargetPath>build\</TargetPath>
+ </PackageFile>
+ </ItemGroup>
+ <Target Name="GenerateNupkgProps" DependsOnTargets="CalculatePackageVersion">
+ <PropertyGroup>
+ <PropsFileContents>
+&lt;Project DefaultTargets="Build" xmlns="http://schemas.microsoft.com/developer/msbuild/2003"&gt;
+ &lt;ItemGroup&gt;
+ &lt;DotNetCliToolReference Include="$(Id)" Version="$(PackageVersion)" /&gt;
+ &lt;/ItemGroup&gt;
+&lt;/Project&gt;
+ </PropsFileContents>
+ </PropertyGroup>
+ <MakeDir Directories="$(PackageBuildPath)"/>
+ <WriteLinesToFile
+ File="$(PropsFilePath)"
+ Lines="$(PropsFileContents)"
+ Overwrite="true" />
+ </Target>
+</Project> \ No newline at end of file
diff --git a/src/Microsoft.XmlSerializer.Generator/pkg/Microsoft.XmlSerializer.Generator.pkgproj b/src/Microsoft.XmlSerializer.Generator/pkg/Microsoft.XmlSerializer.Generator.pkgproj
index 763dd414d3..fe2f64b2e0 100644
--- a/src/Microsoft.XmlSerializer.Generator/pkg/Microsoft.XmlSerializer.Generator.pkgproj
+++ b/src/Microsoft.XmlSerializer.Generator/pkg/Microsoft.XmlSerializer.Generator.pkgproj
@@ -4,5 +4,18 @@
<ItemGroup>
<ProjectReference Include="..\src\Microsoft.XmlSerializer.Generator.csproj" />
</ItemGroup>
+ <PropertyGroup>
+ <SkipPackageFileCheck>true</SkipPackageFileCheck>
+ </PropertyGroup>
+ <ItemGroup>
+ <PackageFile Include=".\build\prefercliruntime"/>
+ <PackageFile Include=".\build\Microsoft.XmlSerializer.Generator.targets">
+ <TargetPath>build\</TargetPath>
+ </PackageFile>
+ <PackageFile Include=".\build\dotnet-Microsoft.XmlSerializer.Generator.runtimeconfig.json">
+ <TargetPath>\lib\netstandard2.0\</TargetPath>
+ </PackageFile>
+ </ItemGroup>
<Import Project="$([MSBuild]::GetDirectoryNameOfFileAbove($(MSBuildThisFileDirectory), dir.targets))\dir.targets" />
+ <Import Project=".\GenerateNupkgProps.targets" />
</Project> \ No newline at end of file
diff --git a/src/Microsoft.XmlSerializer.Generator/pkg/build/Microsoft.XmlSerializer.Generator.targets b/src/Microsoft.XmlSerializer.Generator/pkg/build/Microsoft.XmlSerializer.Generator.targets
new file mode 100644
index 0000000000..8ebc0d32c4
--- /dev/null
+++ b/src/Microsoft.XmlSerializer.Generator/pkg/build/Microsoft.XmlSerializer.Generator.targets
@@ -0,0 +1,27 @@
+<Project xmlns="http://schemas.microsoft.com/developer/msbuild/2003">
+ <PropertyGroup>
+ <SerializerName>$(AssemblyName).XmlSerializers</SerializerName>
+ <SerializerDllImmediatePath>$(IntermediateOutputPath)$(SerializerName).dll</SerializerDllImmediatePath>
+ <SerializerPdbImmediatePath>$(IntermediateOutputPath)$(SerializerName).pdb</SerializerPdbImmediatePath>
+ <SerializerCsImmediatePath>$(IntermediateOutputPath)$(SerializerName).cs</SerializerCsImmediatePath>
+ <SGenWarningText>SGEN : warning SGEN1: Fail to generate the serializer for $(AssemblyName).dll. Please follow the instructions in https://go.microsoft.com/fwlink/?linkid=858594 and try again.</SGenWarningText>
+ </PropertyGroup>
+ <Target Name="GenerateSerializationAssembly" AfterTargets="Build">
+ <Delete Condition="Exists('$(SerializerDllImmediatePath)') == 'true'" Files="$(SerializerDllImmediatePath)" />
+ <Delete Condition="Exists('$(SerializerPdbImmediatePath)') == 'true'" Files="$(SerializerPdbImmediatePath)" />
+ <Delete Condition="Exists('$(SerializerCsImmediatePath)') == 'true'" Files="$(SerializerCsImmediatePath)" />
+ <Message Text="Running Serialization Tool" Importance="normal" />
+ <Exec Command="dotnet Microsoft.XmlSerializer.Generator $(IntermediateOutputPath)$(AssemblyName).dll /force /quiet" ContinueOnError="true"/>
+ <Warning Condition="Exists('$(SerializerCsImmediatePath)') != 'true'" Text="$(SGenWarningText)" />
+ <Csc Condition="Exists('$(SerializerCsImmediatePath)') == 'true'" ContinueOnError="true" OutputAssembly="$(SerializerDllImmediatePath)" References="@(ReferencePath);@(IntermediateAssembly)" EmitDebugInformation="$(DebugSymbols)" Sources="$(SerializerCsImmediatePath)" TargetType="Library" ToolExe="$(CscToolExe)" ToolPath="$(CscToolPath)"/>
+ <Warning Condition="Exists('$(SerializerDllImmediatePath)') != 'true' And Exists('$(SerializerCsImmediatePath)') == 'true'" Text="$(SGenWarningText)"/>
+ <Copy Condition="Exists('$(SerializerDllImmediatePath)') == 'true'" SourceFiles="$(SerializerDllImmediatePath)" DestinationFolder="$(OutputPath)" />
+ </Target>
+ <Target Name="CleanSerializationAssembly" AfterTargets="CoreClean">
+ <Message Text="Cleaning serialization files..." Importance="normal"/>
+ <Delete Condition="Exists('$(OutputPath)\$(SerializerName).dll') == 'true'" Files="$(OutputPath)\$(SerializerName).dll" />
+ </Target>
+ <Target Name="CopySerializer" AfterTargets="PrepareForPublish">
+ <Copy Condition="Exists('$(OutputPath)\$(AssemblyName).XmlSerializers.dll')=='true'" SourceFiles="$(OutputPath)\$(AssemblyName).XmlSerializers.dll" DestinationFolder="$(PublishDir)" SkipUnchangedFiles="false" />
+ </Target>
+</Project> \ No newline at end of file
diff --git a/src/Microsoft.XmlSerializer.Generator/src/Microsoft.XmlSerializer.Generator.runtimeconfig.json b/src/Microsoft.XmlSerializer.Generator/pkg/build/dotnet-Microsoft.XmlSerializer.Generator.runtimeconfig.json
index 21bc6389d7..7539019b10 100644
--- a/src/Microsoft.XmlSerializer.Generator/src/Microsoft.XmlSerializer.Generator.runtimeconfig.json
+++ b/src/Microsoft.XmlSerializer.Generator/pkg/build/dotnet-Microsoft.XmlSerializer.Generator.runtimeconfig.json
@@ -1,8 +1,9 @@
{
"runtimeOptions": {
+ "tfm": "netcoreapp2.0",
"framework": {
"name": "Microsoft.NETCore.App",
- "version": "9.9.9"
+ "version": "2.0.0"
}
}
} \ No newline at end of file
diff --git a/src/Microsoft.XmlSerializer.Generator/src/prefercliruntime b/src/Microsoft.XmlSerializer.Generator/pkg/build/prefercliruntime
index e69de29bb2..e69de29bb2 100644
--- a/src/Microsoft.XmlSerializer.Generator/src/prefercliruntime
+++ b/src/Microsoft.XmlSerializer.Generator/pkg/build/prefercliruntime
diff --git a/src/Microsoft.XmlSerializer.Generator/src/GenerateThisAssemblyCs.targets b/src/Microsoft.XmlSerializer.Generator/src/GenerateThisAssemblyCs.targets
new file mode 100644
index 0000000000..a047acd078
--- /dev/null
+++ b/src/Microsoft.XmlSerializer.Generator/src/GenerateThisAssemblyCs.targets
@@ -0,0 +1,52 @@
+<?xml version="1.0" encoding="utf-8"?>
+<Project xmlns="http://schemas.microsoft.com/developer/msbuild/2003">
+ <PropertyGroup>
+ <CompileDependsOn>
+ GenerateThisAssemblyCs;
+ $(CompileDependsOn)
+ </CompileDependsOn>
+ </PropertyGroup>
+ <ItemGroup>
+ <Compile Include="$(IntermediateOutputPath)\ThisAssembly.cs"/>
+ </ItemGroup>
+
+ <Target Name="GenerateThisAssemblyCs">
+ <PropertyGroup>
+ <ThisAssemblyCsContents>
+using System%3B
+namespace Microsoft.XmlSerializer.Generator
+{
+ internal static class ThisAssembly
+ {
+ internal const string PackageVersion = "$(PackageVersion)"%3B
+ internal const string AssemblyVersion = "$(AssemblyVersion)"%3B
+ internal const string Version = "$(AssemblyFileVersion)"%3B
+ internal const string PreReleaseLabel = "$(PreReleaseLabel)"%3B
+
+ internal static string InformationalVersion
+ {
+ get
+ {
+ if (string.IsNullOrEmpty(PreReleaseLabel))
+ {
+ return PackageVersion%3B
+ }
+ else
+ {
+ return $"{PackageVersion}-{PreReleaseLabel}"%3B
+ }
+ }
+ }
+ }
+}
+ </ThisAssemblyCsContents>
+ </PropertyGroup>
+
+ <!-- Write ThisAssembly.cs if this is a new version number, or it is missing -->
+ <WriteLinesToFile
+ File="$(IntermediateOutputPath)\ThisAssembly.cs"
+ Lines="$(ThisAssemblyCsContents)"
+ Overwrite="true"
+ Encoding="Unicode"/>
+ </Target>
+</Project> \ No newline at end of file
diff --git a/src/Microsoft.XmlSerializer.Generator/src/Microsoft.XmlSerializer.Generator.csproj b/src/Microsoft.XmlSerializer.Generator/src/Microsoft.XmlSerializer.Generator.csproj
index 7ee5e89c37..5f67201f4c 100644
--- a/src/Microsoft.XmlSerializer.Generator/src/Microsoft.XmlSerializer.Generator.csproj
+++ b/src/Microsoft.XmlSerializer.Generator/src/Microsoft.XmlSerializer.Generator.csproj
@@ -3,7 +3,7 @@
<Import Project="$([MSBuild]::GetDirectoryNameOfFileAbove($(MSBuildThisFileDirectory), dir.props))\dir.props" />
<PropertyGroup>
<ProjectGuid>{80958E8B-2FEB-4F95-83F9-825CA1ED26F8}</ProjectGuid>
- <AssemblyName>Microsoft.XmlSerializer.Generator</AssemblyName>
+ <AssemblyName>dotnet-Microsoft.XmlSerializer.Generator</AssemblyName>
<AllowUnsafeBlocks>true</AllowUnsafeBlocks>
<StringResourcesPath>..\..\System.Private.Xml\src\Resources\Strings.resx</StringResourcesPath>
<DefineConstants>$(DefineConstants);XMLSERIALIZERGENERATOR</DefineConstants>
@@ -154,17 +154,6 @@
<Compile Include="System\Xml\Serialization\XmlElementAttributeExtension.cs" />
<Compile Include="System\Xml\Serialization\XmlRootAttributeExtensions.cs" />
</ItemGroup>
- <ItemGroup>
- <Reference Include="System.Resources.ResourceManager" />
- </ItemGroup>
- <ItemGroup>
- <EmbeddedResource Include="Resources\$(AssemblyName).rd.xml" />
- <Content Include="Microsoft.XmlSerializer.Generator.runtimeconfig.json">
- <CopyToOutputDirectory>PreserveNewest</CopyToOutputDirectory>
- </Content>
- <Content Include="prefercliruntime">
- <CopyToOutputDirectory>PreserveNewest</CopyToOutputDirectory>
- </Content>
- </ItemGroup>
<Import Project="$([MSBuild]::GetDirectoryNameOfFileAbove($(MSBuildThisFileDirectory), dir.targets))\dir.targets" />
+ <Import Project=".\GenerateThisAssemblyCs.targets" />
</Project> \ No newline at end of file
diff --git a/src/Microsoft.XmlSerializer.Generator/src/Resources/Microsoft.XmlSerializer.Generator.rd.xml b/src/Microsoft.XmlSerializer.Generator/src/Resources/Microsoft.XmlSerializer.Generator.rd.xml
deleted file mode 100644
index 9c983cad2f..0000000000
--- a/src/Microsoft.XmlSerializer.Generator/src/Resources/Microsoft.XmlSerializer.Generator.rd.xml
+++ /dev/null
@@ -1,11 +0,0 @@
-<?xml version="1.0" encoding="utf-8" ?>
-<Directives xmlns="http://schemas.microsoft.com/netfx/2013/01/metadata">
- <Library Name="Microsoft.XmlSerializer.Generator">
- <Assembly Name="Microsoft.XmlSerializer.Generator">
- <Namespace Name="Microsoft.XmlSerializer.Generator">
- <!-- XmlQualifiedName is well known to the serializers and must not be explicitly specified to sg.exe -->
- <Type Name="XmlQualifiedName" DataContractSerializer="Excluded" DataContractJsonSerializer="Excluded"/>
- </Namespace>
- </Assembly>
- </Library>
-</Directives>
diff --git a/src/Microsoft.XmlSerializer.Generator/src/Sgen.cs b/src/Microsoft.XmlSerializer.Generator/src/Sgen.cs
index 32201498c1..87c830cf15 100644
--- a/src/Microsoft.XmlSerializer.Generator/src/Sgen.cs
+++ b/src/Microsoft.XmlSerializer.Generator/src/Sgen.cs
@@ -28,18 +28,14 @@ namespace Microsoft.XmlSerializer.Generator
var errs = new ArrayList();
bool force = false;
bool proxyOnly = false;
- bool caseSensitive = false;
+ bool disableRun = true;
+ bool noLogo = false;
+ bool parsableErrors = false;
+ bool silent = false;
+ bool warnings = false;
try
{
- if (args.Length > 0)
- {
- if (args.Any(s => s.IndexOf("casesensitive", StringComparison.OrdinalIgnoreCase) >= 0))
- {
- caseSensitive = true;
- }
- }
-
for (int i = 0; i < args.Length; i++)
{
string arg = args[i];
@@ -55,10 +51,8 @@ namespace Microsoft.XmlSerializer.Generator
}
}
- if (!caseSensitive)
- {
- arg = arg.ToLower(CultureInfo.InvariantCulture);
- }
+ string originalArg = arg;
+ arg = arg.ToLower(CultureInfo.InvariantCulture);
if (ArgumentMatch(arg, "?") || ArgumentMatch(arg, "help"))
{
@@ -87,9 +81,34 @@ namespace Microsoft.XmlSerializer.Generator
{
types.Add(value);
}
- else if (ArgumentMatch(arg, "casesensitive"))
+ else if (ArgumentMatch(arg, "assembly"))
{
- continue;
+ if (assembly != null)
+ {
+ errs.Add(SR.Format(SR.ErrInvalidArgument, "/assembly", arg));
+ }
+
+ assembly = value;
+ }
+ else if (ArgumentMatch(arg, "quiet"))
+ {
+ disableRun = false;
+ }
+ else if (ArgumentMatch(arg, "nologo"))
+ {
+ noLogo = true;
+ }
+ else if (ArgumentMatch(arg, "silent"))
+ {
+ silent = true;
+ }
+ else if (ArgumentMatch(arg, "parsableerrors"))
+ {
+ parsableErrors = true;
+ }
+ else if (ArgumentMatch(arg, "verbose"))
+ {
+ warnings = true;
}
else
{
@@ -100,7 +119,7 @@ namespace Microsoft.XmlSerializer.Generator
errs.Add(SR.Format(SR.ErrInvalidArgument, "/assembly", arg));
}
- assembly = arg;
+ assembly = originalArg;
}
else
{
@@ -109,11 +128,16 @@ namespace Microsoft.XmlSerializer.Generator
}
}
+ if (!noLogo)
+ {
+ WriteHeader();
+ }
+
if (errs.Count > 0)
{
foreach (string err in errs)
{
- Console.Error.WriteLine(FormatMessage(true, SR.Format(SR.Warning, err)));
+ Console.Error.WriteLine(FormatMessage(parsableErrors, true, SR.Format(SR.Warning, err)));
}
}
@@ -121,14 +145,21 @@ namespace Microsoft.XmlSerializer.Generator
{
if (assembly == null)
{
- Console.Error.WriteLine(FormatMessage(false, SR.Format(SR.ErrMissingRequiredArgument, SR.Format(SR.ErrAssembly, "assembly"))));
+ Console.Error.WriteLine(FormatMessage(parsableErrors, false, SR.Format(SR.ErrMissingRequiredArgument, SR.Format(SR.ErrAssembly, "assembly"))));
}
WriteHelp();
return 0;
}
- GenerateFile(types, assembly, proxyOnly, force, codePath);
+ if(disableRun)
+ {
+ Console.WriteLine("This tool is not intended to be used directly.");
+ Console.WriteLine("Please refer to https://github.com/dotnet/core/blob/master/samples/xmlserializergenerator-instructions.md on how to use it.");
+ return 0;
+ }
+
+ GenerateFile(types, assembly, proxyOnly, silent, warnings, force, codePath, parsableErrors);
}
catch (Exception e)
{
@@ -137,14 +168,14 @@ namespace Microsoft.XmlSerializer.Generator
throw;
}
- WriteError(e);
+ WriteError(e, parsableErrors);
return 1;
}
return 0;
}
- private void GenerateFile(List<string> typeNames, string assemblyName, bool proxyOnly, bool force, string outputDirectory)
+ private void GenerateFile(List<string> typeNames, string assemblyName, bool proxyOnly, bool silent, bool warnings, bool force, string outputDirectory, bool parsableerrors)
{
Assembly assembly = LoadAssembly(assemblyName, true);
Type[] types;
@@ -178,7 +209,7 @@ namespace Microsoft.XmlSerializer.Generator
Type type = assembly.GetType(typeName);
if (type == null)
{
- Console.Error.WriteLine(FormatMessage(false, SR.Format(SR.ErrorDetails, SR.Format(SR.ErrLoadType, typeName, assemblyName))));
+ Console.Error.WriteLine(FormatMessage(parsableerrors, false, SR.Format(SR.ErrorDetails, SR.Format(SR.ErrLoadType, typeName, assemblyName))));
}
types[typeIndex++] = type;
@@ -214,7 +245,7 @@ namespace Microsoft.XmlSerializer.Generator
if (!proxyOnly)
{
- ImportType(type, mappings, importedTypes, importer);
+ ImportType(type, mappings, importedTypes, warnings, importer, parsableerrors);
}
}
@@ -244,7 +275,8 @@ namespace Microsoft.XmlSerializer.Generator
throw new ArgumentException(SR.Format(SR.ErrDirectoryNotExists, codePath, outputDirectory));
}
- bool success;
+ bool success = false;
+ bool toDeleteFile = true;
try
{
@@ -260,22 +292,33 @@ namespace Microsoft.XmlSerializer.Generator
}
catch (UnauthorizedAccessException)
{
+ toDeleteFile = false;
throw new UnauthorizedAccessException(SR.Format(SR.DirectoryAccessDenied, outputDirectory));
}
+ finally
+ {
+ if (!success && toDeleteFile && File.Exists(codePath))
+ {
+ File.Delete(codePath);
+ }
+ }
if (success)
{
- Console.Out.WriteLine(SR.Format(SR.InfoAssemblyName, codePath));
- Console.Out.WriteLine(SR.Format(SR.InfoGeneratedAssembly, assembly.Location, codePath));
+ if (!silent)
+ {
+ Console.Out.WriteLine(SR.Format(SR.InfoFileName, codePath));
+ Console.Out.WriteLine(SR.Format(SR.InfoGeneratedFile, assembly.Location, codePath));
+ }
}
else
{
- Console.Out.WriteLine(FormatMessage(false, SR.Format(SR.ErrGenerationFailed, assembly.Location)));
+ Console.Out.WriteLine(FormatMessage(parsableerrors, false, SR.Format(SR.ErrGenerationFailed, assembly.Location)));
}
}
else
{
- Console.Out.WriteLine(FormatMessage(true, SR.Format(SR.InfoNoSerializableTypes, assembly.Location)));
+ Console.Out.WriteLine(FormatMessage(parsableerrors, true, SR.Format(SR.InfoNoSerializableTypes, assembly.Location)));
}
}
@@ -291,7 +334,7 @@ namespace Microsoft.XmlSerializer.Generator
return (arg == formal || (arg.Length == 1 && arg[0] == formal[0]));
}
- private void ImportType(Type type, ArrayList mappings, ArrayList importedTypes, XmlReflectionImporter importer)
+ private void ImportType(Type type, ArrayList mappings, ArrayList importedTypes, bool verbose, XmlReflectionImporter importer, bool parsableerrors)
{
XmlTypeMapping xmlTypeMapping = null;
var localImporter = new XmlReflectionImporter();
@@ -305,6 +348,13 @@ namespace Microsoft.XmlSerializer.Generator
{
throw;
}
+
+ if (verbose)
+ {
+ Console.Out.WriteLine(FormatMessage(parsableerrors, true, SR.Format(SR.InfoIgnoreType, type.FullName)));
+ WriteWarning(e, parsableerrors);
+ }
+
return;
}
if (xmlTypeMapping != null)
@@ -331,32 +381,55 @@ namespace Microsoft.XmlSerializer.Generator
private void WriteHeader()
{
// do not localize Copyright header
- Console.WriteLine(String.Format(CultureInfo.CurrentCulture, "[Microsoft (R) .NET Framework, Version {0}]", TempAssembly.ThisAssembly.InformationalVersion));
+ Console.WriteLine(String.Format(CultureInfo.CurrentCulture, "[Microsoft (R) .NET Core Xml Serialization Generation Utility, Version {0}]", ThisAssembly.InformationalVersion));
Console.WriteLine("Copyright (C) Microsoft Corporation. All rights reserved.");
}
private void WriteHelp()
{
- //TBD
- Console.WriteLine("In Development");
+ Console.Out.WriteLine(SR.Format(SR.HelpDescription));
+ Console.Out.WriteLine(SR.Format(SR.HelpUsage, this.GetType().Assembly.GetName().Name));
+ Console.Out.WriteLine(SR.Format(SR.HelpDevOptions));
+ Console.Out.WriteLine(SR.Format(SR.HelpAssembly, "/assembly:", "/a:"));
+ Console.Out.WriteLine(SR.Format(SR.HelpType, "/type:", "/t:"));
+ Console.Out.WriteLine(SR.Format(SR.HelpProxy, "/proxytypes", "/p"));
+ Console.Out.WriteLine(SR.Format(SR.HelpForce, "/force", "/f"));
+ Console.Out.WriteLine(SR.Format(SR.HelpOut, "/out:", "/o:"));
+
+ Console.Out.WriteLine(SR.Format(SR.HelpMiscOptions));
+ Console.Out.WriteLine(SR.Format(SR.HelpHelp, "/?", "/help"));
}
- private static string FormatMessage(bool warning, string message)
+ private static string FormatMessage(bool parsableerrors, bool warning, string message)
{
- return FormatMessage(warning, "SGEN1", message);
+ return FormatMessage(parsableerrors, warning, "SGEN1", message);
}
- private static string FormatMessage(bool warning, string code, string message)
+ private static string FormatMessage(bool parsableerrors, bool warning, string code, string message)
{
+ if (!parsableerrors)
+ {
+ return message;
+ }
+
return "SGEN: " + (warning ? "warning " : "error ") + code + ": " + message;
}
- private static void WriteError(Exception e)
+ private static void WriteError(Exception e, bool parsableerrors)
+ {
+ Console.Error.WriteLine(FormatMessage(parsableerrors, false, e.Message));
+ if (e.InnerException != null)
+ {
+ WriteError(e.InnerException, parsableerrors);
+ }
+ }
+
+ static void WriteWarning(Exception e, bool parsableerrors)
{
- Console.Error.WriteLine(FormatMessage(false, e.Message));
+ Console.Out.WriteLine(FormatMessage(parsableerrors, true, e.Message));
if (e.InnerException != null)
{
- WriteError(e.InnerException);
+ WriteWarning(e.InnerException, parsableerrors);
}
}
}
diff --git a/src/Microsoft.XmlSerializer.Generator/tests/Configurations.props b/src/Microsoft.XmlSerializer.Generator/tests/Configurations.props
index 2887e64b0d..eb4a540a92 100644
--- a/src/Microsoft.XmlSerializer.Generator/tests/Configurations.props
+++ b/src/Microsoft.XmlSerializer.Generator/tests/Configurations.props
@@ -4,7 +4,7 @@
<BuildConfigurations>
netstandard;
uap;
- netcoreapp-Unix;
+ netcoreapp;
</BuildConfigurations>
</PropertyGroup>
</Project> \ No newline at end of file
diff --git a/src/Microsoft.XmlSerializer.Generator/tests/Microsoft.XmlSerializer.Generator.Tests.csproj b/src/Microsoft.XmlSerializer.Generator/tests/Microsoft.XmlSerializer.Generator.Tests.csproj
index 0730b4eaed..f4d52adb2f 100644
--- a/src/Microsoft.XmlSerializer.Generator/tests/Microsoft.XmlSerializer.Generator.Tests.csproj
+++ b/src/Microsoft.XmlSerializer.Generator/tests/Microsoft.XmlSerializer.Generator.Tests.csproj
@@ -6,14 +6,26 @@
<DefineConstants>$(DefineConstants);XMLSERIALIZERGENERATORTESTS</DefineConstants>
</PropertyGroup>
<PropertyGroup>
- <SkipTestsOnPlatform Condition="'$(TargetGroup)' == 'uap' OR '$(TargetsUnix)' == 'true'">true</SkipTestsOnPlatform>
+ <SkipTestsOnPlatform Condition="'$(TargetGroup)' == 'uap' OR '$(ArchGroup)' == 'arm' OR '$(ArchGroup)' == 'arm64' OR '$(ArchGroup)' == 'armel'">true</SkipTestsOnPlatform>
+ </PropertyGroup>
+ <PropertyGroup Condition="'$(TargetGroup)' == 'netcoreapp'">
+ <!-- We're building netcoreap, run on the test CLI
+ Reuse the same runtimeconfig that the tests use. -->
+ <GeneratorRuntimeConfig>$(ToolsDir)xunit.console.netcore.runtimeconfig.json</GeneratorRuntimeConfig>
+ <GeneratorCliPath>$(TestHostRootPath)</GeneratorCliPath>
+ </PropertyGroup>
+ <PropertyGroup Condition="'$(TargetGroup)' != 'netcoreapp'">
+ <!-- We're building some non-netcoreapp target, run on the Tools CLI.
+ Reuse the same runtimeconfig used by CSC. -->
+ <GeneratorRuntimeConfig>$(ToolsDir)csc.runtimeconfig.json</GeneratorRuntimeConfig>
+ <GeneratorCliPath>$(ToolsDir)dotnetcli/</GeneratorCliPath>
</PropertyGroup>
<PropertyGroup Condition="'$(Configuration)|$(Platform)'=='netstandard-Debug|AnyCPU'" />
<PropertyGroup Condition="'$(Configuration)|$(Platform)'=='netstandard-Release|AnyCPU'" />
<PropertyGroup Condition="'$(Configuration)|$(Platform)' == 'uap-Debug|AnyCPU'" />
<PropertyGroup Condition="'$(Configuration)|$(Platform)' == 'uap-Release|AnyCPU'" />
- <PropertyGroup Condition="'$(Configuration)|$(Platform)' == 'netcoreapp-Unix-Debug|AnyCPU'" />
- <PropertyGroup Condition="'$(Configuration)|$(Platform)' == 'netcoreapp-Unix-Release|AnyCPU'" />
+ <PropertyGroup Condition="'$(Configuration)|$(Platform)' == 'netcoreapp-Debug|AnyCPU'" />
+ <PropertyGroup Condition="'$(Configuration)|$(Platform)' == 'netcoreapp-Release|AnyCPU'" />
<ItemGroup Condition=" '$(SkipTestsOnPlatform)' != 'true' ">
<Compile Include=".\SGenTests.cs" />
<Compile Include="$(TestSourceFolder)..\..\System.Runtime.Serialization.Xml\tests\Utils.cs" />
@@ -22,29 +34,58 @@
</ItemGroup>
<ItemGroup>
<Compile Include=".\AlwaysPassTest.cs" />
+ <Content Include="$(GeneratorRuntimeConfig)">
+ <!-- Rename it to match the Generator application name -->
+ <Link>dotnet-Microsoft.XmlSerializer.Generator.runtimeconfig.json</Link>
+ <CopyToOutputDirectory>PreserveNewest</CopyToOutputDirectory>
+ </Content>
</ItemGroup>
<ItemGroup>
- <ReferenceFromRuntime Include="Microsoft.XmlSerializer.Generator" />
+ <ReferenceFromRuntime Include="dotnet-Microsoft.XmlSerializer.Generator">
+ <!-- Copy this to our test output directory and run from there.
+ This is required so that we can stage the application with a custom runtimeconfig that lets it run on the test shared framework. -->
+ <Private>true</Private>
+ </ReferenceFromRuntime>
</ItemGroup>
- <Target Name="GenerateSerializationAssembly" AfterTargets="Build" Condition=" '$(SkipTestsOnPlatform)' != 'true' " >
+ <!-- This target runs before binplacing as it needs to provide a test assembly to binplace, and depends on CopyFilesToOutputDirectory
+ so that the Generator app dll and runtimeconfig will be copied to the OutputPath -->
+ <Target Name="GenerateSerializationAssembly" DependsOnTargets="CopyFilesToOutputDirectory" BeforeTargets="GetBinPlaceItems" Condition=" '$(SkipTestsOnPlatform)' != 'true' " >
<PropertyGroup>
<SerializerName>$(AssemblyName).XmlSerializers</SerializerName>
</PropertyGroup>
- <Copy SourceFiles="$(ToolsDir)\csc.runtimeconfig.json" DestinationFiles="$(OutputPath)Microsoft.XmlSerializer.Generator.runtimeconfig.json" />
<Message Text="Running Serialization Tool" Importance="normal" />
- <Exec ContinueOnError="true" Command="$(ToolsDir)\dotnetcli\dotnet $(OutputPath)Microsoft.XmlSerializer.Generator.dll $(OutputPath)Microsoft.XmlSerializer.Generator.Tests.dll /force /casesensitive" />
+ <Exec Command="$(GeneratorCliPath)dotnet $(OutputPath)dotnet-Microsoft.XmlSerializer.Generator.dll $(OutputPath)Microsoft.XmlSerializer.Generator.Tests.dll /force /quiet" />
<Warning Condition="Exists('$(OutputPath)$(SerializerName).cs') != 'true'" Text="Fail to generate $(OutputPath)$(SerializerName).cs"/>
- <Csc Condition="Exists('$(OutputPath)$(SerializerName).cs') == 'true'" ContinueOnError="true"
+ <Csc Condition="Exists('$(OutputPath)$(SerializerName).cs') == 'true' AND '$(MSBuildRuntimeType)' != 'core'"
+ OutputAssembly="$(OutputPath)$(SerializerName).dll"
+ References="@(ReferencePath);@(IntermediateAssembly)"
+ EmitDebugInformation="$(DebugSymbols)"
+ DebugType="$(DebugType)"
+ Sources="$(OutputPath)$(SerializerName).cs"
+ TargetType="Library"
+ ToolExe="$(CscToolExe)"
+ ToolPath="$(CscToolPath)"
+ DisabledWarnings="$(NoWarn), 219"
+ UseSharedCompilation="true" />
+ <!-- when building on core CSC requires the OverrideToolHost parameter, but this is not supported by desktop csc -->
+ <Csc Condition="Exists('$(OutputPath)$(SerializerName).cs') == 'true' AND '$(MSBuildRuntimeType)' == 'core'"
OutputAssembly="$(OutputPath)$(SerializerName).dll"
References="@(ReferencePath);@(IntermediateAssembly)"
EmitDebugInformation="$(DebugSymbols)"
+ DebugType="$(DebugType)"
Sources="$(OutputPath)$(SerializerName).cs"
TargetType="Library"
ToolExe="$(CscToolExe)"
ToolPath="$(CscToolPath)"
+ OverrideToolHost="$(OverrideToolHost)"
DisabledWarnings="$(NoWarn), 219"
UseSharedCompilation="true" />
<Warning Condition="Exists('$(OutputPath)$(SerializerName).dll') != 'true'" Text="Fail to generate $(OutputPath)$(SerializerName).dll"/>
+
+ <ItemGroup>
+ <!-- Include the Serializer in ReferenceCopyLocalPaths so that it will be binplaced -->
+ <ReferenceCopyLocalPaths Include="$(OutputPath)$(SerializerName).dll" />
+ </ItemGroup>
</Target>
<Import Project="$([MSBuild]::GetDirectoryNameOfFileAbove($(MSBuildThisFileDirectory), dir.targets))\dir.targets" />
</Project>
diff --git a/src/Microsoft.XmlSerializer.Generator/tests/SGenTests.cs b/src/Microsoft.XmlSerializer.Generator/tests/SGenTests.cs
index 17a492ff2e..be6cf98383 100644
--- a/src/Microsoft.XmlSerializer.Generator/tests/SGenTests.cs
+++ b/src/Microsoft.XmlSerializer.Generator/tests/SGenTests.cs
@@ -15,7 +15,7 @@ namespace Microsoft.XmlSerializer.Generator.Tests
public static void SgenCommandTest()
{
string codefile = "Microsoft.XmlSerializer.Generator.Tests.XmlSerializers.cs";
- int n = Sgen.Main(new string[] { "Microsoft.XmlSerializer.Generator.Tests.dll", "/force", "/casesensitive" });
+ int n = Sgen.Main(new string[] { "Microsoft.XmlSerializer.Generator.Tests.dll", "/force", "/quiet"});
Assert.Equal(0, n);
Assert.True(File.Exists(codefile), string.Format("Fail to generate {0}.", codefile));
}
diff --git a/src/Native/Unix/System.Native/pal_networking.cpp b/src/Native/Unix/System.Native/pal_networking.cpp
index 177232dbf1..7c2a3034b3 100644
--- a/src/Native/Unix/System.Native/pal_networking.cpp
+++ b/src/Native/Unix/System.Native/pal_networking.cpp
@@ -9,6 +9,7 @@
#include "pal_safecrt.h"
#include <stdlib.h>
+#include <limits.h>
#include <pthread.h>
#include <arpa/inet.h>
#include <assert.h>
@@ -1143,13 +1144,29 @@ SystemNative_SetIPv6Address(uint8_t* socketAddress, int32_t socketAddressLen, ui
return PAL_SUCCESS;
}
-static void ConvertMessageHeaderToMsghdr(msghdr* header, const MessageHeader& messageHeader)
+static bool IsStreamSocket(int socket)
{
+ int type;
+ socklen_t length = sizeof(int);
+ return getsockopt(socket, SOL_SOCKET, SO_TYPE, &type, &length) == 0
+ && type == SOCK_STREAM;
+}
+
+static void ConvertMessageHeaderToMsghdr(msghdr* header, const MessageHeader& messageHeader, int socket = -1)
+{
+ // sendmsg/recvmsg can return EMSGSIZE when msg_iovlen is greather than IOV_MAX.
+ // We avoid this for stream sockets by truncating msg_iovlen to IOV_MAX. This is ok since sendmsg is
+ // not required to send all data and recvmsg can be called again to receive more.
+ auto iovlen = static_cast<decltype(header->msg_iovlen)>(messageHeader.IOVectorCount);
+ if (iovlen > IOV_MAX && IsStreamSocket(socket))
+ {
+ iovlen = static_cast<decltype(iovlen)>(IOV_MAX);
+ }
*header = {
.msg_name = messageHeader.SocketAddress,
.msg_namelen = static_cast<unsigned int>(messageHeader.SocketAddressLen),
.msg_iov = reinterpret_cast<iovec*>(messageHeader.IOVectors),
- .msg_iovlen = static_cast<decltype(header->msg_iovlen)>(messageHeader.IOVectorCount),
+ .msg_iovlen = iovlen,
.msg_control = messageHeader.ControlBuffer,
.msg_controllen = static_cast<decltype(header->msg_controllen)>(messageHeader.ControlBufferLen),
};
@@ -1576,7 +1593,7 @@ extern "C" Error SystemNative_ReceiveMessage(intptr_t socket, MessageHeader* mes
}
msghdr header;
- ConvertMessageHeaderToMsghdr(&header, *messageHeader);
+ ConvertMessageHeaderToMsghdr(&header, *messageHeader, fd);
ssize_t res;
while (CheckInterrupted(res = recvmsg(fd, &header, socketFlags)));
@@ -1619,7 +1636,7 @@ extern "C" Error SystemNative_SendMessage(intptr_t socket, MessageHeader* messag
}
msghdr header;
- ConvertMessageHeaderToMsghdr(&header, *messageHeader);
+ ConvertMessageHeaderToMsghdr(&header, *messageHeader, fd);
ssize_t res;
while (CheckInterrupted(res = sendmsg(fd, &header, flags)));
diff --git a/src/Native/Unix/System.Security.Cryptography.Native/openssl.cpp b/src/Native/Unix/System.Security.Cryptography.Native/openssl.cpp
index ec0205d71e..eba1dc2f4a 100644
--- a/src/Native/Unix/System.Security.Cryptography.Native/openssl.cpp
+++ b/src/Native/Unix/System.Security.Cryptography.Native/openssl.cpp
@@ -1271,12 +1271,11 @@ static void LockingCallback(int mode, int n, const char* file, int line)
result = pthread_mutex_unlock(&g_locks[n]);
}
-#pragma clang diagnostic pop
-
if (result != 0)
{
assert(0 && "LockingCallback failed.");
}
+#pragma clang diagnostic pop
}
#ifdef __APPLE__
diff --git a/src/Native/Unix/System.Security.Cryptography.Native/opensslshim.h b/src/Native/Unix/System.Security.Cryptography.Native/opensslshim.h
index 3e405b09da..c77d4bc0f6 100644
--- a/src/Native/Unix/System.Security.Cryptography.Native/opensslshim.h
+++ b/src/Native/Unix/System.Security.Cryptography.Native/opensslshim.h
@@ -281,7 +281,6 @@ int EC_POINT_set_affine_coordinates_GF2m(const EC_GROUP *group, EC_POINT *p,
PER_FUNCTION_BLOCK(SSL_shutdown, true) \
PER_FUNCTION_BLOCK(SSL_state, true) \
PER_FUNCTION_BLOCK(SSLv23_method, true) \
- PER_FUNCTION_BLOCK(SSLv3_method, false) \
PER_FUNCTION_BLOCK(SSL_write, true) \
PER_FUNCTION_BLOCK(TLSv1_1_method, true) \
PER_FUNCTION_BLOCK(TLSv1_2_method, true) \
@@ -572,7 +571,6 @@ FOR_ALL_OPENSSL_FUNCTIONS
#define SSL_shutdown SSL_shutdown_ptr
#define SSL_state SSL_state_ptr
#define SSLv23_method SSLv23_method_ptr
-#define SSLv3_method SSLv3_method_ptr
#define SSL_write SSL_write_ptr
#define TLSv1_1_method TLSv1_1_method_ptr
#define TLSv1_2_method TLSv1_2_method_ptr
diff --git a/src/Native/Unix/configure.cmake b/src/Native/Unix/configure.cmake
index e905577cd1..1598db7bd1 100644
--- a/src/Native/Unix/configure.cmake
+++ b/src/Native/Unix/configure.cmake
@@ -29,7 +29,7 @@ set(CMAKE_REQUIRED_FLAGS -Werror)
# in_pktinfo: Find whether this struct exists
check_include_files(
- linux/in.h
+ "sys/socket.h;linux/in.h"
HAVE_LINUX_IN_H)
if (HAVE_LINUX_IN_H)
@@ -40,10 +40,11 @@ endif ()
check_c_source_compiles(
"
+ #include <sys/socket.h>
#include <${SOCKET_INCLUDES}>
int main()
{
- struct in_pktinfo;
+ struct in_pktinfo pktinfo;
return 0;
}
"
@@ -51,10 +52,11 @@ check_c_source_compiles(
check_c_source_compiles(
"
+ #include <sys/socket.h>
#include <${SOCKET_INCLUDES}>
int main()
{
- struct ip_mreqn;
+ struct ip_mreqn mreqn;
return 0;
}
"
diff --git a/src/Native/build-native.sh b/src/Native/build-native.sh
index 397608e19a..5120267232 100755
--- a/src/Native/build-native.sh
+++ b/src/Native/build-native.sh
@@ -27,6 +27,10 @@ initHostDistroRid()
if [ "$__HostOS" == "Linux" ]; then
if [ -e /etc/os-release ]; then
source /etc/os-release
+ if [[ $ID == "alpine" ]]; then
+ # remove the last version digit
+ VERSION_ID=${VERSION_ID%.*}
+ fi
__HostDistroRid="$ID.$VERSION_ID-$__HostArch"
elif [ -e /etc/redhat-release ]; then
local redhatRelease=$(</etc/redhat-release)
@@ -362,18 +366,8 @@ esac
# Set the default clang version if not already set
if [[ $__ClangMajorVersion == 0 && $__ClangMinorVersion == 0 ]]; then
- if [ $__CrossBuild == 1 ]; then
- if [[ "$__BuildArch" == "arm" || "$__BuildArch" == "armel" ]]; then
- __ClangMajorVersion=3
- __ClangMinorVersion=9
- else
- __ClangMajorVersion=3
- __ClangMinorVersion=6
- fi
- else
- __ClangMajorVersion=3
- __ClangMinorVersion=5
- fi
+ __ClangMajorVersion=3
+ __ClangMinorVersion=9
fi
# Set the remaining variables based upon the determined build configuration
diff --git a/src/System.Buffers/pkg/System.Buffers.pkgproj b/src/System.Buffers/pkg/System.Buffers.pkgproj
index 4312458b78..6794eed7f5 100644
--- a/src/System.Buffers/pkg/System.Buffers.pkgproj
+++ b/src/System.Buffers/pkg/System.Buffers.pkgproj
@@ -7,11 +7,18 @@
</ProjectReference>
<ProjectReference Include="..\src\System.Buffers.csproj" />
- <InboxOnTargetFramework Include="netcoreapp2.0" />
- <InboxOnTargetFramework Include="$(UAPvNextTFM)" />
<!-- this package is part of the implementation closure of NETStandard.Library
therefore it cannot reference NETStandard.Library -->
<SuppressMetaPackage Include="NETStandard.Library" />
+
+ <!-- Since UAP and .NETCoreApp are package based we still want to enable
+ OOBing libraries that happen to overlap with their framework package.
+ This avoids us having to lock the API in our NuGet packages just
+ to match what shipped inbox: since we can provide a new library
+ we can update it to add API without raising the netstandard version. -->
+ <ValidatePackageSuppression Include="TreatAsOutOfBox">
+ <Value>.NETCoreApp;UAP</Value>
+ </ValidatePackageSuppression>
</ItemGroup>
<Import Project="$([MSBuild]::GetDirectoryNameOfFileAbove($(MSBuildThisFileDirectory), dir.targets))\dir.targets" />
</Project> \ No newline at end of file
diff --git a/src/System.Buffers/src/Configurations.props b/src/System.Buffers/src/Configurations.props
index f8eca1e4fa..6544913df5 100644
--- a/src/System.Buffers/src/Configurations.props
+++ b/src/System.Buffers/src/Configurations.props
@@ -4,13 +4,15 @@
<PackageConfigurations>
netstandard1.1;
netstandard;
+ netcoreapp2.0-Windows_NT;
+ netcoreapp2.0-Unix;
+ uap-Windows_NT;
+ uapaot-Windows_NT;
</PackageConfigurations>
<BuildConfigurations>
$(PackageConfigurations);
netcoreapp-Windows_NT;
netcoreapp-Unix;
- uap-Windows_NT;
- uapaot-Windows_NT;
</BuildConfigurations>
</PropertyGroup>
</Project>
diff --git a/src/System.CodeDom/src/Microsoft/CSharp/CSharpCodeGenerator.cs b/src/System.CodeDom/src/Microsoft/CSharp/CSharpCodeGenerator.cs
index e180cb5c5a..a203d193d4 100644
--- a/src/System.CodeDom/src/Microsoft/CSharp/CSharpCodeGenerator.cs
+++ b/src/System.CodeDom/src/Microsoft/CSharp/CSharpCodeGenerator.cs
@@ -2541,7 +2541,7 @@ namespace Microsoft.CSharp
Output.WriteLine();
// CSharp needs to put assembly attributes after using statements.
- // Since we need to create a empty namespace even if we don't need it,
+ // Since we need to create an empty namespace even if we don't need it,
// using will generated after assembly attributes.
var importList = new SortedSet<string>(StringComparer.Ordinal);
foreach (CodeNamespace nspace in e.Namespaces)
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 a4c892eab3..c4202e1a2c 100644
--- a/src/System.Collections.Concurrent/src/System/Collections/Concurrent/ConcurrentQueue.cs
+++ b/src/System.Collections.Concurrent/src/System/Collections/Concurrent/ConcurrentQueue.cs
@@ -1114,10 +1114,10 @@ namespace System.Collections.Concurrent
/// <summary>Padded head and tail indices, to avoid false sharing between producers and consumers.</summary>
[DebuggerDisplay("Head = {Head}, Tail = {Tail}")]
- [StructLayout(LayoutKind.Explicit, Size = 192)] // padding before/between/after fields based on typical cache line size of 64
+ [StructLayout(LayoutKind.Explicit, Size = 384)] // padding before/between/after fields based on worst case cache line size of 128
internal struct PaddedHeadAndTail
{
- [FieldOffset(64)] public int Head;
- [FieldOffset(128)] public int Tail;
+ [FieldOffset(128)] public int Head;
+ [FieldOffset(256)] public int Tail;
}
}
diff --git a/src/System.Collections.Immutable/pkg/System.Collections.Immutable.pkgproj b/src/System.Collections.Immutable/pkg/System.Collections.Immutable.pkgproj
index 3fc9266e62..fb72021465 100644
--- a/src/System.Collections.Immutable/pkg/System.Collections.Immutable.pkgproj
+++ b/src/System.Collections.Immutable/pkg/System.Collections.Immutable.pkgproj
@@ -9,8 +9,15 @@
<ProjectReference Include="..\src\System.Collections.Immutable.csproj">
<SupportedFramework>net45;netcore45;netcoreapp1.0;wp8;wpa81;$(AllXamarinFrameworks)</SupportedFramework>
</ProjectReference>
- <InboxOnTargetFramework Include="netcoreapp2.0" />
- <InboxOnTargetFramework Include="$(UAPvNextTFM)" />
+
+ <!-- Since UAP and .NETCoreApp are package based we still want to enable
+ OOBing libraries that happen to overlap with their framework package.
+ This avoids us having to lock the API in our NuGet packages just
+ to match what shipped inbox: since we can provide a new library
+ we can update it to add API without raising the netstandard version. -->
+ <ValidatePackageSuppression Include="TreatAsOutOfBox">
+ <Value>.NETCoreApp;UAP</Value>
+ </ValidatePackageSuppression>
</ItemGroup>
<Import Project="$([MSBuild]::GetDirectoryNameOfFileAbove($(MSBuildThisFileDirectory), dir.targets))\dir.targets" />
</Project> \ No newline at end of file
diff --git a/src/System.Collections.Immutable/src/PEVerifyCompat.rsp b/src/System.Collections.Immutable/src/PEVerifyCompat.rsp
new file mode 100644
index 0000000000..0a7805fa7a
--- /dev/null
+++ b/src/System.Collections.Immutable/src/PEVerifyCompat.rsp
@@ -0,0 +1 @@
+/features:peverify-compat \ No newline at end of file
diff --git a/src/System.Collections.Immutable/src/Resources/Strings.resx b/src/System.Collections.Immutable/src/Resources/Strings.resx
index 3aeb6428f9..d871641f8c 100644
--- a/src/System.Collections.Immutable/src/Resources/Strings.resx
+++ b/src/System.Collections.Immutable/src/Resources/Strings.resx
@@ -59,10 +59,10 @@
<value>System.Resources.ResXResourceWriter, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089</value>
</resheader>
<data name="ArrayInitializedStateNotEqual" xml:space="preserve">
- <value>Object is not a array with the same initialization state as the array to compare it to.</value>
+ <value>Object is not an array with the same initialization state as the array to compare it to.</value>
</data>
<data name="ArrayLengthsNotEqual" xml:space="preserve">
- <value>Object is not a array with the same number of elements as the array to compare it to.</value>
+ <value>Object is not an array with the same number of elements as the array to compare it to.</value>
</data>
<data name="CannotFindOldValue" xml:space="preserve">
<value>Cannot find the old value</value>
diff --git a/src/System.Collections.Immutable/src/System.Collections.Immutable.csproj b/src/System.Collections.Immutable/src/System.Collections.Immutable.csproj
index 457c68c3a8..e335340572 100644
--- a/src/System.Collections.Immutable/src/System.Collections.Immutable.csproj
+++ b/src/System.Collections.Immutable/src/System.Collections.Immutable.csproj
@@ -9,6 +9,7 @@
<FileAlignment>512</FileAlignment>
<DocumentationFile>$(OutputPath)$(MSBuildProjectName).xml</DocumentationFile>
<GenerateAppxPackageOnBuild>False</GenerateAppxPackageOnBuild>
+ <CompilerResponseFile>$(MSBuildThisFileDirectory)PEVerifyCompat.rsp;$(CompilerResponseFile)</CompilerResponseFile>
<PackageTargetFramework Condition="'$(TargetGroup)' == 'netstandard1.0'">netstandard1.0;portable-net45+win8+wp8+wpa81</PackageTargetFramework>
</PropertyGroup>
<PropertyGroup Condition="'$(Configuration)|$(Platform)' == 'netcoreapp-Debug|AnyCPU'" />
diff --git a/src/System.Collections.Immutable/src/System/Collections/Immutable/ImmutableInterlocked.cs b/src/System.Collections.Immutable/src/System/Collections/Immutable/ImmutableInterlocked.cs
index 5e92ae5330..dfa77cce24 100644
--- a/src/System.Collections.Immutable/src/System/Collections/Immutable/ImmutableInterlocked.cs
+++ b/src/System.Collections.Immutable/src/System/Collections/Immutable/ImmutableInterlocked.cs
@@ -423,7 +423,7 @@ namespace System.Collections.Immutable
#region ImmutableStack<T> members
/// <summary>
- /// Pushes a new element onto a stack.
+ /// Pops the top element off a stack and returns it to the caller, if the stack is not empty.
/// </summary>
/// <typeparam name="T">The type of elements stored in the stack.</typeparam>
/// <param name="location">The variable or field to atomically update.</param>
diff --git a/src/System.Collections/src/System/Collections/Generic/HashSet.cs b/src/System.Collections/src/System/Collections/Generic/HashSet.cs
index 562ed2c4cd..c21afaf758 100644
--- a/src/System.Collections/src/System/Collections/Generic/HashSet.cs
+++ b/src/System.Collections/src/System/Collections/Generic/HashSet.cs
@@ -1150,7 +1150,7 @@ namespace System.Collections.Generic
}
// Able to increase capacity; copy elements to larger array and rehash
- SetCapacity(newSize, false);
+ SetCapacity(newSize);
}
/// <summary>
@@ -1158,7 +1158,7 @@ namespace System.Collections.Generic
/// *must* be a prime. It is very likely that you want to call IncreaseCapacity()
/// instead of this method.
/// </summary>
- private void SetCapacity(int newSize, bool forceNewHashCodes)
+ private void SetCapacity(int newSize)
{
Debug.Assert(_buckets != null, "SetCapacity called on a set with no elements");
@@ -1168,21 +1168,6 @@ namespace System.Collections.Generic
Array.Copy(_slots, 0, newSlots, 0, _lastIndex);
}
-#if FEATURE_RANDOMIZED_STRING_HASHING
- if (forceNewHashCodes)
- {
- for (int i = 0; i < _lastIndex; i++)
- {
- if (newSlots[i].hashCode != -1)
- {
- newSlots[i].hashCode = InternalGetHashCode(newSlots[i].value);
- }
- }
- }
-#else
- Debug.Assert(!forceNewHashCodes);
-#endif
-
int[] newBuckets = new int[newSize];
for (int i = 0; i < _lastIndex; i++)
{
@@ -1209,18 +1194,13 @@ namespace System.Collections.Generic
int hashCode = InternalGetHashCode(value);
int bucket = hashCode % _buckets.Length;
-#if FEATURE_RANDOMIZED_STRING_HASHING
- int collisionCount = 0;
-#endif
+
for (int i = _buckets[bucket] - 1; i >= 0; i = _slots[i].next)
{
if (_slots[i].hashCode == hashCode && _comparer.Equals(_slots[i].value, value))
{
return false;
}
-#if FEATURE_RANDOMIZED_STRING_HASHING
- collisionCount++;
-#endif
}
int index;
@@ -1247,14 +1227,6 @@ namespace System.Collections.Generic
_count++;
_version++;
-#if FEATURE_RANDOMIZED_STRING_HASHING
- if (collisionCount > HashHelpers.HashCollisionThreshold && HashHelpers.IsWellKnownEqualityComparer(_comparer))
- {
- _comparer = (IEqualityComparer<T>)HashHelpers.GetRandomizedEqualityComparer(_comparer);
- SetCapacity(_buckets.Length, true);
- }
-#endif // FEATURE_RANDOMIZED_STRING_HASHING
-
return true;
}
diff --git a/src/System.Collections/src/System/Collections/Generic/SortedSet.cs b/src/System.Collections/src/System/Collections/Generic/SortedSet.cs
index 331dd64944..f6eba756c5 100644
--- a/src/System.Collections/src/System/Collections/Generic/SortedSet.cs
+++ b/src/System.Collections/src/System/Collections/Generic/SortedSet.cs
@@ -5,6 +5,7 @@
using System.Diagnostics;
using System.Diagnostics.CodeAnalysis;
using System.Runtime.Serialization;
+using Interlocked = System.Threading.Interlocked;
namespace System.Collections.Generic
{
@@ -14,23 +15,29 @@ namespace System.Collections.Generic
// 3. If a node is red, the both its children are black
// 4. Every simple path from a node to a descendant leaf contains the same number of black nodes
//
- // The basic idea of red-black tree is to represent 2-3-4 trees as standard BSTs but to add one extra bit of information
+ // The basic idea of a red-black tree is to represent 2-3-4 trees as standard BSTs but to add one extra bit of information
// per node to encode 3-nodes and 4-nodes.
// 4-nodes will be represented as: B
// R R
// 3 -node will be represented as: B or B
// R B B R
//
- // For a detailed description of the algorithm, take a look at "Algorithm" by Rebert Sedgewick.
+ // For a detailed description of the algorithm, take a look at "Algorithms" by Robert Sedgewick.
+
+ internal enum NodeColor : byte
+ {
+ Black,
+ Red
+ }
internal delegate bool TreeWalkPredicate<T>(SortedSet<T>.Node node);
- internal enum TreeRotation
+ internal enum TreeRotation : byte
{
- Left = 1,
- Right = 2,
- RightLeft = 3,
- LeftRight = 4,
+ Left,
+ LeftRight,
+ Right,
+ RightLeft
}
[SuppressMessage("Microsoft.Naming", "CA1710:IdentifiersShouldHaveCorrectSuffix", Justification = "by design name choice")]
@@ -56,12 +63,14 @@ namespace System.Collections.Generic
private const string CountName = "Count"; // Do not rename (binary serialization)
private const string ItemsName = "Items"; // Do not rename (binary serialization)
private const string VersionName = "Version"; // Do not rename (binary serialization)
+
// Needed for enumerator
private const string TreeName = "Tree";
private const string NodeValueName = "Item";
private const string EnumStartName = "EnumStarted";
private const string ReverseName = "Reverse";
private const string EnumVersionName = "EnumVersion";
+
// Needed for TreeSubset
private const string MinName = "Min";
private const string MaxName = "Max";
@@ -108,7 +117,7 @@ namespace System.Collections.Generic
}
return;
}
-
+
int count;
T[] elements = EnumerableHelpers.ToArray(collection, out count);
if (count > 0)
@@ -135,10 +144,7 @@ namespace System.Collections.Generic
}
}
- protected SortedSet(SerializationInfo info, StreamingContext context)
- {
- siInfo = info;
- }
+ protected SortedSet(SerializationInfo info, StreamingContext context) => siInfo = info;
#endregion
@@ -182,7 +188,7 @@ namespace System.Collections.Generic
}
/// <summary>
- /// Does an inorder tree walk and calls the delegate for each node.
+ /// Does an in-order tree walk and calls the delegate for each node.
/// </summary>
/// <param name="action">
/// The delegate to invoke on each node.
@@ -201,7 +207,7 @@ namespace System.Collections.Generic
// Note: It's not strictly necessary to provide the stack capacity, but we don't
// want the stack to unnecessarily allocate arrays as it grows.
- var stack = new Stack<Node>(2 * (int)(Log2(Count + 1)));
+ var stack = new Stack<Node>(2 * (int)Log2(Count + 1));
Node current = root;
while (current != null)
@@ -294,7 +300,7 @@ namespace System.Collections.Generic
{
if (_syncRoot == null)
{
- Threading.Interlocked.CompareExchange(ref _syncRoot, new object(), null);
+ Interlocked.CompareExchange(ref _syncRoot, new object(), null);
}
return _syncRoot;
@@ -315,16 +321,16 @@ namespace System.Collections.Generic
#region ICollection<T> members
- public bool Add(T item) => AddIfNotPresent(item);
+ public bool Add(T item) => AddIfNotPresent(item); // Hack so the implementation can be made virtual
- void ICollection<T>.Add(T item) => AddIfNotPresent(item);
+ void ICollection<T>.Add(T item) => Add(item);
internal virtual bool AddIfNotPresent(T item)
{
if (root == null)
{
// The tree is empty and this is the first item.
- root = new Node(item, isRed: false);
+ root = new Node(item, NodeColor.Black);
count = 1;
version++;
return true;
@@ -350,7 +356,7 @@ namespace System.Collections.Generic
{
// We could have changed root node to red during the search process.
// We need to set it to black before we return.
- root.IsRed = false;
+ root.ColorBlack();
return false;
}
@@ -372,8 +378,8 @@ namespace System.Collections.Generic
}
Debug.Assert(parent != null);
- // ready to insert the new node
- Node node = new Node(item, isRed: true);
+ // We're ready to insert the new node.
+ Node node = new Node(item, NodeColor.Red);
if (order > 0)
{
parent.Right = node;
@@ -383,19 +389,19 @@ namespace System.Collections.Generic
parent.Left = node;
}
- // the new node will be red, so we will need to adjust the colors if parent node is also red
+ // The new node will be red, so we will need to adjust colors if its parent is also red.
if (parent.IsRed)
{
InsertionBalance(node, ref parent, grandParent, greatGrandParent);
}
- // Root node is always black
- root.IsRed = false;
+ // The root node is always black.
+ root.ColorBlack();
++count;
return true;
}
- public bool Remove(T item) => DoRemove(item); // hack so it can be made non-virtual
+ public bool Remove(T item) => DoRemove(item); // Hack so the implementation can be made virtual
internal virtual bool DoRemove(T item)
{
@@ -405,15 +411,15 @@ namespace System.Collections.Generic
}
// Search for a node and then find its successor.
- // Then copy the item from the successor to the matching node and delete the successor.
- // If a node doesn't have a successor, we can replace it with its left child (if not empty.)
+ // Then copy the item from the successor to the matching node, and delete the successor.
+ // If a node doesn't have a successor, we can replace it with its left child (if not empty),
// or delete the matching node.
//
// In top-down implementation, it is important to make sure the node to be deleted is not a 2-node.
// Following code will make sure the node on the path is not a 2-node.
- // even if we don't actually remove from the set, we may be altering its structure (by doing rotations
- // and such). so update version to disable any enumerators/subsets working on it
+ // Even if we don't actually remove from the set, we may be altering its structure (by doing rotations
+ // and such). So update our version to disable any enumerators/subsets working on it.
version++;
Node current = root;
@@ -426,20 +432,20 @@ namespace System.Collections.Generic
{
if (current.Is2Node)
{
- // fix up 2-Node
+ // Fix up 2-node
if (parent == null)
{
- // current is root. Mark it as red
- current.IsRed = true;
+ // `current` is the root. Mark it red.
+ current.ColorRed();
}
else
{
- Node sibling = GetSibling(current, parent);
+ Node sibling = parent.GetSibling(current);
if (sibling.IsRed)
{
// If parent is a 3-node, flip the orientation of the red link.
- // We can achieve this by a single rotation
- // This case is converted to one of other cased below.
+ // We can achieve this by a single rotation.
+ // This case is converted to one of the other cases below.
Debug.Assert(parent.IsBlack);
if (parent.Right == sibling)
{
@@ -450,66 +456,37 @@ namespace System.Collections.Generic
parent.RotateRight();
}
- parent.IsRed = true;
- sibling.IsRed = false; // parent's color
- // sibling becomes child of grandParent or root after rotation. Update link from grandParent or root
- ReplaceChildOfNodeOrRoot(grandParent, parent, sibling);
- // sibling will become grandParent of current node
+ parent.ColorRed();
+ sibling.ColorBlack(); // The red parent can't have black children.
+ // `sibling` becomes the child of `grandParent` or `root` after rotation. Update the link from that node.
+ ReplaceChildOrRoot(grandParent, parent, sibling);
+ // `sibling` will become the grandparent of `current`.
grandParent = sibling;
if (parent == match)
{
parentOfMatch = sibling;
}
- // update sibling, this is necessary for following processing
- sibling = (parent.Left == current) ? parent.Right : parent.Left;
+ sibling = parent.GetSibling(current);
}
Debug.Assert(Node.IsNonNullBlack(sibling));
if (sibling.Is2Node)
{
- Merge2Nodes(parent, current, sibling);
+ parent.Merge2Nodes();
}
else
{
- // current is a 2-node and sibling is either a 3-node or a 4-node.
- // We can change the color of current to red by some rotation.
- TreeRotation rotation = RotationNeeded(parent, current, sibling);
- Node newGrandParent = null;
- switch (rotation)
- {
- case TreeRotation.Right:
- Debug.Assert(parent.Left == sibling);
- Debug.Assert(sibling.Left.IsRed);
- sibling.Left.IsRed = false;
- newGrandParent = parent.RotateRight();
- break;
-
- case TreeRotation.Left:
- Debug.Assert(parent.Right == sibling);
- Debug.Assert(sibling.Right.IsRed);
- sibling.Right.IsRed = false;
- newGrandParent = parent.RotateLeft();
- break;
-
- case TreeRotation.RightLeft:
- Debug.Assert(parent.Right == sibling);
- Debug.Assert(sibling.Left.IsRed);
- newGrandParent = parent.RotateRightLeft();
- break;
-
- case TreeRotation.LeftRight:
- Debug.Assert(parent.Left == sibling);
- Debug.Assert(sibling.Right.IsRed);
- newGrandParent = parent.RotateLeftRight();
- break;
- }
+ // `current` is a 2-node and `sibling` is either a 3-node or a 4-node.
+ // We can change the color of `current` to red by some rotation.
+ Node newGrandParent = parent.Rotate(parent.GetRotation(current, sibling));
+
+ newGrandParent.Color = parent.Color;
+ parent.ColorBlack();
+ current.ColorRed();
- newGrandParent.IsRed = parent.IsRed;
- parent.IsRed = false;
- current.IsRed = true;
- ReplaceChildOfNodeOrRoot(grandParent, parent, newGrandParent);
+ ReplaceChildOrRoot(grandParent, parent, newGrandParent);
if (parent == match)
{
parentOfMatch = newGrandParent;
@@ -519,11 +496,11 @@ namespace System.Collections.Generic
}
}
- // we don't need to compare any more once we found the match
+ // We don't need to compare after we find the match.
int order = foundMatch ? -1 : comparer.Compare(item, current.Item);
if (order == 0)
{
- // save the matching node
+ // Save the matching node.
foundMatch = true;
match = current;
parentOfMatch = parent;
@@ -535,18 +512,14 @@ namespace System.Collections.Generic
current = order < 0 ? current.Left : current.Right;
}
- // move successor to the matching node position and replace links
+ // Move successor to the matching node position and replace links.
if (match != null)
{
ReplaceNode(match, parentOfMatch, parent, grandParent);
--count;
}
- if (root != null)
- {
- root.IsRed = false;
- }
-
+ root?.ColorBlack();
return foundMatch;
}
@@ -557,7 +530,6 @@ namespace System.Collections.Generic
++version;
}
-
public virtual bool Contains(T item) => FindNode(item) != null;
public void CopyTo(T[] array) => CopyTo(array, 0, Count);
@@ -642,7 +614,11 @@ namespace System.Collections.Generic
try
{
- InOrderTreeWalk(node => { objects[index++] = node.Item; return true; });
+ InOrderTreeWalk(node =>
+ {
+ objects[index++] = node.Item;
+ return true;
+ });
}
catch (ArrayTypeMismatchException)
{
@@ -665,8 +641,6 @@ namespace System.Collections.Generic
#region Tree-specific operations
- private static Node GetSibling(Node node, Node parent) => parent.Left == node ? parent.Right : parent.Left;
-
// After calling InsertionBalance, we need to make sure `current` and `parent` are up-to-date.
// It doesn't matter if we keep `grandParent` and `greatGrandParent` up-to-date, because we won't
// need to split again in the next node.
@@ -676,8 +650,8 @@ namespace System.Collections.Generic
Debug.Assert(parent != null);
Debug.Assert(grandParent != null);
- bool parentIsOnRight = (grandParent.Right == parent);
- bool currentIsOnRight = (parent.Right == current);
+ bool parentIsOnRight = grandParent.Right == parent;
+ bool currentIsOnRight = parent.Right == current;
Node newChildOfGreatGrandParent;
if (parentIsOnRight == currentIsOnRight)
@@ -694,35 +668,23 @@ namespace System.Collections.Generic
}
// `grandParent` will become a child of either `parent` of `current`.
- grandParent.IsRed = true;
- newChildOfGreatGrandParent.IsRed = false;
+ grandParent.ColorRed();
+ newChildOfGreatGrandParent.ColorBlack();
- ReplaceChildOfNodeOrRoot(greatGrandParent, grandParent, newChildOfGreatGrandParent);
+ ReplaceChildOrRoot(greatGrandParent, grandParent, newChildOfGreatGrandParent);
}
- private static void Merge2Nodes(Node parent, Node child1, Node child2)
- {
- Debug.Assert(Node.IsNonNullRed(parent));
- // Combine two 2-nodes into a 4-node
- parent.IsRed = false;
- child1.IsRed = true;
- child2.IsRed = true;
- }
-
- // Replace the child of a parent node.
- // If the parent node is null, replace the root.
- private void ReplaceChildOfNodeOrRoot(Node parent, Node child, Node newChild)
+ /// <summary>
+ /// Replaces the child of a parent node, or replaces the root if the parent is <c>null</c>.
+ /// </summary>
+ /// <param name="parent">The (possibly <c>null</c>) parent.</param>
+ /// <param name="child">The child node to replace.</param>
+ /// <param name="newChild">The node to replace <paramref name="child"> with.</param>
+ private void ReplaceChildOrRoot(Node parent, Node child, Node newChild)
{
if (parent != null)
{
- if (parent.Left == child)
- {
- parent.Left = newChild;
- }
- else
- {
- parent.Right = newChild;
- }
+ parent.ReplaceChild(child, newChild);
}
else
{
@@ -730,12 +692,16 @@ namespace System.Collections.Generic
}
}
- // Replace the matching node with its successor.
+ /// <summary>
+ /// Replaces the matching node with its successor.
+ /// </summary>
private void ReplaceNode(Node match, Node parentOfMatch, Node successor, Node parentOfSuccessor)
{
+ Debug.Assert(match != null);
+
if (successor == match)
{
- // this node has no successor, should only happen if right child of matching node is null.
+ // This node has no successor. This can only happen if the right child of the match is null.
Debug.Assert(match.Right == null);
successor = match.Left;
}
@@ -745,14 +711,11 @@ namespace System.Collections.Generic
Debug.Assert(successor.Left == null);
Debug.Assert((successor.Right == null && successor.IsRed) || (successor.Right.IsRed && successor.IsBlack));
- if (successor.Right != null)
- {
- successor.Right.IsRed = false;
- }
+ successor.Right?.ColorBlack();
if (parentOfSuccessor != match)
{
- // detach successor from its parent and set its right child
+ // Detach the successor from its parent and set its right child.
parentOfSuccessor.Left = successor.Right;
successor.Right = match.Right;
}
@@ -762,10 +725,10 @@ namespace System.Collections.Generic
if (successor != null)
{
- successor.IsRed = match.IsRed;
+ successor.Color = match.Color;
}
- ReplaceChildOfNodeOrRoot(parentOfMatch, match, successor);
+ ReplaceChildOrRoot(parentOfMatch, match, successor);
}
internal virtual Node FindNode(T item)
@@ -779,15 +742,26 @@ namespace System.Collections.Generic
return current;
}
- current = (order < 0) ? current.Left : current.Right;
+ current = order < 0 ? current.Left : current.Right;
}
return null;
}
- // Used for bithelpers. Note that this implementation is completely different
- // from the Subset's. The two should not be mixed. This indexes as if the tree were an array.
- // http://en.wikipedia.org/wiki/Binary_Tree#Methods_for_storing_binary_trees
+ /// <summary>
+ /// Searches for an item and returns its zero-based index in this set.
+ /// </summary>
+ /// <param name="item">The item.</param>
+ /// <returns>The item's zero-based index in this set, or -1 if it isn't found.</returns>
+ /// <remarks>
+ /// <para>
+ /// This implementation is based off of http://en.wikipedia.org/wiki/Binary_Tree#Methods_for_storing_binary_trees.
+ /// </para>
+ /// <para>
+ /// This method is used with the <see cref="BitHelper"/> class. Note that this implementation is
+ /// completely different from <see cref="TreeSubSet"/>'s, and that the two should not be mixed.
+ /// </para>
+ /// </remarks>
internal virtual int InternalIndexOf(T item)
{
Node current = root;
@@ -800,8 +774,8 @@ namespace System.Collections.Generic
return count;
}
- current = (order < 0) ? current.Left : current.Right;
- count = (order < 0) ? (2 * count + 1) : (2 * count + 2);
+ current = order < 0 ? current.Left : current.Right;
+ count = order < 0 ? (2 * count + 1) : (2 * count + 2);
}
return -1;
@@ -837,25 +811,12 @@ namespace System.Collections.Generic
internal void UpdateVersion() => ++version;
/// <summary>
- /// Testing counter that can track rotations.
- /// </summary>
- private static TreeRotation RotationNeeded(Node parent, Node current, Node sibling)
- {
- Debug.Assert(Node.IsNonNullRed(sibling.Left) || Node.IsNonNullRed(sibling.Right));
-
- bool currentIsLeftChild = parent.Left == current;
- return Node.IsNonNullRed(sibling.Left) ?
- (currentIsLeftChild ? TreeRotation.RightLeft : TreeRotation.Right) :
- (currentIsLeftChild ? TreeRotation.Left : TreeRotation.LeftRight);
- }
-
- /// <summary>
- /// Used for deep equality of SortedSet testing.
+ /// Returns an <see cref="IEqualityComparer{T}"/> object that can be used to create a collection that contains individual sets.
/// </summary>
public static IEqualityComparer<SortedSet<T>> CreateSetComparer() => CreateSetComparer(memberEqualityComparer: null);
/// <summary>
- /// Creates a new set comparer for this set, where this set's members' equality is defined by the specified comparer.
+ /// Returns an <see cref="IEqualityComparer{T}"/> object, according to a specified comparer, that can be used to create a collection that contains individual sets.
/// </summary>
public static IEqualityComparer<SortedSet<T>> CreateSetComparer(IEqualityComparer<T> memberEqualityComparer)
{
@@ -871,7 +832,6 @@ namespace System.Collections.Generic
/// <returns><c>true</c> if the sets have equal contents; otherwise, <c>false</c>.</returns>
internal static bool SortedSetEquals(SortedSet<T> set1, SortedSet<T> set2, IComparer<T> comparer)
{
- // Handle null cases first.
if (set1 == null)
{
return set2 == null;
@@ -887,7 +847,7 @@ namespace System.Collections.Generic
{
return set1.Count == set2.Count && set1.SetEquals(set2);
}
-
+
bool found = false;
foreach (T item1 in set1)
{
@@ -909,10 +869,14 @@ namespace System.Collections.Generic
return true;
}
+ /// <summary>
+ /// Determines whether two <see cref="SortedSet{T}"/> instances have the same comparer.
+ /// </summary>
+ /// <param name="other">The other <see cref="SortedSet{T}"/>.</param>
+ /// <returns>A value indicating whether both sets have the same comparer.</returns>
private bool HasEqualComparer(SortedSet<T> other)
{
- // Both comparers will most commonly be the default comparer.
- // Avoid a virtual method call to Equals() in that case.
+ // Commonly, both comparers will be the default comparer (and reference-equal). Avoid a virtual method call to Equals() in that case.
return Comparer == other.Comparer || Comparer.Equals(other.Comparer);
}
@@ -927,29 +891,29 @@ namespace System.Collections.Generic
throw new ArgumentNullException(nameof(other));
}
- SortedSet<T> s = other as SortedSet<T>;
- TreeSubSet t = this as TreeSubSet;
+ SortedSet<T> asSorted = other as SortedSet<T>;
+ TreeSubSet treeSubset = this as TreeSubSet;
- if (t != null)
+ if (treeSubset != null)
VersionCheck();
- if (s != null && t == null && count == 0)
+ if (asSorted != null && treeSubset == null && count == 0)
{
- SortedSet<T> dummy = new SortedSet<T>(s, comparer);
+ SortedSet<T> dummy = new SortedSet<T>(asSorted, comparer);
root = dummy.root;
count = dummy.count;
version++;
return;
}
- if (s != null && t == null && HasEqualComparer(s) && (s.Count > this.Count / 2))
+ // This actually hurts if N is much greater than M. The / 2 is arbitrary.
+ if (asSorted != null && treeSubset == null && HasEqualComparer(asSorted) && (asSorted.Count > this.Count / 2))
{
- // This actually hurts if N is much greater than M. The /2 is arbitrary.
// First do a merge sort to an array.
- T[] merged = new T[s.Count + this.Count];
+ T[] merged = new T[asSorted.Count + this.Count];
int c = 0;
Enumerator mine = this.GetEnumerator();
- Enumerator theirs = s.GetEnumerator();
+ Enumerator theirs = asSorted.GetEnumerator();
bool mineEnded = !mine.MoveNext(), theirsEnded = !theirs.MoveNext();
while (!mineEnded && !theirsEnded)
{
@@ -978,7 +942,8 @@ namespace System.Collections.Generic
do
{
merged[c++] = remaining.Current;
- } while (remaining.MoveNext());
+ }
+ while (remaining.MoveNext());
}
// now merged has all c elements
@@ -1017,49 +982,48 @@ namespace System.Collections.Generic
// Only some base cases are handled below.
int size = endIndex - startIndex + 1;
- if (size == 0)
- {
- return null;
- }
+ Node root;
- Node root = null;
- if (size == 1)
- {
- root = new Node(arr[startIndex], isRed: false);
- if (redNode != null)
- {
- root.Left = redNode;
- }
- }
- else if (size == 2)
- {
- root = new Node(arr[startIndex], isRed: false);
- root.Right = new Node(arr[endIndex], isRed: false);
- root.Right.IsRed = true;
- if (redNode != null)
- {
- root.Left = redNode;
- }
- }
- else if (size == 3)
+ switch (size)
{
- root = new Node(arr[startIndex + 1], isRed: false);
- root.Left = new Node(arr[startIndex], isRed: false);
- root.Right = new Node(arr[endIndex], isRed: false);
- if (redNode != null)
- {
- root.Left.Left = redNode;
- }
- }
- else
- {
- int midpt = ((startIndex + endIndex) / 2);
- root = new Node(arr[midpt], isRed: false);
- root.Left = ConstructRootFromSortedArray(arr, startIndex, midpt - 1, redNode);
- root.Right = size % 2 == 0 ?
- ConstructRootFromSortedArray(arr, midpt + 2, endIndex, new Node(arr[midpt + 1], isRed: true)) :
- ConstructRootFromSortedArray(arr, midpt + 1, endIndex, null);
+ case 0:
+ return null;
+ case 1:
+ root = new Node(arr[startIndex], NodeColor.Black);
+ if (redNode != null)
+ {
+ root.Left = redNode;
+ }
+ break;
+ case 2:
+ root = new Node(arr[startIndex], NodeColor.Black);
+ root.Right = new Node(arr[endIndex], NodeColor.Black);
+ root.Right.ColorRed();
+ if (redNode != null)
+ {
+ root.Left = redNode;
+ }
+ break;
+ case 3:
+ root = new Node(arr[startIndex + 1], NodeColor.Black);
+ root.Left = new Node(arr[startIndex], NodeColor.Black);
+ root.Right = new Node(arr[endIndex], NodeColor.Black);
+ if (redNode != null)
+ {
+ root.Left.Left = redNode;
+ }
+ break;
+ default:
+ int midpt = ((startIndex + endIndex) / 2);
+ root = new Node(arr[midpt], NodeColor.Black);
+ root.Left = ConstructRootFromSortedArray(arr, startIndex, midpt - 1, redNode);
+ root.Right = size % 2 == 0 ?
+ ConstructRootFromSortedArray(arr, midpt + 2, endIndex, new Node(arr[midpt + 1], NodeColor.Red)) :
+ ConstructRootFromSortedArray(arr, midpt + 1, endIndex, null);
+ break;
+
}
+
return root;
}
@@ -1079,18 +1043,19 @@ namespace System.Collections.Generic
// HashSet<T> optimizations can't be done until equality comparers and comparers are related
// Technically, this would work as well with an ISorted<T>
- SortedSet<T> s = other as SortedSet<T>;
- TreeSubSet t = this as TreeSubSet;
- if (t != null)
+ SortedSet<T> asSorted = other as SortedSet<T>;
+ TreeSubSet treeSubset = this as TreeSubSet;
+
+ if (treeSubset != null)
VersionCheck();
- // only let this happen if i am also a SortedSet, not a SubSet
- if (s != null && t == null && HasEqualComparer(s))
+
+ if (asSorted != null && treeSubset == null && HasEqualComparer(asSorted))
{
- // first do a merge sort to an array.
+ // First do a merge sort to an array.
T[] merged = new T[this.Count];
int c = 0;
Enumerator mine = this.GetEnumerator();
- Enumerator theirs = s.GetEnumerator();
+ Enumerator theirs = asSorted.GetEnumerator();
bool mineEnded = !mine.MoveNext(), theirsEnded = !theirs.MoveNext();
T max = Max;
T min = Min;
@@ -1144,7 +1109,7 @@ namespace System.Collections.Generic
Clear();
foreach (T item in toSave)
{
- AddIfNotPresent(item);
+ Add(item);
}
}
@@ -1168,8 +1133,8 @@ namespace System.Collections.Generic
if (asSorted != null && HasEqualComparer(asSorted))
{
- // outside range, no point doing anything
- if (!(comparer.Compare(asSorted.Max, Min) < 0 || comparer.Compare(asSorted.Min, Max) > 0))
+ // Outside range, no point in doing anything
+ if (comparer.Compare(asSorted.Max, Min) >= 0 && comparer.Compare(asSorted.Min, Max) <= 0)
{
T min = Min;
T max = Max;
@@ -1280,11 +1245,9 @@ namespace System.Collections.Generic
}
else
{
- // worst case: mark every element in my set and see if I've counted all
- // O(MlogN)
-
+ // Worst case: I mark every element in my set and see if I've counted all of them. O(M log N).
ElementCount result = CheckUniqueAndUnfoundElements(other, false);
- return (result.UniqueCount == Count && result.UnfoundCount >= 0);
+ return result.UniqueCount == Count && result.UnfoundCount >= 0;
}
}
@@ -1321,10 +1284,9 @@ namespace System.Collections.Generic
return IsSubsetOfSortedSetWithSameComparer(asSorted);
}
- // worst case: mark every element in my set and see if I've counted all
- // O(MlogN).
+ // Worst case: I mark every element in my set and see if I've counted all of them. O(M log N).
ElementCount result = CheckUniqueAndUnfoundElements(other, false);
- return (result.UniqueCount == Count && result.UnfoundCount > 0);
+ return result.UniqueCount == Count && result.UnfoundCount > 0;
}
public bool IsSupersetOf(IEnumerable<T> other)
@@ -1385,12 +1347,11 @@ namespace System.Collections.Generic
return true;
}
- // worst case: mark every element in my set and see if I've counted all
- // O(MlogN)
+ // Worst case: I mark every element in my set and see if I've counted all of them. O(M log N).
// slight optimization, put it into a HashSet and then check can do it in O(N+M)
// but slower in better cases + wastes space
ElementCount result = CheckUniqueAndUnfoundElements(other, true);
- return (result.UniqueCount < Count && result.UnfoundCount == 0);
+ return result.UniqueCount < Count && result.UnfoundCount == 0;
}
public bool SetEquals(IEnumerable<T> other)
@@ -1419,10 +1380,9 @@ namespace System.Collections.Generic
return mineEnded && theirsEnded;
}
- // worst case: mark every element in my set and see if I've counted all
- // O(N) by size of other
+ // Worst case: I mark every element in my set and see if I've counted all of them. O(size of the other collection).
ElementCount result = CheckUniqueAndUnfoundElements(other, true);
- return (result.UniqueCount == Count && result.UnfoundCount == 0);
+ return result.UniqueCount == Count && result.UnfoundCount == 0;
}
public bool Overlaps(IEnumerable<T> other)
@@ -1561,7 +1521,7 @@ namespace System.Collections.Generic
return true;
});
- // reverse breadth first to (try to) incur low cost
+ // Enumerate the results of the breadth-first walk in reverse in an attempt to lower cost.
int actuallyRemoved = 0;
for (int i = matches.Count - 1; i >= 0; i--)
{
@@ -1600,8 +1560,8 @@ namespace System.Collections.Generic
}
public T Max => MaxInternal;
-
- internal virtual T MaxInternal
+
+ internal virtual T MaxInternal
{
get
{
@@ -1649,10 +1609,7 @@ namespace System.Collections.Generic
}
#endif
- void ISerializable.GetObjectData(SerializationInfo info, StreamingContext context)
- {
- GetObjectData(info, context);
- }
+ void ISerializable.GetObjectData(SerializationInfo info, StreamingContext context) => GetObjectData(info, context);
protected virtual void GetObjectData(SerializationInfo info, StreamingContext context)
{
@@ -1673,12 +1630,9 @@ namespace System.Collections.Generic
}
}
- void IDeserializationCallback.OnDeserialization(Object sender)
- {
- OnDeserialization(sender);
- }
+ void IDeserializationCallback.OnDeserialization(object sender) => OnDeserialization(sender);
- protected virtual void OnDeserialization(Object sender)
+ protected virtual void OnDeserialization(object sender)
{
if (comparer != null)
{
@@ -1724,33 +1678,44 @@ namespace System.Collections.Generic
[Serializable]
internal sealed class Node
{
- public Node(T item, bool isRed)
+ public Node(T item, NodeColor color)
{
- // The default color is red since we usually don't need to create a black node directly.
Item = item;
- IsRed = isRed;
+ Color = color;
}
+ public static bool IsNonNullBlack(Node node) => node != null && node.IsBlack;
+
+ public static bool IsNonNullRed(Node node) => node != null && node.IsRed;
+
+ public static bool IsNullOrBlack(Node node) => node == null || node.IsBlack;
+
public T Item { get; set; }
public Node Left { get; set; }
public Node Right { get; set; }
- public bool IsRed { get; set; }
+ public NodeColor Color { get; set; }
- public bool IsBlack => !IsRed;
+ public bool IsBlack => Color == NodeColor.Black;
+
+ public bool IsRed => Color == NodeColor.Red;
public bool Is2Node => IsBlack && IsNullOrBlack(Left) && IsNullOrBlack(Right);
public bool Is4Node => IsNonNullRed(Left) && IsNonNullRed(Right);
+ public void ColorBlack() => Color = NodeColor.Black;
+
+ public void ColorRed() => Color = NodeColor.Red;
+
public Node DeepClone(int count)
{
#if DEBUG
Debug.Assert(count == GetCount());
#endif
-
+
// Breadth-first traversal to recreate nodes, preorder traversal to replicate nodes.
var originalNodes = new Stack<Node>(2 * Log2(count) + 2);
@@ -1791,27 +1756,78 @@ namespace System.Collections.Generic
return newRoot;
}
+ /// <summary>
+ /// Gets the rotation this node should undergo during a removal.
+ /// </summary>
+ public TreeRotation GetRotation(Node current, Node sibling)
+ {
+ Debug.Assert(IsNonNullRed(sibling.Left) || IsNonNullRed(sibling.Right));
#if DEBUG
- public int GetCount() => 1 + (Left?.GetCount() ?? 0) + (Right?.GetCount() ?? 0);
+ Debug.Assert(HasChildren(current, sibling));
#endif
- public Node ShallowClone() => new Node(Item, IsRed);
+ bool currentIsLeftChild = Left == current;
+ return IsNonNullRed(sibling.Left) ?
+ (currentIsLeftChild ? TreeRotation.RightLeft : TreeRotation.Right) :
+ (currentIsLeftChild ? TreeRotation.Left : TreeRotation.LeftRight);
+ }
- public static bool IsNonNullBlack(Node node) => node != null && node.IsBlack;
+ /// <summary>
+ /// Gets the sibling of one of this node's children.
+ /// </summary>
+ public Node GetSibling(Node node)
+ {
+ Debug.Assert(node != null);
+ Debug.Assert(node == Left ^ node == Right);
- public static bool IsNonNullRed(Node node) => node != null && node.IsRed;
+ return node == Left ? Right : Left;
+ }
- public static bool IsNullOrBlack(Node node) => node == null || node.IsBlack;
+ public Node ShallowClone() => new Node(Item, Color);
public void Split4Node()
{
Debug.Assert(Left != null);
Debug.Assert(Right != null);
- IsRed = true;
- Left.IsRed = Right.IsRed = false;
+ ColorRed();
+ Left.ColorBlack();
+ Right.ColorBlack();
}
+ /// <summary>
+ /// Does a rotation on this tree. May change the color of a grandchild from red to black.
+ /// </summary>
+ public Node Rotate(TreeRotation rotation)
+ {
+ Node removeRed;
+ switch (rotation)
+ {
+ case TreeRotation.Right:
+ removeRed = Left.Left;
+ Debug.Assert(removeRed.IsRed);
+ removeRed.ColorBlack();
+ return RotateRight();
+ case TreeRotation.Left:
+ removeRed = Right.Right;
+ Debug.Assert(removeRed.IsRed);
+ removeRed.ColorBlack();
+ return RotateLeft();
+ case TreeRotation.RightLeft:
+ Debug.Assert(Right.Left.IsRed);
+ return RotateRightLeft();
+ case TreeRotation.LeftRight:
+ Debug.Assert(Left.Right.IsRed);
+ return RotateLeftRight();
+ default:
+ Debug.Fail($"{nameof(rotation)}: {rotation} is not a defined {nameof(TreeRotation)} value.");
+ return null;
+ }
+ }
+
+ /// <summary>
+ /// Does a left rotation on this tree, making this node the new left child of the current right child.
+ /// </summary>
public Node RotateLeft()
{
Node child = Right;
@@ -1820,6 +1836,9 @@ namespace System.Collections.Generic
return child;
}
+ /// <summary>
+ /// Does a left-right rotation on this tree. The left child is rotated left, then this node is rotated right.
+ /// </summary>
public Node RotateLeftRight()
{
Node child = Left;
@@ -1832,6 +1851,9 @@ namespace System.Collections.Generic
return grandChild;
}
+ /// <summary>
+ /// Does a right rotation on this tree, making this node the new right child of the current left child.
+ /// </summary>
public Node RotateRight()
{
Node child = Left;
@@ -1840,6 +1862,9 @@ namespace System.Collections.Generic
return child;
}
+ /// <summary>
+ /// Does a right-left rotation on this tree. The right child is rotated right, then this node is rotated left.
+ /// </summary>
public Node RotateRightLeft()
{
Node child = Right;
@@ -1851,13 +1876,63 @@ namespace System.Collections.Generic
grandChild.Right = child;
return grandChild;
}
+
+ /// <summary>
+ /// Combines two 2-nodes into a 4-node.
+ /// </summary>
+ public void Merge2Nodes()
+ {
+ Debug.Assert(IsRed);
+ Debug.Assert(Left.Is2Node);
+ Debug.Assert(Right.Is2Node);
+
+ // Combine two 2-nodes into a 4-node.
+ ColorBlack();
+ Left.ColorRed();
+ Right.ColorRed();
+ }
+
+ /// <summary>
+ /// Replaces a child of this node with a new node.
+ /// </summary>
+ /// <param name="child">The child to replace.</param>
+ /// <param name="newChild">The node to replace <paramref name="child"/> with.</param>
+ public void ReplaceChild(Node child, Node newChild)
+ {
+#if DEBUG
+ Debug.Assert(HasChild(child));
+#endif
+
+ if (Left == child)
+ {
+ Left = newChild;
+ }
+ else
+ {
+ Right = newChild;
+ }
+ }
+
+#if DEBUG
+ private int GetCount() => 1 + (Left?.GetCount() ?? 0) + (Right?.GetCount() ?? 0);
+
+ private bool HasChild(Node child) => child == Left || child == Right;
+
+ private bool HasChildren(Node child1, Node child2)
+ {
+ Debug.Assert(child1 != child2);
+
+ return (Left == child1 && Right == child2)
+ || (Left == child2 && Right == child1);
+ }
+#endif
}
[SuppressMessage("Microsoft.Performance", "CA1815:OverrideEqualsAndOperatorEqualsOnValueTypes", Justification = "not an expected scenario")]
[Serializable]
public struct Enumerator : IEnumerator<T>, IEnumerator, ISerializable, IDeserializationCallback
{
- private static readonly Node s_dummyNode = new Node(default(T), isRed: true);
+ private static readonly Node s_dummyNode = new Node(default(T), NodeColor.Red);
private SortedSet<T> _tree;
private int _version;
@@ -1868,27 +1943,17 @@ namespace System.Collections.Generic
private bool _reverse;
internal Enumerator(SortedSet<T> set)
+ : this(set, reverse: false)
{
- _tree = set;
- _tree.VersionCheck(); // make sure that the underlying subset has not been changed since
-
- _version = _tree.version;
-
- // 2lg(n + 1) is the maximum height
- _stack = new Stack<Node>(2 * (int)Log2(set.Count + 1));
- _current = null;
- _reverse = false;
-
- Initialize();
}
internal Enumerator(SortedSet<T> set, bool reverse)
{
_tree = set;
- _tree.VersionCheck(); // make sure that the underlying subset has not been changed since
- _version = _tree.version;
+ set.VersionCheck();
+ _version = set.version;
- // 2lg(n + 1) is the maximum height
+ // 2 log(n + 1) is the maximum height.
_stack = new Stack<Node>(2 * (int)Log2(set.Count + 1));
_current = null;
_reverse = reverse;
@@ -1901,7 +1966,7 @@ namespace System.Collections.Generic
throw new PlatformNotSupportedException();
}
- void IDeserializationCallback.OnDeserialization(Object sender)
+ void IDeserializationCallback.OnDeserialization(object sender)
{
throw new PlatformNotSupportedException();
}
diff --git a/src/System.Collections/tests/Generic/LinkedList/LinkedList.Generic.Tests.Find.cs b/src/System.Collections/tests/Generic/LinkedList/LinkedList.Generic.Tests.Find.cs
index cc91308e81..b93e7c62f1 100644
--- a/src/System.Collections/tests/Generic/LinkedList/LinkedList.Generic.Tests.Find.cs
+++ b/src/System.Collections/tests/Generic/LinkedList/LinkedList.Generic.Tests.Find.cs
@@ -30,14 +30,14 @@ namespace System.Collections.Tests
//[] Call Find an empty collection
linkedList = new LinkedList<T>();
- Assert.Null(linkedList.Find(headItems[0])); //"Err_2899hjaied Expected Find to return false with a non null item on a empty collection"
- Assert.Null(linkedList.Find(default(T))); //"Err_5808ajiea Expected Find to return false with a null item on a empty collection"
+ Assert.Null(linkedList.Find(headItems[0])); //"Err_2899hjaied Expected Find to return false with a non null item on an empty collection"
+ Assert.Null(linkedList.Find(default(T))); //"Err_5808ajiea Expected Find to return false with a null item on an empty collection"
//[] Call Find on a collection with one item in it
linkedList = new LinkedList<T>();
linkedList.AddLast(headItems[0]);
- Assert.Null(linkedList.Find(headItems[1])); //"Err_2899hjaied Expected Find to return false with a non null item on a empty collection size=1"
- Assert.Null(linkedList.Find(default(T))); //"Err_5808ajiea Expected Find to return false with a null item on a empty collection size=1"
+ Assert.Null(linkedList.Find(headItems[1])); //"Err_2899hjaied Expected Find to return false with a non null item on an empty collection size=1"
+ Assert.Null(linkedList.Find(default(T))); //"Err_5808ajiea Expected Find to return false with a null item on an empty collection size=1"
VerifyFind(linkedList, new T[] { headItems[0] });
//[] Call Find on a collection with two items in it
@@ -129,4 +129,4 @@ namespace System.Collections.Tests
VerifyFind(linkedList, tempItems);
}
}
-} \ No newline at end of file
+}
diff --git a/src/System.Collections/tests/Generic/LinkedList/LinkedList.Generic.Tests.FindLast.cs b/src/System.Collections/tests/Generic/LinkedList/LinkedList.Generic.Tests.FindLast.cs
index 4513807420..5769211e23 100644
--- a/src/System.Collections/tests/Generic/LinkedList/LinkedList.Generic.Tests.FindLast.cs
+++ b/src/System.Collections/tests/Generic/LinkedList/LinkedList.Generic.Tests.FindLast.cs
@@ -37,14 +37,14 @@ namespace System.Collections.Tests
//[] Call FindLast an empty collection
linkedList = new LinkedList<T>();
- Assert.Null(linkedList.FindLast(headItems[0])); //"Err_2899hjaied Expected FindLast to return false with a non null item on a empty collection"
- Assert.Null(linkedList.FindLast(default(T))); //"Err_5808ajiea Expected FindLast to return false with a null item on a empty collection"
+ Assert.Null(linkedList.FindLast(headItems[0])); //"Err_2899hjaied Expected FindLast to return false with a non null item on an empty collection"
+ Assert.Null(linkedList.FindLast(default(T))); //"Err_5808ajiea Expected FindLast to return false with a null item on an empty collection"
//[] Call FindLast on a collection with one item in it
linkedList = new LinkedList<T>();
linkedList.AddLast(headItems[0]);
- Assert.Null(linkedList.FindLast(headItems[1])); //"Err_2899hjaied Expected FindLast to return false with a non null item on a empty collection size=1"
- Assert.Null(linkedList.FindLast(default(T))); //"Err_5808ajiea Expected FindLast to return false with a null item on a empty collection size=1"
+ Assert.Null(linkedList.FindLast(headItems[1])); //"Err_2899hjaied Expected FindLast to return false with a non null item on an empty collection size=1"
+ Assert.Null(linkedList.FindLast(default(T))); //"Err_5808ajiea Expected FindLast to return false with a null item on an empty collection size=1"
VerifyFindLast(linkedList, new T[] { headItems[0] });
//[] Call FindLast on a collection with two items in it
@@ -127,4 +127,4 @@ namespace System.Collections.Tests
VerifyFindLast(linkedList, temp);
}
}
-} \ No newline at end of file
+}
diff --git a/src/System.ComponentModel.Annotations/ref/System.ComponentModel.Annotations.csproj b/src/System.ComponentModel.Annotations/ref/System.ComponentModel.Annotations.csproj
index e7dd01ee56..9b96eb41e0 100644
--- a/src/System.ComponentModel.Annotations/ref/System.ComponentModel.Annotations.csproj
+++ b/src/System.ComponentModel.Annotations/ref/System.ComponentModel.Annotations.csproj
@@ -3,7 +3,10 @@
<Import Project="$([MSBuild]::GetDirectoryNameOfFileAbove($(MSBuildThisFileDirectory), dir.props))\dir.props" />
<PropertyGroup>
<ProjectGuid>{C4D6F1F4-DC7E-4756-9A88-171A8B1F1E26}</ProjectGuid>
- <IsPartialFacadeAssembly Condition="'$(TargetGroup)' == 'netfx'">true</IsPartialFacadeAssembly>
+ <!-- Must match version supported by frameworks which support 4.2.* inbox.
+ Can be removed when API is added and this assembly is versioned to 4.3.* -->
+ <AssemblyVersion Condition="'$(TargetsNetFx)' != 'true'">4.2.0.0</AssemblyVersion>
+ <IsPartialFacadeAssembly Condition="'$(TargetsNetFx)' == 'true'">true</IsPartialFacadeAssembly>
</PropertyGroup>
<PropertyGroup Condition="'$(Configuration)|$(Platform)' == 'netfx-Debug|AnyCPU'" />
<PropertyGroup Condition="'$(Configuration)|$(Platform)' == 'netfx-Release|AnyCPU'" />
diff --git a/src/System.ComponentModel.Annotations/src/System/ComponentModel/DataAnnotations/AssociationAttribute.cs b/src/System.ComponentModel.Annotations/src/System/ComponentModel/DataAnnotations/AssociationAttribute.cs
index 25fe1c0b00..5f62287183 100644
--- a/src/System.ComponentModel.Annotations/src/System/ComponentModel/DataAnnotations/AssociationAttribute.cs
+++ b/src/System.ComponentModel.Annotations/src/System/ComponentModel/DataAnnotations/AssociationAttribute.cs
@@ -14,11 +14,6 @@ namespace System.ComponentModel.DataAnnotations
[Obsolete("This attribute is no longer in use and will be ignored if applied.")]
public sealed class AssociationAttribute : Attribute
{
- private string _name;
- private string _thisKey;
- private string _otherKey;
- private bool _isForeignKey;
-
/// <summary>
/// Full form of constructor
/// </summary>
@@ -30,78 +25,50 @@ namespace System.ComponentModel.DataAnnotations
/// on the other side of the association</param>
public AssociationAttribute(string name, string thisKey, string otherKey)
{
- _name = name;
- _thisKey = thisKey;
- _otherKey = otherKey;
+ Name = name;
+ ThisKey = thisKey;
+ OtherKey = otherKey;
}
/// <summary>
/// Gets the name of the association. For bi-directional associations, the name must
/// be the same on both sides of the association
/// </summary>
- public string Name
- {
- get { return _name; }
- }
+ public string Name { get; }
/// <summary>
/// Gets a comma separated list of the property names of the key values
/// on this side of the association
/// </summary>
- public string ThisKey
- {
- get { return _thisKey; }
- }
+ public string ThisKey { get; }
/// <summary>
/// Gets a comma separated list of the property names of the key values
/// on the other side of the association
/// </summary>
- public string OtherKey
- {
- get { return _otherKey; }
- }
+ public string OtherKey { get; }
/// <summary>
/// Gets or sets a value indicating whether this association member represents
/// the foreign key side of an association
/// </summary>
- public bool IsForeignKey
- {
- get { return _isForeignKey; }
- set { _isForeignKey = value; }
- }
+ public bool IsForeignKey { get; set; }
/// <summary>
/// Gets the collection of individual key members specified in the ThisKey string.
/// </summary>
- public IEnumerable<string> ThisKeyMembers
- {
- get
- {
- return GetKeyMembers(ThisKey);
- }
- }
+ public IEnumerable<string> ThisKeyMembers => GetKeyMembers(ThisKey);
/// <summary>
/// Gets the collection of individual key members specified in the OtherKey string.
/// </summary>
- public IEnumerable<string> OtherKeyMembers
- {
- get
- {
- return GetKeyMembers(OtherKey);
- }
- }
+ public IEnumerable<string> OtherKeyMembers => GetKeyMembers(OtherKey);
/// <summary>
/// Parses the comma delimited key specified
/// </summary>
/// <param name="key">The key to parse</param>
/// <returns>Array of individual key members</returns>
- private static string[] GetKeyMembers(string key)
- {
- return key.Replace(" ", string.Empty).Split(',');
- }
+ private static string[] GetKeyMembers(string key) => key.Replace(" ", string.Empty).Split(',');
}
}
diff --git a/src/System.ComponentModel.Annotations/src/System/ComponentModel/DataAnnotations/CompareAttribute.cs b/src/System.ComponentModel.Annotations/src/System/ComponentModel/DataAnnotations/CompareAttribute.cs
index fdc23ab732..38e5f98cba 100644
--- a/src/System.ComponentModel.Annotations/src/System/ComponentModel/DataAnnotations/CompareAttribute.cs
+++ b/src/System.ComponentModel.Annotations/src/System/ComponentModel/DataAnnotations/CompareAttribute.cs
@@ -21,17 +21,15 @@ namespace System.ComponentModel.DataAnnotations
OtherProperty = otherProperty;
}
- public string OtherProperty { get; private set; }
+ public string OtherProperty { get; }
public string OtherPropertyDisplayName { get; internal set; }
public override bool RequiresValidationContext => true;
- public override string FormatErrorMessage(string name)
- {
- return string.Format(CultureInfo.CurrentCulture, ErrorMessageString, name,
- OtherPropertyDisplayName ?? OtherProperty);
- }
+ public override string FormatErrorMessage(string name) =>
+ string.Format(
+ CultureInfo.CurrentCulture, ErrorMessageString, name, OtherPropertyDisplayName ?? OtherProperty);
protected override ValidationResult IsValid(object value, ValidationContext validationContext)
{
@@ -53,14 +51,16 @@ namespace System.ComponentModel.DataAnnotations
{
if (OtherPropertyDisplayName == null)
{
- OtherPropertyDisplayName = GetDisplayNameForProperty(validationContext.ObjectType, otherPropertyInfo);
+ OtherPropertyDisplayName = GetDisplayNameForProperty(otherPropertyInfo);
}
+
return new ValidationResult(FormatErrorMessage(validationContext.DisplayName));
}
+
return null;
}
- private string GetDisplayNameForProperty(Type containerType, PropertyInfo property)
+ private string GetDisplayNameForProperty(PropertyInfo property)
{
var attributes = CustomAttributeExtensions.GetCustomAttributes(property, true);
var display = attributes.OfType<DisplayAttribute>().FirstOrDefault();
@@ -71,10 +71,5 @@ namespace System.ComponentModel.DataAnnotations
return OtherProperty;
}
-
- private static bool IsPublic(PropertyInfo p)
- {
- return (p.GetMethod != null && p.GetMethod.IsPublic) || (p.SetMethod != null && p.SetMethod.IsPublic);
- }
}
}
diff --git a/src/System.ComponentModel.Annotations/src/System/ComponentModel/DataAnnotations/CustomValidationAttribute.cs b/src/System.ComponentModel.Annotations/src/System/ComponentModel/DataAnnotations/CustomValidationAttribute.cs
index 53661bc2ee..fa4561fa20 100644
--- a/src/System.ComponentModel.Annotations/src/System/ComponentModel/DataAnnotations/CustomValidationAttribute.cs
+++ b/src/System.ComponentModel.Annotations/src/System/ComponentModel/DataAnnotations/CustomValidationAttribute.cs
@@ -60,8 +60,6 @@ namespace System.ComponentModel.DataAnnotations
#region Member Fields
private readonly Lazy<string> _malformedErrorMessage;
- private readonly string _method;
- private readonly Type _validatorType;
private bool _isSingleArgumentMethod;
private string _lastMessage;
private MethodInfo _methodInfo;
@@ -76,7 +74,7 @@ namespace System.ComponentModel.DataAnnotations
/// specified type.
/// </summary>
/// <remarks>
- /// An invalid <paramref name="validatorType" /> or <paramref name="Method" /> will be cause
+ /// An invalid <paramref name="validatorType" /> or <paramref name="method" /> will be cause
/// <see cref="IsValid(object, ValidationContext)" />> to return a <see cref="ValidationResult" />
/// and <see cref="ValidationAttribute.FormatErrorMessage" /> to return a summary error message.
/// </remarks>
@@ -88,8 +86,8 @@ namespace System.ComponentModel.DataAnnotations
public CustomValidationAttribute(Type validatorType, string method)
: base(() => SR.CustomValidationAttribute_ValidationError)
{
- _validatorType = validatorType;
- _method = method;
+ ValidatorType = validatorType;
+ Method = method;
_malformedErrorMessage = new Lazy<string>(CheckAttributeWellFormed);
}
@@ -100,18 +98,12 @@ namespace System.ComponentModel.DataAnnotations
/// <summary>
/// Gets the type that contains the validation method identified by <see cref="Method" />.
/// </summary>
- public Type ValidatorType
- {
- get { return _validatorType; }
- }
+ public Type ValidatorType { get; }
/// <summary>
/// Gets the name of the method in <see cref="ValidatorType" /> to invoke to perform validation.
/// </summary>
- public string Method
- {
- get { return _method; }
- }
+ public string Method { get; }
public override bool RequiresValidationContext
{
@@ -154,8 +146,8 @@ namespace System.ComponentModel.DataAnnotations
SR.CustomValidationAttribute_Type_Conversion_Failed,
(value != null ? value.GetType().ToString() : "null"),
_firstParameterType,
- _validatorType,
- _method));
+ ValidatorType,
+ Method));
}
// Invoke the method. Catch TargetInvocationException merely to unwrap it.
@@ -212,10 +204,7 @@ namespace System.ComponentModel.DataAnnotations
/// Checks whether the current attribute instance itself is valid for use.
/// </summary>
/// <returns>The error message why it is not well-formed, null if it is well-formed.</returns>
- private string CheckAttributeWellFormed()
- {
- return ValidateValidatorTypeParameter() ?? ValidateMethodParameter();
- }
+ private string CheckAttributeWellFormed() => ValidateValidatorTypeParameter() ?? ValidateMethodParameter();
/// <summary>
/// Internal helper to determine whether <see cref="ValidatorType" /> is legal for use.
@@ -223,15 +212,15 @@ namespace System.ComponentModel.DataAnnotations
/// <returns><c>null</c> or the appropriate error message.</returns>
private string ValidateValidatorTypeParameter()
{
- if (_validatorType == null)
+ if (ValidatorType == null)
{
return SR.CustomValidationAttribute_ValidatorType_Required;
}
- if (!_validatorType.IsVisible)
+ if (!ValidatorType.IsVisible)
{
return string.Format(CultureInfo.CurrentCulture,
- SR.CustomValidationAttribute_Type_Must_Be_Public, _validatorType.Name);
+ SR.CustomValidationAttribute_Type_Must_Be_Public, ValidatorType.Name);
}
return null;
@@ -243,27 +232,27 @@ namespace System.ComponentModel.DataAnnotations
/// <returns><c>null</c> or the appropriate error message.</returns>
private string ValidateMethodParameter()
{
- if (string.IsNullOrEmpty(_method))
+ if (string.IsNullOrEmpty(Method))
{
return SR.CustomValidationAttribute_Method_Required;
}
// Named method must be public and static
- var methodInfo = _validatorType.GetRuntimeMethods()
- .SingleOrDefault(m => string.Equals(m.Name, _method, StringComparison.Ordinal)
+ var methodInfo = ValidatorType.GetRuntimeMethods()
+ .SingleOrDefault(m => string.Equals(m.Name, Method, StringComparison.Ordinal)
&& m.IsPublic && m.IsStatic);
if (methodInfo == null)
{
return string.Format(CultureInfo.CurrentCulture,
- SR.CustomValidationAttribute_Method_Not_Found, _method, _validatorType.Name);
+ SR.CustomValidationAttribute_Method_Not_Found, Method, ValidatorType.Name);
}
// Method must return a ValidationResult
if (methodInfo.ReturnType != typeof(ValidationResult))
{
return string.Format(CultureInfo.CurrentCulture,
- SR.CustomValidationAttribute_Method_Must_Return_ValidationResult, _method,
- _validatorType.Name);
+ SR.CustomValidationAttribute_Method_Must_Return_ValidationResult, Method,
+ ValidatorType.Name);
}
ParameterInfo[] parameterInfos = methodInfo.GetParameters();
@@ -272,7 +261,7 @@ namespace System.ComponentModel.DataAnnotations
if (parameterInfos.Length == 0 || parameterInfos[0].ParameterType.IsByRef)
{
return string.Format(CultureInfo.CurrentCulture,
- SR.CustomValidationAttribute_Method_Signature, _method, _validatorType.Name);
+ SR.CustomValidationAttribute_Method_Signature, Method, ValidatorType.Name);
}
// We accept 2 forms:
@@ -285,8 +274,8 @@ namespace System.ComponentModel.DataAnnotations
if ((parameterInfos.Length != 2) || (parameterInfos[1].ParameterType != typeof(ValidationContext)))
{
return string.Format(CultureInfo.CurrentCulture,
- SR.CustomValidationAttribute_Method_Signature, _method,
- _validatorType.Name);
+ SR.CustomValidationAttribute_Method_Signature, Method,
+ ValidatorType.Name);
}
}
diff --git a/src/System.ComponentModel.Annotations/src/System/ComponentModel/DataAnnotations/DataTypeAttribute.cs b/src/System.ComponentModel.Annotations/src/System/ComponentModel/DataAnnotations/DataTypeAttribute.cs
index e398ad3f50..686a41a332 100644
--- a/src/System.ComponentModel.Annotations/src/System/ComponentModel/DataAnnotations/DataTypeAttribute.cs
+++ b/src/System.ComponentModel.Annotations/src/System/ComponentModel/DataAnnotations/DataTypeAttribute.cs
@@ -62,13 +62,13 @@ namespace System.ComponentModel.DataAnnotations
/// <summary>
/// Gets the DataType. If it equals DataType.Custom, <see cref="CustomDataType" /> should also be retrieved.
/// </summary>
- public DataType DataType { get; private set; }
+ public DataType DataType { get; }
/// <summary>
/// Gets the string representing a custom data type. Returns a non-null value only if <see cref="DataType" /> is
/// DataType.Custom.
/// </summary>
- public string CustomDataType { get; private set; }
+ public string CustomDataType { get; }
/// <summary>
/// Gets the default display format that gets used along with this DataType.
diff --git a/src/System.ComponentModel.Annotations/src/System/ComponentModel/DataAnnotations/DisplayAttribute.cs b/src/System.ComponentModel.Annotations/src/System/ComponentModel/DataAnnotations/DisplayAttribute.cs
index 53305daa00..f105a857b2 100644
--- a/src/System.ComponentModel.Annotations/src/System/ComponentModel/DataAnnotations/DisplayAttribute.cs
+++ b/src/System.ComponentModel.Annotations/src/System/ComponentModel/DataAnnotations/DisplayAttribute.cs
@@ -57,14 +57,8 @@ namespace System.ComponentModel.DataAnnotations
/// </value>
public string ShortName
{
- get { return _shortName.Value; }
- set
- {
- if (_shortName.Value != value)
- {
- _shortName.Value = value;
- }
- }
+ get => _shortName.Value;
+ set => _shortName.Value = value;
}
/// <summary>
@@ -88,14 +82,8 @@ namespace System.ComponentModel.DataAnnotations
/// </value>
public string Name
{
- get { return _name.Value; }
- set
- {
- if (_name.Value != value)
- {
- _name.Value = value;
- }
- }
+ get => _name.Value;
+ set => _name.Value = value;
}
/// <summary>
@@ -119,14 +107,8 @@ namespace System.ComponentModel.DataAnnotations
/// </value>
public string Description
{
- get { return _description.Value; }
- set
- {
- if (_description.Value != value)
- {
- _description.Value = value;
- }
- }
+ get => _description.Value;
+ set => _description.Value = value;
}
/// <summary>
@@ -150,14 +132,8 @@ namespace System.ComponentModel.DataAnnotations
/// </value>
public string Prompt
{
- get { return _prompt.Value; }
- set
- {
- if (_prompt.Value != value)
- {
- _prompt.Value = value;
- }
- }
+ get => _prompt.Value;
+ set => _prompt.Value = value;
}
/// <summary>
@@ -181,14 +157,8 @@ namespace System.ComponentModel.DataAnnotations
/// </value>
public string GroupName
{
- get { return _groupName.Value; }
- set
- {
- if (_groupName.Value != value)
- {
- _groupName.Value = value;
- }
- }
+ get => _groupName.Value;
+ set => _groupName.Value = value;
}
/// <summary>
@@ -200,7 +170,7 @@ namespace System.ComponentModel.DataAnnotations
/// </summary>
public Type ResourceType
{
- get { return _resourceType; }
+ get => _resourceType;
set
{
if (_resourceType != value)
@@ -240,9 +210,9 @@ namespace System.ComponentModel.DataAnnotations
"GetAutoGenerateField"));
}
- return _autoGenerateField.Value;
+ return _autoGenerateField.GetValueOrDefault();
}
- set { _autoGenerateField = value; }
+ set => _autoGenerateField = value;
}
/// <summary>
@@ -270,9 +240,9 @@ namespace System.ComponentModel.DataAnnotations
"GetAutoGenerateFilter"));
}
- return _autoGenerateFilter.Value;
+ return _autoGenerateFilter.GetValueOrDefault();
}
- set { _autoGenerateFilter = value; }
+ set => _autoGenerateFilter = value;
}
/// <summary>
@@ -297,9 +267,9 @@ namespace System.ComponentModel.DataAnnotations
SR.DisplayAttribute_PropertyNotSet, "Order", "GetOrder"));
}
- return _order.Value;
+ return _order.GetValueOrDefault();
}
- set { _order = value; }
+ set => _order = value;
}
#endregion
@@ -330,10 +300,7 @@ namespace System.ComponentModel.DataAnnotations
/// but a public static property with a name matching the <see cref="ShortName" /> value couldn't be found
/// on the <see cref="ResourceType" />.
/// </exception>
- public string GetShortName()
- {
- return _shortName.GetLocalizableValue() ?? GetName();
- }
+ public string GetShortName() => _shortName.GetLocalizableValue() ?? GetName();
/// <summary>
/// Gets the UI display string for Name.
@@ -360,10 +327,7 @@ namespace System.ComponentModel.DataAnnotations
/// but a public static property with a name matching the <see cref="Name" /> value couldn't be found
/// on the <see cref="ResourceType" />.
/// </exception>
- public string GetName()
- {
- return _name.GetLocalizableValue();
- }
+ public string GetName() => _name.GetLocalizableValue();
/// <summary>
/// Gets the UI display string for Description.
@@ -386,10 +350,7 @@ namespace System.ComponentModel.DataAnnotations
/// but a public static property with a name matching the <see cref="Description" /> value couldn't be found
/// on the <see cref="ResourceType" />.
/// </exception>
- public string GetDescription()
- {
- return _description.GetLocalizableValue();
- }
+ public string GetDescription() => _description.GetLocalizableValue();
/// <summary>
/// Gets the UI display string for Prompt.
@@ -412,10 +373,7 @@ namespace System.ComponentModel.DataAnnotations
/// but a public static property with a name matching the <see cref="Prompt" /> value couldn't be found
/// on the <see cref="ResourceType" />.
/// </exception>
- public string GetPrompt()
- {
- return _prompt.GetLocalizableValue();
- }
+ public string GetPrompt() => _prompt.GetLocalizableValue();
/// <summary>
/// Gets the UI display string for GroupName.
@@ -438,10 +396,7 @@ namespace System.ComponentModel.DataAnnotations
/// but a public static property with a name matching the <see cref="GroupName" /> value couldn't be found
/// on the <see cref="ResourceType" />.
/// </exception>
- public string GetGroupName()
- {
- return _groupName.GetLocalizableValue();
- }
+ public string GetGroupName() => _groupName.GetLocalizableValue();
/// <summary>
/// Gets the value of <see cref="AutoGenerateField" /> if it has been set, or <c>null</c>.
@@ -452,10 +407,7 @@ namespace System.ComponentModel.DataAnnotations
/// When <see cref="AutoGenerateField" /> has not been set returns <c>null</c>.
/// </para>
/// </returns>
- public bool? GetAutoGenerateField()
- {
- return _autoGenerateField;
- }
+ public bool? GetAutoGenerateField() => _autoGenerateField;
/// <summary>
/// Gets the value of <see cref="AutoGenerateFilter" /> if it has been set, or <c>null</c>.
@@ -466,10 +418,7 @@ namespace System.ComponentModel.DataAnnotations
/// When <see cref="AutoGenerateFilter" /> has not been set returns <c>null</c>.
/// </para>
/// </returns>
- public bool? GetAutoGenerateFilter()
- {
- return _autoGenerateFilter;
- }
+ public bool? GetAutoGenerateFilter() => _autoGenerateFilter;
/// <summary>
/// Gets the value of <see cref="Order" /> if it has been set, or <c>null</c>.
@@ -485,10 +434,8 @@ namespace System.ComponentModel.DataAnnotations
/// of 10000. This value allows for explicitly-ordered fields to be displayed before
/// and after the fields that don't specify an order.
/// </remarks>
- public int? GetOrder()
- {
- return _order;
- }
+ public int? GetOrder() => _order;
+
#endregion
}
}
diff --git a/src/System.ComponentModel.Annotations/src/System/ComponentModel/DataAnnotations/DisplayColumnAttribute.cs b/src/System.ComponentModel.Annotations/src/System/ComponentModel/DataAnnotations/DisplayColumnAttribute.cs
index fcf526d222..f77c27101b 100644
--- a/src/System.ComponentModel.Annotations/src/System/ComponentModel/DataAnnotations/DisplayColumnAttribute.cs
+++ b/src/System.ComponentModel.Annotations/src/System/ComponentModel/DataAnnotations/DisplayColumnAttribute.cs
@@ -28,10 +28,10 @@ namespace System.ComponentModel.DataAnnotations
SortDescending = sortDescending;
}
- public string DisplayColumn { get; private set; }
+ public string DisplayColumn { get; }
- public string SortColumn { get; private set; }
+ public string SortColumn { get; }
- public bool SortDescending { get; private set; }
+ public bool SortDescending { get; }
}
}
diff --git a/src/System.ComponentModel.Annotations/src/System/ComponentModel/DataAnnotations/DisplayFormatAttribute.cs b/src/System.ComponentModel.Annotations/src/System/ComponentModel/DataAnnotations/DisplayFormatAttribute.cs
index 6a433e0cfd..37050b6980 100644
--- a/src/System.ComponentModel.Annotations/src/System/ComponentModel/DataAnnotations/DisplayFormatAttribute.cs
+++ b/src/System.ComponentModel.Annotations/src/System/ComponentModel/DataAnnotations/DisplayFormatAttribute.cs
@@ -49,8 +49,8 @@ namespace System.ComponentModel.DataAnnotations
/// </value>
public string NullDisplayText
{
- get { return _nullDisplayText.Value; }
- set { _nullDisplayText.Value = value; }
+ get => _nullDisplayText.Value;
+ set => _nullDisplayText.Value = value;
}
/// <summary>
@@ -75,8 +75,8 @@ namespace System.ComponentModel.DataAnnotations
/// </summary>
public Type NullDisplayTextResourceType
{
- get { return _nullDisplayText.ResourceType; }
- set { _nullDisplayText.ResourceType = value; }
+ get => _nullDisplayText.ResourceType;
+ set => _nullDisplayText.ResourceType = value;
}
/// <summary>
@@ -103,9 +103,6 @@ namespace System.ComponentModel.DataAnnotations
/// but a public static property with a name matching the <see cref="NullDisplayText" /> value couldn't be found
/// on the <see cref="NullDisplayTextResourceType" />.
/// </exception>
- public string GetNullDisplayText()
- {
- return _nullDisplayText.GetLocalizableValue();
- }
+ public string GetNullDisplayText() => _nullDisplayText.GetLocalizableValue();
}
}
diff --git a/src/System.ComponentModel.Annotations/src/System/ComponentModel/DataAnnotations/EditableAttribute.cs b/src/System.ComponentModel.Annotations/src/System/ComponentModel/DataAnnotations/EditableAttribute.cs
index 8591a424cf..b9cc7eb371 100644
--- a/src/System.ComponentModel.Annotations/src/System/ComponentModel/DataAnnotations/EditableAttribute.cs
+++ b/src/System.ComponentModel.Annotations/src/System/ComponentModel/DataAnnotations/EditableAttribute.cs
@@ -42,7 +42,7 @@ namespace System.ComponentModel.DataAnnotations
/// When <c>false</c>, the field/property is not editable.
/// </para>
/// </value>
- public bool AllowEdit { get; private set; }
+ public bool AllowEdit { get; }
/// <summary>
/// Indicates whether or not the field/property allows an initial value
diff --git a/src/System.ComponentModel.Annotations/src/System/ComponentModel/DataAnnotations/EnumDataTypeAttribute.cs b/src/System.ComponentModel.Annotations/src/System/ComponentModel/DataAnnotations/EnumDataTypeAttribute.cs
index 7af31e2dc6..425b47e8bc 100644
--- a/src/System.ComponentModel.Annotations/src/System/ComponentModel/DataAnnotations/EnumDataTypeAttribute.cs
+++ b/src/System.ComponentModel.Annotations/src/System/ComponentModel/DataAnnotations/EnumDataTypeAttribute.cs
@@ -5,7 +5,6 @@
using System.Diagnostics;
using System.Globalization;
using System.Linq;
-using System.Reflection;
namespace System.ComponentModel.DataAnnotations
{
@@ -20,7 +19,7 @@ namespace System.ComponentModel.DataAnnotations
EnumType = enumType;
}
- public Type EnumType { get; private set; }
+ public Type EnumType { get; }
public override bool IsValid(object value)
{
@@ -107,16 +106,10 @@ namespace System.ComponentModel.DataAnnotations
return Enum.IsDefined(EnumType, convertedValue);
}
- private static bool IsEnumTypeInFlagsMode(Type enumType)
- {
- return enumType.GetCustomAttributes(typeof(FlagsAttribute), false).Any();
- }
-
+ private static bool IsEnumTypeInFlagsMode(Type enumType) =>
+ enumType.GetCustomAttributes(typeof(FlagsAttribute), false).Any();
- private static string GetUnderlyingTypeValueString(Type enumType, object enumValue)
- {
- return
- Convert.ChangeType(enumValue, Enum.GetUnderlyingType(enumType), CultureInfo.InvariantCulture).ToString();
- }
+ private static string GetUnderlyingTypeValueString(Type enumType, object enumValue) =>
+ Convert.ChangeType(enumValue, Enum.GetUnderlyingType(enumType), CultureInfo.InvariantCulture).ToString();
}
}
diff --git a/src/System.ComponentModel.Annotations/src/System/ComponentModel/DataAnnotations/FileExtensionsAttribute.cs b/src/System.ComponentModel.Annotations/src/System/ComponentModel/DataAnnotations/FileExtensionsAttribute.cs
index 7eb04acd04..1fedd9df43 100644
--- a/src/System.ComponentModel.Annotations/src/System/ComponentModel/DataAnnotations/FileExtensionsAttribute.cs
+++ b/src/System.ComponentModel.Annotations/src/System/ComponentModel/DataAnnotations/FileExtensionsAttribute.cs
@@ -25,34 +25,23 @@ namespace System.ComponentModel.DataAnnotations
public string Extensions
{
- get
- {
- // Default file extensions match those from jquery validate.
- return string.IsNullOrWhiteSpace(_extensions) ? "png,jpg,jpeg,gif" : _extensions;
- }
- set { _extensions = value; }
+ // Default file extensions match those from jquery validate.
+ get => string.IsNullOrWhiteSpace(_extensions) ? "png,jpg,jpeg,gif" : _extensions;
+ set => _extensions = value;
}
- private string ExtensionsFormatted
- {
- get { return ExtensionsParsed.Aggregate((left, right) => left + ", " + right); }
- }
+ private string ExtensionsFormatted => ExtensionsParsed.Aggregate((left, right) => left + ", " + right);
-
- private string ExtensionsNormalized
- {
- get { return Extensions.Replace(" ", string.Empty).Replace(".", string.Empty).ToLowerInvariant(); }
- }
+ private string ExtensionsNormalized =>
+ Extensions.Replace(" ", string.Empty).Replace(".", string.Empty).ToLowerInvariant();
private IEnumerable<string> ExtensionsParsed
{
get { return ExtensionsNormalized.Split(',').Select(e => "." + e); }
}
- public override string FormatErrorMessage(string name)
- {
- return string.Format(CultureInfo.CurrentCulture, ErrorMessageString, name, ExtensionsFormatted);
- }
+ public override string FormatErrorMessage(string name) =>
+ string.Format(CultureInfo.CurrentCulture, ErrorMessageString, name, ExtensionsFormatted);
public override bool IsValid(object value)
{
diff --git a/src/System.ComponentModel.Annotations/src/System/ComponentModel/DataAnnotations/FilterUIHintAttribute.cs b/src/System.ComponentModel.Annotations/src/System/ComponentModel/DataAnnotations/FilterUIHintAttribute.cs
index 9e22888639..e080c2a4e4 100644
--- a/src/System.ComponentModel.Annotations/src/System/ComponentModel/DataAnnotations/FilterUIHintAttribute.cs
+++ b/src/System.ComponentModel.Annotations/src/System/ComponentModel/DataAnnotations/FilterUIHintAttribute.cs
@@ -13,44 +13,26 @@ namespace System.ComponentModel.DataAnnotations
[Obsolete("This attribute is no longer in use and will be ignored if applied.")]
public sealed class FilterUIHintAttribute : Attribute
{
- private UIHintAttribute.UIHintImplementation _implementation;
+ private readonly UIHintAttribute.UIHintImplementation _implementation;
/// <summary>
/// Gets the name of the control that is most appropriate for this associated
/// property or field
/// </summary>
- public string FilterUIHint
- {
- get
- {
- return this._implementation.UIHint;
- }
- }
+ public string FilterUIHint => _implementation.UIHint;
/// <summary>
/// Gets the name of the presentation layer that supports the control type
/// in <see cref="FilterUIHint"/>
/// </summary>
- public string PresentationLayer
- {
- get
- {
- return this._implementation.PresentationLayer;
- }
- }
+ public string PresentationLayer => _implementation.PresentationLayer;
/// <summary>
/// Gets the name-value pairs used as parameters to the control's constructor
/// </summary>
/// <exception cref="InvalidOperationException"> is thrown if the current attribute
/// is ill-formed.</exception>
- public IDictionary<string, object> ControlParameters
- {
- get
- {
- return this._implementation.ControlParameters;
- }
- }
+ public IDictionary<string, object> ControlParameters => _implementation.ControlParameters;
/// <summary>
/// Constructor that accepts the name of the control, without specifying
@@ -84,7 +66,7 @@ namespace System.ComponentModel.DataAnnotations
public FilterUIHintAttribute(string filterUIHint, string presentationLayer,
params object[] controlParameters)
{
- this._implementation = new UIHintAttribute.UIHintImplementation(
+ _implementation = new UIHintAttribute.UIHintImplementation(
filterUIHint, presentationLayer, controlParameters);
}
@@ -92,10 +74,7 @@ namespace System.ComponentModel.DataAnnotations
/// Returns the hash code for this FilterUIHintAttribute.
/// </summary>
/// <returns>A 32-bit signed integer hash code.</returns>
- public override int GetHashCode()
- {
- return this._implementation.GetHashCode();
- }
+ public override int GetHashCode() => _implementation.GetHashCode();
/// <summary>
/// Determines whether this instance of FilterUIHintAttribute and a specified object,
@@ -112,7 +91,7 @@ namespace System.ComponentModel.DataAnnotations
return false;
}
- return this._implementation.Equals(otherAttribute._implementation);
+ return _implementation.Equals(otherAttribute._implementation);
}
}
}
diff --git a/src/System.ComponentModel.Annotations/src/System/ComponentModel/DataAnnotations/LocalizableString.cs b/src/System.ComponentModel.Annotations/src/System/ComponentModel/DataAnnotations/LocalizableString.cs
index 82d8316d30..8ad0ba8256 100644
--- a/src/System.ComponentModel.Annotations/src/System/ComponentModel/DataAnnotations/LocalizableString.cs
+++ b/src/System.ComponentModel.Annotations/src/System/ComponentModel/DataAnnotations/LocalizableString.cs
@@ -49,7 +49,7 @@ namespace System.ComponentModel.DataAnnotations
/// </summary>
public string Value
{
- get { return _propertyValue; }
+ get => _propertyValue;
set
{
if (_propertyValue != value)
@@ -65,7 +65,7 @@ namespace System.ComponentModel.DataAnnotations
/// </summary>
public Type ResourceType
{
- get { return _resourceType; }
+ get => _resourceType;
set
{
if (_resourceType != value)
diff --git a/src/System.ComponentModel.Annotations/src/System/ComponentModel/DataAnnotations/MaxLengthAttribute.cs b/src/System.ComponentModel.Annotations/src/System/ComponentModel/DataAnnotations/MaxLengthAttribute.cs
index 199e9e596a..06f4ba0ccb 100644
--- a/src/System.ComponentModel.Annotations/src/System/ComponentModel/DataAnnotations/MaxLengthAttribute.cs
+++ b/src/System.ComponentModel.Annotations/src/System/ComponentModel/DataAnnotations/MaxLengthAttribute.cs
@@ -3,7 +3,9 @@
// See the LICENSE file in the project root for more information.
using System.Collections;
+using System.Diagnostics;
using System.Globalization;
+using System.Reflection;
namespace System.ComponentModel.DataAnnotations
{
@@ -42,12 +44,9 @@ namespace System.ComponentModel.DataAnnotations
/// <summary>
/// Gets the maximum allowable length of the collection/string data.
/// </summary>
- public int Length { get; private set; }
+ public int Length { get; }
- private static string DefaultErrorMessageString
- {
- get { return SR.MaxLengthAttribute_ValidationError; }
- }
+ private static string DefaultErrorMessageString => SR.MaxLengthAttribute_ValidationError;
/// <summary>
/// Determines whether a specified object is valid. (Overrides <see cref="ValidationAttribute.IsValid(object)" />)
@@ -76,16 +75,13 @@ namespace System.ComponentModel.DataAnnotations
{
length = str.Length;
}
+ else if (CountPropertyHelper.TryGetCount(value, out var count))
+ {
+ length = count;
+ }
else
{
- if (value is ICollection collection)
- {
- length = collection.Count;
- }
- else
- {
- throw new InvalidCastException(SR.Format(SR.LengthAttribute_InvalidValueType, value.GetType()));
- }
+ throw new InvalidCastException(SR.Format(SR.LengthAttribute_InvalidValueType, value.GetType()));
}
return MaxAllowableLength == Length || length <= Length;
@@ -96,11 +92,9 @@ namespace System.ComponentModel.DataAnnotations
/// </summary>
/// <param name="name">The name to include in the formatted string.</param>
/// <returns>A localized string to describe the maximum acceptable length.</returns>
- public override string FormatErrorMessage(string name)
- {
+ public override string FormatErrorMessage(string name) =>
// An error occurred, so we know the value is greater than the maximum if it was specified
- return string.Format(CultureInfo.CurrentCulture, ErrorMessageString, name, Length);
- }
+ string.Format(CultureInfo.CurrentCulture, ErrorMessageString, name, Length);
/// <summary>
/// Checks that Length has a legal value.
@@ -115,4 +109,39 @@ namespace System.ComponentModel.DataAnnotations
}
}
}
+
+ internal static class CountPropertyHelper
+ {
+ public static bool TryGetCount(object value, out int count)
+ {
+ Debug.Assert(value != null);
+
+ if (value is ICollection collection)
+ {
+ count = collection.Count;
+ return true;
+ }
+
+ PropertyInfo property = null;
+ try
+ {
+ // On CoreRT, this property may not be enabled for reflection.
+ // It may be possible to eliminate the exception by using direct reflection
+ // (i.e. not via the RuntimeReflectionExtensions or the new split TypeInfo format.
+ property = value.GetType().GetRuntimeProperty("Count");
+ }
+ catch (TypeAccessException)
+ {
+ }
+
+ if (property != null && property.CanRead && property.PropertyType == typeof(int))
+ {
+ count = (int)property.GetValue(value);
+ return true;
+ }
+
+ count = -1;
+ return false;
+ }
+ }
}
diff --git a/src/System.ComponentModel.Annotations/src/System/ComponentModel/DataAnnotations/MinLengthAttribute.cs b/src/System.ComponentModel.Annotations/src/System/ComponentModel/DataAnnotations/MinLengthAttribute.cs
index 44109fa21b..e27c376aa0 100644
--- a/src/System.ComponentModel.Annotations/src/System/ComponentModel/DataAnnotations/MinLengthAttribute.cs
+++ b/src/System.ComponentModel.Annotations/src/System/ComponentModel/DataAnnotations/MinLengthAttribute.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.Collections;
using System.Globalization;
namespace System.ComponentModel.DataAnnotations
@@ -30,7 +29,7 @@ namespace System.ComponentModel.DataAnnotations
/// <summary>
/// Gets the minimum allowable length of the collection/string data.
/// </summary>
- public int Length { get; private set; }
+ public int Length { get; }
/// <summary>
/// Determines whether a specified object is valid. (Overrides <see cref="ValidationAttribute.IsValid(object)" />)
@@ -60,16 +59,13 @@ namespace System.ComponentModel.DataAnnotations
{
length = str.Length;
}
+ else if (CountPropertyHelper.TryGetCount(value, out var count))
+ {
+ length = count;
+ }
else
{
- if (value is ICollection collection)
- {
- length = collection.Count;
- }
- else
- {
- throw new InvalidCastException(SR.Format(SR.LengthAttribute_InvalidValueType, value.GetType()));
- }
+ throw new InvalidCastException(SR.Format(SR.LengthAttribute_InvalidValueType, value.GetType()));
}
return length >= Length;
@@ -80,11 +76,9 @@ namespace System.ComponentModel.DataAnnotations
/// </summary>
/// <param name="name">The name to include in the formatted string.</param>
/// <returns>A localized string to describe the minimum acceptable length.</returns>
- public override string FormatErrorMessage(string name)
- {
+ public override string FormatErrorMessage(string name) =>
// An error occurred, so we know the value is less than the minimum
- return string.Format(CultureInfo.CurrentCulture, ErrorMessageString, name, Length);
- }
+ string.Format(CultureInfo.CurrentCulture, ErrorMessageString, name, Length);
/// <summary>
/// Checks that Length has a legal value.
diff --git a/src/System.ComponentModel.Annotations/src/System/ComponentModel/DataAnnotations/RangeAttribute.cs b/src/System.ComponentModel.Annotations/src/System/ComponentModel/DataAnnotations/RangeAttribute.cs
index 1d9f9c0c36..d24b6a262a 100644
--- a/src/System.ComponentModel.Annotations/src/System/ComponentModel/DataAnnotations/RangeAttribute.cs
+++ b/src/System.ComponentModel.Annotations/src/System/ComponentModel/DataAnnotations/RangeAttribute.cs
@@ -3,7 +3,6 @@
// See the LICENSE file in the project root for more information.
using System.Globalization;
-using System.Reflection;
namespace System.ComponentModel.DataAnnotations
{
@@ -69,7 +68,7 @@ namespace System.ComponentModel.DataAnnotations
/// Gets the type of the <see cref="Minimum" /> and <see cref="Maximum" /> values (e.g. Int32, Double, or some custom
/// type)
/// </summary>
- public Type OperandType { get; private set; }
+ public Type OperandType { get; }
private Func<object, object> Conversion { get; set; }
diff --git a/src/System.ComponentModel.Annotations/src/System/ComponentModel/DataAnnotations/RegularExpressionAttribute.cs b/src/System.ComponentModel.Annotations/src/System/ComponentModel/DataAnnotations/RegularExpressionAttribute.cs
index 479d010903..15883c3960 100644
--- a/src/System.ComponentModel.Annotations/src/System/ComponentModel/DataAnnotations/RegularExpressionAttribute.cs
+++ b/src/System.ComponentModel.Annotations/src/System/ComponentModel/DataAnnotations/RegularExpressionAttribute.cs
@@ -34,7 +34,7 @@ namespace System.ComponentModel.DataAnnotations
/// <summary>
/// Gets the regular expression pattern to use
/// </summary>
- public string Pattern { get; private set; }
+ public string Pattern { get; }
private Regex Regex { get; set; }
diff --git a/src/System.ComponentModel.Annotations/src/System/ComponentModel/DataAnnotations/ScaffoldColumnAttribute.cs b/src/System.ComponentModel.Annotations/src/System/ComponentModel/DataAnnotations/ScaffoldColumnAttribute.cs
index b476242c1d..c3ecbe3cfc 100644
--- a/src/System.ComponentModel.Annotations/src/System/ComponentModel/DataAnnotations/ScaffoldColumnAttribute.cs
+++ b/src/System.ComponentModel.Annotations/src/System/ComponentModel/DataAnnotations/ScaffoldColumnAttribute.cs
@@ -12,6 +12,6 @@ namespace System.ComponentModel.DataAnnotations
Scaffold = scaffold;
}
- public bool Scaffold { get; private set; }
+ public bool Scaffold { get; }
}
}
diff --git a/src/System.ComponentModel.Annotations/src/System/ComponentModel/DataAnnotations/Schema/ColumnAttribute.cs b/src/System.ComponentModel.Annotations/src/System/ComponentModel/DataAnnotations/Schema/ColumnAttribute.cs
index c554af5484..8e9d0e4dfa 100644
--- a/src/System.ComponentModel.Annotations/src/System/ComponentModel/DataAnnotations/Schema/ColumnAttribute.cs
+++ b/src/System.ComponentModel.Annotations/src/System/ComponentModel/DataAnnotations/Schema/ColumnAttribute.cs
@@ -12,7 +12,6 @@ namespace System.ComponentModel.DataAnnotations.Schema
[AttributeUsage(AttributeTargets.Property | AttributeTargets.Field, AllowMultiple = false)]
public class ColumnAttribute : Attribute
{
- private readonly string _name;
private int _order = -1;
private string _typeName;
@@ -35,23 +34,20 @@ namespace System.ComponentModel.DataAnnotations.Schema
SR.ArgumentIsNullOrWhitespace, nameof(name)));
}
- _name = name;
+ Name = name;
}
/// <summary>
/// The name of the column the property is mapped to.
/// </summary>
- public string Name
- {
- get { return _name; }
- }
+ public string Name { get; }
/// <summary>
/// The zero-based order of the column the property is mapped to.
/// </summary>
public int Order
{
- get { return _order; }
+ get => _order;
set
{
if (value < 0)
@@ -68,7 +64,7 @@ namespace System.ComponentModel.DataAnnotations.Schema
/// </summary>
public string TypeName
{
- get { return _typeName; }
+ get => _typeName;
set
{
if (string.IsNullOrWhiteSpace(value))
diff --git a/src/System.ComponentModel.Annotations/src/System/ComponentModel/DataAnnotations/Schema/DatabaseGeneratedAttribute.cs b/src/System.ComponentModel.Annotations/src/System/ComponentModel/DataAnnotations/Schema/DatabaseGeneratedAttribute.cs
index 8100910987..7f45f2b0e7 100644
--- a/src/System.ComponentModel.Annotations/src/System/ComponentModel/DataAnnotations/Schema/DatabaseGeneratedAttribute.cs
+++ b/src/System.ComponentModel.Annotations/src/System/ComponentModel/DataAnnotations/Schema/DatabaseGeneratedAttribute.cs
@@ -27,6 +27,6 @@ namespace System.ComponentModel.DataAnnotations.Schema
/// <summary>
/// The pattern used to generate values for the property in the database.
/// </summary>
- public DatabaseGeneratedOption DatabaseGeneratedOption { get; private set; }
+ public DatabaseGeneratedOption DatabaseGeneratedOption { get; }
}
}
diff --git a/src/System.ComponentModel.Annotations/src/System/ComponentModel/DataAnnotations/Schema/ForeignKeyAttribute.cs b/src/System.ComponentModel.Annotations/src/System/ComponentModel/DataAnnotations/Schema/ForeignKeyAttribute.cs
index abb5176d7a..fad15304ad 100644
--- a/src/System.ComponentModel.Annotations/src/System/ComponentModel/DataAnnotations/Schema/ForeignKeyAttribute.cs
+++ b/src/System.ComponentModel.Annotations/src/System/ComponentModel/DataAnnotations/Schema/ForeignKeyAttribute.cs
@@ -14,8 +14,6 @@ namespace System.ComponentModel.DataAnnotations.Schema
[AttributeUsage(AttributeTargets.Property | AttributeTargets.Field, AllowMultiple = false)]
public class ForeignKeyAttribute : Attribute
{
- private readonly string _name;
-
/// <summary>
/// Initializes a new instance of the <see cref="ForeignKeyAttribute" /> class.
/// </summary>
@@ -32,16 +30,13 @@ namespace System.ComponentModel.DataAnnotations.Schema
SR.ArgumentIsNullOrWhitespace, nameof(name)));
}
- _name = name;
+ Name = name;
}
/// <summary>
/// If placed on a foreign key property, the name of the associated navigation property.
/// If placed on a navigation property, the name of the associated foreign key(s).
/// </summary>
- public string Name
- {
- get { return _name; }
- }
+ public string Name { get; }
}
}
diff --git a/src/System.ComponentModel.Annotations/src/System/ComponentModel/DataAnnotations/Schema/InversePropertyAttribute.cs b/src/System.ComponentModel.Annotations/src/System/ComponentModel/DataAnnotations/Schema/InversePropertyAttribute.cs
index ac067db16d..b8b39d3944 100644
--- a/src/System.ComponentModel.Annotations/src/System/ComponentModel/DataAnnotations/Schema/InversePropertyAttribute.cs
+++ b/src/System.ComponentModel.Annotations/src/System/ComponentModel/DataAnnotations/Schema/InversePropertyAttribute.cs
@@ -12,8 +12,6 @@ namespace System.ComponentModel.DataAnnotations.Schema
[AttributeUsage(AttributeTargets.Property | AttributeTargets.Field, AllowMultiple = false)]
public class InversePropertyAttribute : Attribute
{
- private readonly string _property;
-
/// <summary>
/// Initializes a new instance of the <see cref="InversePropertyAttribute" /> class.
/// </summary>
@@ -25,15 +23,13 @@ namespace System.ComponentModel.DataAnnotations.Schema
throw new ArgumentException(string.Format(CultureInfo.CurrentCulture,
SR.ArgumentIsNullOrWhitespace, nameof(property)));
}
- _property = property;
+
+ Property = property;
}
/// <summary>
/// The navigation property representing the other end of the same relationship.
/// </summary>
- public string Property
- {
- get { return _property; }
- }
+ public string Property { get; }
}
}
diff --git a/src/System.ComponentModel.Annotations/src/System/ComponentModel/DataAnnotations/Schema/TableAttribute.cs b/src/System.ComponentModel.Annotations/src/System/ComponentModel/DataAnnotations/Schema/TableAttribute.cs
index f7add7eb87..31133ad398 100644
--- a/src/System.ComponentModel.Annotations/src/System/ComponentModel/DataAnnotations/Schema/TableAttribute.cs
+++ b/src/System.ComponentModel.Annotations/src/System/ComponentModel/DataAnnotations/Schema/TableAttribute.cs
@@ -12,7 +12,6 @@ namespace System.ComponentModel.DataAnnotations.Schema
[AttributeUsage(AttributeTargets.Class, AllowMultiple = false)]
public class TableAttribute : Attribute
{
- private readonly string _name;
private string _schema;
/// <summary>
@@ -26,23 +25,21 @@ namespace System.ComponentModel.DataAnnotations.Schema
throw new ArgumentException(string.Format(CultureInfo.CurrentCulture,
SR.ArgumentIsNullOrWhitespace, nameof(name)));
}
- _name = name;
+
+ Name = name;
}
/// <summary>
/// The name of the table the class is mapped to.
/// </summary>
- public string Name
- {
- get { return _name; }
- }
+ public string Name { get; }
/// <summary>
/// The schema of the table the class is mapped to.
/// </summary>
public string Schema
{
- get { return _schema; }
+ get => _schema;
set
{
if (string.IsNullOrWhiteSpace(value))
@@ -50,6 +47,7 @@ namespace System.ComponentModel.DataAnnotations.Schema
throw new ArgumentException(string.Format(CultureInfo.CurrentCulture,
SR.ArgumentIsNullOrWhitespace, nameof(value)));
}
+
_schema = value;
}
}
diff --git a/src/System.ComponentModel.Annotations/src/System/ComponentModel/DataAnnotations/StringLengthAttribute.cs b/src/System.ComponentModel.Annotations/src/System/ComponentModel/DataAnnotations/StringLengthAttribute.cs
index 9640fe1e2c..2360617175 100644
--- a/src/System.ComponentModel.Annotations/src/System/ComponentModel/DataAnnotations/StringLengthAttribute.cs
+++ b/src/System.ComponentModel.Annotations/src/System/ComponentModel/DataAnnotations/StringLengthAttribute.cs
@@ -26,7 +26,7 @@ namespace System.ComponentModel.DataAnnotations
/// <summary>
/// Gets the maximum acceptable length of the string
/// </summary>
- public int MaximumLength { get; private set; }
+ public int MaximumLength { get; }
/// <summary>
/// Gets or sets the minimum acceptable length of the string
diff --git a/src/System.ComponentModel.Annotations/src/System/ComponentModel/DataAnnotations/UIHintAttribute.cs b/src/System.ComponentModel.Annotations/src/System/ComponentModel/DataAnnotations/UIHintAttribute.cs
index 9f1077f079..befa796bc4 100644
--- a/src/System.ComponentModel.Annotations/src/System/ComponentModel/DataAnnotations/UIHintAttribute.cs
+++ b/src/System.ComponentModel.Annotations/src/System/ComponentModel/DataAnnotations/UIHintAttribute.cs
@@ -51,32 +51,20 @@ namespace System.ComponentModel.DataAnnotations
/// <summary>
/// Gets the name of the control that is most appropriate for this associated property or field
/// </summary>
- public string UIHint
- {
- get { return _implementation.UIHint; }
- }
+ public string UIHint => _implementation.UIHint;
/// <summary>
/// Gets the name of the presentation layer that supports the control type in <see cref="UIHint" />
/// </summary>
- public string PresentationLayer
- {
- get { return _implementation.PresentationLayer; }
- }
+ public string PresentationLayer => _implementation.PresentationLayer;
/// <summary>
/// Gets the name-value pairs used as parameters to the control's constructor
/// </summary>
/// <exception cref="InvalidOperationException"> is thrown if the current attribute is ill-formed.</exception>
- public IDictionary<string, object> ControlParameters
- {
- get { return _implementation.ControlParameters; }
- }
+ public IDictionary<string, object> ControlParameters => _implementation.ControlParameters;
- public override int GetHashCode()
- {
- return _implementation.GetHashCode();
- }
+ public override int GetHashCode() => _implementation.GetHashCode();
public override bool Equals(object obj)
{
@@ -107,12 +95,12 @@ namespace System.ComponentModel.DataAnnotations
/// <summary>
/// Gets the name of the control that is most appropriate for this associated property or field
/// </summary>
- public string UIHint { get; private set; }
+ public string UIHint { get; }
/// <summary>
/// Gets the name of the presentation layer that supports the control type in <see cref="UIHint" />
/// </summary>
- public string PresentationLayer { get; private set; }
+ public string PresentationLayer { get; }
public IDictionary<string, object> ControlParameters
{
diff --git a/src/System.ComponentModel.Annotations/src/System/ComponentModel/DataAnnotations/ValidationAttribute.cs b/src/System.ComponentModel.Annotations/src/System/ComponentModel/DataAnnotations/ValidationAttribute.cs
index 3b3cb32055..75eef3cdad 100644
--- a/src/System.ComponentModel.Annotations/src/System/ComponentModel/DataAnnotations/ValidationAttribute.cs
+++ b/src/System.ComponentModel.Annotations/src/System/ComponentModel/DataAnnotations/ValidationAttribute.cs
@@ -4,7 +4,6 @@
using System.Diagnostics;
using System.Globalization;
-using System.Linq;
using System.Reflection;
namespace System.ComponentModel.DataAnnotations
@@ -116,10 +115,7 @@ namespace System.ComponentModel.DataAnnotations
/// <see cref="ValidationContext" /> to perform validation.
/// Base class returns false. Override in child classes as appropriate.
/// </summary>
- public virtual bool RequiresValidationContext
- {
- get { return false; }
- }
+ public virtual bool RequiresValidationContext => false;
#endregion
@@ -134,12 +130,9 @@ namespace System.ComponentModel.DataAnnotations
/// </value>
public string ErrorMessage
{
- get
- {
- // If _errorMessage is not set, return the default. This is done to preserve
- // behavior prior to the fix where ErrorMessage showed the non-null message to use.
- return _errorMessage ?? _defaultErrorMessage;
- }
+ // If _errorMessage is not set, return the default. This is done to preserve
+ // behavior prior to the fix where ErrorMessage showed the non-null message to use.
+ get => _errorMessage ?? _defaultErrorMessage;
set
{
_errorMessage = value;
@@ -164,7 +157,7 @@ namespace System.ComponentModel.DataAnnotations
/// </value>
public string ErrorMessageResourceName
{
- get { return _errorMessageResourceName; }
+ get => _errorMessageResourceName;
set
{
_errorMessageResourceName = value;
@@ -185,7 +178,7 @@ namespace System.ComponentModel.DataAnnotations
/// </value>
public Type ErrorMessageResourceType
{
- get { return _errorMessageResourceType; }
+ get => _errorMessageResourceType;
set
{
_errorMessageResourceType = value;
@@ -316,10 +309,8 @@ namespace System.ComponentModel.DataAnnotations
/// <param name="name">The user-visible name to include in the formatted message.</param>
/// <returns>The localized string describing the validation error</returns>
/// <exception cref="InvalidOperationException"> is thrown if the current attribute is malformed.</exception>
- public virtual string FormatErrorMessage(string name)
- {
- return string.Format(CultureInfo.CurrentCulture, ErrorMessageString, name);
- }
+ public virtual string FormatErrorMessage(string name) =>
+ string.Format(CultureInfo.CurrentCulture, ErrorMessageString, name);
/// <summary>
/// Gets the value indicating whether or not the specified <paramref name="value" /> is valid
diff --git a/src/System.ComponentModel.Annotations/src/System/ComponentModel/DataAnnotations/ValidationAttributeStore.cs b/src/System.ComponentModel.Annotations/src/System/ComponentModel/DataAnnotations/ValidationAttributeStore.cs
index 06f2a34919..5f41a1ccdf 100644
--- a/src/System.ComponentModel.Annotations/src/System/ComponentModel/DataAnnotations/ValidationAttributeStore.cs
+++ b/src/System.ComponentModel.Annotations/src/System/ComponentModel/DataAnnotations/ValidationAttributeStore.cs
@@ -20,16 +20,12 @@ namespace System.ComponentModel.DataAnnotations
/// </remarks>
internal class ValidationAttributeStore
{
- private static readonly ValidationAttributeStore _singleton = new ValidationAttributeStore();
private readonly Dictionary<Type, TypeStoreItem> _typeStoreItems = new Dictionary<Type, TypeStoreItem>();
/// <summary>
/// Gets the singleton <see cref="ValidationAttributeStore" />
/// </summary>
- internal static ValidationAttributeStore Instance
- {
- get { return _singleton; }
- }
+ internal static ValidationAttributeStore Instance { get; } = new ValidationAttributeStore();
/// <summary>
/// Retrieves the type level validation attributes for the given type.
@@ -144,35 +140,26 @@ namespace System.ComponentModel.DataAnnotations
}
}
- internal static bool IsPublic(PropertyInfo p)
- {
- return (p.GetMethod != null && p.GetMethod.IsPublic) || (p.SetMethod != null && p.SetMethod.IsPublic);
- }
+ internal static bool IsPublic(PropertyInfo p) =>
+ (p.GetMethod != null && p.GetMethod.IsPublic) || (p.SetMethod != null && p.SetMethod.IsPublic);
- internal static bool IsStatic(PropertyInfo p)
- {
- return (p.GetMethod != null && p.GetMethod.IsStatic) || (p.SetMethod != null && p.SetMethod.IsStatic);
- }
+ internal static bool IsStatic(PropertyInfo p) =>
+ (p.GetMethod != null && p.GetMethod.IsStatic) || (p.SetMethod != null && p.SetMethod.IsStatic);
/// <summary>
/// Private abstract class for all store items
/// </summary>
private abstract class StoreItem
{
- private readonly IEnumerable<ValidationAttribute> _validationAttributes;
-
internal StoreItem(IEnumerable<Attribute> attributes)
{
- _validationAttributes = attributes.OfType<ValidationAttribute>();
+ ValidationAttributes = attributes.OfType<ValidationAttribute>();
DisplayAttribute = attributes.OfType<DisplayAttribute>().SingleOrDefault();
}
- internal IEnumerable<ValidationAttribute> ValidationAttributes
- {
- get { return _validationAttributes; }
- }
+ internal IEnumerable<ValidationAttribute> ValidationAttributes { get; }
- internal DisplayAttribute DisplayAttribute { get; set; }
+ internal DisplayAttribute DisplayAttribute { get; }
}
/// <summary>
@@ -248,19 +235,14 @@ nameof(propertyName));
/// </summary>
private class PropertyStoreItem : StoreItem
{
- private readonly Type _propertyType;
-
internal PropertyStoreItem(Type propertyType, IEnumerable<Attribute> attributes)
: base(attributes)
{
Debug.Assert(propertyType != null);
- _propertyType = propertyType;
+ PropertyType = propertyType;
}
- internal Type PropertyType
- {
- get { return _propertyType; }
- }
+ internal Type PropertyType { get; }
}
}
}
diff --git a/src/System.ComponentModel.Annotations/src/System/ComponentModel/DataAnnotations/ValidationContext.cs b/src/System.ComponentModel.Annotations/src/System/ComponentModel/DataAnnotations/ValidationContext.cs
index 57714f55fa..fd5a0b5930 100644
--- a/src/System.ComponentModel.Annotations/src/System/ComponentModel/DataAnnotations/ValidationContext.cs
+++ b/src/System.ComponentModel.Annotations/src/System/ComponentModel/DataAnnotations/ValidationContext.cs
@@ -30,9 +30,7 @@ namespace System.ComponentModel.DataAnnotations
#region Member Fields
private readonly Dictionary<object, object> _items;
- private readonly object _objectInstance;
private string _displayName;
- private string _memberName;
private Func<Type, object> _serviceProvider;
#endregion
@@ -102,7 +100,7 @@ namespace System.ComponentModel.DataAnnotations
_items = new Dictionary<object, object>();
}
- _objectInstance = instance;
+ ObjectInstance = instance;
}
#endregion
@@ -119,18 +117,12 @@ namespace System.ComponentModel.DataAnnotations
/// For example, the property being validated, as well as other properties on the instance might not have been
/// updated to their new values.
/// </remarks>
- public object ObjectInstance
- {
- get { return _objectInstance; }
- }
+ public object ObjectInstance { get; }
/// <summary>
/// Gets the type of the object being validated. It will not be null.
/// </summary>
- public Type ObjectType
- {
- get { return ObjectInstance.GetType(); }
- }
+ public Type ObjectType => ObjectInstance.GetType();
/// <summary>
/// Gets or sets the user-visible name of the type or property being validated.
@@ -172,11 +164,7 @@ namespace System.ComponentModel.DataAnnotations
/// This name reflects the API name of the member being validated, not a localized name. It should be set
/// only for property or parameter contexts.
/// </value>
- public string MemberName
- {
- get { return _memberName; }
- set { _memberName = value; }
- }
+ public string MemberName { get; set; }
/// <summary>
/// Gets the dictionary of key/value pairs associated with this context.
@@ -185,10 +173,7 @@ namespace System.ComponentModel.DataAnnotations
/// This property will never be null, but the dictionary may be empty. Changes made
/// to items in this dictionary will never affect the original dictionary specified in the constructor.
/// </value>
- public IDictionary<object, object> Items
- {
- get { return _items; }
- }
+ public IDictionary<object, object> Items => _items;
#endregion
@@ -204,7 +189,7 @@ namespace System.ComponentModel.DataAnnotations
ValidationAttributeStore store = ValidationAttributeStore.Instance;
DisplayAttribute displayAttribute = null;
- if (string.IsNullOrEmpty(_memberName))
+ if (string.IsNullOrEmpty(MemberName))
{
displayAttribute = store.GetTypeDisplayAttribute(this);
}
@@ -244,15 +229,8 @@ namespace System.ComponentModel.DataAnnotations
/// </summary>
/// <param name="serviceType">The type of the service needed.</param>
/// <returns>An instance of that service or null if it is not available.</returns>
- public object GetService(Type serviceType)
- {
- if (_serviceProvider != null)
- {
- return _serviceProvider(serviceType);
- }
+ public object GetService(Type serviceType) => _serviceProvider?.Invoke(serviceType);
- return null;
- }
#endregion
}
}
diff --git a/src/System.ComponentModel.Annotations/src/System/ComponentModel/DataAnnotations/ValidationException.cs b/src/System.ComponentModel.Annotations/src/System/ComponentModel/DataAnnotations/ValidationException.cs
index e8dd66bc4b..0ae7ccfe7b 100644
--- a/src/System.ComponentModel.Annotations/src/System/ComponentModel/DataAnnotations/ValidationException.cs
+++ b/src/System.ComponentModel.Annotations/src/System/ComponentModel/DataAnnotations/ValidationException.cs
@@ -84,7 +84,7 @@ namespace System.ComponentModel.DataAnnotations
/// <summary>
/// Gets the <see>ValidationAttribute</see> instance that triggered this exception.
/// </summary>
- public ValidationAttribute ValidationAttribute { get; private set; }
+ public ValidationAttribute ValidationAttribute { get; }
/// <summary>
/// Gets the <see cref="ValidationResult" /> instance that describes the validation error.
@@ -107,6 +107,6 @@ namespace System.ComponentModel.DataAnnotations
/// <summary>
/// Gets the value that caused the validating attribute to trigger the exception
/// </summary>
- public object Value { get; private set; }
+ public object Value { get; }
}
}
diff --git a/src/System.ComponentModel.Annotations/src/System/ComponentModel/DataAnnotations/ValidationResult.cs b/src/System.ComponentModel.Annotations/src/System/ComponentModel/DataAnnotations/ValidationResult.cs
index 6521f60caa..7a74fc512c 100644
--- a/src/System.ComponentModel.Annotations/src/System/ComponentModel/DataAnnotations/ValidationResult.cs
+++ b/src/System.ComponentModel.Annotations/src/System/ComponentModel/DataAnnotations/ValidationResult.cs
@@ -26,9 +26,6 @@ namespace System.ComponentModel.DataAnnotations
/// </remarks>
public static readonly ValidationResult Success;
- private readonly IEnumerable<string> _memberNames;
- private string _errorMessage;
-
#endregion
#region All Constructors
@@ -60,8 +57,8 @@ namespace System.ComponentModel.DataAnnotations
/// </param>
public ValidationResult(string errorMessage, IEnumerable<string> memberNames)
{
- _errorMessage = errorMessage;
- _memberNames = memberNames ?? Array.Empty<string>();
+ ErrorMessage = errorMessage;
+ MemberNames = memberNames ?? Array.Empty<string>();
}
/// <summary>
@@ -76,8 +73,8 @@ namespace System.ComponentModel.DataAnnotations
throw new ArgumentNullException(nameof(validationResult));
}
- _errorMessage = validationResult._errorMessage;
- _memberNames = validationResult._memberNames;
+ ErrorMessage = validationResult.ErrorMessage;
+ MemberNames = validationResult.MemberNames;
}
#endregion
@@ -87,19 +84,12 @@ namespace System.ComponentModel.DataAnnotations
/// <summary>
/// Gets the collection of member names affected by this result. The collection may be empty but will never be null.
/// </summary>
- public IEnumerable<string> MemberNames
- {
- get { return _memberNames; }
- }
+ public IEnumerable<string> MemberNames { get; }
/// <summary>
/// Gets the error message for this result. It may be null.
/// </summary>
- public string ErrorMessage
- {
- get { return _errorMessage; }
- set { _errorMessage = value; }
- }
+ public string ErrorMessage { get; set; }
#endregion
@@ -118,10 +108,7 @@ namespace System.ComponentModel.DataAnnotations
/// The <see cref="ErrorMessage" /> property value if specified,
/// otherwise, the base <see cref="Object.ToString" /> result.
/// </returns>
- public override string ToString()
- {
- return ErrorMessage ?? base.ToString();
- }
+ public override string ToString() => ErrorMessage ?? base.ToString();
#endregion Methods
}
}
diff --git a/src/System.ComponentModel.Annotations/src/System/ComponentModel/DataAnnotations/Validator.cs b/src/System.ComponentModel.Annotations/src/System/ComponentModel/DataAnnotations/Validator.cs
index 9040ffe6c9..1fdd87d466 100644
--- a/src/System.ComponentModel.Annotations/src/System/ComponentModel/DataAnnotations/Validator.cs
+++ b/src/System.ComponentModel.Annotations/src/System/ComponentModel/DataAnnotations/Validator.cs
@@ -64,10 +64,7 @@ namespace System.ComponentModel.DataAnnotations
{
result = false;
- if (validationResults != null)
- {
- validationResults.Add(err.ValidationResult);
- }
+ validationResults?.Add(err.ValidationResult);
}
return result;
@@ -95,11 +92,9 @@ namespace System.ComponentModel.DataAnnotations
/// When <paramref name="instance" /> doesn't match the
/// <see cref="ValidationContext.ObjectInstance" />on <paramref name="validationContext" />.
/// </exception>
- public static bool TryValidateObject(object instance, ValidationContext validationContext,
- ICollection<ValidationResult> validationResults)
- {
- return TryValidateObject(instance, validationContext, validationResults, false /*validateAllProperties*/);
- }
+ public static bool TryValidateObject(
+ object instance, ValidationContext validationContext, ICollection<ValidationResult> validationResults) =>
+ TryValidateObject(instance, validationContext, validationResults, false /*validateAllProperties*/);
/// <summary>
/// Tests whether the given object instance is valid.
@@ -157,10 +152,7 @@ namespace System.ComponentModel.DataAnnotations
{
result = false;
- if (validationResults != null)
- {
- validationResults.Add(err.ValidationResult);
- }
+ validationResults?.Add(err.ValidationResult);
}
return result;
@@ -207,10 +199,7 @@ namespace System.ComponentModel.DataAnnotations
{
result = false;
- if (validationResults != null)
- {
- validationResults.Add(err.ValidationResult);
- }
+ validationResults?.Add(err.ValidationResult);
}
return result;
@@ -234,11 +223,8 @@ namespace System.ComponentModel.DataAnnotations
var attributes = _store.GetPropertyValidationAttributes(validationContext);
- var err = GetValidationErrors(value, validationContext, attributes, false).FirstOrDefault();
- if (err != null)
- {
- err.ThrowValidationException();
- }
+ GetValidationErrors(value, validationContext, attributes, false).FirstOrDefault()
+ ?.ThrowValidationException();
}
/// <summary>
@@ -301,12 +287,7 @@ namespace System.ComponentModel.DataAnnotations
SR.Validator_InstanceMustMatchValidationContextInstance, nameof(instance));
}
- var err =
- GetObjectValidationErrors(instance, validationContext, validateAllProperties, false).FirstOrDefault();
- if (err != null)
- {
- err.ThrowValidationException();
- }
+ GetObjectValidationErrors(instance, validationContext, validateAllProperties, false).FirstOrDefault()?.ThrowValidationException();
}
/// <summary>
@@ -334,12 +315,7 @@ namespace System.ComponentModel.DataAnnotations
throw new ArgumentNullException(nameof(validationContext));
}
- var err =
- GetValidationErrors(value, validationContext, validationAttributes, false).FirstOrDefault();
- if (err != null)
- {
- err.ThrowValidationException();
- }
+ GetValidationErrors(value, validationContext, validationAttributes, false).FirstOrDefault()?.ThrowValidationException();
}
/// <summary>
@@ -650,11 +626,11 @@ nameof(value));
Value = value;
}
- internal object Value { get; set; }
+ internal object Value { get; }
- internal ValidationAttribute ValidationAttribute { get; set; }
+ internal ValidationAttribute ValidationAttribute { get; }
- internal ValidationResult ValidationResult { get; set; }
+ internal ValidationResult ValidationResult { get; }
internal Exception ThrowValidationException() => throw new ValidationException(ValidationResult, ValidationAttribute, Value);
}
diff --git a/src/System.ComponentModel.Annotations/tests/MaxLengthAttributeTests.cs b/src/System.ComponentModel.Annotations/tests/MaxLengthAttributeTests.cs
index 58c294b98e..c2e74b25df 100644
--- a/src/System.ComponentModel.Annotations/tests/MaxLengthAttributeTests.cs
+++ b/src/System.ComponentModel.Annotations/tests/MaxLengthAttributeTests.cs
@@ -5,6 +5,7 @@
using System.Collections;
using System.Collections.Generic;
using System.Collections.ObjectModel;
+using System.Linq;
using Xunit;
namespace System.ComponentModel.DataAnnotations.Tests
@@ -30,9 +31,23 @@ namespace System.ComponentModel.DataAnnotations.Tests
yield return new object[] { new MaxLengthAttribute(-1), new Collection<int>(new int[20]) };
yield return new object[] { new MaxLengthAttribute(15), new Collection<string>(new string[14]) };
yield return new object[] { new MaxLengthAttribute(16), new Collection<string>(new string[16]) };
+
yield return new object[] { new MaxLengthAttribute(-1), new List<int>(new int[20]) };
yield return new object[] { new MaxLengthAttribute(15), new List<string>(new string[14]) };
yield return new object[] { new MaxLengthAttribute(16), new List<string>(new string[16]) };
+
+ //ICollection<T> but not ICollection
+ yield return new object[] { new MaxLengthAttribute(-1), new HashSet<int>(Enumerable.Range(1, 20)) };
+ yield return new object[] { new MaxLengthAttribute(15), new HashSet<string>(Enumerable.Range(1, 14).Select(i => i.ToString())) };
+ yield return new object[] { new MaxLengthAttribute(16), new HashSet<string>(Enumerable.Range(1, 16).Select(i => i.ToString())) };
+
+ //ICollection but not ICollection<T>
+ yield return new object[] { new MaxLengthAttribute(-1), new ArrayList(new int[20]) };
+ yield return new object[] { new MaxLengthAttribute(15), new ArrayList(new string[14]) };
+ yield return new object[] { new MaxLengthAttribute(16), new ArrayList(new string[16]) };
+
+ //Multi ICollection<T>
+ yield return new object[] { new MaxLengthAttribute(1), new MultiCollection() };
}
protected override IEnumerable<TestCase> InvalidValues()
@@ -47,6 +62,7 @@ namespace System.ComponentModel.DataAnnotations.Tests
{
yield return new object[] { new MaxLengthAttribute(12), new Collection<byte>(new byte[13]) };
yield return new object[] { new MaxLengthAttribute(12), new List<byte>(new byte[13]) };
+ yield return new object[] { new MaxLengthAttribute(12), new HashSet<int>(Enumerable.Range(1, 13)) };
}
[Fact]
@@ -109,22 +125,36 @@ namespace System.ComponentModel.DataAnnotations.Tests
}
[Fact]
- public static void GetValidationResult_ValueGenericICollection_ThrowsInvalidCastException()
+ public static void GetValidationResult_ValueGenericIEnumerable_ThrowsInvalidCastException()
{
- Assert.Throws<InvalidCastException>(() => new MaxLengthAttribute().GetValidationResult(new GenericICollectionClass(), new ValidationContext(new object())));
+ Assert.Throws<InvalidCastException>(() => new MaxLengthAttribute().GetValidationResult(new GenericIEnumerableClass(), new ValidationContext(new object())));
}
}
- class GenericICollectionClass : ICollection<int>
+ class GenericIEnumerableClass : IEnumerable<int>
+ {
+ public IEnumerator<int> GetEnumerator() => Enumerable.Empty<int>().GetEnumerator();
+ IEnumerator IEnumerable.GetEnumerator() => GetEnumerator();
+ }
+
+ public class MultiCollection : Collection<string>, ICollection<int>, ICollection<uint>
{
- public int Count { get; set; }
- public bool IsReadOnly => false;
- public void Add(int item) { }
- public void Clear() { }
- public bool Contains(int item) => false;
- public void CopyTo(int[] array, int arrayIndex) { }
- public IEnumerator<int> GetEnumerator() => new List<int>(new int[Count]).GetEnumerator();
- public bool Remove(int item) => false;
- IEnumerator IEnumerable.GetEnumerator() => new List<int>(new int[Count]).GetEnumerator();
+ int ICollection<int>.Count => 0;
+ int ICollection<uint>.Count => 0;
+ bool ICollection<int>.IsReadOnly => throw new NotSupportedException();
+ bool ICollection<uint>.IsReadOnly => throw new NotSupportedException();
+ void ICollection<int>.Add(int item) => throw new NotSupportedException();
+ void ICollection<uint>.Add(uint item) => throw new NotSupportedException();
+ void ICollection<int>.Clear() => throw new NotSupportedException();
+ void ICollection<uint>.Clear() => throw new NotSupportedException();
+ bool ICollection<int>.Contains(int item) => throw new NotSupportedException();
+ bool ICollection<uint>.Contains(uint item) => throw new NotSupportedException();
+ void ICollection<int>.CopyTo(int[] array, int arrayIndex) => throw new NotSupportedException();
+ void ICollection<uint>.CopyTo(uint[] array, int arrayIndex) => throw new NotSupportedException();
+ IEnumerator<int> IEnumerable<int>.GetEnumerator() => throw new NotSupportedException();
+ IEnumerator IEnumerable.GetEnumerator() => throw new NotSupportedException();
+ IEnumerator<uint> IEnumerable<uint>.GetEnumerator() => throw new NotSupportedException();
+ bool ICollection<int>.Remove(int item) => throw new NotSupportedException();
+ bool ICollection<uint>.Remove(uint item) => throw new NotSupportedException();
}
}
diff --git a/src/System.ComponentModel.Annotations/tests/MinLengthAttributeTests.cs b/src/System.ComponentModel.Annotations/tests/MinLengthAttributeTests.cs
index 5f9fafe76b..75983fc058 100644
--- a/src/System.ComponentModel.Annotations/tests/MinLengthAttributeTests.cs
+++ b/src/System.ComponentModel.Annotations/tests/MinLengthAttributeTests.cs
@@ -2,8 +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.Collections.Generic;
using System.Collections.ObjectModel;
+using System.Linq;
using Xunit;
namespace System.ComponentModel.DataAnnotations.Tests
@@ -31,6 +33,19 @@ namespace System.ComponentModel.DataAnnotations.Tests
yield return new object[] { new MinLengthAttribute(0), new List<int>(new int[0]) };
yield return new object[] { new MinLengthAttribute(12), new List<int>(new int[14]) };
yield return new object[] { new MinLengthAttribute(16), new List<string>(new string[16]) };
+
+ //ICollection<T> but not ICollection
+ yield return new object[] { new MinLengthAttribute(0), new HashSet<int>() };
+ yield return new object[] { new MinLengthAttribute(12), new HashSet<int>(Enumerable.Range(1, 14)) };
+ yield return new object[] { new MinLengthAttribute(16), new HashSet<string>(Enumerable.Range(1, 16).Select(i => i.ToString())) };
+
+ //ICollection but not ICollection<T>
+ yield return new object[] { new MinLengthAttribute(0), new ArrayList(new int[0]) };
+ yield return new object[] { new MinLengthAttribute(12), new ArrayList(new int[14]) };
+ yield return new object[] { new MinLengthAttribute(16), new ArrayList(new string[16]) };
+
+ //Multi ICollection<T>
+ yield return new object[] { new MinLengthAttribute(0), new MultiCollection() };
}
protected override IEnumerable<TestCase> InvalidValues()
@@ -98,9 +113,9 @@ namespace System.ComponentModel.DataAnnotations.Tests
}
[Fact]
- public static void GetValidationResult_ValueGenericICollection_ThrowsInvalidCastException()
+ public static void GetValidationResult_ValueGenericIEnumerable_ThrowsInvalidCastException()
{
- Assert.Throws<InvalidCastException>(() => new MinLengthAttribute(0).GetValidationResult(new GenericICollectionClass(), new ValidationContext(new object())));
+ Assert.Throws<InvalidCastException>(() => new MinLengthAttribute(0).GetValidationResult(new GenericIEnumerableClass(), new ValidationContext(new object())));
}
}
}
diff --git a/src/System.ComponentModel.Annotations/tests/Schema/ColumnAttributeTests.cs b/src/System.ComponentModel.Annotations/tests/Schema/ColumnAttributeTests.cs
index 155557ce19..8087619eef 100644
--- a/src/System.ComponentModel.Annotations/tests/Schema/ColumnAttributeTests.cs
+++ b/src/System.ComponentModel.Annotations/tests/Schema/ColumnAttributeTests.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 Xunit;
namespace System.ComponentModel.DataAnnotations.Schema.Tests
diff --git a/src/System.ComponentModel.Annotations/tests/Schema/DatabaseGeneratedAttributeTests.cs b/src/System.ComponentModel.Annotations/tests/Schema/DatabaseGeneratedAttributeTests.cs
index 8992115877..6f42ed5d3a 100644
--- a/src/System.ComponentModel.Annotations/tests/Schema/DatabaseGeneratedAttributeTests.cs
+++ b/src/System.ComponentModel.Annotations/tests/Schema/DatabaseGeneratedAttributeTests.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 Xunit;
namespace System.ComponentModel.DataAnnotations.Schema.Tests
diff --git a/src/System.ComponentModel.Primitives/src/System/ComponentModel/Component.cs b/src/System.ComponentModel.Primitives/src/System/ComponentModel/Component.cs
index 11f6e8fefd..1e8c0814b5 100644
--- a/src/System.ComponentModel.Primitives/src/System/ComponentModel/Component.cs
+++ b/src/System.ComponentModel.Primitives/src/System/ComponentModel/Component.cs
@@ -41,7 +41,7 @@ namespace System.ComponentModel
internal bool CanRaiseEventsInternal => CanRaiseEvents;
/// <summary>
- /// <para>Adds a event handler to listen to the Disposed event on the component.</para>
+ /// <para>Adds an event handler to listen to the Disposed event on the component.</para>
/// </summary>
[Browsable(false)]
[EditorBrowsable(EditorBrowsableState.Advanced)]
diff --git a/src/System.ComponentModel.Primitives/src/System/ComponentModel/IComponent.cs b/src/System.ComponentModel.Primitives/src/System/ComponentModel/IComponent.cs
index b21bf7f2ca..4e29c0eae4 100644
--- a/src/System.ComponentModel.Primitives/src/System/ComponentModel/IComponent.cs
+++ b/src/System.ComponentModel.Primitives/src/System/ComponentModel/IComponent.cs
@@ -38,7 +38,7 @@ namespace System.ComponentModel
}
/// <summary>
- /// <para>Adds a event handler to listen to the Disposed event on the component.</para>
+ /// <para>Adds an event handler to listen to the Disposed event on the component.</para>
/// </summary>
event EventHandler Disposed;
}
diff --git a/src/System.ComponentModel.Primitives/tests/CategoryAttributeTests.cs b/src/System.ComponentModel.Primitives/tests/CategoryAttributeTests.cs
index 0bbe4e0658..6d7d85c0f9 100644
--- a/src/System.ComponentModel.Primitives/tests/CategoryAttributeTests.cs
+++ b/src/System.ComponentModel.Primitives/tests/CategoryAttributeTests.cs
@@ -10,6 +10,7 @@ namespace System.ComponentModel.Tests
public class CategoryAttributeTests
{
[Fact]
+ [SkipOnTargetFramework(TargetFrameworkMonikers.NetFramework)] // NetFX does not have fix for #21369
public void Ctor_Default()
{
var attribute = new CategoryAttribute();
diff --git a/src/System.ComponentModel.TypeConverter/src/System/ComponentModel/MarshalByValueComponent.cs b/src/System.ComponentModel.TypeConverter/src/System/ComponentModel/MarshalByValueComponent.cs
index a52609fea8..1af15d3fb5 100644
--- a/src/System.ComponentModel.TypeConverter/src/System/ComponentModel/MarshalByValueComponent.cs
+++ b/src/System.ComponentModel.TypeConverter/src/System/ComponentModel/MarshalByValueComponent.cs
@@ -42,7 +42,7 @@ namespace System.ComponentModel
}
/// <summary>
- /// <para>Adds a event handler to listen to the Disposed event on the component.</para>
+ /// <para>Adds an event handler to listen to the Disposed event on the component.</para>
/// </summary>
public event EventHandler Disposed
{
diff --git a/src/System.ComponentModel.TypeConverter/src/System/ComponentModel/MaskedTextProvider.cs b/src/System.ComponentModel.TypeConverter/src/System/ComponentModel/MaskedTextProvider.cs
index 522e33e704..174d609906 100644
--- a/src/System.ComponentModel.TypeConverter/src/System/ComponentModel/MaskedTextProvider.cs
+++ b/src/System.ComponentModel.TypeConverter/src/System/ComponentModel/MaskedTextProvider.cs
@@ -1782,7 +1782,7 @@ namespace System.ComponentModel
/// character and removes any remaining characters in the range unless the character at the specified position
/// is to be escaped.
/// If specified range covers more than one assigned edit character, shift-left is performed after replacing
- /// the first character. This is useful when in a edit box the user selects text and types a character to replace it.
+ /// the first character. This is useful when in an edit box the user selects text and types a character to replace it.
/// On exit the testPosition contains last position where the primary operation was actually performed if successful,
/// otherwise the first position that made the test fail. This position is relative to the test string.
/// The MaskedTextResultHint out param gives more information about the operation result.
diff --git a/src/System.Configuration.ConfigurationManager/src/System/Configuration/ClientConfigPaths.cs b/src/System.Configuration.ConfigurationManager/src/System/Configuration/ClientConfigPaths.cs
index b62f885187..446df7227d 100644
--- a/src/System.Configuration.ConfigurationManager/src/System/Configuration/ClientConfigPaths.cs
+++ b/src/System.Configuration.ConfigurationManager/src/System/Configuration/ClientConfigPaths.cs
@@ -92,7 +92,7 @@ namespace System.Configuration
// (1) Company name
string part1 = Validate(_companyName, limitSize: true);
- // (2) Domain or product name & a application urit hash
+ // (2) Domain or product name & an application urit hash
string namePrefix = Validate(AppDomain.CurrentDomain.FriendlyName, limitSize: true);
if (string.IsNullOrEmpty(namePrefix))
namePrefix = Validate(ProductName, limitSize: true);
diff --git a/src/System.Configuration.ConfigurationManager/src/System/Configuration/ConfigurationElement.cs b/src/System.Configuration.ConfigurationManager/src/System/Configuration/ConfigurationElement.cs
index 885fdb9c64..0a3f4634c3 100644
--- a/src/System.Configuration.ConfigurationManager/src/System/Configuration/ConfigurationElement.cs
+++ b/src/System.Configuration.ConfigurationManager/src/System/Configuration/ConfigurationElement.cs
@@ -1336,7 +1336,7 @@ namespace System.Configuration
((lockType != ConfigurationLockCollectionType.LockedElements) &&
(lockType != ConfigurationLockCollectionType.LockedElementsExceptionList) &&
typeof(ConfigurationElement).IsAssignableFrom(propToLock.Type)) ||
- // or if not locking elements but the property is a element
+ // or if not locking elements but the property is an element
(((lockType == ConfigurationLockCollectionType.LockedElements) ||
(lockType == ConfigurationLockCollectionType.LockedElementsExceptionList)) &&
!typeof(ConfigurationElement).IsAssignableFrom(propToLock.Type))
diff --git a/src/System.Configuration.ConfigurationManager/src/System/Configuration/ConnectionStringSettingsCollection.cs b/src/System.Configuration.ConfigurationManager/src/System/Configuration/ConnectionStringSettingsCollection.cs
index 018aa2f4d4..bc2423688b 100644
--- a/src/System.Configuration.ConfigurationManager/src/System/Configuration/ConnectionStringSettingsCollection.cs
+++ b/src/System.Configuration.ConfigurationManager/src/System/Configuration/ConnectionStringSettingsCollection.cs
@@ -39,7 +39,7 @@ namespace System.Configuration
}
// the connection string behavior is strange in that is acts kind of like a
- // basic map and partially like a add remove clear collection
+ // basic map and partially like an add remove clear collection
// Overriding these methods allows for the specific behaviors to be
// patterened
protected override void BaseAdd(int index, ConfigurationElement element)
@@ -83,4 +83,4 @@ namespace System.Configuration
BaseClear();
}
}
-} \ No newline at end of file
+}
diff --git a/src/System.Configuration.ConfigurationManager/src/System/Configuration/MgmtConfigurationRecord.cs b/src/System.Configuration.ConfigurationManager/src/System/Configuration/MgmtConfigurationRecord.cs
index e0f4661dc2..87057bfb1d 100644
--- a/src/System.Configuration.ConfigurationManager/src/System/Configuration/MgmtConfigurationRecord.cs
+++ b/src/System.Configuration.ConfigurationManager/src/System/Configuration/MgmtConfigurationRecord.cs
@@ -1747,7 +1747,7 @@ namespace System.Configuration
else definitionUpdates = null;
}
- // Take a element name, and create an xml string that contains
+ // Take an element name, and create an xml string that contains
// that element in an empty state
private string WriteEmptyElement(string elementName)
{
@@ -3183,4 +3183,4 @@ namespace System.Configuration
}
}
}
-} \ No newline at end of file
+}
diff --git a/src/System.Console/tests/NegativeTesting.cs b/src/System.Console/tests/NegativeTesting.cs
index 86a796f24c..9315e76a4b 100644
--- a/src/System.Console/tests/NegativeTesting.cs
+++ b/src/System.Console/tests/NegativeTesting.cs
@@ -8,13 +8,13 @@ using Xunit;
public class NegativeTesting
{
- [ConditionalFact(typeof(PlatformDetection), nameof(PlatformDetection.IsWinRT))] // In appcontainer, the stream cannot be opened: there is no Console
+ [ConditionalFact(typeof(PlatformDetection), nameof(PlatformDetection.IsInAppContainer))] // In appcontainer, the stream cannot be opened: there is no Console
public static void OpenStandardOutNegativeTests_Uap()
{
Assert.Same(Stream.Null, Console.OpenStandardOutput());
}
- [ConditionalFact(typeof(PlatformDetection), nameof(PlatformDetection.IsWinRT))] // In appcontainer, the stream cannot be opened: there is no Console
+ [ConditionalFact(typeof(PlatformDetection), nameof(PlatformDetection.IsInAppContainer))] // In appcontainer, the stream cannot be opened: there is no Console
public static void OpenStandardErrorNegativeTests_Uap()
{
Assert.Same(Stream.Null, Console.OpenStandardError());
diff --git a/src/System.Console/tests/WindowAndCursorProps.cs b/src/System.Console/tests/WindowAndCursorProps.cs
index ff8eb09e71..00e63a3ce2 100644
--- a/src/System.Console/tests/WindowAndCursorProps.cs
+++ b/src/System.Console/tests/WindowAndCursorProps.cs
@@ -154,7 +154,16 @@ public class WindowAndCursorProps : RemoteExecutorTestBase
{
string newTitle = new string('a', int.Parse(lengthOfTitleString));
Console.Title = newTitle;
- Assert.Equal(newTitle, Console.Title);
+
+ if (newTitle.Length > 513 && PlatformDetection.IsWindowsRedStone2)
+ {
+ // RS2 has a bug when getting the window title when the title length is longer than 513 character
+ Assert.Throws<IOException>(() => Console.Title);
+ }
+ else
+ {
+ Assert.Equal(newTitle, Console.Title);
+ }
return SuccessExitCode;
}, lengthOfTitle.ToString()).Dispose();
}
diff --git a/src/System.Data.Common/src/System/Data/DataTable.cs b/src/System.Data.Common/src/System/Data/DataTable.cs
index 8330c56a15..3079e9ab6f 100644
--- a/src/System.Data.Common/src/System/Data/DataTable.cs
+++ b/src/System.Data.Common/src/System/Data/DataTable.cs
@@ -1825,7 +1825,7 @@ namespace System.Data
}
private string GetInheritedNamespace(List<DataTable> visitedTables)
{
- // if there is nested relation: ie: this table is nested child of a another table and
+ // if there is nested relation: ie: this table is nested child of another table and
// if it is not self nested, return parent tables NS: Meanwhile make sure
DataRelation[] nestedRelations = NestedParentRelations;
if (nestedRelations.Length > 0)
diff --git a/src/System.Data.Common/tests/System/Data/DataTableCollectionTest.cs b/src/System.Data.Common/tests/System/Data/DataTableCollectionTest.cs
index 0f76f6d84a..65d574356f 100644
--- a/src/System.Data.Common/tests/System/Data/DataTableCollectionTest.cs
+++ b/src/System.Data.Common/tests/System/Data/DataTableCollectionTest.cs
@@ -243,7 +243,7 @@ namespace System.Data.Tests
string tblname = "";
/* checking for a recently input table, expecting true */
Assert.Equal(true, tbcol.Contains(_tables[0].TableName));
- /* trying to check with a empty string, expecting false */
+ /* trying to check with an empty string, expecting false */
Assert.Equal(false, tbcol.Contains(tblname));
/* trying to check for a table that donot exist, expecting false */
Assert.Equal(false, tbcol.Contains("InvalidTableName"));
@@ -267,7 +267,7 @@ namespace System.Data.Tests
Assert.Equal("Table3", array[2].TableName);
Assert.Equal("Table4", array[3].TableName);
- /* copying with in a array */
+ /* copying with in an array */
DataTable[] array1 = new DataTable[6];
tbcol.CopyTo(array1, 2);
Assert.Equal(null, array1[0]);
diff --git a/src/System.Data.Common/tests/System/Data/DataTableReaderTest.cs b/src/System.Data.Common/tests/System/Data/DataTableReaderTest.cs
index 81ea3fc59b..6eb0951b74 100644
--- a/src/System.Data.Common/tests/System/Data/DataTableReaderTest.cs
+++ b/src/System.Data.Common/tests/System/Data/DataTableReaderTest.cs
@@ -729,7 +729,7 @@ namespace System.Data.Tests
Assert.Equal("col_int*5", schemaTable.Rows[11]["Expression"]);
Assert.True((bool)schemaTable.Rows[11]["IsReadOnly"]);
- // if expression depends on a external col, then set Expression as null..
+ // if expression depends on an external col, then set Expression as null..
Assert.Equal("col_expression_ext", schemaTable.Rows[12]["ColumnName"]);
Assert.Equal(DBNull.Value, schemaTable.Rows[12]["Expression"]);
Assert.True((bool)schemaTable.Rows[12]["IsReadOnly"]);
diff --git a/src/System.Data.Common/tests/System/Data/SqlTypes/SqlMoneyTest.cs b/src/System.Data.Common/tests/System/Data/SqlTypes/SqlMoneyTest.cs
index e4b9ebd0dd..2b40b21a90 100644
--- a/src/System.Data.Common/tests/System/Data/SqlTypes/SqlMoneyTest.cs
+++ b/src/System.Data.Common/tests/System/Data/SqlTypes/SqlMoneyTest.cs
@@ -88,7 +88,7 @@ namespace System.Data.Tests.SqlTypes
[Fact]
public void PublicFields()
{
- // FIXME: There is a error in msdn docs, it says thath MaxValue
+ // FIXME: There is an error in msdn docs, it says thath MaxValue
// is 922,337,203,685,475.5807 when the actual value is
// 922,337,203,685,477.5807
Assert.Equal(922337203685477.5807m, SqlMoney.MaxValue.Value);
diff --git a/src/System.Data.DataSetExtensions/src/System/Data/TypedTableBase.cs b/src/System.Data.DataSetExtensions/src/System/Data/TypedTableBase.cs
index 5e590502bb..908f5f078e 100644
--- a/src/System.Data.DataSetExtensions/src/System/Data/TypedTableBase.cs
+++ b/src/System.Data.DataSetExtensions/src/System/Data/TypedTableBase.cs
@@ -32,7 +32,7 @@ namespace System.Data
: base(info, context) { }
/// <summary>
- /// This property returns a enumerator of T for the TypedTable. Note, this could
+ /// This property returns an enumerator of T for the TypedTable. Note, this could
/// execute the underlying Linq expression.
/// </summary>
/// <returns>IEnumerable of T.</returns>
diff --git a/src/System.Data.DataSetExtensions/tests/Mono/DataTableExtensionsTest.cs b/src/System.Data.DataSetExtensions/tests/Mono/DataTableExtensionsTest.cs
index 30cb49696c..60cdc772ab 100644
--- a/src/System.Data.DataSetExtensions/tests/Mono/DataTableExtensionsTest.cs
+++ b/src/System.Data.DataSetExtensions/tests/Mono/DataTableExtensionsTest.cs
@@ -40,6 +40,8 @@ namespace MonoTests.System.Data
{
public class DataTableExtensionsTest
{
+ private string _testDataSet = "testdataset1.xml";
+
[Fact]
public void CopyToDataTableNoArgNoRows()
{
@@ -77,7 +79,7 @@ namespace MonoTests.System.Data
public void AsEnumerable()
{
DataSet ds = new DataSet();
- ds.ReadXml("Mono/testdataset1.xml");
+ ds.ReadXml(_testDataSet);
DataTable dt = ds.Tables[0];
Assert.Equal("ScoreList", dt.TableName);
var dv = dt.AsEnumerable();
diff --git a/src/System.Data.DataSetExtensions/tests/Mono/EnumerableRowCollectionTest.cs b/src/System.Data.DataSetExtensions/tests/Mono/EnumerableRowCollectionTest.cs
index c0b33e59e7..8f634e13fc 100644
--- a/src/System.Data.DataSetExtensions/tests/Mono/EnumerableRowCollectionTest.cs
+++ b/src/System.Data.DataSetExtensions/tests/Mono/EnumerableRowCollectionTest.cs
@@ -39,11 +39,13 @@ namespace MonoTests.System.Data
{
public class EnumerableRowCollectionTest
{
+ private string _testDataSet = "testdataset1.xml";
+
[Fact]
public void QueryWhere()
{
var ds = new DataSet();
- ds.ReadXml("Mono/testdataset1.xml");
+ ds.ReadXml(_testDataSet);
var table = ds.Tables[0];
/* schema generated as ...
var table = ds.Tables.Add ("ScoreList");
@@ -70,7 +72,7 @@ namespace MonoTests.System.Data
public void QueryWhereSelect ()
{
var ds = new DataSet ();
- ds.ReadXml ("Mono/testdataset1.xml");
+ ds.ReadXml (_testDataSet);
var table = ds.Tables [0];
var q = from line in table.AsEnumerable ()
where line.Field<int> ("Score") > 80
@@ -91,7 +93,7 @@ namespace MonoTests.System.Data
public void QueryWhereSelectOrderBy ()
{
var ds = new DataSet ();
- ds.ReadXml ("Mono/testdataset1.xml");
+ ds.ReadXml (_testDataSet);
var table = ds.Tables [0];
var q = from line in table.AsEnumerable ()
where line.Field<int> ("Score") >= 80
@@ -121,7 +123,7 @@ namespace MonoTests.System.Data
public void QueryWhereSelectOrderByDescending ()
{
var ds = new DataSet ();
- ds.ReadXml ("Mono/testdataset1.xml");
+ ds.ReadXml (_testDataSet);
var table = ds.Tables [0];
var q = from line in table.AsEnumerable ()
where line.Field<int> ("Score") >= 80
@@ -151,7 +153,7 @@ namespace MonoTests.System.Data
public void ThenBy ()
{
var ds = new DataSet ();
- ds.ReadXml ("Mono/testdataset1.xml");
+ ds.ReadXml (_testDataSet);
var table = ds.Tables [0];
var q = from line in table.AsEnumerable ()
where line.Field<int> ("Score") >= 80
@@ -181,7 +183,7 @@ namespace MonoTests.System.Data
public void ThenByDescending ()
{
var ds = new DataSet ();
- ds.ReadXml ("Mono/testdataset1.xml");
+ ds.ReadXml (_testDataSet);
var table = ds.Tables [0];
var q = from line in table.AsEnumerable ()
where line.Field<int> ("Score") >= 80
diff --git a/src/System.Data.Odbc/dir.props b/src/System.Data.Odbc/dir.props
index af5b293385..4356decc45 100644
--- a/src/System.Data.Odbc/dir.props
+++ b/src/System.Data.Odbc/dir.props
@@ -2,7 +2,7 @@
<Project ToolsVersion="14.0" DefaultTargets="Build" xmlns="http://schemas.microsoft.com/developer/msbuild/2003">
<Import Project="..\dir.props" />
<PropertyGroup>
- <AssemblyVersion>4.0.1.0</AssemblyVersion>
+ <AssemblyVersion>4.0.0.0</AssemblyVersion>
<AssemblyKey>Open</AssemblyKey>
</PropertyGroup>
</Project> \ No newline at end of file
diff --git a/src/System.Data.Odbc/pkg/System.Data.Odbc.pkgproj b/src/System.Data.Odbc/pkg/System.Data.Odbc.pkgproj
new file mode 100644
index 0000000000..c0232ef4ea
--- /dev/null
+++ b/src/System.Data.Odbc/pkg/System.Data.Odbc.pkgproj
@@ -0,0 +1,11 @@
+<?xml version="1.0" encoding="utf-8"?>
+<Project ToolsVersion="14.0" DefaultTargets="Build" xmlns="http://schemas.microsoft.com/developer/msbuild/2003">
+ <Import Project="$([MSBuild]::GetDirectoryNameOfFileAbove($(MSBuildThisFileDirectory), dir.props))\dir.props" />
+ <ItemGroup>
+ <ProjectReference Include="..\ref\System.Data.Odbc.csproj">
+ <SupportedFramework>net461;netcoreapp2.0;$(AllXamarinFrameworks)</SupportedFramework>
+ </ProjectReference>
+ <ProjectReference Include="..\src\System.Data.Odbc.csproj" />
+ </ItemGroup>
+ <Import Project="$([MSBuild]::GetDirectoryNameOfFileAbove($(MSBuildThisFileDirectory), dir.targets))\dir.targets" />
+</Project>
diff --git a/src/System.Data.Odbc/src/Configurations.props b/src/System.Data.Odbc/src/Configurations.props
index 34857a0ae4..8c227f14fc 100644
--- a/src/System.Data.Odbc/src/Configurations.props
+++ b/src/System.Data.Odbc/src/Configurations.props
@@ -3,6 +3,7 @@
<PropertyGroup>
<BuildConfigurations>
netfx-Windows_NT;
+ netstandard;
netstandard-Linux;
netstandard-OSX;
netstandard-Windows_NT;
diff --git a/src/System.Data.Odbc/src/Resources/Strings.resx b/src/System.Data.Odbc/src/Resources/Strings.resx
index a0981e69ba..7c1d6f4331 100644
--- a/src/System.Data.Odbc/src/Resources/Strings.resx
+++ b/src/System.Data.Odbc/src/Resources/Strings.resx
@@ -429,4 +429,7 @@
<data name="Odbc_OpenConnectionNoOwner" xml:space="preserve">
<value>An internal connection does not have an owner.</value>
</data>
+ <data name="Odbc_PlatformNotSupported" xml:space="preserve">
+ <value>System.Data.ODBC is not supported on this platform.</value>
+ </data>
</root> \ No newline at end of file
diff --git a/src/System.Data.Odbc/src/System.Data.Odbc.csproj b/src/System.Data.Odbc/src/System.Data.Odbc.csproj
index 43dbb34d2a..e24e87e76c 100644
--- a/src/System.Data.Odbc/src/System.Data.Odbc.csproj
+++ b/src/System.Data.Odbc/src/System.Data.Odbc.csproj
@@ -6,6 +6,7 @@
<AssemblyName>System.Data.Odbc</AssemblyName>
<AllowUnsafeBlocks>true</AllowUnsafeBlocks>
<IsPartialFacadeAssembly Condition="'$(TargetGroup)' == 'netfx'">true</IsPartialFacadeAssembly>
+ <GeneratePlatformNotSupportedAssemblyMessage Condition="'$(TargetGroup)' == 'netstandard' AND '$(OSGroup)' == 'AnyOS'">SR.Odbc_PlatformNotSupported</GeneratePlatformNotSupportedAssemblyMessage>
</PropertyGroup>
<PropertyGroup Condition="'$(Configuration)|$(Platform)' == 'netfx-Windows_NT-Debug|AnyCPU'" />
<PropertyGroup Condition="'$(Configuration)|$(Platform)' == 'netfx-Windows_NT-Release|AnyCPU'" />
@@ -15,7 +16,7 @@
<PropertyGroup Condition="'$(Configuration)|$(Platform)' == 'netstandard-OSX-Release|AnyCPU'" />
<PropertyGroup Condition="'$(Configuration)|$(Platform)' == 'netstandard-Windows_NT-Debug|AnyCPU'" />
<PropertyGroup Condition="'$(Configuration)|$(Platform)' == 'netstandard-Windows_NT-Release|AnyCPU'" />
- <ItemGroup Condition="'$(IsPartialFacadeAssembly)' != 'true'">
+ <ItemGroup Condition="'$(IsPartialFacadeAssembly)' != 'true' AND '$(OSGroup)' != 'AnyOS'">
<Compile Include="$(CommonPath)\System\Data\Common\AdapterUtil.cs">
<Link>Common\System\Data\Common\AdapterUtil.cs</Link>
</Compile>
diff --git a/src/System.Data.SqlClient/ref/System.Data.SqlClient.cs b/src/System.Data.SqlClient/ref/System.Data.SqlClient.cs
index ba7f114727..731959fa3f 100644
--- a/src/System.Data.SqlClient/ref/System.Data.SqlClient.cs
+++ b/src/System.Data.SqlClient/ref/System.Data.SqlClient.cs
@@ -675,6 +675,7 @@ namespace System.Data.SqlClient
public SqlParameter(string parameterName, System.Data.SqlDbType dbType, int size) { }
public SqlParameter(string parameterName, System.Data.SqlDbType dbType, int size, string sourceColumn) { }
public SqlParameter(string parameterName, object value) { }
+ public SqlParameter(string parameterName, System.Data.SqlDbType dbType, int size, System.Data.ParameterDirection direction, bool isNullable, byte precision, byte scale, string sourceColumn, System.Data.DataRowVersion sourceVersion, object value) { }
public SqlParameter(string parameterName, System.Data.SqlDbType dbType, int size, System.Data.ParameterDirection direction, byte precision, byte scale, string sourceColumn, System.Data.DataRowVersion sourceVersion, bool sourceColumnNullMapping, object value, string xmlSchemaCollectionDatabase, string xmlSchemaCollectionOwningSchema, string xmlSchemaCollectionName) { }
object ICloneable.Clone() { throw null; }
public System.Data.SqlTypes.SqlCompareOptions CompareInfo { get { throw null; } set { } }
@@ -763,4 +764,4 @@ namespace System.Data
{
internal OperationAbortedException() { }
}
-} \ No newline at end of file
+}
diff --git a/src/System.Data.SqlClient/ref/System.Data.SqlClient.csproj b/src/System.Data.SqlClient/ref/System.Data.SqlClient.csproj
index 8088626cde..18ecba930a 100644
--- a/src/System.Data.SqlClient/ref/System.Data.SqlClient.csproj
+++ b/src/System.Data.SqlClient/ref/System.Data.SqlClient.csproj
@@ -4,6 +4,9 @@
<PropertyGroup>
<ProjectGuid>{D58E8D2B-3331-4660-8DFB-512D66F8EC63}</ProjectGuid>
<IsPartialFacadeAssembly Condition="'$(TargetGroup)' == 'netfx'">true</IsPartialFacadeAssembly>
+ <!-- Must match version supported by frameworks which support 4.3.* inbox.
+ Can be removed when API is added and this assembly is versioned to 4.4.* -->
+ <AssemblyVersion Condition="'$(TargetsNetFx)' != 'true'">4.3.0.0</AssemblyVersion>
</PropertyGroup>
<PropertyGroup Condition="'$(Configuration)|$(Platform)' == 'netfx-Debug|AnyCPU'" />
<PropertyGroup Condition="'$(Configuration)|$(Platform)' == 'netfx-Release|AnyCPU'" />
diff --git a/src/System.Data.SqlClient/src/System/Data/Common/DbConnectionOptions.cs b/src/System.Data.SqlClient/src/System/Data/Common/DbConnectionOptions.cs
index dc7729a93c..fbb572764e 100644
--- a/src/System.Data.SqlClient/src/System/Data/Common/DbConnectionOptions.cs
+++ b/src/System.Data.SqlClient/src/System/Data/Common/DbConnectionOptions.cs
@@ -47,7 +47,7 @@ namespace System.Data.Common
public bool ConvertValueToIntegratedSecurity()
{
string value;
- return _parsetable.TryGetValue(KEY.Integrated_Security, out value) ?
+ return _parsetable.TryGetValue(KEY.Integrated_Security, out value) && value != null ?
ConvertValueToIntegratedSecurityInternal(value) :
false;
}
@@ -75,7 +75,7 @@ namespace System.Data.Common
public int ConvertValueToInt32(string keyName, int defaultValue)
{
string value;
- return _parsetable.TryGetValue(keyName, out value) ?
+ return _parsetable.TryGetValue(keyName, out value) && value != null ?
ConvertToInt32Internal(keyName, value) :
defaultValue;
}
@@ -107,4 +107,4 @@ namespace System.Data.Common
return _parsetable.ContainsKey(keyword);
}
}
-} \ No newline at end of file
+}
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 f11157e53c..cf6c3f673a 100644
--- a/src/System.Data.SqlClient/src/System/Data/ProviderBase/DbConnectionFactory.cs
+++ b/src/System.Data.SqlClient/src/System/Data/ProviderBase/DbConnectionFactory.cs
@@ -395,15 +395,14 @@ namespace System.Data.ProviderBase
}
}
-
- DbConnectionPoolGroup newConnectionPoolGroup = new DbConnectionPoolGroup(connectionOptions, key, poolOptions);
- newConnectionPoolGroup.ProviderInfo = CreateConnectionPoolGroupProviderInfo(connectionOptions);
-
lock (this)
{
connectionPoolGroups = _connectionPoolGroups;
if (!connectionPoolGroups.TryGetValue(key, out connectionPoolGroup))
{
+ DbConnectionPoolGroup newConnectionPoolGroup = new DbConnectionPoolGroup(connectionOptions, key, poolOptions);
+ newConnectionPoolGroup.ProviderInfo = CreateConnectionPoolGroupProviderInfo(connectionOptions);
+
// build new dictionary with space for new connection string
Dictionary<DbConnectionPoolKey, DbConnectionPoolGroup> newConnectionPoolGroups = new Dictionary<DbConnectionPoolKey, DbConnectionPoolGroup>(1 + connectionPoolGroups.Count);
foreach (KeyValuePair<DbConnectionPoolKey, DbConnectionPoolGroup> entry in connectionPoolGroups)
diff --git a/src/System.Data.SqlClient/src/System/Data/ProviderBase/DbConnectionPoolGroup.cs b/src/System.Data.SqlClient/src/System/Data/ProviderBase/DbConnectionPoolGroup.cs
index fb857dc68a..b28ade14d2 100644
--- a/src/System.Data.SqlClient/src/System/Data/ProviderBase/DbConnectionPoolGroup.cs
+++ b/src/System.Data.SqlClient/src/System/Data/ProviderBase/DbConnectionPoolGroup.cs
@@ -186,20 +186,19 @@ namespace System.Data.ProviderBase
currentIdentity = null;
}
}
+
if (null != currentIdentity)
{
- if (!_poolCollection.TryGetValue(currentIdentity, out pool))
- { // find the pool
- DbConnectionPoolProviderInfo connectionPoolProviderInfo = connectionFactory.CreateConnectionPoolProviderInfo(this.ConnectionOptions);
-
- // optimistically create pool, but its callbacks are delayed until after actual add
- DbConnectionPool newPool = new DbConnectionPool(connectionFactory, this, currentIdentity, connectionPoolProviderInfo);
-
+ if (!_poolCollection.TryGetValue(currentIdentity, out pool)) // find the pool
+ {
lock (this)
{
// Did someone already add it to the list?
if (!_poolCollection.TryGetValue(currentIdentity, out pool))
{
+ DbConnectionPoolProviderInfo connectionPoolProviderInfo = connectionFactory.CreateConnectionPoolProviderInfo(this.ConnectionOptions);
+ DbConnectionPool newPool = new DbConnectionPool(connectionFactory, this, currentIdentity, connectionPoolProviderInfo);
+
if (MarkPoolGroupAsActive())
{
// If we get here, we know for certain that we there isn't
@@ -209,12 +208,15 @@ namespace System.Data.ProviderBase
bool addResult = _poolCollection.TryAdd(currentIdentity, newPool);
Debug.Assert(addResult, "No other pool with current identity should exist at this point");
pool = newPool;
- newPool = null;
}
else
{
// else pool entry has been disabled so don't create new pools
Debug.Assert(PoolGroupStateDisabled == _state, "state should be disabled");
+
+ // don't need to call connectionFactory.QueuePoolForRelease(newPool) because
+ // pool callbacks were delayed and no risk of connections being created
+ newPool.Shutdown();
}
}
else
@@ -223,13 +225,6 @@ namespace System.Data.ProviderBase
Debug.Assert(PoolGroupStateActive == _state, "state should be active since a pool exists and lock holds");
}
}
-
- if (null != newPool)
- {
- // don't need to call connectionFactory.QueuePoolForRelease(newPool) because
- // pool callbacks were delayed and no risk of connections being created
- newPool.Shutdown();
- }
}
// the found pool could be in any state
}
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 53f48d4706..ec32c2f52b 100644
--- a/src/System.Data.SqlClient/src/System/Data/SqlClient/SqlCommand.cs
+++ b/src/System.Data.SqlClient/src/System/Data/SqlClient/SqlCommand.cs
@@ -257,7 +257,7 @@ namespace System.Data.SqlClient
}
set
{
- // Don't allow the connection to be changed while in a async operation.
+ // Don't allow the connection to be changed while in an async operation.
if (_activeConnection != value && _activeConnection != null)
{ // If new value...
if (cachedAsyncState.PendingAsyncOperation)
@@ -363,7 +363,7 @@ namespace System.Data.SqlClient
}
set
{
- // Don't allow the transaction to be changed while in a async operation.
+ // Don't allow the transaction to be changed while in an async operation.
if (_transaction != value && _activeConnection != null)
{ // If new value...
if (cachedAsyncState.PendingAsyncOperation)
diff --git a/src/System.Data.SqlClient/src/System/Data/SqlClient/SqlDataReader.cs b/src/System.Data.SqlClient/src/System/Data/SqlClient/SqlDataReader.cs
index 287ddbce22..708c6f08b7 100644
--- a/src/System.Data.SqlClient/src/System/Data/SqlClient/SqlDataReader.cs
+++ b/src/System.Data.SqlClient/src/System/Data/SqlClient/SqlDataReader.cs
@@ -2349,7 +2349,7 @@ namespace System.Data.SqlClient
}
else if (_typeSystem != SqlConnectionString.TypeSystem.SQLServer2000)
{
- // TypeSystem.SQLServer2005
+ // TypeSystem.SQLServer2005 and above
if (metaData.type == SqlDbType.Udt)
{
@@ -2535,7 +2535,7 @@ namespace System.Data.SqlClient
}
else if (_typeSystem != SqlConnectionString.TypeSystem.SQLServer2000)
{
- // TypeSystem.SQLServer2005
+ // TypeSystem.SQLServer2005 and above
if (metaData.type != SqlDbType.Udt)
{
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 0bc0df2c97..f5c03bb81c 100644
--- a/src/System.Data.SqlClient/src/System/Data/SqlClient/SqlInternalConnectionTds.cs
+++ b/src/System.Data.SqlClient/src/System/Data/SqlClient/SqlInternalConnectionTds.cs
@@ -1416,7 +1416,7 @@ namespace System.Data.SqlClient
// Determine unit interval
if (timeout.IsInfinite)
{
- timeoutUnitInterval = checked((long)ADP.FailoverTimeoutStep * ADP.TimerFromSeconds(ADP.DefaultConnectionTimeout));
+ timeoutUnitInterval = checked((long)(ADP.FailoverTimeoutStep * ADP.TimerFromSeconds(ADP.DefaultConnectionTimeout)));
}
else
{
diff --git a/src/System.Data.SqlClient/src/System/Data/SqlClient/SqlParameter.cs b/src/System.Data.SqlClient/src/System/Data/SqlClient/SqlParameter.cs
index 2946cfd530..56f0f078b8 100644
--- a/src/System.Data.SqlClient/src/System/Data/SqlClient/SqlParameter.cs
+++ b/src/System.Data.SqlClient/src/System/Data/SqlClient/SqlParameter.cs
@@ -112,6 +112,27 @@ namespace System.Data.SqlClient
public SqlParameter(
string parameterName,
+ SqlDbType dbType,
+ int size,
+ ParameterDirection direction,
+ bool isNullable,
+ byte precision,
+ byte scale,
+ string sourceColumn,
+ DataRowVersion sourceVersion,
+ object value
+ ) : this(parameterName, dbType, size, sourceColumn)
+ {
+ this.Direction = direction;
+ this.IsNullable = isNullable;
+ this.Precision = precision;
+ this.Scale = scale;
+ this.SourceVersion = sourceVersion;
+ this.Value = value;
+ }
+
+ public SqlParameter(
+ string parameterName,
SqlDbType dbType,
int size,
ParameterDirection direction,
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 6f43f33e2f..538ebc4fb4 100644
--- a/src/System.Data.SqlClient/src/System/Data/SqlClient/TdsParser.cs
+++ b/src/System.Data.SqlClient/src/System/Data/SqlClient/TdsParser.cs
@@ -1193,7 +1193,7 @@ namespace System.Data.SqlClient
/*
The error message should come back in the following format: "TCP Provider: MESSAGE TEXT"
If the message is received on a Win9x OS, the error message will not contain MESSAGE TEXT
- If we get a error message with no message text, just return the entire message otherwise
+ If we get an error message with no message text, just return the entire message otherwise
return just the message text.
*/
if (len > 0)
@@ -2551,7 +2551,7 @@ namespace System.Data.SqlClient
// situations where this can occur are: an invalid buffer received from client, login error
// and the server refused our connection, and the case where we are trying to log in but
// the server has reached its max connection limit. Bottom line, we need to throw general
- // error in the cases where we did not receive a error token along with the DONE_ERROR.
+ // error in the cases where we did not receive an error token along with the DONE_ERROR.
if ((TdsEnums.DONE_ERROR == (TdsEnums.DONE_ERROR & status)) && stateObj.ErrorCount == 0 &&
stateObj._errorTokenReceived == false && (RunBehavior.Clean != (RunBehavior.Clean & run)))
{
@@ -9630,4 +9630,4 @@ namespace System.Data.SqlClient
return true;
}
} // tdsparser
-}//namespace \ No newline at end of file
+}//namespace
diff --git a/src/System.Data.SqlClient/tests/FunctionalTests/SqlConnectionBasicTests.cs b/src/System.Data.SqlClient/tests/FunctionalTests/SqlConnectionBasicTests.cs
index be2af7860f..2df596fac9 100644
--- a/src/System.Data.SqlClient/tests/FunctionalTests/SqlConnectionBasicTests.cs
+++ b/src/System.Data.SqlClient/tests/FunctionalTests/SqlConnectionBasicTests.cs
@@ -51,5 +51,33 @@ namespace System.Data.SqlClient.Tests
Assert.Same(typeof(SqlClientFactory), factory.GetType());
Assert.Same(SqlClientFactory.Instance, factory);
}
+
+ [Fact]
+ public void SqlConnectionValidParameters()
+ {
+ var con = new SqlConnection("Timeout=1234;packet Size=5678 ;;; ;");
+ Assert.Equal(1234, con.ConnectionTimeout);
+ Assert.Equal(5678, con.PacketSize);
+ }
+
+ [Fact]
+ public void SqlConnectionEmptyParameters()
+ {
+ var con = new SqlConnection("Timeout=;packet Size= ;Integrated Security=;");
+ //default values are defined in internal class DbConnectionStringDefaults
+ Assert.Equal(15, con.ConnectionTimeout);
+ Assert.Equal(8000, con.PacketSize);
+ Assert.False(new SqlConnectionStringBuilder(con.ConnectionString).IntegratedSecurity);
+ }
+
+ [Fact]
+ public void SqlConnectionInvalidParameters()
+ {
+ Assert.Throws<ArgumentException>(() => new SqlConnection("Timeout=null;"));
+ Assert.Throws<ArgumentException>(() => new SqlConnection("Timeout= null;"));
+ Assert.Throws<ArgumentException>(() => new SqlConnection("Timeout=1 1;"));
+ Assert.Throws<ArgumentException>(() => new SqlConnection("Timeout=1a;"));
+ Assert.Throws<ArgumentException>(() => new SqlConnection("Integrated Security=truee"));
+ }
}
}
diff --git a/src/System.Data.SqlClient/tests/ManualTests/SQL/MirroringTest/ConnectionOnMirroringTest.cs b/src/System.Data.SqlClient/tests/ManualTests/SQL/MirroringTest/ConnectionOnMirroringTest.cs
new file mode 100644
index 0000000000..ac72f03d1c
--- /dev/null
+++ b/src/System.Data.SqlClient/tests/ManualTests/SQL/MirroringTest/ConnectionOnMirroringTest.cs
@@ -0,0 +1,97 @@
+// 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.Diagnostics;
+using System.Threading;
+
+namespace System.Data.SqlClient.ManualTesting.Tests
+{
+ public static class ConnectionOnMirroringTest
+ {
+ private static ManualResetEvent workerCompletedEvent = new ManualResetEvent(false);
+
+ [CheckConnStrSetupFact]
+ public static void TestMultipleConnectionToMirroredServer()
+ {
+ string mirroringStateDesc;
+ string failoverPartnerName;
+ bool isMirroring = GetMirroringInfo(DataTestUtility.TcpConnStr, out mirroringStateDesc, out failoverPartnerName);
+ bool isSynchronized = "SYNCHRONIZED".Equals(mirroringStateDesc, StringComparison.InvariantCultureIgnoreCase);
+ if (isMirroring && isSynchronized && !string.IsNullOrEmpty(failoverPartnerName))
+ {
+ SqlConnectionStringBuilder builder = new SqlConnectionStringBuilder(DataTestUtility.TcpConnStr);
+ builder.ConnectTimeout = 0;
+
+ TestWorker worker = new TestWorker(builder.ConnectionString);
+ Thread childThread = new Thread(() => worker.TestMultipleConnection());
+ childThread.Start();
+
+ if (workerCompletedEvent.WaitOne(10000))
+ {
+ childThread.Join();
+ }
+ else
+ {
+ // currently Thread.Abort() throws PlatformNotSupportedException in CoreFx.
+ childThread.Interrupt();
+ throw new Exception("SqlConnection could not open and close successfully in timely manner. Possibly connection hangs.");
+ }
+ }
+ }
+
+ private static bool GetMirroringInfo(string connectionString, out string mirroringStateDesc, out string failoverPartnerName)
+ {
+ mirroringStateDesc = null;
+ failoverPartnerName = null;
+
+ SqlConnectionStringBuilder builder = new SqlConnectionStringBuilder(connectionString);
+ string dbname = builder.InitialCatalog;
+
+ builder.ConnectTimeout = 5;
+ connectionString = builder.ConnectionString;
+
+ DataTable dt = DataTestUtility.RunQuery(connectionString, $"select mirroring_state_desc from sys.database_mirroring where database_id = DB_ID('{dbname}')");
+ mirroringStateDesc = dt.Rows[0][0].ToString();
+
+ bool isMirroring = !string.IsNullOrEmpty(mirroringStateDesc);
+ if (isMirroring)
+ {
+ dt = DataTestUtility.RunQuery(connectionString, $"select mirroring_partner_name from sys.database_mirroring where database_id = DB_ID('{dbname}')");
+ failoverPartnerName = dt.Rows[0][0].ToString();
+ }
+
+ return isMirroring;
+ }
+
+ private class TestWorker
+ {
+ private string _connectionString;
+
+ public TestWorker(string connectionString)
+ {
+ _connectionString = connectionString;
+ }
+
+ public void TestMultipleConnection()
+ {
+ List<SqlConnection> list = new List<SqlConnection>();
+
+ for (int i = 0; i < 10; ++i)
+ {
+ SqlConnection conn = new SqlConnection(_connectionString);
+ list.Add(conn);
+ conn.Open();
+ }
+
+ foreach (SqlConnection conn in list)
+ {
+ conn.Dispose();
+ }
+
+ workerCompletedEvent.Set();
+ }
+ }
+ }
+}
diff --git a/src/System.Data.SqlClient/tests/ManualTests/SQL/ParameterTest/ParametersTest.cs b/src/System.Data.SqlClient/tests/ManualTests/SQL/ParameterTest/ParametersTest.cs
index f3d0adb14b..e711ec1fa0 100644
--- a/src/System.Data.SqlClient/tests/ManualTests/SQL/ParameterTest/ParametersTest.cs
+++ b/src/System.Data.SqlClient/tests/ManualTests/SQL/ParameterTest/ParametersTest.cs
@@ -98,6 +98,38 @@ namespace System.Data.SqlClient.ManualTesting.Tests
}
[CheckConnStrSetupFact]
+ public static void Test_SqlParameter_Constructor()
+ {
+ using (var conn = new SqlConnection(s_connString))
+ {
+ var dataTable = new DataTable();
+ var adapter = new SqlDataAdapter();
+
+ adapter.SelectCommand = new SqlCommand("SELECT CustomerID, ContactTitle FROM dbo.Customers WHERE ContactTitle = @ContactTitle", conn);
+ var selectParam = new SqlParameter("@ContactTitle", SqlDbType.NVarChar, 30, ParameterDirection.Input, true, 0, 0, "ContactTitle", DataRowVersion.Current, "Owner");
+ adapter.SelectCommand.Parameters.Add(selectParam);
+
+ adapter.UpdateCommand = new SqlCommand("UPDATE dbo.Customers SET ContactTitle = @ContactTitle WHERE CustomerID = @CustomerID", conn);
+ var titleParam = new SqlParameter("@ContactTitle", SqlDbType.NVarChar, 30, ParameterDirection.Input, true, 0, 0, "ContactTitle", DataRowVersion.Current, null);
+ var idParam = new SqlParameter("@CustomerID", SqlDbType.NChar, 5, ParameterDirection.Input, false, 0, 0, "CustomerID", DataRowVersion.Current, null);
+ adapter.UpdateCommand.Parameters.Add(titleParam);
+ adapter.UpdateCommand.Parameters.Add(idParam);
+
+ adapter.Fill(dataTable);
+ object titleData = dataTable.Rows[0]["ContactTitle"];
+ Assert.Equal("Owner", (string)titleData);
+
+ titleData = "Test Data";
+ adapter.Update(dataTable);
+ adapter.Fill(dataTable);
+ Assert.Equal("Test Data", (string)titleData);
+
+ titleData = "Owner";
+ adapter.Update(dataTable);
+ }
+ }
+
+ [CheckConnStrSetupFact]
public static void Test_WithEnumValue_ShouldInferToUnderlyingType()
{
using (var conn = new SqlConnection(s_connString))
diff --git a/src/System.Data.SqlClient/tests/ManualTests/SQL/UdtTest/UdtTest.cs b/src/System.Data.SqlClient/tests/ManualTests/SQL/UdtTest/UdtTest.cs
index 79d926b372..7a6722bd25 100644
--- a/src/System.Data.SqlClient/tests/ManualTests/SQL/UdtTest/UdtTest.cs
+++ b/src/System.Data.SqlClient/tests/ManualTests/SQL/UdtTest/UdtTest.cs
@@ -40,6 +40,24 @@ namespace System.Data.SqlClient.ManualTesting.Tests
}
[CheckConnStrSetupFact]
+ public static void GetValueTest()
+ {
+ using (SqlConnection conn = new SqlConnection(DataTestUtility.TcpConnStr))
+ using (SqlCommand cmd = new SqlCommand("select hierarchyid::Parse('/1/') as col0", conn))
+ {
+ conn.Open();
+ using (SqlDataReader reader = cmd.ExecuteReader())
+ {
+ Assert.True(reader.Read());
+
+ Assert.Throws<PlatformNotSupportedException>(() => reader.GetValue(0));
+
+ Assert.Throws<PlatformNotSupportedException>(() => reader.GetSqlValue(0));
+ }
+ }
+ }
+
+ [CheckConnStrSetupFact]
public static void TestUdtSqlParameterThrowsPlatformNotSupportedException()
{
using (SqlConnection connection = new SqlConnection(DataTestUtility.TcpConnStr))
@@ -338,4 +356,4 @@ namespace System.Data.SqlClient.ManualTesting.Tests
return hex.ToString();
}
}
-} \ No newline at end of file
+}
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 3805a80820..7a0e541915 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
@@ -56,6 +56,7 @@
<Compile Include="SQL\LocalDBTest\LocalDBTest.cs" />
<Compile Include="SQL\MARSSessionPoolingTest\MARSSessionPoolingTest.cs" />
<Compile Include="SQL\MARSTest\MARSTest.cs" />
+ <Compile Include="SQL\MirroringTest\ConnectionOnMirroringTest.cs" />
<Compile Include="SQL\ParallelTransactionsTest\ParallelTransactionsTest.cs" />
<Compile Include="SQL\SqlSchemaInfoTest\SqlSchemaInfoTest.cs" />
<Compile Include="SQL\SqlBulkCopyTest\AdjustPrecScaleForBulkCopy.cs" />
diff --git a/src/System.Data.SqlClient/tests/StressTests/System.Data.StressFramework/DataStressErrors.cs b/src/System.Data.SqlClient/tests/StressTests/System.Data.StressFramework/DataStressErrors.cs
index 2a341ecd63..bf20276c98 100644
--- a/src/System.Data.SqlClient/tests/StressTests/System.Data.StressFramework/DataStressErrors.cs
+++ b/src/System.Data.SqlClient/tests/StressTests/System.Data.StressFramework/DataStressErrors.cs
@@ -140,7 +140,7 @@ namespace Stress.Data
}
/// <summary>
- /// Reports that a fatal error has happened. This is a error that completely prevents the test from continuing,
+ /// Reports that a fatal error has happened. This is an error that completely prevents the test from continuing,
/// for example a setup failure. Ordinary programming errors should not be handled by this method.
/// </summary>
/// <param name="description">A description of the error</param>
@@ -213,4 +213,4 @@ namespace Stress.Data
}
#endregion
}
-} \ No newline at end of file
+}
diff --git a/src/System.Diagnostics.DiagnosticSource/pkg/System.Diagnostics.DiagnosticSource.pkgproj b/src/System.Diagnostics.DiagnosticSource/pkg/System.Diagnostics.DiagnosticSource.pkgproj
index 98fb9b3179..9217e74da3 100644
--- a/src/System.Diagnostics.DiagnosticSource/pkg/System.Diagnostics.DiagnosticSource.pkgproj
+++ b/src/System.Diagnostics.DiagnosticSource/pkg/System.Diagnostics.DiagnosticSource.pkgproj
@@ -9,10 +9,18 @@
<ProjectReference Include="..\src\System.Diagnostics.DiagnosticSource.csproj">
<SupportedFramework>net46;net45;netcore45;netcoreapp1.0;wpa81;$(AllXamarinFrameworks)</SupportedFramework>
</ProjectReference>
- <InboxOnTargetFramework Include="netcoreapp2.0" />
<!-- this package is part of the implementation closure of NETStandard.Library
therefore it cannot reference NETStandard.Library -->
<SuppressMetaPackage Include="NETStandard.Library" />
+
+ <!-- Since UAP and .NETCoreApp are package based we still want to enable
+ OOBing libraries that happen to overlap with their framework package.
+ This avoids us having to lock the API in our NuGet packages just
+ to match what shipped inbox: since we can provide a new library
+ we can update it to add API without raising the netstandard version. -->
+ <ValidatePackageSuppression Include="TreatAsOutOfBox">
+ <Value>.NETCoreApp;UAP</Value>
+ </ValidatePackageSuppression>
</ItemGroup>
<Import Project="$([MSBuild]::GetDirectoryNameOfFileAbove($(MSBuildThisFileDirectory), dir.targets))\dir.targets" />
</Project> \ No newline at end of file
diff --git a/src/System.Diagnostics.DiagnosticSource/src/DiagnosticSourceUsersGuide.md b/src/System.Diagnostics.DiagnosticSource/src/DiagnosticSourceUsersGuide.md
index 3e4201eebc..75d2d83c05 100644
--- a/src/System.Diagnostics.DiagnosticSource/src/DiagnosticSourceUsersGuide.md
+++ b/src/System.Diagnostics.DiagnosticSource/src/DiagnosticSourceUsersGuide.md
@@ -1,4 +1,4 @@
-# DiagnosticSource Users Guide
+# DiagnosticSource User's Guide
This document describes DiagnosticSource, a simple module that allows code
to be instrumented for production-time logging of **rich data payloads** for
@@ -41,12 +41,12 @@ there is a bridge that pipes information from DiagnosticSource's to an EventSour
consumers can get at all DiagnosticSource events. While the data payloads from
DiagnosticSource can't in general be passed through to the EventSource (because they are
not serializable), there is a mechanism in the bridge that enables consumers to specify which fields
-along to the EventSource.
+to pass along to the EventSource.
What this means is that in general it is not necessary to instrument a code site multiple
times. By instrumenting with Diagnostic source, both clients that need the rich data
(and thus use DiagnosticListener) as well as any consumers using EventListeners
-(or OS facilities like ETW)) can get at the data.
+(or OS facilities like ETW) can get at the data.
----------------------------------------
## Instrumenting with DiagnosticSource/DiagnosticListener
@@ -86,25 +86,27 @@ A typical call site will look like
Already some of the architectural elements are being exposed, namely
- 1. Every event has a string name (e.g. Request Start), and exactly one object as a payload.
- 2. If you need to send more than one item, you can do so by creating a object with all information
- in it as properties. CSharp's [anonymous type](https://msdn.microsoft.com/en-us/library/bb397696.aspx)
- feature is typically used to create a type to pass 'on the fly', and makes this scheme very
- convenient.
- 3. At the instrumentation site, you must guard the call to 'Write' with an 'IsEnabled' check on
- the same event name. Without this check, even when the instrumentation is inactive, the rules
- of the C# language require all the work of creating the payload object and calling 'Write' to be
- done, even though nothing is actually listening for the data. By guarding the 'Write' call, we
- make it efficient when the source is not enabled.
+1. Every event has a string name (e.g. Request Start), and exactly one object as a payload.
+2. If you need to send more than one item, you can do so by creating a object with all information
+ in it as properties. C#'s [anonymous type](https://msdn.microsoft.com/en-us/library/bb397696.aspx)
+ feature is typically used to create a type to pass 'on the fly', and makes this scheme very
+ convenient.
+3. At the instrumentation site, you must guard the call to 'Write' with an 'IsEnabled' check on
+ the same event name. Without this check, even when the instrumentation is inactive, the rules
+ of the C# language require all the work of creating the payload object and calling 'Write' to be
+ done, even though nothing is actually listening for the data. By guarding the 'Write' call, we
+ make it efficient when the source is not enabled.
### Creating DiagnosticSources (Actually DiagnosticListeners)
Perhaps confusingly you make a DiagnosticSource by creating a DiagnosticListener
+```C#
static DiagnosticSource mySource = new DiagnosticListener("System.Net.Http");
+```
Basically a DiagnosticListener is a named place where a source sends its information (events).
-From an implementation point of view, DiagnosticSource is a abstract class that has the two
+From an implementation point of view, DiagnosticSource is an abstract class that has the two
instrumentation methods, and DiagnosticListener is something that implements that abstract class.
Thus every DiagnosticListener is a DiagnosticSource, and by making a DiagnosticListener you
implicitly make a DiagnosticSource as well.
@@ -119,7 +121,7 @@ Thus the event names only need to be unique within a component.
#### DiagnosticListener Names
- * CONSIDER - the likely scenarios for USING information when deciding how may
+ * CONSIDER - the likely scenarios for USING information when deciding how many
DiagnosticListener to have and the events in each. Keep in mind that it is **very easy
and efficient** to filter all the events in a particular listener so ideally the
most important scenarios involve turning on whole listeners and not needing to filter
@@ -140,7 +142,7 @@ Thus the event names only need to be unique within a component.
component naming**. You want it to be the case that users can correctly guess which
listeners to activate knowing just their scenario.
- * DO - Make the name for the DiagnosticListeners **globally unique**. This is Typically
+ * DO - Make the name for the DiagnosticListeners **globally unique**. This is typically
done by making the first part of the name the component (e.g. System.Net.Http)
* DO - Use dots '.' to create multi-part names. This works well if the name is a Name
@@ -159,7 +161,7 @@ Thus the event names only need to be unique within a component.
naming one event 'RequestStart' and the another 'RequestStop' is good because tools can use the
convention to determine that the time interval betweeen them is interesting.
-### payloads
+### Payloads
* DO use the anonymous type syntax 'new { property1 =value1 ...}' as the default way to pass
a payload *even if there is only one data element*. This makes adding more data later easy
@@ -167,7 +169,7 @@ Thus the event names only need to be unique within a component.
* CONSIDER - if you have an event that is so frequent that the performance of the logging is
a important consideration, **and** you have only one data item **and** it is unlikely that
- you will ever have more data to pass to the event, **and** and the data item is a normal class
+ you will ever have more data to pass to the event, **and** the data item is a normal class
(not a value type) **then** you save some cost by simply by passing the data object directly
without using an anonymous type wrapper.
@@ -211,7 +213,7 @@ active in the system at runtime. The API to accomplish this is the 'AllListene
IObservable\<DiagnosticListener>.
The IObservable interface is the 'callback' version of the IEnumerable interface. You can learn
-more about it at the [Reactive Extensions Site](https://msdn.microsoft.com/en-us/data/gg577609.aspx).
+more about it at the [Reactive Extensions](https://msdn.microsoft.com/en-us/data/gg577609.aspx) site.
In a nutshell, you have an object called an IObserver which has three callbacks, OnNext, OnComplete
and OnError, and an IObservable has single method called 'Subscribe' which gets passed one of these
Observers. Once connected, the Observer gets callback (mostly OnNext callbacks) when things
@@ -286,7 +288,7 @@ call 'Subscribe' on it as well. Thus we can fill out the previous example a bit
In this example after finding the 'System.Net.Http' DiagnosticListener, we create an action that
prints out the name of the listener, event, and payload.ToString(). Notice a few things:
- 1. DiagnosticListener implement IObservable\<KeyValuePair\<string, object>>. This means
+ 1. DiagnosticListener implements IObservable\<KeyValuePair\<string, object>>. This means
on each callback we get a KeyValuePair. The key of this pair is the name of the event
and the value is the payload object. In the code above we simply log this information
to the Console.
@@ -316,8 +318,8 @@ an object. Odds are that you want to get at more specific data. There are tw
2. Use reflection API, for example if we assuming we have the method
```C#
- /// Define a shortcut method that fetches a field of a particular name.
- static class PropertyExtensions
+ /// Define a shortcut method that fetches a field of a particular name.
+ static class PropertyExtensions
{
static object GetProperty(this object _this, string propertyName)
{
@@ -392,8 +394,8 @@ And consumers may use such properties to filter events more precisely.
{
if (eventName == "RequestStart")
{
- HttpRequestMessage request = context as HttpRequestMessage;
- if (request != null)
+ HttpRequestMessage request = context as HttpRequestMessage;
+ if (request != null)
{
return IsUriEnabled(request.RequestUri);
}
diff --git a/src/System.Diagnostics.DiagnosticSource/src/System/Diagnostics/DiagnosticSource.cs b/src/System.Diagnostics.DiagnosticSource/src/System/Diagnostics/DiagnosticSource.cs
index bdd5fa78ab..0a665fc0cd 100644
--- a/src/System.Diagnostics.DiagnosticSource/src/System/Diagnostics/DiagnosticSource.cs
+++ b/src/System.Diagnostics.DiagnosticSource/src/System/Diagnostics/DiagnosticSource.cs
@@ -31,7 +31,7 @@ namespace System.Diagnostics
/// </summary>
/// <param name="name">The name of the event being written.</param>
/// <param name="value">An object that represent the value being passed as a payload for the event.
- /// This is often a anonymous type which contains several sub-values.</param>
+ /// This is often an anonymous type which contains several sub-values.</param>
public abstract void Write(string name, object value);
/// <summary>
diff --git a/src/System.Diagnostics.DiagnosticSource/src/System/Diagnostics/DiagnosticSourceEventSource.cs b/src/System.Diagnostics.DiagnosticSource/src/System/Diagnostics/DiagnosticSourceEventSource.cs
index 3bf3a3c0f8..449ab9635d 100644
--- a/src/System.Diagnostics.DiagnosticSource/src/System/Diagnostics/DiagnosticSourceEventSource.cs
+++ b/src/System.Diagnostics.DiagnosticSource/src/System/Diagnostics/DiagnosticSourceEventSource.cs
@@ -871,7 +871,7 @@ namespace System.Diagnostics
}
/// <summary>
- /// CallbackObserver is a adapter class that creates an observer (which you can pass
+ /// CallbackObserver is an adapter class that creates an observer (which you can pass
/// to IObservable.Subscribe), and calls the given callback every time the 'next'
/// operation on the IObserver happens.
/// </summary>
diff --git a/src/System.Diagnostics.DiagnosticSource/tests/DiagnosticSourceTests.cs b/src/System.Diagnostics.DiagnosticSource/tests/DiagnosticSourceTests.cs
index c04497d7b8..ac1bf6f537 100644
--- a/src/System.Diagnostics.DiagnosticSource/tests/DiagnosticSourceTests.cs
+++ b/src/System.Diagnostics.DiagnosticSource/tests/DiagnosticSourceTests.cs
@@ -651,7 +651,7 @@ namespace System.Diagnostics.Tests
}
/// <summary>
- /// Used to make an observer out of a action delegate.
+ /// Used to make an observer out of an action delegate.
/// </summary>
public static IObserver<T> MakeObserver<T>(
Action<T> onNext = null, Action onCompleted = null)
diff --git a/src/System.Diagnostics.DiagnosticSource/tests/HttpHandlerDiagnosticListenerTests.cs b/src/System.Diagnostics.DiagnosticSource/tests/HttpHandlerDiagnosticListenerTests.cs
index b64f9385e1..f741ae3ab3 100644
--- a/src/System.Diagnostics.DiagnosticSource/tests/HttpHandlerDiagnosticListenerTests.cs
+++ b/src/System.Diagnostics.DiagnosticSource/tests/HttpHandlerDiagnosticListenerTests.cs
@@ -437,7 +437,7 @@ namespace System.Diagnostics.Tests
}
/// <summary>
- /// CallbackObserver is a adapter class that creates an observer (which you can pass
+ /// CallbackObserver is an adapter class that creates an observer (which you can pass
/// to IObservable.Subscribe), and calls the given callback every time the 'next'
/// operation on the IObserver happens.
/// </summary>
diff --git a/src/System.Diagnostics.FileVersionInfo/tests/System.Diagnostics.FileVersionInfo.Tests/System.Diagnostics.FileVersionInfo.Tests.csproj b/src/System.Diagnostics.FileVersionInfo/tests/System.Diagnostics.FileVersionInfo.Tests/System.Diagnostics.FileVersionInfo.Tests.csproj
index b05b42f738..2e73b2ef8e 100644
--- a/src/System.Diagnostics.FileVersionInfo/tests/System.Diagnostics.FileVersionInfo.Tests/System.Diagnostics.FileVersionInfo.Tests.csproj
+++ b/src/System.Diagnostics.FileVersionInfo/tests/System.Diagnostics.FileVersionInfo.Tests/System.Diagnostics.FileVersionInfo.Tests.csproj
@@ -54,7 +54,7 @@
</PropertyGroup>
<Target Name="MangleTestAssemblyExtension">
<!-- Copy TestAssembly to file without .dll extension so that ILC preserves it as a data file rather than feeding it to the output executable. -->
- <Copy SourceFiles="$(OutputPath)\System.Diagnostics.FileVersionInfo.TestAssembly.dll" DestinationFiles="$(OutputPath)\System.Diagnostics.FileVersionInfo.TestAssembly.ildll" />
+ <Copy SourceFiles="$(TestPath)\System.Diagnostics.FileVersionInfo.TestAssembly.dll" DestinationFiles="$(TestPath)\System.Diagnostics.FileVersionInfo.TestAssembly.ildll" />
</Target>
</Project>
diff --git a/src/System.Diagnostics.Process/src/Resources/Strings.resx b/src/System.Diagnostics.Process/src/Resources/Strings.resx
index 71dc8266c7..e4ee4b3903 100644
--- a/src/System.Diagnostics.Process/src/Resources/Strings.resx
+++ b/src/System.Diagnostics.Process/src/Resources/Strings.resx
@@ -210,6 +210,9 @@
<data name="CantRedirectStreams" xml:space="preserve">
<value>The Process object must have the UseShellExecute property set to false in order to redirect IO streams.</value>
</data>
+ <data name="DirectoryNotValidAsInput" xml:space="preserve">
+ <value>The FileName property should not be a directory unless UseShellExecute is set.</value>
+ </data>
<data name="PendingAsyncOperation" xml:space="preserve">
<value>An async read operation has already been started on the stream.</value>
</data>
diff --git a/src/System.Diagnostics.Process/src/System/Diagnostics/Process.Linux.cs b/src/System.Diagnostics.Process/src/System/Diagnostics/Process.Linux.cs
index bf05c42546..898cf347ec 100644
--- a/src/System.Diagnostics.Process/src/System/Diagnostics/Process.Linux.cs
+++ b/src/System.Diagnostics.Process/src/System/Diagnostics/Process.Linux.cs
@@ -57,6 +57,21 @@ namespace System.Diagnostics
}
}
+ /// <summary>Gets execution path</summary>
+ private string GetPathToOpenFile()
+ {
+ string[] allowedProgramsToRun = { "xdg-open", "gnome-open", "kfmclient" };
+ foreach (var program in allowedProgramsToRun)
+ {
+ string pathToProgram = FindProgramInPath(program);
+ if (!string.IsNullOrEmpty(pathToProgram))
+ {
+ return pathToProgram;
+ }
+ }
+ return null;
+ }
+
/// <summary>
/// Gets the amount of time the associated process has spent utilizing the CPU.
/// It is the sum of the <see cref='System.Diagnostics.Process.UserProcessorTime'/> and
@@ -171,9 +186,14 @@ namespace System.Diagnostics
// ---- PAL layer ends here ----
// -----------------------------
- /// <summary>Gets the path to the current executable, or null if it could not be retrieved.</summary>
- private static string GetExePath()
+ /// <summary>Gets the path to the executable for the process, or null if it could not be retrieved.</summary>
+ /// <param name="processId">The pid for the target process, or -1 for the current process.</param>
+ internal static string GetExePath(int processId = -1)
{
+ string exeFilePath = processId == -1 ?
+ Interop.procfs.SelfExeFilePath :
+ Interop.procfs.GetExeFilePathForProcess(processId);
+
// Determine the maximum size of a path
int maxPath = Interop.Sys.MaxPath;
@@ -182,7 +202,7 @@ namespace System.Diagnostics
{
// Read from procfs the symbolic link to this process' executable
byte[] buffer = new byte[pathLen + 1]; // +1 for null termination
- int resultLength = Interop.Sys.ReadLink(Interop.procfs.SelfExeFilePath, buffer, pathLen);
+ int resultLength = Interop.Sys.ReadLink(exeFilePath, buffer, pathLen);
// If we got one, null terminate it (readlink doesn't do this) and return the string
if (resultLength > 0)
diff --git a/src/System.Diagnostics.Process/src/System/Diagnostics/Process.OSX.cs b/src/System.Diagnostics.Process/src/System/Diagnostics/Process.OSX.cs
index 2870fc7ae3..560d04c4cb 100644
--- a/src/System.Diagnostics.Process/src/System/Diagnostics/Process.OSX.cs
+++ b/src/System.Diagnostics.Process/src/System/Diagnostics/Process.OSX.cs
@@ -88,6 +88,12 @@ namespace System.Diagnostics
}
}
+ /// <summary>Gets execution path</summary>
+ private string GetPathToOpenFile()
+ {
+ return "/usr/bin/open";
+ }
+
/// <summary>
/// Gets the amount of time the associated process has spent utilizing the CPU.
/// It is the sum of the <see cref='System.Diagnostics.Process.UserProcessorTime'/> and
diff --git a/src/System.Diagnostics.Process/src/System/Diagnostics/Process.Unix.cs b/src/System.Diagnostics.Process/src/System/Diagnostics/Process.Unix.cs
index 2d2c3c2fea..9f93d4ebbb 100644
--- a/src/System.Diagnostics.Process/src/System/Diagnostics/Process.Unix.cs
+++ b/src/System.Diagnostics.Process/src/System/Diagnostics/Process.Unix.cs
@@ -45,7 +45,7 @@ namespace System.Diagnostics
[CLSCompliant(false)]
public static Process Start(string fileName, string arguments, string userName, SecureString password, string domain)
- {
+ {
throw new PlatformNotSupportedException(SR.ProcessStartIdentityNotSupported);
}
@@ -163,7 +163,7 @@ namespace System.Diagnostics
}
Debug.Assert(pri >= -20 && pri <= 20);
- return
+ return
pri < -15 ? ProcessPriorityClass.RealTime :
pri < -10 ? ProcessPriorityClass.High :
pri < -5 ? ProcessPriorityClass.AboveNormal :
@@ -219,7 +219,10 @@ namespace System.Diagnostics
return new SafeProcessHandle(_processId);
}
- /// <summary>Starts the process using the supplied start info.</summary>
+ /// <summary>
+ /// Starts the process using the supplied start info.
+ /// With UseShellExecute option, we'll try the shell tools to launch it(e.g. "open fileName")
+ /// </summary>
/// <param name="startInfo">The start info with which to start the process.</param>
private bool StartCore(ProcessStartInfo startInfo)
{
@@ -232,32 +235,43 @@ namespace System.Diagnostics
{
throw new InvalidOperationException(SR.CantRedirectStreams);
}
+ }
- const string ShellPath = "/bin/sh";
+ int childPid, stdinFd, stdoutFd, stderrFd;
+ string[] envp = CreateEnvp(startInfo);
+ string cwd = !string.IsNullOrWhiteSpace(startInfo.WorkingDirectory) ? startInfo.WorkingDirectory : null;
- filename = ShellPath;
- argv = new string[3] { ShellPath, "-c", startInfo.FileName + " " + startInfo.Arguments};
+ if (startInfo.UseShellExecute)
+ {
+ // use default program to open file/url
+ filename = GetPathToOpenFile();
+ argv = ParseArgv(startInfo, filename);
}
else
{
filename = ResolvePath(startInfo.FileName);
argv = ParseArgv(startInfo);
+ if (Directory.Exists(startInfo.FileName))
+ {
+ throw new Win32Exception(SR.DirectoryNotValidAsInput);
+ }
}
- string[] envp = CreateEnvp(startInfo);
- string cwd = !string.IsNullOrWhiteSpace(startInfo.WorkingDirectory) ? startInfo.WorkingDirectory : null;
+ if (string.IsNullOrEmpty(filename))
+ {
+ throw new Win32Exception(Interop.Error.ENOENT.Info().RawErrno);
+ }
// Invoke the shim fork/execve routine. It will create pipes for all requested
// redirects, fork a child process, map the pipe ends onto the appropriate stdin/stdout/stderr
// descriptors, and execve to execute the requested process. The shim implementation
// is used to fork/execve as executing managed code in a forked process is not safe (only
// the calling thread will transfer, thread IDs aren't stable across the fork, etc.)
- int childPid, stdinFd, stdoutFd, stderrFd;
Interop.Sys.ForkAndExecProcess(
- filename, argv, envp, cwd,
- startInfo.RedirectStandardInput, startInfo.RedirectStandardOutput, startInfo.RedirectStandardError,
- out childPid,
- out stdinFd, out stdoutFd, out stderrFd);
+ filename, argv, envp, cwd,
+ startInfo.RedirectStandardInput, startInfo.RedirectStandardOutput, startInfo.RedirectStandardError,
+ out childPid,
+ out stdinFd, out stdoutFd, out stderrFd);
// Store the child's information into this Process object.
Debug.Assert(childPid >= 0);
@@ -300,23 +314,31 @@ namespace System.Diagnostics
/// <summary>Size to use for redirect streams and stream readers/writers.</summary>
private const int StreamBufferSize = 4096;
+
/// <summary>Converts the filename and arguments information from a ProcessStartInfo into an argv array.</summary>
/// <param name="psi">The ProcessStartInfo.</param>
+ /// <param name="alternativePath">alternative resolved path to use as first argument</param>
/// <returns>The argv array.</returns>
- private static string[] ParseArgv(ProcessStartInfo psi)
+ private static string[] ParseArgv(ProcessStartInfo psi, string alternativePath = null)
{
- string argv0 = psi.FileName; // pass filename (instead of resolved path) as argv[0], to match what caller supplied
- if (string.IsNullOrEmpty(psi.Arguments))
+ string argv0 = psi.FileName; // when no alternative path exists, pass filename (instead of resolved path) as argv[0], to match what caller supplied
+ if (string.IsNullOrEmpty(psi.Arguments) && string.IsNullOrEmpty(alternativePath))
{
return new string[] { argv0 };
}
- else
+
+ var argvList = new List<string>();
+ if (!string.IsNullOrEmpty(alternativePath))
{
- var argvList = new List<string>();
- argvList.Add(argv0);
- ParseArgumentsIntoList(psi.Arguments, argvList);
- return argvList.ToArray();
+ argvList.Add(alternativePath);
+ if (alternativePath.Contains("kfmclient"))
+ {
+ argvList.Add("openURL"); // kfmclient needs OpenURL
+ }
}
+ argvList.Add(argv0);
+ ParseArgumentsIntoList(psi.Arguments, argvList);
+ return argvList.ToArray();
}
/// <summary>Converts the environment variables information from a ProcessStartInfo into an envp array.</summary>
@@ -333,9 +355,9 @@ namespace System.Diagnostics
return envp;
}
- /// <summary>Resolves a path to the filename passed to ProcessStartInfo.</summary>
+ /// <summary>Resolves a path to the filename passed to ProcessStartInfo. </summary>
/// <param name="filename">The filename.</param>
- /// <returns>The resolved path.</returns>
+ /// <returns>The resolved path. It can return null in case of URLs.</returns>
private static string ResolvePath(string filename)
{
// Follow the same resolution that Windows uses with CreateProcess:
@@ -377,6 +399,17 @@ namespace System.Diagnostics
}
// Then check each directory listed in the PATH environment variables
+ return FindProgramInPath(filename);
+ }
+
+ /// <summary>
+ /// Gets the path to the program
+ /// </summary>
+ /// <param name="program"></param>
+ /// <returns></returns>
+ private static string FindProgramInPath(string program)
+ {
+ string path;
string pathEnvVar = Environment.GetEnvironmentVariable("PATH");
if (pathEnvVar != null)
{
@@ -384,16 +417,14 @@ namespace System.Diagnostics
while (pathParser.MoveNext())
{
string subPath = pathParser.ExtractCurrent();
- path = Path.Combine(subPath, filename);
+ path = Path.Combine(subPath, program);
if (File.Exists(path))
{
return path;
}
}
}
-
- // Could not find the file
- throw new Win32Exception(Interop.Error.ENOENT.Info().RawErrno);
+ return null;
}
/// <summary>Convert a number of "jiffies", or ticks, to a TimeSpan.</summary>
@@ -436,7 +467,7 @@ namespace System.Diagnostics
{
Debug.Assert(fd >= 0);
return new FileStream(
- new SafeFileHandle((IntPtr)fd, ownsHandle: true),
+ new SafeFileHandle((IntPtr)fd, ownsHandle: true),
access, StreamBufferSize, isAsync: false);
}
diff --git a/src/System.Diagnostics.Process/src/System/Diagnostics/ProcessManager.Linux.cs b/src/System.Diagnostics.Process/src/System/Diagnostics/ProcessManager.Linux.cs
index a64f50d89a..61e1d1f2e5 100644
--- a/src/System.Diagnostics.Process/src/System/Diagnostics/ProcessManager.Linux.cs
+++ b/src/System.Diagnostics.Process/src/System/Diagnostics/ProcessManager.Linux.cs
@@ -80,6 +80,22 @@ namespace System.Diagnostics
}
}
+ // Move the main executable module to be the first in the list if it's not already
+ string exePath = Process.GetExePath(processId);
+ for (int i = 0; i < modules.Count; i++)
+ {
+ ProcessModule module = modules[i];
+ if (module.FileName == exePath)
+ {
+ if (i > 0)
+ {
+ modules.RemoveAt(i);
+ modules.Insert(0, module);
+ }
+ break;
+ }
+ }
+
// Return the set of modules found
return modules;
}
diff --git a/src/System.Diagnostics.Process/src/System/Diagnostics/ProcessModuleCollection.cs b/src/System.Diagnostics.Process/src/System/Diagnostics/ProcessModuleCollection.cs
index e370668b7c..6b701ec5c9 100644
--- a/src/System.Diagnostics.Process/src/System/Diagnostics/ProcessModuleCollection.cs
+++ b/src/System.Diagnostics.Process/src/System/Diagnostics/ProcessModuleCollection.cs
@@ -27,6 +27,10 @@ namespace System.Diagnostics
internal void Add(ProcessModule module) => InnerList.Add(module);
+ internal void Insert(int index, ProcessModule module) => InnerList.Insert(index, module);
+
+ internal void RemoveAt(int index) => InnerList.RemoveAt(index);
+
public ProcessModule this[int index] => (ProcessModule)InnerList[index];
public int IndexOf(ProcessModule module) => InnerList.IndexOf(module);
diff --git a/src/System.Diagnostics.Process/tests/ProcessTests.Unix.cs b/src/System.Diagnostics.Process/tests/ProcessTests.Unix.cs
index e8470a92e8..188308dbe9 100644
--- a/src/System.Diagnostics.Process/tests/ProcessTests.Unix.cs
+++ b/src/System.Diagnostics.Process/tests/ProcessTests.Unix.cs
@@ -62,12 +62,114 @@ namespace System.Diagnostics.Tests
}
[Fact]
- public void TestUseShellExecute_Unix_Succeeds()
+ [PlatformSpecific(TestPlatforms.Linux)]
+ public void ProcessStart_UseShellExecute_OnLinux_ThrowsIfNoProgramInstalled()
{
- using (var p = Process.Start(new ProcessStartInfo { UseShellExecute = true, FileName = "exit", Arguments = "42" }))
+ if (!s_allowedProgramsToRun.Any(program => IsProgramInstalled(program)))
{
- Assert.True(p.WaitForExit(WaitInMS));
- Assert.Equal(42, p.ExitCode);
+ Console.WriteLine($"None of the following programs were installed on this machine: {string.Join(",", s_allowedProgramsToRun)}.");
+ Assert.Throws<Win32Exception>(() => Process.Start(new ProcessStartInfo { UseShellExecute = true, FileName = Environment.CurrentDirectory }));
+ }
+ }
+
+ [Theory, InlineData(true), InlineData(false)]
+ [OuterLoop("Opens program")]
+ public void ProcessStart_UseShellExecute_OnUnix_SuccessWhenProgramInstalled(bool isFolder)
+ {
+ string programToOpen = s_allowedProgramsToRun.FirstOrDefault(program => IsProgramInstalled(program));
+ string fileToOpen;
+ if (isFolder)
+ {
+ fileToOpen = Environment.CurrentDirectory;
+ }
+ else
+ {
+ fileToOpen = GetTestFilePath() + ".txt";
+ File.WriteAllText(fileToOpen, $"{nameof(ProcessStart_UseShellExecute_OnUnix_SuccessWhenProgramInstalled)}");
+ }
+
+ if (RuntimeInformation.IsOSPlatform(OSPlatform.OSX) || programToOpen != null)
+ {
+ using (var px = Process.Start(new ProcessStartInfo { UseShellExecute = true, FileName = fileToOpen }))
+ {
+ Assert.NotNull(px);
+ if (!RuntimeInformation.IsOSPlatform(OSPlatform.OSX)) // on OSX, process name is dotnet for some reason. Refer to #23972
+ {
+ Assert.Equal(programToOpen, px.ProcessName);
+ }
+ px.Kill();
+ px.WaitForExit();
+ Assert.True(px.HasExited);
+ }
+ }
+ }
+
+ [Theory, InlineData("nano"), InlineData("vi")]
+ [PlatformSpecific(TestPlatforms.Linux)]
+ [OuterLoop("Opens program")]
+ public void ProcessStart_OpenFileOnLinux_UsesSpecifiedProgram(string programToOpenWith)
+ {
+ if (IsProgramInstalled(programToOpenWith))
+ {
+ string fileToOpen = GetTestFilePath() + ".txt";
+ File.WriteAllText(fileToOpen, $"{nameof(ProcessStart_OpenFileOnLinux_UsesSpecifiedProgram)}");
+ using (var px = Process.Start(programToOpenWith, fileToOpen))
+ {
+ Assert.Equal(programToOpenWith, px.ProcessName);
+ px.Kill();
+ px.WaitForExit();
+ Assert.True(px.HasExited);
+ }
+ }
+ else
+ {
+ Console.WriteLine($"Program specified to open file with {programToOpenWith} is not installed on this machine.");
+ }
+ }
+
+ [Theory, InlineData("/usr/bin/open"), InlineData("/usr/bin/nano")]
+ [PlatformSpecific(TestPlatforms.OSX)]
+ [OuterLoop("Opens program")]
+ public void ProcessStart_OpenFileOnOsx_UsesSpecifiedProgram(string programToOpenWith)
+ {
+ string fileToOpen = GetTestFilePath() + ".txt";
+ File.WriteAllText(fileToOpen, $"{nameof(ProcessStart_OpenFileOnOsx_UsesSpecifiedProgram)}");
+ using (var px = Process.Start(programToOpenWith, fileToOpen))
+ {
+ // Assert.Equal(programToOpenWith, px.ProcessName); // on OSX, process name is dotnet for some reason. Refer to #23972
+ Console.WriteLine($"in OSX, {nameof(programToOpenWith)} is {programToOpenWith}, while {nameof(px.ProcessName)} is {px.ProcessName}.");
+ px.Kill();
+ px.WaitForExit();
+ Assert.True(px.HasExited);
+ }
+ }
+
+ [Theory, InlineData("Safari"), InlineData("\"Google Chrome\"")]
+ [PlatformSpecific(TestPlatforms.OSX)]
+ [OuterLoop("Opens browser")]
+ public void ProcessStart_OpenUrl_UsesSpecifiedApplication(string applicationToOpenWith)
+ {
+ using (var px = Process.Start("/usr/bin/open", "https://github.com/dotnet/corefx -a " + applicationToOpenWith))
+ {
+ Assert.NotNull(px);
+ px.Kill();
+ px.WaitForExit();
+ Assert.True(px.HasExited);
+ }
+ }
+
+ [Theory, InlineData("-a Safari"), InlineData("-a \"Google Chrome\"")]
+ [PlatformSpecific(TestPlatforms.OSX)]
+ [OuterLoop("Opens browser")]
+ public void ProcessStart_UseShellExecuteTrue_OpenUrl_SuccessfullyReadsArgument(string arguments)
+ {
+ var startInfo = new ProcessStartInfo { UseShellExecute = true, FileName = "https://github.com/dotnet/corefx", Arguments = arguments };
+ using (var px = Process.Start(startInfo))
+ {
+ Assert.NotNull(px);
+ px.Kill();
+ px.WaitForExit();
+ Assert.True(px.HasExited);
}
}
@@ -148,5 +250,32 @@ namespace System.Diagnostics.Tests
[DllImport("libc")]
private static extern int chmod(string path, int mode);
+
+ private readonly string[] s_allowedProgramsToRun = new string[] { "xdg-open", "gnome-open", "kfmclient" };
+
+ /// <summary>
+ /// Checks if the program is installed
+ /// </summary>
+ /// <param name="program"></param>
+ /// <returns></returns>
+ private bool IsProgramInstalled(string program)
+ {
+ string path;
+ string pathEnvVar = Environment.GetEnvironmentVariable("PATH");
+ if (pathEnvVar != null)
+ {
+ var pathParser = new StringParser(pathEnvVar, ':', skipEmpty: true);
+ while (pathParser.MoveNext())
+ {
+ string subPath = pathParser.ExtractCurrent();
+ path = Path.Combine(subPath, program);
+ if (File.Exists(path))
+ {
+ return true;
+ }
+ }
+ }
+ return false;
+ }
}
}
diff --git a/src/System.Diagnostics.Process/tests/ProcessTests.cs b/src/System.Diagnostics.Process/tests/ProcessTests.cs
index 4eed35edee..f39bb591a3 100644
--- a/src/System.Diagnostics.Process/tests/ProcessTests.cs
+++ b/src/System.Diagnostics.Process/tests/ProcessTests.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.ComponentModel;
using System.IO;
@@ -13,7 +12,6 @@ using System.Security;
using System.Text;
using System.Threading;
using Xunit;
-using Xunit.NetCore.Extensions;
namespace System.Diagnostics.Tests
{
@@ -121,6 +119,71 @@ namespace System.Diagnostics.Tests
}
[Fact]
+ public void ProcessStart_TryExitCommandAsFileName_ThrowsWin32Exception()
+ {
+ Win32Exception e = Assert.Throws<Win32Exception>(() => Process.Start(new ProcessStartInfo { UseShellExecute = false, FileName = "exit", Arguments = "42" }));
+ }
+
+ [Fact]
+ public void ProcessStart_UseShellExecuteFalse_FilenameIsUrl_ThrowsWin32Exception()
+ {
+ Win32Exception e = Assert.Throws<Win32Exception>(() => Process.Start(new ProcessStartInfo { UseShellExecute = false, FileName = "https://www.github.com/corefx" }));
+ }
+
+ [Fact]
+ public void ProcessStart_TryOpenFolder_UseShellExecuteIsFalse_ThrowsWin32Exception()
+ {
+ Win32Exception e = Assert.Throws<Win32Exception>(() => Process.Start(new ProcessStartInfo { UseShellExecute = false, FileName = Path.GetTempPath() }));
+ }
+
+ [ConditionalFact(typeof(PlatformDetection), nameof(PlatformDetection.HasWindowsShell))]
+ [SkipOnTargetFramework(TargetFrameworkMonikers.Uap, "not supported on UAP")]
+ [OuterLoop("Launches File Explorer")]
+ public void ProcessStart_UseShellExecuteTrue_OpenMissingFile_Throws()
+ {
+ string fileToOpen = Path.Combine(Environment.CurrentDirectory, "_no_such_file.TXT");
+ Win32Exception e = Assert.Throws<Win32Exception>(() => Process.Start(new ProcessStartInfo { UseShellExecute = true, FileName = fileToOpen }));
+ }
+
+ [PlatformSpecific(TestPlatforms.Windows)]
+ [ConditionalTheory(typeof(PlatformDetection), nameof(PlatformDetection.HasWindowsShell))]
+ [InlineData(true)]
+ [InlineData(false)]
+ [SkipOnTargetFramework(TargetFrameworkMonikers.Uap, "not supported on UAP")]
+ [OuterLoop("Launches File Explorer")]
+ public void ProcessStart_UseShellExecute_OnWindows_DoesNotThrow(bool isFolder)
+ {
+ string fileToOpen;
+ if (isFolder)
+ {
+ fileToOpen = Environment.CurrentDirectory;
+ }
+ else
+ {
+ fileToOpen = GetTestFilePath() + ".txt";
+ File.WriteAllText(fileToOpen, $"{nameof(ProcessStart_UseShellExecute_OnWindows_DoesNotThrow)}");
+ }
+
+ using (var px = Process.Start(new ProcessStartInfo { UseShellExecute = true, FileName = fileToOpen }))
+ {
+ if (isFolder)
+ {
+ Assert.Null(px); // Not sure why px returned is null. but the call does not throw and opens folder successfully.
+ }
+ else
+ {
+ if (px != null) // sometimes process is null: tracked by #24048
+ {
+ Assert.Equal("notepad", px.ProcessName);
+
+ px.Kill();
+ Assert.True(px.WaitForExit(WaitInMS));
+ }
+ }
+ }
+ }
+
+ [Fact]
public void TestExitCode()
{
{
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 4be4b88920..3ccd854fc0 100644
--- a/src/System.Diagnostics.Process/tests/System.Diagnostics.Process.Tests.csproj
+++ b/src/System.Diagnostics.Process/tests/System.Diagnostics.Process.Tests.csproj
@@ -19,6 +19,9 @@
<Compile Include="$(CommonPath)\System\PasteArguments.cs">
<Link>Common\System\PasteArguments.cs</Link>
</Compile>
+ <Compile Include="$(CommonPath)\System\IO\StringParser.cs">
+ <Link>Common\System\IO\StringParser.cs</Link>
+ </Compile>
<Compile Include="$(CommonTestPath)\System\ShouldNotBeInvokedException.cs">
<Link>Common\System\ShouldNotBeInvokedException.cs</Link>
</Compile>
diff --git a/src/System.Diagnostics.StackTrace/tests/StackFrameTests.cs b/src/System.Diagnostics.StackTrace/tests/StackFrameTests.cs
index dfc590848a..4587f058e0 100644
--- a/src/System.Diagnostics.StackTrace/tests/StackFrameTests.cs
+++ b/src/System.Diagnostics.StackTrace/tests/StackFrameTests.cs
@@ -24,6 +24,7 @@ namespace System.Diagnostics.Tests
VerifyStackFrame(stackFrame, false, 0, typeof(StackFrameTests).GetMethod(nameof(Ctor_Default)), isCurrentFrame: true);
}
+ [ActiveIssue(23796, TargetFrameworkMonikers.NetFramework)]
[Theory]
[InlineData(true)]
[InlineData(false)]
@@ -43,6 +44,7 @@ namespace System.Diagnostics.Tests
VerifyStackFrame(stackFrame, true, skipFrames, typeof(StackFrameTests).GetMethod(nameof(Ctor_SkipFrames)), isCurrentFrame: skipFrames == 0);
}
+ [ActiveIssue(23796, TargetFrameworkMonikers.NetFramework)]
[Theory]
[InlineData(StackFrame.OFFSET_UNKNOWN, true)]
[InlineData(0, true)]
diff --git a/src/System.Diagnostics.Tracing/tests/BasicEventSourceTest/TestEventCounter.cs b/src/System.Diagnostics.Tracing/tests/BasicEventSourceTest/TestEventCounter.cs
index 281fae85ab..1f655227ea 100644
--- a/src/System.Diagnostics.Tracing/tests/BasicEventSourceTest/TestEventCounter.cs
+++ b/src/System.Diagnostics.Tracing/tests/BasicEventSourceTest/TestEventCounter.cs
@@ -44,6 +44,7 @@ namespace BasicEventSourceTests
[Fact]
[SkipOnTargetFramework(TargetFrameworkMonikers.NetFramework, reason: "https://github.com/dotnet/corefx/issues/23661")]
+ [ActiveIssue("https://github.com/dotnet/corefx/issues/22791", TargetFrameworkMonikers.UapAot)]
public void Test_Write_Metric_EventListener()
{
using (var listener = new EventListenerListener())
diff --git a/src/System.DirectoryServices.AccountManagement/src/System/DirectoryServices/AccountManagement/AD/ADStoreCtx.cs b/src/System.DirectoryServices.AccountManagement/src/System/DirectoryServices/AccountManagement/AD/ADStoreCtx.cs
index 0846907edb..a5362b7fa0 100644
--- a/src/System.DirectoryServices.AccountManagement/src/System/DirectoryServices/AccountManagement/AD/ADStoreCtx.cs
+++ b/src/System.DirectoryServices.AccountManagement/src/System/DirectoryServices/AccountManagement/AD/ADStoreCtx.cs
@@ -2078,7 +2078,7 @@ namespace System.DirectoryServices.AccountManagement
// interact with other StoreCtxs to fulfill the request.
//
// This method is typically used by ResultSet implementations, when they're iterating over a collection
- // (e.g., of group membership) and encounter a entry that represents a foreign principal.
+ // (e.g., of group membership) and encounter an entry that represents a foreign principal.
internal override Principal ResolveCrossStoreRefToPrincipal(object o)
{
Debug.Assert(o is DirectoryEntry);
@@ -2200,7 +2200,7 @@ namespace System.DirectoryServices.AccountManagement
}
// Returns true if AccountInfo is supported for the specified principal, false otherwise.
- // Used when a application tries to access the AccountInfo property of a newly-inserted
+ // Used when an application tries to access the AccountInfo property of a newly-inserted
// (not yet persisted) AuthenticablePrincipal, to determine whether it should be allowed.
internal override bool SupportsAccounts(AuthenticablePrincipal p)
{
@@ -2213,7 +2213,7 @@ namespace System.DirectoryServices.AccountManagement
}
// Returns the set of credential types supported by this store for the specified principal.
- // Used when a application tries to access the PasswordInfo property of a newly-inserted
+ // Used when an application tries to access the PasswordInfo property of a newly-inserted
// (not yet persisted) AuthenticablePrincipal, to determine whether it should be allowed.
// Also used to implement AuthenticablePrincipal.SupportedCredentialTypes.
internal override CredentialTypes SupportedCredTypes(AuthenticablePrincipal p)
diff --git a/src/System.DirectoryServices.AccountManagement/src/System/DirectoryServices/AccountManagement/AD/ADStoreCtx_LoadStore.cs b/src/System.DirectoryServices.AccountManagement/src/System/DirectoryServices/AccountManagement/AD/ADStoreCtx_LoadStore.cs
index 559bc0e715..57dec83e39 100644
--- a/src/System.DirectoryServices.AccountManagement/src/System/DirectoryServices/AccountManagement/AD/ADStoreCtx_LoadStore.cs
+++ b/src/System.DirectoryServices.AccountManagement/src/System/DirectoryServices/AccountManagement/AD/ADStoreCtx_LoadStore.cs
@@ -258,7 +258,7 @@ namespace System.DirectoryServices.AccountManagement
GlobalDebug.WriteLineIf(GlobalDebug.Info, "ADStoreCtx", "GetAsPrincipal: using path={0}", (null != de ? de.Path : "searchResult"));
- // Construct a appropriate Principal object.
+ // Construct an appropriate Principal object.
bool targetIsFromGC = SDSUtils.IsObjectFromGC(path);
try
diff --git a/src/System.DirectoryServices.AccountManagement/src/System/DirectoryServices/AccountManagement/AD/SDSUtils.cs b/src/System.DirectoryServices.AccountManagement/src/System/DirectoryServices/AccountManagement/AD/SDSUtils.cs
index 6d290a781e..d365332c1d 100644
--- a/src/System.DirectoryServices.AccountManagement/src/System/DirectoryServices/AccountManagement/AD/SDSUtils.cs
+++ b/src/System.DirectoryServices.AccountManagement/src/System/DirectoryServices/AccountManagement/AD/SDSUtils.cs
@@ -23,7 +23,7 @@ namespace System.DirectoryServices.AccountManagement
{
Principal p;
- // Construct a appropriate Principal object.
+ // Construct an appropriate Principal object.
// Make* constructs a Principal that is marked persisted
// and not loaded (p.unpersisted = false, p.loaded = false).
@@ -85,7 +85,7 @@ namespace System.DirectoryServices.AccountManagement
{
Principal p;
- // Construct a appropriate Principal object.
+ // Construct an appropriate Principal object.
// Make* constructs a Principal that is marked persisted
// and not loaded (p.unpersisted = false, p.loaded = false).
diff --git a/src/System.DirectoryServices.AccountManagement/src/System/DirectoryServices/AccountManagement/FindResultEnumerator.cs b/src/System.DirectoryServices.AccountManagement/src/System/DirectoryServices/AccountManagement/FindResultEnumerator.cs
index b52bec2492..3e4aee89d8 100644
--- a/src/System.DirectoryServices.AccountManagement/src/System/DirectoryServices/AccountManagement/FindResultEnumerator.cs
+++ b/src/System.DirectoryServices.AccountManagement/src/System/DirectoryServices/AccountManagement/FindResultEnumerator.cs
@@ -154,7 +154,7 @@ namespace System.DirectoryServices.AccountManagement
// Internal Constructors
//
- // Constructs a enumerator to enumerate over the supplied of ResultSet
+ // Constructs an enumerator to enumerate over the supplied of ResultSet
// Note that resultSet can be null
internal FindResultEnumerator(ResultSet resultSet)
{
diff --git a/src/System.DirectoryServices.AccountManagement/src/System/DirectoryServices/AccountManagement/PrincipalCollection.cs b/src/System.DirectoryServices.AccountManagement/src/System/DirectoryServices/AccountManagement/PrincipalCollection.cs
index 2924e10016..a86b831e05 100644
--- a/src/System.DirectoryServices.AccountManagement/src/System/DirectoryServices/AccountManagement/PrincipalCollection.cs
+++ b/src/System.DirectoryServices.AccountManagement/src/System/DirectoryServices/AccountManagement/PrincipalCollection.cs
@@ -429,7 +429,7 @@ namespace System.DirectoryServices.AccountManagement
}
else
{
- // They're trying to remove a already-persisted value. We add it to the
+ // They're trying to remove an already-persisted value. We add it to the
// removedValues list. Then, if it's already been loaded into insertedValuesCompleted,
// we remove it from insertedValuesCompleted.
diff --git a/src/System.DirectoryServices.AccountManagement/src/System/DirectoryServices/AccountManagement/SAM/SAMStoreCtx.cs b/src/System.DirectoryServices.AccountManagement/src/System/DirectoryServices/AccountManagement/SAM/SAMStoreCtx.cs
index d1d01ec541..416dd325cc 100644
--- a/src/System.DirectoryServices.AccountManagement/src/System/DirectoryServices/AccountManagement/SAM/SAMStoreCtx.cs
+++ b/src/System.DirectoryServices.AccountManagement/src/System/DirectoryServices/AccountManagement/SAM/SAMStoreCtx.cs
@@ -811,7 +811,7 @@ namespace System.DirectoryServices.AccountManagement
// interact with other StoreCtxs to fulfill the request.
//
// This method is typically used by ResultSet implementations, when they're iterating over a collection
- // (e.g., of group membership) and encounter a entry that represents a foreign principal.
+ // (e.g., of group membership) and encounter an entry that represents a foreign principal.
internal override Principal ResolveCrossStoreRefToPrincipal(object o)
{
Debug.Assert(o is DirectoryEntry);
@@ -894,7 +894,7 @@ namespace System.DirectoryServices.AccountManagement
//
// Returns true if AccountInfo is supported for the specified principal, false otherwise.
- // Used when a application tries to access the AccountInfo property of a newly-inserted
+ // Used when an application tries to access the AccountInfo property of a newly-inserted
// (not yet persisted) AuthenticablePrincipal, to determine whether it should be allowed.
internal override bool SupportsAccounts(AuthenticablePrincipal p)
{
@@ -907,7 +907,7 @@ namespace System.DirectoryServices.AccountManagement
}
// Returns the set of credential types supported by this store for the specified principal.
- // Used when a application tries to access the PasswordInfo property of a newly-inserted
+ // Used when an application tries to access the PasswordInfo property of a newly-inserted
// (not yet persisted) AuthenticablePrincipal, to determine whether it should be allowed.
// Also used to implement AuthenticablePrincipal.SupportedCredentialTypes.
internal override CredentialTypes SupportedCredTypes(AuthenticablePrincipal p)
diff --git a/src/System.DirectoryServices.AccountManagement/src/System/DirectoryServices/AccountManagement/SAM/SAMStoreCtx_LoadStore.cs b/src/System.DirectoryServices.AccountManagement/src/System/DirectoryServices/AccountManagement/SAM/SAMStoreCtx_LoadStore.cs
index 88594f37fa..baaf4b05c9 100644
--- a/src/System.DirectoryServices.AccountManagement/src/System/DirectoryServices/AccountManagement/SAM/SAMStoreCtx_LoadStore.cs
+++ b/src/System.DirectoryServices.AccountManagement/src/System/DirectoryServices/AccountManagement/SAM/SAMStoreCtx_LoadStore.cs
@@ -207,7 +207,7 @@ namespace System.DirectoryServices.AccountManagement
GlobalDebug.WriteLineIf(GlobalDebug.Info, "SAMStoreCtx", "GetAsPrincipal: using path={0}", de.Path);
- // Construct a appropriate Principal object.
+ // Construct an appropriate Principal object.
Principal p = SDSUtils.DirectoryEntryToPrincipal(de, this.OwningContext, null);
Debug.Assert(p != null);
diff --git a/src/System.DirectoryServices.AccountManagement/src/System/DirectoryServices/AccountManagement/StoreCtx.cs b/src/System.DirectoryServices.AccountManagement/src/System/DirectoryServices/AccountManagement/StoreCtx.cs
index a1340e384f..b4ef442830 100644
--- a/src/System.DirectoryServices.AccountManagement/src/System/DirectoryServices/AccountManagement/StoreCtx.cs
+++ b/src/System.DirectoryServices.AccountManagement/src/System/DirectoryServices/AccountManagement/StoreCtx.cs
@@ -206,7 +206,7 @@ namespace System.DirectoryServices.AccountManagement
// interact with other StoreCtxs to fulfill the request.
//
// This method is typically used by ResultSet implementations, when they're iterating over a collection
- // (e.g., of group membership) and encounter a entry that represents a foreign principal.
+ // (e.g., of group membership) and encounter an entry that represents a foreign principal.
internal abstract Principal ResolveCrossStoreRefToPrincipal(object o);
//
@@ -219,12 +219,12 @@ namespace System.DirectoryServices.AccountManagement
internal abstract bool IsValidProperty(Principal p, string propertyName);
// Returns true if AccountInfo is supported for the specified principal, false otherwise.
- // Used when a application tries to access the AccountInfo property of a newly-inserted
+ // Used when an application tries to access the AccountInfo property of a newly-inserted
// (not yet persisted) AuthenticablePrincipal, to determine whether it should be allowed.
internal abstract bool SupportsAccounts(AuthenticablePrincipal p);
// Returns the set of credential types supported by this store for the specified principal.
- // Used when a application tries to access the PasswordInfo property of a newly-inserted
+ // Used when an application tries to access the PasswordInfo property of a newly-inserted
// (not yet persisted) AuthenticablePrincipal, to determine whether it should be allowed.
// Also used to implement AuthenticablePrincipal.SupportedCredentialTypes.
internal abstract CredentialTypes SupportedCredTypes(AuthenticablePrincipal p);
diff --git a/src/System.DirectoryServices.AccountManagement/src/System/DirectoryServices/AccountManagement/Utils.cs b/src/System.DirectoryServices.AccountManagement/src/System/DirectoryServices/AccountManagement/Utils.cs
index ede2a49703..94bdfed888 100644
--- a/src/System.DirectoryServices.AccountManagement/src/System/DirectoryServices/AccountManagement/Utils.cs
+++ b/src/System.DirectoryServices.AccountManagement/src/System/DirectoryServices/AccountManagement/Utils.cs
@@ -237,7 +237,7 @@ namespace System.DirectoryServices.AccountManagement
(identAuth.b5 == 0) &&
(identAuth.b6 == 5))
{
- // No, so it can't be a account or builtin SID.
+ // No, so it can't be an account or builtin SID.
// Probably something like \Everyone or \LOCAL.
return SidType.FakeObject;
}
diff --git a/src/System.DirectoryServices.AccountManagement/tests/PrincipalContextTests.cs b/src/System.DirectoryServices.AccountManagement/tests/PrincipalContextTests.cs
index 02bd6dc51a..bf67a3c059 100644
--- a/src/System.DirectoryServices.AccountManagement/tests/PrincipalContextTests.cs
+++ b/src/System.DirectoryServices.AccountManagement/tests/PrincipalContextTests.cs
@@ -101,6 +101,7 @@ namespace System.DirectoryServices.AccountManagement.Tests
}
}
+ [ActiveIssue(23800)]
[ConditionalTheory(typeof(PlatformDetection), nameof(PlatformDetection.IsNotWindowsNanoServer))]
[OuterLoop("Takes too long on domain joined machines")]
[InlineData(ContextType.Machine, null, "userName", "password")]
@@ -126,6 +127,7 @@ namespace System.DirectoryServices.AccountManagement.Tests
}
}
+ [ActiveIssue(23800)]
[ConditionalTheory(typeof(PlatformDetection), nameof(PlatformDetection.IsNotWindowsNanoServer))]
[OuterLoop("Takes too long on domain joined machines")]
[InlineData(ContextType.Machine, null, null, "userName", "password")]
@@ -168,7 +170,11 @@ namespace System.DirectoryServices.AccountManagement.Tests
[Fact]
public void Ctor_DomainContextType_ThrowsPrincipalServerDownException()
{
- Assert.Throws<PrincipalServerDownException>(() => new PrincipalContext(ContextType.Domain));
+ if (Environment.MachineName.Equals(Environment.UserDomainName, StringComparison.OrdinalIgnoreCase))
+ {
+ // The machine is not connected to a domain. we expect PrincipalContext(ContextType.Domain) to throw
+ Assert.Throws<PrincipalServerDownException>(() => new PrincipalContext(ContextType.Domain));
+ }
}
[Fact]
@@ -292,6 +298,7 @@ namespace System.DirectoryServices.AccountManagement.Tests
Assert.Equal(expected, context.ValidateCredentials(userName, password, ContextOptions.Negotiate));
}
+ [ActiveIssue(23800)]
[ConditionalFact(typeof(PlatformDetection), nameof(PlatformDetection.IsNotWindowsNanoServer))]
[OuterLoop("Takes too long on domain joined machines")]
public void ValidateCredentials_InvalidUserName_ThrowsException()
@@ -300,6 +307,7 @@ namespace System.DirectoryServices.AccountManagement.Tests
Assert.Throws<Exception>(() => context.ValidateCredentials("\0", "password"));
}
+ [ActiveIssue(23800)]
[ConditionalFact(typeof(PlatformDetection), nameof(PlatformDetection.IsNotWindowsNanoServer))]
[OuterLoop("Takes too long on domain joined machines")]
public void ValidateCredentials_IncorrectUserNamePassword_ThrowsException()
diff --git a/src/System.DirectoryServices.Protocols/src/System/DirectoryServices/Protocols/common/SearchResults.cs b/src/System.DirectoryServices.Protocols/src/System/DirectoryServices/Protocols/common/SearchResults.cs
index 9edcb9389b..7c81120717 100644
--- a/src/System.DirectoryServices.Protocols/src/System/DirectoryServices/Protocols/common/SearchResults.cs
+++ b/src/System.DirectoryServices.Protocols/src/System/DirectoryServices/Protocols/common/SearchResults.cs
@@ -72,10 +72,11 @@ namespace System.DirectoryServices.Protocols
{
private DirectoryControl[] _resultControls = null;
- internal SearchResultEntry(string dn) => DistinguishedName = dn;
+ internal SearchResultEntry(string dn) : this(dn, new SearchResultAttributeCollection()) {}
- internal SearchResultEntry(string dn, SearchResultAttributeCollection attrs) : this(dn)
+ internal SearchResultEntry(string dn, SearchResultAttributeCollection attrs)
{
+ DistinguishedName = dn;
Attributes = attrs;
}
diff --git a/src/System.DirectoryServices/src/System/DirectoryServices/ActiveDirectory/Utils.cs b/src/System.DirectoryServices/src/System/DirectoryServices/ActiveDirectory/Utils.cs
index 5512312aa6..ae29ccfeed 100644
--- a/src/System.DirectoryServices/src/System/DirectoryServices/ActiveDirectory/Utils.cs
+++ b/src/System.DirectoryServices/src/System/DirectoryServices/ActiveDirectory/Utils.cs
@@ -2304,7 +2304,7 @@ namespace System.DirectoryServices.ActiveDirectory
(identAuth.b5 == 0) &&
(identAuth.b6 == 5))
{
- // No, so it can't be a account or builtin SID.
+ // No, so it can't be an account or builtin SID.
// Probably something like \Everyone or \LOCAL.
return SidType.FakeObject;
}
diff --git a/src/System.DirectoryServices/tests/LDAP.Configuration.xml b/src/System.DirectoryServices/tests/LDAP.Configuration.xml
new file mode 100644
index 0000000000..f587727b9a
--- /dev/null
+++ b/src/System.DirectoryServices/tests/LDAP.Configuration.xml
@@ -0,0 +1,19 @@
+<?xml version="1.0" encoding="UTF-8"?>
+<!--
+ To enable the tests marked with [ConditionalFact(nameof(IsLdapConfigurationExist))], need to setup LDAP server and provide the needed server info here.
+ The easiest way to get LDAP server is to download and install OpenDJ https://backstage.forgerock.com/downloads/OpenDJ/Directory%20Services/5.0.0#browse.
+
+ Download "DS zip" file then extract it. you can set it up by running a command like that following:
+ /setup directory-server --sampleData 2 --rootUserDN "cn=Directory Manager" --rootUserPassword password --hostname localhost.localdomain --ldapPort 1389 --ldapsPort 1636 --httpPort 8080 --httpsPort 8443 --adminConnectorPort 4444 --baseDN dc=example,dc=com --acceptLicense –enableStartTls
+
+ After that delete this comment and have the following contents in this Xml file:
+
+<Configuration>
+ <ServerName>server machine name</ServerName>
+ <Domain>DC=example,DC=com</Domain>
+ <Port>1389</Port>
+ <User>cn=Directory Manager</User>
+ <Password>password</Password>
+ <AuthenticationTypes>ServerBind,None</AuthenticationTypes>
+</Configuration>
+--> \ No newline at end of file
diff --git a/src/System.DirectoryServices/tests/System.DirectoryServices.Tests.csproj b/src/System.DirectoryServices/tests/System.DirectoryServices.Tests.csproj
index c8123fbb03..a4ede97814 100644
--- a/src/System.DirectoryServices/tests/System.DirectoryServices.Tests.csproj
+++ b/src/System.DirectoryServices/tests/System.DirectoryServices.Tests.csproj
@@ -10,6 +10,7 @@
<Compile Include="System\DirectoryServices\ActiveDirectorySecurityTests.cs" />
<Compile Include="System\DirectoryServices\ActiveDirectory\DomainControllerTests.cs" />
<Compile Include="System\DirectoryServices\DirectoryEntryTests.cs" />
+ <Compile Include="System\DirectoryServices\DirectoryServicesTests.cs" />
<Compile Include="System\DirectoryServices\DirectorySynchronizationTests.cs" />
<Compile Include="System\DirectoryServices\DirectoryVirtualListViewContextTests.cs" />
<Compile Include="System\DirectoryServices\DirectoryVirtualListViewTests.cs" />
@@ -18,6 +19,15 @@
<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\DirectoryServices\LdapConfiguration.cs">
+ <Link>Common\DirectoryServices\LdapConfiguration.cs</Link>
+ </Compile>
+ </ItemGroup>
+ <ItemGroup>
+ <None Include="LDAP.Configuration.xml">
+ <CopyToOutputDirectory>PreserveNewest</CopyToOutputDirectory>
+ </None>
</ItemGroup>
<Import Project="$([MSBuild]::GetDirectoryNameOfFileAbove($(MSBuildThisFileDirectory), dir.targets))\dir.targets" />
</Project> \ No newline at end of file
diff --git a/src/System.DirectoryServices/tests/System/DirectoryServices/ActiveDirectory/ActiveDirectoryInterSiteTransportTests.cs b/src/System.DirectoryServices/tests/System/DirectoryServices/ActiveDirectory/ActiveDirectoryInterSiteTransportTests.cs
index 98dd109458..33c516c056 100644
--- a/src/System.DirectoryServices/tests/System/DirectoryServices/ActiveDirectory/ActiveDirectoryInterSiteTransportTests.cs
+++ b/src/System.DirectoryServices/tests/System/DirectoryServices/ActiveDirectory/ActiveDirectoryInterSiteTransportTests.cs
@@ -36,8 +36,12 @@ namespace System.DirectoryServices.ActiveDirectory.Tests
[SkipOnTargetFramework(TargetFrameworkMonikers.Uap, "Not approved COM object for app")]
public void FindByTransportType_ForestNoDomainAssociatedWithName_ThrowsActiveDirectoryOperationException_NoUap()
{
- var context = new DirectoryContext(DirectoryContextType.Forest, "\0");
- AssertExtensions.Throws<ArgumentException>("context", () => ActiveDirectoryInterSiteTransport.FindByTransportType(context, ActiveDirectoryTransportType.Rpc));
+ // Domain joined machines will not throw on the ActiveDirectoryInterSiteTransport.FindByTransportType call.
+ if (Environment.MachineName.Equals(Environment.UserDomainName, StringComparison.OrdinalIgnoreCase))
+ {
+ var context = new DirectoryContext(DirectoryContextType.Forest, "\0");
+ AssertExtensions.Throws<ArgumentException>("context", () => ActiveDirectoryInterSiteTransport.FindByTransportType(context, ActiveDirectoryTransportType.Rpc));
+ }
}
[Fact]
diff --git a/src/System.DirectoryServices/tests/System/DirectoryServices/ActiveDirectory/DomainControllerTests.cs b/src/System.DirectoryServices/tests/System/DirectoryServices/ActiveDirectory/DomainControllerTests.cs
index 1251f474e0..d95fd471d3 100644
--- a/src/System.DirectoryServices/tests/System/DirectoryServices/ActiveDirectory/DomainControllerTests.cs
+++ b/src/System.DirectoryServices/tests/System/DirectoryServices/ActiveDirectory/DomainControllerTests.cs
@@ -109,9 +109,13 @@ namespace System.DirectoryServices.ActiveDirectory.Tests
[SkipOnTargetFramework(TargetFrameworkMonikers.Uap, "Not approved COM object for app")]
public void FindAll_NoSuchName_ReturnsEmpty()
{
- var context = new DirectoryContext(DirectoryContextType.Domain, "\0");
- Assert.Empty(DomainController.FindAll(context));
- Assert.Empty(DomainController.FindAll(context, "siteName"));
+ // Domain joined machines can have entries in the DomainController.
+ if (Environment.MachineName.Equals(Environment.UserDomainName, StringComparison.OrdinalIgnoreCase))
+ {
+ var context = new DirectoryContext(DirectoryContextType.Domain, "\0");
+ Assert.Empty(DomainController.FindAll(context));
+ Assert.Empty(DomainController.FindAll(context, "siteName"));
+ }
}
[Fact]
diff --git a/src/System.DirectoryServices/tests/System/DirectoryServices/DirectoryServicesTests.cs b/src/System.DirectoryServices/tests/System/DirectoryServices/DirectoryServicesTests.cs
new file mode 100644
index 0000000000..05796aafc5
--- /dev/null
+++ b/src/System.DirectoryServices/tests/System/DirectoryServices/DirectoryServicesTests.cs
@@ -0,0 +1,155 @@
+// 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;
+using System.Collections.Generic;
+using System.Collections;
+using Xunit;
+
+namespace System.DirectoryServices.Tests
+{
+ public class DirectoryServicesTests
+ {
+ internal static bool IsLdapConfigurationExist => LdapConfiguration.Configuration != null;
+
+ [ConditionalFact(nameof(IsLdapConfigurationExist))]
+ public void TestOU() // adding and removing organization unit
+ {
+ using (DirectoryEntry de = new DirectoryEntry(LdapConfiguration.Configuration.LdapPath,
+ LdapConfiguration.Configuration.UserName,
+ LdapConfiguration.Configuration.Password,
+ LdapConfiguration.Configuration.AuthenticationTypes))
+ {
+ string ouName = "NetCoreDevs";
+
+ // ensure cleanup before doing the creation.
+ DeleteOU(de, ouName);
+
+ CreateOU(de, ouName, ".Net Core Developers Unit");
+ try
+ {
+ SearchOUByName(de, ouName);
+ }
+ finally
+ {
+ // Clean up the added ou
+ DeleteOU(de, ouName);
+ }
+ }
+ }
+
+ [ConditionalFact(nameof(IsLdapConfigurationExist))]
+ public void TestOrganizationalRole() // adding and removing users to/from the ou
+ {
+ using (DirectoryEntry de = new DirectoryEntry(LdapConfiguration.Configuration.LdapPath,
+ LdapConfiguration.Configuration.UserName,
+ LdapConfiguration.Configuration.Password,
+ LdapConfiguration.Configuration.AuthenticationTypes))
+ {
+ DeleteOU(de, "CoreFxRootOU");
+
+ using (DirectoryEntry rootOU = CreateOU(de, "CoreFxRootOU", "CoreFx Root OU"))
+ {
+ try
+ {
+ DirectoryEntry child1OU = CreateOU(rootOU, "CoreFxChild1OU", "CoreFx Child OU 1");
+ DirectoryEntry child2OU = CreateOU(rootOU, "CoreFxChild2OU", "CoreFx Child OU 2");
+
+ CreateOrganizationalRole(child1OU, "user.ou1.1", "User 1 is in CoreFx ou 1", "1 111 111 11111");
+ CreateOrganizationalRole(child1OU, "user.ou1.2", "User 2 is in CoreFx ou 1", "1 222 222 22222");
+
+ CreateOrganizationalRole(child2OU, "user.ou2.1", "User 1 is in CoreFx ou 2", "1 333 333 3333");
+ CreateOrganizationalRole(child2OU, "user.ou2.2", "User 2 is in CoreFx ou 2", "1 333 333 3333");
+
+ // now let's search for the added data:
+ SearchOUByName(rootOU, "CoreFxChild1OU");
+ SearchOUByName(rootOU, "CoreFxChild2OU");
+
+ SearchOrganizationalRole(child1OU, "user.ou1.1");
+ SearchOrganizationalRole(child1OU, "user.ou1.2");
+
+ SearchOrganizationalRole(child2OU, "user.ou2.1");
+ SearchOrganizationalRole(child2OU, "user.ou2.2");
+ }
+ finally
+ {
+ // rootOU.DeleteTree(); doesn't work as getting "A protocol error occurred. (Exception from HRESULT: 0x80072021)"
+ DeleteOU(de, "CoreFxRootOU");
+ }
+ }
+ }
+ }
+
+ private DirectoryEntry CreateOU(DirectoryEntry de, string ou, string description)
+ {
+ DirectoryEntry ouCoreDevs = de.Children.Add($"ou={ou}","Class");
+ ouCoreDevs.Properties["objectClass"].Value = "organizationalUnit"; // has to be organizationalUnit
+ ouCoreDevs.Properties["description"].Value = description;
+ ouCoreDevs.Properties["ou"].Value = ou;
+ ouCoreDevs.CommitChanges();
+ return ouCoreDevs;
+ }
+
+ private DirectoryEntry CreateOrganizationalRole(DirectoryEntry ouEntry, string cn, string description, string phone)
+ {
+ DirectoryEntry cnEntry = ouEntry.Children.Add($"cn={cn}","Class");
+ cnEntry.Properties["objectClass"].Value = "organizationalRole";
+ cnEntry.Properties["cn"].Value = cn;
+ cnEntry.Properties["description"].Value = description;
+ cnEntry.Properties["ou"].Value = ouEntry.Name;
+ cnEntry.Properties["telephoneNumber"].Value = phone;
+ cnEntry.CommitChanges();
+ return cnEntry;
+ }
+
+ private void DeleteOU(DirectoryEntry parentDe, string ou)
+ {
+ try
+ {
+ // We didn't use DirectoryEntry.DeleteTree as it fails on OpenDJ with "A protocol error occurred. (Exception from HRESULT: 0x80072021)"
+ // Also on AD servers DirectoryEntry.Children.Remove(de) will fail if the de is not a leaf entry. so we had to do it recursively.
+ DirectoryEntry de = parentDe.Children.Find($"ou={ou}");
+ DeleteDirectoryEntry(parentDe, de);
+ }
+ catch
+ {
+ // ignore the error if the test failed early and couldn't create the OU we are trying to delete
+ }
+ }
+
+ private void DeleteDirectoryEntry(DirectoryEntry parent, DirectoryEntry de)
+ {
+ foreach (DirectoryEntry child in de.Children)
+ {
+ DeleteDirectoryEntry(de, child);
+ }
+
+ parent.Children.Remove(de);
+ parent.CommitChanges();
+ }
+
+ private void SearchOUByName(DirectoryEntry de, string ouName)
+ {
+ using (DirectorySearcher ds = new DirectorySearcher(de))
+ {
+ ds.ClientTimeout = new TimeSpan(0, 2, 0);
+ ds.Filter = $"(&(objectClass=organizationalUnit)(ou={ouName}))";
+ ds.PropertiesToLoad.Add("ou");
+ SearchResult sr = ds.FindOne();
+ Assert.Equal(ouName, sr.Properties["ou"][0]);
+ }
+ }
+
+ private void SearchOrganizationalRole(DirectoryEntry de, string cnName)
+ {
+ using (DirectorySearcher ds = new DirectorySearcher(de))
+ {
+ ds.Filter = $"(&(objectClass=organizationalRole)(cn={cnName}))";
+ ds.PropertiesToLoad.Add("cn");
+ SearchResult sr = ds.FindOne();
+ Assert.Equal(cnName, sr.Properties["cn"][0]);
+ }
+ }
+ }
+}
diff --git a/src/System.Drawing.Common/System.Drawing.Common.sln b/src/System.Drawing.Common/System.Drawing.Common.sln
index d8a540b334..bdc9c7a707 100644
--- a/src/System.Drawing.Common/System.Drawing.Common.sln
+++ b/src/System.Drawing.Common/System.Drawing.Common.sln
@@ -1,6 +1,6 @@
Microsoft Visual Studio Solution File, Format Version 12.00
-# Visual Studio 14
-VisualStudioVersion = 14.0.25420.1
+# Visual Studio 15
+VisualStudioVersion = 15.0.26911.0
MinimumVisualStudioVersion = 10.0.40219.1
Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "System.Drawing.Common.Tests", "tests\System.Drawing.Common.Tests.csproj", "{4B93E684-0630-45F4-8F63-6C7788C9892F}"
ProjectSection(ProjectDependencies) = postProject
@@ -30,8 +30,8 @@ Global
{4B93E684-0630-45F4-8F63-6C7788C9892F}.Debug|Any CPU.Build.0 = netcoreapp-Debug|Any CPU
{4B93E684-0630-45F4-8F63-6C7788C9892F}.Release|Any CPU.ActiveCfg = netcoreapp-Release|Any CPU
{4B93E684-0630-45F4-8F63-6C7788C9892F}.Release|Any CPU.Build.0 = netcoreapp-Release|Any CPU
- {191B3618-FECD-4ABD-9D6B-5AC90DC33621}.Debug|Any CPU.ActiveCfg = netcoreapp2.0-Unix-Debug|Any CPU
- {191B3618-FECD-4ABD-9D6B-5AC90DC33621}.Debug|Any CPU.Build.0 = netcoreapp2.0-Unix-Debug|Any CPU
+ {191B3618-FECD-4ABD-9D6B-5AC90DC33621}.Debug|Any CPU.ActiveCfg = netcoreapp2.0-Windows_NT-Debug|Any CPU
+ {191B3618-FECD-4ABD-9D6B-5AC90DC33621}.Debug|Any CPU.Build.0 = netcoreapp2.0-Windows_NT-Debug|Any CPU
{191B3618-FECD-4ABD-9D6B-5AC90DC33621}.Release|Any CPU.ActiveCfg = netcoreapp2.0-Unix-Release|Any CPU
{191B3618-FECD-4ABD-9D6B-5AC90DC33621}.Release|Any CPU.Build.0 = netcoreapp2.0-Unix-Release|Any CPU
{D7AEA698-275D-441F-B7A7-8491D1F0EFF0}.Debug|Any CPU.ActiveCfg = netcoreapp2.0-Debug|Any CPU
@@ -47,4 +47,7 @@ Global
{191B3618-FECD-4ABD-9D6B-5AC90DC33621} = {E107E9C1-E893-4E87-987E-04EF0DCEAEFD}
{D7AEA698-275D-441F-B7A7-8491D1F0EFF0} = {2E666815-2EDB-464B-9DF6-380BF4789AD4}
EndGlobalSection
+ GlobalSection(ExtensibilityGlobals) = postSolution
+ SolutionGuid = {ACBCC0AB-54DC-4B76-9556-2569EF381DFB}
+ EndGlobalSection
EndGlobal
diff --git a/src/System.Drawing.Common/src/Unix/MonoTODOAttribute.cs b/src/System.Drawing.Common/src/MonoTODOAttribute.cs
index a8193e7b0e..a8193e7b0e 100644
--- a/src/System.Drawing.Common/src/Unix/MonoTODOAttribute.cs
+++ b/src/System.Drawing.Common/src/MonoTODOAttribute.cs
diff --git a/src/System.Drawing.Common/src/System.Drawing.Common.csproj b/src/System.Drawing.Common/src/System.Drawing.Common.csproj
index 9d9755f4ad..e96c9dddc0 100644
--- a/src/System.Drawing.Common/src/System.Drawing.Common.csproj
+++ b/src/System.Drawing.Common/src/System.Drawing.Common.csproj
@@ -32,6 +32,7 @@
<Reference Include="System.Runtime" />
<Reference Include="System.Runtime.Extensions" />
<Reference Include="System.Runtime.InteropServices" />
+ <Reference Include="System.Runtime.InteropServices.RuntimeInformation" />
<Reference Include="System.ComponentModel" />
<Reference Include="System.ComponentModel.Primitives" />
<Reference Include="System.Threading" />
@@ -45,12 +46,17 @@
<Compile Include="System\Drawing\BitmapSuffixInSatelliteAssemblyAttribute.cs" />
<Compile Include="System\Drawing\Brushes.cs" />
<Compile Include="System\Drawing\CharacterRange.cs" />
+ <Compile Include="System\Drawing\ColorTranslator.cs" />
+ <Compile Include="System\Drawing\ContentAlignment.cs" />
<Compile Include="System\Drawing\IDeviceContext.cs" />
<Compile Include="System\Drawing\GdiplusNative.cs" />
<Compile Include="System\Drawing\Graphics.cs" />
+ <Compile Include="System\Drawing\GraphicsUnit.cs" />
+ <Compile Include="System\Drawing\ImageType.cs" />
<Compile Include="System\Drawing\Pen.cs" />
<Compile Include="System\Drawing\Pens.cs" />
<Compile Include="System\Drawing\RotateFlipType.cs" />
+ <Compile Include="System\Drawing\SystemColors.cs" />
<Compile Include="System\Drawing\StringFormat.cs" />
<Compile Include="System\Drawing\SystemFonts.cs" />
<Compile Include="System\Drawing\SystemPens.cs" />
@@ -109,6 +115,7 @@
<Compile Include="System\Drawing\Imaging\FrameDimension.cs" />
<Compile Include="System\Drawing\Imaging\ImageCodecFlags.cs" />
<Compile Include="System\Drawing\Imaging\ImageFlags.cs" />
+ <Compile Include="System\Drawing\Imaging\ImageFormat.cs" />
<Compile Include="System\Drawing\Imaging\ImageLockMode.cs" />
<Compile Include="System\Drawing\Imaging\MetafileType.cs" />
<Compile Include="System\Drawing\Imaging\PaletteFlags.cs" />
@@ -139,6 +146,7 @@
<Compile Include="System\Drawing\Internal\GPRECT.cs" />
<Compile Include="System\Drawing\Internal\GPRECTF.cs" />
<Compile Include="System\Drawing\Brush.cs" />
+ <Compile Include="System\Drawing\FontFamily.cs" />
<Compile Include="System\Drawing\SolidBrush.cs" />
<Compile Include="System\Drawing\SystemBrushes.cs" />
<Compile Include="System\Drawing\TextureBrush.cs" />
@@ -190,60 +198,57 @@
<Compile Include="$(CommonPath)\System\Drawing\KnownColorTable.cs">
<Link>System\Drawing\KnownColorTable.cs</Link>
</Compile>
+ <Compile Include="$(CommonPath)\System\Runtime\InteropServices\FunctionWrapper.cs">
+ <Link>Common\System\Runtime\InteropServices\FunctionWrapper.cs</Link>
+ </Compile>
</ItemGroup>
<ItemGroup Condition="'$(TargetsWindows)' == 'true'">
<!-- Windows-specific -->
<Compile Include="AssemblyRef.cs" />
<Compile Include="SRDescriptionAttribute.cs" />
- <Compile Include="System\Drawing\Bitmap.cs" />
+ <Compile Include="System\Drawing\Bitmap.Windows.cs" />
<Compile Include="System\Drawing\BitmapSelector.cs" />
- <Compile Include="System\Drawing\BufferedGraphics.cs" />
- <Compile Include="System\Drawing\BufferedGraphicsContext.cs" />
- <Compile Include="System\Drawing\BufferedGraphicsManager.cs" />
- <Compile Include="System\Drawing\ColorTranslator.cs" />
- <Compile Include="System\Drawing\ContentAlignment.cs" />
+ <Compile Include="System\Drawing\BufferedGraphics.Windows.cs" />
+ <Compile Include="System\Drawing\BufferedGraphicsContext.Windows.cs" />
+ <Compile Include="System\Drawing\BufferedGraphicsManager.Windows.cs" />
<Compile Include="System\Drawing\Drawing2D\CustomLineCap.Windows.cs" />
- <Compile Include="System\Drawing\Drawing2D\GraphicsPath.cs" />
- <Compile Include="System\Drawing\Font.cs" />
+ <Compile Include="System\Drawing\Drawing2D\GraphicsPath.Windows.cs" />
+ <Compile Include="System\Drawing\Font.Windows.cs" />
<Compile Include="System\Drawing\Font.NotSerializable.cs" />
- <Compile Include="System\Drawing\FontFamily.cs" />
<Compile Include="System\Drawing\GdiplusNative.Windows.cs" />
<Compile Include="System\Drawing\Graphics.Windows.cs" />
<Compile Include="System\Drawing\GraphicsContext.cs" />
- <Compile Include="System\Drawing\Icon.cs" />
+ <Compile Include="System\Drawing\Icon.Windows.cs" />
<Compile Include="System\Drawing\Icon.NotSerializable.cs" />
- <Compile Include="System\Drawing\Image.cs" />
+ <Compile Include="System\Drawing\Image.Windows.cs" />
<Compile Include="System\Drawing\Image.NotSerializable.cs" />
- <Compile Include="System\Drawing\ImageAnimator.cs" />
+ <Compile Include="System\Drawing\ImageAnimator.Windows.cs" />
<Compile Include="System\Drawing\ImageInfo.cs" />
- <Compile Include="System\Drawing\Imaging\BitmapData.cs" />
- <Compile Include="System\Drawing\Imaging\ImageFormat.cs" />
- <Compile Include="System\Drawing\Imaging\Metafile.cs" />
- <Compile Include="System\Drawing\Imaging\MetafileHeader.cs" />
- <Compile Include="System\Drawing\Imaging\METAHEADER.cs" />
+ <Compile Include="System\Drawing\Imaging\BitmapData.Windows.cs" />
+ <Compile Include="System\Drawing\Imaging\Metafile.Windows.cs" />
+ <Compile Include="System\Drawing\Imaging\MetafileHeader.Windows.cs" />
+ <Compile Include="System\Drawing\Imaging\MetaHeader.Windows.cs" />
<Compile Include="System\Drawing\Internal\GPStream.cs" />
<Compile Include="System\Drawing\LocalAppContextSwitches.cs" />
<Compile Include="System\Drawing\Pen.Windows.cs" />
<Compile Include="System\Drawing\Printing\DefaultPrintController.cs" />
<Compile Include="System\Drawing\Printing\ModeField.cs" />
- <Compile Include="System\Drawing\Printing\PageSettings.cs" />
- <Compile Include="System\Drawing\Printing\PreviewPrintController.cs" />
- <Compile Include="System\Drawing\Printing\PrintController.cs" />
- <Compile Include="System\Drawing\Printing\PrintDocument.cs">
+ <Compile Include="System\Drawing\Printing\PageSettings.Windows.cs" />
+ <Compile Include="System\Drawing\Printing\PreviewPrintController.Windows.cs" />
+ <Compile Include="System\Drawing\Printing\PrintController.Windows.cs" />
+ <Compile Include="System\Drawing\Printing\PrintDocument.Windows.cs">
<SubType>Component</SubType>
</Compile>
- <Compile Include="System\Drawing\Printing\PrinterSettings.cs" />
- <Compile Include="System\Drawing\Printing\PrintEvent.cs" />
- <Compile Include="System\Drawing\Printing\PrintPageEvent.cs" />
+ <Compile Include="System\Drawing\Printing\PrinterSettings.Windows.cs" />
+ <Compile Include="System\Drawing\Printing\PrintEventArgs.Windows.cs" />
+ <Compile Include="System\Drawing\Printing\PrintPageEventArgs.Windows.cs" />
<Compile Include="System\Drawing\Printing\PrintPreviewGraphics.cs" />
<Compile Include="System\Drawing\Printing\TriState.cs" />
<Compile Include="System\Drawing\Region.Windows.cs" />
- <Compile Include="System\Drawing\SystemColors.cs" />
<Compile Include="System\Drawing\SystemFonts.Windows.cs" />
- <Compile Include="System\Drawing\SystemIcons.cs" />
+ <Compile Include="System\Drawing\SystemIcons.Windows.cs" />
<Compile Include="System\Drawing\ToolboxBitmapAttribute.cs" />
<Compile Include="System\Drawing\Text\PrivateFontCollection.Windows.cs" />
- <Compile Include="System\Drawing\Unit.cs" />
<Compile Include="misc\DbgUtil.cs" />
<Compile Include="misc\DpiHelper.cs" />
<Compile Include="misc\ExternDll.cs" />
@@ -282,60 +287,53 @@
<Compile Include="$(CommonPath)\Microsoft\Win32\SafeHandles\SafeLibraryHandle.cs">
<Link>Common\Microsoft\Win32\SafeHandles\SafeLibraryHandle.cs</Link>
</Compile>
+ <Compile Include="$(CommonPath)\System\Runtime\InteropServices\FunctionWrapper.Windows.cs">
+ <Link>Common\System\Runtime\InteropServices\FunctionWrapper.Windows.cs</Link>
+ </Compile>
</ItemGroup>
<ItemGroup Condition="'$(TargetsUnix)' == 'true'">
<!-- Unix-specific -->
<Compile Include="System\Drawing\Graphics.Unix.cs" />
+ <Compile Include="System\Drawing\Icon.Unix.cs" />
+ <Compile Include="System\Drawing\Icon.NotSerializable.cs" />
<Compile Include="System\Drawing\SystemFonts.Unix.cs" />
- <Compile Include="Unix\System.Drawing\Bitmap.cs" />
- <Compile Include="Unix\System.Drawing\BufferedGraphics.cs" />
- <Compile Include="Unix\System.Drawing\BufferedGraphicsManager.cs" />
- <Compile Include="Unix\System.Drawing\BufferedGraphicsContext.cs" />
- <Compile Include="Unix\System.Drawing\macFunctions.cs" />
- <Compile Include="Unix\System.Drawing\ColorTranslator.cs" />
- <Compile Include="Unix\System.Drawing\ComIStreamMarshaler.cs" />
- <Compile Include="Unix\System.Drawing\ComIStreamWrapper.cs" />
- <Compile Include="Unix\System.Drawing\ContentAlignment.cs" />
- <Compile Include="Unix\System.Drawing\Font.cs" />
- <Compile Include="Unix\System.Drawing\FontFamily.cs" />
- <Compile Include="Unix\System.Drawing\GraphicsUnit.cs" />
- <Compile Include="Unix\System.Drawing\gdipEnums.cs" />
- <Compile Include="Unix\System.Drawing\gdipFunctions.cs" />
+ <Compile Include="System\Drawing\Imaging\BitmapData.Unix.cs" />
+ <Compile Include="System\Drawing\Imaging\Metafile.Unix.cs" />
+ <Compile Include="System\Drawing\Imaging\MetafileHeader.Unix.cs" />
+ <Compile Include="System\Drawing\Imaging\MetaHeader.Unix.cs" />
+ <Compile Include="System\Drawing\Printing\LibcupsNative.cs" />
+ <Compile Include="System\Drawing\Printing\PrintingServices.Unix.cs" />
+ <Compile Include="System\Drawing\Printing\PageSettings.Unix.cs" />
+ <Compile Include="System\Drawing\Printing\PreviewPrintController.Unix.cs" />
+ <Compile Include="System\Drawing\Printing\PrintController.Unix.cs" />
+ <Compile Include="System\Drawing\Printing\PrintDocument.Unix.cs" />
+ <Compile Include="System\Drawing\Printing\PrinterSettings.Unix.cs" />
+ <Compile Include="System\Drawing\Printing\PrintEventArgs.Unix.cs" />
+ <Compile Include="System\Drawing\Printing\PrintPageEventArgs.Unix.cs" />
+ <Compile Include="System\Drawing\Printing\StandardPrintController.Unix.cs" />
+ <Compile Include="System\Drawing\Bitmap.Unix.cs" />
+ <Compile Include="System\Drawing\BufferedGraphics.Unix.cs" />
+ <Compile Include="System\Drawing\BufferedGraphicsManager.Unix.cs" />
+ <Compile Include="System\Drawing\BufferedGraphicsContext.Unix.cs" />
+ <Compile Include="System\Drawing\macFunctions.cs" />
+ <Compile Include="System\Drawing\Font.Unix.cs" />
<Compile Include="System\Drawing\GdiplusNative.Unix.cs" />
- <Compile Include="Unix\System.Drawing\gdipStructs.cs" />
- <Compile Include="Unix\System.Drawing\Icon.cs" />
- <Compile Include="Unix\System.Drawing\ImageAnimator.cs" />
- <Compile Include="Unix\System.Drawing\Image.cs" />
- <Compile Include="Unix\System.Drawing\KnownColors.cs" />
+ <Compile Include="System\Drawing\GdiPlusStreamHelper.Unix.cs" />
+ <Compile Include="System\Drawing\LibX11Functions.cs" />
+ <Compile Include="System\Drawing\MarshallingHelpers.cs" />
+ <Compile Include="System\Drawing\NativeStructs.Unix.cs" />
+ <Compile Include="System\Drawing\ImageAnimator.Unix.cs" />
+ <Compile Include="System\Drawing\Image.Unix.cs" />
<Compile Include="System\Drawing\Pen.Unix.cs" />
<Compile Include="System\Drawing\Region.Unix.cs" />
- <Compile Include="Unix\System.Drawing\SRDescriptionAttribute.cs" />
- <Compile Include="Unix\System.Drawing\SystemColors.cs" />
- <Compile Include="Unix\System.Drawing\SystemIcons.cs" />
- <Compile Include="Unix\System.Drawing\ToolboxBitmapAttribute.cs" />
+ <Compile Include="System\Drawing\SRDescriptionAttribute.cs" />
+ <Compile Include="System\Drawing\SystemIcons.Unix.cs" />
+ <Compile Include="System\Drawing\ToolboxBitmapAttribute.Unix.cs" />
<Compile Include="System\Drawing\Drawing2D\AdjustableArrowCap.Unix.cs" />
<Compile Include="System\Drawing\Drawing2D\CustomLineCap.Unix.cs" />
- <Compile Include="Unix\System.Drawing.Drawing2D\GraphicsPath.cs" />
- <Compile Include="Unix\System.Drawing.Imaging\BitmapData.cs" />
- <Compile Include="Unix\System.Drawing.Imaging\ImageFormat.cs" />
- <Compile Include="Unix\System.Drawing.Imaging\Metafile.cs" />
- <Compile Include="Unix\System.Drawing.Imaging\MetafileHeader.cs" />
- <Compile Include="Unix\System.Drawing.Imaging\MetaHeader.cs" />
- <Compile Include="Unix\System.Drawing.Printing\PrintingServices.cs" />
- <Compile Include="Unix\System.Drawing.Printing\PrintingServicesWin32.cs" />
- <Compile Include="Unix\System.Drawing.Printing\PrintingServicesUnix.cs" />
- <Compile Include="Unix\System.Drawing.Printing\PageSettings.cs" />
- <Compile Include="Unix\System.Drawing.Printing\PreviewPrintController.cs" />
- <Compile Include="Unix\System.Drawing.Printing\PrintController.cs" />
- <Compile Include="Unix\System.Drawing.Printing\PrintDocument.cs">
- <SubType>Component</SubType>
- </Compile>
- <Compile Include="Unix\System.Drawing.Printing\PrinterSettings.cs" />
- <Compile Include="Unix\System.Drawing.Printing\PrintEventArgs.cs" />
- <Compile Include="Unix\System.Drawing.Printing\PrintPageEventArgs.cs" />
- <Compile Include="Unix\System.Drawing.Printing\StandardPrintController.cs" />
+ <Compile Include="System\Drawing\Drawing2D\GraphicsPath.Unix.cs" />
<Compile Include="System\Drawing\Text\PrivateFontCollection.Unix.cs" />
- <Compile Include="Unix\MonoTODOAttribute.cs" />
+ <Compile Include="MonoTODOAttribute.cs" />
<Compile Include="misc\ExternDll.Unix.cs" />
<Compile Include="$(CommonPath)\Interop\Unix\Interop.Libraries.cs">
<Link>Common\Interop\Unix\Interop.Libraries.cs</Link>
@@ -346,6 +344,9 @@
<Compile Include="$(CommonPath)\Interop\Unix\libdl\Interop.dlsym.cs">
<Link>Common\Interop\Unix\libdl\Interop.dlsym.cs</Link>
</Compile>
+ <Compile Include="$(CommonPath)\System\Runtime\InteropServices\FunctionWrapper.Unix.cs">
+ <Link>Common\System\Runtime\InteropServices\FunctionWrapper.Unix.cs</Link>
+ </Compile>
</ItemGroup>
<ItemGroup>
<EmbeddedResource Include="Resources\System\Drawing\DefaultComponent.bmp">
@@ -360,4 +361,4 @@
</EmbeddedResource>
</ItemGroup>
<Import Project="$([MSBuild]::GetDirectoryNameOfFileAbove($(MSBuildThisFileDirectory), dir.targets))\dir.targets" />
-</Project> \ No newline at end of file
+</Project>
diff --git a/src/System.Drawing.Common/src/Unix/System.Drawing/Bitmap.cs b/src/System.Drawing.Common/src/System/Drawing/Bitmap.Unix.cs
index 34c11158d8..5c6707c9ae 100644
--- a/src/System.Drawing.Common/src/Unix/System.Drawing/Bitmap.cs
+++ b/src/System.Drawing.Common/src/System/Drawing/Bitmap.Unix.cs
@@ -71,9 +71,6 @@ namespace System.Drawing
// (when using MS GDI+ and IStream we must ensure the stream stays alive for all the life of the Image)
internal Bitmap(IntPtr ptr, Stream stream)
{
- // under Win32 stream is owned by SD/GDI+ code
- if (GDIPlus.RunningOnWindows())
- this.stream = stream;
nativeObject = ptr;
}
@@ -87,7 +84,7 @@ namespace System.Drawing
throw new ArgumentNullException("g");
IntPtr bmp;
- Status s = SafeNativeMethods.Gdip.GdipCreateBitmapFromGraphics(width, height, g.nativeObject, out bmp);
+ int s = SafeNativeMethods.Gdip.GdipCreateBitmapFromGraphics(width, height, g.nativeObject, out bmp);
SafeNativeMethods.Gdip.CheckStatus(s);
nativeObject = bmp;
}
@@ -95,7 +92,7 @@ namespace System.Drawing
public Bitmap(int width, int height, PixelFormat format)
{
IntPtr bmp;
- Status s = SafeNativeMethods.Gdip.GdipCreateBitmapFromScan0(width, height, 0, format, IntPtr.Zero, out bmp);
+ int s = SafeNativeMethods.Gdip.GdipCreateBitmapFromScan0(width, height, 0, format, IntPtr.Zero, out bmp);
SafeNativeMethods.Gdip.CheckStatus(s);
nativeObject = bmp;
@@ -121,7 +118,7 @@ namespace System.Drawing
throw new ArgumentNullException("filename");
IntPtr imagePtr;
- Status st;
+ int st;
if (useIcm)
st = SafeNativeMethods.Gdip.GdipCreateBitmapFromFileICM(filename, out imagePtr);
@@ -149,9 +146,6 @@ namespace System.Drawing
}
nativeObject = InitFromStream(s);
- // under Win32 stream is owned by SD/GDI+ code
- if (GDIPlus.RunningOnWindows())
- stream = s;
}
public Bitmap(Image original, int width, int height) : this(width, height, PixelFormat.Format32bppArgb)
@@ -166,7 +160,7 @@ namespace System.Drawing
{
IntPtr bmp;
- Status status = SafeNativeMethods.Gdip.GdipCreateBitmapFromScan0(width, height, stride, format, scan0, out bmp);
+ int status = SafeNativeMethods.Gdip.GdipCreateBitmapFromScan0(width, height, stride, format, scan0, out bmp);
SafeNativeMethods.Gdip.CheckStatus(status);
nativeObject = bmp;
}
@@ -182,7 +176,7 @@ namespace System.Drawing
int argb;
- Status s = SafeNativeMethods.Gdip.GdipBitmapGetPixel(nativeObject, x, y, out argb);
+ int s = SafeNativeMethods.Gdip.GdipBitmapGetPixel(nativeObject, x, y, out argb);
SafeNativeMethods.Gdip.CheckStatus(s);
return Color.FromArgb(argb);
@@ -190,8 +184,8 @@ namespace System.Drawing
public void SetPixel(int x, int y, Color color)
{
- Status s = SafeNativeMethods.Gdip.GdipBitmapSetPixel(nativeObject, x, y, color.ToArgb());
- if (s == Status.InvalidParameter)
+ int s = SafeNativeMethods.Gdip.GdipBitmapSetPixel(nativeObject, x, y, color.ToArgb());
+ if (s == SafeNativeMethods.Gdip.InvalidParameter)
{
// check is done in case of an error only to avoid another
// unmanaged call for normal (successful) calls
@@ -207,7 +201,7 @@ namespace System.Drawing
public Bitmap Clone(Rectangle rect, PixelFormat format)
{
IntPtr bmp;
- Status status = SafeNativeMethods.Gdip.GdipCloneBitmapAreaI(rect.X, rect.Y, rect.Width, rect.Height,
+ int status = SafeNativeMethods.Gdip.GdipCloneBitmapAreaI(rect.X, rect.Y, rect.Width, rect.Height,
format, nativeObject, out bmp);
SafeNativeMethods.Gdip.CheckStatus(status);
return new Bitmap(bmp);
@@ -216,7 +210,7 @@ namespace System.Drawing
public Bitmap Clone(RectangleF rect, PixelFormat format)
{
IntPtr bmp;
- Status status = SafeNativeMethods.Gdip.GdipCloneBitmapArea(rect.X, rect.Y, rect.Width, rect.Height,
+ int status = SafeNativeMethods.Gdip.GdipCloneBitmapArea(rect.X, rect.Y, rect.Width, rect.Height,
format, nativeObject, out bmp);
SafeNativeMethods.Gdip.CheckStatus(status);
return new Bitmap(bmp);
@@ -225,7 +219,7 @@ namespace System.Drawing
public static Bitmap FromHicon(IntPtr hicon)
{
IntPtr bitmap;
- Status status = SafeNativeMethods.Gdip.GdipCreateBitmapFromHICON(hicon, out bitmap);
+ int status = SafeNativeMethods.Gdip.GdipCreateBitmapFromHICON(hicon, out bitmap);
SafeNativeMethods.Gdip.CheckStatus(status);
return new Bitmap(bitmap);
}
@@ -233,7 +227,7 @@ namespace System.Drawing
public static Bitmap FromResource(IntPtr hinstance, string bitmapName) //TODO: Untested
{
IntPtr bitmap;
- Status status = SafeNativeMethods.Gdip.GdipCreateBitmapFromResource(hinstance, bitmapName, out bitmap);
+ int status = SafeNativeMethods.Gdip.GdipCreateBitmapFromResource(hinstance, bitmapName, out bitmap);
SafeNativeMethods.Gdip.CheckStatus(status);
return new Bitmap(bitmap);
}
@@ -249,7 +243,7 @@ namespace System.Drawing
{
IntPtr HandleBmp;
- Status status = SafeNativeMethods.Gdip.GdipCreateHBITMAPFromBitmap(nativeObject, out HandleBmp, background.ToArgb());
+ int status = SafeNativeMethods.Gdip.GdipCreateHBITMAPFromBitmap(nativeObject, out HandleBmp, background.ToArgb());
SafeNativeMethods.Gdip.CheckStatus(status);
return HandleBmp;
@@ -260,7 +254,7 @@ namespace System.Drawing
{
IntPtr HandleIcon;
- Status status = SafeNativeMethods.Gdip.GdipCreateHICONFromBitmap(nativeObject, out HandleIcon);
+ int status = SafeNativeMethods.Gdip.GdipCreateHICONFromBitmap(nativeObject, out HandleIcon);
SafeNativeMethods.Gdip.CheckStatus(status);
return HandleIcon;
@@ -275,7 +269,11 @@ namespace System.Drawing
public
BitmapData LockBits(Rectangle rect, ImageLockMode flags, PixelFormat format, BitmapData bitmapData)
{
- Status status = SafeNativeMethods.Gdip.GdipBitmapLockBits(nativeObject, ref rect, flags, format, bitmapData);
+ int status = SafeNativeMethods.Gdip.GdipBitmapLockBits(nativeObject, ref rect, flags, format, bitmapData);
+ if (status == 7)
+ {
+ status = 8; // libgdiplus has the wrong error code mapping for this state.
+ }
//NOTE: scan0 points to piece of memory allocated in the unmanaged space
SafeNativeMethods.Gdip.CheckStatus(status);
@@ -311,13 +309,13 @@ namespace System.Drawing
public void SetResolution(float xDpi, float yDpi)
{
- Status status = SafeNativeMethods.Gdip.GdipBitmapSetResolution(nativeObject, xDpi, yDpi);
+ int status = SafeNativeMethods.Gdip.GdipBitmapSetResolution(nativeObject, xDpi, yDpi);
SafeNativeMethods.Gdip.CheckStatus(status);
}
public void UnlockBits(BitmapData bitmapdata)
{
- Status status = SafeNativeMethods.Gdip.GdipBitmapUnlockBits(nativeObject, bitmapdata);
+ int status = SafeNativeMethods.Gdip.GdipBitmapUnlockBits(nativeObject, bitmapdata);
SafeNativeMethods.Gdip.CheckStatus(status);
}
}
diff --git a/src/System.Drawing.Common/src/System/Drawing/Bitmap.cs b/src/System.Drawing.Common/src/System/Drawing/Bitmap.Windows.cs
index 3b58ff245c..3b58ff245c 100644
--- a/src/System.Drawing.Common/src/System/Drawing/Bitmap.cs
+++ b/src/System.Drawing.Common/src/System/Drawing/Bitmap.Windows.cs
diff --git a/src/System.Drawing.Common/src/Unix/System.Drawing/BufferedGraphics.cs b/src/System.Drawing.Common/src/System/Drawing/BufferedGraphics.Unix.cs
index 298aa8ea98..298aa8ea98 100644
--- a/src/System.Drawing.Common/src/Unix/System.Drawing/BufferedGraphics.cs
+++ b/src/System.Drawing.Common/src/System/Drawing/BufferedGraphics.Unix.cs
diff --git a/src/System.Drawing.Common/src/System/Drawing/BufferedGraphics.cs b/src/System.Drawing.Common/src/System/Drawing/BufferedGraphics.Windows.cs
index c6068fb65b..c6068fb65b 100644
--- a/src/System.Drawing.Common/src/System/Drawing/BufferedGraphics.cs
+++ b/src/System.Drawing.Common/src/System/Drawing/BufferedGraphics.Windows.cs
diff --git a/src/System.Drawing.Common/src/Unix/System.Drawing/BufferedGraphicsContext.cs b/src/System.Drawing.Common/src/System/Drawing/BufferedGraphicsContext.Unix.cs
index de0d434af8..de0d434af8 100644
--- a/src/System.Drawing.Common/src/Unix/System.Drawing/BufferedGraphicsContext.cs
+++ b/src/System.Drawing.Common/src/System/Drawing/BufferedGraphicsContext.Unix.cs
diff --git a/src/System.Drawing.Common/src/System/Drawing/BufferedGraphicsContext.cs b/src/System.Drawing.Common/src/System/Drawing/BufferedGraphicsContext.Windows.cs
index 6d53c5db87..6d53c5db87 100644
--- a/src/System.Drawing.Common/src/System/Drawing/BufferedGraphicsContext.cs
+++ b/src/System.Drawing.Common/src/System/Drawing/BufferedGraphicsContext.Windows.cs
diff --git a/src/System.Drawing.Common/src/Unix/System.Drawing/BufferedGraphicsManager.cs b/src/System.Drawing.Common/src/System/Drawing/BufferedGraphicsManager.Unix.cs
index 60f9abc8d9..60f9abc8d9 100644
--- a/src/System.Drawing.Common/src/Unix/System.Drawing/BufferedGraphicsManager.cs
+++ b/src/System.Drawing.Common/src/System/Drawing/BufferedGraphicsManager.Unix.cs
diff --git a/src/System.Drawing.Common/src/System/Drawing/BufferedGraphicsManager.cs b/src/System.Drawing.Common/src/System/Drawing/BufferedGraphicsManager.Windows.cs
index cef23d976b..cef23d976b 100644
--- a/src/System.Drawing.Common/src/System/Drawing/BufferedGraphicsManager.cs
+++ b/src/System.Drawing.Common/src/System/Drawing/BufferedGraphicsManager.Windows.cs
diff --git a/src/System.Drawing.Common/src/Unix/System.Drawing.Drawing2D/GraphicsPath.cs b/src/System.Drawing.Common/src/System/Drawing/Drawing2D/GraphicsPath.Unix.cs
index 20ef190946..1260c98a5c 100644
--- a/src/System.Drawing.Common/src/Unix/System.Drawing.Drawing2D/GraphicsPath.cs
+++ b/src/System.Drawing.Common/src/System/Drawing/Drawing2D/GraphicsPath.Unix.cs
@@ -50,13 +50,13 @@ namespace System.Drawing.Drawing2D
public GraphicsPath()
{
- Status status = SafeNativeMethods.Gdip.GdipCreatePath(FillMode.Alternate, out nativePath);
+ int status = SafeNativeMethods.Gdip.GdipCreatePath(FillMode.Alternate, out nativePath);
SafeNativeMethods.Gdip.CheckStatus(status);
}
public GraphicsPath(FillMode fillMode)
{
- Status status = SafeNativeMethods.Gdip.GdipCreatePath(fillMode, out nativePath);
+ int status = SafeNativeMethods.Gdip.GdipCreatePath(fillMode, out nativePath);
SafeNativeMethods.Gdip.CheckStatus(status);
}
@@ -77,7 +77,7 @@ namespace System.Drawing.Drawing2D
if (pts.Length != types.Length)
throw new ArgumentException("Invalid parameter passed. Number of points and types must be same.");
- Status status = SafeNativeMethods.Gdip.GdipCreatePath2I(pts, types, pts.Length, fillMode, out nativePath);
+ int status = SafeNativeMethods.Gdip.GdipCreatePath2I(pts, types, pts.Length, fillMode, out nativePath);
SafeNativeMethods.Gdip.CheckStatus(status);
}
@@ -88,7 +88,7 @@ namespace System.Drawing.Drawing2D
if (pts.Length != types.Length)
throw new ArgumentException("Invalid parameter passed. Number of points and types must be same.");
- Status status = SafeNativeMethods.Gdip.GdipCreatePath2(pts, types, pts.Length, fillMode, out nativePath);
+ int status = SafeNativeMethods.Gdip.GdipCreatePath2(pts, types, pts.Length, fillMode, out nativePath);
SafeNativeMethods.Gdip.CheckStatus(status);
}
@@ -96,7 +96,7 @@ namespace System.Drawing.Drawing2D
{
IntPtr clone;
- Status status = SafeNativeMethods.Gdip.GdipClonePath(nativePath, out clone);
+ int status = SafeNativeMethods.Gdip.GdipClonePath(nativePath, out clone);
SafeNativeMethods.Gdip.CheckStatus(status);
return new GraphicsPath(clone);
@@ -115,7 +115,7 @@ namespace System.Drawing.Drawing2D
void Dispose(bool disposing)
{
- Status status;
+ int status;
if (nativePath != IntPtr.Zero)
{
status = SafeNativeMethods.Gdip.GdipDeletePath(nativePath);
@@ -130,7 +130,7 @@ namespace System.Drawing.Drawing2D
get
{
FillMode mode;
- Status status = SafeNativeMethods.Gdip.GdipGetPathFillMode(nativePath, out mode);
+ int status = SafeNativeMethods.Gdip.GdipGetPathFillMode(nativePath, out mode);
SafeNativeMethods.Gdip.CheckStatus(status);
return mode;
@@ -140,7 +140,7 @@ namespace System.Drawing.Drawing2D
if ((value < FillMode.Alternate) || (value > FillMode.Winding))
throw new InvalidEnumArgumentException("FillMode", (int)value, typeof(FillMode));
- Status status = SafeNativeMethods.Gdip.GdipSetPathFillMode(nativePath, value);
+ int status = SafeNativeMethods.Gdip.GdipSetPathFillMode(nativePath, value);
SafeNativeMethods.Gdip.CheckStatus(status);
}
}
@@ -150,7 +150,7 @@ namespace System.Drawing.Drawing2D
get
{
int count;
- Status status = SafeNativeMethods.Gdip.GdipGetPointCount(nativePath, out count);
+ int status = SafeNativeMethods.Gdip.GdipGetPointCount(nativePath, out count);
SafeNativeMethods.Gdip.CheckStatus(status);
PointF[] points = new PointF[count];
@@ -179,7 +179,7 @@ namespace System.Drawing.Drawing2D
get
{
int count;
- Status status = SafeNativeMethods.Gdip.GdipGetPointCount(nativePath, out count);
+ int status = SafeNativeMethods.Gdip.GdipGetPointCount(nativePath, out count);
SafeNativeMethods.Gdip.CheckStatus(status);
if (count == 0)
throw new ArgumentException("PathPoints");
@@ -197,7 +197,7 @@ namespace System.Drawing.Drawing2D
get
{
int count;
- Status status = SafeNativeMethods.Gdip.GdipGetPointCount(nativePath, out count);
+ int status = SafeNativeMethods.Gdip.GdipGetPointCount(nativePath, out count);
SafeNativeMethods.Gdip.CheckStatus(status);
if (count == 0)
throw new ArgumentException("PathTypes");
@@ -215,7 +215,7 @@ namespace System.Drawing.Drawing2D
get
{
int count;
- Status status = SafeNativeMethods.Gdip.GdipGetPointCount(nativePath, out count);
+ int status = SafeNativeMethods.Gdip.GdipGetPointCount(nativePath, out count);
SafeNativeMethods.Gdip.CheckStatus(status);
return count;
@@ -239,25 +239,25 @@ namespace System.Drawing.Drawing2D
//
public void AddArc(Rectangle rect, float startAngle, float sweepAngle)
{
- Status status = SafeNativeMethods.Gdip.GdipAddPathArcI(nativePath, rect.X, rect.Y, rect.Width, rect.Height, startAngle, sweepAngle);
+ int status = SafeNativeMethods.Gdip.GdipAddPathArcI(nativePath, rect.X, rect.Y, rect.Width, rect.Height, startAngle, sweepAngle);
SafeNativeMethods.Gdip.CheckStatus(status);
}
public void AddArc(RectangleF rect, float startAngle, float sweepAngle)
{
- Status status = SafeNativeMethods.Gdip.GdipAddPathArc(nativePath, rect.X, rect.Y, rect.Width, rect.Height, startAngle, sweepAngle);
+ int status = SafeNativeMethods.Gdip.GdipAddPathArc(nativePath, rect.X, rect.Y, rect.Width, rect.Height, startAngle, sweepAngle);
SafeNativeMethods.Gdip.CheckStatus(status);
}
public void AddArc(int x, int y, int width, int height, float startAngle, float sweepAngle)
{
- Status status = SafeNativeMethods.Gdip.GdipAddPathArcI(nativePath, x, y, width, height, startAngle, sweepAngle);
+ int status = SafeNativeMethods.Gdip.GdipAddPathArcI(nativePath, x, y, width, height, startAngle, sweepAngle);
SafeNativeMethods.Gdip.CheckStatus(status);
}
public void AddArc(float x, float y, float width, float height, float startAngle, float sweepAngle)
{
- Status status = SafeNativeMethods.Gdip.GdipAddPathArc(nativePath, x, y, width, height, startAngle, sweepAngle);
+ int status = SafeNativeMethods.Gdip.GdipAddPathArc(nativePath, x, y, width, height, startAngle, sweepAngle);
SafeNativeMethods.Gdip.CheckStatus(status);
}
@@ -266,7 +266,7 @@ namespace System.Drawing.Drawing2D
//
public void AddBezier(Point pt1, Point pt2, Point pt3, Point pt4)
{
- Status status = SafeNativeMethods.Gdip.GdipAddPathBezierI(nativePath, pt1.X, pt1.Y,
+ int status = SafeNativeMethods.Gdip.GdipAddPathBezierI(nativePath, pt1.X, pt1.Y,
pt2.X, pt2.Y, pt3.X, pt3.Y, pt4.X, pt4.Y);
SafeNativeMethods.Gdip.CheckStatus(status);
@@ -274,7 +274,7 @@ namespace System.Drawing.Drawing2D
public void AddBezier(PointF pt1, PointF pt2, PointF pt3, PointF pt4)
{
- Status status = SafeNativeMethods.Gdip.GdipAddPathBezier(nativePath, pt1.X, pt1.Y,
+ int status = SafeNativeMethods.Gdip.GdipAddPathBezier(nativePath, pt1.X, pt1.Y,
pt2.X, pt2.Y, pt3.X, pt3.Y, pt4.X, pt4.Y);
SafeNativeMethods.Gdip.CheckStatus(status);
@@ -282,13 +282,13 @@ namespace System.Drawing.Drawing2D
public void AddBezier(int x1, int y1, int x2, int y2, int x3, int y3, int x4, int y4)
{
- Status status = SafeNativeMethods.Gdip.GdipAddPathBezierI(nativePath, x1, y1, x2, y2, x3, y3, x4, y4);
+ int status = SafeNativeMethods.Gdip.GdipAddPathBezierI(nativePath, x1, y1, x2, y2, x3, y3, x4, y4);
SafeNativeMethods.Gdip.CheckStatus(status);
}
public void AddBezier(float x1, float y1, float x2, float y2, float x3, float y3, float x4, float y4)
{
- Status status = SafeNativeMethods.Gdip.GdipAddPathBezier(nativePath, x1, y1, x2, y2, x3, y3, x4, y4);
+ int status = SafeNativeMethods.Gdip.GdipAddPathBezier(nativePath, x1, y1, x2, y2, x3, y3, x4, y4);
SafeNativeMethods.Gdip.CheckStatus(status);
}
@@ -299,7 +299,7 @@ namespace System.Drawing.Drawing2D
{
if (points == null)
throw new ArgumentNullException("points");
- Status status = SafeNativeMethods.Gdip.GdipAddPathBeziersI(nativePath, points, points.Length);
+ int status = SafeNativeMethods.Gdip.GdipAddPathBeziersI(nativePath, points, points.Length);
SafeNativeMethods.Gdip.CheckStatus(status);
}
@@ -307,7 +307,7 @@ namespace System.Drawing.Drawing2D
{
if (points == null)
throw new ArgumentNullException("points");
- Status status = SafeNativeMethods.Gdip.GdipAddPathBeziers(nativePath, points, points.Length);
+ int status = SafeNativeMethods.Gdip.GdipAddPathBeziers(nativePath, points, points.Length);
SafeNativeMethods.Gdip.CheckStatus(status);
}
@@ -316,25 +316,25 @@ namespace System.Drawing.Drawing2D
//
public void AddEllipse(RectangleF rect)
{
- Status status = SafeNativeMethods.Gdip.GdipAddPathEllipse(nativePath, rect.X, rect.Y, rect.Width, rect.Height);
+ int status = SafeNativeMethods.Gdip.GdipAddPathEllipse(nativePath, rect.X, rect.Y, rect.Width, rect.Height);
SafeNativeMethods.Gdip.CheckStatus(status);
}
public void AddEllipse(float x, float y, float width, float height)
{
- Status status = SafeNativeMethods.Gdip.GdipAddPathEllipse(nativePath, x, y, width, height);
+ int status = SafeNativeMethods.Gdip.GdipAddPathEllipse(nativePath, x, y, width, height);
SafeNativeMethods.Gdip.CheckStatus(status);
}
public void AddEllipse(Rectangle rect)
{
- Status status = SafeNativeMethods.Gdip.GdipAddPathEllipseI(nativePath, rect.X, rect.Y, rect.Width, rect.Height);
+ int status = SafeNativeMethods.Gdip.GdipAddPathEllipseI(nativePath, rect.X, rect.Y, rect.Width, rect.Height);
SafeNativeMethods.Gdip.CheckStatus(status);
}
public void AddEllipse(int x, int y, int width, int height)
{
- Status status = SafeNativeMethods.Gdip.GdipAddPathEllipseI(nativePath, x, y, width, height);
+ int status = SafeNativeMethods.Gdip.GdipAddPathEllipseI(nativePath, x, y, width, height);
SafeNativeMethods.Gdip.CheckStatus(status);
}
@@ -344,13 +344,13 @@ namespace System.Drawing.Drawing2D
//
public void AddLine(Point pt1, Point pt2)
{
- Status status = SafeNativeMethods.Gdip.GdipAddPathLineI(nativePath, pt1.X, pt1.Y, pt2.X, pt2.Y);
+ int status = SafeNativeMethods.Gdip.GdipAddPathLineI(nativePath, pt1.X, pt1.Y, pt2.X, pt2.Y);
SafeNativeMethods.Gdip.CheckStatus(status);
}
public void AddLine(PointF pt1, PointF pt2)
{
- Status status = SafeNativeMethods.Gdip.GdipAddPathLine(nativePath, pt1.X, pt1.Y, pt2.X,
+ int status = SafeNativeMethods.Gdip.GdipAddPathLine(nativePath, pt1.X, pt1.Y, pt2.X,
pt2.Y);
SafeNativeMethods.Gdip.CheckStatus(status);
@@ -358,13 +358,13 @@ namespace System.Drawing.Drawing2D
public void AddLine(int x1, int y1, int x2, int y2)
{
- Status status = SafeNativeMethods.Gdip.GdipAddPathLineI(nativePath, x1, y1, x2, y2);
+ int status = SafeNativeMethods.Gdip.GdipAddPathLineI(nativePath, x1, y1, x2, y2);
SafeNativeMethods.Gdip.CheckStatus(status);
}
public void AddLine(float x1, float y1, float x2, float y2)
{
- Status status = SafeNativeMethods.Gdip.GdipAddPathLine(nativePath, x1, y1, x2,
+ int status = SafeNativeMethods.Gdip.GdipAddPathLine(nativePath, x1, y1, x2,
y2);
SafeNativeMethods.Gdip.CheckStatus(status);
@@ -380,7 +380,7 @@ namespace System.Drawing.Drawing2D
if (points.Length == 0)
throw new ArgumentException("points");
- Status status = SafeNativeMethods.Gdip.GdipAddPathLine2I(nativePath, points, points.Length);
+ int status = SafeNativeMethods.Gdip.GdipAddPathLine2I(nativePath, points, points.Length);
SafeNativeMethods.Gdip.CheckStatus(status);
}
@@ -391,7 +391,7 @@ namespace System.Drawing.Drawing2D
if (points.Length == 0)
throw new ArgumentException("points");
- Status status = SafeNativeMethods.Gdip.GdipAddPathLine2(nativePath, points, points.Length);
+ int status = SafeNativeMethods.Gdip.GdipAddPathLine2(nativePath, points, points.Length);
SafeNativeMethods.Gdip.CheckStatus(status);
}
@@ -400,20 +400,20 @@ namespace System.Drawing.Drawing2D
//
public void AddPie(Rectangle rect, float startAngle, float sweepAngle)
{
- Status status = SafeNativeMethods.Gdip.GdipAddPathPie(
+ int status = SafeNativeMethods.Gdip.GdipAddPathPie(
nativePath, rect.X, rect.Y, rect.Width, rect.Height, startAngle, sweepAngle);
SafeNativeMethods.Gdip.CheckStatus(status);
}
public void AddPie(int x, int y, int width, int height, float startAngle, float sweepAngle)
{
- Status status = SafeNativeMethods.Gdip.GdipAddPathPieI(nativePath, x, y, width, height, startAngle, sweepAngle);
+ int status = SafeNativeMethods.Gdip.GdipAddPathPieI(nativePath, x, y, width, height, startAngle, sweepAngle);
SafeNativeMethods.Gdip.CheckStatus(status);
}
public void AddPie(float x, float y, float width, float height, float startAngle, float sweepAngle)
{
- Status status = SafeNativeMethods.Gdip.GdipAddPathPie(nativePath, x, y, width, height, startAngle, sweepAngle);
+ int status = SafeNativeMethods.Gdip.GdipAddPathPie(nativePath, x, y, width, height, startAngle, sweepAngle);
SafeNativeMethods.Gdip.CheckStatus(status);
}
@@ -425,7 +425,7 @@ namespace System.Drawing.Drawing2D
if (points == null)
throw new ArgumentNullException("points");
- Status status = SafeNativeMethods.Gdip.GdipAddPathPolygonI(nativePath, points, points.Length);
+ int status = SafeNativeMethods.Gdip.GdipAddPathPolygonI(nativePath, points, points.Length);
SafeNativeMethods.Gdip.CheckStatus(status);
}
@@ -434,7 +434,7 @@ namespace System.Drawing.Drawing2D
if (points == null)
throw new ArgumentNullException("points");
- Status status = SafeNativeMethods.Gdip.GdipAddPathPolygon(nativePath, points, points.Length);
+ int status = SafeNativeMethods.Gdip.GdipAddPathPolygon(nativePath, points, points.Length);
SafeNativeMethods.Gdip.CheckStatus(status);
}
@@ -443,13 +443,13 @@ namespace System.Drawing.Drawing2D
//
public void AddRectangle(Rectangle rect)
{
- Status status = SafeNativeMethods.Gdip.GdipAddPathRectangleI(nativePath, rect.X, rect.Y, rect.Width, rect.Height);
+ int status = SafeNativeMethods.Gdip.GdipAddPathRectangleI(nativePath, rect.X, rect.Y, rect.Width, rect.Height);
SafeNativeMethods.Gdip.CheckStatus(status);
}
public void AddRectangle(RectangleF rect)
{
- Status status = SafeNativeMethods.Gdip.GdipAddPathRectangle(nativePath, rect.X, rect.Y, rect.Width, rect.Height);
+ int status = SafeNativeMethods.Gdip.GdipAddPathRectangle(nativePath, rect.X, rect.Y, rect.Width, rect.Height);
SafeNativeMethods.Gdip.CheckStatus(status);
}
@@ -463,7 +463,7 @@ namespace System.Drawing.Drawing2D
if (rects.Length == 0)
throw new ArgumentException("rects");
- Status status = SafeNativeMethods.Gdip.GdipAddPathRectanglesI(nativePath, rects, rects.Length);
+ int status = SafeNativeMethods.Gdip.GdipAddPathRectanglesI(nativePath, rects, rects.Length);
SafeNativeMethods.Gdip.CheckStatus(status);
}
@@ -474,7 +474,7 @@ namespace System.Drawing.Drawing2D
if (rects.Length == 0)
throw new ArgumentException("rects");
- Status status = SafeNativeMethods.Gdip.GdipAddPathRectangles(nativePath, rects, rects.Length);
+ int status = SafeNativeMethods.Gdip.GdipAddPathRectangles(nativePath, rects, rects.Length);
SafeNativeMethods.Gdip.CheckStatus(status);
}
@@ -486,14 +486,14 @@ namespace System.Drawing.Drawing2D
if (addingPath == null)
throw new ArgumentNullException("addingPath");
- Status status = SafeNativeMethods.Gdip.GdipAddPathPath(nativePath, addingPath.nativePath, connect);
+ int status = SafeNativeMethods.Gdip.GdipAddPathPath(nativePath, addingPath.nativePath, connect);
SafeNativeMethods.Gdip.CheckStatus(status);
}
public PointF GetLastPoint()
{
PointF pt;
- Status status = SafeNativeMethods.Gdip.GdipGetPathLastPoint(nativePath, out pt);
+ int status = SafeNativeMethods.Gdip.GdipGetPathLastPoint(nativePath, out pt);
SafeNativeMethods.Gdip.CheckStatus(status);
return pt;
@@ -507,7 +507,7 @@ namespace System.Drawing.Drawing2D
if (points == null)
throw new ArgumentNullException("points");
- Status status = SafeNativeMethods.Gdip.GdipAddPathClosedCurveI(nativePath, points, points.Length);
+ int status = SafeNativeMethods.Gdip.GdipAddPathClosedCurveI(nativePath, points, points.Length);
SafeNativeMethods.Gdip.CheckStatus(status);
}
@@ -516,7 +516,7 @@ namespace System.Drawing.Drawing2D
if (points == null)
throw new ArgumentNullException("points");
- Status status = SafeNativeMethods.Gdip.GdipAddPathClosedCurve(nativePath, points, points.Length);
+ int status = SafeNativeMethods.Gdip.GdipAddPathClosedCurve(nativePath, points, points.Length);
SafeNativeMethods.Gdip.CheckStatus(status);
}
@@ -525,7 +525,7 @@ namespace System.Drawing.Drawing2D
if (points == null)
throw new ArgumentNullException("points");
- Status status = SafeNativeMethods.Gdip.GdipAddPathClosedCurve2I(nativePath, points, points.Length, tension);
+ int status = SafeNativeMethods.Gdip.GdipAddPathClosedCurve2I(nativePath, points, points.Length, tension);
SafeNativeMethods.Gdip.CheckStatus(status);
}
@@ -534,7 +534,7 @@ namespace System.Drawing.Drawing2D
if (points == null)
throw new ArgumentNullException("points");
- Status status = SafeNativeMethods.Gdip.GdipAddPathClosedCurve2(nativePath, points, points.Length, tension);
+ int status = SafeNativeMethods.Gdip.GdipAddPathClosedCurve2(nativePath, points, points.Length, tension);
SafeNativeMethods.Gdip.CheckStatus(status);
}
@@ -546,7 +546,7 @@ namespace System.Drawing.Drawing2D
if (points == null)
throw new ArgumentNullException("points");
- Status status = SafeNativeMethods.Gdip.GdipAddPathCurveI(nativePath, points, points.Length);
+ int status = SafeNativeMethods.Gdip.GdipAddPathCurveI(nativePath, points, points.Length);
SafeNativeMethods.Gdip.CheckStatus(status);
}
@@ -555,7 +555,7 @@ namespace System.Drawing.Drawing2D
if (points == null)
throw new ArgumentNullException("points");
- Status status = SafeNativeMethods.Gdip.GdipAddPathCurve(nativePath, points, points.Length);
+ int status = SafeNativeMethods.Gdip.GdipAddPathCurve(nativePath, points, points.Length);
SafeNativeMethods.Gdip.CheckStatus(status);
}
@@ -564,7 +564,7 @@ namespace System.Drawing.Drawing2D
if (points == null)
throw new ArgumentNullException("points");
- Status status = SafeNativeMethods.Gdip.GdipAddPathCurve2I(nativePath, points, points.Length, tension);
+ int status = SafeNativeMethods.Gdip.GdipAddPathCurve2I(nativePath, points, points.Length, tension);
SafeNativeMethods.Gdip.CheckStatus(status);
}
@@ -573,7 +573,7 @@ namespace System.Drawing.Drawing2D
if (points == null)
throw new ArgumentNullException("points");
- Status status = SafeNativeMethods.Gdip.GdipAddPathCurve2(nativePath, points, points.Length, tension);
+ int status = SafeNativeMethods.Gdip.GdipAddPathCurve2(nativePath, points, points.Length, tension);
SafeNativeMethods.Gdip.CheckStatus(status);
}
@@ -582,7 +582,7 @@ namespace System.Drawing.Drawing2D
if (points == null)
throw new ArgumentNullException("points");
- Status status = SafeNativeMethods.Gdip.GdipAddPathCurve3I(nativePath, points, points.Length,
+ int status = SafeNativeMethods.Gdip.GdipAddPathCurve3I(nativePath, points, points.Length,
offset, numberOfSegments, tension);
SafeNativeMethods.Gdip.CheckStatus(status);
@@ -593,7 +593,7 @@ namespace System.Drawing.Drawing2D
if (points == null)
throw new ArgumentNullException("points");
- Status status = SafeNativeMethods.Gdip.GdipAddPathCurve3(nativePath, points, points.Length,
+ int status = SafeNativeMethods.Gdip.GdipAddPathCurve3(nativePath, points, points.Length,
offset, numberOfSegments, tension);
SafeNativeMethods.Gdip.CheckStatus(status);
@@ -601,13 +601,13 @@ namespace System.Drawing.Drawing2D
public void Reset()
{
- Status status = SafeNativeMethods.Gdip.GdipResetPath(nativePath);
+ int status = SafeNativeMethods.Gdip.GdipResetPath(nativePath);
SafeNativeMethods.Gdip.CheckStatus(status);
}
public void Reverse()
{
- Status status = SafeNativeMethods.Gdip.GdipReversePath(nativePath);
+ int status = SafeNativeMethods.Gdip.GdipReversePath(nativePath);
SafeNativeMethods.Gdip.CheckStatus(status);
}
@@ -616,7 +616,7 @@ namespace System.Drawing.Drawing2D
if (matrix == null)
throw new ArgumentNullException("matrix");
- Status status = SafeNativeMethods.Gdip.GdipTransformPath(nativePath, matrix.nativeMatrix);
+ int status = SafeNativeMethods.Gdip.GdipTransformPath(nativePath, matrix.nativeMatrix);
SafeNativeMethods.Gdip.CheckStatus(status);
}
@@ -646,7 +646,7 @@ namespace System.Drawing.Drawing2D
IntPtr sformat = (format == null) ? IntPtr.Zero : format.nativeFormat;
// note: the NullReferenceException on s.Length is the expected (MS) exception
- Status status = SafeNativeMethods.Gdip.GdipAddPathStringI(nativePath, s, s.Length, family.NativeFamily, style, emSize, ref layoutRect, sformat);
+ int status = SafeNativeMethods.Gdip.GdipAddPathStringI(nativePath, s, s.Length, family.NativeFamily, style, emSize, ref layoutRect, sformat);
SafeNativeMethods.Gdip.CheckStatus(status);
}
@@ -658,27 +658,27 @@ namespace System.Drawing.Drawing2D
IntPtr sformat = (format == null) ? IntPtr.Zero : format.nativeFormat;
// note: the NullReferenceException on s.Length is the expected (MS) exception
- Status status = SafeNativeMethods.Gdip.GdipAddPathString(nativePath, s, s.Length, family.NativeFamily, style, emSize, ref layoutRect, sformat);
+ int status = SafeNativeMethods.Gdip.GdipAddPathString(nativePath, s, s.Length, family.NativeFamily, style, emSize, ref layoutRect, sformat);
SafeNativeMethods.Gdip.CheckStatus(status);
}
public void ClearMarkers()
{
- Status s = SafeNativeMethods.Gdip.GdipClearPathMarkers(nativePath);
+ int s = SafeNativeMethods.Gdip.GdipClearPathMarkers(nativePath);
SafeNativeMethods.Gdip.CheckStatus(s);
}
public void CloseAllFigures()
{
- Status s = SafeNativeMethods.Gdip.GdipClosePathFigures(nativePath);
+ int s = SafeNativeMethods.Gdip.GdipClosePathFigures(nativePath);
SafeNativeMethods.Gdip.CheckStatus(s);
}
public void CloseFigure()
{
- Status s = SafeNativeMethods.Gdip.GdipClosePathFigure(nativePath);
+ int s = SafeNativeMethods.Gdip.GdipClosePathFigure(nativePath);
SafeNativeMethods.Gdip.CheckStatus(s);
}
@@ -696,7 +696,7 @@ namespace System.Drawing.Drawing2D
public void Flatten(Matrix matrix, float flatness)
{
IntPtr m = (matrix == null) ? IntPtr.Zero : matrix.nativeMatrix;
- Status status = SafeNativeMethods.Gdip.GdipFlattenPath(nativePath, m, flatness);
+ int status = SafeNativeMethods.Gdip.GdipFlattenPath(nativePath, m, flatness);
SafeNativeMethods.Gdip.CheckStatus(status);
}
@@ -717,7 +717,7 @@ namespace System.Drawing.Drawing2D
IntPtr m = (matrix == null) ? IntPtr.Zero : matrix.nativeMatrix;
IntPtr p = (pen == null) ? IntPtr.Zero : pen.NativePen;
- Status s = SafeNativeMethods.Gdip.GdipGetPathWorldBounds(nativePath, out retval, m, p);
+ int s = SafeNativeMethods.Gdip.GdipGetPathWorldBounds(nativePath, out retval, m, p);
SafeNativeMethods.Gdip.CheckStatus(s);
@@ -762,7 +762,7 @@ namespace System.Drawing.Drawing2D
bool result;
IntPtr g = (graphics == null) ? IntPtr.Zero : graphics.nativeObject;
- Status s = SafeNativeMethods.Gdip.GdipIsOutlineVisiblePathPointI(nativePath, x, y, pen.NativePen, g, out result);
+ int s = SafeNativeMethods.Gdip.GdipIsOutlineVisiblePathPointI(nativePath, x, y, pen.NativePen, g, out result);
SafeNativeMethods.Gdip.CheckStatus(s);
return result;
@@ -776,7 +776,7 @@ namespace System.Drawing.Drawing2D
bool result;
IntPtr g = (graphics == null) ? IntPtr.Zero : graphics.nativeObject;
- Status s = SafeNativeMethods.Gdip.GdipIsOutlineVisiblePathPoint(nativePath, x, y, pen.NativePen, g, out result);
+ int s = SafeNativeMethods.Gdip.GdipIsOutlineVisiblePathPoint(nativePath, x, y, pen.NativePen, g, out result);
SafeNativeMethods.Gdip.CheckStatus(s);
return result;
@@ -818,7 +818,7 @@ namespace System.Drawing.Drawing2D
IntPtr g = (graphics == null) ? IntPtr.Zero : graphics.nativeObject;
- Status s = SafeNativeMethods.Gdip.GdipIsVisiblePathPointI(nativePath, x, y, g, out retval);
+ int s = SafeNativeMethods.Gdip.GdipIsVisiblePathPointI(nativePath, x, y, g, out retval);
SafeNativeMethods.Gdip.CheckStatus(s);
@@ -831,7 +831,7 @@ namespace System.Drawing.Drawing2D
IntPtr g = (graphics == null) ? IntPtr.Zero : graphics.nativeObject;
- Status s = SafeNativeMethods.Gdip.GdipIsVisiblePathPoint(nativePath, x, y, g, out retval);
+ int s = SafeNativeMethods.Gdip.GdipIsVisiblePathPoint(nativePath, x, y, g, out retval);
SafeNativeMethods.Gdip.CheckStatus(s);
@@ -840,14 +840,14 @@ namespace System.Drawing.Drawing2D
public void SetMarkers()
{
- Status s = SafeNativeMethods.Gdip.GdipSetPathMarker(nativePath);
+ int s = SafeNativeMethods.Gdip.GdipSetPathMarker(nativePath);
SafeNativeMethods.Gdip.CheckStatus(s);
}
public void StartFigure()
{
- Status s = SafeNativeMethods.Gdip.GdipStartPathFigure(nativePath);
+ int s = SafeNativeMethods.Gdip.GdipStartPathFigure(nativePath);
SafeNativeMethods.Gdip.CheckStatus(s);
}
@@ -878,7 +878,7 @@ namespace System.Drawing.Drawing2D
IntPtr m = (matrix == null) ? IntPtr.Zero : matrix.nativeMatrix;
- Status s = SafeNativeMethods.Gdip.GdipWarpPath(nativePath, m, destPoints, destPoints.Length,
+ int s = SafeNativeMethods.Gdip.GdipWarpPath(nativePath, m, destPoints, destPoints.Length,
srcRect.X, srcRect.Y, srcRect.Width, srcRect.Height, warpMode, flatness);
SafeNativeMethods.Gdip.CheckStatus(s);
@@ -905,7 +905,7 @@ namespace System.Drawing.Drawing2D
return;
IntPtr m = (matrix == null) ? IntPtr.Zero : matrix.nativeMatrix;
- Status s = SafeNativeMethods.Gdip.GdipWidenPath(nativePath, pen.NativePen, m, flatness);
+ int s = SafeNativeMethods.Gdip.GdipWidenPath(nativePath, pen.NativePen, m, flatness);
SafeNativeMethods.Gdip.CheckStatus(s);
}
}
diff --git a/src/System.Drawing.Common/src/System/Drawing/Drawing2D/GraphicsPath.cs b/src/System.Drawing.Common/src/System/Drawing/Drawing2D/GraphicsPath.Windows.cs
index b819ec198c..b819ec198c 100644
--- a/src/System.Drawing.Common/src/System/Drawing/Drawing2D/GraphicsPath.cs
+++ b/src/System.Drawing.Common/src/System/Drawing/Drawing2D/GraphicsPath.Windows.cs
diff --git a/src/System.Drawing.Common/src/System/Drawing/Drawing2D/HatchBrush.cs b/src/System.Drawing.Common/src/System/Drawing/Drawing2D/HatchBrush.cs
index 68e539988d..43ea6829e2 100644
--- a/src/System.Drawing.Common/src/System/Drawing/Drawing2D/HatchBrush.cs
+++ b/src/System.Drawing.Common/src/System/Drawing/Drawing2D/HatchBrush.cs
@@ -15,6 +15,11 @@ namespace System.Drawing.Drawing2D
public HatchBrush(HatchStyle hatchstyle, Color foreColor, Color backColor)
{
+ if (hatchstyle < HatchStyle.Min || hatchstyle > HatchStyle.SolidDiamond)
+ {
+ throw new ArgumentException(SR.Format(SR.InvalidEnumArgument, nameof(hatchstyle), hatchstyle, nameof(HatchStyle)), nameof(hatchstyle));
+ }
+
IntPtr nativeBrush;
int status = SafeNativeMethods.Gdip.GdipCreateHatchBrush(unchecked((int)hatchstyle), foreColor.ToArgb(), backColor.ToArgb(), out nativeBrush);
SafeNativeMethods.Gdip.CheckStatus(status);
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 cf158ee977..162a4735ec 100644
--- a/src/System.Drawing.Common/src/System/Drawing/Drawing2D/LinearGradientBrush.cs
+++ b/src/System.Drawing.Common/src/System/Drawing/Drawing2D/LinearGradientBrush.cs
@@ -335,9 +335,14 @@ namespace System.Drawing.Drawing2D
public void SetSigmaBellShape(float focus, float scale)
{
- if (focus < 0 || focus > 1 || scale < 0 || scale > 1)
+ if (focus < 0 || focus > 1)
{
- throw new ArgumentException(SR.Format(SR.GdiplusInvalidParameter));
+ throw new ArgumentException(SR.Format(SR.GdiplusInvalidParameter), nameof(focus));
+ }
+
+ if (scale < 0 || scale > 1)
+ {
+ throw new ArgumentException(SR.Format(SR.GdiplusInvalidParameter), nameof(scale));
}
int status = SafeNativeMethods.Gdip.GdipSetLineSigmaBlend(new HandleRef(this, NativeBrush), focus, scale);
@@ -348,9 +353,14 @@ namespace System.Drawing.Drawing2D
public void SetBlendTriangularShape(float focus, float scale)
{
- if (focus < 0 || focus > 1 || scale < 0 || scale > 1)
+ if (focus < 0 || focus > 1)
{
- throw new ArgumentException(SR.Format(SR.GdiplusInvalidParameter));
+ throw new ArgumentException(SR.Format(SR.GdiplusInvalidParameter), nameof(focus));
+ }
+
+ if (scale < 0 || scale > 1)
+ {
+ throw new ArgumentException(SR.Format(SR.GdiplusInvalidParameter), nameof(scale));
}
int status = SafeNativeMethods.Gdip.GdipSetLineLinearBlend(new HandleRef(this, NativeBrush), focus, scale);
@@ -531,7 +541,7 @@ namespace System.Drawing.Drawing2D
{
if (value == null)
{
- throw new ArgumentNullException("matrix");
+ throw new ArgumentNullException(nameof(value));
}
int status = SafeNativeMethods.Gdip.GdipSetLineTransform(new HandleRef(this, NativeBrush), new HandleRef(value, value.nativeMatrix));
@@ -554,6 +564,13 @@ namespace System.Drawing.Drawing2D
throw new ArgumentNullException(nameof(matrix));
}
+ // Multiplying the transform by a disposed matrix is a nop in GDI+, but throws
+ // with the libgdiplus backend. Simulate a nop for compatability with GDI+.
+ if (matrix.nativeMatrix == IntPtr.Zero)
+ {
+ return;
+ }
+
int status = SafeNativeMethods.Gdip.GdipMultiplyLineTransform(new HandleRef(this, NativeBrush),
new HandleRef(matrix, matrix.nativeMatrix),
order);
diff --git a/src/System.Drawing.Common/src/System/Drawing/Drawing2D/Matrix.cs b/src/System.Drawing.Common/src/System/Drawing/Drawing2D/Matrix.cs
index 99a2a84ced..4bd39c992c 100644
--- a/src/System.Drawing.Common/src/System/Drawing/Drawing2D/Matrix.cs
+++ b/src/System.Drawing.Common/src/System/Drawing/Drawing2D/Matrix.cs
@@ -170,7 +170,12 @@ namespace System.Drawing.Drawing2D
{
if (matrix == null)
{
- throw new ArgumentNullException("matrix");
+ throw new ArgumentNullException(nameof(matrix));
+ }
+
+ if (matrix.nativeMatrix == nativeMatrix)
+ {
+ throw new InvalidOperationException(SR.GdiplusObjectBusy);
}
int status = SafeNativeMethods.Gdip.GdipMultiplyMatrix(new HandleRef(this, nativeMatrix), new HandleRef(matrix, matrix.nativeMatrix),
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 d4053460d0..a268e66aad 100644
--- a/src/System.Drawing.Common/src/System/Drawing/Drawing2D/PathGradientBrush.cs
+++ b/src/System.Drawing.Common/src/System/Drawing/Drawing2D/PathGradientBrush.cs
@@ -173,26 +173,16 @@ namespace System.Drawing.Drawing2D
}
set
{
- int status = SafeNativeMethods.Gdip.GdipGetPathGradientSurroundColorCount(new HandleRef(this, NativeBrush),
- out int count);
-
- if (status != SafeNativeMethods.Gdip.Ok)
- throw SafeNativeMethods.Gdip.StatusException(status);
-
- if ((value.Length > count) || (count <= 0))
- throw SafeNativeMethods.Gdip.StatusException(SafeNativeMethods.Gdip.InvalidParameter);
-
- count = value.Length;
+ int count = value.Length;
int[] argbs = new int[count];
for (int i = 0; i < value.Length; i++)
argbs[i] = value[i].ToArgb();
- status = SafeNativeMethods.Gdip.GdipSetPathGradientSurroundColorsWithCount(new HandleRef(this, NativeBrush),
+ int status = SafeNativeMethods.Gdip.GdipSetPathGradientSurroundColorsWithCount(new HandleRef(this, NativeBrush),
argbs,
ref count);
- if (status != SafeNativeMethods.Gdip.Ok)
- throw SafeNativeMethods.Gdip.StatusException(status);
+ SafeNativeMethods.Gdip.CheckStatus(status);
}
}
@@ -250,44 +240,25 @@ namespace System.Drawing.Drawing2D
int count = retval;
- IntPtr factors = IntPtr.Zero;
- IntPtr positions = IntPtr.Zero;
+ var factors = new float[count];
+ var positions = new float[count];
- try
- {
- int size = checked(4 * count);
- factors = Marshal.AllocHGlobal(size);
- positions = Marshal.AllocHGlobal(size);
-
- // Retrieve horizontal blend factors
+ // Retrieve horizontal blend factors
- status = SafeNativeMethods.Gdip.GdipGetPathGradientBlend(new HandleRef(this, NativeBrush), factors, positions, count);
+ status = SafeNativeMethods.Gdip.GdipGetPathGradientBlend(new HandleRef(this, NativeBrush), factors, positions, count);
- if (status != SafeNativeMethods.Gdip.Ok)
- {
- throw SafeNativeMethods.Gdip.StatusException(status);
- }
-
- // Return the result in a managed array
+ if (status != SafeNativeMethods.Gdip.Ok)
+ {
+ throw SafeNativeMethods.Gdip.StatusException(status);
+ }
- Blend blend = new Blend(count);
+ // Return the result in a managed array
- Marshal.Copy(factors, blend.Factors, 0, count);
- Marshal.Copy(positions, blend.Positions, 0, count);
+ Blend blend = new Blend(count);
+ blend.Factors = factors;
+ blend.Positions = positions;
- return blend;
- }
- finally
- {
- if (factors != IntPtr.Zero)
- {
- Marshal.FreeHGlobal(factors);
- }
- if (positions != IntPtr.Zero)
- {
- Marshal.FreeHGlobal(positions);
- }
- }
+ return blend;
}
set
{
@@ -368,30 +339,36 @@ namespace System.Drawing.Drawing2D
public void SetSigmaBellShape(float focus, float scale)
{
- if (focus < 0 || focus > 1 || scale < 0 || scale > 1)
+ if (focus < 0 || focus > 1)
{
- throw new ArgumentException(SR.Format(SR.GdiplusInvalidParameter));
+ throw new ArgumentException(SR.Format(SR.GdiplusInvalidParameter), nameof(focus));
}
- int status = SafeNativeMethods.Gdip.GdipSetPathGradientSigmaBlend(new HandleRef(this, NativeBrush), focus, scale);
+ if (scale < 0 || scale > 1)
+ {
+ throw new ArgumentException(SR.Format(SR.GdiplusInvalidParameter), nameof(scale));
+ }
- if (status != SafeNativeMethods.Gdip.Ok)
- throw SafeNativeMethods.Gdip.StatusException(status);
+ int status = SafeNativeMethods.Gdip.GdipSetPathGradientSigmaBlend(new HandleRef(this, NativeBrush), focus, scale);
+ SafeNativeMethods.Gdip.CheckStatus(status);
}
public void SetBlendTriangularShape(float focus) => SetBlendTriangularShape(focus, (float)1.0);
public void SetBlendTriangularShape(float focus, float scale)
{
- if (focus < 0 || focus > 1 || scale < 0 || scale > 1)
+ if (focus < 0 || focus > 1)
{
- throw new ArgumentException(SR.Format(SR.GdiplusInvalidParameter));
+ throw new ArgumentException(SR.Format(SR.GdiplusInvalidParameter), nameof(focus));
}
- int status = SafeNativeMethods.Gdip.GdipSetPathGradientLinearBlend(new HandleRef(this, NativeBrush), focus, scale);
+ if (scale < 0 || scale > 1)
+ {
+ throw new ArgumentException(SR.Format(SR.GdiplusInvalidParameter), nameof(scale));
+ }
- if (status != SafeNativeMethods.Gdip.Ok)
- throw SafeNativeMethods.Gdip.StatusException(status);
+ int status = SafeNativeMethods.Gdip.GdipSetPathGradientLinearBlend(new HandleRef(this, NativeBrush), focus, scale);
+ SafeNativeMethods.Gdip.CheckStatus(status);
}
public ColorBlend InterpolationColors
@@ -399,118 +376,76 @@ namespace System.Drawing.Drawing2D
get
{
// Figure out the size of blend factor array
- int status = SafeNativeMethods.Gdip.GdipGetPathGradientPresetBlendCount(new HandleRef(this, NativeBrush), out int retval);
+ int status = SafeNativeMethods.Gdip.GdipGetPathGradientPresetBlendCount(new HandleRef(this, NativeBrush), out int count);
+ SafeNativeMethods.Gdip.CheckStatus(status);
- if (status != SafeNativeMethods.Gdip.Ok)
- {
- throw SafeNativeMethods.Gdip.StatusException(status);
- }
-
- // If retVal is 0, then there is nothing to marshal.
+ // If count is 0, then there is nothing to marshal.
// In this case, we'll return an empty ColorBlend...
- //
- if (retval == 0)
+ if (count == 0)
{
return new ColorBlend();
}
- // Allocate temporary native memory buffer
-
- int count = retval;
+ int[] colors = new int[count];
+ float[] positions = new float[count];
- IntPtr colors = IntPtr.Zero;
- IntPtr positions = IntPtr.Zero;
+ ColorBlend blend = new ColorBlend(count);
- try
+ // status would fail if we ask points or types with a < 2 count
+ if (count > 1)
{
- int size = checked(4 * count);
- colors = Marshal.AllocHGlobal(size);
- positions = Marshal.AllocHGlobal(size);
-
// Retrieve horizontal blend factors
-
status = SafeNativeMethods.Gdip.GdipGetPathGradientPresetBlend(new HandleRef(this, NativeBrush), colors, positions, count);
- if (status != SafeNativeMethods.Gdip.Ok)
- {
- throw SafeNativeMethods.Gdip.StatusException(status);
- }
+ SafeNativeMethods.Gdip.CheckStatus(status);
// Return the result in a managed array
- ColorBlend blend = new ColorBlend(count);
-
- int[] argb = new int[count];
- Marshal.Copy(colors, argb, 0, count);
- Marshal.Copy(positions, blend.Positions, 0, count);
+ blend.Positions = positions;
// copy ARGB values into Color array of ColorBlend
- blend.Colors = new Color[argb.Length];
-
- for (int i = 0; i < argb.Length; i++)
- {
- blend.Colors[i] = Color.FromArgb(argb[i]);
- }
+ blend.Colors = new Color[count];
- return blend;
- }
- finally
- {
- if (colors != IntPtr.Zero)
- {
- Marshal.FreeHGlobal(colors);
- }
- if (positions != IntPtr.Zero)
+ for (int i = 0; i < count; i++)
{
- Marshal.FreeHGlobal(positions);
+ blend.Colors[i] = Color.FromArgb(colors[i]);
}
}
+
+ return blend;
}
set
{
- // Allocate temporary native memory buffer
- // and copy input blend factors into it.
-
+ // The Desktop implementation will throw various exceptions - ranging from NullReferenceExceptions to Argument(OutOfRange)Exceptions
+ // depending on how sane the input is. These checks exist to replicate the exact Desktop behavior.
int count = value.Colors.Length;
- IntPtr colors = IntPtr.Zero;
- IntPtr positions = IntPtr.Zero;
-
- try
+ if (value.Positions == null)
{
- int size = checked(4 * count);
- colors = Marshal.AllocHGlobal(size);
- positions = Marshal.AllocHGlobal(size);
-
- int[] argbs = new int[count];
- for (int i = 0; i < count; i++)
- {
- argbs[i] = value.Colors[i].ToArgb();
- }
-
- Marshal.Copy(argbs, 0, colors, count);
- Marshal.Copy(value.Positions, 0, positions, count);
-
- // Set blend factors
+ throw new ArgumentNullException("source");
+ }
- int status = SafeNativeMethods.Gdip.GdipSetPathGradientPresetBlend(new HandleRef(this, NativeBrush), new HandleRef(null, colors), new HandleRef(null, positions), count);
+ if (value.Colors.Length > value.Positions.Length)
+ {
+ throw new ArgumentOutOfRangeException();
+ }
- if (status != SafeNativeMethods.Gdip.Ok)
- {
- throw SafeNativeMethods.Gdip.StatusException(status);
- }
+ if (value.Colors.Length < value.Positions.Length)
+ {
+ throw new ArgumentException();
}
- finally
+
+ float[] positions = value.Positions;
+ int[] argbs = new int[count];
+ for (int i = 0; i < count; i++)
{
- if (colors != IntPtr.Zero)
- {
- Marshal.FreeHGlobal(colors);
- }
- if (positions != IntPtr.Zero)
- {
- Marshal.FreeHGlobal(positions);
- }
+ argbs[i] = value.Colors[i].ToArgb();
}
+
+ // Set blend factors
+ int status = SafeNativeMethods.Gdip.GdipSetPathGradientPresetBlend(new HandleRef(this, NativeBrush), argbs, positions, count);
+
+ SafeNativeMethods.Gdip.CheckStatus(status);
}
}
@@ -521,21 +456,19 @@ namespace System.Drawing.Drawing2D
Matrix matrix = new Matrix();
int status = SafeNativeMethods.Gdip.GdipGetPathGradientTransform(new HandleRef(this, NativeBrush), new HandleRef(matrix, matrix.nativeMatrix));
-
- if (status != SafeNativeMethods.Gdip.Ok)
- throw SafeNativeMethods.Gdip.StatusException(status);
+ SafeNativeMethods.Gdip.CheckStatus(status);
return matrix;
}
set
{
if (value == null)
- throw new ArgumentNullException("matrix");
+ {
+ throw new ArgumentNullException(nameof(value));
+ }
int status = SafeNativeMethods.Gdip.GdipSetPathGradientTransform(new HandleRef(this, NativeBrush), new HandleRef(value, value.nativeMatrix));
-
- if (status != SafeNativeMethods.Gdip.Ok)
- throw SafeNativeMethods.Gdip.StatusException(status);
+ SafeNativeMethods.Gdip.CheckStatus(status);
}
}
@@ -552,14 +485,21 @@ namespace System.Drawing.Drawing2D
public void MultiplyTransform(Matrix matrix, MatrixOrder order)
{
if (matrix == null)
- throw new ArgumentNullException("matrix");
+ {
+ throw new ArgumentNullException(nameof(matrix));
+ }
+
+ // Multiplying the transform by a disposed matrix is a nop in GDI+, but throws
+ // with the libgdiplus backend. Simulate a nop for compatability with GDI+.
+ if (matrix.nativeMatrix == IntPtr.Zero)
+ {
+ return;
+ }
int status = SafeNativeMethods.Gdip.GdipMultiplyPathGradientTransform(new HandleRef(this, NativeBrush),
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);
diff --git a/src/System.Drawing.Common/src/Unix/System.Drawing/Font.cs b/src/System.Drawing.Common/src/System/Drawing/Font.Unix.cs
index a77cc2ca66..2f360846f1 100644
--- a/src/System.Drawing.Common/src/Unix/System.Drawing/Font.cs
+++ b/src/System.Drawing.Common/src/System/Drawing/Font.Unix.cs
@@ -52,7 +52,6 @@ namespace System.Drawing
private string systemFontName;
private string originalFontName;
private float _size;
- private object olf;
private const byte DefaultCharSet = 1;
private static int CharSetOffset = -1;
@@ -73,9 +72,9 @@ namespace System.Drawing
}
setProperties(family, emSize, style, unit, charSet, isVertical);
- Status status = SafeNativeMethods.Gdip.GdipCreateFont(family.NativeFamily, emSize, style, unit, out fontObject);
+ int status = SafeNativeMethods.Gdip.GdipCreateFont(family.NativeFamily, emSize, style, unit, out fontObject);
- if (status == Status.FontStyleNotFound)
+ if (status == SafeNativeMethods.Gdip.FontStyleNotFound)
throw new ArgumentException(string.Format("Style {0} isn't supported by font {1}.", style.ToString(), familyName));
SafeNativeMethods.Gdip.CheckStatus(status);
@@ -113,7 +112,7 @@ namespace System.Drawing
{
if (fontObject != IntPtr.Zero)
{
- Status status = SafeNativeMethods.Gdip.GdipDeleteFont(fontObject);
+ int status = SafeNativeMethods.Gdip.GdipDeleteFont(fontObject);
fontObject = IntPtr.Zero;
GC.SuppressFinalize(this);
// check the status code (throw) at the last step
@@ -214,7 +213,6 @@ namespace System.Drawing
public static Font FromHfont(IntPtr hfont)
{
IntPtr newObject;
- IntPtr hdc;
FontStyle newStyle = FontStyle.Regular;
float newSize;
SafeNativeMethods.LOGFONT lf = new SafeNativeMethods.LOGFONT();
@@ -226,32 +224,10 @@ namespace System.Drawing
return (result);
}
- if (GDIPlus.RunningOnUnix())
- {
- // If we're on Unix we use our private gdiplus API to avoid Wine
- // dependencies in S.D
- Status s = SafeNativeMethods.Gdip.GdipCreateFontFromHfont(hfont, out newObject, ref lf);
- SafeNativeMethods.Gdip.CheckStatus(s);
- }
- else
- {
-
- // This needs testing
- // GetDC, SelectObject, ReleaseDC GetTextMetric and
- // GetFontFace are not really GDIPlus, see gdipFunctions.cs
-
- newStyle = FontStyle.Regular;
-
- hdc = GDIPlus.GetDC(IntPtr.Zero);
- try
- {
- return FromLogFont(lf, hdc);
- }
- finally
- {
- GDIPlus.ReleaseDC(IntPtr.Zero, hdc);
- }
- }
+ // If we're on Unix we use our private gdiplus API to avoid Wine
+ // dependencies in S.D
+ int s = SafeNativeMethods.Gdip.GdipCreateFontFromHfont(hfont, out newObject, ref lf);
+ SafeNativeMethods.Gdip.CheckStatus(s);
if (lf.lfItalic != 0)
{
@@ -290,17 +266,7 @@ namespace System.Drawing
if (fontObject == IntPtr.Zero)
throw new ArgumentException("Object has been disposed.");
- if (GDIPlus.RunningOnUnix())
- return fontObject;
-
- // win32 specific code
- if (olf == null)
- {
- olf = new LOGFONT();
- ToLogFont(olf);
- }
- LOGFONT lf = (LOGFONT)olf;
- return GDIPlus.CreateFontIndirect(ref lf);
+ return fontObject;
}
internal Font(IntPtr newFontObject, string familyName, FontStyle style, float size)
@@ -325,7 +291,7 @@ namespace System.Drawing
// no null checks, MS throws a NullReferenceException if original is null
setProperties(prototype.FontFamily, prototype.Size, newStyle, prototype.Unit, prototype.GdiCharSet, prototype.GdiVerticalFont);
- Status status = SafeNativeMethods.Gdip.GdipCreateFont(_fontFamily.NativeFamily, Size, Style, Unit, out fontObject);
+ int status = SafeNativeMethods.Gdip.GdipCreateFont(_fontFamily.NativeFamily, Size, Style, Unit, out fontObject);
SafeNativeMethods.Gdip.CheckStatus(status);
}
@@ -365,7 +331,7 @@ namespace System.Drawing
if (family == null)
throw new ArgumentNullException("family");
- Status status;
+ int status;
setProperties(family, emSize, style, unit, gdiCharSet, gdiVerticalFont);
status = SafeNativeMethods.Gdip.GdipCreateFont(family.NativeFamily, emSize, style, unit, out fontObject);
SafeNativeMethods.Gdip.CheckStatus(status);
@@ -632,7 +598,7 @@ namespace System.Drawing
{
IntPtr newObject;
SafeNativeMethods.LOGFONT o = (SafeNativeMethods.LOGFONT)lf;
- Status status = SafeNativeMethods.Gdip.GdipCreateFontFromLogfont(hdc, ref o, out newObject);
+ int status = SafeNativeMethods.Gdip.GdipCreateFontFromLogfont(hdc, ref o, out newObject);
SafeNativeMethods.Gdip.CheckStatus(status);
return new Font(newObject, "Microsoft Sans Serif", FontStyle.Regular, 10);
}
@@ -644,50 +610,18 @@ namespace System.Drawing
public static Font FromLogFont(object lf)
{
- if (GDIPlus.RunningOnUnix())
- return FromLogFont(lf, IntPtr.Zero);
-
- // win32 specific code
- IntPtr hDC = IntPtr.Zero;
- try
- {
- hDC = GDIPlus.GetDC(IntPtr.Zero);
- return FromLogFont(lf, hDC);
- }
- finally
- {
- GDIPlus.ReleaseDC(IntPtr.Zero, hDC);
- }
+ return FromLogFont(lf, IntPtr.Zero);
}
public void ToLogFont(object logFont)
{
- if (GDIPlus.RunningOnUnix())
- {
- // Unix - We don't have a window we could associate the DC with
- // so we use an image instead
- using (Bitmap img = new Bitmap(1, 1, Imaging.PixelFormat.Format32bppArgb))
- {
- using (Graphics g = Graphics.FromImage(img))
- {
- ToLogFont(logFont, g);
- }
- }
- }
- else
+ // Unix - We don't have a window we could associate the DC with
+ // so we use an image instead
+ using (Bitmap img = new Bitmap(1, 1, Imaging.PixelFormat.Format32bppArgb))
{
- // Windows
- IntPtr hDC = GDIPlus.GetDC(IntPtr.Zero);
- try
- {
- using (Graphics g = Graphics.FromHdc(hDC))
- {
- ToLogFont(logFont, g);
- }
- }
- finally
+ using (Graphics g = Graphics.FromImage(img))
{
- GDIPlus.ReleaseDC(IntPtr.Zero, hDC);
+ ToLogFont(logFont, g);
}
}
}
@@ -711,14 +645,14 @@ namespace System.Drawing
int size = Marshal.SizeOf(logFont);
if (size >= Marshal.SizeOf(lf))
{
- Status status;
+ int status;
IntPtr copy = Marshal.AllocHGlobal(size);
try
{
Marshal.StructureToPtr(logFont, copy, false);
status = SafeNativeMethods.Gdip.GdipGetLogFont(NativeObject, graphics.NativeObject, logFont);
- if (status != Status.Ok)
+ if (status != SafeNativeMethods.Gdip.Ok)
{
// reset to original values
Marshal.PtrToStructure(copy, logFont);
@@ -764,7 +698,7 @@ namespace System.Drawing
throw new ArgumentNullException("graphics");
float size;
- Status status = SafeNativeMethods.Gdip.GdipGetFontHeight(fontObject, graphics.NativeObject, out size);
+ int status = SafeNativeMethods.Gdip.GdipGetFontHeight(fontObject, graphics.NativeObject, out size);
SafeNativeMethods.Gdip.CheckStatus(status);
return size;
}
@@ -772,7 +706,7 @@ namespace System.Drawing
public float GetHeight(float dpi)
{
float size;
- Status status = SafeNativeMethods.Gdip.GdipGetFontHeightGivenDPI(fontObject, dpi, out size);
+ int status = SafeNativeMethods.Gdip.GdipGetFontHeightGivenDPI(fontObject, dpi, out size);
SafeNativeMethods.Gdip.CheckStatus(status);
return size;
}
diff --git a/src/System.Drawing.Common/src/System/Drawing/Font.cs b/src/System.Drawing.Common/src/System/Drawing/Font.Windows.cs
index 23bf242f19..23bf242f19 100644
--- a/src/System.Drawing.Common/src/System/Drawing/Font.cs
+++ b/src/System.Drawing.Common/src/System/Drawing/Font.Windows.cs
diff --git a/src/System.Drawing.Common/src/System/Drawing/GdiPlusStreamHelper.Unix.cs b/src/System.Drawing.Common/src/System/Drawing/GdiPlusStreamHelper.Unix.cs
new file mode 100644
index 0000000000..b9300116d0
--- /dev/null
+++ b/src/System.Drawing.Common/src/System/Drawing/GdiPlusStreamHelper.Unix.cs
@@ -0,0 +1,330 @@
+// Licensed to the .NET Foundation under one or more agreements.
+// See the LICENSE file in the project root for more information.
+//
+// System.Drawing.GdiPlusStreamHelper.cs
+// - Originally in System.Drawing.gdipFunctions.cs
+//
+// Authors:
+// Alexandre Pigolkine (pigolkine@gmx.de)
+// Jordi Mas i Hernandez (jordi@ximian.com)
+// Sanjay Gupta (gsanjay@novell.com)
+// Ravindra (rkumar@novell.com)
+// Peter Dennis Bartok (pbartok@novell.com)
+// Sebastien Pouliot <sebastien@ximian.com>
+//
+// Copyright (C) 2004 - 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.IO;
+using System.Runtime.InteropServices;
+
+namespace System.Drawing
+{
+ internal sealed partial class GdiPlusStreamHelper
+ {
+ public Stream stream;
+
+ private StreamGetHeaderDelegate sghd = null;
+ private StreamGetBytesDelegate sgbd = null;
+ private StreamSeekDelegate skd = null;
+ private StreamPutBytesDelegate spbd = null;
+ private StreamCloseDelegate scd = null;
+ private StreamSizeDelegate ssd = null;
+ private byte[] start_buf;
+ private int start_buf_pos;
+ private int start_buf_len;
+ private byte[] managedBuf;
+ private const int default_bufsize = 4096;
+
+ public GdiPlusStreamHelper(Stream s, bool seekToOrigin)
+ {
+ managedBuf = new byte[default_bufsize];
+
+ stream = s;
+ if (stream != null && stream.CanSeek && seekToOrigin)
+ {
+ stream.Seek(0, SeekOrigin.Begin);
+ }
+ }
+
+ public int StreamGetHeaderImpl(IntPtr buf, int bufsz)
+ {
+ int bytesRead;
+
+ start_buf = new byte[bufsz];
+
+ try
+ {
+ bytesRead = stream.Read(start_buf, 0, bufsz);
+ }
+ catch (IOException)
+ {
+ return -1;
+ }
+
+ if (bytesRead > 0 && buf != IntPtr.Zero)
+ {
+ Marshal.Copy(start_buf, 0, (IntPtr)(buf.ToInt64()), bytesRead);
+ }
+
+ start_buf_pos = 0;
+ start_buf_len = bytesRead;
+
+ return bytesRead;
+ }
+
+ public StreamGetHeaderDelegate GetHeaderDelegate
+ {
+ get
+ {
+ if (stream != null && stream.CanRead)
+ {
+ if (sghd == null)
+ {
+ sghd = new StreamGetHeaderDelegate(StreamGetHeaderImpl);
+ }
+ return sghd;
+ }
+ return null;
+ }
+ }
+
+ public int StreamGetBytesImpl(IntPtr buf, int bufsz, bool peek)
+ {
+ if (buf == IntPtr.Zero && peek)
+ {
+ return -1;
+ }
+
+ if (bufsz > managedBuf.Length)
+ managedBuf = new byte[bufsz];
+ int bytesRead = 0;
+ long streamPosition = 0;
+
+ if (bufsz > 0)
+ {
+ if (stream.CanSeek)
+ {
+ streamPosition = stream.Position;
+ }
+ if (start_buf_len > 0)
+ {
+ if (start_buf_len > bufsz)
+ {
+ Array.Copy(start_buf, start_buf_pos, managedBuf, 0, bufsz);
+ start_buf_pos += bufsz;
+ start_buf_len -= bufsz;
+ bytesRead = bufsz;
+ bufsz = 0;
+ }
+ else
+ {
+ // this is easy
+ Array.Copy(start_buf, start_buf_pos, managedBuf, 0, start_buf_len);
+ bufsz -= start_buf_len;
+ bytesRead = start_buf_len;
+ start_buf_len = 0;
+ }
+ }
+
+ if (bufsz > 0)
+ {
+ try
+ {
+ bytesRead += stream.Read(managedBuf, bytesRead, bufsz);
+ }
+ catch (IOException)
+ {
+ return -1;
+ }
+ }
+
+ if (bytesRead > 0 && buf != IntPtr.Zero)
+ {
+ Marshal.Copy(managedBuf, 0, (IntPtr)(buf.ToInt64()), bytesRead);
+ }
+
+ if (!stream.CanSeek && (bufsz == 10) && peek)
+ {
+ // Special 'hack' to support peeking of the type for gdi+ on non-seekable streams
+ }
+
+ if (peek)
+ {
+ if (stream.CanSeek)
+ {
+ // If we are peeking bytes, then go back to original position before peeking
+ stream.Seek(streamPosition, SeekOrigin.Begin);
+ }
+ else
+ {
+ throw new NotSupportedException();
+ }
+ }
+ }
+
+ return bytesRead;
+ }
+
+ public StreamGetBytesDelegate GetBytesDelegate
+ {
+ get
+ {
+ if (stream != null && stream.CanRead)
+ {
+ if (sgbd == null)
+ {
+ sgbd = new StreamGetBytesDelegate(StreamGetBytesImpl);
+ }
+ return sgbd;
+ }
+ return null;
+ }
+ }
+
+ public long StreamSeekImpl(int offset, int whence)
+ {
+ // Make sure we have a valid 'whence'.
+ if ((whence < 0) || (whence > 2))
+ return -1;
+
+ // Invalidate the start_buf if we're actually going to call a Seek method.
+ start_buf_pos += start_buf_len;
+ start_buf_len = 0;
+
+ SeekOrigin origin;
+
+ // Translate 'whence' into a SeekOrigin enum member.
+ switch (whence)
+ {
+ case 0:
+ origin = SeekOrigin.Begin;
+ break;
+ case 1:
+ origin = SeekOrigin.Current;
+ break;
+ case 2:
+ origin = SeekOrigin.End;
+ break;
+
+ // The following line is redundant but necessary to avoid a
+ // "Use of unassigned local variable" error without actually
+ // initializing 'origin' to a dummy value.
+ default:
+ return -1;
+ }
+
+ // Do the actual seek operation and return its result.
+ return stream.Seek((long)offset, origin);
+ }
+
+ public StreamSeekDelegate SeekDelegate
+ {
+ get
+ {
+ if (stream != null && stream.CanSeek)
+ {
+ if (skd == null)
+ {
+ skd = new StreamSeekDelegate(StreamSeekImpl);
+ }
+ return skd;
+ }
+ return null;
+ }
+ }
+
+ public int StreamPutBytesImpl(IntPtr buf, int bufsz)
+ {
+ if (bufsz > managedBuf.Length)
+ managedBuf = new byte[bufsz];
+ Marshal.Copy(buf, managedBuf, 0, bufsz);
+ stream.Write(managedBuf, 0, bufsz);
+ return bufsz;
+ }
+
+ public StreamPutBytesDelegate PutBytesDelegate
+ {
+ get
+ {
+ if (stream != null && stream.CanWrite)
+ {
+ if (spbd == null)
+ {
+ spbd = new StreamPutBytesDelegate(StreamPutBytesImpl);
+ }
+ return spbd;
+ }
+ return null;
+ }
+ }
+
+ public void StreamCloseImpl()
+ {
+ stream.Dispose();
+ }
+
+ public StreamCloseDelegate CloseDelegate
+ {
+ get
+ {
+ if (stream != null)
+ {
+ if (scd == null)
+ {
+ scd = new StreamCloseDelegate(StreamCloseImpl);
+ }
+ return scd;
+ }
+ return null;
+ }
+ }
+
+ public long StreamSizeImpl()
+ {
+ try
+ {
+ return stream.Length;
+ }
+ catch
+ {
+ return -1;
+ }
+ }
+
+ public StreamSizeDelegate SizeDelegate
+ {
+ get
+ {
+ if (stream != null)
+ {
+ if (ssd == null)
+ {
+ ssd = new StreamSizeDelegate(StreamSizeImpl);
+ }
+ return ssd;
+ }
+ return null;
+ }
+ }
+ }
+}
diff --git a/src/System.Drawing.Common/src/System/Drawing/Gdiplus.cs b/src/System.Drawing.Common/src/System/Drawing/Gdiplus.cs
index 344a4111eb..e2729225a6 100644
--- a/src/System.Drawing.Common/src/System/Drawing/Gdiplus.cs
+++ b/src/System.Drawing.Common/src/System/Drawing/Gdiplus.cs
@@ -86,7 +86,7 @@ namespace System.Drawing
s_gdipModule = LoadNativeLibrary();
LoadSharedFunctionPointers();
- LoadPlatformFunctionPointers(); // This should be combined with the above call when Windows/Unix implementations are unified.
+ PlatformInitialize();
StartupInput input = StartupInput.GetDefault();
StartupOutput output;
diff --git a/src/System.Drawing.Common/src/System/Drawing/GdiplusNative.Unix.cs b/src/System.Drawing.Common/src/System/Drawing/GdiplusNative.Unix.cs
index 09e2a4504c..7e531ba0b2 100644
--- a/src/System.Drawing.Common/src/System/Drawing/GdiplusNative.Unix.cs
+++ b/src/System.Drawing.Common/src/System/Drawing/GdiplusNative.Unix.cs
@@ -6,8 +6,6 @@ using System.Drawing.Drawing2D;
using System.Drawing.Imaging;
using System.Drawing.Text;
using System.Runtime.InteropServices;
-using System.Runtime.InteropServices.ComTypes;
-using System.Text;
namespace System.Drawing
{
@@ -15,302 +13,346 @@ namespace System.Drawing
{
internal unsafe partial class Gdip
{
+ public static IntPtr Display = IntPtr.Zero;
+ public static bool UseX11Drawable = false;
+ public static bool UseCarbonDrawable = false;
+ public static bool UseCocoaDrawable = false;
+
private static IntPtr LoadNativeLibrary()
{
- // Various Unix package managers have chosen different names for the "libgdiplus" shared library.
- // The mono project, where libgdiplus originated, allowed both of the names below to be used, via
- // a global configuration setting. We prefer the "unversioned" shared object name, and fallback to
- // the name suffixed with ".0".
- IntPtr lib = Interop.Libdl.dlopen("libgdiplus.so", Interop.Libdl.RTLD_NOW);
- if (lib == IntPtr.Zero)
+ IntPtr lib = IntPtr.Zero;
+ if (RuntimeInformation.IsOSPlatform(OSPlatform.OSX))
+ {
+ lib = Interop.Libdl.dlopen("libgdiplus.dylib", Interop.Libdl.RTLD_NOW);
+ }
+ else
{
- lib = Interop.Libdl.dlopen("libgdiplus.so.0", Interop.Libdl.RTLD_NOW);
+ // Various Unix package managers have chosen different names for the "libgdiplus" shared library.
+ // The mono project, where libgdiplus originated, allowed both of the names below to be used, via
+ // a global configuration setting. We prefer the "unversioned" shared object name, and fallback to
+ // the name suffixed with ".0".
+ lib = Interop.Libdl.dlopen("libgdiplus.so", Interop.Libdl.RTLD_NOW);
if (lib == IntPtr.Zero)
{
- throw new DllNotFoundException(SR.LibgdiplusNotFound);
+ lib = Interop.Libdl.dlopen("libgdiplus.so.0", Interop.Libdl.RTLD_NOW);
}
}
+ // This function may return a null handle. If it does, individual functions loaded from it will throw a DllNotFoundException,
+ // but not until an attempt is made to actually use the function (rather than load it). This matches how PInvokes behave.
return lib;
}
private static IntPtr LoadFunctionPointer(IntPtr nativeLibraryHandle, string functionName) => Interop.Libdl.dlsym(nativeLibraryHandle, functionName);
- internal static void CheckStatus(Status status) => GDIPlus.CheckStatus(status);
+ private static void PlatformInitialize()
+ {
+ InitializeSystemContext();
+ LoadFunctionPointers();
+ }
+
+ private static void InitializeSystemContext()
+ {
+ if (Environment.GetEnvironmentVariable("not_supported_MONO_MWF_USE_NEW_X11_BACKEND") != null || Environment.GetEnvironmentVariable("MONO_MWF_MAC_FORCE_X11") != null)
+ {
+ UseX11Drawable = true;
+ }
+ else
+ {
+ IntPtr buf = Marshal.AllocHGlobal(8192);
+ // This is kind of a hack but gets us sysname from uname (struct utsname *name) on
+ // linux and darwin
+ if (uname(buf) != 0)
+ {
+ // WTH: We couldn't detect the OS; lets default to X11
+ UseX11Drawable = true;
+ }
+ else
+ {
+ string os = Marshal.PtrToStringAnsi(buf);
+ if (os == "Darwin")
+ UseCarbonDrawable = true;
+ else
+ UseX11Drawable = true;
+ }
+ Marshal.FreeHGlobal(buf);
+ }
+
+ // under MS 1.x this event is raised only for the default application domain
+#if !NETSTANDARD1_6
+ AppDomain.CurrentDomain.ProcessExit += new EventHandler(ProcessExit);
+#endif
+ }
- private static void LoadPlatformFunctionPointers()
+ [DllImport("libc")]
+ static extern int uname(IntPtr buf);
+
+ private static void ProcessExit(object sender, EventArgs e)
{
- GdiplusStartup_ptr = LoadFunction<GdiplusStartup_delegate>("GdiplusStartup");
- GdiplusShutdown_ptr = LoadFunction<GdiplusShutdown_delegate>("GdiplusShutdown");
- GdipAlloc_ptr = LoadFunction<GdipAlloc_delegate>("GdipAlloc");
- GdipFree_ptr = LoadFunction<GdipFree_delegate>("GdipFree");
- GdipDeleteBrush_ptr = LoadFunction<GdipDeleteBrush_delegate>("GdipDeleteBrush");
- GdipGetBrushType_ptr = LoadFunction<GdipGetBrushType_delegate>("GdipGetBrushType");
- GdipCreateFromHDC_ptr = LoadFunction<GdipCreateFromHDC_delegate>("GdipCreateFromHDC");
- GdipDeleteGraphics_ptr = LoadFunction<GdipDeleteGraphics_delegate>("GdipDeleteGraphics");
- GdipRestoreGraphics_ptr = LoadFunction<GdipRestoreGraphics_delegate>("GdipRestoreGraphics");
- GdipSaveGraphics_ptr = LoadFunction<GdipSaveGraphics_delegate>("GdipSaveGraphics");
- GdipDrawArc_ptr = LoadFunction<GdipDrawArc_delegate>("GdipDrawArc");
- GdipDrawArcI_ptr = LoadFunction<GdipDrawArcI_delegate>("GdipDrawArcI");
- GdipDrawBezier_ptr = LoadFunction<GdipDrawBezier_delegate>("GdipDrawBezier");
- GdipDrawBezierI_ptr = LoadFunction<GdipDrawBezierI_delegate>("GdipDrawBezierI");
- GdipDrawEllipseI_ptr = LoadFunction<GdipDrawEllipseI_delegate>("GdipDrawEllipseI");
- GdipDrawEllipse_ptr = LoadFunction<GdipDrawEllipse_delegate>("GdipDrawEllipse");
- GdipDrawLine_ptr = LoadFunction<GdipDrawLine_delegate>("GdipDrawLine");
- GdipDrawLineI_ptr = LoadFunction<GdipDrawLineI_delegate>("GdipDrawLineI");
- GdipDrawLines_ptr = LoadFunction<GdipDrawLines_delegate>("GdipDrawLines");
- GdipDrawLinesI_ptr = LoadFunction<GdipDrawLinesI_delegate>("GdipDrawLinesI");
- GdipDrawPath_ptr = LoadFunction<GdipDrawPath_delegate>("GdipDrawPath");
- GdipDrawPie_ptr = LoadFunction<GdipDrawPie_delegate>("GdipDrawPie");
- GdipDrawPieI_ptr = LoadFunction<GdipDrawPieI_delegate>("GdipDrawPieI");
- GdipDrawPolygon_ptr = LoadFunction<GdipDrawPolygon_delegate>("GdipDrawPolygon");
- GdipDrawPolygonI_ptr = LoadFunction<GdipDrawPolygonI_delegate>("GdipDrawPolygonI");
- GdipDrawRectangle_ptr = LoadFunction<GdipDrawRectangle_delegate>("GdipDrawRectangle");
- GdipDrawRectangleI_ptr = LoadFunction<GdipDrawRectangleI_delegate>("GdipDrawRectangleI");
- GdipDrawRectangles_ptr = LoadFunction<GdipDrawRectangles_delegate>("GdipDrawRectangles");
- GdipDrawRectanglesI_ptr = LoadFunction<GdipDrawRectanglesI_delegate>("GdipDrawRectanglesI");
- GdipFillEllipseI_ptr = LoadFunction<GdipFillEllipseI_delegate>("GdipFillEllipseI");
- GdipFillEllipse_ptr = LoadFunction<GdipFillEllipse_delegate>("GdipFillEllipse");
- GdipFillPolygon_ptr = LoadFunction<GdipFillPolygon_delegate>("GdipFillPolygon");
- GdipFillPolygonI_ptr = LoadFunction<GdipFillPolygonI_delegate>("GdipFillPolygonI");
- GdipFillPolygon2_ptr = LoadFunction<GdipFillPolygon2_delegate>("GdipFillPolygon2");
- GdipFillPolygon2I_ptr = LoadFunction<GdipFillPolygon2I_delegate>("GdipFillPolygon2I");
- GdipFillRectangle_ptr = LoadFunction<GdipFillRectangle_delegate>("GdipFillRectangle");
- GdipFillRectangleI_ptr = LoadFunction<GdipFillRectangleI_delegate>("GdipFillRectangleI");
- GdipFillRectangles_ptr = LoadFunction<GdipFillRectangles_delegate>("GdipFillRectangles");
- GdipFillRectanglesI_ptr = LoadFunction<GdipFillRectanglesI_delegate>("GdipFillRectanglesI");
- GdipDrawString_ptr = LoadFunction<GdipDrawString_delegate>("GdipDrawString");
- GdipGetDC_ptr = LoadFunction<GdipGetDC_delegate>("GdipGetDC");
- GdipReleaseDC_ptr = LoadFunction<GdipReleaseDC_delegate>("GdipReleaseDC");
- GdipDrawImageRectI_ptr = LoadFunction<GdipDrawImageRectI_delegate>("GdipDrawImageRectI");
- GdipGetRenderingOrigin_ptr = LoadFunction<GdipGetRenderingOrigin_delegate>("GdipGetRenderingOrigin");
- GdipSetRenderingOrigin_ptr = LoadFunction<GdipSetRenderingOrigin_delegate>("GdipSetRenderingOrigin");
- GdipCloneBitmapArea_ptr = LoadFunction<GdipCloneBitmapArea_delegate>("GdipCloneBitmapArea");
- GdipCloneBitmapAreaI_ptr = LoadFunction<GdipCloneBitmapAreaI_delegate>("GdipCloneBitmapAreaI");
- GdipGraphicsClear_ptr = LoadFunction<GdipGraphicsClear_delegate>("GdipGraphicsClear");
- GdipDrawClosedCurve_ptr = LoadFunction<GdipDrawClosedCurve_delegate>("GdipDrawClosedCurve");
- GdipDrawClosedCurveI_ptr = LoadFunction<GdipDrawClosedCurveI_delegate>("GdipDrawClosedCurveI");
- GdipDrawClosedCurve2_ptr = LoadFunction<GdipDrawClosedCurve2_delegate>("GdipDrawClosedCurve2");
- GdipDrawClosedCurve2I_ptr = LoadFunction<GdipDrawClosedCurve2I_delegate>("GdipDrawClosedCurve2I");
- GdipDrawCurve_ptr = LoadFunction<GdipDrawCurve_delegate>("GdipDrawCurve");
- GdipDrawCurveI_ptr = LoadFunction<GdipDrawCurveI_delegate>("GdipDrawCurveI");
- GdipDrawCurve2_ptr = LoadFunction<GdipDrawCurve2_delegate>("GdipDrawCurve2");
- GdipDrawCurve2I_ptr = LoadFunction<GdipDrawCurve2I_delegate>("GdipDrawCurve2I");
- GdipDrawCurve3_ptr = LoadFunction<GdipDrawCurve3_delegate>("GdipDrawCurve3");
- GdipDrawCurve3I_ptr = LoadFunction<GdipDrawCurve3I_delegate>("GdipDrawCurve3I");
- GdipFillClosedCurve_ptr = LoadFunction<GdipFillClosedCurve_delegate>("GdipFillClosedCurve");
- GdipFillClosedCurveI_ptr = LoadFunction<GdipFillClosedCurveI_delegate>("GdipFillClosedCurveI");
- GdipFillClosedCurve2_ptr = LoadFunction<GdipFillClosedCurve2_delegate>("GdipFillClosedCurve2");
- GdipFillClosedCurve2I_ptr = LoadFunction<GdipFillClosedCurve2I_delegate>("GdipFillClosedCurve2I");
- GdipFillPie_ptr = LoadFunction<GdipFillPie_delegate>("GdipFillPie");
- GdipFillPieI_ptr = LoadFunction<GdipFillPieI_delegate>("GdipFillPieI");
- GdipFillPath_ptr = LoadFunction<GdipFillPath_delegate>("GdipFillPath");
- GdipGetNearestColor_ptr = LoadFunction<GdipGetNearestColor_delegate>("GdipGetNearestColor");
- GdipTransformPoints_ptr = LoadFunction<GdipTransformPoints_delegate>("GdipTransformPoints");
- GdipTransformPointsI_ptr = LoadFunction<GdipTransformPointsI_delegate>("GdipTransformPointsI");
- GdipSetCompositingMode_ptr = LoadFunction<GdipSetCompositingMode_delegate>("GdipSetCompositingMode");
- GdipGetCompositingMode_ptr = LoadFunction<GdipGetCompositingMode_delegate>("GdipGetCompositingMode");
- GdipSetCompositingQuality_ptr = LoadFunction<GdipSetCompositingQuality_delegate>("GdipSetCompositingQuality");
- GdipGetCompositingQuality_ptr = LoadFunction<GdipGetCompositingQuality_delegate>("GdipGetCompositingQuality");
- GdipSetInterpolationMode_ptr = LoadFunction<GdipSetInterpolationMode_delegate>("GdipSetInterpolationMode");
- GdipGetInterpolationMode_ptr = LoadFunction<GdipGetInterpolationMode_delegate>("GdipGetInterpolationMode");
- GdipGetDpiX_ptr = LoadFunction<GdipGetDpiX_delegate>("GdipGetDpiX");
- GdipGetDpiY_ptr = LoadFunction<GdipGetDpiY_delegate>("GdipGetDpiY");
- GdipGetPageUnit_ptr = LoadFunction<GdipGetPageUnit_delegate>("GdipGetPageUnit");
- GdipGetPageScale_ptr = LoadFunction<GdipGetPageScale_delegate>("GdipGetPageScale");
- GdipSetPageUnit_ptr = LoadFunction<GdipSetPageUnit_delegate>("GdipSetPageUnit");
- GdipSetPageScale_ptr = LoadFunction<GdipSetPageScale_delegate>("GdipSetPageScale");
- GdipSetPixelOffsetMode_ptr = LoadFunction<GdipSetPixelOffsetMode_delegate>("GdipSetPixelOffsetMode");
- GdipGetPixelOffsetMode_ptr = LoadFunction<GdipGetPixelOffsetMode_delegate>("GdipGetPixelOffsetMode");
- GdipSetSmoothingMode_ptr = LoadFunction<GdipSetSmoothingMode_delegate>("GdipSetSmoothingMode");
- GdipGetSmoothingMode_ptr = LoadFunction<GdipGetSmoothingMode_delegate>("GdipGetSmoothingMode");
- GdipSetTextContrast_ptr = LoadFunction<GdipSetTextContrast_delegate>("GdipSetTextContrast");
- GdipGetTextContrast_ptr = LoadFunction<GdipGetTextContrast_delegate>("GdipGetTextContrast");
- GdipSetTextRenderingHint_ptr = LoadFunction<GdipSetTextRenderingHint_delegate>("GdipSetTextRenderingHint");
- GdipGetTextRenderingHint_ptr = LoadFunction<GdipGetTextRenderingHint_delegate>("GdipGetTextRenderingHint");
- GdipFlush_ptr = LoadFunction<GdipFlush_delegate>("GdipFlush");
- GdipAddPathString_ptr = LoadFunction<GdipAddPathString_delegate>("GdipAddPathString");
- GdipAddPathStringI_ptr = LoadFunction<GdipAddPathStringI_delegate>("GdipAddPathStringI");
- GdipCreateFromHWND_ptr = LoadFunction<GdipCreateFromHWND_delegate>("GdipCreateFromHWND");
- GdipMeasureString_ptr = LoadFunction<GdipMeasureString_delegate>("GdipMeasureString");
- GdipMeasureCharacterRanges_ptr = LoadFunction<GdipMeasureCharacterRanges_delegate>("GdipMeasureCharacterRanges");
- GdipCreateBitmapFromScan0_ptr = LoadFunction<GdipCreateBitmapFromScan0_delegate>("GdipCreateBitmapFromScan0");
- GdipCreateBitmapFromGraphics_ptr = LoadFunction<GdipCreateBitmapFromGraphics_delegate>("GdipCreateBitmapFromGraphics");
- GdipBitmapLockBits_ptr = LoadFunction<GdipBitmapLockBits_delegate>("GdipBitmapLockBits");
- GdipBitmapSetResolution_ptr = LoadFunction<GdipBitmapSetResolution_delegate>("GdipBitmapSetResolution");
- GdipBitmapUnlockBits_ptr = LoadFunction<GdipBitmapUnlockBits_delegate>("GdipBitmapUnlockBits");
- GdipBitmapGetPixel_ptr = LoadFunction<GdipBitmapGetPixel_delegate>("GdipBitmapGetPixel");
- GdipBitmapSetPixel_ptr = LoadFunction<GdipBitmapSetPixel_delegate>("GdipBitmapSetPixel");
- GdipLoadImageFromFile_ptr = LoadFunction<GdipLoadImageFromFile_delegate>("GdipLoadImageFromFile");
- GdipLoadImageFromStream_ptr = LoadFunction<GdipLoadImageFromStream_delegate>("GdipLoadImageFromStream");
- GdipSaveImageToStream_ptr = LoadFunction<GdipSaveImageToStream_delegate>("GdipSaveImageToStream");
- GdipCloneImage_ptr = LoadFunction<GdipCloneImage_delegate>("GdipCloneImage");
- GdipLoadImageFromFileICM_ptr = LoadFunction<GdipLoadImageFromFileICM_delegate>("GdipLoadImageFromFileICM");
- GdipCreateBitmapFromHBITMAP_ptr = LoadFunction<GdipCreateBitmapFromHBITMAP_delegate>("GdipCreateBitmapFromHBITMAP");
- GdipDisposeImage_ptr = LoadFunction<GdipDisposeImage_delegate>("GdipDisposeImage");
- GdipGetImageFlags_ptr = LoadFunction<GdipGetImageFlags_delegate>("GdipGetImageFlags");
- GdipGetImageType_ptr = LoadFunction<GdipGetImageType_delegate>("GdipGetImageType");
- GdipImageGetFrameDimensionsCount_ptr = LoadFunction<GdipImageGetFrameDimensionsCount_delegate>("GdipImageGetFrameDimensionsCount");
- GdipImageGetFrameDimensionsList_ptr = LoadFunction<GdipImageGetFrameDimensionsList_delegate>("GdipImageGetFrameDimensionsList");
- GdipGetImageHeight_ptr = LoadFunction<GdipGetImageHeight_delegate>("GdipGetImageHeight");
- GdipGetImageHorizontalResolution_ptr = LoadFunction<GdipGetImageHorizontalResolution_delegate>("GdipGetImageHorizontalResolution");
- GdipGetImagePaletteSize_ptr = LoadFunction<GdipGetImagePaletteSize_delegate>("GdipGetImagePaletteSize");
- GdipGetImagePalette_ptr = LoadFunction<GdipGetImagePalette_delegate>("GdipGetImagePalette");
- GdipSetImagePalette_ptr = LoadFunction<GdipSetImagePalette_delegate>("GdipSetImagePalette");
- GdipGetImageDimension_ptr = LoadFunction<GdipGetImageDimension_delegate>("GdipGetImageDimension");
- GdipGetImagePixelFormat_ptr = LoadFunction<GdipGetImagePixelFormat_delegate>("GdipGetImagePixelFormat");
- GdipGetPropertyCount_ptr = LoadFunction<GdipGetPropertyCount_delegate>("GdipGetPropertyCount");
- GdipGetPropertyIdList_ptr = LoadFunction<GdipGetPropertyIdList_delegate>("GdipGetPropertyIdList");
- GdipGetPropertySize_ptr = LoadFunction<GdipGetPropertySize_delegate>("GdipGetPropertySize");
- GdipGetAllPropertyItems_ptr = LoadFunction<GdipGetAllPropertyItems_delegate>("GdipGetAllPropertyItems");
- GdipGetImageRawFormat_ptr = LoadFunction<GdipGetImageRawFormat_delegate>("GdipGetImageRawFormat");
- GdipGetImageVerticalResolution_ptr = LoadFunction<GdipGetImageVerticalResolution_delegate>("GdipGetImageVerticalResolution");
- GdipGetImageWidth_ptr = LoadFunction<GdipGetImageWidth_delegate>("GdipGetImageWidth");
- GdipGetImageBounds_ptr = LoadFunction<GdipGetImageBounds_delegate>("GdipGetImageBounds");
- GdipGetEncoderParameterListSize_ptr = LoadFunction<GdipGetEncoderParameterListSize_delegate>("GdipGetEncoderParameterListSize");
- GdipGetEncoderParameterList_ptr = LoadFunction<GdipGetEncoderParameterList_delegate>("GdipGetEncoderParameterList");
- GdipImageGetFrameCount_ptr = LoadFunction<GdipImageGetFrameCount_delegate>("GdipImageGetFrameCount");
- GdipImageSelectActiveFrame_ptr = LoadFunction<GdipImageSelectActiveFrame_delegate>("GdipImageSelectActiveFrame");
- GdipGetPropertyItemSize_ptr = LoadFunction<GdipGetPropertyItemSize_delegate>("GdipGetPropertyItemSize");
- GdipGetPropertyItem_ptr = LoadFunction<GdipGetPropertyItem_delegate>("GdipGetPropertyItem");
- GdipRemovePropertyItem_ptr = LoadFunction<GdipRemovePropertyItem_delegate>("GdipRemovePropertyItem");
- GdipSetPropertyItem_ptr = LoadFunction<GdipSetPropertyItem_delegate>("GdipSetPropertyItem");
- GdipGetImageThumbnail_ptr = LoadFunction<GdipGetImageThumbnail_delegate>("GdipGetImageThumbnail");
- GdipImageRotateFlip_ptr = LoadFunction<GdipImageRotateFlip_delegate>("GdipImageRotateFlip");
- GdipSaveImageToFile_ptr = LoadFunction<GdipSaveImageToFile_delegate>("GdipSaveImageToFile");
- GdipSaveAdd_ptr = LoadFunction<GdipSaveAdd_delegate>("GdipSaveAdd");
- GdipSaveAddImage_ptr = LoadFunction<GdipSaveAddImage_delegate>("GdipSaveAddImage");
- GdipDrawImageI_ptr = LoadFunction<GdipDrawImageI_delegate>("GdipDrawImageI");
- GdipGetImageGraphicsContext_ptr = LoadFunction<GdipGetImageGraphicsContext_delegate>("GdipGetImageGraphicsContext");
- GdipDrawImage_ptr = LoadFunction<GdipDrawImage_delegate>("GdipDrawImage");
- GdipDrawImagePoints_ptr = LoadFunction<GdipDrawImagePoints_delegate>("GdipDrawImagePoints");
- GdipDrawImagePointsI_ptr = LoadFunction<GdipDrawImagePointsI_delegate>("GdipDrawImagePointsI");
- GdipDrawImageRectRectI_ptr = LoadFunction<GdipDrawImageRectRectI_delegate>("GdipDrawImageRectRectI");
- GdipDrawImageRectRect_ptr = LoadFunction<GdipDrawImageRectRect_delegate>("GdipDrawImageRectRect");
- GdipDrawImagePointsRectI_ptr = LoadFunction<GdipDrawImagePointsRectI_delegate>("GdipDrawImagePointsRectI");
- GdipDrawImagePointsRect_ptr = LoadFunction<GdipDrawImagePointsRect_delegate>("GdipDrawImagePointsRect");
- GdipDrawImageRect_ptr = LoadFunction<GdipDrawImageRect_delegate>("GdipDrawImageRect");
- GdipDrawImagePointRect_ptr = LoadFunction<GdipDrawImagePointRect_delegate>("GdipDrawImagePointRect");
- GdipDrawImagePointRectI_ptr = LoadFunction<GdipDrawImagePointRectI_delegate>("GdipDrawImagePointRectI");
- GdipCreateHBITMAPFromBitmap_ptr = LoadFunction<GdipCreateHBITMAPFromBitmap_delegate>("GdipCreateHBITMAPFromBitmap");
- GdipCreateBitmapFromFile_ptr = LoadFunction<GdipCreateBitmapFromFile_delegate>("GdipCreateBitmapFromFile");
- GdipCreateBitmapFromFileICM_ptr = LoadFunction<GdipCreateBitmapFromFileICM_delegate>("GdipCreateBitmapFromFileICM");
- GdipCreateHICONFromBitmap_ptr = LoadFunction<GdipCreateHICONFromBitmap_delegate>("GdipCreateHICONFromBitmap");
- GdipCreateBitmapFromHICON_ptr = LoadFunction<GdipCreateBitmapFromHICON_delegate>("GdipCreateBitmapFromHICON");
- GdipCreateBitmapFromResource_ptr = LoadFunction<GdipCreateBitmapFromResource_delegate>("GdipCreateBitmapFromResource");
- GdipCreatePath_ptr = LoadFunction<GdipCreatePath_delegate>("GdipCreatePath");
- GdipCreatePath2_ptr = LoadFunction<GdipCreatePath2_delegate>("GdipCreatePath2");
- GdipCreatePath2I_ptr = LoadFunction<GdipCreatePath2I_delegate>("GdipCreatePath2I");
- GdipClonePath_ptr = LoadFunction<GdipClonePath_delegate>("GdipClonePath");
- GdipDeletePath_ptr = LoadFunction<GdipDeletePath_delegate>("GdipDeletePath");
- GdipResetPath_ptr = LoadFunction<GdipResetPath_delegate>("GdipResetPath");
- GdipGetPointCount_ptr = LoadFunction<GdipGetPointCount_delegate>("GdipGetPointCount");
- GdipGetPathTypes_ptr = LoadFunction<GdipGetPathTypes_delegate>("GdipGetPathTypes");
- GdipGetPathPoints_ptr = LoadFunction<GdipGetPathPoints_delegate>("GdipGetPathPoints");
- GdipGetPathPointsI_ptr = LoadFunction<GdipGetPathPointsI_delegate>("GdipGetPathPointsI");
- GdipGetPathFillMode_ptr = LoadFunction<GdipGetPathFillMode_delegate>("GdipGetPathFillMode");
- GdipSetPathFillMode_ptr = LoadFunction<GdipSetPathFillMode_delegate>("GdipSetPathFillMode");
- GdipStartPathFigure_ptr = LoadFunction<GdipStartPathFigure_delegate>("GdipStartPathFigure");
- GdipClosePathFigure_ptr = LoadFunction<GdipClosePathFigure_delegate>("GdipClosePathFigure");
- GdipClosePathFigures_ptr = LoadFunction<GdipClosePathFigures_delegate>("GdipClosePathFigures");
- GdipSetPathMarker_ptr = LoadFunction<GdipSetPathMarker_delegate>("GdipSetPathMarker");
- GdipClearPathMarkers_ptr = LoadFunction<GdipClearPathMarkers_delegate>("GdipClearPathMarkers");
- GdipReversePath_ptr = LoadFunction<GdipReversePath_delegate>("GdipReversePath");
- GdipGetPathLastPoint_ptr = LoadFunction<GdipGetPathLastPoint_delegate>("GdipGetPathLastPoint");
- GdipAddPathLine_ptr = LoadFunction<GdipAddPathLine_delegate>("GdipAddPathLine");
- GdipAddPathLine2_ptr = LoadFunction<GdipAddPathLine2_delegate>("GdipAddPathLine2");
- GdipAddPathLine2I_ptr = LoadFunction<GdipAddPathLine2I_delegate>("GdipAddPathLine2I");
- GdipAddPathArc_ptr = LoadFunction<GdipAddPathArc_delegate>("GdipAddPathArc");
- GdipAddPathBezier_ptr = LoadFunction<GdipAddPathBezier_delegate>("GdipAddPathBezier");
- GdipAddPathBeziers_ptr = LoadFunction<GdipAddPathBeziers_delegate>("GdipAddPathBeziers");
- GdipAddPathCurve_ptr = LoadFunction<GdipAddPathCurve_delegate>("GdipAddPathCurve");
- GdipAddPathCurveI_ptr = LoadFunction<GdipAddPathCurveI_delegate>("GdipAddPathCurveI");
- GdipAddPathCurve2_ptr = LoadFunction<GdipAddPathCurve2_delegate>("GdipAddPathCurve2");
- GdipAddPathCurve2I_ptr = LoadFunction<GdipAddPathCurve2I_delegate>("GdipAddPathCurve2I");
- GdipAddPathCurve3_ptr = LoadFunction<GdipAddPathCurve3_delegate>("GdipAddPathCurve3");
- GdipAddPathCurve3I_ptr = LoadFunction<GdipAddPathCurve3I_delegate>("GdipAddPathCurve3I");
- GdipAddPathClosedCurve_ptr = LoadFunction<GdipAddPathClosedCurve_delegate>("GdipAddPathClosedCurve");
- GdipAddPathClosedCurveI_ptr = LoadFunction<GdipAddPathClosedCurveI_delegate>("GdipAddPathClosedCurveI");
- GdipAddPathClosedCurve2_ptr = LoadFunction<GdipAddPathClosedCurve2_delegate>("GdipAddPathClosedCurve2");
- GdipAddPathClosedCurve2I_ptr = LoadFunction<GdipAddPathClosedCurve2I_delegate>("GdipAddPathClosedCurve2I");
- GdipAddPathRectangle_ptr = LoadFunction<GdipAddPathRectangle_delegate>("GdipAddPathRectangle");
- GdipAddPathRectangles_ptr = LoadFunction<GdipAddPathRectangles_delegate>("GdipAddPathRectangles");
- GdipAddPathEllipse_ptr = LoadFunction<GdipAddPathEllipse_delegate>("GdipAddPathEllipse");
- GdipAddPathEllipseI_ptr = LoadFunction<GdipAddPathEllipseI_delegate>("GdipAddPathEllipseI");
- GdipAddPathPie_ptr = LoadFunction<GdipAddPathPie_delegate>("GdipAddPathPie");
- GdipAddPathPieI_ptr = LoadFunction<GdipAddPathPieI_delegate>("GdipAddPathPieI");
- GdipAddPathPolygon_ptr = LoadFunction<GdipAddPathPolygon_delegate>("GdipAddPathPolygon");
- GdipAddPathPath_ptr = LoadFunction<GdipAddPathPath_delegate>("GdipAddPathPath");
- GdipAddPathLineI_ptr = LoadFunction<GdipAddPathLineI_delegate>("GdipAddPathLineI");
- GdipAddPathArcI_ptr = LoadFunction<GdipAddPathArcI_delegate>("GdipAddPathArcI");
- GdipAddPathBezierI_ptr = LoadFunction<GdipAddPathBezierI_delegate>("GdipAddPathBezierI");
- GdipAddPathBeziersI_ptr = LoadFunction<GdipAddPathBeziersI_delegate>("GdipAddPathBeziersI");
- GdipAddPathPolygonI_ptr = LoadFunction<GdipAddPathPolygonI_delegate>("GdipAddPathPolygonI");
- GdipAddPathRectangleI_ptr = LoadFunction<GdipAddPathRectangleI_delegate>("GdipAddPathRectangleI");
- GdipAddPathRectanglesI_ptr = LoadFunction<GdipAddPathRectanglesI_delegate>("GdipAddPathRectanglesI");
- GdipFlattenPath_ptr = LoadFunction<GdipFlattenPath_delegate>("GdipFlattenPath");
- GdipTransformPath_ptr = LoadFunction<GdipTransformPath_delegate>("GdipTransformPath");
- GdipWarpPath_ptr = LoadFunction<GdipWarpPath_delegate>("GdipWarpPath");
- GdipWidenPath_ptr = LoadFunction<GdipWidenPath_delegate>("GdipWidenPath");
- GdipGetPathWorldBounds_ptr = LoadFunction<GdipGetPathWorldBounds_delegate>("GdipGetPathWorldBounds");
- GdipGetPathWorldBoundsI_ptr = LoadFunction<GdipGetPathWorldBoundsI_delegate>("GdipGetPathWorldBoundsI");
- GdipIsVisiblePathPoint_ptr = LoadFunction<GdipIsVisiblePathPoint_delegate>("GdipIsVisiblePathPoint");
- GdipIsVisiblePathPointI_ptr = LoadFunction<GdipIsVisiblePathPointI_delegate>("GdipIsVisiblePathPointI");
- GdipIsOutlineVisiblePathPoint_ptr = LoadFunction<GdipIsOutlineVisiblePathPoint_delegate>("GdipIsOutlineVisiblePathPoint");
- GdipIsOutlineVisiblePathPointI_ptr = LoadFunction<GdipIsOutlineVisiblePathPointI_delegate>("GdipIsOutlineVisiblePathPointI");
- GdipCreateFont_ptr = LoadFunction<GdipCreateFont_delegate>("GdipCreateFont");
- GdipDeleteFont_ptr = LoadFunction<GdipDeleteFont_delegate>("GdipDeleteFont");
- GdipGetLogFont_ptr = LoadFunction<GdipGetLogFont_delegate>("GdipGetLogFontW");
- GdipCreateFontFromDC_ptr = LoadFunction<GdipCreateFontFromDC_delegate>("GdipCreateFontFromDC");
- GdipCreateFontFromLogfont_ptr = LoadFunction<GdipCreateFontFromLogfont_delegate>("GdipCreateFontFromLogfontW");
- GdipCreateFontFromHfont_ptr = LoadFunction<GdipCreateFontFromHfont_delegate>("GdipCreateFontFromHfontA");
- GdipCreateFontFamilyFromName_ptr = LoadFunction<GdipCreateFontFamilyFromName_delegate>("GdipCreateFontFamilyFromName");
- GdipGetFamilyName_ptr = LoadFunction<GdipGetFamilyName_delegate>("GdipGetFamilyName");
- GdipGetGenericFontFamilySansSerif_ptr = LoadFunction<GdipGetGenericFontFamilySansSerif_delegate>("GdipGetGenericFontFamilySansSerif");
- GdipGetGenericFontFamilySerif_ptr = LoadFunction<GdipGetGenericFontFamilySerif_delegate>("GdipGetGenericFontFamilySerif");
- GdipGetGenericFontFamilyMonospace_ptr = LoadFunction<GdipGetGenericFontFamilyMonospace_delegate>("GdipGetGenericFontFamilyMonospace");
- GdipGetCellAscent_ptr = LoadFunction<GdipGetCellAscent_delegate>("GdipGetCellAscent");
- GdipGetCellDescent_ptr = LoadFunction<GdipGetCellDescent_delegate>("GdipGetCellDescent");
- GdipGetLineSpacing_ptr = LoadFunction<GdipGetLineSpacing_delegate>("GdipGetLineSpacing");
- GdipGetEmHeight_ptr = LoadFunction<GdipGetEmHeight_delegate>("GdipGetEmHeight");
- GdipIsStyleAvailable_ptr = LoadFunction<GdipIsStyleAvailable_delegate>("GdipIsStyleAvailable");
- GdipDeleteFontFamily_ptr = LoadFunction<GdipDeleteFontFamily_delegate>("GdipDeleteFontFamily");
- GdipGetFontSize_ptr = LoadFunction<GdipGetFontSize_delegate>("GdipGetFontSize");
- GdipGetFontHeight_ptr = LoadFunction<GdipGetFontHeight_delegate>("GdipGetFontHeight");
- GdipGetFontHeightGivenDPI_ptr = LoadFunction<GdipGetFontHeightGivenDPI_delegate>("GdipGetFontHeightGivenDPI");
- GdipCreateMetafileFromFile_ptr = LoadFunction<GdipCreateMetafileFromFile_delegate>("GdipCreateMetafileFromFile");
- GdipCreateMetafileFromEmf_ptr = LoadFunction<GdipCreateMetafileFromEmf_delegate>("GdipCreateMetafileFromEmf");
- GdipCreateMetafileFromWmf_ptr = LoadFunction<GdipCreateMetafileFromWmf_delegate>("GdipCreateMetafileFromWmf");
- GdipGetMetafileHeaderFromFile_ptr = LoadFunction<GdipGetMetafileHeaderFromFile_delegate>("GdipGetMetafileHeaderFromFile");
- GdipGetMetafileHeaderFromMetafile_ptr = LoadFunction<GdipGetMetafileHeaderFromMetafile_delegate>("GdipGetMetafileHeaderFromMetafile");
- GdipGetMetafileHeaderFromEmf_ptr = LoadFunction<GdipGetMetafileHeaderFromEmf_delegate>("GdipGetMetafileHeaderFromEmf");
- GdipGetMetafileHeaderFromWmf_ptr = LoadFunction<GdipGetMetafileHeaderFromWmf_delegate>("GdipGetMetafileHeaderFromWmf");
- GdipGetHemfFromMetafile_ptr = LoadFunction<GdipGetHemfFromMetafile_delegate>("GdipGetHemfFromMetafile");
- GdipGetMetafileDownLevelRasterizationLimit_ptr = LoadFunction<GdipGetMetafileDownLevelRasterizationLimit_delegate>("GdipGetMetafileDownLevelRasterizationLimit");
- GdipSetMetafileDownLevelRasterizationLimit_ptr = LoadFunction<GdipSetMetafileDownLevelRasterizationLimit_delegate>("GdipSetMetafileDownLevelRasterizationLimit");
- GdipPlayMetafileRecord_ptr = LoadFunction<GdipPlayMetafileRecord_delegate>("GdipPlayMetafileRecord");
- GdipRecordMetafile_ptr = LoadFunction<GdipRecordMetafile_delegate>("GdipRecordMetafile");
- GdipRecordMetafileI_ptr = LoadFunction<GdipRecordMetafileI_delegate>("GdipRecordMetafileI");
- GdipRecordMetafileFileName_ptr = LoadFunction<GdipRecordMetafileFileName_delegate>("GdipRecordMetafileFileName");
- GdipRecordMetafileFileNameI_ptr = LoadFunction<GdipRecordMetafileFileNameI_delegate>("GdipRecordMetafileFileNameI");
- GdipCreateMetafileFromStream_ptr = LoadFunction<GdipCreateMetafileFromStream_delegate>("GdipCreateMetafileFromStream");
- GdipGetMetafileHeaderFromStream_ptr = LoadFunction<GdipGetMetafileHeaderFromStream_delegate>("GdipGetMetafileHeaderFromStream");
- GdipRecordMetafileStream_ptr = LoadFunction<GdipRecordMetafileStream_delegate>("GdipRecordMetafileStream");
- GdipRecordMetafileStreamI_ptr = LoadFunction<GdipRecordMetafileStreamI_delegate>("GdipRecordMetafileStreamI");
- GdipCreateFromContext_macosx_ptr = LoadFunction<GdipCreateFromContext_macosx_delegate>("GdipCreateFromContext_macosx");
- GdipSetVisibleClip_linux_ptr = LoadFunction<GdipSetVisibleClip_linux_delegate>("GdipSetVisibleClip_linux");
- GdipCreateFromXDrawable_linux_ptr = LoadFunction<GdipCreateFromXDrawable_linux_delegate>("GdipCreateFromXDrawable_linux");
- GdipLoadImageFromDelegate_linux_ptr = LoadFunction<GdipLoadImageFromDelegate_linux_delegate>("GdipLoadImageFromDelegate_linux");
- GdipSaveImageToDelegate_linux_ptr = LoadFunction<GdipSaveImageToDelegate_linux_delegate>("GdipSaveImageToDelegate_linux");
- GdipCreateMetafileFromDelegate_linux_ptr = LoadFunction<GdipCreateMetafileFromDelegate_linux_delegate>("GdipCreateMetafileFromDelegate_linux");
- GdipGetMetafileHeaderFromDelegate_linux_ptr = LoadFunction<GdipGetMetafileHeaderFromDelegate_linux_delegate>("GdipGetMetafileHeaderFromDelegate_linux");
- GdipRecordMetafileFromDelegate_linux_ptr = LoadFunction<GdipRecordMetafileFromDelegate_linux_delegate>("GdipRecordMetafileFromDelegate_linux");
- GdipRecordMetafileFromDelegateI_linux_ptr = LoadFunction<GdipRecordMetafileFromDelegateI_linux_delegate>("GdipRecordMetafileFromDelegateI_linux");
+ // Called all pending objects and claim any pending handle before
+ // shutting down
+ GC.Collect();
+ GC.WaitForPendingFinalizers();
+ }
+
+ private static void LoadFunctionPointers()
+ {
+ GdiplusStartup_ptr = FunctionWrapper.Load<GdiplusStartup_delegate>(s_gdipModule, "GdiplusStartup");
+ GdiplusShutdown_ptr = FunctionWrapper.Load<GdiplusShutdown_delegate>(s_gdipModule, "GdiplusShutdown");
+ GdipAlloc_ptr = FunctionWrapper.Load<GdipAlloc_delegate>(s_gdipModule, "GdipAlloc");
+ GdipFree_ptr = FunctionWrapper.Load<GdipFree_delegate>(s_gdipModule, "GdipFree");
+ GdipDeleteBrush_ptr = FunctionWrapper.Load<GdipDeleteBrush_delegate>(s_gdipModule, "GdipDeleteBrush");
+ GdipGetBrushType_ptr = FunctionWrapper.Load<GdipGetBrushType_delegate>(s_gdipModule, "GdipGetBrushType");
+ GdipCreateFromHDC_ptr = FunctionWrapper.Load<GdipCreateFromHDC_delegate>(s_gdipModule, "GdipCreateFromHDC");
+ GdipDeleteGraphics_ptr = FunctionWrapper.Load<GdipDeleteGraphics_delegate>(s_gdipModule, "GdipDeleteGraphics");
+ GdipRestoreGraphics_ptr = FunctionWrapper.Load<GdipRestoreGraphics_delegate>(s_gdipModule, "GdipRestoreGraphics");
+ GdipSaveGraphics_ptr = FunctionWrapper.Load<GdipSaveGraphics_delegate>(s_gdipModule, "GdipSaveGraphics");
+ GdipDrawArc_ptr = FunctionWrapper.Load<GdipDrawArc_delegate>(s_gdipModule, "GdipDrawArc");
+ GdipDrawArcI_ptr = FunctionWrapper.Load<GdipDrawArcI_delegate>(s_gdipModule, "GdipDrawArcI");
+ GdipDrawBezier_ptr = FunctionWrapper.Load<GdipDrawBezier_delegate>(s_gdipModule, "GdipDrawBezier");
+ GdipDrawBezierI_ptr = FunctionWrapper.Load<GdipDrawBezierI_delegate>(s_gdipModule, "GdipDrawBezierI");
+ GdipDrawEllipseI_ptr = FunctionWrapper.Load<GdipDrawEllipseI_delegate>(s_gdipModule, "GdipDrawEllipseI");
+ GdipDrawEllipse_ptr = FunctionWrapper.Load<GdipDrawEllipse_delegate>(s_gdipModule, "GdipDrawEllipse");
+ GdipDrawLine_ptr = FunctionWrapper.Load<GdipDrawLine_delegate>(s_gdipModule, "GdipDrawLine");
+ GdipDrawLineI_ptr = FunctionWrapper.Load<GdipDrawLineI_delegate>(s_gdipModule, "GdipDrawLineI");
+ GdipDrawLines_ptr = FunctionWrapper.Load<GdipDrawLines_delegate>(s_gdipModule, "GdipDrawLines");
+ GdipDrawLinesI_ptr = FunctionWrapper.Load<GdipDrawLinesI_delegate>(s_gdipModule, "GdipDrawLinesI");
+ GdipDrawPath_ptr = FunctionWrapper.Load<GdipDrawPath_delegate>(s_gdipModule, "GdipDrawPath");
+ GdipDrawPie_ptr = FunctionWrapper.Load<GdipDrawPie_delegate>(s_gdipModule, "GdipDrawPie");
+ GdipDrawPieI_ptr = FunctionWrapper.Load<GdipDrawPieI_delegate>(s_gdipModule, "GdipDrawPieI");
+ GdipDrawPolygon_ptr = FunctionWrapper.Load<GdipDrawPolygon_delegate>(s_gdipModule, "GdipDrawPolygon");
+ GdipDrawPolygonI_ptr = FunctionWrapper.Load<GdipDrawPolygonI_delegate>(s_gdipModule, "GdipDrawPolygonI");
+ GdipDrawRectangle_ptr = FunctionWrapper.Load<GdipDrawRectangle_delegate>(s_gdipModule, "GdipDrawRectangle");
+ GdipDrawRectangleI_ptr = FunctionWrapper.Load<GdipDrawRectangleI_delegate>(s_gdipModule, "GdipDrawRectangleI");
+ GdipDrawRectangles_ptr = FunctionWrapper.Load<GdipDrawRectangles_delegate>(s_gdipModule, "GdipDrawRectangles");
+ GdipDrawRectanglesI_ptr = FunctionWrapper.Load<GdipDrawRectanglesI_delegate>(s_gdipModule, "GdipDrawRectanglesI");
+ GdipFillEllipseI_ptr = FunctionWrapper.Load<GdipFillEllipseI_delegate>(s_gdipModule, "GdipFillEllipseI");
+ GdipFillEllipse_ptr = FunctionWrapper.Load<GdipFillEllipse_delegate>(s_gdipModule, "GdipFillEllipse");
+ GdipFillPolygon_ptr = FunctionWrapper.Load<GdipFillPolygon_delegate>(s_gdipModule, "GdipFillPolygon");
+ GdipFillPolygonI_ptr = FunctionWrapper.Load<GdipFillPolygonI_delegate>(s_gdipModule, "GdipFillPolygonI");
+ GdipFillPolygon2_ptr = FunctionWrapper.Load<GdipFillPolygon2_delegate>(s_gdipModule, "GdipFillPolygon2");
+ GdipFillPolygon2I_ptr = FunctionWrapper.Load<GdipFillPolygon2I_delegate>(s_gdipModule, "GdipFillPolygon2I");
+ GdipFillRectangle_ptr = FunctionWrapper.Load<GdipFillRectangle_delegate>(s_gdipModule, "GdipFillRectangle");
+ GdipFillRectangleI_ptr = FunctionWrapper.Load<GdipFillRectangleI_delegate>(s_gdipModule, "GdipFillRectangleI");
+ GdipFillRectangles_ptr = FunctionWrapper.Load<GdipFillRectangles_delegate>(s_gdipModule, "GdipFillRectangles");
+ GdipFillRectanglesI_ptr = FunctionWrapper.Load<GdipFillRectanglesI_delegate>(s_gdipModule, "GdipFillRectanglesI");
+ GdipDrawString_ptr = FunctionWrapper.Load<GdipDrawString_delegate>(s_gdipModule, "GdipDrawString");
+ GdipGetDC_ptr = FunctionWrapper.Load<GdipGetDC_delegate>(s_gdipModule, "GdipGetDC");
+ GdipReleaseDC_ptr = FunctionWrapper.Load<GdipReleaseDC_delegate>(s_gdipModule, "GdipReleaseDC");
+ GdipDrawImageRectI_ptr = FunctionWrapper.Load<GdipDrawImageRectI_delegate>(s_gdipModule, "GdipDrawImageRectI");
+ GdipGetRenderingOrigin_ptr = FunctionWrapper.Load<GdipGetRenderingOrigin_delegate>(s_gdipModule, "GdipGetRenderingOrigin");
+ GdipSetRenderingOrigin_ptr = FunctionWrapper.Load<GdipSetRenderingOrigin_delegate>(s_gdipModule, "GdipSetRenderingOrigin");
+ GdipCloneBitmapArea_ptr = FunctionWrapper.Load<GdipCloneBitmapArea_delegate>(s_gdipModule, "GdipCloneBitmapArea");
+ GdipCloneBitmapAreaI_ptr = FunctionWrapper.Load<GdipCloneBitmapAreaI_delegate>(s_gdipModule, "GdipCloneBitmapAreaI");
+ GdipGraphicsClear_ptr = FunctionWrapper.Load<GdipGraphicsClear_delegate>(s_gdipModule, "GdipGraphicsClear");
+ GdipDrawClosedCurve_ptr = FunctionWrapper.Load<GdipDrawClosedCurve_delegate>(s_gdipModule, "GdipDrawClosedCurve");
+ GdipDrawClosedCurveI_ptr = FunctionWrapper.Load<GdipDrawClosedCurveI_delegate>(s_gdipModule, "GdipDrawClosedCurveI");
+ GdipDrawClosedCurve2_ptr = FunctionWrapper.Load<GdipDrawClosedCurve2_delegate>(s_gdipModule, "GdipDrawClosedCurve2");
+ GdipDrawClosedCurve2I_ptr = FunctionWrapper.Load<GdipDrawClosedCurve2I_delegate>(s_gdipModule, "GdipDrawClosedCurve2I");
+ GdipDrawCurve_ptr = FunctionWrapper.Load<GdipDrawCurve_delegate>(s_gdipModule, "GdipDrawCurve");
+ GdipDrawCurveI_ptr = FunctionWrapper.Load<GdipDrawCurveI_delegate>(s_gdipModule, "GdipDrawCurveI");
+ GdipDrawCurve2_ptr = FunctionWrapper.Load<GdipDrawCurve2_delegate>(s_gdipModule, "GdipDrawCurve2");
+ GdipDrawCurve2I_ptr = FunctionWrapper.Load<GdipDrawCurve2I_delegate>(s_gdipModule, "GdipDrawCurve2I");
+ GdipDrawCurve3_ptr = FunctionWrapper.Load<GdipDrawCurve3_delegate>(s_gdipModule, "GdipDrawCurve3");
+ GdipDrawCurve3I_ptr = FunctionWrapper.Load<GdipDrawCurve3I_delegate>(s_gdipModule, "GdipDrawCurve3I");
+ GdipFillClosedCurve_ptr = FunctionWrapper.Load<GdipFillClosedCurve_delegate>(s_gdipModule, "GdipFillClosedCurve");
+ GdipFillClosedCurveI_ptr = FunctionWrapper.Load<GdipFillClosedCurveI_delegate>(s_gdipModule, "GdipFillClosedCurveI");
+ GdipFillClosedCurve2_ptr = FunctionWrapper.Load<GdipFillClosedCurve2_delegate>(s_gdipModule, "GdipFillClosedCurve2");
+ GdipFillClosedCurve2I_ptr = FunctionWrapper.Load<GdipFillClosedCurve2I_delegate>(s_gdipModule, "GdipFillClosedCurve2I");
+ GdipFillPie_ptr = FunctionWrapper.Load<GdipFillPie_delegate>(s_gdipModule, "GdipFillPie");
+ GdipFillPieI_ptr = FunctionWrapper.Load<GdipFillPieI_delegate>(s_gdipModule, "GdipFillPieI");
+ GdipFillPath_ptr = FunctionWrapper.Load<GdipFillPath_delegate>(s_gdipModule, "GdipFillPath");
+ GdipGetNearestColor_ptr = FunctionWrapper.Load<GdipGetNearestColor_delegate>(s_gdipModule, "GdipGetNearestColor");
+ GdipTransformPoints_ptr = FunctionWrapper.Load<GdipTransformPoints_delegate>(s_gdipModule, "GdipTransformPoints");
+ GdipTransformPointsI_ptr = FunctionWrapper.Load<GdipTransformPointsI_delegate>(s_gdipModule, "GdipTransformPointsI");
+ GdipSetCompositingMode_ptr = FunctionWrapper.Load<GdipSetCompositingMode_delegate>(s_gdipModule, "GdipSetCompositingMode");
+ GdipGetCompositingMode_ptr = FunctionWrapper.Load<GdipGetCompositingMode_delegate>(s_gdipModule, "GdipGetCompositingMode");
+ GdipSetCompositingQuality_ptr = FunctionWrapper.Load<GdipSetCompositingQuality_delegate>(s_gdipModule, "GdipSetCompositingQuality");
+ GdipGetCompositingQuality_ptr = FunctionWrapper.Load<GdipGetCompositingQuality_delegate>(s_gdipModule, "GdipGetCompositingQuality");
+ GdipSetInterpolationMode_ptr = FunctionWrapper.Load<GdipSetInterpolationMode_delegate>(s_gdipModule, "GdipSetInterpolationMode");
+ GdipGetInterpolationMode_ptr = FunctionWrapper.Load<GdipGetInterpolationMode_delegate>(s_gdipModule, "GdipGetInterpolationMode");
+ GdipGetDpiX_ptr = FunctionWrapper.Load<GdipGetDpiX_delegate>(s_gdipModule, "GdipGetDpiX");
+ GdipGetDpiY_ptr = FunctionWrapper.Load<GdipGetDpiY_delegate>(s_gdipModule, "GdipGetDpiY");
+ GdipGetPageUnit_ptr = FunctionWrapper.Load<GdipGetPageUnit_delegate>(s_gdipModule, "GdipGetPageUnit");
+ GdipGetPageScale_ptr = FunctionWrapper.Load<GdipGetPageScale_delegate>(s_gdipModule, "GdipGetPageScale");
+ GdipSetPageUnit_ptr = FunctionWrapper.Load<GdipSetPageUnit_delegate>(s_gdipModule, "GdipSetPageUnit");
+ GdipSetPageScale_ptr = FunctionWrapper.Load<GdipSetPageScale_delegate>(s_gdipModule, "GdipSetPageScale");
+ GdipSetPixelOffsetMode_ptr = FunctionWrapper.Load<GdipSetPixelOffsetMode_delegate>(s_gdipModule, "GdipSetPixelOffsetMode");
+ GdipGetPixelOffsetMode_ptr = FunctionWrapper.Load<GdipGetPixelOffsetMode_delegate>(s_gdipModule, "GdipGetPixelOffsetMode");
+ GdipSetSmoothingMode_ptr = FunctionWrapper.Load<GdipSetSmoothingMode_delegate>(s_gdipModule, "GdipSetSmoothingMode");
+ GdipGetSmoothingMode_ptr = FunctionWrapper.Load<GdipGetSmoothingMode_delegate>(s_gdipModule, "GdipGetSmoothingMode");
+ GdipSetTextContrast_ptr = FunctionWrapper.Load<GdipSetTextContrast_delegate>(s_gdipModule, "GdipSetTextContrast");
+ GdipGetTextContrast_ptr = FunctionWrapper.Load<GdipGetTextContrast_delegate>(s_gdipModule, "GdipGetTextContrast");
+ GdipSetTextRenderingHint_ptr = FunctionWrapper.Load<GdipSetTextRenderingHint_delegate>(s_gdipModule, "GdipSetTextRenderingHint");
+ GdipGetTextRenderingHint_ptr = FunctionWrapper.Load<GdipGetTextRenderingHint_delegate>(s_gdipModule, "GdipGetTextRenderingHint");
+ GdipFlush_ptr = FunctionWrapper.Load<GdipFlush_delegate>(s_gdipModule, "GdipFlush");
+ GdipAddPathString_ptr = FunctionWrapper.Load<GdipAddPathString_delegate>(s_gdipModule, "GdipAddPathString");
+ GdipAddPathStringI_ptr = FunctionWrapper.Load<GdipAddPathStringI_delegate>(s_gdipModule, "GdipAddPathStringI");
+ GdipCreateFromHWND_ptr = FunctionWrapper.Load<GdipCreateFromHWND_delegate>(s_gdipModule, "GdipCreateFromHWND");
+ GdipMeasureString_ptr = FunctionWrapper.Load<GdipMeasureString_delegate>(s_gdipModule, "GdipMeasureString");
+ GdipMeasureCharacterRanges_ptr = FunctionWrapper.Load<GdipMeasureCharacterRanges_delegate>(s_gdipModule, "GdipMeasureCharacterRanges");
+ GdipCreateBitmapFromScan0_ptr = FunctionWrapper.Load<GdipCreateBitmapFromScan0_delegate>(s_gdipModule, "GdipCreateBitmapFromScan0");
+ GdipCreateBitmapFromGraphics_ptr = FunctionWrapper.Load<GdipCreateBitmapFromGraphics_delegate>(s_gdipModule, "GdipCreateBitmapFromGraphics");
+ GdipBitmapLockBits_ptr = FunctionWrapper.Load<GdipBitmapLockBits_delegate>(s_gdipModule, "GdipBitmapLockBits");
+ GdipBitmapSetResolution_ptr = FunctionWrapper.Load<GdipBitmapSetResolution_delegate>(s_gdipModule, "GdipBitmapSetResolution");
+ GdipBitmapUnlockBits_ptr = FunctionWrapper.Load<GdipBitmapUnlockBits_delegate>(s_gdipModule, "GdipBitmapUnlockBits");
+ GdipBitmapGetPixel_ptr = FunctionWrapper.Load<GdipBitmapGetPixel_delegate>(s_gdipModule, "GdipBitmapGetPixel");
+ GdipBitmapSetPixel_ptr = FunctionWrapper.Load<GdipBitmapSetPixel_delegate>(s_gdipModule, "GdipBitmapSetPixel");
+ GdipLoadImageFromFile_ptr = FunctionWrapper.Load<GdipLoadImageFromFile_delegate>(s_gdipModule, "GdipLoadImageFromFile");
+ GdipCloneImage_ptr = FunctionWrapper.Load<GdipCloneImage_delegate>(s_gdipModule, "GdipCloneImage");
+ GdipLoadImageFromFileICM_ptr = FunctionWrapper.Load<GdipLoadImageFromFileICM_delegate>(s_gdipModule, "GdipLoadImageFromFileICM");
+ GdipCreateBitmapFromHBITMAP_ptr = FunctionWrapper.Load<GdipCreateBitmapFromHBITMAP_delegate>(s_gdipModule, "GdipCreateBitmapFromHBITMAP");
+ GdipDisposeImage_ptr = FunctionWrapper.Load<GdipDisposeImage_delegate>(s_gdipModule, "GdipDisposeImage");
+ GdipGetImageFlags_ptr = FunctionWrapper.Load<GdipGetImageFlags_delegate>(s_gdipModule, "GdipGetImageFlags");
+ GdipGetImageType_ptr = FunctionWrapper.Load<GdipGetImageType_delegate>(s_gdipModule, "GdipGetImageType");
+ GdipImageGetFrameDimensionsCount_ptr = FunctionWrapper.Load<GdipImageGetFrameDimensionsCount_delegate>(s_gdipModule, "GdipImageGetFrameDimensionsCount");
+ GdipImageGetFrameDimensionsList_ptr = FunctionWrapper.Load<GdipImageGetFrameDimensionsList_delegate>(s_gdipModule, "GdipImageGetFrameDimensionsList");
+ GdipGetImageHeight_ptr = FunctionWrapper.Load<GdipGetImageHeight_delegate>(s_gdipModule, "GdipGetImageHeight");
+ GdipGetImageHorizontalResolution_ptr = FunctionWrapper.Load<GdipGetImageHorizontalResolution_delegate>(s_gdipModule, "GdipGetImageHorizontalResolution");
+ GdipGetImagePaletteSize_ptr = FunctionWrapper.Load<GdipGetImagePaletteSize_delegate>(s_gdipModule, "GdipGetImagePaletteSize");
+ GdipGetImagePalette_ptr = FunctionWrapper.Load<GdipGetImagePalette_delegate>(s_gdipModule, "GdipGetImagePalette");
+ GdipSetImagePalette_ptr = FunctionWrapper.Load<GdipSetImagePalette_delegate>(s_gdipModule, "GdipSetImagePalette");
+ GdipGetImageDimension_ptr = FunctionWrapper.Load<GdipGetImageDimension_delegate>(s_gdipModule, "GdipGetImageDimension");
+ GdipGetImagePixelFormat_ptr = FunctionWrapper.Load<GdipGetImagePixelFormat_delegate>(s_gdipModule, "GdipGetImagePixelFormat");
+ GdipGetPropertyCount_ptr = FunctionWrapper.Load<GdipGetPropertyCount_delegate>(s_gdipModule, "GdipGetPropertyCount");
+ GdipGetPropertyIdList_ptr = FunctionWrapper.Load<GdipGetPropertyIdList_delegate>(s_gdipModule, "GdipGetPropertyIdList");
+ GdipGetPropertySize_ptr = FunctionWrapper.Load<GdipGetPropertySize_delegate>(s_gdipModule, "GdipGetPropertySize");
+ GdipGetAllPropertyItems_ptr = FunctionWrapper.Load<GdipGetAllPropertyItems_delegate>(s_gdipModule, "GdipGetAllPropertyItems");
+ GdipGetImageRawFormat_ptr = FunctionWrapper.Load<GdipGetImageRawFormat_delegate>(s_gdipModule, "GdipGetImageRawFormat");
+ GdipGetImageVerticalResolution_ptr = FunctionWrapper.Load<GdipGetImageVerticalResolution_delegate>(s_gdipModule, "GdipGetImageVerticalResolution");
+ GdipGetImageWidth_ptr = FunctionWrapper.Load<GdipGetImageWidth_delegate>(s_gdipModule, "GdipGetImageWidth");
+ GdipGetImageBounds_ptr = FunctionWrapper.Load<GdipGetImageBounds_delegate>(s_gdipModule, "GdipGetImageBounds");
+ GdipGetEncoderParameterListSize_ptr = FunctionWrapper.Load<GdipGetEncoderParameterListSize_delegate>(s_gdipModule, "GdipGetEncoderParameterListSize");
+ GdipGetEncoderParameterList_ptr = FunctionWrapper.Load<GdipGetEncoderParameterList_delegate>(s_gdipModule, "GdipGetEncoderParameterList");
+ GdipImageGetFrameCount_ptr = FunctionWrapper.Load<GdipImageGetFrameCount_delegate>(s_gdipModule, "GdipImageGetFrameCount");
+ GdipImageSelectActiveFrame_ptr = FunctionWrapper.Load<GdipImageSelectActiveFrame_delegate>(s_gdipModule, "GdipImageSelectActiveFrame");
+ GdipGetPropertyItemSize_ptr = FunctionWrapper.Load<GdipGetPropertyItemSize_delegate>(s_gdipModule, "GdipGetPropertyItemSize");
+ GdipGetPropertyItem_ptr = FunctionWrapper.Load<GdipGetPropertyItem_delegate>(s_gdipModule, "GdipGetPropertyItem");
+ GdipRemovePropertyItem_ptr = FunctionWrapper.Load<GdipRemovePropertyItem_delegate>(s_gdipModule, "GdipRemovePropertyItem");
+ GdipSetPropertyItem_ptr = FunctionWrapper.Load<GdipSetPropertyItem_delegate>(s_gdipModule, "GdipSetPropertyItem");
+ GdipGetImageThumbnail_ptr = FunctionWrapper.Load<GdipGetImageThumbnail_delegate>(s_gdipModule, "GdipGetImageThumbnail");
+ GdipImageRotateFlip_ptr = FunctionWrapper.Load<GdipImageRotateFlip_delegate>(s_gdipModule, "GdipImageRotateFlip");
+ GdipSaveImageToFile_ptr = FunctionWrapper.Load<GdipSaveImageToFile_delegate>(s_gdipModule, "GdipSaveImageToFile");
+ GdipSaveAdd_ptr = FunctionWrapper.Load<GdipSaveAdd_delegate>(s_gdipModule, "GdipSaveAdd");
+ GdipSaveAddImage_ptr = FunctionWrapper.Load<GdipSaveAddImage_delegate>(s_gdipModule, "GdipSaveAddImage");
+ GdipDrawImageI_ptr = FunctionWrapper.Load<GdipDrawImageI_delegate>(s_gdipModule, "GdipDrawImageI");
+ GdipGetImageGraphicsContext_ptr = FunctionWrapper.Load<GdipGetImageGraphicsContext_delegate>(s_gdipModule, "GdipGetImageGraphicsContext");
+ GdipDrawImage_ptr = FunctionWrapper.Load<GdipDrawImage_delegate>(s_gdipModule, "GdipDrawImage");
+ GdipDrawImagePoints_ptr = FunctionWrapper.Load<GdipDrawImagePoints_delegate>(s_gdipModule, "GdipDrawImagePoints");
+ GdipDrawImagePointsI_ptr = FunctionWrapper.Load<GdipDrawImagePointsI_delegate>(s_gdipModule, "GdipDrawImagePointsI");
+ GdipDrawImageRectRectI_ptr = FunctionWrapper.Load<GdipDrawImageRectRectI_delegate>(s_gdipModule, "GdipDrawImageRectRectI");
+ GdipDrawImageRectRect_ptr = FunctionWrapper.Load<GdipDrawImageRectRect_delegate>(s_gdipModule, "GdipDrawImageRectRect");
+ GdipDrawImagePointsRectI_ptr = FunctionWrapper.Load<GdipDrawImagePointsRectI_delegate>(s_gdipModule, "GdipDrawImagePointsRectI");
+ GdipDrawImagePointsRect_ptr = FunctionWrapper.Load<GdipDrawImagePointsRect_delegate>(s_gdipModule, "GdipDrawImagePointsRect");
+ GdipDrawImageRect_ptr = FunctionWrapper.Load<GdipDrawImageRect_delegate>(s_gdipModule, "GdipDrawImageRect");
+ GdipDrawImagePointRect_ptr = FunctionWrapper.Load<GdipDrawImagePointRect_delegate>(s_gdipModule, "GdipDrawImagePointRect");
+ GdipDrawImagePointRectI_ptr = FunctionWrapper.Load<GdipDrawImagePointRectI_delegate>(s_gdipModule, "GdipDrawImagePointRectI");
+ GdipCreateHBITMAPFromBitmap_ptr = FunctionWrapper.Load<GdipCreateHBITMAPFromBitmap_delegate>(s_gdipModule, "GdipCreateHBITMAPFromBitmap");
+ GdipCreateBitmapFromFile_ptr = FunctionWrapper.Load<GdipCreateBitmapFromFile_delegate>(s_gdipModule, "GdipCreateBitmapFromFile");
+ GdipCreateBitmapFromFileICM_ptr = FunctionWrapper.Load<GdipCreateBitmapFromFileICM_delegate>(s_gdipModule, "GdipCreateBitmapFromFileICM");
+ GdipCreateHICONFromBitmap_ptr = FunctionWrapper.Load<GdipCreateHICONFromBitmap_delegate>(s_gdipModule, "GdipCreateHICONFromBitmap");
+ GdipCreateBitmapFromHICON_ptr = FunctionWrapper.Load<GdipCreateBitmapFromHICON_delegate>(s_gdipModule, "GdipCreateBitmapFromHICON");
+ GdipCreateBitmapFromResource_ptr = FunctionWrapper.Load<GdipCreateBitmapFromResource_delegate>(s_gdipModule, "GdipCreateBitmapFromResource");
+ GdipCreatePath_ptr = FunctionWrapper.Load<GdipCreatePath_delegate>(s_gdipModule, "GdipCreatePath");
+ GdipCreatePath2_ptr = FunctionWrapper.Load<GdipCreatePath2_delegate>(s_gdipModule, "GdipCreatePath2");
+ GdipCreatePath2I_ptr = FunctionWrapper.Load<GdipCreatePath2I_delegate>(s_gdipModule, "GdipCreatePath2I");
+ GdipClonePath_ptr = FunctionWrapper.Load<GdipClonePath_delegate>(s_gdipModule, "GdipClonePath");
+ GdipDeletePath_ptr = FunctionWrapper.Load<GdipDeletePath_delegate>(s_gdipModule, "GdipDeletePath");
+ GdipResetPath_ptr = FunctionWrapper.Load<GdipResetPath_delegate>(s_gdipModule, "GdipResetPath");
+ GdipGetPointCount_ptr = FunctionWrapper.Load<GdipGetPointCount_delegate>(s_gdipModule, "GdipGetPointCount");
+ GdipGetPathTypes_ptr = FunctionWrapper.Load<GdipGetPathTypes_delegate>(s_gdipModule, "GdipGetPathTypes");
+ GdipGetPathPoints_ptr = FunctionWrapper.Load<GdipGetPathPoints_delegate>(s_gdipModule, "GdipGetPathPoints");
+ GdipGetPathPointsI_ptr = FunctionWrapper.Load<GdipGetPathPointsI_delegate>(s_gdipModule, "GdipGetPathPointsI");
+ GdipGetPathFillMode_ptr = FunctionWrapper.Load<GdipGetPathFillMode_delegate>(s_gdipModule, "GdipGetPathFillMode");
+ GdipSetPathFillMode_ptr = FunctionWrapper.Load<GdipSetPathFillMode_delegate>(s_gdipModule, "GdipSetPathFillMode");
+ GdipStartPathFigure_ptr = FunctionWrapper.Load<GdipStartPathFigure_delegate>(s_gdipModule, "GdipStartPathFigure");
+ GdipClosePathFigure_ptr = FunctionWrapper.Load<GdipClosePathFigure_delegate>(s_gdipModule, "GdipClosePathFigure");
+ GdipClosePathFigures_ptr = FunctionWrapper.Load<GdipClosePathFigures_delegate>(s_gdipModule, "GdipClosePathFigures");
+ GdipSetPathMarker_ptr = FunctionWrapper.Load<GdipSetPathMarker_delegate>(s_gdipModule, "GdipSetPathMarker");
+ GdipClearPathMarkers_ptr = FunctionWrapper.Load<GdipClearPathMarkers_delegate>(s_gdipModule, "GdipClearPathMarkers");
+ GdipReversePath_ptr = FunctionWrapper.Load<GdipReversePath_delegate>(s_gdipModule, "GdipReversePath");
+ GdipGetPathLastPoint_ptr = FunctionWrapper.Load<GdipGetPathLastPoint_delegate>(s_gdipModule, "GdipGetPathLastPoint");
+ GdipAddPathLine_ptr = FunctionWrapper.Load<GdipAddPathLine_delegate>(s_gdipModule, "GdipAddPathLine");
+ GdipAddPathLine2_ptr = FunctionWrapper.Load<GdipAddPathLine2_delegate>(s_gdipModule, "GdipAddPathLine2");
+ GdipAddPathLine2I_ptr = FunctionWrapper.Load<GdipAddPathLine2I_delegate>(s_gdipModule, "GdipAddPathLine2I");
+ GdipAddPathArc_ptr = FunctionWrapper.Load<GdipAddPathArc_delegate>(s_gdipModule, "GdipAddPathArc");
+ GdipAddPathBezier_ptr = FunctionWrapper.Load<GdipAddPathBezier_delegate>(s_gdipModule, "GdipAddPathBezier");
+ GdipAddPathBeziers_ptr = FunctionWrapper.Load<GdipAddPathBeziers_delegate>(s_gdipModule, "GdipAddPathBeziers");
+ GdipAddPathCurve_ptr = FunctionWrapper.Load<GdipAddPathCurve_delegate>(s_gdipModule, "GdipAddPathCurve");
+ GdipAddPathCurveI_ptr = FunctionWrapper.Load<GdipAddPathCurveI_delegate>(s_gdipModule, "GdipAddPathCurveI");
+ GdipAddPathCurve2_ptr = FunctionWrapper.Load<GdipAddPathCurve2_delegate>(s_gdipModule, "GdipAddPathCurve2");
+ GdipAddPathCurve2I_ptr = FunctionWrapper.Load<GdipAddPathCurve2I_delegate>(s_gdipModule, "GdipAddPathCurve2I");
+ GdipAddPathCurve3_ptr = FunctionWrapper.Load<GdipAddPathCurve3_delegate>(s_gdipModule, "GdipAddPathCurve3");
+ GdipAddPathCurve3I_ptr = FunctionWrapper.Load<GdipAddPathCurve3I_delegate>(s_gdipModule, "GdipAddPathCurve3I");
+ GdipAddPathClosedCurve_ptr = FunctionWrapper.Load<GdipAddPathClosedCurve_delegate>(s_gdipModule, "GdipAddPathClosedCurve");
+ GdipAddPathClosedCurveI_ptr = FunctionWrapper.Load<GdipAddPathClosedCurveI_delegate>(s_gdipModule, "GdipAddPathClosedCurveI");
+ GdipAddPathClosedCurve2_ptr = FunctionWrapper.Load<GdipAddPathClosedCurve2_delegate>(s_gdipModule, "GdipAddPathClosedCurve2");
+ GdipAddPathClosedCurve2I_ptr = FunctionWrapper.Load<GdipAddPathClosedCurve2I_delegate>(s_gdipModule, "GdipAddPathClosedCurve2I");
+ GdipAddPathRectangle_ptr = FunctionWrapper.Load<GdipAddPathRectangle_delegate>(s_gdipModule, "GdipAddPathRectangle");
+ GdipAddPathRectangles_ptr = FunctionWrapper.Load<GdipAddPathRectangles_delegate>(s_gdipModule, "GdipAddPathRectangles");
+ GdipAddPathEllipse_ptr = FunctionWrapper.Load<GdipAddPathEllipse_delegate>(s_gdipModule, "GdipAddPathEllipse");
+ GdipAddPathEllipseI_ptr = FunctionWrapper.Load<GdipAddPathEllipseI_delegate>(s_gdipModule, "GdipAddPathEllipseI");
+ GdipAddPathPie_ptr = FunctionWrapper.Load<GdipAddPathPie_delegate>(s_gdipModule, "GdipAddPathPie");
+ GdipAddPathPieI_ptr = FunctionWrapper.Load<GdipAddPathPieI_delegate>(s_gdipModule, "GdipAddPathPieI");
+ GdipAddPathPolygon_ptr = FunctionWrapper.Load<GdipAddPathPolygon_delegate>(s_gdipModule, "GdipAddPathPolygon");
+ GdipAddPathPath_ptr = FunctionWrapper.Load<GdipAddPathPath_delegate>(s_gdipModule, "GdipAddPathPath");
+ GdipAddPathLineI_ptr = FunctionWrapper.Load<GdipAddPathLineI_delegate>(s_gdipModule, "GdipAddPathLineI");
+ GdipAddPathArcI_ptr = FunctionWrapper.Load<GdipAddPathArcI_delegate>(s_gdipModule, "GdipAddPathArcI");
+ GdipAddPathBezierI_ptr = FunctionWrapper.Load<GdipAddPathBezierI_delegate>(s_gdipModule, "GdipAddPathBezierI");
+ GdipAddPathBeziersI_ptr = FunctionWrapper.Load<GdipAddPathBeziersI_delegate>(s_gdipModule, "GdipAddPathBeziersI");
+ GdipAddPathPolygonI_ptr = FunctionWrapper.Load<GdipAddPathPolygonI_delegate>(s_gdipModule, "GdipAddPathPolygonI");
+ GdipAddPathRectangleI_ptr = FunctionWrapper.Load<GdipAddPathRectangleI_delegate>(s_gdipModule, "GdipAddPathRectangleI");
+ GdipAddPathRectanglesI_ptr = FunctionWrapper.Load<GdipAddPathRectanglesI_delegate>(s_gdipModule, "GdipAddPathRectanglesI");
+ GdipFlattenPath_ptr = FunctionWrapper.Load<GdipFlattenPath_delegate>(s_gdipModule, "GdipFlattenPath");
+ GdipTransformPath_ptr = FunctionWrapper.Load<GdipTransformPath_delegate>(s_gdipModule, "GdipTransformPath");
+ GdipWarpPath_ptr = FunctionWrapper.Load<GdipWarpPath_delegate>(s_gdipModule, "GdipWarpPath");
+ GdipWidenPath_ptr = FunctionWrapper.Load<GdipWidenPath_delegate>(s_gdipModule, "GdipWidenPath");
+ GdipGetPathWorldBounds_ptr = FunctionWrapper.Load<GdipGetPathWorldBounds_delegate>(s_gdipModule, "GdipGetPathWorldBounds");
+ GdipGetPathWorldBoundsI_ptr = FunctionWrapper.Load<GdipGetPathWorldBoundsI_delegate>(s_gdipModule, "GdipGetPathWorldBoundsI");
+ GdipIsVisiblePathPoint_ptr = FunctionWrapper.Load<GdipIsVisiblePathPoint_delegate>(s_gdipModule, "GdipIsVisiblePathPoint");
+ GdipIsVisiblePathPointI_ptr = FunctionWrapper.Load<GdipIsVisiblePathPointI_delegate>(s_gdipModule, "GdipIsVisiblePathPointI");
+ GdipIsOutlineVisiblePathPoint_ptr = FunctionWrapper.Load<GdipIsOutlineVisiblePathPoint_delegate>(s_gdipModule, "GdipIsOutlineVisiblePathPoint");
+ GdipIsOutlineVisiblePathPointI_ptr = FunctionWrapper.Load<GdipIsOutlineVisiblePathPointI_delegate>(s_gdipModule, "GdipIsOutlineVisiblePathPointI");
+ GdipCreateFont_ptr = FunctionWrapper.Load<GdipCreateFont_delegate>(s_gdipModule, "GdipCreateFont");
+ GdipDeleteFont_ptr = FunctionWrapper.Load<GdipDeleteFont_delegate>(s_gdipModule, "GdipDeleteFont");
+ GdipGetLogFont_ptr = FunctionWrapper.Load<GdipGetLogFont_delegate>(s_gdipModule, "GdipGetLogFontW");
+ GdipCreateFontFromDC_ptr = FunctionWrapper.Load<GdipCreateFontFromDC_delegate>(s_gdipModule, "GdipCreateFontFromDC");
+ GdipCreateFontFromLogfont_ptr = FunctionWrapper.Load<GdipCreateFontFromLogfont_delegate>(s_gdipModule, "GdipCreateFontFromLogfontW");
+ GdipCreateFontFromHfont_ptr = FunctionWrapper.Load<GdipCreateFontFromHfont_delegate>(s_gdipModule, "GdipCreateFontFromHfontA");
+ GdipGetFontSize_ptr = FunctionWrapper.Load<GdipGetFontSize_delegate>(s_gdipModule, "GdipGetFontSize");
+ GdipGetFontHeight_ptr = FunctionWrapper.Load<GdipGetFontHeight_delegate>(s_gdipModule, "GdipGetFontHeight");
+ GdipGetFontHeightGivenDPI_ptr = FunctionWrapper.Load<GdipGetFontHeightGivenDPI_delegate>(s_gdipModule, "GdipGetFontHeightGivenDPI");
+ GdipCreateMetafileFromFile_ptr = FunctionWrapper.Load<GdipCreateMetafileFromFile_delegate>(s_gdipModule, "GdipCreateMetafileFromFile");
+ GdipCreateMetafileFromEmf_ptr = FunctionWrapper.Load<GdipCreateMetafileFromEmf_delegate>(s_gdipModule, "GdipCreateMetafileFromEmf");
+ GdipCreateMetafileFromWmf_ptr = FunctionWrapper.Load<GdipCreateMetafileFromWmf_delegate>(s_gdipModule, "GdipCreateMetafileFromWmf");
+ GdipGetMetafileHeaderFromFile_ptr = FunctionWrapper.Load<GdipGetMetafileHeaderFromFile_delegate>(s_gdipModule, "GdipGetMetafileHeaderFromFile");
+ GdipGetMetafileHeaderFromMetafile_ptr = FunctionWrapper.Load<GdipGetMetafileHeaderFromMetafile_delegate>(s_gdipModule, "GdipGetMetafileHeaderFromMetafile");
+ GdipGetMetafileHeaderFromEmf_ptr = FunctionWrapper.Load<GdipGetMetafileHeaderFromEmf_delegate>(s_gdipModule, "GdipGetMetafileHeaderFromEmf");
+ GdipGetMetafileHeaderFromWmf_ptr = FunctionWrapper.Load<GdipGetMetafileHeaderFromWmf_delegate>(s_gdipModule, "GdipGetMetafileHeaderFromWmf");
+ GdipGetHemfFromMetafile_ptr = FunctionWrapper.Load<GdipGetHemfFromMetafile_delegate>(s_gdipModule, "GdipGetHemfFromMetafile");
+ GdipGetMetafileDownLevelRasterizationLimit_ptr = FunctionWrapper.Load<GdipGetMetafileDownLevelRasterizationLimit_delegate>(s_gdipModule, "GdipGetMetafileDownLevelRasterizationLimit");
+ GdipSetMetafileDownLevelRasterizationLimit_ptr = FunctionWrapper.Load<GdipSetMetafileDownLevelRasterizationLimit_delegate>(s_gdipModule, "GdipSetMetafileDownLevelRasterizationLimit");
+ GdipPlayMetafileRecord_ptr = FunctionWrapper.Load<GdipPlayMetafileRecord_delegate>(s_gdipModule, "GdipPlayMetafileRecord");
+ GdipRecordMetafile_ptr = FunctionWrapper.Load<GdipRecordMetafile_delegate>(s_gdipModule, "GdipRecordMetafile");
+ GdipRecordMetafileI_ptr = FunctionWrapper.Load<GdipRecordMetafileI_delegate>(s_gdipModule, "GdipRecordMetafileI");
+ GdipRecordMetafileFileName_ptr = FunctionWrapper.Load<GdipRecordMetafileFileName_delegate>(s_gdipModule, "GdipRecordMetafileFileName");
+ GdipRecordMetafileFileNameI_ptr = FunctionWrapper.Load<GdipRecordMetafileFileNameI_delegate>(s_gdipModule, "GdipRecordMetafileFileNameI");
+ GdipCreateFromContext_macosx_ptr = FunctionWrapper.Load<GdipCreateFromContext_macosx_delegate>(s_gdipModule, "GdipCreateFromContext_macosx");
+ GdipSetVisibleClip_linux_ptr = FunctionWrapper.Load<GdipSetVisibleClip_linux_delegate>(s_gdipModule, "GdipSetVisibleClip_linux");
+ GdipCreateFromXDrawable_linux_ptr = FunctionWrapper.Load<GdipCreateFromXDrawable_linux_delegate>(s_gdipModule, "GdipCreateFromXDrawable_linux");
+ GdipLoadImageFromDelegate_linux_ptr = FunctionWrapper.Load<GdipLoadImageFromDelegate_linux_delegate>(s_gdipModule, "GdipLoadImageFromDelegate_linux");
+ GdipSaveImageToDelegate_linux_ptr = FunctionWrapper.Load<GdipSaveImageToDelegate_linux_delegate>(s_gdipModule, "GdipSaveImageToDelegate_linux");
+ GdipCreateMetafileFromDelegate_linux_ptr = FunctionWrapper.Load<GdipCreateMetafileFromDelegate_linux_delegate>(s_gdipModule, "GdipCreateMetafileFromDelegate_linux");
+ GdipGetMetafileHeaderFromDelegate_linux_ptr = FunctionWrapper.Load<GdipGetMetafileHeaderFromDelegate_linux_delegate>(s_gdipModule, "GdipGetMetafileHeaderFromDelegate_linux");
+ GdipRecordMetafileFromDelegate_linux_ptr = FunctionWrapper.Load<GdipRecordMetafileFromDelegate_linux_delegate>(s_gdipModule, "GdipRecordMetafileFromDelegate_linux");
+ GdipRecordMetafileFromDelegateI_linux_ptr = FunctionWrapper.Load<GdipRecordMetafileFromDelegateI_linux_delegate>(s_gdipModule, "GdipRecordMetafileFromDelegateI_linux");
+ GdipGetPostScriptSavePage_ptr = FunctionWrapper.Load<GdipGetPostScriptSavePage_delegate>(s_gdipModule, "GdipGetPostScriptSavePage");
+ GdipGetPostScriptGraphicsContext_ptr = FunctionWrapper.Load<GdipGetPostScriptGraphicsContext_delegate>(s_gdipModule, "GdipGetPostScriptGraphicsContext");
}
// Imported functions
- private delegate Status GdiplusStartup_delegate(out IntPtr token, ref StartupInput input, out StartupOutput output);
+ private delegate int GdiplusStartup_delegate(out IntPtr token, ref StartupInput input, out StartupOutput output);
private static FunctionWrapper<GdiplusStartup_delegate> GdiplusStartup_ptr;
internal static int GdiplusStartup(out IntPtr token, ref StartupInput input, out StartupOutput output) => (int)GdiplusStartup_ptr.Delegate(out token, ref input, out output);
@@ -326,1108 +368,1037 @@ namespace System.Drawing
private static FunctionWrapper<GdipFree_delegate> GdipFree_ptr;
internal static void GdipFree(IntPtr ptr) => GdipFree_ptr.Delegate(ptr);
- private delegate Status GdipDeleteBrush_delegate(IntPtr brush);
+ private delegate int GdipDeleteBrush_delegate(IntPtr brush);
private static FunctionWrapper<GdipDeleteBrush_delegate> GdipDeleteBrush_ptr;
- internal static Status GdipDeleteBrush(IntPtr brush) => GdipDeleteBrush_ptr.Delegate(brush);
+ internal static int GdipDeleteBrush(IntPtr brush) => GdipDeleteBrush_ptr.Delegate(brush);
internal static int IntGdipDeleteBrush(HandleRef brush) => (int)GdipDeleteBrush_ptr.Delegate(brush.Handle);
- private delegate Status GdipGetBrushType_delegate(IntPtr brush, out BrushType type);
+ private delegate int GdipGetBrushType_delegate(IntPtr brush, out BrushType type);
private static FunctionWrapper<GdipGetBrushType_delegate> GdipGetBrushType_ptr;
- internal static Status GdipGetBrushType(IntPtr brush, out BrushType type) => GdipGetBrushType_ptr.Delegate(brush, out type);
+ internal static int GdipGetBrushType(IntPtr brush, out BrushType type) => GdipGetBrushType_ptr.Delegate(brush, out type);
- private delegate Status GdipCreateFromHDC_delegate(IntPtr hDC, out IntPtr graphics);
+ private delegate int GdipCreateFromHDC_delegate(IntPtr hDC, out IntPtr graphics);
private static FunctionWrapper<GdipCreateFromHDC_delegate> GdipCreateFromHDC_ptr;
- internal static Status GdipCreateFromHDC(IntPtr hDC, out IntPtr graphics) => GdipCreateFromHDC_ptr.Delegate(hDC, out graphics);
+ internal static int GdipCreateFromHDC(IntPtr hDC, out IntPtr graphics) => GdipCreateFromHDC_ptr.Delegate(hDC, out graphics);
- private delegate Status GdipDeleteGraphics_delegate(IntPtr graphics);
+ private delegate int GdipDeleteGraphics_delegate(IntPtr graphics);
private static FunctionWrapper<GdipDeleteGraphics_delegate> GdipDeleteGraphics_ptr;
- internal static Status GdipDeleteGraphics(IntPtr graphics) => GdipDeleteGraphics_ptr.Delegate(graphics);
+ internal static int GdipDeleteGraphics(IntPtr graphics) => GdipDeleteGraphics_ptr.Delegate(graphics);
internal static int IntGdipDeleteGraphics(HandleRef graphics) => (int)GdipDeleteGraphics_ptr.Delegate(graphics.Handle);
- private delegate Status GdipRestoreGraphics_delegate(IntPtr graphics, uint graphicsState);
+ private delegate int GdipRestoreGraphics_delegate(IntPtr graphics, uint graphicsState);
private static FunctionWrapper<GdipRestoreGraphics_delegate> GdipRestoreGraphics_ptr;
- internal static Status GdipRestoreGraphics(IntPtr graphics, uint graphicsState) => GdipRestoreGraphics_ptr.Delegate(graphics, graphicsState);
+ internal static int GdipRestoreGraphics(IntPtr graphics, uint graphicsState) => GdipRestoreGraphics_ptr.Delegate(graphics, graphicsState);
- private delegate Status GdipSaveGraphics_delegate(IntPtr graphics, out uint state);
+ private delegate int GdipSaveGraphics_delegate(IntPtr graphics, out uint state);
private static FunctionWrapper<GdipSaveGraphics_delegate> GdipSaveGraphics_ptr;
- internal static Status GdipSaveGraphics(IntPtr graphics, out uint state) => GdipSaveGraphics_ptr.Delegate(graphics, out state);
+ internal static int GdipSaveGraphics(IntPtr graphics, out uint state) => GdipSaveGraphics_ptr.Delegate(graphics, out state);
- private delegate Status GdipDrawArc_delegate(IntPtr graphics, IntPtr pen, float x, float y, float width, float height, float startAngle, float sweepAngle);
+ private delegate int GdipDrawArc_delegate(IntPtr graphics, IntPtr pen, float x, float y, float width, float height, float startAngle, float sweepAngle);
private static FunctionWrapper<GdipDrawArc_delegate> GdipDrawArc_ptr;
- internal static Status GdipDrawArc(IntPtr graphics, IntPtr pen, float x, float y, float width, float height, float startAngle, float sweepAngle) => GdipDrawArc_ptr.Delegate(graphics, pen, x, y, width, height, startAngle, sweepAngle);
+ internal static int GdipDrawArc(IntPtr graphics, IntPtr pen, float x, float y, float width, float height, float startAngle, float sweepAngle) => GdipDrawArc_ptr.Delegate(graphics, pen, x, y, width, height, startAngle, sweepAngle);
- private delegate Status GdipDrawArcI_delegate(IntPtr graphics, IntPtr pen, int x, int y, int width, int height, float startAngle, float sweepAngle);
+ private delegate int GdipDrawArcI_delegate(IntPtr graphics, IntPtr pen, int x, int y, int width, int height, float startAngle, float sweepAngle);
private static FunctionWrapper<GdipDrawArcI_delegate> GdipDrawArcI_ptr;
- internal static Status GdipDrawArcI(IntPtr graphics, IntPtr pen, int x, int y, int width, int height, float startAngle, float sweepAngle) => GdipDrawArcI_ptr.Delegate(graphics, pen, x, y, width, height, startAngle, sweepAngle);
+ internal static int GdipDrawArcI(IntPtr graphics, IntPtr pen, int x, int y, int width, int height, float startAngle, float sweepAngle) => GdipDrawArcI_ptr.Delegate(graphics, pen, x, y, width, height, startAngle, sweepAngle);
- private delegate Status GdipDrawBezier_delegate(IntPtr graphics, IntPtr pen, float x1, float y1, float x2, float y2, float x3, float y3, float x4, float y4);
+ private delegate int GdipDrawBezier_delegate(IntPtr graphics, IntPtr pen, float x1, float y1, float x2, float y2, float x3, float y3, float x4, float y4);
private static FunctionWrapper<GdipDrawBezier_delegate> GdipDrawBezier_ptr;
- internal static Status GdipDrawBezier(IntPtr graphics, IntPtr pen, float x1, float y1, float x2, float y2, float x3, float y3, float x4, float y4) => GdipDrawBezier_ptr.Delegate(graphics, pen, x1, y1, x2, y2, x3, y3, x4, y4);
+ internal static int GdipDrawBezier(IntPtr graphics, IntPtr pen, float x1, float y1, float x2, float y2, float x3, float y3, float x4, float y4) => GdipDrawBezier_ptr.Delegate(graphics, pen, x1, y1, x2, y2, x3, y3, x4, y4);
- private delegate Status GdipDrawBezierI_delegate(IntPtr graphics, IntPtr pen, int x1, int y1, int x2, int y2, int x3, int y3, int x4, int y4);
+ private delegate int GdipDrawBezierI_delegate(IntPtr graphics, IntPtr pen, int x1, int y1, int x2, int y2, int x3, int y3, int x4, int y4);
private static FunctionWrapper<GdipDrawBezierI_delegate> GdipDrawBezierI_ptr;
- internal static Status GdipDrawBezierI(IntPtr graphics, IntPtr pen, int x1, int y1, int x2, int y2, int x3, int y3, int x4, int y4) => GdipDrawBezierI_ptr.Delegate(graphics, pen, x1, y1, x2, y2, x3, y3, x4, y4);
+ internal static int GdipDrawBezierI(IntPtr graphics, IntPtr pen, int x1, int y1, int x2, int y2, int x3, int y3, int x4, int y4) => GdipDrawBezierI_ptr.Delegate(graphics, pen, x1, y1, x2, y2, x3, y3, x4, y4);
- private delegate Status GdipDrawEllipseI_delegate(IntPtr graphics, IntPtr pen, int x, int y, int width, int height);
+ private delegate int GdipDrawEllipseI_delegate(IntPtr graphics, IntPtr pen, int x, int y, int width, int height);
private static FunctionWrapper<GdipDrawEllipseI_delegate> GdipDrawEllipseI_ptr;
- internal static Status GdipDrawEllipseI(IntPtr graphics, IntPtr pen, int x, int y, int width, int height) => GdipDrawEllipseI_ptr.Delegate(graphics, pen, x, y, width, height);
+ internal static int GdipDrawEllipseI(IntPtr graphics, IntPtr pen, int x, int y, int width, int height) => GdipDrawEllipseI_ptr.Delegate(graphics, pen, x, y, width, height);
- private delegate Status GdipDrawEllipse_delegate(IntPtr graphics, IntPtr pen, float x, float y, float width, float height);
+ private delegate int GdipDrawEllipse_delegate(IntPtr graphics, IntPtr pen, float x, float y, float width, float height);
private static FunctionWrapper<GdipDrawEllipse_delegate> GdipDrawEllipse_ptr;
- internal static Status GdipDrawEllipse(IntPtr graphics, IntPtr pen, float x, float y, float width, float height) => GdipDrawEllipse_ptr.Delegate(graphics, pen, x, y, width, height);
+ internal static int GdipDrawEllipse(IntPtr graphics, IntPtr pen, float x, float y, float width, float height) => GdipDrawEllipse_ptr.Delegate(graphics, pen, x, y, width, height);
- private delegate Status GdipDrawLine_delegate(IntPtr graphics, IntPtr pen, float x1, float y1, float x2, float y2);
+ private delegate int GdipDrawLine_delegate(IntPtr graphics, IntPtr pen, float x1, float y1, float x2, float y2);
private static FunctionWrapper<GdipDrawLine_delegate> GdipDrawLine_ptr;
- internal static Status GdipDrawLine(IntPtr graphics, IntPtr pen, float x1, float y1, float x2, float y2) => GdipDrawLine_ptr.Delegate(graphics, pen, x1, y1, x2, y2);
+ internal static int GdipDrawLine(IntPtr graphics, IntPtr pen, float x1, float y1, float x2, float y2) => GdipDrawLine_ptr.Delegate(graphics, pen, x1, y1, x2, y2);
- private delegate Status GdipDrawLineI_delegate(IntPtr graphics, IntPtr pen, int x1, int y1, int x2, int y2);
+ private delegate int GdipDrawLineI_delegate(IntPtr graphics, IntPtr pen, int x1, int y1, int x2, int y2);
private static FunctionWrapper<GdipDrawLineI_delegate> GdipDrawLineI_ptr;
- internal static Status GdipDrawLineI(IntPtr graphics, IntPtr pen, int x1, int y1, int x2, int y2) => GdipDrawLineI_ptr.Delegate(graphics, pen, x1, y1, x2, y2);
+ internal static int GdipDrawLineI(IntPtr graphics, IntPtr pen, int x1, int y1, int x2, int y2) => GdipDrawLineI_ptr.Delegate(graphics, pen, x1, y1, x2, y2);
- private delegate Status GdipDrawLines_delegate(IntPtr graphics, IntPtr pen, PointF[] points, int count);
+ private delegate int GdipDrawLines_delegate(IntPtr graphics, IntPtr pen, PointF[] points, int count);
private static FunctionWrapper<GdipDrawLines_delegate> GdipDrawLines_ptr;
- internal static Status GdipDrawLines(IntPtr graphics, IntPtr pen, PointF[] points, int count) => GdipDrawLines_ptr.Delegate(graphics, pen, points, count);
+ internal static int GdipDrawLines(IntPtr graphics, IntPtr pen, PointF[] points, int count) => GdipDrawLines_ptr.Delegate(graphics, pen, points, count);
- private delegate Status GdipDrawLinesI_delegate(IntPtr graphics, IntPtr pen, Point[] points, int count);
+ private delegate int GdipDrawLinesI_delegate(IntPtr graphics, IntPtr pen, Point[] points, int count);
private static FunctionWrapper<GdipDrawLinesI_delegate> GdipDrawLinesI_ptr;
- internal static Status GdipDrawLinesI(IntPtr graphics, IntPtr pen, Point[] points, int count) => GdipDrawLinesI_ptr.Delegate(graphics, pen, points, count);
+ internal static int GdipDrawLinesI(IntPtr graphics, IntPtr pen, Point[] points, int count) => GdipDrawLinesI_ptr.Delegate(graphics, pen, points, count);
- private delegate Status GdipDrawPath_delegate(IntPtr graphics, IntPtr pen, IntPtr path);
+ private delegate int GdipDrawPath_delegate(IntPtr graphics, IntPtr pen, IntPtr path);
private static FunctionWrapper<GdipDrawPath_delegate> GdipDrawPath_ptr;
- internal static Status GdipDrawPath(IntPtr graphics, IntPtr pen, IntPtr path) => GdipDrawPath_ptr.Delegate(graphics, pen, path);
+ internal static int GdipDrawPath(IntPtr graphics, IntPtr pen, IntPtr path) => GdipDrawPath_ptr.Delegate(graphics, pen, path);
- private delegate Status GdipDrawPie_delegate(IntPtr graphics, IntPtr pen, float x, float y, float width, float height, float startAngle, float sweepAngle);
+ private delegate int GdipDrawPie_delegate(IntPtr graphics, IntPtr pen, float x, float y, float width, float height, float startAngle, float sweepAngle);
private static FunctionWrapper<GdipDrawPie_delegate> GdipDrawPie_ptr;
- internal static Status GdipDrawPie(IntPtr graphics, IntPtr pen, float x, float y, float width, float height, float startAngle, float sweepAngle) => GdipDrawPie_ptr.Delegate(graphics, pen, x, y, width, height, startAngle, sweepAngle);
+ internal static int GdipDrawPie(IntPtr graphics, IntPtr pen, float x, float y, float width, float height, float startAngle, float sweepAngle) => GdipDrawPie_ptr.Delegate(graphics, pen, x, y, width, height, startAngle, sweepAngle);
- private delegate Status GdipDrawPieI_delegate(IntPtr graphics, IntPtr pen, int x, int y, int width, int height, float startAngle, float sweepAngle);
+ private delegate int GdipDrawPieI_delegate(IntPtr graphics, IntPtr pen, int x, int y, int width, int height, float startAngle, float sweepAngle);
private static FunctionWrapper<GdipDrawPieI_delegate> GdipDrawPieI_ptr;
- internal static Status GdipDrawPieI(IntPtr graphics, IntPtr pen, int x, int y, int width, int height, float startAngle, float sweepAngle) => GdipDrawPieI_ptr.Delegate(graphics, pen, x, y, width, height, startAngle, sweepAngle);
+ internal static int GdipDrawPieI(IntPtr graphics, IntPtr pen, int x, int y, int width, int height, float startAngle, float sweepAngle) => GdipDrawPieI_ptr.Delegate(graphics, pen, x, y, width, height, startAngle, sweepAngle);
- private delegate Status GdipDrawPolygon_delegate(IntPtr graphics, IntPtr pen, PointF[] points, int count);
+ private delegate int GdipDrawPolygon_delegate(IntPtr graphics, IntPtr pen, PointF[] points, int count);
private static FunctionWrapper<GdipDrawPolygon_delegate> GdipDrawPolygon_ptr;
- internal static Status GdipDrawPolygon(IntPtr graphics, IntPtr pen, PointF[] points, int count) => GdipDrawPolygon_ptr.Delegate(graphics, pen, points, count);
+ internal static int GdipDrawPolygon(IntPtr graphics, IntPtr pen, PointF[] points, int count) => GdipDrawPolygon_ptr.Delegate(graphics, pen, points, count);
- private delegate Status GdipDrawPolygonI_delegate(IntPtr graphics, IntPtr pen, Point[] points, int count);
+ private delegate int GdipDrawPolygonI_delegate(IntPtr graphics, IntPtr pen, Point[] points, int count);
private static FunctionWrapper<GdipDrawPolygonI_delegate> GdipDrawPolygonI_ptr;
- internal static Status GdipDrawPolygonI(IntPtr graphics, IntPtr pen, Point[] points, int count) => GdipDrawPolygonI_ptr.Delegate(graphics, pen, points, count);
+ internal static int GdipDrawPolygonI(IntPtr graphics, IntPtr pen, Point[] points, int count) => GdipDrawPolygonI_ptr.Delegate(graphics, pen, points, count);
- private delegate Status GdipDrawRectangle_delegate(IntPtr graphics, IntPtr pen, float x, float y, float width, float height);
+ private delegate int GdipDrawRectangle_delegate(IntPtr graphics, IntPtr pen, float x, float y, float width, float height);
private static FunctionWrapper<GdipDrawRectangle_delegate> GdipDrawRectangle_ptr;
- internal static Status GdipDrawRectangle(IntPtr graphics, IntPtr pen, float x, float y, float width, float height) => GdipDrawRectangle_ptr.Delegate(graphics, pen, x, y, width, height);
+ internal static int GdipDrawRectangle(IntPtr graphics, IntPtr pen, float x, float y, float width, float height) => GdipDrawRectangle_ptr.Delegate(graphics, pen, x, y, width, height);
- private delegate Status GdipDrawRectangleI_delegate(IntPtr graphics, IntPtr pen, int x, int y, int width, int height);
+ private delegate int GdipDrawRectangleI_delegate(IntPtr graphics, IntPtr pen, int x, int y, int width, int height);
private static FunctionWrapper<GdipDrawRectangleI_delegate> GdipDrawRectangleI_ptr;
- internal static Status GdipDrawRectangleI(IntPtr graphics, IntPtr pen, int x, int y, int width, int height) => GdipDrawRectangleI_ptr.Delegate(graphics, pen, x, y, width, height);
+ internal static int GdipDrawRectangleI(IntPtr graphics, IntPtr pen, int x, int y, int width, int height) => GdipDrawRectangleI_ptr.Delegate(graphics, pen, x, y, width, height);
- private delegate Status GdipDrawRectangles_delegate(IntPtr graphics, IntPtr pen, RectangleF[] rects, int count);
+ private delegate int GdipDrawRectangles_delegate(IntPtr graphics, IntPtr pen, RectangleF[] rects, int count);
private static FunctionWrapper<GdipDrawRectangles_delegate> GdipDrawRectangles_ptr;
- internal static Status GdipDrawRectangles(IntPtr graphics, IntPtr pen, RectangleF[] rects, int count) => GdipDrawRectangles_ptr.Delegate(graphics, pen, rects, count);
+ internal static int GdipDrawRectangles(IntPtr graphics, IntPtr pen, RectangleF[] rects, int count) => GdipDrawRectangles_ptr.Delegate(graphics, pen, rects, count);
- private delegate Status GdipDrawRectanglesI_delegate(IntPtr graphics, IntPtr pen, Rectangle[] rects, int count);
+ private delegate int GdipDrawRectanglesI_delegate(IntPtr graphics, IntPtr pen, Rectangle[] rects, int count);
private static FunctionWrapper<GdipDrawRectanglesI_delegate> GdipDrawRectanglesI_ptr;
- internal static Status GdipDrawRectanglesI(IntPtr graphics, IntPtr pen, Rectangle[] rects, int count) => GdipDrawRectanglesI_ptr.Delegate(graphics, pen, rects, count);
+ internal static int GdipDrawRectanglesI(IntPtr graphics, IntPtr pen, Rectangle[] rects, int count) => GdipDrawRectanglesI_ptr.Delegate(graphics, pen, rects, count);
- private delegate Status GdipFillEllipseI_delegate(IntPtr graphics, IntPtr pen, int x, int y, int width, int height);
+ private delegate int GdipFillEllipseI_delegate(IntPtr graphics, IntPtr pen, int x, int y, int width, int height);
private static FunctionWrapper<GdipFillEllipseI_delegate> GdipFillEllipseI_ptr;
- internal static Status GdipFillEllipseI(IntPtr graphics, IntPtr pen, int x, int y, int width, int height) => GdipFillEllipseI_ptr.Delegate(graphics, pen, x, y, width, height);
+ internal static int GdipFillEllipseI(IntPtr graphics, IntPtr pen, int x, int y, int width, int height) => GdipFillEllipseI_ptr.Delegate(graphics, pen, x, y, width, height);
- private delegate Status GdipFillEllipse_delegate(IntPtr graphics, IntPtr pen, float x, float y, float width, float height);
+ private delegate int GdipFillEllipse_delegate(IntPtr graphics, IntPtr pen, float x, float y, float width, float height);
private static FunctionWrapper<GdipFillEllipse_delegate> GdipFillEllipse_ptr;
- internal static Status GdipFillEllipse(IntPtr graphics, IntPtr pen, float x, float y, float width, float height) => GdipFillEllipse_ptr.Delegate(graphics, pen, x, y, width, height);
+ internal static int GdipFillEllipse(IntPtr graphics, IntPtr pen, float x, float y, float width, float height) => GdipFillEllipse_ptr.Delegate(graphics, pen, x, y, width, height);
- private delegate Status GdipFillPolygon_delegate(IntPtr graphics, IntPtr brush, PointF[] points, int count, FillMode fillMode);
+ private delegate int GdipFillPolygon_delegate(IntPtr graphics, IntPtr brush, PointF[] points, int count, FillMode fillMode);
private static FunctionWrapper<GdipFillPolygon_delegate> GdipFillPolygon_ptr;
- internal static Status GdipFillPolygon(IntPtr graphics, IntPtr brush, PointF[] points, int count, FillMode fillMode) => GdipFillPolygon_ptr.Delegate(graphics, brush, points, count, fillMode);
+ internal static int GdipFillPolygon(IntPtr graphics, IntPtr brush, PointF[] points, int count, FillMode fillMode) => GdipFillPolygon_ptr.Delegate(graphics, brush, points, count, fillMode);
- private delegate Status GdipFillPolygonI_delegate(IntPtr graphics, IntPtr brush, Point[] points, int count, FillMode fillMode);
+ private delegate int GdipFillPolygonI_delegate(IntPtr graphics, IntPtr brush, Point[] points, int count, FillMode fillMode);
private static FunctionWrapper<GdipFillPolygonI_delegate> GdipFillPolygonI_ptr;
- internal static Status GdipFillPolygonI(IntPtr graphics, IntPtr brush, Point[] points, int count, FillMode fillMode) => GdipFillPolygonI_ptr.Delegate(graphics, brush, points, count, fillMode);
+ internal static int GdipFillPolygonI(IntPtr graphics, IntPtr brush, Point[] points, int count, FillMode fillMode) => GdipFillPolygonI_ptr.Delegate(graphics, brush, points, count, fillMode);
- private delegate Status GdipFillPolygon2_delegate(IntPtr graphics, IntPtr brush, PointF[] points, int count);
+ private delegate int GdipFillPolygon2_delegate(IntPtr graphics, IntPtr brush, PointF[] points, int count);
private static FunctionWrapper<GdipFillPolygon2_delegate> GdipFillPolygon2_ptr;
- internal static Status GdipFillPolygon2(IntPtr graphics, IntPtr brush, PointF[] points, int count) => GdipFillPolygon2_ptr.Delegate(graphics, brush, points, count);
+ internal static int GdipFillPolygon2(IntPtr graphics, IntPtr brush, PointF[] points, int count) => GdipFillPolygon2_ptr.Delegate(graphics, brush, points, count);
- private delegate Status GdipFillPolygon2I_delegate(IntPtr graphics, IntPtr brush, Point[] points, int count);
+ private delegate int GdipFillPolygon2I_delegate(IntPtr graphics, IntPtr brush, Point[] points, int count);
private static FunctionWrapper<GdipFillPolygon2I_delegate> GdipFillPolygon2I_ptr;
- internal static Status GdipFillPolygon2I(IntPtr graphics, IntPtr brush, Point[] points, int count) => GdipFillPolygon2I_ptr.Delegate(graphics, brush, points, count);
+ internal static int GdipFillPolygon2I(IntPtr graphics, IntPtr brush, Point[] points, int count) => GdipFillPolygon2I_ptr.Delegate(graphics, brush, points, count);
- private delegate Status GdipFillRectangle_delegate(IntPtr graphics, IntPtr brush, float x1, float y1, float x2, float y2);
+ private delegate int GdipFillRectangle_delegate(IntPtr graphics, IntPtr brush, float x1, float y1, float x2, float y2);
private static FunctionWrapper<GdipFillRectangle_delegate> GdipFillRectangle_ptr;
- internal static Status GdipFillRectangle(IntPtr graphics, IntPtr brush, float x1, float y1, float x2, float y2) => GdipFillRectangle_ptr.Delegate(graphics, brush, x1, y1, x2, y2);
+ internal static int GdipFillRectangle(IntPtr graphics, IntPtr brush, float x1, float y1, float x2, float y2) => GdipFillRectangle_ptr.Delegate(graphics, brush, x1, y1, x2, y2);
- private delegate Status GdipFillRectangleI_delegate(IntPtr graphics, IntPtr brush, int x1, int y1, int x2, int y2);
+ private delegate int GdipFillRectangleI_delegate(IntPtr graphics, IntPtr brush, int x1, int y1, int x2, int y2);
private static FunctionWrapper<GdipFillRectangleI_delegate> GdipFillRectangleI_ptr;
- internal static Status GdipFillRectangleI(IntPtr graphics, IntPtr brush, int x1, int y1, int x2, int y2) => GdipFillRectangleI_ptr.Delegate(graphics, brush, x1, y1, x2, y2);
+ internal static int GdipFillRectangleI(IntPtr graphics, IntPtr brush, int x1, int y1, int x2, int y2) => GdipFillRectangleI_ptr.Delegate(graphics, brush, x1, y1, x2, y2);
- private delegate Status GdipFillRectangles_delegate(IntPtr graphics, IntPtr brush, RectangleF[] rects, int count);
+ private delegate int GdipFillRectangles_delegate(IntPtr graphics, IntPtr brush, RectangleF[] rects, int count);
private static FunctionWrapper<GdipFillRectangles_delegate> GdipFillRectangles_ptr;
- internal static Status GdipFillRectangles(IntPtr graphics, IntPtr brush, RectangleF[] rects, int count) => GdipFillRectangles_ptr.Delegate(graphics, brush, rects, count);
+ internal static int GdipFillRectangles(IntPtr graphics, IntPtr brush, RectangleF[] rects, int count) => GdipFillRectangles_ptr.Delegate(graphics, brush, rects, count);
- private delegate Status GdipFillRectanglesI_delegate(IntPtr graphics, IntPtr brush, Rectangle[] rects, int count);
+ private delegate int GdipFillRectanglesI_delegate(IntPtr graphics, IntPtr brush, Rectangle[] rects, int count);
private static FunctionWrapper<GdipFillRectanglesI_delegate> GdipFillRectanglesI_ptr;
- internal static Status GdipFillRectanglesI(IntPtr graphics, IntPtr brush, Rectangle[] rects, int count) => GdipFillRectanglesI_ptr.Delegate(graphics, brush, rects, count);
+ internal static int GdipFillRectanglesI(IntPtr graphics, IntPtr brush, Rectangle[] rects, int count) => GdipFillRectanglesI_ptr.Delegate(graphics, brush, rects, count);
- private delegate Status GdipDrawString_delegate(IntPtr graphics, [MarshalAs(UnmanagedType.LPWStr)]string text, int len, IntPtr font, ref RectangleF rc, IntPtr format, IntPtr brush);
+ private delegate int GdipDrawString_delegate(IntPtr graphics, [MarshalAs(UnmanagedType.LPWStr)]string text, int len, IntPtr font, ref RectangleF rc, IntPtr format, IntPtr brush);
private static FunctionWrapper<GdipDrawString_delegate> GdipDrawString_ptr;
- internal static Status GdipDrawString(IntPtr graphics, string text, int len, IntPtr font, ref RectangleF rc, IntPtr format, IntPtr brush) => GdipDrawString_ptr.Delegate(graphics, text, len, font, ref rc, format, brush);
+ internal static int GdipDrawString(IntPtr graphics, string text, int len, IntPtr font, ref RectangleF rc, IntPtr format, IntPtr brush) => GdipDrawString_ptr.Delegate(graphics, text, len, font, ref rc, format, brush);
- private delegate Status GdipGetDC_delegate(IntPtr graphics, out IntPtr hdc);
+ private delegate int GdipGetDC_delegate(IntPtr graphics, out IntPtr hdc);
private static FunctionWrapper<GdipGetDC_delegate> GdipGetDC_ptr;
- internal static Status GdipGetDC(IntPtr graphics, out IntPtr hdc) => GdipGetDC_ptr.Delegate(graphics, out hdc);
+ internal static int GdipGetDC(IntPtr graphics, out IntPtr hdc) => GdipGetDC_ptr.Delegate(graphics, out hdc);
- private delegate Status GdipReleaseDC_delegate(IntPtr graphics, IntPtr hdc);
+ private delegate int GdipReleaseDC_delegate(IntPtr graphics, IntPtr hdc);
private static FunctionWrapper<GdipReleaseDC_delegate> GdipReleaseDC_ptr;
- internal static Status GdipReleaseDC(IntPtr graphics, IntPtr hdc) => GdipReleaseDC_ptr.Delegate(graphics, hdc);
+ internal static int GdipReleaseDC(IntPtr graphics, IntPtr hdc) => GdipReleaseDC_ptr.Delegate(graphics, hdc);
internal static int IntGdipReleaseDC(HandleRef graphics, HandleRef hdc) => (int)GdipReleaseDC_ptr.Delegate(graphics.Handle, hdc.Handle);
- private delegate Status GdipDrawImageRectI_delegate(IntPtr graphics, IntPtr image, int x, int y, int width, int height);
+ private delegate int GdipDrawImageRectI_delegate(IntPtr graphics, IntPtr image, int x, int y, int width, int height);
private static FunctionWrapper<GdipDrawImageRectI_delegate> GdipDrawImageRectI_ptr;
- internal static Status GdipDrawImageRectI(IntPtr graphics, IntPtr image, int x, int y, int width, int height) => GdipDrawImageRectI_ptr.Delegate(graphics, image, x, y, width, height);
+ internal static int GdipDrawImageRectI(IntPtr graphics, IntPtr image, int x, int y, int width, int height) => GdipDrawImageRectI_ptr.Delegate(graphics, image, x, y, width, height);
- private delegate Status GdipGetRenderingOrigin_delegate(IntPtr graphics, out int x, out int y);
+ private delegate int GdipGetRenderingOrigin_delegate(IntPtr graphics, out int x, out int y);
private static FunctionWrapper<GdipGetRenderingOrigin_delegate> GdipGetRenderingOrigin_ptr;
- internal static Status GdipGetRenderingOrigin(IntPtr graphics, out int x, out int y) => GdipGetRenderingOrigin_ptr.Delegate(graphics, out x, out y);
+ internal static int GdipGetRenderingOrigin(IntPtr graphics, out int x, out int y) => GdipGetRenderingOrigin_ptr.Delegate(graphics, out x, out y);
- private delegate Status GdipSetRenderingOrigin_delegate(IntPtr graphics, int x, int y);
+ private delegate int GdipSetRenderingOrigin_delegate(IntPtr graphics, int x, int y);
private static FunctionWrapper<GdipSetRenderingOrigin_delegate> GdipSetRenderingOrigin_ptr;
- internal static Status GdipSetRenderingOrigin(IntPtr graphics, int x, int y) => GdipSetRenderingOrigin_ptr.Delegate(graphics, x, y);
+ internal static int GdipSetRenderingOrigin(IntPtr graphics, int x, int y) => GdipSetRenderingOrigin_ptr.Delegate(graphics, x, y);
- private delegate Status GdipCloneBitmapArea_delegate(float x, float y, float width, float height, PixelFormat format, IntPtr original, out IntPtr bitmap);
+ private delegate int GdipCloneBitmapArea_delegate(float x, float y, float width, float height, PixelFormat format, IntPtr original, out IntPtr bitmap);
private static FunctionWrapper<GdipCloneBitmapArea_delegate> GdipCloneBitmapArea_ptr;
- internal static Status GdipCloneBitmapArea(float x, float y, float width, float height, PixelFormat format, IntPtr original, out IntPtr bitmap) => GdipCloneBitmapArea_ptr.Delegate(x, y, width, height, format, original, out bitmap);
+ internal static int GdipCloneBitmapArea(float x, float y, float width, float height, PixelFormat format, IntPtr original, out IntPtr bitmap) => GdipCloneBitmapArea_ptr.Delegate(x, y, width, height, format, original, out bitmap);
- private delegate Status GdipCloneBitmapAreaI_delegate(int x, int y, int width, int height, PixelFormat format, IntPtr original, out IntPtr bitmap);
+ private delegate int GdipCloneBitmapAreaI_delegate(int x, int y, int width, int height, PixelFormat format, IntPtr original, out IntPtr bitmap);
private static FunctionWrapper<GdipCloneBitmapAreaI_delegate> GdipCloneBitmapAreaI_ptr;
- internal static Status GdipCloneBitmapAreaI(int x, int y, int width, int height, PixelFormat format, IntPtr original, out IntPtr bitmap) => GdipCloneBitmapAreaI_ptr.Delegate(x, y, width, height, format, original, out bitmap);
+ internal static int GdipCloneBitmapAreaI(int x, int y, int width, int height, PixelFormat format, IntPtr original, out IntPtr bitmap) => GdipCloneBitmapAreaI_ptr.Delegate(x, y, width, height, format, original, out bitmap);
- private delegate Status GdipGraphicsClear_delegate(IntPtr graphics, int argb);
+ private delegate int GdipGraphicsClear_delegate(IntPtr graphics, int argb);
private static FunctionWrapper<GdipGraphicsClear_delegate> GdipGraphicsClear_ptr;
- internal static Status GdipGraphicsClear(IntPtr graphics, int argb) => GdipGraphicsClear_ptr.Delegate(graphics, argb);
+ internal static int GdipGraphicsClear(IntPtr graphics, int argb) => GdipGraphicsClear_ptr.Delegate(graphics, argb);
- private delegate Status GdipDrawClosedCurve_delegate(IntPtr graphics, IntPtr pen, PointF[] points, int count);
+ private delegate int GdipDrawClosedCurve_delegate(IntPtr graphics, IntPtr pen, PointF[] points, int count);
private static FunctionWrapper<GdipDrawClosedCurve_delegate> GdipDrawClosedCurve_ptr;
- internal static Status GdipDrawClosedCurve(IntPtr graphics, IntPtr pen, PointF[] points, int count) => GdipDrawClosedCurve_ptr.Delegate(graphics, pen, points, count);
+ internal static int GdipDrawClosedCurve(IntPtr graphics, IntPtr pen, PointF[] points, int count) => GdipDrawClosedCurve_ptr.Delegate(graphics, pen, points, count);
- private delegate Status GdipDrawClosedCurveI_delegate(IntPtr graphics, IntPtr pen, Point[] points, int count);
+ private delegate int GdipDrawClosedCurveI_delegate(IntPtr graphics, IntPtr pen, Point[] points, int count);
private static FunctionWrapper<GdipDrawClosedCurveI_delegate> GdipDrawClosedCurveI_ptr;
- internal static Status GdipDrawClosedCurveI(IntPtr graphics, IntPtr pen, Point[] points, int count) => GdipDrawClosedCurveI_ptr.Delegate(graphics, pen, points, count);
+ internal static int GdipDrawClosedCurveI(IntPtr graphics, IntPtr pen, Point[] points, int count) => GdipDrawClosedCurveI_ptr.Delegate(graphics, pen, points, count);
- private delegate Status GdipDrawClosedCurve2_delegate(IntPtr graphics, IntPtr pen, PointF[] points, int count, float tension);
+ private delegate int GdipDrawClosedCurve2_delegate(IntPtr graphics, IntPtr pen, PointF[] points, int count, float tension);
private static FunctionWrapper<GdipDrawClosedCurve2_delegate> GdipDrawClosedCurve2_ptr;
- internal static Status GdipDrawClosedCurve2(IntPtr graphics, IntPtr pen, PointF[] points, int count, float tension) => GdipDrawClosedCurve2_ptr.Delegate(graphics, pen, points, count, tension);
+ internal static int GdipDrawClosedCurve2(IntPtr graphics, IntPtr pen, PointF[] points, int count, float tension) => GdipDrawClosedCurve2_ptr.Delegate(graphics, pen, points, count, tension);
- private delegate Status GdipDrawClosedCurve2I_delegate(IntPtr graphics, IntPtr pen, Point[] points, int count, float tension);
+ private delegate int GdipDrawClosedCurve2I_delegate(IntPtr graphics, IntPtr pen, Point[] points, int count, float tension);
private static FunctionWrapper<GdipDrawClosedCurve2I_delegate> GdipDrawClosedCurve2I_ptr;
- internal static Status GdipDrawClosedCurve2I(IntPtr graphics, IntPtr pen, Point[] points, int count, float tension) => GdipDrawClosedCurve2I_ptr.Delegate(graphics, pen, points, count, tension);
+ internal static int GdipDrawClosedCurve2I(IntPtr graphics, IntPtr pen, Point[] points, int count, float tension) => GdipDrawClosedCurve2I_ptr.Delegate(graphics, pen, points, count, tension);
- private delegate Status GdipDrawCurve_delegate(IntPtr graphics, IntPtr pen, PointF[] points, int count);
+ private delegate int GdipDrawCurve_delegate(IntPtr graphics, IntPtr pen, PointF[] points, int count);
private static FunctionWrapper<GdipDrawCurve_delegate> GdipDrawCurve_ptr;
- internal static Status GdipDrawCurve(IntPtr graphics, IntPtr pen, PointF[] points, int count) => GdipDrawCurve_ptr.Delegate(graphics, pen, points, count);
+ internal static int GdipDrawCurve(IntPtr graphics, IntPtr pen, PointF[] points, int count) => GdipDrawCurve_ptr.Delegate(graphics, pen, points, count);
- private delegate Status GdipDrawCurveI_delegate(IntPtr graphics, IntPtr pen, Point[] points, int count);
+ private delegate int GdipDrawCurveI_delegate(IntPtr graphics, IntPtr pen, Point[] points, int count);
private static FunctionWrapper<GdipDrawCurveI_delegate> GdipDrawCurveI_ptr;
- internal static Status GdipDrawCurveI(IntPtr graphics, IntPtr pen, Point[] points, int count) => GdipDrawCurveI_ptr.Delegate(graphics, pen, points, count);
+ internal static int GdipDrawCurveI(IntPtr graphics, IntPtr pen, Point[] points, int count) => GdipDrawCurveI_ptr.Delegate(graphics, pen, points, count);
- private delegate Status GdipDrawCurve2_delegate(IntPtr graphics, IntPtr pen, PointF[] points, int count, float tension);
+ private delegate int GdipDrawCurve2_delegate(IntPtr graphics, IntPtr pen, PointF[] points, int count, float tension);
private static FunctionWrapper<GdipDrawCurve2_delegate> GdipDrawCurve2_ptr;
- internal static Status GdipDrawCurve2(IntPtr graphics, IntPtr pen, PointF[] points, int count, float tension) => GdipDrawCurve2_ptr.Delegate(graphics, pen, points, count, tension);
+ internal static int GdipDrawCurve2(IntPtr graphics, IntPtr pen, PointF[] points, int count, float tension) => GdipDrawCurve2_ptr.Delegate(graphics, pen, points, count, tension);
- private delegate Status GdipDrawCurve2I_delegate(IntPtr graphics, IntPtr pen, Point[] points, int count, float tension);
+ private delegate int GdipDrawCurve2I_delegate(IntPtr graphics, IntPtr pen, Point[] points, int count, float tension);
private static FunctionWrapper<GdipDrawCurve2I_delegate> GdipDrawCurve2I_ptr;
- internal static Status GdipDrawCurve2I(IntPtr graphics, IntPtr pen, Point[] points, int count, float tension) => GdipDrawCurve2I_ptr.Delegate(graphics, pen, points, count, tension);
+ internal static int GdipDrawCurve2I(IntPtr graphics, IntPtr pen, Point[] points, int count, float tension) => GdipDrawCurve2I_ptr.Delegate(graphics, pen, points, count, tension);
- private delegate Status GdipDrawCurve3_delegate(IntPtr graphics, IntPtr pen, PointF[] points, int count, int offset, int numberOfSegments, float tension);
+ private delegate int GdipDrawCurve3_delegate(IntPtr graphics, IntPtr pen, PointF[] points, int count, int offset, int numberOfSegments, float tension);
private static FunctionWrapper<GdipDrawCurve3_delegate> GdipDrawCurve3_ptr;
- internal static Status GdipDrawCurve3(IntPtr graphics, IntPtr pen, PointF[] points, int count, int offset, int numberOfSegments, float tension) => GdipDrawCurve3_ptr.Delegate(graphics, pen, points, count, offset, numberOfSegments, tension);
+ internal static int GdipDrawCurve3(IntPtr graphics, IntPtr pen, PointF[] points, int count, int offset, int numberOfSegments, float tension) => GdipDrawCurve3_ptr.Delegate(graphics, pen, points, count, offset, numberOfSegments, tension);
- private delegate Status GdipDrawCurve3I_delegate(IntPtr graphics, IntPtr pen, Point[] points, int count, int offset, int numberOfSegments, float tension);
+ private delegate int GdipDrawCurve3I_delegate(IntPtr graphics, IntPtr pen, Point[] points, int count, int offset, int numberOfSegments, float tension);
private static FunctionWrapper<GdipDrawCurve3I_delegate> GdipDrawCurve3I_ptr;
- internal static Status GdipDrawCurve3I(IntPtr graphics, IntPtr pen, Point[] points, int count, int offset, int numberOfSegments, float tension) => GdipDrawCurve3I_ptr.Delegate(graphics, pen, points, count, offset, numberOfSegments, tension);
+ internal static int GdipDrawCurve3I(IntPtr graphics, IntPtr pen, Point[] points, int count, int offset, int numberOfSegments, float tension) => GdipDrawCurve3I_ptr.Delegate(graphics, pen, points, count, offset, numberOfSegments, tension);
- private delegate Status GdipFillClosedCurve_delegate(IntPtr graphics, IntPtr brush, PointF[] points, int count);
+ private delegate int GdipFillClosedCurve_delegate(IntPtr graphics, IntPtr brush, PointF[] points, int count);
private static FunctionWrapper<GdipFillClosedCurve_delegate> GdipFillClosedCurve_ptr;
- internal static Status GdipFillClosedCurve(IntPtr graphics, IntPtr brush, PointF[] points, int count) => GdipFillClosedCurve_ptr.Delegate(graphics, brush, points, count);
+ internal static int GdipFillClosedCurve(IntPtr graphics, IntPtr brush, PointF[] points, int count) => GdipFillClosedCurve_ptr.Delegate(graphics, brush, points, count);
- private delegate Status GdipFillClosedCurveI_delegate(IntPtr graphics, IntPtr brush, Point[] points, int count);
+ private delegate int GdipFillClosedCurveI_delegate(IntPtr graphics, IntPtr brush, Point[] points, int count);
private static FunctionWrapper<GdipFillClosedCurveI_delegate> GdipFillClosedCurveI_ptr;
- internal static Status GdipFillClosedCurveI(IntPtr graphics, IntPtr brush, Point[] points, int count) => GdipFillClosedCurveI_ptr.Delegate(graphics, brush, points, count);
+ internal static int GdipFillClosedCurveI(IntPtr graphics, IntPtr brush, Point[] points, int count) => GdipFillClosedCurveI_ptr.Delegate(graphics, brush, points, count);
- private delegate Status GdipFillClosedCurve2_delegate(IntPtr graphics, IntPtr brush, PointF[] points, int count, float tension, FillMode fillMode);
+ private delegate int GdipFillClosedCurve2_delegate(IntPtr graphics, IntPtr brush, PointF[] points, int count, float tension, FillMode fillMode);
private static FunctionWrapper<GdipFillClosedCurve2_delegate> GdipFillClosedCurve2_ptr;
- internal static Status GdipFillClosedCurve2(IntPtr graphics, IntPtr brush, PointF[] points, int count, float tension, FillMode fillMode) => GdipFillClosedCurve2_ptr.Delegate(graphics, brush, points, count, tension, fillMode);
+ internal static int GdipFillClosedCurve2(IntPtr graphics, IntPtr brush, PointF[] points, int count, float tension, FillMode fillMode) => GdipFillClosedCurve2_ptr.Delegate(graphics, brush, points, count, tension, fillMode);
- private delegate Status GdipFillClosedCurve2I_delegate(IntPtr graphics, IntPtr brush, Point[] points, int count, float tension, FillMode fillMode);
+ private delegate int GdipFillClosedCurve2I_delegate(IntPtr graphics, IntPtr brush, Point[] points, int count, float tension, FillMode fillMode);
private static FunctionWrapper<GdipFillClosedCurve2I_delegate> GdipFillClosedCurve2I_ptr;
- internal static Status GdipFillClosedCurve2I(IntPtr graphics, IntPtr brush, Point[] points, int count, float tension, FillMode fillMode) => GdipFillClosedCurve2I_ptr.Delegate(graphics, brush, points, count, tension, fillMode);
+ internal static int GdipFillClosedCurve2I(IntPtr graphics, IntPtr brush, Point[] points, int count, float tension, FillMode fillMode) => GdipFillClosedCurve2I_ptr.Delegate(graphics, brush, points, count, tension, fillMode);
- private delegate Status GdipFillPie_delegate(IntPtr graphics, IntPtr brush, float x, float y, float width, float height, float startAngle, float sweepAngle);
+ private delegate int GdipFillPie_delegate(IntPtr graphics, IntPtr brush, float x, float y, float width, float height, float startAngle, float sweepAngle);
private static FunctionWrapper<GdipFillPie_delegate> GdipFillPie_ptr;
- internal static Status GdipFillPie(IntPtr graphics, IntPtr brush, float x, float y, float width, float height, float startAngle, float sweepAngle) => GdipFillPie_ptr.Delegate(graphics, brush, x, y, width, height, startAngle, sweepAngle);
+ internal static int GdipFillPie(IntPtr graphics, IntPtr brush, float x, float y, float width, float height, float startAngle, float sweepAngle) => GdipFillPie_ptr.Delegate(graphics, brush, x, y, width, height, startAngle, sweepAngle);
- private delegate Status GdipFillPieI_delegate(IntPtr graphics, IntPtr brush, int x, int y, int width, int height, float startAngle, float sweepAngle);
+ private delegate int GdipFillPieI_delegate(IntPtr graphics, IntPtr brush, int x, int y, int width, int height, float startAngle, float sweepAngle);
private static FunctionWrapper<GdipFillPieI_delegate> GdipFillPieI_ptr;
- internal static Status GdipFillPieI(IntPtr graphics, IntPtr brush, int x, int y, int width, int height, float startAngle, float sweepAngle) => GdipFillPieI_ptr.Delegate(graphics, brush, x, y, width, height, startAngle, sweepAngle);
+ internal static int GdipFillPieI(IntPtr graphics, IntPtr brush, int x, int y, int width, int height, float startAngle, float sweepAngle) => GdipFillPieI_ptr.Delegate(graphics, brush, x, y, width, height, startAngle, sweepAngle);
- private delegate Status GdipFillPath_delegate(IntPtr graphics, IntPtr brush, IntPtr path);
+ private delegate int GdipFillPath_delegate(IntPtr graphics, IntPtr brush, IntPtr path);
private static FunctionWrapper<GdipFillPath_delegate> GdipFillPath_ptr;
- internal static Status GdipFillPath(IntPtr graphics, IntPtr brush, IntPtr path) => GdipFillPath_ptr.Delegate(graphics, brush, path);
+ internal static int GdipFillPath(IntPtr graphics, IntPtr brush, IntPtr path) => GdipFillPath_ptr.Delegate(graphics, brush, path);
- private delegate Status GdipGetNearestColor_delegate(IntPtr graphics, out int argb);
+ private delegate int GdipGetNearestColor_delegate(IntPtr graphics, out int argb);
private static FunctionWrapper<GdipGetNearestColor_delegate> GdipGetNearestColor_ptr;
- internal static Status GdipGetNearestColor(IntPtr graphics, out int argb) => GdipGetNearestColor_ptr.Delegate(graphics, out argb);
+ internal static int GdipGetNearestColor(IntPtr graphics, out int argb) => GdipGetNearestColor_ptr.Delegate(graphics, out argb);
- private delegate Status GdipTransformPoints_delegate(IntPtr graphics, CoordinateSpace destSpace, CoordinateSpace srcSpace, IntPtr points, int count);
+ private delegate int GdipTransformPoints_delegate(IntPtr graphics, CoordinateSpace destSpace, CoordinateSpace srcSpace, IntPtr points, int count);
private static FunctionWrapper<GdipTransformPoints_delegate> GdipTransformPoints_ptr;
- internal static Status GdipTransformPoints(IntPtr graphics, CoordinateSpace destSpace, CoordinateSpace srcSpace, IntPtr points, int count) => GdipTransformPoints_ptr.Delegate(graphics, destSpace, srcSpace, points, count);
+ internal static int GdipTransformPoints(IntPtr graphics, CoordinateSpace destSpace, CoordinateSpace srcSpace, IntPtr points, int count) => GdipTransformPoints_ptr.Delegate(graphics, destSpace, srcSpace, points, count);
- private delegate Status GdipTransformPointsI_delegate(IntPtr graphics, CoordinateSpace destSpace, CoordinateSpace srcSpace, IntPtr points, int count);
+ private delegate int GdipTransformPointsI_delegate(IntPtr graphics, CoordinateSpace destSpace, CoordinateSpace srcSpace, IntPtr points, int count);
private static FunctionWrapper<GdipTransformPointsI_delegate> GdipTransformPointsI_ptr;
- internal static Status GdipTransformPointsI(IntPtr graphics, CoordinateSpace destSpace, CoordinateSpace srcSpace, IntPtr points, int count) => GdipTransformPointsI_ptr.Delegate(graphics, destSpace, srcSpace, points, count);
+ internal static int GdipTransformPointsI(IntPtr graphics, CoordinateSpace destSpace, CoordinateSpace srcSpace, IntPtr points, int count) => GdipTransformPointsI_ptr.Delegate(graphics, destSpace, srcSpace, points, count);
- private delegate Status GdipSetCompositingMode_delegate(IntPtr graphics, CompositingMode compositingMode);
+ private delegate int GdipSetCompositingMode_delegate(IntPtr graphics, CompositingMode compositingMode);
private static FunctionWrapper<GdipSetCompositingMode_delegate> GdipSetCompositingMode_ptr;
- internal static Status GdipSetCompositingMode(IntPtr graphics, CompositingMode compositingMode) => GdipSetCompositingMode_ptr.Delegate(graphics, compositingMode);
+ internal static int GdipSetCompositingMode(IntPtr graphics, CompositingMode compositingMode) => GdipSetCompositingMode_ptr.Delegate(graphics, compositingMode);
- private delegate Status GdipGetCompositingMode_delegate(IntPtr graphics, out CompositingMode compositingMode);
+ private delegate int GdipGetCompositingMode_delegate(IntPtr graphics, out CompositingMode compositingMode);
private static FunctionWrapper<GdipGetCompositingMode_delegate> GdipGetCompositingMode_ptr;
- internal static Status GdipGetCompositingMode(IntPtr graphics, out CompositingMode compositingMode) => GdipGetCompositingMode_ptr.Delegate(graphics, out compositingMode);
+ internal static int GdipGetCompositingMode(IntPtr graphics, out CompositingMode compositingMode) => GdipGetCompositingMode_ptr.Delegate(graphics, out compositingMode);
- private delegate Status GdipSetCompositingQuality_delegate(IntPtr graphics, CompositingQuality compositingQuality);
+ private delegate int GdipSetCompositingQuality_delegate(IntPtr graphics, CompositingQuality compositingQuality);
private static FunctionWrapper<GdipSetCompositingQuality_delegate> GdipSetCompositingQuality_ptr;
- internal static Status GdipSetCompositingQuality(IntPtr graphics, CompositingQuality compositingQuality) => GdipSetCompositingQuality_ptr.Delegate(graphics, compositingQuality);
+ internal static int GdipSetCompositingQuality(IntPtr graphics, CompositingQuality compositingQuality) => GdipSetCompositingQuality_ptr.Delegate(graphics, compositingQuality);
- private delegate Status GdipGetCompositingQuality_delegate(IntPtr graphics, out CompositingQuality compositingQuality);
+ private delegate int GdipGetCompositingQuality_delegate(IntPtr graphics, out CompositingQuality compositingQuality);
private static FunctionWrapper<GdipGetCompositingQuality_delegate> GdipGetCompositingQuality_ptr;
- internal static Status GdipGetCompositingQuality(IntPtr graphics, out CompositingQuality compositingQuality) => GdipGetCompositingQuality_ptr.Delegate(graphics, out compositingQuality);
+ internal static int GdipGetCompositingQuality(IntPtr graphics, out CompositingQuality compositingQuality) => GdipGetCompositingQuality_ptr.Delegate(graphics, out compositingQuality);
- private delegate Status GdipSetInterpolationMode_delegate(IntPtr graphics, InterpolationMode interpolationMode);
+ private delegate int GdipSetInterpolationMode_delegate(IntPtr graphics, InterpolationMode interpolationMode);
private static FunctionWrapper<GdipSetInterpolationMode_delegate> GdipSetInterpolationMode_ptr;
- internal static Status GdipSetInterpolationMode(IntPtr graphics, InterpolationMode interpolationMode) => GdipSetInterpolationMode_ptr.Delegate(graphics, interpolationMode);
+ internal static int GdipSetInterpolationMode(IntPtr graphics, InterpolationMode interpolationMode) => GdipSetInterpolationMode_ptr.Delegate(graphics, interpolationMode);
- private delegate Status GdipGetInterpolationMode_delegate(IntPtr graphics, out InterpolationMode interpolationMode);
+ private delegate int GdipGetInterpolationMode_delegate(IntPtr graphics, out InterpolationMode interpolationMode);
private static FunctionWrapper<GdipGetInterpolationMode_delegate> GdipGetInterpolationMode_ptr;
- internal static Status GdipGetInterpolationMode(IntPtr graphics, out InterpolationMode interpolationMode) => GdipGetInterpolationMode_ptr.Delegate(graphics, out interpolationMode);
+ internal static int GdipGetInterpolationMode(IntPtr graphics, out InterpolationMode interpolationMode) => GdipGetInterpolationMode_ptr.Delegate(graphics, out interpolationMode);
- private delegate Status GdipGetDpiX_delegate(IntPtr graphics, out float dpi);
+ private delegate int GdipGetDpiX_delegate(IntPtr graphics, out float dpi);
private static FunctionWrapper<GdipGetDpiX_delegate> GdipGetDpiX_ptr;
- internal static Status GdipGetDpiX(IntPtr graphics, out float dpi) => GdipGetDpiX_ptr.Delegate(graphics, out dpi);
+ internal static int GdipGetDpiX(IntPtr graphics, out float dpi) => GdipGetDpiX_ptr.Delegate(graphics, out dpi);
- private delegate Status GdipGetDpiY_delegate(IntPtr graphics, out float dpi);
+ private delegate int GdipGetDpiY_delegate(IntPtr graphics, out float dpi);
private static FunctionWrapper<GdipGetDpiY_delegate> GdipGetDpiY_ptr;
- internal static Status GdipGetDpiY(IntPtr graphics, out float dpi) => GdipGetDpiY_ptr.Delegate(graphics, out dpi);
+ internal static int GdipGetDpiY(IntPtr graphics, out float dpi) => GdipGetDpiY_ptr.Delegate(graphics, out dpi);
- private delegate Status GdipGetPageUnit_delegate(IntPtr graphics, out GraphicsUnit unit);
+ private delegate int GdipGetPageUnit_delegate(IntPtr graphics, out GraphicsUnit unit);
private static FunctionWrapper<GdipGetPageUnit_delegate> GdipGetPageUnit_ptr;
- internal static Status GdipGetPageUnit(IntPtr graphics, out GraphicsUnit unit) => GdipGetPageUnit_ptr.Delegate(graphics, out unit);
+ internal static int GdipGetPageUnit(IntPtr graphics, out GraphicsUnit unit) => GdipGetPageUnit_ptr.Delegate(graphics, out unit);
- private delegate Status GdipGetPageScale_delegate(IntPtr graphics, out float scale);
+ private delegate int GdipGetPageScale_delegate(IntPtr graphics, out float scale);
private static FunctionWrapper<GdipGetPageScale_delegate> GdipGetPageScale_ptr;
- internal static Status GdipGetPageScale(IntPtr graphics, out float scale) => GdipGetPageScale_ptr.Delegate(graphics, out scale);
+ internal static int GdipGetPageScale(IntPtr graphics, out float scale) => GdipGetPageScale_ptr.Delegate(graphics, out scale);
- private delegate Status GdipSetPageUnit_delegate(IntPtr graphics, GraphicsUnit unit);
+ private delegate int GdipSetPageUnit_delegate(IntPtr graphics, GraphicsUnit unit);
private static FunctionWrapper<GdipSetPageUnit_delegate> GdipSetPageUnit_ptr;
- internal static Status GdipSetPageUnit(IntPtr graphics, GraphicsUnit unit) => GdipSetPageUnit_ptr.Delegate(graphics, unit);
+ internal static int GdipSetPageUnit(IntPtr graphics, GraphicsUnit unit) => GdipSetPageUnit_ptr.Delegate(graphics, unit);
- private delegate Status GdipSetPageScale_delegate(IntPtr graphics, float scale);
+ private delegate int GdipSetPageScale_delegate(IntPtr graphics, float scale);
private static FunctionWrapper<GdipSetPageScale_delegate> GdipSetPageScale_ptr;
- internal static Status GdipSetPageScale(IntPtr graphics, float scale) => GdipSetPageScale_ptr.Delegate(graphics, scale);
+ internal static int GdipSetPageScale(IntPtr graphics, float scale) => GdipSetPageScale_ptr.Delegate(graphics, scale);
- private delegate Status GdipSetPixelOffsetMode_delegate(IntPtr graphics, PixelOffsetMode pixelOffsetMode);
+ private delegate int GdipSetPixelOffsetMode_delegate(IntPtr graphics, PixelOffsetMode pixelOffsetMode);
private static FunctionWrapper<GdipSetPixelOffsetMode_delegate> GdipSetPixelOffsetMode_ptr;
- internal static Status GdipSetPixelOffsetMode(IntPtr graphics, PixelOffsetMode pixelOffsetMode) => GdipSetPixelOffsetMode_ptr.Delegate(graphics, pixelOffsetMode);
+ internal static int GdipSetPixelOffsetMode(IntPtr graphics, PixelOffsetMode pixelOffsetMode) => GdipSetPixelOffsetMode_ptr.Delegate(graphics, pixelOffsetMode);
- private delegate Status GdipGetPixelOffsetMode_delegate(IntPtr graphics, out PixelOffsetMode pixelOffsetMode);
+ private delegate int GdipGetPixelOffsetMode_delegate(IntPtr graphics, out PixelOffsetMode pixelOffsetMode);
private static FunctionWrapper<GdipGetPixelOffsetMode_delegate> GdipGetPixelOffsetMode_ptr;
- internal static Status GdipGetPixelOffsetMode(IntPtr graphics, out PixelOffsetMode pixelOffsetMode) => GdipGetPixelOffsetMode_ptr.Delegate(graphics, out pixelOffsetMode);
+ internal static int GdipGetPixelOffsetMode(IntPtr graphics, out PixelOffsetMode pixelOffsetMode) => GdipGetPixelOffsetMode_ptr.Delegate(graphics, out pixelOffsetMode);
- private delegate Status GdipSetSmoothingMode_delegate(IntPtr graphics, SmoothingMode smoothingMode);
+ private delegate int GdipSetSmoothingMode_delegate(IntPtr graphics, SmoothingMode smoothingMode);
private static FunctionWrapper<GdipSetSmoothingMode_delegate> GdipSetSmoothingMode_ptr;
- internal static Status GdipSetSmoothingMode(IntPtr graphics, SmoothingMode smoothingMode) => GdipSetSmoothingMode_ptr.Delegate(graphics, smoothingMode);
+ internal static int GdipSetSmoothingMode(IntPtr graphics, SmoothingMode smoothingMode) => GdipSetSmoothingMode_ptr.Delegate(graphics, smoothingMode);
- private delegate Status GdipGetSmoothingMode_delegate(IntPtr graphics, out SmoothingMode smoothingMode);
+ private delegate int GdipGetSmoothingMode_delegate(IntPtr graphics, out SmoothingMode smoothingMode);
private static FunctionWrapper<GdipGetSmoothingMode_delegate> GdipGetSmoothingMode_ptr;
- internal static Status GdipGetSmoothingMode(IntPtr graphics, out SmoothingMode smoothingMode) => GdipGetSmoothingMode_ptr.Delegate(graphics, out smoothingMode);
+ internal static int GdipGetSmoothingMode(IntPtr graphics, out SmoothingMode smoothingMode) => GdipGetSmoothingMode_ptr.Delegate(graphics, out smoothingMode);
- private delegate Status GdipSetTextContrast_delegate(IntPtr graphics, int contrast);
+ private delegate int GdipSetTextContrast_delegate(IntPtr graphics, int contrast);
private static FunctionWrapper<GdipSetTextContrast_delegate> GdipSetTextContrast_ptr;
- internal static Status GdipSetTextContrast(IntPtr graphics, int contrast) => GdipSetTextContrast_ptr.Delegate(graphics, contrast);
+ internal static int GdipSetTextContrast(IntPtr graphics, int contrast) => GdipSetTextContrast_ptr.Delegate(graphics, contrast);
- private delegate Status GdipGetTextContrast_delegate(IntPtr graphics, out int contrast);
+ private delegate int GdipGetTextContrast_delegate(IntPtr graphics, out int contrast);
private static FunctionWrapper<GdipGetTextContrast_delegate> GdipGetTextContrast_ptr;
- internal static Status GdipGetTextContrast(IntPtr graphics, out int contrast) => GdipGetTextContrast_ptr.Delegate(graphics, out contrast);
+ internal static int GdipGetTextContrast(IntPtr graphics, out int contrast) => GdipGetTextContrast_ptr.Delegate(graphics, out contrast);
- private delegate Status GdipSetTextRenderingHint_delegate(IntPtr graphics, TextRenderingHint mode);
+ private delegate int GdipSetTextRenderingHint_delegate(IntPtr graphics, TextRenderingHint mode);
private static FunctionWrapper<GdipSetTextRenderingHint_delegate> GdipSetTextRenderingHint_ptr;
- internal static Status GdipSetTextRenderingHint(IntPtr graphics, TextRenderingHint mode) => GdipSetTextRenderingHint_ptr.Delegate(graphics, mode);
+ internal static int GdipSetTextRenderingHint(IntPtr graphics, TextRenderingHint mode) => GdipSetTextRenderingHint_ptr.Delegate(graphics, mode);
- private delegate Status GdipGetTextRenderingHint_delegate(IntPtr graphics, out TextRenderingHint mode);
+ private delegate int GdipGetTextRenderingHint_delegate(IntPtr graphics, out TextRenderingHint mode);
private static FunctionWrapper<GdipGetTextRenderingHint_delegate> GdipGetTextRenderingHint_ptr;
- internal static Status GdipGetTextRenderingHint(IntPtr graphics, out TextRenderingHint mode) => GdipGetTextRenderingHint_ptr.Delegate(graphics, out mode);
+ internal static int GdipGetTextRenderingHint(IntPtr graphics, out TextRenderingHint mode) => GdipGetTextRenderingHint_ptr.Delegate(graphics, out mode);
- private delegate Status GdipFlush_delegate(IntPtr graphics, FlushIntention intention);
+ private delegate int GdipFlush_delegate(IntPtr graphics, FlushIntention intention);
private static FunctionWrapper<GdipFlush_delegate> GdipFlush_ptr;
- internal static Status GdipFlush(IntPtr graphics, FlushIntention intention) => GdipFlush_ptr.Delegate(graphics, intention);
+ internal static int GdipFlush(IntPtr graphics, FlushIntention intention) => GdipFlush_ptr.Delegate(graphics, intention);
- private delegate Status GdipAddPathString_delegate(IntPtr path, [MarshalAs(UnmanagedType.LPWStr)]string s, int lenght, IntPtr family, int style, float emSize, ref RectangleF layoutRect, IntPtr format);
+ private delegate int GdipAddPathString_delegate(IntPtr path, [MarshalAs(UnmanagedType.LPWStr)]string s, int lenght, IntPtr family, int style, float emSize, ref RectangleF layoutRect, IntPtr format);
private static FunctionWrapper<GdipAddPathString_delegate> GdipAddPathString_ptr;
- internal static Status GdipAddPathString(IntPtr path, string s, int lenght, IntPtr family, int style, float emSize, ref RectangleF layoutRect, IntPtr format) => GdipAddPathString_ptr.Delegate(path, s, lenght, family, style, emSize, ref layoutRect, format);
+ internal static int GdipAddPathString(IntPtr path, string s, int lenght, IntPtr family, int style, float emSize, ref RectangleF layoutRect, IntPtr format) => GdipAddPathString_ptr.Delegate(path, s, lenght, family, style, emSize, ref layoutRect, format);
- private delegate Status GdipAddPathStringI_delegate(IntPtr path, [MarshalAs(UnmanagedType.LPWStr)]string s, int lenght, IntPtr family, int style, float emSize, ref Rectangle layoutRect, IntPtr format);
+ private delegate int GdipAddPathStringI_delegate(IntPtr path, [MarshalAs(UnmanagedType.LPWStr)]string s, int lenght, IntPtr family, int style, float emSize, ref Rectangle layoutRect, IntPtr format);
private static FunctionWrapper<GdipAddPathStringI_delegate> GdipAddPathStringI_ptr;
- internal static Status GdipAddPathStringI(IntPtr path, string s, int lenght, IntPtr family, int style, float emSize, ref Rectangle layoutRect, IntPtr format) => GdipAddPathStringI_ptr.Delegate(path, s, lenght, family, style, emSize, ref layoutRect, format);
+ internal static int GdipAddPathStringI(IntPtr path, string s, int lenght, IntPtr family, int style, float emSize, ref Rectangle layoutRect, IntPtr format) => GdipAddPathStringI_ptr.Delegate(path, s, lenght, family, style, emSize, ref layoutRect, format);
- private delegate Status GdipCreateFromHWND_delegate(IntPtr hwnd, out IntPtr graphics);
+ private delegate int GdipCreateFromHWND_delegate(IntPtr hwnd, out IntPtr graphics);
private static FunctionWrapper<GdipCreateFromHWND_delegate> GdipCreateFromHWND_ptr;
- internal static Status GdipCreateFromHWND(IntPtr hwnd, out IntPtr graphics) => GdipCreateFromHWND_ptr.Delegate(hwnd, out graphics);
+ internal static int GdipCreateFromHWND(IntPtr hwnd, out IntPtr graphics) => GdipCreateFromHWND_ptr.Delegate(hwnd, out graphics);
- private delegate Status GdipMeasureString_delegate(IntPtr graphics, [MarshalAs(UnmanagedType.LPWStr)]string str, int length, IntPtr font, ref RectangleF layoutRect, IntPtr stringFormat, out RectangleF boundingBox, int* codepointsFitted, int* linesFilled);
+ private delegate int GdipMeasureString_delegate(IntPtr graphics, [MarshalAs(UnmanagedType.LPWStr)]string str, int length, IntPtr font, ref RectangleF layoutRect, IntPtr stringFormat, out RectangleF boundingBox, int* codepointsFitted, int* linesFilled);
private static FunctionWrapper<GdipMeasureString_delegate> GdipMeasureString_ptr;
- internal static Status GdipMeasureString(IntPtr graphics, string str, int length, IntPtr font, ref RectangleF layoutRect, IntPtr stringFormat, out RectangleF boundingBox, int* codepointsFitted, int* linesFilled) => GdipMeasureString_ptr.Delegate(graphics, str, length, font, ref layoutRect, stringFormat, out boundingBox, codepointsFitted, linesFilled);
+ internal static int GdipMeasureString(IntPtr graphics, string str, int length, IntPtr font, ref RectangleF layoutRect, IntPtr stringFormat, out RectangleF boundingBox, int* codepointsFitted, int* linesFilled) => GdipMeasureString_ptr.Delegate(graphics, str, length, font, ref layoutRect, stringFormat, out boundingBox, codepointsFitted, linesFilled);
- private delegate Status GdipMeasureCharacterRanges_delegate(IntPtr graphics, [MarshalAs(UnmanagedType.LPWStr)]string str, int length, IntPtr font, ref RectangleF layoutRect, IntPtr stringFormat, int regcount, out IntPtr regions);
+ private delegate int GdipMeasureCharacterRanges_delegate(IntPtr graphics, [MarshalAs(UnmanagedType.LPWStr)]string str, int length, IntPtr font, ref RectangleF layoutRect, IntPtr stringFormat, int regcount, out IntPtr regions);
private static FunctionWrapper<GdipMeasureCharacterRanges_delegate> GdipMeasureCharacterRanges_ptr;
- internal static Status GdipMeasureCharacterRanges(IntPtr graphics, string str, int length, IntPtr font, ref RectangleF layoutRect, IntPtr stringFormat, int regcount, out IntPtr regions) => GdipMeasureCharacterRanges_ptr.Delegate(graphics, str, length, font, ref layoutRect, stringFormat, regcount, out regions);
+ internal static int GdipMeasureCharacterRanges(IntPtr graphics, string str, int length, IntPtr font, ref RectangleF layoutRect, IntPtr stringFormat, int regcount, out IntPtr regions) => GdipMeasureCharacterRanges_ptr.Delegate(graphics, str, length, font, ref layoutRect, stringFormat, regcount, out regions);
- private delegate Status GdipCreateBitmapFromScan0_delegate(int width, int height, int stride, PixelFormat format, IntPtr scan0, out IntPtr bmp);
+ private delegate int GdipCreateBitmapFromScan0_delegate(int width, int height, int stride, PixelFormat format, IntPtr scan0, out IntPtr bmp);
private static FunctionWrapper<GdipCreateBitmapFromScan0_delegate> GdipCreateBitmapFromScan0_ptr;
- internal static Status GdipCreateBitmapFromScan0(int width, int height, int stride, PixelFormat format, IntPtr scan0, out IntPtr bmp) => GdipCreateBitmapFromScan0_ptr.Delegate(width, height, stride, format, scan0, out bmp);
+ internal static int GdipCreateBitmapFromScan0(int width, int height, int stride, PixelFormat format, IntPtr scan0, out IntPtr bmp) => GdipCreateBitmapFromScan0_ptr.Delegate(width, height, stride, format, scan0, out bmp);
- private delegate Status GdipCreateBitmapFromGraphics_delegate(int width, int height, IntPtr target, out IntPtr bitmap);
+ private delegate int GdipCreateBitmapFromGraphics_delegate(int width, int height, IntPtr target, out IntPtr bitmap);
private static FunctionWrapper<GdipCreateBitmapFromGraphics_delegate> GdipCreateBitmapFromGraphics_ptr;
- internal static Status GdipCreateBitmapFromGraphics(int width, int height, IntPtr target, out IntPtr bitmap) => GdipCreateBitmapFromGraphics_ptr.Delegate(width, height, target, out bitmap);
+ internal static int GdipCreateBitmapFromGraphics(int width, int height, IntPtr target, out IntPtr bitmap) => GdipCreateBitmapFromGraphics_ptr.Delegate(width, height, target, out bitmap);
- private delegate Status GdipBitmapLockBits_delegate(IntPtr bmp, ref Rectangle rc, ImageLockMode flags, PixelFormat format, [In] [Out] BitmapData bmpData);
+ private delegate int GdipBitmapLockBits_delegate(IntPtr bmp, ref Rectangle rc, ImageLockMode flags, PixelFormat format, [In] [Out] BitmapData bmpData);
private static FunctionWrapper<GdipBitmapLockBits_delegate> GdipBitmapLockBits_ptr;
- internal static Status GdipBitmapLockBits(IntPtr bmp, ref Rectangle rc, ImageLockMode flags, PixelFormat format, [In] [Out] BitmapData bmpData) => GdipBitmapLockBits_ptr.Delegate(bmp, ref rc, flags, format, bmpData);
+ internal static int GdipBitmapLockBits(IntPtr bmp, ref Rectangle rc, ImageLockMode flags, PixelFormat format, [In] [Out] BitmapData bmpData) => GdipBitmapLockBits_ptr.Delegate(bmp, ref rc, flags, format, bmpData);
- private delegate Status GdipBitmapSetResolution_delegate(IntPtr bmp, float xdpi, float ydpi);
+ private delegate int GdipBitmapSetResolution_delegate(IntPtr bmp, float xdpi, float ydpi);
private static FunctionWrapper<GdipBitmapSetResolution_delegate> GdipBitmapSetResolution_ptr;
- internal static Status GdipBitmapSetResolution(IntPtr bmp, float xdpi, float ydpi) => GdipBitmapSetResolution_ptr.Delegate(bmp, xdpi, ydpi);
+ internal static int GdipBitmapSetResolution(IntPtr bmp, float xdpi, float ydpi) => GdipBitmapSetResolution_ptr.Delegate(bmp, xdpi, ydpi);
- private delegate Status GdipBitmapUnlockBits_delegate(IntPtr bmp, [In] [Out] BitmapData bmpData);
+ private delegate int GdipBitmapUnlockBits_delegate(IntPtr bmp, [In] [Out] BitmapData bmpData);
private static FunctionWrapper<GdipBitmapUnlockBits_delegate> GdipBitmapUnlockBits_ptr;
- internal static Status GdipBitmapUnlockBits(IntPtr bmp, [In] [Out] BitmapData bmpData) => GdipBitmapUnlockBits_ptr.Delegate(bmp, bmpData);
+ internal static int GdipBitmapUnlockBits(IntPtr bmp, [In] [Out] BitmapData bmpData) => GdipBitmapUnlockBits_ptr.Delegate(bmp, bmpData);
- private delegate Status GdipBitmapGetPixel_delegate(IntPtr bmp, int x, int y, out int argb);
+ private delegate int GdipBitmapGetPixel_delegate(IntPtr bmp, int x, int y, out int argb);
private static FunctionWrapper<GdipBitmapGetPixel_delegate> GdipBitmapGetPixel_ptr;
- internal static Status GdipBitmapGetPixel(IntPtr bmp, int x, int y, out int argb) => GdipBitmapGetPixel_ptr.Delegate(bmp, x, y, out argb);
+ internal static int GdipBitmapGetPixel(IntPtr bmp, int x, int y, out int argb) => GdipBitmapGetPixel_ptr.Delegate(bmp, x, y, out argb);
- private delegate Status GdipBitmapSetPixel_delegate(IntPtr bmp, int x, int y, int argb);
+ private delegate int GdipBitmapSetPixel_delegate(IntPtr bmp, int x, int y, int argb);
private static FunctionWrapper<GdipBitmapSetPixel_delegate> GdipBitmapSetPixel_ptr;
- internal static Status GdipBitmapSetPixel(IntPtr bmp, int x, int y, int argb) => GdipBitmapSetPixel_ptr.Delegate(bmp, x, y, argb);
+ internal static int GdipBitmapSetPixel(IntPtr bmp, int x, int y, int argb) => GdipBitmapSetPixel_ptr.Delegate(bmp, x, y, argb);
- private delegate Status GdipLoadImageFromFile_delegate([MarshalAs(UnmanagedType.LPWStr)]string filename, out IntPtr image);
+ private delegate int GdipLoadImageFromFile_delegate([MarshalAs(UnmanagedType.LPWStr)]string filename, out IntPtr image);
private static FunctionWrapper<GdipLoadImageFromFile_delegate> GdipLoadImageFromFile_ptr;
- internal static Status GdipLoadImageFromFile(string filename, out IntPtr image) => GdipLoadImageFromFile_ptr.Delegate(filename, out image);
-
- private delegate Status GdipLoadImageFromStream_delegate([MarshalAs(UnmanagedType.CustomMarshaler, MarshalTypeRef = typeof(ComIStreamMarshaler))]IStream stream, out IntPtr image);
- private static FunctionWrapper<GdipLoadImageFromStream_delegate> GdipLoadImageFromStream_ptr;
- internal static Status GdipLoadImageFromStream(IStream stream, out IntPtr image) => GdipLoadImageFromStream_ptr.Delegate(stream, out image);
+ internal static int GdipLoadImageFromFile(string filename, out IntPtr image) => GdipLoadImageFromFile_ptr.Delegate(filename, out image);
- private delegate Status GdipSaveImageToStream_delegate(HandleRef image, [MarshalAs(UnmanagedType.CustomMarshaler, MarshalTypeRef = typeof(ComIStreamMarshaler))]IStream stream, ref Guid clsidEncoder, HandleRef encoderParams);
- private static FunctionWrapper<GdipSaveImageToStream_delegate> GdipSaveImageToStream_ptr;
- internal static Status GdipSaveImageToStream(HandleRef image, IStream stream, ref Guid clsidEncoder, HandleRef encoderParams) => GdipSaveImageToStream_ptr.Delegate(image, stream, ref clsidEncoder, encoderParams);
-
- private delegate Status GdipCloneImage_delegate(IntPtr image, out IntPtr imageclone);
+ private delegate int GdipCloneImage_delegate(IntPtr image, out IntPtr imageclone);
private static FunctionWrapper<GdipCloneImage_delegate> GdipCloneImage_ptr;
- internal static Status GdipCloneImage(IntPtr image, out IntPtr imageclone) => GdipCloneImage_ptr.Delegate(image, out imageclone);
+ internal static int GdipCloneImage(IntPtr image, out IntPtr imageclone) => GdipCloneImage_ptr.Delegate(image, out imageclone);
- private delegate Status GdipLoadImageFromFileICM_delegate([MarshalAs(UnmanagedType.LPWStr)]string filename, out IntPtr image);
+ private delegate int GdipLoadImageFromFileICM_delegate([MarshalAs(UnmanagedType.LPWStr)]string filename, out IntPtr image);
private static FunctionWrapper<GdipLoadImageFromFileICM_delegate> GdipLoadImageFromFileICM_ptr;
- internal static Status GdipLoadImageFromFileICM(string filename, out IntPtr image) => GdipLoadImageFromFileICM_ptr.Delegate(filename, out image);
+ internal static int GdipLoadImageFromFileICM(string filename, out IntPtr image) => GdipLoadImageFromFileICM_ptr.Delegate(filename, out image);
- private delegate Status GdipCreateBitmapFromHBITMAP_delegate(IntPtr hBitMap, IntPtr gdiPalette, out IntPtr image);
+ private delegate int GdipCreateBitmapFromHBITMAP_delegate(IntPtr hBitMap, IntPtr gdiPalette, out IntPtr image);
private static FunctionWrapper<GdipCreateBitmapFromHBITMAP_delegate> GdipCreateBitmapFromHBITMAP_ptr;
- internal static Status GdipCreateBitmapFromHBITMAP(IntPtr hBitMap, IntPtr gdiPalette, out IntPtr image) => GdipCreateBitmapFromHBITMAP_ptr.Delegate(hBitMap, gdiPalette, out image);
+ internal static int GdipCreateBitmapFromHBITMAP(IntPtr hBitMap, IntPtr gdiPalette, out IntPtr image) => GdipCreateBitmapFromHBITMAP_ptr.Delegate(hBitMap, gdiPalette, out image);
- private delegate Status GdipDisposeImage_delegate(IntPtr image);
+ private delegate int GdipDisposeImage_delegate(IntPtr image);
private static FunctionWrapper<GdipDisposeImage_delegate> GdipDisposeImage_ptr;
- internal static Status GdipDisposeImage(IntPtr image) => GdipDisposeImage_ptr.Delegate(image);
+ internal static int GdipDisposeImage(IntPtr image) => GdipDisposeImage_ptr.Delegate(image);
internal static int IntGdipDisposeImage(HandleRef image) => (int)GdipDisposeImage_ptr.Delegate(image.Handle);
- private delegate Status GdipGetImageFlags_delegate(IntPtr image, out int flag);
+ private delegate int GdipGetImageFlags_delegate(IntPtr image, out int flag);
private static FunctionWrapper<GdipGetImageFlags_delegate> GdipGetImageFlags_ptr;
- internal static Status GdipGetImageFlags(IntPtr image, out int flag) => GdipGetImageFlags_ptr.Delegate(image, out flag);
+ internal static int GdipGetImageFlags(IntPtr image, out int flag) => GdipGetImageFlags_ptr.Delegate(image, out flag);
- private delegate Status GdipGetImageType_delegate(IntPtr image, out ImageType type);
+ private delegate int GdipGetImageType_delegate(IntPtr image, out ImageType type);
private static FunctionWrapper<GdipGetImageType_delegate> GdipGetImageType_ptr;
- internal static Status GdipGetImageType(IntPtr image, out ImageType type) => GdipGetImageType_ptr.Delegate(image, out type);
+ internal static int GdipGetImageType(IntPtr image, out ImageType type) => GdipGetImageType_ptr.Delegate(image, out type);
- private delegate Status GdipImageGetFrameDimensionsCount_delegate(IntPtr image, out uint count);
+ private delegate int GdipImageGetFrameDimensionsCount_delegate(IntPtr image, out uint count);
private static FunctionWrapper<GdipImageGetFrameDimensionsCount_delegate> GdipImageGetFrameDimensionsCount_ptr;
- internal static Status GdipImageGetFrameDimensionsCount(IntPtr image, out uint count) => GdipImageGetFrameDimensionsCount_ptr.Delegate(image, out count);
+ internal static int GdipImageGetFrameDimensionsCount(IntPtr image, out uint count) => GdipImageGetFrameDimensionsCount_ptr.Delegate(image, out count);
- private delegate Status GdipImageGetFrameDimensionsList_delegate(IntPtr image, [Out] Guid[] dimensionIDs, uint count);
+ private delegate int GdipImageGetFrameDimensionsList_delegate(IntPtr image, [Out] Guid[] dimensionIDs, uint count);
private static FunctionWrapper<GdipImageGetFrameDimensionsList_delegate> GdipImageGetFrameDimensionsList_ptr;
- internal static Status GdipImageGetFrameDimensionsList(IntPtr image, [Out] Guid[] dimensionIDs, uint count) => GdipImageGetFrameDimensionsList_ptr.Delegate(image, dimensionIDs, count);
+ internal static int GdipImageGetFrameDimensionsList(IntPtr image, [Out] Guid[] dimensionIDs, uint count) => GdipImageGetFrameDimensionsList_ptr.Delegate(image, dimensionIDs, count);
- private delegate Status GdipGetImageHeight_delegate(IntPtr image, out uint height);
+ private delegate int GdipGetImageHeight_delegate(IntPtr image, out uint height);
private static FunctionWrapper<GdipGetImageHeight_delegate> GdipGetImageHeight_ptr;
- internal static Status GdipGetImageHeight(IntPtr image, out uint height) => GdipGetImageHeight_ptr.Delegate(image, out height);
+ internal static int GdipGetImageHeight(IntPtr image, out uint height) => GdipGetImageHeight_ptr.Delegate(image, out height);
- private delegate Status GdipGetImageHorizontalResolution_delegate(IntPtr image, out float resolution);
+ private delegate int GdipGetImageHorizontalResolution_delegate(IntPtr image, out float resolution);
private static FunctionWrapper<GdipGetImageHorizontalResolution_delegate> GdipGetImageHorizontalResolution_ptr;
- internal static Status GdipGetImageHorizontalResolution(IntPtr image, out float resolution) => GdipGetImageHorizontalResolution_ptr.Delegate(image, out resolution);
+ internal static int GdipGetImageHorizontalResolution(IntPtr image, out float resolution) => GdipGetImageHorizontalResolution_ptr.Delegate(image, out resolution);
- private delegate Status GdipGetImagePaletteSize_delegate(IntPtr image, out int size);
+ private delegate int GdipGetImagePaletteSize_delegate(IntPtr image, out int size);
private static FunctionWrapper<GdipGetImagePaletteSize_delegate> GdipGetImagePaletteSize_ptr;
- internal static Status GdipGetImagePaletteSize(IntPtr image, out int size) => GdipGetImagePaletteSize_ptr.Delegate(image, out size);
+ internal static int GdipGetImagePaletteSize(IntPtr image, out int size) => GdipGetImagePaletteSize_ptr.Delegate(image, out size);
- private delegate Status GdipGetImagePalette_delegate(IntPtr image, IntPtr palette, int size);
+ private delegate int GdipGetImagePalette_delegate(IntPtr image, IntPtr palette, int size);
private static FunctionWrapper<GdipGetImagePalette_delegate> GdipGetImagePalette_ptr;
- internal static Status GdipGetImagePalette(IntPtr image, IntPtr palette, int size) => GdipGetImagePalette_ptr.Delegate(image, palette, size);
+ internal static int GdipGetImagePalette(IntPtr image, IntPtr palette, int size) => GdipGetImagePalette_ptr.Delegate(image, palette, size);
- private delegate Status GdipSetImagePalette_delegate(IntPtr image, IntPtr palette);
+ private delegate int GdipSetImagePalette_delegate(IntPtr image, IntPtr palette);
private static FunctionWrapper<GdipSetImagePalette_delegate> GdipSetImagePalette_ptr;
- internal static Status GdipSetImagePalette(IntPtr image, IntPtr palette) => GdipSetImagePalette_ptr.Delegate(image, palette);
+ internal static int GdipSetImagePalette(IntPtr image, IntPtr palette) => GdipSetImagePalette_ptr.Delegate(image, palette);
- private delegate Status GdipGetImageDimension_delegate(IntPtr image, out float width, out float height);
+ private delegate int GdipGetImageDimension_delegate(IntPtr image, out float width, out float height);
private static FunctionWrapper<GdipGetImageDimension_delegate> GdipGetImageDimension_ptr;
- internal static Status GdipGetImageDimension(IntPtr image, out float width, out float height) => GdipGetImageDimension_ptr.Delegate(image, out width, out height);
+ internal static int GdipGetImageDimension(IntPtr image, out float width, out float height) => GdipGetImageDimension_ptr.Delegate(image, out width, out height);
- private delegate Status GdipGetImagePixelFormat_delegate(IntPtr image, out PixelFormat format);
+ private delegate int GdipGetImagePixelFormat_delegate(IntPtr image, out PixelFormat format);
private static FunctionWrapper<GdipGetImagePixelFormat_delegate> GdipGetImagePixelFormat_ptr;
- internal static Status GdipGetImagePixelFormat(IntPtr image, out PixelFormat format) => GdipGetImagePixelFormat_ptr.Delegate(image, out format);
+ internal static int GdipGetImagePixelFormat(IntPtr image, out PixelFormat format) => GdipGetImagePixelFormat_ptr.Delegate(image, out format);
- private delegate Status GdipGetPropertyCount_delegate(IntPtr image, out uint propNumbers);
+ private delegate int GdipGetPropertyCount_delegate(IntPtr image, out uint propNumbers);
private static FunctionWrapper<GdipGetPropertyCount_delegate> GdipGetPropertyCount_ptr;
- internal static Status GdipGetPropertyCount(IntPtr image, out uint propNumbers) => GdipGetPropertyCount_ptr.Delegate(image, out propNumbers);
+ internal static int GdipGetPropertyCount(IntPtr image, out uint propNumbers) => GdipGetPropertyCount_ptr.Delegate(image, out propNumbers);
- private delegate Status GdipGetPropertyIdList_delegate(IntPtr image, uint propNumbers, [Out] int[] list);
+ private delegate int GdipGetPropertyIdList_delegate(IntPtr image, uint propNumbers, [Out] int[] list);
private static FunctionWrapper<GdipGetPropertyIdList_delegate> GdipGetPropertyIdList_ptr;
- internal static Status GdipGetPropertyIdList(IntPtr image, uint propNumbers, [Out] int[] list) => GdipGetPropertyIdList_ptr.Delegate(image, propNumbers, list);
+ internal static int GdipGetPropertyIdList(IntPtr image, uint propNumbers, [Out] int[] list) => GdipGetPropertyIdList_ptr.Delegate(image, propNumbers, list);
- private delegate Status GdipGetPropertySize_delegate(IntPtr image, out int bufferSize, out int propNumbers);
+ private delegate int GdipGetPropertySize_delegate(IntPtr image, out int bufferSize, out int propNumbers);
private static FunctionWrapper<GdipGetPropertySize_delegate> GdipGetPropertySize_ptr;
- internal static Status GdipGetPropertySize(IntPtr image, out int bufferSize, out int propNumbers) => GdipGetPropertySize_ptr.Delegate(image, out bufferSize, out propNumbers);
+ internal static int GdipGetPropertySize(IntPtr image, out int bufferSize, out int propNumbers) => GdipGetPropertySize_ptr.Delegate(image, out bufferSize, out propNumbers);
- private delegate Status GdipGetAllPropertyItems_delegate(IntPtr image, int bufferSize, int propNumbers, IntPtr items);
+ private delegate int GdipGetAllPropertyItems_delegate(IntPtr image, int bufferSize, int propNumbers, IntPtr items);
private static FunctionWrapper<GdipGetAllPropertyItems_delegate> GdipGetAllPropertyItems_ptr;
- internal static Status GdipGetAllPropertyItems(IntPtr image, int bufferSize, int propNumbers, IntPtr items) => GdipGetAllPropertyItems_ptr.Delegate(image, bufferSize, propNumbers, items);
+ internal static int GdipGetAllPropertyItems(IntPtr image, int bufferSize, int propNumbers, IntPtr items) => GdipGetAllPropertyItems_ptr.Delegate(image, bufferSize, propNumbers, items);
- private delegate Status GdipGetImageRawFormat_delegate(IntPtr image, out Guid format);
+ private delegate int GdipGetImageRawFormat_delegate(IntPtr image, out Guid format);
private static FunctionWrapper<GdipGetImageRawFormat_delegate> GdipGetImageRawFormat_ptr;
- internal static Status GdipGetImageRawFormat(IntPtr image, out Guid format) => GdipGetImageRawFormat_ptr.Delegate(image, out format);
+ internal static int GdipGetImageRawFormat(IntPtr image, out Guid format) => GdipGetImageRawFormat_ptr.Delegate(image, out format);
- private delegate Status GdipGetImageVerticalResolution_delegate(IntPtr image, out float resolution);
+ private delegate int GdipGetImageVerticalResolution_delegate(IntPtr image, out float resolution);
private static FunctionWrapper<GdipGetImageVerticalResolution_delegate> GdipGetImageVerticalResolution_ptr;
- internal static Status GdipGetImageVerticalResolution(IntPtr image, out float resolution) => GdipGetImageVerticalResolution_ptr.Delegate(image, out resolution);
+ internal static int GdipGetImageVerticalResolution(IntPtr image, out float resolution) => GdipGetImageVerticalResolution_ptr.Delegate(image, out resolution);
- private delegate Status GdipGetImageWidth_delegate(IntPtr image, out uint width);
+ private delegate int GdipGetImageWidth_delegate(IntPtr image, out uint width);
private static FunctionWrapper<GdipGetImageWidth_delegate> GdipGetImageWidth_ptr;
- internal static Status GdipGetImageWidth(IntPtr image, out uint width) => GdipGetImageWidth_ptr.Delegate(image, out width);
+ internal static int GdipGetImageWidth(IntPtr image, out uint width) => GdipGetImageWidth_ptr.Delegate(image, out width);
- private delegate Status GdipGetImageBounds_delegate(IntPtr image, out RectangleF source, ref GraphicsUnit unit);
+ private delegate int GdipGetImageBounds_delegate(IntPtr image, out RectangleF source, ref GraphicsUnit unit);
private static FunctionWrapper<GdipGetImageBounds_delegate> GdipGetImageBounds_ptr;
- internal static Status GdipGetImageBounds(IntPtr image, out RectangleF source, ref GraphicsUnit unit) => GdipGetImageBounds_ptr.Delegate(image, out source, ref unit);
+ internal static int GdipGetImageBounds(IntPtr image, out RectangleF source, ref GraphicsUnit unit) => GdipGetImageBounds_ptr.Delegate(image, out source, ref unit);
- private delegate Status GdipGetEncoderParameterListSize_delegate(IntPtr image, ref Guid encoder, out uint size);
+ private delegate int GdipGetEncoderParameterListSize_delegate(IntPtr image, ref Guid encoder, out uint size);
private static FunctionWrapper<GdipGetEncoderParameterListSize_delegate> GdipGetEncoderParameterListSize_ptr;
- internal static Status GdipGetEncoderParameterListSize(IntPtr image, ref Guid encoder, out uint size) => GdipGetEncoderParameterListSize_ptr.Delegate(image, ref encoder, out size);
+ internal static int GdipGetEncoderParameterListSize(IntPtr image, ref Guid encoder, out uint size) => GdipGetEncoderParameterListSize_ptr.Delegate(image, ref encoder, out size);
- private delegate Status GdipGetEncoderParameterList_delegate(IntPtr image, ref Guid encoder, uint size, IntPtr buffer);
+ private delegate int GdipGetEncoderParameterList_delegate(IntPtr image, ref Guid encoder, uint size, IntPtr buffer);
private static FunctionWrapper<GdipGetEncoderParameterList_delegate> GdipGetEncoderParameterList_ptr;
- internal static Status GdipGetEncoderParameterList(IntPtr image, ref Guid encoder, uint size, IntPtr buffer) => GdipGetEncoderParameterList_ptr.Delegate(image, ref encoder, size, buffer);
+ internal static int GdipGetEncoderParameterList(IntPtr image, ref Guid encoder, uint size, IntPtr buffer) => GdipGetEncoderParameterList_ptr.Delegate(image, ref encoder, size, buffer);
- private delegate Status GdipImageGetFrameCount_delegate(IntPtr image, ref Guid guidDimension, out uint count);
+ private delegate int GdipImageGetFrameCount_delegate(IntPtr image, ref Guid guidDimension, out uint count);
private static FunctionWrapper<GdipImageGetFrameCount_delegate> GdipImageGetFrameCount_ptr;
- internal static Status GdipImageGetFrameCount(IntPtr image, ref Guid guidDimension, out uint count) => GdipImageGetFrameCount_ptr.Delegate(image, ref guidDimension, out count);
+ internal static int GdipImageGetFrameCount(IntPtr image, ref Guid guidDimension, out uint count) => GdipImageGetFrameCount_ptr.Delegate(image, ref guidDimension, out count);
- private delegate Status GdipImageSelectActiveFrame_delegate(IntPtr image, ref Guid guidDimension, int frameIndex);
+ private delegate int GdipImageSelectActiveFrame_delegate(IntPtr image, ref Guid guidDimension, int frameIndex);
private static FunctionWrapper<GdipImageSelectActiveFrame_delegate> GdipImageSelectActiveFrame_ptr;
- internal static Status GdipImageSelectActiveFrame(IntPtr image, ref Guid guidDimension, int frameIndex) => GdipImageSelectActiveFrame_ptr.Delegate(image, ref guidDimension, frameIndex);
+ internal static int GdipImageSelectActiveFrame(IntPtr image, ref Guid guidDimension, int frameIndex) => GdipImageSelectActiveFrame_ptr.Delegate(image, ref guidDimension, frameIndex);
- private delegate Status GdipGetPropertyItemSize_delegate(IntPtr image, int propertyID, out int propertySize);
+ private delegate int GdipGetPropertyItemSize_delegate(IntPtr image, int propertyID, out int propertySize);
private static FunctionWrapper<GdipGetPropertyItemSize_delegate> GdipGetPropertyItemSize_ptr;
- internal static Status GdipGetPropertyItemSize(IntPtr image, int propertyID, out int propertySize) => GdipGetPropertyItemSize_ptr.Delegate(image, propertyID, out propertySize);
+ internal static int GdipGetPropertyItemSize(IntPtr image, int propertyID, out int propertySize) => GdipGetPropertyItemSize_ptr.Delegate(image, propertyID, out propertySize);
- private delegate Status GdipGetPropertyItem_delegate(IntPtr image, int propertyID, int propertySize, IntPtr buffer);
+ private delegate int GdipGetPropertyItem_delegate(IntPtr image, int propertyID, int propertySize, IntPtr buffer);
private static FunctionWrapper<GdipGetPropertyItem_delegate> GdipGetPropertyItem_ptr;
- internal static Status GdipGetPropertyItem(IntPtr image, int propertyID, int propertySize, IntPtr buffer) => GdipGetPropertyItem_ptr.Delegate(image, propertyID, propertySize, buffer);
+ internal static int GdipGetPropertyItem(IntPtr image, int propertyID, int propertySize, IntPtr buffer) => GdipGetPropertyItem_ptr.Delegate(image, propertyID, propertySize, buffer);
- private delegate Status GdipRemovePropertyItem_delegate(IntPtr image, int propertyId);
+ private delegate int GdipRemovePropertyItem_delegate(IntPtr image, int propertyId);
private static FunctionWrapper<GdipRemovePropertyItem_delegate> GdipRemovePropertyItem_ptr;
- internal static Status GdipRemovePropertyItem(IntPtr image, int propertyId) => GdipRemovePropertyItem_ptr.Delegate(image, propertyId);
+ internal static int GdipRemovePropertyItem(IntPtr image, int propertyId) => GdipRemovePropertyItem_ptr.Delegate(image, propertyId);
- private delegate Status GdipSetPropertyItem_delegate(IntPtr image, GdipPropertyItem* propertyItem);
+ private delegate int GdipSetPropertyItem_delegate(IntPtr image, GdipPropertyItem* propertyItem);
private static FunctionWrapper<GdipSetPropertyItem_delegate> GdipSetPropertyItem_ptr;
- internal static Status GdipSetPropertyItem(IntPtr image, GdipPropertyItem* propertyItem) => GdipSetPropertyItem_ptr.Delegate(image, propertyItem);
+ internal static int GdipSetPropertyItem(IntPtr image, GdipPropertyItem* propertyItem) => GdipSetPropertyItem_ptr.Delegate(image, propertyItem);
- private delegate Status GdipGetImageThumbnail_delegate(IntPtr image, uint width, uint height, out IntPtr thumbImage, IntPtr callback, IntPtr callBackData);
+ private delegate int GdipGetImageThumbnail_delegate(IntPtr image, uint width, uint height, out IntPtr thumbImage, IntPtr callback, IntPtr callBackData);
private static FunctionWrapper<GdipGetImageThumbnail_delegate> GdipGetImageThumbnail_ptr;
- internal static Status GdipGetImageThumbnail(IntPtr image, uint width, uint height, out IntPtr thumbImage, IntPtr callback, IntPtr callBackData) => GdipGetImageThumbnail_ptr.Delegate(image, width, height, out thumbImage, callback, callBackData);
+ internal static int GdipGetImageThumbnail(IntPtr image, uint width, uint height, out IntPtr thumbImage, IntPtr callback, IntPtr callBackData) => GdipGetImageThumbnail_ptr.Delegate(image, width, height, out thumbImage, callback, callBackData);
- private delegate Status GdipImageRotateFlip_delegate(IntPtr image, RotateFlipType rotateFlipType);
+ private delegate int GdipImageRotateFlip_delegate(IntPtr image, RotateFlipType rotateFlipType);
private static FunctionWrapper<GdipImageRotateFlip_delegate> GdipImageRotateFlip_ptr;
- internal static Status GdipImageRotateFlip(IntPtr image, RotateFlipType rotateFlipType) => GdipImageRotateFlip_ptr.Delegate(image, rotateFlipType);
+ internal static int GdipImageRotateFlip(IntPtr image, RotateFlipType rotateFlipType) => GdipImageRotateFlip_ptr.Delegate(image, rotateFlipType);
- private delegate Status GdipSaveImageToFile_delegate(IntPtr image, [MarshalAs(UnmanagedType.LPWStr)]string filename, ref Guid encoderClsID, IntPtr encoderParameters);
+ private delegate int GdipSaveImageToFile_delegate(IntPtr image, [MarshalAs(UnmanagedType.LPWStr)]string filename, ref Guid encoderClsID, IntPtr encoderParameters);
private static FunctionWrapper<GdipSaveImageToFile_delegate> GdipSaveImageToFile_ptr;
- internal static Status GdipSaveImageToFile(IntPtr image, string filename, ref Guid encoderClsID, IntPtr encoderParameters) => GdipSaveImageToFile_ptr.Delegate(image, filename, ref encoderClsID, encoderParameters);
+ internal static int GdipSaveImageToFile(IntPtr image, string filename, ref Guid encoderClsID, IntPtr encoderParameters) => GdipSaveImageToFile_ptr.Delegate(image, filename, ref encoderClsID, encoderParameters);
- private delegate Status GdipSaveAdd_delegate(IntPtr image, IntPtr encoderParameters);
+ private delegate int GdipSaveAdd_delegate(IntPtr image, IntPtr encoderParameters);
private static FunctionWrapper<GdipSaveAdd_delegate> GdipSaveAdd_ptr;
- internal static Status GdipSaveAdd(IntPtr image, IntPtr encoderParameters) => GdipSaveAdd_ptr.Delegate(image, encoderParameters);
+ internal static int GdipSaveAdd(IntPtr image, IntPtr encoderParameters) => GdipSaveAdd_ptr.Delegate(image, encoderParameters);
- private delegate Status GdipSaveAddImage_delegate(IntPtr image, IntPtr imagenew, IntPtr encoderParameters);
+ private delegate int GdipSaveAddImage_delegate(IntPtr image, IntPtr imagenew, IntPtr encoderParameters);
private static FunctionWrapper<GdipSaveAddImage_delegate> GdipSaveAddImage_ptr;
- internal static Status GdipSaveAddImage(IntPtr image, IntPtr imagenew, IntPtr encoderParameters) => GdipSaveAddImage_ptr.Delegate(image, imagenew, encoderParameters);
+ internal static int GdipSaveAddImage(IntPtr image, IntPtr imagenew, IntPtr encoderParameters) => GdipSaveAddImage_ptr.Delegate(image, imagenew, encoderParameters);
- private delegate Status GdipDrawImageI_delegate(IntPtr graphics, IntPtr image, int x, int y);
+ private delegate int GdipDrawImageI_delegate(IntPtr graphics, IntPtr image, int x, int y);
private static FunctionWrapper<GdipDrawImageI_delegate> GdipDrawImageI_ptr;
- internal static Status GdipDrawImageI(IntPtr graphics, IntPtr image, int x, int y) => GdipDrawImageI_ptr.Delegate(graphics, image, x, y);
+ internal static int GdipDrawImageI(IntPtr graphics, IntPtr image, int x, int y) => GdipDrawImageI_ptr.Delegate(graphics, image, x, y);
- private delegate Status GdipGetImageGraphicsContext_delegate(IntPtr image, out IntPtr graphics);
+ private delegate int GdipGetImageGraphicsContext_delegate(IntPtr image, out IntPtr graphics);
private static FunctionWrapper<GdipGetImageGraphicsContext_delegate> GdipGetImageGraphicsContext_ptr;
- internal static Status GdipGetImageGraphicsContext(IntPtr image, out IntPtr graphics) => GdipGetImageGraphicsContext_ptr.Delegate(image, out graphics);
+ internal static int GdipGetImageGraphicsContext(IntPtr image, out IntPtr graphics) => GdipGetImageGraphicsContext_ptr.Delegate(image, out graphics);
- private delegate Status GdipDrawImage_delegate(IntPtr graphics, IntPtr image, float x, float y);
+ private delegate int GdipDrawImage_delegate(IntPtr graphics, IntPtr image, float x, float y);
private static FunctionWrapper<GdipDrawImage_delegate> GdipDrawImage_ptr;
- internal static Status GdipDrawImage(IntPtr graphics, IntPtr image, float x, float y) => GdipDrawImage_ptr.Delegate(graphics, image, x, y);
+ internal static int GdipDrawImage(IntPtr graphics, IntPtr image, float x, float y) => GdipDrawImage_ptr.Delegate(graphics, image, x, y);
- private delegate Status GdipDrawImagePoints_delegate(IntPtr graphics, IntPtr image, PointF[] destPoints, int count);
+ private delegate int GdipDrawImagePoints_delegate(IntPtr graphics, IntPtr image, PointF[] destPoints, int count);
private static FunctionWrapper<GdipDrawImagePoints_delegate> GdipDrawImagePoints_ptr;
- internal static Status GdipDrawImagePoints(IntPtr graphics, IntPtr image, PointF[] destPoints, int count) => GdipDrawImagePoints_ptr.Delegate(graphics, image, destPoints, count);
+ internal static int GdipDrawImagePoints(IntPtr graphics, IntPtr image, PointF[] destPoints, int count) => GdipDrawImagePoints_ptr.Delegate(graphics, image, destPoints, count);
- private delegate Status GdipDrawImagePointsI_delegate(IntPtr graphics, IntPtr image, Point[] destPoints, int count);
+ private delegate int GdipDrawImagePointsI_delegate(IntPtr graphics, IntPtr image, Point[] destPoints, int count);
private static FunctionWrapper<GdipDrawImagePointsI_delegate> GdipDrawImagePointsI_ptr;
- internal static Status GdipDrawImagePointsI(IntPtr graphics, IntPtr image, Point[] destPoints, int count) => GdipDrawImagePointsI_ptr.Delegate(graphics, image, destPoints, count);
+ internal static int GdipDrawImagePointsI(IntPtr graphics, IntPtr image, Point[] destPoints, int count) => GdipDrawImagePointsI_ptr.Delegate(graphics, image, destPoints, count);
- private delegate Status GdipDrawImageRectRectI_delegate(IntPtr graphics, IntPtr image, int dstx, int dsty, int dstwidth, int dstheight, int srcx, int srcy, int srcwidth, int srcheight, GraphicsUnit srcUnit, IntPtr imageattr, Graphics.DrawImageAbort callback, IntPtr callbackData);
+ private delegate int GdipDrawImageRectRectI_delegate(IntPtr graphics, IntPtr image, int dstx, int dsty, int dstwidth, int dstheight, int srcx, int srcy, int srcwidth, int srcheight, GraphicsUnit srcUnit, IntPtr imageattr, Graphics.DrawImageAbort callback, IntPtr callbackData);
private static FunctionWrapper<GdipDrawImageRectRectI_delegate> GdipDrawImageRectRectI_ptr;
- internal static Status GdipDrawImageRectRectI(IntPtr graphics, IntPtr image, int dstx, int dsty, int dstwidth, int dstheight, int srcx, int srcy, int srcwidth, int srcheight, GraphicsUnit srcUnit, IntPtr imageattr, Graphics.DrawImageAbort callback, IntPtr callbackData) => GdipDrawImageRectRectI_ptr.Delegate(graphics, image, dstx, dsty, dstwidth, dstheight, srcx, srcy, srcwidth, srcheight, srcUnit, imageattr, callback, callbackData);
+ internal static int GdipDrawImageRectRectI(IntPtr graphics, IntPtr image, int dstx, int dsty, int dstwidth, int dstheight, int srcx, int srcy, int srcwidth, int srcheight, GraphicsUnit srcUnit, IntPtr imageattr, Graphics.DrawImageAbort callback, IntPtr callbackData) => GdipDrawImageRectRectI_ptr.Delegate(graphics, image, dstx, dsty, dstwidth, dstheight, srcx, srcy, srcwidth, srcheight, srcUnit, imageattr, callback, callbackData);
- private delegate Status GdipDrawImageRectRect_delegate(IntPtr graphics, IntPtr image, float dstx, float dsty, float dstwidth, float dstheight, float srcx, float srcy, float srcwidth, float srcheight, GraphicsUnit srcUnit, IntPtr imageattr, Graphics.DrawImageAbort callback, IntPtr callbackData);
+ private delegate int GdipDrawImageRectRect_delegate(IntPtr graphics, IntPtr image, float dstx, float dsty, float dstwidth, float dstheight, float srcx, float srcy, float srcwidth, float srcheight, GraphicsUnit srcUnit, IntPtr imageattr, Graphics.DrawImageAbort callback, IntPtr callbackData);
private static FunctionWrapper<GdipDrawImageRectRect_delegate> GdipDrawImageRectRect_ptr;
- internal static Status GdipDrawImageRectRect(IntPtr graphics, IntPtr image, float dstx, float dsty, float dstwidth, float dstheight, float srcx, float srcy, float srcwidth, float srcheight, GraphicsUnit srcUnit, IntPtr imageattr, Graphics.DrawImageAbort callback, IntPtr callbackData) => GdipDrawImageRectRect_ptr.Delegate(graphics, image, dstx, dsty, dstwidth, dstheight, srcx, srcy, srcwidth, srcheight, srcUnit, imageattr, callback, callbackData);
+ internal static int GdipDrawImageRectRect(IntPtr graphics, IntPtr image, float dstx, float dsty, float dstwidth, float dstheight, float srcx, float srcy, float srcwidth, float srcheight, GraphicsUnit srcUnit, IntPtr imageattr, Graphics.DrawImageAbort callback, IntPtr callbackData) => GdipDrawImageRectRect_ptr.Delegate(graphics, image, dstx, dsty, dstwidth, dstheight, srcx, srcy, srcwidth, srcheight, srcUnit, imageattr, callback, callbackData);
- private delegate Status GdipDrawImagePointsRectI_delegate(IntPtr graphics, IntPtr image, Point[] destPoints, int count, int srcx, int srcy, int srcwidth, int srcheight, GraphicsUnit srcUnit, IntPtr imageattr, Graphics.DrawImageAbort callback, IntPtr callbackData);
+ private delegate int GdipDrawImagePointsRectI_delegate(IntPtr graphics, IntPtr image, Point[] destPoints, int count, int srcx, int srcy, int srcwidth, int srcheight, GraphicsUnit srcUnit, IntPtr imageattr, Graphics.DrawImageAbort callback, IntPtr callbackData);
private static FunctionWrapper<GdipDrawImagePointsRectI_delegate> GdipDrawImagePointsRectI_ptr;
- internal static Status GdipDrawImagePointsRectI(IntPtr graphics, IntPtr image, Point[] destPoints, int count, int srcx, int srcy, int srcwidth, int srcheight, GraphicsUnit srcUnit, IntPtr imageattr, Graphics.DrawImageAbort callback, IntPtr callbackData) => GdipDrawImagePointsRectI_ptr.Delegate(graphics, image, destPoints, count, srcx, srcy, srcwidth, srcheight, srcUnit, imageattr, callback, callbackData);
+ internal static int GdipDrawImagePointsRectI(IntPtr graphics, IntPtr image, Point[] destPoints, int count, int srcx, int srcy, int srcwidth, int srcheight, GraphicsUnit srcUnit, IntPtr imageattr, Graphics.DrawImageAbort callback, IntPtr callbackData) => GdipDrawImagePointsRectI_ptr.Delegate(graphics, image, destPoints, count, srcx, srcy, srcwidth, srcheight, srcUnit, imageattr, callback, callbackData);
- private delegate Status GdipDrawImagePointsRect_delegate(IntPtr graphics, IntPtr image, PointF[] destPoints, int count, float srcx, float srcy, float srcwidth, float srcheight, GraphicsUnit srcUnit, IntPtr imageattr, Graphics.DrawImageAbort callback, IntPtr callbackData);
+ private delegate int GdipDrawImagePointsRect_delegate(IntPtr graphics, IntPtr image, PointF[] destPoints, int count, float srcx, float srcy, float srcwidth, float srcheight, GraphicsUnit srcUnit, IntPtr imageattr, Graphics.DrawImageAbort callback, IntPtr callbackData);
private static FunctionWrapper<GdipDrawImagePointsRect_delegate> GdipDrawImagePointsRect_ptr;
- internal static Status GdipDrawImagePointsRect(IntPtr graphics, IntPtr image, PointF[] destPoints, int count, float srcx, float srcy, float srcwidth, float srcheight, GraphicsUnit srcUnit, IntPtr imageattr, Graphics.DrawImageAbort callback, IntPtr callbackData) => GdipDrawImagePointsRect_ptr.Delegate(graphics, image, destPoints, count, srcx, srcy, srcwidth, srcheight, srcUnit, imageattr, callback, callbackData);
+ internal static int GdipDrawImagePointsRect(IntPtr graphics, IntPtr image, PointF[] destPoints, int count, float srcx, float srcy, float srcwidth, float srcheight, GraphicsUnit srcUnit, IntPtr imageattr, Graphics.DrawImageAbort callback, IntPtr callbackData) => GdipDrawImagePointsRect_ptr.Delegate(graphics, image, destPoints, count, srcx, srcy, srcwidth, srcheight, srcUnit, imageattr, callback, callbackData);
- private delegate Status GdipDrawImageRect_delegate(IntPtr graphics, IntPtr image, float x, float y, float width, float height);
+ private delegate int GdipDrawImageRect_delegate(IntPtr graphics, IntPtr image, float x, float y, float width, float height);
private static FunctionWrapper<GdipDrawImageRect_delegate> GdipDrawImageRect_ptr;
- internal static Status GdipDrawImageRect(IntPtr graphics, IntPtr image, float x, float y, float width, float height) => GdipDrawImageRect_ptr.Delegate(graphics, image, x, y, width, height);
+ internal static int GdipDrawImageRect(IntPtr graphics, IntPtr image, float x, float y, float width, float height) => GdipDrawImageRect_ptr.Delegate(graphics, image, x, y, width, height);
- private delegate Status GdipDrawImagePointRect_delegate(IntPtr graphics, IntPtr image, float x, float y, float srcx, float srcy, float srcwidth, float srcheight, GraphicsUnit srcUnit);
+ private delegate int GdipDrawImagePointRect_delegate(IntPtr graphics, IntPtr image, float x, float y, float srcx, float srcy, float srcwidth, float srcheight, GraphicsUnit srcUnit);
private static FunctionWrapper<GdipDrawImagePointRect_delegate> GdipDrawImagePointRect_ptr;
- internal static Status GdipDrawImagePointRect(IntPtr graphics, IntPtr image, float x, float y, float srcx, float srcy, float srcwidth, float srcheight, GraphicsUnit srcUnit) => GdipDrawImagePointRect_ptr.Delegate(graphics, image, x, y, srcx, srcy, srcwidth, srcheight, srcUnit);
+ internal static int GdipDrawImagePointRect(IntPtr graphics, IntPtr image, float x, float y, float srcx, float srcy, float srcwidth, float srcheight, GraphicsUnit srcUnit) => GdipDrawImagePointRect_ptr.Delegate(graphics, image, x, y, srcx, srcy, srcwidth, srcheight, srcUnit);
- private delegate Status GdipDrawImagePointRectI_delegate(IntPtr graphics, IntPtr image, int x, int y, int srcx, int srcy, int srcwidth, int srcheight, GraphicsUnit srcUnit);
+ private delegate int GdipDrawImagePointRectI_delegate(IntPtr graphics, IntPtr image, int x, int y, int srcx, int srcy, int srcwidth, int srcheight, GraphicsUnit srcUnit);
private static FunctionWrapper<GdipDrawImagePointRectI_delegate> GdipDrawImagePointRectI_ptr;
- internal static Status GdipDrawImagePointRectI(IntPtr graphics, IntPtr image, int x, int y, int srcx, int srcy, int srcwidth, int srcheight, GraphicsUnit srcUnit) => GdipDrawImagePointRectI_ptr.Delegate(graphics, image, x, y, srcx, srcy, srcwidth, srcheight, srcUnit);
+ internal static int GdipDrawImagePointRectI(IntPtr graphics, IntPtr image, int x, int y, int srcx, int srcy, int srcwidth, int srcheight, GraphicsUnit srcUnit) => GdipDrawImagePointRectI_ptr.Delegate(graphics, image, x, y, srcx, srcy, srcwidth, srcheight, srcUnit);
- private delegate Status GdipCreateHBITMAPFromBitmap_delegate(IntPtr bmp, out IntPtr HandleBmp, int clrbackground);
+ private delegate int GdipCreateHBITMAPFromBitmap_delegate(IntPtr bmp, out IntPtr HandleBmp, int clrbackground);
private static FunctionWrapper<GdipCreateHBITMAPFromBitmap_delegate> GdipCreateHBITMAPFromBitmap_ptr;
- internal static Status GdipCreateHBITMAPFromBitmap(IntPtr bmp, out IntPtr HandleBmp, int clrbackground) => GdipCreateHBITMAPFromBitmap_ptr.Delegate(bmp, out HandleBmp, clrbackground);
+ internal static int GdipCreateHBITMAPFromBitmap(IntPtr bmp, out IntPtr HandleBmp, int clrbackground) => GdipCreateHBITMAPFromBitmap_ptr.Delegate(bmp, out HandleBmp, clrbackground);
- private delegate Status GdipCreateBitmapFromFile_delegate([MarshalAs(UnmanagedType.LPWStr)]string filename, out IntPtr bitmap);
+ private delegate int GdipCreateBitmapFromFile_delegate([MarshalAs(UnmanagedType.LPWStr)]string filename, out IntPtr bitmap);
private static FunctionWrapper<GdipCreateBitmapFromFile_delegate> GdipCreateBitmapFromFile_ptr;
- internal static Status GdipCreateBitmapFromFile(string filename, out IntPtr bitmap) => GdipCreateBitmapFromFile_ptr.Delegate(filename, out bitmap);
+ internal static int GdipCreateBitmapFromFile(string filename, out IntPtr bitmap) => GdipCreateBitmapFromFile_ptr.Delegate(filename, out bitmap);
- private delegate Status GdipCreateBitmapFromFileICM_delegate([MarshalAs(UnmanagedType.LPWStr)]string filename, out IntPtr bitmap);
+ private delegate int GdipCreateBitmapFromFileICM_delegate([MarshalAs(UnmanagedType.LPWStr)]string filename, out IntPtr bitmap);
private static FunctionWrapper<GdipCreateBitmapFromFileICM_delegate> GdipCreateBitmapFromFileICM_ptr;
- internal static Status GdipCreateBitmapFromFileICM(string filename, out IntPtr bitmap) => GdipCreateBitmapFromFileICM_ptr.Delegate(filename, out bitmap);
+ internal static int GdipCreateBitmapFromFileICM(string filename, out IntPtr bitmap) => GdipCreateBitmapFromFileICM_ptr.Delegate(filename, out bitmap);
- private delegate Status GdipCreateHICONFromBitmap_delegate(IntPtr bmp, out IntPtr HandleIcon);
+ private delegate int GdipCreateHICONFromBitmap_delegate(IntPtr bmp, out IntPtr HandleIcon);
private static FunctionWrapper<GdipCreateHICONFromBitmap_delegate> GdipCreateHICONFromBitmap_ptr;
- internal static Status GdipCreateHICONFromBitmap(IntPtr bmp, out IntPtr HandleIcon) => GdipCreateHICONFromBitmap_ptr.Delegate(bmp, out HandleIcon);
+ internal static int GdipCreateHICONFromBitmap(IntPtr bmp, out IntPtr HandleIcon) => GdipCreateHICONFromBitmap_ptr.Delegate(bmp, out HandleIcon);
- private delegate Status GdipCreateBitmapFromHICON_delegate(IntPtr hicon, out IntPtr bitmap);
+ private delegate int GdipCreateBitmapFromHICON_delegate(IntPtr hicon, out IntPtr bitmap);
private static FunctionWrapper<GdipCreateBitmapFromHICON_delegate> GdipCreateBitmapFromHICON_ptr;
- internal static Status GdipCreateBitmapFromHICON(IntPtr hicon, out IntPtr bitmap) => GdipCreateBitmapFromHICON_ptr.Delegate(hicon, out bitmap);
+ internal static int GdipCreateBitmapFromHICON(IntPtr hicon, out IntPtr bitmap) => GdipCreateBitmapFromHICON_ptr.Delegate(hicon, out bitmap);
- private delegate Status GdipCreateBitmapFromResource_delegate(IntPtr hInstance, [MarshalAs(UnmanagedType.LPWStr)]string lpBitmapName, out IntPtr bitmap);
+ private delegate int GdipCreateBitmapFromResource_delegate(IntPtr hInstance, [MarshalAs(UnmanagedType.LPWStr)]string lpBitmapName, out IntPtr bitmap);
private static FunctionWrapper<GdipCreateBitmapFromResource_delegate> GdipCreateBitmapFromResource_ptr;
- internal static Status GdipCreateBitmapFromResource(IntPtr hInstance, string lpBitmapName, out IntPtr bitmap) => GdipCreateBitmapFromResource_ptr.Delegate(hInstance, lpBitmapName, out bitmap);
+ internal static int GdipCreateBitmapFromResource(IntPtr hInstance, string lpBitmapName, out IntPtr bitmap) => GdipCreateBitmapFromResource_ptr.Delegate(hInstance, lpBitmapName, out bitmap);
- private delegate Status GdipCreatePath_delegate(FillMode brushMode, out IntPtr path);
+ private delegate int GdipCreatePath_delegate(FillMode brushMode, out IntPtr path);
private static FunctionWrapper<GdipCreatePath_delegate> GdipCreatePath_ptr;
- internal static Status GdipCreatePath(FillMode brushMode, out IntPtr path) => GdipCreatePath_ptr.Delegate(brushMode, out path);
+ internal static int GdipCreatePath(FillMode brushMode, out IntPtr path) => GdipCreatePath_ptr.Delegate(brushMode, out path);
- private delegate Status GdipCreatePath2_delegate(PointF[] points, byte[] types, int count, FillMode brushMode, out IntPtr path);
+ private delegate int GdipCreatePath2_delegate(PointF[] points, byte[] types, int count, FillMode brushMode, out IntPtr path);
private static FunctionWrapper<GdipCreatePath2_delegate> GdipCreatePath2_ptr;
- internal static Status GdipCreatePath2(PointF[] points, byte[] types, int count, FillMode brushMode, out IntPtr path) => GdipCreatePath2_ptr.Delegate(points, types, count, brushMode, out path);
+ internal static int GdipCreatePath2(PointF[] points, byte[] types, int count, FillMode brushMode, out IntPtr path) => GdipCreatePath2_ptr.Delegate(points, types, count, brushMode, out path);
- private delegate Status GdipCreatePath2I_delegate(Point[] points, byte[] types, int count, FillMode brushMode, out IntPtr path);
+ private delegate int GdipCreatePath2I_delegate(Point[] points, byte[] types, int count, FillMode brushMode, out IntPtr path);
private static FunctionWrapper<GdipCreatePath2I_delegate> GdipCreatePath2I_ptr;
- internal static Status GdipCreatePath2I(Point[] points, byte[] types, int count, FillMode brushMode, out IntPtr path) => GdipCreatePath2I_ptr.Delegate(points, types, count, brushMode, out path);
+ internal static int GdipCreatePath2I(Point[] points, byte[] types, int count, FillMode brushMode, out IntPtr path) => GdipCreatePath2I_ptr.Delegate(points, types, count, brushMode, out path);
- private delegate Status GdipClonePath_delegate(IntPtr path, out IntPtr clonePath);
+ private delegate int GdipClonePath_delegate(IntPtr path, out IntPtr clonePath);
private static FunctionWrapper<GdipClonePath_delegate> GdipClonePath_ptr;
- internal static Status GdipClonePath(IntPtr path, out IntPtr clonePath) => GdipClonePath_ptr.Delegate(path, out clonePath);
+ internal static int GdipClonePath(IntPtr path, out IntPtr clonePath) => GdipClonePath_ptr.Delegate(path, out clonePath);
- private delegate Status GdipDeletePath_delegate(IntPtr path);
+ private delegate int GdipDeletePath_delegate(IntPtr path);
private static FunctionWrapper<GdipDeletePath_delegate> GdipDeletePath_ptr;
- internal static Status GdipDeletePath(IntPtr path) => GdipDeletePath_ptr.Delegate(path);
+ internal static int GdipDeletePath(IntPtr path) => GdipDeletePath_ptr.Delegate(path);
internal static int IntGdipDeletePath(HandleRef path) => (int)GdipDeletePath_ptr.Delegate(path.Handle);
- private delegate Status GdipResetPath_delegate(IntPtr path);
+ private delegate int GdipResetPath_delegate(IntPtr path);
private static FunctionWrapper<GdipResetPath_delegate> GdipResetPath_ptr;
- internal static Status GdipResetPath(IntPtr path) => GdipResetPath_ptr.Delegate(path);
+ internal static int GdipResetPath(IntPtr path) => GdipResetPath_ptr.Delegate(path);
- private delegate Status GdipGetPointCount_delegate(IntPtr path, out int count);
+ private delegate int GdipGetPointCount_delegate(IntPtr path, out int count);
private static FunctionWrapper<GdipGetPointCount_delegate> GdipGetPointCount_ptr;
- internal static Status GdipGetPointCount(IntPtr path, out int count) => GdipGetPointCount_ptr.Delegate(path, out count);
+ internal static int GdipGetPointCount(IntPtr path, out int count) => GdipGetPointCount_ptr.Delegate(path, out count);
- private delegate Status GdipGetPathTypes_delegate(IntPtr path, [Out] byte[] types, int count);
+ private delegate int GdipGetPathTypes_delegate(IntPtr path, [Out] byte[] types, int count);
private static FunctionWrapper<GdipGetPathTypes_delegate> GdipGetPathTypes_ptr;
- internal static Status GdipGetPathTypes(IntPtr path, [Out] byte[] types, int count) => GdipGetPathTypes_ptr.Delegate(path, types, count);
+ internal static int GdipGetPathTypes(IntPtr path, [Out] byte[] types, int count) => GdipGetPathTypes_ptr.Delegate(path, types, count);
- private delegate Status GdipGetPathPoints_delegate(IntPtr path, [Out] PointF[] points, int count);
+ private delegate int GdipGetPathPoints_delegate(IntPtr path, [Out] PointF[] points, int count);
private static FunctionWrapper<GdipGetPathPoints_delegate> GdipGetPathPoints_ptr;
- internal static Status GdipGetPathPoints(IntPtr path, [Out] PointF[] points, int count) => GdipGetPathPoints_ptr.Delegate(path, points, count);
+ internal static int GdipGetPathPoints(IntPtr path, [Out] PointF[] points, int count) => GdipGetPathPoints_ptr.Delegate(path, points, count);
- private delegate Status GdipGetPathPointsI_delegate(IntPtr path, [Out] Point[] points, int count);
+ private delegate int GdipGetPathPointsI_delegate(IntPtr path, [Out] Point[] points, int count);
private static FunctionWrapper<GdipGetPathPointsI_delegate> GdipGetPathPointsI_ptr;
- internal static Status GdipGetPathPointsI(IntPtr path, [Out] Point[] points, int count) => GdipGetPathPointsI_ptr.Delegate(path, points, count);
+ internal static int GdipGetPathPointsI(IntPtr path, [Out] Point[] points, int count) => GdipGetPathPointsI_ptr.Delegate(path, points, count);
- private delegate Status GdipGetPathFillMode_delegate(IntPtr path, out FillMode fillMode);
+ private delegate int GdipGetPathFillMode_delegate(IntPtr path, out FillMode fillMode);
private static FunctionWrapper<GdipGetPathFillMode_delegate> GdipGetPathFillMode_ptr;
- internal static Status GdipGetPathFillMode(IntPtr path, out FillMode fillMode) => GdipGetPathFillMode_ptr.Delegate(path, out fillMode);
+ internal static int GdipGetPathFillMode(IntPtr path, out FillMode fillMode) => GdipGetPathFillMode_ptr.Delegate(path, out fillMode);
- private delegate Status GdipSetPathFillMode_delegate(IntPtr path, FillMode fillMode);
+ private delegate int GdipSetPathFillMode_delegate(IntPtr path, FillMode fillMode);
private static FunctionWrapper<GdipSetPathFillMode_delegate> GdipSetPathFillMode_ptr;
- internal static Status GdipSetPathFillMode(IntPtr path, FillMode fillMode) => GdipSetPathFillMode_ptr.Delegate(path, fillMode);
+ internal static int GdipSetPathFillMode(IntPtr path, FillMode fillMode) => GdipSetPathFillMode_ptr.Delegate(path, fillMode);
- private delegate Status GdipStartPathFigure_delegate(IntPtr path);
+ private delegate int GdipStartPathFigure_delegate(IntPtr path);
private static FunctionWrapper<GdipStartPathFigure_delegate> GdipStartPathFigure_ptr;
- internal static Status GdipStartPathFigure(IntPtr path) => GdipStartPathFigure_ptr.Delegate(path);
+ internal static int GdipStartPathFigure(IntPtr path) => GdipStartPathFigure_ptr.Delegate(path);
- private delegate Status GdipClosePathFigure_delegate(IntPtr path);
+ private delegate int GdipClosePathFigure_delegate(IntPtr path);
private static FunctionWrapper<GdipClosePathFigure_delegate> GdipClosePathFigure_ptr;
- internal static Status GdipClosePathFigure(IntPtr path) => GdipClosePathFigure_ptr.Delegate(path);
+ internal static int GdipClosePathFigure(IntPtr path) => GdipClosePathFigure_ptr.Delegate(path);
- private delegate Status GdipClosePathFigures_delegate(IntPtr path);
+ private delegate int GdipClosePathFigures_delegate(IntPtr path);
private static FunctionWrapper<GdipClosePathFigures_delegate> GdipClosePathFigures_ptr;
- internal static Status GdipClosePathFigures(IntPtr path) => GdipClosePathFigures_ptr.Delegate(path);
+ internal static int GdipClosePathFigures(IntPtr path) => GdipClosePathFigures_ptr.Delegate(path);
- private delegate Status GdipSetPathMarker_delegate(IntPtr path);
+ private delegate int GdipSetPathMarker_delegate(IntPtr path);
private static FunctionWrapper<GdipSetPathMarker_delegate> GdipSetPathMarker_ptr;
- internal static Status GdipSetPathMarker(IntPtr path) => GdipSetPathMarker_ptr.Delegate(path);
+ internal static int GdipSetPathMarker(IntPtr path) => GdipSetPathMarker_ptr.Delegate(path);
- private delegate Status GdipClearPathMarkers_delegate(IntPtr path);
+ private delegate int GdipClearPathMarkers_delegate(IntPtr path);
private static FunctionWrapper<GdipClearPathMarkers_delegate> GdipClearPathMarkers_ptr;
- internal static Status GdipClearPathMarkers(IntPtr path) => GdipClearPathMarkers_ptr.Delegate(path);
+ internal static int GdipClearPathMarkers(IntPtr path) => GdipClearPathMarkers_ptr.Delegate(path);
- private delegate Status GdipReversePath_delegate(IntPtr path);
+ private delegate int GdipReversePath_delegate(IntPtr path);
private static FunctionWrapper<GdipReversePath_delegate> GdipReversePath_ptr;
- internal static Status GdipReversePath(IntPtr path) => GdipReversePath_ptr.Delegate(path);
+ internal static int GdipReversePath(IntPtr path) => GdipReversePath_ptr.Delegate(path);
- private delegate Status GdipGetPathLastPoint_delegate(IntPtr path, out PointF lastPoint);
+ private delegate int GdipGetPathLastPoint_delegate(IntPtr path, out PointF lastPoint);
private static FunctionWrapper<GdipGetPathLastPoint_delegate> GdipGetPathLastPoint_ptr;
- internal static Status GdipGetPathLastPoint(IntPtr path, out PointF lastPoint) => GdipGetPathLastPoint_ptr.Delegate(path, out lastPoint);
+ internal static int GdipGetPathLastPoint(IntPtr path, out PointF lastPoint) => GdipGetPathLastPoint_ptr.Delegate(path, out lastPoint);
- private delegate Status GdipAddPathLine_delegate(IntPtr path, float x1, float y1, float x2, float y2);
+ private delegate int GdipAddPathLine_delegate(IntPtr path, float x1, float y1, float x2, float y2);
private static FunctionWrapper<GdipAddPathLine_delegate> GdipAddPathLine_ptr;
- internal static Status GdipAddPathLine(IntPtr path, float x1, float y1, float x2, float y2) => GdipAddPathLine_ptr.Delegate(path, x1, y1, x2, y2);
+ internal static int GdipAddPathLine(IntPtr path, float x1, float y1, float x2, float y2) => GdipAddPathLine_ptr.Delegate(path, x1, y1, x2, y2);
- private delegate Status GdipAddPathLine2_delegate(IntPtr path, PointF[] points, int count);
+ private delegate int GdipAddPathLine2_delegate(IntPtr path, PointF[] points, int count);
private static FunctionWrapper<GdipAddPathLine2_delegate> GdipAddPathLine2_ptr;
- internal static Status GdipAddPathLine2(IntPtr path, PointF[] points, int count) => GdipAddPathLine2_ptr.Delegate(path, points, count);
+ internal static int GdipAddPathLine2(IntPtr path, PointF[] points, int count) => GdipAddPathLine2_ptr.Delegate(path, points, count);
- private delegate Status GdipAddPathLine2I_delegate(IntPtr path, Point[] points, int count);
+ private delegate int GdipAddPathLine2I_delegate(IntPtr path, Point[] points, int count);
private static FunctionWrapper<GdipAddPathLine2I_delegate> GdipAddPathLine2I_ptr;
- internal static Status GdipAddPathLine2I(IntPtr path, Point[] points, int count) => GdipAddPathLine2I_ptr.Delegate(path, points, count);
+ internal static int GdipAddPathLine2I(IntPtr path, Point[] points, int count) => GdipAddPathLine2I_ptr.Delegate(path, points, count);
- private delegate Status GdipAddPathArc_delegate(IntPtr path, float x, float y, float width, float height, float startAngle, float sweepAngle);
+ private delegate int GdipAddPathArc_delegate(IntPtr path, float x, float y, float width, float height, float startAngle, float sweepAngle);
private static FunctionWrapper<GdipAddPathArc_delegate> GdipAddPathArc_ptr;
- internal static Status GdipAddPathArc(IntPtr path, float x, float y, float width, float height, float startAngle, float sweepAngle) => GdipAddPathArc_ptr.Delegate(path, x, y, width, height, startAngle, sweepAngle);
+ internal static int GdipAddPathArc(IntPtr path, float x, float y, float width, float height, float startAngle, float sweepAngle) => GdipAddPathArc_ptr.Delegate(path, x, y, width, height, startAngle, sweepAngle);
- private delegate Status GdipAddPathBezier_delegate(IntPtr path, float x1, float y1, float x2, float y2, float x3, float y3, float x4, float y4);
+ private delegate int GdipAddPathBezier_delegate(IntPtr path, float x1, float y1, float x2, float y2, float x3, float y3, float x4, float y4);
private static FunctionWrapper<GdipAddPathBezier_delegate> GdipAddPathBezier_ptr;
- internal static Status GdipAddPathBezier(IntPtr path, float x1, float y1, float x2, float y2, float x3, float y3, float x4, float y4) => GdipAddPathBezier_ptr.Delegate(path, x1, y1, x2, y2, x3, y3, x4, y4);
+ internal static int GdipAddPathBezier(IntPtr path, float x1, float y1, float x2, float y2, float x3, float y3, float x4, float y4) => GdipAddPathBezier_ptr.Delegate(path, x1, y1, x2, y2, x3, y3, x4, y4);
- private delegate Status GdipAddPathBeziers_delegate(IntPtr path, PointF[] points, int count);
+ private delegate int GdipAddPathBeziers_delegate(IntPtr path, PointF[] points, int count);
private static FunctionWrapper<GdipAddPathBeziers_delegate> GdipAddPathBeziers_ptr;
- internal static Status GdipAddPathBeziers(IntPtr path, PointF[] points, int count) => GdipAddPathBeziers_ptr.Delegate(path, points, count);
+ internal static int GdipAddPathBeziers(IntPtr path, PointF[] points, int count) => GdipAddPathBeziers_ptr.Delegate(path, points, count);
- private delegate Status GdipAddPathCurve_delegate(IntPtr path, PointF[] points, int count);
+ private delegate int GdipAddPathCurve_delegate(IntPtr path, PointF[] points, int count);
private static FunctionWrapper<GdipAddPathCurve_delegate> GdipAddPathCurve_ptr;
- internal static Status GdipAddPathCurve(IntPtr path, PointF[] points, int count) => GdipAddPathCurve_ptr.Delegate(path, points, count);
+ internal static int GdipAddPathCurve(IntPtr path, PointF[] points, int count) => GdipAddPathCurve_ptr.Delegate(path, points, count);
- private delegate Status GdipAddPathCurveI_delegate(IntPtr path, Point[] points, int count);
+ private delegate int GdipAddPathCurveI_delegate(IntPtr path, Point[] points, int count);
private static FunctionWrapper<GdipAddPathCurveI_delegate> GdipAddPathCurveI_ptr;
- internal static Status GdipAddPathCurveI(IntPtr path, Point[] points, int count) => GdipAddPathCurveI_ptr.Delegate(path, points, count);
+ internal static int GdipAddPathCurveI(IntPtr path, Point[] points, int count) => GdipAddPathCurveI_ptr.Delegate(path, points, count);
- private delegate Status GdipAddPathCurve2_delegate(IntPtr path, PointF[] points, int count, float tension);
+ private delegate int GdipAddPathCurve2_delegate(IntPtr path, PointF[] points, int count, float tension);
private static FunctionWrapper<GdipAddPathCurve2_delegate> GdipAddPathCurve2_ptr;
- internal static Status GdipAddPathCurve2(IntPtr path, PointF[] points, int count, float tension) => GdipAddPathCurve2_ptr.Delegate(path, points, count, tension);
+ internal static int GdipAddPathCurve2(IntPtr path, PointF[] points, int count, float tension) => GdipAddPathCurve2_ptr.Delegate(path, points, count, tension);
- private delegate Status GdipAddPathCurve2I_delegate(IntPtr path, Point[] points, int count, float tension);
+ private delegate int GdipAddPathCurve2I_delegate(IntPtr path, Point[] points, int count, float tension);
private static FunctionWrapper<GdipAddPathCurve2I_delegate> GdipAddPathCurve2I_ptr;
- internal static Status GdipAddPathCurve2I(IntPtr path, Point[] points, int count, float tension) => GdipAddPathCurve2I_ptr.Delegate(path, points, count, tension);
+ internal static int GdipAddPathCurve2I(IntPtr path, Point[] points, int count, float tension) => GdipAddPathCurve2I_ptr.Delegate(path, points, count, tension);
- private delegate Status GdipAddPathCurve3_delegate(IntPtr path, PointF[] points, int count, int offset, int numberOfSegments, float tension);
+ private delegate int GdipAddPathCurve3_delegate(IntPtr path, PointF[] points, int count, int offset, int numberOfSegments, float tension);
private static FunctionWrapper<GdipAddPathCurve3_delegate> GdipAddPathCurve3_ptr;
- internal static Status GdipAddPathCurve3(IntPtr path, PointF[] points, int count, int offset, int numberOfSegments, float tension) => GdipAddPathCurve3_ptr.Delegate(path, points, count, offset, numberOfSegments, tension);
+ internal static int GdipAddPathCurve3(IntPtr path, PointF[] points, int count, int offset, int numberOfSegments, float tension) => GdipAddPathCurve3_ptr.Delegate(path, points, count, offset, numberOfSegments, tension);
- private delegate Status GdipAddPathCurve3I_delegate(IntPtr path, Point[] points, int count, int offset, int numberOfSegments, float tension);
+ private delegate int GdipAddPathCurve3I_delegate(IntPtr path, Point[] points, int count, int offset, int numberOfSegments, float tension);
private static FunctionWrapper<GdipAddPathCurve3I_delegate> GdipAddPathCurve3I_ptr;
- internal static Status GdipAddPathCurve3I(IntPtr path, Point[] points, int count, int offset, int numberOfSegments, float tension) => GdipAddPathCurve3I_ptr.Delegate(path, points, count, offset, numberOfSegments, tension);
+ internal static int GdipAddPathCurve3I(IntPtr path, Point[] points, int count, int offset, int numberOfSegments, float tension) => GdipAddPathCurve3I_ptr.Delegate(path, points, count, offset, numberOfSegments, tension);
- private delegate Status GdipAddPathClosedCurve_delegate(IntPtr path, PointF[] points, int count);
+ private delegate int GdipAddPathClosedCurve_delegate(IntPtr path, PointF[] points, int count);
private static FunctionWrapper<GdipAddPathClosedCurve_delegate> GdipAddPathClosedCurve_ptr;
- internal static Status GdipAddPathClosedCurve(IntPtr path, PointF[] points, int count) => GdipAddPathClosedCurve_ptr.Delegate(path, points, count);
+ internal static int GdipAddPathClosedCurve(IntPtr path, PointF[] points, int count) => GdipAddPathClosedCurve_ptr.Delegate(path, points, count);
- private delegate Status GdipAddPathClosedCurveI_delegate(IntPtr path, Point[] points, int count);
+ private delegate int GdipAddPathClosedCurveI_delegate(IntPtr path, Point[] points, int count);
private static FunctionWrapper<GdipAddPathClosedCurveI_delegate> GdipAddPathClosedCurveI_ptr;
- internal static Status GdipAddPathClosedCurveI(IntPtr path, Point[] points, int count) => GdipAddPathClosedCurveI_ptr.Delegate(path, points, count);
+ internal static int GdipAddPathClosedCurveI(IntPtr path, Point[] points, int count) => GdipAddPathClosedCurveI_ptr.Delegate(path, points, count);
- private delegate Status GdipAddPathClosedCurve2_delegate(IntPtr path, PointF[] points, int count, float tension);
+ private delegate int GdipAddPathClosedCurve2_delegate(IntPtr path, PointF[] points, int count, float tension);
private static FunctionWrapper<GdipAddPathClosedCurve2_delegate> GdipAddPathClosedCurve2_ptr;
- internal static Status GdipAddPathClosedCurve2(IntPtr path, PointF[] points, int count, float tension) => GdipAddPathClosedCurve2_ptr.Delegate(path, points, count, tension);
+ internal static int GdipAddPathClosedCurve2(IntPtr path, PointF[] points, int count, float tension) => GdipAddPathClosedCurve2_ptr.Delegate(path, points, count, tension);
- private delegate Status GdipAddPathClosedCurve2I_delegate(IntPtr path, Point[] points, int count, float tension);
+ private delegate int GdipAddPathClosedCurve2I_delegate(IntPtr path, Point[] points, int count, float tension);
private static FunctionWrapper<GdipAddPathClosedCurve2I_delegate> GdipAddPathClosedCurve2I_ptr;
- internal static Status GdipAddPathClosedCurve2I(IntPtr path, Point[] points, int count, float tension) => GdipAddPathClosedCurve2I_ptr.Delegate(path, points, count, tension);
+ internal static int GdipAddPathClosedCurve2I(IntPtr path, Point[] points, int count, float tension) => GdipAddPathClosedCurve2I_ptr.Delegate(path, points, count, tension);
- private delegate Status GdipAddPathRectangle_delegate(IntPtr path, float x, float y, float width, float height);
+ private delegate int GdipAddPathRectangle_delegate(IntPtr path, float x, float y, float width, float height);
private static FunctionWrapper<GdipAddPathRectangle_delegate> GdipAddPathRectangle_ptr;
- internal static Status GdipAddPathRectangle(IntPtr path, float x, float y, float width, float height) => GdipAddPathRectangle_ptr.Delegate(path, x, y, width, height);
+ internal static int GdipAddPathRectangle(IntPtr path, float x, float y, float width, float height) => GdipAddPathRectangle_ptr.Delegate(path, x, y, width, height);
- private delegate Status GdipAddPathRectangles_delegate(IntPtr path, RectangleF[] rects, int count);
+ private delegate int GdipAddPathRectangles_delegate(IntPtr path, RectangleF[] rects, int count);
private static FunctionWrapper<GdipAddPathRectangles_delegate> GdipAddPathRectangles_ptr;
- internal static Status GdipAddPathRectangles(IntPtr path, RectangleF[] rects, int count) => GdipAddPathRectangles_ptr.Delegate(path, rects, count);
+ internal static int GdipAddPathRectangles(IntPtr path, RectangleF[] rects, int count) => GdipAddPathRectangles_ptr.Delegate(path, rects, count);
- private delegate Status GdipAddPathEllipse_delegate(IntPtr path, float x, float y, float width, float height);
+ private delegate int GdipAddPathEllipse_delegate(IntPtr path, float x, float y, float width, float height);
private static FunctionWrapper<GdipAddPathEllipse_delegate> GdipAddPathEllipse_ptr;
- internal static Status GdipAddPathEllipse(IntPtr path, float x, float y, float width, float height) => GdipAddPathEllipse_ptr.Delegate(path, x, y, width, height);
+ internal static int GdipAddPathEllipse(IntPtr path, float x, float y, float width, float height) => GdipAddPathEllipse_ptr.Delegate(path, x, y, width, height);
- private delegate Status GdipAddPathEllipseI_delegate(IntPtr path, int x, int y, int width, int height);
+ private delegate int GdipAddPathEllipseI_delegate(IntPtr path, int x, int y, int width, int height);
private static FunctionWrapper<GdipAddPathEllipseI_delegate> GdipAddPathEllipseI_ptr;
- internal static Status GdipAddPathEllipseI(IntPtr path, int x, int y, int width, int height) => GdipAddPathEllipseI_ptr.Delegate(path, x, y, width, height);
+ internal static int GdipAddPathEllipseI(IntPtr path, int x, int y, int width, int height) => GdipAddPathEllipseI_ptr.Delegate(path, x, y, width, height);
- private delegate Status GdipAddPathPie_delegate(IntPtr path, float x, float y, float width, float height, float startAngle, float sweepAngle);
+ private delegate int GdipAddPathPie_delegate(IntPtr path, float x, float y, float width, float height, float startAngle, float sweepAngle);
private static FunctionWrapper<GdipAddPathPie_delegate> GdipAddPathPie_ptr;
- internal static Status GdipAddPathPie(IntPtr path, float x, float y, float width, float height, float startAngle, float sweepAngle) => GdipAddPathPie_ptr.Delegate(path, x, y, width, height, startAngle, sweepAngle);
+ internal static int GdipAddPathPie(IntPtr path, float x, float y, float width, float height, float startAngle, float sweepAngle) => GdipAddPathPie_ptr.Delegate(path, x, y, width, height, startAngle, sweepAngle);
- private delegate Status GdipAddPathPieI_delegate(IntPtr path, int x, int y, int width, int height, float startAngle, float sweepAngle);
+ private delegate int GdipAddPathPieI_delegate(IntPtr path, int x, int y, int width, int height, float startAngle, float sweepAngle);
private static FunctionWrapper<GdipAddPathPieI_delegate> GdipAddPathPieI_ptr;
- internal static Status GdipAddPathPieI(IntPtr path, int x, int y, int width, int height, float startAngle, float sweepAngle) => GdipAddPathPieI_ptr.Delegate(path, x, y, width, height, startAngle, sweepAngle);
+ internal static int GdipAddPathPieI(IntPtr path, int x, int y, int width, int height, float startAngle, float sweepAngle) => GdipAddPathPieI_ptr.Delegate(path, x, y, width, height, startAngle, sweepAngle);
- private delegate Status GdipAddPathPolygon_delegate(IntPtr path, PointF[] points, int count);
+ private delegate int GdipAddPathPolygon_delegate(IntPtr path, PointF[] points, int count);
private static FunctionWrapper<GdipAddPathPolygon_delegate> GdipAddPathPolygon_ptr;
- internal static Status GdipAddPathPolygon(IntPtr path, PointF[] points, int count) => GdipAddPathPolygon_ptr.Delegate(path, points, count);
+ internal static int GdipAddPathPolygon(IntPtr path, PointF[] points, int count) => GdipAddPathPolygon_ptr.Delegate(path, points, count);
- private delegate Status GdipAddPathPath_delegate(IntPtr path, IntPtr addingPath, bool connect);
+ private delegate int GdipAddPathPath_delegate(IntPtr path, IntPtr addingPath, bool connect);
private static FunctionWrapper<GdipAddPathPath_delegate> GdipAddPathPath_ptr;
- internal static Status GdipAddPathPath(IntPtr path, IntPtr addingPath, bool connect) => GdipAddPathPath_ptr.Delegate(path, addingPath, connect);
+ internal static int GdipAddPathPath(IntPtr path, IntPtr addingPath, bool connect) => GdipAddPathPath_ptr.Delegate(path, addingPath, connect);
- private delegate Status GdipAddPathLineI_delegate(IntPtr path, int x1, int y1, int x2, int y2);
+ private delegate int GdipAddPathLineI_delegate(IntPtr path, int x1, int y1, int x2, int y2);
private static FunctionWrapper<GdipAddPathLineI_delegate> GdipAddPathLineI_ptr;
- internal static Status GdipAddPathLineI(IntPtr path, int x1, int y1, int x2, int y2) => GdipAddPathLineI_ptr.Delegate(path, x1, y1, x2, y2);
+ internal static int GdipAddPathLineI(IntPtr path, int x1, int y1, int x2, int y2) => GdipAddPathLineI_ptr.Delegate(path, x1, y1, x2, y2);
- private delegate Status GdipAddPathArcI_delegate(IntPtr path, int x, int y, int width, int height, float startAngle, float sweepAngle);
+ private delegate int GdipAddPathArcI_delegate(IntPtr path, int x, int y, int width, int height, float startAngle, float sweepAngle);
private static FunctionWrapper<GdipAddPathArcI_delegate> GdipAddPathArcI_ptr;
- internal static Status GdipAddPathArcI(IntPtr path, int x, int y, int width, int height, float startAngle, float sweepAngle) => GdipAddPathArcI_ptr.Delegate(path, x, y, width, height, startAngle, sweepAngle);
+ internal static int GdipAddPathArcI(IntPtr path, int x, int y, int width, int height, float startAngle, float sweepAngle) => GdipAddPathArcI_ptr.Delegate(path, x, y, width, height, startAngle, sweepAngle);
- private delegate Status GdipAddPathBezierI_delegate(IntPtr path, int x1, int y1, int x2, int y2, int x3, int y3, int x4, int y4);
+ private delegate int GdipAddPathBezierI_delegate(IntPtr path, int x1, int y1, int x2, int y2, int x3, int y3, int x4, int y4);
private static FunctionWrapper<GdipAddPathBezierI_delegate> GdipAddPathBezierI_ptr;
- internal static Status GdipAddPathBezierI(IntPtr path, int x1, int y1, int x2, int y2, int x3, int y3, int x4, int y4) => GdipAddPathBezierI_ptr.Delegate(path, x1, y1, x2, y2, x3, y3, x4, y4);
+ internal static int GdipAddPathBezierI(IntPtr path, int x1, int y1, int x2, int y2, int x3, int y3, int x4, int y4) => GdipAddPathBezierI_ptr.Delegate(path, x1, y1, x2, y2, x3, y3, x4, y4);
- private delegate Status GdipAddPathBeziersI_delegate(IntPtr path, Point[] points, int count);
+ private delegate int GdipAddPathBeziersI_delegate(IntPtr path, Point[] points, int count);
private static FunctionWrapper<GdipAddPathBeziersI_delegate> GdipAddPathBeziersI_ptr;
- internal static Status GdipAddPathBeziersI(IntPtr path, Point[] points, int count) => GdipAddPathBeziersI_ptr.Delegate(path, points, count);
+ internal static int GdipAddPathBeziersI(IntPtr path, Point[] points, int count) => GdipAddPathBeziersI_ptr.Delegate(path, points, count);
- private delegate Status GdipAddPathPolygonI_delegate(IntPtr path, Point[] points, int count);
+ private delegate int GdipAddPathPolygonI_delegate(IntPtr path, Point[] points, int count);
private static FunctionWrapper<GdipAddPathPolygonI_delegate> GdipAddPathPolygonI_ptr;
- internal static Status GdipAddPathPolygonI(IntPtr path, Point[] points, int count) => GdipAddPathPolygonI_ptr.Delegate(path, points, count);
+ internal static int GdipAddPathPolygonI(IntPtr path, Point[] points, int count) => GdipAddPathPolygonI_ptr.Delegate(path, points, count);
- private delegate Status GdipAddPathRectangleI_delegate(IntPtr path, int x, int y, int width, int height);
+ private delegate int GdipAddPathRectangleI_delegate(IntPtr path, int x, int y, int width, int height);
private static FunctionWrapper<GdipAddPathRectangleI_delegate> GdipAddPathRectangleI_ptr;
- internal static Status GdipAddPathRectangleI(IntPtr path, int x, int y, int width, int height) => GdipAddPathRectangleI_ptr.Delegate(path, x, y, width, height);
+ internal static int GdipAddPathRectangleI(IntPtr path, int x, int y, int width, int height) => GdipAddPathRectangleI_ptr.Delegate(path, x, y, width, height);
- private delegate Status GdipAddPathRectanglesI_delegate(IntPtr path, Rectangle[] rects, int count);
+ private delegate int GdipAddPathRectanglesI_delegate(IntPtr path, Rectangle[] rects, int count);
private static FunctionWrapper<GdipAddPathRectanglesI_delegate> GdipAddPathRectanglesI_ptr;
- internal static Status GdipAddPathRectanglesI(IntPtr path, Rectangle[] rects, int count) => GdipAddPathRectanglesI_ptr.Delegate(path, rects, count);
+ internal static int GdipAddPathRectanglesI(IntPtr path, Rectangle[] rects, int count) => GdipAddPathRectanglesI_ptr.Delegate(path, rects, count);
- private delegate Status GdipFlattenPath_delegate(IntPtr path, IntPtr matrix, float floatness);
+ private delegate int GdipFlattenPath_delegate(IntPtr path, IntPtr matrix, float floatness);
private static FunctionWrapper<GdipFlattenPath_delegate> GdipFlattenPath_ptr;
- internal static Status GdipFlattenPath(IntPtr path, IntPtr matrix, float floatness) => GdipFlattenPath_ptr.Delegate(path, matrix, floatness);
+ internal static int GdipFlattenPath(IntPtr path, IntPtr matrix, float floatness) => GdipFlattenPath_ptr.Delegate(path, matrix, floatness);
- private delegate Status GdipTransformPath_delegate(IntPtr path, IntPtr matrix);
+ private delegate int GdipTransformPath_delegate(IntPtr path, IntPtr matrix);
private static FunctionWrapper<GdipTransformPath_delegate> GdipTransformPath_ptr;
- internal static Status GdipTransformPath(IntPtr path, IntPtr matrix) => GdipTransformPath_ptr.Delegate(path, matrix);
+ internal static int GdipTransformPath(IntPtr path, IntPtr matrix) => GdipTransformPath_ptr.Delegate(path, matrix);
- private delegate Status GdipWarpPath_delegate(IntPtr path, IntPtr matrix, PointF[] points, int count, float srcx, float srcy, float srcwidth, float srcheight, WarpMode mode, float flatness);
+ private delegate int GdipWarpPath_delegate(IntPtr path, IntPtr matrix, PointF[] points, int count, float srcx, float srcy, float srcwidth, float srcheight, WarpMode mode, float flatness);
private static FunctionWrapper<GdipWarpPath_delegate> GdipWarpPath_ptr;
- internal static Status GdipWarpPath(IntPtr path, IntPtr matrix, PointF[] points, int count, float srcx, float srcy, float srcwidth, float srcheight, WarpMode mode, float flatness) => GdipWarpPath_ptr.Delegate(path, matrix, points, count, srcx, srcy, srcwidth, srcheight, mode, flatness);
+ internal static int GdipWarpPath(IntPtr path, IntPtr matrix, PointF[] points, int count, float srcx, float srcy, float srcwidth, float srcheight, WarpMode mode, float flatness) => GdipWarpPath_ptr.Delegate(path, matrix, points, count, srcx, srcy, srcwidth, srcheight, mode, flatness);
- private delegate Status GdipWidenPath_delegate(IntPtr path, IntPtr pen, IntPtr matrix, float flatness);
+ private delegate int GdipWidenPath_delegate(IntPtr path, IntPtr pen, IntPtr matrix, float flatness);
private static FunctionWrapper<GdipWidenPath_delegate> GdipWidenPath_ptr;
- internal static Status GdipWidenPath(IntPtr path, IntPtr pen, IntPtr matrix, float flatness) => GdipWidenPath_ptr.Delegate(path, pen, matrix, flatness);
+ internal static int GdipWidenPath(IntPtr path, IntPtr pen, IntPtr matrix, float flatness) => GdipWidenPath_ptr.Delegate(path, pen, matrix, flatness);
- private delegate Status GdipGetPathWorldBounds_delegate(IntPtr path, out RectangleF bounds, IntPtr matrix, IntPtr pen);
+ private delegate int GdipGetPathWorldBounds_delegate(IntPtr path, out RectangleF bounds, IntPtr matrix, IntPtr pen);
private static FunctionWrapper<GdipGetPathWorldBounds_delegate> GdipGetPathWorldBounds_ptr;
- internal static Status GdipGetPathWorldBounds(IntPtr path, out RectangleF bounds, IntPtr matrix, IntPtr pen) => GdipGetPathWorldBounds_ptr.Delegate(path, out bounds, matrix, pen);
+ internal static int GdipGetPathWorldBounds(IntPtr path, out RectangleF bounds, IntPtr matrix, IntPtr pen) => GdipGetPathWorldBounds_ptr.Delegate(path, out bounds, matrix, pen);
- private delegate Status GdipGetPathWorldBoundsI_delegate(IntPtr path, out Rectangle bounds, IntPtr matrix, IntPtr pen);
+ private delegate int GdipGetPathWorldBoundsI_delegate(IntPtr path, out Rectangle bounds, IntPtr matrix, IntPtr pen);
private static FunctionWrapper<GdipGetPathWorldBoundsI_delegate> GdipGetPathWorldBoundsI_ptr;
- internal static Status GdipGetPathWorldBoundsI(IntPtr path, out Rectangle bounds, IntPtr matrix, IntPtr pen) => GdipGetPathWorldBoundsI_ptr.Delegate(path, out bounds, matrix, pen);
+ internal static int GdipGetPathWorldBoundsI(IntPtr path, out Rectangle bounds, IntPtr matrix, IntPtr pen) => GdipGetPathWorldBoundsI_ptr.Delegate(path, out bounds, matrix, pen);
- private delegate Status GdipIsVisiblePathPoint_delegate(IntPtr path, float x, float y, IntPtr graphics, out bool result);
+ private delegate int GdipIsVisiblePathPoint_delegate(IntPtr path, float x, float y, IntPtr graphics, out bool result);
private static FunctionWrapper<GdipIsVisiblePathPoint_delegate> GdipIsVisiblePathPoint_ptr;
- internal static Status GdipIsVisiblePathPoint(IntPtr path, float x, float y, IntPtr graphics, out bool result) => GdipIsVisiblePathPoint_ptr.Delegate(path, x, y, graphics, out result);
+ internal static int GdipIsVisiblePathPoint(IntPtr path, float x, float y, IntPtr graphics, out bool result) => GdipIsVisiblePathPoint_ptr.Delegate(path, x, y, graphics, out result);
- private delegate Status GdipIsVisiblePathPointI_delegate(IntPtr path, int x, int y, IntPtr graphics, out bool result);
+ private delegate int GdipIsVisiblePathPointI_delegate(IntPtr path, int x, int y, IntPtr graphics, out bool result);
private static FunctionWrapper<GdipIsVisiblePathPointI_delegate> GdipIsVisiblePathPointI_ptr;
- internal static Status GdipIsVisiblePathPointI(IntPtr path, int x, int y, IntPtr graphics, out bool result) => GdipIsVisiblePathPointI_ptr.Delegate(path, x, y, graphics, out result);
+ internal static int GdipIsVisiblePathPointI(IntPtr path, int x, int y, IntPtr graphics, out bool result) => GdipIsVisiblePathPointI_ptr.Delegate(path, x, y, graphics, out result);
- private delegate Status GdipIsOutlineVisiblePathPoint_delegate(IntPtr path, float x, float y, IntPtr pen, IntPtr graphics, out bool result);
+ private delegate int GdipIsOutlineVisiblePathPoint_delegate(IntPtr path, float x, float y, IntPtr pen, IntPtr graphics, out bool result);
private static FunctionWrapper<GdipIsOutlineVisiblePathPoint_delegate> GdipIsOutlineVisiblePathPoint_ptr;
- internal static Status GdipIsOutlineVisiblePathPoint(IntPtr path, float x, float y, IntPtr pen, IntPtr graphics, out bool result) => GdipIsOutlineVisiblePathPoint_ptr.Delegate(path, x, y, pen, graphics, out result);
+ internal static int GdipIsOutlineVisiblePathPoint(IntPtr path, float x, float y, IntPtr pen, IntPtr graphics, out bool result) => GdipIsOutlineVisiblePathPoint_ptr.Delegate(path, x, y, pen, graphics, out result);
- private delegate Status GdipIsOutlineVisiblePathPointI_delegate(IntPtr path, int x, int y, IntPtr pen, IntPtr graphics, out bool result);
+ private delegate int GdipIsOutlineVisiblePathPointI_delegate(IntPtr path, int x, int y, IntPtr pen, IntPtr graphics, out bool result);
private static FunctionWrapper<GdipIsOutlineVisiblePathPointI_delegate> GdipIsOutlineVisiblePathPointI_ptr;
- internal static Status GdipIsOutlineVisiblePathPointI(IntPtr path, int x, int y, IntPtr pen, IntPtr graphics, out bool result) => GdipIsOutlineVisiblePathPointI_ptr.Delegate(path, x, y, pen, graphics, out result);
+ internal static int GdipIsOutlineVisiblePathPointI(IntPtr path, int x, int y, IntPtr pen, IntPtr graphics, out bool result) => GdipIsOutlineVisiblePathPointI_ptr.Delegate(path, x, y, pen, graphics, out result);
- private delegate Status GdipCreateFont_delegate(IntPtr fontFamily, float emSize, FontStyle style, GraphicsUnit unit, out IntPtr font);
+ private delegate int GdipCreateFont_delegate(IntPtr fontFamily, float emSize, FontStyle style, GraphicsUnit unit, out IntPtr font);
private static FunctionWrapper<GdipCreateFont_delegate> GdipCreateFont_ptr;
- internal static Status GdipCreateFont(IntPtr fontFamily, float emSize, FontStyle style, GraphicsUnit unit, out IntPtr font) => GdipCreateFont_ptr.Delegate(fontFamily, emSize, style, unit, out font);
+ internal static int GdipCreateFont(IntPtr fontFamily, float emSize, FontStyle style, GraphicsUnit unit, out IntPtr font) => GdipCreateFont_ptr.Delegate(fontFamily, emSize, style, unit, out font);
- private delegate Status GdipDeleteFont_delegate(IntPtr font);
+ private delegate int GdipDeleteFont_delegate(IntPtr font);
private static FunctionWrapper<GdipDeleteFont_delegate> GdipDeleteFont_ptr;
- internal static Status GdipDeleteFont(IntPtr font) => GdipDeleteFont_ptr.Delegate(font);
+ internal static int GdipDeleteFont(IntPtr font) => GdipDeleteFont_ptr.Delegate(font);
internal static int IntGdipDeleteFont(HandleRef font) => (int)GdipDeleteFont_ptr.Delegate(font.Handle);
#pragma warning disable CS0618 // Legacy code: We don't care about using obsolete API's.
- private delegate Status GdipGetLogFont_delegate(IntPtr font, IntPtr graphics, [MarshalAs(UnmanagedType.AsAny), Out] object logfontA);
+ private delegate int GdipGetLogFont_delegate(IntPtr font, IntPtr graphics, [MarshalAs(UnmanagedType.AsAny), Out] object logfontA);
#pragma warning restore CS0618
private static FunctionWrapper<GdipGetLogFont_delegate> GdipGetLogFont_ptr;
- internal static Status GdipGetLogFont(IntPtr font, IntPtr graphics, [Out] object logfontA) => GdipGetLogFont_ptr.Delegate(font, graphics, logfontA);
+ internal static int GdipGetLogFont(IntPtr font, IntPtr graphics, [Out] object logfontA) => GdipGetLogFont_ptr.Delegate(font, graphics, logfontA);
- private delegate Status GdipCreateFontFromDC_delegate(IntPtr hdc, out IntPtr font);
+ private delegate int GdipCreateFontFromDC_delegate(IntPtr hdc, out IntPtr font);
private static FunctionWrapper<GdipCreateFontFromDC_delegate> GdipCreateFontFromDC_ptr;
- internal static Status GdipCreateFontFromDC(IntPtr hdc, out IntPtr font) => GdipCreateFontFromDC_ptr.Delegate(hdc, out font);
+ internal static int GdipCreateFontFromDC(IntPtr hdc, out IntPtr font) => GdipCreateFontFromDC_ptr.Delegate(hdc, out font);
- private delegate Status GdipCreateFontFromLogfont_delegate(IntPtr hdc, ref LOGFONT lf, out IntPtr ptr);
+ private delegate int GdipCreateFontFromLogfont_delegate(IntPtr hdc, ref LOGFONT lf, out IntPtr ptr);
private static FunctionWrapper<GdipCreateFontFromLogfont_delegate> GdipCreateFontFromLogfont_ptr;
- internal static Status GdipCreateFontFromLogfont(IntPtr hdc, ref LOGFONT lf, out IntPtr ptr) => GdipCreateFontFromLogfont_ptr.Delegate(hdc, ref lf, out ptr);
+ internal static int GdipCreateFontFromLogfont(IntPtr hdc, ref LOGFONT lf, out IntPtr ptr) => GdipCreateFontFromLogfont_ptr.Delegate(hdc, ref lf, out ptr);
- private delegate Status GdipCreateFontFromHfont_delegate(IntPtr hdc, out IntPtr font, ref LOGFONT lf);
+ private delegate int GdipCreateFontFromHfont_delegate(IntPtr hdc, out IntPtr font, ref LOGFONT lf);
private static FunctionWrapper<GdipCreateFontFromHfont_delegate> GdipCreateFontFromHfont_ptr;
- internal static Status GdipCreateFontFromHfont(IntPtr hdc, out IntPtr font, ref LOGFONT lf) => GdipCreateFontFromHfont_ptr.Delegate(hdc, out font, ref lf);
-
- [UnmanagedFunctionPointer(CallingConvention.Cdecl, CharSet = CharSet.Auto)]
- private delegate Status GdipCreateFontFamilyFromName_delegate([MarshalAs(UnmanagedType.LPWStr)]string fName, IntPtr collection, out IntPtr fontFamily);
- private static FunctionWrapper<GdipCreateFontFamilyFromName_delegate> GdipCreateFontFamilyFromName_ptr;
- internal static Status GdipCreateFontFamilyFromName(string fName, IntPtr collection, out IntPtr fontFamily) => GdipCreateFontFamilyFromName_ptr.Delegate(fName, collection, out fontFamily);
-
- private delegate Status GdipGetFamilyName_delegate(IntPtr family, IntPtr name, int language);
- private static FunctionWrapper<GdipGetFamilyName_delegate> GdipGetFamilyName_ptr;
- internal static Status GdipGetFamilyName(IntPtr family, IntPtr name, int language) => GdipGetFamilyName_ptr.Delegate(family, name, language);
- internal static unsafe Status GdipGetFamilyName(IntPtr family, StringBuilder nameBuilder, int language)
- {
- const int LF_FACESIZE = 32;
- char* namePtr = stackalloc char[LF_FACESIZE];
- Status ret = GdipGetFamilyName(family, (IntPtr)namePtr, language);
- string name = Marshal.PtrToStringUni((IntPtr)namePtr);
- nameBuilder.Append(name);
- return ret;
- }
-
-
- private delegate Status GdipGetGenericFontFamilySansSerif_delegate(out IntPtr fontFamily);
- private static FunctionWrapper<GdipGetGenericFontFamilySansSerif_delegate> GdipGetGenericFontFamilySansSerif_ptr;
- internal static Status GdipGetGenericFontFamilySansSerif(out IntPtr fontFamily) => GdipGetGenericFontFamilySansSerif_ptr.Delegate(out fontFamily);
-
- private delegate Status GdipGetGenericFontFamilySerif_delegate(out IntPtr fontFamily);
- private static FunctionWrapper<GdipGetGenericFontFamilySerif_delegate> GdipGetGenericFontFamilySerif_ptr;
- internal static Status GdipGetGenericFontFamilySerif(out IntPtr fontFamily) => GdipGetGenericFontFamilySerif_ptr.Delegate(out fontFamily);
-
- private delegate Status GdipGetGenericFontFamilyMonospace_delegate(out IntPtr fontFamily);
- private static FunctionWrapper<GdipGetGenericFontFamilyMonospace_delegate> GdipGetGenericFontFamilyMonospace_ptr;
- internal static Status GdipGetGenericFontFamilyMonospace(out IntPtr fontFamily) => GdipGetGenericFontFamilyMonospace_ptr.Delegate(out fontFamily);
-
- private delegate Status GdipGetCellAscent_delegate(IntPtr fontFamily, int style, out short ascent);
- private static FunctionWrapper<GdipGetCellAscent_delegate> GdipGetCellAscent_ptr;
- internal static Status GdipGetCellAscent(IntPtr fontFamily, int style, out short ascent) => GdipGetCellAscent_ptr.Delegate(fontFamily, style, out ascent);
-
- private delegate Status GdipGetCellDescent_delegate(IntPtr fontFamily, int style, out short descent);
- private static FunctionWrapper<GdipGetCellDescent_delegate> GdipGetCellDescent_ptr;
- internal static Status GdipGetCellDescent(IntPtr fontFamily, int style, out short descent) => GdipGetCellDescent_ptr.Delegate(fontFamily, style, out descent);
+ internal static int GdipCreateFontFromHfont(IntPtr hdc, out IntPtr font, ref LOGFONT lf) => GdipCreateFontFromHfont_ptr.Delegate(hdc, out font, ref lf);
- private delegate Status GdipGetLineSpacing_delegate(IntPtr fontFamily, int style, out short spacing);
- private static FunctionWrapper<GdipGetLineSpacing_delegate> GdipGetLineSpacing_ptr;
- internal static Status GdipGetLineSpacing(IntPtr fontFamily, int style, out short spacing) => GdipGetLineSpacing_ptr.Delegate(fontFamily, style, out spacing);
-
- private delegate Status GdipGetEmHeight_delegate(IntPtr fontFamily, int style, out short emHeight);
- private static FunctionWrapper<GdipGetEmHeight_delegate> GdipGetEmHeight_ptr;
- internal static Status GdipGetEmHeight(IntPtr fontFamily, int style, out short emHeight) => GdipGetEmHeight_ptr.Delegate(fontFamily, style, out emHeight);
-
- private delegate Status GdipIsStyleAvailable_delegate(IntPtr fontFamily, int style, out bool styleAvailable);
- private static FunctionWrapper<GdipIsStyleAvailable_delegate> GdipIsStyleAvailable_ptr;
- internal static Status GdipIsStyleAvailable(IntPtr fontFamily, int style, out bool styleAvailable) => GdipIsStyleAvailable_ptr.Delegate(fontFamily, style, out styleAvailable);
-
- private delegate Status GdipDeleteFontFamily_delegate(IntPtr fontFamily);
- private static FunctionWrapper<GdipDeleteFontFamily_delegate> GdipDeleteFontFamily_ptr;
- internal static Status GdipDeleteFontFamily(IntPtr fontFamily) => GdipDeleteFontFamily_ptr.Delegate(fontFamily);
- internal static int IntGdipDeleteFontFamily(HandleRef fontFamily) => (int)GdipDeleteFontFamily_ptr.Delegate(fontFamily.Handle);
-
- private delegate Status GdipGetFontSize_delegate(IntPtr font, out float size);
+ private delegate int GdipGetFontSize_delegate(IntPtr font, out float size);
private static FunctionWrapper<GdipGetFontSize_delegate> GdipGetFontSize_ptr;
- internal static Status GdipGetFontSize(IntPtr font, out float size) => GdipGetFontSize_ptr.Delegate(font, out size);
+ internal static int GdipGetFontSize(IntPtr font, out float size) => GdipGetFontSize_ptr.Delegate(font, out size);
- private delegate Status GdipGetFontHeight_delegate(IntPtr font, IntPtr graphics, out float height);
+ private delegate int GdipGetFontHeight_delegate(IntPtr font, IntPtr graphics, out float height);
private static FunctionWrapper<GdipGetFontHeight_delegate> GdipGetFontHeight_ptr;
- internal static Status GdipGetFontHeight(IntPtr font, IntPtr graphics, out float height) => GdipGetFontHeight_ptr.Delegate(font, graphics, out height);
+ internal static int GdipGetFontHeight(IntPtr font, IntPtr graphics, out float height) => GdipGetFontHeight_ptr.Delegate(font, graphics, out height);
- private delegate Status GdipGetFontHeightGivenDPI_delegate(IntPtr font, float dpi, out float height);
+ private delegate int GdipGetFontHeightGivenDPI_delegate(IntPtr font, float dpi, out float height);
private static FunctionWrapper<GdipGetFontHeightGivenDPI_delegate> GdipGetFontHeightGivenDPI_ptr;
- internal static Status GdipGetFontHeightGivenDPI(IntPtr font, float dpi, out float height) => GdipGetFontHeightGivenDPI_ptr.Delegate(font, dpi, out height);
+ internal static int GdipGetFontHeightGivenDPI(IntPtr font, float dpi, out float height) => GdipGetFontHeightGivenDPI_ptr.Delegate(font, dpi, out height);
- private delegate Status GdipCreateMetafileFromFile_delegate([MarshalAs(UnmanagedType.LPWStr)]string filename, out IntPtr metafile);
+ private delegate int GdipCreateMetafileFromFile_delegate([MarshalAs(UnmanagedType.LPWStr)]string filename, out IntPtr metafile);
private static FunctionWrapper<GdipCreateMetafileFromFile_delegate> GdipCreateMetafileFromFile_ptr;
- internal static Status GdipCreateMetafileFromFile(string filename, out IntPtr metafile) => GdipCreateMetafileFromFile_ptr.Delegate(filename, out metafile);
+ internal static int GdipCreateMetafileFromFile(string filename, out IntPtr metafile) => GdipCreateMetafileFromFile_ptr.Delegate(filename, out metafile);
- private delegate Status GdipCreateMetafileFromEmf_delegate(IntPtr hEmf, bool deleteEmf, out IntPtr metafile);
+ private delegate int GdipCreateMetafileFromEmf_delegate(IntPtr hEmf, bool deleteEmf, out IntPtr metafile);
private static FunctionWrapper<GdipCreateMetafileFromEmf_delegate> GdipCreateMetafileFromEmf_ptr;
- internal static Status GdipCreateMetafileFromEmf(IntPtr hEmf, bool deleteEmf, out IntPtr metafile) => GdipCreateMetafileFromEmf_ptr.Delegate(hEmf, deleteEmf, out metafile);
+ internal static int GdipCreateMetafileFromEmf(IntPtr hEmf, bool deleteEmf, out IntPtr metafile) => GdipCreateMetafileFromEmf_ptr.Delegate(hEmf, deleteEmf, out metafile);
- private delegate Status GdipCreateMetafileFromWmf_delegate(IntPtr hWmf, bool deleteWmf, WmfPlaceableFileHeader wmfPlaceableFileHeader, out IntPtr metafile);
+ private delegate int GdipCreateMetafileFromWmf_delegate(IntPtr hWmf, bool deleteWmf, WmfPlaceableFileHeader wmfPlaceableFileHeader, out IntPtr metafile);
private static FunctionWrapper<GdipCreateMetafileFromWmf_delegate> GdipCreateMetafileFromWmf_ptr;
- internal static Status GdipCreateMetafileFromWmf(IntPtr hWmf, bool deleteWmf, WmfPlaceableFileHeader wmfPlaceableFileHeader, out IntPtr metafile) => GdipCreateMetafileFromWmf_ptr.Delegate(hWmf, deleteWmf, wmfPlaceableFileHeader, out metafile);
+ internal static int GdipCreateMetafileFromWmf(IntPtr hWmf, bool deleteWmf, WmfPlaceableFileHeader wmfPlaceableFileHeader, out IntPtr metafile) => GdipCreateMetafileFromWmf_ptr.Delegate(hWmf, deleteWmf, wmfPlaceableFileHeader, out metafile);
- private delegate Status GdipGetMetafileHeaderFromFile_delegate([MarshalAs(UnmanagedType.LPWStr)]string filename, IntPtr header);
+ private delegate int GdipGetMetafileHeaderFromFile_delegate([MarshalAs(UnmanagedType.LPWStr)]string filename, IntPtr header);
private static FunctionWrapper<GdipGetMetafileHeaderFromFile_delegate> GdipGetMetafileHeaderFromFile_ptr;
- internal static Status GdipGetMetafileHeaderFromFile(string filename, IntPtr header) => GdipGetMetafileHeaderFromFile_ptr.Delegate(filename, header);
+ internal static int GdipGetMetafileHeaderFromFile(string filename, IntPtr header) => GdipGetMetafileHeaderFromFile_ptr.Delegate(filename, header);
- private delegate Status GdipGetMetafileHeaderFromMetafile_delegate(IntPtr metafile, IntPtr header);
+ private delegate int GdipGetMetafileHeaderFromMetafile_delegate(IntPtr metafile, IntPtr header);
private static FunctionWrapper<GdipGetMetafileHeaderFromMetafile_delegate> GdipGetMetafileHeaderFromMetafile_ptr;
- internal static Status GdipGetMetafileHeaderFromMetafile(IntPtr metafile, IntPtr header) => GdipGetMetafileHeaderFromMetafile_ptr.Delegate(metafile, header);
+ internal static int GdipGetMetafileHeaderFromMetafile(IntPtr metafile, IntPtr header) => GdipGetMetafileHeaderFromMetafile_ptr.Delegate(metafile, header);
- private delegate Status GdipGetMetafileHeaderFromEmf_delegate(IntPtr hEmf, IntPtr header);
+ private delegate int GdipGetMetafileHeaderFromEmf_delegate(IntPtr hEmf, IntPtr header);
private static FunctionWrapper<GdipGetMetafileHeaderFromEmf_delegate> GdipGetMetafileHeaderFromEmf_ptr;
- internal static Status GdipGetMetafileHeaderFromEmf(IntPtr hEmf, IntPtr header) => GdipGetMetafileHeaderFromEmf_ptr.Delegate(hEmf, header);
+ internal static int GdipGetMetafileHeaderFromEmf(IntPtr hEmf, IntPtr header) => GdipGetMetafileHeaderFromEmf_ptr.Delegate(hEmf, header);
- private delegate Status GdipGetMetafileHeaderFromWmf_delegate(IntPtr hWmf, IntPtr wmfPlaceableFileHeader, IntPtr header);
+ private delegate int GdipGetMetafileHeaderFromWmf_delegate(IntPtr hWmf, IntPtr wmfPlaceableFileHeader, IntPtr header);
private static FunctionWrapper<GdipGetMetafileHeaderFromWmf_delegate> GdipGetMetafileHeaderFromWmf_ptr;
- internal static Status GdipGetMetafileHeaderFromWmf(IntPtr hWmf, IntPtr wmfPlaceableFileHeader, IntPtr header) => GdipGetMetafileHeaderFromWmf_ptr.Delegate(hWmf, wmfPlaceableFileHeader, header);
+ internal static int GdipGetMetafileHeaderFromWmf(IntPtr hWmf, IntPtr wmfPlaceableFileHeader, IntPtr header) => GdipGetMetafileHeaderFromWmf_ptr.Delegate(hWmf, wmfPlaceableFileHeader, header);
- private delegate Status GdipGetHemfFromMetafile_delegate(IntPtr metafile, out IntPtr hEmf);
+ private delegate int GdipGetHemfFromMetafile_delegate(IntPtr metafile, out IntPtr hEmf);
private static FunctionWrapper<GdipGetHemfFromMetafile_delegate> GdipGetHemfFromMetafile_ptr;
- internal static Status GdipGetHemfFromMetafile(IntPtr metafile, out IntPtr hEmf) => GdipGetHemfFromMetafile_ptr.Delegate(metafile, out hEmf);
+ internal static int GdipGetHemfFromMetafile(IntPtr metafile, out IntPtr hEmf) => GdipGetHemfFromMetafile_ptr.Delegate(metafile, out hEmf);
- private delegate Status GdipGetMetafileDownLevelRasterizationLimit_delegate(IntPtr metafile, ref uint metafileRasterizationLimitDpi);
+ private delegate int GdipGetMetafileDownLevelRasterizationLimit_delegate(IntPtr metafile, ref uint metafileRasterizationLimitDpi);
private static FunctionWrapper<GdipGetMetafileDownLevelRasterizationLimit_delegate> GdipGetMetafileDownLevelRasterizationLimit_ptr;
- internal static Status GdipGetMetafileDownLevelRasterizationLimit(IntPtr metafile, ref uint metafileRasterizationLimitDpi) => GdipGetMetafileDownLevelRasterizationLimit_ptr.Delegate(metafile, ref metafileRasterizationLimitDpi);
+ internal static int GdipGetMetafileDownLevelRasterizationLimit(IntPtr metafile, ref uint metafileRasterizationLimitDpi) => GdipGetMetafileDownLevelRasterizationLimit_ptr.Delegate(metafile, ref metafileRasterizationLimitDpi);
- private delegate Status GdipSetMetafileDownLevelRasterizationLimit_delegate(IntPtr metafile, uint metafileRasterizationLimitDpi);
+ private delegate int GdipSetMetafileDownLevelRasterizationLimit_delegate(IntPtr metafile, uint metafileRasterizationLimitDpi);
private static FunctionWrapper<GdipSetMetafileDownLevelRasterizationLimit_delegate> GdipSetMetafileDownLevelRasterizationLimit_ptr;
- internal static Status GdipSetMetafileDownLevelRasterizationLimit(IntPtr metafile, uint metafileRasterizationLimitDpi) => GdipSetMetafileDownLevelRasterizationLimit_ptr.Delegate(metafile, metafileRasterizationLimitDpi);
+ internal static int GdipSetMetafileDownLevelRasterizationLimit(IntPtr metafile, uint metafileRasterizationLimitDpi) => GdipSetMetafileDownLevelRasterizationLimit_ptr.Delegate(metafile, metafileRasterizationLimitDpi);
- private delegate Status GdipPlayMetafileRecord_delegate(IntPtr metafile, EmfPlusRecordType recordType, int flags, int dataSize, byte[] data);
+ private delegate int GdipPlayMetafileRecord_delegate(IntPtr metafile, EmfPlusRecordType recordType, int flags, int dataSize, byte[] data);
private static FunctionWrapper<GdipPlayMetafileRecord_delegate> GdipPlayMetafileRecord_ptr;
- internal static Status GdipPlayMetafileRecord(IntPtr metafile, EmfPlusRecordType recordType, int flags, int dataSize, byte[] data) => GdipPlayMetafileRecord_ptr.Delegate(metafile, recordType, flags, dataSize, data);
+ internal static int GdipPlayMetafileRecord(IntPtr metafile, EmfPlusRecordType recordType, int flags, int dataSize, byte[] data) => GdipPlayMetafileRecord_ptr.Delegate(metafile, recordType, flags, dataSize, data);
- private delegate Status GdipRecordMetafile_delegate(IntPtr hdc, EmfType type, ref RectangleF frameRect, MetafileFrameUnit frameUnit, [MarshalAs(UnmanagedType.LPWStr)]string description, out IntPtr metafile);
+ private delegate int GdipRecordMetafile_delegate(IntPtr hdc, EmfType type, ref RectangleF frameRect, MetafileFrameUnit frameUnit, [MarshalAs(UnmanagedType.LPWStr)]string description, out IntPtr metafile);
private static FunctionWrapper<GdipRecordMetafile_delegate> GdipRecordMetafile_ptr;
- internal static Status GdipRecordMetafile(IntPtr hdc, EmfType type, ref RectangleF frameRect, MetafileFrameUnit frameUnit, string description, out IntPtr metafile) => GdipRecordMetafile_ptr.Delegate(hdc, type, ref frameRect, frameUnit, description, out metafile);
+ internal static int GdipRecordMetafile(IntPtr hdc, EmfType type, ref RectangleF frameRect, MetafileFrameUnit frameUnit, string description, out IntPtr metafile) => GdipRecordMetafile_ptr.Delegate(hdc, type, ref frameRect, frameUnit, description, out metafile);
- private delegate Status GdipRecordMetafileI_delegate(IntPtr hdc, EmfType type, ref Rectangle frameRect, MetafileFrameUnit frameUnit, [MarshalAs(UnmanagedType.LPWStr)]string description, out IntPtr metafile);
+ private delegate int GdipRecordMetafileI_delegate(IntPtr hdc, EmfType type, ref Rectangle frameRect, MetafileFrameUnit frameUnit, [MarshalAs(UnmanagedType.LPWStr)]string description, out IntPtr metafile);
private static FunctionWrapper<GdipRecordMetafileI_delegate> GdipRecordMetafileI_ptr;
- internal static Status GdipRecordMetafileI(IntPtr hdc, EmfType type, ref Rectangle frameRect, MetafileFrameUnit frameUnit, string description, out IntPtr metafile) => GdipRecordMetafileI_ptr.Delegate(hdc, type, ref frameRect, frameUnit, description, out metafile);
+ internal static int GdipRecordMetafileI(IntPtr hdc, EmfType type, ref Rectangle frameRect, MetafileFrameUnit frameUnit, string description, out IntPtr metafile) => GdipRecordMetafileI_ptr.Delegate(hdc, type, ref frameRect, frameUnit, description, out metafile);
- private delegate Status GdipRecordMetafileFileName_delegate([MarshalAs(UnmanagedType.LPWStr)]string filename, IntPtr hdc, EmfType type, ref RectangleF frameRect, MetafileFrameUnit frameUnit, [MarshalAs(UnmanagedType.LPWStr)]string description, out IntPtr metafile);
+ private delegate int GdipRecordMetafileFileName_delegate([MarshalAs(UnmanagedType.LPWStr)]string filename, IntPtr hdc, EmfType type, ref RectangleF frameRect, MetafileFrameUnit frameUnit, [MarshalAs(UnmanagedType.LPWStr)]string description, out IntPtr metafile);
private static FunctionWrapper<GdipRecordMetafileFileName_delegate> GdipRecordMetafileFileName_ptr;
- internal static Status GdipRecordMetafileFileName(string filename, IntPtr hdc, EmfType type, ref RectangleF frameRect, MetafileFrameUnit frameUnit, string description, out IntPtr metafile) => GdipRecordMetafileFileName_ptr.Delegate(filename, hdc, type, ref frameRect, frameUnit, description, out metafile);
+ internal static int GdipRecordMetafileFileName(string filename, IntPtr hdc, EmfType type, ref RectangleF frameRect, MetafileFrameUnit frameUnit, string description, out IntPtr metafile) => GdipRecordMetafileFileName_ptr.Delegate(filename, hdc, type, ref frameRect, frameUnit, description, out metafile);
- private delegate Status GdipRecordMetafileFileNameI_delegate([MarshalAs(UnmanagedType.LPWStr)]string filename, IntPtr hdc, EmfType type, ref Rectangle frameRect, MetafileFrameUnit frameUnit, [MarshalAs(UnmanagedType.LPWStr)]string description, out IntPtr metafile);
+ private delegate int GdipRecordMetafileFileNameI_delegate([MarshalAs(UnmanagedType.LPWStr)]string filename, IntPtr hdc, EmfType type, ref Rectangle frameRect, MetafileFrameUnit frameUnit, [MarshalAs(UnmanagedType.LPWStr)]string description, out IntPtr metafile);
private static FunctionWrapper<GdipRecordMetafileFileNameI_delegate> GdipRecordMetafileFileNameI_ptr;
- internal static Status GdipRecordMetafileFileNameI(string filename, IntPtr hdc, EmfType type, ref Rectangle frameRect, MetafileFrameUnit frameUnit, string description, out IntPtr metafile) => GdipRecordMetafileFileNameI_ptr.Delegate(filename, hdc, type, ref frameRect, frameUnit, description, out metafile);
-
- private delegate Status GdipCreateMetafileFromStream_delegate([MarshalAs(UnmanagedType.CustomMarshaler, MarshalTypeRef = typeof(ComIStreamMarshaler))]IStream stream, out IntPtr metafile);
- private static FunctionWrapper<GdipCreateMetafileFromStream_delegate> GdipCreateMetafileFromStream_ptr;
- internal static Status GdipCreateMetafileFromStream(IStream stream, out IntPtr metafile) => GdipCreateMetafileFromStream_ptr.Delegate(stream, out metafile);
+ internal static int GdipRecordMetafileFileNameI(string filename, IntPtr hdc, EmfType type, ref Rectangle frameRect, MetafileFrameUnit frameUnit, string description, out IntPtr metafile) => GdipRecordMetafileFileNameI_ptr.Delegate(filename, hdc, type, ref frameRect, frameUnit, description, out metafile);
- private delegate Status GdipGetMetafileHeaderFromStream_delegate([MarshalAs(UnmanagedType.CustomMarshaler, MarshalTypeRef = typeof(ComIStreamMarshaler))]IStream stream, IntPtr header);
- private static FunctionWrapper<GdipGetMetafileHeaderFromStream_delegate> GdipGetMetafileHeaderFromStream_ptr;
- internal static Status GdipGetMetafileHeaderFromStream(IStream stream, IntPtr header) => GdipGetMetafileHeaderFromStream_ptr.Delegate(stream, header);
-
- private delegate Status GdipRecordMetafileStream_delegate([MarshalAs(UnmanagedType.CustomMarshaler, MarshalTypeRef = typeof(ComIStreamMarshaler))]IStream stream, IntPtr hdc, EmfType type, ref RectangleF frameRect, MetafileFrameUnit frameUnit, [MarshalAs(UnmanagedType.LPWStr)]string description, out IntPtr metafile);
- private static FunctionWrapper<GdipRecordMetafileStream_delegate> GdipRecordMetafileStream_ptr;
- internal static Status GdipRecordMetafileStream(IStream stream, IntPtr hdc, EmfType type, ref RectangleF frameRect, MetafileFrameUnit frameUnit, string description, out IntPtr metafile) => GdipRecordMetafileStream_ptr.Delegate(stream, hdc, type, ref frameRect, frameUnit, description, out metafile);
-
- private delegate Status GdipRecordMetafileStreamI_delegate([MarshalAs(UnmanagedType.CustomMarshaler, MarshalTypeRef = typeof(ComIStreamMarshaler))]IStream stream, IntPtr hdc, EmfType type, ref Rectangle frameRect, MetafileFrameUnit frameUnit, [MarshalAs(UnmanagedType.LPWStr)]string description, out IntPtr metafile);
- private static FunctionWrapper<GdipRecordMetafileStreamI_delegate> GdipRecordMetafileStreamI_ptr;
- internal static Status GdipRecordMetafileStreamI(IStream stream, IntPtr hdc, EmfType type, ref Rectangle frameRect, MetafileFrameUnit frameUnit, string description, out IntPtr metafile) => GdipRecordMetafileStreamI_ptr.Delegate(stream, hdc, type, ref frameRect, frameUnit, description, out metafile);
-
- private delegate Status GdipCreateFromContext_macosx_delegate(IntPtr cgref, int width, int height, out IntPtr graphics);
+ private delegate int GdipCreateFromContext_macosx_delegate(IntPtr cgref, int width, int height, out IntPtr graphics);
private static FunctionWrapper<GdipCreateFromContext_macosx_delegate> GdipCreateFromContext_macosx_ptr;
- internal static Status GdipCreateFromContext_macosx(IntPtr cgref, int width, int height, out IntPtr graphics) =>GdipCreateFromContext_macosx_ptr.Delegate(cgref, width, height, out graphics);
+ internal static int GdipCreateFromContext_macosx(IntPtr cgref, int width, int height, out IntPtr graphics) => GdipCreateFromContext_macosx_ptr.Delegate(cgref, width, height, out graphics);
- private delegate Status GdipSetVisibleClip_linux_delegate(IntPtr graphics, ref Rectangle rect);
+ private delegate int GdipSetVisibleClip_linux_delegate(IntPtr graphics, ref Rectangle rect);
private static FunctionWrapper<GdipSetVisibleClip_linux_delegate> GdipSetVisibleClip_linux_ptr;
- internal static Status GdipSetVisibleClip_linux(IntPtr graphics, ref Rectangle rect) => GdipSetVisibleClip_linux_ptr.Delegate(graphics, ref rect);
+ internal static int GdipSetVisibleClip_linux(IntPtr graphics, ref Rectangle rect) => GdipSetVisibleClip_linux_ptr.Delegate(graphics, ref rect);
- private delegate Status GdipCreateFromXDrawable_linux_delegate(IntPtr drawable, IntPtr display, out IntPtr graphics);
+ private delegate int GdipCreateFromXDrawable_linux_delegate(IntPtr drawable, IntPtr display, out IntPtr graphics);
private static FunctionWrapper<GdipCreateFromXDrawable_linux_delegate> GdipCreateFromXDrawable_linux_ptr;
- internal static Status GdipCreateFromXDrawable_linux(IntPtr drawable, IntPtr display, out IntPtr graphics) => GdipCreateFromXDrawable_linux_ptr.Delegate(drawable, display, out graphics);
+ internal static int GdipCreateFromXDrawable_linux(IntPtr drawable, IntPtr display, out IntPtr graphics) => GdipCreateFromXDrawable_linux_ptr.Delegate(drawable, display, out graphics);
// Stream functions for non-Win32 (libgdiplus specific)
- private delegate Status GdipLoadImageFromDelegate_linux_delegate(StreamGetHeaderDelegate getHeader,
+ private delegate int GdipLoadImageFromDelegate_linux_delegate(StreamGetHeaderDelegate getHeader,
StreamGetBytesDelegate getBytes, StreamPutBytesDelegate putBytes, StreamSeekDelegate doSeek,
StreamCloseDelegate close, StreamSizeDelegate size, out IntPtr image);
private static FunctionWrapper<GdipLoadImageFromDelegate_linux_delegate> GdipLoadImageFromDelegate_linux_ptr;
- internal static Status GdipLoadImageFromDelegate_linux(StreamGetHeaderDelegate getHeader,
+ internal static int GdipLoadImageFromDelegate_linux(StreamGetHeaderDelegate getHeader,
StreamGetBytesDelegate getBytes, StreamPutBytesDelegate putBytes, StreamSeekDelegate doSeek,
StreamCloseDelegate close, StreamSizeDelegate size, out IntPtr image)
=> GdipLoadImageFromDelegate_linux_ptr.Delegate(getHeader, getBytes, putBytes, doSeek, close, size, out image);
- private delegate Status GdipSaveImageToDelegate_linux_delegate(IntPtr image, StreamGetBytesDelegate getBytes,
+ private delegate int GdipSaveImageToDelegate_linux_delegate(IntPtr image, StreamGetBytesDelegate getBytes,
StreamPutBytesDelegate putBytes, StreamSeekDelegate doSeek, StreamCloseDelegate close,
StreamSizeDelegate size, ref Guid encoderClsID, IntPtr encoderParameters);
private static FunctionWrapper<GdipSaveImageToDelegate_linux_delegate> GdipSaveImageToDelegate_linux_ptr;
- internal static Status GdipSaveImageToDelegate_linux(IntPtr image, StreamGetBytesDelegate getBytes,
+ internal static int GdipSaveImageToDelegate_linux(IntPtr image, StreamGetBytesDelegate getBytes,
StreamPutBytesDelegate putBytes, StreamSeekDelegate doSeek, StreamCloseDelegate close,
StreamSizeDelegate size, ref Guid encoderClsID, IntPtr encoderParameters)
=> GdipSaveImageToDelegate_linux_ptr.Delegate(image, getBytes, putBytes, doSeek, close, size, ref encoderClsID, encoderParameters);
- private delegate Status GdipCreateMetafileFromDelegate_linux_delegate(StreamGetHeaderDelegate getHeader,
+ private delegate int GdipCreateMetafileFromDelegate_linux_delegate(StreamGetHeaderDelegate getHeader,
StreamGetBytesDelegate getBytes, StreamPutBytesDelegate putBytes, StreamSeekDelegate doSeek,
StreamCloseDelegate close, StreamSizeDelegate size, out IntPtr metafile);
private static FunctionWrapper<GdipCreateMetafileFromDelegate_linux_delegate> GdipCreateMetafileFromDelegate_linux_ptr;
- internal static Status GdipCreateMetafileFromDelegate_linux(StreamGetHeaderDelegate getHeader,
+ internal static int GdipCreateMetafileFromDelegate_linux(StreamGetHeaderDelegate getHeader,
StreamGetBytesDelegate getBytes, StreamPutBytesDelegate putBytes, StreamSeekDelegate doSeek,
StreamCloseDelegate close, StreamSizeDelegate size, out IntPtr metafile)
=> GdipCreateMetafileFromDelegate_linux_ptr.Delegate(getHeader, getBytes, putBytes, doSeek, close, size, out metafile);
- private delegate Status GdipGetMetafileHeaderFromDelegate_linux_delegate(StreamGetHeaderDelegate getHeader,
+ private delegate int GdipGetMetafileHeaderFromDelegate_linux_delegate(StreamGetHeaderDelegate getHeader,
StreamGetBytesDelegate getBytes, StreamPutBytesDelegate putBytes, StreamSeekDelegate doSeek,
StreamCloseDelegate close, StreamSizeDelegate size, IntPtr header);
private static FunctionWrapper<GdipGetMetafileHeaderFromDelegate_linux_delegate> GdipGetMetafileHeaderFromDelegate_linux_ptr;
- internal static Status GdipGetMetafileHeaderFromDelegate_linux(StreamGetHeaderDelegate getHeader,
+ internal static int GdipGetMetafileHeaderFromDelegate_linux(StreamGetHeaderDelegate getHeader,
StreamGetBytesDelegate getBytes, StreamPutBytesDelegate putBytes, StreamSeekDelegate doSeek,
StreamCloseDelegate close, StreamSizeDelegate size, IntPtr header)
=> GdipGetMetafileHeaderFromDelegate_linux_ptr.Delegate(getHeader, getBytes, putBytes, doSeek, close, size, header);
- private delegate Status GdipRecordMetafileFromDelegate_linux_delegate(StreamGetHeaderDelegate getHeader,
+ private delegate int GdipRecordMetafileFromDelegate_linux_delegate(StreamGetHeaderDelegate getHeader,
StreamGetBytesDelegate getBytes, StreamPutBytesDelegate putBytes, StreamSeekDelegate doSeek,
StreamCloseDelegate close, StreamSizeDelegate size, IntPtr hdc, EmfType type, ref RectangleF frameRect,
MetafileFrameUnit frameUnit, [MarshalAs(UnmanagedType.LPWStr)] string description, out IntPtr metafile);
private static FunctionWrapper<GdipRecordMetafileFromDelegate_linux_delegate> GdipRecordMetafileFromDelegate_linux_ptr;
- internal static Status GdipRecordMetafileFromDelegate_linux(StreamGetHeaderDelegate getHeader,
+ internal static int GdipRecordMetafileFromDelegate_linux(StreamGetHeaderDelegate getHeader,
StreamGetBytesDelegate getBytes, StreamPutBytesDelegate putBytes, StreamSeekDelegate doSeek,
StreamCloseDelegate close, StreamSizeDelegate size, IntPtr hdc, EmfType type, ref RectangleF frameRect,
MetafileFrameUnit frameUnit, string description, out IntPtr metafile)
=> GdipRecordMetafileFromDelegate_linux_ptr.Delegate(getHeader, getBytes, putBytes, doSeek, close, size, hdc, type, ref frameRect, frameUnit, description, out metafile);
- private delegate Status GdipRecordMetafileFromDelegateI_linux_delegate(StreamGetHeaderDelegate getHeader,
+ private delegate int GdipRecordMetafileFromDelegateI_linux_delegate(StreamGetHeaderDelegate getHeader,
StreamGetBytesDelegate getBytes, StreamPutBytesDelegate putBytes, StreamSeekDelegate doSeek,
StreamCloseDelegate close, StreamSizeDelegate size, IntPtr hdc, EmfType type, ref Rectangle frameRect,
MetafileFrameUnit frameUnit, [MarshalAs(UnmanagedType.LPWStr)] string description, out IntPtr metafile);
private static FunctionWrapper<GdipRecordMetafileFromDelegateI_linux_delegate> GdipRecordMetafileFromDelegateI_linux_ptr;
- internal static Status GdipRecordMetafileFromDelegateI_linux(StreamGetHeaderDelegate getHeader,
+ internal static int GdipRecordMetafileFromDelegateI_linux(StreamGetHeaderDelegate getHeader,
StreamGetBytesDelegate getBytes, StreamPutBytesDelegate putBytes, StreamSeekDelegate doSeek,
StreamCloseDelegate close, StreamSizeDelegate size, IntPtr hdc, EmfType type, ref Rectangle frameRect,
MetafileFrameUnit frameUnit, string description, out IntPtr metafile)
=> GdipRecordMetafileFromDelegateI_linux_ptr.Delegate(getHeader, getBytes, putBytes, doSeek, close, size, hdc, type, ref frameRect, frameUnit, description, out metafile);
+
+ private delegate int GdipGetPostScriptGraphicsContext_delegate(string filename, int width, int height, double dpix, double dpiy, ref IntPtr graphics);
+ private static FunctionWrapper<GdipGetPostScriptGraphicsContext_delegate> GdipGetPostScriptGraphicsContext_ptr;
+ internal static int GdipGetPostScriptGraphicsContext([MarshalAs(UnmanagedType.LPStr)]string filename, int width, int height, double dpix, double dpiy, ref IntPtr graphics)
+ => GdipGetPostScriptGraphicsContext_ptr.Delegate(filename, width, height, dpix, dpiy, ref graphics);
+
+ private delegate int GdipGetPostScriptSavePage_delegate(IntPtr graphics);
+ private static FunctionWrapper<GdipGetPostScriptSavePage_delegate> GdipGetPostScriptSavePage_ptr;
+ internal static int GdipGetPostScriptSavePage(IntPtr graphics) => GdipGetPostScriptSavePage_ptr.Delegate(graphics);
}
}
diff --git a/src/System.Drawing.Common/src/System/Drawing/GdiplusNative.Windows.cs b/src/System.Drawing.Common/src/System/Drawing/GdiplusNative.Windows.cs
index bc436d6c3a..ed059bc8ab 100644
--- a/src/System.Drawing.Common/src/System/Drawing/GdiplusNative.Windows.cs
+++ b/src/System.Drawing.Common/src/System/Drawing/GdiplusNative.Windows.cs
@@ -24,285 +24,277 @@ namespace System.Drawing
return s_gdipHandle.DangerousGetHandle();
}
- private static IntPtr LoadFunctionPointer(IntPtr nativeLibraryHandle, string functionName) => Interop.Kernel32.GetProcAddress(nativeLibraryHandle, functionName);
+ private static void PlatformInitialize()
+ {
+ LoadFunctionPointers();
+ }
- private static void LoadPlatformFunctionPointers()
+ private static void LoadFunctionPointers()
{
- GdiplusStartup_ptr = LoadFunction<GdiplusStartup_delegate>("GdiplusStartup");
- GdipCreatePath_ptr = LoadFunction<GdipCreatePath_delegate>("GdipCreatePath");
- GdipCreatePath2_ptr = LoadFunction<GdipCreatePath2_delegate>("GdipCreatePath2");
- GdipCreatePath2I_ptr = LoadFunction<GdipCreatePath2I_delegate>("GdipCreatePath2I");
- GdipClonePath_ptr = LoadFunction<GdipClonePath_delegate>("GdipClonePath");
- GdipDeletePath_ptr = LoadFunction<GdipDeletePath_delegate>("GdipDeletePath");
- GdipResetPath_ptr = LoadFunction<GdipResetPath_delegate>("GdipResetPath");
- GdipGetPointCount_ptr = LoadFunction<GdipGetPointCount_delegate>("GdipGetPointCount");
- GdipGetPathTypes_ptr = LoadFunction<GdipGetPathTypes_delegate>("GdipGetPathTypes");
- GdipGetPathPoints_ptr = LoadFunction<GdipGetPathPoints_delegate>("GdipGetPathPoints");
- GdipGetPathFillMode_ptr = LoadFunction<GdipGetPathFillMode_delegate>("GdipGetPathFillMode");
- GdipSetPathFillMode_ptr = LoadFunction<GdipSetPathFillMode_delegate>("GdipSetPathFillMode");
- GdipGetPathData_ptr = LoadFunction<GdipGetPathData_delegate>("GdipGetPathData");
- GdipStartPathFigure_ptr = LoadFunction<GdipStartPathFigure_delegate>("GdipStartPathFigure");
- GdipClosePathFigure_ptr = LoadFunction<GdipClosePathFigure_delegate>("GdipClosePathFigure");
- GdipClosePathFigures_ptr = LoadFunction<GdipClosePathFigures_delegate>("GdipClosePathFigures");
- GdipSetPathMarker_ptr = LoadFunction<GdipSetPathMarker_delegate>("GdipSetPathMarker");
- GdipClearPathMarkers_ptr = LoadFunction<GdipClearPathMarkers_delegate>("GdipClearPathMarkers");
- GdipReversePath_ptr = LoadFunction<GdipReversePath_delegate>("GdipReversePath");
- GdipGetPathLastPoint_ptr = LoadFunction<GdipGetPathLastPoint_delegate>("GdipGetPathLastPoint");
- GdipAddPathLine_ptr = LoadFunction<GdipAddPathLine_delegate>("GdipAddPathLine");
- GdipAddPathLine2_ptr = LoadFunction<GdipAddPathLine2_delegate>("GdipAddPathLine2");
- GdipAddPathArc_ptr = LoadFunction<GdipAddPathArc_delegate>("GdipAddPathArc");
- GdipAddPathBezier_ptr = LoadFunction<GdipAddPathBezier_delegate>("GdipAddPathBezier");
- GdipAddPathBeziers_ptr = LoadFunction<GdipAddPathBeziers_delegate>("GdipAddPathBeziers");
- GdipAddPathCurve_ptr = LoadFunction<GdipAddPathCurve_delegate>("GdipAddPathCurve");
- GdipAddPathCurve2_ptr = LoadFunction<GdipAddPathCurve2_delegate>("GdipAddPathCurve2");
- GdipAddPathCurve3_ptr = LoadFunction<GdipAddPathCurve3_delegate>("GdipAddPathCurve3");
- GdipAddPathClosedCurve_ptr = LoadFunction<GdipAddPathClosedCurve_delegate>("GdipAddPathClosedCurve");
- GdipAddPathClosedCurve2_ptr = LoadFunction<GdipAddPathClosedCurve2_delegate>("GdipAddPathClosedCurve2");
- GdipAddPathRectangle_ptr = LoadFunction<GdipAddPathRectangle_delegate>("GdipAddPathRectangle");
- GdipAddPathRectangles_ptr = LoadFunction<GdipAddPathRectangles_delegate>("GdipAddPathRectangles");
- GdipAddPathEllipse_ptr = LoadFunction<GdipAddPathEllipse_delegate>("GdipAddPathEllipse");
- GdipAddPathPie_ptr = LoadFunction<GdipAddPathPie_delegate>("GdipAddPathPie");
- GdipAddPathPolygon_ptr = LoadFunction<GdipAddPathPolygon_delegate>("GdipAddPathPolygon");
- GdipAddPathPath_ptr = LoadFunction<GdipAddPathPath_delegate>("GdipAddPathPath");
- GdipAddPathString_ptr = LoadFunction<GdipAddPathString_delegate>("GdipAddPathString");
- GdipAddPathStringI_ptr = LoadFunction<GdipAddPathStringI_delegate>("GdipAddPathStringI");
- GdipAddPathLineI_ptr = LoadFunction<GdipAddPathLineI_delegate>("GdipAddPathLineI");
- GdipAddPathLine2I_ptr = LoadFunction<GdipAddPathLine2I_delegate>("GdipAddPathLine2I");
- GdipAddPathArcI_ptr = LoadFunction<GdipAddPathArcI_delegate>("GdipAddPathArcI");
- GdipAddPathBezierI_ptr = LoadFunction<GdipAddPathBezierI_delegate>("GdipAddPathBezierI");
- GdipAddPathBeziersI_ptr = LoadFunction<GdipAddPathBeziersI_delegate>("GdipAddPathBeziersI");
- GdipAddPathCurveI_ptr = LoadFunction<GdipAddPathCurveI_delegate>("GdipAddPathCurveI");
- GdipAddPathCurve2I_ptr = LoadFunction<GdipAddPathCurve2I_delegate>("GdipAddPathCurve2I");
- GdipAddPathCurve3I_ptr = LoadFunction<GdipAddPathCurve3I_delegate>("GdipAddPathCurve3I");
- GdipAddPathClosedCurveI_ptr = LoadFunction<GdipAddPathClosedCurveI_delegate>("GdipAddPathClosedCurveI");
- GdipAddPathClosedCurve2I_ptr = LoadFunction<GdipAddPathClosedCurve2I_delegate>("GdipAddPathClosedCurve2I");
- GdipAddPathRectangleI_ptr = LoadFunction<GdipAddPathRectangleI_delegate>("GdipAddPathRectangleI");
- GdipAddPathRectanglesI_ptr = LoadFunction<GdipAddPathRectanglesI_delegate>("GdipAddPathRectanglesI");
- GdipAddPathEllipseI_ptr = LoadFunction<GdipAddPathEllipseI_delegate>("GdipAddPathEllipseI");
- GdipAddPathPieI_ptr = LoadFunction<GdipAddPathPieI_delegate>("GdipAddPathPieI");
- GdipAddPathPolygonI_ptr = LoadFunction<GdipAddPathPolygonI_delegate>("GdipAddPathPolygonI");
- GdipFlattenPath_ptr = LoadFunction<GdipFlattenPath_delegate>("GdipFlattenPath");
- GdipWidenPath_ptr = LoadFunction<GdipWidenPath_delegate>("GdipWidenPath");
- GdipWarpPath_ptr = LoadFunction<GdipWarpPath_delegate>("GdipWarpPath");
- GdipTransformPath_ptr = LoadFunction<GdipTransformPath_delegate>("GdipTransformPath");
- GdipGetPathWorldBounds_ptr = LoadFunction<GdipGetPathWorldBounds_delegate>("GdipGetPathWorldBounds");
- GdipIsVisiblePathPoint_ptr = LoadFunction<GdipIsVisiblePathPoint_delegate>("GdipIsVisiblePathPoint");
- GdipIsVisiblePathPointI_ptr = LoadFunction<GdipIsVisiblePathPointI_delegate>("GdipIsVisiblePathPointI");
- GdipIsOutlineVisiblePathPoint_ptr = LoadFunction<GdipIsOutlineVisiblePathPoint_delegate>("GdipIsOutlineVisiblePathPoint");
- GdipIsOutlineVisiblePathPointI_ptr = LoadFunction<GdipIsOutlineVisiblePathPointI_delegate>("GdipIsOutlineVisiblePathPointI");
- GdipDeleteBrush_ptr = LoadFunction<GdipDeleteBrush_delegate>("GdipDeleteBrush");
- GdipLoadImageFromStream_ptr = LoadFunction<GdipLoadImageFromStream_delegate>("GdipLoadImageFromStream");
- GdipLoadImageFromFile_ptr = LoadFunction<GdipLoadImageFromFile_delegate>("GdipLoadImageFromFile");
- GdipLoadImageFromStreamICM_ptr = LoadFunction<GdipLoadImageFromStreamICM_delegate>("GdipLoadImageFromStreamICM");
- GdipLoadImageFromFileICM_ptr = LoadFunction<GdipLoadImageFromFileICM_delegate>("GdipLoadImageFromFileICM");
- GdipCloneImage_ptr = LoadFunction<GdipCloneImage_delegate>("GdipCloneImage");
- GdipDisposeImage_ptr = LoadFunction<GdipDisposeImage_delegate>("GdipDisposeImage");
- GdipSaveImageToFile_ptr = LoadFunction<GdipSaveImageToFile_delegate>("GdipSaveImageToFile");
- GdipSaveImageToStream_ptr = LoadFunction<GdipSaveImageToStream_delegate>("GdipSaveImageToStream");
- GdipSaveAdd_ptr = LoadFunction<GdipSaveAdd_delegate>("GdipSaveAdd");
- GdipSaveAddImage_ptr = LoadFunction<GdipSaveAddImage_delegate>("GdipSaveAddImage");
- GdipGetImageGraphicsContext_ptr = LoadFunction<GdipGetImageGraphicsContext_delegate>("GdipGetImageGraphicsContext");
- GdipGetImageBounds_ptr = LoadFunction<GdipGetImageBounds_delegate>("GdipGetImageBounds");
- GdipGetImageDimension_ptr = LoadFunction<GdipGetImageDimension_delegate>("GdipGetImageDimension");
- GdipGetImageType_ptr = LoadFunction<GdipGetImageType_delegate>("GdipGetImageType");
- GdipGetImageWidth_ptr = LoadFunction<GdipGetImageWidth_delegate>("GdipGetImageWidth");
- GdipGetImageHeight_ptr = LoadFunction<GdipGetImageHeight_delegate>("GdipGetImageHeight");
- GdipGetImageHorizontalResolution_ptr = LoadFunction<GdipGetImageHorizontalResolution_delegate>("GdipGetImageHorizontalResolution");
- GdipGetImageVerticalResolution_ptr = LoadFunction<GdipGetImageVerticalResolution_delegate>("GdipGetImageVerticalResolution");
- GdipGetImageFlags_ptr = LoadFunction<GdipGetImageFlags_delegate>("GdipGetImageFlags");
- GdipGetImageRawFormat_ptr = LoadFunction<GdipGetImageRawFormat_delegate>("GdipGetImageRawFormat");
- GdipGetImagePixelFormat_ptr = LoadFunction<GdipGetImagePixelFormat_delegate>("GdipGetImagePixelFormat");
- GdipGetImageThumbnail_ptr = LoadFunction<GdipGetImageThumbnail_delegate>("GdipGetImageThumbnail");
- GdipGetEncoderParameterListSize_ptr = LoadFunction<GdipGetEncoderParameterListSize_delegate>("GdipGetEncoderParameterListSize");
- GdipGetEncoderParameterList_ptr = LoadFunction<GdipGetEncoderParameterList_delegate>("GdipGetEncoderParameterList");
- GdipImageGetFrameDimensionsCount_ptr = LoadFunction<GdipImageGetFrameDimensionsCount_delegate>("GdipImageGetFrameDimensionsCount");
- GdipImageGetFrameDimensionsList_ptr = LoadFunction<GdipImageGetFrameDimensionsList_delegate>("GdipImageGetFrameDimensionsList");
- GdipImageGetFrameCount_ptr = LoadFunction<GdipImageGetFrameCount_delegate>("GdipImageGetFrameCount");
- GdipImageSelectActiveFrame_ptr = LoadFunction<GdipImageSelectActiveFrame_delegate>("GdipImageSelectActiveFrame");
- GdipImageRotateFlip_ptr = LoadFunction<GdipImageRotateFlip_delegate>("GdipImageRotateFlip");
- GdipGetImagePalette_ptr = LoadFunction<GdipGetImagePalette_delegate>("GdipGetImagePalette");
- GdipSetImagePalette_ptr = LoadFunction<GdipSetImagePalette_delegate>("GdipSetImagePalette");
- GdipGetImagePaletteSize_ptr = LoadFunction<GdipGetImagePaletteSize_delegate>("GdipGetImagePaletteSize");
- GdipGetPropertyCount_ptr = LoadFunction<GdipGetPropertyCount_delegate>("GdipGetPropertyCount");
- GdipGetPropertyIdList_ptr = LoadFunction<GdipGetPropertyIdList_delegate>("GdipGetPropertyIdList");
- GdipGetPropertyItemSize_ptr = LoadFunction<GdipGetPropertyItemSize_delegate>("GdipGetPropertyItemSize");
- GdipGetPropertyItem_ptr = LoadFunction<GdipGetPropertyItem_delegate>("GdipGetPropertyItem");
- GdipGetPropertySize_ptr = LoadFunction<GdipGetPropertySize_delegate>("GdipGetPropertySize");
- GdipGetAllPropertyItems_ptr = LoadFunction<GdipGetAllPropertyItems_delegate>("GdipGetAllPropertyItems");
- GdipRemovePropertyItem_ptr = LoadFunction<GdipRemovePropertyItem_delegate>("GdipRemovePropertyItem");
- GdipSetPropertyItem_ptr = LoadFunction<GdipSetPropertyItem_delegate>("GdipSetPropertyItem");
- GdipImageForceValidation_ptr = LoadFunction<GdipImageForceValidation_delegate>("GdipImageForceValidation");
- GdipCreateBitmapFromStream_ptr = LoadFunction<GdipCreateBitmapFromStream_delegate>("GdipCreateBitmapFromStream");
- GdipCreateBitmapFromFile_ptr = LoadFunction<GdipCreateBitmapFromFile_delegate>("GdipCreateBitmapFromFile");
- GdipCreateBitmapFromStreamICM_ptr = LoadFunction<GdipCreateBitmapFromStreamICM_delegate>("GdipCreateBitmapFromStreamICM");
- GdipCreateBitmapFromFileICM_ptr = LoadFunction<GdipCreateBitmapFromFileICM_delegate>("GdipCreateBitmapFromFileICM");
- GdipCreateBitmapFromScan0_ptr = LoadFunction<GdipCreateBitmapFromScan0_delegate>("GdipCreateBitmapFromScan0");
- GdipCreateBitmapFromGraphics_ptr = LoadFunction<GdipCreateBitmapFromGraphics_delegate>("GdipCreateBitmapFromGraphics");
- GdipCreateBitmapFromHBITMAP_ptr = LoadFunction<GdipCreateBitmapFromHBITMAP_delegate>("GdipCreateBitmapFromHBITMAP");
- GdipCreateBitmapFromHICON_ptr = LoadFunction<GdipCreateBitmapFromHICON_delegate>("GdipCreateBitmapFromHICON");
- GdipCreateBitmapFromResource_ptr = LoadFunction<GdipCreateBitmapFromResource_delegate>("GdipCreateBitmapFromResource");
- GdipCreateHBITMAPFromBitmap_ptr = LoadFunction<GdipCreateHBITMAPFromBitmap_delegate>("GdipCreateHBITMAPFromBitmap");
- GdipCreateHICONFromBitmap_ptr = LoadFunction<GdipCreateHICONFromBitmap_delegate>("GdipCreateHICONFromBitmap");
- GdipCloneBitmapArea_ptr = LoadFunction<GdipCloneBitmapArea_delegate>("GdipCloneBitmapArea");
- GdipCloneBitmapAreaI_ptr = LoadFunction<GdipCloneBitmapAreaI_delegate>("GdipCloneBitmapAreaI");
- GdipBitmapLockBits_ptr = LoadFunction<GdipBitmapLockBits_delegate>("GdipBitmapLockBits");
- GdipBitmapUnlockBits_ptr = LoadFunction<GdipBitmapUnlockBits_delegate>("GdipBitmapUnlockBits");
- GdipBitmapGetPixel_ptr = LoadFunction<GdipBitmapGetPixel_delegate>("GdipBitmapGetPixel");
- GdipBitmapSetPixel_ptr = LoadFunction<GdipBitmapSetPixel_delegate>("GdipBitmapSetPixel");
- GdipBitmapSetResolution_ptr = LoadFunction<GdipBitmapSetResolution_delegate>("GdipBitmapSetResolution");
- GdipFlush_ptr = LoadFunction<GdipFlush_delegate>("GdipFlush");
- GdipCreateFromHDC_ptr = LoadFunction<GdipCreateFromHDC_delegate>("GdipCreateFromHDC");
- GdipCreateFromHDC2_ptr = LoadFunction<GdipCreateFromHDC2_delegate>("GdipCreateFromHDC2");
- GdipCreateFromHWND_ptr = LoadFunction<GdipCreateFromHWND_delegate>("GdipCreateFromHWND");
- GdipDeleteGraphics_ptr = LoadFunction<GdipDeleteGraphics_delegate>("GdipDeleteGraphics");
- GdipGetDC_ptr = LoadFunction<GdipGetDC_delegate>("GdipGetDC");
- GdipReleaseDC_ptr = LoadFunction<GdipReleaseDC_delegate>("GdipReleaseDC");
- GdipSetCompositingMode_ptr = LoadFunction<GdipSetCompositingMode_delegate>("GdipSetCompositingMode");
- GdipSetTextRenderingHint_ptr = LoadFunction<GdipSetTextRenderingHint_delegate>("GdipSetTextRenderingHint");
- GdipSetTextContrast_ptr = LoadFunction<GdipSetTextContrast_delegate>("GdipSetTextContrast");
- GdipSetInterpolationMode_ptr = LoadFunction<GdipSetInterpolationMode_delegate>("GdipSetInterpolationMode");
- GdipGetCompositingMode_ptr = LoadFunction<GdipGetCompositingMode_delegate>("GdipGetCompositingMode");
- GdipSetRenderingOrigin_ptr = LoadFunction<GdipSetRenderingOrigin_delegate>("GdipSetRenderingOrigin");
- GdipGetRenderingOrigin_ptr = LoadFunction<GdipGetRenderingOrigin_delegate>("GdipGetRenderingOrigin");
- GdipSetCompositingQuality_ptr = LoadFunction<GdipSetCompositingQuality_delegate>("GdipSetCompositingQuality");
- GdipGetCompositingQuality_ptr = LoadFunction<GdipGetCompositingQuality_delegate>("GdipGetCompositingQuality");
- GdipSetSmoothingMode_ptr = LoadFunction<GdipSetSmoothingMode_delegate>("GdipSetSmoothingMode");
- GdipGetSmoothingMode_ptr = LoadFunction<GdipGetSmoothingMode_delegate>("GdipGetSmoothingMode");
- GdipSetPixelOffsetMode_ptr = LoadFunction<GdipSetPixelOffsetMode_delegate>("GdipSetPixelOffsetMode");
- GdipGetPixelOffsetMode_ptr = LoadFunction<GdipGetPixelOffsetMode_delegate>("GdipGetPixelOffsetMode");
- GdipGetTextRenderingHint_ptr = LoadFunction<GdipGetTextRenderingHint_delegate>("GdipGetTextRenderingHint");
- GdipGetTextContrast_ptr = LoadFunction<GdipGetTextContrast_delegate>("GdipGetTextContrast");
- GdipGetInterpolationMode_ptr = LoadFunction<GdipGetInterpolationMode_delegate>("GdipGetInterpolationMode");
- GdipGetPageUnit_ptr = LoadFunction<GdipGetPageUnit_delegate>("GdipGetPageUnit");
- GdipGetPageScale_ptr = LoadFunction<GdipGetPageScale_delegate>("GdipGetPageScale");
- GdipSetPageUnit_ptr = LoadFunction<GdipSetPageUnit_delegate>("GdipSetPageUnit");
- GdipSetPageScale_ptr = LoadFunction<GdipSetPageScale_delegate>("GdipSetPageScale");
- GdipGetDpiX_ptr = LoadFunction<GdipGetDpiX_delegate>("GdipGetDpiX");
- GdipGetDpiY_ptr = LoadFunction<GdipGetDpiY_delegate>("GdipGetDpiY");
- GdipTransformPoints_ptr = LoadFunction<GdipTransformPoints_delegate>("GdipTransformPoints");
- GdipTransformPointsI_ptr = LoadFunction<GdipTransformPointsI_delegate>("GdipTransformPointsI");
- GdipGetNearestColor_ptr = LoadFunction<GdipGetNearestColor_delegate>("GdipGetNearestColor");
- GdipCreateHalftonePalette_ptr = LoadFunction<GdipCreateHalftonePalette_delegate>("GdipCreateHalftonePalette");
- GdipDrawLine_ptr = LoadFunction<GdipDrawLine_delegate>("GdipDrawLine");
- GdipDrawLineI_ptr = LoadFunction<GdipDrawLineI_delegate>("GdipDrawLineI");
- GdipDrawLines_ptr = LoadFunction<GdipDrawLines_delegate>("GdipDrawLines");
- GdipDrawLinesI_ptr = LoadFunction<GdipDrawLinesI_delegate>("GdipDrawLinesI");
- GdipDrawArc_ptr = LoadFunction<GdipDrawArc_delegate>("GdipDrawArc");
- GdipDrawArcI_ptr = LoadFunction<GdipDrawArcI_delegate>("GdipDrawArcI");
- GdipDrawBezier_ptr = LoadFunction<GdipDrawBezier_delegate>("GdipDrawBezier");
- GdipDrawBeziers_ptr = LoadFunction<GdipDrawBeziers_delegate>("GdipDrawBeziers");
- GdipDrawBeziersI_ptr = LoadFunction<GdipDrawBeziersI_delegate>("GdipDrawBeziersI");
- GdipDrawRectangle_ptr = LoadFunction<GdipDrawRectangle_delegate>("GdipDrawRectangle");
- GdipDrawRectangleI_ptr = LoadFunction<GdipDrawRectangleI_delegate>("GdipDrawRectangleI");
- GdipDrawRectangles_ptr = LoadFunction<GdipDrawRectangles_delegate>("GdipDrawRectangles");
- GdipDrawRectanglesI_ptr = LoadFunction<GdipDrawRectanglesI_delegate>("GdipDrawRectanglesI");
- GdipDrawEllipse_ptr = LoadFunction<GdipDrawEllipse_delegate>("GdipDrawEllipse");
- GdipDrawEllipseI_ptr = LoadFunction<GdipDrawEllipseI_delegate>("GdipDrawEllipseI");
- GdipDrawPie_ptr = LoadFunction<GdipDrawPie_delegate>("GdipDrawPie");
- GdipDrawPieI_ptr = LoadFunction<GdipDrawPieI_delegate>("GdipDrawPieI");
- GdipDrawPolygon_ptr = LoadFunction<GdipDrawPolygon_delegate>("GdipDrawPolygon");
- GdipDrawPolygonI_ptr = LoadFunction<GdipDrawPolygonI_delegate>("GdipDrawPolygonI");
- GdipDrawPath_ptr = LoadFunction<GdipDrawPath_delegate>("GdipDrawPath");
- GdipDrawCurve_ptr = LoadFunction<GdipDrawCurve_delegate>("GdipDrawCurve");
- GdipDrawCurveI_ptr = LoadFunction<GdipDrawCurveI_delegate>("GdipDrawCurveI");
- GdipDrawCurve2_ptr = LoadFunction<GdipDrawCurve2_delegate>("GdipDrawCurve2");
- GdipDrawCurve2I_ptr = LoadFunction<GdipDrawCurve2I_delegate>("GdipDrawCurve2I");
- GdipDrawCurve3_ptr = LoadFunction<GdipDrawCurve3_delegate>("GdipDrawCurve3");
- GdipDrawCurve3I_ptr = LoadFunction<GdipDrawCurve3I_delegate>("GdipDrawCurve3I");
- GdipDrawClosedCurve_ptr = LoadFunction<GdipDrawClosedCurve_delegate>("GdipDrawClosedCurve");
- GdipDrawClosedCurveI_ptr = LoadFunction<GdipDrawClosedCurveI_delegate>("GdipDrawClosedCurveI");
- GdipDrawClosedCurve2_ptr = LoadFunction<GdipDrawClosedCurve2_delegate>("GdipDrawClosedCurve2");
- GdipDrawClosedCurve2I_ptr = LoadFunction<GdipDrawClosedCurve2I_delegate>("GdipDrawClosedCurve2I");
- GdipGraphicsClear_ptr = LoadFunction<GdipGraphicsClear_delegate>("GdipGraphicsClear");
- GdipFillRectangle_ptr = LoadFunction<GdipFillRectangle_delegate>("GdipFillRectangle");
- GdipFillRectangleI_ptr = LoadFunction<GdipFillRectangleI_delegate>("GdipFillRectangleI");
- GdipFillRectangles_ptr = LoadFunction<GdipFillRectangles_delegate>("GdipFillRectangles");
- GdipFillRectanglesI_ptr = LoadFunction<GdipFillRectanglesI_delegate>("GdipFillRectanglesI");
- GdipFillPolygon_ptr = LoadFunction<GdipFillPolygon_delegate>("GdipFillPolygon");
- GdipFillPolygonI_ptr = LoadFunction<GdipFillPolygonI_delegate>("GdipFillPolygonI");
- GdipFillEllipse_ptr = LoadFunction<GdipFillEllipse_delegate>("GdipFillEllipse");
- GdipFillEllipseI_ptr = LoadFunction<GdipFillEllipseI_delegate>("GdipFillEllipseI");
- GdipFillPie_ptr = LoadFunction<GdipFillPie_delegate>("GdipFillPie");
- GdipFillPieI_ptr = LoadFunction<GdipFillPieI_delegate>("GdipFillPieI");
- GdipFillPath_ptr = LoadFunction<GdipFillPath_delegate>("GdipFillPath");
- GdipFillClosedCurve_ptr = LoadFunction<GdipFillClosedCurve_delegate>("GdipFillClosedCurve");
- GdipFillClosedCurveI_ptr = LoadFunction<GdipFillClosedCurveI_delegate>("GdipFillClosedCurveI");
- GdipFillClosedCurve2_ptr = LoadFunction<GdipFillClosedCurve2_delegate>("GdipFillClosedCurve2");
- GdipFillClosedCurve2I_ptr = LoadFunction<GdipFillClosedCurve2I_delegate>("GdipFillClosedCurve2I");
- GdipDrawImage_ptr = LoadFunction<GdipDrawImage_delegate>("GdipDrawImage");
- GdipDrawImageI_ptr = LoadFunction<GdipDrawImageI_delegate>("GdipDrawImageI");
- GdipDrawImageRect_ptr = LoadFunction<GdipDrawImageRect_delegate>("GdipDrawImageRect");
- GdipDrawImageRectI_ptr = LoadFunction<GdipDrawImageRectI_delegate>("GdipDrawImageRectI");
- GdipDrawImagePoints_ptr = LoadFunction<GdipDrawImagePoints_delegate>("GdipDrawImagePoints");
- GdipDrawImagePointsI_ptr = LoadFunction<GdipDrawImagePointsI_delegate>("GdipDrawImagePointsI");
- GdipDrawImagePointRect_ptr = LoadFunction<GdipDrawImagePointRect_delegate>("GdipDrawImagePointRect");
- GdipDrawImagePointRectI_ptr = LoadFunction<GdipDrawImagePointRectI_delegate>("GdipDrawImagePointRectI");
- GdipDrawImageRectRect_ptr = LoadFunction<GdipDrawImageRectRect_delegate>("GdipDrawImageRectRect");
- GdipDrawImageRectRectI_ptr = LoadFunction<GdipDrawImageRectRectI_delegate>("GdipDrawImageRectRectI");
- GdipDrawImagePointsRect_ptr = LoadFunction<GdipDrawImagePointsRect_delegate>("GdipDrawImagePointsRect");
- GdipDrawImagePointsRectI_ptr = LoadFunction<GdipDrawImagePointsRectI_delegate>("GdipDrawImagePointsRectI");
- GdipEnumerateMetafileDestPoint_ptr = LoadFunction<GdipEnumerateMetafileDestPoint_delegate>("GdipEnumerateMetafileDestPoint");
- GdipEnumerateMetafileDestPointI_ptr = LoadFunction<GdipEnumerateMetafileDestPointI_delegate>("GdipEnumerateMetafileDestPointI");
- GdipEnumerateMetafileDestRect_ptr = LoadFunction<GdipEnumerateMetafileDestRect_delegate>("GdipEnumerateMetafileDestRect");
- GdipEnumerateMetafileDestRectI_ptr = LoadFunction<GdipEnumerateMetafileDestRectI_delegate>("GdipEnumerateMetafileDestRectI");
- GdipEnumerateMetafileDestPoints_ptr = LoadFunction<GdipEnumerateMetafileDestPoints_delegate>("GdipEnumerateMetafileDestPoints");
- GdipEnumerateMetafileDestPointsI_ptr = LoadFunction<GdipEnumerateMetafileDestPointsI_delegate>("GdipEnumerateMetafileDestPointsI");
- GdipEnumerateMetafileSrcRectDestPoint_ptr = LoadFunction<GdipEnumerateMetafileSrcRectDestPoint_delegate>("GdipEnumerateMetafileSrcRectDestPoint");
- GdipEnumerateMetafileSrcRectDestPointI_ptr = LoadFunction<GdipEnumerateMetafileSrcRectDestPointI_delegate>("GdipEnumerateMetafileSrcRectDestPointI");
- GdipEnumerateMetafileSrcRectDestRect_ptr = LoadFunction<GdipEnumerateMetafileSrcRectDestRect_delegate>("GdipEnumerateMetafileSrcRectDestRect");
- GdipEnumerateMetafileSrcRectDestRectI_ptr = LoadFunction<GdipEnumerateMetafileSrcRectDestRectI_delegate>("GdipEnumerateMetafileSrcRectDestRectI");
- GdipEnumerateMetafileSrcRectDestPoints_ptr = LoadFunction<GdipEnumerateMetafileSrcRectDestPoints_delegate>("GdipEnumerateMetafileSrcRectDestPoints");
- GdipEnumerateMetafileSrcRectDestPointsI_ptr = LoadFunction<GdipEnumerateMetafileSrcRectDestPointsI_delegate>("GdipEnumerateMetafileSrcRectDestPointsI");
- GdipPlayMetafileRecord_ptr = LoadFunction<GdipPlayMetafileRecord_delegate>("GdipPlayMetafileRecord");
- GdipSaveGraphics_ptr = LoadFunction<GdipSaveGraphics_delegate>("GdipSaveGraphics");
- GdipRestoreGraphics_ptr = LoadFunction<GdipRestoreGraphics_delegate>("GdipRestoreGraphics");
- GdipEndContainer_ptr = LoadFunction<GdipEndContainer_delegate>("GdipEndContainer");
- GdipGetMetafileHeaderFromWmf_ptr = LoadFunction<GdipGetMetafileHeaderFromWmf_delegate>("GdipGetMetafileHeaderFromWmf");
- GdipGetMetafileHeaderFromEmf_ptr = LoadFunction<GdipGetMetafileHeaderFromEmf_delegate>("GdipGetMetafileHeaderFromEmf");
- GdipGetMetafileHeaderFromFile_ptr = LoadFunction<GdipGetMetafileHeaderFromFile_delegate>("GdipGetMetafileHeaderFromFile");
- GdipGetMetafileHeaderFromStream_ptr = LoadFunction<GdipGetMetafileHeaderFromStream_delegate>("GdipGetMetafileHeaderFromStream");
- GdipGetMetafileHeaderFromMetafile_ptr = LoadFunction<GdipGetMetafileHeaderFromMetafile_delegate>("GdipGetMetafileHeaderFromMetafile");
- GdipGetHemfFromMetafile_ptr = LoadFunction<GdipGetHemfFromMetafile_delegate>("GdipGetHemfFromMetafile");
- GdipCreateMetafileFromWmf_ptr = LoadFunction<GdipCreateMetafileFromWmf_delegate>("GdipCreateMetafileFromWmf");
- GdipCreateMetafileFromEmf_ptr = LoadFunction<GdipCreateMetafileFromEmf_delegate>("GdipCreateMetafileFromEmf");
- GdipCreateMetafileFromFile_ptr = LoadFunction<GdipCreateMetafileFromFile_delegate>("GdipCreateMetafileFromFile");
- GdipCreateMetafileFromStream_ptr = LoadFunction<GdipCreateMetafileFromStream_delegate>("GdipCreateMetafileFromStream");
- GdipRecordMetafile_ptr = LoadFunction<GdipRecordMetafile_delegate>("GdipRecordMetafile");
- GdipRecordMetafile2_ptr = LoadFunction<GdipRecordMetafile2_delegate>("GdipRecordMetafile");
- GdipRecordMetafileI_ptr = LoadFunction<GdipRecordMetafileI_delegate>("GdipRecordMetafileI");
- GdipRecordMetafileFileName_ptr = LoadFunction<GdipRecordMetafileFileName_delegate>("GdipRecordMetafileFileName");
- GdipRecordMetafileFileName2_ptr = LoadFunction<GdipRecordMetafileFileName2_delegate>("GdipRecordMetafileFileName");
- GdipRecordMetafileFileNameI_ptr = LoadFunction<GdipRecordMetafileFileNameI_delegate>("GdipRecordMetafileFileNameI");
- GdipRecordMetafileStream_ptr = LoadFunction<GdipRecordMetafileStream_delegate>("GdipRecordMetafileStream");
- GdipRecordMetafileStream2_ptr = LoadFunction<GdipRecordMetafileStream2_delegate>("GdipRecordMetafileStream");
- GdipRecordMetafileStreamI_ptr = LoadFunction<GdipRecordMetafileStreamI_delegate>("GdipRecordMetafileStreamI");
- GdipComment_ptr = LoadFunction<GdipComment_delegate>("GdipComment");
- GdipCreateFontFamilyFromName_ptr = LoadFunction<GdipCreateFontFamilyFromName_delegate>("GdipCreateFontFamilyFromName");
- GdipGetGenericFontFamilySansSerif_ptr = LoadFunction<GdipGetGenericFontFamilySansSerif_delegate>("GdipGetGenericFontFamilySansSerif");
- GdipGetGenericFontFamilySerif_ptr = LoadFunction<GdipGetGenericFontFamilySerif_delegate>("GdipGetGenericFontFamilySerif");
- GdipGetGenericFontFamilyMonospace_ptr = LoadFunction<GdipGetGenericFontFamilyMonospace_delegate>("GdipGetGenericFontFamilyMonospace");
- GdipDeleteFontFamily_ptr = LoadFunction<GdipDeleteFontFamily_delegate>("GdipDeleteFontFamily");
- GdipGetFamilyName_ptr = LoadFunction<GdipGetFamilyName_delegate>("GdipGetFamilyName");
- GdipIsStyleAvailable_ptr = LoadFunction<GdipIsStyleAvailable_delegate>("GdipIsStyleAvailable");
- GdipGetEmHeight_ptr = LoadFunction<GdipGetEmHeight_delegate>("GdipGetEmHeight");
- GdipGetCellAscent_ptr = LoadFunction<GdipGetCellAscent_delegate>("GdipGetCellAscent");
- GdipGetCellDescent_ptr = LoadFunction<GdipGetCellDescent_delegate>("GdipGetCellDescent");
- GdipGetLineSpacing_ptr = LoadFunction<GdipGetLineSpacing_delegate>("GdipGetLineSpacing");
- GdipCreateFontFromDC_ptr = LoadFunction<GdipCreateFontFromDC_delegate>("GdipCreateFontFromDC");
- GdipCreateFontFromLogfontW_ptr = LoadFunction<GdipCreateFontFromLogfontW_delegate>("GdipCreateFontFromLogfontW");
- GdipCreateFont_ptr = LoadFunction<GdipCreateFont_delegate>("GdipCreateFont");
- GdipGetLogFontW_ptr = LoadFunction<GdipGetLogFontW_delegate>("GdipGetLogFontW");
- GdipCloneFont_ptr = LoadFunction<GdipCloneFont_delegate>("GdipCloneFont");
- GdipDeleteFont_ptr = LoadFunction<GdipDeleteFont_delegate>("GdipDeleteFont");
- GdipGetFamily_ptr = LoadFunction<GdipGetFamily_delegate>("GdipGetFamily");
- GdipGetFontStyle_ptr = LoadFunction<GdipGetFontStyle_delegate>("GdipGetFontStyle");
- GdipGetFontSize_ptr = LoadFunction<GdipGetFontSize_delegate>("GdipGetFontSize");
- GdipGetFontHeight_ptr = LoadFunction<GdipGetFontHeight_delegate>("GdipGetFontHeight");
- GdipGetFontHeightGivenDPI_ptr = LoadFunction<GdipGetFontHeightGivenDPI_delegate>("GdipGetFontHeightGivenDPI");
- GdipGetFontUnit_ptr = LoadFunction<GdipGetFontUnit_delegate>("GdipGetFontUnit");
- GdipDrawString_ptr = LoadFunction<GdipDrawString_delegate>("GdipDrawString");
- GdipMeasureString_ptr = LoadFunction<GdipMeasureString_delegate>("GdipMeasureString");
- GdipMeasureCharacterRanges_ptr = LoadFunction<GdipMeasureCharacterRanges_delegate>("GdipMeasureCharacterRanges");
+ GdiplusStartup_ptr = FunctionWrapper.Load<GdiplusStartup_delegate>(s_gdipModule, "GdiplusStartup");
+ GdipCreatePath_ptr = FunctionWrapper.Load<GdipCreatePath_delegate>(s_gdipModule, "GdipCreatePath");
+ GdipCreatePath2_ptr = FunctionWrapper.Load<GdipCreatePath2_delegate>(s_gdipModule, "GdipCreatePath2");
+ GdipCreatePath2I_ptr = FunctionWrapper.Load<GdipCreatePath2I_delegate>(s_gdipModule, "GdipCreatePath2I");
+ GdipClonePath_ptr = FunctionWrapper.Load<GdipClonePath_delegate>(s_gdipModule, "GdipClonePath");
+ GdipDeletePath_ptr = FunctionWrapper.Load<GdipDeletePath_delegate>(s_gdipModule, "GdipDeletePath");
+ GdipResetPath_ptr = FunctionWrapper.Load<GdipResetPath_delegate>(s_gdipModule, "GdipResetPath");
+ GdipGetPointCount_ptr = FunctionWrapper.Load<GdipGetPointCount_delegate>(s_gdipModule, "GdipGetPointCount");
+ GdipGetPathTypes_ptr = FunctionWrapper.Load<GdipGetPathTypes_delegate>(s_gdipModule, "GdipGetPathTypes");
+ GdipGetPathPoints_ptr = FunctionWrapper.Load<GdipGetPathPoints_delegate>(s_gdipModule, "GdipGetPathPoints");
+ GdipGetPathFillMode_ptr = FunctionWrapper.Load<GdipGetPathFillMode_delegate>(s_gdipModule, "GdipGetPathFillMode");
+ GdipSetPathFillMode_ptr = FunctionWrapper.Load<GdipSetPathFillMode_delegate>(s_gdipModule, "GdipSetPathFillMode");
+ GdipGetPathData_ptr = FunctionWrapper.Load<GdipGetPathData_delegate>(s_gdipModule, "GdipGetPathData");
+ GdipStartPathFigure_ptr = FunctionWrapper.Load<GdipStartPathFigure_delegate>(s_gdipModule, "GdipStartPathFigure");
+ GdipClosePathFigure_ptr = FunctionWrapper.Load<GdipClosePathFigure_delegate>(s_gdipModule, "GdipClosePathFigure");
+ GdipClosePathFigures_ptr = FunctionWrapper.Load<GdipClosePathFigures_delegate>(s_gdipModule, "GdipClosePathFigures");
+ GdipSetPathMarker_ptr = FunctionWrapper.Load<GdipSetPathMarker_delegate>(s_gdipModule, "GdipSetPathMarker");
+ GdipClearPathMarkers_ptr = FunctionWrapper.Load<GdipClearPathMarkers_delegate>(s_gdipModule, "GdipClearPathMarkers");
+ GdipReversePath_ptr = FunctionWrapper.Load<GdipReversePath_delegate>(s_gdipModule, "GdipReversePath");
+ GdipGetPathLastPoint_ptr = FunctionWrapper.Load<GdipGetPathLastPoint_delegate>(s_gdipModule, "GdipGetPathLastPoint");
+ GdipAddPathLine_ptr = FunctionWrapper.Load<GdipAddPathLine_delegate>(s_gdipModule, "GdipAddPathLine");
+ GdipAddPathLine2_ptr = FunctionWrapper.Load<GdipAddPathLine2_delegate>(s_gdipModule, "GdipAddPathLine2");
+ GdipAddPathArc_ptr = FunctionWrapper.Load<GdipAddPathArc_delegate>(s_gdipModule, "GdipAddPathArc");
+ GdipAddPathBezier_ptr = FunctionWrapper.Load<GdipAddPathBezier_delegate>(s_gdipModule, "GdipAddPathBezier");
+ GdipAddPathBeziers_ptr = FunctionWrapper.Load<GdipAddPathBeziers_delegate>(s_gdipModule, "GdipAddPathBeziers");
+ GdipAddPathCurve_ptr = FunctionWrapper.Load<GdipAddPathCurve_delegate>(s_gdipModule, "GdipAddPathCurve");
+ GdipAddPathCurve2_ptr = FunctionWrapper.Load<GdipAddPathCurve2_delegate>(s_gdipModule, "GdipAddPathCurve2");
+ GdipAddPathCurve3_ptr = FunctionWrapper.Load<GdipAddPathCurve3_delegate>(s_gdipModule, "GdipAddPathCurve3");
+ GdipAddPathClosedCurve_ptr = FunctionWrapper.Load<GdipAddPathClosedCurve_delegate>(s_gdipModule, "GdipAddPathClosedCurve");
+ GdipAddPathClosedCurve2_ptr = FunctionWrapper.Load<GdipAddPathClosedCurve2_delegate>(s_gdipModule, "GdipAddPathClosedCurve2");
+ GdipAddPathRectangle_ptr = FunctionWrapper.Load<GdipAddPathRectangle_delegate>(s_gdipModule, "GdipAddPathRectangle");
+ GdipAddPathRectangles_ptr = FunctionWrapper.Load<GdipAddPathRectangles_delegate>(s_gdipModule, "GdipAddPathRectangles");
+ GdipAddPathEllipse_ptr = FunctionWrapper.Load<GdipAddPathEllipse_delegate>(s_gdipModule, "GdipAddPathEllipse");
+ GdipAddPathPie_ptr = FunctionWrapper.Load<GdipAddPathPie_delegate>(s_gdipModule, "GdipAddPathPie");
+ GdipAddPathPolygon_ptr = FunctionWrapper.Load<GdipAddPathPolygon_delegate>(s_gdipModule, "GdipAddPathPolygon");
+ GdipAddPathPath_ptr = FunctionWrapper.Load<GdipAddPathPath_delegate>(s_gdipModule, "GdipAddPathPath");
+ GdipAddPathString_ptr = FunctionWrapper.Load<GdipAddPathString_delegate>(s_gdipModule, "GdipAddPathString");
+ GdipAddPathStringI_ptr = FunctionWrapper.Load<GdipAddPathStringI_delegate>(s_gdipModule, "GdipAddPathStringI");
+ GdipAddPathLineI_ptr = FunctionWrapper.Load<GdipAddPathLineI_delegate>(s_gdipModule, "GdipAddPathLineI");
+ GdipAddPathLine2I_ptr = FunctionWrapper.Load<GdipAddPathLine2I_delegate>(s_gdipModule, "GdipAddPathLine2I");
+ GdipAddPathArcI_ptr = FunctionWrapper.Load<GdipAddPathArcI_delegate>(s_gdipModule, "GdipAddPathArcI");
+ GdipAddPathBezierI_ptr = FunctionWrapper.Load<GdipAddPathBezierI_delegate>(s_gdipModule, "GdipAddPathBezierI");
+ GdipAddPathBeziersI_ptr = FunctionWrapper.Load<GdipAddPathBeziersI_delegate>(s_gdipModule, "GdipAddPathBeziersI");
+ GdipAddPathCurveI_ptr = FunctionWrapper.Load<GdipAddPathCurveI_delegate>(s_gdipModule, "GdipAddPathCurveI");
+ GdipAddPathCurve2I_ptr = FunctionWrapper.Load<GdipAddPathCurve2I_delegate>(s_gdipModule, "GdipAddPathCurve2I");
+ GdipAddPathCurve3I_ptr = FunctionWrapper.Load<GdipAddPathCurve3I_delegate>(s_gdipModule, "GdipAddPathCurve3I");
+ GdipAddPathClosedCurveI_ptr = FunctionWrapper.Load<GdipAddPathClosedCurveI_delegate>(s_gdipModule, "GdipAddPathClosedCurveI");
+ GdipAddPathClosedCurve2I_ptr = FunctionWrapper.Load<GdipAddPathClosedCurve2I_delegate>(s_gdipModule, "GdipAddPathClosedCurve2I");
+ GdipAddPathRectangleI_ptr = FunctionWrapper.Load<GdipAddPathRectangleI_delegate>(s_gdipModule, "GdipAddPathRectangleI");
+ GdipAddPathRectanglesI_ptr = FunctionWrapper.Load<GdipAddPathRectanglesI_delegate>(s_gdipModule, "GdipAddPathRectanglesI");
+ GdipAddPathEllipseI_ptr = FunctionWrapper.Load<GdipAddPathEllipseI_delegate>(s_gdipModule, "GdipAddPathEllipseI");
+ GdipAddPathPieI_ptr = FunctionWrapper.Load<GdipAddPathPieI_delegate>(s_gdipModule, "GdipAddPathPieI");
+ GdipAddPathPolygonI_ptr = FunctionWrapper.Load<GdipAddPathPolygonI_delegate>(s_gdipModule, "GdipAddPathPolygonI");
+ GdipFlattenPath_ptr = FunctionWrapper.Load<GdipFlattenPath_delegate>(s_gdipModule, "GdipFlattenPath");
+ GdipWidenPath_ptr = FunctionWrapper.Load<GdipWidenPath_delegate>(s_gdipModule, "GdipWidenPath");
+ GdipWarpPath_ptr = FunctionWrapper.Load<GdipWarpPath_delegate>(s_gdipModule, "GdipWarpPath");
+ GdipTransformPath_ptr = FunctionWrapper.Load<GdipTransformPath_delegate>(s_gdipModule, "GdipTransformPath");
+ GdipGetPathWorldBounds_ptr = FunctionWrapper.Load<GdipGetPathWorldBounds_delegate>(s_gdipModule, "GdipGetPathWorldBounds");
+ GdipIsVisiblePathPoint_ptr = FunctionWrapper.Load<GdipIsVisiblePathPoint_delegate>(s_gdipModule, "GdipIsVisiblePathPoint");
+ GdipIsVisiblePathPointI_ptr = FunctionWrapper.Load<GdipIsVisiblePathPointI_delegate>(s_gdipModule, "GdipIsVisiblePathPointI");
+ GdipIsOutlineVisiblePathPoint_ptr = FunctionWrapper.Load<GdipIsOutlineVisiblePathPoint_delegate>(s_gdipModule, "GdipIsOutlineVisiblePathPoint");
+ GdipIsOutlineVisiblePathPointI_ptr = FunctionWrapper.Load<GdipIsOutlineVisiblePathPointI_delegate>(s_gdipModule, "GdipIsOutlineVisiblePathPointI");
+ GdipDeleteBrush_ptr = FunctionWrapper.Load<GdipDeleteBrush_delegate>(s_gdipModule, "GdipDeleteBrush");
+ GdipLoadImageFromStream_ptr = FunctionWrapper.Load<GdipLoadImageFromStream_delegate>(s_gdipModule, "GdipLoadImageFromStream");
+ GdipLoadImageFromFile_ptr = FunctionWrapper.Load<GdipLoadImageFromFile_delegate>(s_gdipModule, "GdipLoadImageFromFile");
+ GdipLoadImageFromStreamICM_ptr = FunctionWrapper.Load<GdipLoadImageFromStreamICM_delegate>(s_gdipModule, "GdipLoadImageFromStreamICM");
+ GdipLoadImageFromFileICM_ptr = FunctionWrapper.Load<GdipLoadImageFromFileICM_delegate>(s_gdipModule, "GdipLoadImageFromFileICM");
+ GdipCloneImage_ptr = FunctionWrapper.Load<GdipCloneImage_delegate>(s_gdipModule, "GdipCloneImage");
+ GdipDisposeImage_ptr = FunctionWrapper.Load<GdipDisposeImage_delegate>(s_gdipModule, "GdipDisposeImage");
+ GdipSaveImageToFile_ptr = FunctionWrapper.Load<GdipSaveImageToFile_delegate>(s_gdipModule, "GdipSaveImageToFile");
+ GdipSaveImageToStream_ptr = FunctionWrapper.Load<GdipSaveImageToStream_delegate>(s_gdipModule, "GdipSaveImageToStream");
+ GdipSaveAdd_ptr = FunctionWrapper.Load<GdipSaveAdd_delegate>(s_gdipModule, "GdipSaveAdd");
+ GdipSaveAddImage_ptr = FunctionWrapper.Load<GdipSaveAddImage_delegate>(s_gdipModule, "GdipSaveAddImage");
+ GdipGetImageGraphicsContext_ptr = FunctionWrapper.Load<GdipGetImageGraphicsContext_delegate>(s_gdipModule, "GdipGetImageGraphicsContext");
+ GdipGetImageBounds_ptr = FunctionWrapper.Load<GdipGetImageBounds_delegate>(s_gdipModule, "GdipGetImageBounds");
+ GdipGetImageDimension_ptr = FunctionWrapper.Load<GdipGetImageDimension_delegate>(s_gdipModule, "GdipGetImageDimension");
+ GdipGetImageType_ptr = FunctionWrapper.Load<GdipGetImageType_delegate>(s_gdipModule, "GdipGetImageType");
+ GdipGetImageWidth_ptr = FunctionWrapper.Load<GdipGetImageWidth_delegate>(s_gdipModule, "GdipGetImageWidth");
+ GdipGetImageHeight_ptr = FunctionWrapper.Load<GdipGetImageHeight_delegate>(s_gdipModule, "GdipGetImageHeight");
+ GdipGetImageHorizontalResolution_ptr = FunctionWrapper.Load<GdipGetImageHorizontalResolution_delegate>(s_gdipModule, "GdipGetImageHorizontalResolution");
+ GdipGetImageVerticalResolution_ptr = FunctionWrapper.Load<GdipGetImageVerticalResolution_delegate>(s_gdipModule, "GdipGetImageVerticalResolution");
+ GdipGetImageFlags_ptr = FunctionWrapper.Load<GdipGetImageFlags_delegate>(s_gdipModule, "GdipGetImageFlags");
+ GdipGetImageRawFormat_ptr = FunctionWrapper.Load<GdipGetImageRawFormat_delegate>(s_gdipModule, "GdipGetImageRawFormat");
+ GdipGetImagePixelFormat_ptr = FunctionWrapper.Load<GdipGetImagePixelFormat_delegate>(s_gdipModule, "GdipGetImagePixelFormat");
+ GdipGetImageThumbnail_ptr = FunctionWrapper.Load<GdipGetImageThumbnail_delegate>(s_gdipModule, "GdipGetImageThumbnail");
+ GdipGetEncoderParameterListSize_ptr = FunctionWrapper.Load<GdipGetEncoderParameterListSize_delegate>(s_gdipModule, "GdipGetEncoderParameterListSize");
+ GdipGetEncoderParameterList_ptr = FunctionWrapper.Load<GdipGetEncoderParameterList_delegate>(s_gdipModule, "GdipGetEncoderParameterList");
+ GdipImageGetFrameDimensionsCount_ptr = FunctionWrapper.Load<GdipImageGetFrameDimensionsCount_delegate>(s_gdipModule, "GdipImageGetFrameDimensionsCount");
+ GdipImageGetFrameDimensionsList_ptr = FunctionWrapper.Load<GdipImageGetFrameDimensionsList_delegate>(s_gdipModule, "GdipImageGetFrameDimensionsList");
+ GdipImageGetFrameCount_ptr = FunctionWrapper.Load<GdipImageGetFrameCount_delegate>(s_gdipModule, "GdipImageGetFrameCount");
+ GdipImageSelectActiveFrame_ptr = FunctionWrapper.Load<GdipImageSelectActiveFrame_delegate>(s_gdipModule, "GdipImageSelectActiveFrame");
+ GdipImageRotateFlip_ptr = FunctionWrapper.Load<GdipImageRotateFlip_delegate>(s_gdipModule, "GdipImageRotateFlip");
+ GdipGetImagePalette_ptr = FunctionWrapper.Load<GdipGetImagePalette_delegate>(s_gdipModule, "GdipGetImagePalette");
+ GdipSetImagePalette_ptr = FunctionWrapper.Load<GdipSetImagePalette_delegate>(s_gdipModule, "GdipSetImagePalette");
+ GdipGetImagePaletteSize_ptr = FunctionWrapper.Load<GdipGetImagePaletteSize_delegate>(s_gdipModule, "GdipGetImagePaletteSize");
+ GdipGetPropertyCount_ptr = FunctionWrapper.Load<GdipGetPropertyCount_delegate>(s_gdipModule, "GdipGetPropertyCount");
+ GdipGetPropertyIdList_ptr = FunctionWrapper.Load<GdipGetPropertyIdList_delegate>(s_gdipModule, "GdipGetPropertyIdList");
+ GdipGetPropertyItemSize_ptr = FunctionWrapper.Load<GdipGetPropertyItemSize_delegate>(s_gdipModule, "GdipGetPropertyItemSize");
+ GdipGetPropertyItem_ptr = FunctionWrapper.Load<GdipGetPropertyItem_delegate>(s_gdipModule, "GdipGetPropertyItem");
+ GdipGetPropertySize_ptr = FunctionWrapper.Load<GdipGetPropertySize_delegate>(s_gdipModule, "GdipGetPropertySize");
+ GdipGetAllPropertyItems_ptr = FunctionWrapper.Load<GdipGetAllPropertyItems_delegate>(s_gdipModule, "GdipGetAllPropertyItems");
+ GdipRemovePropertyItem_ptr = FunctionWrapper.Load<GdipRemovePropertyItem_delegate>(s_gdipModule, "GdipRemovePropertyItem");
+ GdipSetPropertyItem_ptr = FunctionWrapper.Load<GdipSetPropertyItem_delegate>(s_gdipModule, "GdipSetPropertyItem");
+ GdipImageForceValidation_ptr = FunctionWrapper.Load<GdipImageForceValidation_delegate>(s_gdipModule, "GdipImageForceValidation");
+ GdipCreateBitmapFromStream_ptr = FunctionWrapper.Load<GdipCreateBitmapFromStream_delegate>(s_gdipModule, "GdipCreateBitmapFromStream");
+ GdipCreateBitmapFromFile_ptr = FunctionWrapper.Load<GdipCreateBitmapFromFile_delegate>(s_gdipModule, "GdipCreateBitmapFromFile");
+ GdipCreateBitmapFromStreamICM_ptr = FunctionWrapper.Load<GdipCreateBitmapFromStreamICM_delegate>(s_gdipModule, "GdipCreateBitmapFromStreamICM");
+ GdipCreateBitmapFromFileICM_ptr = FunctionWrapper.Load<GdipCreateBitmapFromFileICM_delegate>(s_gdipModule, "GdipCreateBitmapFromFileICM");
+ GdipCreateBitmapFromScan0_ptr = FunctionWrapper.Load<GdipCreateBitmapFromScan0_delegate>(s_gdipModule, "GdipCreateBitmapFromScan0");
+ GdipCreateBitmapFromGraphics_ptr = FunctionWrapper.Load<GdipCreateBitmapFromGraphics_delegate>(s_gdipModule, "GdipCreateBitmapFromGraphics");
+ GdipCreateBitmapFromHBITMAP_ptr = FunctionWrapper.Load<GdipCreateBitmapFromHBITMAP_delegate>(s_gdipModule, "GdipCreateBitmapFromHBITMAP");
+ GdipCreateBitmapFromHICON_ptr = FunctionWrapper.Load<GdipCreateBitmapFromHICON_delegate>(s_gdipModule, "GdipCreateBitmapFromHICON");
+ GdipCreateBitmapFromResource_ptr = FunctionWrapper.Load<GdipCreateBitmapFromResource_delegate>(s_gdipModule, "GdipCreateBitmapFromResource");
+ GdipCreateHBITMAPFromBitmap_ptr = FunctionWrapper.Load<GdipCreateHBITMAPFromBitmap_delegate>(s_gdipModule, "GdipCreateHBITMAPFromBitmap");
+ GdipCreateHICONFromBitmap_ptr = FunctionWrapper.Load<GdipCreateHICONFromBitmap_delegate>(s_gdipModule, "GdipCreateHICONFromBitmap");
+ GdipCloneBitmapArea_ptr = FunctionWrapper.Load<GdipCloneBitmapArea_delegate>(s_gdipModule, "GdipCloneBitmapArea");
+ GdipCloneBitmapAreaI_ptr = FunctionWrapper.Load<GdipCloneBitmapAreaI_delegate>(s_gdipModule, "GdipCloneBitmapAreaI");
+ GdipBitmapLockBits_ptr = FunctionWrapper.Load<GdipBitmapLockBits_delegate>(s_gdipModule, "GdipBitmapLockBits");
+ GdipBitmapUnlockBits_ptr = FunctionWrapper.Load<GdipBitmapUnlockBits_delegate>(s_gdipModule, "GdipBitmapUnlockBits");
+ GdipBitmapGetPixel_ptr = FunctionWrapper.Load<GdipBitmapGetPixel_delegate>(s_gdipModule, "GdipBitmapGetPixel");
+ GdipBitmapSetPixel_ptr = FunctionWrapper.Load<GdipBitmapSetPixel_delegate>(s_gdipModule, "GdipBitmapSetPixel");
+ GdipBitmapSetResolution_ptr = FunctionWrapper.Load<GdipBitmapSetResolution_delegate>(s_gdipModule, "GdipBitmapSetResolution");
+ GdipFlush_ptr = FunctionWrapper.Load<GdipFlush_delegate>(s_gdipModule, "GdipFlush");
+ GdipCreateFromHDC_ptr = FunctionWrapper.Load<GdipCreateFromHDC_delegate>(s_gdipModule, "GdipCreateFromHDC");
+ GdipCreateFromHDC2_ptr = FunctionWrapper.Load<GdipCreateFromHDC2_delegate>(s_gdipModule, "GdipCreateFromHDC2");
+ GdipCreateFromHWND_ptr = FunctionWrapper.Load<GdipCreateFromHWND_delegate>(s_gdipModule, "GdipCreateFromHWND");
+ GdipDeleteGraphics_ptr = FunctionWrapper.Load<GdipDeleteGraphics_delegate>(s_gdipModule, "GdipDeleteGraphics");
+ GdipGetDC_ptr = FunctionWrapper.Load<GdipGetDC_delegate>(s_gdipModule, "GdipGetDC");
+ GdipReleaseDC_ptr = FunctionWrapper.Load<GdipReleaseDC_delegate>(s_gdipModule, "GdipReleaseDC");
+ GdipSetCompositingMode_ptr = FunctionWrapper.Load<GdipSetCompositingMode_delegate>(s_gdipModule, "GdipSetCompositingMode");
+ GdipSetTextRenderingHint_ptr = FunctionWrapper.Load<GdipSetTextRenderingHint_delegate>(s_gdipModule, "GdipSetTextRenderingHint");
+ GdipSetTextContrast_ptr = FunctionWrapper.Load<GdipSetTextContrast_delegate>(s_gdipModule, "GdipSetTextContrast");
+ GdipSetInterpolationMode_ptr = FunctionWrapper.Load<GdipSetInterpolationMode_delegate>(s_gdipModule, "GdipSetInterpolationMode");
+ GdipGetCompositingMode_ptr = FunctionWrapper.Load<GdipGetCompositingMode_delegate>(s_gdipModule, "GdipGetCompositingMode");
+ GdipSetRenderingOrigin_ptr = FunctionWrapper.Load<GdipSetRenderingOrigin_delegate>(s_gdipModule, "GdipSetRenderingOrigin");
+ GdipGetRenderingOrigin_ptr = FunctionWrapper.Load<GdipGetRenderingOrigin_delegate>(s_gdipModule, "GdipGetRenderingOrigin");
+ GdipSetCompositingQuality_ptr = FunctionWrapper.Load<GdipSetCompositingQuality_delegate>(s_gdipModule, "GdipSetCompositingQuality");
+ GdipGetCompositingQuality_ptr = FunctionWrapper.Load<GdipGetCompositingQuality_delegate>(s_gdipModule, "GdipGetCompositingQuality");
+ GdipSetSmoothingMode_ptr = FunctionWrapper.Load<GdipSetSmoothingMode_delegate>(s_gdipModule, "GdipSetSmoothingMode");
+ GdipGetSmoothingMode_ptr = FunctionWrapper.Load<GdipGetSmoothingMode_delegate>(s_gdipModule, "GdipGetSmoothingMode");
+ GdipSetPixelOffsetMode_ptr = FunctionWrapper.Load<GdipSetPixelOffsetMode_delegate>(s_gdipModule, "GdipSetPixelOffsetMode");
+ GdipGetPixelOffsetMode_ptr = FunctionWrapper.Load<GdipGetPixelOffsetMode_delegate>(s_gdipModule, "GdipGetPixelOffsetMode");
+ GdipGetTextRenderingHint_ptr = FunctionWrapper.Load<GdipGetTextRenderingHint_delegate>(s_gdipModule, "GdipGetTextRenderingHint");
+ GdipGetTextContrast_ptr = FunctionWrapper.Load<GdipGetTextContrast_delegate>(s_gdipModule, "GdipGetTextContrast");
+ GdipGetInterpolationMode_ptr = FunctionWrapper.Load<GdipGetInterpolationMode_delegate>(s_gdipModule, "GdipGetInterpolationMode");
+ GdipGetPageUnit_ptr = FunctionWrapper.Load<GdipGetPageUnit_delegate>(s_gdipModule, "GdipGetPageUnit");
+ GdipGetPageScale_ptr = FunctionWrapper.Load<GdipGetPageScale_delegate>(s_gdipModule, "GdipGetPageScale");
+ GdipSetPageUnit_ptr = FunctionWrapper.Load<GdipSetPageUnit_delegate>(s_gdipModule, "GdipSetPageUnit");
+ GdipSetPageScale_ptr = FunctionWrapper.Load<GdipSetPageScale_delegate>(s_gdipModule, "GdipSetPageScale");
+ GdipGetDpiX_ptr = FunctionWrapper.Load<GdipGetDpiX_delegate>(s_gdipModule, "GdipGetDpiX");
+ GdipGetDpiY_ptr = FunctionWrapper.Load<GdipGetDpiY_delegate>(s_gdipModule, "GdipGetDpiY");
+ GdipTransformPoints_ptr = FunctionWrapper.Load<GdipTransformPoints_delegate>(s_gdipModule, "GdipTransformPoints");
+ GdipTransformPointsI_ptr = FunctionWrapper.Load<GdipTransformPointsI_delegate>(s_gdipModule, "GdipTransformPointsI");
+ GdipGetNearestColor_ptr = FunctionWrapper.Load<GdipGetNearestColor_delegate>(s_gdipModule, "GdipGetNearestColor");
+ GdipCreateHalftonePalette_ptr = FunctionWrapper.Load<GdipCreateHalftonePalette_delegate>(s_gdipModule, "GdipCreateHalftonePalette");
+ GdipDrawLine_ptr = FunctionWrapper.Load<GdipDrawLine_delegate>(s_gdipModule, "GdipDrawLine");
+ GdipDrawLineI_ptr = FunctionWrapper.Load<GdipDrawLineI_delegate>(s_gdipModule, "GdipDrawLineI");
+ GdipDrawLines_ptr = FunctionWrapper.Load<GdipDrawLines_delegate>(s_gdipModule, "GdipDrawLines");
+ GdipDrawLinesI_ptr = FunctionWrapper.Load<GdipDrawLinesI_delegate>(s_gdipModule, "GdipDrawLinesI");
+ GdipDrawArc_ptr = FunctionWrapper.Load<GdipDrawArc_delegate>(s_gdipModule, "GdipDrawArc");
+ GdipDrawArcI_ptr = FunctionWrapper.Load<GdipDrawArcI_delegate>(s_gdipModule, "GdipDrawArcI");
+ GdipDrawBezier_ptr = FunctionWrapper.Load<GdipDrawBezier_delegate>(s_gdipModule, "GdipDrawBezier");
+ GdipDrawBeziers_ptr = FunctionWrapper.Load<GdipDrawBeziers_delegate>(s_gdipModule, "GdipDrawBeziers");
+ GdipDrawBeziersI_ptr = FunctionWrapper.Load<GdipDrawBeziersI_delegate>(s_gdipModule, "GdipDrawBeziersI");
+ GdipDrawRectangle_ptr = FunctionWrapper.Load<GdipDrawRectangle_delegate>(s_gdipModule, "GdipDrawRectangle");
+ GdipDrawRectangleI_ptr = FunctionWrapper.Load<GdipDrawRectangleI_delegate>(s_gdipModule, "GdipDrawRectangleI");
+ GdipDrawRectangles_ptr = FunctionWrapper.Load<GdipDrawRectangles_delegate>(s_gdipModule, "GdipDrawRectangles");
+ GdipDrawRectanglesI_ptr = FunctionWrapper.Load<GdipDrawRectanglesI_delegate>(s_gdipModule, "GdipDrawRectanglesI");
+ GdipDrawEllipse_ptr = FunctionWrapper.Load<GdipDrawEllipse_delegate>(s_gdipModule, "GdipDrawEllipse");
+ GdipDrawEllipseI_ptr = FunctionWrapper.Load<GdipDrawEllipseI_delegate>(s_gdipModule, "GdipDrawEllipseI");
+ GdipDrawPie_ptr = FunctionWrapper.Load<GdipDrawPie_delegate>(s_gdipModule, "GdipDrawPie");
+ GdipDrawPieI_ptr = FunctionWrapper.Load<GdipDrawPieI_delegate>(s_gdipModule, "GdipDrawPieI");
+ GdipDrawPolygon_ptr = FunctionWrapper.Load<GdipDrawPolygon_delegate>(s_gdipModule, "GdipDrawPolygon");
+ GdipDrawPolygonI_ptr = FunctionWrapper.Load<GdipDrawPolygonI_delegate>(s_gdipModule, "GdipDrawPolygonI");
+ GdipDrawPath_ptr = FunctionWrapper.Load<GdipDrawPath_delegate>(s_gdipModule, "GdipDrawPath");
+ GdipDrawCurve_ptr = FunctionWrapper.Load<GdipDrawCurve_delegate>(s_gdipModule, "GdipDrawCurve");
+ GdipDrawCurveI_ptr = FunctionWrapper.Load<GdipDrawCurveI_delegate>(s_gdipModule, "GdipDrawCurveI");
+ GdipDrawCurve2_ptr = FunctionWrapper.Load<GdipDrawCurve2_delegate>(s_gdipModule, "GdipDrawCurve2");
+ GdipDrawCurve2I_ptr = FunctionWrapper.Load<GdipDrawCurve2I_delegate>(s_gdipModule, "GdipDrawCurve2I");
+ GdipDrawCurve3_ptr = FunctionWrapper.Load<GdipDrawCurve3_delegate>(s_gdipModule, "GdipDrawCurve3");
+ GdipDrawCurve3I_ptr = FunctionWrapper.Load<GdipDrawCurve3I_delegate>(s_gdipModule, "GdipDrawCurve3I");
+ GdipDrawClosedCurve_ptr = FunctionWrapper.Load<GdipDrawClosedCurve_delegate>(s_gdipModule, "GdipDrawClosedCurve");
+ GdipDrawClosedCurveI_ptr = FunctionWrapper.Load<GdipDrawClosedCurveI_delegate>(s_gdipModule, "GdipDrawClosedCurveI");
+ GdipDrawClosedCurve2_ptr = FunctionWrapper.Load<GdipDrawClosedCurve2_delegate>(s_gdipModule, "GdipDrawClosedCurve2");
+ GdipDrawClosedCurve2I_ptr = FunctionWrapper.Load<GdipDrawClosedCurve2I_delegate>(s_gdipModule, "GdipDrawClosedCurve2I");
+ GdipGraphicsClear_ptr = FunctionWrapper.Load<GdipGraphicsClear_delegate>(s_gdipModule, "GdipGraphicsClear");
+ GdipFillRectangle_ptr = FunctionWrapper.Load<GdipFillRectangle_delegate>(s_gdipModule, "GdipFillRectangle");
+ GdipFillRectangleI_ptr = FunctionWrapper.Load<GdipFillRectangleI_delegate>(s_gdipModule, "GdipFillRectangleI");
+ GdipFillRectangles_ptr = FunctionWrapper.Load<GdipFillRectangles_delegate>(s_gdipModule, "GdipFillRectangles");
+ GdipFillRectanglesI_ptr = FunctionWrapper.Load<GdipFillRectanglesI_delegate>(s_gdipModule, "GdipFillRectanglesI");
+ GdipFillPolygon_ptr = FunctionWrapper.Load<GdipFillPolygon_delegate>(s_gdipModule, "GdipFillPolygon");
+ GdipFillPolygonI_ptr = FunctionWrapper.Load<GdipFillPolygonI_delegate>(s_gdipModule, "GdipFillPolygonI");
+ GdipFillEllipse_ptr = FunctionWrapper.Load<GdipFillEllipse_delegate>(s_gdipModule, "GdipFillEllipse");
+ GdipFillEllipseI_ptr = FunctionWrapper.Load<GdipFillEllipseI_delegate>(s_gdipModule, "GdipFillEllipseI");
+ GdipFillPie_ptr = FunctionWrapper.Load<GdipFillPie_delegate>(s_gdipModule, "GdipFillPie");
+ GdipFillPieI_ptr = FunctionWrapper.Load<GdipFillPieI_delegate>(s_gdipModule, "GdipFillPieI");
+ GdipFillPath_ptr = FunctionWrapper.Load<GdipFillPath_delegate>(s_gdipModule, "GdipFillPath");
+ GdipFillClosedCurve_ptr = FunctionWrapper.Load<GdipFillClosedCurve_delegate>(s_gdipModule, "GdipFillClosedCurve");
+ GdipFillClosedCurveI_ptr = FunctionWrapper.Load<GdipFillClosedCurveI_delegate>(s_gdipModule, "GdipFillClosedCurveI");
+ GdipFillClosedCurve2_ptr = FunctionWrapper.Load<GdipFillClosedCurve2_delegate>(s_gdipModule, "GdipFillClosedCurve2");
+ GdipFillClosedCurve2I_ptr = FunctionWrapper.Load<GdipFillClosedCurve2I_delegate>(s_gdipModule, "GdipFillClosedCurve2I");
+ GdipDrawImage_ptr = FunctionWrapper.Load<GdipDrawImage_delegate>(s_gdipModule, "GdipDrawImage");
+ GdipDrawImageI_ptr = FunctionWrapper.Load<GdipDrawImageI_delegate>(s_gdipModule, "GdipDrawImageI");
+ GdipDrawImageRect_ptr = FunctionWrapper.Load<GdipDrawImageRect_delegate>(s_gdipModule, "GdipDrawImageRect");
+ GdipDrawImageRectI_ptr = FunctionWrapper.Load<GdipDrawImageRectI_delegate>(s_gdipModule, "GdipDrawImageRectI");
+ GdipDrawImagePoints_ptr = FunctionWrapper.Load<GdipDrawImagePoints_delegate>(s_gdipModule, "GdipDrawImagePoints");
+ GdipDrawImagePointsI_ptr = FunctionWrapper.Load<GdipDrawImagePointsI_delegate>(s_gdipModule, "GdipDrawImagePointsI");
+ GdipDrawImagePointRect_ptr = FunctionWrapper.Load<GdipDrawImagePointRect_delegate>(s_gdipModule, "GdipDrawImagePointRect");
+ GdipDrawImagePointRectI_ptr = FunctionWrapper.Load<GdipDrawImagePointRectI_delegate>(s_gdipModule, "GdipDrawImagePointRectI");
+ GdipDrawImageRectRect_ptr = FunctionWrapper.Load<GdipDrawImageRectRect_delegate>(s_gdipModule, "GdipDrawImageRectRect");
+ GdipDrawImageRectRectI_ptr = FunctionWrapper.Load<GdipDrawImageRectRectI_delegate>(s_gdipModule, "GdipDrawImageRectRectI");
+ GdipDrawImagePointsRect_ptr = FunctionWrapper.Load<GdipDrawImagePointsRect_delegate>(s_gdipModule, "GdipDrawImagePointsRect");
+ GdipDrawImagePointsRectI_ptr = FunctionWrapper.Load<GdipDrawImagePointsRectI_delegate>(s_gdipModule, "GdipDrawImagePointsRectI");
+ GdipEnumerateMetafileDestPoint_ptr = FunctionWrapper.Load<GdipEnumerateMetafileDestPoint_delegate>(s_gdipModule, "GdipEnumerateMetafileDestPoint");
+ GdipEnumerateMetafileDestPointI_ptr = FunctionWrapper.Load<GdipEnumerateMetafileDestPointI_delegate>(s_gdipModule, "GdipEnumerateMetafileDestPointI");
+ GdipEnumerateMetafileDestRect_ptr = FunctionWrapper.Load<GdipEnumerateMetafileDestRect_delegate>(s_gdipModule, "GdipEnumerateMetafileDestRect");
+ GdipEnumerateMetafileDestRectI_ptr = FunctionWrapper.Load<GdipEnumerateMetafileDestRectI_delegate>(s_gdipModule, "GdipEnumerateMetafileDestRectI");
+ GdipEnumerateMetafileDestPoints_ptr = FunctionWrapper.Load<GdipEnumerateMetafileDestPoints_delegate>(s_gdipModule, "GdipEnumerateMetafileDestPoints");
+ GdipEnumerateMetafileDestPointsI_ptr = FunctionWrapper.Load<GdipEnumerateMetafileDestPointsI_delegate>(s_gdipModule, "GdipEnumerateMetafileDestPointsI");
+ GdipEnumerateMetafileSrcRectDestPoint_ptr = FunctionWrapper.Load<GdipEnumerateMetafileSrcRectDestPoint_delegate>(s_gdipModule, "GdipEnumerateMetafileSrcRectDestPoint");
+ GdipEnumerateMetafileSrcRectDestPointI_ptr = FunctionWrapper.Load<GdipEnumerateMetafileSrcRectDestPointI_delegate>(s_gdipModule, "GdipEnumerateMetafileSrcRectDestPointI");
+ GdipEnumerateMetafileSrcRectDestRect_ptr = FunctionWrapper.Load<GdipEnumerateMetafileSrcRectDestRect_delegate>(s_gdipModule, "GdipEnumerateMetafileSrcRectDestRect");
+ GdipEnumerateMetafileSrcRectDestRectI_ptr = FunctionWrapper.Load<GdipEnumerateMetafileSrcRectDestRectI_delegate>(s_gdipModule, "GdipEnumerateMetafileSrcRectDestRectI");
+ GdipEnumerateMetafileSrcRectDestPoints_ptr = FunctionWrapper.Load<GdipEnumerateMetafileSrcRectDestPoints_delegate>(s_gdipModule, "GdipEnumerateMetafileSrcRectDestPoints");
+ GdipEnumerateMetafileSrcRectDestPointsI_ptr = FunctionWrapper.Load<GdipEnumerateMetafileSrcRectDestPointsI_delegate>(s_gdipModule, "GdipEnumerateMetafileSrcRectDestPointsI");
+ GdipPlayMetafileRecord_ptr = FunctionWrapper.Load<GdipPlayMetafileRecord_delegate>(s_gdipModule, "GdipPlayMetafileRecord");
+ GdipSaveGraphics_ptr = FunctionWrapper.Load<GdipSaveGraphics_delegate>(s_gdipModule, "GdipSaveGraphics");
+ GdipRestoreGraphics_ptr = FunctionWrapper.Load<GdipRestoreGraphics_delegate>(s_gdipModule, "GdipRestoreGraphics");
+ GdipEndContainer_ptr = FunctionWrapper.Load<GdipEndContainer_delegate>(s_gdipModule, "GdipEndContainer");
+ GdipGetMetafileHeaderFromWmf_ptr = FunctionWrapper.Load<GdipGetMetafileHeaderFromWmf_delegate>(s_gdipModule, "GdipGetMetafileHeaderFromWmf");
+ GdipGetMetafileHeaderFromEmf_ptr = FunctionWrapper.Load<GdipGetMetafileHeaderFromEmf_delegate>(s_gdipModule, "GdipGetMetafileHeaderFromEmf");
+ GdipGetMetafileHeaderFromFile_ptr = FunctionWrapper.Load<GdipGetMetafileHeaderFromFile_delegate>(s_gdipModule, "GdipGetMetafileHeaderFromFile");
+ GdipGetMetafileHeaderFromStream_ptr = FunctionWrapper.Load<GdipGetMetafileHeaderFromStream_delegate>(s_gdipModule, "GdipGetMetafileHeaderFromStream");
+ GdipGetMetafileHeaderFromMetafile_ptr = FunctionWrapper.Load<GdipGetMetafileHeaderFromMetafile_delegate>(s_gdipModule, "GdipGetMetafileHeaderFromMetafile");
+ GdipGetHemfFromMetafile_ptr = FunctionWrapper.Load<GdipGetHemfFromMetafile_delegate>(s_gdipModule, "GdipGetHemfFromMetafile");
+ GdipCreateMetafileFromWmf_ptr = FunctionWrapper.Load<GdipCreateMetafileFromWmf_delegate>(s_gdipModule, "GdipCreateMetafileFromWmf");
+ GdipCreateMetafileFromEmf_ptr = FunctionWrapper.Load<GdipCreateMetafileFromEmf_delegate>(s_gdipModule, "GdipCreateMetafileFromEmf");
+ GdipCreateMetafileFromFile_ptr = FunctionWrapper.Load<GdipCreateMetafileFromFile_delegate>(s_gdipModule, "GdipCreateMetafileFromFile");
+ GdipCreateMetafileFromStream_ptr = FunctionWrapper.Load<GdipCreateMetafileFromStream_delegate>(s_gdipModule, "GdipCreateMetafileFromStream");
+ GdipRecordMetafile_ptr = FunctionWrapper.Load<GdipRecordMetafile_delegate>(s_gdipModule, "GdipRecordMetafile");
+ GdipRecordMetafile2_ptr = FunctionWrapper.Load<GdipRecordMetafile2_delegate>(s_gdipModule, "GdipRecordMetafile");
+ GdipRecordMetafileI_ptr = FunctionWrapper.Load<GdipRecordMetafileI_delegate>(s_gdipModule, "GdipRecordMetafileI");
+ GdipRecordMetafileFileName_ptr = FunctionWrapper.Load<GdipRecordMetafileFileName_delegate>(s_gdipModule, "GdipRecordMetafileFileName");
+ GdipRecordMetafileFileName2_ptr = FunctionWrapper.Load<GdipRecordMetafileFileName2_delegate>(s_gdipModule, "GdipRecordMetafileFileName");
+ GdipRecordMetafileFileNameI_ptr = FunctionWrapper.Load<GdipRecordMetafileFileNameI_delegate>(s_gdipModule, "GdipRecordMetafileFileNameI");
+ GdipRecordMetafileStream_ptr = FunctionWrapper.Load<GdipRecordMetafileStream_delegate>(s_gdipModule, "GdipRecordMetafileStream");
+ GdipRecordMetafileStream2_ptr = FunctionWrapper.Load<GdipRecordMetafileStream2_delegate>(s_gdipModule, "GdipRecordMetafileStream");
+ GdipRecordMetafileStreamI_ptr = FunctionWrapper.Load<GdipRecordMetafileStreamI_delegate>(s_gdipModule, "GdipRecordMetafileStreamI");
+ GdipComment_ptr = FunctionWrapper.Load<GdipComment_delegate>(s_gdipModule, "GdipComment");
+ GdipCreateFontFromDC_ptr = FunctionWrapper.Load<GdipCreateFontFromDC_delegate>(s_gdipModule, "GdipCreateFontFromDC");
+ GdipCreateFontFromLogfontW_ptr = FunctionWrapper.Load<GdipCreateFontFromLogfontW_delegate>(s_gdipModule, "GdipCreateFontFromLogfontW");
+ GdipCreateFont_ptr = FunctionWrapper.Load<GdipCreateFont_delegate>(s_gdipModule, "GdipCreateFont");
+ GdipGetLogFontW_ptr = FunctionWrapper.Load<GdipGetLogFontW_delegate>(s_gdipModule, "GdipGetLogFontW");
+ GdipCloneFont_ptr = FunctionWrapper.Load<GdipCloneFont_delegate>(s_gdipModule, "GdipCloneFont");
+ GdipDeleteFont_ptr = FunctionWrapper.Load<GdipDeleteFont_delegate>(s_gdipModule, "GdipDeleteFont");
+ GdipGetFamily_ptr = FunctionWrapper.Load<GdipGetFamily_delegate>(s_gdipModule, "GdipGetFamily");
+ GdipGetFontStyle_ptr = FunctionWrapper.Load<GdipGetFontStyle_delegate>(s_gdipModule, "GdipGetFontStyle");
+ GdipGetFontSize_ptr = FunctionWrapper.Load<GdipGetFontSize_delegate>(s_gdipModule, "GdipGetFontSize");
+ GdipGetFontHeight_ptr = FunctionWrapper.Load<GdipGetFontHeight_delegate>(s_gdipModule, "GdipGetFontHeight");
+ GdipGetFontHeightGivenDPI_ptr = FunctionWrapper.Load<GdipGetFontHeightGivenDPI_delegate>(s_gdipModule, "GdipGetFontHeightGivenDPI");
+ GdipGetFontUnit_ptr = FunctionWrapper.Load<GdipGetFontUnit_delegate>(s_gdipModule, "GdipGetFontUnit");
+ GdipDrawString_ptr = FunctionWrapper.Load<GdipDrawString_delegate>(s_gdipModule, "GdipDrawString");
+ GdipMeasureString_ptr = FunctionWrapper.Load<GdipMeasureString_delegate>(s_gdipModule, "GdipMeasureString");
+ GdipMeasureCharacterRanges_ptr = FunctionWrapper.Load<GdipMeasureCharacterRanges_delegate>(s_gdipModule, "GdipMeasureCharacterRanges");
}
// Imported functions
@@ -583,7 +575,7 @@ namespace System.Drawing
private static FunctionWrapper<GdipDisposeImage_delegate> GdipDisposeImage_ptr;
internal static int IntGdipDisposeImage(HandleRef image) => GdipDisposeImage_ptr.Delegate(image);
- private delegate int GdipSaveImageToFile_delegate(HandleRef image, string filename, ref Guid classId, HandleRef encoderParams);
+ private delegate int GdipSaveImageToFile_delegate(HandleRef image, [MarshalAs(UnmanagedType.LPWStr)] string filename, ref Guid classId, HandleRef encoderParams);
private static FunctionWrapper<GdipSaveImageToFile_delegate> GdipSaveImageToFile_ptr;
internal static int GdipSaveImageToFile(HandleRef image, string filename, ref Guid classId, HandleRef encoderParams) => GdipSaveImageToFile_ptr.Delegate(image, filename, ref classId, encoderParams);
@@ -1301,59 +1293,6 @@ namespace System.Drawing
private static FunctionWrapper<GdipComment_delegate> GdipComment_ptr;
internal static int GdipComment(HandleRef graphics, int sizeData, byte[] data) => GdipComment_ptr.Delegate(graphics, sizeData, data);
- private delegate int GdipCreateFontFamilyFromName_delegate([MarshalAs(UnmanagedType.LPWStr)]string name, HandleRef fontCollection, out IntPtr FontFamily);
- private static FunctionWrapper<GdipCreateFontFamilyFromName_delegate> GdipCreateFontFamilyFromName_ptr;
- internal static int GdipCreateFontFamilyFromName(string name, HandleRef fontCollection, out IntPtr FontFamily) => GdipCreateFontFamilyFromName_ptr.Delegate(name, fontCollection, out FontFamily);
-
- private delegate int GdipGetGenericFontFamilySansSerif_delegate(out IntPtr fontfamily);
- private static FunctionWrapper<GdipGetGenericFontFamilySansSerif_delegate> GdipGetGenericFontFamilySansSerif_ptr;
- internal static int GdipGetGenericFontFamilySansSerif(out IntPtr fontfamily) => GdipGetGenericFontFamilySansSerif_ptr.Delegate(out fontfamily);
-
- private delegate int GdipGetGenericFontFamilySerif_delegate(out IntPtr fontfamily);
- private static FunctionWrapper<GdipGetGenericFontFamilySerif_delegate> GdipGetGenericFontFamilySerif_ptr;
- internal static int GdipGetGenericFontFamilySerif(out IntPtr fontfamily) => GdipGetGenericFontFamilySerif_ptr.Delegate(out fontfamily);
-
- private delegate int GdipGetGenericFontFamilyMonospace_delegate(out IntPtr fontfamily);
- private static FunctionWrapper<GdipGetGenericFontFamilyMonospace_delegate> GdipGetGenericFontFamilyMonospace_ptr;
- internal static int GdipGetGenericFontFamilyMonospace(out IntPtr fontfamily) => GdipGetGenericFontFamilyMonospace_ptr.Delegate(out fontfamily);
-
- private delegate int GdipDeleteFontFamily_delegate(HandleRef fontFamily);
- private static FunctionWrapper<GdipDeleteFontFamily_delegate> GdipDeleteFontFamily_ptr;
- internal static int IntGdipDeleteFontFamily(HandleRef fontFamily) => GdipDeleteFontFamily_ptr.Delegate(fontFamily);
-
- private delegate int GdipGetFamilyName_delegate(HandleRef family, IntPtr name, int language);
- private static FunctionWrapper<GdipGetFamilyName_delegate> GdipGetFamilyName_ptr;
- internal static int GdipGetFamilyName(HandleRef family, IntPtr name, int language) => GdipGetFamilyName_ptr.Delegate(family, name, language);
- internal static unsafe int GdipGetFamilyName(HandleRef family, StringBuilder nameBuilder, int language)
- {
- const int LF_FACESIZE = 32;
- char* namePtr = stackalloc char[LF_FACESIZE];
- int ret = GdipGetFamilyName(family, (IntPtr)namePtr, language);
- string name = Marshal.PtrToStringUni((IntPtr)namePtr);
- nameBuilder.Append(name);
- return ret;
- }
-
- private delegate int GdipIsStyleAvailable_delegate(HandleRef family, FontStyle style, out int isStyleAvailable);
- private static FunctionWrapper<GdipIsStyleAvailable_delegate> GdipIsStyleAvailable_ptr;
- internal static int GdipIsStyleAvailable(HandleRef family, FontStyle style, out int isStyleAvailable) => GdipIsStyleAvailable_ptr.Delegate(family, style, out isStyleAvailable);
-
- private delegate int GdipGetEmHeight_delegate(HandleRef family, FontStyle style, out int EmHeight);
- private static FunctionWrapper<GdipGetEmHeight_delegate> GdipGetEmHeight_ptr;
- internal static int GdipGetEmHeight(HandleRef family, FontStyle style, out int EmHeight) => GdipGetEmHeight_ptr.Delegate(family, style, out EmHeight);
-
- private delegate int GdipGetCellAscent_delegate(HandleRef family, FontStyle style, out int CellAscent);
- private static FunctionWrapper<GdipGetCellAscent_delegate> GdipGetCellAscent_ptr;
- internal static int GdipGetCellAscent(HandleRef family, FontStyle style, out int CellAscent) => GdipGetCellAscent_ptr.Delegate(family, style, out CellAscent);
-
- private delegate int GdipGetCellDescent_delegate(HandleRef family, FontStyle style, out int CellDescent);
- private static FunctionWrapper<GdipGetCellDescent_delegate> GdipGetCellDescent_ptr;
- internal static int GdipGetCellDescent(HandleRef family, FontStyle style, out int CellDescent) => GdipGetCellDescent_ptr.Delegate(family, style, out CellDescent);
-
- private delegate int GdipGetLineSpacing_delegate(HandleRef family, FontStyle style, out int LineSpaceing);
- private static FunctionWrapper<GdipGetLineSpacing_delegate> GdipGetLineSpacing_ptr;
- internal static int GdipGetLineSpacing(HandleRef family, FontStyle style, out int LineSpaceing) => GdipGetLineSpacing_ptr.Delegate(family, style, out LineSpaceing);
-
private delegate int GdipCreateFontFromDC_delegate(HandleRef hdc, ref IntPtr font);
private static FunctionWrapper<GdipCreateFontFromDC_delegate> GdipCreateFontFromDC_ptr;
internal static int GdipCreateFontFromDC(HandleRef hdc, ref IntPtr font) => GdipCreateFontFromDC_ptr.Delegate(hdc, ref font);
diff --git a/src/System.Drawing.Common/src/System/Drawing/GdiplusNative.cs b/src/System.Drawing.Common/src/System/Drawing/GdiplusNative.cs
index 46ae26d667..5c306473b2 100644
--- a/src/System.Drawing.Common/src/System/Drawing/GdiplusNative.cs
+++ b/src/System.Drawing.Common/src/System/Drawing/GdiplusNative.cs
@@ -8,6 +8,7 @@ using System.Drawing.Imaging;
using System.Drawing.Internal;
using System.Drawing.Text;
using System.Runtime.InteropServices;
+using System.Text;
namespace System.Drawing
{
@@ -19,337 +20,308 @@ namespace System.Drawing
{
private static IntPtr s_gdipModule;
- private static FunctionWrapper<T> LoadFunction<T>(string name) where T : class
- {
- if (s_gdipModule == IntPtr.Zero)
- {
- throw new DllNotFoundException();
- }
-
- Lazy<T> lazyDelegate = new Lazy<T>(() =>
- {
- IntPtr funcPtr = LoadFunctionPointer(s_gdipModule, name);
- if (funcPtr == IntPtr.Zero)
- {
- return null;
- }
- else
- {
- return Marshal.GetDelegateForFunctionPointer<T>(funcPtr);
- }
- });
-
- return new FunctionWrapper<T>(lazyDelegate);
- }
-
- /// <summary>
- /// Utility class which lazily loads function pointers and throws an EntryPointNotFoundException at
- /// usage-time if the function pointer can not be loaded.
- /// </summary>
- /// <typeparam name="T">The type of the function to wrap.</typeparam>
- private class FunctionWrapper<T> where T : class
- {
- private Lazy<T> _lazyDelegate;
-
- public FunctionWrapper(Lazy<T> lazyDelegate)
- {
- _lazyDelegate = lazyDelegate;
- }
-
- public T Delegate => _lazyDelegate.Value ?? throw new EntryPointNotFoundException();
- }
-
private static void LoadSharedFunctionPointers()
{
- GdipBeginContainer_ptr = LoadFunction<GdipBeginContainer_delegate>("GdipBeginContainer");
- GdipBeginContainer2_ptr = LoadFunction<GdipBeginContainer2_delegate>("GdipBeginContainer2");
- GdipBeginContainerI_ptr = LoadFunction<GdipBeginContainerI_delegate>("GdipBeginContainerI");
- GdipEndContainer_ptr = LoadFunction<GdipEndContainer_delegate>("GdipEndContainer");
- GdipCreateAdjustableArrowCap_ptr = LoadFunction<GdipCreateAdjustableArrowCap_delegate>("GdipCreateAdjustableArrowCap");
- GdipGetAdjustableArrowCapHeight_ptr = LoadFunction<GdipGetAdjustableArrowCapHeight_delegate>("GdipGetAdjustableArrowCapHeight");
- GdipSetAdjustableArrowCapHeight_ptr = LoadFunction<GdipSetAdjustableArrowCapHeight_delegate>("GdipSetAdjustableArrowCapHeight");
- GdipSetAdjustableArrowCapWidth_ptr = LoadFunction<GdipSetAdjustableArrowCapWidth_delegate>("GdipSetAdjustableArrowCapWidth");
- GdipGetAdjustableArrowCapWidth_ptr = LoadFunction<GdipGetAdjustableArrowCapWidth_delegate>("GdipGetAdjustableArrowCapWidth");
- GdipSetAdjustableArrowCapMiddleInset_ptr = LoadFunction<GdipSetAdjustableArrowCapMiddleInset_delegate>("GdipSetAdjustableArrowCapMiddleInset");
- GdipGetAdjustableArrowCapMiddleInset_ptr = LoadFunction<GdipGetAdjustableArrowCapMiddleInset_delegate>("GdipGetAdjustableArrowCapMiddleInset");
- GdipSetAdjustableArrowCapFillState_ptr = LoadFunction<GdipSetAdjustableArrowCapFillState_delegate>("GdipSetAdjustableArrowCapFillState");
- GdipGetAdjustableArrowCapFillState_ptr = LoadFunction<GdipGetAdjustableArrowCapFillState_delegate>("GdipGetAdjustableArrowCapFillState");
- GdipGetCustomLineCapType_ptr = LoadFunction<GdipGetCustomLineCapType_delegate>("GdipGetCustomLineCapType");
- GdipCreateCustomLineCap_ptr = LoadFunction<GdipCreateCustomLineCap_delegate>("GdipCreateCustomLineCap");
- GdipDeleteCustomLineCap_ptr = LoadFunction<GdipDeleteCustomLineCap_delegate>("GdipDeleteCustomLineCap");
- GdipCloneCustomLineCap_ptr = LoadFunction<GdipCloneCustomLineCap_delegate>("GdipCloneCustomLineCap");
- GdipSetCustomLineCapStrokeCaps_ptr = LoadFunction<GdipSetCustomLineCapStrokeCaps_delegate>("GdipSetCustomLineCapStrokeCaps");
- GdipGetCustomLineCapStrokeCaps_ptr = LoadFunction<GdipGetCustomLineCapStrokeCaps_delegate>("GdipGetCustomLineCapStrokeCaps");
- GdipSetCustomLineCapStrokeJoin_ptr = LoadFunction<GdipSetCustomLineCapStrokeJoin_delegate>("GdipSetCustomLineCapStrokeJoin");
- GdipGetCustomLineCapStrokeJoin_ptr = LoadFunction<GdipGetCustomLineCapStrokeJoin_delegate>("GdipGetCustomLineCapStrokeJoin");
- GdipSetCustomLineCapBaseCap_ptr = LoadFunction<GdipSetCustomLineCapBaseCap_delegate>("GdipSetCustomLineCapBaseCap");
- GdipGetCustomLineCapBaseCap_ptr = LoadFunction<GdipGetCustomLineCapBaseCap_delegate>("GdipGetCustomLineCapBaseCap");
- GdipSetCustomLineCapBaseInset_ptr = LoadFunction<GdipSetCustomLineCapBaseInset_delegate>("GdipSetCustomLineCapBaseInset");
- GdipGetCustomLineCapBaseInset_ptr = LoadFunction<GdipGetCustomLineCapBaseInset_delegate>("GdipGetCustomLineCapBaseInset");
- GdipSetCustomLineCapWidthScale_ptr = LoadFunction<GdipSetCustomLineCapWidthScale_delegate>("GdipSetCustomLineCapWidthScale");
- GdipGetCustomLineCapWidthScale_ptr = LoadFunction<GdipGetCustomLineCapWidthScale_delegate>("GdipGetCustomLineCapWidthScale");
- GdipCreatePathIter_ptr = LoadFunction<GdipCreatePathIter_delegate>("GdipCreatePathIter");
- GdipDeletePathIter_ptr = LoadFunction<GdipDeletePathIter_delegate>("GdipDeletePathIter");
- GdipPathIterNextSubpath_ptr = LoadFunction<GdipPathIterNextSubpath_delegate>("GdipPathIterNextSubpath");
- GdipPathIterNextSubpathPath_ptr = LoadFunction<GdipPathIterNextSubpathPath_delegate>("GdipPathIterNextSubpathPath");
- GdipPathIterNextPathType_ptr = LoadFunction<GdipPathIterNextPathType_delegate>("GdipPathIterNextPathType");
- GdipPathIterNextMarker_ptr = LoadFunction<GdipPathIterNextMarker_delegate>("GdipPathIterNextMarker");
- GdipPathIterNextMarkerPath_ptr = LoadFunction<GdipPathIterNextMarkerPath_delegate>("GdipPathIterNextMarkerPath");
- GdipPathIterGetCount_ptr = LoadFunction<GdipPathIterGetCount_delegate>("GdipPathIterGetCount");
- GdipPathIterGetSubpathCount_ptr = LoadFunction<GdipPathIterGetSubpathCount_delegate>("GdipPathIterGetSubpathCount");
- GdipPathIterHasCurve_ptr = LoadFunction<GdipPathIterHasCurve_delegate>("GdipPathIterHasCurve");
- GdipPathIterRewind_ptr = LoadFunction<GdipPathIterRewind_delegate>("GdipPathIterRewind");
- GdipPathIterEnumerate_ptr = LoadFunction<GdipPathIterEnumerate_delegate>("GdipPathIterEnumerate");
- GdipPathIterCopyData_ptr = LoadFunction<GdipPathIterCopyData_delegate>("GdipPathIterCopyData");
- GdipCreateHatchBrush_ptr = LoadFunction<GdipCreateHatchBrush_delegate>("GdipCreateHatchBrush");
- GdipGetHatchStyle_ptr = LoadFunction<GdipGetHatchStyle_delegate>("GdipGetHatchStyle");
- GdipGetHatchForegroundColor_ptr = LoadFunction<GdipGetHatchForegroundColor_delegate>("GdipGetHatchForegroundColor");
- GdipGetHatchBackgroundColor_ptr = LoadFunction<GdipGetHatchBackgroundColor_delegate>("GdipGetHatchBackgroundColor");
- GdipCreateLineBrush_ptr = LoadFunction<GdipCreateLineBrush_delegate>("GdipCreateLineBrush");
- GdipCreateLineBrushI_ptr = LoadFunction<GdipCreateLineBrushI_delegate>("GdipCreateLineBrushI");
- GdipCreateLineBrushFromRect_ptr = LoadFunction<GdipCreateLineBrushFromRect_delegate>("GdipCreateLineBrushFromRect");
- GdipCreateLineBrushFromRectI_ptr = LoadFunction<GdipCreateLineBrushFromRectI_delegate>("GdipCreateLineBrushFromRectI");
- GdipCreateLineBrushFromRectWithAngle_ptr = LoadFunction<GdipCreateLineBrushFromRectWithAngle_delegate>("GdipCreateLineBrushFromRectWithAngle");
- GdipCreateLineBrushFromRectWithAngleI_ptr = LoadFunction<GdipCreateLineBrushFromRectWithAngleI_delegate>("GdipCreateLineBrushFromRectWithAngleI");
- GdipSetLineColors_ptr = LoadFunction<GdipSetLineColors_delegate>("GdipSetLineColors");
- GdipGetLineColors_ptr = LoadFunction<GdipGetLineColors_delegate>("GdipGetLineColors");
- GdipGetLineRect_ptr = LoadFunction<GdipGetLineRect_delegate>("GdipGetLineRect");
- GdipGetLineGammaCorrection_ptr = LoadFunction<GdipGetLineGammaCorrection_delegate>("GdipGetLineGammaCorrection");
- GdipSetLineGammaCorrection_ptr = LoadFunction<GdipSetLineGammaCorrection_delegate>("GdipSetLineGammaCorrection");
- GdipSetLineSigmaBlend_ptr = LoadFunction<GdipSetLineSigmaBlend_delegate>("GdipSetLineSigmaBlend");
- GdipSetLineLinearBlend_ptr = LoadFunction<GdipSetLineLinearBlend_delegate>("GdipSetLineLinearBlend");
- GdipGetLineBlendCount_ptr = LoadFunction<GdipGetLineBlendCount_delegate>("GdipGetLineBlendCount");
- GdipGetLineBlend_ptr = LoadFunction<GdipGetLineBlend_delegate>("GdipGetLineBlend");
- GdipSetLineBlend_ptr = LoadFunction<GdipSetLineBlend_delegate>("GdipSetLineBlend");
- GdipGetLinePresetBlendCount_ptr = LoadFunction<GdipGetLinePresetBlendCount_delegate>("GdipGetLinePresetBlendCount");
- GdipGetLinePresetBlend_ptr = LoadFunction<GdipGetLinePresetBlend_delegate>("GdipGetLinePresetBlend");
- GdipSetLinePresetBlend_ptr = LoadFunction<GdipSetLinePresetBlend_delegate>("GdipSetLinePresetBlend");
- GdipSetLineWrapMode_ptr = LoadFunction<GdipSetLineWrapMode_delegate>("GdipSetLineWrapMode");
- GdipGetLineWrapMode_ptr = LoadFunction<GdipGetLineWrapMode_delegate>("GdipGetLineWrapMode");
- GdipResetLineTransform_ptr = LoadFunction<GdipResetLineTransform_delegate>("GdipResetLineTransform");
- GdipMultiplyLineTransform_ptr = LoadFunction<GdipMultiplyLineTransform_delegate>("GdipMultiplyLineTransform");
- GdipGetLineTransform_ptr = LoadFunction<GdipGetLineTransform_delegate>("GdipGetLineTransform");
- GdipSetLineTransform_ptr = LoadFunction<GdipSetLineTransform_delegate>("GdipSetLineTransform");
- GdipTranslateLineTransform_ptr = LoadFunction<GdipTranslateLineTransform_delegate>("GdipTranslateLineTransform");
- GdipScaleLineTransform_ptr = LoadFunction<GdipScaleLineTransform_delegate>("GdipScaleLineTransform");
- GdipRotateLineTransform_ptr = LoadFunction<GdipRotateLineTransform_delegate>("GdipRotateLineTransform");
- GdipCreatePathGradient_ptr = LoadFunction<GdipCreatePathGradient_delegate>("GdipCreatePathGradient");
- GdipCreatePathGradientI_ptr = LoadFunction<GdipCreatePathGradientI_delegate>("GdipCreatePathGradientI");
- GdipCreatePathGradientFromPath_ptr = LoadFunction<GdipCreatePathGradientFromPath_delegate>("GdipCreatePathGradientFromPath");
- GdipGetPathGradientCenterColor_ptr = LoadFunction<GdipGetPathGradientCenterColor_delegate>("GdipGetPathGradientCenterColor");
- GdipSetPathGradientCenterColor_ptr = LoadFunction<GdipSetPathGradientCenterColor_delegate>("GdipSetPathGradientCenterColor");
- GdipGetPathGradientSurroundColorsWithCount_ptr = LoadFunction<GdipGetPathGradientSurroundColorsWithCount_delegate>("GdipGetPathGradientSurroundColorsWithCount");
- GdipSetPathGradientSurroundColorsWithCount_ptr = LoadFunction<GdipSetPathGradientSurroundColorsWithCount_delegate>("GdipSetPathGradientSurroundColorsWithCount");
- GdipGetPathGradientCenterPoint_ptr = LoadFunction<GdipGetPathGradientCenterPoint_delegate>("GdipGetPathGradientCenterPoint");
- GdipSetPathGradientCenterPoint_ptr = LoadFunction<GdipSetPathGradientCenterPoint_delegate>("GdipSetPathGradientCenterPoint");
- GdipGetPathGradientRect_ptr = LoadFunction<GdipGetPathGradientRect_delegate>("GdipGetPathGradientRect");
- GdipGetPathGradientPointCount_ptr = LoadFunction<GdipGetPathGradientPointCount_delegate>("GdipGetPathGradientPointCount");
- GdipGetPathGradientSurroundColorCount_ptr = LoadFunction<GdipGetPathGradientSurroundColorCount_delegate>("GdipGetPathGradientSurroundColorCount");
- GdipGetPathGradientBlendCount_ptr = LoadFunction<GdipGetPathGradientBlendCount_delegate>("GdipGetPathGradientBlendCount");
- GdipGetPathGradientBlend_ptr = LoadFunction<GdipGetPathGradientBlend_delegate>("GdipGetPathGradientBlend");
- GdipSetPathGradientBlend_ptr = LoadFunction<GdipSetPathGradientBlend_delegate>("GdipSetPathGradientBlend");
- GdipGetPathGradientPresetBlendCount_ptr = LoadFunction<GdipGetPathGradientPresetBlendCount_delegate>("GdipGetPathGradientPresetBlendCount");
- GdipGetPathGradientPresetBlend_ptr = LoadFunction<GdipGetPathGradientPresetBlend_delegate>("GdipGetPathGradientPresetBlend");
- GdipSetPathGradientPresetBlend_ptr = LoadFunction<GdipSetPathGradientPresetBlend_delegate>("GdipSetPathGradientPresetBlend");
- GdipSetPathGradientSigmaBlend_ptr = LoadFunction<GdipSetPathGradientSigmaBlend_delegate>("GdipSetPathGradientSigmaBlend");
- GdipSetPathGradientLinearBlend_ptr = LoadFunction<GdipSetPathGradientLinearBlend_delegate>("GdipSetPathGradientLinearBlend");
- GdipSetPathGradientWrapMode_ptr = LoadFunction<GdipSetPathGradientWrapMode_delegate>("GdipSetPathGradientWrapMode");
- GdipGetPathGradientWrapMode_ptr = LoadFunction<GdipGetPathGradientWrapMode_delegate>("GdipGetPathGradientWrapMode");
- GdipSetPathGradientTransform_ptr = LoadFunction<GdipSetPathGradientTransform_delegate>("GdipSetPathGradientTransform");
- GdipGetPathGradientTransform_ptr = LoadFunction<GdipGetPathGradientTransform_delegate>("GdipGetPathGradientTransform");
- GdipResetPathGradientTransform_ptr = LoadFunction<GdipResetPathGradientTransform_delegate>("GdipResetPathGradientTransform");
- GdipMultiplyPathGradientTransform_ptr = LoadFunction<GdipMultiplyPathGradientTransform_delegate>("GdipMultiplyPathGradientTransform");
- GdipTranslatePathGradientTransform_ptr = LoadFunction<GdipTranslatePathGradientTransform_delegate>("GdipTranslatePathGradientTransform");
- GdipScalePathGradientTransform_ptr = LoadFunction<GdipScalePathGradientTransform_delegate>("GdipScalePathGradientTransform");
- GdipRotatePathGradientTransform_ptr = LoadFunction<GdipRotatePathGradientTransform_delegate>("GdipRotatePathGradientTransform");
- GdipGetPathGradientFocusScales_ptr = LoadFunction<GdipGetPathGradientFocusScales_delegate>("GdipGetPathGradientFocusScales");
- GdipSetPathGradientFocusScales_ptr = LoadFunction<GdipSetPathGradientFocusScales_delegate>("GdipSetPathGradientFocusScales");
- GdipCloneBrush_ptr = LoadFunction<GdipCloneBrush_delegate>("GdipCloneBrush");
- GdipCreateImageAttributes_ptr = LoadFunction<GdipCreateImageAttributes_delegate>("GdipCreateImageAttributes");
- GdipCloneImageAttributes_ptr = LoadFunction<GdipCloneImageAttributes_delegate>("GdipCloneImageAttributes");
- GdipDisposeImageAttributes_ptr = LoadFunction<GdipDisposeImageAttributes_delegate>("GdipDisposeImageAttributes");
- GdipSetImageAttributesColorMatrix_ptr = LoadFunction<GdipSetImageAttributesColorMatrix_delegate>("GdipSetImageAttributesColorMatrix");
- GdipSetImageAttributesThreshold_ptr = LoadFunction<GdipSetImageAttributesThreshold_delegate>("GdipSetImageAttributesThreshold");
- GdipSetImageAttributesGamma_ptr = LoadFunction<GdipSetImageAttributesGamma_delegate>("GdipSetImageAttributesGamma");
- GdipSetImageAttributesNoOp_ptr = LoadFunction<GdipSetImageAttributesNoOp_delegate>("GdipSetImageAttributesNoOp");
- GdipSetImageAttributesColorKeys_ptr = LoadFunction<GdipSetImageAttributesColorKeys_delegate>("GdipSetImageAttributesColorKeys");
- GdipSetImageAttributesOutputChannel_ptr = LoadFunction<GdipSetImageAttributesOutputChannel_delegate>("GdipSetImageAttributesOutputChannel");
- GdipSetImageAttributesOutputChannelColorProfile_ptr = LoadFunction<GdipSetImageAttributesOutputChannelColorProfile_delegate>("GdipSetImageAttributesOutputChannelColorProfile");
- GdipSetImageAttributesRemapTable_ptr = LoadFunction<GdipSetImageAttributesRemapTable_delegate>("GdipSetImageAttributesRemapTable");
- GdipSetImageAttributesWrapMode_ptr = LoadFunction<GdipSetImageAttributesWrapMode_delegate>("GdipSetImageAttributesWrapMode");
- GdipGetImageAttributesAdjustedPalette_ptr = LoadFunction<GdipGetImageAttributesAdjustedPalette_delegate>("GdipGetImageAttributesAdjustedPalette");
- GdipGetImageDecodersSize_ptr = LoadFunction<GdipGetImageDecodersSize_delegate>("GdipGetImageDecodersSize");
- GdipGetImageDecoders_ptr = LoadFunction<GdipGetImageDecoders_delegate>("GdipGetImageDecoders");
- GdipGetImageEncodersSize_ptr = LoadFunction<GdipGetImageEncodersSize_delegate>("GdipGetImageEncodersSize");
- GdipGetImageEncoders_ptr = LoadFunction<GdipGetImageEncoders_delegate>("GdipGetImageEncoders");
- GdipCreateSolidFill_ptr = LoadFunction<GdipCreateSolidFill_delegate>("GdipCreateSolidFill");
- GdipSetSolidFillColor_ptr = LoadFunction<GdipSetSolidFillColor_delegate>("GdipSetSolidFillColor");
- GdipGetSolidFillColor_ptr = LoadFunction<GdipGetSolidFillColor_delegate>("GdipGetSolidFillColor");
- GdipCreateTexture_ptr = LoadFunction<GdipCreateTexture_delegate>("GdipCreateTexture");
- GdipCreateTexture2_ptr = LoadFunction<GdipCreateTexture2_delegate>("GdipCreateTexture2");
- GdipCreateTextureIA_ptr = LoadFunction<GdipCreateTextureIA_delegate>("GdipCreateTextureIA");
- GdipCreateTexture2I_ptr = LoadFunction<GdipCreateTexture2I_delegate>("GdipCreateTexture2I");
- GdipCreateTextureIAI_ptr = LoadFunction<GdipCreateTextureIAI_delegate>("GdipCreateTextureIAI");
- GdipSetTextureTransform_ptr = LoadFunction<GdipSetTextureTransform_delegate>("GdipSetTextureTransform");
- GdipGetTextureTransform_ptr = LoadFunction<GdipGetTextureTransform_delegate>("GdipGetTextureTransform");
- GdipResetTextureTransform_ptr = LoadFunction<GdipResetTextureTransform_delegate>("GdipResetTextureTransform");
- GdipMultiplyTextureTransform_ptr = LoadFunction<GdipMultiplyTextureTransform_delegate>("GdipMultiplyTextureTransform");
- GdipTranslateTextureTransform_ptr = LoadFunction<GdipTranslateTextureTransform_delegate>("GdipTranslateTextureTransform");
- GdipScaleTextureTransform_ptr = LoadFunction<GdipScaleTextureTransform_delegate>("GdipScaleTextureTransform");
- GdipRotateTextureTransform_ptr = LoadFunction<GdipRotateTextureTransform_delegate>("GdipRotateTextureTransform");
- GdipSetTextureWrapMode_ptr = LoadFunction<GdipSetTextureWrapMode_delegate>("GdipSetTextureWrapMode");
- GdipGetTextureWrapMode_ptr = LoadFunction<GdipGetTextureWrapMode_delegate>("GdipGetTextureWrapMode");
- GdipGetTextureImage_ptr = LoadFunction<GdipGetTextureImage_delegate>("GdipGetTextureImage");
- GdipGetFontCollectionFamilyCount_ptr = LoadFunction<GdipGetFontCollectionFamilyCount_delegate>("GdipGetFontCollectionFamilyCount");
- GdipGetFontCollectionFamilyList_ptr = LoadFunction<GdipGetFontCollectionFamilyList_delegate>("GdipGetFontCollectionFamilyList");
- GdipCloneFontFamily_ptr = LoadFunction<GdipCloneFontFamily_delegate>("GdipCloneFontFamily");
- GdipNewInstalledFontCollection_ptr = LoadFunction<GdipNewInstalledFontCollection_delegate>("GdipNewInstalledFontCollection");
- GdipNewPrivateFontCollection_ptr = LoadFunction<GdipNewPrivateFontCollection_delegate>("GdipNewPrivateFontCollection");
- GdipDeletePrivateFontCollection_ptr = LoadFunction<GdipDeletePrivateFontCollection_delegate>("GdipDeletePrivateFontCollection");
- GdipPrivateAddFontFile_ptr = LoadFunction<GdipPrivateAddFontFile_delegate>("GdipPrivateAddFontFile");
- GdipPrivateAddMemoryFont_ptr = LoadFunction<GdipPrivateAddMemoryFont_delegate>("GdipPrivateAddMemoryFont");
- GdipCreatePen1_ptr = LoadFunction<GdipCreatePen1_delegate>("GdipCreatePen1");
- GdipCreatePen2_ptr = LoadFunction<GdipCreatePen2_delegate>("GdipCreatePen2");
- GdipClonePen_ptr = LoadFunction<GdipClonePen_delegate>("GdipClonePen");
- GdipDeletePen_ptr = LoadFunction<GdipDeletePen_delegate>("GdipDeletePen");
- GdipSetPenMode_ptr = LoadFunction<GdipSetPenMode_delegate>("GdipSetPenMode");
- GdipGetPenMode_ptr = LoadFunction<GdipGetPenMode_delegate>("GdipGetPenMode");
- GdipSetPenWidth_ptr = LoadFunction<GdipSetPenWidth_delegate>("GdipSetPenWidth");
- GdipGetPenWidth_ptr = LoadFunction<GdipGetPenWidth_delegate>("GdipGetPenWidth");
- GdipSetPenLineCap197819_ptr = LoadFunction<GdipSetPenLineCap197819_delegate>("GdipSetPenLineCap197819");
- GdipSetPenStartCap_ptr = LoadFunction<GdipSetPenStartCap_delegate>("GdipSetPenStartCap");
- GdipSetPenEndCap_ptr = LoadFunction<GdipSetPenEndCap_delegate>("GdipSetPenEndCap");
- GdipGetPenStartCap_ptr = LoadFunction<GdipGetPenStartCap_delegate>("GdipGetPenStartCap");
- GdipGetPenEndCap_ptr = LoadFunction<GdipGetPenEndCap_delegate>("GdipGetPenEndCap");
- GdipGetPenDashCap197819_ptr = LoadFunction<GdipGetPenDashCap197819_delegate>("GdipGetPenDashCap197819");
- GdipSetPenDashCap197819_ptr = LoadFunction<GdipSetPenDashCap197819_delegate>("GdipSetPenDashCap197819");
- GdipSetPenLineJoin_ptr = LoadFunction<GdipSetPenLineJoin_delegate>("GdipSetPenLineJoin");
- GdipGetPenLineJoin_ptr = LoadFunction<GdipGetPenLineJoin_delegate>("GdipGetPenLineJoin");
- GdipSetPenCustomStartCap_ptr = LoadFunction<GdipSetPenCustomStartCap_delegate>("GdipSetPenCustomStartCap");
- GdipGetPenCustomStartCap_ptr = LoadFunction<GdipGetPenCustomStartCap_delegate>("GdipGetPenCustomStartCap");
- GdipSetPenCustomEndCap_ptr = LoadFunction<GdipSetPenCustomEndCap_delegate>("GdipSetPenCustomEndCap");
- GdipGetPenCustomEndCap_ptr = LoadFunction<GdipGetPenCustomEndCap_delegate>("GdipGetPenCustomEndCap");
- GdipSetPenMiterLimit_ptr = LoadFunction<GdipSetPenMiterLimit_delegate>("GdipSetPenMiterLimit");
- GdipGetPenMiterLimit_ptr = LoadFunction<GdipGetPenMiterLimit_delegate>("GdipGetPenMiterLimit");
- GdipSetPenTransform_ptr = LoadFunction<GdipSetPenTransform_delegate>("GdipSetPenTransform");
- GdipGetPenTransform_ptr = LoadFunction<GdipGetPenTransform_delegate>("GdipGetPenTransform");
- GdipResetPenTransform_ptr = LoadFunction<GdipResetPenTransform_delegate>("GdipResetPenTransform");
- GdipMultiplyPenTransform_ptr = LoadFunction<GdipMultiplyPenTransform_delegate>("GdipMultiplyPenTransform");
- GdipTranslatePenTransform_ptr = LoadFunction<GdipTranslatePenTransform_delegate>("GdipTranslatePenTransform");
- GdipScalePenTransform_ptr = LoadFunction<GdipScalePenTransform_delegate>("GdipScalePenTransform");
- GdipRotatePenTransform_ptr = LoadFunction<GdipRotatePenTransform_delegate>("GdipRotatePenTransform");
- GdipSetPenColor_ptr = LoadFunction<GdipSetPenColor_delegate>("GdipSetPenColor");
- GdipGetPenColor_ptr = LoadFunction<GdipGetPenColor_delegate>("GdipGetPenColor");
- GdipSetPenBrushFill_ptr = LoadFunction<GdipSetPenBrushFill_delegate>("GdipSetPenBrushFill");
- GdipGetPenBrushFill_ptr = LoadFunction<GdipGetPenBrushFill_delegate>("GdipGetPenBrushFill");
- GdipGetPenFillType_ptr = LoadFunction<GdipGetPenFillType_delegate>("GdipGetPenFillType");
- GdipGetPenDashStyle_ptr = LoadFunction<GdipGetPenDashStyle_delegate>("GdipGetPenDashStyle");
- GdipSetPenDashStyle_ptr = LoadFunction<GdipSetPenDashStyle_delegate>("GdipSetPenDashStyle");
- GdipSetPenDashArray_ptr = LoadFunction<GdipSetPenDashArray_delegate>("GdipSetPenDashArray");
- GdipGetPenDashOffset_ptr = LoadFunction<GdipGetPenDashOffset_delegate>("GdipGetPenDashOffset");
- GdipSetPenDashOffset_ptr = LoadFunction<GdipSetPenDashOffset_delegate>("GdipSetPenDashOffset");
- GdipGetPenDashCount_ptr = LoadFunction<GdipGetPenDashCount_delegate>("GdipGetPenDashCount");
- GdipGetPenDashArray_ptr = LoadFunction<GdipGetPenDashArray_delegate>("GdipGetPenDashArray");
- GdipGetPenCompoundCount_ptr = LoadFunction<GdipGetPenCompoundCount_delegate>("GdipGetPenCompoundCount");
- GdipSetPenCompoundArray_ptr = LoadFunction<GdipSetPenCompoundArray_delegate>("GdipSetPenCompoundArray");
- GdipGetPenCompoundArray_ptr = LoadFunction<GdipGetPenCompoundArray_delegate>("GdipGetPenCompoundArray");
- GdipSetWorldTransform_ptr = LoadFunction<GdipSetWorldTransform_delegate>("GdipSetWorldTransform");
- GdipResetWorldTransform_ptr = LoadFunction<GdipResetWorldTransform_delegate>("GdipResetWorldTransform");
- GdipMultiplyWorldTransform_ptr = LoadFunction<GdipMultiplyWorldTransform_delegate>("GdipMultiplyWorldTransform");
- GdipTranslateWorldTransform_ptr = LoadFunction<GdipTranslateWorldTransform_delegate>("GdipTranslateWorldTransform");
- GdipScaleWorldTransform_ptr = LoadFunction<GdipScaleWorldTransform_delegate>("GdipScaleWorldTransform");
- GdipRotateWorldTransform_ptr = LoadFunction<GdipRotateWorldTransform_delegate>("GdipRotateWorldTransform");
- GdipGetWorldTransform_ptr = LoadFunction<GdipGetWorldTransform_delegate>("GdipGetWorldTransform");
- GdipCreateMatrix_ptr = LoadFunction<GdipCreateMatrix_delegate>("GdipCreateMatrix");
- GdipCreateMatrix2_ptr = LoadFunction<GdipCreateMatrix2_delegate>("GdipCreateMatrix2");
- GdipCreateMatrix3_ptr = LoadFunction<GdipCreateMatrix3_delegate>("GdipCreateMatrix3");
- GdipCreateMatrix3I_ptr = LoadFunction<GdipCreateMatrix3I_delegate>("GdipCreateMatrix3I");
- GdipCloneMatrix_ptr = LoadFunction<GdipCloneMatrix_delegate>("GdipCloneMatrix");
- GdipDeleteMatrix_ptr = LoadFunction<GdipDeleteMatrix_delegate>("GdipDeleteMatrix");
- GdipSetMatrixElements_ptr = LoadFunction<GdipSetMatrixElements_delegate>("GdipSetMatrixElements");
- GdipMultiplyMatrix_ptr = LoadFunction<GdipMultiplyMatrix_delegate>("GdipMultiplyMatrix");
- GdipTranslateMatrix_ptr = LoadFunction<GdipTranslateMatrix_delegate>("GdipTranslateMatrix");
- GdipScaleMatrix_ptr = LoadFunction<GdipScaleMatrix_delegate>("GdipScaleMatrix");
- GdipRotateMatrix_ptr = LoadFunction<GdipRotateMatrix_delegate>("GdipRotateMatrix");
- GdipShearMatrix_ptr = LoadFunction<GdipShearMatrix_delegate>("GdipShearMatrix");
- GdipInvertMatrix_ptr = LoadFunction<GdipInvertMatrix_delegate>("GdipInvertMatrix");
- GdipTransformMatrixPoints_ptr = LoadFunction<GdipTransformMatrixPoints_delegate>("GdipTransformMatrixPoints");
- GdipTransformMatrixPointsI_ptr = LoadFunction<GdipTransformMatrixPointsI_delegate>("GdipTransformMatrixPointsI");
- GdipVectorTransformMatrixPoints_ptr = LoadFunction<GdipVectorTransformMatrixPoints_delegate>("GdipVectorTransformMatrixPoints");
- GdipVectorTransformMatrixPointsI_ptr = LoadFunction<GdipVectorTransformMatrixPointsI_delegate>("GdipVectorTransformMatrixPointsI");
- GdipGetMatrixElements_ptr = LoadFunction<GdipGetMatrixElements_delegate>("GdipGetMatrixElements");
- GdipIsMatrixInvertible_ptr = LoadFunction<GdipIsMatrixInvertible_delegate>("GdipIsMatrixInvertible");
- GdipIsMatrixIdentity_ptr = LoadFunction<GdipIsMatrixIdentity_delegate>("GdipIsMatrixIdentity");
- GdipIsMatrixEqual_ptr = LoadFunction<GdipIsMatrixEqual_delegate>("GdipIsMatrixEqual");
- GdipCreateRegion_ptr = LoadFunction<GdipCreateRegion_delegate>("GdipCreateRegion");
- GdipCreateRegionRect_ptr = LoadFunction<GdipCreateRegionRect_delegate>("GdipCreateRegionRect");
- GdipCreateRegionRectI_ptr = LoadFunction<GdipCreateRegionRectI_delegate>("GdipCreateRegionRectI");
- GdipCreateRegionPath_ptr = LoadFunction<GdipCreateRegionPath_delegate>("GdipCreateRegionPath");
- GdipCreateRegionRgnData_ptr = LoadFunction<GdipCreateRegionRgnData_delegate>("GdipCreateRegionRgnData");
- GdipCreateRegionHrgn_ptr = LoadFunction<GdipCreateRegionHrgn_delegate>("GdipCreateRegionHrgn");
- GdipCloneRegion_ptr = LoadFunction<GdipCloneRegion_delegate>("GdipCloneRegion");
- GdipDeleteRegion_ptr = LoadFunction<GdipDeleteRegion_delegate>("GdipDeleteRegion");
- GdipFillRegion_ptr = LoadFunction<GdipFillRegion_delegate>("GdipFillRegion");
- GdipSetInfinite_ptr = LoadFunction<GdipSetInfinite_delegate>("GdipSetInfinite");
- GdipSetEmpty_ptr = LoadFunction<GdipSetEmpty_delegate>("GdipSetEmpty");
- GdipCombineRegionRect_ptr = LoadFunction<GdipCombineRegionRect_delegate>("GdipCombineRegionRect");
- GdipCombineRegionRectI_ptr = LoadFunction<GdipCombineRegionRectI_delegate>("GdipCombineRegionRectI");
- GdipCombineRegionPath_ptr = LoadFunction<GdipCombineRegionPath_delegate>("GdipCombineRegionPath");
- GdipCombineRegionRegion_ptr = LoadFunction<GdipCombineRegionRegion_delegate>("GdipCombineRegionRegion");
- GdipTranslateRegion_ptr = LoadFunction<GdipTranslateRegion_delegate>("GdipTranslateRegion");
- GdipTranslateRegionI_ptr = LoadFunction<GdipTranslateRegionI_delegate>("GdipTranslateRegionI");
- GdipTransformRegion_ptr = LoadFunction<GdipTransformRegion_delegate>("GdipTransformRegion");
- GdipGetRegionBounds_ptr = LoadFunction<GdipGetRegionBounds_delegate>("GdipGetRegionBounds");
- GdipGetRegionHRgn_ptr = LoadFunction<GdipGetRegionHRgn_delegate>("GdipGetRegionHRgn");
- GdipIsEmptyRegion_ptr = LoadFunction<GdipIsEmptyRegion_delegate>("GdipIsEmptyRegion");
- GdipIsInfiniteRegion_ptr = LoadFunction<GdipIsInfiniteRegion_delegate>("GdipIsInfiniteRegion");
- GdipIsEqualRegion_ptr = LoadFunction<GdipIsEqualRegion_delegate>("GdipIsEqualRegion");
- GdipGetRegionDataSize_ptr = LoadFunction<GdipGetRegionDataSize_delegate>("GdipGetRegionDataSize");
- GdipGetRegionData_ptr = LoadFunction<GdipGetRegionData_delegate>("GdipGetRegionData");
- GdipIsVisibleRegionPoint_ptr = LoadFunction<GdipIsVisibleRegionPoint_delegate>("GdipIsVisibleRegionPoint");
- GdipIsVisibleRegionPointI_ptr = LoadFunction<GdipIsVisibleRegionPointI_delegate>("GdipIsVisibleRegionPointI");
- GdipIsVisibleRegionRect_ptr = LoadFunction<GdipIsVisibleRegionRect_delegate>("GdipIsVisibleRegionRect");
- GdipIsVisibleRegionRectI_ptr = LoadFunction<GdipIsVisibleRegionRectI_delegate>("GdipIsVisibleRegionRectI");
- GdipGetRegionScansCount_ptr = LoadFunction<GdipGetRegionScansCount_delegate>("GdipGetRegionScansCount");
- GdipGetRegionScans_ptr = LoadFunction<GdipGetRegionScans_delegate>("GdipGetRegionScans");
- GdipSetClipGraphics_ptr = LoadFunction<GdipSetClipGraphics_delegate>("GdipSetClipGraphics");
- GdipSetClipRect_ptr = LoadFunction<GdipSetClipRect_delegate>("GdipSetClipRect");
- GdipSetClipRectI_ptr = LoadFunction<GdipSetClipRectI_delegate>("GdipSetClipRectI");
- GdipSetClipPath_ptr = LoadFunction<GdipSetClipPath_delegate>("GdipSetClipPath");
- GdipSetClipRegion_ptr = LoadFunction<GdipSetClipRegion_delegate>("GdipSetClipRegion");
- GdipResetClip_ptr = LoadFunction<GdipResetClip_delegate>("GdipResetClip");
- GdipTranslateClip_ptr = LoadFunction<GdipTranslateClip_delegate>("GdipTranslateClip");
- GdipGetClip_ptr = LoadFunction<GdipGetClip_delegate>("GdipGetClip");
- GdipGetClipBounds_ptr = LoadFunction<GdipGetClipBounds_delegate>("GdipGetClipBounds");
- GdipIsClipEmpty_ptr = LoadFunction<GdipIsClipEmpty_delegate>("GdipIsClipEmpty");
- GdipGetVisibleClipBounds_ptr = LoadFunction<GdipGetVisibleClipBounds_delegate>("GdipGetVisibleClipBounds");
- GdipIsVisibleClipEmpty_ptr = LoadFunction<GdipIsVisibleClipEmpty_delegate>("GdipIsVisibleClipEmpty");
- GdipIsVisiblePoint_ptr = LoadFunction<GdipIsVisiblePoint_delegate>("GdipIsVisiblePoint");
- GdipIsVisiblePointI_ptr = LoadFunction<GdipIsVisiblePointI_delegate>("GdipIsVisiblePointI");
- GdipIsVisibleRect_ptr = LoadFunction<GdipIsVisibleRect_delegate>("GdipIsVisibleRect");
- GdipIsVisibleRectI_ptr = LoadFunction<GdipIsVisibleRectI_delegate>("GdipIsVisibleRectI");
- GdipSetStringFormatMeasurableCharacterRanges_ptr = LoadFunction<GdipSetStringFormatMeasurableCharacterRanges_delegate>("GdipSetStringFormatMeasurableCharacterRanges");
- GdipCreateStringFormat_ptr = LoadFunction<GdipCreateStringFormat_delegate>("GdipCreateStringFormat");
- GdipStringFormatGetGenericDefault_ptr = LoadFunction<GdipStringFormatGetGenericDefault_delegate>("GdipStringFormatGetGenericDefault");
- GdipStringFormatGetGenericTypographic_ptr = LoadFunction<GdipStringFormatGetGenericTypographic_delegate>("GdipStringFormatGetGenericTypographic");
- GdipDeleteStringFormat_ptr = LoadFunction<GdipDeleteStringFormat_delegate>("GdipDeleteStringFormat");
- GdipCloneStringFormat_ptr = LoadFunction<GdipCloneStringFormat_delegate>("GdipCloneStringFormat");
- GdipSetStringFormatFlags_ptr = LoadFunction<GdipSetStringFormatFlags_delegate>("GdipSetStringFormatFlags");
- GdipGetStringFormatFlags_ptr = LoadFunction<GdipGetStringFormatFlags_delegate>("GdipGetStringFormatFlags");
- GdipSetStringFormatAlign_ptr = LoadFunction<GdipSetStringFormatAlign_delegate>("GdipSetStringFormatAlign");
- GdipGetStringFormatAlign_ptr = LoadFunction<GdipGetStringFormatAlign_delegate>("GdipGetStringFormatAlign");
- GdipSetStringFormatLineAlign_ptr = LoadFunction<GdipSetStringFormatLineAlign_delegate>("GdipSetStringFormatLineAlign");
- GdipGetStringFormatLineAlign_ptr = LoadFunction<GdipGetStringFormatLineAlign_delegate>("GdipGetStringFormatLineAlign");
- GdipSetStringFormatHotkeyPrefix_ptr = LoadFunction<GdipSetStringFormatHotkeyPrefix_delegate>("GdipSetStringFormatHotkeyPrefix");
- GdipGetStringFormatHotkeyPrefix_ptr = LoadFunction<GdipGetStringFormatHotkeyPrefix_delegate>("GdipGetStringFormatHotkeyPrefix");
- GdipSetStringFormatTabStops_ptr = LoadFunction<GdipSetStringFormatTabStops_delegate>("GdipSetStringFormatTabStops");
- GdipGetStringFormatTabStops_ptr = LoadFunction<GdipGetStringFormatTabStops_delegate>("GdipGetStringFormatTabStops");
- GdipGetStringFormatTabStopCount_ptr = LoadFunction<GdipGetStringFormatTabStopCount_delegate>("GdipGetStringFormatTabStopCount");
- GdipGetStringFormatMeasurableCharacterRangeCount_ptr = LoadFunction<GdipGetStringFormatMeasurableCharacterRangeCount_delegate>("GdipGetStringFormatMeasurableCharacterRangeCount");
- GdipSetStringFormatTrimming_ptr = LoadFunction<GdipSetStringFormatTrimming_delegate>("GdipSetStringFormatTrimming");
- GdipGetStringFormatTrimming_ptr = LoadFunction<GdipGetStringFormatTrimming_delegate>("GdipGetStringFormatTrimming");
- GdipSetStringFormatDigitSubstitution_ptr = LoadFunction<GdipSetStringFormatDigitSubstitution_delegate>("GdipSetStringFormatDigitSubstitution");
- GdipGetStringFormatDigitSubstitution_ptr = LoadFunction<GdipGetStringFormatDigitSubstitution_delegate>("GdipGetStringFormatDigitSubstitution");
+ GdipBeginContainer_ptr = FunctionWrapper.Load<GdipBeginContainer_delegate>(s_gdipModule, "GdipBeginContainer");
+ GdipBeginContainer2_ptr = FunctionWrapper.Load<GdipBeginContainer2_delegate>(s_gdipModule, "GdipBeginContainer2");
+ GdipBeginContainerI_ptr = FunctionWrapper.Load<GdipBeginContainerI_delegate>(s_gdipModule, "GdipBeginContainerI");
+ GdipEndContainer_ptr = FunctionWrapper.Load<GdipEndContainer_delegate>(s_gdipModule, "GdipEndContainer");
+ GdipCreateAdjustableArrowCap_ptr = FunctionWrapper.Load<GdipCreateAdjustableArrowCap_delegate>(s_gdipModule, "GdipCreateAdjustableArrowCap");
+ GdipGetAdjustableArrowCapHeight_ptr = FunctionWrapper.Load<GdipGetAdjustableArrowCapHeight_delegate>(s_gdipModule, "GdipGetAdjustableArrowCapHeight");
+ GdipSetAdjustableArrowCapHeight_ptr = FunctionWrapper.Load<GdipSetAdjustableArrowCapHeight_delegate>(s_gdipModule, "GdipSetAdjustableArrowCapHeight");
+ GdipSetAdjustableArrowCapWidth_ptr = FunctionWrapper.Load<GdipSetAdjustableArrowCapWidth_delegate>(s_gdipModule, "GdipSetAdjustableArrowCapWidth");
+ GdipGetAdjustableArrowCapWidth_ptr = FunctionWrapper.Load<GdipGetAdjustableArrowCapWidth_delegate>(s_gdipModule, "GdipGetAdjustableArrowCapWidth");
+ GdipSetAdjustableArrowCapMiddleInset_ptr = FunctionWrapper.Load<GdipSetAdjustableArrowCapMiddleInset_delegate>(s_gdipModule, "GdipSetAdjustableArrowCapMiddleInset");
+ GdipGetAdjustableArrowCapMiddleInset_ptr = FunctionWrapper.Load<GdipGetAdjustableArrowCapMiddleInset_delegate>(s_gdipModule, "GdipGetAdjustableArrowCapMiddleInset");
+ GdipSetAdjustableArrowCapFillState_ptr = FunctionWrapper.Load<GdipSetAdjustableArrowCapFillState_delegate>(s_gdipModule, "GdipSetAdjustableArrowCapFillState");
+ GdipGetAdjustableArrowCapFillState_ptr = FunctionWrapper.Load<GdipGetAdjustableArrowCapFillState_delegate>(s_gdipModule, "GdipGetAdjustableArrowCapFillState");
+ GdipGetCustomLineCapType_ptr = FunctionWrapper.Load<GdipGetCustomLineCapType_delegate>(s_gdipModule, "GdipGetCustomLineCapType");
+ GdipCreateCustomLineCap_ptr = FunctionWrapper.Load<GdipCreateCustomLineCap_delegate>(s_gdipModule, "GdipCreateCustomLineCap");
+ GdipDeleteCustomLineCap_ptr = FunctionWrapper.Load<GdipDeleteCustomLineCap_delegate>(s_gdipModule, "GdipDeleteCustomLineCap");
+ GdipCloneCustomLineCap_ptr = FunctionWrapper.Load<GdipCloneCustomLineCap_delegate>(s_gdipModule, "GdipCloneCustomLineCap");
+ GdipSetCustomLineCapStrokeCaps_ptr = FunctionWrapper.Load<GdipSetCustomLineCapStrokeCaps_delegate>(s_gdipModule, "GdipSetCustomLineCapStrokeCaps");
+ GdipGetCustomLineCapStrokeCaps_ptr = FunctionWrapper.Load<GdipGetCustomLineCapStrokeCaps_delegate>(s_gdipModule, "GdipGetCustomLineCapStrokeCaps");
+ GdipSetCustomLineCapStrokeJoin_ptr = FunctionWrapper.Load<GdipSetCustomLineCapStrokeJoin_delegate>(s_gdipModule, "GdipSetCustomLineCapStrokeJoin");
+ GdipGetCustomLineCapStrokeJoin_ptr = FunctionWrapper.Load<GdipGetCustomLineCapStrokeJoin_delegate>(s_gdipModule, "GdipGetCustomLineCapStrokeJoin");
+ GdipSetCustomLineCapBaseCap_ptr = FunctionWrapper.Load<GdipSetCustomLineCapBaseCap_delegate>(s_gdipModule, "GdipSetCustomLineCapBaseCap");
+ GdipGetCustomLineCapBaseCap_ptr = FunctionWrapper.Load<GdipGetCustomLineCapBaseCap_delegate>(s_gdipModule, "GdipGetCustomLineCapBaseCap");
+ GdipSetCustomLineCapBaseInset_ptr = FunctionWrapper.Load<GdipSetCustomLineCapBaseInset_delegate>(s_gdipModule, "GdipSetCustomLineCapBaseInset");
+ GdipGetCustomLineCapBaseInset_ptr = FunctionWrapper.Load<GdipGetCustomLineCapBaseInset_delegate>(s_gdipModule, "GdipGetCustomLineCapBaseInset");
+ GdipSetCustomLineCapWidthScale_ptr = FunctionWrapper.Load<GdipSetCustomLineCapWidthScale_delegate>(s_gdipModule, "GdipSetCustomLineCapWidthScale");
+ GdipGetCustomLineCapWidthScale_ptr = FunctionWrapper.Load<GdipGetCustomLineCapWidthScale_delegate>(s_gdipModule, "GdipGetCustomLineCapWidthScale");
+ GdipCreatePathIter_ptr = FunctionWrapper.Load<GdipCreatePathIter_delegate>(s_gdipModule, "GdipCreatePathIter");
+ GdipDeletePathIter_ptr = FunctionWrapper.Load<GdipDeletePathIter_delegate>(s_gdipModule, "GdipDeletePathIter");
+ GdipPathIterNextSubpath_ptr = FunctionWrapper.Load<GdipPathIterNextSubpath_delegate>(s_gdipModule, "GdipPathIterNextSubpath");
+ GdipPathIterNextSubpathPath_ptr = FunctionWrapper.Load<GdipPathIterNextSubpathPath_delegate>(s_gdipModule, "GdipPathIterNextSubpathPath");
+ GdipPathIterNextPathType_ptr = FunctionWrapper.Load<GdipPathIterNextPathType_delegate>(s_gdipModule, "GdipPathIterNextPathType");
+ GdipPathIterNextMarker_ptr = FunctionWrapper.Load<GdipPathIterNextMarker_delegate>(s_gdipModule, "GdipPathIterNextMarker");
+ GdipPathIterNextMarkerPath_ptr = FunctionWrapper.Load<GdipPathIterNextMarkerPath_delegate>(s_gdipModule, "GdipPathIterNextMarkerPath");
+ GdipPathIterGetCount_ptr = FunctionWrapper.Load<GdipPathIterGetCount_delegate>(s_gdipModule, "GdipPathIterGetCount");
+ GdipPathIterGetSubpathCount_ptr = FunctionWrapper.Load<GdipPathIterGetSubpathCount_delegate>(s_gdipModule, "GdipPathIterGetSubpathCount");
+ GdipPathIterHasCurve_ptr = FunctionWrapper.Load<GdipPathIterHasCurve_delegate>(s_gdipModule, "GdipPathIterHasCurve");
+ GdipPathIterRewind_ptr = FunctionWrapper.Load<GdipPathIterRewind_delegate>(s_gdipModule, "GdipPathIterRewind");
+ GdipPathIterEnumerate_ptr = FunctionWrapper.Load<GdipPathIterEnumerate_delegate>(s_gdipModule, "GdipPathIterEnumerate");
+ GdipPathIterCopyData_ptr = FunctionWrapper.Load<GdipPathIterCopyData_delegate>(s_gdipModule, "GdipPathIterCopyData");
+ GdipCreateHatchBrush_ptr = FunctionWrapper.Load<GdipCreateHatchBrush_delegate>(s_gdipModule, "GdipCreateHatchBrush");
+ GdipGetHatchStyle_ptr = FunctionWrapper.Load<GdipGetHatchStyle_delegate>(s_gdipModule, "GdipGetHatchStyle");
+ GdipGetHatchForegroundColor_ptr = FunctionWrapper.Load<GdipGetHatchForegroundColor_delegate>(s_gdipModule, "GdipGetHatchForegroundColor");
+ GdipGetHatchBackgroundColor_ptr = FunctionWrapper.Load<GdipGetHatchBackgroundColor_delegate>(s_gdipModule, "GdipGetHatchBackgroundColor");
+ GdipCreateLineBrush_ptr = FunctionWrapper.Load<GdipCreateLineBrush_delegate>(s_gdipModule, "GdipCreateLineBrush");
+ GdipCreateLineBrushI_ptr = FunctionWrapper.Load<GdipCreateLineBrushI_delegate>(s_gdipModule, "GdipCreateLineBrushI");
+ GdipCreateLineBrushFromRect_ptr = FunctionWrapper.Load<GdipCreateLineBrushFromRect_delegate>(s_gdipModule, "GdipCreateLineBrushFromRect");
+ GdipCreateLineBrushFromRectI_ptr = FunctionWrapper.Load<GdipCreateLineBrushFromRectI_delegate>(s_gdipModule, "GdipCreateLineBrushFromRectI");
+ GdipCreateLineBrushFromRectWithAngle_ptr = FunctionWrapper.Load<GdipCreateLineBrushFromRectWithAngle_delegate>(s_gdipModule, "GdipCreateLineBrushFromRectWithAngle");
+ GdipCreateLineBrushFromRectWithAngleI_ptr = FunctionWrapper.Load<GdipCreateLineBrushFromRectWithAngleI_delegate>(s_gdipModule, "GdipCreateLineBrushFromRectWithAngleI");
+ GdipSetLineColors_ptr = FunctionWrapper.Load<GdipSetLineColors_delegate>(s_gdipModule, "GdipSetLineColors");
+ GdipGetLineColors_ptr = FunctionWrapper.Load<GdipGetLineColors_delegate>(s_gdipModule, "GdipGetLineColors");
+ GdipGetLineRect_ptr = FunctionWrapper.Load<GdipGetLineRect_delegate>(s_gdipModule, "GdipGetLineRect");
+ GdipGetLineGammaCorrection_ptr = FunctionWrapper.Load<GdipGetLineGammaCorrection_delegate>(s_gdipModule, "GdipGetLineGammaCorrection");
+ GdipSetLineGammaCorrection_ptr = FunctionWrapper.Load<GdipSetLineGammaCorrection_delegate>(s_gdipModule, "GdipSetLineGammaCorrection");
+ GdipSetLineSigmaBlend_ptr = FunctionWrapper.Load<GdipSetLineSigmaBlend_delegate>(s_gdipModule, "GdipSetLineSigmaBlend");
+ GdipSetLineLinearBlend_ptr = FunctionWrapper.Load<GdipSetLineLinearBlend_delegate>(s_gdipModule, "GdipSetLineLinearBlend");
+ GdipGetLineBlendCount_ptr = FunctionWrapper.Load<GdipGetLineBlendCount_delegate>(s_gdipModule, "GdipGetLineBlendCount");
+ GdipGetLineBlend_ptr = FunctionWrapper.Load<GdipGetLineBlend_delegate>(s_gdipModule, "GdipGetLineBlend");
+ GdipSetLineBlend_ptr = FunctionWrapper.Load<GdipSetLineBlend_delegate>(s_gdipModule, "GdipSetLineBlend");
+ GdipGetLinePresetBlendCount_ptr = FunctionWrapper.Load<GdipGetLinePresetBlendCount_delegate>(s_gdipModule, "GdipGetLinePresetBlendCount");
+ GdipGetLinePresetBlend_ptr = FunctionWrapper.Load<GdipGetLinePresetBlend_delegate>(s_gdipModule, "GdipGetLinePresetBlend");
+ GdipSetLinePresetBlend_ptr = FunctionWrapper.Load<GdipSetLinePresetBlend_delegate>(s_gdipModule, "GdipSetLinePresetBlend");
+ GdipSetLineWrapMode_ptr = FunctionWrapper.Load<GdipSetLineWrapMode_delegate>(s_gdipModule, "GdipSetLineWrapMode");
+ GdipGetLineWrapMode_ptr = FunctionWrapper.Load<GdipGetLineWrapMode_delegate>(s_gdipModule, "GdipGetLineWrapMode");
+ GdipResetLineTransform_ptr = FunctionWrapper.Load<GdipResetLineTransform_delegate>(s_gdipModule, "GdipResetLineTransform");
+ GdipMultiplyLineTransform_ptr = FunctionWrapper.Load<GdipMultiplyLineTransform_delegate>(s_gdipModule, "GdipMultiplyLineTransform");
+ GdipGetLineTransform_ptr = FunctionWrapper.Load<GdipGetLineTransform_delegate>(s_gdipModule, "GdipGetLineTransform");
+ GdipSetLineTransform_ptr = FunctionWrapper.Load<GdipSetLineTransform_delegate>(s_gdipModule, "GdipSetLineTransform");
+ GdipTranslateLineTransform_ptr = FunctionWrapper.Load<GdipTranslateLineTransform_delegate>(s_gdipModule, "GdipTranslateLineTransform");
+ GdipScaleLineTransform_ptr = FunctionWrapper.Load<GdipScaleLineTransform_delegate>(s_gdipModule, "GdipScaleLineTransform");
+ GdipRotateLineTransform_ptr = FunctionWrapper.Load<GdipRotateLineTransform_delegate>(s_gdipModule, "GdipRotateLineTransform");
+ GdipCreatePathGradient_ptr = FunctionWrapper.Load<GdipCreatePathGradient_delegate>(s_gdipModule, "GdipCreatePathGradient");
+ GdipCreatePathGradientI_ptr = FunctionWrapper.Load<GdipCreatePathGradientI_delegate>(s_gdipModule, "GdipCreatePathGradientI");
+ GdipCreatePathGradientFromPath_ptr = FunctionWrapper.Load<GdipCreatePathGradientFromPath_delegate>(s_gdipModule, "GdipCreatePathGradientFromPath");
+ GdipGetPathGradientCenterColor_ptr = FunctionWrapper.Load<GdipGetPathGradientCenterColor_delegate>(s_gdipModule, "GdipGetPathGradientCenterColor");
+ GdipSetPathGradientCenterColor_ptr = FunctionWrapper.Load<GdipSetPathGradientCenterColor_delegate>(s_gdipModule, "GdipSetPathGradientCenterColor");
+ GdipGetPathGradientSurroundColorsWithCount_ptr = FunctionWrapper.Load<GdipGetPathGradientSurroundColorsWithCount_delegate>(s_gdipModule, "GdipGetPathGradientSurroundColorsWithCount");
+ GdipSetPathGradientSurroundColorsWithCount_ptr = FunctionWrapper.Load<GdipSetPathGradientSurroundColorsWithCount_delegate>(s_gdipModule, "GdipSetPathGradientSurroundColorsWithCount");
+ GdipGetPathGradientCenterPoint_ptr = FunctionWrapper.Load<GdipGetPathGradientCenterPoint_delegate>(s_gdipModule, "GdipGetPathGradientCenterPoint");
+ GdipSetPathGradientCenterPoint_ptr = FunctionWrapper.Load<GdipSetPathGradientCenterPoint_delegate>(s_gdipModule, "GdipSetPathGradientCenterPoint");
+ GdipGetPathGradientRect_ptr = FunctionWrapper.Load<GdipGetPathGradientRect_delegate>(s_gdipModule, "GdipGetPathGradientRect");
+ GdipGetPathGradientPointCount_ptr = FunctionWrapper.Load<GdipGetPathGradientPointCount_delegate>(s_gdipModule, "GdipGetPathGradientPointCount");
+ GdipGetPathGradientSurroundColorCount_ptr = FunctionWrapper.Load<GdipGetPathGradientSurroundColorCount_delegate>(s_gdipModule, "GdipGetPathGradientSurroundColorCount");
+ GdipGetPathGradientBlendCount_ptr = FunctionWrapper.Load<GdipGetPathGradientBlendCount_delegate>(s_gdipModule, "GdipGetPathGradientBlendCount");
+ GdipGetPathGradientBlend_ptr = FunctionWrapper.Load<GdipGetPathGradientBlend_delegate>(s_gdipModule, "GdipGetPathGradientBlend");
+ GdipSetPathGradientBlend_ptr = FunctionWrapper.Load<GdipSetPathGradientBlend_delegate>(s_gdipModule, "GdipSetPathGradientBlend");
+ GdipGetPathGradientPresetBlendCount_ptr = FunctionWrapper.Load<GdipGetPathGradientPresetBlendCount_delegate>(s_gdipModule, "GdipGetPathGradientPresetBlendCount");
+ GdipGetPathGradientPresetBlend_ptr = FunctionWrapper.Load<GdipGetPathGradientPresetBlend_delegate>(s_gdipModule, "GdipGetPathGradientPresetBlend");
+ GdipSetPathGradientPresetBlend_ptr = FunctionWrapper.Load<GdipSetPathGradientPresetBlend_delegate>(s_gdipModule, "GdipSetPathGradientPresetBlend");
+ GdipSetPathGradientSigmaBlend_ptr = FunctionWrapper.Load<GdipSetPathGradientSigmaBlend_delegate>(s_gdipModule, "GdipSetPathGradientSigmaBlend");
+ GdipSetPathGradientLinearBlend_ptr = FunctionWrapper.Load<GdipSetPathGradientLinearBlend_delegate>(s_gdipModule, "GdipSetPathGradientLinearBlend");
+ GdipSetPathGradientWrapMode_ptr = FunctionWrapper.Load<GdipSetPathGradientWrapMode_delegate>(s_gdipModule, "GdipSetPathGradientWrapMode");
+ GdipGetPathGradientWrapMode_ptr = FunctionWrapper.Load<GdipGetPathGradientWrapMode_delegate>(s_gdipModule, "GdipGetPathGradientWrapMode");
+ GdipSetPathGradientTransform_ptr = FunctionWrapper.Load<GdipSetPathGradientTransform_delegate>(s_gdipModule, "GdipSetPathGradientTransform");
+ GdipGetPathGradientTransform_ptr = FunctionWrapper.Load<GdipGetPathGradientTransform_delegate>(s_gdipModule, "GdipGetPathGradientTransform");
+ GdipResetPathGradientTransform_ptr = FunctionWrapper.Load<GdipResetPathGradientTransform_delegate>(s_gdipModule, "GdipResetPathGradientTransform");
+ GdipMultiplyPathGradientTransform_ptr = FunctionWrapper.Load<GdipMultiplyPathGradientTransform_delegate>(s_gdipModule, "GdipMultiplyPathGradientTransform");
+ GdipTranslatePathGradientTransform_ptr = FunctionWrapper.Load<GdipTranslatePathGradientTransform_delegate>(s_gdipModule, "GdipTranslatePathGradientTransform");
+ GdipScalePathGradientTransform_ptr = FunctionWrapper.Load<GdipScalePathGradientTransform_delegate>(s_gdipModule, "GdipScalePathGradientTransform");
+ GdipRotatePathGradientTransform_ptr = FunctionWrapper.Load<GdipRotatePathGradientTransform_delegate>(s_gdipModule, "GdipRotatePathGradientTransform");
+ GdipGetPathGradientFocusScales_ptr = FunctionWrapper.Load<GdipGetPathGradientFocusScales_delegate>(s_gdipModule, "GdipGetPathGradientFocusScales");
+ GdipSetPathGradientFocusScales_ptr = FunctionWrapper.Load<GdipSetPathGradientFocusScales_delegate>(s_gdipModule, "GdipSetPathGradientFocusScales");
+ GdipCloneBrush_ptr = FunctionWrapper.Load<GdipCloneBrush_delegate>(s_gdipModule, "GdipCloneBrush");
+ GdipCreateImageAttributes_ptr = FunctionWrapper.Load<GdipCreateImageAttributes_delegate>(s_gdipModule, "GdipCreateImageAttributes");
+ GdipCloneImageAttributes_ptr = FunctionWrapper.Load<GdipCloneImageAttributes_delegate>(s_gdipModule, "GdipCloneImageAttributes");
+ GdipDisposeImageAttributes_ptr = FunctionWrapper.Load<GdipDisposeImageAttributes_delegate>(s_gdipModule, "GdipDisposeImageAttributes");
+ GdipSetImageAttributesColorMatrix_ptr = FunctionWrapper.Load<GdipSetImageAttributesColorMatrix_delegate>(s_gdipModule, "GdipSetImageAttributesColorMatrix");
+ GdipSetImageAttributesThreshold_ptr = FunctionWrapper.Load<GdipSetImageAttributesThreshold_delegate>(s_gdipModule, "GdipSetImageAttributesThreshold");
+ GdipSetImageAttributesGamma_ptr = FunctionWrapper.Load<GdipSetImageAttributesGamma_delegate>(s_gdipModule, "GdipSetImageAttributesGamma");
+ GdipSetImageAttributesNoOp_ptr = FunctionWrapper.Load<GdipSetImageAttributesNoOp_delegate>(s_gdipModule, "GdipSetImageAttributesNoOp");
+ GdipSetImageAttributesColorKeys_ptr = FunctionWrapper.Load<GdipSetImageAttributesColorKeys_delegate>(s_gdipModule, "GdipSetImageAttributesColorKeys");
+ GdipSetImageAttributesOutputChannel_ptr = FunctionWrapper.Load<GdipSetImageAttributesOutputChannel_delegate>(s_gdipModule, "GdipSetImageAttributesOutputChannel");
+ GdipSetImageAttributesOutputChannelColorProfile_ptr = FunctionWrapper.Load<GdipSetImageAttributesOutputChannelColorProfile_delegate>(s_gdipModule, "GdipSetImageAttributesOutputChannelColorProfile");
+ GdipSetImageAttributesRemapTable_ptr = FunctionWrapper.Load<GdipSetImageAttributesRemapTable_delegate>(s_gdipModule, "GdipSetImageAttributesRemapTable");
+ GdipSetImageAttributesWrapMode_ptr = FunctionWrapper.Load<GdipSetImageAttributesWrapMode_delegate>(s_gdipModule, "GdipSetImageAttributesWrapMode");
+ GdipGetImageAttributesAdjustedPalette_ptr = FunctionWrapper.Load<GdipGetImageAttributesAdjustedPalette_delegate>(s_gdipModule, "GdipGetImageAttributesAdjustedPalette");
+ GdipGetImageDecodersSize_ptr = FunctionWrapper.Load<GdipGetImageDecodersSize_delegate>(s_gdipModule, "GdipGetImageDecodersSize");
+ GdipGetImageDecoders_ptr = FunctionWrapper.Load<GdipGetImageDecoders_delegate>(s_gdipModule, "GdipGetImageDecoders");
+ GdipGetImageEncodersSize_ptr = FunctionWrapper.Load<GdipGetImageEncodersSize_delegate>(s_gdipModule, "GdipGetImageEncodersSize");
+ GdipGetImageEncoders_ptr = FunctionWrapper.Load<GdipGetImageEncoders_delegate>(s_gdipModule, "GdipGetImageEncoders");
+ GdipCreateSolidFill_ptr = FunctionWrapper.Load<GdipCreateSolidFill_delegate>(s_gdipModule, "GdipCreateSolidFill");
+ GdipSetSolidFillColor_ptr = FunctionWrapper.Load<GdipSetSolidFillColor_delegate>(s_gdipModule, "GdipSetSolidFillColor");
+ GdipGetSolidFillColor_ptr = FunctionWrapper.Load<GdipGetSolidFillColor_delegate>(s_gdipModule, "GdipGetSolidFillColor");
+ GdipCreateTexture_ptr = FunctionWrapper.Load<GdipCreateTexture_delegate>(s_gdipModule, "GdipCreateTexture");
+ GdipCreateTexture2_ptr = FunctionWrapper.Load<GdipCreateTexture2_delegate>(s_gdipModule, "GdipCreateTexture2");
+ GdipCreateTextureIA_ptr = FunctionWrapper.Load<GdipCreateTextureIA_delegate>(s_gdipModule, "GdipCreateTextureIA");
+ GdipCreateTexture2I_ptr = FunctionWrapper.Load<GdipCreateTexture2I_delegate>(s_gdipModule, "GdipCreateTexture2I");
+ GdipCreateTextureIAI_ptr = FunctionWrapper.Load<GdipCreateTextureIAI_delegate>(s_gdipModule, "GdipCreateTextureIAI");
+ GdipSetTextureTransform_ptr = FunctionWrapper.Load<GdipSetTextureTransform_delegate>(s_gdipModule, "GdipSetTextureTransform");
+ GdipGetTextureTransform_ptr = FunctionWrapper.Load<GdipGetTextureTransform_delegate>(s_gdipModule, "GdipGetTextureTransform");
+ GdipResetTextureTransform_ptr = FunctionWrapper.Load<GdipResetTextureTransform_delegate>(s_gdipModule, "GdipResetTextureTransform");
+ GdipMultiplyTextureTransform_ptr = FunctionWrapper.Load<GdipMultiplyTextureTransform_delegate>(s_gdipModule, "GdipMultiplyTextureTransform");
+ GdipTranslateTextureTransform_ptr = FunctionWrapper.Load<GdipTranslateTextureTransform_delegate>(s_gdipModule, "GdipTranslateTextureTransform");
+ GdipScaleTextureTransform_ptr = FunctionWrapper.Load<GdipScaleTextureTransform_delegate>(s_gdipModule, "GdipScaleTextureTransform");
+ GdipRotateTextureTransform_ptr = FunctionWrapper.Load<GdipRotateTextureTransform_delegate>(s_gdipModule, "GdipRotateTextureTransform");
+ GdipSetTextureWrapMode_ptr = FunctionWrapper.Load<GdipSetTextureWrapMode_delegate>(s_gdipModule, "GdipSetTextureWrapMode");
+ GdipGetTextureWrapMode_ptr = FunctionWrapper.Load<GdipGetTextureWrapMode_delegate>(s_gdipModule, "GdipGetTextureWrapMode");
+ GdipGetTextureImage_ptr = FunctionWrapper.Load<GdipGetTextureImage_delegate>(s_gdipModule, "GdipGetTextureImage");
+ GdipGetFontCollectionFamilyCount_ptr = FunctionWrapper.Load<GdipGetFontCollectionFamilyCount_delegate>(s_gdipModule, "GdipGetFontCollectionFamilyCount");
+ GdipGetFontCollectionFamilyList_ptr = FunctionWrapper.Load<GdipGetFontCollectionFamilyList_delegate>(s_gdipModule, "GdipGetFontCollectionFamilyList");
+ GdipCloneFontFamily_ptr = FunctionWrapper.Load<GdipCloneFontFamily_delegate>(s_gdipModule, "GdipCloneFontFamily");
+ GdipCreateFontFamilyFromName_ptr = FunctionWrapper.Load<GdipCreateFontFamilyFromName_delegate>(s_gdipModule, "GdipCreateFontFamilyFromName");
+ GdipGetGenericFontFamilySansSerif_ptr = FunctionWrapper.Load<GdipGetGenericFontFamilySansSerif_delegate>(s_gdipModule, "GdipGetGenericFontFamilySansSerif");
+ GdipGetGenericFontFamilySerif_ptr = FunctionWrapper.Load<GdipGetGenericFontFamilySerif_delegate>(s_gdipModule, "GdipGetGenericFontFamilySerif");
+ GdipGetGenericFontFamilyMonospace_ptr = FunctionWrapper.Load<GdipGetGenericFontFamilyMonospace_delegate>(s_gdipModule, "GdipGetGenericFontFamilyMonospace");
+ GdipDeleteFontFamily_ptr = FunctionWrapper.Load<GdipDeleteFontFamily_delegate>(s_gdipModule, "GdipDeleteFontFamily");
+ GdipGetFamilyName_ptr = FunctionWrapper.Load<GdipGetFamilyName_delegate>(s_gdipModule, "GdipGetFamilyName");
+ GdipIsStyleAvailable_ptr = FunctionWrapper.Load<GdipIsStyleAvailable_delegate>(s_gdipModule, "GdipIsStyleAvailable");
+ GdipGetEmHeight_ptr = FunctionWrapper.Load<GdipGetEmHeight_delegate>(s_gdipModule, "GdipGetEmHeight");
+ GdipGetCellAscent_ptr = FunctionWrapper.Load<GdipGetCellAscent_delegate>(s_gdipModule, "GdipGetCellAscent");
+ GdipGetCellDescent_ptr = FunctionWrapper.Load<GdipGetCellDescent_delegate>(s_gdipModule, "GdipGetCellDescent");
+ GdipGetLineSpacing_ptr = FunctionWrapper.Load<GdipGetLineSpacing_delegate>(s_gdipModule, "GdipGetLineSpacing");
+ GdipNewInstalledFontCollection_ptr = FunctionWrapper.Load<GdipNewInstalledFontCollection_delegate>(s_gdipModule, "GdipNewInstalledFontCollection");
+ GdipNewPrivateFontCollection_ptr = FunctionWrapper.Load<GdipNewPrivateFontCollection_delegate>(s_gdipModule, "GdipNewPrivateFontCollection");
+ GdipDeletePrivateFontCollection_ptr = FunctionWrapper.Load<GdipDeletePrivateFontCollection_delegate>(s_gdipModule, "GdipDeletePrivateFontCollection");
+ GdipPrivateAddFontFile_ptr = FunctionWrapper.Load<GdipPrivateAddFontFile_delegate>(s_gdipModule, "GdipPrivateAddFontFile");
+ GdipPrivateAddMemoryFont_ptr = FunctionWrapper.Load<GdipPrivateAddMemoryFont_delegate>(s_gdipModule, "GdipPrivateAddMemoryFont");
+ GdipCreatePen1_ptr = FunctionWrapper.Load<GdipCreatePen1_delegate>(s_gdipModule, "GdipCreatePen1");
+ GdipCreatePen2_ptr = FunctionWrapper.Load<GdipCreatePen2_delegate>(s_gdipModule, "GdipCreatePen2");
+ GdipClonePen_ptr = FunctionWrapper.Load<GdipClonePen_delegate>(s_gdipModule, "GdipClonePen");
+ GdipDeletePen_ptr = FunctionWrapper.Load<GdipDeletePen_delegate>(s_gdipModule, "GdipDeletePen");
+ GdipSetPenMode_ptr = FunctionWrapper.Load<GdipSetPenMode_delegate>(s_gdipModule, "GdipSetPenMode");
+ GdipGetPenMode_ptr = FunctionWrapper.Load<GdipGetPenMode_delegate>(s_gdipModule, "GdipGetPenMode");
+ GdipSetPenWidth_ptr = FunctionWrapper.Load<GdipSetPenWidth_delegate>(s_gdipModule, "GdipSetPenWidth");
+ GdipGetPenWidth_ptr = FunctionWrapper.Load<GdipGetPenWidth_delegate>(s_gdipModule, "GdipGetPenWidth");
+ GdipSetPenLineCap197819_ptr = FunctionWrapper.Load<GdipSetPenLineCap197819_delegate>(s_gdipModule, "GdipSetPenLineCap197819");
+ GdipSetPenStartCap_ptr = FunctionWrapper.Load<GdipSetPenStartCap_delegate>(s_gdipModule, "GdipSetPenStartCap");
+ GdipSetPenEndCap_ptr = FunctionWrapper.Load<GdipSetPenEndCap_delegate>(s_gdipModule, "GdipSetPenEndCap");
+ GdipGetPenStartCap_ptr = FunctionWrapper.Load<GdipGetPenStartCap_delegate>(s_gdipModule, "GdipGetPenStartCap");
+ GdipGetPenEndCap_ptr = FunctionWrapper.Load<GdipGetPenEndCap_delegate>(s_gdipModule, "GdipGetPenEndCap");
+ GdipGetPenDashCap197819_ptr = FunctionWrapper.Load<GdipGetPenDashCap197819_delegate>(s_gdipModule, "GdipGetPenDashCap197819");
+ GdipSetPenDashCap197819_ptr = FunctionWrapper.Load<GdipSetPenDashCap197819_delegate>(s_gdipModule, "GdipSetPenDashCap197819");
+ GdipSetPenLineJoin_ptr = FunctionWrapper.Load<GdipSetPenLineJoin_delegate>(s_gdipModule, "GdipSetPenLineJoin");
+ GdipGetPenLineJoin_ptr = FunctionWrapper.Load<GdipGetPenLineJoin_delegate>(s_gdipModule, "GdipGetPenLineJoin");
+ GdipSetPenCustomStartCap_ptr = FunctionWrapper.Load<GdipSetPenCustomStartCap_delegate>(s_gdipModule, "GdipSetPenCustomStartCap");
+ GdipGetPenCustomStartCap_ptr = FunctionWrapper.Load<GdipGetPenCustomStartCap_delegate>(s_gdipModule, "GdipGetPenCustomStartCap");
+ GdipSetPenCustomEndCap_ptr = FunctionWrapper.Load<GdipSetPenCustomEndCap_delegate>(s_gdipModule, "GdipSetPenCustomEndCap");
+ GdipGetPenCustomEndCap_ptr = FunctionWrapper.Load<GdipGetPenCustomEndCap_delegate>(s_gdipModule, "GdipGetPenCustomEndCap");
+ GdipSetPenMiterLimit_ptr = FunctionWrapper.Load<GdipSetPenMiterLimit_delegate>(s_gdipModule, "GdipSetPenMiterLimit");
+ GdipGetPenMiterLimit_ptr = FunctionWrapper.Load<GdipGetPenMiterLimit_delegate>(s_gdipModule, "GdipGetPenMiterLimit");
+ GdipSetPenTransform_ptr = FunctionWrapper.Load<GdipSetPenTransform_delegate>(s_gdipModule, "GdipSetPenTransform");
+ GdipGetPenTransform_ptr = FunctionWrapper.Load<GdipGetPenTransform_delegate>(s_gdipModule, "GdipGetPenTransform");
+ GdipResetPenTransform_ptr = FunctionWrapper.Load<GdipResetPenTransform_delegate>(s_gdipModule, "GdipResetPenTransform");
+ GdipMultiplyPenTransform_ptr = FunctionWrapper.Load<GdipMultiplyPenTransform_delegate>(s_gdipModule, "GdipMultiplyPenTransform");
+ GdipTranslatePenTransform_ptr = FunctionWrapper.Load<GdipTranslatePenTransform_delegate>(s_gdipModule, "GdipTranslatePenTransform");
+ GdipScalePenTransform_ptr = FunctionWrapper.Load<GdipScalePenTransform_delegate>(s_gdipModule, "GdipScalePenTransform");
+ GdipRotatePenTransform_ptr = FunctionWrapper.Load<GdipRotatePenTransform_delegate>(s_gdipModule, "GdipRotatePenTransform");
+ GdipSetPenColor_ptr = FunctionWrapper.Load<GdipSetPenColor_delegate>(s_gdipModule, "GdipSetPenColor");
+ GdipGetPenColor_ptr = FunctionWrapper.Load<GdipGetPenColor_delegate>(s_gdipModule, "GdipGetPenColor");
+ GdipSetPenBrushFill_ptr = FunctionWrapper.Load<GdipSetPenBrushFill_delegate>(s_gdipModule, "GdipSetPenBrushFill");
+ GdipGetPenBrushFill_ptr = FunctionWrapper.Load<GdipGetPenBrushFill_delegate>(s_gdipModule, "GdipGetPenBrushFill");
+ GdipGetPenFillType_ptr = FunctionWrapper.Load<GdipGetPenFillType_delegate>(s_gdipModule, "GdipGetPenFillType");
+ GdipGetPenDashStyle_ptr = FunctionWrapper.Load<GdipGetPenDashStyle_delegate>(s_gdipModule, "GdipGetPenDashStyle");
+ GdipSetPenDashStyle_ptr = FunctionWrapper.Load<GdipSetPenDashStyle_delegate>(s_gdipModule, "GdipSetPenDashStyle");
+ GdipSetPenDashArray_ptr = FunctionWrapper.Load<GdipSetPenDashArray_delegate>(s_gdipModule, "GdipSetPenDashArray");
+ GdipGetPenDashOffset_ptr = FunctionWrapper.Load<GdipGetPenDashOffset_delegate>(s_gdipModule, "GdipGetPenDashOffset");
+ GdipSetPenDashOffset_ptr = FunctionWrapper.Load<GdipSetPenDashOffset_delegate>(s_gdipModule, "GdipSetPenDashOffset");
+ GdipGetPenDashCount_ptr = FunctionWrapper.Load<GdipGetPenDashCount_delegate>(s_gdipModule, "GdipGetPenDashCount");
+ GdipGetPenDashArray_ptr = FunctionWrapper.Load<GdipGetPenDashArray_delegate>(s_gdipModule, "GdipGetPenDashArray");
+ GdipGetPenCompoundCount_ptr = FunctionWrapper.Load<GdipGetPenCompoundCount_delegate>(s_gdipModule, "GdipGetPenCompoundCount");
+ GdipSetPenCompoundArray_ptr = FunctionWrapper.Load<GdipSetPenCompoundArray_delegate>(s_gdipModule, "GdipSetPenCompoundArray");
+ GdipGetPenCompoundArray_ptr = FunctionWrapper.Load<GdipGetPenCompoundArray_delegate>(s_gdipModule, "GdipGetPenCompoundArray");
+ GdipSetWorldTransform_ptr = FunctionWrapper.Load<GdipSetWorldTransform_delegate>(s_gdipModule, "GdipSetWorldTransform");
+ GdipResetWorldTransform_ptr = FunctionWrapper.Load<GdipResetWorldTransform_delegate>(s_gdipModule, "GdipResetWorldTransform");
+ GdipMultiplyWorldTransform_ptr = FunctionWrapper.Load<GdipMultiplyWorldTransform_delegate>(s_gdipModule, "GdipMultiplyWorldTransform");
+ GdipTranslateWorldTransform_ptr = FunctionWrapper.Load<GdipTranslateWorldTransform_delegate>(s_gdipModule, "GdipTranslateWorldTransform");
+ GdipScaleWorldTransform_ptr = FunctionWrapper.Load<GdipScaleWorldTransform_delegate>(s_gdipModule, "GdipScaleWorldTransform");
+ GdipRotateWorldTransform_ptr = FunctionWrapper.Load<GdipRotateWorldTransform_delegate>(s_gdipModule, "GdipRotateWorldTransform");
+ GdipGetWorldTransform_ptr = FunctionWrapper.Load<GdipGetWorldTransform_delegate>(s_gdipModule, "GdipGetWorldTransform");
+ GdipCreateMatrix_ptr = FunctionWrapper.Load<GdipCreateMatrix_delegate>(s_gdipModule, "GdipCreateMatrix");
+ GdipCreateMatrix2_ptr = FunctionWrapper.Load<GdipCreateMatrix2_delegate>(s_gdipModule, "GdipCreateMatrix2");
+ GdipCreateMatrix3_ptr = FunctionWrapper.Load<GdipCreateMatrix3_delegate>(s_gdipModule, "GdipCreateMatrix3");
+ GdipCreateMatrix3I_ptr = FunctionWrapper.Load<GdipCreateMatrix3I_delegate>(s_gdipModule, "GdipCreateMatrix3I");
+ GdipCloneMatrix_ptr = FunctionWrapper.Load<GdipCloneMatrix_delegate>(s_gdipModule, "GdipCloneMatrix");
+ GdipDeleteMatrix_ptr = FunctionWrapper.Load<GdipDeleteMatrix_delegate>(s_gdipModule, "GdipDeleteMatrix");
+ GdipSetMatrixElements_ptr = FunctionWrapper.Load<GdipSetMatrixElements_delegate>(s_gdipModule, "GdipSetMatrixElements");
+ GdipMultiplyMatrix_ptr = FunctionWrapper.Load<GdipMultiplyMatrix_delegate>(s_gdipModule, "GdipMultiplyMatrix");
+ GdipTranslateMatrix_ptr = FunctionWrapper.Load<GdipTranslateMatrix_delegate>(s_gdipModule, "GdipTranslateMatrix");
+ GdipScaleMatrix_ptr = FunctionWrapper.Load<GdipScaleMatrix_delegate>(s_gdipModule, "GdipScaleMatrix");
+ GdipRotateMatrix_ptr = FunctionWrapper.Load<GdipRotateMatrix_delegate>(s_gdipModule, "GdipRotateMatrix");
+ GdipShearMatrix_ptr = FunctionWrapper.Load<GdipShearMatrix_delegate>(s_gdipModule, "GdipShearMatrix");
+ GdipInvertMatrix_ptr = FunctionWrapper.Load<GdipInvertMatrix_delegate>(s_gdipModule, "GdipInvertMatrix");
+ GdipTransformMatrixPoints_ptr = FunctionWrapper.Load<GdipTransformMatrixPoints_delegate>(s_gdipModule, "GdipTransformMatrixPoints");
+ GdipTransformMatrixPointsI_ptr = FunctionWrapper.Load<GdipTransformMatrixPointsI_delegate>(s_gdipModule, "GdipTransformMatrixPointsI");
+ GdipVectorTransformMatrixPoints_ptr = FunctionWrapper.Load<GdipVectorTransformMatrixPoints_delegate>(s_gdipModule, "GdipVectorTransformMatrixPoints");
+ GdipVectorTransformMatrixPointsI_ptr = FunctionWrapper.Load<GdipVectorTransformMatrixPointsI_delegate>(s_gdipModule, "GdipVectorTransformMatrixPointsI");
+ GdipGetMatrixElements_ptr = FunctionWrapper.Load<GdipGetMatrixElements_delegate>(s_gdipModule, "GdipGetMatrixElements");
+ GdipIsMatrixInvertible_ptr = FunctionWrapper.Load<GdipIsMatrixInvertible_delegate>(s_gdipModule, "GdipIsMatrixInvertible");
+ GdipIsMatrixIdentity_ptr = FunctionWrapper.Load<GdipIsMatrixIdentity_delegate>(s_gdipModule, "GdipIsMatrixIdentity");
+ GdipIsMatrixEqual_ptr = FunctionWrapper.Load<GdipIsMatrixEqual_delegate>(s_gdipModule, "GdipIsMatrixEqual");
+ GdipCreateRegion_ptr = FunctionWrapper.Load<GdipCreateRegion_delegate>(s_gdipModule, "GdipCreateRegion");
+ GdipCreateRegionRect_ptr = FunctionWrapper.Load<GdipCreateRegionRect_delegate>(s_gdipModule, "GdipCreateRegionRect");
+ GdipCreateRegionRectI_ptr = FunctionWrapper.Load<GdipCreateRegionRectI_delegate>(s_gdipModule, "GdipCreateRegionRectI");
+ GdipCreateRegionPath_ptr = FunctionWrapper.Load<GdipCreateRegionPath_delegate>(s_gdipModule, "GdipCreateRegionPath");
+ GdipCreateRegionRgnData_ptr = FunctionWrapper.Load<GdipCreateRegionRgnData_delegate>(s_gdipModule, "GdipCreateRegionRgnData");
+ GdipCreateRegionHrgn_ptr = FunctionWrapper.Load<GdipCreateRegionHrgn_delegate>(s_gdipModule, "GdipCreateRegionHrgn");
+ GdipCloneRegion_ptr = FunctionWrapper.Load<GdipCloneRegion_delegate>(s_gdipModule, "GdipCloneRegion");
+ GdipDeleteRegion_ptr = FunctionWrapper.Load<GdipDeleteRegion_delegate>(s_gdipModule, "GdipDeleteRegion");
+ GdipFillRegion_ptr = FunctionWrapper.Load<GdipFillRegion_delegate>(s_gdipModule, "GdipFillRegion");
+ GdipSetInfinite_ptr = FunctionWrapper.Load<GdipSetInfinite_delegate>(s_gdipModule, "GdipSetInfinite");
+ GdipSetEmpty_ptr = FunctionWrapper.Load<GdipSetEmpty_delegate>(s_gdipModule, "GdipSetEmpty");
+ GdipCombineRegionRect_ptr = FunctionWrapper.Load<GdipCombineRegionRect_delegate>(s_gdipModule, "GdipCombineRegionRect");
+ GdipCombineRegionRectI_ptr = FunctionWrapper.Load<GdipCombineRegionRectI_delegate>(s_gdipModule, "GdipCombineRegionRectI");
+ GdipCombineRegionPath_ptr = FunctionWrapper.Load<GdipCombineRegionPath_delegate>(s_gdipModule, "GdipCombineRegionPath");
+ GdipCombineRegionRegion_ptr = FunctionWrapper.Load<GdipCombineRegionRegion_delegate>(s_gdipModule, "GdipCombineRegionRegion");
+ GdipTranslateRegion_ptr = FunctionWrapper.Load<GdipTranslateRegion_delegate>(s_gdipModule, "GdipTranslateRegion");
+ GdipTranslateRegionI_ptr = FunctionWrapper.Load<GdipTranslateRegionI_delegate>(s_gdipModule, "GdipTranslateRegionI");
+ GdipTransformRegion_ptr = FunctionWrapper.Load<GdipTransformRegion_delegate>(s_gdipModule, "GdipTransformRegion");
+ GdipGetRegionBounds_ptr = FunctionWrapper.Load<GdipGetRegionBounds_delegate>(s_gdipModule, "GdipGetRegionBounds");
+ GdipGetRegionHRgn_ptr = FunctionWrapper.Load<GdipGetRegionHRgn_delegate>(s_gdipModule, "GdipGetRegionHRgn");
+ GdipIsEmptyRegion_ptr = FunctionWrapper.Load<GdipIsEmptyRegion_delegate>(s_gdipModule, "GdipIsEmptyRegion");
+ GdipIsInfiniteRegion_ptr = FunctionWrapper.Load<GdipIsInfiniteRegion_delegate>(s_gdipModule, "GdipIsInfiniteRegion");
+ GdipIsEqualRegion_ptr = FunctionWrapper.Load<GdipIsEqualRegion_delegate>(s_gdipModule, "GdipIsEqualRegion");
+ GdipGetRegionDataSize_ptr = FunctionWrapper.Load<GdipGetRegionDataSize_delegate>(s_gdipModule, "GdipGetRegionDataSize");
+ GdipGetRegionData_ptr = FunctionWrapper.Load<GdipGetRegionData_delegate>(s_gdipModule, "GdipGetRegionData");
+ GdipIsVisibleRegionPoint_ptr = FunctionWrapper.Load<GdipIsVisibleRegionPoint_delegate>(s_gdipModule, "GdipIsVisibleRegionPoint");
+ GdipIsVisibleRegionPointI_ptr = FunctionWrapper.Load<GdipIsVisibleRegionPointI_delegate>(s_gdipModule, "GdipIsVisibleRegionPointI");
+ GdipIsVisibleRegionRect_ptr = FunctionWrapper.Load<GdipIsVisibleRegionRect_delegate>(s_gdipModule, "GdipIsVisibleRegionRect");
+ GdipIsVisibleRegionRectI_ptr = FunctionWrapper.Load<GdipIsVisibleRegionRectI_delegate>(s_gdipModule, "GdipIsVisibleRegionRectI");
+ GdipGetRegionScansCount_ptr = FunctionWrapper.Load<GdipGetRegionScansCount_delegate>(s_gdipModule, "GdipGetRegionScansCount");
+ GdipGetRegionScans_ptr = FunctionWrapper.Load<GdipGetRegionScans_delegate>(s_gdipModule, "GdipGetRegionScans");
+ GdipSetClipGraphics_ptr = FunctionWrapper.Load<GdipSetClipGraphics_delegate>(s_gdipModule, "GdipSetClipGraphics");
+ GdipSetClipRect_ptr = FunctionWrapper.Load<GdipSetClipRect_delegate>(s_gdipModule, "GdipSetClipRect");
+ GdipSetClipRectI_ptr = FunctionWrapper.Load<GdipSetClipRectI_delegate>(s_gdipModule, "GdipSetClipRectI");
+ GdipSetClipPath_ptr = FunctionWrapper.Load<GdipSetClipPath_delegate>(s_gdipModule, "GdipSetClipPath");
+ GdipSetClipRegion_ptr = FunctionWrapper.Load<GdipSetClipRegion_delegate>(s_gdipModule, "GdipSetClipRegion");
+ GdipResetClip_ptr = FunctionWrapper.Load<GdipResetClip_delegate>(s_gdipModule, "GdipResetClip");
+ GdipTranslateClip_ptr = FunctionWrapper.Load<GdipTranslateClip_delegate>(s_gdipModule, "GdipTranslateClip");
+ GdipGetClip_ptr = FunctionWrapper.Load<GdipGetClip_delegate>(s_gdipModule, "GdipGetClip");
+ GdipGetClipBounds_ptr = FunctionWrapper.Load<GdipGetClipBounds_delegate>(s_gdipModule, "GdipGetClipBounds");
+ GdipIsClipEmpty_ptr = FunctionWrapper.Load<GdipIsClipEmpty_delegate>(s_gdipModule, "GdipIsClipEmpty");
+ GdipGetVisibleClipBounds_ptr = FunctionWrapper.Load<GdipGetVisibleClipBounds_delegate>(s_gdipModule, "GdipGetVisibleClipBounds");
+ GdipIsVisibleClipEmpty_ptr = FunctionWrapper.Load<GdipIsVisibleClipEmpty_delegate>(s_gdipModule, "GdipIsVisibleClipEmpty");
+ GdipIsVisiblePoint_ptr = FunctionWrapper.Load<GdipIsVisiblePoint_delegate>(s_gdipModule, "GdipIsVisiblePoint");
+ GdipIsVisiblePointI_ptr = FunctionWrapper.Load<GdipIsVisiblePointI_delegate>(s_gdipModule, "GdipIsVisiblePointI");
+ GdipIsVisibleRect_ptr = FunctionWrapper.Load<GdipIsVisibleRect_delegate>(s_gdipModule, "GdipIsVisibleRect");
+ GdipIsVisibleRectI_ptr = FunctionWrapper.Load<GdipIsVisibleRectI_delegate>(s_gdipModule, "GdipIsVisibleRectI");
+ GdipSetStringFormatMeasurableCharacterRanges_ptr = FunctionWrapper.Load<GdipSetStringFormatMeasurableCharacterRanges_delegate>(s_gdipModule, "GdipSetStringFormatMeasurableCharacterRanges");
+ GdipCreateStringFormat_ptr = FunctionWrapper.Load<GdipCreateStringFormat_delegate>(s_gdipModule, "GdipCreateStringFormat");
+ GdipStringFormatGetGenericDefault_ptr = FunctionWrapper.Load<GdipStringFormatGetGenericDefault_delegate>(s_gdipModule, "GdipStringFormatGetGenericDefault");
+ GdipStringFormatGetGenericTypographic_ptr = FunctionWrapper.Load<GdipStringFormatGetGenericTypographic_delegate>(s_gdipModule, "GdipStringFormatGetGenericTypographic");
+ GdipDeleteStringFormat_ptr = FunctionWrapper.Load<GdipDeleteStringFormat_delegate>(s_gdipModule, "GdipDeleteStringFormat");
+ GdipCloneStringFormat_ptr = FunctionWrapper.Load<GdipCloneStringFormat_delegate>(s_gdipModule, "GdipCloneStringFormat");
+ GdipSetStringFormatFlags_ptr = FunctionWrapper.Load<GdipSetStringFormatFlags_delegate>(s_gdipModule, "GdipSetStringFormatFlags");
+ GdipGetStringFormatFlags_ptr = FunctionWrapper.Load<GdipGetStringFormatFlags_delegate>(s_gdipModule, "GdipGetStringFormatFlags");
+ GdipSetStringFormatAlign_ptr = FunctionWrapper.Load<GdipSetStringFormatAlign_delegate>(s_gdipModule, "GdipSetStringFormatAlign");
+ GdipGetStringFormatAlign_ptr = FunctionWrapper.Load<GdipGetStringFormatAlign_delegate>(s_gdipModule, "GdipGetStringFormatAlign");
+ GdipSetStringFormatLineAlign_ptr = FunctionWrapper.Load<GdipSetStringFormatLineAlign_delegate>(s_gdipModule, "GdipSetStringFormatLineAlign");
+ GdipGetStringFormatLineAlign_ptr = FunctionWrapper.Load<GdipGetStringFormatLineAlign_delegate>(s_gdipModule, "GdipGetStringFormatLineAlign");
+ GdipSetStringFormatHotkeyPrefix_ptr = FunctionWrapper.Load<GdipSetStringFormatHotkeyPrefix_delegate>(s_gdipModule, "GdipSetStringFormatHotkeyPrefix");
+ GdipGetStringFormatHotkeyPrefix_ptr = FunctionWrapper.Load<GdipGetStringFormatHotkeyPrefix_delegate>(s_gdipModule, "GdipGetStringFormatHotkeyPrefix");
+ GdipSetStringFormatTabStops_ptr = FunctionWrapper.Load<GdipSetStringFormatTabStops_delegate>(s_gdipModule, "GdipSetStringFormatTabStops");
+ GdipGetStringFormatTabStops_ptr = FunctionWrapper.Load<GdipGetStringFormatTabStops_delegate>(s_gdipModule, "GdipGetStringFormatTabStops");
+ GdipGetStringFormatTabStopCount_ptr = FunctionWrapper.Load<GdipGetStringFormatTabStopCount_delegate>(s_gdipModule, "GdipGetStringFormatTabStopCount");
+ GdipGetStringFormatMeasurableCharacterRangeCount_ptr = FunctionWrapper.Load<GdipGetStringFormatMeasurableCharacterRangeCount_delegate>(s_gdipModule, "GdipGetStringFormatMeasurableCharacterRangeCount");
+ GdipSetStringFormatTrimming_ptr = FunctionWrapper.Load<GdipSetStringFormatTrimming_delegate>(s_gdipModule, "GdipSetStringFormatTrimming");
+ GdipGetStringFormatTrimming_ptr = FunctionWrapper.Load<GdipGetStringFormatTrimming_delegate>(s_gdipModule, "GdipGetStringFormatTrimming");
+ GdipSetStringFormatDigitSubstitution_ptr = FunctionWrapper.Load<GdipSetStringFormatDigitSubstitution_delegate>(s_gdipModule, "GdipSetStringFormatDigitSubstitution");
+ GdipGetStringFormatDigitSubstitution_ptr = FunctionWrapper.Load<GdipGetStringFormatDigitSubstitution_delegate>(s_gdipModule, "GdipGetStringFormatDigitSubstitution");
}
// Shared function imports (all platforms)
@@ -697,9 +669,9 @@ namespace System.Drawing
private static FunctionWrapper<GdipGetPathGradientBlendCount_delegate> GdipGetPathGradientBlendCount_ptr;
internal static int GdipGetPathGradientBlendCount(HandleRef brush, out int count) => GdipGetPathGradientBlendCount_ptr.Delegate(brush, out count);
- private delegate int GdipGetPathGradientBlend_delegate(HandleRef brush, IntPtr blend, IntPtr positions, int count);
+ private delegate int GdipGetPathGradientBlend_delegate(HandleRef brush, float[] blend, float[] positions, int count);
private static FunctionWrapper<GdipGetPathGradientBlend_delegate> GdipGetPathGradientBlend_ptr;
- internal static int GdipGetPathGradientBlend(HandleRef brush, IntPtr blend, IntPtr positions, int count) => GdipGetPathGradientBlend_ptr.Delegate(brush, blend, positions, count);
+ internal static int GdipGetPathGradientBlend(HandleRef brush, float[] blend, float[] positions, int count) => GdipGetPathGradientBlend_ptr.Delegate(brush, blend, positions, count);
private delegate int GdipSetPathGradientBlend_delegate(HandleRef brush, HandleRef blend, HandleRef positions, int count);
private static FunctionWrapper<GdipSetPathGradientBlend_delegate> GdipSetPathGradientBlend_ptr;
@@ -709,13 +681,13 @@ namespace System.Drawing
private static FunctionWrapper<GdipGetPathGradientPresetBlendCount_delegate> GdipGetPathGradientPresetBlendCount_ptr;
internal static int GdipGetPathGradientPresetBlendCount(HandleRef brush, out int count) => GdipGetPathGradientPresetBlendCount_ptr.Delegate(brush, out count);
- private delegate int GdipGetPathGradientPresetBlend_delegate(HandleRef brush, IntPtr blend, IntPtr positions, int count);
+ private delegate int GdipGetPathGradientPresetBlend_delegate(HandleRef brush, int[] blend, float[] positions, int count);
private static FunctionWrapper<GdipGetPathGradientPresetBlend_delegate> GdipGetPathGradientPresetBlend_ptr;
- internal static int GdipGetPathGradientPresetBlend(HandleRef brush, IntPtr blend, IntPtr positions, int count) => GdipGetPathGradientPresetBlend_ptr.Delegate(brush, blend, positions, count);
+ internal static int GdipGetPathGradientPresetBlend(HandleRef brush, int[] blend, float[] positions, int count) => GdipGetPathGradientPresetBlend_ptr.Delegate(brush, blend, positions, count);
- private delegate int GdipSetPathGradientPresetBlend_delegate(HandleRef brush, HandleRef blend, HandleRef positions, int count);
+ private delegate int GdipSetPathGradientPresetBlend_delegate(HandleRef brush, int[] blend, float[] positions, int count);
private static FunctionWrapper<GdipSetPathGradientPresetBlend_delegate> GdipSetPathGradientPresetBlend_ptr;
- internal static int GdipSetPathGradientPresetBlend(HandleRef brush, HandleRef blend, HandleRef positions, int count) => GdipSetPathGradientPresetBlend_ptr.Delegate(brush, blend, positions, count);
+ internal static int GdipSetPathGradientPresetBlend(HandleRef brush, int[] blend, float[] positions, int count) => GdipSetPathGradientPresetBlend_ptr.Delegate(brush, blend, positions, count);
private delegate int GdipSetPathGradientSigmaBlend_delegate(HandleRef brush, float focus, float scale);
private static FunctionWrapper<GdipSetPathGradientSigmaBlend_delegate> GdipSetPathGradientSigmaBlend_ptr;
@@ -922,6 +894,59 @@ namespace System.Drawing
private static FunctionWrapper<GdipCloneFontFamily_delegate> GdipCloneFontFamily_ptr;
internal static int GdipCloneFontFamily(HandleRef fontfamily, out IntPtr clonefontfamily) => GdipCloneFontFamily_ptr.Delegate(fontfamily, out clonefontfamily);
+ private delegate int GdipCreateFontFamilyFromName_delegate([MarshalAs(UnmanagedType.LPWStr)]string name, HandleRef fontCollection, out IntPtr FontFamily);
+ private static FunctionWrapper<GdipCreateFontFamilyFromName_delegate> GdipCreateFontFamilyFromName_ptr;
+ internal static int GdipCreateFontFamilyFromName(string name, HandleRef fontCollection, out IntPtr FontFamily) => GdipCreateFontFamilyFromName_ptr.Delegate(name, fontCollection, out FontFamily);
+
+ private delegate int GdipGetGenericFontFamilySansSerif_delegate(out IntPtr fontfamily);
+ private static FunctionWrapper<GdipGetGenericFontFamilySansSerif_delegate> GdipGetGenericFontFamilySansSerif_ptr;
+ internal static int GdipGetGenericFontFamilySansSerif(out IntPtr fontfamily) => GdipGetGenericFontFamilySansSerif_ptr.Delegate(out fontfamily);
+
+ private delegate int GdipGetGenericFontFamilySerif_delegate(out IntPtr fontfamily);
+ private static FunctionWrapper<GdipGetGenericFontFamilySerif_delegate> GdipGetGenericFontFamilySerif_ptr;
+ internal static int GdipGetGenericFontFamilySerif(out IntPtr fontfamily) => GdipGetGenericFontFamilySerif_ptr.Delegate(out fontfamily);
+
+ private delegate int GdipGetGenericFontFamilyMonospace_delegate(out IntPtr fontfamily);
+ private static FunctionWrapper<GdipGetGenericFontFamilyMonospace_delegate> GdipGetGenericFontFamilyMonospace_ptr;
+ internal static int GdipGetGenericFontFamilyMonospace(out IntPtr fontfamily) => GdipGetGenericFontFamilyMonospace_ptr.Delegate(out fontfamily);
+
+ private delegate int GdipDeleteFontFamily_delegate(HandleRef fontFamily);
+ private static FunctionWrapper<GdipDeleteFontFamily_delegate> GdipDeleteFontFamily_ptr;
+ internal static int IntGdipDeleteFontFamily(HandleRef fontFamily) => GdipDeleteFontFamily_ptr.Delegate(fontFamily);
+
+ private delegate int GdipGetFamilyName_delegate(HandleRef family, IntPtr name, int language);
+ private static FunctionWrapper<GdipGetFamilyName_delegate> GdipGetFamilyName_ptr;
+ internal static int GdipGetFamilyName(HandleRef family, IntPtr name, int language) => GdipGetFamilyName_ptr.Delegate(family, name, language);
+ internal static unsafe int GdipGetFamilyName(HandleRef family, StringBuilder nameBuilder, int language)
+ {
+ const int LF_FACESIZE = 32;
+ char* namePtr = stackalloc char[LF_FACESIZE];
+ int ret = GdipGetFamilyName(family, (IntPtr)namePtr, language);
+ string name = Marshal.PtrToStringUni((IntPtr)namePtr);
+ nameBuilder.Append(name);
+ return ret;
+ }
+
+ private delegate int GdipIsStyleAvailable_delegate(HandleRef family, FontStyle style, out int isStyleAvailable);
+ private static FunctionWrapper<GdipIsStyleAvailable_delegate> GdipIsStyleAvailable_ptr;
+ internal static int GdipIsStyleAvailable(HandleRef family, FontStyle style, out int isStyleAvailable) => GdipIsStyleAvailable_ptr.Delegate(family, style, out isStyleAvailable);
+
+ private delegate int GdipGetEmHeight_delegate(HandleRef family, FontStyle style, out int EmHeight);
+ private static FunctionWrapper<GdipGetEmHeight_delegate> GdipGetEmHeight_ptr;
+ internal static int GdipGetEmHeight(HandleRef family, FontStyle style, out int EmHeight) => GdipGetEmHeight_ptr.Delegate(family, style, out EmHeight);
+
+ private delegate int GdipGetCellAscent_delegate(HandleRef family, FontStyle style, out int CellAscent);
+ private static FunctionWrapper<GdipGetCellAscent_delegate> GdipGetCellAscent_ptr;
+ internal static int GdipGetCellAscent(HandleRef family, FontStyle style, out int CellAscent) => GdipGetCellAscent_ptr.Delegate(family, style, out CellAscent);
+
+ private delegate int GdipGetCellDescent_delegate(HandleRef family, FontStyle style, out int CellDescent);
+ private static FunctionWrapper<GdipGetCellDescent_delegate> GdipGetCellDescent_ptr;
+ internal static int GdipGetCellDescent(HandleRef family, FontStyle style, out int CellDescent) => GdipGetCellDescent_ptr.Delegate(family, style, out CellDescent);
+
+ private delegate int GdipGetLineSpacing_delegate(HandleRef family, FontStyle style, out int LineSpaceing);
+ private static FunctionWrapper<GdipGetLineSpacing_delegate> GdipGetLineSpacing_ptr;
+ internal static int GdipGetLineSpacing(HandleRef family, FontStyle style, out int LineSpaceing) => GdipGetLineSpacing_ptr.Delegate(family, style, out LineSpaceing);
+
private delegate int GdipNewInstalledFontCollection_delegate(out IntPtr fontCollection);
private static FunctionWrapper<GdipNewInstalledFontCollection_delegate> GdipNewInstalledFontCollection_ptr;
internal static int GdipNewInstalledFontCollection(out IntPtr fontCollection) => GdipNewInstalledFontCollection_ptr.Delegate(out fontCollection);
@@ -1106,9 +1131,9 @@ namespace System.Drawing
private static FunctionWrapper<GdipGetPenDashCount_delegate> GdipGetPenDashCount_ptr;
internal static int GdipGetPenDashCount(HandleRef pen, out int dashcount) => GdipGetPenDashCount_ptr.Delegate(pen, out dashcount);
- private delegate int GdipGetPenDashArray_delegate(HandleRef pen, IntPtr memorydash, int count);
+ private delegate int GdipGetPenDashArray_delegate(HandleRef pen, float[] memorydash, int count);
private static FunctionWrapper<GdipGetPenDashArray_delegate> GdipGetPenDashArray_ptr;
- internal static int GdipGetPenDashArray(HandleRef pen, IntPtr memorydash, int count) => GdipGetPenDashArray_ptr.Delegate(pen, memorydash, count);
+ internal static int GdipGetPenDashArray(HandleRef pen, float[] memorydash, int count) => GdipGetPenDashArray_ptr.Delegate(pen, memorydash, count);
private delegate int GdipGetPenCompoundCount_delegate(HandleRef pen, out int count);
private static FunctionWrapper<GdipGetPenCompoundCount_delegate> GdipGetPenCompoundCount_ptr;
diff --git a/src/System.Drawing.Common/src/System/Drawing/Graphics.Unix.cs b/src/System.Drawing.Common/src/System/Drawing/Graphics.Unix.cs
index eda7921b06..4cf0917f63 100644
--- a/src/System.Drawing.Common/src/System/Drawing/Graphics.Unix.cs
+++ b/src/System.Drawing.Common/src/System/Drawing/Graphics.Unix.cs
@@ -162,7 +162,7 @@ namespace System.Drawing
public void Clear(Color color)
{
- Status status;
+ int status;
status = SafeNativeMethods.Gdip.GdipGraphicsClear(nativeObject, color.ToArgb());
SafeNativeMethods.Gdip.CheckStatus(status);
}
@@ -193,34 +193,18 @@ namespace System.Drawing
if (!Enum.IsDefined(typeof(CopyPixelOperation), copyPixelOperation))
throw new InvalidEnumArgumentException(string.Format("Enum argument value '{0}' is not valid for CopyPixelOperation", copyPixelOperation));
- if (GDIPlus.UseX11Drawable)
+ if (SafeNativeMethods.Gdip.UseX11Drawable)
{
CopyFromScreenX11(sourceX, sourceY, destinationX, destinationY, blockRegionSize, copyPixelOperation);
}
- else if (GDIPlus.UseCarbonDrawable)
+ else if (SafeNativeMethods.Gdip.UseCarbonDrawable)
{
CopyFromScreenMac(sourceX, sourceY, destinationX, destinationY, blockRegionSize, copyPixelOperation);
}
- else if (GDIPlus.UseCocoaDrawable)
+ else if (SafeNativeMethods.Gdip.UseCocoaDrawable)
{
CopyFromScreenMac(sourceX, sourceY, destinationX, destinationY, blockRegionSize, copyPixelOperation);
}
- else
- {
- CopyFromScreenWin32(sourceX, sourceY, destinationX, destinationY, blockRegionSize, copyPixelOperation);
- }
- }
-
- private void CopyFromScreenWin32(int sourceX, int sourceY, int destinationX, int destinationY, Size blockRegionSize, CopyPixelOperation copyPixelOperation)
- {
- IntPtr window = GDIPlus.GetDesktopWindow();
- IntPtr srcDC = GDIPlus.GetDC(window);
- IntPtr dstDC = GetHdc();
- GDIPlus.BitBlt(dstDC, destinationX, destinationY, blockRegionSize.Width,
- blockRegionSize.Height, srcDC, sourceX, sourceY, (int)copyPixelOperation);
-
- GDIPlus.ReleaseDC(IntPtr.Zero, srcDC);
- ReleaseHdc(dstDC);
}
private void CopyFromScreenMac(int sourceX, int sourceY, int destinationX, int destinationY, Size blockRegionSize, CopyPixelOperation copyPixelOperation)
@@ -236,18 +220,18 @@ namespace System.Drawing
if (copyPixelOperation != CopyPixelOperation.SourceCopy)
throw new NotImplementedException("Operation not implemented under X11");
- if (GDIPlus.Display == IntPtr.Zero)
+ if (SafeNativeMethods.Gdip.Display == IntPtr.Zero)
{
- GDIPlus.Display = GDIPlus.XOpenDisplay(IntPtr.Zero);
+ SafeNativeMethods.Gdip.Display = LibX11Functions.XOpenDisplay(IntPtr.Zero);
}
- window = GDIPlus.XRootWindow(GDIPlus.Display, 0);
- defvisual = GDIPlus.XDefaultVisual(GDIPlus.Display, 0);
+ window = LibX11Functions.XRootWindow(SafeNativeMethods.Gdip.Display, 0);
+ defvisual = LibX11Functions.XDefaultVisual(SafeNativeMethods.Gdip.Display, 0);
XVisualInfo visual = new XVisualInfo();
/* Get XVisualInfo for this visual */
- visual.visualid = GDIPlus.XVisualIDFromVisual(defvisual);
- vPtr = GDIPlus.XGetVisualInfo(GDIPlus.Display, 0x1 /* VisualIDMask */, ref visual, ref nitems);
+ visual.visualid = LibX11Functions.XVisualIDFromVisual(defvisual);
+ vPtr = LibX11Functions.XGetVisualInfo(SafeNativeMethods.Gdip.Display, 0x1 /* VisualIDMask */, ref visual, ref nitems);
visual = (XVisualInfo)Marshal.PtrToStructure(vPtr, typeof(XVisualInfo));
#if false
Console.WriteLine ("visual\t{0}", visual.visual);
@@ -261,7 +245,7 @@ namespace System.Drawing
Console.WriteLine ("colormap_size\t{0}", visual.colormap_size);
Console.WriteLine ("bits_per_rgb\t{0}", visual.bits_per_rgb);
#endif
- image = GDIPlus.XGetImage(GDIPlus.Display, window, sourceX, sourceY, blockRegionSize.Width,
+ image = LibX11Functions.XGetImage(SafeNativeMethods.Gdip.Display, window, sourceX, sourceY, blockRegionSize.Width,
blockRegionSize.Height, AllPlanes, 2 /* ZPixmap*/);
if (image == IntPtr.Zero)
{
@@ -279,7 +263,7 @@ namespace System.Drawing
{
for (int x = 0; x < blockRegionSize.Width; x++)
{
- pixel = GDIPlus.XGetPixel(image, x, y);
+ pixel = LibX11Functions.XGetPixel(image, x, y);
switch (visual.depth)
{
@@ -305,16 +289,16 @@ namespace System.Drawing
DrawImage(bmp, destinationX, destinationY);
bmp.Dispose();
- GDIPlus.XDestroyImage(image);
- GDIPlus.XFree(vPtr);
+ LibX11Functions.XDestroyImage(image);
+ LibX11Functions.XFree(vPtr);
}
public void Dispose()
{
- Status status;
+ int status;
if (!disposed)
{
- if (GDIPlus.UseCarbonDrawable || GDIPlus.UseCocoaDrawable)
+ if (SafeNativeMethods.Gdip.UseCarbonDrawable || SafeNativeMethods.Gdip.UseCocoaDrawable)
{
Flush();
if (maccontext != null)
@@ -345,7 +329,7 @@ namespace System.Drawing
public void DrawArc(Pen pen, float x, float y, float width, float height, float startAngle, float sweepAngle)
{
- Status status;
+ int status;
if (pen == null)
throw new ArgumentNullException("pen");
@@ -359,7 +343,7 @@ namespace System.Drawing
// int sweepAngle. However, GdipDrawArcI uses also float for the startAngle and sweepAngle params
public void DrawArc(Pen pen, int x, int y, int width, int height, int startAngle, int sweepAngle)
{
- Status status;
+ int status;
if (pen == null)
throw new ArgumentNullException("pen");
status = SafeNativeMethods.Gdip.GdipDrawArcI(nativeObject, pen.NativePen,
@@ -369,7 +353,7 @@ namespace System.Drawing
public void DrawBezier(Pen pen, PointF pt1, PointF pt2, PointF pt3, PointF pt4)
{
- Status status;
+ int status;
if (pen == null)
throw new ArgumentNullException("pen");
status = SafeNativeMethods.Gdip.GdipDrawBezier(nativeObject, pen.NativePen,
@@ -380,7 +364,7 @@ namespace System.Drawing
public void DrawBezier(Pen pen, Point pt1, Point pt2, Point pt3, Point pt4)
{
- Status status;
+ int status;
if (pen == null)
throw new ArgumentNullException("pen");
status = SafeNativeMethods.Gdip.GdipDrawBezierI(nativeObject, pen.NativePen,
@@ -391,7 +375,7 @@ namespace System.Drawing
public void DrawBezier(Pen pen, float x1, float y1, float x2, float y2, float x3, float y3, float x4, float y4)
{
- Status status;
+ int status;
if (pen == null)
throw new ArgumentNullException("pen");
status = SafeNativeMethods.Gdip.GdipDrawBezier(nativeObject, pen.NativePen, x1,
@@ -407,7 +391,7 @@ namespace System.Drawing
throw new ArgumentNullException("points");
int length = points.Length;
- Status status;
+ int status;
if (length < 4)
return;
@@ -435,7 +419,7 @@ namespace System.Drawing
throw new ArgumentNullException("points");
int length = points.Length;
- Status status;
+ int status;
if (length < 4)
return;
@@ -463,7 +447,7 @@ namespace System.Drawing
if (points == null)
throw new ArgumentNullException("points");
- Status status;
+ int status;
status = SafeNativeMethods.Gdip.GdipDrawClosedCurve(nativeObject, pen.NativePen, points, points.Length);
SafeNativeMethods.Gdip.CheckStatus(status);
}
@@ -475,7 +459,7 @@ namespace System.Drawing
if (points == null)
throw new ArgumentNullException("points");
- Status status;
+ int status;
status = SafeNativeMethods.Gdip.GdipDrawClosedCurveI(nativeObject, pen.NativePen, points, points.Length);
SafeNativeMethods.Gdip.CheckStatus(status);
}
@@ -489,7 +473,7 @@ namespace System.Drawing
if (points == null)
throw new ArgumentNullException("points");
- Status status;
+ int status;
status = SafeNativeMethods.Gdip.GdipDrawClosedCurve2I(nativeObject, pen.NativePen, points, points.Length, tension);
SafeNativeMethods.Gdip.CheckStatus(status);
}
@@ -503,7 +487,7 @@ namespace System.Drawing
if (points == null)
throw new ArgumentNullException("points");
- Status status;
+ int status;
status = SafeNativeMethods.Gdip.GdipDrawClosedCurve2(nativeObject, pen.NativePen, points, points.Length, tension);
SafeNativeMethods.Gdip.CheckStatus(status);
}
@@ -515,7 +499,7 @@ namespace System.Drawing
if (points == null)
throw new ArgumentNullException("points");
- Status status;
+ int status;
status = SafeNativeMethods.Gdip.GdipDrawCurveI(nativeObject, pen.NativePen, points, points.Length);
SafeNativeMethods.Gdip.CheckStatus(status);
}
@@ -527,7 +511,7 @@ namespace System.Drawing
if (points == null)
throw new ArgumentNullException("points");
- Status status;
+ int status;
status = SafeNativeMethods.Gdip.GdipDrawCurve(nativeObject, pen.NativePen, points, points.Length);
SafeNativeMethods.Gdip.CheckStatus(status);
}
@@ -539,7 +523,7 @@ namespace System.Drawing
if (points == null)
throw new ArgumentNullException("points");
- Status status;
+ int status;
status = SafeNativeMethods.Gdip.GdipDrawCurve2(nativeObject, pen.NativePen, points, points.Length, tension);
SafeNativeMethods.Gdip.CheckStatus(status);
}
@@ -551,7 +535,7 @@ namespace System.Drawing
if (points == null)
throw new ArgumentNullException("points");
- Status status;
+ int status;
status = SafeNativeMethods.Gdip.GdipDrawCurve2I(nativeObject, pen.NativePen, points, points.Length, tension);
SafeNativeMethods.Gdip.CheckStatus(status);
}
@@ -563,7 +547,7 @@ namespace System.Drawing
if (points == null)
throw new ArgumentNullException("points");
- Status status;
+ int status;
status = SafeNativeMethods.Gdip.GdipDrawCurve3(nativeObject, pen.NativePen,
points, points.Length, offset,
numberOfSegments, 0.5f);
@@ -577,7 +561,7 @@ namespace System.Drawing
if (points == null)
throw new ArgumentNullException("points");
- Status status;
+ int status;
status = SafeNativeMethods.Gdip.GdipDrawCurve3I(nativeObject, pen.NativePen,
points, points.Length, offset,
numberOfSegments, tension);
@@ -591,7 +575,7 @@ namespace System.Drawing
if (points == null)
throw new ArgumentNullException("points");
- Status status;
+ int status;
status = SafeNativeMethods.Gdip.GdipDrawCurve3(nativeObject, pen.NativePen,
points, points.Length, offset,
numberOfSegments, tension);
@@ -617,7 +601,7 @@ namespace System.Drawing
{
if (pen == null)
throw new ArgumentNullException("pen");
- Status status;
+ int status;
status = SafeNativeMethods.Gdip.GdipDrawEllipseI(nativeObject, pen.NativePen, x, y, width, height);
SafeNativeMethods.Gdip.CheckStatus(status);
}
@@ -626,7 +610,7 @@ namespace System.Drawing
{
if (pen == null)
throw new ArgumentNullException("pen");
- Status status = SafeNativeMethods.Gdip.GdipDrawEllipse(nativeObject, pen.NativePen, x, y, width, height);
+ int status = SafeNativeMethods.Gdip.GdipDrawEllipse(nativeObject, pen.NativePen, x, y, width, height);
SafeNativeMethods.Gdip.CheckStatus(status);
}
@@ -659,7 +643,7 @@ namespace System.Drawing
if (image == null)
throw new ArgumentNullException("image");
- Status status = SafeNativeMethods.Gdip.GdipDrawImageRect(nativeObject, image.NativeObject, rect.X, rect.Y, rect.Width, rect.Height);
+ int status = SafeNativeMethods.Gdip.GdipDrawImageRect(nativeObject, image.NativeObject, rect.X, rect.Y, rect.Width, rect.Height);
SafeNativeMethods.Gdip.CheckStatus(status);
}
@@ -668,7 +652,7 @@ namespace System.Drawing
if (image == null)
throw new ArgumentNullException("image");
- Status status = SafeNativeMethods.Gdip.GdipDrawImage(nativeObject, image.NativeObject, point.X, point.Y);
+ int status = SafeNativeMethods.Gdip.GdipDrawImage(nativeObject, image.NativeObject, point.X, point.Y);
SafeNativeMethods.Gdip.CheckStatus(status);
}
@@ -679,7 +663,7 @@ namespace System.Drawing
if (destPoints == null)
throw new ArgumentNullException("destPoints");
- Status status = SafeNativeMethods.Gdip.GdipDrawImagePointsI(nativeObject, image.NativeObject, destPoints, destPoints.Length);
+ int status = SafeNativeMethods.Gdip.GdipDrawImagePointsI(nativeObject, image.NativeObject, destPoints, destPoints.Length);
SafeNativeMethods.Gdip.CheckStatus(status);
}
@@ -703,7 +687,7 @@ namespace System.Drawing
throw new ArgumentNullException("image");
if (destPoints == null)
throw new ArgumentNullException("destPoints");
- Status status = SafeNativeMethods.Gdip.GdipDrawImagePoints(nativeObject, image.NativeObject, destPoints, destPoints.Length);
+ int status = SafeNativeMethods.Gdip.GdipDrawImagePoints(nativeObject, image.NativeObject, destPoints, destPoints.Length);
SafeNativeMethods.Gdip.CheckStatus(status);
}
@@ -711,7 +695,7 @@ namespace System.Drawing
{
if (image == null)
throw new ArgumentNullException("image");
- Status status = SafeNativeMethods.Gdip.GdipDrawImageI(nativeObject, image.NativeObject, x, y);
+ int status = SafeNativeMethods.Gdip.GdipDrawImageI(nativeObject, image.NativeObject, x, y);
SafeNativeMethods.Gdip.CheckStatus(status);
}
@@ -719,7 +703,7 @@ namespace System.Drawing
{
if (image == null)
throw new ArgumentNullException("image");
- Status status = SafeNativeMethods.Gdip.GdipDrawImage(nativeObject, image.NativeObject, x, y);
+ int status = SafeNativeMethods.Gdip.GdipDrawImage(nativeObject, image.NativeObject, x, y);
SafeNativeMethods.Gdip.CheckStatus(status);
}
@@ -727,7 +711,7 @@ namespace System.Drawing
{
if (image == null)
throw new ArgumentNullException("image");
- Status status = SafeNativeMethods.Gdip.GdipDrawImageRectRectI(nativeObject, image.NativeObject,
+ int status = SafeNativeMethods.Gdip.GdipDrawImageRectRectI(nativeObject, image.NativeObject,
destRect.X, destRect.Y, destRect.Width, destRect.Height,
srcRect.X, srcRect.Y, srcRect.Width, srcRect.Height,
srcUnit, IntPtr.Zero, null, IntPtr.Zero);
@@ -738,7 +722,7 @@ namespace System.Drawing
{
if (image == null)
throw new ArgumentNullException("image");
- Status status = SafeNativeMethods.Gdip.GdipDrawImageRectRect(nativeObject, image.NativeObject,
+ int status = SafeNativeMethods.Gdip.GdipDrawImageRectRect(nativeObject, image.NativeObject,
destRect.X, destRect.Y, destRect.Width, destRect.Height,
srcRect.X, srcRect.Y, srcRect.Width, srcRect.Height,
srcUnit, IntPtr.Zero, null, IntPtr.Zero);
@@ -752,7 +736,7 @@ namespace System.Drawing
if (destPoints == null)
throw new ArgumentNullException("destPoints");
- Status status = SafeNativeMethods.Gdip.GdipDrawImagePointsRectI(nativeObject, image.NativeObject,
+ int status = SafeNativeMethods.Gdip.GdipDrawImagePointsRectI(nativeObject, image.NativeObject,
destPoints, destPoints.Length, srcRect.X, srcRect.Y,
srcRect.Width, srcRect.Height, srcUnit, IntPtr.Zero,
null, IntPtr.Zero);
@@ -766,7 +750,7 @@ namespace System.Drawing
if (destPoints == null)
throw new ArgumentNullException("destPoints");
- Status status = SafeNativeMethods.Gdip.GdipDrawImagePointsRect(nativeObject, image.NativeObject,
+ int status = SafeNativeMethods.Gdip.GdipDrawImagePointsRect(nativeObject, image.NativeObject,
destPoints, destPoints.Length, srcRect.X, srcRect.Y,
srcRect.Width, srcRect.Height, srcUnit, IntPtr.Zero,
null, IntPtr.Zero);
@@ -780,7 +764,7 @@ namespace System.Drawing
throw new ArgumentNullException("image");
if (destPoints == null)
throw new ArgumentNullException("destPoints");
- Status status = SafeNativeMethods.Gdip.GdipDrawImagePointsRectI(nativeObject, image.NativeObject,
+ int status = SafeNativeMethods.Gdip.GdipDrawImagePointsRectI(nativeObject, image.NativeObject,
destPoints, destPoints.Length, srcRect.X, srcRect.Y,
srcRect.Width, srcRect.Height, srcUnit,
imageAttr != null ? imageAttr.nativeImageAttributes : IntPtr.Zero, null, IntPtr.Zero);
@@ -791,7 +775,7 @@ namespace System.Drawing
{
if (image == null)
throw new ArgumentNullException("image");
- Status status = SafeNativeMethods.Gdip.GdipDrawImageRect(nativeObject, image.NativeObject, x, y,
+ int status = SafeNativeMethods.Gdip.GdipDrawImageRect(nativeObject, image.NativeObject, x, y,
width, height);
SafeNativeMethods.Gdip.CheckStatus(status);
}
@@ -803,7 +787,7 @@ namespace System.Drawing
throw new ArgumentNullException("image");
if (destPoints == null)
throw new ArgumentNullException("destPoints");
- Status status = SafeNativeMethods.Gdip.GdipDrawImagePointsRect(nativeObject, image.NativeObject,
+ int status = SafeNativeMethods.Gdip.GdipDrawImagePointsRect(nativeObject, image.NativeObject,
destPoints, destPoints.Length, srcRect.X, srcRect.Y,
srcRect.Width, srcRect.Height, srcUnit,
imageAttr != null ? imageAttr.nativeImageAttributes : IntPtr.Zero, null, IntPtr.Zero);
@@ -814,7 +798,7 @@ namespace System.Drawing
{
if (image == null)
throw new ArgumentNullException("image");
- Status status = SafeNativeMethods.Gdip.GdipDrawImagePointRectI(nativeObject, image.NativeObject, x, y, srcRect.X, srcRect.Y, srcRect.Width, srcRect.Height, srcUnit);
+ int status = SafeNativeMethods.Gdip.GdipDrawImagePointRectI(nativeObject, image.NativeObject, x, y, srcRect.X, srcRect.Y, srcRect.Width, srcRect.Height, srcUnit);
SafeNativeMethods.Gdip.CheckStatus(status);
}
@@ -822,7 +806,7 @@ namespace System.Drawing
{
if (image == null)
throw new ArgumentNullException("image");
- Status status = SafeNativeMethods.Gdip.GdipDrawImageRectI(nativeObject, image.nativeObject, x, y, width, height);
+ int status = SafeNativeMethods.Gdip.GdipDrawImageRectI(nativeObject, image.nativeObject, x, y, width, height);
SafeNativeMethods.Gdip.CheckStatus(status);
}
@@ -830,7 +814,7 @@ namespace System.Drawing
{
if (image == null)
throw new ArgumentNullException("image");
- Status status = SafeNativeMethods.Gdip.GdipDrawImagePointRect(nativeObject, image.nativeObject, x, y, srcRect.X, srcRect.Y, srcRect.Width, srcRect.Height, srcUnit);
+ int status = SafeNativeMethods.Gdip.GdipDrawImagePointRect(nativeObject, image.nativeObject, x, y, srcRect.X, srcRect.Y, srcRect.Width, srcRect.Height, srcUnit);
SafeNativeMethods.Gdip.CheckStatus(status);
}
@@ -840,7 +824,7 @@ namespace System.Drawing
throw new ArgumentNullException("image");
if (destPoints == null)
throw new ArgumentNullException("destPoints");
- Status status = SafeNativeMethods.Gdip.GdipDrawImagePointsRect(nativeObject, image.NativeObject,
+ int status = SafeNativeMethods.Gdip.GdipDrawImagePointsRect(nativeObject, image.NativeObject,
destPoints, destPoints.Length, srcRect.X, srcRect.Y,
srcRect.Width, srcRect.Height, srcUnit,
imageAttr != null ? imageAttr.nativeImageAttributes : IntPtr.Zero, callback, IntPtr.Zero);
@@ -854,7 +838,7 @@ namespace System.Drawing
if (destPoints == null)
throw new ArgumentNullException("destPoints");
- Status status = SafeNativeMethods.Gdip.GdipDrawImagePointsRectI(nativeObject, image.NativeObject,
+ int status = SafeNativeMethods.Gdip.GdipDrawImagePointsRectI(nativeObject, image.NativeObject,
destPoints, destPoints.Length, srcRect.X, srcRect.Y,
srcRect.Width, srcRect.Height, srcUnit,
imageAttr != null ? imageAttr.nativeImageAttributes : IntPtr.Zero, callback, IntPtr.Zero);
@@ -868,7 +852,7 @@ namespace System.Drawing
if (destPoints == null)
throw new ArgumentNullException("destPoints");
- Status status = SafeNativeMethods.Gdip.GdipDrawImagePointsRectI(nativeObject, image.NativeObject,
+ int status = SafeNativeMethods.Gdip.GdipDrawImagePointsRectI(nativeObject, image.NativeObject,
destPoints, destPoints.Length, srcRect.X, srcRect.Y,
srcRect.Width, srcRect.Height, srcUnit,
imageAttr != null ? imageAttr.nativeImageAttributes : IntPtr.Zero, callback, (IntPtr)callbackData);
@@ -879,7 +863,7 @@ namespace System.Drawing
{
if (image == null)
throw new ArgumentNullException("image");
- Status status = SafeNativeMethods.Gdip.GdipDrawImageRectRect(nativeObject, image.NativeObject,
+ int status = SafeNativeMethods.Gdip.GdipDrawImageRectRect(nativeObject, image.NativeObject,
destRect.X, destRect.Y, destRect.Width, destRect.Height,
srcX, srcY, srcWidth, srcHeight, srcUnit, IntPtr.Zero,
null, IntPtr.Zero);
@@ -888,7 +872,7 @@ namespace System.Drawing
public void DrawImage(Image image, PointF[] destPoints, RectangleF srcRect, GraphicsUnit srcUnit, ImageAttributes imageAttr, DrawImageAbort callback, int callbackData)
{
- Status status = SafeNativeMethods.Gdip.GdipDrawImagePointsRect(nativeObject, image.NativeObject,
+ int status = SafeNativeMethods.Gdip.GdipDrawImagePointsRect(nativeObject, image.NativeObject,
destPoints, destPoints.Length, srcRect.X, srcRect.Y,
srcRect.Width, srcRect.Height, srcUnit,
imageAttr != null ? imageAttr.nativeImageAttributes : IntPtr.Zero, callback, (IntPtr)callbackData);
@@ -899,7 +883,7 @@ namespace System.Drawing
{
if (image == null)
throw new ArgumentNullException("image");
- Status status = SafeNativeMethods.Gdip.GdipDrawImageRectRectI(nativeObject, image.NativeObject,
+ int status = SafeNativeMethods.Gdip.GdipDrawImageRectRectI(nativeObject, image.NativeObject,
destRect.X, destRect.Y, destRect.Width, destRect.Height,
srcX, srcY, srcWidth, srcHeight, srcUnit, IntPtr.Zero,
null, IntPtr.Zero);
@@ -910,7 +894,7 @@ namespace System.Drawing
{
if (image == null)
throw new ArgumentNullException("image");
- Status status = SafeNativeMethods.Gdip.GdipDrawImageRectRect(nativeObject, image.NativeObject,
+ int status = SafeNativeMethods.Gdip.GdipDrawImageRectRect(nativeObject, image.NativeObject,
destRect.X, destRect.Y, destRect.Width, destRect.Height,
srcX, srcY, srcWidth, srcHeight, srcUnit,
imageAttrs != null ? imageAttrs.nativeImageAttributes : IntPtr.Zero, null, IntPtr.Zero);
@@ -921,7 +905,7 @@ namespace System.Drawing
{
if (image == null)
throw new ArgumentNullException("image");
- Status status = SafeNativeMethods.Gdip.GdipDrawImageRectRectI(nativeObject, image.NativeObject,
+ int status = SafeNativeMethods.Gdip.GdipDrawImageRectRectI(nativeObject, image.NativeObject,
destRect.X, destRect.Y, destRect.Width,
destRect.Height, srcX, srcY, srcWidth, srcHeight,
srcUnit, imageAttr != null ? imageAttr.nativeImageAttributes : IntPtr.Zero, null, IntPtr.Zero);
@@ -932,7 +916,7 @@ namespace System.Drawing
{
if (image == null)
throw new ArgumentNullException("image");
- Status status = SafeNativeMethods.Gdip.GdipDrawImageRectRectI(nativeObject, image.NativeObject,
+ int status = SafeNativeMethods.Gdip.GdipDrawImageRectRectI(nativeObject, image.NativeObject,
destRect.X, destRect.Y, destRect.Width,
destRect.Height, srcX, srcY, srcWidth, srcHeight,
srcUnit, imageAttr != null ? imageAttr.nativeImageAttributes : IntPtr.Zero, callback,
@@ -944,7 +928,7 @@ namespace System.Drawing
{
if (image == null)
throw new ArgumentNullException("image");
- Status status = SafeNativeMethods.Gdip.GdipDrawImageRectRect(nativeObject, image.NativeObject,
+ int status = SafeNativeMethods.Gdip.GdipDrawImageRectRect(nativeObject, image.NativeObject,
destRect.X, destRect.Y, destRect.Width,
destRect.Height, srcX, srcY, srcWidth, srcHeight,
srcUnit, imageAttrs != null ? imageAttrs.nativeImageAttributes : IntPtr.Zero,
@@ -956,7 +940,7 @@ namespace System.Drawing
{
if (image == null)
throw new ArgumentNullException("image");
- Status status = SafeNativeMethods.Gdip.GdipDrawImageRectRect(nativeObject, image.NativeObject,
+ int status = SafeNativeMethods.Gdip.GdipDrawImageRectRect(nativeObject, image.NativeObject,
destRect.X, destRect.Y, destRect.Width, destRect.Height,
srcX, srcY, srcWidth, srcHeight, srcUnit,
imageAttrs != null ? imageAttrs.nativeImageAttributes : IntPtr.Zero, callback, callbackData);
@@ -967,7 +951,7 @@ namespace System.Drawing
{
if (image == null)
throw new ArgumentNullException("image");
- Status status = SafeNativeMethods.Gdip.GdipDrawImageRectRect(nativeObject, image.NativeObject,
+ int status = SafeNativeMethods.Gdip.GdipDrawImageRectRect(nativeObject, image.NativeObject,
destRect.X, destRect.Y, destRect.Width, destRect.Height,
srcX, srcY, srcWidth, srcHeight, srcUnit,
imageAttrs != null ? imageAttrs.nativeImageAttributes : IntPtr.Zero, callback, callbackData);
@@ -1025,7 +1009,7 @@ namespace System.Drawing
{
if (pen == null)
throw new ArgumentNullException("pen");
- Status status = SafeNativeMethods.Gdip.GdipDrawLine(nativeObject, pen.NativePen,
+ int status = SafeNativeMethods.Gdip.GdipDrawLine(nativeObject, pen.NativePen,
pt1.X, pt1.Y, pt2.X, pt2.Y);
SafeNativeMethods.Gdip.CheckStatus(status);
}
@@ -1034,7 +1018,7 @@ namespace System.Drawing
{
if (pen == null)
throw new ArgumentNullException("pen");
- Status status = SafeNativeMethods.Gdip.GdipDrawLineI(nativeObject, pen.NativePen,
+ int status = SafeNativeMethods.Gdip.GdipDrawLineI(nativeObject, pen.NativePen,
pt1.X, pt1.Y, pt2.X, pt2.Y);
SafeNativeMethods.Gdip.CheckStatus(status);
}
@@ -1043,7 +1027,7 @@ namespace System.Drawing
{
if (pen == null)
throw new ArgumentNullException("pen");
- Status status = SafeNativeMethods.Gdip.GdipDrawLineI(nativeObject, pen.NativePen, x1, y1, x2, y2);
+ int status = SafeNativeMethods.Gdip.GdipDrawLineI(nativeObject, pen.NativePen, x1, y1, x2, y2);
SafeNativeMethods.Gdip.CheckStatus(status);
}
@@ -1054,7 +1038,7 @@ namespace System.Drawing
if (!float.IsNaN(x1) && !float.IsNaN(y1) &&
!float.IsNaN(x2) && !float.IsNaN(y2))
{
- Status status = SafeNativeMethods.Gdip.GdipDrawLine(nativeObject, pen.NativePen, x1, y1, x2, y2);
+ int status = SafeNativeMethods.Gdip.GdipDrawLine(nativeObject, pen.NativePen, x1, y1, x2, y2);
SafeNativeMethods.Gdip.CheckStatus(status);
}
}
@@ -1065,7 +1049,7 @@ namespace System.Drawing
throw new ArgumentNullException("pen");
if (points == null)
throw new ArgumentNullException("points");
- Status status = SafeNativeMethods.Gdip.GdipDrawLines(nativeObject, pen.NativePen, points, points.Length);
+ int status = SafeNativeMethods.Gdip.GdipDrawLines(nativeObject, pen.NativePen, points, points.Length);
SafeNativeMethods.Gdip.CheckStatus(status);
}
@@ -1075,7 +1059,7 @@ namespace System.Drawing
throw new ArgumentNullException("pen");
if (points == null)
throw new ArgumentNullException("points");
- Status status = SafeNativeMethods.Gdip.GdipDrawLinesI(nativeObject, pen.NativePen, points, points.Length);
+ int status = SafeNativeMethods.Gdip.GdipDrawLinesI(nativeObject, pen.NativePen, points, points.Length);
SafeNativeMethods.Gdip.CheckStatus(status);
}
@@ -1085,7 +1069,7 @@ namespace System.Drawing
throw new ArgumentNullException("pen");
if (path == null)
throw new ArgumentNullException("path");
- Status status = SafeNativeMethods.Gdip.GdipDrawPath(nativeObject, pen.NativePen, path.nativePath);
+ int status = SafeNativeMethods.Gdip.GdipDrawPath(nativeObject, pen.NativePen, path.nativePath);
SafeNativeMethods.Gdip.CheckStatus(status);
}
@@ -1107,7 +1091,7 @@ namespace System.Drawing
{
if (pen == null)
throw new ArgumentNullException("pen");
- Status status = SafeNativeMethods.Gdip.GdipDrawPie(nativeObject, pen.NativePen, x, y, width, height, startAngle, sweepAngle);
+ int status = SafeNativeMethods.Gdip.GdipDrawPie(nativeObject, pen.NativePen, x, y, width, height, startAngle, sweepAngle);
SafeNativeMethods.Gdip.CheckStatus(status);
}
@@ -1118,7 +1102,7 @@ namespace System.Drawing
{
if (pen == null)
throw new ArgumentNullException("pen");
- Status status = SafeNativeMethods.Gdip.GdipDrawPieI(nativeObject, pen.NativePen, x, y, width, height, startAngle, sweepAngle);
+ int status = SafeNativeMethods.Gdip.GdipDrawPieI(nativeObject, pen.NativePen, x, y, width, height, startAngle, sweepAngle);
SafeNativeMethods.Gdip.CheckStatus(status);
}
@@ -1128,7 +1112,7 @@ namespace System.Drawing
throw new ArgumentNullException("pen");
if (points == null)
throw new ArgumentNullException("points");
- Status status = SafeNativeMethods.Gdip.GdipDrawPolygonI(nativeObject, pen.NativePen, points, points.Length);
+ int status = SafeNativeMethods.Gdip.GdipDrawPolygonI(nativeObject, pen.NativePen, points, points.Length);
SafeNativeMethods.Gdip.CheckStatus(status);
}
@@ -1138,7 +1122,7 @@ namespace System.Drawing
throw new ArgumentNullException("pen");
if (points == null)
throw new ArgumentNullException("points");
- Status status = SafeNativeMethods.Gdip.GdipDrawPolygon(nativeObject, pen.NativePen, points, points.Length);
+ int status = SafeNativeMethods.Gdip.GdipDrawPolygon(nativeObject, pen.NativePen, points, points.Length);
SafeNativeMethods.Gdip.CheckStatus(status);
}
@@ -1153,7 +1137,7 @@ namespace System.Drawing
{
if (pen == null)
throw new ArgumentNullException("pen");
- Status status = SafeNativeMethods.Gdip.GdipDrawRectangle(nativeObject, pen.NativePen, x, y, width, height);
+ int status = SafeNativeMethods.Gdip.GdipDrawRectangle(nativeObject, pen.NativePen, x, y, width, height);
SafeNativeMethods.Gdip.CheckStatus(status);
}
@@ -1161,7 +1145,7 @@ namespace System.Drawing
{
if (pen == null)
throw new ArgumentNullException("pen");
- Status status = SafeNativeMethods.Gdip.GdipDrawRectangleI(nativeObject, pen.NativePen, x, y, width, height);
+ int status = SafeNativeMethods.Gdip.GdipDrawRectangleI(nativeObject, pen.NativePen, x, y, width, height);
SafeNativeMethods.Gdip.CheckStatus(status);
}
@@ -1171,7 +1155,7 @@ namespace System.Drawing
throw new ArgumentNullException("image");
if (rects == null)
throw new ArgumentNullException("rects");
- Status status = SafeNativeMethods.Gdip.GdipDrawRectangles(nativeObject, pen.NativePen, rects, rects.Length);
+ int status = SafeNativeMethods.Gdip.GdipDrawRectangles(nativeObject, pen.NativePen, rects, rects.Length);
SafeNativeMethods.Gdip.CheckStatus(status);
}
@@ -1181,7 +1165,7 @@ namespace System.Drawing
throw new ArgumentNullException("image");
if (rects == null)
throw new ArgumentNullException("rects");
- Status status = SafeNativeMethods.Gdip.GdipDrawRectanglesI(nativeObject, pen.NativePen, rects, rects.Length);
+ int status = SafeNativeMethods.Gdip.GdipDrawRectanglesI(nativeObject, pen.NativePen, rects, rects.Length);
SafeNativeMethods.Gdip.CheckStatus(status);
}
@@ -1219,7 +1203,7 @@ namespace System.Drawing
if (s == null || s.Length == 0)
return;
- Status status = SafeNativeMethods.Gdip.GdipDrawString(nativeObject, s, s.Length, font.NativeObject, ref layoutRectangle, format != null ? format.nativeFormat : IntPtr.Zero, brush.NativeBrush);
+ int status = SafeNativeMethods.Gdip.GdipDrawString(nativeObject, s, s.Length, font.NativeObject, ref layoutRectangle, format != null ? format.nativeFormat : IntPtr.Zero, brush.NativeBrush);
SafeNativeMethods.Gdip.CheckStatus(status);
}
@@ -1455,7 +1439,7 @@ namespace System.Drawing
throw new ArgumentNullException("brush");
if (points == null)
throw new ArgumentNullException("points");
- Status status = SafeNativeMethods.Gdip.GdipFillClosedCurve(nativeObject, brush.NativeBrush, points, points.Length);
+ int status = SafeNativeMethods.Gdip.GdipFillClosedCurve(nativeObject, brush.NativeBrush, points, points.Length);
SafeNativeMethods.Gdip.CheckStatus(status);
}
@@ -1465,7 +1449,7 @@ namespace System.Drawing
throw new ArgumentNullException("brush");
if (points == null)
throw new ArgumentNullException("points");
- Status status = SafeNativeMethods.Gdip.GdipFillClosedCurveI(nativeObject, brush.NativeBrush, points, points.Length);
+ int status = SafeNativeMethods.Gdip.GdipFillClosedCurveI(nativeObject, brush.NativeBrush, points, points.Length);
SafeNativeMethods.Gdip.CheckStatus(status);
}
@@ -1494,7 +1478,7 @@ namespace System.Drawing
throw new ArgumentNullException("brush");
if (points == null)
throw new ArgumentNullException("points");
- Status status = SafeNativeMethods.Gdip.GdipFillClosedCurve2(nativeObject, brush.NativeBrush, points, points.Length, tension, fillmode);
+ int status = SafeNativeMethods.Gdip.GdipFillClosedCurve2(nativeObject, brush.NativeBrush, points, points.Length, tension, fillmode);
SafeNativeMethods.Gdip.CheckStatus(status);
}
@@ -1504,7 +1488,7 @@ namespace System.Drawing
throw new ArgumentNullException("brush");
if (points == null)
throw new ArgumentNullException("points");
- Status status = SafeNativeMethods.Gdip.GdipFillClosedCurve2I(nativeObject, brush.NativeBrush, points, points.Length, tension, fillmode);
+ int status = SafeNativeMethods.Gdip.GdipFillClosedCurve2I(nativeObject, brush.NativeBrush, points, points.Length, tension, fillmode);
SafeNativeMethods.Gdip.CheckStatus(status);
}
@@ -1526,7 +1510,7 @@ namespace System.Drawing
{
if (brush == null)
throw new ArgumentNullException("brush");
- Status status = SafeNativeMethods.Gdip.GdipFillEllipse(nativeObject, brush.NativeBrush, x, y, width, height);
+ int status = SafeNativeMethods.Gdip.GdipFillEllipse(nativeObject, brush.NativeBrush, x, y, width, height);
SafeNativeMethods.Gdip.CheckStatus(status);
}
@@ -1534,7 +1518,7 @@ namespace System.Drawing
{
if (brush == null)
throw new ArgumentNullException("brush");
- Status status = SafeNativeMethods.Gdip.GdipFillEllipseI(nativeObject, brush.NativeBrush, x, y, width, height);
+ int status = SafeNativeMethods.Gdip.GdipFillEllipseI(nativeObject, brush.NativeBrush, x, y, width, height);
SafeNativeMethods.Gdip.CheckStatus(status);
}
@@ -1544,7 +1528,7 @@ namespace System.Drawing
throw new ArgumentNullException("brush");
if (path == null)
throw new ArgumentNullException("path");
- Status status = SafeNativeMethods.Gdip.GdipFillPath(nativeObject, brush.NativeBrush, path.nativePath);
+ int status = SafeNativeMethods.Gdip.GdipFillPath(nativeObject, brush.NativeBrush, path.nativePath);
SafeNativeMethods.Gdip.CheckStatus(status);
}
@@ -1552,7 +1536,7 @@ namespace System.Drawing
{
if (brush == null)
throw new ArgumentNullException("brush");
- Status status = SafeNativeMethods.Gdip.GdipFillPie(nativeObject, brush.NativeBrush, rect.X, rect.Y, rect.Width, rect.Height, startAngle, sweepAngle);
+ int status = SafeNativeMethods.Gdip.GdipFillPie(nativeObject, brush.NativeBrush, rect.X, rect.Y, rect.Width, rect.Height, startAngle, sweepAngle);
SafeNativeMethods.Gdip.CheckStatus(status);
}
@@ -1560,7 +1544,7 @@ namespace System.Drawing
{
if (brush == null)
throw new ArgumentNullException("brush");
- Status status = SafeNativeMethods.Gdip.GdipFillPieI(nativeObject, brush.NativeBrush, x, y, width, height, startAngle, sweepAngle);
+ int status = SafeNativeMethods.Gdip.GdipFillPieI(nativeObject, brush.NativeBrush, x, y, width, height, startAngle, sweepAngle);
SafeNativeMethods.Gdip.CheckStatus(status);
}
@@ -1568,7 +1552,7 @@ namespace System.Drawing
{
if (brush == null)
throw new ArgumentNullException("brush");
- Status status = SafeNativeMethods.Gdip.GdipFillPie(nativeObject, brush.NativeBrush, x, y, width, height, startAngle, sweepAngle);
+ int status = SafeNativeMethods.Gdip.GdipFillPie(nativeObject, brush.NativeBrush, x, y, width, height, startAngle, sweepAngle);
SafeNativeMethods.Gdip.CheckStatus(status);
}
@@ -1578,7 +1562,7 @@ namespace System.Drawing
throw new ArgumentNullException("brush");
if (points == null)
throw new ArgumentNullException("points");
- Status status = SafeNativeMethods.Gdip.GdipFillPolygon2(nativeObject, brush.NativeBrush, points, points.Length);
+ int status = SafeNativeMethods.Gdip.GdipFillPolygon2(nativeObject, brush.NativeBrush, points, points.Length);
SafeNativeMethods.Gdip.CheckStatus(status);
}
@@ -1588,7 +1572,7 @@ namespace System.Drawing
throw new ArgumentNullException("brush");
if (points == null)
throw new ArgumentNullException("points");
- Status status = SafeNativeMethods.Gdip.GdipFillPolygon2I(nativeObject, brush.NativeBrush, points, points.Length);
+ int status = SafeNativeMethods.Gdip.GdipFillPolygon2I(nativeObject, brush.NativeBrush, points, points.Length);
SafeNativeMethods.Gdip.CheckStatus(status);
}
@@ -1598,7 +1582,7 @@ namespace System.Drawing
throw new ArgumentNullException("brush");
if (points == null)
throw new ArgumentNullException("points");
- Status status = SafeNativeMethods.Gdip.GdipFillPolygonI(nativeObject, brush.NativeBrush, points, points.Length, fillMode);
+ int status = SafeNativeMethods.Gdip.GdipFillPolygonI(nativeObject, brush.NativeBrush, points, points.Length, fillMode);
SafeNativeMethods.Gdip.CheckStatus(status);
}
@@ -1608,7 +1592,7 @@ namespace System.Drawing
throw new ArgumentNullException("brush");
if (points == null)
throw new ArgumentNullException("points");
- Status status = SafeNativeMethods.Gdip.GdipFillPolygon(nativeObject, brush.NativeBrush, points, points.Length, fillMode);
+ int status = SafeNativeMethods.Gdip.GdipFillPolygon(nativeObject, brush.NativeBrush, points, points.Length, fillMode);
SafeNativeMethods.Gdip.CheckStatus(status);
}
@@ -1631,7 +1615,7 @@ namespace System.Drawing
if (brush == null)
throw new ArgumentNullException("brush");
- Status status = SafeNativeMethods.Gdip.GdipFillRectangleI(nativeObject, brush.NativeBrush, x, y, width, height);
+ int status = SafeNativeMethods.Gdip.GdipFillRectangleI(nativeObject, brush.NativeBrush, x, y, width, height);
SafeNativeMethods.Gdip.CheckStatus(status);
}
@@ -1640,7 +1624,7 @@ namespace System.Drawing
if (brush == null)
throw new ArgumentNullException("brush");
- Status status = SafeNativeMethods.Gdip.GdipFillRectangle(nativeObject, brush.NativeBrush, x, y, width, height);
+ int status = SafeNativeMethods.Gdip.GdipFillRectangle(nativeObject, brush.NativeBrush, x, y, width, height);
SafeNativeMethods.Gdip.CheckStatus(status);
}
@@ -1651,7 +1635,7 @@ namespace System.Drawing
if (rects == null)
throw new ArgumentNullException("rects");
- Status status = SafeNativeMethods.Gdip.GdipFillRectanglesI(nativeObject, brush.NativeBrush, rects, rects.Length);
+ int status = SafeNativeMethods.Gdip.GdipFillRectanglesI(nativeObject, brush.NativeBrush, rects, rects.Length);
SafeNativeMethods.Gdip.CheckStatus(status);
}
@@ -1662,7 +1646,7 @@ namespace System.Drawing
if (rects == null)
throw new ArgumentNullException("rects");
- Status status = SafeNativeMethods.Gdip.GdipFillRectangles(nativeObject, brush.NativeBrush, rects, rects.Length);
+ int status = SafeNativeMethods.Gdip.GdipFillRectangles(nativeObject, brush.NativeBrush, rects, rects.Length);
SafeNativeMethods.Gdip.CheckStatus(status);
}
@@ -1674,7 +1658,7 @@ namespace System.Drawing
if (region == null)
throw new ArgumentNullException("region");
- Status status = (Status)SafeNativeMethods.Gdip.GdipFillRegion(new HandleRef(this, nativeObject), new HandleRef(brush, brush.NativeBrush), new HandleRef(region, region._nativeRegion));
+ int status = (int)SafeNativeMethods.Gdip.GdipFillRegion(new HandleRef(this, nativeObject), new HandleRef(brush, brush.NativeBrush), new HandleRef(region, region._nativeRegion));
SafeNativeMethods.Gdip.CheckStatus(status);
}
@@ -1692,7 +1676,7 @@ namespace System.Drawing
return;
}
- Status status = SafeNativeMethods.Gdip.GdipFlush(nativeObject, intention);
+ int status = SafeNativeMethods.Gdip.GdipFlush(nativeObject, intention);
SafeNativeMethods.Gdip.CheckStatus(status);
if (maccontext != null)
@@ -1703,7 +1687,7 @@ namespace System.Drawing
public static Graphics FromHdc(IntPtr hdc)
{
IntPtr graphics;
- Status status = SafeNativeMethods.Gdip.GdipCreateFromHDC(hdc, out graphics);
+ int status = SafeNativeMethods.Gdip.GdipCreateFromHDC(hdc, out graphics);
SafeNativeMethods.Gdip.CheckStatus(status);
return new Graphics(graphics);
}
@@ -1718,7 +1702,7 @@ namespace System.Drawing
[EditorBrowsable(EditorBrowsableState.Advanced)]
public static Graphics FromHdcInternal(IntPtr hdc)
{
- GDIPlus.Display = hdc;
+ SafeNativeMethods.Gdip.Display = hdc;
return null;
}
@@ -1727,7 +1711,7 @@ namespace System.Drawing
{
IntPtr graphics;
- if (GDIPlus.UseCocoaDrawable)
+ if (SafeNativeMethods.Gdip.UseCocoaDrawable)
{
CocoaContext context = MacSupport.GetCGContextForNSView(hwnd);
SafeNativeMethods.Gdip.GdipCreateFromContext_macosx(context.ctx, context.width, context.height, out graphics);
@@ -1738,7 +1722,7 @@ namespace System.Drawing
return g;
}
- if (GDIPlus.UseCarbonDrawable)
+ if (SafeNativeMethods.Gdip.UseCarbonDrawable)
{
CarbonContext context = MacSupport.GetCGContextForView(hwnd);
SafeNativeMethods.Gdip.GdipCreateFromContext_macosx(context.ctx, context.width, context.height, out graphics);
@@ -1748,24 +1732,24 @@ namespace System.Drawing
return g;
}
- if (GDIPlus.UseX11Drawable)
+ if (SafeNativeMethods.Gdip.UseX11Drawable)
{
- if (GDIPlus.Display == IntPtr.Zero)
+ if (SafeNativeMethods.Gdip.Display == IntPtr.Zero)
{
- GDIPlus.Display = GDIPlus.XOpenDisplay(IntPtr.Zero);
- if (GDIPlus.Display == IntPtr.Zero)
+ SafeNativeMethods.Gdip.Display = LibX11Functions.XOpenDisplay(IntPtr.Zero);
+ if (SafeNativeMethods.Gdip.Display == IntPtr.Zero)
throw new NotSupportedException("Could not open display (X-Server required. Check your DISPLAY environment variable)");
}
if (hwnd == IntPtr.Zero)
{
- hwnd = GDIPlus.XRootWindow(GDIPlus.Display, GDIPlus.XDefaultScreen(GDIPlus.Display));
+ hwnd = LibX11Functions.XRootWindow(SafeNativeMethods.Gdip.Display, LibX11Functions.XDefaultScreen(SafeNativeMethods.Gdip.Display));
}
- return FromXDrawable(hwnd, GDIPlus.Display);
+ return FromXDrawable(hwnd, SafeNativeMethods.Gdip.Display);
}
- Status status = SafeNativeMethods.Gdip.GdipCreateFromHWND(hwnd, out graphics);
+ int status = SafeNativeMethods.Gdip.GdipCreateFromHWND(hwnd, out graphics);
SafeNativeMethods.Gdip.CheckStatus(status);
return new Graphics(graphics);
@@ -1787,15 +1771,12 @@ namespace System.Drawing
if ((image.PixelFormat & PixelFormat.Indexed) != 0)
throw new Exception("Cannot create Graphics from an indexed bitmap.");
- Status status = SafeNativeMethods.Gdip.GdipGetImageGraphicsContext(image.nativeObject, out graphics);
+ int status = SafeNativeMethods.Gdip.GdipGetImageGraphicsContext(image.nativeObject, out graphics);
SafeNativeMethods.Gdip.CheckStatus(status);
Graphics result = new Graphics(graphics);
- if (GDIPlus.RunningOnUnix())
- {
- Rectangle rect = new Rectangle(0, 0, image.Width, image.Height);
- SafeNativeMethods.Gdip.GdipSetVisibleClip_linux(result.NativeObject, ref rect);
- }
+ Rectangle rect = new Rectangle(0, 0, image.Width, image.Height);
+ SafeNativeMethods.Gdip.GdipSetVisibleClip_linux(result.NativeObject, ref rect);
return result;
}
@@ -1804,7 +1785,7 @@ namespace System.Drawing
{
IntPtr graphics;
- Status s = SafeNativeMethods.Gdip.GdipCreateFromXDrawable_linux(drawable, display, out graphics);
+ int s = SafeNativeMethods.Gdip.GdipCreateFromXDrawable_linux(drawable, display, out graphics);
SafeNativeMethods.Gdip.CheckStatus(s);
return new Graphics(graphics);
}
@@ -1825,7 +1806,7 @@ namespace System.Drawing
{
int argb;
- Status status = SafeNativeMethods.Gdip.GdipGetNearestColor(nativeObject, out argb);
+ int status = SafeNativeMethods.Gdip.GdipGetNearestColor(nativeObject, out argb);
SafeNativeMethods.Gdip.CheckStatus(status);
return Color.FromArgb(argb);
@@ -1855,7 +1836,7 @@ namespace System.Drawing
native_regions[i] = regions[i]._nativeRegion;
}
- Status status = SafeNativeMethods.Gdip.GdipMeasureCharacterRanges(nativeObject, text, text.Length,
+ int status = SafeNativeMethods.Gdip.GdipMeasureCharacterRanges(nativeObject, text, text.Length,
font.NativeObject, ref layoutRect, stringFormat.nativeFormat, regcount, out native_regions[0]);
SafeNativeMethods.Gdip.CheckStatus(status);
@@ -1873,7 +1854,7 @@ namespace System.Drawing
RectangleF boundingBox = new RectangleF();
- Status status = SafeNativeMethods.Gdip.GdipMeasureString(nativeObject, text, text.Length, font.NativeObject,
+ int status = SafeNativeMethods.Gdip.GdipMeasureString(nativeObject, text, text.Length, font.NativeObject,
ref layoutRect, stringFormat, out boundingBox, null, null);
SafeNativeMethods.Gdip.CheckStatus(status);
@@ -1939,7 +1920,7 @@ namespace System.Drawing
{
fixed (int* pc = &charactersFitted, pl = &linesFilled)
{
- Status status = SafeNativeMethods.Gdip.GdipMeasureString(nativeObject, text, text.Length,
+ int status = SafeNativeMethods.Gdip.GdipMeasureString(nativeObject, text, text.Length,
font.NativeObject, ref rect, format, out boundingBox, pc, pl);
SafeNativeMethods.Gdip.CheckStatus(status);
}
@@ -1962,7 +1943,7 @@ namespace System.Drawing
[EditorBrowsable(EditorBrowsableState.Never)]
public void ReleaseHdcInternal(IntPtr hdc)
{
- Status status = Status.InvalidParameter;
+ int status = SafeNativeMethods.Gdip.InvalidParameter;
if (hdc == deviceContextHdc)
{
status = SafeNativeMethods.Gdip.GdipReleaseDC(nativeObject, deviceContextHdc);
@@ -1974,14 +1955,14 @@ namespace System.Drawing
public void Restore(GraphicsState gstate)
{
// the possible NRE thrown by gstate.nativeState match MS behaviour
- Status status = SafeNativeMethods.Gdip.GdipRestoreGraphics(nativeObject, (uint)gstate.nativeState);
+ int status = SafeNativeMethods.Gdip.GdipRestoreGraphics(nativeObject, (uint)gstate.nativeState);
SafeNativeMethods.Gdip.CheckStatus(status);
}
public GraphicsState Save()
{
uint saveState;
- Status status = SafeNativeMethods.Gdip.GdipSaveGraphics(nativeObject, out saveState);
+ int status = SafeNativeMethods.Gdip.GdipSaveGraphics(nativeObject, out saveState);
SafeNativeMethods.Gdip.CheckStatus(status);
GraphicsState state = new GraphicsState((int)saveState);
@@ -1994,12 +1975,12 @@ namespace System.Drawing
if (pts == null)
throw new ArgumentNullException("pts");
- IntPtr ptrPt = GDIPlus.FromPointToUnManagedMemory(pts);
+ IntPtr ptrPt = MarshallingHelpers.FromPointToUnManagedMemory(pts);
- Status status = SafeNativeMethods.Gdip.GdipTransformPoints(nativeObject, destSpace, srcSpace, ptrPt, pts.Length);
+ int status = SafeNativeMethods.Gdip.GdipTransformPoints(nativeObject, destSpace, srcSpace, ptrPt, pts.Length);
SafeNativeMethods.Gdip.CheckStatus(status);
- GDIPlus.FromUnManagedMemoryToPoint(ptrPt, pts);
+ MarshallingHelpers.FromUnManagedMemoryToPoint(ptrPt, pts);
}
@@ -2007,12 +1988,12 @@ namespace System.Drawing
{
if (pts == null)
throw new ArgumentNullException("pts");
- IntPtr ptrPt = GDIPlus.FromPointToUnManagedMemoryI(pts);
+ IntPtr ptrPt = MarshallingHelpers.FromPointToUnManagedMemoryI(pts);
- Status status = SafeNativeMethods.Gdip.GdipTransformPointsI(nativeObject, destSpace, srcSpace, ptrPt, pts.Length);
+ int status = SafeNativeMethods.Gdip.GdipTransformPointsI(nativeObject, destSpace, srcSpace, ptrPt, pts.Length);
SafeNativeMethods.Gdip.CheckStatus(status);
- GDIPlus.FromUnManagedMemoryToPointI(ptrPt, pts);
+ MarshallingHelpers.FromUnManagedMemoryToPointI(ptrPt, pts);
}
public CompositingMode CompositingMode
@@ -2020,14 +2001,14 @@ namespace System.Drawing
get
{
CompositingMode mode;
- Status status = SafeNativeMethods.Gdip.GdipGetCompositingMode(nativeObject, out mode);
+ int status = SafeNativeMethods.Gdip.GdipGetCompositingMode(nativeObject, out mode);
SafeNativeMethods.Gdip.CheckStatus(status);
return mode;
}
set
{
- Status status = SafeNativeMethods.Gdip.GdipSetCompositingMode(nativeObject, value);
+ int status = SafeNativeMethods.Gdip.GdipSetCompositingMode(nativeObject, value);
SafeNativeMethods.Gdip.CheckStatus(status);
}
@@ -2039,13 +2020,13 @@ namespace System.Drawing
{
CompositingQuality quality;
- Status status = SafeNativeMethods.Gdip.GdipGetCompositingQuality(nativeObject, out quality);
+ int status = SafeNativeMethods.Gdip.GdipGetCompositingQuality(nativeObject, out quality);
SafeNativeMethods.Gdip.CheckStatus(status);
return quality;
}
set
{
- Status status = SafeNativeMethods.Gdip.GdipSetCompositingQuality(nativeObject, value);
+ int status = SafeNativeMethods.Gdip.GdipSetCompositingQuality(nativeObject, value);
SafeNativeMethods.Gdip.CheckStatus(status);
}
}
@@ -2056,7 +2037,7 @@ namespace System.Drawing
{
float x;
- Status status = SafeNativeMethods.Gdip.GdipGetDpiX(nativeObject, out x);
+ int status = SafeNativeMethods.Gdip.GdipGetDpiX(nativeObject, out x);
SafeNativeMethods.Gdip.CheckStatus(status);
return x;
}
@@ -2068,7 +2049,7 @@ namespace System.Drawing
{
float y;
- Status status = SafeNativeMethods.Gdip.GdipGetDpiY(nativeObject, out y);
+ int status = SafeNativeMethods.Gdip.GdipGetDpiY(nativeObject, out y);
SafeNativeMethods.Gdip.CheckStatus(status);
return y;
}
@@ -2079,13 +2060,13 @@ namespace System.Drawing
get
{
InterpolationMode imode = InterpolationMode.Invalid;
- Status status = SafeNativeMethods.Gdip.GdipGetInterpolationMode(nativeObject, out imode);
+ int status = SafeNativeMethods.Gdip.GdipGetInterpolationMode(nativeObject, out imode);
SafeNativeMethods.Gdip.CheckStatus(status);
return imode;
}
set
{
- Status status = SafeNativeMethods.Gdip.GdipSetInterpolationMode(nativeObject, value);
+ int status = SafeNativeMethods.Gdip.GdipSetInterpolationMode(nativeObject, value);
SafeNativeMethods.Gdip.CheckStatus(status);
}
}
@@ -2096,13 +2077,13 @@ namespace System.Drawing
{
float scale;
- Status status = SafeNativeMethods.Gdip.GdipGetPageScale(nativeObject, out scale);
+ int status = SafeNativeMethods.Gdip.GdipGetPageScale(nativeObject, out scale);
SafeNativeMethods.Gdip.CheckStatus(status);
return scale;
}
set
{
- Status status = SafeNativeMethods.Gdip.GdipSetPageScale(nativeObject, value);
+ int status = SafeNativeMethods.Gdip.GdipSetPageScale(nativeObject, value);
SafeNativeMethods.Gdip.CheckStatus(status);
}
}
@@ -2113,13 +2094,13 @@ namespace System.Drawing
{
GraphicsUnit unit;
- Status status = SafeNativeMethods.Gdip.GdipGetPageUnit(nativeObject, out unit);
+ int status = SafeNativeMethods.Gdip.GdipGetPageUnit(nativeObject, out unit);
SafeNativeMethods.Gdip.CheckStatus(status);
return unit;
}
set
{
- Status status = SafeNativeMethods.Gdip.GdipSetPageUnit(nativeObject, value);
+ int status = SafeNativeMethods.Gdip.GdipSetPageUnit(nativeObject, value);
SafeNativeMethods.Gdip.CheckStatus(status);
}
}
@@ -2131,13 +2112,13 @@ namespace System.Drawing
{
PixelOffsetMode pixelOffset = PixelOffsetMode.Invalid;
- Status status = SafeNativeMethods.Gdip.GdipGetPixelOffsetMode(nativeObject, out pixelOffset);
+ int status = SafeNativeMethods.Gdip.GdipGetPixelOffsetMode(nativeObject, out pixelOffset);
SafeNativeMethods.Gdip.CheckStatus(status);
return pixelOffset;
}
set
{
- Status status = SafeNativeMethods.Gdip.GdipSetPixelOffsetMode(nativeObject, value);
+ int status = SafeNativeMethods.Gdip.GdipSetPixelOffsetMode(nativeObject, value);
SafeNativeMethods.Gdip.CheckStatus(status);
}
}
@@ -2147,14 +2128,14 @@ namespace System.Drawing
get
{
int x, y;
- Status status = SafeNativeMethods.Gdip.GdipGetRenderingOrigin(nativeObject, out x, out y);
+ int status = SafeNativeMethods.Gdip.GdipGetRenderingOrigin(nativeObject, out x, out y);
SafeNativeMethods.Gdip.CheckStatus(status);
return new Point(x, y);
}
set
{
- Status status = SafeNativeMethods.Gdip.GdipSetRenderingOrigin(nativeObject, value.X, value.Y);
+ int status = SafeNativeMethods.Gdip.GdipSetRenderingOrigin(nativeObject, value.X, value.Y);
SafeNativeMethods.Gdip.CheckStatus(status);
}
}
@@ -2165,14 +2146,14 @@ namespace System.Drawing
{
SmoothingMode mode = SmoothingMode.Invalid;
- Status status = SafeNativeMethods.Gdip.GdipGetSmoothingMode(nativeObject, out mode);
+ int status = SafeNativeMethods.Gdip.GdipGetSmoothingMode(nativeObject, out mode);
SafeNativeMethods.Gdip.CheckStatus(status);
return mode;
}
set
{
- Status status = SafeNativeMethods.Gdip.GdipSetSmoothingMode(nativeObject, value);
+ int status = SafeNativeMethods.Gdip.GdipSetSmoothingMode(nativeObject, value);
SafeNativeMethods.Gdip.CheckStatus(status);
}
}
@@ -2184,14 +2165,14 @@ namespace System.Drawing
{
int contrast;
- Status status = SafeNativeMethods.Gdip.GdipGetTextContrast(nativeObject, out contrast);
+ int status = SafeNativeMethods.Gdip.GdipGetTextContrast(nativeObject, out contrast);
SafeNativeMethods.Gdip.CheckStatus(status);
return contrast;
}
set
{
- Status status = SafeNativeMethods.Gdip.GdipSetTextContrast(nativeObject, value);
+ int status = SafeNativeMethods.Gdip.GdipSetTextContrast(nativeObject, value);
SafeNativeMethods.Gdip.CheckStatus(status);
}
}
@@ -2202,14 +2183,14 @@ namespace System.Drawing
{
TextRenderingHint hint;
- Status status = SafeNativeMethods.Gdip.GdipGetTextRenderingHint(nativeObject, out hint);
+ int status = SafeNativeMethods.Gdip.GdipGetTextRenderingHint(nativeObject, out hint);
SafeNativeMethods.Gdip.CheckStatus(status);
return hint;
}
set
{
- Status status = SafeNativeMethods.Gdip.GdipSetTextRenderingHint(nativeObject, value);
+ int status = SafeNativeMethods.Gdip.GdipSetTextRenderingHint(nativeObject, value);
SafeNativeMethods.Gdip.CheckStatus(status);
}
}
diff --git a/src/System.Drawing.Common/src/System/Drawing/Unit.cs b/src/System.Drawing.Common/src/System/Drawing/GraphicsUnit.cs
index c1a71a009a..c1a71a009a 100644
--- a/src/System.Drawing.Common/src/System/Drawing/Unit.cs
+++ b/src/System.Drawing.Common/src/System/Drawing/GraphicsUnit.cs
diff --git a/src/System.Drawing.Common/src/System/Drawing/Icon.Serializable.Unix.cs b/src/System.Drawing.Common/src/System/Drawing/Icon.Serializable.Unix.cs
new file mode 100644
index 0000000000..c75a01d948
--- /dev/null
+++ b/src/System.Drawing.Common/src/System/Drawing/Icon.Serializable.Unix.cs
@@ -0,0 +1,50 @@
+// 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.Runtime.Serialization;
+using System.Security.Permissions;
+
+namespace System.Drawing
+{
+ [Serializable]
+ partial class Icon
+ {
+ private const string IconSizeSerializationName = "IconSize";
+ private const string IconDataSerializationName = "IconData";
+
+ private Icon(SerializationInfo info, StreamingContext context)
+ {
+ MemoryStream dataStream = null;
+ int width = 0;
+ int height = 0;
+ foreach (SerializationEntry serEnum in info)
+ {
+ if (string.Equals(serEnum.Name, IconDataSerializationName, StringComparison.CurrentCultureIgnoreCase))
+ {
+ dataStream = new MemoryStream((byte[])serEnum.Value);
+ }
+ if (string.Equals(serEnum.Name, IconSizeSerializationName, StringComparison.CurrentCultureIgnoreCase))
+ {
+ Size iconSize = (Size)serEnum.Value;
+ width = iconSize.Width;
+ height = iconSize.Height;
+ }
+ }
+ if (dataStream != null)
+ {
+ dataStream.Seek(0, SeekOrigin.Begin);
+ InitFromStreamWithSize(dataStream, width, height);
+ }
+ }
+
+ void ISerializable.GetObjectData(SerializationInfo si, StreamingContext context)
+ {
+ MemoryStream ms = new MemoryStream();
+ Save(ms);
+ si.AddValue(IconSizeSerializationName, this.Size, typeof(Size));
+ si.AddValue(IconDataSerializationName, ms.ToArray());
+ }
+ }
+}
diff --git a/src/System.Drawing.Common/src/System/Drawing/Icon.Serializable.cs b/src/System.Drawing.Common/src/System/Drawing/Icon.Serializable.Windows.cs
index 8cd871c9b8..8cd871c9b8 100644
--- a/src/System.Drawing.Common/src/System/Drawing/Icon.Serializable.cs
+++ b/src/System.Drawing.Common/src/System/Drawing/Icon.Serializable.Windows.cs
diff --git a/src/System.Drawing.Common/src/Unix/System.Drawing/Icon.cs b/src/System.Drawing.Common/src/System/Drawing/Icon.Unix.cs
index 8d1b453025..26f6f183e3 100644
--- a/src/System.Drawing.Common/src/Unix/System.Drawing/Icon.cs
+++ b/src/System.Drawing.Common/src/System/Drawing/Icon.Unix.cs
@@ -44,14 +44,13 @@ using System.Runtime.InteropServices;
namespace System.Drawing
{
- [Serializable]
#if !NETCORE
#if !MONOTOUCH
[Editor ("System.Drawing.Design.IconEditor, " + Consts.AssemblySystem_Drawing_Design, typeof (System.Drawing.Design.UITypeEditor))]
#endif
[TypeConverter(typeof(IconConverter))]
#endif
- public sealed class Icon : MarshalByRefObject, ISerializable, ICloneable, IDisposable
+ public sealed partial class Icon : MarshalByRefObject, ISerializable, ICloneable, IDisposable
{
[StructLayout(LayoutKind.Sequential)]
internal struct IconDirEntry
@@ -131,23 +130,9 @@ namespace System.Drawing
this.handle = handle;
bitmap = Bitmap.FromHicon(handle);
iconSize = new Size(bitmap.Width, bitmap.Height);
- if (GDIPlus.RunningOnUnix())
- {
- bitmap = Bitmap.FromHicon(handle);
- iconSize = new Size(bitmap.Width, bitmap.Height);
- // FIXME: we need to convert the bitmap into an icon
- }
- else
- {
- IconInfo ii;
- GDIPlus.GetIconInfo(handle, out ii);
- if (!ii.IsIcon)
- throw new NotImplementedException("Handle doesn't represent an ICON.");
-
- // If this structure defines an icon, the hot spot is always in the center of the icon
- iconSize = new Size(ii.xHotspot * 2, ii.yHotspot * 2);
- bitmap = (Bitmap)Image.FromHbitmap(ii.hbmColor);
- }
+ bitmap = Bitmap.FromHicon(handle);
+ iconSize = new Size(bitmap.Width, bitmap.Height);
+ // FIXME: we need to convert the bitmap into an icon
undisposable = true;
}
#endif
@@ -160,7 +145,7 @@ namespace System.Drawing
public Icon(Icon original, Size size)
{
if (original == null)
- throw new ArgumentException("original");
+ throw new ArgumentNullException(nameof(original));
iconSize = size;
iconDir = original.iconDir;
@@ -264,37 +249,13 @@ namespace System.Drawing
{
if (s == null)
{
- string msg = string.Format("Resource '{0}' was not found.", resource);
- throw new FileNotFoundException(msg);
+ throw new ArgumentException(null);
}
InitFromStreamWithSize(s, 32, 32); // 32x32 is default
}
}
- private Icon(SerializationInfo info, StreamingContext context)
- {
- MemoryStream dataStream = null;
- int width = 0;
- int height = 0;
- foreach (SerializationEntry serEnum in info)
- {
- if (String.Compare(serEnum.Name, "IconData", true) == 0)
- {
- dataStream = new MemoryStream((byte[])serEnum.Value);
- }
- if (String.Compare(serEnum.Name, "IconSize", true) == 0)
- {
- Size iconSize = (Size)serEnum.Value;
- width = iconSize.Width;
- height = iconSize.Height;
- }
- }
- if (dataStream != null)
- {
- dataStream.Seek(0, SeekOrigin.Begin);
- InitFromStreamWithSize(dataStream, width, height);
- }
- }
+
internal Icon(string resourceName, bool undisposable)
{
@@ -310,14 +271,6 @@ namespace System.Drawing
this.undisposable = true;
}
- void ISerializable.GetObjectData(SerializationInfo si, StreamingContext context)
- {
- MemoryStream ms = new MemoryStream();
- Save(ms);
- si.AddValue("IconSize", this.Size, typeof(Size));
- si.AddValue("IconData", ms.ToArray());
- }
-
public Icon(Stream stream, Size size) :
this(stream, size.Width, size.Height)
{
@@ -342,8 +295,10 @@ namespace System.Drawing
[MonoLimitation("The same icon, SystemIcons.WinLogo, is returned for all file types.")]
public static Icon ExtractAssociatedIcon(string filePath)
{
+ if (filePath == null)
+ throw new ArgumentNullException(nameof(filePath));
if (String.IsNullOrEmpty(filePath))
- throw new ArgumentException("Null or empty path.", "filePath");
+ throw new ArgumentException("Null or empty path.", "path");
if (!File.Exists(filePath))
throw new FileNotFoundException("Couldn't find specified file.", filePath);
@@ -358,13 +313,6 @@ namespace System.Drawing
if (!disposed)
{
-#if !MONOTOUCH
- if (GDIPlus.RunningOnWindows() && (handle != IntPtr.Zero))
- {
- GDIPlus.DestroyIcon(handle);
- handle = IntPtr.Zero;
- }
-#endif
if (bitmap != null)
{
bitmap.Dispose();
@@ -655,24 +603,15 @@ namespace System.Drawing
{
if (bitmap == null)
{
- if (GDIPlus.RunningOnUnix())
+ // Mono's libgdiplus doesn't require to keep the stream alive when loading images
+ using (MemoryStream ms = new MemoryStream())
{
- // Mono's libgdiplus doesn't require to keep the stream alive when loading images
- using (MemoryStream ms = new MemoryStream())
- {
- // save the current icon
- Save(ms, Width, Height);
- ms.Position = 0;
+ // save the current icon
+ Save(ms, Width, Height);
+ ms.Position = 0;
- // libgdiplus can now decode icons
- bitmap = (Bitmap)Image.LoadFromStream(ms, false);
- }
- }
- else
- {
- // MS GDI+ ICO codec is more limited than the MS Icon class
- // so we can't, reliably, get bitmap using it. We need to do this the "slow" way
- bitmap = BuildBitmapOnWin32();
+ // libgdiplus can now decode icons
+ bitmap = (Bitmap)Image.LoadFromStream(ms, false);
}
}
return bitmap;
@@ -703,22 +642,15 @@ namespace System.Drawing
{
get
{
+ if (disposed)
+ {
+ throw new ObjectDisposedException(GetType().Name);
+ }
+
// note: this handle doesn't survive the lifespan of the icon instance
- if (!disposed && (handle == IntPtr.Zero))
+ if (handle == IntPtr.Zero)
{
- if (GDIPlus.RunningOnUnix())
- {
- handle = GetInternalBitmap().NativeObject;
- }
- else
- {
- // remember that this block executes only with MS GDI+
- IconInfo ii = new IconInfo();
- ii.IsIcon = true;
- ii.hbmColor = ToBitmap().GetHbitmap();
- ii.hbmMask = ii.hbmColor;
- handle = GDIPlus.CreateIconIndirect(ref ii);
- }
+ handle = GetInternalBitmap().NativeObject;
}
return handle;
}
@@ -729,6 +661,11 @@ namespace System.Drawing
{
get
{
+ if (disposed)
+ {
+ throw new ObjectDisposedException(GetType().Name);
+ }
+
return iconSize.Height;
}
}
@@ -737,6 +674,11 @@ namespace System.Drawing
{
get
{
+ if (disposed)
+ {
+ throw new ObjectDisposedException(GetType().Name);
+ }
+
return iconSize;
}
}
@@ -746,6 +688,11 @@ namespace System.Drawing
{
get
{
+ if (disposed)
+ {
+ throw new ObjectDisposedException(GetType().Name);
+ }
+
return iconSize.Width;
}
}
@@ -757,10 +704,13 @@ namespace System.Drawing
private void InitFromStreamWithSize(Stream stream, int width, int height)
{
- //read the icon header
- if (stream == null || stream.Length == 0)
+ if (stream == null)
+ throw new ArgumentNullException(nameof(stream));
+
+ if (stream.Length == 0)
throw new System.ArgumentException("The argument 'stream' must be a picture that can be used as a Icon", "stream");
+ //read the icon header
BinaryReader reader = new BinaryReader(stream);
//iconDir = new IconDir ();
@@ -789,17 +739,7 @@ namespace System.Drawing
ide.bitCount = reader.ReadUInt16();
ide.bytesInRes = reader.ReadUInt32();
ide.imageOffset = reader.ReadUInt32();
-#if false
-Console.WriteLine ("Entry: {0}", i);
-Console.WriteLine ("\tide.width: {0}", ide.width);
-Console.WriteLine ("\tide.height: {0}", ide.height);
-Console.WriteLine ("\tide.colorCount: {0}", ide.colorCount);
-Console.WriteLine ("\tide.reserved: {0}", ide.reserved);
-Console.WriteLine ("\tide.planes: {0}", ide.planes);
-Console.WriteLine ("\tide.bitCount: {0}", ide.bitCount);
-Console.WriteLine ("\tide.bytesInRes: {0}", ide.bytesInRes);
-Console.WriteLine ("\tide.imageOffset: {0}", ide.imageOffset);
-#endif
+
// Vista 256x256 icons points directly to a PNG bitmap
// 256x256 icons are decoded as 0x0 (width and height are encoded as BYTE)
// and we ignore them just like MS does (at least up to fx 2.0)
@@ -883,20 +823,6 @@ Console.WriteLine ("\tide.imageOffset: {0}", ide.imageOffset);
bih.biYPelsPerMeter = bihReader.ReadInt32();
bih.biClrUsed = bihReader.ReadUInt32();
bih.biClrImportant = bihReader.ReadUInt32();
-#if false
-Console.WriteLine ("Entry: {0}", j);
-Console.WriteLine ("\tbih.biSize: {0}", bih.biSize);
-Console.WriteLine ("\tbih.biWidth: {0}", bih.biWidth);
-Console.WriteLine ("\tbih.biHeight: {0}", bih.biHeight);
-Console.WriteLine ("\tbih.biPlanes: {0}", bih.biPlanes);
-Console.WriteLine ("\tbih.biBitCount: {0}", bih.biBitCount);
-Console.WriteLine ("\tbih.biCompression: {0}", bih.biCompression);
-Console.WriteLine ("\tbih.biSizeImage: {0}", bih.biSizeImage);
-Console.WriteLine ("\tbih.biXPelsPerMeter: {0}", bih.biXPelsPerMeter);
-Console.WriteLine ("\tbih.biYPelsPerMeter: {0}", bih.biYPelsPerMeter);
-Console.WriteLine ("\tbih.biClrUsed: {0}", bih.biClrUsed);
-Console.WriteLine ("\tbih.biClrImportant: {0}", bih.biClrImportant);
-#endif
iidata.iconHeader = bih;
//Read the number of colors used and corresponding memory occupied by
//color table. Fill this memory chunk into rgbquad[]
diff --git a/src/System.Drawing.Common/src/System/Drawing/Icon.cs b/src/System.Drawing.Common/src/System/Drawing/Icon.Windows.cs
index 0d38d257e5..0d38d257e5 100644
--- a/src/System.Drawing.Common/src/System/Drawing/Icon.cs
+++ b/src/System.Drawing.Common/src/System/Drawing/Icon.Windows.cs
diff --git a/src/System.Drawing.Common/src/Unix/System.Drawing/Image.cs b/src/System.Drawing.Common/src/System/Drawing/Image.Unix.cs
index 0ef118e4ba..30b1ed2a6e 100644
--- a/src/System.Drawing.Common/src/Unix/System.Drawing/Image.cs
+++ b/src/System.Drawing.Common/src/System/Drawing/Image.Unix.cs
@@ -57,10 +57,6 @@ namespace System.Drawing
private object tag;
internal IntPtr nativeObject = IntPtr.Zero;
- // when using MS GDI+ and IStream we must ensure the stream stays alive for all the life of the Image
- // http://groups.google.com/group/microsoft.public.win32.programmer.gdi/browse_thread/thread/4967097db1469a27/4d36385b83532126?lnk=st&q=IStream+gdi&rnum=3&hl=en#4d36385b83532126
- internal Stream stream;
-
// constructor
internal Image()
@@ -83,9 +79,6 @@ namespace System.Drawing
{
MemoryStream ms = new MemoryStream(bytes);
nativeObject = InitFromStream(ms);
- // under Win32 stream is owned by SD/GDI+ code
- if (GDIPlus.RunningOnWindows())
- stream = ms;
}
}
}
@@ -119,7 +112,7 @@ namespace System.Drawing
public static Image FromFile(string filename, bool useEmbeddedColorManagement)
{
IntPtr imagePtr;
- Status st;
+ int st;
if (!File.Exists(filename))
throw new FileNotFoundException(filename);
@@ -141,7 +134,7 @@ namespace System.Drawing
public static Bitmap FromHbitmap(IntPtr hbitmap, IntPtr hpalette)
{
IntPtr imagePtr;
- Status st;
+ int st;
st = SafeNativeMethods.Gdip.GdipCreateBitmapFromHBITMAP(hbitmap, hpalette, out imagePtr);
@@ -175,12 +168,6 @@ namespace System.Drawing
throw new ArgumentNullException("stream");
Image img = CreateFromHandle(InitFromStream(stream));
-
- // Under Windows, we may need to keep a reference on the stream as long as the image is alive
- // (GDI+ seems to use a lazy loader)
- if (keepAlive && GDIPlus.RunningOnWindows())
- img.stream = stream;
-
return img;
}
@@ -283,10 +270,10 @@ namespace System.Drawing
internal static IntPtr InitFromStream(Stream stream)
{
if (stream == null)
- throw new ArgumentException("stream");
+ throw new ArgumentNullException(nameof(stream));
IntPtr imagePtr;
- Status st;
+ int st;
// Seeking required
if (!stream.CanSeek)
@@ -311,23 +298,16 @@ namespace System.Drawing
stream = new MemoryStream(buffer, 0, index);
}
- if (GDIPlus.RunningOnUnix())
- {
- // Unix, with libgdiplus
- // We use a custom API for this, because there's no easy way
- // to get the Stream down to libgdiplus. So, we wrap the stream
- // with a set of delegates.
- GDIPlus.GdiPlusStreamHelper sh = new GDIPlus.GdiPlusStreamHelper(stream, true);
+ // Unix, with libgdiplus
+ // We use a custom API for this, because there's no easy way
+ // to get the Stream down to libgdiplus. So, we wrap the stream
+ // with a set of delegates.
+ GdiPlusStreamHelper sh = new GdiPlusStreamHelper(stream, true);
- st = SafeNativeMethods.Gdip.GdipLoadImageFromDelegate_linux(sh.GetHeaderDelegate, sh.GetBytesDelegate,
- sh.PutBytesDelegate, sh.SeekDelegate, sh.CloseDelegate, sh.SizeDelegate, out imagePtr);
- }
- else
- {
- st = SafeNativeMethods.Gdip.GdipLoadImageFromStream(new ComIStreamWrapper(stream), out imagePtr);
- }
+ st = SafeNativeMethods.Gdip.GdipLoadImageFromDelegate_linux(sh.GetHeaderDelegate, sh.GetBytesDelegate,
+ sh.PutBytesDelegate, sh.SeekDelegate, sh.CloseDelegate, sh.SizeDelegate, out imagePtr);
- return st == Status.Ok ? imagePtr : IntPtr.Zero;
+ return st == SafeNativeMethods.Gdip.Ok ? imagePtr : IntPtr.Zero;
}
// non-static
@@ -335,7 +315,7 @@ namespace System.Drawing
{
RectangleF source;
- Status status = SafeNativeMethods.Gdip.GdipGetImageBounds(nativeObject, out source, ref pageUnit);
+ int status = SafeNativeMethods.Gdip.GdipGetImageBounds(nativeObject, out source, ref pageUnit);
SafeNativeMethods.Gdip.CheckStatus(status);
return source;
@@ -343,7 +323,7 @@ namespace System.Drawing
public EncoderParameters GetEncoderParameterList(Guid encoder)
{
- Status status;
+ int status;
uint sz;
status = SafeNativeMethods.Gdip.GdipGetEncoderParameterListSize(nativeObject, ref encoder, out sz);
@@ -371,7 +351,7 @@ namespace System.Drawing
uint count;
Guid guid = dimension.Guid;
- Status status = SafeNativeMethods.Gdip.GdipImageGetFrameCount(nativeObject, ref guid, out count);
+ int status = SafeNativeMethods.Gdip.GdipImageGetFrameCount(nativeObject, ref guid, out count);
SafeNativeMethods.Gdip.CheckStatus(status);
return (int)count;
@@ -383,7 +363,7 @@ namespace System.Drawing
IntPtr property;
PropertyItem item = new PropertyItem();
GdipPropertyItem gdipProperty = new GdipPropertyItem();
- Status status;
+ int status;
status = SafeNativeMethods.Gdip.GdipGetPropertyItemSize(nativeObject, propid,
out propSize);
@@ -415,7 +395,7 @@ namespace System.Drawing
using (Graphics g = Graphics.FromImage(ThumbNail))
{
- Status status = SafeNativeMethods.Gdip.GdipDrawImageRectRectI(g.nativeObject, nativeObject,
+ int status = SafeNativeMethods.Gdip.GdipDrawImageRectRectI(g.nativeObject, nativeObject,
0, 0, thumbWidth, thumbHeight,
0, 0, this.Width, this.Height,
GraphicsUnit.Pixel, IntPtr.Zero, null, IntPtr.Zero);
@@ -429,13 +409,13 @@ namespace System.Drawing
public void RemovePropertyItem(int propid)
{
- Status status = SafeNativeMethods.Gdip.GdipRemovePropertyItem(nativeObject, propid);
+ int status = SafeNativeMethods.Gdip.GdipRemovePropertyItem(nativeObject, propid);
SafeNativeMethods.Gdip.CheckStatus(status);
}
public void RotateFlip(RotateFlipType rotateFlipType)
{
- Status status = SafeNativeMethods.Gdip.GdipImageRotateFlip(nativeObject, rotateFlipType);
+ int status = SafeNativeMethods.Gdip.GdipImageRotateFlip(nativeObject, rotateFlipType);
SafeNativeMethods.Gdip.CheckStatus(status);
}
@@ -483,7 +463,7 @@ namespace System.Drawing
public void Save(string filename, ImageCodecInfo encoder, EncoderParameters encoderParams)
{
- Status st;
+ int st;
Guid guid = encoder.Clsid;
if (encoderParams == null)
@@ -512,7 +492,7 @@ namespace System.Drawing
public void Save(Stream stream, ImageCodecInfo encoder, EncoderParameters encoderParams)
{
- Status st;
+ int st;
IntPtr nativeEncoderParams;
Guid guid = encoder.Clsid;
@@ -523,17 +503,9 @@ namespace System.Drawing
try
{
- if (GDIPlus.RunningOnUnix())
- {
- GDIPlus.GdiPlusStreamHelper sh = new GDIPlus.GdiPlusStreamHelper(stream, false);
- st = SafeNativeMethods.Gdip.GdipSaveImageToDelegate_linux(nativeObject, sh.GetBytesDelegate, sh.PutBytesDelegate,
- sh.SeekDelegate, sh.CloseDelegate, sh.SizeDelegate, ref guid, nativeEncoderParams);
- }
- else
- {
- st = SafeNativeMethods.Gdip.GdipSaveImageToStream(new HandleRef(this, nativeObject),
- new ComIStreamWrapper(stream), ref guid, new HandleRef(encoderParams, nativeEncoderParams));
- }
+ GdiPlusStreamHelper sh = new GdiPlusStreamHelper(stream, false);
+ st = SafeNativeMethods.Gdip.GdipSaveImageToDelegate_linux(nativeObject, sh.GetBytesDelegate, sh.PutBytesDelegate,
+ sh.SeekDelegate, sh.CloseDelegate, sh.SizeDelegate, ref guid, nativeEncoderParams);
}
finally
{
@@ -546,7 +518,7 @@ namespace System.Drawing
public void SaveAdd(EncoderParameters encoderParams)
{
- Status st;
+ int st;
IntPtr nativeEncoderParams = encoderParams.ConvertToMemory();
st = SafeNativeMethods.Gdip.GdipSaveAdd(nativeObject, nativeEncoderParams);
@@ -556,7 +528,7 @@ namespace System.Drawing
public void SaveAdd(Image image, EncoderParameters encoderParams)
{
- Status st;
+ int st;
IntPtr nativeEncoderParams = encoderParams.ConvertToMemory();
st = SafeNativeMethods.Gdip.GdipSaveAddImage(nativeObject, image.NativeObject, nativeEncoderParams);
@@ -567,7 +539,7 @@ namespace System.Drawing
public int SelectActiveFrame(FrameDimension dimension, int frameIndex)
{
Guid guid = dimension.Guid;
- Status st = SafeNativeMethods.Gdip.GdipImageSelectActiveFrame(nativeObject, ref guid, frameIndex);
+ int st = SafeNativeMethods.Gdip.GdipImageSelectActiveFrame(nativeObject, ref guid, frameIndex);
SafeNativeMethods.Gdip.CheckStatus(st);
@@ -594,7 +566,7 @@ namespace System.Drawing
unsafe
{
- Status status = SafeNativeMethods.Gdip.GdipSetPropertyItem(nativeObject, &pi);
+ int status = SafeNativeMethods.Gdip.GdipSetPropertyItem(nativeObject, &pi);
SafeNativeMethods.Gdip.CheckStatus(status);
}
@@ -613,7 +585,7 @@ namespace System.Drawing
{
int flags;
- Status status = SafeNativeMethods.Gdip.GdipGetImageFlags(nativeObject, out flags);
+ int status = SafeNativeMethods.Gdip.GdipGetImageFlags(nativeObject, out flags);
SafeNativeMethods.Gdip.CheckStatus(status);
return flags;
}
@@ -625,7 +597,7 @@ namespace System.Drawing
get
{
uint found;
- Status status = SafeNativeMethods.Gdip.GdipImageGetFrameDimensionsCount(nativeObject, out found);
+ int status = SafeNativeMethods.Gdip.GdipImageGetFrameDimensionsCount(nativeObject, out found);
SafeNativeMethods.Gdip.CheckStatus(status);
Guid[] guid = new Guid[found];
status = SafeNativeMethods.Gdip.GdipImageGetFrameDimensionsList(nativeObject, guid, found);
@@ -642,7 +614,7 @@ namespace System.Drawing
get
{
uint height;
- Status status = SafeNativeMethods.Gdip.GdipGetImageHeight(nativeObject, out height);
+ int status = SafeNativeMethods.Gdip.GdipGetImageHeight(nativeObject, out height);
SafeNativeMethods.Gdip.CheckStatus(status);
return (int)height;
@@ -655,7 +627,7 @@ namespace System.Drawing
{
float resolution;
- Status status = SafeNativeMethods.Gdip.GdipGetImageHorizontalResolution(nativeObject, out resolution);
+ int status = SafeNativeMethods.Gdip.GdipGetImageHorizontalResolution(nativeObject, out resolution);
SafeNativeMethods.Gdip.CheckStatus(status);
return resolution;
@@ -680,7 +652,7 @@ namespace System.Drawing
int bytes;
ColorPalette ret = new ColorPalette();
- Status st = SafeNativeMethods.Gdip.GdipGetImagePaletteSize(nativeObject, out bytes);
+ int st = SafeNativeMethods.Gdip.GdipGetImagePaletteSize(nativeObject, out bytes);
SafeNativeMethods.Gdip.CheckStatus(st);
IntPtr palette_data = Marshal.AllocHGlobal(bytes);
try
@@ -711,7 +683,7 @@ namespace System.Drawing
try
{
- Status st = SafeNativeMethods.Gdip.GdipSetImagePalette(nativeObject, palette_data);
+ int st = SafeNativeMethods.Gdip.GdipSetImagePalette(nativeObject, palette_data);
SafeNativeMethods.Gdip.CheckStatus(st);
}
@@ -727,7 +699,7 @@ namespace System.Drawing
get
{
float width, height;
- Status status = SafeNativeMethods.Gdip.GdipGetImageDimension(nativeObject, out width, out height);
+ int status = SafeNativeMethods.Gdip.GdipGetImageDimension(nativeObject, out width, out height);
SafeNativeMethods.Gdip.CheckStatus(status);
return new SizeF(width, height);
@@ -739,7 +711,7 @@ namespace System.Drawing
get
{
PixelFormat pixFormat;
- Status status = SafeNativeMethods.Gdip.GdipGetImagePixelFormat(nativeObject, out pixFormat);
+ int status = SafeNativeMethods.Gdip.GdipGetImagePixelFormat(nativeObject, out pixFormat);
SafeNativeMethods.Gdip.CheckStatus(status);
return pixFormat;
@@ -753,7 +725,7 @@ namespace System.Drawing
{
uint propNumbers;
- Status status = SafeNativeMethods.Gdip.GdipGetPropertyCount(nativeObject,
+ int status = SafeNativeMethods.Gdip.GdipGetPropertyCount(nativeObject,
out propNumbers);
SafeNativeMethods.Gdip.CheckStatus(status);
@@ -775,7 +747,7 @@ namespace System.Drawing
IntPtr properties, propPtr;
PropertyItem[] items;
GdipPropertyItem gdipProperty = new GdipPropertyItem();
- Status status;
+ int status;
status = SafeNativeMethods.Gdip.GdipGetPropertySize(nativeObject, out propsSize, out propNums);
SafeNativeMethods.Gdip.CheckStatus(status);
@@ -817,7 +789,7 @@ namespace System.Drawing
get
{
Guid guid;
- Status st = SafeNativeMethods.Gdip.GdipGetImageRawFormat(nativeObject, out guid);
+ int st = SafeNativeMethods.Gdip.GdipGetImageRawFormat(nativeObject, out guid);
SafeNativeMethods.Gdip.CheckStatus(st);
return new ImageFormat(guid);
@@ -849,7 +821,7 @@ namespace System.Drawing
{
float resolution;
- Status status = SafeNativeMethods.Gdip.GdipGetImageVerticalResolution(nativeObject, out resolution);
+ int status = SafeNativeMethods.Gdip.GdipGetImageVerticalResolution(nativeObject, out resolution);
SafeNativeMethods.Gdip.CheckStatus(status);
return resolution;
@@ -864,7 +836,7 @@ namespace System.Drawing
get
{
uint width;
- Status status = SafeNativeMethods.Gdip.GdipGetImageWidth(nativeObject, out width);
+ int status = SafeNativeMethods.Gdip.GdipGetImageWidth(nativeObject, out width);
SafeNativeMethods.Gdip.CheckStatus(status);
return (int)width;
@@ -906,13 +878,7 @@ namespace System.Drawing
{
if (nativeObject != IntPtr.Zero)
{
- Status status = SafeNativeMethods.Gdip.GdipDisposeImage(nativeObject);
- // dispose the stream (set under Win32 only if SD owns the stream) and ...
- if (stream != null)
- {
- stream.Dispose();
- stream = null;
- }
+ int status = SafeNativeMethods.Gdip.GdipDisposeImage(nativeObject);
// ... set nativeObject to null before (possibly) throwing an exception
nativeObject = IntPtr.Zero;
SafeNativeMethods.Gdip.CheckStatus(status);
@@ -921,11 +887,8 @@ namespace System.Drawing
public object Clone()
{
- if (GDIPlus.RunningOnWindows() && stream != null)
- return CloneFromStream();
-
IntPtr newimage = IntPtr.Zero;
- Status status = SafeNativeMethods.Gdip.GdipCloneImage(NativeObject, out newimage);
+ int status = SafeNativeMethods.Gdip.GdipCloneImage(NativeObject, out newimage);
SafeNativeMethods.Gdip.CheckStatus(status);
if (this is Bitmap)
@@ -933,32 +896,6 @@ namespace System.Drawing
else
return new Metafile(newimage);
}
-
- // On win32, when cloning images that were originally created from a stream, we need to
- // clone both the image and the stream to make sure the gc doesn't kill it
- // (when using MS GDI+ and IStream we must ensure the stream stays alive for all the life of the Image)
- object CloneFromStream()
- {
- byte[] bytes = new byte[stream.Length];
- MemoryStream ms = new MemoryStream(bytes);
- int count = (stream.Length < 4096 ? (int)stream.Length : 4096);
- byte[] buffer = new byte[count];
- stream.Position = 0;
- do
- {
- count = stream.Read(buffer, 0, count);
- ms.Write(buffer, 0, count);
- } while (count == 4096);
-
- IntPtr newimage = IntPtr.Zero;
- newimage = InitFromStream(ms);
-
- if (this is Bitmap)
- return new Bitmap(newimage, ms);
- else
- return new Metafile(newimage, ms);
- }
-
}
}
diff --git a/src/System.Drawing.Common/src/System/Drawing/Image.cs b/src/System.Drawing.Common/src/System/Drawing/Image.Windows.cs
index f827c4c2de..80c3821f20 100644
--- a/src/System.Drawing.Common/src/System/Drawing/Image.cs
+++ b/src/System.Drawing.Common/src/System/Drawing/Image.Windows.cs
@@ -355,12 +355,6 @@ namespace System.Drawing
}
}
- private enum ImageTypeEnum
- {
- Bitmap = 1,
- Metafile = 2,
- }
-
internal static Image CreateImageObject(IntPtr nativeImage)
{
Image image;
@@ -372,13 +366,13 @@ namespace System.Drawing
if (status != SafeNativeMethods.Gdip.Ok)
throw SafeNativeMethods.Gdip.StatusException(status);
- switch ((ImageTypeEnum)type)
+ switch ((ImageType)type)
{
- case ImageTypeEnum.Bitmap:
+ case ImageType.Bitmap:
image = Bitmap.FromGDIplus(nativeImage);
break;
- case ImageTypeEnum.Metafile:
+ case ImageType.Metafile:
image = Metafile.FromGDIplus(nativeImage);
break;
diff --git a/src/System.Drawing.Common/src/Unix/System.Drawing/ImageAnimator.cs b/src/System.Drawing.Common/src/System/Drawing/ImageAnimator.Unix.cs
index 5757c7510f..5757c7510f 100644
--- a/src/System.Drawing.Common/src/Unix/System.Drawing/ImageAnimator.cs
+++ b/src/System.Drawing.Common/src/System/Drawing/ImageAnimator.Unix.cs
diff --git a/src/System.Drawing.Common/src/System/Drawing/ImageAnimator.cs b/src/System.Drawing.Common/src/System/Drawing/ImageAnimator.Windows.cs
index 40473af635..6d5e3e4a89 100644
--- a/src/System.Drawing.Common/src/System/Drawing/ImageAnimator.cs
+++ b/src/System.Drawing.Common/src/System/Drawing/ImageAnimator.Windows.cs
@@ -60,7 +60,7 @@ namespace System.Drawing
private static ReaderWriterLock s_rwImgListLock = new ReaderWriterLock();
/// <summary>
- /// Flag to avoid a deadlock when waiting on a write-lock and a an attempt to acquire a read-lock is
+ /// Flag to avoid a deadlock when waiting on a write-lock and an attempt to acquire a read-lock is
/// made in the same thread. If RWLock is currently owned by another thread, the current thread is going to wait on an
/// event using CoWaitForMultipleHandles while pumps message.
/// The comment above refers to the COM STA message pump, not to be confused with the UI message pump.
diff --git a/src/System.Drawing.Common/src/System/Drawing/ImageType.cs b/src/System.Drawing.Common/src/System/Drawing/ImageType.cs
new file mode 100644
index 0000000000..439576ce9e
--- /dev/null
+++ b/src/System.Drawing.Common/src/System/Drawing/ImageType.cs
@@ -0,0 +1,13 @@
+// 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 enum ImageType
+ {
+ Unknown = 0,
+ Bitmap = 1,
+ Metafile = 2,
+ }
+}
diff --git a/src/System.Drawing.Common/src/Unix/System.Drawing.Imaging/BitmapData.cs b/src/System.Drawing.Common/src/System/Drawing/Imaging/BitmapData.Unix.cs
index e7d9b2eb11..e7d9b2eb11 100644
--- a/src/System.Drawing.Common/src/Unix/System.Drawing.Imaging/BitmapData.cs
+++ b/src/System.Drawing.Common/src/System/Drawing/Imaging/BitmapData.Unix.cs
diff --git a/src/System.Drawing.Common/src/System/Drawing/Imaging/BitmapData.cs b/src/System.Drawing.Common/src/System/Drawing/Imaging/BitmapData.Windows.cs
index 1a0a747ada..1a0a747ada 100644
--- a/src/System.Drawing.Common/src/System/Drawing/Imaging/BitmapData.cs
+++ b/src/System.Drawing.Common/src/System/Drawing/Imaging/BitmapData.Windows.cs
diff --git a/src/System.Drawing.Common/src/Unix/System.Drawing.Imaging/MetaHeader.cs b/src/System.Drawing.Common/src/System/Drawing/Imaging/MetaHeader.Unix.cs
index 673fff1f2a..673fff1f2a 100644
--- a/src/System.Drawing.Common/src/Unix/System.Drawing.Imaging/MetaHeader.cs
+++ b/src/System.Drawing.Common/src/System/Drawing/Imaging/MetaHeader.Unix.cs
diff --git a/src/System.Drawing.Common/src/System/Drawing/Imaging/METAHEADER.cs b/src/System.Drawing.Common/src/System/Drawing/Imaging/MetaHeader.Windows.cs
index bb64171049..bb64171049 100644
--- a/src/System.Drawing.Common/src/System/Drawing/Imaging/METAHEADER.cs
+++ b/src/System.Drawing.Common/src/System/Drawing/Imaging/MetaHeader.Windows.cs
diff --git a/src/System.Drawing.Common/src/Unix/System.Drawing.Imaging/Metafile.cs b/src/System.Drawing.Common/src/System/Drawing/Imaging/Metafile.Unix.cs
index 4f66f0dd29..9825ac7337 100644
--- a/src/System.Drawing.Common/src/Unix/System.Drawing.Imaging/Metafile.cs
+++ b/src/System.Drawing.Common/src/System/Drawing/Imaging/Metafile.Unix.cs
@@ -59,49 +59,37 @@ namespace System.Drawing.Imaging
// (when using MS GDI+ and IStream we must ensure the stream stays alive for all the life of the Image)
internal Metafile(IntPtr ptr, Stream stream)
{
- // under Win32 stream is owned by SD/GDI+ code
- if (GDIPlus.RunningOnWindows())
- this.stream = stream;
nativeObject = ptr;
}
public Metafile(Stream stream)
{
if (stream == null)
- throw new ArgumentException("stream");
-
- Status status;
- if (GDIPlus.RunningOnUnix())
- {
- // With libgdiplus we use a custom API for this, because there's no easy way
- // to get the Stream down to libgdiplus. So, we wrap the stream with a set of delegates.
- GDIPlus.GdiPlusStreamHelper sh = new GDIPlus.GdiPlusStreamHelper(stream, false);
- status = SafeNativeMethods.Gdip.GdipCreateMetafileFromDelegate_linux(sh.GetHeaderDelegate, sh.GetBytesDelegate,
- sh.PutBytesDelegate, sh.SeekDelegate, sh.CloseDelegate, sh.SizeDelegate, out nativeObject);
- }
- else
- {
- status = SafeNativeMethods.Gdip.GdipCreateMetafileFromStream(new ComIStreamWrapper(stream), out nativeObject);
- }
+ throw new ArgumentNullException("stream");
+
+ int status;
+ // With libgdiplus we use a custom API for this, because there's no easy way
+ // to get the Stream down to libgdiplus. So, we wrap the stream with a set of delegates.
+ GdiPlusStreamHelper sh = new GdiPlusStreamHelper(stream, false);
+ status = SafeNativeMethods.Gdip.GdipCreateMetafileFromDelegate_linux(sh.GetHeaderDelegate, sh.GetBytesDelegate,
+ sh.PutBytesDelegate, sh.SeekDelegate, sh.CloseDelegate, sh.SizeDelegate, out nativeObject);
SafeNativeMethods.Gdip.CheckStatus(status);
}
public Metafile(string filename)
{
- if (filename == null)
- throw new ArgumentNullException("filename");
- if (filename.Length == 0)
- throw new ArgumentException("filename");
+ // Called in order to emulate exception behavior from netfx related to invalid file paths.
+ Path.GetFullPath(filename);
- Status status = SafeNativeMethods.Gdip.GdipCreateMetafileFromFile(filename, out nativeObject);
- if (status == Status.GenericError)
+ int status = SafeNativeMethods.Gdip.GdipCreateMetafileFromFile(filename, out nativeObject);
+ if (status == SafeNativeMethods.Gdip.GenericError)
throw new ExternalException("Couldn't load specified file.");
SafeNativeMethods.Gdip.CheckStatus(status);
}
public Metafile(IntPtr henhmetafile, bool deleteEmf)
{
- Status status = SafeNativeMethods.Gdip.GdipCreateMetafileFromEmf(henhmetafile, deleteEmf, out nativeObject);
+ int status = SafeNativeMethods.Gdip.GdipCreateMetafileFromEmf(henhmetafile, deleteEmf, out nativeObject);
SafeNativeMethods.Gdip.CheckStatus(status);
}
@@ -122,7 +110,7 @@ namespace System.Drawing.Imaging
public Metafile(IntPtr hmetafile, WmfPlaceableFileHeader wmfHeader)
{
- Status status = SafeNativeMethods.Gdip.GdipCreateMetafileFromEmf(hmetafile, false, out nativeObject);
+ int status = SafeNativeMethods.Gdip.GdipCreateMetafileFromEmf(hmetafile, false, out nativeObject);
SafeNativeMethods.Gdip.CheckStatus(status);
}
@@ -154,7 +142,7 @@ namespace System.Drawing.Imaging
public Metafile(IntPtr hmetafile, WmfPlaceableFileHeader wmfHeader, bool deleteWmf)
{
- Status status = SafeNativeMethods.Gdip.GdipCreateMetafileFromEmf(hmetafile, deleteWmf, out nativeObject);
+ int status = SafeNativeMethods.Gdip.GdipCreateMetafileFromEmf(hmetafile, deleteWmf, out nativeObject);
SafeNativeMethods.Gdip.CheckStatus(status);
}
@@ -231,7 +219,7 @@ namespace System.Drawing.Imaging
public Metafile(IntPtr referenceHdc, Rectangle frameRect, MetafileFrameUnit frameUnit, EmfType type,
string desc)
{
- Status status = SafeNativeMethods.Gdip.GdipRecordMetafileI(referenceHdc, type, ref frameRect, frameUnit,
+ int status = SafeNativeMethods.Gdip.GdipRecordMetafileI(referenceHdc, type, ref frameRect, frameUnit,
desc, out nativeObject);
SafeNativeMethods.Gdip.CheckStatus(status);
}
@@ -239,7 +227,7 @@ namespace System.Drawing.Imaging
public Metafile(IntPtr referenceHdc, RectangleF frameRect, MetafileFrameUnit frameUnit, EmfType type,
string description)
{
- Status status = SafeNativeMethods.Gdip.GdipRecordMetafile(referenceHdc, type, ref frameRect, frameUnit,
+ int status = SafeNativeMethods.Gdip.GdipRecordMetafile(referenceHdc, type, ref frameRect, frameUnit,
description, out nativeObject);
SafeNativeMethods.Gdip.CheckStatus(status);
}
@@ -281,21 +269,13 @@ namespace System.Drawing.Imaging
if (stream == null)
throw new NullReferenceException("stream");
- Status status = Status.NotImplemented;
- if (GDIPlus.RunningOnUnix())
- {
- // With libgdiplus we use a custom API for this, because there's no easy way
- // to get the Stream down to libgdiplus. So, we wrap the stream with a set of delegates.
- GDIPlus.GdiPlusStreamHelper sh = new GDIPlus.GdiPlusStreamHelper(stream, false);
- status = SafeNativeMethods.Gdip.GdipRecordMetafileFromDelegateI_linux(sh.GetHeaderDelegate, sh.GetBytesDelegate,
- sh.PutBytesDelegate, sh.SeekDelegate, sh.CloseDelegate, sh.SizeDelegate, referenceHdc,
- type, ref frameRect, frameUnit, description, out nativeObject);
- }
- else
- {
- status = SafeNativeMethods.Gdip.GdipRecordMetafileStreamI(new ComIStreamWrapper(stream), referenceHdc,
- type, ref frameRect, frameUnit, description, out nativeObject);
- }
+ int status = SafeNativeMethods.Gdip.NotImplemented;
+ // With libgdiplus we use a custom API for this, because there's no easy way
+ // to get the Stream down to libgdiplus. So, we wrap the stream with a set of delegates.
+ GdiPlusStreamHelper sh = new GdiPlusStreamHelper(stream, false);
+ status = SafeNativeMethods.Gdip.GdipRecordMetafileFromDelegateI_linux(sh.GetHeaderDelegate, sh.GetBytesDelegate,
+ sh.PutBytesDelegate, sh.SeekDelegate, sh.CloseDelegate, sh.SizeDelegate, referenceHdc,
+ type, ref frameRect, frameUnit, description, out nativeObject);
SafeNativeMethods.Gdip.CheckStatus(status);
}
@@ -305,28 +285,23 @@ namespace System.Drawing.Imaging
if (stream == null)
throw new NullReferenceException("stream");
- Status status = Status.NotImplemented;
- if (GDIPlus.RunningOnUnix())
- {
- // With libgdiplus we use a custom API for this, because there's no easy way
- // to get the Stream down to libgdiplus. So, we wrap the stream with a set of delegates.
- GDIPlus.GdiPlusStreamHelper sh = new GDIPlus.GdiPlusStreamHelper(stream, false);
- status = SafeNativeMethods.Gdip.GdipRecordMetafileFromDelegate_linux(sh.GetHeaderDelegate, sh.GetBytesDelegate,
- sh.PutBytesDelegate, sh.SeekDelegate, sh.CloseDelegate, sh.SizeDelegate, referenceHdc,
- type, ref frameRect, frameUnit, description, out nativeObject);
- }
- else
- {
- status = SafeNativeMethods.Gdip.GdipRecordMetafileStream(new ComIStreamWrapper(stream), referenceHdc,
- type, ref frameRect, frameUnit, description, out nativeObject);
- }
+ int status = SafeNativeMethods.Gdip.NotImplemented;
+ // With libgdiplus we use a custom API for this, because there's no easy way
+ // to get the Stream down to libgdiplus. So, we wrap the stream with a set of delegates.
+ GdiPlusStreamHelper sh = new GdiPlusStreamHelper(stream, false);
+ status = SafeNativeMethods.Gdip.GdipRecordMetafileFromDelegate_linux(sh.GetHeaderDelegate, sh.GetBytesDelegate,
+ sh.PutBytesDelegate, sh.SeekDelegate, sh.CloseDelegate, sh.SizeDelegate, referenceHdc,
+ type, ref frameRect, frameUnit, description, out nativeObject);
SafeNativeMethods.Gdip.CheckStatus(status);
}
public Metafile(string fileName, IntPtr referenceHdc, Rectangle frameRect, MetafileFrameUnit frameUnit,
EmfType type, string description)
{
- Status status = SafeNativeMethods.Gdip.GdipRecordMetafileFileNameI(fileName, referenceHdc, type, ref frameRect,
+ // Called in order to emulate exception behavior from netfx related to invalid file paths.
+ Path.GetFullPath(fileName);
+
+ int status = SafeNativeMethods.Gdip.GdipRecordMetafileFileNameI(fileName, referenceHdc, type, ref frameRect,
frameUnit, description, out nativeObject);
SafeNativeMethods.Gdip.CheckStatus(status);
}
@@ -334,7 +309,10 @@ namespace System.Drawing.Imaging
public Metafile(string fileName, IntPtr referenceHdc, RectangleF frameRect, MetafileFrameUnit frameUnit,
EmfType type, string description)
{
- Status status = SafeNativeMethods.Gdip.GdipRecordMetafileFileName(fileName, referenceHdc, type, ref frameRect, frameUnit,
+ // Called in order to emulate exception behavior from netfx related to invalid file paths.
+ Path.GetFullPath(fileName);
+
+ int status = SafeNativeMethods.Gdip.GdipRecordMetafileFileName(fileName, referenceHdc, type, ref frameRect, frameUnit,
description, out nativeObject);
SafeNativeMethods.Gdip.CheckStatus(status);
}
@@ -352,7 +330,7 @@ namespace System.Drawing.Imaging
IntPtr header = Marshal.AllocHGlobal(Marshal.SizeOf(typeof(MetafileHeader)));
try
{
- Status status = SafeNativeMethods.Gdip.GdipGetMetafileHeaderFromMetafile(nativeObject, header);
+ int status = SafeNativeMethods.Gdip.GdipGetMetafileHeaderFromMetafile(nativeObject, header);
SafeNativeMethods.Gdip.CheckStatus(status);
return new MetafileHeader(header);
}
@@ -368,7 +346,7 @@ namespace System.Drawing.Imaging
IntPtr header = Marshal.AllocHGlobal(Marshal.SizeOf(typeof(MetafileHeader)));
try
{
- Status status = SafeNativeMethods.Gdip.GdipGetMetafileHeaderFromEmf(henhmetafile, header);
+ int status = SafeNativeMethods.Gdip.GdipGetMetafileHeaderFromEmf(henhmetafile, header);
SafeNativeMethods.Gdip.CheckStatus(status);
return new MetafileHeader(header);
}
@@ -387,21 +365,13 @@ namespace System.Drawing.Imaging
IntPtr header = Marshal.AllocHGlobal(Marshal.SizeOf(typeof(MetafileHeader)));
try
{
- Status status;
-
- if (GDIPlus.RunningOnUnix())
- {
- // With libgdiplus we use a custom API for this, because there's no easy way
- // to get the Stream down to libgdiplus. So, we wrap the stream with a set of delegates.
- GDIPlus.GdiPlusStreamHelper sh = new GDIPlus.GdiPlusStreamHelper(stream, false);
- status = SafeNativeMethods.Gdip.GdipGetMetafileHeaderFromDelegate_linux(sh.GetHeaderDelegate,
- sh.GetBytesDelegate, sh.PutBytesDelegate, sh.SeekDelegate, sh.CloseDelegate,
- sh.SizeDelegate, header);
- }
- else
- {
- status = SafeNativeMethods.Gdip.GdipGetMetafileHeaderFromStream(new ComIStreamWrapper(stream), header);
- }
+ int status;
+ // With libgdiplus we use a custom API for this, because there's no easy way
+ // to get the Stream down to libgdiplus. So, we wrap the stream with a set of delegates.
+ GdiPlusStreamHelper sh = new GdiPlusStreamHelper(stream, false);
+ status = SafeNativeMethods.Gdip.GdipGetMetafileHeaderFromDelegate_linux(sh.GetHeaderDelegate,
+ sh.GetBytesDelegate, sh.PutBytesDelegate, sh.SeekDelegate, sh.CloseDelegate,
+ sh.SizeDelegate, header);
SafeNativeMethods.Gdip.CheckStatus(status);
return new MetafileHeader(header);
}
@@ -420,7 +390,7 @@ namespace System.Drawing.Imaging
IntPtr header = Marshal.AllocHGlobal(Marshal.SizeOf(typeof(MetafileHeader)));
try
{
- Status status = SafeNativeMethods.Gdip.GdipGetMetafileHeaderFromFile(fileName, header);
+ int status = SafeNativeMethods.Gdip.GdipGetMetafileHeaderFromFile(fileName, header);
SafeNativeMethods.Gdip.CheckStatus(status);
return new MetafileHeader(header);
}
@@ -436,7 +406,7 @@ namespace System.Drawing.Imaging
IntPtr header = Marshal.AllocHGlobal(Marshal.SizeOf(typeof(MetafileHeader)));
try
{
- Status status = SafeNativeMethods.Gdip.GdipGetMetafileHeaderFromEmf(hmetafile, header);
+ int status = SafeNativeMethods.Gdip.GdipGetMetafileHeaderFromEmf(hmetafile, header);
SafeNativeMethods.Gdip.CheckStatus(status);
return new MetafileHeader(header);
}
@@ -449,7 +419,7 @@ namespace System.Drawing.Imaging
[MonoLimitation("Metafiles aren't only partially supported by libgdiplus.")]
public void PlayRecord(EmfPlusRecordType recordType, int flags, int dataSize, byte[] data)
{
- Status status = SafeNativeMethods.Gdip.GdipPlayMetafileRecord(nativeObject, recordType, flags, dataSize, data);
+ int status = SafeNativeMethods.Gdip.GdipPlayMetafileRecord(nativeObject, recordType, flags, dataSize, data);
SafeNativeMethods.Gdip.CheckStatus(status);
}
}
diff --git a/src/System.Drawing.Common/src/System/Drawing/Imaging/Metafile.cs b/src/System.Drawing.Common/src/System/Drawing/Imaging/Metafile.Windows.cs
index e043f81811..7a3c6b2ad7 100644
--- a/src/System.Drawing.Common/src/System/Drawing/Imaging/Metafile.cs
+++ b/src/System.Drawing.Common/src/System/Drawing/Imaging/Metafile.Windows.cs
@@ -14,6 +14,9 @@ namespace System.Drawing.Imaging
/// </summary>
public sealed partial class Metafile : Image
{
+ // GDI+ doesn't handle filenames over MAX_PATH very well
+ private const int MaxPath = 260;
+
/// <summary>
/// Initializes a new instance of the <see cref='Metafile'/> class from the specified handle and
/// <see cref='WmfPlaceableFileHeader'/>.
@@ -297,6 +300,14 @@ namespace System.Drawing.Imaging
public Metafile(string fileName, IntPtr referenceHdc, RectangleF frameRect,
MetafileFrameUnit frameUnit, EmfType type, String description)
{
+ // Called in order to emulate exception behavior from netfx related to invalid file paths.
+ Path.GetFullPath(fileName);
+
+ if (fileName.Length > MaxPath)
+ {
+ throw new PathTooLongException();
+ }
+
IntPtr metafile = IntPtr.Zero;
GPRECTF rectf = new GPRECTF(frameRect);
@@ -349,6 +360,9 @@ namespace System.Drawing.Imaging
/// </summary>
public Metafile(string fileName, IntPtr referenceHdc, Rectangle frameRect, MetafileFrameUnit frameUnit, EmfType type, string description)
{
+ // Called in order to emulate exception behavior from netfx related to invalid file paths.
+ Path.GetFullPath(fileName);
+
IntPtr metafile = IntPtr.Zero;
int status;
diff --git a/src/System.Drawing.Common/src/Unix/System.Drawing.Imaging/MetafileHeader.cs b/src/System.Drawing.Common/src/System/Drawing/Imaging/MetafileHeader.Unix.cs
index 8efaab27cb..f4f2cdd7d7 100644
--- a/src/System.Drawing.Common/src/Unix/System.Drawing.Imaging/MetafileHeader.cs
+++ b/src/System.Drawing.Common/src/System/Drawing/Imaging/MetafileHeader.Unix.cs
@@ -153,7 +153,16 @@ namespace System.Drawing.Imaging
public Rectangle Bounds
{
- get { return new Rectangle(header.x, header.y, header.width, header.height); }
+ get
+ {
+ if (this.MetafileSize == 0)
+ {
+ // GDI+ compatibility;
+ return new Rectangle();
+ }
+
+ return new Rectangle(header.x, header.y, header.width, header.height);
+ }
}
public float DpiX
diff --git a/src/System.Drawing.Common/src/System/Drawing/Imaging/MetafileHeader.cs b/src/System.Drawing.Common/src/System/Drawing/Imaging/MetafileHeader.Windows.cs
index b70bcd1e1d..b70bcd1e1d 100644
--- a/src/System.Drawing.Common/src/System/Drawing/Imaging/MetafileHeader.cs
+++ b/src/System.Drawing.Common/src/System/Drawing/Imaging/MetafileHeader.Windows.cs
diff --git a/src/System.Drawing.Common/src/System/Drawing/LibX11Functions.cs b/src/System.Drawing.Common/src/System/Drawing/LibX11Functions.cs
new file mode 100644
index 0000000000..a152a0def2
--- /dev/null
+++ b/src/System.Drawing.Common/src/System/Drawing/LibX11Functions.cs
@@ -0,0 +1,50 @@
+// 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.
+
+// Originally in System.Drawing.gdipFunctions.cs
+
+using System.Runtime.InteropServices;
+
+namespace System.Drawing
+{
+ internal static class LibX11Functions
+ {
+ // Some special X11 stuff
+ [DllImport("libX11", EntryPoint = "XOpenDisplay")]
+ internal extern static IntPtr XOpenDisplay(IntPtr display);
+
+ [DllImport("libX11", EntryPoint = "XCloseDisplay")]
+ internal extern static int XCloseDisplay(IntPtr display);
+
+ [DllImport("libX11", EntryPoint = "XRootWindow")]
+ internal extern static IntPtr XRootWindow(IntPtr display, int screen);
+
+ [DllImport("libX11", EntryPoint = "XDefaultScreen")]
+ internal extern static int XDefaultScreen(IntPtr display);
+
+ [DllImport("libX11", EntryPoint = "XDefaultDepth")]
+ internal extern static uint XDefaultDepth(IntPtr display, int screen);
+
+ [DllImport("libX11", EntryPoint = "XGetImage")]
+ internal extern static IntPtr XGetImage(IntPtr display, IntPtr drawable, int src_x, int src_y, int width, int height, int pane, int format);
+
+ [DllImport("libX11", EntryPoint = "XGetPixel")]
+ internal extern static int XGetPixel(IntPtr image, int x, int y);
+
+ [DllImport("libX11", EntryPoint = "XDestroyImage")]
+ internal extern static int XDestroyImage(IntPtr image);
+
+ [DllImport("libX11", EntryPoint = "XDefaultVisual")]
+ internal extern static IntPtr XDefaultVisual(IntPtr display, int screen);
+
+ [DllImport("libX11", EntryPoint = "XGetVisualInfo")]
+ internal extern static IntPtr XGetVisualInfo(IntPtr display, int vinfo_mask, ref XVisualInfo vinfo_template, ref int nitems);
+
+ [DllImport("libX11", EntryPoint = "XVisualIDFromVisual")]
+ internal extern static IntPtr XVisualIDFromVisual(IntPtr visual);
+
+ [DllImport("libX11", EntryPoint = "XFree")]
+ internal extern static void XFree(IntPtr data);
+ }
+}
diff --git a/src/System.Drawing.Common/src/System/Drawing/MarshallingHelpers.cs b/src/System.Drawing.Common/src/System/Drawing/MarshallingHelpers.cs
new file mode 100644
index 0000000000..c6e75f3230
--- /dev/null
+++ b/src/System.Drawing.Common/src/System/Drawing/MarshallingHelpers.cs
@@ -0,0 +1,86 @@
+// Licensed to the .NET Foundation under one or more agreements.
+// See the LICENSE file in the project root for more information.
+//
+// Authors:
+// Alexandre Pigolkine (pigolkine@gmx.de)
+// Jordi Mas i Hernandez (jordi@ximian.com)
+// Sanjay Gupta (gsanjay@novell.com)
+// Ravindra (rkumar@novell.com)
+// Peter Dennis Bartok (pbartok@novell.com)
+// Sebastien Pouliot <sebastien@ximian.com>
+//
+// Copyright (C) 2004 - 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.Runtime.InteropServices;
+
+namespace System.Drawing
+{
+ internal static class MarshallingHelpers
+ {
+ // Copies a Ptr to an array of Points and releases the memory
+ static public void FromUnManagedMemoryToPointI(IntPtr prt, Point[] pts)
+ {
+ int nPointSize = Marshal.SizeOf(pts[0]);
+ IntPtr pos = prt;
+ for (int i = 0; i < pts.Length; i++, pos = new IntPtr(pos.ToInt64() + nPointSize))
+ pts[i] = (Point)Marshal.PtrToStructure(pos, typeof(Point));
+
+ Marshal.FreeHGlobal(prt);
+ }
+
+ // Copies a Ptr to an array of Points and releases the memory
+ static public void FromUnManagedMemoryToPoint(IntPtr prt, PointF[] pts)
+ {
+ int nPointSize = Marshal.SizeOf(pts[0]);
+ IntPtr pos = prt;
+ for (int i = 0; i < pts.Length; i++, pos = new IntPtr(pos.ToInt64() + nPointSize))
+ pts[i] = (PointF)Marshal.PtrToStructure(pos, typeof(PointF));
+
+ Marshal.FreeHGlobal(prt);
+ }
+
+ // Copies an array of Points to unmanaged memory
+ static public IntPtr FromPointToUnManagedMemoryI(Point[] pts)
+ {
+ int nPointSize = Marshal.SizeOf(pts[0]);
+ IntPtr dest = Marshal.AllocHGlobal(nPointSize * pts.Length);
+ IntPtr pos = dest;
+ for (int i = 0; i < pts.Length; i++, pos = new IntPtr(pos.ToInt64() + nPointSize))
+ Marshal.StructureToPtr(pts[i], pos, false);
+
+ return dest;
+ }
+
+ // Copies an array of Points to unmanaged memory
+ static public IntPtr FromPointToUnManagedMemory(PointF[] pts)
+ {
+ int nPointSize = Marshal.SizeOf(pts[0]);
+ IntPtr dest = Marshal.AllocHGlobal(nPointSize * pts.Length);
+ IntPtr pos = dest;
+ for (int i = 0; i < pts.Length; i++, pos = new IntPtr(pos.ToInt64() + nPointSize))
+ Marshal.StructureToPtr(pts[i], pos, false);
+
+ return dest;
+ }
+ }
+}
diff --git a/src/System.Drawing.Common/src/Unix/System.Drawing/gdipStructs.cs b/src/System.Drawing.Common/src/System/Drawing/NativeStructs.Unix.cs
index 941014001b..c9ad9dba0b 100644
--- a/src/System.Drawing.Common/src/Unix/System.Drawing/gdipStructs.cs
+++ b/src/System.Drawing.Common/src/System/Drawing/NativeStructs.Unix.cs
@@ -1,7 +1,7 @@
// Licensed to the .NET Foundation under one or more agreements.
// See the LICENSE file in the project root for more information.
//
-// System.Drawing.gdipStructs.cs
+// System.Drawing.NativeStructs.cs
//
// Author:
// Alexandre Pigolkine (pigolkine@gmx.de)
@@ -34,20 +34,6 @@ using System.Runtime.InteropServices;
namespace System.Drawing
{
- [StructLayout(LayoutKind.Sequential)]
- internal struct GdiColorPalette
- {
- internal int Flags; // Palette flags
- internal int Count; // Number of color entries
- }
-
- [StructLayout(LayoutKind.Sequential)]
- internal struct GdiColorMap
- {
- internal int from;
- internal int to;
- }
-
[StructLayout(LayoutKind.Sequential, CharSet = CharSet.Auto)]
internal struct LOGFONT
{
@@ -113,15 +99,6 @@ namespace System.Drawing
}
[StructLayout(LayoutKind.Sequential)]
- internal struct GdipEncoderParameter
- {
- internal Guid guid;
- internal uint numberOfValues;
- internal EncoderParameterValueType type;
- internal IntPtr value;
- }
-
- [StructLayout(LayoutKind.Sequential)]
internal struct GdipPropertyItem
{
internal int id;
@@ -156,15 +133,6 @@ namespace System.Drawing
}
[StructLayout(LayoutKind.Sequential)]
- internal struct XColor
- {
- public int pixel;
- public ushort red, green, blue;
- public sbyte flags;
- public sbyte pad;
- }
-
- [StructLayout(LayoutKind.Sequential)]
internal struct XVisualInfo
{
internal IntPtr visual;
diff --git a/src/System.Drawing.Common/src/System/Drawing/Pen.cs b/src/System.Drawing.Common/src/System/Drawing/Pen.cs
index eb91f0ee72..16cc0071da 100644
--- a/src/System.Drawing.Common/src/System/Drawing/Pen.cs
+++ b/src/System.Drawing.Common/src/System/Drawing/Pen.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.
@@ -27,6 +27,9 @@ namespace System.Drawing
private Color _color;
private bool _immutable;
+ // Tracks whether the dash style has been changed to something else than Solid during the lifetime of this object.
+ private bool _dashStyleWasOrIsNotSolid;
+
/// <summary>
/// Creates a Pen from a native GDI+ object.
/// </summary>
@@ -669,6 +672,11 @@ namespace System.Drawing
{
EnsureValidDashPattern();
}
+
+ if (value != DashStyle.Solid)
+ {
+ this._dashStyleWasOrIsNotSolid = true;
+ }
}
}
@@ -721,26 +729,35 @@ namespace System.Drawing
{
get
{
- int count = 0;
- int status = SafeNativeMethods.Gdip.GdipGetPenDashCount(new HandleRef(this, NativePen), out count);
+ int status = SafeNativeMethods.Gdip.GdipGetPenDashCount(new HandleRef(this, NativePen), out int count);
SafeNativeMethods.Gdip.CheckStatus(status);
-
- // Allocate temporary native memory buffer
- // and pass it to GDI+ to retrieve dash array elements.
- IntPtr buf = Marshal.AllocHGlobal(checked(4 * count));
- try
+
+ float[] pattern;
+ // don't call GdipGetPenDashArray with a 0 count
+ if (count > 0)
{
- status = SafeNativeMethods.Gdip.GdipGetPenDashArray(new HandleRef(this, NativePen), buf, count);
+ pattern = new float[count];
+ status = SafeNativeMethods.Gdip.GdipGetPenDashArray(new HandleRef(this, NativePen), pattern, count);
SafeNativeMethods.Gdip.CheckStatus(status);
-
- var dashArray = new float[count];
- Marshal.Copy(buf, dashArray, 0, count);
- return dashArray;
}
- finally
+ else if (DashStyle == DashStyle.Solid && !this._dashStyleWasOrIsNotSolid)
{
- Marshal.FreeHGlobal(buf);
+ // Most likely we're replicating an existing System.Drawing bug here, it doesn't make much sense to
+ // ask for a dash pattern when using a solid dash.
+ throw new OutOfMemoryException();
+ }
+ else if (DashStyle == DashStyle.Solid)
+ {
+ pattern = new float[0];
+ }
+ else
+ {
+ // special case (not handled inside GDI+)
+ pattern = new float[1];
+ pattern[0] = 1.0f;
}
+
+ return pattern;
}
set
{
diff --git a/src/System.Drawing.Common/src/System/Drawing/Printing/LibcupsNative.cs b/src/System.Drawing.Common/src/System/Drawing/Printing/LibcupsNative.cs
new file mode 100644
index 0000000000..d78dd6ad8d
--- /dev/null
+++ b/src/System.Drawing.Common/src/System/Drawing/Printing/LibcupsNative.cs
@@ -0,0 +1,88 @@
+// 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;
+using System.Text;
+
+namespace System.Drawing.Printing
+{
+ internal static class LibcupsNative
+ {
+ private static IntPtr s_libcupsHandle = LoadLibcups();
+
+ private static IntPtr LoadLibcups()
+ {
+ // We allow both "libcups.so" and "libcups.so.2" to be loaded.
+ IntPtr lib = Interop.Libdl.dlopen("libcups.so", Interop.Libdl.RTLD_NOW);
+ if (lib == IntPtr.Zero)
+ {
+ lib = Interop.Libdl.dlopen("libcups.so.2", Interop.Libdl.RTLD_NOW);
+ }
+
+ return lib;
+ }
+
+ private delegate int cupsGetDests_delegate(ref IntPtr dests);
+ private static FunctionWrapper<cupsGetDests_delegate> cupsGetDests_ptr
+ = FunctionWrapper.Load<cupsGetDests_delegate>(s_libcupsHandle, "cupsGetDests");
+ internal static int cupsGetDests(ref IntPtr dests) => cupsGetDests_ptr.Delegate(ref dests);
+
+ private delegate int cupsFreeDests_delegate(int num_dests, IntPtr dests);
+ private static FunctionWrapper<cupsFreeDests_delegate> cupsFreeDests_ptr
+ = FunctionWrapper.Load<cupsFreeDests_delegate>(s_libcupsHandle, "cupsFreeDests");
+ internal static void cupsFreeDests(int num_dests, IntPtr dests) => cupsFreeDests_ptr.Delegate(num_dests, dests);
+
+ private delegate IntPtr cupsTempFd_delegate([MarshalAs(UnmanagedType.LPStr)]StringBuilder sb, int len);
+ private static FunctionWrapper<cupsTempFd_delegate> cupsTempFd_ptr
+ = FunctionWrapper.Load<cupsTempFd_delegate>(s_libcupsHandle, "cupsTempFd");
+ internal static IntPtr cupsTempFd(StringBuilder sb, int len) => cupsTempFd_ptr.Delegate(sb, len);
+
+ private delegate IntPtr cupsGetDefault_delegate();
+ private static FunctionWrapper<cupsGetDefault_delegate> cupsGetDefault_ptr
+ = FunctionWrapper.Load<cupsGetDefault_delegate>(s_libcupsHandle, "cupsGetDefault");
+ internal static IntPtr cupsGetDefault() => cupsGetDefault_ptr.Delegate();
+
+ private delegate int cupsPrintFile_delegate(
+ [MarshalAs(UnmanagedType.LPStr)]string printer,
+ [MarshalAs(UnmanagedType.LPStr)]string filename,
+ [MarshalAs(UnmanagedType.LPStr)]string title,
+ int num_options,
+ IntPtr options);
+ private static FunctionWrapper<cupsPrintFile_delegate> cupsPrintFile_ptr
+ = FunctionWrapper.Load<cupsPrintFile_delegate>(s_libcupsHandle, "cupsPrintFile");
+ internal static int cupsPrintFile(string printer, string filename, string title, int num_options, IntPtr options)
+ => cupsPrintFile_ptr.Delegate(printer, filename, title, num_options, options);
+
+ private delegate IntPtr cupsGetPPD_delegate([MarshalAs(UnmanagedType.LPStr)]string printer);
+ private static FunctionWrapper<cupsGetPPD_delegate> cupsGetPPD_ptr
+ = FunctionWrapper.Load<cupsGetPPD_delegate>(s_libcupsHandle, "cupsGetPPD");
+ internal static IntPtr cupsGetPPD(string printer) => cupsGetPPD_ptr.Delegate(printer);
+
+ private delegate IntPtr ppdOpenFile_delegate([MarshalAs(UnmanagedType.LPStr)]string filename);
+ private static FunctionWrapper<ppdOpenFile_delegate> ppdOpenFile_ptr
+ = FunctionWrapper.Load<ppdOpenFile_delegate>(s_libcupsHandle, "ppdOpenFile");
+ internal static IntPtr ppdOpenFile(string filename) => ppdOpenFile_ptr.Delegate(filename);
+
+ private delegate IntPtr ppdFindOption_delegate(IntPtr ppd_file, [MarshalAs(UnmanagedType.LPStr)]string keyword);
+ private static FunctionWrapper<ppdFindOption_delegate> ppdFindOption_ptr
+ = FunctionWrapper.Load<ppdFindOption_delegate>(s_libcupsHandle, "ppdFindOption");
+ internal static IntPtr ppdFindOption(IntPtr ppd_file, string keyword) => ppdFindOption_ptr.Delegate(ppd_file, keyword);
+
+ private delegate void ppdClose_delegate(IntPtr ppd);
+ private static FunctionWrapper<ppdClose_delegate> ppdClose_ptr
+ = FunctionWrapper.Load<ppdClose_delegate>(s_libcupsHandle, "ppdClose");
+ internal static void ppdClose(IntPtr ppd) => ppdClose_ptr.Delegate(ppd);
+
+ private delegate int cupsParseOptions_delegate([MarshalAs(UnmanagedType.LPStr)]string arg, int number_of_options, ref IntPtr options);
+ private static FunctionWrapper<cupsParseOptions_delegate> cupsParseOptions_ptr
+ = FunctionWrapper.Load<cupsParseOptions_delegate>(s_libcupsHandle, "cupsParseOptions");
+ internal static int cupsParseOptions(string arg, int number_of_options, ref IntPtr options)
+ => cupsParseOptions_ptr.Delegate(arg, number_of_options, ref options);
+
+ private delegate void cupsFreeOptions_delegate(int number_options, IntPtr options);
+ private static FunctionWrapper<cupsFreeOptions_delegate> cupsFreeOptions_ptr
+ = FunctionWrapper.Load<cupsFreeOptions_delegate>(s_libcupsHandle, "cupsFreeOptions");
+ internal static void cupsFreeOptions(int number_options, IntPtr options) => cupsFreeOptions_ptr.Delegate(number_options, options);
+ }
+}
diff --git a/src/System.Drawing.Common/src/Unix/System.Drawing.Printing/PageSettings.cs b/src/System.Drawing.Common/src/System/Drawing/Printing/PageSettings.Unix.cs
index ca643832cd..ca643832cd 100644
--- a/src/System.Drawing.Common/src/Unix/System.Drawing.Printing/PageSettings.cs
+++ b/src/System.Drawing.Common/src/System/Drawing/Printing/PageSettings.Unix.cs
diff --git a/src/System.Drawing.Common/src/System/Drawing/Printing/PageSettings.cs b/src/System.Drawing.Common/src/System/Drawing/Printing/PageSettings.Windows.cs
index 8635c234b0..8635c234b0 100644
--- a/src/System.Drawing.Common/src/System/Drawing/Printing/PageSettings.cs
+++ b/src/System.Drawing.Common/src/System/Drawing/Printing/PageSettings.Windows.cs
diff --git a/src/System.Drawing.Common/src/Unix/System.Drawing.Printing/PreviewPrintController.cs b/src/System.Drawing.Common/src/System/Drawing/Printing/PreviewPrintController.Unix.cs
index 7514415d1e..7514415d1e 100644
--- a/src/System.Drawing.Common/src/Unix/System.Drawing.Printing/PreviewPrintController.cs
+++ b/src/System.Drawing.Common/src/System/Drawing/Printing/PreviewPrintController.Unix.cs
diff --git a/src/System.Drawing.Common/src/System/Drawing/Printing/PreviewPrintController.cs b/src/System.Drawing.Common/src/System/Drawing/Printing/PreviewPrintController.Windows.cs
index 4bd40b9093..4bd40b9093 100644
--- a/src/System.Drawing.Common/src/System/Drawing/Printing/PreviewPrintController.cs
+++ b/src/System.Drawing.Common/src/System/Drawing/Printing/PreviewPrintController.Windows.cs
diff --git a/src/System.Drawing.Common/src/Unix/System.Drawing.Printing/PrintController.cs b/src/System.Drawing.Common/src/System/Drawing/Printing/PrintController.Unix.cs
index b9c482f067..b9c482f067 100644
--- a/src/System.Drawing.Common/src/Unix/System.Drawing.Printing/PrintController.cs
+++ b/src/System.Drawing.Common/src/System/Drawing/Printing/PrintController.Unix.cs
diff --git a/src/System.Drawing.Common/src/System/Drawing/Printing/PrintController.cs b/src/System.Drawing.Common/src/System/Drawing/Printing/PrintController.Windows.cs
index 9e9c2099e4..9e9c2099e4 100644
--- a/src/System.Drawing.Common/src/System/Drawing/Printing/PrintController.cs
+++ b/src/System.Drawing.Common/src/System/Drawing/Printing/PrintController.Windows.cs
diff --git a/src/System.Drawing.Common/src/Unix/System.Drawing.Printing/PrintDocument.cs b/src/System.Drawing.Common/src/System/Drawing/Printing/PrintDocument.Unix.cs
index 6c3a8e40ac..6c3a8e40ac 100644
--- a/src/System.Drawing.Common/src/Unix/System.Drawing.Printing/PrintDocument.cs
+++ b/src/System.Drawing.Common/src/System/Drawing/Printing/PrintDocument.Unix.cs
diff --git a/src/System.Drawing.Common/src/System/Drawing/Printing/PrintDocument.cs b/src/System.Drawing.Common/src/System/Drawing/Printing/PrintDocument.Windows.cs
index 70fee2afa5..70fee2afa5 100644
--- a/src/System.Drawing.Common/src/System/Drawing/Printing/PrintDocument.cs
+++ b/src/System.Drawing.Common/src/System/Drawing/Printing/PrintDocument.Windows.cs
diff --git a/src/System.Drawing.Common/src/Unix/System.Drawing.Printing/PrintEventArgs.cs b/src/System.Drawing.Common/src/System/Drawing/Printing/PrintEventArgs.Unix.cs
index 0ea43bbd92..0ea43bbd92 100644
--- a/src/System.Drawing.Common/src/Unix/System.Drawing.Printing/PrintEventArgs.cs
+++ b/src/System.Drawing.Common/src/System/Drawing/Printing/PrintEventArgs.Unix.cs
diff --git a/src/System.Drawing.Common/src/System/Drawing/Printing/PrintEvent.cs b/src/System.Drawing.Common/src/System/Drawing/Printing/PrintEventArgs.Windows.cs
index 41020b8bbf..41020b8bbf 100644
--- a/src/System.Drawing.Common/src/System/Drawing/Printing/PrintEvent.cs
+++ b/src/System.Drawing.Common/src/System/Drawing/Printing/PrintEventArgs.Windows.cs
diff --git a/src/System.Drawing.Common/src/Unix/System.Drawing.Printing/PrintPageEventArgs.cs b/src/System.Drawing.Common/src/System/Drawing/Printing/PrintPageEventArgs.Unix.cs
index 73a42bb5fc..73a42bb5fc 100644
--- a/src/System.Drawing.Common/src/Unix/System.Drawing.Printing/PrintPageEventArgs.cs
+++ b/src/System.Drawing.Common/src/System/Drawing/Printing/PrintPageEventArgs.Unix.cs
diff --git a/src/System.Drawing.Common/src/System/Drawing/Printing/PrintPageEvent.cs b/src/System.Drawing.Common/src/System/Drawing/Printing/PrintPageEventArgs.Windows.cs
index b7aeb80911..b7aeb80911 100644
--- a/src/System.Drawing.Common/src/System/Drawing/Printing/PrintPageEvent.cs
+++ b/src/System.Drawing.Common/src/System/Drawing/Printing/PrintPageEventArgs.Windows.cs
diff --git a/src/System.Drawing.Common/src/Unix/System.Drawing.Printing/PrinterSettings.cs b/src/System.Drawing.Common/src/System/Drawing/Printing/PrinterSettings.Unix.cs
index b2129379df..337713c187 100644
--- a/src/System.Drawing.Common/src/Unix/System.Drawing.Printing/PrinterSettings.cs
+++ b/src/System.Drawing.Common/src/System/Drawing/Printing/PrinterSettings.Unix.cs
@@ -62,19 +62,14 @@ namespace System.Drawing.Printing
private PageSettings default_pagesettings;
private Duplex duplex;
internal bool is_plotter;
- private PrintingServices printing_services;
internal NameValueCollection printer_capabilities; // this stores a list of all the printer options. Used only in cups, but might come in handy on win too.
- public PrinterSettings() : this(SysPrn.CreatePrintingService())
- {
- }
- internal PrinterSettings(PrintingServices printing_services)
+ public PrinterSettings()
{
- this.printing_services = printing_services;
- printer_name = printing_services.DefaultPrinter;
+ printer_name = PrintingServices.DefaultPrinter;
ResetToDefaults();
- printing_services.LoadPrinterSettings(printer_name, this);
+ PrintingServices.LoadPrinterSettings(printer_name, this);
}
private void ResetToDefaults()
@@ -152,12 +147,12 @@ namespace System.Drawing.Printing
public static PrinterSettings.StringCollection InstalledPrinters
{
- get { return SysPrn.GlobalService.InstalledPrinters; }
+ get { return PrintingServices.InstalledPrinters; }
}
public bool IsDefaultPrinter
{
- get { return (printer_name == printing_services.DefaultPrinter); }
+ get { return (printer_name == PrintingServices.DefaultPrinter); }
}
public bool IsPlotter
@@ -167,7 +162,7 @@ namespace System.Drawing.Printing
public bool IsValid
{
- get { return printing_services.IsPrinterValid(this.printer_name); }
+ get { return PrintingServices.IsPrinterValid(this.printer_name); }
}
public int LandscapeAngle
@@ -241,7 +236,7 @@ namespace System.Drawing.Printing
return;
printer_name = value;
- printing_services.LoadPrinterSettings(printer_name, this);
+ PrintingServices.LoadPrinterSettings(printer_name, this);
}
}
@@ -255,7 +250,7 @@ namespace System.Drawing.Printing
if (printer_resolutions == null)
{
printer_resolutions = new PrinterSettings.PrinterResolutionCollection(new PrinterResolution[] { });
- printing_services.LoadPrinterResolutions(printer_name, this);
+ PrintingServices.LoadPrinterResolutions(printer_name, this);
}
return printer_resolutions;
@@ -311,7 +306,7 @@ namespace System.Drawing.Printing
//methods
public object Clone()
{
- PrinterSettings ps = new PrinterSettings(printing_services);
+ PrinterSettings ps = new PrinterSettings();
return ps;
}
diff --git a/src/System.Drawing.Common/src/System/Drawing/Printing/PrinterSettings.cs b/src/System.Drawing.Common/src/System/Drawing/Printing/PrinterSettings.Windows.cs
index ccc03bea84..ccc03bea84 100644
--- a/src/System.Drawing.Common/src/System/Drawing/Printing/PrinterSettings.cs
+++ b/src/System.Drawing.Common/src/System/Drawing/Printing/PrinterSettings.Windows.cs
diff --git a/src/System.Drawing.Common/src/Unix/System.Drawing.Printing/PrintingServicesUnix.cs b/src/System.Drawing.Common/src/System/Drawing/Printing/PrintingServices.Unix.cs
index 11583fcf25..0e4d3773f8 100644
--- a/src/System.Drawing.Common/src/Unix/System.Drawing.Printing/PrintingServicesUnix.cs
+++ b/src/System.Drawing.Common/src/System/Drawing/Printing/PrintingServices.Unix.cs
@@ -1,9 +1,7 @@
// Licensed to the .NET Foundation under one or more agreements.
// See the LICENSE file in the project root for more information.
//
-//#define PrintDebug
-//
-// Copyright (C) 2005, 2007 Novell, Inc. http://www.novell.com
+// Copyright (C) 2005 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
@@ -31,24 +29,28 @@
using System.Runtime.InteropServices;
using System.Collections;
-using System.Collections.Specialized;
using System.Drawing.Printing;
using System.ComponentModel;
using System.Drawing.Imaging;
+using System.Diagnostics;
using System.Text;
using System.IO;
+using System.Collections.Specialized;
namespace System.Drawing.Printing
{
- internal class PrintingServicesUnix : PrintingServices
+ /// <summary>
+ /// This class is designed to cache the values retrieved by the
+ /// native printing services, as opposed to GlobalPrintingServices, which
+ /// doesn't cache any values.
+ /// </summary>
+ internal static class PrintingServices
{
#region Private Fields
private static Hashtable doc_info = new Hashtable();
private static bool cups_installed;
- //private string printer_name;
-
private static Hashtable installed_printers;
private static string default_printer = String.Empty;
@@ -56,11 +58,7 @@ namespace System.Drawing.Printing
#region Constructor
- internal PrintingServicesUnix()
- {
- }
-
- static PrintingServicesUnix()
+ static PrintingServices()
{
installed_printers = new Hashtable();
CheckCupsInstalled();
@@ -84,7 +82,7 @@ namespace System.Drawing.Printing
}
}
- internal override string DefaultPrinter
+ internal static string DefaultPrinter
{
get
{
@@ -106,7 +104,7 @@ namespace System.Drawing.Printing
{
try
{
- cupsGetDefault();
+ LibcupsNative.cupsGetDefault();
}
catch (DllNotFoundException)
{
@@ -126,13 +124,13 @@ namespace System.Drawing.Printing
/// Open the printer's PPD file
/// </summary>
/// <param name="printer">Printer name, returned from cupsGetDests</param>
- private IntPtr OpenPrinter(string printer)
+ private static IntPtr OpenPrinter(string printer)
{
try
{
- IntPtr ptr = cupsGetPPD(printer);
+ IntPtr ptr = LibcupsNative.cupsGetPPD(printer);
string ppd_filename = Marshal.PtrToStringAnsi(ptr);
- IntPtr ppd_handle = ppdOpenFile(ppd_filename);
+ IntPtr ppd_handle = LibcupsNative.ppdOpenFile(ppd_filename);
return ppd_handle;
}
catch (Exception)
@@ -140,7 +138,6 @@ namespace System.Drawing.Printing
#if NETCORE
System.Diagnostics.Debug.WriteLine("There was an error opening the printer {0}. Please check your cups installation.");
#else
-
Console.WriteLine("There was an error opening the printer {0}. Please check your cups installation.");
#endif
}
@@ -151,12 +148,12 @@ namespace System.Drawing.Printing
/// Close the printer file
/// </summary>
/// <param name="handle">PPD handle</param>
- private void ClosePrinter(ref IntPtr handle)
+ private static void ClosePrinter(ref IntPtr handle)
{
try
{
if (handle != IntPtr.Zero)
- ppdClose(handle);
+ LibcupsNative.ppdClose(handle);
}
finally
{
@@ -168,7 +165,7 @@ namespace System.Drawing.Printing
{
try
{
- return cupsGetDests(ref ptr);
+ return LibcupsNative.cupsGetDests(ref ptr);
}
catch
{
@@ -182,7 +179,7 @@ namespace System.Drawing.Printing
try
{
if (ptr != IntPtr.Zero)
- cupsFreeDests(count, ptr);
+ LibcupsNative.cupsFreeDests(count, ptr);
}
finally
{
@@ -194,22 +191,12 @@ namespace System.Drawing.Printing
/// Checks if a printer has a valid PPD file. Caches the result unless force is true
/// </summary>
/// <param name="force">Does the check disregarding the last cached value if true</param>
- internal override bool IsPrinterValid(string printer)
+ internal static bool IsPrinterValid(string printer)
{
if (!cups_installed || printer == null | printer == String.Empty)
return false;
return installed_printers.Contains(printer);
- /*
- if (!force && this.printer_name != null && String.Intern(this.printer_name).Equals(printer))
- return is_printer_valid;
-
- IntPtr ptr = cupsGetPPD (printer);
- string ppd_filename = Marshal.PtrToStringAnsi (ptr);
- is_printer_valid = ppd_filename != null;
- this.printer_name = printer;
- return is_printer_valid;
- */
}
/// <summary>
@@ -217,7 +204,7 @@ namespace System.Drawing.Printing
/// </summary>
/// <param name="printer">Printer name</param>
/// <param name="settings">PrinterSettings object to initialize</param>
- internal override void LoadPrinterSettings(string printer, PrinterSettings settings)
+ internal static void LoadPrinterSettings(string printer, PrinterSettings settings)
{
if (cups_installed == false || (printer == null) || (printer == String.Empty))
return;
@@ -405,7 +392,7 @@ namespace System.Drawing.Printing
int choice_size = Marshal.SizeOf(typeof(PPD_CHOICE));
defoption = null;
- ptr = ppdFindOption(ppd, option_name);
+ ptr = LibcupsNative.ppdFindOption(ppd, option_name);
if (ptr != IntPtr.Zero)
{
ppd_option = (PPD_OPTION)Marshal.PtrToStructure(ptr, typeof(PPD_OPTION));
@@ -432,7 +419,7 @@ namespace System.Drawing.Printing
/// </summary>
/// <param name="printer">Printer name</param>
/// <param name="settings">PrinterSettings object to fill</param>
- internal override void LoadPrinterResolutions(string printer, PrinterSettings settings)
+ internal static void LoadPrinterResolutions(string printer, PrinterSettings settings)
{
IntPtr ppd_handle = OpenPrinter(printer);
if (ppd_handle == IntPtr.Zero)
@@ -447,7 +434,7 @@ namespace System.Drawing.Printing
/// Create a PrinterResolution from a string Resolution that is set in the PPD option.
/// An example of Resolution is "600x600dpi" or "600dpi". Returns null if malformed or "Unknown".
/// </summary>
- private PrinterResolution ParseResolution(string resolution)
+ private static PrinterResolution ParseResolution(string resolution)
{
if (String.IsNullOrEmpty(resolution))
return null;
@@ -490,7 +477,7 @@ namespace System.Drawing.Printing
/// <param name="settings">PrinterSettings object to fill</param>
/// <param name="def_size">Default paper size, from the global options of the printer</param>
/// <param name="paper_names">List of available paper sizes that gets filled</param>
- private PaperSize LoadPrinterPaperSizes(IntPtr ppd_handle, PrinterSettings settings,
+ private static PaperSize LoadPrinterPaperSizes(IntPtr ppd_handle, PrinterSettings settings,
string def_size, NameValueCollection paper_names)
{
IntPtr ptr;
@@ -528,7 +515,7 @@ namespace System.Drawing.Printing
/// <param name="settings">PrinterSettings object to fill</param>
/// <param name="def_source">Default paper source, from the global options of the printer</param>
/// <param name="paper_sources">List of available paper sizes that gets filled</param>
- private PaperSource LoadPrinterPaperSources(PrinterSettings settings, string def_source,
+ private static PaperSource LoadPrinterPaperSources(PrinterSettings settings, string def_source,
NameValueCollection paper_sources)
{
PaperSourceKind kind;
@@ -570,7 +557,7 @@ namespace System.Drawing.Printing
/// Sets the available resolutions and default resolution from a
/// printer's PPD file into settings.
/// </summary>
- private void LoadPrinterResolutionsAndDefault(string printer,
+ private static void LoadPrinterResolutionsAndDefault(string printer,
PrinterSettings settings, IntPtr ppd_handle)
{
if (settings.printer_resolutions == null)
@@ -675,7 +662,7 @@ namespace System.Drawing.Printing
/// <param name="type"></param>
/// <param name="status"></param>
/// <param name="comment"></param>
- internal override void GetPrintDialogInfo(string printer, ref string port, ref string type, ref string status, ref string comment)
+ internal static void GetPrintDialogInfo(string printer, ref string port, ref string type, ref string status, ref string comment)
{
int count = 0, state = -1;
bool found = false;
@@ -743,7 +730,7 @@ namespace System.Drawing.Printing
/// </summary>
/// <param name="width"></param>
/// <param name="height"></param>
- private PaperKind GetPaperKind(int width, int height)
+ private static PaperKind GetPaperKind(int width, int height)
{
if (width == 827 && height == 1169)
return PaperKind.A4;
@@ -856,7 +843,7 @@ namespace System.Drawing.Printing
sb.Append(" Duplex=DuplexNoTumble");
}
- return cupsParseOptions(sb.ToString(), 0, ref options);
+ return LibcupsNative.cupsParseOptions(sb.ToString(), 0, ref options);
}
internal static bool StartDoc(GraphicsPrinter gr, string doc_name, string output_file)
@@ -875,8 +862,8 @@ namespace System.Drawing.Printing
IntPtr options;
int options_count = GetCupsOptions(doc.settings, doc.default_page_settings, out options);
- cupsPrintFile(doc.settings.PrinterName, doc.filename, doc.title, options_count, options);
- cupsFreeOptions(options_count, options);
+ LibcupsNative.cupsPrintFile(doc.settings.PrinterName, doc.filename, doc.title, options_count, options);
+ LibcupsNative.cupsFreeOptions(options_count, options);
doc_info.Remove(gr.Hdc);
if (tmpfile != null)
{
@@ -894,7 +881,7 @@ namespace System.Drawing.Printing
internal static bool EndPage(GraphicsPrinter gr)
{
- GdipGetPostScriptSavePage(gr.Hdc);
+ SafeNativeMethods.Gdip.GdipGetPostScriptSavePage(gr.Hdc);
return true;
}
@@ -908,7 +895,7 @@ namespace System.Drawing.Printing
{
StringBuilder sb = new StringBuilder(1024);
int length = sb.Capacity;
- cupsTempFd(sb, length);
+ LibcupsNative.cupsTempFd(sb, length);
name = sb.ToString();
tmpfile = name;
}
@@ -928,7 +915,7 @@ namespace System.Drawing.Printing
height = psize.Height;
}
- GdipGetPostScriptGraphicsContext(name,
+ SafeNativeMethods.Gdip.GdipGetPostScriptGraphicsContext(name,
width * 72 / 100,
height * 72 / 100,
default_page_settings.PrinterResolution.X,
@@ -945,52 +932,6 @@ namespace System.Drawing.Printing
#endregion
- #region DllImports
-
- [DllImport("libcups", CharSet = CharSet.Ansi)]
- static extern int cupsGetDests(ref IntPtr dests);
-
- // [DllImport("libcups", CharSet=CharSet.Ansi)]
- // static extern void cupsGetDest (string name, string instance, int num_dests, ref IntPtr dests);
-
- [DllImport("libcups")]
- static extern void cupsFreeDests(int num_dests, IntPtr dests);
-
- [DllImport("libcups", CharSet = CharSet.Ansi)]
- static extern IntPtr cupsTempFd(StringBuilder sb, int len);
-
- [DllImport("libcups", CharSet = CharSet.Ansi)]
- static extern IntPtr cupsGetDefault();
-
- [DllImport("libcups", CharSet = CharSet.Ansi)]
- static extern int cupsPrintFile(string printer, string filename, string title, int num_options, IntPtr options);
-
- [DllImport("libcups", CharSet = CharSet.Ansi)]
- static extern IntPtr cupsGetPPD(string printer);
-
- [DllImport("libcups", CharSet = CharSet.Ansi)]
- static extern IntPtr ppdOpenFile(string filename);
-
- [DllImport("libcups", CharSet = CharSet.Ansi)]
- static extern IntPtr ppdFindOption(IntPtr ppd_file, string keyword);
-
- [DllImport("libcups")]
- static extern void ppdClose(IntPtr ppd);
-
- [DllImport("libcups", CharSet = CharSet.Ansi)]
- static extern int cupsParseOptions(string arg, int number_of_options, ref IntPtr options);
-
- [DllImport("libcups")]
- static extern void cupsFreeOptions(int number_options, IntPtr options);
-
- [DllImport("gdiplus.dll", CharSet = CharSet.Ansi)]
- static extern int GdipGetPostScriptGraphicsContext(string filename, int with, int height, double dpix, double dpiy, ref IntPtr graphics);
-
- [DllImport("gdiplus.dll")]
- static extern int GdipGetPostScriptSavePage(IntPtr graphics);
-
- #endregion
-
#pragma warning disable 649
#region Struct
public struct DOCINFO
@@ -1105,42 +1046,56 @@ namespace System.Drawing.Printing
#endregion
#pragma warning restore 649
+ internal static void LoadDefaultResolutions(PrinterSettings.PrinterResolutionCollection col)
+ {
+ col.Add(new PrinterResolution(PrinterResolutionKind.High, (int)PrinterResolutionKind.High, -1));
+ col.Add(new PrinterResolution(PrinterResolutionKind.Medium, (int)PrinterResolutionKind.Medium, -1));
+ col.Add(new PrinterResolution(PrinterResolutionKind.Low, (int)PrinterResolutionKind.Low, -1));
+ col.Add(new PrinterResolution(PrinterResolutionKind.Draft, (int)PrinterResolutionKind.Draft, -1));
+ }
}
- class GlobalPrintingServicesUnix : GlobalPrintingServices
+ internal class SysPrn
{
- internal override PrinterSettings.StringCollection InstalledPrinters
+ internal static void GetPrintDialogInfo(string printer, ref string port, ref string type, ref string status, ref string comment)
{
- get
- {
- return PrintingServicesUnix.InstalledPrinters;
- }
+ PrintingServices.GetPrintDialogInfo(printer, ref port, ref type, ref status, ref comment);
}
- internal override IntPtr CreateGraphicsContext(PrinterSettings settings, PageSettings default_page_settings)
+ internal class Printer
{
- return PrintingServicesUnix.CreateGraphicsContext(settings, default_page_settings);
- }
+ public readonly string Comment;
+ public readonly string Port;
+ public readonly string Type;
+ public readonly string Status;
+ public PrinterSettings Settings;
- internal override bool StartDoc(GraphicsPrinter gr, string doc_name, string output_file)
- {
- return PrintingServicesUnix.StartDoc(gr, doc_name, output_file);
+ public Printer(string port, string type, string status, string comment)
+ {
+ Port = port;
+ Type = type;
+ Status = status;
+ Comment = comment;
+ }
}
+ }
- internal override bool EndDoc(GraphicsPrinter gr)
- {
- return PrintingServicesUnix.EndDoc(gr);
- }
+ internal class GraphicsPrinter
+ {
+ private Graphics graphics;
+ private IntPtr hDC;
- internal override bool StartPage(GraphicsPrinter gr)
+ internal GraphicsPrinter(Graphics gr, IntPtr dc)
{
- return PrintingServicesUnix.StartPage(gr);
+ graphics = gr;
+ hDC = dc;
}
- internal override bool EndPage(GraphicsPrinter gr)
+ internal Graphics Graphics
{
- return PrintingServicesUnix.EndPage(gr);
+ get { return graphics; }
+ set { graphics = value; }
}
+ internal IntPtr Hdc { get { return hDC; } }
}
}
-
diff --git a/src/System.Drawing.Common/src/Unix/System.Drawing.Printing/StandardPrintController.cs b/src/System.Drawing.Common/src/System/Drawing/Printing/StandardPrintController.Unix.cs
index c7cb2d1c47..d8ed01bf2d 100644
--- a/src/System.Drawing.Common/src/Unix/System.Drawing.Printing/StandardPrintController.cs
+++ b/src/System.Drawing.Common/src/System/Drawing/Printing/StandardPrintController.Unix.cs
@@ -46,24 +46,24 @@ namespace System.Drawing.Printing
public override void OnEndPage(PrintDocument document, PrintPageEventArgs e)
{
- SysPrn.GlobalService.EndPage(e.GraphicsContext);
+ PrintingServices.EndPage(e.GraphicsContext);
}
public override void OnStartPrint(PrintDocument document, PrintEventArgs e)
{
- IntPtr dc = SysPrn.GlobalService.CreateGraphicsContext(document.PrinterSettings, document.DefaultPageSettings);
+ IntPtr dc = PrintingServices.CreateGraphicsContext(document.PrinterSettings, document.DefaultPageSettings);
e.GraphicsContext = new GraphicsPrinter(null, dc);
- SysPrn.GlobalService.StartDoc(e.GraphicsContext, document.DocumentName, string.Empty);
+ PrintingServices.StartDoc(e.GraphicsContext, document.DocumentName, string.Empty);
}
public override void OnEndPrint(PrintDocument document, PrintEventArgs e)
{
- SysPrn.GlobalService.EndDoc(e.GraphicsContext);
+ PrintingServices.EndDoc(e.GraphicsContext);
}
public override Graphics OnStartPage(PrintDocument document, PrintPageEventArgs e)
{
- SysPrn.GlobalService.StartPage(e.GraphicsContext);
+ PrintingServices.StartPage(e.GraphicsContext);
return e.Graphics;
}
}
diff --git a/src/System.Drawing.Common/src/Unix/System.Drawing/SRDescriptionAttribute.cs b/src/System.Drawing.Common/src/System/Drawing/SRDescriptionAttribute.cs
index 6cb35b8b89..6cb35b8b89 100644
--- a/src/System.Drawing.Common/src/Unix/System.Drawing/SRDescriptionAttribute.cs
+++ b/src/System.Drawing.Common/src/System/Drawing/SRDescriptionAttribute.cs
diff --git a/src/System.Drawing.Common/src/Unix/System.Drawing/SystemIcons.cs b/src/System.Drawing.Common/src/System/Drawing/SystemIcons.Unix.cs
index 2516f81bfa..2516f81bfa 100644
--- a/src/System.Drawing.Common/src/Unix/System.Drawing/SystemIcons.cs
+++ b/src/System.Drawing.Common/src/System/Drawing/SystemIcons.Unix.cs
diff --git a/src/System.Drawing.Common/src/System/Drawing/SystemIcons.cs b/src/System.Drawing.Common/src/System/Drawing/SystemIcons.Windows.cs
index 13b4c742c3..13b4c742c3 100644
--- a/src/System.Drawing.Common/src/System/Drawing/SystemIcons.cs
+++ b/src/System.Drawing.Common/src/System/Drawing/SystemIcons.Windows.cs
diff --git a/src/System.Drawing.Common/src/System/Drawing/TextureBrush.cs b/src/System.Drawing.Common/src/System/Drawing/TextureBrush.cs
index c39f329afc..1710dfb4dc 100644
--- a/src/System.Drawing.Common/src/System/Drawing/TextureBrush.cs
+++ b/src/System.Drawing.Common/src/System/Drawing/TextureBrush.cs
@@ -168,7 +168,7 @@ namespace System.Drawing
{
if (value == null)
{
- throw new ArgumentNullException("value");
+ throw new ArgumentNullException(nameof(value));
}
int status = SafeNativeMethods.Gdip.GdipSetTextureTransform(new HandleRef(this, NativeBrush), new HandleRef(value, value.nativeMatrix));
@@ -225,6 +225,13 @@ namespace System.Drawing
throw new ArgumentNullException(nameof(matrix));
}
+ // Multiplying the transform by a disposed matrix is a nop in GDI+, but throws
+ // with the libgdiplus backend. Simulate a nop for compatability with GDI+.
+ if (matrix.nativeMatrix == IntPtr.Zero)
+ {
+ return;
+ }
+
int status = SafeNativeMethods.Gdip.GdipMultiplyTextureTransform(new HandleRef(this, NativeBrush),
new HandleRef(matrix, matrix.nativeMatrix),
order);
diff --git a/src/System.Drawing.Common/src/Unix/System.Drawing/ToolboxBitmapAttribute.cs b/src/System.Drawing.Common/src/System/Drawing/ToolboxBitmapAttribute.Unix.cs
index 356fddd4b1..356fddd4b1 100644
--- a/src/System.Drawing.Common/src/Unix/System.Drawing/ToolboxBitmapAttribute.cs
+++ b/src/System.Drawing.Common/src/System/Drawing/ToolboxBitmapAttribute.Unix.cs
diff --git a/src/System.Drawing.Common/src/Unix/System.Drawing/macFunctions.cs b/src/System.Drawing.Common/src/System/Drawing/macFunctions.cs
index f15b66ac60..f15b66ac60 100644
--- a/src/System.Drawing.Common/src/Unix/System.Drawing/macFunctions.cs
+++ b/src/System.Drawing.Common/src/System/Drawing/macFunctions.cs
diff --git a/src/System.Drawing.Common/src/Unix/System.Drawing.Imaging/ImageFormat.cs b/src/System.Drawing.Common/src/Unix/System.Drawing.Imaging/ImageFormat.cs
deleted file mode 100644
index 1618926ae9..0000000000
--- a/src/System.Drawing.Common/src/Unix/System.Drawing.Imaging/ImageFormat.cs
+++ /dev/null
@@ -1,259 +0,0 @@
-// Licensed to the .NET Foundation under one or more agreements.
-// See the LICENSE file in the project root for more information.
-//
-// System.Drawing.Imaging.ImageFormat.cs
-//
-// Authors:
-// Everaldo Canuto (everaldo.canuto@bol.com.br)
-// Andreas Nahr (ClassDevelopment@A-SoftTech.com)
-// Dennis Hayes (dennish@raytek.com)
-// Jordi Mas i Hernandez (jordi@ximian.com)
-// Sebastien Pouliot <sebastien@ximian.com>
-//
-// (C) 2002-4 Ximian, Inc. http://www.ximian.com
-// Copyright (C) 2004,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.ComponentModel;
-
-namespace System.Drawing.Imaging
-{
-#if !NETCORE
- [TypeConverter (typeof (ImageFormatConverter))]
-#endif
- public sealed class ImageFormat
- {
-
- private Guid guid;
- private string name;
-
- private const string BmpGuid = "b96b3cab-0728-11d3-9d7b-0000f81ef32e";
- private const string EmfGuid = "b96b3cac-0728-11d3-9d7b-0000f81ef32e";
- private const string ExifGuid = "b96b3cb2-0728-11d3-9d7b-0000f81ef32e";
- private const string GifGuid = "b96b3cb0-0728-11d3-9d7b-0000f81ef32e";
- private const string TiffGuid = "b96b3cb1-0728-11d3-9d7b-0000f81ef32e";
- private const string PngGuid = "b96b3caf-0728-11d3-9d7b-0000f81ef32e";
- private const string MemoryBmpGuid = "b96b3caa-0728-11d3-9d7b-0000f81ef32e";
- private const string IconGuid = "b96b3cb5-0728-11d3-9d7b-0000f81ef32e";
- private const string JpegGuid = "b96b3cae-0728-11d3-9d7b-0000f81ef32e";
- private const string WmfGuid = "b96b3cad-0728-11d3-9d7b-0000f81ef32e";
-
- // lock(this) is bad
- // http://msdn.microsoft.com/library/en-us/dnaskdr/html/askgui06032003.asp?frame=true
- private static object locker = new object();
-
- private static ImageFormat BmpImageFormat;
- private static ImageFormat EmfImageFormat;
- private static ImageFormat ExifImageFormat;
- private static ImageFormat GifImageFormat;
- private static ImageFormat TiffImageFormat;
- private static ImageFormat PngImageFormat;
- private static ImageFormat MemoryBmpImageFormat;
- private static ImageFormat IconImageFormat;
- private static ImageFormat JpegImageFormat;
- private static ImageFormat WmfImageFormat;
-
-
- // constructors
- public ImageFormat(Guid guid)
- {
- this.guid = guid;
- }
-
- private ImageFormat(string name, string guid)
- {
- this.name = name;
- this.guid = new Guid(guid);
- }
-
-
- // methods
- public override bool Equals(object o)
- {
- ImageFormat f = (o as ImageFormat);
- if (f == null)
- return false;
-
- return f.Guid.Equals(guid);
- }
-
-
- public override int GetHashCode()
- {
- return guid.GetHashCode();
- }
-
-
- public override string ToString()
- {
- if (name != null)
- return name;
-
- return ("[ImageFormat: " + guid.ToString() + "]");
- }
-
- // properties
- public Guid Guid
- {
- get { return guid; }
- }
-
-
- public static ImageFormat Bmp
- {
- get
- {
- lock (locker)
- {
- if (BmpImageFormat == null)
- BmpImageFormat = new ImageFormat("Bmp", BmpGuid);
- return BmpImageFormat;
- }
- }
- }
-
- public static ImageFormat Emf
- {
- get
- {
- lock (locker)
- {
- if (EmfImageFormat == null)
- EmfImageFormat = new ImageFormat("Emf", EmfGuid);
- return EmfImageFormat;
- }
- }
- }
-
-
- public static ImageFormat Exif
- {
- get
- {
- lock (locker)
- {
- if (ExifImageFormat == null)
- ExifImageFormat = new ImageFormat("Exif", ExifGuid);
- return ExifImageFormat;
- }
- }
- }
-
-
- public static ImageFormat Gif
- {
- get
- {
- lock (locker)
- {
- if (GifImageFormat == null)
- GifImageFormat = new ImageFormat("Gif", GifGuid);
- return GifImageFormat;
- }
- }
- }
-
-
- public static ImageFormat Icon
- {
- get
- {
- lock (locker)
- {
- if (IconImageFormat == null)
- IconImageFormat = new ImageFormat("Icon", IconGuid);
- return IconImageFormat;
- }
- }
- }
-
-
- public static ImageFormat Jpeg
- {
- get
- {
- lock (locker)
- {
- if (JpegImageFormat == null)
- JpegImageFormat = new ImageFormat("Jpeg", JpegGuid);
- return JpegImageFormat;
- }
- }
- }
-
-
- public static ImageFormat MemoryBmp
- {
- get
- {
- lock (locker)
- {
- if (MemoryBmpImageFormat == null)
- MemoryBmpImageFormat = new ImageFormat("MemoryBMP", MemoryBmpGuid);
- return MemoryBmpImageFormat;
- }
- }
- }
-
-
- public static ImageFormat Png
- {
- get
- {
- lock (locker)
- {
- if (PngImageFormat == null)
- PngImageFormat = new ImageFormat("Png", PngGuid);
- return PngImageFormat;
- }
- }
- }
-
-
- public static ImageFormat Tiff
- {
- get
- {
- lock (locker)
- {
- if (TiffImageFormat == null)
- TiffImageFormat = new ImageFormat("Tiff", TiffGuid);
- return TiffImageFormat;
- }
- }
- }
-
-
- public static ImageFormat Wmf
- {
- get
- {
- lock (locker)
- {
- if (WmfImageFormat == null)
- WmfImageFormat = new ImageFormat("Wmf", WmfGuid);
- return WmfImageFormat;
- }
- }
- }
- }
-}
diff --git a/src/System.Drawing.Common/src/Unix/System.Drawing.Printing/PrintingServices.cs b/src/System.Drawing.Common/src/Unix/System.Drawing.Printing/PrintingServices.cs
deleted file mode 100644
index 07d6e1ab12..0000000000
--- a/src/System.Drawing.Common/src/Unix/System.Drawing.Printing/PrintingServices.cs
+++ /dev/null
@@ -1,162 +0,0 @@
-// Licensed to the .NET Foundation under one or more agreements.
-// See the LICENSE file in the project root for more information.
-//
-// Copyright (C) 2005 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.
-//
-// Author:
-//
-// Jordi Mas i Hernandez, jordimash@gmail.com
-//
-
-using System.Runtime.InteropServices;
-using System.Collections;
-using System.Drawing.Printing;
-using System.ComponentModel;
-using System.Drawing.Imaging;
-
-namespace System.Drawing.Printing
-{
- /// <summary>
- /// This class is designed to cache the values retrieved by the
- /// native printing services, as opposed to GlobalPrintingServices, which
- /// doesn't cache any values.
- /// </summary>
- internal abstract class PrintingServices
- {
- #region Properties
- internal abstract string DefaultPrinter { get; }
- #endregion
-
- #region Methods
- internal abstract bool IsPrinterValid(string printer);
- internal abstract void LoadPrinterSettings(string printer, PrinterSettings settings);
- internal abstract void LoadPrinterResolutions(string printer, PrinterSettings settings);
-
- // Used from SWF
- internal abstract void GetPrintDialogInfo(string printer, ref string port, ref string type, ref string status, ref string comment);
-
- internal void LoadDefaultResolutions(PrinterSettings.PrinterResolutionCollection col)
- {
- col.Add(new PrinterResolution(PrinterResolutionKind.High, (int)PrinterResolutionKind.High, -1));
- col.Add(new PrinterResolution(PrinterResolutionKind.Medium, (int)PrinterResolutionKind.Medium, -1));
- col.Add(new PrinterResolution(PrinterResolutionKind.Low, (int)PrinterResolutionKind.Low, -1));
- col.Add(new PrinterResolution(PrinterResolutionKind.Draft, (int)PrinterResolutionKind.Draft, -1));
- }
- #endregion
- }
-
- internal abstract class GlobalPrintingServices
- {
- #region Properties
- internal abstract PrinterSettings.StringCollection InstalledPrinters { get; }
- #endregion
-
- #region Methods
- internal abstract IntPtr CreateGraphicsContext(PrinterSettings settings, PageSettings page_settings);
-
- internal abstract bool StartDoc(GraphicsPrinter gr, string doc_name, string output_file);
- internal abstract bool StartPage(GraphicsPrinter gr);
- internal abstract bool EndPage(GraphicsPrinter gr);
- internal abstract bool EndDoc(GraphicsPrinter gr);
- #endregion
-
- }
-
- internal class SysPrn
- {
- static GlobalPrintingServices global_printing_services;
- static bool is_unix;
-
- static SysPrn()
- {
- is_unix = GDIPlus.RunningOnUnix();
- }
-
- internal static PrintingServices CreatePrintingService()
- {
- if (is_unix)
- return new PrintingServicesUnix();
- return new PrintingServicesWin32();
- }
-
- internal static GlobalPrintingServices GlobalService
- {
- get
- {
- if (global_printing_services == null)
- {
- if (is_unix)
- global_printing_services = new GlobalPrintingServicesUnix();
- else
- global_printing_services = new GlobalPrintingServicesWin32();
- }
-
- return global_printing_services;
- }
- }
-
- internal static void GetPrintDialogInfo(string printer, ref string port, ref string type, ref string status, ref string comment)
- {
- CreatePrintingService().GetPrintDialogInfo(printer, ref port, ref type, ref status, ref comment);
- }
-
- internal class Printer
- {
- //public readonly string Name;
- public readonly string Comment;
- public readonly string Port;
- public readonly string Type;
- public readonly string Status;
- public PrinterSettings Settings;
- //public bool IsDefault;
-
- public Printer(string port, string type, string status, string comment)
- {
- Port = port;
- Type = type;
- Status = status;
- Comment = comment;
- }
- }
- }
-
- internal class GraphicsPrinter
- {
- private Graphics graphics;
- private IntPtr hDC;
-
- internal GraphicsPrinter(Graphics gr, IntPtr dc)
- {
- graphics = gr;
- hDC = dc;
- }
-
- internal Graphics Graphics
- {
- get { return graphics; }
- set { graphics = value; }
- }
- internal IntPtr Hdc { get { return hDC; } }
- }
-}
-
-
diff --git a/src/System.Drawing.Common/src/Unix/System.Drawing.Printing/PrintingServicesWin32.cs b/src/System.Drawing.Common/src/Unix/System.Drawing.Printing/PrintingServicesWin32.cs
deleted file mode 100644
index d4217142c2..0000000000
--- a/src/System.Drawing.Common/src/Unix/System.Drawing.Printing/PrintingServicesWin32.cs
+++ /dev/null
@@ -1,743 +0,0 @@
-// Licensed to the .NET Foundation under one or more agreements.
-// See the LICENSE file in the project root for more information.
-//
-// Copyright (C) 2005 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.
-//
-// Author:
-//
-// Jordi Mas i Hernandez, jordimash@gmail.com
-//
-
-using System.Runtime.InteropServices;
-using System.Collections;
-using System.Drawing.Printing;
-using System.ComponentModel;
-using System.Text;
-
-namespace System.Drawing.Printing
-{
- internal class PrintingServicesWin32 : PrintingServices
- {
- // private string printer_name;
- private bool is_printer_valid;
-
- internal PrintingServicesWin32()
- {
-
- }
-
- internal override bool IsPrinterValid(string printer)
- {
- if (printer == null | printer == String.Empty)
- return false;
-
- int ret = Win32DocumentProperties(IntPtr.Zero, IntPtr.Zero, printer, IntPtr.Zero, IntPtr.Zero, 0);
- is_printer_valid = (ret > 0);
- // this.printer_name = printer;
- return is_printer_valid;
- }
-
- internal override void LoadPrinterSettings(string printer, PrinterSettings settings)
- {
- int ret;
- DEVMODE devmode;
- IntPtr hPrn = IntPtr.Zero;
- IntPtr ptr_dev = IntPtr.Zero;
-
- settings.maximum_copies = Win32DeviceCapabilities(printer, null, DCCapabilities.DC_COPIES, IntPtr.Zero, IntPtr.Zero);
-
- ret = Win32DeviceCapabilities(printer, null, DCCapabilities.DC_DUPLEX, IntPtr.Zero, IntPtr.Zero);
- settings.can_duplex = (ret == 1) ? true : false;
-
- ret = Win32DeviceCapabilities(printer, null, DCCapabilities.DC_COLORDEVICE, IntPtr.Zero, IntPtr.Zero);
- settings.supports_color = (ret == 1) ? true : false;
-
- ret = Win32DeviceCapabilities(printer, null, DCCapabilities.DC_ORIENTATION, IntPtr.Zero, IntPtr.Zero);
- if (ret != -1)
- settings.landscape_angle = ret;
-
- IntPtr dc = IntPtr.Zero;
- dc = Win32CreateIC(null, printer, null, IntPtr.Zero /* DEVMODE */);
- ret = Win32GetDeviceCaps(dc, (int)DevCapabilities.TECHNOLOGY);
- settings.is_plotter = ret == (int)PrinterType.DT_PLOTTER;
- Win32DeleteDC(dc);
-
- try
- {
- Win32OpenPrinter(printer, out hPrn, IntPtr.Zero);
- ret = Win32DocumentProperties(IntPtr.Zero, hPrn, null, IntPtr.Zero, IntPtr.Zero, 0);
-
- if (ret < 0)
- return;
-
- ptr_dev = Marshal.AllocHGlobal(ret);
- ret = Win32DocumentProperties(IntPtr.Zero, hPrn, null, ptr_dev, IntPtr.Zero, 2);
-
- devmode = (DEVMODE)Marshal.PtrToStructure(ptr_dev, typeof(DEVMODE));
-
- LoadPrinterPaperSizes(printer, settings);
- foreach (PaperSize paper_size in settings.PaperSizes)
- {
- if ((int)paper_size.Kind == devmode.dmPaperSize)
- {
- settings.DefaultPageSettings.PaperSize = paper_size;
- break;
- }
- }
-
- LoadPrinterPaperSources(printer, settings);
- foreach (PaperSource paper_source in settings.PaperSources)
- {
- if ((int)paper_source.Kind == devmode.dmDefaultSource)
- {
- settings.DefaultPageSettings.PaperSource = paper_source;
- break;
- }
- }
- }
- finally
- {
- Win32ClosePrinter(hPrn);
-
- if (ptr_dev != IntPtr.Zero)
- Marshal.FreeHGlobal(ptr_dev);
- }
-
-
- }
-
- internal override void LoadPrinterResolutions(string printer, PrinterSettings settings)
- {
- int ret;
- IntPtr ptr, buff = IntPtr.Zero;
-
- settings.PrinterResolutions.Clear();
- LoadDefaultResolutions(settings.PrinterResolutions);
- ret = Win32DeviceCapabilities(printer, null, DCCapabilities.DC_ENUMRESOLUTIONS, IntPtr.Zero, IntPtr.Zero);
-
- if (ret == -1)
- return;
-
- ptr = buff = Marshal.AllocHGlobal(ret * 2 * Marshal.SizeOf(buff));
- ret = Win32DeviceCapabilities(printer, null, DCCapabilities.DC_ENUMRESOLUTIONS, buff, IntPtr.Zero);
- int x, y;
- if (ret != -1)
- {
- for (int i = 0; i < ret; i++)
- {
- x = Marshal.ReadInt32(ptr);
- ptr = new IntPtr(ptr.ToInt64() + Marshal.SizeOf(x));
- y = Marshal.ReadInt32(ptr);
- ptr = new IntPtr(ptr.ToInt64() + Marshal.SizeOf(y));
- settings.PrinterResolutions.Add(new PrinterResolution
- (PrinterResolutionKind.Custom, x, y));
- }
- }
- Marshal.FreeHGlobal(buff);
- }
-
- void LoadPrinterPaperSizes(string printer, PrinterSettings settings)
- {
- int items, ret;
- IntPtr ptr_names, buff_names = IntPtr.Zero;
- IntPtr ptr_sizes, buff_sizes = IntPtr.Zero;
- IntPtr ptr_sizes_enum, buff_sizes_enum = IntPtr.Zero;
- string name;
-
- if (settings.PaperSizes == null)
- settings.paper_sizes = new PrinterSettings.PaperSizeCollection(new PaperSize[0]);
- else
- settings.PaperSizes.Clear();
-
- items = Win32DeviceCapabilities(printer, null, DCCapabilities.DC_PAPERSIZE, IntPtr.Zero, IntPtr.Zero);
-
- if (items == -1)
- return;
-
- try
- {
- ptr_sizes = buff_sizes = Marshal.AllocHGlobal(items * 2 * 4);
- ptr_names = buff_names = Marshal.AllocHGlobal(items * 64 * 2);
- ptr_sizes_enum = buff_sizes_enum = Marshal.AllocHGlobal(items * 2);
- ret = Win32DeviceCapabilities(printer, null, DCCapabilities.DC_PAPERSIZE, buff_sizes, IntPtr.Zero);
-
- if (ret == -1)
- {
- // the finally clause will free the unmanaged memory before returning
- return;
- }
-
- ret = Win32DeviceCapabilities(printer, null, DCCapabilities.DC_PAPERS, buff_sizes_enum, IntPtr.Zero);
- ret = Win32DeviceCapabilities(printer, null, DCCapabilities.DC_PAPERNAMES, buff_names, IntPtr.Zero);
-
- int x, y;
- PaperSize ps;
- PaperKind kind;
- for (int i = 0; i < ret; i++)
- {
- x = Marshal.ReadInt32(ptr_sizes, i * 8);
- y = Marshal.ReadInt32(ptr_sizes, (i * 8) + 4);
-
- x = PrinterUnitConvert.Convert(x, PrinterUnit.TenthsOfAMillimeter,
- PrinterUnit.Display);
-
- y = PrinterUnitConvert.Convert(y, PrinterUnit.TenthsOfAMillimeter,
- PrinterUnit.Display);
-
- name = Marshal.PtrToStringUni(ptr_names);
- ptr_names = new IntPtr(ptr_names.ToInt64() + 64 * 2);
-
- kind = (PaperKind)Marshal.ReadInt16(ptr_sizes_enum);
- ptr_sizes_enum = new IntPtr(ptr_sizes_enum.ToInt64() + 2);
-
- ps = new PaperSize(name, x, y);
- ps.RawKind = (int)kind;
- settings.PaperSizes.Add(ps);
- }
- }
- finally
- {
- if (buff_names != IntPtr.Zero)
- Marshal.FreeHGlobal(buff_names);
- if (buff_sizes != IntPtr.Zero)
- Marshal.FreeHGlobal(buff_sizes);
- if (buff_sizes_enum != IntPtr.Zero)
- Marshal.FreeHGlobal(buff_sizes_enum);
- }
- }
-
- internal static bool StartDoc(GraphicsPrinter gr, string doc_name, string output_file)
- {
- DOCINFO di = new DOCINFO();
- int ret;
-
- di.cbSize = Marshal.SizeOf(di);
- di.lpszDocName = Marshal.StringToHGlobalUni(doc_name);
- di.lpszOutput = IntPtr.Zero;
- di.lpszDatatype = IntPtr.Zero;
- di.fwType = 0;
-
- ret = Win32StartDoc(gr.Hdc, ref di);
- Marshal.FreeHGlobal(di.lpszDocName);
- return (ret > 0) ? true : false;
- }
-
- void LoadPrinterPaperSources(string printer, PrinterSettings settings)
- {
- int items, ret;
- IntPtr ptr_names, buff_names = IntPtr.Zero;
- IntPtr ptr_bins, buff_bins = IntPtr.Zero;
- PaperSourceKind kind;
- string name;
-
- if (settings.PaperSources == null)
- settings.paper_sources = new PrinterSettings.PaperSourceCollection(new PaperSource[0]);
- else
- settings.PaperSources.Clear();
-
- items = Win32DeviceCapabilities(printer, null, DCCapabilities.DC_BINNAMES, IntPtr.Zero, IntPtr.Zero);
-
- if (items == -1)
- return;
-
- try
- {
- ptr_names = buff_names = Marshal.AllocHGlobal(items * 2 * 24);
- ptr_bins = buff_bins = Marshal.AllocHGlobal(items * 2);
-
- ret = Win32DeviceCapabilities(printer, null, DCCapabilities.DC_BINNAMES, buff_names, IntPtr.Zero);
-
- if (ret == -1)
- {
- // the finally clause will free the unmanaged memory before returning
- return;
- }
-
- ret = Win32DeviceCapabilities(printer, null, DCCapabilities.DC_BINS, buff_bins, IntPtr.Zero);
-
- for (int i = 0; i < ret; i++)
- {
- name = Marshal.PtrToStringUni(ptr_names);
- kind = (PaperSourceKind)Marshal.ReadInt16(ptr_bins);
- settings.PaperSources.Add(new PaperSource(kind, name));
-
- ptr_names = new IntPtr(ptr_names.ToInt64() + 24 * 2);
- ptr_bins = new IntPtr(ptr_bins.ToInt64() + 2);
- }
-
- }
- finally
- {
- if (buff_names != IntPtr.Zero)
- Marshal.FreeHGlobal(buff_names);
-
- if (buff_bins != IntPtr.Zero)
- Marshal.FreeHGlobal(buff_bins);
-
- }
-
- }
-
- internal static bool StartPage(GraphicsPrinter gr)
- {
- int ret = Win32StartPage(gr.Hdc);
- return (ret > 0) ? true : false;
- }
-
- internal static bool EndPage(GraphicsPrinter gr)
- {
- int ret = Win32EndPage(gr.Hdc);
- return (ret > 0) ? true : false;
- }
-
- internal static bool EndDoc(GraphicsPrinter gr)
- {
- int ret = Win32EndDoc(gr.Hdc);
- Win32DeleteDC(gr.Hdc);
- gr.Graphics.Dispose();
- return (ret > 0) ? true : false;
- }
-
- internal static IntPtr CreateGraphicsContext(PrinterSettings settings, PageSettings default_page_settings)
- {
- IntPtr dc = IntPtr.Zero;
- dc = Win32CreateDC(null, settings.PrinterName, null, IntPtr.Zero /* DEVMODE */);
- return dc;
- }
-
- // Properties
- internal override string DefaultPrinter
- {
- get
- {
- StringBuilder name = new StringBuilder(1024);
- int length = name.Capacity;
-
- if (Win32GetDefaultPrinter(name, ref length) > 0)
- if (IsPrinterValid(name.ToString()))
- return name.ToString();
- return String.Empty;
- }
- }
-
- internal static PrinterSettings.StringCollection InstalledPrinters
- {
- get
- {
- PrinterSettings.StringCollection col = new PrinterSettings.StringCollection(new string[] { });
- PRINTER_INFO printer_info;
- uint cbNeeded = 0, printers = 0;
- IntPtr ptr, buff;
- string s;
-
- // Determine space needed
- Win32EnumPrinters((int)EnumPrinters.PRINTER_ENUM_CONNECTIONS | (int)EnumPrinters.PRINTER_ENUM_LOCAL,
- null, 2, IntPtr.Zero, 0, ref cbNeeded, ref printers);
-
- if (cbNeeded <= 0)
- return col;
-
- ptr = buff = Marshal.AllocHGlobal((int)cbNeeded);
-
- try
- {
- // Give us the printer list
- Win32EnumPrinters((int)EnumPrinters.PRINTER_ENUM_CONNECTIONS | (int)EnumPrinters.PRINTER_ENUM_LOCAL,
- null, 2, buff, (uint)cbNeeded, ref cbNeeded, ref printers);
-
- for (int i = 0; i < printers; i++)
- {
- printer_info = (PRINTER_INFO)Marshal.PtrToStructure(ptr, typeof(PRINTER_INFO));
- s = Marshal.PtrToStringUni(printer_info.pPrinterName);
- col.Add(s);
- ptr = new IntPtr(ptr.ToInt64() + Marshal.SizeOf(printer_info));
- }
- }
- finally
- {
- Marshal.FreeHGlobal(buff);
- }
- return col;
- }
- }
-
- internal override void GetPrintDialogInfo(string printer, ref string port, ref string type, ref string status, ref string comment)
- {
- IntPtr hPrn;
- PRINTER_INFO printer_info = new PRINTER_INFO();
- int needed = 0;
- IntPtr ptr;
-
- Win32OpenPrinter(printer, out hPrn, IntPtr.Zero);
-
- if (hPrn == IntPtr.Zero)
- return;
-
- Win32GetPrinter(hPrn, 2, IntPtr.Zero, 0, ref needed);
- ptr = Marshal.AllocHGlobal(needed);
-
- Win32GetPrinter(hPrn, 2, ptr, needed, ref needed);
- printer_info = (PRINTER_INFO)Marshal.PtrToStructure(ptr, typeof(PRINTER_INFO));
- Marshal.FreeHGlobal(ptr);
-
- port = Marshal.PtrToStringUni(printer_info.pPortName);
- comment = Marshal.PtrToStringUni(printer_info.pComment);
- type = Marshal.PtrToStringUni(printer_info.pDriverName);
- status = GetPrinterStatusMsg(printer_info.Status);
-
- Win32ClosePrinter(hPrn);
- }
-
- private string GetPrinterStatusMsg(uint status)
- {
- string rslt = string.Empty;
-
- if (status == 0)
- return "Ready";
-
- if ((status & (uint)PrinterStatus.PS_PAUSED) != 0)
- rslt += "Paused; ";
- if ((status & (uint)PrinterStatus.PS_ERROR) != 0)
- rslt += "Error; ";
- if ((status & (uint)PrinterStatus.PS_PENDING_DELETION) != 0)
- rslt += "Pending deletion; ";
- if ((status & (uint)PrinterStatus.PS_PAPER_JAM) != 0)
- rslt += "Paper jam; ";
- if ((status & (uint)PrinterStatus.PS_PAPER_OUT) != 0)
- rslt += "Paper out; ";
- if ((status & (uint)PrinterStatus.PS_MANUAL_FEED) != 0)
- rslt += "Manual feed; ";
- if ((status & (uint)PrinterStatus.PS_PAPER_PROBLEM) != 0)
- rslt += "Paper problem; ";
- if ((status & (uint)PrinterStatus.PS_OFFLINE) != 0)
- rslt += "Offline; ";
- if ((status & (uint)PrinterStatus.PS_IO_ACTIVE) != 0)
- rslt += "I/O active; ";
- if ((status & (uint)PrinterStatus.PS_BUSY) != 0)
- rslt += "Busy; ";
- if ((status & (uint)PrinterStatus.PS_PRINTING) != 0)
- rslt += "Printing; ";
- if ((status & (uint)PrinterStatus.PS_OUTPUT_BIN_FULL) != 0)
- rslt += "Output bin full; ";
- if ((status & (uint)PrinterStatus.PS_NOT_AVAILABLE) != 0)
- rslt += "Not available; ";
- if ((status & (uint)PrinterStatus.PS_WAITING) != 0)
- rslt += "Waiting; ";
- if ((status & (uint)PrinterStatus.PS_PROCESSING) != 0)
- rslt += "Processing; ";
- if ((status & (uint)PrinterStatus.PS_INITIALIZING) != 0)
- rslt += "Initializing; ";
- if ((status & (uint)PrinterStatus.PS_WARMING_UP) != 0)
- rslt += "Warming up; ";
- if ((status & (uint)PrinterStatus.PS_TONER_LOW) != 0)
- rslt += "Toner low; ";
- if ((status & (uint)PrinterStatus.PS_NO_TONER) != 0)
- rslt += "No toner; ";
- if ((status & (uint)PrinterStatus.PS_PAGE_PUNT) != 0)
- rslt += "Page punt; ";
- if ((status & (uint)PrinterStatus.PS_USER_INTERVENTION) != 0)
- rslt += "User intervention; ";
- if ((status & (uint)PrinterStatus.PS_OUT_OF_MEMORY) != 0)
- rslt += "Out of memory; ";
- if ((status & (uint)PrinterStatus.PS_DOOR_OPEN) != 0)
- rslt += "Door open; ";
- if ((status & (uint)PrinterStatus.PS_SERVER_UNKNOWN) != 0)
- rslt += "Server unkown; ";
- if ((status & (uint)PrinterStatus.PS_POWER_SAVE) != 0)
- rslt += "Power save; ";
-
- return rslt;
- }
-
- //
- // DllImports
- //
-
- [DllImport("winspool.drv", CharSet = CharSet.Unicode, EntryPoint = "OpenPrinter", SetLastError = true)]
- static extern int Win32OpenPrinter(string pPrinterName, out IntPtr phPrinter, IntPtr pDefault);
-
- [DllImport("winspool.drv", CharSet = CharSet.Unicode, EntryPoint = "GetPrinter", SetLastError = true)]
- static extern int Win32GetPrinter(IntPtr hPrinter, int level, IntPtr dwBuf, int size, ref int dwNeeded);
-
- [DllImport("winspool.drv", CharSet = CharSet.Unicode, EntryPoint = "ClosePrinter", SetLastError = true)]
- static extern int Win32ClosePrinter(IntPtr hPrinter);
-
- [DllImport("winspool.drv", CharSet = CharSet.Unicode, EntryPoint = "DeviceCapabilities", SetLastError = true)]
- static extern int Win32DeviceCapabilities(string device, string port, DCCapabilities cap, IntPtr outputBuffer, IntPtr deviceMode);
-
- [DllImport("winspool.drv", CharSet = CharSet.Unicode, EntryPoint = "EnumPrinters", SetLastError = true)]
- static extern int Win32EnumPrinters(int Flags, string Name, uint Level, IntPtr pPrinterEnum, uint cbBuf,
- ref uint pcbNeeded, ref uint pcReturned);
-
- [DllImport("winspool.drv", EntryPoint = "GetDefaultPrinter", CharSet = CharSet.Unicode, SetLastError = true)]
- private static extern int Win32GetDefaultPrinter(StringBuilder buffer, ref int bufferSize);
-
- [DllImport("winspool.drv", EntryPoint = "DocumentProperties", CharSet = CharSet.Unicode, SetLastError = true)]
- private static extern int Win32DocumentProperties(IntPtr hwnd, IntPtr hPrinter, string pDeviceName,
- IntPtr pDevModeOutput, IntPtr pDevModeInput, int fMode);
-
- [DllImport("gdi32.dll", EntryPoint = "CreateDC")]
- static extern IntPtr Win32CreateDC(string lpszDriver, string lpszDevice,
- string lpszOutput, IntPtr lpInitData);
-
- [DllImport("gdi32.dll", EntryPoint = "CreateIC")]
- static extern IntPtr Win32CreateIC(string lpszDriver, string lpszDevice,
- string lpszOutput, IntPtr lpInitData);
-
- [DllImport("gdi32.dll", CharSet = CharSet.Unicode, EntryPoint = "StartDoc")]
- static extern int Win32StartDoc(IntPtr hdc, [In] ref DOCINFO lpdi);
-
- [DllImport("gdi32.dll", EntryPoint = "StartPage")]
- static extern int Win32StartPage(IntPtr hDC);
-
- [DllImport("gdi32.dll", EntryPoint = "EndPage")]
- static extern int Win32EndPage(IntPtr hdc);
-
- [DllImport("gdi32.dll", EntryPoint = "EndDoc")]
- static extern int Win32EndDoc(IntPtr hdc);
-
- [DllImport("gdi32.dll", EntryPoint = "DeleteDC")]
- public static extern IntPtr Win32DeleteDC(IntPtr hDc);
-
- [DllImport("gdi32.dll", EntryPoint = "GetDeviceCaps")]
- public static extern int Win32GetDeviceCaps(IntPtr hDc, int index);
-
- //
- // Structs
- //
- [StructLayout(LayoutKind.Sequential)]
- internal struct PRINTER_INFO
- {
- public IntPtr pServerName;
- public IntPtr pPrinterName;
- public IntPtr pShareName;
- public IntPtr pPortName;
- public IntPtr pDriverName;
- public IntPtr pComment;
- public IntPtr pLocation;
- public IntPtr pDevMode;
- public IntPtr pSepFile;
- public IntPtr pPrintProcessor;
- public IntPtr pDatatype;
- public IntPtr pParameters;
- public IntPtr pSecurityDescriptor;
- public uint Attributes;
- public uint Priority;
- public uint DefaultPriority;
- public uint StartTime;
- public uint UntilTime;
- public uint Status;
- public uint cJobs;
- public uint AveragePPM;
- }
-
- [StructLayout(LayoutKind.Sequential)]
- internal struct DOCINFO
- {
- public int cbSize;
- public IntPtr lpszDocName;
- public IntPtr lpszOutput;
- public IntPtr lpszDatatype;
- public int fwType;
- }
-
- [StructLayout(LayoutKind.Sequential, CharSet = CharSet.Unicode)]
- internal struct DEVMODE
- {
- [MarshalAs(UnmanagedType.ByValTStr, SizeConst = 32)]
- public string dmDeviceName;
- public short dmSpecVersion;
- public short dmDriverVersion;
- public short dmSize;
- public short dmDriverExtra;
- public int dmFields;
-
- public short dmOrientation;
- public short dmPaperSize;
- public short dmPaperLength;
- public short dmPaperWidth;
-
- public short dmScale;
- public short dmCopies;
- public short dmDefaultSource;
- public short dmPrintQuality;
- public short dmColor;
- public short dmDuplex;
- public short dmYResolution;
- public short dmTTOption;
- public short dmCollate;
- [MarshalAs(UnmanagedType.ByValTStr, SizeConst = 32)]
- public string dmFormName;
- public short dmLogPixels;
- public short dmBitsPerPel;
- public int dmPelsWidth;
- public int dmPelsHeight;
- public int dmDisplayFlags;
- public int dmDisplayFrequency;
- public int dmICMMethod;
- public int dmICMIntent;
- public int dmMediaType;
- public int dmDitherType;
- public int dmReserved1;
- public int dmReserved2;
- public int dmPanningWidth;
- public int dmPanningHeight;
- }
-
- // Enums
- internal enum DCCapabilities : short
- {
- 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,
- DC_BINADJUST = 19,
- DC_EMF_COMPLIANT = 20,
- DC_DATATYPE_PRODUCED = 21,
- DC_COLLATE = 22,
- DC_MANUFACTURER = 23,
- DC_MODEL = 24,
- DC_PERSONALITY = 25,
- DC_PRINTRATE = 26,
- DC_PRINTRATEUNIT = 27,
- DC_PRINTERMEM = 28,
- DC_MEDIAREADY = 29,
- DC_STAPLE = 30,
- DC_PRINTRATEPPM = 31,
- DC_COLORDEVICE = 32,
- DC_NUP = 33
- }
-
- [Flags]
- internal enum PrinterStatus : uint
- {
- PS_PAUSED = 0x00000001,
- PS_ERROR = 0x00000002,
- PS_PENDING_DELETION = 0x00000004,
- PS_PAPER_JAM = 0x00000008,
- PS_PAPER_OUT = 0x00000010,
- PS_MANUAL_FEED = 0x00000020,
- PS_PAPER_PROBLEM = 0x00000040,
- PS_OFFLINE = 0x00000080,
- PS_IO_ACTIVE = 0x00000100,
- PS_BUSY = 0x00000200,
- PS_PRINTING = 0x00000400,
- PS_OUTPUT_BIN_FULL = 0x00000800,
- PS_NOT_AVAILABLE = 0x00001000,
- PS_WAITING = 0x00002000,
- PS_PROCESSING = 0x00004000,
- PS_INITIALIZING = 0x00008000,
- PS_WARMING_UP = 0x00010000,
- PS_TONER_LOW = 0x00020000,
- PS_NO_TONER = 0x00040000,
- PS_PAGE_PUNT = 0x00080000,
- PS_USER_INTERVENTION = 0x00100000,
- PS_OUT_OF_MEMORY = 0x00200000,
- PS_DOOR_OPEN = 0x00400000,
- PS_SERVER_UNKNOWN = 0x00800000,
- PS_POWER_SAVE = 0x01000000
- }
-
- // for use in GetDeviceCaps
- internal enum DevCapabilities
- {
- TECHNOLOGY = 2,
- }
-
- internal enum PrinterType
- {
- DT_PLOTTER = 0, // Vector Plotter
- DT_RASDIPLAY = 1, // Raster Display
- DT_RASPRINTER = 2, // Raster printer
- DT_RASCAMERA = 3, // Raster camera
- DT_CHARSTREAM = 4, // Character-stream, PLP
- DT_METAFILE = 5, // Metafile, VDM
- DT_DISPFILE = 6, // Display-file
- }
-
- [Flags]
- internal enum EnumPrinters : uint
- {
- PRINTER_ENUM_DEFAULT = 0x1,
- PRINTER_ENUM_LOCAL = 0x2,
- PRINTER_ENUM_CONNECTIONS = 0x4,
- PRINTER_ENUM_FAVORITE = 0x4,
- PRINTER_ENUM_NAME = 0x8,
- PRINTER_ENUM_REMOTE = 0x10,
- PRINTER_ENUM_SHARED = 0x20,
- PRINTER_ENUM_NETWORK = 0x40,
- }
- }
-
- class GlobalPrintingServicesWin32 : GlobalPrintingServices
- {
- internal override PrinterSettings.StringCollection InstalledPrinters
- {
- get
- {
- return PrintingServicesWin32.InstalledPrinters;
- }
- }
-
- internal override IntPtr CreateGraphicsContext(PrinterSettings settings, PageSettings default_page_settings)
- {
- return PrintingServicesWin32.CreateGraphicsContext(settings, default_page_settings);
- }
-
- internal override bool StartDoc(GraphicsPrinter gr, string doc_name, string output_file)
- {
- return PrintingServicesWin32.StartDoc(gr, doc_name, output_file);
- }
-
- internal override bool EndDoc(GraphicsPrinter gr)
- {
- return PrintingServicesWin32.EndDoc(gr);
- }
-
- internal override bool StartPage(GraphicsPrinter gr)
- {
- return PrintingServicesWin32.StartPage(gr);
- }
-
- internal override bool EndPage(GraphicsPrinter gr)
- {
- return PrintingServicesWin32.EndPage(gr);
- }
- }
-}
-
-
-
diff --git a/src/System.Drawing.Common/src/Unix/System.Drawing/ColorTranslator.cs b/src/System.Drawing.Common/src/Unix/System.Drawing/ColorTranslator.cs
deleted file mode 100644
index f3a184ba63..0000000000
--- a/src/System.Drawing.Common/src/Unix/System.Drawing/ColorTranslator.cs
+++ /dev/null
@@ -1,207 +0,0 @@
-// Licensed to the .NET Foundation under one or more agreements.
-// See the LICENSE file in the project root for more information.
-//
-// System.Drawing.ColorTranslator.cs
-//
-// Authors:
-// Dennis Hayes (dennish@raytek.com)
-// Ravindra (rkumar@novell.com)
-// Sebastien Pouliot <sebastien@ximian.com>
-//
-// Copyright (C) 2001 Ximian, Inc. http://www.ximian.com
-// Copyright (C) 2004,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.ComponentModel;
-using System.Globalization;
-
-namespace System.Drawing
-{
-
- public sealed class ColorTranslator
- {
-
- private ColorTranslator()
- {
- }
-
- public static Color FromHtml(string htmlColor)
- {
- if (string.IsNullOrEmpty(htmlColor))
- return Color.Empty;
-
- switch (htmlColor.ToLowerInvariant())
- {
- case "buttonface":
- case "threedface":
- return SystemColors.Control;
- case "buttonhighlight":
- case "threedlightshadow":
- return SystemColors.ControlLightLight;
- case "buttonshadow":
- return SystemColors.ControlDark;
- case "captiontext":
- return SystemColors.ActiveCaptionText;
- case "threeddarkshadow":
- return SystemColors.ControlDarkDark;
- case "threedhighlight":
- return SystemColors.ControlLight;
- case "background":
- return SystemColors.Desktop;
- case "buttontext":
- return SystemColors.ControlText;
- case "infobackground":
- return SystemColors.Info;
- // special case for Color.LightGray versus html's LightGrey (#340917)
- case "lightgrey":
- return Color.LightGray;
- }
-
- if (htmlColor[0] == '#' && htmlColor.Length == 4)
- {
- char r = htmlColor[1], g = htmlColor[2], b = htmlColor[3];
- htmlColor = new string(new char[] { '#', r, r, g, g, b, b });
- }
-#if NETCORE
- return ColorConverterCommon.ConvertFromString(htmlColor, CultureInfo.CurrentCulture);
-#else
- TypeConverter converter = TypeDescriptor.GetConverter (typeof (Color));
- return (Color) converter.ConvertFromString (htmlColor);
-#endif
- }
-
- internal static Color FromBGR(int bgr)
- {
- Color result = Color.FromArgb(0xFF, (bgr & 0xFF), ((bgr >> 8) & 0xFF), ((bgr >> 16) & 0xFF));
- Color known = KnownColors.FindColorMatch(result);
- return (known.IsEmpty) ? result : known;
- }
-
- public static Color FromOle(int oleColor)
- {
- // OleColor format is BGR
- return FromBGR(oleColor);
- }
-
- public static Color FromWin32(int win32Color)
- {
- // Win32Color format is BGR
- return FromBGR(win32Color);
- }
-
- public static string ToHtml(Color c)
- {
- if (c.IsEmpty)
- return String.Empty;
-
- if (ColorUtil.IsSystemColor(c))
- {
- KnownColor kc = c.ToKnownColor();
- switch (kc)
- {
- case KnownColor.ActiveBorder:
- case KnownColor.ActiveCaption:
- case KnownColor.AppWorkspace:
- case KnownColor.GrayText:
- case KnownColor.Highlight:
- case KnownColor.HighlightText:
- case KnownColor.InactiveBorder:
- case KnownColor.InactiveCaption:
- case KnownColor.InactiveCaptionText:
- case KnownColor.InfoText:
- case KnownColor.Menu:
- case KnownColor.MenuText:
- case KnownColor.ScrollBar:
- case KnownColor.Window:
- case KnownColor.WindowFrame:
- case KnownColor.WindowText:
- return KnownColors.GetName(kc).ToLowerInvariant();
-
- case KnownColor.ActiveCaptionText:
- return "captiontext";
- case KnownColor.Control:
- return "buttonface";
- case KnownColor.ControlDark:
- return "buttonshadow";
- case KnownColor.ControlDarkDark:
- return "threeddarkshadow";
- case KnownColor.ControlLight:
- return "buttonface";
- case KnownColor.ControlLightLight:
- return "buttonhighlight";
- case KnownColor.ControlText:
- return "buttontext";
- case KnownColor.Desktop:
- return "background";
- case KnownColor.HotTrack:
- return "highlight";
- case KnownColor.Info:
- return "infobackground";
-
- default:
- return String.Empty;
- }
- }
-
- if (c.IsNamedColor)
- {
- if (c == Color.LightGray)
- return "LightGrey";
- else
- return c.Name;
- }
-
- return FormatHtml(c.R, c.G, c.B);
- }
-
- static char GetHexNumber(int b)
- {
- return (char)(b > 9 ? 55 + b : 48 + b);
- }
-
- static string FormatHtml(int r, int g, int b)
- {
- char[] htmlColor = new char[7];
- htmlColor[0] = '#';
- htmlColor[1] = GetHexNumber((r >> 4) & 15);
- htmlColor[2] = GetHexNumber(r & 15);
- htmlColor[3] = GetHexNumber((g >> 4) & 15);
- htmlColor[4] = GetHexNumber(g & 15);
- htmlColor[5] = GetHexNumber((b >> 4) & 15);
- htmlColor[6] = GetHexNumber(b & 15);
-
- return new string(htmlColor);
- }
-
- public static int ToOle(Color c)
- {
- // OleColor format is BGR, same as Win32
- return ((c.B << 16) | (c.G << 8) | c.R);
- }
-
- public static int ToWin32(Color c)
- {
- // Win32Color format is BGR, Same as OleColor
- return ((c.B << 16) | (c.G << 8) | c.R);
- }
- }
-}
diff --git a/src/System.Drawing.Common/src/Unix/System.Drawing/ComIStreamMarshaler.cs b/src/System.Drawing.Common/src/Unix/System.Drawing/ComIStreamMarshaler.cs
deleted file mode 100644
index 24c690a1bb..0000000000
--- a/src/System.Drawing.Common/src/Unix/System.Drawing/ComIStreamMarshaler.cs
+++ /dev/null
@@ -1,718 +0,0 @@
-// Licensed to the .NET Foundation under one or more agreements.
-// See the LICENSE file in the project root for more information.
-//
-// System.Drawing.ComIStreamMarshaler.cs
-//
-// Author:
-// Kornél Pál <http://www.kornelpal.hu/>
-//
-// Copyright (C) 2005-2006 Kornél Pál
-//
-
-//
-// 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.
-//
-
-// Undefine to debug the protected blocks
-#define MAP_EX_TO_HR
-
-// Define to debug wrappers recursively
-// #define RECURSIVE_WRAPPING
-
-using System;
-using System.IO;
-using System.Reflection;
-using System.Runtime.InteropServices;
-using System.Runtime.InteropServices.ComTypes;
-using STATSTG = System.Runtime.InteropServices.ComTypes.STATSTG;
-
-namespace System.Drawing
-{
- // Mono does not implement COM interface marshaling
- // This custom marshaler should be replaced with UnmanagedType.Interface
- // Provides identical behaviour under Mono and .NET Framework
- internal sealed class ComIStreamMarshaler : ICustomMarshaler
- {
- private const int S_OK = 0x00000000;
- private const int E_NOINTERFACE = unchecked((int)0x80004002);
-
- private delegate int QueryInterfaceDelegate(IntPtr @this, [In()] ref Guid riid, IntPtr ppvObject);
- private delegate int AddRefDelegate(IntPtr @this);
- private delegate int ReleaseDelegate(IntPtr @this);
- private delegate int ReadDelegate(IntPtr @this, [Out(), MarshalAs(UnmanagedType.LPArray, SizeParamIndex = 2)] byte[] pv, int cb, IntPtr pcbRead);
- private delegate int WriteDelegate(IntPtr @this, [MarshalAs(UnmanagedType.LPArray, SizeParamIndex = 2)] byte[] pv, int cb, IntPtr pcbWritten);
- private delegate int SeekDelegate(IntPtr @this, long dlibMove, int dwOrigin, IntPtr plibNewPosition);
- private delegate int SetSizeDelegate(IntPtr @this, long libNewSize);
- private delegate int CopyToDelegate(IntPtr @this, [MarshalAs(UnmanagedType.CustomMarshaler, MarshalTypeRef = typeof(ComIStreamMarshaler))] IStream pstm, long cb, IntPtr pcbRead, IntPtr pcbWritten);
- private delegate int CommitDelegate(IntPtr @this, int grfCommitFlags);
- private delegate int RevertDelegate(IntPtr @this);
- private delegate int LockRegionDelegate(IntPtr @this, long libOffset, long cb, int dwLockType);
- private delegate int UnlockRegionDelegate(IntPtr @this, long libOffset, long cb, int dwLockType);
- private delegate int StatDelegate(IntPtr @this, out STATSTG pstatstg, int grfStatFlag);
- private delegate int CloneDelegate(IntPtr @this, out IntPtr ppstm);
-
- [StructLayout(LayoutKind.Sequential)]
- private sealed class IStreamInterface
- {
- internal IntPtr lpVtbl;
- internal IntPtr gcHandle;
- }
-
- [StructLayout(LayoutKind.Sequential)]
- private sealed class IStreamVtbl
- {
- internal QueryInterfaceDelegate QueryInterface;
- internal AddRefDelegate AddRef;
- internal ReleaseDelegate Release;
- internal ReadDelegate Read;
- internal WriteDelegate Write;
- internal SeekDelegate Seek;
- internal SetSizeDelegate SetSize;
- internal CopyToDelegate CopyTo;
- internal CommitDelegate Commit;
- internal RevertDelegate Revert;
- internal LockRegionDelegate LockRegion;
- internal UnlockRegionDelegate UnlockRegion;
- internal StatDelegate Stat;
- internal CloneDelegate Clone;
- }
-
- // Managed COM Callable Wrapper implementation
- // Reference counting is thread safe
- private sealed class ManagedToNativeWrapper
- {
- // Mono does not implement Marshal.Release
- [StructLayout(LayoutKind.Sequential)]
- private sealed class ReleaseSlot
- {
- internal ReleaseDelegate Release;
- }
-
- private static readonly Guid IID_IUnknown = new Guid("00000000-0000-0000-C000-000000000046");
- private static readonly Guid IID_IStream = new Guid("0000000C-0000-0000-C000-000000000046");
- private static readonly MethodInfo exceptionGetHResult = typeof(Exception).GetTypeInfo().GetProperty("HResult", BindingFlags.GetProperty | BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.Instance | BindingFlags.DeclaredOnly | BindingFlags.ExactBinding, null, typeof(int), new Type[] { }, null).GetGetMethod(true);
- // Keeps delegates alive while they are marshaled
- private static readonly IStreamVtbl managedVtable;
- private static IntPtr comVtable;
- private static int vtableRefCount;
-
- private IStream managedInterface;
- private IntPtr comInterface;
- // Keeps the object alive when it has no managed references
- private GCHandle gcHandle;
- private int refCount = 1;
-
- static ManagedToNativeWrapper()
- {
- EventHandler onShutdown;
- AppDomain currentDomain;
- IStreamVtbl newVtable;
-
- onShutdown = new EventHandler(OnShutdown);
- currentDomain = AppDomain.CurrentDomain;
- currentDomain.DomainUnload += onShutdown;
- currentDomain.ProcessExit += onShutdown;
-
- newVtable = new IStreamVtbl();
- newVtable.QueryInterface = new QueryInterfaceDelegate(QueryInterface);
- newVtable.AddRef = new AddRefDelegate(AddRef);
- newVtable.Release = new ReleaseDelegate(Release);
- newVtable.Read = new ReadDelegate(Read);
- newVtable.Write = new WriteDelegate(Write);
- newVtable.Seek = new SeekDelegate(Seek);
- newVtable.SetSize = new SetSizeDelegate(SetSize);
- newVtable.CopyTo = new CopyToDelegate(CopyTo);
- newVtable.Commit = new CommitDelegate(Commit);
- newVtable.Revert = new RevertDelegate(Revert);
- newVtable.LockRegion = new LockRegionDelegate(LockRegion);
- newVtable.UnlockRegion = new UnlockRegionDelegate(UnlockRegion);
- newVtable.Stat = new StatDelegate(Stat);
- newVtable.Clone = new CloneDelegate(Clone);
- managedVtable = newVtable;
-
- CreateVtable();
- }
-
- private ManagedToNativeWrapper(IStream managedInterface)
- {
- IStreamInterface newInterface;
-
- lock (managedVtable)
- {
- // Vtable may have been disposed when shutting down
- if (vtableRefCount == 0 && comVtable == IntPtr.Zero)
- CreateVtable();
- vtableRefCount++;
- }
-
- try
- {
- this.managedInterface = managedInterface;
- gcHandle = GCHandle.Alloc(this);
-
- newInterface = new IStreamInterface();
- newInterface.lpVtbl = comVtable;
- newInterface.gcHandle = (IntPtr)gcHandle;
- comInterface = Marshal.AllocHGlobal(Marshal.SizeOf(typeof(IStreamInterface)));
- Marshal.StructureToPtr(newInterface, comInterface, false);
- }
- catch
- {
- this.Dispose();
- throw;
- }
- }
-
- private void Dispose()
- {
- if (gcHandle.IsAllocated)
- gcHandle.Free();
-
- if (comInterface != IntPtr.Zero)
- {
- Marshal.FreeHGlobal(comInterface);
- comInterface = IntPtr.Zero;
- }
-
- managedInterface = null;
-
- lock (managedVtable)
- {
- // Dispose vtable when shutting down
- if (--vtableRefCount == 0 && Environment.HasShutdownStarted)
- DisposeVtable();
- }
- }
-
- private static void OnShutdown(object sender, EventArgs e)
- {
- lock (managedVtable)
- {
- // There may be object instances when shutting down
- if (vtableRefCount == 0 && comVtable != IntPtr.Zero)
- DisposeVtable();
- }
- }
-
- private static void CreateVtable()
- {
- comVtable = Marshal.AllocHGlobal(Marshal.SizeOf(typeof(IStreamVtbl)));
- Marshal.StructureToPtr(managedVtable, comVtable, false);
- }
-
- private static void DisposeVtable()
- {
- Marshal.DestroyStructure(comVtable, typeof(IStreamVtbl));
- Marshal.FreeHGlobal(comVtable);
- comVtable = IntPtr.Zero;
- }
-
- internal static IStream GetUnderlyingInterface(IntPtr comInterface, bool outParam)
- {
- if (Marshal.ReadIntPtr(comInterface) == comVtable)
- {
- IStream managedInterface = GetObject(comInterface).managedInterface;
-
- if (outParam)
- Release(comInterface);
-
- return managedInterface;
- }
- else
- return null;
- }
-
- internal static IntPtr GetInterface(IStream managedInterface)
- {
- IntPtr comInterface;
-
- if (managedInterface == null)
- return IntPtr.Zero;
-#if !RECURSIVE_WRAPPING
- else if ((comInterface = NativeToManagedWrapper.GetUnderlyingInterface(managedInterface)) == IntPtr.Zero)
-#endif
- comInterface = new ManagedToNativeWrapper(managedInterface).comInterface;
-
- return comInterface;
- }
-
- internal static void ReleaseInterface(IntPtr comInterface)
- {
- if (comInterface != IntPtr.Zero)
- {
- IntPtr vtable = Marshal.ReadIntPtr(comInterface);
-
- if (vtable == comVtable)
- Release(comInterface);
- else
- {
- ReleaseSlot releaseSlot = (ReleaseSlot)Marshal.PtrToStructure((IntPtr)((long)vtable + (long)(IntPtr.Size * 2)), typeof(ReleaseSlot));
- releaseSlot.Release(comInterface);
- }
- }
- }
-
- // Mono does not implement Marshal.GetHRForException
- private static int GetHRForException(Exception e)
- {
- return (int)exceptionGetHResult.Invoke(e, null);
- }
-
- private static ManagedToNativeWrapper GetObject(IntPtr @this)
- {
- return (ManagedToNativeWrapper)((GCHandle)Marshal.ReadIntPtr(@this, IntPtr.Size)).Target;
- }
-
- private static int QueryInterface(IntPtr @this, ref Guid riid, IntPtr ppvObject)
- {
-#if MAP_EX_TO_HR
- try
- {
-#endif
- if (IID_IUnknown.Equals(riid) || IID_IStream.Equals(riid))
- {
- Marshal.WriteIntPtr(ppvObject, @this);
- AddRef(@this);
- return S_OK;
- }
- else
- {
- Marshal.WriteIntPtr(ppvObject, IntPtr.Zero);
- return E_NOINTERFACE;
- }
-#if MAP_EX_TO_HR
- }
- catch (Exception e)
- {
- return GetHRForException(e);
- }
-#endif
- }
-
- private static int AddRef(IntPtr @this)
- {
-#if MAP_EX_TO_HR
- try
- {
-#endif
- ManagedToNativeWrapper thisObject = GetObject(@this);
-
- lock (thisObject)
- {
- return ++thisObject.refCount;
- }
-#if MAP_EX_TO_HR
- }
- catch
- {
- return 0;
- }
-#endif
- }
-
- private static int Release(IntPtr @this)
- {
-#if MAP_EX_TO_HR
- try
- {
-#endif
- ManagedToNativeWrapper thisObject = GetObject(@this);
-
- lock (thisObject)
- {
- if ((thisObject.refCount != 0) && (--thisObject.refCount == 0))
- thisObject.Dispose();
-
- return thisObject.refCount;
- }
-#if MAP_EX_TO_HR
- }
- catch
- {
- return 0;
- }
-#endif
- }
-
- private static int Read(IntPtr @this, byte[] pv, int cb, IntPtr pcbRead)
- {
-#if MAP_EX_TO_HR
- try
- {
-#endif
- GetObject(@this).managedInterface.Read(pv, cb, pcbRead);
- return S_OK;
-#if MAP_EX_TO_HR
- }
- catch (Exception e)
- {
- return GetHRForException(e);
- }
-#endif
- }
-
- private static int Write(IntPtr @this, byte[] pv, int cb, IntPtr pcbWritten)
- {
-#if MAP_EX_TO_HR
- try
- {
-#endif
- GetObject(@this).managedInterface.Write(pv, cb, pcbWritten);
- return S_OK;
-#if MAP_EX_TO_HR
- }
- catch (Exception e)
- {
- return GetHRForException(e);
- }
-#endif
- }
-
- private static int Seek(IntPtr @this, long dlibMove, int dwOrigin, IntPtr plibNewPosition)
- {
-#if MAP_EX_TO_HR
- try
- {
-#endif
- GetObject(@this).managedInterface.Seek(dlibMove, dwOrigin, plibNewPosition);
- return S_OK;
-#if MAP_EX_TO_HR
- }
- catch (Exception e)
- {
- return GetHRForException(e);
- }
-#endif
- }
-
- private static int SetSize(IntPtr @this, long libNewSize)
- {
-#if MAP_EX_TO_HR
- try
- {
-#endif
- GetObject(@this).managedInterface.SetSize(libNewSize);
- return S_OK;
-#if MAP_EX_TO_HR
- }
- catch (Exception e)
- {
- return GetHRForException(e);
- }
-#endif
- }
-
- private static int CopyTo(IntPtr @this, IStream pstm, long cb, IntPtr pcbRead, IntPtr pcbWritten)
- {
-#if MAP_EX_TO_HR
- try
- {
-#endif
- GetObject(@this).managedInterface.CopyTo(pstm, cb, pcbRead, pcbWritten);
- return S_OK;
-#if MAP_EX_TO_HR
- }
- catch (Exception e)
- {
- return GetHRForException(e);
- }
-#endif
- }
-
- private static int Commit(IntPtr @this, int grfCommitFlags)
- {
-#if MAP_EX_TO_HR
- try
- {
-#endif
- GetObject(@this).managedInterface.Commit(grfCommitFlags);
- return S_OK;
-#if MAP_EX_TO_HR
- }
- catch (Exception e)
- {
- return GetHRForException(e);
- }
-#endif
- }
-
- private static int Revert(IntPtr @this)
- {
-#if MAP_EX_TO_HR
- try
- {
-#endif
- GetObject(@this).managedInterface.Revert();
- return S_OK;
-#if MAP_EX_TO_HR
- }
- catch (Exception e)
- {
- return GetHRForException(e);
- }
-#endif
- }
-
- private static int LockRegion(IntPtr @this, long libOffset, long cb, int dwLockType)
- {
-#if MAP_EX_TO_HR
- try
- {
-#endif
- GetObject(@this).managedInterface.LockRegion(libOffset, cb, dwLockType);
- return S_OK;
-#if MAP_EX_TO_HR
- }
- catch (Exception e)
- {
- return GetHRForException(e);
- }
-#endif
- }
-
- private static int UnlockRegion(IntPtr @this, long libOffset, long cb, int dwLockType)
- {
-#if MAP_EX_TO_HR
- try
- {
-#endif
- GetObject(@this).managedInterface.UnlockRegion(libOffset, cb, dwLockType);
- return S_OK;
-#if MAP_EX_TO_HR
- }
- catch (Exception e)
- {
- return GetHRForException(e);
- }
-#endif
- }
-
- private static int Stat(IntPtr @this, out STATSTG pstatstg, int grfStatFlag)
- {
-#if MAP_EX_TO_HR
- try
- {
-#endif
- GetObject(@this).managedInterface.Stat(out pstatstg, grfStatFlag);
- return S_OK;
-#if MAP_EX_TO_HR
- }
- catch (Exception e)
- {
- pstatstg = new STATSTG();
- return GetHRForException(e);
- }
-#endif
- }
-
- private static int Clone(IntPtr @this, out IntPtr ppstm)
- {
- ppstm = IntPtr.Zero;
-#if MAP_EX_TO_HR
- try
- {
-#endif
- IStream newInterface;
-
- GetObject(@this).managedInterface.Clone(out newInterface);
- ppstm = ManagedToNativeWrapper.GetInterface(newInterface);
- return S_OK;
-#if MAP_EX_TO_HR
- }
- catch (Exception e)
- {
- return GetHRForException(e);
- }
-#endif
- }
- }
-
- // Managed Runtime Callable Wrapper implementation
- private sealed class NativeToManagedWrapper : IStream
- {
- private IntPtr comInterface;
- private IStreamVtbl managedVtable;
-
- private NativeToManagedWrapper(IntPtr comInterface, bool outParam)
- {
- this.comInterface = comInterface;
- managedVtable = (IStreamVtbl)Marshal.PtrToStructure(Marshal.ReadIntPtr(comInterface), typeof(IStreamVtbl));
- if (!outParam)
- managedVtable.AddRef(comInterface);
- }
-
- ~NativeToManagedWrapper()
- {
- Dispose(false);
- }
-
- private void Dispose(bool disposing)
- {
- managedVtable.Release(comInterface);
- if (disposing)
- {
- comInterface = IntPtr.Zero;
- managedVtable = null;
- GC.SuppressFinalize(this);
- }
- }
-
- internal static IntPtr GetUnderlyingInterface(IStream managedInterface)
- {
- if (managedInterface is NativeToManagedWrapper)
- {
- NativeToManagedWrapper wrapper = (NativeToManagedWrapper)managedInterface;
-
- wrapper.managedVtable.AddRef(wrapper.comInterface);
- return wrapper.comInterface;
- }
- else
- return IntPtr.Zero;
- }
-
- internal static IStream GetInterface(IntPtr comInterface, bool outParam)
- {
- IStream managedInterface;
-
- if (comInterface == IntPtr.Zero)
- return null;
-#if !RECURSIVE_WRAPPING
- else if ((managedInterface = ManagedToNativeWrapper.GetUnderlyingInterface(comInterface, outParam)) == null)
-#endif
- managedInterface = (IStream)new NativeToManagedWrapper(comInterface, outParam);
-
- return managedInterface;
- }
-
- internal static void ReleaseInterface(IStream managedInterface)
- {
- if (managedInterface is NativeToManagedWrapper)
- ((NativeToManagedWrapper)managedInterface).Dispose(true);
- }
-
- // Mono does not implement Marshal.ThrowExceptionForHR
- private static void ThrowExceptionForHR(int result)
- {
- if (result < 0)
- throw new COMException(null, result);
- }
-
- public void Read(byte[] pv, int cb, IntPtr pcbRead)
- {
- ThrowExceptionForHR(managedVtable.Read(comInterface, pv, cb, pcbRead));
- }
-
- public void Write(byte[] pv, int cb, IntPtr pcbWritten)
- {
- ThrowExceptionForHR(managedVtable.Write(comInterface, pv, cb, pcbWritten));
- }
-
- public void Seek(long dlibMove, int dwOrigin, IntPtr plibNewPosition)
- {
- ThrowExceptionForHR(managedVtable.Seek(comInterface, dlibMove, dwOrigin, plibNewPosition));
- }
-
- public void SetSize(long libNewSize)
- {
- ThrowExceptionForHR(managedVtable.SetSize(comInterface, libNewSize));
- }
-
- public void CopyTo(IStream pstm, long cb, IntPtr pcbRead, IntPtr pcbWritten)
- {
- ThrowExceptionForHR(managedVtable.CopyTo(comInterface, pstm, cb, pcbRead, pcbWritten));
- }
-
- public void Commit(int grfCommitFlags)
- {
- ThrowExceptionForHR(managedVtable.Commit(comInterface, grfCommitFlags));
- }
-
- public void Revert()
- {
- ThrowExceptionForHR(managedVtable.Revert(comInterface));
- }
-
- public void LockRegion(long libOffset, long cb, int dwLockType)
- {
- ThrowExceptionForHR(managedVtable.LockRegion(comInterface, libOffset, cb, dwLockType));
- }
-
- public void UnlockRegion(long libOffset, long cb, int dwLockType)
- {
- ThrowExceptionForHR(managedVtable.UnlockRegion(comInterface, libOffset, cb, dwLockType));
- }
-
- public void Stat(out STATSTG pstatstg, int grfStatFlag)
- {
- ThrowExceptionForHR(managedVtable.Stat(comInterface, out pstatstg, grfStatFlag));
- }
-
- public void Clone(out IStream ppstm)
- {
- IntPtr newInterface;
-
- ThrowExceptionForHR(managedVtable.Clone(comInterface, out newInterface));
- ppstm = NativeToManagedWrapper.GetInterface(newInterface, true);
- }
- }
-
- private static readonly ComIStreamMarshaler defaultInstance = new ComIStreamMarshaler();
-
- private ComIStreamMarshaler()
- {
- }
-
- private static ICustomMarshaler GetInstance(string cookie)
- {
- return defaultInstance;
- }
-
- public IntPtr MarshalManagedToNative(object managedObj)
- {
-#if RECURSIVE_WRAPPING
- managedObj = NativeToManagedWrapper.GetInterface(ManagedToNativeWrapper.GetInterface((IStream)managedObj), true);
-#endif
- return ManagedToNativeWrapper.GetInterface((IStream)managedObj);
- }
-
- public void CleanUpNativeData(IntPtr pNativeData)
- {
- ManagedToNativeWrapper.ReleaseInterface(pNativeData);
- }
-
- public object MarshalNativeToManaged(IntPtr pNativeData)
- {
-#if RECURSIVE_WRAPPING
- pNativeData = ManagedToNativeWrapper.GetInterface(NativeToManagedWrapper.GetInterface(pNativeData, true));
-#endif
- return NativeToManagedWrapper.GetInterface(pNativeData, false);
- }
-
- public void CleanUpManagedData(object managedObj)
- {
- NativeToManagedWrapper.ReleaseInterface((IStream)managedObj);
- }
-
- public int GetNativeDataSize()
- {
- return -1;
- }
- }
-}
diff --git a/src/System.Drawing.Common/src/Unix/System.Drawing/ComIStreamWrapper.cs b/src/System.Drawing.Common/src/Unix/System.Drawing/ComIStreamWrapper.cs
deleted file mode 100644
index 37ef6c03b8..0000000000
--- a/src/System.Drawing.Common/src/Unix/System.Drawing/ComIStreamWrapper.cs
+++ /dev/null
@@ -1,199 +0,0 @@
-// Licensed to the .NET Foundation under one or more agreements.
-// See the LICENSE file in the project root for more information.
-//
-// System.Drawing.ComIStreamWrapper.cs
-//
-// Author:
-// Kornél Pál <http://www.kornelpal.hu/>
-//
-// Copyright (C) 2005-2008 Kornél Pál
-//
-
-//
-// 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;
-using System.IO;
-using System.Reflection;
-using System.Runtime.InteropServices;
-using System.Runtime.InteropServices.ComTypes;
-using STATSTG = System.Runtime.InteropServices.ComTypes.STATSTG;
-
-namespace System.Drawing
-{
- // Stream to IStream wrapper for COM interop
- internal sealed class ComIStreamWrapper : IStream
- {
- private const int STG_E_INVALIDFUNCTION = unchecked((int)0x80030001);
-
- private readonly Stream baseStream;
- private long position = -1;
-
- internal ComIStreamWrapper(Stream stream)
- {
- baseStream = stream;
- }
-
- private void SetSizeToPosition()
- {
- if (position != -1)
- {
- if (position > baseStream.Length)
- baseStream.SetLength(position);
- baseStream.Position = position;
- position = -1;
- }
- }
-
- public void Read(byte[] pv, int cb, IntPtr pcbRead)
- {
- int read = 0;
-
- if (cb != 0)
- {
- SetSizeToPosition();
- read = baseStream.Read(pv, 0, cb);
- }
-
- if (pcbRead != IntPtr.Zero)
- Marshal.WriteInt32(pcbRead, read);
- }
-
- public void Write(byte[] pv, int cb, IntPtr pcbWritten)
- {
- if (cb != 0)
- {
- SetSizeToPosition();
- baseStream.Write(pv, 0, cb);
- }
-
- if (pcbWritten != IntPtr.Zero)
- Marshal.WriteInt32(pcbWritten, cb);
- }
-
- public void Seek(long dlibMove, int dwOrigin, IntPtr plibNewPosition)
- {
- long length = baseStream.Length;
- long newPosition;
-
- switch ((SeekOrigin)dwOrigin)
- {
- case SeekOrigin.Begin:
- newPosition = dlibMove;
- break;
- case SeekOrigin.Current:
- if (position == -1)
- newPosition = baseStream.Position + dlibMove;
- else
- newPosition = position + dlibMove;
- break;
- case SeekOrigin.End:
- newPosition = length + dlibMove;
- break;
- default:
- throw new ExternalException(null, STG_E_INVALIDFUNCTION);
- }
-
- if (newPosition > length)
- position = newPosition;
- else
- {
- baseStream.Position = newPosition;
- position = -1;
- }
-
- if (plibNewPosition != IntPtr.Zero)
- Marshal.WriteInt64(plibNewPosition, newPosition);
- }
-
- public void SetSize(long libNewSize)
- {
- baseStream.SetLength(libNewSize);
- }
-
- public void CopyTo(IStream pstm, long cb, IntPtr pcbRead, IntPtr pcbWritten)
- {
- byte[] buffer;
- long written = 0;
- int read;
- int count;
-
- if (cb != 0)
- {
- if (cb < 4096)
- count = (int)cb;
- else
- count = 4096;
- buffer = new byte[count];
- SetSizeToPosition();
- while (true)
- {
- if ((read = baseStream.Read(buffer, 0, count)) == 0)
- break;
- pstm.Write(buffer, read, IntPtr.Zero);
- written += read;
- if (written >= cb)
- break;
- if (cb - written < 4096)
- count = (int)(cb - written);
- }
- }
-
- if (pcbRead != IntPtr.Zero)
- Marshal.WriteInt64(pcbRead, written);
- if (pcbWritten != IntPtr.Zero)
- Marshal.WriteInt64(pcbWritten, written);
- }
-
- public void Commit(int grfCommitFlags)
- {
- baseStream.Flush();
- SetSizeToPosition();
- }
-
- public void Revert()
- {
- throw new ExternalException(null, STG_E_INVALIDFUNCTION);
- }
-
- public void LockRegion(long libOffset, long cb, int dwLockType)
- {
- throw new ExternalException(null, STG_E_INVALIDFUNCTION);
- }
-
- public void UnlockRegion(long libOffset, long cb, int dwLockType)
- {
- throw new ExternalException(null, STG_E_INVALIDFUNCTION);
- }
-
- public void Stat(out STATSTG pstatstg, int grfStatFlag)
- {
- pstatstg = new STATSTG();
- pstatstg.cbSize = baseStream.Length;
- }
-
- public void Clone(out IStream ppstm)
- {
- ppstm = null;
- throw new ExternalException(null, STG_E_INVALIDFUNCTION);
- }
- }
-} \ No newline at end of file
diff --git a/src/System.Drawing.Common/src/Unix/System.Drawing/ContentAlignment.cs b/src/System.Drawing.Common/src/Unix/System.Drawing/ContentAlignment.cs
deleted file mode 100644
index 42f0d83447..0000000000
--- a/src/System.Drawing.Common/src/Unix/System.Drawing/ContentAlignment.cs
+++ /dev/null
@@ -1,50 +0,0 @@
-// Licensed to the .NET Foundation under one or more agreements.
-// See the LICENSE file in the project root for more information.
-//
-// System.Drawing.ContentAlignment.cs
-//
-// Author: Dennis Hayes (dennish@raytek.com)
-//
-// (C) 2001 Ximian, Inc. http://www.ximian.com
-// Copyright (C) 2004,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.ComponentModel;
-
-namespace System.Drawing
-{
-#if !NETCORE
- [Editor ("System.Drawing.Design.ContentAlignmentEditor, " + Consts.AssemblySystem_Drawing_Design, typeof (System.Drawing.Design.UITypeEditor))]
-#endif
- public enum ContentAlignment
- {
- TopLeft = 0x001,
- TopCenter = 0x002,
- TopRight = 0x004,
- MiddleLeft = 0x010,
- MiddleCenter = 0x020,
- MiddleRight = 0x040,
- BottomLeft = 0x100,
- BottomCenter = 0x200,
- BottomRight = 0x400
- }
-}
diff --git a/src/System.Drawing.Common/src/Unix/System.Drawing/FontFamily.cs b/src/System.Drawing.Common/src/Unix/System.Drawing/FontFamily.cs
deleted file mode 100644
index d5c738c342..0000000000
--- a/src/System.Drawing.Common/src/Unix/System.Drawing/FontFamily.cs
+++ /dev/null
@@ -1,245 +0,0 @@
-// Licensed to the .NET Foundation under one or more agreements.
-// See the LICENSE file in the project root for more information.
-//
-// System.Drawing.FontFamily.cs
-//
-// Author:
-// Dennis Hayes (dennish@Raytek.com)
-// Alexandre Pigolkine (pigolkine@gmx.de)
-// Peter Dennis Bartok (pbartok@novell.com)
-//
-// Copyright (C) 2002/2004 Ximian, Inc http://www.ximian.com
-// Copyright (C) 2004 - 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.Drawing.Text;
-using System.Text;
-using System.Runtime.InteropServices;
-
-namespace System.Drawing
-{
-
- public sealed class FontFamily : MarshalByRefObject, IDisposable
- {
-
- //static private FontFamily genericMonospace;
- //static private FontFamily genericSansSerif;
- //static private FontFamily genericSerif;
- private string name;
- private IntPtr nativeFontFamily = IntPtr.Zero;
-
- internal FontFamily(IntPtr fntfamily)
- {
- nativeFontFamily = fntfamily;
- }
-
- internal void refreshName()
- {
- StringBuilder sb;
-
- if (nativeFontFamily == IntPtr.Zero)
- return;
-
- sb = new StringBuilder(GDIPlus.FACESIZE);
- Status status = SafeNativeMethods.Gdip.GdipGetFamilyName(nativeFontFamily, sb, 0);
- SafeNativeMethods.Gdip.CheckStatus(status);
- name = sb.ToString();
- }
-
- ~FontFamily()
- {
- Dispose();
- }
-
- internal IntPtr NativeObject
- {
- get
- {
- return nativeFontFamily;
- }
- }
-
- internal IntPtr NativeFamily
- {
- get
- {
- return nativeFontFamily;
- }
- }
-
- public FontFamily(GenericFontFamilies genericFamily)
- {
- Status status;
- switch (genericFamily)
- {
- case GenericFontFamilies.SansSerif:
- status = SafeNativeMethods.Gdip.GdipGetGenericFontFamilySansSerif(out nativeFontFamily);
- break;
- case GenericFontFamilies.Serif:
- status = SafeNativeMethods.Gdip.GdipGetGenericFontFamilySerif(out nativeFontFamily);
- break;
- case GenericFontFamilies.Monospace:
- default: // Undocumented default
- status = SafeNativeMethods.Gdip.GdipGetGenericFontFamilyMonospace(out nativeFontFamily);
- break;
- }
- SafeNativeMethods.Gdip.CheckStatus(status);
- }
-
- public FontFamily(string name) : this(name, null)
- {
- }
-
- public FontFamily(string name, FontCollection fontCollection)
- {
- IntPtr handle = (fontCollection == null) ? IntPtr.Zero : fontCollection._nativeFontCollection;
- Status status = SafeNativeMethods.Gdip.GdipCreateFontFamilyFromName(name, handle, out nativeFontFamily);
- SafeNativeMethods.Gdip.CheckStatus(status);
- }
-
- public string Name
- {
- get
- {
- if (nativeFontFamily == IntPtr.Zero)
- throw new ArgumentException("Name", "Object was disposed.");
- if (name == null)
- refreshName();
- return name;
- }
- }
-
- public static FontFamily GenericMonospace
- {
- get { return new FontFamily(GenericFontFamilies.Monospace); }
- }
-
- public static FontFamily GenericSansSerif
- {
- get { return new FontFamily(GenericFontFamilies.SansSerif); }
- }
-
- public static FontFamily GenericSerif
- {
- get { return new FontFamily(GenericFontFamilies.Serif); }
- }
-
- public int GetCellAscent(FontStyle style)
- {
- short outProperty;
- Status status = SafeNativeMethods.Gdip.GdipGetCellAscent(nativeFontFamily, (int)style, out outProperty);
- SafeNativeMethods.Gdip.CheckStatus(status);
-
- return (int)outProperty;
- }
-
- public int GetCellDescent(FontStyle style)
- {
- short outProperty;
- Status status = SafeNativeMethods.Gdip.GdipGetCellDescent(nativeFontFamily, (int)style, out outProperty);
- SafeNativeMethods.Gdip.CheckStatus(status);
-
- return (int)outProperty;
- }
-
- public int GetEmHeight(FontStyle style)
- {
- short outProperty;
- Status status = SafeNativeMethods.Gdip.GdipGetEmHeight(nativeFontFamily, (int)style, out outProperty);
- SafeNativeMethods.Gdip.CheckStatus(status);
-
- return (int)outProperty;
- }
-
- public int GetLineSpacing(FontStyle style)
- {
- short outProperty;
- Status status = SafeNativeMethods.Gdip.GdipGetLineSpacing(nativeFontFamily, (int)style, out outProperty);
- SafeNativeMethods.Gdip.CheckStatus(status);
-
- return (int)outProperty;
- }
-
- [MonoDocumentationNote("When used with libgdiplus this method always return true (styles are created on demand).")]
- public bool IsStyleAvailable(FontStyle style)
- {
- bool outProperty;
- Status status = SafeNativeMethods.Gdip.GdipIsStyleAvailable(nativeFontFamily, (int)style, out outProperty);
- SafeNativeMethods.Gdip.CheckStatus(status);
-
- return outProperty;
- }
-
- public void Dispose()
- {
- if (nativeFontFamily != IntPtr.Zero)
- {
- Status status = SafeNativeMethods.Gdip.GdipDeleteFontFamily(nativeFontFamily);
- nativeFontFamily = IntPtr.Zero;
- GC.SuppressFinalize(this);
- // check the status code (throw) at the last step
- SafeNativeMethods.Gdip.CheckStatus(status);
- }
- }
-
- public override bool Equals(object obj)
- {
- FontFamily o = (obj as FontFamily);
- if (o == null)
- return false;
-
- return (Name == o.Name);
- }
-
- public override int GetHashCode()
- {
- return Name.GetHashCode();
- }
-
-
- public static FontFamily[] Families
- {
- get { return new InstalledFontCollection().Families; }
- }
-
- public static FontFamily[] GetFamilies(Graphics graphics)
- {
- if (graphics == null)
- throw new ArgumentNullException("graphics");
-
- InstalledFontCollection fntcol = new InstalledFontCollection();
- return fntcol.Families;
- }
-
- [MonoLimitation("The language parameter is ignored. We always return the name using the default system language.")]
- public string GetName(int language)
- {
- return Name;
- }
-
- public override string ToString()
- {
- return String.Concat("[FontFamily: Name=", Name, "]");
- }
- }
-}
-
diff --git a/src/System.Drawing.Common/src/Unix/System.Drawing/GraphicsUnit.cs b/src/System.Drawing.Common/src/Unix/System.Drawing/GraphicsUnit.cs
deleted file mode 100644
index 41963d4554..0000000000
--- a/src/System.Drawing.Common/src/Unix/System.Drawing/GraphicsUnit.cs
+++ /dev/null
@@ -1,44 +0,0 @@
-// Licensed to the .NET Foundation under one or more agreements.
-// See the LICENSE file in the project root for more information.
-//
-// System.Drawing.GraphicsUnit.cs
-//
-// Author: Dennis Hayes (dennish@raytek.com)
-//
-// (C) 2001 Ximian, Inc. http://www.ximian.com
-// Copyright (C) 2004,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.
-//
-
-namespace System.Drawing
-{
-
- public enum GraphicsUnit
- {
- World = 0,
- Display = 1,
- Pixel = 2,
- Point = 3,
- Inch = 4,
- Document = 5,
- Millimeter = 6
- }
-}
diff --git a/src/System.Drawing.Common/src/Unix/System.Drawing/KnownColors.cs b/src/System.Drawing.Common/src/Unix/System.Drawing/KnownColors.cs
deleted file mode 100644
index a8bafc40fb..0000000000
--- a/src/System.Drawing.Common/src/Unix/System.Drawing/KnownColors.cs
+++ /dev/null
@@ -1,666 +0,0 @@
-// Licensed to the .NET Foundation under one or more agreements.
-// See the LICENSE file in the project root for more information.
-//
-// System.Drawing.KnownColors
-//
-// Authors:
-// Gonzalo Paniagua Javier (gonzalo@ximian.com)
-// Peter Dennis Bartok (pbartok@novell.com)
-// Sebastien Pouliot <sebastien@ximian.com>
-//
-// Copyright (C) 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.
-//
-
-namespace System.Drawing
-{
-
- internal static class KnownColors
- {
- // FindColorMatch relies on the index + 1 == KnowColor match
- static internal uint[] ArgbValues = new uint[] {
- 0x00000000, /* 000 - Empty */
- 0xFFD4D0C8, /* 001 - ActiveBorder */
- 0xFF0054E3, /* 002 - ActiveCaption */
- 0xFFFFFFFF, /* 003 - ActiveCaptionText */
- 0xFF808080, /* 004 - AppWorkspace */
- 0xFFECE9D8, /* 005 - Control */
- 0xFFACA899, /* 006 - ControlDark */
- 0xFF716F64, /* 007 - ControlDarkDark */
- 0xFFF1EFE2, /* 008 - ControlLight */
- 0xFFFFFFFF, /* 009 - ControlLightLight */
- 0xFF000000, /* 010 - ControlText */
- 0xFF004E98, /* 011 - Desktop */
- 0xFFACA899, /* 012 - GrayText */
- 0xFF316AC5, /* 013 - Highlight */
- 0xFFFFFFFF, /* 014 - HighlightText */
- 0xFF000080, /* 015 - HotTrack */
- 0xFFD4D0C8, /* 016 - InactiveBorder */
- 0xFF7A96DF, /* 017 - InactiveCaption */
- 0xFFD8E4F8, /* 018 - InactiveCaptionText */
- 0xFFFFFFE1, /* 019 - Info */
- 0xFF000000, /* 020 - InfoText */
- 0xFFFFFFFF, /* 021 - Menu */
- 0xFF000000, /* 022 - MenuText */
- 0xFFD4D0C8, /* 023 - ScrollBar */
- 0xFFFFFFFF, /* 024 - Window */
- 0xFF000000, /* 025 - WindowFrame */
- 0xFF000000, /* 026 - WindowText */
- 0x00FFFFFF, /* 027 - Transparent */
- 0xFFF0F8FF, /* 028 - AliceBlue */
- 0xFFFAEBD7, /* 029 - AntiqueWhite */
- 0xFF00FFFF, /* 030 - Aqua */
- 0xFF7FFFD4, /* 031 - Aquamarine */
- 0xFFF0FFFF, /* 032 - Azure */
- 0xFFF5F5DC, /* 033 - Beige */
- 0xFFFFE4C4, /* 034 - Bisque */
- 0xFF000000, /* 035 - Black */
- 0xFFFFEBCD, /* 036 - BlanchedAlmond */
- 0xFF0000FF, /* 037 - Blue */
- 0xFF8A2BE2, /* 038 - BlueViolet */
- 0xFFA52A2A, /* 039 - Brown */
- 0xFFDEB887, /* 040 - BurlyWood */
- 0xFF5F9EA0, /* 041 - CadetBlue */
- 0xFF7FFF00, /* 042 - Chartreuse */
- 0xFFD2691E, /* 043 - Chocolate */
- 0xFFFF7F50, /* 044 - Coral */
- 0xFF6495ED, /* 045 - CornflowerBlue */
- 0xFFFFF8DC, /* 046 - Cornsilk */
- 0xFFDC143C, /* 047 - Crimson */
- 0xFF00FFFF, /* 048 - Cyan */
- 0xFF00008B, /* 049 - DarkBlue */
- 0xFF008B8B, /* 050 - DarkCyan */
- 0xFFB8860B, /* 051 - DarkGoldenrod */
- 0xFFA9A9A9, /* 052 - DarkGray */
- 0xFF006400, /* 053 - DarkGreen */
- 0xFFBDB76B, /* 054 - DarkKhaki */
- 0xFF8B008B, /* 055 - DarkMagenta */
- 0xFF556B2F, /* 056 - DarkOliveGreen */
- 0xFFFF8C00, /* 057 - DarkOrange */
- 0xFF9932CC, /* 058 - DarkOrchid */
- 0xFF8B0000, /* 059 - DarkRed */
- 0xFFE9967A, /* 060 - DarkSalmon */
- 0xFF8FBC8B, /* 061 - DarkSeaGreen */
- 0xFF483D8B, /* 062 - DarkSlateBlue */
- 0xFF2F4F4F, /* 063 - DarkSlateGray */
- 0xFF00CED1, /* 064 - DarkTurquoise */
- 0xFF9400D3, /* 065 - DarkViolet */
- 0xFFFF1493, /* 066 - DeepPink */
- 0xFF00BFFF, /* 067 - DeepSkyBlue */
- 0xFF696969, /* 068 - DimGray */
- 0xFF1E90FF, /* 069 - DodgerBlue */
- 0xFFB22222, /* 070 - Firebrick */
- 0xFFFFFAF0, /* 071 - FloralWhite */
- 0xFF228B22, /* 072 - ForestGreen */
- 0xFFFF00FF, /* 073 - Fuchsia */
- 0xFFDCDCDC, /* 074 - Gainsboro */
- 0xFFF8F8FF, /* 075 - GhostWhite */
- 0xFFFFD700, /* 076 - Gold */
- 0xFFDAA520, /* 077 - Goldenrod */
- 0xFF808080, /* 078 - Gray */
- 0xFF008000, /* 079 - Green */
- 0xFFADFF2F, /* 080 - GreenYellow */
- 0xFFF0FFF0, /* 081 - Honeydew */
- 0xFFFF69B4, /* 082 - HotPink */
- 0xFFCD5C5C, /* 083 - IndianRed */
- 0xFF4B0082, /* 084 - Indigo */
- 0xFFFFFFF0, /* 085 - Ivory */
- 0xFFF0E68C, /* 086 - Khaki */
- 0xFFE6E6FA, /* 087 - Lavender */
- 0xFFFFF0F5, /* 088 - LavenderBlush */
- 0xFF7CFC00, /* 089 - LawnGreen */
- 0xFFFFFACD, /* 090 - LemonChiffon */
- 0xFFADD8E6, /* 091 - LightBlue */
- 0xFFF08080, /* 092 - LightCoral */
- 0xFFE0FFFF, /* 093 - LightCyan */
- 0xFFFAFAD2, /* 094 - LightGoldenrodYellow */
- 0xFFD3D3D3, /* 095 - LightGray */
- 0xFF90EE90, /* 096 - LightGreen */
- 0xFFFFB6C1, /* 097 - LightPink */
- 0xFFFFA07A, /* 098 - LightSalmon */
- 0xFF20B2AA, /* 099 - LightSeaGreen */
- 0xFF87CEFA, /* 100 - LightSkyBlue */
- 0xFF778899, /* 101 - LightSlateGray */
- 0xFFB0C4DE, /* 102 - LightSteelBlue */
- 0xFFFFFFE0, /* 103 - LightYellow */
- 0xFF00FF00, /* 104 - Lime */
- 0xFF32CD32, /* 105 - LimeGreen */
- 0xFFFAF0E6, /* 106 - Linen */
- 0xFFFF00FF, /* 107 - Magenta */
- 0xFF800000, /* 108 - Maroon */
- 0xFF66CDAA, /* 109 - MediumAquamarine */
- 0xFF0000CD, /* 110 - MediumBlue */
- 0xFFBA55D3, /* 111 - MediumOrchid */
- 0xFF9370DB, /* 112 - MediumPurple */
- 0xFF3CB371, /* 113 - MediumSeaGreen */
- 0xFF7B68EE, /* 114 - MediumSlateBlue */
- 0xFF00FA9A, /* 115 - MediumSpringGreen */
- 0xFF48D1CC, /* 116 - MediumTurquoise */
- 0xFFC71585, /* 117 - MediumVioletRed */
- 0xFF191970, /* 118 - MidnightBlue */
- 0xFFF5FFFA, /* 119 - MintCream */
- 0xFFFFE4E1, /* 120 - MistyRose */
- 0xFFFFE4B5, /* 121 - Moccasin */
- 0xFFFFDEAD, /* 122 - NavajoWhite */
- 0xFF000080, /* 123 - Navy */
- 0xFFFDF5E6, /* 124 - OldLace */
- 0xFF808000, /* 125 - Olive */
- 0xFF6B8E23, /* 126 - OliveDrab */
- 0xFFFFA500, /* 127 - Orange */
- 0xFFFF4500, /* 128 - OrangeRed */
- 0xFFDA70D6, /* 129 - Orchid */
- 0xFFEEE8AA, /* 130 - PaleGoldenrod */
- 0xFF98FB98, /* 131 - PaleGreen */
- 0xFFAFEEEE, /* 132 - PaleTurquoise */
- 0xFFDB7093, /* 133 - PaleVioletRed */
- 0xFFFFEFD5, /* 134 - PapayaWhip */
- 0xFFFFDAB9, /* 135 - PeachPuff */
- 0xFFCD853F, /* 136 - Peru */
- 0xFFFFC0CB, /* 137 - Pink */
- 0xFFDDA0DD, /* 138 - Plum */
- 0xFFB0E0E6, /* 139 - PowderBlue */
- 0xFF800080, /* 140 - Purple */
- 0xFFFF0000, /* 141 - Red */
- 0xFFBC8F8F, /* 142 - RosyBrown */
- 0xFF4169E1, /* 143 - RoyalBlue */
- 0xFF8B4513, /* 144 - SaddleBrown */
- 0xFFFA8072, /* 145 - Salmon */
- 0xFFF4A460, /* 146 - SandyBrown */
- 0xFF2E8B57, /* 147 - SeaGreen */
- 0xFFFFF5EE, /* 148 - SeaShell */
- 0xFFA0522D, /* 149 - Sienna */
- 0xFFC0C0C0, /* 150 - Silver */
- 0xFF87CEEB, /* 151 - SkyBlue */
- 0xFF6A5ACD, /* 152 - SlateBlue */
- 0xFF708090, /* 153 - SlateGray */
- 0xFFFFFAFA, /* 154 - Snow */
- 0xFF00FF7F, /* 155 - SpringGreen */
- 0xFF4682B4, /* 156 - SteelBlue */
- 0xFFD2B48C, /* 157 - Tan */
- 0xFF008080, /* 158 - Teal */
- 0xFFD8BFD8, /* 159 - Thistle */
- 0xFFFF6347, /* 160 - Tomato */
- 0xFF40E0D0, /* 161 - Turquoise */
- 0xFFEE82EE, /* 162 - Violet */
- 0xFFF5DEB3, /* 163 - Wheat */
- 0xFFFFFFFF, /* 164 - White */
- 0xFFF5F5F5, /* 165 - WhiteSmoke */
- 0xFFFFFF00, /* 166 - Yellow */
- 0xFF9ACD32, /* 167 - YellowGreen */
- 0xFFECE9D8, /* 168 - ButtonFace */
- 0xFFFFFFFF, /* 169 - ButtonHighlight */
- 0xFFACA899, /* 170 - ButtonShadow */
- 0xFF3D95FF, /* 171 - GradientActiveCaption */
- 0xFF9DB9EB, /* 172 - GradientInactiveCaption */
- 0xFFECE9D8, /* 173 - MenuBar */
- 0xFF316AC5, /* 174 - MenuHighlight */
- };
-
-#if !MONOTOUCH && !MONOMAC && SUPPORTS_WINDOWS_COLORS
- static KnownColors ()
- {
- if (GDIPlus.RunningOnWindows ()) {
- // If we're on Windows we should behave like MS and pull the colors
- RetrieveWindowsSystemColors ();
- }
- // note: Mono's SWF Theme class will call the static Update method to apply
- // correct system colors outside Windows
- }
-
- // Windows values are in BGR format and without alpha
- // so we force it to opaque (or everything will be transparent) and reverse B and R
- static uint GetSysColor (GetSysColorIndex index)
- {
- uint bgr = SafeNativeMethods.Gdip.Win32GetSysColor (index);
- return 0xFF000000 | (bgr & 0xFF) << 16 | (bgr & 0xFF00) | (bgr >> 16);
- }
-
- static void RetrieveWindowsSystemColors ()
- {
- ArgbValues [(int)KnownColor.ActiveBorder] = GetSysColor (GetSysColorIndex.COLOR_ACTIVEBORDER);
- ArgbValues [(int)KnownColor.ActiveCaption] = GetSysColor (GetSysColorIndex.COLOR_ACTIVECAPTION);
- ArgbValues [(int)KnownColor.ActiveCaptionText] = GetSysColor (GetSysColorIndex.COLOR_CAPTIONTEXT);
- ArgbValues [(int)KnownColor.AppWorkspace] = GetSysColor (GetSysColorIndex.COLOR_APPWORKSPACE);
- ArgbValues [(int)KnownColor.Control] = GetSysColor (GetSysColorIndex.COLOR_BTNFACE);
- ArgbValues [(int)KnownColor.ControlDark] = GetSysColor (GetSysColorIndex.COLOR_BTNSHADOW);
- ArgbValues [(int)KnownColor.ControlDarkDark] = GetSysColor (GetSysColorIndex.COLOR_3DDKSHADOW);
- ArgbValues [(int)KnownColor.ControlLight] = GetSysColor (GetSysColorIndex.COLOR_3DLIGHT);
- ArgbValues [(int)KnownColor.ControlLightLight] = GetSysColor (GetSysColorIndex.COLOR_BTNHIGHLIGHT);
- ArgbValues [(int)KnownColor.ControlText] = GetSysColor (GetSysColorIndex.COLOR_BTNTEXT);
- ArgbValues [(int)KnownColor.Desktop] = GetSysColor (GetSysColorIndex.COLOR_DESKTOP);
- ArgbValues [(int)KnownColor.GrayText] = GetSysColor (GetSysColorIndex.COLOR_GRAYTEXT);
- ArgbValues [(int)KnownColor.Highlight] = GetSysColor (GetSysColorIndex.COLOR_HIGHLIGHT);
- ArgbValues [(int)KnownColor.HighlightText] = GetSysColor (GetSysColorIndex.COLOR_HIGHLIGHTTEXT);
- ArgbValues [(int)KnownColor.HotTrack] = GetSysColor (GetSysColorIndex.COLOR_HOTLIGHT);
- ArgbValues [(int)KnownColor.InactiveBorder] = GetSysColor (GetSysColorIndex.COLOR_INACTIVEBORDER);
- ArgbValues [(int)KnownColor.InactiveCaption] = GetSysColor (GetSysColorIndex.COLOR_INACTIVECAPTION);
- ArgbValues [(int)KnownColor.InactiveCaptionText] = GetSysColor (GetSysColorIndex.COLOR_INACTIVECAPTIONTEXT);
- ArgbValues [(int)KnownColor.Info] = GetSysColor (GetSysColorIndex.COLOR_INFOBK);
- ArgbValues [(int)KnownColor.InfoText] = GetSysColor (GetSysColorIndex.COLOR_INFOTEXT);
- ArgbValues [(int)KnownColor.Menu] = GetSysColor (GetSysColorIndex.COLOR_MENU);
- ArgbValues [(int)KnownColor.MenuText] = GetSysColor (GetSysColorIndex.COLOR_MENUTEXT);
- ArgbValues [(int)KnownColor.ScrollBar] = GetSysColor (GetSysColorIndex.COLOR_SCROLLBAR);
- ArgbValues [(int)KnownColor.Window] = GetSysColor (GetSysColorIndex.COLOR_WINDOW);
- ArgbValues [(int)KnownColor.WindowFrame] = GetSysColor (GetSysColorIndex.COLOR_WINDOWFRAME);
- ArgbValues [(int)KnownColor.WindowText] = GetSysColor (GetSysColorIndex.COLOR_WINDOWTEXT);
- ArgbValues [(int)KnownColor.ButtonFace] = GetSysColor (GetSysColorIndex.COLOR_BTNFACE);
- ArgbValues [(int)KnownColor.ButtonHighlight] = GetSysColor (GetSysColorIndex.COLOR_BTNHIGHLIGHT);
- ArgbValues [(int)KnownColor.ButtonShadow] = GetSysColor (GetSysColorIndex.COLOR_BTNSHADOW);
- ArgbValues [(int)KnownColor.GradientActiveCaption] = GetSysColor (GetSysColorIndex.COLOR_GRADIENTACTIVECAPTION);
- ArgbValues [(int)KnownColor.GradientInactiveCaption] = GetSysColor (GetSysColorIndex.COLOR_GRADIENTINACTIVECAPTION);
- ArgbValues [(int)KnownColor.MenuBar] = GetSysColor (GetSysColorIndex.COLOR_MENUBAR);
- ArgbValues [(int)KnownColor.MenuHighlight] = GetSysColor (GetSysColorIndex.COLOR_MENUHIGHLIGHT);
- }
-#endif
-
- public static Color FromKnownColor(KnownColor kc)
- {
- return ColorUtil.FromKnownColor(kc);
- }
-
- public static string GetName(short kc)
- {
- switch (kc)
- {
- case 1:
- return "ActiveBorder";
- case 2:
- return "ActiveCaption";
- case 3:
- return "ActiveCaptionText";
- case 4:
- return "AppWorkspace";
- case 5:
- return "Control";
- case 6:
- return "ControlDark";
- case 7:
- return "ControlDarkDark";
- case 8:
- return "ControlLight";
- case 9:
- return "ControlLightLight";
- case 10:
- return "ControlText";
- case 11:
- return "Desktop";
- case 12:
- return "GrayText";
- case 13:
- return "Highlight";
- case 14:
- return "HighlightText";
- case 15:
- return "HotTrack";
- case 16:
- return "InactiveBorder";
- case 17:
- return "InactiveCaption";
- case 18:
- return "InactiveCaptionText";
- case 19:
- return "Info";
- case 20:
- return "InfoText";
- case 21:
- return "Menu";
- case 22:
- return "MenuText";
- case 23:
- return "ScrollBar";
- case 24:
- return "Window";
- case 25:
- return "WindowFrame";
- case 26:
- return "WindowText";
- case 27:
- return "Transparent";
- case 28:
- return "AliceBlue";
- case 29:
- return "AntiqueWhite";
- case 30:
- return "Aqua";
- case 31:
- return "Aquamarine";
- case 32:
- return "Azure";
- case 33:
- return "Beige";
- case 34:
- return "Bisque";
- case 35:
- return "Black";
- case 36:
- return "BlanchedAlmond";
- case 37:
- return "Blue";
- case 38:
- return "BlueViolet";
- case 39:
- return "Brown";
- case 40:
- return "BurlyWood";
- case 41:
- return "CadetBlue";
- case 42:
- return "Chartreuse";
- case 43:
- return "Chocolate";
- case 44:
- return "Coral";
- case 45:
- return "CornflowerBlue";
- case 46:
- return "Cornsilk";
- case 47:
- return "Crimson";
- case 48:
- return "Cyan";
- case 49:
- return "DarkBlue";
- case 50:
- return "DarkCyan";
- case 51:
- return "DarkGoldenrod";
- case 52:
- return "DarkGray";
- case 53:
- return "DarkGreen";
- case 54:
- return "DarkKhaki";
- case 55:
- return "DarkMagenta";
- case 56:
- return "DarkOliveGreen";
- case 57:
- return "DarkOrange";
- case 58:
- return "DarkOrchid";
- case 59:
- return "DarkRed";
- case 60:
- return "DarkSalmon";
- case 61:
- return "DarkSeaGreen";
- case 62:
- return "DarkSlateBlue";
- case 63:
- return "DarkSlateGray";
- case 64:
- return "DarkTurquoise";
- case 65:
- return "DarkViolet";
- case 66:
- return "DeepPink";
- case 67:
- return "DeepSkyBlue";
- case 68:
- return "DimGray";
- case 69:
- return "DodgerBlue";
- case 70:
- return "Firebrick";
- case 71:
- return "FloralWhite";
- case 72:
- return "ForestGreen";
- case 73:
- return "Fuchsia";
- case 74:
- return "Gainsboro";
- case 75:
- return "GhostWhite";
- case 76:
- return "Gold";
- case 77:
- return "Goldenrod";
- case 78:
- return "Gray";
- case 79:
- return "Green";
- case 80:
- return "GreenYellow";
- case 81:
- return "Honeydew";
- case 82:
- return "HotPink";
- case 83:
- return "IndianRed";
- case 84:
- return "Indigo";
- case 85:
- return "Ivory";
- case 86:
- return "Khaki";
- case 87:
- return "Lavender";
- case 88:
- return "LavenderBlush";
- case 89:
- return "LawnGreen";
- case 90:
- return "LemonChiffon";
- case 91:
- return "LightBlue";
- case 92:
- return "LightCoral";
- case 93:
- return "LightCyan";
- case 94:
- return "LightGoldenrodYellow";
- case 95:
- return "LightGray";
- case 96:
- return "LightGreen";
- case 97:
- return "LightPink";
- case 98:
- return "LightSalmon";
- case 99:
- return "LightSeaGreen";
- case 100:
- return "LightSkyBlue";
- case 101:
- return "LightSlateGray";
- case 102:
- return "LightSteelBlue";
- case 103:
- return "LightYellow";
- case 104:
- return "Lime";
- case 105:
- return "LimeGreen";
- case 106:
- return "Linen";
- case 107:
- return "Magenta";
- case 108:
- return "Maroon";
- case 109:
- return "MediumAquamarine";
- case 110:
- return "MediumBlue";
- case 111:
- return "MediumOrchid";
- case 112:
- return "MediumPurple";
- case 113:
- return "MediumSeaGreen";
- case 114:
- return "MediumSlateBlue";
- case 115:
- return "MediumSpringGreen";
- case 116:
- return "MediumTurquoise";
- case 117:
- return "MediumVioletRed";
- case 118:
- return "MidnightBlue";
- case 119:
- return "MintCream";
- case 120:
- return "MistyRose";
- case 121:
- return "Moccasin";
- case 122:
- return "NavajoWhite";
- case 123:
- return "Navy";
- case 124:
- return "OldLace";
- case 125:
- return "Olive";
- case 126:
- return "OliveDrab";
- case 127:
- return "Orange";
- case 128:
- return "OrangeRed";
- case 129:
- return "Orchid";
- case 130:
- return "PaleGoldenrod";
- case 131:
- return "PaleGreen";
- case 132:
- return "PaleTurquoise";
- case 133:
- return "PaleVioletRed";
- case 134:
- return "PapayaWhip";
- case 135:
- return "PeachPuff";
- case 136:
- return "Peru";
- case 137:
- return "Pink";
- case 138:
- return "Plum";
- case 139:
- return "PowderBlue";
- case 140:
- return "Purple";
- case 141:
- return "Red";
- case 142:
- return "RosyBrown";
- case 143:
- return "RoyalBlue";
- case 144:
- return "SaddleBrown";
- case 145:
- return "Salmon";
- case 146:
- return "SandyBrown";
- case 147:
- return "SeaGreen";
- case 148:
- return "SeaShell";
- case 149:
- return "Sienna";
- case 150:
- return "Silver";
- case 151:
- return "SkyBlue";
- case 152:
- return "SlateBlue";
- case 153:
- return "SlateGray";
- case 154:
- return "Snow";
- case 155:
- return "SpringGreen";
- case 156:
- return "SteelBlue";
- case 157:
- return "Tan";
- case 158:
- return "Teal";
- case 159:
- return "Thistle";
- case 160:
- return "Tomato";
- case 161:
- return "Turquoise";
- case 162:
- return "Violet";
- case 163:
- return "Wheat";
- case 164:
- return "White";
- case 165:
- return "WhiteSmoke";
- case 166:
- return "Yellow";
- case 167:
- return "YellowGreen";
- case 168:
- return "ButtonFace";
- case 169:
- return "ButtonHighlight";
- case 170:
- return "ButtonShadow";
- case 171:
- return "GradientActiveCaption";
- case 172:
- return "GradientInactiveCaption";
- case 173:
- return "MenuBar";
- case 174:
- return "MenuHighlight";
- default:
- return String.Empty;
- }
- }
-
- public static string GetName(KnownColor kc)
- {
- return GetName((short)kc);
- }
-
- // FIXME: Linear scan
- public static Color FindColorMatch(Color c)
- {
- uint argb = (uint)c.ToArgb();
-
- // 1-based
- const int first_real_color_index = (int)KnownColor.AliceBlue;
- const int last_real_color_index = (int)KnownColor.YellowGreen;
-
- for (int i = first_real_color_index - 1; i < last_real_color_index; i++)
- {
- if (argb == KnownColors.ArgbValues[i])
- return KnownColors.FromKnownColor((KnownColor)i);
- }
-
- return Color.Empty;
- }
-
- // When this method is called, we teach any new color(s) to the Color class
- // NOTE: This is called (reflection) by System.Windows.Forms.Theme (this isn't dead code)
- public static void Update(int knownColor, int color)
- {
- ArgbValues[knownColor] = (uint)color;
- }
- }
-}
diff --git a/src/System.Drawing.Common/src/Unix/System.Drawing/SystemColors.cs b/src/System.Drawing.Common/src/Unix/System.Drawing/SystemColors.cs
deleted file mode 100644
index e4f72a2431..0000000000
--- a/src/System.Drawing.Common/src/Unix/System.Drawing/SystemColors.cs
+++ /dev/null
@@ -1,208 +0,0 @@
-// Licensed to the .NET Foundation under one or more agreements.
-// See the LICENSE file in the project root for more information.
-//
-// System.Drawing.SystemColors
-//
-// Copyright (C) 2002 Ximian, Inc (http://www.ximian.com)
-// Copyright (C) 2004-2005, 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.
-//
-// Authors:
-// Gonzalo Paniagua Javier (gonzalo@ximian.com)
-// Peter Dennis Bartok (pbartok@novell.com)
-// Sebastien Pouliot <sebastien@ximian.com>
-//
-
-namespace System.Drawing
-{
-
- public sealed class SystemColors
- {
-
- private SystemColors()
- {
- }
-
- static public Color ActiveBorder
- {
- get { return KnownColors.FromKnownColor(KnownColor.ActiveBorder); }
- }
-
- static public Color ActiveCaption
- {
- get { return KnownColors.FromKnownColor(KnownColor.ActiveCaption); }
- }
-
- static public Color ActiveCaptionText
- {
- get { return KnownColors.FromKnownColor(KnownColor.ActiveCaptionText); }
- }
-
- static public Color AppWorkspace
- {
- get { return KnownColors.FromKnownColor(KnownColor.AppWorkspace); }
- }
-
- static public Color Control
- {
- get { return KnownColors.FromKnownColor(KnownColor.Control); }
- }
-
- static public Color ControlDark
- {
- get { return KnownColors.FromKnownColor(KnownColor.ControlDark); }
- }
-
- static public Color ControlDarkDark
- {
- get { return KnownColors.FromKnownColor(KnownColor.ControlDarkDark); }
- }
-
- static public Color ControlLight
- {
- get { return KnownColors.FromKnownColor(KnownColor.ControlLight); }
- }
-
- static public Color ControlLightLight
- {
- get { return KnownColors.FromKnownColor(KnownColor.ControlLightLight); }
- }
-
- static public Color ControlText
- {
- get { return KnownColors.FromKnownColor(KnownColor.ControlText); }
- }
-
- static public Color Desktop
- {
- get { return KnownColors.FromKnownColor(KnownColor.Desktop); }
- }
-
- static public Color GrayText
- {
- get { return KnownColors.FromKnownColor(KnownColor.GrayText); }
- }
-
- static public Color Highlight
- {
- get { return KnownColors.FromKnownColor(KnownColor.Highlight); }
- }
-
- static public Color HighlightText
- {
- get { return KnownColors.FromKnownColor(KnownColor.HighlightText); }
- }
-
- static public Color HotTrack
- {
- get { return KnownColors.FromKnownColor(KnownColor.HotTrack); }
- }
-
- static public Color InactiveBorder
- {
- get { return KnownColors.FromKnownColor(KnownColor.InactiveBorder); }
- }
-
- static public Color InactiveCaption
- {
- get { return KnownColors.FromKnownColor(KnownColor.InactiveCaption); }
- }
-
- static public Color InactiveCaptionText
- {
- get { return KnownColors.FromKnownColor(KnownColor.InactiveCaptionText); }
- }
-
- static public Color Info
- {
- get { return KnownColors.FromKnownColor(KnownColor.Info); }
- }
-
- static public Color InfoText
- {
- get { return KnownColors.FromKnownColor(KnownColor.InfoText); }
- }
-
- static public Color Menu
- {
- get { return KnownColors.FromKnownColor(KnownColor.Menu); }
- }
-
- static public Color MenuText
- {
- get { return KnownColors.FromKnownColor(KnownColor.MenuText); }
- }
-
- static public Color ScrollBar
- {
- get { return KnownColors.FromKnownColor(KnownColor.ScrollBar); }
- }
-
- static public Color Window
- {
- get { return KnownColors.FromKnownColor(KnownColor.Window); }
- }
-
- static public Color WindowFrame
- {
- get { return KnownColors.FromKnownColor(KnownColor.WindowFrame); }
- }
-
- static public Color WindowText
- {
- get { return KnownColors.FromKnownColor(KnownColor.WindowText); }
- }
- static public Color ButtonFace
- {
- get { return KnownColors.FromKnownColor(KnownColor.ButtonFace); }
- }
-
- static public Color ButtonHighlight
- {
- get { return KnownColors.FromKnownColor(KnownColor.ButtonHighlight); }
- }
-
- static public Color ButtonShadow
- {
- get { return KnownColors.FromKnownColor(KnownColor.ButtonShadow); }
- }
-
- static public Color GradientActiveCaption
- {
- get { return KnownColors.FromKnownColor(KnownColor.GradientActiveCaption); }
- }
-
- static public Color GradientInactiveCaption
- {
- get { return KnownColors.FromKnownColor(KnownColor.GradientInactiveCaption); }
- }
-
- static public Color MenuBar
- {
- get { return KnownColors.FromKnownColor(KnownColor.MenuBar); }
- }
-
- static public Color MenuHighlight
- {
- get { return KnownColors.FromKnownColor(KnownColor.MenuHighlight); }
- }
- }
-}
diff --git a/src/System.Drawing.Common/src/Unix/System.Drawing/gdipEnums.cs b/src/System.Drawing.Common/src/Unix/System.Drawing/gdipEnums.cs
deleted file mode 100644
index dbf28bfd67..0000000000
--- a/src/System.Drawing.Common/src/Unix/System.Drawing/gdipEnums.cs
+++ /dev/null
@@ -1,120 +0,0 @@
-// Licensed to the .NET Foundation under one or more agreements.
-// See the LICENSE file in the project root for more information.
-//
-// System.Drawing.gdipEnums.cs
-//
-// Authors:
-// Alexandre Pigolkine (pigolkine@gmx.de)
-// Sebastien Pouliot <sebastien@ximian.com>
-//
-// Copyright (C) 2004, 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.
-//
-
-namespace System.Drawing
-{
-
- internal enum Status
- {
- Ok = 0,
- GenericError = 1,
- InvalidParameter = 2,
- OutOfMemory = 3,
- ObjectBusy = 4,
- InsufficientBuffer = 5,
- NotImplemented = 6,
- Win32Error = 7,
- WrongState = 8,
- Aborted = 9,
- FileNotFound = 10,
- ValueOverflow = 11,
- AccessDenied = 12,
- UnknownImageFormat = 13,
- FontFamilyNotFound = 14,
- FontStyleNotFound = 15,
- NotTrueTypeFont = 16,
- UnsupportedGdiplusVersion = 17,
- GdiplusNotInitialized = 18,
- PropertyNotFound = 19,
- PropertyNotSupported = 20,
- ProfileNotFound = 21
- }
-
- internal enum BrushType
- {
- BrushTypeSolidColor = 0,
- BrushTypeHatchFill = 1,
- BrushTypeTextureFill = 2,
- BrushTypePathGradient = 3,
- BrushTypeLinearGradient = 4
- }
-
- internal enum ImageType
- {
- Unknown = 0,
- Bitmap = 1,
- Metafile = 2
- }
-
- internal enum GetSysColorIndex
- {
- COLOR_SCROLLBAR = 0,
- COLOR_BACKGROUND = 1,
- COLOR_ACTIVECAPTION = 2,
- COLOR_INACTIVECAPTION = 3,
- COLOR_MENU = 4,
- COLOR_WINDOW = 5,
- COLOR_WINDOWFRAME = 6,
- COLOR_MENUTEXT = 7,
- COLOR_WINDOWTEXT = 8,
- COLOR_CAPTIONTEXT = 9,
- COLOR_ACTIVEBORDER = 10,
- COLOR_INACTIVEBORDER = 11,
- COLOR_APPWORKSPACE = 12,
- COLOR_HIGHLIGHT = 13,
- COLOR_HIGHLIGHTTEXT = 14,
- COLOR_BTNFACE = 15,
- COLOR_BTNSHADOW = 16,
- COLOR_GRAYTEXT = 17,
- COLOR_BTNTEXT = 18,
- COLOR_INACTIVECAPTIONTEXT = 19,
- COLOR_BTNHIGHLIGHT = 20,
- COLOR_3DDKSHADOW = 21,
- COLOR_3DLIGHT = 22,
- COLOR_INFOTEXT = 23,
- COLOR_INFOBK = 24,
-
- COLOR_HOTLIGHT = 26,
- COLOR_GRADIENTACTIVECAPTION = 27,
- COLOR_GRADIENTINACTIVECAPTION = 28,
- COLOR_MENUHIGHLIGHT = 29,
- COLOR_MENUBAR = 30,
-
- COLOR_DESKTOP = 1,
- COLOR_3DFACE = 16,
- COLOR_3DSHADOW = 16,
- COLOR_3DHIGHLIGHT = 20,
- COLOR_3DHILIGHT = 20,
- COLOR_BTNHILIGHT = 20,
-
- COLOR_MAXVALUE = 30,/* Maximum value */
- }
-}
diff --git a/src/System.Drawing.Common/src/Unix/System.Drawing/gdipFunctions.cs b/src/System.Drawing.Common/src/Unix/System.Drawing/gdipFunctions.cs
deleted file mode 100644
index 9c97abbf35..0000000000
--- a/src/System.Drawing.Common/src/Unix/System.Drawing/gdipFunctions.cs
+++ /dev/null
@@ -1,620 +0,0 @@
-// Licensed to the .NET Foundation under one or more agreements.
-// See the LICENSE file in the project root for more information.
-//
-// System.Drawing.gdipFunctions.cs
-//
-// Authors:
-// Alexandre Pigolkine (pigolkine@gmx.de)
-// Jordi Mas i Hernandez (jordi@ximian.com)
-// Sanjay Gupta (gsanjay@novell.com)
-// Ravindra (rkumar@novell.com)
-// Peter Dennis Bartok (pbartok@novell.com)
-// Sebastien Pouliot <sebastien@ximian.com>
-//
-// Copyright (C) 2004 - 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.IO;
-using System.Runtime.InteropServices;
-using System.Text;
-using System.Drawing.Drawing2D;
-using System.Drawing.Imaging;
-using System.Drawing.Text;
-using System.Globalization;
-using System.Security;
-using System.Runtime.InteropServices.ComTypes;
-
-namespace System.Drawing
-{
- /// <summary>
- /// GDI+ API Functions
- /// </summary>
- internal static class GDIPlus
- {
- public const int FACESIZE = 32;
- public const int LANG_NEUTRAL = 0;
- public static IntPtr Display = IntPtr.Zero;
- public static bool UseX11Drawable = false;
- public static bool UseCarbonDrawable = false;
- public static bool UseCocoaDrawable = false;
-
- private const string GdiPlus = "gdiplus";
-
- #region gdiplus.dll functions
-
- internal static ulong GdiPlusToken = 0;
-
- static void ProcessExit(object sender, EventArgs e)
- {
- // Called all pending objects and claim any pending handle before
- // shutting down
- GC.Collect();
- GC.WaitForPendingFinalizers();
-#if false
- GdiPlusToken = 0;
-
- // This causes crashes in because this call occurs before all
- // managed GDI+ objects are finalized. When they are finalized
- // they call into a shutdown GDI+ and we crash.
- GdiplusShutdown (ref GdiPlusToken);
-
- // This causes crashes in Mono libgdiplus because this call
- // occurs before all managed GDI objects are finalized
- // When they are finalized they use the closed display and
- // crash
- if (UseX11Drawable && Display != IntPtr.Zero) {
- XCloseDisplay (Display);
- }
-#endif
- }
-
- static GDIPlus()
- {
-#if NETSTANDARD1_6
- bool isUnix = !RuntimeInformation.IsOSPlatform (OSPlatform.Windows);
-#else
- int platform = (int)Environment.OSVersion.Platform;
- bool isUnix = (platform == 4) || (platform == 6) || (platform == 128);
-#endif
-
- if (isUnix)
- {
- if (Environment.GetEnvironmentVariable("not_supported_MONO_MWF_USE_NEW_X11_BACKEND") != null || Environment.GetEnvironmentVariable("MONO_MWF_MAC_FORCE_X11") != null)
- {
- UseX11Drawable = true;
- }
- else
- {
- IntPtr buf = Marshal.AllocHGlobal(8192);
- // This is kind of a hack but gets us sysname from uname (struct utsname *name) on
- // linux and darwin
- if (uname(buf) != 0)
- {
- // WTH: We couldn't detect the OS; lets default to X11
- UseX11Drawable = true;
- }
- else
- {
- string os = Marshal.PtrToStringAnsi(buf);
- if (os == "Darwin")
- UseCarbonDrawable = true;
- else
- UseX11Drawable = true;
- }
- Marshal.FreeHGlobal(buf);
- }
- }
-
- // under MS 1.x this event is raised only for the default application domain
-#if !NETSTANDARD1_6
- AppDomain.CurrentDomain.ProcessExit += new EventHandler(ProcessExit);
-#endif
- }
-
- static public bool RunningOnWindows()
- {
- return !UseX11Drawable && !UseCarbonDrawable && !UseCocoaDrawable;
- }
-
- static public bool RunningOnUnix()
- {
- return UseX11Drawable || UseCarbonDrawable || UseCocoaDrawable;
- }
-
- // Copies a Ptr to an array of Points and releases the memory
- static public void FromUnManagedMemoryToPointI(IntPtr prt, Point[] pts)
- {
- int nPointSize = Marshal.SizeOf(pts[0]);
- IntPtr pos = prt;
- for (int i = 0; i < pts.Length; i++, pos = new IntPtr(pos.ToInt64() + nPointSize))
- pts[i] = (Point)Marshal.PtrToStructure(pos, typeof(Point));
-
- Marshal.FreeHGlobal(prt);
- }
-
- // Copies a Ptr to an array of Points and releases the memory
- static public void FromUnManagedMemoryToPoint(IntPtr prt, PointF[] pts)
- {
- int nPointSize = Marshal.SizeOf(pts[0]);
- IntPtr pos = prt;
- for (int i = 0; i < pts.Length; i++, pos = new IntPtr(pos.ToInt64() + nPointSize))
- pts[i] = (PointF)Marshal.PtrToStructure(pos, typeof(PointF));
-
- Marshal.FreeHGlobal(prt);
- }
-
- // Copies an array of Points to unmanaged memory
- static public IntPtr FromPointToUnManagedMemoryI(Point[] pts)
- {
- int nPointSize = Marshal.SizeOf(pts[0]);
- IntPtr dest = Marshal.AllocHGlobal(nPointSize * pts.Length);
- IntPtr pos = dest;
- for (int i = 0; i < pts.Length; i++, pos = new IntPtr(pos.ToInt64() + nPointSize))
- Marshal.StructureToPtr(pts[i], pos, false);
-
- return dest;
- }
-
- // Copies a Ptr to an array of v and releases the memory
- static public void FromUnManagedMemoryToRectangles(IntPtr prt, RectangleF[] pts)
- {
- int nPointSize = Marshal.SizeOf(pts[0]);
- IntPtr pos = prt;
- for (int i = 0; i < pts.Length; i++, pos = new IntPtr(pos.ToInt64() + nPointSize))
- pts[i] = (RectangleF)Marshal.PtrToStructure(pos, typeof(RectangleF));
-
- Marshal.FreeHGlobal(prt);
- }
-
- // Copies an array of Points to unmanaged memory
- static public IntPtr FromPointToUnManagedMemory(PointF[] pts)
- {
- int nPointSize = Marshal.SizeOf(pts[0]);
- IntPtr dest = Marshal.AllocHGlobal(nPointSize * pts.Length);
- IntPtr pos = dest;
- for (int i = 0; i < pts.Length; i++, pos = new IntPtr(pos.ToInt64() + nPointSize))
- Marshal.StructureToPtr(pts[i], pos, false);
-
- return dest;
- }
-
- // Converts a status into exception
- // TODO: Add more status code mappings here
- static internal void CheckStatus(Status status)
- {
- string msg;
- switch (status)
- {
- case Status.Ok:
- return;
- case Status.GenericError:
- msg = string.Format("Generic Error [GDI+ status: {0}]", status);
- throw new Exception(msg);
- case Status.InvalidParameter:
- msg = string.Format("A null reference or invalid value was found [GDI+ status: {0}]", status);
- throw new ArgumentException(msg);
- case Status.OutOfMemory:
- msg = string.Format("Not enough memory to complete operation [GDI+ status: {0}]", status);
- throw new OutOfMemoryException(msg);
- case Status.ObjectBusy:
- msg = string.Format("Object is busy and cannot state allow this operation [GDI+ status: {0}]", status);
- throw new MemberAccessException(msg);
- case Status.InsufficientBuffer:
- msg = string.Format("Insufficient buffer provided to complete operation [GDI+ status: {0}]", status);
-#if NETCORE
- throw new Exception(msg);
-#else
- throw new InternalBufferOverflowException (msg);
-#endif
- case Status.PropertyNotSupported:
- msg = string.Format("Property not supported [GDI+ status: {0}]", status);
- throw new NotSupportedException(msg);
- case Status.FileNotFound:
- msg = string.Format("Requested file was not found [GDI+ status: {0}]", status);
- throw new FileNotFoundException(msg);
- case Status.AccessDenied:
- msg = string.Format("Access to resource was denied [GDI+ status: {0}]", status);
- throw new UnauthorizedAccessException(msg);
- case Status.UnknownImageFormat:
- msg = string.Format("Either the image format is unknown or you don't have the required libraries to decode this format [GDI+ status: {0}]", status);
- throw new NotSupportedException(msg);
- case Status.NotImplemented:
- msg = string.Format("The requested feature is not implemented [GDI+ status: {0}]", status);
- throw new NotImplementedException(msg);
- case Status.WrongState:
- msg = string.Format("Object is not in a state that can allow this operation [GDI+ status: {0}]", status);
- throw new ArgumentException(msg);
- case Status.FontFamilyNotFound:
- msg = string.Format("The requested FontFamily could not be found [GDI+ status: {0}]", status);
- throw new ArgumentException(msg);
- case Status.ValueOverflow:
- msg = string.Format("Argument is out of range [GDI+ status: {0}]", status);
- throw new OverflowException(msg);
- case Status.Win32Error:
- msg = string.Format("The operation is invalid [GDI+ status: {0}]", status);
- throw new InvalidOperationException(msg);
- default:
- msg = string.Format("Unknown Error [GDI+ status: {0}]", status);
- throw new Exception(msg);
- }
- }
-
- // This is win32/gdi, not gdiplus, but it's easier to keep in here, also see above comment
- [DllImport("gdi32.dll", CallingConvention = CallingConvention.StdCall, CharSet = CharSet.Auto)]
- internal static extern IntPtr CreateFontIndirect(ref LOGFONT logfont);
- [DllImport("user32.dll", EntryPoint = "GetDC", CallingConvention = CallingConvention.StdCall, CharSet = CharSet.Ansi)]
- internal static extern IntPtr GetDC(IntPtr hwnd);
- [DllImport("user32.dll", EntryPoint = "ReleaseDC", CallingConvention = CallingConvention.StdCall, CharSet = CharSet.Ansi)]
- internal static extern int ReleaseDC(IntPtr hWnd, IntPtr hDC);
- [DllImport("gdi32.dll", EntryPoint = "SelectObject", CallingConvention = CallingConvention.StdCall, CharSet = CharSet.Ansi)]
- internal static extern IntPtr SelectObject(IntPtr hdc, IntPtr obj);
- [DllImport("user32.dll", SetLastError = true)]
- internal static extern bool GetIconInfo(IntPtr hIcon, out IconInfo iconinfo);
- [DllImport("user32.dll", CallingConvention = CallingConvention.StdCall, SetLastError = true)]
- internal static extern IntPtr CreateIconIndirect([In] ref IconInfo piconinfo);
- [DllImport("user32.dll", CallingConvention = CallingConvention.StdCall, SetLastError = true)]
- internal static extern bool DestroyIcon(IntPtr hIcon);
- [DllImport("gdi32.dll")]
- internal static extern bool DeleteObject(IntPtr hObject);
- [DllImport("user32.dll")]
- internal static extern IntPtr GetDesktopWindow();
-
- [DllImport("gdi32.dll", SetLastError = true)]
- public static extern int BitBlt(IntPtr hdcDest, int nXDest, int nYDest,
- int nWidth, int nHeight, IntPtr hdcSrc, int nXSrc, int nYSrc, int dwRop);
-
- [DllImport("user32.dll", EntryPoint = "GetSysColor", CallingConvention = CallingConvention.StdCall)]
- public static extern uint Win32GetSysColor(GetSysColorIndex index);
-
-
- // Some special X11 stuff
- [DllImport("libX11", EntryPoint = "XOpenDisplay")]
- internal extern static IntPtr XOpenDisplay(IntPtr display);
-
- [DllImport("libX11", EntryPoint = "XCloseDisplay")]
- internal extern static int XCloseDisplay(IntPtr display);
-
- [DllImport("libX11", EntryPoint = "XRootWindow")]
- internal extern static IntPtr XRootWindow(IntPtr display, int screen);
-
- [DllImport("libX11", EntryPoint = "XDefaultScreen")]
- internal extern static int XDefaultScreen(IntPtr display);
-
- [DllImport("libX11", EntryPoint = "XDefaultDepth")]
- internal extern static uint XDefaultDepth(IntPtr display, int screen);
-
- [DllImport("libX11", EntryPoint = "XGetImage")]
- internal extern static IntPtr XGetImage(IntPtr display, IntPtr drawable, int src_x, int src_y, int width, int height, int pane, int format);
-
- [DllImport("libX11", EntryPoint = "XGetPixel")]
- internal extern static int XGetPixel(IntPtr image, int x, int y);
-
- [DllImport("libX11", EntryPoint = "XDestroyImage")]
- internal extern static int XDestroyImage(IntPtr image);
-
- [DllImport("libX11", EntryPoint = "XDefaultVisual")]
- internal extern static IntPtr XDefaultVisual(IntPtr display, int screen);
-
- [DllImport("libX11", EntryPoint = "XGetVisualInfo")]
- internal extern static IntPtr XGetVisualInfo(IntPtr display, int vinfo_mask, ref XVisualInfo vinfo_template, ref int nitems);
-
- [DllImport("libX11", EntryPoint = "XVisualIDFromVisual")]
- internal extern static IntPtr XVisualIDFromVisual(IntPtr visual);
-
- [DllImport("libX11", EntryPoint = "XFree")]
- internal extern static void XFree(IntPtr data);
-
- internal sealed class GdiPlusStreamHelper
- {
- public Stream stream;
-
- private StreamGetHeaderDelegate sghd = null;
- private StreamGetBytesDelegate sgbd = null;
- private StreamSeekDelegate skd = null;
- private StreamPutBytesDelegate spbd = null;
- private StreamCloseDelegate scd = null;
- private StreamSizeDelegate ssd = null;
- private byte[] start_buf;
- private int start_buf_pos;
- private int start_buf_len;
- private byte[] managedBuf;
- private const int default_bufsize = 4096;
-
- public GdiPlusStreamHelper(Stream s, bool seekToOrigin)
- {
- managedBuf = new byte[default_bufsize];
-
- stream = s;
- if (stream != null && stream.CanSeek && seekToOrigin)
- {
- stream.Seek(0, SeekOrigin.Begin);
- }
- }
-
- public int StreamGetHeaderImpl(IntPtr buf, int bufsz)
- {
- int bytesRead;
-
- start_buf = new byte[bufsz];
-
- try
- {
- bytesRead = stream.Read(start_buf, 0, bufsz);
- }
- catch (IOException)
- {
- return -1;
- }
-
- if (bytesRead > 0 && buf != IntPtr.Zero)
- {
- Marshal.Copy(start_buf, 0, (IntPtr)(buf.ToInt64()), bytesRead);
- }
-
- start_buf_pos = 0;
- start_buf_len = bytesRead;
-
- return bytesRead;
- }
-
- public StreamGetHeaderDelegate GetHeaderDelegate
- {
- get
- {
- if (stream != null && stream.CanRead)
- {
- if (sghd == null)
- {
- sghd = new StreamGetHeaderDelegate(StreamGetHeaderImpl);
- }
- return sghd;
- }
- return null;
- }
- }
-
- public int StreamGetBytesImpl(IntPtr buf, int bufsz, bool peek)
- {
- if (buf == IntPtr.Zero && peek)
- {
- return -1;
- }
-
- if (bufsz > managedBuf.Length)
- managedBuf = new byte[bufsz];
- int bytesRead = 0;
- long streamPosition = 0;
-
- if (bufsz > 0)
- {
- if (stream.CanSeek)
- {
- streamPosition = stream.Position;
- }
- if (start_buf_len > 0)
- {
- if (start_buf_len > bufsz)
- {
- Array.Copy(start_buf, start_buf_pos, managedBuf, 0, bufsz);
- start_buf_pos += bufsz;
- start_buf_len -= bufsz;
- bytesRead = bufsz;
- bufsz = 0;
- }
- else
- {
- // this is easy
- Array.Copy(start_buf, start_buf_pos, managedBuf, 0, start_buf_len);
- bufsz -= start_buf_len;
- bytesRead = start_buf_len;
- start_buf_len = 0;
- }
- }
-
- if (bufsz > 0)
- {
- try
- {
- bytesRead += stream.Read(managedBuf, bytesRead, bufsz);
- }
- catch (IOException)
- {
- return -1;
- }
- }
-
- if (bytesRead > 0 && buf != IntPtr.Zero)
- {
- Marshal.Copy(managedBuf, 0, (IntPtr)(buf.ToInt64()), bytesRead);
- }
-
- if (!stream.CanSeek && (bufsz == 10) && peek)
- {
- // Special 'hack' to support peeking of the type for gdi+ on non-seekable streams
- }
-
- if (peek)
- {
- if (stream.CanSeek)
- {
- // If we are peeking bytes, then go back to original position before peeking
- stream.Seek(streamPosition, SeekOrigin.Begin);
- }
- else
- {
- throw new NotSupportedException();
- }
- }
- }
-
- return bytesRead;
- }
-
- public StreamGetBytesDelegate GetBytesDelegate
- {
- get
- {
- if (stream != null && stream.CanRead)
- {
- if (sgbd == null)
- {
- sgbd = new StreamGetBytesDelegate(StreamGetBytesImpl);
- }
- return sgbd;
- }
- return null;
- }
- }
-
- public long StreamSeekImpl(int offset, int whence)
- {
- // Make sure we have a valid 'whence'.
- if ((whence < 0) || (whence > 2))
- return -1;
-
- // Invalidate the start_buf if we're actually going to call a Seek method.
- start_buf_pos += start_buf_len;
- start_buf_len = 0;
-
- SeekOrigin origin;
-
- // Translate 'whence' into a SeekOrigin enum member.
- switch (whence)
- {
- case 0:
- origin = SeekOrigin.Begin;
- break;
- case 1:
- origin = SeekOrigin.Current;
- break;
- case 2:
- origin = SeekOrigin.End;
- break;
-
- // The following line is redundant but necessary to avoid a
- // "Use of unassigned local variable" error without actually
- // initializing 'origin' to a dummy value.
- default:
- return -1;
- }
-
- // Do the actual seek operation and return its result.
- return stream.Seek((long)offset, origin);
- }
-
- public StreamSeekDelegate SeekDelegate
- {
- get
- {
- if (stream != null && stream.CanSeek)
- {
- if (skd == null)
- {
- skd = new StreamSeekDelegate(StreamSeekImpl);
- }
- return skd;
- }
- return null;
- }
- }
-
- public int StreamPutBytesImpl(IntPtr buf, int bufsz)
- {
- if (bufsz > managedBuf.Length)
- managedBuf = new byte[bufsz];
- Marshal.Copy(buf, managedBuf, 0, bufsz);
- stream.Write(managedBuf, 0, bufsz);
- return bufsz;
- }
-
- public StreamPutBytesDelegate PutBytesDelegate
- {
- get
- {
- if (stream != null && stream.CanWrite)
- {
- if (spbd == null)
- {
- spbd = new StreamPutBytesDelegate(StreamPutBytesImpl);
- }
- return spbd;
- }
- return null;
- }
- }
-
- public void StreamCloseImpl()
- {
- stream.Dispose();
- }
-
- public StreamCloseDelegate CloseDelegate
- {
- get
- {
- if (stream != null)
- {
- if (scd == null)
- {
- scd = new StreamCloseDelegate(StreamCloseImpl);
- }
- return scd;
- }
- return null;
- }
- }
-
- public long StreamSizeImpl()
- {
- try
- {
- return stream.Length;
- }
- catch
- {
- return -1;
- }
- }
-
- public StreamSizeDelegate SizeDelegate
- {
- get
- {
- if (stream != null)
- {
- if (ssd == null)
- {
- ssd = new StreamSizeDelegate(StreamSizeImpl);
- }
- return ssd;
- }
- return null;
- }
- }
-
- }
-
- [DllImport("libc")]
- static extern int uname(IntPtr buf);
- #endregion
- }
-}
diff --git a/src/System.Drawing.Common/tests/BitmapTests.cs b/src/System.Drawing.Common/tests/BitmapTests.cs
index 6bd3895f8c..a0488f4004 100644
--- a/src/System.Drawing.Common/tests/BitmapTests.cs
+++ b/src/System.Drawing.Common/tests/BitmapTests.cs
@@ -1093,13 +1093,9 @@ namespace System.Drawing.Tests
AssertExtensions.Throws<ArgumentException>(null, () => bitmap.SetResolution(1, 1));
}
- public static IEnumerable<object[]> LockBits_TestData()
+ public static IEnumerable<object[]> LockBits_NotUnix_TestData()
{
Bitmap bitmap() => new Bitmap(2, 2, PixelFormat.Format32bppArgb);
- yield return new object[] { bitmap(), new Rectangle(0, 0, 2, 2), ImageLockMode.ReadOnly, PixelFormat.Format32bppArgb, 8, 1 };
- yield return new object[] { bitmap(), new Rectangle(0, 0, 2, 2), ImageLockMode.ReadWrite, PixelFormat.Format32bppArgb, 8, 3 };
- yield return new object[] { bitmap(), new Rectangle(0, 0, 2, 2), ImageLockMode.WriteOnly, PixelFormat.Format32bppArgb, 8, 2 };
-
yield return new object[] { bitmap(), new Rectangle(1, 1, 1,1), ImageLockMode.ReadOnly, PixelFormat.Format32bppArgb, 8, 1 };
yield return new object[] { bitmap(), new Rectangle(1, 1, 1, 1), ImageLockMode.ReadWrite, PixelFormat.Format32bppArgb, 8, 3 };
yield return new object[] { bitmap(), new Rectangle(1, 1, 1, 1), ImageLockMode.WriteOnly, PixelFormat.Format32bppArgb, 8, 2 };
@@ -1108,6 +1104,21 @@ namespace System.Drawing.Tests
yield return new object[] { bitmap(), new Rectangle(0, 0, 2, 2), ImageLockMode.WriteOnly, PixelFormat.Format16bppGrayScale, 4, 65538 };
+ yield return new object[] { new Bitmap(100, 100, PixelFormat.Format32bppRgb), new Rectangle(0, 0, 100, 100), ImageLockMode.ReadOnly, PixelFormat.Format8bppIndexed, 100, 65537 };
+ yield return new object[] { new Bitmap(100, 100, PixelFormat.Format32bppRgb), new Rectangle(0, 0, 100, 100), ImageLockMode.ReadWrite, PixelFormat.Format8bppIndexed, 100, 65539 };
+ yield return new object[] { new Bitmap(100, 100, PixelFormat.Format32bppRgb), new Rectangle(0, 0, 100, 100), ImageLockMode.WriteOnly, PixelFormat.Format8bppIndexed, 100, 65538 };
+
+ yield return new object[] { new Bitmap(100, 100, PixelFormat.Format8bppIndexed), new Rectangle(0, 0, 100, 100), ImageLockMode.ReadWrite, PixelFormat.Format24bppRgb, 300, 65539 };
+ yield return new object[] { new Bitmap(100, 100, PixelFormat.Format8bppIndexed), new Rectangle(0, 0, 100, 100), ImageLockMode.WriteOnly, PixelFormat.Format24bppRgb, 300, 65538 };
+ }
+
+ public static IEnumerable<object[]> LockBits_TestData()
+ {
+ Bitmap bitmap() => new Bitmap(2, 2, PixelFormat.Format32bppArgb);
+ yield return new object[] { bitmap(), new Rectangle(0, 0, 2, 2), ImageLockMode.ReadOnly, PixelFormat.Format32bppArgb, 8, 1 };
+ yield return new object[] { bitmap(), new Rectangle(0, 0, 2, 2), ImageLockMode.ReadWrite, PixelFormat.Format32bppArgb, 8, 3 };
+ yield return new object[] { bitmap(), new Rectangle(0, 0, 2, 2), ImageLockMode.WriteOnly, PixelFormat.Format32bppArgb, 8, 2 };
+
yield return new object[] { new Bitmap(100, 100, PixelFormat.Format32bppRgb), new Rectangle(0, 0, 100, 100), ImageLockMode.ReadOnly, PixelFormat.Format32bppRgb, 400, 1 };
yield return new object[] { new Bitmap(100, 100, PixelFormat.Format32bppRgb), new Rectangle(0, 0, 100, 100), ImageLockMode.ReadWrite, PixelFormat.Format32bppRgb, 400, 3 };
yield return new object[] { new Bitmap(100, 100, PixelFormat.Format32bppRgb), new Rectangle(0, 0, 100, 100), ImageLockMode.WriteOnly, PixelFormat.Format32bppRgb, 400, 2 };
@@ -1116,10 +1127,6 @@ namespace System.Drawing.Tests
yield return new object[] { new Bitmap(100, 100, PixelFormat.Format32bppRgb), new Rectangle(0, 0, 100, 100), ImageLockMode.ReadWrite, PixelFormat.Format24bppRgb, 300, 65539 };
yield return new object[] { new Bitmap(100, 100, PixelFormat.Format32bppRgb), new Rectangle(0, 0, 100, 100), ImageLockMode.WriteOnly, PixelFormat.Format24bppRgb, 300, 65538 };
- yield return new object[] { new Bitmap(100, 100, PixelFormat.Format32bppRgb), new Rectangle(0, 0, 100, 100), ImageLockMode.ReadOnly, PixelFormat.Format8bppIndexed, 100, 65537 };
- yield return new object[] { new Bitmap(100, 100, PixelFormat.Format32bppRgb), new Rectangle(0, 0, 100, 100), ImageLockMode.ReadWrite, PixelFormat.Format8bppIndexed, 100, 65539 };
- yield return new object[] { new Bitmap(100, 100, PixelFormat.Format32bppRgb), new Rectangle(0, 0, 100, 100), ImageLockMode.WriteOnly, PixelFormat.Format8bppIndexed, 100, 65538 };
-
yield return new object[] { new Bitmap(100, 100, PixelFormat.Format24bppRgb), new Rectangle(0, 0, 100, 100), ImageLockMode.ReadOnly, PixelFormat.Format24bppRgb, 300, 1 };
yield return new object[] { new Bitmap(100, 100, PixelFormat.Format24bppRgb), new Rectangle(0, 0, 100, 100), ImageLockMode.ReadWrite, PixelFormat.Format24bppRgb, 300, 3 };
yield return new object[] { new Bitmap(100, 100, PixelFormat.Format24bppRgb), new Rectangle(0, 0, 100, 100), ImageLockMode.WriteOnly, PixelFormat.Format24bppRgb, 300, 2 };
@@ -1129,8 +1136,6 @@ namespace System.Drawing.Tests
yield return new object[] { new Bitmap(100, 100, PixelFormat.Format24bppRgb), new Rectangle(0, 0, 100, 100), ImageLockMode.WriteOnly, PixelFormat.Format32bppRgb, 400, 65538 };
yield return new object[] { new Bitmap(100, 100, PixelFormat.Format8bppIndexed), new Rectangle(0, 0, 100, 100), ImageLockMode.ReadOnly, PixelFormat.Format24bppRgb, 300, 65537 };
- yield return new object[] { new Bitmap(100, 100, PixelFormat.Format8bppIndexed), new Rectangle(0, 0, 100, 100), ImageLockMode.ReadWrite, PixelFormat.Format24bppRgb, 300, 65539 };
- yield return new object[] { new Bitmap(100, 100, PixelFormat.Format8bppIndexed), new Rectangle(0, 0, 100, 100), ImageLockMode.WriteOnly, PixelFormat.Format24bppRgb, 300, 65538 };
yield return new object[] { new Bitmap(100, 100, PixelFormat.Format8bppIndexed), new Rectangle(0, 0, 100, 100), ImageLockMode.ReadOnly, PixelFormat.Format8bppIndexed, 100, 1 };
yield return new object[] { new Bitmap(100, 100, PixelFormat.Format8bppIndexed), new Rectangle(0, 0, 100, 100), ImageLockMode.ReadWrite, PixelFormat.Format8bppIndexed, 100, 3 };
@@ -1142,11 +1147,23 @@ namespace System.Drawing.Tests
yield return new object[] { new Bitmap(184, 184, PixelFormat.Format1bppIndexed), new Rectangle(0, 0, 184, 184), ImageLockMode.WriteOnly, PixelFormat.Format1bppIndexed, 24, 2 };
}
- [ActiveIssue(20884, TestPlatforms.AnyUnix)]
[ConditionalTheory(Helpers.GdiplusIsAvailable)]
[MemberData(nameof(LockBits_TestData))]
public void LockBits_Invoke_Success(Bitmap bitmap, Rectangle rectangle, ImageLockMode lockMode, PixelFormat pixelFormat, int expectedStride, int expectedReserved)
{
+ Do_LockBits_Invoke_Success(bitmap, rectangle, lockMode, pixelFormat, expectedStride, expectedReserved);
+ }
+
+ [ActiveIssue(20884, TestPlatforms.AnyUnix)]
+ [ConditionalTheory(Helpers.GdiplusIsAvailable)]
+ [MemberData(nameof(LockBits_NotUnix_TestData))]
+ public void LockBits_Invoke_Success_NotUnix(Bitmap bitmap, Rectangle rectangle, ImageLockMode lockMode, PixelFormat pixelFormat, int expectedStride, int expectedReserved)
+ {
+ Do_LockBits_Invoke_Success(bitmap, rectangle, lockMode, pixelFormat, expectedStride, expectedReserved);
+ }
+
+ private void Do_LockBits_Invoke_Success(Bitmap bitmap, Rectangle rectangle, ImageLockMode lockMode, PixelFormat pixelFormat, int expectedStride, int expectedReserved)
+ {
try
{
BitmapData data = bitmap.LockBits(rectangle, lockMode, pixelFormat);
@@ -1154,7 +1171,13 @@ namespace System.Drawing.Tests
Assert.Equal(rectangle.Width, data.Width);
Assert.Equal(rectangle.Height, data.Height);
Assert.Equal(expectedStride, data.Stride);
- Assert.Equal(expectedReserved, data.Reserved);
+
+ if (RuntimeInformation.IsOSPlatform(OSPlatform.Windows))
+ {
+ // "Reserved" is documented as "Reserved. Do not use.", so it's not clear whether we actually need to test this in any unit tests.
+ // Additionally, the values are not consistent accross Windows (GDI+) and Unix (libgdiplus)
+ Assert.Equal(expectedReserved, data.Reserved);
+ }
// Locking with 16bppGrayscale succeeds, but the data can't be unlocked.
if (pixelFormat == PixelFormat.Format16bppGrayScale)
diff --git a/src/System.Drawing.Common/tests/ColorTranslatorTests.cs b/src/System.Drawing.Common/tests/ColorTranslatorTests.cs
index d6f25263f3..32d5968a47 100644
--- a/src/System.Drawing.Common/tests/ColorTranslatorTests.cs
+++ b/src/System.Drawing.Common/tests/ColorTranslatorTests.cs
@@ -79,7 +79,6 @@ namespace System.Drawing.Tests
}
}
- [ActiveIssue(20884, TestPlatforms.AnyUnix)]
[Theory]
[MemberData(nameof(FromOle_TestData))]
public void FromOle_Color_ReturnsExpected(int oleColor, Color color)
@@ -107,7 +106,6 @@ namespace System.Drawing.Tests
yield return new object[] { SystemColors.ButtonShadow, unchecked((int)0x80000010) };
}
- [ActiveIssue(20884, TestPlatforms.AnyUnix)]
[Theory]
[MemberData(nameof(ToOle_TestData))]
public void ToOle_Color_ReturnsExpected(Color color, int oleColor)
@@ -189,7 +187,6 @@ namespace System.Drawing.Tests
yield return new object[] { "threedlightshadow", SystemColors.ControlLightLight };
}
- [ActiveIssue(20884, TestPlatforms.AnyUnix)]
[Theory]
[MemberData(nameof(FromHtml_TestData))]
public void FromHtml_String_ReturnsExpected(string htmlColor, Color expected)
@@ -200,7 +197,6 @@ namespace System.Drawing.Tests
}
}
- [ActiveIssue(20884, TestPlatforms.AnyUnix)]
[Theory]
[InlineData("'", typeof(Exception))]
[InlineData("'\"", typeof(Exception))]
@@ -251,7 +247,6 @@ namespace System.Drawing.Tests
yield return new object[] { SystemColors.ButtonShadow, "" };
}
- [ActiveIssue(20884, TestPlatforms.AnyUnix)]
[Theory]
[MemberData(nameof(ToHtml_TestData))]
public void ToHtml_Color_ReturnsExpected(Color color, string expected)
diff --git a/src/System.Drawing.Common/tests/Drawing2D/HatchBrushTests.cs b/src/System.Drawing.Common/tests/Drawing2D/HatchBrushTests.cs
index e1eb51602d..4aff17f43c 100644
--- a/src/System.Drawing.Common/tests/Drawing2D/HatchBrushTests.cs
+++ b/src/System.Drawing.Common/tests/Drawing2D/HatchBrushTests.cs
@@ -47,14 +47,13 @@ namespace System.Drawing.Drawing2D.Tests
Assert.Equal(backColor.ToArgb(), brush.BackgroundColor.ToArgb());
}
- [ActiveIssue(20884, TestPlatforms.AnyUnix)]
- [ConditionalTheory(Helpers.GdiplusIsAvailable)]
+ [Theory]
[InlineData(HatchStyle.Horizontal -1 )]
[InlineData(HatchStyle.SolidDiamond + 1)]
public void Ctor_InvalidHatchStyle_ThrowsArgumentException(HatchStyle hatchStyle)
{
- AssertExtensions.Throws<ArgumentException>(null, () => new HatchBrush(hatchStyle, Color.Empty));
- AssertExtensions.Throws<ArgumentException>(null, () => new HatchBrush(hatchStyle, Color.Empty, Color.Empty));
+ AssertExtensions.Throws<ArgumentException>("hatchstyle", null, () => new HatchBrush(hatchStyle, Color.Empty));
+ AssertExtensions.Throws<ArgumentException>("hatchstyle", null, () => new HatchBrush(hatchStyle, Color.Empty, Color.Empty));
}
[ConditionalFact(Helpers.GdiplusIsAvailable)]
diff --git a/src/System.Drawing.Common/tests/Drawing2D/LinearGradientBrushTests.cs b/src/System.Drawing.Common/tests/Drawing2D/LinearGradientBrushTests.cs
index 5704a80623..37f67b3933 100644
--- a/src/System.Drawing.Common/tests/Drawing2D/LinearGradientBrushTests.cs
+++ b/src/System.Drawing.Common/tests/Drawing2D/LinearGradientBrushTests.cs
@@ -236,7 +236,6 @@ namespace System.Drawing.Drawing2D.Tests
AssertExtensions.Throws<ArgumentException>(null, () => new LinearGradientBrush(new RectangleF(1, 2, 3, 0), Color.Empty, Color.Empty, 0, true));
}
- [ActiveIssue(20884, TestPlatforms.AnyUnix)]
[ConditionalTheory(Helpers.GdiplusIsAvailable)]
[InlineData(LinearGradientMode.Horizontal - 1)]
[InlineData(LinearGradientMode.BackwardDiagonal + 1)]
@@ -246,36 +245,6 @@ namespace System.Drawing.Drawing2D.Tests
Assert.ThrowsAny<ArgumentException>(() => new LinearGradientBrush(new RectangleF(1, 2, 3, 4), Color.Empty, Color.Empty, linearGradientMode));
}
- public static IEnumerable<object[]> Ctor_HatchStyle_ForeColor_BackColor_TestData()
- {
- yield return new object[] { HatchStyle.Horizontal, new Color(), new Color() };
- yield return new object[] { HatchStyle.SolidDiamond, Color.PapayaWhip, Color.Plum };
- }
-
- [ConditionalTheory(Helpers.GdiplusIsAvailable)]
- [MemberData(nameof(Ctor_HatchStyle_ForeColor_BackColor_TestData))]
- public void Ctor_HatchStyle_ForeColor_BackColor(HatchStyle hatchStyle, Color foreColor, Color backColor)
- {
- var brush = new HatchBrush(hatchStyle, foreColor, backColor);
- Assert.Equal(hatchStyle, brush.HatchStyle);
-
- Assert.NotEqual(foreColor, brush.ForegroundColor);
- Assert.Equal(foreColor.ToArgb(), brush.ForegroundColor.ToArgb());
-
- Assert.NotEqual(backColor, brush.BackgroundColor);
- Assert.Equal(backColor.ToArgb(), brush.BackgroundColor.ToArgb());
- }
-
- [ActiveIssue(20884, TestPlatforms.AnyUnix)]
- [ConditionalTheory(Helpers.GdiplusIsAvailable)]
- [InlineData(HatchStyle.Horizontal - 1)]
- [InlineData(HatchStyle.SolidDiamond + 1)]
- public void Ctor_InvalidHatchStyle_ThrowsArgumentException(HatchStyle hatchStyle)
- {
- AssertExtensions.Throws<ArgumentException>(null, () => new HatchBrush(hatchStyle, Color.Empty));
- AssertExtensions.Throws<ArgumentException>(null, () => new HatchBrush(hatchStyle, Color.Empty, Color.Empty));
- }
-
[ConditionalFact(Helpers.GdiplusIsAvailable)]
public void Clone_Brush_ReturnsClone()
{
@@ -369,7 +338,6 @@ namespace System.Drawing.Drawing2D.Tests
Assert.Throws<NullReferenceException>(() => brush.Blend = new Blend { Factors = null });
}
- [ActiveIssue(20884, TestPlatforms.AnyUnix)]
[ConditionalFact(Helpers.GdiplusIsAvailable)]
public void Blend_SetNullBlendPositions_ThrowsArgumentNullException()
{
@@ -377,7 +345,6 @@ namespace System.Drawing.Drawing2D.Tests
AssertExtensions.Throws<ArgumentNullException>("source", () => brush.Blend = new Blend { Factors = new float[2], Positions = null });
}
- [ActiveIssue(20884, TestPlatforms.AnyUnix)]
[ConditionalFact(Helpers.GdiplusIsAvailable)]
public void Blend_SetFactorsLengthGreaterThanPositionsLength_ThrowsArgumentOutOfRangeException()
{
@@ -632,12 +599,11 @@ namespace System.Drawing.Drawing2D.Tests
Assert.Equal(transform, brush.Transform);
}
- [ActiveIssue(20884, TestPlatforms.AnyUnix)]
[ConditionalFact(Helpers.GdiplusIsAvailable)]
public void Transform_SetNull_ThrowsArgumentNullException()
{
var brush = new LinearGradientBrush(new Rectangle(1, 2, 3, 4), Color.Plum, Color.Red, 45, true);
- AssertExtensions.Throws<ArgumentNullException>("matrix", () => brush.Transform = null);
+ AssertExtensions.Throws<ArgumentNullException>("value", "matrix", () => brush.Transform = null);
}
[ConditionalFact(Helpers.GdiplusIsAvailable)]
@@ -661,7 +627,6 @@ namespace System.Drawing.Drawing2D.Tests
Assert.Equal(wrapMode, brush.WrapMode);
}
- [ActiveIssue(20884, TestPlatforms.AnyUnix)]
[ConditionalTheory(Helpers.GdiplusIsAvailable)]
[InlineData(WrapMode.Tile - 1)]
[InlineData(WrapMode.Clamp + 1)]
@@ -748,25 +713,27 @@ namespace System.Drawing.Drawing2D.Tests
[ConditionalFact(Helpers.GdiplusIsAvailable)]
public void MultiplyTransform_NullMatrix_ThrowsArgumentNullException()
{
- var brush = new LinearGradientBrush(new Rectangle(1, 2, 3, 4), Color.Plum, Color.Red, 45, true);
- AssertExtensions.Throws<ArgumentNullException>("matrix", () => brush.MultiplyTransform(null));
- AssertExtensions.Throws<ArgumentNullException>("matrix", () => brush.MultiplyTransform(null, MatrixOrder.Append));
+ using (var brush = new LinearGradientBrush(new Rectangle(1, 2, 3, 4), Color.Plum, Color.Red, 45, true))
+ {
+ AssertExtensions.Throws<ArgumentNullException>("matrix", () => brush.MultiplyTransform(null));
+ AssertExtensions.Throws<ArgumentNullException>("matrix", () => brush.MultiplyTransform(null, MatrixOrder.Append));
+ }
}
- [ActiveIssue(20884, TestPlatforms.AnyUnix)]
[ConditionalFact(Helpers.GdiplusIsAvailable)]
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;
+ using (var brush = new LinearGradientBrush(new Rectangle(1, 2, 3, 4), Color.Plum, Color.Red, 45, true))
+ using (Matrix transform = brush.Transform)
+ {
+ var matrix = new Matrix();
+ matrix.Dispose();
- var matrix = new Matrix();
- matrix.Dispose();
+ brush.MultiplyTransform(matrix);
+ brush.MultiplyTransform(matrix, MatrixOrder.Append);
- brush.MultiplyTransform(matrix);
- brush.MultiplyTransform(matrix, MatrixOrder.Append);
-
- Assert.Equal(transform, brush.Transform);
+ Assert.Equal(transform, brush.Transform);
+ }
}
[ConditionalFact(Helpers.GdiplusIsAvailable)]
@@ -959,8 +926,8 @@ namespace System.Drawing.Drawing2D.Tests
public void SetSigmalBellShape_InvalidFocus_ThrowsArgumentException(float focus)
{
var brush = new LinearGradientBrush(new Rectangle(1, 2, 3, 4), Color.Plum, Color.Red, 45, true);
- AssertExtensions.Throws<ArgumentException>(null, () => brush.SetSigmaBellShape(focus));
- AssertExtensions.Throws<ArgumentException>(null, () => brush.SetSigmaBellShape(focus, 1));
+ AssertExtensions.Throws<ArgumentException>("focus", null, () => brush.SetSigmaBellShape(focus));
+ AssertExtensions.Throws<ArgumentException>("focus", null, () => brush.SetSigmaBellShape(focus, 1));
}
[ConditionalTheory(Helpers.GdiplusIsAvailable)]
@@ -971,7 +938,7 @@ namespace System.Drawing.Drawing2D.Tests
public void SetSigmalBellShape_InvalidScale_ThrowsArgumentException(float scale)
{
var brush = new LinearGradientBrush(new Rectangle(1, 2, 3, 4), Color.Plum, Color.Red, 45, true);
- AssertExtensions.Throws<ArgumentException>(null, () => brush.SetSigmaBellShape(0.1f, scale));
+ AssertExtensions.Throws<ArgumentException>("scale", null, () => brush.SetSigmaBellShape(0.1f, scale));
}
[ConditionalFact(Helpers.GdiplusIsAvailable)]
@@ -1019,8 +986,8 @@ namespace System.Drawing.Drawing2D.Tests
public void SetBlendTriangularShape_InvalidFocus_ThrowsArgumentException(float focus)
{
var brush = new LinearGradientBrush(new Rectangle(1, 2, 3, 4), Color.Plum, Color.Red, 45, true);
- AssertExtensions.Throws<ArgumentException>(null, () => brush.SetBlendTriangularShape(focus));
- AssertExtensions.Throws<ArgumentException>(null, () => brush.SetBlendTriangularShape(focus, 1));
+ AssertExtensions.Throws<ArgumentException>("focus", null, () => brush.SetBlendTriangularShape(focus));
+ AssertExtensions.Throws<ArgumentException>("focus", null, () => brush.SetBlendTriangularShape(focus, 1));
}
[ConditionalTheory(Helpers.GdiplusIsAvailable)]
@@ -1031,7 +998,7 @@ namespace System.Drawing.Drawing2D.Tests
public void SetBlendTriangularShape_InvalidScale_ThrowsArgumentException(float scale)
{
var brush = new LinearGradientBrush(new Rectangle(1, 2, 3, 4), Color.Plum, Color.Red, 45, true);
- AssertExtensions.Throws<ArgumentException>(null, () => brush.SetBlendTriangularShape(0.1f, scale));
+ AssertExtensions.Throws<ArgumentException>("scale", null, () => brush.SetBlendTriangularShape(0.1f, scale));
}
[ConditionalFact(Helpers.GdiplusIsAvailable)]
diff --git a/src/System.Drawing.Common/tests/Drawing2D/MatrixTests.cs b/src/System.Drawing.Common/tests/Drawing2D/MatrixTests.cs
index 421e8c7b19..b70be00e73 100644
--- a/src/System.Drawing.Common/tests/Drawing2D/MatrixTests.cs
+++ b/src/System.Drawing.Common/tests/Drawing2D/MatrixTests.cs
@@ -417,6 +417,16 @@ namespace System.Drawing.Drawing2D.Tests
}
[ConditionalFact(Helpers.GdiplusIsAvailable)]
+ public void Multiply_SameMatrix_ThrowsInvalidOperationException()
+ {
+ using (var matrix = new Matrix())
+ {
+ Assert.Throws<InvalidOperationException>(() => matrix.Multiply(matrix));
+ Assert.Throws<InvalidOperationException>(() => matrix.Multiply(matrix, MatrixOrder.Prepend));
+ }
+ }
+
+ [ConditionalFact(Helpers.GdiplusIsAvailable)]
public void Reset_Matrix_ReturnsExpected()
{
using (var matrix = new Matrix(1, 2, 3, 4, 5, 6))
diff --git a/src/System.Drawing.Common/tests/Drawing2D/PathGradientBrushTests.cs b/src/System.Drawing.Common/tests/Drawing2D/PathGradientBrushTests.cs
index 7edf6ea8dd..27e9e060db 100644
--- a/src/System.Drawing.Common/tests/Drawing2D/PathGradientBrushTests.cs
+++ b/src/System.Drawing.Common/tests/Drawing2D/PathGradientBrushTests.cs
@@ -92,7 +92,6 @@ namespace System.Drawing.Drawing2D.Tests
Assert.Throws<OutOfMemoryException>(() => new PathGradientBrush(new PointF[pointsLength], WrapMode.Clamp));
}
- [ActiveIssue(20884, TestPlatforms.AnyUnix)]
[ConditionalFact(Helpers.GdiplusIsAvailable)]
public void Ctor_InvalidWrapMode_ThrowsInvalidEnumArgumentException()
{
@@ -350,7 +349,6 @@ namespace System.Drawing.Drawing2D.Tests
}
}
- [ActiveIssue(20884, TestPlatforms.AnyUnix)]
[ConditionalFact(Helpers.GdiplusIsAvailable)]
public void Blend_InvalidFactorPositionsLengthMismatch_ThrowsArgumentOutOfRangeException()
{
@@ -373,7 +371,6 @@ namespace System.Drawing.Drawing2D.Tests
}
}
- [ActiveIssue(20884, TestPlatforms.AnyUnix)]
[ConditionalFact(Helpers.GdiplusIsAvailable)]
public void Blend_NullBlendProperites_ThrowsArgumentNullException()
{
@@ -485,8 +482,8 @@ namespace System.Drawing.Drawing2D.Tests
{
using (PathGradientBrush brush = new PathGradientBrush(_defaultFloatPoints))
{
- AssertExtensions.Throws<ArgumentException>(null, () => brush.SetSigmaBellShape(focus));
- AssertExtensions.Throws<ArgumentException>(null, () => brush.SetSigmaBellShape(focus, 1f));
+ AssertExtensions.Throws<ArgumentException>("focus", null, () => brush.SetSigmaBellShape(focus));
+ AssertExtensions.Throws<ArgumentException>("focus", null, () => brush.SetSigmaBellShape(focus, 1f));
}
}
@@ -497,7 +494,7 @@ namespace System.Drawing.Drawing2D.Tests
{
using (PathGradientBrush brush = new PathGradientBrush(_defaultFloatPoints))
{
- AssertExtensions.Throws<ArgumentException>(null, () => brush.SetSigmaBellShape(1f, scale));
+ AssertExtensions.Throws<ArgumentException>("scale", null, () => brush.SetSigmaBellShape(1f, scale));
}
}
@@ -583,8 +580,8 @@ namespace System.Drawing.Drawing2D.Tests
{
using (PathGradientBrush brush = new PathGradientBrush(_defaultFloatPoints))
{
- AssertExtensions.Throws<ArgumentException>(null, () => brush.SetBlendTriangularShape(focus));
- AssertExtensions.Throws<ArgumentException>(null, () => brush.SetBlendTriangularShape(focus, 1f));
+ AssertExtensions.Throws<ArgumentException>("focus", null, () => brush.SetBlendTriangularShape(focus));
+ AssertExtensions.Throws<ArgumentException>("focus", null, () => brush.SetBlendTriangularShape(focus, 1f));
}
}
@@ -595,7 +592,7 @@ namespace System.Drawing.Drawing2D.Tests
{
using (PathGradientBrush brush = new PathGradientBrush(_defaultFloatPoints))
{
- AssertExtensions.Throws<ArgumentException>(null, () => brush.SetBlendTriangularShape(1f, scale));
+ AssertExtensions.Throws<ArgumentException>("scale", null, () => brush.SetBlendTriangularShape(1f, scale));
}
}
@@ -672,7 +669,6 @@ namespace System.Drawing.Drawing2D.Tests
}
}
- [ActiveIssue(20884, TestPlatforms.AnyUnix)]
[ConditionalFact(Helpers.GdiplusIsAvailable)]
public void InterpolationColors_NullPoints_ArgumentNullException()
{
@@ -712,7 +708,6 @@ namespace System.Drawing.Drawing2D.Tests
}
}
- [ActiveIssue(20884, TestPlatforms.AnyUnix)]
[ConditionalFact(Helpers.GdiplusIsAvailable)]
public void InterpolationColors_ColorsLengthGreaterThenPointsLength_ThrowsArgumentOutOfRangeException()
{
@@ -756,13 +751,12 @@ namespace System.Drawing.Drawing2D.Tests
AssertExtensions.Throws<ArgumentException>(null, () => brush.Transform);
}
- [ActiveIssue(20884, TestPlatforms.AnyUnix)]
[ConditionalFact(Helpers.GdiplusIsAvailable)]
public void Transform_Null_ArgumentNullException()
{
using (PathGradientBrush brush = new PathGradientBrush(_defaultFloatPoints))
{
- AssertExtensions.Throws<ArgumentNullException>("matrix", () => brush.Transform = null);
+ AssertExtensions.Throws<ArgumentNullException>("value", "matrix", () => brush.Transform = null);
}
}
@@ -841,9 +835,9 @@ namespace System.Drawing.Drawing2D.Tests
}
[ConditionalFact(Helpers.GdiplusIsAvailable)]
- public void MultiplyTransform_Null_ArgumentNullException()
+ public void MultiplyTransform_NullMatrix_ThrowsArgumentNullException()
{
- using (PathGradientBrush brush = new PathGradientBrush(_defaultFloatPoints))
+ using (var brush = new PathGradientBrush(_defaultFloatPoints))
{
AssertExtensions.Throws<ArgumentNullException>("matrix", () => brush.MultiplyTransform(null));
AssertExtensions.Throws<ArgumentNullException>("matrix", () => brush.MultiplyTransform(null, MatrixOrder.Append));
@@ -851,6 +845,22 @@ namespace System.Drawing.Drawing2D.Tests
}
[ConditionalFact(Helpers.GdiplusIsAvailable)]
+ public void MultiplyTransform_DisposedMatrix_Nop()
+ {
+ using (var brush = new PathGradientBrush(_defaultFloatPoints))
+ using (Matrix transform = brush.Transform)
+ {
+ var matrix = new Matrix();
+ matrix.Dispose();
+
+ brush.MultiplyTransform(matrix);
+ brush.MultiplyTransform(matrix, MatrixOrder.Append);
+
+ Assert.Equal(transform, brush.Transform);
+ }
+ }
+
+ [ConditionalFact(Helpers.GdiplusIsAvailable)]
public void MultiplyTransform_InvalidMatrixOrder_ArgumentException()
{
using (PathGradientBrush brush = new PathGradientBrush(_defaultFloatPoints))
@@ -1059,7 +1069,6 @@ namespace System.Drawing.Drawing2D.Tests
AssertExtensions.Throws<ArgumentException>(null, () => brush.WrapMode);
}
- [ActiveIssue(20884, TestPlatforms.AnyUnix)]
[ConditionalFact(Helpers.GdiplusIsAvailable)]
public void WrapMode_Invalid_InvalidEnumArgumentException()
{
diff --git a/src/System.Drawing.Common/tests/FontFamilyTests.cs b/src/System.Drawing.Common/tests/FontFamilyTests.cs
index aeac9bf470..ad60729124 100644
--- a/src/System.Drawing.Common/tests/FontFamilyTests.cs
+++ b/src/System.Drawing.Common/tests/FontFamilyTests.cs
@@ -110,7 +110,15 @@ namespace System.Drawing.Tests
FontFamily[] families = FontFamily.Families;
FontFamily[] familiesWithGraphics = FontFamily.GetFamilies(graphics);
- Assert.Equal(families, familiesWithGraphics);
+ // FontFamily.Equals uses the native handle to determine equality. However, GDI+ does not always
+ // cache handles, so we cannot just Assert.Equal(families, familiesWithGraphics);
+ Assert.Equal(families.Length, familiesWithGraphics.Length);
+
+ for (int i = 0; i < families.Length; i++)
+ {
+ Assert.Equal(families[i].Name, familiesWithGraphics[i].Name);
+ }
+
foreach (FontFamily fontFamily in families)
{
using (FontFamily copy = new FontFamily(fontFamily.Name))
diff --git a/src/System.Drawing.Common/tests/FontTests.cs b/src/System.Drawing.Common/tests/FontTests.cs
index 65926fb7a2..e742cedcf1 100644
--- a/src/System.Drawing.Common/tests/FontTests.cs
+++ b/src/System.Drawing.Common/tests/FontTests.cs
@@ -638,7 +638,7 @@ namespace System.Drawing.Tests
};
using (Font font = Font.FromLogFont(logFont))
{
- VerifyFont(font, family.Name, 16, fontStyle, GraphicsUnit.World, charSet, expectedGdiVerticalFont: false);
+ VerifyFont(font, family.Name, font.Size, fontStyle, GraphicsUnit.World, charSet, expectedGdiVerticalFont: false);
}
}
}
diff --git a/src/System.Drawing.Common/tests/GraphicsTests.cs b/src/System.Drawing.Common/tests/GraphicsTests.cs
index 8b4347a1c3..fa8c6c7e5c 100644
--- a/src/System.Drawing.Common/tests/GraphicsTests.cs
+++ b/src/System.Drawing.Common/tests/GraphicsTests.cs
@@ -1804,6 +1804,7 @@ namespace System.Drawing.Tests
yield return new object[] { 0, 0, 0, 0, new Size(-1, -1) };
}
+ [ActiveIssue(23650)]
[ActiveIssue(20884, TestPlatforms.AnyUnix)]
[ConditionalTheory(Helpers.GdiplusIsAvailable)]
[MemberData(nameof(CopyFromScreen_TestData))]
@@ -1881,6 +1882,7 @@ namespace System.Drawing.Tests
yield return new object[] { CopyPixelOperation.CaptureBlt };
}
+ [ActiveIssue(23650)]
[ActiveIssue(20884, TestPlatforms.AnyUnix)]
[ConditionalTheory(Helpers.GdiplusIsAvailable)]
[MemberData(nameof(CopyPixelOperation_TestData))]
@@ -1895,6 +1897,7 @@ namespace System.Drawing.Tests
}
}
+ [ActiveIssue(23650)]
[ActiveIssue(20884, TestPlatforms.AnyUnix)]
[ConditionalTheory(Helpers.GdiplusIsAvailable)]
[MemberData(nameof(CopyPixelOperation_TestData))]
@@ -1909,6 +1912,7 @@ namespace System.Drawing.Tests
}
}
+ [ActiveIssue(23650)]
[ActiveIssue(20884, TestPlatforms.AnyUnix)]
[ConditionalTheory(Helpers.GdiplusIsAvailable)]
[InlineData(CopyPixelOperation.NoMirrorBitmap + 1)]
@@ -1938,6 +1942,7 @@ namespace System.Drawing.Tests
}
}
+ [ActiveIssue(23650)]
[ActiveIssue(20884, TestPlatforms.AnyUnix)]
[ConditionalFact(Helpers.GdiplusIsAvailable)]
public void CopyFromScreen_Busy_ThrowsInvalidOperationException()
@@ -1960,6 +1965,7 @@ namespace System.Drawing.Tests
}
}
+ [ActiveIssue(23650)]
[ActiveIssue(20884, TestPlatforms.AnyUnix)]
[ConditionalFact(Helpers.GdiplusIsAvailable)]
public void CopyFromScreen_Disposed_ThrowsArgumentException()
diff --git a/src/System.Drawing.Common/tests/Helpers.cs b/src/System.Drawing.Common/tests/Helpers.cs
index f63aef81f0..a1e577c41b 100644
--- a/src/System.Drawing.Common/tests/Helpers.cs
+++ b/src/System.Drawing.Common/tests/Helpers.cs
@@ -11,31 +11,85 @@ using Xunit.Sdk;
namespace System.Drawing
{
public static class Helpers
- {
+ {
public const string GdiplusIsAvailable = nameof(Helpers) + "." + nameof(GetGdiplusIsAvailable);
+ public const string RecentGdiplusIsAvailable = nameof(Helpers) + "." + nameof(GetRecentGdiPlusIsAvailable);
+ public const string RecentGdiplusIsAvailable2 = nameof(Helpers) + "." + nameof(GetRecentGdiPlusIsAvailable2);
+ public const string GdiPlusIsAvailableNotRedhat73 = nameof(Helpers) + "." + nameof(GetGdiPlusIsAvailableNotRedhat73);
+ public const string GdiPlusIsAvailableNotWindows7 = nameof(Helpers) + "." + nameof(GetGdiPlusIsAvailableNotWindows7);
public const string AnyInstalledPrinters = nameof(Helpers) + "." + nameof(IsAnyInstalledPrinters);
public static bool GetGdiplusIsAvailable()
{
if (RuntimeInformation.IsOSPlatform(OSPlatform.Windows))
{
- return PlatformDetection.IsNotWindowsNanoServer;
+ return PlatformDetection.IsNotWindowsNanoServer && PlatformDetection.IsNotWindowsServerCore;
}
else
{
- IntPtr nativeLib = dlopen("libgdiplus.so", RTLD_NOW);
- if (nativeLib == IntPtr.Zero)
+ IntPtr nativeLib;
+ if (RuntimeInformation.IsOSPlatform(OSPlatform.OSX))
{
- nativeLib = dlopen("libgdiplus.so.0", RTLD_NOW);
+ nativeLib = dlopen("libgdiplus.dylib", RTLD_NOW);
+ }
+ else
+ {
+ nativeLib = dlopen("libgdiplus.so", RTLD_NOW);
+ if (nativeLib == IntPtr.Zero)
+ {
+ nativeLib = dlopen("libgdiplus.so.0", RTLD_NOW);
+ }
}
return nativeLib != IntPtr.Zero;
}
}
+ public static bool GetRecentGdiPlusIsAvailable2()
+ {
+ // CentOS 7, RHEL 7 and Ubuntu 14.04, as well as Fedora 25 and OpenSUSE 4.22 are running outdated versions of libgdiplus
+ if (PlatformDetection.IsCentos7 || PlatformDetection.IsRedHat || PlatformDetection.IsUbuntu1404 || PlatformDetection.IsFedora || PlatformDetection.IsOpenSUSE)
+ {
+ return false;
+ }
+
+ return GetGdiplusIsAvailable();
+ }
+
+ public static bool GetGdiPlusIsAvailableNotRedhat73()
+ {
+ if (PlatformDetection.IsRedHat)
+ {
+ return false;
+ }
+
+ return GetGdiplusIsAvailable();
+ }
+
+ public static bool GetGdiPlusIsAvailableNotWindows7()
+ {
+ if (PlatformDetection.IsWindows7)
+ {
+ return false;
+ }
+
+ return GetGdiplusIsAvailable();
+ }
+
+ public static bool GetRecentGdiPlusIsAvailable()
+ {
+ // CentOS 7, RHEL 7 and Ubuntu 14.04 are running outdated versions of libgdiplus
+ if (PlatformDetection.IsCentos7 || PlatformDetection.IsRedHat || PlatformDetection.IsUbuntu1404)
+ {
+ return false;
+ }
+
+ return GetGdiplusIsAvailable();
+ }
+
public static bool IsAnyInstalledPrinters()
{
- return PrinterSettings.InstalledPrinters.Count == 0;
+ return PrinterSettings.InstalledPrinters.Count > 0;
}
[DllImport("libdl")]
diff --git a/src/System.Drawing.Common/tests/IconTests.cs b/src/System.Drawing.Common/tests/IconTests.cs
index d8aa36fbf4..cad6da5ce4 100644
--- a/src/System.Drawing.Common/tests/IconTests.cs
+++ b/src/System.Drawing.Common/tests/IconTests.cs
@@ -143,7 +143,6 @@ namespace System.Drawing.Tests
}
}
- [ActiveIssue(20884, TestPlatforms.AnyUnix)]
[ConditionalFact(Helpers.GdiplusIsAvailable)]
public void Ctor_NullStream_ThrowsArgumentNullException()
{
@@ -240,7 +239,6 @@ namespace System.Drawing.Tests
}
}
- [ActiveIssue(20884, TestPlatforms.AnyUnix)]
[ConditionalFact(Helpers.GdiplusIsAvailable)]
public void Ctor_NullIcon_ThrowsArgumentNullException()
{
@@ -248,7 +246,8 @@ namespace System.Drawing.Tests
AssertExtensions.Throws<ArgumentNullException, ArgumentException>("original", null, () => new Icon((Icon)null, new Size(32, 32)));
}
- [ActiveIssue(20884, TestPlatforms.AnyUnix)]
+ // libgdiplus causes a segfault when given an invalid Icon handle.
+ [PlatformSpecific(TestPlatforms.Windows)]
[ConditionalFact(Helpers.GdiplusIsAvailable)]
public void Ctor_InvalidHandle_Success()
{
@@ -284,7 +283,6 @@ namespace System.Drawing.Tests
Assert.Throws<NullReferenceException>(() => new Icon(null, "48x48_multiple_entries_4bit.ico"));
}
- [ActiveIssue(20884, TestPlatforms.AnyUnix)]
[ConditionalTheory(Helpers.GdiplusIsAvailable)]
[InlineData(typeof(Icon), null)]
[InlineData(typeof(Icon), "")]
@@ -323,13 +321,11 @@ namespace System.Drawing.Tests
}
}
- [ActiveIssue(20884, TestPlatforms.AnyUnix)]
[ConditionalFact(Helpers.GdiplusIsAvailable)]
public void Dispose_IconData_DestroysHandle()
{
var icon = new Icon(Helpers.GetTestBitmapPath("48x48_multiple_entries_4bit.ico"));
icon.Dispose();
-
Assert.Throws<ObjectDisposedException>(() => icon.Handle);
}
@@ -395,7 +391,6 @@ namespace System.Drawing.Tests
Assert.Null(Icon.ExtractAssociatedIcon("http://microsoft.com"));
}
- [ActiveIssue(20884, TestPlatforms.AnyUnix)]
[ConditionalFact(Helpers.GdiplusIsAvailable)]
public void ExtractAssociatedIcon_NullFilePath_ThrowsArgumentNullException()
{
@@ -550,7 +545,6 @@ namespace System.Drawing.Tests
}
}
- [ActiveIssue(20884, TestPlatforms.AnyUnix)]
[ConditionalFact(Helpers.GdiplusIsAvailable)]
public void ToBitmap_BitmapIconFromHandle_ReturnsExpected()
{
@@ -731,7 +725,6 @@ namespace System.Drawing.Tests
AssertExtensions.Throws<ArgumentException>(null, () => Icon.FromHandle(IntPtr.Zero));
}
- [ActiveIssue(20884, TestPlatforms.AnyUnix)]
[ConditionalFact(Helpers.GdiplusIsAvailable)]
public void Size_GetWhenDisposed_ThrowsObjectDisposedException()
{
diff --git a/src/System.Drawing.Common/tests/Imaging/ImageAttributesTests.cs b/src/System.Drawing.Common/tests/Imaging/ImageAttributesTests.cs
index 9b66ee8dfe..76fd78966b 100644
--- a/src/System.Drawing.Common/tests/Imaging/ImageAttributesTests.cs
+++ b/src/System.Drawing.Common/tests/Imaging/ImageAttributesTests.cs
@@ -31,8 +31,6 @@ using Xunit;
namespace System.Drawing.Imaging.Tests
{
- // Disposing any ImageAttributes seems to cause a crash on Unix.
- [ActiveIssue(20884, TestPlatforms.AnyUnix)]
public class ImageAttributesTests
{
private readonly Rectangle _rectangle = new Rectangle(0, 0, 64, 64);
@@ -69,6 +67,7 @@ namespace System.Drawing.Imaging.Tests
imageAttr.Dispose();
}
+ [ActiveIssue(20884, TestPlatforms.AnyUnix)] // Causes a crash on libgdiplus.
[ConditionalFact(Helpers.GdiplusIsAvailable)]
public void Clone_Success()
{
@@ -521,6 +520,7 @@ namespace System.Drawing.Imaging.Tests
}
}
+ [ActiveIssue(20884, TestPlatforms.AnyUnix)]
[ConditionalFact(Helpers.GdiplusIsAvailable)]
public void SetThreshold_Threshold_Success()
{
@@ -535,6 +535,7 @@ namespace System.Drawing.Imaging.Tests
}
}
+ [ActiveIssue(20884, TestPlatforms.AnyUnix)]
[ConditionalTheory(Helpers.GdiplusIsAvailable)]
[MemberData(nameof(ColorAdjustType_TestData))]
public void SetThreshold_ThresholdType_Success(ColorAdjustType type)
@@ -550,7 +551,7 @@ namespace System.Drawing.Imaging.Tests
}
}
- [ConditionalTheory(Helpers.GdiplusIsAvailable)]
+ [ActiveIssue(20884, TestPlatforms.AnyUnix)]
[MemberData(nameof(ColorAdjustTypeI_TestData))]
public void SetThreshold_ThresholdTypeI_Success(ColorAdjustType type)
{
@@ -565,6 +566,7 @@ namespace System.Drawing.Imaging.Tests
}
}
+ [ActiveIssue(20884, TestPlatforms.AnyUnix)]
[ConditionalFact(Helpers.GdiplusIsAvailable)]
public void SetThreshold_Disposed_ThrowsArgumentException()
{
@@ -574,6 +576,7 @@ namespace System.Drawing.Imaging.Tests
AssertExtensions.Throws<ArgumentException>(null, () => imageAttr.SetThreshold(0.5f));
}
+ [ActiveIssue(20884, TestPlatforms.AnyUnix)]
[ConditionalTheory(Helpers.GdiplusIsAvailable)]
[MemberData(nameof(ColorAdjustType_InvalidTypes_TestData))]
public void SetThreshold_InvalidType_ThrowsArgumentException(ColorAdjustType type)
@@ -598,6 +601,7 @@ namespace System.Drawing.Imaging.Tests
}
}
+ [ActiveIssue(20884, TestPlatforms.AnyUnix)]
[ConditionalTheory(Helpers.GdiplusIsAvailable)]
[MemberData(nameof(ColorAdjustType_AllTypesAllowed_TestData))]
public void ClearThreshold_ThresholdTypeI_Success(ColorAdjustType type)
@@ -614,6 +618,7 @@ namespace System.Drawing.Imaging.Tests
}
}
+ [ActiveIssue(20884, TestPlatforms.AnyUnix)]
[ConditionalFact(Helpers.GdiplusIsAvailable)]
public void ClearThreshold_Disposed_ThrowsArgumentException()
{
@@ -623,6 +628,7 @@ namespace System.Drawing.Imaging.Tests
AssertExtensions.Throws<ArgumentException>(null, () => imageAttr.ClearThreshold(ColorAdjustType.Default));
}
+ [ActiveIssue(20884, TestPlatforms.AnyUnix)]
[ConditionalTheory(Helpers.GdiplusIsAvailable)]
[MemberData(nameof(ColorAdjustType_InvalidTypes_TestData))]
public void ClearThreshold_InvalidTypes_ThrowsArgumentException(ColorAdjustType type)
@@ -633,6 +639,7 @@ namespace System.Drawing.Imaging.Tests
}
}
+ [ActiveIssue(20884, TestPlatforms.AnyUnix)]
[ConditionalFact(Helpers.GdiplusIsAvailable)]
public void SetGamma_Gamma_Success()
{
@@ -647,6 +654,7 @@ namespace System.Drawing.Imaging.Tests
}
}
+ [ActiveIssue(20884, TestPlatforms.AnyUnix)]
[ConditionalTheory(Helpers.GdiplusIsAvailable)]
[MemberData(nameof(ColorAdjustType_TestData))]
public void SetGamma_GammaType_Success(ColorAdjustType type)
@@ -662,6 +670,7 @@ namespace System.Drawing.Imaging.Tests
}
}
+ [ActiveIssue(20884, TestPlatforms.AnyUnix)]
[ConditionalTheory(Helpers.GdiplusIsAvailable)]
[MemberData(nameof(ColorAdjustTypeI_TestData))]
public void SetGamma_GammaTypeI_Success(ColorAdjustType type)
@@ -733,6 +742,7 @@ namespace System.Drawing.Imaging.Tests
}
}
+ [ActiveIssue(20884, TestPlatforms.AnyUnix)]
[ConditionalFact(Helpers.GdiplusIsAvailable)]
public void SetNoOp_Success()
{
@@ -749,6 +759,7 @@ namespace System.Drawing.Imaging.Tests
}
}
+ [ActiveIssue(20884, TestPlatforms.AnyUnix)]
[ConditionalTheory(Helpers.GdiplusIsAvailable)]
[MemberData(nameof(ColorAdjustType_AllTypesAllowed_TestData))]
public void SetNoOp_Type_Success(ColorAdjustType type)
@@ -805,6 +816,7 @@ namespace System.Drawing.Imaging.Tests
}
}
+ [ActiveIssue(20884, TestPlatforms.AnyUnix)]
[ConditionalTheory(Helpers.GdiplusIsAvailable)]
[MemberData(nameof(ColorAdjustType_TestData))]
public void ClearNoOp_Type_Success(ColorAdjustType type)
@@ -843,6 +855,7 @@ namespace System.Drawing.Imaging.Tests
}
}
+ [ActiveIssue(20884, TestPlatforms.AnyUnix)]
[ConditionalFact(Helpers.GdiplusIsAvailable)]
public void ClearNoOp_Disposed_ThrowsArgumentException()
{
@@ -995,6 +1008,7 @@ namespace System.Drawing.Imaging.Tests
yield return new object[] { ColorChannelFlag.ColorChannelY, Color.FromArgb(255, 100, 100, 100), Color.FromArgb(255, 207, 207, 207) };
}
+ [ActiveIssue(20884, TestPlatforms.AnyUnix)]
[ConditionalTheory(Helpers.GdiplusIsAvailable)]
[MemberData(nameof(SetOutputChannel_ColorChannelFlag_TestData))]
public void SetOutputChannel_Flag_Success(ColorChannelFlag flag, Color actualColor, Color expectedColor)
@@ -1023,6 +1037,7 @@ namespace System.Drawing.Imaging.Tests
yield return new object[] { ColorChannelFlag.ColorChannelY, ColorAdjustType.Bitmap, Color.FromArgb(255, 100, 100, 100), Color.FromArgb(255, 207, 207, 207) };
}
+ [ActiveIssue(20884, TestPlatforms.AnyUnix)]
[ConditionalTheory(Helpers.GdiplusIsAvailable)]
[MemberData(nameof(SetOutputChannel_ColorChannelFlagType_TestData))]
public void SetOutputChannel_FlagType_Success(ColorChannelFlag flag, ColorAdjustType type, Color actualColor, Color expectedColor)
@@ -1055,6 +1070,7 @@ namespace System.Drawing.Imaging.Tests
yield return new object[] { ColorChannelFlag.ColorChannelY, ColorAdjustType.Text, Color.FromArgb(255, 100, 100, 100) };
}
+ [ActiveIssue(20884, TestPlatforms.AnyUnix)]
[ConditionalTheory(Helpers.GdiplusIsAvailable)]
[MemberData(nameof(SetOutputChannel_ColorChannelFlagTypeI_TestData))]
public void SetOutputChannel_FlagTypeI_Success(ColorChannelFlag flag, ColorAdjustType type, Color color)
@@ -1071,6 +1087,7 @@ namespace System.Drawing.Imaging.Tests
}
}
+ [ActiveIssue(20884, TestPlatforms.AnyUnix)]
[ConditionalFact(Helpers.GdiplusIsAvailable)]
public void SetOutputChannel_Disposed_ThrowsArgumentException()
{
@@ -1081,6 +1098,7 @@ namespace System.Drawing.Imaging.Tests
AssertExtensions.Throws<ArgumentException>(null, () => imageAttr.SetOutputChannel(ColorChannelFlag.ColorChannelY, ColorAdjustType.Default));
}
+ [ActiveIssue(20884, TestPlatforms.AnyUnix)]
[ConditionalTheory(Helpers.GdiplusIsAvailable)]
[MemberData(nameof(ColorAdjustType_InvalidTypes_TestData))]
public void SetOutputChannel_InvalidTypes_ThrowsArgumentException(ColorAdjustType type)
@@ -1100,6 +1118,7 @@ namespace System.Drawing.Imaging.Tests
yield return new object[] { (ColorChannelFlag)int.MaxValue };
}
+ [ActiveIssue(20884, TestPlatforms.AnyUnix)]
[ConditionalTheory(Helpers.GdiplusIsAvailable)]
[MemberData(nameof(SetOutputChannel_InvalidColorChannelFlags_TestData))]
public void SetOutputChannel_InvalidFlags_ThrowsArgumentException(ColorChannelFlag flag)
@@ -1111,6 +1130,7 @@ namespace System.Drawing.Imaging.Tests
}
}
+ [ActiveIssue(20884, TestPlatforms.AnyUnix)]
[ConditionalFact(Helpers.GdiplusIsAvailable)]
public void ClearOutputChannel_Success()
{
@@ -1127,6 +1147,7 @@ namespace System.Drawing.Imaging.Tests
}
}
+ [ActiveIssue(20884, TestPlatforms.AnyUnix)]
[ConditionalTheory(Helpers.GdiplusIsAvailable)]
[MemberData(nameof(ColorAdjustType_AllTypesAllowed_TestData))]
public void ClearOutputChannel_Type_Success(ColorAdjustType type)
@@ -1144,6 +1165,7 @@ namespace System.Drawing.Imaging.Tests
}
}
+ [ActiveIssue(20884, TestPlatforms.AnyUnix)]
[ConditionalFact(Helpers.GdiplusIsAvailable)]
public void ClearOutputChannel_Disposed_ThrowsArgumentException()
{
@@ -1154,6 +1176,7 @@ namespace System.Drawing.Imaging.Tests
AssertExtensions.Throws<ArgumentException>(null, () => imageAttr.ClearOutputChannel(ColorAdjustType.Default));
}
+ [ActiveIssue(20884, TestPlatforms.AnyUnix)]
[ConditionalTheory(Helpers.GdiplusIsAvailable)]
[MemberData(nameof(ColorAdjustType_InvalidTypes_TestData))]
public void ClearOutputChannel_InvalidTypes_ThrowsArgumentException(ColorAdjustType type)
@@ -1164,6 +1187,7 @@ namespace System.Drawing.Imaging.Tests
}
}
+ [ActiveIssue(20884, TestPlatforms.AnyUnix)]
[ConditionalFact(Helpers.GdiplusIsAvailable)]
public void SetOutputChannelColorProfile_Name_Success()
{
@@ -1179,6 +1203,7 @@ namespace System.Drawing.Imaging.Tests
}
}
+ [ActiveIssue(20884, TestPlatforms.AnyUnix)]
[ConditionalFact(Helpers.GdiplusIsAvailable)]
public void SetOutputChannelColorProfile_Disposed_ThrowsArgumentException()
{
@@ -1212,6 +1237,7 @@ namespace System.Drawing.Imaging.Tests
}
}
+ [ActiveIssue(20884, TestPlatforms.AnyUnix)]
[ConditionalFact(Helpers.GdiplusIsAvailable)]
public void SetOutputChannelColorProfile_InvalidPath_ThrowsOutOfMemoryException()
{
@@ -1222,6 +1248,7 @@ namespace System.Drawing.Imaging.Tests
}
}
+ [ActiveIssue(20884, TestPlatforms.AnyUnix)]
[ConditionalFact(Helpers.GdiplusIsAvailable)]
public void SetOutputChannelColorProfile_InvalidPath_ThrowsPathTooLongException()
{
@@ -1233,7 +1260,7 @@ namespace System.Drawing.Imaging.Tests
}
}
-
+ [ActiveIssue(20884, TestPlatforms.AnyUnix)]
[ConditionalTheory(Helpers.GdiplusIsAvailable)]
[MemberData(nameof(ColorAdjustType_InvalidTypes_TestData))]
public void SetOutputChannelColorProfile_InvalidTypes_ThrowsArgumentException(ColorAdjustType type)
@@ -1244,6 +1271,7 @@ namespace System.Drawing.Imaging.Tests
}
}
+ [ActiveIssue(20884, TestPlatforms.AnyUnix)]
[ConditionalFact(Helpers.GdiplusIsAvailable)]
public void ClearOutputChannelColorProfile_Success()
{
@@ -1261,6 +1289,7 @@ namespace System.Drawing.Imaging.Tests
}
}
+ [ActiveIssue(20884, TestPlatforms.AnyUnix)]
[ConditionalTheory(Helpers.GdiplusIsAvailable)]
[MemberData(nameof(ColorAdjustType_AllTypesAllowed_TestData))]
public void ClearOutputChannelColorProfile_Type_Success(ColorAdjustType type)
@@ -1279,6 +1308,7 @@ namespace System.Drawing.Imaging.Tests
}
}
+ [ActiveIssue(20884, TestPlatforms.AnyUnix)]
[ConditionalFact(Helpers.GdiplusIsAvailable)]
public void ClearOutputChannelColorProfile_Disposed_ThrowsArgumentException()
{
@@ -1289,6 +1319,7 @@ namespace System.Drawing.Imaging.Tests
AssertExtensions.Throws<ArgumentException>(null, () => imageAttr.ClearOutputChannelColorProfile(ColorAdjustType.Default));
}
+ [ActiveIssue(20884, TestPlatforms.AnyUnix)]
[ConditionalTheory(Helpers.GdiplusIsAvailable)]
[MemberData(nameof(ColorAdjustType_InvalidTypes_TestData))]
public void ClearOutputChannelColorProfile_InvalidTypes_ThrowsArgumentException(ColorAdjustType type)
@@ -1381,6 +1412,7 @@ namespace System.Drawing.Imaging.Tests
}
}
+ [ActiveIssue(20884, TestPlatforms.AnyUnix)]
[ConditionalFact(Helpers.GdiplusIsAvailable)]
public void SetRemapTable_EmptyMap_ThrowsArgumentException()
{
@@ -1390,6 +1422,7 @@ namespace System.Drawing.Imaging.Tests
}
}
+ [ActiveIssue(20884, TestPlatforms.AnyUnix)]
[ConditionalFact(Helpers.GdiplusIsAvailable)]
public void ClearRemapTable_Success()
{
@@ -1405,6 +1438,7 @@ namespace System.Drawing.Imaging.Tests
}
}
+ [ActiveIssue(20884, TestPlatforms.AnyUnix)]
[ConditionalTheory(Helpers.GdiplusIsAvailable)]
[MemberData(nameof(ColorAdjustType_AllTypesAllowed_TestData))]
public void ClearRemapTable_Type_Success(ColorAdjustType type)
@@ -1452,6 +1486,7 @@ namespace System.Drawing.Imaging.Tests
AssertExtensions.Throws<ArgumentException>(null, () => imageAttr.SetWrapMode(WrapMode.Clamp, Color.Black, true));
}
+ [ActiveIssue(20884, TestPlatforms.AnyUnix)]
[ConditionalFact(Helpers.GdiplusIsAvailable)]
public void GetAdjustedPalette_Disposed_ThrowsArgumentException()
{
@@ -1473,6 +1508,7 @@ namespace System.Drawing.Imaging.Tests
}
}
+ [ActiveIssue(20884, TestPlatforms.AnyUnix)]
[ConditionalTheory(Helpers.GdiplusIsAvailable)]
[MemberData(nameof(ColorAdjustType_InvalidTypes_TestData))]
public void GetAdjustedPalette_Disposed_ThrowsArgumentException(ColorAdjustType type)
diff --git a/src/System.Drawing.Common/tests/Imaging/MetafileTests.cs b/src/System.Drawing.Common/tests/Imaging/MetafileTests.cs
index 919b90cb01..443a4df835 100644
--- a/src/System.Drawing.Common/tests/Imaging/MetafileTests.cs
+++ b/src/System.Drawing.Common/tests/Imaging/MetafileTests.cs
@@ -37,7 +37,6 @@ namespace System.Drawing.Imaging.Tests
private readonly Rectangle _rectangle = new Rectangle(0, 0, 64, 64);
private readonly RectangleF _rectangleF = new RectangleF(0, 0, 64, 64);
- [ActiveIssue(20884, TestPlatforms.AnyUnix)]
[ConditionalFact(Helpers.GdiplusIsAvailable)]
public void Ctor_IntPtrZero_ThrowsArgumentException()
{
@@ -64,21 +63,18 @@ namespace System.Drawing.Imaging.Tests
}
}
- [ActiveIssue(20884, TestPlatforms.AnyUnix)]
[ConditionalFact(Helpers.GdiplusIsAvailable)]
public void Ctor_Bitmap_ThrowsExternalException()
{
Assert.Throws<ExternalException>(() => new Metafile(GetPath(BmpFile)));
}
- [ActiveIssue(20884, TestPlatforms.AnyUnix)]
[ConditionalFact(Helpers.GdiplusIsAvailable)]
public void Ctor_NullString_ThrowsArgumentNullException()
{
AssertExtensions.Throws<ArgumentNullException>("path", () => new Metafile((string)null));
}
- [ActiveIssue(20884, TestPlatforms.AnyUnix)]
[ConditionalFact(Helpers.GdiplusIsAvailable)]
public void Ctor_InvalidPath_ThrowsExternalException()
{
@@ -112,7 +108,6 @@ namespace System.Drawing.Imaging.Tests
}
}
- [ActiveIssue(20884, TestPlatforms.AnyUnix)]
[ConditionalFact(Helpers.GdiplusIsAvailable)]
public void Ctor_NullStream_ThrowsArgumentException()
{
@@ -136,13 +131,13 @@ namespace System.Drawing.Imaging.Tests
yield return new object[] { EmfType.EmfPlusOnly };
}
- [ActiveIssue(20884, TestPlatforms.AnyUnix)]
[ConditionalTheory(Helpers.GdiplusIsAvailable)]
[MemberData(nameof(EmfType_TestData))]
public void Ctor_IntPtrEmfType_Success(EmfType emfType)
{
- using (var bufferGraphics = Graphics.FromHwndInternal(IntPtr.Zero))
- using (var metafile = new Metafile(bufferGraphics.GetHdc(), emfType))
+ using (Bitmap bmp = new Bitmap(10, 10, PixelFormat.Format32bppArgb))
+ using (Graphics g = Graphics.FromImage(bmp))
+ using (var metafile = new Metafile(g.GetHdc(), emfType))
{
AssertMetafileIsBlank(metafile);
AssertEmfType(metafile.GetMetafileHeader(), emfType);
@@ -157,14 +152,14 @@ namespace System.Drawing.Imaging.Tests
yield return new object[] { (EmfType)int.MinValue };
}
- [ActiveIssue(20884, TestPlatforms.AnyUnix)]
[ConditionalTheory(Helpers.GdiplusIsAvailable)]
[MemberData(nameof(EmfType_Invalid_TestData))]
public void Ctor_IntPtrInvalidEmfType_ThrowsArgumentException(EmfType emfType)
{
- using (var bufferGraphics = Graphics.FromHwndInternal(IntPtr.Zero))
+ using (Bitmap bmp = new Bitmap(10, 10, PixelFormat.Format32bppArgb))
+ using (Graphics g = Graphics.FromImage(bmp))
{
- AssertExtensions.Throws<ArgumentException>(null, () => new Metafile(bufferGraphics.GetHdc(), emfType));
+ AssertExtensions.Throws<ArgumentException>(null, () => new Metafile(g.GetHdc(), emfType));
}
}
@@ -175,7 +170,6 @@ namespace System.Drawing.Imaging.Tests
AssertExtensions.Throws<ArgumentException>(null, () => new Metafile((IntPtr)null, EmfType.EmfOnly));
}
- [ActiveIssue(20884, TestPlatforms.AnyUnix)]
[ConditionalFact(Helpers.GdiplusIsAvailable)]
public void Ctor_ZeroPointerEmfType_ThrowsArgumentException()
{
@@ -188,13 +182,13 @@ namespace System.Drawing.Imaging.Tests
yield return new object[] { "description" };
}
- [ActiveIssue(20884, TestPlatforms.AnyUnix)]
[ConditionalTheory(Helpers.GdiplusIsAvailable)]
[MemberData(nameof(Description_TestData))]
public void Ctor_IntPtrEmfTypeString_Success(string description)
{
- using (var bufferGraphics = Graphics.FromHwndInternal(IntPtr.Zero))
- using (var metafile = new Metafile(bufferGraphics.GetHdc(), EmfType.EmfOnly, description))
+ using (Bitmap bmp = new Bitmap(10, 10, PixelFormat.Format32bppArgb))
+ using (Graphics g = Graphics.FromImage(bmp))
+ using (var metafile = new Metafile(g.GetHdc(), EmfType.EmfOnly, description))
{
AssertMetafileIsBlank(metafile);
}
@@ -208,12 +202,12 @@ namespace System.Drawing.Imaging.Tests
AssertExtensions.Throws<ArgumentException>(null, () => new Metafile(IntPtr.Zero, EmfType.EmfOnly, description));
}
- [ActiveIssue(20884, TestPlatforms.AnyUnix)]
[ConditionalFact(Helpers.GdiplusIsAvailable)]
public void Ctor_IntPtrRectangleF_Success()
{
- using (var bufferGraphics = Graphics.FromHwndInternal(IntPtr.Zero))
- using (var metafile = new Metafile(bufferGraphics.GetHdc(), _rectangleF))
+ using (Bitmap bmp = new Bitmap(10, 10, PixelFormat.Format32bppArgb))
+ using (Graphics g = Graphics.FromImage(bmp))
+ using (var metafile = new Metafile(g.GetHdc(), _rectangleF))
{
AssertMetafileIsBlank(metafile);
}
@@ -229,92 +223,91 @@ namespace System.Drawing.Imaging.Tests
yield return new object[] { MetafileFrameUnit.GdiCompatible };
}
- [ActiveIssue(20884, TestPlatforms.AnyUnix)]
[ConditionalTheory(Helpers.GdiplusIsAvailable)]
[MemberData(nameof(MetafileFrameUnit_TestData))]
public void Ctor_IntPtrRectangleFMetafileFrameUnit_Success(MetafileFrameUnit frameUnit)
{
- using (var bufferGraphics = Graphics.FromHwndInternal(IntPtr.Zero))
- using (var metafile = new Metafile(bufferGraphics.GetHdc(), _rectangleF, frameUnit))
+ using (Bitmap bmp = new Bitmap(10, 10, PixelFormat.Format32bppArgb))
+ using (Graphics g = Graphics.FromImage(bmp))
+ using (var metafile = new Metafile(g.GetHdc(), _rectangleF, frameUnit))
{
AssertMetafileIsBlank(metafile);
}
}
- [ActiveIssue(20884, TestPlatforms.AnyUnix)]
[ConditionalTheory(Helpers.GdiplusIsAvailable)]
[MemberData(nameof(EmfType_TestData))]
public void Ctor_IntPtrRectangleFMetafileFrameUnitEmfType_Success(EmfType emfType)
{
- using (var bufferGraphics = Graphics.FromHwndInternal(IntPtr.Zero))
- using (var metafile = new Metafile(bufferGraphics.GetHdc(), _rectangleF, MetafileFrameUnit.Pixel, emfType))
+ using (Bitmap bmp = new Bitmap(10, 10, PixelFormat.Format32bppArgb))
+ using (Graphics g = Graphics.FromImage(bmp))
+ using (var metafile = new Metafile(g.GetHdc(), _rectangleF, MetafileFrameUnit.Pixel, emfType))
{
AssertMetafileIsBlank(metafile);
AssertEmfType(metafile.GetMetafileHeader(), emfType);
}
}
- [ActiveIssue(20884, TestPlatforms.AnyUnix)]
[ConditionalTheory(Helpers.GdiplusIsAvailable)]
[MemberData(nameof(Description_TestData))]
public void Ctor_IntPtrRectangleFMetafileFrameUnitEmfTypeString_Success(string description)
{
- using (var bufferGraphics = Graphics.FromHwndInternal(IntPtr.Zero))
- using (var metafile = new Metafile(bufferGraphics.GetHdc(), _rectangleF, MetafileFrameUnit.Pixel, EmfType.EmfOnly, description))
+ using (Bitmap bmp = new Bitmap(10, 10, PixelFormat.Format32bppArgb))
+ using (Graphics g = Graphics.FromImage(bmp))
+ using (var metafile = new Metafile(g.GetHdc(), _rectangleF, MetafileFrameUnit.Pixel, EmfType.EmfOnly, description))
{
AssertMetafileIsBlank(metafile);
}
}
- [ActiveIssue(20884, TestPlatforms.AnyUnix)]
[ConditionalFact(Helpers.GdiplusIsAvailable)]
public void Ctor_IntPtrRectangle_Success()
{
- using (var bufferGraphics = Graphics.FromHwndInternal(IntPtr.Zero))
- using (var metafile = new Metafile(bufferGraphics.GetHdc(), _rectangle))
+ using (Bitmap bmp = new Bitmap(10, 10, PixelFormat.Format32bppArgb))
+ using (Graphics g = Graphics.FromImage(bmp))
+ using (var metafile = new Metafile(g.GetHdc(), _rectangle))
{
AssertMetafileIsBlank(metafile);
}
}
- [ActiveIssue(20884, TestPlatforms.AnyUnix)]
[ConditionalTheory(Helpers.GdiplusIsAvailable)]
[MemberData(nameof(MetafileFrameUnit_TestData))]
public void Ctor_IntPtrRectangleMetafileFrameUnit_Success(MetafileFrameUnit frameUnit)
{
- using (var bufferGraphics = Graphics.FromHwndInternal(IntPtr.Zero))
- using (var metafile = new Metafile(bufferGraphics.GetHdc(), _rectangle, frameUnit))
+ using (Bitmap bmp = new Bitmap(10, 10, PixelFormat.Format32bppArgb))
+ using (Graphics g = Graphics.FromImage(bmp))
+ using (var metafile = new Metafile(g.GetHdc(), _rectangle, frameUnit))
{
AssertMetafileIsBlank(metafile);
}
}
- [ActiveIssue(20884, TestPlatforms.AnyUnix)]
[ConditionalTheory(Helpers.GdiplusIsAvailable)]
[MemberData(nameof(EmfType_TestData))]
public void Ctor_IntPtrRectangleMetafileFrameUnitEmfType_Success(EmfType emfType)
{
- using (var bufferGraphics = Graphics.FromHwndInternal(IntPtr.Zero))
- using (var metafile = new Metafile(bufferGraphics.GetHdc(), _rectangle, MetafileFrameUnit.Pixel, emfType))
+ using (Bitmap bmp = new Bitmap(10, 10, PixelFormat.Format32bppArgb))
+ using (Graphics g = Graphics.FromImage(bmp))
+ using (var metafile = new Metafile(g.GetHdc(), _rectangle, MetafileFrameUnit.Pixel, emfType))
{
AssertMetafileIsBlank(metafile);
AssertEmfType(metafile.GetMetafileHeader(), emfType);
}
}
- [ActiveIssue(20884, TestPlatforms.AnyUnix)]
[ConditionalTheory(Helpers.GdiplusIsAvailable)]
[MemberData(nameof(Description_TestData))]
public void Ctor_IntPtrRectangleMetafileFrameUnitEmfTypeString_Success(string description)
{
- using (var bufferGraphics = Graphics.FromHwndInternal(IntPtr.Zero))
- using (var metafile = new Metafile(bufferGraphics.GetHdc(), _rectangle, MetafileFrameUnit.Pixel, EmfType.EmfOnly, description))
+ using (Bitmap bmp = new Bitmap(10, 10, PixelFormat.Format32bppArgb))
+ using (Graphics g = Graphics.FromImage(bmp))
+ using (var metafile = new Metafile(g.GetHdc(), _rectangle, MetafileFrameUnit.Pixel, EmfType.EmfOnly, description))
{
AssertMetafileIsBlank(metafile);
}
}
- [ActiveIssue(20884, TestPlatforms.AnyUnix)]
[ConditionalFact(Helpers.GdiplusIsAvailable)]
public void Ctor_IntPtrZeroI_ThrowsArgumentException()
{
@@ -341,14 +334,14 @@ namespace System.Drawing.Imaging.Tests
yield return new object[] { (MetafileFrameUnit)int.MinValue };
}
- [ActiveIssue(20884, TestPlatforms.AnyUnix)]
[ConditionalTheory(Helpers.GdiplusIsAvailable)]
[MemberData(nameof(MetafileFrameUnit_Invalid_TestData))]
public void Ctor_InvalidMetafileFrameUnit_ThrowsArgumentException(MetafileFrameUnit farameUnit)
{
- using (var bufferGraphics = Graphics.FromHwndInternal(IntPtr.Zero))
+ using (Bitmap bmp = new Bitmap(10, 10, PixelFormat.Format32bppArgb))
+ using (Graphics g = Graphics.FromImage(bmp))
{
- IntPtr referenceHdc = bufferGraphics.GetHdc();
+ IntPtr referenceHdc = g.GetHdc();
AssertExtensions.Throws<ArgumentException>(null, () => new Metafile(referenceHdc, _rectangleF, farameUnit));
AssertExtensions.Throws<ArgumentException>(null, () => new Metafile(referenceHdc, _rectangleF, farameUnit, EmfType.EmfOnly));
AssertExtensions.Throws<ArgumentException>(null, () =>
@@ -361,14 +354,14 @@ namespace System.Drawing.Imaging.Tests
}
}
- [ActiveIssue(20884, TestPlatforms.AnyUnix)]
[ConditionalTheory(Helpers.GdiplusIsAvailable)]
[MemberData(nameof(EmfType_Invalid_TestData))]
public void Ctor_InvalidEmfType_ThrowsArgumentException(EmfType emfType)
{
- using (var bufferGraphics = Graphics.FromHwndInternal(IntPtr.Zero))
+ using (Bitmap bmp = new Bitmap(10, 10, PixelFormat.Format32bppArgb))
+ using (Graphics g = Graphics.FromImage(bmp))
{
- IntPtr referenceHdc = bufferGraphics.GetHdc();
+ IntPtr referenceHdc = g.GetHdc();
AssertExtensions.Throws<ArgumentException>(null, () =>
new Metafile(referenceHdc, _rectangleF, MetafileFrameUnit.GdiCompatible, emfType));
AssertExtensions.Throws<ArgumentException>(null, () =>
@@ -381,13 +374,13 @@ namespace System.Drawing.Imaging.Tests
}
}
- [ActiveIssue(20884, TestPlatforms.AnyUnix)]
[ConditionalFact(Helpers.GdiplusIsAvailable)]
public void Ctor_StringIntPtr_Success()
{
string fileName = GetPath("newTestImage.wmf");
- using (var bufferGraphics = Graphics.FromHwndInternal(IntPtr.Zero))
- using (var metafile = new Metafile(fileName, bufferGraphics.GetHdc()))
+ using (Bitmap bmp = new Bitmap(10, 10, PixelFormat.Format32bppArgb))
+ using (Graphics g = Graphics.FromImage(bmp))
+ using (var metafile = new Metafile(fileName, g.GetHdc()))
{
AssertMetafileIsBlank(metafile);
Assert.True(File.Exists(fileName));
@@ -396,14 +389,14 @@ namespace System.Drawing.Imaging.Tests
File.Delete(fileName);
}
- [ActiveIssue(20884, TestPlatforms.AnyUnix)]
[ConditionalTheory(Helpers.GdiplusIsAvailable)]
[MemberData(nameof(EmfType_TestData))]
public void Ctor_StringIntPtrEmfType_Success(EmfType emfType)
{
string fileName = GetPath("newTestImage.wmf");
- using (var bufferGraphics = Graphics.FromHwndInternal(IntPtr.Zero))
- using (var metafile = new Metafile(fileName, bufferGraphics.GetHdc(), emfType))
+ using (Bitmap bmp = new Bitmap(10, 10, PixelFormat.Format32bppArgb))
+ using (Graphics g = Graphics.FromImage(bmp))
+ using (var metafile = new Metafile(fileName, g.GetHdc(), emfType))
{
AssertMetafileIsBlank(metafile);
AssertEmfType(metafile.GetMetafileHeader(), emfType);
@@ -413,14 +406,14 @@ namespace System.Drawing.Imaging.Tests
File.Delete(fileName);
}
- [ActiveIssue(20884, TestPlatforms.AnyUnix)]
[ConditionalTheory(Helpers.GdiplusIsAvailable)]
[MemberData(nameof(Description_TestData))]
public void Ctor_StringIntPtrEmfType_Success(string description)
{
string fileName = GetPath("newTestImage.wmf");
- using (var bufferGraphics = Graphics.FromHwndInternal(IntPtr.Zero))
- using (var metafile = new Metafile(fileName, bufferGraphics.GetHdc(), EmfType.EmfPlusDual, description))
+ using (Bitmap bmp = new Bitmap(10, 10, PixelFormat.Format32bppArgb))
+ using (Graphics g = Graphics.FromImage(bmp))
+ using (var metafile = new Metafile(fileName, g.GetHdc(), EmfType.EmfPlusDual, description))
{
AssertMetafileIsBlank(metafile);
AssertEmfType(metafile.GetMetafileHeader(), EmfType.EmfPlusDual);
@@ -441,28 +434,28 @@ namespace System.Drawing.Imaging.Tests
DeleteFile(fileName);
}
- [ActiveIssue(20884, TestPlatforms.AnyUnix)]
[ConditionalTheory(Helpers.GdiplusIsAvailable)]
[MemberData(nameof(EmfType_Invalid_TestData))]
public void Ctor_InvalidEmfTypeI_ThrowsArgumentException(EmfType emfType)
{
string fileName = GetPath("newTestImage.wmf");
- using (var bufferGraphics = Graphics.FromHwndInternal(IntPtr.Zero))
+ using (Bitmap bmp = new Bitmap(10, 10, PixelFormat.Format32bppArgb))
+ using (Graphics g = Graphics.FromImage(bmp))
{
- IntPtr referenceHdc = bufferGraphics.GetHdc();
+ IntPtr referenceHdc = g.GetHdc();
AssertExtensions.Throws<ArgumentException>(null, () => new Metafile(fileName, referenceHdc, emfType));
AssertExtensions.Throws<ArgumentException>(null, () => new Metafile(fileName, referenceHdc, emfType, "description"));
DeleteFile(fileName);
}
}
- [ActiveIssue(20884, TestPlatforms.AnyUnix)]
[ConditionalFact(Helpers.GdiplusIsAvailable)]
public void Ctor_NullPath_ThrowsArgumentNullException()
{
- using (var bufferGraphics = Graphics.FromHwndInternal(IntPtr.Zero))
+ using (Bitmap bmp = new Bitmap(10, 10, PixelFormat.Format32bppArgb))
+ using (Graphics g = Graphics.FromImage(bmp))
{
- IntPtr referenceHdc = bufferGraphics.GetHdc();
+ IntPtr referenceHdc = g.GetHdc();
AssertExtensions.Throws<ArgumentNullException>("path", () => new Metafile((string)null, referenceHdc));
AssertExtensions.Throws<ArgumentNullException>("path", () => new Metafile((string)null, referenceHdc, EmfType.EmfOnly));
AssertExtensions.Throws<ArgumentNullException>("path", () => new Metafile((string)null, referenceHdc, EmfType.EmfOnly, "description"));
@@ -475,23 +468,26 @@ namespace System.Drawing.Imaging.Tests
[InlineData("")]
public void Ctor_InvalidPathI_ThrowsArgumentException(string fileName)
{
- using (var bufferGraphics = Graphics.FromHwndInternal(IntPtr.Zero))
+ using (Bitmap bmp = new Bitmap(10, 10, PixelFormat.Format32bppArgb))
+ using (Graphics g = Graphics.FromImage(bmp))
{
- IntPtr referenceHdc = bufferGraphics.GetHdc();
+ IntPtr referenceHdc = g.GetHdc();
AssertExtensions.Throws<ArgumentException>("path", null, () => new Metafile(fileName, referenceHdc));
AssertExtensions.Throws<ArgumentException>("path", null, () => new Metafile(fileName, referenceHdc, EmfType.EmfOnly));
AssertExtensions.Throws<ArgumentException>("path", null, () => new Metafile(fileName, referenceHdc, EmfType.EmfOnly, "description"));
}
}
+ // Long paths aren't that much of a problem on Unix.
[ActiveIssue(20884, TestPlatforms.AnyUnix)]
[ConditionalFact(Helpers.GdiplusIsAvailable)]
public void Ctor_PathTooLong_ThrowsPathTooLongException()
{
string fileName = GetPath(new string('a', short.MaxValue));
- using (var bufferGraphics = Graphics.FromHwndInternal(IntPtr.Zero))
+ using (Bitmap bmp = new Bitmap(10, 10, PixelFormat.Format32bppArgb))
+ using (Graphics g = Graphics.FromImage(bmp))
{
- IntPtr referenceHdc = bufferGraphics.GetHdc();
+ IntPtr referenceHdc = g.GetHdc();
Assert.Throws<PathTooLongException>(() => new Metafile(fileName, referenceHdc));
Assert.Throws<PathTooLongException>(() => new Metafile(fileName, referenceHdc, EmfType.EmfOnly));
Assert.Throws<PathTooLongException>(() => new Metafile(fileName, referenceHdc, EmfType.EmfOnly, "description"));
@@ -499,13 +495,13 @@ namespace System.Drawing.Imaging.Tests
}
}
- [ActiveIssue(20884, TestPlatforms.AnyUnix)]
[ConditionalTheory(Helpers.GdiplusIsAvailable)]
public void Ctor_StringIntPtrRectangleF_Success()
{
string fileName = GetPath("newTestImage.wmf");
- using (var bufferGraphics = Graphics.FromHwndInternal(IntPtr.Zero))
- using (var metafile = new Metafile(fileName, bufferGraphics.GetHdc(), _rectangleF))
+ using (Bitmap bmp = new Bitmap(10, 10, PixelFormat.Format32bppArgb))
+ using (Graphics g = Graphics.FromImage(bmp))
+ using (var metafile = new Metafile(fileName, g.GetHdc(), _rectangleF))
{
AssertMetafileIsBlank(metafile);
Assert.True(File.Exists(fileName));
@@ -514,14 +510,14 @@ namespace System.Drawing.Imaging.Tests
File.Delete(fileName);
}
- [ActiveIssue(20884, TestPlatforms.AnyUnix)]
[ConditionalTheory(Helpers.GdiplusIsAvailable)]
[MemberData(nameof(MetafileFrameUnit_TestData))]
public void Ctor_StringIntPtrRectangleFMetafileFrameUnit_Success(MetafileFrameUnit frameUnit)
{
string fileName = GetPath("newTestImage.wmf");
- using (var bufferGraphics = Graphics.FromHwndInternal(IntPtr.Zero))
- using (var metafile = new Metafile(fileName, bufferGraphics.GetHdc(), _rectangleF, frameUnit))
+ using (Bitmap bmp = new Bitmap(10, 10, PixelFormat.Format32bppArgb))
+ using (Graphics g = Graphics.FromImage(bmp))
+ using (var metafile = new Metafile(fileName, g.GetHdc(), _rectangleF, frameUnit))
{
AssertMetafileIsBlank(metafile);
Assert.True(File.Exists(fileName));
@@ -530,14 +526,14 @@ namespace System.Drawing.Imaging.Tests
File.Delete(fileName);
}
- [ActiveIssue(20884, TestPlatforms.AnyUnix)]
[ConditionalTheory(Helpers.GdiplusIsAvailable)]
[MemberData(nameof(EmfType_TestData))]
public void Ctor_StringIntPtrRectangleFMetafileFrameUnitEmfType_Success(EmfType emfType)
{
string fileName = GetPath("newTestImage.wmf");
- using (var bufferGraphics = Graphics.FromHwndInternal(IntPtr.Zero))
- using (var metafile = new Metafile(fileName, bufferGraphics.GetHdc(), _rectangleF, MetafileFrameUnit.GdiCompatible, emfType))
+ using (Bitmap bmp = new Bitmap(10, 10, PixelFormat.Format32bppArgb))
+ using (Graphics g = Graphics.FromImage(bmp))
+ using (var metafile = new Metafile(fileName, g.GetHdc(), _rectangleF, MetafileFrameUnit.GdiCompatible, emfType))
{
AssertMetafileIsBlank(metafile);
AssertEmfType(metafile.GetMetafileHeader(), emfType);
@@ -547,15 +543,15 @@ namespace System.Drawing.Imaging.Tests
File.Delete(fileName);
}
- [ActiveIssue(20884, TestPlatforms.AnyUnix)]
[ConditionalTheory(Helpers.GdiplusIsAvailable)]
[MemberData(nameof(Description_TestData))]
public void Ctor_StringIntPtrRectangleFMetafileFrameUnitEmfTypeString_Success(string description)
{
string fileName = GetPath("newTestImage.wmf");
- using (var bufferGraphics = Graphics.FromHwndInternal(IntPtr.Zero))
+ using (Bitmap bmp = new Bitmap(10, 10, PixelFormat.Format32bppArgb))
+ using (Graphics g = Graphics.FromImage(bmp))
using (var metafile = new Metafile(
- fileName, bufferGraphics.GetHdc(), _rectangleF, MetafileFrameUnit.GdiCompatible, EmfType.EmfOnly, description))
+ fileName, g.GetHdc(), _rectangleF, MetafileFrameUnit.GdiCompatible, EmfType.EmfOnly, description))
{
AssertMetafileIsBlank(metafile);
AssertEmfType(metafile.GetMetafileHeader(), EmfType.EmfOnly);
@@ -565,15 +561,15 @@ namespace System.Drawing.Imaging.Tests
File.Delete(fileName);
}
- [ActiveIssue(20884, TestPlatforms.AnyUnix)]
[ConditionalTheory(Helpers.GdiplusIsAvailable)]
[MemberData(nameof(Description_TestData))]
public void Ctor_RectangleFEmpty_Success(string description)
{
string fileName = GetPath("newTestImage.wmf");
- using (var bufferGraphics = Graphics.FromHwndInternal(IntPtr.Zero))
+ using (Bitmap bmp = new Bitmap(10, 10, PixelFormat.Format32bppArgb))
+ using (Graphics g = Graphics.FromImage(bmp))
using (var metafile = new Metafile(
- fileName, bufferGraphics.GetHdc(), new RectangleF(), MetafileFrameUnit.GdiCompatible, EmfType.EmfOnly, description))
+ fileName, g.GetHdc(), new RectangleF(), MetafileFrameUnit.GdiCompatible, EmfType.EmfOnly, description))
{
AssertMetafileIsBlank(metafile);
AssertEmfType(metafile.GetMetafileHeader(), EmfType.EmfOnly);
@@ -583,13 +579,13 @@ namespace System.Drawing.Imaging.Tests
File.Delete(fileName);
}
- [ActiveIssue(20884, TestPlatforms.AnyUnix)]
[ConditionalTheory(Helpers.GdiplusIsAvailable)]
public void Ctor_StringIntPtrRectangle_Success()
{
string fileName = GetPath("newTestImage.wmf");
- using (var bufferGraphics = Graphics.FromHwndInternal(IntPtr.Zero))
- using (var metafile = new Metafile(fileName, bufferGraphics.GetHdc(), _rectangle))
+ using (Bitmap bmp = new Bitmap(10, 10, PixelFormat.Format32bppArgb))
+ using (Graphics g = Graphics.FromImage(bmp))
+ using (var metafile = new Metafile(fileName, g.GetHdc(), _rectangle))
{
AssertMetafileIsBlank(metafile);
Assert.True(File.Exists(fileName));
@@ -598,14 +594,14 @@ namespace System.Drawing.Imaging.Tests
File.Delete(fileName);
}
- [ActiveIssue(20884, TestPlatforms.AnyUnix)]
[ConditionalTheory(Helpers.GdiplusIsAvailable)]
[MemberData(nameof(MetafileFrameUnit_TestData))]
public void Ctor_StringIntPtrRectangleMetafileFrameUnit_Success(MetafileFrameUnit frameUnit)
{
string fileName = GetPath("newTestImage.wmf");
- using (var bufferGraphics = Graphics.FromHwndInternal(IntPtr.Zero))
- using (var metafile = new Metafile(fileName, bufferGraphics.GetHdc(), _rectangle, frameUnit))
+ using (Bitmap bmp = new Bitmap(10, 10, PixelFormat.Format32bppArgb))
+ using (Graphics g = Graphics.FromImage(bmp))
+ using (var metafile = new Metafile(fileName, g.GetHdc(), _rectangle, frameUnit))
{
AssertMetafileIsBlank(metafile);
Assert.True(File.Exists(fileName));
@@ -614,14 +610,14 @@ namespace System.Drawing.Imaging.Tests
File.Delete(fileName);
}
- [ActiveIssue(20884, TestPlatforms.AnyUnix)]
[ConditionalTheory(Helpers.GdiplusIsAvailable)]
[MemberData(nameof(EmfType_TestData))]
public void Ctor_StringIntPtrRectangleMetafileFrameUnitEmfType_Success(EmfType emfType)
{
string fileName = GetPath("newTestImage.wmf");
- using (var bufferGraphics = Graphics.FromHwndInternal(IntPtr.Zero))
- using (var metafile = new Metafile(fileName, bufferGraphics.GetHdc(), _rectangle, MetafileFrameUnit.GdiCompatible, emfType))
+ using (Bitmap bmp = new Bitmap(10, 10, PixelFormat.Format32bppArgb))
+ using (Graphics g = Graphics.FromImage(bmp))
+ using (var metafile = new Metafile(fileName, g.GetHdc(), _rectangle, MetafileFrameUnit.GdiCompatible, emfType))
{
AssertMetafileIsBlank(metafile);
AssertEmfType(metafile.GetMetafileHeader(), emfType);
@@ -631,15 +627,15 @@ namespace System.Drawing.Imaging.Tests
File.Delete(fileName);
}
- [ActiveIssue(20884, TestPlatforms.AnyUnix)]
[ConditionalTheory(Helpers.GdiplusIsAvailable)]
[MemberData(nameof(Description_TestData))]
public void Ctor_StringIntPtrRectangleMetafileFrameUnitEmfTypeString_Success(string description)
{
string fileName = GetPath("newTestImage.wmf");
- using (var bufferGraphics = Graphics.FromHwndInternal(IntPtr.Zero))
+ using (Bitmap bmp = new Bitmap(10, 10, PixelFormat.Format32bppArgb))
+ using (Graphics g = Graphics.FromImage(bmp))
using (var metafile = new Metafile(
- fileName, bufferGraphics.GetHdc(), _rectangle, MetafileFrameUnit.GdiCompatible, EmfType.EmfOnly, description))
+ fileName, g.GetHdc(), _rectangle, MetafileFrameUnit.GdiCompatible, EmfType.EmfOnly, description))
{
AssertMetafileIsBlank(metafile);
AssertEmfType(metafile.GetMetafileHeader(), EmfType.EmfOnly);
@@ -649,15 +645,15 @@ namespace System.Drawing.Imaging.Tests
File.Delete(fileName);
}
- [ActiveIssue(20884, TestPlatforms.AnyUnix)]
[ConditionalTheory(Helpers.GdiplusIsAvailable)]
[MemberData(nameof(Description_TestData))]
public void Ctor_RectangleEmpty_Success(string description)
{
string fileName = GetPath("newTestImage.wmf");
- using (var bufferGraphics = Graphics.FromHwndInternal(IntPtr.Zero))
+ using (Bitmap bmp = new Bitmap(10, 10, PixelFormat.Format32bppArgb))
+ using (Graphics g = Graphics.FromImage(bmp))
using (var metafile = new Metafile(
- fileName, bufferGraphics.GetHdc(), new Rectangle(), MetafileFrameUnit.GdiCompatible, EmfType.EmfOnly, description))
+ fileName, g.GetHdc(), new Rectangle(), MetafileFrameUnit.GdiCompatible, EmfType.EmfOnly, description))
{
AssertMetafileIsBlank(metafile);
AssertEmfType(metafile.GetMetafileHeader(), EmfType.EmfOnly);
@@ -688,15 +684,15 @@ namespace System.Drawing.Imaging.Tests
DeleteFile(fileName);
}
- [ActiveIssue(20884, TestPlatforms.AnyUnix)]
[ConditionalTheory(Helpers.GdiplusIsAvailable)]
[MemberData(nameof(MetafileFrameUnit_Invalid_TestData))]
public void Ctor_InvalidEmfTypeII_ThrowsArgumentException(MetafileFrameUnit frameUnit)
{
string fileName = GetPath("newTestImage.wmf");
- using (var bufferGraphics = Graphics.FromHwndInternal(IntPtr.Zero))
+ using (Bitmap bmp = new Bitmap(10, 10, PixelFormat.Format32bppArgb))
+ using (Graphics g = Graphics.FromImage(bmp))
{
- IntPtr referenceHdc = bufferGraphics.GetHdc();
+ IntPtr referenceHdc = g.GetHdc();
AssertExtensions.Throws<ArgumentException>(null, () => new Metafile(fileName, referenceHdc, _rectangleF, frameUnit));
AssertExtensions.Throws<ArgumentException>(null, () =>
new Metafile(fileName, referenceHdc, _rectangleF, frameUnit, EmfType.EmfOnly));
@@ -712,15 +708,15 @@ namespace System.Drawing.Imaging.Tests
}
}
- [ActiveIssue(20884, TestPlatforms.AnyUnix)]
[ConditionalTheory(Helpers.GdiplusIsAvailable)]
[MemberData(nameof(EmfType_Invalid_TestData))]
public void Ctor_InvalidEmfTypeII_ThrowsArgumentException(EmfType emfType)
{
string fileName = GetPath("newTestImage.wmf");
- using (var bufferGraphics = Graphics.FromHwndInternal(IntPtr.Zero))
+ using (Bitmap bmp = new Bitmap(10, 10, PixelFormat.Format32bppArgb))
+ using (Graphics g = Graphics.FromImage(bmp))
{
- IntPtr referenceHdc = bufferGraphics.GetHdc();
+ IntPtr referenceHdc = g.GetHdc();
AssertExtensions.Throws<ArgumentException>(null, () =>
new Metafile(fileName, referenceHdc, _rectangleF, MetafileFrameUnit.GdiCompatible, emfType));
AssertExtensions.Throws<ArgumentException>(null, () =>
@@ -734,14 +730,13 @@ namespace System.Drawing.Imaging.Tests
}
}
- [ActiveIssue(22723)]
- [ActiveIssue(20884, TestPlatforms.AnyUnix)]
[ConditionalFact(Helpers.GdiplusIsAvailable)]
public void Ctor_NullPathI_ThrowsArgumentNullException()
{
- using (var bufferGraphics = Graphics.FromHwndInternal(IntPtr.Zero))
+ using (Bitmap bmp = new Bitmap(10, 10, PixelFormat.Format32bppArgb))
+ using (Graphics g = Graphics.FromImage(bmp))
{
- IntPtr referenceHdc = bufferGraphics.GetHdc();
+ IntPtr referenceHdc = g.GetHdc();
AssertExtensions.Throws<ArgumentNullException>("path", () => new Metafile((string)null, referenceHdc, _rectangleF));
AssertExtensions.Throws<ArgumentNullException>("path", () =>
new Metafile((string)null, referenceHdc, _rectangleF, MetafileFrameUnit.GdiCompatible));
@@ -752,35 +747,36 @@ namespace System.Drawing.Imaging.Tests
}
}
- [ActiveIssue(22723)]
[ActiveIssue(20884, TestPlatforms.AnyUnix)]
[ConditionalTheory(Helpers.GdiplusIsAvailable)]
[InlineData(@"fileNo*-//\\#@(found")]
[InlineData("")]
public void Ctor_InvalidPathII_ThrowsArgumentException(string fileName)
{
- using (var bufferGraphics = Graphics.FromHwndInternal(IntPtr.Zero))
+ using (Bitmap bmp = new Bitmap(10, 10, PixelFormat.Format32bppArgb))
+ using (Graphics g = Graphics.FromImage(bmp))
{
- IntPtr referenceHdc = bufferGraphics.GetHdc();
- AssertExtensions.Throws<ArgumentException>(null, () => new Metafile(fileName, referenceHdc, _rectangleF));
- AssertExtensions.Throws<ArgumentException>(null, () =>
+ IntPtr referenceHdc = g.GetHdc();
+ AssertExtensions.Throws<ArgumentException, ArgumentException>("path", null, () => new Metafile(fileName, referenceHdc, _rectangleF));
+ AssertExtensions.Throws<ArgumentException, ArgumentException>("path", null, () =>
new Metafile(fileName, referenceHdc, _rectangleF, MetafileFrameUnit.GdiCompatible));
- AssertExtensions.Throws<ArgumentException>(null, () =>
+ AssertExtensions.Throws<ArgumentException, ArgumentException>("path", null, () =>
new Metafile(fileName, referenceHdc, _rectangleF, MetafileFrameUnit.GdiCompatible, EmfType.EmfOnly));
- AssertExtensions.Throws<ArgumentException>(null, () =>
+ AssertExtensions.Throws<ArgumentException, ArgumentException>("path", null, () =>
new Metafile(fileName, referenceHdc, _rectangleF, MetafileFrameUnit.GdiCompatible, EmfType.EmfOnly, "description"));
}
}
- [ActiveIssue(22723)]
+ // Long paths aren't that much of a problem on Unix.
[ActiveIssue(20884, TestPlatforms.AnyUnix)]
[ConditionalFact(Helpers.GdiplusIsAvailable)]
public void Ctor_PathTooLongI_ThrowsPathTooLongException()
{
string fileName = GetPath(new string('a', 261));
- using (var bufferGraphics = Graphics.FromHwndInternal(IntPtr.Zero))
+ using (Bitmap bmp = new Bitmap(10, 10, PixelFormat.Format32bppArgb))
+ using (Graphics g = Graphics.FromImage(bmp))
{
- IntPtr referenceHdc = bufferGraphics.GetHdc();
+ IntPtr referenceHdc = g.GetHdc();
Assert.Throws<PathTooLongException>(() => new Metafile(fileName, referenceHdc, _rectangleF));
Assert.Throws<PathTooLongException>(() =>
new Metafile(fileName, referenceHdc, _rectangleF, MetafileFrameUnit.GdiCompatible));
@@ -792,69 +788,69 @@ namespace System.Drawing.Imaging.Tests
}
}
- [ActiveIssue(20884, TestPlatforms.AnyUnix)]
[ConditionalTheory(Helpers.GdiplusIsAvailable)]
public void Ctor_StreamIntPtrRectangle_Success()
{
- using (var bufferGraphics = Graphics.FromHwndInternal(IntPtr.Zero))
+ using (Bitmap bmp = new Bitmap(10, 10, PixelFormat.Format32bppArgb))
+ using (Graphics g = Graphics.FromImage(bmp))
using (var stream = new MemoryStream())
- using (var metafile = new Metafile(stream, bufferGraphics.GetHdc(), _rectangle))
+ using (var metafile = new Metafile(stream, g.GetHdc(), _rectangle))
{
AssertMetafileIsBlank(metafile);
}
}
- [ActiveIssue(20884, TestPlatforms.AnyUnix)]
[ConditionalTheory(Helpers.GdiplusIsAvailable)]
[MemberData(nameof(MetafileFrameUnit_TestData))]
public void Ctor_StreamIntPtrRectangleMetafileFrameUnit_Success(MetafileFrameUnit frameUnit)
{
- using (var bufferGraphics = Graphics.FromHwndInternal(IntPtr.Zero))
+ using (Bitmap bmp = new Bitmap(10, 10, PixelFormat.Format32bppArgb))
+ using (Graphics g = Graphics.FromImage(bmp))
using (var stream = new MemoryStream())
- using (var metafile = new Metafile(stream, bufferGraphics.GetHdc(), _rectangle, frameUnit))
+ using (var metafile = new Metafile(stream, g.GetHdc(), _rectangle, frameUnit))
{
AssertMetafileIsBlank(metafile);
}
}
- [ActiveIssue(20884, TestPlatforms.AnyUnix)]
[ConditionalTheory(Helpers.GdiplusIsAvailable)]
[MemberData(nameof(EmfType_TestData))]
public void Ctor_StreamIntPtrRectangleMetafileFrameUnitEmfType_Success(EmfType emfType)
{
- using (var bufferGraphics = Graphics.FromHwndInternal(IntPtr.Zero))
+ using (Bitmap bmp = new Bitmap(10, 10, PixelFormat.Format32bppArgb))
+ using (Graphics g = Graphics.FromImage(bmp))
using (var stream = new MemoryStream())
- using (var metafile = new Metafile(stream, bufferGraphics.GetHdc(), _rectangle, MetafileFrameUnit.GdiCompatible, emfType))
+ using (var metafile = new Metafile(stream, g.GetHdc(), _rectangle, MetafileFrameUnit.GdiCompatible, emfType))
{
AssertMetafileIsBlank(metafile);
AssertEmfType(metafile.GetMetafileHeader(), emfType);
}
}
- [ActiveIssue(20884, TestPlatforms.AnyUnix)]
[ConditionalTheory(Helpers.GdiplusIsAvailable)]
[MemberData(nameof(Description_TestData))]
public void Ctor_StreamIntPtrRectangleMetafileFrameUnitEmfTypeString_Success(string description)
{
- using (var bufferGraphics = Graphics.FromHwndInternal(IntPtr.Zero))
+ using (Bitmap bmp = new Bitmap(10, 10, PixelFormat.Format32bppArgb))
+ using (Graphics g = Graphics.FromImage(bmp))
using (var stream = new MemoryStream())
using (var metafile = new Metafile(
- stream, bufferGraphics.GetHdc(), _rectangle, MetafileFrameUnit.GdiCompatible, EmfType.EmfOnly, description))
+ stream, g.GetHdc(), _rectangle, MetafileFrameUnit.GdiCompatible, EmfType.EmfOnly, description))
{
AssertMetafileIsBlank(metafile);
AssertEmfType(metafile.GetMetafileHeader(), EmfType.EmfOnly);
}
}
- [ActiveIssue(20884, TestPlatforms.AnyUnix)]
[ConditionalTheory(Helpers.GdiplusIsAvailable)]
[MemberData(nameof(Description_TestData))]
public void Ctor_RectangleEmptyI_Success(string description)
{
- using (var bufferGraphics = Graphics.FromHwndInternal(IntPtr.Zero))
+ using (Bitmap bmp = new Bitmap(10, 10, PixelFormat.Format32bppArgb))
+ using (Graphics g = Graphics.FromImage(bmp))
using (var stream = new MemoryStream())
using (var metafile = new Metafile(
- stream, bufferGraphics.GetHdc(), new Rectangle(), MetafileFrameUnit.GdiCompatible, EmfType.EmfOnly, description))
+ stream, g.GetHdc(), new Rectangle(), MetafileFrameUnit.GdiCompatible, EmfType.EmfOnly, description))
{
AssertMetafileIsBlank(metafile);
AssertEmfType(metafile.GetMetafileHeader(), EmfType.EmfOnly);
@@ -876,15 +872,15 @@ namespace System.Drawing.Imaging.Tests
}
}
- [ActiveIssue(20884, TestPlatforms.AnyUnix)]
[ConditionalTheory(Helpers.GdiplusIsAvailable)]
[MemberData(nameof(MetafileFrameUnit_Invalid_TestData))]
public void Ctor_InvalidEmfTypeIII_ThrowsArgumentException(MetafileFrameUnit frameUnit)
{
using (var stream = new MemoryStream())
- using (var bufferGraphics = Graphics.FromHwndInternal(IntPtr.Zero))
+ using (Bitmap bmp = new Bitmap(10, 10, PixelFormat.Format32bppArgb))
+ using (Graphics g = Graphics.FromImage(bmp))
{
- IntPtr referenceHdc = bufferGraphics.GetHdc();
+ IntPtr referenceHdc = g.GetHdc();
AssertExtensions.Throws<ArgumentException>(null, () => new Metafile(stream, referenceHdc, _rectangle, frameUnit));
AssertExtensions.Throws<ArgumentException>(null, () =>
new Metafile(stream, referenceHdc, _rectangle, frameUnit, EmfType.EmfOnly));
@@ -893,15 +889,15 @@ namespace System.Drawing.Imaging.Tests
}
}
- [ActiveIssue(20884, TestPlatforms.AnyUnix)]
[ConditionalTheory(Helpers.GdiplusIsAvailable)]
[MemberData(nameof(EmfType_Invalid_TestData))]
public void Ctor_InvalidEmfTypeIII_ThrowsArgumentException(EmfType emfType)
{
using (var stream = new MemoryStream())
- using (var bufferGraphics = Graphics.FromHwndInternal(IntPtr.Zero))
+ using (Bitmap bmp = new Bitmap(10, 10, PixelFormat.Format32bppArgb))
+ using (Graphics g = Graphics.FromImage(bmp))
{
- IntPtr referenceHdc = bufferGraphics.GetHdc();
+ IntPtr referenceHdc = g.GetHdc();
AssertExtensions.Throws<ArgumentException>(null, () =>
new Metafile(stream, referenceHdc, _rectangle, MetafileFrameUnit.GdiCompatible, emfType));
AssertExtensions.Throws<ArgumentException>(null, () =>
@@ -909,13 +905,13 @@ namespace System.Drawing.Imaging.Tests
}
}
- [ActiveIssue(20884, TestPlatforms.AnyUnix)]
[ConditionalFact(Helpers.GdiplusIsAvailable)]
public void Ctor_NullStream_ThrowsNullReferenceException()
{
- using (var bufferGraphics = Graphics.FromHwndInternal(IntPtr.Zero))
+ using (Bitmap bmp = new Bitmap(10, 10, PixelFormat.Format32bppArgb))
+ using (Graphics g = Graphics.FromImage(bmp))
{
- IntPtr referenceHdc = bufferGraphics.GetHdc();
+ IntPtr referenceHdc = g.GetHdc();
Assert.Throws<NullReferenceException>(() => new Metafile((Stream)null, referenceHdc, _rectangleF));
Assert.Throws<NullReferenceException>(() => new Metafile((Stream)null, referenceHdc, _rectangleF, MetafileFrameUnit.GdiCompatible));
Assert.Throws<NullReferenceException>(() =>
@@ -925,7 +921,6 @@ namespace System.Drawing.Imaging.Tests
}
}
- [ActiveIssue(20884, TestPlatforms.AnyUnix)]
[ConditionalFact(Helpers.GdiplusIsAvailable)]
public void Static_GetMetafileHeader_String_ReturnsExpected()
{
@@ -933,7 +928,6 @@ namespace System.Drawing.Imaging.Tests
AssertMetafileHeader(header);
}
- [ActiveIssue(20884, TestPlatforms.AnyUnix)]
[ConditionalFact(Helpers.GdiplusIsAvailable)]
public void Static_GetMetafileHeader_IntPtr_ThrowsArgumentException()
{
@@ -960,7 +954,6 @@ namespace System.Drawing.Imaging.Tests
AssertExtensions.Throws<ArgumentNullException>("path", () => Metafile.GetMetafileHeader((string)null));
}
- [ActiveIssue(20884, TestPlatforms.AnyUnix)]
[ConditionalFact(Helpers.GdiplusIsAvailable)]
public void Static_GetMetafileHeader_Stream_ReturnsExpected()
{
@@ -971,7 +964,6 @@ namespace System.Drawing.Imaging.Tests
}
}
- [ActiveIssue(20884, TestPlatforms.AnyUnix)]
[ConditionalFact(Helpers.GdiplusIsAvailable)]
public void Static_GetMetafileHeader_NullStream_ThrowsNullReferenceException()
{
@@ -988,7 +980,6 @@ namespace System.Drawing.Imaging.Tests
}
}
- [ActiveIssue(20884, TestPlatforms.AnyUnix)]
[ConditionalFact(Helpers.GdiplusIsAvailable)]
public void GetMetafileHeader_ReturnsExpected()
{
@@ -997,7 +988,7 @@ namespace System.Drawing.Imaging.Tests
MetafileHeader headerA = metafile.GetMetafileHeader();
MetafileHeader headerB = metafile.GetMetafileHeader();
AssertMetafileHeader(headerA);
- Assert.False(ReferenceEquals(headerA, headerB));
+ Assert.NotSame(headerA, headerB);
}
}
@@ -1076,8 +1067,13 @@ namespace System.Drawing.Imaging.Tests
GraphicsUnit graphicsUnit = (GraphicsUnit)int.MaxValue;
AssertMetafileHeaderIsBlank(metafile.GetMetafileHeader());
- Assert.Equal(new Rectangle(0, 0, 1, 1), metafile.GetBounds(ref graphicsUnit));
- Assert.Equal(GraphicsUnit.Pixel, graphicsUnit);
+
+ if (RuntimeInformation.IsOSPlatform(OSPlatform.Windows))
+ {
+ // This values are incorrect on libgdiplus.
+ Assert.Equal(new Rectangle(0, 0, 1, 1), metafile.GetBounds(ref graphicsUnit));
+ Assert.Equal(GraphicsUnit.Pixel, graphicsUnit);
+ }
}
private void AssertMetafileHeaderIsBlank(MetafileHeader metafileHeader)
diff --git a/src/System.Drawing.Common/tests/Printing/PrintDocumentTests.cs b/src/System.Drawing.Common/tests/Printing/PrintDocumentTests.cs
index 223dc1f346..de604b044b 100644
--- a/src/System.Drawing.Common/tests/Printing/PrintDocumentTests.cs
+++ b/src/System.Drawing.Common/tests/Printing/PrintDocumentTests.cs
@@ -254,10 +254,6 @@ namespace System.Drawing.Printing.Tests
case PaperKind.Letter:
Assert.Equal(new Rectangle(0, 0, 850, 1100), pageSettings.Bounds);
break;
-
- default:
- Assert.False(true, "Unexpected default paper size");
- break;
}
Assert.False(pageSettings.Landscape);
diff --git a/src/System.Drawing.Common/tests/Printing/PrinterSettingsTests.cs b/src/System.Drawing.Common/tests/Printing/PrinterSettingsTests.cs
index efaaa54683..9569246895 100644
--- a/src/System.Drawing.Common/tests/Printing/PrinterSettingsTests.cs
+++ b/src/System.Drawing.Common/tests/Printing/PrinterSettingsTests.cs
@@ -29,6 +29,7 @@ using System.Collections.Generic;
using System.ComponentModel;
using System.Drawing.Imaging;
using System.Globalization;
+using System.Linq;
using Xunit;
namespace System.Drawing.Printing.Tests
@@ -47,7 +48,7 @@ namespace System.Drawing.Printing.Tests
public void CanDuplex_ReturnsExpected()
{
var printerSettings = new PrinterSettings();
- Assert.Equal(true, printerSettings.CanDuplex);
+ bool canDuplex = printerSettings.CanDuplex;
}
[ConditionalFact(Helpers.GdiplusIsAvailable)]
@@ -83,7 +84,7 @@ namespace System.Drawing.Printing.Tests
public void Collate_Default_ReturnsExpected()
{
var printerSettings = new PrinterSettings();
- Assert.Equal(true, printerSettings.Collate);
+ bool collate = printerSettings.Collate;
}
[ConditionalFact(Helpers.GdiplusIsAvailable)]
@@ -181,6 +182,7 @@ namespace System.Drawing.Printing.Tests
}
[ConditionalFact(Helpers.GdiplusIsAvailable)]
+ [ActiveIssue(20884, TestPlatforms.AnyUnix)]
public void IsValid_ReturnsExpected()
{
var printerSettings = new PrinterSettings()
@@ -195,14 +197,15 @@ namespace System.Drawing.Printing.Tests
public void LandscapeAngle_ReturnsExpected()
{
var printerSettings = new PrinterSettings();
- Assert.Equal(0, printerSettings.LandscapeAngle);
+ int[] validValues = new[] { 0, 90, 270 };
+ Assert.True(validValues.Contains(printerSettings.LandscapeAngle), "PrinterSettings.LandscapeAngle must be 0, 90, or 270 degrees.");
}
[ConditionalFact(Helpers.AnyInstalledPrinters, Helpers.GdiplusIsAvailable)]
public void MaximumCopies_ReturnsExpected()
{
var printerSettings = new PrinterSettings();
- Assert.Equal(0, printerSettings.MaximumCopies);
+ Assert.True(printerSettings.MaximumCopies >= 0, "PrinterSettings.MaximumCopies should not be negative.");
}
[Fact]
@@ -476,8 +479,8 @@ namespace System.Drawing.Printing.Tests
Assert.NotNull(graphic);
Assert.Equal(printerSettings.DefaultPageSettings.Bounds.X, graphic.VisibleClipBounds.X, 0);
Assert.Equal(printerSettings.DefaultPageSettings.Bounds.Y, graphic.VisibleClipBounds.Y, 0);
- Assert.Equal(printerSettings.DefaultPageSettings.Bounds.Height, graphic.VisibleClipBounds.Height, 0);
- Assert.Equal(printerSettings.DefaultPageSettings.Bounds.Width, graphic.VisibleClipBounds.Width, 0);
+ Assert.Equal(printerSettings.DefaultPageSettings.PrintableArea.Height, graphic.VisibleClipBounds.Height, 0);
+ Assert.Equal(printerSettings.DefaultPageSettings.PrintableArea.Width, graphic.VisibleClipBounds.Width, 0);
}
}
@@ -489,8 +492,8 @@ namespace System.Drawing.Printing.Tests
using (Graphics graphic = printerSettings.CreateMeasurementGraphics(true))
{
Assert.NotNull(graphic);
- Assert.Equal(printerSettings.DefaultPageSettings.Bounds.Height, graphic.VisibleClipBounds.Height, 0);
- Assert.Equal(printerSettings.DefaultPageSettings.Bounds.Width, graphic.VisibleClipBounds.Width, 0);
+ Assert.Equal(printerSettings.DefaultPageSettings.PrintableArea.Height, graphic.VisibleClipBounds.Height, 0);
+ Assert.Equal(printerSettings.DefaultPageSettings.PrintableArea.Width, graphic.VisibleClipBounds.Width, 0);
}
}
@@ -505,8 +508,8 @@ namespace System.Drawing.Printing.Tests
Assert.NotNull(graphic);
Assert.Equal(printerSettings.DefaultPageSettings.Bounds.X, graphic.VisibleClipBounds.X, 0);
Assert.Equal(printerSettings.DefaultPageSettings.Bounds.Y, graphic.VisibleClipBounds.Y, 0);
- Assert.Equal(printerSettings.DefaultPageSettings.Bounds.Height, graphic.VisibleClipBounds.Height, 0);
- Assert.Equal(printerSettings.DefaultPageSettings.Bounds.Width, graphic.VisibleClipBounds.Width, 0);
+ Assert.Equal(printerSettings.DefaultPageSettings.PrintableArea.Height, graphic.VisibleClipBounds.Height, 0);
+ Assert.Equal(printerSettings.DefaultPageSettings.PrintableArea.Width, graphic.VisibleClipBounds.Width, 0);
}
}
@@ -519,8 +522,8 @@ namespace System.Drawing.Printing.Tests
using (Graphics graphic = printerSettings.CreateMeasurementGraphics(pageSettings, true))
{
Assert.NotNull(graphic);
- Assert.Equal(printerSettings.DefaultPageSettings.Bounds.Height, graphic.VisibleClipBounds.Height, 0);
- Assert.Equal(printerSettings.DefaultPageSettings.Bounds.Width, graphic.VisibleClipBounds.Width, 0);
+ Assert.Equal(printerSettings.DefaultPageSettings.PrintableArea.Height, graphic.VisibleClipBounds.Height, 0);
+ Assert.Equal(printerSettings.DefaultPageSettings.PrintableArea.Width, graphic.VisibleClipBounds.Width, 0);
}
}
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 2e3ba2b068..6a24e7f28d 100644
--- a/src/System.Drawing.Common/tests/System.Drawing.Common.Tests.csproj
+++ b/src/System.Drawing.Common/tests/System.Drawing.Common.Tests.csproj
@@ -3,11 +3,8 @@
<Import Project="$([MSBuild]::GetDirectoryNameOfFileAbove($(MSBuildThisFileDirectory), dir.props))\dir.props" />
<PropertyGroup>
<ProjectGuid>{4B93E684-0630-45F4-8F63-6C7788C9892F}</ProjectGuid>
+ <AllowUnsafeBlocks>true</AllowUnsafeBlocks>
</PropertyGroup>
- <PropertyGroup Condition="'$(Configuration)|$(Platform)' == 'netcoreapp-Debug|AnyCPU'" />
- <PropertyGroup Condition="'$(Configuration)|$(Platform)' == 'netcoreapp-Release|AnyCPU'" />
- <PropertyGroup Condition="'$(Configuration)|$(Platform)' == 'netfx-Debug|AnyCPU'" />
- <PropertyGroup Condition="'$(Configuration)|$(Platform)' == 'netfx-Release|AnyCPU'" />
<ItemGroup>
<Compile Include="BitmapTests.cs" />
<Compile Include="BrushTests.cs" />
@@ -31,6 +28,15 @@
<Compile Include="Imaging\ImageAttributesTests.cs" />
<Compile Include="Imaging\MetafileTests.cs" />
<Compile Include="Imaging\PropertyItemTests.cs" />
+ <Compile Include="mono\System.Drawing.Imaging\BmpCodecTests.cs" />
+ <Compile Include="mono\System.Drawing.Imaging\GifCodecTests.cs" />
+ <Compile Include="mono\System.Drawing.Imaging\IconCodecTests.cs" />
+ <Compile Include="mono\System.Drawing.Imaging\JpegCodecTests.cs" />
+ <Compile Include="mono\System.Drawing.Imaging\PngCodecTesst.cs" />
+ <Compile Include="mono\System.Drawing.Imaging\TiffCodecTests.cs" />
+ <Compile Include="mono\System.Drawing\GraphicsTests.cs" />
+ <Compile Include="mono\System.Imaging\MetafileTest.cs" />
+ <Compile Include="mono\System.Drawing\BitmapTests.cs" />
<Compile Include="PenTests.cs" />
<Compile Include="PensTests.cs" />
<Compile Include="Imaging\BitmapDataTests.cs" />
@@ -74,19 +80,19 @@
</Compile>
</ItemGroup>
<ItemGroup>
- <SupplementalTestData Include="$(PackagesDir)system.drawing.common.testdata\1.0.3\content\**\*.*">
+ <SupplementalTestData Include="$(PackagesDir)system.drawing.common.testdata\1.0.6\content\**\*.*">
<Link>%(RecursiveDir)%(Filename)%(Extension)</Link>
</SupplementalTestData>
- <EmbeddedResource Include="$(PackagesDir)system.drawing.common.testdata\1.0.3\content\bitmaps\48x48_multiple_entries_4bit.ico">
+ <EmbeddedResource Include="$(PackagesDir)system.drawing.common.testdata\1.0.6\content\bitmaps\48x48_multiple_entries_4bit.ico">
<LogicalName>System.Drawing.Tests.48x48_multiple_entries_4bit.ico</LogicalName>
</EmbeddedResource>
- <EmbeddedResource Include="$(PackagesDir)system.drawing.common.testdata\1.0.3\content\bitmaps\bitmap_173x183_indexed_8bit.bmp">
+ <EmbeddedResource Include="$(PackagesDir)system.drawing.common.testdata\1.0.6\content\bitmaps\bitmap_173x183_indexed_8bit.bmp">
<LogicalName>System.Drawing.Tests.bitmap_173x183_indexed_8bit.bmp</LogicalName>
</EmbeddedResource>
- <EmbeddedResource Include="$(PackagesDir)system.drawing.common.testdata\1.0.3\content\bitmaps\empty.file">
+ <EmbeddedResource Include="$(PackagesDir)system.drawing.common.testdata\1.0.6\content\bitmaps\empty.file">
<LogicalName>System.Drawing.Tests.empty.file</LogicalName>
</EmbeddedResource>
- <EmbeddedResource Include="$(PackagesDir)system.drawing.common.testdata\1.0.3\content\bitmaps\invalid.ico">
+ <EmbeddedResource Include="$(PackagesDir)system.drawing.common.testdata\1.0.6\content\bitmaps\invalid.ico">
<LogicalName>System.Drawing.Tests.invalid.ico</LogicalName>
</EmbeddedResource>
<Compile Include="Printing\MarginsTests.cs" />
@@ -103,4 +109,4 @@
</ProjectReference>
</ItemGroup>
<Import Project="$([MSBuild]::GetDirectoryNameOfFileAbove($(MSBuildThisFileDirectory), dir.targets))\dir.targets" />
-</Project> \ No newline at end of file
+</Project>
diff --git a/src/System.Drawing.Common/tests/SystemFontsTests.cs b/src/System.Drawing.Common/tests/SystemFontsTests.cs
index 5e2029c082..642a06781c 100644
--- a/src/System.Drawing.Common/tests/SystemFontsTests.cs
+++ b/src/System.Drawing.Common/tests/SystemFontsTests.cs
@@ -19,7 +19,6 @@ namespace System.Drawing.Tests
yield return new object[] { (Func<Font>)(() => SystemFonts.StatusFont) };
}
- [ActiveIssue(23690, TestPlatforms.Linux)]
[ConditionalTheory(Helpers.GdiplusIsAvailable)]
[MemberData(nameof(SystemFonts_TestData))]
public void SystemFont_Get_ReturnsExpected(Func<Font> getFont)
@@ -30,7 +29,9 @@ namespace System.Drawing.Tests
Assert.NotNull(font);
Assert.NotNull(otherFont);
Assert.NotSame(font, otherFont);
- Assert.Equal(font, otherFont);
+
+ // Assert.Equal on a font will use the native handle to assert equality, which is not always guaranteed.
+ Assert.Equal(font.Name, otherFont.Name);
}
}
diff --git a/src/System.Drawing.Common/tests/Text/InstalledFontCollectionTests.cs b/src/System.Drawing.Common/tests/Text/InstalledFontCollectionTests.cs
index 97cbc9007e..e35710dd90 100644
--- a/src/System.Drawing.Common/tests/Text/InstalledFontCollectionTests.cs
+++ b/src/System.Drawing.Common/tests/Text/InstalledFontCollectionTests.cs
@@ -7,8 +7,7 @@ namespace System.Drawing.Text.Tests
{
public class InstalledFontCollectionTests
{
- [ActiveIssue(20884, TestPlatforms.AnyUnix)]
- [ConditionalFact(Helpers.GdiplusIsAvailable)]
+ [ConditionalFact(Helpers.GdiPlusIsAvailableNotRedhat73)]
public void Ctor_Default()
{
using (var fontCollection = new InstalledFontCollection())
@@ -17,8 +16,7 @@ namespace System.Drawing.Text.Tests
}
}
- [ActiveIssue(20884, TestPlatforms.AnyUnix)]
- [ConditionalFact(Helpers.GdiplusIsAvailable)]
+ [ConditionalFact(Helpers.GdiPlusIsAvailableNotRedhat73)]
public void Families_GetWhenDisposed_ReturnsNonEmpty()
{
var fontCollection = new InstalledFontCollection();
diff --git a/src/System.Drawing.Common/tests/TextureBrushTests.cs b/src/System.Drawing.Common/tests/TextureBrushTests.cs
index bb93324f0d..02e3e4cc39 100644
--- a/src/System.Drawing.Common/tests/TextureBrushTests.cs
+++ b/src/System.Drawing.Common/tests/TextureBrushTests.cs
@@ -294,7 +294,6 @@ namespace System.Drawing.Tests
AssertExtensions.Throws<ArgumentException>(null, () => new TextureBrush(image, WrapMode.Tile, Rectangle.Empty));
}
- [ActiveIssue(20884, TestPlatforms.AnyUnix)]
[ConditionalTheory(Helpers.GdiplusIsAvailable)]
[InlineData(WrapMode.Tile - 1)]
[InlineData(WrapMode.Clamp + 1)]
@@ -431,7 +430,6 @@ namespace System.Drawing.Tests
}
}
- [ActiveIssue(20884, TestPlatforms.AnyUnix)]
[ConditionalFact(Helpers.GdiplusIsAvailable)]
public void MultiplyTransform_DisposedMatrix_Nop()
{
@@ -662,7 +660,6 @@ namespace System.Drawing.Tests
}
}
- [ActiveIssue(20884, TestPlatforms.AnyUnix)]
[ConditionalFact(Helpers.GdiplusIsAvailable)]
public void Transform_SetNull_ThrowsArgumentNullException()
{
@@ -786,7 +783,6 @@ namespace System.Drawing.Tests
}
}
- [ActiveIssue(20884, TestPlatforms.AnyUnix)]
[ConditionalTheory(Helpers.GdiplusIsAvailable)]
[InlineData(WrapMode.Tile - 1)]
[InlineData(WrapMode.Clamp + 1)]
diff --git a/src/System.Drawing.Common/tests/mono/System.Drawing.Imaging/BmpCodecTests.cs b/src/System.Drawing.Common/tests/mono/System.Drawing.Imaging/BmpCodecTests.cs
new file mode 100644
index 0000000000..1d8dca31c6
--- /dev/null
+++ b/src/System.Drawing.Common/tests/mono/System.Drawing.Imaging/BmpCodecTests.cs
@@ -0,0 +1,540 @@
+// Licensed to the .NET Foundation under one or more agreements.
+// See the LICENSE file in the project root for more information.
+//
+// BMPCodec class testing unit
+//
+// Authors:
+// Jordi Mas i Hernàndez (jordi@ximian.com)
+// Sebastien Pouliot <sebastien@ximian.com>
+//
+// (C) 2004 Ximian, Inc. http://www.ximian.com
+// Copyright (C) 2004-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;
+using System.Drawing;
+using System.Drawing.Imaging;
+using System.IO;
+using Xunit;
+
+namespace MonoTests.System.Drawing.Imaging
+{
+ public class BmpCodecTest
+ {
+ /* Checks bitmap features on a known 1bbp bitmap */
+ [ConditionalFact(Helpers.GdiplusIsAvailable)]
+ public void Bitmap1bitFeatures()
+ {
+ string sInFile = Helpers.GetTestBitmapPath("almogaver1bit.bmp");
+ using (Bitmap bmp = new Bitmap(sInFile))
+ {
+ GraphicsUnit unit = GraphicsUnit.World;
+ RectangleF rect = bmp.GetBounds(ref unit);
+
+ Assert.Equal(PixelFormat.Format4bppIndexed, bmp.PixelFormat);
+ Assert.Equal(173, bmp.Width);
+ Assert.Equal(183, bmp.Height);
+
+ Assert.Equal(0, rect.X);
+ Assert.Equal(0, rect.Y);
+ Assert.Equal(173, rect.Width);
+ Assert.Equal(183, rect.Height);
+
+ Assert.Equal(173, bmp.Size.Width);
+ Assert.Equal(183, bmp.Size.Height);
+ }
+ }
+
+ [ConditionalFact(Helpers.GdiplusIsAvailable)]
+ public void Bitmap1bitPixels()
+ {
+ string sInFile = Helpers.GetTestBitmapPath("almogaver1bit.bmp");
+ using (Bitmap bmp = new Bitmap(sInFile))
+ {
+ // sampling values from a well known bitmap
+ Assert.Equal(-1, bmp.GetPixel(0, 0).ToArgb());
+ Assert.Equal(-4144960, bmp.GetPixel(0, 32).ToArgb());
+ Assert.Equal(-1, bmp.GetPixel(0, 64).ToArgb());
+ Assert.Equal(-1, bmp.GetPixel(0, 96).ToArgb());
+ Assert.Equal(-4144960, bmp.GetPixel(0, 128).ToArgb());
+ Assert.Equal(-1, bmp.GetPixel(0, 160).ToArgb());
+ Assert.Equal(-4144960, bmp.GetPixel(32, 0).ToArgb());
+ Assert.Equal(-4144960, bmp.GetPixel(32, 32).ToArgb());
+ Assert.Equal(-1, bmp.GetPixel(32, 64).ToArgb());
+ Assert.Equal(-4144960, bmp.GetPixel(32, 96).ToArgb());
+ Assert.Equal(-4144960, bmp.GetPixel(32, 128).ToArgb());
+ Assert.Equal(-8355712, bmp.GetPixel(32, 160).ToArgb());
+ Assert.Equal(-16777216, bmp.GetPixel(64, 0).ToArgb());
+ Assert.Equal(-8355712, bmp.GetPixel(64, 32).ToArgb());
+ Assert.Equal(-1, bmp.GetPixel(64, 64).ToArgb());
+ Assert.Equal(-16777216, bmp.GetPixel(64, 96).ToArgb());
+ Assert.Equal(-8355840, bmp.GetPixel(64, 128).ToArgb());
+ Assert.Equal(-16777216, bmp.GetPixel(64, 160).ToArgb());
+ Assert.Equal(-4144960, bmp.GetPixel(96, 0).ToArgb());
+ Assert.Equal(-8355712, bmp.GetPixel(96, 32).ToArgb());
+ Assert.Equal(-16777216, bmp.GetPixel(96, 64).ToArgb());
+ Assert.Equal(-4144960, bmp.GetPixel(96, 96).ToArgb());
+ Assert.Equal(-8355840, bmp.GetPixel(96, 128).ToArgb());
+ Assert.Equal(-16777216, bmp.GetPixel(96, 160).ToArgb());
+ Assert.Equal(-1, bmp.GetPixel(128, 0).ToArgb());
+ Assert.Equal(-8355712, bmp.GetPixel(128, 32).ToArgb());
+ Assert.Equal(-1, bmp.GetPixel(128, 64).ToArgb());
+ Assert.Equal(-4144960, bmp.GetPixel(128, 96).ToArgb());
+ Assert.Equal(-16777216, bmp.GetPixel(128, 128).ToArgb());
+ Assert.Equal(-4144960, bmp.GetPixel(128, 160).ToArgb());
+ Assert.Equal(-4144960, bmp.GetPixel(160, 0).ToArgb());
+ Assert.Equal(-1, bmp.GetPixel(160, 32).ToArgb());
+ Assert.Equal(-4144960, bmp.GetPixel(160, 64).ToArgb());
+ Assert.Equal(-4144960, bmp.GetPixel(160, 96).ToArgb());
+ Assert.Equal(-4144960, bmp.GetPixel(160, 128).ToArgb());
+ Assert.Equal(-8355712, bmp.GetPixel(160, 160).ToArgb());
+ }
+ }
+
+ /* Checks bitmap features on a known 8bbp bitmap */
+ [ConditionalFact(Helpers.GdiplusIsAvailable)]
+ public void Bitmap8bitFeatures()
+ {
+ string sInFile = Helpers.GetTestBitmapPath("almogaver8bits.bmp");
+ using (Bitmap bmp = new Bitmap(sInFile))
+ {
+ GraphicsUnit unit = GraphicsUnit.World;
+ RectangleF rect = bmp.GetBounds(ref unit);
+
+ Assert.Equal(PixelFormat.Format8bppIndexed, bmp.PixelFormat);
+ Assert.Equal(173, bmp.Width);
+ Assert.Equal(183, bmp.Height);
+
+ Assert.Equal(0, rect.X);
+ Assert.Equal(0, rect.Y);
+ Assert.Equal(173, rect.Width);
+ Assert.Equal(183, rect.Height);
+
+ Assert.Equal(173, bmp.Size.Width);
+ Assert.Equal(183, bmp.Size.Height);
+ }
+ }
+
+ [ConditionalFact(Helpers.GdiplusIsAvailable)]
+ public void Bitmap8bitPixels()
+ {
+ string sInFile = Helpers.GetTestBitmapPath("almogaver8bits.bmp");
+ using (Bitmap bmp = new Bitmap(sInFile))
+ {
+ // sampling values from a well known bitmap
+ Assert.Equal(-1040, bmp.GetPixel(0, 0).ToArgb());
+ Assert.Equal(-4137792, bmp.GetPixel(0, 32).ToArgb());
+ Assert.Equal(-1040, bmp.GetPixel(0, 64).ToArgb());
+ Assert.Equal(-1040, bmp.GetPixel(0, 96).ToArgb());
+ Assert.Equal(-4137792, bmp.GetPixel(0, 128).ToArgb());
+ Assert.Equal(-1040, bmp.GetPixel(0, 160).ToArgb());
+ Assert.Equal(-4137792, bmp.GetPixel(32, 0).ToArgb());
+ Assert.Equal(-4137792, bmp.GetPixel(32, 32).ToArgb());
+ Assert.Equal(-1040, bmp.GetPixel(32, 64).ToArgb());
+ Assert.Equal(-4144960, bmp.GetPixel(32, 96).ToArgb());
+ Assert.Equal(-6250304, bmp.GetPixel(32, 128).ToArgb());
+ Assert.Equal(-8355712, bmp.GetPixel(32, 160).ToArgb());
+ Assert.Equal(-12566464, bmp.GetPixel(64, 0).ToArgb());
+ Assert.Equal(-6258560, bmp.GetPixel(64, 32).ToArgb());
+ Assert.Equal(-1040, bmp.GetPixel(64, 64).ToArgb());
+ Assert.Equal(-16777216, bmp.GetPixel(64, 96).ToArgb());
+ Assert.Equal(-8355776, bmp.GetPixel(64, 128).ToArgb());
+ Assert.Equal(-16777216, bmp.GetPixel(64, 160).ToArgb());
+ Assert.Equal(-4137792, bmp.GetPixel(96, 0).ToArgb());
+ Assert.Equal(-8355712, bmp.GetPixel(96, 32).ToArgb());
+ Assert.Equal(-12566464, bmp.GetPixel(96, 64).ToArgb());
+ Assert.Equal(-2039680, bmp.GetPixel(96, 96).ToArgb());
+ Assert.Equal(-4153280, bmp.GetPixel(96, 128).ToArgb());
+ Assert.Equal(-12566464, bmp.GetPixel(96, 160).ToArgb());
+ Assert.Equal(-1040, bmp.GetPixel(128, 0).ToArgb());
+ Assert.Equal(-6258560, bmp.GetPixel(128, 32).ToArgb());
+ Assert.Equal(-1040, bmp.GetPixel(128, 64).ToArgb());
+ Assert.Equal(-4144960, bmp.GetPixel(128, 96).ToArgb());
+ Assert.Equal(-12566464, bmp.GetPixel(128, 128).ToArgb());
+ Assert.Equal(-4144960, bmp.GetPixel(128, 160).ToArgb());
+ Assert.Equal(-4137792, bmp.GetPixel(160, 0).ToArgb());
+ Assert.Equal(-1040, bmp.GetPixel(160, 32).ToArgb());
+ Assert.Equal(-4144960, bmp.GetPixel(160, 64).ToArgb());
+ Assert.Equal(-4137792, bmp.GetPixel(160, 96).ToArgb());
+ Assert.Equal(-4137792, bmp.GetPixel(160, 128).ToArgb());
+ Assert.Equal(-8355712, bmp.GetPixel(160, 160).ToArgb());
+ }
+ }
+
+ /* Checks bitmap features on a known 24-bits bitmap */
+ [ConditionalFact(Helpers.GdiplusIsAvailable)]
+ public void Bitmap24bitFeatures()
+ {
+ string sInFile = Helpers.GetTestBitmapPath("almogaver24bits.bmp");
+ using (Bitmap bmp = new Bitmap(sInFile))
+ {
+ GraphicsUnit unit = GraphicsUnit.World;
+ RectangleF rect = bmp.GetBounds(ref unit);
+
+ Assert.Equal(PixelFormat.Format24bppRgb, bmp.PixelFormat);
+ Assert.Equal(173, bmp.Width);
+ Assert.Equal(183, bmp.Height);
+
+ Assert.Equal(0, rect.X);
+ Assert.Equal(0, rect.Y);
+ Assert.Equal(173, rect.Width);
+ Assert.Equal(183, rect.Height);
+
+ Assert.Equal(173, bmp.Size.Width);
+ Assert.Equal(183, bmp.Size.Height);
+ }
+ }
+
+ [ConditionalFact(Helpers.GdiplusIsAvailable)]
+ public void Bitmap24bitPixels()
+ {
+ string sInFile = Helpers.GetTestBitmapPath("almogaver24bits.bmp");
+ using (Bitmap bmp = new Bitmap(sInFile))
+ {
+ // sampling values from a well known bitmap
+ Assert.Equal(-1645353, bmp.GetPixel(0, 32).ToArgb());
+ Assert.Equal(-461332, bmp.GetPixel(0, 64).ToArgb());
+ Assert.Equal(-330005, bmp.GetPixel(0, 96).ToArgb());
+ Assert.Equal(-2237489, bmp.GetPixel(0, 128).ToArgb());
+ Assert.Equal(-1251105, bmp.GetPixel(0, 160).ToArgb());
+ Assert.Equal(-3024947, bmp.GetPixel(32, 0).ToArgb());
+ Assert.Equal(-2699070, bmp.GetPixel(32, 32).ToArgb());
+ Assert.Equal(-2366734, bmp.GetPixel(32, 64).ToArgb());
+ Assert.Equal(-4538413, bmp.GetPixel(32, 96).ToArgb());
+ Assert.Equal(-6116681, bmp.GetPixel(32, 128).ToArgb());
+ Assert.Equal(-7369076, bmp.GetPixel(32, 160).ToArgb());
+ Assert.Equal(-13024729, bmp.GetPixel(64, 0).ToArgb());
+ Assert.Equal(-7174020, bmp.GetPixel(64, 32).ToArgb());
+ Assert.Equal(-51, bmp.GetPixel(64, 64).ToArgb());
+ Assert.Equal(-16053503, bmp.GetPixel(64, 96).ToArgb());
+ Assert.Equal(-8224431, bmp.GetPixel(64, 128).ToArgb());
+ Assert.Equal(-16579326, bmp.GetPixel(64, 160).ToArgb());
+ Assert.Equal(-2502457, bmp.GetPixel(96, 0).ToArgb());
+ Assert.Equal(-9078395, bmp.GetPixel(96, 32).ToArgb());
+ Assert.Equal(-12696508, bmp.GetPixel(96, 64).ToArgb());
+ Assert.Equal(-70772, bmp.GetPixel(96, 96).ToArgb());
+ Assert.Equal(-4346279, bmp.GetPixel(96, 128).ToArgb());
+ Assert.Equal(-11583193, bmp.GetPixel(96, 160).ToArgb());
+ Assert.Equal(-724763, bmp.GetPixel(128, 0).ToArgb());
+ Assert.Equal(-7238268, bmp.GetPixel(128, 32).ToArgb());
+ Assert.Equal(-2169612, bmp.GetPixel(128, 64).ToArgb());
+ Assert.Equal(-3683883, bmp.GetPixel(128, 96).ToArgb());
+ Assert.Equal(-12892867, bmp.GetPixel(128, 128).ToArgb());
+ Assert.Equal(-3750464, bmp.GetPixel(128, 160).ToArgb());
+ Assert.Equal(-3222844, bmp.GetPixel(160, 0).ToArgb());
+ Assert.Equal(-65806, bmp.GetPixel(160, 32).ToArgb());
+ Assert.Equal(-2961726, bmp.GetPixel(160, 64).ToArgb());
+ Assert.Equal(-2435382, bmp.GetPixel(160, 96).ToArgb());
+ Assert.Equal(-2501944, bmp.GetPixel(160, 128).ToArgb());
+ Assert.Equal(-9211799, bmp.GetPixel(160, 160).ToArgb());
+ }
+ }
+
+ [ConditionalFact(Helpers.GdiplusIsAvailable)]
+ public void Bitmap24bitData()
+ {
+ string sInFile = Helpers.GetTestBitmapPath("almogaver24bits.bmp");
+ using (Bitmap bmp = new Bitmap(sInFile))
+ {
+ Assert.Equal(-3355456, bmp.GetPixel(163, 1).ToArgb());
+ BitmapData data = bmp.LockBits(new Rectangle(0, 0, bmp.Width, bmp.Height), ImageLockMode.ReadOnly, PixelFormat.Format24bppRgb);
+ try
+ {
+ Assert.Equal(bmp.Height, data.Height);
+ Assert.Equal(bmp.Width, data.Width);
+ Assert.Equal(PixelFormat.Format24bppRgb, data.PixelFormat);
+ Assert.Equal(520, data.Stride);
+ Assert.Equal(183, data.Height);
+
+ unsafe
+ {
+ byte* scan = (byte*)data.Scan0;
+ // sampling values from a well known bitmap
+ Assert.Equal(217, *(scan + 0));
+ Assert.Equal(192, *(scan + 1009));
+ Assert.Equal(210, *(scan + 2018));
+ Assert.Equal(196, *(scan + 3027));
+ Assert.Equal(216, *(scan + 4036));
+ Assert.Equal(215, *(scan + 5045));
+ Assert.Equal(218, *(scan + 6054));
+ Assert.Equal(218, *(scan + 7063));
+ Assert.Equal(95, *(scan + 8072));
+ Assert.Equal(9, *(scan + 9081));
+ Assert.Equal(247, *(scan + 10090));
+ Assert.Equal(161, *(scan + 11099));
+ Assert.Equal(130, *(scan + 12108));
+ Assert.Equal(131, *(scan + 13117));
+ Assert.Equal(175, *(scan + 14126));
+ Assert.Equal(217, *(scan + 15135));
+ Assert.Equal(201, *(scan + 16144));
+ Assert.Equal(183, *(scan + 17153));
+ Assert.Equal(236, *(scan + 18162));
+ Assert.Equal(242, *(scan + 19171));
+ Assert.Equal(125, *(scan + 20180));
+ Assert.Equal(193, *(scan + 21189));
+ Assert.Equal(227, *(scan + 22198));
+ Assert.Equal(44, *(scan + 23207));
+ Assert.Equal(230, *(scan + 24216));
+ Assert.Equal(224, *(scan + 25225));
+ Assert.Equal(164, *(scan + 26234));
+ Assert.Equal(43, *(scan + 27243));
+ Assert.Equal(200, *(scan + 28252));
+ Assert.Equal(255, *(scan + 29261));
+ Assert.Equal(226, *(scan + 30270));
+ Assert.Equal(230, *(scan + 31279));
+ Assert.Equal(178, *(scan + 32288));
+ Assert.Equal(224, *(scan + 33297));
+ Assert.Equal(233, *(scan + 34306));
+ Assert.Equal(212, *(scan + 35315));
+ Assert.Equal(153, *(scan + 36324));
+ Assert.Equal(143, *(scan + 37333));
+ Assert.Equal(215, *(scan + 38342));
+ Assert.Equal(116, *(scan + 39351));
+ Assert.Equal(26, *(scan + 40360));
+ Assert.Equal(28, *(scan + 41369));
+ Assert.Equal(75, *(scan + 42378));
+ Assert.Equal(50, *(scan + 43387));
+ Assert.Equal(244, *(scan + 44396));
+ Assert.Equal(191, *(scan + 45405));
+ Assert.Equal(200, *(scan + 46414));
+ Assert.Equal(197, *(scan + 47423));
+ Assert.Equal(232, *(scan + 48432));
+ Assert.Equal(186, *(scan + 49441));
+ Assert.Equal(210, *(scan + 50450));
+ Assert.Equal(215, *(scan + 51459));
+ Assert.Equal(155, *(scan + 52468));
+ Assert.Equal(56, *(scan + 53477));
+ Assert.Equal(149, *(scan + 54486));
+ Assert.Equal(137, *(scan + 55495));
+ Assert.Equal(141, *(scan + 56504));
+ Assert.Equal(36, *(scan + 57513));
+ Assert.Equal(39, *(scan + 58522));
+ Assert.Equal(25, *(scan + 59531));
+ Assert.Equal(44, *(scan + 60540));
+ Assert.Equal(12, *(scan + 61549));
+ Assert.Equal(161, *(scan + 62558));
+ Assert.Equal(179, *(scan + 63567));
+ Assert.Equal(181, *(scan + 64576));
+ Assert.Equal(165, *(scan + 65585));
+ Assert.Equal(182, *(scan + 66594));
+ Assert.Equal(186, *(scan + 67603));
+ Assert.Equal(201, *(scan + 68612));
+ Assert.Equal(49, *(scan + 69621));
+ Assert.Equal(161, *(scan + 70630));
+ Assert.Equal(140, *(scan + 71639));
+ Assert.Equal(2, *(scan + 72648));
+ Assert.Equal(15, *(scan + 73657));
+ Assert.Equal(33, *(scan + 74666));
+ Assert.Equal(17, *(scan + 75675));
+ Assert.Equal(0, *(scan + 76684));
+ Assert.Equal(47, *(scan + 77693));
+ Assert.Equal(4, *(scan + 78702));
+ Assert.Equal(142, *(scan + 79711));
+ Assert.Equal(151, *(scan + 80720));
+ Assert.Equal(124, *(scan + 81729));
+ Assert.Equal(81, *(scan + 82738));
+ Assert.Equal(214, *(scan + 83747));
+ Assert.Equal(217, *(scan + 84756));
+ Assert.Equal(30, *(scan + 85765));
+ Assert.Equal(185, *(scan + 86774));
+ Assert.Equal(200, *(scan + 87783));
+ Assert.Equal(37, *(scan + 88792));
+ Assert.Equal(2, *(scan + 89801));
+ Assert.Equal(41, *(scan + 90810));
+ Assert.Equal(16, *(scan + 91819));
+ Assert.Equal(0, *(scan + 92828));
+ Assert.Equal(146, *(scan + 93837));
+ Assert.Equal(163, *(scan + 94846));
+ }
+ }
+ finally
+ {
+ bmp.UnlockBits(data);
+ }
+ }
+ }
+
+ /* Checks bitmap features on a known 32-bits bitmap (codec)*/
+ [ConditionalFact(Helpers.GdiplusIsAvailable)]
+ public void Bitmap32bitFeatures()
+ {
+ string sInFile = Helpers.GetTestBitmapPath("almogaver32bits.bmp");
+ using (Bitmap bmp = new Bitmap(sInFile))
+ {
+ GraphicsUnit unit = GraphicsUnit.World;
+ RectangleF rect = bmp.GetBounds(ref unit);
+
+ Assert.Equal(173, bmp.Width);
+ Assert.Equal(183, bmp.Height);
+
+ Assert.Equal(0, rect.X);
+ Assert.Equal(0, rect.Y);
+ Assert.Equal(173, rect.Width);
+ Assert.Equal(183, rect.Height);
+
+ Assert.Equal(173, bmp.Size.Width);
+ Assert.Equal(183, bmp.Size.Height);
+ }
+ }
+
+ [ConditionalFact(Helpers.GdiplusIsAvailable)]
+ public void Bitmap32bitPixels()
+ {
+ string sInFile = Helpers.GetTestBitmapPath("almogaver32bits.bmp");
+ using (Bitmap bmp = new Bitmap(sInFile))
+ {
+ Assert.Equal(PixelFormat.Format32bppRgb, bmp.PixelFormat);
+ // sampling values from a well known bitmap
+ Assert.Equal(-1579559, bmp.GetPixel(0, 0).ToArgb());
+ Assert.Equal(-1645353, bmp.GetPixel(0, 32).ToArgb());
+ Assert.Equal(-461332, bmp.GetPixel(0, 64).ToArgb());
+ Assert.Equal(-330005, bmp.GetPixel(0, 96).ToArgb());
+ Assert.Equal(-2237489, bmp.GetPixel(0, 128).ToArgb());
+ Assert.Equal(-1251105, bmp.GetPixel(0, 160).ToArgb());
+ Assert.Equal(-3024947, bmp.GetPixel(32, 0).ToArgb());
+ Assert.Equal(-2699070, bmp.GetPixel(32, 32).ToArgb());
+ Assert.Equal(-2366734, bmp.GetPixel(32, 64).ToArgb());
+ Assert.Equal(-4538413, bmp.GetPixel(32, 96).ToArgb());
+ Assert.Equal(-6116681, bmp.GetPixel(32, 128).ToArgb());
+ Assert.Equal(-7369076, bmp.GetPixel(32, 160).ToArgb());
+ Assert.Equal(-13024729, bmp.GetPixel(64, 0).ToArgb());
+ Assert.Equal(-7174020, bmp.GetPixel(64, 32).ToArgb());
+ Assert.Equal(-51, bmp.GetPixel(64, 64).ToArgb());
+ Assert.Equal(-16053503, bmp.GetPixel(64, 96).ToArgb());
+ Assert.Equal(-8224431, bmp.GetPixel(64, 128).ToArgb());
+ Assert.Equal(-16579326, bmp.GetPixel(64, 160).ToArgb());
+ Assert.Equal(-2502457, bmp.GetPixel(96, 0).ToArgb());
+ Assert.Equal(-9078395, bmp.GetPixel(96, 32).ToArgb());
+ Assert.Equal(-12696508, bmp.GetPixel(96, 64).ToArgb());
+ Assert.Equal(-70772, bmp.GetPixel(96, 96).ToArgb());
+ Assert.Equal(-4346279, bmp.GetPixel(96, 128).ToArgb());
+ Assert.Equal(-11583193, bmp.GetPixel(96, 160).ToArgb());
+ Assert.Equal(-724763, bmp.GetPixel(128, 0).ToArgb());
+ Assert.Equal(-7238268, bmp.GetPixel(128, 32).ToArgb());
+ Assert.Equal(-2169612, bmp.GetPixel(128, 64).ToArgb());
+ Assert.Equal(-3683883, bmp.GetPixel(128, 96).ToArgb());
+ Assert.Equal(-12892867, bmp.GetPixel(128, 128).ToArgb());
+ Assert.Equal(-3750464, bmp.GetPixel(128, 160).ToArgb());
+ Assert.Equal(-3222844, bmp.GetPixel(160, 0).ToArgb());
+ Assert.Equal(-65806, bmp.GetPixel(160, 32).ToArgb());
+ Assert.Equal(-2961726, bmp.GetPixel(160, 64).ToArgb());
+ Assert.Equal(-2435382, bmp.GetPixel(160, 96).ToArgb());
+ Assert.Equal(-2501944, bmp.GetPixel(160, 128).ToArgb());
+ Assert.Equal(-9211799, bmp.GetPixel(160, 160).ToArgb());
+ }
+ }
+
+ private void Save(PixelFormat original, PixelFormat expected, bool colorCheck)
+ {
+ string sOutFile = $"linerect-{expected}.bmp";
+
+ // Save
+ Bitmap bmp = new Bitmap(100, 100, original);
+ Graphics gr = Graphics.FromImage(bmp);
+
+ using (Pen p = new Pen(Color.BlueViolet, 2))
+ {
+ gr.DrawLine(p, 10.0F, 10.0F, 90.0F, 90.0F);
+ gr.DrawRectangle(p, 10.0F, 10.0F, 80.0F, 80.0F);
+ }
+
+ try
+ {
+ bmp.Save(sOutFile, ImageFormat.Bmp);
+
+ // Load
+ using (Bitmap bmpLoad = new Bitmap(sOutFile))
+ {
+ Assert.Equal(expected, bmpLoad.PixelFormat);
+ if (colorCheck)
+ {
+ Color color = bmpLoad.GetPixel(10, 10);
+ Assert.Equal(Color.FromArgb(255, 138, 43, 226), color);
+ }
+ }
+ }
+ finally
+ {
+ gr.Dispose();
+ bmp.Dispose();
+ try
+ {
+ File.Delete(sOutFile);
+ }
+ catch
+ {
+ }
+ }
+ }
+
+ [ConditionalFact(Helpers.RecentGdiplusIsAvailable)]
+ public void Save_24bppRgb()
+ {
+ Save(PixelFormat.Format24bppRgb, PixelFormat.Format24bppRgb, true);
+ }
+
+ [ConditionalFact(Helpers.RecentGdiplusIsAvailable)]
+ public void Save_32bppRgb()
+ {
+ Save(PixelFormat.Format32bppRgb, PixelFormat.Format32bppRgb, true);
+ }
+
+ [ConditionalFact(Helpers.RecentGdiplusIsAvailable)]
+ public void Save_32bppArgb()
+ {
+ Save(PixelFormat.Format32bppArgb, PixelFormat.Format32bppRgb, true);
+ }
+
+ [ConditionalFact(Helpers.RecentGdiplusIsAvailable)]
+ public void Save_32bppPArgb()
+ {
+ Save(PixelFormat.Format32bppPArgb, PixelFormat.Format32bppRgb, true);
+ }
+
+ [ConditionalFact(Helpers.GdiplusIsAvailable)]
+ public void NonInvertedBitmap()
+ {
+ // regression check against http://bugzilla.ximian.com/show_bug.cgi?id=80751
+ string sInFile = Helpers.GetTestBitmapPath("non-inverted.bmp");
+ using (Bitmap bmp = new Bitmap(sInFile))
+ {
+ GraphicsUnit unit = GraphicsUnit.World;
+ RectangleF rect = bmp.GetBounds(ref unit);
+
+ Assert.Equal(90, bmp.Width);
+ Assert.Equal(60, bmp.Height);
+
+ Assert.Equal(0, rect.X);
+ Assert.Equal(0, rect.Y);
+ Assert.Equal(90, rect.Width);
+ Assert.Equal(60, rect.Height);
+
+ Assert.Equal(90, bmp.Size.Width);
+ Assert.Equal(60, bmp.Size.Height);
+
+ // sampling values from a well known bitmap
+ Assert.Equal(-16777216, bmp.GetPixel(12, 21).ToArgb());
+ Assert.Equal(-1, bmp.GetPixel(21, 37).ToArgb());
+ }
+ }
+ }
+}
diff --git a/src/System.Drawing.Common/tests/mono/System.Drawing.Imaging/GifCodecTests.cs b/src/System.Drawing.Common/tests/mono/System.Drawing.Imaging/GifCodecTests.cs
new file mode 100644
index 0000000000..6f854bf00b
--- /dev/null
+++ b/src/System.Drawing.Common/tests/mono/System.Drawing.Imaging/GifCodecTests.cs
@@ -0,0 +1,266 @@
+// Licensed to the .NET Foundation under one or more agreements.
+// See the LICENSE file in the project root for more information.
+//
+// GIF Codec class testing unit
+//
+// Authors:
+// Jordi Mas i Hernàndez (jordi@ximian.com)
+// Sebastien Pouliot <sebastien@ximian.com>
+//
+// 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.Drawing;
+using System.Drawing.Imaging;
+using System.IO;
+using Xunit;
+
+namespace MonoTests.System.Drawing.Imaging
+{
+ public class GifCodecTest
+ {
+ /* Checks bitmap features on a known 1bbp bitmap */
+ private void Bitmap8bitsFeatures(string filename)
+ {
+ using (Bitmap bmp = new Bitmap(filename))
+ {
+ GraphicsUnit unit = GraphicsUnit.World;
+ RectangleF rect = bmp.GetBounds(ref unit);
+
+ Assert.Equal(PixelFormat.Format8bppIndexed, bmp.PixelFormat);
+ Assert.Equal(110, bmp.Width);
+ Assert.Equal(100, bmp.Height);
+
+ Assert.Equal(0, rect.X);
+ Assert.Equal(0, rect.Y);
+ Assert.Equal(110, rect.Width);
+ Assert.Equal(100, rect.Height);
+
+ Assert.Equal(110, bmp.Size.Width);
+ Assert.Equal(100, bmp.Size.Height);
+ }
+ }
+
+ [ConditionalFact(Helpers.GdiplusIsAvailable)]
+ public void Bitmap8bitsFeatures_Gif89()
+ {
+ Bitmap8bitsFeatures(Helpers.GetTestBitmapPath("nature24bits.gif"));
+ }
+
+ [ConditionalFact(Helpers.GdiplusIsAvailable)]
+ public void Bitmap8bitsFeatures_Gif87()
+ {
+ Bitmap8bitsFeatures(Helpers.GetTestBitmapPath("nature24bits87.gif"));
+ }
+
+ private void Bitmap8bitsPixels(string filename)
+ {
+ using (Bitmap bmp = new Bitmap(filename))
+ {
+ // sampling values from a well known bitmap
+ Assert.Equal(-10644802, bmp.GetPixel(0, 0).ToArgb());
+ Assert.Equal(-12630705, bmp.GetPixel(0, 32).ToArgb());
+ Assert.Equal(-14537409, bmp.GetPixel(0, 64).ToArgb());
+ Assert.Equal(-14672099, bmp.GetPixel(0, 96).ToArgb());
+ Assert.Equal(-526863, bmp.GetPixel(32, 0).ToArgb());
+ Assert.Equal(-10263970, bmp.GetPixel(32, 32).ToArgb());
+ Assert.Equal(-10461317, bmp.GetPixel(32, 64).ToArgb());
+ Assert.Equal(-9722415, bmp.GetPixel(32, 96).ToArgb());
+ Assert.Equal(-131076, bmp.GetPixel(64, 0).ToArgb());
+ Assert.Equal(-2702435, bmp.GetPixel(64, 32).ToArgb());
+ Assert.Equal(-6325922, bmp.GetPixel(64, 64).ToArgb());
+ Assert.Equal(-12411924, bmp.GetPixel(64, 96).ToArgb());
+ Assert.Equal(-131076, bmp.GetPixel(96, 0).ToArgb());
+ Assert.Equal(-7766649, bmp.GetPixel(96, 32).ToArgb());
+ Assert.Equal(-11512986, bmp.GetPixel(96, 64).ToArgb());
+ Assert.Equal(-12616230, bmp.GetPixel(96, 96).ToArgb());
+ }
+ }
+
+ [ConditionalFact(Helpers.GdiplusIsAvailable)]
+ public void Bitmap8bitsPixels_Gif89()
+ {
+ Bitmap8bitsPixels(Helpers.GetTestBitmapPath("nature24bits.gif"));
+ }
+
+ [ConditionalFact(Helpers.GdiplusIsAvailable)]
+ public void Bitmap8bitsPixels_Gif87()
+ {
+ Bitmap8bitsPixels(Helpers.GetTestBitmapPath("nature24bits87.gif"));
+ }
+
+ [ConditionalFact(Helpers.GdiplusIsAvailable)]
+ public void Bitmap8bitsData()
+ {
+ string sInFile = Helpers.GetTestBitmapPath("nature24bits.gif");
+ using (Bitmap bmp = new Bitmap(sInFile))
+ {
+ BitmapData data = bmp.LockBits(new Rectangle(0, 0, bmp.Width, bmp.Height), ImageLockMode.ReadOnly, PixelFormat.Format24bppRgb);
+ try
+ {
+ Assert.Equal(bmp.Height, data.Height);
+ Assert.Equal(bmp.Width, data.Width);
+ Assert.Equal(PixelFormat.Format24bppRgb, data.PixelFormat);
+ Assert.Equal(332, data.Stride);
+ Assert.Equal(100, data.Height);
+
+ unsafe
+ {
+ byte* scan = (byte*)data.Scan0;
+ // sampling values from a well known bitmap
+ Assert.Equal(190, *(scan + 0));
+ Assert.Equal(217, *(scan + 1009));
+ Assert.Equal(120, *(scan + 2018));
+ Assert.Equal(253, *(scan + 3027));
+ Assert.Equal(233, *(scan + 4036));
+ Assert.Equal(176, *(scan + 5045));
+ Assert.Equal(151, *(scan + 6054));
+ Assert.Equal(220, *(scan + 7063));
+ Assert.Equal(139, *(scan + 8072));
+ Assert.Equal(121, *(scan + 9081));
+ Assert.Equal(160, *(scan + 10090));
+ Assert.Equal(92, *(scan + 11099));
+ Assert.Equal(96, *(scan + 12108));
+ Assert.Equal(64, *(scan + 13117));
+ Assert.Equal(156, *(scan + 14126));
+ Assert.Equal(68, *(scan + 15135));
+ Assert.Equal(156, *(scan + 16144));
+ Assert.Equal(84, *(scan + 17153));
+ Assert.Equal(55, *(scan + 18162));
+ Assert.Equal(68, *(scan + 19171));
+ Assert.Equal(116, *(scan + 20180));
+ Assert.Equal(61, *(scan + 21189));
+ Assert.Equal(69, *(scan + 22198));
+ Assert.Equal(75, *(scan + 23207));
+ Assert.Equal(61, *(scan + 24216));
+ Assert.Equal(66, *(scan + 25225));
+ Assert.Equal(40, *(scan + 26234));
+ Assert.Equal(55, *(scan + 27243));
+ Assert.Equal(53, *(scan + 28252));
+ Assert.Equal(215, *(scan + 29261));
+ Assert.Equal(99, *(scan + 30270));
+ Assert.Equal(67, *(scan + 31279));
+ Assert.Equal(142, *(scan + 32288));
+ }
+ }
+ finally
+ {
+ bmp.UnlockBits(data);
+ }
+ }
+ }
+
+ [ConditionalFact(Helpers.GdiplusIsAvailable)]
+ public void Interlaced()
+ {
+ string sInFile = Helpers.GetTestBitmapPath("81773-interlaced.gif");
+ using (Bitmap bmp = new Bitmap(sInFile))
+ {
+ for (int i = 0; i < 255; i++)
+ {
+ Color c = bmp.GetPixel(0, i);
+ Assert.Equal(255, c.A);
+ Assert.Equal(i, c.R);
+ Assert.Equal(i, c.G);
+ Assert.Equal(i, c.B);
+ }
+ }
+ }
+
+ private void Save(PixelFormat original, PixelFormat expected, bool exactColorCheck)
+ {
+ string sOutFile = $"linerect-{expected}.gif";
+
+ // Save
+ Bitmap bmp = new Bitmap(100, 100, original);
+ Graphics gr = Graphics.FromImage(bmp);
+
+ using (Pen p = new Pen(Color.Red, 2))
+ {
+ gr.DrawLine(p, 10.0F, 10.0F, 90.0F, 90.0F);
+ gr.DrawRectangle(p, 10.0F, 10.0F, 80.0F, 80.0F);
+ }
+
+ try
+ {
+ bmp.Save(sOutFile, ImageFormat.Gif);
+
+ // Load
+ using (Bitmap bmpLoad = new Bitmap(sOutFile))
+ {
+ Assert.Equal(expected, bmpLoad.PixelFormat);
+ Color color = bmpLoad.GetPixel(10, 10);
+ if (exactColorCheck)
+ {
+ Assert.Equal(Color.FromArgb(255, 255, 0, 0), color);
+ }
+ else
+ {
+ // FIXME: we don't save a pure red (F8 instead of FF) into the file so the color-check assert will fail
+ // this is due to libgif's QuantizeBuffer. An alternative would be to make our own that checks if less than 256 colors
+ // are used in the bitmap (or else use QuantizeBuffer).
+ Assert.Equal(255, color.A);
+ Assert.True(color.R >= 248);
+ Assert.Equal(0, color.G);
+ Assert.Equal(0, color.B);
+ }
+ }
+ }
+ finally
+ {
+ gr.Dispose();
+ bmp.Dispose();
+ try
+ {
+ File.Delete(sOutFile);
+ }
+ catch
+ {
+ }
+ }
+ }
+
+ [ConditionalFact(Helpers.RecentGdiplusIsAvailable)]
+ public void Save_24bppRgb()
+ {
+ Save(PixelFormat.Format24bppRgb, PixelFormat.Format8bppIndexed, false);
+ }
+
+ [ConditionalFact(Helpers.RecentGdiplusIsAvailable)]
+ public void Save_32bppRgb()
+ {
+ Save(PixelFormat.Format32bppRgb, PixelFormat.Format8bppIndexed, false);
+ }
+
+ [ConditionalFact(Helpers.RecentGdiplusIsAvailable)]
+ public void Save_32bppArgb()
+ {
+ Save(PixelFormat.Format32bppArgb, PixelFormat.Format8bppIndexed, false);
+ }
+
+ [ConditionalFact(Helpers.RecentGdiplusIsAvailable)]
+ public void Save_32bppPArgb()
+ {
+ Save(PixelFormat.Format32bppPArgb, PixelFormat.Format8bppIndexed, false);
+ }
+ }
+}
diff --git a/src/System.Drawing.Common/tests/mono/System.Drawing.Imaging/IconCodecTests.cs b/src/System.Drawing.Common/tests/mono/System.Drawing.Imaging/IconCodecTests.cs
new file mode 100644
index 0000000000..af810fb9fe
--- /dev/null
+++ b/src/System.Drawing.Common/tests/mono/System.Drawing.Imaging/IconCodecTests.cs
@@ -0,0 +1,2103 @@
+// Licensed to the .NET Foundation under one or more agreements.
+// See the LICENSE file in the project root for more information.
+//
+// ICO Codec class testing unit
+//
+// Authors:
+// Jordi Mas i Hernàndez (jordi@ximian.com)
+// Sebastien Pouliot <sebastien@ximian.com>
+//
+// 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.Drawing;
+using System.Drawing.Imaging;
+using System.IO;
+using Xunit;
+
+namespace MonoTests.System.Drawing.Imaging
+{
+
+ public class IconCodecTest
+ {
+ [ConditionalFact(Helpers.RecentGdiplusIsAvailable)]
+ public void Image16()
+ {
+ string sInFile = Helpers.GetTestBitmapPath("16x16_one_entry_4bit.ico");
+ using (Image image = Image.FromFile(sInFile))
+ {
+ Assert.True(image.RawFormat.Equals(ImageFormat.Icon));
+ // note that image is "promoted" to 32bits
+ Assert.Equal(PixelFormat.Format32bppArgb, image.PixelFormat);
+ Assert.Equal(73746, image.Flags);
+
+ using (Bitmap bmp = new Bitmap(image))
+ {
+ Assert.True(bmp.RawFormat.Equals(ImageFormat.MemoryBmp));
+ Assert.Equal(PixelFormat.Format32bppArgb, bmp.PixelFormat);
+ Assert.Equal(2, bmp.Flags);
+ Assert.Equal(0, bmp.Palette.Entries.Length);
+ }
+ }
+ }
+
+ [PlatformSpecific(TestPlatforms.AnyUnix)]
+ [ConditionalFact(Helpers.RecentGdiplusIsAvailable)]
+ public void Image16_PaletteEntries_Unix()
+ {
+ string sInFile = Helpers.GetTestBitmapPath("16x16_one_entry_4bit.ico");
+ using (Image image = Image.FromFile(sInFile))
+ {
+ // The values are inconsistent across Windows & Unix: GDI+ returns 0, libgdiplus returns 16.
+ Assert.Equal(16, image.Palette.Entries.Length);
+ }
+ }
+
+ [PlatformSpecific(TestPlatforms.Windows)]
+ [ConditionalFact(Helpers.GdiplusIsAvailable)]
+ public void Image16_PaletteEntries_Windows()
+ {
+ string sInFile = Helpers.GetTestBitmapPath("16x16_one_entry_4bit.ico");
+ using (Image image = Image.FromFile(sInFile))
+ {
+ // The values are inconsistent across Windows & Unix: GDI+ returns 0, libgdiplus returns 16.
+ Assert.Equal(0, image.Palette.Entries.Length);
+ }
+ }
+
+ // simley.ico has 48x48, 32x32 and 16x16 images (in that order)
+ [ConditionalFact(Helpers.RecentGdiplusIsAvailable)]
+ public void Bitmap16Features()
+ {
+ string sInFile = Helpers.GetTestBitmapPath("48x48_multiple_entries_4bit.ico");
+ using (Bitmap bmp = new Bitmap(sInFile))
+ {
+ GraphicsUnit unit = GraphicsUnit.World;
+ RectangleF rect = bmp.GetBounds(ref unit);
+
+ Assert.True(bmp.RawFormat.Equals(ImageFormat.Icon));
+ // note that image is "promoted" to 32bits
+ Assert.Equal(PixelFormat.Format32bppArgb, bmp.PixelFormat);
+ Assert.Equal(73746, bmp.Flags);
+
+ Assert.Equal(1, bmp.FrameDimensionsList.Length);
+ Assert.Equal(0, bmp.PropertyIdList.Length);
+ Assert.Equal(0, bmp.PropertyItems.Length);
+ Assert.Null(bmp.Tag);
+ Assert.Equal(96.0f, bmp.HorizontalResolution);
+ Assert.Equal(96.0f, bmp.VerticalResolution);
+ Assert.Equal(16, bmp.Width);
+ Assert.Equal(16, bmp.Height);
+
+ Assert.Equal(0, rect.X);
+ Assert.Equal(0, rect.Y);
+ Assert.Equal(16, rect.Width);
+ Assert.Equal(16, rect.Height);
+
+ Assert.Equal(16, bmp.Size.Width);
+ Assert.Equal(16, bmp.Size.Height);
+ }
+ }
+
+ [PlatformSpecific(TestPlatforms.AnyUnix)]
+ [ConditionalFact(Helpers.GdiplusIsAvailable)]
+ public void Bitmap16Features_Palette_Entries_Unix()
+ {
+ string sInFile = Helpers.GetTestBitmapPath("48x48_multiple_entries_4bit.ico");
+ using (Bitmap bmp = new Bitmap(sInFile))
+ {
+ // These values are inconsistent accross Windows & Unix: 0 on Windows, 16 on Unix
+ Assert.Equal(16, bmp.Palette.Entries.Length);
+ Assert.Equal(-16777216, bmp.Palette.Entries[0].ToArgb());
+ Assert.Equal(-16777216, bmp.Palette.Entries[1].ToArgb());
+ Assert.Equal(-16744448, bmp.Palette.Entries[2].ToArgb());
+ Assert.Equal(-8355840, bmp.Palette.Entries[3].ToArgb());
+ Assert.Equal(-16777088, bmp.Palette.Entries[4].ToArgb());
+ Assert.Equal(-8388480, bmp.Palette.Entries[5].ToArgb());
+ Assert.Equal(-16744320, bmp.Palette.Entries[6].ToArgb());
+ Assert.Equal(-4144960, bmp.Palette.Entries[7].ToArgb());
+ Assert.Equal(-8355712, bmp.Palette.Entries[8].ToArgb());
+ Assert.Equal(-65536, bmp.Palette.Entries[9].ToArgb());
+ Assert.Equal(-16711936, bmp.Palette.Entries[10].ToArgb());
+ Assert.Equal(-256, bmp.Palette.Entries[11].ToArgb());
+ Assert.Equal(-16776961, bmp.Palette.Entries[12].ToArgb());
+ Assert.Equal(-65281, bmp.Palette.Entries[13].ToArgb());
+ Assert.Equal(-16711681, bmp.Palette.Entries[14].ToArgb());
+ Assert.Equal(-1, bmp.Palette.Entries[15].ToArgb());
+ }
+ }
+
+ [PlatformSpecific(TestPlatforms.Windows)]
+ [ConditionalFact(Helpers.GdiplusIsAvailable)]
+ public void Bitmap16Features_Palette_Entries_Windows()
+ {
+ string sInFile = Helpers.GetTestBitmapPath("48x48_multiple_entries_4bit.ico");
+ using (Bitmap bmp = new Bitmap(sInFile))
+ {
+ // These values are inconsistent accross Windows & Unix: 0 on Windows, 16 on Unix
+ Assert.Equal(0, bmp.Palette.Entries.Length);
+ }
+ }
+
+ [ConditionalFact(Helpers.GdiplusIsAvailable)]
+ public void Bitmap16Pixels()
+ {
+ string sInFile = Helpers.GetTestBitmapPath("48x48_multiple_entries_4bit.ico");
+ using (Bitmap bmp = new Bitmap(sInFile))
+ {
+ // sampling values from a well known bitmap
+ Assert.Equal(0, bmp.GetPixel(0, 0).ToArgb());
+ Assert.Equal(0, bmp.GetPixel(0, 4).ToArgb());
+ Assert.Equal(0, bmp.GetPixel(0, 8).ToArgb());
+ Assert.Equal(0, bmp.GetPixel(0, 12).ToArgb());
+ Assert.Equal(0, bmp.GetPixel(4, 0).ToArgb());
+ Assert.Equal(-256, bmp.GetPixel(4, 4).ToArgb());
+ Assert.Equal(-256, bmp.GetPixel(4, 8).ToArgb());
+ Assert.Equal(-8355840, bmp.GetPixel(4, 12).ToArgb());
+ Assert.Equal(0, bmp.GetPixel(8, 0).ToArgb());
+ Assert.Equal(-256, bmp.GetPixel(8, 4).ToArgb());
+ Assert.Equal(-256, bmp.GetPixel(8, 8).ToArgb());
+ Assert.Equal(-256, bmp.GetPixel(8, 12).ToArgb());
+ Assert.Equal(0, bmp.GetPixel(12, 0).ToArgb());
+ Assert.Equal(0, bmp.GetPixel(12, 4).ToArgb());
+ Assert.Equal(-8355840, bmp.GetPixel(12, 8).ToArgb());
+ Assert.Equal(0, bmp.GetPixel(12, 12).ToArgb());
+ }
+ }
+
+ [ConditionalFact(Helpers.GdiplusIsAvailable)]
+ public void Bitmap16Data()
+ {
+ string sInFile = Helpers.GetTestBitmapPath("48x48_multiple_entries_4bit.ico");
+ using (Bitmap bmp = new Bitmap(sInFile))
+ {
+ BitmapData data = bmp.LockBits(new Rectangle(0, 0, bmp.Width, bmp.Height), ImageLockMode.ReadOnly, PixelFormat.Format24bppRgb);
+ try
+ {
+ Assert.Equal(bmp.Height, data.Height);
+ Assert.Equal(bmp.Width, data.Width);
+ Assert.Equal(PixelFormat.Format24bppRgb, data.PixelFormat);
+ Assert.Equal(16, data.Height);
+
+ unsafe
+ {
+ byte* scan = (byte*)data.Scan0;
+ // sampling values from a well known bitmap
+ Assert.Equal(0, *(scan + 0));
+ Assert.Equal(0, *(scan + 13));
+ Assert.Equal(0, *(scan + 26));
+ Assert.Equal(0, *(scan + 39));
+ Assert.Equal(0, *(scan + 52));
+ Assert.Equal(0, *(scan + 65));
+ Assert.Equal(0, *(scan + 78));
+ Assert.Equal(0, *(scan + 91));
+ Assert.Equal(0, *(scan + 104));
+ Assert.Equal(0, *(scan + 117));
+ Assert.Equal(0, *(scan + 130));
+ Assert.Equal(0, *(scan + 143));
+ Assert.Equal(0, *(scan + 156));
+ Assert.Equal(255, *(scan + 169));
+ Assert.Equal(0, *(scan + 182));
+ Assert.Equal(0, *(scan + 195));
+ Assert.Equal(255, *(scan + 208));
+ Assert.Equal(255, *(scan + 221));
+ Assert.Equal(0, *(scan + 234));
+ Assert.Equal(128, *(scan + 247));
+ Assert.Equal(0, *(scan + 260));
+ Assert.Equal(0, *(scan + 273));
+ Assert.Equal(0, *(scan + 286));
+ Assert.Equal(255, *(scan + 299));
+ Assert.Equal(0, *(scan + 312));
+ Assert.Equal(128, *(scan + 325));
+ Assert.Equal(0, *(scan + 338));
+ Assert.Equal(0, *(scan + 351));
+ Assert.Equal(255, *(scan + 364));
+ Assert.Equal(0, *(scan + 377));
+ Assert.Equal(0, *(scan + 390));
+ Assert.Equal(255, *(scan + 403));
+ Assert.Equal(255, *(scan + 416));
+ Assert.Equal(0, *(scan + 429));
+ Assert.Equal(255, *(scan + 442));
+ Assert.Equal(0, *(scan + 455));
+ Assert.Equal(0, *(scan + 468));
+ Assert.Equal(0, *(scan + 481));
+ Assert.Equal(255, *(scan + 494));
+ Assert.Equal(0, *(scan + 507));
+ Assert.Equal(0, *(scan + 520));
+ Assert.Equal(0, *(scan + 533));
+ Assert.Equal(0, *(scan + 546));
+ Assert.Equal(255, *(scan + 559));
+ Assert.Equal(0, *(scan + 572));
+ Assert.Equal(0, *(scan + 585));
+ Assert.Equal(255, *(scan + 598));
+ Assert.Equal(0, *(scan + 611));
+ Assert.Equal(0, *(scan + 624));
+ Assert.Equal(0, *(scan + 637));
+ Assert.Equal(128, *(scan + 650));
+ Assert.Equal(0, *(scan + 663));
+ Assert.Equal(0, *(scan + 676));
+ Assert.Equal(0, *(scan + 689));
+ Assert.Equal(0, *(scan + 702));
+ Assert.Equal(0, *(scan + 715));
+ Assert.Equal(0, *(scan + 728));
+ Assert.Equal(0, *(scan + 741));
+ Assert.Equal(0, *(scan + 754));
+ Assert.Equal(0, *(scan + 767));
+ }
+ }
+ finally
+ {
+ bmp.UnlockBits(data);
+ }
+ }
+ }
+
+ // VisualPng.ico only has a 32x32 size available
+ [ConditionalFact(Helpers.RecentGdiplusIsAvailable)]
+ public void Bitmap32Features()
+ {
+ string sInFile = Helpers.GetTestBitmapPath("VisualPng.ico");
+ using (Bitmap bmp = new Bitmap(sInFile))
+ {
+ GraphicsUnit unit = GraphicsUnit.World;
+ RectangleF rect = bmp.GetBounds(ref unit);
+
+ Assert.True(bmp.RawFormat.Equals(ImageFormat.Icon));
+ Assert.Equal(PixelFormat.Format32bppArgb, bmp.PixelFormat);
+ Assert.Equal(73746, bmp.Flags);
+
+ Assert.Equal(1, bmp.FrameDimensionsList.Length);
+ Assert.Equal(0, bmp.PropertyIdList.Length);
+ Assert.Equal(0, bmp.PropertyItems.Length);
+ Assert.Null(bmp.Tag);
+ Assert.Equal(96.0f, bmp.HorizontalResolution);
+ Assert.Equal(96.0f, bmp.VerticalResolution);
+ Assert.Equal(32, bmp.Width);
+ Assert.Equal(32, bmp.Height);
+
+ Assert.Equal(0, rect.X);
+ Assert.Equal(0, rect.Y);
+ Assert.Equal(32, rect.Width);
+ Assert.Equal(32, rect.Height);
+
+ Assert.Equal(32, bmp.Size.Width);
+ Assert.Equal(32, bmp.Size.Height);
+ }
+ }
+
+ [PlatformSpecific(TestPlatforms.AnyUnix)]
+ [ConditionalFact(Helpers.RecentGdiplusIsAvailable)]
+ public void Bitmap32Features_PaletteEntries_Unix()
+ {
+ string sInFile = Helpers.GetTestBitmapPath("VisualPng.ico");
+ using (Bitmap bmp = new Bitmap(sInFile))
+ {
+ // These values areinconsistent accross Windows & Unix: 0 on Windows, 16 on Unix
+ Assert.Equal(16, bmp.Palette.Entries.Length);
+
+ Assert.Equal(-16777216, bmp.Palette.Entries[0].ToArgb());
+ Assert.Equal(-8388608, bmp.Palette.Entries[1].ToArgb());
+ Assert.Equal(-16744448, bmp.Palette.Entries[2].ToArgb());
+ Assert.Equal(-8355840, bmp.Palette.Entries[3].ToArgb());
+ Assert.Equal(-16777088, bmp.Palette.Entries[4].ToArgb());
+ Assert.Equal(-8388480, bmp.Palette.Entries[5].ToArgb());
+ Assert.Equal(-16744320, bmp.Palette.Entries[6].ToArgb());
+ Assert.Equal(-4144960, bmp.Palette.Entries[7].ToArgb());
+ Assert.Equal(-8355712, bmp.Palette.Entries[8].ToArgb());
+ Assert.Equal(-65536, bmp.Palette.Entries[9].ToArgb());
+ Assert.Equal(-16711936, bmp.Palette.Entries[10].ToArgb());
+ Assert.Equal(-256, bmp.Palette.Entries[11].ToArgb());
+ Assert.Equal(-16776961, bmp.Palette.Entries[12].ToArgb());
+ Assert.Equal(-65281, bmp.Palette.Entries[13].ToArgb());
+ Assert.Equal(-16711681, bmp.Palette.Entries[14].ToArgb());
+ Assert.Equal(-1, bmp.Palette.Entries[15].ToArgb());
+ }
+ }
+
+ [PlatformSpecific(TestPlatforms.Windows)]
+ [ConditionalFact(Helpers.GdiplusIsAvailable)]
+ public void Bitmap32Features_PaletteEntries_Windows()
+ {
+ string sInFile = Helpers.GetTestBitmapPath("VisualPng.ico");
+ using (Bitmap bmp = new Bitmap(sInFile))
+ {
+ // These values areinconsistent accross Windows & Unix: 0 on Windows, 16 on Unix
+ Assert.Equal(0, bmp.Palette.Entries.Length);
+ }
+ }
+
+ [ConditionalFact(Helpers.GdiplusIsAvailable)]
+ public void Bitmap32Pixels()
+ {
+ string sInFile = Helpers.GetTestBitmapPath("VisualPng.ico");
+ using (Bitmap bmp = new Bitmap(sInFile))
+ {
+ // sampling values from a well known bitmap
+ Assert.Equal(0, bmp.GetPixel(0, 0).ToArgb());
+ Assert.Equal(-8388608, bmp.GetPixel(0, 4).ToArgb());
+ Assert.Equal(0, bmp.GetPixel(0, 8).ToArgb());
+ Assert.Equal(0, bmp.GetPixel(0, 12).ToArgb());
+ Assert.Equal(0, bmp.GetPixel(0, 16).ToArgb());
+ Assert.Equal(0, bmp.GetPixel(0, 20).ToArgb());
+ Assert.Equal(0, bmp.GetPixel(0, 24).ToArgb());
+ Assert.Equal(0, bmp.GetPixel(0, 28).ToArgb());
+ Assert.Equal(0, bmp.GetPixel(4, 0).ToArgb());
+ Assert.Equal(0, bmp.GetPixel(4, 4).ToArgb());
+ Assert.Equal(0, bmp.GetPixel(4, 8).ToArgb());
+ Assert.Equal(0, bmp.GetPixel(4, 12).ToArgb());
+ Assert.Equal(0, bmp.GetPixel(4, 16).ToArgb());
+ Assert.Equal(0, bmp.GetPixel(4, 20).ToArgb());
+ Assert.Equal(0, bmp.GetPixel(4, 24).ToArgb());
+ Assert.Equal(0, bmp.GetPixel(4, 28).ToArgb());
+ Assert.Equal(0, bmp.GetPixel(8, 0).ToArgb());
+ Assert.Equal(0, bmp.GetPixel(8, 4).ToArgb());
+ Assert.Equal(0, bmp.GetPixel(8, 8).ToArgb());
+ Assert.Equal(0, bmp.GetPixel(8, 12).ToArgb());
+ Assert.Equal(0, bmp.GetPixel(8, 16).ToArgb());
+ Assert.Equal(-65536, bmp.GetPixel(8, 20).ToArgb());
+ Assert.Equal(0, bmp.GetPixel(8, 24).ToArgb());
+ Assert.Equal(0, bmp.GetPixel(8, 28).ToArgb());
+ Assert.Equal(0, bmp.GetPixel(12, 0).ToArgb());
+ Assert.Equal(0, bmp.GetPixel(12, 4).ToArgb());
+ Assert.Equal(-8388608, bmp.GetPixel(12, 8).ToArgb());
+ Assert.Equal(0, bmp.GetPixel(12, 12).ToArgb());
+ Assert.Equal(0, bmp.GetPixel(12, 16).ToArgb());
+ Assert.Equal(-65536, bmp.GetPixel(12, 20).ToArgb());
+ Assert.Equal(0, bmp.GetPixel(12, 24).ToArgb());
+ Assert.Equal(0, bmp.GetPixel(12, 28).ToArgb());
+ Assert.Equal(0, bmp.GetPixel(16, 0).ToArgb());
+ Assert.Equal(0, bmp.GetPixel(16, 4).ToArgb());
+ Assert.Equal(0, bmp.GetPixel(16, 8).ToArgb());
+ Assert.Equal(0, bmp.GetPixel(16, 12).ToArgb());
+ Assert.Equal(0, bmp.GetPixel(16, 16).ToArgb());
+ Assert.Equal(0, bmp.GetPixel(16, 20).ToArgb());
+ Assert.Equal(-65536, bmp.GetPixel(16, 24).ToArgb());
+ Assert.Equal(0, bmp.GetPixel(16, 28).ToArgb());
+ Assert.Equal(0, bmp.GetPixel(20, 0).ToArgb());
+ Assert.Equal(0, bmp.GetPixel(20, 4).ToArgb());
+ Assert.Equal(-8388608, bmp.GetPixel(20, 8).ToArgb());
+ Assert.Equal(0, bmp.GetPixel(20, 12).ToArgb());
+ Assert.Equal(0, bmp.GetPixel(20, 16).ToArgb());
+ Assert.Equal(0, bmp.GetPixel(20, 20).ToArgb());
+ Assert.Equal(0, bmp.GetPixel(20, 24).ToArgb());
+ Assert.Equal(0, bmp.GetPixel(20, 28).ToArgb());
+ Assert.Equal(0, bmp.GetPixel(24, 0).ToArgb());
+ Assert.Equal(0, bmp.GetPixel(24, 4).ToArgb());
+ Assert.Equal(-16777216, bmp.GetPixel(24, 8).ToArgb());
+ Assert.Equal(0, bmp.GetPixel(24, 12).ToArgb());
+ Assert.Equal(0, bmp.GetPixel(24, 16).ToArgb());
+ Assert.Equal(0, bmp.GetPixel(24, 20).ToArgb());
+ Assert.Equal(0, bmp.GetPixel(24, 24).ToArgb());
+ Assert.Equal(0, bmp.GetPixel(24, 28).ToArgb());
+ Assert.Equal(0, bmp.GetPixel(28, 0).ToArgb());
+ Assert.Equal(0, bmp.GetPixel(28, 4).ToArgb());
+ Assert.Equal(0, bmp.GetPixel(28, 8).ToArgb());
+ Assert.Equal(0, bmp.GetPixel(28, 12).ToArgb());
+ Assert.Equal(0, bmp.GetPixel(28, 16).ToArgb());
+ Assert.Equal(0, bmp.GetPixel(28, 20).ToArgb());
+ Assert.Equal(-8388608, bmp.GetPixel(28, 24).ToArgb());
+ Assert.Equal(0, bmp.GetPixel(28, 28).ToArgb());
+ }
+ }
+
+ [ConditionalFact(Helpers.GdiplusIsAvailable)]
+ public void Bitmap32Data()
+ {
+ string sInFile = Helpers.GetTestBitmapPath("VisualPng.ico");
+ using (Bitmap bmp = new Bitmap(sInFile))
+ {
+ BitmapData data = bmp.LockBits(new Rectangle(0, 0, bmp.Width, bmp.Height), ImageLockMode.ReadOnly, PixelFormat.Format24bppRgb);
+ try
+ {
+ Assert.Equal(bmp.Height, data.Height);
+ Assert.Equal(bmp.Width, data.Width);
+ Assert.Equal(PixelFormat.Format24bppRgb, data.PixelFormat);
+ Assert.Equal(32, data.Height);
+
+ unsafe
+ {
+ byte* scan = (byte*)data.Scan0;
+ // sampling values from a well known bitmap
+ Assert.Equal(0, *(scan + 0));
+ Assert.Equal(0, *(scan + 13));
+ Assert.Equal(0, *(scan + 26));
+ Assert.Equal(0, *(scan + 39));
+ Assert.Equal(0, *(scan + 52));
+ Assert.Equal(0, *(scan + 65));
+ Assert.Equal(0, *(scan + 78));
+ Assert.Equal(0, *(scan + 91));
+ Assert.Equal(0, *(scan + 104));
+ Assert.Equal(0, *(scan + 117));
+ Assert.Equal(0, *(scan + 130));
+ Assert.Equal(0, *(scan + 143));
+ Assert.Equal(0, *(scan + 156));
+ Assert.Equal(0, *(scan + 169));
+ Assert.Equal(0, *(scan + 182));
+ Assert.Equal(0, *(scan + 195));
+ Assert.Equal(0, *(scan + 208));
+ Assert.Equal(0, *(scan + 221));
+ Assert.Equal(0, *(scan + 234));
+ Assert.Equal(0, *(scan + 247));
+ Assert.Equal(0, *(scan + 260));
+ Assert.Equal(0, *(scan + 273));
+ Assert.Equal(0, *(scan + 286));
+ Assert.Equal(0, *(scan + 299));
+ Assert.Equal(0, *(scan + 312));
+ Assert.Equal(0, *(scan + 325));
+ Assert.Equal(0, *(scan + 338));
+ Assert.Equal(0, *(scan + 351));
+ Assert.Equal(0, *(scan + 364));
+ Assert.Equal(0, *(scan + 377));
+ Assert.Equal(0, *(scan + 390));
+ Assert.Equal(0, *(scan + 403));
+ Assert.Equal(0, *(scan + 416));
+ Assert.Equal(0, *(scan + 429));
+ Assert.Equal(0, *(scan + 442));
+ Assert.Equal(0, *(scan + 455));
+ Assert.Equal(0, *(scan + 468));
+ Assert.Equal(0, *(scan + 481));
+ Assert.Equal(128, *(scan + 494));
+ Assert.Equal(0, *(scan + 507));
+ Assert.Equal(0, *(scan + 520));
+ Assert.Equal(0, *(scan + 533));
+ Assert.Equal(0, *(scan + 546));
+ Assert.Equal(0, *(scan + 559));
+ Assert.Equal(128, *(scan + 572));
+ Assert.Equal(0, *(scan + 585));
+ Assert.Equal(0, *(scan + 598));
+ Assert.Equal(0, *(scan + 611));
+ Assert.Equal(0, *(scan + 624));
+ Assert.Equal(0, *(scan + 637));
+ Assert.Equal(128, *(scan + 650));
+ Assert.Equal(0, *(scan + 663));
+ Assert.Equal(0, *(scan + 676));
+ Assert.Equal(0, *(scan + 689));
+ Assert.Equal(0, *(scan + 702));
+ Assert.Equal(0, *(scan + 715));
+ Assert.Equal(0, *(scan + 728));
+ Assert.Equal(0, *(scan + 741));
+ Assert.Equal(0, *(scan + 754));
+ Assert.Equal(0, *(scan + 767));
+ Assert.Equal(0, *(scan + 780));
+ Assert.Equal(0, *(scan + 793));
+ Assert.Equal(128, *(scan + 806));
+ Assert.Equal(0, *(scan + 819));
+ Assert.Equal(0, *(scan + 832));
+ Assert.Equal(128, *(scan + 845));
+ Assert.Equal(0, *(scan + 858));
+ Assert.Equal(0, *(scan + 871));
+ Assert.Equal(0, *(scan + 884));
+ }
+ }
+ finally
+ {
+ bmp.UnlockBits(data);
+ }
+ }
+ }
+
+ // 48x48_one_entry_1bit.ico only has a 48x48 size available
+ [ConditionalFact(Helpers.RecentGdiplusIsAvailable)]
+ public void Bitmap48Features()
+ {
+ string sInFile = Helpers.GetTestBitmapPath("48x48_one_entry_1bit.ico");
+ using (Bitmap bmp = new Bitmap(sInFile))
+ {
+ GraphicsUnit unit = GraphicsUnit.World;
+ RectangleF rect = bmp.GetBounds(ref unit);
+
+ Assert.True(bmp.RawFormat.Equals(ImageFormat.Icon));
+ Assert.Equal(PixelFormat.Format32bppArgb, bmp.PixelFormat);
+ Assert.Equal(73746, bmp.Flags);
+
+ Assert.Equal(1, bmp.FrameDimensionsList.Length);
+ Assert.Equal(0, bmp.PropertyIdList.Length);
+ Assert.Equal(0, bmp.PropertyItems.Length);
+ Assert.Null(bmp.Tag);
+ Assert.Equal(96.0f, bmp.HorizontalResolution);
+ Assert.Equal(96.0f, bmp.VerticalResolution);
+ Assert.Equal(48, bmp.Width);
+ Assert.Equal(48, bmp.Height);
+
+ Assert.Equal(0, rect.X);
+ Assert.Equal(0, rect.Y);
+ Assert.Equal(48, rect.Width);
+ Assert.Equal(48, rect.Height);
+
+ Assert.Equal(48, bmp.Size.Width);
+ Assert.Equal(48, bmp.Size.Height);
+ }
+ }
+
+ [PlatformSpecific(TestPlatforms.AnyUnix)]
+ [ConditionalFact(Helpers.RecentGdiplusIsAvailable)]
+ public void Bitmap48Features_Palette_Entries_Unix()
+ {
+ string sInFile = Helpers.GetTestBitmapPath("48x48_one_entry_1bit.ico");
+ using (Bitmap bmp = new Bitmap(sInFile))
+ {
+ // These values are inconsistent accross Windows & Unix: 0 on Windows, 16 on Unix
+ Assert.Equal(2, bmp.Palette.Entries.Length);
+ Assert.Equal(-16777216, bmp.Palette.Entries[0].ToArgb());
+ Assert.Equal(-1, bmp.Palette.Entries[1].ToArgb());
+ }
+ }
+
+ [PlatformSpecific(TestPlatforms.Windows)]
+ [ConditionalFact(Helpers.GdiplusIsAvailable)]
+ public void Bitmap48Features_Palette_Entries_Windows()
+ {
+ string sInFile = Helpers.GetTestBitmapPath("48x48_one_entry_1bit.ico");
+ using (Bitmap bmp = new Bitmap(sInFile))
+ {
+ // These values are inconsistent accross Windows & Unix: 0 on Windows, 16 on Unix
+ Assert.Equal(0, bmp.Palette.Entries.Length);
+ }
+ }
+
+ [ConditionalFact(Helpers.GdiplusIsAvailable)]
+ public void Bitmap48Pixels()
+ {
+ string sInFile = Helpers.GetTestBitmapPath("48x48_one_entry_1bit.ico");
+ using (Bitmap bmp = new Bitmap(sInFile))
+ {
+ // sampling values from a well known bitmap
+ Assert.Equal(-16777216, bmp.GetPixel(0, 0).ToArgb());
+ Assert.Equal(-16777216, bmp.GetPixel(0, 4).ToArgb());
+ Assert.Equal(-16777216, bmp.GetPixel(0, 8).ToArgb());
+ Assert.Equal(-16777216, bmp.GetPixel(0, 12).ToArgb());
+ Assert.Equal(-16777216, bmp.GetPixel(0, 16).ToArgb());
+ Assert.Equal(-16777216, bmp.GetPixel(0, 20).ToArgb());
+ Assert.Equal(-16777216, bmp.GetPixel(0, 24).ToArgb());
+ Assert.Equal(-16777216, bmp.GetPixel(0, 28).ToArgb());
+ Assert.Equal(-16777216, bmp.GetPixel(0, 32).ToArgb());
+ Assert.Equal(-16777216, bmp.GetPixel(0, 36).ToArgb());
+ Assert.Equal(-16777216, bmp.GetPixel(0, 40).ToArgb());
+ Assert.Equal(-16777216, bmp.GetPixel(0, 44).ToArgb());
+ Assert.Equal(-16777216, bmp.GetPixel(4, 0).ToArgb());
+ Assert.Equal(0, bmp.GetPixel(4, 4).ToArgb());
+ Assert.Equal(0, bmp.GetPixel(4, 8).ToArgb());
+ Assert.Equal(0, bmp.GetPixel(4, 12).ToArgb());
+ Assert.Equal(0, bmp.GetPixel(4, 16).ToArgb());
+ Assert.Equal(0, bmp.GetPixel(4, 20).ToArgb());
+ Assert.Equal(0, bmp.GetPixel(4, 24).ToArgb());
+ Assert.Equal(0, bmp.GetPixel(4, 28).ToArgb());
+ Assert.Equal(0, bmp.GetPixel(4, 32).ToArgb());
+ Assert.Equal(0, bmp.GetPixel(4, 36).ToArgb());
+ Assert.Equal(0, bmp.GetPixel(4, 40).ToArgb());
+ Assert.Equal(-1, bmp.GetPixel(4, 44).ToArgb());
+ Assert.Equal(-16777216, bmp.GetPixel(8, 0).ToArgb());
+ Assert.Equal(0, bmp.GetPixel(8, 4).ToArgb());
+ Assert.Equal(-16777216, bmp.GetPixel(8, 8).ToArgb());
+ Assert.Equal(-16777216, bmp.GetPixel(8, 12).ToArgb());
+ Assert.Equal(-16777216, bmp.GetPixel(8, 16).ToArgb());
+ Assert.Equal(-16777216, bmp.GetPixel(8, 20).ToArgb());
+ Assert.Equal(-16777216, bmp.GetPixel(8, 24).ToArgb());
+ Assert.Equal(-16777216, bmp.GetPixel(8, 28).ToArgb());
+ Assert.Equal(-16777216, bmp.GetPixel(8, 32).ToArgb());
+ Assert.Equal(-16777216, bmp.GetPixel(8, 36).ToArgb());
+ Assert.Equal(-16777216, bmp.GetPixel(8, 40).ToArgb());
+ Assert.Equal(-1, bmp.GetPixel(8, 44).ToArgb());
+ Assert.Equal(-16777216, bmp.GetPixel(12, 0).ToArgb());
+ Assert.Equal(0, bmp.GetPixel(12, 4).ToArgb());
+ Assert.Equal(-16777216, bmp.GetPixel(12, 8).ToArgb());
+ Assert.Equal(-1, bmp.GetPixel(12, 12).ToArgb());
+ Assert.Equal(-1, bmp.GetPixel(12, 16).ToArgb());
+ Assert.Equal(-1, bmp.GetPixel(12, 20).ToArgb());
+ Assert.Equal(-1, bmp.GetPixel(12, 24).ToArgb());
+ Assert.Equal(-1, bmp.GetPixel(12, 28).ToArgb());
+ Assert.Equal(-1, bmp.GetPixel(12, 32).ToArgb());
+ Assert.Equal(0, bmp.GetPixel(12, 36).ToArgb());
+ Assert.Equal(-16777216, bmp.GetPixel(12, 40).ToArgb());
+ Assert.Equal(-1, bmp.GetPixel(12, 44).ToArgb());
+ Assert.Equal(-16777216, bmp.GetPixel(16, 0).ToArgb());
+ Assert.Equal(0, bmp.GetPixel(16, 4).ToArgb());
+ Assert.Equal(-16777216, bmp.GetPixel(16, 8).ToArgb());
+ Assert.Equal(-1, bmp.GetPixel(16, 12).ToArgb());
+ Assert.Equal(0, bmp.GetPixel(16, 16).ToArgb());
+ Assert.Equal(0, bmp.GetPixel(16, 20).ToArgb());
+ Assert.Equal(0, bmp.GetPixel(16, 24).ToArgb());
+ Assert.Equal(0, bmp.GetPixel(16, 28).ToArgb());
+ Assert.Equal(-1, bmp.GetPixel(16, 32).ToArgb());
+ Assert.Equal(0, bmp.GetPixel(16, 36).ToArgb());
+ Assert.Equal(-16777216, bmp.GetPixel(16, 40).ToArgb());
+ Assert.Equal(-1, bmp.GetPixel(16, 44).ToArgb());
+ Assert.Equal(-16777216, bmp.GetPixel(20, 0).ToArgb());
+ Assert.Equal(0, bmp.GetPixel(20, 4).ToArgb());
+ Assert.Equal(-16777216, bmp.GetPixel(20, 8).ToArgb());
+ Assert.Equal(-1, bmp.GetPixel(20, 12).ToArgb());
+ Assert.Equal(0, bmp.GetPixel(20, 16).ToArgb());
+ Assert.Equal(-16777216, bmp.GetPixel(20, 20).ToArgb());
+ Assert.Equal(-16777216, bmp.GetPixel(20, 24).ToArgb());
+ Assert.Equal(0, bmp.GetPixel(20, 28).ToArgb());
+ Assert.Equal(-1, bmp.GetPixel(20, 32).ToArgb());
+ Assert.Equal(0, bmp.GetPixel(20, 36).ToArgb());
+ Assert.Equal(-16777216, bmp.GetPixel(20, 40).ToArgb());
+ Assert.Equal(-1, bmp.GetPixel(20, 44).ToArgb());
+ Assert.Equal(-16777216, bmp.GetPixel(24, 0).ToArgb());
+ Assert.Equal(0, bmp.GetPixel(24, 4).ToArgb());
+ Assert.Equal(-16777216, bmp.GetPixel(24, 8).ToArgb());
+ Assert.Equal(-1, bmp.GetPixel(24, 12).ToArgb());
+ Assert.Equal(0, bmp.GetPixel(24, 16).ToArgb());
+ }
+ }
+
+ [ConditionalFact(Helpers.GdiplusIsAvailable)]
+ public void Bitmap48Data()
+ {
+ string sInFile = Helpers.GetTestBitmapPath("48x48_one_entry_1bit.ico");
+ using (Bitmap bmp = new Bitmap(sInFile))
+ {
+ BitmapData data = bmp.LockBits(new Rectangle(0, 0, bmp.Width, bmp.Height), ImageLockMode.ReadOnly, PixelFormat.Format24bppRgb);
+ try
+ {
+ Assert.Equal(bmp.Height, data.Height);
+ Assert.Equal(bmp.Width, data.Width);
+ Assert.Equal(PixelFormat.Format24bppRgb, data.PixelFormat);
+ Assert.Equal(48, data.Height);
+
+ unsafe
+ {
+ byte* scan = (byte*)data.Scan0;
+ // sampling values from a well known bitmap
+ Assert.Equal(0, *(scan + 0));
+ Assert.Equal(0, *(scan + 13));
+ Assert.Equal(0, *(scan + 26));
+ Assert.Equal(0, *(scan + 39));
+ Assert.Equal(0, *(scan + 52));
+ Assert.Equal(0, *(scan + 65));
+ Assert.Equal(0, *(scan + 78));
+ Assert.Equal(0, *(scan + 91));
+ Assert.Equal(0, *(scan + 104));
+ Assert.Equal(0, *(scan + 117));
+ Assert.Equal(0, *(scan + 130));
+ Assert.Equal(0, *(scan + 143));
+ Assert.Equal(0, *(scan + 156));
+ Assert.Equal(0, *(scan + 169));
+ Assert.Equal(0, *(scan + 182));
+ Assert.Equal(0, *(scan + 195));
+ Assert.Equal(0, *(scan + 208));
+ Assert.Equal(0, *(scan + 221));
+ Assert.Equal(0, *(scan + 234));
+ Assert.Equal(0, *(scan + 247));
+ Assert.Equal(0, *(scan + 260));
+ Assert.Equal(0, *(scan + 273));
+ Assert.Equal(0, *(scan + 286));
+ Assert.Equal(255, *(scan + 299));
+ Assert.Equal(255, *(scan + 312));
+ Assert.Equal(255, *(scan + 325));
+ Assert.Equal(255, *(scan + 338));
+ Assert.Equal(255, *(scan + 351));
+ Assert.Equal(255, *(scan + 364));
+ Assert.Equal(255, *(scan + 377));
+ Assert.Equal(255, *(scan + 390));
+ Assert.Equal(255, *(scan + 403));
+ Assert.Equal(255, *(scan + 416));
+ Assert.Equal(0, *(scan + 429));
+ Assert.Equal(255, *(scan + 442));
+ Assert.Equal(255, *(scan + 455));
+ Assert.Equal(255, *(scan + 468));
+ Assert.Equal(255, *(scan + 481));
+ Assert.Equal(255, *(scan + 494));
+ Assert.Equal(255, *(scan + 507));
+ Assert.Equal(255, *(scan + 520));
+ Assert.Equal(255, *(scan + 533));
+ Assert.Equal(255, *(scan + 546));
+ Assert.Equal(255, *(scan + 559));
+ Assert.Equal(0, *(scan + 572));
+ Assert.Equal(255, *(scan + 585));
+ Assert.Equal(0, *(scan + 598));
+ Assert.Equal(0, *(scan + 611));
+ Assert.Equal(0, *(scan + 624));
+ Assert.Equal(0, *(scan + 637));
+ Assert.Equal(0, *(scan + 650));
+ Assert.Equal(0, *(scan + 663));
+ Assert.Equal(0, *(scan + 676));
+ Assert.Equal(0, *(scan + 689));
+ Assert.Equal(0, *(scan + 702));
+ Assert.Equal(0, *(scan + 715));
+ Assert.Equal(255, *(scan + 728));
+ Assert.Equal(0, *(scan + 741));
+ Assert.Equal(0, *(scan + 754));
+ Assert.Equal(0, *(scan + 767));
+ Assert.Equal(0, *(scan + 780));
+ Assert.Equal(0, *(scan + 793));
+ Assert.Equal(0, *(scan + 806));
+ Assert.Equal(0, *(scan + 819));
+ Assert.Equal(0, *(scan + 832));
+ Assert.Equal(0, *(scan + 845));
+ Assert.Equal(0, *(scan + 858));
+ Assert.Equal(255, *(scan + 871));
+ Assert.Equal(0, *(scan + 884));
+ Assert.Equal(0, *(scan + 897));
+ Assert.Equal(0, *(scan + 910));
+ Assert.Equal(0, *(scan + 923));
+ Assert.Equal(0, *(scan + 936));
+ }
+ }
+ finally
+ {
+ bmp.UnlockBits(data);
+ }
+ }
+ }
+
+ // 64x64x256 only has a 64x64 size available
+ [ConditionalFact(Helpers.RecentGdiplusIsAvailable)]
+ public void Bitmap64Features()
+ {
+ string sInFile = Helpers.GetTestBitmapPath("64x64_one_entry_8bit.ico");
+ using (Bitmap bmp = new Bitmap(sInFile))
+ {
+ GraphicsUnit unit = GraphicsUnit.World;
+ RectangleF rect = bmp.GetBounds(ref unit);
+
+ Assert.True(bmp.RawFormat.Equals(ImageFormat.Icon));
+ Assert.Equal(PixelFormat.Format32bppArgb, bmp.PixelFormat);
+ Assert.Equal(73746, bmp.Flags);
+
+ Assert.Equal(1, bmp.FrameDimensionsList.Length);
+ Assert.Equal(0, bmp.PropertyIdList.Length);
+ Assert.Equal(0, bmp.PropertyItems.Length);
+ Assert.Null(bmp.Tag);
+ Assert.Equal(96.0f, bmp.HorizontalResolution);
+ Assert.Equal(96.0f, bmp.VerticalResolution);
+ Assert.Equal(64, bmp.Width);
+ Assert.Equal(64, bmp.Height);
+
+ Assert.Equal(0, rect.X);
+ Assert.Equal(0, rect.Y);
+ Assert.Equal(64, rect.Width);
+ Assert.Equal(64, rect.Height);
+
+ Assert.Equal(64, bmp.Size.Width);
+ Assert.Equal(64, bmp.Size.Height);
+ }
+ }
+
+ [PlatformSpecific(TestPlatforms.AnyUnix)]
+ [ConditionalFact(Helpers.RecentGdiplusIsAvailable)]
+ public void Bitmap64Features_Palette_Entries_Unix()
+ {
+ string sInFile = Helpers.GetTestBitmapPath("64x64_one_entry_8bit.ico");
+ using (Bitmap bmp = new Bitmap(sInFile))
+ {
+ // This value is inconsistent accross Windows & Unix: 0 on Windows, 256 on Unix
+ Assert.Equal(256, bmp.Palette.Entries.Length);
+ }
+ }
+
+ [PlatformSpecific(TestPlatforms.Windows)]
+ [ConditionalFact(Helpers.GdiplusIsAvailable)]
+ public void Bitmap64Features_Palette_Entries_Windows()
+ {
+ string sInFile = Helpers.GetTestBitmapPath("64x64_one_entry_8bit.ico");
+ using (Bitmap bmp = new Bitmap(sInFile))
+ {
+ // This value is inconsistent accross Windows & Unix: 0 on Windows, 256 on Unix
+ Assert.Equal(0, bmp.Palette.Entries.Length);
+ }
+ }
+
+ [ConditionalFact(Helpers.GdiplusIsAvailable)]
+ public void Bitmap64Pixels()
+ {
+ string sInFile = Helpers.GetTestBitmapPath("64x64_one_entry_8bit.ico");
+ using (Bitmap bmp = new Bitmap(sInFile))
+ {
+ // sampling values from a well known bitmap
+ Assert.Equal(-65383, bmp.GetPixel(0, 0).ToArgb());
+ Assert.Equal(-65383, bmp.GetPixel(0, 4).ToArgb());
+ Assert.Equal(-65383, bmp.GetPixel(0, 8).ToArgb());
+ Assert.Equal(-65383, bmp.GetPixel(0, 12).ToArgb());
+ Assert.Equal(-65383, bmp.GetPixel(0, 16).ToArgb());
+ Assert.Equal(-65383, bmp.GetPixel(0, 20).ToArgb());
+ Assert.Equal(-65383, bmp.GetPixel(0, 24).ToArgb());
+ Assert.Equal(-65383, bmp.GetPixel(0, 28).ToArgb());
+ Assert.Equal(-65383, bmp.GetPixel(0, 32).ToArgb());
+ Assert.Equal(-65383, bmp.GetPixel(0, 36).ToArgb());
+ Assert.Equal(-65383, bmp.GetPixel(0, 40).ToArgb());
+ Assert.Equal(-65383, bmp.GetPixel(0, 44).ToArgb());
+ Assert.Equal(-65383, bmp.GetPixel(0, 48).ToArgb());
+ Assert.Equal(-65383, bmp.GetPixel(0, 52).ToArgb());
+ Assert.Equal(-65383, bmp.GetPixel(0, 56).ToArgb());
+ Assert.Equal(-65383, bmp.GetPixel(0, 60).ToArgb());
+ Assert.Equal(-65383, bmp.GetPixel(4, 0).ToArgb());
+ Assert.Equal(-10079335, bmp.GetPixel(4, 4).ToArgb());
+ Assert.Equal(-10079335, bmp.GetPixel(4, 8).ToArgb());
+ Assert.Equal(-10079335, bmp.GetPixel(4, 12).ToArgb());
+ Assert.Equal(-10079335, bmp.GetPixel(4, 16).ToArgb());
+ Assert.Equal(-10079335, bmp.GetPixel(4, 20).ToArgb());
+ Assert.Equal(-10079335, bmp.GetPixel(4, 24).ToArgb());
+ Assert.Equal(-10079335, bmp.GetPixel(4, 28).ToArgb());
+ Assert.Equal(-10079335, bmp.GetPixel(4, 32).ToArgb());
+ Assert.Equal(-10079335, bmp.GetPixel(4, 36).ToArgb());
+ Assert.Equal(-10079335, bmp.GetPixel(4, 40).ToArgb());
+ Assert.Equal(-10079335, bmp.GetPixel(4, 44).ToArgb());
+ Assert.Equal(-10079335, bmp.GetPixel(4, 48).ToArgb());
+ Assert.Equal(-10079335, bmp.GetPixel(4, 52).ToArgb());
+ Assert.Equal(-10079335, bmp.GetPixel(4, 56).ToArgb());
+ Assert.Equal(0, bmp.GetPixel(4, 60).ToArgb());
+ Assert.Equal(-65383, bmp.GetPixel(8, 0).ToArgb());
+ Assert.Equal(-10079335, bmp.GetPixel(8, 4).ToArgb());
+ Assert.Equal(-3342490, bmp.GetPixel(8, 8).ToArgb());
+ Assert.Equal(-3342490, bmp.GetPixel(8, 12).ToArgb());
+ Assert.Equal(-3342490, bmp.GetPixel(8, 16).ToArgb());
+ Assert.Equal(-3342490, bmp.GetPixel(8, 20).ToArgb());
+ Assert.Equal(-3342490, bmp.GetPixel(8, 24).ToArgb());
+ Assert.Equal(-3342490, bmp.GetPixel(8, 28).ToArgb());
+ Assert.Equal(-3342490, bmp.GetPixel(8, 32).ToArgb());
+ Assert.Equal(-3342490, bmp.GetPixel(8, 36).ToArgb());
+ Assert.Equal(-3342490, bmp.GetPixel(8, 40).ToArgb());
+ Assert.Equal(-3342490, bmp.GetPixel(8, 44).ToArgb());
+ Assert.Equal(-3342490, bmp.GetPixel(8, 48).ToArgb());
+ Assert.Equal(-3342490, bmp.GetPixel(8, 52).ToArgb());
+ Assert.Equal(0, bmp.GetPixel(8, 56).ToArgb());
+ Assert.Equal(0, bmp.GetPixel(8, 60).ToArgb());
+ Assert.Equal(-65383, bmp.GetPixel(12, 0).ToArgb());
+ Assert.Equal(-10079335, bmp.GetPixel(12, 4).ToArgb());
+ Assert.Equal(-3342490, bmp.GetPixel(12, 8).ToArgb());
+ Assert.Equal(-33664, bmp.GetPixel(12, 12).ToArgb());
+ Assert.Equal(-33664, bmp.GetPixel(12, 16).ToArgb());
+ Assert.Equal(-33664, bmp.GetPixel(12, 20).ToArgb());
+ Assert.Equal(-33664, bmp.GetPixel(12, 24).ToArgb());
+ Assert.Equal(-33664, bmp.GetPixel(12, 28).ToArgb());
+ Assert.Equal(-33664, bmp.GetPixel(12, 32).ToArgb());
+ Assert.Equal(-33664, bmp.GetPixel(12, 36).ToArgb());
+ Assert.Equal(-33664, bmp.GetPixel(12, 40).ToArgb());
+ }
+ }
+
+ [ConditionalFact(Helpers.GdiplusIsAvailable)]
+ public void Bitmap64Data()
+ {
+ string sInFile = Helpers.GetTestBitmapPath("64x64_one_entry_8bit.ico");
+ using (Bitmap bmp = new Bitmap(sInFile))
+ {
+ BitmapData data = bmp.LockBits(new Rectangle(0, 0, bmp.Width, bmp.Height), ImageLockMode.ReadOnly, PixelFormat.Format24bppRgb);
+ try
+ {
+ Assert.Equal(bmp.Height, data.Height);
+ Assert.Equal(bmp.Width, data.Width);
+ Assert.Equal(PixelFormat.Format24bppRgb, data.PixelFormat);
+ Assert.Equal(64, data.Height);
+
+ unsafe
+ {
+ byte* scan = (byte*)data.Scan0;
+ // sampling values from a well known bitmap
+ Assert.Equal(153, *(scan + 0));
+ Assert.Equal(0, *(scan + 97));
+ Assert.Equal(255, *(scan + 194));
+ Assert.Equal(0, *(scan + 291));
+ Assert.Equal(0, *(scan + 388));
+ Assert.Equal(204, *(scan + 485));
+ Assert.Equal(204, *(scan + 582));
+ Assert.Equal(0, *(scan + 679));
+ Assert.Equal(204, *(scan + 776));
+ Assert.Equal(153, *(scan + 873));
+ Assert.Equal(0, *(scan + 970));
+ Assert.Equal(0, *(scan + 1067));
+ Assert.Equal(153, *(scan + 1164));
+ Assert.Equal(153, *(scan + 1261));
+ Assert.Equal(102, *(scan + 1358));
+ Assert.Equal(0, *(scan + 1455));
+ Assert.Equal(0, *(scan + 1552));
+ Assert.Equal(204, *(scan + 1649));
+ Assert.Equal(153, *(scan + 1746));
+ Assert.Equal(0, *(scan + 1843));
+ Assert.Equal(0, *(scan + 1940));
+ Assert.Equal(51, *(scan + 2037));
+ Assert.Equal(0, *(scan + 2134));
+ Assert.Equal(0, *(scan + 2231));
+ Assert.Equal(102, *(scan + 2328));
+ Assert.Equal(124, *(scan + 2425));
+ Assert.Equal(204, *(scan + 2522));
+ Assert.Equal(0, *(scan + 2619));
+ Assert.Equal(0, *(scan + 2716));
+ Assert.Equal(204, *(scan + 2813));
+ Assert.Equal(51, *(scan + 2910));
+ Assert.Equal(0, *(scan + 3007));
+ Assert.Equal(255, *(scan + 3104));
+ Assert.Equal(0, *(scan + 3201));
+ Assert.Equal(0, *(scan + 3298));
+ Assert.Equal(0, *(scan + 3395));
+ Assert.Equal(128, *(scan + 3492));
+ Assert.Equal(0, *(scan + 3589));
+ Assert.Equal(255, *(scan + 3686));
+ Assert.Equal(128, *(scan + 3783));
+ Assert.Equal(0, *(scan + 3880));
+ Assert.Equal(128, *(scan + 3977));
+ Assert.Equal(0, *(scan + 4074));
+ Assert.Equal(0, *(scan + 4171));
+ Assert.Equal(204, *(scan + 4268));
+ Assert.Equal(0, *(scan + 4365));
+ Assert.Equal(0, *(scan + 4462));
+ Assert.Equal(102, *(scan + 4559));
+ Assert.Equal(0, *(scan + 4656));
+ Assert.Equal(0, *(scan + 4753));
+ Assert.Equal(102, *(scan + 4850));
+ Assert.Equal(0, *(scan + 4947));
+ Assert.Equal(0, *(scan + 5044));
+ Assert.Equal(204, *(scan + 5141));
+ Assert.Equal(128, *(scan + 5238));
+ Assert.Equal(0, *(scan + 5335));
+ Assert.Equal(128, *(scan + 5432));
+ Assert.Equal(128, *(scan + 5529));
+ Assert.Equal(0, *(scan + 5626));
+ Assert.Equal(255, *(scan + 5723));
+ Assert.Equal(153, *(scan + 5820));
+ Assert.Equal(0, *(scan + 5917));
+ Assert.Equal(0, *(scan + 6014));
+ Assert.Equal(51, *(scan + 6111));
+ Assert.Equal(0, *(scan + 6208));
+ Assert.Equal(255, *(scan + 6305));
+ Assert.Equal(153, *(scan + 6402));
+ Assert.Equal(0, *(scan + 6499));
+ Assert.Equal(153, *(scan + 6596));
+ Assert.Equal(102, *(scan + 6693));
+ Assert.Equal(0, *(scan + 6790));
+ Assert.Equal(204, *(scan + 6887));
+ Assert.Equal(153, *(scan + 6984));
+ Assert.Equal(0, *(scan + 7081));
+ Assert.Equal(204, *(scan + 7178));
+ Assert.Equal(153, *(scan + 7275));
+ Assert.Equal(0, *(scan + 7372));
+ Assert.Equal(0, *(scan + 7469));
+ Assert.Equal(153, *(scan + 7566));
+ Assert.Equal(0, *(scan + 7663));
+ Assert.Equal(0, *(scan + 7760));
+ Assert.Equal(153, *(scan + 7857));
+ Assert.Equal(102, *(scan + 7954));
+ Assert.Equal(102, *(scan + 8051));
+ Assert.Equal(0, *(scan + 8148));
+ Assert.Equal(0, *(scan + 8245));
+ Assert.Equal(0, *(scan + 8342));
+ Assert.Equal(204, *(scan + 8439));
+ Assert.Equal(0, *(scan + 8536));
+ Assert.Equal(204, *(scan + 8633));
+ Assert.Equal(128, *(scan + 8730));
+ Assert.Equal(0, *(scan + 8827));
+ Assert.Equal(0, *(scan + 8924));
+ Assert.Equal(153, *(scan + 9021));
+ Assert.Equal(153, *(scan + 9118));
+ Assert.Equal(255, *(scan + 9215));
+ Assert.Equal(0, *(scan + 9312));
+ Assert.Equal(0, *(scan + 9409));
+ Assert.Equal(204, *(scan + 9506));
+ Assert.Equal(0, *(scan + 9603));
+ Assert.Equal(0, *(scan + 9700));
+ Assert.Equal(0, *(scan + 9797));
+ Assert.Equal(128, *(scan + 9894));
+ Assert.Equal(0, *(scan + 9991));
+ Assert.Equal(0, *(scan + 10088));
+ Assert.Equal(0, *(scan + 10185));
+ Assert.Equal(102, *(scan + 10282));
+ Assert.Equal(0, *(scan + 10379));
+ Assert.Equal(0, *(scan + 10476));
+ Assert.Equal(51, *(scan + 10573));
+ Assert.Equal(204, *(scan + 10670));
+ Assert.Equal(0, *(scan + 10767));
+ Assert.Equal(0, *(scan + 10864));
+ Assert.Equal(0, *(scan + 10961));
+ Assert.Equal(153, *(scan + 11058));
+ Assert.Equal(0, *(scan + 11155));
+ Assert.Equal(0, *(scan + 11252));
+ Assert.Equal(153, *(scan + 11349));
+ Assert.Equal(51, *(scan + 11446));
+ Assert.Equal(0, *(scan + 11543));
+ Assert.Equal(0, *(scan + 11640));
+ Assert.Equal(0, *(scan + 11737));
+ Assert.Equal(204, *(scan + 11834));
+ Assert.Equal(0, *(scan + 11931));
+ Assert.Equal(0, *(scan + 12028));
+ Assert.Equal(255, *(scan + 12125));
+ Assert.Equal(153, *(scan + 12222));
+ }
+ }
+ finally
+ {
+ bmp.UnlockBits(data);
+ }
+ }
+ }
+
+ // 96x96x256.ico only has a 96x96 size available
+ [ConditionalFact(Helpers.RecentGdiplusIsAvailable)]
+ public void Bitmap96Features()
+ {
+ string sInFile = Helpers.GetTestBitmapPath("96x96_one_entry_8bit.ico");
+ using (Bitmap bmp = new Bitmap(sInFile))
+ {
+ GraphicsUnit unit = GraphicsUnit.World;
+ RectangleF rect = bmp.GetBounds(ref unit);
+
+ Assert.True(bmp.RawFormat.Equals(ImageFormat.Icon));
+ Assert.Equal(PixelFormat.Format32bppArgb, bmp.PixelFormat);
+ Assert.Equal(73746, bmp.Flags);
+
+ Assert.Equal(1, bmp.FrameDimensionsList.Length);
+ Assert.Equal(0, bmp.PropertyIdList.Length);
+ Assert.Equal(0, bmp.PropertyItems.Length);
+ Assert.Null(bmp.Tag);
+ Assert.Equal(96.0f, bmp.HorizontalResolution);
+ Assert.Equal(96.0f, bmp.VerticalResolution);
+ Assert.Equal(96, bmp.Width);
+ Assert.Equal(96, bmp.Height);
+
+ Assert.Equal(0, rect.X);
+ Assert.Equal(0, rect.Y);
+ Assert.Equal(96, rect.Width);
+ Assert.Equal(96, rect.Height);
+
+ Assert.Equal(96, bmp.Size.Width);
+ Assert.Equal(96, bmp.Size.Height);
+ }
+ }
+
+ [PlatformSpecific(TestPlatforms.AnyUnix)]
+ [ConditionalFact(Helpers.RecentGdiplusIsAvailable)]
+ public void Bitmap96Features_Palette_Entries_Unix()
+ {
+ string sInFile = Helpers.GetTestBitmapPath("96x96_one_entry_8bit.ico");
+ using (Bitmap bmp = new Bitmap(sInFile))
+ {
+ // This value is inconsistent accross Unix and Windows.
+ Assert.Equal(256, bmp.Palette.Entries.Length);
+ }
+ }
+
+ [PlatformSpecific(TestPlatforms.Windows)]
+ [ConditionalFact(Helpers.RecentGdiplusIsAvailable)]
+ public void Bitmap96Features_Palette_Entries_Windows()
+ {
+ string sInFile = Helpers.GetTestBitmapPath("96x96_one_entry_8bit.ico");
+ using (Bitmap bmp = new Bitmap(sInFile))
+ {
+ // This value is inconsistent accross Unix and Windows.
+ Assert.Equal(0, bmp.Palette.Entries.Length);
+ }
+ }
+
+ [ConditionalFact(Helpers.RecentGdiplusIsAvailable)]
+ public void Bitmap96Pixels()
+ {
+ string sInFile = Helpers.GetTestBitmapPath("96x96_one_entry_8bit.ico");
+ using (Bitmap bmp = new Bitmap(sInFile))
+ {
+ // sampling values from a well known bitmap
+ Assert.Equal(0, bmp.GetPixel(0, 0).ToArgb());
+ Assert.Equal(0, bmp.GetPixel(0, 4).ToArgb());
+ Assert.Equal(0, bmp.GetPixel(0, 8).ToArgb());
+ Assert.Equal(0, bmp.GetPixel(0, 12).ToArgb());
+ Assert.Equal(0, bmp.GetPixel(0, 16).ToArgb());
+ Assert.Equal(0, bmp.GetPixel(0, 20).ToArgb());
+ Assert.Equal(0, bmp.GetPixel(0, 24).ToArgb());
+ Assert.Equal(0, bmp.GetPixel(0, 28).ToArgb());
+ Assert.Equal(0, bmp.GetPixel(0, 32).ToArgb());
+ Assert.Equal(0, bmp.GetPixel(0, 36).ToArgb());
+ Assert.Equal(0, bmp.GetPixel(0, 40).ToArgb());
+ Assert.Equal(0, bmp.GetPixel(0, 44).ToArgb());
+ Assert.Equal(0, bmp.GetPixel(0, 48).ToArgb());
+ Assert.Equal(0, bmp.GetPixel(0, 52).ToArgb());
+ Assert.Equal(0, bmp.GetPixel(0, 56).ToArgb());
+ Assert.Equal(0, bmp.GetPixel(0, 60).ToArgb());
+ Assert.Equal(0, bmp.GetPixel(0, 64).ToArgb());
+ Assert.Equal(-14935012, bmp.GetPixel(0, 68).ToArgb());
+ Assert.Equal(0, bmp.GetPixel(0, 72).ToArgb());
+ Assert.Equal(0, bmp.GetPixel(0, 76).ToArgb());
+ Assert.Equal(0, bmp.GetPixel(0, 80).ToArgb());
+ Assert.Equal(0, bmp.GetPixel(0, 84).ToArgb());
+ Assert.Equal(0, bmp.GetPixel(0, 88).ToArgb());
+ Assert.Equal(0, bmp.GetPixel(0, 92).ToArgb());
+ Assert.Equal(0, bmp.GetPixel(4, 0).ToArgb());
+ Assert.Equal(0, bmp.GetPixel(4, 4).ToArgb());
+ Assert.Equal(-14935012, bmp.GetPixel(4, 8).ToArgb());
+ Assert.Equal(-3407872, bmp.GetPixel(4, 12).ToArgb());
+ Assert.Equal(-3407872, bmp.GetPixel(4, 16).ToArgb());
+ Assert.Equal(-14935012, bmp.GetPixel(4, 20).ToArgb());
+ Assert.Equal(0, bmp.GetPixel(4, 24).ToArgb());
+ Assert.Equal(0, bmp.GetPixel(4, 28).ToArgb());
+ Assert.Equal(0, bmp.GetPixel(4, 32).ToArgb());
+ Assert.Equal(0, bmp.GetPixel(4, 36).ToArgb());
+ Assert.Equal(-3368602, bmp.GetPixel(4, 40).ToArgb());
+ Assert.Equal(-3368602, bmp.GetPixel(4, 44).ToArgb());
+ Assert.Equal(-3368602, bmp.GetPixel(4, 48).ToArgb());
+ Assert.Equal(-3368602, bmp.GetPixel(4, 52).ToArgb());
+ Assert.Equal(0, bmp.GetPixel(4, 56).ToArgb());
+ Assert.Equal(0, bmp.GetPixel(4, 60).ToArgb());
+ Assert.Equal(-3342541, bmp.GetPixel(4, 64).ToArgb());
+ Assert.Equal(-3342541, bmp.GetPixel(4, 68).ToArgb());
+ Assert.Equal(-3342541, bmp.GetPixel(4, 72).ToArgb());
+ Assert.Equal(0, bmp.GetPixel(4, 76).ToArgb());
+ Assert.Equal(0, bmp.GetPixel(4, 80).ToArgb());
+ Assert.Equal(-26317, bmp.GetPixel(4, 84).ToArgb());
+ Assert.Equal(-26317, bmp.GetPixel(4, 88).ToArgb());
+ Assert.Equal(-26317, bmp.GetPixel(4, 92).ToArgb());
+ Assert.Equal(0, bmp.GetPixel(8, 0).ToArgb());
+ Assert.Equal(-14935012, bmp.GetPixel(8, 4).ToArgb());
+ Assert.Equal(-3407872, bmp.GetPixel(8, 8).ToArgb());
+ Assert.Equal(-3407872, bmp.GetPixel(8, 12).ToArgb());
+ Assert.Equal(-3407872, bmp.GetPixel(8, 16).ToArgb());
+ Assert.Equal(-3407872, bmp.GetPixel(8, 20).ToArgb());
+ Assert.Equal(-14935012, bmp.GetPixel(8, 24).ToArgb());
+ Assert.Equal(0, bmp.GetPixel(8, 28).ToArgb());
+ Assert.Equal(0, bmp.GetPixel(8, 32).ToArgb());
+ Assert.Equal(-3368602, bmp.GetPixel(8, 36).ToArgb());
+ Assert.Equal(-3368602, bmp.GetPixel(8, 40).ToArgb());
+ Assert.Equal(-3368602, bmp.GetPixel(8, 44).ToArgb());
+ Assert.Equal(-3368602, bmp.GetPixel(8, 48).ToArgb());
+ Assert.Equal(-3368602, bmp.GetPixel(8, 52).ToArgb());
+ Assert.Equal(-3368602, bmp.GetPixel(8, 56).ToArgb());
+ Assert.Equal(0, bmp.GetPixel(8, 60).ToArgb());
+ Assert.Equal(-3342541, bmp.GetPixel(8, 64).ToArgb());
+ Assert.Equal(-3342541, bmp.GetPixel(8, 68).ToArgb());
+ Assert.Equal(-3342541, bmp.GetPixel(8, 72).ToArgb());
+ Assert.Equal(0, bmp.GetPixel(8, 76).ToArgb());
+ Assert.Equal(0, bmp.GetPixel(8, 80).ToArgb());
+ Assert.Equal(-26317, bmp.GetPixel(8, 84).ToArgb());
+ Assert.Equal(-26317, bmp.GetPixel(8, 88).ToArgb());
+ Assert.Equal(-26317, bmp.GetPixel(8, 92).ToArgb());
+ Assert.Equal(0, bmp.GetPixel(12, 0).ToArgb());
+ Assert.Equal(-3407872, bmp.GetPixel(12, 4).ToArgb());
+ Assert.Equal(-3407872, bmp.GetPixel(12, 8).ToArgb());
+ Assert.Equal(-3407872, bmp.GetPixel(12, 12).ToArgb());
+ Assert.Equal(-3407872, bmp.GetPixel(12, 16).ToArgb());
+ Assert.Equal(-3407872, bmp.GetPixel(12, 20).ToArgb());
+ Assert.Equal(-3407872, bmp.GetPixel(12, 24).ToArgb());
+ Assert.Equal(0, bmp.GetPixel(12, 28).ToArgb());
+ Assert.Equal(-3368602, bmp.GetPixel(12, 32).ToArgb());
+ Assert.Equal(-3368602, bmp.GetPixel(12, 36).ToArgb());
+ Assert.Equal(-3368602, bmp.GetPixel(12, 40).ToArgb());
+ Assert.Equal(-3368602, bmp.GetPixel(12, 44).ToArgb());
+ Assert.Equal(-3368602, bmp.GetPixel(12, 48).ToArgb());
+ Assert.Equal(-3368602, bmp.GetPixel(12, 52).ToArgb());
+ Assert.Equal(-3368602, bmp.GetPixel(12, 56).ToArgb());
+ Assert.Equal(-3368602, bmp.GetPixel(12, 60).ToArgb());
+ Assert.Equal(-3342541, bmp.GetPixel(12, 64).ToArgb());
+ Assert.Equal(-3342541, bmp.GetPixel(12, 68).ToArgb());
+ Assert.Equal(-14935012, bmp.GetPixel(12, 72).ToArgb());
+ Assert.Equal(0, bmp.GetPixel(12, 76).ToArgb());
+ Assert.Equal(0, bmp.GetPixel(12, 80).ToArgb());
+ Assert.Equal(-26317, bmp.GetPixel(12, 84).ToArgb());
+ Assert.Equal(-26317, bmp.GetPixel(12, 88).ToArgb());
+ Assert.Equal(-26317, bmp.GetPixel(12, 92).ToArgb());
+ Assert.Equal(0, bmp.GetPixel(16, 0).ToArgb());
+ Assert.Equal(-3407872, bmp.GetPixel(16, 4).ToArgb());
+ Assert.Equal(-3407872, bmp.GetPixel(16, 8).ToArgb());
+ Assert.Equal(-3407872, bmp.GetPixel(16, 12).ToArgb());
+ Assert.Equal(-3407872, bmp.GetPixel(16, 16).ToArgb());
+ Assert.Equal(-3407872, bmp.GetPixel(16, 20).ToArgb());
+ Assert.Equal(-3407872, bmp.GetPixel(16, 24).ToArgb());
+ Assert.Equal(0, bmp.GetPixel(16, 28).ToArgb());
+ Assert.Equal(-3368602, bmp.GetPixel(16, 32).ToArgb());
+ Assert.Equal(-3368602, bmp.GetPixel(16, 36).ToArgb());
+ Assert.Equal(-3368602, bmp.GetPixel(16, 40).ToArgb());
+ Assert.Equal(-3368602, bmp.GetPixel(16, 44).ToArgb());
+ Assert.Equal(-3368602, bmp.GetPixel(16, 48).ToArgb());
+ Assert.Equal(-3368602, bmp.GetPixel(16, 52).ToArgb());
+ Assert.Equal(-3368602, bmp.GetPixel(16, 56).ToArgb());
+ Assert.Equal(-3368602, bmp.GetPixel(16, 60).ToArgb());
+ Assert.Equal(0, bmp.GetPixel(16, 64).ToArgb());
+ Assert.Equal(0, bmp.GetPixel(16, 68).ToArgb());
+ Assert.Equal(0, bmp.GetPixel(16, 72).ToArgb());
+ Assert.Equal(0, bmp.GetPixel(16, 76).ToArgb());
+ Assert.Equal(-14935012, bmp.GetPixel(16, 80).ToArgb());
+ Assert.Equal(0, bmp.GetPixel(16, 84).ToArgb());
+ Assert.Equal(-14935012, bmp.GetPixel(16, 88).ToArgb());
+ Assert.Equal(0, bmp.GetPixel(16, 92).ToArgb());
+ Assert.Equal(0, bmp.GetPixel(20, 0).ToArgb());
+ Assert.Equal(-14935012, bmp.GetPixel(20, 4).ToArgb());
+ Assert.Equal(-3407872, bmp.GetPixel(20, 8).ToArgb());
+ Assert.Equal(-3407872, bmp.GetPixel(20, 12).ToArgb());
+ Assert.Equal(-3407872, bmp.GetPixel(20, 16).ToArgb());
+ Assert.Equal(-3407872, bmp.GetPixel(20, 20).ToArgb());
+ Assert.Equal(-14935012, bmp.GetPixel(20, 24).ToArgb());
+ Assert.Equal(0, bmp.GetPixel(20, 28).ToArgb());
+ Assert.Equal(-3368602, bmp.GetPixel(20, 32).ToArgb());
+ Assert.Equal(-3368602, bmp.GetPixel(20, 36).ToArgb());
+ Assert.Equal(-3368602, bmp.GetPixel(20, 40).ToArgb());
+ Assert.Equal(-3368602, bmp.GetPixel(20, 44).ToArgb());
+ Assert.Equal(-3368602, bmp.GetPixel(20, 48).ToArgb());
+ Assert.Equal(-3368602, bmp.GetPixel(20, 52).ToArgb());
+ Assert.Equal(-3368602, bmp.GetPixel(20, 56).ToArgb());
+ Assert.Equal(-3368602, bmp.GetPixel(20, 60).ToArgb());
+ Assert.Equal(0, bmp.GetPixel(20, 64).ToArgb());
+ Assert.Equal(0, bmp.GetPixel(20, 68).ToArgb());
+ Assert.Equal(-13434829, bmp.GetPixel(20, 72).ToArgb());
+ Assert.Equal(-13434829, bmp.GetPixel(20, 76).ToArgb());
+ Assert.Equal(-13434829, bmp.GetPixel(20, 80).ToArgb());
+ Assert.Equal(-13434829, bmp.GetPixel(20, 84).ToArgb());
+ Assert.Equal(-13434829, bmp.GetPixel(20, 88).ToArgb());
+ Assert.Equal(0, bmp.GetPixel(20, 92).ToArgb());
+ Assert.Equal(0, bmp.GetPixel(24, 0).ToArgb());
+ Assert.Equal(0, bmp.GetPixel(24, 4).ToArgb());
+ Assert.Equal(-14935012, bmp.GetPixel(24, 8).ToArgb());
+ Assert.Equal(-3407872, bmp.GetPixel(24, 12).ToArgb());
+ Assert.Equal(-3407872, bmp.GetPixel(24, 16).ToArgb());
+ Assert.Equal(-14935012, bmp.GetPixel(24, 20).ToArgb());
+ Assert.Equal(0, bmp.GetPixel(24, 24).ToArgb());
+ Assert.Equal(0, bmp.GetPixel(24, 28).ToArgb());
+ Assert.Equal(-3368602, bmp.GetPixel(24, 32).ToArgb());
+ Assert.Equal(-3368602, bmp.GetPixel(24, 36).ToArgb());
+ Assert.Equal(-3368602, bmp.GetPixel(24, 40).ToArgb());
+ Assert.Equal(-3368602, bmp.GetPixel(24, 44).ToArgb());
+ Assert.Equal(-3368602, bmp.GetPixel(24, 48).ToArgb());
+ Assert.Equal(-3368602, bmp.GetPixel(24, 52).ToArgb());
+ Assert.Equal(-3368602, bmp.GetPixel(24, 56).ToArgb());
+ Assert.Equal(-3368602, bmp.GetPixel(24, 60).ToArgb());
+ Assert.Equal(0, bmp.GetPixel(24, 64).ToArgb());
+ Assert.Equal(-13434829, bmp.GetPixel(24, 68).ToArgb());
+ Assert.Equal(-13434829, bmp.GetPixel(24, 72).ToArgb());
+ Assert.Equal(-13434829, bmp.GetPixel(24, 76).ToArgb());
+ Assert.Equal(-13434829, bmp.GetPixel(24, 80).ToArgb());
+ Assert.Equal(-13434829, bmp.GetPixel(24, 84).ToArgb());
+ Assert.Equal(-13434829, bmp.GetPixel(24, 88).ToArgb());
+ Assert.Equal(-14935012, bmp.GetPixel(24, 92).ToArgb());
+ Assert.Equal(0, bmp.GetPixel(28, 0).ToArgb());
+ Assert.Equal(0, bmp.GetPixel(28, 4).ToArgb());
+ Assert.Equal(-14935012, bmp.GetPixel(28, 8).ToArgb());
+ Assert.Equal(0, bmp.GetPixel(28, 12).ToArgb());
+ Assert.Equal(0, bmp.GetPixel(28, 16).ToArgb());
+ Assert.Equal(-14935012, bmp.GetPixel(28, 20).ToArgb());
+ Assert.Equal(-16777012, bmp.GetPixel(28, 24).ToArgb());
+ Assert.Equal(0, bmp.GetPixel(28, 28).ToArgb());
+ Assert.Equal(-3368602, bmp.GetPixel(28, 32).ToArgb());
+ Assert.Equal(-3368602, bmp.GetPixel(28, 36).ToArgb());
+ Assert.Equal(-3368602, bmp.GetPixel(28, 40).ToArgb());
+ Assert.Equal(-3368602, bmp.GetPixel(28, 44).ToArgb());
+ Assert.Equal(-3368602, bmp.GetPixel(28, 48).ToArgb());
+ Assert.Equal(-3368602, bmp.GetPixel(28, 52).ToArgb());
+ Assert.Equal(-3368602, bmp.GetPixel(28, 56).ToArgb());
+ Assert.Equal(-3368602, bmp.GetPixel(28, 60).ToArgb());
+ Assert.Equal(0, bmp.GetPixel(28, 64).ToArgb());
+ Assert.Equal(-13434829, bmp.GetPixel(28, 68).ToArgb());
+ Assert.Equal(-13434829, bmp.GetPixel(28, 72).ToArgb());
+ Assert.Equal(-13434829, bmp.GetPixel(28, 76).ToArgb());
+ Assert.Equal(-13434829, bmp.GetPixel(28, 80).ToArgb());
+ Assert.Equal(-13434829, bmp.GetPixel(28, 84).ToArgb());
+ Assert.Equal(-13434829, bmp.GetPixel(28, 88).ToArgb());
+ Assert.Equal(-13434829, bmp.GetPixel(28, 92).ToArgb());
+ Assert.Equal(0, bmp.GetPixel(32, 0).ToArgb());
+ Assert.Equal(-10027264, bmp.GetPixel(32, 4).ToArgb());
+ Assert.Equal(-10027264, bmp.GetPixel(32, 8).ToArgb());
+ Assert.Equal(-10027264, bmp.GetPixel(32, 12).ToArgb());
+ Assert.Equal(-14935012, bmp.GetPixel(32, 16).ToArgb());
+ Assert.Equal(-16777012, bmp.GetPixel(32, 20).ToArgb());
+ Assert.Equal(-16777012, bmp.GetPixel(32, 24).ToArgb());
+ Assert.Equal(-16777012, bmp.GetPixel(32, 28).ToArgb());
+ Assert.Equal(0, bmp.GetPixel(32, 32).ToArgb());
+ Assert.Equal(-3368602, bmp.GetPixel(32, 36).ToArgb());
+ Assert.Equal(-3368602, bmp.GetPixel(32, 40).ToArgb());
+ Assert.Equal(-3368602, bmp.GetPixel(32, 44).ToArgb());
+ Assert.Equal(-3368602, bmp.GetPixel(32, 48).ToArgb());
+ Assert.Equal(-3368602, bmp.GetPixel(32, 52).ToArgb());
+ Assert.Equal(-3368602, bmp.GetPixel(32, 56).ToArgb());
+ Assert.Equal(0, bmp.GetPixel(32, 60).ToArgb());
+ Assert.Equal(0, bmp.GetPixel(32, 64).ToArgb());
+ Assert.Equal(-13434829, bmp.GetPixel(32, 68).ToArgb());
+ Assert.Equal(-13434829, bmp.GetPixel(32, 72).ToArgb());
+ Assert.Equal(-13434829, bmp.GetPixel(32, 76).ToArgb());
+ Assert.Equal(-13434829, bmp.GetPixel(32, 80).ToArgb());
+ Assert.Equal(-13434829, bmp.GetPixel(32, 84).ToArgb());
+ Assert.Equal(-13434829, bmp.GetPixel(32, 88).ToArgb());
+ Assert.Equal(-13434829, bmp.GetPixel(32, 92).ToArgb());
+ Assert.Equal(0, bmp.GetPixel(36, 0).ToArgb());
+ Assert.Equal(-10027264, bmp.GetPixel(36, 4).ToArgb());
+ Assert.Equal(-10027264, bmp.GetPixel(36, 8).ToArgb());
+ Assert.Equal(-10027264, bmp.GetPixel(36, 12).ToArgb());
+ Assert.Equal(-10027264, bmp.GetPixel(36, 16).ToArgb());
+ Assert.Equal(-14935012, bmp.GetPixel(36, 20).ToArgb());
+ Assert.Equal(-16777012, bmp.GetPixel(36, 24).ToArgb());
+ Assert.Equal(0, bmp.GetPixel(36, 28).ToArgb());
+ Assert.Equal(0, bmp.GetPixel(36, 32).ToArgb());
+ Assert.Equal(0, bmp.GetPixel(36, 36).ToArgb());
+ Assert.Equal(-3368602, bmp.GetPixel(36, 40).ToArgb());
+ Assert.Equal(-3368602, bmp.GetPixel(36, 44).ToArgb());
+ Assert.Equal(-3368602, bmp.GetPixel(36, 48).ToArgb());
+ Assert.Equal(-3368602, bmp.GetPixel(36, 52).ToArgb());
+ Assert.Equal(0, bmp.GetPixel(36, 56).ToArgb());
+ Assert.Equal(0, bmp.GetPixel(36, 60).ToArgb());
+ Assert.Equal(0, bmp.GetPixel(36, 64).ToArgb());
+ Assert.Equal(-13434829, bmp.GetPixel(36, 68).ToArgb());
+ Assert.Equal(-13434829, bmp.GetPixel(36, 72).ToArgb());
+ Assert.Equal(-13434829, bmp.GetPixel(36, 76).ToArgb());
+ Assert.Equal(-13434829, bmp.GetPixel(36, 80).ToArgb());
+ Assert.Equal(-13434829, bmp.GetPixel(36, 84).ToArgb());
+ Assert.Equal(-13434829, bmp.GetPixel(36, 88).ToArgb());
+ Assert.Equal(-13434829, bmp.GetPixel(36, 92).ToArgb());
+ Assert.Equal(0, bmp.GetPixel(40, 0).ToArgb());
+ Assert.Equal(-10027264, bmp.GetPixel(40, 4).ToArgb());
+ Assert.Equal(-10027264, bmp.GetPixel(40, 8).ToArgb());
+ Assert.Equal(-10027264, bmp.GetPixel(40, 12).ToArgb());
+ Assert.Equal(-14935012, bmp.GetPixel(40, 16).ToArgb());
+ Assert.Equal(0, bmp.GetPixel(40, 20).ToArgb());
+ Assert.Equal(0, bmp.GetPixel(40, 24).ToArgb());
+ Assert.Equal(0, bmp.GetPixel(40, 28).ToArgb());
+ Assert.Equal(-13408717, bmp.GetPixel(40, 32).ToArgb());
+ Assert.Equal(-13408717, bmp.GetPixel(40, 36).ToArgb());
+ Assert.Equal(0, bmp.GetPixel(40, 40).ToArgb());
+ Assert.Equal(0, bmp.GetPixel(40, 44).ToArgb());
+ Assert.Equal(-14935012, bmp.GetPixel(40, 48).ToArgb());
+ Assert.Equal(0, bmp.GetPixel(40, 52).ToArgb());
+ Assert.Equal(0, bmp.GetPixel(40, 56).ToArgb());
+ Assert.Equal(-26317, bmp.GetPixel(40, 60).ToArgb());
+ Assert.Equal(-26317, bmp.GetPixel(40, 64).ToArgb());
+ Assert.Equal(-14935012, bmp.GetPixel(40, 68).ToArgb());
+ Assert.Equal(-13434829, bmp.GetPixel(40, 72).ToArgb());
+ Assert.Equal(-13434829, bmp.GetPixel(40, 76).ToArgb());
+ Assert.Equal(-13434829, bmp.GetPixel(40, 80).ToArgb());
+ Assert.Equal(-13434829, bmp.GetPixel(40, 84).ToArgb());
+ Assert.Equal(-13434829, bmp.GetPixel(40, 88).ToArgb());
+ Assert.Equal(0, bmp.GetPixel(40, 92).ToArgb());
+ Assert.Equal(0, bmp.GetPixel(44, 0).ToArgb());
+ Assert.Equal(0, bmp.GetPixel(44, 4).ToArgb());
+ Assert.Equal(-14935012, bmp.GetPixel(44, 8).ToArgb());
+ Assert.Equal(0, bmp.GetPixel(44, 12).ToArgb());
+ Assert.Equal(0, bmp.GetPixel(44, 16).ToArgb());
+ Assert.Equal(0, bmp.GetPixel(44, 20).ToArgb());
+ Assert.Equal(0, bmp.GetPixel(44, 24).ToArgb());
+ Assert.Equal(0, bmp.GetPixel(44, 28).ToArgb());
+ Assert.Equal(-13408717, bmp.GetPixel(44, 32).ToArgb());
+ Assert.Equal(-13408717, bmp.GetPixel(44, 36).ToArgb());
+ Assert.Equal(0, bmp.GetPixel(44, 40).ToArgb());
+ Assert.Equal(-13312, bmp.GetPixel(44, 44).ToArgb());
+ Assert.Equal(-13312, bmp.GetPixel(44, 48).ToArgb());
+ Assert.Equal(-13312, bmp.GetPixel(44, 52).ToArgb());
+ Assert.Equal(-13312, bmp.GetPixel(44, 56).ToArgb());
+ Assert.Equal(-14935012, bmp.GetPixel(44, 60).ToArgb());
+ Assert.Equal(-14935012, bmp.GetPixel(44, 64).ToArgb());
+ Assert.Equal(0, bmp.GetPixel(44, 68).ToArgb());
+ Assert.Equal(-14935012, bmp.GetPixel(44, 72).ToArgb());
+ Assert.Equal(-13434829, bmp.GetPixel(44, 76).ToArgb());
+ Assert.Equal(-13434829, bmp.GetPixel(44, 80).ToArgb());
+ Assert.Equal(-13434829, bmp.GetPixel(44, 84).ToArgb());
+ Assert.Equal(-14935012, bmp.GetPixel(44, 88).ToArgb());
+ Assert.Equal(0, bmp.GetPixel(44, 92).ToArgb());
+ Assert.Equal(0, bmp.GetPixel(48, 0).ToArgb());
+ Assert.Equal(0, bmp.GetPixel(48, 4).ToArgb());
+ Assert.Equal(0, bmp.GetPixel(48, 8).ToArgb());
+ Assert.Equal(0, bmp.GetPixel(48, 12).ToArgb());
+ Assert.Equal(-52429, bmp.GetPixel(48, 16).ToArgb());
+ Assert.Equal(-52429, bmp.GetPixel(48, 20).ToArgb());
+ Assert.Equal(-52429, bmp.GetPixel(48, 24).ToArgb());
+ Assert.Equal(-52429, bmp.GetPixel(48, 28).ToArgb());
+ Assert.Equal(-14935012, bmp.GetPixel(48, 32).ToArgb());
+ Assert.Equal(0, bmp.GetPixel(48, 36).ToArgb());
+ Assert.Equal(-14935012, bmp.GetPixel(48, 40).ToArgb());
+ Assert.Equal(-13312, bmp.GetPixel(48, 44).ToArgb());
+ Assert.Equal(-13312, bmp.GetPixel(48, 48).ToArgb());
+ Assert.Equal(-13312, bmp.GetPixel(48, 52).ToArgb());
+ Assert.Equal(-13312, bmp.GetPixel(48, 56).ToArgb());
+ Assert.Equal(0, bmp.GetPixel(48, 60).ToArgb());
+ // Assert.Equal(1842204, bmp.GetPixel(48, 64).ToArgb());
+ Assert.Equal(-3355546, bmp.GetPixel(48, 68).ToArgb());
+ Assert.Equal(-3355546, bmp.GetPixel(48, 72).ToArgb());
+ Assert.Equal(0, bmp.GetPixel(48, 76).ToArgb());
+ Assert.Equal(0, bmp.GetPixel(48, 80).ToArgb());
+ Assert.Equal(0, bmp.GetPixel(48, 84).ToArgb());
+ Assert.Equal(0, bmp.GetPixel(48, 88).ToArgb());
+ Assert.Equal(0, bmp.GetPixel(48, 92).ToArgb());
+ Assert.Equal(0, bmp.GetPixel(52, 0).ToArgb());
+ Assert.Equal(0, bmp.GetPixel(52, 4).ToArgb());
+ Assert.Equal(-14935012, bmp.GetPixel(52, 8).ToArgb());
+ Assert.Equal(-52429, bmp.GetPixel(52, 12).ToArgb());
+ Assert.Equal(-52429, bmp.GetPixel(52, 16).ToArgb());
+ Assert.Equal(-52429, bmp.GetPixel(52, 20).ToArgb());
+ Assert.Equal(-52429, bmp.GetPixel(52, 24).ToArgb());
+ Assert.Equal(-52429, bmp.GetPixel(52, 28).ToArgb());
+ Assert.Equal(-52429, bmp.GetPixel(52, 32).ToArgb());
+ Assert.Equal(-52429, bmp.GetPixel(52, 36).ToArgb());
+ Assert.Equal(-14935012, bmp.GetPixel(52, 40).ToArgb());
+ Assert.Equal(-13312, bmp.GetPixel(52, 44).ToArgb());
+ Assert.Equal(-13312, bmp.GetPixel(52, 48).ToArgb());
+ Assert.Equal(-13312, bmp.GetPixel(52, 52).ToArgb());
+ Assert.Equal(-13312, bmp.GetPixel(52, 56).ToArgb());
+ Assert.Equal(0, bmp.GetPixel(52, 60).ToArgb());
+ Assert.Equal(-3355546, bmp.GetPixel(52, 64).ToArgb());
+ Assert.Equal(-3355546, bmp.GetPixel(52, 68).ToArgb());
+ Assert.Equal(-3355546, bmp.GetPixel(52, 72).ToArgb());
+ Assert.Equal(-3355546, bmp.GetPixel(52, 76).ToArgb());
+ Assert.Equal(0, bmp.GetPixel(52, 80).ToArgb());
+ Assert.Equal(-6737101, bmp.GetPixel(52, 84).ToArgb());
+ Assert.Equal(-6737101, bmp.GetPixel(52, 88).ToArgb());
+ Assert.Equal(-6737101, bmp.GetPixel(52, 92).ToArgb());
+ Assert.Equal(0, bmp.GetPixel(56, 0).ToArgb());
+ Assert.Equal(0, bmp.GetPixel(56, 4).ToArgb());
+ Assert.Equal(-52429, bmp.GetPixel(56, 8).ToArgb());
+ Assert.Equal(-52429, bmp.GetPixel(56, 12).ToArgb());
+ Assert.Equal(-52429, bmp.GetPixel(56, 16).ToArgb());
+ Assert.Equal(-52429, bmp.GetPixel(56, 20).ToArgb());
+ Assert.Equal(-52429, bmp.GetPixel(56, 24).ToArgb());
+ Assert.Equal(-52429, bmp.GetPixel(56, 28).ToArgb());
+ Assert.Equal(-52429, bmp.GetPixel(56, 32).ToArgb());
+ Assert.Equal(-52429, bmp.GetPixel(56, 36).ToArgb());
+ Assert.Equal(-14935012, bmp.GetPixel(56, 40).ToArgb());
+ Assert.Equal(-13312, bmp.GetPixel(56, 44).ToArgb());
+ Assert.Equal(-13312, bmp.GetPixel(56, 48).ToArgb());
+ Assert.Equal(-13312, bmp.GetPixel(56, 52).ToArgb());
+ Assert.Equal(-13312, bmp.GetPixel(56, 56).ToArgb());
+ Assert.Equal(0, bmp.GetPixel(56, 60).ToArgb());
+ Assert.Equal(-3355546, bmp.GetPixel(56, 64).ToArgb());
+ Assert.Equal(-3355546, bmp.GetPixel(56, 68).ToArgb());
+ Assert.Equal(-3355546, bmp.GetPixel(56, 72).ToArgb());
+ Assert.Equal(-3355546, bmp.GetPixel(56, 76).ToArgb());
+ Assert.Equal(-6737101, bmp.GetPixel(56, 80).ToArgb());
+ Assert.Equal(-6737101, bmp.GetPixel(56, 84).ToArgb());
+ Assert.Equal(-6737101, bmp.GetPixel(56, 88).ToArgb());
+ Assert.Equal(-6737101, bmp.GetPixel(56, 92).ToArgb());
+ Assert.Equal(0, bmp.GetPixel(60, 0).ToArgb());
+ Assert.Equal(-52429, bmp.GetPixel(60, 4).ToArgb());
+ Assert.Equal(-52429, bmp.GetPixel(60, 8).ToArgb());
+ Assert.Equal(-52429, bmp.GetPixel(60, 12).ToArgb());
+ Assert.Equal(-52429, bmp.GetPixel(60, 16).ToArgb());
+ Assert.Equal(-52429, bmp.GetPixel(60, 20).ToArgb());
+ Assert.Equal(-52429, bmp.GetPixel(60, 24).ToArgb());
+ Assert.Equal(-52429, bmp.GetPixel(60, 28).ToArgb());
+ Assert.Equal(-52429, bmp.GetPixel(60, 32).ToArgb());
+ Assert.Equal(-52429, bmp.GetPixel(60, 36).ToArgb());
+ Assert.Equal(-52429, bmp.GetPixel(60, 40).ToArgb());
+ Assert.Equal(0, bmp.GetPixel(60, 44).ToArgb());
+ Assert.Equal(-14935012, bmp.GetPixel(60, 48).ToArgb());
+ Assert.Equal(0, bmp.GetPixel(60, 52).ToArgb());
+ Assert.Equal(0, bmp.GetPixel(60, 56).ToArgb());
+ Assert.Equal(0, bmp.GetPixel(60, 60).ToArgb());
+ Assert.Equal(0, bmp.GetPixel(60, 64).ToArgb());
+ Assert.Equal(-3355546, bmp.GetPixel(60, 68).ToArgb());
+ Assert.Equal(-3355546, bmp.GetPixel(60, 72).ToArgb());
+ Assert.Equal(0, bmp.GetPixel(60, 76).ToArgb());
+ Assert.Equal(-6737101, bmp.GetPixel(60, 80).ToArgb());
+ Assert.Equal(-6737101, bmp.GetPixel(60, 84).ToArgb());
+ Assert.Equal(-6737101, bmp.GetPixel(60, 88).ToArgb());
+ Assert.Equal(-6737101, bmp.GetPixel(60, 92).ToArgb());
+ Assert.Equal(0, bmp.GetPixel(64, 0).ToArgb());
+ Assert.Equal(-52429, bmp.GetPixel(64, 4).ToArgb());
+ Assert.Equal(-52429, bmp.GetPixel(64, 8).ToArgb());
+ Assert.Equal(-52429, bmp.GetPixel(64, 12).ToArgb());
+ Assert.Equal(-52429, bmp.GetPixel(64, 16).ToArgb());
+ Assert.Equal(-52429, bmp.GetPixel(64, 20).ToArgb());
+ Assert.Equal(-52429, bmp.GetPixel(64, 24).ToArgb());
+ Assert.Equal(-52429, bmp.GetPixel(64, 28).ToArgb());
+ Assert.Equal(-52429, bmp.GetPixel(64, 32).ToArgb());
+ Assert.Equal(-52429, bmp.GetPixel(64, 36).ToArgb());
+ Assert.Equal(-52429, bmp.GetPixel(64, 40).ToArgb());
+ Assert.Equal(-14935012, bmp.GetPixel(64, 44).ToArgb());
+ Assert.Equal(0, bmp.GetPixel(64, 48).ToArgb());
+ Assert.Equal(0, bmp.GetPixel(64, 52).ToArgb());
+ Assert.Equal(-6750157, bmp.GetPixel(64, 56).ToArgb());
+ Assert.Equal(-6750157, bmp.GetPixel(64, 60).ToArgb());
+ Assert.Equal(-6750157, bmp.GetPixel(64, 64).ToArgb());
+ Assert.Equal(-14935012, bmp.GetPixel(64, 68).ToArgb());
+ Assert.Equal(0, bmp.GetPixel(64, 72).ToArgb());
+ Assert.Equal(0, bmp.GetPixel(64, 76).ToArgb());
+ Assert.Equal(0, bmp.GetPixel(64, 80).ToArgb());
+ Assert.Equal(-6737101, bmp.GetPixel(64, 84).ToArgb());
+ Assert.Equal(-6737101, bmp.GetPixel(64, 88).ToArgb());
+ Assert.Equal(-14935012, bmp.GetPixel(64, 92).ToArgb());
+ Assert.Equal(-14935012, bmp.GetPixel(68, 0).ToArgb());
+ Assert.Equal(-52429, bmp.GetPixel(68, 4).ToArgb());
+ Assert.Equal(-52429, bmp.GetPixel(68, 8).ToArgb());
+ Assert.Equal(-52429, bmp.GetPixel(68, 12).ToArgb());
+ Assert.Equal(-52429, bmp.GetPixel(68, 16).ToArgb());
+ Assert.Equal(-52429, bmp.GetPixel(68, 20).ToArgb());
+ Assert.Equal(-52429, bmp.GetPixel(68, 24).ToArgb());
+ Assert.Equal(-52429, bmp.GetPixel(68, 28).ToArgb());
+ Assert.Equal(-52429, bmp.GetPixel(68, 32).ToArgb());
+ Assert.Equal(-52429, bmp.GetPixel(68, 36).ToArgb());
+ Assert.Equal(-52429, bmp.GetPixel(68, 40).ToArgb());
+ Assert.Equal(-52429, bmp.GetPixel(68, 44).ToArgb());
+ Assert.Equal(0, bmp.GetPixel(68, 48).ToArgb());
+ Assert.Equal(-6750157, bmp.GetPixel(68, 52).ToArgb());
+ Assert.Equal(-6750157, bmp.GetPixel(68, 56).ToArgb());
+ Assert.Equal(-6750157, bmp.GetPixel(68, 60).ToArgb());
+ Assert.Equal(-6750157, bmp.GetPixel(68, 64).ToArgb());
+ Assert.Equal(-6750157, bmp.GetPixel(68, 68).ToArgb());
+ Assert.Equal(-14935012, bmp.GetPixel(68, 72).ToArgb());
+ Assert.Equal(-16751002, bmp.GetPixel(68, 76).ToArgb());
+ Assert.Equal(-16751002, bmp.GetPixel(68, 80).ToArgb());
+ Assert.Equal(0, bmp.GetPixel(68, 84).ToArgb());
+ Assert.Equal(0, bmp.GetPixel(68, 88).ToArgb());
+ Assert.Equal(-39373, bmp.GetPixel(68, 92).ToArgb());
+ Assert.Equal(-14935012, bmp.GetPixel(72, 0).ToArgb());
+ Assert.Equal(-52429, bmp.GetPixel(72, 4).ToArgb());
+ Assert.Equal(-52429, bmp.GetPixel(72, 8).ToArgb());
+ Assert.Equal(-52429, bmp.GetPixel(72, 12).ToArgb());
+ Assert.Equal(-52429, bmp.GetPixel(72, 16).ToArgb());
+ Assert.Equal(-52429, bmp.GetPixel(72, 20).ToArgb());
+ Assert.Equal(-52429, bmp.GetPixel(72, 24).ToArgb());
+ Assert.Equal(-52429, bmp.GetPixel(72, 28).ToArgb());
+ Assert.Equal(-52429, bmp.GetPixel(72, 32).ToArgb());
+ Assert.Equal(-52429, bmp.GetPixel(72, 36).ToArgb());
+ Assert.Equal(-52429, bmp.GetPixel(72, 40).ToArgb());
+ Assert.Equal(-52429, bmp.GetPixel(72, 44).ToArgb());
+ Assert.Equal(-14935012, bmp.GetPixel(72, 48).ToArgb());
+ Assert.Equal(-6750157, bmp.GetPixel(72, 52).ToArgb());
+ Assert.Equal(-6750157, bmp.GetPixel(72, 56).ToArgb());
+ Assert.Equal(-6750157, bmp.GetPixel(72, 60).ToArgb());
+ Assert.Equal(-6750157, bmp.GetPixel(72, 64).ToArgb());
+ Assert.Equal(-6750157, bmp.GetPixel(72, 68).ToArgb());
+ Assert.Equal(-6750157, bmp.GetPixel(72, 72).ToArgb());
+ Assert.Equal(0, bmp.GetPixel(72, 76).ToArgb());
+ Assert.Equal(0, bmp.GetPixel(72, 80).ToArgb());
+ Assert.Equal(0, bmp.GetPixel(72, 84).ToArgb());
+ Assert.Equal(0, bmp.GetPixel(72, 88).ToArgb());
+ Assert.Equal(-39373, bmp.GetPixel(72, 92).ToArgb());
+ Assert.Equal(0, bmp.GetPixel(76, 0).ToArgb());
+ Assert.Equal(-52429, bmp.GetPixel(76, 4).ToArgb());
+ Assert.Equal(-52429, bmp.GetPixel(76, 8).ToArgb());
+ Assert.Equal(-52429, bmp.GetPixel(76, 12).ToArgb());
+ Assert.Equal(-52429, bmp.GetPixel(76, 16).ToArgb());
+ Assert.Equal(-52429, bmp.GetPixel(76, 20).ToArgb());
+ Assert.Equal(-52429, bmp.GetPixel(76, 24).ToArgb());
+ Assert.Equal(-52429, bmp.GetPixel(76, 28).ToArgb());
+ Assert.Equal(-52429, bmp.GetPixel(76, 32).ToArgb());
+ Assert.Equal(-52429, bmp.GetPixel(76, 36).ToArgb());
+ Assert.Equal(-52429, bmp.GetPixel(76, 40).ToArgb());
+ Assert.Equal(-14935012, bmp.GetPixel(76, 44).ToArgb());
+ Assert.Equal(-6750157, bmp.GetPixel(76, 48).ToArgb());
+ Assert.Equal(-6750157, bmp.GetPixel(76, 52).ToArgb());
+ Assert.Equal(-6750157, bmp.GetPixel(76, 56).ToArgb());
+ Assert.Equal(-6750157, bmp.GetPixel(76, 60).ToArgb());
+ Assert.Equal(-6750157, bmp.GetPixel(76, 64).ToArgb());
+ Assert.Equal(-6750157, bmp.GetPixel(76, 68).ToArgb());
+ Assert.Equal(-6750157, bmp.GetPixel(76, 72).ToArgb());
+ Assert.Equal(-14935012, bmp.GetPixel(76, 76).ToArgb());
+ Assert.Equal(0, bmp.GetPixel(76, 80).ToArgb());
+ Assert.Equal(-65383, bmp.GetPixel(76, 84).ToArgb());
+ Assert.Equal(-65383, bmp.GetPixel(76, 88).ToArgb());
+ Assert.Equal(-14935012, bmp.GetPixel(76, 92).ToArgb());
+ Assert.Equal(0, bmp.GetPixel(80, 0).ToArgb());
+ Assert.Equal(-52429, bmp.GetPixel(80, 4).ToArgb());
+ Assert.Equal(-52429, bmp.GetPixel(80, 8).ToArgb());
+ Assert.Equal(-52429, bmp.GetPixel(80, 12).ToArgb());
+ Assert.Equal(-52429, bmp.GetPixel(80, 16).ToArgb());
+ Assert.Equal(-52429, bmp.GetPixel(80, 20).ToArgb());
+ Assert.Equal(-52429, bmp.GetPixel(80, 24).ToArgb());
+ Assert.Equal(-52429, bmp.GetPixel(80, 28).ToArgb());
+ Assert.Equal(-52429, bmp.GetPixel(80, 32).ToArgb());
+ Assert.Equal(-52429, bmp.GetPixel(80, 36).ToArgb());
+ Assert.Equal(-52429, bmp.GetPixel(80, 40).ToArgb());
+ Assert.Equal(0, bmp.GetPixel(80, 44).ToArgb());
+ Assert.Equal(-6750157, bmp.GetPixel(80, 48).ToArgb());
+ Assert.Equal(-6750157, bmp.GetPixel(80, 52).ToArgb());
+ Assert.Equal(-6750157, bmp.GetPixel(80, 56).ToArgb());
+ Assert.Equal(-6750157, bmp.GetPixel(80, 60).ToArgb());
+ Assert.Equal(-6750157, bmp.GetPixel(80, 64).ToArgb());
+ Assert.Equal(-6750157, bmp.GetPixel(80, 68).ToArgb());
+ Assert.Equal(-6750157, bmp.GetPixel(80, 72).ToArgb());
+ Assert.Equal(-14935012, bmp.GetPixel(80, 76).ToArgb());
+ Assert.Equal(-65383, bmp.GetPixel(80, 80).ToArgb());
+ Assert.Equal(-65383, bmp.GetPixel(80, 84).ToArgb());
+ Assert.Equal(-65383, bmp.GetPixel(80, 88).ToArgb());
+ Assert.Equal(-65383, bmp.GetPixel(80, 92).ToArgb());
+ Assert.Equal(0, bmp.GetPixel(84, 0).ToArgb());
+ Assert.Equal(0, bmp.GetPixel(84, 4).ToArgb());
+ Assert.Equal(-52429, bmp.GetPixel(84, 8).ToArgb());
+ Assert.Equal(-52429, bmp.GetPixel(84, 12).ToArgb());
+ Assert.Equal(-52429, bmp.GetPixel(84, 16).ToArgb());
+ Assert.Equal(-52429, bmp.GetPixel(84, 20).ToArgb());
+ Assert.Equal(-52429, bmp.GetPixel(84, 24).ToArgb());
+ Assert.Equal(-52429, bmp.GetPixel(84, 28).ToArgb());
+ Assert.Equal(-52429, bmp.GetPixel(84, 32).ToArgb());
+ Assert.Equal(-52429, bmp.GetPixel(84, 36).ToArgb());
+ Assert.Equal(-14935012, bmp.GetPixel(84, 40).ToArgb());
+ Assert.Equal(0, bmp.GetPixel(84, 44).ToArgb());
+ Assert.Equal(-14935012, bmp.GetPixel(84, 48).ToArgb());
+ Assert.Equal(-6750157, bmp.GetPixel(84, 52).ToArgb());
+ Assert.Equal(-6750157, bmp.GetPixel(84, 56).ToArgb());
+ Assert.Equal(-6750157, bmp.GetPixel(84, 60).ToArgb());
+ Assert.Equal(-6750157, bmp.GetPixel(84, 64).ToArgb());
+ Assert.Equal(-6750157, bmp.GetPixel(84, 68).ToArgb());
+ Assert.Equal(-6750157, bmp.GetPixel(84, 72).ToArgb());
+ Assert.Equal(0, bmp.GetPixel(84, 76).ToArgb());
+ Assert.Equal(-65383, bmp.GetPixel(84, 80).ToArgb());
+ Assert.Equal(-65383, bmp.GetPixel(84, 84).ToArgb());
+ Assert.Equal(-65383, bmp.GetPixel(84, 88).ToArgb());
+ Assert.Equal(-65383, bmp.GetPixel(84, 92).ToArgb());
+ Assert.Equal(0, bmp.GetPixel(88, 0).ToArgb());
+ Assert.Equal(-3342490, bmp.GetPixel(88, 4).ToArgb());
+ Assert.Equal(-14935012, bmp.GetPixel(88, 8).ToArgb());
+ Assert.Equal(-52429, bmp.GetPixel(88, 12).ToArgb());
+ Assert.Equal(-52429, bmp.GetPixel(88, 16).ToArgb());
+ Assert.Equal(-52429, bmp.GetPixel(88, 20).ToArgb());
+ Assert.Equal(-52429, bmp.GetPixel(88, 24).ToArgb());
+ Assert.Equal(-52429, bmp.GetPixel(88, 28).ToArgb());
+ Assert.Equal(-52429, bmp.GetPixel(88, 32).ToArgb());
+ Assert.Equal(-52429, bmp.GetPixel(88, 36).ToArgb());
+ Assert.Equal(0, bmp.GetPixel(88, 40).ToArgb());
+ Assert.Equal(-16777063, bmp.GetPixel(88, 44).ToArgb());
+ Assert.Equal(0, bmp.GetPixel(88, 48).ToArgb());
+ Assert.Equal(-6750157, bmp.GetPixel(88, 52).ToArgb());
+ Assert.Equal(-6750157, bmp.GetPixel(88, 56).ToArgb());
+ Assert.Equal(-6750157, bmp.GetPixel(88, 60).ToArgb());
+ Assert.Equal(-6750157, bmp.GetPixel(88, 64).ToArgb());
+ Assert.Equal(-6750157, bmp.GetPixel(88, 68).ToArgb());
+ Assert.Equal(-6750157, bmp.GetPixel(88, 72).ToArgb());
+ Assert.Equal(0, bmp.GetPixel(88, 76).ToArgb());
+ Assert.Equal(-65383, bmp.GetPixel(88, 80).ToArgb());
+ Assert.Equal(-65383, bmp.GetPixel(88, 84).ToArgb());
+ Assert.Equal(-65383, bmp.GetPixel(88, 88).ToArgb());
+ Assert.Equal(-65383, bmp.GetPixel(88, 92).ToArgb());
+ Assert.Equal(-14935012, bmp.GetPixel(92, 0).ToArgb());
+ Assert.Equal(-3342490, bmp.GetPixel(92, 4).ToArgb());
+ Assert.Equal(-14935012, bmp.GetPixel(92, 8).ToArgb());
+ Assert.Equal(0, bmp.GetPixel(92, 12).ToArgb());
+ Assert.Equal(-52429, bmp.GetPixel(92, 16).ToArgb());
+ Assert.Equal(-52429, bmp.GetPixel(92, 20).ToArgb());
+ Assert.Equal(-52429, bmp.GetPixel(92, 24).ToArgb());
+ Assert.Equal(-52429, bmp.GetPixel(92, 28).ToArgb());
+ Assert.Equal(-14935012, bmp.GetPixel(92, 32).ToArgb());
+ Assert.Equal(0, bmp.GetPixel(92, 36).ToArgb());
+ Assert.Equal(0, bmp.GetPixel(92, 40).ToArgb());
+ Assert.Equal(0, bmp.GetPixel(92, 44).ToArgb());
+ Assert.Equal(0, bmp.GetPixel(92, 48).ToArgb());
+ Assert.Equal(0, bmp.GetPixel(92, 52).ToArgb());
+ Assert.Equal(-6750157, bmp.GetPixel(92, 56).ToArgb());
+ Assert.Equal(-6750157, bmp.GetPixel(92, 60).ToArgb());
+ Assert.Equal(-6750157, bmp.GetPixel(92, 64).ToArgb());
+ Assert.Equal(-6750157, bmp.GetPixel(92, 68).ToArgb());
+ Assert.Equal(0, bmp.GetPixel(92, 72).ToArgb());
+ Assert.Equal(0, bmp.GetPixel(92, 76).ToArgb());
+ Assert.Equal(-65383, bmp.GetPixel(92, 80).ToArgb());
+ Assert.Equal(-65383, bmp.GetPixel(92, 84).ToArgb());
+ Assert.Equal(-65383, bmp.GetPixel(92, 88).ToArgb());
+ Assert.Equal(-65383, bmp.GetPixel(92, 92).ToArgb());
+ }
+ }
+
+ [ConditionalFact(Helpers.GdiplusIsAvailable)]
+ public void Bitmap96Data()
+ {
+ string sInFile = Helpers.GetTestBitmapPath("96x96_one_entry_8bit.ico");
+ using (Bitmap bmp = new Bitmap(sInFile))
+ {
+ BitmapData data = bmp.LockBits(new Rectangle(0, 0, bmp.Width, bmp.Height), ImageLockMode.ReadOnly, PixelFormat.Format24bppRgb);
+ try
+ {
+ Assert.Equal(bmp.Height, data.Height);
+ Assert.Equal(bmp.Width, data.Width);
+ Assert.Equal(PixelFormat.Format24bppRgb, data.PixelFormat);
+ Assert.Equal(96, data.Height);
+
+ unsafe
+ {
+ byte* scan = (byte*)data.Scan0;
+ // sampling values from a well known bitmap
+ Assert.Equal(0, *(scan + 0));
+ Assert.Equal(0, *(scan + 97));
+ Assert.Equal(0, *(scan + 194));
+ Assert.Equal(0, *(scan + 291));
+ Assert.Equal(0, *(scan + 388));
+ Assert.Equal(28, *(scan + 485));
+ Assert.Equal(0, *(scan + 582));
+ Assert.Equal(28, *(scan + 679));
+ Assert.Equal(255, *(scan + 776));
+ Assert.Equal(0, *(scan + 873));
+ Assert.Equal(255, *(scan + 970));
+ Assert.Equal(255, *(scan + 1067));
+ Assert.Equal(0, *(scan + 1164));
+ Assert.Equal(255, *(scan + 1261));
+ Assert.Equal(255, *(scan + 1358));
+ Assert.Equal(0, *(scan + 1455));
+ Assert.Equal(255, *(scan + 1552));
+ Assert.Equal(255, *(scan + 1649));
+ Assert.Equal(0, *(scan + 1746));
+ Assert.Equal(255, *(scan + 1843));
+ Assert.Equal(255, *(scan + 1940));
+ Assert.Equal(0, *(scan + 2037));
+ Assert.Equal(255, *(scan + 2134));
+ Assert.Equal(255, *(scan + 2231));
+ Assert.Equal(0, *(scan + 2328));
+ Assert.Equal(255, *(scan + 2425));
+ Assert.Equal(255, *(scan + 2522));
+ Assert.Equal(0, *(scan + 2619));
+ Assert.Equal(255, *(scan + 2716));
+ Assert.Equal(255, *(scan + 2813));
+ Assert.Equal(0, *(scan + 2910));
+ Assert.Equal(255, *(scan + 3007));
+ Assert.Equal(255, *(scan + 3104));
+ Assert.Equal(0, *(scan + 3201));
+ Assert.Equal(255, *(scan + 3298));
+ Assert.Equal(255, *(scan + 3395));
+ Assert.Equal(0, *(scan + 3492));
+ Assert.Equal(0, *(scan + 3589));
+ Assert.Equal(255, *(scan + 3686));
+ Assert.Equal(0, *(scan + 3783));
+ Assert.Equal(0, *(scan + 3880));
+ Assert.Equal(255, *(scan + 3977));
+ Assert.Equal(0, *(scan + 4074));
+ Assert.Equal(0, *(scan + 4171));
+ Assert.Equal(255, *(scan + 4268));
+ Assert.Equal(0, *(scan + 4365));
+ Assert.Equal(28, *(scan + 4462));
+ Assert.Equal(255, *(scan + 4559));
+ Assert.Equal(0, *(scan + 4656));
+ Assert.Equal(51, *(scan + 4753));
+ Assert.Equal(255, *(scan + 4850));
+ Assert.Equal(0, *(scan + 4947));
+ Assert.Equal(51, *(scan + 5044));
+ Assert.Equal(255, *(scan + 5141));
+ Assert.Equal(0, *(scan + 5238));
+ Assert.Equal(51, *(scan + 5335));
+ Assert.Equal(255, *(scan + 5432));
+ Assert.Equal(0, *(scan + 5529));
+ Assert.Equal(51, *(scan + 5626));
+ Assert.Equal(255, *(scan + 5723));
+ Assert.Equal(0, *(scan + 5820));
+ Assert.Equal(51, *(scan + 5917));
+ Assert.Equal(255, *(scan + 6014));
+ Assert.Equal(0, *(scan + 6111));
+ Assert.Equal(51, *(scan + 6208));
+ Assert.Equal(255, *(scan + 6305));
+ Assert.Equal(0, *(scan + 6402));
+ Assert.Equal(51, *(scan + 6499));
+ Assert.Equal(255, *(scan + 6596));
+ Assert.Equal(0, *(scan + 6693));
+ Assert.Equal(51, *(scan + 6790));
+ Assert.Equal(255, *(scan + 6887));
+ Assert.Equal(0, *(scan + 6984));
+ Assert.Equal(51, *(scan + 7081));
+ Assert.Equal(255, *(scan + 7178));
+ Assert.Equal(0, *(scan + 7275));
+ Assert.Equal(51, *(scan + 7372));
+ Assert.Equal(255, *(scan + 7469));
+ Assert.Equal(0, *(scan + 7566));
+ Assert.Equal(51, *(scan + 7663));
+ Assert.Equal(255, *(scan + 7760));
+ Assert.Equal(0, *(scan + 7857));
+ Assert.Equal(51, *(scan + 7954));
+ Assert.Equal(255, *(scan + 8051));
+ Assert.Equal(0, *(scan + 8148));
+ Assert.Equal(51, *(scan + 8245));
+ Assert.Equal(255, *(scan + 8342));
+ Assert.Equal(0, *(scan + 8439));
+ Assert.Equal(51, *(scan + 8536));
+ Assert.Equal(28, *(scan + 8633));
+ Assert.Equal(0, *(scan + 8730));
+ Assert.Equal(51, *(scan + 8827));
+ Assert.Equal(0, *(scan + 8924));
+ Assert.Equal(0, *(scan + 9021));
+ Assert.Equal(51, *(scan + 9118));
+ Assert.Equal(0, *(scan + 9215));
+ Assert.Equal(0, *(scan + 9312));
+ Assert.Equal(51, *(scan + 9409));
+ Assert.Equal(0, *(scan + 9506));
+ Assert.Equal(0, *(scan + 9603));
+ Assert.Equal(51, *(scan + 9700));
+ Assert.Equal(0, *(scan + 9797));
+ Assert.Equal(28, *(scan + 9894));
+ Assert.Equal(51, *(scan + 9991));
+ Assert.Equal(0, *(scan + 10088));
+ Assert.Equal(0, *(scan + 10185));
+ Assert.Equal(51, *(scan + 10282));
+ Assert.Equal(0, *(scan + 10379));
+ Assert.Equal(0, *(scan + 10476));
+ Assert.Equal(51, *(scan + 10573));
+ Assert.Equal(0, *(scan + 10670));
+ Assert.Equal(0, *(scan + 10767));
+ Assert.Equal(51, *(scan + 10864));
+ Assert.Equal(204, *(scan + 10961));
+ Assert.Equal(0, *(scan + 11058));
+ Assert.Equal(51, *(scan + 11155));
+ Assert.Equal(204, *(scan + 11252));
+ Assert.Equal(0, *(scan + 11349));
+ Assert.Equal(51, *(scan + 11446));
+ Assert.Equal(204, *(scan + 11543));
+ Assert.Equal(0, *(scan + 11640));
+ Assert.Equal(51, *(scan + 11737));
+ Assert.Equal(204, *(scan + 11834));
+ Assert.Equal(0, *(scan + 11931));
+ Assert.Equal(51, *(scan + 12028));
+ Assert.Equal(204, *(scan + 12125));
+ Assert.Equal(0, *(scan + 12222));
+ Assert.Equal(51, *(scan + 12319));
+ Assert.Equal(204, *(scan + 12416));
+ Assert.Equal(28, *(scan + 12513));
+ Assert.Equal(51, *(scan + 12610));
+ Assert.Equal(204, *(scan + 12707));
+ Assert.Equal(0, *(scan + 12804));
+ Assert.Equal(28, *(scan + 12901));
+ Assert.Equal(204, *(scan + 12998));
+ Assert.Equal(0, *(scan + 13095));
+ Assert.Equal(0, *(scan + 13192));
+ Assert.Equal(204, *(scan + 13289));
+ Assert.Equal(0, *(scan + 13386));
+ Assert.Equal(0, *(scan + 13483));
+ Assert.Equal(204, *(scan + 13580));
+ Assert.Equal(0, *(scan + 13677));
+ Assert.Equal(28, *(scan + 13774));
+ Assert.Equal(204, *(scan + 13871));
+ Assert.Equal(0, *(scan + 13968));
+ Assert.Equal(0, *(scan + 14065));
+ Assert.Equal(204, *(scan + 14162));
+ Assert.Equal(0, *(scan + 14259));
+ Assert.Equal(0, *(scan + 14356));
+ Assert.Equal(204, *(scan + 14453));
+ Assert.Equal(0, *(scan + 14550));
+ Assert.Equal(0, *(scan + 14647));
+ Assert.Equal(204, *(scan + 14744));
+ Assert.Equal(0, *(scan + 14841));
+ Assert.Equal(0, *(scan + 14938));
+ Assert.Equal(204, *(scan + 15035));
+ Assert.Equal(0, *(scan + 15132));
+ Assert.Equal(0, *(scan + 15229));
+ Assert.Equal(204, *(scan + 15326));
+ Assert.Equal(0, *(scan + 15423));
+ Assert.Equal(0, *(scan + 15520));
+ Assert.Equal(204, *(scan + 15617));
+ Assert.Equal(0, *(scan + 15714));
+ Assert.Equal(0, *(scan + 15811));
+ Assert.Equal(204, *(scan + 15908));
+ Assert.Equal(0, *(scan + 16005));
+ Assert.Equal(0, *(scan + 16102));
+ Assert.Equal(204, *(scan + 16199));
+ Assert.Equal(0, *(scan + 16296));
+ Assert.Equal(0, *(scan + 16393));
+ Assert.Equal(204, *(scan + 16490));
+ Assert.Equal(0, *(scan + 16587));
+ Assert.Equal(0, *(scan + 16684));
+ Assert.Equal(204, *(scan + 16781));
+ Assert.Equal(0, *(scan + 16878));
+ Assert.Equal(0, *(scan + 16975));
+ Assert.Equal(204, *(scan + 17072));
+ Assert.Equal(0, *(scan + 17169));
+ Assert.Equal(0, *(scan + 17266));
+ Assert.Equal(204, *(scan + 17363));
+ Assert.Equal(0, *(scan + 17460));
+ Assert.Equal(0, *(scan + 17557));
+ Assert.Equal(28, *(scan + 17654));
+ Assert.Equal(0, *(scan + 17751));
+ Assert.Equal(0, *(scan + 17848));
+ Assert.Equal(0, *(scan + 17945));
+ Assert.Equal(28, *(scan + 18042));
+ Assert.Equal(0, *(scan + 18139));
+ Assert.Equal(0, *(scan + 18236));
+ Assert.Equal(51, *(scan + 18333));
+ Assert.Equal(28, *(scan + 18430));
+ Assert.Equal(0, *(scan + 18527));
+ Assert.Equal(51, *(scan + 18624));
+ Assert.Equal(0, *(scan + 18721));
+ Assert.Equal(28, *(scan + 18818));
+ Assert.Equal(51, *(scan + 18915));
+ Assert.Equal(255, *(scan + 19012));
+ Assert.Equal(51, *(scan + 19109));
+ Assert.Equal(51, *(scan + 19206));
+ Assert.Equal(255, *(scan + 19303));
+ Assert.Equal(51, *(scan + 19400));
+ Assert.Equal(51, *(scan + 19497));
+ Assert.Equal(255, *(scan + 19594));
+ Assert.Equal(51, *(scan + 19691));
+ Assert.Equal(51, *(scan + 19788));
+ Assert.Equal(255, *(scan + 19885));
+ Assert.Equal(51, *(scan + 19982));
+ Assert.Equal(51, *(scan + 20079));
+ Assert.Equal(255, *(scan + 20176));
+ Assert.Equal(51, *(scan + 20273));
+ Assert.Equal(51, *(scan + 20370));
+ Assert.Equal(255, *(scan + 20467));
+ Assert.Equal(51, *(scan + 20564));
+ Assert.Equal(51, *(scan + 20661));
+ Assert.Equal(255, *(scan + 20758));
+ Assert.Equal(51, *(scan + 20855));
+ Assert.Equal(51, *(scan + 20952));
+ Assert.Equal(255, *(scan + 21049));
+ Assert.Equal(51, *(scan + 21146));
+ Assert.Equal(51, *(scan + 21243));
+ Assert.Equal(28, *(scan + 21340));
+ Assert.Equal(51, *(scan + 21437));
+ Assert.Equal(51, *(scan + 21534));
+ Assert.Equal(0, *(scan + 21631));
+ Assert.Equal(51, *(scan + 21728));
+ Assert.Equal(28, *(scan + 21825));
+ Assert.Equal(0, *(scan + 21922));
+ Assert.Equal(51, *(scan + 22019));
+ Assert.Equal(28, *(scan + 22116));
+ Assert.Equal(0, *(scan + 22213));
+ Assert.Equal(51, *(scan + 22310));
+ Assert.Equal(0, *(scan + 22407));
+ Assert.Equal(0, *(scan + 22504));
+ Assert.Equal(51, *(scan + 22601));
+ Assert.Equal(0, *(scan + 22698));
+ Assert.Equal(0, *(scan + 22795));
+ Assert.Equal(51, *(scan + 22892));
+ Assert.Equal(28, *(scan + 22989));
+ Assert.Equal(0, *(scan + 23086));
+ Assert.Equal(28, *(scan + 23183));
+ Assert.Equal(153, *(scan + 23280));
+ Assert.Equal(28, *(scan + 23377));
+ Assert.Equal(0, *(scan + 23474));
+ Assert.Equal(153, *(scan + 23571));
+ Assert.Equal(28, *(scan + 23668));
+ Assert.Equal(0, *(scan + 23765));
+ Assert.Equal(153, *(scan + 23862));
+ Assert.Equal(0, *(scan + 23959));
+ Assert.Equal(28, *(scan + 24056));
+ Assert.Equal(153, *(scan + 24153));
+ Assert.Equal(0, *(scan + 24250));
+ Assert.Equal(153, *(scan + 24347));
+ Assert.Equal(153, *(scan + 24444));
+ Assert.Equal(0, *(scan + 24541));
+ Assert.Equal(153, *(scan + 24638));
+ Assert.Equal(153, *(scan + 24735));
+ Assert.Equal(0, *(scan + 24832));
+ Assert.Equal(153, *(scan + 24929));
+ Assert.Equal(153, *(scan + 25026));
+ Assert.Equal(0, *(scan + 25123));
+ Assert.Equal(153, *(scan + 25220));
+ Assert.Equal(153, *(scan + 25317));
+ Assert.Equal(0, *(scan + 25414));
+ Assert.Equal(153, *(scan + 25511));
+ Assert.Equal(153, *(scan + 25608));
+ Assert.Equal(0, *(scan + 25705));
+ Assert.Equal(153, *(scan + 25802));
+ Assert.Equal(153, *(scan + 25899));
+ Assert.Equal(0, *(scan + 25996));
+ Assert.Equal(153, *(scan + 26093));
+ Assert.Equal(153, *(scan + 26190));
+ Assert.Equal(0, *(scan + 26287));
+ Assert.Equal(153, *(scan + 26384));
+ Assert.Equal(153, *(scan + 26481));
+ Assert.Equal(0, *(scan + 26578));
+ Assert.Equal(153, *(scan + 26675));
+ Assert.Equal(153, *(scan + 26772));
+ Assert.Equal(28, *(scan + 26869));
+ Assert.Equal(153, *(scan + 26966));
+ Assert.Equal(28, *(scan + 27063));
+ Assert.Equal(28, *(scan + 27160));
+ Assert.Equal(28, *(scan + 27257));
+ Assert.Equal(0, *(scan + 27354));
+ Assert.Equal(0, *(scan + 27451));
+ Assert.Equal(0, *(scan + 27548));
+ Assert.Equal(0, *(scan + 27645));
+ }
+ }
+ finally
+ {
+ bmp.UnlockBits(data);
+ }
+ }
+ }
+
+ [ConditionalFact(Helpers.GdiplusIsAvailable)]
+ public void Xp32bppIconFeatures()
+ {
+ string sInFile = Helpers.GetTestBitmapPath("48x48_multiple_entries_32bit.ico");
+ using (Bitmap bmp = new Bitmap(sInFile))
+ {
+ GraphicsUnit unit = GraphicsUnit.World;
+ RectangleF rect = bmp.GetBounds(ref unit);
+
+ Assert.True(bmp.RawFormat.Equals(ImageFormat.Icon));
+ // note that image is "promoted" to 32bits
+ Assert.Equal(PixelFormat.Format32bppArgb, bmp.PixelFormat);
+ Assert.Equal(73746, bmp.Flags);
+ Assert.Equal(0, bmp.Palette.Entries.Length);
+ Assert.Equal(1, bmp.FrameDimensionsList.Length);
+ Assert.Equal(0, bmp.PropertyIdList.Length);
+ Assert.Equal(0, bmp.PropertyItems.Length);
+ Assert.Null(bmp.Tag);
+ Assert.Equal(96.0f, bmp.HorizontalResolution);
+ Assert.Equal(96.0f, bmp.VerticalResolution);
+ Assert.Equal(16, bmp.Width);
+ Assert.Equal(16, bmp.Height);
+
+ Assert.Equal(0, rect.X);
+ Assert.Equal(0, rect.Y);
+ Assert.Equal(16, rect.Width);
+ Assert.Equal(16, rect.Height);
+
+ Assert.Equal(16, bmp.Size.Width);
+ Assert.Equal(16, bmp.Size.Height);
+ }
+ }
+
+ private void Save(PixelFormat original, PixelFormat expected, bool colorCheck)
+ {
+ string sOutFile = $"linerect-{expected}.ico";
+
+ // Save
+ Bitmap bmp = new Bitmap(100, 100, original);
+ Graphics gr = Graphics.FromImage(bmp);
+
+ using (Pen p = new Pen(Color.Red, 2))
+ {
+ gr.DrawLine(p, 10.0F, 10.0F, 90.0F, 90.0F);
+ gr.DrawRectangle(p, 10.0F, 10.0F, 80.0F, 80.0F);
+ }
+
+ try
+ {
+ // there's no encoder, so we're not saving a ICO but the alpha
+ // bit get sets so it's not like saving a bitmap either
+ bmp.Save(sOutFile, ImageFormat.Icon);
+
+ // Load
+ using (Bitmap bmpLoad = new Bitmap(sOutFile))
+ {
+ Assert.Equal(ImageFormat.Png, bmpLoad.RawFormat);
+ Assert.Equal(expected, bmpLoad.PixelFormat);
+ if (colorCheck)
+ {
+ Color color = bmpLoad.GetPixel(10, 10);
+ Assert.Equal(Color.FromArgb(255, 255, 0, 0), color);
+ }
+ }
+ }
+ finally
+ {
+ gr.Dispose();
+ bmp.Dispose();
+ try
+ {
+ File.Delete(sOutFile);
+ }
+ catch
+ {
+ }
+ }
+ }
+
+ [ConditionalFact(Helpers.RecentGdiplusIsAvailable)]
+ public void Save_24bppRgb()
+ {
+ Save(PixelFormat.Format24bppRgb, PixelFormat.Format24bppRgb, true);
+ }
+
+ [ConditionalFact(Helpers.RecentGdiplusIsAvailable)]
+ public void Save_32bppRgb()
+ {
+ Save(PixelFormat.Format32bppRgb, PixelFormat.Format32bppArgb, true);
+ }
+
+ [ConditionalFact(Helpers.RecentGdiplusIsAvailable)]
+ public void Save_32bppArgb()
+ {
+ Save(PixelFormat.Format32bppArgb, PixelFormat.Format32bppArgb, true);
+ }
+
+ [ConditionalFact(Helpers.RecentGdiplusIsAvailable)]
+ public void Save_32bppPArgb()
+ {
+ Save(PixelFormat.Format32bppPArgb, PixelFormat.Format32bppArgb, true);
+ }
+ }
+}
diff --git a/src/System.Drawing.Common/tests/mono/System.Drawing.Imaging/JpegCodecTests.cs b/src/System.Drawing.Common/tests/mono/System.Drawing.Imaging/JpegCodecTests.cs
new file mode 100644
index 0000000000..98ae8d0007
--- /dev/null
+++ b/src/System.Drawing.Common/tests/mono/System.Drawing.Imaging/JpegCodecTests.cs
@@ -0,0 +1,428 @@
+// Licensed to the .NET Foundation under one or more agreements.
+// See the LICENSE file in the project root for more information.
+//
+// JpegCodec class testing unit
+//
+// Authors:
+// Jordi Mas i Hernàndez (jordi@ximian.com)
+// Sebastien Pouliot <sebastien@ximian.com>
+//
+// (C) 2004 Ximian, Inc. http://www.ximian.com
+// Copyright (C) 2004-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;
+using System.Drawing;
+using System.Drawing.Imaging;
+using Xunit;
+using System.IO;
+using System.Security.Permissions;
+
+namespace MonoTests.System.Drawing.Imaging
+{
+ public class JpegCodecTest
+ {
+ [ConditionalFact(Helpers.RecentGdiplusIsAvailable)]
+ public void Bitmap8bbpIndexedGreyscaleFeatures()
+ {
+ string sInFile = Helpers.GetTestBitmapPath("nature-greyscale.jpg");
+ using (Bitmap bmp = new Bitmap(sInFile))
+ {
+ GraphicsUnit unit = GraphicsUnit.World;
+ RectangleF rect = bmp.GetBounds(ref unit);
+
+ Assert.Equal(PixelFormat.Format8bppIndexed, bmp.PixelFormat);
+ Assert.Equal(110, bmp.Width);
+ Assert.Equal(100, bmp.Height);
+
+ Assert.Equal(0, rect.X);
+ Assert.Equal(0, rect.Y);
+ Assert.Equal(110, rect.Width);
+ Assert.Equal(100, rect.Height);
+
+ Assert.Equal(110, bmp.Size.Width);
+ Assert.Equal(100, bmp.Size.Height);
+
+ Assert.Equal(110, bmp.PhysicalDimension.Width);
+ Assert.Equal(100, bmp.PhysicalDimension.Height);
+
+ Assert.Equal(72, bmp.HorizontalResolution);
+ Assert.Equal(72, bmp.VerticalResolution);
+
+ // This value is not consistent accross Windows & Unix
+ // Assert.Equal(77896, bmp.Flags);
+
+ ColorPalette cp = bmp.Palette;
+ Assert.Equal(256, cp.Entries.Length);
+
+ // This value is not consistent accross Windows & Unix
+ // Assert.Equal(0, cp.Flags);
+ for (int i = 0; i < 256; i++)
+ {
+ Color c = cp.Entries[i];
+ Assert.Equal(0xFF, c.A);
+ Assert.Equal(i, c.R);
+ Assert.Equal(i, c.G);
+ Assert.Equal(i, c.B);
+ }
+ }
+ }
+
+ [ConditionalFact(Helpers.GdiPlusIsAvailableNotWindows7)]
+ public void Bitmap8bbpIndexedGreyscalePixels()
+ {
+ string sInFile = Helpers.GetTestBitmapPath("nature-greyscale.jpg");
+ using (Bitmap bmp = new Bitmap(sInFile))
+ {
+ // sampling values from a well known bitmap
+ Assert.Equal(-7697782, bmp.GetPixel(0, 0).ToArgb());
+ Assert.Equal(-12171706, bmp.GetPixel(0, 32).ToArgb());
+ Assert.Equal(-14013910, bmp.GetPixel(0, 64).ToArgb());
+ Assert.Equal(-15132391, bmp.GetPixel(0, 96).ToArgb());
+ Assert.Equal(-328966, bmp.GetPixel(32, 0).ToArgb());
+ Assert.Equal(-9934744, bmp.GetPixel(32, 32).ToArgb());
+ Assert.Equal(-10263709, bmp.GetPixel(32, 64).ToArgb());
+ Assert.Equal(-7368817, bmp.GetPixel(32, 96).ToArgb());
+ Assert.Equal(-1, bmp.GetPixel(64, 0).ToArgb());
+ Assert.Equal(-4276546, bmp.GetPixel(64, 32).ToArgb());
+ Assert.Equal(-9079435, bmp.GetPixel(64, 64).ToArgb());
+ // Assert.Equal(-7697782, bmp.GetPixel(64, 96).ToArgb());
+ Assert.Equal(-1, bmp.GetPixel(96, 0).ToArgb());
+ Assert.Equal(-8224126, bmp.GetPixel(96, 32).ToArgb());
+ Assert.Equal(-11053225, bmp.GetPixel(96, 64).ToArgb());
+ Assert.Equal(-9211021, bmp.GetPixel(96, 96).ToArgb());
+ }
+ }
+
+ [ConditionalFact(Helpers.GdiPlusIsAvailableNotWindows7)]
+ public void Bitmap8bbpIndexedGreyscaleData()
+ {
+ string sInFile = Helpers.GetTestBitmapPath("nature-greyscale.jpg");
+ using (Bitmap bmp = new Bitmap(sInFile))
+ {
+ BitmapData data = bmp.LockBits(new Rectangle(0, 0, bmp.Width, bmp.Height), ImageLockMode.ReadOnly, PixelFormat.Format24bppRgb);
+ try
+ {
+ Assert.Equal(bmp.Height, data.Height);
+ Assert.Equal(bmp.Width, data.Width);
+ Assert.Equal(PixelFormat.Format24bppRgb, data.PixelFormat);
+ Assert.Equal(100, data.Height);
+
+ unsafe
+ {
+ byte* scan = (byte*)data.Scan0;
+ // sampling values from a well known bitmap
+ Assert.Equal(138, *(scan + 0));
+ Assert.Equal(203, *(scan + 1009));
+ Assert.Equal(156, *(scan + 2018));
+ Assert.Equal(248, *(scan + 3027));
+ Assert.Equal(221, *(scan + 4036));
+ Assert.Equal(185, *(scan + 5045));
+ Assert.Equal(128, *(scan + 6054));
+ Assert.Equal(205, *(scan + 7063));
+ Assert.Equal(153, *(scan + 8072));
+ Assert.Equal(110, *(scan + 9081));
+ Assert.Equal(163, *(scan + 10090));
+ Assert.Equal(87, *(scan + 11099));
+ Assert.Equal(90, *(scan + 12108));
+ Assert.Equal(81, *(scan + 13117));
+ // Assert.Equal(124, *(scan + 14126));
+ Assert.Equal(99, *(scan + 15135));
+ Assert.Equal(153, *(scan + 16144));
+ Assert.Equal(57, *(scan + 17153));
+ Assert.Equal(89, *(scan + 18162));
+ Assert.Equal(71, *(scan + 19171));
+ Assert.Equal(106, *(scan + 20180));
+ Assert.Equal(55, *(scan + 21189));
+ Assert.Equal(75, *(scan + 22198));
+ Assert.Equal(77, *(scan + 23207));
+ Assert.Equal(58, *(scan + 24216));
+ Assert.Equal(69, *(scan + 25225));
+ Assert.Equal(43, *(scan + 26234));
+ Assert.Equal(55, *(scan + 27243));
+ Assert.Equal(74, *(scan + 28252));
+ Assert.Equal(145, *(scan + 29261));
+ Assert.Equal(87, *(scan + 30270));
+ Assert.Equal(85, *(scan + 31279));
+ Assert.Equal(106, *(scan + 32288));
+ }
+ }
+ finally
+ {
+ bmp.UnlockBits(data);
+ }
+ }
+ }
+
+ /* Checks bitmap features on a known 24-bits bitmap */
+ [ConditionalFact(Helpers.RecentGdiplusIsAvailable)]
+ public void Bitmap24bitFeatures()
+ {
+ string sInFile = Helpers.GetTestBitmapPath("nature24bits.jpg");
+ using (Bitmap bmp = new Bitmap(sInFile))
+ {
+ GraphicsUnit unit = GraphicsUnit.World;
+ RectangleF rect = bmp.GetBounds(ref unit);
+
+ Assert.Equal(PixelFormat.Format24bppRgb, bmp.PixelFormat);
+ Assert.Equal(110, bmp.Width);
+ Assert.Equal(100, bmp.Height);
+
+ Assert.Equal(0, rect.X);
+ Assert.Equal(0, rect.Y);
+ Assert.Equal(110, rect.Width);
+ Assert.Equal(100, rect.Height);
+
+ Assert.Equal(110, bmp.Size.Width);
+ Assert.Equal(100, bmp.Size.Height);
+
+ Assert.Equal(110, bmp.PhysicalDimension.Width);
+ Assert.Equal(100, bmp.PhysicalDimension.Height);
+
+ Assert.Equal(72, bmp.HorizontalResolution);
+ Assert.Equal(72, bmp.VerticalResolution);
+
+ /* note: under MS flags aren't constant between executions in this case (no palette) */
+ // Assert.Equal(77960, bmp.Flags);
+
+ Assert.Equal(0, bmp.Palette.Entries.Length);
+ }
+ }
+
+ [ConditionalFact(Helpers.GdiplusIsAvailable)]
+ public void Bitmap24bitPixels()
+ {
+ string sInFile = Helpers.GetTestBitmapPath("nature24bits.jpg");
+ using (Bitmap bmp = new Bitmap(sInFile))
+ {
+ // sampling values from a well known bitmap
+ Assert.Equal(-10447423, bmp.GetPixel(0, 0).ToArgb());
+ Assert.Equal(-12171958, bmp.GetPixel(0, 32).ToArgb());
+ Assert.Equal(-15192259, bmp.GetPixel(0, 64).ToArgb());
+ Assert.Equal(-15131110, bmp.GetPixel(0, 96).ToArgb());
+ Assert.Equal(-395272, bmp.GetPixel(32, 0).ToArgb());
+ Assert.Equal(-10131359, bmp.GetPixel(32, 32).ToArgb());
+ Assert.Equal(-10984322, bmp.GetPixel(32, 64).ToArgb());
+ Assert.Equal(-11034683, bmp.GetPixel(32, 96).ToArgb());
+ Assert.Equal(-1, bmp.GetPixel(64, 0).ToArgb());
+ Assert.Equal(-3163242, bmp.GetPixel(64, 32).ToArgb());
+ Assert.Equal(-7311538, bmp.GetPixel(64, 64).ToArgb());
+ Assert.Equal(-12149780, bmp.GetPixel(64, 96).ToArgb());
+ Assert.Equal(-1, bmp.GetPixel(96, 0).ToArgb());
+ Assert.Equal(-8224378, bmp.GetPixel(96, 32).ToArgb());
+ Assert.Equal(-11053718, bmp.GetPixel(96, 64).ToArgb());
+ Assert.Equal(-12944166, bmp.GetPixel(96, 96).ToArgb());
+ }
+ }
+
+ [ConditionalFact(Helpers.GdiplusIsAvailable)]
+ public void Bitmap24bitData()
+ {
+ string sInFile = Helpers.GetTestBitmapPath("almogaver24bits.bmp");
+ using (Bitmap bmp = new Bitmap(sInFile))
+ {
+ BitmapData data = bmp.LockBits(new Rectangle(0, 0, bmp.Width, bmp.Height), ImageLockMode.ReadOnly, PixelFormat.Format24bppRgb);
+ try
+ {
+ Assert.Equal(bmp.Height, data.Height);
+ Assert.Equal(bmp.Width, data.Width);
+ Assert.Equal(PixelFormat.Format24bppRgb, data.PixelFormat);
+ Assert.Equal(520, data.Stride);
+ Assert.Equal(183, data.Height);
+
+ unsafe
+ {
+ byte* scan = (byte*)data.Scan0;
+ // sampling values from a well known bitmap
+ Assert.Equal(217, *(scan + 0));
+ Assert.Equal(192, *(scan + 1009));
+ Assert.Equal(210, *(scan + 2018));
+ Assert.Equal(196, *(scan + 3027));
+ Assert.Equal(216, *(scan + 4036));
+ Assert.Equal(215, *(scan + 5045));
+ Assert.Equal(218, *(scan + 6054));
+ Assert.Equal(218, *(scan + 7063));
+ Assert.Equal(95, *(scan + 8072));
+ Assert.Equal(9, *(scan + 9081));
+ Assert.Equal(247, *(scan + 10090));
+ Assert.Equal(161, *(scan + 11099));
+ Assert.Equal(130, *(scan + 12108));
+ Assert.Equal(131, *(scan + 13117));
+ Assert.Equal(175, *(scan + 14126));
+ Assert.Equal(217, *(scan + 15135));
+ Assert.Equal(201, *(scan + 16144));
+ Assert.Equal(183, *(scan + 17153));
+ Assert.Equal(236, *(scan + 18162));
+ Assert.Equal(242, *(scan + 19171));
+ Assert.Equal(125, *(scan + 20180));
+ Assert.Equal(193, *(scan + 21189));
+ Assert.Equal(227, *(scan + 22198));
+ Assert.Equal(44, *(scan + 23207));
+ Assert.Equal(230, *(scan + 24216));
+ Assert.Equal(224, *(scan + 25225));
+ Assert.Equal(164, *(scan + 26234));
+ Assert.Equal(43, *(scan + 27243));
+ Assert.Equal(200, *(scan + 28252));
+ Assert.Equal(255, *(scan + 29261));
+ Assert.Equal(226, *(scan + 30270));
+ Assert.Equal(230, *(scan + 31279));
+ Assert.Equal(178, *(scan + 32288));
+ Assert.Equal(224, *(scan + 33297));
+ Assert.Equal(233, *(scan + 34306));
+ Assert.Equal(212, *(scan + 35315));
+ Assert.Equal(153, *(scan + 36324));
+ Assert.Equal(143, *(scan + 37333));
+ Assert.Equal(215, *(scan + 38342));
+ Assert.Equal(116, *(scan + 39351));
+ Assert.Equal(26, *(scan + 40360));
+ Assert.Equal(28, *(scan + 41369));
+ Assert.Equal(75, *(scan + 42378));
+ Assert.Equal(50, *(scan + 43387));
+ Assert.Equal(244, *(scan + 44396));
+ Assert.Equal(191, *(scan + 45405));
+ Assert.Equal(200, *(scan + 46414));
+ Assert.Equal(197, *(scan + 47423));
+ Assert.Equal(232, *(scan + 48432));
+ Assert.Equal(186, *(scan + 49441));
+ Assert.Equal(210, *(scan + 50450));
+ Assert.Equal(215, *(scan + 51459));
+ Assert.Equal(155, *(scan + 52468));
+ Assert.Equal(56, *(scan + 53477));
+ Assert.Equal(149, *(scan + 54486));
+ Assert.Equal(137, *(scan + 55495));
+ Assert.Equal(141, *(scan + 56504));
+ Assert.Equal(36, *(scan + 57513));
+ Assert.Equal(39, *(scan + 58522));
+ Assert.Equal(25, *(scan + 59531));
+ Assert.Equal(44, *(scan + 60540));
+ Assert.Equal(12, *(scan + 61549));
+ Assert.Equal(161, *(scan + 62558));
+ Assert.Equal(179, *(scan + 63567));
+ Assert.Equal(181, *(scan + 64576));
+ Assert.Equal(165, *(scan + 65585));
+ Assert.Equal(182, *(scan + 66594));
+ Assert.Equal(186, *(scan + 67603));
+ Assert.Equal(201, *(scan + 68612));
+ Assert.Equal(49, *(scan + 69621));
+ Assert.Equal(161, *(scan + 70630));
+ Assert.Equal(140, *(scan + 71639));
+ Assert.Equal(2, *(scan + 72648));
+ Assert.Equal(15, *(scan + 73657));
+ Assert.Equal(33, *(scan + 74666));
+ Assert.Equal(17, *(scan + 75675));
+ Assert.Equal(0, *(scan + 76684));
+ Assert.Equal(47, *(scan + 77693));
+ Assert.Equal(4, *(scan + 78702));
+ Assert.Equal(142, *(scan + 79711));
+ Assert.Equal(151, *(scan + 80720));
+ Assert.Equal(124, *(scan + 81729));
+ Assert.Equal(81, *(scan + 82738));
+ Assert.Equal(214, *(scan + 83747));
+ Assert.Equal(217, *(scan + 84756));
+ Assert.Equal(30, *(scan + 85765));
+ Assert.Equal(185, *(scan + 86774));
+ Assert.Equal(200, *(scan + 87783));
+ Assert.Equal(37, *(scan + 88792));
+ Assert.Equal(2, *(scan + 89801));
+ Assert.Equal(41, *(scan + 90810));
+ Assert.Equal(16, *(scan + 91819));
+ Assert.Equal(0, *(scan + 92828));
+ Assert.Equal(146, *(scan + 93837));
+ Assert.Equal(163, *(scan + 94846));
+ }
+ }
+ finally
+ {
+ bmp.UnlockBits(data);
+ }
+ }
+ }
+
+ private void Save(PixelFormat original, PixelFormat expected)
+ {
+ string sOutFile = $"linerect-{expected}.jpeg";
+
+ // Save
+ Bitmap bmp = new Bitmap(100, 100, original);
+ Graphics gr = Graphics.FromImage(bmp);
+
+ using (Pen p = new Pen(Color.Red, 2))
+ {
+ gr.DrawLine(p, 10.0F, 10.0F, 90.0F, 90.0F);
+ gr.DrawRectangle(p, 10.0F, 10.0F, 80.0F, 80.0F);
+ }
+
+ try
+ {
+ bmp.Save(sOutFile, ImageFormat.Jpeg);
+
+ // Load
+ using (Bitmap bmpLoad = new Bitmap(sOutFile))
+ {
+ Assert.Equal(expected, bmpLoad.PixelFormat);
+ Color color = bmpLoad.GetPixel(10, 10);
+ // by default JPEG isn't lossless - so value is "near" read
+ Assert.True(color.R >= 195);
+ Assert.True(color.G < 60);
+ Assert.True(color.B < 60);
+ Assert.Equal(0xFF, color.A);
+ }
+ }
+ finally
+ {
+ gr.Dispose();
+ bmp.Dispose();
+ try
+ {
+ File.Delete(sOutFile);
+ }
+ catch
+ {
+ }
+ }
+ }
+
+ [ConditionalFact(Helpers.RecentGdiplusIsAvailable)]
+ public void Save_24bppRgb()
+ {
+ Save(PixelFormat.Format24bppRgb, PixelFormat.Format24bppRgb);
+ }
+
+ [ConditionalFact(Helpers.RecentGdiplusIsAvailable)]
+ public void Save_32bppRgb()
+ {
+ Save(PixelFormat.Format32bppRgb, PixelFormat.Format24bppRgb);
+ }
+
+ [ConditionalFact(Helpers.RecentGdiplusIsAvailable)]
+ public void Save_32bppArgb()
+ {
+ Save(PixelFormat.Format32bppArgb, PixelFormat.Format24bppRgb);
+ }
+
+ [ConditionalFact(Helpers.RecentGdiplusIsAvailable)]
+ public void Save_32bppPArgb()
+ {
+ Save(PixelFormat.Format32bppPArgb, PixelFormat.Format24bppRgb);
+ }
+ }
+}
diff --git a/src/System.Drawing.Common/tests/mono/System.Drawing.Imaging/PngCodecTesst.cs b/src/System.Drawing.Common/tests/mono/System.Drawing.Imaging/PngCodecTesst.cs
new file mode 100644
index 0000000000..5fbfc795ae
--- /dev/null
+++ b/src/System.Drawing.Common/tests/mono/System.Drawing.Imaging/PngCodecTesst.cs
@@ -0,0 +1,686 @@
+// Licensed to the .NET Foundation under one or more agreements.
+// See the LICENSE file in the project root for more information.
+//
+// PNG Codec class testing unit
+//
+// Authors:
+// Jordi Mas i Hernàndez (jordi@ximian.com)
+// Sebastien Pouliot <sebastien@ximian.com>
+//
+// 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;
+using System.Drawing;
+using System.Drawing.Imaging;
+using System.IO;
+using Xunit;
+
+namespace MonoTests.System.Drawing.Imaging
+{
+ public class PngCodecTest
+ {
+ private bool IsArm64Process()
+ {
+ if (Environment.OSVersion.Platform != PlatformID.Unix || !Environment.Is64BitProcess)
+ return false;
+
+ try
+ {
+ var process = new global::System.Diagnostics.Process();
+ process.StartInfo.FileName = "uname";
+ process.StartInfo.Arguments = "-m";
+ process.StartInfo.RedirectStandardOutput = true;
+ process.StartInfo.UseShellExecute = false;
+ process.Start();
+ process.WaitForExit();
+ var output = process.StandardOutput.ReadToEnd();
+
+ return output.Trim() == "aarch64";
+ }
+ catch
+ {
+ return false;
+ }
+ }
+
+ /* Checks bitmap features on a known 1bbp bitmap */
+ [ConditionalFact(Helpers.RecentGdiplusIsAvailable)]
+ public void Bitmap1bitFeatures()
+ {
+ string sInFile = Helpers.GetTestBitmapPath("1bit.png");
+ using (Bitmap bmp = new Bitmap(sInFile))
+ {
+ GraphicsUnit unit = GraphicsUnit.World;
+ RectangleF rect = bmp.GetBounds(ref unit);
+
+ Assert.Equal(PixelFormat.Format1bppIndexed, bmp.PixelFormat);
+
+ Assert.Equal(0, bmp.Palette.Flags);
+ Assert.Equal(2, bmp.Palette.Entries.Length);
+ Assert.Equal(-16777216, bmp.Palette.Entries[0].ToArgb());
+ Assert.Equal(-1, bmp.Palette.Entries[1].ToArgb());
+
+ Assert.Equal(288, bmp.Width);
+ Assert.Equal(384, bmp.Height);
+
+ Assert.Equal(0, rect.X);
+ Assert.Equal(0, rect.Y);
+ Assert.Equal(288, rect.Width);
+ Assert.Equal(384, rect.Height);
+
+ Assert.Equal(288, bmp.Size.Width);
+ Assert.Equal(384, bmp.Size.Height);
+ }
+ }
+
+ [ConditionalFact(Helpers.RecentGdiplusIsAvailable)]
+ public void Bitmap1bitPixels()
+ {
+ string sInFile = Helpers.GetTestBitmapPath("1bit.png");
+ using (Bitmap bmp = new Bitmap(sInFile))
+ {
+ // sampling values from a well known bitmap
+ Assert.Equal(-1, bmp.GetPixel(0, 0).ToArgb());
+ Assert.Equal(-1, bmp.GetPixel(0, 32).ToArgb());
+ Assert.Equal(-1, bmp.GetPixel(0, 64).ToArgb());
+ Assert.Equal(-1, bmp.GetPixel(0, 96).ToArgb());
+ Assert.Equal(-1, bmp.GetPixel(0, 128).ToArgb());
+ Assert.Equal(-16777216, bmp.GetPixel(0, 160).ToArgb());
+ Assert.Equal(-16777216, bmp.GetPixel(0, 192).ToArgb());
+ Assert.Equal(-16777216, bmp.GetPixel(0, 224).ToArgb());
+ Assert.Equal(-1, bmp.GetPixel(0, 256).ToArgb());
+ Assert.Equal(-16777216, bmp.GetPixel(0, 288).ToArgb());
+ Assert.Equal(-1, bmp.GetPixel(0, 320).ToArgb());
+ Assert.Equal(-16777216, bmp.GetPixel(0, 352).ToArgb());
+ Assert.Equal(-16777216, bmp.GetPixel(32, 0).ToArgb());
+ Assert.Equal(-1, bmp.GetPixel(32, 32).ToArgb());
+ Assert.Equal(-1, bmp.GetPixel(32, 64).ToArgb());
+ Assert.Equal(-16777216, bmp.GetPixel(32, 96).ToArgb());
+ Assert.Equal(-1, bmp.GetPixel(32, 128).ToArgb());
+ Assert.Equal(-1, bmp.GetPixel(32, 160).ToArgb());
+ Assert.Equal(-16777216, bmp.GetPixel(32, 192).ToArgb());
+ Assert.Equal(-1, bmp.GetPixel(32, 224).ToArgb());
+ Assert.Equal(-16777216, bmp.GetPixel(32, 256).ToArgb());
+ Assert.Equal(-16777216, bmp.GetPixel(32, 288).ToArgb());
+ Assert.Equal(-1, bmp.GetPixel(32, 320).ToArgb());
+ Assert.Equal(-1, bmp.GetPixel(32, 352).ToArgb());
+ Assert.Equal(-16777216, bmp.GetPixel(64, 0).ToArgb());
+ Assert.Equal(-16777216, bmp.GetPixel(64, 32).ToArgb());
+ Assert.Equal(-16777216, bmp.GetPixel(64, 64).ToArgb());
+ Assert.Equal(-16777216, bmp.GetPixel(64, 96).ToArgb());
+ Assert.Equal(-16777216, bmp.GetPixel(64, 128).ToArgb());
+ Assert.Equal(-16777216, bmp.GetPixel(64, 160).ToArgb());
+ Assert.Equal(-16777216, bmp.GetPixel(64, 192).ToArgb());
+ Assert.Equal(-16777216, bmp.GetPixel(64, 224).ToArgb());
+ Assert.Equal(-16777216, bmp.GetPixel(64, 256).ToArgb());
+ Assert.Equal(-16777216, bmp.GetPixel(64, 288).ToArgb());
+ Assert.Equal(-16777216, bmp.GetPixel(64, 320).ToArgb());
+ Assert.Equal(-16777216, bmp.GetPixel(64, 352).ToArgb());
+ Assert.Equal(-1, bmp.GetPixel(96, 0).ToArgb());
+ Assert.Equal(-16777216, bmp.GetPixel(96, 32).ToArgb());
+ Assert.Equal(-16777216, bmp.GetPixel(96, 64).ToArgb());
+ Assert.Equal(-16777216, bmp.GetPixel(96, 96).ToArgb());
+ Assert.Equal(-16777216, bmp.GetPixel(96, 128).ToArgb());
+ Assert.Equal(-16777216, bmp.GetPixel(96, 160).ToArgb());
+ Assert.Equal(-1, bmp.GetPixel(96, 192).ToArgb());
+ Assert.Equal(-16777216, bmp.GetPixel(96, 224).ToArgb());
+ Assert.Equal(-16777216, bmp.GetPixel(96, 256).ToArgb());
+ Assert.Equal(-16777216, bmp.GetPixel(96, 288).ToArgb());
+ Assert.Equal(-1, bmp.GetPixel(96, 320).ToArgb());
+ Assert.Equal(-1, bmp.GetPixel(96, 352).ToArgb());
+ Assert.Equal(-16777216, bmp.GetPixel(128, 0).ToArgb());
+ Assert.Equal(-16777216, bmp.GetPixel(128, 32).ToArgb());
+ Assert.Equal(-16777216, bmp.GetPixel(128, 64).ToArgb());
+ Assert.Equal(-16777216, bmp.GetPixel(128, 96).ToArgb());
+ Assert.Equal(-16777216, bmp.GetPixel(128, 128).ToArgb());
+ Assert.Equal(-16777216, bmp.GetPixel(128, 160).ToArgb());
+ Assert.Equal(-16777216, bmp.GetPixel(128, 192).ToArgb());
+ Assert.Equal(-16777216, bmp.GetPixel(128, 224).ToArgb());
+ Assert.Equal(-1, bmp.GetPixel(128, 256).ToArgb());
+ Assert.Equal(-16777216, bmp.GetPixel(128, 288).ToArgb());
+ Assert.Equal(-16777216, bmp.GetPixel(128, 320).ToArgb());
+ Assert.Equal(-16777216, bmp.GetPixel(128, 352).ToArgb());
+ Assert.Equal(-1, bmp.GetPixel(160, 0).ToArgb());
+ Assert.Equal(-1, bmp.GetPixel(160, 32).ToArgb());
+ Assert.Equal(-16777216, bmp.GetPixel(160, 64).ToArgb());
+ Assert.Equal(-1, bmp.GetPixel(160, 96).ToArgb());
+ Assert.Equal(-16777216, bmp.GetPixel(160, 128).ToArgb());
+ Assert.Equal(-1, bmp.GetPixel(160, 160).ToArgb());
+ }
+ }
+
+ [ConditionalFact(Helpers.RecentGdiplusIsAvailable)]
+ public void Bitmap1bitData()
+ {
+ string sInFile = Helpers.GetTestBitmapPath("1bit.png");
+ using (Bitmap bmp = new Bitmap(sInFile))
+ {
+ BitmapData data = bmp.LockBits(new Rectangle(0, 0, bmp.Width, bmp.Height), ImageLockMode.ReadOnly, PixelFormat.Format24bppRgb);
+ try
+ {
+ Assert.Equal(bmp.Height, data.Height);
+ Assert.Equal(bmp.Width, data.Width);
+ Assert.Equal(PixelFormat.Format24bppRgb, data.PixelFormat);
+ Assert.Equal(864, data.Stride);
+ Assert.Equal(384, data.Height);
+
+ unsafe
+ {
+ byte* scan = (byte*)data.Scan0;
+ // sampling values from a well known bitmap
+ Assert.Equal(255, *(scan + 0));
+ Assert.Equal(255, *(scan + 1009));
+ Assert.Equal(255, *(scan + 2018));
+ Assert.Equal(255, *(scan + 3027));
+ Assert.Equal(255, *(scan + 4036));
+ Assert.Equal(255, *(scan + 5045));
+ Assert.Equal(255, *(scan + 6054));
+ Assert.Equal(255, *(scan + 7063));
+ Assert.Equal(255, *(scan + 8072));
+ Assert.Equal(255, *(scan + 9081));
+ Assert.Equal(255, *(scan + 10090));
+ Assert.Equal(0, *(scan + 11099));
+ Assert.Equal(255, *(scan + 12108));
+ Assert.Equal(255, *(scan + 13117));
+ Assert.Equal(0, *(scan + 14126));
+ Assert.Equal(255, *(scan + 15135));
+ Assert.Equal(255, *(scan + 16144));
+ Assert.Equal(0, *(scan + 17153));
+ Assert.Equal(0, *(scan + 18162));
+ Assert.Equal(255, *(scan + 19171));
+ Assert.Equal(0, *(scan + 20180));
+ Assert.Equal(255, *(scan + 21189));
+ Assert.Equal(255, *(scan + 22198));
+ Assert.Equal(0, *(scan + 23207));
+ Assert.Equal(0, *(scan + 24216));
+ Assert.Equal(0, *(scan + 25225));
+ Assert.Equal(0, *(scan + 26234));
+ Assert.Equal(255, *(scan + 27243));
+ Assert.Equal(255, *(scan + 28252));
+ Assert.Equal(0, *(scan + 29261));
+ Assert.Equal(255, *(scan + 30270));
+ Assert.Equal(0, *(scan + 31279));
+ Assert.Equal(0, *(scan + 32288));
+ Assert.Equal(255, *(scan + 33297));
+ Assert.Equal(255, *(scan + 34306));
+ Assert.Equal(255, *(scan + 35315));
+ Assert.Equal(255, *(scan + 36324));
+ Assert.Equal(0, *(scan + 37333));
+ Assert.Equal(255, *(scan + 38342));
+ Assert.Equal(255, *(scan + 39351));
+ Assert.Equal(255, *(scan + 40360));
+ Assert.Equal(255, *(scan + 41369));
+ Assert.Equal(255, *(scan + 42378));
+ Assert.Equal(0, *(scan + 43387));
+ Assert.Equal(0, *(scan + 44396));
+ Assert.Equal(255, *(scan + 45405));
+ Assert.Equal(255, *(scan + 46414));
+ Assert.Equal(255, *(scan + 47423));
+ Assert.Equal(255, *(scan + 48432));
+ Assert.Equal(255, *(scan + 49441));
+ Assert.Equal(0, *(scan + 50450));
+ Assert.Equal(0, *(scan + 51459));
+ Assert.Equal(255, *(scan + 52468));
+ Assert.Equal(255, *(scan + 53477));
+ Assert.Equal(255, *(scan + 54486));
+ Assert.Equal(0, *(scan + 55495));
+ Assert.Equal(0, *(scan + 56504));
+ Assert.Equal(0, *(scan + 57513));
+ Assert.Equal(255, *(scan + 58522));
+ Assert.Equal(255, *(scan + 59531));
+ Assert.Equal(0, *(scan + 60540));
+ Assert.Equal(0, *(scan + 61549));
+ Assert.Equal(0, *(scan + 62558));
+ Assert.Equal(0, *(scan + 63567));
+ Assert.Equal(255, *(scan + 64576));
+ Assert.Equal(0, *(scan + 65585));
+ Assert.Equal(255, *(scan + 66594));
+ Assert.Equal(255, *(scan + 67603));
+ Assert.Equal(0, *(scan + 68612));
+ Assert.Equal(0, *(scan + 69621));
+ Assert.Equal(0, *(scan + 70630));
+ Assert.Equal(0, *(scan + 71639));
+ Assert.Equal(0, *(scan + 72648));
+ Assert.Equal(255, *(scan + 73657));
+ }
+ }
+ finally
+ {
+ bmp.UnlockBits(data);
+ }
+ }
+ }
+
+ /* Checks bitmap features on a known 2bbp bitmap */
+ [ConditionalFact(Helpers.RecentGdiplusIsAvailable2)]
+ public void Bitmap2bitFeatures()
+ {
+ if (IsArm64Process())
+ Assert.True(false, "https://bugzilla.xamarin.com/show_bug.cgi?id=41171");
+
+ string sInFile = Helpers.GetTestBitmapPath("81674-2bpp.png");
+ using (Bitmap bmp = new Bitmap(sInFile))
+ {
+ GraphicsUnit unit = GraphicsUnit.World;
+ RectangleF rect = bmp.GetBounds(ref unit);
+
+ // quite a promotion! (2 -> 32)
+ Assert.Equal(PixelFormat.Format32bppArgb, bmp.PixelFormat);
+
+ // MS returns a random Flags value (not a good sign)
+ //Assert.Equal (0, bmp.Palette.Flags);
+ Assert.Equal(0, bmp.Palette.Entries.Length);
+
+ Assert.Equal(100, bmp.Width);
+ Assert.Equal(100, bmp.Height);
+
+ Assert.Equal(0, rect.X);
+ Assert.Equal(0, rect.Y);
+ Assert.Equal(100, rect.Width);
+ Assert.Equal(100, rect.Height);
+
+ Assert.Equal(100, bmp.Size.Width);
+ Assert.Equal(100, bmp.Size.Height);
+ }
+ }
+
+ [ConditionalFact(Helpers.RecentGdiplusIsAvailable2)]
+ public void Bitmap2bitPixels()
+ {
+ if (IsArm64Process())
+ Assert.True(false, "https://bugzilla.xamarin.com/show_bug.cgi?id=41171");
+
+ string sInFile = Helpers.GetTestBitmapPath("81674-2bpp.png");
+ using (Bitmap bmp = new Bitmap(sInFile))
+ {
+ // sampling values from a well known bitmap
+ Assert.Equal(-11249559, bmp.GetPixel(0, 0).ToArgb());
+ Assert.Equal(-11249559, bmp.GetPixel(0, 32).ToArgb());
+ Assert.Equal(-11249559, bmp.GetPixel(0, 64).ToArgb());
+ Assert.Equal(-11249559, bmp.GetPixel(0, 96).ToArgb());
+ Assert.Equal(-11249559, bmp.GetPixel(32, 0).ToArgb());
+ Assert.Equal(-16777216, bmp.GetPixel(32, 32).ToArgb());
+ Assert.Equal(-11249559, bmp.GetPixel(32, 64).ToArgb());
+ Assert.Equal(-11249559, bmp.GetPixel(32, 96).ToArgb());
+ Assert.Equal(-11249559, bmp.GetPixel(64, 0).ToArgb());
+ Assert.Equal(-16777216, bmp.GetPixel(64, 32).ToArgb());
+ Assert.Equal(-11249559, bmp.GetPixel(64, 64).ToArgb());
+ Assert.Equal(-11249559, bmp.GetPixel(64, 96).ToArgb());
+ Assert.Equal(-11249559, bmp.GetPixel(96, 0).ToArgb());
+ Assert.Equal(-11249559, bmp.GetPixel(96, 32).ToArgb());
+ Assert.Equal(-11249559, bmp.GetPixel(96, 64).ToArgb());
+ Assert.Equal(-11249559, bmp.GetPixel(96, 96).ToArgb());
+ }
+ }
+
+ [ConditionalFact(Helpers.RecentGdiplusIsAvailable2)]
+ public void Bitmap2bitData()
+ {
+ if (IsArm64Process())
+ Assert.True(false, "https://bugzilla.xamarin.com/show_bug.cgi?id=41171");
+
+ string sInFile = Helpers.GetTestBitmapPath("81674-2bpp.png");
+ using (Bitmap bmp = new Bitmap(sInFile))
+ {
+ BitmapData data = bmp.LockBits(new Rectangle(0, 0, bmp.Width, bmp.Height), ImageLockMode.ReadOnly, PixelFormat.Format24bppRgb);
+ try
+ {
+ Assert.Equal(bmp.Height, data.Height);
+ Assert.Equal(bmp.Width, data.Width);
+ Assert.Equal(PixelFormat.Format24bppRgb, data.PixelFormat);
+ Assert.Equal(300, data.Stride);
+ Assert.Equal(100, data.Height);
+
+ unsafe
+ {
+ byte* scan = (byte*)data.Scan0;
+ // sampling values from a well known bitmap
+ Assert.Equal(105, *(scan + 0));
+ Assert.Equal(88, *(scan + 1009));
+ Assert.Equal(255, *(scan + 2018));
+ Assert.Equal(105, *(scan + 3027));
+ Assert.Equal(88, *(scan + 4036));
+ Assert.Equal(84, *(scan + 5045));
+ Assert.Equal(255, *(scan + 6054));
+ Assert.Equal(88, *(scan + 7063));
+ Assert.Equal(84, *(scan + 8072));
+ Assert.Equal(0, *(scan + 9081));
+ Assert.Equal(0, *(scan + 10090));
+ Assert.Equal(84, *(scan + 11099));
+ Assert.Equal(0, *(scan + 12108));
+ Assert.Equal(88, *(scan + 13117));
+ Assert.Equal(84, *(scan + 14126));
+ Assert.Equal(105, *(scan + 15135));
+ Assert.Equal(88, *(scan + 16144));
+ Assert.Equal(84, *(scan + 17153));
+ Assert.Equal(0, *(scan + 18162));
+ Assert.Equal(88, *(scan + 19171));
+ Assert.Equal(84, *(scan + 20180));
+ Assert.Equal(0, *(scan + 21189));
+ Assert.Equal(88, *(scan + 22198));
+ Assert.Equal(84, *(scan + 23207));
+ Assert.Equal(105, *(scan + 24216));
+ Assert.Equal(88, *(scan + 25225));
+ Assert.Equal(0, *(scan + 26234));
+ Assert.Equal(105, *(scan + 27243));
+ Assert.Equal(88, *(scan + 28252));
+ Assert.Equal(84, *(scan + 29261));
+ }
+ }
+ finally
+ {
+ bmp.UnlockBits(data);
+ }
+ }
+ }
+
+ /* Checks bitmap features on a known 4bbp bitmap */
+ [ConditionalFact(Helpers.RecentGdiplusIsAvailable)]
+ public void Bitmap4bitFeatures()
+ {
+ string sInFile = Helpers.GetTestBitmapPath("4bit.png");
+ using (Bitmap bmp = new Bitmap(sInFile))
+ {
+ GraphicsUnit unit = GraphicsUnit.World;
+ RectangleF rect = bmp.GetBounds(ref unit);
+
+ Assert.Equal(PixelFormat.Format4bppIndexed, bmp.PixelFormat);
+
+ Assert.Equal(0, bmp.Palette.Flags);
+ Assert.Equal(16, bmp.Palette.Entries.Length);
+ Assert.Equal(-12106173, bmp.Palette.Entries[0].ToArgb());
+ Assert.Equal(-10979957, bmp.Palette.Entries[1].ToArgb());
+ Assert.Equal(-8879241, bmp.Palette.Entries[2].ToArgb());
+ Assert.Equal(-10381134, bmp.Palette.Entries[3].ToArgb());
+ Assert.Equal(-7441574, bmp.Palette.Entries[4].ToArgb());
+ Assert.Equal(-6391673, bmp.Palette.Entries[5].ToArgb());
+ Assert.Equal(-5861009, bmp.Palette.Entries[6].ToArgb());
+ Assert.Equal(-3824008, bmp.Palette.Entries[7].ToArgb());
+ Assert.Equal(-5790569, bmp.Palette.Entries[8].ToArgb());
+ Assert.Equal(-6178617, bmp.Palette.Entries[9].ToArgb());
+ Assert.Equal(-4668490, bmp.Palette.Entries[10].ToArgb());
+ Assert.Equal(-5060143, bmp.Palette.Entries[11].ToArgb());
+ Assert.Equal(-3492461, bmp.Palette.Entries[12].ToArgb());
+ Assert.Equal(-2967099, bmp.Palette.Entries[13].ToArgb());
+ Assert.Equal(-2175574, bmp.Palette.Entries[14].ToArgb());
+ Assert.Equal(-1314578, bmp.Palette.Entries[15].ToArgb());
+
+ Assert.Equal(288, bmp.Width);
+ Assert.Equal(384, bmp.Height);
+
+ Assert.Equal(0, rect.X);
+ Assert.Equal(0, rect.Y);
+ Assert.Equal(288, rect.Width);
+ Assert.Equal(384, rect.Height);
+
+ Assert.Equal(288, bmp.Size.Width);
+ Assert.Equal(384, bmp.Size.Height);
+ }
+ }
+
+ [ConditionalFact(Helpers.RecentGdiplusIsAvailable)]
+ public void Bitmap4bitPixels()
+ {
+ string sInFile = Helpers.GetTestBitmapPath("4bit.png");
+ using (Bitmap bmp = new Bitmap(sInFile))
+ {
+ // sampling values from a well known bitmap
+ Assert.Equal(-10381134, bmp.GetPixel(0, 0).ToArgb());
+ Assert.Equal(-1314578, bmp.GetPixel(0, 32).ToArgb());
+ Assert.Equal(-1314578, bmp.GetPixel(0, 64).ToArgb());
+ Assert.Equal(-1314578, bmp.GetPixel(0, 96).ToArgb());
+ Assert.Equal(-3824008, bmp.GetPixel(0, 128).ToArgb());
+ Assert.Equal(-12106173, bmp.GetPixel(0, 160).ToArgb());
+ Assert.Equal(-12106173, bmp.GetPixel(0, 192).ToArgb());
+ Assert.Equal(-12106173, bmp.GetPixel(0, 224).ToArgb());
+ Assert.Equal(-12106173, bmp.GetPixel(0, 256).ToArgb());
+ Assert.Equal(-7441574, bmp.GetPixel(0, 288).ToArgb());
+ Assert.Equal(-3492461, bmp.GetPixel(0, 320).ToArgb());
+ Assert.Equal(-5861009, bmp.GetPixel(0, 352).ToArgb());
+ Assert.Equal(-10381134, bmp.GetPixel(32, 0).ToArgb());
+ Assert.Equal(-1314578, bmp.GetPixel(32, 32).ToArgb());
+ Assert.Equal(-7441574, bmp.GetPixel(32, 64).ToArgb());
+ Assert.Equal(-12106173, bmp.GetPixel(32, 96).ToArgb());
+ Assert.Equal(-1314578, bmp.GetPixel(32, 128).ToArgb());
+ Assert.Equal(-1314578, bmp.GetPixel(32, 160).ToArgb());
+ Assert.Equal(-12106173, bmp.GetPixel(32, 192).ToArgb());
+ Assert.Equal(-12106173, bmp.GetPixel(32, 224).ToArgb());
+ Assert.Equal(-12106173, bmp.GetPixel(32, 256).ToArgb());
+ Assert.Equal(-12106173, bmp.GetPixel(32, 288).ToArgb());
+ Assert.Equal(-3492461, bmp.GetPixel(32, 320).ToArgb());
+ Assert.Equal(-2175574, bmp.GetPixel(32, 352).ToArgb());
+ Assert.Equal(-6178617, bmp.GetPixel(64, 0).ToArgb());
+ Assert.Equal(-12106173, bmp.GetPixel(64, 32).ToArgb());
+ Assert.Equal(-12106173, bmp.GetPixel(64, 64).ToArgb());
+ Assert.Equal(-12106173, bmp.GetPixel(64, 96).ToArgb());
+ Assert.Equal(-12106173, bmp.GetPixel(64, 128).ToArgb());
+ Assert.Equal(-12106173, bmp.GetPixel(64, 160).ToArgb());
+ Assert.Equal(-12106173, bmp.GetPixel(64, 192).ToArgb());
+ Assert.Equal(-12106173, bmp.GetPixel(64, 224).ToArgb());
+ Assert.Equal(-5790569, bmp.GetPixel(64, 256).ToArgb());
+ Assert.Equal(-12106173, bmp.GetPixel(64, 288).ToArgb());
+ Assert.Equal(-12106173, bmp.GetPixel(64, 320).ToArgb());
+ Assert.Equal(-5790569, bmp.GetPixel(64, 352).ToArgb());
+ Assert.Equal(-1314578, bmp.GetPixel(96, 0).ToArgb());
+ Assert.Equal(-10381134, bmp.GetPixel(96, 32).ToArgb());
+ Assert.Equal(-12106173, bmp.GetPixel(96, 64).ToArgb());
+ Assert.Equal(-12106173, bmp.GetPixel(96, 96).ToArgb());
+ Assert.Equal(-7441574, bmp.GetPixel(96, 128).ToArgb());
+ Assert.Equal(-12106173, bmp.GetPixel(96, 160).ToArgb());
+ Assert.Equal(-5790569, bmp.GetPixel(96, 192).ToArgb());
+ Assert.Equal(-12106173, bmp.GetPixel(96, 224).ToArgb());
+ Assert.Equal(-4668490, bmp.GetPixel(96, 256).ToArgb());
+ Assert.Equal(-12106173, bmp.GetPixel(96, 288).ToArgb());
+ Assert.Equal(-1314578, bmp.GetPixel(96, 320).ToArgb());
+ Assert.Equal(-3492461, bmp.GetPixel(96, 352).ToArgb());
+ Assert.Equal(-5861009, bmp.GetPixel(128, 0).ToArgb());
+ Assert.Equal(-7441574, bmp.GetPixel(128, 32).ToArgb());
+ Assert.Equal(-7441574, bmp.GetPixel(128, 64).ToArgb());
+ Assert.Equal(-12106173, bmp.GetPixel(128, 96).ToArgb());
+ Assert.Equal(-12106173, bmp.GetPixel(128, 128).ToArgb());
+ Assert.Equal(-12106173, bmp.GetPixel(128, 160).ToArgb());
+ Assert.Equal(-12106173, bmp.GetPixel(128, 192).ToArgb());
+ Assert.Equal(-12106173, bmp.GetPixel(128, 224).ToArgb());
+ Assert.Equal(-12106173, bmp.GetPixel(128, 256).ToArgb());
+ Assert.Equal(-12106173, bmp.GetPixel(128, 288).ToArgb());
+ Assert.Equal(-12106173, bmp.GetPixel(128, 320).ToArgb());
+ Assert.Equal(-12106173, bmp.GetPixel(128, 352).ToArgb());
+ Assert.Equal(-1314578, bmp.GetPixel(160, 0).ToArgb());
+ Assert.Equal(-1314578, bmp.GetPixel(160, 32).ToArgb());
+ Assert.Equal(-12106173, bmp.GetPixel(160, 64).ToArgb());
+ Assert.Equal(-1314578, bmp.GetPixel(160, 96).ToArgb());
+ Assert.Equal(-12106173, bmp.GetPixel(160, 128).ToArgb());
+ Assert.Equal(-5790569, bmp.GetPixel(160, 160).ToArgb());
+ Assert.Equal(-12106173, bmp.GetPixel(160, 192).ToArgb());
+ }
+ }
+
+ [ConditionalFact(Helpers.RecentGdiplusIsAvailable)]
+ public void Bitmap4bitData()
+ {
+ string sInFile = Helpers.GetTestBitmapPath("4bit.png");
+ using (Bitmap bmp = new Bitmap(sInFile))
+ {
+ BitmapData data = bmp.LockBits(new Rectangle(0, 0, bmp.Width, bmp.Height), ImageLockMode.ReadOnly, PixelFormat.Format24bppRgb);
+ try
+ {
+ Assert.Equal(bmp.Height, data.Height);
+ Assert.Equal(bmp.Width, data.Width);
+ Assert.Equal(PixelFormat.Format24bppRgb, data.PixelFormat);
+ Assert.Equal(864, data.Stride);
+
+ unsafe
+ {
+ byte* scan = (byte*)data.Scan0;
+ // sampling values from a well known bitmap
+ Assert.Equal(178, *(scan + 0));
+ Assert.Equal(184, *(scan + 1009));
+ Assert.Equal(235, *(scan + 2018));
+ Assert.Equal(209, *(scan + 3027));
+ Assert.Equal(240, *(scan + 4036));
+ Assert.Equal(142, *(scan + 5045));
+ Assert.Equal(139, *(scan + 6054));
+ Assert.Equal(152, *(scan + 7063));
+ Assert.Equal(235, *(scan + 8072));
+ Assert.Equal(209, *(scan + 9081));
+ Assert.Equal(240, *(scan + 10090));
+ Assert.Equal(142, *(scan + 11099));
+ Assert.Equal(199, *(scan + 12108));
+ Assert.Equal(201, *(scan + 13117));
+ Assert.Equal(97, *(scan + 14126));
+ Assert.Equal(238, *(scan + 15135));
+ Assert.Equal(240, *(scan + 16144));
+ Assert.Equal(158, *(scan + 17153));
+ Assert.Equal(119, *(scan + 18162));
+ Assert.Equal(201, *(scan + 19171));
+ Assert.Equal(88, *(scan + 20180));
+ Assert.Equal(238, *(scan + 21189));
+ Assert.Equal(240, *(scan + 22198));
+ Assert.Equal(120, *(scan + 23207));
+ Assert.Equal(182, *(scan + 24216));
+ Assert.Equal(70, *(scan + 25225));
+ Assert.Equal(71, *(scan + 26234));
+ Assert.Equal(238, *(scan + 27243));
+ Assert.Equal(240, *(scan + 28252));
+ Assert.Equal(120, *(scan + 29261));
+ Assert.Equal(238, *(scan + 30270));
+ Assert.Equal(70, *(scan + 31279));
+ Assert.Equal(71, *(scan + 32288));
+ Assert.Equal(238, *(scan + 33297));
+ Assert.Equal(240, *(scan + 34306));
+ Assert.Equal(210, *(scan + 35315));
+ Assert.Equal(238, *(scan + 36324));
+ Assert.Equal(70, *(scan + 37333));
+ Assert.Equal(97, *(scan + 38342));
+ Assert.Equal(238, *(scan + 39351));
+ Assert.Equal(240, *(scan + 40360));
+ Assert.Equal(235, *(scan + 41369));
+ Assert.Equal(238, *(scan + 42378));
+ Assert.Equal(117, *(scan + 43387));
+ Assert.Equal(158, *(scan + 44396));
+ Assert.Equal(170, *(scan + 45405));
+ Assert.Equal(240, *(scan + 46414));
+ Assert.Equal(235, *(scan + 47423));
+ Assert.Equal(209, *(scan + 48432));
+ Assert.Equal(120, *(scan + 49441));
+ Assert.Equal(71, *(scan + 50450));
+ Assert.Equal(119, *(scan + 51459));
+ Assert.Equal(240, *(scan + 52468));
+ Assert.Equal(235, *(scan + 53477));
+ Assert.Equal(209, *(scan + 54486));
+ Assert.Equal(70, *(scan + 55495));
+ Assert.Equal(71, *(scan + 56504));
+ Assert.Equal(67, *(scan + 57513));
+ Assert.Equal(240, *(scan + 58522));
+ Assert.Equal(167, *(scan + 59531));
+ Assert.Equal(67, *(scan + 60540));
+ Assert.Equal(70, *(scan + 61549));
+ Assert.Equal(71, *(scan + 62558));
+ Assert.Equal(67, *(scan + 63567));
+ Assert.Equal(240, *(scan + 64576));
+ Assert.Equal(120, *(scan + 65585));
+ Assert.Equal(182, *(scan + 66594));
+ Assert.Equal(70, *(scan + 67603));
+ Assert.Equal(120, *(scan + 68612));
+ Assert.Equal(67, *(scan + 69621));
+ Assert.Equal(70, *(scan + 70630));
+ Assert.Equal(71, *(scan + 71639));
+ Assert.Equal(90, *(scan + 72648));
+ Assert.Equal(240, *(scan + 73657));
+ }
+ }
+ finally
+ {
+ bmp.UnlockBits(data);
+ }
+ }
+ }
+
+ private void Save(PixelFormat original, PixelFormat expected, bool colorCheck)
+ {
+ string sOutFile = $"linerect-{expected}.png";
+
+ // Save
+ Bitmap bmp = new Bitmap(100, 100, original);
+ Graphics gr = Graphics.FromImage(bmp);
+
+ using (Pen p = new Pen(Color.BlueViolet, 2))
+ {
+ gr.DrawLine(p, 10.0F, 10.0F, 90.0F, 90.0F);
+ gr.DrawRectangle(p, 10.0F, 10.0F, 80.0F, 80.0F);
+ }
+
+ try
+ {
+ bmp.Save(sOutFile, ImageFormat.Png);
+
+ // Load
+ using (Bitmap bmpLoad = new Bitmap(sOutFile))
+ {
+ Assert.Equal(expected, bmpLoad.PixelFormat);
+ if (colorCheck)
+ {
+ Color color = bmpLoad.GetPixel(10, 10);
+ Assert.Equal(Color.FromArgb(255, 138, 43, 226), color);
+ }
+ }
+ }
+ finally
+ {
+ gr.Dispose();
+ bmp.Dispose();
+ try
+ {
+ File.Delete(sOutFile);
+ }
+ catch
+ {
+ }
+ }
+ }
+
+ [ConditionalFact(Helpers.RecentGdiplusIsAvailable)]
+ public void Save_24bppRgb()
+ {
+ Save(PixelFormat.Format24bppRgb, PixelFormat.Format24bppRgb, true);
+ }
+
+ [ConditionalFact(Helpers.RecentGdiplusIsAvailable)]
+ public void Save_32bppRgb()
+ {
+ Save(PixelFormat.Format32bppRgb, PixelFormat.Format32bppArgb, true);
+ }
+
+ [ConditionalFact(Helpers.RecentGdiplusIsAvailable)]
+ public void Save_32bppArgb()
+ {
+ Save(PixelFormat.Format32bppArgb, PixelFormat.Format32bppArgb, true);
+ }
+
+ [ConditionalFact(Helpers.RecentGdiplusIsAvailable)]
+ public void Save_32bppPArgb()
+ {
+ Save(PixelFormat.Format32bppPArgb, PixelFormat.Format32bppArgb, true);
+ }
+ }
+}
diff --git a/src/System.Drawing.Common/tests/mono/System.Drawing.Imaging/TiffCodecTests.cs b/src/System.Drawing.Common/tests/mono/System.Drawing.Imaging/TiffCodecTests.cs
new file mode 100644
index 0000000000..63e904b409
--- /dev/null
+++ b/src/System.Drawing.Common/tests/mono/System.Drawing.Imaging/TiffCodecTests.cs
@@ -0,0 +1,315 @@
+// Licensed to the .NET Foundation under one or more agreements.
+// See the LICENSE file in the project root for more information.
+//
+// TIFF Codec class testing unit
+//
+// Authors:
+// Jordi Mas i Hernàndez (jordi@ximian.com)
+// Sebastien Pouliot <sebastien@ximian.com>
+//
+// 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;
+using System.Drawing;
+using System.Drawing.Imaging;
+using System.IO;
+using Xunit;
+
+namespace MonoTests.System.Drawing.Imaging
+{
+ public class TiffCodecTest
+ {
+ /* Checks bitmap features on a known 32bbp bitmap */
+ [ConditionalFact(Helpers.GdiplusIsAvailable)]
+ public void Bitmap32bitsFeatures()
+ {
+ string sInFile = Helpers.GetTestBitmapPath("almogaver32bits.tif");
+ using (Bitmap bmp = new Bitmap(sInFile))
+ {
+ GraphicsUnit unit = GraphicsUnit.World;
+ RectangleF rect = bmp.GetBounds(ref unit);
+ // MS reports 24 bpp while we report 32 bpp
+ // Assert.Equal (PixelFormat.Format24bppRgb, bmp.PixelFormat);
+ Assert.Equal(173, bmp.Width);
+ Assert.Equal(183, bmp.Height);
+
+ Assert.Equal(0, rect.X);
+ Assert.Equal(0, rect.Y);
+ Assert.Equal(173, rect.Width);
+ Assert.Equal(183, rect.Height);
+
+ Assert.Equal(173, bmp.Size.Width);
+ Assert.Equal(183, bmp.Size.Height);
+ }
+ }
+
+ /* Checks bitmap features on a known 32bbp bitmap */
+ [ConditionalFact(Helpers.GdiplusIsAvailable)]
+ [ActiveIssue(20884, TestPlatforms.AnyUnix)]
+ public void Bitmap32bitsPixelFormat()
+ {
+ string sInFile = Helpers.GetTestBitmapPath("almogaver32bits.tif");
+ using (Bitmap bmp = new Bitmap(sInFile))
+ {
+ // GDI+ reports 24 bpp while libgdiplus reports 32 bpp
+ Assert.Equal (PixelFormat.Format24bppRgb, bmp.PixelFormat);
+ }
+ }
+
+ [ConditionalFact(Helpers.GdiplusIsAvailable)]
+ public void Bitmap32bitsPixels()
+ {
+ string sInFile = Helpers.GetTestBitmapPath("almogaver32bits.tif");
+ using (Bitmap bmp = new Bitmap(sInFile))
+ {
+ // sampling values from a well known bitmap
+ Assert.Equal(-1579559, bmp.GetPixel(0, 0).ToArgb());
+ Assert.Equal(-1645353, bmp.GetPixel(0, 32).ToArgb());
+ Assert.Equal(-461332, bmp.GetPixel(0, 64).ToArgb());
+ Assert.Equal(-330005, bmp.GetPixel(0, 96).ToArgb());
+ Assert.Equal(-2237489, bmp.GetPixel(0, 128).ToArgb());
+ Assert.Equal(-1251105, bmp.GetPixel(0, 160).ToArgb());
+ Assert.Equal(-3024947, bmp.GetPixel(32, 0).ToArgb());
+ Assert.Equal(-2699070, bmp.GetPixel(32, 32).ToArgb());
+ Assert.Equal(-2366734, bmp.GetPixel(32, 64).ToArgb());
+ Assert.Equal(-4538413, bmp.GetPixel(32, 96).ToArgb());
+ Assert.Equal(-6116681, bmp.GetPixel(32, 128).ToArgb());
+ Assert.Equal(-7369076, bmp.GetPixel(32, 160).ToArgb());
+ Assert.Equal(-13024729, bmp.GetPixel(64, 0).ToArgb());
+ Assert.Equal(-7174020, bmp.GetPixel(64, 32).ToArgb());
+ Assert.Equal(-51, bmp.GetPixel(64, 64).ToArgb());
+ Assert.Equal(-16053503, bmp.GetPixel(64, 96).ToArgb());
+ Assert.Equal(-8224431, bmp.GetPixel(64, 128).ToArgb());
+ Assert.Equal(-16579326, bmp.GetPixel(64, 160).ToArgb());
+ Assert.Equal(-2502457, bmp.GetPixel(96, 0).ToArgb());
+ Assert.Equal(-9078395, bmp.GetPixel(96, 32).ToArgb());
+ Assert.Equal(-12696508, bmp.GetPixel(96, 64).ToArgb());
+ Assert.Equal(-70772, bmp.GetPixel(96, 96).ToArgb());
+ Assert.Equal(-4346279, bmp.GetPixel(96, 128).ToArgb());
+ Assert.Equal(-11583193, bmp.GetPixel(96, 160).ToArgb());
+ Assert.Equal(-724763, bmp.GetPixel(128, 0).ToArgb());
+ Assert.Equal(-7238268, bmp.GetPixel(128, 32).ToArgb());
+ Assert.Equal(-2169612, bmp.GetPixel(128, 64).ToArgb());
+ Assert.Equal(-3683883, bmp.GetPixel(128, 96).ToArgb());
+ Assert.Equal(-12892867, bmp.GetPixel(128, 128).ToArgb());
+ Assert.Equal(-3750464, bmp.GetPixel(128, 160).ToArgb());
+ Assert.Equal(-3222844, bmp.GetPixel(160, 0).ToArgb());
+ Assert.Equal(-65806, bmp.GetPixel(160, 32).ToArgb());
+ Assert.Equal(-2961726, bmp.GetPixel(160, 64).ToArgb());
+ Assert.Equal(-2435382, bmp.GetPixel(160, 96).ToArgb());
+ Assert.Equal(-2501944, bmp.GetPixel(160, 128).ToArgb());
+ Assert.Equal(-9211799, bmp.GetPixel(160, 160).ToArgb());
+ }
+ }
+
+ [ConditionalFact(Helpers.GdiplusIsAvailable)]
+ public void Bitmap32bitsData()
+ {
+ string sInFile = Helpers.GetTestBitmapPath("almogaver32bits.tif");
+ using (Bitmap bmp = new Bitmap(sInFile))
+ {
+ BitmapData data = bmp.LockBits(new Rectangle(0, 0, bmp.Width, bmp.Height), ImageLockMode.ReadOnly, PixelFormat.Format24bppRgb);
+ try
+ {
+ Assert.Equal(bmp.Height, data.Height);
+ Assert.Equal(bmp.Width, data.Width);
+ Assert.Equal(PixelFormat.Format24bppRgb, data.PixelFormat);
+ Assert.Equal(520, data.Stride);
+ Assert.Equal(183, data.Height);
+
+ unsafe
+ {
+ byte* scan = (byte*)data.Scan0;
+ // sampling values from a well known bitmap
+ Assert.Equal(217, *(scan + 0));
+ Assert.Equal(192, *(scan + 1009));
+ Assert.Equal(210, *(scan + 2018));
+ Assert.Equal(196, *(scan + 3027));
+ Assert.Equal(216, *(scan + 4036));
+ Assert.Equal(215, *(scan + 5045));
+ Assert.Equal(218, *(scan + 6054));
+ Assert.Equal(218, *(scan + 7063));
+ Assert.Equal(95, *(scan + 8072));
+ Assert.Equal(9, *(scan + 9081));
+ Assert.Equal(247, *(scan + 10090));
+ Assert.Equal(161, *(scan + 11099));
+ Assert.Equal(130, *(scan + 12108));
+ Assert.Equal(131, *(scan + 13117));
+ Assert.Equal(175, *(scan + 14126));
+ Assert.Equal(217, *(scan + 15135));
+ Assert.Equal(201, *(scan + 16144));
+ Assert.Equal(183, *(scan + 17153));
+ Assert.Equal(236, *(scan + 18162));
+ Assert.Equal(242, *(scan + 19171));
+ Assert.Equal(125, *(scan + 20180));
+ Assert.Equal(193, *(scan + 21189));
+ Assert.Equal(227, *(scan + 22198));
+ Assert.Equal(44, *(scan + 23207));
+ Assert.Equal(230, *(scan + 24216));
+ Assert.Equal(224, *(scan + 25225));
+ Assert.Equal(164, *(scan + 26234));
+ Assert.Equal(43, *(scan + 27243));
+ Assert.Equal(200, *(scan + 28252));
+ Assert.Equal(255, *(scan + 29261));
+ Assert.Equal(226, *(scan + 30270));
+ Assert.Equal(230, *(scan + 31279));
+ Assert.Equal(178, *(scan + 32288));
+ Assert.Equal(224, *(scan + 33297));
+ Assert.Equal(233, *(scan + 34306));
+ Assert.Equal(212, *(scan + 35315));
+ Assert.Equal(153, *(scan + 36324));
+ Assert.Equal(143, *(scan + 37333));
+ Assert.Equal(215, *(scan + 38342));
+ Assert.Equal(116, *(scan + 39351));
+ Assert.Equal(26, *(scan + 40360));
+ Assert.Equal(28, *(scan + 41369));
+ Assert.Equal(75, *(scan + 42378));
+ Assert.Equal(50, *(scan + 43387));
+ Assert.Equal(244, *(scan + 44396));
+ Assert.Equal(191, *(scan + 45405));
+ Assert.Equal(200, *(scan + 46414));
+ Assert.Equal(197, *(scan + 47423));
+ Assert.Equal(232, *(scan + 48432));
+ Assert.Equal(186, *(scan + 49441));
+ Assert.Equal(210, *(scan + 50450));
+ Assert.Equal(215, *(scan + 51459));
+ Assert.Equal(155, *(scan + 52468));
+ Assert.Equal(56, *(scan + 53477));
+ Assert.Equal(149, *(scan + 54486));
+ Assert.Equal(137, *(scan + 55495));
+ Assert.Equal(141, *(scan + 56504));
+ Assert.Equal(36, *(scan + 57513));
+ Assert.Equal(39, *(scan + 58522));
+ Assert.Equal(25, *(scan + 59531));
+ Assert.Equal(44, *(scan + 60540));
+ Assert.Equal(12, *(scan + 61549));
+ Assert.Equal(161, *(scan + 62558));
+ Assert.Equal(179, *(scan + 63567));
+ Assert.Equal(181, *(scan + 64576));
+ Assert.Equal(165, *(scan + 65585));
+ Assert.Equal(182, *(scan + 66594));
+ Assert.Equal(186, *(scan + 67603));
+ Assert.Equal(201, *(scan + 68612));
+ Assert.Equal(49, *(scan + 69621));
+ Assert.Equal(161, *(scan + 70630));
+ Assert.Equal(140, *(scan + 71639));
+ Assert.Equal(2, *(scan + 72648));
+ Assert.Equal(15, *(scan + 73657));
+ Assert.Equal(33, *(scan + 74666));
+ Assert.Equal(17, *(scan + 75675));
+ Assert.Equal(0, *(scan + 76684));
+ Assert.Equal(47, *(scan + 77693));
+ Assert.Equal(4, *(scan + 78702));
+ Assert.Equal(142, *(scan + 79711));
+ Assert.Equal(151, *(scan + 80720));
+ Assert.Equal(124, *(scan + 81729));
+ Assert.Equal(81, *(scan + 82738));
+ Assert.Equal(214, *(scan + 83747));
+ Assert.Equal(217, *(scan + 84756));
+ Assert.Equal(30, *(scan + 85765));
+ Assert.Equal(185, *(scan + 86774));
+ Assert.Equal(200, *(scan + 87783));
+ Assert.Equal(37, *(scan + 88792));
+ Assert.Equal(2, *(scan + 89801));
+ Assert.Equal(41, *(scan + 90810));
+ Assert.Equal(16, *(scan + 91819));
+ Assert.Equal(0, *(scan + 92828));
+ Assert.Equal(146, *(scan + 93837));
+ Assert.Equal(163, *(scan + 94846));
+ }
+ }
+ finally
+ {
+ bmp.UnlockBits(data);
+ }
+ }
+ }
+
+ private void Save(PixelFormat original, PixelFormat expected, bool colorCheck)
+ {
+ string sOutFile = $"linerect-{expected}.tif";
+
+ // Save
+ Bitmap bmp = new Bitmap(100, 100, original);
+ Graphics gr = Graphics.FromImage(bmp);
+
+ using (Pen p = new Pen(Color.BlueViolet, 2))
+ {
+ gr.DrawLine(p, 10.0F, 10.0F, 90.0F, 90.0F);
+ gr.DrawRectangle(p, 10.0F, 10.0F, 80.0F, 80.0F);
+ }
+
+ try
+ {
+ bmp.Save(sOutFile, ImageFormat.Tiff);
+
+ // Load
+ using (Bitmap bmpLoad = new Bitmap(sOutFile))
+ {
+ Assert.Equal(expected, bmpLoad.PixelFormat);
+ if (colorCheck)
+ {
+ Color color = bmpLoad.GetPixel(10, 10);
+ Assert.Equal(Color.FromArgb(255, 138, 43, 226), color);
+ }
+ }
+ }
+ finally
+ {
+ gr.Dispose();
+ bmp.Dispose();
+ try
+ {
+ File.Delete(sOutFile);
+ }
+ catch
+ {
+ }
+ }
+ }
+
+ [ConditionalFact(Helpers.RecentGdiplusIsAvailable)]
+ public void Save_24bppRgb()
+ {
+ Save(PixelFormat.Format24bppRgb, PixelFormat.Format24bppRgb, true);
+ }
+
+ [ConditionalFact(Helpers.RecentGdiplusIsAvailable)]
+ public void Save_32bppRgb()
+ {
+ Save(PixelFormat.Format32bppRgb, PixelFormat.Format32bppArgb, true);
+ }
+
+ [ConditionalFact(Helpers.RecentGdiplusIsAvailable)]
+ public void Save_32bppArgb()
+ {
+ Save(PixelFormat.Format32bppArgb, PixelFormat.Format32bppArgb, true);
+ }
+
+ [ConditionalFact(Helpers.RecentGdiplusIsAvailable)]
+ public void Save_32bppPArgb()
+ {
+ Save(PixelFormat.Format32bppPArgb, PixelFormat.Format32bppArgb, true);
+ }
+ }
+}
diff --git a/src/System.Drawing.Common/tests/mono/System.Drawing/BitmapTests.cs b/src/System.Drawing.Common/tests/mono/System.Drawing/BitmapTests.cs
new file mode 100644
index 0000000000..f11f2999cb
--- /dev/null
+++ b/src/System.Drawing.Common/tests/mono/System.Drawing/BitmapTests.cs
@@ -0,0 +1,1583 @@
+// Licensed to the .NET Foundation under one or more agreements.
+// See the LICENSE file in the project root for more information.
+//
+// Bitmap class testing unit
+//
+// Authors:
+// Jordi Mas i Hernàndez (jmas@softcatala.org>
+// Jonathan Gilbert <logic@deltaq.org>
+// Sebastien Pouliot <sebastien@ximian.com>
+//
+// (C) 2004 Ximian, Inc. http://www.ximian.com
+// Copyright (C) 2004,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;
+using System.Drawing;
+using System.Drawing.Imaging;
+using System.IO;
+using System.Runtime.InteropServices;
+using System.Runtime.Serialization;
+using System.Runtime.Serialization.Formatters.Binary;
+using System.Security.Cryptography;
+using System.Security.Permissions;
+using System.Text;
+using System.Xml.Serialization;
+using Xunit;
+
+namespace MonoTests.System.Drawing
+{
+
+ public class TestBitmap
+ {
+
+ [ConditionalFact(Helpers.GdiplusIsAvailable)]
+ public void TestPixels()
+ {
+ // Tests GetSetPixel/SetPixel
+ Bitmap bmp = new Bitmap(100, 100, PixelFormat.Format32bppRgb);
+ bmp.SetPixel(0, 0, Color.FromArgb(255, 128, 128, 128));
+ Color color = bmp.GetPixel(0, 0);
+
+ Assert.Equal(Color.FromArgb(255, 128, 128, 128), color);
+
+ bmp.SetPixel(99, 99, Color.FromArgb(255, 255, 0, 155));
+ Color color2 = bmp.GetPixel(99, 99);
+ Assert.Equal(Color.FromArgb(255, 255, 0, 155), color2);
+ }
+
+ [ActiveIssue(20884)]
+ public void LockBits_IndexedWrite_NonIndexed()
+ {
+ using (Bitmap bmp = new Bitmap(100, 100, PixelFormat.Format8bppIndexed))
+ {
+ Rectangle rect = new Rectangle(0, 0, bmp.Width, bmp.Height);
+ Assert.Throws<ArgumentException>(() => bmp.LockBits(rect, ImageLockMode.ReadWrite, PixelFormat.Format24bppRgb));
+ }
+ }
+
+ [ActiveIssue(20884)]
+ public void LockBits_NonIndexedWrite_ToIndexed()
+ {
+ using (Bitmap bmp = new Bitmap(100, 100, PixelFormat.Format32bppRgb))
+ {
+ BitmapData bd = new BitmapData();
+ Rectangle rect = new Rectangle(0, 0, bmp.Width, bmp.Height);
+ Assert.Throws<ArgumentException>(() => bmp.LockBits(rect, ImageLockMode.ReadWrite, PixelFormat.Format8bppIndexed, bd));
+
+ // test to see if there's a leak or not in this case
+ Assert.Equal(IntPtr.Zero, bd.Scan0);
+ }
+ }
+
+ [ConditionalFact(Helpers.GdiplusIsAvailable)]
+ public void LockBits_ImageLockMode_Invalid()
+ {
+ using (Bitmap bmp = new Bitmap(10, 10, PixelFormat.Format24bppRgb))
+ {
+ Rectangle r = new Rectangle(4, 4, 4, 4);
+ BitmapData data = bmp.LockBits(r, (ImageLockMode)0, PixelFormat.Format24bppRgb);
+ try
+ {
+ Assert.Equal(4, data.Height);
+ Assert.Equal(4, data.Width);
+ Assert.True(data.Stride >= 12);
+ Assert.Equal(PixelFormat.Format24bppRgb, data.PixelFormat);
+ Assert.False(IntPtr.Zero.Equals(data.Scan0));
+ }
+ finally
+ {
+ bmp.UnlockBits(data);
+ }
+ }
+ }
+
+ [ConditionalFact(Helpers.GdiplusIsAvailable)]
+ public void LockBits_Double()
+ {
+ using (Bitmap bmp = new Bitmap(10, 10, PixelFormat.Format24bppRgb))
+ {
+ Rectangle r = new Rectangle(4, 4, 4, 4);
+ BitmapData data = bmp.LockBits(r, ImageLockMode.ReadOnly, PixelFormat.Format24bppRgb);
+ try
+ {
+ Assert.Throws<InvalidOperationException>(() => bmp.LockBits(r, ImageLockMode.ReadOnly, PixelFormat.Format24bppRgb));
+ }
+ finally
+ {
+ bmp.UnlockBits(data);
+ }
+ }
+ }
+
+ [ConditionalFact(Helpers.GdiplusIsAvailable)]
+ public void Format1bppIndexed()
+ {
+ using (Bitmap bmp = new Bitmap(1, 1, PixelFormat.Format1bppIndexed))
+ {
+ Color c = bmp.GetPixel(0, 0);
+ Assert.Equal(-16777216, c.ToArgb());
+ Assert.Throws<InvalidOperationException>(() => bmp.SetPixel(0, 0, c));
+ }
+ }
+
+ [ConditionalFact(Helpers.GdiplusIsAvailable)]
+ public void Format4bppIndexed()
+ {
+ using (Bitmap bmp = new Bitmap(1, 1, PixelFormat.Format4bppIndexed))
+ {
+ Color c = bmp.GetPixel(0, 0);
+ Assert.Equal(-16777216, c.ToArgb());
+ Assert.Throws<InvalidOperationException>(() => bmp.SetPixel(0, 0, c));
+ }
+ }
+
+ [ConditionalFact(Helpers.GdiplusIsAvailable)]
+ public void Format8bppIndexed()
+ {
+ using (Bitmap bmp = new Bitmap(1, 1, PixelFormat.Format8bppIndexed))
+ {
+ Color c = bmp.GetPixel(0, 0);
+ Assert.Equal(-16777216, c.ToArgb());
+ Assert.Throws<InvalidOperationException>(() => bmp.SetPixel(0, 0, c));
+ }
+ }
+
+ private void FormatTest(PixelFormat format)
+ {
+ bool alpha = Image.IsAlphaPixelFormat(format);
+ int size = Image.GetPixelFormatSize(format) / 8 * 2;
+ using (Bitmap bmp = new Bitmap(2, 1, format))
+ {
+ Color a = Color.FromArgb(128, 64, 32, 16);
+ Color b = Color.FromArgb(192, 96, 48, 24);
+ bmp.SetPixel(0, 0, a);
+ bmp.SetPixel(1, 0, b);
+ Color c = bmp.GetPixel(0, 0);
+ Color d = bmp.GetPixel(1, 0);
+ if (size == 4)
+ {
+ Assert.Equal(255, c.A);
+ Assert.Equal(66, c.R);
+ if (format == PixelFormat.Format16bppRgb565)
+ {
+ Assert.Equal(32, c.G);
+ }
+ else
+ {
+ Assert.Equal(33, c.G);
+ }
+ Assert.Equal(16, c.B);
+
+ Assert.Equal(255, d.A);
+ Assert.Equal(99, d.R);
+ if (format == PixelFormat.Format16bppRgb565)
+ {
+ Assert.Equal(48, d.G);
+ }
+ else
+ {
+ Assert.Equal(49, d.G);
+ }
+ Assert.Equal(24, d.B);
+ }
+ else if (alpha)
+ {
+ if (format == PixelFormat.Format32bppPArgb)
+ {
+ Assert.Equal(a.A, c.A);
+ // note sure why the -1
+ Assert.Equal(a.R - 1, c.R);
+ Assert.Equal(a.G - 1, c.G);
+ Assert.Equal(a.B - 1, c.B);
+
+ Assert.Equal(b.A, d.A);
+ // note sure why the -1
+ Assert.Equal(b.R - 1, d.R);
+ Assert.Equal(b.G - 1, d.G);
+ Assert.Equal(b.B - 1, d.B);
+ }
+ else
+ {
+ Assert.Equal(a, c);
+ Assert.Equal(b, d);
+ }
+ }
+ else
+ {
+ Assert.Equal(Color.FromArgb(255, 64, 32, 16), c);
+ Assert.Equal(Color.FromArgb(255, 96, 48, 24), d);
+ }
+ BitmapData bd = bmp.LockBits(new Rectangle(0, 0, 2, 1), ImageLockMode.ReadOnly, format);
+ try
+ {
+ byte[] data = new byte[size];
+ Marshal.Copy(bd.Scan0, data, 0, size);
+ if (format == PixelFormat.Format32bppPArgb)
+ {
+ Assert.Equal(Math.Ceiling((float)c.B * c.A / 255), data[0]);
+ Assert.Equal(Math.Ceiling((float)c.G * c.A / 255), data[1]);
+ Assert.Equal(Math.Ceiling((float)c.R * c.A / 255), data[2]);
+ Assert.Equal(c.A, data[3]);
+ Assert.Equal(Math.Ceiling((float)d.B * d.A / 255), data[4]);
+ Assert.Equal(Math.Ceiling((float)d.G * d.A / 255), data[5]);
+ Assert.Equal(Math.Ceiling((float)d.R * d.A / 255), data[6]);
+ Assert.Equal(d.A, data[7]);
+ }
+ else if (size == 4)
+ {
+ int n = 0;
+ switch (format)
+ {
+ case PixelFormat.Format16bppRgb565:
+ Assert.Equal(2, data[n++]);
+ Assert.Equal(65, data[n++]);
+ Assert.Equal(131, data[n++]);
+ Assert.Equal(97, data[n++]);
+ break;
+ case PixelFormat.Format16bppArgb1555:
+ Assert.Equal(130, data[n++]);
+ Assert.Equal(160, data[n++]);
+ Assert.Equal(195, data[n++]);
+ Assert.Equal(176, data[n++]);
+ break;
+ case PixelFormat.Format16bppRgb555:
+ Assert.Equal(130, data[n++]);
+ Assert.Equal(32, data[n++]);
+ Assert.Equal(195, data[n++]);
+ Assert.Equal(48, data[n++]);
+ break;
+ }
+ }
+ else
+ {
+ int n = 0;
+ Assert.Equal(c.B, data[n++]);
+ Assert.Equal(c.G, data[n++]);
+ Assert.Equal(c.R, data[n++]);
+ if (size % 4 == 0)
+ Assert.Equal(c.A, data[n++]);
+ Assert.Equal(d.B, data[n++]);
+ Assert.Equal(d.G, data[n++]);
+ Assert.Equal(d.R, data[n++]);
+ if (size % 4 == 0)
+ Assert.Equal(d.A, data[n++]);
+ }
+ }
+ finally
+ {
+ bmp.UnlockBits(bd);
+ }
+ }
+ }
+
+ [ConditionalFact(Helpers.GdiplusIsAvailable)]
+ public void Format32bppArgb()
+ {
+ FormatTest(PixelFormat.Format32bppArgb);
+ }
+
+ [ActiveIssue(20884)]
+ public void Format32bppRgb()
+ {
+ FormatTest(PixelFormat.Format32bppRgb);
+ }
+
+ [ConditionalFact(Helpers.GdiplusIsAvailable)]
+ public void Format24bppRgb()
+ {
+ FormatTest(PixelFormat.Format24bppRgb);
+ }
+
+ /* Get the output directory depending on the runtime and location*/
+ public static string getOutSubDir()
+ {
+ string sSub, sRslt;
+
+ if (Environment.GetEnvironmentVariable("MSNet") == null)
+ sSub = "mono/";
+ else
+ sSub = "MSNet/";
+
+ sRslt = Path.GetFullPath(sSub);
+
+ if (!Directory.Exists(sRslt))
+ {
+ sRslt = "Test/System.Drawing/" + sSub;
+ }
+
+ if (sRslt.Length > 0)
+ {
+ if (sRslt[sRslt.Length - 1] != '\\' && sRslt[sRslt.Length - 1] != '/')
+ {
+ sRslt += "/";
+ }
+ }
+
+ return sRslt;
+ }
+
+ [ConditionalFact(Helpers.GdiplusIsAvailable)]
+ public void Clone()
+ {
+ string sInFile = Helpers.GetTestBitmapPath("almogaver24bits.bmp");
+ Rectangle rect = new Rectangle(0, 0, 50, 50);
+ using (Bitmap bmp = new Bitmap(sInFile))
+ using (Bitmap bmpNew = bmp.Clone(rect, PixelFormat.Format32bppArgb))
+ {
+ Color colororg0 = bmp.GetPixel(0, 0);
+ Color colororg50 = bmp.GetPixel(49, 49);
+ Color colornew0 = bmpNew.GetPixel(0, 0);
+ Color colornew50 = bmpNew.GetPixel(49, 49);
+
+ Assert.Equal(colororg0, colornew0);
+ Assert.Equal(colororg50, colornew50);
+ }
+ }
+
+ [ConditionalFact(Helpers.GdiplusIsAvailable)]
+ public void CloneImage()
+ {
+ string sInFile = Helpers.GetTestBitmapPath("almogaver24bits.bmp");
+ using (Bitmap bmp = new Bitmap(sInFile))
+ using (Bitmap bmpNew = (Bitmap)bmp.Clone())
+ {
+ Assert.Equal(bmp.Width, bmpNew.Width);
+ Assert.Equal(bmp.Height, bmpNew.Height);
+ Assert.Equal(bmp.PixelFormat, bmpNew.PixelFormat);
+ }
+ }
+
+ [ConditionalFact(Helpers.GdiplusIsAvailable)]
+ public void Frames()
+ {
+ string sInFile = Helpers.GetTestBitmapPath("almogaver24bits.bmp");
+ using (Bitmap bmp = new Bitmap(sInFile))
+ {
+ int cnt = bmp.GetFrameCount(FrameDimension.Page);
+ int active = bmp.SelectActiveFrame(FrameDimension.Page, 0);
+
+ Assert.Equal(1, cnt);
+ Assert.Equal(0, active);
+ }
+ }
+
+ [ConditionalFact(Helpers.GdiplusIsAvailable)]
+ public void FileDoesNotExists()
+ {
+ Assert.Throws<ArgumentException>(() => new Bitmap("FileDoesNotExists.jpg"));
+ }
+
+ static string ByteArrayToString(byte[] arrInput)
+ {
+ StringBuilder sOutput = new StringBuilder(arrInput.Length);
+ for (int i = 0; i < arrInput.Length - 1; i++)
+ {
+ sOutput.Append(arrInput[i].ToString("X2"));
+ }
+ return sOutput.ToString();
+ }
+
+
+ public string RotateBmp(Bitmap src, RotateFlipType rotate)
+ {
+ int width = 150, height = 150, index = 0;
+ byte[] pixels = new byte[width * height * 3];
+ byte[] hash;
+ Color clr;
+
+ using (Bitmap bmp_rotate = src.Clone(new RectangleF(0, 0, width, height), PixelFormat.Format32bppArgb))
+ {
+ bmp_rotate.RotateFlip(rotate);
+
+ for (int y = 0; y < height; y++)
+ {
+ for (int x = 0; x < width; x++)
+ {
+ clr = bmp_rotate.GetPixel(x, y);
+ pixels[index++] = clr.R;
+ pixels[index++] = clr.G;
+ pixels[index++] = clr.B;
+ }
+ }
+
+ hash = MD5.Create().ComputeHash(pixels);
+ return ByteArrayToString(hash);
+ }
+ }
+ public string RotateIndexedBmp(Bitmap src, RotateFlipType type)
+ {
+ int pixels_per_byte;
+
+ switch (src.PixelFormat)
+ {
+ case PixelFormat.Format1bppIndexed:
+ pixels_per_byte = 8;
+ break;
+ case PixelFormat.Format4bppIndexed:
+ pixels_per_byte = 2;
+ break;
+ case PixelFormat.Format8bppIndexed:
+ pixels_per_byte = 1;
+ break;
+
+ default:
+ throw new Exception("Cannot pass a bitmap of format " + src.PixelFormat + " to RotateIndexedBmp");
+ }
+
+ using (Bitmap test = src.Clone() as Bitmap)
+ {
+ test.RotateFlip(type);
+
+ BitmapData data = null;
+ byte[] pixel_data;
+
+ try
+ {
+ data = test.LockBits(new Rectangle(0, 0, test.Width, test.Height), ImageLockMode.ReadOnly, test.PixelFormat);
+
+ int scan_size = (data.Width + pixels_per_byte - 1) / pixels_per_byte;
+ pixel_data = new byte[data.Height * scan_size];
+
+ for (int y = 0; y < data.Height; y++)
+ {
+ IntPtr src_ptr = (IntPtr)(y * data.Stride + data.Scan0.ToInt64());
+ int dest_offset = y * scan_size;
+ for (int x = 0; x < scan_size; x++)
+ pixel_data[dest_offset + x] = Marshal.ReadByte(src_ptr, x);
+ }
+ }
+ finally
+ {
+ if (test != null && data != null)
+ {
+ try
+ { test.UnlockBits(data); }
+ catch { }
+ }
+ }
+
+ if (pixel_data == null)
+ return "--ERROR--";
+
+ byte[] hash = MD5.Create().ComputeHash(pixel_data);
+ return ByteArrayToString(hash);
+ }
+ }
+
+
+ // Rotate bitmap in diffent ways, and check the result
+ // pixels using MD5
+ [ConditionalFact(Helpers.GdiplusIsAvailable)]
+ public void Rotate()
+ {
+ string sInFile = Helpers.GetTestBitmapPath("almogaver24bits.bmp");
+ using (Bitmap bmp = new Bitmap(sInFile))
+ {
+ Assert.Equal("312958A3C67402E1299413794988A3", RotateBmp(bmp, RotateFlipType.Rotate90FlipNone));
+ Assert.Equal("BF70D8DA4F1545AEDD77D0296B47AE", RotateBmp(bmp, RotateFlipType.Rotate180FlipNone));
+ Assert.Equal("15AD2ADBDC7090C0EC744D0F7ACE2F", RotateBmp(bmp, RotateFlipType.Rotate270FlipNone));
+ Assert.Equal("2E10FEC1F4FD64ECC51D7CE68AEB18", RotateBmp(bmp, RotateFlipType.RotateNoneFlipX));
+ Assert.Equal("E63204779B566ED01162B90B49BD9E", RotateBmp(bmp, RotateFlipType.Rotate90FlipX));
+ Assert.Equal("B1ECB17B5093E13D04FF55CFCF7763", RotateBmp(bmp, RotateFlipType.Rotate180FlipX));
+ Assert.Equal("71A173882C16755D86F4BC26532374", RotateBmp(bmp, RotateFlipType.Rotate270FlipX));
+ }
+ }
+
+ // Rotate 1- and 4-bit bitmaps in different ways and check the
+ // resulting pixels using MD5
+ [ConditionalFact(Helpers.RecentGdiplusIsAvailable)]
+ [PlatformSpecific(TestPlatforms.AnyUnix)]
+ public void Rotate1bit4bit()
+ {
+ string[] files = {
+ Helpers.GetTestBitmapPath ("1bit.png"),
+ Helpers.GetTestBitmapPath ("4bit.png")
+ };
+
+ StringBuilder md5s = new StringBuilder();
+
+ foreach (string file in files)
+ {
+ using (Bitmap bmp = new Bitmap(file))
+ {
+ foreach (RotateFlipType type in Enum.GetValues(typeof(RotateFlipType)))
+ {
+ md5s.Append(RotateIndexedBmp(bmp, type));
+ }
+ }
+ }
+
+ using (StreamWriter writer = new StreamWriter("/tmp/md5s.txt"))
+ {
+ writer.WriteLine(md5s);
+ }
+
+ Assert.Equal(
+ "A4DAF507C92BDE10626BC7B34FEFE5" + // 1-bit RotateNoneFlipNone
+ "A4DAF507C92BDE10626BC7B34FEFE5" + // 1-bit Rotate180FlipXY
+ "C0975EAFD2FC1CC9CC7AF20B92FC9F" + // 1-bit Rotate90FlipNone
+ "C0975EAFD2FC1CC9CC7AF20B92FC9F" + // 1-bit Rotate270FlipXY
+ "64AE60858A02228F7B1B18C7812FB6" + // 1-bit Rotate180FlipNone
+ "64AE60858A02228F7B1B18C7812FB6" + // 1-bit RotateNoneFlipXY
+ "E96D3390938350F9DE2608C4364424" + // 1-bit Rotate270FlipNone
+ "E96D3390938350F9DE2608C4364424" + // 1-bit Rotate90FlipXY
+ "23947CE822C1DDE6BEA69C01F8D0D9" + // 1-bit RotateNoneFlipX
+ "23947CE822C1DDE6BEA69C01F8D0D9" + // 1-bit Rotate180FlipY
+ "BE45F685BDEBD7079AA1B2CBA46723" + // 1-bit Rotate90FlipX
+ "BE45F685BDEBD7079AA1B2CBA46723" + // 1-bit Rotate270FlipY
+ "353E937CFF31B1BF6C3DD0A031ACB5" + // 1-bit Rotate180FlipX
+ "353E937CFF31B1BF6C3DD0A031ACB5" + // 1-bit RotateNoneFlipY
+ "AEA18A770A845E25B6A8CE28DD6DCB" + // 1-bit Rotate270FlipX
+ "AEA18A770A845E25B6A8CE28DD6DCB" + // 1-bit Rotate90FlipY
+ "3CC874B571902366AACED5D619E87D" + // 4-bit RotateNoneFlipNone
+ "3CC874B571902366AACED5D619E87D" + // 4-bit Rotate180FlipXY
+ "8DE25C7E1BE4A3B535DB5D83198D83" + // 4-bit Rotate90FlipNone
+ "8DE25C7E1BE4A3B535DB5D83198D83" + // 4-bit Rotate270FlipXY
+ "27CF5E9CE70BE9EBC47FB996721B95" + // 4-bit Rotate180FlipNone
+ "27CF5E9CE70BE9EBC47FB996721B95" + // 4-bit RotateNoneFlipXY
+ "A919CCB8F97CAD7DC1F01026D11A5D" + // 4-bit Rotate270FlipNone
+ "A919CCB8F97CAD7DC1F01026D11A5D" + // 4-bit Rotate90FlipXY
+ "545876C99ACF833E69FBFFBF436034" + // 4-bit RotateNoneFlipX
+ "545876C99ACF833E69FBFFBF436034" + // 4-bit Rotate180FlipY
+ "5DB56687757CDEFC52D89C77CA9223" + // 4-bit Rotate90FlipX
+ "5DB56687757CDEFC52D89C77CA9223" + // 4-bit Rotate270FlipY
+ "05A77EDDCDF20D5B0AC0169E95D7D7" + // 4-bit Rotate180FlipX
+ "05A77EDDCDF20D5B0AC0169E95D7D7" + // 4-bit RotateNoneFlipY
+ "B6B6245796C836923ABAABDF368B29" + // 4-bit Rotate270FlipX
+ "B6B6245796C836923ABAABDF368B29", // 4-bit Rotate90FlipY
+ md5s.ToString());
+ }
+
+ private Bitmap CreateBitmap(int width, int height, PixelFormat fmt)
+ {
+ Bitmap bmp = new Bitmap(width, height, fmt);
+ using (Graphics gr = Graphics.FromImage(bmp))
+ {
+ Color c = Color.FromArgb(255, 100, 200, 250);
+ for (int x = 1; x < 80; x++)
+ {
+ bmp.SetPixel(x, 1, c);
+ bmp.SetPixel(x, 2, c);
+ bmp.SetPixel(x, 78, c);
+ bmp.SetPixel(x, 79, c);
+ }
+ for (int y = 3; y < 78; y++)
+ {
+ bmp.SetPixel(1, y, c);
+ bmp.SetPixel(2, y, c);
+ bmp.SetPixel(78, y, c);
+ bmp.SetPixel(79, y, c);
+ }
+ }
+ return bmp;
+ }
+
+ private byte[] HashPixels(Bitmap bmp)
+ {
+ int len = bmp.Width * bmp.Height * 4;
+ int index = 0;
+ byte[] pixels = new byte[len];
+
+ for (int y = 0; y < bmp.Height; y++)
+ {
+ for (int x = 0; x < bmp.Width; x++)
+ {
+ Color clr = bmp.GetPixel(x, y);
+ pixels[index++] = clr.R;
+ pixels[index++] = clr.G;
+ pixels[index++] = clr.B;
+ }
+ }
+ return MD5.Create().ComputeHash(pixels);
+ }
+
+ private byte[] HashLock(Bitmap bmp, int width, int height, PixelFormat fmt, ImageLockMode mode)
+ {
+ int len = bmp.Width * bmp.Height * 4;
+ byte[] pixels = new byte[len];
+ BitmapData bd = bmp.LockBits(new Rectangle(0, 0, width, height), mode, fmt);
+ try
+ {
+ int index = 0;
+ int bbps = Image.GetPixelFormatSize(fmt);
+ long pos = bd.Scan0.ToInt64();
+ byte[] btv = new byte[1];
+ for (int y = 0; y < bd.Height; y++)
+ {
+ for (int x = 0; x < bd.Width; x++)
+ {
+
+ /* Read the pixels*/
+ for (int bt = 0; bt < bbps / 8; bt++, index++)
+ {
+ long cur = pos;
+ cur += y * bd.Stride;
+ cur += x * bbps / 8;
+ cur += bt;
+ Marshal.Copy((IntPtr)cur, btv, 0, 1);
+ pixels[index] = btv[0];
+
+ /* Make change of all the colours = 250 to 10*/
+ if (btv[0] == 250)
+ {
+ btv[0] = 10;
+ Marshal.Copy(btv, 0, (IntPtr)cur, 1);
+ }
+ }
+ }
+ }
+
+ for (int i = index; i < len; i++)
+ pixels[index] = 0;
+ }
+ finally
+ {
+ bmp.UnlockBits(bd);
+ }
+ return MD5.Create().ComputeHash(pixels);
+ }
+
+ // Tests the LockBitmap functions. Makes a hash of the block of pixels that it returns
+ // firsts, changes them, and then using GetPixel does another check of the changes.
+ // The results match the .Net framework
+ private static byte[] DefaultBitmapHash = new byte[] { 0xD8, 0xD3, 0x68, 0x9C, 0x86, 0x7F, 0xB6, 0xA0, 0x76, 0xD6, 0x00, 0xEF, 0xFF, 0xE5, 0x8E, 0x1B };
+ private static byte[] FinalWholeBitmapHash = new byte[] { 0x5F, 0x52, 0x98, 0x37, 0xE3, 0x94, 0xE1, 0xA6, 0x06, 0x6C, 0x5B, 0xF1, 0xA9, 0xC2, 0xA9, 0x43 };
+
+ [ConditionalFact(Helpers.GdiplusIsAvailable)]
+ public void LockBitmap_Format32bppArgb_Format32bppArgb_ReadWrite_Whole()
+ {
+ using (Bitmap bmp = CreateBitmap(100, 100, PixelFormat.Format32bppArgb))
+ {
+ Assert.Equal(DefaultBitmapHash, HashPixels(bmp));
+ byte[] expected = { 0x89, 0x6A, 0x6B, 0x35, 0x5C, 0x89, 0xD9, 0xE9, 0xF4, 0x51, 0xD5, 0x89, 0xED, 0x28, 0x68, 0x5C };
+ byte[] actual = HashLock(bmp, bmp.Width, bmp.Height, PixelFormat.Format32bppArgb, ImageLockMode.ReadWrite);
+ Assert.Equal(expected, actual);
+ Assert.Equal(FinalWholeBitmapHash, HashPixels(bmp));
+ }
+ }
+
+ [ConditionalFact(Helpers.GdiplusIsAvailable)]
+ public void LockBitmap_Format32bppArgb_Format32bppPArgb_ReadWrite_Whole()
+ {
+ using (Bitmap bmp = CreateBitmap(100, 100, PixelFormat.Format32bppArgb))
+ {
+ Assert.Equal(DefaultBitmapHash, HashPixels(bmp));
+ byte[] expected = { 0x89, 0x6A, 0x6B, 0x35, 0x5C, 0x89, 0xD9, 0xE9, 0xF4, 0x51, 0xD5, 0x89, 0xED, 0x28, 0x68, 0x5C };
+ byte[] actual = HashLock(bmp, bmp.Width, bmp.Height, PixelFormat.Format32bppPArgb, ImageLockMode.ReadWrite);
+ Assert.Equal(expected, actual);
+ Assert.Equal(FinalWholeBitmapHash, HashPixels(bmp));
+ }
+ }
+
+ [ActiveIssue(20884)]
+ public void LockBitmap_Format32bppArgb_Format32bppRgb_ReadWrite_Whole()
+ {
+ using (Bitmap bmp = CreateBitmap(100, 100, PixelFormat.Format32bppArgb))
+ {
+ Assert.Equal(DefaultBitmapHash, HashPixels(bmp));
+ byte[] expected = { 0xC0, 0x28, 0xB5, 0x2E, 0x86, 0x90, 0x6F, 0x37, 0x09, 0x5F, 0x49, 0xA4, 0x91, 0xDA, 0xEE, 0xB9 };
+ byte[] actual = HashLock(bmp, bmp.Width, bmp.Height, PixelFormat.Format32bppRgb, ImageLockMode.ReadWrite);
+ Assert.Equal(expected, actual);
+ Assert.Equal(FinalWholeBitmapHash, HashPixels(bmp));
+ }
+ }
+
+ [ConditionalFact(Helpers.GdiplusIsAvailable)]
+ public void LockBitmap_Format32bppArgb_Format24bppRgb_ReadWrite_Whole()
+ {
+ using (Bitmap bmp = CreateBitmap(100, 100, PixelFormat.Format32bppArgb))
+ {
+ Assert.Equal(DefaultBitmapHash, HashPixels(bmp));
+ byte[] expected = { 0xA7, 0xB2, 0x50, 0x04, 0x11, 0x12, 0x64, 0x68, 0x6B, 0x7D, 0x2F, 0x6E, 0x69, 0x24, 0xCB, 0x14 };
+ byte[] actual = HashLock(bmp, bmp.Width, bmp.Height, PixelFormat.Format24bppRgb, ImageLockMode.ReadWrite);
+ Assert.Equal(expected, actual);
+ Assert.Equal(FinalWholeBitmapHash, HashPixels(bmp));
+ }
+ }
+
+ private static byte[] FinalPartialBitmapHash = new byte[] { 0xED, 0xD8, 0xDC, 0x9B, 0x44, 0x00, 0x22, 0x9B, 0x07, 0x06, 0x4A, 0x21, 0x70, 0xA7, 0x31, 0x1D };
+
+ [ConditionalFact(Helpers.GdiplusIsAvailable)]
+ public void LockBitmap_Format32bppArgb_Format32bppArgb_ReadWrite_Partial()
+ {
+ using (Bitmap bmp = CreateBitmap(100, 100, PixelFormat.Format32bppArgb))
+ {
+ Assert.Equal(DefaultBitmapHash, HashPixels(bmp));
+ byte[] expected = { 0x5D, 0xFF, 0x02, 0x34, 0xEB, 0x7C, 0xF7, 0x42, 0xD4, 0xB7, 0x70, 0x49, 0xB4, 0x06, 0x79, 0xBC };
+ byte[] actual = HashLock(bmp, 50, 50, PixelFormat.Format32bppArgb, ImageLockMode.ReadWrite);
+ Assert.Equal(expected, actual);
+ Assert.Equal(FinalPartialBitmapHash, HashPixels(bmp));
+ }
+ }
+
+ [ConditionalFact(Helpers.GdiplusIsAvailable)]
+ public void LockBitmap_Format32bppArgb_Format32bppPArgb_ReadWrite_Partial()
+ {
+ using (Bitmap bmp = CreateBitmap(100, 100, PixelFormat.Format32bppArgb))
+ {
+ Assert.Equal(DefaultBitmapHash, HashPixels(bmp));
+ byte[] expected = { 0x5D, 0xFF, 0x02, 0x34, 0xEB, 0x7C, 0xF7, 0x42, 0xD4, 0xB7, 0x70, 0x49, 0xB4, 0x06, 0x79, 0xBC };
+ byte[] actual = HashLock(bmp, 50, 50, PixelFormat.Format32bppPArgb, ImageLockMode.ReadWrite);
+ Assert.Equal(expected, actual);
+ Assert.Equal(FinalPartialBitmapHash, HashPixels(bmp));
+ }
+ }
+
+ [ActiveIssue(20884)]
+ public void LockBitmap_Format32bppArgb_Format32bppRgb_ReadWrite_Partial()
+ {
+ using (Bitmap bmp = CreateBitmap(100, 100, PixelFormat.Format32bppArgb))
+ {
+ Assert.Equal(DefaultBitmapHash, HashPixels(bmp));
+ byte[] expected = { 0x72, 0x33, 0x09, 0x67, 0x53, 0x65, 0x38, 0xF9, 0xE4, 0x58, 0xE1, 0x0A, 0xAA, 0x6A, 0xCC, 0xB8 };
+ byte[] actual = HashLock(bmp, 50, 50, PixelFormat.Format32bppRgb, ImageLockMode.ReadWrite);
+ Assert.Equal(expected, actual);
+ Assert.Equal(FinalPartialBitmapHash, HashPixels(bmp));
+ }
+ }
+
+ [ConditionalFact(Helpers.GdiplusIsAvailable)]
+ public void LockBitmap_Format32bppArgb_Format24bppRgb_ReadWrite_Partial()
+ {
+ using (Bitmap bmp = CreateBitmap(100, 100, PixelFormat.Format32bppArgb))
+ {
+ Assert.Equal(DefaultBitmapHash, HashPixels(bmp));
+ byte[] expected = { 0x4D, 0x39, 0x21, 0x88, 0xC2, 0x17, 0x14, 0x5F, 0x89, 0x9E, 0x02, 0x75, 0xF3, 0x64, 0xD8, 0xF0 };
+ byte[] actual = HashLock(bmp, 50, 50, PixelFormat.Format24bppRgb, ImageLockMode.ReadWrite);
+ Assert.Equal(expected, actual);
+ Assert.Equal(FinalPartialBitmapHash, HashPixels(bmp));
+ }
+ }
+
+ // Tests the LockBitmap and UnlockBitmap functions, specifically the copying
+ // of bitmap data in the directions indicated by the ImageLockMode.
+ [ConditionalFact(Helpers.GdiplusIsAvailable)]
+ public void LockUnlockBitmap()
+ {
+ BitmapData data;
+ int pixel_value;
+ Color pixel_colour;
+
+ Color red = Color.FromArgb(Color.Red.A, Color.Red.R, Color.Red.G, Color.Red.B);
+ Color blue = Color.FromArgb(Color.Blue.A, Color.Blue.R, Color.Blue.G, Color.Blue.B);
+
+ using (Bitmap bmp = new Bitmap(1, 1, PixelFormat.Format32bppRgb))
+ {
+ bmp.SetPixel(0, 0, red);
+ pixel_colour = bmp.GetPixel(0, 0);
+ Assert.Equal(red, pixel_colour);
+
+ data = bmp.LockBits(new Rectangle(0, 0, 1, 1), ImageLockMode.ReadOnly, PixelFormat.Format32bppArgb);
+ try
+ {
+ pixel_value = Marshal.ReadByte(data.Scan0, 0);
+ pixel_value |= Marshal.ReadByte(data.Scan0, 1) << 8;
+ pixel_value |= Marshal.ReadByte(data.Scan0, 2) << 16;
+ pixel_value |= Marshal.ReadByte(data.Scan0, 3) << 24;
+
+ pixel_colour = Color.FromArgb(pixel_value);
+ // Disregard alpha information in the test
+ pixel_colour = Color.FromArgb(red.A, pixel_colour.R, pixel_colour.G, pixel_colour.B);
+ Assert.Equal(red, pixel_colour);
+
+ // write blue but we're locked in read-only...
+ Marshal.WriteByte(data.Scan0, 0, blue.B);
+ Marshal.WriteByte(data.Scan0, 1, blue.G);
+ Marshal.WriteByte(data.Scan0, 2, blue.R);
+ Marshal.WriteByte(data.Scan0, 3, blue.A);
+ }
+ finally
+ {
+ bmp.UnlockBits(data);
+ pixel_colour = bmp.GetPixel(0, 0);
+ // Disregard alpha information in the test
+ pixel_colour = Color.FromArgb(red.A, pixel_colour.R, pixel_colour.G, pixel_colour.B);
+ // ...so we still read red after unlocking
+ Assert.Equal(red, pixel_colour);
+ }
+
+ data = bmp.LockBits(new Rectangle(0, 0, 1, 1), ImageLockMode.ReadWrite, PixelFormat.Format32bppArgb);
+ try
+ {
+ // write blue
+ Marshal.WriteByte(data.Scan0, 0, blue.B);
+ Marshal.WriteByte(data.Scan0, 1, blue.G);
+ Marshal.WriteByte(data.Scan0, 2, blue.R);
+ Marshal.WriteByte(data.Scan0, 3, blue.A);
+ }
+ finally
+ {
+ bmp.UnlockBits(data);
+ pixel_colour = bmp.GetPixel(0, 0);
+ // Disregard alpha information in the test
+ pixel_colour = Color.FromArgb(blue.A, pixel_colour.R, pixel_colour.G, pixel_colour.B);
+ // read blue
+ Assert.Equal(blue, pixel_colour);
+ }
+ }
+
+ using (Bitmap bmp = new Bitmap(1, 1, PixelFormat.Format32bppArgb))
+ {
+ bmp.SetPixel(0, 0, red);
+
+ data = bmp.LockBits(new Rectangle(0, 0, 1, 1), ImageLockMode.ReadOnly, PixelFormat.Format24bppRgb);
+ try
+ {
+ byte b = Marshal.ReadByte(data.Scan0, 0);
+ byte g = Marshal.ReadByte(data.Scan0, 1);
+ byte r = Marshal.ReadByte(data.Scan0, 2);
+ pixel_colour = Color.FromArgb(red.A, r, g, b);
+ Assert.Equal(red, pixel_colour);
+ // write blue but we're locked in read-only...
+ Marshal.WriteByte(data.Scan0, 0, blue.B);
+ Marshal.WriteByte(data.Scan0, 1, blue.G);
+ Marshal.WriteByte(data.Scan0, 2, blue.R);
+ }
+ finally
+ {
+ bmp.UnlockBits(data);
+ // ...so we still read red after unlocking
+ Assert.Equal(red, bmp.GetPixel(0, 0));
+ }
+
+ data = bmp.LockBits(new Rectangle(0, 0, 1, 1), ImageLockMode.ReadWrite, PixelFormat.Format24bppRgb);
+ try
+ {
+ // write blue
+ Marshal.WriteByte(data.Scan0, 0, blue.B);
+ Marshal.WriteByte(data.Scan0, 1, blue.G);
+ Marshal.WriteByte(data.Scan0, 2, blue.R);
+ }
+ finally
+ {
+ bmp.UnlockBits(data);
+ // read blue
+ Assert.Equal(blue, bmp.GetPixel(0, 0));
+ }
+ }
+ }
+ [ConditionalFact(Helpers.GdiplusIsAvailable)]
+ public void DefaultFormat1()
+ {
+ using (Bitmap bmp = new Bitmap(20, 20))
+ {
+ Assert.Equal(ImageFormat.MemoryBmp, bmp.RawFormat);
+ }
+ }
+
+ [ConditionalFact(Helpers.GdiplusIsAvailable)]
+ public void DefaultFormat2()
+ {
+ string filename = Path.GetTempFileName();
+ using (Bitmap bmp = new Bitmap(20, 20))
+ {
+ bmp.Save(filename);
+ }
+
+ using (Bitmap other = new Bitmap(filename))
+ {
+ Assert.Equal(ImageFormat.Png, other.RawFormat);
+ }
+ File.Delete(filename);
+ }
+
+ [ConditionalFact(Helpers.GdiplusIsAvailable)]
+ public void BmpDataStride1()
+ {
+ Bitmap bmp = new Bitmap(184, 184, PixelFormat.Format1bppIndexed);
+ BitmapData data = bmp.LockBits(new Rectangle(0, 0, bmp.Width, bmp.Height), ImageLockMode.ReadWrite, PixelFormat.Format1bppIndexed);
+ try
+ {
+ Assert.Equal(24, data.Stride);
+ }
+ finally
+ {
+ bmp.UnlockBits(data);
+ bmp.Dispose();
+ }
+ }
+
+ private Stream Serialize(object o)
+ {
+ MemoryStream ms = new MemoryStream();
+ IFormatter formatter = new BinaryFormatter();
+ formatter.Serialize(ms, o);
+ ms.Position = 0;
+ return ms;
+ }
+
+ private object Deserialize(Stream s)
+ {
+ return new BinaryFormatter().Deserialize(s);
+ }
+
+ [ActiveIssue(20844)]
+ public void Serialize_Icon()
+ {
+ // this cause a problem with resgen, see http://bugzilla.ximian.com/show_bug.cgi?id=80565
+ string filename = Helpers.GetTestBitmapPath("16x16_one_entry_4bit.ico");
+ using (Bitmap icon = new Bitmap(filename))
+ {
+ using (Stream s = Serialize(icon))
+ {
+ using (Bitmap copy = (Bitmap)Deserialize(s))
+ {
+ Assert.Equal(icon.Height, copy.Height);
+ Assert.Equal(icon.Width, copy.Width);
+ Assert.Equal(icon.PixelFormat, copy.PixelFormat);
+ Assert.Equal(icon.RawFormat, ImageFormat.Icon);
+ Assert.Equal(copy.RawFormat, ImageFormat.Png);
+ }
+ }
+ }
+ }
+
+ static int[] palette1 = {
+ -16777216,
+ -1,
+ };
+
+ [ConditionalFact(Helpers.GdiplusIsAvailable)]
+ public void Format1bppIndexed_Palette()
+ {
+ using (Bitmap bmp = new Bitmap(1, 1, PixelFormat.Format1bppIndexed))
+ {
+ ColorPalette pal = bmp.Palette;
+ Assert.Equal(2, pal.Entries.Length);
+ for (int i = 0; i < pal.Entries.Length; i++)
+ {
+ Assert.Equal(palette1[i], pal.Entries[i].ToArgb());
+ }
+ Assert.Equal(2, pal.Flags);
+ }
+ }
+
+ static int[] palette16 = {
+ -16777216,
+ -8388608,
+ -16744448,
+ -8355840,
+ -16777088,
+ -8388480,
+ -16744320,
+ -8355712,
+ -4144960,
+ -65536,
+ -16711936,
+ -256,
+ -16776961,
+ -65281,
+ -16711681,
+ -1,
+ };
+
+ [ConditionalFact(Helpers.GdiplusIsAvailable)]
+ public void Format4bppIndexed_Palette()
+ {
+ using (Bitmap bmp = new Bitmap(1, 1, PixelFormat.Format4bppIndexed))
+ {
+ ColorPalette pal = bmp.Palette;
+ Assert.Equal(16, pal.Entries.Length);
+ for (int i = 0; i < pal.Entries.Length; i++)
+ {
+ Assert.Equal(palette16[i], pal.Entries[i].ToArgb());
+ }
+ Assert.Equal(0, pal.Flags);
+ }
+ }
+
+ static int[] palette256 = {
+ -16777216,
+ -8388608,
+ -16744448,
+ -8355840,
+ -16777088,
+ -8388480,
+ -16744320,
+ -8355712,
+ -4144960,
+ -65536,
+ -16711936,
+ -256,
+ -16776961,
+ -65281,
+ -16711681,
+ -1,
+ 0,
+ 0,
+ 0,
+ 0,
+ 0,
+ 0,
+ 0,
+ 0,
+ 0,
+ 0,
+ 0,
+ 0,
+ 0,
+ 0,
+ 0,
+ 0,
+ 0,
+ 0,
+ 0,
+ 0,
+ 0,
+ 0,
+ 0,
+ 0,
+ -16777216,
+ -16777165,
+ -16777114,
+ -16777063,
+ -16777012,
+ -16776961,
+ -16764160,
+ -16764109,
+ -16764058,
+ -16764007,
+ -16763956,
+ -16763905,
+ -16751104,
+ -16751053,
+ -16751002,
+ -16750951,
+ -16750900,
+ -16750849,
+ -16738048,
+ -16737997,
+ -16737946,
+ -16737895,
+ -16737844,
+ -16737793,
+ -16724992,
+ -16724941,
+ -16724890,
+ -16724839,
+ -16724788,
+ -16724737,
+ -16711936,
+ -16711885,
+ -16711834,
+ -16711783,
+ -16711732,
+ -16711681,
+ -13434880,
+ -13434829,
+ -13434778,
+ -13434727,
+ -13434676,
+ -13434625,
+ -13421824,
+ -13421773,
+ -13421722,
+ -13421671,
+ -13421620,
+ -13421569,
+ -13408768,
+ -13408717,
+ -13408666,
+ -13408615,
+ -13408564,
+ -13408513,
+ -13395712,
+ -13395661,
+ -13395610,
+ -13395559,
+ -13395508,
+ -13395457,
+ -13382656,
+ -13382605,
+ -13382554,
+ -13382503,
+ -13382452,
+ -13382401,
+ -13369600,
+ -13369549,
+ -13369498,
+ -13369447,
+ -13369396,
+ -13369345,
+ -10092544,
+ -10092493,
+ -10092442,
+ -10092391,
+ -10092340,
+ -10092289,
+ -10079488,
+ -10079437,
+ -10079386,
+ -10079335,
+ -10079284,
+ -10079233,
+ -10066432,
+ -10066381,
+ -10066330,
+ -10066279,
+ -10066228,
+ -10066177,
+ -10053376,
+ -10053325,
+ -10053274,
+ -10053223,
+ -10053172,
+ -10053121,
+ -10040320,
+ -10040269,
+ -10040218,
+ -10040167,
+ -10040116,
+ -10040065,
+ -10027264,
+ -10027213,
+ -10027162,
+ -10027111,
+ -10027060,
+ -10027009,
+ -6750208,
+ -6750157,
+ -6750106,
+ -6750055,
+ -6750004,
+ -6749953,
+ -6737152,
+ -6737101,
+ -6737050,
+ -6736999,
+ -6736948,
+ -6736897,
+ -6724096,
+ -6724045,
+ -6723994,
+ -6723943,
+ -6723892,
+ -6723841,
+ -6711040,
+ -6710989,
+ -6710938,
+ -6710887,
+ -6710836,
+ -6710785,
+ -6697984,
+ -6697933,
+ -6697882,
+ -6697831,
+ -6697780,
+ -6697729,
+ -6684928,
+ -6684877,
+ -6684826,
+ -6684775,
+ -6684724,
+ -6684673,
+ -3407872,
+ -3407821,
+ -3407770,
+ -3407719,
+ -3407668,
+ -3407617,
+ -3394816,
+ -3394765,
+ -3394714,
+ -3394663,
+ -3394612,
+ -3394561,
+ -3381760,
+ -3381709,
+ -3381658,
+ -3381607,
+ -3381556,
+ -3381505,
+ -3368704,
+ -3368653,
+ -3368602,
+ -3368551,
+ -3368500,
+ -3368449,
+ -3355648,
+ -3355597,
+ -3355546,
+ -3355495,
+ -3355444,
+ -3355393,
+ -3342592,
+ -3342541,
+ -3342490,
+ -3342439,
+ -3342388,
+ -3342337,
+ -65536,
+ -65485,
+ -65434,
+ -65383,
+ -65332,
+ -65281,
+ -52480,
+ -52429,
+ -52378,
+ -52327,
+ -52276,
+ -52225,
+ -39424,
+ -39373,
+ -39322,
+ -39271,
+ -39220,
+ -39169,
+ -26368,
+ -26317,
+ -26266,
+ -26215,
+ -26164,
+ -26113,
+ -13312,
+ -13261,
+ -13210,
+ -13159,
+ -13108,
+ -13057,
+ -256,
+ -205,
+ -154,
+ -103,
+ -52,
+ -1,
+ };
+
+ [ConditionalFact(Helpers.GdiplusIsAvailable)]
+ public void Format8bppIndexed_Palette()
+ {
+ using (Bitmap bmp = new Bitmap(1, 1, PixelFormat.Format8bppIndexed))
+ {
+ ColorPalette pal = bmp.Palette;
+ Assert.Equal(256, pal.Entries.Length);
+ for (int i = 0; i < pal.Entries.Length; i++)
+ {
+ Assert.Equal(palette256[i], pal.Entries[i].ToArgb());
+ }
+ Assert.Equal(4, pal.Flags);
+ }
+ }
+
+ [ConditionalFact(Helpers.GdiplusIsAvailable)]
+ public void XmlSerialization()
+ {
+ new XmlSerializer(typeof(Bitmap));
+ }
+
+ [ConditionalFact(Helpers.GdiplusIsAvailable)]
+ public void BitmapImageCtor()
+ {
+ Assert.Throws<NullReferenceException>(() => new Bitmap((Image)null));
+ }
+
+ [ConditionalFact(Helpers.GdiplusIsAvailable)]
+ public void BitmapImageSizeCtor()
+ {
+ Assert.Throws<ArgumentException>(() => new Bitmap((Image)null, Size.Empty));
+ }
+
+ [ConditionalFact(Helpers.GdiplusIsAvailable)]
+ public void BitmapImageIntIntCtor()
+ {
+ Assert.Throws<ArgumentException>(() => new Bitmap((Image)null, Int32.MinValue, Int32.MaxValue));
+ }
+
+ [ConditionalFact(Helpers.GdiplusIsAvailable)]
+ public void BitmapIntIntCtor()
+ {
+ Assert.Throws<ArgumentException>(() => new Bitmap(Int32.MinValue, Int32.MaxValue));
+ }
+
+ [ConditionalFact(Helpers.GdiplusIsAvailable)]
+ public void BitmapIntIntGraphicCtor()
+ {
+ Assert.Throws<ArgumentNullException>(() => new Bitmap(1, 1, null));
+ }
+
+ [ConditionalFact(Helpers.GdiplusIsAvailable)]
+ public void BitmapIntIntPixelFormatCtor()
+ {
+ Assert.Throws<ArgumentException>(() => new Bitmap(Int32.MinValue, Int32.MaxValue, PixelFormat.Format1bppIndexed));
+ }
+
+ [ConditionalFact(Helpers.GdiplusIsAvailable)]
+ public void BitmapStreamCtor()
+ {
+ AssertExtensions.Throws<ArgumentNullException, ArgumentException>("stream", null, () => new Bitmap((Stream)null));
+ }
+
+ [ConditionalFact(Helpers.GdiplusIsAvailable)]
+ public void BitmapStreamBoolCtor()
+ {
+ AssertExtensions.Throws<ArgumentNullException, ArgumentException>("stream", null, () => new Bitmap((Stream)null, true));
+ }
+
+ [ConditionalFact(Helpers.GdiplusIsAvailable)]
+ public void BitmapStringCtor()
+ {
+ Assert.Throws<ArgumentNullException>(() => new Bitmap((string)null));
+ }
+
+ [ConditionalFact(Helpers.GdiplusIsAvailable)]
+ public void BitmapStringBoolCtor()
+ {
+ Assert.Throws<ArgumentNullException>(() => new Bitmap((string)null, false));
+ }
+
+ [ConditionalFact(Helpers.GdiplusIsAvailable)]
+ public void BitmapTypeStringCtor1()
+ {
+ Assert.Throws<NullReferenceException>(() => new Bitmap((Type)null, "mono"));
+ }
+
+ [ConditionalFact(Helpers.GdiplusIsAvailable)]
+ public void BitmapTypeStringCtor2()
+ {
+ Assert.Throws<ArgumentException>(() => new Bitmap(typeof(Bitmap), null));
+ }
+
+ private void SetResolution(float x, float y)
+ {
+ using (Bitmap bmp = new Bitmap(1, 1))
+ {
+ bmp.SetResolution(x, y);
+ }
+ }
+
+ [ConditionalFact(Helpers.GdiplusIsAvailable)]
+ public void SetResolution_Zero()
+ {
+ Assert.Throws<ArgumentException>(() => SetResolution(0.0f, 0.0f));
+ }
+
+ [ConditionalFact(Helpers.GdiplusIsAvailable)]
+ public void SetResolution_Negative_X()
+ {
+ Assert.Throws<ArgumentException>(() => SetResolution(-1.0f, 1.0f));
+ }
+
+ [ConditionalFact(Helpers.GdiplusIsAvailable)]
+ public void SetResolution_Negative_Y()
+ {
+ Assert.Throws<ArgumentException>(() => SetResolution(1.0f, -1.0f));
+ }
+
+ [ConditionalFact(Helpers.GdiplusIsAvailable)]
+ public void SetResolution_MaxValue()
+ {
+ SetResolution(Single.MaxValue, Single.MaxValue);
+ }
+
+ [ConditionalFact(Helpers.GdiplusIsAvailable)]
+ public void SetResolution_PositiveInfinity()
+ {
+ SetResolution(Single.PositiveInfinity, Single.PositiveInfinity);
+ }
+
+ [ConditionalFact(Helpers.GdiplusIsAvailable)]
+ public void SetResolution_NaN()
+ {
+ Assert.Throws<ArgumentException>(() => SetResolution(Single.NaN, Single.NaN));
+ }
+
+ [ConditionalFact(Helpers.GdiplusIsAvailable)]
+ public void SetResolution_NegativeInfinity()
+ {
+ Assert.Throws<ArgumentException>(() => SetResolution(Single.NegativeInfinity, Single.NegativeInfinity));
+ }
+ }
+
+ public class BitmapFullTrustTest
+ {
+ [ConditionalFact(Helpers.GdiplusIsAvailable)]
+ public void BitmapIntIntIntPixelFormatIntPtrCtor()
+ {
+ new Bitmap(1, 1, 1, PixelFormat.Format1bppIndexed, IntPtr.Zero);
+ }
+
+ // BitmapFromHicon## is *almost* the same as IconTest.Icon##ToBitmap except
+ // for the Flags property
+
+ private void HiconTest(string msg, Bitmap b, int size)
+ {
+ Assert.Equal(PixelFormat.Format32bppArgb, b.PixelFormat);
+ // unlike the GDI+ icon decoder the palette isn't kept
+ Assert.Equal(0, b.Palette.Entries.Length);
+ Assert.Equal(size, b.Height);
+ Assert.Equal(size, b.Width);
+ Assert.Equal(b.RawFormat, ImageFormat.MemoryBmp);
+ Assert.Equal(335888, b.Flags);
+ }
+
+ [ConditionalFact(Helpers.GdiplusIsAvailable)]
+ public void Hicon16()
+ {
+ IntPtr hicon;
+ int size;
+ using (Icon icon = new Icon(Helpers.GetTestBitmapPath("16x16_one_entry_4bit.ico")))
+ {
+ size = icon.Width;
+ using (Bitmap bitmap = Bitmap.FromHicon(icon.Handle))
+ {
+ HiconTest("Icon.Handle/FromHicon", bitmap, size);
+ hicon = bitmap.GetHicon();
+ }
+ }
+ using (Bitmap bitmap2 = Bitmap.FromHicon(hicon))
+ {
+ // hicon survives bitmap and icon disposal
+ HiconTest("GetHicon/FromHicon", bitmap2, size);
+ }
+ }
+
+ [ConditionalFact(Helpers.GdiplusIsAvailable)]
+ public void Hicon32()
+ {
+ IntPtr hicon;
+ int size;
+ using (Icon icon = new Icon(Helpers.GetTestBitmapPath("32x32_one_entry_4bit.ico")))
+ {
+ size = icon.Width;
+ using (Bitmap bitmap = Bitmap.FromHicon(icon.Handle))
+ {
+ HiconTest("Icon.Handle/FromHicon", bitmap, size);
+ hicon = bitmap.GetHicon();
+ }
+ }
+ using (Bitmap bitmap2 = Bitmap.FromHicon(hicon))
+ {
+ // hicon survives bitmap and icon disposal
+ HiconTest("GetHicon/FromHicon", bitmap2, size);
+ }
+ }
+
+ [ConditionalFact(Helpers.GdiplusIsAvailable)]
+ public void Hicon64()
+ {
+ IntPtr hicon;
+ int size;
+ using (Icon icon = new Icon(Helpers.GetTestBitmapPath("64x64_one_entry_8bit.ico")))
+ {
+ size = icon.Width;
+ using (Bitmap bitmap = Bitmap.FromHicon(icon.Handle))
+ {
+ HiconTest("Icon.Handle/FromHicon", bitmap, size);
+ hicon = bitmap.GetHicon();
+ }
+ }
+ using (Bitmap bitmap2 = Bitmap.FromHicon(hicon))
+ {
+ // hicon survives bitmap and icon disposal
+ HiconTest("GetHicon/FromHicon", bitmap2, size);
+ }
+ }
+
+ [ConditionalFact(Helpers.GdiplusIsAvailable)]
+ public void Hicon96()
+ {
+ IntPtr hicon;
+ int size;
+ using (Icon icon = new Icon(Helpers.GetTestBitmapPath("96x96_one_entry_8bit.ico")))
+ {
+ size = icon.Width;
+ using (Bitmap bitmap = Bitmap.FromHicon(icon.Handle))
+ {
+ HiconTest("Icon.Handle/FromHicon", bitmap, size);
+ hicon = bitmap.GetHicon();
+ }
+ }
+ using (Bitmap bitmap2 = Bitmap.FromHicon(hicon))
+ {
+ // hicon survives bitmap and icon disposal
+ HiconTest("GetHicon/FromHicon", bitmap2, size);
+ }
+ }
+
+ [ConditionalFact(Helpers.GdiplusIsAvailable)]
+ public void HBitmap()
+ {
+ IntPtr hbitmap;
+ string sInFile = Helpers.GetTestBitmapPath("almogaver24bits.bmp");
+ using (Bitmap bitmap = new Bitmap(sInFile))
+ {
+ Assert.Equal(PixelFormat.Format24bppRgb, bitmap.PixelFormat);
+ Assert.Equal(0, bitmap.Palette.Entries.Length);
+ Assert.Equal(183, bitmap.Height);
+ Assert.Equal(173, bitmap.Width);
+ Assert.Equal(73744, bitmap.Flags);
+ Assert.Equal(bitmap.RawFormat, ImageFormat.Bmp);
+ hbitmap = bitmap.GetHbitmap();
+ }
+
+ // hbitmap survives original bitmap disposal
+ using (Image image = Image.FromHbitmap(hbitmap))
+ {
+ //Assert.Equal (PixelFormat.Format32bppRgb, image.PixelFormat);
+ Assert.Equal(0, image.Palette.Entries.Length);
+ Assert.Equal(183, image.Height);
+ Assert.Equal(173, image.Width);
+ Assert.Equal(335888, image.Flags);
+ Assert.Equal(image.RawFormat, ImageFormat.MemoryBmp);
+ }
+ }
+
+ [ConditionalFact(Helpers.GdiplusIsAvailable)]
+ public void CreateMultipleBitmapFromSameHBITMAP()
+ {
+ IntPtr hbitmap;
+ string sInFile = Helpers.GetTestBitmapPath("almogaver24bits.bmp");
+ using (Bitmap bitmap = new Bitmap(sInFile))
+ {
+ Assert.Equal(PixelFormat.Format24bppRgb, bitmap.PixelFormat);
+ Assert.Equal(0, bitmap.Palette.Entries.Length);
+ Assert.Equal(183, bitmap.Height);
+ Assert.Equal(173, bitmap.Width);
+ Assert.Equal(73744, bitmap.Flags);
+ Assert.Equal(bitmap.RawFormat, ImageFormat.Bmp);
+ hbitmap = bitmap.GetHbitmap();
+ }
+ // hbitmap survives original bitmap disposal
+ using (Image image = Image.FromHbitmap(hbitmap))
+ {
+ //Assert.Equal (PixelFormat.Format32bppRgb, image.PixelFormat);
+ Assert.Equal(0, image.Palette.Entries.Length);
+ Assert.Equal(183, image.Height);
+ Assert.Equal(173, image.Width);
+ Assert.Equal(335888, image.Flags);
+ Assert.Equal(image.RawFormat, ImageFormat.MemoryBmp);
+ }
+ using (Image image2 = Image.FromHbitmap(hbitmap))
+ {
+ //Assert.Equal (PixelFormat.Format32bppRgb, image2.PixelFormat);
+ Assert.Equal(0, image2.Palette.Entries.Length);
+ Assert.Equal(183, image2.Height);
+ Assert.Equal(173, image2.Width);
+ Assert.Equal(335888, image2.Flags);
+ Assert.Equal(image2.RawFormat, ImageFormat.MemoryBmp);
+ }
+ }
+ }
+}
+
diff --git a/src/System.Drawing.Common/tests/mono/System.Drawing/GraphicsTests.cs b/src/System.Drawing.Common/tests/mono/System.Drawing/GraphicsTests.cs
new file mode 100644
index 0000000000..a87fb83b6b
--- /dev/null
+++ b/src/System.Drawing.Common/tests/mono/System.Drawing/GraphicsTests.cs
@@ -0,0 +1,3251 @@
+// Licensed to the .NET Foundation under one or more agreements.
+// See the LICENSE file in the project root for more information.
+//
+// Graphics class testing unit
+//
+// Authors:
+// Jordi Mas, jordi@ximian.com
+// Sebastien Pouliot <sebastien@ximian.com>
+//
+// Copyright (C) 2005-2008 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;
+using System.Drawing;
+using System.Drawing.Drawing2D;
+using System.Drawing.Imaging;
+using System.Drawing.Text;
+using Xunit;
+
+namespace MonoTests.System.Drawing
+{
+ public class GraphicsTest : IDisposable
+ {
+ private RectangleF[] rects;
+ private Font font;
+
+ public GraphicsTest()
+ {
+ try
+ {
+ font = new Font("Arial", 12);
+ }
+ catch
+ {
+ }
+ }
+
+ public void Dispose()
+ {
+ if (font != null)
+ font.Dispose();
+ }
+
+ private bool IsEmptyBitmap(Bitmap bitmap, out int x, out int y)
+ {
+ bool result = true;
+ int empty = Color.Empty.ToArgb();
+ for (y = 0; y < bitmap.Height; y++)
+ {
+ for (x = 0; x < bitmap.Width; x++)
+ {
+ if (bitmap.GetPixel(x, y).ToArgb() != empty)
+ return false;
+ }
+ }
+
+ x = -1;
+ y = -1;
+ return result;
+ }
+
+ private void CheckForEmptyBitmap(Bitmap bitmap)
+ {
+ int x, y;
+ if (!IsEmptyBitmap(bitmap, out x, out y))
+ Assert.True(false, String.Format("Position {0},{1}", x, y));
+ }
+
+ private void CheckForNonEmptyBitmap(Bitmap bitmap)
+ {
+ int x, y;
+ if (IsEmptyBitmap(bitmap, out x, out y))
+ Assert.True(false);
+ }
+
+ private void AssertEquals(string msg, object expected, object actual)
+ {
+ Assert.Equal(expected, actual);
+ }
+
+ private void AssertEquals(string msg, double expected, double actual, int precision)
+ {
+ Assert.Equal(expected, actual, precision);
+ }
+
+ [ConditionalFact(Helpers.GdiplusIsAvailable)]
+ public void DefaultProperties()
+ {
+ using (Bitmap bmp = new Bitmap(200, 200))
+ using (Graphics g = Graphics.FromImage(bmp))
+ using (Region r = new Region())
+ {
+ Assert.Equal(r.GetBounds(g), g.ClipBounds);
+ Assert.Equal(CompositingMode.SourceOver, g.CompositingMode);
+ Assert.Equal(CompositingQuality.Default, g.CompositingQuality);
+ Assert.Equal(InterpolationMode.Bilinear, g.InterpolationMode);
+ Assert.Equal(1, g.PageScale);
+ Assert.Equal(GraphicsUnit.Display, g.PageUnit);
+ Assert.Equal(PixelOffsetMode.Default, g.PixelOffsetMode);
+ Assert.Equal(new Point(0, 0), g.RenderingOrigin);
+ Assert.Equal(SmoothingMode.None, g.SmoothingMode);
+ Assert.Equal(TextRenderingHint.SystemDefault, g.TextRenderingHint);
+ }
+ }
+
+ [ConditionalFact(Helpers.GdiplusIsAvailable)]
+ public void SetGetProperties()
+ {
+ using (Bitmap bmp = new Bitmap(200, 200))
+ using (Graphics g = Graphics.FromImage(bmp))
+ {
+ g.CompositingMode = CompositingMode.SourceCopy;
+ g.CompositingQuality = CompositingQuality.GammaCorrected;
+ g.InterpolationMode = InterpolationMode.HighQualityBilinear;
+ g.PageScale = 2;
+ g.PageUnit = GraphicsUnit.Inch;
+ g.PixelOffsetMode = PixelOffsetMode.Half;
+ g.RenderingOrigin = new Point(10, 20);
+ g.SmoothingMode = SmoothingMode.AntiAlias;
+ g.TextRenderingHint = TextRenderingHint.SystemDefault;
+
+ //Clipping set/get tested in clipping functions
+ Assert.Equal(CompositingMode.SourceCopy, g.CompositingMode);
+ Assert.Equal(CompositingQuality.GammaCorrected, g.CompositingQuality);
+ Assert.Equal(InterpolationMode.HighQualityBilinear, g.InterpolationMode);
+ Assert.Equal(2, g.PageScale);
+ Assert.Equal(GraphicsUnit.Inch, g.PageUnit);
+ Assert.Equal(PixelOffsetMode.Half, g.PixelOffsetMode);
+ Assert.Equal(new Point(10, 20), g.RenderingOrigin);
+ Assert.Equal(SmoothingMode.AntiAlias, g.SmoothingMode);
+ Assert.Equal(TextRenderingHint.SystemDefault, g.TextRenderingHint);
+ }
+ }
+
+ // Properties
+ [ConditionalFact(Helpers.GdiplusIsAvailable)]
+ public void Clip()
+ {
+ RectangleF[] rects;
+ using (Bitmap bmp = new Bitmap(200, 200))
+ using (Graphics g = Graphics.FromImage(bmp))
+ {
+ g.Clip = new Region(new Rectangle(50, 40, 210, 220));
+ rects = g.Clip.GetRegionScans(new Matrix());
+
+ Assert.Equal(1, rects.Length);
+ Assert.Equal(50, rects[0].X);
+ Assert.Equal(40, rects[0].Y);
+ Assert.Equal(210, rects[0].Width);
+ Assert.Equal(220, rects[0].Height);
+ }
+ }
+
+ [ConditionalFact(Helpers.GdiplusIsAvailable)]
+ public void Clip_NotAReference()
+ {
+ using (Bitmap bmp = new Bitmap(200, 200))
+ using (Graphics g = Graphics.FromImage(bmp))
+ {
+ Assert.True(g.Clip.IsInfinite(g));
+ g.Clip.IsEmpty(g);
+ Assert.False(g.Clip.IsEmpty(g));
+ Assert.True(g.Clip.IsInfinite(g));
+ }
+ }
+
+ [ConditionalFact(Helpers.GdiplusIsAvailable)]
+ public void ExcludeClip()
+ {
+ using (Bitmap bmp = new Bitmap(200, 200))
+ using (Graphics g = Graphics.FromImage(bmp))
+ {
+ g.Clip = new Region(new RectangleF(10, 10, 100, 100));
+ g.ExcludeClip(new Rectangle(40, 60, 100, 20));
+ rects = g.Clip.GetRegionScans(new Matrix());
+
+ Assert.Equal(3, rects.Length);
+
+ Assert.Equal(10, rects[0].X);
+ Assert.Equal(10, rects[0].Y);
+ Assert.Equal(100, rects[0].Width);
+ Assert.Equal(50, rects[0].Height);
+
+ Assert.Equal(10, rects[1].X);
+ Assert.Equal(60, rects[1].Y);
+ Assert.Equal(30, rects[1].Width);
+ Assert.Equal(20, rects[1].Height);
+
+ Assert.Equal(10, rects[2].X);
+ Assert.Equal(80, rects[2].Y);
+ Assert.Equal(100, rects[2].Width);
+ Assert.Equal(30, rects[2].Height);
+ }
+ }
+
+ [ConditionalFact(Helpers.GdiplusIsAvailable)]
+ public void IntersectClip()
+ {
+ using (Bitmap bmp = new Bitmap(200, 200))
+ using (Graphics g = Graphics.FromImage(bmp))
+ {
+ g.Clip = new Region(new RectangleF(260, 30, 60, 80));
+ g.IntersectClip(new Rectangle(290, 40, 60, 80));
+ rects = g.Clip.GetRegionScans(new Matrix());
+
+ Assert.Equal(1, rects.Length);
+
+ Assert.Equal(290, rects[0].X);
+ Assert.Equal(40, rects[0].Y);
+ Assert.Equal(30, rects[0].Width);
+ Assert.Equal(70, rects[0].Height);
+ }
+ }
+
+ [ConditionalFact(Helpers.GdiplusIsAvailable)]
+ public void ResetClip()
+ {
+ using (Bitmap bmp = new Bitmap(200, 200))
+ using (Graphics g = Graphics.FromImage(bmp))
+ {
+ g.Clip = new Region(new RectangleF(260, 30, 60, 80));
+ g.IntersectClip(new Rectangle(290, 40, 60, 80));
+ g.ResetClip();
+ rects = g.Clip.GetRegionScans(new Matrix());
+
+ Assert.Equal(1, rects.Length);
+
+ Assert.Equal(-4194304, rects[0].X);
+ Assert.Equal(-4194304, rects[0].Y);
+ Assert.Equal(8388608, rects[0].Width);
+ Assert.Equal(8388608, rects[0].Height);
+ }
+ }
+
+ [ConditionalFact(Helpers.GdiplusIsAvailable)]
+ public void SetClip()
+ {
+ RectangleF[] rects;
+ using (Bitmap bmp = new Bitmap(200, 200))
+ {
+ Graphics g = Graphics.FromImage(bmp);
+ // Region
+ g.SetClip(new Region(new Rectangle(50, 40, 210, 220)), CombineMode.Replace);
+ rects = g.Clip.GetRegionScans(new Matrix());
+ Assert.Equal(1, rects.Length);
+ Assert.Equal(50, rects[0].X);
+ Assert.Equal(40, rects[0].Y);
+ Assert.Equal(210, rects[0].Width);
+ Assert.Equal(220, rects[0].Height);
+ g.Dispose();
+
+ // RectangleF
+ g = Graphics.FromImage(bmp);
+ g.SetClip(new RectangleF(50, 40, 210, 220));
+ rects = g.Clip.GetRegionScans(new Matrix());
+ Assert.Equal(1, rects.Length);
+ Assert.Equal(50, rects[0].X);
+ Assert.Equal(40, rects[0].Y);
+ Assert.Equal(210, rects[0].Width);
+ Assert.Equal(220, rects[0].Height);
+ g.Dispose();
+
+ // Rectangle
+ g = Graphics.FromImage(bmp);
+ g.SetClip(new Rectangle(50, 40, 210, 220));
+ rects = g.Clip.GetRegionScans(new Matrix());
+ Assert.Equal(1, rects.Length);
+ Assert.Equal(50, rects[0].X);
+ Assert.Equal(40, rects[0].Y);
+ Assert.Equal(210, rects[0].Width);
+ Assert.Equal(220, rects[0].Height);
+ }
+ }
+
+ [ConditionalFact(Helpers.GdiplusIsAvailable)]
+ public void SetSaveReset()
+ {
+ using (Bitmap bmp = new Bitmap(200, 200))
+ using (Graphics g = Graphics.FromImage(bmp))
+ {
+ GraphicsState state_default, state_modified;
+
+ state_default = g.Save(); // Default
+
+ g.CompositingMode = CompositingMode.SourceCopy;
+ g.CompositingQuality = CompositingQuality.GammaCorrected;
+ g.InterpolationMode = InterpolationMode.HighQualityBilinear;
+ g.PageScale = 2;
+ g.PageUnit = GraphicsUnit.Inch;
+ g.PixelOffsetMode = PixelOffsetMode.Half;
+ g.Clip = new Region(new Rectangle(0, 0, 100, 100));
+ g.RenderingOrigin = new Point(10, 20);
+ g.SmoothingMode = SmoothingMode.AntiAlias;
+ g.TextRenderingHint = TextRenderingHint.ClearTypeGridFit;
+
+
+ state_modified = g.Save(); // Modified
+
+ g.CompositingMode = CompositingMode.SourceOver;
+ g.CompositingQuality = CompositingQuality.Default;
+ g.InterpolationMode = InterpolationMode.Bilinear;
+ g.PageScale = 5;
+ g.PageUnit = GraphicsUnit.Display;
+ g.PixelOffsetMode = PixelOffsetMode.Default;
+ g.Clip = new Region(new Rectangle(1, 2, 20, 25));
+ g.RenderingOrigin = new Point(5, 6);
+ g.SmoothingMode = SmoothingMode.None;
+ g.TextRenderingHint = TextRenderingHint.SystemDefault;
+
+ g.Restore(state_modified);
+
+ Assert.Equal(CompositingMode.SourceCopy, g.CompositingMode);
+ Assert.Equal(CompositingQuality.GammaCorrected, g.CompositingQuality);
+ Assert.Equal(InterpolationMode.HighQualityBilinear, g.InterpolationMode);
+ Assert.Equal(2, g.PageScale);
+ Assert.Equal(GraphicsUnit.Inch, g.PageUnit);
+ Assert.Equal(PixelOffsetMode.Half, g.PixelOffsetMode);
+ Assert.Equal(new Point(10, 20), g.RenderingOrigin);
+ Assert.Equal(SmoothingMode.AntiAlias, g.SmoothingMode);
+ Assert.Equal(TextRenderingHint.ClearTypeGridFit, g.TextRenderingHint);
+ Assert.Equal(0, (int)g.ClipBounds.X);
+ Assert.Equal(0, (int)g.ClipBounds.Y);
+
+ g.Restore(state_default);
+
+ Assert.Equal(CompositingMode.SourceOver, g.CompositingMode);
+ Assert.Equal(CompositingQuality.Default, g.CompositingQuality);
+ Assert.Equal(InterpolationMode.Bilinear, g.InterpolationMode);
+ Assert.Equal(1, g.PageScale);
+ Assert.Equal(GraphicsUnit.Display, g.PageUnit);
+ Assert.Equal(PixelOffsetMode.Default, g.PixelOffsetMode);
+ Assert.Equal(new Point(0, 0), g.RenderingOrigin);
+ Assert.Equal(SmoothingMode.None, g.SmoothingMode);
+ Assert.Equal(TextRenderingHint.SystemDefault, g.TextRenderingHint);
+
+ Region r = new Region();
+ Assert.Equal(r.GetBounds(g), g.ClipBounds);
+ }
+ }
+
+ [ConditionalFact(Helpers.GdiplusIsAvailable)]
+ public void LoadIndexed_BmpFile()
+ {
+ // Tests that we can load an indexed file, but...
+ string sInFile = Helpers.GetTestBitmapPath("almogaver1bit.bmp");
+ // note: file is misnamed (it's a 4bpp bitmap)
+ using (Image img = Image.FromFile(sInFile))
+ {
+ Assert.Equal(PixelFormat.Format4bppIndexed, img.PixelFormat);
+ Assert.Throws<Exception>(() => Graphics.FromImage(img));
+ }
+ }
+
+ class BitmapAndGraphics : IDisposable
+ {
+ private readonly Bitmap _bitmap;
+ public Graphics Graphics { get; }
+ public BitmapAndGraphics(int width, int height)
+ {
+ _bitmap = new Bitmap(width, height);
+ Graphics = Graphics.FromImage(_bitmap);
+ Graphics.Clip = new Region(new Rectangle(0, 0, width, height));
+ }
+ public void Dispose() { Graphics.Dispose(); _bitmap.Dispose(); }
+ }
+
+ private void Compare(string msg, RectangleF b1, RectangleF b2)
+ {
+ AssertEquals(msg + ".compare.X", b1.X, b2.X);
+ AssertEquals(msg + ".compare.Y", b1.Y, b2.Y);
+ AssertEquals(msg + ".compare.Width", b1.Width, b2.Width);
+ AssertEquals(msg + ".compare.Height", b1.Height, b2.Height);
+ }
+
+ [ConditionalFact(Helpers.GdiplusIsAvailable)]
+ public void Clip_GetBounds()
+ {
+ using (var b = new BitmapAndGraphics(16, 16))
+ {
+ var g = b.Graphics;
+ RectangleF bounds = g.Clip.GetBounds(g);
+ Assert.Equal(0, bounds.X);
+ Assert.Equal(0, bounds.Y);
+ Assert.Equal(16, bounds.Width);
+ Assert.Equal(16, bounds.Height);
+ Assert.True(g.Transform.IsIdentity);
+ }
+ }
+
+ [ConditionalFact(Helpers.GdiplusIsAvailable)]
+ public void Clip_TranslateTransform()
+ {
+ using (var b = new BitmapAndGraphics(16, 16))
+ {
+ var g = b.Graphics;
+ g.TranslateTransform(12.22f, 10.10f);
+ RectangleF bounds = g.Clip.GetBounds(g);
+ Compare("translate", bounds, g.ClipBounds);
+ Assert.Equal(-12.2200003f, bounds.X);
+ Assert.Equal(-10.1000004f, bounds.Y);
+ Assert.Equal(16, bounds.Width);
+ Assert.Equal(16, bounds.Height);
+ float[] elements = g.Transform.Elements;
+ Assert.Equal(1, elements[0]);
+ Assert.Equal(0, elements[1]);
+ Assert.Equal(0, elements[2]);
+ Assert.Equal(1, elements[3]);
+ Assert.Equal(12.2200003f, elements[4]);
+ Assert.Equal(10.1000004f, elements[5]);
+
+ g.ResetTransform();
+ bounds = g.Clip.GetBounds(g);
+ Compare("reset", bounds, g.ClipBounds);
+ Assert.Equal(0, bounds.X);
+ Assert.Equal(0, bounds.Y);
+ Assert.Equal(16, bounds.Width);
+ Assert.Equal(16, bounds.Height);
+ Assert.True(g.Transform.IsIdentity);
+ }
+ }
+
+ [ConditionalFact(Helpers.GdiplusIsAvailable)]
+ public void Transform_NonInvertibleMatrix()
+ {
+ Matrix matrix = new Matrix(123, 24, 82, 16, 47, 30);
+ Assert.False(matrix.IsInvertible);
+
+ using (var b = new BitmapAndGraphics(16, 16))
+ {
+ var g = b.Graphics;
+ Assert.Throws<ArgumentException>(() => g.Transform = matrix);
+ }
+ }
+
+
+ [ConditionalFact(Helpers.GdiplusIsAvailable)]
+ public void Multiply_NonInvertibleMatrix()
+ {
+ Matrix matrix = new Matrix(123, 24, 82, 16, 47, 30);
+ Assert.False(matrix.IsInvertible);
+ using (var b = new BitmapAndGraphics(16, 16))
+ {
+ var g = b.Graphics;
+ Assert.Throws<ArgumentException>(() => g.MultiplyTransform(matrix));
+ }
+ }
+
+ private void CheckBounds(string msg, RectangleF bounds, float x, float y, float w, float h)
+ {
+ AssertEquals(msg + ".X", x, bounds.X, 1);
+ AssertEquals(msg + ".Y", y, bounds.Y, 1);
+ AssertEquals(msg + ".Width", w, bounds.Width, 1);
+ AssertEquals(msg + ".Height", h, bounds.Height, 1);
+ }
+
+ [ConditionalFact(Helpers.GdiplusIsAvailable)]
+ public void ClipBounds()
+ {
+ using (var b = new BitmapAndGraphics(16, 16))
+ {
+ var g = b.Graphics;
+ CheckBounds("graphics.ClipBounds", g.ClipBounds, 0, 0, 16, 16);
+ CheckBounds("graphics.Clip.GetBounds", g.Clip.GetBounds(g), 0, 0, 16, 16);
+
+ g.Clip = new Region(new Rectangle(0, 0, 8, 8));
+ CheckBounds("clip.ClipBounds", g.ClipBounds, 0, 0, 8, 8);
+ CheckBounds("clip.Clip.GetBounds", g.Clip.GetBounds(g), 0, 0, 8, 8);
+ }
+ }
+
+ [ConditionalFact(Helpers.GdiplusIsAvailable)]
+ public void ClipBounds_Rotate()
+ {
+ using (var b = new BitmapAndGraphics(16, 16))
+ {
+ var g = b.Graphics;
+ g.Clip = new Region(new Rectangle(0, 0, 8, 8));
+ g.RotateTransform(90);
+ CheckBounds("rotate.ClipBounds", g.ClipBounds, 0, -8, 8, 8);
+ CheckBounds("rotate.Clip.GetBounds", g.Clip.GetBounds(g), 0, -8, 8, 8);
+
+ g.Transform = new Matrix();
+ CheckBounds("identity.ClipBounds", g.Clip.GetBounds(g), 0, 0, 8, 8);
+ CheckBounds("identity.Clip.GetBounds", g.Clip.GetBounds(g), 0, 0, 8, 8);
+ }
+ }
+
+ [ConditionalFact(Helpers.GdiplusIsAvailable)]
+ public void ClipBounds_Scale()
+ {
+ RectangleF clip = new Rectangle(0, 0, 8, 8);
+ using (var b = new BitmapAndGraphics(16, 16))
+ {
+ var g = b.Graphics;
+ g.Clip = new Region(clip);
+ g.ScaleTransform(0.25f, 0.5f);
+ CheckBounds("scale.ClipBounds", g.ClipBounds, 0, 0, 32, 16);
+ CheckBounds("scale.Clip.GetBounds", g.Clip.GetBounds(g), 0, 0, 32, 16);
+
+ g.SetClip(clip);
+ CheckBounds("setclip.ClipBounds", g.ClipBounds, 0, 0, 8, 8);
+ CheckBounds("setclip.Clip.GetBounds", g.Clip.GetBounds(g), 0, 0, 8, 8);
+ }
+ }
+
+ [ConditionalFact(Helpers.GdiplusIsAvailable)]
+ public void ClipBounds_Translate()
+ {
+ using (var b = new BitmapAndGraphics(16, 16))
+ {
+ var g = b.Graphics;
+ g.Clip = new Region(new Rectangle(0, 0, 8, 8));
+ Region clone = g.Clip.Clone();
+ g.TranslateTransform(8, 8);
+ CheckBounds("translate.ClipBounds", g.ClipBounds, -8, -8, 8, 8);
+ CheckBounds("translate.Clip.GetBounds", g.Clip.GetBounds(g), -8, -8, 8, 8);
+
+ g.SetClip(clone, CombineMode.Replace);
+ CheckBounds("setclip.ClipBounds", g.Clip.GetBounds(g), 0, 0, 8, 8);
+ CheckBounds("setclip.Clip.GetBounds", g.Clip.GetBounds(g), 0, 0, 8, 8);
+ }
+ }
+
+ [ConditionalFact(Helpers.GdiplusIsAvailable)]
+ public void ClipBounds_Transform_Translation()
+ {
+ using (var b = new BitmapAndGraphics(16, 16))
+ {
+ var g = b.Graphics;
+ g.Clip = new Region(new Rectangle(0, 0, 8, 8));
+ g.Transform = new Matrix(1, 0, 0, 1, 8, 8);
+ CheckBounds("transform.ClipBounds", g.ClipBounds, -8, -8, 8, 8);
+ CheckBounds("transform.Clip.GetBounds", g.Clip.GetBounds(g), -8, -8, 8, 8);
+
+ g.ResetTransform();
+ CheckBounds("reset.ClipBounds", g.ClipBounds, 0, 0, 8, 8);
+ CheckBounds("reset.Clip.GetBounds", g.Clip.GetBounds(g), 0, 0, 8, 8);
+ }
+ }
+
+ [ConditionalFact(Helpers.GdiplusIsAvailable)]
+ public void ClipBounds_Transform_Scale()
+ {
+ using (var b = new BitmapAndGraphics(16, 16))
+ {
+ var g = b.Graphics;
+ g.Clip = new Region(new Rectangle(0, 0, 8, 8));
+ g.Transform = new Matrix(0.5f, 0, 0, 0.25f, 0, 0);
+ CheckBounds("scale.ClipBounds", g.ClipBounds, 0, 0, 16, 32);
+ CheckBounds("scale.Clip.GetBounds", g.Clip.GetBounds(g), 0, 0, 16, 32);
+
+ g.ResetClip();
+ // see next test for ClipBounds
+ CheckBounds("resetclip.Clip.GetBounds", g.Clip.GetBounds(g), -4194304, -4194304, 8388608, 8388608);
+ Assert.True(g.Clip.IsInfinite(g));
+ }
+ }
+
+ [ConditionalFact(Helpers.GdiplusIsAvailable)]
+ public void ClipBounds_Multiply()
+ {
+ using (var b = new BitmapAndGraphics(16, 16))
+ {
+ var g = b.Graphics;
+ g.Clip = new Region(new Rectangle(0, 0, 8, 8));
+ g.Transform = new Matrix(1, 0, 0, 1, 8, 8);
+ g.MultiplyTransform(g.Transform);
+ CheckBounds("multiply.ClipBounds", g.ClipBounds, -16, -16, 8, 8);
+ CheckBounds("multiply.Clip.GetBounds", g.Clip.GetBounds(g), -16, -16, 8, 8);
+
+ g.ResetTransform();
+ CheckBounds("reset.ClipBounds", g.ClipBounds, 0, 0, 8, 8);
+ CheckBounds("reset.Clip.GetBounds", g.Clip.GetBounds(g), 0, 0, 8, 8);
+ }
+ }
+
+ [ConditionalFact(Helpers.GdiplusIsAvailable)]
+ public void ClipBounds_Cumulative_Effects()
+ {
+ using (var b = new BitmapAndGraphics(16, 16))
+ {
+ var g = b.Graphics;
+ CheckBounds("graphics.ClipBounds", g.ClipBounds, 0, 0, 16, 16);
+ CheckBounds("graphics.Clip.GetBounds", g.Clip.GetBounds(g), 0, 0, 16, 16);
+
+ g.Clip = new Region(new Rectangle(0, 0, 8, 8));
+ CheckBounds("clip.ClipBounds", g.ClipBounds, 0, 0, 8, 8);
+ CheckBounds("clip.Clip.GetBounds", g.Clip.GetBounds(g), 0, 0, 8, 8);
+
+ g.RotateTransform(90);
+ CheckBounds("rotate.ClipBounds", g.ClipBounds, 0, -8, 8, 8);
+ CheckBounds("rotate.Clip.GetBounds", g.Clip.GetBounds(g), 0, -8, 8, 8);
+
+ g.ScaleTransform(0.25f, 0.5f);
+ CheckBounds("scale.ClipBounds", g.ClipBounds, 0, -16, 32, 16);
+ CheckBounds("scale.Clip.GetBounds", g.Clip.GetBounds(g), 0, -16, 32, 16);
+
+ g.TranslateTransform(8, 8);
+ CheckBounds("translate.ClipBounds", g.ClipBounds, -8, -24, 32, 16);
+ CheckBounds("translate.Clip.GetBounds", g.Clip.GetBounds(g), -8, -24, 32, 16);
+
+ g.MultiplyTransform(g.Transform);
+ CheckBounds("multiply.ClipBounds", g.ClipBounds, -104, -56, 64, 64);
+ CheckBounds("multiply.Clip.GetBounds", g.Clip.GetBounds(g), -104, -56, 64, 64);
+
+ g.ResetTransform();
+ CheckBounds("reset.ClipBounds", g.ClipBounds, 0, 0, 8, 8);
+ CheckBounds("reset.Clip.GetBounds", g.Clip.GetBounds(g), 0, 0, 8, 8);
+ }
+ }
+
+ [ConditionalFact(Helpers.GdiplusIsAvailable)]
+ public void Clip_TranslateTransform_BoundsChange()
+ {
+ using (var b = new BitmapAndGraphics(16, 16))
+ {
+ var g = b.Graphics;
+ CheckBounds("graphics.ClipBounds", g.ClipBounds, 0, 0, 16, 16);
+ CheckBounds("graphics.Clip.GetBounds", g.Clip.GetBounds(g), 0, 0, 16, 16);
+ g.TranslateTransform(-16, -16);
+ CheckBounds("translated.ClipBounds", g.ClipBounds, 16, 16, 16, 16);
+ CheckBounds("translated.Clip.GetBounds", g.Clip.GetBounds(g), 16, 16, 16, 16);
+
+ g.Clip = new Region(new Rectangle(0, 0, 8, 8));
+ // ClipBounds isn't affected by a previous translation
+ CheckBounds("rectangle.ClipBounds", g.ClipBounds, 0, 0, 8, 8);
+ // Clip.GetBounds isn't affected by a previous translation
+ CheckBounds("rectangle.Clip.GetBounds", g.Clip.GetBounds(g), 0, 0, 8, 8);
+
+ g.ResetTransform();
+ CheckBounds("reseted.ClipBounds", g.ClipBounds, -16, -16, 8, 8);
+ CheckBounds("reseted.Clip.GetBounds", g.Clip.GetBounds(g), -16, -16, 8, 8);
+ }
+ }
+
+ [ConditionalFact(Helpers.GdiplusIsAvailable)]
+ public void Clip_RotateTransform_BoundsChange()
+ {
+ using (var b = new BitmapAndGraphics(16, 16))
+ {
+ var g = b.Graphics;
+ CheckBounds("graphics.ClipBounds", g.ClipBounds, 0, 0, 16, 16);
+ CheckBounds("graphics.Clip.GetBounds", g.Clip.GetBounds(g), 0, 0, 16, 16);
+ // we select a "simple" angle because the region will be converted into
+ // a bitmap (well for libgdiplus) and we would lose precision after that
+ g.RotateTransform(90);
+ CheckBounds("rotated.ClipBounds", g.ClipBounds, 0, -16, 16, 16);
+ CheckBounds("rotated.Clip.GetBounds", g.Clip.GetBounds(g), 0, -16, 16, 16);
+ g.Clip = new Region(new Rectangle(0, 0, 8, 8));
+ // ClipBounds isn't affected by a previous rotation (90)
+ CheckBounds("rectangle.ClipBounds", g.ClipBounds, 0, 0, 8, 8);
+ // Clip.GetBounds isn't affected by a previous rotation
+ CheckBounds("rectangle.Clip.GetBounds", g.Clip.GetBounds(g), 0, 0, 8, 8);
+
+ g.ResetTransform();
+ CheckBounds("reseted.ClipBounds", g.ClipBounds, -8, 0, 8, 8);
+ CheckBounds("reseted.Clip.GetBounds", g.Clip.GetBounds(g), -8, 0, 8, 8);
+ }
+ }
+
+ private void CheckBoundsInt(string msg, RectangleF bounds, int x, int y, int w, int h)
+ {
+ // currently bounds are rounded at 8 pixels (FIXME - we can go down to 1 pixel)
+ AssertEquals(msg + ".X", x, bounds.X, -1);
+ AssertEquals(msg + ".Y", y, bounds.Y, -1);
+ AssertEquals(msg + ".Width", w, bounds.Width, -1);
+ AssertEquals(msg + ".Height", h, bounds.Height, -1);
+ }
+
+ [ConditionalFact(Helpers.GdiplusIsAvailable)]
+ public void Clip_ScaleTransform_NoBoundsChange()
+ {
+ using (var b = new BitmapAndGraphics(16, 16))
+ {
+ var g = b.Graphics;
+ CheckBounds("graphics.ClipBounds", g.ClipBounds, 0, 0, 16, 16);
+ CheckBounds("graphics.Clip.GetBounds", g.Clip.GetBounds(g), 0, 0, 16, 16);
+ g.ScaleTransform(2, 0.5f);
+ CheckBounds("scaled.ClipBounds", g.ClipBounds, 0, 0, 8, 32);
+ CheckBounds("scaled.Clip.GetBounds", g.Clip.GetBounds(g), 0, 0, 8, 32);
+ g.Clip = new Region(new Rectangle(0, 0, 8, 8));
+ // ClipBounds isn't affected by a previous scaling
+ CheckBounds("rectangle.ClipBounds", g.ClipBounds, 0, 0, 8, 8);
+ // Clip.GetBounds isn't affected by a previous scaling
+ CheckBounds("rectangle.Clip.GetBounds", g.Clip.GetBounds(g), 0, 0, 8, 8);
+
+ g.ResetTransform();
+ CheckBounds("reseted.ClipBounds", g.ClipBounds, 0, 0, 16, 4);
+ CheckBounds("reseted.Clip.GetBounds", g.Clip.GetBounds(g), 0, 0, 16, 4);
+ }
+ }
+
+ [ConditionalFact(Helpers.GdiplusIsAvailable)]
+ public void ScaleTransform_X0()
+ {
+ using (var b = new BitmapAndGraphics(16, 16))
+ {
+ var g = b.Graphics;
+ Assert.Throws<ArgumentException>(() => g.ScaleTransform(0, 1));
+ }
+ }
+
+ [ConditionalFact(Helpers.GdiplusIsAvailable)]
+ public void ScaleTransform_Y0()
+ {
+ using (var b = new BitmapAndGraphics(16, 16))
+ {
+ var g = b.Graphics;
+ Assert.Throws<ArgumentException>(() => g.ScaleTransform(1, 0));
+ }
+ }
+
+ [ConditionalFact(Helpers.GdiplusIsAvailable)]
+ public void TranslateTransform_Order()
+ {
+ using (var b = new BitmapAndGraphics(16, 16))
+ {
+ var g = b.Graphics;
+ g.Transform = new Matrix(1, 2, 3, 4, 5, 6);
+ g.TranslateTransform(3, -3);
+ float[] elements = g.Transform.Elements;
+ Assert.Equal(1, elements[0]);
+ Assert.Equal(2, elements[1]);
+ Assert.Equal(3, elements[2]);
+ Assert.Equal(4, elements[3]);
+ Assert.Equal(-1, elements[4]);
+ Assert.Equal(0, elements[5]);
+
+ g.Transform = new Matrix(1, 2, 3, 4, 5, 6);
+ g.TranslateTransform(3, -3, MatrixOrder.Prepend);
+ elements = g.Transform.Elements;
+ Assert.Equal(1, elements[0]);
+ Assert.Equal(2, elements[1]);
+ Assert.Equal(3, elements[2]);
+ Assert.Equal(4, elements[3]);
+ Assert.Equal(-1, elements[4]);
+ Assert.Equal(0, elements[5]);
+
+ g.Transform = new Matrix(1, 2, 3, 4, 5, 6);
+ g.TranslateTransform(3, -3, MatrixOrder.Append);
+ elements = g.Transform.Elements;
+ Assert.Equal(1, elements[0]);
+ Assert.Equal(2, elements[1]);
+ Assert.Equal(3, elements[2]);
+ Assert.Equal(4, elements[3]);
+ Assert.Equal(8, elements[4]);
+ Assert.Equal(3, elements[5]);
+ }
+ }
+
+ static Point[] SmallCurve = new Point[3] { new Point(0, 0), new Point(15, 5), new Point(5, 15) };
+ static PointF[] SmallCurveF = new PointF[3] { new PointF(0, 0), new PointF(15, 5), new PointF(5, 15) };
+
+ static Point[] TooSmallCurve = new Point[2] { new Point(0, 0), new Point(15, 5) };
+ static PointF[] LargeCurveF = new PointF[4] { new PointF(0, 0), new PointF(15, 5), new PointF(5, 15), new PointF(0, 20) };
+
+ [ConditionalFact(Helpers.GdiplusIsAvailable)]
+ public void DrawCurve_NotEnoughPoints()
+ {
+ using (Bitmap bitmap = new Bitmap(20, 20))
+ using (Graphics g = Graphics.FromImage(bitmap))
+ {
+ CheckForEmptyBitmap(bitmap);
+ g.DrawCurve(Pens.Black, TooSmallCurve, 0.5f);
+ CheckForNonEmptyBitmap(bitmap);
+ // so a "curve" can be drawn with less than 3 points!
+ // actually I used to call that a line... (and it's not related to tension)
+ g.Dispose();
+ bitmap.Dispose();
+ }
+ }
+
+ [ConditionalFact(Helpers.GdiplusIsAvailable)]
+ public void DrawCurve_SinglePoint()
+ {
+ using (Bitmap bitmap = new Bitmap(20, 20))
+ using (Graphics g = Graphics.FromImage(bitmap))
+ {
+ Assert.Throws<ArgumentException>(() => g.DrawCurve(Pens.Black, new Point[1] { new Point(10, 10) }, 0.5f));
+ // a single point isn't enough
+ }
+ }
+
+ [ConditionalFact(Helpers.GdiplusIsAvailable)]
+ public void DrawCurve3_NotEnoughPoints()
+ {
+ using (Bitmap bitmap = new Bitmap(20, 20))
+ using (Graphics g = Graphics.FromImage(bitmap))
+ {
+ Assert.Throws<ArgumentException>(() => g.DrawCurve(Pens.Black, TooSmallCurve, 0, 2, 0.5f));
+ // aha, this is API dependent
+ }
+ }
+
+ [ConditionalFact(Helpers.GdiplusIsAvailable)]
+ public void DrawCurve_NegativeTension()
+ {
+ using (Bitmap bitmap = new Bitmap(20, 20))
+ using (Graphics g = Graphics.FromImage(bitmap))
+ {
+ // documented as bigger (or equals) to 0
+ g.DrawCurve(Pens.Black, SmallCurveF, -0.9f);
+ CheckForNonEmptyBitmap(bitmap);
+ g.Dispose();
+ bitmap.Dispose();
+ }
+ }
+
+ [ConditionalFact(Helpers.GdiplusIsAvailable)]
+ public void DrawCurve_PositiveTension()
+ {
+ using (Bitmap bitmap = new Bitmap(20, 20))
+ using (Graphics g = Graphics.FromImage(bitmap))
+ {
+ g.DrawCurve(Pens.Black, SmallCurveF, 0.9f);
+ // this is not the same as -1
+ CheckForNonEmptyBitmap(bitmap);
+ g.Dispose();
+ bitmap.Dispose();
+ }
+ }
+
+ [ConditionalFact(Helpers.GdiplusIsAvailable)]
+ public void DrawCurve_ZeroSegments()
+ {
+ using (Bitmap bitmap = new Bitmap(20, 20))
+ using (Graphics g = Graphics.FromImage(bitmap))
+ {
+ Assert.Throws<ArgumentException>(() => g.DrawCurve(Pens.Black, SmallCurveF, 0, 0));
+ }
+ }
+
+ [ConditionalFact(Helpers.GdiplusIsAvailable)]
+ public void DrawCurve_NegativeSegments()
+ {
+ using (Bitmap bitmap = new Bitmap(20, 20))
+ using (Graphics g = Graphics.FromImage(bitmap))
+ {
+ Assert.Throws<ArgumentException>(() => g.DrawCurve(Pens.Black, SmallCurveF, 0, -1));
+ }
+ }
+
+ [ConditionalFact(Helpers.GdiplusIsAvailable)]
+ public void DrawCurve_OffsetTooLarge()
+ {
+ using (Bitmap bitmap = new Bitmap(20, 20))
+ using (Graphics g = Graphics.FromImage(bitmap))
+ {
+ // starting offset 1 doesn't give 3 points to make a curve
+ Assert.Throws<ArgumentException>(() => g.DrawCurve(Pens.Black, SmallCurveF, 1, 2));
+ // and in this case 2 points aren't enough to draw something
+ }
+ }
+
+ [ConditionalFact(Helpers.GdiplusIsAvailable)]
+ public void DrawCurve_Offset_0()
+ {
+ using (Bitmap bitmap = new Bitmap(20, 20))
+ using (Graphics g = Graphics.FromImage(bitmap))
+ {
+ g.DrawCurve(Pens.Black, LargeCurveF, 0, 2, 0.5f);
+ CheckForNonEmptyBitmap(bitmap);
+ g.Dispose();
+ bitmap.Dispose();
+ }
+ }
+
+ [ConditionalFact(Helpers.GdiplusIsAvailable)]
+ public void DrawCurve_Offset_1()
+ {
+ using (Bitmap bitmap = new Bitmap(20, 20))
+ using (Graphics g = Graphics.FromImage(bitmap))
+ {
+ g.DrawCurve(Pens.Black, LargeCurveF, 1, 2, 0.5f);
+ CheckForNonEmptyBitmap(bitmap);
+ g.Dispose();
+ bitmap.Dispose();
+ }
+ }
+
+ [ConditionalFact(Helpers.GdiplusIsAvailable)]
+ public void DrawCurve_Offset_2()
+ {
+ using (Bitmap bitmap = new Bitmap(20, 20))
+ using (Graphics g = Graphics.FromImage(bitmap))
+ {
+ // it works even with two points because we know the previous ones
+ g.DrawCurve(Pens.Black, LargeCurveF, 2, 1, 0.5f);
+ CheckForNonEmptyBitmap(bitmap);
+ g.Dispose();
+ bitmap.Dispose();
+ }
+ }
+
+ [ConditionalFact(Helpers.GdiplusIsAvailable)]
+ public void DrawRectangle_Negative()
+ {
+ using (Bitmap bitmap = new Bitmap(20, 20))
+ using (Graphics g = Graphics.FromImage(bitmap))
+ using (Pen pen = new Pen(Color.Red))
+ {
+ g.DrawRectangle(pen, 5, 5, -10, -10);
+ g.DrawRectangle(pen, 0.0f, 0.0f, 5.0f, -10.0f);
+ g.DrawRectangle(pen, new Rectangle(15, 0, -10, 5));
+ CheckForEmptyBitmap(bitmap);
+ pen.Dispose();
+ g.Dispose();
+ bitmap.Dispose();
+ }
+ }
+
+ [ConditionalFact(Helpers.GdiplusIsAvailable)]
+ public void DrawRectangles_Negative()
+ {
+ using (Bitmap bitmap = new Bitmap(20, 20))
+ using (Graphics g = Graphics.FromImage(bitmap))
+ using (Pen pen = new Pen(Color.Red))
+ {
+ Rectangle[] rects = new Rectangle[2]
+ {
+ new Rectangle (5, 5, -10, -10),
+ new Rectangle (0, 0, 5, -10)
+ };
+ RectangleF[] rectf = new RectangleF[2]
+ {
+ new RectangleF (0.0f, 5.0f, -10.0f, -10.0f),
+ new RectangleF (15.0f, 0.0f, -10.0f, 5.0f)
+ };
+ g.DrawRectangles(pen, rects);
+ g.DrawRectangles(pen, rectf);
+ CheckForEmptyBitmap(bitmap);
+ pen.Dispose();
+ g.Dispose();
+ bitmap.Dispose();
+ }
+ }
+
+ [ConditionalFact(Helpers.GdiplusIsAvailable)]
+ public void FillRectangle_Negative()
+ {
+ using (Bitmap bitmap = new Bitmap(20, 20))
+ using (Graphics g = Graphics.FromImage(bitmap))
+ using (SolidBrush brush = new SolidBrush(Color.Red))
+ {
+ g.FillRectangle(brush, 5, 5, -10, -10);
+ g.FillRectangle(brush, 0.0f, 0.0f, 5.0f, -10.0f);
+ g.FillRectangle(brush, new Rectangle(15, 0, -10, 5));
+ CheckForEmptyBitmap(bitmap);
+ brush.Dispose();
+ g.Dispose();
+ bitmap.Dispose();
+ }
+ }
+
+ [ConditionalFact(Helpers.GdiplusIsAvailable)]
+ public void FillRectangles_Negative()
+ {
+ using (Bitmap bitmap = new Bitmap(20, 20))
+ using (Graphics g = Graphics.FromImage(bitmap))
+ using (SolidBrush brush = new SolidBrush(Color.Red))
+ {
+ Rectangle[] rects = new Rectangle[2]
+ {
+ new Rectangle (5, 5, -10, -10),
+ new Rectangle (0, 0, 5, -10)
+ };
+
+ RectangleF[] rectf = new RectangleF[2]
+ {
+ new RectangleF (0.0f, 5.0f, -10.0f, -10.0f),
+ new RectangleF (15.0f, 0.0f, -10.0f, 5.0f)
+ };
+
+ g.FillRectangles(brush, rects);
+ g.FillRectangles(brush, rectf);
+ CheckForEmptyBitmap(bitmap);
+ brush.Dispose();
+ g.Dispose();
+ bitmap.Dispose();
+ }
+ }
+
+ private void CheckDefaultProperties(string message, Graphics g)
+ {
+ Assert.True(g.Clip.IsInfinite(g), message + ".Clip.IsInfinite");
+ AssertEquals(message + ".CompositingMode", CompositingMode.SourceOver, g.CompositingMode);
+ AssertEquals(message + ".CompositingQuality", CompositingQuality.Default, g.CompositingQuality);
+ AssertEquals(message + ".InterpolationMode", InterpolationMode.Bilinear, g.InterpolationMode);
+ AssertEquals(message + ".PageScale", 1.0f, g.PageScale);
+ AssertEquals(message + ".PageUnit", GraphicsUnit.Display, g.PageUnit);
+ AssertEquals(message + ".PixelOffsetMode", PixelOffsetMode.Default, g.PixelOffsetMode);
+ AssertEquals(message + ".SmoothingMode", SmoothingMode.None, g.SmoothingMode);
+ AssertEquals(message + ".TextContrast", 4, g.TextContrast);
+ AssertEquals(message + ".TextRenderingHint", TextRenderingHint.SystemDefault, g.TextRenderingHint);
+ Assert.True(g.Transform.IsIdentity, message + ".Transform.IsIdentity");
+ }
+
+ private void CheckCustomProperties(string message, Graphics g)
+ {
+ Assert.False(g.Clip.IsInfinite(g), message + ".Clip.IsInfinite");
+ AssertEquals(message + ".CompositingMode", CompositingMode.SourceCopy, g.CompositingMode);
+ AssertEquals(message + ".CompositingQuality", CompositingQuality.HighQuality, g.CompositingQuality);
+ AssertEquals(message + ".InterpolationMode", InterpolationMode.HighQualityBicubic, g.InterpolationMode);
+ AssertEquals(message + ".PageScale", 0.5f, g.PageScale);
+ AssertEquals(message + ".PageUnit", GraphicsUnit.Inch, g.PageUnit);
+ AssertEquals(message + ".PixelOffsetMode", PixelOffsetMode.Half, g.PixelOffsetMode);
+ AssertEquals(message + ".RenderingOrigin", new Point(-1, -1), g.RenderingOrigin);
+ AssertEquals(message + ".SmoothingMode", SmoothingMode.AntiAlias, g.SmoothingMode);
+ AssertEquals(message + ".TextContrast", 0, g.TextContrast);
+ AssertEquals(message + ".TextRenderingHint", TextRenderingHint.AntiAlias, g.TextRenderingHint);
+ Assert.False(g.Transform.IsIdentity, message + ".Transform.IsIdentity");
+ }
+
+ private void CheckMatrix(string message, Matrix m, float xx, float yx, float xy, float yy, float x0, float y0)
+ {
+ float[] elements = m.Elements;
+ AssertEquals(message + ".Matrix.xx", xx, elements[0], 2);
+ AssertEquals(message + ".Matrix.yx", yx, elements[1], 2);
+ AssertEquals(message + ".Matrix.xy", xy, elements[2], 2);
+ AssertEquals(message + ".Matrix.yy", yy, elements[3], 2);
+ AssertEquals(message + ".Matrix.x0", x0, elements[4], 2);
+ AssertEquals(message + ".Matrix.y0", y0, elements[5], 2);
+ }
+
+ [ConditionalFact(Helpers.GdiplusIsAvailable)]
+ public void BeginContainer()
+ {
+ using (Bitmap bitmap = new Bitmap(20, 20))
+ using (Graphics g = Graphics.FromImage(bitmap))
+ {
+
+ CheckDefaultProperties("default", g);
+ Assert.Equal(new Point(0, 0), g.RenderingOrigin);
+
+ g.Clip = new Region(new Rectangle(10, 10, 10, 10));
+ g.CompositingMode = CompositingMode.SourceCopy;
+ g.CompositingQuality = CompositingQuality.HighQuality;
+ g.InterpolationMode = InterpolationMode.HighQualityBicubic;
+ g.PageScale = 0.5f;
+ g.PageUnit = GraphicsUnit.Inch;
+ g.PixelOffsetMode = PixelOffsetMode.Half;
+ g.RenderingOrigin = new Point(-1, -1);
+ g.RotateTransform(45);
+ g.SmoothingMode = SmoothingMode.AntiAlias;
+ g.TextContrast = 0;
+ g.TextRenderingHint = TextRenderingHint.AntiAlias;
+ CheckCustomProperties("modified", g);
+ CheckMatrix("modified.Transform", g.Transform, 0.707f, 0.707f, -0.707f, 0.707f, 0, 0);
+
+ GraphicsContainer gc = g.BeginContainer();
+ // things gets reseted after calling BeginContainer
+ CheckDefaultProperties("BeginContainer", g);
+ // but not everything
+ Assert.Equal(new Point(-1, -1), g.RenderingOrigin);
+
+ g.EndContainer(gc);
+ CheckCustomProperties("EndContainer", g);
+ }
+ }
+
+ [ConditionalFact(Helpers.GdiplusIsAvailable)]
+ public void BeginContainer_Rect()
+ {
+ using (Bitmap bitmap = new Bitmap(20, 20))
+ using (Graphics g = Graphics.FromImage(bitmap))
+ {
+ CheckDefaultProperties("default", g);
+ Assert.Equal(new Point(0, 0), g.RenderingOrigin);
+
+ g.Clip = new Region(new Rectangle(10, 10, 10, 10));
+ g.CompositingMode = CompositingMode.SourceCopy;
+ g.CompositingQuality = CompositingQuality.HighQuality;
+ g.InterpolationMode = InterpolationMode.HighQualityBicubic;
+ g.PageScale = 0.5f;
+ g.PageUnit = GraphicsUnit.Inch;
+ g.PixelOffsetMode = PixelOffsetMode.Half;
+ g.RenderingOrigin = new Point(-1, -1);
+ g.RotateTransform(45);
+ g.SmoothingMode = SmoothingMode.AntiAlias;
+ g.TextContrast = 0;
+ g.TextRenderingHint = TextRenderingHint.AntiAlias;
+ CheckCustomProperties("modified", g);
+ CheckMatrix("modified.Transform", g.Transform, 0.707f, 0.707f, -0.707f, 0.707f, 0, 0);
+
+ GraphicsContainer gc = g.BeginContainer(new Rectangle(10, 20, 30, 40), new Rectangle(10, 20, 300, 400), GraphicsUnit.Millimeter);
+ // things gets reseted after calling BeginContainer
+ CheckDefaultProperties("BeginContainer", g);
+ // but not everything
+ Assert.Equal(new Point(-1, -1), g.RenderingOrigin);
+
+ g.EndContainer(gc);
+ CheckCustomProperties("EndContainer", g);
+ CheckMatrix("EndContainer.Transform", g.Transform, 0.707f, 0.707f, -0.707f, 0.707f, 0, 0);
+ }
+ }
+
+ [ConditionalFact(Helpers.GdiplusIsAvailable)]
+ public void BeginContainer_RectF()
+ {
+ using (Bitmap bitmap = new Bitmap(20, 20))
+ using (Graphics g = Graphics.FromImage(bitmap))
+ {
+ CheckDefaultProperties("default", g);
+ Assert.Equal(new Point(0, 0), g.RenderingOrigin);
+
+ g.Clip = new Region(new Rectangle(10, 10, 10, 10));
+ g.CompositingMode = CompositingMode.SourceCopy;
+ g.CompositingQuality = CompositingQuality.HighQuality;
+ g.InterpolationMode = InterpolationMode.HighQualityBicubic;
+ g.PageScale = 0.5f;
+ g.PageUnit = GraphicsUnit.Inch;
+ g.PixelOffsetMode = PixelOffsetMode.Half;
+ g.RenderingOrigin = new Point(-1, -1);
+ g.RotateTransform(45);
+ g.SmoothingMode = SmoothingMode.AntiAlias;
+ g.TextContrast = 0;
+ g.TextRenderingHint = TextRenderingHint.AntiAlias;
+ CheckCustomProperties("modified", g);
+ CheckMatrix("modified.Transform", g.Transform, 0.707f, 0.707f, -0.707f, 0.707f, 0, 0);
+
+ GraphicsContainer gc = g.BeginContainer(new RectangleF(40, 30, 20, 10), new RectangleF(10, 20, 30, 40), GraphicsUnit.Inch);
+ // things gets reseted after calling BeginContainer
+ CheckDefaultProperties("BeginContainer", g);
+ // but not everything
+ Assert.Equal(new Point(-1, -1), g.RenderingOrigin);
+
+ g.EndContainer(gc);
+ CheckCustomProperties("EndContainer", g);
+ }
+ }
+
+ private void BeginContainer_GraphicsUnit(GraphicsUnit unit)
+ {
+ using (Bitmap bitmap = new Bitmap(20, 20))
+ using (Graphics g = Graphics.FromImage(bitmap))
+ {
+ g.BeginContainer(new RectangleF(40, 30, 20, 10), new RectangleF(10, 20, 30, 40), unit);
+ }
+ }
+
+ [ConditionalFact(Helpers.GdiplusIsAvailable)]
+ public void BeginContainer_GraphicsUnit_Display()
+ {
+ Assert.Throws<ArgumentException>(() => BeginContainer_GraphicsUnit(GraphicsUnit.Display));
+ }
+
+ [ConditionalFact(Helpers.GdiplusIsAvailable)]
+ public void BeginContainer_GraphicsUnit_Valid()
+ {
+ BeginContainer_GraphicsUnit(GraphicsUnit.Document);
+ BeginContainer_GraphicsUnit(GraphicsUnit.Inch);
+ BeginContainer_GraphicsUnit(GraphicsUnit.Millimeter);
+ BeginContainer_GraphicsUnit(GraphicsUnit.Pixel);
+ BeginContainer_GraphicsUnit(GraphicsUnit.Point);
+ }
+
+ [ConditionalFact(Helpers.GdiplusIsAvailable)]
+ public void BeginContainer_GraphicsUnit_World()
+ {
+ Assert.Throws<ArgumentException>(() => BeginContainer_GraphicsUnit(GraphicsUnit.World));
+ }
+
+ [ConditionalFact(Helpers.GdiplusIsAvailable)]
+ public void BeginContainer_GraphicsUnit_Bad()
+ {
+ Assert.Throws<ArgumentException>(() => BeginContainer_GraphicsUnit((GraphicsUnit)Int32.MinValue));
+ }
+
+ [ConditionalFact(Helpers.GdiplusIsAvailable)]
+ public void EndContainer_Null()
+ {
+ using (Bitmap bitmap = new Bitmap(20, 20))
+ using (Graphics g = Graphics.FromImage(bitmap))
+ {
+ Assert.Throws<ArgumentNullException>(() => g.EndContainer(null));
+ }
+ }
+
+ [ConditionalFact(Helpers.GdiplusIsAvailable)]
+ public void Save()
+ {
+ using (Bitmap bitmap = new Bitmap(20, 20))
+ using (Graphics g = Graphics.FromImage(bitmap))
+ {
+ CheckDefaultProperties("default", g);
+ Assert.Equal(new Point(0, 0), g.RenderingOrigin);
+
+ GraphicsState gs1 = g.Save();
+ // nothing is changed after a save
+ CheckDefaultProperties("save1", g);
+ Assert.Equal(new Point(0, 0), g.RenderingOrigin);
+
+ g.Clip = new Region(new Rectangle(10, 10, 10, 10));
+ g.CompositingMode = CompositingMode.SourceCopy;
+ g.CompositingQuality = CompositingQuality.HighQuality;
+ g.InterpolationMode = InterpolationMode.HighQualityBicubic;
+ g.PageScale = 0.5f;
+ g.PageUnit = GraphicsUnit.Inch;
+ g.PixelOffsetMode = PixelOffsetMode.Half;
+ g.RenderingOrigin = new Point(-1, -1);
+ g.RotateTransform(45);
+ g.SmoothingMode = SmoothingMode.AntiAlias;
+ g.TextContrast = 0;
+ g.TextRenderingHint = TextRenderingHint.AntiAlias;
+ CheckCustomProperties("modified", g);
+ CheckMatrix("modified.Transform", g.Transform, 0.707f, 0.707f, -0.707f, 0.707f, 0, 0);
+
+ GraphicsState gs2 = g.Save();
+ CheckCustomProperties("save2", g);
+
+ g.Restore(gs2);
+ CheckCustomProperties("restored1", g);
+ CheckMatrix("restored1.Transform", g.Transform, 0.707f, 0.707f, -0.707f, 0.707f, 0, 0);
+
+ g.Restore(gs1);
+ CheckDefaultProperties("restored2", g);
+ Assert.Equal(new Point(0, 0), g.RenderingOrigin);
+ }
+ }
+
+ [ConditionalFact(Helpers.GdiplusIsAvailable)]
+ public void Restore_Null()
+ {
+ using (Bitmap bitmap = new Bitmap(20, 20))
+ using (Graphics g = Graphics.FromImage(bitmap))
+ {
+ Assert.Throws<NullReferenceException>(() => g.Restore(null));
+ }
+ }
+
+ [ConditionalFact(Helpers.GdiplusIsAvailable)]
+ public void FillRectangles_BrushNull_Rectangle()
+ {
+ using (Bitmap bitmap = new Bitmap(20, 20))
+ using (Graphics g = Graphics.FromImage(bitmap))
+ {
+ Assert.Throws<ArgumentNullException>(() => g.FillRectangles(null, new Rectangle[1]));
+ }
+ }
+
+ [ConditionalFact(Helpers.GdiplusIsAvailable)]
+ public void FillRectangles_Rectangle_Null()
+ {
+ using (Bitmap bitmap = new Bitmap(20, 20))
+ using (Graphics g = Graphics.FromImage(bitmap))
+ {
+ Assert.Throws<ArgumentNullException>(() => g.FillRectangles(Brushes.Red, (Rectangle[])null));
+ }
+ }
+
+ [ConditionalFact(Helpers.GdiplusIsAvailable)]
+ public void FillRectanglesZeroRectangle()
+ {
+ using (Bitmap bitmap = new Bitmap(20, 20))
+ using (Graphics g = Graphics.FromImage(bitmap))
+ {
+ Assert.Throws<ArgumentException>(() => g.FillRectangles(Brushes.Red, new Rectangle[0]));
+ }
+ }
+
+ [ConditionalFact(Helpers.GdiplusIsAvailable)]
+ public void FillRectangles_BrushNull_RectangleF()
+ {
+ using (Bitmap bitmap = new Bitmap(20, 20))
+ using (Graphics g = Graphics.FromImage(bitmap))
+ {
+ Assert.Throws<ArgumentNullException>(() => g.FillRectangles(null, new RectangleF[1]));
+ }
+ }
+
+ [ConditionalFact(Helpers.GdiplusIsAvailable)]
+ public void FillRectangles_RectangleF_Null()
+ {
+ using (Bitmap bitmap = new Bitmap(20, 20))
+ using (Graphics g = Graphics.FromImage(bitmap))
+ {
+ Assert.Throws<ArgumentNullException>(() => g.FillRectangles(Brushes.Red, (RectangleF[])null));
+ }
+ }
+
+ [ConditionalFact(Helpers.GdiplusIsAvailable)]
+ public void FillRectanglesZeroRectangleF()
+ {
+ using (Bitmap bitmap = new Bitmap(20, 20))
+ using (Graphics g = Graphics.FromImage(bitmap))
+ {
+ Assert.Throws<ArgumentException>(() => g.FillRectangles(Brushes.Red, new RectangleF[0]));
+ }
+ }
+
+ [ConditionalFact(Helpers.GdiplusIsAvailable)]
+ public void FillRectangles_NormalBehavior()
+ {
+ using (Bitmap bitmap = new Bitmap(20, 20))
+ {
+ using (Graphics g = Graphics.FromImage(bitmap))
+ {
+ g.Clear(Color.Fuchsia);
+ Rectangle rect = new Rectangle(5, 5, 10, 10);
+ g.Clip = new Region(rect);
+ g.FillRectangle(Brushes.Red, rect);
+ }
+ Assert.Equal(Color.Red.ToArgb(), bitmap.GetPixel(5, 5).ToArgb());
+ Assert.Equal(Color.Red.ToArgb(), bitmap.GetPixel(14, 5).ToArgb());
+ Assert.Equal(Color.Red.ToArgb(), bitmap.GetPixel(5, 14).ToArgb());
+ Assert.Equal(Color.Red.ToArgb(), bitmap.GetPixel(14, 14).ToArgb());
+
+ Assert.Equal(Color.Fuchsia.ToArgb(), bitmap.GetPixel(15, 5).ToArgb());
+ Assert.Equal(Color.Fuchsia.ToArgb(), bitmap.GetPixel(5, 15).ToArgb());
+ Assert.Equal(Color.Fuchsia.ToArgb(), bitmap.GetPixel(15, 15).ToArgb());
+ }
+ }
+
+ private Bitmap FillDrawRectangle(float width)
+ {
+ Bitmap bitmap = new Bitmap(20, 20);
+ using (Graphics g = Graphics.FromImage(bitmap))
+ {
+ g.Clear(Color.Red);
+ Rectangle rect = new Rectangle(5, 5, 10, 10);
+ g.FillRectangle(Brushes.Green, rect);
+ if (width >= 0)
+ {
+ using (Pen pen = new Pen(Color.Blue, width))
+ {
+ g.DrawRectangle(pen, rect);
+ }
+ }
+ else
+ {
+ g.DrawRectangle(Pens.Blue, rect);
+ }
+ }
+ return bitmap;
+ }
+
+ [ConditionalFact(Helpers.GdiplusIsAvailable)]
+ public void FillDrawRectangle_Width_Default()
+ {
+ // default pen size
+ using (Bitmap bitmap = FillDrawRectangle(Single.MinValue))
+ {
+ // NW
+ Assert.Equal(0xFFFF0000, (uint)bitmap.GetPixel(4, 4).ToArgb());
+ Assert.Equal(0xFF0000FF, (uint)bitmap.GetPixel(5, 5).ToArgb());
+ Assert.Equal(0xFF008000, (uint)bitmap.GetPixel(6, 6).ToArgb());
+ // N
+ Assert.Equal(0xFFFF0000, (uint)bitmap.GetPixel(9, 4).ToArgb());
+ Assert.Equal(0xFF0000FF, (uint)bitmap.GetPixel(9, 5).ToArgb());
+ Assert.Equal(0xFF008000, (uint)bitmap.GetPixel(9, 6).ToArgb());
+ // NE
+ Assert.Equal(0xFFFF0000, (uint)bitmap.GetPixel(16, 4).ToArgb());
+ Assert.Equal(0xFF0000FF, (uint)bitmap.GetPixel(15, 5).ToArgb());
+ Assert.Equal(0xFF008000, (uint)bitmap.GetPixel(14, 6).ToArgb());
+ // E
+ Assert.Equal(0xFFFF0000, (uint)bitmap.GetPixel(16, 9).ToArgb());
+ Assert.Equal(0xFF0000FF, (uint)bitmap.GetPixel(15, 9).ToArgb());
+ Assert.Equal(0xFF008000, (uint)bitmap.GetPixel(14, 9).ToArgb());
+ // SE
+ Assert.Equal(0xFFFF0000, (uint)bitmap.GetPixel(16, 16).ToArgb());
+ Assert.Equal(0xFF0000FF, (uint)bitmap.GetPixel(15, 15).ToArgb());
+ Assert.Equal(0xFF008000, (uint)bitmap.GetPixel(14, 14).ToArgb());
+ // S
+ Assert.Equal(0xFFFF0000, (uint)bitmap.GetPixel(9, 16).ToArgb());
+ Assert.Equal(0xFF0000FF, (uint)bitmap.GetPixel(9, 15).ToArgb());
+ Assert.Equal(0xFF008000, (uint)bitmap.GetPixel(9, 14).ToArgb());
+ // SW
+ Assert.Equal(0xFFFF0000, (uint)bitmap.GetPixel(4, 16).ToArgb());
+ Assert.Equal(0xFF0000FF, (uint)bitmap.GetPixel(5, 15).ToArgb());
+ Assert.Equal(0xFF008000, (uint)bitmap.GetPixel(6, 14).ToArgb());
+ // W
+ Assert.Equal(0xFFFF0000, (uint)bitmap.GetPixel(4, 9).ToArgb());
+ Assert.Equal(0xFF0000FF, (uint)bitmap.GetPixel(5, 9).ToArgb());
+ Assert.Equal(0xFF008000, (uint)bitmap.GetPixel(6, 9).ToArgb());
+ }
+ }
+
+ [ConditionalFact(Helpers.RecentGdiplusIsAvailable)]
+ public void FillDrawRectangle_Width_2()
+ {
+ // even pen size
+ using (Bitmap bitmap = FillDrawRectangle(2.0f))
+ {
+ // NW
+ Assert.Equal(0xFFFF0000, (uint)bitmap.GetPixel(3, 3).ToArgb());
+ Assert.Equal(0xFF0000FF, (uint)bitmap.GetPixel(4, 4).ToArgb());
+ Assert.Equal(0xFF0000FF, (uint)bitmap.GetPixel(5, 5).ToArgb());
+ Assert.Equal(0xFF008000, (uint)bitmap.GetPixel(6, 6).ToArgb());
+ // N
+ Assert.Equal(0xFFFF0000, (uint)bitmap.GetPixel(9, 3).ToArgb());
+ Assert.Equal(0xFF0000FF, (uint)bitmap.GetPixel(9, 4).ToArgb());
+ Assert.Equal(0xFF0000FF, (uint)bitmap.GetPixel(9, 5).ToArgb());
+ Assert.Equal(0xFF008000, (uint)bitmap.GetPixel(9, 6).ToArgb());
+ // NE
+ Assert.Equal(0xFFFF0000, (uint)bitmap.GetPixel(16, 3).ToArgb());
+ Assert.Equal(0xFF0000FF, (uint)bitmap.GetPixel(15, 4).ToArgb());
+ Assert.Equal(0xFF0000FF, (uint)bitmap.GetPixel(14, 5).ToArgb());
+ Assert.Equal(0xFF008000, (uint)bitmap.GetPixel(13, 6).ToArgb());
+ // E
+ Assert.Equal(0xFFFF0000, (uint)bitmap.GetPixel(16, 9).ToArgb());
+ Assert.Equal(0xFF0000FF, (uint)bitmap.GetPixel(15, 9).ToArgb());
+ Assert.Equal(0xFF0000FF, (uint)bitmap.GetPixel(14, 9).ToArgb());
+ Assert.Equal(0xFF008000, (uint)bitmap.GetPixel(13, 9).ToArgb());
+ // SE
+ Assert.Equal(0xFFFF0000, (uint)bitmap.GetPixel(16, 16).ToArgb());
+ Assert.Equal(0xFF0000FF, (uint)bitmap.GetPixel(15, 15).ToArgb());
+ Assert.Equal(0xFF0000FF, (uint)bitmap.GetPixel(14, 14).ToArgb());
+ Assert.Equal(0xFF008000, (uint)bitmap.GetPixel(13, 13).ToArgb());
+ // S
+ Assert.Equal(0xFFFF0000, (uint)bitmap.GetPixel(9, 16).ToArgb());
+ Assert.Equal(0xFF0000FF, (uint)bitmap.GetPixel(9, 15).ToArgb());
+ Assert.Equal(0xFF0000FF, (uint)bitmap.GetPixel(9, 14).ToArgb());
+ Assert.Equal(0xFF008000, (uint)bitmap.GetPixel(9, 13).ToArgb());
+ // SW
+ Assert.Equal(0xFFFF0000, (uint)bitmap.GetPixel(3, 16).ToArgb());
+ Assert.Equal(0xFF0000FF, (uint)bitmap.GetPixel(4, 15).ToArgb());
+ Assert.Equal(0xFF0000FF, (uint)bitmap.GetPixel(5, 14).ToArgb());
+ Assert.Equal(0xFF008000, (uint)bitmap.GetPixel(6, 13).ToArgb());
+ // W
+ Assert.Equal(0xFFFF0000, (uint)bitmap.GetPixel(3, 9).ToArgb());
+ Assert.Equal(0xFF0000FF, (uint)bitmap.GetPixel(4, 9).ToArgb());
+ Assert.Equal(0xFF0000FF, (uint)bitmap.GetPixel(5, 9).ToArgb());
+ Assert.Equal(0xFF008000, (uint)bitmap.GetPixel(6, 9).ToArgb());
+ }
+ }
+
+ [ConditionalFact(Helpers.GdiplusIsAvailable)]
+ public void FillDrawRectangle_Width_3()
+ {
+ // odd pen size
+ using (Bitmap bitmap = FillDrawRectangle(3.0f))
+ {
+ // NW
+ Assert.Equal(0xFFFF0000, (uint)bitmap.GetPixel(3, 3).ToArgb());
+ Assert.Equal(0xFF0000FF, (uint)bitmap.GetPixel(4, 4).ToArgb());
+ Assert.Equal(0xFF0000FF, (uint)bitmap.GetPixel(5, 5).ToArgb());
+ Assert.Equal(0xFF0000FF, (uint)bitmap.GetPixel(6, 6).ToArgb());
+ Assert.Equal(0xFF008000, (uint)bitmap.GetPixel(7, 7).ToArgb());
+ // N
+ Assert.Equal(0xFFFF0000, (uint)bitmap.GetPixel(9, 3).ToArgb());
+ Assert.Equal(0xFF0000FF, (uint)bitmap.GetPixel(9, 4).ToArgb());
+ Assert.Equal(0xFF0000FF, (uint)bitmap.GetPixel(9, 5).ToArgb());
+ Assert.Equal(0xFF0000FF, (uint)bitmap.GetPixel(9, 6).ToArgb());
+ Assert.Equal(0xFF008000, (uint)bitmap.GetPixel(9, 7).ToArgb());
+ // NE
+ Assert.Equal(0xFFFF0000, (uint)bitmap.GetPixel(17, 3).ToArgb());
+ Assert.Equal(0xFF0000FF, (uint)bitmap.GetPixel(16, 4).ToArgb());
+ Assert.Equal(0xFF0000FF, (uint)bitmap.GetPixel(15, 5).ToArgb());
+ Assert.Equal(0xFF0000FF, (uint)bitmap.GetPixel(14, 6).ToArgb());
+ Assert.Equal(0xFF008000, (uint)bitmap.GetPixel(13, 7).ToArgb());
+ // E
+ Assert.Equal(0xFFFF0000, (uint)bitmap.GetPixel(17, 9).ToArgb());
+ Assert.Equal(0xFF0000FF, (uint)bitmap.GetPixel(16, 9).ToArgb());
+ Assert.Equal(0xFF0000FF, (uint)bitmap.GetPixel(15, 9).ToArgb());
+ Assert.Equal(0xFF0000FF, (uint)bitmap.GetPixel(14, 9).ToArgb());
+ Assert.Equal(0xFF008000, (uint)bitmap.GetPixel(13, 9).ToArgb());
+ // SE
+ Assert.Equal(0xFFFF0000, (uint)bitmap.GetPixel(17, 17).ToArgb());
+ Assert.Equal(0xFF0000FF, (uint)bitmap.GetPixel(16, 16).ToArgb());
+ Assert.Equal(0xFF0000FF, (uint)bitmap.GetPixel(15, 15).ToArgb());
+ Assert.Equal(0xFF0000FF, (uint)bitmap.GetPixel(14, 14).ToArgb());
+ Assert.Equal(0xFF008000, (uint)bitmap.GetPixel(13, 13).ToArgb());
+ // S
+ Assert.Equal(0xFFFF0000, (uint)bitmap.GetPixel(9, 17).ToArgb());
+ Assert.Equal(0xFF0000FF, (uint)bitmap.GetPixel(9, 16).ToArgb());
+ Assert.Equal(0xFF0000FF, (uint)bitmap.GetPixel(9, 15).ToArgb());
+ Assert.Equal(0xFF0000FF, (uint)bitmap.GetPixel(9, 14).ToArgb());
+ Assert.Equal(0xFF008000, (uint)bitmap.GetPixel(9, 13).ToArgb());
+ // SW
+ Assert.Equal(0xFFFF0000, (uint)bitmap.GetPixel(3, 17).ToArgb());
+ Assert.Equal(0xFF0000FF, (uint)bitmap.GetPixel(4, 16).ToArgb());
+ Assert.Equal(0xFF0000FF, (uint)bitmap.GetPixel(5, 15).ToArgb());
+ Assert.Equal(0xFF0000FF, (uint)bitmap.GetPixel(6, 14).ToArgb());
+ Assert.Equal(0xFF008000, (uint)bitmap.GetPixel(7, 13).ToArgb());
+ // W
+ Assert.Equal(0xFFFF0000, (uint)bitmap.GetPixel(3, 9).ToArgb());
+ Assert.Equal(0xFF0000FF, (uint)bitmap.GetPixel(4, 9).ToArgb());
+ Assert.Equal(0xFF0000FF, (uint)bitmap.GetPixel(5, 9).ToArgb());
+ Assert.Equal(0xFF0000FF, (uint)bitmap.GetPixel(6, 9).ToArgb());
+ Assert.Equal(0xFF008000, (uint)bitmap.GetPixel(7, 9).ToArgb());
+ }
+ }
+
+ // reverse, draw the fill over
+ private Bitmap DrawFillRectangle(float width)
+ {
+ Bitmap bitmap = new Bitmap(20, 20);
+ using (Graphics g = Graphics.FromImage(bitmap))
+ {
+ g.Clear(Color.Red);
+ Rectangle rect = new Rectangle(5, 5, 10, 10);
+ if (width >= 0)
+ {
+ using (Pen pen = new Pen(Color.Blue, width))
+ {
+ g.DrawRectangle(pen, rect);
+ }
+ }
+ else
+ {
+ g.DrawRectangle(Pens.Blue, rect);
+ }
+ g.FillRectangle(Brushes.Green, rect);
+ }
+ return bitmap;
+ }
+
+ [ConditionalFact(Helpers.GdiplusIsAvailable)]
+ public void DrawFillRectangle_Width_Default()
+ {
+ // default pen size
+ using (Bitmap bitmap = DrawFillRectangle(Single.MinValue))
+ {
+ // NW - no blue border
+ Assert.Equal(0xFFFF0000, (uint)bitmap.GetPixel(4, 4).ToArgb());
+ Assert.Equal(0xFF008000, (uint)bitmap.GetPixel(5, 5).ToArgb());
+ Assert.Equal(0xFF008000, (uint)bitmap.GetPixel(6, 6).ToArgb());
+ // N - no blue border
+ Assert.Equal(0xFFFF0000, (uint)bitmap.GetPixel(9, 4).ToArgb());
+ Assert.Equal(0xFF008000, (uint)bitmap.GetPixel(9, 5).ToArgb());
+ Assert.Equal(0xFF008000, (uint)bitmap.GetPixel(9, 6).ToArgb());
+ // NE
+ Assert.Equal(0xFFFF0000, (uint)bitmap.GetPixel(16, 4).ToArgb());
+ Assert.Equal(0xFF0000FF, (uint)bitmap.GetPixel(15, 5).ToArgb());
+ Assert.Equal(0xFF008000, (uint)bitmap.GetPixel(14, 6).ToArgb());
+ // E
+ Assert.Equal(0xFFFF0000, (uint)bitmap.GetPixel(16, 9).ToArgb());
+ Assert.Equal(0xFF0000FF, (uint)bitmap.GetPixel(15, 9).ToArgb());
+ Assert.Equal(0xFF008000, (uint)bitmap.GetPixel(14, 9).ToArgb());
+ // SE
+ Assert.Equal(0xFFFF0000, (uint)bitmap.GetPixel(16, 16).ToArgb());
+ Assert.Equal(0xFF0000FF, (uint)bitmap.GetPixel(15, 15).ToArgb());
+ Assert.Equal(0xFF008000, (uint)bitmap.GetPixel(14, 14).ToArgb());
+ // S
+ Assert.Equal(0xFFFF0000, (uint)bitmap.GetPixel(9, 16).ToArgb());
+ Assert.Equal(0xFF0000FF, (uint)bitmap.GetPixel(9, 15).ToArgb());
+ Assert.Equal(0xFF008000, (uint)bitmap.GetPixel(9, 14).ToArgb());
+ // SW
+ Assert.Equal(0xFFFF0000, (uint)bitmap.GetPixel(4, 16).ToArgb());
+ Assert.Equal(0xFF0000FF, (uint)bitmap.GetPixel(5, 15).ToArgb());
+ Assert.Equal(0xFF008000, (uint)bitmap.GetPixel(6, 14).ToArgb());
+ // W - no blue border
+ Assert.Equal(0xFFFF0000, (uint)bitmap.GetPixel(4, 9).ToArgb());
+ Assert.Equal(0xFF008000, (uint)bitmap.GetPixel(5, 9).ToArgb());
+ Assert.Equal(0xFF008000, (uint)bitmap.GetPixel(6, 9).ToArgb());
+ }
+ }
+
+ [ConditionalFact(Helpers.RecentGdiplusIsAvailable)]
+ public void DrawFillRectangle_Width_2()
+ {
+ // even pen size
+ using (Bitmap bitmap = DrawFillRectangle(2.0f))
+ {
+ // looks like a one pixel border - but enlarged
+ // NW
+ Assert.Equal(0xFFFF0000, (uint)bitmap.GetPixel(3, 3).ToArgb());
+ Assert.Equal(0xFF0000FF, (uint)bitmap.GetPixel(4, 4).ToArgb());
+ Assert.Equal(0xFF008000, (uint)bitmap.GetPixel(5, 5).ToArgb());
+ // N
+ Assert.Equal(0xFFFF0000, (uint)bitmap.GetPixel(9, 3).ToArgb());
+ Assert.Equal(0xFF0000FF, (uint)bitmap.GetPixel(9, 4).ToArgb());
+ Assert.Equal(0xFF008000, (uint)bitmap.GetPixel(9, 5).ToArgb());
+ // NE
+ Assert.Equal(0xFFFF0000, (uint)bitmap.GetPixel(16, 3).ToArgb());
+ Assert.Equal(0xFF0000FF, (uint)bitmap.GetPixel(15, 4).ToArgb());
+ Assert.Equal(0xFF008000, (uint)bitmap.GetPixel(14, 5).ToArgb());
+ // E
+ Assert.Equal(0xFFFF0000, (uint)bitmap.GetPixel(16, 9).ToArgb());
+ Assert.Equal(0xFF0000FF, (uint)bitmap.GetPixel(15, 9).ToArgb());
+ Assert.Equal(0xFF008000, (uint)bitmap.GetPixel(14, 9).ToArgb());
+ // SE
+ Assert.Equal(0xFFFF0000, (uint)bitmap.GetPixel(16, 16).ToArgb());
+ Assert.Equal(0xFF0000FF, (uint)bitmap.GetPixel(15, 15).ToArgb());
+ Assert.Equal(0xFF008000, (uint)bitmap.GetPixel(14, 14).ToArgb());
+ // S
+ Assert.Equal(0xFFFF0000, (uint)bitmap.GetPixel(9, 16).ToArgb());
+ Assert.Equal(0xFF0000FF, (uint)bitmap.GetPixel(9, 15).ToArgb());
+ Assert.Equal(0xFF008000, (uint)bitmap.GetPixel(9, 14).ToArgb());
+ // SW
+ Assert.Equal(0xFFFF0000, (uint)bitmap.GetPixel(3, 16).ToArgb());
+ Assert.Equal(0xFF0000FF, (uint)bitmap.GetPixel(4, 15).ToArgb());
+ Assert.Equal(0xFF008000, (uint)bitmap.GetPixel(5, 14).ToArgb());
+ // W
+ Assert.Equal(0xFFFF0000, (uint)bitmap.GetPixel(3, 9).ToArgb());
+ Assert.Equal(0xFF0000FF, (uint)bitmap.GetPixel(4, 9).ToArgb());
+ Assert.Equal(0xFF008000, (uint)bitmap.GetPixel(5, 9).ToArgb());
+ }
+ }
+
+ [ConditionalFact(Helpers.GdiplusIsAvailable)]
+ public void DrawFillRectangle_Width_3()
+ {
+ // odd pen size
+ using (Bitmap bitmap = DrawFillRectangle(3.0f))
+ {
+ // NW
+ Assert.Equal(0xFFFF0000, (uint)bitmap.GetPixel(3, 3).ToArgb());
+ Assert.Equal(0xFF0000FF, (uint)bitmap.GetPixel(4, 4).ToArgb());
+ Assert.Equal(0xFF008000, (uint)bitmap.GetPixel(5, 5).ToArgb());
+ // N
+ Assert.Equal(0xFFFF0000, (uint)bitmap.GetPixel(9, 3).ToArgb());
+ Assert.Equal(0xFF0000FF, (uint)bitmap.GetPixel(9, 4).ToArgb());
+ Assert.Equal(0xFF008000, (uint)bitmap.GetPixel(9, 5).ToArgb());
+ // NE
+ Assert.Equal(0xFFFF0000, (uint)bitmap.GetPixel(17, 3).ToArgb());
+ Assert.Equal(0xFF0000FF, (uint)bitmap.GetPixel(16, 4).ToArgb());
+ Assert.Equal(0xFF0000FF, (uint)bitmap.GetPixel(15, 4).ToArgb());
+ Assert.Equal(0xFF008000, (uint)bitmap.GetPixel(14, 5).ToArgb());
+ // E
+ Assert.Equal(0xFFFF0000, (uint)bitmap.GetPixel(17, 9).ToArgb());
+ Assert.Equal(0xFF0000FF, (uint)bitmap.GetPixel(16, 9).ToArgb());
+ Assert.Equal(0xFF0000FF, (uint)bitmap.GetPixel(15, 9).ToArgb());
+ Assert.Equal(0xFF008000, (uint)bitmap.GetPixel(14, 9).ToArgb());
+ // SE
+ Assert.Equal(0xFFFF0000, (uint)bitmap.GetPixel(17, 17).ToArgb());
+ Assert.Equal(0xFF0000FF, (uint)bitmap.GetPixel(16, 16).ToArgb());
+ Assert.Equal(0xFF0000FF, (uint)bitmap.GetPixel(15, 15).ToArgb());
+ Assert.Equal(0xFF008000, (uint)bitmap.GetPixel(14, 14).ToArgb());
+ // S
+ Assert.Equal(0xFFFF0000, (uint)bitmap.GetPixel(9, 17).ToArgb());
+ Assert.Equal(0xFF0000FF, (uint)bitmap.GetPixel(9, 16).ToArgb());
+ Assert.Equal(0xFF0000FF, (uint)bitmap.GetPixel(9, 15).ToArgb());
+ Assert.Equal(0xFF008000, (uint)bitmap.GetPixel(9, 14).ToArgb());
+ // SW
+ Assert.Equal(0xFFFF0000, (uint)bitmap.GetPixel(3, 17).ToArgb());
+ Assert.Equal(0xFF0000FF, (uint)bitmap.GetPixel(4, 16).ToArgb());
+ Assert.Equal(0xFF0000FF, (uint)bitmap.GetPixel(5, 15).ToArgb());
+ Assert.Equal(0xFF008000, (uint)bitmap.GetPixel(6, 14).ToArgb());
+ // W
+ Assert.Equal(0xFFFF0000, (uint)bitmap.GetPixel(3, 9).ToArgb());
+ Assert.Equal(0xFF0000FF, (uint)bitmap.GetPixel(4, 9).ToArgb());
+ Assert.Equal(0xFF008000, (uint)bitmap.GetPixel(5, 9).ToArgb());
+ }
+ }
+
+ private Bitmap DrawLines(float width)
+ {
+ Bitmap bitmap = new Bitmap(20, 20);
+ using (Graphics g = Graphics.FromImage(bitmap))
+ {
+ g.Clear(Color.Red);
+ Point[] pts = new Point[3] { new Point(5, 5), new Point(15, 5), new Point(15, 15) };
+ if (width >= 0)
+ {
+ using (Pen pen = new Pen(Color.Blue, width))
+ {
+ g.DrawLines(pen, pts);
+ }
+ }
+ else
+ {
+ g.DrawLines(Pens.Blue, pts);
+ }
+ }
+ return bitmap;
+ }
+
+ [ConditionalFact(Helpers.GdiplusIsAvailable)]
+ public void DrawLines_Width_Default()
+ {
+ // default pen size
+ using (Bitmap bitmap = DrawLines(Single.MinValue))
+ {
+ // start
+ Assert.Equal(0xFFFF0000, (uint)bitmap.GetPixel(4, 4).ToArgb());
+ Assert.Equal(0xFFFF0000, (uint)bitmap.GetPixel(4, 5).ToArgb());
+ Assert.Equal(0xFFFF0000, (uint)bitmap.GetPixel(4, 6).ToArgb());
+ Assert.Equal(0xFFFF0000, (uint)bitmap.GetPixel(5, 4).ToArgb());
+ Assert.Equal(0xFF0000FF, (uint)bitmap.GetPixel(5, 5).ToArgb());
+ Assert.Equal(0xFFFF0000, (uint)bitmap.GetPixel(5, 6).ToArgb());
+ // middle
+ Assert.Equal(0xFFFF0000, (uint)bitmap.GetPixel(14, 4).ToArgb());
+ Assert.Equal(0xFF0000FF, (uint)bitmap.GetPixel(14, 5).ToArgb());
+ Assert.Equal(0xFFFF0000, (uint)bitmap.GetPixel(14, 6).ToArgb());
+ Assert.Equal(0xFFFF0000, (uint)bitmap.GetPixel(15, 4).ToArgb());
+ Assert.Equal(0xFF0000FF, (uint)bitmap.GetPixel(15, 5).ToArgb());
+ Assert.Equal(0xFF0000FF, (uint)bitmap.GetPixel(15, 6).ToArgb());
+ Assert.Equal(0xFFFF0000, (uint)bitmap.GetPixel(16, 4).ToArgb());
+ Assert.Equal(0xFFFF0000, (uint)bitmap.GetPixel(16, 5).ToArgb());
+ Assert.Equal(0xFFFF0000, (uint)bitmap.GetPixel(16, 6).ToArgb());
+ //end
+ Assert.Equal(0xFFFF0000, (uint)bitmap.GetPixel(14, 15).ToArgb());
+ Assert.Equal(0xFF0000FF, (uint)bitmap.GetPixel(15, 15).ToArgb());
+ Assert.Equal(0xFFFF0000, (uint)bitmap.GetPixel(16, 15).ToArgb());
+ Assert.Equal(0xFFFF0000, (uint)bitmap.GetPixel(14, 16).ToArgb());
+ Assert.Equal(0xFFFF0000, (uint)bitmap.GetPixel(15, 16).ToArgb());
+ Assert.Equal(0xFFFF0000, (uint)bitmap.GetPixel(16, 16).ToArgb());
+ }
+ }
+
+ [ConditionalFact(Helpers.GdiplusIsAvailable)]
+ public void MeasureString_StringFont()
+ {
+ using (Bitmap bitmap = new Bitmap(20, 20))
+ {
+ using (Graphics g = Graphics.FromImage(bitmap))
+ {
+ SizeF size = g.MeasureString(null, font);
+ Assert.True(size.IsEmpty);
+ size = g.MeasureString(String.Empty, font);
+ Assert.True(size.IsEmpty);
+ // null font
+ size = g.MeasureString(null, null);
+ Assert.True(size.IsEmpty);
+ size = g.MeasureString(String.Empty, null);
+ Assert.True(size.IsEmpty);
+ }
+ }
+ }
+
+ [ConditionalFact(Helpers.GdiplusIsAvailable)]
+ public void MeasureString_StringFont_Null()
+ {
+ using (Bitmap bitmap = new Bitmap(20, 20))
+ using (Graphics g = Graphics.FromImage(bitmap))
+ {
+ Assert.Throws<ArgumentNullException>(() => g.MeasureString("a", null));
+ }
+ }
+
+ [ConditionalFact(Helpers.GdiplusIsAvailable)]
+ public void MeasureString_StringFontSizeF()
+ {
+ using (Bitmap bitmap = new Bitmap(20, 20))
+ using (Graphics g = Graphics.FromImage(bitmap))
+ {
+ SizeF size = g.MeasureString("a", font, SizeF.Empty);
+ Assert.False(size.IsEmpty);
+
+ size = g.MeasureString(String.Empty, font, SizeF.Empty);
+ Assert.True(size.IsEmpty);
+ }
+ }
+
+ private void MeasureString_StringFontInt(string s)
+ {
+ using (Bitmap bitmap = new Bitmap(20, 20))
+ using (Graphics g = Graphics.FromImage(bitmap))
+ {
+ SizeF size0 = g.MeasureString(s, font, 0);
+ SizeF sizeN = g.MeasureString(s, font, Int32.MinValue);
+ SizeF sizeP = g.MeasureString(s, font, Int32.MaxValue);
+ Assert.Equal(size0, sizeN);
+ Assert.Equal(size0, sizeP);
+ }
+ }
+
+ [ConditionalFact(Helpers.GdiplusIsAvailable)]
+ public void MeasureString_StringFontInt_ShortString()
+ {
+ MeasureString_StringFontInt("a");
+ }
+
+ [ConditionalFact(Helpers.GdiplusIsAvailable)]
+ public void MeasureString_StringFontInt_LongString()
+ {
+ MeasureString_StringFontInt("A very long string...");
+ }
+
+ [ConditionalFact(Helpers.GdiplusIsAvailable)]
+ public void MeasureString_StringFormat_Alignment()
+ {
+ string text = "Hello Mono::";
+ StringFormat string_format = new StringFormat();
+
+ using (Bitmap bitmap = new Bitmap(20, 20))
+ using (Graphics g = Graphics.FromImage(bitmap))
+ {
+ string_format.Alignment = StringAlignment.Near;
+ SizeF near = g.MeasureString(text, font, Int32.MaxValue, string_format);
+
+ string_format.Alignment = StringAlignment.Center;
+ SizeF center = g.MeasureString(text, font, Int32.MaxValue, string_format);
+
+ string_format.Alignment = StringAlignment.Far;
+ SizeF far = g.MeasureString(text, font, Int32.MaxValue, string_format);
+
+ Assert.Equal(near.Width, center.Width, 1);
+ Assert.Equal(near.Height, center.Height, 1);
+
+ Assert.Equal(center.Width, far.Width, 1);
+ Assert.Equal(center.Height, far.Height, 1);
+ }
+ }
+
+ [ConditionalFact(Helpers.GdiplusIsAvailable)]
+ public void MeasureString_StringFormat_Alignment_DirectionVertical()
+ {
+ string text = "Hello Mono::";
+ StringFormat string_format = new StringFormat();
+ string_format.FormatFlags = StringFormatFlags.DirectionVertical;
+
+ using (Bitmap bitmap = new Bitmap(20, 20))
+ using (Graphics g = Graphics.FromImage(bitmap))
+ {
+ string_format.Alignment = StringAlignment.Near;
+ SizeF near = g.MeasureString(text, font, Int32.MaxValue, string_format);
+
+ string_format.Alignment = StringAlignment.Center;
+ SizeF center = g.MeasureString(text, font, Int32.MaxValue, string_format);
+
+ string_format.Alignment = StringAlignment.Far;
+ SizeF far = g.MeasureString(text, font, Int32.MaxValue, string_format);
+
+ Assert.Equal(near.Width, center.Width, 0);
+ Assert.Equal(near.Height, center.Height, 0);
+
+ Assert.Equal(center.Width, far.Width, 0);
+ Assert.Equal(center.Height, far.Height, 0);
+ }
+ }
+
+ [ConditionalFact(Helpers.GdiplusIsAvailable)]
+ public void MeasureString_StringFormat_LineAlignment()
+ {
+ string text = "Hello Mono::";
+ StringFormat string_format = new StringFormat();
+
+ using (Bitmap bitmap = new Bitmap(20, 20))
+ using (Graphics g = Graphics.FromImage(bitmap))
+ {
+ string_format.LineAlignment = StringAlignment.Near;
+ SizeF near = g.MeasureString(text, font, Int32.MaxValue, string_format);
+
+ string_format.LineAlignment = StringAlignment.Center;
+ SizeF center = g.MeasureString(text, font, Int32.MaxValue, string_format);
+
+ string_format.LineAlignment = StringAlignment.Far;
+ SizeF far = g.MeasureString(text, font, Int32.MaxValue, string_format);
+
+ Assert.Equal(near.Width, center.Width, 1);
+ Assert.Equal(near.Height, center.Height, 1);
+
+ Assert.Equal(center.Width, far.Width, 1);
+ Assert.Equal(center.Height, far.Height, 1);
+ }
+ }
+
+ [ConditionalFact(Helpers.GdiplusIsAvailable)]
+ public void MeasureString_StringFormat_LineAlignment_DirectionVertical()
+ {
+ string text = "Hello Mono::";
+ StringFormat string_format = new StringFormat();
+ string_format.FormatFlags = StringFormatFlags.DirectionVertical;
+
+ using (Bitmap bitmap = new Bitmap(20, 20))
+ using (Graphics g = Graphics.FromImage(bitmap))
+ {
+ string_format.LineAlignment = StringAlignment.Near;
+ SizeF near = g.MeasureString(text, font, Int32.MaxValue, string_format);
+
+ string_format.LineAlignment = StringAlignment.Center;
+ SizeF center = g.MeasureString(text, font, Int32.MaxValue, string_format);
+
+ string_format.LineAlignment = StringAlignment.Far;
+ SizeF far = g.MeasureString(text, font, Int32.MaxValue, string_format);
+
+ Assert.Equal(near.Width, center.Width, 1);
+ Assert.Equal(near.Height, center.Height, 1);
+
+ Assert.Equal(center.Width, far.Width, 1);
+ Assert.Equal(center.Height, far.Height, 1);
+ }
+ }
+
+ [ActiveIssue(20844)]
+ public void MeasureString_MultlineString_Width()
+ {
+ using (Bitmap bitmap = new Bitmap(20, 20))
+ using (Graphics g = Graphics.FromImage(bitmap))
+ {
+ StringFormat string_format = new StringFormat();
+
+ string text1 = "Test\nTest123\nTest 456\nTest 1,2,3,4,5...";
+ string text2 = "Test 1,2,3,4,5...";
+
+ SizeF size1 = g.MeasureString(text1, font, SizeF.Empty, string_format);
+ SizeF size2 = g.MeasureString(text2, font, SizeF.Empty, string_format);
+
+ Assert.Equal((int)size1.Width, (int)size2.Width);
+ }
+ }
+
+ [ConditionalFact(Helpers.GdiplusIsAvailable)]
+ public void MeasureString_CharactersFitted()
+ {
+ using (Bitmap bitmap = new Bitmap(20, 20))
+ using (Graphics g = Graphics.FromImage(bitmap))
+ {
+ string s = "aaa aa aaaa a aaa";
+ SizeF size = g.MeasureString(s, font);
+
+ int chars, lines;
+ SizeF size2 = g.MeasureString(s, font, new SizeF(80, size.Height), null, out chars, out lines);
+
+ // in pixels
+ Assert.True(size2.Width < size.Width);
+ Assert.Equal(size2.Height, size.Height);
+
+ Assert.Equal(1, lines);
+ // LAMESPEC: documentation seems to suggest chars is total length
+ Assert.True(chars < s.Length);
+ }
+ }
+
+ [ConditionalFact(Helpers.GdiPlusIsAvailableNotRedhat73)]
+ public void MeasureString_Whitespace()
+ {
+ using (Bitmap bitmap = new Bitmap(20, 20))
+ using (Graphics g = Graphics.FromImage(bitmap))
+ {
+ string s = String.Empty;
+ SizeF size = g.MeasureString(s, font);
+ Assert.Equal(0, size.Height);
+ Assert.Equal(0, size.Width);
+
+ s += " ";
+ SizeF expected = g.MeasureString(s, font);
+ for (int i = 1; i < 10; i++)
+ {
+ s += " ";
+ size = g.MeasureString(s, font);
+ Assert.Equal(expected.Height, size.Height, 1);
+ Assert.Equal(expected.Width, size.Width, 1);
+ }
+
+ s = "a";
+ expected = g.MeasureString(s, font);
+ s = " " + s;
+ size = g.MeasureString(s, font);
+ float space_width = size.Width - expected.Width;
+ for (int i = 1; i < 10; i++)
+ {
+ size = g.MeasureString(s, font);
+ Assert.Equal(expected.Height, size.Height, 1);
+ Assert.Equal(expected.Width + i * space_width, size.Width, 1);
+ s = " " + s;
+ }
+
+ s = "a";
+ expected = g.MeasureString(s, font);
+ for (int i = 1; i < 10; i++)
+ {
+ s = s + " ";
+ size = g.MeasureString(s, font);
+ Assert.Equal(expected.Height, size.Height, 1);
+ Assert.Equal(expected.Width, size.Width, 1);
+ }
+ }
+ }
+
+ [ConditionalFact(Helpers.GdiplusIsAvailable)]
+ public void MeasureCharacterRanges_NullOrEmptyText()
+ {
+ using (Bitmap bitmap = new Bitmap(20, 20))
+ using (Graphics g = Graphics.FromImage(bitmap))
+ {
+ Region[] regions = g.MeasureCharacterRanges(null, font, new RectangleF(), null);
+ Assert.Equal(0, regions.Length);
+ regions = g.MeasureCharacterRanges(String.Empty, font, new RectangleF(), null);
+ Assert.Equal(0, regions.Length);
+ // null font is ok with null or empty string
+ regions = g.MeasureCharacterRanges(null, null, new RectangleF(), null);
+ Assert.Equal(0, regions.Length);
+ regions = g.MeasureCharacterRanges(String.Empty, null, new RectangleF(), null);
+ Assert.Equal(0, regions.Length);
+ }
+ }
+
+ [ConditionalFact(Helpers.GdiplusIsAvailable)]
+ public void MeasureCharacterRanges_EmptyStringFormat()
+ {
+ using (Bitmap bitmap = new Bitmap(20, 20))
+ using (Graphics g = Graphics.FromImage(bitmap))
+ {
+ // string format without character ranges
+ Region[] regions = g.MeasureCharacterRanges("Mono", font, new RectangleF(), new StringFormat());
+ Assert.Equal(0, regions.Length);
+ }
+ }
+
+ [ConditionalFact(Helpers.GdiplusIsAvailable)]
+ public void MeasureCharacterRanges_FontNull()
+ {
+ using (Bitmap bitmap = new Bitmap(20, 20))
+ using (Graphics g = Graphics.FromImage(bitmap))
+ {
+ Assert.Throws<ArgumentNullException>(() => g.MeasureCharacterRanges("a", null, new RectangleF(), null));
+ }
+ }
+
+ [ConditionalFact(Helpers.GdiPlusIsAvailableNotRedhat73)]
+ public void MeasureCharacterRanges_TwoLines()
+ {
+ string text = "this\nis a test";
+ CharacterRange[] ranges = new CharacterRange[2];
+ ranges[0] = new CharacterRange(0, 5);
+ ranges[1] = new CharacterRange(5, 9);
+
+ StringFormat string_format = new StringFormat();
+ string_format.FormatFlags = StringFormatFlags.NoClip;
+ string_format.SetMeasurableCharacterRanges(ranges);
+
+ using (Bitmap bitmap = new Bitmap(20, 20))
+ using (Graphics g = Graphics.FromImage(bitmap))
+ {
+ SizeF size = g.MeasureString(text, font, new Point(0, 0), string_format);
+ RectangleF layout_rect = new RectangleF(0.0f, 0.0f, size.Width, size.Height);
+ Region[] regions = g.MeasureCharacterRanges(text, font, layout_rect, string_format);
+
+ Assert.Equal(2, regions.Length);
+ Assert.Equal(regions[0].GetBounds(g).Height, regions[1].GetBounds(g).Height);
+ }
+ }
+
+ private void MeasureCharacterRanges(string text, int first, int length)
+ {
+ CharacterRange[] ranges = new CharacterRange[1];
+ ranges[0] = new CharacterRange(first, length);
+
+ StringFormat string_format = new StringFormat();
+ string_format.FormatFlags = StringFormatFlags.NoClip;
+ string_format.SetMeasurableCharacterRanges(ranges);
+
+ using (Bitmap bitmap = new Bitmap(20, 20))
+ using (Graphics g = Graphics.FromImage(bitmap))
+ {
+ SizeF size = g.MeasureString(text, font, new Point(0, 0), string_format);
+ RectangleF layout_rect = new RectangleF(0.0f, 0.0f, size.Width, size.Height);
+ g.MeasureCharacterRanges(text, font, layout_rect, string_format);
+ }
+ }
+
+ [ConditionalFact(Helpers.GdiplusIsAvailable)]
+ public void MeasureCharacterRanges_FirstTooFar()
+ {
+ string text = "this\nis a test";
+ Assert.Throws<ArgumentException>(() => MeasureCharacterRanges(text, text.Length, 1));
+ }
+
+ [ConditionalFact(Helpers.GdiplusIsAvailable)]
+ public void MeasureCharacterRanges_LengthTooLong()
+ {
+ string text = "this\nis a test";
+ Assert.Throws<ArgumentException>(() => MeasureCharacterRanges(text, 0, text.Length + 1));
+ }
+
+ [ConditionalFact(Helpers.GdiplusIsAvailable)]
+ public void MeasureCharacterRanges_Prefix()
+ {
+ string text = "Hello &Mono::";
+ CharacterRange[] ranges = new CharacterRange[1];
+ ranges[0] = new CharacterRange(5, 4);
+
+ StringFormat string_format = new StringFormat();
+ string_format.SetMeasurableCharacterRanges(ranges);
+
+ using (Bitmap bitmap = new Bitmap(20, 20))
+ using (Graphics g = Graphics.FromImage(bitmap))
+ {
+ SizeF size = g.MeasureString(text, font, new Point(0, 0), string_format);
+ RectangleF layout_rect = new RectangleF(0.0f, 0.0f, size.Width, size.Height);
+
+ // here & is part of the measure and visible
+ string_format.HotkeyPrefix = HotkeyPrefix.None;
+ Region[] regions = g.MeasureCharacterRanges(text, font, layout_rect, string_format);
+ RectangleF bounds_none = regions[0].GetBounds(g);
+
+ // here & is part of the measure (range) but visible as an underline
+ string_format.HotkeyPrefix = HotkeyPrefix.Show;
+ regions = g.MeasureCharacterRanges(text, font, layout_rect, string_format);
+ RectangleF bounds_show = regions[0].GetBounds(g);
+ Assert.True(bounds_show.Width < bounds_none.Width);
+
+ // here & is part of the measure (range) but invisible
+ string_format.HotkeyPrefix = HotkeyPrefix.Hide;
+ regions = g.MeasureCharacterRanges(text, font, layout_rect, string_format);
+ RectangleF bounds_hide = regions[0].GetBounds(g);
+ Assert.Equal(bounds_hide.Width, bounds_show.Width);
+ }
+ }
+
+ [ConditionalFact(Helpers.GdiplusIsAvailable)]
+ public void MeasureCharacterRanges_NullStringFormat()
+ {
+ using (Bitmap bitmap = new Bitmap(20, 20))
+ using (Graphics g = Graphics.FromImage(bitmap))
+ {
+ Assert.Throws<ArgumentException>(() => g.MeasureCharacterRanges("Mono", font, new RectangleF(), null));
+ }
+ }
+
+ static CharacterRange[] ranges = new CharacterRange[] {
+ new CharacterRange (0, 1),
+ new CharacterRange (1, 1),
+ new CharacterRange (2, 1)
+ };
+
+ Region[] Measure(Graphics gfx, RectangleF rect)
+ {
+ using (StringFormat format = StringFormat.GenericTypographic)
+ {
+ format.SetMeasurableCharacterRanges(ranges);
+
+ using (Font font = new Font(FontFamily.GenericSerif, 11.0f))
+ {
+ return gfx.MeasureCharacterRanges("abc", font, rect, format);
+ }
+ }
+ }
+
+ [ConditionalFact(Helpers.GdiplusIsAvailable)]
+ public void Measure()
+ {
+ using (Graphics gfx = Graphics.FromImage(new Bitmap(1, 1)))
+ {
+ Region[] zero = Measure(gfx, new RectangleF(0, 0, 0, 0));
+ Assert.Equal(3, zero.Length);
+
+ Region[] small = Measure(gfx, new RectangleF(0, 0, 100, 100));
+ Assert.Equal(3, small.Length);
+ for (int i = 0; i < 3; i++)
+ {
+ RectangleF zb = zero[i].GetBounds(gfx);
+ RectangleF sb = small[i].GetBounds(gfx);
+ Assert.Equal(sb.X, zb.X);
+ Assert.Equal(sb.Y, zb.Y);
+ Assert.Equal(sb.Width, zb.Width);
+ Assert.Equal(sb.Height, zb.Height);
+ }
+
+ Region[] max = Measure(gfx, new RectangleF(0, 0, Single.MaxValue, Single.MaxValue));
+ Assert.Equal(3, max.Length);
+ for (int i = 0; i < 3; i++)
+ {
+ RectangleF zb = zero[i].GetBounds(gfx);
+ RectangleF mb = max[i].GetBounds(gfx);
+ Assert.Equal(mb.X, zb.X);
+ Assert.Equal(mb.Y, zb.Y);
+ Assert.Equal(mb.Width, zb.Width);
+ Assert.Equal(mb.Height, zb.Height);
+ }
+ }
+ }
+
+ [ConditionalFact(Helpers.GdiplusIsAvailable)]
+ public void MeasureLimits()
+ {
+ using (Graphics gfx = Graphics.FromImage(new Bitmap(1, 1)))
+ {
+ Region[] min = Measure(gfx, new RectangleF(0, 0, Single.MinValue, Single.MinValue));
+ Assert.Equal(3, min.Length);
+ for (int i = 0; i < 3; i++)
+ {
+ RectangleF mb = min[i].GetBounds(gfx);
+ Assert.Equal(-4194304.0f, mb.X);
+ Assert.Equal(-4194304.0f, mb.Y);
+ Assert.Equal(8388608.0f, mb.Width);
+ Assert.Equal(8388608.0f, mb.Height);
+ }
+
+ Region[] neg = Measure(gfx, new RectangleF(0, 0, -20, -20));
+ Assert.Equal(3, neg.Length);
+ for (int i = 0; i < 3; i++)
+ {
+ RectangleF mb = neg[i].GetBounds(gfx);
+ Assert.Equal(-4194304.0f, mb.X);
+ Assert.Equal(-4194304.0f, mb.Y);
+ Assert.Equal(8388608.0f, mb.Width);
+ Assert.Equal(8388608.0f, mb.Height);
+ }
+ }
+ }
+
+ [ConditionalFact(Helpers.GdiplusIsAvailable)]
+ public void DrawString_EndlessLoop()
+ {
+ using (Bitmap bitmap = new Bitmap(20, 20))
+ using (Graphics g = Graphics.FromImage(bitmap))
+ {
+ Rectangle rect = Rectangle.Empty;
+ rect.Location = new Point(10, 10);
+ rect.Size = new Size(1, 20);
+ StringFormat fmt = new StringFormat();
+ fmt.Alignment = StringAlignment.Center;
+ fmt.LineAlignment = StringAlignment.Center;
+ fmt.FormatFlags = StringFormatFlags.NoWrap;
+ fmt.Trimming = StringTrimming.EllipsisWord;
+ g.DrawString("Test String", font, Brushes.Black, rect, fmt);
+ }
+ }
+
+ [ConditionalFact(Helpers.GdiplusIsAvailable)]
+ public void DrawString_EndlessLoop_Wrapping()
+ {
+ using (Bitmap bitmap = new Bitmap(20, 20))
+ using (Graphics g = Graphics.FromImage(bitmap))
+ {
+ Rectangle rect = Rectangle.Empty;
+ rect.Location = new Point(10, 10);
+ rect.Size = new Size(1, 20);
+ StringFormat fmt = new StringFormat();
+ fmt.Alignment = StringAlignment.Center;
+ fmt.LineAlignment = StringAlignment.Center;
+ fmt.Trimming = StringTrimming.EllipsisWord;
+ g.DrawString("Test String", font, Brushes.Black, rect, fmt);
+ }
+ }
+
+ [ConditionalFact(Helpers.RecentGdiplusIsAvailable)]
+ public void MeasureString_Wrapping_Dots()
+ {
+ string text = "this is really long text........................................... with a lot o periods.";
+ using (Bitmap bitmap = new Bitmap(20, 20))
+ using (Graphics g = Graphics.FromImage(bitmap))
+ {
+ using (StringFormat format = new StringFormat())
+ {
+ format.Alignment = StringAlignment.Center;
+ SizeF sz = g.MeasureString(text, font, 80, format);
+ Assert.True(sz.Width <= 80);
+ Assert.True(sz.Height > font.Height * 2);
+ }
+ }
+ }
+
+ [ConditionalFact(Helpers.GdiplusIsAvailable)]
+ public void GetReleaseHdcInternal()
+ {
+ using (Bitmap b = new Bitmap(10, 10))
+ using (Graphics g = Graphics.FromImage(b))
+ {
+ IntPtr hdc1 = g.GetHdc();
+ g.ReleaseHdcInternal(hdc1);
+ IntPtr hdc2 = g.GetHdc();
+ g.ReleaseHdcInternal(hdc2);
+ Assert.Equal(hdc1, hdc2);
+ }
+ }
+
+ [ConditionalFact(Helpers.GdiplusIsAvailable)]
+ public void ReleaseHdcInternal_IntPtrZero()
+ {
+ using (Bitmap b = new Bitmap(10, 10))
+ using (Graphics g = Graphics.FromImage(b))
+ {
+ Assert.Throws<ArgumentException>(() => g.ReleaseHdcInternal(IntPtr.Zero));
+ }
+ }
+
+ [ConditionalFact(Helpers.GdiplusIsAvailable)]
+ public void ReleaseHdcInternal_TwoTimes()
+ {
+ using (Bitmap b = new Bitmap(10, 10))
+ using (Graphics g = Graphics.FromImage(b))
+ {
+ IntPtr hdc = g.GetHdc();
+ g.ReleaseHdcInternal(hdc);
+ Assert.Throws<ArgumentException>(() => g.ReleaseHdcInternal(hdc));
+ }
+ }
+ [ConditionalFact(Helpers.GdiplusIsAvailable)]
+ public void TestReleaseHdc()
+ {
+ using (Bitmap b = new Bitmap(10, 10))
+ using (Graphics g = Graphics.FromImage(b))
+ {
+ IntPtr hdc1 = g.GetHdc();
+ g.ReleaseHdc();
+ IntPtr hdc2 = g.GetHdc();
+ g.ReleaseHdc();
+ Assert.Equal(hdc1, hdc2);
+ }
+ }
+
+ [ConditionalFact(Helpers.GdiplusIsAvailable)]
+ public void TestReleaseHdcException()
+ {
+ using (Bitmap b = new Bitmap(10, 10))
+ using (Graphics g = Graphics.FromImage(b))
+ {
+ Assert.Throws<ArgumentException>(() => g.ReleaseHdc());
+ }
+ }
+
+ [ConditionalFact(Helpers.GdiplusIsAvailable)]
+ public void TestReleaseHdcException2()
+ {
+ using (Bitmap b = new Bitmap(10, 10))
+ using (Graphics g = Graphics.FromImage(b))
+ {
+ g.GetHdc();
+ g.ReleaseHdc();
+ Assert.Throws<ArgumentException>(() => g.ReleaseHdc());
+ }
+ }
+ [ConditionalFact(Helpers.GdiplusIsAvailable)]
+ public void VisibleClipBound()
+ {
+ // see #78958
+ using (Bitmap bmp = new Bitmap(100, 100))
+ using (Graphics g = Graphics.FromImage(bmp))
+ {
+ RectangleF noclip = g.VisibleClipBounds;
+ Assert.Equal(0, noclip.X);
+ Assert.Equal(0, noclip.Y);
+ Assert.Equal(100, noclip.Width);
+ Assert.Equal(100, noclip.Height);
+
+ // note: libgdiplus regions are precise to multiple of multiple of 8
+ g.Clip = new Region(new RectangleF(0, 0, 32, 32));
+ RectangleF clip = g.VisibleClipBounds;
+ Assert.Equal(0, clip.X);
+ Assert.Equal(0, clip.Y);
+ Assert.Equal(32, clip.Width, 4);
+ Assert.Equal(32, clip.Height, 4);
+
+ g.RotateTransform(90);
+ RectangleF rotclip = g.VisibleClipBounds;
+ Assert.Equal(0, rotclip.X);
+ Assert.Equal(-32, rotclip.Y, 4);
+ Assert.Equal(32, rotclip.Width, 4);
+ Assert.Equal(32, rotclip.Height, 4);
+ }
+ }
+
+ [ConditionalFact(Helpers.GdiplusIsAvailable)]
+ public void VisibleClipBound_BigClip()
+ {
+ using (Bitmap bmp = new Bitmap(100, 100))
+ using (Graphics g = Graphics.FromImage(bmp))
+ {
+ RectangleF noclip = g.VisibleClipBounds;
+ Assert.Equal(0, noclip.X);
+ Assert.Equal(0, noclip.Y);
+ Assert.Equal(100, noclip.Width);
+ Assert.Equal(100, noclip.Height);
+
+ // clip is larger than bitmap
+ g.Clip = new Region(new RectangleF(0, 0, 200, 200));
+ RectangleF clipbound = g.ClipBounds;
+ Assert.Equal(0, clipbound.X);
+ Assert.Equal(0, clipbound.Y);
+ Assert.Equal(200, clipbound.Width);
+ Assert.Equal(200, clipbound.Height);
+
+ RectangleF clip = g.VisibleClipBounds;
+ Assert.Equal(0, clip.X);
+ Assert.Equal(0, clip.Y);
+ Assert.Equal(100, clip.Width);
+ Assert.Equal(100, clip.Height);
+
+ g.RotateTransform(90);
+ RectangleF rotclipbound = g.ClipBounds;
+ Assert.Equal(0, rotclipbound.X);
+ Assert.Equal(-200, rotclipbound.Y, 4);
+ Assert.Equal(200, rotclipbound.Width, 4);
+ Assert.Equal(200, rotclipbound.Height, 4);
+
+ RectangleF rotclip = g.VisibleClipBounds;
+ Assert.Equal(0, rotclip.X);
+ Assert.Equal(-100, rotclip.Y, 4);
+ Assert.Equal(100, rotclip.Width, 4);
+ Assert.Equal(100, rotclip.Height, 4);
+ }
+ }
+
+ [ConditionalFact(Helpers.GdiplusIsAvailable)]
+ public void Rotate()
+ {
+ using (Bitmap bmp = new Bitmap(100, 50))
+ using (Graphics g = Graphics.FromImage(bmp))
+ {
+ RectangleF vcb = g.VisibleClipBounds;
+ Assert.Equal(0, vcb.X);
+ Assert.Equal(0, vcb.Y);
+ Assert.Equal(100, vcb.Width, 4);
+ Assert.Equal(50, vcb.Height, 4);
+
+ g.RotateTransform(90);
+ RectangleF rvcb = g.VisibleClipBounds;
+ Assert.Equal(0, rvcb.X);
+ Assert.Equal(-100, rvcb.Y, 4);
+ Assert.Equal(50.0f, rvcb.Width, 4);
+ Assert.Equal(100, rvcb.Height, 4);
+ }
+ }
+
+ [ConditionalFact(Helpers.GdiplusIsAvailable)]
+ public void Scale()
+ {
+ using (Bitmap bmp = new Bitmap(100, 50))
+ using (Graphics g = Graphics.FromImage(bmp))
+ {
+ RectangleF vcb = g.VisibleClipBounds;
+ Assert.Equal(0, vcb.X);
+ Assert.Equal(0, vcb.Y);
+ Assert.Equal(100, vcb.Width);
+ Assert.Equal(50, vcb.Height);
+
+ g.ScaleTransform(2, 0.5f);
+ RectangleF svcb = g.VisibleClipBounds;
+ Assert.Equal(0, svcb.X);
+ Assert.Equal(0, svcb.Y);
+ Assert.Equal(50, svcb.Width);
+ Assert.Equal(100, svcb.Height);
+ }
+ }
+
+ [ConditionalFact(Helpers.GdiplusIsAvailable)]
+ public void Translate()
+ {
+ using (Bitmap bmp = new Bitmap(100, 50))
+ using (Graphics g = Graphics.FromImage(bmp))
+ {
+ RectangleF vcb = g.VisibleClipBounds;
+ Assert.Equal(0, vcb.X);
+ Assert.Equal(0, vcb.Y);
+ Assert.Equal(100, vcb.Width);
+ Assert.Equal(50, vcb.Height);
+
+ g.TranslateTransform(-25, 25);
+ RectangleF tvcb = g.VisibleClipBounds;
+ Assert.Equal(25, tvcb.X);
+ Assert.Equal(-25, tvcb.Y);
+ Assert.Equal(100, tvcb.Width);
+ Assert.Equal(50, tvcb.Height);
+ }
+ }
+
+ [ConditionalFact(Helpers.GdiplusIsAvailable)]
+ public void DrawIcon_NullRectangle()
+ {
+ using (Bitmap bmp = new Bitmap(40, 40))
+ using (Graphics g = Graphics.FromImage(bmp))
+ {
+ Assert.Throws<ArgumentNullException>(() => g.DrawIcon(null, new Rectangle(0, 0, 32, 32)));
+ }
+ }
+
+ [ConditionalFact(Helpers.GdiplusIsAvailable)]
+ public void DrawIcon_IconRectangle()
+ {
+ using (Bitmap bmp = new Bitmap(40, 40))
+ using (Graphics g = Graphics.FromImage(bmp))
+ {
+ g.DrawIcon(SystemIcons.Application, new Rectangle(0, 0, 40, 20));
+ // Rectangle is empty when X, Y, Width and Height == 0
+ // (yep X and Y too, RectangleF only checks for Width and Height)
+ g.DrawIcon(SystemIcons.Asterisk, new Rectangle(0, 0, 0, 0));
+ // so this one is half-empty ;-)
+ g.DrawIcon(SystemIcons.Error, new Rectangle(20, 40, 0, 0));
+ // negative width or height isn't empty (for Rectangle)
+ g.DrawIconUnstretched(SystemIcons.WinLogo, new Rectangle(10, 20, -1, 0));
+ g.DrawIconUnstretched(SystemIcons.WinLogo, new Rectangle(20, 10, 0, -1));
+ }
+ }
+
+ [ConditionalFact(Helpers.GdiplusIsAvailable)]
+ public void DrawIcon_NullIntInt()
+ {
+ using (Bitmap bmp = new Bitmap(40, 40))
+ using (Graphics g = Graphics.FromImage(bmp))
+ {
+ Assert.Throws<ArgumentNullException>(() => g.DrawIcon(null, 4, 2));
+ }
+ }
+
+ [ConditionalFact(Helpers.GdiplusIsAvailable)]
+ public void DrawIcon_IconIntInt()
+ {
+ using (Bitmap bmp = new Bitmap(40, 40))
+ using (Graphics g = Graphics.FromImage(bmp))
+ {
+ g.DrawIcon(SystemIcons.Exclamation, 4, 2);
+ g.DrawIcon(SystemIcons.Hand, 0, 0);
+ }
+ }
+
+ [ConditionalFact(Helpers.GdiplusIsAvailable)]
+ public void DrawIconUnstretched_NullRectangle()
+ {
+ using (Bitmap bmp = new Bitmap(40, 40))
+ using (Graphics g = Graphics.FromImage(bmp))
+ {
+ Assert.Throws<ArgumentNullException>(() => g.DrawIconUnstretched(null, new Rectangle(0, 0, 40, 20)));
+ }
+ }
+
+ [ConditionalFact(Helpers.GdiplusIsAvailable)]
+ public void DrawIconUnstretched_IconRectangle()
+ {
+ using (Bitmap bmp = new Bitmap(40, 40))
+ using (Graphics g = Graphics.FromImage(bmp))
+ {
+ g.DrawIconUnstretched(SystemIcons.Information, new Rectangle(0, 0, 40, 20));
+ // Rectangle is empty when X, Y, Width and Height == 0
+ // (yep X and Y too, RectangleF only checks for Width and Height)
+ g.DrawIconUnstretched(SystemIcons.Question, new Rectangle(0, 0, 0, 0));
+ // so this one is half-empty ;-)
+ g.DrawIconUnstretched(SystemIcons.Warning, new Rectangle(20, 40, 0, 0));
+ // negative width or height isn't empty (for Rectangle)
+ g.DrawIconUnstretched(SystemIcons.WinLogo, new Rectangle(10, 20, -1, 0));
+ g.DrawIconUnstretched(SystemIcons.WinLogo, new Rectangle(20, 10, 0, -1));
+ }
+ }
+
+ [ConditionalFact(Helpers.GdiplusIsAvailable)]
+ public void DrawImage_NullRectangleF()
+ {
+ using (Bitmap bmp = new Bitmap(40, 40))
+ using (Graphics g = Graphics.FromImage(bmp))
+ {
+ Assert.Throws<ArgumentNullException>(() => g.DrawImage(null, new RectangleF(0, 0, 0, 0)));
+ }
+ }
+
+ [ConditionalFact(Helpers.GdiplusIsAvailable)]
+ public void DrawImage_ImageRectangleF()
+ {
+ using (Bitmap bmp = new Bitmap(40, 40))
+ using (Graphics g = Graphics.FromImage(bmp))
+ {
+ g.DrawImage(bmp, new RectangleF(0, 0, 0, 0));
+ g.DrawImage(bmp, new RectangleF(20, 40, 0, 0));
+ g.DrawImage(bmp, new RectangleF(10, 20, -1, 0));
+ g.DrawImage(bmp, new RectangleF(20, 10, 0, -1));
+ }
+ }
+
+ [ConditionalFact(Helpers.GdiplusIsAvailable)]
+ public void DrawImage_NullPointF()
+ {
+ using (Bitmap bmp = new Bitmap(40, 40))
+ using (Graphics g = Graphics.FromImage(bmp))
+ {
+ Assert.Throws<ArgumentNullException>(() => g.DrawImage(null, new PointF(0, 0)));
+ }
+ }
+
+ [ConditionalFact(Helpers.GdiplusIsAvailable)]
+ public void DrawImage_ImagePointF()
+ {
+ using (Bitmap bmp = new Bitmap(40, 40))
+ using (Graphics g = Graphics.FromImage(bmp))
+ {
+ g.DrawImage(bmp, new PointF(0, 0));
+ }
+ }
+
+ [ConditionalFact(Helpers.GdiplusIsAvailable)]
+ public void DrawImage_NullPointFArray()
+ {
+ using (Bitmap bmp = new Bitmap(40, 40))
+ using (Graphics g = Graphics.FromImage(bmp))
+ {
+ Assert.Throws<ArgumentNullException>(() => g.DrawImage(null, new PointF[0]));
+ }
+ }
+
+ [ConditionalFact(Helpers.GdiplusIsAvailable)]
+ public void DrawImage_ImagePointFArrayNull()
+ {
+ using (Bitmap bmp = new Bitmap(40, 40))
+ {
+ using (Graphics g = Graphics.FromImage(bmp))
+ {
+ Assert.Throws<ArgumentNullException>(() => g.DrawImage(bmp, (PointF[])null));
+ }
+ }
+ }
+
+ [ConditionalFact(Helpers.GdiplusIsAvailable)]
+ public void DrawImage_ImagePointFArrayEmpty()
+ {
+ using (Bitmap bmp = new Bitmap(40, 40))
+ using (Graphics g = Graphics.FromImage(bmp))
+ {
+ Assert.Throws<ArgumentException>(() => g.DrawImage(bmp, new PointF[0]));
+ }
+ }
+
+ [ConditionalFact(Helpers.GdiplusIsAvailable)]
+ public void DrawImage_ImagePointFArray()
+ {
+ using (Bitmap bmp = new Bitmap(40, 40))
+ using (Graphics g = Graphics.FromImage(bmp))
+ {
+ g.DrawImage(bmp, new PointF[] {
+ new PointF (0, 0), new PointF (1, 1), new PointF (2, 2) });
+ }
+ }
+
+ [ConditionalFact(Helpers.GdiplusIsAvailable)]
+ public void DrawImage_NullRectangle()
+ {
+ using (Bitmap bmp = new Bitmap(40, 40))
+ using (Graphics g = Graphics.FromImage(bmp))
+ {
+ Assert.Throws<ArgumentNullException>(() => g.DrawImage(null, new Rectangle(0, 0, 0, 0)));
+ }
+ }
+
+ [ConditionalFact(Helpers.GdiplusIsAvailable)]
+ public void DrawImage_ImageRectangle()
+ {
+ using (Bitmap bmp = new Bitmap(40, 40))
+ using (Graphics g = Graphics.FromImage(bmp))
+ {
+ // Rectangle is empty when X, Y, Width and Height == 0
+ // (yep X and Y too, RectangleF only checks for Width and Height)
+ g.DrawImage(bmp, new Rectangle(0, 0, 0, 0));
+ // so this one is half-empty ;-)
+ g.DrawImage(bmp, new Rectangle(20, 40, 0, 0));
+ // negative width or height isn't empty (for Rectangle)
+ g.DrawImage(bmp, new Rectangle(10, 20, -1, 0));
+ g.DrawImage(bmp, new Rectangle(20, 10, 0, -1));
+ }
+ }
+
+ [ConditionalFact(Helpers.GdiplusIsAvailable)]
+ public void DrawImage_NullPoint()
+ {
+ using (Bitmap bmp = new Bitmap(40, 40))
+ using (Graphics g = Graphics.FromImage(bmp))
+ {
+ Assert.Throws<ArgumentNullException>(() => g.DrawImage(null, new Point(0, 0)));
+ }
+ }
+
+ [ConditionalFact(Helpers.GdiplusIsAvailable)]
+ public void DrawImage_ImagePoint()
+ {
+ using (Bitmap bmp = new Bitmap(40, 40))
+ using (Graphics g = Graphics.FromImage(bmp))
+ {
+ g.DrawImage(bmp, new Point(0, 0));
+ }
+ }
+
+ [ConditionalFact(Helpers.GdiplusIsAvailable)]
+ public void DrawImage_NullPointArray()
+ {
+ using (Bitmap bmp = new Bitmap(40, 40))
+ using (Graphics g = Graphics.FromImage(bmp))
+ {
+ Assert.Throws<ArgumentNullException>(() => g.DrawImage(null, new Point[0]));
+ }
+ }
+
+ [ConditionalFact(Helpers.GdiplusIsAvailable)]
+ public void DrawImage_ImagePointArrayNull()
+ {
+ using (Bitmap bmp = new Bitmap(40, 40))
+ using (Graphics g = Graphics.FromImage(bmp))
+ {
+ Assert.Throws<ArgumentNullException>(() => g.DrawImage(bmp, (Point[])null));
+ }
+ }
+
+ [ConditionalFact(Helpers.GdiplusIsAvailable)]
+ public void DrawImage_ImagePointArrayEmpty()
+ {
+ using (Bitmap bmp = new Bitmap(40, 40))
+ using (Graphics g = Graphics.FromImage(bmp))
+ {
+ Assert.Throws<ArgumentException>(() => g.DrawImage(bmp, new Point[0]));
+ }
+ }
+
+ [ConditionalFact(Helpers.GdiplusIsAvailable)]
+ public void DrawImage_ImagePointArray()
+ {
+ using (Bitmap bmp = new Bitmap(40, 40))
+ using (Graphics g = Graphics.FromImage(bmp))
+ {
+ g.DrawImage(bmp, new Point[] {
+ new Point (0, 0), new Point (1, 1), new Point (2, 2) });
+ }
+ }
+
+ [ConditionalFact(Helpers.GdiplusIsAvailable)]
+ public void DrawImage_NullIntInt()
+ {
+ using (Bitmap bmp = new Bitmap(40, 40))
+ using (Graphics g = Graphics.FromImage(bmp))
+ {
+ Assert.Throws<ArgumentNullException>(() => g.DrawImage(null, Int32.MaxValue, Int32.MinValue));
+ }
+ }
+
+ [ConditionalFact(Helpers.GdiplusIsAvailable)]
+ public void DrawImage_ImageIntInt_Overflow()
+ {
+ using (Bitmap bmp = new Bitmap(40, 40))
+ using (Graphics g = Graphics.FromImage(bmp))
+ {
+ Assert.Throws<OverflowException>(() => g.DrawImage(bmp, Int32.MaxValue, Int32.MinValue));
+ }
+ }
+
+ [ConditionalFact(Helpers.GdiplusIsAvailable)]
+ public void DrawImage_ImageIntInt()
+ {
+ using (Bitmap bmp = new Bitmap(40, 40))
+ using (Graphics g = Graphics.FromImage(bmp))
+ {
+ g.DrawImage(bmp, -40, -40);
+ }
+ }
+
+ [ConditionalFact(Helpers.GdiplusIsAvailable)]
+ public void DrawImage_NullFloat()
+ {
+ using (Bitmap bmp = new Bitmap(40, 40))
+ using (Graphics g = Graphics.FromImage(bmp))
+ {
+ Assert.Throws<ArgumentNullException>(() => g.DrawImage(null, Single.MaxValue, Single.MinValue));
+ }
+ }
+
+ [ConditionalFact(Helpers.GdiplusIsAvailable)]
+ public void DrawImage_ImageFloatFloat_Overflow()
+ {
+ using (Bitmap bmp = new Bitmap(40, 40))
+ using (Graphics g = Graphics.FromImage(bmp))
+ {
+ Assert.Throws<OverflowException>(() => g.DrawImage(bmp, Single.MaxValue, Single.MinValue));
+ }
+ }
+
+ [ConditionalFact(Helpers.GdiplusIsAvailable)]
+ public void DrawImage_ImageFloatFloat()
+ {
+ using (Bitmap bmp = new Bitmap(40, 40))
+ using (Graphics g = Graphics.FromImage(bmp))
+ {
+ g.DrawImage(bmp, -40.0f, -40.0f);
+ }
+ }
+
+ [ConditionalFact(Helpers.GdiplusIsAvailable)]
+ public void DrawImage_NullRectangleRectangleGraphicsUnit()
+ {
+ using (Bitmap bmp = new Bitmap(40, 40))
+ using (Graphics g = Graphics.FromImage(bmp))
+ {
+ Assert.Throws<ArgumentNullException>(() => g.DrawImage(null, new Rectangle(), new Rectangle(), GraphicsUnit.Display));
+ }
+ }
+
+ private void DrawImage_ImageRectangleRectangleGraphicsUnit(GraphicsUnit unit)
+ {
+ using (Bitmap bmp = new Bitmap(40, 40))
+ using (Graphics g = Graphics.FromImage(bmp))
+ {
+ Rectangle r = new Rectangle(0, 0, 40, 40);
+ g.DrawImage(bmp, r, r, unit);
+ }
+ }
+
+ [ConditionalFact(Helpers.GdiplusIsAvailable)]
+ public void DrawImage_ImageRectangleRectangleGraphicsUnit_Display()
+ {
+ Assert.Throws<ArgumentException>(() => DrawImage_ImageRectangleRectangleGraphicsUnit(GraphicsUnit.Display));
+ }
+
+ [ActiveIssue(20844, TestPlatforms.Any)]
+ public void DrawImage_ImageRectangleRectangleGraphicsUnit_Document()
+ {
+ Assert.Throws<NotImplementedException>(() => DrawImage_ImageRectangleRectangleGraphicsUnit(GraphicsUnit.Document));
+ }
+
+ [ActiveIssue(20844)]
+ public void DrawImage_ImageRectangleRectangleGraphicsUnit_Inch()
+ {
+ Assert.Throws<NotImplementedException>(() => DrawImage_ImageRectangleRectangleGraphicsUnit(GraphicsUnit.Inch));
+ }
+
+ [ActiveIssue(20844, TestPlatforms.Any)]
+ public void DrawImage_ImageRectangleRectangleGraphicsUnit_Millimeter()
+ {
+ Assert.Throws<NotImplementedException>(() => DrawImage_ImageRectangleRectangleGraphicsUnit(GraphicsUnit.Millimeter));
+ }
+
+ [ConditionalFact(Helpers.GdiplusIsAvailable)]
+ public void DrawImage_ImageRectangleRectangleGraphicsUnit_Pixel()
+ {
+ // this unit works
+ DrawImage_ImageRectangleRectangleGraphicsUnit(GraphicsUnit.Pixel);
+ }
+
+ [ActiveIssue(20844, TestPlatforms.Any)]
+ public void DrawImage_ImageRectangleRectangleGraphicsUnit_Point()
+ {
+ Assert.Throws<NotImplementedException>(() => DrawImage_ImageRectangleRectangleGraphicsUnit(GraphicsUnit.Point));
+ }
+
+ [ConditionalFact(Helpers.GdiplusIsAvailable)]
+ public void DrawImage_ImageRectangleRectangleGraphicsUnit_World()
+ {
+ Assert.Throws<ArgumentException>(() => DrawImage_ImageRectangleRectangleGraphicsUnit(GraphicsUnit.World));
+ }
+
+ [ConditionalFact(Helpers.GdiplusIsAvailable)]
+ public void DrawImage_NullPointRectangleGraphicsUnit()
+ {
+ Rectangle r = new Rectangle(1, 2, 3, 4);
+ Point[] pts = new Point[3] { new Point(1, 1), new Point(2, 2), new Point(3, 3) };
+ using (Bitmap bmp = new Bitmap(40, 40))
+ using (Graphics g = Graphics.FromImage(bmp))
+ {
+ Assert.Throws<ArgumentNullException>(() => g.DrawImage(null, pts, r, GraphicsUnit.Pixel));
+ }
+ }
+
+ private void DrawImage_ImagePointRectangleGraphicsUnit(Point[] pts)
+ {
+ Rectangle r = new Rectangle(1, 2, 3, 4);
+ using (Bitmap bmp = new Bitmap(40, 40))
+ using (Graphics g = Graphics.FromImage(bmp))
+ {
+ g.DrawImage(bmp, pts, r, GraphicsUnit.Pixel);
+ }
+ }
+
+ [ConditionalFact(Helpers.GdiplusIsAvailable)]
+ public void DrawImage_ImageNullRectangleGraphicsUnit()
+ {
+ Assert.Throws<ArgumentNullException>(() => DrawImage_ImagePointRectangleGraphicsUnit(null));
+ }
+
+ [ConditionalFact(Helpers.GdiplusIsAvailable)]
+ public void DrawImage_ImagePoint0RectangleGraphicsUnit()
+ {
+ Assert.Throws<ArgumentException>(() => DrawImage_ImagePointRectangleGraphicsUnit(new Point[0]));
+ }
+
+ [ConditionalFact(Helpers.GdiplusIsAvailable)]
+ public void DrawImage_ImagePoint1RectangleGraphicsUnit()
+ {
+ Point p = new Point(1, 1);
+ Assert.Throws<ArgumentException>(() => DrawImage_ImagePointRectangleGraphicsUnit(new Point[1] { p }));
+ }
+
+ [ConditionalFact(Helpers.GdiplusIsAvailable)]
+ public void DrawImage_ImagePoint2RectangleGraphicsUnit()
+ {
+ Point p = new Point(1, 1);
+ Assert.Throws<ArgumentException>(() => DrawImage_ImagePointRectangleGraphicsUnit(new Point[2] { p, p }));
+ }
+
+ [ConditionalFact(Helpers.GdiplusIsAvailable)]
+ public void DrawImage_ImagePoint3RectangleGraphicsUnit()
+ {
+ Point p = new Point(1, 1);
+ DrawImage_ImagePointRectangleGraphicsUnit(new Point[3] { p, p, p });
+ }
+
+ [ConditionalFact(Helpers.GdiplusIsAvailable)]
+ public void DrawImage_ImagePoint4RectangleGraphicsUnit()
+ {
+ Point p = new Point(1, 1);
+ Assert.Throws<NotImplementedException>(() => DrawImage_ImagePointRectangleGraphicsUnit(new Point[4] { p, p, p, p }));
+ }
+
+ [ConditionalFact(Helpers.GdiplusIsAvailable)]
+ public void DrawImage_NullPointFRectangleGraphicsUnit()
+ {
+ Rectangle r = new Rectangle(1, 2, 3, 4);
+ PointF[] pts = new PointF[3] { new PointF(1, 1), new PointF(2, 2), new PointF(3, 3) };
+ using (Bitmap bmp = new Bitmap(40, 40))
+ using (Graphics g = Graphics.FromImage(bmp))
+ {
+ Assert.Throws<ArgumentNullException>(() => g.DrawImage(null, pts, r, GraphicsUnit.Pixel));
+ }
+ }
+
+ private void DrawImage_ImagePointFRectangleGraphicsUnit(PointF[] pts)
+ {
+ Rectangle r = new Rectangle(1, 2, 3, 4);
+ using (Bitmap bmp = new Bitmap(40, 40))
+ using (Graphics g = Graphics.FromImage(bmp))
+ {
+ g.DrawImage(bmp, pts, r, GraphicsUnit.Pixel);
+ }
+ }
+
+ [ConditionalFact(Helpers.GdiplusIsAvailable)]
+ public void DrawImage_ImageNullFRectangleGraphicsUnit()
+ {
+ Assert.Throws<ArgumentNullException>(() => DrawImage_ImagePointFRectangleGraphicsUnit(null));
+ }
+
+ [ConditionalFact(Helpers.GdiplusIsAvailable)]
+ public void DrawImage_ImagePointF0RectangleGraphicsUnit()
+ {
+ Assert.Throws<ArgumentException>(() => DrawImage_ImagePointFRectangleGraphicsUnit(new PointF[0]));
+ }
+
+ [ConditionalFact(Helpers.GdiplusIsAvailable)]
+ public void DrawImage_ImagePointF1RectangleGraphicsUnit()
+ {
+ PointF p = new PointF(1, 1);
+ Assert.Throws<ArgumentException>(() => DrawImage_ImagePointFRectangleGraphicsUnit(new PointF[1] { p }));
+ }
+
+ [ConditionalFact(Helpers.GdiplusIsAvailable)]
+ public void DrawImage_ImagePointF2RectangleGraphicsUnit()
+ {
+ PointF p = new PointF(1, 1);
+ Assert.Throws<ArgumentException>(() => DrawImage_ImagePointFRectangleGraphicsUnit(new PointF[2] { p, p }));
+ }
+
+ [ConditionalFact(Helpers.GdiplusIsAvailable)]
+ public void DrawImage_ImagePointF3RectangleGraphicsUnit()
+ {
+ PointF p = new PointF(1, 1);
+ DrawImage_ImagePointFRectangleGraphicsUnit(new PointF[3] { p, p, p });
+ }
+
+ [ConditionalFact(Helpers.GdiplusIsAvailable)]
+ public void DrawImage_ImagePointF4RectangleGraphicsUnit()
+ {
+ PointF p = new PointF(1, 1);
+ Assert.Throws<NotImplementedException>(() => DrawImage_ImagePointFRectangleGraphicsUnit(new PointF[4] { p, p, p, p }));
+ }
+
+ [ConditionalFact(Helpers.GdiplusIsAvailable)]
+ public void DrawImage_ImagePointRectangleGraphicsUnitNull()
+ {
+ Point p = new Point(1, 1);
+ Point[] pts = new Point[3] { p, p, p };
+ Rectangle r = new Rectangle(1, 2, 3, 4);
+ using (Bitmap bmp = new Bitmap(40, 40))
+ using (Graphics g = Graphics.FromImage(bmp))
+ {
+ g.DrawImage(bmp, pts, r, GraphicsUnit.Pixel, null);
+ }
+ }
+
+ [ConditionalFact(Helpers.GdiplusIsAvailable)]
+ public void DrawImage_ImagePointRectangleGraphicsUnitAttributes()
+ {
+ Point p = new Point(1, 1);
+ Point[] pts = new Point[3] { p, p, p };
+ Rectangle r = new Rectangle(1, 2, 3, 4);
+ using (Bitmap bmp = new Bitmap(40, 40))
+ using (Graphics g = Graphics.FromImage(bmp))
+ {
+ ImageAttributes ia = new ImageAttributes();
+ g.DrawImage(bmp, pts, r, GraphicsUnit.Pixel, ia);
+ }
+ }
+
+ [ConditionalFact(Helpers.GdiplusIsAvailable)]
+ public void DrawImageUnscaled_NullPoint()
+ {
+ using (Bitmap bmp = new Bitmap(40, 40))
+ using (Graphics g = Graphics.FromImage(bmp))
+ {
+ Assert.Throws<ArgumentNullException>(() => g.DrawImageUnscaled(null, new Point(0, 0)));
+ }
+ }
+
+ [ConditionalFact(Helpers.GdiplusIsAvailable)]
+ public void DrawImageUnscaled_ImagePoint()
+ {
+ using (Bitmap bmp = new Bitmap(40, 40))
+ using (Graphics g = Graphics.FromImage(bmp))
+ {
+ g.DrawImageUnscaled(bmp, new Point(0, 0));
+ }
+ }
+
+ [ConditionalFact(Helpers.GdiplusIsAvailable)]
+ public void DrawImageUnscaled_NullRectangle()
+ {
+ using (Bitmap bmp = new Bitmap(40, 40))
+ using (Graphics g = Graphics.FromImage(bmp))
+ {
+ Assert.Throws<ArgumentNullException>(() => g.DrawImageUnscaled(null, new Rectangle(0, 0, -1, -1)));
+ }
+ }
+
+ [ConditionalFact(Helpers.GdiplusIsAvailable)]
+ public void DrawImageUnscaled_ImageRectangle()
+ {
+ using (Bitmap bmp = new Bitmap(40, 40))
+ using (Graphics g = Graphics.FromImage(bmp))
+ {
+ g.DrawImageUnscaled(bmp, new Rectangle(0, 0, -1, -1));
+ }
+ }
+
+ [ConditionalFact(Helpers.GdiplusIsAvailable)]
+ public void DrawImageUnscaled_NullIntInt()
+ {
+ using (Bitmap bmp = new Bitmap(40, 40))
+ using (Graphics g = Graphics.FromImage(bmp))
+ {
+ Assert.Throws<ArgumentNullException>(() => g.DrawImageUnscaled(null, 0, 0));
+ }
+ }
+
+ [ConditionalFact(Helpers.GdiplusIsAvailable)]
+ public void DrawImageUnscaled_ImageIntInt()
+ {
+ using (Bitmap bmp = new Bitmap(40, 40))
+ using (Graphics g = Graphics.FromImage(bmp))
+ {
+ g.DrawImageUnscaled(bmp, 0, 0);
+ }
+ }
+
+ [ConditionalFact(Helpers.GdiplusIsAvailable)]
+ public void DrawImageUnscaled_NullIntIntIntInt()
+ {
+ using (Bitmap bmp = new Bitmap(40, 40))
+ using (Graphics g = Graphics.FromImage(bmp))
+ {
+ Assert.Throws<ArgumentNullException>(() => g.DrawImageUnscaled(null, 0, 0, -1, -1));
+ }
+ }
+
+ [ConditionalFact(Helpers.GdiplusIsAvailable)]
+ public void DrawImageUnscaled_ImageIntIntIntInt()
+ {
+ using (Bitmap bmp = new Bitmap(40, 40))
+ using (Graphics g = Graphics.FromImage(bmp))
+ {
+ g.DrawImageUnscaled(bmp, 0, 0, -1, -1);
+ }
+ }
+
+ [ConditionalFact(Helpers.GdiplusIsAvailable)]
+ public void DrawImageUnscaledAndClipped_Null()
+ {
+ using (Bitmap bmp = new Bitmap(40, 40))
+ using (Graphics g = Graphics.FromImage(bmp))
+ {
+ Assert.Throws<ArgumentNullException>(() => g.DrawImageUnscaledAndClipped(null, new Rectangle(0, 0, 0, 0)));
+ }
+ }
+
+ [ConditionalFact(Helpers.GdiplusIsAvailable)]
+ public void DrawImageUnscaledAndClipped()
+ {
+ using (Bitmap bmp = new Bitmap(40, 40))
+ using (Graphics g = Graphics.FromImage(bmp))
+ {
+ // Rectangle is empty when X, Y, Width and Height == 0
+ // (yep X and Y too, RectangleF only checks for Width and Height)
+ g.DrawImageUnscaledAndClipped(bmp, new Rectangle(0, 0, 0, 0));
+ // so this one is half-empty ;-)
+ g.DrawImageUnscaledAndClipped(bmp, new Rectangle(20, 40, 0, 0));
+ // negative width or height isn't empty (for Rectangle)
+ g.DrawImageUnscaledAndClipped(bmp, new Rectangle(10, 20, -1, 0));
+ g.DrawImageUnscaledAndClipped(bmp, new Rectangle(20, 10, 0, -1));
+ // smaller
+ g.DrawImageUnscaledAndClipped(bmp, new Rectangle(0, 0, 10, 20));
+ g.DrawImageUnscaledAndClipped(bmp, new Rectangle(0, 0, 40, 10));
+ g.DrawImageUnscaledAndClipped(bmp, new Rectangle(0, 0, 80, 20));
+ }
+ }
+
+ [ConditionalFact(Helpers.GdiplusIsAvailable)]
+ public void DrawPath_Pen_Null()
+ {
+ using (Bitmap bmp = new Bitmap(20, 20))
+ using (Graphics g = Graphics.FromImage(bmp))
+ using (GraphicsPath path = new GraphicsPath())
+ {
+ Assert.Throws<ArgumentNullException>(() => g.DrawPath(null, path));
+ }
+ }
+
+ [ConditionalFact(Helpers.GdiplusIsAvailable)]
+ public void DrawPath_Path_Null()
+ {
+ using (Bitmap bmp = new Bitmap(20, 20))
+ using (Graphics g = Graphics.FromImage(bmp))
+ {
+ Assert.Throws<ArgumentNullException>(() => g.DrawPath(Pens.Black, null));
+ }
+ }
+
+ [ConditionalFact(Helpers.GdiplusIsAvailable)]
+ public void DrawPath_Arcs()
+ {
+ using (Bitmap bmp = new Bitmap(20, 20))
+ using (Graphics g = Graphics.FromImage(bmp))
+ using (GraphicsPath path = new GraphicsPath())
+ {
+ int d = 5;
+ Rectangle baserect = new Rectangle(0, 0, 19, 19);
+ Rectangle arcrect = new Rectangle(baserect.Location, new Size(d, d));
+
+ path.AddArc(arcrect, 180, 90);
+ arcrect.X = baserect.Right - d;
+ path.AddArc(arcrect, 270, 90);
+ arcrect.Y = baserect.Bottom - d;
+ path.AddArc(arcrect, 0, 90);
+ arcrect.X = baserect.Left;
+ path.AddArc(arcrect, 90, 90);
+ path.CloseFigure();
+ g.Clear(Color.White);
+ g.DrawPath(Pens.SteelBlue, path);
+
+ Assert.Equal(-12156236, bmp.GetPixel(0, 9).ToArgb());
+ Assert.Equal(-1, bmp.GetPixel(1, 9).ToArgb());
+ }
+ }
+
+ [ConditionalFact(Helpers.GdiplusIsAvailable)]
+ public void FillPath_Brush_Null()
+ {
+ using (Bitmap bmp = new Bitmap(20, 20))
+ using (Graphics g = Graphics.FromImage(bmp))
+ using (GraphicsPath path = new GraphicsPath())
+ {
+ Assert.Throws<ArgumentNullException>(() => g.FillPath(null, path));
+ }
+ }
+
+ [ConditionalFact(Helpers.GdiplusIsAvailable)]
+ public void FillPath_Path_Null()
+ {
+ using (Bitmap bmp = new Bitmap(20, 20))
+ using (Graphics g = Graphics.FromImage(bmp))
+ {
+ Assert.Throws<ArgumentNullException>(() => g.FillPath(Brushes.Black, null));
+ }
+ }
+
+ [ConditionalFact(Helpers.GdiplusIsAvailable)]
+ public void FillPath_Arcs()
+ {
+ using (Bitmap bmp = new Bitmap(20, 20))
+ using (Graphics g = Graphics.FromImage(bmp))
+ using (GraphicsPath path = new GraphicsPath())
+ {
+ int d = 5;
+ Rectangle baserect = new Rectangle(0, 0, 19, 19);
+ Rectangle arcrect = new Rectangle(baserect.Location, new Size(d, d));
+
+ path.AddArc(arcrect, 180, 90);
+ arcrect.X = baserect.Right - d;
+ path.AddArc(arcrect, 270, 90);
+ arcrect.Y = baserect.Bottom - d;
+ path.AddArc(arcrect, 0, 90);
+ arcrect.X = baserect.Left;
+ path.AddArc(arcrect, 90, 90);
+ path.CloseFigure();
+ g.Clear(Color.White);
+ g.FillPath(Brushes.SteelBlue, path);
+
+ Assert.Equal(-12156236, bmp.GetPixel(0, 9).ToArgb());
+ Assert.Equal(-12156236, bmp.GetPixel(1, 9).ToArgb());
+ }
+ }
+
+ [ConditionalFact(Helpers.GdiplusIsAvailable)]
+ public void TransformPoints()
+ {
+ using (Bitmap bmp = new Bitmap(10, 10))
+ using (Graphics g = Graphics.FromImage(bmp))
+ {
+ Point[] pts = new Point[5];
+ PointF[] ptf = new PointF[5];
+ for (int i = 0; i < 5; i++)
+ {
+ pts[i] = new Point(i, i);
+ ptf[i] = new PointF(i, i);
+ }
+
+ g.TransformPoints(CoordinateSpace.Page, CoordinateSpace.Device, pts);
+ g.TransformPoints(CoordinateSpace.Page, CoordinateSpace.Device, ptf);
+
+ for (int i = 0; i < 5; i++)
+ {
+ Assert.Equal(i, pts[i].X);
+ Assert.Equal(i, pts[i].Y);
+ Assert.Equal(i, ptf[i].X);
+ Assert.Equal(i, ptf[i].Y);
+ }
+ }
+ }
+
+ [ConditionalFact(Helpers.GdiplusIsAvailable)]
+ public void Dpi()
+ {
+ float x, y;
+ using (Bitmap bmp = new Bitmap(10, 10))
+ {
+ using (Graphics g = Graphics.FromImage(bmp))
+ {
+ x = g.DpiX - 10;
+ y = g.DpiY + 10;
+ }
+ bmp.SetResolution(x, y);
+ using (Graphics g = Graphics.FromImage(bmp))
+ {
+ Assert.Equal(x, g.DpiX);
+ Assert.Equal(y, g.DpiY);
+ }
+ }
+ }
+ }
+
+ public class GraphicsFullTrustTest
+ {
+ // note: this test would fail, on ReleaseHdc, without fulltrust
+ // i.e. it's a demand and not a linkdemand
+ [ConditionalFact(Helpers.GdiplusIsAvailable)]
+ public void GetReleaseHdc()
+ {
+ using (Bitmap b = new Bitmap(100, 100))
+ {
+ using (Graphics g = Graphics.FromImage(b))
+ {
+ IntPtr hdc1 = g.GetHdc();
+ g.ReleaseHdc(hdc1);
+ IntPtr hdc2 = g.GetHdc();
+ g.ReleaseHdc(hdc2);
+ Assert.Equal(hdc1, hdc2);
+ }
+ }
+ }
+ }
+}
diff --git a/src/System.Drawing.Common/tests/mono/System.Imaging/MetafileTest.cs b/src/System.Drawing.Common/tests/mono/System.Imaging/MetafileTest.cs
new file mode 100644
index 0000000000..f58f13d1d7
--- /dev/null
+++ b/src/System.Drawing.Common/tests/mono/System.Imaging/MetafileTest.cs
@@ -0,0 +1,485 @@
+// Licensed to the .NET Foundation under one or more agreements.
+// See the LICENSE file in the project root for more information.
+//
+// Metafile class unit tests
+//
+// Authors:
+// Sebastien Pouliot <sebastien@ximian.com>
+//
+// Copyright (C) 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;
+using System.Drawing;
+using System.Drawing.Drawing2D;
+using System.Drawing.Imaging;
+using System.IO;
+using System.Runtime.InteropServices;
+using System.Security.Permissions;
+using Xunit;
+
+namespace MonoTests.System.Drawing.Imaging
+{
+
+ public class MetafileTest
+ {
+
+ public const string Bitmap = "non-inverted.bmp";
+ public const string WmfPlaceable = "telescope_01.wmf";
+ public const string Emf = "milkmateya01.emf";
+
+ [ConditionalFact(Helpers.GdiplusIsAvailable)]
+ public void Metafile_String()
+ {
+ string filename = Helpers.GetTestBitmapPath(WmfPlaceable);
+ using (Metafile mf = new Metafile(filename))
+ using (Metafile clone = (Metafile)mf.Clone())
+ {
+ }
+ }
+
+ static public void Check_MetaHeader_WmfPlaceable(MetaHeader mh)
+ {
+ Assert.Equal(9, mh.HeaderSize);
+ Assert.Equal(98, mh.MaxRecord);
+ Assert.Equal(3, mh.NoObjects);
+ Assert.Equal(0, mh.NoParameters);
+ Assert.Equal(1737, mh.Size);
+ Assert.Equal(1, mh.Type);
+ Assert.Equal(0x300, mh.Version);
+ }
+
+ public static void Check_MetafileHeader_WmfPlaceable(MetafileHeader header)
+ {
+ Assert.Equal(MetafileType.WmfPlaceable, header.Type);
+ Assert.Equal(0x300, header.Version);
+ // filesize - 22, which happens to be the size (22) of a PLACEABLEMETAHEADER struct
+ Assert.Equal(3474, header.MetafileSize);
+
+ Assert.Equal(-30, header.Bounds.X);
+ Assert.Equal(-40, header.Bounds.Y);
+ Assert.Equal(3096, header.Bounds.Width);
+ Assert.Equal(4127, header.Bounds.Height);
+ Assert.Equal(606, header.DpiX);
+ Assert.Equal(606, header.DpiY);
+ Assert.Equal(0, header.EmfPlusHeaderSize);
+ Assert.Equal(0, header.LogicalDpiX);
+ Assert.Equal(0, header.LogicalDpiY);
+
+ Assert.NotNull(header.WmfHeader);
+ Check_MetaHeader_WmfPlaceable(header.WmfHeader);
+
+ Assert.False(header.IsDisplay());
+ Assert.False(header.IsEmf());
+ Assert.False(header.IsEmfOrEmfPlus());
+ Assert.False(header.IsEmfPlus());
+ Assert.False(header.IsEmfPlusDual());
+ Assert.False(header.IsEmfPlusOnly());
+ Assert.True(header.IsWmf());
+ Assert.True(header.IsWmfPlaceable());
+ }
+
+ [ConditionalFact(Helpers.GdiplusIsAvailable)]
+ public void GetMetafileHeader_FromFile_WmfPlaceable()
+ {
+ using (Metafile mf = new Metafile(Helpers.GetTestBitmapPath(WmfPlaceable)))
+ {
+ MetafileHeader header1 = mf.GetMetafileHeader();
+ Check_MetafileHeader_WmfPlaceable(header1);
+
+ MetaHeader mh1 = header1.WmfHeader;
+ Check_MetaHeader_WmfPlaceable(mh1);
+
+ MetaHeader mh2 = mf.GetMetafileHeader().WmfHeader;
+ Assert.NotSame(mh1, mh2);
+ }
+ }
+
+ [ConditionalFact(Helpers.GdiplusIsAvailable)]
+ public void GetMetafileHeader_FromFileStream_WmfPlaceable()
+ {
+ using (FileStream fs = File.OpenRead(Helpers.GetTestBitmapPath(WmfPlaceable)))
+ using (Metafile mf = new Metafile(fs))
+ {
+ MetafileHeader header1 = mf.GetMetafileHeader();
+ Check_MetafileHeader_WmfPlaceable(header1);
+
+ MetaHeader mh1 = header1.WmfHeader;
+ Check_MetaHeader_WmfPlaceable(mh1);
+
+ MetaHeader mh2 = mf.GetMetafileHeader().WmfHeader;
+ Assert.NotSame(mh1, mh2);
+ }
+ }
+
+ [ConditionalFact(Helpers.GdiplusIsAvailable)]
+ public void GetMetafileHeader_FromMemoryStream_WmfPlaceable()
+ {
+ string filename = Helpers.GetTestBitmapPath(WmfPlaceable);
+ using (MemoryStream ms = new MemoryStream(File.ReadAllBytes(filename)))
+ using (Metafile mf = new Metafile(ms))
+ {
+ MetafileHeader header1 = mf.GetMetafileHeader();
+ Check_MetafileHeader_WmfPlaceable(header1);
+
+ MetaHeader mh1 = header1.WmfHeader;
+ Check_MetaHeader_WmfPlaceable(mh1);
+
+ MetaHeader mh2 = mf.GetMetafileHeader().WmfHeader;
+ Assert.NotSame(mh1, mh2);
+ }
+ }
+
+ public static void Check_MetafileHeader_Emf(MetafileHeader header)
+ {
+ Assert.Equal(MetafileType.Emf, header.Type);
+ Assert.Equal(65536, header.Version);
+ // extactly the filesize
+ Assert.Equal(20456, header.MetafileSize);
+
+ Assert.Equal(0, header.Bounds.X);
+ Assert.Equal(0, header.Bounds.Y);
+
+ Assert.Throws<ArgumentException>(() => header.WmfHeader);
+
+ Assert.False(header.IsDisplay());
+ Assert.True(header.IsEmf());
+ Assert.True(header.IsEmfOrEmfPlus());
+ Assert.False(header.IsEmfPlus());
+ Assert.False(header.IsEmfPlusDual());
+ Assert.False(header.IsEmfPlusOnly());
+ Assert.False(header.IsWmf());
+ Assert.False(header.IsWmfPlaceable());
+ }
+
+ [ConditionalFact(Helpers.GdiplusIsAvailable)]
+ public void GetMetafileHeader_FromFile_Emf()
+ {
+ using (Metafile mf = new Metafile(Helpers.GetTestBitmapPath(Emf)))
+ {
+ MetafileHeader header1 = mf.GetMetafileHeader();
+ Check_MetafileHeader_Emf(header1);
+ }
+ }
+
+ [ConditionalFact(Helpers.GdiplusIsAvailable)]
+ public void GetMetafileHeader_FromFileStream_Emf()
+ {
+ using (FileStream fs = File.OpenRead(Helpers.GetTestBitmapPath(Emf)))
+ using (Metafile mf = new Metafile(fs))
+ {
+ MetafileHeader header1 = mf.GetMetafileHeader();
+ Check_MetafileHeader_Emf(header1);
+ }
+ }
+
+ [ConditionalFact(Helpers.GdiplusIsAvailable)]
+ public void GetMetafileHeader_FromMemoryStream_Emf()
+ {
+ string filename = Helpers.GetTestBitmapPath(Emf);
+ using (MemoryStream ms = new MemoryStream(File.ReadAllBytes(filename)))
+ using (Metafile mf = new Metafile(ms))
+ {
+ MetafileHeader header1 = mf.GetMetafileHeader();
+ Check_MetafileHeader_Emf(header1);
+ }
+ }
+ }
+
+ public class MetafileFulltrustTest
+ {
+ private void CheckEmptyHeader(Metafile mf, EmfType type)
+ {
+ MetafileHeader mh = mf.GetMetafileHeader();
+ Assert.Equal(0, mh.Bounds.X);
+ Assert.Equal(0, mh.Bounds.Y);
+ Assert.Equal(0, mh.Bounds.Width);
+ Assert.Equal(0, mh.Bounds.Height);
+ Assert.Equal(0, mh.MetafileSize);
+ switch (type)
+ {
+ case EmfType.EmfOnly:
+ Assert.Equal(MetafileType.Emf, mh.Type);
+ break;
+ case EmfType.EmfPlusDual:
+ Assert.Equal(MetafileType.EmfPlusDual, mh.Type);
+ break;
+ case EmfType.EmfPlusOnly:
+ Assert.Equal(MetafileType.EmfPlusOnly, mh.Type);
+ break;
+ default:
+ Assert.True(false, string.Format("Unknown EmfType '{0}'", type));
+ break;
+ }
+ }
+
+ private void Metafile_IntPtrEmfType(EmfType type)
+ {
+ using (Bitmap bmp = new Bitmap(10, 10, PixelFormat.Format32bppArgb))
+ {
+ using (Graphics g = Graphics.FromImage(bmp))
+ {
+ IntPtr hdc = g.GetHdc();
+ try
+ {
+ Metafile mf = new Metafile(hdc, type);
+ CheckEmptyHeader(mf, type);
+ }
+ finally
+ {
+ g.ReleaseHdc(hdc);
+ }
+ }
+ }
+ }
+
+ [ConditionalFact(Helpers.GdiplusIsAvailable)]
+ public void Metafile_IntPtrRectangle_Empty()
+ {
+ using (Bitmap bmp = new Bitmap(10, 10, PixelFormat.Format32bppArgb))
+ using (Graphics g = Graphics.FromImage(bmp))
+ {
+ IntPtr hdc = g.GetHdc();
+ try
+ {
+ Metafile mf = new Metafile(hdc, new Rectangle());
+ CheckEmptyHeader(mf, EmfType.EmfPlusDual);
+ }
+ finally
+ {
+ g.ReleaseHdc(hdc);
+ }
+ }
+ }
+
+ [ConditionalFact(Helpers.GdiplusIsAvailable)]
+ public void Metafile_IntPtrRectangleF_Empty()
+ {
+ using (Bitmap bmp = new Bitmap(10, 10, PixelFormat.Format32bppArgb))
+ using (Graphics g = Graphics.FromImage(bmp))
+ {
+ IntPtr hdc = g.GetHdc();
+ try
+ {
+ Metafile mf = new Metafile(hdc, new RectangleF());
+ CheckEmptyHeader(mf, EmfType.EmfPlusDual);
+ }
+ finally
+ {
+ g.ReleaseHdc(hdc);
+ }
+ }
+ }
+
+ private void Metafile_StreamEmfType(Stream stream, EmfType type)
+ {
+ using (Bitmap bmp = new Bitmap(10, 10, PixelFormat.Format32bppArgb))
+ using (Graphics g = Graphics.FromImage(bmp))
+ {
+ IntPtr hdc = g.GetHdc();
+ try
+ {
+ Metafile mf = new Metafile(stream, hdc, type);
+ CheckEmptyHeader(mf, type);
+ }
+ finally
+ {
+ g.ReleaseHdc(hdc);
+ }
+ }
+ }
+
+ [ConditionalFact(Helpers.GdiplusIsAvailable)]
+ public void Metafile_StreamIntPtrEmfType_Null()
+ {
+ Assert.Throws<NullReferenceException>(() => Metafile_StreamEmfType(null, EmfType.EmfOnly));
+ }
+
+ [ConditionalFact(Helpers.GdiplusIsAvailable)]
+ public void Metafile_StreamIntPtrEmfType_EmfOnly()
+ {
+ using (MemoryStream ms = new MemoryStream())
+ {
+ Metafile_StreamEmfType(ms, EmfType.EmfOnly);
+ }
+ }
+
+ [ConditionalFact(Helpers.GdiplusIsAvailable)]
+ public void Metafile_StreamIntPtrEmfType_Invalid()
+ {
+ using (MemoryStream ms = new MemoryStream())
+ {
+ Assert.Throws<ArgumentException>(() => Metafile_StreamEmfType(ms, (EmfType)Int32.MinValue));
+ }
+ }
+
+ private void CreateFilename(EmfType type, bool single)
+ {
+ string name = string.Format("{0}-{1}.emf", type, single ? "Single" : "Multiple");
+ string filename = Path.Combine(Path.GetTempPath(), name);
+ Metafile mf;
+ using (Bitmap bmp = new Bitmap(100, 100, PixelFormat.Format32bppArgb))
+ {
+ using (Graphics g = Graphics.FromImage(bmp))
+ {
+ IntPtr hdc = g.GetHdc();
+ try
+ {
+ mf = new Metafile(filename, hdc, type);
+ Assert.Equal(0, new FileInfo(filename).Length);
+ }
+ finally
+ {
+ g.ReleaseHdc(hdc);
+ }
+ }
+ long size = 0;
+ using (Graphics g = Graphics.FromImage(mf))
+ {
+ g.FillRectangle(Brushes.BlueViolet, 10, 10, 80, 80);
+ size = new FileInfo(filename).Length;
+ Assert.Equal(0, size);
+ }
+
+ if (!single)
+ {
+ using (Graphics g = Graphics.FromImage(mf))
+ {
+ g.DrawRectangle(Pens.Azure, 10, 10, 80, 80);
+ }
+ }
+ mf.Dispose();
+ Assert.Equal(size, new FileInfo(filename).Length);
+ }
+ }
+
+ [ActiveIssue(20844)]
+ public void CreateFilename_SingleGraphics_EmfOnly()
+ {
+ CreateFilename(EmfType.EmfOnly, true);
+ }
+
+ [ActiveIssue(20844)]
+ public void CreateFilename_SingleGraphics_EmfPlusDual()
+ {
+ CreateFilename(EmfType.EmfPlusDual, true);
+ }
+
+ [ActiveIssue(20844)]
+ public void CreateFilename_SingleGraphics_EmfPlusOnly()
+ {
+ CreateFilename(EmfType.EmfPlusOnly, true);
+ }
+
+ [ConditionalFact(Helpers.GdiplusIsAvailable)]
+ public void Measure()
+ {
+ Font test_font = new Font(FontFamily.GenericMonospace, 12);
+
+ Metafile mf;
+ using (Bitmap bmp = new Bitmap(100, 100, PixelFormat.Format32bppArgb))
+ using (Graphics g = Graphics.FromImage(bmp))
+ {
+ IntPtr hdc = g.GetHdc();
+ try
+ {
+ mf = new Metafile(hdc, EmfType.EmfPlusOnly);
+ }
+ finally
+ {
+ g.ReleaseHdc(hdc);
+ }
+ }
+ using (Graphics g = Graphics.FromImage(mf))
+ {
+ string text = "this\nis a test";
+ CharacterRange[] ranges = new CharacterRange[2];
+ ranges[0] = new CharacterRange(0, 5);
+ ranges[1] = new CharacterRange(5, 9);
+
+ SizeF size = g.MeasureString(text, test_font);
+ Assert.False(size.IsEmpty);
+
+ StringFormat sf = new StringFormat();
+ sf.FormatFlags = StringFormatFlags.NoClip;
+ sf.SetMeasurableCharacterRanges(ranges);
+
+ RectangleF rect = new RectangleF(0, 0, size.Width, size.Height);
+ Region[] region = g.MeasureCharacterRanges(text, test_font, rect, sf);
+ Assert.Equal(2, region.Length);
+ mf.Dispose();
+ }
+ }
+
+ [ConditionalFact(Helpers.GdiplusIsAvailable)]
+ public void WorldTransforms()
+ {
+ Metafile mf;
+ using (Bitmap bmp = new Bitmap(100, 100, PixelFormat.Format32bppArgb))
+ {
+ using (Graphics g = Graphics.FromImage(bmp))
+ {
+ IntPtr hdc = g.GetHdc();
+ try
+ {
+ mf = new Metafile(hdc, EmfType.EmfPlusOnly);
+ }
+ finally
+ {
+ g.ReleaseHdc(hdc);
+ }
+ }
+ using (Graphics g = Graphics.FromImage(mf))
+ {
+ Assert.True(g.Transform.IsIdentity);
+ g.ScaleTransform(2f, 0.5f);
+ Assert.False(g.Transform.IsIdentity);
+ g.RotateTransform(90);
+ g.TranslateTransform(-2, 2);
+ Matrix m = g.Transform;
+ g.MultiplyTransform(m);
+ // check
+ float[] elements = g.Transform.Elements;
+ Assert.Equal(-1f, elements[0], 5);
+ Assert.Equal(0f, elements[1], 5);
+ Assert.Equal(0f, elements[2], 5);
+ Assert.Equal(-1f, elements[3], 5);
+ Assert.Equal(-2f, elements[4], 5);
+ Assert.Equal(-3f, elements[5], 5);
+
+ g.Transform = m;
+ elements = g.Transform.Elements;
+ Assert.Equal(0f, elements[0], 5);
+ Assert.Equal(0.5f, elements[1], 5);
+ Assert.Equal(-2f, elements[2], 5);
+ Assert.Equal(0f, elements[3], 5);
+ Assert.Equal(-4f, elements[4], 5);
+ Assert.Equal(-1f, elements[5], 5);
+
+ g.ResetTransform();
+ Assert.True(g.Transform.IsIdentity);
+ }
+ mf.Dispose();
+ }
+ }
+ }
+}
diff --git a/src/System.Dynamic.Runtime/tests/Dynamic.NamedAndOptional/Conformance.dynamic.namedandoptional.decl.other.cs b/src/System.Dynamic.Runtime/tests/Dynamic.NamedAndOptional/Conformance.dynamic.namedandoptional.decl.other.cs
index ef6bc7621f..77c37e64d1 100644
--- a/src/System.Dynamic.Runtime/tests/Dynamic.NamedAndOptional/Conformance.dynamic.namedandoptional.decl.other.cs
+++ b/src/System.Dynamic.Runtime/tests/Dynamic.NamedAndOptional/Conformance.dynamic.namedandoptional.decl.other.cs
@@ -8,7 +8,7 @@ namespace ManagedTests.DynamicCSharp.Conformance.dynamic.namedandoptional.decl.o
{
// <Area>Declaration of Methods with Optional Parameters</Area>
// <Title>Declaration of Optional Params</Title>
- // <Description>Simple Declaration of a an Extension method with optional parameters</Description>
+ // <Description>Simple Declaration of an Extension method with optional parameters</Description>
// <Expects status=success></Expects>
// <Code>
public static class Extension
@@ -46,7 +46,7 @@ namespace ManagedTests.DynamicCSharp.Conformance.dynamic.namedandoptional.decl.o
{
// <Area>Declaration of Methods with Optional Parameters</Area>
// <Title>Declaration of Optional Params</Title>
- // <Description>Simple Declaration of a an Extension method with optional parameters</Description>
+ // <Description>Simple Declaration of an Extension method with optional parameters</Description>
// <Expects status=success></Expects>
// <Code>
public static class Extension
@@ -95,7 +95,7 @@ namespace ManagedTests.DynamicCSharp.Conformance.dynamic.namedandoptional.decl.o
{
// <Area>Declaration of Methods with Optional Parameters</Area>
// <Title>Declaration of Optional Params</Title>
- // <Description>Simple Declaration of a an Extension method with optional parameters</Description>
+ // <Description>Simple Declaration of an Extension method with optional parameters</Description>
// <Expects status=success></Expects>
// <Code>
public static class Extension
diff --git a/src/System.Globalization/tests/CultureInfo/CultureInfoCurrentCulture.cs b/src/System.Globalization/tests/CultureInfo/CultureInfoCurrentCulture.cs
index adc3cffa85..763126eb7c 100644
--- a/src/System.Globalization/tests/CultureInfo/CultureInfoCurrentCulture.cs
+++ b/src/System.Globalization/tests/CultureInfo/CultureInfoCurrentCulture.cs
@@ -14,7 +14,7 @@ namespace System.Globalization.Tests
[Fact]
public void CurrentCulture()
{
- if (PlatformDetection.IsNetNative && !PlatformDetection.IsWinRT) // Tide us over until .Net Native ILC tests run are run inside an appcontainer.
+ if (PlatformDetection.IsNetNative && !PlatformDetection.IsInAppContainer) // Tide us over until .Net Native ILC tests run are run inside an appcontainer.
return;
RemoteInvoke(() =>
@@ -43,7 +43,7 @@ namespace System.Globalization.Tests
[Fact]
public void CurrentUICulture()
{
- if (PlatformDetection.IsNetNative && !PlatformDetection.IsWinRT) // Tide us over until .Net Native ILC tests run are run inside an appcontainer.
+ if (PlatformDetection.IsNetNative && !PlatformDetection.IsInAppContainer) // Tide us over until .Net Native ILC tests run are run inside an appcontainer.
return;
RemoteInvoke(() =>
diff --git a/src/System.Globalization/tests/NumberFormatInfo/NumberFormatInfoCurrencyDecimalDigits.cs b/src/System.Globalization/tests/NumberFormatInfo/NumberFormatInfoCurrencyDecimalDigits.cs
index b276ccd253..950e6d3115 100644
--- a/src/System.Globalization/tests/NumberFormatInfo/NumberFormatInfoCurrencyDecimalDigits.cs
+++ b/src/System.Globalization/tests/NumberFormatInfo/NumberFormatInfoCurrencyDecimalDigits.cs
@@ -13,8 +13,8 @@ namespace System.Globalization.Tests
public static IEnumerable<object[]> CurrencyDecimalDigits_TestData()
{
yield return new object[] { NumberFormatInfo.InvariantInfo, 2, 2 };
- yield return new object[] { new CultureInfo("en-US").NumberFormat, 2, 2 };
- yield return new object[] { new CultureInfo("ko").NumberFormat, 0, 2 };
+ yield return new object[] { CultureInfo.GetCultureInfo("en-US").NumberFormat, 2, 2 };
+ yield return new object[] { CultureInfo.GetCultureInfo("ko").NumberFormat, 0, 2 };
}
[Theory]
diff --git a/src/System.Globalization/tests/NumberFormatInfo/NumberFormatInfoCurrencyGroupSizes.cs b/src/System.Globalization/tests/NumberFormatInfo/NumberFormatInfoCurrencyGroupSizes.cs
index a84d8b9a0e..c9b25d03e2 100644
--- a/src/System.Globalization/tests/NumberFormatInfo/NumberFormatInfoCurrencyGroupSizes.cs
+++ b/src/System.Globalization/tests/NumberFormatInfo/NumberFormatInfoCurrencyGroupSizes.cs
@@ -12,12 +12,12 @@ namespace System.Globalization.Tests
public static IEnumerable<object[]> CurrencyGroupSizes_TestData()
{
yield return new object[] { NumberFormatInfo.InvariantInfo, new int[] { 3 } };
- yield return new object[] { new CultureInfo("en-US").NumberFormat, new int[] { 3 } };
+ yield return new object[] { CultureInfo.GetCultureInfo("en-US").NumberFormat, new int[] { 3 } };
if ((!PlatformDetection.IsUbuntu || PlatformDetection.IsUbuntu1404)
&& !PlatformDetection.IsWindows7 && !PlatformDetection.IsWindows8x && !PlatformDetection.IsFedora)
{
- yield return new object[] { new CultureInfo("ur-IN").NumberFormat, new int[] { 3, 2 } };
+ yield return new object[] { CultureInfo.GetCultureInfo("ur-IN").NumberFormat, new int[] { 3, 2 } };
}
}
diff --git a/src/System.Globalization/tests/NumberFormatInfo/NumberFormatInfoCurrencyNegativePattern.cs b/src/System.Globalization/tests/NumberFormatInfo/NumberFormatInfoCurrencyNegativePattern.cs
index 90670e4c68..c6960c612a 100644
--- a/src/System.Globalization/tests/NumberFormatInfo/NumberFormatInfoCurrencyNegativePattern.cs
+++ b/src/System.Globalization/tests/NumberFormatInfo/NumberFormatInfoCurrencyNegativePattern.cs
@@ -13,7 +13,7 @@ namespace System.Globalization.Tests
public static IEnumerable<object[]> CurrencyNegativePattern_TestData()
{
yield return new object[] { NumberFormatInfo.InvariantInfo, new int[] { 0 } };
- yield return new object[] { new CultureInfo("bg-BG").NumberFormat, new int[] { 8 } };
+ yield return new object[] { CultureInfo.GetCultureInfo("bg-BG").NumberFormat, new int[] { 8 } };
}
[Theory]
@@ -36,7 +36,7 @@ namespace System.Globalization.Tests
CultureInfo culture;
try
{
- culture = new CultureInfo(locale);
+ culture = CultureInfo.GetCultureInfo(locale);
}
catch(CultureNotFoundException)
{
diff --git a/src/System.Globalization/tests/NumberFormatInfo/NumberFormatInfoCurrencyPositivePattern.cs b/src/System.Globalization/tests/NumberFormatInfo/NumberFormatInfoCurrencyPositivePattern.cs
index 373c6db599..90a5b7c810 100644
--- a/src/System.Globalization/tests/NumberFormatInfo/NumberFormatInfoCurrencyPositivePattern.cs
+++ b/src/System.Globalization/tests/NumberFormatInfo/NumberFormatInfoCurrencyPositivePattern.cs
@@ -12,8 +12,8 @@ namespace System.Globalization.Tests
public static IEnumerable<object[]> CurrencyPositivePattern_TestData()
{
yield return new object[] { NumberFormatInfo.InvariantInfo, 0 };
- yield return new object[] { new CultureInfo("en-US").NumberFormat, 0 };
- yield return new object[] { new CultureInfo("fr-FR").NumberFormat, 3 };
+ yield return new object[] { CultureInfo.GetCultureInfo("en-US").NumberFormat, 0 };
+ yield return new object[] { CultureInfo.GetCultureInfo("fr-FR").NumberFormat, 3 };
}
[Theory]
diff --git a/src/System.Globalization/tests/NumberFormatInfo/NumberFormatInfoCurrencySymbol.cs b/src/System.Globalization/tests/NumberFormatInfo/NumberFormatInfoCurrencySymbol.cs
index 4bb33ebe33..a68b7303f6 100644
--- a/src/System.Globalization/tests/NumberFormatInfo/NumberFormatInfoCurrencySymbol.cs
+++ b/src/System.Globalization/tests/NumberFormatInfo/NumberFormatInfoCurrencySymbol.cs
@@ -14,7 +14,7 @@ namespace System.Globalization.Tests
[InlineData("", "\x00a4")] // international
public void CurrencySymbol_Get(string name, string expected)
{
- Assert.Equal(expected, new CultureInfo(name).NumberFormat.CurrencySymbol);
+ Assert.Equal(expected, CultureInfo.GetCultureInfo(name).NumberFormat.CurrencySymbol);
}
[Theory]
diff --git a/src/System.Globalization/tests/NumberFormatInfo/NumberFormatInfoCurrentInfo.cs b/src/System.Globalization/tests/NumberFormatInfo/NumberFormatInfoCurrentInfo.cs
index 52570de47e..2954a52780 100644
--- a/src/System.Globalization/tests/NumberFormatInfo/NumberFormatInfoCurrentInfo.cs
+++ b/src/System.Globalization/tests/NumberFormatInfo/NumberFormatInfoCurrentInfo.cs
@@ -12,8 +12,8 @@ namespace System.Globalization.Tests
{
public static IEnumerable<object[]> CurrentInfo_CustomCulture_TestData()
{
- yield return new object[] { new CultureInfo("en") };
- yield return new object[] { new CultureInfo("en-US") };
+ yield return new object[] { CultureInfo.GetCultureInfo("en") };
+ yield return new object[] { CultureInfo.GetCultureInfo("en-US") };
yield return new object[] { CultureInfo.InvariantCulture };
}
@@ -23,7 +23,7 @@ namespace System.Globalization.Tests
{
RemoteInvoke((cultureName) =>
{
- CultureInfo newCulture = new CultureInfo(cultureName);
+ CultureInfo newCulture = CultureInfo.GetCultureInfo(cultureName);
CultureInfo.CurrentCulture = newCulture;
Assert.Same(newCulture.NumberFormat, NumberFormatInfo.CurrentInfo);
return SuccessExitCode;
@@ -56,7 +56,7 @@ namespace System.Globalization.Tests
{
public CultureInfoSubclassOverridesGetFormat(string name): base(name) { }
- public static NumberFormatInfo CustomFormat { get; } = new CultureInfo("fr-FR").NumberFormat;
+ public static NumberFormatInfo CustomFormat { get; } = CultureInfo.GetCultureInfo("fr-FR").NumberFormat;
public override object GetFormat(Type formatType) => CustomFormat;
}
@@ -65,7 +65,7 @@ namespace System.Globalization.Tests
{
public CultureInfoSubclassOverridesNumberFormat(string name): base(name) { }
- public static NumberFormatInfo CustomFormat { get; } = new CultureInfo("fr-FR").NumberFormat;
+ public static NumberFormatInfo CustomFormat { get; } = CultureInfo.GetCultureInfo("fr-FR").NumberFormat;
public override NumberFormatInfo NumberFormat
{
diff --git a/src/System.Globalization/tests/NumberFormatInfo/NumberFormatInfoData.cs b/src/System.Globalization/tests/NumberFormatInfo/NumberFormatInfoData.cs
index 8f86f6f3f6..675de22d56 100644
--- a/src/System.Globalization/tests/NumberFormatInfo/NumberFormatInfoData.cs
+++ b/src/System.Globalization/tests/NumberFormatInfo/NumberFormatInfoData.cs
@@ -8,17 +8,7 @@ namespace System.Globalization.Tests
{
public static int[] UrINNumberGroupSizes()
{
- if (
- (PlatformDetection.IsWindows && PlatformDetection.WindowsVersion >= 10)
-#if !uap
- ||
- (PlatformDetection.IsOSX && PlatformDetection.OSXKernelVersion >= new Version(15, 0))
-#endif
- || (PlatformDetection.IsUbuntu && !PlatformDetection.IsUbuntu1404)
- || PlatformDetection.IsFedora
- || (PlatformDetection.IsDebian && !PlatformDetection.IsDebian8)
- || PlatformDetection.IsTizen
- )
+ if (PlatformDetection.WindowsVersion >= 10 || PlatformDetection.ICUVersion.Major >= 55)
{
return new int[] { 3 };
}
@@ -78,7 +68,7 @@ namespace System.Globalization.Tests
return PlatformDetection.IsWindows ? new int[] { 15 } : new int[] { 8, 15 };
}
- throw DateTimeFormatInfoData.GetCultureNotSupportedException(new CultureInfo(localeName));
+ throw DateTimeFormatInfoData.GetCultureNotSupportedException(CultureInfo.GetCultureInfo(localeName));
}
}
}
diff --git a/src/System.Globalization/tests/NumberFormatInfo/NumberFormatInfoGetInstance.cs b/src/System.Globalization/tests/NumberFormatInfo/NumberFormatInfoGetInstance.cs
index 26b51308e3..23e053df2e 100644
--- a/src/System.Globalization/tests/NumberFormatInfo/NumberFormatInfoGetInstance.cs
+++ b/src/System.Globalization/tests/NumberFormatInfo/NumberFormatInfoGetInstance.cs
@@ -11,7 +11,7 @@ namespace System.Globalization.Tests
{
public static IEnumerable<object[]> GetInstance_TestData()
{
- CultureInfo frFRCulture = new CultureInfo("fr-FR");
+ CultureInfo frFRCulture = CultureInfo.GetCultureInfo("fr-FR");
yield return new object[] { frFRCulture, frFRCulture.NumberFormat };
yield return new object[] { frFRCulture.NumberFormat, frFRCulture.NumberFormat };
yield return new object[] { new CustomFormatProvider(), CustomFormatProvider.CustomFormat };
@@ -55,7 +55,7 @@ namespace System.Globalization.Tests
private class CustomFormatProvider : IFormatProvider
{
- public static NumberFormatInfo CustomFormat { get; } = new CultureInfo("fr-FR").NumberFormat;
+ public static NumberFormatInfo CustomFormat { get; } = CultureInfo.GetCultureInfo("fr-FR").NumberFormat;
public object GetFormat(Type formatType) => CustomFormat;
}
diff --git a/src/System.Globalization/tests/NumberFormatInfo/NumberFormatInfoNegativeInfinitySymbol.cs b/src/System.Globalization/tests/NumberFormatInfo/NumberFormatInfoNegativeInfinitySymbol.cs
index 2a8fc36df3..327b76dd8c 100644
--- a/src/System.Globalization/tests/NumberFormatInfo/NumberFormatInfoNegativeInfinitySymbol.cs
+++ b/src/System.Globalization/tests/NumberFormatInfo/NumberFormatInfoNegativeInfinitySymbol.cs
@@ -12,8 +12,8 @@ namespace System.Globalization.Tests
public static IEnumerable<object[]> NegativeInfinitySymbol_TestData()
{
yield return new object[] { NumberFormatInfo.InvariantInfo };
- yield return new object[] { new CultureInfo("en-US").NumberFormat };
- yield return new object[] { new CultureInfo("fr-FR").NumberFormat };
+ yield return new object[] { CultureInfo.GetCultureInfo("en-US").NumberFormat };
+ yield return new object[] { CultureInfo.GetCultureInfo("fr-FR").NumberFormat };
}
[Theory]
diff --git a/src/System.Globalization/tests/NumberFormatInfo/NumberFormatInfoNegativeSign.cs b/src/System.Globalization/tests/NumberFormatInfo/NumberFormatInfoNegativeSign.cs
index 1bf3bb1411..5949f328ea 100644
--- a/src/System.Globalization/tests/NumberFormatInfo/NumberFormatInfoNegativeSign.cs
+++ b/src/System.Globalization/tests/NumberFormatInfo/NumberFormatInfoNegativeSign.cs
@@ -12,7 +12,7 @@ namespace System.Globalization.Tests
public static IEnumerable<object[]> NegativeSign_TestData()
{
yield return new object[] { NumberFormatInfo.InvariantInfo, "-" };
- yield return new object[] { new CultureInfo("en-US").NumberFormat, "-" };
+ yield return new object[] { CultureInfo.GetCultureInfo("en-US").NumberFormat, "-" };
}
[Theory]
diff --git a/src/System.Globalization/tests/NumberFormatInfo/NumberFormatInfoNumberDecimalDigits.cs b/src/System.Globalization/tests/NumberFormatInfo/NumberFormatInfoNumberDecimalDigits.cs
index 26da474545..030d28bb21 100644
--- a/src/System.Globalization/tests/NumberFormatInfo/NumberFormatInfoNumberDecimalDigits.cs
+++ b/src/System.Globalization/tests/NumberFormatInfo/NumberFormatInfoNumberDecimalDigits.cs
@@ -13,7 +13,7 @@ namespace System.Globalization.Tests
public static IEnumerable<object[]> NumberDecimalDigits_TestData()
{
yield return new object[] { NumberFormatInfo.InvariantInfo, 2, 2 };
- yield return new object[] { new CultureInfo("en-US").NumberFormat, 2, 3 };
+ yield return new object[] { CultureInfo.GetCultureInfo("en-US").NumberFormat, 2, 3 };
}
[Theory]
diff --git a/src/System.Globalization/tests/NumberFormatInfo/NumberFormatInfoNumberGroupSizes.cs b/src/System.Globalization/tests/NumberFormatInfo/NumberFormatInfoNumberGroupSizes.cs
index 31752d563a..fa16372e29 100644
--- a/src/System.Globalization/tests/NumberFormatInfo/NumberFormatInfoNumberGroupSizes.cs
+++ b/src/System.Globalization/tests/NumberFormatInfo/NumberFormatInfoNumberGroupSizes.cs
@@ -12,12 +12,12 @@ namespace System.Globalization.Tests
public static IEnumerable<object[]> NumberGroupSizes_TestData()
{
yield return new object[] { NumberFormatInfo.InvariantInfo, new int[] { 3 } };
- yield return new object[] { new CultureInfo("en-US").NumberFormat, new int[] { 3 } };
+ yield return new object[] { CultureInfo.GetCultureInfo("en-US").NumberFormat, new int[] { 3 } };
// Culture does not exist on Windows 7
if (!PlatformDetection.IsWindows7)
{
- yield return new object[] { new CultureInfo("ur-IN").NumberFormat, NumberFormatInfoData.UrINNumberGroupSizes() };
+ yield return new object[] { CultureInfo.GetCultureInfo("ur-IN").NumberFormat, NumberFormatInfoData.UrINNumberGroupSizes() };
}
}
diff --git a/src/System.Globalization/tests/NumberFormatInfo/NumberFormatInfoNumberNegativePattern.cs b/src/System.Globalization/tests/NumberFormatInfo/NumberFormatInfoNumberNegativePattern.cs
index aafacb9c2c..516fa21f7d 100644
--- a/src/System.Globalization/tests/NumberFormatInfo/NumberFormatInfoNumberNegativePattern.cs
+++ b/src/System.Globalization/tests/NumberFormatInfo/NumberFormatInfoNumberNegativePattern.cs
@@ -12,7 +12,7 @@ namespace System.Globalization.Tests
public static IEnumerable<object[]> NumberNegativePattern_TestData()
{
yield return new object[] { NumberFormatInfo.InvariantInfo, 1 };
- yield return new object[] { new CultureInfo("en-US").NumberFormat, 1 };
+ yield return new object[] { CultureInfo.GetCultureInfo("en-US").NumberFormat, 1 };
}
[Theory]
diff --git a/src/System.Globalization/tests/NumberFormatInfo/NumberFormatInfoPercentGroupSizes.cs b/src/System.Globalization/tests/NumberFormatInfo/NumberFormatInfoPercentGroupSizes.cs
index f20884a9b2..8a0320979f 100644
--- a/src/System.Globalization/tests/NumberFormatInfo/NumberFormatInfoPercentGroupSizes.cs
+++ b/src/System.Globalization/tests/NumberFormatInfo/NumberFormatInfoPercentGroupSizes.cs
@@ -12,7 +12,7 @@ namespace System.Globalization.Tests
public static IEnumerable<object[]> PercentGroupSizes_TestData()
{
yield return new object[] { NumberFormatInfo.InvariantInfo, new int[] { 3 } };
- yield return new object[] { new CultureInfo("en-US").NumberFormat, new int[] { 3 } };
+ yield return new object[] { CultureInfo.GetCultureInfo("en-US").NumberFormat, new int[] { 3 } };
}
[Theory]
diff --git a/src/System.Globalization/tests/NumberFormatInfo/NumberFormatInfoPercentNegativePattern.cs b/src/System.Globalization/tests/NumberFormatInfo/NumberFormatInfoPercentNegativePattern.cs
index 5e750d1190..bd1afebef4 100644
--- a/src/System.Globalization/tests/NumberFormatInfo/NumberFormatInfoPercentNegativePattern.cs
+++ b/src/System.Globalization/tests/NumberFormatInfo/NumberFormatInfoPercentNegativePattern.cs
@@ -12,9 +12,9 @@ namespace System.Globalization.Tests
{
public static IEnumerable<object[]> PercentNegativePattern_TestData()
{
- yield return new object[] { new CultureInfo("en-US").NumberFormat, 1 };
- yield return new object[] { new CultureInfo("en-MY").NumberFormat, 1 };
- yield return new object[] { new CultureInfo("tr").NumberFormat, 2 };
+ yield return new object[] { CultureInfo.GetCultureInfo("en-US").NumberFormat, 1 };
+ yield return new object[] { CultureInfo.GetCultureInfo("en-MY").NumberFormat, 1 };
+ yield return new object[] { CultureInfo.GetCultureInfo("tr").NumberFormat, 2 };
}
/// <summary>
diff --git a/src/System.Globalization/tests/NumberFormatInfo/NumberFormatInfoPercentPositivePattern.cs b/src/System.Globalization/tests/NumberFormatInfo/NumberFormatInfoPercentPositivePattern.cs
index 8211d28999..5f595dc76a 100644
--- a/src/System.Globalization/tests/NumberFormatInfo/NumberFormatInfoPercentPositivePattern.cs
+++ b/src/System.Globalization/tests/NumberFormatInfo/NumberFormatInfoPercentPositivePattern.cs
@@ -12,9 +12,9 @@ namespace System.Globalization.Tests
{
public static IEnumerable<object[]> PercentPositivePattern_TestData()
{
- yield return new object[] { new CultureInfo("en-US").NumberFormat, 1 };
- yield return new object[] { new CultureInfo("en-MY").NumberFormat, 1 };
- yield return new object[] { new CultureInfo("tr").NumberFormat, 2 };
+ yield return new object[] { CultureInfo.GetCultureInfo("en-US").NumberFormat, 1 };
+ yield return new object[] { CultureInfo.GetCultureInfo("en-MY").NumberFormat, 1 };
+ yield return new object[] { CultureInfo.GetCultureInfo("tr").NumberFormat, 2 };
}
/// <summary>
diff --git a/src/System.Globalization/tests/NumberFormatInfo/NumberFormatInfoPercentSymbol.cs b/src/System.Globalization/tests/NumberFormatInfo/NumberFormatInfoPercentSymbol.cs
index 37973c2c66..c13cdfd8a9 100644
--- a/src/System.Globalization/tests/NumberFormatInfo/NumberFormatInfoPercentSymbol.cs
+++ b/src/System.Globalization/tests/NumberFormatInfo/NumberFormatInfoPercentSymbol.cs
@@ -12,7 +12,7 @@ namespace System.Globalization.Tests
public static IEnumerable<object[]> PercentSymbol_TestData()
{
yield return new object[] { NumberFormatInfo.InvariantInfo, "%" };
- yield return new object[] { new CultureInfo("en-US").NumberFormat, "%" };
+ yield return new object[] { CultureInfo.GetCultureInfo("en-US").NumberFormat, "%" };
}
[Theory]
diff --git a/src/System.Globalization/tests/NumberFormatInfo/NumberFormatInfoPositiveInfinitySymbol.cs b/src/System.Globalization/tests/NumberFormatInfo/NumberFormatInfoPositiveInfinitySymbol.cs
index 9cbef54072..21f7a42cab 100644
--- a/src/System.Globalization/tests/NumberFormatInfo/NumberFormatInfoPositiveInfinitySymbol.cs
+++ b/src/System.Globalization/tests/NumberFormatInfo/NumberFormatInfoPositiveInfinitySymbol.cs
@@ -12,8 +12,8 @@ namespace System.Globalization.Tests
public static IEnumerable<object[]> PositiveInfinitySymbol_TestData()
{
yield return new object[] { NumberFormatInfo.InvariantInfo };
- yield return new object[] { new CultureInfo("en-US").NumberFormat };
- yield return new object[] { new CultureInfo("fr-FR").NumberFormat };
+ yield return new object[] { CultureInfo.GetCultureInfo("en-US").NumberFormat };
+ yield return new object[] { CultureInfo.GetCultureInfo("fr-FR").NumberFormat };
}
[Theory]
diff --git a/src/System.Globalization/tests/NumberFormatInfo/NumberFormatInfoPositiveSign.cs b/src/System.Globalization/tests/NumberFormatInfo/NumberFormatInfoPositiveSign.cs
index ffc2e677cd..92b8bf9ff8 100644
--- a/src/System.Globalization/tests/NumberFormatInfo/NumberFormatInfoPositiveSign.cs
+++ b/src/System.Globalization/tests/NumberFormatInfo/NumberFormatInfoPositiveSign.cs
@@ -12,7 +12,7 @@ namespace System.Globalization.Tests
public static IEnumerable<object[]> PositiveSign_TestData()
{
yield return new object[] { NumberFormatInfo.InvariantInfo, "+" };
- yield return new object[] { new CultureInfo("en-US").NumberFormat, "+" };
+ yield return new object[] { CultureInfo.GetCultureInfo("en-US").NumberFormat, "+" };
}
[Theory]
diff --git a/src/System.IO.Compression/src/System/IO/Compression/DeflateManaged/OutputWindow.cs b/src/System.IO.Compression/src/System/IO/Compression/DeflateManaged/OutputWindow.cs
index f182c548eb..df3cf010e0 100644
--- a/src/System.IO.Compression/src/System/IO/Compression/DeflateManaged/OutputWindow.cs
+++ b/src/System.IO.Compression/src/System/IO/Compression/DeflateManaged/OutputWindow.cs
@@ -17,7 +17,7 @@ namespace System.IO.Compression
{
// With Deflate64 we can have up to a 65536 length as well as up to a 65538 distance. This means we need a Window that is at
// least 131074 bytes long so we have space to retrieve up to a full 64kb in lookback and place it in our buffer without
- // overwriting existing data. OutputWindow requires that the WindowSize be a exponent of 2, so we round up to 2^18.
+ // overwriting existing data. OutputWindow requires that the WindowSize be an exponent of 2, so we round up to 2^18.
private const int WindowSize = 262144;
private const int WindowMask = 262143;
diff --git a/src/System.IO.Compression/src/System/IO/Compression/DeflateZLib/DeflateStream.cs b/src/System.IO.Compression/src/System/IO/Compression/DeflateZLib/DeflateStream.cs
index 0fd76a3e8f..9371a98fdd 100644
--- a/src/System.IO.Compression/src/System/IO/Compression/DeflateZLib/DeflateStream.cs
+++ b/src/System.IO.Compression/src/System/IO/Compression/DeflateZLib/DeflateStream.cs
@@ -352,58 +352,73 @@ namespace System.IO.Compression
public override Task<int> ReadAsync(byte[] array, int offset, int count, CancellationToken cancellationToken)
{
- // We use this checking order for compat to earlier versions:
+ ValidateParameters(array, offset, count);
+ return ReadAsyncMemory(new Memory<byte>(array, offset, count), cancellationToken).AsTask();
+ }
+
+ public override ValueTask<int> ReadAsync(Memory<byte> destination, CancellationToken cancellationToken = default(CancellationToken))
+ {
+ if (GetType() != typeof(DeflateStream))
+ {
+ // Ensure that existing streams derived from DeflateStream and that override ReadAsync(byte[],...)
+ // get their existing behaviors when the newer Memory-based overload is used.
+ return base.ReadAsync(destination, cancellationToken);
+ }
+ else
+ {
+ return ReadAsyncMemory(destination, cancellationToken);
+ }
+ }
+
+ internal ValueTask<int> ReadAsyncMemory(Memory<byte> destination, CancellationToken cancellationToken)
+ {
EnsureDecompressionMode();
EnsureNoActiveAsyncOperation();
- ValidateParameters(array, offset, count);
EnsureNotDisposed();
if (cancellationToken.IsCancellationRequested)
{
- return Task.FromCanceled<int>(cancellationToken);
+ return new ValueTask<int>(Task.FromCanceled<int>(cancellationToken));
}
EnsureBufferInitialized();
- Task<int> readTask = null;
+ bool cleanup = true;
AsyncOperationStarting();
try
{
// Try to read decompressed data in output buffer
- int bytesRead = _inflater.Inflate(array, offset, count);
+ int bytesRead = _inflater.Inflate(destination.Span);
if (bytesRead != 0)
{
// If decompression output buffer is not empty, return immediately.
- return Task.FromResult(bytesRead);
+ return new ValueTask<int>(bytesRead);
}
if (_inflater.Finished())
{
// end of compression stream
- return Task.FromResult(0);
+ return new ValueTask<int>(0);
}
// If there is no data on the output buffer and we are not at
// the end of the stream, we need to get more data from the base stream
- readTask = _stream.ReadAsync(_buffer, 0, _buffer.Length, cancellationToken);
- if (readTask == null)
- {
- throw new InvalidOperationException(SR.NotSupported_UnreadableStream);
- }
-
- return ReadAsyncCore(readTask, array, offset, count, cancellationToken);
+ ValueTask<int> readTask = _stream.ReadAsync(_buffer, cancellationToken);
+ cleanup = false;
+ return FinishReadAsyncMemory(readTask, destination, cancellationToken);
}
finally
{
// if we haven't started any async work, decrement the counter to end the transaction
- if (readTask == null)
+ if (cleanup)
{
AsyncOperationCompleting();
}
}
}
- private async Task<int> ReadAsyncCore(Task<int> readTask, byte[] array, int offset, int count, CancellationToken cancellationToken)
+ private async ValueTask<int> FinishReadAsyncMemory(
+ ValueTask<int> readTask, Memory<byte> destination, CancellationToken cancellationToken)
{
try
{
@@ -428,17 +443,13 @@ namespace System.IO.Compression
// Feed the data from base stream into decompression engine
_inflater.SetInput(_buffer, 0, bytesRead);
- bytesRead = _inflater.Inflate(array, offset, count);
+ bytesRead = _inflater.Inflate(destination.Span);
if (bytesRead == 0 && !_inflater.Finished())
{
// We could have read in head information and didn't get any data.
// Read from the base stream again.
- readTask = _stream.ReadAsync(_buffer, 0, _buffer.Length, cancellationToken);
- if (readTask == null)
- {
- throw new InvalidOperationException(SR.NotSupported_UnreadableStream);
- }
+ readTask = _stream.ReadAsync(_buffer, cancellationToken);
}
else
{
@@ -632,19 +643,36 @@ namespace System.IO.Compression
public override Task WriteAsync(byte[] array, int offset, int count, CancellationToken cancellationToken)
{
- // We use this checking order for compat to earlier versions:
+ ValidateParameters(array, offset, count);
+ return WriteAsyncMemory(new ReadOnlyMemory<byte>(array, offset, count), cancellationToken);
+ }
+
+ public override Task WriteAsync(ReadOnlyMemory<byte> source, CancellationToken cancellationToken)
+ {
+ if (GetType() != typeof(DeflateStream))
+ {
+ // Ensure that existing streams derived from DeflateStream and that override WriteAsync(byte[],...)
+ // get their existing behaviors when the newer Memory-based overload is used.
+ return base.WriteAsync(source, cancellationToken);
+ }
+ else
+ {
+ return WriteAsyncMemory(source, cancellationToken);
+ }
+ }
+
+ internal Task WriteAsyncMemory(ReadOnlyMemory<byte> source, CancellationToken cancellationToken)
+ {
EnsureCompressionMode();
EnsureNoActiveAsyncOperation();
- ValidateParameters(array, offset, count);
EnsureNotDisposed();
- if (cancellationToken.IsCancellationRequested)
- return Task.FromCanceled<int>(cancellationToken);
-
- return WriteAsyncCore(array, offset, count, cancellationToken);
+ return cancellationToken.IsCancellationRequested ?
+ Task.FromCanceled<int>(cancellationToken) :
+ WriteAsyncMemoryCore(source, cancellationToken);
}
- private async Task WriteAsyncCore(byte[] array, int offset, int count, CancellationToken cancellationToken)
+ private async Task WriteAsyncMemoryCore(ReadOnlyMemory<byte> source, CancellationToken cancellationToken)
{
AsyncOperationStarting();
try
@@ -652,7 +680,7 @@ namespace System.IO.Compression
await WriteDeflaterOutputAsync(cancellationToken).ConfigureAwait(false);
// Pass new bytes through deflater
- _deflater.SetInput(array, offset, count);
+ _deflater.SetInput(source);
await WriteDeflaterOutputAsync(cancellationToken).ConfigureAwait(false);
diff --git a/src/System.IO.Compression/src/System/IO/Compression/DeflateZLib/Deflater.cs b/src/System.IO.Compression/src/System/IO/Compression/DeflateZLib/Deflater.cs
index eea84cb203..35cd2af261 100644
--- a/src/System.IO.Compression/src/System/IO/Compression/DeflateZLib/Deflater.cs
+++ b/src/System.IO.Compression/src/System/IO/Compression/DeflateZLib/Deflater.cs
@@ -2,9 +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.Buffers;
using System.Diagnostics;
using System.Diagnostics.Contracts;
-using System.Runtime.InteropServices;
using System.Security;
using ZErrorCode = System.IO.Compression.ZLibNative.ErrorCode;
@@ -18,7 +18,7 @@ namespace System.IO.Compression
internal sealed class Deflater : IDisposable
{
private ZLibNative.ZLibStreamHandle _zlibStream;
- private GCHandle _inputBufferHandle;
+ private MemoryHandle _inputBufferHandle;
private bool _isDisposed;
private const int minWindowBits = -15; // WindowBits must be between -8..-15 to write no header, 8..15 for a
private const int maxWindowBits = 31; // zlib header, or 24..31 for a GZip header
@@ -90,22 +90,22 @@ namespace System.IO.Compression
public bool NeedsInput() => 0 == _zlibStream.AvailIn;
- internal void SetInput(byte[] inputBuffer, int startIndex, int count)
+ internal unsafe void SetInput(ReadOnlyMemory<byte> inputBuffer)
{
Debug.Assert(NeedsInput(), "We have something left in previous input!");
- Debug.Assert(null != inputBuffer);
- Debug.Assert(startIndex >= 0 && count >= 0 && count + startIndex <= inputBuffer.Length);
- Debug.Assert(!_inputBufferHandle.IsAllocated);
+ Debug.Assert(_inputBufferHandle.PinnedPointer == null);
- if (0 == count)
+ if (0 == inputBuffer.Length)
+ {
return;
+ }
lock (SyncLock)
{
- _inputBufferHandle = GCHandle.Alloc(inputBuffer, GCHandleType.Pinned);
+ _inputBufferHandle = inputBuffer.Retain(pin: true);
- _zlibStream.NextIn = _inputBufferHandle.AddrOfPinnedObject() + startIndex;
- _zlibStream.AvailIn = (uint)count;
+ _zlibStream.NextIn = (IntPtr)_inputBufferHandle.PinnedPointer;
+ _zlibStream.AvailIn = (uint)inputBuffer.Length;
}
}
@@ -113,7 +113,7 @@ namespace System.IO.Compression
{
Debug.Assert(NeedsInput(), "We have something left in previous input!");
Debug.Assert(inputBufferPtr != null);
- Debug.Assert(!_inputBufferHandle.IsAllocated);
+ Debug.Assert(_inputBufferHandle.PinnedPointer == null);
if (count == 0)
{
@@ -174,7 +174,10 @@ namespace System.IO.Compression
Debug.Assert(null != outputBuffer, "Can't pass in a null output buffer!");
Debug.Assert(outputBuffer.Length > 0, "Can't pass in an empty output buffer!");
Debug.Assert(NeedsInput(), "We have something left in previous input!");
- Debug.Assert(!_inputBufferHandle.IsAllocated);
+ unsafe
+ {
+ Debug.Assert(_inputBufferHandle.PinnedPointer == null);
+ }
// Note: we require that NeedsInput() == true, i.e. that 0 == _zlibStream.AvailIn.
// If there is still input left we should never be getting here; instead we
@@ -192,7 +195,10 @@ namespace System.IO.Compression
Debug.Assert(null != outputBuffer, "Can't pass in a null output buffer!");
Debug.Assert(outputBuffer.Length > 0, "Can't pass in an empty output buffer!");
Debug.Assert(NeedsInput(), "We have something left in previous input!");
- Debug.Assert(!_inputBufferHandle.IsAllocated);
+ unsafe
+ {
+ Debug.Assert(_inputBufferHandle.PinnedPointer == null);
+ }
// Note: we require that NeedsInput() == true, i.e. that 0 == _zlibStream.AvailIn.
// If there is still input left we should never be getting here; instead we
@@ -207,10 +213,7 @@ namespace System.IO.Compression
{
_zlibStream.AvailIn = 0;
_zlibStream.NextIn = ZLibNative.ZNullPtr;
- if (_inputBufferHandle.IsAllocated)
- {
- _inputBufferHandle.Free();
- }
+ _inputBufferHandle.Dispose();
}
}
diff --git a/src/System.IO.Compression/src/System/IO/Compression/GZipStream.cs b/src/System.IO.Compression/src/System/IO/Compression/GZipStream.cs
index 0dd59aba4c..4796b9b39b 100644
--- a/src/System.IO.Compression/src/System/IO/Compression/GZipStream.cs
+++ b/src/System.IO.Compression/src/System/IO/Compression/GZipStream.cs
@@ -120,7 +120,6 @@ namespace System.IO.Compression
// to this Write(ReadOnlySpan<byte>) overload being introduced. In that case, this Write(ReadOnlySpan<byte>) overload
// should use the behavior of Write(byte[],int,int) overload.
base.Write(source);
- return;
}
else
{
@@ -159,12 +158,44 @@ namespace System.IO.Compression
return _deflateStream.ReadAsync(array, offset, count, cancellationToken);
}
+ public override ValueTask<int> ReadAsync(Memory<byte> destination, CancellationToken cancellationToken = default(CancellationToken))
+ {
+ if (GetType() != typeof(GZipStream))
+ {
+ // GZipStream is not sealed, and a derived type may have overridden ReadAsync(byte[], int, int) prior
+ // to this ReadAsync(Memory<byte>) overload being introduced. In that case, this ReadAsync(Memory<byte>) overload
+ // should use the behavior of ReadAsync(byte[],int,int) overload.
+ return base.ReadAsync(destination, cancellationToken);
+ }
+ else
+ {
+ CheckDeflateStream();
+ return _deflateStream.ReadAsyncMemory(destination, cancellationToken);
+ }
+ }
+
public override Task WriteAsync(byte[] array, int offset, int count, CancellationToken cancellationToken)
{
CheckDeflateStream();
return _deflateStream.WriteAsync(array, offset, count, cancellationToken);
}
+ public override Task WriteAsync(ReadOnlyMemory<byte> source, CancellationToken cancellationToken = default(CancellationToken))
+ {
+ if (GetType() != typeof(GZipStream))
+ {
+ // GZipStream is not sealed, and a derived type may have overridden WriteAsync(byte[], int, int) prior
+ // to this WriteAsync(ReadOnlyMemory<byte>) overload being introduced. In that case, this
+ // WriteAsync(ReadOnlyMemory<byte>) overload should use the behavior of Write(byte[],int,int) overload.
+ return base.WriteAsync(source, cancellationToken);
+ }
+ else
+ {
+ CheckDeflateStream();
+ return _deflateStream.WriteAsyncMemory(source, cancellationToken);
+ }
+ }
+
public override Task FlushAsync(CancellationToken cancellationToken)
{
CheckDeflateStream();
diff --git a/src/System.IO.Compression/src/System/IO/Compression/PositionPreservingWriteOnlyStreamWrapper.netcoreapp.cs b/src/System.IO.Compression/src/System/IO/Compression/PositionPreservingWriteOnlyStreamWrapper.netcoreapp.cs
index fd22f7a5fb..1c5aa7b6e2 100644
--- a/src/System.IO.Compression/src/System/IO/Compression/PositionPreservingWriteOnlyStreamWrapper.netcoreapp.cs
+++ b/src/System.IO.Compression/src/System/IO/Compression/PositionPreservingWriteOnlyStreamWrapper.netcoreapp.cs
@@ -2,6 +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.Threading;
+using System.Threading.Tasks;
+
namespace System.IO.Compression
{
internal sealed partial class PositionPreservingWriteOnlyStreamWrapper : Stream
@@ -11,5 +14,11 @@ namespace System.IO.Compression
_position += source.Length;
_stream.Write(source);
}
+
+ public override Task WriteAsync(ReadOnlyMemory<byte> source, CancellationToken cancellationToken = default(CancellationToken))
+ {
+ _position += source.Length;
+ return _stream.WriteAsync(source, cancellationToken);
+ }
}
}
diff --git a/src/System.IO.Compression/src/System/IO/Compression/ZipArchiveEntry.cs b/src/System.IO.Compression/src/System/IO/Compression/ZipArchiveEntry.cs
index 3f13ca44e0..842090b27d 100644
--- a/src/System.IO.Compression/src/System/IO/Compression/ZipArchiveEntry.cs
+++ b/src/System.IO.Compression/src/System/IO/Compression/ZipArchiveEntry.cs
@@ -460,7 +460,7 @@ namespace System.IO.Compression
BinaryWriter writer = new BinaryWriter(_archive.ArchiveStream);
// _entryname only gets set when we read in or call moveTo. MoveTo does a check, and
- // reading in should not be able to produce a entryname longer than ushort.MaxValue
+ // reading in should not be able to produce an entryname longer than ushort.MaxValue
Debug.Assert(_storedEntryNameBytes.Length <= ushort.MaxValue);
// decide if we need the Zip64 extra field:
@@ -786,7 +786,7 @@ namespace System.IO.Compression
BinaryWriter writer = new BinaryWriter(_archive.ArchiveStream);
// _entryname only gets set when we read in or call moveTo. MoveTo does a check, and
- // reading in should not be able to produce a entryname longer than ushort.MaxValue
+ // reading in should not be able to produce an entryname longer than ushort.MaxValue
Debug.Assert(_storedEntryNameBytes.Length <= ushort.MaxValue);
// decide if we need the Zip64 extra field:
diff --git a/src/System.IO.Compression/tests/Configurations.props b/src/System.IO.Compression/tests/Configurations.props
index 742254e254..e245e48733 100644
--- a/src/System.IO.Compression/tests/Configurations.props
+++ b/src/System.IO.Compression/tests/Configurations.props
@@ -6,6 +6,7 @@
netstandard-Windows_NT;
netcoreapp-Unix;
netcoreapp-Windows_NT;
+ uap-Windows_NT;
</BuildConfigurations>
</PropertyGroup>
</Project> \ No newline at end of file
diff --git a/src/System.IO.Compression/tests/DeflateStreamTests.cs b/src/System.IO.Compression/tests/DeflateStreamTests.cs
index f214ccaae7..e2cf6737f7 100644
--- a/src/System.IO.Compression/tests/DeflateStreamTests.cs
+++ b/src/System.IO.Compression/tests/DeflateStreamTests.cs
@@ -440,14 +440,15 @@ namespace System.IO.Compression.Tests
{
SyncArray,
SyncSpan,
- AsyncArray
+ AsyncArray,
+ AsyncMemory
}
public static IEnumerable<object[]> RoundtripCompressDecompressOuterData
{
get
{
- foreach (ReadWriteMode readWriteMode in new[] { ReadWriteMode.SyncArray, ReadWriteMode.SyncSpan, ReadWriteMode.AsyncArray })
+ foreach (ReadWriteMode readWriteMode in new[] { ReadWriteMode.SyncArray, ReadWriteMode.SyncSpan, ReadWriteMode.AsyncArray, ReadWriteMode.AsyncMemory })
{
foreach (bool useGzip in new[] { true, false }) // whether to add on gzip headers/footers
{
@@ -493,6 +494,9 @@ namespace System.IO.Compression.Tests
case ReadWriteMode.SyncSpan:
compressor.Write(new ReadOnlySpan<byte>(data, i, chunkSize));
break;
+ case ReadWriteMode.AsyncMemory:
+ await compressor.WriteAsync(new ReadOnlyMemory<byte>(data, i, chunkSize));
+ break;
}
}
}
@@ -534,11 +538,15 @@ namespace System.IO.Compression.Tests
case ReadWriteMode.SyncSpan:
compressor.Write(new ReadOnlySpan<byte>(data, i, chunkSize));
break;
+ case ReadWriteMode.AsyncMemory:
+ await compressor.WriteAsync(new ReadOnlyMemory<byte>(data, i, chunkSize));
+ break;
}
}
switch (readWriteMode)
{
case ReadWriteMode.AsyncArray:
+ case ReadWriteMode.AsyncMemory:
await compressor.FlushAsync();
break;
case ReadWriteMode.SyncSpan:
@@ -585,6 +593,9 @@ namespace System.IO.Compression.Tests
case ReadWriteMode.SyncSpan:
compressor.Write(new ReadOnlySpan<byte>(data, i, chunkSize));
break;
+ case ReadWriteMode.AsyncMemory:
+ await compressor.WriteAsync(new ReadOnlyMemory<byte>(data, i, chunkSize));
+ break;
}
for (int j = i; j < i + chunkSize; j++)
expected.Insert(j, data[j]);
@@ -592,6 +603,7 @@ namespace System.IO.Compression.Tests
switch (readWriteMode)
{
case ReadWriteMode.AsyncArray:
+ case ReadWriteMode.AsyncMemory:
await compressor.FlushAsync();
break;
case ReadWriteMode.SyncSpan:
@@ -630,6 +642,7 @@ namespace System.IO.Compression.Tests
switch (readWriteMode)
{
case ReadWriteMode.AsyncArray:
+ case ReadWriteMode.AsyncMemory:
await compressor.FlushAsync();
break;
case ReadWriteMode.SyncSpan:
@@ -651,12 +664,16 @@ namespace System.IO.Compression.Tests
case ReadWriteMode.SyncSpan:
compressor.Write(new ReadOnlySpan<byte>(data, i, chunkSize));
break;
+ case ReadWriteMode.AsyncMemory:
+ await compressor.WriteAsync(new ReadOnlyMemory<byte>(data, i, chunkSize));
+ break;
}
}
switch (readWriteMode)
{
case ReadWriteMode.AsyncArray:
+ case ReadWriteMode.AsyncMemory:
await compressor.FlushAsync();
break;
case ReadWriteMode.SyncSpan:
@@ -700,6 +717,12 @@ namespace System.IO.Compression.Tests
decompressed.Write(buffer, 0, bytesRead);
}
break;
+ case ReadWriteMode.AsyncMemory:
+ while ((bytesRead = await decompressor.ReadAsync(new Memory<byte>(buffer))) != 0)
+ {
+ decompressed.Write(buffer, 0, bytesRead);
+ }
+ break;
}
Assert.Equal<byte>(expected, decompressed.ToArray());
}
@@ -710,6 +733,8 @@ namespace System.IO.Compression.Tests
[InlineData(ReadWriteMode.AsyncArray, false)]
[InlineData(ReadWriteMode.SyncSpan, false)]
[InlineData(ReadWriteMode.SyncSpan, true)]
+ [InlineData(ReadWriteMode.AsyncMemory, false)]
+ [InlineData(ReadWriteMode.AsyncMemory, true)]
public async Task SequentialReadsOnMemoryStream_Return_SameBytes(ReadWriteMode readWriteMode, bool derived)
{
byte[] data = new byte[1024 * 10];
@@ -727,6 +752,7 @@ namespace System.IO.Compression.Tests
case ReadWriteMode.SyncArray: compressor.Write(data, i, 1024); break;
case ReadWriteMode.AsyncArray: await compressor.WriteAsync(data, i, 1024); break;
case ReadWriteMode.SyncSpan: compressor.Write(new Span<byte>(data, i, 1024)); break;
+ case ReadWriteMode.AsyncMemory: await compressor.WriteAsync(new ReadOnlyMemory<byte>(data, i, 1024)); break;
}
}
@@ -750,6 +776,7 @@ namespace System.IO.Compression.Tests
case ReadWriteMode.SyncArray: decompressor.Read(array, 0, array.Length); break;
case ReadWriteMode.AsyncArray: await decompressor.ReadAsync(array, 0, array.Length); break;
case ReadWriteMode.SyncSpan: decompressor.Read(new Span<byte>(array)); break;
+ case ReadWriteMode.AsyncMemory: await decompressor.ReadAsync(new Memory<byte>(array)); break;
}
for (i = 0; i < array.Length; i++)
{
@@ -762,6 +789,7 @@ namespace System.IO.Compression.Tests
case ReadWriteMode.SyncArray: decompressor.Read(array2, 0, array2.Length); break;
case ReadWriteMode.AsyncArray: await decompressor.ReadAsync(array2, 0, array2.Length); break;
case ReadWriteMode.SyncSpan: decompressor.Read(new Span<byte>(array2)); break;
+ case ReadWriteMode.AsyncMemory: await decompressor.ReadAsync(new Memory<byte>(array2)); break;
}
for (j = 0; j < array2.Length; j++)
{
@@ -799,7 +827,7 @@ namespace System.IO.Compression.Tests
public async Task WrapNullReturningTasksStream()
{
using (var ds = new DeflateStream(new BadWrappedStream(BadWrappedStream.Mode.ReturnNullTasks), CompressionMode.Decompress))
- await Assert.ThrowsAsync<InvalidOperationException>(() => ds.ReadAsync(new byte[1024], 0, 1024));
+ await Assert.ThrowsAsync<ArgumentNullException>(() => ds.ReadAsync(new byte[1024], 0, 1024));
}
[Fact]
@@ -810,11 +838,15 @@ namespace System.IO.Compression.Tests
Assert.Throws<InvalidDataException>(() => ds.Read(new byte[1024], 0, 1024));
using (var ds = new DeflateStream(new BadWrappedStream(BadWrappedStream.Mode.ReturnTooLargeCounts), CompressionMode.Decompress))
await Assert.ThrowsAsync<InvalidDataException>(() => ds.ReadAsync(new byte[1024], 0, 1024));
+ using (var ds = new DeflateStream(new BadWrappedStream(BadWrappedStream.Mode.ReturnTooLargeCounts), CompressionMode.Decompress))
+ await Assert.ThrowsAsync<InvalidDataException>(async () => { await ds.ReadAsync(new Memory<byte>(new byte[1024])); });
using (var ds = new DeflateStream(new BadWrappedStream(BadWrappedStream.Mode.ReturnTooSmallCounts), CompressionMode.Decompress))
Assert.Equal(0, ds.Read(new byte[1024], 0, 1024));
using (var ds = new DeflateStream(new BadWrappedStream(BadWrappedStream.Mode.ReturnTooSmallCounts), CompressionMode.Decompress))
Assert.Equal(0, await ds.ReadAsync(new byte[1024], 0, 1024));
+ using (var ds = new DeflateStream(new BadWrappedStream(BadWrappedStream.Mode.ReturnTooSmallCounts), CompressionMode.Decompress))
+ Assert.Equal(0, await ds.ReadAsync(new Memory<byte>(new byte[1024])));
}
public static IEnumerable<object[]> CopyToAsync_Roundtrip_OutputMatchesInput_MemberData()
@@ -933,7 +965,7 @@ namespace System.IO.Compression.Tests
}
}
- public class ManualSyncMemoryStream : MemoryStream
+ public partial class ManualSyncMemoryStream : MemoryStream
{
private bool isSync;
public ManualResetEventSlim manualResetEvent = new ManualResetEventSlim(initialState: false);
diff --git a/src/System.IO.Compression/tests/DeflateStreamTests.netcoreapp.cs b/src/System.IO.Compression/tests/DeflateStreamTests.netcoreapp.cs
new file mode 100644
index 0000000000..bcbe5d463a
--- /dev/null
+++ b/src/System.IO.Compression/tests/DeflateStreamTests.netcoreapp.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.Threading;
+using System.Threading.Tasks;
+
+namespace System.IO.Compression.Tests
+{
+ public partial class ManualSyncMemoryStream : MemoryStream
+ {
+ public override ValueTask<int> ReadAsync(Memory<byte> destination, CancellationToken cancellationToken)
+ {
+ ReadHit = true;
+ return base.ReadAsync(destination, cancellationToken);
+ }
+
+ public override Task WriteAsync(ReadOnlyMemory<byte> source, CancellationToken cancellationToken)
+ {
+ WriteHit = true;
+ return base.WriteAsync(source, cancellationToken);
+ }
+ }
+}
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 b64b6dae89..9496693e27 100644
--- a/src/System.IO.Compression/tests/System.IO.Compression.Tests.csproj
+++ b/src/System.IO.Compression/tests/System.IO.Compression.Tests.csproj
@@ -12,6 +12,8 @@
<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'" />
<ItemGroup>
<Compile Include="AsyncStreamTests.cs" />
<Compile Include="DeflateStreamTests.cs" />
@@ -52,8 +54,9 @@
<Link>Common\System\Threading\Tasks\TaskToApm.cs</Link>
</Compile>
</ItemGroup>
- <ItemGroup Condition="'$(TargetGroup)' == 'netcoreapp'">
+ <ItemGroup Condition="'$(TargetGroup)' == 'netcoreapp' or '$(TargetGroup)' == 'uap'">
<Compile Include="ZipArchive\zip_netcoreappTests.cs" />
+ <Compile Include="DeflateStreamTests.netcoreapp.cs" />
</ItemGroup>
<ItemGroup>
<SupplementalTestData Include="$(PackagesDir)system.io.compression.testdata\1.0.5-prerelease\content\**\*.*">
diff --git a/src/System.IO.FileSystem.DriveInfo/tests/DriveInfo.Windows.Tests.cs b/src/System.IO.FileSystem.DriveInfo/tests/DriveInfo.Windows.Tests.cs
index ec4cbdb4f4..ec841e5b22 100644
--- a/src/System.IO.FileSystem.DriveInfo/tests/DriveInfo.Windows.Tests.cs
+++ b/src/System.IO.FileSystem.DriveInfo/tests/DriveInfo.Windows.Tests.cs
@@ -80,7 +80,7 @@ namespace System.IO.FileSystem.DriveInfoTests
Assert.NotNull(validDrive.Name);
Assert.NotNull(validDrive.RootDirectory.Name);
- if (PlatformDetection.IsWinRT)
+ if (PlatformDetection.IsInAppContainer)
{
Assert.Throws<UnauthorizedAccessException>(() => validDrive.AvailableFreeSpace);
Assert.Throws<UnauthorizedAccessException>(() => validDrive.DriveFormat);
@@ -218,7 +218,7 @@ namespace System.IO.FileSystem.DriveInfoTests
}
};
- if (PlatformDetection.IsWinRT)
+ if (PlatformDetection.IsInAppContainer)
{
Assert.Throws<UnauthorizedAccessException>(() => DoDriveCheck());
}
@@ -234,7 +234,7 @@ namespace System.IO.FileSystem.DriveInfoTests
{
DriveInfo drive = DriveInfo.GetDrives().Where(d => d.DriveType == DriveType.Fixed).First();
// Inside an AppContainer access to VolumeLabel is denied.
- if (PlatformDetection.IsWinRT)
+ if (PlatformDetection.IsInAppContainer)
{
Assert.Throws<UnauthorizedAccessException>(() => drive.VolumeLabel);
return;
diff --git a/src/System.IO.FileSystem.Watcher/src/PinvokeAnalyzerExceptionList.analyzerdata.uap b/src/System.IO.FileSystem.Watcher/src/PinvokeAnalyzerExceptionList.analyzerdata.uap
deleted file mode 100644
index 0719fa0f9d..0000000000
--- a/src/System.IO.FileSystem.Watcher/src/PinvokeAnalyzerExceptionList.analyzerdata.uap
+++ /dev/null
@@ -1,3 +0,0 @@
-## need to create a uap config that uses CreateFileFromApp, then remove this baseline ##
-# https://github.com/dotnet/corefx/issues/21025
-kernel32.dll!CreateFileW \ No newline at end of file
diff --git a/src/System.IO.FileSystem.Watcher/src/System.IO.FileSystem.Watcher.csproj b/src/System.IO.FileSystem.Watcher/src/System.IO.FileSystem.Watcher.csproj
index 6fe4526ccb..91f7d75d8f 100644
--- a/src/System.IO.FileSystem.Watcher/src/System.IO.FileSystem.Watcher.csproj
+++ b/src/System.IO.FileSystem.Watcher/src/System.IO.FileSystem.Watcher.csproj
@@ -41,9 +41,6 @@
<Compile Include="$(CommonPath)\Interop\Windows\Interop.Libraries.cs">
<Link>Common\Interop\Windows\Interop.Libraries.cs</Link>
</Compile>
- <Compile Include="$(CommonPath)\Interop\Windows\kernel32\Interop.CreateFile.cs">
- <Link>Common\Interop\Windows\kernel32\Interop.CreateFile.cs</Link>
- </Compile>
<Compile Include="$(CommonPath)\Interop\Windows\Interop.BOOL.cs">
<Link>Common\Interop\Windows\Interop.BOOL.cs</Link>
</Compile>
@@ -58,6 +55,30 @@
</Compile>
<Compile Include="System\IO\FileSystemWatcher.Win32.cs" />
</ItemGroup>
+ <!-- Windows : Win32 only -->
+ <ItemGroup Condition="'$(TargetsWindows)' == 'true' and '$(TargetGroup)' != 'uap'">
+ <Compile Include="$(CommonPath)\Interop\Windows\kernel32\Interop.UnsafeCreateFile.cs">
+ <Link>Common\Interop\Windows\Interop.UnsafeCreateFile.cs</Link>
+ </Compile>
+ <Compile Include="$(CommonPath)\Interop\Windows\kernel32\Interop.CreateFile.cs">
+ <Link>Common\Interop\Windows\Interop.CreateFile.cs</Link>
+ </Compile>
+ </ItemGroup>
+ <!-- Windows : UAP - Win32 + WinRT -->
+ <ItemGroup Condition="'$(TargetsWindows)' == 'true' and '$(TargetGroup)' == 'uap'">
+ <Compile Include="$(CommonPath)\Interop\Windows\kernel32\Interop.CreateFile2.cs">
+ <Link>Common\Interop\Windows\Interop.CreateFile2.cs</Link>
+ </Compile>
+ <Compile Include="$(CommonPath)\Interop\Windows\kernel32\Interop.UnsafeCreateFile.uap.cs">
+ <Link>Common\Interop\Windows\Interop.UnsafeCreateFile.uap.cs</Link>
+ </Compile>
+ <Compile Include="$(CommonPath)\Interop\Windows\kernel32\Interop.COPYFILE2_EXTENDED_PARAMETERS.cs">
+ <Link>Common\Interop\Windows\Interop.COPYFILE2_EXTENDED_PARAMETERS.cs</Link>
+ </Compile>
+ <Compile Include="$(CommonPath)\Interop\Windows\kernel32\Interop.CREATEFILE2_EXTENDED_PARAMETERS.cs">
+ <Link>Common\Interop\Windows\Interop.CREATEFILE2_EXTENDED_PARAMETERS.cs</Link>
+ </Compile>
+ </ItemGroup>
<ItemGroup Condition=" '$(TargetsUnix)' == 'true'">
<Compile Include="$(CommonPath)\Interop\Unix\Interop.Libraries.cs">
<Link>Common\Interop\Unix\Interop.Libraries.cs</Link>
diff --git a/src/System.IO.FileSystem.Watcher/src/System/IO/FileSystemWatcher.Win32.cs b/src/System.IO.FileSystem.Watcher/src/System/IO/FileSystemWatcher.Win32.cs
index 541ada33b4..a0b8ae9d18 100644
--- a/src/System.IO.FileSystem.Watcher/src/System/IO/FileSystemWatcher.Win32.cs
+++ b/src/System.IO.FileSystem.Watcher/src/System/IO/FileSystemWatcher.Win32.cs
@@ -27,7 +27,7 @@ namespace System.IO
// Create handle to directory being monitored
var defaultSecAttrs = default(Interop.Kernel32.SECURITY_ATTRIBUTES);
- _directoryHandle = Interop.Kernel32.CreateFile(
+ _directoryHandle = Interop.Kernel32.UnsafeCreateFile(
lpFileName: _directory,
dwDesiredAccess: Interop.Kernel32.FileOperations.FILE_LIST_DIRECTORY,
dwShareMode: FileShare.Read | FileShare.Delete | FileShare.Write,
diff --git a/src/System.IO.FileSystem.Watcher/tests/FileSystemWatcher.File.Create.cs b/src/System.IO.FileSystem.Watcher/tests/FileSystemWatcher.File.Create.cs
index b9c8f44363..e6862ad3f6 100644
--- a/src/System.IO.FileSystem.Watcher/tests/FileSystemWatcher.File.Create.cs
+++ b/src/System.IO.FileSystem.Watcher/tests/FileSystemWatcher.File.Create.cs
@@ -11,6 +11,7 @@ namespace System.IO.Tests
public class File_Create_Tests : FileSystemWatcherTest
{
[Fact]
+ [ActiveIssue("https://github.com/dotnet/coreclr/issues/14154", TestPlatforms.AnyUnix)]
public void FileSystemWatcher_File_Create()
{
using (var testDirectory = new TempDirectory(GetTestFilePath()))
@@ -102,4 +103,4 @@ namespace System.IO.Tests
}
}
}
-} \ No newline at end of file
+}
diff --git a/src/System.IO.FileSystem.Watcher/tests/FileSystemWatcher.cs b/src/System.IO.FileSystem.Watcher/tests/FileSystemWatcher.cs
index 34347fd98e..284e6b372f 100644
--- a/src/System.IO.FileSystem.Watcher/tests/FileSystemWatcher.cs
+++ b/src/System.IO.FileSystem.Watcher/tests/FileSystemWatcher.cs
@@ -197,6 +197,7 @@ namespace System.IO.Tests
/// EndInit will begin EnableRaisingEvents if we previously set EnableRaisingEvents=true
/// </summary>
[Fact]
+ [ActiveIssue("https://github.com/dotnet/coreclr/issues/14154", TestPlatforms.AnyUnix)]
public void EndInit_ResumesPausedEnableRaisingEvents()
{
using (var testDirectory = new TempDirectory(GetTestFilePath()))
@@ -215,6 +216,7 @@ namespace System.IO.Tests
[Theory]
[InlineData(true)]
[InlineData(false)]
+ [ActiveIssue("https://github.com/dotnet/coreclr/issues/14154", TestPlatforms.AnyUnix)]
public void EndInit_ResumesPausedEnableRaisingEvents(bool setBeforeBeginInit)
{
using (var testDirectory = new TempDirectory(GetTestFilePath()))
diff --git a/src/System.IO.FileSystem.Watcher/tests/FileSystemWatcher.unit.cs b/src/System.IO.FileSystem.Watcher/tests/FileSystemWatcher.unit.cs
index 1bf1a12a61..f9e7fa446d 100644
--- a/src/System.IO.FileSystem.Watcher/tests/FileSystemWatcher.unit.cs
+++ b/src/System.IO.FileSystem.Watcher/tests/FileSystemWatcher.unit.cs
@@ -497,7 +497,7 @@ namespace System.IO.Tests
watcher.Path = ".";
Assert.Equal(".", watcher.Path);
- if (!PlatformDetection.IsWinRT)
+ if (!PlatformDetection.IsInAppContainer)
{
watcher.Path = "..";
Assert.Equal("..", watcher.Path);
diff --git a/src/System.IO.FileSystem.Watcher/tests/Utility/FileSystemWatcherTest.cs b/src/System.IO.FileSystem.Watcher/tests/Utility/FileSystemWatcherTest.cs
index 342f37b804..8778820b41 100644
--- a/src/System.IO.FileSystem.Watcher/tests/Utility/FileSystemWatcherTest.cs
+++ b/src/System.IO.FileSystem.Watcher/tests/Utility/FileSystemWatcherTest.cs
@@ -203,7 +203,7 @@ namespace System.IO.Tests
string[] expectedFullPaths = expectedPaths == null ? null : expectedPaths.Select(e => Path.GetFullPath(e)).ToArray();
// On OSX we get a number of extra events tacked onto valid events. As such, we can not ever confidently
- // say that a event won't occur, only that one will occur.
+ // say that an event won't occur, only that one will occur.
if (RuntimeInformation.IsOSPlatform(OSPlatform.OSX))
{
if (verifyChanged = ((expectedEvents & WatcherChangeTypes.Changed) > 0))
@@ -443,4 +443,4 @@ namespace System.IO.Tests
NotifyFilters.LastWrite |
NotifyFilters.Size;
}
-} \ No newline at end of file
+}
diff --git a/src/System.IO.FileSystem/src/System.IO.FileSystem.csproj b/src/System.IO.FileSystem/src/System.IO.FileSystem.csproj
index a27295cbd4..9160591924 100644
--- a/src/System.IO.FileSystem/src/System.IO.FileSystem.csproj
+++ b/src/System.IO.FileSystem/src/System.IO.FileSystem.csproj
@@ -195,9 +195,6 @@
<Compile Include="$(CommonPath)\System\Memory\FixedBufferExtensions.cs">
<Link>Common\System\Memory\FixedBufferExtensions.cs</Link>
</Compile>
- </ItemGroup>
- <!-- Windows : Win32 only -->
- <ItemGroup Condition="'$(TargetsWindows)' == 'true' and '$(UWPCompatible)' != 'true'">
<Compile Include="$(CommonPath)\Interop\Windows\kernel32\Interop.DeleteFile.cs">
<Link>Common\Interop\Windows\Interop.DeleteFile.cs</Link>
</Compile>
@@ -222,12 +219,6 @@
<Compile Include="$(CommonPath)\Interop\Windows\kernel32\Interop.ReplaceFile.cs">
<Link>Common\Interop\Windows\Interop.ReplaceFile.cs</Link>
</Compile>
- <Compile Include="$(CommonPath)\Interop\Windows\kernel32\Interop.CreateFile.cs">
- <Link>Common\Interop\Windows\Interop.CreateFile.cs</Link>
- </Compile>
- <Compile Include="$(CommonPath)\Interop\Windows\kernel32\Interop.UnsafeCreateFile.cs">
- <Link>Common\Interop\Windows\Interop.UnsafeCreateFile.cs</Link>
- </Compile>
<Compile Include="$(CommonPath)\Interop\Windows\kernel32\Interop.CopyFile.cs">
<Link>Common\Interop\Windows\Interop.CopyFile.cs</Link>
</Compile>
@@ -235,9 +226,23 @@
<Link>Common\Interop\Windows\Interop.CopyFileEx.cs</Link>
</Compile>
</ItemGroup>
+ <!-- Windows : Win32 only -->
+ <ItemGroup Condition="'$(TargetsWindows)' == 'true' and '$(UWPCompatible)' != 'true'">
+ <Compile Include="$(CommonPath)\Interop\Windows\kernel32\Interop.UnsafeCreateFile.cs">
+ <Link>Common\Interop\Windows\Interop.UnsafeCreateFile.cs</Link>
+ </Compile>
+ <Compile Include="$(CommonPath)\Interop\Windows\kernel32\Interop.CreateFile.cs">
+ <Link>Common\Interop\Windows\Interop.CreateFile.cs</Link>
+ </Compile>
+ </ItemGroup>
<!-- Windows : UAP - Win32 + WinRT -->
<ItemGroup Condition="'$(TargetsWindows)' == 'true' and '$(UWPCompatible)' == 'true'">
- <Compile Include="System\IO\FromApp.Interop.cs" />
+ <Compile Include="$(CommonPath)\Interop\Windows\kernel32\Interop.CreateFile2.cs">
+ <Link>Common\Interop\Windows\Interop.CreateFile2.cs</Link>
+ </Compile>
+ <Compile Include="$(CommonPath)\Interop\Windows\kernel32\Interop.UnsafeCreateFile.uap.cs">
+ <Link>Common\Interop\Windows\Interop.UnsafeCreateFile.uap.cs</Link>
+ </Compile>
<Compile Include="$(CommonPath)\Interop\Windows\kernel32\Interop.COPYFILE2_EXTENDED_PARAMETERS.cs">
<Link>Common\Interop\Windows\Interop.COPYFILE2_EXTENDED_PARAMETERS.cs</Link>
</Compile>
diff --git a/src/System.IO.FileSystem/src/System/IO/FromApp.Interop.cs b/src/System.IO.FileSystem/src/System/IO/FromApp.Interop.cs
deleted file mode 100644
index 3abf72d220..0000000000
--- a/src/System.IO.FileSystem/src/System/IO/FromApp.Interop.cs
+++ /dev/null
@@ -1,150 +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.IO;
-using System.Runtime.InteropServices;
-
-#pragma warning disable BCL0015
-internal partial class Interop
-{
- internal partial class Kernel32
- {
- [DllImport("FileApiInterop.dll", SetLastError = true, CharSet = CharSet.Unicode, ExactSpelling = true)]
- private static extern bool CopyFileFromApp(string lpExistingFileName, string lpNewFileName, bool bFailIfExists);
-
- internal static int CopyFile(string src, string dst, bool failIfExists)
- {
- src = PathInternal.EnsureExtendedPrefixOverMaxPath(src);
- dst = PathInternal.EnsureExtendedPrefixOverMaxPath(dst);
- if (!CopyFileFromApp(src, dst, failIfExists))
- {
- return Marshal.GetLastWin32Error();
- }
- return Errors.ERROR_SUCCESS;
- }
-
- [DllImport("FileApiInterop.dll", SetLastError = true, CharSet = CharSet.Unicode, ExactSpelling = true)]
- private static extern bool CreateDirectoryFromApp(string lpPathName, ref SECURITY_ATTRIBUTES lpSecurityAttributes);
-
- internal static bool CreateDirectory(string path, ref SECURITY_ATTRIBUTES lpSecurityAttributes)
- {
- // We always want to add for CreateDirectory to get around the legacy 248 character limitation
- path = PathInternal.EnsureExtendedPrefix(path);
- return CreateDirectoryFromApp(path, ref lpSecurityAttributes);
- }
-
- [DllImport("FileApiInterop.dll", SetLastError = true, CharSet = CharSet.Unicode, ExactSpelling = true)]
- private static extern bool DeleteFileFromApp(string lpFileName);
-
- internal static bool DeleteFile(string path)
- {
- path = PathInternal.EnsureExtendedPrefixOverMaxPath(path);
- return DeleteFileFromApp(path);
- }
-
- [DllImport("FileApiInterop.dll", SetLastError = true, CharSet = CharSet.Unicode, ExactSpelling = true)]
- private static extern SafeFindHandle FindFirstFileExFromApp(string lpFileName, FINDEX_INFO_LEVELS fInfoLevelId, ref WIN32_FIND_DATA lpFindFileData, FINDEX_SEARCH_OPS fSearchOp, IntPtr lpSearchFilter, int dwAdditionalFlags);
-
- internal static SafeFindHandle FindFirstFile(string fileName, ref WIN32_FIND_DATA data)
- {
- fileName = PathInternal.EnsureExtendedPrefixOverMaxPath(fileName);
-
- // use FindExInfoBasic since we don't care about short name and it has better perf
- return FindFirstFileExFromApp(fileName, FINDEX_INFO_LEVELS.FindExInfoBasic, ref data, FINDEX_SEARCH_OPS.FindExSearchNameMatch, IntPtr.Zero, 0);
- }
-
- [DllImport("FileApiInterop.dll", SetLastError = true, CharSet = CharSet.Unicode, ExactSpelling = true)]
- private static extern bool GetFileAttributesExFromApp(string lpFileName, GET_FILEEX_INFO_LEVELS fInfoLevelId, ref WIN32_FILE_ATTRIBUTE_DATA lpFileInformation);
-
- internal static bool GetFileAttributesEx(string name, GET_FILEEX_INFO_LEVELS fileInfoLevel, ref WIN32_FILE_ATTRIBUTE_DATA lpFileInformation)
- {
- name = PathInternal.EnsureExtendedPrefixOverMaxPath(name);
- return GetFileAttributesExFromApp(name, fileInfoLevel, ref lpFileInformation);
- }
-
- [DllImport("FileApiInterop.dll", SetLastError = true, CharSet = CharSet.Unicode, ExactSpelling = true)]
- private static extern bool MoveFileFromApp(string lpExistingFileName, string lpNewFileName);
-
- internal static bool MoveFile(string src, string dst)
- {
- src = PathInternal.EnsureExtendedPrefixOverMaxPath(src);
- dst = PathInternal.EnsureExtendedPrefixOverMaxPath(dst);
- return MoveFileFromApp(src, dst);
- }
-
- [DllImport("FileApiInterop.dll", SetLastError = true, CharSet = CharSet.Unicode, ExactSpelling = true)]
- private static extern bool RemoveDirectoryFromApp(string lpPathName);
-
- internal static bool RemoveDirectory(string path)
- {
- path = PathInternal.EnsureExtendedPrefixOverMaxPath(path);
- return RemoveDirectoryFromApp(path);
- }
-
- [DllImport("FileApiInterop.dll", SetLastError = true, CharSet = CharSet.Unicode, ExactSpelling = true)]
- private static extern bool ReplaceFileFromApp(
- string lpReplacedFileName, string lpReplacementFileName, string lpBackupFileName,
- int dwReplaceFlags, IntPtr lpExclude, IntPtr lpReserved);
-
- internal static bool ReplaceFile(
- string replacedFileName, string replacementFileName, string backupFileName,
- int dwReplaceFlags, IntPtr lpExclude, IntPtr lpReserved)
- {
- replacedFileName = PathInternal.EnsureExtendedPrefixOverMaxPath(replacedFileName);
- replacementFileName = PathInternal.EnsureExtendedPrefixOverMaxPath(replacementFileName);
- backupFileName = PathInternal.EnsureExtendedPrefixOverMaxPath(backupFileName);
-
- return ReplaceFileFromApp(
- replacedFileName, replacementFileName, backupFileName,
- dwReplaceFlags, lpExclude, lpReserved);
- }
-
- internal const int REPLACEFILE_WRITE_THROUGH = 0x1;
- internal const int REPLACEFILE_IGNORE_MERGE_ERRORS = 0x2;
-
- [DllImport("FileApiInterop.dll", SetLastError = true, CharSet = CharSet.Unicode, ExactSpelling = true)]
- private static extern bool SetFileAttributesFromApp(string lpFileName, int dwFileAttributes);
-
- internal static bool SetFileAttributes(string name, int attr)
- {
- name = PathInternal.EnsureExtendedPrefixOverMaxPath(name);
- return SetFileAttributesFromApp(name, attr);
- }
-
- [DllImport("FileApiInterop.dll", EntryPoint = "CreateFile2FromApp", SetLastError = true, CharSet = CharSet.Unicode)]
- internal static extern SafeFileHandle CreateFile2(
- string lpFileName,
- int dwDesiredAccess,
- FileShare dwShareMode,
- FileMode dwCreationDisposition,
- [In] ref CREATEFILE2_EXTENDED_PARAMETERS parameters);
-
- internal static unsafe SafeFileHandle UnsafeCreateFile(
- string lpFileName,
- int dwDesiredAccess,
- FileShare dwShareMode,
- ref SECURITY_ATTRIBUTES securityAttrs,
- FileMode dwCreationDisposition,
- int dwFlagsAndAttributes,
- IntPtr hTemplateFile)
- {
- CREATEFILE2_EXTENDED_PARAMETERS parameters;
- parameters.dwSize = (uint)Marshal.SizeOf<CREATEFILE2_EXTENDED_PARAMETERS>();
-
- parameters.dwFileAttributes = (uint)dwFlagsAndAttributes & 0x0000FFFF;
- parameters.dwSecurityQosFlags = (uint)dwFlagsAndAttributes & 0x000F0000;
- parameters.dwFileFlags = (uint)dwFlagsAndAttributes & 0xFFF00000;
-
- parameters.hTemplateFile = hTemplateFile;
- fixed (SECURITY_ATTRIBUTES* lpSecurityAttributes = &securityAttrs)
- {
- parameters.lpSecurityAttributes = (IntPtr)lpSecurityAttributes;
- return CreateFile2(lpFileName, dwDesiredAccess, dwShareMode, dwCreationDisposition, ref parameters);
- }
- }
- }
-}
-#pragma warning restore BCL0015
diff --git a/src/System.IO.FileSystem/tests/Directory/Delete.cs b/src/System.IO.FileSystem/tests/Directory/Delete.cs
index a2adcf855a..b7b9cb7176 100644
--- a/src/System.IO.FileSystem/tests/Directory/Delete.cs
+++ b/src/System.IO.FileSystem/tests/Directory/Delete.cs
@@ -208,6 +208,9 @@ namespace System.IO.Tests
[Trait(XunitConstants.Category, XunitConstants.RequiresElevation)]
public void Unix_NotFoundDirectory_ReadOnlyVolume()
{
+ if (PlatformDetection.IsRedHat69)
+ return; // [ActiveIssue(https://github.com/dotnet/corefx/issues/21920)]
+
ReadOnly_FileSystemHelper(readOnlyDirectory =>
{
Assert.Throws<DirectoryNotFoundException>(() => Delete(Path.Combine(readOnlyDirectory, "DoesNotExist")));
@@ -251,8 +254,10 @@ namespace System.IO.Tests
}
[Fact]
+ [ActiveIssue(24242)]
[PlatformSpecific(TestPlatforms.Windows)]
[OuterLoop("This test is very slow.")]
+ [SkipOnTargetFramework(TargetFrameworkMonikers.NetFramework, "Desktop does not have the fix for #22596")]
public void RecursiveDelete_DeepNesting()
{
// Create a 2000 level deep directory and recursively delete from the root.
diff --git a/src/System.IO.FileSystem/tests/File/Delete.cs b/src/System.IO.FileSystem/tests/File/Delete.cs
index 2c74a91b33..f6f7ade21f 100644
--- a/src/System.IO.FileSystem/tests/File/Delete.cs
+++ b/src/System.IO.FileSystem/tests/File/Delete.cs
@@ -129,6 +129,9 @@ namespace System.IO.Tests
[Trait(XunitConstants.Category, XunitConstants.RequiresElevation)]
public void Unix_NonExistentPath_ReadOnlyVolume()
{
+ if (PlatformDetection.IsRedHat69)
+ return; // [ActiveIssue(https://github.com/dotnet/corefx/issues/21920)]
+
ReadOnly_FileSystemHelper(readOnlyDirectory =>
{
Delete(Path.Combine(readOnlyDirectory, "DoesNotExist"));
@@ -141,6 +144,9 @@ namespace System.IO.Tests
[Trait(XunitConstants.Category, XunitConstants.RequiresElevation)]
public void Unix_ExistingDirectory_ReadOnlyVolume()
{
+ if (PlatformDetection.IsRedHat69)
+ return; // [ActiveIssue(https://github.com/dotnet/corefx/issues/21920)]
+
ReadOnly_FileSystemHelper(readOnlyDirectory =>
{
Assert.Throws<IOException>(() => Delete(Path.Combine(readOnlyDirectory, "subdir")));
diff --git a/src/System.IO.FileSystem/tests/FileStream/ReadWriteSpan.netcoreapp.cs b/src/System.IO.FileSystem/tests/FileStream/ReadWriteSpan.netcoreapp.cs
index 3a67c5c9d0..272b19769e 100644
--- a/src/System.IO.FileSystem/tests/FileStream/ReadWriteSpan.netcoreapp.cs
+++ b/src/System.IO.FileSystem/tests/FileStream/ReadWriteSpan.netcoreapp.cs
@@ -3,6 +3,8 @@
// See the LICENSE file in the project root for more information.
using System.Linq;
+using System.Threading;
+using System.Threading.Tasks;
using Xunit;
namespace System.IO.Tests
@@ -123,6 +125,119 @@ namespace System.IO.Tests
Assert.Equal(TestBuffer, buffer);
}
}
+
+ [Fact]
+ public void DisposedStream_ReadWriteAsync_Throws()
+ {
+ var fs = CreateFileStream(GetTestFilePath(), FileMode.Create);
+ fs.Dispose();
+ Assert.Throws<ObjectDisposedException>(() => { fs.ReadAsync(new Memory<byte>(new byte[1])); });
+ Assert.Throws<ObjectDisposedException>(() => { fs.WriteAsync(new ReadOnlyMemory<byte>(new byte[1])); });
+ }
+
+ [Fact]
+ public async Task EmptyFile_ReadAsync_Succeeds()
+ {
+ using (var fs = CreateFileStream(GetTestFilePath(), FileMode.Create))
+ {
+ // use a recognizable pattern
+ var buffer = (byte[])TestBuffer.Clone();
+
+ Assert.Equal(0, await fs.ReadAsync(Memory<byte>.Empty));
+ Assert.Equal(0, await fs.ReadAsync(new Memory<byte>(buffer, 0, 1)));
+ Assert.Equal(TestBuffer, buffer);
+
+ Assert.Equal(0, await fs.ReadAsync(new Memory<byte>(buffer, 0, buffer.Length)));
+ Assert.Equal(TestBuffer, buffer);
+
+ Assert.Equal(0, await fs.ReadAsync(new Memory<byte>(buffer, buffer.Length - 1, 1)));
+ Assert.Equal(TestBuffer, buffer);
+
+ Assert.Equal(0, await fs.ReadAsync(new Memory<byte>(buffer, buffer.Length / 2, buffer.Length - buffer.Length / 2)));
+ Assert.Equal(TestBuffer, buffer);
+ }
+ }
+
+ [Fact]
+ public async Task NonEmptyFile_ReadAsync_GetsExpectedData()
+ {
+ string fileName = GetTestFilePath();
+ File.WriteAllBytes(fileName, TestBuffer);
+
+ using (var fs = CreateFileStream(fileName, FileMode.Open))
+ {
+ var buffer = new byte[TestBuffer.Length];
+ Assert.Equal(TestBuffer.Length, await fs.ReadAsync(new Memory<byte>(buffer, 0, buffer.Length)));
+ Assert.Equal(TestBuffer, buffer);
+
+ // Larger than needed buffer, read into beginning, rest remains untouched
+ fs.Position = 0;
+ buffer = new byte[TestBuffer.Length * 2];
+ Assert.Equal(TestBuffer.Length, await fs.ReadAsync(new Memory<byte>(buffer)));
+ Assert.Equal(TestBuffer, buffer.Take(TestBuffer.Length));
+ Assert.Equal(new byte[buffer.Length - TestBuffer.Length], buffer.Skip(TestBuffer.Length));
+
+ // Larger than needed buffer, read into middle, beginning and end remain untouched
+ fs.Position = 0;
+ buffer = new byte[TestBuffer.Length * 2];
+ Assert.Equal(TestBuffer.Length, await fs.ReadAsync(new Memory<byte>(buffer, 2, buffer.Length - 2)));
+ Assert.Equal(TestBuffer, buffer.Skip(2).Take(TestBuffer.Length));
+ Assert.Equal(new byte[2], buffer.Take(2));
+ Assert.Equal(new byte[buffer.Length - TestBuffer.Length - 2], buffer.Skip(2 + TestBuffer.Length));
+ }
+ }
+
+ [Fact]
+ public void ReadOnly_WriteAsync_Throws()
+ {
+ string fileName = GetTestFilePath();
+ File.WriteAllBytes(fileName, TestBuffer);
+
+ using (var fs = CreateFileStream(fileName, FileMode.Open, FileAccess.Read))
+ {
+ Assert.Throws<NotSupportedException>(() => { fs.WriteAsync(new ReadOnlyMemory<byte>(new byte[1])); });
+ fs.Dispose();
+ Assert.Throws<ObjectDisposedException>(() => { fs.WriteAsync(new ReadOnlyMemory<byte>(new byte[1])); }); // Disposed checking happens first
+ }
+ }
+
+ [Fact]
+ public void WriteOnly_ReadAsync_Throws()
+ {
+ using (var fs = CreateFileStream(GetTestFilePath(), FileMode.Create, FileAccess.Write))
+ {
+ Assert.Throws<NotSupportedException>(() => { fs.ReadAsync(new Memory<byte>(new byte[1])); });
+ fs.Dispose();
+ Assert.Throws<ObjectDisposedException>(() => { fs.ReadAsync(new Memory<byte>(new byte[1])); });// Disposed checking happens first
+ }
+ }
+
+ [Fact]
+ public async Task EmptyWriteAsync_NoDataWritten()
+ {
+ using (var fs = CreateFileStream(GetTestFilePath(), FileMode.Create))
+ {
+ await fs.WriteAsync(Memory<byte>.Empty);
+ Assert.Equal(0, fs.Length);
+ Assert.Equal(0, fs.Position);
+ }
+ }
+
+ [Fact]
+ public async Task NonEmptyWriteAsync_WritesExpectedData()
+ {
+ using (var fs = CreateFileStream(GetTestFilePath(), FileMode.Create))
+ {
+ await fs.WriteAsync(new Memory<byte>(TestBuffer));
+ Assert.Equal(TestBuffer.Length, fs.Length);
+ Assert.Equal(TestBuffer.Length, fs.Position);
+
+ fs.Position = 0;
+ var buffer = new byte[TestBuffer.Length];
+ Assert.Equal(TestBuffer.Length, await fs.ReadAsync(new Memory<byte>(buffer)));
+ Assert.Equal(TestBuffer, buffer);
+ }
+ }
}
public class Sync_FileStream_ReadWrite_Span : FileStream_ReadWrite_Span
@@ -160,6 +275,25 @@ namespace System.IO.Tests
Assert.True(fs.ReadArrayInvoked);
}
}
+
+ [Fact]
+ public async Task CallMemoryReadWriteAsyncOnDerivedFileStream_ArrayMethodsUsed()
+ {
+ using (var fs = (DerivedFileStream)CreateFileStream(GetTestFilePath(), FileMode.Create, FileAccess.ReadWrite))
+ {
+ Assert.False(fs.WriteAsyncArrayInvoked);
+ Assert.False(fs.ReadAsyncArrayInvoked);
+
+ await fs.WriteAsync(new ReadOnlyMemory<byte>(new byte[1]));
+ Assert.True(fs.WriteAsyncArrayInvoked);
+ Assert.False(fs.ReadAsyncArrayInvoked);
+
+ fs.Position = 0;
+ await fs.ReadAsync(new Memory<byte>(new byte[1]));
+ Assert.True(fs.WriteAsyncArrayInvoked);
+ Assert.True(fs.ReadAsyncArrayInvoked);
+ }
+ }
}
public sealed class Async_DerivedFileStream_ReadWrite_Span : Async_FileStream_ReadWrite_Span
@@ -171,6 +305,7 @@ namespace System.IO.Tests
internal sealed class DerivedFileStream : FileStream
{
public bool ReadArrayInvoked = false, WriteArrayInvoked = false;
+ public bool ReadAsyncArrayInvoked = false, WriteAsyncArrayInvoked = false;
public DerivedFileStream(string path, FileMode mode, FileAccess access, FileShare share, int bufferSize, FileOptions options) :
base(path, mode, access, share, bufferSize, options)
@@ -188,5 +323,17 @@ namespace System.IO.Tests
WriteArrayInvoked = true;
base.Write(array, offset, count);
}
+
+ public override Task<int> ReadAsync(byte[] buffer, int offset, int count, CancellationToken cancellationToken)
+ {
+ ReadAsyncArrayInvoked = true;
+ return base.ReadAsync(buffer, offset, count, cancellationToken);
+ }
+
+ public override Task WriteAsync(byte[] buffer, int offset, int count, CancellationToken cancellationToken)
+ {
+ WriteAsyncArrayInvoked = true;
+ return base.WriteAsync(buffer, offset, count, cancellationToken);
+ }
}
}
diff --git a/src/System.IO.FileSystem/tests/FileSystemTest.cs b/src/System.IO.FileSystem/tests/FileSystemTest.cs
index 7fcae98914..4e593f27b8 100644
--- a/src/System.IO.FileSystem/tests/FileSystemTest.cs
+++ b/src/System.IO.FileSystem/tests/FileSystemTest.cs
@@ -61,7 +61,7 @@ namespace System.IO.Tests
protected string GetNamedPipeServerStreamName()
{
- if (PlatformDetection.IsWinRT)
+ if (PlatformDetection.IsInAppContainer)
{
return @"LOCAL\" + Guid.NewGuid().ToString("N");
}
diff --git a/src/System.IO.FileSystem/tests/PortedCommon/IOServices.cs b/src/System.IO.FileSystem/tests/PortedCommon/IOServices.cs
index 41d8b5f1fe..6b45e65b5a 100644
--- a/src/System.IO.FileSystem/tests/PortedCommon/IOServices.cs
+++ b/src/System.IO.FileSystem/tests/PortedCommon/IOServices.cs
@@ -228,7 +228,7 @@ internal class IOServices
public static bool IsDriveNTFS(string drive)
{
- if (PlatformDetection.IsWinRT)
+ if (PlatformDetection.IsInAppContainer)
{
// we cannot determine filesystem so assume NTFS
return true;
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 6a75704f5a..1ecc4c4585 100644
--- a/src/System.IO.FileSystem/tests/System.IO.FileSystem.Tests.csproj
+++ b/src/System.IO.FileSystem/tests/System.IO.FileSystem.Tests.csproj
@@ -54,9 +54,6 @@
<Compile Include="File\ReadWriteAllTextAsync.cs" />
<Compile Include="FileStream\ReadWriteSpan.netcoreapp.cs" />
</ItemGroup>
- <ItemGroup Condition="'$(TargetGroup)' == 'uapaot' or '$(TargetGroup)' == 'uap'">
- <Compile Include="WinRT_BrokeredFunctions.cs" />
- </ItemGroup>
<ItemGroup>
<!-- Rewritten -->
<Compile Include="DirectoryInfo\GetSetAttributes.cs" />
diff --git a/src/System.IO.FileSystem/tests/WinRT_BrokeredFunctions.cs b/src/System.IO.FileSystem/tests/WinRT_BrokeredFunctions.cs
deleted file mode 100644
index cb20e27349..0000000000
--- a/src/System.IO.FileSystem/tests/WinRT_BrokeredFunctions.cs
+++ /dev/null
@@ -1,209 +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.Generic;
-using System.Linq;
-using System.Runtime.InteropServices;
-using Xunit;
-using Windows.Storage;
-
-namespace System.IO.Tests
-{
- [PlatformSpecific(TestPlatforms.Windows)]
- [SkipOnTargetFramework(~(TargetFrameworkMonikers.Uap | TargetFrameworkMonikers.UapAot))]
- public partial class WinRT_BrokeredFunctions : FileSystemTest
- {
- private static string s_musicFolder = StorageLibrary.GetLibraryAsync(KnownLibraryId.Music).AsTask().Result.SaveFolder.Path;
-
- [Fact]
- public void CopyFile_ToBrokeredLocation()
- {
- string testFile = GetTestFilePath();
- File.Create(testFile).Dispose();
-
- string destination = Path.Combine(s_musicFolder, "CopyToBrokeredLocation_" + Path.GetRandomFileName());
- try
- {
- Assert.False(File.Exists(destination), "destination shouldn't exist before copying");
- File.Copy(testFile, destination);
- Assert.True(File.Exists(testFile), "testFile should exist after copying");
- Assert.True(File.Exists(destination), "destination should exist after copying");
- }
- finally
- {
- File.Delete(destination);
- }
- }
-
- [Fact]
- public void CreateDirectory()
- {
- string testFolder = Path.Combine(s_musicFolder, "CreateDirectory_" + Path.GetRandomFileName());
- try
- {
- Assert.False(Directory.Exists(testFolder), "destination shouldn't exist");
- Directory.CreateDirectory(testFolder);
- Assert.True(Directory.Exists(testFolder), "destination should exist");
- }
- finally
- {
- Directory.Delete(testFolder);
- }
- }
-
- [Fact]
- public void DeleteFile()
- {
- string testFile = Path.Combine(s_musicFolder, "DeleteFile_" + Path.GetRandomFileName());
- CreateFileInBrokeredLocation(testFile);
- Assert.True(File.Exists(testFile), "testFile should exist before deleting");
- File.Delete(testFile);
- Assert.False(File.Exists(testFile), "testFile shouldn't exist after deleting");
- }
-
- [Fact]
- public void FindFirstFile()
- {
- string subFolder = Path.Combine(s_musicFolder, "FindFirstFile_SubFolder_" + Path.GetRandomFileName());
- Directory.CreateDirectory(subFolder);
- string testFile = null;
-
- try
- {
- testFile = Path.Combine(subFolder, "FindFirstFile_SubFile_" + Path.GetRandomFileName());
- CreateFileInBrokeredLocation(testFile);
- Assert.True(File.Exists(testFile), "testFile should exist");
- }
- finally
- {
- Directory.Delete(subFolder, true);
- }
- Assert.False(File.Exists(testFile), "testFile shouldn't exist after a recursive delete");
- Assert.False(Directory.Exists(subFolder), "subFolder shouldn't exist after a recursive delete");
- }
-
- [Fact]
- [ActiveIssue(23444)]
- public void GetFileAttributesEx()
- {
- string destination = Path.Combine(s_musicFolder, "GetFileAttributesEx_" + Path.GetRandomFileName());
- CreateFileInBrokeredLocation(destination);
- try
- {
- FileAttributes attr = File.GetAttributes(destination);
- Assert.False((attr & FileAttributes.ReadOnly) == 0, "new file in brokered location should not be readonly");
- }
- finally
- {
- File.Delete(destination);
- }
- }
-
- [Fact]
- public void MoveFile()
- {
- string testFile = GetTestFilePath();
- File.Create(testFile).Dispose();
-
- string destination = Path.Combine(s_musicFolder, "MoveFile_" + Path.GetRandomFileName());
- try
- {
- Assert.False(File.Exists(destination), "destination shouldn't exist before moving");
- File.Move(testFile, destination);
- Assert.False(File.Exists(testFile), "testFile shouldn't exist after moving");
- Assert.True(File.Exists(destination), "destination should exist after moving");
- }
- finally
- {
- File.Delete(destination);
- }
- }
-
- [Fact]
- public void RemoveDirectory()
- {
- string testFolder = Path.Combine(s_musicFolder, "CreateDirectory_" + Path.GetRandomFileName());
- Assert.False(Directory.Exists(testFolder), "destination shouldn't exist");
- Directory.CreateDirectory(testFolder);
- Assert.True(Directory.Exists(testFolder), "destination should exist");
- Directory.Delete(testFolder);
- Assert.False(Directory.Exists(testFolder), "destination shouldn't exist");
- }
-
- [Fact]
- public void ReplaceFile()
- {
- string testFile = GetTestFilePath();
- File.Create(testFile).Dispose();
-
- string destination = Path.Combine(s_musicFolder, "ReplaceFile_" + Path.GetRandomFileName());
- File.Copy(testFile, destination);
-
- // Need to be on the same drive
- Assert.Equal(testFile[0], destination[0]);
-
- string destinationBackup = Path.Combine(s_musicFolder, "ReplaceFile_" + Path.GetRandomFileName());
- try
- {
- Assert.True(File.Exists(destination), "destination should exist before replacing");
- Assert.False(File.Exists(destinationBackup), "destination shouldn't exist before replacing");
- File.Replace(testFile, destination, destinationBackup);
- Assert.False(File.Exists(testFile), "testFile shouldn't exist after replacing");
- Assert.True(File.Exists(destination), "destination should exist after replacing");
- Assert.True(File.Exists(destinationBackup), "destinationBackup should exist after replacing");
- }
- finally
- {
- File.Delete(destination);
- File.Delete(destinationBackup);
- }
- }
-
- [Fact]
- [ActiveIssue(23444)]
- public void SetFileAttributes()
- {
- string destination = Path.Combine(s_musicFolder, "SetFileAttributes_" + Path.GetRandomFileName());
- CreateFileInBrokeredLocation(destination);
- FileAttributes attr = File.GetAttributes(destination);
- try
- {
- Assert.False(((attr & FileAttributes.ReadOnly) > 0), "new file in brokered location should not be readonly");
- File.SetAttributes(destination, attr | FileAttributes.ReadOnly);
- Assert.True(((File.GetAttributes(destination) & FileAttributes.ReadOnly) > 0), "file in brokered location should be readonly after setting FileAttributes");
- }
- finally
- {
- File.SetAttributes(destination, attr);
- Assert.False(((File.GetAttributes(destination) & FileAttributes.ReadOnly) > 0), "file in brokered location should NOT be readonly after setting FileAttributes");
- File.Delete(destination);
- }
- }
-
- private void CreateFileInBrokeredLocation(string path)
- {
- // Temporary hack until FileStream is updated to support brokering
- string testFile = GetTestFilePath();
- File.WriteAllText(testFile, "CoreFX test file");
- File.Copy(testFile, path);
- }
-
- // Temporarily blocking until the CoreCLR change is made [Fact]
- public void WriteReadAllText()
- {
- string destination = Path.Combine(s_musicFolder, "WriteReadAllText_" + Path.GetRandomFileName());
- string content = "WriteReadAllText";
- File.WriteAllText(destination, content);
- try
- {
- Assert.True(File.Exists(destination));
- Assert.Equal(content, File.ReadAllText(destination));
- }
- finally
- {
- File.Delete(destination);
- }
- }
- }
-}
diff --git a/src/System.IO.IsolatedStorage/tests/System/IO/IsolatedStorage/HelperTests.cs b/src/System.IO.IsolatedStorage/tests/System/IO/IsolatedStorage/HelperTests.cs
index d998dca8e1..1709c51a91 100644
--- a/src/System.IO.IsolatedStorage/tests/System/IO/IsolatedStorage/HelperTests.cs
+++ b/src/System.IO.IsolatedStorage/tests/System/IO/IsolatedStorage/HelperTests.cs
@@ -46,7 +46,7 @@ namespace System.IO.IsolatedStorage.Tests
{
// Machine scope is behind a policy that isn't enabled by default
// https://github.com/dotnet/corefx/issues/19839
- if (scope == IsolatedStorageScope.Machine && PlatformDetection.IsWinRT)
+ if (scope == IsolatedStorageScope.Machine && PlatformDetection.IsInAppContainer)
return;
string path = Helper.GetDataDirectory(scope);
diff --git a/src/System.IO.IsolatedStorage/tests/System/IO/IsolatedStorage/IsoStorageTest.cs b/src/System.IO.IsolatedStorage/tests/System/IO/IsolatedStorage/IsoStorageTest.cs
index 641f0e7026..7c401c00d6 100644
--- a/src/System.IO.IsolatedStorage/tests/System/IO/IsolatedStorage/IsoStorageTest.cs
+++ b/src/System.IO.IsolatedStorage/tests/System/IO/IsolatedStorage/IsoStorageTest.cs
@@ -81,7 +81,7 @@ namespace System.IO.IsolatedStorage
// https://github.com/dotnet/corefx/issues/12628
if (RuntimeInformation.IsOSPlatform(OSPlatform.Windows)
- && !PlatformDetection.IsWinRT)
+ && !PlatformDetection.IsInAppContainer)
{
validScopes.Add(PresetScopes.MachineStoreForApplication);
validScopes.Add(PresetScopes.MachineStoreForAssembly);
diff --git a/src/System.IO.IsolatedStorage/tests/System/IO/IsolatedStorage/TestHelper.cs b/src/System.IO.IsolatedStorage/tests/System/IO/IsolatedStorage/TestHelper.cs
index 0b99d04cc3..583b71a756 100644
--- a/src/System.IO.IsolatedStorage/tests/System/IO/IsolatedStorage/TestHelper.cs
+++ b/src/System.IO.IsolatedStorage/tests/System/IO/IsolatedStorage/TestHelper.cs
@@ -35,7 +35,7 @@ namespace System.IO.IsolatedStorage
// https://github.com/dotnet/corefx/issues/12628
// https://github.com/dotnet/corefx/issues/19839
if (RuntimeInformation.IsOSPlatform(OSPlatform.Windows)
- && !PlatformDetection.IsWinRT)
+ && !PlatformDetection.IsInAppContainer)
{
s_roots.Add(Helper.GetDataDirectory(IsolatedStorageScope.Machine));
}
diff --git a/src/System.IO.MemoryMappedFiles/src/Microsoft/Win32/SafeMemoryMappedViewHandle.Windows.cs b/src/System.IO.MemoryMappedFiles/src/Microsoft/Win32/SafeMemoryMappedViewHandle.Windows.cs
index 2c4800c492..6095bd6e22 100644
--- a/src/System.IO.MemoryMappedFiles/src/Microsoft/Win32/SafeMemoryMappedViewHandle.Windows.cs
+++ b/src/System.IO.MemoryMappedFiles/src/Microsoft/Win32/SafeMemoryMappedViewHandle.Windows.cs
@@ -13,7 +13,7 @@ namespace Microsoft.Win32.SafeHandles
{
IntPtr h = handle;
handle = IntPtr.Zero;
- return Interop.Kernel32.UnmapViewOfFile(h) != 0;
+ return Interop.Kernel32.UnmapViewOfFile(h);
}
}
}
diff --git a/src/System.IO.MemoryMappedFiles/src/System.IO.MemoryMappedFiles.csproj b/src/System.IO.MemoryMappedFiles/src/System.IO.MemoryMappedFiles.csproj
index 9b57c2bd08..b7cd99bfd5 100644
--- a/src/System.IO.MemoryMappedFiles/src/System.IO.MemoryMappedFiles.csproj
+++ b/src/System.IO.MemoryMappedFiles/src/System.IO.MemoryMappedFiles.csproj
@@ -189,6 +189,7 @@
<Reference Include="System.Runtime.InteropServices" />
<Reference Include="System.Threading" />
<Reference Include="System.Threading.Tasks" />
+ <Reference Include="System.Threading.Thread" />
</ItemGroup>
<Import Project="$([MSBuild]::GetDirectoryNameOfFileAbove($(MSBuildThisFileDirectory), dir.targets))\dir.targets" />
</Project>
diff --git a/src/System.IO.MemoryMappedFiles/src/System/IO/MemoryMappedFiles/MemoryMappedFile.Windows.cs b/src/System.IO.MemoryMappedFiles/src/System/IO/MemoryMappedFiles/MemoryMappedFile.Windows.cs
index 8bb0d595e2..24ea3a4658 100644
--- a/src/System.IO.MemoryMappedFiles/src/System/IO/MemoryMappedFiles/MemoryMappedFile.Windows.cs
+++ b/src/System.IO.MemoryMappedFiles/src/System/IO/MemoryMappedFiles/MemoryMappedFile.Windows.cs
@@ -146,7 +146,7 @@ namespace System.IO.MemoryMappedFiles
}
else
{
- ThreadSleep(waitSleep);
+ Thread.Sleep(waitSleep);
waitSleep *= 2;
}
}
@@ -256,13 +256,5 @@ namespace System.IO.MemoryMappedFiles
}
return secAttrs;
}
-
- /// <summary>
- /// Replacement for Thread.Sleep(milliseconds), which isn't available.
- /// </summary>
- internal static void ThreadSleep(int milliseconds)
- {
- new ManualResetEventSlim(initialState: false).Wait(milliseconds);
- }
}
}
diff --git a/src/System.IO.MemoryMappedFiles/src/System/IO/MemoryMappedFiles/MemoryMappedView.Windows.cs b/src/System.IO.MemoryMappedFiles/src/System/IO/MemoryMappedFiles/MemoryMappedView.Windows.cs
index 711b40a0eb..5d203ea499 100644
--- a/src/System.IO.MemoryMappedFiles/src/System/IO/MemoryMappedFiles/MemoryMappedView.Windows.cs
+++ b/src/System.IO.MemoryMappedFiles/src/System/IO/MemoryMappedFiles/MemoryMappedView.Windows.cs
@@ -30,7 +30,7 @@ namespace System.IO.MemoryMappedFiles
ulong nativeSize;
long extraMemNeeded, newOffset;
ValidateSizeAndOffset(
- size, offset, GetSystemPageAllocationGranularity(),
+ size, offset, GetSystemPageAllocationGranularity(),
out nativeSize, out extraMemNeeded, out newOffset);
// if request is >= than total virtual, then MapViewOfFile will fail with meaningless error message
@@ -107,9 +107,8 @@ namespace System.IO.MemoryMappedFiles
{
_viewHandle.AcquirePointer(ref firstPagePtr);
- bool success = Interop.Kernel32.FlushViewOfFile((IntPtr)firstPagePtr, capacity) != 0;
- if (success)
- return; // This will visit the finally block.
+ if (Interop.Kernel32.FlushViewOfFile((IntPtr)firstPagePtr, capacity))
+ return;
// It is a known issue within the NTFS transaction log system that
// causes FlushViewOfFile to intermittently fail with ERROR_LOCK_VIOLATION
@@ -119,24 +118,25 @@ namespace System.IO.MemoryMappedFiles
// this strategy successfully flushed the view after no more than 3 retries.
int error = Marshal.GetLastWin32Error();
- bool canRetry = (!success && error == Interop.Errors.ERROR_LOCK_VIOLATION);
+ if (error != Interop.Errors.ERROR_LOCK_VIOLATION)
+ throw Win32Marshal.GetExceptionForWin32Error(error);
SpinWait spinWait = new SpinWait();
- for (int w = 0; canRetry && w < MaxFlushWaits; w++)
+ for (int w = 0; w < MaxFlushWaits; w++)
{
int pause = (1 << w); // MaxFlushRetries should never be over 30
- MemoryMappedFile.ThreadSleep(pause);
+ Thread.Sleep(pause);
- for (int r = 0; canRetry && r < MaxFlushRetriesPerWait; r++)
+ for (int r = 0; r < MaxFlushRetriesPerWait; r++)
{
- success = Interop.Kernel32.FlushViewOfFile((IntPtr)firstPagePtr, capacity) != 0;
- if (success)
- return; // This will visit the finally block.
-
- spinWait.SpinOnce();
+ if (Interop.Kernel32.FlushViewOfFile((IntPtr)firstPagePtr, capacity))
+ return;
error = Marshal.GetLastWin32Error();
- canRetry = (error == Interop.Errors.ERROR_LOCK_VIOLATION);
+ if (error != Interop.Errors.ERROR_LOCK_VIOLATION)
+ throw Win32Marshal.GetExceptionForWin32Error(error);
+
+ spinWait.SpinOnce();
}
}
diff --git a/src/System.IO.MemoryMappedFiles/tests/MemoryMappedFile.CrossProcess.cs b/src/System.IO.MemoryMappedFiles/tests/MemoryMappedFile.CrossProcess.cs
index 867ee66ae2..1916d09836 100644
--- a/src/System.IO.MemoryMappedFiles/tests/MemoryMappedFile.CrossProcess.cs
+++ b/src/System.IO.MemoryMappedFiles/tests/MemoryMappedFile.CrossProcess.cs
@@ -27,7 +27,7 @@ namespace System.IO.MemoryMappedFiles.Tests
acc.Flush();
// Spawn and then wait for the other process, which will verify the data and write its own known pattern
- RemoteInvoke(DataShared_OtherProcess, file.Path).Dispose();
+ RemoteInvoke(new Func<string, int>(DataShared_OtherProcess), file.Path).Dispose();
// Now verify we're seeing the data from the other process
for (int i = 0; i < capacity; i++)
diff --git a/src/System.IO.Packaging/src/System/IO/Packaging/ContentType.cs b/src/System.IO.Packaging/src/System/IO/Packaging/ContentType.cs
index 117f067410..80efc16d11 100644
--- a/src/System.IO.Packaging/src/System/IO/Packaging/ContentType.cs
+++ b/src/System.IO.Packaging/src/System/IO/Packaging/ContentType.cs
@@ -147,7 +147,7 @@ namespace System.IO.Packaging
/// ReadOnly
/// Consider following Content type -
/// type/subtype ; param1=value1 ; param2=value2 ; param3="value3"
- /// This will return a enumerator over a dictionary of the parameter/value pairs.
+ /// This will return an enumerator over a dictionary of the parameter/value pairs.
/// </summary>
internal Dictionary<string, string>.Enumerator ParameterValuePairs
{
diff --git a/src/System.IO.Pipes/src/PinvokeAnalyzerExceptionList.analyzerdata b/src/System.IO.Pipes/src/PinvokeAnalyzerExceptionList.analyzerdata
deleted file mode 100644
index 0719fa0f9d..0000000000
--- a/src/System.IO.Pipes/src/PinvokeAnalyzerExceptionList.analyzerdata
+++ /dev/null
@@ -1,3 +0,0 @@
-## need to create a uap config that uses CreateFileFromApp, then remove this baseline ##
-# https://github.com/dotnet/corefx/issues/21025
-kernel32.dll!CreateFileW \ No newline at end of file
diff --git a/src/System.IO.Pipes/src/System.IO.Pipes.csproj b/src/System.IO.Pipes/src/System.IO.Pipes.csproj
index 7abd3d26fa..f0c917351b 100644
--- a/src/System.IO.Pipes/src/System.IO.Pipes.csproj
+++ b/src/System.IO.Pipes/src/System.IO.Pipes.csproj
@@ -95,9 +95,6 @@
<Compile Include="$(CommonPath)\Interop\Windows\kernel32\Interop.GetNamedPipeInfo.cs">
<Link>Common\Interop\Windows\Interop.GetNamedPipeInfo.cs</Link>
</Compile>
- <Compile Include="$(CommonPath)\Interop\Windows\kernel32\Interop.CreateNamedPipeClient.cs">
- <Link>Common\Interop\Windows\Interop.CreateNamedPipeClient.cs</Link>
- </Compile>
<Compile Include="$(CommonPath)\Interop\Windows\kernel32\Interop.SetNamedPipeHandleState.cs">
<Link>Common\Interop\Windows\Interop.SetNamedPipeHandleState.cs</Link>
</Compile>
@@ -146,6 +143,21 @@
<Compile Include="System\IO\Pipes\PipeStream.Windows.cs" />
<Compile Include="System\IO\Pipes\ReadWriteCompletionSource.cs" />
</ItemGroup>
+ <!-- Windows : Win32 only -->
+ <ItemGroup Condition="'$(TargetsWindows)' == 'true' and '$(TargetGroup)' != 'uap'">
+ <Compile Include="$(CommonPath)\Interop\Windows\kernel32\Interop.CreateNamedPipeClient.cs">
+ <Link>Common\Interop\Windows\Interop.CreateNamedPipeClient.cs</Link>
+ </Compile>
+ </ItemGroup>
+ <!-- Windows : UAP - Win32 + WinRT -->
+ <ItemGroup Condition="'$(TargetsWindows)' == 'true' and '$(TargetGroup)' == 'uap'">
+ <Compile Include="$(CommonPath)\Interop\Windows\kernel32\Interop.CreateNamedPipeClient.Uap.cs">
+ <Link>Common\Interop\Windows\Interop.CreateNamedPipeClient.Uap.cs</Link>
+ </Compile>
+ <Compile Include="$(CommonPath)\Interop\Windows\kernel32\Interop.CREATEFILE2_EXTENDED_PARAMETERS.cs">
+ <Link>Common\Interop\Windows\Interop.CREATEFILE2_EXTENDED_PARAMETERS.cs</Link>
+ </Compile>
+ </ItemGroup>
<ItemGroup Condition=" '$(TargetsUnix)' == 'true' ">
<Compile Include="Microsoft\Win32\SafeHandles\SafePipeHandle.Unix.cs" />
<Compile Include="System\IO\Pipes\AnonymousPipeServerStream.Unix.cs" />
diff --git a/src/System.IO.Pipes/src/System/IO/Pipes/ConnectionCompletionSource.cs b/src/System.IO.Pipes/src/System/IO/Pipes/ConnectionCompletionSource.cs
index 2966835eaf..5f196ee79c 100644
--- a/src/System.IO.Pipes/src/System/IO/Pipes/ConnectionCompletionSource.cs
+++ b/src/System.IO.Pipes/src/System/IO/Pipes/ConnectionCompletionSource.cs
@@ -12,7 +12,7 @@ namespace System.IO.Pipes
// Using RunContinuationsAsynchronously for compat reasons (old API used ThreadPool.QueueUserWorkItem for continuations)
internal ConnectionCompletionSource(NamedPipeServerStream server, CancellationToken cancellationToken)
- : base(server._threadPoolBinding, cancellationToken, pinData: null)
+ : base(server._threadPoolBinding, cancellationToken, ReadOnlyMemory<byte>.Empty)
{
_serverStream = server;
}
diff --git a/src/System.IO.Pipes/src/System/IO/Pipes/PipeCompletionSource.cs b/src/System.IO.Pipes/src/System/IO/Pipes/PipeCompletionSource.cs
index 7796871fac..94361f28c6 100644
--- a/src/System.IO.Pipes/src/System/IO/Pipes/PipeCompletionSource.cs
+++ b/src/System.IO.Pipes/src/System/IO/Pipes/PipeCompletionSource.cs
@@ -2,11 +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.Buffers;
using System.Diagnostics;
+using System.Runtime.InteropServices;
using System.Security;
using System.Threading;
using System.Threading.Tasks;
-using System.Runtime.InteropServices;
namespace System.IO.Pipes
{
@@ -24,6 +25,7 @@ namespace System.IO.Pipes
private CancellationTokenRegistration _cancellationRegistration;
private int _errorCode;
private NativeOverlapped* _overlapped;
+ private MemoryHandle _pinnedMemory;
private int _state;
#if DEBUG
@@ -31,7 +33,7 @@ namespace System.IO.Pipes
#endif
// Using RunContinuationsAsynchronously for compat reasons (old API used ThreadPool.QueueUserWorkItem for continuations)
- protected PipeCompletionSource(ThreadPoolBoundHandle handle, CancellationToken cancellationToken, object pinData)
+ protected PipeCompletionSource(ThreadPoolBoundHandle handle, CancellationToken cancellationToken, ReadOnlyMemory<byte> bufferToPin)
: base(TaskCreationOptions.RunContinuationsAsynchronously)
{
Debug.Assert(handle != null, "handle is null");
@@ -40,13 +42,14 @@ namespace System.IO.Pipes
_cancellationToken = cancellationToken;
_state = NoResult;
+ _pinnedMemory = bufferToPin.Retain(pin: true);
_overlapped = _threadPoolBinding.AllocateNativeOverlapped((errorCode, numBytes, pOverlapped) =>
{
var completionSource = (PipeCompletionSource<TResult>)ThreadPoolBoundHandle.GetNativeOverlappedState(pOverlapped);
Debug.Assert(completionSource.Overlapped == pOverlapped);
completionSource.AsyncCallback(errorCode, numBytes);
- }, this, pinData);
+ }, this, null);
}
internal NativeOverlapped* Overlapped
@@ -96,11 +99,13 @@ namespace System.IO.Pipes
// NOTE: The cancellation must *NOT* be running at this point, or it may observe freed memory
// (this is why we disposed the registration above)
- if (Overlapped != null)
+ if (_overlapped != null)
{
_threadPoolBinding.FreeNativeOverlapped(Overlapped);
_overlapped = null;
}
+
+ _pinnedMemory.Dispose();
}
internal abstract void SetCompletedSynchronously();
diff --git a/src/System.IO.Pipes/src/System/IO/Pipes/PipeStream.Unix.cs b/src/System.IO.Pipes/src/System/IO/Pipes/PipeStream.Unix.cs
index 5b4354a8bc..84fc05a8fb 100644
--- a/src/System.IO.Pipes/src/System/IO/Pipes/PipeStream.Unix.cs
+++ b/src/System.IO.Pipes/src/System/IO/Pipes/PipeStream.Unix.cs
@@ -156,35 +156,54 @@ namespace System.IO.Pipes
}
}
- private async Task<int> ReadAsyncCore(byte[] buffer, int offset, int count, CancellationToken cancellationToken)
+ private async Task<int> ReadAsyncCore(Memory<byte> destination, CancellationToken cancellationToken)
{
Debug.Assert(this is NamedPipeClientStream || this is NamedPipeServerStream, $"Expected a named pipe, got a {GetType()}");
Socket socket = InternalHandle.NamedPipeSocket;
- // If a cancelable token is used, we have a choice: we can either ignore it and use a true async operation
- // with Socket.ReceiveAsync, or we can use a polling loop on a worker thread to block for short intervals
- // and check for cancellation in between. We do the latter.
- if (cancellationToken.CanBeCanceled)
+ try
{
- await Task.CompletedTask.ForceAsync(); // queue the remainder of the work to avoid blocking the caller
- int timeout = 10000;
- const int MaxTimeoutMicroseconds = 500000;
- while (true)
+ // TODO #22608:
+ // Remove all of this cancellation workaround once Socket.ReceiveAsync
+ // that accepts a CancellationToken is available.
+
+ // If a cancelable token is used and there's no data, issue a zero-length read so that
+ // we're asynchronously notified when data is available, and concurrently monitor the
+ // supplied cancellation token. If cancellation is requested, we will end up "leaking"
+ // the zero-length read until data becomes available, at which point it'll be satisfied.
+ // But it's very rare to reuse a stream after an operation has been canceled, so even if
+ // we do incur such a situation, it's likely to be very short lived.
+ if (cancellationToken.CanBeCanceled)
{
cancellationToken.ThrowIfCancellationRequested();
- if (socket.Poll(timeout, SelectMode.SelectRead))
+ if (socket.Available == 0)
{
- return ReadCore(new Span<byte>(buffer, offset, count));
+ Task<int> t = socket.ReceiveAsync(Array.Empty<byte>(), SocketFlags.None);
+ if (!t.IsCompletedSuccessfully)
+ {
+ var cancelTcs = new TaskCompletionSource<bool>();
+ using (cancellationToken.Register(s => ((TaskCompletionSource<bool>)s).TrySetResult(true), cancelTcs))
+ {
+ if (t == await Task.WhenAny(t, cancelTcs.Task).ConfigureAwait(false))
+ {
+ t.GetAwaiter().GetResult(); // propagate any failure
+ }
+ cancellationToken.ThrowIfCancellationRequested();
+
+ // At this point there was data available. In the rare case where multiple concurrent
+ // ReadAsyncs are issued against the PipeStream, worst case is the reads that lose
+ // the race condition for the data will end up in a non-cancelable state as part of
+ // the actual async receive operation.
+ }
+ }
}
- timeout = Math.Min(timeout * 2, MaxTimeoutMicroseconds);
}
- }
- // The token wasn't cancelable, so we can simply use an async receive on the socket.
- try
- {
- return await socket.ReceiveAsync(new ArraySegment<byte>(buffer, offset, count), SocketFlags.None).ConfigureAwait(false);
+ // Issue the asynchronous read.
+ return await (destination.TryGetArray(out ArraySegment<byte> buffer) ?
+ socket.ReceiveAsync(buffer, SocketFlags.None) :
+ socket.ReceiveAsync(destination.ToArray(), SocketFlags.None)).ConfigureAwait(false);
}
catch (SocketException e)
{
@@ -192,11 +211,28 @@ namespace System.IO.Pipes
}
}
- private async Task WriteAsyncCore(byte[] buffer, int offset, int count, CancellationToken cancellationToken)
+ private async Task WriteAsyncCore(ReadOnlyMemory<byte> source, CancellationToken cancellationToken)
{
Debug.Assert(this is NamedPipeClientStream || this is NamedPipeServerStream, $"Expected a named pipe, got a {GetType()}");
try
{
+ // TODO #22608: Remove this terribly inefficient special-case once Socket.SendAsync
+ // accepts a Memory<T> in the near future.
+ byte[] buffer;
+ int offset, count;
+ if (source.DangerousTryGetArray(out ArraySegment<byte> segment))
+ {
+ buffer = segment.Array;
+ offset = segment.Offset;
+ count = segment.Count;
+ }
+ else
+ {
+ buffer = source.ToArray();
+ offset = 0;
+ count = buffer.Length;
+ }
+
while (count > 0)
{
// cancellationToken is (mostly) ignored. We could institute a polling loop like we do for reads if
diff --git a/src/System.IO.Pipes/src/System/IO/Pipes/PipeStream.Windows.cs b/src/System.IO.Pipes/src/System/IO/Pipes/PipeStream.Windows.cs
index ca92f17c32..22b62e4ad5 100644
--- a/src/System.IO.Pipes/src/System/IO/Pipes/PipeStream.Windows.cs
+++ b/src/System.IO.Pipes/src/System/IO/Pipes/PipeStream.Windows.cs
@@ -81,7 +81,7 @@ namespace System.IO.Pipes
}
[SecuritySafeCritical]
- private Task<int> ReadAsyncCore(byte[] buffer, int offset, int count, CancellationToken cancellationToken)
+ private Task<int> ReadAsyncCore(Memory<byte> buffer, CancellationToken cancellationToken)
{
var completionSource = new ReadWriteCompletionSource(this, buffer, cancellationToken, isWrite: false);
@@ -90,7 +90,7 @@ namespace System.IO.Pipes
int r;
unsafe
{
- r = ReadFileNative(_handle, new Span<byte>(buffer, offset, count), completionSource.Overlapped, out errorCode);
+ r = ReadFileNative(_handle, buffer.Span, completionSource.Overlapped, out errorCode);
}
// ReadFile, the OS version, will return 0 on failure, but this ReadFileNative wrapper
@@ -149,7 +149,7 @@ namespace System.IO.Pipes
}
[SecuritySafeCritical]
- private Task WriteAsyncCore(byte[] buffer, int offset, int count, CancellationToken cancellationToken)
+ private Task WriteAsyncCore(ReadOnlyMemory<byte> buffer, CancellationToken cancellationToken)
{
var completionSource = new ReadWriteCompletionSource(this, buffer, cancellationToken, isWrite: true);
int errorCode = 0;
@@ -158,7 +158,7 @@ namespace System.IO.Pipes
int r;
unsafe
{
- r = WriteFileNative(_handle, new ReadOnlySpan<byte>(buffer, offset, count), completionSource.Overlapped, out errorCode);
+ r = WriteFileNative(_handle, buffer.Span, completionSource.Overlapped, out errorCode);
}
// WriteFile, the OS version, will return 0 on failure, but this WriteFileNative
diff --git a/src/System.IO.Pipes/src/System/IO/Pipes/PipeStream.cs b/src/System.IO.Pipes/src/System/IO/Pipes/PipeStream.cs
index dbf467da54..928ad8a18a 100644
--- a/src/System.IO.Pipes/src/System/IO/Pipes/PipeStream.cs
+++ b/src/System.IO.Pipes/src/System/IO/Pipes/PipeStream.cs
@@ -172,7 +172,35 @@ namespace System.IO.Pipes
return s_zeroTask;
}
- return ReadAsyncCore(buffer, offset, count, cancellationToken);
+ return ReadAsyncCore(new Memory<byte>(buffer, offset, count), cancellationToken);
+ }
+
+ public override ValueTask<int> ReadAsync(Memory<byte> destination, CancellationToken cancellationToken = default(CancellationToken))
+ {
+ if (!_isAsync)
+ {
+ return base.ReadAsync(destination, cancellationToken);
+ }
+
+ if (!CanRead)
+ {
+ throw Error.GetReadNotSupported();
+ }
+
+ if (cancellationToken.IsCancellationRequested)
+ {
+ return new ValueTask<int>(Task.FromCanceled<int>(cancellationToken));
+ }
+
+ CheckReadOperations();
+
+ if (destination.Length == 0)
+ {
+ UpdateMessageCompletion(false);
+ return new ValueTask<int>(0);
+ }
+
+ return new ValueTask<int>(ReadAsyncCore(destination, cancellationToken));
}
public override IAsyncResult BeginRead(byte[] buffer, int offset, int count, AsyncCallback callback, object state)
@@ -253,7 +281,34 @@ namespace System.IO.Pipes
return Task.CompletedTask;
}
- return WriteAsyncCore(buffer, offset, count, cancellationToken);
+ return WriteAsyncCore(new ReadOnlyMemory<byte>(buffer, offset, count), cancellationToken);
+ }
+
+ public override Task WriteAsync(ReadOnlyMemory<byte> source, CancellationToken cancellationToken = default(CancellationToken))
+ {
+ if (!_isAsync)
+ {
+ return base.WriteAsync(source, cancellationToken);
+ }
+
+ if (!CanWrite)
+ {
+ throw Error.GetWriteNotSupported();
+ }
+
+ if (cancellationToken.IsCancellationRequested)
+ {
+ return Task.FromCanceled<int>(cancellationToken);
+ }
+
+ CheckWriteOperations();
+
+ if (source.Length == 0)
+ {
+ return Task.CompletedTask;
+ }
+
+ return WriteAsyncCore(source, cancellationToken);
}
public override IAsyncResult BeginWrite(byte[] buffer, int offset, int count, AsyncCallback callback, object state)
diff --git a/src/System.IO.Pipes/src/System/IO/Pipes/ReadWriteCompletionSource.cs b/src/System.IO.Pipes/src/System/IO/Pipes/ReadWriteCompletionSource.cs
index 174aba72e3..1008140011 100644
--- a/src/System.IO.Pipes/src/System/IO/Pipes/ReadWriteCompletionSource.cs
+++ b/src/System.IO.Pipes/src/System/IO/Pipes/ReadWriteCompletionSource.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.Threading;
namespace System.IO.Pipes
@@ -15,11 +14,9 @@ namespace System.IO.Pipes
private bool _isMessageComplete;
private int _numBytes; // number of buffer read OR written
- internal ReadWriteCompletionSource(PipeStream stream, byte[] buffer, CancellationToken cancellationToken, bool isWrite)
- : base(stream._threadPoolBinding, cancellationToken, pinData: buffer)
+ internal ReadWriteCompletionSource(PipeStream stream, ReadOnlyMemory<byte> bufferToPin, CancellationToken cancellationToken, bool isWrite)
+ : base(stream._threadPoolBinding, cancellationToken, bufferToPin)
{
- Debug.Assert(buffer != null, "buffer is null");
-
_pipeStream = stream;
_isWrite = isWrite;
_isMessageComplete = true;
diff --git a/src/System.IO.Pipes/tests/AnonymousPipeTests/AnonymousPipeTest.Specific.cs b/src/System.IO.Pipes/tests/AnonymousPipeTests/AnonymousPipeTest.Specific.cs
index b35086fa31..69d0a2ab2c 100644
--- a/src/System.IO.Pipes/tests/AnonymousPipeTests/AnonymousPipeTest.Specific.cs
+++ b/src/System.IO.Pipes/tests/AnonymousPipeTests/AnonymousPipeTest.Specific.cs
@@ -79,7 +79,7 @@ namespace System.IO.Pipes.Tests
}
}
- [Fact]
+ [ConditionalFact(typeof(PlatformDetection), "IsNotRedHat69")]
[PlatformSpecific(TestPlatforms.Linux)] // On Linux, setting the buffer size of the server will also set the buffer size of the client
public static void Linux_BufferSizeRoundtrips()
{
diff --git a/src/System.IO.Pipes/tests/Configurations.props b/src/System.IO.Pipes/tests/Configurations.props
index cfc57211a4..742254e254 100644
--- a/src/System.IO.Pipes/tests/Configurations.props
+++ b/src/System.IO.Pipes/tests/Configurations.props
@@ -4,6 +4,8 @@
<BuildConfigurations>
netstandard-Unix;
netstandard-Windows_NT;
+ netcoreapp-Unix;
+ netcoreapp-Windows_NT;
</BuildConfigurations>
</PropertyGroup>
</Project> \ No newline at end of file
diff --git a/src/System.IO.Pipes/tests/NamedPipeTests/NamedPipeTest.CrossProcess.cs b/src/System.IO.Pipes/tests/NamedPipeTests/NamedPipeTest.CrossProcess.cs
index 9df741d1bf..482d5f5910 100644
--- a/src/System.IO.Pipes/tests/NamedPipeTests/NamedPipeTest.CrossProcess.cs
+++ b/src/System.IO.Pipes/tests/NamedPipeTests/NamedPipeTest.CrossProcess.cs
@@ -88,7 +88,7 @@ namespace System.IO.Pipes.Tests
private static string GetUniquePipeName()
{
- if (PlatformDetection.IsWinRT)
+ if (PlatformDetection.IsInAppContainer)
{
return @"LOCAL\" + Path.GetRandomFileName();
}
diff --git a/src/System.IO.Pipes/tests/NamedPipeTests/NamedPipeTest.Read.cs b/src/System.IO.Pipes/tests/NamedPipeTests/NamedPipeTest.Read.cs
index 0585223659..c55abab909 100644
--- a/src/System.IO.Pipes/tests/NamedPipeTests/NamedPipeTest.Read.cs
+++ b/src/System.IO.Pipes/tests/NamedPipeTests/NamedPipeTest.Read.cs
@@ -67,8 +67,7 @@ namespace System.IO.Pipes.Tests
return ret;
}
- // InOut pipes can be written/read from either direction
- public override void WriteToReadOnlyPipe_Throws_NotSupportedException() { }
+ public override bool SupportsBidirectionalReadingWriting => true;
}
[ActiveIssue(22271, TargetFrameworkMonikers.UapNotUapAot)]
@@ -90,7 +89,6 @@ namespace System.IO.Pipes.Tests
return ret;
}
- // InOut pipes can be written/read from either direction
- public override void WriteToReadOnlyPipe_Throws_NotSupportedException() { }
+ public override bool SupportsBidirectionalReadingWriting => true;
}
}
diff --git a/src/System.IO.Pipes/tests/NamedPipeTests/NamedPipeTest.RunAsClient.Windows.cs b/src/System.IO.Pipes/tests/NamedPipeTests/NamedPipeTest.RunAsClient.Windows.cs
index a3e56015e7..9a5222d44d 100644
--- a/src/System.IO.Pipes/tests/NamedPipeTests/NamedPipeTest.RunAsClient.Windows.cs
+++ b/src/System.IO.Pipes/tests/NamedPipeTests/NamedPipeTest.RunAsClient.Windows.cs
@@ -35,7 +35,7 @@ namespace System.IO.Pipes.Tests
private static string GetUniquePipeName()
{
- if (PlatformDetection.IsWinRT)
+ if (PlatformDetection.IsInAppContainer)
{
return @"LOCAL\" + Path.GetRandomFileName();
}
diff --git a/src/System.IO.Pipes/tests/NamedPipeTests/NamedPipeTest.Specific.cs b/src/System.IO.Pipes/tests/NamedPipeTests/NamedPipeTest.Specific.cs
index 598c2212db..caaf0a8179 100644
--- a/src/System.IO.Pipes/tests/NamedPipeTests/NamedPipeTest.Specific.cs
+++ b/src/System.IO.Pipes/tests/NamedPipeTests/NamedPipeTest.Specific.cs
@@ -80,7 +80,7 @@ namespace System.IO.Pipes.Tests
[InlineData(PipeOptions.None)]
[InlineData(PipeOptions.Asynchronous)]
[PlatformSpecific(TestPlatforms.Windows)] // Unix currently doesn't support message mode
- public async Task Windows_MessagePipeTransissionMode(PipeOptions serverOptions)
+ public void Windows_MessagePipeTransmissionMode(PipeOptions serverOptions)
{
byte[] msg1 = new byte[] { 5, 7, 9, 10 };
byte[] msg2 = new byte[] { 2, 4 };
@@ -99,10 +99,10 @@ namespace System.IO.Pipes.Tests
server.ReadMode = PipeTransmissionMode.Message;
Assert.Equal(PipeTransmissionMode.Message, server.ReadMode);
+ client.Connect();
+
Task clientTask = Task.Run(() =>
{
- client.Connect();
-
client.Write(msg1, 0, msg1.Length);
client.Write(msg2, 0, msg2.Length);
client.Write(msg1, 0, msg1.Length);
@@ -115,54 +115,57 @@ namespace System.IO.Pipes.Tests
Assert.Equal(1, serverCount);
});
- server.WaitForConnection();
-
- int len1 = server.Read(received1, 0, msg1.Length);
- Assert.True(server.IsMessageComplete);
- Assert.Equal(msg1.Length, len1);
- Assert.Equal(msg1, received1);
-
- int len2 = server.Read(received2, 0, msg2.Length);
- Assert.True(server.IsMessageComplete);
- Assert.Equal(msg2.Length, len2);
- Assert.Equal(msg2, received2);
-
- int expectedRead = msg1.Length - 1;
- int len3 = server.Read(received3, 0, expectedRead); // read one less than message
- Assert.False(server.IsMessageComplete);
- Assert.Equal(expectedRead, len3);
- for (int i = 0; i < expectedRead; ++i)
+ Task serverTask = Task.Run(async () =>
{
- Assert.Equal(msg1[i], received3[i]);
- }
-
- expectedRead = msg1.Length - expectedRead;
- Assert.Equal(expectedRead, server.Read(received3, len3, expectedRead));
- Assert.True(server.IsMessageComplete);
- Assert.Equal(msg1, received3);
-
- Assert.Equal(msg1.Length, await server.ReadAsync(received4, 0, msg1.Length));
- Assert.True(server.IsMessageComplete);
- Assert.Equal(msg1, received4);
-
- Assert.Equal(msg2.Length, await server.ReadAsync(received5, 0, msg2.Length));
- Assert.True(server.IsMessageComplete);
- Assert.Equal(msg2, received5);
-
- expectedRead = msg1.Length - 1;
- Assert.Equal(expectedRead, await server.ReadAsync(received6, 0, expectedRead)); // read one less than message
- Assert.False(server.IsMessageComplete);
- for (int i = 0; i < expectedRead; ++i)
- {
- Assert.Equal(msg1[i], received6[i]);
- }
-
- expectedRead = msg1.Length - expectedRead;
- Assert.Equal(expectedRead, await server.ReadAsync(received6, msg1.Length - expectedRead, expectedRead));
- Assert.True(server.IsMessageComplete);
- Assert.Equal(msg1, received6);
+ server.WaitForConnection();
+
+ int len1 = server.Read(received1, 0, msg1.Length);
+ Assert.True(server.IsMessageComplete);
+ Assert.Equal(msg1.Length, len1);
+ Assert.Equal(msg1, received1);
+
+ int len2 = server.Read(received2, 0, msg2.Length);
+ Assert.True(server.IsMessageComplete);
+ Assert.Equal(msg2.Length, len2);
+ Assert.Equal(msg2, received2);
+
+ int expectedRead = msg1.Length - 1;
+ int len3 = server.Read(received3, 0, expectedRead); // read one less than message
+ Assert.False(server.IsMessageComplete);
+ Assert.Equal(expectedRead, len3);
+ for (int i = 0; i < expectedRead; ++i)
+ {
+ Assert.Equal(msg1[i], received3[i]);
+ }
+
+ expectedRead = msg1.Length - expectedRead;
+ Assert.Equal(expectedRead, server.Read(received3, len3, expectedRead));
+ Assert.True(server.IsMessageComplete);
+ Assert.Equal(msg1, received3);
+
+ Assert.Equal(msg1.Length, await server.ReadAsync(received4, 0, msg1.Length));
+ Assert.True(server.IsMessageComplete);
+ Assert.Equal(msg1, received4);
+
+ Assert.Equal(msg2.Length, await server.ReadAsync(received5, 0, msg2.Length));
+ Assert.True(server.IsMessageComplete);
+ Assert.Equal(msg2, received5);
+
+ expectedRead = msg1.Length - 1;
+ Assert.Equal(expectedRead, await server.ReadAsync(received6, 0, expectedRead)); // read one less than message
+ Assert.False(server.IsMessageComplete);
+ for (int i = 0; i < expectedRead; ++i)
+ {
+ Assert.Equal(msg1[i], received6[i]);
+ }
+
+ expectedRead = msg1.Length - expectedRead;
+ Assert.Equal(expectedRead, await server.ReadAsync(received6, msg1.Length - expectedRead, expectedRead));
+ Assert.True(server.IsMessageComplete);
+ Assert.Equal(msg1, received6);
+ });
- await clientTask;
+ Assert.True(Task.WaitAll(new[] { clientTask, serverTask }, TimeSpan.FromSeconds(15)));
}
}
}
@@ -233,7 +236,7 @@ namespace System.IO.Pipes.Tests
[Fact]
[PlatformSpecific(TestPlatforms.AnyUnix)] // Unix currently doesn't support message mode
- public void Unix_MessagePipeTransissionMode()
+ public void Unix_MessagePipeTransmissionMode()
{
Assert.Throws<PlatformNotSupportedException>(() => new NamedPipeServerStream(GetUniquePipeName(), PipeDirection.InOut, 1, PipeTransmissionMode.Message));
}
diff --git a/src/System.IO.Pipes/tests/NamedPipeTests/NamedPipeTest.Write.cs b/src/System.IO.Pipes/tests/NamedPipeTests/NamedPipeTest.Write.cs
index 6a92b0beea..6ec57c07c3 100644
--- a/src/System.IO.Pipes/tests/NamedPipeTests/NamedPipeTest.Write.cs
+++ b/src/System.IO.Pipes/tests/NamedPipeTests/NamedPipeTest.Write.cs
@@ -68,6 +68,6 @@ namespace System.IO.Pipes.Tests
}
// InOut pipes can be written/read from either direction
- public override void ReadOnWriteOnlyPipe_Throws_NotSupportedException() { }
+ public override bool SupportsBidirectionalReadingWriting => true;
}
}
diff --git a/src/System.IO.Pipes/tests/PipeTest.Read.cs b/src/System.IO.Pipes/tests/PipeTest.Read.cs
index ab63f28bd7..86ad322241 100644
--- a/src/System.IO.Pipes/tests/PipeTest.Read.cs
+++ b/src/System.IO.Pipes/tests/PipeTest.Read.cs
@@ -16,6 +16,8 @@ namespace System.IO.Pipes.Tests
/// </summary>
public abstract partial class PipeTest_Read : PipeTestBase
{
+ public virtual bool SupportsBidirectionalReadingWriting => false;
+
[Fact]
public void ReadWithNullBuffer_Throws_ArgumentNullException()
{
@@ -117,8 +119,13 @@ namespace System.IO.Pipes.Tests
}
[Fact]
- public virtual void WriteToReadOnlyPipe_Throws_NotSupportedException()
+ public void WriteToReadOnlyPipe_Throws_NotSupportedException()
{
+ if (SupportsBidirectionalReadingWriting)
+ {
+ return;
+ }
+
using (ServerClientPair pair = CreateServerClientPair())
{
PipeStream pipe = pair.readablePipe;
diff --git a/src/System.IO.Pipes/tests/PipeTest.Read.netcoreapp.cs b/src/System.IO.Pipes/tests/PipeTest.Read.netcoreapp.cs
new file mode 100644
index 0000000000..ecaedc9c73
--- /dev/null
+++ b/src/System.IO.Pipes/tests/PipeTest.Read.netcoreapp.cs
@@ -0,0 +1,134 @@
+// 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.Threading.Tasks;
+using Xunit;
+
+namespace System.IO.Pipes.Tests
+{
+ public abstract partial class PipeTest_Read : PipeTestBase
+ {
+ [Fact]
+ public void WriteToReadOnlyPipe_Span_Throws_NotSupportedException()
+ {
+ if (SupportsBidirectionalReadingWriting)
+ {
+ return;
+ }
+
+ using (ServerClientPair pair = CreateServerClientPair())
+ {
+ PipeStream pipe = pair.readablePipe;
+ Assert.True(pipe.IsConnected);
+ Assert.False(pipe.CanWrite);
+ Assert.False(pipe.CanSeek);
+
+ Assert.Throws<NotSupportedException>(() => pipe.Write(new ReadOnlySpan<byte>(new byte[5])));
+ Assert.Throws<NotSupportedException>(() => { pipe.WriteAsync(new ReadOnlyMemory<byte>(new byte[5])); });
+ }
+ }
+
+ [Fact]
+ public async Task ReadWithZeroLengthBuffer_Span_Nop()
+ {
+ using (ServerClientPair pair = CreateServerClientPair())
+ {
+ PipeStream pipe = pair.readablePipe;
+ var buffer = new byte[] { };
+
+ Assert.Equal(0, pipe.Read(new Span<byte>(buffer)));
+ ValueTask<int> read = pipe.ReadAsync(new Memory<byte>(buffer));
+ Assert.Equal(0, await read);
+ }
+ }
+
+ [Fact]
+ public void ReadOnDisposedReadablePipe_Span_Throws_ObjectDisposedException()
+ {
+ using (ServerClientPair pair = CreateServerClientPair())
+ {
+ PipeStream pipe = pair.readablePipe;
+ pipe.Dispose();
+ byte[] buffer = new byte[] { 0, 0, 0, 0 };
+
+ Assert.Throws<ObjectDisposedException>(() => pipe.Read(new Span<byte>(buffer)));
+ Assert.Throws<ObjectDisposedException>(() => { pipe.ReadAsync(new Memory<byte>(buffer)); });
+ }
+ }
+
+ [Fact]
+ [SkipOnTargetFramework(TargetFrameworkMonikers.NetFramework, "There is a bug in netfx around async read on a broken PipeStream. See #2601 and #2899. This bug is fixed in netcore.")]
+ public virtual async Task ReadFromPipeWithClosedPartner_Span_ReadNoBytes()
+ {
+ using (ServerClientPair pair = CreateServerClientPair())
+ {
+ pair.writeablePipe.Dispose();
+ byte[] buffer = new byte[] { 0, 0, 0, 0 };
+
+ // The pipe won't be marked as Broken until the first read, so prime it
+ // to test both the case where it's not yet marked as "Broken" and then
+ // where it is.
+ Assert.Equal(0, pair.readablePipe.Read(new Span<byte>(buffer)));
+
+ Assert.Equal(0, pair.readablePipe.Read(new Span<byte>(buffer)));
+ Assert.Equal(0, await pair.readablePipe.ReadAsync(new Memory<byte>(buffer)));
+ }
+ }
+
+ [Fact]
+ public async Task ValidWriteAsync_Span_ValidReadAsync()
+ {
+ using (ServerClientPair pair = CreateServerClientPair())
+ {
+ Assert.True(pair.writeablePipe.IsConnected);
+ Assert.True(pair.readablePipe.IsConnected);
+
+ byte[] sent = new byte[] { 123, 0, 5 };
+ byte[] received = new byte[] { 0, 0, 0 };
+
+ Task write = pair.writeablePipe.WriteAsync(new ReadOnlyMemory<byte>(sent));
+ Assert.Equal(sent.Length, await pair.readablePipe.ReadAsync(new Memory<byte>(received, 0, sent.Length)));
+ Assert.Equal(sent, received);
+ await write;
+ }
+ }
+
+ [Theory]
+ [OuterLoop]
+ [MemberData(nameof(AsyncReadWriteChain_MemberData))]
+ public async Task AsyncReadWriteChain_Span_ReadWrite(int iterations, int writeBufferSize, int readBufferSize, bool cancelableToken)
+ {
+ var writeBuffer = new byte[writeBufferSize];
+ var readBuffer = new byte[readBufferSize];
+ var rand = new Random();
+ var cancellationToken = cancelableToken ? new CancellationTokenSource().Token : CancellationToken.None;
+
+ using (ServerClientPair pair = CreateServerClientPair())
+ {
+ // Repeatedly and asynchronously write to the writable pipe and read from the readable pipe,
+ // verifying that the correct data made it through.
+ for (int iter = 0; iter < iterations; iter++)
+ {
+ rand.NextBytes(writeBuffer);
+ Task writerTask = pair.writeablePipe.WriteAsync(new ReadOnlyMemory<byte>(writeBuffer), cancellationToken);
+
+ int totalRead = 0;
+ while (totalRead < writeBuffer.Length)
+ {
+ int numRead = await pair.readablePipe.ReadAsync(new Memory<byte>(readBuffer), cancellationToken);
+ Assert.True(numRead > 0);
+ Assert.Equal<byte>(
+ new ArraySegment<byte>(writeBuffer, totalRead, numRead),
+ new ArraySegment<byte>(readBuffer, 0, numRead));
+ totalRead += numRead;
+ }
+ Assert.Equal(writeBuffer.Length, totalRead);
+
+ await writerTask;
+ }
+ }
+ }
+ }
+}
diff --git a/src/System.IO.Pipes/tests/PipeTest.Write.cs b/src/System.IO.Pipes/tests/PipeTest.Write.cs
index 2a97ce3608..9d7d4dc9fc 100644
--- a/src/System.IO.Pipes/tests/PipeTest.Write.cs
+++ b/src/System.IO.Pipes/tests/PipeTest.Write.cs
@@ -12,8 +12,10 @@ namespace System.IO.Pipes.Tests
/// Tests that cover Write and WriteAsync behaviors that are shared between
/// AnonymousPipes and NamedPipes
/// </summary>
- public abstract class PipeTest_Write : PipeTestBase
+ public abstract partial class PipeTest_Write : PipeTestBase
{
+ public virtual bool SupportsBidirectionalReadingWriting => false;
+
[Fact]
public void WriteWithNullBuffer_Throws_ArgumentNullException()
{
@@ -117,8 +119,13 @@ namespace System.IO.Pipes.Tests
}
[Fact]
- public virtual void ReadOnWriteOnlyPipe_Throws_NotSupportedException()
+ public void ReadOnWriteOnlyPipe_Throws_NotSupportedException()
{
+ if (SupportsBidirectionalReadingWriting)
+ {
+ return;
+ }
+
using (ServerClientPair pair = CreateServerClientPair())
{
PipeStream pipe = pair.writeablePipe;
diff --git a/src/System.IO.Pipes/tests/PipeTest.Write.netcoreapp.cs b/src/System.IO.Pipes/tests/PipeTest.Write.netcoreapp.cs
new file mode 100644
index 0000000000..c6d34da58c
--- /dev/null
+++ b/src/System.IO.Pipes/tests/PipeTest.Write.netcoreapp.cs
@@ -0,0 +1,84 @@
+// 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;
+using System.Threading.Tasks;
+using Xunit;
+
+namespace System.IO.Pipes.Tests
+{
+ /// <summary>
+ /// Tests that cover Write and WriteAsync behaviors that are shared between
+ /// AnonymousPipes and NamedPipes
+ /// </summary>
+ public abstract partial class PipeTest_Write : PipeTestBase
+ {
+ [Fact]
+ public void ReadOnWriteOnlyPipe_Span_Throws_NotSupportedException()
+ {
+ if (SupportsBidirectionalReadingWriting)
+ {
+ return;
+ }
+
+ using (ServerClientPair pair = CreateServerClientPair())
+ {
+ PipeStream pipe = pair.writeablePipe;
+ Assert.True(pipe.IsConnected);
+ Assert.False(pipe.CanRead);
+
+ Assert.Throws<NotSupportedException>(() => pipe.Read(new Span<byte>(new byte[9])));
+ Assert.Throws<NotSupportedException>(() => { pipe.ReadAsync(new Memory<byte>(new byte[10])); });
+ }
+ }
+
+ [Fact]
+ public async Task WriteZeroLengthBuffer_Span_Nop()
+ {
+ using (ServerClientPair pair = CreateServerClientPair())
+ {
+ PipeStream pipe = pair.writeablePipe;
+
+ // Shouldn't throw
+ pipe.Write(new Span<byte>(Array.Empty<byte>()));
+ await pipe.WriteAsync(new Memory<byte>(Array.Empty<byte>()));
+ }
+ }
+
+ [Fact]
+ public void WriteToDisposedWriteablePipe_Span_Throws_ObjectDisposedException()
+ {
+ using (ServerClientPair pair = CreateServerClientPair())
+ {
+ PipeStream pipe = pair.writeablePipe;
+ pipe.Dispose();
+ byte[] buffer = new byte[] { 0, 0, 0, 0 };
+
+ Assert.Throws<ObjectDisposedException>(() => pipe.Write(new Span<byte>(buffer)));
+ Assert.Throws<ObjectDisposedException>(() => { pipe.WriteAsync(new Memory<byte>(buffer)); });
+ }
+ }
+
+ [Fact]
+ public virtual void WriteToPipeWithClosedPartner_Span_Throws_IOException()
+ {
+ using (ServerClientPair pair = CreateServerClientPair())
+ {
+ if (!RuntimeInformation.IsOSPlatform(OSPlatform.Windows) &&
+ (pair.readablePipe is NamedPipeClientStream || pair.writeablePipe is NamedPipeClientStream))
+ {
+ // On Unix, NamedPipe*Stream is implemented in term of sockets, where information
+ // about shutdown is not immediately propagated.
+ return;
+ }
+
+ pair.readablePipe.Dispose();
+ byte[] buffer = new byte[] { 0, 0, 0, 0 };
+
+ Assert.Throws<IOException>(() => pair.writeablePipe.Write(new Span<byte>(buffer)));
+ Assert.Throws<IOException>(() => { pair.writeablePipe.WriteAsync(new Memory<byte>(buffer)); });
+ }
+ }
+ }
+}
diff --git a/src/System.IO.Pipes/tests/PipeTestBase.cs b/src/System.IO.Pipes/tests/PipeTestBase.cs
index b1efd342bd..796ee5688a 100644
--- a/src/System.IO.Pipes/tests/PipeTestBase.cs
+++ b/src/System.IO.Pipes/tests/PipeTestBase.cs
@@ -80,7 +80,7 @@ namespace System.IO.Pipes.Tests
/// <returns></returns>
protected static string GetUniquePipeName()
{
- if (PlatformDetection.IsWinRT)
+ if (PlatformDetection.IsInAppContainer)
{
return @"LOCAL\" + Path.GetRandomFileName();
}
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 8db2657104..e60965a979 100644
--- a/src/System.IO.Pipes/tests/System.IO.Pipes.Tests.csproj
+++ b/src/System.IO.Pipes/tests/System.IO.Pipes.Tests.csproj
@@ -11,6 +11,10 @@
<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)' == 'netcoreapp-Unix-Debug|AnyCPU'" />
+ <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'" />
<ItemGroup>
<Compile Include="NamedPipeTests\NamedPipeTest.cs" />
<Compile Include="PipeTest.cs" />
@@ -29,6 +33,8 @@
<Compile Include="NamedPipeTests\NamedPipeTest.Write.cs" />
<Compile Include="NamedPipeTests\NamedPipeTest.Specific.cs" />
<Compile Include="NamedPipeTests\NamedPipeTest.Simple.cs" />
+ <Compile Include="PipeTest.Read.netcoreapp.cs" Condition="'$(TargetGroup)' == 'netcoreapp'" />
+ <Compile Include="PipeTest.Write.netcoreapp.cs" Condition="'$(TargetGroup)' == 'netcoreapp'" />
<Compile Include="PipeTestBase.cs" />
<Compile Include="PipeTest.Read.cs" />
<Compile Include="PipeTest.Write.cs" />
@@ -50,4 +56,4 @@
</ProjectReference>
</ItemGroup>
<Import Project="$([MSBuild]::GetDirectoryNameOfFileAbove($(MSBuildThisFileDirectory), dir.targets))\dir.targets" />
-</Project>
+</Project> \ No newline at end of file
diff --git a/src/System.IO.Ports/ref/System.IO.Ports.csproj b/src/System.IO.Ports/ref/System.IO.Ports.csproj
index b1225e47c8..0f40a66c0f 100644
--- a/src/System.IO.Ports/ref/System.IO.Ports.csproj
+++ b/src/System.IO.Ports/ref/System.IO.Ports.csproj
@@ -4,6 +4,9 @@
<PropertyGroup>
<ProjectGuid>{75DE4259-43BB-4067-9F30-3AC920D51AEC}</ProjectGuid>
<IsPartialFacadeAssembly Condition="'$(TargetGroup)' == 'netfx'">true</IsPartialFacadeAssembly>
+ <!-- Must match version supported by frameworks which support 4.0.* inbox.
+ Can be removed when API is added and this assembly is versioned to 4.1.* -->
+ <AssemblyVersion Condition="'$(TargetsNetFx)' != 'true'">4.0.1.0</AssemblyVersion>
</PropertyGroup>
<PropertyGroup Condition="'$(Configuration)|$(Platform)' == 'netstandard-Debug|AnyCPU'" />
<PropertyGroup Condition="'$(Configuration)|$(Platform)' == 'netstandard-Release|AnyCPU'" />
diff --git a/src/System.IO.Ports/src/PinvokeAnalyzerExceptionList.analyzerdata b/src/System.IO.Ports/src/PinvokeAnalyzerExceptionList.analyzerdata
deleted file mode 100644
index 0719fa0f9d..0000000000
--- a/src/System.IO.Ports/src/PinvokeAnalyzerExceptionList.analyzerdata
+++ /dev/null
@@ -1,3 +0,0 @@
-## need to create a uap config that uses CreateFileFromApp, then remove this baseline ##
-# https://github.com/dotnet/corefx/issues/21025
-kernel32.dll!CreateFileW \ No newline at end of file
diff --git a/src/System.IO.Ports/src/PinvokeAnalyzerExceptionList.analyzerdata.netstandard b/src/System.IO.Ports/src/PinvokeAnalyzerExceptionList.analyzerdata.netstandard
new file mode 100644
index 0000000000..a60530e769
--- /dev/null
+++ b/src/System.IO.Ports/src/PinvokeAnalyzerExceptionList.analyzerdata.netstandard
@@ -0,0 +1,2 @@
+# not available in OneCore
+kernel32.dll!CreateFileW
diff --git a/src/System.IO.Ports/src/System.IO.Ports.csproj b/src/System.IO.Ports/src/System.IO.Ports.csproj
index 090190981c..e9268ac8d0 100644
--- a/src/System.IO.Ports/src/System.IO.Ports.csproj
+++ b/src/System.IO.Ports/src/System.IO.Ports.csproj
@@ -85,9 +85,6 @@
<Compile Include="$(CommonPath)\Interop\Windows\kernel32\Interop.WaitCommEvent.cs">
<Link>Common\Interop\Windows\kernel32\Interop.WaitCommEvent.cs</Link>
</Compile>
- <Compile Include="$(CommonPath)\Interop\Windows\kernel32\Interop.CreateFile.cs">
- <Link>Common\Interop\Windows\kernel32\Interop.CreateFile.cs</Link>
- </Compile>
<Compile Include="$(CommonPath)\Interop\Windows\kernel32\Interop.ReadFile_SafeHandle_IntPtr.cs">
<Link>Common\Interop\Windows\kernel32\Interop.ReadFile_SafeHandle_IntPtr.cs</Link>
</Compile>
@@ -134,6 +131,11 @@
<Link>Common\Interop\Windows\Interop.BOOL.cs</Link>
</Compile>
</ItemGroup>
+ <ItemGroup Condition="'$(TargetGroup)' != 'uap' and '$(TargetsWindows)' == 'true'">
+ <Compile Include="$(CommonPath)\Interop\Windows\kernel32\Interop.CreateFile.cs">
+ <Link>Common\Interop\Windows\kernel32\Interop.CreateFile.cs</Link>
+ </Compile>
+ </ItemGroup>
<ItemGroup Condition="'$(TargetGroup)' == 'uap'">
<Compile Include="System\IO\Ports\SerialPort.Uap.cs" />
<Compile Include="System\IO\Ports\SerialStream.Uap.cs" />
diff --git a/src/System.IO.Ports/tests/SerialPort/ReadTo.cs b/src/System.IO.Ports/tests/SerialPort/ReadTo.cs
index d32a574d8a..007be6b054 100644
--- a/src/System.IO.Ports/tests/SerialPort/ReadTo.cs
+++ b/src/System.IO.Ports/tests/SerialPort/ReadTo.cs
@@ -314,7 +314,7 @@ namespace System.IO.Ports.Tests
{
using (SerialPort com = new SerialPort(TCSupport.LocalMachineSerialInfo.FirstAvailablePortName))
{
- Debug.WriteLine("Verifying read method thows ArgumentExcpetion with a null NewLine string");
+ Debug.WriteLine("Verifying read method throws ArgumentExcpetion with a null NewLine string");
com.Open();
VerifyReadException(com, null, typeof(ArgumentNullException));
@@ -326,7 +326,7 @@ namespace System.IO.Ports.Tests
{
using (SerialPort com = new SerialPort(TCSupport.LocalMachineSerialInfo.FirstAvailablePortName))
{
- Debug.WriteLine("Verifying read method thows ArgumentExcpetion with a empty NewLine string");
+ Debug.WriteLine("Verifying read method throws ArgumentExcpetion with an empty NewLine string");
com.Open();
VerifyReadException(com, "", typeof(ArgumentException));
diff --git a/src/System.IO.Ports/tests/SerialPort/Read_byte_int_int.cs b/src/System.IO.Ports/tests/SerialPort/Read_byte_int_int.cs
index f584039f3b..b60f98995b 100644
--- a/src/System.IO.Ports/tests/SerialPort/Read_byte_int_int.cs
+++ b/src/System.IO.Ports/tests/SerialPort/Read_byte_int_int.cs
@@ -27,10 +27,10 @@ namespace System.IO.Ports.Tests
private const int defaultByteOffset = 0;
private const int defaultByteCount = 1;
- //The maximum buffer size when a exception occurs
+ //The maximum buffer size when an exception occurs
private const int maxBufferSizeForException = 255;
- //The maximum buffer size when a exception is not expected
+ //The maximum buffer size when an exception is not expected
private const int maxBufferSize = 8;
private enum ReadDataFromEnum { NonBuffered, Buffered, BufferedAndNonBuffered };
diff --git a/src/System.IO.Ports/tests/SerialPort/Read_char_int_int.cs b/src/System.IO.Ports/tests/SerialPort/Read_char_int_int.cs
index 067d6eaefc..9f960bfff2 100644
--- a/src/System.IO.Ports/tests/SerialPort/Read_char_int_int.cs
+++ b/src/System.IO.Ports/tests/SerialPort/Read_char_int_int.cs
@@ -28,10 +28,10 @@ namespace System.IO.Ports.Tests
private const int defaultCharOffset = 0;
private const int defaultCharCount = 1;
- //The maximum buffer size when a exception occurs
+ //The maximum buffer size when an exception occurs
private const int maxBufferSizeForException = 255;
- //The maximum buffer size when a exception is not expected
+ //The maximum buffer size when an exception is not expected
private const int maxBufferSize = 8;
public enum ReadDataFromEnum { NonBuffered, Buffered, BufferedAndNonBuffered };
diff --git a/src/System.IO.Ports/tests/SerialPort/Write_byte_int_int.cs b/src/System.IO.Ports/tests/SerialPort/Write_byte_int_int.cs
index 63d95abbd9..1e8a12325f 100644
--- a/src/System.IO.Ports/tests/SerialPort/Write_byte_int_int.cs
+++ b/src/System.IO.Ports/tests/SerialPort/Write_byte_int_int.cs
@@ -23,10 +23,10 @@ namespace System.IO.Ports.Tests
private const int DEFAULT_BUFFER_OFFSET = 0;
private const int DEFAULT_BUFFER_COUNT = 1;
- //The maximum buffer size when a exception occurs
+ //The maximum buffer size when an exception occurs
private const int MAX_BUFFER_SIZE_FOR_EXCEPTION = 255;
- //The maximum buffer size when a exception is not expected
+ //The maximum buffer size when an exception is not expected
private const int MAX_BUFFER_SIZE = 8;
//The default number of times the write method is called when verifying write
diff --git a/src/System.IO.Ports/tests/SerialPort/Write_char_int_int.cs b/src/System.IO.Ports/tests/SerialPort/Write_char_int_int.cs
index 1f2bf7115c..1cebe54ede 100644
--- a/src/System.IO.Ports/tests/SerialPort/Write_char_int_int.cs
+++ b/src/System.IO.Ports/tests/SerialPort/Write_char_int_int.cs
@@ -23,10 +23,10 @@ namespace System.IO.Ports.Tests
private const int DEFAULT_CHAR_OFFSET = 0;
private const int DEFAULT_CHAR_COUNT = 1;
- //The maximum buffer size when a exception occurs
+ //The maximum buffer size when an exception occurs
private const int MAX_BUFFER_SIZE_FOR_EXCEPTION = 255;
- //The maximum buffer size when a exception is not expected
+ //The maximum buffer size when an exception is not expected
private const int MAX_BUFFER_SIZE = 8;
//The default number of times the write method is called when verifying write
diff --git a/src/System.IO.Ports/tests/SerialStream/BeginRead.cs b/src/System.IO.Ports/tests/SerialStream/BeginRead.cs
index f6fae70314..a637413f9b 100644
--- a/src/System.IO.Ports/tests/SerialStream/BeginRead.cs
+++ b/src/System.IO.Ports/tests/SerialStream/BeginRead.cs
@@ -26,10 +26,10 @@ namespace System.IO.Ports.Tests
private const int defaultByteOffset = 0;
private const int defaultByteCount = 1;
- // The maximum buffer size when a exception occurs
+ // The maximum buffer size when an exception occurs
private const int maxBufferSizeForException = 255;
- // The maximum buffer size when a exception is not expected
+ // The maximum buffer size when an exception is not expected
private const int maxBufferSize = 8;
// Maximum time to wait for processing the read command to complete
diff --git a/src/System.IO.Ports/tests/SerialStream/BeginWrite.cs b/src/System.IO.Ports/tests/SerialStream/BeginWrite.cs
index 40934daf83..37dd8a5066 100644
--- a/src/System.IO.Ports/tests/SerialStream/BeginWrite.cs
+++ b/src/System.IO.Ports/tests/SerialStream/BeginWrite.cs
@@ -23,10 +23,10 @@ namespace System.IO.Ports.Tests
private const int DEFAULT_BUFFER_OFFSET = 0;
private const int DEFAULT_BUFFER_COUNT = 1;
- // The maximum buffer size when a exception occurs
+ // The maximum buffer size when an exception occurs
private const int MAX_BUFFER_SIZE_FOR_EXCEPTION = 255;
- // The maximum buffer size when a exception is not expected
+ // The maximum buffer size when an exception is not expected
private const int MAX_BUFFER_SIZE = 8;
// The default number of times the write method is called when verifying write
diff --git a/src/System.IO.Ports/tests/SerialStream/Read_byte_int_int.cs b/src/System.IO.Ports/tests/SerialStream/Read_byte_int_int.cs
index 5564f751fe..144bfe2e72 100644
--- a/src/System.IO.Ports/tests/SerialStream/Read_byte_int_int.cs
+++ b/src/System.IO.Ports/tests/SerialStream/Read_byte_int_int.cs
@@ -25,10 +25,10 @@ namespace System.IO.Ports.Tests
private const int defaultByteOffset = 0;
private const int defaultByteCount = 1;
- // The maximum buffer size when a exception occurs
+ // The maximum buffer size when an exception occurs
private const int maxBufferSizeForException = 255;
- // The maximum buffer size when a exception is not expected
+ // The maximum buffer size when an exception is not expected
private const int maxBufferSize = 8;
#region Test Cases
diff --git a/src/System.IO.Ports/tests/SerialStream/Write_byte_int_int.cs b/src/System.IO.Ports/tests/SerialStream/Write_byte_int_int.cs
index 33b650e9db..170bdfeb01 100644
--- a/src/System.IO.Ports/tests/SerialStream/Write_byte_int_int.cs
+++ b/src/System.IO.Ports/tests/SerialStream/Write_byte_int_int.cs
@@ -23,10 +23,10 @@ namespace System.IO.Ports.Tests
private const int DEFAULT_BUFFER_OFFSET = 0;
private const int DEFAULT_BUFFER_COUNT = 1;
- // The maximum buffer size when a exception occurs
+ // The maximum buffer size when an exception occurs
private const int MAX_BUFFER_SIZE_FOR_EXCEPTION = 255;
- // The maximum buffer size when a exception is not expected
+ // The maximum buffer size when an exception is not expected
private const int MAX_BUFFER_SIZE = 8;
// The default number of times the write method is called when verifying write
diff --git a/src/System.IO.UnmanagedMemoryStream/tests/UmsReadWrite.netcoreapp.cs b/src/System.IO.UnmanagedMemoryStream/tests/UmsReadWrite.netcoreapp.cs
index 0432d5a7c9..a438d9cf42 100644
--- a/src/System.IO.UnmanagedMemoryStream/tests/UmsReadWrite.netcoreapp.cs
+++ b/src/System.IO.UnmanagedMemoryStream/tests/UmsReadWrite.netcoreapp.cs
@@ -11,4 +11,12 @@ namespace System.IO.Tests
public override void Write(UnmanagedMemoryStream stream, byte[] array, int offset, int count) =>
stream.Write(new Span<byte>(array, offset, count));
}
+
+ public sealed class MemoryUmsReadWriteTests : UmsReadWriteTests
+ {
+ public override int Read(UnmanagedMemoryStream stream, byte[] array, int offset, int count) =>
+ stream.ReadAsync(new Memory<byte>(array, offset, count)).GetAwaiter().GetResult();
+ public override void Write(UnmanagedMemoryStream stream, byte[] array, int offset, int count) =>
+ stream.WriteAsync(new Memory<byte>(array, offset, count)).GetAwaiter().GetResult();
+ }
}
diff --git a/src/System.IO/tests/BinaryReader/BinaryReaderTests.cs b/src/System.IO/tests/BinaryReader/BinaryReaderTests.cs
index 7764e7b60d..f64de6936f 100644
--- a/src/System.IO/tests/BinaryReader/BinaryReaderTests.cs
+++ b/src/System.IO/tests/BinaryReader/BinaryReaderTests.cs
@@ -5,12 +5,13 @@
using System;
using System.Collections.Generic;
using System.IO;
+using System.Linq;
using System.Text;
using Xunit;
namespace System.IO.Tests
{
- public class BinaryReaderTests
+ public partial class BinaryReaderTests
{
protected virtual Stream CreateStream()
{
@@ -130,5 +131,62 @@ namespace System.IO.Tests
}
}
}
+
+ [Theory]
+ [InlineData(100, 0, 100, 100, 100)]
+ [InlineData(100, 25, 50, 100, 50)]
+ [InlineData(50, 0, 100, 100, 50)]
+ [InlineData(0, 0, 10, 10, 0)]
+ public void Read_CharArray(int sourceSize, int index, int count, int destinationSize, int expectedReadLength)
+ {
+ using (var stream = CreateStream())
+ {
+ var source = new char[sourceSize];
+ var random = new Random(345);
+
+ for (int i = 0; i < sourceSize; i++)
+ {
+ source[i] = (char)random.Next(0, 127);
+ }
+
+ stream.Write(Encoding.ASCII.GetBytes(source), 0, source.Length);
+ stream.Position = 0;
+
+ using (var reader = new BinaryReader(stream, Encoding.ASCII))
+ {
+ var destination = new char[destinationSize];
+
+ int readCount = reader.Read(destination, index, count);
+
+ Assert.Equal(expectedReadLength, readCount);
+ Assert.Equal(source.Take(readCount), destination.Skip(index).Take(readCount));
+
+ // Make sure we didn't write past the end
+ Assert.True(destination.Skip(readCount + index).All(b => b == default(char)));
+ }
+ }
+ }
+
+ [Theory]
+ [InlineData(new[] { 'h', 'e', 'l', 'l', 'o' }, 5, new[] { 'h', 'e', 'l', 'l', 'o' })]
+ [InlineData(new[] { 'h', 'e', 'l', 'l', 'o' }, 8, new[] { 'h', 'e', 'l', 'l', 'o' })]
+ [InlineData(new[] { 'h', 'e', '\0', '\0', 'o' }, 5, new[] { 'h', 'e', '\0', '\0', 'o' })]
+ [InlineData(new[] { 'h', 'e', 'l', 'l', 'o' }, 0, new char[0])]
+ [InlineData(new char[0], 5, new char[0])]
+ public void ReadChars(char[] source, int readLength, char[] expected)
+ {
+ using (var stream = CreateStream())
+ {
+ stream.Write(Encoding.ASCII.GetBytes(source), 0, source.Length);
+ stream.Position = 0;
+
+ using (var reader = new BinaryReader(stream))
+ {
+ var destination = reader.ReadChars(readLength);
+
+ Assert.Equal(expected, destination);
+ }
+ }
+ }
}
}
diff --git a/src/System.IO/tests/BinaryReader/BinaryReaderTests.netcoreapp.cs b/src/System.IO/tests/BinaryReader/BinaryReaderTests.netcoreapp.cs
new file mode 100644
index 0000000000..8cd56e7169
--- /dev/null
+++ b/src/System.IO/tests/BinaryReader/BinaryReaderTests.netcoreapp.cs
@@ -0,0 +1,97 @@
+using System.Linq;
+using System.Text;
+using Xunit;
+
+namespace System.IO.Tests
+{
+ public partial class BinaryReaderTests
+ {
+ [Theory]
+ [InlineData(100, 100, 100)]
+ [InlineData(100, 50, 50)]
+ [InlineData(50, 100, 50)]
+ [InlineData(10, 0, 0)]
+ [InlineData(0, 10, 0)]
+ public void Read_ByteSpan(int sourceSize, int destinationSize, int expectedReadLength)
+ {
+ using (var stream = CreateStream())
+ {
+ var source = new byte[sourceSize];
+ new Random(345).NextBytes(source);
+ stream.Write(source, 0, source.Length);
+ stream.Position = 0;
+
+ using (var reader = new BinaryReader(stream))
+ {
+ var destination = new byte[destinationSize];
+
+ int readCount = reader.Read(new Span<byte>(destination));
+
+ Assert.Equal(expectedReadLength, readCount);
+ Assert.Equal(source.Take(expectedReadLength), destination.Take(expectedReadLength));
+
+ // Make sure we didn't write past the end
+ Assert.True(destination.Skip(expectedReadLength).All(b => b == default(byte)));
+ }
+ }
+ }
+
+ [Fact]
+ public void Read_ByteSpan_ThrowIfDisposed()
+ {
+ using (var memStream = CreateStream())
+ {
+ var binaryReader = new BinaryReader(memStream);
+ binaryReader.Dispose();
+ Assert.Throws<ObjectDisposedException>(() => binaryReader.Read(new Span<byte>()));
+ }
+ }
+
+ [Theory]
+ [InlineData(100, 100, 100)]
+ [InlineData(100, 50, 50)]
+ [InlineData(50, 100, 50)]
+ [InlineData(10, 0, 0)]
+ [InlineData(0, 10, 0)]
+ public void Read_CharSpan(int sourceSize, int destinationSize, int expectedReadLength)
+ {
+ using (var stream = CreateStream())
+ {
+ var source = new char[sourceSize];
+ var random = new Random(345);
+
+ for (int i = 0; i < sourceSize; i++)
+ {
+ source[i] = (char)random.Next(0, 127);
+ }
+
+ stream.Write(Encoding.ASCII.GetBytes(source), 0, source.Length);
+ stream.Position = 0;
+
+ using (var reader = new BinaryReader(stream, Encoding.ASCII))
+ {
+ var destination = new char[destinationSize];
+
+ int readCount = reader.Read(new Span<char>(destination));
+
+ Assert.Equal(expectedReadLength, readCount);
+ Assert.Equal(source.Take(expectedReadLength), destination.Take(expectedReadLength));
+
+ // Make sure we didn't write past the end
+ Assert.True(destination.Skip(expectedReadLength).All(b => b == default(char)));
+ }
+ }
+ }
+
+ [Fact]
+ public void Read_CharSpan_ThrowIfDisposed()
+ {
+ using (var memStream = CreateStream())
+ {
+ var binaryReader = new BinaryReader(memStream);
+ binaryReader.Dispose();
+ Assert.Throws<ObjectDisposedException>(() => binaryReader.Read(new Span<char>()));
+ }
+ }
+ }
+}
diff --git a/src/System.IO/tests/BufferedStream/BufferedStreamTests.cs b/src/System.IO/tests/BufferedStream/BufferedStreamTests.cs
index 259f82b274..17d4f2d502 100644
--- a/src/System.IO/tests/BufferedStream/BufferedStreamTests.cs
+++ b/src/System.IO/tests/BufferedStream/BufferedStreamTests.cs
@@ -29,7 +29,7 @@ namespace System.IO.Tests
{
tasks[i] = stream.WriteAsync(data, 250 * i, 250);
}
- Assert.False(tasks.All(t => t.IsCompleted));
+ Assert.All(tasks, t => Assert.Equal(TaskStatus.WaitingForActivation, t.Status));
mcaos.Release();
await Task.WhenAll(tasks);
@@ -264,13 +264,22 @@ namespace System.IO.Tests
}
}
- internal sealed class ManuallyReleaseAsyncOperationsStream : MemoryStream
+ internal sealed class ManuallyReleaseAsyncOperationsStream : Stream
{
+ private readonly MemoryStream _stream = new MemoryStream();
private readonly TaskCompletionSource<bool> _tcs = new TaskCompletionSource<bool>(TaskCreationOptions.RunContinuationsAsynchronously);
private bool _canSeek = true;
public override bool CanSeek => _canSeek;
+ public override bool CanRead => _stream.CanRead;
+
+ public override bool CanWrite => _stream.CanWrite;
+
+ public override long Length => _stream.Length;
+
+ public override long Position { get => _stream.Position; set => _stream.Position = value; }
+
public void SetCanSeek(bool canSeek) => _canSeek = canSeek;
public void Release() { _tcs.SetResult(true); }
@@ -278,38 +287,44 @@ namespace System.IO.Tests
public override async Task<int> ReadAsync(byte[] buffer, int offset, int count, CancellationToken cancellationToken)
{
await _tcs.Task;
- return await base.ReadAsync(buffer, offset, count, cancellationToken);
+ return await _stream.ReadAsync(buffer, offset, count, cancellationToken);
}
public override async Task WriteAsync(byte[] buffer, int offset, int count, CancellationToken cancellationToken)
{
await _tcs.Task;
- await base.WriteAsync(buffer, offset, count, cancellationToken);
+ await _stream.WriteAsync(buffer, offset, count, cancellationToken);
}
public override async Task FlushAsync(CancellationToken cancellationToken)
{
await _tcs.Task;
- await base.FlushAsync(cancellationToken);
+ await _stream.FlushAsync(cancellationToken);
}
+
+ public override void Flush() => _stream.Flush();
+ public override int Read(byte[] buffer, int offset, int count) => _stream.Read(buffer, offset, count);
+ public override long Seek(long offset, SeekOrigin origin) => _stream.Seek(offset, origin);
+ public override void SetLength(long value) => _stream.SetLength(value);
+ public override void Write(byte[] buffer, int offset, int count) => _stream.Write(buffer, offset, count);
}
internal sealed class ThrowsExceptionFromAsyncOperationsStream : MemoryStream
{
- public override Task<int> ReadAsync(byte[] buffer, int offset, int count, CancellationToken cancellationToken)
- {
+ public override int Read(byte[] buffer, int offset, int count) =>
throw new InvalidOperationException("Exception from ReadAsync");
- }
- public override Task WriteAsync(byte[] buffer, int offset, int count, CancellationToken cancellationToken)
- {
+ public override void Write(byte[] buffer, int offset, int count) =>
+ throw new InvalidOperationException("Exception from ReadAsync");
+
+ public override Task<int> ReadAsync(byte[] buffer, int offset, int count, CancellationToken cancellationToken) =>
+ throw new InvalidOperationException("Exception from ReadAsync");
+
+ public override Task WriteAsync(byte[] buffer, int offset, int count, CancellationToken cancellationToken) =>
throw new InvalidOperationException("Exception from WriteAsync");
- }
- public override Task FlushAsync(CancellationToken cancellationToken)
- {
+ public override Task FlushAsync(CancellationToken cancellationToken) =>
throw new InvalidOperationException("Exception from FlushAsync");
- }
}
public class BufferedStream_NS17
diff --git a/src/System.IO/tests/BufferedStream/BufferedStreamTests.netcoreapp.cs b/src/System.IO/tests/BufferedStream/BufferedStreamTests.netcoreapp.cs
index 53111e8d09..7ead9aa31e 100644
--- a/src/System.IO/tests/BufferedStream/BufferedStreamTests.netcoreapp.cs
+++ b/src/System.IO/tests/BufferedStream/BufferedStreamTests.netcoreapp.cs
@@ -2,7 +2,8 @@
// 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;
+using System.Threading.Tasks;
using Xunit;
namespace System.IO.Tests
@@ -49,5 +50,41 @@ namespace System.IO.Tests
}
Assert.Equal(data, result.ToArray());
}
+
+ [Theory]
+ [InlineData(1, 1)]
+ [InlineData(1, 2)]
+ [InlineData(1024, 4096)]
+ [InlineData(4096, 4097)]
+ [InlineData(4096, 1)]
+ [InlineData(2047, 4096)]
+ public async Task ReadMemory_WriteMemory_AllDataCopied(int spanSize, int bufferSize)
+ {
+ byte[] data = new byte[80000];
+ new Random(42).NextBytes(data);
+
+ var result = new MemoryStream();
+ using (var output = new BufferedStream(result, bufferSize))
+ using (var input = new BufferedStream(new MemoryStream(data), bufferSize))
+ {
+ Memory<byte> memory = new byte[spanSize];
+ int bytesRead;
+ while ((bytesRead = await input.ReadAsync(memory)) != 0)
+ {
+ await output.WriteAsync(memory.Slice(0, bytesRead));
+ }
+ }
+ Assert.Equal(data, result.ToArray());
+ }
+
+ [Fact]
+ public void ReadWriteMemory_Precanceled_Throws()
+ {
+ using (var bs = new BufferedStream(new MemoryStream()))
+ {
+ Assert.Equal(TaskStatus.Canceled, bs.ReadAsync(new byte[1], new CancellationToken(true)).AsTask().Status);
+ Assert.Equal(TaskStatus.Canceled, bs.WriteAsync(new byte[1], new CancellationToken(true)).Status);
+ }
+ }
}
}
diff --git a/src/System.IO/tests/MemoryStream/MemoryStreamTests.netcoreapp.cs b/src/System.IO/tests/MemoryStream/MemoryStreamTests.netcoreapp.cs
index f3d9e1f801..4ea914b071 100644
--- a/src/System.IO/tests/MemoryStream/MemoryStreamTests.netcoreapp.cs
+++ b/src/System.IO/tests/MemoryStream/MemoryStreamTests.netcoreapp.cs
@@ -4,6 +4,8 @@
using Xunit;
using System.Linq;
+using System.Threading;
+using System.Threading.Tasks;
namespace System.IO.Tests
{
@@ -64,34 +66,115 @@ namespace System.IO.Tests
public void DerivedMemoryStream_ReadWriteSpanCalled_ReadWriteArrayUsed()
{
var s = new ReadWriteOverridingMemoryStream();
- Assert.False(s.WriteInvoked);
- Assert.False(s.ReadInvoked);
+ Assert.False(s.WriteArrayInvoked);
+ Assert.False(s.ReadArrayInvoked);
s.Write((ReadOnlySpan<byte>)new byte[1]);
- Assert.True(s.WriteInvoked);
- Assert.False(s.ReadInvoked);
+ Assert.True(s.WriteArrayInvoked);
+ Assert.False(s.ReadArrayInvoked);
s.Position = 0;
s.Read((Span<byte>)new byte[1]);
- Assert.True(s.WriteInvoked);
- Assert.True(s.ReadInvoked);
+ Assert.True(s.WriteArrayInvoked);
+ Assert.True(s.ReadArrayInvoked);
+ }
+
+ [Fact]
+ public async Task WriteAsyncReadOnlyMemory_DataWrittenAndPositionUpdated_Success()
+ {
+ const int Iters = 100;
+ var rand = new Random();
+ byte[] data = Enumerable.Range(0, (Iters * (Iters + 1)) / 2).Select(_ => (byte)rand.Next(256)).ToArray();
+ var s = new MemoryStream();
+
+ int expectedPos = 0;
+ for (int i = 0; i <= Iters; i++)
+ {
+ await s.WriteAsync(new ReadOnlyMemory<byte>(data, expectedPos, i));
+ expectedPos += i;
+ Assert.Equal(expectedPos, s.Position);
+ }
+
+ Assert.Equal(data, s.ToArray());
+ }
+
+ [Fact]
+ public async Task ReadAsyncMemory_DataReadAndPositionUpdated_Success()
+ {
+ const int Iters = 100;
+ var rand = new Random();
+ byte[] data = Enumerable.Range(0, (Iters * (Iters + 1)) / 2).Select(_ => (byte)rand.Next(256)).ToArray();
+ var s = new MemoryStream(data);
+
+ int expectedPos = 0;
+ for (int i = 0; i <= Iters; i++)
+ {
+ var toRead = new Memory<byte>(new byte[i * 3]); // enough room to read the data and have some offset and have slack at the end
+
+ // Do the read and validate we read the expected number of bytes
+ Assert.Equal(i, await s.ReadAsync(toRead.Slice(i, i)));
+
+ // The contents prior to and after the read should be empty.
+ Assert.Equal<byte>(new byte[i], toRead.Slice(0, i).ToArray());
+ Assert.Equal<byte>(new byte[i], toRead.Slice(i * 2, i).ToArray());
+
+ // And the data read should match what was expected.
+ Assert.Equal(new Span<byte>(data, expectedPos, i).ToArray(), toRead.Slice(i, i).ToArray());
+
+ // Updated position should match
+ expectedPos += i;
+ Assert.Equal(expectedPos, s.Position);
+ }
+
+ // A final read should be empty
+ Assert.Equal(0, await s.ReadAsync(new Memory<byte>(new byte[1])));
+ }
+
+ [Fact]
+ public async Task DerivedMemoryStream_ReadWriteAsyncMemoryCalled_ReadWriteAsyncArrayUsed()
+ {
+ var s = new ReadWriteOverridingMemoryStream();
+ Assert.False(s.WriteArrayInvoked);
+ Assert.False(s.ReadArrayInvoked);
+
+ await s.WriteAsync((ReadOnlyMemory<byte>)new byte[1]);
+ Assert.True(s.WriteArrayInvoked);
+ Assert.False(s.ReadArrayInvoked);
+
+ s.Position = 0;
+ await s.ReadAsync((Memory<byte>)new byte[1]);
+ Assert.True(s.WriteArrayInvoked);
+ Assert.True(s.ReadArrayInvoked);
}
private class ReadWriteOverridingMemoryStream : MemoryStream
{
- public bool ReadInvoked, WriteInvoked;
+ public bool ReadArrayInvoked, WriteArrayInvoked;
+ public bool ReadAsyncArrayInvoked, WriteAsyncArrayInvoked;
public override int Read(byte[] buffer, int offset, int count)
{
- ReadInvoked = true;
+ ReadArrayInvoked = true;
return base.Read(buffer, offset, count);
}
public override void Write(byte[] buffer, int offset, int count)
{
- WriteInvoked = true;
+ WriteArrayInvoked = true;
base.Write(buffer, offset, count);
}
+
+ public override Task<int> ReadAsync(byte[] buffer, int offset, int count, CancellationToken cancellationToken)
+ {
+ ReadAsyncArrayInvoked = true;
+ return base.ReadAsync(buffer, offset, count, cancellationToken);
+ }
+
+ public override Task WriteAsync(byte[] buffer, int offset, int count, CancellationToken cancellationToken)
+ {
+ WriteAsyncArrayInvoked = true;
+ return base.WriteAsync(buffer, offset, count, cancellationToken);
+ }
}
}
}
diff --git a/src/System.IO/tests/Stream/Stream.ReadWriteSpan.netcoreapp.cs b/src/System.IO/tests/Stream/Stream.ReadWriteSpan.netcoreapp.cs
index a860c97f9a..6bdea544b0 100644
--- a/src/System.IO/tests/Stream/Stream.ReadWriteSpan.netcoreapp.cs
+++ b/src/System.IO/tests/Stream/Stream.ReadWriteSpan.netcoreapp.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.Buffers;
+using System.Runtime.InteropServices;
+using System.Threading;
+using System.Threading.Tasks;
using Xunit;
namespace System.IO.Tests
@@ -58,5 +62,128 @@ namespace System.IO.Tests
Assert.True(writeInvoked);
writeInvoked = false;
}
+
+ [Fact]
+ public async Task ReadAsyncMemory_WrapsArray_DelegatesToReadAsyncArray_Success()
+ {
+ bool readInvoked = false;
+ var s = new DelegateStream(
+ canReadFunc: () => true,
+ readAsyncFunc: (array, offset, count, cancellationToken) =>
+ {
+ readInvoked = true;
+ Assert.NotNull(array);
+ Assert.Equal(5, offset);
+ Assert.Equal(20, count);
+
+ for (int i = 0; i < 10; i++)
+ {
+ array[offset + i] = (byte)i;
+ }
+ return Task.FromResult(10);
+ });
+
+ Memory<byte> totalMemory = new byte[30];
+ Memory<byte> targetMemory = totalMemory.Slice(5, 20);
+
+ Assert.Equal(10, await s.ReadAsync(targetMemory));
+ Assert.True(readInvoked);
+ for (int i = 0; i < 10; i++)
+ Assert.Equal(i, targetMemory.Span[i]);
+ for (int i = 10; i < 20; i++)
+ Assert.Equal(0, targetMemory.Span[i]);
+ readInvoked = false;
+ }
+
+ [Fact]
+ public async Task ReadAsyncMemory_WrapsNative_DelegatesToReadAsyncArrayWithPool_Success()
+ {
+ bool readInvoked = false;
+ var s = new DelegateStream(
+ canReadFunc: () => true,
+ readAsyncFunc: (array, offset, count, cancellationToken) =>
+ {
+ readInvoked = true;
+ Assert.NotNull(array);
+ Assert.Equal(0, offset);
+ Assert.Equal(20, count);
+
+ for (int i = 0; i < 10; i++)
+ {
+ array[offset + i] = (byte)i;
+ }
+ return Task.FromResult(10);
+ });
+
+ using (var totalNativeMemory = new NativeOwnedMemory(30))
+ {
+ Memory<byte> totalMemory = totalNativeMemory.Memory;
+ Memory<byte> targetMemory = totalMemory.Slice(5, 20);
+
+ Assert.Equal(10, await s.ReadAsync(targetMemory));
+ Assert.True(readInvoked);
+ for (int i = 0; i < 10; i++)
+ Assert.Equal(i, targetMemory.Span[i]);
+ readInvoked = false;
+ }
+ }
+
+ [Fact]
+ public async Task WriteAsyncMemory_WrapsArray_DelegatesToWrite_Success()
+ {
+ bool writeInvoked = false;
+ var s = new DelegateStream(
+ canWriteFunc: () => true,
+ writeAsyncFunc: (array, offset, count, cancellationToken) =>
+ {
+ writeInvoked = true;
+ Assert.NotNull(array);
+ Assert.Equal(2, offset);
+ Assert.Equal(3, count);
+
+ for (int i = 0; i < count; i++)
+ Assert.Equal(i, array[offset + i]);
+
+ return Task.CompletedTask;
+ });
+
+ Memory<byte> memory = new byte[10];
+ memory.Span[3] = 1;
+ memory.Span[4] = 2;
+ await s.WriteAsync(memory.Slice(2, 3));
+ Assert.True(writeInvoked);
+ writeInvoked = false;
+ }
+
+ [Fact]
+ public async Task WriteAsyncMemory_WrapsNative_DelegatesToWrite_Success()
+ {
+ bool writeInvoked = false;
+ var s = new DelegateStream(
+ canWriteFunc: () => true,
+ writeAsyncFunc: (array, offset, count, cancellationToken) =>
+ {
+ writeInvoked = true;
+ Assert.NotNull(array);
+ Assert.Equal(0, offset);
+ Assert.Equal(3, count);
+
+ for (int i = 0; i < count; i++)
+ Assert.Equal(i, array[i]);
+
+ return Task.CompletedTask;
+ });
+
+ using (var nativeMemory = new NativeOwnedMemory(10))
+ {
+ Memory<byte> memory = nativeMemory.Memory;
+ memory.Span[2] = 0;
+ memory.Span[3] = 1;
+ memory.Span[4] = 2;
+ await s.WriteAsync(memory.Slice(2, 3));
+ Assert.True(writeInvoked);
+ writeInvoked = false;
+ }
+ }
}
}
diff --git a/src/System.IO/tests/StreamReader/StreamReaderTests.cs b/src/System.IO/tests/StreamReader/StreamReaderTests.cs
index 0a70a82028..a127c809be 100644
--- a/src/System.IO/tests/StreamReader/StreamReaderTests.cs
+++ b/src/System.IO/tests/StreamReader/StreamReaderTests.cs
@@ -40,33 +40,7 @@ namespace System.IO.Tests
protected Tuple<char[], StreamReader> GetCharArrayStream()
{
- var chArr = new char[]{
- char.MinValue
- ,char.MaxValue
- ,'\t'
- ,' '
- ,'$'
- ,'@'
- ,'#'
- ,'\0'
- ,'\v'
- ,'\''
- ,'\u3190'
- ,'\uC3A0'
- ,'A'
- ,'5'
- ,'\r'
- ,'\uFE70'
- ,'-'
- ,';'
- ,'\r'
- ,'\n'
- ,'T'
- ,'3'
- ,'\n'
- ,'K'
- ,'\u00E6'
- };
+ var chArr = TestDataProvider.CharData;
var ms = CreateStream();
var sw = new StreamWriter(ms);
diff --git a/src/System.IO/tests/StreamWriter/StreamWriter.WriteTests.cs b/src/System.IO/tests/StreamWriter/StreamWriter.WriteTests.cs
index 5c913da954..b36033d118 100644
--- a/src/System.IO/tests/StreamWriter/StreamWriter.WriteTests.cs
+++ b/src/System.IO/tests/StreamWriter/StreamWriter.WriteTests.cs
@@ -20,7 +20,7 @@ namespace System.IO.Tests
[Fact]
public void WriteChars()
{
- char[] chArr = setupArray();
+ char[] chArr = TestDataProvider.CharData;
// [] Write a wide variety of characters and read them back
@@ -40,30 +40,6 @@ namespace System.IO.Tests
}
}
- private static char[] setupArray()
- {
- return new char[]{
- char.MinValue
- ,char.MaxValue
- ,'\t'
- ,' '
- ,'$'
- ,'@'
- ,'#'
- ,'\0'
- ,'\v'
- ,'\''
- ,'\u3190'
- ,'\uC3A0'
- ,'A'
- ,'5'
- ,'\uFE70'
- ,'-'
- ,';'
- ,'\u00E6'
- };
- }
-
[Fact]
public void NullArray()
{
@@ -78,7 +54,7 @@ namespace System.IO.Tests
[Fact]
public void NegativeOffset()
{
- char[] chArr = setupArray();
+ char[] chArr = TestDataProvider.CharData;
// [] Exception if offset is negative
Stream ms = CreateStream();
@@ -91,7 +67,7 @@ namespace System.IO.Tests
[Fact]
public void NegativeCount()
{
- char[] chArr = setupArray();
+ char[] chArr = TestDataProvider.CharData;
// [] Exception if count is negative
Stream ms = CreateStream();
@@ -104,7 +80,7 @@ namespace System.IO.Tests
[Fact]
public void WriteCustomLenghtStrings()
{
- char[] chArr = setupArray();
+ char[] chArr = TestDataProvider.CharData;
// [] Write some custom length strings
Stream ms = CreateStream();
@@ -127,7 +103,7 @@ namespace System.IO.Tests
[Fact]
public void WriteToStreamWriter()
{
- char[] chArr = setupArray();
+ char[] chArr = TestDataProvider.CharData;
// [] Just construct a streamwriter and write to it
//-------------------------------------------------
Stream ms = CreateStream();
@@ -149,7 +125,7 @@ namespace System.IO.Tests
[Fact]
public void TestWritingPastEndOfArray()
{
- char[] chArr = setupArray();
+ char[] chArr = TestDataProvider.CharData;
Stream ms = CreateStream();
StreamWriter sw = new StreamWriter(ms);
@@ -160,7 +136,7 @@ namespace System.IO.Tests
[Fact]
public void VerifyWrittenString()
{
- char[] chArr = setupArray();
+ char[] chArr = TestDataProvider.CharData;
// [] Write string with wide selection of characters and read it back
StringBuilder sb = new StringBuilder(40);
diff --git a/src/System.IO/tests/StringWriter/StringWriterTests.cs b/src/System.IO/tests/StringWriter/StringWriterTests.cs
index 6655a2d548..3e149612ad 100644
--- a/src/System.IO/tests/StringWriter/StringWriterTests.cs
+++ b/src/System.IO/tests/StringWriter/StringWriterTests.cs
@@ -17,33 +17,9 @@ namespace System.IO.Tests
static int[] iArrLargeValues = new int[] { int.MaxValue, int.MaxValue - 1, int.MaxValue / 2, int.MaxValue / 10, int.MaxValue / 100 };
static int[] iArrValidValues = new int[] { 10000, 100000, int.MaxValue / 2000, int.MaxValue / 5000, short.MaxValue };
- private static char[] getCharArray()
- {
- return new char[]{
- char.MinValue
- ,char.MaxValue
- ,'\t'
- ,' '
- ,'$'
- ,'@'
- ,'#'
- ,'\0'
- ,'\v'
- ,'\''
- ,'\u3190'
- ,'\uC3A0'
- ,'A'
- ,'5'
- ,'\uFE70'
- ,'-'
- ,';'
- ,'\u00E6'
- };
- }
-
private static StringBuilder getSb()
{
- var chArr = getCharArray();
+ var chArr = TestDataProvider.CharData;
var sb = new StringBuilder(40);
for (int i = 0; i < chArr.Length; i++)
sb.Append(chArr[i]);
@@ -88,7 +64,7 @@ namespace System.IO.Tests
[Fact]
public static void WriteArray()
{
- var chArr = getCharArray();
+ var chArr = TestDataProvider.CharData;
StringBuilder sb = getSb();
StringWriter sw = new StringWriter(sb);
@@ -125,7 +101,7 @@ namespace System.IO.Tests
[Fact]
public static void CantWriteIndexLargeValues()
{
- var chArr = getCharArray();
+ var chArr = TestDataProvider.CharData;
for (int i = 0; i < iArrLargeValues.Length; i++)
{
StringWriter sw = new StringWriter();
@@ -136,7 +112,7 @@ namespace System.IO.Tests
[Fact]
public static void CantWriteCountLargeValues()
{
- var chArr = getCharArray();
+ var chArr = TestDataProvider.CharData;
for (int i = 0; i < iArrLargeValues.Length; i++)
{
StringWriter sw = new StringWriter();
@@ -150,7 +126,7 @@ namespace System.IO.Tests
StringWriter sw = new StringWriter();
StringReader sr;
- var chArr = getCharArray();
+ var chArr = TestDataProvider.CharData;
sw.Write(chArr, 2, 5);
diff --git a/src/System.IO/tests/System.IO.Tests.csproj b/src/System.IO/tests/System.IO.Tests.csproj
index 971feb0177..d54417b8cd 100644
--- a/src/System.IO/tests/System.IO.Tests.csproj
+++ b/src/System.IO/tests/System.IO.Tests.csproj
@@ -5,6 +5,7 @@
<RootNamespace>System.IO</RootNamespace>
<AssemblyName>System.IO.Tests</AssemblyName>
<ProjectGuid>{492EC54D-D2C4-4B3F-AC1F-646B3F7EBB02}</ProjectGuid>
+ <AllowUnsafeBlocks>true</AllowUnsafeBlocks>
</PropertyGroup>
<!-- Default configurations to help VS understand the configurations -->
<PropertyGroup Condition="'$(Configuration)|$(Platform)' == 'netcoreapp-Debug|AnyCPU'" />
@@ -12,6 +13,7 @@
<PropertyGroup Condition="'$(Configuration)|$(Platform)' == 'netstandard-Debug|AnyCPU'" />
<PropertyGroup Condition="'$(Configuration)|$(Platform)' == 'netstandard-Release|AnyCPU'" />
<ItemGroup>
+ <Compile Include="BinaryReader\BinaryReaderTests.netcoreapp.cs" Condition="'$(TargetGroup)' == 'netcoreapp'" />
<Compile Include="IndentedTextWriter.cs" />
<Compile Include="BinaryReader\BinaryReaderTests.cs" />
<Compile Include="MemoryStream\MemoryStream.GetBufferTests.cs" />
@@ -51,6 +53,9 @@
<Compile Include="Stream\Stream.TimeoutTests.cs" />
<Compile Include="StringReader\StringReader.CtorTests.cs" />
<Compile Include="StringWriter\StringWriterTests.cs" />
+ <Compile Include="$(CommonTestPath)\System\Buffers\NativeOwnedMemory.cs" Condition="'$(TargetGroup)' == 'netcoreapp'" >
+ <Link>Common\System\Buffers\NativeOwnedMemory.cs</Link>
+ </Compile>
<Compile Include="$(CommonTestPath)\System\IO\CallTrackingStream.cs">
<Link>Common\System\IO\CallTrackingStream.cs</Link>
</Compile>
@@ -60,6 +65,13 @@
<Compile Include="$(CommonTestPath)\System\IO\WrappedMemoryStream.cs">
<Link>Common\System\IO\WrappedMemoryStream.cs</Link>
</Compile>
+ <Compile Include="TestDataProvider\TestDataProvider.cs" />
+ <Compile Include="TextReader\CharArrayTextReader.cs" />
+ <Compile Include="TextReader\TextReaderTests.cs" />
+ <Compile Include="TextReader\TextReaderTests.netcoreapp.cs" Condition="'$(TargetGroup)' == 'netcoreapp'" />
+ <Compile Include="TextWriter\CharArrayTextWriter.cs" />
+ <Compile Include="TextWriter\TextWriterTests.cs" />
+ <Compile Include="TextWriter\TextWriterTests.netcoreapp.cs" Condition="'$(TargetGroup)' == 'netcoreapp'" />
</ItemGroup>
<ItemGroup>
<EmbeddedResource Include="Resources\$(AssemblyName).rd.xml" />
diff --git a/src/System.IO/tests/TestDataProvider/TestDataProvider.cs b/src/System.IO/tests/TestDataProvider/TestDataProvider.cs
new file mode 100644
index 0000000000..b7e37ddff1
--- /dev/null
+++ b/src/System.IO/tests/TestDataProvider/TestDataProvider.cs
@@ -0,0 +1,72 @@
+using System;
+using System.Collections.Generic;
+using System.Linq;
+using System.Text;
+using System.Threading.Tasks;
+
+namespace System.IO.Tests
+{
+ public static class TestDataProvider
+ {
+ private static readonly char[] s_charData;
+ private static readonly char[] s_smallData;
+ private static readonly char[] s_largeData;
+
+ public static object FirstObject { get; } = (object)1;
+ public static object SecondObject { get; } = (object)"[second object]";
+ public static object ThirdObject { get; } = (object)"<third object>";
+ public static object[] MultipleObjects { get; } = new object[] { FirstObject, SecondObject, ThirdObject };
+
+ public static string FormatStringOneObject { get; } = "Object is {0}";
+ public static string FormatStringTwoObjects { get; } = $"Object are '{0}', {SecondObject}";
+ public static string FormatStringThreeObjects { get; } = $"Objects are {0}, {SecondObject}, {ThirdObject}";
+ public static string FormatStringMultipleObjects { get; } = "Multiple Objects are: {0}, {1}, {2}";
+
+ static TestDataProvider()
+ {
+ s_charData = new char[]
+ {
+ char.MinValue,
+ char.MaxValue,
+ '\t',
+ ' ',
+ '$',
+ '@',
+ '#',
+ '\0',
+ '\v',
+ '\'',
+ '\u3190',
+ '\uC3A0',
+ 'A',
+ '5',
+ '\r',
+ '\uFE70',
+ '-',
+ ';',
+ '\r',
+ '\n',
+ 'T',
+ '3',
+ '\n',
+ 'K',
+ '\u00E6'
+ };
+
+ s_smallData = "HELLO".ToCharArray();
+
+ var data = new List<char>();
+ for (int count = 0; count < 1000; ++count)
+ {
+ data.AddRange(s_smallData);
+ }
+ s_largeData = data.ToArray();
+ }
+
+ public static char[] CharData => s_charData;
+
+ public static char[] SmallData => s_smallData;
+
+ public static char[] LargeData => s_largeData;
+ }
+}
diff --git a/src/System.IO/tests/TextReader/CharArrayTextReader.cs b/src/System.IO/tests/TextReader/CharArrayTextReader.cs
new file mode 100644
index 0000000000..c82f2bb321
--- /dev/null
+++ b/src/System.IO/tests/TextReader/CharArrayTextReader.cs
@@ -0,0 +1,37 @@
+// 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.IO.Tests
+{
+ public class CharArrayTextReader : TextReader
+ {
+ private readonly char[] _charBuffer;
+ private int _charPos = 0;
+
+ public bool EndOfStream => _charPos >= _charBuffer.Length;
+
+ public CharArrayTextReader(char[] data)
+ {
+ _charBuffer = data;
+ }
+
+ public override int Peek()
+ {
+ if (_charPos == _charBuffer.Length)
+ {
+ return -1;
+ }
+ return _charBuffer[_charPos];
+ }
+
+ public override int Read()
+ {
+ if (_charPos == _charBuffer.Length)
+ {
+ return -1;
+ }
+ return _charBuffer[_charPos++];
+ }
+ }
+}
diff --git a/src/System.IO/tests/TextReader/TextReaderTests.cs b/src/System.IO/tests/TextReader/TextReaderTests.cs
new file mode 100644
index 0000000000..befc068cb6
--- /dev/null
+++ b/src/System.IO/tests/TextReader/TextReaderTests.cs
@@ -0,0 +1,248 @@
+// 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.Threading.Tasks;
+using Xunit;
+
+namespace System.IO.Tests
+{
+ public partial class TextReaderTests
+ {
+ protected (char[] chArr, CharArrayTextReader textReader) GetCharArray()
+ {
+ CharArrayTextReader tr = new CharArrayTextReader(TestDataProvider.CharData);
+ return (TestDataProvider.CharData, tr);
+ }
+
+ [Fact]
+ public void EndOfStream()
+ {
+ using (CharArrayTextReader tr = new CharArrayTextReader(TestDataProvider.SmallData))
+ {
+ var result = tr.ReadToEnd();
+
+ Assert.Equal("HELLO", result);
+
+ Assert.True(tr.EndOfStream, "End of TextReader was not true after ReadToEnd");
+ }
+ }
+
+ [Fact]
+ public void NotEndOfStream()
+ {
+ using (CharArrayTextReader tr = new CharArrayTextReader(TestDataProvider.SmallData))
+ {
+ char[] charBuff = new char[3];
+ var result = tr.Read(charBuff, 0, 3);
+
+ Assert.Equal(3, result);
+
+ Assert.Equal("HEL", new string(charBuff));
+
+ Assert.False(tr.EndOfStream, "End of TextReader was true after ReadToEnd");
+ }
+ }
+
+ [Fact]
+ public async Task ReadToEndAsync()
+ {
+ using (CharArrayTextReader tr = new CharArrayTextReader(TestDataProvider.LargeData))
+ {
+ var result = await tr.ReadToEndAsync();
+
+ Assert.Equal(5000, result.Length);
+ }
+ }
+
+ [Fact]
+ public void TestRead()
+ {
+ (char[] chArr, CharArrayTextReader textReader) baseInfo = GetCharArray();
+ using (CharArrayTextReader tr = baseInfo.textReader)
+ {
+ for (int count = 0; count < baseInfo.chArr.Length; ++count)
+ {
+ int tmp = tr.Read();
+ Assert.Equal((int)baseInfo.chArr[count], tmp);
+ }
+ }
+ }
+
+ [Fact]
+ public void ArgumentNullOnNullArray()
+ {
+ (char[] chArr, CharArrayTextReader textReader) baseInfo = GetCharArray();
+ using (CharArrayTextReader tr = baseInfo.textReader)
+ {
+ Assert.Throws<ArgumentNullException>(() => tr.Read(null, 0, 0));
+ }
+ }
+
+ [Fact]
+ public void ArgumentOutOfRangeOnInvalidOffset()
+ {
+ using (CharArrayTextReader tr = GetCharArray().textReader)
+ {
+ Assert.Throws<ArgumentOutOfRangeException>(() => tr.Read(new char[0], -1, 0));
+ }
+ }
+
+ [Fact]
+ public void ArgumentOutOfRangeOnNegativCount()
+ {
+ using (CharArrayTextReader tr = GetCharArray().textReader)
+ {
+ AssertExtensions.Throws<ArgumentException>(null, () => tr.Read(new char[0], 0, 1));
+ }
+ }
+
+ [Fact]
+ public void ArgumentExceptionOffsetAndCount()
+ {
+ using (CharArrayTextReader tr = GetCharArray().textReader)
+ {
+ AssertExtensions.Throws<ArgumentException>(null, () => tr.Read(new char[0], 2, 0));
+ }
+ }
+
+ [Fact]
+ public void EmptyInput()
+ {
+ using (CharArrayTextReader tr = new CharArrayTextReader(new char[] { }))
+ {
+ char[] buffer = new char[10];
+ int read = tr.Read(buffer, 0, 1);
+ Assert.Equal(0, read);
+ }
+ }
+
+ [Fact]
+ public void ReadCharArr()
+ {
+ (char[] chArr, CharArrayTextReader textReader) baseInfo = GetCharArray();
+ using (CharArrayTextReader tr = baseInfo.textReader)
+ {
+ char[] chArr = new char[baseInfo.chArr.Length];
+
+ var read = tr.Read(chArr, 0, chArr.Length);
+ Assert.Equal(chArr.Length, read);
+
+ for (int count = 0; count < baseInfo.chArr.Length; ++count)
+ {
+ Assert.Equal(baseInfo.chArr[count], chArr[count]);
+ }
+ }
+ }
+
+ [Fact]
+ public void ReadBlockCharArr()
+ {
+ (char[] chArr, CharArrayTextReader textReader) baseInfo = GetCharArray();
+ using (CharArrayTextReader tr = baseInfo.textReader)
+ {
+ char[] chArr = new char[baseInfo.chArr.Length];
+
+ var read = tr.ReadBlock(chArr, 0, chArr.Length);
+ Assert.Equal(chArr.Length, read);
+
+ for (int count = 0; count < baseInfo.chArr.Length; ++count)
+ {
+ Assert.Equal(baseInfo.chArr[count], chArr[count]);
+ }
+ }
+ }
+
+ [Fact]
+ public async void ReadBlockAsyncCharArr()
+ {
+ (char[] chArr, CharArrayTextReader textReader) baseInfo = GetCharArray();
+ using (CharArrayTextReader tr = baseInfo.textReader)
+ {
+ char[] chArr = new char[baseInfo.chArr.Length];
+
+ var read = await tr.ReadBlockAsync(chArr, 0, chArr.Length);
+ Assert.Equal(chArr.Length, read);
+
+ for (int count = 0; count < baseInfo.chArr.Length; ++count)
+ {
+ Assert.Equal(baseInfo.chArr[count], chArr[count]);
+ }
+ }
+ }
+
+ [Fact]
+ public async Task ReadAsync()
+ {
+ (char[] chArr, CharArrayTextReader textReader) baseInfo = GetCharArray();
+ using (CharArrayTextReader tr = baseInfo.textReader)
+ {
+ char[] chArr = new char[baseInfo.chArr.Length];
+
+ var read = await tr.ReadAsync(chArr, 4, 3);
+ Assert.Equal(read, 3);
+
+ for (int count = 0; count < 3; ++count)
+ {
+ Assert.Equal(baseInfo.chArr[count], chArr[count + 4]);
+ }
+ }
+ }
+
+ [Fact]
+ public void ReadLines()
+ {
+ (char[] chArr, CharArrayTextReader textReader) baseInfo = GetCharArray();
+ using (CharArrayTextReader tr = baseInfo.textReader)
+ {
+ string valueString = new string(baseInfo.chArr);
+
+ var data = tr.ReadLine();
+ Assert.Equal(valueString.Substring(0, valueString.IndexOf('\r')), data);
+
+ data = tr.ReadLine();
+ Assert.Equal(valueString.Substring(valueString.IndexOf('\r') + 1, 3), data);
+
+ data = tr.ReadLine();
+ Assert.Equal(valueString.Substring(valueString.IndexOf('\n') + 1, 2), data);
+
+ data = tr.ReadLine();
+ Assert.Equal((valueString.Substring(valueString.LastIndexOf('\n') + 1)), data);
+ }
+ }
+
+ [Fact]
+ public void ReadLines2()
+ {
+ (char[] chArr, CharArrayTextReader textReader) baseInfo = GetCharArray();
+ using (CharArrayTextReader tr = baseInfo.textReader)
+ {
+ string valueString = new string(baseInfo.chArr);
+
+ char[] temp = new char[10];
+ tr.Read(temp, 0, 1);
+ var data = tr.ReadLine();
+
+ Assert.Equal(valueString.Substring(1, valueString.IndexOf('\r') - 1), data);
+ }
+ }
+
+ [Fact]
+ public async Task ReadLineAsyncContinuousNewLinesAndTabs()
+ {
+ char[] newLineTabData = new char[] { '\n', '\n', '\r', '\r', '\n' };
+ using (CharArrayTextReader tr = new CharArrayTextReader(newLineTabData))
+ {
+ for (int count = 0; count < 4; ++count)
+ {
+ var data = await tr.ReadLineAsync();
+ Assert.Equal(string.Empty, data);
+ }
+
+ var eol = await tr.ReadLineAsync();
+ Assert.Null(eol);
+ }
+ }
+ }
+}
diff --git a/src/System.IO/tests/TextReader/TextReaderTests.netcoreapp.cs b/src/System.IO/tests/TextReader/TextReaderTests.netcoreapp.cs
new file mode 100644
index 0000000000..6ed515a57e
--- /dev/null
+++ b/src/System.IO/tests/TextReader/TextReaderTests.netcoreapp.cs
@@ -0,0 +1,51 @@
+// 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.Threading.Tasks;
+using Xunit;
+
+namespace System.IO.Tests
+{
+ public partial class TextReaderTests
+ {
+ [Fact]
+ public void ReadSpan()
+ {
+ (char[] chArr, CharArrayTextReader textReader) baseInfo = GetCharArray();
+ using (CharArrayTextReader tr = baseInfo.textReader)
+ {
+ char[] chArr = new char[baseInfo.chArr.Length];
+ var chSpan = new Span<char>(chArr, 0, baseInfo.chArr.Length);
+
+ var read = tr.Read(chSpan);
+ Assert.Equal(chArr.Length, read);
+
+ for (int i = 0; i < baseInfo.chArr.Length; i++)
+ {
+ Assert.Equal(baseInfo.chArr[i], chArr[i]);
+ }
+ }
+ }
+
+ [Fact]
+ public void ReadBlockSpan()
+ {
+ (char[] chArr, CharArrayTextReader textReader) baseInfo = GetCharArray();
+ using (CharArrayTextReader tr = baseInfo.textReader)
+ {
+ char[] chArr = new char[baseInfo.chArr.Length];
+ var chSpan = new Span<char>(chArr, 0, baseInfo.chArr.Length);
+
+ var read = tr.ReadBlock(chSpan);
+ Assert.Equal(chArr.Length, read);
+
+ for (int i = 0; i < baseInfo.chArr.Length; i++)
+ {
+ Assert.Equal(baseInfo.chArr[i], chArr[i]);
+ }
+ }
+ }
+ }
+}
diff --git a/src/System.IO/tests/TextWriter/CharArrayTextWriter.cs b/src/System.IO/tests/TextWriter/CharArrayTextWriter.cs
new file mode 100644
index 0000000000..0eb9b61942
--- /dev/null
+++ b/src/System.IO/tests/TextWriter/CharArrayTextWriter.cs
@@ -0,0 +1,29 @@
+// 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.Text;
+
+namespace System.IO.Tests
+{
+ public class CharArrayTextWriter : TextWriter
+ {
+ private StringBuilder _sb;
+
+ public override Encoding Encoding => Encoding.Unicode;
+
+ public CharArrayTextWriter()
+ {
+ _sb = new StringBuilder();
+ }
+
+ public override void Write(char value)
+ {
+ _sb.Append(value);
+ }
+
+ public string Text => _sb.ToString();
+
+ public void Clear() => _sb.Clear();
+ }
+}
diff --git a/src/System.IO/tests/TextWriter/TextWriterTests.cs b/src/System.IO/tests/TextWriter/TextWriterTests.cs
new file mode 100644
index 0000000000..2a7aaf7658
--- /dev/null
+++ b/src/System.IO/tests/TextWriter/TextWriterTests.cs
@@ -0,0 +1,543 @@
+// 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.Linq;
+using System.Threading.Tasks;
+using Xunit;
+
+namespace System.IO.Tests
+{
+ public partial class TextWriterTests
+ {
+ protected static CharArrayTextWriter NewTextWriter => new CharArrayTextWriter() { NewLine = "---" };
+
+ #region Write Overloads
+
+ [Fact]
+ public void WriteCharTest()
+ {
+ using (CharArrayTextWriter tw = NewTextWriter)
+ {
+ for (int count = 0; count < TestDataProvider.CharData.Length; ++count)
+ {
+ tw.Write(TestDataProvider.CharData[count]);
+ }
+ Assert.Equal(new string(TestDataProvider.CharData), tw.Text);
+ }
+ }
+
+ [Fact]
+ public void WriteCharArrayTest()
+ {
+ using (CharArrayTextWriter tw = NewTextWriter)
+ {
+ tw.Write(TestDataProvider.CharData);
+ Assert.Equal(new string(TestDataProvider.CharData), tw.Text);
+ }
+ }
+
+ [Fact]
+ public void WriteCharArrayIndexCountTest()
+ {
+ using (CharArrayTextWriter tw = NewTextWriter)
+ {
+ tw.Write(TestDataProvider.CharData, 3, 5);
+ Assert.Equal(new string(TestDataProvider.CharData, 3, 5), tw.Text);
+ }
+ }
+
+ [Fact]
+ public void WriteBoolTest()
+ {
+ using (CharArrayTextWriter tw = NewTextWriter)
+ {
+ tw.Write(true);
+ Assert.Equal("True", tw.Text);
+
+ tw.Clear();
+ tw.Write(false);
+ Assert.Equal("False", tw.Text);
+ }
+ }
+
+ [Fact]
+ public void WriteIntTest()
+ {
+ using (CharArrayTextWriter tw = NewTextWriter)
+ {
+ tw.Write(int.MinValue);
+ Assert.Equal(int.MinValue.ToString(), tw.Text);
+
+ tw.Clear();
+ tw.Write(int.MaxValue);
+ Assert.Equal(int.MaxValue.ToString(), tw.Text);
+ }
+ }
+
+ [Fact]
+ public void WriteUIntTest()
+ {
+ using (CharArrayTextWriter tw = NewTextWriter)
+ {
+ tw.Write(uint.MinValue);
+ Assert.Equal(uint.MinValue.ToString(), tw.Text);
+
+ tw.Clear();
+ tw.Write(uint.MaxValue);
+ Assert.Equal(uint.MaxValue.ToString(), tw.Text);
+ }
+ }
+
+ [Fact]
+ public void WriteLongTest()
+ {
+ using (CharArrayTextWriter tw = NewTextWriter)
+ {
+ tw.Write(long.MinValue);
+ Assert.Equal(long.MinValue.ToString(), tw.Text);
+
+ tw.Clear();
+ tw.Write(long.MaxValue);
+ Assert.Equal(long.MaxValue.ToString(), tw.Text);
+ }
+ }
+
+ [Fact]
+ public void WriteULongTest()
+ {
+ using (CharArrayTextWriter tw = NewTextWriter)
+ {
+ tw.Write(ulong.MinValue);
+ Assert.Equal(ulong.MinValue.ToString(), tw.Text);
+
+ tw.Clear();
+ tw.Write(ulong.MaxValue);
+ Assert.Equal(ulong.MaxValue.ToString(), tw.Text);
+
+ }
+ }
+
+ [Fact]
+ public void WriteFloatTest()
+ {
+ using (CharArrayTextWriter tw = NewTextWriter)
+ {
+ tw.Write(float.MinValue);
+ Assert.Equal(float.MinValue.ToString(), tw.Text);
+
+ tw.Clear();
+ tw.Write(float.MaxValue);
+ Assert.Equal(float.MaxValue.ToString(), tw.Text);
+
+ tw.Clear();
+ tw.Write(float.NaN);
+ Assert.Equal(float.NaN.ToString(), tw.Text);
+ }
+ }
+
+ [Fact]
+ public void WriteDoubleTest()
+ {
+ using (CharArrayTextWriter tw = NewTextWriter)
+ {
+ tw.Write(double.MinValue);
+ Assert.Equal(double.MinValue.ToString(), tw.Text);
+ tw.Clear();
+
+ tw.Write(double.MaxValue);
+ Assert.Equal(double.MaxValue.ToString(), tw.Text);
+ tw.Clear();
+
+ tw.Write(double.NaN);
+ Assert.Equal(double.NaN.ToString(), tw.Text);
+ tw.Clear();
+ }
+ }
+
+ [Fact]
+ public void WriteDecimalTest()
+ {
+ using (CharArrayTextWriter tw = NewTextWriter)
+ {
+ tw.Write(decimal.MinValue);
+ Assert.Equal(decimal.MinValue.ToString(), tw.Text);
+
+ tw.Clear();
+ tw.Write(decimal.MaxValue);
+ Assert.Equal(decimal.MaxValue.ToString(), tw.Text);
+ }
+ }
+
+ [Fact]
+ public void WriteStringTest()
+ {
+ using (CharArrayTextWriter tw = NewTextWriter)
+ {
+ tw.Write(new string(TestDataProvider.CharData));
+ Assert.Equal(new string(TestDataProvider.CharData), tw.Text);
+ }
+ }
+
+ [Fact]
+ public void WriteObjectTest()
+ {
+ using (CharArrayTextWriter tw = NewTextWriter)
+ {
+ tw.Write(TestDataProvider.FirstObject);
+ Assert.Equal(TestDataProvider.FirstObject.ToString(), tw.Text);
+ }
+ }
+
+ [Fact]
+ public void WriteStringObjectTest()
+ {
+ using (CharArrayTextWriter tw = NewTextWriter)
+ {
+ tw.Write(TestDataProvider.FormatStringOneObject, TestDataProvider.FirstObject);
+ Assert.Equal(string.Format(TestDataProvider.FormatStringOneObject, TestDataProvider.FirstObject), tw.Text);
+ }
+ }
+
+ [Fact]
+ public void WriteStringTwoObjectsTest()
+ {
+ using (CharArrayTextWriter tw = NewTextWriter)
+ {
+ tw.Write(TestDataProvider.FormatStringTwoObjects, TestDataProvider.FirstObject, TestDataProvider.SecondObject);
+ Assert.Equal(string.Format(TestDataProvider.FormatStringTwoObjects, TestDataProvider.FirstObject, TestDataProvider.SecondObject), tw.Text);
+ }
+ }
+
+ [Fact]
+ public void WriteStringThreeObjectsTest()
+ {
+ using (CharArrayTextWriter tw = NewTextWriter)
+ {
+ tw.Write(TestDataProvider.FormatStringThreeObjects, TestDataProvider.FirstObject, TestDataProvider.SecondObject, TestDataProvider.ThirdObject);
+ Assert.Equal(string.Format(TestDataProvider.FormatStringThreeObjects, TestDataProvider.FirstObject, TestDataProvider.SecondObject, TestDataProvider.ThirdObject), tw.Text);
+ }
+ }
+
+ [Fact]
+ public void WriteStringMultipleObjectsTest()
+ {
+ using (CharArrayTextWriter tw = NewTextWriter)
+ {
+ tw.Write(TestDataProvider.FormatStringMultipleObjects, TestDataProvider.MultipleObjects);
+ Assert.Equal(string.Format(TestDataProvider.FormatStringMultipleObjects, TestDataProvider.MultipleObjects), tw.Text);
+ }
+ }
+
+ #endregion
+
+ #region WriteLine Overloads
+
+ [Fact]
+ public void WriteLineTest()
+ {
+ using (CharArrayTextWriter tw = NewTextWriter)
+ {
+ tw.WriteLine();
+ Assert.Equal(tw.NewLine, tw.Text);
+ }
+ }
+
+ [Fact]
+ public void WriteLineCharTest()
+ {
+ using (CharArrayTextWriter tw = NewTextWriter)
+ {
+ for (int count = 0; count < TestDataProvider.CharData.Length; ++count)
+ {
+ tw.WriteLine(TestDataProvider.CharData[count]);
+ }
+ Assert.Equal(string.Join(tw.NewLine, TestDataProvider.CharData.Select(ch => ch.ToString()).ToArray()) + tw.NewLine, tw.Text);
+ }
+ }
+
+ [Fact]
+ public void WriteLineCharArrayTest()
+ {
+ using (CharArrayTextWriter tw = NewTextWriter)
+ {
+ tw.WriteLine(TestDataProvider.CharData);
+ Assert.Equal(new string(TestDataProvider.CharData) + tw.NewLine, tw.Text);
+ }
+ }
+
+ [Fact]
+ public void WriteLineCharArrayIndexCountTest()
+ {
+ using (CharArrayTextWriter tw = NewTextWriter)
+ {
+ tw.WriteLine(TestDataProvider.CharData, 3, 5);
+ Assert.Equal(new string(TestDataProvider.CharData, 3, 5) + tw.NewLine, tw.Text);
+ }
+ }
+
+ [Fact]
+ public void WriteLineBoolTest()
+ {
+ using (CharArrayTextWriter tw = NewTextWriter)
+ {
+ tw.WriteLine(true);
+ Assert.Equal("True" + tw.NewLine, tw.Text);
+
+ tw.Clear();
+ tw.WriteLine(false);
+ Assert.Equal("False" + tw.NewLine, tw.Text);
+ }
+ }
+
+ [Fact]
+ public void WriteLineIntTest()
+ {
+ using (CharArrayTextWriter tw = NewTextWriter)
+ {
+ tw.WriteLine(int.MinValue);
+ Assert.Equal(int.MinValue.ToString() + tw.NewLine, tw.Text);
+
+ tw.Clear();
+ tw.WriteLine(int.MaxValue);
+ Assert.Equal(int.MaxValue.ToString() + tw.NewLine, tw.Text);
+ }
+ }
+
+ [Fact]
+ public void WriteLineUIntTest()
+ {
+ using (CharArrayTextWriter tw = NewTextWriter)
+ {
+ tw.WriteLine(uint.MinValue);
+ Assert.Equal(uint.MinValue.ToString() + tw.NewLine, tw.Text);
+
+ tw.Clear();
+ tw.WriteLine(uint.MaxValue);
+ Assert.Equal(uint.MaxValue.ToString() + tw.NewLine, tw.Text);
+ }
+ }
+
+ [Fact]
+ public void WriteLineLongTest()
+ {
+ using (CharArrayTextWriter tw = NewTextWriter)
+ {
+ tw.WriteLine(long.MinValue);
+ Assert.Equal(long.MinValue.ToString() + tw.NewLine, tw.Text);
+
+ tw.Clear();
+ tw.WriteLine(long.MaxValue);
+ Assert.Equal(long.MaxValue.ToString() + tw.NewLine, tw.Text);
+ }
+ }
+
+ [Fact]
+ public void WriteLineULongTest()
+ {
+ using (CharArrayTextWriter tw = NewTextWriter)
+ {
+ tw.WriteLine(ulong.MinValue);
+ Assert.Equal(ulong.MinValue.ToString() + tw.NewLine, tw.Text);
+
+ tw.Clear();
+ tw.WriteLine(ulong.MaxValue);
+ Assert.Equal(ulong.MaxValue.ToString() + tw.NewLine, tw.Text);
+ }
+ }
+
+ [Fact]
+ public void WriteLineFloatTest()
+ {
+ using (CharArrayTextWriter tw = NewTextWriter)
+ {
+ tw.WriteLine(float.MinValue);
+ Assert.Equal(float.MinValue.ToString() + tw.NewLine, tw.Text);
+
+ tw.Clear();
+ tw.WriteLine(float.MaxValue);
+ Assert.Equal(float.MaxValue.ToString() + tw.NewLine, tw.Text);
+
+ tw.Clear();
+ tw.WriteLine(float.NaN);
+ Assert.Equal(float.NaN.ToString() + tw.NewLine, tw.Text);
+ }
+ }
+
+ [Fact]
+ public void WriteLineDoubleTest()
+ {
+ using (CharArrayTextWriter tw = NewTextWriter)
+ {
+ tw.WriteLine(double.MinValue);
+ Assert.Equal(double.MinValue.ToString() + tw.NewLine, tw.Text);
+ tw.Clear();
+
+ tw.WriteLine(double.MaxValue);
+ Assert.Equal(double.MaxValue.ToString() + tw.NewLine, tw.Text);
+ tw.Clear();
+
+ tw.WriteLine(double.NaN);
+ Assert.Equal(double.NaN.ToString() + tw.NewLine, tw.Text);
+ tw.Clear();
+ }
+ }
+
+ [Fact]
+ public void WriteLineDecimalTest()
+ {
+ using (CharArrayTextWriter tw = NewTextWriter)
+ {
+ tw.WriteLine(decimal.MinValue);
+ Assert.Equal(decimal.MinValue.ToString() + tw.NewLine, tw.Text);
+
+ tw.Clear();
+ tw.WriteLine(decimal.MaxValue);
+ Assert.Equal(decimal.MaxValue.ToString() + tw.NewLine, tw.Text);
+ }
+ }
+
+ [Fact]
+ public void WriteLineStringTest()
+ {
+ using (CharArrayTextWriter tw = NewTextWriter)
+ {
+ tw.WriteLine(new string(TestDataProvider.CharData));
+ Assert.Equal(new string(TestDataProvider.CharData) + tw.NewLine, tw.Text);
+ }
+ }
+
+ [Fact]
+ public void WriteLineObjectTest()
+ {
+ using (CharArrayTextWriter tw = NewTextWriter)
+ {
+ tw.WriteLine(TestDataProvider.FirstObject);
+ Assert.Equal(TestDataProvider.FirstObject.ToString() + tw.NewLine, tw.Text);
+ }
+ }
+
+ [Fact]
+ public void WriteLineStringObjectTest()
+ {
+ using (CharArrayTextWriter tw = NewTextWriter)
+ {
+ tw.WriteLine(TestDataProvider.FormatStringOneObject, TestDataProvider.FirstObject);
+ Assert.Equal(string.Format(TestDataProvider.FormatStringOneObject + tw.NewLine, TestDataProvider.FirstObject), tw.Text);
+ }
+ }
+
+ [Fact]
+ public void WriteLineStringTwoObjectsTest()
+ {
+ using (CharArrayTextWriter tw = NewTextWriter)
+ {
+ tw.WriteLine(TestDataProvider.FormatStringTwoObjects, TestDataProvider.FirstObject, TestDataProvider.SecondObject);
+ Assert.Equal(string.Format(TestDataProvider.FormatStringTwoObjects + tw.NewLine, TestDataProvider.FirstObject, TestDataProvider.SecondObject), tw.Text);
+ }
+ }
+
+ [Fact]
+ public void WriteLineStringThreeObjectsTest()
+ {
+ using (CharArrayTextWriter tw = NewTextWriter)
+ {
+ tw.WriteLine(TestDataProvider.FormatStringThreeObjects, TestDataProvider.FirstObject, TestDataProvider.SecondObject, TestDataProvider.ThirdObject);
+ Assert.Equal(string.Format(TestDataProvider.FormatStringThreeObjects + tw.NewLine, TestDataProvider.FirstObject, TestDataProvider.SecondObject, TestDataProvider.ThirdObject), tw.Text);
+ }
+ }
+
+ [Fact]
+ public void WriteLineStringMultipleObjectsTest()
+ {
+ using (CharArrayTextWriter tw = NewTextWriter)
+ {
+ tw.WriteLine(TestDataProvider.FormatStringMultipleObjects, TestDataProvider.MultipleObjects);
+ Assert.Equal(string.Format(TestDataProvider.FormatStringMultipleObjects + tw.NewLine, TestDataProvider.MultipleObjects), tw.Text);
+ }
+ }
+
+ #endregion
+
+ #region Write Async Overloads
+
+ [Fact]
+ public async void WriteAsyncCharTest()
+ {
+ using (CharArrayTextWriter tw = NewTextWriter)
+ {
+ await tw.WriteAsync('a');
+ Assert.Equal("a", tw.Text);
+ }
+ }
+
+ [Fact]
+ public async void WriteAsyncStringTest()
+ {
+ using (CharArrayTextWriter tw = NewTextWriter)
+ {
+ var toWrite = new string(TestDataProvider.CharData);
+ await tw.WriteAsync(toWrite);
+ Assert.Equal(toWrite, tw.Text);
+ }
+ }
+
+ [Fact]
+ public async void WriteAsyncCharArrayIndexCountTest()
+ {
+ using (CharArrayTextWriter tw = NewTextWriter)
+ {
+ await tw.WriteAsync(TestDataProvider.CharData, 3, 5);
+ Assert.Equal(new string(TestDataProvider.CharData, 3, 5), tw.Text);
+ }
+ }
+
+ #endregion
+
+ #region WriteLineAsync Overloads
+
+ [Fact]
+ public async void WriteLineAsyncTest()
+ {
+ using (CharArrayTextWriter tw = NewTextWriter)
+ {
+ await tw.WriteLineAsync();
+ Assert.Equal(tw.NewLine, tw.Text);
+ }
+ }
+
+ [Fact]
+ public async void WriteLineAsyncCharTest()
+ {
+ using (CharArrayTextWriter tw = NewTextWriter)
+ {
+ await tw.WriteLineAsync('a');
+ Assert.Equal("a" + tw.NewLine, tw.Text);
+ }
+ }
+
+ [Fact]
+ public async void WriteLineAsyncStringTest()
+ {
+ using (CharArrayTextWriter tw = NewTextWriter)
+ {
+ var toWrite = new string(TestDataProvider.CharData);
+ await tw.WriteLineAsync(toWrite);
+ Assert.Equal(toWrite + tw.NewLine, tw.Text);
+ }
+ }
+
+ [Fact]
+ public async void WriteLineAsyncCharArrayIndexCount()
+ {
+ using (CharArrayTextWriter tw = NewTextWriter)
+ {
+ await tw.WriteLineAsync(TestDataProvider.CharData, 3, 5);
+ Assert.Equal(new string(TestDataProvider.CharData, 3, 5) + tw.NewLine, tw.Text);
+ }
+ }
+
+ #endregion
+ }
+}
diff --git a/src/System.IO/tests/TextWriter/TextWriterTests.netcoreapp.cs b/src/System.IO/tests/TextWriter/TextWriterTests.netcoreapp.cs
new file mode 100644
index 0000000000..9c53162ceb
--- /dev/null
+++ b/src/System.IO/tests/TextWriter/TextWriterTests.netcoreapp.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 System.Collections.Generic;
+using System.Linq;
+using System.Threading.Tasks;
+using Xunit;
+
+namespace System.IO.Tests
+{
+ public partial class TextWriterTests
+ {
+ [Fact]
+ public void WriteCharSpanTest()
+ {
+ using (CharArrayTextWriter tw = NewTextWriter)
+ {
+ var rs = new ReadOnlySpan<char>(TestDataProvider.CharData, 4, 6);
+ tw.Write(rs);
+ Assert.Equal(new string(rs), tw.Text);
+ }
+ }
+
+ [Fact]
+ public void WriteLineCharSpanTest()
+ {
+ using (CharArrayTextWriter tw = NewTextWriter)
+ {
+ var rs = new ReadOnlySpan<char>(TestDataProvider.CharData, 4, 6);
+ tw.WriteLine(rs);
+ Assert.Equal(new string(rs) + tw.NewLine, tw.Text);
+ }
+ }
+ }
+}
diff --git a/src/System.Linq.Expressions/src/System/Linq/Expressions/Compiler/LambdaCompiler.Expressions.cs b/src/System.Linq.Expressions/src/System/Linq/Expressions/Compiler/LambdaCompiler.Expressions.cs
index d8b1c61f74..042140e9ca 100644
--- a/src/System.Linq.Expressions/src/System/Linq/Expressions/Compiler/LambdaCompiler.Expressions.cs
+++ b/src/System.Linq.Expressions/src/System/Linq/Expressions/Compiler/LambdaCompiler.Expressions.cs
@@ -171,7 +171,7 @@ namespace System.Linq.Expressions.Compiler
// Optimization: inline code for literal lambda's directly
//
- // This is worth it because otherwise we end up with a extra call
+ // This is worth it because otherwise we end up with an extra call
// to DynamicMethod.CreateDelegate, which is expensive.
//
if (node.LambdaOperand != null)
diff --git a/src/System.Linq.Expressions/src/System/Linq/Expressions/ExpressionType.cs b/src/System.Linq.Expressions/src/System/Linq/Expressions/ExpressionType.cs
index a4f9d67870..c9aa32455e 100644
--- a/src/System.Linq.Expressions/src/System/Linq/Expressions/ExpressionType.cs
+++ b/src/System.Linq.Expressions/src/System/Linq/Expressions/ExpressionType.cs
@@ -334,7 +334,7 @@ namespace System.Linq.Expressions
/// </summary>
PostDecrementAssign,
/// <summary>
- /// A node that represents a exact type test.
+ /// A node that represents an exact type test.
/// </summary>
TypeEqual,
/// <summary>
diff --git a/src/System.Linq/src/System/Linq/Take.cs b/src/System.Linq/src/System/Linq/Take.cs
index 7a53ece2b1..b73fab326a 100644
--- a/src/System.Linq/src/System/Linq/Take.cs
+++ b/src/System.Linq/src/System/Linq/Take.cs
@@ -116,10 +116,18 @@ namespace System.Linq
Debug.Assert(source != null);
Debug.Assert(count > 0);
- var queue = new Queue<TSource>();
+ Queue<TSource> queue;
using (IEnumerator<TSource> e = source.GetEnumerator())
{
+ if (!e.MoveNext())
+ {
+ yield break;
+ }
+
+ queue = new Queue<TSource>();
+ queue.Enqueue(e.Current);
+
while (e.MoveNext())
{
if (queue.Count < count)
diff --git a/src/System.Linq/tests/ConcatTests.cs b/src/System.Linq/tests/ConcatTests.cs
index 89b9052942..425fefbdd7 100644
--- a/src/System.Linq/tests/ConcatTests.cs
+++ b/src/System.Linq/tests/ConcatTests.cs
@@ -421,5 +421,123 @@ namespace System.Linq.Tests
Assert.Equal(0xf00, en.Current);
}
}
+
+ [Theory]
+ [MemberData(nameof(GetToArrayDataSources))]
+ public void CollectionInterleavedWithLazyEnumerables_ToArray(IEnumerable<int>[] arrays)
+ {
+ // See https://github.com/dotnet/corefx/issues/23680
+
+ IEnumerable<int> concats = arrays[0];
+
+ for (int i = 1; i < arrays.Length; i++)
+ {
+ concats = concats.Concat(arrays[i]);
+ }
+
+ int[] results = concats.ToArray();
+
+ for (int i = 0; i < results.Length; i++)
+ {
+ Assert.Equal(i, results[i]);
+ }
+ }
+
+ private static IEnumerable<object[]> GetToArrayDataSources()
+ {
+ // Marker at the end
+ yield return new object[]
+ {
+ new IEnumerable<int>[]
+ {
+ new TestEnumerable<int>(new int[] { 0 }),
+ new TestEnumerable<int>(new int[] { 1 }),
+ new TestEnumerable<int>(new int[] { 2 }),
+ new int[] { 3 },
+ }
+ };
+
+ // Marker at beginning
+ yield return new object[]
+ {
+ new IEnumerable<int>[]
+ {
+ new int[] { 0 },
+ new TestEnumerable<int>(new int[] { 1 }),
+ new TestEnumerable<int>(new int[] { 2 }),
+ new TestEnumerable<int>(new int[] { 3 }),
+ }
+ };
+
+ // Marker in middle
+ yield return new object[]
+ {
+ new IEnumerable<int>[]
+ {
+ new TestEnumerable<int>(new int[] { 0 }),
+ new int[] { 1 },
+ new TestEnumerable<int>(new int[] { 2 }),
+ }
+ };
+
+ // Non-marker in middle
+ yield return new object[]
+ {
+ new IEnumerable<int>[]
+ {
+ new int[] { 0 },
+ new TestEnumerable<int>(new int[] { 1 }),
+ new int[] { 2 },
+ }
+ };
+
+ // Big arrays (marker in middle)
+ yield return new object[]
+ {
+ new IEnumerable<int>[]
+ {
+ new TestEnumerable<int>(Enumerable.Range(0, 100).ToArray()),
+ Enumerable.Range(100, 100).ToArray(),
+ new TestEnumerable<int>(Enumerable.Range(200, 100).ToArray()),
+ }
+ };
+
+ // Big arrays (non-marker in middle)
+ yield return new object[]
+ {
+ new IEnumerable<int>[]
+ {
+ Enumerable.Range(0, 100).ToArray(),
+ new TestEnumerable<int>(Enumerable.Range(100, 100).ToArray()),
+ Enumerable.Range(200, 100).ToArray(),
+ }
+ };
+
+ // Interleaved (first marker)
+ yield return new object[]
+ {
+ new IEnumerable<int>[]
+ {
+ new int[] { 0 },
+ new TestEnumerable<int>(new int[] { 1 }),
+ new int[] { 2 },
+ new TestEnumerable<int>(new int[] { 3 }),
+ new int[] { 4 },
+ }
+ };
+
+ // Interleaved (first non-marker)
+ yield return new object[]
+ {
+ new IEnumerable<int>[]
+ {
+ new TestEnumerable<int>(new int[] { 0 }),
+ new int[] { 1 },
+ new TestEnumerable<int>(new int[] { 2 }),
+ new int[] { 3 },
+ new TestEnumerable<int>(new int[] { 4 }),
+ }
+ };
+ }
}
}
diff --git a/src/System.Linq/tests/SelectManyTests.cs b/src/System.Linq/tests/SelectManyTests.cs
index 10eb908b72..1026e93698 100644
--- a/src/System.Linq/tests/SelectManyTests.cs
+++ b/src/System.Linq/tests/SelectManyTests.cs
@@ -477,5 +477,116 @@ namespace System.Linq.Tests
IEnumerable<int> iterator = counts.SelectMany(c => Enumerable.Range(1, c));
Assert.Throws<OverflowException>(() => iterator.Count());
}
+
+ [Theory]
+ [MemberData(nameof(GetToArrayDataSources))]
+ public void CollectionInterleavedWithLazyEnumerables_ToArray(IEnumerable<int>[] arrays)
+ {
+ // See https://github.com/dotnet/corefx/issues/23680
+
+ int[] results = arrays.SelectMany(ar => ar).ToArray();
+
+ for (int i = 0; i < results.Length; i++)
+ {
+ Assert.Equal(i, results[i]);
+ }
+ }
+
+ private static IEnumerable<object[]> GetToArrayDataSources()
+ {
+ // Marker at the end
+ yield return new object[]
+ {
+ new IEnumerable<int>[]
+ {
+ new TestEnumerable<int>(new int[] { 0 }),
+ new TestEnumerable<int>(new int[] { 1 }),
+ new TestEnumerable<int>(new int[] { 2 }),
+ new int[] { 3 },
+ }
+ };
+
+ // Marker at beginning
+ yield return new object[]
+ {
+ new IEnumerable<int>[]
+ {
+ new int[] { 0 },
+ new TestEnumerable<int>(new int[] { 1 }),
+ new TestEnumerable<int>(new int[] { 2 }),
+ new TestEnumerable<int>(new int[] { 3 }),
+ }
+ };
+
+ // Marker in middle
+ yield return new object[]
+ {
+ new IEnumerable<int>[]
+ {
+ new TestEnumerable<int>(new int[] { 0 }),
+ new int[] { 1 },
+ new TestEnumerable<int>(new int[] { 2 }),
+ }
+ };
+
+ // Non-marker in middle
+ yield return new object[]
+ {
+ new IEnumerable<int>[]
+ {
+ new int[] { 0 },
+ new TestEnumerable<int>(new int[] { 1 }),
+ new int[] { 2 },
+ }
+ };
+
+ // Big arrays (marker in middle)
+ yield return new object[]
+ {
+ new IEnumerable<int>[]
+ {
+ new TestEnumerable<int>(Enumerable.Range(0, 100).ToArray()),
+ Enumerable.Range(100, 100).ToArray(),
+ new TestEnumerable<int>(Enumerable.Range(200, 100).ToArray()),
+ }
+ };
+
+ // Big arrays (non-marker in middle)
+ yield return new object[]
+ {
+ new IEnumerable<int>[]
+ {
+ Enumerable.Range(0, 100).ToArray(),
+ new TestEnumerable<int>(Enumerable.Range(100, 100).ToArray()),
+ Enumerable.Range(200, 100).ToArray(),
+ }
+ };
+
+ // Interleaved (first marker)
+ yield return new object[]
+ {
+ new IEnumerable<int>[]
+ {
+ new int[] { 0 },
+ new TestEnumerable<int>(new int[] { 1 }),
+ new int[] { 2 },
+ new TestEnumerable<int>(new int[] { 3 }),
+ new int[] { 4 },
+ }
+ };
+
+ // Interleaved (first non-marker)
+ yield return new object[]
+ {
+ new IEnumerable<int>[]
+ {
+ new TestEnumerable<int>(new int[] { 0 }),
+ new int[] { 1 },
+ new TestEnumerable<int>(new int[] { 2 }),
+ new int[] { 3 },
+ new TestEnumerable<int>(new int[] { 4 }),
+ }
+ };
+ }
}
}
diff --git a/src/System.Memory/pkg/System.Memory.pkgproj b/src/System.Memory/pkg/System.Memory.pkgproj
index f3cd4ae500..ff57701606 100644
--- a/src/System.Memory/pkg/System.Memory.pkgproj
+++ b/src/System.Memory/pkg/System.Memory.pkgproj
@@ -4,11 +4,18 @@
<ItemGroup>
<PackageIndex Include="$(ProjectDir)\pkg\baseline\packageBaseline.1.1.json" />
<ProjectReference Include="..\ref\System.Memory.csproj">
- <SupportedFramework>net45;netcore45;wp8;wpa81;netcoreapp1.0;$(AllXamarinFrameworks)</SupportedFramework>
+ <SupportedFramework>net45;netcore45;wpa81;netcoreapp1.0;$(AllXamarinFrameworks)</SupportedFramework>
</ProjectReference>
<ProjectReference Include="..\src\System.Memory.csproj" />
- <InboxOnTargetFramework Include="netcoreapp2.1" />
- <InboxOnTargetFramework Include="$(UAPvNextTFM)" />
+
+ <!-- Since UAP and .NETCoreApp are package based we still want to enable
+ OOBing libraries that happen to overlap with their framework package.
+ This avoids us having to lock the API in our NuGet packages just
+ to match what shipped inbox: since we can provide a new library
+ we can update it to add API without raising the netstandard version. -->
+ <ValidatePackageSuppression Include="TreatAsOutOfBox">
+ <Value>.NETCoreApp;UAP</Value>
+ </ValidatePackageSuppression>
</ItemGroup>
<Import Project="$([MSBuild]::GetDirectoryNameOfFileAbove($(MSBuildThisFileDirectory), dir.targets))\dir.targets" />
</Project> \ No newline at end of file
diff --git a/src/System.Memory/ref/Configurations.props b/src/System.Memory/ref/Configurations.props
index a3959b9563..41873b4f7e 100644
--- a/src/System.Memory/ref/Configurations.props
+++ b/src/System.Memory/ref/Configurations.props
@@ -1,12 +1,9 @@
<?xml version="1.0" encoding="utf-8"?>
<Project ToolsVersion="14.0" DefaultTargets="Build" xmlns="http://schemas.microsoft.com/developer/msbuild/2003">
<PropertyGroup>
- <PackageConfigurations>
- netstandard1.0;
- netstandard;
- </PackageConfigurations>
<BuildConfigurations>
- $(PackageConfigurations);
+ netstandard1.1;
+ netstandard;
netcoreapp;
uap;
</BuildConfigurations>
diff --git a/src/System.Memory/ref/System.Memory.cs b/src/System.Memory/ref/System.Memory.cs
index 389fcdb54e..04b521e293 100644
--- a/src/System.Memory/ref/System.Memory.cs
+++ b/src/System.Memory/ref/System.Memory.cs
@@ -5,11 +5,9 @@
// Changes to this file must follow the http://aka.ms/api-review process.
// ------------------------------------------------------------------------------
-#pragma warning disable 0809 //warning CS0809: Obsolete member 'Span<T>.Equals(object)' overrides non-obsolete member 'object.Equals(object)'
namespace System
{
- [System.Runtime.InteropServices.StructLayoutAttribute(System.Runtime.InteropServices.LayoutKind.Sequential)]
- public partial struct ReadOnlySpan<T>
+ public readonly ref struct ReadOnlySpan<T>
{
public static ReadOnlySpan<T> Empty { get { throw null; } }
public ReadOnlySpan(T[] array) { throw null;}
@@ -19,14 +17,18 @@ namespace System
public T this[int index] { get { throw null; }}
public int Length { get { throw null; } }
public void CopyTo(Span<T> destination) { }
+ [System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Never)]
public static ReadOnlySpan<T> DangerousCreate(object obj, ref T objectData, int length) { throw null; }
+ [System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Never)]
public ref T DangerousGetPinnableReference() { throw null; }
+#pragma warning disable 0809 //warning CS0809: Obsolete member 'Span<T>.Equals(object)' overrides non-obsolete member 'object.Equals(object)'
[System.ObsoleteAttribute("Equals() on ReadOnlySpan will always throw an exception. Use == instead.")]
[System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Never)]
public override bool Equals(object obj) { throw null; }
[System.ObsoleteAttribute("GetHashCode() on ReadOnlySpan will always throw an exception.")]
[System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Never)]
public override int GetHashCode() { throw null; }
+#pragma warning restore 0809
public static bool operator ==(ReadOnlySpan<T> left, ReadOnlySpan<T> right) { throw null; }
public static implicit operator ReadOnlySpan<T> (T[] array) { throw null; }
public static implicit operator ReadOnlySpan<T> (ArraySegment<T> arraySegment) { throw null; }
@@ -37,8 +39,7 @@ namespace System
public bool TryCopyTo(Span<T> destination) { throw null; }
}
- [System.Runtime.InteropServices.StructLayoutAttribute(System.Runtime.InteropServices.LayoutKind.Sequential)]
- public partial struct Span<T>
+ public readonly ref struct Span<T>
{
public static Span<T> Empty { get { throw null; } }
public Span(T[] array) { throw null;}
@@ -50,14 +51,18 @@ namespace System
public void Clear() { }
public void Fill(T value) { }
public void CopyTo(Span<T> destination) { }
+ [System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Never)]
public static Span<T> DangerousCreate(object obj, ref T objectData, int length) { throw null; }
+ [System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Never)]
public ref T DangerousGetPinnableReference() { throw null; }
+#pragma warning disable 0809 //warning CS0809: Obsolete member 'Span<T>.Equals(object)' overrides non-obsolete member 'object.Equals(object)'
[System.ObsoleteAttribute("Equals() on Span will always throw an exception. Use == instead.")]
[System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Never)]
public override bool Equals(object obj) { throw null; }
[System.ObsoleteAttribute("GetHashCode() on Span will always throw an exception.")]
[System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Never)]
public override int GetHashCode() { throw null; }
+#pragma warning restore 0809
public static bool operator ==(Span<T> left, Span<T> right) { throw null; }
public static implicit operator Span<T> (T[] array) { throw null; }
public static implicit operator Span<T> (ArraySegment<T> arraySegment) { throw null; }
@@ -117,5 +122,83 @@ namespace System
public static ReadOnlySpan<TTo> NonPortableCast<TFrom, TTo>(this ReadOnlySpan<TFrom> source) where TFrom : struct where TTo : struct { throw null; }
}
+
+ public readonly struct ReadOnlyMemory<T>
+ {
+ public static ReadOnlyMemory<T> Empty { get { throw null; } }
+ public ReadOnlyMemory(T[] array) { throw null;}
+ public ReadOnlyMemory(T[] array, int start, int length) { throw null;}
+ internal ReadOnlyMemory(Buffers.OwnedMemory<T> owner, int index, int length) { throw null;}
+ public bool IsEmpty { get { throw null; } }
+ public int Length { get { throw null; } }
+ [System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Never)]
+ public override bool Equals(object obj) { throw null; }
+ public bool Equals(ReadOnlyMemory<T> other) { throw null; }
+ [System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Never)]
+ public override int GetHashCode() { throw null; }
+ public static implicit operator ReadOnlyMemory<T>(T[] array) { throw null; }
+ public static implicit operator ReadOnlyMemory<T>(ArraySegment<T> arraySegment) { throw null; }
+ public ReadOnlyMemory<T> Slice(int start) { throw null; }
+ public ReadOnlyMemory<T> Slice(int start, int length) { throw null; }
+ public ReadOnlySpan<T> Span { get { throw null; } }
+ public unsafe Buffers.MemoryHandle Retain(bool pin = false) { throw null; }
+ public T[] ToArray() { throw null; }
+ [System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Never)]
+ public bool DangerousTryGetArray(out ArraySegment<T> arraySegment) { throw null; }
+ }
+
+ public readonly struct Memory<T>
+ {
+ public static Memory<T> Empty { get { throw null; } }
+ public Memory(T[] array) { throw null;}
+ public Memory(T[] array, int start, int length) { throw null;}
+ internal Memory(Buffers.OwnedMemory<T> owner, int index, int length) { throw null;}
+ public bool IsEmpty { get { throw null; } }
+ public int Length { get { throw null; } }
+ [System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Never)]
+ public override bool Equals(object obj) { throw null; }
+ public bool Equals(Memory<T> other) { throw null; }
+ [System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Never)]
+ public override int GetHashCode() { throw null; }
+ public static implicit operator Memory<T>(T[] array) { throw null; }
+ public static implicit operator Memory<T>(ArraySegment<T> arraySegment) { throw null; }
+ public static implicit operator ReadOnlyMemory<T>(Memory<T> memory) { throw null; }
+ public Memory<T> Slice(int start) { throw null; }
+ public Memory<T> Slice(int start, int length) { throw null; }
+ public Span<T> Span { get { throw null; } }
+ public unsafe Buffers.MemoryHandle Retain(bool pin = false) { throw null; }
+ public T[] ToArray() { throw null; }
+ public bool TryGetArray(out ArraySegment<T> arraySegment) { throw null; }
+ }
}
+namespace System.Buffers
+{
+ public unsafe struct MemoryHandle : IDisposable
+ {
+ public MemoryHandle(IRetainable owner, void* pinnedPointer = null, System.Runtime.InteropServices.GCHandle handle = default(System.Runtime.InteropServices.GCHandle)) { throw null; }
+ public void* PinnedPointer { get { throw null; } }
+ public void Dispose() { throw null; }
+ }
+
+ public interface IRetainable
+ {
+ bool Release();
+ void Retain();
+ }
+
+ public abstract class OwnedMemory<T> : IDisposable, IRetainable
+ {
+ public Memory<T> Memory { get { throw null; } }
+ public abstract bool IsDisposed { get; }
+ protected abstract bool IsRetained { get; }
+ public abstract int Length { get; }
+ public abstract Span<T> Span { get; }
+ public void Dispose() { throw null; }
+ protected abstract void Dispose(bool disposing);
+ public abstract MemoryHandle Pin();
+ public abstract bool Release();
+ public abstract void Retain();
+ protected internal abstract bool TryGetArray(out ArraySegment<T> arraySegment);
+ }
+} \ No newline at end of file
diff --git a/src/System.Memory/ref/System.Memory.csproj b/src/System.Memory/ref/System.Memory.csproj
index 3ab1def519..0d0db9a2fd 100644
--- a/src/System.Memory/ref/System.Memory.csproj
+++ b/src/System.Memory/ref/System.Memory.csproj
@@ -9,8 +9,8 @@
</PropertyGroup>
<PropertyGroup Condition="'$(Configuration)|$(Platform)' == 'netstandard-Debug|AnyCPU'" />
<PropertyGroup Condition="'$(Configuration)|$(Platform)' == 'netstandard-Release|AnyCPU'" />
- <PropertyGroup Condition="'$(Configuration)|$(Platform)' == 'netstandard1.0-Debug|AnyCPU'" />
- <PropertyGroup Condition="'$(Configuration)|$(Platform)' == 'netstandard1.0-Release|AnyCPU'" />
+ <PropertyGroup Condition="'$(Configuration)|$(Platform)' == 'netstandard1.1-Debug|AnyCPU'" />
+ <PropertyGroup Condition="'$(Configuration)|$(Platform)' == 'netstandard1.1-Release|AnyCPU'" />
<PropertyGroup Condition="'$(Configuration)|$(Platform)' == 'netcoreapp-Debug|AnyCPU'" />
<PropertyGroup Condition="'$(Configuration)|$(Platform)' == 'netcoreapp-Release|AnyCPU'" />
<PropertyGroup Condition="'$(Configuration)|$(Platform)' == 'uap-Debug|AnyCPU'" />
@@ -20,9 +20,11 @@
</ItemGroup>
<ItemGroup Condition="'$(IsPartialFacadeAssembly)' == 'true'">
<ProjectReference Include="..\..\System.Runtime\ref\System.Runtime.csproj" />
+ <ProjectReference Include="..\..\System.Runtime.InteropServices\ref\System.Runtime.InteropServices.csproj" />
</ItemGroup>
- <ItemGroup Condition="'$(TargetGroup)' == 'netstandard1.0'">
+ <ItemGroup Condition="'$(TargetGroup)' == 'netstandard1.1'">
<Reference Include="System.Runtime" />
+ <Reference Include="System.Runtime.InteropServices" />
</ItemGroup>
<Import Project="$([MSBuild]::GetDirectoryNameOfFileAbove($(MSBuildThisFileDirectory), dir.targets))\dir.targets" />
</Project>
diff --git a/src/System.Memory/src/Configurations.props b/src/System.Memory/src/Configurations.props
index 487dfe3495..3026f5c782 100644
--- a/src/System.Memory/src/Configurations.props
+++ b/src/System.Memory/src/Configurations.props
@@ -1,12 +1,9 @@
<?xml version="1.0" encoding="utf-8"?>
<Project ToolsVersion="14.0" DefaultTargets="Build" xmlns="http://schemas.microsoft.com/developer/msbuild/2003">
<PropertyGroup>
- <PackageConfigurations>
- netstandard1.0;
- netstandard;
- </PackageConfigurations>
<BuildConfigurations>
- $(PackageConfigurations);
+ netstandard1.1;
+ netstandard;
netcoreapp-Windows_NT;
netcoreapp-Unix;
uap-Windows_NT;
diff --git a/src/System.Memory/src/Resources/Strings.resx b/src/System.Memory/src/Resources/Strings.resx
index 797f8e29eb..9fd5a70774 100644
--- a/src/System.Memory/src/Resources/Strings.resx
+++ b/src/System.Memory/src/Resources/Strings.resx
@@ -1,5 +1,64 @@
<?xml version="1.0" encoding="utf-8"?>
<root>
+ <!--
+ Microsoft ResX Schema
+
+ Version 2.0
+
+ The primary goals of this format is to allow a simple XML format
+ that is mostly human readable. The generation and parsing of the
+ various data types are done through the TypeConverter classes
+ associated with the data types.
+
+ Example:
+
+ ... ado.net/XML headers & schema ...
+ <resheader name="resmimetype">text/microsoft-resx</resheader>
+ <resheader name="version">2.0</resheader>
+ <resheader name="reader">System.Resources.ResXResourceReader, System.Windows.Forms, ...</resheader>
+ <resheader name="writer">System.Resources.ResXResourceWriter, System.Windows.Forms, ...</resheader>
+ <data name="Name1"><value>this is my long string</value><comment>this is a comment</comment></data>
+ <data name="Color1" type="System.Drawing.Color, System.Drawing">Blue</data>
+ <data name="Bitmap1" mimetype="application/x-microsoft.net.object.binary.base64">
+ <value>[base64 mime encoded serialized .NET Framework object]</value>
+ </data>
+ <data name="Icon1" type="System.Drawing.Icon, System.Drawing" mimetype="application/x-microsoft.net.object.bytearray.base64">
+ <value>[base64 mime encoded string representing a byte array form of the .NET Framework object]</value>
+ <comment>This is a comment</comment>
+ </data>
+
+ There are any number of "resheader" rows that contain simple
+ name/value pairs.
+
+ Each data row contains a name, and value. The row also contains a
+ type or mimetype. Type corresponds to a .NET class that support
+ text/value conversion through the TypeConverter architecture.
+ Classes that don't support this are serialized and stored with the
+ mimetype set.
+
+ The mimetype is used for serialized objects, and tells the
+ ResXResourceReader how to depersist the object. This is currently not
+ extensible. For a given mimetype the value must be set accordingly:
+
+ Note - application/x-microsoft.net.object.binary.base64 is the format
+ that the ResXResourceWriter will generate, however the reader can
+ read any of the formats listed below.
+
+ mimetype: application/x-microsoft.net.object.binary.base64
+ value : The object must be serialized with
+ : System.Runtime.Serialization.Formatters.Binary.BinaryFormatter
+ : and then encoded with base64 encoding.
+
+ mimetype: application/x-microsoft.net.object.soap.base64
+ value : The object must be serialized with
+ : System.Runtime.Serialization.Formatters.Soap.SoapFormatter
+ : and then encoded with base64 encoding.
+
+ mimetype: application/x-microsoft.net.object.bytearray.base64
+ value : The object must be serialized into a byte array
+ : using a System.ComponentModel.TypeConverter
+ : and then encoded with base64 encoding.
+ -->
<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">
@@ -73,4 +132,10 @@
<data name="Argument_DestinationTooShort" xml:space="preserve">
<value>Destination is too short.</value>
</data>
-</root>
+ <data name="MemoryDisposed" xml:space="preserve">
+ <value>Memory&lt;T&gt; has been disposed.</value>
+ </data>
+ <data name="OutstandingReferences" xml:space="preserve">
+ <value>Release all references before disposing this instance.</value>
+ </data>
+</root> \ No newline at end of file
diff --git a/src/System.Memory/src/System.Memory.csproj b/src/System.Memory/src/System.Memory.csproj
index 2945135c16..d551fd6925 100644
--- a/src/System.Memory/src/System.Memory.csproj
+++ b/src/System.Memory/src/System.Memory.csproj
@@ -8,7 +8,7 @@
<DocumentationFile>$(OutputPath)$(MSBuildProjectName).xml</DocumentationFile>
<IsPartialFacadeAssembly Condition="'$(TargetGroup)' == 'netcoreapp' OR '$(TargetGroup)' == 'uap'">true</IsPartialFacadeAssembly>
<DefineConstants Condition="'$(TargetGroup)'=='netcoreapp'">$(DefineConstants);netcoreapp</DefineConstants>
- <DefineConstants Condition="'$(TargetGroup)'=='netstandard1.0'">$(DefineConstants);netstandard10</DefineConstants>
+ <DefineConstants Condition="'$(TargetGroup)'=='netstandard1.1'">$(DefineConstants);netstandard11</DefineConstants>
</PropertyGroup>
<PropertyGroup Condition="'$(Configuration)|$(Platform)' == 'netcoreapp-Unix-Debug|AnyCPU'" />
<PropertyGroup Condition="'$(Configuration)|$(Platform)' == 'netcoreapp-Unix-Release|AnyCPU'" />
@@ -16,8 +16,8 @@
<PropertyGroup Condition="'$(Configuration)|$(Platform)' == 'netcoreapp-Windows_NT-Release|AnyCPU'" />
<PropertyGroup Condition="'$(Configuration)|$(Platform)' == 'netstandard-Debug|AnyCPU'" />
<PropertyGroup Condition="'$(Configuration)|$(Platform)' == 'netstandard-Release|AnyCPU'" />
- <PropertyGroup Condition="'$(Configuration)|$(Platform)' == 'netstandard1.0-Debug|AnyCPU'" />
- <PropertyGroup Condition="'$(Configuration)|$(Platform)' == 'netstandard1.0-Release|AnyCPU'" />
+ <PropertyGroup Condition="'$(Configuration)|$(Platform)' == 'netstandard1.1-Debug|AnyCPU'" />
+ <PropertyGroup Condition="'$(Configuration)|$(Platform)' == 'netstandard1.1-Release|AnyCPU'" />
<PropertyGroup Condition="'$(Configuration)|$(Platform)' == 'uap-Windows_NT-Debug|AnyCPU'" />
<PropertyGroup Condition="'$(Configuration)|$(Platform)' == 'uap-Windows_NT-Release|AnyCPU'" />
<ItemGroup>
@@ -34,15 +34,21 @@
<Compile Include="System\Pinnable.cs" />
<Compile Include="System\ThrowHelper.cs" />
<Compile Include="System\SpanHelpers.Clear.cs" />
+ <Compile Include="System\Memory.cs" />
+ <Compile Include="System\ReadOnlyMemory.cs" />
+ <Compile Include="System\Buffers\IRetainable.cs" />
+ <Compile Include="System\Buffers\MemoryHandle.cs" />
+ <Compile Include="System\Buffers\OwnedMemory.cs" />
</ItemGroup>
<ItemGroup Condition="'$(IsPartialFacadeAssembly)' != 'true'">
<Reference Include="System.Diagnostics.Debug" />
<Reference Include="System.Reflection" />
<Reference Include="System.Resources.ResourceManager" />
<Reference Include="System.Runtime" />
- <Reference Condition="'$(TargetGroup)' != 'netstandard1.0'" Include="System.Numerics.Vectors" />
- <Reference Condition="'$(TargetGroup)' != 'netstandard1.0'" Include="System.Runtime.CompilerServices.Unsafe" />
- <ProjectReference Condition="'$(TargetGroup)' == 'netstandard1.0'" Include="..\..\System.Runtime.CompilerServices.Unsafe\ref\System.Runtime.CompilerServices.Unsafe.csproj" />
+ <Reference Include="System.Runtime.InteropServices" />
+ <Reference Condition="'$(TargetGroup)' != 'netstandard1.1'" Include="System.Numerics.Vectors" />
+ <Reference Condition="'$(TargetGroup)' != 'netstandard1.1'" Include="System.Runtime.CompilerServices.Unsafe" />
+ <ProjectReference Condition="'$(TargetGroup)' == 'netstandard1.1'" Include="..\..\System.Runtime.CompilerServices.Unsafe\ref\System.Runtime.CompilerServices.Unsafe.csproj" />
</ItemGroup>
<ItemGroup Condition="'$(IsPartialFacadeAssembly)' == 'true'">
<Compile Include="System\SpanExtensions.Fast.cs" />
@@ -55,4 +61,4 @@
<ProjectReference Include="..\..\System.Numerics.Vectors\src\System.Numerics.Vectors.csproj" />
</ItemGroup>
<Import Project="$([MSBuild]::GetDirectoryNameOfFileAbove($(MSBuildThisFileDirectory), dir.targets))\dir.targets" />
-</Project> \ No newline at end of file
+</Project>
diff --git a/src/System.Memory/src/System/Buffers/IRetainable.cs b/src/System.Memory/src/System/Buffers/IRetainable.cs
new file mode 100644
index 0000000000..3a92b3d5f5
--- /dev/null
+++ b/src/System.Memory/src/System/Buffers/IRetainable.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 System.Runtime;
+using System.Runtime.CompilerServices;
+
+namespace System.Buffers
+{
+ /// <summary>
+ /// Provides a mechanism for manual lifetime management.
+ /// </summary>
+ public interface IRetainable
+ {
+ /// <summary>
+ /// Call this method to indicate that the IRetainable object is in use.
+ /// Do not dispose until Release is called.
+ /// </summary>
+ void Retain();
+
+ /// <summary>
+ /// Call this method to indicate that the IRetainable object is no longer in use.
+ /// The object can now be disposed.
+ /// </summary>
+ bool Release();
+ }
+}
diff --git a/src/System.Memory/src/System/Buffers/MemoryHandle.cs b/src/System.Memory/src/System/Buffers/MemoryHandle.cs
new file mode 100644
index 0000000000..315d07076c
--- /dev/null
+++ b/src/System.Memory/src/System/Buffers/MemoryHandle.cs
@@ -0,0 +1,57 @@
+// 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;
+using System.Runtime.InteropServices;
+
+namespace System.Buffers
+{
+ /// <summary>
+ /// A handle for the memory.
+ /// </summary>
+ public unsafe struct MemoryHandle : IDisposable
+ {
+ private IRetainable _retainable;
+ private void* _pointer;
+ private GCHandle _handle;
+
+ /// <summary>
+ /// Creates a new memory handle for the memory.
+ /// </summary>
+ /// <param name="retainable">reference to manually managed object</param>
+ /// <param name="pinnedPointer">pointer to the buffer, or null if the buffer is not pinned</param>
+ /// <param name="handle">handle used to pin array buffers</param>
+ public MemoryHandle(IRetainable retainable, void* pinnedPointer = null, GCHandle handle = default(GCHandle))
+ {
+ _retainable = retainable;
+ _pointer = pinnedPointer;
+ _handle = handle;
+ }
+
+ /// <summary>
+ /// Returns the address of the pinned object, or null if the object is not pinned.
+ /// </summary>
+ public void* PinnedPointer => _pointer;
+
+ /// <summary>
+ /// Frees the pinned handle and releases IRetainable.
+ /// </summary>
+ public void Dispose()
+ {
+ if (_handle.IsAllocated)
+ {
+ _handle.Free();
+ }
+
+ if (_retainable != null)
+ {
+ _retainable.Release();
+ _retainable = null;
+ }
+
+ _pointer = null;
+ }
+
+ }
+}
diff --git a/src/System.Memory/src/System/Buffers/OwnedMemory.cs b/src/System.Memory/src/System/Buffers/OwnedMemory.cs
new file mode 100644
index 0000000000..3daae843da
--- /dev/null
+++ b/src/System.Memory/src/System/Buffers/OwnedMemory.cs
@@ -0,0 +1,97 @@
+// 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;
+using System.Runtime.CompilerServices;
+
+namespace System.Buffers
+{
+
+ /// <summary>
+ /// Owner of Memory<typeparamref name="T"/> that provides appropriate lifetime management mechanisms for it.
+ /// </summary>
+ public abstract class OwnedMemory<T> : IDisposable, IRetainable
+ {
+
+ /// <summary>
+ /// The number of items in the Memory<typeparamref name="T"/>.
+ /// </summary>
+ public abstract int Length { get; }
+
+ /// <summary>
+ /// Returns a span wrapping the underlying memory.
+ /// </summary>
+ public abstract Span<T> Span { get; }
+
+ /// <summary>
+ /// Returns a Memory<typeparamref name="T"/> if the underlying memory has not been freed.
+ /// </summary>
+ /// <exception cref="System.ObjectDisposedException">
+ /// Thrown when the underlying memory has already been disposed.
+ /// </exception>
+ public Memory<T> Memory
+ {
+ get
+ {
+ if (IsDisposed)
+ {
+ ThrowHelper.ThrowObjectDisposedException_MemoryDisposed(nameof(OwnedMemory<T>));
+ }
+ return new Memory<T>(this, 0, Length);
+ }
+ }
+
+ /// <summary>
+ /// Returns a handle for the array that has been pinned and hence its address can be taken
+ /// </summary>
+ public abstract MemoryHandle Pin();
+
+ /// <summary>
+ /// Returns an array segment.
+ /// </summary>
+ protected internal abstract bool TryGetArray(out ArraySegment<T> arraySegment);
+
+ /// <summary>
+ /// Implements IDisposable.
+ /// </summary>
+ /// <exception cref="System.InvalidOperationException">
+ /// Throw when there are still retained references to the memory
+ /// </exception>
+ public void Dispose()
+ {
+ if (IsRetained)
+ {
+ ThrowHelper.ThrowInvalidOperationException_OutstandingReferences();
+ }
+ Dispose(true);
+ GC.SuppressFinalize(this);
+ }
+
+ /// <summary>
+ /// Clean up of any leftover managed and unmanaged resources.
+ /// </summary>
+ protected abstract void Dispose(bool disposing);
+
+ /// <summary>
+ /// Return true if someone is holding a reference to the memory.
+ /// </summary>
+ protected abstract bool IsRetained { get; }
+
+ /// <summary>
+ /// Return true if the underlying memory has been freed.
+ /// </summary>
+ public abstract bool IsDisposed { get; }
+
+ /// <summary>
+ /// Implements IRetainable. Prevent accidental disposal of the memory.
+ /// </summary>
+ public abstract void Retain();
+
+ /// <summary>
+ /// Implements IRetainable. The memory can now be diposed.
+ /// </summary>
+ public abstract bool Release();
+
+ }
+}
diff --git a/src/System.Memory/src/System/Memory.cs b/src/System.Memory/src/System/Memory.cs
new file mode 100644
index 0000000000..c5779b70ad
--- /dev/null
+++ b/src/System.Memory/src/System/Memory.cs
@@ -0,0 +1,304 @@
+// 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.Buffers;
+using EditorBrowsableAttribute = System.ComponentModel.EditorBrowsableAttribute;
+using EditorBrowsableState = System.ComponentModel.EditorBrowsableState;
+using System.Diagnostics;
+using System.Runtime;
+using System.Runtime.CompilerServices;
+using System.Runtime.InteropServices;
+
+namespace System
+{
+ /// <summary>
+ /// Memory represents a contiguous region of arbitrary memory similar to Span.
+ /// Unlike Span, it is not a byref-like type.
+ /// </summary>
+ public readonly struct Memory<T>
+ {
+ // The highest order bit of _index is used to discern whether _arrayOrOwnedMemory is an array or an owned memory
+ // if (_index >> 31) == 1, object _arrayOrOwnedMemory is an OwnedMemory<T>
+ // else, object _arrayOrOwnedMemory is a T[]
+ private readonly object _arrayOrOwnedMemory;
+ private readonly int _index;
+ private readonly int _length;
+
+ private const int RemoveOwnedFlagBitMask = 0x7FFFFFFF;
+
+ /// <summary>
+ /// Creates a new memory over the entirety of the target array.
+ /// </summary>
+ /// <param name="array">The target array.</param>
+ /// <exception cref="System.ArgumentNullException">Thrown when <paramref name="array"/> is a null
+ /// reference (Nothing in Visual Basic).</exception>
+ /// <exception cref="System.ArrayTypeMismatchException">Thrown when <paramref name="array"/> is covariant and array's type is not exactly T[].</exception>
+ [MethodImpl(MethodImplOptions.AggressiveInlining)]
+ public Memory(T[] array)
+ {
+ if (array == null)
+ ThrowHelper.ThrowArgumentNullException(ExceptionArgument.array);
+ if (default(T) == null && array.GetType() != typeof(T[]))
+ ThrowHelper.ThrowArrayTypeMismatchException_ArrayTypeMustBeExactMatch(typeof(T));
+
+ _arrayOrOwnedMemory = array;
+ _index = 0;
+ _length = array.Length;
+ }
+
+ /// <summary>
+ /// Creates a new memory over the portion of the target array beginning
+ /// at 'start' index and ending at 'end' index (exclusive).
+ /// </summary>
+ /// <param name="array">The target array.</param>
+ /// <param name="start">The index at which to begin the memory.</param>
+ /// <param name="length">The number of items in the memory.</param>
+ /// <exception cref="System.ArgumentNullException">Thrown when <paramref name="array"/> is a null
+ /// reference (Nothing in Visual Basic).</exception>
+ /// <exception cref="System.ArrayTypeMismatchException">Thrown when <paramref name="array"/> is covariant and array's type is not exactly T[].</exception>
+ /// <exception cref="System.ArgumentOutOfRangeException">
+ /// Thrown when the specified <paramref name="start"/> or end index is not in the range (&lt;0 or &gt;=Length).
+ /// </exception>
+ [MethodImpl(MethodImplOptions.AggressiveInlining)]
+ public Memory(T[] array, int start, int length)
+ {
+ if (array == null)
+ ThrowHelper.ThrowArgumentNullException(ExceptionArgument.array);
+ if (default(T) == null && array.GetType() != typeof(T[]))
+ ThrowHelper.ThrowArrayTypeMismatchException_ArrayTypeMustBeExactMatch(typeof(T));
+ if ((uint)start > (uint)array.Length || (uint)length > (uint)(array.Length - start))
+ ThrowHelper.ThrowArgumentOutOfRangeException(ExceptionArgument.start);
+
+ _arrayOrOwnedMemory = array;
+ _index = start;
+ _length = length;
+ }
+
+ // Constructor for internal use only.
+ [MethodImpl(MethodImplOptions.AggressiveInlining)]
+ internal Memory(OwnedMemory<T> owner, int index, int length)
+ {
+ if (owner == null)
+ ThrowHelper.ThrowArgumentNullException(ExceptionArgument.ownedMemory);
+ if (index < 0 || length < 0)
+ ThrowHelper.ThrowArgumentOutOfRangeException(ExceptionArgument.start);
+
+ _arrayOrOwnedMemory = owner;
+ _index = index | (1 << 31); // Before using _index, check if _index < 0, then 'and' it with RemoveOwnedFlagBitMask
+ _length = length;
+ }
+
+ /// <summary>
+ /// Defines an implicit conversion of an array to a <see cref="Memory{T}"/>
+ /// </summary>
+ public static implicit operator Memory<T>(T[] array) => new Memory<T>(array);
+
+ /// <summary>
+ /// Defines an implicit conversion of a <see cref="ArraySegment{T}"/> to a <see cref="Memory{T}"/>
+ /// </summary>
+ public static implicit operator Memory<T>(ArraySegment<T> arraySegment) => new Memory<T>(arraySegment.Array, arraySegment.Offset, arraySegment.Count);
+
+ /// <summary>
+ /// Defines an implicit conversion of a <see cref="Memory{T}"/> to a <see cref="ReadOnlyMemory{T}"/>
+ /// </summary>
+ [MethodImpl(MethodImplOptions.AggressiveInlining)]
+ public static implicit operator ReadOnlyMemory<T>(Memory<T> memory)
+ {
+ if (memory._index < 0)
+ return new ReadOnlyMemory<T>((OwnedMemory<T>)memory._arrayOrOwnedMemory, memory._index & RemoveOwnedFlagBitMask, memory._length);
+ return new ReadOnlyMemory<T>((T[])memory._arrayOrOwnedMemory, memory._index, memory._length);
+ }
+
+ /// <summary>
+ /// Returns an empty <see cref="Memory{T}"/>
+ /// </summary>
+ public static Memory<T> Empty { get; } =
+#if !netstandard11
+ Array.Empty<T>();
+#else
+ new T[0];
+#endif
+
+ /// <summary>
+ /// The number of items in the memory.
+ /// </summary>
+ public int Length => _length;
+
+ /// <summary>
+ /// Returns true if Length is 0.
+ /// </summary>
+ public bool IsEmpty => _length == 0;
+
+ /// <summary>
+ /// Forms a slice out of the given memory, beginning at 'start'.
+ /// </summary>
+ /// <param name="start">The index at which to begin this slice.</param>
+ /// <exception cref="System.ArgumentOutOfRangeException">
+ /// Thrown when the specified <paramref name="start"/> index is not in range (&lt;0 or &gt;=Length).
+ /// </exception>
+ [MethodImpl(MethodImplOptions.AggressiveInlining)]
+ public Memory<T> Slice(int start)
+ {
+ if ((uint)start > (uint)_length)
+ ThrowHelper.ThrowArgumentOutOfRangeException(ExceptionArgument.start);
+
+ if (_index < 0)
+ return new Memory<T>((OwnedMemory<T>)_arrayOrOwnedMemory, (_index & RemoveOwnedFlagBitMask) + start, _length - start);
+ return new Memory<T>((T[])_arrayOrOwnedMemory, _index + start, _length - start);
+ }
+
+ /// <summary>
+ /// Forms a slice out of the given memory, beginning at 'start', of given length
+ /// </summary>
+ /// <param name="start">The index at which to begin this slice.</param>
+ /// <param name="length">The desired length for the slice (exclusive).</param>
+ /// <exception cref="System.ArgumentOutOfRangeException">
+ /// Thrown when the specified <paramref name="start"/> or end index is not in range (&lt;0 or &gt;=Length).
+ /// </exception>
+ [MethodImpl(MethodImplOptions.AggressiveInlining)]
+ public Memory<T> Slice(int start, int length)
+ {
+ if ((uint)start > (uint)_length || (uint)length > (uint)(_length - start))
+ ThrowHelper.ThrowArgumentOutOfRangeException(ExceptionArgument.start);
+
+ if (_index < 0)
+ return new Memory<T>((OwnedMemory<T>)_arrayOrOwnedMemory, (_index & RemoveOwnedFlagBitMask) + start, length);
+ return new Memory<T>((T[])_arrayOrOwnedMemory, _index + start, length);
+ }
+
+ /// <summary>
+ /// Returns a span from the memory.
+ /// </summary>
+ public Span<T> Span
+ {
+ [MethodImpl(MethodImplOptions.AggressiveInlining)]
+ get
+ {
+ if (_index < 0)
+ return ((OwnedMemory<T>)_arrayOrOwnedMemory).Span.Slice(_index & RemoveOwnedFlagBitMask, _length);
+ return new Span<T>((T[])_arrayOrOwnedMemory, _index, _length);
+ }
+ }
+
+ /// <summary>
+ /// Returns a handle for the array.
+ /// <param name="pin">If pin is true, the GC will not move the array and hence its address can be taken</param>
+ /// </summary>
+ public unsafe MemoryHandle Retain(bool pin = false)
+ {
+ MemoryHandle memoryHandle;
+ if (pin)
+ {
+ if (_index < 0)
+ {
+ memoryHandle = ((OwnedMemory<T>)_arrayOrOwnedMemory).Pin();
+ }
+ else
+ {
+ var array = (T[])_arrayOrOwnedMemory;
+ var handle = GCHandle.Alloc(array, GCHandleType.Pinned);
+ void* pointer = Unsafe.Add<T>((void*)handle.AddrOfPinnedObject(), _index);
+ memoryHandle = new MemoryHandle(null, pointer, handle);
+ }
+ }
+ else
+ {
+ if (_index < 0)
+ {
+ ((OwnedMemory<T>)_arrayOrOwnedMemory).Retain();
+ memoryHandle = new MemoryHandle((OwnedMemory<T>)_arrayOrOwnedMemory);
+ }
+ else
+ {
+ memoryHandle = new MemoryHandle(null);
+ }
+ }
+ return memoryHandle;
+ }
+
+ /// <summary>
+ /// Get an array segment from the underlying memory.
+ /// If unable to get the array segment, return false with a default array segment.
+ /// </summary>
+ public bool TryGetArray(out ArraySegment<T> arraySegment)
+ {
+ if (_index < 0)
+ {
+ if (((OwnedMemory<T>)_arrayOrOwnedMemory).TryGetArray(out var segment))
+ {
+ arraySegment = new ArraySegment<T>(segment.Array, segment.Offset + (_index & RemoveOwnedFlagBitMask), _length);
+ return true;
+ }
+ }
+ else
+ {
+ arraySegment = new ArraySegment<T>((T[])_arrayOrOwnedMemory, _index, _length);
+ return true;
+ }
+
+ arraySegment = default(ArraySegment<T>);
+ return false;
+ }
+
+ /// <summary>
+ /// Copies the contents from the memory into a new array. This heap
+ /// allocates, so should generally be avoided, however it is sometimes
+ /// necessary to bridge the gap with APIs written in terms of arrays.
+ /// </summary>
+ public T[] ToArray() => Span.ToArray();
+
+ /// <summary>
+ /// Determines whether the specified object is equal to the current object.
+ /// Returns true if the object is Memory or ReadOnlyMemory and if both objects point to the same array and have the same length.
+ /// </summary>
+ [EditorBrowsable(EditorBrowsableState.Never)]
+ public override bool Equals(object obj)
+ {
+ if (obj is ReadOnlyMemory<T>)
+ {
+ return ((ReadOnlyMemory<T>)obj).Equals(this);
+ }
+ else if (obj is Memory<T> memory)
+ {
+ return Equals(memory);
+ }
+ else
+ {
+ return false;
+ }
+ }
+
+ /// <summary>
+ /// Returns true if the memory points to the same array and has the same length. Note that
+ /// this does *not* check to see if the *contents* are equal.
+ /// </summary>
+ public bool Equals(Memory<T> other)
+ {
+ return
+ _arrayOrOwnedMemory == other._arrayOrOwnedMemory &&
+ _index == other._index &&
+ _length == other._length;
+ }
+
+ /// <summary>
+ /// Serves as the default hash function.
+ /// </summary>
+ [EditorBrowsable(EditorBrowsableState.Never)]
+ public override int GetHashCode()
+ {
+ return CombineHashCodes(_arrayOrOwnedMemory.GetHashCode(), (_index & RemoveOwnedFlagBitMask).GetHashCode(), _length.GetHashCode());
+ }
+
+ private static int CombineHashCodes(int left, int right)
+ {
+ return ((left << 5) + left) ^ right;
+ }
+
+ private static int CombineHashCodes(int h1, int h2, int h3)
+ {
+ return CombineHashCodes(CombineHashCodes(h1, h2), h3);
+ }
+
+ }
+}
diff --git a/src/System.Memory/src/System/ReadOnlyMemory.cs b/src/System.Memory/src/System/ReadOnlyMemory.cs
new file mode 100644
index 0000000000..5d901c518e
--- /dev/null
+++ b/src/System.Memory/src/System/ReadOnlyMemory.cs
@@ -0,0 +1,289 @@
+// 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.Buffers;
+using EditorBrowsableAttribute = System.ComponentModel.EditorBrowsableAttribute;
+using EditorBrowsableState = System.ComponentModel.EditorBrowsableState;
+using System.Diagnostics;
+using System.Runtime;
+using System.Runtime.CompilerServices;
+using System.Runtime.InteropServices;
+
+namespace System
+{
+ /// <summary>
+ /// ReadOnlyMemory represents a contiguous region of arbitrary similar to ReadOnlySpan.
+ /// Unlike ReadOnlySpan, it is not a byref-like type.
+ /// </summary>
+ public readonly struct ReadOnlyMemory<T>
+ {
+ // The highest order bit of _index is used to discern whether _arrayOrOwnedMemory is an array or an owned memory
+ // if (_index >> 31) == 1, object _arrayOrOwnedMemory is an OwnedMemory<T>
+ // else, object _arrayOrOwnedMemory is a T[]
+ private readonly object _arrayOrOwnedMemory;
+ private readonly int _index;
+ private readonly int _length;
+
+ private const int RemoveOwnedFlagBitMask = 0x7FFFFFFF;
+
+ /// <summary>
+ /// Creates a new memory over the entirety of the target array.
+ /// </summary>
+ /// <param name="array">The target array.</param>
+ /// <exception cref="System.ArgumentNullException">Thrown when <paramref name="array"/> is a null
+ /// reference (Nothing in Visual Basic).</exception>
+ /// <exception cref="System.ArrayTypeMismatchException">Thrown when <paramref name="array"/> is covariant and array's type is not exactly T[].</exception>
+ [MethodImpl(MethodImplOptions.AggressiveInlining)]
+ public ReadOnlyMemory(T[] array)
+ {
+ if (array == null)
+ ThrowHelper.ThrowArgumentNullException(ExceptionArgument.array);
+
+ _arrayOrOwnedMemory = array;
+ _index = 0;
+ _length = array.Length;
+ }
+
+ /// <summary>
+ /// Creates a new memory over the portion of the target array beginning
+ /// at 'start' index and ending at 'end' index (exclusive).
+ /// </summary>
+ /// <param name="array">The target array.</param>
+ /// <param name="start">The index at which to begin the memory.</param>
+ /// <param name="length">The number of items in the memory.</param>
+ /// <exception cref="System.ArgumentNullException">Thrown when <paramref name="array"/> is a null
+ /// reference (Nothing in Visual Basic).</exception>
+ /// <exception cref="System.ArrayTypeMismatchException">Thrown when <paramref name="array"/> is covariant and array's type is not exactly T[].</exception>
+ /// <exception cref="System.ArgumentOutOfRangeException">
+ /// Thrown when the specified <paramref name="start"/> or end index is not in the range (&lt;0 or &gt;=Length).
+ /// </exception>
+ [MethodImpl(MethodImplOptions.AggressiveInlining)]
+ public ReadOnlyMemory(T[] array, int start, int length)
+ {
+ if (array == null)
+ ThrowHelper.ThrowArgumentNullException(ExceptionArgument.array);
+ if ((uint)start > (uint)array.Length || (uint)length > (uint)(array.Length - start))
+ ThrowHelper.ThrowArgumentOutOfRangeException(ExceptionArgument.start);
+
+ _arrayOrOwnedMemory = array;
+ _index = start;
+ _length = length;
+ }
+
+ // Constructor for internal use only.
+ [MethodImpl(MethodImplOptions.AggressiveInlining)]
+ internal ReadOnlyMemory(OwnedMemory<T> owner, int index, int length)
+ {
+ if (owner == null)
+ ThrowHelper.ThrowArgumentNullException(ExceptionArgument.ownedMemory);
+ if (index < 0 || length < 0)
+ ThrowHelper.ThrowArgumentOutOfRangeException(ExceptionArgument.start);
+
+ _arrayOrOwnedMemory = owner;
+ _index = index | (1 << 31); // Before using _index, check if _index < 0, then 'and' it with RemoveOwnedFlagBitMask
+ _length = length;
+ }
+
+ /// <summary>
+ /// Defines an implicit conversion of an array to a <see cref="Memory{T}"/>
+ /// </summary>
+ public static implicit operator ReadOnlyMemory<T>(T[] array) => new ReadOnlyMemory<T>(array);
+
+ /// <summary>
+ /// Defines an implicit conversion of a <see cref="ArraySegment{T}"/> to a <see cref="Memory{T}"/>
+ /// </summary>
+ public static implicit operator ReadOnlyMemory<T>(ArraySegment<T> arraySegment) => new ReadOnlyMemory<T>(arraySegment.Array, arraySegment.Offset, arraySegment.Count);
+
+ /// <summary>
+ /// Returns an empty <see cref="Memory{T}"/>
+ /// </summary>
+ public static ReadOnlyMemory<T> Empty { get; } =
+#if !netstandard11
+ Array.Empty<T>();
+#else
+ new T[0];
+#endif
+
+ /// <summary>
+ /// The number of items in the memory.
+ /// </summary>
+ public int Length => _length;
+
+ /// <summary>
+ /// Returns true if Length is 0.
+ /// </summary>
+ public bool IsEmpty => _length == 0;
+
+ /// <summary>
+ /// Forms a slice out of the given memory, beginning at 'start'.
+ /// </summary>
+ /// <param name="start">The index at which to begin this slice.</param>
+ /// <exception cref="System.ArgumentOutOfRangeException">
+ /// Thrown when the specified <paramref name="start"/> index is not in range (&lt;0 or &gt;=Length).
+ /// </exception>
+ [MethodImpl(MethodImplOptions.AggressiveInlining)]
+ public ReadOnlyMemory<T> Slice(int start)
+ {
+ if ((uint)start > (uint)_length)
+ ThrowHelper.ThrowArgumentOutOfRangeException(ExceptionArgument.start);
+
+ if (_index < 0)
+ return new ReadOnlyMemory<T>((OwnedMemory<T>)_arrayOrOwnedMemory, (_index & RemoveOwnedFlagBitMask) + start, _length - start);
+ return new ReadOnlyMemory<T>((T[])_arrayOrOwnedMemory, _index + start, _length - start);
+ }
+
+ /// <summary>
+ /// Forms a slice out of the given memory, beginning at 'start', of given length
+ /// </summary>
+ /// <param name="start">The index at which to begin this slice.</param>
+ /// <param name="length">The desired length for the slice (exclusive).</param>
+ /// <exception cref="System.ArgumentOutOfRangeException">
+ /// Thrown when the specified <paramref name="start"/> or end index is not in range (&lt;0 or &gt;=Length).
+ /// </exception>
+ [MethodImpl(MethodImplOptions.AggressiveInlining)]
+ public ReadOnlyMemory<T> Slice(int start, int length)
+ {
+ if ((uint)start > (uint)_length || (uint)length > (uint)(_length - start))
+ ThrowHelper.ThrowArgumentOutOfRangeException(ExceptionArgument.start);
+
+ if (_index < 0)
+ return new ReadOnlyMemory<T>((OwnedMemory<T>)_arrayOrOwnedMemory, (_index & RemoveOwnedFlagBitMask) + start, length);
+ return new ReadOnlyMemory<T>((T[])_arrayOrOwnedMemory, _index + start, length);
+ }
+
+ /// <summary>
+ /// Returns a span from the memory.
+ /// </summary>
+ public ReadOnlySpan<T> Span
+ {
+ [MethodImpl(MethodImplOptions.AggressiveInlining)]
+ get
+ {
+ if (_index < 0)
+ return ((OwnedMemory<T>)_arrayOrOwnedMemory).Span.Slice(_index & RemoveOwnedFlagBitMask, _length);
+ return new ReadOnlySpan<T>((T[])_arrayOrOwnedMemory, _index, _length);
+ }
+ }
+
+ /// <summary>
+ /// Returns a handle for the array.
+ /// <param name="pin">If pin is true, the GC will not move the array and hence its address can be taken</param>
+ /// </summary>
+ public unsafe MemoryHandle Retain(bool pin = false)
+ {
+ MemoryHandle memoryHandle;
+ if (pin)
+ {
+ if (_index < 0)
+ {
+ memoryHandle = ((OwnedMemory<T>)_arrayOrOwnedMemory).Pin();
+ }
+ else
+ {
+ var array = (T[])_arrayOrOwnedMemory;
+ var handle = GCHandle.Alloc(array, GCHandleType.Pinned);
+ void* pointer = Unsafe.Add<T>((void*)handle.AddrOfPinnedObject(), _index);
+ memoryHandle = new MemoryHandle(null, pointer, handle);
+ }
+ }
+ else
+ {
+ if (_index < 0)
+ {
+ ((OwnedMemory<T>)_arrayOrOwnedMemory).Retain();
+ memoryHandle = new MemoryHandle((OwnedMemory<T>)_arrayOrOwnedMemory);
+ }
+ else
+ {
+ memoryHandle = new MemoryHandle(null);
+ }
+ }
+ return memoryHandle;
+ }
+
+ /// <summary>
+ /// Get an array segment from the underlying memory.
+ /// If unable to get the array segment, return false with a default array segment.
+ /// </summary>
+ [EditorBrowsable(EditorBrowsableState.Never)]
+ public bool DangerousTryGetArray(out ArraySegment<T> arraySegment)
+ {
+ if (_index < 0)
+ {
+ if (((OwnedMemory<T>)_arrayOrOwnedMemory).TryGetArray(out var segment))
+ {
+ arraySegment = new ArraySegment<T>(segment.Array, segment.Offset + (_index & RemoveOwnedFlagBitMask), _length);
+ return true;
+ }
+ }
+ else
+ {
+ arraySegment = new ArraySegment<T>((T[])_arrayOrOwnedMemory, _index, _length);
+ return true;
+ }
+
+ arraySegment = default(ArraySegment<T>);
+ return false;
+ }
+
+ /// <summary>
+ /// Copies the contents from the memory into a new array. This heap
+ /// allocates, so should generally be avoided, however it is sometimes
+ /// necessary to bridge the gap with APIs written in terms of arrays.
+ /// </summary>
+ public T[] ToArray() => Span.ToArray();
+
+ /// <summary>
+ /// Determines whether the specified object is equal to the current object.
+ /// </summary>
+ [EditorBrowsable(EditorBrowsableState.Never)]
+ public override bool Equals(object obj)
+ {
+ if (obj is ReadOnlyMemory<T> readOnlyMemory)
+ {
+ return Equals(readOnlyMemory);
+ }
+ else if (obj is Memory<T> memory)
+ {
+ return Equals(memory);
+ }
+ else
+ {
+ return false;
+ }
+ }
+
+ /// <summary>
+ /// Returns true if the memory points to the same array and has the same length. Note that
+ /// this does *not* check to see if the *contents* are equal.
+ /// </summary>
+ public bool Equals(ReadOnlyMemory<T> other)
+ {
+ return
+ _arrayOrOwnedMemory == other._arrayOrOwnedMemory &&
+ _index == other._index &&
+ _length == other._length;
+ }
+
+ /// <summary>
+ /// Serves as the default hash function.
+ /// </summary>
+ [EditorBrowsable( EditorBrowsableState.Never)]
+ public override int GetHashCode()
+ {
+ return CombineHashCodes(_arrayOrOwnedMemory.GetHashCode(), (_index & RemoveOwnedFlagBitMask).GetHashCode(), _length.GetHashCode());
+ }
+
+ private static int CombineHashCodes(int left, int right)
+ {
+ return ((left << 5) + left) ^ right;
+ }
+
+ private static int CombineHashCodes(int h1, int h2, int h3)
+ {
+ return CombineHashCodes(CombineHashCodes(h1, h2), h3);
+ }
+
+ }
+}
diff --git a/src/System.Memory/src/System/ReadOnlySpan.cs b/src/System.Memory/src/System/ReadOnlySpan.cs
index 7e34691688..bfb6e6b7f0 100644
--- a/src/System.Memory/src/System/ReadOnlySpan.cs
+++ b/src/System.Memory/src/System/ReadOnlySpan.cs
@@ -21,7 +21,7 @@ namespace System
/// ReadOnlySpan represents a contiguous region of arbitrary memory. Unlike arrays, it can point to either managed
/// or native memory, or to memory allocated on the stack. It is type- and memory-safe.
/// </summary>
- public struct ReadOnlySpan<T>
+ public readonly ref struct ReadOnlySpan<T>
{
/// <summary>
/// Creates a new read-only span over the entirety of the target array.
@@ -104,6 +104,7 @@ namespace System
/// <param name="objectData">A reference to data within that object.</param>
/// <param name="length">The number of <typeparamref name="T"/> elements the memory contains.</param>
[MethodImpl(MethodImplOptions.AggressiveInlining)]
+ [EditorBrowsable(EditorBrowsableState.Never)]
public static ReadOnlySpan<T> DangerousCreate(object obj, ref T objectData, int length)
{
Pinnable<T> pinnable = Unsafe.As<Pinnable<T>>(obj);
@@ -314,6 +315,7 @@ namespace System
/// would have been stored. Such a reference can be used for pinning but must never be dereferenced.
/// </summary>
[MethodImpl(MethodImplOptions.AggressiveInlining)]
+ [EditorBrowsable(EditorBrowsableState.Never)]
public ref T DangerousGetPinnableReference()
{
if (_pinnable == null)
diff --git a/src/System.Memory/src/System/Span.cs b/src/System.Memory/src/System/Span.cs
index 75cefe2e4b..991d0a02e5 100644
--- a/src/System.Memory/src/System/Span.cs
+++ b/src/System.Memory/src/System/Span.cs
@@ -22,7 +22,7 @@ namespace System
/// </summary>
[DebuggerTypeProxy(typeof(SpanDebugView<>))]
[DebuggerDisplay("Length = {Length}")]
- public struct Span<T>
+ public readonly ref struct Span<T>
{
/// <summary>
/// Creates a new span over the entirety of the target array.
@@ -109,6 +109,7 @@ namespace System
/// <param name="objectData">A reference to data within that object.</param>
/// <param name="length">The number of <typeparamref name="T"/> elements the memory contains.</param>
[MethodImpl(MethodImplOptions.AggressiveInlining)]
+ [EditorBrowsable(EditorBrowsableState.Never)]
public static Span<T> DangerousCreate(object obj, ref T objectData, int length)
{
Pinnable<T> pinnable = Unsafe.As<Pinnable<T>>(obj);
@@ -426,6 +427,7 @@ namespace System
/// would have been stored. Such a reference can be used for pinning but must never be dereferenced.
/// </summary>
[MethodImpl(MethodImplOptions.AggressiveInlining)]
+ [EditorBrowsable(EditorBrowsableState.Never)]
public ref T DangerousGetPinnableReference()
{
if (_pinnable == null)
diff --git a/src/System.Memory/src/System/SpanExtensions.Fast.cs b/src/System.Memory/src/System/SpanExtensions.Fast.cs
index 1795296373..364427b7a8 100644
--- a/src/System.Memory/src/System/SpanExtensions.Fast.cs
+++ b/src/System.Memory/src/System/SpanExtensions.Fast.cs
@@ -45,7 +45,7 @@ namespace System
/// </summary>
/// <param name="text">The target string.</param>
/// <exception cref="System.ArgumentNullException">Thrown when <paramref name="text"/> is null.</exception>
- public static ReadOnlySpan<char> AsReadOnlySpan(this string text) => Span.AsSpan(text);
+ public static ReadOnlySpan<char> AsReadOnlySpan(this string text) => Span.AsReadOnlySpan(text);
/// <summary>
/// Casts a Span of one primitive type <typeparamref name="TFrom"/> to another primitive type <typeparamref name="TTo"/>.
diff --git a/src/System.Memory/src/System/SpanHelpers.byte.cs b/src/System.Memory/src/System/SpanHelpers.byte.cs
index 29fbca8274..ba0e8b990d 100644
--- a/src/System.Memory/src/System/SpanHelpers.byte.cs
+++ b/src/System.Memory/src/System/SpanHelpers.byte.cs
@@ -5,7 +5,7 @@
using System.Diagnostics;
using System.Runtime.CompilerServices;
-#if !netstandard10
+#if !netstandard11
using System.Numerics;
#endif
@@ -75,7 +75,7 @@ namespace System
uint uValue = value; // Use uint for comparisons to avoid unnecessary 8->32 extensions
IntPtr index = (IntPtr)0; // Use UIntPtr for arithmetic to avoid unnecessary 64->32->64 truncations
IntPtr nLength = (IntPtr)(uint)length;
-#if !netstandard10
+#if !netstandard11
if (Vector.IsHardwareAccelerated && length >= Vector<byte>.Count * 2)
{
unchecked
@@ -135,7 +135,7 @@ namespace System
index += 1;
}
-#if !netstandard10
+#if !netstandard11
if (Vector.IsHardwareAccelerated && ((int)(byte*)index < length))
{
nLength = (IntPtr)(uint)((length - (uint)index) & ~(Vector<byte>.Count - 1));
@@ -190,7 +190,7 @@ namespace System
uint uValue1 = value1; // Use uint for comparisons to avoid unnecessary 8->32 extensions
IntPtr index = (IntPtr)0; // Use UIntPtr for arithmetic to avoid unnecessary 64->32->64 truncations
IntPtr nLength = (IntPtr)(uint)length;
-#if !netstandard10
+#if !netstandard11
if (Vector.IsHardwareAccelerated && length >= Vector<byte>.Count * 2)
{
unchecked
@@ -264,7 +264,7 @@ namespace System
index += 1;
}
-#if !netstandard10
+#if !netstandard11
if (Vector.IsHardwareAccelerated && ((int)(byte*)index < length))
{
nLength = (IntPtr)(uint)((length - (uint)index) & ~(Vector<byte>.Count - 1));
@@ -325,7 +325,7 @@ namespace System
uint uValue2 = value2; // Use uint for comparisons to avoid unnecessary 8->32 extensions
IntPtr index = (IntPtr)0; // Use UIntPtr for arithmetic to avoid unnecessary 64->32->64 truncations
IntPtr nLength = (IntPtr)(uint)length;
-#if !netstandard10
+#if !netstandard11
if (Vector.IsHardwareAccelerated && length >= Vector<byte>.Count * 2)
{
unchecked
@@ -399,7 +399,7 @@ namespace System
index += 1;
}
-#if !netstandard10
+#if !netstandard11
if (Vector.IsHardwareAccelerated && ((int)(byte*)index < length))
{
nLength = (IntPtr)(uint)((length - (uint)index) & ~(Vector<byte>.Count - 1));
@@ -465,7 +465,7 @@ namespace System
IntPtr i = (IntPtr)0; // Use IntPtr and byte* for arithmetic to avoid unnecessary 64->32->64 truncations
IntPtr n = (IntPtr)length;
-#if !netstandard10
+#if !netstandard11
if (Vector.IsHardwareAccelerated && (byte*)n >= (byte*)Vector<byte>.Count)
{
n -= Vector<byte>.Count;
@@ -513,7 +513,7 @@ namespace System
return false;
}
-#if !netstandard10
+#if !netstandard11
// Vector sub-search adapted from https://github.com/aspnet/KestrelHttpServer/pull/1138
[MethodImpl(MethodImplOptions.AggressiveInlining)]
private static int LocateFirstFoundByte(Vector<byte> match)
@@ -536,7 +536,7 @@ namespace System
}
#endif
-#if !netstandard10
+#if !netstandard11
[MethodImpl(MethodImplOptions.AggressiveInlining)]
private static int LocateFirstFoundByte(ulong match)
{
@@ -545,12 +545,12 @@ namespace System
// Flag least significant power of two bit
var powerOfTwoFlag = match ^ (match - 1);
// Shift all powers of two into the high byte and extract
- return (int)((powerOfTwoFlag * xorPowerOfTwoToHighByte) >> 57);
+ return (int)((powerOfTwoFlag * XorPowerOfTwoToHighByte) >> 57);
}
}
#endif
-#if !netstandard10
+#if !netstandard11
[MethodImpl(MethodImplOptions.AggressiveInlining)]
private static Vector<byte> GetVector(byte vectorByte)
{
@@ -565,9 +565,9 @@ namespace System
}
#endif
-#if !netstandard10
- private const ulong xorPowerOfTwoToHighByte = (0x07ul |
- 0x06ul << 8 |
+#if !netstandard11
+ private const ulong XorPowerOfTwoToHighByte = (0x07ul |
+ 0x06ul << 8 |
0x05ul << 16 |
0x04ul << 24 |
0x03ul << 32 |
diff --git a/src/System.Memory/src/System/ThrowHelper.cs b/src/System.Memory/src/System/ThrowHelper.cs
index c783993517..2fd6c9c8cf 100644
--- a/src/System.Memory/src/System/ThrowHelper.cs
+++ b/src/System.Memory/src/System/ThrowHelper.cs
@@ -46,6 +46,14 @@ namespace System
internal static void ThrowArgumentOutOfRangeException(ExceptionArgument argument) { throw CreateArgumentOutOfRangeException(argument); }
[MethodImpl(MethodImplOptions.NoInlining)]
private static Exception CreateArgumentOutOfRangeException(ExceptionArgument argument) { return new ArgumentOutOfRangeException(argument.ToString()); }
+
+ internal static void ThrowInvalidOperationException_OutstandingReferences() { throw CreateInvalidOperationException_OutstandingReferences(); }
+ [MethodImpl(MethodImplOptions.NoInlining)]
+ private static Exception CreateInvalidOperationException_OutstandingReferences() { return new InvalidOperationException(SR.OutstandingReferences); }
+
+ internal static void ThrowObjectDisposedException_MemoryDisposed(string objectName) { throw CreateObjectDisposedException_MemoryDisposed(objectName); }
+ [MethodImpl(MethodImplOptions.NoInlining)]
+ private static Exception CreateObjectDisposedException_MemoryDisposed(string objectName) { return new ObjectDisposedException(objectName, SR.MemoryDisposed); }
}
#if !MONO
internal enum ExceptionArgument
@@ -55,6 +63,7 @@ namespace System
start,
text,
obj,
+ ownedMemory
}
#endif
}
diff --git a/src/System.Memory/tests/Configurations.props b/src/System.Memory/tests/Configurations.props
index 3efbed0bcd..78953dfc88 100644
--- a/src/System.Memory/tests/Configurations.props
+++ b/src/System.Memory/tests/Configurations.props
@@ -2,8 +2,7 @@
<Project ToolsVersion="14.0" DefaultTargets="Build" xmlns="http://schemas.microsoft.com/developer/msbuild/2003">
<PropertyGroup>
<BuildConfigurations>
- netcoreapp;
- netfx;
+ netstandard;
</BuildConfigurations>
</PropertyGroup>
</Project>
diff --git a/src/System.Memory/tests/Memory/CtorArray.cs b/src/System.Memory/tests/Memory/CtorArray.cs
new file mode 100644
index 0000000000..d5b153768f
--- /dev/null
+++ b/src/System.Memory/tests/Memory/CtorArray.cs
@@ -0,0 +1,104 @@
+// 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.MemoryTests
+{
+ //
+ // Tests for Memory<T>.ctor(T[])
+ //
+ // These tests will also exercise the matching codepaths in Memory<T>.ctor(T[], int, int). This makes it easier to ensure
+ // that these parallel tests stay consistent, and avoid excess repetition in the files devoted to those specific overloads.
+ //
+ public static partial class MemoryTests
+ {
+ [Fact]
+ public static void CtorArrayInt()
+ {
+ int[] a = { 91, 92, -93, 94 };
+ Memory<int> memory;
+
+ memory = new Memory<int>(a);
+ memory.Validate(91, 92, -93, 94);
+
+ memory = new Memory<int>(a, 0, a.Length);
+ memory.Validate(91, 92, -93, 94);
+ }
+
+ [Fact]
+ public static void CtorArrayLong()
+ {
+ long[] a = { 91, -92, 93, 94, -95 };
+ Memory<long> memory;
+
+ memory = new Memory<long>(a);
+ memory.Validate(91, -92, 93, 94, -95);
+
+ memory = new Memory<long>(a, 0, a.Length);
+ memory.Validate(91, -92, 93, 94, -95);
+ }
+
+ [Fact]
+ public static void CtorArrayObject()
+ {
+ object o1 = new object();
+ object o2 = new object();
+ object[] a = { o1, o2 };
+ Memory<object> memory;
+
+ memory = new Memory<object>(a);
+ memory.ValidateReferenceType(o1, o2);
+
+ memory = new Memory<object>(a, 0, a.Length);
+ memory.ValidateReferenceType(o1, o2);
+ }
+
+ [Fact]
+ public static void CtorArrayZeroLength()
+ {
+ int[] empty = Array.Empty<int>();
+ Memory<int> memory;
+
+ memory = new Memory<int>(empty);
+ memory.Validate();
+
+ memory = new Memory<int>(empty, 0, empty.Length);
+ memory.Validate();
+ }
+
+ [Fact]
+ public static void CtorArrayNullArray()
+ {
+ Assert.Throws<ArgumentNullException>(() => new Memory<int>(null));
+ Assert.Throws<ArgumentNullException>(() => new Memory<int>(null, 0, 0));
+ }
+
+ [Fact]
+ public static void CtorArrayWrongArrayType()
+ {
+ // Cannot pass variant array, if array type is not a valuetype.
+ string[] a = { "Hello" };
+ Assert.Throws<ArrayTypeMismatchException>(() => new Memory<object>(a));
+ Assert.Throws<ArrayTypeMismatchException>(() => new Memory<object>(a, 0, a.Length));
+ }
+
+ [Fact]
+ public static void CtorArrayWrongValueType()
+ {
+ // Can pass variant array, if array type is a valuetype.
+
+ uint[] a = { 42u, 0xffffffffu };
+ int[] aAsIntArray = (int[])(object)a;
+ Memory<int> memory;
+
+ memory = new Memory<int>(aAsIntArray);
+ memory.Validate(42, -1);
+
+ memory = new Memory<int>(aAsIntArray, 0, aAsIntArray.Length);
+ memory.Validate(42, -1);
+ }
+ }
+}
+
diff --git a/src/System.Memory/tests/Memory/CtorArrayIntInt.cs b/src/System.Memory/tests/Memory/CtorArrayIntInt.cs
new file mode 100644
index 0000000000..251fbf2551
--- /dev/null
+++ b/src/System.Memory/tests/Memory/CtorArrayIntInt.cs
@@ -0,0 +1,80 @@
+// 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.MemoryTests
+{
+ //
+ // Tests for MemoryTests<T>.ctor(T[], int, int). If the test is not specific to this overload, consider putting it in CtorArray.cs instread.
+ //
+ public static partial class MemoryTests
+ {
+ [Fact]
+ public static void CtorArrayWithStartAndLengthInt()
+ {
+ int[] a = { 90, 91, 92, 93, 94, 95, 96, 97, 98 };
+ var memory = new Memory<int>(a, 3, 2);
+ memory.Validate(93, 94);
+ }
+
+ [Fact]
+ public static void CtorArrayWithStartAndLengthLong()
+ {
+ long[] a = { 90, 91, 92, 93, 94, 95, 96, 97, 98 };
+ var memory = new Memory<long>(a, 4, 3);
+ memory.Validate(94, 95, 96);
+ }
+
+ [Fact]
+ public static void CtorArrayWithStartAndLengthRangeExtendsToEndOfArray()
+ {
+ long[] a = { 90, 91, 92, 93, 94, 95, 96, 97, 98 };
+ var memory = new Memory<long>(a, 4, 5);
+ memory.Validate(94, 95, 96, 97, 98);
+ }
+
+ [Fact]
+ public static void CtorArrayWithNegativeStartAndLength()
+ {
+ int[] a = new int[3];
+ Assert.Throws<ArgumentOutOfRangeException>(() => new Memory<int>(a, -1, 0));
+ }
+
+ [Fact]
+ public static void CtorArrayWithStartTooLargeAndLength()
+ {
+ int[] a = new int[3];
+ Assert.Throws<ArgumentOutOfRangeException>(() => new Memory<int>(a, 4, 0));
+ }
+
+ [Fact]
+ public static void CtorArrayWithStartAndNegativeLength()
+ {
+ int[] a = new int[3];
+ Assert.Throws<ArgumentOutOfRangeException>(() => new Memory<int>(a, 0, -1));
+ }
+
+ [Fact]
+ public static void CtorArrayWithStartAndLengthTooLarge()
+ {
+ int[] a = new int[3];
+ Assert.Throws<ArgumentOutOfRangeException>(() => new Memory<int>(a, 3, 1));
+ Assert.Throws<ArgumentOutOfRangeException>(() => new Memory<int>(a, 2, 2));
+ Assert.Throws<ArgumentOutOfRangeException>(() => new Memory<int>(a, 1, 3));
+ Assert.Throws<ArgumentOutOfRangeException>(() => new Memory<int>(a, 0, 4));
+ Assert.Throws<ArgumentOutOfRangeException>(() => new Memory<int>(a, int.MaxValue, int.MaxValue));
+ }
+
+ [Fact]
+ public static void CtorArrayWithStartAndLengthBothEqual()
+ {
+ // Valid for start to equal the array length. This returns an empty memory that starts "just past the array."
+ int[] a = { 91, 92, 93 };
+ var memory = new Memory<int>(a, 3, 0);
+ memory.Validate();
+ }
+ }
+}
+
diff --git a/src/System.Memory/tests/Memory/CustomMemoryForTest.cs b/src/System.Memory/tests/Memory/CustomMemoryForTest.cs
new file mode 100644
index 0000000000..ae23459eac
--- /dev/null
+++ b/src/System.Memory/tests/Memory/CustomMemoryForTest.cs
@@ -0,0 +1,97 @@
+// 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.Buffers;
+using System.Runtime.InteropServices;
+using System.Threading;
+
+namespace System.MemoryTests
+{
+ public class CustomMemoryForTest<T> : OwnedMemory<T>
+ {
+ private bool _disposed;
+ private int _referenceCount;
+ private int _noReferencesCalledCount;
+ private T[] _array;
+
+ public CustomMemoryForTest(T[] array)
+ {
+ _array = array;
+ }
+
+ public int OnNoRefencesCalledCount => _noReferencesCalledCount;
+
+ public override int Length => _array.Length;
+
+ public override bool IsDisposed => _disposed;
+
+ protected override bool IsRetained => _referenceCount > 0;
+
+ public override Span<T> Span
+ {
+ get
+ {
+ if (IsDisposed)
+ throw new ObjectDisposedException(nameof(CustomMemoryForTest<T>));
+ return new Span<T>(_array, 0, _array.Length);
+ }
+ }
+
+ public override MemoryHandle Pin()
+ {
+ unsafe
+ {
+ Retain();
+ var handle = GCHandle.Alloc(_array, GCHandleType.Pinned);
+ return new MemoryHandle(this, (void*)handle.AddrOfPinnedObject(), handle);
+ }
+ }
+
+ protected override bool TryGetArray(out ArraySegment<T> arraySegment)
+ {
+ if (IsDisposed)
+ throw new ObjectDisposedException(nameof(CustomMemoryForTest<T>));
+ arraySegment = new ArraySegment<T>(_array);
+ return true;
+ }
+
+ protected override void Dispose(bool disposing)
+ {
+ if (_disposed)
+ return;
+
+ if (disposing)
+ {
+ _array = null;
+ }
+
+ _disposed = true;
+
+ }
+
+ public override void Retain()
+ {
+ if (IsDisposed)
+ throw new ObjectDisposedException(nameof(CustomMemoryForTest<T>));
+ Interlocked.Increment(ref _referenceCount);
+ }
+
+ public override bool Release()
+ {
+ int newRefCount = Interlocked.Decrement(ref _referenceCount);
+
+ if (newRefCount < 0)
+ throw new InvalidOperationException();
+
+ if (newRefCount == 0)
+ {
+ _noReferencesCalledCount++;
+ return false;
+ }
+ return true;
+ }
+ }
+}
+
diff --git a/src/System.Memory/tests/Memory/Empty.cs b/src/System.Memory/tests/Memory/Empty.cs
new file mode 100644
index 0000000000..73738f76a4
--- /dev/null
+++ b/src/System.Memory/tests/Memory/Empty.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 Xunit;
+
+namespace System.MemoryTests
+{
+ public static partial class MemoryTests
+ {
+ [Fact]
+ public static void Empty()
+ {
+ Memory<int> empty = Memory<int>.Empty;
+ Assert.True(empty.IsEmpty);
+ Assert.Equal(0, empty.Length);
+ }
+
+ [Fact]
+ public static void IsEmpty()
+ {
+ Memory<int> empty = new int[0];
+ Assert.True(empty.IsEmpty);
+ Assert.Equal(0, empty.Length);
+ }
+ }
+}
diff --git a/src/System.Memory/tests/Memory/Equality.cs b/src/System.Memory/tests/Memory/Equality.cs
new file mode 100644
index 0000000000..f81068b5bf
--- /dev/null
+++ b/src/System.Memory/tests/Memory/Equality.cs
@@ -0,0 +1,245 @@
+// 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.Linq;
+using Xunit;
+
+#pragma warning disable 1718 //Comparison made to same variable; did you mean to compare something else?
+
+namespace System.MemoryTests
+{
+ public static partial class MemoryTests
+ {
+ [Fact]
+ public static void EqualityTrue()
+ {
+ int[] a = { 91, 92, 93, 94, 95 };
+ var left = new Memory<int>(a, 2, 3);
+ var right = new Memory<int>(a, 2, 3);
+
+ Assert.True(left.Equals(right));
+ Assert.True(right.Equals(left));
+ }
+
+ [Fact]
+ public static void EqualityReflexivity()
+ {
+ int[] a = { 91, 92, 93, 94, 95 };
+ var left = new Memory<int>(a, 2, 3);
+
+ Assert.True(left.Equals(left));
+ }
+
+ [Fact]
+ public static void EqualityIncludesLength()
+ {
+ int[] a = { 91, 92, 93, 94, 95 };
+ var left = new Memory<int>(a, 2, 1);
+ var right = new Memory<int>(a, 2, 3);
+
+ Assert.False(left.Equals(right));
+ Assert.False(right.Equals(left));
+ }
+
+ [Fact]
+ public static void EqualityIncludesBase()
+ {
+ int[] a = { 91, 92, 93, 94, 95 };
+ var left = new Memory<int>(a, 1, 3);
+ var right = new Memory<int>(a, 2, 3);
+
+ Assert.False(left.Equals(right));
+ Assert.False(right.Equals(left));
+ }
+
+ [Fact]
+ public static void EqualityComparesRangeNotContent()
+ {
+ var left = new Memory<int>(new int[] { 0, 1, 2 }, 1, 1);
+ var right = new Memory<int>(new int[] { 0, 1, 2 }, 1, 1);
+
+ Assert.False(left.Equals(right));
+ Assert.False(right.Equals(left));
+ }
+
+ [Fact]
+ public static void EmptyMemoryNotUnified()
+ {
+ var left = new Memory<int>(new int[0]);
+ var right = new Memory<int>(new int[0]);
+
+ Memory<int> memoryFromNonEmptyArrayButWithZeroLength = new Memory<int>(new int[1] { 123 }).Slice(0, 0);
+
+ Assert.False(left.Equals(right));
+ Assert.False(right.Equals(left));
+
+ Assert.False(memoryFromNonEmptyArrayButWithZeroLength.Equals(left));
+ Assert.False(left.Equals(memoryFromNonEmptyArrayButWithZeroLength));
+
+ // Empty property is equal
+ left = Memory<int>.Empty;
+ right = Memory<int>.Empty;
+
+ Assert.True(left.Equals(right));
+ Assert.True(right.Equals(left));
+ }
+
+ [Fact]
+ public static void MemoryCanBeBoxed()
+ {
+ Memory<byte> memory = Memory<byte>.Empty;
+ object memoryAsObject = memory;
+ Assert.True(memory.Equals(memoryAsObject));
+
+ ReadOnlyMemory<byte> readOnlyMemory = ReadOnlyMemory<byte>.Empty;
+ object readOnlyMemoryAsObject = readOnlyMemory;
+ Assert.True(readOnlyMemory.Equals(readOnlyMemoryAsObject));
+
+ Assert.False(memory.Equals(new object()));
+ Assert.False(readOnlyMemory.Equals(new object()));
+
+ Assert.False(memory.Equals((object)(new Memory<byte>(new byte[] { 1, 2 }))));
+ Assert.False(readOnlyMemory.Equals((object)(new ReadOnlyMemory<byte>(new byte[] { 1, 2 }))));
+
+ Assert.True(memory.Equals(readOnlyMemoryAsObject));
+ Assert.True(readOnlyMemory.Equals(memoryAsObject));
+ }
+
+
+ [Theory]
+ [MemberData(nameof(ValidArraySegments))]
+ public static void MemoryReferencingSameMemoryAreEqualInEveryAspect(byte[] bytes, int start, int length)
+ {
+ var memory = new Memory<byte>(bytes, start, length);
+ var pointingToSameMemory = new Memory<byte>(bytes, start, length);
+ Memory<byte> structCopy = memory;
+
+ Assert.True(memory.Equals(pointingToSameMemory));
+ Assert.True(pointingToSameMemory.Equals(memory));
+
+ Assert.True(memory.Equals(structCopy));
+ Assert.True(structCopy.Equals(memory));
+ }
+
+ [Theory]
+ [MemberData(nameof(FullArraySegments))]
+ public static void MemoryArrayEquivalenceAndImplicitCastsAreEqual(byte[] bytes)
+ {
+ var memory = new Memory<byte>(bytes);
+ var readOnlyMemory = new ReadOnlyMemory<byte>(bytes);
+ ReadOnlyMemory<byte> implicitReadOnlyMemory = memory;
+ Memory<byte> implicitMemoryArray = bytes;
+ ReadOnlyMemory<byte> implicitReadOnlyMemoryArray = bytes;
+
+ Assert.True(memory.Equals(bytes));
+ Assert.True(readOnlyMemory.Equals(bytes));
+ Assert.True(implicitReadOnlyMemory.Equals(bytes));
+ Assert.True(implicitMemoryArray.Equals(bytes));
+ Assert.True(implicitReadOnlyMemoryArray.Equals(bytes));
+
+ Assert.True(readOnlyMemory.Equals(memory));
+ Assert.True(implicitReadOnlyMemory.Equals(memory));
+ Assert.True(implicitMemoryArray.Equals(memory));
+ Assert.True(implicitReadOnlyMemoryArray.Equals(memory));
+
+ Assert.True(memory.Equals(readOnlyMemory));
+ Assert.True(implicitReadOnlyMemory.Equals(readOnlyMemory));
+ Assert.True(implicitMemoryArray.Equals(readOnlyMemory));
+ Assert.True(implicitReadOnlyMemoryArray.Equals(readOnlyMemory));
+
+ Assert.True(memory.Equals(implicitMemoryArray));
+ Assert.True(readOnlyMemory.Equals(implicitMemoryArray));
+ Assert.True(implicitReadOnlyMemory.Equals(implicitMemoryArray));
+ Assert.True(implicitReadOnlyMemoryArray.Equals(implicitMemoryArray));
+
+ Assert.True(memory.Equals(implicitReadOnlyMemory));
+ Assert.True(readOnlyMemory.Equals(implicitReadOnlyMemory));
+ Assert.True(implicitMemoryArray.Equals(implicitReadOnlyMemory));
+ Assert.True(implicitReadOnlyMemoryArray.Equals(implicitReadOnlyMemory));
+
+ Assert.True(memory.Equals(implicitReadOnlyMemoryArray));
+ Assert.True(readOnlyMemory.Equals(implicitReadOnlyMemoryArray));
+ Assert.True(implicitReadOnlyMemory.Equals(implicitReadOnlyMemoryArray));
+ Assert.True(implicitMemoryArray.Equals(implicitReadOnlyMemoryArray));
+ }
+
+ [Theory]
+ [MemberData(nameof(ValidArraySegments))]
+ public static void RangedMemoryEquivalenceAndImplicitCastsAreEqual(byte[] bytes, int start, int length)
+ {
+ var memory = new Memory<byte>(bytes, start, length);
+ var readOnlyMemory = new ReadOnlyMemory<byte>(bytes, start, length);
+ ReadOnlyMemory<byte> implicitReadOnlyMemory = memory;
+
+ Assert.True(readOnlyMemory.Equals(memory));
+ Assert.True(implicitReadOnlyMemory.Equals(memory));
+
+ Assert.True(memory.Equals(readOnlyMemory));
+ Assert.True(implicitReadOnlyMemory.Equals(readOnlyMemory));
+
+ Assert.True(memory.Equals(implicitReadOnlyMemory));
+ Assert.True(readOnlyMemory.Equals(implicitReadOnlyMemory));
+ }
+
+ [Theory]
+ [MemberData(nameof(ValidArraySegments))]
+ public static void MemoryOfEqualValuesAreNotEqual(byte[] bytes, int start, int length)
+ {
+ byte[] bytesCopy = bytes.ToArray();
+
+ var memory = new Memory<byte>(bytes, start, length);
+ var ofSameValues = new Memory<byte>(bytesCopy, start, length);
+
+ Assert.False(memory.Equals(ofSameValues));
+ Assert.False(ofSameValues.Equals(memory));
+ }
+
+ [Theory]
+ [MemberData(nameof(ValidArraySegments))]
+ public static void MemoryOfDifferentValuesAreNotEqual(byte[] bytes, int start, int length)
+ {
+ byte[] differentBytes = bytes.Select(value => ++value).ToArray();
+
+ var memory = new Memory<byte>(bytes, start, length);
+ var ofDifferentValues = new Memory<byte>(differentBytes, start, length);
+
+ Assert.False(memory.Equals(ofDifferentValues));
+ Assert.False(ofDifferentValues.Equals(memory));
+ }
+
+ public static IEnumerable<object[]> ValidArraySegments
+ {
+ get
+ {
+ return new List<object[]>
+ {
+ new object[] { new byte[1] { 0 }, 0, 1},
+ new object[] { new byte[2] { 0, 0 }, 0, 2},
+ new object[] { new byte[2] { 0, 0 }, 0, 1},
+ new object[] { new byte[2] { 0, 0 }, 1, 1},
+ new object[] { new byte[3] { 0, 0, 0 }, 0, 3},
+ new object[] { new byte[3] { 0, 0, 0 }, 0, 2},
+ new object[] { new byte[3] { 0, 0, 0 }, 1, 2},
+ new object[] { new byte[3] { 0, 0, 0 }, 1, 1},
+ new object[] { Enumerable.Range(0, 100000).Select(i => (byte)i).ToArray(), 0, 100000 }
+ };
+ }
+ }
+
+ public static IEnumerable<object[]> FullArraySegments
+ {
+ get
+ {
+ return new List<object[]>
+ {
+ new object[] { new byte[1] { 0 } },
+ new object[] { new byte[2] { 0, 0 } },
+ new object[] { new byte[3] { 0, 0, 0 } },
+ new object[] { Enumerable.Range(0, 100000).Select(i => (byte)i).ToArray() }
+ };
+ }
+ }
+ }
+}
diff --git a/src/System.Memory/tests/Memory/GetHashCode.cs b/src/System.Memory/tests/Memory/GetHashCode.cs
new file mode 100644
index 0000000000..e4a4c2bac0
--- /dev/null
+++ b/src/System.Memory/tests/Memory/GetHashCode.cs
@@ -0,0 +1,89 @@
+// 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.MemoryTests
+{
+ public static partial class MemoryTests
+ {
+ [Fact]
+ public static void SameObjectsHaveSameHashCodes()
+ {
+ int[] a = { 91, 92, 93, 94, 95 };
+ var left = new Memory<int>(a, 2, 3);
+ var right = new Memory<int>(a, 2, 3);
+
+ int[] b = { 1, 2, 3, 4, 5 };
+ var different = new Memory<int>(b, 2, 3);
+
+ Assert.Equal(left.GetHashCode(), right.GetHashCode());
+ Assert.NotEqual(left.GetHashCode(), different.GetHashCode());
+ }
+
+ [Fact]
+ public static void HashCodeIncludesLength()
+ {
+ int[] a = { 91, 92, 93, 94, 95 };
+ var left = new Memory<int>(a, 2, 1);
+ var right = new Memory<int>(a, 2, 3);
+
+ Assert.NotEqual(left.GetHashCode(), right.GetHashCode());
+ }
+
+ [Fact]
+ public static void HashCodeIncludesBase()
+ {
+ int[] a = { 91, 92, 93, 94, 95 };
+ var left = new Memory<int>(a, 1, 3);
+ var right = new Memory<int>(a, 2, 3);
+
+ Assert.NotEqual(left.GetHashCode(), right.GetHashCode());
+ }
+
+ [Fact]
+ public static void HashCodesDifferentForSameContent()
+ {
+ var left = new Memory<int>(new int[] { 0, 1, 2 }, 1, 1);
+ var right = new Memory<int>(new int[] { 0, 1, 2 }, 1, 1);
+
+ Assert.NotEqual(left.GetHashCode(), right.GetHashCode());
+ }
+
+ [Fact]
+ public static void EmptyMemoryHashCodeNotUnified()
+ {
+ var left = new Memory<int>(new int[0]);
+ var right = new Memory<int>(new int[0]);
+
+ Memory<int> memoryFromNonEmptyArrayButWithZeroLength = new Memory<int>(new int[1] { 123 }).Slice(0, 0);
+
+ Assert.NotEqual(left.GetHashCode(), right.GetHashCode());
+ Assert.NotEqual(left.GetHashCode(), memoryFromNonEmptyArrayButWithZeroLength.GetHashCode());
+ Assert.NotEqual(right.GetHashCode(), memoryFromNonEmptyArrayButWithZeroLength.GetHashCode());
+
+ // Empty property hashcode is equal
+ left = Memory<int>.Empty;
+ right = Memory<int>.Empty;
+
+ Assert.Equal(left.GetHashCode(), right.GetHashCode());
+ }
+
+ [Fact]
+ public static void HashCodesForImplicitCastsAreEqual()
+ {
+ byte[] bytes = new byte[10];
+ var memory = new Memory<byte>(bytes);
+ var readOnlyMemory = new ReadOnlyMemory<byte>(bytes);
+ ReadOnlyMemory<byte> implicitReadOnlyMemory = memory;
+ Memory<byte> implicitMemoryArray = bytes;
+ ReadOnlyMemory<byte> implicitReadOnlyMemoryArray = bytes;
+
+ Assert.Equal(readOnlyMemory.GetHashCode(), memory.GetHashCode());
+ Assert.Equal(implicitReadOnlyMemory.GetHashCode(), memory.GetHashCode());
+ Assert.Equal(implicitMemoryArray.GetHashCode(), memory.GetHashCode());
+ Assert.Equal(implicitReadOnlyMemoryArray.GetHashCode(), memory.GetHashCode());
+ }
+ }
+}
diff --git a/src/System.Memory/tests/Memory/ImplicitConversion.cs b/src/System.Memory/tests/Memory/ImplicitConversion.cs
new file mode 100644
index 0000000000..75a545167d
--- /dev/null
+++ b/src/System.Memory/tests/Memory/ImplicitConversion.cs
@@ -0,0 +1,120 @@
+// 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.MemoryTests
+{
+ public static partial class MemoryTests
+ {
+ [Fact]
+ public static void CtorImplicitArray()
+ {
+ int[] intArray = { 19, -17 };
+ Cast(intArray, 19, -17);
+
+ Memory<int> memoryInt = intArray;
+ CastReadOnly(memoryInt, 19, -17);
+
+ long[] longArray = { 1, -3, 7, -15, 31 };
+ Cast<long>(longArray, 1, -3, 7, -15, 31);
+
+ Memory<long> memoryLong = longArray;
+ CastReadOnly<long>(memoryLong, 1, -3, 7, -15, 31);
+
+ object o1 = new object();
+ object o2 = new object();
+ object o3 = new object();
+ object o4 = new object();
+ object[] objectArray = { o1, o2, o3, o4 };
+ CastReference(objectArray, o1, o2, o3, o4);
+
+ Memory<object> memoryObject = objectArray;
+ CastReadOnlyReference(memoryObject, o1, o2, o3, o4);
+ }
+
+ [Fact]
+ public static void CtorImplicitZeroLengthArray()
+ {
+ int[] emptyArray1 = Array.Empty<int>();
+ Cast<int>(emptyArray1);
+
+ Memory<int> memoryEmpty = emptyArray1;
+ CastReadOnly<int>(memoryEmpty);
+
+ int[] emptyArray2 = new int[0];
+ Cast<int>(emptyArray2);
+
+ Memory<int> memoryEmptyInt = emptyArray2;
+ CastReadOnly<int>(memoryEmptyInt);
+ }
+
+ [Fact]
+ public static void CtorImplicitArraySegment()
+ {
+ int[] a = { 19, -17 };
+ ArraySegment<int> segmentInt = new ArraySegment<int>(a, 1, 1);
+ Cast(segmentInt, -17);
+
+ Memory<int> memoryInt = segmentInt;
+ CastReadOnly(memoryInt, -17);
+
+ long[] b = { 1, -3, 7, -15, 31 };
+ ArraySegment<long> segmentLong = new ArraySegment<long>(b, 1, 3);
+ Cast<long>(segmentLong, -3, 7, -15);
+
+ Memory<long> memoryLong = segmentLong;
+ CastReadOnly<long>(memoryLong, -3, 7, -15);
+
+ object o1 = new object();
+ object o2 = new object();
+ object o3 = new object();
+ object o4 = new object();
+ object[] c = { o1, o2, o3, o4 };
+ ArraySegment<object> segmentObject = new ArraySegment<object>(c, 0, 2);
+ CastReference(segmentObject, o1, o2);
+
+ Memory<object> memoryObject = segmentObject;
+ CastReadOnlyReference(memoryObject, o1, o2);
+ }
+
+ [Fact]
+ public static void CtorImplicitZeroLengthArraySegment()
+ {
+ int[] empty = Array.Empty<int>();
+ ArraySegment<int> emptySegment = new ArraySegment<int>(empty);
+ Cast<int>(emptySegment);
+
+ Memory<int> memoryEmpty = emptySegment;
+ CastReadOnly<int>(memoryEmpty);
+
+ int[] a = { 19, -17 };
+ ArraySegment<int> segmentInt = new ArraySegment<int>(a, 1, 0);
+ Cast<int>(segmentInt);
+
+ Memory<int> memoryEmptyInt = segmentInt;
+ CastReadOnly<int>(memoryEmptyInt);
+ }
+
+ private static void Cast<T>(Memory<T> memory, params T[] expected) where T : struct, IEquatable<T>
+ {
+ memory.Validate(expected);
+ }
+
+ private static void CastReference<T>(Memory<T> memory, params T[] expected)
+ {
+ memory.ValidateReferenceType(expected);
+ }
+
+ private static void CastReadOnly<T>(ReadOnlyMemory<T> memory, params T[] expected) where T : struct, IEquatable<T>
+ {
+ memory.Validate(expected);
+ }
+
+ private static void CastReadOnlyReference<T>(ReadOnlyMemory<T> memory, params T[] expected)
+ {
+ memory.ValidateReferenceType(expected);
+ }
+ }
+}
diff --git a/src/System.Memory/tests/Memory/OwnedMemory.cs b/src/System.Memory/tests/Memory/OwnedMemory.cs
new file mode 100644
index 0000000000..cef1264f91
--- /dev/null
+++ b/src/System.Memory/tests/Memory/OwnedMemory.cs
@@ -0,0 +1,96 @@
+// 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.Buffers;
+using Xunit;
+
+namespace System.MemoryTests
+{
+ //
+ // Tests for internal Memory<T>.ctor(OwnedMemory<T>, int , int)
+ //
+ public static partial class MemoryTests
+ {
+ [Fact]
+ public static void MemoryFromOwnedMemoryInt()
+ {
+ int[] a = { 91, 92, -93, 94 };
+ OwnedMemory<int> owner = new CustomMemoryForTest<int>(a);
+ Memory<int> memory = owner.Memory;
+ memory.Validate(91, 92, -93, 94);
+ }
+
+ [Fact]
+ public static void MemoryFromOwnedMemoryLong()
+ {
+ long[] a = { 91, -92, 93, 94, -95 };
+ OwnedMemory<long> owner = new CustomMemoryForTest<long>(a);
+ Memory<long> memory = owner.Memory;
+ memory.Validate(91, -92, 93, 94, -95);
+ }
+
+ [Fact]
+ public static void MemoryFromOwnedMemoryObject()
+ {
+ object o1 = new object();
+ object o2 = new object();
+ object[] a = { o1, o2 };
+ OwnedMemory<object> owner = new CustomMemoryForTest<object>(a);
+ Memory<object> memory = owner.Memory;
+ memory.ValidateReferenceType(o1, o2);
+ }
+
+ [Fact]
+ public static void ImplicitReadOnlyMemoryFromOwnedMemory()
+ {
+ long[] a = { 91, -92, 93, 94, -95 };
+ OwnedMemory<long> owner = new CustomMemoryForTest<long>(a);
+ Memory<long> memory = owner.Memory;
+ CastReadOnly<long>(memory, 91, -92, 93, 94, -95);
+ }
+
+ [Fact]
+ public static void OwnedMemoryDispose()
+ {
+ int[] a = { 91, 92, -93, 94 };
+ OwnedMemory<int> owner = new CustomMemoryForTest<int>(a);
+ Assert.False(owner.IsDisposed);
+ owner.Dispose();
+ Assert.True(owner.IsDisposed);
+ }
+
+ [Fact]
+ public static void MemoryFromOwnedMemoryAfterDispose()
+ {
+ int[] a = { 91, 92, -93, 94 };
+ OwnedMemory<int> owner = new CustomMemoryForTest<int>(a);
+ owner.Dispose();
+ Assert.Throws<ObjectDisposedException>(() => owner.Memory);
+ }
+
+ [Fact]
+ public static void DisposeOwnedMemoryAfterRetain()
+ {
+ int[] a = { 91, 92, -93, 94 };
+ OwnedMemory<int> owner = new CustomMemoryForTest<int>(a);
+ owner.Retain();
+ Assert.Throws<InvalidOperationException>(() => owner.Dispose());
+ owner.Release();
+ }
+
+ [Fact]
+ public static void DisposeOwnedMemoryAfterRetainAndRelease()
+ {
+ int[] a = { 91, 92, -93, 94 };
+ OwnedMemory<int> owner = new CustomMemoryForTest<int>(a);
+ owner.Retain();
+ owner.Release();
+ owner.Dispose();
+ Assert.True(owner.IsDisposed);
+ }
+ }
+
+}
+
diff --git a/src/System.Memory/tests/Memory/Retain.cs b/src/System.Memory/tests/Memory/Retain.cs
new file mode 100644
index 0000000000..d64a9d0a72
--- /dev/null
+++ b/src/System.Memory/tests/Memory/Retain.cs
@@ -0,0 +1,85 @@
+// 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.Buffers;
+using Xunit;
+
+namespace System.MemoryTests
+{
+ public static partial class MemoryTests
+ {
+
+ [Fact]
+ public static void MemoryRetainWithoutPinning()
+ {
+ int[] array = { 1, 2, 3, 4, 5 };
+ Memory<int> memory = array;
+ MemoryHandle handle = memory.Retain();
+ unsafe
+ {
+ int* pointer = (int*)handle.PinnedPointer;
+ Assert.True(pointer == null);
+ }
+ handle.Dispose();
+ }
+
+ [Fact]
+ public static void MemoryRetainWithPinning()
+ {
+ int[] array = { 1, 2, 3, 4, 5 };
+ Memory<int> memory = array;
+ MemoryHandle handle = memory.Retain(pin: true);
+ unsafe
+ {
+ int* pointer = (int*)handle.PinnedPointer;
+ Assert.True(pointer != null);
+
+ GC.Collect();
+
+ for (int i = 0; i < memory.Length; i++)
+ {
+ Assert.Equal(array[i], pointer[i]);
+ }
+ }
+ handle.Dispose();
+ }
+
+ [Fact]
+ public static void OwnedMemoryRetainWithoutPinning()
+ {
+ int[] array = { 1, 2, 3, 4, 5 };
+ OwnedMemory<int> owner = new CustomMemoryForTest<int>(array);
+ Memory<int> memory = owner.Memory;
+ MemoryHandle handle = memory.Retain();
+ unsafe
+ {
+ int* pointer = (int*)handle.PinnedPointer;
+ Assert.True(pointer == null);
+ }
+ handle.Dispose();
+ }
+
+ [Fact]
+ public static void OwnedMemoryRetainWithPinning()
+ {
+ int[] array = { 1, 2, 3, 4, 5 };
+ OwnedMemory<int> owner = new CustomMemoryForTest<int>(array);
+ Memory<int> memory = owner.Memory;
+ MemoryHandle handle = memory.Retain(pin: true);
+ unsafe
+ {
+ int* pointer = (int*)handle.PinnedPointer;
+ Assert.True(pointer != null);
+
+ GC.Collect();
+
+ for (int i = 0; i < memory.Length; i++)
+ {
+ Assert.Equal(array[i], pointer[i]);
+ }
+ }
+ handle.Dispose();
+ }
+ }
+}
diff --git a/src/System.Memory/tests/Memory/Slice.cs b/src/System.Memory/tests/Memory/Slice.cs
new file mode 100644
index 0000000000..70dcdb26e7
--- /dev/null
+++ b/src/System.Memory/tests/Memory/Slice.cs
@@ -0,0 +1,112 @@
+// 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 System.Runtime.CompilerServices;
+using System.Buffers;
+
+namespace System.MemoryTests
+{
+ public static partial class MemoryTests
+ {
+ [Fact]
+ public static void SliceWithStart()
+ {
+ int[] a = { 90, 91, 92, 93, 94, 95, 96, 97, 98, 99 };
+ Memory<int> memory = new Memory<int>(a).Slice(6);
+ Assert.Equal(4, memory.Length);
+ Assert.True(Unsafe.AreSame(ref a[6], ref memory.Span.DangerousGetPinnableReference()));
+
+ OwnedMemory<int> owner = new CustomMemoryForTest<int>(a);
+ Memory<int> memoryFromOwner = owner.Memory.Slice(6);
+
+ Assert.Equal(4, memoryFromOwner.Length);
+ Assert.True(Unsafe.AreSame(ref a[6], ref memoryFromOwner.Span.DangerousGetPinnableReference()));
+ }
+
+ [Fact]
+ public static void SliceWithStartPastEnd()
+ {
+ int[] a = { 90, 91, 92, 93, 94, 95, 96, 97, 98, 99 };
+ Memory<int> memory = new Memory<int>(a).Slice(a.Length);
+ Assert.Equal(0, memory.Length);
+ Assert.True(Unsafe.AreSame(ref a[a.Length - 1], ref Unsafe.Subtract(ref memory.Span.DangerousGetPinnableReference(), 1)));
+
+ OwnedMemory<int> owner = new CustomMemoryForTest<int>(a);
+ Memory<int> memoryFromOwner = owner.Memory.Slice(a.Length);
+
+ Assert.Equal(0, memoryFromOwner.Length);
+ Assert.True(Unsafe.AreSame(ref a[a.Length - 1], ref Unsafe.Subtract(ref memoryFromOwner.Span.DangerousGetPinnableReference(), 1)));
+ }
+
+ [Fact]
+ public static void SliceWithStartAndLength()
+ {
+ int[] a = { 90, 91, 92, 93, 94, 95, 96, 97, 98, 99 };
+ Memory<int> memory = new Memory<int>(a).Slice(3, 5);
+ Assert.Equal(5, memory.Length);
+ Assert.True(Unsafe.AreSame(ref a[3], ref memory.Span.DangerousGetPinnableReference()));
+
+ OwnedMemory<int> owner = new CustomMemoryForTest<int>(a);
+ Memory<int> memoryFromOwner = owner.Memory.Slice(3, 5);
+
+ Assert.Equal(5, memoryFromOwner.Length);
+ Assert.True(Unsafe.AreSame(ref a[3], ref memoryFromOwner.Span.DangerousGetPinnableReference()));
+ }
+
+ [Fact]
+ public static void SliceWithStartAndLengthUpToEnd()
+ {
+ int[] a = { 90, 91, 92, 93, 94, 95, 96, 97, 98, 99 };
+ Memory<int> memory = new Memory<int>(a).Slice(4, 6);
+ Assert.Equal(6, memory.Length);
+ Assert.True(Unsafe.AreSame(ref a[4], ref memory.Span.DangerousGetPinnableReference()));
+
+ OwnedMemory<int> owner = new CustomMemoryForTest<int>(a);
+ Memory<int> memoryFromOwner = owner.Memory.Slice(4, 6);
+
+ Assert.Equal(6, memoryFromOwner.Length);
+ Assert.True(Unsafe.AreSame(ref a[4], ref memoryFromOwner.Span.DangerousGetPinnableReference()));
+ }
+
+ [Fact]
+ public static void SliceWithStartAndLengthPastEnd()
+ {
+ int[] a = { 90, 91, 92, 93, 94, 95, 96, 97, 98, 99 };
+ Memory<int> memory = new Memory<int>(a).Slice(a.Length, 0);
+ Assert.Equal(0, memory.Length);
+ Assert.True(Unsafe.AreSame(ref a[a.Length - 1], ref Unsafe.Subtract(ref memory.Span.DangerousGetPinnableReference(), 1)));
+
+ OwnedMemory<int> owner = new CustomMemoryForTest<int>(a);
+ Memory<int> memoryFromOwner = owner.Memory.Slice(a.Length, 0);
+
+ Assert.Equal(0, memoryFromOwner.Length);
+ Assert.True(Unsafe.AreSame(ref a[a.Length - 1], ref Unsafe.Subtract(ref memoryFromOwner.Span.DangerousGetPinnableReference(), 1)));
+ }
+
+ [Fact]
+ public static void SliceRangeChecks()
+ {
+ int[] a = { 90, 91, 92, 93, 94, 95, 96, 97, 98, 99 };
+ Assert.Throws<ArgumentOutOfRangeException>(() => new Memory<int>(a).Slice(-1));
+ Assert.Throws<ArgumentOutOfRangeException>(() => new Memory<int>(a).Slice(a.Length + 1));
+ Assert.Throws<ArgumentOutOfRangeException>(() => new Memory<int>(a).Slice(-1, 0));
+ Assert.Throws<ArgumentOutOfRangeException>(() => new Memory<int>(a).Slice(0, a.Length + 1));
+ Assert.Throws<ArgumentOutOfRangeException>(() => new Memory<int>(a).Slice(2, a.Length + 1 - 2));
+ Assert.Throws<ArgumentOutOfRangeException>(() => new Memory<int>(a).Slice(a.Length + 1, 0));
+ Assert.Throws<ArgumentOutOfRangeException>(() => new Memory<int>(a).Slice(a.Length, 1));
+
+ OwnedMemory<int> owner = new CustomMemoryForTest<int>(a);
+ Memory<int> memory = owner.Memory;
+
+ Assert.Throws<ArgumentOutOfRangeException>(() => memory.Slice(-1));
+ Assert.Throws<ArgumentOutOfRangeException>(() => memory.Slice(a.Length + 1));
+ Assert.Throws<ArgumentOutOfRangeException>(() => memory.Slice(-1, 0));
+ Assert.Throws<ArgumentOutOfRangeException>(() => memory.Slice(0, a.Length + 1));
+ Assert.Throws<ArgumentOutOfRangeException>(() => memory.Slice(2, a.Length + 1 - 2));
+ Assert.Throws<ArgumentOutOfRangeException>(() => memory.Slice(a.Length + 1, 0));
+ Assert.Throws<ArgumentOutOfRangeException>(() => memory.Slice(a.Length, 1));
+ }
+ }
+}
diff --git a/src/System.Memory/tests/Memory/Span.cs b/src/System.Memory/tests/Memory/Span.cs
new file mode 100644
index 0000000000..ec10646cc5
--- /dev/null
+++ b/src/System.Memory/tests/Memory/Span.cs
@@ -0,0 +1,99 @@
+// 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.Buffers;
+using Xunit;
+
+namespace System.MemoryTests
+{
+ public static partial class MemoryTests
+ {
+ [Fact]
+ public static void SpanFromCtorArrayInt()
+ {
+ int[] a = { 91, 92, -93, 94 };
+ Memory<int> memory;
+
+ memory = new Memory<int>(a);
+ memory.Span.Validate(91, 92, -93, 94);
+
+ memory = new Memory<int>(a, 0, a.Length);
+ memory.Span.Validate(91, 92, -93, 94);
+
+ OwnedMemory<int> owner = new CustomMemoryForTest<int>(a);
+ owner.Memory.Span.Validate(91, 92, -93, 94);
+ }
+
+ [Fact]
+ public static void SpanFromCtorArrayLong()
+ {
+ long[] a = { 91, -92, 93, 94, -95 };
+ Memory<long> memory;
+
+ memory = new Memory<long>(a);
+ memory.Span.Validate(91, -92, 93, 94, -95);
+
+ memory = new Memory<long>(a, 0, a.Length);
+ memory.Span.Validate(91, -92, 93, 94, -95);
+
+ OwnedMemory<long> owner = new CustomMemoryForTest<long>(a);
+ owner.Memory.Span.Validate(91, -92, 93, 94, -95);
+ }
+
+ [ActiveIssue(23952, TargetFrameworkMonikers.UapAot)]
+ [Fact]
+ public static void SpanFromCtorArrayObject()
+ {
+ object o1 = new object();
+ object o2 = new object();
+ object[] a = { o1, o2 };
+ Memory<object> memory;
+
+ memory = new Memory<object>(a);
+ memory.Span.ValidateReferenceType(o1, o2);
+
+ memory = new Memory<object>(a, 0, a.Length);
+ memory.Span.ValidateReferenceType(o1, o2);
+
+ OwnedMemory<object> owner = new CustomMemoryForTest<object>(a);
+ owner.Memory.Span.ValidateReferenceType(o1, o2);
+ }
+
+ [Fact]
+ public static void SpanFromCtorArrayZeroLength()
+ {
+ int[] empty = Array.Empty<int>();
+ Memory<int> memory;
+
+ memory = new Memory<int>(empty);
+ memory.Span.Validate();
+
+ memory = new Memory<int>(empty, 0, empty.Length);
+ memory.Span.Validate();
+
+ OwnedMemory<int> owner = new CustomMemoryForTest<int>(empty);
+ owner.Memory.Span.Validate();
+ }
+
+ [Fact]
+ public static void SpanFromCtorArrayWrongValueType()
+ {
+ // Can pass variant array, if array type is a valuetype.
+
+ uint[] a = { 42u, 0xffffffffu };
+ int[] aAsIntArray = (int[])(object)a;
+ Memory<int> memory;
+
+ memory = new Memory<int>(aAsIntArray);
+ memory.Span.Validate(42, -1);
+
+ memory = new Memory<int>(aAsIntArray, 0, aAsIntArray.Length);
+ memory.Span.Validate(42, -1);
+
+ OwnedMemory<int> owner = new CustomMemoryForTest<int>(aAsIntArray);
+ owner.Memory.Span.Validate(42, -1);
+ }
+
+ }
+}
diff --git a/src/System.Memory/tests/Memory/ToArray.cs b/src/System.Memory/tests/Memory/ToArray.cs
new file mode 100644
index 0000000000..cb796596ff
--- /dev/null
+++ b/src/System.Memory/tests/Memory/ToArray.cs
@@ -0,0 +1,29 @@
+// 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.MemoryTests
+{
+ public static partial class MemoryTests
+ {
+ [Fact]
+ public static void ToArray1()
+ {
+ int[] a = { 91, 92, 93 };
+ var memory = new Memory<int>(a);
+ int[] copy = memory.ToArray();
+ Assert.Equal<int>(a, copy);
+ Assert.NotSame(a, copy);
+ }
+
+ [Fact]
+ public static void ToArrayEmpty()
+ {
+ Memory<int> memory = Memory<int>.Empty;
+ int[] copy = memory.ToArray();
+ Assert.Equal(0, copy.Length);
+ }
+ }
+}
diff --git a/src/System.Memory/tests/Memory/TryGetArray.cs b/src/System.Memory/tests/Memory/TryGetArray.cs
new file mode 100644
index 0000000000..b2cbc098b7
--- /dev/null
+++ b/src/System.Memory/tests/Memory/TryGetArray.cs
@@ -0,0 +1,41 @@
+// 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.Buffers;
+using Xunit;
+
+namespace System.MemoryTests
+{
+ public static partial class MemoryTests
+ {
+ [Fact]
+ public static void MemoryTryGetArray()
+ {
+ int[] array = new int[10];
+ Memory<int> memory = array;
+ Assert.True(memory.TryGetArray(out ArraySegment<int> segment));
+ Assert.Equal(array.Length, segment.Count);
+
+ for (int i = segment.Offset; i < segment.Count + segment.Offset; i++)
+ {
+ Assert.Equal(array[i], segment.Array[i]);
+ }
+ }
+
+ [Fact]
+ public static void OwnedMemoryTryGetArray()
+ {
+ int[] array = new int[10];
+ OwnedMemory<int> owner = new CustomMemoryForTest<int>(array);
+ Memory<int> memory = owner.Memory;
+ Assert.True(memory.TryGetArray(out ArraySegment<int> segment));
+ Assert.Equal(array.Length, segment.Count);
+
+ for (int i = segment.Offset; i < segment.Count + segment.Offset; i++)
+ {
+ Assert.Equal(array[i], segment.Array[i]);
+ }
+ }
+ }
+}
diff --git a/src/System.Memory/tests/ReadOnlyMemory/CtorArray.cs b/src/System.Memory/tests/ReadOnlyMemory/CtorArray.cs
new file mode 100644
index 0000000000..a682942df7
--- /dev/null
+++ b/src/System.Memory/tests/ReadOnlyMemory/CtorArray.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 Xunit;
+using static System.TestHelpers;
+
+namespace System.MemoryTests
+{
+ //
+ // Tests for Memory<T>.ctor(T[])
+ //
+ // These tests will also exercise the matching codepaths in Memory<T>.ctor(T[], int, int). This makes it easier to ensure
+ // that these parallel tests stay consistent, and avoid excess repetition in the files devoted to those specific overloads.
+ //
+ public static partial class ReadOnlyMemoryTests
+ {
+ [Fact]
+ public static void CtorArrayInt()
+ {
+ int[] a = { 91, 92, -93, 94 };
+ ReadOnlyMemory<int> memory;
+
+ memory = new ReadOnlyMemory<int>(a);
+ memory.Validate(91, 92, -93, 94);
+
+ memory = new ReadOnlyMemory<int>(a, 0, a.Length);
+ memory.Validate(91, 92, -93, 94);
+ }
+
+ [Fact]
+ public static void CtorArrayLong()
+ {
+ long[] a = { 91, -92, 93, 94, -95 };
+ ReadOnlyMemory<long> memory;
+
+ memory = new ReadOnlyMemory<long>(a);
+ memory.Validate(91, -92, 93, 94, -95);
+
+ memory = new ReadOnlyMemory<long>(a, 0, a.Length);
+ memory.Validate(91, -92, 93, 94, -95);
+ }
+
+ [ActiveIssue(23952, TargetFrameworkMonikers.UapAot)]
+ [Fact]
+ public static void CtorArrayObject()
+ {
+ object o1 = new object();
+ object o2 = new object();
+ object[] a = { o1, o2 };
+ ReadOnlyMemory<object> memory;
+
+ memory = new ReadOnlyMemory<object>(a);
+ memory.ValidateReferenceType(o1, o2);
+
+ memory = new ReadOnlyMemory<object>(a, 0, a.Length);
+ memory.ValidateReferenceType(o1, o2);
+ }
+
+ [Fact]
+ public static void CtorArrayZeroLength()
+ {
+ int[] empty = Array.Empty<int>();
+ ReadOnlyMemory<int> memory;
+
+ memory = new ReadOnlyMemory<int>(empty);
+ memory.Validate();
+
+ memory = new ReadOnlyMemory<int>(empty, 0, empty.Length);
+ memory.Validate();
+ }
+
+ [Fact]
+ public static void CtorArrayNullArray()
+ {
+ Assert.Throws<ArgumentNullException>(() => new ReadOnlyMemory<int>(null));
+ Assert.Throws<ArgumentNullException>(() => new ReadOnlyMemory<int>(null, 0, 0));
+ }
+
+ [Fact]
+ public static void CtorArrayWrongValueType()
+ {
+ // Can pass variant array, if array type is a valuetype.
+
+ uint[] a = { 42u, 0xffffffffu };
+ int[] aAsIntArray = (int[])(object)a;
+ ReadOnlyMemory<int> memory;
+
+ memory = new ReadOnlyMemory<int>(aAsIntArray);
+ memory.Validate(42, -1);
+
+ memory = new ReadOnlyMemory<int>(aAsIntArray, 0, aAsIntArray.Length);
+ memory.Validate(42, -1);
+ }
+
+ [ActiveIssue(23952, TargetFrameworkMonikers.UapAot)]
+ [Fact]
+ public static void CtorVariantArrayType()
+ {
+ // For ReadOnlyMemory<T>, variant arrays are allowed for string to object
+ // and reference type to object.
+
+ ReadOnlyMemory<object> memory;
+
+ string[] strArray = { "Hello" };
+ memory = new ReadOnlyMemory<object>(strArray);
+ memory.ValidateReferenceType("Hello");
+ memory = new ReadOnlyMemory<object>(strArray, 0, strArray.Length);
+ memory.ValidateReferenceType("Hello");
+
+ TestClass c1 = new TestClass();
+ TestClass c2 = new TestClass();
+ TestClass[] clsArray = { c1, c2 };
+ memory = new ReadOnlyMemory<object>(clsArray);
+ memory.ValidateReferenceType(c1, c2);
+ memory = new ReadOnlyMemory<object>(clsArray, 0, clsArray.Length);
+ memory.ValidateReferenceType(c1, c2);
+ }
+ }
+}
+
diff --git a/src/System.Memory/tests/ReadOnlyMemory/CtorArrayIntInt.cs b/src/System.Memory/tests/ReadOnlyMemory/CtorArrayIntInt.cs
new file mode 100644
index 0000000000..2ca4c20df1
--- /dev/null
+++ b/src/System.Memory/tests/ReadOnlyMemory/CtorArrayIntInt.cs
@@ -0,0 +1,80 @@
+// 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.MemoryTests
+{
+ //
+ // Tests for MemoryTests<T>.ctor(T[], int, int). If the test is not specific to this overload, consider putting it in CtorArray.cs instread.
+ //
+ public static partial class ReadOnlyMemoryTests
+ {
+ [Fact]
+ public static void CtorArrayWithStartAndLengthInt()
+ {
+ int[] a = { 90, 91, 92, 93, 94, 95, 96, 97, 98 };
+ var memory = new ReadOnlyMemory<int>(a, 3, 2);
+ memory.Validate(93, 94);
+ }
+
+ [Fact]
+ public static void CtorArrayWithStartAndLengthLong()
+ {
+ long[] a = { 90, 91, 92, 93, 94, 95, 96, 97, 98 };
+ var memory = new ReadOnlyMemory<long>(a, 4, 3);
+ memory.Validate(94, 95, 96);
+ }
+
+ [Fact]
+ public static void CtorArrayWithStartAndLengthRangeExtendsToEndOfArray()
+ {
+ long[] a = { 90, 91, 92, 93, 94, 95, 96, 97, 98 };
+ var memory = new ReadOnlyMemory<long>(a, 4, 5);
+ memory.Validate(94, 95, 96, 97, 98);
+ }
+
+ [Fact]
+ public static void CtorArrayWithNegativeStartAndLength()
+ {
+ int[] a = new int[3];
+ Assert.Throws<ArgumentOutOfRangeException>(() => new ReadOnlyMemory<int>(a, -1, 0));
+ }
+
+ [Fact]
+ public static void CtorArrayWithStartTooLargeAndLength()
+ {
+ int[] a = new int[3];
+ Assert.Throws<ArgumentOutOfRangeException>(() => new ReadOnlyMemory<int>(a, 4, 0));
+ }
+
+ [Fact]
+ public static void CtorArrayWithStartAndNegativeLength()
+ {
+ int[] a = new int[3];
+ Assert.Throws<ArgumentOutOfRangeException>(() => new ReadOnlyMemory<int>(a, 0, -1));
+ }
+
+ [Fact]
+ public static void CtorArrayWithStartAndLengthTooLarge()
+ {
+ int[] a = new int[3];
+ Assert.Throws<ArgumentOutOfRangeException>(() => new ReadOnlyMemory<int>(a, 3, 1));
+ Assert.Throws<ArgumentOutOfRangeException>(() => new ReadOnlyMemory<int>(a, 2, 2));
+ Assert.Throws<ArgumentOutOfRangeException>(() => new ReadOnlyMemory<int>(a, 1, 3));
+ Assert.Throws<ArgumentOutOfRangeException>(() => new ReadOnlyMemory<int>(a, 0, 4));
+ Assert.Throws<ArgumentOutOfRangeException>(() => new ReadOnlyMemory<int>(a, int.MaxValue, int.MaxValue));
+ }
+
+ [Fact]
+ public static void CtorArrayWithStartAndLengthBothEqual()
+ {
+ // Valid for start to equal the array length. This returns an empty memory that starts "just past the array."
+ int[] a = { 91, 92, 93 };
+ var memory = new ReadOnlyMemory<int>(a, 3, 0);
+ memory.Validate();
+ }
+ }
+}
+
diff --git a/src/System.Memory/tests/ReadOnlyMemory/DangerousTryGetArray.cs b/src/System.Memory/tests/ReadOnlyMemory/DangerousTryGetArray.cs
new file mode 100644
index 0000000000..f6a9c7baf5
--- /dev/null
+++ b/src/System.Memory/tests/ReadOnlyMemory/DangerousTryGetArray.cs
@@ -0,0 +1,41 @@
+// 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.Buffers;
+using Xunit;
+
+namespace System.MemoryTests
+{
+ public static partial class ReadOnlyMemoryTests
+ {
+ [Fact]
+ public static void MemoryDangerousTryGetArray()
+ {
+ int[] array = new int[10];
+ ReadOnlyMemory<int> memory = array;
+ Assert.True(memory.DangerousTryGetArray(out ArraySegment<int> segment));
+ Assert.Equal(array.Length, segment.Count);
+
+ for (int i = segment.Offset; i < segment.Count + segment.Offset; i++)
+ {
+ Assert.Equal(array[i], segment.Array[i]);
+ }
+ }
+
+ [Fact]
+ public static void OwnedMemoryTryGetArray()
+ {
+ int[] array = new int[10];
+ OwnedMemory<int> owner = new CustomMemoryForTest<int>(array);
+ ReadOnlyMemory<int> memory = owner.Memory;
+ Assert.True(memory.DangerousTryGetArray(out ArraySegment<int> segment));
+ Assert.Equal(array.Length, segment.Count);
+
+ for (int i = segment.Offset; i < segment.Count + segment.Offset; i++)
+ {
+ Assert.Equal(array[i], segment.Array[i]);
+ }
+ }
+ }
+}
diff --git a/src/System.Memory/tests/ReadOnlyMemory/Empty.cs b/src/System.Memory/tests/ReadOnlyMemory/Empty.cs
new file mode 100644
index 0000000000..c53b3c6bbc
--- /dev/null
+++ b/src/System.Memory/tests/ReadOnlyMemory/Empty.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 Xunit;
+
+namespace System.MemoryTests
+{
+ public static partial class ReadOnlyMemoryTests
+ {
+ [Fact]
+ public static void Empty()
+ {
+ ReadOnlyMemory<int> empty = ReadOnlyMemory<int>.Empty;
+ Assert.True(empty.IsEmpty);
+ Assert.Equal(0, empty.Length);
+ }
+
+ [Fact]
+ public static void IsEmpty()
+ {
+ ReadOnlyMemory<int> empty = new int[0];
+ Assert.True(empty.IsEmpty);
+ Assert.Equal(0, empty.Length);
+ }
+ }
+}
diff --git a/src/System.Memory/tests/ReadOnlyMemory/Equality.cs b/src/System.Memory/tests/ReadOnlyMemory/Equality.cs
new file mode 100644
index 0000000000..a6dd5a9000
--- /dev/null
+++ b/src/System.Memory/tests/ReadOnlyMemory/Equality.cs
@@ -0,0 +1,163 @@
+// 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.Linq;
+using Xunit;
+
+#pragma warning disable 1718 //Comparison made to same variable; did you mean to compare something else?
+
+namespace System.MemoryTests
+{
+ public static partial class ReadOnlyMemoryTests
+ {
+ [Fact]
+ public static void EqualityTrue()
+ {
+ int[] a = { 91, 92, 93, 94, 95 };
+ var left = new ReadOnlyMemory<int>(a, 2, 3);
+ var right = new ReadOnlyMemory<int>(a, 2, 3);
+
+ Assert.True(left.Equals(right));
+ Assert.True(right.Equals(left));
+ }
+
+ [Fact]
+ public static void EqualityReflexivity()
+ {
+ int[] a = { 91, 92, 93, 94, 95 };
+ var left = new ReadOnlyMemory<int>(a, 2, 3);
+
+ Assert.True(left.Equals(left));
+ }
+
+ [Fact]
+ public static void EqualityIncludesLength()
+ {
+ int[] a = { 91, 92, 93, 94, 95 };
+ var left = new ReadOnlyMemory<int>(a, 2, 1);
+ var right = new ReadOnlyMemory<int>(a, 2, 3);
+
+ Assert.False(left.Equals(right));
+ Assert.False(right.Equals(left));
+ }
+
+ [Fact]
+ public static void EqualityIncludesBase()
+ {
+ int[] a = { 91, 92, 93, 94, 95 };
+ var left = new ReadOnlyMemory<int>(a, 1, 3);
+ var right = new ReadOnlyMemory<int>(a, 2, 3);
+
+ Assert.False(left.Equals(right));
+ Assert.False(right.Equals(left));
+ }
+
+ [Fact]
+ public static void EqualityComparesRangeNotContent()
+ {
+ var left = new ReadOnlyMemory<int>(new int[] { 0, 1, 2 }, 1, 1);
+ var right = new ReadOnlyMemory<int>(new int[] { 0, 1, 2 }, 1, 1);
+
+ Assert.False(left.Equals(right));
+ Assert.False(right.Equals(left));
+ }
+
+ [Fact]
+ public static void EmptyMemoryNotUnified()
+ {
+ var left = new ReadOnlyMemory<int>(new int[0]);
+ var right = new ReadOnlyMemory<int>(new int[0]);
+
+ ReadOnlyMemory<int> memoryFromNonEmptyArrayButWithZeroLength = new ReadOnlyMemory<int>(new int[1] { 123 }).Slice(0, 0);
+
+ Assert.False(left.Equals(right));
+ Assert.False(right.Equals(left));
+
+ Assert.False(memoryFromNonEmptyArrayButWithZeroLength.Equals(left));
+ Assert.False(left.Equals(memoryFromNonEmptyArrayButWithZeroLength));
+
+ // Empty property is equal
+ left = ReadOnlyMemory<int>.Empty;
+ right = ReadOnlyMemory<int>.Empty;
+
+ Assert.True(left.Equals(right));
+ Assert.True(right.Equals(left));
+ }
+
+ [Theory]
+ [MemberData(nameof(ValidArraySegments))]
+ public static void MemoryReferencingSameMemoryAreEqualInEveryAspect(byte[] bytes, int start, int length)
+ {
+ var memory = new ReadOnlyMemory<byte>(bytes, start, length);
+ var pointingToSameMemory = new ReadOnlyMemory<byte>(bytes, start, length);
+ ReadOnlyMemory<byte> structCopy = memory;
+
+ Assert.True(memory.Equals(pointingToSameMemory));
+ Assert.True(pointingToSameMemory.Equals(memory));
+
+ Assert.True(memory.Equals(structCopy));
+ Assert.True(structCopy.Equals(memory));
+ }
+
+ [Theory]
+ [MemberData(nameof(ValidArraySegments))]
+ public static void MemoryOfEqualValuesAreNotEqual(byte[] bytes, int start, int length)
+ {
+ byte[] bytesCopy = bytes.ToArray();
+
+ var memory = new ReadOnlyMemory<byte>(bytes, start, length);
+ var ofSameValues = new ReadOnlyMemory<byte>(bytesCopy, start, length);
+
+ Assert.False(memory.Equals(ofSameValues));
+ Assert.False(ofSameValues.Equals(memory));
+ }
+
+ [Theory]
+ [MemberData(nameof(ValidArraySegments))]
+ public static void MemoryOfDifferentValuesAreNotEqual(byte[] bytes, int start, int length)
+ {
+ byte[] differentBytes = bytes.Select(value => ++value).ToArray();
+
+ var memory = new ReadOnlyMemory<byte>(bytes, start, length);
+ var ofDifferentValues = new ReadOnlyMemory<byte>(differentBytes, start, length);
+
+ Assert.False(memory.Equals(ofDifferentValues));
+ Assert.False(ofDifferentValues.Equals(memory));
+ }
+
+ public static IEnumerable<object[]> ValidArraySegments
+ {
+ get
+ {
+ return new List<object[]>
+ {
+ new object[] { new byte[1] { 0 }, 0, 1},
+ new object[] { new byte[2] { 0, 0 }, 0, 2},
+ new object[] { new byte[2] { 0, 0 }, 0, 1},
+ new object[] { new byte[2] { 0, 0 }, 1, 1},
+ new object[] { new byte[3] { 0, 0, 0 }, 0, 3},
+ new object[] { new byte[3] { 0, 0, 0 }, 0, 2},
+ new object[] { new byte[3] { 0, 0, 0 }, 1, 2},
+ new object[] { new byte[3] { 0, 0, 0 }, 1, 1},
+ new object[] { Enumerable.Range(0, 100000).Select(i => (byte)i).ToArray(), 0, 100000 }
+ };
+ }
+ }
+
+ public static IEnumerable<object[]> FullArraySegments
+ {
+ get
+ {
+ return new List<object[]>
+ {
+ new object[] { new byte[1] { 0 } },
+ new object[] { new byte[2] { 0, 0 } },
+ new object[] { new byte[3] { 0, 0, 0 } },
+ new object[] { Enumerable.Range(0, 100000).Select(i => (byte)i).ToArray() }
+ };
+ }
+ }
+ }
+}
diff --git a/src/System.Memory/tests/ReadOnlyMemory/GetHashCode.cs b/src/System.Memory/tests/ReadOnlyMemory/GetHashCode.cs
new file mode 100644
index 0000000000..1e53747c32
--- /dev/null
+++ b/src/System.Memory/tests/ReadOnlyMemory/GetHashCode.cs
@@ -0,0 +1,73 @@
+// 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.MemoryTests
+{
+ public static partial class ReadOnlyMemoryTests
+ {
+ [Fact]
+ public static void SameObjectsHaveSameHashCodes()
+ {
+ int[] a = { 91, 92, 93, 94, 95 };
+ var left = new ReadOnlyMemory<int>(a, 2, 3);
+ var right = new ReadOnlyMemory<int>(a, 2, 3);
+
+ int[] b = { 1, 2, 3, 4, 5 };
+ var different = new ReadOnlyMemory<int>(b, 2, 3);
+
+ Assert.Equal(left.GetHashCode(), right.GetHashCode());
+ Assert.NotEqual(left.GetHashCode(), different.GetHashCode());
+ }
+
+ [Fact]
+ public static void HashCodeIncludesLength()
+ {
+ int[] a = { 91, 92, 93, 94, 95 };
+ var left = new ReadOnlyMemory<int>(a, 2, 1);
+ var right = new ReadOnlyMemory<int>(a, 2, 3);
+
+ Assert.NotEqual(left.GetHashCode(), right.GetHashCode());
+ }
+
+ [Fact]
+ public static void HashCodeIncludesBase()
+ {
+ int[] a = { 91, 92, 93, 94, 95 };
+ var left = new ReadOnlyMemory<int>(a, 1, 3);
+ var right = new ReadOnlyMemory<int>(a, 2, 3);
+
+ Assert.NotEqual(left.GetHashCode(), right.GetHashCode());
+ }
+
+ [Fact]
+ public static void HashCodesDifferentForSameContent()
+ {
+ var left = new ReadOnlyMemory<int>(new int[] { 0, 1, 2 }, 1, 1);
+ var right = new ReadOnlyMemory<int>(new int[] { 0, 1, 2 }, 1, 1);
+
+ Assert.NotEqual(left.GetHashCode(), right.GetHashCode());
+ }
+
+ [Fact]
+ public static void EmptyMemoryHashCodeNotUnified()
+ {
+ var left = new ReadOnlyMemory<int>(new int[0]);
+ var right = new ReadOnlyMemory<int>(new int[0]);
+
+ ReadOnlyMemory<int> memoryFromNonEmptyArrayButWithZeroLength = new Memory<int>(new int[1] { 123 }).Slice(0, 0);
+
+ Assert.NotEqual(left.GetHashCode(), right.GetHashCode());
+ Assert.NotEqual(left.GetHashCode(), memoryFromNonEmptyArrayButWithZeroLength.GetHashCode());
+ Assert.NotEqual(right.GetHashCode(), memoryFromNonEmptyArrayButWithZeroLength.GetHashCode());
+
+ // Empty property hashcode is equal
+ left = ReadOnlyMemory<int>.Empty;
+ right = ReadOnlyMemory<int>.Empty;
+
+ Assert.Equal(left.GetHashCode(), right.GetHashCode());
+ }
+ }
+}
diff --git a/src/System.Memory/tests/ReadOnlyMemory/ImplicitConversion.cs b/src/System.Memory/tests/ReadOnlyMemory/ImplicitConversion.cs
new file mode 100644
index 0000000000..205dfd28c3
--- /dev/null
+++ b/src/System.Memory/tests/ReadOnlyMemory/ImplicitConversion.cs
@@ -0,0 +1,80 @@
+// 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.MemoryTests
+{
+ public static partial class ReadOnlyMemoryTests
+ {
+ [Fact]
+ public static void CtorImplicitArray()
+ {
+ int[] intArray = { 19, -17 };
+ CastReadOnly(intArray, 19, -17);
+
+ long[] longArray = { 1, -3, 7, -15, 31 };
+ CastReadOnly<long>(longArray, 1, -3, 7, -15, 31);
+
+ object o1 = new object();
+ object o2 = new object();
+ object o3 = new object();
+ object o4 = new object();
+ object[] objectArray = { o1, o2, o3, o4 };
+ CastReadOnlyReference(objectArray, o1, o2, o3, o4);
+ }
+
+ [Fact]
+ public static void CtorImplicitZeroLengthArray()
+ {
+ int[] emptyArray1 = Array.Empty<int>();
+ CastReadOnly<int>(emptyArray1);
+
+ int[] emptyArray2 = new int[0];
+ CastReadOnly<int>(emptyArray2);
+ }
+
+ [Fact]
+ public static void CtorImplicitArraySegment()
+ {
+ int[] a = { 19, -17 };
+ ArraySegment<int> segmentInt = new ArraySegment<int>(a, 1, 1);
+ CastReadOnly(segmentInt, -17);
+
+ long[] b = { 1, -3, 7, -15, 31 };
+ ArraySegment<long> segmentLong = new ArraySegment<long>(b, 1, 3);
+ CastReadOnly<long>(segmentLong, -3, 7, -15);
+
+ object o1 = new object();
+ object o2 = new object();
+ object o3 = new object();
+ object o4 = new object();
+ object[] c = { o1, o2, o3, o4 };
+ ArraySegment<object> segmentObject = new ArraySegment<object>(c, 0, 2);
+ CastReadOnlyReference(segmentObject, o1, o2);
+ }
+
+ [Fact]
+ public static void CtorImplicitZeroLengthArraySegment()
+ {
+ int[] empty = Array.Empty<int>();
+ ArraySegment<int> emptySegment = new ArraySegment<int>(empty);
+ CastReadOnly<int>(emptySegment);
+
+ int[] a = { 19, -17 };
+ ArraySegment<int> segmentInt = new ArraySegment<int>(a, 1, 0);
+ CastReadOnly<int>(segmentInt);
+ }
+
+ private static void CastReadOnly<T>(ReadOnlyMemory<T> memory, params T[] expected) where T : struct, IEquatable<T>
+ {
+ memory.Validate(expected);
+ }
+
+ private static void CastReadOnlyReference<T>(ReadOnlyMemory<T> memory, params T[] expected)
+ {
+ memory.ValidateReferenceType(expected);
+ }
+ }
+}
diff --git a/src/System.Memory/tests/ReadOnlyMemory/Retain.cs b/src/System.Memory/tests/ReadOnlyMemory/Retain.cs
new file mode 100644
index 0000000000..437b6f39b4
--- /dev/null
+++ b/src/System.Memory/tests/ReadOnlyMemory/Retain.cs
@@ -0,0 +1,85 @@
+// 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.Buffers;
+using Xunit;
+
+namespace System.MemoryTests
+{
+ public static partial class ReadOnlyMemoryTests
+ {
+
+ [Fact]
+ public static void MemoryRetainWithoutPinning()
+ {
+ int[] array = { 1, 2, 3, 4, 5 };
+ ReadOnlyMemory<int> memory = array;
+ MemoryHandle handle = memory.Retain();
+ unsafe
+ {
+ int* pointer = (int*)handle.PinnedPointer;
+ Assert.True(pointer == null);
+ }
+ handle.Dispose();
+ }
+
+ [Fact]
+ public static void MemoryRetainWithPinning()
+ {
+ int[] array = { 1, 2, 3, 4, 5 };
+ ReadOnlyMemory<int> memory = array;
+ MemoryHandle handle = memory.Retain(pin: true);
+ unsafe
+ {
+ int* pointer = (int*)handle.PinnedPointer;
+ Assert.True(pointer != null);
+
+ GC.Collect();
+
+ for (int i = 0; i < memory.Length; i++)
+ {
+ Assert.Equal(array[i], pointer[i]);
+ }
+ }
+ handle.Dispose();
+ }
+
+ [Fact]
+ public static void OwnedMemoryRetainWithoutPinning()
+ {
+ int[] array = { 1, 2, 3, 4, 5 };
+ OwnedMemory<int> owner = new CustomMemoryForTest<int>(array);
+ ReadOnlyMemory<int> memory = owner.Memory;
+ MemoryHandle handle = memory.Retain();
+ unsafe
+ {
+ int* pointer = (int*)handle.PinnedPointer;
+ Assert.True(pointer == null);
+ }
+ handle.Dispose();
+ }
+
+ [Fact]
+ public static void OwnedMemoryRetainWithPinning()
+ {
+ int[] array = { 1, 2, 3, 4, 5 };
+ OwnedMemory<int> owner = new CustomMemoryForTest<int>(array);
+ ReadOnlyMemory<int> memory = owner.Memory;
+ MemoryHandle handle = memory.Retain(pin: true);
+ unsafe
+ {
+ int* pointer = (int*)handle.PinnedPointer;
+ Assert.True(pointer != null);
+
+ GC.Collect();
+
+ for (int i = 0; i < memory.Length; i++)
+ {
+ Assert.Equal(array[i], pointer[i]);
+ }
+ }
+ handle.Dispose();
+ }
+ }
+}
diff --git a/src/System.Memory/tests/ReadOnlyMemory/Slice.cs b/src/System.Memory/tests/ReadOnlyMemory/Slice.cs
new file mode 100644
index 0000000000..edeeb9d53f
--- /dev/null
+++ b/src/System.Memory/tests/ReadOnlyMemory/Slice.cs
@@ -0,0 +1,112 @@
+// 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 System.Runtime.CompilerServices;
+using System.Buffers;
+
+namespace System.MemoryTests
+{
+ public static partial class ReadOnlyMemoryTests
+ {
+ [Fact]
+ public static void SliceWithStart()
+ {
+ int[] a = { 90, 91, 92, 93, 94, 95, 96, 97, 98, 99 };
+ ReadOnlyMemory<int> memory = new ReadOnlyMemory<int>(a).Slice(6);
+ Assert.Equal(4, memory.Length);
+ Assert.True(Unsafe.AreSame(ref a[6], ref memory.Span.DangerousGetPinnableReference()));
+
+ OwnedMemory<int> owner = new CustomMemoryForTest<int>(a);
+ ReadOnlyMemory<int> memoryFromOwner = ((ReadOnlyMemory<int>)owner.Memory).Slice(6);
+
+ Assert.Equal(4, memoryFromOwner.Length);
+ Assert.True(Unsafe.AreSame(ref a[6], ref memoryFromOwner.Span.DangerousGetPinnableReference()));
+ }
+
+ [Fact]
+ public static void SliceWithStartPastEnd()
+ {
+ int[] a = { 90, 91, 92, 93, 94, 95, 96, 97, 98, 99 };
+ ReadOnlyMemory<int> memory = new ReadOnlyMemory<int>(a).Slice(a.Length);
+ Assert.Equal(0, memory.Length);
+ Assert.True(Unsafe.AreSame(ref a[a.Length - 1], ref Unsafe.Subtract(ref memory.Span.DangerousGetPinnableReference(), 1)));
+
+ OwnedMemory<int> owner = new CustomMemoryForTest<int>(a);
+ ReadOnlyMemory<int> memoryFromOwner = ((ReadOnlyMemory<int>)owner.Memory).Slice(a.Length);
+
+ Assert.Equal(0, memoryFromOwner.Length);
+ Assert.True(Unsafe.AreSame(ref a[a.Length - 1], ref Unsafe.Subtract(ref memoryFromOwner.Span.DangerousGetPinnableReference(), 1)));
+ }
+
+ [Fact]
+ public static void SliceWithStartAndLength()
+ {
+ int[] a = { 90, 91, 92, 93, 94, 95, 96, 97, 98, 99 };
+ ReadOnlyMemory<int> memory = new ReadOnlyMemory<int>(a).Slice(3, 5);
+ Assert.Equal(5, memory.Length);
+ Assert.True(Unsafe.AreSame(ref a[3], ref memory.Span.DangerousGetPinnableReference()));
+
+ OwnedMemory<int> owner = new CustomMemoryForTest<int>(a);
+ ReadOnlyMemory<int> memoryFromOwner = ((ReadOnlyMemory<int>)owner.Memory).Slice(3, 5);
+
+ Assert.Equal(5, memoryFromOwner.Length);
+ Assert.True(Unsafe.AreSame(ref a[3], ref memoryFromOwner.Span.DangerousGetPinnableReference()));
+ }
+
+ [Fact]
+ public static void SliceWithStartAndLengthUpToEnd()
+ {
+ int[] a = { 90, 91, 92, 93, 94, 95, 96, 97, 98, 99 };
+ ReadOnlyMemory<int> memory = new ReadOnlyMemory<int>(a).Slice(4, 6);
+ Assert.Equal(6, memory.Length);
+ Assert.True(Unsafe.AreSame(ref a[4], ref memory.Span.DangerousGetPinnableReference()));
+
+ OwnedMemory<int> owner = new CustomMemoryForTest<int>(a);
+ ReadOnlyMemory<int> memoryFromOwner = ((ReadOnlyMemory<int>)owner.Memory).Slice(4, 6);
+
+ Assert.Equal(6, memoryFromOwner.Length);
+ Assert.True(Unsafe.AreSame(ref a[4], ref memoryFromOwner.Span.DangerousGetPinnableReference()));
+ }
+
+ [Fact]
+ public static void SliceWithStartAndLengthPastEnd()
+ {
+ int[] a = { 90, 91, 92, 93, 94, 95, 96, 97, 98, 99 };
+ ReadOnlyMemory<int> memory = new ReadOnlyMemory<int>(a).Slice(a.Length, 0);
+ Assert.Equal(0, memory.Length);
+ Assert.True(Unsafe.AreSame(ref a[a.Length - 1], ref Unsafe.Subtract(ref memory.Span.DangerousGetPinnableReference(), 1)));
+
+ OwnedMemory<int> owner = new CustomMemoryForTest<int>(a);
+ ReadOnlyMemory<int> memoryFromOwner = ((ReadOnlyMemory<int>)owner.Memory).Slice(a.Length, 0);
+
+ Assert.Equal(0, memoryFromOwner.Length);
+ Assert.True(Unsafe.AreSame(ref a[a.Length - 1], ref Unsafe.Subtract(ref memoryFromOwner.Span.DangerousGetPinnableReference(), 1)));
+ }
+
+ [Fact]
+ public static void SliceRangeChecks()
+ {
+ int[] a = { 90, 91, 92, 93, 94, 95, 96, 97, 98, 99 };
+ Assert.Throws<ArgumentOutOfRangeException>(() => new ReadOnlyMemory<int>(a).Slice(-1));
+ Assert.Throws<ArgumentOutOfRangeException>(() => new ReadOnlyMemory<int>(a).Slice(a.Length + 1));
+ Assert.Throws<ArgumentOutOfRangeException>(() => new ReadOnlyMemory<int>(a).Slice(-1, 0));
+ Assert.Throws<ArgumentOutOfRangeException>(() => new ReadOnlyMemory<int>(a).Slice(0, a.Length + 1));
+ Assert.Throws<ArgumentOutOfRangeException>(() => new ReadOnlyMemory<int>(a).Slice(2, a.Length + 1 - 2));
+ Assert.Throws<ArgumentOutOfRangeException>(() => new ReadOnlyMemory<int>(a).Slice(a.Length + 1, 0));
+ Assert.Throws<ArgumentOutOfRangeException>(() => new ReadOnlyMemory<int>(a).Slice(a.Length, 1));
+
+ OwnedMemory<int> owner = new CustomMemoryForTest<int>(a);
+ ReadOnlyMemory<int> memory = owner.Memory;
+
+ Assert.Throws<ArgumentOutOfRangeException>(() => memory.Slice(-1));
+ Assert.Throws<ArgumentOutOfRangeException>(() => memory.Slice(a.Length + 1));
+ Assert.Throws<ArgumentOutOfRangeException>(() => memory.Slice(-1, 0));
+ Assert.Throws<ArgumentOutOfRangeException>(() => memory.Slice(0, a.Length + 1));
+ Assert.Throws<ArgumentOutOfRangeException>(() => memory.Slice(2, a.Length + 1 - 2));
+ Assert.Throws<ArgumentOutOfRangeException>(() => memory.Slice(a.Length + 1, 0));
+ Assert.Throws<ArgumentOutOfRangeException>(() => memory.Slice(a.Length, 1));
+ }
+ }
+}
diff --git a/src/System.Memory/tests/ReadOnlyMemory/Span.cs b/src/System.Memory/tests/ReadOnlyMemory/Span.cs
new file mode 100644
index 0000000000..dd0a3b9374
--- /dev/null
+++ b/src/System.Memory/tests/ReadOnlyMemory/Span.cs
@@ -0,0 +1,99 @@
+// 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.Buffers;
+using Xunit;
+
+namespace System.MemoryTests
+{
+ public static partial class ReadOnlyMemoryTests
+ {
+ [Fact]
+ public static void SpanFromCtorArrayInt()
+ {
+ int[] a = { 91, 92, -93, 94 };
+ ReadOnlyMemory<int> memory;
+
+ memory = new ReadOnlyMemory<int>(a);
+ memory.Span.Validate(91, 92, -93, 94);
+
+ memory = new ReadOnlyMemory<int>(a, 0, a.Length);
+ memory.Span.Validate(91, 92, -93, 94);
+
+ OwnedMemory<int> owner = new CustomMemoryForTest<int>(a);
+ ((ReadOnlyMemory<int>)owner.Memory).Span.Validate(91, 92, -93, 94);
+ }
+
+ [Fact]
+ public static void SpanFromCtorArrayLong()
+ {
+ long[] a = { 91, -92, 93, 94, -95 };
+ ReadOnlyMemory<long> memory;
+
+ memory = new ReadOnlyMemory<long>(a);
+ memory.Span.Validate(91, -92, 93, 94, -95);
+
+ memory = new ReadOnlyMemory<long>(a, 0, a.Length);
+ memory.Span.Validate(91, -92, 93, 94, -95);
+
+ OwnedMemory<long> owner = new CustomMemoryForTest<long>(a);
+ ((ReadOnlyMemory<long>)owner.Memory).Span.Validate(91, -92, 93, 94, -95);
+ }
+
+ [ActiveIssue(23952, TargetFrameworkMonikers.UapAot)]
+ [Fact]
+ public static void SpanFromCtorArrayObject()
+ {
+ object o1 = new object();
+ object o2 = new object();
+ object[] a = { o1, o2 };
+ ReadOnlyMemory<object> memory;
+
+ memory = new ReadOnlyMemory<object>(a);
+ memory.Span.ValidateReferenceType(o1, o2);
+
+ memory = new ReadOnlyMemory<object>(a, 0, a.Length);
+ memory.Span.ValidateReferenceType(o1, o2);
+
+ OwnedMemory<object> owner = new CustomMemoryForTest<object>(a);
+ ((ReadOnlyMemory<object>)owner.Memory).Span.ValidateReferenceType(o1, o2);
+ }
+
+ [Fact]
+ public static void SpanFromCtorArrayZeroLength()
+ {
+ int[] empty = Array.Empty<int>();
+ ReadOnlyMemory<int> memory;
+
+ memory = new ReadOnlyMemory<int>(empty);
+ memory.Span.Validate();
+
+ memory = new ReadOnlyMemory<int>(empty, 0, empty.Length);
+ memory.Span.Validate();
+
+ OwnedMemory<int> owner = new CustomMemoryForTest<int>(empty);
+ ((ReadOnlyMemory<int>)owner.Memory).Span.Validate();
+ }
+
+ [Fact]
+ public static void SpanFromCtorArrayWrongValueType()
+ {
+ // Can pass variant array, if array type is a valuetype.
+
+ uint[] a = { 42u, 0xffffffffu };
+ int[] aAsIntArray = (int[])(object)a;
+ ReadOnlyMemory<int> memory;
+
+ memory = new ReadOnlyMemory<int>(aAsIntArray);
+ memory.Span.Validate(42, -1);
+
+ memory = new ReadOnlyMemory<int>(aAsIntArray, 0, aAsIntArray.Length);
+ memory.Span.Validate(42, -1);
+
+ OwnedMemory<int> owner = new CustomMemoryForTest<int>(aAsIntArray);
+ ((ReadOnlyMemory<int>)owner.Memory).Span.Validate(42, -1);
+ }
+
+ }
+}
diff --git a/src/System.Memory/tests/ReadOnlyMemory/ToArray.cs b/src/System.Memory/tests/ReadOnlyMemory/ToArray.cs
new file mode 100644
index 0000000000..aa5ff3c029
--- /dev/null
+++ b/src/System.Memory/tests/ReadOnlyMemory/ToArray.cs
@@ -0,0 +1,29 @@
+// 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.MemoryTests
+{
+ public static partial class ReadOnlyMemoryTests
+ {
+ [Fact]
+ public static void ToArray1()
+ {
+ int[] a = { 91, 92, 93 };
+ var memory = new ReadOnlyMemory<int>(a);
+ int[] copy = memory.ToArray();
+ Assert.Equal<int>(a, copy);
+ Assert.NotSame(a, copy);
+ }
+
+ [Fact]
+ public static void ToArrayEmpty()
+ {
+ ReadOnlyMemory<int> memory = ReadOnlyMemory<int>.Empty;
+ int[] copy = memory.ToArray();
+ Assert.Equal(0, copy.Length);
+ }
+ }
+}
diff --git a/src/System.Memory/tests/ReadOnlySpan/AsBytes.cs b/src/System.Memory/tests/ReadOnlySpan/AsBytes.cs
index 18e6775e86..9493f7a1b2 100644
--- a/src/System.Memory/tests/ReadOnlySpan/AsBytes.cs
+++ b/src/System.Memory/tests/ReadOnlySpan/AsBytes.cs
@@ -16,7 +16,7 @@ namespace System.SpanTests
ReadOnlySpan<uint> span = new ReadOnlySpan<uint>(a);
ReadOnlySpan<byte> asBytes = span.AsBytes<uint>();
- Assert.True(Unsafe.AreSame<byte>(ref Unsafe.As<uint, byte>(ref span.DangerousGetPinnableReference()), ref asBytes.DangerousGetPinnableReference()));
+ Assert.True(Unsafe.AreSame(ref Unsafe.As<uint, byte>(ref span.DangerousGetPinnableReference()), ref asBytes.DangerousGetPinnableReference()));
asBytes.Validate<byte>(0x11, 0x22, 0x33, 0x44, 0x55, 0x66, 0x77, 0x88);
}
@@ -24,7 +24,7 @@ namespace System.SpanTests
public static void AsBytesContainsReferences()
{
ReadOnlySpan<StructWithReferences> span = new ReadOnlySpan<StructWithReferences>(Array.Empty<StructWithReferences>());
- AssertThrows<ArgumentException, StructWithReferences>(span, (_span) => _span.AsBytes<StructWithReferences>().DontBox());
+ TestHelpers.AssertThrows<ArgumentException, StructWithReferences>(span, (_span) => _span.AsBytes().DontBox());
}
}
}
diff --git a/src/System.Memory/tests/ReadOnlySpan/AsReadOnlySpan.cs b/src/System.Memory/tests/ReadOnlySpan/AsReadOnlySpan.cs
index 5281c96870..065edc98c1 100644
--- a/src/System.Memory/tests/ReadOnlySpan/AsReadOnlySpan.cs
+++ b/src/System.Memory/tests/ReadOnlySpan/AsReadOnlySpan.cs
@@ -3,28 +3,36 @@
// See the LICENSE file in the project root for more information.
using Xunit;
-using System.Runtime.CompilerServices;
namespace System.SpanTests
{
public static partial class ReadOnlySpanTests
{
[Fact]
- public static void ArrayAsReadOnlySpan()
+ public static void IntArrayAsReadOnlySpan()
{
int[] a = { 19, -17 };
ReadOnlySpan<int> spanInt = a.AsReadOnlySpan();
- spanInt.Validate<int>(19, -17);
+ spanInt.Validate(19, -17);
+ }
+ [Fact]
+ public static void LongArrayAsReadOnlySpan()
+ {
long[] b = { 1, -3, 7, -15, 31 };
ReadOnlySpan<long> spanLong = b.AsReadOnlySpan();
- spanLong.Validate<long>(1, -3, 7, -15, 31);
+ spanLong.Validate(1, -3, 7, -15, 31);
+ }
+ [ActiveIssue(23952, TargetFrameworkMonikers.UapAot)]
+ [Fact]
+ public static void ObjectArrayAsReadOnlySpan()
+ {
object o1 = new object();
object o2 = new object();
object[] c = { o1, o2 };
ReadOnlySpan<object> spanObject = c.AsReadOnlySpan();
- spanObject.Validate<object>(o1, o2);
+ spanObject.ValidateReferenceType(o1, o2);
}
[Fact]
@@ -32,7 +40,7 @@ namespace System.SpanTests
{
int[] a = null;
ReadOnlySpan<int> span;
- AssertThrows<ArgumentNullException, int>(span, _span => _span = a.AsReadOnlySpan());
+ TestHelpers.AssertThrows<ArgumentNullException, int>(span, _span => _span = a.AsReadOnlySpan());
}
[Fact]
@@ -40,22 +48,31 @@ namespace System.SpanTests
{
int[] empty = Array.Empty<int>();
ReadOnlySpan<int> span = empty.AsReadOnlySpan();
- span.Validate<int>();
+ span.Validate();
}
[Fact]
- public static void ArraySegmentAsSpan()
+ public static void IntArraySegmentAsSpan()
{
int[] a = { 19, -17 };
ArraySegment<int> segmentInt = new ArraySegment<int>(a, 1, 1);
ReadOnlySpan<int> spanInt = segmentInt.AsReadOnlySpan();
- spanInt.Validate<int>(-17);
+ spanInt.Validate(-17);
+ }
+ [Fact]
+ public static void LongArraySegmentAsSpan()
+ {
long[] b = { 1, -3, 7, -15, 31 };
ArraySegment<long> segmentLong = new ArraySegment<long>(b, 1, 3);
ReadOnlySpan<long> spanLong = segmentLong.AsReadOnlySpan();
- spanLong.Validate<long>(-3, 7, -15);
+ spanLong.Validate(-3, 7, -15);
+ }
+ [ActiveIssue(23952, TargetFrameworkMonikers.UapAot)]
+ [Fact]
+ public static void ObjectArraySegmentAsSpan()
+ {
object o1 = new object();
object o2 = new object();
object o3 = new object();
@@ -63,7 +80,7 @@ namespace System.SpanTests
object[] c = { o1, o2, o3, o4 };
ArraySegment<object> segmentObject = new ArraySegment<object>(c, 0, 2);
ReadOnlySpan<object> spanObject = segmentObject.AsReadOnlySpan();
- spanObject.Validate<object>(o1, o2);
+ spanObject.ValidateReferenceType(o1, o2);
}
[Fact]
@@ -72,12 +89,37 @@ namespace System.SpanTests
int[] empty = Array.Empty<int>();
ArraySegment<int> emptySegment = new ArraySegment<int>(empty);
ReadOnlySpan<int> span = emptySegment.AsReadOnlySpan();
- span.Validate<int>();
+ span.Validate();
int[] a = { 19, -17 };
ArraySegment<int> segmentInt = new ArraySegment<int>(a, 1, 0);
ReadOnlySpan<int> spanInt = segmentInt.AsReadOnlySpan();
- spanInt.Validate<int>();
+ spanInt.Validate();
+ }
+
+ [Fact]
+ public static void StringAsReadOnlySpanNullary()
+ {
+ string s = "Hello";
+ ReadOnlySpan<char> span = s.AsReadOnlySpan();
+ char[] expected = s.ToCharArray();
+ span.Validate(expected);
+ }
+
+ [Fact]
+ public static void StringAsReadOnlySpanEmptyString()
+ {
+ string s = "";
+ ReadOnlySpan<char> span = s.AsReadOnlySpan();
+ char[] expected = s.ToCharArray();
+ span.Validate(expected);
+ }
+
+ [Fact]
+ public static void StringAsReadOnlySpanNullChecked()
+ {
+ string s = null;
+ Assert.Throws<ArgumentNullException>(() => s.AsReadOnlySpan().DontBox());
}
}
-} \ No newline at end of file
+}
diff --git a/src/System.Memory/tests/ReadOnlySpan/AsSpan.cs b/src/System.Memory/tests/ReadOnlySpan/AsSpan.cs
deleted file mode 100644
index 37aaf54cfb..0000000000
--- a/src/System.Memory/tests/ReadOnlySpan/AsSpan.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 Xunit;
-using System.Runtime.CompilerServices;
-
-namespace System.SpanTests
-{
- public static partial class ReadOnlySpanTests
- {
- [Fact]
- public static void StringAsSpanNullary()
- {
- string s = "Hello";
- ReadOnlySpan<char> span = s.AsReadOnlySpan();
- char[] expected = s.ToCharArray();
- span.Validate(expected);
- }
-
- [Fact]
- public static void StringAsSpanEmptyString()
- {
- string s = "";
- ReadOnlySpan<char> span = s.AsReadOnlySpan();
- char[] expected = s.ToCharArray();
- span.Validate(expected);
- }
-
- [Fact]
- public static void StringAsSpanNullChecked()
- {
- string s = null;
- Assert.Throws<ArgumentNullException>(() => s.AsReadOnlySpan().DontBox());
- }
- }
-}
diff --git a/src/System.Memory/tests/ReadOnlySpan/CopyTo.cs b/src/System.Memory/tests/ReadOnlySpan/CopyTo.cs
index 92036a72c3..4dd30a179d 100644
--- a/src/System.Memory/tests/ReadOnlySpan/CopyTo.cs
+++ b/src/System.Memory/tests/ReadOnlySpan/CopyTo.cs
@@ -92,7 +92,7 @@ namespace System.SpanTests
int[] dst = { 99, 100 };
ReadOnlySpan<int> srcSpan = new ReadOnlySpan<int>(src);
- AssertThrows<ArgumentException, int>(srcSpan, (_srcSpan) => _srcSpan.CopyTo(dst));
+ TestHelpers.AssertThrows<ArgumentException, int>(srcSpan, (_srcSpan) => _srcSpan.CopyTo(dst));
int[] expected = { 99, 100 };
Assert.Equal<int>(expected, dst); // CopyTo() checks for sufficient space before doing any copying.
}
diff --git a/src/System.Memory/tests/ReadOnlySpan/CtorArray.cs b/src/System.Memory/tests/ReadOnlySpan/CtorArray.cs
index 825154c633..d8e9214c56 100644
--- a/src/System.Memory/tests/ReadOnlySpan/CtorArray.cs
+++ b/src/System.Memory/tests/ReadOnlySpan/CtorArray.cs
@@ -3,6 +3,7 @@
// See the LICENSE file in the project root for more information.
using Xunit;
+using static System.TestHelpers;
namespace System.SpanTests
{
@@ -21,10 +22,10 @@ namespace System.SpanTests
ReadOnlySpan<int> span;
span = new ReadOnlySpan<int>(a);
- span.Validate<int>(91, 92, -93, 94);
+ span.Validate(91, 92, -93, 94);
span = new ReadOnlySpan<int>(a, 0, a.Length);
- span.Validate<int>(91, 92, -93, 94);
+ span.Validate(91, 92, -93, 94);
}
[Fact]
@@ -34,12 +35,13 @@ namespace System.SpanTests
ReadOnlySpan<long> span;
span = new ReadOnlySpan<long>(a);
- span.Validate<long>(91, -92, 93, 94, -95);
+ span.Validate(91, -92, 93, 94, -95);
span = new ReadOnlySpan<long>(a, 0, a.Length);
- span.Validate<long>(91, -92, 93, 94, -95);
+ span.Validate(91, -92, 93, 94, -95);
}
+ [ActiveIssue(23952, TargetFrameworkMonikers.UapAot)]
[Fact]
public static void CtorArray3()
{
@@ -49,10 +51,10 @@ namespace System.SpanTests
ReadOnlySpan<object> span;
span = new ReadOnlySpan<object>(a);
- span.Validate<object>(o1, o2);
+ span.ValidateReferenceType(o1, o2);
span = new ReadOnlySpan<object>(a, 0, a.Length);
- span.Validate<object>(o1, o2);
+ span.ValidateReferenceType(o1, o2);
}
[Fact]
@@ -62,17 +64,17 @@ namespace System.SpanTests
ReadOnlySpan<int> span;
span = new ReadOnlySpan<int>(empty);
- span.Validate<int>();
+ span.Validate();
span = new ReadOnlySpan<int>(empty, 0, empty.Length);
- span.Validate<int>();
+ span.Validate();
}
[Fact]
public static void CtorArrayNullArray()
{
- Assert.Throws<ArgumentNullException>(() => new ReadOnlySpan<int>((int[])null).DontBox());
- Assert.Throws<ArgumentNullException>(() => new ReadOnlySpan<int>((int[])null, 0, 0).DontBox());
+ Assert.Throws<ArgumentNullException>(() => new ReadOnlySpan<int>(null).DontBox());
+ Assert.Throws<ArgumentNullException>(() => new ReadOnlySpan<int>(null, 0, 0).DontBox());
}
[Fact]
@@ -85,12 +87,13 @@ namespace System.SpanTests
ReadOnlySpan<int> span;
span = new ReadOnlySpan<int>(aAsIntArray);
- span.Validate<int>(42, -1);
+ span.Validate(42, -1);
span = new ReadOnlySpan<int>(aAsIntArray, 0, aAsIntArray.Length);
- span.Validate<int>(42, -1);
+ span.Validate(42, -1);
}
+ [ActiveIssue(23952, TargetFrameworkMonikers.UapAot)]
[Fact]
public static void CtorVariantArrayType()
{
@@ -101,17 +104,17 @@ namespace System.SpanTests
string[] strArray = { "Hello" };
span = new ReadOnlySpan<object>(strArray);
- span.Validate("Hello");
+ span.ValidateReferenceType("Hello");
span = new ReadOnlySpan<object>(strArray, 0, strArray.Length);
- span.Validate("Hello");
+ span.ValidateReferenceType("Hello");
TestClass c1 = new TestClass();
TestClass c2 = new TestClass();
TestClass[] clsArray = { c1, c2 };
span = new ReadOnlySpan<object>(clsArray);
- span.Validate(c1, c2);
+ span.ValidateReferenceType(c1, c2);
span = new ReadOnlySpan<object>(clsArray, 0, clsArray.Length);
- span.Validate(c1, c2);
+ span.ValidateReferenceType(c1, c2);
}
}
}
diff --git a/src/System.Memory/tests/ReadOnlySpan/CtorArrayIntInt.cs b/src/System.Memory/tests/ReadOnlySpan/CtorArrayIntInt.cs
index 518da9d1eb..b29198cfbb 100644
--- a/src/System.Memory/tests/ReadOnlySpan/CtorArrayIntInt.cs
+++ b/src/System.Memory/tests/ReadOnlySpan/CtorArrayIntInt.cs
@@ -16,7 +16,7 @@ namespace System.SpanTests
{
int[] a = { 90, 91, 92, 93, 94, 95, 96, 97, 98 };
ReadOnlySpan<int> span = new ReadOnlySpan<int>(a, 3, 2);
- span.Validate<int>(93, 94);
+ span.Validate(93, 94);
}
[Fact]
@@ -24,7 +24,7 @@ namespace System.SpanTests
{
long[] a = { 90, 91, 92, 93, 94, 95, 96, 97, 98 };
ReadOnlySpan<long> span = new ReadOnlySpan<long>(a, 4, 3);
- span.Validate<long>(94, 95, 96);
+ span.Validate(94, 95, 96);
}
[Fact]
@@ -32,7 +32,7 @@ namespace System.SpanTests
{
long[] a = { 90, 91, 92, 93, 94, 95, 96, 97, 98 };
ReadOnlySpan<long> span = new ReadOnlySpan<long>(a, 4, 5);
- span.Validate<long>(94, 95, 96, 97, 98);
+ span.Validate(94, 95, 96, 97, 98);
}
[Fact]
@@ -73,7 +73,7 @@ namespace System.SpanTests
// Valid for start to equal the array length. This returns an empty span that starts "just past the array."
int[] a = { 91, 92, 93 };
ReadOnlySpan<int> span = new ReadOnlySpan<int>(a, 3, 0);
- span.Validate<int>();
+ span.Validate();
}
}
}
diff --git a/src/System.Memory/tests/ReadOnlySpan/CtorPointerInt.cs b/src/System.Memory/tests/ReadOnlySpan/CtorPointerInt.cs
index 1851b6d770..3cf399b055 100644
--- a/src/System.Memory/tests/ReadOnlySpan/CtorPointerInt.cs
+++ b/src/System.Memory/tests/ReadOnlySpan/CtorPointerInt.cs
@@ -20,8 +20,8 @@ namespace System.SpanTests
fixed (int *pa = a)
{
ReadOnlySpan<int> span = new ReadOnlySpan<int>(pa, 3);
- span.Validate<int>(90, 91, 92);
- Assert.True(Unsafe.AreSame<int>(ref Unsafe.AsRef<int>(pa), ref span.DangerousGetPinnableReference()));
+ span.Validate(90, 91, 92);
+ Assert.True(Unsafe.AreSame(ref Unsafe.AsRef<int>(pa), ref span.DangerousGetPinnableReference()));
}
}
}
@@ -32,8 +32,8 @@ namespace System.SpanTests
unsafe
{
ReadOnlySpan<int> span = new ReadOnlySpan<int>((void*)null, 0);
- span.Validate<int>();
- Assert.True(Unsafe.AreSame<int>(ref Unsafe.AsRef<int>((void*)null), ref span.DangerousGetPinnableReference()));
+ span.Validate();
+ Assert.True(Unsafe.AreSame(ref Unsafe.AsRef<int>((void*)null), ref span.DangerousGetPinnableReference()));
}
}
diff --git a/src/System.Memory/tests/ReadOnlySpan/DangerousCreate.cs b/src/System.Memory/tests/ReadOnlySpan/DangerousCreate.cs
index 9346ef85f3..fd1be1656b 100644
--- a/src/System.Memory/tests/ReadOnlySpan/DangerousCreate.cs
+++ b/src/System.Memory/tests/ReadOnlySpan/DangerousCreate.cs
@@ -3,8 +3,8 @@
// See the LICENSE file in the project root for more information.
using Xunit;
-using System.Runtime.InteropServices;
using System.Runtime.CompilerServices;
+using static System.TestHelpers;
namespace System.SpanTests
{
@@ -13,17 +13,19 @@ namespace System.SpanTests
[Fact]
public static void DangerousCreate1()
{
- TestClass testClass = new TestClass();
- testClass.C0 = 'a';
- testClass.C1 = 'b';
- testClass.C2 = 'c';
- testClass.C3 = 'd';
- testClass.C4 = 'e';
+ TestClass testClass = new TestClass
+ {
+ C0 = 'a',
+ C1 = 'b',
+ C2 = 'c',
+ C3 = 'd',
+ C4 = 'e'
+ };
ReadOnlySpan<char> span = ReadOnlySpan<char>.DangerousCreate(testClass, ref testClass.C1, 3);
- span.Validate<char>('b', 'c', 'd');
+ span.Validate('b', 'c', 'd');
ref char pc1 = ref span.DangerousGetPinnableReference();
- Assert.True(Unsafe.AreSame<char>(ref testClass.C1, ref pc1));
+ Assert.True(Unsafe.AreSame(ref testClass.C1, ref pc1));
}
}
}
diff --git a/src/System.Memory/tests/ReadOnlySpan/DangerousGetPinnableReference.cs b/src/System.Memory/tests/ReadOnlySpan/DangerousGetPinnableReference.cs
index 4fc1796955..9f93501235 100644
--- a/src/System.Memory/tests/ReadOnlySpan/DangerousGetPinnableReference.cs
+++ b/src/System.Memory/tests/ReadOnlySpan/DangerousGetPinnableReference.cs
@@ -3,8 +3,8 @@
// See the LICENSE file in the project root for more information.
using Xunit;
-using System.Runtime.InteropServices;
using System.Runtime.CompilerServices;
+using static System.TestHelpers;
namespace System.SpanTests
{
@@ -16,7 +16,7 @@ namespace System.SpanTests
int[] a = { 91, 92, 93, 94, 95 };
ReadOnlySpan<int> span = new ReadOnlySpan<int>(a, 1, 3);
ref int pinnableReference = ref span.DangerousGetPinnableReference();
- Assert.True(Unsafe.AreSame<int>(ref a[1], ref pinnableReference));
+ Assert.True(Unsafe.AreSame(ref a[1], ref pinnableReference));
}
[Fact]
@@ -29,7 +29,7 @@ namespace System.SpanTests
ReadOnlySpan<int> span = new ReadOnlySpan<int>(a, a.Length, 0);
ref int pinnableReference = ref span.DangerousGetPinnableReference();
ref int expected = ref Unsafe.Add<int>(ref a[a.Length - 1], 1);
- Assert.True(Unsafe.AreSame<int>(ref expected, ref pinnableReference));
+ Assert.True(Unsafe.AreSame(ref expected, ref pinnableReference));
}
[Fact]
@@ -40,7 +40,7 @@ namespace System.SpanTests
int i = 42;
ReadOnlySpan<int> span = new ReadOnlySpan<int>(&i, 1);
ref int pinnableReference = ref span.DangerousGetPinnableReference();
- Assert.True(Unsafe.AreSame<int>(ref i, ref pinnableReference));
+ Assert.True(Unsafe.AreSame(ref i, ref pinnableReference));
}
}
@@ -51,7 +51,7 @@ namespace System.SpanTests
ReadOnlySpan<char> span = ReadOnlySpan<char>.DangerousCreate(testClass, ref testClass.C1, 3);
ref char pinnableReference = ref span.DangerousGetPinnableReference();
- Assert.True(Unsafe.AreSame<char>(ref testClass.C1, ref pinnableReference));
+ Assert.True(Unsafe.AreSame(ref testClass.C1, ref pinnableReference));
}
[Fact]
@@ -61,7 +61,7 @@ namespace System.SpanTests
{
ReadOnlySpan<int> span = ReadOnlySpan<int>.Empty;
ref int pinnableReference = ref span.DangerousGetPinnableReference();
- Assert.True(Unsafe.AreSame<int>(ref Unsafe.AsRef<int>(null), ref pinnableReference));
+ Assert.True(Unsafe.AreSame(ref Unsafe.AsRef<int>(null), ref pinnableReference));
}
}
}
diff --git a/src/System.Memory/tests/ReadOnlySpan/Empty.cs b/src/System.Memory/tests/ReadOnlySpan/Empty.cs
index 11ebb2b27c..0af910dfec 100644
--- a/src/System.Memory/tests/ReadOnlySpan/Empty.cs
+++ b/src/System.Memory/tests/ReadOnlySpan/Empty.cs
@@ -19,7 +19,7 @@ namespace System.SpanTests
{
ref int expected = ref Unsafe.AsRef<int>(null);
ref int actual = ref empty.DangerousGetPinnableReference();
- Assert.True(Unsafe.AreSame<int>(ref expected, ref actual));
+ Assert.True(Unsafe.AreSame(ref expected, ref actual));
}
}
}
diff --git a/src/System.Memory/tests/ReadOnlySpan/IndexOf.T.cs b/src/System.Memory/tests/ReadOnlySpan/IndexOf.T.cs
index 7e1cdbf2a0..3ace67ee0e 100644
--- a/src/System.Memory/tests/ReadOnlySpan/IndexOf.T.cs
+++ b/src/System.Memory/tests/ReadOnlySpan/IndexOf.T.cs
@@ -80,7 +80,7 @@ namespace System.SpanTests
foreach (TInt elem in a)
{
int numCompares = log.CountCompares(elem.Value, 9999);
- Assert.True(numCompares == 1);
+ Assert.True(numCompares == 1, $"Expected {numCompares} == 1 for element {elem.Value}.");
}
}
}
diff --git a/src/System.Memory/tests/ReadOnlySpan/IndexOf.byte.cs b/src/System.Memory/tests/ReadOnlySpan/IndexOf.byte.cs
index 1e98500187..09182a4bc1 100644
--- a/src/System.Memory/tests/ReadOnlySpan/IndexOf.byte.cs
+++ b/src/System.Memory/tests/ReadOnlySpan/IndexOf.byte.cs
@@ -193,7 +193,7 @@ namespace System.SpanTests
}
var found = span[index];
- Assert.Equal((byte)expectResult, (byte)found);
+ Assert.Equal((byte)expectResult, found);
Assert.Equal(expectIndex, index);
}
diff --git a/src/System.Memory/tests/ReadOnlySpan/NonPortableCast.cs b/src/System.Memory/tests/ReadOnlySpan/NonPortableCast.cs
index 12af06bf4a..2a360a205c 100644
--- a/src/System.Memory/tests/ReadOnlySpan/NonPortableCast.cs
+++ b/src/System.Memory/tests/ReadOnlySpan/NonPortableCast.cs
@@ -24,14 +24,14 @@ namespace System.SpanTests
public static void PortableCastToTypeContainsReferences()
{
ReadOnlySpan<uint> span = new ReadOnlySpan<uint>(Array.Empty<uint>());
- AssertThrows<ArgumentException, uint>(span, (_span) => _span.NonPortableCast<uint, StructWithReferences>().DontBox());
+ TestHelpers.AssertThrows<ArgumentException, uint>(span, (_span) => _span.NonPortableCast<uint, StructWithReferences>().DontBox());
}
[Fact]
public static void PortableCastFromTypeContainsReferences()
{
ReadOnlySpan<StructWithReferences> span = new ReadOnlySpan<StructWithReferences>(Array.Empty<StructWithReferences>());
- AssertThrows<ArgumentException, StructWithReferences>(span, (_span) => _span.NonPortableCast<StructWithReferences, uint>().DontBox());
+ TestHelpers.AssertThrows<ArgumentException, StructWithReferences>(span, (_span) => _span.NonPortableCast<StructWithReferences, uint>().DontBox());
}
}
}
diff --git a/src/System.Memory/tests/ReadOnlySpan/Overflow.cs b/src/System.Memory/tests/ReadOnlySpan/Overflow.cs
index 6c42890253..dc9ed088e7 100644
--- a/src/System.Memory/tests/ReadOnlySpan/Overflow.cs
+++ b/src/System.Memory/tests/ReadOnlySpan/Overflow.cs
@@ -3,7 +3,6 @@
// See the LICENSE file in the project root for more information.
using Xunit;
-using System.Runtime.InteropServices;
using System.Runtime.CompilerServices;
namespace System.SpanTests
@@ -41,7 +40,7 @@ namespace System.SpanTests
int bigIndex = checked(GuidTwoGiBLimit + 1);
uint byteOffset = checked((uint)bigIndex * (uint)sizeof(Guid));
- Assert.True(byteOffset > (uint)int.MaxValue); // Make sure byteOffset actually overflows 2Gb, or this test is pointless.
+ Assert.True(byteOffset > int.MaxValue); // Make sure byteOffset actually overflows 2Gb, or this test is pointless.
Guid expectedGuid = Guid.NewGuid();
ref Guid expected = ref Unsafe.Add<Guid>(ref memory, bigIndex);
expected = expectedGuid;
diff --git a/src/System.Memory/tests/ReadOnlySpan/SequenceEqual.T.cs b/src/System.Memory/tests/ReadOnlySpan/SequenceEqual.T.cs
index d2d9c91d8e..45571867d6 100644
--- a/src/System.Memory/tests/ReadOnlySpan/SequenceEqual.T.cs
+++ b/src/System.Memory/tests/ReadOnlySpan/SequenceEqual.T.cs
@@ -64,7 +64,7 @@ namespace System.SpanTests
foreach (TInt elem in first)
{
int numCompares = log.CountCompares(elem.Value, elem.Value);
- Assert.True(numCompares == 1);
+ Assert.True(numCompares == 1, $"Expected {numCompares} == 1 for element {elem.Value}.");
}
}
}
diff --git a/src/System.Memory/tests/ReadOnlySpan/Slice.cs b/src/System.Memory/tests/ReadOnlySpan/Slice.cs
index 1760b436d0..5efa1f1b3e 100644
--- a/src/System.Memory/tests/ReadOnlySpan/Slice.cs
+++ b/src/System.Memory/tests/ReadOnlySpan/Slice.cs
@@ -15,7 +15,7 @@ namespace System.SpanTests
int[] a = { 90, 91, 92, 93, 94, 95, 96, 97, 98, 99 };
ReadOnlySpan<int> span = new ReadOnlySpan<int>(a).Slice(6);
Assert.Equal(4, span.Length);
- Assert.True(Unsafe.AreSame<int>(ref a[6], ref span.DangerousGetPinnableReference()));
+ Assert.True(Unsafe.AreSame(ref a[6], ref span.DangerousGetPinnableReference()));
}
[Fact]
@@ -24,7 +24,7 @@ namespace System.SpanTests
int[] a = { 90, 91, 92, 93, 94, 95, 96, 97, 98, 99 };
ReadOnlySpan<int> span = new ReadOnlySpan<int>(a).Slice(a.Length);
Assert.Equal(0, span.Length);
- Assert.True(Unsafe.AreSame<int>(ref a[a.Length - 1], ref Unsafe.Subtract<int>(ref span.DangerousGetPinnableReference(), 1)));
+ Assert.True(Unsafe.AreSame(ref a[a.Length - 1], ref Unsafe.Subtract<int>(ref span.DangerousGetPinnableReference(), 1)));
}
[Fact]
@@ -33,7 +33,7 @@ namespace System.SpanTests
int[] a = { 90, 91, 92, 93, 94, 95, 96, 97, 98, 99 };
ReadOnlySpan<int> span = new ReadOnlySpan<int>(a).Slice(3, 5);
Assert.Equal(5, span.Length);
- Assert.True(Unsafe.AreSame<int>(ref a[3], ref span.DangerousGetPinnableReference()));
+ Assert.True(Unsafe.AreSame(ref a[3], ref span.DangerousGetPinnableReference()));
}
[Fact]
@@ -42,7 +42,7 @@ namespace System.SpanTests
int[] a = { 90, 91, 92, 93, 94, 95, 96, 97, 98, 99 };
ReadOnlySpan<int> span = new ReadOnlySpan<int>(a).Slice(4, 6);
Assert.Equal(6, span.Length);
- Assert.True(Unsafe.AreSame<int>(ref a[4], ref span.DangerousGetPinnableReference()));
+ Assert.True(Unsafe.AreSame(ref a[4], ref span.DangerousGetPinnableReference()));
}
[Fact]
@@ -51,7 +51,7 @@ namespace System.SpanTests
int[] a = { 90, 91, 92, 93, 94, 95, 96, 97, 98, 99 };
ReadOnlySpan<int> span = new ReadOnlySpan<int>(a).Slice(a.Length, 0);
Assert.Equal(0, span.Length);
- Assert.True(Unsafe.AreSame<int>(ref a[a.Length - 1], ref Unsafe.Subtract<int>(ref span.DangerousGetPinnableReference(), 1)));
+ Assert.True(Unsafe.AreSame(ref a[a.Length - 1], ref Unsafe.Subtract<int>(ref span.DangerousGetPinnableReference(), 1)));
}
[Fact]
diff --git a/src/System.Memory/tests/ReadOnlySpan/StartsWith.T.cs b/src/System.Memory/tests/ReadOnlySpan/StartsWith.T.cs
index 221fada56d..7d3771de35 100644
--- a/src/System.Memory/tests/ReadOnlySpan/StartsWith.T.cs
+++ b/src/System.Memory/tests/ReadOnlySpan/StartsWith.T.cs
@@ -85,7 +85,7 @@ namespace System.SpanTests
foreach (TInt elem in first)
{
int numCompares = log.CountCompares(elem.Value, elem.Value);
- Assert.True(numCompares == 1);
+ Assert.True(numCompares == 1, $"Expected {numCompares} == 1 for element {elem.Value}.");
}
}
}
diff --git a/src/System.Memory/tests/ReadOnlySpan/TestHelpers.cs b/src/System.Memory/tests/ReadOnlySpan/TestHelpers.cs
deleted file mode 100644
index bbeba43e57..0000000000
--- a/src/System.Memory/tests/ReadOnlySpan/TestHelpers.cs
+++ /dev/null
@@ -1,79 +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;
-using System.Runtime.InteropServices;
-
-namespace System.SpanTests
-{
- public static partial class ReadOnlySpanTests
- {
- private static void Validate<T>(this ReadOnlySpan<T> span, params T[] expected)
- {
- bool isValueType = default(T) != null || Nullable.GetUnderlyingType(typeof(T)) != null;
- Assert.Equal(span.Length, expected.Length);
- for (int i = 0; i < expected.Length; i++)
- {
- T actual = span[i];
- if (isValueType)
- Assert.Equal(expected[i], actual);
- else
- Assert.Same(expected[i], actual);
- }
-
- object ignore;
- AssertThrows<IndexOutOfRangeException, T>(span, (_span) => ignore = _span[expected.Length]);
- }
-
- private delegate void AssertThrowsAction<T>(ReadOnlySpan<T> span);
-
- // Cannot use standard Assert.Throws() when testing Span - Span and closures don't get along.
- private static void AssertThrows<E, T>(ReadOnlySpan<T> span, AssertThrowsAction<T> action) where E:Exception
- {
- try
- {
- action(span);
- Assert.False(true, "Expected exception: " + typeof(E).GetType());
- }
- catch (E)
- {
- }
- catch (Exception wrongException)
- {
- Assert.False(true, "Wrong exception thrown: Expected " + typeof(E).GetType() + ": Actual: " + wrongException.GetType());
- }
- }
-
- //
- // The innocent looking construct:
- //
- // Assert.Throws<E>( () => new Span() );
- //
- // generates a hidden box of the Span as the return value of the lambda. This makes the IL illegal and unloadable on
- // runtimes that enforce the actual Span rules (never mind that we expect never to reach the box instruction...)
- //
- // The workaround is to code it like this:
- //
- // Assert.Throws<E>( () => new Span().DontBox() );
- //
- // which turns the lambda return type back to "void" and eliminates the troublesome box instruction.
- //
- private static void DontBox<T>(this ReadOnlySpan<T> span)
- {
- // This space intentionally left blank.
- }
-
- [StructLayout(LayoutKind.Sequential)]
- private sealed class TestClass
- {
- private double _d;
- public char C0;
- public char C1;
- public char C2;
- public char C3;
- public char C4;
- }
- }
-}
-
diff --git a/src/System.Memory/tests/ReadOnlySpan/ToArray.cs b/src/System.Memory/tests/ReadOnlySpan/ToArray.cs
index 8053ced3be..7db9bfb284 100644
--- a/src/System.Memory/tests/ReadOnlySpan/ToArray.cs
+++ b/src/System.Memory/tests/ReadOnlySpan/ToArray.cs
@@ -3,7 +3,6 @@
// See the LICENSE file in the project root for more information.
using Xunit;
-using System.Runtime.CompilerServices;
namespace System.SpanTests
{
diff --git a/src/System.Memory/tests/Span/AsBytes.cs b/src/System.Memory/tests/Span/AsBytes.cs
index 7603ac7b88..0eabb23aba 100644
--- a/src/System.Memory/tests/Span/AsBytes.cs
+++ b/src/System.Memory/tests/Span/AsBytes.cs
@@ -24,7 +24,7 @@ namespace System.SpanTests
public static void AsBytesContainsReferences()
{
Span<StructWithReferences> span = new Span<StructWithReferences>(Array.Empty<StructWithReferences>());
- AssertThrows<ArgumentException, StructWithReferences>(span, (_span) => _span.AsBytes<StructWithReferences>().DontBox());
+ TestHelpers.AssertThrows<ArgumentException, StructWithReferences>(span, (_span) => _span.AsBytes().DontBox());
}
}
}
diff --git a/src/System.Memory/tests/Span/AsSpan.cs b/src/System.Memory/tests/Span/AsSpan.cs
index ce7f33451a..bce971839d 100644
--- a/src/System.Memory/tests/Span/AsSpan.cs
+++ b/src/System.Memory/tests/Span/AsSpan.cs
@@ -3,28 +3,36 @@
// See the LICENSE file in the project root for more information.
using Xunit;
-using System.Runtime.CompilerServices;
namespace System.SpanTests
{
public static partial class SpanTests
{
[Fact]
- public static void ArrayAsSpan()
+ public static void IntArrayAsSpan()
{
int[] a = { 91, 92, -93, 94 };
Span<int> spanInt = a.AsSpan();
- spanInt.Validate<int>(91, 92, -93, 94);
+ spanInt.Validate(91, 92, -93, 94);
+ }
+ [Fact]
+ public static void LongArrayAsSpan()
+ {
long[] b = { 91, -92, 93, 94, -95 };
Span<long> spanLong = b.AsSpan();
- spanLong.Validate<long>(91, -92, 93, 94, -95);
+ spanLong.Validate(91, -92, 93, 94, -95);
+ }
+ [ActiveIssue(23952, TargetFrameworkMonikers.UapAot)]
+ [Fact]
+ public static void ObjectArrayAsSpan()
+ {
object o1 = new object();
object o2 = new object();
object[] c = { o1, o2 };
Span<object> spanObject = c.AsSpan();
- spanObject.Validate<object>(o1, o2);
+ spanObject.ValidateReferenceType(o1, o2);
}
[Fact]
@@ -32,22 +40,31 @@ namespace System.SpanTests
{
int[] empty = Array.Empty<int>();
Span<int> span = empty.AsSpan();
- span.Validate<int>();
+ span.Validate();
}
[Fact]
- public static void ArraySegmentAsSpan()
+ public static void IntArraySegmentAsSpan()
{
int[] a = { 91, 92, -93, 94 };
ArraySegment<int> segmentInt = new ArraySegment<int>(a, 1, 2);
Span<int> spanInt = segmentInt.AsSpan();
- spanInt.Validate<int>(92, -93);
+ spanInt.Validate(92, -93);
+ }
+ [Fact]
+ public static void LongArraySegmentAsSpan()
+ {
long[] b = { 91, -92, 93, 94, -95 };
ArraySegment<long> segmentLong = new ArraySegment<long>(b, 1, 3);
Span<long> spanLong = segmentLong.AsSpan();
- spanLong.Validate<long>(-92, 93, 94);
+ spanLong.Validate(-92, 93, 94);
+ }
+ [ActiveIssue(23952, TargetFrameworkMonikers.UapAot)]
+ [Fact]
+ public static void ObjectArraySegmentAsSpan()
+ {
object o1 = new object();
object o2 = new object();
object o3 = new object();
@@ -55,7 +72,7 @@ namespace System.SpanTests
object[] c = { o1, o2, o3, o4 };
ArraySegment<object> segmentObject = new ArraySegment<object>(c, 1, 2);
Span<object> spanObject = segmentObject.AsSpan();
- spanObject.Validate<object>(o2, o3);
+ spanObject.ValidateReferenceType(o2, o3);
}
[Fact]
@@ -64,12 +81,12 @@ namespace System.SpanTests
int[] empty = Array.Empty<int>();
ArraySegment<int> segmentEmpty = new ArraySegment<int>(empty);
Span<int> spanEmpty = segmentEmpty.AsSpan();
- spanEmpty.Validate<int>();
+ spanEmpty.Validate();
int[] a = { 91, 92, -93, 94 };
ArraySegment<int> segmentInt = new ArraySegment<int>(a, 0, 0);
Span<int> spanInt = segmentInt.AsSpan();
- spanInt.Validate<int>();
+ spanInt.Validate();
}
}
}
diff --git a/src/System.Memory/tests/Span/Clear.cs b/src/System.Memory/tests/Span/Clear.cs
index 433143b6c9..ecd0c4a34f 100644
--- a/src/System.Memory/tests/Span/Clear.cs
+++ b/src/System.Memory/tests/Span/Clear.cs
@@ -4,6 +4,7 @@
using Xunit;
using System.Runtime.CompilerServices;
+using static System.TestHelpers;
namespace System.SpanTests
{
diff --git a/src/System.Memory/tests/Span/CopyTo.cs b/src/System.Memory/tests/Span/CopyTo.cs
index d547232f38..a626ad2a3b 100644
--- a/src/System.Memory/tests/Span/CopyTo.cs
+++ b/src/System.Memory/tests/Span/CopyTo.cs
@@ -92,7 +92,7 @@ namespace System.SpanTests
int[] dst = { 99, 100 };
Span<int> srcSpan = new Span<int>(src);
- AssertThrows<ArgumentException, int>(srcSpan, (_srcSpan) => _srcSpan.CopyTo(dst));
+ TestHelpers.AssertThrows<ArgumentException, int>(srcSpan, (_srcSpan) => _srcSpan.CopyTo(dst));
int[] expected = { 99, 100 };
Assert.Equal<int>(expected, dst); // CopyTo() checks for sufficient space before doing any copying.
}
@@ -177,7 +177,7 @@ namespace System.SpanTests
int[] src = { 1, 2, 3 };
int[] dst = { 99, 100 };
- AssertThrows<ArgumentException, int>(src, (_src) => _src.CopyTo(dst));
+ TestHelpers.AssertThrows<ArgumentException, int>(src, (_src) => _src.CopyTo(dst));
int[] expected = { 99, 100 };
Assert.Equal<int>(expected, dst); // CopyTo() checks for sufficient space before doing any copying.
}
diff --git a/src/System.Memory/tests/Span/CtorArray.cs b/src/System.Memory/tests/Span/CtorArray.cs
index 1fb981674c..7bd4dd32a5 100644
--- a/src/System.Memory/tests/Span/CtorArray.cs
+++ b/src/System.Memory/tests/Span/CtorArray.cs
@@ -21,10 +21,10 @@ namespace System.SpanTests
Span<int> span;
span = new Span<int>(a);
- span.Validate<int>(91, 92, -93, 94);
+ span.Validate(91, 92, -93, 94);
span = new Span<int>(a, 0, a.Length);
- span.Validate<int>(91, 92, -93, 94);
+ span.Validate(91, 92, -93, 94);
}
[Fact]
@@ -34,12 +34,13 @@ namespace System.SpanTests
Span<long> span;
span = new Span<long>(a);
- span.Validate<long>(91, -92, 93, 94, -95);
+ span.Validate(91, -92, 93, 94, -95);
span = new Span<long>(a, 0, a.Length);
- span.Validate<long>(91, -92, 93, 94, -95);
+ span.Validate(91, -92, 93, 94, -95);
}
+ [ActiveIssue(23952, TargetFrameworkMonikers.UapAot)]
[Fact]
public static void CtorArray3()
{
@@ -49,10 +50,10 @@ namespace System.SpanTests
Span<object> span;
span = new Span<object>(a);
- span.Validate<object>(o1, o2);
+ span.ValidateReferenceType(o1, o2);
span = new Span<object>(a, 0, a.Length);
- span.Validate<object>(o1, o2);
+ span.ValidateReferenceType(o1, o2);
}
[Fact]
@@ -62,17 +63,17 @@ namespace System.SpanTests
Span<int> span;
span = new Span<int>(empty);
- span.Validate<int>();
+ span.Validate();
span = new Span<int>(empty, 0, empty.Length);
- span.Validate<int>();
+ span.Validate();
}
[Fact]
public static void CtorArrayNullArray()
{
- Assert.Throws<ArgumentNullException>(() => new Span<int>((int[])null).DontBox());
- Assert.Throws<ArgumentNullException>(() => new Span<int>((int[])null, 0, 0).DontBox());
+ Assert.Throws<ArgumentNullException>(() => new Span<int>(null).DontBox());
+ Assert.Throws<ArgumentNullException>(() => new Span<int>(null, 0, 0).DontBox());
}
[Fact]
@@ -94,10 +95,10 @@ namespace System.SpanTests
Span<int> span;
span = new Span<int>(aAsIntArray);
- span.Validate<int>(42, -1);
+ span.Validate(42, -1);
span = new Span<int>(aAsIntArray, 0, aAsIntArray.Length);
- span.Validate<int>(42, -1);
+ span.Validate(42, -1);
}
}
}
diff --git a/src/System.Memory/tests/Span/CtorArrayIntInt.cs b/src/System.Memory/tests/Span/CtorArrayIntInt.cs
index 5618db5fbf..26a8c97eac 100644
--- a/src/System.Memory/tests/Span/CtorArrayIntInt.cs
+++ b/src/System.Memory/tests/Span/CtorArrayIntInt.cs
@@ -16,7 +16,7 @@ namespace System.SpanTests
{
int[] a = { 90, 91, 92, 93, 94, 95, 96, 97, 98 };
Span<int> span = new Span<int>(a, 3, 2);
- span.Validate<int>(93, 94);
+ span.Validate(93, 94);
}
[Fact]
@@ -24,7 +24,7 @@ namespace System.SpanTests
{
long[] a = { 90, 91, 92, 93, 94, 95, 96, 97, 98 };
Span<long> span = new Span<long>(a, 4, 3);
- span.Validate<long>(94, 95, 96);
+ span.Validate(94, 95, 96);
}
[Fact]
@@ -32,7 +32,7 @@ namespace System.SpanTests
{
long[] a = { 90, 91, 92, 93, 94, 95, 96, 97, 98 };
Span<long> span = new Span<long>(a, 4, 5);
- span.Validate<long>(94, 95, 96, 97, 98);
+ span.Validate(94, 95, 96, 97, 98);
}
[Fact]
@@ -73,7 +73,7 @@ namespace System.SpanTests
// Valid for start to equal the array length. This returns an empty span that starts "just past the array."
int[] a = { 91, 92, 93 };
Span<int> span = new Span<int>(a, 3, 0);
- span.Validate<int>();
+ span.Validate();
}
}
}
diff --git a/src/System.Memory/tests/Span/CtorPointerInt.cs b/src/System.Memory/tests/Span/CtorPointerInt.cs
index 600801b94e..2d11fa5829 100644
--- a/src/System.Memory/tests/Span/CtorPointerInt.cs
+++ b/src/System.Memory/tests/Span/CtorPointerInt.cs
@@ -20,8 +20,8 @@ namespace System.SpanTests
fixed (int *pa = a)
{
Span<int> span = new Span<int>(pa, 3);
- span.Validate<int>(90, 91, 92);
- Assert.True(Unsafe.AreSame<int>(ref Unsafe.AsRef<int>(pa), ref span.DangerousGetPinnableReference()));
+ span.Validate(90, 91, 92);
+ Assert.True(Unsafe.AreSame(ref Unsafe.AsRef<int>(pa), ref span.DangerousGetPinnableReference()));
}
}
}
@@ -32,8 +32,8 @@ namespace System.SpanTests
unsafe
{
Span<int> span = new Span<int>((void*)null, 0);
- span.Validate<int>();
- Assert.True(Unsafe.AreSame<int>(ref Unsafe.AsRef<int>((void*)null), ref span.DangerousGetPinnableReference()));
+ span.Validate();
+ Assert.True(Unsafe.AreSame(ref Unsafe.AsRef<int>((void*)null), ref span.DangerousGetPinnableReference()));
}
}
diff --git a/src/System.Memory/tests/Span/DangerousCreate.cs b/src/System.Memory/tests/Span/DangerousCreate.cs
index ea2715b9c5..f41fa1e9ec 100644
--- a/src/System.Memory/tests/Span/DangerousCreate.cs
+++ b/src/System.Memory/tests/Span/DangerousCreate.cs
@@ -3,8 +3,8 @@
// See the LICENSE file in the project root for more information.
using Xunit;
-using System.Runtime.InteropServices;
using System.Runtime.CompilerServices;
+using static System.TestHelpers;
namespace System.SpanTests
{
@@ -13,17 +13,19 @@ namespace System.SpanTests
[Fact]
public static void DangerousCreate1()
{
- TestClass testClass = new TestClass();
- testClass.C0 = 'a';
- testClass.C1 = 'b';
- testClass.C2 = 'c';
- testClass.C3 = 'd';
- testClass.C4 = 'e';
+ TestClass testClass = new TestClass
+ {
+ C0 = 'a',
+ C1 = 'b',
+ C2 = 'c',
+ C3 = 'd',
+ C4 = 'e'
+ };
Span<char> span = Span<char>.DangerousCreate(testClass, ref testClass.C1, 3);
- span.Validate<char>('b', 'c', 'd');
+ span.Validate('b', 'c', 'd');
ref char pc1 = ref span.DangerousGetPinnableReference();
- Assert.True(Unsafe.AreSame<char>(ref testClass.C1, ref pc1));
+ Assert.True(Unsafe.AreSame(ref testClass.C1, ref pc1));
}
}
}
diff --git a/src/System.Memory/tests/Span/DangerousGetPinnableReference.cs b/src/System.Memory/tests/Span/DangerousGetPinnableReference.cs
index 199e7048a3..11e0bcf31c 100644
--- a/src/System.Memory/tests/Span/DangerousGetPinnableReference.cs
+++ b/src/System.Memory/tests/Span/DangerousGetPinnableReference.cs
@@ -3,8 +3,8 @@
// See the LICENSE file in the project root for more information.
using Xunit;
-using System.Runtime.InteropServices;
using System.Runtime.CompilerServices;
+using static System.TestHelpers;
namespace System.SpanTests
{
@@ -16,7 +16,7 @@ namespace System.SpanTests
int[] a = { 91, 92, 93, 94, 95 };
Span<int> span = new Span<int>(a, 1, 3);
ref int pinnableReference = ref span.DangerousGetPinnableReference();
- Assert.True(Unsafe.AreSame<int>(ref a[1], ref pinnableReference));
+ Assert.True(Unsafe.AreSame(ref a[1], ref pinnableReference));
}
[Fact]
@@ -29,7 +29,7 @@ namespace System.SpanTests
Span<int> span = new Span<int>(a, a.Length, 0);
ref int pinnableReference = ref span.DangerousGetPinnableReference();
ref int expected = ref Unsafe.Add<int>(ref a[a.Length - 1], 1);
- Assert.True(Unsafe.AreSame<int>(ref expected, ref pinnableReference));
+ Assert.True(Unsafe.AreSame(ref expected, ref pinnableReference));
}
[Fact]
@@ -40,7 +40,7 @@ namespace System.SpanTests
int i = 42;
Span<int> span = new Span<int>(&i, 1);
ref int pinnableReference = ref span.DangerousGetPinnableReference();
- Assert.True(Unsafe.AreSame<int>(ref i, ref pinnableReference));
+ Assert.True(Unsafe.AreSame(ref i, ref pinnableReference));
}
}
@@ -51,7 +51,7 @@ namespace System.SpanTests
Span<char> span = Span<char>.DangerousCreate(testClass, ref testClass.C1, 3);
ref char pinnableReference = ref span.DangerousGetPinnableReference();
- Assert.True(Unsafe.AreSame<char>(ref testClass.C1, ref pinnableReference));
+ Assert.True(Unsafe.AreSame(ref testClass.C1, ref pinnableReference));
}
[Fact]
@@ -61,7 +61,7 @@ namespace System.SpanTests
{
Span<int> span = Span<int>.Empty;
ref int pinnableReference = ref span.DangerousGetPinnableReference();
- Assert.True(Unsafe.AreSame<int>(ref Unsafe.AsRef<int>(null), ref pinnableReference));
+ Assert.True(Unsafe.AreSame(ref Unsafe.AsRef<int>(null), ref pinnableReference));
}
}
}
diff --git a/src/System.Memory/tests/Span/Empty.cs b/src/System.Memory/tests/Span/Empty.cs
index 50e2e5196b..8d8d1a4dc7 100644
--- a/src/System.Memory/tests/Span/Empty.cs
+++ b/src/System.Memory/tests/Span/Empty.cs
@@ -19,7 +19,7 @@ namespace System.SpanTests
{
ref int expected = ref Unsafe.AsRef<int>(null);
ref int actual = ref empty.DangerousGetPinnableReference();
- Assert.True(Unsafe.AreSame<int>(ref expected, ref actual));
+ Assert.True(Unsafe.AreSame(ref expected, ref actual));
}
}
}
diff --git a/src/System.Memory/tests/Span/Fill.cs b/src/System.Memory/tests/Span/Fill.cs
index 4976bd815f..929ebede79 100644
--- a/src/System.Memory/tests/Span/Fill.cs
+++ b/src/System.Memory/tests/Span/Fill.cs
@@ -4,6 +4,7 @@
using System.Runtime.InteropServices;
using Xunit;
+using static System.TestHelpers;
namespace System.SpanTests
{
diff --git a/src/System.Memory/tests/Span/IndexOf.T.cs b/src/System.Memory/tests/Span/IndexOf.T.cs
index b3b197a725..8d9736be83 100644
--- a/src/System.Memory/tests/Span/IndexOf.T.cs
+++ b/src/System.Memory/tests/Span/IndexOf.T.cs
@@ -80,7 +80,7 @@ namespace System.SpanTests
foreach (TInt elem in a)
{
int numCompares = log.CountCompares(elem.Value, 9999);
- Assert.True(numCompares == 1);
+ Assert.True(numCompares == 1, $"Expected {numCompares} == 1 for element {elem.Value}.");
}
}
}
diff --git a/src/System.Memory/tests/Span/IndexOf.byte.cs b/src/System.Memory/tests/Span/IndexOf.byte.cs
index c6014cf3a1..265bda555d 100644
--- a/src/System.Memory/tests/Span/IndexOf.byte.cs
+++ b/src/System.Memory/tests/Span/IndexOf.byte.cs
@@ -193,7 +193,7 @@ namespace System.SpanTests
}
var found = span[index];
- Assert.Equal((byte)expectResult, (byte)found);
+ Assert.Equal((byte)expectResult, found);
Assert.Equal(expectIndex, index);
}
diff --git a/src/System.Memory/tests/Span/NonPortableCast.cs b/src/System.Memory/tests/Span/NonPortableCast.cs
index 0927ebb888..18b80f7b49 100644
--- a/src/System.Memory/tests/Span/NonPortableCast.cs
+++ b/src/System.Memory/tests/Span/NonPortableCast.cs
@@ -24,14 +24,14 @@ namespace System.SpanTests
public static void PortableCastToTypeContainsReferences()
{
Span<uint> span = new Span<uint>(Array.Empty<uint>());
- AssertThrows<ArgumentException, uint>(span, (_span) => _span.NonPortableCast<uint, StructWithReferences>().DontBox());
+ TestHelpers.AssertThrows<ArgumentException, uint>(span, (_span) => _span.NonPortableCast<uint, StructWithReferences>().DontBox());
}
[Fact]
public static void PortableCastFromTypeContainsReferences()
{
Span<StructWithReferences> span = new Span<StructWithReferences>(Array.Empty<StructWithReferences>());
- AssertThrows<ArgumentException, StructWithReferences>(span, (_span) => _span.NonPortableCast<StructWithReferences, uint>().DontBox());
+ TestHelpers.AssertThrows<ArgumentException, StructWithReferences>(span, (_span) => _span.NonPortableCast<StructWithReferences, uint>().DontBox());
}
}
}
diff --git a/src/System.Memory/tests/Span/Overflow.cs b/src/System.Memory/tests/Span/Overflow.cs
index e5335a0f9e..b9f9070f1b 100644
--- a/src/System.Memory/tests/Span/Overflow.cs
+++ b/src/System.Memory/tests/Span/Overflow.cs
@@ -3,7 +3,6 @@
// See the LICENSE file in the project root for more information.
using Xunit;
-using System.Runtime.InteropServices;
using System.Runtime.CompilerServices;
namespace System.SpanTests
@@ -41,7 +40,7 @@ namespace System.SpanTests
int bigIndex = checked(GuidTwoGiBLimit + 1);
uint byteOffset = checked((uint)bigIndex * (uint)sizeof(Guid));
- Assert.True(byteOffset > (uint)int.MaxValue); // Make sure byteOffset actually overflows 2Gb, or this test is pointless.
+ Assert.True(byteOffset > int.MaxValue); // Make sure byteOffset actually overflows 2Gb, or this test is pointless.
ref Guid expected = ref Unsafe.Add<Guid>(ref memory, bigIndex);
Assert.True(Unsafe.AreSame<Guid>(ref expected, ref span[bigIndex]));
diff --git a/src/System.Memory/tests/Span/SequenceEqual.T.cs b/src/System.Memory/tests/Span/SequenceEqual.T.cs
index 5f88a1acce..9444cac7d8 100644
--- a/src/System.Memory/tests/Span/SequenceEqual.T.cs
+++ b/src/System.Memory/tests/Span/SequenceEqual.T.cs
@@ -64,7 +64,7 @@ namespace System.SpanTests
foreach (TInt elem in first)
{
int numCompares = log.CountCompares(elem.Value, elem.Value);
- Assert.True(numCompares == 1);
+ Assert.True(numCompares == 1, $"Expected {numCompares} == 1 for element {elem.Value}.");
}
}
}
diff --git a/src/System.Memory/tests/Span/Slice.cs b/src/System.Memory/tests/Span/Slice.cs
index e15f4cb2bb..968f66ca00 100644
--- a/src/System.Memory/tests/Span/Slice.cs
+++ b/src/System.Memory/tests/Span/Slice.cs
@@ -15,7 +15,7 @@ namespace System.SpanTests
int[] a = { 90, 91, 92, 93, 94, 95, 96, 97, 98, 99 };
Span<int> span = new Span<int>(a).Slice(6);
Assert.Equal(4, span.Length);
- Assert.True(Unsafe.AreSame<int>(ref a[6], ref span.DangerousGetPinnableReference()));
+ Assert.True(Unsafe.AreSame(ref a[6], ref span.DangerousGetPinnableReference()));
}
[Fact]
@@ -24,7 +24,7 @@ namespace System.SpanTests
int[] a = { 90, 91, 92, 93, 94, 95, 96, 97, 98, 99 };
Span<int> span = new Span<int>(a).Slice(a.Length);
Assert.Equal(0, span.Length);
- Assert.True(Unsafe.AreSame<int>(ref a[a.Length - 1], ref Unsafe.Subtract<int>(ref span.DangerousGetPinnableReference(), 1)));
+ Assert.True(Unsafe.AreSame(ref a[a.Length - 1], ref Unsafe.Subtract<int>(ref span.DangerousGetPinnableReference(), 1)));
}
[Fact]
@@ -33,7 +33,7 @@ namespace System.SpanTests
int[] a = { 90, 91, 92, 93, 94, 95, 96, 97, 98, 99 };
Span<int> span = new Span<int>(a).Slice(3, 5);
Assert.Equal(5, span.Length);
- Assert.True(Unsafe.AreSame<int>(ref a[3], ref span.DangerousGetPinnableReference()));
+ Assert.True(Unsafe.AreSame(ref a[3], ref span.DangerousGetPinnableReference()));
}
[Fact]
@@ -42,7 +42,7 @@ namespace System.SpanTests
int[] a = { 90, 91, 92, 93, 94, 95, 96, 97, 98, 99 };
Span<int> span = new Span<int>(a).Slice(4, 6);
Assert.Equal(6, span.Length);
- Assert.True(Unsafe.AreSame<int>(ref a[4], ref span.DangerousGetPinnableReference()));
+ Assert.True(Unsafe.AreSame(ref a[4], ref span.DangerousGetPinnableReference()));
}
[Fact]
@@ -51,7 +51,7 @@ namespace System.SpanTests
int[] a = { 90, 91, 92, 93, 94, 95, 96, 97, 98, 99 };
Span<int> span = new Span<int>(a).Slice(a.Length, 0);
Assert.Equal(0, span.Length);
- Assert.True(Unsafe.AreSame<int>(ref a[a.Length - 1], ref Unsafe.Subtract<int>(ref span.DangerousGetPinnableReference(), 1)));
+ Assert.True(Unsafe.AreSame(ref a[a.Length - 1], ref Unsafe.Subtract<int>(ref span.DangerousGetPinnableReference(), 1)));
}
[Fact]
diff --git a/src/System.Memory/tests/Span/StartsWith.T.cs b/src/System.Memory/tests/Span/StartsWith.T.cs
index ec7e46c469..c13e777c25 100644
--- a/src/System.Memory/tests/Span/StartsWith.T.cs
+++ b/src/System.Memory/tests/Span/StartsWith.T.cs
@@ -85,7 +85,7 @@ namespace System.SpanTests
foreach (TInt elem in first)
{
int numCompares = log.CountCompares(elem.Value, elem.Value);
- Assert.True(numCompares == 1);
+ Assert.True(numCompares == 1, $"Expected {numCompares} == 1 for element {elem.Value}.");
}
}
}
diff --git a/src/System.Memory/tests/Span/TestHelpers.cs b/src/System.Memory/tests/Span/TestHelpers.cs
deleted file mode 100644
index 0e00c970cd..0000000000
--- a/src/System.Memory/tests/Span/TestHelpers.cs
+++ /dev/null
@@ -1,95 +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;
-using System.Runtime.InteropServices;
-
-namespace System.SpanTests
-{
- public static partial class SpanTests
- {
- private static void Validate<T>(this Span<T> span, params T[] expected)
- {
- bool isValueType = default(T) != null || Nullable.GetUnderlyingType(typeof(T)) != null;
- Assert.Equal(span.Length, expected.Length);
- for (int i = 0; i < expected.Length; i++)
- {
- T actual = span[i];
- if (isValueType)
- Assert.Equal(expected[i], actual);
- else
- Assert.Same(expected[i], actual);
- }
-
- object ignore;
- AssertThrows<IndexOutOfRangeException, T>(span, (_span) => ignore = _span[expected.Length]);
- }
-
- private delegate void AssertThrowsAction<T>(Span<T> span);
-
- // Cannot use standard Assert.Throws() when testing Span - Span and closures don't get along.
- private static void AssertThrows<E, T>(Span<T> span, AssertThrowsAction<T> action) where E:Exception
- {
- try
- {
- action(span);
- Assert.False(true, "Expected exception: " + typeof(E).GetType());
- }
- catch (E)
- {
- }
- catch (Exception wrongException)
- {
- Assert.False(true, "Wrong exception thrown: Expected " + typeof(E).GetType() + ": Actual: " + wrongException.GetType());
- }
- }
-
- //
- // The innocent looking construct:
- //
- // Assert.Throws<E>( () => new Span() );
- //
- // generates a hidden box of the Span as the return value of the lambda. This makes the IL illegal and unloadable on
- // runtimes that enforce the actual Span rules (never mind that we expect never to reach the box instruction...)
- //
- // The workaround is to code it like this:
- //
- // Assert.Throws<E>( () => new Span().DontBox() );
- //
- // which turns the lambda return type back to "void" and eliminates the troublesome box instruction.
- //
- private static void DontBox<T>(this Span<T> span)
- {
- // This space intentionally left blank.
- }
-
- [StructLayout(LayoutKind.Sequential)]
- private sealed class TestClass
- {
- private double _d;
- public char C0;
- public char C1;
- public char C2;
- public char C3;
- public char C4;
- }
-
- [StructLayout(LayoutKind.Sequential)]
- private struct TestValueTypeWithReference
- {
- public int I;
- public string S;
- }
-
- private enum TestEnum
- {
- e0,
- e1,
- e2,
- e3,
- e4,
- }
- }
-}
-
diff --git a/src/System.Memory/tests/Span/ToArray.cs b/src/System.Memory/tests/Span/ToArray.cs
index ecabef0684..5561acdbe3 100644
--- a/src/System.Memory/tests/Span/ToArray.cs
+++ b/src/System.Memory/tests/Span/ToArray.cs
@@ -3,7 +3,6 @@
// See the LICENSE file in the project root for more information.
using Xunit;
-using System.Runtime.CompilerServices;
namespace System.SpanTests
{
diff --git a/src/System.Memory/tests/System.Memory.Tests.csproj b/src/System.Memory/tests/System.Memory.Tests.csproj
index eaca378048..cb78a8db24 100644
--- a/src/System.Memory/tests/System.Memory.Tests.csproj
+++ b/src/System.Memory/tests/System.Memory.Tests.csproj
@@ -12,6 +12,7 @@
<ItemGroup>
<Compile Include="AllocationHelper.cs" />
<Compile Include="TInt.cs" />
+ <Compile Include="TestHelpers.cs" />
</ItemGroup>
<ItemGroup>
<Compile Include="Span\AsBytes.cs" />
@@ -42,13 +43,11 @@
<Compile Include="Span\Slice.cs" />
<Compile Include="Span\StartsWith.T.cs" />
<Compile Include="Span\StartsWith.byte.cs" />
- <Compile Include="Span\TestHelpers.cs" />
<Compile Include="Span\ToArray.cs" />
</ItemGroup>
<ItemGroup>
<Compile Include="ReadOnlySpan\AsBytes.cs" />
<Compile Include="ReadOnlySpan\AsReadOnlySpan.cs" />
- <Compile Include="ReadOnlySpan\AsSpan.cs" />
<Compile Include="ReadOnlySpan\CopyTo.cs" />
<Compile Include="ReadOnlySpan\CtorArray.cs" />
<Compile Include="ReadOnlySpan\CtorArrayIntInt.cs" />
@@ -72,8 +71,35 @@
<Compile Include="ReadOnlySpan\Slice.cs" />
<Compile Include="ReadOnlySpan\StartsWith.T.cs" />
<Compile Include="ReadOnlySpan\StartsWith.byte.cs" />
- <Compile Include="ReadOnlySpan\TestHelpers.cs" />
<Compile Include="ReadOnlySpan\ToArray.cs" />
</ItemGroup>
+ <ItemGroup>
+ <Compile Include="Memory\CtorArray.cs" />
+ <Compile Include="Memory\CtorArrayIntInt.cs" />
+ <Compile Include="Memory\CustomMemoryForTest.cs" />
+ <Compile Include="Memory\Empty.cs" />
+ <Compile Include="Memory\Equality.cs" />
+ <Compile Include="Memory\GetHashCode.cs" />
+ <Compile Include="Memory\ImplicitConversion.cs" />
+ <Compile Include="Memory\OwnedMemory.cs" />
+ <Compile Include="Memory\Retain.cs" />
+ <Compile Include="Memory\Slice.cs" />
+ <Compile Include="Memory\Span.cs" />
+ <Compile Include="Memory\ToArray.cs" />
+ <Compile Include="Memory\TryGetArray.cs" />
+ </ItemGroup>
+ <ItemGroup>
+ <Compile Include="ReadOnlyMemory\CtorArray.cs" />
+ <Compile Include="ReadOnlyMemory\CtorArrayIntInt.cs" />
+ <Compile Include="ReadOnlyMemory\DangerousTryGetArray.cs" />
+ <Compile Include="ReadOnlyMemory\Empty.cs" />
+ <Compile Include="ReadOnlyMemory\Equality.cs" />
+ <Compile Include="ReadOnlyMemory\GetHashCode.cs" />
+ <Compile Include="ReadOnlyMemory\ImplicitConversion.cs" />
+ <Compile Include="ReadOnlyMemory\Retain.cs" />
+ <Compile Include="ReadOnlyMemory\Slice.cs" />
+ <Compile Include="ReadOnlyMemory\Span.cs" />
+ <Compile Include="ReadOnlyMemory\ToArray.cs" />
+ </ItemGroup>
<Import Project="$([MSBuild]::GetDirectoryNameOfFileAbove($(MSBuildThisFileDirectory), dir.targets))\dir.targets" />
</Project> \ No newline at end of file
diff --git a/src/System.Memory/tests/TInt.cs b/src/System.Memory/tests/TInt.cs
index e4a74643ab..e6dba18fe8 100644
--- a/src/System.Memory/tests/TInt.cs
+++ b/src/System.Memory/tests/TInt.cs
@@ -5,8 +5,6 @@
using System.Collections.Generic;
using System.Linq;
-using Xunit;
-
#pragma warning disable 0809 //warning CS0809: Obsolete member overrides non-obsolete member
namespace System
diff --git a/src/System.Memory/tests/TestHelpers.cs b/src/System.Memory/tests/TestHelpers.cs
new file mode 100644
index 0000000000..7b46964a25
--- /dev/null
+++ b/src/System.Memory/tests/TestHelpers.cs
@@ -0,0 +1,184 @@
+// 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 System.Runtime.InteropServices;
+
+namespace System
+{
+ public static class TestHelpers
+ {
+ public static void Validate<T>(this Span<T> span, params T[] expected) where T : struct, IEquatable<T>
+ {
+ Assert.True(span.SequenceEqual(expected));
+ }
+
+ public static void ValidateReferenceType<T>(this Span<T> span, params T[] expected)
+ {
+ Assert.Equal(span.Length, expected.Length);
+ for (int i = 0; i < expected.Length; i++)
+ {
+ T actual = span[i];
+ Assert.Same(expected[i], actual);
+ }
+
+ T ignore;
+ AssertThrows<IndexOutOfRangeException, T>(span, (_span) => ignore = _span[expected.Length]);
+ }
+
+ public delegate void AssertThrowsAction<T>(Span<T> span);
+
+ // Cannot use standard Assert.Throws() when testing Span - Span and closures don't get along.
+ public static void AssertThrows<E, T>(Span<T> span, AssertThrowsAction<T> action) where E:Exception
+ {
+ try
+ {
+ action(span);
+ Assert.False(true, "Expected exception: " + typeof(E).GetType());
+ }
+ catch (E)
+ {
+ }
+ catch (Exception wrongException)
+ {
+ Assert.False(true, "Wrong exception thrown: Expected " + typeof(E).GetType() + ": Actual: " + wrongException.GetType());
+ }
+ }
+
+ //
+ // The innocent looking construct:
+ //
+ // Assert.Throws<E>( () => new Span() );
+ //
+ // generates a hidden box of the Span as the return value of the lambda. This makes the IL illegal and unloadable on
+ // runtimes that enforce the actual Span rules (never mind that we expect never to reach the box instruction...)
+ //
+ // The workaround is to code it like this:
+ //
+ // Assert.Throws<E>( () => new Span().DontBox() );
+ //
+ // which turns the lambda return type back to "void" and eliminates the troublesome box instruction.
+ //
+ public static void DontBox<T>(this Span<T> span)
+ {
+ // This space intentionally left blank.
+ }
+
+ public static void Validate<T>(this ReadOnlySpan<T> span, params T[] expected) where T : struct, IEquatable<T>
+ {
+ Assert.True(span.SequenceEqual(expected));
+ }
+
+ public static void ValidateReferenceType<T>(this ReadOnlySpan<T> span, params T[] expected)
+ {
+ Assert.Equal(span.Length, expected.Length);
+ for (int i = 0; i < expected.Length; i++)
+ {
+ T actual = span[i];
+ Assert.Same(expected[i], actual);
+ }
+
+ T ignore;
+ AssertThrows<IndexOutOfRangeException, T>(span, (_span) => ignore = _span[expected.Length]);
+ }
+
+ public delegate void AssertThrowsActionReadOnly<T>(ReadOnlySpan<T> span);
+
+ // Cannot use standard Assert.Throws() when testing Span - Span and closures don't get along.
+ public static void AssertThrows<E, T>(ReadOnlySpan<T> span, AssertThrowsActionReadOnly<T> action) where E:Exception
+ {
+ try
+ {
+ action(span);
+ Assert.False(true, "Expected exception: " + typeof(E).GetType());
+ }
+ catch (E)
+ {
+ }
+ catch (Exception wrongException)
+ {
+ Assert.False(true, "Wrong exception thrown: Expected " + typeof(E).GetType() + ": Actual: " + wrongException.GetType());
+ }
+ }
+
+ //
+ // The innocent looking construct:
+ //
+ // Assert.Throws<E>( () => new Span() );
+ //
+ // generates a hidden box of the Span as the return value of the lambda. This makes the IL illegal and unloadable on
+ // runtimes that enforce the actual Span rules (never mind that we expect never to reach the box instruction...)
+ //
+ // The workaround is to code it like this:
+ //
+ // Assert.Throws<E>( () => new Span().DontBox() );
+ //
+ // which turns the lambda return type back to "void" and eliminates the troublesome box instruction.
+ //
+ public static void DontBox<T>(this ReadOnlySpan<T> span)
+ {
+ // This space intentionally left blank.
+ }
+
+ public static void Validate<T>(this Memory<T> memory, params T[] expected) where T : struct, IEquatable<T>
+ {
+ Assert.True(memory.Span.SequenceEqual(expected));
+ }
+
+ public static void ValidateReferenceType<T>(this Memory<T> memory, params T[] expected)
+ {
+ T[] bufferArray = memory.ToArray();
+ Assert.Equal(memory.Length, expected.Length);
+ for (int i = 0; i < expected.Length; i++)
+ {
+ T actual = bufferArray[i];
+ Assert.Same(expected[i], actual);
+ }
+ }
+
+ public static void Validate<T>(this ReadOnlyMemory<T> memory, params T[] expected) where T : struct, IEquatable<T>
+ {
+ Assert.True(memory.Span.SequenceEqual(expected));
+ }
+
+ public static void ValidateReferenceType<T>(this ReadOnlyMemory<T> memory, params T[] expected)
+ {
+ T[] bufferArray = memory.ToArray();
+ Assert.Equal(memory.Length, expected.Length);
+ for (int i = 0; i < expected.Length; i++)
+ {
+ T actual = bufferArray[i];
+ Assert.Same(expected[i], actual);
+ }
+ }
+
+ [StructLayout(LayoutKind.Sequential)]
+ public sealed class TestClass
+ {
+ private double _d;
+ public char C0;
+ public char C1;
+ public char C2;
+ public char C3;
+ public char C4;
+ }
+
+ [StructLayout(LayoutKind.Sequential)]
+ public struct TestValueTypeWithReference
+ {
+ public int I;
+ public string S;
+ }
+
+ public enum TestEnum
+ {
+ e0,
+ e1,
+ e2,
+ e3,
+ e4,
+ }
+ }
+}
+
diff --git a/src/System.Net.Http.WinHttpHandler/src/System.Net.Http.WinHttpHandler.csproj b/src/System.Net.Http.WinHttpHandler/src/System.Net.Http.WinHttpHandler.csproj
index 4c0e2e8e3a..78b6c50387 100644
--- a/src/System.Net.Http.WinHttpHandler/src/System.Net.Http.WinHttpHandler.csproj
+++ b/src/System.Net.Http.WinHttpHandler/src/System.Net.Http.WinHttpHandler.csproj
@@ -35,6 +35,9 @@
<Compile Include="$(CommonPath)\System\Net\HttpVersionInternal.cs">
<Link>Common\System\Net\HttpVersionInternal.cs</Link>
</Compile>
+ <Compile Include="$(CommonPath)\System\Net\Logging\NetEventSource.Common.cs">
+ <Link>Common\System\Net\Logging\NetEventSource.Common.cs</Link>
+ </Compile>
</ItemGroup>
<ItemGroup>
<Reference Include="System.Buffers" />
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 2661bfcf9b..eca0378858 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
@@ -5,11 +5,13 @@
</PropertyGroup>
<ItemGroup>
<CompileItem Include="$(CommonPath)\Interop\Windows\Interop.Libraries.cs" />
+ <CompileItem Include="$(CommonPath)\Interop\Windows\Crypt32\Interop.CertEnumCertificatesInStore.cs" />
<CompileItem Include="$(CommonPath)\Interop\Windows\Crypt32\Interop.certificates_types.cs" />
<CompileItem Include="$(CommonPath)\Interop\Windows\Crypt32\Interop.certificates.cs" />
<CompileItem Include="$(CommonPath)\Interop\Windows\kernel32\Interop.FormatMessage.cs" />
<CompileItem Include="$(CommonPath)\Interop\Windows\kernel32\Interop.GetModuleHandle.cs" />
<CompileItem Include="$(CommonPath)\Interop\Windows\Interop.HRESULT_FROM_WIN32.cs" />
+ <CompileItem Include="$(CommonPath)\Interop\Windows\SChannel\UnmanagedCertificateContext.IntPtr.cs" />
<CompileItem Include="$(CommonPath)\Interop\Windows\winhttp\Interop.SafeWinHttpHandle.cs" />
<CompileItem Include="$(CommonPath)\Interop\Windows\winhttp\Interop.winhttp_types.cs" />
<CompileItem Include="$(CommonPath)\Interop\Windows\winhttp\Interop.winhttp.cs" />
@@ -17,8 +19,8 @@
<CompileItem Include="$(CommonPath)\System\StringExtensions.cs" />
<CompileItem Include="$(CommonPath)\System\Net\HttpKnownHeaderNames.cs" />
<CompileItem Include="$(CommonPath)\System\Net\HttpKnownHeaderNames.TryGetHeaderName.cs" />
- <CompileItem Include="$(CommonPath)\System\Net\UriScheme.cs" />
<CompileItem Include="$(CommonPath)\System\Net\SecurityProtocol.cs" />
+ <CompileItem Include="$(CommonPath)\System\Net\UriScheme.cs" />
<CompileItem Include="$(CommonPath)\System\Net\Http\HttpHandlerDefaults.cs" />
<CompileItem Include="$(CommonPath)\System\Net\Http\NoWriteNoSeekStreamContent.cs" />
<CompileItem Include="$(CommonPath)\System\Net\Http\WinHttpException.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 6868120114..ca315bcf41 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
@@ -16,6 +16,7 @@ namespace System.Net.Http
// TODO: Issue #2165. Merge with similar code used in System.Net.Security move to Common/src//System/Net.
public static void BuildChain(
X509Certificate2 certificate,
+ X509Certificate2Collection remoteCertificateStore,
string hostName,
bool checkCertificateRevocationList,
out X509Chain chain,
@@ -32,6 +33,19 @@ namespace System.Net.Http
// Authenticate the remote party: (e.g. when operating in client mode, authenticate the server).
chain.ChainPolicy.ApplicationPolicy.Add(s_serverAuthOid);
+ if (remoteCertificateStore.Count > 0)
+ {
+ if (WinHttpTraceHelper.IsTraceEnabled())
+ {
+ foreach (X509Certificate cert in remoteCertificateStore)
+ {
+ WinHttpTraceHelper.Trace("WinHttpCertificateHelper.BuildChain: adding cert to ExtraStore: {0}", cert.Subject);
+ }
+ }
+
+ chain.ChainPolicy.ExtraStore.AddRange(remoteCertificateStore);
+ }
+
if (!chain.Build(certificate))
{
sslPolicyErrors |= SslPolicyErrors.RemoteCertificateChainErrors;
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 636229ad3f..7bea4857cb 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
@@ -258,7 +258,11 @@ namespace System.Net.Http
throw WinHttpException.CreateExceptionUsingError(lastError);
}
-
+
+ // Get any additional certificates sent from the remote server during the TLS/SSL handshake.
+ X509Certificate2Collection remoteCertificateStore =
+ UnmanagedCertificateContext.GetRemoteCertificatesFromStoreContext(certHandle);
+
// Create a managed wrapper around the certificate handle. Since this results in duplicating
// the handle, we will close the original handle after creating the wrapper.
var serverCertificate = new X509Certificate2(certHandle);
@@ -266,26 +270,28 @@ namespace System.Net.Http
X509Chain chain = null;
SslPolicyErrors sslPolicyErrors;
+ bool result = false;
try
{
WinHttpCertificateHelper.BuildChain(
serverCertificate,
+ remoteCertificateStore,
state.RequestMessage.RequestUri.Host,
state.CheckCertificateRevocationList,
out chain,
out sslPolicyErrors);
- bool result = state.ServerCertificateValidationCallback(
+ result = state.ServerCertificateValidationCallback(
state.RequestMessage,
serverCertificate,
chain,
sslPolicyErrors);
- if (!result)
- {
- throw WinHttpException.CreateExceptionUsingError(
- (int)Interop.WinHttp.ERROR_WINHTTP_SECURE_FAILURE);
- }
+ }
+ catch (Exception ex)
+ {
+ throw WinHttpException.CreateExceptionUsingError(
+ (int)Interop.WinHttp.ERROR_WINHTTP_SECURE_FAILURE, ex);
}
finally
{
@@ -296,6 +302,12 @@ namespace System.Net.Http
serverCertificate.Dispose();
}
+
+ if (!result)
+ {
+ throw WinHttpException.CreateExceptionUsingError(
+ (int)Interop.WinHttp.ERROR_WINHTTP_SECURE_FAILURE);
+ }
}
}
diff --git a/src/System.Net.Http.WinHttpHandler/tests/FunctionalTests/ServerCertificateTest.cs b/src/System.Net.Http.WinHttpHandler/tests/FunctionalTests/ServerCertificateTest.cs
index 7b7857172f..0aad931e89 100644
--- a/src/System.Net.Http.WinHttpHandler/tests/FunctionalTests/ServerCertificateTest.cs
+++ b/src/System.Net.Http.WinHttpHandler/tests/FunctionalTests/ServerCertificateTest.cs
@@ -111,14 +111,16 @@ namespace System.Net.Http.WinHttpHandlerFunctional.Tests
[OuterLoop] // TODO: Issue #11345
[Fact]
- public async Task UseCallback_CallbackThrowsSpecificException_ThrowsInnerSpecificException()
+ public async Task UseCallback_CallbackThrowsSpecificException_SpecificExceptionPropagatesAsBaseException()
{
var handler = new WinHttpHandler();
handler.ServerCertificateValidationCallback = CustomServerCertificateValidationCallback;
using (var client = new HttpClient(handler))
{
_validationCallbackHistory.ThrowException = true;
- await Assert.ThrowsAsync<CustomException>(() => client.GetAsync(System.Net.Test.Common.Configuration.Http.SecureRemoteEchoServer));
+ HttpRequestException ex = await Assert.ThrowsAsync<HttpRequestException>(() =>
+ client.GetAsync(System.Net.Test.Common.Configuration.Http.SecureRemoteEchoServer));
+ Assert.True(ex.GetBaseException() is CustomException);
}
}
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 9892003c2a..871e66692e 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
@@ -19,12 +19,18 @@
<Compile Include="$(CommonPath)\Interop\Windows\Interop.Libraries.cs">
<Link>Common\Interop\Windows\Interop.Libraries.cs</Link>
</Compile>
+ <Compile Include="$(CommonPath)\Interop\Windows\Crypt32\Interop.CertEnumCertificatesInStore.cs">
+ <Link>Common\Interop\Windows\Crypt32\Interop.CertEnumCertificatesInStore.cs</Link>
+ </Compile>
<Compile Include="$(CommonPath)\Interop\Windows\Crypt32\Interop.certificates_types.cs">
<Link>Common\Interop\Windows\Crypt32\Interop.certificates_types.cs</Link>
</Compile>
<Compile Include="$(CommonPath)\Interop\Windows\Interop.HRESULT_FROM_WIN32.cs">
<Link>Common\Interop\Windows\Interop.HRESULT_FROM_WIN32.cs</Link>
</Compile>
+ <Compile Include="$(CommonPath)\Interop\Windows\SChannel\UnmanagedCertificateContext.IntPtr.cs">
+ <Link>Common\Interop\Windows\SChannel\UnmanagedCertificateContext.IntPtr.cs</Link>
+ </Compile>
<Compile Include="$(CommonPath)\Interop\Windows\winhttp\Interop.SafeWinHttpHandle.cs">
<Link>Common\Interop\Windows\winhttp\Interop.SafeWinHttpHandle.cs</Link>
</Compile>
@@ -52,6 +58,9 @@
<Compile Include="$(CommonPath)\System\Net\HttpVersionInternal.cs">
<Link>Common\System\Net\HttpVersionInternal.cs</Link>
</Compile>
+ <Compile Include="$(CommonPath)\System\Net\Logging\NetEventSource.Common.cs">
+ <Link>Common\System\Net\Logging\NetEventSource.Common.cs</Link>
+ </Compile>
<Compile Include="$(CommonPath)\System\Net\UriScheme.cs">
<Link>Common\System\Net\UriScheme.cs</Link>
</Compile>
diff --git a/src/System.Net.Http/ref/System.Net.Http.cs b/src/System.Net.Http/ref/System.Net.Http.cs
index e3c4085fc4..c4ad870c81 100644
--- a/src/System.Net.Http/ref/System.Net.Http.cs
+++ b/src/System.Net.Http/ref/System.Net.Http.cs
@@ -225,6 +225,12 @@ namespace System.Net.Http
public void Add(System.Net.Http.HttpContent content, string name) { }
public void Add(System.Net.Http.HttpContent content, string name, string fileName) { }
}
+ public sealed partial class ReadOnlyMemoryContent : System.Net.Http.HttpContent
+ {
+ public ReadOnlyMemoryContent(System.ReadOnlyMemory<byte> content) { }
+ protected override System.Threading.Tasks.Task SerializeToStreamAsync(System.IO.Stream stream, System.Net.TransportContext context) => throw null;
+ protected internal override bool TryComputeLength(out long length) => throw null;
+ }
public partial class StreamContent : System.Net.Http.HttpContent
{
public StreamContent(System.IO.Stream content) { }
diff --git a/src/System.Net.Http/src/HttpDiagnosticsGuide.md b/src/System.Net.Http/src/HttpDiagnosticsGuide.md
index 145da9de5b..50aba47b65 100644
--- a/src/System.Net.Http/src/HttpDiagnosticsGuide.md
+++ b/src/System.Net.Http/src/HttpDiagnosticsGuide.md
@@ -3,7 +3,7 @@
This document describes `HttpClientHandler` instrumentation with [DiagnosticSource](https://github.com/dotnet/corefx/blob/master/src/System.Diagnostics.DiagnosticSource/src/DiagnosticSourceUsersGuide.md).
# Overview
-Applications typically log outgoing HTTP requests; typically it's done with DelegatingHandler implementation that logs every request. However in existing system it may require extensive code changes, since DelegatingHandler needs to be added to HttpClient pipeline every time when new client is created.
+Applications typically log outgoing HTTP requests; typically it's done with DelegatingHandler implementation that logs every request. However in an existing system it may require extensive code changes, since DelegatingHandler needs to be added to HttpClient pipeline every time when new client is created.
DiagnosticListener instrumentation allows to enable outgoing request tracing with a few lines of code; it also provides context necessary to correlate logs.
Context is represented as `System.Diagnostics.Activity` class. Activity may be started as a child of another Activity and the whole operation is represented with a tree of Activities. You can find more details in [Activity User Guide](https://github.com/dotnet/corefx/blob/master/src/System.Diagnostics.DiagnosticSource/src/ActivityUserGuide.md).
@@ -12,16 +12,15 @@ Activity carries useful properties for logging such as Id, start time, Tags, Bag
Instrumentation ensures `Activity.Current` represents current outgoing request in Write event callbacks (if request is instrumented). Consumers **should not** assume `Activity.Current` is accurate in IsEnabled callbacks.
-In microservice environment some context should flow with outgoing requests to correlate telemtry from all services involved in operation processing.
+In a microservice environment some context should flow with outgoing requests to correlate telemetry from all services involved in processing an operation.
Instrumentation adds context into the request headers:
* Request-Id header with `Activity.Id` value
* Correlation-Context header with `Activity.Baggage` key-value pair list in `k1=v1, k2=v2` format
-See [Http Protocol proposal](https://github.com/lmolkova/correlation/blob/master/http_protocol_proposal_v1.md) for more details
-[comment]: TODO: Update link once it's moved
+See [HTTP Protocol proposal](https://github.com/dotnet/corefx/blob/master/src/System.Diagnostics.DiagnosticSource/src/HttpCorrelationProtocol.md) for more details.
## Subscription
-Instrumentation is off by default; to enable it, consumer first needs to subscribe to DiagnosticListener called "HttpHandlerDiagnosticListener".
+Instrumentation is off by default; to enable it, consumer first needs to subscribe to a DiagnosticListener called "HttpHandlerDiagnosticListener".
```C#
var subscription = DiagnosticListener.AllListeners.Subscribe(delegate (DiagnosticListener listener)
@@ -37,7 +36,7 @@ var subscription = DiagnosticListener.AllListeners.Subscribe(delegate (Diagnosti
```
## Events
-If there is **at least one consumer**, subscribed for "HttpHandlerDiagnosticListener" events, `HttpClientHandler` instruments outgoing request depending on subscription and request properties.
+If there is **at least one consumer** subscribed for "HttpHandlerDiagnosticListener" events, `HttpClientHandler` instruments outgoing request depending on subscription and request properties.
Note that DiagnosticListener best practice is to guard every `Write` method with `IsEnabled` check. In case there is more than one consumer, **each consumer** will receive Write event if **at least one** consumer returned true for `IsEnabled`.
diff --git a/src/System.Net.Http/src/Resources/Strings.resx b/src/System.Net.Http/src/Resources/Strings.resx
index 51632035b6..0f4cf30cd7 100644
--- a/src/System.Net.Http/src/Resources/Strings.resx
+++ b/src/System.Net.Http/src/Resources/Strings.resx
@@ -381,4 +381,7 @@
<data name="net_http_ssl_connection_failed" xml:space="preserve">
<value>The SSL connection could not be established, see inner exception.</value>
</data>
-</root> \ No newline at end of file
+ <data name="IO_SeekBeforeBegin" xml:space="preserve">
+ <value>An attempt was made to move the position before the beginning of the stream.</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 c295bfab93..0c1be5c433 100644
--- a/src/System.Net.Http/src/System.Net.Http.csproj
+++ b/src/System.Net.Http/src/System.Net.Http.csproj
@@ -53,6 +53,7 @@
<Compile Include="System\Net\Http\MultipartContent.cs" />
<Compile Include="System\Net\Http\MultipartFormDataContent.cs" />
<Compile Include="System\Net\Http\NetEventSource.Http.cs" />
+ <Compile Include="System\Net\Http\ReadOnlyMemoryContent.cs" />
<Compile Include="System\Net\Http\StreamContent.cs" />
<Compile Include="System\Net\Http\StreamToStreamCopy.cs" />
<Compile Include="System\Net\Http\StringContent.cs" />
@@ -107,6 +108,9 @@
<Compile Include="$(CommonPath)\System\IO\DelegatingStream.cs">
<Link>Common\System\IO\DelegatingStream.cs</Link>
</Compile>
+ <Compile Include="$(CommonPath)\System\IO\ReadOnlyMemoryStream.cs">
+ <Link>Common\System\IO\ReadOnlyMemoryStream.cs</Link>
+ </Compile>
<Compile Include="$(CommonPath)\System\IO\StringBuilderCache.cs">
<Link>Common\System\IO\StringBuilderCache.cs</Link>
</Compile>
@@ -136,11 +140,13 @@
<Compile Include="System\Net\Http\Managed\HttpConnectionPool.cs" />
<Compile Include="System\Net\Http\Managed\HttpConnectionPools.cs" />
<Compile Include="System\Net\Http\Managed\HttpConnectionSettings.cs" />
+ <Compile Include="System\Net\Http\Managed\HttpContentDuplexStream.cs" />
<Compile Include="System\Net\Http\Managed\HttpContentReadStream.cs" />
<Compile Include="System\Net\Http\Managed\HttpContentStream.cs" />
<Compile Include="System\Net\Http\Managed\HttpContentWriteStream.cs" />
<Compile Include="System\Net\Http\Managed\HttpProxyConnectionHandler.cs" />
<Compile Include="System\Net\Http\Managed\ManagedHandler.cs" />
+ <Compile Include="System\Net\Http\Managed\RawConnectionStream.cs" />
</ItemGroup>
<!-- Common, except for Windows net46 build -->
<ItemGroup Condition="'$(TargetGroup)' != 'net46' And '$(TargetGroup)' != 'netfx'">
@@ -446,6 +452,7 @@
<Reference Include="System.Text.Encoding" />
<Reference Include="System.Text.Encoding.Extensions" />
<Reference Include="System.Threading" />
+ <Reference Include="System.Threading.Thread" />
<Reference Include="System.Threading.Tasks" />
<Reference Include="System.Threading.Tasks.Extensions" />
<Reference Include="System.Threading.Timer" />
@@ -456,4 +463,4 @@
<Reference Include="System.Security.Cryptography.Primitives" />
</ItemGroup>
<Import Project="$([MSBuild]::GetDirectoryNameOfFileAbove($(MSBuildThisFileDirectory), dir.targets))\dir.targets" />
-</Project> \ No newline at end of file
+</Project>
diff --git a/src/System.Net.Http/src/System/Net/Http/Headers/ObjectCollection.cs b/src/System.Net.Http/src/System/Net/Http/Headers/ObjectCollection.cs
index 08206cb6b3..92315b1f78 100644
--- a/src/System.Net.Http/src/System/Net/Http/Headers/ObjectCollection.cs
+++ b/src/System.Net.Http/src/System/Net/Http/Headers/ObjectCollection.cs
@@ -4,6 +4,7 @@
using System.Collections.Generic;
using System.Collections.ObjectModel;
+using System.Diagnostics;
namespace System.Net.Http.Headers
{
@@ -23,6 +24,7 @@ namespace System.Net.Http.Headers
public ObjectCollection(Action<T> validator)
: base(new List<T>())
{
+ Debug.Assert(validator != null, $"{nameof(validator)} must not be null.");
_validator = validator;
}
@@ -35,19 +37,13 @@ namespace System.Net.Http.Headers
protected override void InsertItem(int index, T item)
{
- if (_validator != null)
- {
- _validator(item);
- }
+ _validator(item);
base.InsertItem(index, item);
}
protected override void SetItem(int index, T item)
{
- if (_validator != null)
- {
- _validator(item);
- }
+ _validator(item);
base.SetItem(index, item);
}
diff --git a/src/System.Net.Http/src/System/Net/Http/HttpClientHandler.cs b/src/System.Net.Http/src/System/Net/Http/HttpClientHandler.cs
index 1203fb6512..aaadad33e3 100644
--- a/src/System.Net.Http/src/System/Net/Http/HttpClientHandler.cs
+++ b/src/System.Net.Http/src/System/Net/Http/HttpClientHandler.cs
@@ -2,16 +2,52 @@
// 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.Security.Cryptography.X509Certificates;
+using System.Threading;
namespace System.Net.Http
{
public partial class HttpClientHandler : HttpMessageHandler
{
// This partial implementation contains members common to all HttpClientHandler implementations.
-
- private static bool UseManagedHandler => Environment.GetEnvironmentVariable("COMPlus_UseManagedHttpClientHandler") == "true";
+ private const string ManagedHandlerSettingName = "COMPlus_UseManagedHttpClientHandler";
+
+ private static LocalDataStoreSlot s_useManagedHandlerSlot;
+
+ private static bool UseManagedHandler
+ {
+ get
+ {
+ // Check the environment variable to see if it's been set to true. If it has, use the managed handler.
+ if (Environment.GetEnvironmentVariable(ManagedHandlerSettingName) == "true")
+ {
+ return true;
+ }
+
+ // Then check whether a thread local has been set with the same name.
+ // If it's been set to a Boolean true, also use the managed handler.
+ LocalDataStoreSlot slot = LazyInitializer.EnsureInitialized(ref s_useManagedHandlerSlot, () =>
+ {
+ LocalDataStoreSlot local = Thread.GetNamedDataSlot(ManagedHandlerSettingName);
+ if (local == null)
+ {
+ try
+ {
+ local = Thread.AllocateNamedDataSlot(ManagedHandlerSettingName);
+ }
+ catch (ArgumentException)
+ {
+ local = Thread.GetNamedDataSlot(ManagedHandlerSettingName);
+ }
+ }
+ return local;
+ });
+ Debug.Assert(slot != null);
+ return Thread.GetData(slot) is bool result && result;
+ }
+ }
public static Func<HttpRequestMessage, X509Certificate2, X509Chain, SslPolicyErrors, bool> DangerousAcceptAnyServerCertificateValidator { get; } = delegate { return true; };
}
diff --git a/src/System.Net.Http/src/System/Net/Http/HttpUtilities.cs b/src/System.Net.Http/src/System/Net/Http/HttpUtilities.cs
index 252e1c3928..aa8f1faa32 100644
--- a/src/System.Net.Http/src/System/Net/Http/HttpUtilities.cs
+++ b/src/System.Net.Http/src/System/Net/Http/HttpUtilities.cs
@@ -25,12 +25,19 @@ namespace System.Net.Http
internal static bool IsHttpUri(Uri uri)
{
Debug.Assert(uri != null);
-
- string scheme = uri.Scheme;
- return string.Equals("http", scheme, StringComparison.OrdinalIgnoreCase) ||
- string.Equals("https", scheme, StringComparison.OrdinalIgnoreCase);
+ return IsSupportedScheme(uri.Scheme);
}
+ internal static bool IsSupportedScheme(string scheme) =>
+ IsSupportedNonSecureScheme(scheme) ||
+ IsSupportedSecureScheme(scheme);
+
+ internal static bool IsSupportedNonSecureScheme(string scheme) =>
+ string.Equals(scheme, "http", StringComparison.OrdinalIgnoreCase);
+
+ internal static bool IsSupportedSecureScheme(string scheme) =>
+ string.Equals(scheme, "https", StringComparison.OrdinalIgnoreCase);
+
// Returns true if the task was faulted or canceled and sets tcs accordingly.
internal static bool HandleFaultsAndCancelation<T>(Task task, TaskCompletionSource<T> tcs)
{
diff --git a/src/System.Net.Http/src/System/Net/Http/Managed/AuthenticationHandler.cs b/src/System.Net.Http/src/System/Net/Http/Managed/AuthenticationHandler.cs
index e4ddde8d4f..5ae0562595 100644
--- a/src/System.Net.Http/src/System/Net/Http/Managed/AuthenticationHandler.cs
+++ b/src/System.Net.Http/src/System/Net/Http/Managed/AuthenticationHandler.cs
@@ -14,7 +14,7 @@ namespace System.Net.Http
{
private readonly HttpMessageHandler _innerHandler;
private readonly bool _preAuthenticate;
- private readonly ICredentials _credentials;
+ private ICredentials _credentials;
private AuthenticationHelper.DigestResponse _digestResponse;
public AuthenticationHandler(bool preAuthenticate, ICredentials credentials, HttpMessageHandler innerHandler)
@@ -44,7 +44,15 @@ namespace System.Net.Http
HttpResponseMessage response = await _innerHandler.SendAsync(request, cancellationToken).ConfigureAwait(false);
- if (!_preAuthenticate && response.StatusCode == HttpStatusCode.Unauthorized)
+ // In case of redirection, ensure _credentials as CredentialCache
+ if (AutoRedirectHandler.RequestNeedsRedirect(response))
+ {
+ // Just as with WinHttpHandler and CurlHandler, for security reasons, we drop the server credential if it is
+ // anything other than a CredentialCache. We allow credentials in a CredentialCache since they
+ // are specifically tied to URIs.
+ _credentials = _credentials as CredentialCache;
+ }
+ else if (_credentials != null && !_preAuthenticate && response.StatusCode == HttpStatusCode.Unauthorized)
{
HttpHeaderValueCollection<AuthenticationHeaderValue> authenticateValues = response.Headers.WwwAuthenticate;
diff --git a/src/System.Net.Http/src/System/Net/Http/Managed/AuthenticationHelper.Digest.cs b/src/System.Net.Http/src/System/Net/Http/Managed/AuthenticationHelper.Digest.cs
index d46f230ce0..8630562f6d 100644
--- a/src/System.Net.Http/src/System/Net/Http/Managed/AuthenticationHelper.Digest.cs
+++ b/src/System.Net.Http/src/System/Net/Http/Managed/AuthenticationHelper.Digest.cs
@@ -52,7 +52,7 @@ namespace System.Net.Http
return false;
}
- string parameter = await GetDigestTokenForCredential(credential, request, digestResponse);
+ string parameter = await GetDigestTokenForCredential(credential, request, digestResponse).ConfigureAwait(false);
// Any errors in obtaining parameter return false
if (string.IsNullOrEmpty(parameter))
@@ -177,7 +177,7 @@ namespace System.Net.Http
string a2 = request.Method.Method + ":" + request.RequestUri.PathAndQuery;
if (qop == AuthInt)
{
- string content = request.Content == null ? string.Empty : await request.Content.ReadAsStringAsync();
+ string content = request.Content == null ? string.Empty : await request.Content.ReadAsStringAsync().ConfigureAwait(false);
a2 = a2 + ":" + ComputeHash(content, algorithm);
}
@@ -218,12 +218,7 @@ namespace System.Net.Http
private static string GetRandomAlphaNumericString()
{
const int Length = 16;
- Span<byte> randomNumbers;
- unsafe
- {
- byte* ptr = stackalloc byte[Length * 2];
- randomNumbers = new Span<byte>(ptr, Length * 2);
- }
+ Span<byte> randomNumbers = stackalloc byte[Length * 2];
s_rng.GetBytes(randomNumbers);
StringBuilder sb = StringBuilderCache.Acquire(Length);
diff --git a/src/System.Net.Http/src/System/Net/Http/Managed/AutoRedirectHandler.cs b/src/System.Net.Http/src/System/Net/Http/Managed/AutoRedirectHandler.cs
index 20205ef7de..a35175acaa 100644
--- a/src/System.Net.Http/src/System/Net/Http/Managed/AutoRedirectHandler.cs
+++ b/src/System.Net.Http/src/System/Net/Http/Managed/AutoRedirectHandler.cs
@@ -23,6 +23,39 @@ namespace System.Net.Http
_maxAutomaticRedirections = maxAutomaticRedirections;
}
+ internal static bool RequestNeedsRedirect(HttpResponseMessage response)
+ {
+ bool needRedirect = false;
+ switch (response.StatusCode)
+ {
+ case HttpStatusCode.Moved:
+ case HttpStatusCode.Found:
+ case HttpStatusCode.SeeOther:
+ case HttpStatusCode.TemporaryRedirect:
+ needRedirect = true;
+ break;
+
+ case HttpStatusCode.MultipleChoices:
+ needRedirect = response.Headers.Location != null; // Don't redirect if no Location specified
+ break;
+ }
+
+ return needRedirect;
+ }
+
+ private static bool RequestRequiresForceGet(HttpStatusCode statusCode, HttpMethod requestMethod)
+ {
+ if (statusCode == HttpStatusCode.Moved ||
+ statusCode == HttpStatusCode.Found ||
+ statusCode == HttpStatusCode.SeeOther ||
+ statusCode == HttpStatusCode.MultipleChoices)
+ {
+ return requestMethod == HttpMethod.Post;
+ }
+
+ return false;
+ }
+
protected internal override async Task<HttpResponseMessage> SendAsync(HttpRequestMessage request, CancellationToken cancellationToken)
{
HttpResponseMessage response;
@@ -31,28 +64,7 @@ namespace System.Net.Http
{
response = await _innerHandler.SendAsync(request, cancellationToken).ConfigureAwait(false);
- bool needRedirect = false;
- bool forceGet = false;
- switch (response.StatusCode)
- {
- case HttpStatusCode.TemporaryRedirect:
- needRedirect = true;
- break;
-
- case HttpStatusCode.Moved:
- case HttpStatusCode.Found:
- case HttpStatusCode.SeeOther:
- needRedirect = true;
- forceGet = request.Method == HttpMethod.Post;
- break;
-
- case HttpStatusCode.MultipleChoices:
- needRedirect = response.Headers.Location != null; // Don't redirect if no Location specified
- forceGet = request.Method == HttpMethod.Post;
- break;
- }
-
- if (!needRedirect)
+ if (!RequestNeedsRedirect(response))
{
break;
}
@@ -68,10 +80,10 @@ namespace System.Net.Http
location = new Uri(request.RequestUri, location);
}
- // Disallow automatic redirection from https to http
+ // Disallow automatic redirection from secure to non-secure schemes
bool allowed =
- (request.RequestUri.Scheme == UriScheme.Http && (location.Scheme == UriScheme.Http || location.Scheme == UriScheme.Https)) ||
- (request.RequestUri.Scheme == UriScheme.Https && location.Scheme == UriScheme.Https);
+ (HttpUtilities.IsSupportedNonSecureScheme(request.RequestUri.Scheme) && HttpUtilities.IsSupportedScheme(location.Scheme)) ||
+ (HttpUtilities.IsSupportedSecureScheme(request.RequestUri.Scheme) && HttpUtilities.IsSupportedSecureScheme(location.Scheme));
if (!allowed)
{
break;
@@ -86,7 +98,7 @@ namespace System.Net.Http
// Set up for the automatic redirect
request.RequestUri = location;
- if (forceGet)
+ if (RequestRequiresForceGet(response.StatusCode, request.Method))
{
request.Method = HttpMethod.Get;
request.Content = null;
diff --git a/src/System.Net.Http/src/System/Net/Http/Managed/ChunkedEncodingWriteStream.cs b/src/System.Net.Http/src/System/Net/Http/Managed/ChunkedEncodingWriteStream.cs
index f5763abf36..c3cf273950 100644
--- a/src/System.Net.Http/src/System/Net/Http/Managed/ChunkedEncodingWriteStream.cs
+++ b/src/System.Net.Http/src/System/Net/Http/Managed/ChunkedEncodingWriteStream.cs
@@ -68,7 +68,7 @@ namespace System.Net.Http
// source was empty, and it might be kept open to enable subsequent communication. And it's necessary
// in general for at least the first write, as we need to ensure if it's the entirety of the content
// and if all of the headers and content fit in the write buffer that we've actually sent the request.
- await _connection.FlushAsync(RequestCancellationToken);
+ await _connection.FlushAsync(RequestCancellationToken).ConfigureAwait(false);
}
public override Task FlushAsync(CancellationToken ignored)
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 4bf3efa9cb..d96ff6547d 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
@@ -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.IO;
using System.Net.Sockets;
using System.Threading.Tasks;
@@ -9,7 +10,7 @@ namespace System.Net.Http
{
internal static class ConnectHelper
{
- public static async ValueTask<NetworkStream> ConnectAsync(string host, int port)
+ public static async ValueTask<Stream> ConnectAsync(string host, int port)
{
var socket = new Socket(SocketType.Stream, ProtocolType.Tcp) { NoDelay = true };
try
diff --git a/src/System.Net.Http/src/System/Net/Http/Managed/ConnectionCloseReadStream.cs b/src/System.Net.Http/src/System/Net/Http/Managed/ConnectionCloseReadStream.cs
index 9cc75e9f54..1983142d3d 100644
--- a/src/System.Net.Http/src/System/Net/Http/Managed/ConnectionCloseReadStream.cs
+++ b/src/System.Net.Http/src/System/Net/Http/Managed/ConnectionCloseReadStream.cs
@@ -12,8 +12,7 @@ namespace System.Net.Http
{
private sealed class ConnectionCloseReadStream : HttpContentReadStream
{
- public ConnectionCloseReadStream(HttpConnection connection)
- : base(connection)
+ public ConnectionCloseReadStream(HttpConnection connection) : base(connection)
{
}
@@ -28,7 +27,6 @@ namespace System.Net.Http
}
int bytesRead = await _connection.ReadAsync(buffer, offset, count, cancellationToken).ConfigureAwait(false);
-
if (bytesRead == 0)
{
// We cannot reuse this connection, so close it.
@@ -47,17 +45,14 @@ namespace System.Net.Http
throw new ArgumentNullException(nameof(destination));
}
- if (_connection == null)
+ if (_connection != null) // null if response body fully consumed
{
- // Response body fully consumed
- return;
- }
+ await _connection.CopyToAsync(destination, cancellationToken).ConfigureAwait(false);
- await _connection.CopyToAsync(destination, cancellationToken).ConfigureAwait(false);
-
- // We cannot reuse this connection, so close it.
- _connection.Dispose();
- _connection = null;
+ // We cannot reuse this connection, so close it.
+ _connection.Dispose();
+ _connection = null;
+ }
}
}
}
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 4c708f8494..51086a060c 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
@@ -347,7 +347,7 @@ namespace System.Net.Http
}
// Create the response stream.
- HttpContentReadStream responseStream;
+ HttpContentStream responseStream;
if (request.Method == HttpMethod.Head || (int)response.StatusCode == 204 || (int)response.StatusCode == 304)
{
responseStream = EmptyReadStream.Instance;
@@ -370,6 +370,10 @@ namespace System.Net.Http
{
responseStream = new ChunkedEncodingReadStream(this);
}
+ else if (response.StatusCode == HttpStatusCode.SwitchingProtocols)
+ {
+ responseStream = new RawConnectionStream(this);
+ }
else
{
responseStream = new ConnectionCloseReadStream(this);
@@ -663,7 +667,7 @@ namespace System.Net.Http
private async Task FlushThenWriteWithoutBufferingAsync(byte[] buffer, int offset, int count, CancellationToken cancellationToken)
{
await FlushAsync(cancellationToken).ConfigureAwait(false);
- await WriteToStreamAsync(buffer, offset, count, cancellationToken);
+ await WriteToStreamAsync(buffer, offset, count, cancellationToken).ConfigureAwait(false);
}
private Task WriteByteAsync(byte b, CancellationToken cancellationToken)
diff --git a/src/System.Net.Http/src/System/Net/Http/Managed/HttpConnectionContent.cs b/src/System.Net.Http/src/System/Net/Http/Managed/HttpConnectionContent.cs
index 6ce4fea1cf..bf6bfb525e 100644
--- a/src/System.Net.Http/src/System/Net/Http/Managed/HttpConnectionContent.cs
+++ b/src/System.Net.Http/src/System/Net/Http/Managed/HttpConnectionContent.cs
@@ -14,14 +14,14 @@ namespace System.Net.Http
private sealed class HttpConnectionContent : HttpContent
{
private readonly CancellationToken _cancellationToken;
- private HttpContentReadStream _stream;
+ private HttpContentStream _stream;
public HttpConnectionContent(CancellationToken cancellationToken)
{
_cancellationToken = cancellationToken;
}
- public void SetStream(HttpContentReadStream stream)
+ public void SetStream(HttpContentStream stream)
{
Debug.Assert(stream != null);
Debug.Assert(stream.CanRead);
@@ -29,14 +29,14 @@ namespace System.Net.Http
_stream = stream;
}
- private HttpContentReadStream ConsumeStream()
+ private HttpContentStream ConsumeStream()
{
if (_stream == null)
{
throw new InvalidOperationException(SR.net_http_content_stream_already_read);
}
- HttpContentReadStream stream = _stream;
+ HttpContentStream stream = _stream;
_stream = null;
return stream;
}
@@ -45,7 +45,7 @@ namespace System.Net.Http
{
Debug.Assert(stream != null);
- using (HttpContentReadStream contentStream = ConsumeStream())
+ using (HttpContentStream contentStream = ConsumeStream())
{
const int BufferSize = 8192;
await contentStream.CopyToAsync(stream, BufferSize, _cancellationToken).ConfigureAwait(false);
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 00e498a340..c0635480de 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
@@ -50,7 +50,14 @@ namespace System.Net.Http
{
callback = (object sender, X509Certificate certificate, X509Chain chain, SslPolicyErrors sslPolicyErrors) =>
{
- return _settings._serverCertificateCustomValidationCallback(request, certificate as X509Certificate2, chain, sslPolicyErrors);
+ try
+ {
+ return _settings._serverCertificateCustomValidationCallback(request, certificate as X509Certificate2, chain, sslPolicyErrors);
+ }
+ catch (Exception e)
+ {
+ throw new HttpRequestException(SR.net_http_ssl_connection_failed, e);
+ }
};
}
@@ -82,7 +89,7 @@ namespace System.Net.Http
TransportContext transportContext = null;
- if (uri.Scheme == UriScheme.Https)
+ if (HttpUtilities.IsSupportedSecureScheme(uri.Scheme))
{
SslStream sslStream = await EstablishSslConnection(uri.IdnHost, request, stream).ConfigureAwait(false);
stream = sslStream;
diff --git a/src/System.Net.Http/src/System/Net/Http/Managed/HttpConnectionKey.cs b/src/System.Net.Http/src/System/Net/Http/Managed/HttpConnectionKey.cs
index d4e4185551..7d991dc2da 100644
--- a/src/System.Net.Http/src/System/Net/Http/Managed/HttpConnectionKey.cs
+++ b/src/System.Net.Http/src/System/Net/Http/Managed/HttpConnectionKey.cs
@@ -12,9 +12,9 @@ namespace System.Net.Http
public HttpConnectionKey(Uri uri)
{
- UsingSSL =
- uri.Scheme == UriScheme.Http ? false :
- uri.Scheme == UriScheme.Https ? true :
+ UsingSSL =
+ HttpUtilities.IsSupportedNonSecureScheme(uri.Scheme) ? false :
+ HttpUtilities.IsSupportedSecureScheme(uri.Scheme) ? true :
throw new ArgumentException(SR.net_http_client_http_baseaddress_required, nameof(uri));
Host = uri.Host;
diff --git a/src/System.Net.Http/src/System/Net/Http/Managed/HttpContentDuplexStream.cs b/src/System.Net.Http/src/System/Net/Http/Managed/HttpContentDuplexStream.cs
new file mode 100644
index 0000000000..4fa5b269e0
--- /dev/null
+++ b/src/System.Net.Http/src/System/Net/Http/Managed/HttpContentDuplexStream.cs
@@ -0,0 +1,31 @@
+// 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.Diagnostics;
+using System.IO;
+using System.Threading;
+
+namespace System.Net.Http
+{
+ internal abstract class HttpContentDuplexStream : HttpContentStream
+ {
+ public HttpContentDuplexStream(HttpConnection connection) : base(connection)
+ {
+ }
+
+ public override bool CanRead => true;
+ public override bool CanWrite => true;
+
+ public override void Flush() => FlushAsync().GetAwaiter().GetResult();
+
+ public override int Read(byte[] buffer, int offset, int count) =>
+ ReadAsync(buffer, offset, count, CancellationToken.None).GetAwaiter().GetResult();
+
+ public override void Write(byte[] buffer, int offset, int count) =>
+ WriteAsync(buffer, offset, count, CancellationToken.None).GetAwaiter().GetResult();
+
+ public override void CopyTo(Stream destination, int bufferSize) =>
+ CopyToAsync(destination, bufferSize, CancellationToken.None).GetAwaiter().GetResult();
+ }
+}
diff --git a/src/System.Net.Http/src/System/Net/Http/Managed/HttpContentReadStream.cs b/src/System.Net.Http/src/System/Net/Http/Managed/HttpContentReadStream.cs
index 795c143d6a..62c48b3797 100644
--- a/src/System.Net.Http/src/System/Net/Http/Managed/HttpContentReadStream.cs
+++ b/src/System.Net.Http/src/System/Net/Http/Managed/HttpContentReadStream.cs
@@ -9,30 +9,14 @@ namespace System.Net.Http
{
internal abstract class HttpContentReadStream : HttpContentStream
{
- protected HttpConnection _connection;
-
- public HttpContentReadStream(HttpConnection connection)
+ public HttpContentReadStream(HttpConnection connection) : base(connection)
{
- _connection = connection;
}
public override bool CanRead => true;
- public override bool CanSeek => false;
public override bool CanWrite => false;
- public override long Length => throw new NotSupportedException();
-
- public override long Position
- {
- get { throw new NotSupportedException(); }
- set { throw new NotSupportedException(); }
- }
-
- public override void Flush() => throw new NotSupportedException();
-
- public override long Seek(long offset, SeekOrigin origin) => throw new NotSupportedException();
-
- public override void SetLength(long value) => throw new NotSupportedException();
+ public override void Flush() { }
public override void Write(byte[] buffer, int offset, int count) => throw new NotSupportedException();
@@ -41,17 +25,5 @@ namespace System.Net.Http
public override void CopyTo(Stream destination, int bufferSize) =>
CopyToAsync(destination, bufferSize, CancellationToken.None).GetAwaiter().GetResult();
-
- protected override void Dispose(bool disposing)
- {
- if (_connection != null)
- {
- // We haven't finished reading the body, so close the connection.
- _connection.Dispose();
- _connection = null;
- }
-
- base.Dispose(disposing);
- }
}
}
diff --git a/src/System.Net.Http/src/System/Net/Http/Managed/HttpContentStream.cs b/src/System.Net.Http/src/System/Net/Http/Managed/HttpContentStream.cs
index 991ea06bc0..b54f6c45dd 100644
--- a/src/System.Net.Http/src/System/Net/Http/Managed/HttpContentStream.cs
+++ b/src/System.Net.Http/src/System/Net/Http/Managed/HttpContentStream.cs
@@ -3,11 +3,60 @@
// See the LICENSE file in the project root for more information.
using System.IO;
+using System.Threading;
+using System.Threading.Tasks;
namespace System.Net.Http
{
internal abstract class HttpContentStream : Stream
{
+ protected HttpConnection _connection;
+
+ public HttpContentStream(HttpConnection connection)
+ {
+ _connection = connection;
+ }
+
+ protected override void Dispose(bool disposing)
+ {
+ if (disposing)
+ {
+ if (_connection != null)
+ {
+ _connection.Dispose();
+ _connection = null;
+ }
+ }
+
+ base.Dispose(disposing);
+ }
+
+ public override bool CanSeek => false;
+
+ public override IAsyncResult BeginRead(byte[] buffer, int offset, int count, AsyncCallback callback, object state) =>
+ TaskToApm.Begin(ReadAsync(buffer, offset, count, default(CancellationToken)), callback, state);
+
+ public override int EndRead(IAsyncResult asyncResult) =>
+ TaskToApm.End<int>(asyncResult);
+
+ public override IAsyncResult BeginWrite(byte[] buffer, int offset, int count, AsyncCallback callback, object state) =>
+ TaskToApm.Begin(WriteAsync(buffer, offset, count, default(CancellationToken)), callback, state);
+
+ public override void EndWrite(IAsyncResult asyncResult) =>
+ TaskToApm.End(asyncResult);
+
+ public override long Seek(long offset, SeekOrigin origin) => throw new NotSupportedException();
+
+ public override void SetLength(long value) => throw new NotSupportedException();
+
+ public override long Length => throw new NotSupportedException();
+
+ public override long Position
+ {
+ get { throw new NotSupportedException(); }
+ set { throw new NotSupportedException(); }
+ }
+
protected static void ValidateBufferArgs(byte[] buffer, int offset, int count)
{
if (buffer == null)
diff --git a/src/System.Net.Http/src/System/Net/Http/Managed/HttpContentWriteStream.cs b/src/System.Net.Http/src/System/Net/Http/Managed/HttpContentWriteStream.cs
index a998366083..54c68df478 100644
--- a/src/System.Net.Http/src/System/Net/Http/Managed/HttpContentWriteStream.cs
+++ b/src/System.Net.Http/src/System/Net/Http/Managed/HttpContentWriteStream.cs
@@ -11,12 +11,9 @@ namespace System.Net.Http
{
internal abstract class HttpContentWriteStream : HttpContentStream
{
- protected HttpConnection _connection;
-
- public HttpContentWriteStream(HttpConnection connection, CancellationToken cancellationToken)
+ public HttpContentWriteStream(HttpConnection connection, CancellationToken cancellationToken) : base(connection)
{
Debug.Assert(connection != null);
- _connection = connection;
RequestCancellationToken = cancellationToken;
}
@@ -29,42 +26,15 @@ namespace System.Net.Http
internal CancellationToken RequestCancellationToken { get; }
public override bool CanRead => false;
- public override bool CanSeek => false;
public override bool CanWrite => true;
- public override long Length => throw new NotSupportedException();
-
- public override long Position
- {
- get { throw new NotSupportedException(); }
- set { throw new NotSupportedException(); }
- }
-
public override void Flush() => FlushAsync().GetAwaiter().GetResult();
- public override long Seek(long offset, SeekOrigin origin) => throw new NotSupportedException();
-
- public override void SetLength(long value) => throw new NotSupportedException();
-
public override int Read(byte[] buffer, int offset, int count) => throw new NotSupportedException();
public override void Write(byte[] buffer, int offset, int count) =>
WriteAsync(buffer, offset, count, CancellationToken.None).GetAwaiter().GetResult();
public abstract Task FinishAsync();
-
- protected override void Dispose(bool disposing)
- {
- if (disposing)
- {
- if (_connection != null)
- {
- _connection.Dispose();
- _connection = null;
- }
- }
-
- base.Dispose(disposing);
- }
}
}
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 90031b717b..db807d407f 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
@@ -4,7 +4,6 @@
using System.Diagnostics;
using System.IO;
-using System.Net;
using System.Net.Http.Headers;
using System.Threading;
using System.Threading.Tasks;
@@ -22,9 +21,11 @@ namespace System.Net.Http
public HttpProxyConnectionHandler(HttpConnectionSettings settings, HttpMessageHandler innerHandler)
{
Debug.Assert(innerHandler != null);
+ Debug.Assert(settings._useProxy);
+ Debug.Assert(settings._proxy != null || s_proxyFromEnvironment.Value != null);
_innerHandler = innerHandler;
- _proxy = (settings._useProxy && settings._proxy != null) ? settings._proxy : new PassthroughWebProxy(s_proxyFromEnvironment.Value);
+ _proxy = settings._proxy ?? new PassthroughWebProxy(s_proxyFromEnvironment.Value);
_defaultCredentials = settings._defaultProxyCredentials;
_connectionPools = new HttpConnectionPools(settings._maxConnectionsPerServer);
}
@@ -58,7 +59,7 @@ namespace System.Net.Http
throw new InvalidOperationException(SR.net_http_invalid_proxy_scheme);
}
- if (request.RequestUri.Scheme == UriScheme.Https)
+ if (!HttpUtilities.IsSupportedNonSecureScheme(request.RequestUri.Scheme))
{
// TODO #23136: Implement SSL tunneling through proxy
throw new NotImplementedException("no support for SSL tunneling through proxy");
diff --git a/src/System.Net.Http/src/System/Net/Http/Managed/ManagedHandler.cs b/src/System.Net.Http/src/System/Net/Http/Managed/ManagedHandler.cs
index 1ae7e4189b..cf1a1798f3 100644
--- a/src/System.Net.Http/src/System/Net/Http/Managed/ManagedHandler.cs
+++ b/src/System.Net.Http/src/System/Net/Http/Managed/ManagedHandler.cs
@@ -263,8 +263,8 @@ namespace System.Net.Http
{
HttpMessageHandler handler = new HttpConnectionHandler(_settings);
- if ((_settings._useProxy && _settings._proxy != null) ||
- HttpProxyConnectionHandler.EnvironmentProxyConfigured)
+ if (_settings._useProxy &&
+ (_settings._proxy != null || HttpProxyConnectionHandler.EnvironmentProxyConfigured))
{
handler = new HttpProxyConnectionHandler(_settings, handler);
}
diff --git a/src/System.Net.Http/src/System/Net/Http/Managed/RawConnectionStream.cs b/src/System.Net.Http/src/System/Net/Http/Managed/RawConnectionStream.cs
new file mode 100644
index 0000000000..3cca8c2be5
--- /dev/null
+++ b/src/System.Net.Http/src/System/Net/Http/Managed/RawConnectionStream.cs
@@ -0,0 +1,72 @@
+// 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;
+using System.Threading.Tasks;
+
+namespace System.Net.Http
+{
+ internal sealed partial class HttpConnection : IDisposable
+ {
+ private sealed class RawConnectionStream : HttpContentDuplexStream
+ {
+ public RawConnectionStream(HttpConnection connection) : base(connection)
+ {
+ }
+
+ public override async Task<int> ReadAsync(byte[] buffer, int offset, int count, CancellationToken cancellationToken)
+ {
+ ValidateBufferArgs(buffer, offset, count);
+
+ if (_connection == null || count == 0)
+ {
+ // Response body fully consumed or the caller didn't ask for any data
+ return 0;
+ }
+
+ int bytesRead = await _connection.ReadAsync(buffer, offset, count, cancellationToken).ConfigureAwait(false);
+ if (bytesRead == 0)
+ {
+ // We cannot reuse this connection, so close it.
+ _connection.Dispose();
+ _connection = null;
+ return 0;
+ }
+
+ return bytesRead;
+ }
+
+ public override async Task CopyToAsync(Stream destination, int bufferSize, CancellationToken cancellationToken)
+ {
+ if (destination == null)
+ {
+ throw new ArgumentNullException(nameof(destination));
+ }
+
+ if (_connection != null) // null if response body fully consumed
+ {
+ await _connection.CopyToAsync(destination, cancellationToken).ConfigureAwait(false);
+
+ // We cannot reuse this connection, so close it.
+ _connection.Dispose();
+ _connection = null;
+ }
+ }
+
+ public override Task WriteAsync(byte[] buffer, int offset, int count, CancellationToken cancellationToken)
+ {
+ ValidateBufferArgs(buffer, offset, count);
+ return
+ _connection == null ? Task.FromException(new IOException(SR.net_http_io_write)) :
+ count > 0 ? _connection.WriteWithoutBufferingAsync(buffer, offset, count, cancellationToken) :
+ Task.CompletedTask;
+ }
+
+ public override Task FlushAsync(CancellationToken cancellationToken) =>
+ _connection != null ? _connection.FlushAsync(cancellationToken) :
+ Task.CompletedTask;
+ }
+ }
+}
diff --git a/src/System.Net.Http/src/System/Net/Http/ReadOnlyMemoryContent.cs b/src/System.Net.Http/src/System/Net/Http/ReadOnlyMemoryContent.cs
new file mode 100644
index 0000000000..2f42bd1973
--- /dev/null
+++ b/src/System.Net.Http/src/System/Net/Http/ReadOnlyMemoryContent.cs
@@ -0,0 +1,40 @@
+// 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
+{
+ public sealed class ReadOnlyMemoryContent : HttpContent
+ {
+ private readonly ReadOnlyMemory<byte> _content;
+
+ public ReadOnlyMemoryContent(ReadOnlyMemory<byte> content)
+ {
+ _content = content;
+ if (content.DangerousTryGetArray(out ArraySegment<byte> array))
+ {
+ // If we have an array, allow HttpClient to take optimized paths by just
+ // giving it the array content to use as its already buffered data.
+ SetBuffer(array.Array, array.Offset, array.Count);
+ }
+ }
+
+ protected override Task SerializeToStreamAsync(Stream stream, TransportContext context) =>
+ stream.WriteAsync(_content);
+
+ protected internal override bool TryComputeLength(out long length)
+ {
+ length = _content.Length;
+ return true;
+ }
+
+ protected override Task<Stream> CreateContentReadStreamAsync() =>
+ Task.FromResult<Stream>(new ReadOnlyMemoryStream(_content));
+
+ internal override Stream TryCreateContentReadStream() =>
+ new ReadOnlyMemoryStream(_content);
+ }
+}
diff --git a/src/System.Net.Http/src/uap/System/Net/cookie.cs b/src/System.Net.Http/src/uap/System/Net/cookie.cs
index b9206381bc..6233da39f6 100644
--- a/src/System.Net.Http/src/uap/System/Net/cookie.cs
+++ b/src/System.Net.Http/src/uap/System/Net/cookie.cs
@@ -360,15 +360,8 @@ namespace System.Net
{
//
// +1 in the host length is to account for the leading dot in domain
- if ((host.Length + 1 == domain.Length) &&
- (string.Compare(host, 0, domain, 1, host.Length, StringComparison.OrdinalIgnoreCase) == 0))
- {
- return true;
- }
- else
- {
- return false;
- }
+ return (host.Length + 1 == domain.Length) &&
+ (string.Compare(host, 0, domain, 1, host.Length, StringComparison.OrdinalIgnoreCase) == 0);
}
//
diff --git a/src/System.Net.Http/tests/FunctionalTests/CancellationTest.cs b/src/System.Net.Http/tests/FunctionalTests/CancellationTest.cs
index f97b8fee1d..f29922b17c 100644
--- a/src/System.Net.Http/tests/FunctionalTests/CancellationTest.cs
+++ b/src/System.Net.Http/tests/FunctionalTests/CancellationTest.cs
@@ -13,7 +13,7 @@ using Xunit.Abstractions;
namespace System.Net.Http.Functional.Tests
{
- public class CancellationTest
+ public class CancellationTest : HttpClientTestBase
{
private readonly ITestOutputHelper _output;
@@ -37,8 +37,10 @@ namespace System.Net.Http.Functional.Tests
TimeSpan timeout = useTimeout ? new TimeSpan(0, 0, 1) : Timeout.InfiniteTimeSpan;
CancellationToken cancellationToken = useTimeout ? CancellationToken.None : cts.Token;
- using (var client = new HttpClient() { Timeout = timeout })
+ using (HttpClient client = CreateHttpClient())
{
+ client.Timeout = timeout;
+
var triggerResponseWrite = new TaskCompletionSource<bool>(TaskCreationOptions.RunContinuationsAsynchronously);
var triggerRequestCancel = new TaskCompletionSource<bool>(TaskCreationOptions.RunContinuationsAsynchronously);
@@ -107,7 +109,7 @@ namespace System.Net.Http.Functional.Tests
[InlineData(true)]
public async Task ReadAsStreamAsync_ReadAsync_Cancel_TaskCanceledQuickly(bool startResponseBody)
{
- using (var client = new HttpClient())
+ using (HttpClient client = CreateHttpClient())
{
await LoopbackServer.CreateServerAsync(async (server, url) =>
{
diff --git a/src/System.Net.Http/tests/FunctionalTests/DefaultCredentialsTest.cs b/src/System.Net.Http/tests/FunctionalTests/DefaultCredentialsTest.cs
index c3e31a0a54..2e003ac80b 100644
--- a/src/System.Net.Http/tests/FunctionalTests/DefaultCredentialsTest.cs
+++ b/src/System.Net.Http/tests/FunctionalTests/DefaultCredentialsTest.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.Net.Test.Common;
using System.Security.Principal;
using System.Threading.Tasks;
@@ -15,7 +14,8 @@ namespace System.Net.Http.Functional.Tests
// TODO: #2383 - Consolidate the use of the environment variable settings to Common/tests.
[SkipOnTargetFramework(TargetFrameworkMonikers.Uap, "dotnet/corefx #20010")]
- public class DefaultCredentialsTest
+ [PlatformSpecific(TestPlatforms.Windows)]
+ public class DefaultCredentialsTest : HttpClientTestBase
{
private static string DomainJoinedTestServer => Configuration.Http.DomainJoinedHttpHost;
private static bool DomainJoinedTestsEnabled => !string.IsNullOrEmpty(DomainJoinedTestServer);
@@ -50,7 +50,7 @@ namespace System.Net.Http.Functional.Tests
[InlineData(true)]
public async Task UseDefaultCredentials_DefaultValue_Unauthorized(bool useProxy)
{
- var handler = new HttpClientHandler();
+ HttpClientHandler handler = CreateHttpClientHandler();
handler.UseProxy = useProxy;
using (var client = new HttpClient(handler))
@@ -67,7 +67,9 @@ namespace System.Net.Http.Functional.Tests
[InlineData(true)]
public async Task UseDefaultCredentials_SetFalse_Unauthorized(bool useProxy)
{
- var handler = new HttpClientHandler { UseProxy = useProxy, UseDefaultCredentials = false };
+ HttpClientHandler handler = CreateHttpClientHandler();
+ handler.UseProxy = useProxy;
+ handler.UseDefaultCredentials = false;
using (var client = new HttpClient(handler))
using (HttpResponseMessage response = await client.GetAsync(s_authenticatedServer))
@@ -83,7 +85,9 @@ namespace System.Net.Http.Functional.Tests
[InlineData(true)]
public async Task UseDefaultCredentials_SetTrue_ConnectAsCurrentIdentity(bool useProxy)
{
- var handler = new HttpClientHandler { UseProxy = useProxy, UseDefaultCredentials = true };
+ HttpClientHandler handler = CreateHttpClientHandler();
+ handler.UseProxy = useProxy;
+ handler.UseDefaultCredentials = true;
using (var client = new HttpClient(handler))
using (HttpResponseMessage response = await client.GetAsync(s_authenticatedServer))
@@ -104,7 +108,9 @@ namespace System.Net.Http.Functional.Tests
[InlineData(true)]
public async Task UseDefaultCredentials_SetTrueAndServerOffersMultipleSchemes_Ok(bool useProxy)
{
- var handler = new HttpClientHandler { UseProxy = useProxy, UseDefaultCredentials = true };
+ HttpClientHandler handler = CreateHttpClientHandler();
+ handler.UseProxy = useProxy;
+ handler.UseDefaultCredentials = true;
using (var client = new HttpClient(handler))
using (HttpResponseMessage response = await client.GetAsync(s_multipleSchemesAuthenticatedServer))
@@ -125,10 +131,10 @@ namespace System.Net.Http.Functional.Tests
[InlineData(true)]
public async Task Credentials_SetToSpecificCredential_ConnectAsSpecificIdentity(bool useProxy)
{
- var handler = new HttpClientHandler {
- UseProxy = useProxy,
- UseDefaultCredentials = false,
- Credentials = _specificCredential };
+ HttpClientHandler handler = CreateHttpClientHandler();
+ handler.UseProxy = useProxy;
+ handler.UseDefaultCredentials = false;
+ handler.Credentials = _specificCredential;
using (var client = new HttpClient(handler))
using (HttpResponseMessage response = await client.GetAsync(s_authenticatedServer))
@@ -147,7 +153,7 @@ namespace System.Net.Http.Functional.Tests
[InlineData(true)]
public async Task Credentials_SetToWrappedDefaultCredential_ConnectAsCurrentIdentity(bool useProxy)
{
- var handler = new HttpClientHandler();
+ HttpClientHandler handler = CreateHttpClientHandler();
handler.UseProxy = useProxy;
handler.Credentials = new CredentialWrapper
{
@@ -171,7 +177,7 @@ namespace System.Net.Http.Functional.Tests
[ConditionalFact(nameof(DomainProxyTestsEnabled))]
public async Task Proxy_UseAuthenticatedProxyWithNoCredentials_ProxyAuthenticationRequired()
{
- var handler = new HttpClientHandler();
+ HttpClientHandler handler = CreateHttpClientHandler();
handler.Proxy = new AuthenticatedProxy(null);
using (var client = new HttpClient(handler))
@@ -186,7 +192,7 @@ namespace System.Net.Http.Functional.Tests
[ConditionalFact(nameof(DomainProxyTestsEnabled))]
public async Task Proxy_UseAuthenticatedProxyWithDefaultCredentials_OK()
{
- var handler = new HttpClientHandler();
+ HttpClientHandler handler = CreateHttpClientHandler();
handler.Proxy = new AuthenticatedProxy(CredentialCache.DefaultCredentials);
using (var client = new HttpClient(handler))
@@ -205,7 +211,7 @@ namespace System.Net.Http.Functional.Tests
InnerCredentials = CredentialCache.DefaultCredentials
};
- var handler = new HttpClientHandler();
+ HttpClientHandler handler = CreateHttpClientHandler();
handler.Proxy = new AuthenticatedProxy(wrappedCreds);
using (var client = new HttpClient(handler))
diff --git a/src/System.Net.Http/tests/FunctionalTests/DiagnosticsTests.cs b/src/System.Net.Http/tests/FunctionalTests/DiagnosticsTests.cs
index 8942afaf81..f899baa83f 100644
--- a/src/System.Net.Http/tests/FunctionalTests/DiagnosticsTests.cs
+++ b/src/System.Net.Http/tests/FunctionalTests/DiagnosticsTests.cs
@@ -6,7 +6,6 @@ using System.Collections.Concurrent;
using System.Collections.Generic;
using System.Diagnostics;
using System.Diagnostics.Tracing;
-using System.IO;
using System.Linq;
using System.Net.Http.Headers;
using System.Net.Test.Common;
@@ -21,7 +20,7 @@ namespace System.Net.Http.Functional.Tests
[ActiveIssue(20470, TargetFrameworkMonikers.UapAot)]
[SkipOnTargetFramework(TargetFrameworkMonikers.NetFramework, "NetEventSource is only part of .NET Core.")]
- public class DiagnosticsTest : RemoteExecutorTestBase
+ public class DiagnosticsTest : HttpClientTestBase
{
[Fact]
public static void EventSource_ExistsWithCorrectId()
@@ -48,7 +47,7 @@ namespace System.Net.Http.Functional.Tests
[Fact]
public void SendAsync_ExpectedDiagnosticSourceLogging()
{
- RemoteInvoke(() =>
+ RemoteInvoke(useManagedHandlerString =>
{
bool requestLogged = false;
Guid requestGuid = Guid.Empty;
@@ -90,7 +89,7 @@ namespace System.Net.Http.Functional.Tests
using (DiagnosticListener.AllListeners.Subscribe(diagnosticListenerObserver))
{
diagnosticListenerObserver.Enable( s => !s.Contains("HttpRequestOut"));
- using (var client = new HttpClient())
+ using (HttpClient client = CreateHttpClient(useManagedHandlerString))
{
client.GetAsync(Configuration.Http.RemoteEchoServer).Result.Dispose();
}
@@ -105,7 +104,7 @@ namespace System.Net.Http.Functional.Tests
}
return SuccessExitCode;
- }).Dispose();
+ }, UseManagedHandler.ToString()).Dispose();
}
/// <remarks>
@@ -116,7 +115,7 @@ namespace System.Net.Http.Functional.Tests
[Fact]
public void SendAsync_ExpectedDiagnosticSourceNoLogging()
{
- RemoteInvoke(() =>
+ RemoteInvoke(useManagedHandlerString =>
{
bool requestLogged = false;
bool responseLogged = false;
@@ -145,7 +144,7 @@ namespace System.Net.Http.Functional.Tests
using (DiagnosticListener.AllListeners.Subscribe(diagnosticListenerObserver))
{
- using (var client = new HttpClient())
+ using (HttpClient client = CreateHttpClient(useManagedHandlerString))
{
LoopbackServer.CreateServerAsync(async (server, url) =>
{
@@ -165,14 +164,15 @@ namespace System.Net.Http.Functional.Tests
Assert.False(activityStopLogged, "HttpRequestOut.Stop was logged while logging disabled.");
}
return SuccessExitCode;
- }).Dispose();
+ }, UseManagedHandler.ToString()).Dispose();
}
+ [ActiveIssue(23771, TestPlatforms.AnyUnix)]
[OuterLoop] // TODO: Issue #11345
[Fact]
public void SendAsync_HttpTracingEnabled_Succeeds()
{
- RemoteInvoke(async () =>
+ RemoteInvoke(async useManagedHandlerString =>
{
using (var listener = new TestEventListener("Microsoft-System-Net-Http", EventLevel.Verbose))
{
@@ -180,7 +180,7 @@ namespace System.Net.Http.Functional.Tests
await listener.RunWithCallbackAsync(events.Enqueue, async () =>
{
// Exercise various code paths to get coverage of tracing
- using (var client = new HttpClient())
+ using (HttpClient client = CreateHttpClient(useManagedHandlerString))
{
// Do a get to a loopback server
await LoopbackServer.CreateServerAsync(async (server, url) =>
@@ -209,14 +209,14 @@ namespace System.Net.Http.Functional.Tests
}
return SuccessExitCode;
- }).Dispose();
+ }, UseManagedHandler.ToString()).Dispose();
}
[OuterLoop] // TODO: Issue #11345
[Fact]
public void SendAsync_ExpectedDiagnosticExceptionLogging()
{
- RemoteInvoke(() =>
+ RemoteInvoke(useManagedHandlerString =>
{
bool exceptionLogged = false;
bool responseLogged = false;
@@ -242,7 +242,7 @@ namespace System.Net.Http.Functional.Tests
using (DiagnosticListener.AllListeners.Subscribe(diagnosticListenerObserver))
{
diagnosticListenerObserver.Enable(s => !s.Contains("HttpRequestOut"));
- using (var client = new HttpClient())
+ using (HttpClient client = CreateHttpClient(useManagedHandlerString))
{
Assert.ThrowsAsync<HttpRequestException>(() => client.GetAsync($"http://{Guid.NewGuid()}.com")).Wait();
}
@@ -254,14 +254,15 @@ namespace System.Net.Http.Functional.Tests
}
return SuccessExitCode;
- }).Dispose();
+ }, UseManagedHandler.ToString()).Dispose();
}
+ [ActiveIssue(23209)]
[OuterLoop] // TODO: Issue #11345
[Fact]
public void SendAsync_ExpectedDiagnosticCancelledLogging()
{
- RemoteInvoke(() =>
+ RemoteInvoke(useManagedHandlerString =>
{
bool cancelLogged = false;
var diagnosticListenerObserver = new FakeDiagnosticListenerObserver(kvp =>
@@ -278,7 +279,7 @@ namespace System.Net.Http.Functional.Tests
using (DiagnosticListener.AllListeners.Subscribe(diagnosticListenerObserver))
{
diagnosticListenerObserver.Enable(s => !s.Contains("HttpRequestOut"));
- using (var client = new HttpClient())
+ using (HttpClient client = CreateHttpClient(useManagedHandlerString))
{
LoopbackServer.CreateServerAsync(async (server, url) =>
{
@@ -300,14 +301,14 @@ namespace System.Net.Http.Functional.Tests
diagnosticListenerObserver.Disable();
return SuccessExitCode;
- }).Dispose();
+ }, UseManagedHandler.ToString()).Dispose();
}
[OuterLoop] // TODO: Issue #11345
[Fact]
public void SendAsync_ExpectedDiagnosticSourceActivityLogging()
{
- RemoteInvoke(() =>
+ RemoteInvoke(useManagedHandlerString =>
{
bool requestLogged = false;
bool responseLogged = false;
@@ -353,7 +354,7 @@ namespace System.Net.Http.Functional.Tests
using (DiagnosticListener.AllListeners.Subscribe(diagnosticListenerObserver))
{
diagnosticListenerObserver.Enable(s => s.Contains("HttpRequestOut"));
- using (var client = new HttpClient())
+ using (HttpClient client = CreateHttpClient(useManagedHandlerString))
{
LoopbackServer.CreateServerAsync(async (server, url) =>
{
@@ -377,14 +378,14 @@ namespace System.Net.Http.Functional.Tests
}
return SuccessExitCode;
- }).Dispose();
+ }, UseManagedHandler.ToString()).Dispose();
}
[OuterLoop] // TODO: Issue #11345
[Fact]
public void SendAsync_ExpectedDiagnosticSourceUrlFilteredActivityLogging()
{
- RemoteInvoke(() =>
+ RemoteInvoke(useManagedHandlerString =>
{
bool activityStartLogged = false;
bool activityStopLogged = false;
@@ -407,7 +408,7 @@ namespace System.Net.Http.Functional.Tests
}
return true;
});
- using (var client = new HttpClient())
+ using (HttpClient client = CreateHttpClient(useManagedHandlerString))
{
client.GetAsync(Configuration.Http.RemoteEchoServer).Result.Dispose();
}
@@ -418,14 +419,14 @@ namespace System.Net.Http.Functional.Tests
}
return SuccessExitCode;
- }).Dispose();
+ }, UseManagedHandler.ToString()).Dispose();
}
[OuterLoop] // TODO: Issue #11345
[Fact]
public void SendAsync_ExpectedDiagnosticExceptionActivityLogging()
{
- RemoteInvoke(() =>
+ RemoteInvoke(useManagedHandlerString =>
{
bool exceptionLogged = false;
bool activityStopLogged = false;
@@ -452,7 +453,7 @@ namespace System.Net.Http.Functional.Tests
using (DiagnosticListener.AllListeners.Subscribe(diagnosticListenerObserver))
{
diagnosticListenerObserver.Enable();
- using (var client = new HttpClient())
+ using (HttpClient client = CreateHttpClient(useManagedHandlerString))
{
Assert.ThrowsAsync<HttpRequestException>(() => client.GetAsync($"http://{Guid.NewGuid()}.com")).Wait();
}
@@ -464,14 +465,14 @@ namespace System.Net.Http.Functional.Tests
}
return SuccessExitCode;
- }).Dispose();
+ }, UseManagedHandler.ToString()).Dispose();
}
[OuterLoop] // TODO: Issue #11345
[Fact]
public void SendAsync_ExpectedDiagnosticSourceNewAndDeprecatedEventsLogging()
{
- RemoteInvoke(() =>
+ RemoteInvoke(useManagedHandlerString =>
{
bool requestLogged = false;
bool responseLogged = false;
@@ -489,7 +490,7 @@ namespace System.Net.Http.Functional.Tests
using (DiagnosticListener.AllListeners.Subscribe(diagnosticListenerObserver))
{
diagnosticListenerObserver.Enable();
- using (var client = new HttpClient())
+ using (HttpClient client = CreateHttpClient(useManagedHandlerString))
{
client.GetAsync(Configuration.Http.RemoteEchoServer).Result.Dispose();
}
@@ -503,14 +504,14 @@ namespace System.Net.Http.Functional.Tests
}
return SuccessExitCode;
- }).Dispose();
+ }, UseManagedHandler.ToString()).Dispose();
}
[OuterLoop] // TODO: Issue #11345
[Fact]
public void SendAsync_ExpectedDiagnosticExceptionOnlyActivityLogging()
{
- RemoteInvoke(() =>
+ RemoteInvoke(useManagedHandlerString =>
{
bool exceptionLogged = false;
bool activityLogged = false;
@@ -529,7 +530,7 @@ namespace System.Net.Http.Functional.Tests
using (DiagnosticListener.AllListeners.Subscribe(diagnosticListenerObserver))
{
diagnosticListenerObserver.Enable(s => s.Equals("System.Net.Http.Exception"));
- using (var client = new HttpClient())
+ using (HttpClient client = CreateHttpClient(useManagedHandlerString))
{
Assert.ThrowsAsync<HttpRequestException>(() => client.GetAsync($"http://{Guid.NewGuid()}.com")).Wait();
}
@@ -541,14 +542,14 @@ namespace System.Net.Http.Functional.Tests
}
return SuccessExitCode;
- }).Dispose();
+ }, UseManagedHandler.ToString()).Dispose();
}
[OuterLoop] // TODO: Issue #11345
[Fact]
public void SendAsync_ExpectedDiagnosticStopOnlyActivityLogging()
{
- RemoteInvoke(() =>
+ RemoteInvoke(useManagedHandlerString =>
{
bool activityStartLogged = false;
bool activityStopLogged = false;
@@ -566,7 +567,7 @@ namespace System.Net.Http.Functional.Tests
using (DiagnosticListener.AllListeners.Subscribe(diagnosticListenerObserver))
{
diagnosticListenerObserver.Enable(s => s.Equals("System.Net.Http.HttpRequestOut"));
- using (var client = new HttpClient())
+ using (HttpClient client = CreateHttpClient(useManagedHandlerString))
{
client.GetAsync(Configuration.Http.RemoteEchoServer).Result.Dispose();
}
@@ -578,14 +579,14 @@ namespace System.Net.Http.Functional.Tests
}
return SuccessExitCode;
- }).Dispose();
+ }, UseManagedHandler.ToString()).Dispose();
}
[OuterLoop] // TODO: Issue #11345
[Fact]
public void SendAsync_ExpectedDiagnosticCancelledActivityLogging()
{
- RemoteInvoke(() =>
+ RemoteInvoke(useManagedHandlerString =>
{
bool cancelLogged = false;
var diagnosticListenerObserver = new FakeDiagnosticListenerObserver(kvp =>
@@ -603,7 +604,7 @@ namespace System.Net.Http.Functional.Tests
using (DiagnosticListener.AllListeners.Subscribe(diagnosticListenerObserver))
{
diagnosticListenerObserver.Enable();
- using (var client = new HttpClient())
+ using (HttpClient client = CreateHttpClient(useManagedHandlerString))
{
LoopbackServer.CreateServerAsync(async (server, url) =>
{
@@ -625,7 +626,7 @@ namespace System.Net.Http.Functional.Tests
diagnosticListenerObserver.Disable();
return SuccessExitCode;
- }).Dispose();
+ }, UseManagedHandler.ToString()).Dispose();
}
private static T GetPropertyValueFromAnonymousTypeInstance<T>(object obj, string propertyName)
diff --git a/src/System.Net.Http/tests/FunctionalTests/HttpClientEKUTest.cs b/src/System.Net.Http/tests/FunctionalTests/HttpClientEKUTest.cs
index 831c89310e..d5c693a6fd 100644
--- a/src/System.Net.Http/tests/FunctionalTests/HttpClientEKUTest.cs
+++ b/src/System.Net.Http/tests/FunctionalTests/HttpClientEKUTest.cs
@@ -15,7 +15,7 @@ namespace System.Net.Http.Functional.Tests
{
using Configuration = System.Net.Test.Common.Configuration;
- public class HttpClientEKUTest
+ public class HttpClientEKUTest : HttpClientTestBase
{
// Curl + OSX SecureTransport doesn't support the custom certificate callback.
private static bool BackendSupportsCustomCertificateHandling =>
@@ -56,7 +56,7 @@ namespace System.Net.Http.Functional.Tests
options.ServerCertificate = serverCertificateNoEku;
using (var server = new HttpsTestServer(options))
- using (var handler = new HttpClientHandler())
+ using (HttpClientHandler handler = CreateHttpClientHandler())
using (var client = new HttpClient(handler))
{
server.Start();
@@ -78,7 +78,7 @@ namespace System.Net.Http.Functional.Tests
options.ServerCertificate = serverCertificateWrongEku;
using (var server = new HttpsTestServer(options))
- using (var handler = new HttpClientHandler())
+ using (HttpClientHandler handler = CreateHttpClientHandler())
using (var client = new HttpClient(handler))
{
server.Start();
@@ -101,7 +101,7 @@ namespace System.Net.Http.Functional.Tests
options.RequireClientAuthentication = true;
using (var server = new HttpsTestServer(options))
- using (var handler = new HttpClientHandler())
+ using (HttpClientHandler handler = CreateHttpClientHandler())
using (var client = new HttpClient(handler))
{
server.Start();
@@ -125,7 +125,7 @@ namespace System.Net.Http.Functional.Tests
options.RequireClientAuthentication = true;
using (var server = new HttpsTestServer(options))
- using (var handler = new HttpClientHandler())
+ using (HttpClientHandler handler = CreateHttpClientHandler())
using (var client = new HttpClient(handler))
{
server.Start();
diff --git a/src/System.Net.Http/tests/FunctionalTests/HttpClientHandlerTest.AcceptAllCerts.cs b/src/System.Net.Http/tests/FunctionalTests/HttpClientHandlerTest.AcceptAllCerts.cs
index 157a84a306..b1544255b1 100644
--- a/src/System.Net.Http/tests/FunctionalTests/HttpClientHandlerTest.AcceptAllCerts.cs
+++ b/src/System.Net.Http/tests/FunctionalTests/HttpClientHandlerTest.AcceptAllCerts.cs
@@ -5,7 +5,6 @@
using System.Net.Security;
using System.Net.Test.Common;
using System.Security.Authentication;
-using System.Security.Cryptography.X509Certificates;
using System.Threading.Tasks;
using Xunit;
@@ -13,7 +12,7 @@ namespace System.Net.Http.Functional.Tests
{
using Configuration = System.Net.Test.Common.Configuration;
- public class HttpClientHandler_DangerousAcceptAllCertificatesValidator_Test
+ public class HttpClientHandler_DangerousAcceptAllCertificatesValidator_Test : HttpClientTestBase
{
// TODO: https://github.com/dotnet/corefx/issues/7812
private static bool ClientSupportsDHECipherSuites => (!PlatformDetection.IsWindows || PlatformDetection.IsWindows10Version1607OrGreater);
@@ -35,9 +34,11 @@ namespace System.Net.Http.Functional.Tests
[InlineData(SslProtocols.None, true)]
public async Task SetDelegate_ConnectionSucceeds(SslProtocols acceptedProtocol, bool requestOnlyThisProtocol)
{
- using (var handler = new HttpClientHandler() { ServerCertificateCustomValidationCallback = HttpClientHandler.DangerousAcceptAnyServerCertificateValidator })
+ using (HttpClientHandler handler = CreateHttpClientHandler())
using (var client = new HttpClient(handler))
{
+ handler.ServerCertificateCustomValidationCallback = HttpClientHandler.DangerousAcceptAnyServerCertificateValidator;
+
// 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
@@ -69,8 +70,10 @@ namespace System.Net.Http.Functional.Tests
[MemberData(nameof(InvalidCertificateServers))]
public async Task InvalidCertificateServers_CertificateValidationDisabled_Succeeds(string url)
{
- using (var client = new HttpClient(new HttpClientHandler() { ServerCertificateCustomValidationCallback = HttpClientHandler.DangerousAcceptAnyServerCertificateValidator }))
+ using (HttpClientHandler handler = CreateHttpClientHandler())
+ using (var client = new HttpClient(handler))
{
+ handler.ServerCertificateCustomValidationCallback = HttpClientHandler.DangerousAcceptAnyServerCertificateValidator;
(await client.GetAsync(url)).Dispose();
}
}
diff --git a/src/System.Net.Http/tests/FunctionalTests/HttpClientHandlerTest.ClientCertificates.cs b/src/System.Net.Http/tests/FunctionalTests/HttpClientHandlerTest.ClientCertificates.cs
index 84262143d7..9530ce22fe 100644
--- a/src/System.Net.Http/tests/FunctionalTests/HttpClientHandlerTest.ClientCertificates.cs
+++ b/src/System.Net.Http/tests/FunctionalTests/HttpClientHandlerTest.ClientCertificates.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.Net.Security;
using System.Net.Sockets;
using System.Net.Test.Common;
@@ -15,13 +14,13 @@ namespace System.Net.Http.Functional.Tests
{
using Configuration = System.Net.Test.Common.Configuration;
- public class HttpClientHandler_ClientCertificates_Test : RemoteExecutorTestBase
+ public class HttpClientHandler_ClientCertificates_Test : HttpClientTestBase
{
- public static bool CanTestCertificates =>
+ public bool CanTestCertificates =>
Capability.IsTrustedRootCertificateInstalled() &&
(BackendSupportsCustomCertificateHandling || Capability.AreHostsFileNamesInstalled());
- public static bool CanTestClientCertificates =>
+ public bool CanTestClientCertificates =>
CanTestCertificates && BackendSupportsCustomCertificateHandling;
public HttpClientHandler_ClientCertificates_Test(ITestOutputHelper output)
@@ -33,7 +32,7 @@ namespace System.Net.Http.Functional.Tests
[Fact]
public void ClientCertificateOptions_Default()
{
- using (var handler = new HttpClientHandler())
+ using (HttpClientHandler handler = CreateHttpClientHandler())
{
Assert.Equal(ClientCertificateOption.Manual, handler.ClientCertificateOptions);
}
@@ -44,7 +43,7 @@ namespace System.Net.Http.Functional.Tests
[InlineData((ClientCertificateOption)(-1))]
public void ClientCertificateOptions_InvalidArg_ThrowsException(ClientCertificateOption option)
{
- using (var handler = new HttpClientHandler())
+ using (HttpClientHandler handler = CreateHttpClientHandler())
{
AssertExtensions.Throws<ArgumentOutOfRangeException>("value", () => handler.ClientCertificateOptions = option);
}
@@ -55,7 +54,7 @@ namespace System.Net.Http.Functional.Tests
[InlineData(ClientCertificateOption.Manual)]
public void ClientCertificateOptions_ValueArg_Roundtrips(ClientCertificateOption option)
{
- using (var handler = new HttpClientHandler())
+ using (HttpClientHandler handler = CreateHttpClientHandler())
{
handler.ClientCertificateOptions = option;
Assert.Equal(option, handler.ClientCertificateOptions);
@@ -65,7 +64,7 @@ namespace System.Net.Http.Functional.Tests
[Fact]
public void ClientCertificates_ClientCertificateOptionsAutomatic_ThrowsException()
{
- using (var handler = new HttpClientHandler())
+ using (HttpClientHandler handler = CreateHttpClientHandler())
{
handler.ClientCertificateOptions = ClientCertificateOption.Automatic;
Assert.Throws<InvalidOperationException>(() => handler.ClientCertificates);
@@ -81,8 +80,10 @@ namespace System.Net.Http.Functional.Tests
return;
}
- using (var client = new HttpClient(new HttpClientHandler() { ClientCertificateOptions = ClientCertificateOption.Automatic }))
+ using (HttpClientHandler handler = CreateHttpClientHandler())
+ using (var client = new HttpClient(handler))
{
+ handler.ClientCertificateOptions = ClientCertificateOption.Automatic;
await Assert.ThrowsAsync<PlatformNotSupportedException>(() => client.GetAsync(Configuration.Http.SecureRemoteEchoServer));
}
}
@@ -96,7 +97,7 @@ namespace System.Net.Http.Functional.Tests
return;
}
- var handler = new HttpClientHandler();
+ HttpClientHandler handler = CreateHttpClientHandler();
handler.ClientCertificates.Add(Configuration.Certificates.GetClientCertificate());
using (var client = new HttpClient(handler))
{
@@ -117,10 +118,10 @@ namespace System.Net.Http.Functional.Tests
// 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 () =>
+ RemoteInvoke(async useManagedHandlerString =>
{
var cert = Configuration.Certificates.GetClientCertificate();
- var handler = new HttpClientHandler();
+ HttpClientHandler handler = CreateHttpClientHandler(useManagedHandlerString);
handler.ClientCertificates.Add(cert);
using (var client = new HttpClient(handler))
{
@@ -134,14 +135,14 @@ namespace System.Net.Http.Functional.Tests
return SuccessExitCode;
}
- }).Dispose();
+ }, UseManagedHandler.ToString()).Dispose();
}
[OuterLoop] // TODO: Issue #11345
[Fact]
public void Manual_SendClientCertificateWithServerAuthEKUToRemoteServer_Forbidden()
{
- if (ManagedHandlerTestHelpers.IsEnabled)
+ if (UseManagedHandler)
{
// TODO #23128: The managed handler is currently sending out client certificates when it shouldn't.
return;
@@ -156,10 +157,10 @@ namespace System.Net.Http.Functional.Tests
// 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 () =>
+ RemoteInvoke(async useManagedHandlerString =>
{
var cert = Configuration.Certificates.GetServerCertificate();
- var handler = new HttpClientHandler();
+ HttpClientHandler handler = CreateHttpClientHandler(useManagedHandlerString);
handler.ClientCertificates.Add(cert);
using (var client = new HttpClient(handler))
{
@@ -168,7 +169,7 @@ namespace System.Net.Http.Functional.Tests
return SuccessExitCode;
}
- }).Dispose();
+ }, UseManagedHandler.ToString()).Dispose();
}
[OuterLoop] // TODO: Issue #11345
@@ -184,10 +185,10 @@ namespace System.Net.Http.Functional.Tests
// 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 () =>
+ RemoteInvoke(async useManagedHandlerString =>
{
var cert = Configuration.Certificates.GetNoEKUCertificate();
- var handler = new HttpClientHandler();
+ HttpClientHandler handler = CreateHttpClientHandler(useManagedHandlerString);
handler.ClientCertificates.Add(cert);
using (var client = new HttpClient(handler))
{
@@ -201,7 +202,7 @@ namespace System.Net.Http.Functional.Tests
return SuccessExitCode;
}
- }).Dispose();
+ }, UseManagedHandler.ToString()).Dispose();
}
[SkipOnTargetFramework(TargetFrameworkMonikers.Uap, "dotnet/corefx #20010")]
@@ -214,7 +215,7 @@ namespace System.Net.Http.Functional.Tests
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
+ if (!BackendSupportsCustomCertificateHandling) // 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;
@@ -224,7 +225,8 @@ namespace System.Net.Http.Functional.Tests
Func<X509Certificate2, HttpClient> createClient = (cert) =>
{
- var handler = new HttpClientHandler() { ServerCertificateCustomValidationCallback = delegate { return true; } };
+ HttpClientHandler handler = CreateHttpClientHandler();
+ handler.ServerCertificateCustomValidationCallback = delegate { return true; };
handler.ClientCertificates.Add(cert);
return new HttpClient(handler);
};
@@ -279,9 +281,8 @@ namespace System.Net.Http.Functional.Tests
}, options);
}
- private static bool BackendSupportsCustomCertificateHandling =>
- HttpClientHandler_ServerCertificates_Test.BackendSupportsCustomCertificateHandling;
-
- private static bool BackendDoesNotSupportCustomCertificateHandling => !BackendSupportsCustomCertificateHandling;
+ private bool BackendSupportsCustomCertificateHandling =>
+ UseManagedHandler ||
+ new HttpClientHandler_ServerCertificates_Test().BackendSupportsCustomCertificateHandling;
}
}
diff --git a/src/System.Net.Http/tests/FunctionalTests/HttpClientHandlerTest.DefaultProxyCredentials.cs b/src/System.Net.Http/tests/FunctionalTests/HttpClientHandlerTest.DefaultProxyCredentials.cs
index 085cb57da5..547ea250aa 100644
--- a/src/System.Net.Http/tests/FunctionalTests/HttpClientHandlerTest.DefaultProxyCredentials.cs
+++ b/src/System.Net.Http/tests/FunctionalTests/HttpClientHandlerTest.DefaultProxyCredentials.cs
@@ -4,6 +4,7 @@
using System.Diagnostics;
using System.Net.Test.Common;
+using System.Runtime.InteropServices;
using System.Text;
using System.Threading.Tasks;
using Xunit;
@@ -12,12 +13,12 @@ namespace System.Net.Http.Functional.Tests
{
using Configuration = System.Net.Test.Common.Configuration;
- public class HttpClientHandler_DefaultProxyCredentials_Test : RemoteExecutorTestBase
+ public class HttpClientHandler_DefaultProxyCredentials_Test : HttpClientTestBase
{
[Fact]
public void Default_Get_Null()
{
- using (var handler = new HttpClientHandler())
+ using (HttpClientHandler handler = CreateHttpClientHandler())
{
Assert.Null(handler.DefaultProxyCredentials);
}
@@ -26,7 +27,7 @@ namespace System.Net.Http.Functional.Tests
[Fact]
public void SetGet_Roundtrips()
{
- using (var handler = new HttpClientHandler())
+ using (HttpClientHandler handler = CreateHttpClientHandler())
{
var creds = new NetworkCredential("username", "password", "domain");
@@ -41,6 +42,7 @@ namespace System.Net.Http.Functional.Tests
}
}
+ [ActiveIssue(23702, TargetFrameworkMonikers.NetFramework)]
[ActiveIssue(20010, TargetFrameworkMonikers.Uap)]
[OuterLoop] // TODO: Issue #11345
[Fact]
@@ -53,7 +55,7 @@ namespace System.Net.Http.Functional.Tests
var rightCreds = new NetworkCredential("rightusername", "rightpassword");
var wrongCreds = new NetworkCredential("wrongusername", "wrongpassword");
- using (var handler = new HttpClientHandler())
+ using (HttpClientHandler handler = CreateHttpClientHandler())
using (var client = new HttpClient(handler))
{
handler.Proxy = new UseSpecifiedUriWebProxy(proxyUrl, rightCreds);
@@ -75,12 +77,23 @@ namespace System.Net.Http.Functional.Tests
}
[OuterLoop] // TODO: Issue #11345
- [Fact]
- [PlatformSpecific(TestPlatforms.AnyUnix)] // proxies set via the http_proxy environment variable are specific to Unix
- public void ProxySetViaEnvironmentVariable_DefaultProxyCredentialsUsed()
+ [Theory]
+ [InlineData(false)]
+ [InlineData(true)]
+ public void ProxySetViaEnvironmentVariable_DefaultProxyCredentialsUsed(bool useProxy)
{
- int port;
- Task<LoopbackGetRequestHttpProxy.ProxyResult> proxyTask = LoopbackGetRequestHttpProxy.StartAsync(out port, requireAuth: true, expectCreds: true);
+ bool envVarsSupported = UseManagedHandler || !RuntimeInformation.IsOSPlatform(OSPlatform.Windows);
+ if (!envVarsSupported)
+ {
+ return;
+ }
+
+ int port = 0;
+ Task<LoopbackGetRequestHttpProxy.ProxyResult> proxyTask = null;
+ if (useProxy)
+ {
+ proxyTask = LoopbackGetRequestHttpProxy.StartAsync(out port, requireAuth: true, expectCreds: true);
+ }
const string ExpectedUsername = "rightusername";
const string ExpectedPassword = "rightpassword";
@@ -90,13 +103,14 @@ namespace System.Net.Http.Functional.Tests
// test in another process.
var psi = new ProcessStartInfo();
psi.Environment.Add("http_proxy", $"http://localhost:{port}");
- RemoteInvoke(() =>
+ RemoteInvoke((useProxyString, useManagedHandlerString) =>
{
- using (var handler = new HttpClientHandler())
+ using (HttpClientHandler handler = CreateHttpClientHandler(useManagedHandlerString))
using (var client = new HttpClient(handler))
{
var creds = new NetworkCredential(ExpectedUsername, ExpectedPassword);
handler.DefaultProxyCredentials = creds;
+ handler.UseProxy = bool.Parse(useProxyString);
Task<HttpResponseMessage> responseTask = client.GetAsync(Configuration.Http.RemoteEchoServer);
Task<string> responseStringTask = responseTask.ContinueWith(t =>
@@ -108,9 +122,12 @@ namespace System.Net.Http.Functional.Tests
TestHelper.VerifyResponseBody(responseStringTask.Result, responseTask.Result.Content.Headers.ContentMD5, false, null);
}
return SuccessExitCode;
- }, new RemoteInvokeOptions { StartInfo = psi }).Dispose();
+ }, useProxy.ToString(), UseManagedHandler.ToString(), new RemoteInvokeOptions { StartInfo = psi }).Dispose();
- Assert.Equal($"{ExpectedUsername}:{ExpectedPassword}", proxyTask.Result.AuthenticationHeaderValue);
+ if (useProxy)
+ {
+ Assert.Equal($"{ExpectedUsername}:{ExpectedPassword}", proxyTask.Result.AuthenticationHeaderValue);
+ }
}
// The purpose of this test is mainly to validate the .NET Framework OOB System.Net.Http implementation
@@ -122,7 +139,7 @@ namespace System.Net.Http.Functional.Tests
{
WebRequest.DefaultWebProxy = null;
- using (var handler = new HttpClientHandler())
+ using (HttpClientHandler handler = CreateHttpClientHandler())
using (var client = new HttpClient(handler))
{
handler.DefaultProxyCredentials = new NetworkCredential("UsernameNotUsed", "PasswordNotUsed");
diff --git a/src/System.Net.Http/tests/FunctionalTests/HttpClientHandlerTest.MaxConnectionsPerServer.cs b/src/System.Net.Http/tests/FunctionalTests/HttpClientHandlerTest.MaxConnectionsPerServer.cs
index 87aa8dcee5..f53be768eb 100644
--- a/src/System.Net.Http/tests/FunctionalTests/HttpClientHandlerTest.MaxConnectionsPerServer.cs
+++ b/src/System.Net.Http/tests/FunctionalTests/HttpClientHandlerTest.MaxConnectionsPerServer.cs
@@ -3,7 +3,6 @@
// See the LICENSE file in the project root for more information.
using System.Linq;
-using System.Net.Test.Common;
using System.Runtime.InteropServices;
using System.Threading.Tasks;
@@ -14,13 +13,13 @@ namespace System.Net.Http.Functional.Tests
using Configuration = System.Net.Test.Common.Configuration;
[SkipOnTargetFramework(TargetFrameworkMonikers.Uap, "dotnet/corefx #20010")]
- public class HttpClientHandler_MaxConnectionsPerServer_Test
+ public class HttpClientHandler_MaxConnectionsPerServer_Test : HttpClientTestBase
{
[Fact]
[SkipOnTargetFramework(TargetFrameworkMonikers.NetFramework, "MaxConnectionsPerServer either returns two or int.MaxValue depending if ctor of HttpClientHandlerTest executed first. Disabling cause of random xunit execution order.")]
public void Default_ExpectedValue()
{
- using (var handler = new HttpClientHandler())
+ using (HttpClientHandler handler = CreateHttpClientHandler())
{
Assert.Equal(int.MaxValue, handler.MaxConnectionsPerServer);
}
@@ -31,7 +30,7 @@ namespace System.Net.Http.Functional.Tests
[InlineData(-1)]
public void Set_InvalidValues_Throws(int invalidValue)
{
- using (var handler = new HttpClientHandler())
+ using (HttpClientHandler handler = CreateHttpClientHandler())
{
Assert.Throws<ArgumentOutOfRangeException>(() => handler.MaxConnectionsPerServer = invalidValue);
}
@@ -44,7 +43,7 @@ namespace System.Net.Http.Functional.Tests
[InlineData(int.MaxValue - 1)]
public void Set_ValidValues_Success(int validValue)
{
- using (var handler = new HttpClientHandler())
+ using (HttpClientHandler handler = CreateHttpClientHandler())
{
try
{
@@ -68,8 +67,10 @@ namespace System.Net.Http.Functional.Tests
[InlineData(3, 5, false)]
public async Task GetAsync_MaxLimited_ConcurrentCallsStillSucceed(int maxConnections, int numRequests, bool secure)
{
- using (var client = new HttpClient(new HttpClientHandler { MaxConnectionsPerServer = maxConnections }))
+ using (HttpClientHandler handler = CreateHttpClientHandler())
+ using (var client = new HttpClient(handler))
{
+ handler.MaxConnectionsPerServer = maxConnections;
await Task.WhenAll(
from i in Enumerable.Range(0, numRequests)
select client.GetAsync(secure ? Configuration.Http.RemoteEchoServer : Configuration.Http.SecureRemoteEchoServer));
diff --git a/src/System.Net.Http/tests/FunctionalTests/HttpClientHandlerTest.MaxResponseHeadersLength.cs b/src/System.Net.Http/tests/FunctionalTests/HttpClientHandlerTest.MaxResponseHeadersLength.cs
index c04259a14e..1a666845c9 100644
--- a/src/System.Net.Http/tests/FunctionalTests/HttpClientHandlerTest.MaxResponseHeadersLength.cs
+++ b/src/System.Net.Http/tests/FunctionalTests/HttpClientHandlerTest.MaxResponseHeadersLength.cs
@@ -3,9 +3,6 @@
// See the LICENSE file in the project root for more information.
using System.Collections.Generic;
-using System.Diagnostics;
-using System.IO;
-using System.Net.Sockets;
using System.Net.Test.Common;
using System.Text;
using System.Threading.Tasks;
@@ -15,7 +12,7 @@ namespace System.Net.Http.Functional.Tests
{
using Configuration = System.Net.Test.Common.Configuration;
- public class HttpClientHandler_MaxResponseHeadersLength_Test : RemoteExecutorTestBase
+ public class HttpClientHandler_MaxResponseHeadersLength_Test : HttpClientTestBase
{
[SkipOnTargetFramework(TargetFrameworkMonikers.Uap, "Not currently supported on UAP")]
[Theory]
@@ -23,7 +20,7 @@ namespace System.Net.Http.Functional.Tests
[InlineData(-1)]
public void InvalidValue_ThrowsException(int invalidValue)
{
- using (var handler = new HttpClientHandler())
+ using (HttpClientHandler handler = CreateHttpClientHandler())
{
AssertExtensions.Throws<ArgumentOutOfRangeException>("value", () => handler.MaxResponseHeadersLength = invalidValue);
}
@@ -36,7 +33,7 @@ namespace System.Net.Http.Functional.Tests
[InlineData(int.MaxValue)]
public void ValidValue_SetGet_Roundtrips(int validValue)
{
- using (var handler = new HttpClientHandler())
+ using (HttpClientHandler handler = CreateHttpClientHandler())
{
handler.MaxResponseHeadersLength = validValue;
Assert.Equal(validValue, handler.MaxResponseHeadersLength);
@@ -46,7 +43,7 @@ namespace System.Net.Http.Functional.Tests
[Fact]
public async Task SetAfterUse_Throws()
{
- using (var handler = new HttpClientHandler())
+ using (HttpClientHandler handler = CreateHttpClientHandler())
using (var client = new HttpClient(handler))
{
handler.MaxResponseHeadersLength = int.MaxValue;
@@ -62,9 +59,10 @@ namespace System.Net.Http.Functional.Tests
{
await LoopbackServer.CreateServerAsync(async (server, url) =>
{
- using (var handler = new HttpClientHandler() { MaxResponseHeadersLength = maxResponseHeadersLength })
+ using (HttpClientHandler handler = CreateHttpClientHandler())
using (var client = new HttpClient(handler))
{
+ handler.MaxResponseHeadersLength = maxResponseHeadersLength;
Task<HttpResponseMessage> getAsync = client.GetAsync(url, HttpCompletionOption.ResponseHeadersRead);
await LoopbackServer.AcceptSocketAsync(server, async (s, serverStream, reader, writer) =>
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 bb9d8e4901..132c930e66 100644
--- a/src/System.Net.Http/tests/FunctionalTests/HttpClientHandlerTest.ServerCertificates.Unix.cs
+++ b/src/System.Net.Http/tests/FunctionalTests/HttpClientHandlerTest.ServerCertificates.Unix.cs
@@ -14,17 +14,12 @@ using Xunit;
namespace System.Net.Http.Functional.Tests
{
- public partial class HttpClientHandler_ServerCertificates_Test : RemoteExecutorTestBase
+ public partial class HttpClientHandler_ServerCertificates_Test
{
private static bool ShouldSuppressRevocationException
{
get
{
- if (ManagedHandlerTestHelpers.IsEnabled)
- {
- return false;
- }
-
if (!RuntimeInformation.IsOSPlatform(OSPlatform.OSX))
{
return false;
@@ -53,11 +48,11 @@ namespace System.Net.Http.Functional.Tests
}
}
- internal static bool BackendSupportsCustomCertificateHandling
+ internal bool BackendSupportsCustomCertificateHandling
{
get
{
- if (ManagedHandlerTestHelpers.IsEnabled)
+ if (UseManagedHandler)
{
return true;
}
@@ -73,8 +68,6 @@ namespace System.Net.Http.Functional.Tests
}
}
- private static bool BackendDoesNotSupportCustomCertificateHandling => !BackendSupportsCustomCertificateHandling;
-
[DllImport("System.Net.Http.Native", EntryPoint = "HttpNative_GetSslVersionDescription")]
private static extern string CurlSslVersionDescription();
}
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 b44163a41e..c213aab296 100644
--- a/src/System.Net.Http/tests/FunctionalTests/HttpClientHandlerTest.ServerCertificates.Windows.cs
+++ b/src/System.Net.Http/tests/FunctionalTests/HttpClientHandlerTest.ServerCertificates.Windows.cs
@@ -2,24 +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.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;
-using Xunit;
-
namespace System.Net.Http.Functional.Tests
{
- public partial class HttpClientHandler_ServerCertificates_Test : RemoteExecutorTestBase
+ public partial class HttpClientHandler_ServerCertificates_Test
{
private static bool ShouldSuppressRevocationException => false;
- internal static bool BackendSupportsCustomCertificateHandling => true;
+ internal bool BackendSupportsCustomCertificateHandling => true;
- private static bool BackendDoesNotSupportCustomCertificateHandling => !BackendSupportsCustomCertificateHandling;
+ private bool BackendDoesNotSupportCustomCertificateHandling => !BackendSupportsCustomCertificateHandling;
}
}
diff --git a/src/System.Net.Http/tests/FunctionalTests/HttpClientHandlerTest.ServerCertificates.cs b/src/System.Net.Http/tests/FunctionalTests/HttpClientHandlerTest.ServerCertificates.cs
index e4b5bb5909..43fef62f82 100644
--- a/src/System.Net.Http/tests/FunctionalTests/HttpClientHandlerTest.ServerCertificates.cs
+++ b/src/System.Net.Http/tests/FunctionalTests/HttpClientHandlerTest.ServerCertificates.cs
@@ -3,7 +3,6 @@
// See the LICENSE file in the project root for more information.
using System.Collections.Generic;
-using System.Diagnostics;
using System.Linq;
using System.Net.Security;
using System.Net.Test.Common;
@@ -18,18 +17,18 @@ namespace System.Net.Http.Functional.Tests
using Configuration = System.Net.Test.Common.Configuration;
[SkipOnTargetFramework(TargetFrameworkMonikers.NetFramework, ".NET Framework throws PNSE for ServerCertificateCustomValidationCallback")]
- public partial class HttpClientHandler_ServerCertificates_Test : RemoteExecutorTestBase
+ public partial class HttpClientHandler_ServerCertificates_Test : HttpClientTestBase
{
// TODO: https://github.com/dotnet/corefx/issues/7812
private static bool ClientSupportsDHECipherSuites => (!PlatformDetection.IsWindows || PlatformDetection.IsWindows10Version1607OrGreater);
- private static bool BackendSupportsCustomCertificateHandlingAndClientSupportsDHECipherSuites =>
+ private bool BackendSupportsCustomCertificateHandlingAndClientSupportsDHECipherSuites =>
(BackendSupportsCustomCertificateHandling && ClientSupportsDHECipherSuites);
[Fact]
[SkipOnTargetFramework(~TargetFrameworkMonikers.Uap)]
public void Ctor_ExpectedDefaultPropertyValues_UapPlatform()
{
- using (var handler = new HttpClientHandler())
+ using (HttpClientHandler handler = CreateHttpClientHandler())
{
Assert.Null(handler.ServerCertificateCustomValidationCallback);
Assert.True(handler.CheckCertificateRevocationList);
@@ -40,7 +39,7 @@ namespace System.Net.Http.Functional.Tests
[SkipOnTargetFramework(TargetFrameworkMonikers.Uap)]
public void Ctor_ExpectedDefaultValues_NotUapPlatform()
{
- using (var handler = new HttpClientHandler())
+ using (HttpClientHandler handler = CreateHttpClientHandler())
{
Assert.Null(handler.ServerCertificateCustomValidationCallback);
Assert.False(handler.CheckCertificateRevocationList);
@@ -51,7 +50,7 @@ namespace System.Net.Http.Functional.Tests
[Fact]
public async Task NoCallback_ValidCertificate_SuccessAndExpectedPropertyBehavior()
{
- var handler = new HttpClientHandler();
+ HttpClientHandler handler = CreateHttpClientHandler();
using (var client = new HttpClient(handler))
{
using (HttpResponseMessage response = await client.GetAsync(Configuration.Http.SecureRemoteEchoServer))
@@ -66,10 +65,14 @@ 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))]
+ [Fact]
public async Task UseCallback_HaveNoCredsAndUseAuthenticatedCustomProxyAndPostToSecureServer_ProxyAuthenticationRequiredStatusCode()
{
- if (ManagedHandlerTestHelpers.IsEnabled)
+ if (!BackendSupportsCustomCertificateHandling)
+ {
+ return;
+ }
+ if (UseManagedHandler)
{
return; // TODO #23136: SSL proxy tunneling not yet implemented in ManagedHandler
}
@@ -81,7 +84,7 @@ namespace System.Net.Http.Functional.Tests
expectCreds: false);
Uri proxyUrl = new Uri($"http://localhost:{port}");
- var handler = new HttpClientHandler();
+ HttpClientHandler handler = CreateHttpClientHandler();
handler.Proxy = new UseSpecifiedUriWebProxy(proxyUrl, null);
handler.ServerCertificateCustomValidationCallback = delegate { return true; };
using (var client = new HttpClient(handler))
@@ -101,13 +104,13 @@ namespace System.Net.Http.Functional.Tests
[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
+ if (!BackendSupportsCustomCertificateHandling)
{
Console.WriteLine($"Skipping {nameof(UseCallback_NotSecureConnection_CallbackNotCalled)}()");
return;
}
- var handler = new HttpClientHandler();
+ HttpClientHandler handler = CreateHttpClientHandler();
using (var client = new HttpClient(handler))
{
bool callbackCalled = false;
@@ -142,13 +145,13 @@ namespace System.Net.Http.Functional.Tests
[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
+ if (!BackendSupportsCustomCertificateHandling)
{
Console.WriteLine($"Skipping {nameof(UseCallback_ValidCertificate_ExpectedValuesDuringCallback)}({url}, {checkRevocation})");
return;
}
- var handler = new HttpClientHandler();
+ HttpClientHandler handler = CreateHttpClientHandler();
using (var client = new HttpClient(handler))
{
bool callbackCalled = false;
@@ -190,13 +193,13 @@ namespace System.Net.Http.Functional.Tests
[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
+ if (!BackendSupportsCustomCertificateHandling)
{
Console.WriteLine($"Skipping {nameof(UseCallback_CallbackReturnsFailure_ThrowsException)}()");
return;
}
- var handler = new HttpClientHandler();
+ HttpClientHandler handler = CreateHttpClientHandler();
using (var client = new HttpClient(handler))
{
handler.ServerCertificateCustomValidationCallback = delegate { return false; };
@@ -204,25 +207,24 @@ namespace System.Net.Http.Functional.Tests
}
}
- [ActiveIssue(21904, ~TargetFrameworkMonikers.Uap)]
[OuterLoop] // TODO: Issue #11345
- [ConditionalFact(nameof(BackendSupportsCustomCertificateHandling))]
- public async Task UseCallback_CallbackThrowsException_ExceptionPropagatesAsInnerException()
+ [Fact]
+ public async Task UseCallback_CallbackThrowsException_ExceptionPropagatesAsBaseException()
{
- if (BackendDoesNotSupportCustomCertificateHandling) // can't use [Conditional*] right now as it's evaluated at the wrong time for the managed handler
+ if (!BackendSupportsCustomCertificateHandling)
{
- Console.WriteLine($"Skipping {nameof(UseCallback_CallbackThrowsException_ExceptionPropagatesAsInnerException)}()");
+ Console.WriteLine($"Skipping {nameof(UseCallback_CallbackThrowsException_ExceptionPropagatesAsBaseException)}()");
return;
}
- var handler = new HttpClientHandler();
+ HttpClientHandler handler = CreateHttpClientHandler();
using (var client = new HttpClient(handler))
{
var e = new DivideByZeroException();
handler.ServerCertificateCustomValidationCallback = delegate { throw e; };
HttpRequestException ex = await Assert.ThrowsAsync<HttpRequestException>(() => client.GetAsync(Configuration.Http.SecureRemoteEchoServer));
- Assert.Same(e, ex.InnerException);
+ Assert.Same(e, ex.GetBaseException());
}
}
@@ -238,7 +240,7 @@ namespace System.Net.Http.Functional.Tests
[MemberData(nameof(CertificateValidationServers))]
public async Task NoCallback_BadCertificate_ThrowsException(string url)
{
- using (var client = new HttpClient())
+ using (HttpClient client = CreateHttpClient())
{
await Assert.ThrowsAsync<HttpRequestException>(() => client.GetAsync(url));
}
@@ -254,7 +256,7 @@ namespace System.Net.Http.Functional.Tests
// CheckCertificateRevocationList throws in the general case.
try
{
- using (var client = new HttpClient())
+ using (HttpClient client = CreateHttpClient())
using (HttpResponseMessage response = await client.GetAsync(Configuration.Http.RevokedCertRemoteServer))
{
Assert.Equal(HttpStatusCode.OK, response.StatusCode);
@@ -262,7 +264,7 @@ namespace System.Net.Http.Functional.Tests
}
catch (HttpRequestException)
{
- if (!ShouldSuppressRevocationException)
+ if (UseManagedHandler || !ShouldSuppressRevocationException)
throw;
}
}
@@ -271,13 +273,14 @@ namespace System.Net.Http.Functional.Tests
[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
+ if (!BackendSupportsCustomCertificateHandling)
{
Console.WriteLine($"Skipping {nameof(NoCallback_RevokedCertificate_RevocationChecking_Fails)}()");
return;
}
- var handler = new HttpClientHandler() { CheckCertificateRevocationList = true };
+ HttpClientHandler handler = CreateHttpClientHandler();
+ handler.CheckCertificateRevocationList = true;
using (var client = new HttpClient(handler))
{
await Assert.ThrowsAsync<HttpRequestException>(() => client.GetAsync(Configuration.Http.RevokedCertRemoteServer));
@@ -291,15 +294,15 @@ namespace System.Net.Http.Functional.Tests
new object[] { Configuration.Http.WrongHostNameCertRemoteServer , SslPolicyErrors.RemoteCertificateNameMismatch},
};
- public async Task UseCallback_BadCertificate_ExpectedPolicyErrors_Helper(string url, SslPolicyErrors expectedErrors)
+ private async Task UseCallback_BadCertificate_ExpectedPolicyErrors_Helper(string url, bool useManagedHandler, SslPolicyErrors expectedErrors)
{
- if (BackendDoesNotSupportCustomCertificateHandling) // can't use [Conditional*] right now as it's evaluated at the wrong time for the managed handler
+ if (!BackendSupportsCustomCertificateHandling)
{
Console.WriteLine($"Skipping {nameof(UseCallback_BadCertificate_ExpectedPolicyErrors)}({url}, {expectedErrors})");
return;
}
- var handler = new HttpClientHandler();
+ HttpClientHandler handler = CreateHttpClientHandler(useManagedHandler);
using (var client = new HttpClient(handler))
{
bool callbackCalled = false;
@@ -310,7 +313,7 @@ namespace System.Net.Http.Functional.Tests
Assert.NotNull(request);
Assert.NotNull(cert);
Assert.NotNull(chain);
- if (!ManagedHandlerTestHelpers.IsEnabled)
+ if (!useManagedHandler)
{
// TODO #23137: This test is failing with the managed handler on the exact value of the managed errors,
// e.g. reporting "RemoteCertificateNameMismatch, RemoteCertificateChainErrors" when we only expect
@@ -330,27 +333,33 @@ namespace System.Net.Http.Functional.Tests
}
[OuterLoop] // TODO: Issue #11345
- [ConditionalTheory(nameof(BackendSupportsCustomCertificateHandlingAndClientSupportsDHECipherSuites))]
+ [Theory]
[MemberData(nameof(CertificateValidationServersAndExpectedPolicies))]
public async Task UseCallback_BadCertificate_ExpectedPolicyErrors(string url, SslPolicyErrors expectedErrors)
{
+ if (!BackendSupportsCustomCertificateHandlingAndClientSupportsDHECipherSuites)
+ {
+ return;
+ }
+
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) =>
+ RemoteInvoke((remoteUrl, remoteExpectedErrors, useManagedHandlerString) =>
{
UseCallback_BadCertificate_ExpectedPolicyErrors_Helper(
remoteUrl,
+ bool.Parse(useManagedHandlerString),
(SslPolicyErrors)Enum.Parse(typeof(SslPolicyErrors), remoteExpectedErrors)).Wait();
return SuccessExitCode;
- }, url, expectedErrors.ToString()).Dispose();
+ }, url, expectedErrors.ToString(), UseManagedHandler.ToString()).Dispose();
}
else
{
- await UseCallback_BadCertificate_ExpectedPolicyErrors_Helper(url, expectedErrors);
+ await UseCallback_BadCertificate_ExpectedPolicyErrors_Helper(url, UseManagedHandler, expectedErrors);
}
}
@@ -358,12 +367,14 @@ namespace System.Net.Http.Functional.Tests
[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
+ if (BackendSupportsCustomCertificateHandling)
{
return;
}
- using (var client = new HttpClient(new HttpClientHandler() { ServerCertificateCustomValidationCallback = delegate { return true; } }))
+ HttpClientHandler handler = CreateHttpClientHandler();
+ handler.ServerCertificateCustomValidationCallback = delegate { return true; };
+ using (var client = new HttpClient(handler))
{
await Assert.ThrowsAsync<PlatformNotSupportedException>(() => client.GetAsync(Configuration.Http.SecureRemoteEchoServer));
}
@@ -375,12 +386,14 @@ namespace System.Net.Http.Functional.Tests
[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
+ if (BackendSupportsCustomCertificateHandling)
{
return;
}
- using (var client = new HttpClient(new HttpClientHandler() { CheckCertificateRevocationList = true }))
+ HttpClientHandler handler = CreateHttpClientHandler();
+ handler.CheckCertificateRevocationList = true;
+ using (var client = new HttpClient(handler))
{
await Assert.ThrowsAsync<PlatformNotSupportedException>(() => client.GetAsync(Configuration.Http.SecureRemoteEchoServer));
}
@@ -392,7 +405,7 @@ namespace System.Net.Http.Functional.Tests
public async Task PostAsync_Post_ChannelBinding_ConfiguredCorrectly()
{
var content = new ChannelBindingAwareContent("Test contest");
- using (var client = new HttpClient())
+ using (HttpClient client = CreateHttpClient())
using (HttpResponseMessage response = await client.PostAsync(Configuration.Http.SecureRemoteEchoServer, content))
{
// Validate status.
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 83b32ec77f..56377d5e69 100644
--- a/src/System.Net.Http/tests/FunctionalTests/HttpClientHandlerTest.SslProtocols.Unix.cs
+++ b/src/System.Net.Http/tests/FunctionalTests/HttpClientHandlerTest.SslProtocols.Unix.cs
@@ -16,11 +16,11 @@ namespace System.Net.Http.Functional.Tests
{
public partial class HttpClientHandler_SslProtocols_Test
{
- private static bool BackendSupportsSslConfiguration =>
- ManagedHandlerTestHelpers.IsEnabled ||
+ private bool BackendSupportsSslConfiguration =>
+ UseManagedHandler ||
(CurlSslVersionDescription()?.StartsWith("OpenSSL") ?? false);
- private static bool SSLv3DisabledByDefault =>
+ private bool SSLv3DisabledByDefault =>
BackendSupportsSslConfiguration ||
Version.Parse(CurlVersionDescription()) >= new Version(7, 39); // libcurl disables SSLv3 by default starting in v7.39
diff --git a/src/System.Net.Http/tests/FunctionalTests/HttpClientHandlerTest.SslProtocols.Windows.cs b/src/System.Net.Http/tests/FunctionalTests/HttpClientHandlerTest.SslProtocols.Windows.cs
index 8f390f1288..28b5e9c8ce 100644
--- a/src/System.Net.Http/tests/FunctionalTests/HttpClientHandlerTest.SslProtocols.Windows.cs
+++ b/src/System.Net.Http/tests/FunctionalTests/HttpClientHandlerTest.SslProtocols.Windows.cs
@@ -2,20 +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.IO;
-using System.Net.Security;
-using System.Net.Sockets;
-using System.Net.Test.Common;
-using System.Runtime.InteropServices;
-using System.Security.Authentication;
-using System.Threading;
-using System.Threading.Tasks;
-using Xunit;
namespace System.Net.Http.Functional.Tests
{
- using Configuration = System.Net.Test.Common.Configuration;
-
public partial class HttpClientHandler_SslProtocols_Test
{
private static bool BackendSupportsSslConfiguration => true;
diff --git a/src/System.Net.Http/tests/FunctionalTests/HttpClientHandlerTest.SslProtocols.cs b/src/System.Net.Http/tests/FunctionalTests/HttpClientHandlerTest.SslProtocols.cs
index d6a166c4ce..d7cb6c3a0f 100644
--- a/src/System.Net.Http/tests/FunctionalTests/HttpClientHandlerTest.SslProtocols.cs
+++ b/src/System.Net.Http/tests/FunctionalTests/HttpClientHandlerTest.SslProtocols.cs
@@ -4,11 +4,8 @@
using System.IO;
using System.Net.Security;
-using System.Net.Sockets;
using System.Net.Test.Common;
-using System.Runtime.InteropServices;
using System.Security.Authentication;
-using System.Threading;
using System.Threading.Tasks;
using Xunit;
@@ -18,12 +15,12 @@ namespace System.Net.Http.Functional.Tests
[SkipOnTargetFramework(TargetFrameworkMonikers.Uap, "SslProtocols not supported on UAP")]
[SkipOnTargetFramework(TargetFrameworkMonikers.NetFramework, "dotnet/corefx #16805")]
- public partial class HttpClientHandler_SslProtocols_Test
+ public partial class HttpClientHandler_SslProtocols_Test : HttpClientTestBase
{
[Fact]
public void DefaultProtocols_MatchesExpected()
{
- using (var handler = new HttpClientHandler())
+ using (HttpClientHandler handler = CreateHttpClientHandler())
{
Assert.Equal(SslProtocols.None, handler.SslProtocols);
}
@@ -40,7 +37,7 @@ namespace System.Net.Http.Functional.Tests
[InlineData(SslProtocols.Tls | SslProtocols.Tls11 | SslProtocols.Tls12)]
public void SetGetProtocols_Roundtrips(SslProtocols protocols)
{
- using (var handler = new HttpClientHandler())
+ using (HttpClientHandler handler = CreateHttpClientHandler())
{
handler.SslProtocols = protocols;
Assert.Equal(protocols, handler.SslProtocols);
@@ -48,12 +45,18 @@ namespace System.Net.Http.Functional.Tests
}
[OuterLoop] // TODO: Issue #11345
- [ConditionalFact(nameof(BackendSupportsSslConfiguration))]
+ [Fact]
public async Task SetProtocols_AfterRequest_ThrowsException()
{
- using (var handler = new HttpClientHandler() { ServerCertificateCustomValidationCallback = LoopbackServer.AllowAllCertificates })
+ if (!BackendSupportsSslConfiguration)
+ {
+ return;
+ }
+
+ using (HttpClientHandler handler = CreateHttpClientHandler())
using (var client = new HttpClient(handler))
{
+ handler.ServerCertificateCustomValidationCallback = LoopbackServer.AllowAllCertificates;
await LoopbackServer.CreateServerAsync(async (server, url) =>
{
await TestHelper.WhenAllCompletedOrAnyFailed(
@@ -75,14 +78,14 @@ namespace System.Net.Http.Functional.Tests
#pragma warning restore 0618
public void DisabledProtocols_SetSslProtocols_ThrowsException(SslProtocols disabledProtocols)
{
- using (var handler = new HttpClientHandler())
+ using (HttpClientHandler handler = CreateHttpClientHandler())
{
Assert.Throws<NotSupportedException>(() => handler.SslProtocols = disabledProtocols);
}
}
[OuterLoop] // TODO: Issue #11345
- [ConditionalTheory(nameof(BackendSupportsSslConfiguration))]
+ [Theory]
[InlineData(SslProtocols.Tls, false)]
[InlineData(SslProtocols.Tls, true)]
[InlineData(SslProtocols.Tls11, false)]
@@ -91,15 +94,21 @@ namespace System.Net.Http.Functional.Tests
[InlineData(SslProtocols.Tls12, true)]
public async Task GetAsync_AllowedSSLVersion_Succeeds(SslProtocols acceptedProtocol, bool requestOnlyThisProtocol)
{
- if (ManagedHandlerTestHelpers.IsEnabled)
+ if (!BackendSupportsSslConfiguration)
+ {
+ return;
+ }
+ if (UseManagedHandler)
{
// TODO #23138: The managed handler is failing.
return;
}
- using (var handler = new HttpClientHandler() { ServerCertificateCustomValidationCallback = LoopbackServer.AllowAllCertificates })
+ using (HttpClientHandler handler = CreateHttpClientHandler())
using (var client = new HttpClient(handler))
{
+ handler.ServerCertificateCustomValidationCallback = LoopbackServer.AllowAllCertificates;
+
if (requestOnlyThisProtocol)
{
handler.SslProtocols = acceptedProtocol;
@@ -130,13 +139,13 @@ namespace System.Net.Http.Functional.Tests
[MemberData(nameof(SupportedSSLVersionServers))]
public async Task GetAsync_SupportedSSLVersion_Succeeds(SslProtocols sslProtocols, string url)
{
- if (ManagedHandlerTestHelpers.IsEnabled)
+ if (UseManagedHandler)
{
// TODO #23138: The managed handler is failing.
return;
}
- using (HttpClientHandler handler = new HttpClientHandler())
+ using (HttpClientHandler handler = CreateHttpClientHandler())
{
if (PlatformDetection.IsCentos7)
{
@@ -162,30 +171,38 @@ namespace System.Net.Http.Functional.Tests
// when trying to use such an SslStream, we can't stand up a localhost server that
// only speaks those protocols.
[OuterLoop("Avoid www.ssllabs.com dependency in innerloop.")]
- [ConditionalTheory(nameof(SSLv3DisabledByDefault))]
+ [Theory]
[MemberData(nameof(NotSupportedSSLVersionServers))]
public async Task GetAsync_UnsupportedSSLVersion_Throws(string name, string url)
{
- if (ManagedHandlerTestHelpers.IsEnabled && !PlatformDetection.IsWindows10Version1607OrGreater)
+ if (!SSLv3DisabledByDefault)
+ {
+ return;
+ }
+
+ if (UseManagedHandler && !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())
+ using (HttpClient client = CreateHttpClient())
{
await Assert.ThrowsAsync<HttpRequestException>(() => client.GetAsync(url));
}
}
[OuterLoop] // TODO: Issue #11345
- [ConditionalFact(nameof(BackendSupportsSslConfiguration), nameof(SslDefaultsToTls12))]
+ [ConditionalFact(nameof(SslDefaultsToTls12))]
public async Task GetAsync_NoSpecifiedProtocol_DefaultsToTls12()
{
- using (var handler = new HttpClientHandler() { ServerCertificateCustomValidationCallback = LoopbackServer.AllowAllCertificates })
+ if (!BackendSupportsSslConfiguration) return;
+ using (HttpClientHandler handler = CreateHttpClientHandler())
using (var client = new HttpClient(handler))
{
+ handler.ServerCertificateCustomValidationCallback = LoopbackServer.AllowAllCertificates;
+
var options = new LoopbackServer.Options { UseSsl = true };
await LoopbackServer.CreateServerAsync(async (server, url) =>
{
@@ -202,16 +219,20 @@ namespace System.Net.Http.Functional.Tests
}
[OuterLoop] // TODO: Issue #11345
- [ConditionalTheory(nameof(BackendSupportsSslConfiguration))]
+ [Theory]
[InlineData(SslProtocols.Tls11, SslProtocols.Tls, typeof(IOException))]
[InlineData(SslProtocols.Tls12, SslProtocols.Tls11, typeof(IOException))]
[InlineData(SslProtocols.Tls, SslProtocols.Tls12, typeof(AuthenticationException))]
public async Task GetAsync_AllowedSSLVersionDiffersFromServer_ThrowsException(
SslProtocols allowedProtocol, SslProtocols acceptedProtocol, Type exceptedServerException)
{
- using (var handler = new HttpClientHandler() { SslProtocols = allowedProtocol, ServerCertificateCustomValidationCallback = LoopbackServer.AllowAllCertificates })
+ if (!BackendSupportsSslConfiguration) return;
+ using (HttpClientHandler handler = CreateHttpClientHandler())
using (var client = new HttpClient(handler))
{
+ handler.SslProtocols = allowedProtocol;
+ handler.ServerCertificateCustomValidationCallback = LoopbackServer.AllowAllCertificates;
+
var options = new LoopbackServer.Options { UseSsl = true, SslProtocols = acceptedProtocol };
await LoopbackServer.CreateServerAsync(async (server, url) =>
{
@@ -227,9 +248,12 @@ namespace System.Net.Http.Functional.Tests
[Fact]
public async Task GetAsync_DisallowTls10_AllowTls11_AllowTls12()
{
- using (var handler = new HttpClientHandler() { SslProtocols = SslProtocols.Tls11 | SslProtocols.Tls12, ServerCertificateCustomValidationCallback = LoopbackServer.AllowAllCertificates })
+ using (HttpClientHandler handler = CreateHttpClientHandler())
using (var client = new HttpClient(handler))
{
+ handler.SslProtocols = SslProtocols.Tls11 | SslProtocols.Tls12;
+ handler.ServerCertificateCustomValidationCallback = LoopbackServer.AllowAllCertificates;
+
if (BackendSupportsSslConfiguration)
{
LoopbackServer.Options options = new LoopbackServer.Options { UseSsl = true };
diff --git a/src/System.Net.Http/tests/FunctionalTests/HttpClientHandlerTest.cs b/src/System.Net.Http/tests/FunctionalTests/HttpClientHandlerTest.cs
index 2b0c8b6bcb..1d9b2e4dc0 100644
--- a/src/System.Net.Http/tests/FunctionalTests/HttpClientHandlerTest.cs
+++ b/src/System.Net.Http/tests/FunctionalTests/HttpClientHandlerTest.cs
@@ -7,11 +7,9 @@ using System.Diagnostics;
using System.IO;
using System.Linq;
using System.Net.Sockets;
-using System.Net.Security;
using System.Net.Test.Common;
using System.Runtime.InteropServices;
using System.Security.Authentication;
-using System.Security.Authentication.ExtendedProtection;
using System.Security.Cryptography.X509Certificates;
using System.Text;
using System.Threading;
@@ -26,7 +24,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 : RemoteExecutorTestBase
+ public class HttpClientHandlerTest : HttpClientTestBase
{
readonly ITestOutputHelper _output;
private const string ExpectedContent = "Test contest";
@@ -126,7 +124,7 @@ namespace System.Net.Http.Functional.Tests
[Fact]
public void Ctor_ExpectedDefaultPropertyValues_CommonPlatform()
{
- using (var handler = new HttpClientHandler())
+ using (HttpClientHandler handler = CreateHttpClientHandler())
{
// Same as .NET Framework (Desktop).
Assert.Equal(DecompressionMethods.None, handler.AutomaticDecompression);
@@ -150,7 +148,7 @@ namespace System.Net.Http.Functional.Tests
[Fact]
public void Ctor_ExpectedDefaultPropertyValues_NotUapPlatform()
{
- using (var handler = new HttpClientHandler())
+ using (HttpClientHandler handler = CreateHttpClientHandler())
{
// Same as .NET Framework (Desktop).
Assert.Equal(64, handler.MaxResponseHeadersLength);
@@ -171,7 +169,7 @@ namespace System.Net.Http.Functional.Tests
[ConditionalFact(typeof(PlatformDetection), nameof(PlatformDetection.IsUap))]
public void Ctor_ExpectedDefaultPropertyValues_UapPlatform()
{
- using (var handler = new HttpClientHandler())
+ using (HttpClientHandler handler = CreateHttpClientHandler())
{
Assert.True(handler.CheckCertificateRevocationList);
Assert.Equal(0, handler.MaxRequestContentBufferSize);
@@ -186,7 +184,7 @@ namespace System.Net.Http.Functional.Tests
[Fact]
public void Credentials_SetGet_Roundtrips()
{
- using (var handler = new HttpClientHandler())
+ using (HttpClientHandler handler = CreateHttpClientHandler())
{
var creds = new NetworkCredential("username", "password", "domain");
@@ -206,7 +204,7 @@ namespace System.Net.Http.Functional.Tests
[InlineData(0)]
public void MaxAutomaticRedirections_InvalidValue_Throws(int redirects)
{
- using (var handler = new HttpClientHandler())
+ using (HttpClientHandler handler = CreateHttpClientHandler())
{
Assert.Throws<ArgumentOutOfRangeException>(() => handler.MaxAutomaticRedirections = redirects);
}
@@ -217,7 +215,7 @@ namespace System.Net.Http.Functional.Tests
[InlineData((long)int.MaxValue + (long)1)]
public void MaxRequestContentBufferSize_SetInvalidValue_ThrowsArgumentOutOfRangeException(long value)
{
- using (var handler = new HttpClientHandler())
+ using (HttpClientHandler handler = CreateHttpClientHandler())
{
Assert.Throws<ArgumentOutOfRangeException>(() => handler.MaxRequestContentBufferSize = value);
}
@@ -229,7 +227,7 @@ namespace System.Net.Http.Functional.Tests
[InlineData(true)]
public async Task UseDefaultCredentials_SetToFalseAndServerNeedsAuth_StatusCodeUnauthorized(bool useProxy)
{
- var handler = new HttpClientHandler();
+ HttpClientHandler handler = CreateHttpClientHandler();
handler.UseProxy = useProxy;
handler.UseDefaultCredentials = false;
using (var client = new HttpClient(handler))
@@ -246,7 +244,7 @@ namespace System.Net.Http.Functional.Tests
[Fact]
public void Properties_Get_CountIsZero()
{
- using (var handler = new HttpClientHandler())
+ using (HttpClientHandler handler = CreateHttpClientHandler())
{
IDictionary<String, object> dict = handler.Properties;
Assert.Same(dict, handler.Properties);
@@ -257,7 +255,7 @@ namespace System.Net.Http.Functional.Tests
[Fact]
public void Properties_AddItemToDictionary_ItemPresent()
{
- using (var handler = new HttpClientHandler())
+ using (HttpClientHandler handler = CreateHttpClientHandler())
{
IDictionary<String, object> dict = handler.Properties;
@@ -274,7 +272,7 @@ namespace System.Net.Http.Functional.Tests
[Theory, MemberData(nameof(EchoServers))]
public async Task SendAsync_SimpleGet_Success(Uri remoteServer)
{
- using (var client = new HttpClient())
+ using (HttpClient client = CreateHttpClient())
using (HttpResponseMessage response = await client.GetAsync(remoteServer))
{
string responseContent = await response.Content.ReadAsStringAsync();
@@ -292,7 +290,7 @@ namespace System.Net.Http.Functional.Tests
[Fact]
public async Task GetAsync_IPv6LinkLocalAddressUri_Success()
{
- using (var client = new HttpClient())
+ using (HttpClient client = CreateHttpClient())
{
var options = new LoopbackServer.Options { Address = LoopbackServer.GetIPv6LinkLocalAddress() };
await LoopbackServer.CreateServerAsync(async (server, url) =>
@@ -310,7 +308,7 @@ namespace System.Net.Http.Functional.Tests
[MemberData(nameof(GetAsync_IPBasedUri_Success_MemberData))]
public async Task GetAsync_IPBasedUri_Success(IPAddress address)
{
- using (var client = new HttpClient())
+ using (HttpClient client = CreateHttpClient())
{
var options = new LoopbackServer.Options { Address = address };
await LoopbackServer.CreateServerAsync(async (server, url) =>
@@ -338,7 +336,7 @@ namespace System.Net.Http.Functional.Tests
[Fact]
public async Task SendAsync_MultipleRequestsReusingSameClient_Success()
{
- using (var client = new HttpClient())
+ using (HttpClient client = CreateHttpClient())
{
for (int i = 0; i < 3; i++)
{
@@ -354,7 +352,7 @@ namespace System.Net.Http.Functional.Tests
[Fact]
public async Task GetAsync_ResponseContentAfterClientAndHandlerDispose_Success()
{
- using (var client = new HttpClient())
+ using (HttpClient client = CreateHttpClient())
using (HttpResponseMessage response = await client.GetAsync(Configuration.Http.SecureRemoteEchoServer))
{
client.Dispose();
@@ -371,7 +369,7 @@ namespace System.Net.Http.Functional.Tests
{
var cts = new CancellationTokenSource();
cts.Cancel();
- using (var client = new HttpClient())
+ using (HttpClient client = CreateHttpClient())
{
var request = new HttpRequestMessage(HttpMethod.Post, Configuration.Http.RemoteEchoServer);
OperationCanceledException ex = await Assert.ThrowsAnyAsync<OperationCanceledException>(() =>
@@ -389,7 +387,7 @@ namespace System.Net.Http.Functional.Tests
[Theory, MemberData(nameof(CompressedServers))]
public async Task GetAsync_SetAutomaticDecompression_ContentDecompressed(Uri server)
{
- var handler = new HttpClientHandler();
+ HttpClientHandler handler = CreateHttpClientHandler();
handler.AutomaticDecompression = DecompressionMethods.GZip | DecompressionMethods.Deflate;
using (var client = new HttpClient(handler))
{
@@ -411,7 +409,7 @@ namespace System.Net.Http.Functional.Tests
[Theory, MemberData(nameof(CompressedServers))]
public async Task GetAsync_SetAutomaticDecompression_HeadersRemoved(Uri server)
{
- var handler = new HttpClientHandler();
+ HttpClientHandler handler = CreateHttpClientHandler();
handler.AutomaticDecompression = DecompressionMethods.GZip | DecompressionMethods.Deflate;
using (var client = new HttpClient(handler))
using (HttpResponseMessage response = await client.GetAsync(server, HttpCompletionOption.ResponseHeadersRead))
@@ -427,7 +425,7 @@ namespace System.Net.Http.Functional.Tests
[Fact]
public async Task GetAsync_ServerNeedsBasicAuthAndSetDefaultCredentials_StatusCodeUnauthorized()
{
- var handler = new HttpClientHandler();
+ HttpClientHandler handler = CreateHttpClientHandler();
handler.Credentials = CredentialCache.DefaultCredentials;
using (var client = new HttpClient(handler))
{
@@ -443,7 +441,7 @@ namespace System.Net.Http.Functional.Tests
[Fact]
public async Task GetAsync_ServerNeedsAuthAndSetCredential_StatusCodeOK()
{
- var handler = new HttpClientHandler();
+ HttpClientHandler handler = CreateHttpClientHandler();
handler.Credentials = _credential;
using (var client = new HttpClient(handler))
{
@@ -462,9 +460,9 @@ namespace System.Net.Http.Functional.Tests
// 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 () =>
+ RemoteInvoke(async useManagedHandlerString =>
{
- using (var client = new HttpClient())
+ using (var client = CreateHttpClient(useManagedHandlerString))
{
Uri uri = Configuration.Http.BasicAuthUriForCreds(secure: false, userName: Username, password: Password);
using (HttpResponseMessage response = await client.GetAsync(uri))
@@ -474,7 +472,7 @@ namespace System.Net.Http.Functional.Tests
return SuccessExitCode;
}
- }).Dispose();
+ }, UseManagedHandler.ToString()).Dispose();
}
[OuterLoop] // TODO: Issue #11345
@@ -488,7 +486,7 @@ namespace System.Net.Http.Functional.Tests
_output.WriteLine(responseHeaders);
await LoopbackServer.CreateServerAsync(async (server, url) =>
{
- var handler = new HttpClientHandler();
+ HttpClientHandler handler = CreateHttpClientHandler();
handler.Credentials = new NetworkCredential("unused", "unused");
using (var client = new HttpClient(handler))
{
@@ -508,7 +506,7 @@ namespace System.Net.Http.Functional.Tests
[Theory, MemberData(nameof(RedirectStatusCodes))]
public async Task GetAsync_AllowAutoRedirectFalse_RedirectFromHttpToHttp_StatusCodeRedirect(int statusCode)
{
- var handler = new HttpClientHandler();
+ HttpClientHandler handler = CreateHttpClientHandler();
handler.AllowAutoRedirect = false;
using (var client = new HttpClient(handler))
{
@@ -526,13 +524,14 @@ namespace System.Net.Http.Functional.Tests
}
}
+ [ActiveIssue(23769)]
[ActiveIssue(22707, TestPlatforms.AnyUnix)]
[OuterLoop] // TODO: Issue #11345
[Theory, MemberData(nameof(RedirectStatusCodesOldMethodsNewMethods))]
public async Task AllowAutoRedirect_True_ValidateNewMethodUsedOnRedirection(
int statusCode, string oldMethod, string newMethod)
{
- var handler = new HttpClientHandler() { AllowAutoRedirect = true };
+ HttpClientHandler handler = CreateHttpClientHandler();
using (var client = new HttpClient(handler))
{
await LoopbackServer.CreateServerAsync(async (origServer, origUrl) =>
@@ -572,7 +571,7 @@ namespace System.Net.Http.Functional.Tests
[Theory, MemberData(nameof(RedirectStatusCodes))]
public async Task GetAsync_AllowAutoRedirectTrue_RedirectFromHttpToHttp_StatusCodeOK(int statusCode)
{
- var handler = new HttpClientHandler();
+ HttpClientHandler handler = CreateHttpClientHandler();
handler.AllowAutoRedirect = true;
using (var client = new HttpClient(handler))
{
@@ -594,7 +593,7 @@ namespace System.Net.Http.Functional.Tests
[Fact]
public async Task GetAsync_AllowAutoRedirectTrue_RedirectFromHttpToHttps_StatusCodeOK()
{
- var handler = new HttpClientHandler();
+ HttpClientHandler handler = CreateHttpClientHandler();
handler.AllowAutoRedirect = true;
using (var client = new HttpClient(handler))
{
@@ -617,7 +616,7 @@ namespace System.Net.Http.Functional.Tests
[Fact]
public async Task GetAsync_AllowAutoRedirectTrue_RedirectFromHttpsToHttp_StatusCodeRedirect()
{
- var handler = new HttpClientHandler();
+ HttpClientHandler handler = CreateHttpClientHandler();
handler.AllowAutoRedirect = true;
using (var client = new HttpClient(handler))
{
@@ -640,7 +639,7 @@ namespace System.Net.Http.Functional.Tests
[Fact]
public async Task GetAsync_AllowAutoRedirectTrue_RedirectToUriWithParams_RequestMsgUriSet()
{
- var handler = new HttpClientHandler();
+ HttpClientHandler handler = CreateHttpClientHandler();
handler.AllowAutoRedirect = true;
Uri targetUri = Configuration.Http.BasicAuthUriForCreds(secure: false, userName: Username, password: Password);
using (var client = new HttpClient(handler))
@@ -681,7 +680,9 @@ namespace System.Net.Http.Functional.Tests
return;
}
- using (var client = new HttpClient(new HttpClientHandler() { MaxAutomaticRedirections = maxHops }))
+ HttpClientHandler handler = CreateHttpClientHandler();
+ handler.MaxAutomaticRedirections = maxHops;
+ using (var client = new HttpClient(handler))
{
Task<HttpResponseMessage> t = client.GetAsync(Configuration.Http.RedirectUriForDestinationUri(
secure: false,
@@ -708,7 +709,9 @@ namespace System.Net.Http.Functional.Tests
[Fact]
public async Task GetAsync_AllowAutoRedirectTrue_RedirectWithRelativeLocation()
{
- using (var client = new HttpClient(new HttpClientHandler() { AllowAutoRedirect = true }))
+ HttpClientHandler handler = CreateHttpClientHandler();
+ handler.AllowAutoRedirect = true;
+ using (var client = new HttpClient(handler))
{
Uri uri = Configuration.Http.RedirectUriForDestinationUri(
secure: false,
@@ -733,7 +736,8 @@ namespace System.Net.Http.Functional.Tests
[InlineData(400)]
public async Task GetAsync_AllowAutoRedirectTrue_NonRedirectStatusCode_LocationHeader_NoRedirect(int statusCode)
{
- using (var handler = new HttpClientHandler() { AllowAutoRedirect = true })
+ HttpClientHandler handler = CreateHttpClientHandler();
+ handler.AllowAutoRedirect = true;
using (var client = new HttpClient(handler))
{
await LoopbackServer.CreateServerAsync(async (origServer, origUrl) =>
@@ -774,7 +778,8 @@ namespace System.Net.Http.Functional.Tests
public async Task GetAsync_AllowAutoRedirectTrue_RetainsOriginalFragmentIfAppropriate(
string origFragment, string redirFragment, string expectedFragment, bool useRelativeRedirect)
{
- using (var handler = new HttpClientHandler() { AllowAutoRedirect = true })
+ HttpClientHandler handler = CreateHttpClientHandler();
+ handler.AllowAutoRedirect = true;
using (var client = new HttpClient(handler))
{
await LoopbackServer.CreateServerAsync(async (origServer, origUrl) =>
@@ -808,17 +813,10 @@ namespace System.Net.Http.Functional.Tests
}
}
- [OuterLoop] // TODO: Issue #11345
[Fact]
public async Task GetAsync_CredentialIsNetworkCredentialUriRedirect_StatusCodeUnauthorized()
{
- if (ManagedHandlerTestHelpers.IsEnabled)
- {
- // TODO #23129: The managed handler is currently getting Ok when it should be getting Unauthorized.
- return;
- }
-
- var handler = new HttpClientHandler();
+ HttpClientHandler handler = CreateHttpClientHandler();
handler.Credentials = _credential;
using (var client = new HttpClient(handler))
{
@@ -849,7 +847,7 @@ namespace System.Net.Http.Functional.Tests
var credentialCache = new CredentialCache();
credentialCache.Add(uri, "Basic", _credential);
- var handler = new HttpClientHandler();
+ HttpClientHandler handler = CreateHttpClientHandler();
if (PlatformDetection.IsUap)
{
// UAP does not support CredentialCache for Credentials.
@@ -873,7 +871,7 @@ namespace System.Net.Http.Functional.Tests
[Fact]
public async Task GetAsync_DefaultCoookieContainer_NoCookieSent()
{
- using (HttpClient client = new HttpClient())
+ using (HttpClient client = CreateHttpClient())
{
using (HttpResponseMessage httpResponse = await client.GetAsync(Configuration.Http.RemoteEchoServer))
{
@@ -889,7 +887,7 @@ namespace System.Net.Http.Functional.Tests
[InlineData("cookieName1", "cookieValue1")]
public async Task GetAsync_SetCookieContainer_CookieSent(string cookieName, string cookieValue)
{
- var handler = new HttpClientHandler();
+ HttpClientHandler handler = CreateHttpClientHandler();
var cookieContainer = new CookieContainer();
cookieContainer.Add(Configuration.Http.RemoteEchoServer, new Cookie(cookieName, cookieValue));
handler.CookieContainer = cookieContainer;
@@ -915,7 +913,7 @@ namespace System.Net.Http.Functional.Tests
statusCode: 302,
destinationUri: Configuration.Http.RemoteEchoServer,
hops: 1);
- using (HttpClient client = new HttpClient())
+ using (HttpClient client = CreateHttpClient())
{
client.DefaultRequestHeaders.Add(
"X-SetCookie",
@@ -934,7 +932,7 @@ namespace System.Net.Http.Functional.Tests
[Theory, MemberData(nameof(HeaderWithEmptyValueAndUris))]
public async Task GetAsync_RequestHeadersAddCustomHeaders_HeaderAndEmptyValueSent(string name, string value, Uri uri)
{
- using (var client = new HttpClient())
+ using (HttpClient client = CreateHttpClient())
{
_output.WriteLine($"name={name}, value={value}");
client.DefaultRequestHeaders.Add(name, value);
@@ -952,7 +950,7 @@ namespace System.Net.Http.Functional.Tests
[Theory, MemberData(nameof(HeaderValueAndUris))]
public async Task GetAsync_RequestHeadersAddCustomHeaders_HeaderAndValueSent(string name, string value, Uri uri)
{
- using (var client = new HttpClient())
+ using (HttpClient client = CreateHttpClient())
{
_output.WriteLine($"name={name}, value={value}");
client.DefaultRequestHeaders.Add(name, value);
@@ -1022,7 +1020,7 @@ namespace System.Net.Http.Functional.Tests
await LoopbackServer.CreateServerAsync(async (server, url) =>
{
- using (var handler = new HttpClientHandler())
+ using (HttpClientHandler handler = CreateHttpClientHandler())
using (var client = new HttpClient(handler))
{
Task<HttpResponseMessage> getResponseTask = client.GetAsync(url);
@@ -1057,7 +1055,7 @@ namespace System.Net.Http.Functional.Tests
[InlineData(true)]
public async Task GetAsync_TrailingHeaders_Ignored(bool includeTrailerHeader)
{
- if (ManagedHandlerTestHelpers.IsEnabled)
+ if (UseManagedHandler)
{
// TODO #23130: The managed handler isn't correctly handling trailing headers.
return;
@@ -1065,7 +1063,7 @@ namespace System.Net.Http.Functional.Tests
await LoopbackServer.CreateServerAsync(async (server, url) =>
{
- using (var handler = new HttpClientHandler())
+ using (HttpClientHandler handler = CreateHttpClientHandler())
using (var client = new HttpClient(handler))
{
Task<HttpResponseMessage> getResponseTask = client.GetAsync(url);
@@ -1103,7 +1101,7 @@ namespace System.Net.Http.Functional.Tests
{
await LoopbackServer.CreateServerAsync(async (server, url) =>
{
- using (var client = new HttpClient())
+ using (HttpClient client = CreateHttpClient())
{
string partialResponse = "HTTP/1.1 200 OK\r\n" +
"Transfer-Encoding: chunked\r\n" +
@@ -1130,7 +1128,7 @@ namespace System.Net.Http.Functional.Tests
[Fact]
public async Task GetAsync_ResponseHeadersRead_ReadFromEachIterativelyDoesntDeadlock()
{
- using (var client = new HttpClient())
+ using (HttpClient client = CreateHttpClient())
{
const int NumGets = 5;
Task<HttpResponseMessage>[] responseTasks = (from _ in Enumerable.Range(0, NumGets)
@@ -1156,7 +1154,7 @@ namespace System.Net.Http.Functional.Tests
public async Task SendAsync_HttpRequestMsgResponseHeadersRead_StatusCodeOK()
{
HttpRequestMessage request = new HttpRequestMessage(HttpMethod.Get, Configuration.Http.SecureRemoteEchoServer);
- using (var client = new HttpClient())
+ using (HttpClient client = CreateHttpClient())
{
using (HttpResponseMessage response = await client.SendAsync(request, HttpCompletionOption.ResponseHeadersRead))
{
@@ -1178,7 +1176,7 @@ namespace System.Net.Http.Functional.Tests
{
await LoopbackServer.CreateServerAsync(async (server, url) =>
{
- using (var client = new HttpClient())
+ using (HttpClient client = CreateHttpClient())
{
Task<HttpResponseMessage> getResponse = client.GetAsync(url, HttpCompletionOption.ResponseHeadersRead);
@@ -1213,7 +1211,7 @@ namespace System.Net.Http.Functional.Tests
[Fact]
public async Task Dispose_DisposingHandlerCancelsActiveOperationsWithoutResponses()
{
- if (ManagedHandlerTestHelpers.IsEnabled)
+ if (UseManagedHandler)
{
// TODO #23131: The ManagedHandler isn't correctly handling disposal of the handler.
// It should cause the outstanding requests to be canceled with OperationCanceledExceptions,
@@ -1260,7 +1258,7 @@ namespace System.Net.Http.Functional.Tests
// Make three requests
Task<HttpResponseMessage> get1, get2;
HttpResponseMessage response3;
- using (var client = new HttpClient())
+ using (HttpClient client = CreateHttpClient())
{
get1 = client.GetAsync(url1, HttpCompletionOption.ResponseHeadersRead);
get2 = client.GetAsync(url2, HttpCompletionOption.ResponseHeadersRead);
@@ -1293,7 +1291,7 @@ namespace System.Net.Http.Functional.Tests
{
await LoopbackServer.CreateServerAsync(async (server, url) =>
{
- using (var client = new HttpClient())
+ using (HttpClient client = CreateHttpClient())
{
Task<HttpResponseMessage> getResponseTask = client.GetAsync(url);
await TestHelper.WhenAllCompletedOrAnyFailed(
@@ -1324,7 +1322,7 @@ namespace System.Net.Http.Functional.Tests
await LoopbackServer.CreateServerAsync(async (server, url) =>
{
- using (var client = new HttpClient())
+ using (HttpClient client = CreateHttpClient())
{
Task<HttpResponseMessage> getResponseTask = client.GetAsync(url);
await LoopbackServer.ReadRequestAndSendResponseAsync(server,
@@ -1343,7 +1341,7 @@ namespace System.Net.Http.Functional.Tests
[Theory, MemberData(nameof(VerifyUploadServers))]
public async Task PostAsync_CallMethodTwice_StringContent(Uri remoteServer)
{
- using (var client = new HttpClient())
+ using (HttpClient client = CreateHttpClient())
{
string data = "Test String";
var content = new StringContent(data, Encoding.UTF8);
@@ -1368,7 +1366,7 @@ namespace System.Net.Http.Functional.Tests
[Theory, MemberData(nameof(VerifyUploadServers))]
public async Task PostAsync_CallMethod_UnicodeStringContent(Uri remoteServer)
{
- using (var client = new HttpClient())
+ using (HttpClient client = CreateHttpClient())
{
string data = "\ub4f1\uffc7\u4e82\u67ab4\uc6d4\ud1a0\uc694\uc77c\uffda3\u3155\uc218\uffdb";
var content = new StringContent(data, Encoding.UTF8);
@@ -1385,7 +1383,7 @@ namespace System.Net.Http.Functional.Tests
[Theory, MemberData(nameof(VerifyUploadServersStreamsAndExpectedData))]
public async Task PostAsync_CallMethod_StreamContent(Uri remoteServer, HttpContent content, byte[] expectedData)
{
- using (var client = new HttpClient())
+ using (HttpClient client = CreateHttpClient())
{
content.Headers.ContentMD5 = TestHelper.ComputeMD5Hash(expectedData);
@@ -1526,7 +1524,7 @@ namespace System.Net.Http.Functional.Tests
[Theory, MemberData(nameof(EchoServers))]
public async Task PostAsync_CallMethod_NullContent(Uri remoteServer)
{
- using (var client = new HttpClient())
+ using (HttpClient client = CreateHttpClient())
{
using (HttpResponseMessage response = await client.PostAsync(remoteServer, null))
{
@@ -1547,7 +1545,7 @@ namespace System.Net.Http.Functional.Tests
[Theory, MemberData(nameof(EchoServers))]
public async Task PostAsync_CallMethod_EmptyContent(Uri remoteServer)
{
- using (var client = new HttpClient())
+ using (HttpClient client = CreateHttpClient())
{
var content = new StringContent(string.Empty);
using (HttpResponseMessage response = await client.PostAsync(remoteServer, content))
@@ -1572,7 +1570,7 @@ namespace System.Net.Http.Functional.Tests
[InlineData(null)]
public async Task PostAsync_ExpectContinue_Success(bool? expectContinue)
{
- using (var client = new HttpClient())
+ using (HttpClient client = CreateHttpClient())
{
var req = new HttpRequestMessage(HttpMethod.Post, Configuration.Http.RemoteEchoServer)
{
@@ -1583,7 +1581,7 @@ namespace System.Net.Http.Functional.Tests
using (HttpResponseMessage response = await client.SendAsync(req))
{
Assert.Equal(HttpStatusCode.OK, response.StatusCode);
- if (ManagedHandlerTestHelpers.IsEnabled)
+ if (UseManagedHandler)
{
const string ExpectedReqHeader = "\"Expect\": \"100-continue\"";
if (expectContinue == true)
@@ -1613,7 +1611,7 @@ namespace System.Net.Http.Functional.Tests
secure ? Configuration.Http.SecureRemoteEchoServer : Configuration.Http.RemoteEchoServer,
1);
- using (var client = new HttpClient())
+ using (HttpClient client = CreateHttpClient())
using (HttpResponseMessage response = await client.PostAsync(redirectUri, content))
{
Assert.Equal(HttpStatusCode.OK, response.StatusCode);
@@ -1623,6 +1621,7 @@ namespace System.Net.Http.Functional.Tests
}
}
+ [ActiveIssue(23768)]
[ActiveIssue(22191, TargetFrameworkMonikers.Uap)]
[OuterLoop] // takes several seconds
[Fact]
@@ -1650,7 +1649,7 @@ namespace System.Net.Http.Functional.Tests
Uri redirectUri = Configuration.Http.RedirectUriForDestinationUri(false, statusCode, Configuration.Http.SecureRemoteEchoServer, 1);
- using (var client = new HttpClient())
+ using (HttpClient client = CreateHttpClient())
using (HttpResponseMessage response = await client.PostAsync(redirectUri, new StreamContent(fs)))
{
Assert.Equal(HttpStatusCode.OK, response.StatusCode);
@@ -1667,7 +1666,7 @@ namespace System.Net.Http.Functional.Tests
public async Task PostAsync_ReuseRequestContent_Success(Uri remoteServer)
{
const string ContentString = "This is the content string.";
- using (var client = new HttpClient())
+ using (HttpClient client = CreateHttpClient())
{
var content = new StringContent(ContentString);
for (int i = 0; i < 2; i++)
@@ -1687,7 +1686,7 @@ namespace System.Net.Http.Functional.Tests
[InlineData(HttpStatusCode.MethodNotAllowed, "")]
public async Task GetAsync_CallMethod_ExpectedStatusLine(HttpStatusCode statusCode, string reasonPhrase)
{
- using (var client = new HttpClient())
+ using (HttpClient client = CreateHttpClient())
{
using (HttpResponseMessage response = await client.GetAsync(Configuration.Http.StatusCodeUri(
false,
@@ -1710,7 +1709,7 @@ namespace System.Net.Http.Functional.Tests
string method,
bool secureServer)
{
- using (var client = new HttpClient())
+ using (HttpClient client = CreateHttpClient())
{
var request = new HttpRequestMessage(
new HttpMethod(method),
@@ -1745,7 +1744,7 @@ namespace System.Net.Http.Functional.Tests
return;
}
- using (var client = new HttpClient())
+ using (HttpClient client = CreateHttpClient())
{
var request = new HttpRequestMessage(
new HttpMethod(method),
@@ -1775,7 +1774,7 @@ namespace System.Net.Http.Functional.Tests
[InlineData("12345678910", 5)]
public async Task SendAsync_SendSameRequestMultipleTimesDirectlyOnHandler_Success(string stringContent, int startingPosition)
{
- using (var handler = new HttpMessageInvoker(new HttpClientHandler()))
+ using (var handler = new HttpMessageInvoker(CreateHttpClientHandler()))
{
byte[] byteContent = Encoding.ASCII.GetBytes(stringContent);
var content = new MemoryStream();
@@ -1824,7 +1823,7 @@ namespace System.Net.Http.Functional.Tests
return;
}
- using (var client = new HttpClient())
+ using (HttpClient client = CreateHttpClient())
{
var request = new HttpRequestMessage(
new HttpMethod(method),
@@ -1835,7 +1834,7 @@ namespace System.Net.Http.Functional.Tests
using (HttpResponseMessage response = await client.SendAsync(request))
{
- if (method == "TRACE" && (RuntimeInformation.IsOSPlatform(OSPlatform.Windows) || ManagedHandlerTestHelpers.IsEnabled))
+ if (method == "TRACE" && (RuntimeInformation.IsOSPlatform(OSPlatform.Windows) || UseManagedHandler))
{
// .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".
@@ -1860,7 +1859,7 @@ namespace System.Net.Http.Functional.Tests
[Fact]
public async Task SendAsync_RequestVersion10_ServerReceivesVersion10Request()
{
- if (ManagedHandlerTestHelpers.IsEnabled)
+ if (UseManagedHandler)
{
// TODO #23132: ManagedHandler doesn't support 1.0 currently.
return;
@@ -1883,7 +1882,7 @@ namespace System.Net.Http.Functional.Tests
[Fact]
public async Task SendAsync_RequestVersionNotSpecified_ServerReceivesVersion11Request()
{
- if (ManagedHandlerTestHelpers.IsEnabled)
+ if (UseManagedHandler)
{
// TODO #23132: ManagedHandler requires 1.1 currently.
return;
@@ -1895,6 +1894,7 @@ namespace System.Net.Http.Functional.Tests
Assert.Equal(new Version(1, 1), receivedRequestVersion);
}
+ [ActiveIssue(23770, TestPlatforms.AnyUnix)]
[SkipOnTargetFramework(TargetFrameworkMonikers.NetFramework, "Specifying Version(2,0) throws exception on netfx")]
[OuterLoop] // TODO: Issue #11345
[Theory]
@@ -1907,7 +1907,7 @@ namespace System.Net.Http.Functional.Tests
_output.WriteLine("Skipping test due to Windows 10 version prior to Version 1703.");
return;
}
- if (ManagedHandlerTestHelpers.IsEnabled)
+ if (UseManagedHandler)
{
// TODO #23134: The managed handler doesn't yet support HTTP/2.
return;
@@ -1918,7 +1918,7 @@ namespace System.Net.Http.Functional.Tests
var request = new HttpRequestMessage(HttpMethod.Get, server);
request.Version = new Version(2, 0);
- using (var handler = new HttpClientHandler())
+ using (HttpClientHandler handler = CreateHttpClientHandler())
using (var client = new HttpClient(handler, false))
{
// It is generally expected that the test hosts will be trusted, so we don't register a validation
@@ -1954,13 +1954,12 @@ namespace System.Net.Http.Functional.Tests
}
}
- [ActiveIssue(22735)]
[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)
+ if (UseManagedHandler)
{
// TODO #23134: The managed handler doesn't yet support HTTP/2.
return;
@@ -1970,7 +1969,7 @@ namespace System.Net.Http.Functional.Tests
var request = new HttpRequestMessage(HttpMethod.Get, server);
request.Version = new Version(2, 0);
- var handler = new HttpClientHandler();
+ HttpClientHandler handler = CreateHttpClientHandler();
using (var client = new HttpClient(handler))
{
using (HttpResponseMessage response = await client.SendAsync(request))
@@ -1990,7 +1989,7 @@ namespace System.Net.Http.Functional.Tests
var request = new HttpRequestMessage(HttpMethod.Get, url);
request.Version = requestVersion;
- using (var client = new HttpClient())
+ using (HttpClient client = CreateHttpClient())
{
Task<HttpResponseMessage> getResponse = client.SendAsync(request);
Task<List<string>> serverTask = LoopbackServer.ReadRequestAndSendResponseAsync(server);
@@ -2030,7 +2029,7 @@ namespace System.Net.Http.Functional.Tests
[MemberData(nameof(CredentialsForProxy))]
public async Task Proxy_BypassFalse_GetRequestGoesThroughCustomProxy(ICredentials creds, bool wrapCredsInCache)
{
- if (ManagedHandlerTestHelpers.IsEnabled)
+ if (UseManagedHandler)
{
// TODO #23135: ManagedHandler currently gets error "System.NotImplementedException : Basic auth: can't handle ':' in domain "dom:\ain""
return;
@@ -2052,9 +2051,11 @@ namespace System.Net.Http.Functional.Tests
creds = cache;
}
- using (var handler = new HttpClientHandler() { Proxy = new UseSpecifiedUriWebProxy(proxyUrl, creds) })
+ using (HttpClientHandler handler = CreateHttpClientHandler())
using (var client = new HttpClient(handler))
{
+ handler.Proxy = new UseSpecifiedUriWebProxy(proxyUrl, creds);
+
Task<HttpResponseMessage> responseTask = client.GetAsync(Configuration.Http.RemoteEchoServer);
Task<string> responseStringTask = responseTask.ContinueWith(t => t.Result.Content.ReadAsStringAsync(), TaskScheduler.Default).Unwrap();
await TestHelper.WhenAllCompletedOrAnyFailed(proxyTask, responseTask, responseStringTask);
@@ -2080,7 +2081,9 @@ namespace System.Net.Http.Functional.Tests
[MemberData(nameof(BypassedProxies))]
public async Task Proxy_BypassTrue_GetRequestDoesntGoesThroughCustomProxy(IWebProxy proxy)
{
- using (var client = new HttpClient(new HttpClientHandler() { Proxy = proxy }))
+ HttpClientHandler handler = CreateHttpClientHandler();
+ handler.Proxy = proxy;
+ using (var client = new HttpClient(handler))
using (HttpResponseMessage response = await client.GetAsync(Configuration.Http.RemoteEchoServer))
{
TestHelper.VerifyResponseBody(
@@ -2103,7 +2106,8 @@ namespace System.Net.Http.Functional.Tests
expectCreds: false);
Uri proxyUrl = new Uri($"http://localhost:{port}");
- using (var handler = new HttpClientHandler() { Proxy = new UseSpecifiedUriWebProxy(proxyUrl, null) })
+ HttpClientHandler handler = CreateHttpClientHandler();
+ handler.Proxy = new UseSpecifiedUriWebProxy(proxyUrl, null);
using (var client = new HttpClient(handler))
{
Task<HttpResponseMessage> responseTask = client.GetAsync(Configuration.Http.RemoteEchoServer);
@@ -2144,7 +2148,7 @@ namespace System.Net.Http.Functional.Tests
var request = new HttpRequestMessage(HttpMethod.Get, uri);
string statusLine = string.Empty;
- using (var client = new HttpClient())
+ using (HttpClient client = CreateHttpClient())
{
Task<HttpResponseMessage> getResponseTask = client.SendAsync(request);
Task<List<string>> serverTask = LoopbackServer.ReadRequestAndSendResponseAsync(server);
diff --git a/src/System.Net.Http/tests/FunctionalTests/HttpClientMiniStressTest.cs b/src/System.Net.Http/tests/FunctionalTests/HttpClientMiniStressTest.cs
index 2d4d07b15b..7866a00087 100644
--- a/src/System.Net.Http/tests/FunctionalTests/HttpClientMiniStressTest.cs
+++ b/src/System.Net.Http/tests/FunctionalTests/HttpClientMiniStressTest.cs
@@ -14,7 +14,7 @@ namespace System.Net.Http.Functional.Tests
{
using Configuration = System.Net.Test.Common.Configuration;
- public class HttpClientMiniStress
+ public class HttpClientMiniStress : HttpClientTestBase
{
private static bool HttpStressEnabled => Configuration.Http.StressEnabled;
@@ -23,7 +23,7 @@ namespace System.Net.Http.Functional.Tests
public void SingleClient_ManyGets_Sync(int numRequests, int dop, HttpCompletionOption completionOption)
{
string responseText = CreateResponse("abcdefghijklmnopqrstuvwxyz");
- using (var client = new HttpClient())
+ using (HttpClient client = CreateHttpClient())
{
Parallel.For(0, numRequests, new ParallelOptions { MaxDegreeOfParallelism = dop, TaskScheduler = new ThreadPerTaskScheduler() }, _ =>
{
@@ -36,7 +36,7 @@ namespace System.Net.Http.Functional.Tests
public async Task SingleClient_ManyGets_Async(int numRequests, int dop, HttpCompletionOption completionOption)
{
string responseText = CreateResponse("abcdefghijklmnopqrstuvwxyz");
- using (var client = new HttpClient())
+ using (HttpClient client = CreateHttpClient())
{
await ForCountAsync(numRequests, dop, i => CreateServerAndGetAsync(client, completionOption, responseText));
}
@@ -49,7 +49,7 @@ namespace System.Net.Http.Functional.Tests
string responseText = CreateResponse("abcdefghijklmnopqrstuvwxyz");
Parallel.For(0, numRequests, new ParallelOptions { MaxDegreeOfParallelism = dop, TaskScheduler = new ThreadPerTaskScheduler() }, _ =>
{
- using (var client = new HttpClient())
+ using (HttpClient client = CreateHttpClient())
{
CreateServerAndGet(client, completionOption, responseText);
}
@@ -63,7 +63,7 @@ namespace System.Net.Http.Functional.Tests
string responseText = CreateResponse("");
await ForCountAsync(numRequests, dop, async i =>
{
- using (HttpClient client = new HttpClient())
+ using (HttpClient client = CreateHttpClient())
{
await CreateServerAndPostAsync(client, numBytes, responseText);
}
@@ -76,7 +76,7 @@ namespace System.Net.Http.Functional.Tests
{
for (int i = 0; i < numClients; i++)
{
- new HttpClient().Dispose();
+ CreateHttpClient().Dispose();
}
}
@@ -86,7 +86,7 @@ namespace System.Net.Http.Functional.Tests
{
await LoopbackServer.CreateServerAsync(async (server, url) =>
{
- using (var client = new HttpClient())
+ using (HttpClient client = CreateHttpClient())
{
client.Timeout = Timeout.InfiniteTimeSpan;
@@ -193,7 +193,7 @@ namespace System.Net.Http.Functional.Tests
{
await LoopbackServer.CreateServerAsync(async (server, url) =>
{
- using (var client = new HttpClient())
+ using (HttpClient client = CreateHttpClient())
{
Func<Task<WeakReference>> getAsync = async () => new WeakReference(await client.GetAsync(url, HttpCompletionOption.ResponseHeadersRead));
Task<WeakReference> wrt = getAsync();
diff --git a/src/System.Net.Http/tests/FunctionalTests/HttpClientTest.cs b/src/System.Net.Http/tests/FunctionalTests/HttpClientTest.cs
index 42228af72a..5be76eb659 100644
--- a/src/System.Net.Http/tests/FunctionalTests/HttpClientTest.cs
+++ b/src/System.Net.Http/tests/FunctionalTests/HttpClientTest.cs
@@ -2,13 +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.Collections.Concurrent;
-using System.Diagnostics;
-using System.Diagnostics.Tracing;
using System.IO;
using System.Linq;
using System.Net.Test.Common;
-using System.Reflection;
using System.Threading;
using System.Threading.Tasks;
@@ -16,14 +12,12 @@ using Xunit;
namespace System.Net.Http.Functional.Tests
{
- using Configuration = System.Net.Test.Common.Configuration;
-
- public class HttpClientTest
+ public class HttpClientTest : HttpClientTestBase
{
[Fact]
public void Dispose_MultipleTimes_Success()
{
- var client = new HttpClient();
+ HttpClient client = CreateHttpClient();
client.Dispose();
client.Dispose();
}
@@ -31,7 +25,7 @@ namespace System.Net.Http.Functional.Tests
[Fact]
public void DefaultRequestHeaders_Idempotent()
{
- using (var client = new HttpClient())
+ using (HttpClient client = CreateHttpClient())
{
Assert.NotNull(client.DefaultRequestHeaders);
Assert.Same(client.DefaultRequestHeaders, client.DefaultRequestHeaders);
@@ -41,7 +35,7 @@ namespace System.Net.Http.Functional.Tests
[Fact]
public void BaseAddress_Roundtrip_Equal()
{
- using (var client = new HttpClient())
+ using (HttpClient client = CreateHttpClient())
{
Assert.Null(client.BaseAddress);
@@ -57,7 +51,7 @@ namespace System.Net.Http.Functional.Tests
[Fact]
public void BaseAddress_InvalidUri_Throws()
{
- using (var client = new HttpClient())
+ using (HttpClient client = CreateHttpClient())
{
AssertExtensions.Throws<ArgumentException>("value", () => client.BaseAddress = new Uri("ftp://onlyhttpsupported"));
AssertExtensions.Throws<ArgumentException>("value", () => client.BaseAddress = new Uri("/onlyabsolutesupported", UriKind.Relative));
@@ -67,7 +61,7 @@ namespace System.Net.Http.Functional.Tests
[Fact]
public void Timeout_Roundtrip_Equal()
{
- using (var client = new HttpClient())
+ using (HttpClient client = CreateHttpClient())
{
client.Timeout = Timeout.InfiniteTimeSpan;
Assert.Equal(Timeout.InfiniteTimeSpan, client.Timeout);
@@ -80,7 +74,7 @@ namespace System.Net.Http.Functional.Tests
[Fact]
public void Timeout_OutOfRange_Throws()
{
- using (var client = new HttpClient())
+ using (HttpClient client = CreateHttpClient())
{
AssertExtensions.Throws<ArgumentOutOfRangeException>("value", () => client.Timeout = TimeSpan.FromSeconds(-2));
AssertExtensions.Throws<ArgumentOutOfRangeException>("value", () => client.Timeout = TimeSpan.FromSeconds(0));
@@ -91,7 +85,7 @@ namespace System.Net.Http.Functional.Tests
[Fact]
public void MaxResponseContentBufferSize_Roundtrip_Equal()
{
- using (var client = new HttpClient())
+ using (HttpClient client = CreateHttpClient())
{
client.MaxResponseContentBufferSize = 1;
Assert.Equal(1, client.MaxResponseContentBufferSize);
@@ -104,7 +98,7 @@ namespace System.Net.Http.Functional.Tests
[Fact]
public void MaxResponseContentBufferSize_OutOfRange_Throws()
{
- using (var client = new HttpClient())
+ using (HttpClient client = CreateHttpClient())
{
AssertExtensions.Throws<ArgumentOutOfRangeException>("value", () => client.MaxResponseContentBufferSize = -1);
AssertExtensions.Throws<ArgumentOutOfRangeException>("value", () => client.MaxResponseContentBufferSize = 0);
@@ -124,8 +118,10 @@ namespace System.Net.Http.Functional.Tests
[InlineData(1000, 1000, false)]
public async Task MaxResponseContentBufferSize_ThrowsIfTooSmallForContent(int maxSize, int contentLength, bool exceptionExpected)
{
- using (var client = new HttpClient() { MaxResponseContentBufferSize = maxSize })
+ using (HttpClient client = CreateHttpClient())
{
+ client.MaxResponseContentBufferSize = maxSize;
+
await LoopbackServer.CreateServerAsync(async (server, url) =>
{
Task<string> getTask = client.GetStringAsync(url);
@@ -166,7 +162,7 @@ namespace System.Net.Http.Functional.Tests
[InlineData("/something.html")]
public void GetAsync_NoBaseAddress_InvalidUri_ThrowsException(string uri)
{
- using (var client = new HttpClient())
+ using (HttpClient client = CreateHttpClient())
{
Assert.Throws<InvalidOperationException>(() => { client.GetAsync(uri == null ? null : new Uri(uri, UriKind.RelativeOrAbsolute)); });
}
@@ -253,7 +249,7 @@ namespace System.Net.Http.Functional.Tests
[Fact]
public async Task GetAsync_InvalidUrl_ExpectedExceptionThrown()
{
- using (var client = new HttpClient())
+ using (HttpClient client = CreateHttpClient())
{
await Assert.ThrowsAsync<HttpRequestException>(() => client.GetAsync(CreateFakeUri()));
await Assert.ThrowsAsync<HttpRequestException>(() => client.GetStringAsync(CreateFakeUri()));
@@ -363,7 +359,7 @@ namespace System.Net.Http.Functional.Tests
[Fact]
public void Dispose_UseAfterDispose_Throws()
{
- var client = new HttpClient();
+ HttpClient client = CreateHttpClient();
client.Dispose();
Assert.Throws<ObjectDisposedException>(() => client.BaseAddress = null);
@@ -411,8 +407,10 @@ namespace System.Net.Http.Functional.Tests
[OuterLoop("One second delay in getting server's response")]
public async Task Timeout_SetTo30AndGetResponseFromLoopbackQuickly_Success()
{
- using (var client = new HttpClient() { Timeout = TimeSpan.FromSeconds(30) })
+ using (HttpClient client = CreateHttpClient())
{
+ client.Timeout = TimeSpan.FromSeconds(30);
+
await LoopbackServer.CreateServerAsync(async (server, url) =>
{
Task getTask = client.GetStringAsync(url);
diff --git a/src/System.Net.Http/tests/FunctionalTests/HttpClientTestBase.cs b/src/System.Net.Http/tests/FunctionalTests/HttpClientTestBase.cs
new file mode 100644
index 0000000000..c8220d916b
--- /dev/null
+++ b/src/System.Net.Http/tests/FunctionalTests/HttpClientTestBase.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.Diagnostics;
+using System.Threading;
+
+namespace System.Net.Http.Functional.Tests
+{
+ public abstract class HttpClientTestBase : RemoteExecutorTestBase
+ {
+ private const string ManagedHandlerEnvVar = "COMPlus_UseManagedHttpClientHandler";
+ private static readonly LocalDataStoreSlot s_managedHandlerSlot;
+
+ static HttpClientTestBase()
+ {
+ s_managedHandlerSlot = Thread.GetNamedDataSlot(ManagedHandlerEnvVar);
+ if (s_managedHandlerSlot == null)
+ {
+ try
+ {
+ s_managedHandlerSlot = Thread.AllocateNamedDataSlot(ManagedHandlerEnvVar);
+ }
+ catch (ArgumentException)
+ {
+ s_managedHandlerSlot = Thread.GetNamedDataSlot(ManagedHandlerEnvVar);
+ }
+ }
+ Debug.Assert(s_managedHandlerSlot != null);
+ }
+
+ protected virtual bool UseManagedHandler => false;
+
+ protected HttpClient CreateHttpClient() => new HttpClient(CreateHttpClientHandler());
+
+ protected HttpClientHandler CreateHttpClientHandler() => CreateHttpClientHandler(UseManagedHandler);
+
+ protected static HttpClient CreateHttpClient(string useManagedHandlerBoolString) =>
+ new HttpClient(CreateHttpClientHandler(useManagedHandlerBoolString));
+
+ protected static HttpClientHandler CreateHttpClientHandler(string useManagedHandlerBoolString) =>
+ CreateHttpClientHandler(bool.Parse(useManagedHandlerBoolString));
+
+ protected static HttpClientHandler CreateHttpClientHandler(bool useManagedHandler) =>
+ useManagedHandler ? CreateManagedHttpClientHandler() : new HttpClientHandler();
+
+ private static HttpClientHandler CreateManagedHttpClientHandler()
+ {
+ try
+ {
+ Thread.SetData(s_managedHandlerSlot, true);
+ return new HttpClientHandler();
+ }
+ finally
+ {
+ Thread.SetData(s_managedHandlerSlot, null);
+ }
+ }
+ }
+}
diff --git a/src/System.Net.Http/tests/FunctionalTests/ManagedHandlerTest.cs b/src/System.Net.Http/tests/FunctionalTests/ManagedHandlerTest.cs
index ab2c497fc4..dfbade9de1 100644
--- a/src/System.Net.Http/tests/FunctionalTests/ManagedHandlerTest.cs
+++ b/src/System.Net.Http/tests/FunctionalTests/ManagedHandlerTest.cs
@@ -21,123 +21,87 @@ using Xunit.Abstractions;
// - By setting the env var prior to running tests, every test will implicitly use the managed handler,
// at which point the tests in this file are duplicative and can be commented out.
-// For now parallelism is disabled because we use an env var to turn on the managed handler, and the env var
-// impacts any tests running concurrently in the process. We can remove this restriction in the future once
-// plans around the ManagedHandler are better understood.
-[assembly: CollectionBehavior(CollectionBehavior.CollectionPerAssembly, DisableTestParallelization = true, MaxParallelThreads = 1)]
-
namespace System.Net.Http.Functional.Tests
{
public sealed class ManagedHandler_HttpClientTest : HttpClientTest, IDisposable
{
- public ManagedHandler_HttpClientTest() => ManagedHandlerTestHelpers.SetEnvVar();
- public void Dispose() => ManagedHandlerTestHelpers.RemoveEnvVar();
+ protected override bool UseManagedHandler => true;
}
public sealed class ManagedHandler_DiagnosticsTest : DiagnosticsTest, IDisposable
{
- public ManagedHandler_DiagnosticsTest() => ManagedHandlerTestHelpers.SetEnvVar();
- public new void Dispose()
- {
- ManagedHandlerTestHelpers.RemoveEnvVar();
- base.Dispose();
- }
+ protected override bool UseManagedHandler => true;
}
- // TODO #23139: 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_HttpClientEKUTest : HttpClientEKUTest, IDisposable
+ {
+ protected override bool UseManagedHandler => true;
+ }
public sealed class ManagedHandler_HttpClientHandler_DangerousAcceptAllCertificatesValidator_Test : HttpClientHandler_DangerousAcceptAllCertificatesValidator_Test, IDisposable
{
- public ManagedHandler_HttpClientHandler_DangerousAcceptAllCertificatesValidator_Test() => ManagedHandlerTestHelpers.SetEnvVar();
- public void Dispose() => ManagedHandlerTestHelpers.RemoveEnvVar();
+ protected override bool UseManagedHandler => true;
}
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 ManagedHandler_HttpClientHandler_ClientCertificates_Test(ITestOutputHelper output) : base(output) { }
+ protected override bool UseManagedHandler => true;
}
public sealed class ManagedHandler_HttpClientHandler_DefaultProxyCredentials_Test : HttpClientHandler_DefaultProxyCredentials_Test, IDisposable
{
- public ManagedHandler_HttpClientHandler_DefaultProxyCredentials_Test() => ManagedHandlerTestHelpers.SetEnvVar();
- public new void Dispose()
- {
- ManagedHandlerTestHelpers.RemoveEnvVar();
- base.Dispose();
- }
+ protected override bool UseManagedHandler => true;
}
public sealed class ManagedHandler_HttpClientHandler_MaxConnectionsPerServer_Test : HttpClientHandler_MaxConnectionsPerServer_Test, IDisposable
{
- public ManagedHandler_HttpClientHandler_MaxConnectionsPerServer_Test() => ManagedHandlerTestHelpers.SetEnvVar();
- public void Dispose() => ManagedHandlerTestHelpers.RemoveEnvVar();
+ protected override bool UseManagedHandler => true;
}
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();
- }
+ protected override bool UseManagedHandler => true;
}
public sealed class ManagedHandler_PostScenarioTest : PostScenarioTest, IDisposable
{
- public ManagedHandler_PostScenarioTest(ITestOutputHelper output) : base(output) => ManagedHandlerTestHelpers.SetEnvVar();
- public void Dispose() => ManagedHandlerTestHelpers.RemoveEnvVar();
+ public ManagedHandler_PostScenarioTest(ITestOutputHelper output) : base(output) { }
+ protected override bool UseManagedHandler => true;
}
public sealed class ManagedHandler_ResponseStreamTest : ResponseStreamTest, IDisposable
{
- public ManagedHandler_ResponseStreamTest(ITestOutputHelper output) : base(output) => ManagedHandlerTestHelpers.SetEnvVar();
- public void Dispose() => ManagedHandlerTestHelpers.RemoveEnvVar();
+ public ManagedHandler_ResponseStreamTest(ITestOutputHelper output) : base(output) { }
+ protected override bool UseManagedHandler => true;
}
-
+
public sealed class ManagedHandler_HttpClientHandler_SslProtocols_Test : HttpClientHandler_SslProtocols_Test, IDisposable
{
- public ManagedHandler_HttpClientHandler_SslProtocols_Test() => ManagedHandlerTestHelpers.SetEnvVar();
- public void Dispose() => ManagedHandlerTestHelpers.RemoveEnvVar();
+ protected override bool UseManagedHandler => true;
}
public sealed class ManagedHandler_SchSendAuxRecordHttpTest : SchSendAuxRecordHttpTest, IDisposable
{
- public ManagedHandler_SchSendAuxRecordHttpTest(ITestOutputHelper output) : base(output) => ManagedHandlerTestHelpers.SetEnvVar();
- public void Dispose() => ManagedHandlerTestHelpers.RemoveEnvVar();
+ public ManagedHandler_SchSendAuxRecordHttpTest(ITestOutputHelper output) : base(output) { }
+ protected override bool UseManagedHandler => true;
}
public sealed class ManagedHandler_HttpClientMiniStress : HttpClientMiniStress, IDisposable
{
- public ManagedHandler_HttpClientMiniStress() => ManagedHandlerTestHelpers.SetEnvVar();
- public void Dispose() => ManagedHandlerTestHelpers.RemoveEnvVar();
+ protected override bool UseManagedHandler => true;
}
- // TODO #23140:
- //public sealed class ManagedHandler_DefaultCredentialsTest : DefaultCredentialsTest, IDisposable
- //{
- // 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();
- }
+ public ManagedHandler_HttpClientHandlerTest(ITestOutputHelper output) : base(output) { }
+ protected override bool UseManagedHandler => true;
+ }
+
+ public sealed class ManagedHandler_DefaultCredentialsTest : DefaultCredentialsTest, IDisposable
+ {
+ public ManagedHandler_DefaultCredentialsTest(ITestOutputHelper output) : base(output) { }
+ protected override bool UseManagedHandler => true;
}
// TODO #23141: Socket's don't support canceling individual operations, so ReadStream on NetworkStream
@@ -147,30 +111,24 @@ namespace System.Net.Http.Functional.Tests
// 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();
+ // public ManagedHandler_CancellationTest(ITestOutputHelper output) : base(output) { }
+ // protected override bool UseManagedHandler => true;
//}
// TODO #23142: 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();
- // public new void Dispose()
- // {
- // ManagedHandlerTestHelpers.RemoveEnvVar();
- // base.Dispose();
- // }
+ // protected override bool UseManagedHandler => true;
//}
- public sealed class ManagedHandler_HttpClientHandler_DuplexCommunication_Test : IDisposable
+ public sealed class ManagedHandler_HttpClientHandler_DuplexCommunication_Test : HttpClientTestBase, IDisposable
{
- public ManagedHandler_HttpClientHandler_DuplexCommunication_Test() => ManagedHandlerTestHelpers.SetEnvVar();
- public void Dispose() => ManagedHandlerTestHelpers.RemoveEnvVar();
+ protected override bool UseManagedHandler => true;
[Fact]
public async Task SendBytesBackAndForthBetweenClientAndServer_Success()
{
- using (var client = new HttpClient())
+ using (HttpClient client = CreateHttpClient())
using (var listener = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp))
{
listener.Bind(new IPEndPoint(IPAddress.Loopback, 0));
@@ -295,10 +253,9 @@ namespace System.Net.Http.Functional.Tests
}
- public sealed class ManagedHandler_HttpClientHandler_ConnectionPooling_Test : IDisposable
+ public sealed class ManagedHandler_HttpClientHandler_ConnectionPooling_Test : HttpClientTestBase, IDisposable
{
- public ManagedHandler_HttpClientHandler_ConnectionPooling_Test() => ManagedHandlerTestHelpers.SetEnvVar();
- public void Dispose() => ManagedHandlerTestHelpers.RemoveEnvVar();
+ protected override bool UseManagedHandler => true;
// TODO: Currently the subsequent tests sometimes fail/hang with WinHttpHandler / CurlHandler.
// In theory they should pass with any handler that does appropriate connection pooling.
@@ -308,7 +265,7 @@ namespace System.Net.Http.Functional.Tests
[Fact]
public async Task MultipleIterativeRequests_SameConnectionReused()
{
- using (var client = new HttpClient())
+ using (HttpClient client = CreateHttpClient())
using (var listener = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp))
{
listener.Bind(new IPEndPoint(IPAddress.Loopback, 0));
@@ -347,7 +304,7 @@ namespace System.Net.Http.Functional.Tests
[Fact]
public async Task ServerDisconnectsAfterInitialRequest_SubsequentRequestUsesDifferentConnection()
{
- using (var client = new HttpClient())
+ using (HttpClient client = CreateHttpClient())
using (var listener = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp))
{
listener.Bind(new IPEndPoint(IPAddress.Loopback, 0));
@@ -386,7 +343,7 @@ namespace System.Net.Http.Functional.Tests
[Fact]
public async Task ServerSendsConnectionClose_SubsequentRequestUsesDifferentConnection()
{
- using (var client = new HttpClient())
+ using (HttpClient client = CreateHttpClient())
using (var listener = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp))
{
listener.Bind(new IPEndPoint(IPAddress.Loopback, 0));
diff --git a/src/System.Net.Http/tests/FunctionalTests/ManagedHandlerTestHelpers.cs b/src/System.Net.Http/tests/FunctionalTests/ManagedHandlerTestHelpers.cs
deleted file mode 100644
index 758dbdceb0..0000000000
--- a/src/System.Net.Http/tests/FunctionalTests/ManagedHandlerTestHelpers.cs
+++ /dev/null
@@ -1,17 +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;
-using Xunit.Abstractions;
-
-namespace System.Net.Http.Functional.Tests
-{
- internal static class ManagedHandlerTestHelpers
- {
- private const string ManagedHandlerEnvVar = "COMPlus_UseManagedHttpClientHandler";
- public static void SetEnvVar() => Environment.SetEnvironmentVariable(ManagedHandlerEnvVar, "true");
- public static void RemoveEnvVar() => Environment.SetEnvironmentVariable(ManagedHandlerEnvVar, null);
- public static bool IsEnabled => Environment.GetEnvironmentVariable(ManagedHandlerEnvVar) == "true";
- }
-}
diff --git a/src/System.Net.Http/tests/FunctionalTests/PostScenarioTest.cs b/src/System.Net.Http/tests/FunctionalTests/PostScenarioTest.cs
index d1a7823b7b..5c5ee93fe8 100644
--- a/src/System.Net.Http/tests/FunctionalTests/PostScenarioTest.cs
+++ b/src/System.Net.Http/tests/FunctionalTests/PostScenarioTest.cs
@@ -2,14 +2,8 @@
// 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.Net.Http.Headers;
-using System.Net.Test.Common;
-using System.Security.Cryptography;
using System.Text;
using System.Threading.Tasks;
-
using Xunit;
using Xunit.Abstractions;
@@ -20,7 +14,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.
[SkipOnTargetFramework(TargetFrameworkMonikers.Uap, "dotnet/corefx #20010")]
- public class PostScenarioTest
+ public class PostScenarioTest : HttpClientTestBase
{
private const string ExpectedContent = "Test contest";
private const string UserName = "user1";
@@ -178,7 +172,7 @@ namespace System.Net.Http.Functional.Tests
[Theory, MemberData(nameof(EchoServers))]
public async Task PostAsync_EmptyContent_ContentTypeHeaderNotSent(Uri serverUri)
{
- using (var client = new HttpClient())
+ using (HttpClient client = CreateHttpClient())
using (HttpResponseMessage response = await client.PostAsync(serverUri, null))
{
string responseContent = await response.Content.ReadAsStringAsync();
@@ -195,7 +189,7 @@ namespace System.Net.Http.Functional.Tests
bool useContentLengthUpload,
bool useChunkedEncodingUpload)
{
- using (var client = new HttpClient())
+ using (HttpClient client = CreateHttpClient())
{
if (!useContentLengthUpload && requestContent != null)
{
@@ -234,7 +228,7 @@ namespace System.Net.Http.Functional.Tests
NetworkCredential credential,
bool preAuthenticate)
{
- var handler = new HttpClientHandler();
+ HttpClientHandler handler = CreateHttpClientHandler();
handler.PreAuthenticate = preAuthenticate;
handler.Credentials = credential;
using (var client = new HttpClient(handler))
diff --git a/src/System.Net.Http/tests/FunctionalTests/PostScenarioUWPTest.cs b/src/System.Net.Http/tests/FunctionalTests/PostScenarioUWPTest.cs
index 1cce398e2b..1c58ff83eb 100644
--- a/src/System.Net.Http/tests/FunctionalTests/PostScenarioUWPTest.cs
+++ b/src/System.Net.Http/tests/FunctionalTests/PostScenarioUWPTest.cs
@@ -15,7 +15,7 @@ namespace System.Net.Http.Functional.Tests
{
using Configuration = System.Net.Test.Common.Configuration;
- public class PostScenarioUWPTest : RemoteExecutorTestBase
+ public class PostScenarioUWPTest : HttpClientTestBase
{
private readonly ITestOutputHelper _output;
@@ -27,15 +27,15 @@ namespace System.Net.Http.Functional.Tests
[Fact]
public void Authentication_UseStreamContent_Throws()
{
- RemoteInvoke(async () =>
+ RemoteInvoke(async useManagedHandlerString =>
{
// 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();
+ Uri uri = Configuration.Http.BasicAuthUriForCreds(secure: false, userName: username, password: password);
+ HttpClientHandler handler = CreateHttpClientHandler(useManagedHandlerString);
handler.Credentials = new NetworkCredential(username, password);
using (var client = new HttpClient(handler))
@@ -48,18 +48,18 @@ namespace System.Net.Http.Functional.Tests
}
return SuccessExitCode;
- }).Dispose();
+ }, UseManagedHandler.ToString()).Dispose();
}
[Fact]
public void Authentication_UseMultiInterfaceNonRewindableStreamContent_Throws()
{
- RemoteInvoke(async () =>
+ RemoteInvoke(async useManagedHandlerString =>
{
string username = "testuser";
string password = "password";
Uri uri = Configuration.Http.BasicAuthUriForCreds(secure: false, userName: username, password: password);
- var handler = new HttpClientHandler();
+ HttpClientHandler handler = CreateHttpClientHandler(useManagedHandlerString);
handler.Credentials = new NetworkCredential(username, password);
using (var client = new HttpClient(handler))
@@ -72,18 +72,18 @@ namespace System.Net.Http.Functional.Tests
}
return SuccessExitCode;
- }).Dispose();
+ }, UseManagedHandler.ToString()).Dispose();
}
[Fact]
public void Authentication_UseMultiInterfaceStreamContent_Success()
{
- RemoteInvoke(async () =>
+ RemoteInvoke(async useManagedHandlerString =>
{
string username = "testuser";
string password = "password";
Uri uri = Configuration.Http.BasicAuthUriForCreds(secure: false, userName: username, password: password);
- var handler = new HttpClientHandler();
+ HttpClientHandler handler = CreateHttpClientHandler(useManagedHandlerString);
handler.Credentials = new NetworkCredential(username, password);
using (var client = new HttpClient(handler))
@@ -100,18 +100,18 @@ namespace System.Net.Http.Functional.Tests
}
return SuccessExitCode;
- }).Dispose();
+ }, UseManagedHandler.ToString()).Dispose();
}
[Fact]
public void Authentication_UseMemoryStreamVisibleBufferContent_Success()
{
- RemoteInvoke(async () =>
+ RemoteInvoke(async useManagedHandlerString =>
{
string username = "testuser";
string password = "password";
Uri uri = Configuration.Http.BasicAuthUriForCreds(secure: false, userName: username, password: password);
- var handler = new HttpClientHandler();
+ HttpClientHandler handler = CreateHttpClientHandler(useManagedHandlerString);
handler.Credentials = new NetworkCredential(username, password);
using (var client = new HttpClient(handler))
@@ -128,18 +128,18 @@ namespace System.Net.Http.Functional.Tests
}
return SuccessExitCode;
- }).Dispose();
+ }, UseManagedHandler.ToString()).Dispose();
}
[Fact]
public void Authentication_UseMemoryStreamNotVisibleBufferContent_Success()
{
- RemoteInvoke(async () =>
+ RemoteInvoke(async useManagedHandlerString =>
{
string username = "testuser";
string password = "password";
Uri uri = Configuration.Http.BasicAuthUriForCreds(secure: false, userName: username, password: password);
- var handler = new HttpClientHandler();
+ HttpClientHandler handler = CreateHttpClientHandler(useManagedHandlerString);
handler.Credentials = new NetworkCredential(username, password);
using (var client = new HttpClient(handler))
@@ -156,7 +156,7 @@ namespace System.Net.Http.Functional.Tests
}
return SuccessExitCode;
- }).Dispose();
+ }, UseManagedHandler.ToString()).Dispose();
}
}
}
diff --git a/src/System.Net.Http/tests/FunctionalTests/ReadOnlyMemoryContentTest.cs b/src/System.Net.Http/tests/FunctionalTests/ReadOnlyMemoryContentTest.cs
new file mode 100644
index 0000000000..01334a8c3f
--- /dev/null
+++ b/src/System.Net.Http/tests/FunctionalTests/ReadOnlyMemoryContentTest.cs
@@ -0,0 +1,404 @@
+// 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.Buffers;
+using System.Collections.Generic;
+using System.IO;
+using System.IO.Tests;
+using System.Threading;
+using System.Threading.Tasks;
+using Xunit;
+
+namespace System.Net.Http.Functional.Tests
+{
+ public class ReadOnlyMemoryContentTest
+ {
+ public static IEnumerable<object[]> ContentLengthsAndUseArrays()
+ {
+ foreach (int length in new[] { 0, 1, 4096 })
+ {
+ foreach (bool useArray in new[] { true, false })
+ {
+ yield return new object[] { length, useArray };
+ }
+ }
+ }
+
+ public static IEnumerable<object[]> TrueFalse()
+ {
+ yield return new object[] { true };
+ yield return new object[] { false };
+ }
+
+ [Theory]
+ [MemberData(nameof(ContentLengthsAndUseArrays))]
+ public void ContentLength_LengthMatchesArrayLength(int contentLength, bool useArray)
+ {
+ Memory<byte> memory;
+ OwnedMemory<byte> ownedMemory;
+ ReadOnlyMemoryContent content = CreateContent(contentLength, useArray, out memory, out ownedMemory);
+
+ Assert.Equal(contentLength, content.Headers.ContentLength);
+
+ ownedMemory?.Dispose();
+ }
+
+ [Theory]
+ [MemberData(nameof(TrueFalse))]
+ public async Task ReadAsStreamAsync_TrivialMembersHaveExpectedValuesAndBehavior(bool useArray)
+ {
+ const int ContentLength = 42;
+ Memory<byte> memory;
+ OwnedMemory<byte> ownedMemory;
+ ReadOnlyMemoryContent content = CreateContent(ContentLength, useArray, out memory, out ownedMemory);
+
+ using (Stream stream = await content.ReadAsStreamAsync())
+ {
+ // property values
+ Assert.Equal(ContentLength, stream.Length);
+ Assert.Equal(0, stream.Position);
+ Assert.True(stream.CanRead);
+ Assert.True(stream.CanSeek);
+ Assert.False(stream.CanWrite);
+
+ // not supported
+ Assert.Throws<NotSupportedException>(() => stream.SetLength(12345));
+ Assert.Throws<NotSupportedException>(() => stream.WriteByte(0));
+ Assert.Throws<NotSupportedException>(() => stream.Write(new byte[1], 0, 1));
+ Assert.Throws<NotSupportedException>(() => stream.Write(new ReadOnlySpan<byte>(new byte[1])));
+ await Assert.ThrowsAsync<NotSupportedException>(() => stream.WriteAsync(new byte[1], 0, 1));
+ await Assert.ThrowsAsync<NotSupportedException>(() => stream.WriteAsync(new ReadOnlyMemory<byte>(new byte[1])));
+
+ // nops
+ stream.Flush();
+ await stream.FlushAsync();
+ }
+
+ ownedMemory?.Dispose();
+ }
+
+ [Theory]
+ [MemberData(nameof(TrueFalse))]
+ public async Task ReadAsStreamAsync_Seek(bool useArray)
+ {
+ const int ContentLength = 42;
+ Memory<byte> memory;
+ OwnedMemory<byte> ownedMemory;
+ ReadOnlyMemoryContent content = CreateContent(ContentLength, useArray, out memory, out ownedMemory);
+
+ using (Stream s = await content.ReadAsStreamAsync())
+ {
+ foreach (int pos in new[] { 0, ContentLength / 2, ContentLength - 1 })
+ {
+ s.Position = pos;
+ Assert.Equal(pos, s.Position);
+ Assert.Equal(memory.Span[pos], s.ReadByte());
+ }
+
+ foreach (int pos in new[] { 0, ContentLength / 2, ContentLength - 1 })
+ {
+ Assert.Equal(0, s.Seek(0, SeekOrigin.Begin));
+ Assert.Equal(memory.Span[0], s.ReadByte());
+ }
+
+ Assert.Equal(ContentLength, s.Seek(0, SeekOrigin.End));
+ Assert.Equal(s.Position, s.Length);
+ Assert.Equal(-1, s.ReadByte());
+
+ Assert.Equal(0, s.Seek(-ContentLength, SeekOrigin.End));
+ Assert.Equal(0, s.Position);
+ Assert.Equal(memory.Span[0], s.ReadByte());
+
+ s.Position = 0;
+ Assert.Equal(0, s.Seek(0, SeekOrigin.Current));
+ Assert.Equal(0, s.Position);
+
+ Assert.Equal(1, s.Seek(1, SeekOrigin.Current));
+ Assert.Equal(1, s.Position);
+ Assert.Equal(memory.Span[1], s.ReadByte());
+ Assert.Equal(2, s.Position);
+ Assert.Equal(3, s.Seek(1, SeekOrigin.Current));
+ Assert.Equal(1, s.Seek(-2, SeekOrigin.Current));
+
+ Assert.Equal(int.MaxValue, s.Seek(int.MaxValue, SeekOrigin.Begin));
+ Assert.Equal(int.MaxValue, s.Position);
+ Assert.Equal(int.MaxValue, s.Seek(0, SeekOrigin.Current));
+ Assert.Equal(int.MaxValue, s.Position);
+ Assert.Equal(int.MaxValue, s.Seek(int.MaxValue - ContentLength, SeekOrigin.End));
+ Assert.Equal(int.MaxValue, s.Position);
+ Assert.Equal(-1, s.ReadByte());
+ Assert.Equal(int.MaxValue, s.Position);
+
+ Assert.Throws<ArgumentOutOfRangeException>("value", () => s.Position = -1);
+ Assert.Throws<IOException>(() => s.Seek(-1, SeekOrigin.Begin));
+
+ AssertExtensions.Throws<ArgumentOutOfRangeException>("value", () => s.Position = (long)int.MaxValue + 1);
+ AssertExtensions.Throws<ArgumentOutOfRangeException>("offset", () => s.Seek((long)int.MaxValue + 1, SeekOrigin.Begin));
+
+ Assert.ThrowsAny<ArgumentException>(() => s.Seek(0, (SeekOrigin)42));
+ }
+
+ ownedMemory?.Dispose();
+ }
+
+ [Theory]
+ [MemberData(nameof(ContentLengthsAndUseArrays))]
+ public async Task ReadAsStreamAsync_ReadByte_MatchesInput(int contentLength, bool useArray)
+ {
+ Memory<byte> memory;
+ OwnedMemory<byte> ownedMemory;
+ ReadOnlyMemoryContent content = CreateContent(contentLength, useArray, out memory, out ownedMemory);
+
+ using (Stream stream = await content.ReadAsStreamAsync())
+ {
+ for (int i = 0; i < contentLength; i++)
+ {
+ Assert.Equal(memory.Span[i], stream.ReadByte());
+ Assert.Equal(i + 1, stream.Position);
+ }
+ Assert.Equal(-1, stream.ReadByte());
+ Assert.Equal(stream.Length, stream.Position);
+ }
+
+ ownedMemory?.Dispose();
+ }
+
+ [Theory]
+ [MemberData(nameof(TrueFalse))]
+ public async Task ReadAsStreamAsync_Read_InvalidArguments(bool useArray)
+ {
+ const int ContentLength = 42;
+ Memory<byte> memory;
+ OwnedMemory<byte> ownedMemory;
+ ReadOnlyMemoryContent content = CreateContent(ContentLength, useArray, out memory, out ownedMemory);
+
+ using (Stream stream = await content.ReadAsStreamAsync())
+ {
+ AssertExtensions.Throws<ArgumentNullException>("buffer", () => stream.Read(null, 0, 0));
+ AssertExtensions.Throws<ArgumentNullException>("buffer", () => { stream.ReadAsync(null, 0, 0); });
+
+ AssertExtensions.Throws<ArgumentOutOfRangeException>("offset", () => stream.Read(new byte[1], -1, 1));
+ AssertExtensions.Throws<ArgumentOutOfRangeException>("offset", () => stream.Read(new byte[1], -1, 1));
+
+ AssertExtensions.Throws<ArgumentOutOfRangeException>("count", () => stream.Read(new byte[1], 0, -1));
+ AssertExtensions.Throws<ArgumentOutOfRangeException>("count", () => stream.Read(new byte[1], 0, -1));
+
+ Assert.ThrowsAny<ArgumentException>(() => { stream.ReadAsync(new byte[1], 2, 0); });
+ Assert.ThrowsAny<ArgumentException>(() => { stream.ReadAsync(new byte[1], 2, 0); });
+ Assert.ThrowsAny<ArgumentException>(() => { stream.ReadAsync(new byte[1], 0, 2); });
+ Assert.ThrowsAny<ArgumentException>(() => { stream.ReadAsync(new byte[1], 0, 2); });
+ }
+
+ ownedMemory?.Dispose();
+ }
+
+ [Theory]
+ [InlineData(0, false)] // Read(byte[], ...)
+ [InlineData(1, false)] // Read(Span<byte>, ...)
+ [InlineData(2, false)] // ReadAsync(byte[], ...)
+ [InlineData(3, false)] // ReadAsync(Memory<byte>,...)
+ [InlineData(4, false)] // Begin/EndRead(byte[],...)
+ [InlineData(0, true)] // Read(byte[], ...)
+ [InlineData(1, true)] // Read(Span<byte>, ...)
+ [InlineData(2, true)] // ReadAsync(byte[], ...)
+ [InlineData(3, true)] // ReadAsync(Memory<byte>,...)
+ [InlineData(4, true)] // Begin/EndRead(byte[],...)
+ public async Task ReadAsStreamAsync_ReadMultipleBytes_MatchesInput(int mode, bool useArray)
+ {
+ const int ContentLength = 1024;
+
+ Memory<byte> memory;
+ OwnedMemory<byte> ownedMemory;
+ ReadOnlyMemoryContent content = CreateContent(ContentLength, useArray, out memory, out ownedMemory);
+
+ var buffer = new byte[3];
+
+ using (Stream stream = await content.ReadAsStreamAsync())
+ {
+ for (int i = 0; i < ContentLength; i += buffer.Length)
+ {
+ int bytesRead =
+ mode == 0 ? stream.Read(buffer, 0, buffer.Length) :
+ mode == 1 ? stream.Read(new Span<byte>(buffer)) :
+ mode == 2 ? await stream.ReadAsync(buffer, 0, buffer.Length) :
+ mode == 3 ? await stream.ReadAsync(new Memory<byte>(buffer)) :
+ await Task.Factory.FromAsync(stream.BeginRead, stream.EndRead, buffer, 0, buffer.Length, null);
+
+ Assert.Equal(Math.Min(buffer.Length, ContentLength - i), bytesRead);
+ for (int j = 0; j < bytesRead; j++)
+ {
+ Assert.Equal(memory.Span[i + j], buffer[j]);
+ }
+
+ Assert.Equal(i + bytesRead, stream.Position);
+ }
+
+ Assert.Equal(0,
+ mode == 0 ? stream.Read(buffer, 0, buffer.Length) :
+ mode == 1 ? stream.Read(new Span<byte>(buffer)) :
+ mode == 2 ? await stream.ReadAsync(buffer, 0, buffer.Length) :
+ mode == 3 ? await stream.ReadAsync(new Memory<byte>(buffer)) :
+ await Task.Factory.FromAsync(stream.BeginRead, stream.EndRead, buffer, 0, buffer.Length, null));
+ }
+
+ ownedMemory?.Dispose();
+ }
+
+ [Theory]
+ [MemberData(nameof(TrueFalse))]
+ public async Task ReadAsStreamAsync_ReadWithCancelableToken_MatchesInput(bool useArray)
+ {
+ const int ContentLength = 100;
+
+ Memory<byte> memory;
+ OwnedMemory<byte> ownedMemory;
+ ReadOnlyMemoryContent content = CreateContent(ContentLength, useArray, out memory, out ownedMemory);
+
+ var buffer = new byte[1];
+ var cts = new CancellationTokenSource();
+ int bytesRead;
+
+ using (Stream stream = await content.ReadAsStreamAsync())
+ {
+ for (int i = 0; i < ContentLength; i++)
+ {
+ switch (i % 2)
+ {
+ case 0:
+ bytesRead = await stream.ReadAsync(buffer, 0, 1, cts.Token);
+ break;
+ default:
+ bytesRead = await stream.ReadAsync(new Memory<byte>(buffer), cts.Token);
+ break;
+ }
+ Assert.Equal(1, bytesRead);
+ Assert.Equal(memory.Span[i], buffer[0]);
+ }
+ }
+
+ ownedMemory?.Dispose();
+ }
+
+ [Theory]
+ [MemberData(nameof(TrueFalse))]
+ public async Task ReadAsStreamAsync_ReadWithCanceledToken_MatchesInput(bool useArray)
+ {
+ const int ContentLength = 2;
+
+ Memory<byte> memory;
+ OwnedMemory<byte> ownedMemory;
+ ReadOnlyMemoryContent content = CreateContent(ContentLength, useArray, out memory, out ownedMemory);
+
+ using (Stream stream = await content.ReadAsStreamAsync())
+ {
+ await Assert.ThrowsAnyAsync<OperationCanceledException>(() => stream.ReadAsync(new byte[1], 0, 1, new CancellationToken(true)));
+ await Assert.ThrowsAnyAsync<OperationCanceledException>(async () => await stream.ReadAsync(new Memory<byte>(new byte[1]), new CancellationToken(true)));
+ await Assert.ThrowsAnyAsync<OperationCanceledException>(async () => await stream.CopyToAsync(new MemoryStream(), 1, new CancellationToken(true)));
+ }
+
+ ownedMemory?.Dispose();
+ }
+
+ [Theory]
+ [MemberData(nameof(ContentLengthsAndUseArrays))]
+ public async Task CopyToAsync_AllContentCopied(int contentLength, bool useArray)
+ {
+ Memory<byte> memory;
+ OwnedMemory<byte> ownedMemory;
+ ReadOnlyMemoryContent content = CreateContent(contentLength, useArray, out memory, out ownedMemory);
+
+ var destination = new MemoryStream();
+ await content.CopyToAsync(destination);
+
+ Assert.Equal<byte>(memory.ToArray(), destination.ToArray());
+
+ ownedMemory?.Dispose();
+ }
+
+ [Theory]
+ [MemberData(nameof(ContentLengthsAndUseArrays))]
+ public async Task ReadAsStreamAsync_CopyTo_AllContentCopied(int contentLength, bool useArray)
+ {
+ Memory<byte> memory;
+ OwnedMemory<byte> ownedMemory;
+ ReadOnlyMemoryContent content = CreateContent(contentLength, useArray, out memory, out ownedMemory);
+
+ var destination = new MemoryStream();
+ using (Stream s = await content.ReadAsStreamAsync())
+ {
+ s.CopyTo(destination);
+ }
+
+ Assert.Equal<byte>(memory.ToArray(), destination.ToArray());
+
+ ownedMemory?.Dispose();
+ }
+
+ [Theory]
+ [MemberData(nameof(TrueFalse))]
+ public async Task ReadAsStreamAsync_CopyTo_InvalidArguments(bool useArray)
+ {
+ const int ContentLength = 42;
+ Memory<byte> memory;
+ OwnedMemory<byte> ownedMemory;
+ ReadOnlyMemoryContent content = CreateContent(ContentLength, useArray, out memory, out ownedMemory);
+
+ using (Stream s = await content.ReadAsStreamAsync())
+ {
+ AssertExtensions.Throws<ArgumentNullException>("destination", () => s.CopyTo(null));
+ AssertExtensions.Throws<ArgumentNullException>("destination", () => { s.CopyToAsync(null); });
+
+ AssertExtensions.Throws<ArgumentOutOfRangeException>("bufferSize", () => s.CopyTo(new MemoryStream(), 0));
+ AssertExtensions.Throws<ArgumentOutOfRangeException>("bufferSize", () => { s.CopyToAsync(new MemoryStream(), 0); });
+
+ Assert.Throws<NotSupportedException>(() => s.CopyTo(new MemoryStream(new byte[1], writable:false)));
+ Assert.Throws<NotSupportedException>(() => { s.CopyToAsync(new MemoryStream(new byte[1], writable: false)); });
+
+ var disposedDestination = new MemoryStream();
+ disposedDestination.Dispose();
+ Assert.Throws<ObjectDisposedException>(() => s.CopyTo(disposedDestination));
+ Assert.Throws<ObjectDisposedException>(() => { s.CopyToAsync(disposedDestination); });
+ }
+
+ ownedMemory?.Dispose();
+ }
+
+ [Theory]
+ [MemberData(nameof(ContentLengthsAndUseArrays))]
+ public async Task ReadAsStreamAsync_CopyToAsync_AllContentCopied(int contentLength, bool useArray)
+ {
+ Memory<byte> memory;
+ OwnedMemory<byte> ownedMemory;
+ ReadOnlyMemoryContent content = CreateContent(contentLength, useArray, out memory, out ownedMemory);
+
+ var destination = new MemoryStream();
+ using (Stream s = await content.ReadAsStreamAsync())
+ {
+ await s.CopyToAsync(destination);
+ }
+
+ Assert.Equal<byte>(memory.ToArray(), destination.ToArray());
+
+ ownedMemory?.Dispose();
+ }
+
+ private static ReadOnlyMemoryContent CreateContent(int contentLength, bool useArray, out Memory<byte> memory, out OwnedMemory<byte> ownedMemory)
+ {
+ if (useArray)
+ {
+ memory = new byte[contentLength];
+ ownedMemory = null;
+ }
+ else
+ {
+ ownedMemory = new NativeOwnedMemory(contentLength);
+ memory = ownedMemory.Memory;
+ }
+
+ new Random(contentLength).NextBytes(memory.Span);
+
+ return new ReadOnlyMemoryContent(memory);
+ }
+ }
+}
diff --git a/src/System.Net.Http/tests/FunctionalTests/ResponseStreamTest.cs b/src/System.Net.Http/tests/FunctionalTests/ResponseStreamTest.cs
index 16b930d5ca..d067473b05 100644
--- a/src/System.Net.Http/tests/FunctionalTests/ResponseStreamTest.cs
+++ b/src/System.Net.Http/tests/FunctionalTests/ResponseStreamTest.cs
@@ -3,7 +3,6 @@
// See the LICENSE file in the project root for more information.
using System.IO;
-using System.Net.Sockets;
using System.Net.Test.Common;
using System.Text;
using System.Threading;
@@ -17,7 +16,7 @@ namespace System.Net.Http.Functional.Tests
using Configuration = System.Net.Test.Common.Configuration;
[SkipOnTargetFramework(TargetFrameworkMonikers.Uap, "dotnet/corefx #20010")]
- public class ResponseStreamTest
+ public class ResponseStreamTest : HttpClientTestBase
{
private readonly ITestOutputHelper _output;
@@ -36,7 +35,7 @@ namespace System.Net.Http.Functional.Tests
[InlineData(5)]
public async Task GetStreamAsync_ReadToEnd_Success(int readMode)
{
- using (var client = new HttpClient())
+ using (HttpClient client = CreateHttpClient())
{
string customHeaderValue = Guid.NewGuid().ToString("N");
client.DefaultRequestHeaders.Add("X-ResponseStreamTest", customHeaderValue);
@@ -111,7 +110,7 @@ namespace System.Net.Http.Functional.Tests
[Fact]
public async Task GetAsync_UseResponseHeadersReadAndCallLoadIntoBuffer_Success()
{
- using (var client = new HttpClient())
+ using (HttpClient client = CreateHttpClient())
using (HttpResponseMessage response = await client.GetAsync(Configuration.Http.RemoteEchoServer, HttpCompletionOption.ResponseHeadersRead))
{
await response.Content.LoadIntoBufferAsync();
@@ -130,7 +129,7 @@ namespace System.Net.Http.Functional.Tests
[Fact]
public async Task GetAsync_UseResponseHeadersReadAndCopyToMemoryStream_Success()
{
- using (var client = new HttpClient())
+ using (HttpClient client = CreateHttpClient())
using (HttpResponseMessage response = await client.GetAsync(Configuration.Http.RemoteEchoServer, HttpCompletionOption.ResponseHeadersRead))
{
var memoryStream = new MemoryStream();
@@ -154,7 +153,7 @@ namespace System.Net.Http.Functional.Tests
[Fact]
public async Task GetStreamAsync_ReadZeroBytes_Success()
{
- using (var client = new HttpClient())
+ using (HttpClient client = CreateHttpClient())
using (Stream stream = await client.GetStreamAsync(Configuration.Http.RemoteEchoServer))
{
Assert.Equal(0, stream.Read(new byte[1], 0, 0));
@@ -169,7 +168,7 @@ namespace System.Net.Http.Functional.Tests
{
var cts = new CancellationTokenSource();
- using (var client = new HttpClient())
+ using (HttpClient client = CreateHttpClient())
using (HttpResponseMessage response =
await client.GetAsync(Configuration.Http.RemoteEchoServer, HttpCompletionOption.ResponseHeadersRead))
using (Stream stream = await response.Content.ReadAsStreamAsync())
@@ -243,7 +242,7 @@ namespace System.Net.Http.Functional.Tests
private async Task ReadAsStreamHelper(IPEndPoint serverEndPoint)
{
- using (var client = new HttpClient())
+ using (HttpClient client = CreateHttpClient())
{
using (var response = await client.GetAsync(
new Uri($"http://{serverEndPoint.Address}:{(serverEndPoint).Port}/"),
diff --git a/src/System.Net.Http/tests/FunctionalTests/SchSendAuxRecordHttpTest.cs b/src/System.Net.Http/tests/FunctionalTests/SchSendAuxRecordHttpTest.cs
index 50de6a06ea..c02e2f1eb6 100644
--- a/src/System.Net.Http/tests/FunctionalTests/SchSendAuxRecordHttpTest.cs
+++ b/src/System.Net.Http/tests/FunctionalTests/SchSendAuxRecordHttpTest.cs
@@ -11,10 +11,8 @@ using Xunit.Abstractions;
namespace System.Net.Http.Functional.Tests
{
- using Configuration = System.Net.Test.Common.Configuration;
-
[SkipOnTargetFramework(TargetFrameworkMonikers.Uap, "dotnet/corefx #20010")]
- public class SchSendAuxRecordHttpTest
+ public class SchSendAuxRecordHttpTest : HttpClientTestBase
{
readonly ITestOutputHelper _output;
@@ -32,9 +30,10 @@ namespace System.Net.Http.Functional.Tests
options.AllowedProtocols = SslProtocols.Tls;
using (var server = new HttpsTestServer(options))
- using (var handler = new HttpClientHandler() { ServerCertificateCustomValidationCallback = LoopbackServer.AllowAllCertificates })
+ using (HttpClientHandler handler = CreateHttpClientHandler())
using (var client = new HttpClient(handler))
{
+ handler.ServerCertificateCustomValidationCallback = LoopbackServer.AllowAllCertificates;
server.Start();
var tasks = new Task[2];
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 59eabee735..ae66726b39 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
@@ -5,6 +5,7 @@
<ProjectGuid>{C85CF035-7804-41FF-9557-48B7C948B58D}</ProjectGuid>
<DefineConstants Condition="'$(TargetGroup)'=='netcoreapp'">$(DefineConstants);netcoreapp</DefineConstants>
<DefineConstants Condition="'$(TargetsWindows)'=='true'">$(DefineConstants);TargetsWindows</DefineConstants>
+ <AllowUnsafeBlocks>true</AllowUnsafeBlocks>
</PropertyGroup>
<PropertyGroup Condition="'$(Configuration)|$(Platform)' == 'netcoreapp-Unix-Debug|AnyCPU'" />
<PropertyGroup Condition="'$(Configuration)|$(Platform)' == 'netcoreapp-Unix-Release|AnyCPU'" />
@@ -17,6 +18,9 @@
<PropertyGroup Condition="'$(Configuration)|$(Platform)' == 'uap-Windows_NT-Debug|AnyCPU'" />
<PropertyGroup Condition="'$(Configuration)|$(Platform)' == 'uap-Windows_NT-Release|AnyCPU'" />
<ItemGroup>
+ <Compile Include="$(CommonTestPath)\System\Buffers\NativeOwnedMemory.cs">
+ <Link>Common\System\Buffers\NativeOwnedMemory.cs</Link>
+ </Compile>
<Compile Include="$(CommonTestPath)\System\Diagnostics\Tracing\TestEventListener.cs">
<Link>Common\System\Diagnostics\Tracing\TestEventListener.cs</Link>
</Compile>
@@ -78,6 +82,7 @@
<Compile Include="HttpClientHandlerTest.SslProtocols.Unix.cs" Condition="'$(TargetsUnix)' == 'true'" />
<Compile Include="HttpClientHandlerTest.SslProtocols.Windows.cs" Condition="'$(TargetsWindows)' == 'true'" />
<Compile Include="DiagnosticsTests.cs" />
+ <Compile Include="HttpClientTestBase.cs" />
<Compile Include="HttpClientTest.cs" />
<Compile Include="HttpClientEKUTest.cs" />
<Compile Include="HttpClientMiniStressTest.cs" />
@@ -98,14 +103,12 @@
<Compile Include="StringContentTest.cs" />
<Compile Include="SyncBlockingContent.cs" />
<Compile Include="TestHelper.cs" />
- <Compile Include="ManagedHandlerTestHelpers.cs" />
- </ItemGroup>
- <ItemGroup Condition=" '$(TargetsWindows)' == 'true' ">
<Compile Include="DefaultCredentialsTest.cs" />
</ItemGroup>
<ItemGroup Condition="'$(TargetGroup)' == 'netcoreapp'">
<Compile Include="ManagedHandlerTest.cs" />
<Compile Include="HttpClientHandlerTest.AcceptAllCerts.cs" />
+ <Compile Include="ReadOnlyMemoryContentTest.cs" />
</ItemGroup>
<ItemGroup Condition="'$(TargetGroup)' == 'netstandard'">
<Compile Include="$(CommonTestPath)\System\IO\StreamSpanExtensions.netstandard.cs">
@@ -128,5 +131,8 @@
<ItemGroup>
<SupplementalTestData Include="$(PackagesDir)system.net.testdata\1.0.0-prerelease\content\**\*.*" />
</ItemGroup>
+ <ItemGroup Condition="'$(TargetsOSX)'=='true'">
+ <TestCommandLines Include="ulimit -Sn 4096" />
+ </ItemGroup>
<Import Project="$([MSBuild]::GetDirectoryNameOfFileAbove($(MSBuildThisFileDirectory), dir.targets))\dir.targets" />
</Project> \ No newline at end of file
diff --git a/src/System.Net.NameResolution/src/System/Net/NameResolutionPal.Unix.cs b/src/System.Net.NameResolution/src/System/Net/NameResolutionPal.Unix.cs
index a943070b49..3e93367e76 100644
--- a/src/System.Net.NameResolution/src/System/Net/NameResolutionPal.Unix.cs
+++ b/src/System.Net.NameResolution/src/System/Net/NameResolutionPal.Unix.cs
@@ -141,6 +141,12 @@ namespace System.Net
public static unsafe IPHostEntry GetHostByName(string hostName)
{
+ if (hostName == "")
+ {
+ // To match documented behavior on Windows, if an empty string is passed in, use the local host's name.
+ hostName = Dns.GetHostName();
+ }
+
Interop.Sys.HostEntry entry;
int err = Interop.Sys.GetHostByName(hostName, &entry);
if (err != 0)
@@ -167,6 +173,12 @@ namespace System.Net
public static unsafe SocketError TryGetAddrInfo(string name, out IPHostEntry hostinfo, out int nativeErrorCode)
{
+ if (name == "")
+ {
+ // To match documented behavior on Windows, if an empty string is passed in, use the local host's name.
+ name = Dns.GetHostName();
+ }
+
Interop.Sys.HostEntry entry;
int result = Interop.Sys.GetHostEntryForName(name, &entry);
if (result != 0)
diff --git a/src/System.Net.NameResolution/tests/FunctionalTests/GetHostByNameTest.cs b/src/System.Net.NameResolution/tests/FunctionalTests/GetHostByNameTest.cs
index cbd4eacf3e..0ccdc17e82 100644
--- a/src/System.Net.NameResolution/tests/FunctionalTests/GetHostByNameTest.cs
+++ b/src/System.Net.NameResolution/tests/FunctionalTests/GetHostByNameTest.cs
@@ -101,5 +101,23 @@ namespace System.Net.NameResolution.Tests
Assert.Equal(1, entry.AddressList.Length);
Assert.Equal(IPAddress.IPv6Loopback, entry.AddressList[0]);
}
+
+ [Fact]
+ public void DnsObsoleteGetHostByName_EmptyString_ReturnsHostName()
+ {
+ IPHostEntry entry = Dns.GetHostByName("");
+
+ // DNS labels should be compared as case insensitive for ASCII characters. See RFC 4343.
+ Assert.Contains(Dns.GetHostName(), entry.HostName, StringComparison.OrdinalIgnoreCase);
+ }
+
+ [Fact]
+ public void DnsObsoleteBeginEndGetHostByName_EmptyString_ReturnsHostName()
+ {
+ IPHostEntry entry = Dns.EndGetHostByName(Dns.BeginGetHostByName("", null, null));
+
+ // DNS labels should be compared as case insensitive for ASCII characters. See RFC 4343.
+ Assert.Contains(Dns.GetHostName(), entry.HostName, StringComparison.OrdinalIgnoreCase);
+ }
}
}
diff --git a/src/System.Net.NameResolution/tests/FunctionalTests/GetHostEntryTest.cs b/src/System.Net.NameResolution/tests/FunctionalTests/GetHostEntryTest.cs
index 55de4e7fe1..e5b5174e43 100644
--- a/src/System.Net.NameResolution/tests/FunctionalTests/GetHostEntryTest.cs
+++ b/src/System.Net.NameResolution/tests/FunctionalTests/GetHostEntryTest.cs
@@ -20,10 +20,20 @@ namespace System.Net.NameResolution.Tests
TestGetHostEntryAsync(() => Dns.GetHostEntryAsync(localIPAddress));
}
- [Fact]
- public void Dns_GetHostEntryAsync_HostString_Ok()
+ [Theory]
+ [InlineData("")]
+ [InlineData(TestSettings.LocalHost)]
+ public void Dns_GetHostEntry_HostString_Ok(string hostName)
{
- TestGetHostEntryAsync(() => Dns.GetHostEntryAsync(TestSettings.LocalHost));
+ TestGetHostEntryAsync(() => Task.FromResult(Dns.GetHostEntry(hostName)));
+ }
+
+ [Theory]
+ [InlineData("")]
+ [InlineData(TestSettings.LocalHost)]
+ public void Dns_GetHostEntryAsync_HostString_Ok(string hostName)
+ {
+ TestGetHostEntryAsync(() => Dns.GetHostEntryAsync(hostName));
}
[Fact]
@@ -81,34 +91,6 @@ namespace System.Net.NameResolution.Tests
await Assert.ThrowsAsync<ArgumentException>(() => Dns.GetHostEntryAsync(addressString));
}
- public static IEnumerable<object[]> GetNoneAddresses()
- {
- yield return new object[] { IPAddress.None };
- }
-
- [PlatformSpecific(~TestPlatforms.OSX)] // macOS will resolve IPAddress.None to broadcasthost and produce a valid listing
- [Theory]
- [MemberData(nameof(GetNoneAddresses))]
- public async Task Dns_GetHostEntryAsync_NoneIPAddress_Fail(IPAddress address)
- {
- string addressString = address.ToString();
-
- await Assert.ThrowsAnyAsync<SocketException>(() => Dns.GetHostEntryAsync(address));
- await Assert.ThrowsAnyAsync<SocketException>(() => Dns.GetHostEntryAsync(addressString));
- }
-
- [PlatformSpecific(TestPlatforms.OSX)] // macOS will resolve IPAddress.None to broadcasthost and produce a valid listing
- [Theory]
- [MemberData(nameof(GetNoneAddresses))]
- public async Task Dns_GetHostEntryAsync_NoneIPAddress_Success(IPAddress address)
- {
- IPHostEntry result = await Dns.GetHostEntryAsync(address);
- Assert.NotNull(result);
- Assert.NotNull(result.AddressList);
- Assert.Equal(1, result.AddressList.Length);
- Assert.Equal(address, result.AddressList[0]);
- }
-
[Fact]
public void DnsBeginGetHostEntry_BadName_Throws()
{
diff --git a/src/System.Net.NameResolution/tests/PalTests/Fakes/DnsFake.cs b/src/System.Net.NameResolution/tests/PalTests/Fakes/DnsFake.cs
new file mode 100644
index 0000000000..e8ca1f7df9
--- /dev/null
+++ b/src/System.Net.NameResolution/tests/PalTests/Fakes/DnsFake.cs
@@ -0,0 +1,11 @@
+// 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
+{
+ internal static class Dns
+ {
+ public static string GetHostName() => string.Empty;
+ }
+}
diff --git a/src/System.Net.NameResolution/tests/PalTests/System.Net.NameResolution.Pal.Tests.csproj b/src/System.Net.NameResolution/tests/PalTests/System.Net.NameResolution.Pal.Tests.csproj
index cfb28bcee1..333aa11cc1 100644
--- a/src/System.Net.NameResolution/tests/PalTests/System.Net.NameResolution.Pal.Tests.csproj
+++ b/src/System.Net.NameResolution/tests/PalTests/System.Net.NameResolution.Pal.Tests.csproj
@@ -26,6 +26,7 @@
<ItemGroup>
<Compile Include="NameResolutionPalTests.cs" />
<Compile Include="Fakes\DebugThreadTracking.cs" />
+ <Compile Include="Fakes\DnsFake.cs" />
<Compile Include="Fakes\IPAddressFakeExtensions.cs" />
<Compile Include="$(CommonPath)\System\Net\Logging\NetEventSource.Common.cs">
<Link>Common\System\Net\Logging\NetEventSource.cs</Link>
@@ -170,4 +171,4 @@
</Compile>
</ItemGroup>
<Import Project="$([MSBuild]::GetDirectoryNameOfFileAbove($(MSBuildThisFileDirectory), dir.targets))\dir.targets" />
-</Project> \ No newline at end of file
+</Project>
diff --git a/src/System.Net.NetworkInformation/tests/FunctionalTests/FileUtil.cs b/src/System.Net.NetworkInformation/tests/FunctionalTests/FileUtil.cs
index faad68cd10..d51628e3a1 100644
--- a/src/System.Net.NetworkInformation/tests/FunctionalTests/FileUtil.cs
+++ b/src/System.Net.NetworkInformation/tests/FunctionalTests/FileUtil.cs
@@ -14,7 +14,7 @@ namespace System.Net.NetworkInformation.Tests
/// </summary>
public static void NormalizeLineEndings(string source, string normalizedDest)
{
- string contents = File.ReadAllText(TestFile(source));
+ string contents = File.ReadAllText(source);
if (Environment.NewLine == "\r\n")
{
if (!contents.Contains(Environment.NewLine))
@@ -32,14 +32,5 @@ namespace System.Net.NetworkInformation.Tests
File.WriteAllText(normalizedDest, contents);
}
-
- /// <summary>
- /// Gets a path to the desired test file
- /// </summary>
- /// <returns>The correct path to a valid test file</returns>
- public static string TestFile(string source)
- {
- return Path.Combine("NetworkFiles", source);
- }
}
}
diff --git a/src/System.Net.NetworkInformation/tests/FunctionalTests/MiscParsingTests.cs b/src/System.Net.NetworkInformation/tests/FunctionalTests/MiscParsingTests.cs
index 669af3f26d..54152936aa 100644
--- a/src/System.Net.NetworkInformation/tests/FunctionalTests/MiscParsingTests.cs
+++ b/src/System.Net.NetworkInformation/tests/FunctionalTests/MiscParsingTests.cs
@@ -30,27 +30,27 @@ namespace System.Net.NetworkInformation.Tests
[Fact]
public static void RawIntFileParsing()
{
- int val = StringParsingHelpers.ParseRawIntFile(FileUtil.TestFile("rawint"));
+ int val = StringParsingHelpers.ParseRawIntFile("rawint");
Assert.Equal(12, val);
- int max = StringParsingHelpers.ParseRawIntFile(FileUtil.TestFile("rawint_maxvalue"));
+ int max = StringParsingHelpers.ParseRawIntFile("rawint_maxvalue");
Assert.Equal(int.MaxValue, max);
}
[Fact]
public static void RawLongFileParsing()
{
- long val = StringParsingHelpers.ParseRawLongFile(FileUtil.TestFile("rawlong"));
+ long val = StringParsingHelpers.ParseRawLongFile("rawlong");
Assert.Equal(3147483647L, val);
- long max = StringParsingHelpers.ParseRawLongFile(FileUtil.TestFile("rawlong_maxvalue"));
+ long max = StringParsingHelpers.ParseRawLongFile("rawlong_maxvalue");
Assert.Equal(long.MaxValue, max);
}
[Fact]
public static void RawHexIntParsing()
{
- int val = StringParsingHelpers.ParseRawHexFileAsInt(FileUtil.TestFile("rawhexint"));
+ int val = StringParsingHelpers.ParseRawHexFileAsInt("rawhexint");
Assert.Equal(10, val);
}
}
diff --git a/src/System.Net.Ping/tests/FunctionalTests/PingTest.cs b/src/System.Net.Ping/tests/FunctionalTests/PingTest.cs
index 947e7a346e..c4a31ebe24 100644
--- a/src/System.Net.Ping/tests/FunctionalTests/PingTest.cs
+++ b/src/System.Net.Ping/tests/FunctionalTests/PingTest.cs
@@ -2,7 +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.Net.Sockets;
using System.Net.Test.Common;
+using System.Runtime.InteropServices;
using System.Threading;
using System.Threading.Tasks;
@@ -32,6 +34,19 @@ namespace System.Net.NetworkInformation.Tests
}
}
+ private static void PingResultValidator(PingReply pingReply, IPAddress localIpAddress)
+ {
+ if (pingReply.Status == IPStatus.TimedOut)
+ {
+ // Workaround OSX ping6 bug, refer issue #15018
+ Assert.Equal(AddressFamily.InterNetworkV6, localIpAddress.AddressFamily);
+ Assert.True(RuntimeInformation.IsOSPlatform(OSPlatform.OSX));
+ return;
+ }
+
+ Assert.Equal(IPStatus.Success, pingReply.Status);
+ Assert.True(pingReply.Address.Equals(localIpAddress));
+ }
[Fact]
public async Task SendPingAsync_InvalidArgs()
@@ -90,8 +105,7 @@ namespace System.Net.NetworkInformation.Tests
(ping) => ping.SendPingAsync(localIpAddress),
(pingReply) =>
{
- Assert.Equal(IPStatus.Success, pingReply.Status);
- Assert.True(pingReply.Address.Equals(localIpAddress));
+ PingResultValidator(pingReply, localIpAddress);
});
}
@@ -105,8 +119,7 @@ namespace System.Net.NetworkInformation.Tests
(ping) => ping.SendPingAsync(localIpAddress.ToString()),
(pingReply) =>
{
- Assert.Equal(IPStatus.Success, pingReply.Status);
- Assert.True(pingReply.Address.Equals(localIpAddress));
+ PingResultValidator(pingReply, localIpAddress);
});
}
@@ -120,8 +133,7 @@ namespace System.Net.NetworkInformation.Tests
(ping) => ping.SendPingAsync(localIpAddress, TestSettings.PingTimeout),
(pingReply) =>
{
- Assert.Equal(IPStatus.Success, pingReply.Status);
- Assert.True(pingReply.Address.Equals(localIpAddress));
+ PingResultValidator(pingReply, localIpAddress);
});
}
@@ -137,9 +149,7 @@ namespace System.Net.NetworkInformation.Tests
(ping) => ping.SendPingAsync(localIpAddress, TestSettings.PingTimeout, buffer),
(pingReply) =>
{
- Assert.Equal(IPStatus.Success, pingReply.Status);
- Assert.True(pingReply.Address.Equals(localIpAddress));
-
+ PingResultValidator(pingReply, localIpAddress);
Assert.Equal(buffer, pingReply.Buffer);
});
}
@@ -155,8 +165,7 @@ namespace System.Net.NetworkInformation.Tests
(ping) => ping.SendPingAsync(localIpAddress, TestSettings.PingTimeout, buffer),
(pingReply) =>
{
- Assert.Equal(IPStatus.Success, pingReply.Status);
- Assert.True(pingReply.Address.Equals(localIpAddress));
+ PingResultValidator(pingReply, localIpAddress);
// Non-root pings cannot send arbitrary data in the buffer, and do not receive it back in the PingReply.
if (Capability.CanUseRawSockets(localIpAddress.AddressFamily))
@@ -183,8 +192,7 @@ namespace System.Net.NetworkInformation.Tests
(ping) => ping.SendPingAsync(localIpAddress, TestSettings.PingTimeout, buffer, options),
(pingReply) =>
{
- Assert.Equal(IPStatus.Success, pingReply.Status);
- Assert.True(pingReply.Address.Equals(localIpAddress));
+ PingResultValidator(pingReply, localIpAddress);
Assert.Equal(buffer, pingReply.Buffer);
Assert.InRange(pingReply.RoundtripTime, 0, long.MaxValue);
});
@@ -201,8 +209,7 @@ namespace System.Net.NetworkInformation.Tests
(ping) => ping.SendPingAsync(localIpAddress, TestSettings.PingTimeout, buffer, new PingOptions()),
(pingReply) =>
{
- Assert.Equal(IPStatus.Success, pingReply.Status);
- Assert.True(pingReply.Address.Equals(localIpAddress));
+ PingResultValidator(pingReply, localIpAddress);
// Non-root pings cannot send arbitrary data in the buffer, and do not receive it back in the PingReply.
if (Capability.CanUseRawSockets(localIpAddress.AddressFamily))
@@ -226,8 +233,7 @@ namespace System.Net.NetworkInformation.Tests
(ping) => ping.SendPingAsync(TestSettings.LocalHost),
(pingReply) =>
{
- Assert.Equal(IPStatus.Success, pingReply.Status);
- Assert.True(pingReply.Address.Equals(localIpAddress));
+ PingResultValidator(pingReply, localIpAddress);
});
}
@@ -241,8 +247,7 @@ namespace System.Net.NetworkInformation.Tests
(ping) => ping.SendPingAsync(TestSettings.LocalHost, TestSettings.PingTimeout),
(pingReply) =>
{
- Assert.Equal(IPStatus.Success, pingReply.Status);
- Assert.True(pingReply.Address.Equals(localIpAddress));
+ PingResultValidator(pingReply, localIpAddress);
});
}
@@ -258,9 +263,7 @@ namespace System.Net.NetworkInformation.Tests
(ping) => ping.SendPingAsync(TestSettings.LocalHost, TestSettings.PingTimeout, buffer),
(pingReply) =>
{
- Assert.Equal(IPStatus.Success, pingReply.Status);
- Assert.True(pingReply.Address.Equals(localIpAddress));
-
+ PingResultValidator(pingReply, localIpAddress);
Assert.Equal(buffer, pingReply.Buffer);
});
}
@@ -276,8 +279,7 @@ namespace System.Net.NetworkInformation.Tests
(ping) => ping.SendPingAsync(TestSettings.LocalHost, TestSettings.PingTimeout, buffer),
(pingReply) =>
{
- Assert.Equal(IPStatus.Success, pingReply.Status);
- Assert.True(pingReply.Address.Equals(localIpAddress));
+ PingResultValidator(pingReply, localIpAddress);
// Non-root pings cannot send arbitrary data in the buffer, and do not receive it back in the PingReply.
if (Capability.CanUseRawSockets(localIpAddress.AddressFamily))
@@ -303,8 +305,7 @@ namespace System.Net.NetworkInformation.Tests
(ping) => ping.SendPingAsync(TestSettings.LocalHost, TestSettings.PingTimeout, buffer, new PingOptions()),
(pingReply) =>
{
- Assert.Equal(IPStatus.Success, pingReply.Status);
- Assert.True(pingReply.Address.Equals(localIpAddress));
+ PingResultValidator(pingReply, localIpAddress);
Assert.Equal(buffer, pingReply.Buffer);
});
@@ -321,8 +322,7 @@ namespace System.Net.NetworkInformation.Tests
(ping) => ping.SendPingAsync(TestSettings.LocalHost, TestSettings.PingTimeout, buffer, new PingOptions()),
(pingReply) =>
{
- Assert.Equal(IPStatus.Success, pingReply.Status);
- Assert.True(pingReply.Address.Equals(localIpAddress));
+ PingResultValidator(pingReply, localIpAddress);
// Non-root pings cannot send arbitrary data in the buffer, and do not receive it back in the PingReply.
if (Capability.CanUseRawSockets(localIpAddress.AddressFamily))
@@ -347,8 +347,7 @@ namespace System.Net.NetworkInformation.Tests
for (int i = 0; i < 3; i++)
{
PingReply pingReply = await p.SendPingAsync(TestSettings.LocalHost);
- Assert.Equal(IPStatus.Success, pingReply.Status);
- Assert.True(pingReply.Address.Equals(localIpAddress));
+ PingResultValidator(pingReply, localIpAddress);
}
}
}
@@ -364,8 +363,7 @@ namespace System.Net.NetworkInformation.Tests
for (int i = 0; i < 3; i++)
{
PingReply pingReply = p.Send(TestSettings.LocalHost);
- Assert.Equal(IPStatus.Success, pingReply.Status);
- Assert.True(pingReply.Address.Equals(localIpAddress));
+ PingResultValidator(pingReply, localIpAddress);
}
}
}
@@ -399,8 +397,7 @@ namespace System.Net.NetworkInformation.Tests
await tcs.Task;
Assert.NotNull(ea);
- Assert.Equal(IPStatus.Success, ea.Reply.Status);
- Assert.True(ea.Reply.Address.Equals(localIpAddress));
+ PingResultValidator(ea.Reply, localIpAddress);
}
// Several canceled iterations
diff --git a/src/System.Net.Ping/tests/FunctionalTests/UnixPingUtilityTests.cs b/src/System.Net.Ping/tests/FunctionalTests/UnixPingUtilityTests.cs
index 8346b9448c..62e9191af9 100644
--- a/src/System.Net.Ping/tests/FunctionalTests/UnixPingUtilityTests.cs
+++ b/src/System.Net.Ping/tests/FunctionalTests/UnixPingUtilityTests.cs
@@ -4,6 +4,7 @@
using System.Diagnostics;
using System.Net.Sockets;
+using System.Runtime.InteropServices;
using System.Threading.Tasks;
using Xunit;
@@ -22,7 +23,7 @@ namespace System.Net.NetworkInformation.Tests
[InlineData(1)]
[InlineData(50)]
[InlineData(1000)]
- [PlatformSpecific(TestPlatforms.AnyUnix)] // Tests un-priviledged Ping support on Unix
+ [PlatformSpecific(TestPlatforms.AnyUnix)] // Tests un-priviledged Ping support on Unix
public static async Task PacketSizeIsRespected(int payloadSize)
{
IPAddress localAddress = await TestSettings.GetLocalIPAddress();
@@ -39,6 +40,13 @@ namespace System.Net.NetworkInformation.Tests
string pingOutput = p.StandardOutput.ReadToEnd();
Assert.True(p.WaitForExit(TestSettings.PingTimeout), "Ping process did not exit in " + TestSettings.PingTimeout + " ms.");
+ if (p.ExitCode == 1 || p.ExitCode == 2)
+ {
+ // Workaround known OSX bug in ping6 utility.
+ Assert.Equal(utilityPath, UnixCommandLinePing.Ping6UtilityPath);
+ Assert.True(RuntimeInformation.IsOSPlatform(OSPlatform.OSX));
+ return;
+ }
try
{
diff --git a/src/System.Net.Primitives/src/System/Net/CookieContainer.cs b/src/System.Net.Primitives/src/System/Net/CookieContainer.cs
index ffd89b0467..32fa5f3951 100644
--- a/src/System.Net.Primitives/src/System/Net/CookieContainer.cs
+++ b/src/System.Net.Primitives/src/System/Net/CookieContainer.cs
@@ -225,7 +225,9 @@ namespace System.Net
if (cookie.Domain.Length == 0)
{
- throw new ArgumentException(SR.net_emptystringcall, "cookie.Domain");
+ throw new ArgumentException(
+ SR.Format(SR.net_emptystringcall, nameof(cookie) + "." + nameof(cookie.Domain)),
+ nameof(cookie) + "." + nameof(cookie.Domain));
}
Uri uri;
diff --git a/src/System.Net.Primitives/src/System/Net/IPAddress.cs b/src/System.Net.Primitives/src/System/Net/IPAddress.cs
index e82d8d458d..26d6af3286 100644
--- a/src/System.Net.Primitives/src/System/Net/IPAddress.cs
+++ b/src/System.Net.Primitives/src/System/Net/IPAddress.cs
@@ -398,8 +398,11 @@ namespace System.Net
#if BIGENDIAN
return host;
#else
- return (((long)HostToNetworkOrder(unchecked((int)host)) & 0xFFFFFFFF) << 32)
- | ((long)HostToNetworkOrder(unchecked((int)(host >> 32))) & 0xFFFFFFFF);
+ ulong value = (ulong)host;
+ value = (value << 32) | (value >> 32);
+ value = (value & 0x0000FFFF0000FFFF) << 16 | (value & 0xFFFF0000FFFF0000) >> 16;
+ value = (value & 0x00FF00FF00FF00FF) << 8 | (value & 0xFF00FF00FF00FF00) >> 8;
+ return (long)value;
#endif
}
@@ -408,8 +411,10 @@ namespace System.Net
#if BIGENDIAN
return host;
#else
- return (((int)HostToNetworkOrder(unchecked((short)host)) & 0xFFFF) << 16)
- | ((int)HostToNetworkOrder(unchecked((short)(host >> 16))) & 0xFFFF);
+ uint value = (uint)host;
+ value = (value << 16) | (value >> 16);
+ value = (value & 0x00FF00FF) << 8 | (value & 0xFF00FF00) >> 8;
+ return (int)value;
#endif
}
diff --git a/src/System.Net.Primitives/src/System/Net/IPv6AddressHelper.cs b/src/System.Net.Primitives/src/System/Net/IPv6AddressHelper.cs
index 0559c427ad..ae348c5267 100644
--- a/src/System.Net.Primitives/src/System/Net/IPv6AddressHelper.cs
+++ b/src/System.Net.Primitives/src/System/Net/IPv6AddressHelper.cs
@@ -242,9 +242,12 @@ namespace System
if (sequenceLength != 0)
{
+ if (sequenceLength > 4)
+ {
+ return false;
+ }
+
++sequenceCount;
- lastSequence = i - sequenceLength;
- sequenceLength = 0;
}
// these sequence counts are -1 because it is implied in end-of-sequence
@@ -252,7 +255,6 @@ namespace System
const int ExpectedSequenceCount = 8;
return
!expectingNumber &&
- (sequenceLength <= 4) &&
(haveCompressor ? (sequenceCount < ExpectedSequenceCount) : (sequenceCount == ExpectedSequenceCount)) &&
!needsClosingBracket;
}
diff --git a/src/System.Net.Primitives/tests/FunctionalTests/IPAddressParsing.cs b/src/System.Net.Primitives/tests/FunctionalTests/IPAddressParsing.cs
index 9408feaa38..a57aac898d 100644
--- a/src/System.Net.Primitives/tests/FunctionalTests/IPAddressParsing.cs
+++ b/src/System.Net.Primitives/tests/FunctionalTests/IPAddressParsing.cs
@@ -2,13 +2,32 @@
// 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.Net.Sockets;
using Xunit;
namespace System.Net.Primitives.Functional.Tests
{
+ public sealed class IPAddressParsing_String : IPAddressParsing
+ {
+ public override IPAddress Parse(string ipString) => IPAddress.Parse(ipString);
+ public override bool TryParse(string ipString, out IPAddress address) => IPAddress.TryParse(ipString, out address);
+
+ [Fact]
+ public void Parse_Null_Throws()
+ {
+ Assert.Throws<ArgumentNullException>(() => Parse((string)null));
+
+ Assert.False(TryParse((string)null, out IPAddress ipAddress));
+ Assert.Null(ipAddress);
+ }
+ }
+
public abstract class IPAddressParsing
{
+ public abstract IPAddress Parse(string ipString);
+ public abstract bool TryParse(string ipString, out IPAddress address);
+
public static readonly object[][] ValidIpv4Addresses =
{
// Decimal
@@ -60,22 +79,19 @@ namespace System.Net.Primitives.Functional.Tests
[MemberData(nameof(ValidIpv4Addresses))]
public void ParseIPv4_ValidAddress_Success(string address, string expected)
{
- IPAddress ip = IPAddress.Parse(address);
+ IPAddress ip = Parse(address);
// Validate the ToString of the parsed address matches the expected value
Assert.Equal(expected, ip.ToString());
Assert.Equal(AddressFamily.InterNetwork, ip.AddressFamily);
// Validate the ToString representation can be parsed as well back into the same IP
- IPAddress ip2 = IPAddress.Parse(ip.ToString());
+ IPAddress ip2 = Parse(ip.ToString());
Assert.Equal(ip, ip2);
}
public static readonly object[][] InvalidIpv4Addresses =
{
- new object[] { "" }, // empty
- new object[] { " " }, // whitespace
- new object[] { " " }, // whitespace
new object[] { " 127.0.0.1" }, // leading whitespace
new object[] { "127.0.0.1 " }, // trailing whitespace
new object[] { " 127.0.0.1 " }, // leading and trailing whitespace
@@ -84,7 +100,6 @@ namespace System.Net.Primitives.Functional.Tests
new object[] { "1.1.1.0x" }, // Empty trailing hex segment
new object[] { "0000X9D.0x3B.0X19.0x1B" }, // Leading zeros on hex
new object[] { "0x.1.1.1" }, // Empty leading hex segment
- new object[] { "0.0.0.089" }, // Octal (leading zero) but with 8 or 9
new object[] { "260.156" }, // Left dotted segments can't be more than 255
new object[] { "255.260.156" }, // Left dotted segments can't be more than 255
new object[] { "255.1.1.256" }, // Right dotted segment can't be more than 255
@@ -109,8 +124,17 @@ namespace System.Net.Primitives.Functional.Tests
new object[] { "12.1.abc.5" }, // text in section
};
+ public static readonly object[][] InvalidIpv4AddressesStandalone = // but valid as part of IPv6 addresses
+ {
+ new object[] { "" }, // empty
+ new object[] { " " }, // whitespace
+ new object[] { " " }, // whitespace
+ new object[] { "0.0.0.089" }, // Octal (leading zero) but with 8 or 9
+ };
+
[Theory]
[MemberData(nameof(InvalidIpv4Addresses))]
+ [MemberData(nameof(InvalidIpv4AddressesStandalone))]
public void ParseIPv4_InvalidAddress_Failure(string address)
{
ParseInvalidAddress(address, hasInnerSocketException: !PlatformDetection.IsFullFramework);
@@ -276,14 +300,14 @@ namespace System.Net.Primitives.Functional.Tests
[MemberData(nameof(ValidIpv6Addresses))]
public void ParseIPv6_ValidAddress_RoundtripMatchesExpected(string address, string expected)
{
- IPAddress ip = IPAddress.Parse(address);
+ IPAddress ip = Parse(address);
// Validate the ToString of the parsed address matches the expected value
Assert.Equal(expected.ToLowerInvariant(), ip.ToString());
Assert.Equal(AddressFamily.InterNetworkV6, ip.AddressFamily);
// Validate the ToString representation can be parsed as well back into the same IP
- IPAddress ip2 = IPAddress.Parse(ip.ToString());
+ IPAddress ip2 = Parse(ip.ToString());
Assert.Equal(ip, ip2);
// Validate that anything that doesn't already start with brackets
@@ -292,50 +316,94 @@ namespace System.Net.Primitives.Functional.Tests
{
Assert.Equal(
expected.ToLowerInvariant(),
- IPAddress.Parse("[" + address + "]").ToString());
+ Parse("[" + address + "]").ToString());
}
}
- public static readonly object[][] InvalidIpv6Addresses =
+ [Theory]
+ [MemberData(nameof(ValidIpv6Addresses))]
+ public void TryParseIPv6_ValidAddress_RoundtripMatchesExpected(string address, string expected)
{
- new object[] { ":::4df" },
- new object[] { "4df:::" },
- new object[] { "0:::4df" },
- new object[] { "4df:::0" },
- new object[] { "::4df:::" },
- new object[] { "0::4df:::" },
- new object[] { " ::1" },
- new object[] { ":: 1" },
- new object[] { ":" },
- new object[] { "0:0:0:0:0:0:0:0:0" },
- new object[] { "0:0:0:0:0:0:0" },
- new object[] { "0FFFF::" },
- new object[] { "FFFF0::" },
- new object[] { "[::1" },
- new object[] { "Fe08::/64" }, // with subnet
- new object[] { "[Fe08::1]:80Z" }, // brackets and invalid port
- new object[] { "[Fe08::1" }, // leading bracket
- new object[] { "[[Fe08::1" }, // two leading brackets
- new object[] { "Fe08::1]" }, // trailing bracket
- new object[] { "Fe08::1]]" }, // two trailing brackets
- new object[] { "[Fe08::1]]" }, // one leading and two trailing brackets
- new object[] { ":1" }, // leading single colon
- new object[] { "1:" }, // trailing single colon
- new object[] { " ::1" }, // leading whitespace
- new object[] { "::1 " }, // trailing whitespace
- new object[] { " ::1 " }, // leading and trailing whitespace
- new object[] { "1::1::1" }, // ambiguous failure
- new object[] { "1234::ABCD:1234::ABCD:1234:ABCD" }, // can only use :: once
- new object[] { "1:1\u67081:1:1" }, // invalid char
- new object[] { "FE08::260.168.0.1" }, // out of range
- new object[] { "::192.168.0.0x0" }, // hex failure
- new object[] { "G::" }, // invalid hex
- new object[] { "FFFFF::" }, // invalid value
- new object[] { ":%12" }, // colon scope
- new object[] { "::%1a" }, // alphanumeric scope
- new object[] { "[2001:0db8:85a3:08d3:1319:8a2e:0370:7344]:443/" }, // errneous ending slash after ignored port
- new object[] { "::1234%0x12" }, // invalid scope ID
- };
+ Assert.True(TryParse(address, out IPAddress ip));
+
+ // Validate the ToString of the parsed address matches the expected value
+ Assert.Equal(expected.ToLowerInvariant(), ip.ToString());
+ Assert.Equal(AddressFamily.InterNetworkV6, ip.AddressFamily);
+
+ // Validate the ToString representation can be parsed as well back into the same IP
+ Assert.True(TryParse(ip.ToString(), out IPAddress ip2));
+ Assert.Equal(ip, ip2);
+
+ // Validate that anything that doesn't already start with brackets
+ // can be surrounded with brackets and still parse successfully.
+ if (!address.StartsWith("["))
+ {
+ Assert.Equal(
+ expected.ToLowerInvariant(),
+ Parse("[" + address + "]").ToString());
+ }
+ }
+
+ public static IEnumerable<object[]> InvalidIpv6Addresses()
+ {
+ yield return new object[] { ":::4df" };
+ yield return new object[] { "4df:::" };
+ yield return new object[] { "0:::4df" };
+ yield return new object[] { "4df:::0" };
+ yield return new object[] { "::4df:::" };
+ yield return new object[] { "0::4df:::" };
+ yield return new object[] { " ::1" };
+ yield return new object[] { ":: 1" };
+ yield return new object[] { ":" };
+ yield return new object[] { "0:0:0:0:0:0:0:0:0" };
+ yield return new object[] { "0:0:0:0:0:0:0" };
+ yield return new object[] { "0FFFF::" };
+ yield return new object[] { "FFFF0::" };
+ yield return new object[] { "[::1" }; // missing closing bracket
+ yield return new object[] { "Fe08::/64" }; // with subnet
+ yield return new object[] { "[Fe08::1]:80Z" }; // brackets and invalid port
+ yield return new object[] { "[Fe08::1" }; // leading bracket
+ yield return new object[] { "[[Fe08::1" }; // two leading brackets
+ yield return new object[] { "Fe08::1]" }; // trailing bracket
+ yield return new object[] { "Fe08::1]]" }; // two trailing brackets
+ yield return new object[] { "[Fe08::1]]" }; // one leading and two trailing brackets
+ yield return new object[] { ":1" }; // leading single colon
+ yield return new object[] { "1:" }; // trailing single colon
+ yield return new object[] { " ::1" }; // leading whitespace
+ yield return new object[] { "::1 " }; // trailing whitespace
+ yield return new object[] { " ::1 " }; // leading and trailing whitespace
+ yield return new object[] { "1::1::1" }; // ambiguous failure
+ yield return new object[] { "1234::ABCD:1234::ABCD:1234:ABCD" }; // can only use :: once
+ yield return new object[] { "1:1\u67081:1:1" }; // invalid char
+ yield return new object[] { "FE08::260.168.0.1" }; // out of range
+ yield return new object[] { "::192.168.0.0x0" }; // hex failure
+ yield return new object[] { "G::" }; // invalid hex
+ yield return new object[] { "FFFFF::" }; // invalid value
+ yield return new object[] { ":%12" }; // colon scope
+ yield return new object[] { "::%1a" }; // alphanumeric scope
+ yield return new object[] { "[2001:0db8:85a3:08d3:1319:8a2e:0370:7344]:443/" }; // errneous ending slash after ignored port
+ yield return new object[] { "::1234%0x12" }; // invalid scope ID
+
+ yield return new object[] { "e3fff:ffff:ffff:ffff:ffff:ffff:ffff:abcd" }; // 1st number too long
+ yield return new object[] { "3fff:effff:ffff:ffff:ffff:ffff:ffff:abcd" }; // 2nd number too long
+ yield return new object[] { "3fff:ffff:effff:ffff:ffff:ffff:ffff:abcd" }; // 3rd number too long
+ yield return new object[] { "3fff:ffff:ffff:effff:ffff:ffff:ffff:abcd" }; // 4th number too long
+ yield return new object[] { "3fff:ffff:ffff:ffff:effff:ffff:ffff:abcd" }; // 5th number too long
+ yield return new object[] { "3fff:ffff:ffff:ffff:ffff:effff:ffff:abcd" }; // 6th number too long
+ yield return new object[] { "3fff:ffff:ffff:ffff:ffff:ffff:effff:abcd" }; // 7th number too long
+ yield return new object[] { "3fff:ffff:ffff:ffff:ffff:ffff:ffff:eabcd" }; // 8th number too long
+
+ // Various IPv6 addresses including invalid IPv4 addresses
+ foreach (object[] invalidIPv4AddressArray in InvalidIpv4Addresses)
+ {
+ string invalidIPv4Address = (string)invalidIPv4AddressArray[0];
+ yield return new object[] { "3fff:ffff:ffff:ffff:ffff:ffff:ffff:" + invalidIPv4Address };
+ yield return new object[] { "::" + invalidIPv4Address }; // SIIT
+ yield return new object[] { "::FF:" + invalidIPv4Address }; // SIIT
+ yield return new object[] { "::5EFE:" + invalidIPv4Address }; // ISATAP
+ yield return new object[] { "1::5EFE:" + invalidIPv4Address }; // ISATAP
+ }
+ }
[Theory]
[MemberData(nameof(InvalidIpv6Addresses))]
@@ -361,9 +429,9 @@ namespace System.Net.Primitives.Functional.Tests
ParseInvalidAddress(invalidAddress, hasInnerSocketException: !PlatformDetection.IsFullFramework);
}
- private static void ParseInvalidAddress(string invalidAddress, bool hasInnerSocketException)
+ private void ParseInvalidAddress(string invalidAddress, bool hasInnerSocketException)
{
- FormatException fe = Assert.Throws<FormatException>(() => IPAddress.Parse(invalidAddress));
+ FormatException fe = Assert.Throws<FormatException>(() => Parse(invalidAddress));
if (hasInnerSocketException)
{
SocketException se = Assert.IsType<SocketException>(fe.InnerException);
@@ -375,18 +443,8 @@ namespace System.Net.Primitives.Functional.Tests
}
IPAddress result = IPAddress.Loopback;
- Assert.False(IPAddress.TryParse(invalidAddress, out result));
+ Assert.False(TryParse(invalidAddress, out result));
Assert.Null(result);
}
-
- [Fact]
- public void Parse_Null_Throws()
- {
- Assert.Throws<ArgumentNullException>(() => { IPAddress.Parse((string)null); });
-
- IPAddress ipAddress;
- Assert.False(IPAddress.TryParse((string)null, out ipAddress));
- Assert.Null(ipAddress);
- }
}
}
diff --git a/src/System.Net.Primitives/tests/FunctionalTests/IPAddressParsingSpan.cs b/src/System.Net.Primitives/tests/FunctionalTests/IPAddressParsingSpan.cs
index b5e95ce589..b8f38d10d4 100644
--- a/src/System.Net.Primitives/tests/FunctionalTests/IPAddressParsingSpan.cs
+++ b/src/System.Net.Primitives/tests/FunctionalTests/IPAddressParsingSpan.cs
@@ -7,164 +7,42 @@ using Xunit;
namespace System.Net.Primitives.Functional.Tests
{
- public sealed class IPAddressParsingSpan : IPAddressParsing
+ public sealed class IPAddressParsing_Span : IPAddressParsing
{
- const int IPv4MaxLength = 15;
+ public override IPAddress Parse(string ipString) => IPAddress.Parse(ipString.AsReadOnlySpan());
+ public override bool TryParse(string ipString, out IPAddress address) => IPAddress.TryParse(ipString.AsReadOnlySpan(), out address);
- [Theory]
- [MemberData(nameof(ValidIpv4Addresses))]
- public void ParseIPv4Span_ValidAddress_Success(string address, string expected)
- {
- IPAddress ip = IPAddress.Parse(address.AsReadOnlySpan());
-
- // Validate the ToString of the parsed address matches the expected value
- Assert.Equal(expected, ip.ToString());
- Assert.Equal(AddressFamily.InterNetwork, ip.AddressFamily);
-
- // Validate the ToString representation can be parsed as well back into the same IP
- IPAddress ip2 = IPAddress.Parse(address.AsReadOnlySpan());
- Assert.Equal(ip, ip2);
- }
[Theory]
[MemberData(nameof(ValidIpv4Addresses))]
- public void TryParseIPv4Span_ValidAddress_Success(string address, string expected)
- {
- Assert.True(IPAddress.TryParse(address.AsReadOnlySpan(), out IPAddress ip));
-
- // Validate the ToString of the parsed address matches the expected value
- Assert.Equal(expected, ip.ToString());
- Assert.Equal(AddressFamily.InterNetwork, ip.AddressFamily);
-
- // Validate the ToString representation can be parsed as well back into the same IP
- Assert.True(IPAddress.TryParse(ip.ToString().AsReadOnlySpan(), out IPAddress ip2));
- Assert.Equal(ip, ip2);
- }
-
- [Theory]
- [MemberData(nameof(ValidIpv4Addresses))]
- public void TryFormatIPv4_ValidAddress_Success(string address, string expected)
- {
- const int IPv4MaxPlusOneLength = IPv4MaxLength + 1;
-
- var ip = IPAddress.Parse(address);
-
- var exactSize = new char[IPv4MaxLength];
- Assert.True(ip.TryFormat(new Span<char>(exactSize), out int charsWritten));
- Assert.Equal(expected.Length, charsWritten);
- Assert.Equal(expected, new string(exactSize, 0, charsWritten));
-
- var largerThanRequired = new char[IPv4MaxPlusOneLength];
- Assert.True(ip.TryFormat(new Span<char>(largerThanRequired), out charsWritten));
- Assert.Equal(expected.Length, charsWritten);
- Assert.Equal(expected, new string(largerThanRequired, 0, charsWritten));
- }
-
- [Theory]
- [MemberData(nameof(ValidIpv4Addresses))]
- public void TryFormatIPv4_ProvidedBufferTooSmall_Failure(string address, string expected)
- {
- const int bufferSize = IPv4MaxLength - 1;
- var ip = IPAddress.Parse(address);
-
- var result = new char[bufferSize];
- Assert.False(ip.TryFormat(new Span<char>(result), out int charsWritten));
- Assert.Equal(0, charsWritten);
- Assert.Equal<char>(new char[bufferSize], result);
- }
-
- [Theory]
- [MemberData(nameof(InvalidIpv4Addresses))]
- public void TryParseIPv4_InvalidAddress_Failure(string address)
- {
- Assert.False(IPAddress.TryParse(address.AsReadOnlySpan(), out IPAddress ip));
- Assert.Equal(null, ip);
- }
-
- [Theory]
- [MemberData(nameof(ValidIpv6Addresses))]
- public void ParseIPv6Span_ValidAddress_RoundtripMatchesExpected(string address, string expected)
- {
- IPAddress ip = IPAddress.Parse(address.AsReadOnlySpan());
-
- // Validate the ToString of the parsed address matches the expected value
- Assert.Equal(expected.ToLowerInvariant(), ip.ToString());
- Assert.Equal(AddressFamily.InterNetworkV6, ip.AddressFamily);
-
- // Validate the ToString representation can be parsed as well back into the same IP
- IPAddress ip2 = IPAddress.Parse(address.AsReadOnlySpan());
- Assert.Equal(ip, ip2);
-
- // Validate that anything that doesn't already start with brackets
- // can be surrounded with brackets and still parse successfully.
- if (!address.StartsWith("["))
- {
- Assert.Equal(
- expected.ToLowerInvariant(),
- IPAddress.Parse(("[" + address + "]").AsReadOnlySpan()).ToString());
- }
- }
-
- [Theory]
- [MemberData(nameof(ValidIpv6Addresses))]
- public void TryParseIPv6Span_ValidAddress_RoundtripMatchesExpected(string address, string expected)
- {
- Assert.True(IPAddress.TryParse(address.AsReadOnlySpan(), out IPAddress ip));
-
- // Validate the ToString of the parsed address matches the expected value
- Assert.Equal(expected.ToLowerInvariant(), ip.ToString());
- Assert.Equal(AddressFamily.InterNetworkV6, ip.AddressFamily);
-
- // Validate the ToString representation can be parsed as well back into the same IP
- Assert.True(IPAddress.TryParse(ip.ToString().AsReadOnlySpan(), out IPAddress ip2));
- Assert.Equal(ip, ip2);
-
- // Validate that anything that doesn't already start with brackets
- // can be surrounded with brackets and still parse successfully.
- if (!address.StartsWith("["))
- {
- Assert.True(IPAddress.TryParse(("[" + address + "]").AsReadOnlySpan(), out IPAddress ip3));
- Assert.Equal(expected.ToLowerInvariant(), ip3.ToString());
- }
- }
-
- [Theory]
[MemberData(nameof(ValidIpv6Addresses))]
- public void TryFormatIPv6_ValidAddress_Success(string address, string expected)
+ public void TryFormat_ProvidedBufferLargerThanNeeded_Success(string addressString, string expected)
{
- var ip = IPAddress.Parse(address);
+ IPAddress address = IPAddress.Parse(addressString);
- var exactSize = new char[expected.Length];
- Assert.True(ip.TryFormat(new Span<char>(exactSize), out int charsWritten));
- Assert.Equal(expected.Length, charsWritten);
- Assert.Equal(expected.ToLowerInvariant(), new string(exactSize, 0, charsWritten));
+ const int IPv4MaxLength = 15; // TryFormat currently requires at least this amount of space for IPv4 addresses
+ int requiredLength = address.AddressFamily == AddressFamily.InterNetwork ?
+ IPv4MaxLength :
+ address.ToString().Length;
- var largerThanRequired = new char[expected.Length + 1];
- Assert.True(ip.TryFormat(new Span<char>(largerThanRequired), out charsWritten));
+ var largerThanRequired = new char[requiredLength + 1];
+ Assert.True(address.TryFormat(new Span<char>(largerThanRequired), out int charsWritten));
Assert.Equal(expected.Length, charsWritten);
- Assert.Equal(expected.ToLowerInvariant(), new string(largerThanRequired, 0, charsWritten));
+ Assert.Equal(
+ address.AddressFamily == AddressFamily.InterNetworkV6 ? expected.ToLowerInvariant() : expected,
+ new string(largerThanRequired, 0, charsWritten));
}
[Theory]
+ [MemberData(nameof(ValidIpv4Addresses))]
[MemberData(nameof(ValidIpv6Addresses))]
- public void TryFormatIPv6_ProvidedBufferTooSmall_Failure(string address, string expected)
+ public void TryFormat_ProvidedBufferTooSmall_Failure(string addressString, string expected)
{
- int bufferSize = expected.Length - 1;
- var result = new char[bufferSize];
- var ip = IPAddress.Parse(address);
-
- Assert.False(ip.TryFormat(new Span<char>(result), out int charsWritten));
+ IPAddress address = IPAddress.Parse(addressString);
+ var result = new char[address.ToString().Length - 1];
+ Assert.False(address.TryFormat(new Span<char>(result), out int charsWritten));
Assert.Equal(0, charsWritten);
- Assert.Equal<char>(new char[bufferSize], result);
+ Assert.Equal<char>(new char[result.Length], result);
}
-
- [Theory]
- [MemberData(nameof(InvalidIpv6Addresses))]
- public void TryParseIPv6_InvalidAddress_ReturnsFalse(string invalidAddress)
- {
- Assert.False(IPAddress.TryParse(invalidAddress.AsReadOnlySpan(), out IPAddress ip));
- Assert.Equal(null, ip);
- }
-
}
}
diff --git a/src/System.Net.Primitives/tests/FunctionalTests/IPAddressTest.cs b/src/System.Net.Primitives/tests/FunctionalTests/IPAddressTest.cs
index 4c0d94deb4..1891db4ab0 100644
--- a/src/System.Net.Primitives/tests/FunctionalTests/IPAddressTest.cs
+++ b/src/System.Net.Primitives/tests/FunctionalTests/IPAddressTest.cs
@@ -142,19 +142,27 @@ namespace System.Net.Primitives.Functional.Tests
{
long l1 = (long)0x1350;
long l2 = (long)0x5013000000000000;
+ long l3 = (long)0x0123456789ABCDEF;
+ long l4 = unchecked((long)0xEFCDAB8967452301);
int i1 = (int)0x1350;
int i2 = (int)0x50130000;
-
+ int i3 = (int)0x01234567;
+ int i4 = (int)0x67452301;
+
short s1 = (short)0x1350;
short s2 = (short)0x5013;
-
+
Assert.Equal(l2, IPAddress.HostToNetworkOrder(l1));
+ Assert.Equal(l4, IPAddress.HostToNetworkOrder(l3));
Assert.Equal(i2, IPAddress.HostToNetworkOrder(i1));
+ Assert.Equal(i4, IPAddress.HostToNetworkOrder(i3));
Assert.Equal(s2, IPAddress.HostToNetworkOrder(s1));
Assert.Equal(l1, IPAddress.NetworkToHostOrder(l2));
+ Assert.Equal(l3, IPAddress.NetworkToHostOrder(l4));
Assert.Equal(i1, IPAddress.NetworkToHostOrder(i2));
+ Assert.Equal(i3, IPAddress.NetworkToHostOrder(i4));
Assert.Equal(s1, IPAddress.NetworkToHostOrder(s2));
}
diff --git a/src/System.Net.Requests/src/System/Net/CommandStream.cs b/src/System.Net.Requests/src/System/Net/CommandStream.cs
index fed8c32684..436378c722 100644
--- a/src/System.Net.Requests/src/System/Net/CommandStream.cs
+++ b/src/System.Net.Requests/src/System/Net/CommandStream.cs
@@ -179,7 +179,7 @@ namespace System.Net
/// Pipelined command resolution.
/// How this works:
- /// A list of commands that need to be sent to the FTP server are spliced together into a array,
+ /// A list of commands that need to be sent to the FTP server are spliced together into an array,
/// each command such STOR, PORT, etc, is sent to the server, then the response is parsed into a string,
/// with the response, the delegate is called, which returns an instruction (either continue, stop, or read additional
/// responses from server).
diff --git a/src/System.Net.Requests/tests/HttpWebRequestTest.cs b/src/System.Net.Requests/tests/HttpWebRequestTest.cs
index c049886d3b..3b89a2e089 100644
--- a/src/System.Net.Requests/tests/HttpWebRequestTest.cs
+++ b/src/System.Net.Requests/tests/HttpWebRequestTest.cs
@@ -279,6 +279,7 @@ namespace System.Net.Tests
Assert.Equal(int.MaxValue, request.Timeout);
}
+ [ActiveIssue(22627)]
[Fact]
public async Task Timeout_SetTenMillisecondsOnLoopback_ThrowsWebException()
{
diff --git a/src/System.Net.Security/src/System.Net.Security.csproj b/src/System.Net.Security/src/System.Net.Security.csproj
index 9b3d8def67..251d4bb13c 100644
--- a/src/System.Net.Security/src/System.Net.Security.csproj
+++ b/src/System.Net.Security/src/System.Net.Security.csproj
@@ -21,6 +21,7 @@
<Compile Include="System\Net\CertificateValidationPal.cs" />
<Compile Include="System\Net\FixedSizeReader.cs" />
<Compile Include="System\Net\HelperAsyncResults.cs" />
+ <Compile Include="System\Net\Security\SslStreamInternal.Adapters.cs" />
<Compile Include="System\Net\SslStreamContext.cs" />
<Compile Include="System\Net\Security\AuthenticatedStream.cs" />
<Compile Include="System\Net\Security\NetEventSource.Security.cs" />
@@ -162,6 +163,9 @@
<Compile Include="$(CommonPath)\Interop\Windows\SChannel\UnmanagedCertificateContext.cs">
<Link>Common\Interop\Windows\SChannel\UnmanagedCertificateContext.cs</Link>
</Compile>
+ <Compile Include="$(CommonPath)\Interop\Windows\SChannel\UnmanagedCertificateContext.IntPtr.cs">
+ <Link>Common\Interop\Windows\SChannel\UnmanagedCertificateContext.IntPtr.cs</Link>
+ </Compile>
<Compile Include="$(CommonPath)\Interop\Windows\sspicli\SecPkgContext_Bindings.cs">
<Link>Common\Interop\Windows\sspicli\SecPkgContext_Bindings.cs</Link>
</Compile>
diff --git a/src/System.Net.Security/src/System/Net/Security/SslConnectionInfo.Unix.cs b/src/System.Net.Security/src/System/Net/Security/SslConnectionInfo.Unix.cs
index 40f77b3b2d..f681f47f29 100644
--- a/src/System.Net.Security/src/System/Net/Security/SslConnectionInfo.Unix.cs
+++ b/src/System.Net.Security/src/System/Net/Security/SslConnectionInfo.Unix.cs
@@ -37,7 +37,7 @@ namespace System.Net.Security
DataKeySize = dataKeySize;
DataHashKeySize = dataHashKeySize;
- //Openssl does not provide a way to return a exchange key size.
+ //Openssl does not provide a way to return an exchange key size.
//It internally does calculate the key size before generating key to exchange
//It is not a constant (Algorthim specific) either that we can hardcode and return.
KeyExchKeySize = 0;
diff --git a/src/System.Net.Security/src/System/Net/Security/SslState.cs b/src/System.Net.Security/src/System/Net/Security/SslState.cs
index f44975c581..eb3e1e65b9 100644
--- a/src/System.Net.Security/src/System/Net/Security/SslState.cs
+++ b/src/System.Net.Security/src/System/Net/Security/SslState.cs
@@ -1279,10 +1279,31 @@ namespace System.Net.Security
}
}
- // Returns:
- // true - operation queued
- // false - operation can proceed
- internal bool CheckEnqueueWrite(AsyncProtocolRequest asyncRequest)
+ internal Task CheckEnqueueWriteAsync()
+ {
+ // Clear previous request.
+ int lockState = Interlocked.CompareExchange(ref _lockWriteState, LockWrite, LockNone);
+ if (lockState != LockHandshake)
+ {
+ return Task.CompletedTask;
+ }
+
+ lock (this)
+ {
+ if (_lockWriteState != LockHandshake)
+ {
+ CheckThrow(authSuccessCheck: true);
+ return Task.CompletedTask;
+ }
+
+ _lockWriteState = LockPendingWrite;
+ TaskCompletionSource<int> completionSource = new TaskCompletionSource<int>(TaskCreationOptions.RunContinuationsAsynchronously);
+ _queuedWriteStateRequest = completionSource;
+ return completionSource.Task;
+ }
+ }
+
+ internal void CheckEnqueueWrite()
{
// Clear previous request.
_queuedWriteStateRequest = null;
@@ -1290,7 +1311,7 @@ namespace System.Net.Security
if (lockState != LockHandshake)
{
// Proceed with write.
- return false;
+ return;
}
LazyAsyncResult lazyResult = null;
@@ -1299,27 +1320,20 @@ namespace System.Net.Security
if (_lockWriteState != LockHandshake)
{
// Handshake has completed before we grabbed the lock.
- CheckThrow(true);
- return false;
+ CheckThrow(authSuccessCheck: true);
+ return;
}
_lockWriteState = LockPendingWrite;
- // Still pending, wait or enqueue.
- if (asyncRequest != null)
- {
- _queuedWriteStateRequest = asyncRequest;
- return true;
- }
-
lazyResult = new LazyAsyncResult(null, null, /*must be */null);
_queuedWriteStateRequest = lazyResult;
}
// Need to exit from lock before waiting.
lazyResult.InternalWaitForCompletion();
- CheckThrow(true);
- return false;
+ CheckThrow(authSuccessCheck: true);
+ return;
}
internal void FinishWrite()
diff --git a/src/System.Net.Security/src/System/Net/Security/SslStreamInternal.Adapters.cs b/src/System.Net.Security/src/System/Net/Security/SslStreamInternal.Adapters.cs
new file mode 100644
index 0000000000..48f0c13c57
--- /dev/null
+++ b/src/System.Net.Security/src/System/Net/Security/SslStreamInternal.Adapters.cs
@@ -0,0 +1,53 @@
+// 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.Threading.Tasks;
+
+namespace System.Net.Security
+{
+ // This contains adapters to allow a single code path for sync/async logic
+ internal partial class SslStreamInternal
+ {
+ private interface ISslWriteAdapter
+ {
+ Task LockAsync();
+ Task WriteAsync(byte[] buffer, int offset, int count);
+ }
+
+ private struct SslWriteAsync : ISslWriteAdapter
+ {
+ private readonly SslState _sslState;
+ private readonly CancellationToken _cancellationToken;
+
+ public SslWriteAsync(SslState sslState, CancellationToken cancellationToken)
+ {
+ _sslState = sslState;
+ _cancellationToken = cancellationToken;
+ }
+
+ public Task LockAsync() => _sslState.CheckEnqueueWriteAsync();
+
+ public Task WriteAsync(byte[] buffer, int offset, int count) => _sslState.InnerStream.WriteAsync(buffer, offset, count, _cancellationToken);
+ }
+
+ private struct SslWriteSync : ISslWriteAdapter
+ {
+ private readonly SslState _sslState;
+
+ public SslWriteSync(SslState sslState) => _sslState = sslState;
+
+ public Task LockAsync()
+ {
+ _sslState.CheckEnqueueWrite();
+ return Task.CompletedTask;
+ }
+
+ public Task WriteAsync(byte[] buffer, int offset, int count)
+ {
+ _sslState.InnerStream.Write(buffer, offset, count);
+ return Task.CompletedTask;
+ }
+ }
+ }
+}
diff --git a/src/System.Net.Security/src/System/Net/Security/SslStreamInternal.cs b/src/System.Net.Security/src/System/Net/Security/SslStreamInternal.cs
index 06c91cb2a3..ba789ab33d 100644
--- a/src/System.Net.Security/src/System/Net/Security/SslStreamInternal.cs
+++ b/src/System.Net.Security/src/System/Net/Security/SslStreamInternal.cs
@@ -14,23 +14,19 @@ namespace System.Net.Security
//
// This is a wrapping stream that does data encryption/decryption based on a successfully authenticated SSPI context.
//
- internal class SslStreamInternal
+ internal partial class SslStreamInternal
{
- private static readonly AsyncCallback s_writeCallback = new AsyncCallback(WriteCallback);
- private static readonly AsyncProtocolCallback s_resumeAsyncWriteCallback = new AsyncProtocolCallback(ResumeAsyncWriteCallback);
private static readonly AsyncProtocolCallback s_resumeAsyncReadCallback = new AsyncProtocolCallback(ResumeAsyncReadCallback);
private static readonly AsyncProtocolCallback s_readHeaderCallback = new AsyncProtocolCallback(ReadHeaderCallback);
private static readonly AsyncProtocolCallback s_readFrameCallback = new AsyncProtocolCallback(ReadFrameCallback);
- private static readonly Action<Task, object> s_freeWriteBufferCallback = FreeWriteBuffer;
private const int FrameOverhead = 32;
private const int ReadBufferSize = 4096 * 4 + FrameOverhead; // We read in 16K chunks + headers.
- private SslState _sslState;
+ private readonly SslState _sslState;
private int _nestedWrite;
private int _nestedRead;
private AsyncProtocolRequest _readProtocolRequest; // cached, reusable AsyncProtocolRequest used for read operations
- private AsyncProtocolRequest _writeProtocolRequest; // cached, reusable AsyncProtocolRequest used for write operations
// Never updated directly, special properties are used. This is the read buffer.
private byte[] _internalBuffer;
@@ -49,12 +45,6 @@ namespace System.Net.Security
_decryptedBytesCount = 0;
}
- private static void FreeWriteBuffer(Task t, object buffer)
- {
- ArrayPool<byte>.Shared.Return((byte[])buffer);
- t.GetAwaiter().GetResult();
- }
-
//We will only free the read buffer if it
//actually contains no decrypted or encrypted bytes
private void ReturnReadBufferIfEmpty()
@@ -114,14 +104,14 @@ namespace System.Net.Security
return bytesRead == 1 ? oneByte[0] : -1;
}
- internal int Read(byte[] buffer, int offset, int count)
- {
- return ProcessRead(buffer, offset, count, null);
- }
+ internal int Read(byte[] buffer, int offset, int count) => ProcessRead(buffer, offset, count, null);
internal void Write(byte[] buffer, int offset, int count)
{
- ProcessWrite(buffer, offset, count, null);
+ ValidateParameters(buffer, offset, count);
+
+ SslWriteSync writeAdapter = new SslWriteSync(_sslState);
+ WriteAsyncInternal(writeAdapter, buffer, offset, count).GetAwaiter().GetResult();
}
internal IAsyncResult BeginRead(byte[] buffer, int offset, int count, AsyncCallback asyncCallback, object asyncState)
@@ -167,58 +157,36 @@ namespace System.Net.Security
internal IAsyncResult BeginWrite(byte[] buffer, int offset, int count, AsyncCallback asyncCallback, object asyncState)
{
- var lazyResult = new LazyAsyncResult(this, asyncState, asyncCallback);
- ProcessWrite(buffer, offset, count, lazyResult);
- return lazyResult;
+ return TaskToApm.Begin(WriteAsync(buffer, offset, count, CancellationToken.None), asyncCallback, asyncState);
}
- internal void EndWrite(IAsyncResult asyncResult)
- {
- if (asyncResult == null)
- {
- throw new ArgumentNullException(nameof(asyncResult));
- }
-
- LazyAsyncResult lazyResult = asyncResult as LazyAsyncResult;
- if (lazyResult == null)
- {
- throw new ArgumentException(SR.Format(SR.net_io_async_result, asyncResult.GetType().FullName), nameof(asyncResult));
- }
-
- if (Interlocked.Exchange(ref _nestedWrite, 0) == 0)
- {
- throw new InvalidOperationException(SR.Format(SR.net_io_invalidendcall, "EndWrite"));
- }
+ internal void EndWrite(IAsyncResult asyncResult) => TaskToApm.End(asyncResult);
- // No "artificial" timeouts implemented so far, InnerStream controls timeout.
- lazyResult.InternalWaitForCompletion();
-
- if (lazyResult.Result is Exception e)
- {
- if (e is IOException)
- {
- ExceptionDispatchInfo.Throw(e);
- }
+ internal Task WriteAsync(byte[] buffer, int offset, int count, CancellationToken cancellationToken)
+ {
+ ValidateParameters(buffer, offset, count);
- throw new IOException(SR.net_io_write, e);
- }
+ SslWriteAsync writeAdapter = new SslWriteAsync(_sslState, cancellationToken);
+ return WriteAsyncInternal(writeAdapter, buffer, offset, count);
}
- private void EnsureInternalBufferSize()
+ private void ResetReadBuffer()
{
+ Debug.Assert(_decryptedBytesCount == 0);
+ Debug.Assert(_internalBuffer == null || _internalBufferCount > 0);
+
if (_internalBuffer == null)
{
_internalBuffer = ArrayPool<byte>.Shared.Rent(ReadBufferSize);
}
- else if (_internalOffset > 0 && _internalBufferCount > 0)
+ else if (_internalOffset > 0)
{
// We have buffered data at a non-zero offset.
// To maximize the buffer space available for the next read,
// copy the existing data down to the beginning of the buffer.
Buffer.BlockCopy(_internalBuffer, _internalOffset, _internalBuffer, 0, _internalBufferCount);
+ _internalOffset = 0;
}
-
- _internalOffset = 0;
}
//
@@ -268,137 +236,124 @@ namespace System.Net.Security
return request;
}
- //
- // Sync write method.
- //
- private void ProcessWrite(byte[] buffer, int offset, int count, LazyAsyncResult asyncResult)
+ private Task WriteAsyncInternal<TWriteAdapter>(TWriteAdapter writeAdapter, byte[] buffer, int offset, int count)
+ where TWriteAdapter : struct, ISslWriteAdapter
{
_sslState.CheckThrow(authSuccessCheck: true, shutdownCheck: true);
- ValidateParameters(buffer, offset, count);
- if (Interlocked.Exchange(ref _nestedWrite, 1) == 1)
+ if (count == 0 && !SslStreamPal.CanEncryptEmptyMessage)
{
- throw new NotSupportedException(SR.Format(SR.net_io_invalidnestedcall, "Write", "write"));
+ // If it's an empty message and the PAL doesn't support that, we're done.
+ return Task.CompletedTask;
}
- // If this is an async operation, get the AsyncProtocolRequest to use.
- // We do this only after we verify we're the sole write operation in flight.
- AsyncProtocolRequest asyncRequest = GetOrCreateProtocolRequest(ref _writeProtocolRequest, asyncResult);
+ if (Interlocked.Exchange(ref _nestedWrite, 1) == 1)
+ {
+ throw new NotSupportedException(SR.Format(SR.net_io_invalidnestedcall, nameof(WriteAsync), "write"));
+ }
- bool failed = false;
+ Task t = count < _sslState.MaxDataSize ?
+ WriteSingleChunk(writeAdapter, buffer, offset, count) :
+ WriteAsyncChunked(writeAdapter, buffer, offset, count);
- try
+ if (t.IsCompletedSuccessfully)
{
- StartWriting(buffer, offset, count, asyncRequest);
+ _nestedWrite = 0;
+ return t;
}
- catch (Exception e)
- {
- _sslState.FinishWrite();
+ return ExitWriteAsync(t);
- failed = true;
- if (e is IOException)
+ async Task ExitWriteAsync(Task task)
+ {
+ try
{
- throw;
+ await task.ConfigureAwait(false);
}
+ catch (Exception e)
+ {
+ _sslState.FinishWrite();
- throw new IOException(SR.net_io_write, e);
- }
- finally
- {
- if (asyncRequest == null || failed)
+ if (e is IOException)
+ {
+ throw;
+ }
+
+ throw new IOException(SR.net_io_write, e);
+ }
+ finally
{
_nestedWrite = 0;
}
}
}
- private void StartWriting(byte[] buffer, int offset, int count, AsyncProtocolRequest asyncRequest)
+ private Task WriteSingleChunk<TWriteAdapter>(TWriteAdapter writeAdapter, byte[] buffer, int offset, int count)
+ where TWriteAdapter : struct, ISslWriteAdapter
{
- if (asyncRequest != null)
+ // Request a write IO slot.
+ Task ioSlot = writeAdapter.LockAsync();
+ if (!ioSlot.IsCompletedSuccessfully)
{
- asyncRequest.SetNextRequest(buffer, offset, count, s_resumeAsyncWriteCallback);
+ // Operation is async and has been queued, return.
+ return WaitForWriteIOSlot(writeAdapter, ioSlot, buffer, offset, count);
}
- // We loop to this method from the callback.
- // If the last chunk was just completed from async callback (count < 0), we complete user request.
- if (count >= 0)
- {
- do
- {
- if (count == 0 && !SslStreamPal.CanEncryptEmptyMessage)
- {
- // If it's an empty message and the PAL doesn't support that,
- // we're done.
- break;
- }
-
- // Request a write IO slot.
- if (_sslState.CheckEnqueueWrite(asyncRequest))
- {
- // Operation is async and has been queued, return.
- return;
- }
+ byte[] rentedBuffer = ArrayPool<byte>.Shared.Rent(count + FrameOverhead);
+ byte[] outBuffer = rentedBuffer;
- int chunkBytes = Math.Min(count, _sslState.MaxDataSize);
- byte[] rentedBuffer = ArrayPool<byte>.Shared.Rent(chunkBytes + FrameOverhead);
- byte[] outBuffer = rentedBuffer;
- int encryptedBytes = 0;
+ SecurityStatusPal status = _sslState.EncryptData(buffer, offset, count, ref outBuffer, out int encryptedBytes);
- SecurityStatusPal status = _sslState.EncryptData(buffer, offset, chunkBytes, ref outBuffer, out encryptedBytes);
- if (status.ErrorCode != SecurityStatusPalErrorCode.OK)
- {
- // Re-handshake status is not supported.
- ProtocolToken message = new ProtocolToken(null, status);
- ArrayPool<byte>.Shared.Return(rentedBuffer);
- throw new IOException(SR.net_io_encrypt, message.GetException());
- }
+ if (status.ErrorCode != SecurityStatusPalErrorCode.OK)
+ {
+ // Re-handshake status is not supported.
+ ArrayPool<byte>.Shared.Return(rentedBuffer);
+ ProtocolToken message = new ProtocolToken(null, status);
+ return Task.FromException(new IOException(SR.net_io_encrypt, message.GetException()));
+ }
- if (asyncRequest != null)
- {
- // Prepare for the next request.
- asyncRequest.SetNextRequest(buffer, offset + chunkBytes, count - chunkBytes, s_resumeAsyncWriteCallback);
- Task t = _sslState.InnerStream.WriteAsync(outBuffer, 0, encryptedBytes);
- if (t.IsCompleted)
- {
- ArrayPool<byte>.Shared.Return(rentedBuffer);
- t.GetAwaiter().GetResult();
- }
- else
- {
- t = t.ContinueWith(s_freeWriteBufferCallback, rentedBuffer, CancellationToken.None, TaskContinuationOptions.ExecuteSynchronously, TaskScheduler.Default);
- IAsyncResult ar = TaskToApm.Begin(t, s_writeCallback, asyncRequest);
- if (!ar.CompletedSynchronously)
- {
- return;
- }
- TaskToApm.End(ar);
- }
- }
- else
- {
- try
- {
- _sslState.InnerStream.Write(outBuffer, 0, encryptedBytes);
- }
- finally
- {
- ArrayPool<byte>.Shared.Return(rentedBuffer);
- }
- }
+ Task t = writeAdapter.WriteAsync(outBuffer, 0, encryptedBytes);
+ if (t.IsCompletedSuccessfully)
+ {
+ ArrayPool<byte>.Shared.Return(rentedBuffer);
+ _sslState.FinishWrite();
+ return t;
+ }
+ else
+ {
+ return CompleteAsync(t, rentedBuffer);
+ }
- offset += chunkBytes;
- count -= chunkBytes;
+ async Task WaitForWriteIOSlot(TWriteAdapter wAdapter, Task lockTask, byte[] buff, int off, int c)
+ {
+ await lockTask.ConfigureAwait(false);
+ await WriteSingleChunk(wAdapter, buff, off, c).ConfigureAwait(false);
+ }
- // Release write IO slot.
+ async Task CompleteAsync(Task writeTask, byte[] bufferToReturn)
+ {
+ try
+ {
+ await writeTask.ConfigureAwait(false);
+ }
+ finally
+ {
+ ArrayPool<byte>.Shared.Return(bufferToReturn);
_sslState.FinishWrite();
-
- } while (count != 0);
+ }
}
+ }
- if (asyncRequest != null)
+ private async Task WriteAsyncChunked<TWriteAdapter>(TWriteAdapter writeAdapter, byte[] buffer, int offset, int count)
+ where TWriteAdapter : struct, ISslWriteAdapter
+ {
+ do
{
- asyncRequest.CompleteUser();
- }
+ int chunkBytes = Math.Min(count, _sslState.MaxDataSize);
+ await WriteSingleChunk(writeAdapter, buffer, offset, chunkBytes).ConfigureAwait(false);
+ offset += chunkBytes;
+ count -= chunkBytes;
+
+ } while (count != 0);
}
// Fill the buffer up to the minimum specified size (or more, if possible).
@@ -512,8 +467,6 @@ namespace System.Net.Security
return minSize;
}
- EnsureInternalBufferSize();
-
int bytesRead;
if (asyncRequest != null)
{
@@ -543,11 +496,7 @@ namespace System.Net.Security
_internalOffset += byteCount;
_internalBufferCount -= byteCount;
- if (_internalBufferCount == 0)
- {
- // No remaining buffered bytes, so reset the offset to the beginning for the next read.
- _internalOffset = 0;
- }
+ ReturnReadBufferIfEmpty();
}
private int CopyDecryptedData(byte[] buffer, int offset, int count)
@@ -660,6 +609,7 @@ namespace System.Net.Security
private int StartFrameHeader(byte[] buffer, int offset, int count, AsyncProtocolRequest asyncRequest)
{
+ ResetReadBuffer();
int readBytes = EnsureBufferedBytes(SecureChannel.ReadHeaderSize, asyncRequest, s_readHeaderCallback);
if (readBytes == -1)
{
@@ -774,48 +724,6 @@ namespace System.Net.Security
throw new IOException(SR.net_io_decrypt, message.GetException());
}
- private static void WriteCallback(IAsyncResult transportResult)
- {
- if (transportResult.CompletedSynchronously)
- {
- return;
- }
-
- if (!(transportResult.AsyncState is AsyncProtocolRequest))
- {
- NetEventSource.Fail(transportResult, "State type is wrong, expected AsyncProtocolRequest.");
- }
-
- AsyncProtocolRequest asyncRequest = (AsyncProtocolRequest)transportResult.AsyncState;
-
- var sslStream = (SslStreamInternal)asyncRequest.AsyncObject;
-
- try
- {
- TaskToApm.End(transportResult);
- sslStream._sslState.FinishWrite();
-
- if (asyncRequest.Count == 0)
- {
- // This was the last chunk.
- asyncRequest.Count = -1;
- }
-
- sslStream.StartWriting(asyncRequest.Buffer, asyncRequest.Offset, asyncRequest.Count, asyncRequest);
- }
- catch (Exception e)
- {
- if (asyncRequest.IsUserCompleted)
- {
- // This will throw on a worker thread.
- throw;
- }
-
- sslStream._sslState.FinishWrite();
- asyncRequest.CompleteUserWithError(e);
- }
- }
-
//
// This is used in a rare situation when async Read is resumed from completed handshake.
//
@@ -838,28 +746,6 @@ namespace System.Net.Security
}
}
- //
- // This is used in a rare situation when async Write is resumed from completed handshake.
- //
- private static void ResumeAsyncWriteCallback(AsyncProtocolRequest asyncRequest)
- {
- try
- {
- ((SslStreamInternal)asyncRequest.AsyncObject).StartWriting(asyncRequest.Buffer, asyncRequest.Offset, asyncRequest.Count, asyncRequest);
- }
- catch (Exception e)
- {
- if (asyncRequest.IsUserCompleted)
- {
- // This will throw on a worker thread.
- throw;
- }
-
- ((SslStreamInternal)asyncRequest.AsyncObject)._sslState.FinishWrite();
- asyncRequest.CompleteUserWithError(e);
- }
- }
-
private static void ReadHeaderCallback(AsyncProtocolRequest asyncRequest)
{
try
diff --git a/src/System.Net.Security/tests/FunctionalTests/NegotiateStreamTestForUnix.cs b/src/System.Net.Security/tests/FunctionalTests/NegotiateStreamTestForUnix.cs
index 531e791233..8522a20c56 100644
--- a/src/System.Net.Security/tests/FunctionalTests/NegotiateStreamTestForUnix.cs
+++ b/src/System.Net.Security/tests/FunctionalTests/NegotiateStreamTestForUnix.cs
@@ -3,6 +3,7 @@
// See the LICENSE file in the project root for more information.
using System.Collections.Generic;
+using System.ComponentModel;
using System.Diagnostics;
using System.IO;
using System.Linq;
@@ -72,15 +73,31 @@ namespace System.Net.Security.Tests
}
// Clear the credentials
- var startInfo = new ProcessStartInfo(KDestroyCmd);
- startInfo.UseShellExecute = true;
- startInfo.CreateNoWindow = true;
- startInfo.Arguments = "-A";
- using (Process clearCreds = Process.Start(startInfo))
- {
- clearCreds.WaitForExit();
- output.WriteLine("kdestroy returned {0}", clearCreds.ExitCode);
- return (clearCreds.ExitCode == 0);
+ try
+ {
+ var startInfo = new ProcessStartInfo(KDestroyCmd);
+ startInfo.UseShellExecute = true;
+ startInfo.CreateNoWindow = true;
+ startInfo.Arguments = "-A";
+ using (Process clearCreds = Process.Start(startInfo))
+ {
+ clearCreds.WaitForExit();
+ output.WriteLine("kdestroy returned {0}", clearCreds.ExitCode);
+ return (clearCreds.ExitCode == 0);
+ }
+ }
+ catch (Win32Exception)
+ {
+ // https://github.com/dotnet/corefx/issues/24000
+ // on these distros right now
+ Assert.True(PlatformDetection.IsUbuntu1704 ||
+ PlatformDetection.IsUbuntu1710 ||
+ PlatformDetection.IsOpenSUSE ||
+ PlatformDetection.IsFedora ||
+ PlatformDetection.IsDebian ||
+ PlatformDetection.IsCentos7);
+
+ return false;
}
}
diff --git a/src/System.Net.Sockets/src/System/Net/Sockets/Socket.cs b/src/System.Net.Sockets/src/System/Net/Sockets/Socket.cs
index 1fa073a5c5..b7edd69b9b 100644
--- a/src/System.Net.Sockets/src/System/Net/Sockets/Socket.cs
+++ b/src/System.Net.Sockets/src/System/Net/Sockets/Socket.cs
@@ -3685,7 +3685,7 @@ namespace System.Net.Sockets
// Routine Description:
//
- // BeginAccept - Does a async winsock accept, creating a new socket on success
+ // BeginAccept - Does an async winsock accept, creating a new socket on success
//
// Works by creating a pending accept request the first time,
// and subsequent calls are queued so that when the first accept completes,
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 f5944adf19..0c44554357 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
@@ -253,8 +253,8 @@ namespace System.Net.Sockets
}
if (available == 0)
{
- // Always request at least one byte.
- available = 1;
+ // Don't truncate iovecs.
+ available = int.MaxValue;
}
// Pin buffers and set up iovecs.
@@ -714,6 +714,7 @@ namespace System.Net.Sockets
public static bool TryCompleteSendTo(SafeCloseSocket socket, ReadOnlySpan<byte> buffer, IList<ArraySegment<byte>> buffers, ref int bufferIndex, ref int offset, ref int count, SocketFlags flags, byte[] socketAddress, int socketAddressLen, ref int bytesSent, out SocketError errorCode)
{
+ bool successfulSend = false;
for (;;)
{
int sent;
@@ -733,16 +734,17 @@ namespace System.Net.Sockets
if (sent == -1)
{
- if (errno != Interop.Error.EAGAIN && errno != Interop.Error.EWOULDBLOCK)
+ if (!successfulSend && errno != Interop.Error.EAGAIN && errno != Interop.Error.EWOULDBLOCK)
{
errorCode = GetSocketErrorForErrorCode(errno);
return true;
}
- errorCode = SocketError.Success;
+ errorCode = successfulSend ? SocketError.Success : SocketError.WouldBlock;
return false;
}
+ successfulSend = true;
bytesSent += sent;
bool isComplete = sent == 0 ||
@@ -890,8 +892,8 @@ namespace System.Net.Sockets
int bufferIndex = 0;
int offset = 0;
SocketError errorCode;
- bool completed = TryCompleteSendTo(handle, bufferList, ref bufferIndex, ref offset, socketFlags, null, 0, ref bytesTransferred, out errorCode);
- return completed ? errorCode : SocketError.WouldBlock;
+ TryCompleteSendTo(handle, bufferList, ref bufferIndex, ref offset, socketFlags, null, 0, ref bytesTransferred, out errorCode);
+ return errorCode;
}
public static SocketError Send(SafeCloseSocket handle, byte[] buffer, int offset, int count, SocketFlags socketFlags, out int bytesTransferred)
@@ -903,8 +905,8 @@ namespace System.Net.Sockets
bytesTransferred = 0;
SocketError errorCode;
- bool completed = TryCompleteSendTo(handle, buffer, ref offset, ref count, socketFlags, null, 0, ref bytesTransferred, out errorCode);
- return completed ? errorCode : SocketError.WouldBlock;
+ TryCompleteSendTo(handle, buffer, ref offset, ref count, socketFlags, null, 0, ref bytesTransferred, out errorCode);
+ return errorCode;
}
public static SocketError Send(SafeCloseSocket handle, ReadOnlySpan<byte> buffer, SocketFlags socketFlags, out int bytesTransferred)
@@ -916,8 +918,8 @@ namespace System.Net.Sockets
bytesTransferred = 0;
SocketError errorCode;
- bool completed = TryCompleteSendTo(handle, buffer, socketFlags, null, 0, ref bytesTransferred, out errorCode);
- return completed ? errorCode : SocketError.WouldBlock;
+ TryCompleteSendTo(handle, buffer, socketFlags, null, 0, ref bytesTransferred, out errorCode);
+ return errorCode;
}
public static SocketError SendFile(SafeCloseSocket handle, FileStream fileStream)
@@ -948,8 +950,8 @@ namespace System.Net.Sockets
bytesTransferred = 0;
SocketError errorCode;
- bool completed = TryCompleteSendTo(handle, buffer, ref offset, ref count, socketFlags, socketAddress, socketAddressLen, ref bytesTransferred, out errorCode);
- return completed ? errorCode : SocketError.WouldBlock;
+ TryCompleteSendTo(handle, buffer, ref offset, ref count, socketFlags, socketAddress, socketAddressLen, ref bytesTransferred, out errorCode);
+ return errorCode;
}
public static SocketError Receive(SafeCloseSocket handle, IList<ArraySegment<byte>> buffers, ref SocketFlags socketFlags, out int bytesTransferred)
diff --git a/src/System.Net.Sockets/tests/FunctionalTests/Accept.cs b/src/System.Net.Sockets/tests/FunctionalTests/Accept.cs
index c558af1fbf..270b35599b 100644
--- a/src/System.Net.Sockets/tests/FunctionalTests/Accept.cs
+++ b/src/System.Net.Sockets/tests/FunctionalTests/Accept.cs
@@ -176,6 +176,7 @@ namespace System.Net.Sockets.Tests
}
}
+ [ActiveIssue(22808, TargetFrameworkMonikers.NetFramework)]
[ActiveIssue(17209, TestPlatforms.AnyUnix)]
[OuterLoop] // TODO: Issue #11345
[Theory]
diff --git a/src/System.Net.Sockets/tests/FunctionalTests/DualModeSocketTest.cs b/src/System.Net.Sockets/tests/FunctionalTests/DualModeSocketTest.cs
index 0cdb3fe03f..fba1acd298 100644
--- a/src/System.Net.Sockets/tests/FunctionalTests/DualModeSocketTest.cs
+++ b/src/System.Net.Sockets/tests/FunctionalTests/DualModeSocketTest.cs
@@ -1056,6 +1056,7 @@ namespace System.Net.Sockets.Tests
}
}
+ [OuterLoop] // https://github.com/dotnet/corefx/issues/17681
[Trait("IPv4", "true")]
[Trait("IPv6", "true")]
public class DualModeConnectionlessSendTo : DualModeBase
@@ -1156,6 +1157,7 @@ namespace System.Net.Sockets.Tests
#endregion SendTo Sync
}
+ [OuterLoop] // https://github.com/dotnet/corefx/issues/17681
[Trait("IPv4", "true")]
[Trait("IPv6", "true")]
public class DualModeConnectionlessBeginSendTo : DualModeBase
@@ -1257,6 +1259,7 @@ namespace System.Net.Sockets.Tests
#endregion SendTo Begin/End
}
+ [OuterLoop] // https://github.com/dotnet/corefx/issues/17681
[Trait("IPv4", "true")]
[Trait("IPv6", "true")]
public class DualModeConnectionlessSendToAsync : DualModeBase
@@ -1395,6 +1398,7 @@ namespace System.Net.Sockets.Tests
#endregion SendTo Async/Event
}
+ [OuterLoop] // https://github.com/dotnet/corefx/issues/17681
[Trait("IPv4", "true")]
[Trait("IPv6", "true")]
public class DualModeConnectionlessReceiveFrom : DualModeBase
@@ -1525,6 +1529,7 @@ namespace System.Net.Sockets.Tests
}
}
+ [OuterLoop] // https://github.com/dotnet/corefx/issues/17681
[Trait("IPv4", "true")]
[Trait("IPv6", "true")]
public class DualModeConnectionlessBeginReceiveFrom : DualModeBase
@@ -1673,6 +1678,7 @@ namespace System.Net.Sockets.Tests
#endregion ReceiveFrom Begin/End
}
+ [OuterLoop] // https://github.com/dotnet/corefx/issues/17681
[Trait("IPv4", "true")]
[Trait("IPv6", "true")]
public class DualModeConnectionlessReceiveFromAsync : DualModeBase
@@ -1835,6 +1841,7 @@ namespace System.Net.Sockets.Tests
}
}
+ [OuterLoop] // https://github.com/dotnet/corefx/issues/17681
[Trait("IPv4", "true")]
[Trait("IPv6", "true")]
public class DualModeConnectionlessReceiveMessageFrom : DualModeBase
diff --git a/src/System.Net.Sockets/tests/FunctionalTests/SendReceive.cs b/src/System.Net.Sockets/tests/FunctionalTests/SendReceive.cs
index 1bb887ce0e..fa4274f14d 100644
--- a/src/System.Net.Sockets/tests/FunctionalTests/SendReceive.cs
+++ b/src/System.Net.Sockets/tests/FunctionalTests/SendReceive.cs
@@ -835,6 +835,207 @@ namespace System.Net.Sockets.Tests
}
}
+ public class SendReceive
+ {
+ [Fact]
+ public void SendRecvIovMaxTcp_Success()
+ {
+ // sending/receiving more than IOV_MAX segments causes EMSGSIZE on some platforms.
+ // This is handled internally for stream sockets so this error shouldn't surface.
+
+ // Use more than IOV_MAX (1024 on Linux & macOS) segments.
+ const int SegmentCount = 2400;
+ using (var server = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp))
+ {
+ server.BindToAnonymousPort(IPAddress.Loopback);
+ server.Listen(1);
+
+ var sendBuffer = new byte[SegmentCount];
+ Task serverProcessingTask = Task.Run(() =>
+ {
+ using (Socket acceptSocket = server.Accept())
+ {
+ // send data as SegmentCount (> IOV_MAX) 1-byte segments.
+ var sendSegments = new List<ArraySegment<byte>>();
+ for (int i = 0; i < SegmentCount; i++)
+ {
+ sendBuffer[i] = (byte)i;
+ sendSegments.Add(new ArraySegment<byte>(sendBuffer, i, 1));
+ }
+ SocketError error;
+ // Send blocks until all segments are sent.
+ int bytesSent = acceptSocket.Send(sendSegments, SocketFlags.None, out error);
+
+ Assert.Equal(SegmentCount, bytesSent);
+ Assert.Equal(SocketError.Success, error);
+ }
+ });
+
+ using (var client = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp))
+ {
+ client.Connect(server.LocalEndPoint);
+
+ // receive data as 1-byte segments.
+ var receiveBuffer = new byte[SegmentCount];
+ var receiveSegments = new List<ArraySegment<byte>>();
+ for (int i = 0; i < SegmentCount; i++)
+ {
+ receiveSegments.Add(new ArraySegment<byte>(receiveBuffer, i, 1));
+ }
+ var bytesReceivedTotal = 0;
+ do
+ {
+ SocketError error;
+ // Receive can return up to IOV_MAX segments.
+ int bytesReceived = client.Receive(receiveSegments, SocketFlags.None, out error);
+ bytesReceivedTotal += bytesReceived;
+ // Offset receiveSegments for next Receive.
+ receiveSegments.RemoveRange(0, bytesReceived);
+
+ Assert.NotEqual(0, bytesReceived);
+ Assert.Equal(SocketError.Success, error);
+ } while (bytesReceivedTotal != SegmentCount);
+
+ Assert.Equal(sendBuffer, receiveBuffer);
+ }
+ }
+ }
+
+ [Fact]
+ public void SendIovMaxUdp_SuccessOrMessageSize()
+ {
+ // sending more than IOV_MAX segments causes EMSGSIZE on some platforms.
+ // We handle this for stream sockets by truncating.
+ // This test verifies we are not truncating non-stream sockets.
+
+ // Use more than IOV_MAX (1024 on Linux & macOS) segments
+ // and less than Ethernet MTU.
+ const int SegmentCount = 1200;
+ using (var socket = new Socket(AddressFamily.InterNetwork, SocketType.Dgram, ProtocolType.Udp))
+ {
+ socket.BindToAnonymousPort(IPAddress.Loopback);
+ // Use our own address as destination.
+ socket.Connect(socket.LocalEndPoint);
+
+ var sendBuffer = new byte[SegmentCount];
+ var sendSegments = new List<ArraySegment<byte>>();
+ for (int i = 0; i < SegmentCount; i++)
+ {
+ sendBuffer[i] = (byte)i;
+ sendSegments.Add(new ArraySegment<byte>(sendBuffer, i, 1));
+ }
+
+ SocketError error;
+ // send data as SegmentCount (> IOV_MAX) 1-byte segments.
+ int bytesSent = socket.Send(sendSegments, SocketFlags.None, out error);
+ if (error == SocketError.Success)
+ {
+ // platform sent message with > IOV_MAX segments
+ Assert.Equal(SegmentCount, bytesSent);
+ }
+ else
+ {
+ // platform returns EMSGSIZE
+ Assert.Equal(SocketError.MessageSize, error);
+ Assert.Equal(0, bytesSent);
+ }
+ }
+ }
+
+ [Fact]
+ public async Task ReceiveIovMaxUdp_SuccessOrMessageSize()
+ {
+ // receiving more than IOV_MAX segments causes EMSGSIZE on some platforms.
+ // We handle this for stream sockets by truncating.
+ // This test verifies we are not truncating non-stream sockets.
+
+ // Use more than IOV_MAX (1024 on Linux & macOS) segments
+ // and less than Ethernet MTU.
+ const int SegmentCount = 1200;
+ var sender = new Socket(AddressFamily.InterNetwork, SocketType.Dgram, ProtocolType.Udp);
+ sender.BindToAnonymousPort(IPAddress.Loopback);
+ var receiver = new Socket(AddressFamily.InterNetwork, SocketType.Dgram, ProtocolType.Udp);
+ receiver.Connect(sender.LocalEndPoint); // only receive from sender
+ EndPoint receiverEndPoint = receiver.LocalEndPoint;
+
+ Task receiveTask = Task.Run(() =>
+ {
+ using (receiver)
+ {
+ var receiveBuffer = new byte[SegmentCount];
+ var receiveSegments = new List<ArraySegment<byte>>();
+ for (int i = 0; i < SegmentCount; i++)
+ {
+ receiveSegments.Add(new ArraySegment<byte>(receiveBuffer, i, 1));
+ }
+ // receive data as SegmentCount (> IOV_MAX) 1-byte segments.
+ SocketError error;
+ int bytesReceived = receiver.Receive(receiveSegments, SocketFlags.None, out error);
+
+ if (error == SocketError.Success)
+ {
+ // platform received message in > IOV_MAX segments
+ Assert.Equal(SegmentCount, bytesReceived);
+ }
+ else
+ {
+ // platform returns EMSGSIZE
+ Assert.Equal(SocketError.MessageSize, error);
+ Assert.Equal(0, bytesReceived);
+ }
+ }
+ });
+
+ using (sender)
+ {
+ sender.Connect(receiverEndPoint);
+ var sendBuffer = new byte[SegmentCount];
+ for (int i = 0; i < 10; i++) // UDPRedundancy
+ {
+ int bytesSent = sender.Send(sendBuffer);
+ Assert.Equal(SegmentCount, bytesSent);
+ await Task.WhenAny(receiveTask, Task.Delay(1));
+ if (receiveTask.IsCompleted)
+ {
+ break;
+ }
+ }
+ }
+
+ Assert.True(receiveTask.IsCompleted);
+ await receiveTask;
+ }
+
+ [Fact]
+ [PlatformSpecific(~TestPlatforms.Windows)] // All data is sent, even when very large (100M).
+ public void SocketSendWouldBlock_ReturnsBytesSent()
+ {
+ using (var server = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp))
+ using (var client = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp))
+ {
+ // listen
+ server.BindToAnonymousPort(IPAddress.Loopback);
+ server.Listen(1);
+ // connect
+ client.Connect(server.LocalEndPoint);
+ // accept
+ using (Socket socket = server.Accept())
+ {
+ // We send a large amount of data but don't read it.
+ // A chunck will be sent, attempts to send more will return SocketError.WouldBlock.
+ // Socket.Send must return the success of the partial send.
+ socket.Blocking = false;
+ var data = new byte[5_000_000];
+ SocketError error;
+ int bytesSent = socket.Send(data, 0, data.Length, SocketFlags.None, out error);
+
+ Assert.Equal(SocketError.Success, error);
+ Assert.InRange(bytesSent, 1, data.Length - 1);
+ }
+ }
+ }
+ }
+
public sealed class SendReceiveUdpClient : MemberDatas
{
[OuterLoop] // TODO: Issue #11345
@@ -847,8 +1048,8 @@ namespace System.Net.Sockets.Tests
// TODO #5185: harden against packet loss
const int DatagramSize = 256;
const int DatagramsToSend = 256;
- const int AckTimeout = 1000;
- const int TestTimeout = 30000;
+ const int AckTimeout = 10000;
+ const int TestTimeout = 60000;
using (var left = new UdpClient(new IPEndPoint(leftAddress, 0)))
using (var right = new UdpClient(new IPEndPoint(rightAddress, 0)))
diff --git a/src/System.Net.Sockets/tests/FunctionalTests/Shutdown.cs b/src/System.Net.Sockets/tests/FunctionalTests/Shutdown.cs
index d56739725d..1a15b231d1 100644
--- a/src/System.Net.Sockets/tests/FunctionalTests/Shutdown.cs
+++ b/src/System.Net.Sockets/tests/FunctionalTests/Shutdown.cs
@@ -42,6 +42,7 @@ namespace System.Net.Sockets.Tests
var client = (Socket)args.UserToken;
if (args.BytesTransferred == 0)
{
+ client.Shutdown(SocketShutdown.Send);
client.Dispose();
break;
}
diff --git a/src/System.Net.Sockets/tests/FunctionalTests/SocketOptionNameTest.cs b/src/System.Net.Sockets/tests/FunctionalTests/SocketOptionNameTest.cs
index ad67a34ce6..0baa055ae3 100644
--- a/src/System.Net.Sockets/tests/FunctionalTests/SocketOptionNameTest.cs
+++ b/src/System.Net.Sockets/tests/FunctionalTests/SocketOptionNameTest.cs
@@ -6,6 +6,7 @@ using System.Collections.Generic;
using System.Net.Test.Common;
using System.Runtime.InteropServices;
using System.Text;
+using System.Threading;
using System.Threading.Tasks;
using Xunit;
@@ -86,6 +87,11 @@ namespace System.Net.Sockets.Tests
[Fact]
public async Task MulticastInterface_Set_AnyInterface_Succeeds()
{
+ if (PlatformDetection.IsFedora)
+ {
+ return; // [ActiveIssue(24008)]
+ }
+
// On all platforms, index 0 means "any interface"
await MulticastInterface_Set_Helper(0);
}
@@ -130,6 +136,10 @@ namespace System.Net.Sockets.Tests
sendSocket.SendTo(Encoding.UTF8.GetBytes(message), new IPEndPoint(multicastAddress, port));
}
+ var cts = new CancellationTokenSource();
+ Assert.True(await Task.WhenAny(receiveTask, Task.Delay(20_000, cts.Token)) == receiveTask, "Waiting for received data timed out");
+ cts.Cancel();
+
int bytesReceived = await receiveTask;
string receivedMessage = Encoding.UTF8.GetString(receiveBuffer, 0, bytesReceived);
diff --git a/src/System.Net.Sockets/tests/FunctionalTests/TimeoutTest.cs b/src/System.Net.Sockets/tests/FunctionalTests/TimeoutTest.cs
index 21d804ecc9..2f5031dfc5 100644
--- a/src/System.Net.Sockets/tests/FunctionalTests/TimeoutTest.cs
+++ b/src/System.Net.Sockets/tests/FunctionalTests/TimeoutTest.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 Xunit;
namespace System.Net.Sockets.Tests
@@ -44,6 +45,7 @@ namespace System.Net.Sockets.Tests
// but also not so large that it takes too long to run.
const int Timeout = 2000;
+ [ActiveIssue(23767, TestPlatforms.AnyUnix)]
[OuterLoop] // TODO: Issue #11345
[Theory]
[InlineData(true)]
@@ -106,7 +108,7 @@ namespace System.Net.Sockets.Tests
acceptedSocket.ForceNonBlocking(forceNonBlocking);
- DateTime start = default(DateTime);
+ var sw = new Stopwatch();
// Force Send to timeout by filling the kernel buffer.
var sendBuffer = new byte[16 * 1024];
@@ -114,18 +116,18 @@ namespace System.Net.Sockets.Tests
{
while (true)
{
- start = DateTime.UtcNow;
+ sw.Restart();
acceptedSocket.Send(sendBuffer);
}
}));
- double elapsed = (DateTime.UtcNow - start).TotalMilliseconds;
+ double elapsed = sw.Elapsed.TotalMilliseconds;
Assert.Equal(SocketError.TimedOut, sockEx.SocketErrorCode);
Assert.True(acceptedSocket.Connected);
// Try to ensure that the elapsed timeout is reasonably correct
- Assert.InRange(elapsed, Timeout * 0.75, Timeout * 1.5);
+ Assert.InRange(elapsed, Timeout * 0.5, Timeout * 2);
}
}
}
diff --git a/src/System.Net.Sockets/tests/FunctionalTests/UnixDomainSocketTest.cs b/src/System.Net.Sockets/tests/FunctionalTests/UnixDomainSocketTest.cs
index b21739f053..e6c1dd8a5f 100644
--- a/src/System.Net.Sockets/tests/FunctionalTests/UnixDomainSocketTest.cs
+++ b/src/System.Net.Sockets/tests/FunctionalTests/UnixDomainSocketTest.cs
@@ -4,8 +4,10 @@
using System.Diagnostics;
using System.IO;
+using System.Linq;
using System.Net.Test.Common;
using System.Text;
+using System.Threading;
using System.Threading.Tasks;
using Xunit;
@@ -124,7 +126,7 @@ namespace System.Net.Sockets.Tests
[OuterLoop] // TODO: Issue #11345
[Fact]
- [PlatformSpecific(TestPlatforms.AnyUnix)] // Tests SendReceive sucess for UnixDomainSocketEndPoint on Unix
+ [PlatformSpecific(TestPlatforms.AnyUnix)] // Tests SendReceive success for UnixDomainSocketEndPoint on Unix
public void Socket_SendReceive_Success()
{
string path = GetRandomNonExistingFilePath();
@@ -163,7 +165,7 @@ namespace System.Net.Sockets.Tests
[OuterLoop] // TODO: Issue #11345
[Fact]
- [PlatformSpecific(TestPlatforms.AnyUnix)] // Tests SendReceiveAsync sucess for UnixDomainSocketEndPoint on Unix
+ [PlatformSpecific(TestPlatforms.AnyUnix)] // Tests SendReceiveAsync success for UnixDomainSocketEndPoint on Unix
public async Task Socket_SendReceiveAsync_Success()
{
string path = GetRandomNonExistingFilePath();
@@ -206,7 +208,7 @@ namespace System.Net.Sockets.Tests
[InlineData(500, 18, 21)]
[InlineData(500, 21, 18)]
[InlineData(5, 128000, 64000)]
- [PlatformSpecific(TestPlatforms.AnyUnix)] // Tests SendReceiveAsync sucess for UnixDomainSocketEndPoint on Unix
+ [PlatformSpecific(TestPlatforms.AnyUnix)] // Tests SendReceiveAsync success for UnixDomainSocketEndPoint on Unix
public async Task Socket_SendReceiveAsync_PropagateToStream_Success(int iterations, int writeBufferSize, int readBufferSize)
{
var writeBuffer = new byte[writeBufferSize * iterations];
@@ -260,9 +262,56 @@ namespace System.Net.Sockets.Tests
}
[OuterLoop] // TODO: Issue #11345
+ [Theory]
+ [InlineData(false)]
+ [InlineData(true)]
+ [PlatformSpecific(TestPlatforms.AnyUnix)] // Tests ConcurrentSendReceive success for UnixDomainSocketEndPoint on Unix
+ public void ConcurrentSendReceive(bool forceNonBlocking)
+ {
+ using (Socket server = new Socket(AddressFamily.Unix, SocketType.Stream, ProtocolType.Unspecified))
+ using (Socket client = new Socket(AddressFamily.Unix, SocketType.Stream, ProtocolType.Unspecified))
+ {
+ const int Iters = 25;
+ byte[] sendData = new byte[Iters];
+ byte[] receiveData = new byte[sendData.Length];
+ new Random().NextBytes(sendData);
+
+ string path = GetRandomNonExistingFilePath();
+
+ server.Bind(new UnixDomainSocketEndPoint(path));
+ server.Listen(1);
+
+ Task<Socket> acceptTask = server.AcceptAsync();
+ client.Connect(new UnixDomainSocketEndPoint(path));
+ acceptTask.Wait();
+ Socket accepted = acceptTask.Result;
+
+ client.ForceNonBlocking(forceNonBlocking);
+ accepted.ForceNonBlocking(forceNonBlocking);
+
+ Task[] writes = new Task[Iters];
+ Task<int>[] reads = new Task<int>[Iters];
+ for (int i = 0; i < Iters; i++)
+ {
+ reads[i] = Task.Factory.StartNew(s => accepted.Receive(receiveData, (int)s, 1, SocketFlags.None), i,
+ CancellationToken.None, TaskCreationOptions.LongRunning, TaskScheduler.Default);
+ }
+ for (int i = 0; i < Iters; i++)
+ {
+ writes[i] = Task.Factory.StartNew(s => client.Send(sendData, (int)s, 1, SocketFlags.None), i,
+ CancellationToken.None, TaskCreationOptions.LongRunning, TaskScheduler.Default);
+ }
+ Task.WaitAll(writes);
+ Task.WaitAll(reads);
+
+ Assert.Equal(sendData.OrderBy(i => i), receiveData.OrderBy(i => i));
+ }
+ }
+
+ [OuterLoop] // TODO: Issue #11345
[Fact]
- [PlatformSpecific(TestPlatforms.AnyUnix)] // Tests ConcurrentSendReceive sucess for UnixDomainSocketEndPoint on Unix
- public void ConcurrentSendReceive()
+ [PlatformSpecific(TestPlatforms.AnyUnix)] // Tests ConcurrentSendReceive success for UnixDomainSocketEndPoint on Unix
+ public void ConcurrentSendReceiveAsync()
{
using (Socket server = new Socket(AddressFamily.Unix, SocketType.Stream, ProtocolType.Unspecified))
using (Socket client = new Socket(AddressFamily.Unix, SocketType.Stream, ProtocolType.Unspecified))
diff --git a/src/System.Net.WebProxy/tests/WebProxyTest.cs b/src/System.Net.WebProxy/tests/WebProxyTest.cs
index 79fd45b9dd..dd74d8196b 100644
--- a/src/System.Net.WebProxy/tests/WebProxyTest.cs
+++ b/src/System.Net.WebProxy/tests/WebProxyTest.cs
@@ -176,6 +176,7 @@ namespace System.Net.Tests
yield return new object[] { new Uri($"http://{IPAddress.None}"), false };
}
+ [ActiveIssue(23766, TestPlatforms.AnyUnix)]
[Theory]
[MemberData(nameof(BypassOnLocal_MemberData))]
public static void WebProxy_BypassOnLocal_MatchesExpected(Uri destination, bool isLocal)
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 ef0b4a6ea7..7cbd0c2585 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
@@ -138,6 +138,7 @@
</ItemGroup>
<ItemGroup Condition="'$(TargetsUnix)' == 'true'">
<Reference Include="System.Buffers" />
+ <Reference Include="System.Net.Http" />
<Reference Include="System.Net.NameResolution" />
<Reference Include="System.Net.Security" />
<Reference Include="System.Net.Sockets" />
@@ -146,6 +147,7 @@
<Reference Include="System.Security.Cryptography.Algorithms" />
<Reference Include="System.Security.Cryptography.Primitives" />
<Reference Include="System.Text.Encoding.Extensions" />
+ <Reference Include="System.Threading.Thread" />
<Reference Include="System.Threading.Timer" />
</ItemGroup>
<Import Project="$([MSBuild]::GetDirectoryNameOfFileAbove($(MSBuildThisFileDirectory), dir.targets))\dir.targets" />
diff --git a/src/System.Net.WebSockets.Client/src/System/Net/WebSockets/ClientWebSocketOptions.cs b/src/System.Net.WebSockets.Client/src/System/Net/WebSockets/ClientWebSocketOptions.cs
index c488277150..d5531f146c 100644
--- a/src/System.Net.WebSockets.Client/src/System/Net/WebSockets/ClientWebSocketOptions.cs
+++ b/src/System.Net.WebSockets.Client/src/System/Net/WebSockets/ClientWebSocketOptions.cs
@@ -13,23 +13,20 @@ namespace System.Net.WebSockets
public sealed class ClientWebSocketOptions
{
private bool _isReadOnly; // After ConnectAsync is called the options cannot be modified.
- private readonly List<string> _requestedSubProtocols;
- private readonly WebHeaderCollection _requestHeaders;
private TimeSpan _keepAliveInterval = WebSocket.DefaultKeepAliveInterval;
private bool _useDefaultCredentials;
private ICredentials _credentials;
private IWebProxy _proxy;
- private X509CertificateCollection _clientCertificates;
private CookieContainer _cookies;
private int _receiveBufferSize = 0x1000;
private int _sendBufferSize = 0x1000;
private ArraySegment<byte>? _buffer;
- internal ClientWebSocketOptions()
- {
- _requestedSubProtocols = new List<string>();
- _requestHeaders = new WebHeaderCollection();
- }
+ internal X509CertificateCollection _clientCertificates;
+ internal WebHeaderCollection _requestHeaders;
+ internal List<string> _requestedSubProtocols;
+
+ internal ClientWebSocketOptions() { } // prevent external instantiation
#region HTTP Settings
@@ -39,12 +36,14 @@ namespace System.Net.WebSockets
ThrowIfReadOnly();
// WebHeaderCollection performs validation of headerName/headerValue.
- _requestHeaders.Set(headerName, headerValue);
+ RequestHeaders.Set(headerName, headerValue);
}
- internal WebHeaderCollection RequestHeaders { get { return _requestHeaders; } }
+ internal WebHeaderCollection RequestHeaders =>
+ _requestHeaders ?? (_requestHeaders = new WebHeaderCollection());
- internal List<string> RequestedSubProtocols { get { return _requestedSubProtocols;} }
+ internal List<string> RequestedSubProtocols =>
+ _requestedSubProtocols ?? (_requestedSubProtocols = new List<string>());
public bool UseDefaultCredentials
{
@@ -131,14 +130,15 @@ namespace System.Net.WebSockets
WebSocketValidate.ValidateSubprotocol(subProtocol);
// Duplicates not allowed.
- foreach (string item in _requestedSubProtocols)
+ List<string> subprotocols = RequestedSubProtocols; // force initialization of the list
+ foreach (string item in subprotocols)
{
if (string.Equals(item, subProtocol, StringComparison.OrdinalIgnoreCase))
{
throw new ArgumentException(SR.Format(SR.net_WebSockets_NoDuplicateProtocol, subProtocol), nameof(subProtocol));
}
}
- _requestedSubProtocols.Add(subProtocol);
+ subprotocols.Add(subProtocol);
}
public TimeSpan KeepAliveInterval
diff --git a/src/System.Net.WebSockets.Client/src/System/Net/WebSockets/WebSocketHandle.Managed.cs b/src/System.Net.WebSockets.Client/src/System/Net/WebSockets/WebSocketHandle.Managed.cs
index 39d2292754..45c0e5aca7 100644
--- a/src/System.Net.WebSockets.Client/src/System/Net/WebSockets/WebSocketHandle.Managed.cs
+++ b/src/System.Net.WebSockets.Client/src/System/Net/WebSockets/WebSocketHandle.Managed.cs
@@ -5,6 +5,8 @@
using System.Collections.Generic;
using System.Diagnostics;
using System.IO;
+using System.Net.Http;
+using System.Net.Http.Headers;
using System.Net.Security;
using System.Net.Sockets;
using System.Runtime.ExceptionServices;
@@ -17,15 +19,6 @@ namespace System.Net.WebSockets
{
internal sealed class WebSocketHandle
{
- /// <summary>Per-thread cached StringBuilder for building of strings to send on the connection.</summary>
- [ThreadStatic]
- private static StringBuilder t_cachedStringBuilder;
-
- /// <summary>Default encoding for HTTP requests. Latin alphabet no 1, ISO/IEC 8859-1.</summary>
- private static readonly Encoding s_defaultHttpEncoding = Encoding.GetEncoding(28591);
-
- /// <summary>Size of the receive buffer to use.</summary>
- private const int DefaultReceiveBufferSize = 0x1000;
/// <summary>GUID appended by the server as part of the security key response. Defined in the RFC.</summary>
private const string WSServerGuid = "258EAFA5-E914-47DA-95CA-C5AB0DC85B11";
@@ -71,202 +64,146 @@ namespace System.Net.WebSockets
public Task CloseOutputAsync(WebSocketCloseStatus closeStatus, string statusDescription, CancellationToken cancellationToken) =>
_webSocket.CloseOutputAsync(closeStatus, statusDescription, cancellationToken);
- public async Task ConnectAsyncCore(Uri uri, CancellationToken cancellationToken, ClientWebSocketOptions options)
+ private sealed class DirectManagedHttpClientHandler : HttpClientHandler
{
- // TODO #14480 : Not currently implemented, or explicitly ignored:
- // - ClientWebSocketOptions.UseDefaultCredentials
- // - ClientWebSocketOptions.Credentials
- // - ClientWebSocketOptions.Proxy
- // - ClientWebSocketOptions._sendBufferSize
-
- // Establish connection to the server
- CancellationTokenRegistration registration = cancellationToken.Register(s => ((WebSocketHandle)s).Abort(), this);
- try
- {
- // Connect to the remote server
- Socket connectedSocket = await ConnectSocketAsync(uri.Host, uri.Port, cancellationToken).ConfigureAwait(false);
- Stream stream = new NetworkStream(connectedSocket, ownsSocket:true);
+ private const string ManagedHandlerEnvVar = "COMPlus_UseManagedHttpClientHandler";
+ private static readonly LocalDataStoreSlot s_managedHandlerSlot = GetSlot();
+ private static readonly object s_true = true;
- // Upgrade to SSL if needed
- if (uri.Scheme == UriScheme.Wss)
+ private static LocalDataStoreSlot GetSlot()
+ {
+ LocalDataStoreSlot slot = Thread.GetNamedDataSlot(ManagedHandlerEnvVar);
+ if (slot != null)
{
- var sslStream = new SslStream(stream);
- await sslStream.AuthenticateAsClientAsync(
- uri.Host,
- options.ClientCertificates,
- SecurityProtocol.AllowedSecurityProtocols,
- checkCertificateRevocation: false).ConfigureAwait(false);
- stream = sslStream;
+ return slot;
}
- // Create the security key and expected response, then build all of the request headers
- KeyValuePair<string, string> secKeyAndSecWebSocketAccept = CreateSecKeyAndSecWebSocketAccept();
- byte[] requestHeader = BuildRequestHeader(uri, options, secKeyAndSecWebSocketAccept.Key);
-
- // Write out the header to the connection
- await stream.WriteAsync(requestHeader, 0, requestHeader.Length, cancellationToken).ConfigureAwait(false);
-
- // Parse the response and store our state for the remainder of the connection
- string subprotocol = await ParseAndValidateConnectResponseAsync(stream, options, secKeyAndSecWebSocketAccept.Value, cancellationToken).ConfigureAwait(false);
-
- _webSocket = WebSocket.CreateClientWebSocket(
- stream, subprotocol, options.ReceiveBufferSize, options.SendBufferSize, options.KeepAliveInterval, false, options.Buffer.GetValueOrDefault());
-
- // If a concurrent Abort or Dispose came in before we set _webSocket, make sure to update it appropriately
- if (_state == WebSocketState.Aborted)
+ try
{
- _webSocket.Abort();
+ return Thread.AllocateNamedDataSlot(ManagedHandlerEnvVar);
}
- else if (_state == WebSocketState.Closed)
+ catch (ArgumentException) // in case of a race condition where multiple threads all try to allocate the slot concurrently
{
- _webSocket.Dispose();
+ return Thread.GetNamedDataSlot(ManagedHandlerEnvVar);
}
}
- catch (Exception exc)
- {
- if (_state < WebSocketState.Closed)
- {
- _state = WebSocketState.Closed;
- }
- Abort();
-
- if (exc is WebSocketException)
+ public static DirectManagedHttpClientHandler CreateHandler()
+ {
+ Thread.SetData(s_managedHandlerSlot, s_true);
+ try
{
- throw;
+ return new DirectManagedHttpClientHandler();
}
- throw new WebSocketException(SR.net_webstatus_ConnectFailure, exc);
- }
- finally
- {
- registration.Dispose();
+ finally { Thread.SetData(s_managedHandlerSlot, null); }
}
+
+ public new Task<HttpResponseMessage> SendAsync(
+ HttpRequestMessage request, CancellationToken cancellationToken) =>
+ base.SendAsync(request, cancellationToken);
}
- /// <summary>Connects a socket to the specified host and port, subject to cancellation and aborting.</summary>
- /// <param name="host">The host to which to connect.</param>
- /// <param name="port">The port to which to connect on the host.</param>
- /// <param name="cancellationToken">The CancellationToken to use to cancel the websocket.</param>
- /// <returns>The connected Socket.</returns>
- private async Task<Socket> ConnectSocketAsync(string host, int port, CancellationToken cancellationToken)
+ public async Task ConnectAsyncCore(Uri uri, CancellationToken cancellationToken, ClientWebSocketOptions options)
{
- IPAddress[] addresses = await Dns.GetHostAddressesAsync(host).ConfigureAwait(false);
-
- ExceptionDispatchInfo lastException = null;
- foreach (IPAddress address in addresses)
+ try
{
- var socket = new Socket(address.AddressFamily, SocketType.Stream, ProtocolType.Tcp);
- try
+ // Create the request message, including a uri with ws{s} switched to http{s}.
+ uri = new UriBuilder(uri) { Scheme = (uri.Scheme == UriScheme.Ws) ? UriScheme.Http : UriScheme.Https }.Uri;
+ var request = new HttpRequestMessage(HttpMethod.Get, uri);
+ if (options._requestHeaders?.Count > 0) // use field to avoid lazily initializing the collection
{
- using (cancellationToken.Register(s => ((Socket)s).Dispose(), socket))
- using (_abortSource.Token.Register(s => ((Socket)s).Dispose(), socket))
+ foreach (string key in options.RequestHeaders)
{
- try
- {
- await socket.ConnectAsync(address, port).ConfigureAwait(false);
- }
- catch (ObjectDisposedException ode)
- {
- // If the socket was disposed because cancellation was requested, translate the exception
- // into a new OperationCanceledException. Otherwise, let the original ObjectDisposedexception propagate.
- CancellationToken token = cancellationToken.IsCancellationRequested ? cancellationToken : _abortSource.Token;
- if (token.IsCancellationRequested)
- {
- throw new OperationCanceledException(new OperationCanceledException().Message, ode, token);
- }
- }
+ request.Headers.Add(key, options.RequestHeaders[key]);
}
- cancellationToken.ThrowIfCancellationRequested(); // in case of a race and socket was disposed after the await
- _abortSource.Token.ThrowIfCancellationRequested();
- return socket;
}
- catch (Exception exc)
- {
- socket.Dispose();
- lastException = ExceptionDispatchInfo.Capture(exc);
- }
- }
-
- lastException?.Throw();
-
- Debug.Fail("We should never get here. We should have already returned or an exception should have been thrown.");
- throw new WebSocketException(SR.net_webstatus_ConnectFailure);
- }
- /// <summary>Creates a byte[] containing the headers to send to the server.</summary>
- /// <param name="uri">The Uri of the server.</param>
- /// <param name="options">The options used to configure the websocket.</param>
- /// <param name="secKey">The generated security key to send in the Sec-WebSocket-Key header.</param>
- /// <returns>The byte[] containing the encoded headers ready to send to the network.</returns>
- private static byte[] BuildRequestHeader(Uri uri, ClientWebSocketOptions options, string secKey)
- {
- StringBuilder builder = t_cachedStringBuilder ?? (t_cachedStringBuilder = new StringBuilder());
- Debug.Assert(builder.Length == 0, $"Expected builder to be empty, got one of length {builder.Length}");
- try
- {
- builder.Append("GET ").Append(uri.PathAndQuery).Append(" HTTP/1.1\r\n");
+ // Create the security key and expected response, then build all of the request headers
+ KeyValuePair<string, string> secKeyAndSecWebSocketAccept = CreateSecKeyAndSecWebSocketAccept();
+ AddWebSocketHeaders(request, secKeyAndSecWebSocketAccept.Key, options);
- // Add all of the required headers, honoring Host header if set.
- string hostHeader = options.RequestHeaders[HttpKnownHeaderNames.Host];
- builder.Append("Host: ");
- if (string.IsNullOrEmpty(hostHeader))
+ // Create the handler for this request and populate it with all of the options.
+ DirectManagedHttpClientHandler handler = DirectManagedHttpClientHandler.CreateHandler();
+ handler.UseDefaultCredentials = options.UseDefaultCredentials;
+ handler.Credentials = options.Credentials;
+ handler.Proxy = options.Proxy;
+ handler.CookieContainer = options.Cookies;
+ if (options._clientCertificates?.Count > 0) // use field to avoid lazily initializing the collection
{
- builder.Append(uri.IdnHost).Append(':').Append(uri.Port).Append("\r\n");
+ handler.ClientCertificateOptions = ClientCertificateOption.Manual;
+ handler.ClientCertificates.AddRange(options.ClientCertificates);
}
- else
+
+ // Issue the request. The response must be status code 101.
+ HttpResponseMessage response = await handler.SendAsync(request, cancellationToken).ConfigureAwait(false);
+ if (response.StatusCode != HttpStatusCode.SwitchingProtocols)
{
- builder.Append(hostHeader).Append("\r\n");
+ throw new WebSocketException(SR.net_webstatus_ConnectFailure);
}
- builder.Append("Connection: Upgrade\r\n");
- builder.Append("Upgrade: websocket\r\n");
- builder.Append("Sec-WebSocket-Version: 13\r\n");
- builder.Append("Sec-WebSocket-Key: ").Append(secKey).Append("\r\n");
+ // The Connection, Upgrade, and SecWebSocketAccept headers are required and with specific values.
+ ValidateHeader(response.Headers, HttpKnownHeaderNames.Connection, "Upgrade");
+ ValidateHeader(response.Headers, HttpKnownHeaderNames.Upgrade, "websocket");
+ ValidateHeader(response.Headers, HttpKnownHeaderNames.SecWebSocketAccept, secKeyAndSecWebSocketAccept.Value);
- // Add all of the additionally requested headers
- foreach (string key in options.RequestHeaders.AllKeys)
- {
- if (string.Equals(key, HttpKnownHeaderNames.Host, StringComparison.OrdinalIgnoreCase))
+ // The SecWebSocketProtocol header is optional. We should only get it with a non-empty value if we requested subprotocols,
+ // and then it must only be one of the ones we requested. If we got a subprotocol other than one we requested (or if we
+ // already got one in a previous header), fail. Otherwise, track which one we got.
+ string subprotocol = null;
+ IEnumerable<string> subprotocolEnumerableValues;
+ if (response.Headers.TryGetValues(HttpKnownHeaderNames.SecWebSocketProtocol, out subprotocolEnumerableValues))
+ {
+ Debug.Assert(subprotocolEnumerableValues is string[]);
+ string[] subprotocolArray = (string[])subprotocolEnumerableValues;
+ if (subprotocolArray.Length != 1 ||
+ (subprotocol = options.RequestedSubProtocols.Find(requested => string.Equals(requested, subprotocolArray[0], StringComparison.OrdinalIgnoreCase))) == null)
{
- // Host header handled above
- continue;
+ throw new WebSocketException(
+ WebSocketError.UnsupportedProtocol,
+ SR.Format(SR.net_WebSockets_AcceptUnsupportedProtocol, string.Join(", ", options.RequestedSubProtocols), subprotocol));
}
-
- builder.Append(key).Append(": ").Append(options.RequestHeaders[key]).Append("\r\n");
}
- // Add the optional subprotocols header
- if (options.RequestedSubProtocols.Count > 0)
+ // Get the response stream and wrap it in a web socket.
+ Stream connectedStream = await response.Content.ReadAsStreamAsync().ConfigureAwait(false);
+ Debug.Assert(connectedStream.CanWrite);
+ Debug.Assert(connectedStream.CanRead);
+ _webSocket = WebSocket.CreateClientWebSocket( // TODO https://github.com/dotnet/corefx/issues/21537: Use new API when available
+ connectedStream,
+ subprotocol,
+ options.ReceiveBufferSize,
+ options.SendBufferSize,
+ options.KeepAliveInterval,
+ useZeroMaskingKey: false,
+ internalBuffer:options.Buffer.GetValueOrDefault());
+ }
+ catch (Exception exc)
+ {
+ if (_state < WebSocketState.Closed)
{
- builder.Append(HttpKnownHeaderNames.SecWebSocketProtocol).Append(": ");
- builder.Append(options.RequestedSubProtocols[0]);
- for (int i = 1; i < options.RequestedSubProtocols.Count; i++)
- {
- builder.Append(", ").Append(options.RequestedSubProtocols[i]);
- }
- builder.Append("\r\n");
+ _state = WebSocketState.Closed;
}
- // Add an optional cookies header
- if (options.Cookies != null)
+ Abort();
+
+ if (exc is WebSocketException)
{
- string header = options.Cookies.GetCookieHeader(uri);
- if (!string.IsNullOrWhiteSpace(header))
- {
- builder.Append(HttpKnownHeaderNames.Cookie).Append(": ").Append(header).Append("\r\n");
- }
+ throw;
}
-
- // End the headers
- builder.Append("\r\n");
-
- // Return the bytes for the built up header
- return s_defaultHttpEncoding.GetBytes(builder.ToString());
+ throw new WebSocketException(SR.net_webstatus_ConnectFailure, exc);
}
- finally
+ }
+
+ /// <param name="secKey">The generated security key to send in the Sec-WebSocket-Key header.</param>
+ private static void AddWebSocketHeaders(HttpRequestMessage request, string secKey, ClientWebSocketOptions options)
+ {
+ request.Headers.TryAddWithoutValidation(HttpKnownHeaderNames.Connection, HttpKnownHeaderNames.Upgrade);
+ request.Headers.TryAddWithoutValidation(HttpKnownHeaderNames.Upgrade, "websocket");
+ request.Headers.TryAddWithoutValidation(HttpKnownHeaderNames.SecWebSocketVersion, "13");
+ request.Headers.TryAddWithoutValidation(HttpKnownHeaderNames.SecWebSocketKey, secKey);
+ if (options._requestedSubProtocols?.Count > 0)
{
- // Make sure we clear the builder
- builder.Clear();
+ request.Headers.Add(HttpKnownHeaderNames.SecWebSocketProtocol, string.Join(", ", options.RequestedSubProtocols));
}
}
@@ -287,174 +224,21 @@ namespace System.Net.WebSockets
}
}
- /// <summary>Read and validate the connect response headers from the server.</summary>
- /// <param name="stream">The stream from which to read the response headers.</param>
- /// <param name="options">The options used to configure the websocket.</param>
- /// <param name="expectedSecWebSocketAccept">The expected value of the Sec-WebSocket-Accept header.</param>
- /// <param name="cancellationToken">The CancellationToken to use to cancel the websocket.</param>
- /// <returns>The agreed upon subprotocol with the server, or null if there was none.</returns>
- private async Task<string> ParseAndValidateConnectResponseAsync(
- Stream stream, ClientWebSocketOptions options, string expectedSecWebSocketAccept, CancellationToken cancellationToken)
+ private static void ValidateHeader(HttpHeaders headers, string name, string expectedValue)
{
- // Read the first line of the response
- string statusLine = await ReadResponseHeaderLineAsync(stream, cancellationToken).ConfigureAwait(false);
-
- // Depending on the underlying sockets implementation and timing, connecting to a server that then
- // immediately closes the connection may either result in an exception getting thrown from the connect
- // earlier, or it may result in getting to here but reading 0 bytes. If we read 0 bytes and thus have
- // an empty status line, treat it as a connect failure.
- if (string.IsNullOrEmpty(statusLine))
+ if (!headers.TryGetValues(name, out IEnumerable<string> values))
{
- throw new WebSocketException(SR.Format(SR.net_webstatus_ConnectFailure));
+ ThrowConnectFailure();
}
- const string ExpectedStatusStart = "HTTP/1.1 ";
- const string ExpectedStatusStatWithCode = "HTTP/1.1 101"; // 101 == SwitchingProtocols
-
- // If the status line doesn't begin with "HTTP/1.1" or isn't long enough to contain a status code, fail.
- if (!statusLine.StartsWith(ExpectedStatusStart, StringComparison.Ordinal) || statusLine.Length < ExpectedStatusStatWithCode.Length)
- {
- throw new WebSocketException(WebSocketError.HeaderError);
- }
-
- // If the status line doesn't contain a status code 101, or if it's long enough to have a status description
- // but doesn't contain whitespace after the 101, fail.
- if (!statusLine.StartsWith(ExpectedStatusStatWithCode, StringComparison.Ordinal) ||
- (statusLine.Length > ExpectedStatusStatWithCode.Length && !char.IsWhiteSpace(statusLine[ExpectedStatusStatWithCode.Length])))
- {
- throw new WebSocketException(SR.net_webstatus_ConnectFailure);
- }
-
- // Read each response header. Be liberal in parsing the response header, treating
- // everything to the left of the colon as the key and everything to the right as the value, trimming both.
- // For each header, validate that we got the expected value.
- bool foundUpgrade = false, foundConnection = false, foundSecWebSocketAccept = false;
- string subprotocol = null;
- string line;
- while (!string.IsNullOrEmpty(line = await ReadResponseHeaderLineAsync(stream, cancellationToken).ConfigureAwait(false)))
- {
- int colonIndex = line.IndexOf(':');
- if (colonIndex == -1)
- {
- throw new WebSocketException(WebSocketError.HeaderError);
- }
-
- string headerName = line.SubstringTrim(0, colonIndex);
- string headerValue = line.SubstringTrim(colonIndex + 1);
-
- // The Connection, Upgrade, and SecWebSocketAccept headers are required and with specific values.
- ValidateAndTrackHeader(HttpKnownHeaderNames.Connection, "Upgrade", headerName, headerValue, ref foundConnection);
- ValidateAndTrackHeader(HttpKnownHeaderNames.Upgrade, "websocket", headerName, headerValue, ref foundUpgrade);
- ValidateAndTrackHeader(HttpKnownHeaderNames.SecWebSocketAccept, expectedSecWebSocketAccept, headerName, headerValue, ref foundSecWebSocketAccept);
-
- // The SecWebSocketProtocol header is optional. We should only get it with a non-empty value if we requested subprotocols,
- // and then it must only be one of the ones we requested. If we got a subprotocol other than one we requested (or if we
- // already got one in a previous header), fail. Otherwise, track which one we got.
- if (string.Equals(HttpKnownHeaderNames.SecWebSocketProtocol, headerName, StringComparison.OrdinalIgnoreCase) &&
- !string.IsNullOrWhiteSpace(headerValue))
- {
- string newSubprotocol = options.RequestedSubProtocols.Find(requested => string.Equals(requested, headerValue, StringComparison.OrdinalIgnoreCase));
- if (newSubprotocol == null || subprotocol != null)
- {
- throw new WebSocketException(
- WebSocketError.UnsupportedProtocol,
- SR.Format(SR.net_WebSockets_AcceptUnsupportedProtocol, string.Join(", ", options.RequestedSubProtocols), subprotocol));
- }
- subprotocol = newSubprotocol;
- }
- }
- if (!foundUpgrade || !foundConnection || !foundSecWebSocketAccept)
+ Debug.Assert(values is string[]);
+ string[] array = (string[])values;
+ if (array.Length != 1 || !string.Equals(array[0], expectedValue, StringComparison.OrdinalIgnoreCase))
{
- throw new WebSocketException(SR.net_webstatus_ConnectFailure);
+ throw new WebSocketException(SR.Format(SR.net_WebSockets_InvalidResponseHeader, name, string.Join(", ", array)));
}
-
- return subprotocol;
}
- /// <summary>Validates a received header against expected values and tracks that we've received it.</summary>
- /// <param name="targetHeaderName">The header name against which we're comparing.</param>
- /// <param name="targetHeaderValue">The header value against which we're comparing.</param>
- /// <param name="foundHeaderName">The actual header name received.</param>
- /// <param name="foundHeaderValue">The actual header value received.</param>
- /// <param name="foundHeader">A bool tracking whether this header has been seen.</param>
- private static void ValidateAndTrackHeader(
- string targetHeaderName, string targetHeaderValue,
- string foundHeaderName, string foundHeaderValue,
- ref bool foundHeader)
- {
- bool isTargetHeader = string.Equals(targetHeaderName, foundHeaderName, StringComparison.OrdinalIgnoreCase);
- if (!foundHeader)
- {
- if (isTargetHeader)
- {
- if (!string.Equals(targetHeaderValue, foundHeaderValue, StringComparison.OrdinalIgnoreCase))
- {
- throw new WebSocketException(SR.Format(SR.net_WebSockets_InvalidResponseHeader, targetHeaderName, foundHeaderValue));
- }
- foundHeader = true;
- }
- }
- else
- {
- if (isTargetHeader)
- {
- throw new WebSocketException(SR.Format(SR.net_webstatus_ConnectFailure));
- }
- }
- }
-
- /// <summary>Reads a line from the stream.</summary>
- /// <param name="stream">The stream from which to read.</param>
- /// <param name="cancellationToken">The CancellationToken used to cancel the websocket.</param>
- /// <returns>The read line, or null if none could be read.</returns>
- private static async Task<string> ReadResponseHeaderLineAsync(Stream stream, CancellationToken cancellationToken)
- {
- StringBuilder sb = t_cachedStringBuilder;
- if (sb != null)
- {
- t_cachedStringBuilder = null;
- Debug.Assert(sb.Length == 0, $"Expected empty StringBuilder");
- }
- else
- {
- sb = new StringBuilder();
- }
-
- var arr = new byte[1];
- char prevChar = '\0';
- try
- {
- // TODO: Reading one byte is extremely inefficient. The problem, however,
- // is that if we read multiple bytes, we could end up reading bytes post-headers
- // that are part of messages meant to be read by the managed websocket after
- // the connection. The likely solution here is to wrap the stream in a BufferedStream,
- // though a) that comes at the expense of an extra set of virtual calls, b)
- // it adds a buffer when the managed websocket will already be using a buffer, and
- // c) it's not exposed on the version of the System.IO contract we're currently using.
- while (await stream.ReadAsync(arr, 0, 1, cancellationToken).ConfigureAwait(false) == 1)
- {
- // Process the next char
- char curChar = (char)arr[0];
- if (prevChar == '\r' && curChar == '\n')
- {
- break;
- }
- sb.Append(curChar);
- prevChar = curChar;
- }
-
- if (sb.Length > 0 && sb[sb.Length - 1] == '\r')
- {
- sb.Length = sb.Length - 1;
- }
-
- return sb.ToString();
- }
- finally
- {
- sb.Clear();
- t_cachedStringBuilder = sb;
- }
- }
+ private static void ThrowConnectFailure() => throw new WebSocketException(SR.net_webstatus_ConnectFailure);
}
}
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 68ef741e21..f00c66c3c8 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
@@ -22,7 +22,7 @@ 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;
+using RTWebSocketError = Windows.Networking.Sockets.WebSocketError;
namespace System.Net.WebSockets
{
@@ -400,7 +400,7 @@ namespace System.Net.WebSockets
{
// WinRT WebSockets always throw exceptions of type System.Exception. However, we can determine whether
// or not we're dealing with a known error by using WinRT's WebSocketError.GetStatus method.
- WebErrorStatus status = RTWeb​Socket​Error.GetStatus(exc.HResult);
+ WebErrorStatus status = RTWebSocketError.GetStatus(exc.HResult);
WebSocketError actualError = WebSocketError.Faulted;
switch (status)
{
diff --git a/src/System.Net.WebSockets.Client/tests/AbortTest.cs b/src/System.Net.WebSockets.Client/tests/AbortTest.cs
index d5c6bec1a3..ff6ac0076d 100644
--- a/src/System.Net.WebSockets.Client/tests/AbortTest.cs
+++ b/src/System.Net.WebSockets.Client/tests/AbortTest.cs
@@ -16,9 +16,10 @@ namespace System.Net.WebSockets.Client.Tests
{
public AbortTest(ITestOutputHelper output) : base(output) { }
+ [ActiveIssue(23151, TestPlatforms.AnyUnix)] // need ManagedHandler support for canceling a ConnectAsync operation
[OuterLoop] // TODO: Issue #11345
[ConditionalTheory(nameof(WebSocketsSupported)), MemberData(nameof(EchoServers))]
- public void Abort_ConnectAndAbort_ThrowsWebSocketExceptionWithmessage(Uri server)
+ public async Task Abort_ConnectAndAbort_ThrowsWebSocketExceptionWithmessage(Uri server)
{
using (var cws = new ClientWebSocket())
{
@@ -29,7 +30,7 @@ namespace System.Net.WebSockets.Client.Tests
Task t = cws.ConnectAsync(ub.Uri, cts.Token);
cws.Abort();
- WebSocketException ex = Assert.Throws<WebSocketException>(() => t.GetAwaiter().GetResult());
+ WebSocketException ex = await Assert.ThrowsAsync<WebSocketException>(() => t);
Assert.Equal(ResourceHelper.GetExceptionMessage("net_webstatus_ConnectFailure"), ex.Message);
diff --git a/src/System.Net.WebSockets.Client/tests/CancelTest.cs b/src/System.Net.WebSockets.Client/tests/CancelTest.cs
index 9bc3015aab..183289829d 100644
--- a/src/System.Net.WebSockets.Client/tests/CancelTest.cs
+++ b/src/System.Net.WebSockets.Client/tests/CancelTest.cs
@@ -14,6 +14,7 @@ namespace System.Net.WebSockets.Client.Tests
{
public CancelTest(ITestOutputHelper output) : base(output) { }
+ [ActiveIssue(23151, TestPlatforms.AnyUnix)] // connection opening currently can't be canceled on ManagedHandler
[OuterLoop] // TODO: Issue #11345
[ConditionalTheory(nameof(WebSocketsSupported)), MemberData(nameof(EchoServers))]
public async Task ConnectAsync_Cancel_ThrowsWebSocketExceptionWithMessage(Uri server)
diff --git a/src/System.Net.WebSockets.Client/tests/ClientWebSocketTestBase.cs b/src/System.Net.WebSockets.Client/tests/ClientWebSocketTestBase.cs
index e06bfe3997..d150ebfb5c 100644
--- a/src/System.Net.WebSockets.Client/tests/ClientWebSocketTestBase.cs
+++ b/src/System.Net.WebSockets.Client/tests/ClientWebSocketTestBase.cs
@@ -20,7 +20,7 @@ namespace System.Net.WebSockets.Client.Tests
public static readonly object[][] EchoServers = System.Net.Test.Common.Configuration.WebSockets.EchoServers;
public static readonly object[][] EchoHeadersServers = System.Net.Test.Common.Configuration.WebSockets.EchoHeadersServers;
- public const int TimeOutMilliseconds = 10000;
+ public const int TimeOutMilliseconds = 20000;
public const int CloseDescriptionMaxLength = 123;
public readonly ITestOutputHelper _output;
@@ -84,6 +84,24 @@ namespace System.Net.WebSockets.Client.Tests
}
}
+ protected static async Task<WebSocketReceiveResult> ReceiveEntireMessageAsync(WebSocket ws, ArraySegment<byte> segment, CancellationToken cancellationToken)
+ {
+ int bytesReceived = 0;
+ while (true)
+ {
+ WebSocketReceiveResult r = await ws.ReceiveAsync(segment, cancellationToken);
+ if (r.EndOfMessage)
+ {
+ return new WebSocketReceiveResult(bytesReceived + r.Count, r.MessageType, true, r.CloseStatus, r.CloseStatusDescription);
+ }
+ else
+ {
+ bytesReceived += r.Count;
+ segment = new ArraySegment<byte>(segment.Array, segment.Offset + r.Count, segment.Count - r.Count);
+ }
+ }
+ }
+
public static bool WebSocketsSupported { get { return WebSocketHelper.WebSocketsSupported; } }
}
}
diff --git a/src/System.Net.WebSockets.Client/tests/ConnectTest.cs b/src/System.Net.WebSockets.Client/tests/ConnectTest.cs
index f41b3ffc9a..cde6c660c5 100644
--- a/src/System.Net.WebSockets.Client/tests/ConnectTest.cs
+++ b/src/System.Net.WebSockets.Client/tests/ConnectTest.cs
@@ -69,15 +69,14 @@ namespace System.Net.WebSockets.Client.Tests
Assert.Equal(WebSocketState.Open, cws.State);
byte[] buffer = new byte[65536];
- var segment = new ArraySegment<byte>(buffer, 0, buffer.Length);
WebSocketReceiveResult recvResult;
using (var cts = new CancellationTokenSource(TimeOutMilliseconds))
{
- recvResult = await cws.ReceiveAsync(segment, cts.Token);
+ recvResult = await ReceiveEntireMessageAsync(cws, new ArraySegment<byte>(buffer), cts.Token);
}
Assert.Equal(WebSocketMessageType.Text, recvResult.MessageType);
- string headers = WebSocketData.GetTextFromBuffer(segment);
+ string headers = WebSocketData.GetTextFromBuffer(new ArraySegment<byte>(buffer, 0, recvResult.Count));
Assert.True(headers.Contains("X-CustomHeader1:Value1"));
Assert.True(headers.Contains("X-CustomHeader2:Value2"));
@@ -114,15 +113,14 @@ namespace System.Net.WebSockets.Client.Tests
Assert.Equal(WebSocketState.Open, cws.State);
byte[] buffer = new byte[65536];
- var segment = new ArraySegment<byte>(buffer, 0, buffer.Length);
WebSocketReceiveResult recvResult;
using (var cts = new CancellationTokenSource(TimeOutMilliseconds))
{
- recvResult = await cws.ReceiveAsync(segment, cts.Token);
+ recvResult = await ReceiveEntireMessageAsync(cws, new ArraySegment<byte>(buffer), cts.Token);
}
Assert.Equal(WebSocketMessageType.Text, recvResult.MessageType);
- string headers = WebSocketData.GetTextFromBuffer(segment);
+ string headers = WebSocketData.GetTextFromBuffer(new ArraySegment<byte>(buffer, 0, recvResult.Count));
Assert.Contains($"Host:{logicalHost}", headers, StringComparison.Ordinal);
await cws.CloseAsync(WebSocketCloseStatus.NormalClosure, string.Empty, CancellationToken.None);
@@ -161,15 +159,14 @@ namespace System.Net.WebSockets.Client.Tests
Assert.Equal(WebSocketState.Open, cws.State);
byte[] buffer = new byte[65536];
- var segment = new ArraySegment<byte>(buffer);
WebSocketReceiveResult recvResult;
using (var cts = new CancellationTokenSource(TimeOutMilliseconds))
{
- recvResult = await cws.ReceiveAsync(segment, cts.Token);
+ recvResult = await ReceiveEntireMessageAsync(cws, new ArraySegment<byte>(buffer), cts.Token);
}
Assert.Equal(WebSocketMessageType.Text, recvResult.MessageType);
- string headers = WebSocketData.GetTextFromBuffer(segment);
+ string headers = WebSocketData.GetTextFromBuffer(new ArraySegment<byte>(buffer, 0, recvResult.Count));
Assert.True(headers.Contains("Cookies=Are Yummy"));
Assert.True(headers.Contains("Especially=Chocolate Chip"));
diff --git a/src/System.Net.WebSockets.Client/tests/KeepAliveTest.cs b/src/System.Net.WebSockets.Client/tests/KeepAliveTest.cs
index c56d354092..69216241b4 100644
--- a/src/System.Net.WebSockets.Client/tests/KeepAliveTest.cs
+++ b/src/System.Net.WebSockets.Client/tests/KeepAliveTest.cs
@@ -16,15 +16,16 @@ namespace System.Net.WebSockets.Client.Tests
{
public KeepAliveTest(ITestOutputHelper output) : base(output) { }
+ [ActiveIssue(23204, TargetFrameworkMonikers.Uap)]
[ConditionalFact(nameof(WebSocketsSupported))]
[OuterLoop] // involves long delay
public async Task KeepAlive_LongDelayBetweenSendReceives_Succeeds()
{
- using (ClientWebSocket cws = await WebSocketHelper.GetConnectedWebSocket(System.Net.Test.Common.Configuration.WebSockets.RemoteEchoServer, TimeOutMilliseconds, _output, TimeSpan.FromSeconds(10)))
+ using (ClientWebSocket cws = await WebSocketHelper.GetConnectedWebSocket(System.Net.Test.Common.Configuration.WebSockets.RemoteEchoServer, TimeOutMilliseconds, _output, TimeSpan.FromSeconds(1)))
{
await cws.SendAsync(new ArraySegment<byte>(new byte[1] { 42 }), WebSocketMessageType.Binary, true, CancellationToken.None);
- await Task.Delay(TimeSpan.FromSeconds(60));
+ await Task.Delay(TimeSpan.FromSeconds(10));
byte[] receiveBuffer = new byte[1];
Assert.Equal(1, (await cws.ReceiveAsync(new ArraySegment<byte>(receiveBuffer), CancellationToken.None)).Count);
diff --git a/src/System.Net.WebSockets.Client/tests/SendReceiveTest.cs b/src/System.Net.WebSockets.Client/tests/SendReceiveTest.cs
index d05b3e5bb0..ec7cc95415 100644
--- a/src/System.Net.WebSockets.Client/tests/SendReceiveTest.cs
+++ b/src/System.Net.WebSockets.Client/tests/SendReceiveTest.cs
@@ -285,6 +285,7 @@ namespace System.Net.WebSockets.Client.Tests
}
}
+ [ActiveIssue(23765)]
[OuterLoop] // TODO: Issue #11345
[ConditionalTheory(nameof(WebSocketsSupported)), MemberData(nameof(EchoServers))]
public async Task SendReceive_VaryingLengthBuffers_Success(Uri server)
diff --git a/src/System.Numerics.Vectors/pkg/System.Numerics.Vectors.pkgproj b/src/System.Numerics.Vectors/pkg/System.Numerics.Vectors.pkgproj
index 0a8bbc7c0c..fb09f270ed 100644
--- a/src/System.Numerics.Vectors/pkg/System.Numerics.Vectors.pkgproj
+++ b/src/System.Numerics.Vectors/pkg/System.Numerics.Vectors.pkgproj
@@ -15,14 +15,21 @@
<ProjectReference Include="..\src\System.Numerics.Vectors.csproj" />
</ItemGroup>
<ItemGroup>
- <InboxOnTargetFramework Include="netcoreapp2.0" />
- <InboxOnTargetFramework Include="$(UAPvNextTFM)" />
<InboxOnTargetFramework Include="MonoAndroid10" />
<InboxOnTargetFramework Include="MonoTouch10" />
<InboxOnTargetFramework Include="xamarinios10" />
<InboxOnTargetFramework Include="xamarinmac20" />
<InboxOnTargetFramework Include="xamarintvos10" />
<InboxOnTargetFramework Include="xamarinwatchos10" />
+
+ <!-- Since UAP and .NETCoreApp are package based we still want to enable
+ OOBing libraries that happen to overlap with their framework package.
+ This avoids us having to lock the API in our NuGet packages just
+ to match what shipped inbox: since we can provide a new library
+ we can update it to add API without raising the netstandard version. -->
+ <ValidatePackageSuppression Include="TreatAsOutOfBox">
+ <Value>.NETCoreApp;UAP</Value>
+ </ValidatePackageSuppression>
</ItemGroup>
<Import Project="$([MSBuild]::GetDirectoryNameOfFileAbove($(MSBuildThisFileDirectory), dir.targets))\dir.targets" />
</Project> \ No newline at end of file
diff --git a/src/System.ObjectModel/src/System/Collections/ObjectModel/ObservableCollection.cs b/src/System.ObjectModel/src/System/Collections/ObjectModel/ObservableCollection.cs
index b4111394da..7afcffd7c7 100644
--- a/src/System.ObjectModel/src/System/Collections/ObjectModel/ObservableCollection.cs
+++ b/src/System.ObjectModel/src/System/Collections/ObjectModel/ObservableCollection.cs
@@ -270,7 +270,7 @@ namespace System.Collections.ObjectModel
}
/// <summary>
- /// Disallow reentrant attempts to change this collection. E.g. a event handler
+ /// Disallow reentrant attempts to change this collection. E.g. an event handler
/// of the CollectionChanged event is not allowed to make changes to this collection.
/// </summary>
/// <remarks>
diff --git a/src/System.Private.DataContractSerialization/src/System/Runtime/Serialization/CollectionDataContract.cs b/src/System.Private.DataContractSerialization/src/System/Runtime/Serialization/CollectionDataContract.cs
index 21d871b7a5..f72b25ab9f 100644
--- a/src/System.Private.DataContractSerialization/src/System/Runtime/Serialization/CollectionDataContract.cs
+++ b/src/System.Private.DataContractSerialization/src/System/Runtime/Serialization/CollectionDataContract.cs
@@ -1299,6 +1299,10 @@ namespace System.Runtime.Serialization
if (addMethod == null)
{
Type[] parentInterfaceTypes = interfaceType.GetInterfaces();
+ // The for loop below depeneds on the order for the items in parentInterfaceTypes, which
+ // doesnt' seem right. But it's the behavior of DCS on the full framework.
+ // Sorting the array to make sure the behavior is consistent with Desktop's.
+ Array.Sort(parentInterfaceTypes, (x, y) => string.Compare(x.FullName, y.FullName));
foreach (Type parentInterfaceType in parentInterfaceTypes)
{
if (IsKnownInterface(parentInterfaceType))
diff --git a/src/System.Private.DataContractSerialization/src/System/Runtime/Serialization/Json/XmlJsonWriter.cs b/src/System.Private.DataContractSerialization/src/System/Runtime/Serialization/Json/XmlJsonWriter.cs
index 03227916ae..bdf92cb05d 100644
--- a/src/System.Private.DataContractSerialization/src/System/Runtime/Serialization/Json/XmlJsonWriter.cs
+++ b/src/System.Private.DataContractSerialization/src/System/Runtime/Serialization/Json/XmlJsonWriter.cs
@@ -23,14 +23,45 @@ namespace System.Runtime.Serialization.Json
private const char WHITESPACE = ' ';
private const char CARRIAGE_RETURN = '\r';
private const char NEWLINE = '\n';
- private const char BACKSPACE = '\b';
- private const char FORM_FEED = '\f';
- private const char HORIZONTAL_TABULATION = '\t';
private const string xmlNamespace = "http://www.w3.org/XML/1998/namespace";
private const string xmlnsNamespace = "http://www.w3.org/2000/xmlns/";
// This array was part of a perf improvement for escaping characters < WHITESPACE.
- private static readonly string[] s_escapedJsonStringTable = CreateEscapedJsonStringTable();
+ private static readonly string[] s_escapedJsonStringTable =
+ {
+ "\\u0000",
+ "\\u0001",
+ "\\u0002",
+ "\\u0003",
+ "\\u0004",
+ "\\u0005",
+ "\\u0006",
+ "\\u0007",
+ "\\b",
+ "\\t",
+ "\\n",
+ "\\u000b",
+ "\\f",
+ "\\r",
+ "\\u000e",
+ "\\u000f",
+ "\\u0010",
+ "\\u0011",
+ "\\u0012",
+ "\\u0013",
+ "\\u0014",
+ "\\u0015",
+ "\\u0016",
+ "\\u0017",
+ "\\u0018",
+ "\\u0019",
+ "\\u001a",
+ "\\u001b",
+ "\\u001c",
+ "\\u001d",
+ "\\u001e",
+ "\\u001f"
+ };
private static BinHexEncoding s_binHexEncoding;
@@ -72,20 +103,6 @@ namespace System.Runtime.Serialization.Json
InitializeWriter();
}
- private static string[] CreateEscapedJsonStringTable()
- {
- var table = new string[WHITESPACE];
- for (int ch = 0; ch < WHITESPACE; ch++)
- {
- char abbrev;
- table[ch] = TryEscapeControlCharacter((char)ch, out abbrev) ?
- string.Concat(BACK_SLASH, abbrev) :
- string.Format(CultureInfo.InvariantCulture, "\\u{0:x4}", ch);
- }
-
- return table;
- }
-
private enum JsonDataType
{
None,
@@ -1418,33 +1435,6 @@ namespace System.Runtime.Serialization.Json
}
}
- private static bool TryEscapeControlCharacter(char ch, out char abbrev)
- {
- switch (ch)
- {
- case BACKSPACE:
- abbrev = 'b';
- break;
- case FORM_FEED:
- abbrev = 'f';
- break;
- case NEWLINE:
- abbrev = 'n';
- break;
- case CARRIAGE_RETURN:
- abbrev = 'r';
- break;
- case HORIZONTAL_TABULATION:
- abbrev = 't';
- break;
- default:
- abbrev = ' ';
- return false;
- }
-
- return true;
- }
-
private void WriteIndent()
{
for (int i = 0; i < _indentLevel; i++)
diff --git a/src/System.Private.DataContractSerialization/src/System/Runtime/Serialization/XmlObjectSerializerWriteContext.cs b/src/System.Private.DataContractSerialization/src/System/Runtime/Serialization/XmlObjectSerializerWriteContext.cs
index 802e33e164..0d11ca950d 100644
--- a/src/System.Private.DataContractSerialization/src/System/Runtime/Serialization/XmlObjectSerializerWriteContext.cs
+++ b/src/System.Private.DataContractSerialization/src/System/Runtime/Serialization/XmlObjectSerializerWriteContext.cs
@@ -183,18 +183,16 @@ namespace System.Runtime.Serialization
protected virtual void SerializeWithXsiType(XmlWriterDelegator xmlWriter, object obj, RuntimeTypeHandle objectTypeHandle, Type objectType, int declaredTypeID, RuntimeTypeHandle declaredTypeHandle, Type declaredType)
{
bool verifyKnownType = false;
-#if !uapaot
DataContract dataContract;
if (declaredType.IsInterface && CollectionDataContract.IsCollectionInterface(declaredType))
{
+#if !uapaot
dataContract = GetDataContractSkipValidation(DataContract.GetId(objectTypeHandle), objectTypeHandle, objectType);
if (OnHandleIsReference(xmlWriter, dataContract, obj))
return;
dataContract = GetDataContract(declaredTypeHandle, declaredType);
#else
- DataContract dataContract = DataContract.GetDataContract(declaredType);
- if (dataContract.TypeIsInterface && dataContract.TypeIsCollectionInterface)
- {
+ dataContract = DataContract.GetDataContract(declaredType);
if (OnHandleIsReference(xmlWriter, dataContract, obj))
return;
if (this.Mode == SerializationMode.SharedType && dataContract.IsValidContract(this.Mode))
diff --git a/src/System.Private.Reflection.Metadata.Ecma335/src/Resources/Strings.resx b/src/System.Private.Reflection.Metadata.Ecma335/src/Resources/Strings.resx
index 9d38c67902..75779ebbda 100644
--- a/src/System.Private.Reflection.Metadata.Ecma335/src/Resources/Strings.resx
+++ b/src/System.Private.Reflection.Metadata.Ecma335/src/Resources/Strings.resx
@@ -410,10 +410,10 @@
<value>Invalid exception region bounds: start offset ({0}) is greater than end offset ({1}).</value>
</data>
<data name="ArrayInitializedStateNotEqual" xml:space="preserve">
- <value>Object is not a array with the same initialization state as the array to compare it to.</value>
+ <value>Object is not an array with the same initialization state as the array to compare it to.</value>
</data>
<data name="ArrayLengthsNotEqual" xml:space="preserve">
- <value>Object is not a array with the same number of elements as the array to compare it to.</value>
+ <value>Object is not an array with the same number of elements as the array to compare it to.</value>
</data>
<data name="CannotFindOldValue" xml:space="preserve">
<value>Cannot find the old value</value>
diff --git a/src/System.Private.Xml/src/Resources/Strings.resx b/src/System.Private.Xml/src/Resources/Strings.resx
index f734e7146d..c3943b26f7 100644
--- a/src/System.Private.Xml/src/Resources/Strings.resx
+++ b/src/System.Private.Xml/src/Resources/Strings.resx
@@ -3346,19 +3346,19 @@
<value>Uppercase-First sorting option is not supported.</value>
</data>
<data name="XmlPregenTypeDynamic" xml:space="preserve">
- <value>Cannot pre-generate serialization assembly for type '{0}'. Pre-generation of serialization assemblies is not supported for dynamic types. Save the assembly and load it from disk to use it with XmlSerialization.</value>
+ <value>Cannot pre-generate serialization code for type '{0}'. Pre-generation of serialization assemblies is not supported for dynamic types. Save the assembly and load it from disk to use it with XmlSerialization.</value>
</data>
<data name="XmlPregenOrphanType" xml:space="preserve">
<value>Cannot pre-generate serializer for multiple assemblies. Type '{0}' does not belong to assembly {1}.</value>
</data>
<data name="ErrSerializerExists" xml:space="preserve">
- <value>Cannot generate serialization assembly {0} because it already exists. Use /{1} to force an overwrite of the existing assembly.</value>
+ <value>Cannot generate serialization code {0} because the code file already exists. Use /{1} to force an overwrite of the existing file.</value>
</data>
<data name="ErrDirectoryExists" xml:space="preserve">
- <value>Cannot generate serialization assembly '{0}' because a directory with the same name already exists.</value>
+ <value>Cannot generate serialization code '{0}' because a directory with the same name already exists.</value>
</data>
<data name="ErrDirectoryNotExists" xml:space="preserve">
- <value>Cannot generate serialization assembly '{0}' because directory {1} doesn't exist.</value>
+ <value>Cannot generate serialization code '{0}' because directory {1} doesn't exist.</value>
</data>
<data name="ErrInvalidArgument" xml:space="preserve">
<value>Ignoring invalid command line argument: '{0}'.</value>
@@ -3372,14 +3372,14 @@
<data name="ErrAssembly" xml:space="preserve">
<value>The name of the source assembly.</value>
</data>
- <data name="InfoGeneratedAssembly" xml:space="preserve">
- <value>Generated serialization assembly for assembly {0} --&gt; '{1}'.</value>
+ <data name="InfoGeneratedFile" xml:space="preserve">
+ <value>Generated serialization code for assembly {0} --&gt; '{1}'.</value>
</data>
- <data name="InfoAssemblyName" xml:space="preserve">
- <value>Serialization Assembly Name: {0}.</value>
+ <data name="InfoFileName" xml:space="preserve">
+ <value>Serialization Code File Name: {0}.</value>
</data>
<data name="ErrGenerationFailed" xml:space="preserve">
- <value>Sgen utility failed to pregenerate serialization assembly for {0}.</value>
+ <value>Sgen utility failed to pregenerate serialization code for {0}.</value>
</data>
<data name="ErrorDetails" xml:space="preserve">
<value>Error: {0}.</value>
@@ -3399,7 +3399,53 @@
<data name="InfoNoSerializableTypes" xml:space="preserve">
<value>Assembly '{0}' does not contain any types that can be serialized using XmlSerializer.</value>
</data>
+ <data name="InfoIgnoreType" xml:space="preserve">
+ <value>Ignoring '{0}'.</value>
+ </data>
<data name="FailLoadAssemblyUnderPregenMode" xml:space="preserve">
<value>"Fail to load assembly {0} or {0} doesn't exist under PreGen Mode.</value>
</data>
+ <data name="HelpDescription" xml:space="preserve">
+ <value>Generates serialization code for use with XmlSerializer.
+The utility allows developers to pre-generate code for serialization
+building and deploying the assemblies with the application.
+ </value>
+ </data>
+ <data name="HelpUsage" xml:space="preserve">
+ <value>
+Usage: dotnet {0} [[/assembly:&lt;assembly name&gt;] | [&lt;assembly file location&gt;]]
+ [/type:] [/debug].
+ </value>
+ </data>
+ <data name="HelpDevOptions" xml:space="preserve">
+ <value> Developer options:</value>
+ </data>
+ <data name="HelpAssembly" xml:space="preserve">
+ <value> {0} Assembly location or display name. Short form is '{1}'.</value>
+ </data>
+ <data name="HelpType" xml:space="preserve">
+ <value> {0} Generate code for serialization/deserialization of the
+ specified type from the input assembly. Short form is '{1}'.</value>
+ </data>
+ <data name="HelpForce" xml:space="preserve">
+ <value> {0} Forces overwrite of a previously generated assembly.
+ Short form is '{1}'.</value>
+ </data>
+ <data name="HelpProxy" xml:space="preserve">
+ <value> {0} Generate serialization code only for proxy classes and web
+ method parameters. Short form is '{1}'.</value>
+ </data>
+ <data name="HelpOut" xml:space="preserve">
+ <value> {0} Output directory name (default: target assembly location).
+ Short form is '{1}'.</value>
+ </data>
+ <data name="HelpMiscOptions" xml:space="preserve">
+ <value> Miscellaneous options:</value>
+ </data>
+ <data name="HelpHelp" xml:space="preserve">
+ <value> {0} or {1} Show this message</value>
+ </data>
+ <data name="MoreHelp" xml:space="preserve">
+ <value>If you would like more help, please type "sgen {0}".</value>
+ </data>
</root> \ No newline at end of file
diff --git a/src/System.Private.Xml/src/System/Xml/Core/XmlReaderSettings.cs b/src/System.Private.Xml/src/System/Xml/Core/XmlReaderSettings.cs
index 58304768d2..e72c3abcb8 100644
--- a/src/System.Private.Xml/src/System/Xml/Core/XmlReaderSettings.cs
+++ b/src/System.Private.Xml/src/System/Xml/Core/XmlReaderSettings.cs
@@ -57,6 +57,12 @@ namespace System.Xml
// read-only flag
private bool _isReadOnly;
+ // Creation of validating readers is hidden behind a delegate which is only initialized if the ValidationType
+ // property is set. This is for AOT builds where the tree shaker can reduce the validating readers away
+ // if nobody calls the ValidationType setter. Might also help with non-AOT build when ILLinker is used.
+ delegate XmlReader AddValidationFunc(XmlReader reader, XmlResolver resolver, bool addConformanceWrapper);
+ private AddValidationFunc _addValidationFunc;
+
//
// Constructor
//
@@ -317,6 +323,12 @@ namespace System.Xml
{
CheckReadOnly("ValidationType");
+ // This introduces a dependency on the validation readers and along with that
+ // on XmlSchema and so on. For AOT builds this brings in a LOT of code
+ // which we would like to avoid unless it's needed. So the first approximation
+ // is to only reference this method when somebody explicitly sets the ValidationType.
+ _addValidationFunc = AddValidationInternal;
+
if ((uint)value > (uint)ValidationType.Schema)
{
throw new ArgumentOutOfRangeException(nameof(value));
@@ -574,34 +586,68 @@ namespace System.Xml
internal XmlReader AddValidation(XmlReader reader)
{
+ XmlResolver resolver = null;
if (_validationType == ValidationType.Schema)
{
- XmlResolver resolver = GetXmlResolver_CheckConfig();
+ resolver = GetXmlResolver_CheckConfig();
if (resolver == null &&
!this.IsXmlResolverSet)
{
resolver = new XmlUrlResolver();
}
- reader = new XsdValidatingReader(reader, resolver, this);
}
- else if (_validationType == ValidationType.DTD)
+
+ return AddValidationAndConformanceInternal(reader, resolver, addConformanceWrapper: false);
+ }
+
+ private XmlReader AddValidationAndConformanceWrapper(XmlReader reader)
+ {
+ XmlResolver resolver = null;
+ if (_validationType == ValidationType.Schema)
{
- reader = CreateDtdValidatingReader(reader);
+ resolver = GetXmlResolver_CheckConfig();
}
+
+ return AddValidationAndConformanceInternal(reader, resolver, addConformanceWrapper: true);
+ }
+
+ private XmlReader AddValidationAndConformanceInternal(XmlReader reader, XmlResolver resolver, bool addConformanceWrapper)
+ {
+ // We have to avoid calling the _addValidationFunc delegate if there's no validation to setup
+ // since it would not be initialized (to allow AOT compilers to reduce it away).
+ // So if that's the case and we still need conformance wrapper add it here directly.
+ // This is a slight code duplication, but it's necessary due to ordering constrains
+ // of the reader wrapping as described in AddValidationInternal.
+ if (_validationType == ValidationType.None)
+ {
+ if (addConformanceWrapper)
+ {
+ reader = AddConformanceWrapper(reader);
+ }
+ }
+ else
+ {
+ reader = _addValidationFunc(reader, resolver, addConformanceWrapper);
+ }
+
return reader;
}
- private XmlReader AddValidationAndConformanceWrapper(XmlReader reader)
+ private XmlReader AddValidationInternal(XmlReader reader, XmlResolver resolver, bool addConformanceWrapper)
{
// wrap with DTD validating reader
if (_validationType == ValidationType.DTD)
{
reader = CreateDtdValidatingReader(reader);
}
- // add conformance checking (must go after DTD validation because XmlValidatingReader works only on XmlTextReader),
- // but before XSD validation because of typed value access
- reader = AddConformanceWrapper(reader);
+
+ if (addConformanceWrapper)
+ {
+ // add conformance checking (must go after DTD validation because XmlValidatingReader works only on XmlTextReader),
+ // but before XSD validation because of typed value access
+ reader = AddConformanceWrapper(reader);
+ }
if (_validationType == ValidationType.Schema)
{
diff --git a/src/System.Private.Xml/src/System/Xml/Core/XmlValidatingReaderImpl.cs b/src/System.Private.Xml/src/System/Xml/Core/XmlValidatingReaderImpl.cs
index 191db08572..c2c10347e7 100644
--- a/src/System.Private.Xml/src/System/Xml/Core/XmlValidatingReaderImpl.cs
+++ b/src/System.Private.Xml/src/System/Xml/Core/XmlValidatingReaderImpl.cs
@@ -57,7 +57,7 @@ namespace System.Xml
{
_eventHandler(_reader, new ValidationEventArgs((XmlSchemaException)exception, severity));
}
- else if (_reader.ValidationType != ValidationType.None && severity == XmlSeverityType.Error)
+ else if (_reader._validationType != ValidationType.None && severity == XmlSeverityType.Error)
{
throw exception;
}
diff --git a/src/System.Private.Xml/src/System/Xml/Core/XsdValidatingReader.cs b/src/System.Private.Xml/src/System/Xml/Core/XsdValidatingReader.cs
index afc0d51c94..0c4862631e 100644
--- a/src/System.Private.Xml/src/System/Xml/Core/XsdValidatingReader.cs
+++ b/src/System.Private.Xml/src/System/Xml/Core/XsdValidatingReader.cs
@@ -247,7 +247,7 @@ namespace System.Xml
string prefix = _validator.GetDefaultAttributePrefix(_cachedNode.Namespace);
if (prefix != null && prefix.Length != 0)
{
- return string.Concat(prefix + ":" + _cachedNode.LocalName);
+ return prefix + ":" + _cachedNode.LocalName;
}
return _cachedNode.LocalName;
}
diff --git a/src/System.Private.Xml/src/System/Xml/Schema/XdrBuilder.cs b/src/System.Private.Xml/src/System/Xml/Schema/XdrBuilder.cs
index 40144b2650..47425b23eb 100644
--- a/src/System.Private.Xml/src/System/Xml/Schema/XdrBuilder.cs
+++ b/src/System.Private.Xml/src/System/Xml/Schema/XdrBuilder.cs
@@ -1120,7 +1120,7 @@ namespace System.Xml.Schema
goto cleanup;
}
- // a attributes of type id is not supposed to have a default value
+ // an attribute of type id is not supposed to have a default value
if (builder._AttributeDef._Default != null && ttype == XmlTokenizedType.ID)
{
code = SR.Sch_DefaultIdValue;
diff --git a/src/System.Private.Xml/src/System/Xml/Serialization/Compilation.cs b/src/System.Private.Xml/src/System/Xml/Serialization/Compilation.cs
index 09fb8b4509..73f1f8fe54 100644
--- a/src/System.Private.Xml/src/System/Xml/Serialization/Compilation.cs
+++ b/src/System.Private.Xml/src/System/Xml/Serialization/Compilation.cs
@@ -233,12 +233,6 @@ namespace System.Xml.Serialization
}
#if XMLSERIALIZERGENERATOR
- internal static class ThisAssembly
- {
- internal const string Version = "1.0.0.0";
- internal const string InformationalVersion = "1.0.0.0";
- }
-
private static string GenerateAssemblyId(Type type)
{
Module[] modules = type.Assembly.GetModules();
diff --git a/src/System.Private.Xml/src/System/Xml/Serialization/XmlSerializer.cs b/src/System.Private.Xml/src/System/Xml/Serialization/XmlSerializer.cs
index 6ff3a42cb6..5d6b2b7f4f 100644
--- a/src/System.Private.Xml/src/System/Xml/Serialization/XmlSerializer.cs
+++ b/src/System.Private.Xml/src/System/Xml/Serialization/XmlSerializer.cs
@@ -115,6 +115,22 @@ namespace System.Xml.Serialization
public virtual XmlSerializer GetSerializer(Type type) { throw new NotSupportedException(); }
}
+ // This enum is intentionally kept outside of the XmlSerializer class since if it would be a subclass
+ // of XmlSerializer, then any access to this enum would be treated by AOT compilers as access to the XmlSerializer
+ // as well, which has a large static ctor which brings in a lot of code. So keeping the enum separate
+ // makes sure that using just the enum itself doesn't bring in the whole of serialization code base.
+#if FEATURE_SERIALIZATION_UAPAOT
+ public enum SerializationMode
+#else
+ internal enum SerializationMode
+#endif
+ {
+ CodeGenOnly,
+ ReflectionOnly,
+ ReflectionAsBackup,
+ PreGenOnly
+ }
+
/// <include file='doc\XmlSerializer.uex' path='docs/doc[@for="XmlSerializer"]/*' />
/// <devdoc>
/// <para>[To be supplied.]</para>
@@ -122,18 +138,6 @@ namespace System.Xml.Serialization
public class XmlSerializer
{
#if FEATURE_SERIALIZATION_UAPAOT
- public enum SerializationMode
-#else
- internal enum SerializationMode
-#endif
- {
- CodeGenOnly,
- ReflectionOnly,
- ReflectionAsBackup,
- PreGenOnly
- }
-
-#if FEATURE_SERIALIZATION_UAPAOT
public static SerializationMode Mode { get; set; } = SerializationMode.ReflectionAsBackup;
#else
internal static SerializationMode Mode { get; set; } = SerializationMode.ReflectionAsBackup;
diff --git a/src/System.Private.Xml/tests/Readers/CharCheckingReader/CharReaderTests.cs b/src/System.Private.Xml/tests/Readers/CharCheckingReader/CharReaderTests.cs
index 8f6505e90a..71c061ccd3 100644
--- a/src/System.Private.Xml/tests/Readers/CharCheckingReader/CharReaderTests.cs
+++ b/src/System.Private.Xml/tests/Readers/CharCheckingReader/CharReaderTests.cs
@@ -2,6 +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.Collections;
+using System.Collections.Generic;
+using System.Text;
using OLEDB.Test.ModuleCore;
using Xunit;
@@ -9,352 +12,67 @@ namespace System.Xml.Tests
{
public partial class CharCheckingReaderTest : CGenericTestModule
{
- private static void RunTestCaseAsync(Func<CTestBase> testCaseGenerator)
+ [Theory]
+ [XmlTests(nameof(Create))]
+ public void RunTests(XunitTestCase testCase)
{
- CModInfo.CommandLine = "/async";
- RunTestCase(testCaseGenerator);
+ testCase.Run();
}
- private static void RunTestCase(Func<CTestBase> testCaseGenerator)
+ public static CTestModule Create()
{
var module = new CharCheckingReaderTest();
module.Init(null);
- module.AddChild(testCaseGenerator());
- module.Execute();
-
- Assert.Equal(0, module.FailCount);
- }
-
- private static void RunTest(Func<CTestBase> testCaseGenerator)
- {
- RunTestCase(testCaseGenerator);
- RunTestCaseAsync(testCaseGenerator);
- }
-
- [Fact]
- [OuterLoop]
- public static void ErrorConditionReader()
- {
- RunTest(() => new TCErrorConditionReader() { Attribute = new TestCase() { Name = "ErrorCondition", Desc = "CharCheckingReader" } });
- }
-
- [Fact]
- [OuterLoop]
- public static void DepthReader()
- {
- RunTest(() => new TCDepthReader() { Attribute = new TestCase() { Name = "Depth", Desc = "CharCheckingReader" } });
- }
-
- [Fact]
- [OuterLoop]
- public static void NamespaceReader()
- {
- RunTest(() => new TCNamespaceReader() { Attribute = new TestCase() { Name = "Namespace", Desc = "CharCheckingReader" } });
- }
-
- [Fact]
- [OuterLoop]
- public static void IsEmptyElementReader()
- {
- RunTest(() => new TCIsEmptyElementReader() { Attribute = new TestCase() { Name = "IsEmptyElement", Desc = "CharCheckingReader" } });
- }
-
- [Fact]
- [OuterLoop]
- public static void XmlSpaceReader()
- {
- RunTest(() => new TCXmlSpaceReader() { Attribute = new TestCase() { Name = "XmlSpace", Desc = "CharCheckingReader" } });
- }
-
- [Fact]
- [OuterLoop]
- public static void XmlLangReader()
- {
- RunTest(() => new TCXmlLangReader() { Attribute = new TestCase() { Name = "XmlLang", Desc = "CharCheckingReader" } });
- }
-
- [Fact]
- [OuterLoop]
- public static void SkipReader()
- {
- RunTest(() => new TCSkipReader() { Attribute = new TestCase() { Name = "Skip", Desc = "CharCheckingReader" } });
- }
-
- [Fact]
- [OuterLoop]
- public static void InvalidXMLReader()
- {
- RunTest(() => new TCInvalidXMLReader() { Attribute = new TestCase() { Name = "InvalidXML", Desc = "CharCheckingReader" } });
- }
-
- [Fact]
- [OuterLoop]
- public static void ReadOuterXmlReader()
- {
- RunTest(() => new TCReadOuterXmlReader() { Attribute = new TestCase() { Name = "ReadOuterXml", Desc = "CharCheckingReader" } });
- }
-
- [Fact]
- [OuterLoop]
- public static void AttributeAccessReader()
- {
- RunTest(() => new TCAttributeAccessReader() { Attribute = new TestCase() { Name = "AttributeAccess", Desc = "CharCheckingReader" } });
- }
-
- [Fact]
- [OuterLoop]
- public static void ThisNameReader()
- {
- RunTest(() => new TCThisNameReader() { Attribute = new TestCase() { Name = "This(Name) and This(Name, Namespace)", Desc = "CharCheckingReader" } });
- }
-
- [Fact]
- [OuterLoop]
- public static void MoveToAttributeReader()
- {
- RunTest(() => new TCMoveToAttributeReader() { Attribute = new TestCase() { Name = "MoveToAttribute(Name) and MoveToAttribute(Name, Namespace)", Desc = "CharCheckingReader" } });
- }
-
- [Fact]
- [OuterLoop]
- public static void GetAttributeOrdinalReader()
- {
- RunTest(() => new TCGetAttributeOrdinalReader() { Attribute = new TestCase() { Name = "GetAttribute (Ordinal)", Desc = "CharCheckingReader" } });
- }
-
- [Fact]
- [OuterLoop]
- public static void GetAttributeNameReader()
- {
- RunTest(() => new TCGetAttributeNameReader() { Attribute = new TestCase() { Name = "GetAttribute(Name) and GetAttribute(Name, Namespace)", Desc = "CharCheckingReader" } });
- }
-
- [Fact]
- [OuterLoop]
- public static void ThisOrdinalReader()
- {
- RunTest(() => new TCThisOrdinalReader() { Attribute = new TestCase() { Name = "This [Ordinal]", Desc = "CharCheckingReader" } });
- }
-
- [Fact]
- [OuterLoop]
- public static void MoveToAttributeOrdinalReader()
- {
- RunTest(() => new TCMoveToAttributeOrdinalReader() { Attribute = new TestCase() { Name = "MoveToAttribute(Ordinal)", Desc = "CharCheckingReader" } });
- }
-
- [Fact]
- [OuterLoop]
- public static void MoveToFirstAttributeReader()
- {
- RunTest(() => new TCMoveToFirstAttributeReader() { Attribute = new TestCase() { Name = "MoveToFirstAttribute()", Desc = "CharCheckingReader" } });
- }
-
- [Fact]
- [OuterLoop]
- public static void MoveToNextAttributeReader()
- {
- RunTest(() => new TCMoveToNextAttributeReader() { Attribute = new TestCase() { Name = "MoveToNextAttribute()", Desc = "CharCheckingReader" } });
- }
-
- [Fact]
- [OuterLoop]
- public static void AttributeTestReader()
- {
- RunTest(() => new TCAttributeTestReader() { Attribute = new TestCase() { Name = "Attribute Test when NodeType != Attributes", Desc = "CharCheckingReader" } });
- }
-
- [Fact]
- [OuterLoop]
- public static void AttributeXmlDeclarationReader()
- {
- RunTest(() => new TCAttributeXmlDeclarationReader() { Attribute = new TestCase() { Name = "Attributes test on XmlDeclaration", Desc = "CharCheckingReader" } });
- }
-
- [Fact]
- [OuterLoop]
- public static void XmlnsReader()
- {
- RunTest(() => new TCXmlnsReader() { Attribute = new TestCase() { Name = "xmlns as local name", Desc = "CharCheckingReader" } });
- }
-
- [Fact]
- [OuterLoop]
- public static void XmlnsPrefixReader()
- {
- RunTest(() => new TCXmlnsPrefixReader() { Attribute = new TestCase() { Name = "bounded namespace to xmlns prefix", Desc = "CharCheckingReader" } });
- }
-
- [Fact]
- [OuterLoop]
- public static void ReadInnerXmlReader()
- {
- RunTest(() => new TCReadInnerXmlReader() { Attribute = new TestCase() { Name = "ReadInnerXml", Desc = "CharCheckingReader" } });
- }
- [Fact]
- [OuterLoop]
- public static void MoveToContentReader()
- {
- RunTest(() => new TCMoveToContentReader() { Attribute = new TestCase() { Name = "MoveToContent", Desc = "CharCheckingReader" } });
- }
-
- [Fact]
- [OuterLoop]
- public static void IsStartElementReader()
- {
- RunTest(() => new TCIsStartElementReader() { Attribute = new TestCase() { Name = "IsStartElement", Desc = "CharCheckingReader" } });
- }
-
- [Fact]
- [OuterLoop]
- public static void ReadStartElementReader()
- {
- RunTest(() => new TCReadStartElementReader() { Attribute = new TestCase() { Name = "ReadStartElement", Desc = "CharCheckingReader" } });
- }
-
- [Fact]
- [OuterLoop]
- public static void ReadEndElementReader()
- {
- RunTest(() => new TCReadEndElementReader() { Attribute = new TestCase() { Name = "ReadEndElement", Desc = "CharCheckingReader" } });
- }
- [Fact]
- [OuterLoop]
- public static void ResolveEntityReader()
- {
- RunTest(() => new TCResolveEntityReader() { Attribute = new TestCase() { Name = "ResolveEntity and ReadAttributeValue", Desc = "CharCheckingReader" } });
- }
-
- [Fact]
- [OuterLoop]
- public static void HasValueReader()
- {
- RunTest(() => new TCHasValueReader() { Attribute = new TestCase() { Name = "HasValue", Desc = "CharCheckingReader" } });
- }
-
- [Fact]
- [OuterLoop]
- public static void ReadAttributeValueReader()
- {
- RunTest(() => new TCReadAttributeValueReader() { Attribute = new TestCase() { Name = "ReadAttributeValue", Desc = "CharCheckingReader" } });
- }
- [Fact]
- [OuterLoop]
- public static void ReadReader()
- {
- RunTest(() => new TCReadReader() { Attribute = new TestCase() { Name = "Read", Desc = "CharCheckingReader" } });
- }
-
- [Fact]
- [OuterLoop]
- public static void MoveToElementReader()
- {
- RunTest(() => new TCMoveToElementReader() { Attribute = new TestCase() { Name = "MoveToElement", Desc = "CharCheckingReader" } });
- }
-
- [Fact]
- [OuterLoop]
- public static void DisposeReader()
- {
- RunTest(() => new TCDisposeReader() { Attribute = new TestCase() { Name = "Dispose", Desc = "CharCheckingReader" } });
- }
-
- [Fact]
- [OuterLoop]
- public static void BufferBoundariesReader()
- {
- RunTest(() => new TCBufferBoundariesReader() { Attribute = new TestCase() { Name = "Buffer Boundaries", Desc = "CharCheckingReader" } });
- }
-
- [Fact]
- [OuterLoop]
- public static void XmlNodeIntegrityTestFileBeforeRead()
- {
- RunTest(() => new TCXmlNodeIntegrityTestFile() { Attribute = new TestCase() { Name = "BeforeRead", Desc = "BeforeRead" } });
- }
-
- [Fact]
- [OuterLoop]
- public static void XmlNodeIntegrityTestFileAfterCloseInMiddle()
- {
- RunTest(() => new TCXmlNodeIntegrityTestFile() { Attribute = new TestCase() { Name = "AfterCloseInTheMiddle", Desc = "AfterCloseInTheMiddle" } });
- }
-
- [Fact]
- [OuterLoop]
- public static void XmlNodeIntegrityTestFileAfterClose()
- {
- RunTest(() => new TCXmlNodeIntegrityTestFile() { Attribute = new TestCase() { Name = "AfterClose", Desc = "AfterClose" } });
- }
-
- [Fact]
- [OuterLoop]
- public static void XmlNodeIntegrityTestFileAfterReadIsFalse()
- {
- RunTest(() => new TCXmlNodeIntegrityTestFile() { Attribute = new TestCase() { Name = "AfterReadIsFalse", Desc = "AfterReadIsFalse" } });
- }
-
- [Fact]
- [OuterLoop]
- public static void ReadSubtreeReader()
- {
- RunTest(() => new TCReadSubtreeReader() { Attribute = new TestCase() { Name = "Read Subtree", Desc = "CharCheckingReader" } });
- }
-
- [Fact]
- [OuterLoop]
- public static void ReadToDescendantReader()
- {
- RunTest(() => new TCReadToDescendantReader() { Attribute = new TestCase() { Name = "ReadToDescendant", Desc = "CharCheckingReader" } });
- }
-
- [Fact]
- [OuterLoop]
- public static void ReadToNextSiblingReader()
- {
- RunTest(() => new TCReadToNextSiblingReader() { Attribute = new TestCase() { Name = "ReadToNextSibling", Desc = "CharCheckingReader" } });
- }
-
- [Fact]
- [OuterLoop]
- public static void ReadValueReader()
- {
- RunTest(() => new TCReadValueReader() { Attribute = new TestCase() { Name = "ReadValue", Desc = "CharCheckingReader" } });
- }
-
- [Fact]
- [OuterLoop]
- public static void ReadContentAsBase64Reader()
- {
- RunTest(() => new TCReadContentAsBase64Reader() { Attribute = new TestCase() { Name = "ReadContentAsBase64", Desc = "CharCheckingReader" } });
- }
- [Fact]
- [OuterLoop]
- public static void ReadElementContentAsBase64Reader()
- {
- RunTest(() => new TCReadElementContentAsBase64Reader() { Attribute = new TestCase() { Name = "ReadElementContentAsBase64", Desc = "CharCheckingReader" } });
- }
-
- [Fact]
- [OuterLoop]
- public static void ReadContentAsBinHexReader()
- {
- RunTest(() => new TCReadContentAsBinHexReader() { Attribute = new TestCase() { Name = "ReadContentAsBinHex", Desc = "CharCheckingReader" } });
- }
-
- [Fact]
- [OuterLoop]
- public static void ReadElementContentAsBinHexReader()
- {
- RunTest(() => new TCReadElementContentAsBinHexReader() { Attribute = new TestCase() { Name = "ReadElementContentAsBinHex", Desc = "CharCheckingReader" } });
- }
-
- [Fact]
- [OuterLoop]
- public static void ReadToFollowingReader()
- {
- RunTest(() => new TCReadToFollowingReader() { Attribute = new TestCase() { Name = "ReadToFollowing", Desc = "CharCheckingReader" } });
+ module.AddChild(new TCErrorConditionReader() { Attribute = new TestCase() { Name = "ErrorCondition", Desc = "CharCheckingReader" } });
+ module.AddChild(new TCDepthReader() { Attribute = new TestCase() { Name = "Depth", Desc = "CharCheckingReader" } });
+ module.AddChild(new TCNamespaceReader() { Attribute = new TestCase() { Name = "Namespace", Desc = "CharCheckingReader" } });
+ module.AddChild(new TCIsEmptyElementReader() { Attribute = new TestCase() { Name = "IsEmptyElement", Desc = "CharCheckingReader" } });
+ module.AddChild(new TCXmlSpaceReader() { Attribute = new TestCase() { Name = "XmlSpace", Desc = "CharCheckingReader" } });
+ module.AddChild(new TCXmlLangReader() { Attribute = new TestCase() { Name = "XmlLang", Desc = "CharCheckingReader" } });
+ module.AddChild(new TCSkipReader() { Attribute = new TestCase() { Name = "Skip", Desc = "CharCheckingReader" } });
+ module.AddChild(new TCInvalidXMLReader() { Attribute = new TestCase() { Name = "InvalidXML", Desc = "CharCheckingReader" } });
+ module.AddChild(new TCReadOuterXmlReader() { Attribute = new TestCase() { Name = "ReadOuterXml", Desc = "CharCheckingReader" } });
+ module.AddChild(new TCAttributeAccessReader() { Attribute = new TestCase() { Name = "AttributeAccess", Desc = "CharCheckingReader" } });
+ module.AddChild(new TCThisNameReader() { Attribute = new TestCase() { Name = "This(Name) and This(Name, Namespace)", Desc = "CharCheckingReader" } });
+ module.AddChild(new TCMoveToAttributeReader() { Attribute = new TestCase() { Name = "MoveToAttribute(Name) and MoveToAttribute(Name, Namespace)", Desc = "CharCheckingReader" } });
+ module.AddChild(new TCGetAttributeOrdinalReader() { Attribute = new TestCase() { Name = "GetAttribute (Ordinal)", Desc = "CharCheckingReader" } });
+ module.AddChild(new TCGetAttributeNameReader() { Attribute = new TestCase() { Name = "GetAttribute(Name) and GetAttribute(Name, Namespace)", Desc = "CharCheckingReader" } });
+ module.AddChild(new TCThisOrdinalReader() { Attribute = new TestCase() { Name = "This [Ordinal]", Desc = "CharCheckingReader" } });
+ module.AddChild(new TCMoveToAttributeOrdinalReader() { Attribute = new TestCase() { Name = "MoveToAttribute(Ordinal)", Desc = "CharCheckingReader" } });
+ module.AddChild(new TCMoveToFirstAttributeReader() { Attribute = new TestCase() { Name = "MoveToFirstAttribute()", Desc = "CharCheckingReader" } });
+ module.AddChild(new TCMoveToNextAttributeReader() { Attribute = new TestCase() { Name = "MoveToNextAttribute()", Desc = "CharCheckingReader" } });
+ module.AddChild(new TCAttributeTestReader() { Attribute = new TestCase() { Name = "Attribute Test when NodeType != Attributes", Desc = "CharCheckingReader" } });
+ module.AddChild(new TCAttributeXmlDeclarationReader() { Attribute = new TestCase() { Name = "Attributes test on XmlDeclaration", Desc = "CharCheckingReader" } });
+ module.AddChild(new TCXmlnsReader() { Attribute = new TestCase() { Name = "xmlns as local name", Desc = "CharCheckingReader" } });
+ module.AddChild(new TCXmlnsPrefixReader() { Attribute = new TestCase() { Name = "bounded namespace to xmlns prefix", Desc = "CharCheckingReader" } });
+ module.AddChild(new TCReadInnerXmlReader() { Attribute = new TestCase() { Name = "ReadInnerXml", Desc = "CharCheckingReader" } });
+ module.AddChild(new TCMoveToContentReader() { Attribute = new TestCase() { Name = "MoveToContent", Desc = "CharCheckingReader" } });
+ module.AddChild(new TCIsStartElementReader() { Attribute = new TestCase() { Name = "IsStartElement", Desc = "CharCheckingReader" } });
+ module.AddChild(new TCReadStartElementReader() { Attribute = new TestCase() { Name = "ReadStartElement", Desc = "CharCheckingReader" } });
+ module.AddChild(new TCReadEndElementReader() { Attribute = new TestCase() { Name = "ReadEndElement", Desc = "CharCheckingReader" } });
+ module.AddChild(new TCResolveEntityReader() { Attribute = new TestCase() { Name = "ResolveEntity and ReadAttributeValue", Desc = "CharCheckingReader" } });
+ module.AddChild(new TCHasValueReader() { Attribute = new TestCase() { Name = "HasValue", Desc = "CharCheckingReader" } });
+ module.AddChild(new TCReadAttributeValueReader() { Attribute = new TestCase() { Name = "ReadAttributeValue", Desc = "CharCheckingReader" } });
+ module.AddChild(new TCReadReader() { Attribute = new TestCase() { Name = "Read", Desc = "CharCheckingReader" } });
+ module.AddChild(new TCMoveToElementReader() { Attribute = new TestCase() { Name = "MoveToElement", Desc = "CharCheckingReader" } });
+ module.AddChild(new TCDisposeReader() { Attribute = new TestCase() { Name = "Dispose", Desc = "CharCheckingReader" } });
+ module.AddChild(new TCBufferBoundariesReader() { Attribute = new TestCase() { Name = "Buffer Boundaries", Desc = "CharCheckingReader" } });
+ module.AddChild(new TCXmlNodeIntegrityTestFile() { Attribute = new TestCase() { Name = "BeforeRead", Desc = "BeforeRead" } });
+ module.AddChild(new TCXmlNodeIntegrityTestFile() { Attribute = new TestCase() { Name = "AfterCloseInTheMiddle", Desc = "AfterCloseInTheMiddle" } });
+ module.AddChild(new TCXmlNodeIntegrityTestFile() { Attribute = new TestCase() { Name = "AfterClose", Desc = "AfterClose" } });
+ module.AddChild(new TCXmlNodeIntegrityTestFile() { Attribute = new TestCase() { Name = "AfterReadIsFalse", Desc = "AfterReadIsFalse" } });
+ module.AddChild(new TCReadSubtreeReader() { Attribute = new TestCase() { Name = "Read Subtree", Desc = "CharCheckingReader" } });
+ module.AddChild(new TCReadToDescendantReader() { Attribute = new TestCase() { Name = "ReadToDescendant", Desc = "CharCheckingReader" } });
+ module.AddChild(new TCReadToNextSiblingReader() { Attribute = new TestCase() { Name = "ReadToNextSibling", Desc = "CharCheckingReader" } });
+ module.AddChild(new TCReadValueReader() { Attribute = new TestCase() { Name = "ReadValue", Desc = "CharCheckingReader" } });
+ module.AddChild(new TCReadContentAsBase64Reader() { Attribute = new TestCase() { Name = "ReadContentAsBase64", Desc = "CharCheckingReader" } });
+ module.AddChild(new TCReadElementContentAsBase64Reader() { Attribute = new TestCase() { Name = "ReadElementContentAsBase64", Desc = "CharCheckingReader" } });
+ module.AddChild(new TCReadContentAsBinHexReader() { Attribute = new TestCase() { Name = "ReadContentAsBinHex", Desc = "CharCheckingReader" } });
+ module.AddChild(new TCReadElementContentAsBinHexReader() { Attribute = new TestCase() { Name = "ReadElementContentAsBinHex", Desc = "CharCheckingReader" } });
+ module.AddChild(new TCReadToFollowingReader() { Attribute = new TestCase() { Name = "ReadToFollowing", Desc = "CharCheckingReader" } });
+
+ return module;
}
}
}
diff --git a/src/System.Private.Xml/tests/Readers/CharCheckingReader/System.Xml.RW.CharCheckingReader.Tests.csproj b/src/System.Private.Xml/tests/Readers/CharCheckingReader/System.Xml.RW.CharCheckingReader.Tests.csproj
index a5c4cf3293..035805eaff 100644
--- a/src/System.Private.Xml/tests/Readers/CharCheckingReader/System.Xml.RW.CharCheckingReader.Tests.csproj
+++ b/src/System.Private.Xml/tests/Readers/CharCheckingReader/System.Xml.RW.CharCheckingReader.Tests.csproj
@@ -13,6 +13,7 @@
<ItemGroup>
<Compile Include="CharReaderTests.cs" />
<Compile Include="InheritedCases.cs" />
+ <Compile Include="$(CommonTestPath)\System\Xml\DisableParallelization.cs" />
</ItemGroup>
<ItemGroup>
<ProjectReference Include="$(CommonTestPath)\System\Xml\ModuleCore\ModuleCore.csproj" />
@@ -20,4 +21,4 @@
<ProjectReference Include="..\..\XmlReaderLib\System.Xml.RW.XmlReaderLib.csproj" />
</ItemGroup>
<Import Project="$([MSBuild]::GetDirectoryNameOfFileAbove($(MSBuildThisFileDirectory), dir.targets))\dir.targets" />
-</Project> \ No newline at end of file
+</Project>
diff --git a/src/System.Private.Xml/tests/Readers/CustomReader/CReaderTestModule.cs b/src/System.Private.Xml/tests/Readers/CustomReader/CReaderTestModule.cs
index c07d683d5a..1a1b06aa2a 100644
--- a/src/System.Private.Xml/tests/Readers/CustomReader/CReaderTestModule.cs
+++ b/src/System.Private.Xml/tests/Readers/CustomReader/CReaderTestModule.cs
@@ -9,34 +9,21 @@ namespace System.Xml.Tests
{
public partial class CReaderTestModule : CGenericTestModule
{
- private static void RunTestCaseAsync(Func<CTestBase> testCaseGenerator)
+ [Theory]
+ [XmlTests(nameof(Create))]
+ public void RunTests(XunitTestCase testCase)
{
- CModInfo.CommandLine = "/async";
- RunTestCase(testCaseGenerator);
+ testCase.Run();
}
- private static void RunTestCase(Func<CTestBase> testCaseGenerator)
+ public static CTestModule Create()
{
var module = new CReaderTestModule();
module.Init(null);
- module.AddChild(testCaseGenerator());
- module.Execute();
+ module.AddChild(new TCReadReader() { Attribute = new TestCase() { Name = "Read", Desc = "CustomInheritedReader" } });
- Assert.Equal(0, module.FailCount);
- }
-
- private static void RunTest(Func<CTestBase> testCaseGenerator)
- {
- RunTestCase(testCaseGenerator);
- RunTestCaseAsync(testCaseGenerator);
- }
-
- [Fact]
- [OuterLoop]
- public static void RunTests()
- {
- RunTest(() => new TCReadReader() { Attribute = new TestCase() { Name = "Read", Desc = "CustomInheritedReader" } });
+ return module;
}
}
}
diff --git a/src/System.Private.Xml/tests/Readers/CustomReader/System.Xml.RW.CustomReader.Tests.csproj b/src/System.Private.Xml/tests/Readers/CustomReader/System.Xml.RW.CustomReader.Tests.csproj
index 1a20f15eb1..77307fafb0 100644
--- a/src/System.Private.Xml/tests/Readers/CustomReader/System.Xml.RW.CustomReader.Tests.csproj
+++ b/src/System.Private.Xml/tests/Readers/CustomReader/System.Xml.RW.CustomReader.Tests.csproj
@@ -13,6 +13,7 @@
<ItemGroup>
<Compile Include="CReaderTestModule.cs" />
<Compile Include="InheritedCases.cs" />
+ <Compile Include="$(CommonTestPath)\System\Xml\DisableParallelization.cs" />
</ItemGroup>
<ItemGroup>
<ProjectReference Include="$(CommonTestPath)\System\Xml\ModuleCore\ModuleCore.csproj" />
diff --git a/src/System.Private.Xml/tests/Readers/FactoryReader/FactoryReaderTests.cs b/src/System.Private.Xml/tests/Readers/FactoryReader/FactoryReaderTests.cs
index 116295fca2..a59a5ee6c3 100644
--- a/src/System.Private.Xml/tests/Readers/FactoryReader/FactoryReaderTests.cs
+++ b/src/System.Private.Xml/tests/Readers/FactoryReader/FactoryReaderTests.cs
@@ -9,398 +9,73 @@ namespace System.Xml.Tests
{
public partial class FactoryReaderTest : CGenericTestModule
{
- private static void RunTestCaseAsync(Func<CTestBase> testCaseGenerator)
+ [Theory]
+ [XmlTests(nameof(Create))]
+ public void RunTests(XunitTestCase testCase)
{
- CModInfo.CommandLine = "/async";
- RunTestCase(testCaseGenerator);
+ testCase.Run();
}
- private static void RunTestCase(Func<CTestBase> testCaseGenerator)
+ public static CTestModule Create()
{
var module = new FactoryReaderTest();
module.Init(null);
- module.AddChild(testCaseGenerator());
- module.Execute();
-
- Assert.Equal(0, module.FailCount);
- }
-
- private static void RunTest(Func<CTestBase> testCaseGenerator)
- {
- RunTestCase(testCaseGenerator);
- RunTestCaseAsync(testCaseGenerator);
- }
-
- [Fact]
- [OuterLoop]
- public static void ErrorConditionReader()
- {
- RunTest(() => new TCErrorConditionReader() { Attribute = new TestCase() { Name = "ErrorCondition", Desc = "FactoryReader" } });
- }
-
- [Fact]
- [OuterLoop]
- public static void XMLExceptionReader()
- {
- RunTest(() => new TCXMLExceptionReader() { Attribute = new TestCase() { Name = "XMLException", Desc = "FactoryReader" } });
- }
-
- [Fact]
- [OuterLoop]
- public static void LinePosReader()
- {
- RunTest(() => new TCLinePosReader() { Attribute = new TestCase() { Name = "LinePos", Desc = "FactoryReader" } });
- }
-
- [Fact]
- [OuterLoop]
- public static void DepthReader()
- {
- RunTest(() => new TCDepthReader() { Attribute = new TestCase() { Name = "Depth", Desc = "FactoryReader" } });
- }
-
- [Fact]
- [OuterLoop]
- public static void NamespaceReader()
- {
- RunTest(() => new TCNamespaceReader() { Attribute = new TestCase() { Name = "Namespace", Desc = "FactoryReader" } });
- }
-
- [Fact]
- [OuterLoop]
- public static void LookupNamespaceReader()
- {
- RunTest(() => new TCLookupNamespaceReader() { Attribute = new TestCase() { Name = "LookupNamespace", Desc = "FactoryReader" } });
- }
-
- [Fact]
- [OuterLoop]
- public static void HasValueReader()
- {
- RunTest(() => new TCHasValueReader() { Attribute = new TestCase() { Name = "HasValue", Desc = "FactoryReader" } });
- }
-
- [Fact]
- [OuterLoop]
- public static void IsEmptyElementReader()
- {
- RunTest(() => new TCIsEmptyElementReader() { Attribute = new TestCase() { Name = "IsEmptyElement", Desc = "FactoryReader" } });
- }
-
- [Fact]
- [OuterLoop]
- public static void XmlSpaceReader()
- {
- RunTest(() => new TCXmlSpaceReader() { Attribute = new TestCase() { Name = "XmlSpace", Desc = "FactoryReader" } });
- }
-
- [Fact]
- [OuterLoop]
- public static void XmlLangReader()
- {
- RunTest(() => new TCXmlLangReader() { Attribute = new TestCase() { Name = "XmlLang", Desc = "FactoryReader" } });
- }
-
- [Fact]
- [OuterLoop]
- public static void SkipReader()
- {
- RunTest(() => new TCSkipReader() { Attribute = new TestCase() { Name = "Skip", Desc = "FactoryReader" } });
- }
-
- [Fact]
- [OuterLoop]
- public static void BaseURIReader()
- {
- RunTest(() => new TCBaseURIReader() { Attribute = new TestCase() { Name = "BaseURI", Desc = "FactoryReader" } });
- }
-
- [Fact]
- [OuterLoop]
- public static void InvalidXMLReader()
- {
- RunTest(() => new TCInvalidXMLReader() { Attribute = new TestCase() { Name = "InvalidXML", Desc = "FactoryReader" } });
- }
-
- [Fact]
- [OuterLoop]
- public static void ReadOuterXmlReader()
- {
- RunTest(() => new TCReadOuterXmlReader() { Attribute = new TestCase() { Name = "ReadOuterXml", Desc = "FactoryReader" } });
- }
-
- [Fact]
- [OuterLoop]
- public static void AttributeAccessReader()
- {
- RunTest(() => new TCAttributeAccessReader() { Attribute = new TestCase() { Name = "AttributeAccess", Desc = "FactoryReader" } });
- }
-
- [Fact]
- [OuterLoop]
- public static void ThisNameReader()
- {
- RunTest(() => new TCThisNameReader() { Attribute = new TestCase() { Name = "This(Name) and This(Name, Namespace)", Desc = "FactoryReader" } });
- }
-
- [Fact]
- [OuterLoop]
- public static void MoveToAttributeReader()
- {
- RunTest(() => new TCMoveToAttributeReader() { Attribute = new TestCase() { Name = "MoveToAttribute(Name) and MoveToAttribute(Name, Namespace)", Desc = "FactoryReader" } });
- }
-
- [Fact]
- [OuterLoop]
- public static void GetAttributeOrdinalReader()
- {
- RunTest(() => new TCGetAttributeOrdinalReader() { Attribute = new TestCase() { Name = "GetAttribute (Ordinal)", Desc = "FactoryReader" } });
- }
-
- [Fact]
- [OuterLoop]
- public static void GetAttributeNameReader()
- {
- RunTest(() => new TCGetAttributeNameReader() { Attribute = new TestCase() { Name = "GetAttribute(Name) and GetAttribute(Name, Namespace)", Desc = "FactoryReader" } });
- }
-
- [Fact]
- [OuterLoop]
- public static void ThisOrdinalReader()
- {
- RunTest(() => new TCThisOrdinalReader() { Attribute = new TestCase() { Name = "This [Ordinal]", Desc = "FactoryReader" } });
- }
-
- [Fact]
- [OuterLoop]
- public static void MoveToAttributeOrdinalReader()
- {
- RunTest(() => new TCMoveToAttributeOrdinalReader() { Attribute = new TestCase() { Name = "MoveToAttribute(Ordinal)", Desc = "FactoryReader" } });
- }
-
- [Fact]
- [OuterLoop]
- public static void MoveToFirstAttributeReader()
- {
- RunTest(() => new TCMoveToFirstAttributeReader() { Attribute = new TestCase() { Name = "MoveToFirstAttribute()", Desc = "FactoryReader" } });
- }
-
- [Fact]
- [OuterLoop]
- public static void MoveToNextAttributeReader()
- {
- RunTest(() => new TCMoveToNextAttributeReader() { Attribute = new TestCase() { Name = "MoveToNextAttribute()", Desc = "FactoryReader" } });
- }
-
- [Fact]
- [OuterLoop]
- public static void AttributeTestReader()
- {
- RunTest(() => new TCAttributeTestReader() { Attribute = new TestCase() { Name = "Attribute Test when NodeType != Attributes", Desc = "FactoryReader" } });
- }
-
- [Fact]
- [OuterLoop]
- public static void AttributeXmlDeclarationReader()
- {
- RunTest(() => new TCAttributeXmlDeclarationReader() { Attribute = new TestCase() { Name = "Attributes test on XmlDeclaration", Desc = "FactoryReader" } });
- }
-
- [Fact]
- [OuterLoop]
- public static void XmlnsReader()
- {
- RunTest(() => new TCXmlnsReader() { Attribute = new TestCase() { Name = "xmlns as local name", Desc = "FactoryReader" } });
- }
-
- [Fact]
- [OuterLoop]
- public static void XmlnsPrefixReader()
- {
- RunTest(() => new TCXmlnsPrefixReader() { Attribute = new TestCase() { Name = "bounded namespace to xmlns prefix", Desc = "FactoryReader" } });
- }
-
- [Fact]
- [OuterLoop]
- public static void ReadStateReader()
- {
- RunTest(() => new TCReadStateReader() { Attribute = new TestCase() { Name = "ReadState", Desc = "FactoryReader" } });
- }
-
- [Fact]
- [OuterLoop]
- public static void ReadInnerXmlReader()
- {
- RunTest(() => new TCReadInnerXmlReader() { Attribute = new TestCase() { Name = "ReadInnerXml", Desc = "FactoryReader" } });
- }
-
- [Fact]
- [OuterLoop]
- public static void MoveToContentReader()
- {
- RunTest(() => new TCMoveToContentReader() { Attribute = new TestCase() { Name = "MoveToContent", Desc = "FactoryReader" } });
- }
-
- [Fact]
- [OuterLoop]
- public static void IsStartElementReader()
- {
- RunTest(() => new TCIsStartElementReader() { Attribute = new TestCase() { Name = "IsStartElement", Desc = "FactoryReader" } });
- }
-
- [Fact]
- [OuterLoop]
- public static void ReadStartElementReader()
- {
- RunTest(() => new TCReadStartElementReader() { Attribute = new TestCase() { Name = "ReadStartElement", Desc = "FactoryReader" } });
- }
-
- [Fact]
- [OuterLoop]
- public static void ReadEndElementReader()
- {
- RunTest(() => new TCReadEndElementReader() { Attribute = new TestCase() { Name = "ReadEndElement", Desc = "FactoryReader" } });
- }
-
- [Fact]
- [OuterLoop]
- public static void ResolveEntityReader()
- {
- RunTest(() => new TCResolveEntityReader() { Attribute = new TestCase() { Name = "ResolveEntity and ReadAttributeValue", Desc = "FactoryReader" } });
- }
-
- [Fact]
- [OuterLoop]
- public static void ReadAttributeValueReader()
- {
- RunTest(() => new TCReadAttributeValueReader() { Attribute = new TestCase() { Name = "ReadAttributeValue", Desc = "FactoryReader" } });
- }
-
- [Fact]
- [OuterLoop]
- public static void ReadReader()
- {
- RunTest(() => new TCReadReader() { Attribute = new TestCase() { Name = "Read", Desc = "FactoryReader" } });
- }
-
- [Fact]
- [OuterLoop]
- public static void MoveToElementReader()
- {
- RunTest(() => new TCMoveToElementReader() { Attribute = new TestCase() { Name = "MoveToElement", Desc = "FactoryReader" } });
- }
-
- [Fact]
- [OuterLoop]
- public static void DisposeReader()
- {
- RunTest(() => new TCDisposeReader() { Attribute = new TestCase() { Name = "Dispose", Desc = "FactoryReader" } });
- }
-
- [Fact]
- [OuterLoop]
- public static void BufferBoundariesReader()
- {
- RunTest(() => new TCBufferBoundariesReader() { Attribute = new TestCase() { Name = "Buffer Boundaries", Desc = "FactoryReader" } });
- }
-
- [Fact]
- [OuterLoop]
- public static void XmlNodeIntegrityTestFileBeforeRead()
- {
- RunTest(() => new TCXmlNodeIntegrityTestFile() { Attribute = new TestCase() { Name = "BeforeRead", Desc = "BeforeRead" } });
- }
-
- [Fact]
- [OuterLoop]
- public static void XmlNodeIntegrityTestFileAfterCloseInMiddle()
- {
- RunTest(() => new TCXmlNodeIntegrityTestFile() { Attribute = new TestCase() { Name = "AfterCloseInTheMiddle", Desc = "AfterCloseInTheMiddle" } });
- }
-
- [Fact]
- [OuterLoop]
- public static void XmlNodeIntegrityTestFileAfterClose()
- {
- RunTest(() => new TCXmlNodeIntegrityTestFile() { Attribute = new TestCase() { Name = "AfterClose", Desc = "AfterClose" } });
- }
-
- [Fact]
- [OuterLoop]
- public static void XmlNodeIntegrityTestFileAfterReadIsFalse()
- {
- RunTest(() => new TCXmlNodeIntegrityTestFile() { Attribute = new TestCase() { Name = "AfterReadIsFalse", Desc = "AfterReadIsFalse" } });
- }
-
- [Fact]
- [OuterLoop]
- public static void ReadSubtreeReader()
- {
- RunTest(() => new TCReadSubtreeReader() { Attribute = new TestCase() { Name = "Read Subtree", Desc = "FactoryReader" } });
- }
-
- [Fact]
- [OuterLoop]
- public static void ReadToDescendantReader()
- {
- RunTest(() => new TCReadToDescendantReader() { Attribute = new TestCase() { Name = "ReadToDescendant", Desc = "FactoryReader" } });
- }
-
- [Fact]
- [OuterLoop]
- public static void ReadToNextSiblingReader()
- {
- RunTest(() => new TCReadToNextSiblingReader() { Attribute = new TestCase() { Name = "ReadToNextSibling", Desc = "FactoryReader" } });
- }
-
- [Fact]
- [OuterLoop]
- public static void ReadValueReader()
- {
- RunTest(() => new TCReadValueReader() { Attribute = new TestCase() { Name = "ReadValue", Desc = "FactoryReader" } });
- }
-
- [Fact]
- [OuterLoop]
- public static void ReadContentAsBase64Reader()
- {
- RunTest(() => new TCReadContentAsBase64Reader() { Attribute = new TestCase() { Name = "ReadContentAsBase64", Desc = "FactoryReader" } });
- }
-
- [Fact]
- [OuterLoop]
- public static void ReadElementContentAsBase64Reader()
- {
- RunTest(() => new TCReadElementContentAsBase64Reader() { Attribute = new TestCase() { Name = "ReadElementContentAsBase64", Desc = "FactoryReader" } });
- }
-
- [Fact]
- [OuterLoop]
- public static void ReadContentAsBinHexReader()
- {
- RunTest(() => new TCReadContentAsBinHexReader() { Attribute = new TestCase() { Name = "ReadContentAsBinHex", Desc = "FactoryReader" } });
- }
-
- [Fact]
- [OuterLoop]
- public static void ReadElementContentAsBinHexReader()
- {
- RunTest(() => new TCReadElementContentAsBinHexReader() { Attribute = new TestCase() { Name = "ReadElementContentAsBinHex", Desc = "FactoryReader" } });
- }
-
- [Fact]
- [OuterLoop]
- public static void ReadToFollowingReader()
- {
- RunTest(() => new TCReadToFollowingReader() { Attribute = new TestCase() { Name = "ReadToFollowing", Desc = "FactoryReader" } });
- }
-
- [Fact]
- [OuterLoop]
- public static void Normalization()
- {
- RunTest(() => new TCNormalization() { Attribute = new TestCase() { Name = "FactoryReader Normalization", Desc = "FactoryReader" } });
+ module.AddChild(new TCErrorConditionReader() { Attribute = new TestCase() { Name = "ErrorCondition", Desc = "FactoryReader" } });
+ module.AddChild(new TCXMLExceptionReader() { Attribute = new TestCase() { Name = "XMLException", Desc = "FactoryReader" } });
+ module.AddChild(new TCLinePosReader() { Attribute = new TestCase() { Name = "LinePos", Desc = "FactoryReader" } });
+ module.AddChild(new TCDepthReader() { Attribute = new TestCase() { Name = "Depth", Desc = "FactoryReader" } });
+ module.AddChild(new TCNamespaceReader() { Attribute = new TestCase() { Name = "Namespace", Desc = "FactoryReader" } });
+ module.AddChild(new TCLookupNamespaceReader() { Attribute = new TestCase() { Name = "LookupNamespace", Desc = "FactoryReader" } });
+ module.AddChild(new TCHasValueReader() { Attribute = new TestCase() { Name = "HasValue", Desc = "FactoryReader" } });
+ module.AddChild(new TCIsEmptyElementReader() { Attribute = new TestCase() { Name = "IsEmptyElement", Desc = "FactoryReader" } });
+ module.AddChild(new TCXmlSpaceReader() { Attribute = new TestCase() { Name = "XmlSpace", Desc = "FactoryReader" } });
+ module.AddChild(new TCXmlLangReader() { Attribute = new TestCase() { Name = "XmlLang", Desc = "FactoryReader" } });
+ module.AddChild(new TCSkipReader() { Attribute = new TestCase() { Name = "Skip", Desc = "FactoryReader" } });
+ module.AddChild(new TCBaseURIReader() { Attribute = new TestCase() { Name = "BaseURI", Desc = "FactoryReader" } });
+ module.AddChild(new TCInvalidXMLReader() { Attribute = new TestCase() { Name = "InvalidXML", Desc = "FactoryReader" } });
+ module.AddChild(new TCReadOuterXmlReader() { Attribute = new TestCase() { Name = "ReadOuterXml", Desc = "FactoryReader" } });
+ module.AddChild(new TCAttributeAccessReader() { Attribute = new TestCase() { Name = "AttributeAccess", Desc = "FactoryReader" } });
+ module.AddChild(new TCThisNameReader() { Attribute = new TestCase() { Name = "This(Name) and This(Name, Namespace)", Desc = "FactoryReader" } });
+ module.AddChild(new TCMoveToAttributeReader() { Attribute = new TestCase() { Name = "MoveToAttribute(Name) and MoveToAttribute(Name, Namespace)", Desc = "FactoryReader" } });
+ module.AddChild(new TCGetAttributeOrdinalReader() { Attribute = new TestCase() { Name = "GetAttribute (Ordinal)", Desc = "FactoryReader" } });
+ module.AddChild(new TCGetAttributeNameReader() { Attribute = new TestCase() { Name = "GetAttribute(Name) and GetAttribute(Name, Namespace)", Desc = "FactoryReader" } });
+ module.AddChild(new TCThisOrdinalReader() { Attribute = new TestCase() { Name = "This [Ordinal]", Desc = "FactoryReader" } });
+ module.AddChild(new TCMoveToAttributeOrdinalReader() { Attribute = new TestCase() { Name = "MoveToAttribute(Ordinal)", Desc = "FactoryReader" } });
+ module.AddChild(new TCMoveToFirstAttributeReader() { Attribute = new TestCase() { Name = "MoveToFirstAttribute()", Desc = "FactoryReader" } });
+ module.AddChild(new TCMoveToNextAttributeReader() { Attribute = new TestCase() { Name = "MoveToNextAttribute()", Desc = "FactoryReader" } });
+ module.AddChild(new TCAttributeTestReader() { Attribute = new TestCase() { Name = "Attribute Test when NodeType != Attributes", Desc = "FactoryReader" } });
+ module.AddChild(new TCAttributeXmlDeclarationReader() { Attribute = new TestCase() { Name = "Attributes test on XmlDeclaration", Desc = "FactoryReader" } });
+ module.AddChild(new TCXmlnsReader() { Attribute = new TestCase() { Name = "xmlns as local name", Desc = "FactoryReader" } });
+ module.AddChild(new TCXmlnsPrefixReader() { Attribute = new TestCase() { Name = "bounded namespace to xmlns prefix", Desc = "FactoryReader" } });
+ module.AddChild(new TCReadStateReader() { Attribute = new TestCase() { Name = "ReadState", Desc = "FactoryReader" } });
+ module.AddChild(new TCReadInnerXmlReader() { Attribute = new TestCase() { Name = "ReadInnerXml", Desc = "FactoryReader" } });
+ module.AddChild(new TCMoveToContentReader() { Attribute = new TestCase() { Name = "MoveToContent", Desc = "FactoryReader" } });
+ module.AddChild(new TCIsStartElementReader() { Attribute = new TestCase() { Name = "IsStartElement", Desc = "FactoryReader" } });
+ module.AddChild(new TCReadStartElementReader() { Attribute = new TestCase() { Name = "ReadStartElement", Desc = "FactoryReader" } });
+ module.AddChild(new TCReadEndElementReader() { Attribute = new TestCase() { Name = "ReadEndElement", Desc = "FactoryReader" } });
+ module.AddChild(new TCResolveEntityReader() { Attribute = new TestCase() { Name = "ResolveEntity and ReadAttributeValue", Desc = "FactoryReader" } });
+ module.AddChild(new TCReadAttributeValueReader() { Attribute = new TestCase() { Name = "ReadAttributeValue", Desc = "FactoryReader" } });
+ module.AddChild(new TCReadReader() { Attribute = new TestCase() { Name = "Read", Desc = "FactoryReader" } });
+ module.AddChild(new TCMoveToElementReader() { Attribute = new TestCase() { Name = "MoveToElement", Desc = "FactoryReader" } });
+ module.AddChild(new TCDisposeReader() { Attribute = new TestCase() { Name = "Dispose", Desc = "FactoryReader" } });
+ module.AddChild(new TCBufferBoundariesReader() { Attribute = new TestCase() { Name = "Buffer Boundaries", Desc = "FactoryReader" } });
+ module.AddChild(new TCXmlNodeIntegrityTestFile() { Attribute = new TestCase() { Name = "BeforeRead", Desc = "BeforeRead" } });
+ module.AddChild(new TCXmlNodeIntegrityTestFile() { Attribute = new TestCase() { Name = "AfterCloseInTheMiddle", Desc = "AfterCloseInTheMiddle" } });
+ module.AddChild(new TCXmlNodeIntegrityTestFile() { Attribute = new TestCase() { Name = "AfterClose", Desc = "AfterClose" } });
+ module.AddChild(new TCXmlNodeIntegrityTestFile() { Attribute = new TestCase() { Name = "AfterReadIsFalse", Desc = "AfterReadIsFalse" } });
+ module.AddChild(new TCReadSubtreeReader() { Attribute = new TestCase() { Name = "Read Subtree", Desc = "FactoryReader" } });
+ module.AddChild(new TCReadToDescendantReader() { Attribute = new TestCase() { Name = "ReadToDescendant", Desc = "FactoryReader" } });
+ module.AddChild(new TCReadToNextSiblingReader() { Attribute = new TestCase() { Name = "ReadToNextSibling", Desc = "FactoryReader" } });
+ module.AddChild(new TCReadValueReader() { Attribute = new TestCase() { Name = "ReadValue", Desc = "FactoryReader" } });
+ module.AddChild(new TCReadContentAsBase64Reader() { Attribute = new TestCase() { Name = "ReadContentAsBase64", Desc = "FactoryReader" } });
+ module.AddChild(new TCReadElementContentAsBase64Reader() { Attribute = new TestCase() { Name = "ReadElementContentAsBase64", Desc = "FactoryReader" } });
+ module.AddChild(new TCReadContentAsBinHexReader() { Attribute = new TestCase() { Name = "ReadContentAsBinHex", Desc = "FactoryReader" } });
+ module.AddChild(new TCReadElementContentAsBinHexReader() { Attribute = new TestCase() { Name = "ReadElementContentAsBinHex", Desc = "FactoryReader" } });
+ module.AddChild(new TCReadToFollowingReader() { Attribute = new TestCase() { Name = "ReadToFollowing", Desc = "FactoryReader" } });
+ module.AddChild(new TCNormalization() { Attribute = new TestCase() { Name = "FactoryReader Normalization", Desc = "FactoryReader" } });
+
+ return module;
}
}
}
diff --git a/src/System.Private.Xml/tests/Readers/FactoryReader/System.Xml.RW.FactoryReader.Tests.csproj b/src/System.Private.Xml/tests/Readers/FactoryReader/System.Xml.RW.FactoryReader.Tests.csproj
index f13a26481b..6738ad1ee6 100644
--- a/src/System.Private.Xml/tests/Readers/FactoryReader/System.Xml.RW.FactoryReader.Tests.csproj
+++ b/src/System.Private.Xml/tests/Readers/FactoryReader/System.Xml.RW.FactoryReader.Tests.csproj
@@ -14,6 +14,7 @@
<Compile Include="InheritedCases.cs" />
<Compile Include="Normalization.cs" />
<Compile Include="TCNormalization.cs" />
+ <Compile Include="$(CommonTestPath)\System\Xml\DisableParallelization.cs" />
</ItemGroup>
<ItemGroup>
<ProjectReference Include="$(CommonTestPath)\System\Xml\ModuleCore\ModuleCore.csproj" />
diff --git a/src/System.Private.Xml/tests/Readers/NameTable/CNameTableTestModule.cs b/src/System.Private.Xml/tests/Readers/NameTable/CNameTableTestModule.cs
index 0bb31888a7..a5ca1f3745 100644
--- a/src/System.Private.Xml/tests/Readers/NameTable/CNameTableTestModule.cs
+++ b/src/System.Private.Xml/tests/Readers/NameTable/CNameTableTestModule.cs
@@ -9,96 +9,35 @@ namespace System.Xml.Tests
{
public partial class CNameTableTestModule : CTestModule
{
- private static void RunTestCaseAsync(Func<CTestBase> testCaseGenerator)
+ [Theory]
+ [XmlTests(nameof(Create))]
+ public void RunTests(XunitTestCase testCase)
{
- CModInfo.CommandLine = "/async";
- RunTestCase(testCaseGenerator);
+ testCase.Run();
}
- private static void RunTestCase(Func<CTestBase> testCaseGenerator)
+ public static CTestModule Create()
{
var module = new CNameTableTestModule();
module.Init(null);
- module.AddChild(testCaseGenerator());
- module.Execute();
-
- Assert.Equal(0, module.FailCount);
- }
-
- private static void RunTest(Func<CTestBase> testCaseGenerator)
- {
- RunTestCase(testCaseGenerator);
- RunTestCaseAsync(testCaseGenerator);
- }
-
- [Fact]
- [OuterLoop]
- public static void TCUserNameTable()
- {
- RunTest(() => new TCUserNameTable() { Attribute = new TestCase() { Name = "XmlNameTable user scenario inheritance", Desc = "XmlNameTable inheritance" } });
- }
-
- [Fact]
- [OuterLoop]
- public static void NameTableVerifyWGetChar()
- {
- RunTest(() => new TCRecordNameTableGet() { Attribute = new TestCase() { Name = "NameTable(Get) VerifyWGetChar", Desc = "VerifyWGetChar" } });
- }
-
- [Fact]
- [OuterLoop]
- public static void NameTableVerifyWAddChar()
- {
- RunTest(() => new TCRecordNameTableGet() { Attribute = new TestCase() { Name = "NameTable(Get) VerifyWAddChar", Desc = "VerifyWAddChar" } });
- RunTest(() => new TCRecordNameTableGet() { Attribute = new TestCase() { Name = "NameTable(Get) VerifyWAddString", Desc = "VerifyWAddString" } });
- RunTest(() => new TCRecordNameTableGet() { Attribute = new TestCase() { Name = "NameTable(Get) VerifyWGetString", Desc = "VerifyWGetString" } });
- RunTest(() => new TCRecordNameTableAdd() { Attribute = new TestCase() { Name = "NameTable(Add) VerifyWAddChar", Desc = "VerifyWAddChar" } });
- RunTest(() => new TCRecordNameTableAdd() { Attribute = new TestCase() { Name = "NameTable(Add) VerifyWGetChar", Desc = "VerifyWGetChar" } });
- RunTest(() => new TCRecordNameTableAdd() { Attribute = new TestCase() { Name = "NameTable(Add) VerifyWAddString", Desc = "VerifyWAddString" } });
- RunTest(() => new TCRecordNameTableAdd() { Attribute = new TestCase() { Name = "NameTable(Add) VerifyWGetString", Desc = "VerifyWGetString" } });
- }
-
- [Fact]
- [OuterLoop]
- public static void NameTableVerifyWAddString()
- {
- RunTest(() => new TCRecordNameTableGet() { Attribute = new TestCase() { Name = "NameTable(Get) VerifyWAddString", Desc = "VerifyWAddString" } });
- }
-
- [Fact]
- [OuterLoop]
- public static void NameTableVerifyWGetString()
- {
- RunTest(() => new TCRecordNameTableGet() { Attribute = new TestCase() { Name = "NameTable(Get) VerifyWGetString", Desc = "VerifyWGetString" } });
- }
-
- [Fact]
- [OuterLoop]
- public static void TCRecordNameTableAddVerifyWAddChar()
- {
- RunTest(() => new TCRecordNameTableAdd() { Attribute = new TestCase() { Name = "NameTable(Add) VerifyWAddChar", Desc = "VerifyWAddChar" } });
- }
-
- [Fact]
- [OuterLoop]
- public static void TCRecordNameTableAddVerifyWGetChar()
- {
- RunTest(() => new TCRecordNameTableAdd() { Attribute = new TestCase() { Name = "NameTable(Add) VerifyWGetChar", Desc = "VerifyWGetChar" } });
- }
-
- [Fact]
- [OuterLoop]
- public static void TCRecordNameTableAddVerifyWAddString()
- {
- RunTest(() => new TCRecordNameTableAdd() { Attribute = new TestCase() { Name = "NameTable(Add) VerifyWAddString", Desc = "VerifyWAddString" } });
- }
-
- [Fact]
- [OuterLoop]
- public static void TCRecordNameTableAddVerifyWGetString()
- {
- RunTest(() => new TCRecordNameTableAdd() { Attribute = new TestCase() { Name = "NameTable(Add) VerifyWGetString", Desc = "VerifyWGetString" } });
+ module.AddChild(new TCUserNameTable() { Attribute = new TestCase() { Name = "XmlNameTable user scenario inheritance", Desc = "XmlNameTable inheritance" } });
+ module.AddChild(new TCRecordNameTableGet() { Attribute = new TestCase() { Name = "NameTable(Get) VerifyWGetChar", Desc = "VerifyWGetChar" } });
+ module.AddChild(new TCRecordNameTableGet() { Attribute = new TestCase() { Name = "NameTable(Get) VerifyWAddChar", Desc = "VerifyWAddChar" } });
+ module.AddChild(new TCRecordNameTableGet() { Attribute = new TestCase() { Name = "NameTable(Get) VerifyWAddString", Desc = "VerifyWAddString" } });
+ module.AddChild(new TCRecordNameTableGet() { Attribute = new TestCase() { Name = "NameTable(Get) VerifyWGetString", Desc = "VerifyWGetString" } });
+ module.AddChild(new TCRecordNameTableAdd() { Attribute = new TestCase() { Name = "NameTable(Add) VerifyWAddChar", Desc = "VerifyWAddChar" } });
+ module.AddChild(new TCRecordNameTableAdd() { Attribute = new TestCase() { Name = "NameTable(Add) VerifyWGetChar", Desc = "VerifyWGetChar" } });
+ module.AddChild(new TCRecordNameTableAdd() { Attribute = new TestCase() { Name = "NameTable(Add) VerifyWAddString", Desc = "VerifyWAddString" } });
+ module.AddChild(new TCRecordNameTableAdd() { Attribute = new TestCase() { Name = "NameTable(Add) VerifyWGetString", Desc = "VerifyWGetString" } });
+ module.AddChild(new TCRecordNameTableGet() { Attribute = new TestCase() { Name = "NameTable(Get) VerifyWAddString", Desc = "VerifyWAddString" } });
+ module.AddChild(new TCRecordNameTableGet() { Attribute = new TestCase() { Name = "NameTable(Get) VerifyWGetString", Desc = "VerifyWGetString" } });
+ module.AddChild(new TCRecordNameTableAdd() { Attribute = new TestCase() { Name = "NameTable(Add) VerifyWAddChar", Desc = "VerifyWAddChar" } });
+ module.AddChild(new TCRecordNameTableAdd() { Attribute = new TestCase() { Name = "NameTable(Add) VerifyWGetChar", Desc = "VerifyWGetChar" } });
+ module.AddChild(new TCRecordNameTableAdd() { Attribute = new TestCase() { Name = "NameTable(Add) VerifyWAddString", Desc = "VerifyWAddString" } });
+ module.AddChild(new TCRecordNameTableAdd() { Attribute = new TestCase() { Name = "NameTable(Add) VerifyWGetString", Desc = "VerifyWGetString" } });
+
+ return module;
}
}
}
diff --git a/src/System.Private.Xml/tests/Readers/NameTable/System.Xml.RW.NameTable.Tests.csproj b/src/System.Private.Xml/tests/Readers/NameTable/System.Xml.RW.NameTable.Tests.csproj
index d15a5abb4d..e73c76f249 100644
--- a/src/System.Private.Xml/tests/Readers/NameTable/System.Xml.RW.NameTable.Tests.csproj
+++ b/src/System.Private.Xml/tests/Readers/NameTable/System.Xml.RW.NameTable.Tests.csproj
@@ -17,6 +17,7 @@
<Compile Include="TCUserNameTable.cs" />
<Compile Include="TestFiles.cs" />
<Compile Include="XmlNameTable.cs" />
+ <Compile Include="$(CommonTestPath)\System\Xml\DisableParallelization.cs" />
</ItemGroup>
<ItemGroup>
<ProjectReference Include="$(CommonTestPath)\System\Xml\ModuleCore\ModuleCore.csproj" />
diff --git a/src/System.Private.Xml/tests/Readers/ReaderSettings/CReaderTestModule.cs b/src/System.Private.Xml/tests/Readers/ReaderSettings/CReaderTestModule.cs
index a8712e8905..e88f8a0d9b 100644
--- a/src/System.Private.Xml/tests/Readers/ReaderSettings/CReaderTestModule.cs
+++ b/src/System.Private.Xml/tests/Readers/ReaderSettings/CReaderTestModule.cs
@@ -9,198 +9,45 @@ namespace System.Xml.Tests
{
public partial class CReaderTestModule : CGenericTestModule
{
- private static void RunTestCase(Func<CTestBase> testCaseGenerator)
+ [Theory]
+ [XmlTests(nameof(Create))]
+ public void RunTests(XunitTestCase testCase)
{
- var module = new CReaderTestModule();
-
- module.Init(null);
- module.AddChild(testCaseGenerator());
- module.Execute();
-
- Assert.Equal(0, module.FailCount);
- }
-
- private static void RunTest(Func<CTestBase> testCaseGenerator)
- {
- CModInfo.CommandLine = "";
- RunTestCase(testCaseGenerator);
- CModInfo.CommandLine = "/async";
- RunTestCase(testCaseGenerator);
- }
-
- [Fact]
- [OuterLoop]
- public static void TCConformanceSettings()
- {
- RunTest(() => new TCConformanceSettings() { Attribute = new TestCase() { Name = "Conformance Settings", Desc = "Conformance Settings" } });
- }
-
- [Fact]
- [OuterLoop]
- public static void TCCreateOverloads()
- {
- RunTest(() => new TCCreateOverloads() { Attribute = new TestCase() { Name = "Create Overloads", Desc = "Create Overloads" } });
- }
-
- [Fact]
- [OuterLoop]
- public static void TCFilterSettings()
- {
- RunTest(() => new TCFilterSettings() { Attribute = new TestCase() { Name = "Filter Settings", Desc = "Filter Settings" } });
- }
-
- [Fact]
- [OuterLoop]
- public static void TCLineInfo()
- {
- RunTest(() => new TCLineInfo() { Attribute = new TestCase() { Name = "LineInfo", Desc = "LineInfo" } });
- }
-
- [Fact]
- [OuterLoop]
- public static void TCMaxSettings()
- {
- RunTest(() => new TCMaxSettings() { Attribute = new TestCase() { Name = "MaxCharacters Settings", Desc = "MaxCharacters Settings" } });
- }
-
- [Fact]
- [OuterLoop]
- public static void TCReaderSettingsGenericTestsCharCheckingReader()
- {
- RunTest(() => new TCReaderSettings() { Attribute = new TestCase() { Name = "ReaderSettings Generic Tests.CharCheckingReader", Param = "CharCheckingReader" } });
- }
-
- [Fact]
- [OuterLoop]
- public static void TCReaderSettingsGenericTestsSubtreeReader()
- {
- RunTest(() => new TCReaderSettings() { Attribute = new TestCase() { Name = "ReaderSettings Generic Tests.SubtreeReader", Param = "SubtreeReader" } });
- }
-
- [Fact]
- [OuterLoop]
- public static void TCReaderSettingsGenericTestsCoreReader()
- {
- RunTest(() => new TCReaderSettings() { Attribute = new TestCase() { Name = "ReaderSettings Generic Tests.CoreReader", Param = "CoreReader" } });
- }
-
- [Fact]
- [OuterLoop]
- public static void TCReaderSettingsGenericTestsWrappedReader()
- {
- RunTest(() => new TCReaderSettings() { Attribute = new TestCase() { Name = "ReaderSettings Generic Tests.WrappedReader", Param = "WrappedReader" } });
- }
-
- [Fact]
- [OuterLoop]
- public static void TCCloseInputWrappedReader()
- {
- RunTest(() => new TCCloseInput() { Attribute = new TestCase() { Name = "CloseInput.WrappedReader", Param = "WrappedReader" } });
- }
-
- [Fact]
- [OuterLoop]
- public static void TCCloseInputCharCheckingReader()
- {
- RunTest(() => new TCCloseInput() { Attribute = new TestCase() { Name = "CloseInput.CharCheckingReader", Param = "CharCheckingReader" } });
+ testCase.Run();
}
- [Fact]
- [OuterLoop]
- public static void TCCloseInputCoreReader()
+ public static CTestModule Create()
{
- RunTest(() => new TCCloseInput() { Attribute = new TestCase() { Name = "CloseInput.CoreReader", Param = "CoreReader" } });
- }
-
- [Fact]
- [OuterLoop]
- public static void TCCloseInputSubtreeReader()
- {
- RunTest(() => new TCCloseInput() { Attribute = new TestCase() { Name = "CloseInput.SubtreeReader", Param = "SubtreeReader" } });
- }
-
- [Fact]
- [OuterLoop]
- public static void TCRSGenericCharCheckingReader()
- {
- RunTest(() => new TCRSGeneric() { Attribute = new TestCase() { Name = "ReaderSettings Generic Tests.CharCheckingReader", Param = "CharCheckingReader" } });
- }
-
- [Fact]
- [OuterLoop]
- public static void TCRSGenericCoreReader()
- {
- RunTest(() => new TCRSGeneric() { Attribute = new TestCase() { Name = "ReaderSettings Generic Tests.CoreReader", Param = "CoreReader" } });
- }
-
- [Fact]
- [OuterLoop]
- public static void TCRSGenericWrappedReader()
- {
- RunTest(() => new TCRSGeneric() { Attribute = new TestCase() { Name = "ReaderSettings Generic Tests.WrappedReader", Param = "WrappedReader" } });
- }
-
- [Fact]
- [OuterLoop]
- public static void TCRSGenericSubtreeReader()
- {
- RunTest(() => new TCRSGeneric() { Attribute = new TestCase() { Name = "ReaderSettings Generic Tests.SubtreeReader", Param = "SubtreeReader" } });
- }
-
- [Fact]
- [OuterLoop]
- public static void TCDtdProcessingCoreReaderCharCheckingReader()
- {
- RunTest(() => new TCDtdProcessingCoreReader() { Attribute = new TestCase() { Name = "TCDtdProcessingCoreReader.CharCheckingReader", Param = "CharCheckingReader" } });
- }
-
- [Fact]
- [OuterLoop]
- public static void TCDtdProcessingCoreReaderCoreReader()
- {
- RunTest(() => new TCDtdProcessingCoreReader() { Attribute = new TestCase() { Name = "TCDtdProcessingCoreReader.CoreReader", Param = "CoreReader" } });
- }
-
- [Fact]
- [OuterLoop]
- public static void TCDtdProcessingCoreReaderWrappedReader()
- {
- RunTest(() => new TCDtdProcessingCoreReader() { Attribute = new TestCase() { Name = "TCDtdProcessingCoreReader.WrappedReader", Param = "WrappedReader" } });
- }
-
- [Fact]
- [OuterLoop]
- public static void TCDtdProcessingCoreReaderSubtreeReader()
- {
- RunTest(() => new TCDtdProcessingCoreReader() { Attribute = new TestCase() { Name = "TCDtdProcessingCoreReader.SubtreeReader", Param = "SubtreeReader" } });
- }
-
- [Fact]
- [OuterLoop]
- public static void TCOneByteStreamCharCheckingReader()
- {
- RunTest(() => new TCOneByteStream() { Attribute = new TestCase() { Name = "Read xml as one byte stream.CharCheckingReader", Param = "CharCheckingReader" } });
- }
-
- [Fact]
- [OuterLoop]
- public static void TCOneByteStreamSubtreeReader()
- {
- RunTest(() => new TCOneByteStream() { Attribute = new TestCase() { Name = "Read xml as one byte stream.SubtreeReader", Param = "SubtreeReader" } });
- }
-
- [Fact]
- [OuterLoop]
- public static void TCOneByteStreamCoreReader()
- {
- RunTest(() => new TCOneByteStream() { Attribute = new TestCase() { Name = "Read xml as one byte stream.CoreReader", Param = "CoreReader" } });
- }
+ var module = new CReaderTestModule();
- [Fact]
- [OuterLoop]
- public static void TCOneByteStreamWrappedReader()
- {
- RunTest(() => new TCOneByteStream() { Attribute = new TestCase() { Name = "Read xml as one byte stream.WrappedReader", Param = "WrappedReader" } });
+ module.Init(null);
+ module.AddChild(new TCConformanceSettings() { Attribute = new TestCase() { Name = "Conformance Settings", Desc = "Conformance Settings" } });
+ module.AddChild(new TCCreateOverloads() { Attribute = new TestCase() { Name = "Create Overloads", Desc = "Create Overloads" } });
+ module.AddChild(new TCFilterSettings() { Attribute = new TestCase() { Name = "Filter Settings", Desc = "Filter Settings" } });
+ module.AddChild(new TCLineInfo() { Attribute = new TestCase() { Name = "LineInfo", Desc = "LineInfo" } });
+ module.AddChild(new TCMaxSettings() { Attribute = new TestCase() { Name = "MaxCharacters Settings", Desc = "MaxCharacters Settings" } });
+ module.AddChild(new TCReaderSettings() { Attribute = new TestCase() { Name = "ReaderSettings Generic Tests.CharCheckingReader", Param = "CharCheckingReader" } });
+ module.AddChild(new TCReaderSettings() { Attribute = new TestCase() { Name = "ReaderSettings Generic Tests.SubtreeReader", Param = "SubtreeReader" } });
+ module.AddChild(new TCReaderSettings() { Attribute = new TestCase() { Name = "ReaderSettings Generic Tests.CoreReader", Param = "CoreReader" } });
+ module.AddChild(new TCReaderSettings() { Attribute = new TestCase() { Name = "ReaderSettings Generic Tests.WrappedReader", Param = "WrappedReader" } });
+ module.AddChild(new TCCloseInput() { Attribute = new TestCase() { Name = "CloseInput.WrappedReader", Param = "WrappedReader" } });
+ module.AddChild(new TCCloseInput() { Attribute = new TestCase() { Name = "CloseInput.CharCheckingReader", Param = "CharCheckingReader" } });
+ module.AddChild(new TCCloseInput() { Attribute = new TestCase() { Name = "CloseInput.CoreReader", Param = "CoreReader" } });
+ module.AddChild(new TCCloseInput() { Attribute = new TestCase() { Name = "CloseInput.SubtreeReader", Param = "SubtreeReader" } });
+ module.AddChild(new TCRSGeneric() { Attribute = new TestCase() { Name = "ReaderSettings Generic Tests.CharCheckingReader", Param = "CharCheckingReader" } });
+ module.AddChild(new TCRSGeneric() { Attribute = new TestCase() { Name = "ReaderSettings Generic Tests.CoreReader", Param = "CoreReader" } });
+ module.AddChild(new TCRSGeneric() { Attribute = new TestCase() { Name = "ReaderSettings Generic Tests.WrappedReader", Param = "WrappedReader" } });
+ module.AddChild(new TCRSGeneric() { Attribute = new TestCase() { Name = "ReaderSettings Generic Tests.SubtreeReader", Param = "SubtreeReader" } });
+ module.AddChild(new TCDtdProcessingCoreReader() { Attribute = new TestCase() { Name = "TCDtdProcessingCoreReader.CharCheckingReader", Param = "CharCheckingReader" } });
+ module.AddChild(new TCDtdProcessingCoreReader() { Attribute = new TestCase() { Name = "TCDtdProcessingCoreReader.CoreReader", Param = "CoreReader" } });
+ module.AddChild(new TCDtdProcessingCoreReader() { Attribute = new TestCase() { Name = "TCDtdProcessingCoreReader.WrappedReader", Param = "WrappedReader" } });
+ module.AddChild(new TCDtdProcessingCoreReader() { Attribute = new TestCase() { Name = "TCDtdProcessingCoreReader.SubtreeReader", Param = "SubtreeReader" } });
+ module.AddChild(new TCOneByteStream() { Attribute = new TestCase() { Name = "Read xml as one byte stream.CharCheckingReader", Param = "CharCheckingReader" } });
+ module.AddChild(new TCOneByteStream() { Attribute = new TestCase() { Name = "Read xml as one byte stream.SubtreeReader", Param = "SubtreeReader" } });
+ module.AddChild(new TCOneByteStream() { Attribute = new TestCase() { Name = "Read xml as one byte stream.CoreReader", Param = "CoreReader" } });
+ module.AddChild(new TCOneByteStream() { Attribute = new TestCase() { Name = "Read xml as one byte stream.WrappedReader", Param = "WrappedReader" } });
+
+ return module;
}
}
}
diff --git a/src/System.Private.Xml/tests/Readers/ReaderSettings/System.Xml.RW.ReaderSettings.Tests.csproj b/src/System.Private.Xml/tests/Readers/ReaderSettings/System.Xml.RW.ReaderSettings.Tests.csproj
index a556378423..9597aebbea 100644
--- a/src/System.Private.Xml/tests/Readers/ReaderSettings/System.Xml.RW.ReaderSettings.Tests.csproj
+++ b/src/System.Private.Xml/tests/Readers/ReaderSettings/System.Xml.RW.ReaderSettings.Tests.csproj
@@ -28,6 +28,7 @@
<Compile Include="TCOneByteStream.cs" />
<Compile Include="TCReaderSettings.cs" />
<Compile Include="TCRSGeneric.cs" />
+ <Compile Include="$(CommonTestPath)\System\Xml\DisableParallelization.cs" />
</ItemGroup>
<ItemGroup>
<ProjectReference Include="$(CommonTestPath)\System\Xml\BaseLibManaged\BaseLibManaged.csproj" />
diff --git a/src/System.Private.Xml/tests/Readers/SubtreeReader/SubtreeReaderTests.cs b/src/System.Private.Xml/tests/Readers/SubtreeReader/SubtreeReaderTests.cs
index 41a34cda37..ba3b3f5ab4 100644
--- a/src/System.Private.Xml/tests/Readers/SubtreeReader/SubtreeReaderTests.cs
+++ b/src/System.Private.Xml/tests/Readers/SubtreeReader/SubtreeReaderTests.cs
@@ -9,356 +9,69 @@ namespace System.Xml.Tests
{
public partial class SubtreeReaderTest : CGenericTestModule
{
- private static void RunTestCaseAsync(Func<CTestBase> testCaseGenerator)
+ [Theory]
+ [XmlTests(nameof(Create))]
+ public void RunTests(XunitTestCase testCase)
{
- CModInfo.CommandLine = "/async";
- RunTestCase(testCaseGenerator);
+ testCase.Run();
}
- private static void RunTestCase(Func<CTestBase> testCaseGenerator)
+ public static CTestModule Create()
{
var module = new SubtreeReaderTest();
module.Init(null);
- module.AddChild(testCaseGenerator());
- module.Execute();
-
- Assert.Equal(0, module.FailCount);
- }
-
- private static void RunTest(Func<CTestBase> testCaseGenerator)
- {
- RunTestCase(testCaseGenerator);
- RunTestCaseAsync(testCaseGenerator);
- }
-
- [Fact]
- [OuterLoop]
- public static void InvalidXMLReader()
- {
- RunTest(() => new TCInvalidXMLReader() { Attribute = new TestCase() { Name = "InvalidXML", Desc = "SubtreeReader" } });
- }
-
- [Fact]
- [OuterLoop]
- public static void ErrorConditionReader()
- {
- RunTest(() => new TCErrorConditionReader() { Attribute = new TestCase() { Name = "ErrorCondition", Desc = "SubtreeReader" } });
- }
-
- [Fact]
- [OuterLoop]
- public static void DepthReader()
- {
- RunTest(() => new TCDepthReader() { Attribute = new TestCase() { Name = "Depth", Desc = "SubtreeReader" } });
- }
-
- [Fact]
- [OuterLoop]
- public static void NamespaceReader()
- {
- RunTest(() => new TCNamespaceReader() { Attribute = new TestCase() { Name = "Namespace", Desc = "SubtreeReader" } });
- }
-
- [Fact]
- [OuterLoop]
- public static void LookupNamespaceReader()
- {
- RunTest(() => new TCLookupNamespaceReader() { Attribute = new TestCase() { Name = "LookupNamespace", Desc = "SubtreeReader" } });
- }
-
- [Fact]
- [OuterLoop]
- public static void IsEmptyElementReader()
- {
- RunTest(() => new TCIsEmptyElementReader() { Attribute = new TestCase() { Name = "IsEmptyElement", Desc = "SubtreeReader" } });
- }
-
- [Fact]
- [OuterLoop]
- public static void XmlSpaceReader()
- {
- RunTest(() => new TCXmlSpaceReader() { Attribute = new TestCase() { Name = "XmlSpace", Desc = "SubtreeReader" } });
- }
-
- [Fact]
- [OuterLoop]
- public static void XmlLangReader()
- {
- RunTest(() => new TCXmlLangReader() { Attribute = new TestCase() { Name = "XmlLang", Desc = "SubtreeReader" } });
- }
-
- [Fact]
- [OuterLoop]
- public static void SkipReader()
- {
- RunTest(() => new TCSkipReader() { Attribute = new TestCase() { Name = "Skip", Desc = "SubtreeReader" } });
- }
-
- [Fact]
- [OuterLoop]
- public static void ReadOuterXmlReader()
- {
- RunTest(() => new TCReadOuterXmlReader() { Attribute = new TestCase() { Name = "ReadOuterXml", Desc = "SubtreeReader" } });
- }
-
- [Fact]
- [OuterLoop]
- public static void AttributeAccessReader()
- {
- RunTest(() => new TCAttributeAccessReader() { Attribute = new TestCase() { Name = "AttributeAccess", Desc = "SubtreeReader" } });
- }
-
- [Fact]
- [OuterLoop]
- public static void ThisNameReader()
- {
- RunTest(() => new TCThisNameReader() { Attribute = new TestCase() { Name = "This(Name) and This(Name, Namespace)", Desc = "SubtreeReader" } });
- }
-
- [Fact]
- [OuterLoop]
- public static void MoveToAttributeReader()
- {
- RunTest(() => new TCMoveToAttributeReader() { Attribute = new TestCase() { Name = "MoveToAttribute(Name) and MoveToAttribute(Name, Namespace)", Desc = "SubtreeReader" } });
- }
-
- [Fact]
- [OuterLoop]
- public static void GetAttributeOrdinalReader()
- {
- RunTest(() => new TCGetAttributeOrdinalReader() { Attribute = new TestCase() { Name = "GetAttribute (Ordinal)", Desc = "SubtreeReader" } });
- }
-
- [Fact]
- [OuterLoop]
- public static void GetAttributeNameReader()
- {
- RunTest(() => new TCGetAttributeNameReader() { Attribute = new TestCase() { Name = "GetAttribute(Name) and GetAttribute(Name, Namespace)", Desc = "SubtreeReader" } });
- }
-
- [Fact]
- [OuterLoop]
- public static void ThisOrdinalReader()
- {
- RunTest(() => new TCThisOrdinalReader() { Attribute = new TestCase() { Name = "This [Ordinal]", Desc = "SubtreeReader" } });
- }
-
- [Fact]
- [OuterLoop]
- public static void MoveToAttributeOrdinalReader()
- {
- RunTest(() => new TCMoveToAttributeOrdinalReader() { Attribute = new TestCase() { Name = "MoveToAttribute(Ordinal)", Desc = "SubtreeReader" } });
- }
-
- [Fact]
- [OuterLoop]
- public static void MoveToFirstAttributeReader()
- {
- RunTest(() => new TCMoveToFirstAttributeReader() { Attribute = new TestCase() { Name = "MoveToFirstAttribute()", Desc = "SubtreeReader" } });
- }
-
- [Fact]
- [OuterLoop]
- public static void MoveToNextAttributeReader()
- {
- RunTest(() => new TCMoveToNextAttributeReader() { Attribute = new TestCase() { Name = "MoveToNextAttribute()", Desc = "SubtreeReader" } });
- }
-
- [Fact]
- [OuterLoop]
- public static void AttributeTestReader()
- {
- RunTest(() => new TCAttributeTestReader() { Attribute = new TestCase() { Name = "Attribute Test when NodeType != Attributes", Desc = "SubtreeReader" } });
+ module.AddChild(new TCInvalidXMLReader() { Attribute = new TestCase() { Name = "InvalidXML", Desc = "SubtreeReader" } });
+ module.AddChild(new TCErrorConditionReader() { Attribute = new TestCase() { Name = "ErrorCondition", Desc = "SubtreeReader" } });
+ module.AddChild(new TCDepthReader() { Attribute = new TestCase() { Name = "Depth", Desc = "SubtreeReader" } });
+ module.AddChild(new TCNamespaceReader() { Attribute = new TestCase() { Name = "Namespace", Desc = "SubtreeReader" } });
+ module.AddChild(new TCLookupNamespaceReader() { Attribute = new TestCase() { Name = "LookupNamespace", Desc = "SubtreeReader" } });
+ module.AddChild(new TCIsEmptyElementReader() { Attribute = new TestCase() { Name = "IsEmptyElement", Desc = "SubtreeReader" } });
+ module.AddChild(new TCXmlSpaceReader() { Attribute = new TestCase() { Name = "XmlSpace", Desc = "SubtreeReader" } });
+ module.AddChild(new TCXmlLangReader() { Attribute = new TestCase() { Name = "XmlLang", Desc = "SubtreeReader" } });
+ module.AddChild(new TCSkipReader() { Attribute = new TestCase() { Name = "Skip", Desc = "SubtreeReader" } });
+ module.AddChild(new TCReadOuterXmlReader() { Attribute = new TestCase() { Name = "ReadOuterXml", Desc = "SubtreeReader" } });
+ module.AddChild(new TCAttributeAccessReader() { Attribute = new TestCase() { Name = "AttributeAccess", Desc = "SubtreeReader" } });
+ module.AddChild(new TCThisNameReader() { Attribute = new TestCase() { Name = "This(Name) and This(Name, Namespace)", Desc = "SubtreeReader" } });
+ module.AddChild(new TCMoveToAttributeReader() { Attribute = new TestCase() { Name = "MoveToAttribute(Name) and MoveToAttribute(Name, Namespace)", Desc = "SubtreeReader" } });
+ module.AddChild(new TCGetAttributeOrdinalReader() { Attribute = new TestCase() { Name = "GetAttribute (Ordinal)", Desc = "SubtreeReader" } });
+ module.AddChild(new TCGetAttributeNameReader() { Attribute = new TestCase() { Name = "GetAttribute(Name) and GetAttribute(Name, Namespace)", Desc = "SubtreeReader" } });
+ module.AddChild(new TCThisOrdinalReader() { Attribute = new TestCase() { Name = "This [Ordinal]", Desc = "SubtreeReader" } });
+ module.AddChild(new TCMoveToAttributeOrdinalReader() { Attribute = new TestCase() { Name = "MoveToAttribute(Ordinal)", Desc = "SubtreeReader" } });
+ module.AddChild(new TCMoveToFirstAttributeReader() { Attribute = new TestCase() { Name = "MoveToFirstAttribute()", Desc = "SubtreeReader" } });
+ module.AddChild(new TCMoveToNextAttributeReader() { Attribute = new TestCase() { Name = "MoveToNextAttribute()", Desc = "SubtreeReader" } });
+ module.AddChild(new TCAttributeTestReader() { Attribute = new TestCase() { Name = "Attribute Test when NodeType != Attributes", Desc = "SubtreeReader" } });
+ module.AddChild(new TCXmlnsReader() { Attribute = new TestCase() { Name = "xmlns as local name DCR50345", Desc = "SubtreeReader" } });
+ module.AddChild(new TCXmlnsPrefixReader() { Attribute = new TestCase() { Name = "bounded namespace to xmlns prefix DCR50881", Desc = "SubtreeReader" } });
+ module.AddChild(new TCReadInnerXmlReader() { Attribute = new TestCase() { Name = "ReadInnerXml", Desc = "SubtreeReader" } });
+ module.AddChild(new TCMoveToContentReader() { Attribute = new TestCase() { Name = "MoveToContent", Desc = "SubtreeReader" } });
+ module.AddChild(new TCIsStartElementReader() { Attribute = new TestCase() { Name = "IsStartElement", Desc = "SubtreeReader" } });
+ module.AddChild(new TCReadStartElementReader() { Attribute = new TestCase() { Name = "ReadStartElement", Desc = "SubtreeReader" } });
+ module.AddChild(new TCReadEndElementReader() { Attribute = new TestCase() { Name = "ReadEndElement", Desc = "SubtreeReader" } });
+ module.AddChild(new TCResolveEntityReader() { Attribute = new TestCase() { Name = "ResolveEntity and ReadAttributeValue", Desc = "SubtreeReader" } });
+ module.AddChild(new TCHasValueReader() { Attribute = new TestCase() { Name = "HasValue", Desc = "SubtreeReader" } });
+ module.AddChild(new TCReadAttributeValueReader() { Attribute = new TestCase() { Name = "ReadAttributeValue", Desc = "SubtreeReader" } });
+ module.AddChild(new TCReadReader() { Attribute = new TestCase() { Name = "Read", Desc = "SubtreeReader" } });
+ module.AddChild(new TCMoveToElementReader() { Attribute = new TestCase() { Name = "MoveToElement", Desc = "SubtreeReader" } });
+ module.AddChild(new TCDisposeReader() { Attribute = new TestCase() { Name = "Dispose", Desc = "SubtreeReader" } });
+ module.AddChild(new TCBufferBoundariesReader() { Attribute = new TestCase() { Name = "Buffer Boundaries", Desc = "SubtreeReader" } });
+ module.AddChild(new TCXmlNodeIntegrityTestFile() { Attribute = new TestCase() { Name = "BeforeRead", Desc = "BeforeRead" } });
+ module.AddChild(new TCXmlNodeIntegrityTestFile() { Attribute = new TestCase() { Name = "AfterCloseInTheMiddle", Desc = "AfterCloseInTheMiddle" } });
+ module.AddChild(new TCXmlNodeIntegrityTestFile() { Attribute = new TestCase() { Name = "AfterClose", Desc = "AfterClose" } });
+ module.AddChild(new TCXmlNodeIntegrityTestFile() { Attribute = new TestCase() { Name = "AfterReadIsFalse", Desc = "AfterReadIsFalse" } });
+ module.AddChild(new TCReadSubtreeReader() { Attribute = new TestCase() { Name = "Read Subtree", Desc = "SubtreeReader" } });
+ module.AddChild(new TCReadToDescendantReader() { Attribute = new TestCase() { Name = "ReadToDescendant", Desc = "SubtreeReader" } });
+ module.AddChild(new TCReadToNextSiblingReader() { Attribute = new TestCase() { Name = "ReadToNextSibling", Desc = "SubtreeReader" } });
+ module.AddChild(new TCReadValueReader() { Attribute = new TestCase() { Name = "ReadValue", Desc = "SubtreeReader" } });
+ module.AddChild(new TCReadContentAsBase64Reader() { Attribute = new TestCase() { Name = "ReadContentAsBase64", Desc = "SubtreeReader" } });
+ module.AddChild(new TCReadElementContentAsBase64Reader() { Attribute = new TestCase() { Name = "ReadElementContentAsBase64", Desc = "SubtreeReader" } });
+ module.AddChild(new TCReadContentAsBinHexReader() { Attribute = new TestCase() { Name = "ReadContentAsBinHex", Desc = "SubtreeReader" } });
+ module.AddChild(new TCReadElementContentAsBinHexReader() { Attribute = new TestCase() { Name = "ReadElementContentAsBinHex", Desc = "SubtreeReader" } });
+ module.AddChild(new TCReadToFollowingReader() { Attribute = new TestCase() { Name = "ReadToFollowing", Desc = "SubtreeReader" } });
+
+ return module;
}
- [Fact]
- [OuterLoop]
- public static void XmlnsReader()
- {
- RunTest(() => new TCXmlnsReader() { Attribute = new TestCase() { Name = "xmlns as local name DCR50345", Desc = "SubtreeReader" } });
- }
-
- [Fact]
- [OuterLoop]
- public static void XmlnsPrefixReader()
- {
- RunTest(() => new TCXmlnsPrefixReader() { Attribute = new TestCase() { Name = "bounded namespace to xmlns prefix DCR50881", Desc = "SubtreeReader" } });
- }
-
- [Fact]
- [OuterLoop]
- public static void ReadInnerXmlReader()
- {
- RunTest(() => new TCReadInnerXmlReader() { Attribute = new TestCase() { Name = "ReadInnerXml", Desc = "SubtreeReader" } });
- }
- [Fact]
- [OuterLoop]
- public static void MoveToContentReader()
- {
- RunTest(() => new TCMoveToContentReader() { Attribute = new TestCase() { Name = "MoveToContent", Desc = "SubtreeReader" } });
- }
-
- [Fact]
- [OuterLoop]
- public static void IsStartElementReader()
- {
- RunTest(() => new TCIsStartElementReader() { Attribute = new TestCase() { Name = "IsStartElement", Desc = "SubtreeReader" } });
- }
-
- [Fact]
- [OuterLoop]
- public static void ReadStartElementReader()
- {
- RunTest(() => new TCReadStartElementReader() { Attribute = new TestCase() { Name = "ReadStartElement", Desc = "SubtreeReader" } });
- }
-
- [Fact]
- [OuterLoop]
- public static void ReadEndElementReader()
- {
- RunTest(() => new TCReadEndElementReader() { Attribute = new TestCase() { Name = "ReadEndElement", Desc = "SubtreeReader" } });
- }
-
- [Fact]
- [OuterLoop]
- public static void ResolveEntityReader()
- {
- RunTest(() => new TCResolveEntityReader() { Attribute = new TestCase() { Name = "ResolveEntity and ReadAttributeValue", Desc = "SubtreeReader" } });
- }
-
- [Fact]
- [OuterLoop]
- public static void HasValueReader()
- {
- RunTest(() => new TCHasValueReader() { Attribute = new TestCase() { Name = "HasValue", Desc = "SubtreeReader" } });
- }
-
- [Fact]
- [OuterLoop]
- public static void ReadAttributeValueReader()
- {
- RunTest(() => new TCReadAttributeValueReader() { Attribute = new TestCase() { Name = "ReadAttributeValue", Desc = "SubtreeReader" } });
- }
-
- [Fact]
- [OuterLoop]
- public static void ReadReader()
- {
- RunTest(() => new TCReadReader() { Attribute = new TestCase() { Name = "Read", Desc = "SubtreeReader" } });
- }
-
- [Fact]
- [OuterLoop]
- public static void MoveToElementReader()
- {
- RunTest(() => new TCMoveToElementReader() { Attribute = new TestCase() { Name = "MoveToElement", Desc = "SubtreeReader" } });
- }
-
- [Fact]
- [OuterLoop]
- public static void DisposeReader()
- {
- RunTest(() => new TCDisposeReader() { Attribute = new TestCase() { Name = "Dispose", Desc = "SubtreeReader" } });
- }
-
- [Fact]
- [OuterLoop]
- public static void BufferBoundariesReader()
- {
- RunTest(() => new TCBufferBoundariesReader() { Attribute = new TestCase() { Name = "Buffer Boundaries", Desc = "SubtreeReader" } });
- }
-
- [Fact]
- [OuterLoop]
- public static void XmlNodeIntegrityTestFileBeforeRead()
- {
- RunTest(() => new TCXmlNodeIntegrityTestFile() { Attribute = new TestCase() { Name = "BeforeRead", Desc = "BeforeRead" } });
- }
-
- [Fact]
- [OuterLoop]
- public static void XmlNodeIntegrityTestFileAfterCloseInMiddle()
- {
- RunTest(() => new TCXmlNodeIntegrityTestFile() { Attribute = new TestCase() { Name = "AfterCloseInTheMiddle", Desc = "AfterCloseInTheMiddle" } });
- }
-
- [Fact]
- [OuterLoop]
- public static void XmlNodeIntegrityTestFileAfterClose()
- {
- RunTest(() => new TCXmlNodeIntegrityTestFile() { Attribute = new TestCase() { Name = "AfterClose", Desc = "AfterClose" } });
- }
-
- [Fact]
- [OuterLoop]
- public static void XmlNodeIntegrityTestFileAfterReadIsFalse()
- {
- RunTest(() => new TCXmlNodeIntegrityTestFile() { Attribute = new TestCase() { Name = "AfterReadIsFalse", Desc = "AfterReadIsFalse" } });
- }
-
- [Fact]
- [OuterLoop]
- public static void ReadSubtreeReader()
- {
- RunTest(() => new TCReadSubtreeReader() { Attribute = new TestCase() { Name = "Read Subtree", Desc = "SubtreeReader" } });
- }
-
- [Fact]
- [OuterLoop]
- public static void ReadToDescendantReader()
- {
- RunTest(() => new TCReadToDescendantReader() { Attribute = new TestCase() { Name = "ReadToDescendant", Desc = "SubtreeReader" } });
- }
-
- [Fact]
- [OuterLoop]
- public static void ReadToNextSiblingReader()
- {
- RunTest(() => new TCReadToNextSiblingReader() { Attribute = new TestCase() { Name = "ReadToNextSibling", Desc = "SubtreeReader" } });
- }
-
- [Fact]
- [OuterLoop]
- public static void ReadValueReader()
- {
- RunTest(() => new TCReadValueReader() { Attribute = new TestCase() { Name = "ReadValue", Desc = "SubtreeReader" } });
- }
-
- [Fact]
- [OuterLoop]
- public static void ReadContentAsBase64Reader()
- {
- RunTest(() => new TCReadContentAsBase64Reader() { Attribute = new TestCase() { Name = "ReadContentAsBase64", Desc = "SubtreeReader" } });
- }
-
- [Fact]
- [OuterLoop]
- public static void ReadElementContentAsBase64Reader()
- {
- RunTest(() => new TCReadElementContentAsBase64Reader() { Attribute = new TestCase() { Name = "ReadElementContentAsBase64", Desc = "SubtreeReader" } });
- }
-
- [Fact]
- [OuterLoop]
- public static void ReadContentAsBinHexReader()
- {
- RunTest(() => new TCReadContentAsBinHexReader() { Attribute = new TestCase() { Name = "ReadContentAsBinHex", Desc = "SubtreeReader" } });
- }
-
- [Fact]
- [OuterLoop]
- public static void ReadElementContentAsBinHexReader()
- {
- RunTest(() => new TCReadElementContentAsBinHexReader() { Attribute = new TestCase() { Name = "ReadElementContentAsBinHex", Desc = "SubtreeReader" } });
- }
-
- [Fact]
- [OuterLoop]
- public static void ReadToFollowingReader()
- {
- RunTest(() => new TCReadToFollowingReader() { Attribute = new TestCase() { Name = "ReadToFollowing", Desc = "SubtreeReader" } });
- }
}
}
diff --git a/src/System.Private.Xml/tests/Readers/SubtreeReader/System.Xml.RW.SubtreeReader.Tests.csproj b/src/System.Private.Xml/tests/Readers/SubtreeReader/System.Xml.RW.SubtreeReader.Tests.csproj
index 539f05e296..93aba863f0 100644
--- a/src/System.Private.Xml/tests/Readers/SubtreeReader/System.Xml.RW.SubtreeReader.Tests.csproj
+++ b/src/System.Private.Xml/tests/Readers/SubtreeReader/System.Xml.RW.SubtreeReader.Tests.csproj
@@ -12,6 +12,7 @@
<ItemGroup>
<Compile Include="InheritedCases.cs" />
<Compile Include="SubtreeReaderTests.cs" />
+ <Compile Include="$(CommonTestPath)\System\Xml\DisableParallelization.cs" />
</ItemGroup>
<ItemGroup>
<ProjectReference Include="$(CommonTestPath)\System\Xml\ModuleCore\ModuleCore.csproj" />
diff --git a/src/System.Private.Xml/tests/Readers/WrappedReader/System.Xml.RW.WrappedReader.Tests.csproj b/src/System.Private.Xml/tests/Readers/WrappedReader/System.Xml.RW.WrappedReader.Tests.csproj
index 1436b99538..589a3111b5 100644
--- a/src/System.Private.Xml/tests/Readers/WrappedReader/System.Xml.RW.WrappedReader.Tests.csproj
+++ b/src/System.Private.Xml/tests/Readers/WrappedReader/System.Xml.RW.WrappedReader.Tests.csproj
@@ -12,6 +12,7 @@
<ItemGroup>
<Compile Include="InheritedCases.cs" />
<Compile Include="WrappedReaderTests.cs" />
+ <Compile Include="$(CommonTestPath)\System\Xml\DisableParallelization.cs" />
</ItemGroup>
<ItemGroup>
<ProjectReference Include="$(CommonTestPath)\System\Xml\ModuleCore\ModuleCore.csproj" />
diff --git a/src/System.Private.Xml/tests/Readers/WrappedReader/WrappedReaderTests.cs b/src/System.Private.Xml/tests/Readers/WrappedReader/WrappedReaderTests.cs
index 7912339391..e8bd8f2e8d 100644
--- a/src/System.Private.Xml/tests/Readers/WrappedReader/WrappedReaderTests.cs
+++ b/src/System.Private.Xml/tests/Readers/WrappedReader/WrappedReaderTests.cs
@@ -9,370 +9,69 @@ namespace System.Xml.Tests
{
public partial class WrappedReaderTest : CGenericTestModule
{
- private static void RunTestCaseAsync(Func<CTestBase> testCaseGenerator)
+ [Theory]
+ [XmlTests(nameof(Create))]
+ public void RunTests(XunitTestCase testCase)
{
- CModInfo.CommandLine = "/async";
- RunTestCase(testCaseGenerator);
+ testCase.Run();
}
- private static void RunTestCase(Func<CTestBase> testCaseGenerator)
+ public static CTestModule Create()
{
var module = new WrappedReaderTest();
module.Init(null);
- module.AddChild(testCaseGenerator());
- module.Execute();
-
- Assert.Equal(0, module.FailCount);
- }
-
- private static void RunTest(Func<CTestBase> testCaseGenerator)
- {
- RunTestCase(testCaseGenerator);
- RunTestCaseAsync(testCaseGenerator);
- }
-
- [Fact]
- [OuterLoop]
- public static void ErrorConditionReader()
- {
- RunTest(() => new TCErrorConditionReader() { Attribute = new TestCase() { Name = "ErrorCondition", Desc = "WrappedReader" } });
- }
-
- [Fact]
- [OuterLoop]
- public static void XMLExceptionReader()
- {
- RunTest(() => new TCXMLExceptionReader() { Attribute = new TestCase() { Name = "XMLException", Desc = "WrappedReader" } });
- }
-
- [Fact]
- [OuterLoop]
- public static void LinePosReader()
- {
- RunTest(() => new TCLinePosReader() { Attribute = new TestCase() { Name = "LinePos", Desc = "WrappedReader" } });
- }
-
- [Fact]
- [OuterLoop]
- public static void DepthReader()
- {
- RunTest(() => new TCDepthReader() { Attribute = new TestCase() { Name = "Depth", Desc = "WrappedReader" } });
- }
-
- [Fact]
- [OuterLoop]
- public static void NamespaceReader()
- {
- RunTest(() => new TCNamespaceReader() { Attribute = new TestCase() { Name = "Namespace", Desc = "WrappedReader" } });
- }
-
- [Fact]
- [OuterLoop]
- public static void LookupNamespaceReader()
- {
- RunTest(() => new TCLookupNamespaceReader() { Attribute = new TestCase() { Name = "LookupNamespace", Desc = "WrappedReader" } });
- }
-
- [Fact]
- [OuterLoop]
- public static void HasValueReader()
- {
- RunTest(() => new TCHasValueReader() { Attribute = new TestCase() { Name = "HasValue", Desc = "WrappedReader" } });
- }
-
- [Fact]
- [OuterLoop]
- public static void IsEmptyElementReader()
- {
- RunTest(() => new TCIsEmptyElementReader() { Attribute = new TestCase() { Name = "IsEmptyElement", Desc = "WrappedReader" } });
- }
-
- [Fact]
- [OuterLoop]
- public static void XmlSpaceReader()
- {
- RunTest(() => new TCXmlSpaceReader() { Attribute = new TestCase() { Name = "XmlSpace", Desc = "WrappedReader" } });
- }
-
- [Fact]
- [OuterLoop]
- public static void XmlLangReader()
- {
- RunTest(() => new TCXmlLangReader() { Attribute = new TestCase() { Name = "XmlLang", Desc = "WrappedReader" } });
- }
-
- [Fact]
- [OuterLoop]
- public static void SkipReader()
- {
- RunTest(() => new TCSkipReader() { Attribute = new TestCase() { Name = "Skip", Desc = "WrappedReader" } });
- }
-
- [Fact]
- [OuterLoop]
- public static void InvalidXMLReader()
- {
- RunTest(() => new TCInvalidXMLReader() { Attribute = new TestCase() { Name = "InvalidXML", Desc = "WrappedReader" } });
- }
-
- [Fact]
- [OuterLoop]
- public static void AttributeAccessReader()
- {
- RunTest(() => new TCAttributeAccessReader() { Attribute = new TestCase() { Name = "AttributeAccess", Desc = "WrappedReader" } });
- }
-
- [Fact]
- [OuterLoop]
- public static void ThisNameReader()
- {
- RunTest(() => new TCThisNameReader() { Attribute = new TestCase() { Name = "This(Name) and This(Name, Namespace)", Desc = "WrappedReader" } });
- }
-
- [Fact]
- [OuterLoop]
- public static void MoveToAttributeReader()
- {
- RunTest(() => new TCMoveToAttributeReader() { Attribute = new TestCase() { Name = "MoveToAttribute(Name) and MoveToAttribute(Name, Namespace)", Desc = "WrappedReader" } });
- }
-
- [Fact]
- [OuterLoop]
- public static void GetAttributeOrdinalReader()
- {
- RunTest(() => new TCGetAttributeOrdinalReader() { Attribute = new TestCase() { Name = "GetAttribute (Ordinal)", Desc = "WrappedReader" } });
- }
-
- [Fact]
- [OuterLoop]
- public static void GetAttributeNameReader()
- {
- RunTest(() => new TCGetAttributeNameReader() { Attribute = new TestCase() { Name = "GetAttribute(Name) and GetAttribute(Name, Namespace)", Desc = "WrappedReader" } });
- }
-
- [Fact]
- [OuterLoop]
- public static void ThisOrdinalReader()
- {
- RunTest(() => new TCThisOrdinalReader() { Attribute = new TestCase() { Name = "This [Ordinal]", Desc = "WrappedReader" } });
- }
-
- [Fact]
- [OuterLoop]
- public static void MoveToAttributeOrdinalReader()
- {
- RunTest(() => new TCMoveToAttributeOrdinalReader() { Attribute = new TestCase() { Name = "MoveToAttribute(Ordinal)", Desc = "WrappedReader" } });
- }
-
- [Fact]
- [OuterLoop]
- public static void MoveToFirstAttributeReader()
- {
- RunTest(() => new TCMoveToFirstAttributeReader() { Attribute = new TestCase() { Name = "MoveToFirstAttribute()", Desc = "WrappedReader" } });
- }
-
- [Fact]
- [OuterLoop]
- public static void MoveToNextAttributeReader()
- {
- RunTest(() => new TCMoveToNextAttributeReader() { Attribute = new TestCase() { Name = "MoveToNextAttribute()", Desc = "WrappedReader" } });
- }
-
- [Fact]
- [OuterLoop]
- public static void AttributeTestReader()
- {
- RunTest(() => new TCAttributeTestReader() { Attribute = new TestCase() { Name = "Attribute Test when NodeType != Attributes", Desc = "WrappedReader" } });
- }
-
- [Fact]
- [OuterLoop]
- public static void AttributeXmlDeclarationReader()
- {
- RunTest(() => new TCAttributeXmlDeclarationReader() { Attribute = new TestCase() { Name = "Attributes test on XmlDeclaration DCR52258", Desc = "WrappedReader" } });
- }
-
- [Fact]
- [OuterLoop]
- public static void XmlnsReader()
- {
- RunTest(() => new TCXmlnsReader() { Attribute = new TestCase() { Name = "xmlns as local name DCR50345", Desc = "WrappedReader" } });
- }
-
- [Fact]
- [OuterLoop]
- public static void XmlnsPrefixReader()
- {
- RunTest(() => new TCXmlnsPrefixReader() { Attribute = new TestCase() { Name = "bounded namespace to xmlns prefix DCR50881", Desc = "WrappedReader" } });
- }
-
- [Fact]
- [OuterLoop]
- public static void ReadInnerXmlReader()
- {
- RunTest(() => new TCReadInnerXmlReader() { Attribute = new TestCase() { Name = "ReadInnerXml", Desc = "WrappedReader" } });
- }
-
- [Fact]
- [OuterLoop]
- public static void MoveToContentReader()
- {
- RunTest(() => new TCMoveToContentReader() { Attribute = new TestCase() { Name = "MoveToContent", Desc = "WrappedReader" } });
- }
-
- [Fact]
- [OuterLoop]
- public static void IsStartElementReader()
- {
- RunTest(() => new TCIsStartElementReader() { Attribute = new TestCase() { Name = "IsStartElement", Desc = "WrappedReader" } });
- }
-
- [Fact]
- [OuterLoop]
- public static void ReadStartElementReader()
- {
- RunTest(() => new TCReadStartElementReader() { Attribute = new TestCase() { Name = "ReadStartElement", Desc = "WrappedReader" } });
- }
-
- [Fact]
- [OuterLoop]
- public static void ReadEndElementReader()
- {
- RunTest(() => new TCReadEndElementReader() { Attribute = new TestCase() { Name = "ReadEndElement", Desc = "WrappedReader" } });
- }
-
- [Fact]
- [OuterLoop]
- public static void ResolveEntityReader()
- {
- RunTest(() => new TCResolveEntityReader() { Attribute = new TestCase() { Name = "ResolveEntity and ReadAttributeValue", Desc = "WrappedReader" } });
- }
-
- [Fact]
- [OuterLoop]
- public static void ReadAttributeValueReader()
- {
- RunTest(() => new TCReadAttributeValueReader() { Attribute = new TestCase() { Name = "ReadAttributeValue", Desc = "WrappedReader" } });
- }
-
- [Fact]
- [OuterLoop]
- public static void ReadReader()
- {
- RunTest(() => new TCReadReader() { Attribute = new TestCase() { Name = "Read", Desc = "WrappedReader" } });
- }
-
- [Fact]
- [OuterLoop]
- public static void MoveToElementReader()
- {
- RunTest(() => new TCMoveToElementReader() { Attribute = new TestCase() { Name = "MoveToElement", Desc = "WrappedReader" } });
- }
-
- [Fact]
- [OuterLoop]
- public static void DisposeReader()
- {
- RunTest(() => new TCDisposeReader() { Attribute = new TestCase() { Name = "Dispose", Desc = "WrappedReader" } });
- }
-
- [Fact]
- [OuterLoop]
- public static void BufferBoundariesReader()
- {
- RunTest(() => new TCBufferBoundariesReader() { Attribute = new TestCase() { Name = "Buffer Boundaries", Desc = "WrappedReader" } });
- }
-
- [Fact]
- [OuterLoop]
- public static void XmlNodeIntegrityTestFileAfterClose()
- {
- RunTest(() => new TCXmlNodeIntegrityTestFile() { Attribute = new TestCase() { Name = "AfterClose", Desc = "AfterClose" } });
- }
-
- [Fact]
- [OuterLoop]
- public static void XmlNodeIntegrityTestFileAfterCloseInMiddle()
- {
- RunTest(() => new TCXmlNodeIntegrityTestFile() { Attribute = new TestCase() { Name = "AfterCloseInTheMiddle", Desc = "AfterCloseInTheMiddle" } });
- }
-
- [Fact]
- [OuterLoop]
- public static void XmlNodeIntegrityTestFileBeforeRead()
- {
- RunTest(() => new TCXmlNodeIntegrityTestFile() { Attribute = new TestCase() { Name = "BeforeRead", Desc = "BeforeRead" } });
- }
-
- [Fact]
- [OuterLoop]
- public static void XmlNodeIntegrityTestFileAfterReadIsFalse()
- {
- RunTest(() => new TCXmlNodeIntegrityTestFile() { Attribute = new TestCase() { Name = "AfterReadIsFalse", Desc = "AfterReadIsFalse" } });
- }
-
- [Fact]
- [OuterLoop]
- public static void ReadSubtreeReader()
- {
- RunTest(() => new TCReadSubtreeReader() { Attribute = new TestCase() { Name = "Read Subtree", Desc = "WrappedReader" } });
- }
-
- [Fact]
- [OuterLoop]
- public static void ReadToDescendantReader()
- {
- RunTest(() => new TCReadToDescendantReader() { Attribute = new TestCase() { Name = "ReadToDescendant", Desc = "WrappedReader" } });
- }
-
- [Fact]
- [OuterLoop]
- public static void ReadToNextSiblingReader()
- {
- RunTest(() => new TCReadToNextSiblingReader() { Attribute = new TestCase() { Name = "ReadToNextSibling", Desc = "WrappedReader" } });
- }
-
- [Fact]
- [OuterLoop]
- public static void ReadValueReader()
- {
- RunTest(() => new TCReadValueReader() { Attribute = new TestCase() { Name = "ReadValue", Desc = "WrappedReader" } });
- }
-
- [Fact]
- [OuterLoop]
- public static void ReadContentAsBase64Reader()
- {
- RunTest(() => new TCReadContentAsBase64Reader() { Attribute = new TestCase() { Name = "ReadContentAsBase64", Desc = "WrappedReader" } });
- }
-
- [Fact]
- [OuterLoop]
- public static void ReadElementContentAsBase64Reader()
- {
- RunTest(() => new TCReadElementContentAsBase64Reader() { Attribute = new TestCase() { Name = "ReadElementContentAsBase64", Desc = "WrappedReader" } });
- }
-
- [Fact]
- [OuterLoop]
- public static void ReadContentAsBinHexReader()
- {
- RunTest(() => new TCReadContentAsBinHexReader() { Attribute = new TestCase() { Name = "ReadContentAsBinHex", Desc = "WrappedReader" } });
- }
-
- [Fact]
- [OuterLoop]
- public static void ReadElementContentAsBinHexReader()
- {
- RunTest(() => new TCReadElementContentAsBinHexReader() { Attribute = new TestCase() { Name = "ReadElementContentAsBinHex", Desc = "WrappedReader" } });
- }
-
- [Fact]
- [OuterLoop]
- public static void ReadToFollowingReader()
- {
- RunTest(() => new TCReadToFollowingReader() { Attribute = new TestCase() { Name = "ReadToFollowing", Desc = "WrappedReader" } });
+ module.AddChild(new TCErrorConditionReader() { Attribute = new TestCase() { Name = "ErrorCondition", Desc = "WrappedReader" } });
+ module.AddChild(new TCXMLExceptionReader() { Attribute = new TestCase() { Name = "XMLException", Desc = "WrappedReader" } });
+ module.AddChild(new TCLinePosReader() { Attribute = new TestCase() { Name = "LinePos", Desc = "WrappedReader" } });
+ module.AddChild(new TCDepthReader() { Attribute = new TestCase() { Name = "Depth", Desc = "WrappedReader" } });
+ module.AddChild(new TCNamespaceReader() { Attribute = new TestCase() { Name = "Namespace", Desc = "WrappedReader" } });
+ module.AddChild(new TCLookupNamespaceReader() { Attribute = new TestCase() { Name = "LookupNamespace", Desc = "WrappedReader" } });
+ module.AddChild(new TCHasValueReader() { Attribute = new TestCase() { Name = "HasValue", Desc = "WrappedReader" } });
+ module.AddChild(new TCIsEmptyElementReader() { Attribute = new TestCase() { Name = "IsEmptyElement", Desc = "WrappedReader" } });
+ module.AddChild(new TCXmlSpaceReader() { Attribute = new TestCase() { Name = "XmlSpace", Desc = "WrappedReader" } });
+ module.AddChild(new TCXmlLangReader() { Attribute = new TestCase() { Name = "XmlLang", Desc = "WrappedReader" } });
+ module.AddChild(new TCSkipReader() { Attribute = new TestCase() { Name = "Skip", Desc = "WrappedReader" } });
+ module.AddChild(new TCInvalidXMLReader() { Attribute = new TestCase() { Name = "InvalidXML", Desc = "WrappedReader" } });
+ module.AddChild(new TCAttributeAccessReader() { Attribute = new TestCase() { Name = "AttributeAccess", Desc = "WrappedReader" } });
+ module.AddChild(new TCThisNameReader() { Attribute = new TestCase() { Name = "This(Name) and This(Name, Namespace)", Desc = "WrappedReader" } });
+ module.AddChild(new TCMoveToAttributeReader() { Attribute = new TestCase() { Name = "MoveToAttribute(Name) and MoveToAttribute(Name, Namespace)", Desc = "WrappedReader" } });
+ module.AddChild(new TCGetAttributeOrdinalReader() { Attribute = new TestCase() { Name = "GetAttribute (Ordinal)", Desc = "WrappedReader" } });
+ module.AddChild(new TCGetAttributeNameReader() { Attribute = new TestCase() { Name = "GetAttribute(Name) and GetAttribute(Name, Namespace)", Desc = "WrappedReader" } });
+ module.AddChild(new TCThisOrdinalReader() { Attribute = new TestCase() { Name = "This [Ordinal]", Desc = "WrappedReader" } });
+ module.AddChild(new TCMoveToAttributeOrdinalReader() { Attribute = new TestCase() { Name = "MoveToAttribute(Ordinal)", Desc = "WrappedReader" } });
+ module.AddChild(new TCMoveToFirstAttributeReader() { Attribute = new TestCase() { Name = "MoveToFirstAttribute()", Desc = "WrappedReader" } });
+ module.AddChild(new TCMoveToNextAttributeReader() { Attribute = new TestCase() { Name = "MoveToNextAttribute()", Desc = "WrappedReader" } });
+ module.AddChild(new TCAttributeTestReader() { Attribute = new TestCase() { Name = "Attribute Test when NodeType != Attributes", Desc = "WrappedReader" } });
+ module.AddChild(new TCAttributeXmlDeclarationReader() { Attribute = new TestCase() { Name = "Attributes test on XmlDeclaration DCR52258", Desc = "WrappedReader" } });
+ module.AddChild(new TCXmlnsReader() { Attribute = new TestCase() { Name = "xmlns as local name DCR50345", Desc = "WrappedReader" } });
+ module.AddChild(new TCXmlnsPrefixReader() { Attribute = new TestCase() { Name = "bounded namespace to xmlns prefix DCR50881", Desc = "WrappedReader" } });
+ module.AddChild(new TCReadInnerXmlReader() { Attribute = new TestCase() { Name = "ReadInnerXml", Desc = "WrappedReader" } });
+ module.AddChild(new TCMoveToContentReader() { Attribute = new TestCase() { Name = "MoveToContent", Desc = "WrappedReader" } });
+ module.AddChild(new TCIsStartElementReader() { Attribute = new TestCase() { Name = "IsStartElement", Desc = "WrappedReader" } });
+ module.AddChild(new TCReadStartElementReader() { Attribute = new TestCase() { Name = "ReadStartElement", Desc = "WrappedReader" } });
+ module.AddChild(new TCReadEndElementReader() { Attribute = new TestCase() { Name = "ReadEndElement", Desc = "WrappedReader" } });
+ module.AddChild(new TCResolveEntityReader() { Attribute = new TestCase() { Name = "ResolveEntity and ReadAttributeValue", Desc = "WrappedReader" } });
+ module.AddChild(new TCReadAttributeValueReader() { Attribute = new TestCase() { Name = "ReadAttributeValue", Desc = "WrappedReader" } });
+ module.AddChild(new TCReadReader() { Attribute = new TestCase() { Name = "Read", Desc = "WrappedReader" } });
+ module.AddChild(new TCMoveToElementReader() { Attribute = new TestCase() { Name = "MoveToElement", Desc = "WrappedReader" } });
+ module.AddChild(new TCDisposeReader() { Attribute = new TestCase() { Name = "Dispose", Desc = "WrappedReader" } });
+ module.AddChild(new TCBufferBoundariesReader() { Attribute = new TestCase() { Name = "Buffer Boundaries", Desc = "WrappedReader" } });
+ module.AddChild(new TCXmlNodeIntegrityTestFile() { Attribute = new TestCase() { Name = "AfterClose", Desc = "AfterClose" } });
+ module.AddChild(new TCXmlNodeIntegrityTestFile() { Attribute = new TestCase() { Name = "AfterCloseInTheMiddle", Desc = "AfterCloseInTheMiddle" } });
+ module.AddChild(new TCXmlNodeIntegrityTestFile() { Attribute = new TestCase() { Name = "BeforeRead", Desc = "BeforeRead" } });
+ module.AddChild(new TCXmlNodeIntegrityTestFile() { Attribute = new TestCase() { Name = "AfterReadIsFalse", Desc = "AfterReadIsFalse" } });
+ module.AddChild(new TCReadSubtreeReader() { Attribute = new TestCase() { Name = "Read Subtree", Desc = "WrappedReader" } });
+ module.AddChild(new TCReadToDescendantReader() { Attribute = new TestCase() { Name = "ReadToDescendant", Desc = "WrappedReader" } });
+ module.AddChild(new TCReadToNextSiblingReader() { Attribute = new TestCase() { Name = "ReadToNextSibling", Desc = "WrappedReader" } });
+ module.AddChild(new TCReadValueReader() { Attribute = new TestCase() { Name = "ReadValue", Desc = "WrappedReader" } });
+ module.AddChild(new TCReadContentAsBase64Reader() { Attribute = new TestCase() { Name = "ReadContentAsBase64", Desc = "WrappedReader" } });
+ module.AddChild(new TCReadElementContentAsBase64Reader() { Attribute = new TestCase() { Name = "ReadElementContentAsBase64", Desc = "WrappedReader" } });
+ module.AddChild(new TCReadContentAsBinHexReader() { Attribute = new TestCase() { Name = "ReadContentAsBinHex", Desc = "WrappedReader" } });
+ module.AddChild(new TCReadElementContentAsBinHexReader() { Attribute = new TestCase() { Name = "ReadElementContentAsBinHex", Desc = "WrappedReader" } });
+ module.AddChild(new TCReadToFollowingReader() { Attribute = new TestCase() { Name = "ReadToFollowing", Desc = "WrappedReader" } });
+
+ return module;
}
}
}
diff --git a/src/System.Private.Xml/tests/Writers/RwFactory/CFactoryModule.cs b/src/System.Private.Xml/tests/Writers/RwFactory/CFactoryModule.cs
index bca2f5dd09..33e5b0fe09 100644
--- a/src/System.Private.Xml/tests/Writers/RwFactory/CFactoryModule.cs
+++ b/src/System.Private.Xml/tests/Writers/RwFactory/CFactoryModule.cs
@@ -9,26 +9,20 @@ namespace System.Xml.Tests
{
public partial class CFactoryModule : CXmlDriverModule
{
- [Fact]
- [OuterLoop]
- public static void RunTests()
+ [Theory]
+ [XmlTests(nameof(Create))]
+ public void RunTests(XunitTestCase testCase)
{
- CModInfo.CommandLine = "";
- var module = new CFactoryModule();
-
- module.Init(null);
- module.Execute();
+ testCase.Run();
}
- [Fact]
- [OuterLoop]
- public static void RunTestsAsync()
+ public static CTestModule Create()
{
- CModInfo.CommandLine = "/async";
var module = new CFactoryModule();
module.Init(null);
- module.Execute();
+
+ return module;
}
}
}
diff --git a/src/System.Private.Xml/tests/Writers/RwFactory/System.Xml.RW.RwFactory.Tests.csproj b/src/System.Private.Xml/tests/Writers/RwFactory/System.Xml.RW.RwFactory.Tests.csproj
index b02e4eb875..ebfbf9a48b 100644
--- a/src/System.Private.Xml/tests/Writers/RwFactory/System.Xml.RW.RwFactory.Tests.csproj
+++ b/src/System.Private.Xml/tests/Writers/RwFactory/System.Xml.RW.RwFactory.Tests.csproj
@@ -21,6 +21,7 @@
<Compile Include="CXmlDriverVariation.cs" />
<Compile Include="ReaderFactory.cs" />
<Compile Include="WriterFactory.cs" />
+ <Compile Include="$(CommonTestPath)\System\Xml\DisableParallelization.cs" />
</ItemGroup>
<ItemGroup>
<ProjectReference Include="$(CommonTestPath)\System\Xml\ModuleCore\ModuleCore.csproj" />
diff --git a/src/System.Private.Xml/tests/XmlConvert/System.Xml.RW.XmlConvert.Tests.csproj b/src/System.Private.Xml/tests/XmlConvert/System.Xml.RW.XmlConvert.Tests.csproj
index ab7570f2c9..c954f015e3 100644
--- a/src/System.Private.Xml/tests/XmlConvert/System.Xml.RW.XmlConvert.Tests.csproj
+++ b/src/System.Private.Xml/tests/XmlConvert/System.Xml.RW.XmlConvert.Tests.csproj
@@ -44,6 +44,7 @@
<Compile Include="XmlIdeographicCharConvertTests1.cs" />
<Compile Include="XmlIdeographicCharConvertTests2.cs" />
<Compile Include="XmlIdeographicCharConvertTests3.cs" />
+ <Compile Include="$(CommonTestPath)\System\Xml\DisableParallelization.cs" />
</ItemGroup>
<ItemGroup>
<ProjectReference Include="$(CommonTestPath)\System\Xml\ModuleCore\ModuleCore.csproj" />
diff --git a/src/System.Private.Xml/tests/XmlConvert/XmlConvertTests.cs b/src/System.Private.Xml/tests/XmlConvert/XmlConvertTests.cs
index 51acc9c772..86bd00aee8 100644
--- a/src/System.Private.Xml/tests/XmlConvert/XmlConvertTests.cs
+++ b/src/System.Private.Xml/tests/XmlConvert/XmlConvertTests.cs
@@ -9,204 +9,47 @@ namespace System.Xml.Tests
{
public class XmlConvertTests : CTestModule
{
- [Fact]
- [OuterLoop]
- public static void EncodeDecodeTests()
+ [Theory]
+ [XmlTests(nameof(Create))]
+ public void RunTests(XunitTestCase testCase)
{
- RunTestCase(new EncodeDecodeTests { Attribute = new TestCase { Name = "EncodeName/DecodeName", Desc = "XmlConvert" } });
+ testCase.Run();
}
- [Fact]
- [OuterLoop]
- public static void MiscellaneousTests()
- {
- RunTestCase(new MiscellaneousTests { Attribute = new TestCase { Name = "Misc. Bug Regressions", Desc = "XmlConvert" } });
- }
-
- [Fact]
- [OuterLoop]
- public static void SqlXmlConvertTests0()
- {
- RunTestCase(new SqlXmlConvertTests0 { Attribute = new TestCase { Name = "2. XmlConvert (SQL-XML EncodeName) EncodeNmToken-EncodeLocalNmToken", Desc = "XmlConvert" } });
- }
-
- [Fact]
- [OuterLoop]
- public static void SqlXmlConvertTests1()
- {
- RunTestCase(new SqlXmlConvertTests1 { Attribute = new TestCase { Name = "1. XmlConvert (SQL-XML EncodeName) EncodeName-EncodeLocalName", Desc = "XmlConvert" } });
- }
-
- [Fact]
- [OuterLoop]
- public static void SqlXmlConvertTests2()
- {
- RunTestCase(new SqlXmlConvertTests2 { Attribute = new TestCase { Name = "2. XmlConvert (SQL-XML EncodeName) EncodeName-DecodeName", Desc = "XmlConvert" } });
- }
-
- [Fact]
- [OuterLoop]
- public static void SqlXmlConvertTests3()
- {
- RunTestCase(new SqlXmlConvertTests3 { Attribute = new TestCase { Name = "3. XmlConvert (SQL-XML EncodeName) EncodeLocalName only", Desc = "XmlConvert" } });
- }
-
- [Fact]
- [OuterLoop]
- public static void ToTypeTests()
- {
- RunTestCase(new ToTypeTests { Attribute = new TestCase { Name = "XmlConvert type conversion functions", Desc = "XmlConvert" } });
- }
-
- [Fact]
- [OuterLoop]
- public static void VerifyNameTests1()
- {
- RunTestCase(new VerifyNameTests1 { Attribute = new TestCase { Name = "VerifyName,VerifyNCName,VerifyNMTOKEN,VerifyXmlChar,VerifyWhitespace,VerifyPublicId", Desc = "XmlConvert" } });
- }
-
- [Fact]
- [OuterLoop]
- public static void VerifyNameTests2()
- {
- RunTestCase(new VerifyNameTests2 { Attribute = new TestCase { Name = "VerifyName,VerifyNCName,VerifyNMTOKEN,VerifyXmlChar,VerifyWhitespace,VerifyPublicId", Desc = "XmlConvert" } });
- }
-
- [Fact]
- [OuterLoop]
- public static void VerifyNameTests3()
- {
- RunTestCase(new VerifyNameTests3 { Attribute = new TestCase { Name = "VerifyName,VerifyNCName,VerifyNMTOKEN,VerifyXmlChar,VerifyWhitespace,VerifyPublicId", Desc = "XmlConvert" } });
- }
-
- [Fact]
- [OuterLoop]
- public static void VerifyNameTests4()
- {
- RunTestCase(new VerifyNameTests4 { Attribute = new TestCase { Name = "VerifyName,VerifyNCName,VerifyNMTOKEN,VerifyXmlChar,VerifyWhitespace,VerifyPublicId", Desc = "XmlConvert" } });
- }
-
- [Fact]
- [OuterLoop]
- public static void VerifyNameTests5()
- {
- RunTestCase(new VerifyNameTests5 { Attribute = new TestCase { Name = "VerifyName,VerifyNCName,VerifyNMTOKEN,VerifyXmlChar,VerifyWhitespace,VerifyPublicId", Desc = "XmlConvert" } });
- }
-
- [Fact]
- [OuterLoop]
- public static void XmlBaseCharConvertTests1()
- {
- RunTestCase(new XmlBaseCharConvertTests1 { Attribute = new TestCase { Name = "1. XmlConvert (Boundary Base Char) EncodeName-EncodeLocalName", Desc = "XmlConvert" } });
- }
-
- [Fact]
- [OuterLoop]
- public static void XmlBaseCharConvertTests2()
- {
- RunTestCase(new XmlBaseCharConvertTests2 { Attribute = new TestCase { Name = "2. XmlConvert (Boundary Base Char) EncodeNmToken-EncodeLocalNmToken", Desc = "XmlConvert" } });
- }
-
- [Fact]
- [OuterLoop]
- public static void XmlBaseCharConvertTests3()
- {
- RunTestCase(new XmlBaseCharConvertTests3 { Attribute = new TestCase { Name = "3. XmlConvert (Boundary Base Char) EncodeName-DecodeName ", Desc = "XmlConvert" } });
- }
-
- [Fact]
- [OuterLoop]
- public static void XmlCombiningCharConvertTests1()
- {
- RunTestCase(new XmlCombiningCharConvertTests1 { Attribute = new TestCase { Name = "1. XmlConvert (Boundary Combining Char) EncodeName-EncodeLocalName", Desc = "XmlConvert" } });
- }
-
- [Fact]
- [OuterLoop]
- public static void XmlCombiningCharConvertTests2()
- {
- RunTestCase(new XmlCombiningCharConvertTests2 { Attribute = new TestCase { Name = "2. XmlConvert (Boundary Combining Char) EncodeNmToken-EncodeLocalNmToken", Desc = "XmlConvert" } });
- }
-
- [Fact]
- [OuterLoop]
- public static void XmlCombiningCharConvertTests3()
- {
- RunTestCase(new XmlCombiningCharConvertTests3 { Attribute = new TestCase { Name = "3. XmlConvert (Boundary Combining Char) EncodeName-DecodeName", Desc = "XmlConvert" } });
- }
-
- [Fact]
- [OuterLoop]
- public static void XmlDigitCharConvertTests1()
- {
- RunTestCase(new XmlDigitCharConvertTests1 { Attribute = new TestCase { Name = "1. XmlConvert (Boundary Digit Char) EncodeName-EncodeLocalName", Desc = "XmlConvert" } });
- }
-
- [Fact]
- [OuterLoop]
- public static void XmlDigitCharConvertTests2()
- {
- RunTestCase(new XmlDigitCharConvertTests2 { Attribute = new TestCase { Name = "2. XmlConvert (Boundary Digit Char) EncodeNmToken-EncodeLocalNmToken", Desc = "XmlConvert" } });
- }
-
- [Fact]
- [OuterLoop]
- public static void XmlDigitCharConvertTests3()
- {
- RunTestCase(new XmlDigitCharConvertTests3 { Attribute = new TestCase { Name = "3. XmlConvert (Boundary Digit Char) EncodeName-DecodeName", Desc = "XmlConvert" } });
- }
-
- [Fact]
- [OuterLoop]
- public static void XmlEmbeddedNullCharConvertTests1()
- {
- RunTestCase(new XmlEmbeddedNullCharConvertTests1 { Attribute = new TestCase { Name = "1. XmlConvert (EmbeddedNull Char) EncodeName-EncodeLocalName", Desc = "XmlConvert" } });
- }
-
- [Fact]
- [OuterLoop]
- public static void XmlEmbeddedNullCharConvertTests2()
- {
- RunTestCase(new XmlEmbeddedNullCharConvertTests2 { Attribute = new TestCase { Name = "2. XmlConvert (EmbeddedNull Char) EncodeNmToken-EncodeLocalNmToken", Desc = "XmlConvert" } });
- }
-
- [Fact]
- [OuterLoop]
- public static void XmlEmbeddedNullCharConvertTests3()
- {
- RunTestCase(new XmlEmbeddedNullCharConvertTests3 { Attribute = new TestCase { Name = "3. XmlConvert (EmbeddedNull Char) EncodeName-DecodeName", Desc = "XmlConvert" } });
- }
-
- [Fact]
- [OuterLoop]
- public static void XmlIdeographicCharConvertTests1()
- {
- RunTestCase(new XmlIdeographicCharConvertTests1 { Attribute = new TestCase { Name = "1. XmlConvert (Boundary Ideographic Char) EncodeName-EncodeLocalName", Desc = "XmlConvert" } });
- }
-
- [Fact]
- [OuterLoop]
- public static void XmlIdeographicCharConvertTests2()
- {
- RunTestCase(new XmlIdeographicCharConvertTests2 { Attribute = new TestCase { Name = "2. XmlConvert (Boundary Ideographic Char) EncodeNmToken-EncodeLocalNmToken", Desc = "XmlConvert" } });
- }
-
- [Fact]
- [OuterLoop]
- public static void XmlIdeographicCharConvertTests3()
- {
- RunTestCase(new XmlIdeographicCharConvertTests3 { Attribute = new TestCase { Name = "3. XmlConvert (Boundary Ideographic Char) EncodeName-DecodeName", Desc = "XmlConvert" } });
- }
-
- private static void RunTestCase(CTestBase testCase)
+ public static CTestModule Create()
{
var module = new XmlConvertTests();
module.Init(null);
- module.AddChild(testCase);
- module.Execute();
-
- Assert.Equal(0, module.FailCount);
+ module.AddChild(new EncodeDecodeTests { Attribute = new TestCase { Name = "EncodeName/DecodeName", Desc = "XmlConvert" } });
+ module.AddChild(new MiscellaneousTests { Attribute = new TestCase { Name = "Misc. Bug Regressions", Desc = "XmlConvert" } });
+ module.AddChild(new SqlXmlConvertTests0 { Attribute = new TestCase { Name = "2. XmlConvert (SQL-XML EncodeName) EncodeNmToken-EncodeLocalNmToken", Desc = "XmlConvert" } });
+ module.AddChild(new SqlXmlConvertTests1 { Attribute = new TestCase { Name = "1. XmlConvert (SQL-XML EncodeName) EncodeName-EncodeLocalName", Desc = "XmlConvert" } });
+ module.AddChild(new SqlXmlConvertTests2 { Attribute = new TestCase { Name = "2. XmlConvert (SQL-XML EncodeName) EncodeName-DecodeName", Desc = "XmlConvert" } });
+ module.AddChild(new SqlXmlConvertTests3 { Attribute = new TestCase { Name = "3. XmlConvert (SQL-XML EncodeName) EncodeLocalName only", Desc = "XmlConvert" } });
+ module.AddChild(new ToTypeTests { Attribute = new TestCase { Name = "XmlConvert type conversion functions", Desc = "XmlConvert" } });
+ module.AddChild(new VerifyNameTests1 { Attribute = new TestCase { Name = "VerifyName,VerifyNCName,VerifyNMTOKEN,VerifyXmlChar,VerifyWhitespace,VerifyPublicId", Desc = "XmlConvert" } });
+ module.AddChild(new VerifyNameTests2 { Attribute = new TestCase { Name = "VerifyName,VerifyNCName,VerifyNMTOKEN,VerifyXmlChar,VerifyWhitespace,VerifyPublicId", Desc = "XmlConvert" } });
+ module.AddChild(new VerifyNameTests3 { Attribute = new TestCase { Name = "VerifyName,VerifyNCName,VerifyNMTOKEN,VerifyXmlChar,VerifyWhitespace,VerifyPublicId", Desc = "XmlConvert" } });
+ module.AddChild(new VerifyNameTests4 { Attribute = new TestCase { Name = "VerifyName,VerifyNCName,VerifyNMTOKEN,VerifyXmlChar,VerifyWhitespace,VerifyPublicId", Desc = "XmlConvert" } });
+ module.AddChild(new VerifyNameTests5 { Attribute = new TestCase { Name = "VerifyName,VerifyNCName,VerifyNMTOKEN,VerifyXmlChar,VerifyWhitespace,VerifyPublicId", Desc = "XmlConvert" } });
+ module.AddChild(new XmlBaseCharConvertTests1 { Attribute = new TestCase { Name = "1. XmlConvert (Boundary Base Char) EncodeName-EncodeLocalName", Desc = "XmlConvert" } });
+ module.AddChild(new XmlBaseCharConvertTests2 { Attribute = new TestCase { Name = "2. XmlConvert (Boundary Base Char) EncodeNmToken-EncodeLocalNmToken", Desc = "XmlConvert" } });
+ module.AddChild(new XmlBaseCharConvertTests3 { Attribute = new TestCase { Name = "3. XmlConvert (Boundary Base Char) EncodeName-DecodeName ", Desc = "XmlConvert" } });
+ module.AddChild(new XmlCombiningCharConvertTests1 { Attribute = new TestCase { Name = "1. XmlConvert (Boundary Combining Char) EncodeName-EncodeLocalName", Desc = "XmlConvert" } });
+ module.AddChild(new XmlCombiningCharConvertTests2 { Attribute = new TestCase { Name = "2. XmlConvert (Boundary Combining Char) EncodeNmToken-EncodeLocalNmToken", Desc = "XmlConvert" } });
+ module.AddChild(new XmlCombiningCharConvertTests3 { Attribute = new TestCase { Name = "3. XmlConvert (Boundary Combining Char) EncodeName-DecodeName", Desc = "XmlConvert" } });
+ module.AddChild(new XmlDigitCharConvertTests1 { Attribute = new TestCase { Name = "1. XmlConvert (Boundary Digit Char) EncodeName-EncodeLocalName", Desc = "XmlConvert" } });
+ module.AddChild(new XmlDigitCharConvertTests2 { Attribute = new TestCase { Name = "2. XmlConvert (Boundary Digit Char) EncodeNmToken-EncodeLocalNmToken", Desc = "XmlConvert" } });
+ module.AddChild(new XmlDigitCharConvertTests3 { Attribute = new TestCase { Name = "3. XmlConvert (Boundary Digit Char) EncodeName-DecodeName", Desc = "XmlConvert" } });
+ module.AddChild(new XmlEmbeddedNullCharConvertTests1 { Attribute = new TestCase { Name = "1. XmlConvert (EmbeddedNull Char) EncodeName-EncodeLocalName", Desc = "XmlConvert" } });
+ module.AddChild(new XmlEmbeddedNullCharConvertTests2 { Attribute = new TestCase { Name = "2. XmlConvert (EmbeddedNull Char) EncodeNmToken-EncodeLocalNmToken", Desc = "XmlConvert" } });
+ module.AddChild(new XmlEmbeddedNullCharConvertTests3 { Attribute = new TestCase { Name = "3. XmlConvert (EmbeddedNull Char) EncodeName-DecodeName", Desc = "XmlConvert" } });
+ module.AddChild(new XmlIdeographicCharConvertTests1 { Attribute = new TestCase { Name = "1. XmlConvert (Boundary Ideographic Char) EncodeName-EncodeLocalName", Desc = "XmlConvert" } });
+ module.AddChild(new XmlIdeographicCharConvertTests2 { Attribute = new TestCase { Name = "2. XmlConvert (Boundary Ideographic Char) EncodeNmToken-EncodeLocalNmToken", Desc = "XmlConvert" } });
+ module.AddChild(new XmlIdeographicCharConvertTests3 { Attribute = new TestCase { Name = "3. XmlConvert (Boundary Ideographic Char) EncodeName-DecodeName", Desc = "XmlConvert" } });
+
+ return module;
}
}
}
diff --git a/src/System.Private.Xml/tests/XmlReaderLib/System.Xml.RW.XmlReaderLib.csproj b/src/System.Private.Xml/tests/XmlReaderLib/System.Xml.RW.XmlReaderLib.csproj
index 456772fe64..8ee7108742 100644
--- a/src/System.Private.Xml/tests/XmlReaderLib/System.Xml.RW.XmlReaderLib.csproj
+++ b/src/System.Private.Xml/tests/XmlReaderLib/System.Xml.RW.XmlReaderLib.csproj
@@ -87,4 +87,4 @@
<ProjectReference Include="$(CommonTestPath)\System\Xml\XmlCoreTest\XmlCoreTest.csproj" />
</ItemGroup>
<Import Project="$([MSBuild]::GetDirectoryNameOfFileAbove($(MSBuildThisFileDirectory), dir.targets))\dir.targets" />
-</Project> \ No newline at end of file
+</Project>
diff --git a/src/System.Private.Xml/tests/XmlSerializer/XmlSerializerTests.cs b/src/System.Private.Xml/tests/XmlSerializer/XmlSerializerTests.cs
index bbe198b0f1..821329e542 100644
--- a/src/System.Private.Xml/tests/XmlSerializer/XmlSerializerTests.cs
+++ b/src/System.Private.Xml/tests/XmlSerializer/XmlSerializerTests.cs
@@ -32,13 +32,7 @@ public static partial class XmlSerializerTests
method.Invoke(null, new object[] { 1 });
#endif
#if XMLSERIALIZERGENERATORTESTS
- string path = Path.GetDirectoryName(typeof(XmlSerializerTests).Assembly.Location);
- string serializername = typeof(TypeWithDateTimeStringProperty).Assembly.GetName().Name + ".XmlSerializers.dll";
- string serializerPath = Path.Combine(path, serializername);
- if (File.Exists(serializerPath))
- {
- method.Invoke(null, new object[] { 3 });
- }
+ method.Invoke(null, new object[] { 3 });
#endif
}
}
diff --git a/src/System.Reflection.DispatchProxy/pkg/System.Reflection.DispatchProxy.pkgproj b/src/System.Reflection.DispatchProxy/pkg/System.Reflection.DispatchProxy.pkgproj
index c7b214e621..426087ed03 100644
--- a/src/System.Reflection.DispatchProxy/pkg/System.Reflection.DispatchProxy.pkgproj
+++ b/src/System.Reflection.DispatchProxy/pkg/System.Reflection.DispatchProxy.pkgproj
@@ -13,17 +13,21 @@
<HarvestIncludePaths Include="ref/netstandard1.3;lib/netstandard1.3" />
</ItemGroup>
<ItemGroup>
- <InboxOnTargetFramework Include="netcoreapp2.0" />
- <InboxOnTargetFramework Include="$(UAPvNextTFM)" />
- <File Include="$(PlaceholderFile)">
- <TargetPath>runtimes/aot/lib/$(UAPvNextTFM)</TargetPath>
- </File>
<InboxOnTargetFramework Include="MonoAndroid10" />
<InboxOnTargetFramework Include="MonoTouch10" />
<InboxOnTargetFramework Include="xamarinios10" />
<InboxOnTargetFramework Include="xamarinmac20" />
<InboxOnTargetFramework Include="xamarintvos10" />
<InboxOnTargetFramework Include="xamarinwatchos10" />
+
+ <!-- Since UAP and .NETCoreApp are package based we still want to enable
+ OOBing libraries that happen to overlap with their framework package.
+ This avoids us having to lock the API in our NuGet packages just
+ to match what shipped inbox: since we can provide a new library
+ we can update it to add API without raising the netstandard version. -->
+ <ValidatePackageSuppression Include="TreatAsOutOfBox">
+ <Value>.NETCoreApp;UAP</Value>
+ </ValidatePackageSuppression>
</ItemGroup>
<Import Project="$([MSBuild]::GetDirectoryNameOfFileAbove($(MSBuildThisFileDirectory), dir.targets))\dir.targets" />
</Project> \ No newline at end of file
diff --git a/src/System.Reflection.DispatchProxy/src/Configurations.props b/src/System.Reflection.DispatchProxy/src/Configurations.props
index 3fbe32b9a2..3fbbd69075 100644
--- a/src/System.Reflection.DispatchProxy/src/Configurations.props
+++ b/src/System.Reflection.DispatchProxy/src/Configurations.props
@@ -4,12 +4,13 @@
<PackageConfigurations>
netfx;
netstandard;
+ netcoreapp2.0;
+ uapaot-Windows_NT;
+ uap-Windows_NT;
</PackageConfigurations>
<BuildConfigurations>
$(PackageConfigurations);
- uapaot-Windows_NT;
netcoreapp;
- uap-Windows_NT;
</BuildConfigurations>
</PropertyGroup>
</Project>
diff --git a/src/System.Reflection.Metadata/pkg/System.Reflection.Metadata.pkgproj b/src/System.Reflection.Metadata/pkg/System.Reflection.Metadata.pkgproj
index ebaecb569b..d80cfdefce 100644
--- a/src/System.Reflection.Metadata/pkg/System.Reflection.Metadata.pkgproj
+++ b/src/System.Reflection.Metadata/pkg/System.Reflection.Metadata.pkgproj
@@ -13,8 +13,15 @@
<TargetFramework>portable-net45+win8</TargetFramework>
<Version>1.1.37</Version>
</FilePackageDependency>
- <InboxOnTargetFramework Include="netcoreapp2.0" />
- <InboxOnTargetFramework Include="$(UAPvNextTFM)" />
+
+ <!-- Since UAP and .NETCoreApp are package based we still want to enable
+ OOBing libraries that happen to overlap with their framework package.
+ This avoids us having to lock the API in our NuGet packages just
+ to match what shipped inbox: since we can provide a new library
+ we can update it to add API without raising the netstandard version. -->
+ <ValidatePackageSuppression Include="TreatAsOutOfBox">
+ <Value>.NETCoreApp;UAP</Value>
+ </ValidatePackageSuppression>
</ItemGroup>
<Import Project="$([MSBuild]::GetDirectoryNameOfFileAbove($(MSBuildThisFileDirectory), dir.targets))\dir.targets" />
</Project> \ No newline at end of file
diff --git a/src/System.Reflection.Metadata/ref/System.Reflection.Metadata.cs b/src/System.Reflection.Metadata/ref/System.Reflection.Metadata.cs
index d421ee938b..507b479bf6 100644
--- a/src/System.Reflection.Metadata/ref/System.Reflection.Metadata.cs
+++ b/src/System.Reflection.Metadata/ref/System.Reflection.Metadata.cs
@@ -99,6 +99,9 @@ namespace System.Reflection.Metadata
public System.Reflection.Metadata.StringHandle Name { get { throw null; } }
public System.Reflection.Metadata.BlobHandle PublicKey { get { throw null; } }
public System.Version Version { get { throw null; } }
+#if !NETSTANDARD11
+ public System.Reflection.AssemblyName GetAssemblyName() { throw null; }
+#endif
public System.Reflection.Metadata.CustomAttributeHandleCollection GetCustomAttributes() { throw null; }
public System.Reflection.Metadata.DeclarativeSecurityAttributeHandleCollection GetDeclarativeSecurityAttributes() { throw null; }
}
@@ -164,6 +167,9 @@ namespace System.Reflection.Metadata
public System.Reflection.Metadata.StringHandle Name { get { throw null; } }
public System.Reflection.Metadata.BlobHandle PublicKeyOrToken { get { throw null; } }
public System.Version Version { get { throw null; } }
+#if !NETSTANDARD11
+ public System.Reflection.AssemblyName GetAssemblyName() { throw null; }
+#endif
public System.Reflection.Metadata.CustomAttributeHandleCollection GetCustomAttributes() { throw null; }
}
[System.Runtime.InteropServices.StructLayoutAttribute(System.Runtime.InteropServices.LayoutKind.Sequential)]
diff --git a/src/System.Reflection.Metadata/ref/System.Reflection.Metadata.csproj b/src/System.Reflection.Metadata/ref/System.Reflection.Metadata.csproj
index 911f70d177..c6ac3d6820 100644
--- a/src/System.Reflection.Metadata/ref/System.Reflection.Metadata.csproj
+++ b/src/System.Reflection.Metadata/ref/System.Reflection.Metadata.csproj
@@ -5,6 +5,7 @@
<ProjectGuid>{69B25962-B4C2-4295-8809-5653CD03FC75}</ProjectGuid>
<AllowUnsafeBlocks>true</AllowUnsafeBlocks>
<CLSCompliant>false</CLSCompliant>
+ <DefineConstants Condition="'$(TargetGroup)' == 'netstandard1.1'">$(DefineConstants);NETSTANDARD11</DefineConstants>
</PropertyGroup>
<PropertyGroup Condition="'$(Configuration)|$(Platform)' == 'netcoreapp-Debug|AnyCPU'" />
<PropertyGroup Condition="'$(Configuration)|$(Platform)' == 'netcoreapp-Release|AnyCPU'" />
@@ -31,4 +32,4 @@
<ProjectReference Include="..\..\System.Collections.Immutable\ref\System.Collections.Immutable.csproj" />
</ItemGroup>
<Import Project="$([MSBuild]::GetDirectoryNameOfFileAbove($(MSBuildThisFileDirectory), dir.targets))\dir.targets" />
-</Project> \ No newline at end of file
+</Project>
diff --git a/src/System.Reflection.Metadata/src/System.Reflection.Metadata.csproj b/src/System.Reflection.Metadata/src/System.Reflection.Metadata.csproj
index af9f8167cf..e75d7ef1bc 100644
--- a/src/System.Reflection.Metadata/src/System.Reflection.Metadata.csproj
+++ b/src/System.Reflection.Metadata/src/System.Reflection.Metadata.csproj
@@ -73,6 +73,8 @@
<Compile Include="System\Reflection\Metadata\MetadataReaderProvider.cs" />
<Compile Include="System\Reflection\Metadata\BlobContentId.cs" />
<Compile Include="System\Reflection\Metadata\Signatures\PrimitiveSerializationTypeCode.cs" />
+ <Compile Include="System\Reflection\Metadata\TypeSystem\AssemblyDefinition.netstandard.cs" Condition="'$(TargetGroup)' != 'netstandard1.1'" />
+ <Compile Include="System\Reflection\Metadata\TypeSystem\AssemblyReference.netstandard.cs" Condition="'$(TargetGroup)' != 'netstandard1.1'" />
<Compile Include="System\Reflection\Metadata\TypeSystem\Handles.TypeSystem.cs" />
<Compile Include="System\Reflection\PortableExecutable\ManagedPEBuilder.cs" />
<Compile Include="System\Reflection\PortableExecutable\ManagedTextSection.cs" />
@@ -181,6 +183,7 @@
<Compile Include="System\Reflection\Metadata\Signatures\MemberReferenceKind.cs" />
<Compile Include="System\Reflection\Metadata\Ecma335\MetadataAggregator.cs" />
<Compile Include="System\Reflection\Metadata\MetadataKind.cs" />
+ <Compile Include="System\Reflection\Metadata\MetadataReader.netstandard.cs" Condition="'$(TargetGroup)' != 'netstandard1.1'" />
<Compile Include="System\Reflection\Metadata\MetadataReader.cs" />
<Compile Include="System\Reflection\Metadata\MetadataReader.WinMD.cs" />
<Compile Include="System\Reflection\Metadata\MetadataReaderOptions.cs" />
diff --git a/src/System.Reflection.Metadata/src/System/Reflection/Metadata/MetadataReader.netstandard.cs b/src/System.Reflection.Metadata/src/System/Reflection/Metadata/MetadataReader.netstandard.cs
new file mode 100644
index 0000000000..79b0a52d41
--- /dev/null
+++ b/src/System.Reflection.Metadata/src/System/Reflection/Metadata/MetadataReader.netstandard.cs
@@ -0,0 +1,62 @@
+// 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.Reflection.Metadata
+{
+ public sealed partial class MetadataReader
+ {
+ internal AssemblyName GetAssemblyName(StringHandle nameHandle, Version version, StringHandle cultureHandle, BlobHandle publicKeyOrTokenHandle, AssemblyHashAlgorithm assemblyHashAlgorithm, AssemblyFlags flags)
+ {
+ string name = GetString(nameHandle);
+ string cultureName = (!cultureHandle.IsNil) ? GetString(cultureHandle) : null;
+ var hashAlgorithm = (Configuration.Assemblies.AssemblyHashAlgorithm)assemblyHashAlgorithm;
+ byte[] publicKeyOrToken = !publicKeyOrTokenHandle.IsNil ? GetBlobBytes(publicKeyOrTokenHandle) : null;
+
+ var assemblyName = new AssemblyName(name)
+ {
+ Version = version,
+ CultureName = cultureName,
+ HashAlgorithm = hashAlgorithm,
+ Flags = GetAssemblyNameFlags(flags),
+ ContentType = GetContentTypeFromAssemblyFlags(flags)
+ };
+
+ bool hasPublicKey = (flags & AssemblyFlags.PublicKey) != 0;
+ if (hasPublicKey)
+ {
+ assemblyName.SetPublicKey(publicKeyOrToken);
+ }
+ else
+ {
+ assemblyName.SetPublicKeyToken(publicKeyOrToken);
+ }
+
+ return assemblyName;
+ }
+
+ private AssemblyNameFlags GetAssemblyNameFlags(AssemblyFlags flags)
+ {
+ AssemblyNameFlags assemblyNameFlags = AssemblyNameFlags.None;
+
+ if ((flags & AssemblyFlags.PublicKey) != 0)
+ assemblyNameFlags |= AssemblyNameFlags.PublicKey;
+
+ if ((flags & AssemblyFlags.Retargetable) != 0)
+ assemblyNameFlags |= AssemblyNameFlags.Retargetable;
+
+ if ((flags & AssemblyFlags.EnableJitCompileTracking) != 0)
+ assemblyNameFlags |= AssemblyNameFlags.EnableJITcompileTracking;
+
+ if ((flags & AssemblyFlags.DisableJitCompileOptimizer) != 0)
+ assemblyNameFlags |= AssemblyNameFlags.EnableJITcompileOptimizer;
+
+ return assemblyNameFlags;
+ }
+
+ private AssemblyContentType GetContentTypeFromAssemblyFlags(AssemblyFlags flags)
+ {
+ return (AssemblyContentType)(((int)flags & (int)AssemblyFlags.ContentTypeMask) >> 9);
+ }
+ }
+}
diff --git a/src/System.Reflection.Metadata/src/System/Reflection/Metadata/TypeSystem/AssemblyDefinition.cs b/src/System.Reflection.Metadata/src/System/Reflection/Metadata/TypeSystem/AssemblyDefinition.cs
index 5935b4bac0..3558a0c62b 100644
--- a/src/System.Reflection.Metadata/src/System/Reflection/Metadata/TypeSystem/AssemblyDefinition.cs
+++ b/src/System.Reflection.Metadata/src/System/Reflection/Metadata/TypeSystem/AssemblyDefinition.cs
@@ -6,7 +6,7 @@ using System.Diagnostics;
namespace System.Reflection.Metadata
{
- public struct AssemblyDefinition
+ public partial struct AssemblyDefinition
{
private readonly MetadataReader _reader;
diff --git a/src/System.Reflection.Metadata/src/System/Reflection/Metadata/TypeSystem/AssemblyDefinition.netstandard.cs b/src/System.Reflection.Metadata/src/System/Reflection/Metadata/TypeSystem/AssemblyDefinition.netstandard.cs
new file mode 100644
index 0000000000..9191f5f6d2
--- /dev/null
+++ b/src/System.Reflection.Metadata/src/System/Reflection/Metadata/TypeSystem/AssemblyDefinition.netstandard.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.Reflection.Metadata
+{
+ public partial struct AssemblyDefinition
+ {
+ public AssemblyName GetAssemblyName()
+ {
+ return _reader.GetAssemblyName(Name, Version, Culture, PublicKey, HashAlgorithm, Flags);
+ }
+ }
+}
diff --git a/src/System.Reflection.Metadata/src/System/Reflection/Metadata/TypeSystem/AssemblyReference.cs b/src/System.Reflection.Metadata/src/System/Reflection/Metadata/TypeSystem/AssemblyReference.cs
index ac128cdd16..9a435c5fd4 100644
--- a/src/System.Reflection.Metadata/src/System/Reflection/Metadata/TypeSystem/AssemblyReference.cs
+++ b/src/System.Reflection.Metadata/src/System/Reflection/Metadata/TypeSystem/AssemblyReference.cs
@@ -7,7 +7,7 @@ using System.Reflection.Metadata.Ecma335;
namespace System.Reflection.Metadata
{
- public struct AssemblyReference
+ public partial struct AssemblyReference
{
private readonly MetadataReader _reader;
diff --git a/src/System.Reflection.Metadata/src/System/Reflection/Metadata/TypeSystem/AssemblyReference.netstandard.cs b/src/System.Reflection.Metadata/src/System/Reflection/Metadata/TypeSystem/AssemblyReference.netstandard.cs
new file mode 100644
index 0000000000..5b0d1a92d9
--- /dev/null
+++ b/src/System.Reflection.Metadata/src/System/Reflection/Metadata/TypeSystem/AssemblyReference.netstandard.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.Reflection.Metadata
+{
+ public partial struct AssemblyReference
+ {
+ public AssemblyName GetAssemblyName()
+ {
+ return _reader.GetAssemblyName(Name, Version, Culture, PublicKeyOrToken, AssemblyHashAlgorithm.None, Flags);
+ }
+ }
+}
diff --git a/src/System.Reflection.Metadata/tests/Metadata/Decoding/SignatureDecoderTests.cs b/src/System.Reflection.Metadata/tests/Metadata/Decoding/SignatureDecoderTests.cs
index cecd35b13f..92d5442563 100644
--- a/src/System.Reflection.Metadata/tests/Metadata/Decoding/SignatureDecoderTests.cs
+++ b/src/System.Reflection.Metadata/tests/Metadata/Decoding/SignatureDecoderTests.cs
@@ -264,7 +264,7 @@ namespace System.Reflection.Metadata.Decoding.Tests
// Compiler can generate temporaries or re-order so just check the ones we expect are there.
// (They could get optimized away too. If that happens in practice, change this test to use hard-coded signatures.)
- Assert.Contains("uint8& pinned", localTypes);
+ Assert.Contains("uint8[] pinned", localTypes);
Assert.Contains("uint8[]", localTypes);
}
}
diff --git a/src/System.Reflection.Metadata/tests/Metadata/TypeSystem/AssemblyDefinitionTests.cs b/src/System.Reflection.Metadata/tests/Metadata/TypeSystem/AssemblyDefinitionTests.cs
new file mode 100644
index 0000000000..8bc7f068c1
--- /dev/null
+++ b/src/System.Reflection.Metadata/tests/Metadata/TypeSystem/AssemblyDefinitionTests.cs
@@ -0,0 +1,126 @@
+// 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.Reflection.Metadata.Tests
+{
+ public class AssemblyDefinitionTests
+ {
+ [Fact]
+ public void ValidateAssemblyNameWithCultureSet()
+ {
+ var assembly = new { Assembly = Misc.Satellite, Name = "SatelliteAssembly.resources", Version = new Version(1, 0, 0, 0), ContentType = AssemblyContentType.Default, Culture = "de-DE" };
+
+ var reader = MetadataReaderTests.GetMetadataReader(assembly.Assembly, options: MetadataReaderOptions.ApplyWindowsRuntimeProjections);
+
+ foreach (var assemblyRefHandle in reader.AssemblyReferences)
+ {
+ var assemblyDef = reader.GetAssemblyDefinition();
+ var assemblyRef = reader.GetAssemblyReference(assemblyRefHandle);
+ var assemblyName = assemblyDef.GetAssemblyName();
+
+ // Validate against input assembly
+ Assert.Equal(assembly.Version, assemblyName.Version);
+ Assert.Equal(assembly.Name, assemblyName.Name);
+ Assert.Equal(assembly.ContentType, assemblyName.ContentType);
+ Assert.Equal(assembly.Culture, assemblyName.CultureName);
+ Assert.Equal(Configuration.Assemblies.AssemblyHashAlgorithm.SHA1, assemblyName.HashAlgorithm);
+ Assert.Null(assemblyName.GetPublicKey());
+ Assert.Null(assemblyName.GetPublicKeyToken());
+ Assert.Equal(AssemblyNameFlags.None, assemblyName.Flags);
+
+ // Validate against AssemblyDefinition
+ ValidateDefinitionAssemblyNameAgainst(assemblyName, reader, assemblyDef);
+
+ // Validate against AssemblyReference
+ ValidateDefinitionAssemblyNameAgainst(assemblyName, reader, assemblyRef);
+ }
+ }
+
+ [Fact]
+ public void ValidateAssemblyNameWithPublicKey()
+ {
+ var assembly = new { Assembly = Misc.Signed, Name = "Signed", Version = new Version(0, 0, 0, 0), ContentType = AssemblyContentType.Default, Flags = AssemblyNameFlags.PublicKey };
+
+ var reader = MetadataReaderTests.GetMetadataReader(assembly.Assembly, options: MetadataReaderOptions.ApplyWindowsRuntimeProjections);
+
+ foreach (var assemblyRefHandle in reader.AssemblyReferences)
+ {
+ var assemblyDef = reader.GetAssemblyDefinition();
+ var assemblyRef = reader.GetAssemblyReference(assemblyRefHandle);
+ var assemblyName = assemblyDef.GetAssemblyName();
+
+ // Validate against input assembly
+ Assert.Equal(assembly.Version, assemblyName.Version);
+ Assert.Equal(assembly.Name, assemblyName.Name);
+ Assert.Equal(assembly.ContentType, assemblyName.ContentType);
+ Assert.Null(assemblyName.CultureName);
+ Assert.Equal(Configuration.Assemblies.AssemblyHashAlgorithm.SHA1, assemblyName.HashAlgorithm);
+ Assert.Equal(assembly.Flags, assemblyName.Flags);
+ Assert.NotNull(assemblyName.GetPublicKeyToken());
+ Assert.NotNull(assemblyName.GetPublicKey());
+
+ // Validate against AssemblyDefinition
+ ValidateDefinitionAssemblyNameAgainst(assemblyName, reader, assemblyDef);
+
+ // Validate against AssemblyReference
+ ValidateDefinitionAssemblyNameAgainst(assemblyName, reader, assemblyRef);
+ }
+ }
+
+ [Fact]
+ public void ValidateAssemblyNameForAssemblyDefinition()
+ {
+ var assemblyItems = new[]
+ {
+ new { Assembly = WinRT.Lib, Name = "Lib", Version = new Version(1, 0, 0, 0), ContentType = AssemblyContentType.WindowsRuntime },
+ new { Assembly = NetModule.AppCS, Name = "AppCS", Version = new Version(1, 2, 3, 4), ContentType = AssemblyContentType.Default },
+ new { Assembly = Namespace.NamespaceTests, Name = "NamespaceTests", Version = new Version(0, 0, 0, 0), ContentType = AssemblyContentType.Default },
+ new { Assembly = PortablePdbs.DocumentsDll, Name = "Documents", Version = new Version(0, 0, 0, 0), ContentType = AssemblyContentType.Default }
+ };
+
+ foreach (var item in assemblyItems)
+ {
+ var reader = MetadataReaderTests.GetMetadataReader(item.Assembly, options: MetadataReaderOptions.ApplyWindowsRuntimeProjections);
+
+ foreach (var assemblyRefHandle in reader.AssemblyReferences)
+ {
+ var assemblyDef = reader.GetAssemblyDefinition();
+ var assemblyRef = reader.GetAssemblyReference(assemblyRefHandle);
+ var assemblyName = assemblyDef.GetAssemblyName();
+
+ // Validate against input assembly
+ Assert.Equal(item.Version, assemblyName.Version);
+ Assert.Equal(item.Name, assemblyName.Name);
+ Assert.Equal(item.ContentType, assemblyName.ContentType);
+ Assert.Null(assemblyName.CultureName);
+ Assert.Equal(Configuration.Assemblies.AssemblyHashAlgorithm.SHA1, assemblyName.HashAlgorithm);
+ Assert.Null(assemblyName.GetPublicKey());
+ Assert.Null(assemblyName.GetPublicKeyToken());
+ Assert.Equal(AssemblyNameFlags.None, assemblyName.Flags);
+
+ // Validate against AssemblyDefinition
+ ValidateDefinitionAssemblyNameAgainst(assemblyName, reader, assemblyDef);
+
+ // Validate against AssemblyReference
+ ValidateDefinitionAssemblyNameAgainst(assemblyName, reader, assemblyRef);
+ }
+ }
+ }
+
+ private void ValidateDefinitionAssemblyNameAgainst(AssemblyName assemblyName, MetadataReader reader, AssemblyDefinition assemblyDef)
+ {
+ Assert.Equal(reader.GetString(assemblyDef.Name), assemblyName.Name);
+ Assert.Equal(assemblyDef.Version, assemblyName.Version);
+ Assert.Equal((Configuration.Assemblies.AssemblyHashAlgorithm)assemblyDef.HashAlgorithm, assemblyName.HashAlgorithm);
+ Assert.Equal((AssemblyContentType)(((int)assemblyDef.Flags & (int)AssemblyFlags.ContentTypeMask) >> 9), assemblyName.ContentType);
+ }
+
+ private void ValidateDefinitionAssemblyNameAgainst(AssemblyName assemblyName, MetadataReader reader, AssemblyReference assemblyRef)
+ {
+ Assert.NotEqual(reader.GetString(assemblyRef.Name), assemblyName.Name);
+ }
+ }
+}
diff --git a/src/System.Reflection.Metadata/tests/Metadata/TypeSystem/AssemblyReferenceTests.cs b/src/System.Reflection.Metadata/tests/Metadata/TypeSystem/AssemblyReferenceTests.cs
new file mode 100644
index 0000000000..b0d10d3f92
--- /dev/null
+++ b/src/System.Reflection.Metadata/tests/Metadata/TypeSystem/AssemblyReferenceTests.cs
@@ -0,0 +1,103 @@
+// 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.Linq;
+using Xunit;
+
+namespace System.Reflection.Metadata.Tests
+{
+ public class AssemblyReferenceTests
+ {
+ [Fact]
+ public void ValidateAssemblyNameForSingleAssemblyReference()
+ {
+ var reader = MetadataReaderTests.GetMetadataReader(WinRT.Lib, options: MetadataReaderOptions.ApplyWindowsRuntimeProjections);
+ var handle = reader.AssemblyReferences.Skip(3).First();
+ var assemblyRef = reader.GetAssemblyReference(handle);
+ var assemblyDef = reader.GetAssemblyDefinition();
+ var assemblyName = assemblyRef.GetAssemblyName();
+
+ // Validate against input assembly
+ Assert.Equal("System.Runtime", assemblyName.Name);
+ Assert.Equal(new Version(4, 0, 0, 0), assemblyName.Version);
+ Assert.Equal(new byte[] { 0xB0, 0x3F, 0x5F, 0x7F, 0x11, 0xD5, 0x0A, 0x3A }, assemblyName.GetPublicKeyToken());
+ Assert.Null(assemblyName.CultureName);
+ Assert.Equal(Configuration.Assemblies.AssemblyHashAlgorithm.None, assemblyName.HashAlgorithm);
+ Assert.Null(assemblyName.GetPublicKey());
+ Assert.Equal(AssemblyNameFlags.None, assemblyName.Flags);
+ Assert.Equal(AssemblyContentType.Default, assemblyName.ContentType);
+
+ // Validate against AssemblyRefernce
+ ValidateReferenceAssemblyNameAgainst(assemblyName, reader, assemblyRef);
+
+ // Validate against AssemblyDefinition
+ ValidateReferenceAssemblyNameAgainst(assemblyName, reader, assemblyDef);
+ }
+
+ [Fact]
+ public void ValidateAssemblyNameForMultipleAssemblyReferences()
+ {
+ var expRefs = new string[] { "mscorlib", "System.Core", "System", "Microsoft.VisualBasic" };
+
+ byte[][] expKeys = new byte[][]
+ {
+ new byte[] { 0xb7, 0x7a, 0x5c, 0x56, 0x19, 0x34, 0xe0, 0x89 },
+ new byte[] { 0xb7, 0x7a, 0x5c, 0x56, 0x19, 0x34, 0xe0, 0x89 },
+ new byte[] { 0xb7, 0x7a, 0x5c, 0x56, 0x19, 0x34, 0xe0, 0x89 },
+
+ // VB: B0 3F 5F 7F 11 D5 0A 3A
+ new byte[] { 0xb0, 0x3f, 0x5f, 0x7f, 0x11, 0xd5, 0x0a, 0x3a }
+ };
+
+ var expVers = new Version[]
+ {
+ new Version(4, 0, 0, 0),
+ new Version(4, 0, 0, 0),
+ new Version(4, 0, 0, 0),
+ new Version(/*VB*/10, 0, 0, 0),
+ };
+
+ var reader = MetadataReaderTests.GetMetadataReader(NetModule.AppCS);
+
+ int i = 0;
+ foreach (var assemblyRefHandle in reader.AssemblyReferences)
+ {
+ var assemblyRef = reader.GetAssemblyReference(assemblyRefHandle);
+ var assemblyDef = reader.GetAssemblyDefinition();
+ var assemblyName = assemblyRef.GetAssemblyName();
+
+ // Validate against input assembly
+ Assert.Equal(expRefs[i], assemblyName.Name);
+ Assert.Equal(expVers[i], assemblyName.Version);
+ Assert.Equal(expKeys[i], assemblyName.GetPublicKeyToken());
+ Assert.Null(assemblyName.CultureName);
+ Assert.Equal(Configuration.Assemblies.AssemblyHashAlgorithm.None, assemblyName.HashAlgorithm);
+ Assert.Null(assemblyName.GetPublicKey());
+ Assert.Equal(AssemblyNameFlags.None, assemblyName.Flags);
+ Assert.Equal(AssemblyContentType.Default, assemblyName.ContentType);
+
+ // Validate against AssemblyRefernce
+ ValidateReferenceAssemblyNameAgainst(assemblyName, reader, assemblyRef);
+
+ // Validate against AssemblyDefinition
+ ValidateReferenceAssemblyNameAgainst(assemblyName, reader, assemblyDef);
+
+ i++;
+ }
+ }
+
+ private void ValidateReferenceAssemblyNameAgainst(AssemblyName assemblyName, MetadataReader reader, AssemblyReference assemblyRef)
+ {
+ Assert.Equal(reader.GetString(assemblyRef.Name), assemblyName.Name);
+ Assert.Equal(assemblyRef.Version, assemblyName.Version);
+ Assert.Equal(reader.GetBlobBytes(assemblyRef.PublicKeyOrToken), assemblyName.GetPublicKeyToken());
+ }
+
+ private void ValidateReferenceAssemblyNameAgainst(AssemblyName assemblyName, MetadataReader reader, AssemblyDefinition assemblyDef)
+ {
+ Assert.NotEqual(reader.GetString(assemblyDef.Name), assemblyName.Name);
+ Assert.NotEqual(assemblyDef.Version, assemblyName.Version);
+ }
+ }
+}
diff --git a/src/System.Reflection.Metadata/tests/Resources/Misc/SatelliteAssembly.resources.cs b/src/System.Reflection.Metadata/tests/Resources/Misc/SatelliteAssembly.resources.cs
new file mode 100644
index 0000000000..da2938ba86
--- /dev/null
+++ b/src/System.Reflection.Metadata/tests/Resources/Misc/SatelliteAssembly.resources.cs
@@ -0,0 +1,10 @@
+// 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.
+
+// csc /target:library /debug:full Debug.cs
+
+public class C
+{
+ public static void Main() { }
+}
diff --git a/src/System.Reflection.Metadata/tests/Resources/Misc/SatelliteAssembly.resources.dll b/src/System.Reflection.Metadata/tests/Resources/Misc/SatelliteAssembly.resources.dll
new file mode 100644
index 0000000000..314bf2a0b0
--- /dev/null
+++ b/src/System.Reflection.Metadata/tests/Resources/Misc/SatelliteAssembly.resources.dll
Binary files differ
diff --git a/src/System.Reflection.Metadata/tests/Resources/TestResources.cs b/src/System.Reflection.Metadata/tests/Resources/TestResources.cs
index a37707cbdc..6111b333d2 100644
--- a/src/System.Reflection.Metadata/tests/Resources/TestResources.cs
+++ b/src/System.Reflection.Metadata/tests/Resources/TestResources.cs
@@ -26,6 +26,7 @@ namespace System.Reflection.Metadata.Tests
public static readonly byte[] Debug = ResourceHelper.GetResource("Misc.Debug.dll");
public static readonly byte[] KeyPair = ResourceHelper.GetResource("Misc.KeyPair.snk");
public static readonly byte[] Signed = ResourceHelper.GetResource("Misc.Signed.exe");
+ public static readonly byte[] Satellite = ResourceHelper.GetResource("Misc.SatelliteAssembly.resources.dll");
public static readonly byte[] KeyPair_PublicKey = new byte[]
{
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 f79be12e9d..8850ce334e 100644
--- a/src/System.Reflection.Metadata/tests/System.Reflection.Metadata.Tests.csproj
+++ b/src/System.Reflection.Metadata/tests/System.Reflection.Metadata.Tests.csproj
@@ -38,6 +38,8 @@
<Compile Include="Metadata\Ecma335\MetadataRootBuilderTests.cs" />
<Compile Include="Metadata\Ecma335\PortablePdbBuilderTests.cs" />
<Compile Include="Metadata\LargeTablesAndHeapsTests.cs" />
+ <Compile Include="Metadata\TypeSystem\AssemblyDefinitionTests.cs" />
+ <Compile Include="Metadata\TypeSystem\AssemblyReferenceTests.cs" />
<Compile Include="Metadata\TypeSystem\ClassLayoutRow.cs" />
<Compile Include="Metadata\Decoding\CustomAttributeDecoderTests.cs" />
<Compile Include="Metadata\Decoding\DisassemblingTypeProvider.cs" />
@@ -130,14 +132,16 @@
<EmbeddedResource Include="Resources\PortablePdbs\Documents.Embedded.dll" />
<None Include="Resources\PortablePdbs\Documents.cmd" />
<None Include="Resources\PortablePdbs\Documents.cs" />
+ <None Include="Resources\Misc\SatelliteAssembly.resources.cs" />
+ <EmbeddedResource Include="Resources\Misc\SatelliteAssembly.resources.dll" />
<None Include="Resources\Misc\Signed.cmd" />
<None Include="Resources\Misc\Signed.cs" />
<EmbeddedResource Include="Resources\Misc\Signed.exe" />
</ItemGroup>
- <ItemGroup>
+ <ItemGroup>
<!-- Some internal types are needed, so we reference the implementation assembly, rather than the reference assembly. -->
<TargetingPackExclusions Include="System.Reflection.Metadata" />
<ReferenceFromRuntime Include="System.Reflection.Metadata" />
</ItemGroup>
<Import Project="$([MSBuild]::GetDirectoryNameOfFileAbove($(MSBuildThisFileDirectory), dir.targets))\dir.targets" />
-</Project> \ No newline at end of file
+</Project>
diff --git a/src/System.Reflection.TypeExtensions/ref/System.Reflection.TypeExtensions.csproj b/src/System.Reflection.TypeExtensions/ref/System.Reflection.TypeExtensions.csproj
index 9eb0a5a5f1..86b9334f67 100644
--- a/src/System.Reflection.TypeExtensions/ref/System.Reflection.TypeExtensions.csproj
+++ b/src/System.Reflection.TypeExtensions/ref/System.Reflection.TypeExtensions.csproj
@@ -3,6 +3,9 @@
<Import Project="$([MSBuild]::GetDirectoryNameOfFileAbove($(MSBuildThisFileDirectory), dir.props))\dir.props" />
<PropertyGroup>
<ProjectGuid>{C303A051-8D54-4460-8BFD-DE10F0473BDB}</ProjectGuid>
+ <!-- Must match version supported by frameworks which support 4.1.* inbox.
+ Can be removed when API is added and this assembly is versioned to 4.2.* -->
+ <AssemblyVersion Condition="'$(TargetsNetFx)' != 'true'">4.1.2.0</AssemblyVersion>
</PropertyGroup>
<PropertyGroup Condition="'$(Configuration)|$(Platform)' == 'netfx-Debug|AnyCPU'" />
<PropertyGroup Condition="'$(Configuration)|$(Platform)' == 'netfx-Release|AnyCPU'" />
diff --git a/src/System.Runtime.CompilerServices.Unsafe/pkg/System.Runtime.CompilerServices.Unsafe.pkgproj b/src/System.Runtime.CompilerServices.Unsafe/pkg/System.Runtime.CompilerServices.Unsafe.pkgproj
index 33d27faa55..310dd2420a 100644
--- a/src/System.Runtime.CompilerServices.Unsafe/pkg/System.Runtime.CompilerServices.Unsafe.pkgproj
+++ b/src/System.Runtime.CompilerServices.Unsafe/pkg/System.Runtime.CompilerServices.Unsafe.pkgproj
@@ -7,8 +7,15 @@
<SupportedFramework>net45;netcore45;wp8;wpa81;netcoreapp1.0;$(AllXamarinFrameworks)</SupportedFramework>
</ProjectReference>
<ProjectReference Include="..\src\System.Runtime.CompilerServices.Unsafe.ilproj" />
- <InboxOnTargetFramework Include="netcoreapp2.1" />
- <InboxOnTargetFramework Include="$(UAPvNextTFM)" />
+
+ <!-- Since UAP and .NETCoreApp are package based we still want to enable
+ OOBing libraries that happen to overlap with their framework package.
+ This avoids us having to lock the API in our NuGet packages just
+ to match what shipped inbox: since we can provide a new library
+ we can update it to add API without raising the netstandard version. -->
+ <ValidatePackageSuppression Include="TreatAsOutOfBox">
+ <Value>.NETCoreApp;UAP</Value>
+ </ValidatePackageSuppression>
</ItemGroup>
<Import Project="$([MSBuild]::GetDirectoryNameOfFileAbove($(MSBuildThisFileDirectory), dir.targets))\dir.targets" />
</Project> \ No newline at end of file
diff --git a/src/System.Runtime.CompilerServices.Unsafe/src/Configurations.props b/src/System.Runtime.CompilerServices.Unsafe/src/Configurations.props
index a0858acd2f..ba6b9bda8a 100644
--- a/src/System.Runtime.CompilerServices.Unsafe/src/Configurations.props
+++ b/src/System.Runtime.CompilerServices.Unsafe/src/Configurations.props
@@ -1,12 +1,9 @@
<?xml version="1.0" encoding="utf-8"?>
<Project ToolsVersion="14.0" DefaultTargets="Build" xmlns="http://schemas.microsoft.com/developer/msbuild/2003">
<PropertyGroup>
- <PackageConfigurations>
+ <BuildConfigurations>
netstandard1.0;
netstandard;
- </PackageConfigurations>
- <BuildConfigurations>
- $(PackageConfigurations);
netcoreapp;
</BuildConfigurations>
</PropertyGroup>
diff --git a/src/System.Runtime.CompilerServices.Unsafe/tests/Configurations.props b/src/System.Runtime.CompilerServices.Unsafe/tests/Configurations.props
index d3ac8a63c7..78953dfc88 100644
--- a/src/System.Runtime.CompilerServices.Unsafe/tests/Configurations.props
+++ b/src/System.Runtime.CompilerServices.Unsafe/tests/Configurations.props
@@ -2,7 +2,7 @@
<Project ToolsVersion="14.0" DefaultTargets="Build" xmlns="http://schemas.microsoft.com/developer/msbuild/2003">
<PropertyGroup>
<BuildConfigurations>
- netcoreapp;
+ netstandard;
</BuildConfigurations>
</PropertyGroup>
</Project>
diff --git a/src/System.Runtime.CompilerServices.Unsafe/tests/UnsafeTests.cs b/src/System.Runtime.CompilerServices.Unsafe/tests/UnsafeTests.cs
index 1df5657747..69be503b5f 100644
--- a/src/System.Runtime.CompilerServices.Unsafe/tests/UnsafeTests.cs
+++ b/src/System.Runtime.CompilerServices.Unsafe/tests/UnsafeTests.cs
@@ -587,6 +587,7 @@ namespace System.Runtime.CompilerServices
Assert.Equal(0x12, r3);
}
+ [ActiveIssue(23953, TargetFrameworkMonikers.UapAot)]
[Fact]
public static void RefAreSame()
{
diff --git a/src/System.Runtime.Extensions/ref/System.Runtime.Extensions.cs b/src/System.Runtime.Extensions/ref/System.Runtime.Extensions.cs
index c84f706789..bfb9374a89 100644
--- a/src/System.Runtime.Extensions/ref/System.Runtime.Extensions.cs
+++ b/src/System.Runtime.Extensions/ref/System.Runtime.Extensions.cs
@@ -907,6 +907,7 @@ namespace System
public virtual int Next(int maxValue) { throw null; }
public virtual int Next(int minValue, int maxValue) { throw null; }
public virtual void NextBytes(byte[] buffer) { }
+ public virtual void NextBytes(Span<byte> buffer) { }
public virtual double NextDouble() { throw null; }
protected virtual double Sample() { throw null; }
}
@@ -1222,6 +1223,8 @@ namespace System.IO
public virtual int Read() { throw null; }
public virtual int Read(byte[] buffer, int index, int count) { throw null; }
public virtual int Read(char[] buffer, int index, int count) { throw null; }
+ public virtual int Read(System.Span<byte> destination) { throw null; }
+ public virtual int Read(System.Span<char> destination) { throw null; }
protected internal int Read7BitEncodedInt() { throw null; }
public virtual bool ReadBoolean() { throw null; }
public virtual byte ReadByte() { throw null; }
@@ -1471,8 +1474,10 @@ namespace System.IO
public virtual int Peek() { throw null; }
public virtual int Read() { throw null; }
public virtual int Read(char[] buffer, int index, int count) { throw null; }
+ public virtual int Read(Span<char> destination) { throw null; }
public virtual System.Threading.Tasks.Task<int> ReadAsync(char[] buffer, int index, int count) { throw null; }
public virtual int ReadBlock(char[] buffer, int index, int count) { throw null; }
+ public virtual int ReadBlock(Span<char> destination) { throw null; }
public virtual System.Threading.Tasks.Task<int> ReadBlockAsync(char[] buffer, int index, int count) { throw null; }
public virtual string ReadLine() { throw null; }
public virtual System.Threading.Tasks.Task<string> ReadLineAsync() { throw null; }
@@ -1514,6 +1519,7 @@ namespace System.IO
public virtual void Write(uint value) { }
[System.CLSCompliantAttribute(false)]
public virtual void Write(ulong value) { }
+ public virtual void Write(ReadOnlySpan<char> source) { }
public virtual System.Threading.Tasks.Task WriteAsync(char value) { throw null; }
public System.Threading.Tasks.Task WriteAsync(char[] buffer) { throw null; }
public virtual System.Threading.Tasks.Task WriteAsync(char[] buffer, int index, int count) { throw null; }
@@ -1538,6 +1544,7 @@ namespace System.IO
public virtual void WriteLine(uint value) { }
[System.CLSCompliantAttribute(false)]
public virtual void WriteLine(ulong value) { }
+ public virtual void WriteLine(ReadOnlySpan<char> source) { }
public virtual System.Threading.Tasks.Task WriteLineAsync() { throw null; }
public virtual System.Threading.Tasks.Task WriteLineAsync(char value) { throw null; }
public System.Threading.Tasks.Task WriteLineAsync(char[] buffer) { throw null; }
diff --git a/src/System.Runtime.Extensions/src/PinvokeAnalyzerExceptionList.analyzerdata.uap b/src/System.Runtime.Extensions/src/PinvokeAnalyzerExceptionList.analyzerdata.uap
deleted file mode 100644
index 9e2ef6b397..0000000000
--- a/src/System.Runtime.Extensions/src/PinvokeAnalyzerExceptionList.analyzerdata.uap
+++ /dev/null
@@ -1 +0,0 @@
-shell32.dll!SHGetKnownFolderPath
diff --git a/src/System.Runtime.Extensions/src/PinvokeAnalyzerExceptionList.analyzerdata.uapaot b/src/System.Runtime.Extensions/src/PinvokeAnalyzerExceptionList.analyzerdata.uapaot
deleted file mode 100644
index 9e2ef6b397..0000000000
--- a/src/System.Runtime.Extensions/src/PinvokeAnalyzerExceptionList.analyzerdata.uapaot
+++ /dev/null
@@ -1 +0,0 @@
-shell32.dll!SHGetKnownFolderPath
diff --git a/src/System.Runtime.Extensions/src/Resources/Strings.resx b/src/System.Runtime.Extensions/src/Resources/Strings.resx
index 7dfe4e5ee1..1b7afc3757 100644
--- a/src/System.Runtime.Extensions/src/Resources/Strings.resx
+++ b/src/System.Runtime.Extensions/src/Resources/Strings.resx
@@ -1,5 +1,64 @@
<?xml version="1.0" encoding="utf-8"?>
<root>
+ <!--
+ Microsoft ResX Schema
+
+ Version 2.0
+
+ The primary goals of this format is to allow a simple XML format
+ that is mostly human readable. The generation and parsing of the
+ various data types are done through the TypeConverter classes
+ associated with the data types.
+
+ Example:
+
+ ... ado.net/XML headers & schema ...
+ <resheader name="resmimetype">text/microsoft-resx</resheader>
+ <resheader name="version">2.0</resheader>
+ <resheader name="reader">System.Resources.ResXResourceReader, System.Windows.Forms, ...</resheader>
+ <resheader name="writer">System.Resources.ResXResourceWriter, System.Windows.Forms, ...</resheader>
+ <data name="Name1"><value>this is my long string</value><comment>this is a comment</comment></data>
+ <data name="Color1" type="System.Drawing.Color, System.Drawing">Blue</data>
+ <data name="Bitmap1" mimetype="application/x-microsoft.net.object.binary.base64">
+ <value>[base64 mime encoded serialized .NET Framework object]</value>
+ </data>
+ <data name="Icon1" type="System.Drawing.Icon, System.Drawing" mimetype="application/x-microsoft.net.object.bytearray.base64">
+ <value>[base64 mime encoded string representing a byte array form of the .NET Framework object]</value>
+ <comment>This is a comment</comment>
+ </data>
+
+ There are any number of "resheader" rows that contain simple
+ name/value pairs.
+
+ Each data row contains a name, and value. The row also contains a
+ type or mimetype. Type corresponds to a .NET class that support
+ text/value conversion through the TypeConverter architecture.
+ Classes that don't support this are serialized and stored with the
+ mimetype set.
+
+ The mimetype is used for serialized objects, and tells the
+ ResXResourceReader how to depersist the object. This is currently not
+ extensible. For a given mimetype the value must be set accordingly:
+
+ Note - application/x-microsoft.net.object.binary.base64 is the format
+ that the ResXResourceWriter will generate, however the reader can
+ read any of the formats listed below.
+
+ mimetype: application/x-microsoft.net.object.binary.base64
+ value : The object must be serialized with
+ : System.Runtime.Serialization.Formatters.Binary.BinaryFormatter
+ : and then encoded with base64 encoding.
+
+ mimetype: application/x-microsoft.net.object.soap.base64
+ value : The object must be serialized with
+ : System.Runtime.Serialization.Formatters.Soap.SoapFormatter
+ : and then encoded with base64 encoding.
+
+ mimetype: application/x-microsoft.net.object.bytearray.base64
+ value : The object must be serialized into a byte array
+ : using a System.ComponentModel.TypeConverter
+ : and then encoded with base64 encoding.
+ -->
<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">
@@ -94,21 +153,12 @@
<data name="ArgumentOutOfRange_FileLengthTooBig" xml:space="preserve">
<value>Specified file length was too large for the file system.</value>
</data>
- <data name="Arg_PathIllegal" xml:space="preserve">
- <value>The path is not of a legal form.</value>
- </data>
- <data name="Arg_PathIllegalUNC" xml:space="preserve">
- <value>The UNC path should be of the form \\\\server\\share.</value>
- </data>
<data name="Argument_InvalidPathChars" xml:space="preserve">
<value>Illegal characters in path.</value>
</data>
<data name="Argument_PathEmpty" xml:space="preserve">
<value>Path cannot be the empty string or all whitespace.</value>
</data>
- <data name="Argument_PathFormatNotSupported" xml:space="preserve">
- <value>The given path's format is not supported.</value>
- </data>
<data name="ArgumentOutOfRange_MustBePositive" xml:space="preserve">
<value>'{0}' must be greater than zero.</value>
</data>
@@ -145,9 +195,6 @@
<data name="IO_FileExists_Name" xml:space="preserve">
<value>The file '{0}' already exists.</value>
</data>
- <data name="InvalidOperation_Cryptography" xml:space="preserve">
- <value>Unable to use cryptographic functionality.</value>
- </data>
<data name="Arg_EnumIllegalVal" xml:space="preserve">
<value>Illegal enum value: {0}</value>
</data>
@@ -274,9 +321,6 @@
<data name="NotSupported_ReadOnlyCollection" xml:space="preserve">
<value>Collection is read-only.</value>
</data>
- <data name="Serialization_InsufficientState" xml:space="preserve">
- <value>Insufficient state to return the real object.</value>
- </data>
<data name="Serialization_InvalidOnDeser" xml:space="preserve">
<value>OnDeserialization method was called while the object was not being deserialized.</value>
</data>
@@ -367,4 +411,7 @@
<data name="PlatformNotSupported_AppDomain_ResMon" xml:space="preserve">
<value>AppDomain resource monitoring is not supported on this platform.</value>
</data>
-</root>
+ <data name="IO_InvalidReadLength" xml:space="preserve">
+ <value>The read operation returned an invalid length.</value>
+ </data>
+</root> \ No newline at end of file
diff --git a/src/System.Runtime.Extensions/src/System/Collections/Hashtable.cs b/src/System.Runtime.Extensions/src/System/Collections/Hashtable.cs
index e921e34ae6..7916a38227 100644
--- a/src/System.Runtime.Extensions/src/System/Collections/Hashtable.cs
+++ b/src/System.Runtime.Extensions/src/System/Collections/Hashtable.cs
@@ -734,13 +734,13 @@ namespace System.Collections
private void expand()
{
int rawsize = HashHelpers.ExpandPrime(_buckets.Length);
- rehash(rawsize, false);
+ rehash(rawsize);
}
// We occasionally need to rehash the table to clean up the collision bits.
private void rehash()
{
- rehash(_buckets.Length, false);
+ rehash(_buckets.Length);
}
private void UpdateVersion()
@@ -750,7 +750,7 @@ namespace System.Collections
_version++;
}
- private void rehash(int newsize, bool forceNewHashCode)
+ private void rehash(int newsize)
{
// reset occupancy
_occupancy = 0;
@@ -770,7 +770,7 @@ namespace System.Collections
bucket oldb = _buckets[nb];
if ((oldb.key != null) && (oldb.key != _buckets))
{
- int hashcode = ((forceNewHashCode ? GetHash(oldb.key) : oldb.hash_coll) & 0x7FFFFFFF);
+ int hashcode = oldb.hash_coll & 0x7FFFFFFF;
putEntry(newBuckets, oldb.key, oldb.val, hashcode);
}
}
@@ -783,7 +783,6 @@ namespace System.Collections
_isWriterInProgress = false;
// minimum size of hashtable is 3 now and maximum loadFactor is 0.72 now.
Debug.Assert(_loadsize < newsize, "Our current implementation means this is not possible.");
- return;
}
// Returns an enumerator for this hashtable.
@@ -947,18 +946,7 @@ namespace System.Collections
_count++;
UpdateVersion();
_isWriterInProgress = false;
-#if FEATURE_RANDOMIZED_STRING_HASHING
- if (ntry > HashHelpers.HashCollisionThreshold && HashHelpers.IsWellKnownEqualityComparer(_keycomparer))
- {
- // PERF: We don't want to rehash if _keycomparer is already a RandomizedObjectEqualityComparer since in some
- // cases there may not be any strings in the hashtable and we wouldn't get any mixing.
- if (_keycomparer == null || !(_keycomparer is System.Collections.Generic.RandomizedObjectEqualityComparer))
- {
- _keycomparer = HashHelpers.GetRandomizedEqualityComparer(_keycomparer);
- rehash(buckets.Length, true);
- }
- }
-#endif
+
return;
}
@@ -977,18 +965,6 @@ namespace System.Collections
UpdateVersion();
_isWriterInProgress = false;
-#if FEATURE_RANDOMIZED_STRING_HASHING
- if (ntry > HashHelpers.HashCollisionThreshold && HashHelpers.IsWellKnownEqualityComparer(_keycomparer))
- {
- // PERF: We don't want to rehash if _keycomparer is already a RandomizedObjectEqualityComparer since in some
- // cases there may not be any strings in the hashtable and we wouldn't get any mixing.
- if (_keycomparer == null || !(_keycomparer is System.Collections.Generic.RandomizedObjectEqualityComparer))
- {
- _keycomparer = HashHelpers.GetRandomizedEqualityComparer(_keycomparer);
- rehash(buckets.Length, true);
- }
- }
-#endif
return;
}
@@ -1019,18 +995,6 @@ namespace System.Collections
UpdateVersion();
_isWriterInProgress = false;
-#if FEATURE_RANDOMIZED_STRING_HASHING
- if (buckets.Length > HashHelpers.HashCollisionThreshold && HashHelpers.IsWellKnownEqualityComparer(_keycomparer))
- {
- // PERF: We don't want to rehash if _keycomparer is already a RandomizedObjectEqualityComparer since in some
- // cases there may not be any strings in the hashtable and we wouldn't get any mixing.
- if (_keycomparer == null || !(_keycomparer is System.Collections.Generic.RandomizedObjectEqualityComparer))
- {
- _keycomparer = HashHelpers.GetRandomizedEqualityComparer(_keycomparer);
- rehash(buckets.Length, true);
- }
- }
-#endif
return;
}
@@ -1696,10 +1660,6 @@ namespace System.Collections
internal static class HashHelpers
{
-#if FEATURE_RANDOMIZED_STRING_HASHING
- public const int HashCollisionThreshold = 100;
- public static bool s_UseRandomizedStringHashing = String.UseRandomizedHashing();
-#endif
// Table of prime numbers to use as hash table sizes.
// A typical resize algorithm would pick the smallest prime number in this array
// that is larger than twice the previous capacity.
@@ -1777,87 +1737,5 @@ namespace System.Collections
private static ConditionalWeakTable<object, SerializationInfo> s_serializationInfoTable;
public static ConditionalWeakTable<object, SerializationInfo> SerializationInfoTable => LazyInitializer.EnsureInitialized(ref s_serializationInfoTable);
-
-#if FEATURE_RANDOMIZED_STRING_HASHING
- public static bool IsWellKnownEqualityComparer(object comparer)
- {
- return (comparer == null || comparer == System.Collections.Generic.EqualityComparer<string>.Default || comparer is IWellKnownStringEqualityComparer);
- }
-
- public static IEqualityComparer GetRandomizedEqualityComparer(object comparer)
- {
- Debug.Assert(comparer == null || comparer == System.Collections.Generic.EqualityComparer<string>.Default || comparer is IWellKnownStringEqualityComparer);
-
- if (comparer == null)
- {
- return new System.Collections.Generic.RandomizedObjectEqualityComparer();
- }
-
- if (comparer == System.Collections.Generic.EqualityComparer<string>.Default)
- {
- return new System.Collections.Generic.RandomizedStringEqualityComparer();
- }
-
- IWellKnownStringEqualityComparer cmp = comparer as IWellKnownStringEqualityComparer;
-
- if (cmp != null)
- {
- return cmp.GetRandomizedEqualityComparer();
- }
-
- Debug.Fail("Missing case in GetRandomizedEqualityComparer!");
-
- return null;
- }
-
- public static object GetEqualityComparerForSerialization(object comparer)
- {
- if (comparer == null)
- {
- return null;
- }
-
- IWellKnownStringEqualityComparer cmp = comparer as IWellKnownStringEqualityComparer;
-
- if (cmp != null)
- {
- return cmp.GetEqualityComparerForSerialization();
- }
-
- return comparer;
- }
-
- private const int bufferSize = 1024;
- private static RandomNumberGenerator rng;
- private static byte[] data;
- private static int currentIndex = bufferSize;
- private static readonly object lockObj = new Object();
-
- internal static long GetEntropy()
- {
- lock (lockObj)
- {
- long ret;
-
- if (currentIndex == bufferSize)
- {
- if (null == rng)
- {
- rng = RandomNumberGenerator.Create();
- data = new byte[bufferSize];
- Debug.Assert(bufferSize % 8 == 0, "We increment our current index by 8, so our buffer size must be a multiple of 8");
- }
-
- rng.GetBytes(data);
- currentIndex = 0;
- }
-
- ret = BitConverter.ToInt64(data, currentIndex);
- currentIndex += 8;
-
- return ret;
- }
- }
-#endif // FEATURE_RANDOMIZED_STRING_HASHING
}
}
diff --git a/src/System.Runtime.Extensions/src/System/IO/BufferedStream.cs b/src/System.Runtime.Extensions/src/System/IO/BufferedStream.cs
index f038e801ed..212f821186 100644
--- a/src/System.Runtime.Extensions/src/System/IO/BufferedStream.cs
+++ b/src/System.Runtime.Extensions/src/System/IO/BufferedStream.cs
@@ -589,7 +589,6 @@ namespace System.IO
public override Task<int> ReadAsync(byte[] buffer, int offset, int count, CancellationToken cancellationToken)
{
-
if (buffer == null)
throw new ArgumentNullException(nameof(buffer), SR.ArgumentNull_Buffer);
if (offset < 0)
@@ -645,26 +644,58 @@ namespace System.IO
}
// Delegate to the async implementation.
- return ReadFromUnderlyingStreamAsync(buffer, offset + bytesFromBuffer, count - bytesFromBuffer, cancellationToken,
- bytesFromBuffer, semaphoreLockTask);
+ return ReadFromUnderlyingStreamAsync(
+ new Memory<byte>(buffer, offset + bytesFromBuffer, count - bytesFromBuffer),
+ cancellationToken, bytesFromBuffer, semaphoreLockTask).AsTask();
+ }
+
+ public override ValueTask<int> ReadAsync(Memory<byte> destination, CancellationToken cancellationToken = default(CancellationToken))
+ {
+ if (cancellationToken.IsCancellationRequested)
+ {
+ return new ValueTask<int>(Task.FromCanceled<int>(cancellationToken));
+ }
+
+ EnsureNotClosed();
+ EnsureCanRead();
+
+ int bytesFromBuffer = 0;
+ SemaphoreSlim sem = LazyEnsureAsyncActiveSemaphoreInitialized();
+ Task semaphoreLockTask = sem.WaitAsync();
+ if (semaphoreLockTask.IsCompletedSuccessfully)
+ {
+ bool completeSynchronously = true;
+ try
+ {
+ bytesFromBuffer = ReadFromBuffer(destination.Span);
+ completeSynchronously = bytesFromBuffer == destination.Length;
+ if (completeSynchronously)
+ {
+ // If we satisfied enough data from the buffer, we can complete synchronously.
+ return new ValueTask<int>(bytesFromBuffer);
+ }
+ }
+ finally
+ {
+ if (completeSynchronously) // if this is FALSE, we will be entering ReadFromUnderlyingStreamAsync and releasing there.
+ {
+ sem.Release();
+ }
+ }
+ }
+
+ // Delegate to the async implementation.
+ return ReadFromUnderlyingStreamAsync(destination.Slice(bytesFromBuffer), cancellationToken, bytesFromBuffer, semaphoreLockTask);
}
/// <summary>BufferedStream should be as thin a wrapper as possible. We want ReadAsync to delegate to
/// ReadAsync of the underlying _stream rather than calling the base Stream which implements the one in terms of the other.
/// This allows BufferedStream to affect the semantics of the stream it wraps as little as possible. </summary>
/// <returns>-2 if _bufferSize was set to 0 while waiting on the semaphore; otherwise num of bytes read.</returns>
- private async Task<int> ReadFromUnderlyingStreamAsync(byte[] array, int offset, int count,
- CancellationToken cancellationToken,
- int bytesAlreadySatisfied,
- Task semaphoreLockTask)
+ private async ValueTask<int> ReadFromUnderlyingStreamAsync(
+ Memory<byte> buffer, CancellationToken cancellationToken, int bytesAlreadySatisfied, Task semaphoreLockTask)
{
-
// Same conditions validated with exceptions in ReadAsync:
- // (These should be Debug.Requires(..) but that method had some issues in async methods; using Assert(..) for now.)
- Debug.Assert(array != null);
- Debug.Assert(offset >= 0);
- Debug.Assert(count >= 0);
- Debug.Assert(array.Length - offset >= count);
Debug.Assert(_stream != null);
Debug.Assert(_stream.CanRead);
Debug.Assert(_bufferSize > 0);
@@ -674,17 +705,17 @@ namespace System.IO
await semaphoreLockTask.ConfigureAwait(false);
try
{
-
// The buffer might have been changed by another async task while we were waiting on the semaphore.
// Check it now again.
- int bytesFromBuffer = ReadFromBuffer(array, offset, count);
- if (bytesFromBuffer == count)
+ int bytesFromBuffer = ReadFromBuffer(buffer.Span);
+ if (bytesFromBuffer == buffer.Length)
+ {
return bytesAlreadySatisfied + bytesFromBuffer;
+ }
if (bytesFromBuffer > 0)
{
- count -= bytesFromBuffer;
- offset += bytesFromBuffer;
+ buffer = buffer.Slice(bytesFromBuffer);
bytesAlreadySatisfied += bytesFromBuffer;
}
@@ -693,21 +724,22 @@ namespace System.IO
// If there was anything in the write buffer, clear it.
if (_writePos > 0)
+ {
await FlushWriteAsync(cancellationToken).ConfigureAwait(false); // no Begin-End read version for Flush. Use Async.
+ }
// If the requested read is larger than buffer size, avoid the buffer and still use a single read:
- if (count >= _bufferSize)
+ if (buffer.Length >= _bufferSize)
{
- return bytesAlreadySatisfied + await _stream.ReadAsync(array, offset, count, cancellationToken).ConfigureAwait(false);
+ return bytesAlreadySatisfied + await _stream.ReadAsync(buffer, cancellationToken).ConfigureAwait(false);
}
// Ok. We can fill the buffer:
EnsureBufferAllocated();
_readLen = await _stream.ReadAsync(_buffer, 0, _bufferSize, cancellationToken).ConfigureAwait(false);
- bytesFromBuffer = ReadFromBuffer(array, offset, count);
+ bytesFromBuffer = ReadFromBuffer(buffer.Span);
return bytesAlreadySatisfied + bytesFromBuffer;
-
}
finally
{
@@ -769,7 +801,7 @@ namespace System.IO
offset += bytesToWrite;
}
- private void WriteToBuffer(ref ReadOnlySpan<byte> source)
+ private int WriteToBuffer(ReadOnlySpan<byte> source)
{
int bytesToWrite = Math.Min(_bufferSize - _writePos, source.Length);
if (bytesToWrite > 0)
@@ -777,8 +809,8 @@ namespace System.IO
EnsureBufferAllocated();
source.Slice(0, bytesToWrite).CopyTo(new Span<byte>(_buffer, _writePos, bytesToWrite));
_writePos += bytesToWrite;
- source = source.Slice(bytesToWrite);
}
+ return bytesToWrite;
}
private void WriteToBuffer(byte[] array, ref int offset, ref int count, out Exception error)
@@ -939,7 +971,7 @@ namespace System.IO
{
ClearReadBufferBeforeWrite();
}
- Debug.Assert(_writePos < _bufferSize);
+ Debug.Assert(_writePos < _bufferSize, $"Expected {_writePos} < {_bufferSize}");
int totalUserbytes;
bool useBuffer;
@@ -954,12 +986,13 @@ namespace System.IO
{
// Copy as much data to the buffer as will fit. If there's still room in the buffer,
// everything must have fit.
- WriteToBuffer(ref source);
+ int bytesWritten = WriteToBuffer(source);
if (_writePos < _bufferSize)
{
- Debug.Assert(source.IsEmpty);
+ Debug.Assert(bytesWritten == source.Length);
return;
}
+ source = source.Slice(bytesWritten);
Debug.Assert(_writePos == _bufferSize);
Debug.Assert(_buffer != null);
@@ -969,9 +1002,9 @@ namespace System.IO
_writePos = 0;
// Now write the remainder. It must fit, as we're only on this path if that's true.
- WriteToBuffer(ref source);
+ bytesWritten = WriteToBuffer(source);
+ Debug.Assert(bytesWritten == source.Length);
- Debug.Assert(source.IsEmpty);
Debug.Assert(_writePos < _bufferSize);
}
else // skip the buffer
@@ -1012,16 +1045,21 @@ namespace System.IO
if (buffer.Length - offset < count)
throw new ArgumentException(SR.Argument_InvalidOffLen);
+ return WriteAsync(new ReadOnlyMemory<byte>(buffer, offset, count), cancellationToken);
+ }
+
+ public override Task WriteAsync(ReadOnlyMemory<byte> source, CancellationToken cancellationToken = default(CancellationToken))
+ {
// Fast path check for cancellation already requested
if (cancellationToken.IsCancellationRequested)
+ {
return Task.FromCanceled<int>(cancellationToken);
+ }
EnsureNotClosed();
EnsureCanWrite();
- // Try to satisfy the request from the buffer synchronously. But still need a sem-lock in case that another
- // Async IO Task accesses the buffer concurrently. If we fail to acquire the lock without waiting, make this
- // an Async operation.
+ // Try to satisfy the request from the buffer synchronously.
SemaphoreSlim sem = LazyEnsureAsyncActiveSemaphoreInitialized();
Task semaphoreLockTask = sem.WaitAsync();
if (semaphoreLockTask.IsCompletedSuccessfully)
@@ -1029,25 +1067,20 @@ namespace System.IO
bool completeSynchronously = true;
try
{
-
if (_writePos == 0)
+ {
ClearReadBufferBeforeWrite();
+ }
Debug.Assert(_writePos < _bufferSize);
// If the write completely fits into the buffer, we can complete synchronously:
- completeSynchronously = (count < _bufferSize - _writePos);
-
+ completeSynchronously = source.Length < _bufferSize - _writePos;
if (completeSynchronously)
{
-
- Exception error;
- WriteToBuffer(buffer, ref offset, ref count, out error);
- Debug.Assert(count == 0);
-
- return (error == null)
- ? Task.CompletedTask
- : Task.FromException(error);
+ int bytesWritten = WriteToBuffer(source.Span);
+ Debug.Assert(bytesWritten == source.Length);
+ return Task.CompletedTask;
}
}
finally
@@ -1058,23 +1091,17 @@ namespace System.IO
}
// Delegate to the async implementation.
- return WriteToUnderlyingStreamAsync(buffer, offset, count, cancellationToken, semaphoreLockTask);
+ return WriteToUnderlyingStreamAsync(source, cancellationToken, semaphoreLockTask);
}
-
/// <summary>BufferedStream should be as thin a wrapper as possible. We want WriteAsync to delegate to
/// WriteAsync of the underlying _stream rather than calling the base Stream which implements the one
/// in terms of the other. This allows BufferedStream to affect the semantics of the stream it wraps as
/// little as possible.
/// </summary>
- private async Task WriteToUnderlyingStreamAsync(byte[] array, int offset, int count,
- CancellationToken cancellationToken,
- Task semaphoreLockTask)
+ private async Task WriteToUnderlyingStreamAsync(
+ ReadOnlyMemory<byte> source, CancellationToken cancellationToken, Task semaphoreLockTask)
{
- Debug.Assert(array != null);
- Debug.Assert(offset >= 0);
- Debug.Assert(count >= 0);
- Debug.Assert(array.Length - offset >= count);
Debug.Assert(_stream != null);
Debug.Assert(_stream.CanWrite);
Debug.Assert(_bufferSize > 0);
@@ -1085,7 +1112,6 @@ namespace System.IO
await semaphoreLockTask.ConfigureAwait(false);
try
{
-
// The buffer might have been changed by another async task while we were waiting on the semaphore.
// However, note that if we recalculate the sync completion condition to TRUE, then useBuffer will also be TRUE.
@@ -1095,37 +1121,37 @@ namespace System.IO
int totalUserBytes;
bool useBuffer;
checked
- { // We do not expect buffer sizes big enough for an overflow, but if it happens, lets fail early:
- totalUserBytes = _writePos + count;
- useBuffer = (totalUserBytes + count < (_bufferSize + _bufferSize));
+ {
+ // We do not expect buffer sizes big enough for an overflow, but if it happens, lets fail early:
+ totalUserBytes = _writePos + source.Length;
+ useBuffer = (totalUserBytes + source.Length < (_bufferSize + _bufferSize));
}
if (useBuffer)
{
- WriteToBuffer(array, ref offset, ref count);
+ source = source.Slice(WriteToBuffer(source.Span));
if (_writePos < _bufferSize)
{
- Debug.Assert(count == 0);
+ Debug.Assert(source.Length == 0);
return;
}
- Debug.Assert(count >= 0);
+ Debug.Assert(source.Length >= 0);
Debug.Assert(_writePos == _bufferSize);
Debug.Assert(_buffer != null);
-
await _stream.WriteAsync(_buffer, 0, _writePos, cancellationToken).ConfigureAwait(false);
_writePos = 0;
- WriteToBuffer(array, ref offset, ref count);
+ int bytesWritten = WriteToBuffer(source.Span);
+ Debug.Assert(bytesWritten == source.Length);
- Debug.Assert(count == 0);
Debug.Assert(_writePos < _bufferSize);
}
- else
- { // if (!useBuffer)
+ else // !useBuffer
+ {
// Write out the buffer if necessary.
if (_writePos > 0)
{
@@ -1136,7 +1162,7 @@ namespace System.IO
if (totalUserBytes <= (_bufferSize + _bufferSize) && totalUserBytes <= MaxShadowBufferSize)
{
EnsureShadowBufferAllocated();
- Buffer.BlockCopy(array, offset, _buffer, _writePos, count);
+ source.Span.CopyTo(new Span<byte>(_buffer, _writePos, source.Length));
await _stream.WriteAsync(_buffer, 0, totalUserBytes, cancellationToken).ConfigureAwait(false);
_writePos = 0;
@@ -1148,7 +1174,7 @@ namespace System.IO
}
// Write out user data.
- await _stream.WriteAsync(array, offset, count, cancellationToken).ConfigureAwait(false);
+ await _stream.WriteAsync(source, cancellationToken).ConfigureAwait(false);
}
}
finally
diff --git a/src/System.Runtime.Extensions/src/System/IO/TextReader.cs b/src/System.Runtime.Extensions/src/System/IO/TextReader.cs
index c668a9e175..26a6df51c7 100644
--- a/src/System.Runtime.Extensions/src/System/IO/TextReader.cs
+++ b/src/System.Runtime.Extensions/src/System/IO/TextReader.cs
@@ -8,6 +8,7 @@ using System.Threading.Tasks;
using System.Diagnostics;
using System.Diagnostics.Contracts;
using System.Runtime.CompilerServices;
+using System.Buffers;
namespace System.IO
{
@@ -101,6 +102,30 @@ namespace System.IO
return n;
}
+ // Reads a span of characters. This method will read up to
+ // count characters from this TextReader into the
+ // span of characters Returns the actual number of characters read.
+ //
+ public virtual int Read(Span<char> destination)
+ {
+ char[] buffer = ArrayPool<char>.Shared.Rent(destination.Length);
+
+ try
+ {
+ int numRead = Read(buffer, 0, destination.Length);
+ if ((uint)numRead > destination.Length)
+ {
+ throw new IOException(SR.IO_InvalidReadLength);
+ }
+ new Span<char>(buffer, 0, numRead).CopyTo(destination);
+ return numRead;
+ }
+ finally
+ {
+ ArrayPool<char>.Shared.Return(buffer);
+ }
+ }
+
// Reads all characters from the current position to the end of the
// TextReader, and returns them as one string.
public virtual string ReadToEnd()
@@ -128,6 +153,29 @@ namespace System.IO
return n;
}
+ // Blocking version of read for span of characters. Returns only when count
+ // characters have been read or the end of the file was reached.
+ //
+ public virtual int ReadBlock(Span<char> destination)
+ {
+ char[] buffer = ArrayPool<char>.Shared.Rent(destination.Length);
+
+ try
+ {
+ int numRead = ReadBlock(buffer, 0, destination.Length);
+ if ((uint)numRead > destination.Length)
+ {
+ throw new IOException(SR.IO_InvalidReadLength);
+ }
+ new Span<char>(buffer, 0, numRead).CopyTo(destination);
+ return numRead;
+ }
+ finally
+ {
+ ArrayPool<char>.Shared.Return(buffer);
+ }
+ }
+
// Reads a line. A line is defined as a sequence of characters followed by
// a carriage return ('\r'), a line feed ('\n'), or a carriage return
// immediately followed by a line feed. The resulting string does not
diff --git a/src/System.Runtime.Extensions/src/System/IO/TextWriter.cs b/src/System.Runtime.Extensions/src/System/IO/TextWriter.cs
index 956f849914..29f7649a29 100644
--- a/src/System.Runtime.Extensions/src/System/IO/TextWriter.cs
+++ b/src/System.Runtime.Extensions/src/System/IO/TextWriter.cs
@@ -7,6 +7,7 @@ using System.Threading;
using System.Globalization;
using System.Threading.Tasks;
using System.Runtime.CompilerServices;
+using System.Buffers;
namespace System.IO
{
@@ -162,6 +163,23 @@ namespace System.IO
for (int i = 0; i < count; i++) Write(buffer[index + i]);
}
+ // Writes a span of characters to the text stream.
+ //
+ public virtual void Write(ReadOnlySpan<char> source)
+ {
+ char[] buffer = ArrayPool<char>.Shared.Rent(source.Length);
+
+ try
+ {
+ source.CopyTo(new Span<char>(buffer));
+ Write(buffer, 0, source.Length);
+ }
+ finally
+ {
+ ArrayPool<char>.Shared.Return(buffer);
+ }
+ }
+
// Writes the text representation of a boolean to the text stream. This
// method outputs either Boolean.TrueString or Boolean.FalseString.
//
@@ -329,6 +347,21 @@ namespace System.IO
WriteLine();
}
+ public virtual void WriteLine(ReadOnlySpan<char> source)
+ {
+ char[] buffer = ArrayPool<char>.Shared.Rent(source.Length);
+
+ try
+ {
+ source.CopyTo(new Span<char>(buffer));
+ WriteLine(buffer, 0, source.Length);
+ }
+ finally
+ {
+ ArrayPool<char>.Shared.Return(buffer);
+ }
+ }
+
// Writes the text representation of a boolean followed by a line
// terminator to the text stream.
//
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 60d3847a83..3b72334f4f 100644
--- a/src/System.Runtime.Extensions/tests/System.Runtime.Extensions.Tests.csproj
+++ b/src/System.Runtime.Extensions/tests/System.Runtime.Extensions.Tests.csproj
@@ -32,6 +32,9 @@
<Compile Include="System\Reflection\AssemblyNameProxyTests.cs" />
<Compile Include="System\MarshalByRefObjectTest.cs" />
</ItemGroup>
+ <ItemGroup Condition="'$(TargetGroup)'=='netcoreapp'">
+ <Compile Include="System\Random.netcoreapp.cs" />
+ </ItemGroup>
<ItemGroup Condition="'$(TargetGroup)'!='netstandard'">
<Compile Include="System\BitConverterSpan.cs" />
<Compile Include="System\BitConverter.netcoreapp.cs" />
@@ -123,4 +126,4 @@
</ProjectReference>
</ItemGroup>
<Import Project="$([MSBuild]::GetDirectoryNameOfFileAbove($(MSBuildThisFileDirectory), dir.targets))\dir.targets" />
-</Project> \ No newline at end of file
+</Project>
diff --git a/src/System.Runtime.Extensions/tests/System/EnvironmentTests.cs b/src/System.Runtime.Extensions/tests/System/EnvironmentTests.cs
index 3abbe6d7b6..18dc2f937d 100644
--- a/src/System.Runtime.Extensions/tests/System/EnvironmentTests.cs
+++ b/src/System.Runtime.Extensions/tests/System/EnvironmentTests.cs
@@ -275,7 +275,7 @@ namespace System.Tests
}
// Requires recent RS3 builds and needs to run inside AppContainer
- [ConditionalTheory(typeof(PlatformDetection), nameof(PlatformDetection.IsWindows10Version16251OrGreater), nameof(PlatformDetection.IsWinRT))]
+ [ConditionalTheory(typeof(PlatformDetection), nameof(PlatformDetection.IsWindows10Version16251OrGreater), nameof(PlatformDetection.IsInAppContainer))]
[InlineData(Environment.SpecialFolder.LocalApplicationData)]
[InlineData(Environment.SpecialFolder.Cookies)]
[InlineData(Environment.SpecialFolder.History)]
@@ -291,7 +291,7 @@ namespace System.Tests
}
// Requires recent RS3 builds and needs to run inside AppContainer
- [ConditionalTheory(typeof(PlatformDetection), nameof(PlatformDetection.IsWindows10Version16251OrGreater), nameof(PlatformDetection.IsWinRT))]
+ [ConditionalTheory(typeof(PlatformDetection), nameof(PlatformDetection.IsWindows10Version16251OrGreater), nameof(PlatformDetection.IsInAppContainer))]
[InlineData(Environment.SpecialFolder.ApplicationData)]
[InlineData(Environment.SpecialFolder.MyMusic)]
[InlineData(Environment.SpecialFolder.MyPictures)]
@@ -358,7 +358,7 @@ namespace System.Tests
[InlineData(Environment.SpecialFolder.ProgramFiles)]
[InlineData(Environment.SpecialFolder.CommonProgramFiles)]
[InlineData(Environment.SpecialFolder.AdminTools)]
- [InlineData(Environment.SpecialFolder.CDBurning)]
+ //[InlineData(Environment.SpecialFolder.CDBurning)] // Not available on Server Core
[InlineData(Environment.SpecialFolder.CommonAdminTools)]
[InlineData(Environment.SpecialFolder.CommonDocuments)]
[InlineData(Environment.SpecialFolder.CommonMusic)]
diff --git a/src/System.Runtime.Extensions/tests/System/MathTests.netcoreapp.cs b/src/System.Runtime.Extensions/tests/System/MathTests.netcoreapp.cs
index 2439880d91..f179214076 100644
--- a/src/System.Runtime.Extensions/tests/System/MathTests.netcoreapp.cs
+++ b/src/System.Runtime.Extensions/tests/System/MathTests.netcoreapp.cs
@@ -7,6 +7,7 @@ using Xunit;
namespace System.Tests
{
+ [SkipOnTargetFramework(TargetFrameworkMonikers.UapAot, "Math.Clamp is not in CoreRT yet.")]
public static partial class MathTests
{
public static IEnumerable<object[]> Clamp_UnsignedInt_TestData()
diff --git a/src/System.Runtime.Extensions/tests/System/Random.cs b/src/System.Runtime.Extensions/tests/System/Random.cs
index 74f75ae40f..9c15c6b292 100644
--- a/src/System.Runtime.Extensions/tests/System/Random.cs
+++ b/src/System.Runtime.Extensions/tests/System/Random.cs
@@ -6,7 +6,7 @@ using Xunit;
namespace System.Tests
{
- public static class RandomTests
+ public static partial class RandomTests
{
[Fact]
public static void Unseeded()
@@ -53,14 +53,12 @@ namespace System.Tests
}
}
- [Fact]
- public static void ExpectedValues()
+ // Random has a predictable sequence of values it generates based on its seed.
+ // So that we'll be made aware if a change to the implementation causes these
+ // sequences to change, this test verifies the first few numbers for a few seeds.
+ private static int[][] Values()
{
- // Random has a predictable sequence of values it generates based on its seed.
- // So that we'll be made aware if a change to the implementation causes these
- // sequences to change, this test verifies the first few numbers for a few seeds.
-
- var expectedValues = new int[][]
+ var expectedValues = new int[][]
{
new int[] {1559595546, 1755192844, 1649316166, 1198642031, 442452829, 1200195957, 1945678308, 949569752, 2099272109, 587775847},
new int[] {534011718, 237820880, 1002897798, 1657007234, 1412011072, 929393559, 760389092, 2026928803, 217468053, 1379662799},
@@ -83,7 +81,13 @@ namespace System.Tests
new int[] {278955818, 212301256, 751203777, 859281097, 714632027, 620720087, 2085308890, 1014679847, 439053806, 1956839101},
new int[] {1400855637, 842412939, 104785409, 1317646300, 1684190270, 349917689, 900019674, 2092038898, 704733397, 601242406},
};
+ return (expectedValues);
+ }
+ [Fact]
+ public static void ExpectedValues()
+ {
+ int[][] expectedValues = Values();
for (int seed = 0; seed < expectedValues.Length; seed++)
{
var r = new Random(seed);
@@ -94,6 +98,47 @@ namespace System.Tests
}
}
+ private static byte[][] ByteValues()
+ {
+ var expectedValues = new byte[][]
+ {
+ new byte[] { 0x1A, 0xC, 0x46, 0x6F, 0x5D, 0x75, 0xE4, 0xD8, 0xAD, 0x67 },
+ new byte[] { 0x46, 0xD0, 0x86, 0x82, 0x40, 0x97, 0xE4, 0xA3, 0x95, 0xCF },
+ new byte[] { 0x71, 0x93, 0xC6, 0x95, 0x24, 0xB9, 0xE3, 0x6F, 0x7C, 0x38 },
+ new byte[] { 0x9D, 0x56, 0x5, 0xA9, 0x7, 0xDB, 0xE3, 0x3A, 0x63, 0xA0 },
+ new byte[] { 0xC8, 0x19, 0x45, 0xBC, 0xEB, 0xFD, 0xE2, 0x6, 0x4A, 0x8 },
+ new byte[] { 0xF4, 0xDD, 0x85, 0xCF, 0xCE, 0x1E, 0xE2, 0xD1, 0x31, 0x71 },
+ new byte[] { 0x1F, 0xA0, 0xC4, 0xE2, 0xB1, 0x40, 0xE1, 0x9D, 0x18, 0xD9 },
+ new byte[] { 0x4B, 0x63, 0x4, 0xF6, 0x95, 0x62, 0xE1, 0x68, 0xFF, 0x41 },
+ new byte[] { 0x76, 0x27, 0x44, 0x9, 0x78, 0x84, 0xE0, 0x34, 0xE6, 0xAA },
+ new byte[] { 0xA2, 0xEA, 0x84, 0x1C, 0x5C, 0xA6, 0xDF, 0xFF, 0xCE, 0x12 },
+ new byte[] { 0xCD, 0xAD, 0xC3, 0x2F, 0x3F, 0xC8, 0xDF, 0xCB, 0xB5, 0x7A },
+ new byte[] { 0xF9, 0x71, 0x3, 0x42, 0x23, 0xEA, 0xDE, 0x96, 0x9C, 0xE3 },
+ new byte[] { 0x24, 0x34, 0x43, 0x56, 0x6, 0xC, 0xDE, 0x62, 0x83, 0x4B },
+ new byte[] { 0x50, 0xF7, 0x82, 0x69, 0xEA, 0x2D, 0xDD, 0x2D, 0x6A, 0xB4 },
+ new byte[] { 0x7C, 0xBA, 0xC2, 0x7C, 0xCD, 0x4F, 0xDD, 0xF9, 0x51, 0x1C },
+ new byte[] { 0xA7, 0x7E, 0x2, 0x8F, 0xB0, 0x71, 0xDC, 0xC4, 0x38, 0x84 },
+ new byte[] { 0xD3, 0x41, 0x41, 0xA2, 0x94, 0x93, 0xDC, 0x90, 0x1F, 0xED },
+ new byte[] { 0xFE, 0x4, 0x81, 0xB6, 0x77, 0xB5, 0xDB, 0x5B, 0x7, 0x55 },
+ new byte[] { 0x2A, 0xC8, 0xC1, 0xC9, 0x5B, 0xD7, 0xDA, 0x27, 0xEE, 0xBD },
+ new byte[] { 0x55, 0x8B, 0x1, 0xDC, 0x3E, 0xF9, 0xDA, 0xF2, 0xD5, 0x26 }
+ };
+ return (expectedValues);
+ }
+
+ [Fact]
+ public static void ExpectedValues_NextBytesArray()
+ {
+ byte[][] expectedValues = ByteValues();
+ for (int seed = 0; seed < expectedValues.Length; seed++)
+ {
+ byte[] actualValues = new byte[expectedValues[seed].Length];
+ var r = new Random(seed);
+ r.NextBytes(actualValues);
+ Assert.Equal(expectedValues[seed], actualValues);
+ }
+ }
+
[Fact]
public static void Sample()
{
diff --git a/src/System.Runtime.Extensions/tests/System/Random.netcoreapp.cs b/src/System.Runtime.Extensions/tests/System/Random.netcoreapp.cs
new file mode 100644
index 0000000000..5d00083f3f
--- /dev/null
+++ b/src/System.Runtime.Extensions/tests/System/Random.netcoreapp.cs
@@ -0,0 +1,56 @@
+// 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 RandomTests
+ {
+ [Fact]
+ public static void Empty_Span()
+ {
+ int seed = Environment.TickCount;
+ Random r = new Random(seed);
+ r.NextBytes(Span<byte>.Empty);
+ }
+
+ [Fact]
+ public static void Seeded_Span()
+ {
+ int seed = Environment.TickCount;
+
+ Random r1 = new Random(seed);
+ Random r2 = new Random(seed);
+
+ Span<byte> s1 = new Span<byte>(new byte[1000]);
+ r1.NextBytes(s1);
+ Span<byte> s2 = new Span<byte>(new byte[1000]);
+ r2.NextBytes(s2);
+ for (int i = 0; i < s1.Length; i++)
+ {
+ Assert.Equal(s1[i], s2[i]);
+ }
+ for (int i = 0; i < s1.Length; i++)
+ {
+ int x1 = r1.Next();
+ int x2 = r2.Next();
+ Assert.Equal(x1, x2);
+ }
+ }
+
+ [Fact]
+ public static void ExpectedValues_NextBytesSpan()
+ {
+ byte[][] expectedValues = ByteValues();
+ for (int seed = 0; seed < expectedValues.Length; seed++)
+ {
+ byte[] actualValues = new byte[expectedValues[seed].Length];
+ var r = new Random(seed);
+ r.NextBytes(new Span<byte>(actualValues));
+ Assert.Equal(expectedValues[seed], actualValues);
+ }
+ }
+ }
+}
diff --git a/src/System.Runtime.InteropServices/ref/System.Runtime.InteropServices.cs b/src/System.Runtime.InteropServices/ref/System.Runtime.InteropServices.cs
index f2d619b8f4..3f36a1dd88 100644
--- a/src/System.Runtime.InteropServices/ref/System.Runtime.InteropServices.cs
+++ b/src/System.Runtime.InteropServices/ref/System.Runtime.InteropServices.cs
@@ -7,6 +7,8 @@
// Types moved down into System.Runtime.Handles
[assembly: System.Runtime.CompilerServices.TypeForwardedTo(typeof(System.Runtime.InteropServices.CriticalHandle))]
+[assembly: System.Runtime.CompilerServices.TypeForwardedTo(typeof(System.Runtime.InteropServices.GCHandle))]
+[assembly: System.Runtime.CompilerServices.TypeForwardedTo(typeof(System.Runtime.InteropServices.GCHandleType))]
[assembly: System.Runtime.CompilerServices.TypeForwardedTo(typeof(System.Runtime.InteropServices.SafeHandle))]
[assembly: System.Runtime.CompilerServices.TypeForwardedTo(typeof(System.Reflection.Missing))]
@@ -393,31 +395,6 @@ namespace System.Runtime.InteropServices
public ErrorWrapper(object errorCode) { }
public int ErrorCode { get { throw null; } }
}
- [System.Runtime.InteropServices.StructLayoutAttribute(System.Runtime.InteropServices.LayoutKind.Sequential)]
- public partial struct GCHandle
- {
- public bool IsAllocated { get { throw null; } }
- public object Target {get { throw null; } set { } }
- public System.IntPtr AddrOfPinnedObject() { throw null; }
- public static System.Runtime.InteropServices.GCHandle Alloc(object value) { throw null; }
- public static System.Runtime.InteropServices.GCHandle Alloc(object value, System.Runtime.InteropServices.GCHandleType type) { throw null; }
- public override bool Equals(object o) { throw null; }
- public void Free() { }
- public static System.Runtime.InteropServices.GCHandle FromIntPtr(System.IntPtr value) { throw null; }
- public override int GetHashCode() { throw null; }
- public static bool operator ==(System.Runtime.InteropServices.GCHandle a, System.Runtime.InteropServices.GCHandle b) { throw null; }
- public static explicit operator System.Runtime.InteropServices.GCHandle(System.IntPtr value) { throw null; }
- public static explicit operator System.IntPtr(System.Runtime.InteropServices.GCHandle value) { throw null; }
- public static bool operator !=(System.Runtime.InteropServices.GCHandle a, System.Runtime.InteropServices.GCHandle b) { throw null; }
- public static System.IntPtr ToIntPtr(System.Runtime.InteropServices.GCHandle value) { throw null; }
- }
- public enum GCHandleType
- {
- Normal = 2,
- Pinned = 3,
- Weak = 0,
- WeakTrackResurrection = 1,
- }
[System.AttributeUsageAttribute((System.AttributeTargets)(5149), Inherited = false)]
public sealed partial class GuidAttribute : System.Attribute
{
diff --git a/src/System.Runtime.Intrinsics.X86/System.Runtime.Intrinsics.X86.sln b/src/System.Runtime.Intrinsics.X86/System.Runtime.Intrinsics.X86.sln
new file mode 100644
index 0000000000..1278c3d520
--- /dev/null
+++ b/src/System.Runtime.Intrinsics.X86/System.Runtime.Intrinsics.X86.sln
@@ -0,0 +1,23 @@
+
+Microsoft Visual Studio Solution File, Format Version 12.00
+# Visual Studio 14
+VisualStudioVersion = 14.0.25420.1
+MinimumVisualStudioVersion = 10.0.40219.1
+Project("{2150E333-8FDC-42A3-9474-1A3956D46DE8}") = "ref", "ref", "{F8DD26AC-C306-481B-B0DA-E7D4CD4EF6D7}"
+ ProjectSection(SolutionItems) = preProject
+ ref\Configurations.props = ref\Configurations.props
+ ref\System.Runtime.Intrinsics.X86.cs = ref\System.Runtime.Intrinsics.X86.cs
+ ref\System.Runtime.Intrinsics.X86.csproj = ref\System.Runtime.Intrinsics.X86.csproj
+ EndProjectSection
+EndProject
+Project("{2150E333-8FDC-42A3-9474-1A3956D46DE8}") = "src", "src", "{4F13FF59-6559-4930-B226-5610D85685CD}"
+ ProjectSection(SolutionItems) = preProject
+ src\Configurations.props = src\Configurations.props
+ src\System.Runtime.Intrinsics.X86.csproj = src\System.Runtime.Intrinsics.X86.csproj
+ EndProjectSection
+EndProject
+Global
+ GlobalSection(SolutionProperties) = preSolution
+ HideSolutionNode = FALSE
+ EndGlobalSection
+EndGlobal
diff --git a/src/System.Runtime.Intrinsics.X86/dir.props b/src/System.Runtime.Intrinsics.X86/dir.props
new file mode 100644
index 0000000000..4356decc45
--- /dev/null
+++ b/src/System.Runtime.Intrinsics.X86/dir.props
@@ -0,0 +1,8 @@
+<?xml version="1.0" encoding="utf-8"?>
+<Project ToolsVersion="14.0" DefaultTargets="Build" xmlns="http://schemas.microsoft.com/developer/msbuild/2003">
+ <Import Project="..\dir.props" />
+ <PropertyGroup>
+ <AssemblyVersion>4.0.0.0</AssemblyVersion>
+ <AssemblyKey>Open</AssemblyKey>
+ </PropertyGroup>
+</Project> \ No newline at end of file
diff --git a/src/System.Runtime.Intrinsics.X86/pkg/System.Runtime.Intrinsics.X86.pkgproj b/src/System.Runtime.Intrinsics.X86/pkg/System.Runtime.Intrinsics.X86.pkgproj
new file mode 100644
index 0000000000..d4b7b04f25
--- /dev/null
+++ b/src/System.Runtime.Intrinsics.X86/pkg/System.Runtime.Intrinsics.X86.pkgproj
@@ -0,0 +1,11 @@
+<?xml version="1.0" encoding="utf-8"?>
+<Project ToolsVersion="14.0" DefaultTargets="Build" xmlns="http://schemas.microsoft.com/developer/msbuild/2003">
+ <Import Project="$([MSBuild]::GetDirectoryNameOfFileAbove($(MSBuildThisFileDirectory), dir.props))\dir.props" />
+ <ItemGroup>
+ <ProjectReference Include="..\ref\System.Runtime.Intrinsics.X86.csproj">
+ <SupportedFramework>netcoreapp2.1</SupportedFramework>
+ </ProjectReference>
+ <ProjectReference Include="..\src\System.Runtime.Intrinsics.X86.csproj" />
+ </ItemGroup>
+ <Import Project="$([MSBuild]::GetDirectoryNameOfFileAbove($(MSBuildThisFileDirectory), dir.targets))\dir.targets" />
+</Project> \ No newline at end of file
diff --git a/src/System.Runtime.Intrinsics.X86/ref/Configurations.props b/src/System.Runtime.Intrinsics.X86/ref/Configurations.props
new file mode 100644
index 0000000000..2845c11c54
--- /dev/null
+++ b/src/System.Runtime.Intrinsics.X86/ref/Configurations.props
@@ -0,0 +1,8 @@
+<?xml version="1.0" encoding="utf-8"?>
+<Project ToolsVersion="14.0" DefaultTargets="Build" xmlns="http://schemas.microsoft.com/developer/msbuild/2003">
+ <PropertyGroup>
+ <BuildConfigurations>
+ netcoreapp;
+ </BuildConfigurations>
+ </PropertyGroup>
+</Project> \ No newline at end of file
diff --git a/src/System.Runtime.Intrinsics.X86/ref/System.Runtime.Intrinsics.X86.cs b/src/System.Runtime.Intrinsics.X86/ref/System.Runtime.Intrinsics.X86.cs
new file mode 100644
index 0000000000..c9f0274438
--- /dev/null
+++ b/src/System.Runtime.Intrinsics.X86/ref/System.Runtime.Intrinsics.X86.cs
@@ -0,0 +1,1204 @@
+// 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.
+// ------------------------------------------------------------------------------
+// Changes to this file must follow the http://aka.ms/api-review process.
+// ------------------------------------------------------------------------------
+
+using System.Runtime.InteropServices;
+
+namespace System.Runtime.Intrinsics
+{
+ [StructLayout(LayoutKind.Sequential, Size = 16)]
+ public struct Vector128<T> where T : struct {}
+ [StructLayout(LayoutKind.Sequential, Size = 32)]
+ public struct Vector256<T> where T : struct {}
+}
+
+namespace System.Runtime.Intrinsics.X86
+{
+ public static class Aes
+ {
+ public static bool IsSupported { get { throw null; } }
+ public static Vector128<sbyte> Decrypt(Vector128<sbyte> value, Vector128<sbyte> roundKey) { throw null; }
+ public static Vector128<byte> Decrypt(Vector128<byte> value, Vector128<byte> roundKey) { throw null; }
+ public static Vector128<sbyte> DecryptLast(Vector128<sbyte> value, Vector128<sbyte> roundKey) { throw null; }
+ public static Vector128<byte> DecryptLast(Vector128<byte> value, Vector128<byte> roundKey) { throw null; }
+ public static Vector128<sbyte> Encrypt(Vector128<sbyte> value, Vector128<sbyte> roundKey) { throw null; }
+ public static Vector128<byte> Encrypt(Vector128<byte> value, Vector128<byte> roundKey) { throw null; }
+ public static Vector128<sbyte> EncryptLast(Vector128<sbyte> value, Vector128<sbyte> roundKey) { throw null; }
+ public static Vector128<byte> EncryptLast(Vector128<byte> value, Vector128<byte> roundKey) { throw null; }
+ public static Vector128<sbyte> InvisibleMixColumn(Vector128<sbyte> value) { throw null; }
+ public static Vector128<byte> InvisibleMixColumn(Vector128<byte> value) { throw null; }
+ public static Vector128<sbyte> KeygenAssist(Vector128<sbyte> value, byte control) { throw null; }
+ public static Vector128<byte> KeygenAssist(Vector128<byte> value, byte control) { throw null; }
+ }
+ public static class Avx
+ {
+ public static bool IsSupported { get { throw null; } }
+ public static Vector256<float> Add(Vector256<float> left, Vector256<float> right) { throw null; }
+ public static Vector256<double> Add(Vector256<double> left, Vector256<double> right) { throw null; }
+ public static Vector256<float> AddSubtract(Vector256<float> left, Vector256<float> right) { throw null; }
+ public static Vector256<double> AddSubtract(Vector256<double> left, Vector256<double> right) { throw null; }
+ public static Vector256<float> And(Vector256<float> left, Vector256<float> right) { throw null; }
+ public static Vector256<double> And(Vector256<double> left, Vector256<double> right) { throw null; }
+ public static Vector256<float> AndNot(Vector256<float> left, Vector256<float> right) { throw null; }
+ public static Vector256<double> AndNot(Vector256<double> left, Vector256<double> right) { throw null; }
+ public static Vector256<float> Blend(Vector256<float> left, Vector256<float> right, byte control) { throw null; }
+ public static Vector256<double> Blend(Vector256<double> left, Vector256<double> right, byte control) { throw null; }
+ public static Vector256<float> BlendVariable(Vector256<float> left, Vector256<float> right, Vector256<float> mask) { throw null; }
+ public static Vector256<double> BlendVariable(Vector256<double> left, Vector256<double> right, Vector256<double> mask) { throw null; }
+ public static Vector128<float> BroadcastElementToVector128(ref float source) { throw null; }
+ public static unsafe Vector256<float> BroadcastVector128ToVector256(float* address) { throw null; }
+ public static Vector256<float> BroadcastElementToVector256(ref float source) { throw null; }
+ public static unsafe Vector256<double> BroadcastVector128ToVector256(double* address) { throw null; }
+ public static Vector256<double> BroadcastElementToVector256(ref double source) { throw null; }
+ public static Vector256<float> Ceiling(Vector256<float> value) { throw null; }
+ public static Vector256<double> Ceiling(Vector256<double> value) { throw null; }
+ public static Vector128<float> Compare(Vector128<float> left, Vector128<float> right, FloatComparisonMode mode) { throw null; }
+ public static Vector128<double> Compare(Vector128<double> left, Vector128<double> right, FloatComparisonMode mode) { throw null; }
+ public static Vector256<float> Compare(Vector256<float> left, Vector256<float> right, FloatComparisonMode mode) { throw null; }
+ public static Vector256<double> Compare(Vector256<double> left, Vector256<double> right, FloatComparisonMode mode) { throw null; }
+ public static Vector128<int> ConvertToVector128Int(Vector256<double> value) { throw null; }
+ public static Vector128<float> ConvertToVector128Float(Vector256<double> value) { throw null; }
+ public static Vector256<int> ConvertToVector256Int(Vector256<float> value) { throw null; }
+ public static Vector256<float> ConvertToVector256Float(Vector256<int> value) { throw null; }
+ public static Vector256<double> ConvertToVector256Double(Vector256<float> value) { throw null; }
+ public static Vector256<double> ConvertToVector256Double(Vector256<int> value) { throw null; }
+ public static Vector128<int> ConvertToVector128IntWithTruncation(Vector256<double> value) { throw null; }
+ public static Vector256<int> ConvertToVector256IntWithTruncation(Vector256<float> value) { throw null; }
+ public static Vector256<float> Divide(Vector256<float> left, Vector256<float> right) { throw null; }
+ public static Vector256<double> Divide(Vector256<double> left, Vector256<double> right) { throw null; }
+ public static Vector256<float> DotProduct(Vector256<float> left, Vector256<float> right, byte control) { throw null; }
+ public static Vector256<float> DuplicateEvenIndexed(Vector256<float> value) { throw null; }
+ public static Vector256<double> DuplicateEvenIndexed(Vector256<double> value) { throw null; }
+ public static Vector256<float> DuplicateOddIndexed(Vector256<float> value) { throw null; }
+ public static sbyte ExtractSbyte<T>(Vector256<T> value, byte index) where T : struct { throw null; }
+ public static byte ExtractByte<T>(Vector256<T> value, byte index) where T : struct { throw null; }
+ public static short ExtractShort<T>(Vector256<T> value, byte index) where T : struct { throw null; }
+ public static ushort ExtractUshort<T>(Vector256<T> value, byte index) where T : struct { throw null; }
+ public static int ExtractInt<T>(Vector256<T> value, byte index) where T : struct { throw null; }
+ public static uint ExtractUint<T>(Vector256<T> value, byte index) where T : struct { throw null; }
+ public static long ExtractLong<T>(Vector256<T> value, byte index) where T : struct { throw null; }
+ public static ulong ExtractUlong<T>(Vector256<T> value, byte index) where T : struct { throw null; }
+ public static Vector128<T> ExtractVector128<T>(Vector256<T> value, byte index) where T : struct { throw null; }
+ public static unsafe void ExtractVector128(byte* address, Vector256<byte> value, byte index) { throw null; }
+ public static unsafe void ExtractVector128(sbyte* address, Vector256<sbyte> value, byte index) { throw null; }
+ public static unsafe void ExtractVector128(short* address, Vector256<short> value, byte index) { throw null; }
+ public static unsafe void ExtractVector128(ushort* address, Vector256<ushort> value, byte index) { throw null; }
+ public static unsafe void ExtractVector128(int* address, Vector256<int> value, byte index) { throw null; }
+ public static unsafe void ExtractVector128(uint* address, Vector256<uint> value, byte index) { throw null; }
+ public static unsafe void ExtractVector128(long* address, Vector256<long> value, byte index) { throw null; }
+ public static unsafe void ExtractVector128(ulong* address, Vector256<ulong> value, byte index) { throw null; }
+ public static unsafe void ExtractVector128(float* address, Vector256<float> value, byte index) { throw null; }
+ public static unsafe void ExtractVector128(double* address, Vector256<double> value, byte index) { throw null; }
+ public static Vector256<T> ExtendToVector256<T>(Vector128<T> value) where T : struct { throw null; }
+ public static Vector256<float> Floor(Vector256<float> value) { throw null; }
+ public static Vector256<double> Floor(Vector256<double> value) { throw null; }
+ public static Vector128<T> GetLowerHalf<T>(Vector256<T> value) where T : struct { throw null; }
+ public static Vector256<float> HorizontalAdd(Vector256<float> left, Vector256<float> right) { throw null; }
+ public static Vector256<double> HorizontalAdd(Vector256<double> left, Vector256<double> right) { throw null; }
+ public static Vector256<float> HorizontalSubtract(Vector256<float> left, Vector256<float> right) { throw null; }
+ public static Vector256<double> HorizontalSubtract(Vector256<double> left, Vector256<double> right) { throw null; }
+ public static Vector256<T> InsertSbyte<T>(Vector256<T> value, sbyte data, byte index) where T : struct { throw null; }
+ public static Vector256<T> InsertByte<T>(Vector256<T> value, byte data, byte index) where T : struct { throw null; }
+ public static Vector256<T> InsertShort<T>(Vector256<T> value, short data, byte index) where T : struct { throw null; }
+ public static Vector256<T> InsertUshort<T>(Vector256<T> value, ushort data, byte index) where T : struct { throw null; }
+ public static Vector256<T> InsertInt<T>(Vector256<T> value, int data, byte index) where T : struct { throw null; }
+ public static Vector256<T> InsertUint<T>(Vector256<T> value, uint data, byte index) where T : struct { throw null; }
+ public static Vector256<T> InsertLong<T>(Vector256<T> value, long data, byte index) where T : struct { throw null; }
+ public static Vector256<T> InsertUlong<T>(Vector256<T> value, ulong data, byte index) where T : struct { throw null; }
+ public static Vector256<T> Insert<T>(Vector256<T> value, Vector128<T> data, byte index) where T : struct { throw null; }
+ public static unsafe Vector256<sbyte> Insert(Vector256<sbyte> value, sbyte* address, byte index) { throw null; }
+ public static unsafe Vector256<byte> Insert(Vector256<byte> value, byte* address, byte index) { throw null; }
+ public static unsafe Vector256<short> Insert(Vector256<short> value, short* address, byte index) { throw null; }
+ public static unsafe Vector256<ushort> Insert(Vector256<ushort> value, ushort* address, byte index) { throw null; }
+ public static unsafe Vector256<int> Insert(Vector256<int> value, int* address, byte index) { throw null; }
+ public static unsafe Vector256<uint> Insert(Vector256<uint> value, uint* address, byte index) { throw null; }
+ public static unsafe Vector256<long> Insert(Vector256<long> value, long* address, byte index) { throw null; }
+ public static unsafe Vector256<ulong> Insert(Vector256<ulong> value, ulong* address, byte index) { throw null; }
+ public static unsafe Vector256<float> Insert(Vector256<float> value, float* address, byte index) { throw null; }
+ public static unsafe Vector256<double> Insert(Vector256<double> value, double* address, byte index) { throw null; }
+ public static unsafe Vector256<sbyte> Load(sbyte* address) { throw null; }
+ public static unsafe Vector256<byte> Load(byte* address) { throw null; }
+ public static unsafe Vector256<short> Load(short* address) { throw null; }
+ public static unsafe Vector256<ushort> Load(ushort* address) { throw null; }
+ public static unsafe Vector256<int> Load(int* address) { throw null; }
+ public static unsafe Vector256<uint> Load(uint* address) { throw null; }
+ public static unsafe Vector256<long> Load(long* address) { throw null; }
+ public static unsafe Vector256<ulong> Load(ulong* address) { throw null; }
+ public static unsafe Vector256<float> Load(float* address) { throw null; }
+ public static unsafe Vector256<double> Load(double* address) { throw null; }
+ public static unsafe Vector256<sbyte> LoadAligned(sbyte* address) { throw null; }
+ public static unsafe Vector256<byte> LoadAligned(byte* address) { throw null; }
+ public static unsafe Vector256<short> LoadAligned(short* address) { throw null; }
+ public static unsafe Vector256<ushort> LoadAligned(ushort* address) { throw null; }
+ public static unsafe Vector256<int> LoadAligned(int* address) { throw null; }
+ public static unsafe Vector256<uint> LoadAligned(uint* address) { throw null; }
+ public static unsafe Vector256<long> LoadAligned(long* address) { throw null; }
+ public static unsafe Vector256<ulong> LoadAligned(ulong* address) { throw null; }
+ public static unsafe Vector256<float> LoadAligned(float* address) { throw null; }
+ public static unsafe Vector256<double> LoadAligned(double* address) { throw null; }
+ public static unsafe Vector256<sbyte> LoadDqu(sbyte* address) { throw null; }
+ public static unsafe Vector256<byte> LoadDqu(byte* address) { throw null; }
+ public static unsafe Vector256<short> LoadDqu(short* address) { throw null; }
+ public static unsafe Vector256<ushort> LoadDqu(ushort* address) { throw null; }
+ public static unsafe Vector256<int> LoadDqu(int* address) { throw null; }
+ public static unsafe Vector256<uint> LoadDqu(uint* address) { throw null; }
+ public static unsafe Vector256<long> LoadDqu(long* address) { throw null; }
+ public static unsafe Vector256<ulong> LoadDqu(ulong* address) { throw null; }
+ public static unsafe Vector128<float> MaskLoad(float* address, Vector128<uint> mask) { throw null; }
+ public static unsafe Vector128<double> MaskLoad(double* address, Vector128<ulong> mask) { throw null; }
+ public static unsafe Vector256<float> MaskLoad(float* address, Vector256<uint> mask) { throw null; }
+ public static unsafe Vector256<double> MaskLoad(double* address, Vector256<ulong> mask) { throw null; }
+ public static unsafe void MaskStore(float* address, Vector128<float> mask, Vector128<uint> source) { throw null; }
+ public static unsafe void MaskStore(double* address, Vector128<double> mask, Vector128<ulong> source) { throw null; }
+ public static unsafe void MaskStore(float* address, Vector256<float> mask, Vector256<uint> source) { throw null; }
+ public static unsafe void MaskStore(double* address, Vector256<double> mask, Vector256<ulong> source) { throw null; }
+ public static Vector256<float> Max(Vector256<float> left, Vector256<float> right) { throw null; }
+ public static Vector256<double> Max(Vector256<double> left, Vector256<double> right) { throw null; }
+ public static Vector256<float> Min(Vector256<float> left, Vector256<float> right) { throw null; }
+ public static Vector256<double> Min(Vector256<double> left, Vector256<double> right) { throw null; }
+ public static int MoveMask(Vector256<float> value) { throw null; }
+ public static int MoveMask(Vector256<double> value) { throw null; }
+ public static Vector256<float> Multiply(Vector256<float> left, Vector256<float> right) { throw null; }
+ public static Vector256<double> Multiply(Vector256<double> left, Vector256<double> right) { throw null; }
+ public static Vector256<float> Or(Vector256<float> left, Vector256<float> right) { throw null; }
+ public static Vector256<double> Or(Vector256<double> left, Vector256<double> right) { throw null; }
+ public static Vector128<float> Permute(Vector128<float> value, byte control) { throw null; }
+ public static Vector128<double> Permute(Vector128<double> value, byte control) { throw null; }
+ public static Vector256<float> Permute(Vector256<float> value, byte control) { throw null; }
+ public static Vector256<double> Permute(Vector256<double> value, byte control) { throw null; }
+ public static Vector256<float> Permute2x128(Vector256<float> left, Vector256<float> right, byte control) { throw null; }
+ public static Vector256<double> Permute2x128(Vector256<double> left, Vector256<double> right, byte control) { throw null; }
+ public static Vector128<float> PermuteVar(Vector128<float> left, Vector128<float> mask) { throw null; }
+ public static Vector128<double> PermuteVar(Vector128<double> left, Vector128<double> mask) { throw null; }
+ public static Vector256<float> PermuteVar(Vector256<float> left, Vector256<float> mask) { throw null; }
+ public static Vector256<double> PermuteVar(Vector256<double> left, Vector256<double> mask) { throw null; }
+ public static Vector256<float> Reciprocal(Vector256<float> value) { throw null; }
+ public static Vector256<float> ReciprocalSqrt(Vector256<float> value) { throw null; }
+ public static Vector256<float> RoundToNearestInteger(Vector256<float> value) { throw null; }
+ public static Vector256<float> RoundToNegativeInfinity(Vector256<float> value) { throw null; }
+ public static Vector256<float> RoundToPositiveInfinity(Vector256<float> value) { throw null; }
+ public static Vector256<float> RoundToZero(Vector256<float> value) { throw null; }
+ public static Vector256<float> RoundCurrentDirection(Vector256<float> value) { throw null; }
+ public static Vector256<double> RoundToNearestInteger(Vector256<double> value) { throw null; }
+ public static Vector256<double> RoundToNegativeInfinity(Vector256<double> value) { throw null; }
+ public static Vector256<double> RoundToPositiveInfinity(Vector256<double> value) { throw null; }
+ public static Vector256<double> RoundToZero(Vector256<double> value) { throw null; }
+ public static Vector256<double> RoundCurrentDirection(Vector256<double> value) { throw null; }
+ public static Vector256<sbyte> Set(sbyte e31, sbyte e30, sbyte e29, sbyte e28, sbyte e27, sbyte e26, sbyte e25, sbyte e24, sbyte e23, sbyte e22, sbyte e21, sbyte e20, sbyte e19, sbyte e18, sbyte e17, sbyte e16, sbyte e15, sbyte e14, sbyte e13, sbyte e12, sbyte e11, sbyte e10, sbyte e9, sbyte e8, sbyte e7, sbyte e6, sbyte e5, sbyte e4, sbyte e3, sbyte e2, sbyte e1, sbyte e0) { throw null; }
+ public static Vector256<byte> Set(byte e31, byte e30, byte e29, byte e28, byte e27, byte e26, byte e25, byte e24, byte e23, byte e22, byte e21, byte e20, byte e19, byte e18, byte e17, byte e16, byte e15, byte e14, byte e13, byte e12, byte e11, byte e10, byte e9, byte e8, byte e7, byte e6, byte e5, byte e4, byte e3, byte e2, byte e1, byte e0) { throw null; }
+ public static Vector256<short> Set(short e15, short e14, short e13, short e12, short e11, short e10, short e9, short e8, short e7, short e6, short e5, short e4, short e3, short e2, short e1, short e0) { throw null; }
+ public static Vector256<ushort> Set(ushort e15, ushort e14, ushort e13, ushort e12, ushort e11, ushort e10, ushort e9, ushort e8, ushort e7, ushort e6, ushort e5, ushort e4, ushort e3, ushort e2, ushort e1, ushort e0) { throw null; }
+ public static Vector256<int> Set(int e7, int e6, int e5, int e4, int e3, int e2, int e1, int e0) { throw null; }
+ public static Vector256<uint> Set(uint e7, uint e6, uint e5, uint e4, uint e3, uint e2, uint e1, uint e0) { throw null; }
+ public static Vector256<long> Set(long e3, long e2, long e1, long e0) { throw null; }
+ public static Vector256<ulong> Set(ulong e3, ulong e2, ulong e1, ulong e0) { throw null; }
+ public static Vector256<float> Set(float e7, float e6, float e5, float e4, float e3, float e2, float e1, float e0) { throw null; }
+ public static Vector256<double> Set(double e3, double e2, double e1, double e0) { throw null; }
+ public static Vector256<T> Set1<T>(T value) where T : struct { throw null; }
+ public static Vector256<T> SetHiLo<T>(Vector128<T> hi, Vector128<T> lo) where T : struct { throw null; }
+ public static Vector256<T> SetZero<T>() where T : struct { throw null; }
+ public static Vector256<float> Shuffle(Vector256<float> value, Vector256<float> right, byte control) { throw null; }
+ public static Vector256<double> Shuffle(Vector256<double> value, Vector256<double> right, byte control) { throw null; }
+ public static Vector256<float> Sqrt(Vector256<float> value) { throw null; }
+ public static Vector256<double> Sqrt(Vector256<double> value) { throw null; }
+ public static Vector256<U> StaticCast<T, U>(Vector256<T> value) where T : struct where U : struct { throw null; }
+ public static unsafe void StoreAligned(sbyte* address, Vector256<sbyte> source) { throw null; }
+ public static unsafe void StoreAligned(byte* address, Vector256<byte> source) { throw null; }
+ public static unsafe void StoreAligned(short* address, Vector256<short> source) { throw null; }
+ public static unsafe void StoreAligned(ushort* address, Vector256<ushort> source) { throw null; }
+ public static unsafe void StoreAligned(int* address, Vector256<int> source) { throw null; }
+ public static unsafe void StoreAligned(uint* address, Vector256<uint> source) { throw null; }
+ public static unsafe void StoreAligned(long* address, Vector256<long> source) { throw null; }
+ public static unsafe void StoreAligned(ulong* address, Vector256<ulong> source) { throw null; }
+ public static unsafe void StoreAligned(float* address, Vector256<float> source) { throw null; }
+ public static unsafe void StoreAligned(double* address, Vector256<double> source) { throw null; }
+ public static unsafe void StoreAlignedNonTemporal(sbyte* address, Vector256<sbyte> source) { throw null; }
+ public static unsafe void StoreAlignedNonTemporal(byte* address, Vector256<byte> source) { throw null; }
+ public static unsafe void StoreAlignedNonTemporal(short* address, Vector256<short> source) { throw null; }
+ public static unsafe void StoreAlignedNonTemporal(ushort* address, Vector256<ushort> source) { throw null; }
+ public static unsafe void StoreAlignedNonTemporal(int* address, Vector256<int> source) { throw null; }
+ public static unsafe void StoreAlignedNonTemporal(uint* address, Vector256<uint> source) { throw null; }
+ public static unsafe void StoreAlignedNonTemporal(long* address, Vector256<long> source) { throw null; }
+ public static unsafe void StoreAlignedNonTemporal(ulong* address, Vector256<ulong> source) { throw null; }
+ public static unsafe void StoreAlignedNonTemporal(float* address, Vector256<float> source) { throw null; }
+ public static unsafe void StoreAlignedNonTemporal(double* address, Vector256<double> source) { throw null; }
+ public static unsafe void Store(sbyte* address, Vector256<sbyte> source) { throw null; }
+ public static unsafe void Store(byte* address, Vector256<byte> source) { throw null; }
+ public static unsafe void Store(short* address, Vector256<short> source) { throw null; }
+ public static unsafe void Store(ushort* address, Vector256<ushort> source) { throw null; }
+ public static unsafe void Store(int* address, Vector256<int> source) { throw null; }
+ public static unsafe void Store(uint* address, Vector256<uint> source) { throw null; }
+ public static unsafe void Store(long* address, Vector256<long> source) { throw null; }
+ public static unsafe void Store(ulong* address, Vector256<ulong> source) { throw null; }
+ public static unsafe void Store(float* address, Vector256<float> source) { throw null; }
+ public static unsafe void Store(double* address, Vector256<double> source) { throw null; }
+ public static Vector256<float> Subtract(Vector256<float> left, Vector256<float> right) { throw null; }
+ public static Vector256<double> Subtract(Vector256<double> left, Vector256<double> right) { throw null; }
+ public static bool TestC(Vector128<float> left, Vector128<float> right) { throw null; }
+ public static bool TestC(Vector128<double> left, Vector128<double> right) { throw null; }
+ public static bool TestC<T>(Vector256<T> left, Vector256<T> right) where T : struct { throw null; }
+ public static bool TestNotZAndNotC(Vector128<float> left, Vector128<float> right) { throw null; }
+ public static bool TestNotZAndNotC(Vector128<double> left, Vector128<double> right) { throw null; }
+ public static bool TestNotZAndNotC<T>(Vector256<T> left, Vector256<T> right) where T : struct { throw null; }
+ public static bool TestZ(Vector128<float> left, Vector128<float> right) { throw null; }
+ public static bool TestZ(Vector128<double> left, Vector128<double> right) { throw null; }
+ public static bool TestZ<T>(Vector256<T> left, Vector256<T> right) where T : struct { throw null; }
+ public static Vector256<float> UnpackHigh(Vector256<float> left, Vector256<float> right) { throw null; }
+ public static Vector256<double> UnpackHigh(Vector256<double> left, Vector256<double> right) { throw null; }
+ public static Vector256<float> UnpackLow(Vector256<float> left, Vector256<float> right) { throw null; }
+ public static Vector256<double> UnpackLow(Vector256<double> left, Vector256<double> right) { throw null; }
+ public static Vector256<float> Xor(Vector256<float> left, Vector256<float> right) { throw null; }
+ public static Vector256<double> Xor(Vector256<double> left, Vector256<double> right) { throw null; }
+ public static void ZeroAll() { throw null; }
+ public static void ZeroUpper() { throw null; }
+ public static Vector256<T> ZeroExtendToVector256<T>(Vector128<T> value) where T : struct { throw null; }
+ }
+ public static class Avx2
+ {
+ public static bool IsSupported { get { throw null; } }
+ public static Vector256<byte> Abs(Vector256<sbyte> value) { throw null; }
+ public static Vector256<ushort> Abs(Vector256<short> value) { throw null; }
+ public static Vector256<uint> Abs(Vector256<int> value) { throw null; }
+ public static Vector256<sbyte> Add(Vector256<sbyte> left, Vector256<sbyte> right) { throw null; }
+ public static Vector256<byte> Add(Vector256<byte> left, Vector256<byte> right) { throw null; }
+ public static Vector256<short> Add(Vector256<short> left, Vector256<short> right) { throw null; }
+ public static Vector256<ushort> Add(Vector256<ushort> left, Vector256<ushort> right) { throw null; }
+ public static Vector256<int> Add(Vector256<int> left, Vector256<int> right) { throw null; }
+ public static Vector256<uint> Add(Vector256<uint> left, Vector256<uint> right) { throw null; }
+ public static Vector256<long> Add(Vector256<long> left, Vector256<long> right) { throw null; }
+ public static Vector256<ulong> Add(Vector256<ulong> left, Vector256<ulong> right) { throw null; }
+ public static Vector256<sbyte> AddSaturate(Vector256<sbyte> left, Vector256<sbyte> right) { throw null; }
+ public static Vector256<byte> AddSaturate(Vector256<byte> left, Vector256<byte> right) { throw null; }
+ public static Vector256<short> AddSaturate(Vector256<short> left, Vector256<short> right) { throw null; }
+ public static Vector256<ushort> AddSaturate(Vector256<ushort> left, Vector256<ushort> right) { throw null; }
+ public static Vector256<sbyte> AlignRight(Vector256<sbyte> left, Vector256<sbyte> right, byte mask) { throw null; }
+ public static Vector256<sbyte> And(Vector256<sbyte> left, Vector256<sbyte> right) { throw null; }
+ public static Vector256<byte> And(Vector256<byte> left, Vector256<byte> right) { throw null; }
+ public static Vector256<short> And(Vector256<short> left, Vector256<short> right) { throw null; }
+ public static Vector256<ushort> And(Vector256<ushort> left, Vector256<ushort> right) { throw null; }
+ public static Vector256<int> And(Vector256<int> left, Vector256<int> right) { throw null; }
+ public static Vector256<uint> And(Vector256<uint> left, Vector256<uint> right) { throw null; }
+ public static Vector256<long> And(Vector256<long> left, Vector256<long> right) { throw null; }
+ public static Vector256<ulong> And(Vector256<ulong> left, Vector256<ulong> right) { throw null; }
+ public static Vector256<sbyte> AndNot(Vector256<sbyte> left, Vector256<sbyte> right) { throw null; }
+ public static Vector256<byte> AndNot(Vector256<byte> left, Vector256<byte> right) { throw null; }
+ public static Vector256<short> AndNot(Vector256<short> left, Vector256<short> right) { throw null; }
+ public static Vector256<ushort> AndNot(Vector256<ushort> left, Vector256<ushort> right) { throw null; }
+ public static Vector256<int> AndNot(Vector256<int> left, Vector256<int> right) { throw null; }
+ public static Vector256<uint> AndNot(Vector256<uint> left, Vector256<uint> right) { throw null; }
+ public static Vector256<long> AndNot(Vector256<long> left, Vector256<long> right) { throw null; }
+ public static Vector256<ulong> AndNot(Vector256<ulong> left, Vector256<ulong> right) { throw null; }
+ public static Vector256<byte> Average(Vector256<byte> left, Vector256<byte> right) { throw null; }
+ public static Vector256<ushort> Average(Vector256<ushort> left, Vector256<ushort> right) { throw null; }
+ public static Vector128<int> Blend(Vector128<int> left, Vector128<int> right, byte control) { throw null; }
+ public static Vector128<uint> Blend(Vector128<uint> left, Vector128<uint> right, byte control) { throw null; }
+ public static Vector256<short> Blend(Vector256<short> left, Vector256<short> right, byte control) { throw null; }
+ public static Vector256<ushort> Blend(Vector256<ushort> left, Vector256<ushort> right, byte control) { throw null; }
+ public static Vector256<int> Blend(Vector256<int> left, Vector256<int> right, byte control) { throw null; }
+ public static Vector256<uint> Blend(Vector256<uint> left, Vector256<uint> right, byte control) { throw null; }
+ public static Vector256<sbyte> BlendVariable(Vector256<sbyte> left, Vector256<sbyte> right, Vector256<sbyte> mask) { throw null; }
+ public static Vector256<byte> BlendVariable(Vector256<byte> left, Vector256<byte> right, Vector256<byte> mask) { throw null; }
+ public static Vector128<T> BroadcastElementToVector128<T>(Vector128<T> value) where T : struct { throw null; }
+ public static Vector256<T> BroadcastElementToVector256<T>(Vector128<T> value) where T : struct { throw null; }
+ public static unsafe Vector256<sbyte> BroadcastVector128ToVector256(sbyte* address) { throw null; }
+ public static unsafe Vector256<byte> BroadcastVector128ToVector256(byte* address) { throw null; }
+ public static unsafe Vector256<short> BroadcastVector128ToVector256(short* address) { throw null; }
+ public static unsafe Vector256<ushort> BroadcastVector128ToVector256(ushort* address) { throw null; }
+ public static unsafe Vector256<int> BroadcastVector128ToVector256(int* address) { throw null; }
+ public static unsafe Vector256<uint> BroadcastVector128ToVector256(uint* address) { throw null; }
+ public static unsafe Vector256<long> BroadcastVector128ToVector256(long* address) { throw null; }
+ public static unsafe Vector256<ulong> BroadcastVector128ToVector256(ulong* address) { throw null; }
+ public static Vector256<sbyte> CompareEqual(Vector256<sbyte> left, Vector256<sbyte> right) { throw null; }
+ public static Vector256<byte> CompareEqual(Vector256<byte> left, Vector256<byte> right) { throw null; }
+ public static Vector256<short> CompareEqual(Vector256<short> left, Vector256<short> right) { throw null; }
+ public static Vector256<ushort> CompareEqual(Vector256<ushort> left, Vector256<ushort> right) { throw null; }
+ public static Vector256<int> CompareEqual(Vector256<int> left, Vector256<int> right) { throw null; }
+ public static Vector256<uint> CompareEqual(Vector256<uint> left, Vector256<uint> right) { throw null; }
+ public static Vector256<long> CompareEqual(Vector256<long> left, Vector256<long> right) { throw null; }
+ public static Vector256<ulong> CompareEqual(Vector256<ulong> left, Vector256<ulong> right) { throw null; }
+ public static Vector256<sbyte> CompareGreaterThan(Vector256<sbyte> left, Vector256<sbyte> right) { throw null; }
+ public static Vector256<short> CompareGreaterThan(Vector256<short> left, Vector256<short> right) { throw null; }
+ public static Vector256<int> CompareGreaterThan(Vector256<int> left, Vector256<int> right) { throw null; }
+ public static Vector256<long> CompareGreaterThan(Vector256<long> left, Vector256<long> right) { throw null; }
+ public static Vector256<short> ConvertToVector256Short(Vector128<sbyte> value) { throw null; }
+ public static Vector256<ushort> ConvertToVector256UShort(Vector128<byte> value) { throw null; }
+ public static Vector256<int> ConvertToVector256Int(Vector128<sbyte> value) { throw null; }
+ public static Vector256<int> ConvertToVector256Int(Vector128<short> value) { throw null; }
+ public static Vector256<uint> ConvertToVector256UInt(Vector128<byte> value) { throw null; }
+ public static Vector256<uint> ConvertToVector256UInt(Vector128<ushort> value) { throw null; }
+ public static Vector256<long> ConvertToVector256Long(Vector128<sbyte> value) { throw null; }
+ public static Vector256<long> ConvertToVector256Long(Vector128<short> value) { throw null; }
+ public static Vector256<long> ConvertToVector256Long(Vector128<int> value) { throw null; }
+ public static Vector256<ulong> ConvertToVector256ULong(Vector128<byte> value) { throw null; }
+ public static Vector256<ulong> ConvertToVector256ULong(Vector128<ushort> value) { throw null; }
+ public static Vector256<ulong> ConvertToVector256ULong(Vector128<uint> value) { throw null; }
+ public static Vector128<sbyte> ExtractVector128(Vector256<sbyte> value, byte index) { throw null; }
+ public static unsafe void ExtractVector128(sbyte* address, Vector256<sbyte> value, byte index) { throw null; }
+ public static Vector128<byte> ExtractVector128(Vector256<byte> value, byte index) { throw null; }
+ public static unsafe void ExtractVector128(byte* address, Vector256<byte> value, byte index) { throw null; }
+ public static Vector128<short> ExtractVector128(Vector256<short> value, byte index) { throw null; }
+ public static unsafe void ExtractVector128(short* address, Vector256<short> value, byte index) { throw null; }
+ public static Vector128<ushort> ExtractVector128(Vector256<ushort> value, byte index) { throw null; }
+ public static unsafe void ExtractVector128(ushort* address, Vector256<ushort> value, byte index) { throw null; }
+ public static Vector128<int> ExtractVector128(Vector256<int> value, byte index) { throw null; }
+ public static unsafe void ExtractVector128(int* address, Vector256<int> value, byte index) { throw null; }
+ public static Vector128<uint> ExtractVector128(Vector256<uint> value, byte index) { throw null; }
+ public static unsafe void ExtractVector128(uint* address, Vector256<uint> value, byte index) { throw null; }
+ public static Vector128<long> ExtractVector128(Vector256<long> value, byte index) { throw null; }
+ public static unsafe void ExtractVector128(long* address, Vector256<long> value, byte index) { throw null; }
+ public static Vector128<ulong> ExtractVector128(Vector256<ulong> value, byte index) { throw null; }
+ public static unsafe void ExtractVector128(ulong* address, Vector256<ulong> value, byte index) { throw null; }
+ public static unsafe Vector128<int> GatherVector128(int* baseAddress, Vector128<int> index, byte scale) { throw null; }
+ public static unsafe Vector128<uint> GatherVector128(uint* baseAddress, Vector128<int> index, byte scale) { throw null; }
+ public static unsafe Vector128<long> GatherVector128(long* baseAddress, Vector128<int> index, byte scale) { throw null; }
+ public static unsafe Vector128<ulong> GatherVector128(ulong* baseAddress, Vector128<int> index, byte scale) { throw null; }
+ public static unsafe Vector128<float> GatherVector128(float* baseAddress, Vector128<int> index, byte scale) { throw null; }
+ public static unsafe Vector128<double> GatherVector128(double* baseAddress, Vector128<int> index, byte scale) { throw null; }
+ public static unsafe Vector128<int> GatherVector128(int* baseAddress, Vector128<long> index, byte scale) { throw null; }
+ public static unsafe Vector128<uint> GatherVector128(uint* baseAddress, Vector128<long> index, byte scale) { throw null; }
+ public static unsafe Vector128<long> GatherVector128(long* baseAddress, Vector128<long> index, byte scale) { throw null; }
+ public static unsafe Vector128<ulong> GatherVector128(ulong* baseAddress, Vector128<long> index, byte scale) { throw null; }
+ public static unsafe Vector128<float> GatherVector128(float* baseAddress, Vector128<long> index, byte scale) { throw null; }
+ public static unsafe Vector128<double> GatherVector128(double* baseAddress, Vector128<long> index, byte scale) { throw null; }
+ public static unsafe Vector256<int> GatherVector256(int* baseAddress, Vector256<int> index, byte scale) { throw null; }
+ public static unsafe Vector256<uint> GatherVector256(uint* baseAddress, Vector256<int> index, byte scale) { throw null; }
+ public static unsafe Vector256<long> GatherVector256(long* baseAddress, Vector128<int> index, byte scale) { throw null; }
+ public static unsafe Vector256<ulong> GatherVector256(ulong* baseAddress, Vector128<int> index, byte scale) { throw null; }
+ public static unsafe Vector256<float> GatherVector256(float* baseAddress, Vector256<int> index, byte scale) { throw null; }
+ public static unsafe Vector256<double> GatherVector256(double* baseAddress, Vector128<int> index, byte scale) { throw null; }
+ public static unsafe Vector128<int> GatherVector128(int* baseAddress, Vector256<long> index, byte scale) { throw null; }
+ public static unsafe Vector128<uint> GatherVector128(uint* baseAddress, Vector256<long> index, byte scale) { throw null; }
+ public static unsafe Vector256<long> GatherVector256(long* baseAddress, Vector256<long> index, byte scale) { throw null; }
+ public static unsafe Vector256<ulong> GatherVector256(ulong* baseAddress, Vector256<long> index, byte scale) { throw null; }
+ public static unsafe Vector128<float> GatherVector128(float* baseAddress, Vector256<long> index, byte scale) { throw null; }
+ public static unsafe Vector256<double> GatherVector256(double* baseAddress, Vector256<long> index, byte scale) { throw null; }
+ public static unsafe Vector128<int> GatherMaskVector128(Vector128<int> source, int* baseAddress, Vector128<int> index, Vector128<int> mask, byte scale) { throw null; }
+ public static unsafe Vector128<uint> GatherMaskVector128(Vector128<uint> source, uint* baseAddress, Vector128<int> index, Vector128<uint> mask, byte scale) { throw null; }
+ public static unsafe Vector128<long> GatherMaskVector128(Vector128<long> source, long* baseAddress, Vector128<int> index, Vector128<long> mask, byte scale) { throw null; }
+ public static unsafe Vector128<ulong> GatherMaskVector128(Vector128<ulong> source, ulong* baseAddress, Vector128<int> index, Vector128<ulong> mask, byte scale) { throw null; }
+ public static unsafe Vector128<float> GatherMaskVector128(Vector128<float> source, float* baseAddress, Vector128<int> index, Vector128<float> mask, byte scale) { throw null; }
+ public static unsafe Vector128<double> GatherMaskVector128(Vector128<double> source, double* baseAddress, Vector128<int> index, Vector128<double> mask, byte scale) { throw null; }
+ public static unsafe Vector128<int> GatherMaskVector128(Vector128<int> source, int* baseAddress, Vector128<long> index, Vector128<int> mask, byte scale) { throw null; }
+ public static unsafe Vector128<uint> GatherMaskVector128(Vector128<uint> source, uint* baseAddress, Vector128<long> index, Vector128<uint> mask, byte scale) { throw null; }
+ public static unsafe Vector128<long> GatherMaskVector128(Vector128<long> source, long* baseAddress, Vector128<long> index, Vector128<long> mask, byte scale) { throw null; }
+ public static unsafe Vector128<ulong> GatherMaskVector128(Vector128<ulong> source, ulong* baseAddress, Vector128<long> index, Vector128<ulong> mask, byte scale) { throw null; }
+ public static unsafe Vector128<float> GatherMaskVector128(Vector128<float> source, float* baseAddress, Vector128<long> index, Vector128<float> mask, byte scale) { throw null; }
+ public static unsafe Vector128<double> GatherMaskVector128(Vector128<double> source, double* baseAddress, Vector128<long> index, Vector128<double> mask, byte scale) { throw null; }
+ public static unsafe Vector256<int> GatherMaskVector256(Vector256<int> source, int* baseAddress, Vector256<int> index, Vector256<int> mask, byte scale) { throw null; }
+ public static unsafe Vector256<uint> GatherMaskVector256(Vector256<uint> source, uint* baseAddress, Vector256<int> index, Vector256<uint> mask, byte scale) { throw null; }
+ public static unsafe Vector256<long> GatherMaskVector256(Vector256<long> source, long* baseAddress, Vector128<int> index, Vector256<long> mask, byte scale) { throw null; }
+ public static unsafe Vector256<ulong> GatherMaskVector256(Vector256<ulong> source, ulong* baseAddress, Vector128<int> index, Vector256<ulong> mask, byte scale) { throw null; }
+ public static unsafe Vector256<float> GatherMaskVector256(Vector256<float> source, float* baseAddress, Vector256<int> index, Vector256<float> mask, byte scale) { throw null; }
+ public static unsafe Vector256<double> GatherMaskVector256(Vector256<double> source, double* baseAddress, Vector128<int> index, Vector256<double> mask, byte scale) { throw null; }
+ public static unsafe Vector128<int> GatherMaskVector128(Vector128<int> source, int* baseAddress, Vector256<long> index, Vector128<int> mask, byte scale) { throw null; }
+ public static unsafe Vector128<uint> GatherMaskVector128(Vector128<uint> source, uint* baseAddress, Vector256<long> index, Vector128<uint> mask, byte scale) { throw null; }
+ public static unsafe Vector256<long> GatherMaskVector256(Vector256<long> source, long* baseAddress, Vector256<long> index, Vector256<long> mask, byte scale) { throw null; }
+ public static unsafe Vector256<ulong> GatherMaskVector256(Vector256<ulong> source, ulong* baseAddress, Vector256<long> index, Vector256<ulong> mask, byte scale) { throw null; }
+ public static unsafe Vector128<float> GatherMaskVector128(Vector128<float> source, float* baseAddress, Vector256<long> index, Vector128<float> mask, byte scale) { throw null; }
+ public static unsafe Vector256<double> GatherMaskVector256(Vector256<double> source, double* baseAddress, Vector256<long> index, Vector256<double> mask, byte scale) { throw null; }
+ public static Vector256<short> HorizontalAdd(Vector256<short> left, Vector256<short> right) { throw null; }
+ public static Vector256<int> HorizontalAdd(Vector256<int> left, Vector256<int> right) { throw null; }
+ public static Vector256<short> HorizontalAddSaturate(Vector256<short> left, Vector256<short> right) { throw null; }
+ public static Vector256<short> HorizontalSubtract(Vector256<short> left, Vector256<short> right) { throw null; }
+ public static Vector256<int> HorizontalSubtract(Vector256<int> left, Vector256<int> right) { throw null; }
+ public static Vector256<short> HorizontalSubtractSaturate(Vector256<short> left, Vector256<short> right) { throw null; }
+ public static Vector256<sbyte> Insert(Vector256<sbyte> value, Vector128<sbyte> data, byte index) { throw null; }
+ public static unsafe Vector256<sbyte> Insert(Vector256<sbyte> value, sbyte* address, byte index) { throw null; }
+ public static Vector256<byte> Insert(Vector256<byte> value, Vector128<byte> data, byte index) { throw null; }
+ public static unsafe Vector256<byte> Insert(Vector256<byte> value, byte* address, byte index) { throw null; }
+ public static Vector256<short> Insert(Vector256<short> value, Vector128<short> data, byte index) { throw null; }
+ public static unsafe Vector256<short> Insert(Vector256<short> value, short* address, byte index) { throw null; }
+ public static Vector256<ushort> Insert(Vector256<ushort> value, Vector128<ushort> data, byte index) { throw null; }
+ public static unsafe Vector256<ushort> Insert(Vector256<ushort> value, ushort* address, byte index) { throw null; }
+ public static Vector256<int> Insert(Vector256<int> value, Vector128<int> data, byte index) { throw null; }
+ public static unsafe Vector256<int> Insert(Vector256<int> value, int* address, byte index) { throw null; }
+ public static Vector256<uint> Insert(Vector256<uint> value, Vector128<uint> data, byte index) { throw null; }
+ public static unsafe Vector256<uint> Insert(Vector256<uint> value, uint* address, byte index) { throw null; }
+ public static Vector256<long> Insert(Vector256<long> value, Vector128<long> data, byte index) { throw null; }
+ public static unsafe Vector256<long> Insert(Vector256<long> value, long* address, byte index) { throw null; }
+ public static Vector256<ulong> Insert(Vector256<ulong> value, Vector128<ulong> data, byte index) { throw null; }
+ public static unsafe Vector256<ulong> Insert(Vector256<ulong> value, ulong* address, byte index) { throw null; }
+ public static unsafe Vector128<int> MaskLoad(int* address, Vector128<int> mask) { throw null; }
+ public static unsafe Vector128<uint> MaskLoad(uint* address, Vector128<uint> mask) { throw null; }
+ public static unsafe Vector128<long> MaskLoad(long* address, Vector128<long> mask) { throw null; }
+ public static unsafe Vector128<ulong> MaskLoad(ulong* address, Vector128<ulong> mask) { throw null; }
+ public static unsafe Vector256<int> MaskLoad(int* address, Vector256<int> mask) { throw null; }
+ public static unsafe Vector256<uint> MaskLoad(uint* address, Vector256<uint> mask) { throw null; }
+ public static unsafe Vector256<long> MaskLoad(long* address, Vector256<long> mask) { throw null; }
+ public static unsafe Vector256<ulong> MaskLoad(ulong* address, Vector256<ulong> mask) { throw null; }
+ public static unsafe void MaskStore(int* address, Vector128<int> mask, Vector128<int> source) { throw null; }
+ public static unsafe void MaskStore(uint* address, Vector128<uint> mask, Vector128<uint> source) { throw null; }
+ public static unsafe void MaskStore(long* address, Vector128<long> mask, Vector128<long> source) { throw null; }
+ public static unsafe void MaskStore(ulong* address, Vector128<ulong> mask, Vector128<ulong> source) { throw null; }
+ public static unsafe void MaskStore(int* address, Vector256<int> mask, Vector256<int> source) { throw null; }
+ public static unsafe void MaskStore(uint* address, Vector256<uint> mask, Vector256<uint> source) { throw null; }
+ public static unsafe void MaskStore(long* address, Vector256<long> mask, Vector256<long> source) { throw null; }
+ public static unsafe void MaskStore(ulong* address, Vector256<ulong> mask, Vector256<ulong> source) { throw null; }
+ public static Vector256<int> MultiplyAddAdjacent(Vector256<short> left, Vector256<short> right) { throw null; }
+ public static Vector256<short> MultiplyAddAdjacent(Vector256<byte> left, Vector256<sbyte> right) { throw null; }
+ public static Vector256<sbyte> Max(Vector256<sbyte> left, Vector256<sbyte> right) { throw null; }
+ public static Vector256<byte> Max(Vector256<byte> left, Vector256<short> right) { throw null; }
+ public static Vector256<short> Max(Vector256<short> left, Vector256<short> right) { throw null; }
+ public static Vector256<ushort> Max(Vector256<ushort> left, Vector256<ushort> right) { throw null; }
+ public static Vector256<int> Max(Vector256<int> left, Vector256<int> right) { throw null; }
+ public static Vector256<uint> Max(Vector256<uint> left, Vector256<uint> right) { throw null; }
+ public static Vector256<sbyte> Min(Vector256<sbyte> left, Vector256<sbyte> right) { throw null; }
+ public static Vector256<byte> Min(Vector256<byte> left, Vector256<byte> right) { throw null; }
+ public static Vector256<short> Min(Vector256<short> left, Vector256<short> right) { throw null; }
+ public static Vector256<ushort> Min(Vector256<ushort> left, Vector256<ushort> right) { throw null; }
+ public static Vector256<int> Min(Vector256<int> left, Vector256<int> right) { throw null; }
+ public static Vector256<uint> Min(Vector256<uint> left, Vector256<uint> right) { throw null; }
+ public static int MoveMask(Vector256<sbyte> value) { throw null; }
+ public static int MoveMask(Vector256<byte> value) { throw null; }
+ public static Vector256<ushort> MultipleSumAbsoluteDifferences(Vector256<byte> left, Vector256<byte> right, byte mask) { throw null; }
+ public static Vector256<long> Multiply(Vector256<int> left, Vector256<int> right) { throw null; }
+ public static Vector256<ulong> Multiply(Vector256<uint> left, Vector256<uint> right) { throw null; }
+ public static Vector256<short> MultiplyHigh(Vector256<short> left, Vector256<short> right) { throw null; }
+ public static Vector256<ushort> MultiplyHigh(Vector256<ushort> left, Vector256<ushort> right) { throw null; }
+ public static Vector256<short> MultiplyHighRoundScale(Vector256<short> left, Vector256<short> right) { throw null; }
+ public static Vector256<short> MultiplyLow(Vector256<short> left, Vector256<short> right) { throw null; }
+ public static Vector256<int> MultiplyLow(Vector256<int> left, Vector256<int> right) { throw null; }
+ public static Vector256<sbyte> Or(Vector256<sbyte> left, Vector256<sbyte> right) { throw null; }
+ public static Vector256<byte> Or(Vector256<byte> left, Vector256<byte> right) { throw null; }
+ public static Vector256<short> Or(Vector256<short> left, Vector256<short> right) { throw null; }
+ public static Vector256<ushort> Or(Vector256<ushort> left, Vector256<ushort> right) { throw null; }
+ public static Vector256<int> Or(Vector256<int> left, Vector256<int> right) { throw null; }
+ public static Vector256<uint> Or(Vector256<uint> left, Vector256<uint> right) { throw null; }
+ public static Vector256<long> Or(Vector256<long> left, Vector256<long> right) { throw null; }
+ public static Vector256<ulong> Or(Vector256<ulong> left, Vector256<ulong> right) { throw null; }
+ public static Vector256<sbyte> PackSignedSaturate(Vector256<short> left, Vector256<short> right) { throw null; }
+ public static Vector256<short> PackSignedSaturate(Vector256<int> left, Vector256<int> right) { throw null; }
+ public static Vector256<byte> PackUnsignedSaturate(Vector256<short> left, Vector256<short> right) { throw null; }
+ public static Vector256<ushort> PackUnsignedSaturate(Vector256<int> left, Vector256<int> right) { throw null; }
+ public static Vector256<sbyte> Permute2x128(Vector256<sbyte> left, Vector256<sbyte> right, byte control) { throw null; }
+ public static Vector256<byte> Permute2x128(Vector256<byte> left, Vector256<byte> right, byte control) { throw null; }
+ public static Vector256<short> Permute2x128(Vector256<short> left, Vector256<short> right, byte control) { throw null; }
+ public static Vector256<ushort> Permute2x128(Vector256<ushort> left, Vector256<ushort> right, byte control) { throw null; }
+ public static Vector256<int> Permute2x128(Vector256<int> left, Vector256<int> right, byte control) { throw null; }
+ public static Vector256<uint> Permute2x128(Vector256<uint> left, Vector256<uint> right, byte control) { throw null; }
+ public static Vector256<long> Permute2x128(Vector256<long> left, Vector256<long> right, byte control) { throw null; }
+ public static Vector256<ulong> Permute2x128(Vector256<ulong> left, Vector256<ulong> right, byte control) { throw null; }
+ public static Vector256<long> Permute4x64(Vector256<long> value, byte control) { throw null; }
+ public static Vector256<ulong> Permute4x64(Vector256<ulong> value, byte control) { throw null; }
+ public static Vector256<double> Permute4x64(Vector256<double> value, byte control) { throw null; }
+ public static Vector256<int> PermuteVar8x32(Vector256<int> left, Vector256<int> mask) { throw null; }
+ public static Vector256<uint> PermuteVar8x32(Vector256<uint> left, Vector256<uint> mask) { throw null; }
+ public static Vector256<float> PermuteVar8x32(Vector256<float> left, Vector256<float> mask) { throw null; }
+ public static Vector256<short> ShiftLeftLogical(Vector256<short> value, byte count) { throw null; }
+ public static Vector256<ushort> ShiftLeftLogical(Vector256<ushort> value, byte count) { throw null; }
+ public static Vector256<int> ShiftLeftLogical(Vector256<int> value, byte count) { throw null; }
+ public static Vector256<uint> ShiftLeftLogical(Vector256<uint> value, byte count) { throw null; }
+ public static Vector256<long> ShiftLeftLogical(Vector256<long> value, byte count) { throw null; }
+ public static Vector256<ulong> ShiftLeftLogical(Vector256<ulong> value, byte count) { throw null; }
+ public static Vector256<sbyte> ShiftLeftLogical128BitLane(Vector256<sbyte> value, byte numBytes) { throw null; }
+ public static Vector256<byte> ShiftLeftLogical128BitLane(Vector256<byte> value, byte numBytes) { throw null; }
+ public static Vector256<short> ShiftLeftLogical128BitLane(Vector256<short> value, byte numBytes) { throw null; }
+ public static Vector256<ushort> ShiftLeftLogical128BitLane(Vector256<ushort> value, byte numBytes) { throw null; }
+ public static Vector256<int> ShiftLeftLogical128BitLane(Vector256<int> value, byte numBytes) { throw null; }
+ public static Vector256<uint> ShiftLeftLogical128BitLane(Vector256<uint> value, byte numBytes) { throw null; }
+ public static Vector256<long> ShiftLeftLogical128BitLane(Vector256<long> value, byte numBytes) { throw null; }
+ public static Vector256<ulong> ShiftLeftLogical128BitLane(Vector256<ulong> value, byte numBytes) { throw null; }
+ public static Vector256<int> ShiftLeftLogicalVariable(Vector256<int> value, Vector256<uint> count) { throw null; }
+ public static Vector256<uint> ShiftLeftLogicalVariable(Vector256<uint> value, Vector256<uint> count) { throw null; }
+ public static Vector256<long> ShiftLeftLogicalVariable(Vector256<long> value, Vector256<ulong> count) { throw null; }
+ public static Vector256<ulong> ShiftLeftLogicalVariable(Vector256<ulong> value, Vector256<ulong> count) { throw null; }
+ public static Vector256<short> ShiftRightArithmetic(Vector256<short> value, byte count) { throw null; }
+ public static Vector256<int> ShiftRightArithmetic(Vector256<int> value, byte count) { throw null; }
+ public static Vector256<int> ShiftRightArithmeticVariable(Vector256<int> value, Vector256<uint> count) { throw null; }
+ public static Vector256<short> ShiftRightLogical(Vector256<short> value, byte count) { throw null; }
+ public static Vector256<ushort> ShiftRightLogical(Vector256<ushort> value, byte count) { throw null; }
+ public static Vector256<int> ShiftRightLogical(Vector256<int> value, byte count) { throw null; }
+ public static Vector256<uint> ShiftRightLogical(Vector256<uint> value, byte count) { throw null; }
+ public static Vector256<long> ShiftRightLogical(Vector256<long> value, byte count) { throw null; }
+ public static Vector256<ulong> ShiftRightLogical(Vector256<ulong> value, byte count) { throw null; }
+ public static Vector256<sbyte> ShiftRightLogical128BitLane(Vector256<sbyte> value, byte numBytes) { throw null; }
+ public static Vector256<byte> ShiftRightLogical128BitLane(Vector256<byte> value, byte numBytes) { throw null; }
+ public static Vector256<short> ShiftRightLogical128BitLane(Vector256<short> value, byte numBytes) { throw null; }
+ public static Vector256<ushort> ShiftRightLogical128BitLane(Vector256<ushort> value, byte numBytes) { throw null; }
+ public static Vector256<int> ShiftRightLogical128BitLane(Vector256<int> value, byte numBytes) { throw null; }
+ public static Vector256<uint> ShiftRightLogical128BitLane(Vector256<uint> value, byte numBytes) { throw null; }
+ public static Vector256<long> ShiftRightLogical128BitLane(Vector256<long> value, byte numBytes) { throw null; }
+ public static Vector256<ulong> ShiftRightLogical128BitLane(Vector256<ulong> value, byte numBytes) { throw null; }
+ public static Vector256<int> ShiftRightLogicalVariable(Vector256<int> value, Vector256<uint> count) { throw null; }
+ public static Vector256<uint> ShiftRightLogicalVariable(Vector256<uint> value, Vector256<uint> count) { throw null; }
+ public static Vector256<long> ShiftRightLogicalVariable(Vector256<long> value, Vector256<ulong> count) { throw null; }
+ public static Vector256<ulong> ShiftRightLogicalVariable(Vector256<ulong> value, Vector256<ulong> count) { throw null; }
+ public static Vector256<sbyte> Shuffle(Vector256<sbyte> value, Vector256<sbyte> mask) { throw null; }
+ public static Vector256<byte> Shuffle(Vector256<byte> value, Vector256<byte> mask) { throw null; }
+ public static Vector256<int> Shuffle(Vector256<int> value, byte control) { throw null; }
+ public static Vector256<uint> Shuffle(Vector256<uint> value, byte control) { throw null; }
+ public static Vector256<short> ShuffleHigh(Vector256<short> value, byte control) { throw null; }
+ public static Vector256<ushort> ShuffleHigh(Vector256<ushort> value, byte control) { throw null; }
+ public static Vector256<short> ShuffleLow(Vector256<short> value, byte control) { throw null; }
+ public static Vector256<ushort> ShuffleLow(Vector256<ushort> value, byte control) { throw null; }
+ public static Vector256<sbyte> Sign(Vector256<sbyte> left, Vector256<sbyte> right) { throw null; }
+ public static Vector256<short> Sign(Vector256<short> left, Vector256<short> right) { throw null; }
+ public static Vector256<int> Sign(Vector256<int> left, Vector256<int> right) { throw null; }
+ public static Vector256<sbyte> Subtract(Vector256<sbyte> left, Vector256<sbyte> right) { throw null; }
+ public static Vector256<byte> Subtract(Vector256<byte> left, Vector256<byte> right) { throw null; }
+ public static Vector256<short> Subtract(Vector256<short> left, Vector256<short> right) { throw null; }
+ public static Vector256<ushort> Subtract(Vector256<ushort> left, Vector256<ushort> right) { throw null; }
+ public static Vector256<int> Subtract(Vector256<int> left, Vector256<int> right) { throw null; }
+ public static Vector256<uint> Subtract(Vector256<uint> left, Vector256<uint> right) { throw null; }
+ public static Vector256<long> Subtract(Vector256<long> left, Vector256<long> right) { throw null; }
+ public static Vector256<ulong> Subtract(Vector256<ulong> left, Vector256<ulong> right) { throw null; }
+ public static Vector256<sbyte> SubtractSaturate(Vector256<sbyte> left, Vector256<sbyte> right) { throw null; }
+ public static Vector256<short> SubtractSaturate(Vector256<short> left, Vector256<short> right) { throw null; }
+ public static Vector256<byte> SubtractSaturate(Vector256<byte> left, Vector256<byte> right) { throw null; }
+ public static Vector256<ushort> SubtractSaturate(Vector256<ushort> left, Vector256<ushort> right) { throw null; }
+ public static Vector256<ulong> SumAbsoluteDifferences(Vector256<byte> left, Vector256<byte> right) { throw null; }
+ public static Vector256<sbyte> UnpackHigh(Vector256<sbyte> left, Vector256<sbyte> right) { throw null; }
+ public static Vector256<byte> UnpackHigh(Vector256<byte> left, Vector256<byte> right) { throw null; }
+ public static Vector256<short> UnpackHigh(Vector256<short> left, Vector256<short> right) { throw null; }
+ public static Vector256<ushort> UnpackHigh(Vector256<ushort> left, Vector256<ushort> right) { throw null; }
+ public static Vector256<int> UnpackHigh(Vector256<int> left, Vector256<int> right) { throw null; }
+ public static Vector256<uint> UnpackHigh(Vector256<uint> left, Vector256<uint> right) { throw null; }
+ public static Vector256<long> UnpackHigh(Vector256<long> left, Vector256<long> right) { throw null; }
+ public static Vector256<ulong> UnpackHigh(Vector256<ulong> left, Vector256<ulong> right) { throw null; }
+ public static Vector256<sbyte> UnpackLow(Vector256<sbyte> left, Vector256<sbyte> right) { throw null; }
+ public static Vector256<byte> UnpackLow(Vector256<byte> left, Vector256<byte> right) { throw null; }
+ public static Vector256<short> UnpackLow(Vector256<short> left, Vector256<short> right) { throw null; }
+ public static Vector256<ushort> UnpackLow(Vector256<ushort> left, Vector256<ushort> right) { throw null; }
+ public static Vector256<int> UnpackLow(Vector256<int> left, Vector256<int> right) { throw null; }
+ public static Vector256<uint> UnpackLow(Vector256<uint> left, Vector256<uint> right) { throw null; }
+ public static Vector256<long> UnpackLow(Vector256<long> left, Vector256<long> right) { throw null; }
+ public static Vector256<ulong> UnpackLow(Vector256<ulong> left, Vector256<ulong> right) { throw null; }
+ public static Vector256<sbyte> Xor(Vector256<sbyte> left, Vector256<sbyte> right) { throw null; }
+ public static Vector256<byte> Xor(Vector256<byte> left, Vector256<byte> right) { throw null; }
+ public static Vector256<short> Xor(Vector256<short> left, Vector256<short> right) { throw null; }
+ public static Vector256<ushort> Xor(Vector256<ushort> left, Vector256<ushort> right) { throw null; }
+ public static Vector256<int> Xor(Vector256<int> left, Vector256<int> right) { throw null; }
+ public static Vector256<uint> Xor(Vector256<uint> left, Vector256<uint> right) { throw null; }
+ public static Vector256<long> Xor(Vector256<long> left, Vector256<long> right) { throw null; }
+ public static Vector256<ulong> Xor(Vector256<ulong> left, Vector256<ulong> right) { throw null; }
+ }
+ public static class Bmi1
+ {
+ public static bool IsSupported { get { throw null; } }
+ public static uint AndNot(uint left, uint right) { throw null; }
+ public static ulong AndNot(ulong left, ulong right) { throw null; }
+ public static uint BitFieldExtract(uint value, uint start, uint length) { throw null; }
+ public static ulong BitFieldExtract(ulong value, ulong start, ulong length) { throw null; }
+ public static uint BitFieldExtract(uint value, uint control) { throw null; }
+ public static ulong BitFieldExtract(ulong value, ulong control) { throw null; }
+ public static uint ExtractLowestSetBit(uint value) { throw null; }
+ public static ulong ExtractLowestSetBit(ulong value) { throw null; }
+ public static uint GetMaskUptoLowestSetBit(uint value) { throw null; }
+ public static ulong GetMaskUptoLowestSetBit(ulong value) { throw null; }
+ public static uint ResetLowestSetBit(uint value) { throw null; }
+ public static ulong ResetLowestSetBit(ulong value) { throw null; }
+ public static uint TrailingZeroCount(uint value) { throw null; }
+ public static ulong TrailingZeroCount(ulong value) { throw null; }
+ }
+ public static class Bmi2
+ {
+ public static bool IsSupported { get { throw null; } }
+ public static uint ZeroHighBits(uint value, uint index) { throw null; }
+ public static ulong ZeroHighBits(ulong value, ulong index) { throw null; }
+ public static unsafe uint MultiplyNoFlags(uint left, uint right, uint* high) { throw null; }
+ public static unsafe ulong MultiplyNoFlags(ulong left, ulong right, ulong* high) { throw null; }
+ public static uint ParallelBitDeposit(uint value, uint mask) { throw null; }
+ public static ulong ParallelBitDeposit(ulong value, ulong mask) { throw null; }
+ public static uint ParallelBitExtract(uint value, uint mask) { throw null; }
+ public static ulong ParallelBitExtract(ulong value, ulong mask) { throw null; }
+ }
+ public enum FloatComparisonMode : byte
+ {
+ EqualOrderedNonSignaling = 0,
+ LessThanOrderedSignaling = 1,
+ LessThanOrEqualOrderedSignaling = 2,
+ UnorderedNonSignaling = 3,
+ NotEqualUnorderedNonSignaling = 4,
+ NotLessThanUnorderedSignaling = 5,
+ NotLessThanOrEqualUnorderedSignaling = 6,
+ OrderedNonSignaling = 7,
+ EqualUnorderedNonSignaling = 8,
+ NotGreaterThanOrEqualUnorderedSignaling = 9,
+ NotGreaterThanUnorderedSignaling = 10,
+ FalseOrderedNonSignaling = 11,
+ NotEqualOrderedNonSignaling = 12,
+ GreaterThanOrEqualOrderedSignaling = 13,
+ GreaterThanOrderedSignaling = 14,
+ TrueUnorderedNonSignaling = 15,
+ EqualOrderedSignaling = 16,
+ LessThanOrderedNonSignaling = 17,
+ LessThanOrEqualOrderedNonSignaling = 18,
+ UnorderedSignaling = 19,
+ NotEqualUnorderedSignaling = 20,
+ NotLessThanUnorderedNonSignaling = 21,
+ NotLessThanOrEqualUnorderedNonSignaling = 22,
+ OrderedSignaling = 23,
+ EqualUnorderedSignaling = 24,
+ NotGreaterThanOrEqualUnorderedNonSignaling = 25,
+ NotGreaterThanUnorderedNonSignaling = 26,
+ FalseOrderedSignaling = 27,
+ NotEqualOrderedSignaling = 28,
+ GreaterThanOrEqualOrderedNonSignaling = 29,
+ GreaterThanOrderedNonSignaling = 30,
+ TrueUnorderedSignaling = 31,
+ }
+ public enum StringComparisonMode : byte {
+ EqualAny = 0x00,
+ Ranges = 0x04,
+ EqualEach = 0x08,
+ EqualOrdered = 0x0c,
+ NegativePolarity = 0x10,
+ MaskedNegativePolarity = 0x30,
+ LeastSignificant = 0x00,
+ MostSignificant = 0x40,
+ }
+ public enum ResultsFlag : byte {
+ CFlag = 0,
+ NotCFlagAndNotZFlag = 1,
+ OFlag = 2,
+ SFlag = 3,
+ ZFlag = 4,
+ }
+ public static class Fma
+ {
+ public static bool IsSupported { get { throw null; } }
+ public static Vector128<float> MultiplyAdd(Vector128<float> a, Vector128<float> b, Vector128<float> c) { throw null; }
+ public static Vector128<double> MultiplyAdd(Vector128<double> a, Vector128<double> b, Vector128<double> c) { throw null; }
+ public static Vector256<float> MultiplyAdd(Vector256<float> a, Vector256<float> b, Vector256<float> c) { throw null; }
+ public static Vector256<double> MultiplyAdd(Vector256<double> a, Vector256<double> b, Vector256<double> c) { throw null; }
+ public static Vector128<float> MultiplyAddSubtract(Vector128<float> a, Vector128<float> b, Vector128<float> c) { throw null; }
+ public static Vector128<double> MultiplyAddSubtract(Vector128<double> a, Vector128<double> b, Vector128<double> c) { throw null; }
+ public static Vector256<float> MultiplyAddSubtract(Vector256<float> a, Vector256<float> b, Vector256<float> c) { throw null; }
+ public static Vector256<double> MultiplyAddSubtract(Vector256<double> a, Vector256<double> b, Vector256<double> c) { throw null; }
+ public static Vector128<float> MultiplySubtract(Vector128<float> a, Vector128<float> b, Vector128<float> c) { throw null; }
+ public static Vector128<double> MultiplySubtract(Vector128<double> a, Vector128<double> b, Vector128<double> c) { throw null; }
+ public static Vector256<float> MultiplySubtract(Vector256<float> a, Vector256<float> b, Vector256<float> c) { throw null; }
+ public static Vector256<double> MultiplySubtract(Vector256<double> a, Vector256<double> b, Vector256<double> c) { throw null; }
+ public static Vector128<float> MultiplySubtractAdd(Vector128<float> a, Vector128<float> b, Vector128<float> c) { throw null; }
+ public static Vector128<double> MultiplySubtractAdd(Vector128<double> a, Vector128<double> b, Vector128<double> c) { throw null; }
+ public static Vector256<float> MultiplySubtractAdd(Vector256<float> a, Vector256<float> b, Vector256<float> c) { throw null; }
+ public static Vector256<double> MultiplySubtractAdd(Vector256<double> a, Vector256<double> b, Vector256<double> c) { throw null; }
+ public static Vector128<float> MultiplyAddNegated(Vector128<float> a, Vector128<float> b, Vector128<float> c) { throw null; }
+ public static Vector128<double> MultiplyAddNegated(Vector128<double> a, Vector128<double> b, Vector128<double> c) { throw null; }
+ public static Vector256<float> MultiplyAddNegated(Vector256<float> a, Vector256<float> b, Vector256<float> c) { throw null; }
+ public static Vector256<double> MultiplyAddNegated(Vector256<double> a, Vector256<double> b, Vector256<double> c) { throw null; }
+ public static Vector128<float> MultiplySubtractNegated(Vector128<float> a, Vector128<float> b, Vector128<float> c) { throw null; }
+ public static Vector128<double> MultiplySubtractNegated(Vector128<double> a, Vector128<double> b, Vector128<double> c) { throw null; }
+ public static Vector256<float> MultiplySubtractNegated(Vector256<float> a, Vector256<float> b, Vector256<float> c) { throw null; }
+ public static Vector256<double> MultiplySubtractNegated(Vector256<double> a, Vector256<double> b, Vector256<double> c) { throw null; }
+ }
+ public static class Lzcnt
+ {
+ public static bool IsSupported { get { throw null; } }
+ public static uint LeadingZeroCount(uint value) { throw null; }
+ public static ulong LeadingZeroCount(ulong value) { throw null; }
+ }
+ public static class Pclmulqdq
+ {
+ public static bool IsSupported { get { throw null; } }
+ public static Vector128<long> CarryLessMultiply(Vector128<long> left, Vector128<long> right, byte control) { throw null; }
+ public static Vector128<ulong> CarryLessMultiply(Vector128<ulong> left, Vector128<ulong> right, byte control) { throw null; }
+ }
+ public static class Popcnt
+ {
+ public static bool IsSupported { get { throw null; } }
+ public static int PopCount(uint value) { throw null; }
+ public static long PopCount(ulong value) { throw null; }
+ }
+ public static class Sse
+ {
+ public static bool IsSupported { get { return false; } }
+ public static Vector128<float> Add(Vector128<float> left, Vector128<float> right) { throw new NotImplementedException(); }
+ public static Vector128<float> And(Vector128<float> left, Vector128<float> right) { throw new NotImplementedException(); }
+ public static Vector128<float> AndNot(Vector128<float> left, Vector128<float> right) { throw new NotImplementedException(); }
+ public static Vector128<float> CompareEqual(Vector128<float> left, Vector128<float> right) { throw new NotImplementedException(); }
+ public static Vector128<float> CompareGreaterThan(Vector128<float> left, Vector128<float> right) { throw new NotImplementedException(); }
+ public static Vector128<float> CompareGreaterThanOrEqual(Vector128<float> left, Vector128<float> right) { throw new NotImplementedException(); }
+ public static Vector128<float> CompareLessThan(Vector128<float> left, Vector128<float> right) { throw new NotImplementedException(); }
+ public static Vector128<float> CompareLessThanOrEqual(Vector128<float> left, Vector128<float> right) { throw new NotImplementedException(); }
+ public static Vector128<float> CompareNotEqual(Vector128<float> left, Vector128<float> right) { throw new NotImplementedException(); }
+ public static Vector128<float> CompareNotGreaterThan(Vector128<float> left, Vector128<float> right) { throw new NotImplementedException(); }
+ public static Vector128<float> CompareNotGreaterThanOrEqual(Vector128<float> left, Vector128<float> right) { throw new NotImplementedException(); }
+ public static Vector128<float> CompareNotLessThan(Vector128<float> left, Vector128<float> right) { throw new NotImplementedException(); }
+ public static Vector128<float> CompareNotLessThanOrEqual(Vector128<float> left, Vector128<float> right) { throw new NotImplementedException(); }
+ public static Vector128<float> CompareOrdered(Vector128<float> left, Vector128<float> right) { throw new NotImplementedException(); }
+ public static Vector128<float> CompareUnordered(Vector128<float> left, Vector128<float> right) { throw new NotImplementedException(); }
+ public static Vector128<float> Divide(Vector128<float> left, Vector128<float> right) { throw new NotImplementedException(); }
+ public static unsafe Vector128<float> Load(float* address) { throw new NotImplementedException(); }
+ public static unsafe Vector128<float> LoadAligned(float* address) { throw new NotImplementedException(); }
+ public static Vector128<float> Max(Vector128<float> left, Vector128<float> right) { throw new NotImplementedException(); }
+ public static Vector128<float> Min(Vector128<float> left, Vector128<float> right) { throw new NotImplementedException(); }
+ public static Vector128<float> MoveHighToLow(Vector128<float> left, Vector128<float> right) { throw new NotImplementedException(); }
+ public static Vector128<float> MoveLowToHigh(Vector128<float> left, Vector128<float> right) { throw new NotImplementedException(); }
+ public static Vector128<float> Multiply(Vector128<float> left, Vector128<float> right) { throw new NotImplementedException(); }
+ public static Vector128<float> Or(Vector128<float> left, Vector128<float> right) { throw new NotImplementedException(); }
+ public static Vector128<float> Reciprocal(Vector128<float> value) { throw new NotImplementedException(); }
+ public static Vector128<float> ReciprocalSquareRoot(Vector128<float> value) { throw new NotImplementedException(); }
+ public static Vector128<float> Set(float e3, float e2, float e1, float e0) { throw new NotImplementedException(); }
+ public static Vector128<float> Set1(float value) { throw new NotImplementedException(); }
+ public static Vector128<float> SetZero() { throw new NotImplementedException(); }
+ public static Vector128<U> StaticCast<T, U>(Vector128<T> value) where T : struct where U : struct { throw new NotImplementedException(); }
+ public static Vector128<float> Shuffle(Vector128<float> left, Vector128<float> right, byte control) { throw new NotImplementedException(); }
+ public static Vector128<float> Sqrt(Vector128<float> value) { throw new NotImplementedException(); }
+ public static unsafe void StoreAligned(float* address, Vector128<float> source) { throw new NotImplementedException(); }
+ public static unsafe void StoreAlignedNonTemporal(float* address, Vector128<float> source) { throw new NotImplementedException(); }
+ public static unsafe void Store(float* address, Vector128<float> source) { throw new NotImplementedException(); }
+ public static Vector128<float> Subtract(Vector128<float> left, Vector128<float> right) { throw new NotImplementedException(); }
+ public static Vector128<float> UnpackHigh(Vector128<float> left, Vector128<float> right) { throw new NotImplementedException(); }
+ public static Vector128<float> UnpackLow(Vector128<float> left, Vector128<float> right) { throw new NotImplementedException(); }
+ public static Vector128<float> Xor(Vector128<float> left, Vector128<float> right) { throw new NotImplementedException(); }
+ }
+ public static class Sse2
+ {
+ public static bool IsSupported { get { return false; } }
+ public static Vector128<byte> Add(Vector128<byte> left, Vector128<byte> right) { throw new NotImplementedException(); }
+ public static Vector128<sbyte> Add(Vector128<sbyte> left, Vector128<sbyte> right) { throw new NotImplementedException(); }
+ public static Vector128<short> Add(Vector128<short> left, Vector128<short> right) { throw new NotImplementedException(); }
+ public static Vector128<ushort> Add(Vector128<ushort> left, Vector128<ushort> right) { throw new NotImplementedException(); }
+ public static Vector128<int> Add(Vector128<int> left, Vector128<int> right) { throw new NotImplementedException(); }
+ public static Vector128<uint> Add(Vector128<uint> left, Vector128<uint> right) { throw new NotImplementedException(); }
+ public static Vector128<long> Add(Vector128<byte> left, Vector128<long> right) { throw new NotImplementedException(); }
+ public static Vector128<ulong> Add(Vector128<sbyte> left, Vector128<ulong> right) { throw new NotImplementedException(); }
+ public static Vector128<double> Add(Vector128<double> left, Vector128<double> right) { throw new NotImplementedException(); }
+ public static Vector128<sbyte> AddSaturate(Vector128<sbyte> left, Vector128<sbyte> right) { throw new NotImplementedException(); }
+ public static Vector128<byte> AddSaturate(Vector128<byte> left, Vector128<byte> right) { throw new NotImplementedException(); }
+ public static Vector128<short> AddSaturate(Vector128<short> left, Vector128<short> right) { throw new NotImplementedException(); }
+ public static Vector128<ushort> AddSaturate(Vector128<ushort> left, Vector128<ushort> right) { throw new NotImplementedException(); }
+ public static Vector128<byte> And(Vector128<byte> left, Vector128<byte> right) { throw new NotImplementedException(); }
+ public static Vector128<sbyte> And(Vector128<sbyte> left, Vector128<sbyte> right) { throw new NotImplementedException(); }
+ public static Vector128<short> And(Vector128<short> left, Vector128<short> right) { throw new NotImplementedException(); }
+ public static Vector128<ushort> And(Vector128<ushort> left, Vector128<ushort> right) { throw new NotImplementedException(); }
+ public static Vector128<int> And(Vector128<int> left, Vector128<int> right) { throw new NotImplementedException(); }
+ public static Vector128<uint> And(Vector128<uint> left, Vector128<uint> right) { throw new NotImplementedException(); }
+ public static Vector128<long> And(Vector128<long> left, Vector128<long> right) { throw new NotImplementedException(); }
+ public static Vector128<ulong> And(Vector128<ulong> left, Vector128<ulong> right) { throw new NotImplementedException(); }
+ public static Vector128<double> And(Vector128<double> left, Vector128<double> right) { throw new NotImplementedException(); }
+ public static Vector128<byte> AndNot(Vector128<byte> left, Vector128<byte> right) { throw new NotImplementedException(); }
+ public static Vector128<sbyte> AndNot(Vector128<sbyte> left, Vector128<sbyte> right) { throw new NotImplementedException(); }
+ public static Vector128<short> AndNot(Vector128<short> left, Vector128<short> right) { throw new NotImplementedException(); }
+ public static Vector128<ushort> AndNot(Vector128<ushort> left, Vector128<ushort> right) { throw new NotImplementedException(); }
+ public static Vector128<int> AndNot(Vector128<int> left, Vector128<int> right) { throw new NotImplementedException(); }
+ public static Vector128<uint> AndNot(Vector128<uint> left, Vector128<uint> right) { throw new NotImplementedException(); }
+ public static Vector128<long> AndNot(Vector128<long> left, Vector128<long> right) { throw new NotImplementedException(); }
+ public static Vector128<ulong> AndNot(Vector128<ulong> left, Vector128<ulong> right) { throw new NotImplementedException(); }
+ public static Vector128<double> AndNot(Vector128<double> left, Vector128<double> right) { throw new NotImplementedException(); }
+ public static Vector128<byte> Average(Vector128<byte> left, Vector128<byte> right) { throw new NotImplementedException(); }
+ public static Vector128<ushort> Average(Vector128<ushort> left, Vector128<ushort> right) { throw new NotImplementedException(); }
+ public static Vector128<sbyte> CompareEqual(Vector128<sbyte> left, Vector128<sbyte> right) { throw new NotImplementedException(); }
+ public static Vector128<byte> CompareEqual(Vector128<byte> left, Vector128<byte> right) { throw new NotImplementedException(); }
+ public static Vector128<short> CompareEqual(Vector128<short> left, Vector128<short> right) { throw new NotImplementedException(); }
+ public static Vector128<ushort> CompareEqual(Vector128<ushort> left, Vector128<ushort> right) { throw new NotImplementedException(); }
+ public static Vector128<int> CompareEqual(Vector128<int> left, Vector128<int> right) { throw new NotImplementedException(); }
+ public static Vector128<uint> CompareEqual(Vector128<uint> left, Vector128<uint> right) { throw new NotImplementedException(); }
+ public static Vector128<double> CompareEqual(Vector128<double> left, Vector128<double> right) { throw new NotImplementedException(); }
+ public static Vector128<sbyte> CompareGreaterThan(Vector128<sbyte> left, Vector128<sbyte> right) { throw new NotImplementedException(); }
+ public static Vector128<short> CompareGreaterThan(Vector128<short> left, Vector128<short> right) { throw new NotImplementedException(); }
+ public static Vector128<int> CompareGreaterThan(Vector128<int> left, Vector128<int> right) { throw new NotImplementedException(); }
+ public static Vector128<double> CompareGreaterThan(Vector128<double> left, Vector128<double> right) { throw new NotImplementedException(); }
+ public static Vector128<double> CompareGreaterThanOrEqual(Vector128<double> left, Vector128<double> right) { throw new NotImplementedException(); }
+ public static Vector128<sbyte> CompareLessThan(Vector128<sbyte> left, Vector128<sbyte> right) { throw new NotImplementedException(); }
+ public static Vector128<short> CompareLessThan(Vector128<short> left, Vector128<short> right) { throw new NotImplementedException(); }
+ public static Vector128<int> CompareLessThan(Vector128<int> left, Vector128<int> right) { throw new NotImplementedException(); }
+ public static Vector128<double> CompareLessThan(Vector128<double> left, Vector128<double> right) { throw new NotImplementedException(); }
+ public static Vector128<double> CompareLessThanOrEqual(Vector128<double> left, Vector128<double> right) { throw new NotImplementedException(); }
+ public static Vector128<double> CompareNotEqual(Vector128<double> left, Vector128<double> right) { throw new NotImplementedException(); }
+ public static Vector128<double> CompareNotGreaterThan(Vector128<double> left, Vector128<double> right) { throw new NotImplementedException(); }
+ public static Vector128<double> CompareNotGreaterThanOrEqual(Vector128<double> left, Vector128<double> right) { throw new NotImplementedException(); }
+ public static Vector128<double> CompareNotLessThan(Vector128<double> left, Vector128<double> right) { throw new NotImplementedException(); }
+ public static Vector128<double> CompareNotLessThanOrEqual(Vector128<double> left, Vector128<double> right) { throw new NotImplementedException(); }
+ public static Vector128<double> CompareOrdered(Vector128<double> left, Vector128<double> right) { throw new NotImplementedException(); }
+ public static Vector128<double> CompareUnordered(Vector128<double> left, Vector128<double> right) { throw new NotImplementedException(); }
+ public static Vector128<int> ConvertToInt(Vector128<float> value) { throw new NotImplementedException(); }
+ public static Vector128<int> ConvertToInt(Vector128<double> value) { throw new NotImplementedException(); }
+ public static Vector128<float> ConvertToFloat(Vector128<int> value) { throw new NotImplementedException(); }
+ public static Vector128<float> ConvertToFloat(Vector128<double> value) { throw new NotImplementedException(); }
+ public static Vector128<double> ConvertToDouble(Vector128<int> value) { throw new NotImplementedException(); }
+ public static Vector128<double> ConvertToDouble(Vector128<float> value) { throw new NotImplementedException(); }
+ public static Vector128<int> ConvertToIntWithTruncation(Vector128<float> value) { throw new NotImplementedException(); }
+ public static Vector128<int> ConvertToIntWithTruncation(Vector128<double> value) { throw new NotImplementedException(); }
+ public static Vector128<double> Divide(Vector128<double> left, Vector128<double> right) { throw new NotImplementedException(); }
+ public static short ExtractShort<T>(Vector128<T> value, byte index) where T : struct { throw new NotImplementedException(); }
+ public static ushort ExtractUshort<T>(Vector128<T> value, byte index) where T : struct { throw new NotImplementedException(); }
+ public static Vector128<T> InsertShort<T>(Vector128<T> value, short data, byte index) where T : struct { throw new NotImplementedException(); }
+ public static Vector128<T> InsertUshort<T>(Vector128<T> value, ushort data, byte index) where T : struct { throw new NotImplementedException(); }
+ public static unsafe Vector128<sbyte> Load(sbyte* address) { throw new NotImplementedException(); }
+ public static unsafe Vector128<byte> Load(byte* address) { throw new NotImplementedException(); }
+ public static unsafe Vector128<short> Load(short* address) { throw new NotImplementedException(); }
+ public static unsafe Vector128<ushort> Load(ushort* address) { throw new NotImplementedException(); }
+ public static unsafe Vector128<int> Load(int* address) { throw new NotImplementedException(); }
+ public static unsafe Vector128<uint> Load(uint* address) { throw new NotImplementedException(); }
+ public static unsafe Vector128<long> Load(long* address) { throw new NotImplementedException(); }
+ public static unsafe Vector128<ulong> Load(ulong* address) { throw new NotImplementedException(); }
+ public static unsafe Vector128<double> Load(double* address) { throw new NotImplementedException(); }
+ public static unsafe Vector128<sbyte> LoadAligned(sbyte* address) { throw new NotImplementedException(); }
+ public static unsafe Vector128<byte> LoadAligned(byte* address) { throw new NotImplementedException(); }
+ public static unsafe Vector128<short> LoadAligned(short* address) { throw new NotImplementedException(); }
+ public static unsafe Vector128<ushort> LoadAligned(ushort* address) { throw new NotImplementedException(); }
+ public static unsafe Vector128<int> LoadAligned(int* address) { throw new NotImplementedException(); }
+ public static unsafe Vector128<uint> LoadAligned(uint* address) { throw new NotImplementedException(); }
+ public static unsafe Vector128<long> LoadAligned(long* address) { throw new NotImplementedException(); }
+ public static unsafe Vector128<ulong> LoadAligned(ulong* address) { throw new NotImplementedException(); }
+ public static unsafe Vector128<double> LoadAligned(double* address) { throw new NotImplementedException(); }
+ public static unsafe void MaskMove(Vector128<sbyte> source, Vector128<sbyte> mask, sbyte* address) { throw new NotImplementedException(); }
+ public static unsafe void MaskMove(Vector128<byte> source, Vector128<byte> mask, byte* address) { throw new NotImplementedException(); }
+ public static Vector128<byte> Max(Vector128<byte> left, Vector128<byte> right) { throw new NotImplementedException(); }
+ public static Vector128<short> Max(Vector128<short> left, Vector128<short> right) { throw new NotImplementedException(); }
+ public static Vector128<double> Max(Vector128<double> left, Vector128<double> right) { throw new NotImplementedException(); }
+ public static Vector128<byte> Min(Vector128<byte> left, Vector128<byte> right) { throw new NotImplementedException(); }
+ public static Vector128<short> Min(Vector128<short> left, Vector128<short> right) { throw new NotImplementedException(); }
+ public static Vector128<double> Min(Vector128<double> left, Vector128<double> right) { throw new NotImplementedException(); }
+ public static int MoveMask(Vector128<sbyte> value) { throw new NotImplementedException(); }
+ public static int MoveMask(Vector128<double> value) { throw new NotImplementedException(); }
+ public static Vector128<ulong> Multiply(Vector128<uint> left, Vector128<uint> right) { throw new NotImplementedException(); }
+ public static Vector128<double> Multiply(Vector128<double> left, Vector128<double> right) { throw new NotImplementedException(); }
+ public static Vector128<short> MultiplyHi(Vector128<short> left, Vector128<short> right) { throw new NotImplementedException(); }
+ public static Vector128<ushort> MultiplyHi(Vector128<ushort> left, Vector128<ushort> right) { throw new NotImplementedException(); }
+ public static Vector128<int> MultiplyHorizontalAdd(Vector128<short> left, Vector128<short> right) { throw new NotImplementedException(); }
+ public static Vector128<short> MultiplyLow(Vector128<short> left, Vector128<short> right) { throw new NotImplementedException(); }
+ public static Vector128<byte> Or(Vector128<byte> left, Vector128<byte> right) { throw new NotImplementedException(); }
+ public static Vector128<sbyte> Or(Vector128<sbyte> left, Vector128<sbyte> right) { throw new NotImplementedException(); }
+ public static Vector128<short> Or(Vector128<short> left, Vector128<short> right) { throw new NotImplementedException(); }
+ public static Vector128<ushort> Or(Vector128<ushort> left, Vector128<ushort> right) { throw new NotImplementedException(); }
+ public static Vector128<int> Or(Vector128<int> left, Vector128<int> right) { throw new NotImplementedException(); }
+ public static Vector128<uint> Or(Vector128<uint> left, Vector128<uint> right) { throw new NotImplementedException(); }
+ public static Vector128<long> Or(Vector128<long> left, Vector128<long> right) { throw new NotImplementedException(); }
+ public static Vector128<ulong> Or(Vector128<ulong> left, Vector128<ulong> right) { throw new NotImplementedException(); }
+ public static Vector128<double> Or(Vector128<double> left, Vector128<double> right) { throw new NotImplementedException(); }
+ public static Vector128<sbyte> PackSignedSaturate(Vector128<short> left, Vector128<short> right) { throw new NotImplementedException(); }
+ public static Vector128<short> PackSignedSaturate(Vector128<int> left, Vector128<int> right) { throw new NotImplementedException(); }
+ public static Vector128<byte> PackUnsignedSaturate(Vector128<short> left, Vector128<short> right) { throw new NotImplementedException(); }
+ public static Vector128<sbyte> Set(sbyte e15, sbyte e14, sbyte e13, sbyte e12, sbyte e11, sbyte e10, sbyte e9, sbyte e8, sbyte e7, sbyte e6, sbyte e5, sbyte e4, sbyte e3, sbyte e2, sbyte e1, sbyte e0) { throw new NotImplementedException(); }
+ public static Vector128<byte> Set(byte e15, byte e14, byte e13, byte e12, byte e11, byte e10, byte e9, byte e8, byte e7, byte e6, byte e5, byte e4, byte e3, byte e2, byte e1, byte e0) { throw new NotImplementedException(); }
+ public static Vector128<short> Set(short e7, short e6, short e5, short e4, short e3, short e2, short e1, short e0) { throw new NotImplementedException(); }
+ public static Vector128<ushort> Set(ushort e7, ushort e6, ushort e5, ushort e4, ushort e3, ushort e2, ushort e1, ushort e0) { throw new NotImplementedException(); }
+ public static Vector128<int> Set(int e3, int e2, int e1, int e0) { throw new NotImplementedException(); }
+ public static Vector128<uint> Set(uint e3, uint e2, uint e1, uint e0) { throw new NotImplementedException(); }
+ public static Vector128<long> Set(long e1, long e0) { throw new NotImplementedException(); }
+ public static Vector128<ulong> Set(ulong e1, ulong e0) { throw new NotImplementedException(); }
+ public static Vector128<double> Set(double e1, double e0) { throw new NotImplementedException(); }
+ public static Vector128<byte> Set1(byte value) { throw new NotImplementedException(); }
+ public static Vector128<sbyte> Set1(sbyte value) { throw new NotImplementedException(); }
+ public static Vector128<short> Set1(short value) { throw new NotImplementedException(); }
+ public static Vector128<ushort> Set1(ushort value) { throw new NotImplementedException(); }
+ public static Vector128<int> Set1(int value) { throw new NotImplementedException(); }
+ public static Vector128<uint> Set1(uint value) { throw new NotImplementedException(); }
+ public static Vector128<long> Set1(long value) { throw new NotImplementedException(); }
+ public static Vector128<ulong> Set1(ulong value) { throw new NotImplementedException(); }
+ public static Vector128<double> Set1(double value) { throw new NotImplementedException(); }
+ public static Vector128<T> SetZero<T>() where T : struct { throw new NotImplementedException(); }
+ public static Vector128<long> SumAbsoluteDifferences(Vector128<byte> left, Vector128<byte> right) { throw new NotImplementedException(); }
+ public static Vector128<int> Shuffle(Vector128<int> value, byte control) { throw new NotImplementedException(); }
+ public static Vector128<uint> Shuffle(Vector128<uint> value, byte control) { throw new NotImplementedException(); }
+ public static Vector128<double> Shuffle(Vector128<double> left, Vector128<double> right, byte control) { throw new NotImplementedException(); }
+ public static Vector128<short> ShuffleHigh(Vector128<short> value, byte control) { throw new NotImplementedException(); }
+ public static Vector128<ushort> ShuffleHigh(Vector128<ushort> value, byte control) { throw new NotImplementedException(); }
+ public static Vector128<short> ShuffleLow(Vector128<short> value, byte control) { throw new NotImplementedException(); }
+ public static Vector128<ushort> ShuffleLow(Vector128<ushort> value, byte control) { throw new NotImplementedException(); }
+ public static Vector128<short> ShiftLeftLogical(Vector128<short> value, byte count) { throw new NotImplementedException(); }
+ public static Vector128<ushort> ShiftLeftLogical(Vector128<ushort> value, byte count) { throw new NotImplementedException(); }
+ public static Vector128<int> ShiftLeftLogical(Vector128<int> value, byte count) { throw new NotImplementedException(); }
+ public static Vector128<uint> ShiftLeftLogical(Vector128<uint> value, byte count) { throw new NotImplementedException(); }
+ public static Vector128<long> ShiftLeftLogical(Vector128<long> value, byte count) { throw new NotImplementedException(); }
+ public static Vector128<ulong> ShiftLeftLogical(Vector128<ulong> value, byte count) { throw new NotImplementedException(); }
+ public static Vector128<sbyte> ShiftLeftLogical128BitLane(Vector128<sbyte> value, byte numBytes) { throw new NotImplementedException(); }
+ public static Vector128<byte> ShiftLeftLogical128BitLane(Vector128<byte> value, byte numBytes) { throw new NotImplementedException(); }
+ public static Vector128<short> ShiftLeftLogical128BitLane(Vector128<short> value, byte numBytes) { throw new NotImplementedException(); }
+ public static Vector128<ushort> ShiftLeftLogical128BitLane(Vector128<ushort> value, byte numBytes) { throw new NotImplementedException(); }
+ public static Vector128<int> ShiftLeftLogical128BitLane(Vector128<int> value, byte numBytes) { throw new NotImplementedException(); }
+ public static Vector128<uint> ShiftLeftLogical128BitLane(Vector128<uint> value, byte numBytes) { throw new NotImplementedException(); }
+ public static Vector128<long> ShiftLeftLogical128BitLane(Vector128<long> value, byte numBytes) { throw new NotImplementedException(); }
+ public static Vector128<ulong> ShiftLeftLogical128BitLane(Vector128<ulong> value, byte numBytes) { throw new NotImplementedException(); }
+ public static Vector128<short> ShiftRightArithmetic(Vector128<short> value, byte count) { throw new NotImplementedException(); }
+ public static Vector128<int> ShiftRightArithmetic(Vector128<int> value, byte count) { throw new NotImplementedException(); }
+ public static Vector128<short> ShiftRightLogical(Vector128<short> value, byte count) { throw new NotImplementedException(); }
+ public static Vector128<ushort> ShiftRightLogical(Vector128<ushort> value, byte count) { throw new NotImplementedException(); }
+ public static Vector128<int> ShiftRightLogical(Vector128<int> value, byte count) { throw new NotImplementedException(); }
+ public static Vector128<uint> ShiftRightLogical(Vector128<uint> value, byte count) { throw new NotImplementedException(); }
+ public static Vector128<long> ShiftRightLogical(Vector128<long> value, byte count) { throw new NotImplementedException(); }
+ public static Vector128<ulong> ShiftRightLogical(Vector128<ulong> value, byte count) { throw new NotImplementedException(); }
+ public static Vector128<sbyte> ShiftRightLogical128BitLane(Vector128<sbyte> value, byte numBytes) { throw new NotImplementedException(); }
+ public static Vector128<byte> ShiftRightLogical128BitLane(Vector128<byte> value, byte numBytes) { throw new NotImplementedException(); }
+ public static Vector128<short> ShiftRightLogical128BitLane(Vector128<short> value, byte numBytes) { throw new NotImplementedException(); }
+ public static Vector128<ushort> ShiftRightLogical128BitLane(Vector128<ushort> value, byte numBytes) { throw new NotImplementedException(); }
+ public static Vector128<int> ShiftRightLogical128BitLane(Vector128<int> value, byte numBytes) { throw new NotImplementedException(); }
+ public static Vector128<uint> ShiftRightLogical128BitLane(Vector128<uint> value, byte numBytes) { throw new NotImplementedException(); }
+ public static Vector128<long> ShiftRightLogical128BitLane(Vector128<long> value, byte numBytes) { throw new NotImplementedException(); }
+ public static Vector128<ulong> ShiftRightLogical128BitLane(Vector128<ulong> value, byte numBytes) { throw new NotImplementedException(); }
+ public static Vector128<double> Sqrt(Vector128<double> value) { throw new NotImplementedException(); }
+ public static unsafe void StoreAligned(sbyte* address, Vector128<sbyte> source) { throw new NotImplementedException(); }
+ public static unsafe void StoreAligned(byte* address, Vector128<byte> source) { throw new NotImplementedException(); }
+ public static unsafe void StoreAligned(short* address, Vector128<short> source) { throw new NotImplementedException(); }
+ public static unsafe void StoreAligned(ushort* address, Vector128<ushort> source) { throw new NotImplementedException(); }
+ public static unsafe void StoreAligned(int* address, Vector128<int> source) { throw new NotImplementedException(); }
+ public static unsafe void StoreAligned(uint* address, Vector128<uint> source) { throw new NotImplementedException(); }
+ public static unsafe void StoreAligned(long* address, Vector128<long> source) { throw new NotImplementedException(); }
+ public static unsafe void StoreAligned(ulong* address, Vector128<ulong> source) { throw new NotImplementedException(); }
+ public static unsafe void StoreAligned(double* address, Vector128<double> source) { throw new NotImplementedException(); }
+ public static unsafe void StoreAlignedNonTemporal(sbyte* address, Vector128<sbyte> source) { throw new NotImplementedException(); }
+ public static unsafe void StoreAlignedNonTemporal(byte* address, Vector128<byte> source) { throw new NotImplementedException(); }
+ public static unsafe void StoreAlignedNonTemporal(short* address, Vector128<short> source) { throw new NotImplementedException(); }
+ public static unsafe void StoreAlignedNonTemporal(ushort* address, Vector128<ushort> source) { throw new NotImplementedException(); }
+ public static unsafe void StoreAlignedNonTemporal(int* address, Vector128<int> source) { throw new NotImplementedException(); }
+ public static unsafe void StoreAlignedNonTemporal(uint* address, Vector128<uint> source) { throw new NotImplementedException(); }
+ public static unsafe void StoreAlignedNonTemporal(long* address, Vector128<long> source) { throw new NotImplementedException(); }
+ public static unsafe void StoreAlignedNonTemporal(ulong* address, Vector128<ulong> source) { throw new NotImplementedException(); }
+ public static unsafe void StoreAlignedNonTemporal(double* address, Vector128<double> source) { throw new NotImplementedException(); }
+ public static unsafe void Store(sbyte* address, Vector128<sbyte> source) { throw new NotImplementedException(); }
+ public static unsafe void Store(byte* address, Vector128<byte> source) { throw new NotImplementedException(); }
+ public static unsafe void Store(short* address, Vector128<short> source) { throw new NotImplementedException(); }
+ public static unsafe void Store(ushort* address, Vector128<ushort> source) { throw new NotImplementedException(); }
+ public static unsafe void Store(int* address, Vector128<int> source) { throw new NotImplementedException(); }
+ public static unsafe void Store(uint* address, Vector128<uint> source) { throw new NotImplementedException(); }
+ public static unsafe void Store(long* address, Vector128<long> source) { throw new NotImplementedException(); }
+ public static unsafe void Store(ulong* address, Vector128<ulong> source) { throw new NotImplementedException(); }
+ public static unsafe void Store(double* address, Vector128<double> source) { throw new NotImplementedException(); }
+ public static unsafe void StoreHigh(double* address, Vector128<double> source) { throw new NotImplementedException(); }
+ public static unsafe void StoreLow(long* address, Vector128<long> source) { throw new NotImplementedException(); }
+ public static unsafe void StoreLow(ulong* address, Vector128<ulong> source) { throw new NotImplementedException(); }
+ public static unsafe void StoreLow(double* address, Vector128<double> source) { throw new NotImplementedException(); }
+ public static Vector128<byte> Subtract(Vector128<byte> left, Vector128<byte> right) { throw new NotImplementedException(); }
+ public static Vector128<sbyte> Subtract(Vector128<sbyte> left, Vector128<sbyte> right) { throw new NotImplementedException(); }
+ public static Vector128<short> Subtract(Vector128<short> left, Vector128<short> right) { throw new NotImplementedException(); }
+ public static Vector128<ushort> Subtract(Vector128<ushort> left, Vector128<ushort> right) { throw new NotImplementedException(); }
+ public static Vector128<int> Subtract(Vector128<int> left, Vector128<int> right) { throw new NotImplementedException(); }
+ public static Vector128<uint> Subtract(Vector128<uint> left, Vector128<uint> right) { throw new NotImplementedException(); }
+ public static Vector128<long> Subtract(Vector128<long> left, Vector128<long> right) { throw new NotImplementedException(); }
+ public static Vector128<ulong> Subtract(Vector128<ulong> left, Vector128<ulong> right) { throw new NotImplementedException(); }
+ public static Vector128<double> Subtract(Vector128<double> left, Vector128<double> right) { throw new NotImplementedException(); }
+ public static Vector128<sbyte> SubtractSaturate(Vector128<sbyte> left, Vector128<sbyte> right) { throw new NotImplementedException(); }
+ public static Vector128<short> SubtractSaturate(Vector128<short> left, Vector128<short> right) { throw new NotImplementedException(); }
+ public static Vector128<byte> SubtractSaturate(Vector128<byte> left, Vector128<byte> right) { throw new NotImplementedException(); }
+ public static Vector128<ushort> SubtractSaturate(Vector128<ushort> left, Vector128<ushort> right) { throw new NotImplementedException(); }
+ public static Vector128<byte> UnpackHigh(Vector128<byte> left, Vector128<byte> right) { throw new NotImplementedException(); }
+ public static Vector128<sbyte> UnpackHigh(Vector128<sbyte> left, Vector128<sbyte> right) { throw new NotImplementedException(); }
+ public static Vector128<short> UnpackHigh(Vector128<short> left, Vector128<short> right) { throw new NotImplementedException(); }
+ public static Vector128<ushort> UnpackHigh(Vector128<ushort> left, Vector128<ushort> right) { throw new NotImplementedException(); }
+ public static Vector128<int> UnpackHigh(Vector128<int> left, Vector128<int> right) { throw new NotImplementedException(); }
+ public static Vector128<uint> UnpackHigh(Vector128<uint> left, Vector128<uint> right) { throw new NotImplementedException(); }
+ public static Vector128<long> UnpackHigh(Vector128<long> left, Vector128<long> right) { throw new NotImplementedException(); }
+ public static Vector128<ulong> UnpackHigh(Vector128<ulong> left, Vector128<ulong> right) { throw new NotImplementedException(); }
+ public static Vector128<double> UnpackHigh(Vector128<double> left, Vector128<double> right) { throw new NotImplementedException(); }
+ public static Vector128<byte> UnpackLow(Vector128<byte> left, Vector128<byte> right) { throw new NotImplementedException(); }
+ public static Vector128<sbyte> UnpackLow(Vector128<sbyte> left, Vector128<sbyte> right) { throw new NotImplementedException(); }
+ public static Vector128<short> UnpackLow(Vector128<short> left, Vector128<short> right) { throw new NotImplementedException(); }
+ public static Vector128<ushort> UnpackLow(Vector128<ushort> left, Vector128<ushort> right) { throw new NotImplementedException(); }
+ public static Vector128<int> UnpackLow(Vector128<int> left, Vector128<int> right) { throw new NotImplementedException(); }
+ public static Vector128<uint> UnpackLow(Vector128<uint> left, Vector128<uint> right) { throw new NotImplementedException(); }
+ public static Vector128<long> UnpackLow(Vector128<long> left, Vector128<long> right) { throw new NotImplementedException(); }
+ public static Vector128<ulong> UnpackLow(Vector128<ulong> left, Vector128<ulong> right) { throw new NotImplementedException(); }
+ public static Vector128<double> UnpackLow(Vector128<double> left, Vector128<double> right) { throw new NotImplementedException(); }
+ public static Vector128<byte> Xor(Vector128<byte> left, Vector128<byte> right) { throw new NotImplementedException(); }
+ public static Vector128<sbyte> Xor(Vector128<sbyte> left, Vector128<sbyte> right) { throw new NotImplementedException(); }
+ public static Vector128<short> Xor(Vector128<short> left, Vector128<short> right) { throw new NotImplementedException(); }
+ public static Vector128<ushort> Xor(Vector128<ushort> left, Vector128<ushort> right) { throw new NotImplementedException(); }
+ public static Vector128<int> Xor(Vector128<int> left, Vector128<int> right) { throw new NotImplementedException(); }
+ public static Vector128<uint> Xor(Vector128<uint> left, Vector128<uint> right) { throw new NotImplementedException(); }
+ public static Vector128<long> Xor(Vector128<long> left, Vector128<long> right) { throw new NotImplementedException(); }
+ public static Vector128<ulong> Xor(Vector128<ulong> left, Vector128<ulong> right) { throw new NotImplementedException(); }
+ public static Vector128<double> Xor(Vector128<double> left, Vector128<double> right) { throw new NotImplementedException(); }
+ }
+ public static class Sse3
+ {
+ public static bool IsSupported { get { throw null; } }
+ public static Vector128<float> AddSubtract(Vector128<float> left, Vector128<float> right) { throw null; }
+ public static Vector128<double> AddSubtract(Vector128<double> left, Vector128<double> right) { throw null; }
+ public static Vector128<float> HorizontalAdd(Vector128<float> left, Vector128<float> right) { throw null; }
+ public static Vector128<double> HorizontalAdd(Vector128<double> left, Vector128<double> right) { throw null; }
+ public static Vector128<float> HorizontalSubtract(Vector128<float> left, Vector128<float> right) { throw null; }
+ public static Vector128<double> HorizontalSubtract(Vector128<double> left, Vector128<double> right) { throw null; }
+ public static unsafe Vector128<double> LoadAndDuplicate(double* address) { throw null; }
+ public static unsafe Vector128<sbyte> LoadDqu(sbyte* address) { throw null; }
+ public static unsafe Vector128<byte> LoadDqu(byte* address) { throw null; }
+ public static unsafe Vector128<short> LoadDqu(short* address) { throw null; }
+ public static unsafe Vector128<ushort> LoadDqu(ushort* address) { throw null; }
+ public static unsafe Vector128<int> LoadDqu(int* address) { throw null; }
+ public static unsafe Vector128<uint> LoadDqu(uint* address) { throw null; }
+ public static unsafe Vector128<long> LoadDqu(long* address) { throw null; }
+ public static unsafe Vector128<ulong> LoadDqu(ulong* address) { throw null; }
+ public static Vector128<double> MoveAndDuplicate(Vector128<double> source) { throw null; }
+ public static Vector128<float> MoveHighAndDuplicate(Vector128<float> source) { throw null; }
+ public static Vector128<float> MoveLowAndDuplicate(Vector128<float> source) { throw null; }
+ }
+ public static class Sse41
+ {
+ public static bool IsSupported { get { throw null; } }
+ public static Vector128<short> Blend(Vector128<short> left, Vector128<short> right, byte control) { throw null; }
+ public static Vector128<ushort> Blend(Vector128<ushort> left, Vector128<ushort> right, byte control) { throw null; }
+ public static Vector128<float> Blend(Vector128<float> left, Vector128<float> right, byte control) { throw null; }
+ public static Vector128<double> Blend(Vector128<double> left, Vector128<double> right, byte control) { throw null; }
+ public static Vector128<sbyte> BlendVariable(Vector128<sbyte> left, Vector128<sbyte> right, Vector128<sbyte> mask) { throw null; }
+ public static Vector128<byte> BlendVariable(Vector128<byte> left, Vector128<byte> right, Vector128<byte> mask) { throw null; }
+ public static Vector128<float> BlendVariable(Vector128<float> left, Vector128<float> right, Vector128<float> mask) { throw null; }
+ public static Vector128<double> BlendVariable(Vector128<double> left, Vector128<double> right, Vector128<double> mask) { throw null; }
+ public static Vector128<float> Ceiling(Vector128<float> value) { throw null; }
+ public static Vector128<double> Ceiling(Vector128<double> value) { throw null; }
+ public static Vector128<long> CompareEqual(Vector128<long> left, Vector128<long> right) { throw null; }
+ public static Vector128<ulong> CompareEqual(Vector128<ulong> left, Vector128<ulong> right) { throw null; }
+ public static Vector128<short> ConvertToShort(Vector128<sbyte> value) { throw null; }
+ public static Vector128<short> ConvertToShort(Vector128<byte> value) { throw null; }
+ public static Vector128<int> ConvertToInt(Vector128<sbyte> value) { throw null; }
+ public static Vector128<int> ConvertToInt(Vector128<byte> value) { throw null; }
+ public static Vector128<int> ConvertToInt(Vector128<short> value) { throw null; }
+ public static Vector128<int> ConvertToInt(Vector128<ushort> value) { throw null; }
+ public static Vector128<long> ConvertToLong(Vector128<sbyte> value) { throw null; }
+ public static Vector128<long> ConvertToLong(Vector128<byte> value) { throw null; }
+ public static Vector128<long> ConvertToLong(Vector128<short> value) { throw null; }
+ public static Vector128<long> ConvertToLong(Vector128<ushort> value) { throw null; }
+ public static Vector128<long> ConvertToLong(Vector128<int> value) { throw null; }
+ public static Vector128<long> ConvertToLong(Vector128<uint> value) { throw null; }
+ public static sbyte ExtractSbyte<T>(Vector128<T> value, byte index) where T : struct { throw null; }
+ public static byte ExtractByte<T>(Vector128<T> value, byte index) where T : struct { throw null; }
+ public static int ExtractInt<T>(Vector128<T> value, byte index) where T : struct { throw null; }
+ public static uint ExtractUint<T>(Vector128<T> value, byte index) where T : struct { throw null; }
+ public static long ExtractLong<T>(Vector128<T> value, byte index) where T : struct { throw null; }
+ public static ulong ExtractUlong<T>(Vector128<T> value, byte index) where T : struct { throw null; }
+ public static float ExtractFloat<T>(Vector128<T> value, byte index) where T : struct { throw null; }
+ public static Vector128<float> Floor(Vector128<float> value) { throw null; }
+ public static Vector128<double> Floor(Vector128<double> value) { throw null; }
+ public static Vector128<T> InsertSbyte<T>(Vector128<T> value, sbyte data, byte index) where T : struct { throw null; }
+ public static Vector128<T> InsertByte<T>(Vector128<T> value, byte data, byte index) where T : struct { throw null; }
+ public static Vector128<T> InsertInt<T>(Vector128<T> value, int data, byte index) where T : struct { throw null; }
+ public static Vector128<T> InsertUint<T>(Vector128<T> value, uint data, byte index) where T : struct { throw null; }
+ public static Vector128<T> InsertLong<T>(Vector128<T> value, long data, byte index) where T : struct { throw null; }
+ public static Vector128<T> InsertUlong<T>(Vector128<T> value, ulong data, byte index) where T : struct { throw null; }
+ public static Vector128<T> InsertFloat<T>(Vector128<T> value, float data, byte index) where T : struct { throw null; }
+ public static Vector128<sbyte> Max(Vector128<sbyte> left, Vector128<sbyte> right) { throw null; }
+ public static Vector128<ushort> Max(Vector128<ushort> left, Vector128<ushort> right) { throw null; }
+ public static Vector128<int> Max(Vector128<int> left, Vector128<int> right) { throw null; }
+ public static Vector128<uint> Max(Vector128<uint> left, Vector128<uint> right) { throw null; }
+ public static Vector128<sbyte> Min(Vector128<sbyte> left, Vector128<sbyte> right) { throw null; }
+ public static Vector128<ushort> Min(Vector128<ushort> left, Vector128<ushort> right) { throw null; }
+ public static Vector128<int> Min(Vector128<int> left, Vector128<int> right) { throw null; }
+ public static Vector128<uint> Min(Vector128<uint> left, Vector128<uint> right) { throw null; }
+ public static Vector128<ushort> MinHorizontal(Vector128<ushort> value) { throw null; }
+ public static Vector128<ushort> MultipleSumAbsoluteDifferences(Vector128<byte> left, Vector128<byte> right, byte mask) { throw null; }
+ public static Vector128<long> Multiply(Vector128<int> left, Vector128<int> right) { throw null; }
+ public static Vector128<int> MultiplyLow(Vector128<int> left, Vector128<int> right) { throw null; }
+ public static Vector128<ushort> PackUnsignedSaturate(Vector128<int> left, Vector128<int> right) { throw null; }
+ public static Vector128<float> RoundToNearestInteger(Vector128<float> value) { throw null; }
+ public static Vector128<float> RoundToNegativeInfinity(Vector128<float> value) { throw null; }
+ public static Vector128<float> RoundToPositiveInfinity(Vector128<float> value) { throw null; }
+ public static Vector128<float> RoundToZero(Vector128<float> value) { throw null; }
+ public static Vector128<float> RoundCurrentDirection(Vector128<float> value) { throw null; }
+ public static Vector128<double> RoundToNearestInteger(Vector128<double> value) { throw null; }
+ public static Vector128<double> RoundToNegativeInfinity(Vector128<double> value) { throw null; }
+ public static Vector128<double> RoundToPositiveInfinity(Vector128<double> value) { throw null; }
+ public static Vector128<double> RoundToZero(Vector128<double> value) { throw null; }
+ public static Vector128<double> RoundCurrentDirection(Vector128<double> value) { throw null; }
+ public static unsafe Vector128<sbyte> LoadAlignedNonTemporal(sbyte* address) { throw null; }
+ public static unsafe Vector128<byte> LoadAlignedNonTemporal(byte* address) { throw null; }
+ public static unsafe Vector128<short> LoadAlignedNonTemporal(short* address) { throw null; }
+ public static unsafe Vector128<ushort> LoadAlignedNonTemporal(ushort* address) { throw null; }
+ public static unsafe Vector128<int> LoadAlignedNonTemporal(int* address) { throw null; }
+ public static unsafe Vector128<uint> LoadAlignedNonTemporal(uint* address) { throw null; }
+ public static unsafe Vector128<long> LoadAlignedNonTemporal(long* address) { throw null; }
+ public static unsafe Vector128<ulong> LoadAlignedNonTemporal(ulong* address) { throw null; }
+ public static bool TestAllOnes(Vector128<sbyte> value) { throw null; }
+ public static bool TestAllOnes(Vector128<byte> value) { throw null; }
+ public static bool TestAllOnes(Vector128<short> value) { throw null; }
+ public static bool TestAllOnes(Vector128<ushort> value) { throw null; }
+ public static bool TestAllOnes(Vector128<int> value) { throw null; }
+ public static bool TestAllOnes(Vector128<uint> value) { throw null; }
+ public static bool TestAllOnes(Vector128<long> value) { throw null; }
+ public static bool TestAllOnes(Vector128<ulong> value) { throw null; }
+ public static bool TestAllZeros(Vector128<sbyte> left, Vector128<sbyte> right) { throw null; }
+ public static bool TestAllZeros(Vector128<byte> left, Vector128<byte> right) { throw null; }
+ public static bool TestAllZeros(Vector128<short> left, Vector128<short> right) { throw null; }
+ public static bool TestAllZeros(Vector128<ushort> left, Vector128<ushort> right) { throw null; }
+ public static bool TestAllZeros(Vector128<int> left, Vector128<int> right) { throw null; }
+ public static bool TestAllZeros(Vector128<uint> left, Vector128<uint> right) { throw null; }
+ public static bool TestAllZeros(Vector128<long> left, Vector128<long> right) { throw null; }
+ public static bool TestAllZeros(Vector128<ulong> left, Vector128<ulong> right) { throw null; }
+ public static bool TestC(Vector128<sbyte> left, Vector128<sbyte> right) { throw null; }
+ public static bool TestC(Vector128<byte> left, Vector128<byte> right) { throw null; }
+ public static bool TestC(Vector128<short> left, Vector128<short> right) { throw null; }
+ public static bool TestC(Vector128<ushort> left, Vector128<ushort> right) { throw null; }
+ public static bool TestC(Vector128<int> left, Vector128<int> right) { throw null; }
+ public static bool TestC(Vector128<uint> left, Vector128<uint> right) { throw null; }
+ public static bool TestC(Vector128<long> left, Vector128<long> right) { throw null; }
+ public static bool TestC(Vector128<ulong> left, Vector128<ulong> right) { throw null; }
+ public static bool TestMixOnesZeros(Vector128<sbyte> left, Vector128<sbyte> right) { throw null; }
+ public static bool TestMixOnesZeros(Vector128<byte> left, Vector128<byte> right) { throw null; }
+ public static bool TestMixOnesZeros(Vector128<short> left, Vector128<short> right) { throw null; }
+ public static bool TestMixOnesZeros(Vector128<ushort> left, Vector128<ushort> right) { throw null; }
+ public static bool TestMixOnesZeros(Vector128<int> left, Vector128<int> right) { throw null; }
+ public static bool TestMixOnesZeros(Vector128<uint> left, Vector128<uint> right) { throw null; }
+ public static bool TestMixOnesZeros(Vector128<long> left, Vector128<long> right) { throw null; }
+ public static bool TestMixOnesZeros(Vector128<ulong> left, Vector128<ulong> right) { throw null; }
+ public static bool TestNotZAndNotC(Vector128<sbyte> left, Vector128<sbyte> right) { throw null; }
+ public static bool TestNotZAndNotC(Vector128<byte> left, Vector128<byte> right) { throw null; }
+ public static bool TestNotZAndNotC(Vector128<short> left, Vector128<short> right) { throw null; }
+ public static bool TestNotZAndNotC(Vector128<ushort> left, Vector128<ushort> right) { throw null; }
+ public static bool TestNotZAndNotC(Vector128<int> left, Vector128<int> right) { throw null; }
+ public static bool TestNotZAndNotC(Vector128<uint> left, Vector128<uint> right) { throw null; }
+ public static bool TestNotZAndNotC(Vector128<long> left, Vector128<long> right) { throw null; }
+ public static bool TestNotZAndNotC(Vector128<ulong> left, Vector128<ulong> right) { throw null; }
+ public static bool TestZ(Vector128<sbyte> left, Vector128<sbyte> right) { throw null; }
+ public static bool TestZ(Vector128<byte> left, Vector128<byte> right) { throw null; }
+ public static bool TestZ(Vector128<short> left, Vector128<short> right) { throw null; }
+ public static bool TestZ(Vector128<ushort> left, Vector128<ushort> right) { throw null; }
+ public static bool TestZ(Vector128<int> left, Vector128<int> right) { throw null; }
+ public static bool TestZ(Vector128<uint> left, Vector128<uint> right) { throw null; }
+ public static bool TestZ(Vector128<long> left, Vector128<long> right) { throw null; }
+ public static bool TestZ(Vector128<ulong> left, Vector128<ulong> right) { throw null; }
+ }
+ public static class Sse42
+ {
+ public static bool IsSupported { get { throw null; } }
+ public static bool CompareImplicitLength(Vector128<sbyte> left, Vector128<sbyte> right, ResultsFlag flag, StringComparisonMode mode) { throw null; }
+ public static bool CompareImplicitLength(Vector128<byte> left, Vector128<byte> right, ResultsFlag flag, StringComparisonMode mode) { throw null; }
+ public static bool CompareImplicitLength(Vector128<short> left, Vector128<short> right, ResultsFlag flag, StringComparisonMode mode) { throw null; }
+ public static bool CompareImplicitLength(Vector128<ushort> left, Vector128<ushort> right, ResultsFlag flag, StringComparisonMode mode) { throw null; }
+ public static bool CompareExplicitLength(Vector128<sbyte> left, byte leftLength, Vector128<sbyte> right, byte rightLength, ResultsFlag flag, StringComparisonMode mode) { throw null; }
+ public static bool CompareExplicitLength(Vector128<byte> left, byte leftLength, Vector128<byte> right, byte rightLength, ResultsFlag flag, StringComparisonMode mode) { throw null; }
+ public static bool CompareExplicitLength(Vector128<short> left, byte leftLength, Vector128<short> right, byte rightLength, ResultsFlag flag, StringComparisonMode mode) { throw null; }
+ public static bool CompareExplicitLength(Vector128<ushort> left, byte leftLength, Vector128<ushort> right, byte rightLength, ResultsFlag flag, StringComparisonMode mode) { throw null; }
+ public static int CompareImplicitLengthIndex(Vector128<sbyte> left, Vector128<sbyte> right, StringComparisonMode mode) { throw null; }
+ public static int CompareImplicitLengthIndex(Vector128<byte> left, Vector128<byte> right, StringComparisonMode mode) { throw null; }
+ public static int CompareImplicitLengthIndex(Vector128<short> left, Vector128<short> right, StringComparisonMode mode) { throw null; }
+ public static int CompareImplicitLengthIndex(Vector128<ushort> left, Vector128<ushort> right, StringComparisonMode mode) { throw null; }
+ public static int CompareExplicitLengthIndex(Vector128<sbyte> left, byte leftLength, Vector128<sbyte> right, byte rightLength, StringComparisonMode mode) { throw null; }
+ public static int CompareExplicitLengthIndex(Vector128<byte> left, byte leftLength, Vector128<byte> right, byte rightLength, StringComparisonMode mode) { throw null; }
+ public static int CompareExplicitLengthIndex(Vector128<short> left, byte leftLength, Vector128<short> right, byte rightLength, StringComparisonMode mode) { throw null; }
+ public static int CompareExplicitLengthIndex(Vector128<ushort> left, byte leftLength, Vector128<ushort> right, byte rightLength, StringComparisonMode mode) { throw null; }
+ public static Vector128<ushort> CompareImplicitLengthBitMask(Vector128<sbyte> left, Vector128<sbyte> right, StringComparisonMode mode) { throw null; }
+ public static Vector128<ushort> CompareImplicitLengthBitMask(Vector128<byte> left, Vector128<byte> right, StringComparisonMode mode) { throw null; }
+ public static Vector128<byte> CompareImplicitLengthBitMask(Vector128<short> left, Vector128<short> right, StringComparisonMode mode) { throw null; }
+ public static Vector128<byte> CompareImplicitLengthBitMask(Vector128<ushort> left, Vector128<ushort> right, StringComparisonMode mode) { throw null; }
+ public static Vector128<byte> CompareImplicitLengthUnitMask(Vector128<sbyte> left, Vector128<sbyte> right, StringComparisonMode mode) { throw null; }
+ public static Vector128<byte> CompareImplicitLengthUnitMask(Vector128<byte> left, Vector128<byte> right, StringComparisonMode mode) { throw null; }
+ public static Vector128<ushort> CompareImplicitLengthUnitMask(Vector128<short> left, Vector128<short> right, StringComparisonMode mode) { throw null; }
+ public static Vector128<ushort> CompareImplicitLengthUnitMask(Vector128<ushort> left, Vector128<ushort> right, StringComparisonMode mode) { throw null; }
+ public static Vector128<ushort> CompareExplicitLengthBitMask(Vector128<sbyte> left, byte leftLength, Vector128<sbyte> right, byte rightLength, StringComparisonMode mode) { throw null; }
+ public static Vector128<ushort> CompareExplicitLengthBitMask(Vector128<byte> left, byte leftLength, Vector128<byte> right, byte rightLength, StringComparisonMode mode) { throw null; }
+ public static Vector128<byte> CompareExplicitLengthBitMask(Vector128<short> left, byte leftLength, Vector128<short> right, byte rightLength, StringComparisonMode mode) { throw null; }
+ public static Vector128<byte> CompareExplicitLengthBitMask(Vector128<ushort> left, byte leftLength, Vector128<ushort> right, byte rightLength, StringComparisonMode mode) { throw null; }
+ public static Vector128<byte> CompareExplicitLengthUnitMask(Vector128<sbyte> left, byte leftLength, Vector128<sbyte> right, byte rightLength, StringComparisonMode mode) { throw null; }
+ public static Vector128<byte> CompareExplicitLengthUnitMask(Vector128<byte> left, byte leftLength, Vector128<byte> right, byte rightLength, StringComparisonMode mode) { throw null; }
+ public static Vector128<ushort> CompareExplicitLengthUnitMask(Vector128<short> left, byte leftLength, Vector128<short> right, byte rightLength, StringComparisonMode mode) { throw null; }
+ public static Vector128<ushort> CompareExplicitLengthUnitMask(Vector128<ushort> left, byte leftLength, Vector128<ushort> right, byte rightLength, StringComparisonMode mode) { throw null; }
+ public static Vector128<long> CompareGreaterThan(Vector128<long> left, Vector128<long> right) { throw null; }
+ public static uint Crc32(uint crc, byte data) { throw null; }
+ public static uint Crc32(uint crc, ushort data) { throw null; }
+ public static uint Crc32(uint crc, uint data) { throw null; }
+ public static ulong Crc32(ulong crc, ulong data) { throw null; }
+ }
+ public static class Ssse3
+ {
+ public static bool IsSupported { get { throw null; } }
+ public static Vector128<byte> Abs(Vector128<sbyte> value) { throw null; }
+ public static Vector128<ushort> Abs(Vector128<short> value) { throw null; }
+ public static Vector128<uint> Abs(Vector128<int> value) { throw null; }
+ public static Vector128<sbyte> AlignRight(Vector128<sbyte> left, Vector128<sbyte> right, byte mask) { throw null; }
+ public static Vector128<short> HorizontalAdd(Vector128<short> left, Vector128<short> right) { throw null; }
+ public static Vector128<int> HorizontalAdd(Vector128<int> left, Vector128<int> right) { throw null; }
+ public static Vector128<short> HorizontalAddSaturate(Vector128<short> left, Vector128<short> right) { throw null; }
+ public static Vector128<short> HorizontalSubtract(Vector128<short> left, Vector128<short> right) { throw null; }
+ public static Vector128<int> HorizontalSubtract(Vector128<int> left, Vector128<int> right) { throw null; }
+ public static Vector128<short> HorizontalSubtractSaturate(Vector128<short> left, Vector128<short> right) { throw null; }
+ public static Vector128<short> MultiplyAddAdjacent(Vector128<byte> left, Vector128<sbyte> right) { throw null; }
+ public static Vector128<short> MultiplyHighRoundScale(Vector128<short> left, Vector128<short> right) { throw null; }
+ public static Vector128<sbyte> Shuffle(Vector128<sbyte> value, Vector128<sbyte> mask) { throw null; }
+ public static Vector128<sbyte> Sign(Vector128<sbyte> left, Vector128<sbyte> right) { throw null; }
+ public static Vector128<short> Sign(Vector128<short> left, Vector128<short> right) { throw null; }
+ public static Vector128<int> Sign(Vector128<int> left, Vector128<int> right) { throw null; }
+ }
+}
diff --git a/src/System.Runtime.Intrinsics.X86/ref/System.Runtime.Intrinsics.X86.csproj b/src/System.Runtime.Intrinsics.X86/ref/System.Runtime.Intrinsics.X86.csproj
new file mode 100644
index 0000000000..50432ac3c5
--- /dev/null
+++ b/src/System.Runtime.Intrinsics.X86/ref/System.Runtime.Intrinsics.X86.csproj
@@ -0,0 +1,17 @@
+<?xml version="1.0" encoding="utf-8"?>
+<Project ToolsVersion="14.0" DefaultTargets="Build" xmlns="http://schemas.microsoft.com/developer/msbuild/2003">
+ <Import Project="$([MSBuild]::GetDirectoryNameOfFileAbove($(MSBuildThisFileDirectory), dir.props))\dir.props" />
+ <PropertyGroup>
+ <AllowUnsafeBlocks>true</AllowUnsafeBlocks>
+ <ClsCompliant>false</ClsCompliant>
+ </PropertyGroup>
+ <PropertyGroup Condition="'$(Configuration)|$(Platform)' == 'netcoreapp-Debug|AnyCPU'" />
+ <PropertyGroup Condition="'$(Configuration)|$(Platform)' == 'netcoreapp-Release|AnyCPU'" />
+ <ItemGroup>
+ <Compile Include="System.Runtime.Intrinsics.X86.cs" />
+ </ItemGroup>
+ <ItemGroup>
+ <ProjectReference Include="..\..\System.Runtime\ref\System.Runtime.csproj" />
+ </ItemGroup>
+ <Import Project="$([MSBuild]::GetDirectoryNameOfFileAbove($(MSBuildThisFileDirectory), dir.targets))\dir.targets" />
+</Project> \ No newline at end of file
diff --git a/src/System.Runtime.Intrinsics.X86/src/Configurations.props b/src/System.Runtime.Intrinsics.X86/src/Configurations.props
new file mode 100644
index 0000000000..1040c9ba37
--- /dev/null
+++ b/src/System.Runtime.Intrinsics.X86/src/Configurations.props
@@ -0,0 +1,9 @@
+<?xml version="1.0" encoding="utf-8"?>
+<Project ToolsVersion="14.0" DefaultTargets="Build" xmlns="http://schemas.microsoft.com/developer/msbuild/2003">
+ <PropertyGroup>
+ <BuildConfigurations>
+ netcoreapp-Windows_NT;
+ netcoreapp-Unix;
+ </BuildConfigurations>
+ </PropertyGroup>
+</Project> \ No newline at end of file
diff --git a/src/System.Runtime.Intrinsics.X86/src/System.Runtime.Intrinsics.X86.csproj b/src/System.Runtime.Intrinsics.X86/src/System.Runtime.Intrinsics.X86.csproj
new file mode 100644
index 0000000000..361d1abfa5
--- /dev/null
+++ b/src/System.Runtime.Intrinsics.X86/src/System.Runtime.Intrinsics.X86.csproj
@@ -0,0 +1,16 @@
+<?xml version="1.0" encoding="utf-8"?>
+<Project ToolsVersion="14.0" DefaultTargets="Build" xmlns="http://schemas.microsoft.com/developer/msbuild/2003">
+ <Import Project="$([MSBuild]::GetDirectoryNameOfFileAbove($(MSBuildThisFileDirectory), dir.props))\dir.props" />
+ <PropertyGroup>
+ <AssemblyName>System.Runtime.Intrinsics.X86</AssemblyName>
+ <IsPartialFacadeAssembly>true</IsPartialFacadeAssembly>
+ </PropertyGroup>
+ <PropertyGroup Condition="'$(Configuration)|$(Platform)' == 'netcoreapp-Windows_NT-Debug|AnyCPU'" />
+ <PropertyGroup Condition="'$(Configuration)|$(Platform)' == 'netcoreapp-Windows_NT-Release|AnyCPU'" />
+ <PropertyGroup Condition="'$(Configuration)|$(Platform)' == 'netcoreapp-Unix-Debug|AnyCPU'" />
+ <PropertyGroup Condition="'$(Configuration)|$(Platform)' == 'netcoreapp-Unix-Release|AnyCPU'" />
+ <ItemGroup>
+ <ReferenceFromRuntime Include="System.Private.CoreLib" />
+ </ItemGroup>
+ <Import Project="$([MSBuild]::GetDirectoryNameOfFileAbove($(MSBuildThisFileDirectory), dir.targets))\dir.targets" />
+</Project>
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 6863d1c5d3..15e9701c2d 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
@@ -20,7 +20,7 @@
</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" />
+ <Move SourceFiles="$(TestPath)\System.Runtime.Loader.Noop.Assembly.dll" DestinationFiles="$(TestPath)\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/src/System/Numerics/BigInteger.cs b/src/System.Runtime.Numerics/src/System/Numerics/BigInteger.cs
index f12d5629ac..82ee609fe8 100644
--- a/src/System.Runtime.Numerics/src/System/Numerics/BigInteger.cs
+++ b/src/System.Runtime.Numerics/src/System/Numerics/BigInteger.cs
@@ -316,7 +316,6 @@ namespace System.Numerics
{
int unalignedBytes = byteCount % 4;
int dwordCount = byteCount / 4 + (unalignedBytes == 0 ? 0 : 1);
- bool isZero = true;
uint[] val = new uint[dwordCount];
// Copy all dwords, except but don't do the last one if it's not a full four bytes
@@ -326,7 +325,6 @@ namespace System.Numerics
for (int byteInDword = 0; byteInDword < 4; byteInDword++)
{
byte curByteValue = value[curByte];
- if (curByteValue != 0x00) isZero = false;
val[curDword] = (val[curDword] << 8) | curByteValue;
curByte--;
}
@@ -340,16 +338,11 @@ namespace System.Numerics
for (curByte = byteCount - 1; curByte >= byteCount - unalignedBytes; curByte--)
{
byte curByteValue = value[curByte];
- if (curByteValue != 0x00) isZero = false;
val[curDword] = (val[curDword] << 8) | curByteValue;
}
}
- if (isZero)
- {
- this = s_bnZeroInt;
- }
- else if (isNegative)
+ if (isNegative)
{
NumericsHelpers.DangerousMakeTwosComplement(val); // Mutates val
@@ -358,23 +351,32 @@ namespace System.Numerics
while (len >= 0 && val[len] == 0) len--;
len++;
- if (len == 1 && unchecked((int)(val[0])) > 0)
+ if (len == 1)
{
- if (val[0] == 1 /* abs(-1) */)
- {
- this = s_bnMinusOneInt;
- }
- else if (val[0] == kuMaskHighBit) // abs(Int32.MinValue)
+ switch (val[0])
{
- this = s_bnMinInt;
- }
- else
- {
- _sign = (-1) * ((int)val[0]);
- _bits = null;
+ case 1: // abs(-1)
+ this = s_bnMinusOneInt;
+ return;
+
+ case kuMaskHighBit: // abs(Int32.MinValue)
+ this = s_bnMinInt;
+ return;
+
+ default:
+ if (unchecked((int)val[0]) > 0)
+ {
+ _sign = (-1) * ((int)val[0]);
+ _bits = null;
+ AssertValid();
+ return;
+ }
+
+ break;
}
}
- else if (len != val.Length)
+
+ if (len != val.Length)
{
_sign = -1;
_bits = new uint[len];
diff --git a/src/System.Runtime.Numerics/tests/BigInteger/ctor.cs b/src/System.Runtime.Numerics/tests/BigInteger/ctor.cs
index d642efe456..e0d7ebbcff 100644
--- a/src/System.Runtime.Numerics/tests/BigInteger/ctor.cs
+++ b/src/System.Runtime.Numerics/tests/BigInteger/ctor.cs
@@ -891,6 +891,10 @@ namespace System.Numerics.Tests
// ctor(byte[]): array is UInt32.MaxValue + 1
VerifyCtorByteArray(new byte[] { 0, 0, 0, 0, 1 }, (UInt64)UInt32.MaxValue + 1);
+ // ctor(byte[]): array is Int32.MinValue with overlong representation.
+ VerifyCtorByteArray(new byte[] {0, 0, 0, 0x80, 0xFF});
+ Assert.Equal(new BigInteger(new byte[] { 0, 0, 0, 0x80, 0xFF, 0xFF, 0xFF }), int.MinValue);
+
// ctor(byte[]): array is UInt64.MaxValue
VerifyCtorByteArray(new byte[] { 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0 }, UInt64.MaxValue);
diff --git a/src/System.Runtime.Serialization.Formatters/tests/BinaryFormatterHelper.cs b/src/System.Runtime.Serialization.Formatters/tests/BinaryFormatterHelper.cs
deleted file mode 100644
index 0a329e90a2..0000000000
--- a/src/System.Runtime.Serialization.Formatters/tests/BinaryFormatterHelper.cs
+++ /dev/null
@@ -1,309 +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.Collections.Generic;
-using System.IO;
-using System.Linq;
-using System.Reflection;
-using System.Runtime.Serialization.Formatters.Binary;
-using System.Text;
-using System.Text.RegularExpressions;
-using Xunit;
-
-namespace System.Runtime.Serialization.Formatters.Tests
-{
- public partial class BinaryFormatterTests
- {
- private static void CheckForAnyEquals(object obj, object deserializedObj)
- {
- Assert.True(CheckEquals(obj, deserializedObj), "Error during equality check of type " + obj?.GetType()?.FullName);
- }
-
- public static bool CheckEquals(object objA, object objB)
- {
- if (objA == null && objB == null)
- return true;
-
- if (objA != null && objB != null)
- {
- object equalityResult = null;
- Type objType = objA.GetType();
-
- // Check if custom equality extension method is available
- MethodInfo customEqualityCheck = GetExtensionMethod(objType);
- if (customEqualityCheck != null)
- {
- equalityResult = customEqualityCheck.Invoke(objA, new object[] { objA, objB });
- }
- else
- {
- // Check if object.Equals(object) is overridden and if not check if there is a more concrete equality check implementation
- bool equalsNotOverridden = objType.GetMethod("Equals", new Type[] { typeof(object) }).DeclaringType == typeof(object);
- if (equalsNotOverridden)
- {
- // If type doesn't override Equals(object) method then check if there is a more concrete implementation
- // e.g. if type implements IEquatable<T>.
- MethodInfo equalsMethod = objType.GetMethod("Equals", new Type[] { objType });
- if (equalsMethod.DeclaringType != typeof(object))
- {
- equalityResult = equalsMethod.Invoke(objA, new object[] { objB });
- }
- }
- }
-
- if (equalityResult != null)
- {
- return (bool)equalityResult;
- }
- }
-
- if (objA is IEnumerable objAEnumerable && objB is IEnumerable objBEnumerable)
- {
- return CheckSequenceEquals(objAEnumerable, objBEnumerable);
- }
-
- return objA.Equals(objB);
- }
-
- public static bool CheckSequenceEquals(IEnumerable a, IEnumerable b)
- {
- if (a == null || b == null)
- return a == b;
-
- if (a.GetType() != b.GetType())
- return false;
-
- IEnumerator eA = null;
- IEnumerator eB = null;
-
- try
- {
- eA = (a as IEnumerable).GetEnumerator();
- eB = (a as IEnumerable).GetEnumerator();
- while (true)
- {
- bool moved = eA.MoveNext();
- if (moved != eB.MoveNext())
- return false;
- if (!moved)
- return true;
- if (eA.Current == null && eB.Current == null)
- return true;
- if (!CheckEquals(eA.Current, eB.Current))
- return true;
- }
- }
- finally
- {
- (eA as IDisposable)?.Dispose();
- (eB as IDisposable)?.Dispose();
- }
- }
-
- private static MethodInfo GetExtensionMethod(Type extendedType)
- {
- if (extendedType.IsGenericType)
- {
- MethodInfo method = typeof(EqualityExtensions).GetMethods()
- ?.SingleOrDefault(m =>
- m.Name == "IsEqual" &&
- m.GetParameters().Length == 2 &&
- m.GetParameters()[0].ParameterType.Name == extendedType.Name &&
- m.IsGenericMethodDefinition);
- if (method != null)
- return method.MakeGenericMethod(extendedType.GenericTypeArguments[0]);
- }
-
- return typeof(EqualityExtensions).GetMethod("IsEqual", new[] { extendedType, extendedType });
- }
-
- public static void ValidateEqualityComparer(object obj)
- {
- Type objType = obj.GetType();
- Assert.True(objType.IsGenericType, $"Type `{objType.FullName}` must be generic.");
- Assert.Equal("System.Collections.Generic.ObjectEqualityComparer`1", objType.GetGenericTypeDefinition().FullName);
- Assert.Equal(obj.GetType().GetGenericArguments()[0], objType.GetGenericArguments()[0]);
- }
-
- private static void SanityCheckBlob(object obj, string[] blobs)
- {
- // Check if runtime generated blob is the same as the stored one
- int frameworkBlobNumber = PlatformDetection.IsFullFramework ? 1 : 0;
- if (frameworkBlobNumber < blobs.Length &&
- // WeakReference<Point> and HybridDictionary with default constructor are generating
- // different blobs at runtime for some obscure reason. Excluding those from the check.
- !(obj is WeakReference<Point>) &&
- !(obj is Collections.Specialized.HybridDictionary) &&
- !(obj is TimeZoneInfo.AdjustmentRule))
- {
- string runtimeBlob = SerializeObjectToBlob(obj, FormatterAssemblyStyle.Full);
-
- string storedComparableBlob = CreateComparableBlobInfo(blobs[frameworkBlobNumber]);
- string runtimeComparableBlob = CreateComparableBlobInfo(runtimeBlob);
-
- Assert.True(storedComparableBlob == runtimeComparableBlob,
- $"The stored blob for type {obj.GetType().FullName} is outdated and needs to be updated.{Environment.NewLine}{Environment.NewLine}" +
- $"-------------------- Stored blob ---------------------{Environment.NewLine}" +
- $"Encoded: {blobs[frameworkBlobNumber]}{Environment.NewLine}" +
- $"Decoded: {storedComparableBlob}{Environment.NewLine}{Environment.NewLine}" +
- $"--------------- Runtime generated blob ---------------{Environment.NewLine}" +
- $"Encoded: {runtimeBlob}{Environment.NewLine}" +
- $"Decoded: {runtimeComparableBlob}");
- }
- }
-
- public static string GetTestDataFilePath()
- {
- string GetRepoRootPath()
- {
- var exeFile = new FileInfo(Assembly.GetExecutingAssembly().Location);
-
- DirectoryInfo root = exeFile.Directory;
- while (!Directory.Exists(Path.Combine(root.FullName, ".git")))
- {
- if (root.Parent == null)
- return null;
-
- root = root.Parent;
- }
-
- return root.FullName;
- }
-
- // Get path to binary formatter test data
- string repositoryRootPath = GetRepoRootPath();
- Assert.NotNull(repositoryRootPath);
- string testDataFilePath = Path.Combine(repositoryRootPath, "src", "System.Runtime.Serialization.Formatters", "tests", "BinaryFormatterTestData.cs");
- Assert.True(File.Exists(testDataFilePath));
-
- return testDataFilePath;
- }
-
- public static IEnumerable<object[]> GetCoreTypeRecords()
- {
- // Define all core type records here
- return SerializableEqualityComparers_MemberData()
- .Concat(SerializableObjects_MemberData());
- }
-
- public static IEnumerable<string> GetCoreTypeBlobs(IEnumerable<object[]> records, FormatterAssemblyStyle assemblyStyle)
- {
- foreach (object[] record in records)
- {
- yield return SerializeObjectToBlob(record[0], assemblyStyle);
- }
- }
-
- public static string CreateComparableBlobInfo(string base64Blob)
- {
- string lineSeparator = ((char)0x2028).ToString();
- string paragraphSeparator = ((char)0x2029).ToString();
-
- byte[] data = Convert.FromBase64String(base64Blob);
- base64Blob = Encoding.UTF8.GetString(data);
-
- return Regex.Replace(base64Blob, @"Version=\d.\d.\d.\d.", "Version=0.0.0.0", RegexOptions.Multiline)
- .Replace("\r\n", string.Empty)
- .Replace("\n", string.Empty)
- .Replace("\r", string.Empty)
- .Replace(lineSeparator, string.Empty)
- .Replace(paragraphSeparator, string.Empty);
- }
-
- public static (int blobs, int foundBlobs, int updatedBlobs) UpdateCoreTypeBlobs(string testDataFilePath, string[] blobs)
- {
- // Replace existing test data blobs with updated ones
- string[] testDataLines = File.ReadAllLines(testDataFilePath);
- List<string> updatedTestDataLines = new List<string>();
- int numberOfBlobs = 0;
- int numberOfFoundBlobs = 0;
- int numberOfUpdatedBlobs = 0;
-
- for (int i = 0; i < testDataLines.Length; i++)
- {
- string testDataLine = testDataLines[i];
- if (!testDataLine.Trim().StartsWith("yield") || numberOfBlobs >= blobs.Length)
- {
- updatedTestDataLines.Add(testDataLine);
- continue;
- }
-
- string pattern = null;
- string replacement = null;
- if (PlatformDetection.IsFullFramework)
- {
- pattern = ", \"AAEAAAD[^\"]+\"(?!,)";
- replacement = ", \"" + blobs[numberOfBlobs] + "\"";
- }
- else
- {
- pattern = "\"AAEAAAD[^\"]+\",";
- replacement = "\"" + blobs[numberOfBlobs] + "\",";
- }
-
- Regex regex = new Regex(pattern);
- Match match = regex.Match(testDataLine);
- if (match.Success)
- {
- numberOfFoundBlobs++;
- }
- string updatedLine = regex.Replace(testDataLine, replacement);
- if (testDataLine != updatedLine)
- {
- numberOfUpdatedBlobs++;
- }
- testDataLine = updatedLine;
-
- updatedTestDataLines.Add(testDataLine);
- numberOfBlobs++;
- }
-
- // Check if all blobs were recognized and write updates to file
- Assert.Equal(numberOfBlobs, blobs.Length);
- File.WriteAllLines(testDataFilePath, updatedTestDataLines);
-
- return (numberOfBlobs, numberOfFoundBlobs, numberOfUpdatedBlobs);
- }
-
- public static byte[] SerializeObjectToRaw(object obj, FormatterAssemblyStyle assemblyStyle)
- {
- BinaryFormatter bf = new BinaryFormatter();
- bf.AssemblyFormat = assemblyStyle;
- using (MemoryStream ms = new MemoryStream())
- {
- bf.Serialize(ms, obj);
- return ms.ToArray();
- }
- }
-
- public static string SerializeObjectToBlob(object obj, FormatterAssemblyStyle assemblyStyle)
- {
- byte[] raw = SerializeObjectToRaw(obj, assemblyStyle);
- return Convert.ToBase64String(raw);
- }
-
- public static object DeserializeRawToObject(byte[] raw, FormatterAssemblyStyle assemblyStyle)
- {
- var binaryFormatter = new BinaryFormatter();
- binaryFormatter.AssemblyFormat = assemblyStyle;
- using (var serializedStream = new MemoryStream(raw))
- {
- return binaryFormatter.Deserialize(serializedStream);
- }
- }
-
- public static object DeserializeBlobToObject(string base64Str, FormatterAssemblyStyle assemblyStyle)
- {
- byte[] raw = Convert.FromBase64String(base64Str);
- return DeserializeRawToObject(raw, assemblyStyle);
- }
-
- private class DelegateBinder : SerializationBinder
- {
- public Func<string, string, Type> BindToTypeDelegate = null;
- public override Type BindToType(string assemblyName, string typeName) => BindToTypeDelegate?.Invoke(assemblyName, typeName);
- }
- }
-}
diff --git a/src/System.Runtime.Serialization.Formatters/tests/BinaryFormatterTestData.cs b/src/System.Runtime.Serialization.Formatters/tests/BinaryFormatterTestData.cs
index 7ca062bfdc..54c78feee0 100644
--- a/src/System.Runtime.Serialization.Formatters/tests/BinaryFormatterTestData.cs
+++ b/src/System.Runtime.Serialization.Formatters/tests/BinaryFormatterTestData.cs
@@ -96,44 +96,13 @@ namespace System.Runtime.Serialization.Formatters.Tests
yield return new object[] { "minchar" + char.MinValue + "minchar", new string[] { "AAEAAAD/////AQAAAAAAAAAGAQAAAA9taW5jaGFyAG1pbmNoYXIL", "AAEAAAD/////AQAAAAAAAAAGAQAAAA9taW5jaGFyAG1pbmNoYXIL" } };
// Exceptions
- var exception = new Exception("Exception message", new Exception("Inner exception message"))
- {
- HelpLink = "http://msdn.microsoft.com",
- Source = "Exception_Class_Samples",
- };
- typeof(Exception)
- .GetField("_stackTraceString", BindingFlags.Instance | BindingFlags.NonPublic)
- .SetValue(exception, "StackTrace string...");
- typeof(Exception)
- .GetField("_HResult", BindingFlags.Instance | BindingFlags.NonPublic)
- .SetValue(exception, 1000);
- typeof(Exception)
- .GetField("_remoteStackTraceString", BindingFlags.Instance | BindingFlags.NonPublic)
- .SetValue(exception, "Remote StackTrace string...");
- exception.Data.Add("secret", true);
- exception.Data.Add(1, "one");
+ var exception = new Exception("Exception message", new Exception("Inner exception message"));
+ PopulateException(exception);
yield return new object[] { exception, new string[] { "AAEAAAD/////AQAAAAAAAAAEAQAAABBTeXN0ZW0uRXhjZXB0aW9uDAAAAAlDbGFzc05hbWUHTWVzc2FnZQREYXRhDklubmVyRXhjZXB0aW9uB0hlbHBVUkwQU3RhY2tUcmFjZVN0cmluZxZSZW1vdGVTdGFja1RyYWNlU3RyaW5nEFJlbW90ZVN0YWNrSW5kZXgPRXhjZXB0aW9uTWV0aG9kB0hSZXN1bHQGU291cmNlDVdhdHNvbkJ1Y2tldHMBAQMDAQEBAAEAAQcpU3lzdGVtLkNvbGxlY3Rpb25zLkxpc3REaWN0aW9uYXJ5SW50ZXJuYWwQU3lzdGVtLkV4Y2VwdGlvbggIAgYCAAAAEFN5c3RlbS5FeGNlcHRpb24GAwAAABFFeGNlcHRpb24gbWVzc2FnZQkEAAAACQUAAAAGBgAAABlodHRwOi8vbXNkbi5taWNyb3NvZnQuY29tBgcAAAAUU3RhY2tUcmFjZSBzdHJpbmcuLi4GCAAAABtSZW1vdGUgU3RhY2tUcmFjZSBzdHJpbmcuLi4AAAAACugDAAAGCQAAABdFeGNlcHRpb25fQ2xhc3NfU2FtcGxlcwoEBAAAAClTeXN0ZW0uQ29sbGVjdGlvbnMuTGlzdERpY3Rpb25hcnlJbnRlcm5hbAMAAAAEaGVhZAd2ZXJzaW9uBWNvdW50AwAAOFN5c3RlbS5Db2xsZWN0aW9ucy5MaXN0RGljdGlvbmFyeUludGVybmFsK0RpY3Rpb25hcnlOb2RlCAgJCgAAAAIAAAACAAAAAQUAAAABAAAACQIAAAAGDAAAABdJbm5lciBleGNlcHRpb24gbWVzc2FnZQoKCgoKAAAAAAoAFROACgoECgAAADhTeXN0ZW0uQ29sbGVjdGlvbnMuTGlzdERpY3Rpb25hcnlJbnRlcm5hbCtEaWN0aW9uYXJ5Tm9kZQMAAAADa2V5BXZhbHVlBG5leHQCAgM4U3lzdGVtLkNvbGxlY3Rpb25zLkxpc3REaWN0aW9uYXJ5SW50ZXJuYWwrRGljdGlvbmFyeU5vZGUGDQAAAAZzZWNyZXQIAQEJDgAAAAEOAAAACgAAAAgIAQAAAAYPAAAAA29uZQoL", "AAEAAAD/////AQAAAAAAAAAEAQAAABBTeXN0ZW0uRXhjZXB0aW9uDAAAAAlDbGFzc05hbWUHTWVzc2FnZQREYXRhDklubmVyRXhjZXB0aW9uB0hlbHBVUkwQU3RhY2tUcmFjZVN0cmluZxZSZW1vdGVTdGFja1RyYWNlU3RyaW5nEFJlbW90ZVN0YWNrSW5kZXgPRXhjZXB0aW9uTWV0aG9kB0hSZXN1bHQGU291cmNlDVdhdHNvbkJ1Y2tldHMBAQMDAQEBAAEAAQcpU3lzdGVtLkNvbGxlY3Rpb25zLkxpc3REaWN0aW9uYXJ5SW50ZXJuYWwQU3lzdGVtLkV4Y2VwdGlvbggIAgYCAAAAEFN5c3RlbS5FeGNlcHRpb24GAwAAABFFeGNlcHRpb24gbWVzc2FnZQkEAAAACQUAAAAGBgAAABlodHRwOi8vbXNkbi5taWNyb3NvZnQuY29tBgcAAAAUU3RhY2tUcmFjZSBzdHJpbmcuLi4GCAAAABtSZW1vdGUgU3RhY2tUcmFjZSBzdHJpbmcuLi4AAAAACugDAAAGCQAAABdFeGNlcHRpb25fQ2xhc3NfU2FtcGxlcwoEBAAAAClTeXN0ZW0uQ29sbGVjdGlvbnMuTGlzdERpY3Rpb25hcnlJbnRlcm5hbAMAAAAEaGVhZAd2ZXJzaW9uBWNvdW50AwAAOFN5c3RlbS5Db2xsZWN0aW9ucy5MaXN0RGljdGlvbmFyeUludGVybmFsK0RpY3Rpb25hcnlOb2RlCAgJCgAAAAIAAAACAAAAAQUAAAABAAAACQIAAAAGDAAAABdJbm5lciBleGNlcHRpb24gbWVzc2FnZQoKCgoKAAAAAAoAFROACgoECgAAADhTeXN0ZW0uQ29sbGVjdGlvbnMuTGlzdERpY3Rpb25hcnlJbnRlcm5hbCtEaWN0aW9uYXJ5Tm9kZQMAAAADa2V5BXZhbHVlBG5leHQCAgM4U3lzdGVtLkNvbGxlY3Rpb25zLkxpc3REaWN0aW9uYXJ5SW50ZXJuYWwrRGljdGlvbmFyeU5vZGUGDQAAAAZzZWNyZXQIAQEJDgAAAAEOAAAACgAAAAgIAQAAAAYPAAAAA29uZQoL" } };
- // TODO: Remove after corert AggregateException field is renamed. Issue #23520
- if (!PlatformDetection.IsNetNative)
- {
- var aggregatedException = new AggregateException("Aggregate exception message", new Exception("Exception message", new Exception("Inner exception message")))
- {
- HelpLink = "http://docs.microsoft.com",
- Source = "TestData",
- };
- typeof(Exception)
- .GetField("_stackTraceString", BindingFlags.Instance | BindingFlags.NonPublic)
- .SetValue(aggregatedException, "StackTrace string...");
- typeof(Exception)
- .GetField("_HResult", BindingFlags.Instance | BindingFlags.NonPublic)
- .SetValue(aggregatedException, 2000);
- typeof(Exception)
- .GetField("_remoteStackTraceString", BindingFlags.Instance | BindingFlags.NonPublic)
- .SetValue(aggregatedException, "Remote StackTrace string...");
- aggregatedException.Data.Add("two", 2);
- yield return new object[] { aggregatedException, new string[] { "AAEAAAD/////AQAAAAAAAAAEAQAAABlTeXN0ZW0uQWdncmVnYXRlRXhjZXB0aW9uDQAAAAlDbGFzc05hbWUHTWVzc2FnZQREYXRhDklubmVyRXhjZXB0aW9uB0hlbHBVUkwQU3RhY2tUcmFjZVN0cmluZxZSZW1vdGVTdGFja1RyYWNlU3RyaW5nEFJlbW90ZVN0YWNrSW5kZXgPRXhjZXB0aW9uTWV0aG9kB0hSZXN1bHQGU291cmNlDVdhdHNvbkJ1Y2tldHMPSW5uZXJFeGNlcHRpb25zAQEDAwEBAQABAAEHAylTeXN0ZW0uQ29sbGVjdGlvbnMuTGlzdERpY3Rpb25hcnlJbnRlcm5hbBBTeXN0ZW0uRXhjZXB0aW9uCAgCElN5c3RlbS5FeGNlcHRpb25bXQYCAAAAGVN5c3RlbS5BZ2dyZWdhdGVFeGNlcHRpb24GAwAAABtBZ2dyZWdhdGUgZXhjZXB0aW9uIG1lc3NhZ2UJBAAAAAkFAAAABgYAAAAZaHR0cDovL2RvY3MubWljcm9zb2Z0LmNvbQYHAAAAFFN0YWNrVHJhY2Ugc3RyaW5nLi4uBggAAAAbUmVtb3RlIFN0YWNrVHJhY2Ugc3RyaW5nLi4uAAAAAArQBwAABgkAAAAIVGVzdERhdGEKCQoAAAAEBAAAAClTeXN0ZW0uQ29sbGVjdGlvbnMuTGlzdERpY3Rpb25hcnlJbnRlcm5hbAMAAAAEaGVhZAd2ZXJzaW9uBWNvdW50AwAAOFN5c3RlbS5Db2xsZWN0aW9ucy5MaXN0RGljdGlvbmFyeUludGVybmFsK0RpY3Rpb25hcnlOb2RlCAgJCwAAAAEAAAABAAAABAUAAAAQU3lzdGVtLkV4Y2VwdGlvbgwAAAAJQ2xhc3NOYW1lB01lc3NhZ2UERGF0YQ5Jbm5lckV4Y2VwdGlvbgdIZWxwVVJMEFN0YWNrVHJhY2VTdHJpbmcWUmVtb3RlU3RhY2tUcmFjZVN0cmluZxBSZW1vdGVTdGFja0luZGV4D0V4Y2VwdGlvbk1ldGhvZAdIUmVzdWx0BlNvdXJjZQ1XYXRzb25CdWNrZXRzAQEDAwEBAQABAAEHHlN5c3RlbS5Db2xsZWN0aW9ucy5JRGljdGlvbmFyeRBTeXN0ZW0uRXhjZXB0aW9uCAgCBgwAAAAQU3lzdGVtLkV4Y2VwdGlvbgYNAAAAEUV4Y2VwdGlvbiBtZXNzYWdlCgkOAAAACgoKAAAAAAoAFROACgoHCgAAAAABAAAAAQAAAAMQU3lzdGVtLkV4Y2VwdGlvbgkFAAAABAsAAAA4U3lzdGVtLkNvbGxlY3Rpb25zLkxpc3REaWN0aW9uYXJ5SW50ZXJuYWwrRGljdGlvbmFyeU5vZGUDAAAAA2tleQV2YWx1ZQRuZXh0AgIDOFN5c3RlbS5Db2xsZWN0aW9ucy5MaXN0RGljdGlvbmFyeUludGVybmFsK0RpY3Rpb25hcnlOb2RlBhAAAAADdHdvCAgCAAAACgEOAAAABQAAAAkMAAAABhIAAAAXSW5uZXIgZXhjZXB0aW9uIG1lc3NhZ2UKCgoKCgAAAAAKABUTgAoKCw==", "AAEAAAD/////AQAAAAAAAAAEAQAAABlTeXN0ZW0uQWdncmVnYXRlRXhjZXB0aW9uDQAAAAlDbGFzc05hbWUHTWVzc2FnZQREYXRhDklubmVyRXhjZXB0aW9uB0hlbHBVUkwQU3RhY2tUcmFjZVN0cmluZxZSZW1vdGVTdGFja1RyYWNlU3RyaW5nEFJlbW90ZVN0YWNrSW5kZXgPRXhjZXB0aW9uTWV0aG9kB0hSZXN1bHQGU291cmNlDVdhdHNvbkJ1Y2tldHMPSW5uZXJFeGNlcHRpb25zAQEDAwEBAQABAAEHAylTeXN0ZW0uQ29sbGVjdGlvbnMuTGlzdERpY3Rpb25hcnlJbnRlcm5hbBBTeXN0ZW0uRXhjZXB0aW9uCAgCElN5c3RlbS5FeGNlcHRpb25bXQYCAAAAGVN5c3RlbS5BZ2dyZWdhdGVFeGNlcHRpb24GAwAAABtBZ2dyZWdhdGUgZXhjZXB0aW9uIG1lc3NhZ2UJBAAAAAkFAAAABgYAAAAZaHR0cDovL2RvY3MubWljcm9zb2Z0LmNvbQYHAAAAFFN0YWNrVHJhY2Ugc3RyaW5nLi4uBggAAAAbUmVtb3RlIFN0YWNrVHJhY2Ugc3RyaW5nLi4uAAAAAArQBwAABgkAAAAIVGVzdERhdGEKCQoAAAAEBAAAAClTeXN0ZW0uQ29sbGVjdGlvbnMuTGlzdERpY3Rpb25hcnlJbnRlcm5hbAMAAAAEaGVhZAd2ZXJzaW9uBWNvdW50AwAAOFN5c3RlbS5Db2xsZWN0aW9ucy5MaXN0RGljdGlvbmFyeUludGVybmFsK0RpY3Rpb25hcnlOb2RlCAgJCwAAAAEAAAABAAAABAUAAAAQU3lzdGVtLkV4Y2VwdGlvbgwAAAAJQ2xhc3NOYW1lB01lc3NhZ2UERGF0YQ5Jbm5lckV4Y2VwdGlvbgdIZWxwVVJMEFN0YWNrVHJhY2VTdHJpbmcWUmVtb3RlU3RhY2tUcmFjZVN0cmluZxBSZW1vdGVTdGFja0luZGV4D0V4Y2VwdGlvbk1ldGhvZAdIUmVzdWx0BlNvdXJjZQ1XYXRzb25CdWNrZXRzAQEDAwEBAQABAAEHHlN5c3RlbS5Db2xsZWN0aW9ucy5JRGljdGlvbmFyeRBTeXN0ZW0uRXhjZXB0aW9uCAgCBgwAAAAQU3lzdGVtLkV4Y2VwdGlvbgYNAAAAEUV4Y2VwdGlvbiBtZXNzYWdlCgkOAAAACgoKAAAAAAoAFROACgoHCgAAAAABAAAAAQAAAAMQU3lzdGVtLkV4Y2VwdGlvbgkFAAAABAsAAAA4U3lzdGVtLkNvbGxlY3Rpb25zLkxpc3REaWN0aW9uYXJ5SW50ZXJuYWwrRGljdGlvbmFyeU5vZGUDAAAAA2tleQV2YWx1ZQRuZXh0AgIDOFN5c3RlbS5Db2xsZWN0aW9ucy5MaXN0RGljdGlvbmFyeUludGVybmFsK0RpY3Rpb25hcnlOb2RlBhAAAAADdHdvCAgCAAAACgEOAAAABQAAAAkMAAAABhIAAAAXSW5uZXIgZXhjZXB0aW9uIG1lc3NhZ2UKCgoKCgAAAAAKABUTgAoKCw==" } };
- }
+ var aggregatedException = new AggregateException("Aggregate exception message", new Exception("Exception message", new Exception("Inner exception message")));
+ PopulateException(aggregatedException);
+ yield return new object[] { aggregatedException, new string[] { "AAEAAAD/////AQAAAAAAAAAEAQAAABlTeXN0ZW0uQWdncmVnYXRlRXhjZXB0aW9uDQAAAAlDbGFzc05hbWUHTWVzc2FnZQREYXRhDklubmVyRXhjZXB0aW9uB0hlbHBVUkwQU3RhY2tUcmFjZVN0cmluZxZSZW1vdGVTdGFja1RyYWNlU3RyaW5nEFJlbW90ZVN0YWNrSW5kZXgPRXhjZXB0aW9uTWV0aG9kB0hSZXN1bHQGU291cmNlDVdhdHNvbkJ1Y2tldHMPSW5uZXJFeGNlcHRpb25zAQEDAwEBAQABAAEHAylTeXN0ZW0uQ29sbGVjdGlvbnMuTGlzdERpY3Rpb25hcnlJbnRlcm5hbBBTeXN0ZW0uRXhjZXB0aW9uCAgCElN5c3RlbS5FeGNlcHRpb25bXQYCAAAAGVN5c3RlbS5BZ2dyZWdhdGVFeGNlcHRpb24GAwAAABtBZ2dyZWdhdGUgZXhjZXB0aW9uIG1lc3NhZ2UJBAAAAAkFAAAABgYAAAAZaHR0cDovL21zZG4ubWljcm9zb2Z0LmNvbQYHAAAAFFN0YWNrVHJhY2Ugc3RyaW5nLi4uBggAAAAbUmVtb3RlIFN0YWNrVHJhY2Ugc3RyaW5nLi4uAAAAAAroAwAABgkAAAAXRXhjZXB0aW9uX0NsYXNzX1NhbXBsZXMKCQoAAAAEBAAAAClTeXN0ZW0uQ29sbGVjdGlvbnMuTGlzdERpY3Rpb25hcnlJbnRlcm5hbAMAAAAEaGVhZAd2ZXJzaW9uBWNvdW50AwAAOFN5c3RlbS5Db2xsZWN0aW9ucy5MaXN0RGljdGlvbmFyeUludGVybmFsK0RpY3Rpb25hcnlOb2RlCAgJCwAAAAIAAAACAAAABAUAAAAQU3lzdGVtLkV4Y2VwdGlvbgwAAAAJQ2xhc3NOYW1lB01lc3NhZ2UERGF0YQ5Jbm5lckV4Y2VwdGlvbgdIZWxwVVJMEFN0YWNrVHJhY2VTdHJpbmcWUmVtb3RlU3RhY2tUcmFjZVN0cmluZxBSZW1vdGVTdGFja0luZGV4D0V4Y2VwdGlvbk1ldGhvZAdIUmVzdWx0BlNvdXJjZQ1XYXRzb25CdWNrZXRzAQEDAwEBAQABAAEHHlN5c3RlbS5Db2xsZWN0aW9ucy5JRGljdGlvbmFyeRBTeXN0ZW0uRXhjZXB0aW9uCAgCBgwAAAAQU3lzdGVtLkV4Y2VwdGlvbgYNAAAAEUV4Y2VwdGlvbiBtZXNzYWdlCgkOAAAACgoKAAAAAAoAFROACgoHCgAAAAABAAAAAQAAAAMQU3lzdGVtLkV4Y2VwdGlvbgkFAAAABAsAAAA4U3lzdGVtLkNvbGxlY3Rpb25zLkxpc3REaWN0aW9uYXJ5SW50ZXJuYWwrRGljdGlvbmFyeU5vZGUDAAAAA2tleQV2YWx1ZQRuZXh0AgIDOFN5c3RlbS5Db2xsZWN0aW9ucy5MaXN0RGljdGlvbmFyeUludGVybmFsK0RpY3Rpb25hcnlOb2RlBhAAAAAGc2VjcmV0CAEBCREAAAABDgAAAAUAAAAJDAAAAAYTAAAAF0lubmVyIGV4Y2VwdGlvbiBtZXNzYWdlCgoKCgoAAAAACgAVE4AKCgERAAAACwAAAAgIAQAAAAYUAAAAA29uZQoL", "AAEAAAD/////AQAAAAAAAAAEAQAAABlTeXN0ZW0uQWdncmVnYXRlRXhjZXB0aW9uDQAAAAlDbGFzc05hbWUHTWVzc2FnZQREYXRhDklubmVyRXhjZXB0aW9uB0hlbHBVUkwQU3RhY2tUcmFjZVN0cmluZxZSZW1vdGVTdGFja1RyYWNlU3RyaW5nEFJlbW90ZVN0YWNrSW5kZXgPRXhjZXB0aW9uTWV0aG9kB0hSZXN1bHQGU291cmNlDVdhdHNvbkJ1Y2tldHMPSW5uZXJFeGNlcHRpb25zAQEDAwEBAQABAAEHAylTeXN0ZW0uQ29sbGVjdGlvbnMuTGlzdERpY3Rpb25hcnlJbnRlcm5hbBBTeXN0ZW0uRXhjZXB0aW9uCAgCElN5c3RlbS5FeGNlcHRpb25bXQYCAAAAGVN5c3RlbS5BZ2dyZWdhdGVFeGNlcHRpb24GAwAAABtBZ2dyZWdhdGUgZXhjZXB0aW9uIG1lc3NhZ2UJBAAAAAkFAAAABgYAAAAZaHR0cDovL21zZG4ubWljcm9zb2Z0LmNvbQYHAAAAFFN0YWNrVHJhY2Ugc3RyaW5nLi4uBggAAAAbUmVtb3RlIFN0YWNrVHJhY2Ugc3RyaW5nLi4uAAAAAAroAwAABgkAAAAXRXhjZXB0aW9uX0NsYXNzX1NhbXBsZXMKCQoAAAAEBAAAAClTeXN0ZW0uQ29sbGVjdGlvbnMuTGlzdERpY3Rpb25hcnlJbnRlcm5hbAMAAAAEaGVhZAd2ZXJzaW9uBWNvdW50AwAAOFN5c3RlbS5Db2xsZWN0aW9ucy5MaXN0RGljdGlvbmFyeUludGVybmFsK0RpY3Rpb25hcnlOb2RlCAgJCwAAAAIAAAACAAAABAUAAAAQU3lzdGVtLkV4Y2VwdGlvbgwAAAAJQ2xhc3NOYW1lB01lc3NhZ2UERGF0YQ5Jbm5lckV4Y2VwdGlvbgdIZWxwVVJMEFN0YWNrVHJhY2VTdHJpbmcWUmVtb3RlU3RhY2tUcmFjZVN0cmluZxBSZW1vdGVTdGFja0luZGV4D0V4Y2VwdGlvbk1ldGhvZAdIUmVzdWx0BlNvdXJjZQ1XYXRzb25CdWNrZXRzAQEDAwEBAQABAAEHHlN5c3RlbS5Db2xsZWN0aW9ucy5JRGljdGlvbmFyeRBTeXN0ZW0uRXhjZXB0aW9uCAgCBgwAAAAQU3lzdGVtLkV4Y2VwdGlvbgYNAAAAEUV4Y2VwdGlvbiBtZXNzYWdlCgkOAAAACgoKAAAAAAoAFROACgoHCgAAAAABAAAAAQAAAAMQU3lzdGVtLkV4Y2VwdGlvbgkFAAAABAsAAAA4U3lzdGVtLkNvbGxlY3Rpb25zLkxpc3REaWN0aW9uYXJ5SW50ZXJuYWwrRGljdGlvbmFyeU5vZGUDAAAAA2tleQV2YWx1ZQRuZXh0AgIDOFN5c3RlbS5Db2xsZWN0aW9ucy5MaXN0RGljdGlvbmFyeUludGVybmFsK0RpY3Rpb25hcnlOb2RlBhAAAAAGc2VjcmV0CAEBCREAAAABDgAAAAUAAAAJDAAAAAYTAAAAF0lubmVyIGV4Y2VwdGlvbiBtZXNzYWdlCgoKCgoAAAAACgAVE4AKCgERAAAACwAAAAgIAQAAAAYUAAAAA29uZQoL" } };
// Enum values
yield return new object[] { DayOfWeek.Monday, new string[] { "AAEAAAD/////AQAAAAAAAAAEAQAAABBTeXN0ZW0uRGF5T2ZXZWVrAQAAAAd2YWx1ZV9fAAgBAAAACw==", "AAEAAAD/////AQAAAAAAAAAEAQAAABBTeXN0ZW0uRGF5T2ZXZWVrAQAAAAd2YWx1ZV9fAAgBAAAACw==" } };
@@ -247,6 +216,7 @@ namespace System.Runtime.Serialization.Formatters.Tests
dt2.Columns.Add("jfjfjf");
dt2.Rows.Add("ff1", "ff2");
dt2.Rows.Add("ooo", "sdflkjsdflkjsd");
+ dt2.Rows.Add("nullval", DBNull.Value);
dt2.Locale = CultureInfo.InvariantCulture;
var ds = new DataSet("DataSet123");
@@ -255,8 +225,8 @@ namespace System.Runtime.Serialization.Formatters.Tests
ds.Tables.Add(dt2);
yield return new object[] { dt1, new string[] { "AAEAAAD/////AQAAAAAAAAAMAgAAAE5TeXN0ZW0uRGF0YSwgVmVyc2lvbj00LjAuMC4wLCBDdWx0dXJlPW5ldXRyYWwsIFB1YmxpY0tleVRva2VuPWI3N2E1YzU2MTkzNGUwODkFAQAAABVTeXN0ZW0uRGF0YS5EYXRhVGFibGUDAAAAGURhdGFUYWJsZS5SZW1vdGluZ1ZlcnNpb24JWG1sU2NoZW1hC1htbERpZmZHcmFtAwEBDlN5c3RlbS5WZXJzaW9uAgAAAAkDAAAABgQAAADeBjw/eG1sIHZlcnNpb249IjEuMCIgZW5jb2Rpbmc9InV0Zi0xNiI/Pg0KPHhzOnNjaGVtYSB0YXJnZXROYW1lc3BhY2U9Im15bnMxIiB4bWxuczptc3Rucz0ibXluczEiIHhtbG5zPSJteW5zMSIgeG1sbnM6eHM9Imh0dHA6Ly93d3cudzMub3JnLzIwMDEvWE1MU2NoZW1hIiB4bWxuczptc2RhdGE9InVybjpzY2hlbWFzLW1pY3Jvc29mdC1jb206eG1sLW1zZGF0YSIgYXR0cmlidXRlRm9ybURlZmF1bHQ9InF1YWxpZmllZCIgZWxlbWVudEZvcm1EZWZhdWx0PSJxdWFsaWZpZWQiPg0KICA8eHM6ZWxlbWVudCBuYW1lPSJhYmMiIG1zZGF0YTpMb2NhbGU9IiI+DQogICAgPHhzOmNvbXBsZXhUeXBlPg0KICAgICAgPHhzOnNlcXVlbmNlPg0KICAgICAgICA8eHM6ZWxlbWVudCBuYW1lPSJjb2wxIiB0eXBlPSJ4czpzdHJpbmciIG1zZGF0YTp0YXJnZXROYW1lc3BhY2U9Im15bnMxIiBtaW5PY2N1cnM9IjAiIC8+DQogICAgICAgIDx4czplbGVtZW50IG5hbWU9ImNvbDIiIHR5cGU9InhzOnN0cmluZyIgbXNkYXRhOnRhcmdldE5hbWVzcGFjZT0ibXluczEiIG1pbk9jY3Vycz0iMCIgLz4NCiAgICAgIDwveHM6c2VxdWVuY2U+DQogICAgPC94czpjb21wbGV4VHlwZT4NCiAgPC94czplbGVtZW50Pg0KICA8eHM6ZWxlbWVudCBuYW1lPSJEYXRhU2V0MTIzIiBtc2RhdGE6SXNEYXRhU2V0PSJ0cnVlIiBtc2RhdGE6TWFpbkRhdGFUYWJsZT0ibXluczFfeDAwM0FfYWJjIiBtc2RhdGE6TG9jYWxlPSIiPg0KICAgIDx4czpjb21wbGV4VHlwZT4NCiAgICAgIDx4czpjaG9pY2UgbWluT2NjdXJzPSIwIiBtYXhPY2N1cnM9InVuYm91bmRlZCIgLz4NCiAgICA8L3hzOmNvbXBsZXhUeXBlPg0KICA8L3hzOmVsZW1lbnQ+DQo8L3hzOnNjaGVtYT4GBQAAANwDPGRpZmZncjpkaWZmZ3JhbSB4bWxuczptc2RhdGE9InVybjpzY2hlbWFzLW1pY3Jvc29mdC1jb206eG1sLW1zZGF0YSIgeG1sbnM6ZGlmZmdyPSJ1cm46c2NoZW1hcy1taWNyb3NvZnQtY29tOnhtbC1kaWZmZ3JhbS12MSI+DQogIDxEYXRhU2V0MTIzIHhtbG5zPSJteW5zMSI+DQogICAgPGFiYyBkaWZmZ3I6aWQ9ImFiYzEiIG1zZGF0YTpyb3dPcmRlcj0iMCIgZGlmZmdyOmhhc0NoYW5nZXM9Imluc2VydGVkIj4NCiAgICAgIDxjb2wxPmZvbzwvY29sMT4NCiAgICAgIDxjb2wyPmJhcjwvY29sMj4NCiAgICA8L2FiYz4NCiAgICA8YWJjIGRpZmZncjppZD0iYWJjMiIgbXNkYXRhOnJvd09yZGVyPSIxIiBkaWZmZ3I6aGFzQ2hhbmdlcz0iaW5zZXJ0ZWQiPg0KICAgICAgPGNvbDE+YXNkYXNkPC9jb2wxPg0KICAgICAgPGNvbDI+ZmZmZmZmZmZmPC9jb2wyPg0KICAgIDwvYWJjPg0KICA8L0RhdGFTZXQxMjM+DQo8L2RpZmZncjpkaWZmZ3JhbT4EAwAAAA5TeXN0ZW0uVmVyc2lvbgQAAAAGX01ham9yBl9NaW5vcgZfQnVpbGQJX1JldmlzaW9uAAAAAAgICAgCAAAAAAAAAP//////////Cw==", "AAEAAAD/////AQAAAAAAAAAMAgAAAE5TeXN0ZW0uRGF0YSwgVmVyc2lvbj00LjAuMC4wLCBDdWx0dXJlPW5ldXRyYWwsIFB1YmxpY0tleVRva2VuPWI3N2E1YzU2MTkzNGUwODkFAQAAABVTeXN0ZW0uRGF0YS5EYXRhVGFibGUDAAAAGURhdGFUYWJsZS5SZW1vdGluZ1ZlcnNpb24JWG1sU2NoZW1hC1htbERpZmZHcmFtAwEBDlN5c3RlbS5WZXJzaW9uAgAAAAkDAAAABgQAAADeBjw/eG1sIHZlcnNpb249IjEuMCIgZW5jb2Rpbmc9InV0Zi0xNiI/Pg0KPHhzOnNjaGVtYSB0YXJnZXROYW1lc3BhY2U9Im15bnMxIiB4bWxuczptc3Rucz0ibXluczEiIHhtbG5zPSJteW5zMSIgeG1sbnM6eHM9Imh0dHA6Ly93d3cudzMub3JnLzIwMDEvWE1MU2NoZW1hIiB4bWxuczptc2RhdGE9InVybjpzY2hlbWFzLW1pY3Jvc29mdC1jb206eG1sLW1zZGF0YSIgYXR0cmlidXRlRm9ybURlZmF1bHQ9InF1YWxpZmllZCIgZWxlbWVudEZvcm1EZWZhdWx0PSJxdWFsaWZpZWQiPg0KICA8eHM6ZWxlbWVudCBuYW1lPSJhYmMiIG1zZGF0YTpMb2NhbGU9IiI+DQogICAgPHhzOmNvbXBsZXhUeXBlPg0KICAgICAgPHhzOnNlcXVlbmNlPg0KICAgICAgICA8eHM6ZWxlbWVudCBuYW1lPSJjb2wxIiB0eXBlPSJ4czpzdHJpbmciIG1zZGF0YTp0YXJnZXROYW1lc3BhY2U9Im15bnMxIiBtaW5PY2N1cnM9IjAiIC8+DQogICAgICAgIDx4czplbGVtZW50IG5hbWU9ImNvbDIiIHR5cGU9InhzOnN0cmluZyIgbXNkYXRhOnRhcmdldE5hbWVzcGFjZT0ibXluczEiIG1pbk9jY3Vycz0iMCIgLz4NCiAgICAgIDwveHM6c2VxdWVuY2U+DQogICAgPC94czpjb21wbGV4VHlwZT4NCiAgPC94czplbGVtZW50Pg0KICA8eHM6ZWxlbWVudCBuYW1lPSJEYXRhU2V0MTIzIiBtc2RhdGE6SXNEYXRhU2V0PSJ0cnVlIiBtc2RhdGE6TWFpbkRhdGFUYWJsZT0ibXluczFfeDAwM0FfYWJjIiBtc2RhdGE6TG9jYWxlPSIiPg0KICAgIDx4czpjb21wbGV4VHlwZT4NCiAgICAgIDx4czpjaG9pY2UgbWluT2NjdXJzPSIwIiBtYXhPY2N1cnM9InVuYm91bmRlZCIgLz4NCiAgICA8L3hzOmNvbXBsZXhUeXBlPg0KICA8L3hzOmVsZW1lbnQ+DQo8L3hzOnNjaGVtYT4GBQAAANwDPGRpZmZncjpkaWZmZ3JhbSB4bWxuczptc2RhdGE9InVybjpzY2hlbWFzLW1pY3Jvc29mdC1jb206eG1sLW1zZGF0YSIgeG1sbnM6ZGlmZmdyPSJ1cm46c2NoZW1hcy1taWNyb3NvZnQtY29tOnhtbC1kaWZmZ3JhbS12MSI+DQogIDxEYXRhU2V0MTIzIHhtbG5zPSJteW5zMSI+DQogICAgPGFiYyBkaWZmZ3I6aWQ9ImFiYzEiIG1zZGF0YTpyb3dPcmRlcj0iMCIgZGlmZmdyOmhhc0NoYW5nZXM9Imluc2VydGVkIj4NCiAgICAgIDxjb2wxPmZvbzwvY29sMT4NCiAgICAgIDxjb2wyPmJhcjwvY29sMj4NCiAgICA8L2FiYz4NCiAgICA8YWJjIGRpZmZncjppZD0iYWJjMiIgbXNkYXRhOnJvd09yZGVyPSIxIiBkaWZmZ3I6aGFzQ2hhbmdlcz0iaW5zZXJ0ZWQiPg0KICAgICAgPGNvbDE+YXNkYXNkPC9jb2wxPg0KICAgICAgPGNvbDI+ZmZmZmZmZmZmPC9jb2wyPg0KICAgIDwvYWJjPg0KICA8L0RhdGFTZXQxMjM+DQo8L2RpZmZncjpkaWZmZ3JhbT4EAwAAAA5TeXN0ZW0uVmVyc2lvbgQAAAAGX01ham9yBl9NaW5vcgZfQnVpbGQJX1JldmlzaW9uAAAAAAgICAgCAAAAAAAAAP//////////Cw==" } };
- yield return new object[] { dt2, new string[] { "AAEAAAD/////AQAAAAAAAAAMAgAAAE5TeXN0ZW0uRGF0YSwgVmVyc2lvbj00LjAuMC4wLCBDdWx0dXJlPW5ldXRyYWwsIFB1YmxpY0tleVRva2VuPWI3N2E1YzU2MTkzNGUwODkFAQAAABVTeXN0ZW0uRGF0YS5EYXRhVGFibGUDAAAAGURhdGFUYWJsZS5SZW1vdGluZ1ZlcnNpb24JWG1sU2NoZW1hC1htbERpZmZHcmFtAwEBDlN5c3RlbS5WZXJzaW9uAgAAAAkDAAAABgQAAADeBTw/eG1sIHZlcnNpb249IjEuMCIgZW5jb2Rpbmc9InV0Zi0xNiI/Pg0KPHhzOnNjaGVtYSB4bWxucz0iIiB4bWxuczp4cz0iaHR0cDovL3d3dy53My5vcmcvMjAwMS9YTUxTY2hlbWEiIHhtbG5zOm1zZGF0YT0idXJuOnNjaGVtYXMtbWljcm9zb2Z0LWNvbTp4bWwtbXNkYXRhIj4NCiAgPHhzOmVsZW1lbnQgbmFtZT0ic2Rmc2RmIiBtc2RhdGE6TG9jYWxlPSIiPg0KICAgIDx4czpjb21wbGV4VHlwZT4NCiAgICAgIDx4czpzZXF1ZW5jZT4NCiAgICAgICAgPHhzOmVsZW1lbnQgbmFtZT0ia2trIiB0eXBlPSJ4czpzdHJpbmciIG1zZGF0YTp0YXJnZXROYW1lc3BhY2U9IiIgbWluT2NjdXJzPSIwIiAvPg0KICAgICAgICA8eHM6ZWxlbWVudCBuYW1lPSJqZmpmamYiIHR5cGU9InhzOnN0cmluZyIgbXNkYXRhOnRhcmdldE5hbWVzcGFjZT0iIiBtaW5PY2N1cnM9IjAiIC8+DQogICAgICA8L3hzOnNlcXVlbmNlPg0KICAgIDwveHM6Y29tcGxleFR5cGU+DQogIDwveHM6ZWxlbWVudD4NCiAgPHhzOmVsZW1lbnQgbmFtZT0iRGF0YVNldDEyMyIgbXNkYXRhOklzRGF0YVNldD0idHJ1ZSIgbXNkYXRhOk1haW5EYXRhVGFibGU9InNkZnNkZiIgbXNkYXRhOkxvY2FsZT0iIj4NCiAgICA8eHM6Y29tcGxleFR5cGU+DQogICAgICA8eHM6Y2hvaWNlIG1pbk9jY3Vycz0iMCIgbWF4T2NjdXJzPSJ1bmJvdW5kZWQiIC8+DQogICAgPC94czpjb21wbGV4VHlwZT4NCiAgPC94czplbGVtZW50Pg0KPC94czpzY2hlbWE+BgUAAADmAzxkaWZmZ3I6ZGlmZmdyYW0geG1sbnM6bXNkYXRhPSJ1cm46c2NoZW1hcy1taWNyb3NvZnQtY29tOnhtbC1tc2RhdGEiIHhtbG5zOmRpZmZncj0idXJuOnNjaGVtYXMtbWljcm9zb2Z0LWNvbTp4bWwtZGlmZmdyYW0tdjEiPg0KICA8RGF0YVNldDEyMz4NCiAgICA8c2Rmc2RmIGRpZmZncjppZD0ic2Rmc2RmMSIgbXNkYXRhOnJvd09yZGVyPSIwIiBkaWZmZ3I6aGFzQ2hhbmdlcz0iaW5zZXJ0ZWQiPg0KICAgICAgPGtraz5mZjE8L2traz4NCiAgICAgIDxqZmpmamY+ZmYyPC9qZmpmamY+DQogICAgPC9zZGZzZGY+DQogICAgPHNkZnNkZiBkaWZmZ3I6aWQ9InNkZnNkZjIiIG1zZGF0YTpyb3dPcmRlcj0iMSIgZGlmZmdyOmhhc0NoYW5nZXM9Imluc2VydGVkIj4NCiAgICAgIDxra2s+b29vPC9ra2s+DQogICAgICA8amZqZmpmPnNkZmxranNkZmxranNkPC9qZmpmamY+DQogICAgPC9zZGZzZGY+DQogIDwvRGF0YVNldDEyMz4NCjwvZGlmZmdyOmRpZmZncmFtPgQDAAAADlN5c3RlbS5WZXJzaW9uBAAAAAZfTWFqb3IGX01pbm9yBl9CdWlsZAlfUmV2aXNpb24AAAAACAgICAIAAAAAAAAA//////////8L", "AAEAAAD/////AQAAAAAAAAAMAgAAAE5TeXN0ZW0uRGF0YSwgVmVyc2lvbj00LjAuMC4wLCBDdWx0dXJlPW5ldXRyYWwsIFB1YmxpY0tleVRva2VuPWI3N2E1YzU2MTkzNGUwODkFAQAAABVTeXN0ZW0uRGF0YS5EYXRhVGFibGUDAAAAGURhdGFUYWJsZS5SZW1vdGluZ1ZlcnNpb24JWG1sU2NoZW1hC1htbERpZmZHcmFtAwEBDlN5c3RlbS5WZXJzaW9uAgAAAAkDAAAABgQAAADeBTw/eG1sIHZlcnNpb249IjEuMCIgZW5jb2Rpbmc9InV0Zi0xNiI/Pg0KPHhzOnNjaGVtYSB4bWxucz0iIiB4bWxuczp4cz0iaHR0cDovL3d3dy53My5vcmcvMjAwMS9YTUxTY2hlbWEiIHhtbG5zOm1zZGF0YT0idXJuOnNjaGVtYXMtbWljcm9zb2Z0LWNvbTp4bWwtbXNkYXRhIj4NCiAgPHhzOmVsZW1lbnQgbmFtZT0ic2Rmc2RmIiBtc2RhdGE6TG9jYWxlPSIiPg0KICAgIDx4czpjb21wbGV4VHlwZT4NCiAgICAgIDx4czpzZXF1ZW5jZT4NCiAgICAgICAgPHhzOmVsZW1lbnQgbmFtZT0ia2trIiB0eXBlPSJ4czpzdHJpbmciIG1zZGF0YTp0YXJnZXROYW1lc3BhY2U9IiIgbWluT2NjdXJzPSIwIiAvPg0KICAgICAgICA8eHM6ZWxlbWVudCBuYW1lPSJqZmpmamYiIHR5cGU9InhzOnN0cmluZyIgbXNkYXRhOnRhcmdldE5hbWVzcGFjZT0iIiBtaW5PY2N1cnM9IjAiIC8+DQogICAgICA8L3hzOnNlcXVlbmNlPg0KICAgIDwveHM6Y29tcGxleFR5cGU+DQogIDwveHM6ZWxlbWVudD4NCiAgPHhzOmVsZW1lbnQgbmFtZT0iRGF0YVNldDEyMyIgbXNkYXRhOklzRGF0YVNldD0idHJ1ZSIgbXNkYXRhOk1haW5EYXRhVGFibGU9InNkZnNkZiIgbXNkYXRhOkxvY2FsZT0iIj4NCiAgICA8eHM6Y29tcGxleFR5cGU+DQogICAgICA8eHM6Y2hvaWNlIG1pbk9jY3Vycz0iMCIgbWF4T2NjdXJzPSJ1bmJvdW5kZWQiIC8+DQogICAgPC94czpjb21wbGV4VHlwZT4NCiAgPC94czplbGVtZW50Pg0KPC94czpzY2hlbWE+BgUAAADmAzxkaWZmZ3I6ZGlmZmdyYW0geG1sbnM6bXNkYXRhPSJ1cm46c2NoZW1hcy1taWNyb3NvZnQtY29tOnhtbC1tc2RhdGEiIHhtbG5zOmRpZmZncj0idXJuOnNjaGVtYXMtbWljcm9zb2Z0LWNvbTp4bWwtZGlmZmdyYW0tdjEiPg0KICA8RGF0YVNldDEyMz4NCiAgICA8c2Rmc2RmIGRpZmZncjppZD0ic2Rmc2RmMSIgbXNkYXRhOnJvd09yZGVyPSIwIiBkaWZmZ3I6aGFzQ2hhbmdlcz0iaW5zZXJ0ZWQiPg0KICAgICAgPGtraz5mZjE8L2traz4NCiAgICAgIDxqZmpmamY+ZmYyPC9qZmpmamY+DQogICAgPC9zZGZzZGY+DQogICAgPHNkZnNkZiBkaWZmZ3I6aWQ9InNkZnNkZjIiIG1zZGF0YTpyb3dPcmRlcj0iMSIgZGlmZmdyOmhhc0NoYW5nZXM9Imluc2VydGVkIj4NCiAgICAgIDxra2s+b29vPC9ra2s+DQogICAgICA8amZqZmpmPnNkZmxranNkZmxranNkPC9qZmpmamY+DQogICAgPC9zZGZzZGY+DQogIDwvRGF0YVNldDEyMz4NCjwvZGlmZmdyOmRpZmZncmFtPgQDAAAADlN5c3RlbS5WZXJzaW9uBAAAAAZfTWFqb3IGX01pbm9yBl9CdWlsZAlfUmV2aXNpb24AAAAACAgICAIAAAAAAAAA//////////8L" } };
- yield return new object[] { ds, new string[] { "AAEAAAD/////AQAAAAAAAAAMAgAAAE5TeXN0ZW0uRGF0YSwgVmVyc2lvbj00LjAuMC4wLCBDdWx0dXJlPW5ldXRyYWwsIFB1YmxpY0tleVRva2VuPWI3N2E1YzU2MTkzNGUwODkFAQAAABNTeXN0ZW0uRGF0YS5EYXRhU2V0AwAAABdEYXRhU2V0LlJlbW90aW5nVmVyc2lvbglYbWxTY2hlbWELWG1sRGlmZkdyYW0DAQEOU3lzdGVtLlZlcnNpb24CAAAACQMAAAAGBAAAALoJPD94bWwgdmVyc2lvbj0iMS4wIiBlbmNvZGluZz0idXRmLTE2Ij8+DQo8eHM6c2NoZW1hIGlkPSJEYXRhU2V0MTIzIiB4bWxucz0iIiB4bWxuczp4cz0iaHR0cDovL3d3dy53My5vcmcvMjAwMS9YTUxTY2hlbWEiIHhtbG5zOm1zZGF0YT0idXJuOnNjaGVtYXMtbWljcm9zb2Z0LWNvbTp4bWwtbXNkYXRhIj4NCiAgPHhzOmVsZW1lbnQgbmFtZT0iRGF0YVNldDEyMyIgbXNkYXRhOklzRGF0YVNldD0idHJ1ZSIgbXNkYXRhOkxvY2FsZT0iIj4NCiAgICA8eHM6Y29tcGxleFR5cGU+DQogICAgICA8eHM6Y2hvaWNlIG1pbk9jY3Vycz0iMCIgbWF4T2NjdXJzPSJ1bmJvdW5kZWQiPg0KICAgICAgICA8eHM6ZWxlbWVudCBtc2RhdGE6dGFyZ2V0TmFtZXNwYWNlPSJteW5zMSIgbmFtZT0iYWJjIiBtc2RhdGE6TG9jYWxlPSIiPg0KICAgICAgICAgIDx4czpjb21wbGV4VHlwZT4NCiAgICAgICAgICAgIDx4czpzZXF1ZW5jZT4NCiAgICAgICAgICAgICAgPHhzOmVsZW1lbnQgbmFtZT0iY29sMSIgdHlwZT0ieHM6c3RyaW5nIiBtc2RhdGE6dGFyZ2V0TmFtZXNwYWNlPSJteW5zMSIgbWluT2NjdXJzPSIwIiAvPg0KICAgICAgICAgICAgICA8eHM6ZWxlbWVudCBuYW1lPSJjb2wyIiB0eXBlPSJ4czpzdHJpbmciIG1zZGF0YTp0YXJnZXROYW1lc3BhY2U9Im15bnMxIiBtaW5PY2N1cnM9IjAiIC8+DQogICAgICAgICAgICA8L3hzOnNlcXVlbmNlPg0KICAgICAgICAgIDwveHM6Y29tcGxleFR5cGU+DQogICAgICAgIDwveHM6ZWxlbWVudD4NCiAgICAgICAgPHhzOmVsZW1lbnQgbmFtZT0ic2Rmc2RmIiBtc2RhdGE6TG9jYWxlPSIiPg0KICAgICAgICAgIDx4czpjb21wbGV4VHlwZT4NCiAgICAgICAgICAgIDx4czpzZXF1ZW5jZT4NCiAgICAgICAgICAgICAgPHhzOmVsZW1lbnQgbmFtZT0ia2trIiB0eXBlPSJ4czpzdHJpbmciIG1zZGF0YTp0YXJnZXROYW1lc3BhY2U9IiIgbWluT2NjdXJzPSIwIiAvPg0KICAgICAgICAgICAgICA8eHM6ZWxlbWVudCBuYW1lPSJqZmpmamYiIHR5cGU9InhzOnN0cmluZyIgbXNkYXRhOnRhcmdldE5hbWVzcGFjZT0iIiBtaW5PY2N1cnM9IjAiIC8+DQogICAgICAgICAgICA8L3hzOnNlcXVlbmNlPg0KICAgICAgICAgIDwveHM6Y29tcGxleFR5cGU+DQogICAgICAgIDwveHM6ZWxlbWVudD4NCiAgICAgIDwveHM6Y2hvaWNlPg0KICAgIDwveHM6Y29tcGxleFR5cGU+DQogIDwveHM6ZWxlbWVudD4NCjwveHM6c2NoZW1hPgYFAAAAowU8ZGlmZmdyOmRpZmZncmFtIHhtbG5zOm1zZGF0YT0idXJuOnNjaGVtYXMtbWljcm9zb2Z0LWNvbTp4bWwtbXNkYXRhIiB4bWxuczpkaWZmZ3I9InVybjpzY2hlbWFzLW1pY3Jvc29mdC1jb206eG1sLWRpZmZncmFtLXYxIj48RGF0YVNldDEyMz48YWJjIGRpZmZncjppZD0iYWJjMSIgbXNkYXRhOnJvd09yZGVyPSIwIiBkaWZmZ3I6aGFzQ2hhbmdlcz0iaW5zZXJ0ZWQiIHhtbG5zPSJteW5zMSI+PGNvbDE+Zm9vPC9jb2wxPjxjb2wyPmJhcjwvY29sMj48L2FiYz48YWJjIGRpZmZncjppZD0iYWJjMiIgbXNkYXRhOnJvd09yZGVyPSIxIiBkaWZmZ3I6aGFzQ2hhbmdlcz0iaW5zZXJ0ZWQiIHhtbG5zPSJteW5zMSI+PGNvbDE+YXNkYXNkPC9jb2wxPjxjb2wyPmZmZmZmZmZmZjwvY29sMj48L2FiYz48c2Rmc2RmIGRpZmZncjppZD0ic2Rmc2RmMSIgbXNkYXRhOnJvd09yZGVyPSIwIiBkaWZmZ3I6aGFzQ2hhbmdlcz0iaW5zZXJ0ZWQiPjxra2s+ZmYxPC9ra2s+PGpmamZqZj5mZjI8L2pmamZqZj48L3NkZnNkZj48c2Rmc2RmIGRpZmZncjppZD0ic2Rmc2RmMiIgbXNkYXRhOnJvd09yZGVyPSIxIiBkaWZmZ3I6aGFzQ2hhbmdlcz0iaW5zZXJ0ZWQiPjxra2s+b29vPC9ra2s+PGpmamZqZj5zZGZsa2pzZGZsa2pzZDwvamZqZmpmPjwvc2Rmc2RmPjwvRGF0YVNldDEyMz48L2RpZmZncjpkaWZmZ3JhbT4EAwAAAA5TeXN0ZW0uVmVyc2lvbgQAAAAGX01ham9yBl9NaW5vcgZfQnVpbGQJX1JldmlzaW9uAAAAAAgICAgCAAAAAAAAAP//////////Cw==", "AAEAAAD/////AQAAAAAAAAAMAgAAAE5TeXN0ZW0uRGF0YSwgVmVyc2lvbj00LjAuMC4wLCBDdWx0dXJlPW5ldXRyYWwsIFB1YmxpY0tleVRva2VuPWI3N2E1YzU2MTkzNGUwODkFAQAAABNTeXN0ZW0uRGF0YS5EYXRhU2V0AwAAABdEYXRhU2V0LlJlbW90aW5nVmVyc2lvbglYbWxTY2hlbWELWG1sRGlmZkdyYW0DAQEOU3lzdGVtLlZlcnNpb24CAAAACQMAAAAGBAAAALoJPD94bWwgdmVyc2lvbj0iMS4wIiBlbmNvZGluZz0idXRmLTE2Ij8+DQo8eHM6c2NoZW1hIGlkPSJEYXRhU2V0MTIzIiB4bWxucz0iIiB4bWxuczp4cz0iaHR0cDovL3d3dy53My5vcmcvMjAwMS9YTUxTY2hlbWEiIHhtbG5zOm1zZGF0YT0idXJuOnNjaGVtYXMtbWljcm9zb2Z0LWNvbTp4bWwtbXNkYXRhIj4NCiAgPHhzOmVsZW1lbnQgbmFtZT0iRGF0YVNldDEyMyIgbXNkYXRhOklzRGF0YVNldD0idHJ1ZSIgbXNkYXRhOkxvY2FsZT0iIj4NCiAgICA8eHM6Y29tcGxleFR5cGU+DQogICAgICA8eHM6Y2hvaWNlIG1pbk9jY3Vycz0iMCIgbWF4T2NjdXJzPSJ1bmJvdW5kZWQiPg0KICAgICAgICA8eHM6ZWxlbWVudCBtc2RhdGE6dGFyZ2V0TmFtZXNwYWNlPSJteW5zMSIgbmFtZT0iYWJjIiBtc2RhdGE6TG9jYWxlPSIiPg0KICAgICAgICAgIDx4czpjb21wbGV4VHlwZT4NCiAgICAgICAgICAgIDx4czpzZXF1ZW5jZT4NCiAgICAgICAgICAgICAgPHhzOmVsZW1lbnQgbmFtZT0iY29sMSIgdHlwZT0ieHM6c3RyaW5nIiBtc2RhdGE6dGFyZ2V0TmFtZXNwYWNlPSJteW5zMSIgbWluT2NjdXJzPSIwIiAvPg0KICAgICAgICAgICAgICA8eHM6ZWxlbWVudCBuYW1lPSJjb2wyIiB0eXBlPSJ4czpzdHJpbmciIG1zZGF0YTp0YXJnZXROYW1lc3BhY2U9Im15bnMxIiBtaW5PY2N1cnM9IjAiIC8+DQogICAgICAgICAgICA8L3hzOnNlcXVlbmNlPg0KICAgICAgICAgIDwveHM6Y29tcGxleFR5cGU+DQogICAgICAgIDwveHM6ZWxlbWVudD4NCiAgICAgICAgPHhzOmVsZW1lbnQgbmFtZT0ic2Rmc2RmIiBtc2RhdGE6TG9jYWxlPSIiPg0KICAgICAgICAgIDx4czpjb21wbGV4VHlwZT4NCiAgICAgICAgICAgIDx4czpzZXF1ZW5jZT4NCiAgICAgICAgICAgICAgPHhzOmVsZW1lbnQgbmFtZT0ia2trIiB0eXBlPSJ4czpzdHJpbmciIG1zZGF0YTp0YXJnZXROYW1lc3BhY2U9IiIgbWluT2NjdXJzPSIwIiAvPg0KICAgICAgICAgICAgICA8eHM6ZWxlbWVudCBuYW1lPSJqZmpmamYiIHR5cGU9InhzOnN0cmluZyIgbXNkYXRhOnRhcmdldE5hbWVzcGFjZT0iIiBtaW5PY2N1cnM9IjAiIC8+DQogICAgICAgICAgICA8L3hzOnNlcXVlbmNlPg0KICAgICAgICAgIDwveHM6Y29tcGxleFR5cGU+DQogICAgICAgIDwveHM6ZWxlbWVudD4NCiAgICAgIDwveHM6Y2hvaWNlPg0KICAgIDwveHM6Y29tcGxleFR5cGU+DQogIDwveHM6ZWxlbWVudD4NCjwveHM6c2NoZW1hPgYFAAAAowU8ZGlmZmdyOmRpZmZncmFtIHhtbG5zOm1zZGF0YT0idXJuOnNjaGVtYXMtbWljcm9zb2Z0LWNvbTp4bWwtbXNkYXRhIiB4bWxuczpkaWZmZ3I9InVybjpzY2hlbWFzLW1pY3Jvc29mdC1jb206eG1sLWRpZmZncmFtLXYxIj48RGF0YVNldDEyMz48YWJjIGRpZmZncjppZD0iYWJjMSIgbXNkYXRhOnJvd09yZGVyPSIwIiBkaWZmZ3I6aGFzQ2hhbmdlcz0iaW5zZXJ0ZWQiIHhtbG5zPSJteW5zMSI+PGNvbDE+Zm9vPC9jb2wxPjxjb2wyPmJhcjwvY29sMj48L2FiYz48YWJjIGRpZmZncjppZD0iYWJjMiIgbXNkYXRhOnJvd09yZGVyPSIxIiBkaWZmZ3I6aGFzQ2hhbmdlcz0iaW5zZXJ0ZWQiIHhtbG5zPSJteW5zMSI+PGNvbDE+YXNkYXNkPC9jb2wxPjxjb2wyPmZmZmZmZmZmZjwvY29sMj48L2FiYz48c2Rmc2RmIGRpZmZncjppZD0ic2Rmc2RmMSIgbXNkYXRhOnJvd09yZGVyPSIwIiBkaWZmZ3I6aGFzQ2hhbmdlcz0iaW5zZXJ0ZWQiPjxra2s+ZmYxPC9ra2s+PGpmamZqZj5mZjI8L2pmamZqZj48L3NkZnNkZj48c2Rmc2RmIGRpZmZncjppZD0ic2Rmc2RmMiIgbXNkYXRhOnJvd09yZGVyPSIxIiBkaWZmZ3I6aGFzQ2hhbmdlcz0iaW5zZXJ0ZWQiPjxra2s+b29vPC9ra2s+PGpmamZqZj5zZGZsa2pzZGZsa2pzZDwvamZqZmpmPjwvc2Rmc2RmPjwvRGF0YVNldDEyMz48L2RpZmZncjpkaWZmZ3JhbT4EAwAAAA5TeXN0ZW0uVmVyc2lvbgQAAAAGX01ham9yBl9NaW5vcgZfQnVpbGQJX1JldmlzaW9uAAAAAAgICAgCAAAAAAAAAP//////////Cw==" } };
+ yield return new object[] { dt2, new string[] { "AAEAAAD/////AQAAAAAAAAAMAgAAAE5TeXN0ZW0uRGF0YSwgVmVyc2lvbj00LjAuMC4wLCBDdWx0dXJlPW5ldXRyYWwsIFB1YmxpY0tleVRva2VuPWI3N2E1YzU2MTkzNGUwODkFAQAAABVTeXN0ZW0uRGF0YS5EYXRhVGFibGUDAAAAGURhdGFUYWJsZS5SZW1vdGluZ1ZlcnNpb24JWG1sU2NoZW1hC1htbERpZmZHcmFtAwEBDlN5c3RlbS5WZXJzaW9uAgAAAAkDAAAABgQAAADeBTw/eG1sIHZlcnNpb249IjEuMCIgZW5jb2Rpbmc9InV0Zi0xNiI/Pg0KPHhzOnNjaGVtYSB4bWxucz0iIiB4bWxuczp4cz0iaHR0cDovL3d3dy53My5vcmcvMjAwMS9YTUxTY2hlbWEiIHhtbG5zOm1zZGF0YT0idXJuOnNjaGVtYXMtbWljcm9zb2Z0LWNvbTp4bWwtbXNkYXRhIj4NCiAgPHhzOmVsZW1lbnQgbmFtZT0ic2Rmc2RmIiBtc2RhdGE6TG9jYWxlPSIiPg0KICAgIDx4czpjb21wbGV4VHlwZT4NCiAgICAgIDx4czpzZXF1ZW5jZT4NCiAgICAgICAgPHhzOmVsZW1lbnQgbmFtZT0ia2trIiB0eXBlPSJ4czpzdHJpbmciIG1zZGF0YTp0YXJnZXROYW1lc3BhY2U9IiIgbWluT2NjdXJzPSIwIiAvPg0KICAgICAgICA8eHM6ZWxlbWVudCBuYW1lPSJqZmpmamYiIHR5cGU9InhzOnN0cmluZyIgbXNkYXRhOnRhcmdldE5hbWVzcGFjZT0iIiBtaW5PY2N1cnM9IjAiIC8+DQogICAgICA8L3hzOnNlcXVlbmNlPg0KICAgIDwveHM6Y29tcGxleFR5cGU+DQogIDwveHM6ZWxlbWVudD4NCiAgPHhzOmVsZW1lbnQgbmFtZT0iRGF0YVNldDEyMyIgbXNkYXRhOklzRGF0YVNldD0idHJ1ZSIgbXNkYXRhOk1haW5EYXRhVGFibGU9InNkZnNkZiIgbXNkYXRhOkxvY2FsZT0iIj4NCiAgICA8eHM6Y29tcGxleFR5cGU+DQogICAgICA8eHM6Y2hvaWNlIG1pbk9jY3Vycz0iMCIgbWF4T2NjdXJzPSJ1bmJvdW5kZWQiIC8+DQogICAgPC94czpjb21wbGV4VHlwZT4NCiAgPC94czplbGVtZW50Pg0KPC94czpzY2hlbWE+BgUAAADiBDxkaWZmZ3I6ZGlmZmdyYW0geG1sbnM6bXNkYXRhPSJ1cm46c2NoZW1hcy1taWNyb3NvZnQtY29tOnhtbC1tc2RhdGEiIHhtbG5zOmRpZmZncj0idXJuOnNjaGVtYXMtbWljcm9zb2Z0LWNvbTp4bWwtZGlmZmdyYW0tdjEiPg0KICA8RGF0YVNldDEyMz4NCiAgICA8c2Rmc2RmIGRpZmZncjppZD0ic2Rmc2RmMSIgbXNkYXRhOnJvd09yZGVyPSIwIiBkaWZmZ3I6aGFzQ2hhbmdlcz0iaW5zZXJ0ZWQiPg0KICAgICAgPGtraz5mZjE8L2traz4NCiAgICAgIDxqZmpmamY+ZmYyPC9qZmpmamY+DQogICAgPC9zZGZzZGY+DQogICAgPHNkZnNkZiBkaWZmZ3I6aWQ9InNkZnNkZjIiIG1zZGF0YTpyb3dPcmRlcj0iMSIgZGlmZmdyOmhhc0NoYW5nZXM9Imluc2VydGVkIj4NCiAgICAgIDxra2s+b29vPC9ra2s+DQogICAgICA8amZqZmpmPnNkZmxranNkZmxranNkPC9qZmpmamY+DQogICAgPC9zZGZzZGY+DQogICAgPHNkZnNkZiBkaWZmZ3I6aWQ9InNkZnNkZjMiIG1zZGF0YTpyb3dPcmRlcj0iMiIgZGlmZmdyOmhhc0NoYW5nZXM9Imluc2VydGVkIj4NCiAgICAgIDxra2s+bnVsbHZhbDwva2trPg0KICAgIDwvc2Rmc2RmPg0KICA8L0RhdGFTZXQxMjM+DQo8L2RpZmZncjpkaWZmZ3JhbT4EAwAAAA5TeXN0ZW0uVmVyc2lvbgQAAAAGX01ham9yBl9NaW5vcgZfQnVpbGQJX1JldmlzaW9uAAAAAAgICAgCAAAAAAAAAP//////////Cw==", "AAEAAAD/////AQAAAAAAAAAMAgAAAE5TeXN0ZW0uRGF0YSwgVmVyc2lvbj00LjAuMC4wLCBDdWx0dXJlPW5ldXRyYWwsIFB1YmxpY0tleVRva2VuPWI3N2E1YzU2MTkzNGUwODkFAQAAABVTeXN0ZW0uRGF0YS5EYXRhVGFibGUDAAAAGURhdGFUYWJsZS5SZW1vdGluZ1ZlcnNpb24JWG1sU2NoZW1hC1htbERpZmZHcmFtAwEBDlN5c3RlbS5WZXJzaW9uAgAAAAkDAAAABgQAAADeBTw/eG1sIHZlcnNpb249IjEuMCIgZW5jb2Rpbmc9InV0Zi0xNiI/Pg0KPHhzOnNjaGVtYSB4bWxucz0iIiB4bWxuczp4cz0iaHR0cDovL3d3dy53My5vcmcvMjAwMS9YTUxTY2hlbWEiIHhtbG5zOm1zZGF0YT0idXJuOnNjaGVtYXMtbWljcm9zb2Z0LWNvbTp4bWwtbXNkYXRhIj4NCiAgPHhzOmVsZW1lbnQgbmFtZT0ic2Rmc2RmIiBtc2RhdGE6TG9jYWxlPSIiPg0KICAgIDx4czpjb21wbGV4VHlwZT4NCiAgICAgIDx4czpzZXF1ZW5jZT4NCiAgICAgICAgPHhzOmVsZW1lbnQgbmFtZT0ia2trIiB0eXBlPSJ4czpzdHJpbmciIG1zZGF0YTp0YXJnZXROYW1lc3BhY2U9IiIgbWluT2NjdXJzPSIwIiAvPg0KICAgICAgICA8eHM6ZWxlbWVudCBuYW1lPSJqZmpmamYiIHR5cGU9InhzOnN0cmluZyIgbXNkYXRhOnRhcmdldE5hbWVzcGFjZT0iIiBtaW5PY2N1cnM9IjAiIC8+DQogICAgICA8L3hzOnNlcXVlbmNlPg0KICAgIDwveHM6Y29tcGxleFR5cGU+DQogIDwveHM6ZWxlbWVudD4NCiAgPHhzOmVsZW1lbnQgbmFtZT0iRGF0YVNldDEyMyIgbXNkYXRhOklzRGF0YVNldD0idHJ1ZSIgbXNkYXRhOk1haW5EYXRhVGFibGU9InNkZnNkZiIgbXNkYXRhOkxvY2FsZT0iIj4NCiAgICA8eHM6Y29tcGxleFR5cGU+DQogICAgICA8eHM6Y2hvaWNlIG1pbk9jY3Vycz0iMCIgbWF4T2NjdXJzPSJ1bmJvdW5kZWQiIC8+DQogICAgPC94czpjb21wbGV4VHlwZT4NCiAgPC94czplbGVtZW50Pg0KPC94czpzY2hlbWE+BgUAAADiBDxkaWZmZ3I6ZGlmZmdyYW0geG1sbnM6bXNkYXRhPSJ1cm46c2NoZW1hcy1taWNyb3NvZnQtY29tOnhtbC1tc2RhdGEiIHhtbG5zOmRpZmZncj0idXJuOnNjaGVtYXMtbWljcm9zb2Z0LWNvbTp4bWwtZGlmZmdyYW0tdjEiPg0KICA8RGF0YVNldDEyMz4NCiAgICA8c2Rmc2RmIGRpZmZncjppZD0ic2Rmc2RmMSIgbXNkYXRhOnJvd09yZGVyPSIwIiBkaWZmZ3I6aGFzQ2hhbmdlcz0iaW5zZXJ0ZWQiPg0KICAgICAgPGtraz5mZjE8L2traz4NCiAgICAgIDxqZmpmamY+ZmYyPC9qZmpmamY+DQogICAgPC9zZGZzZGY+DQogICAgPHNkZnNkZiBkaWZmZ3I6aWQ9InNkZnNkZjIiIG1zZGF0YTpyb3dPcmRlcj0iMSIgZGlmZmdyOmhhc0NoYW5nZXM9Imluc2VydGVkIj4NCiAgICAgIDxra2s+b29vPC9ra2s+DQogICAgICA8amZqZmpmPnNkZmxranNkZmxranNkPC9qZmpmamY+DQogICAgPC9zZGZzZGY+DQogICAgPHNkZnNkZiBkaWZmZ3I6aWQ9InNkZnNkZjMiIG1zZGF0YTpyb3dPcmRlcj0iMiIgZGlmZmdyOmhhc0NoYW5nZXM9Imluc2VydGVkIj4NCiAgICAgIDxra2s+bnVsbHZhbDwva2trPg0KICAgIDwvc2Rmc2RmPg0KICA8L0RhdGFTZXQxMjM+DQo8L2RpZmZncjpkaWZmZ3JhbT4EAwAAAA5TeXN0ZW0uVmVyc2lvbgQAAAAGX01ham9yBl9NaW5vcgZfQnVpbGQJX1JldmlzaW9uAAAAAAgICAgCAAAAAAAAAP//////////Cw==" } };
+ yield return new object[] { ds, new string[] { "AAEAAAD/////AQAAAAAAAAAMAgAAAE5TeXN0ZW0uRGF0YSwgVmVyc2lvbj00LjAuMC4wLCBDdWx0dXJlPW5ldXRyYWwsIFB1YmxpY0tleVRva2VuPWI3N2E1YzU2MTkzNGUwODkFAQAAABNTeXN0ZW0uRGF0YS5EYXRhU2V0AwAAABdEYXRhU2V0LlJlbW90aW5nVmVyc2lvbglYbWxTY2hlbWELWG1sRGlmZkdyYW0DAQEOU3lzdGVtLlZlcnNpb24CAAAACQMAAAAGBAAAALoJPD94bWwgdmVyc2lvbj0iMS4wIiBlbmNvZGluZz0idXRmLTE2Ij8+DQo8eHM6c2NoZW1hIGlkPSJEYXRhU2V0MTIzIiB4bWxucz0iIiB4bWxuczp4cz0iaHR0cDovL3d3dy53My5vcmcvMjAwMS9YTUxTY2hlbWEiIHhtbG5zOm1zZGF0YT0idXJuOnNjaGVtYXMtbWljcm9zb2Z0LWNvbTp4bWwtbXNkYXRhIj4NCiAgPHhzOmVsZW1lbnQgbmFtZT0iRGF0YVNldDEyMyIgbXNkYXRhOklzRGF0YVNldD0idHJ1ZSIgbXNkYXRhOkxvY2FsZT0iIj4NCiAgICA8eHM6Y29tcGxleFR5cGU+DQogICAgICA8eHM6Y2hvaWNlIG1pbk9jY3Vycz0iMCIgbWF4T2NjdXJzPSJ1bmJvdW5kZWQiPg0KICAgICAgICA8eHM6ZWxlbWVudCBtc2RhdGE6dGFyZ2V0TmFtZXNwYWNlPSJteW5zMSIgbmFtZT0iYWJjIiBtc2RhdGE6TG9jYWxlPSIiPg0KICAgICAgICAgIDx4czpjb21wbGV4VHlwZT4NCiAgICAgICAgICAgIDx4czpzZXF1ZW5jZT4NCiAgICAgICAgICAgICAgPHhzOmVsZW1lbnQgbmFtZT0iY29sMSIgdHlwZT0ieHM6c3RyaW5nIiBtc2RhdGE6dGFyZ2V0TmFtZXNwYWNlPSJteW5zMSIgbWluT2NjdXJzPSIwIiAvPg0KICAgICAgICAgICAgICA8eHM6ZWxlbWVudCBuYW1lPSJjb2wyIiB0eXBlPSJ4czpzdHJpbmciIG1zZGF0YTp0YXJnZXROYW1lc3BhY2U9Im15bnMxIiBtaW5PY2N1cnM9IjAiIC8+DQogICAgICAgICAgICA8L3hzOnNlcXVlbmNlPg0KICAgICAgICAgIDwveHM6Y29tcGxleFR5cGU+DQogICAgICAgIDwveHM6ZWxlbWVudD4NCiAgICAgICAgPHhzOmVsZW1lbnQgbmFtZT0ic2Rmc2RmIiBtc2RhdGE6TG9jYWxlPSIiPg0KICAgICAgICAgIDx4czpjb21wbGV4VHlwZT4NCiAgICAgICAgICAgIDx4czpzZXF1ZW5jZT4NCiAgICAgICAgICAgICAgPHhzOmVsZW1lbnQgbmFtZT0ia2trIiB0eXBlPSJ4czpzdHJpbmciIG1zZGF0YTp0YXJnZXROYW1lc3BhY2U9IiIgbWluT2NjdXJzPSIwIiAvPg0KICAgICAgICAgICAgICA8eHM6ZWxlbWVudCBuYW1lPSJqZmpmamYiIHR5cGU9InhzOnN0cmluZyIgbXNkYXRhOnRhcmdldE5hbWVzcGFjZT0iIiBtaW5PY2N1cnM9IjAiIC8+DQogICAgICAgICAgICA8L3hzOnNlcXVlbmNlPg0KICAgICAgICAgIDwveHM6Y29tcGxleFR5cGU+DQogICAgICAgIDwveHM6ZWxlbWVudD4NCiAgICAgIDwveHM6Y2hvaWNlPg0KICAgIDwveHM6Y29tcGxleFR5cGU+DQogIDwveHM6ZWxlbWVudD4NCjwveHM6c2NoZW1hPgYFAAAAiwY8ZGlmZmdyOmRpZmZncmFtIHhtbG5zOm1zZGF0YT0idXJuOnNjaGVtYXMtbWljcm9zb2Z0LWNvbTp4bWwtbXNkYXRhIiB4bWxuczpkaWZmZ3I9InVybjpzY2hlbWFzLW1pY3Jvc29mdC1jb206eG1sLWRpZmZncmFtLXYxIj48RGF0YVNldDEyMz48YWJjIGRpZmZncjppZD0iYWJjMSIgbXNkYXRhOnJvd09yZGVyPSIwIiBkaWZmZ3I6aGFzQ2hhbmdlcz0iaW5zZXJ0ZWQiIHhtbG5zPSJteW5zMSI+PGNvbDE+Zm9vPC9jb2wxPjxjb2wyPmJhcjwvY29sMj48L2FiYz48YWJjIGRpZmZncjppZD0iYWJjMiIgbXNkYXRhOnJvd09yZGVyPSIxIiBkaWZmZ3I6aGFzQ2hhbmdlcz0iaW5zZXJ0ZWQiIHhtbG5zPSJteW5zMSI+PGNvbDE+YXNkYXNkPC9jb2wxPjxjb2wyPmZmZmZmZmZmZjwvY29sMj48L2FiYz48c2Rmc2RmIGRpZmZncjppZD0ic2Rmc2RmMSIgbXNkYXRhOnJvd09yZGVyPSIwIiBkaWZmZ3I6aGFzQ2hhbmdlcz0iaW5zZXJ0ZWQiPjxra2s+ZmYxPC9ra2s+PGpmamZqZj5mZjI8L2pmamZqZj48L3NkZnNkZj48c2Rmc2RmIGRpZmZncjppZD0ic2Rmc2RmMiIgbXNkYXRhOnJvd09yZGVyPSIxIiBkaWZmZ3I6aGFzQ2hhbmdlcz0iaW5zZXJ0ZWQiPjxra2s+b29vPC9ra2s+PGpmamZqZj5zZGZsa2pzZGZsa2pzZDwvamZqZmpmPjwvc2Rmc2RmPjxzZGZzZGYgZGlmZmdyOmlkPSJzZGZzZGYzIiBtc2RhdGE6cm93T3JkZXI9IjIiIGRpZmZncjpoYXNDaGFuZ2VzPSJpbnNlcnRlZCI+PGtraz5udWxsdmFsPC9ra2s+PC9zZGZzZGY+PC9EYXRhU2V0MTIzPjwvZGlmZmdyOmRpZmZncmFtPgQDAAAADlN5c3RlbS5WZXJzaW9uBAAAAAZfTWFqb3IGX01pbm9yBl9CdWlsZAlfUmV2aXNpb24AAAAACAgICAIAAAAAAAAA//////////8L", "AAEAAAD/////AQAAAAAAAAAMAgAAAE5TeXN0ZW0uRGF0YSwgVmVyc2lvbj00LjAuMC4wLCBDdWx0dXJlPW5ldXRyYWwsIFB1YmxpY0tleVRva2VuPWI3N2E1YzU2MTkzNGUwODkFAQAAABNTeXN0ZW0uRGF0YS5EYXRhU2V0AwAAABdEYXRhU2V0LlJlbW90aW5nVmVyc2lvbglYbWxTY2hlbWELWG1sRGlmZkdyYW0DAQEOU3lzdGVtLlZlcnNpb24CAAAACQMAAAAGBAAAALoJPD94bWwgdmVyc2lvbj0iMS4wIiBlbmNvZGluZz0idXRmLTE2Ij8+DQo8eHM6c2NoZW1hIGlkPSJEYXRhU2V0MTIzIiB4bWxucz0iIiB4bWxuczp4cz0iaHR0cDovL3d3dy53My5vcmcvMjAwMS9YTUxTY2hlbWEiIHhtbG5zOm1zZGF0YT0idXJuOnNjaGVtYXMtbWljcm9zb2Z0LWNvbTp4bWwtbXNkYXRhIj4NCiAgPHhzOmVsZW1lbnQgbmFtZT0iRGF0YVNldDEyMyIgbXNkYXRhOklzRGF0YVNldD0idHJ1ZSIgbXNkYXRhOkxvY2FsZT0iIj4NCiAgICA8eHM6Y29tcGxleFR5cGU+DQogICAgICA8eHM6Y2hvaWNlIG1pbk9jY3Vycz0iMCIgbWF4T2NjdXJzPSJ1bmJvdW5kZWQiPg0KICAgICAgICA8eHM6ZWxlbWVudCBtc2RhdGE6dGFyZ2V0TmFtZXNwYWNlPSJteW5zMSIgbmFtZT0iYWJjIiBtc2RhdGE6TG9jYWxlPSIiPg0KICAgICAgICAgIDx4czpjb21wbGV4VHlwZT4NCiAgICAgICAgICAgIDx4czpzZXF1ZW5jZT4NCiAgICAgICAgICAgICAgPHhzOmVsZW1lbnQgbmFtZT0iY29sMSIgdHlwZT0ieHM6c3RyaW5nIiBtc2RhdGE6dGFyZ2V0TmFtZXNwYWNlPSJteW5zMSIgbWluT2NjdXJzPSIwIiAvPg0KICAgICAgICAgICAgICA8eHM6ZWxlbWVudCBuYW1lPSJjb2wyIiB0eXBlPSJ4czpzdHJpbmciIG1zZGF0YTp0YXJnZXROYW1lc3BhY2U9Im15bnMxIiBtaW5PY2N1cnM9IjAiIC8+DQogICAgICAgICAgICA8L3hzOnNlcXVlbmNlPg0KICAgICAgICAgIDwveHM6Y29tcGxleFR5cGU+DQogICAgICAgIDwveHM6ZWxlbWVudD4NCiAgICAgICAgPHhzOmVsZW1lbnQgbmFtZT0ic2Rmc2RmIiBtc2RhdGE6TG9jYWxlPSIiPg0KICAgICAgICAgIDx4czpjb21wbGV4VHlwZT4NCiAgICAgICAgICAgIDx4czpzZXF1ZW5jZT4NCiAgICAgICAgICAgICAgPHhzOmVsZW1lbnQgbmFtZT0ia2trIiB0eXBlPSJ4czpzdHJpbmciIG1zZGF0YTp0YXJnZXROYW1lc3BhY2U9IiIgbWluT2NjdXJzPSIwIiAvPg0KICAgICAgICAgICAgICA8eHM6ZWxlbWVudCBuYW1lPSJqZmpmamYiIHR5cGU9InhzOnN0cmluZyIgbXNkYXRhOnRhcmdldE5hbWVzcGFjZT0iIiBtaW5PY2N1cnM9IjAiIC8+DQogICAgICAgICAgICA8L3hzOnNlcXVlbmNlPg0KICAgICAgICAgIDwveHM6Y29tcGxleFR5cGU+DQogICAgICAgIDwveHM6ZWxlbWVudD4NCiAgICAgIDwveHM6Y2hvaWNlPg0KICAgIDwveHM6Y29tcGxleFR5cGU+DQogIDwveHM6ZWxlbWVudD4NCjwveHM6c2NoZW1hPgYFAAAAiwY8ZGlmZmdyOmRpZmZncmFtIHhtbG5zOm1zZGF0YT0idXJuOnNjaGVtYXMtbWljcm9zb2Z0LWNvbTp4bWwtbXNkYXRhIiB4bWxuczpkaWZmZ3I9InVybjpzY2hlbWFzLW1pY3Jvc29mdC1jb206eG1sLWRpZmZncmFtLXYxIj48RGF0YVNldDEyMz48YWJjIGRpZmZncjppZD0iYWJjMSIgbXNkYXRhOnJvd09yZGVyPSIwIiBkaWZmZ3I6aGFzQ2hhbmdlcz0iaW5zZXJ0ZWQiIHhtbG5zPSJteW5zMSI+PGNvbDE+Zm9vPC9jb2wxPjxjb2wyPmJhcjwvY29sMj48L2FiYz48YWJjIGRpZmZncjppZD0iYWJjMiIgbXNkYXRhOnJvd09yZGVyPSIxIiBkaWZmZ3I6aGFzQ2hhbmdlcz0iaW5zZXJ0ZWQiIHhtbG5zPSJteW5zMSI+PGNvbDE+YXNkYXNkPC9jb2wxPjxjb2wyPmZmZmZmZmZmZjwvY29sMj48L2FiYz48c2Rmc2RmIGRpZmZncjppZD0ic2Rmc2RmMSIgbXNkYXRhOnJvd09yZGVyPSIwIiBkaWZmZ3I6aGFzQ2hhbmdlcz0iaW5zZXJ0ZWQiPjxra2s+ZmYxPC9ra2s+PGpmamZqZj5mZjI8L2pmamZqZj48L3NkZnNkZj48c2Rmc2RmIGRpZmZncjppZD0ic2Rmc2RmMiIgbXNkYXRhOnJvd09yZGVyPSIxIiBkaWZmZ3I6aGFzQ2hhbmdlcz0iaW5zZXJ0ZWQiPjxra2s+b29vPC9ra2s+PGpmamZqZj5zZGZsa2pzZGZsa2pzZDwvamZqZmpmPjwvc2Rmc2RmPjxzZGZzZGYgZGlmZmdyOmlkPSJzZGZzZGYzIiBtc2RhdGE6cm93T3JkZXI9IjIiIGRpZmZncjpoYXNDaGFuZ2VzPSJpbnNlcnRlZCI+PGtraz5udWxsdmFsPC9ra2s+PC9zZGZzZGY+PC9EYXRhU2V0MTIzPjwvZGlmZmdyOmRpZmZncmFtPgQDAAAADlN5c3RlbS5WZXJzaW9uBAAAAAZfTWFqb3IGX01pbm9yBl9CdWlsZAlfUmV2aXNpb24AAAAACAgICAIAAAAAAAAA//////////8L" } };
var propertyCollection = new PropertyCollection
{
@@ -293,6 +263,7 @@ namespace System.Runtime.Serialization.Formatters.Tests
yield return new object[] { new SqlString(CultureInfo.InvariantCulture.LCID, SqlCompareOptions.BinarySort, new byte[] { 65, 66, 67 }, true), new string[] { "AAEAAAD/////AQAAAAAAAAAMAgAAAE5TeXN0ZW0uRGF0YSwgVmVyc2lvbj00LjAuMC4wLCBDdWx0dXJlPW5ldXRyYWwsIFB1YmxpY0tleVRva2VuPWI3N2E1YzU2MTkzNGUwODkFAQAAAB5TeXN0ZW0uRGF0YS5TcWxUeXBlcy5TcWxTdHJpbmcFAAAAB21fdmFsdWUJbV9jbXBJbmZvBm1fbGNpZAZtX2ZsYWcKbV9mTm90TnVsbAEDAAQAIFN5c3RlbS5HbG9iYWxpemF0aW9uLkNvbXBhcmVJbmZvCCZTeXN0ZW0uRGF0YS5TcWxUeXBlcy5TcWxDb21wYXJlT3B0aW9ucwIAAAABAgAAAAYDAAAABuSJge+/vQp/AAAABfz///8mU3lzdGVtLkRhdGEuU3FsVHlwZXMuU3FsQ29tcGFyZU9wdGlvbnMBAAAAB3ZhbHVlX18ACAIAAAAAgAAAAQs=", "AAEAAAD/////AQAAAAAAAAAMAgAAAE5TeXN0ZW0uRGF0YSwgVmVyc2lvbj00LjAuMC4wLCBDdWx0dXJlPW5ldXRyYWwsIFB1YmxpY0tleVRva2VuPWI3N2E1YzU2MTkzNGUwODkFAQAAAB5TeXN0ZW0uRGF0YS5TcWxUeXBlcy5TcWxTdHJpbmcFAAAAB21fdmFsdWUJbV9jbXBJbmZvBm1fbGNpZAZtX2ZsYWcKbV9mTm90TnVsbAEDAAQAIFN5c3RlbS5HbG9iYWxpemF0aW9uLkNvbXBhcmVJbmZvCCZTeXN0ZW0uRGF0YS5TcWxUeXBlcy5TcWxDb21wYXJlT3B0aW9ucwIAAAABAgAAAAYDAAAABuSJge+/vQp/AAAABfz///8mU3lzdGVtLkRhdGEuU3FsVHlwZXMuU3FsQ29tcGFyZU9wdGlvbnMBAAAAB3ZhbHVlX18ACAIAAAAAgAAAAQs=" } };
yield return new object[] { new SqlString(CultureInfo.InvariantCulture.LCID, SqlCompareOptions.BinarySort, new byte[] { 65, 66, 67 }, 0, 3), new string[] { "AAEAAAD/////AQAAAAAAAAAMAgAAAE5TeXN0ZW0uRGF0YSwgVmVyc2lvbj00LjAuMC4wLCBDdWx0dXJlPW5ldXRyYWwsIFB1YmxpY0tleVRva2VuPWI3N2E1YzU2MTkzNGUwODkFAQAAAB5TeXN0ZW0uRGF0YS5TcWxUeXBlcy5TcWxTdHJpbmcFAAAAB21fdmFsdWUJbV9jbXBJbmZvBm1fbGNpZAZtX2ZsYWcKbV9mTm90TnVsbAEDAAQAIFN5c3RlbS5HbG9iYWxpemF0aW9uLkNvbXBhcmVJbmZvCCZTeXN0ZW0uRGF0YS5TcWxUeXBlcy5TcWxDb21wYXJlT3B0aW9ucwIAAAABAgAAAAYDAAAABuSJge+/vQp/AAAABfz///8mU3lzdGVtLkRhdGEuU3FsVHlwZXMuU3FsQ29tcGFyZU9wdGlvbnMBAAAAB3ZhbHVlX18ACAIAAAAAgAAAAQs=", "AAEAAAD/////AQAAAAAAAAAMAgAAAE5TeXN0ZW0uRGF0YSwgVmVyc2lvbj00LjAuMC4wLCBDdWx0dXJlPW5ldXRyYWwsIFB1YmxpY0tleVRva2VuPWI3N2E1YzU2MTkzNGUwODkFAQAAAB5TeXN0ZW0uRGF0YS5TcWxUeXBlcy5TcWxTdHJpbmcFAAAAB21fdmFsdWUJbV9jbXBJbmZvBm1fbGNpZAZtX2ZsYWcKbV9mTm90TnVsbAEDAAQAIFN5c3RlbS5HbG9iYWxpemF0aW9uLkNvbXBhcmVJbmZvCCZTeXN0ZW0uRGF0YS5TcWxUeXBlcy5TcWxDb21wYXJlT3B0aW9ucwIAAAABAgAAAAYDAAAABuSJge+/vQp/AAAABfz///8mU3lzdGVtLkRhdGEuU3FsVHlwZXMuU3FsQ29tcGFyZU9wdGlvbnMBAAAAB3ZhbHVlX18ACAIAAAAAgAAAAQs=" } };
yield return new object[] { new SqlString(CultureInfo.InvariantCulture.LCID, SqlCompareOptions.BinarySort, new byte[] { 65, 66, 67 }, 0, 3, true), new string[] { "AAEAAAD/////AQAAAAAAAAAMAgAAAE5TeXN0ZW0uRGF0YSwgVmVyc2lvbj00LjAuMC4wLCBDdWx0dXJlPW5ldXRyYWwsIFB1YmxpY0tleVRva2VuPWI3N2E1YzU2MTkzNGUwODkFAQAAAB5TeXN0ZW0uRGF0YS5TcWxUeXBlcy5TcWxTdHJpbmcFAAAAB21fdmFsdWUJbV9jbXBJbmZvBm1fbGNpZAZtX2ZsYWcKbV9mTm90TnVsbAEDAAQAIFN5c3RlbS5HbG9iYWxpemF0aW9uLkNvbXBhcmVJbmZvCCZTeXN0ZW0uRGF0YS5TcWxUeXBlcy5TcWxDb21wYXJlT3B0aW9ucwIAAAABAgAAAAYDAAAABuSJge+/vQp/AAAABfz///8mU3lzdGVtLkRhdGEuU3FsVHlwZXMuU3FsQ29tcGFyZU9wdGlvbnMBAAAAB3ZhbHVlX18ACAIAAAAAgAAAAQs=", "AAEAAAD/////AQAAAAAAAAAMAgAAAE5TeXN0ZW0uRGF0YSwgVmVyc2lvbj00LjAuMC4wLCBDdWx0dXJlPW5ldXRyYWwsIFB1YmxpY0tleVRva2VuPWI3N2E1YzU2MTkzNGUwODkFAQAAAB5TeXN0ZW0uRGF0YS5TcWxUeXBlcy5TcWxTdHJpbmcFAAAAB21fdmFsdWUJbV9jbXBJbmZvBm1fbGNpZAZtX2ZsYWcKbV9mTm90TnVsbAEDAAQAIFN5c3RlbS5HbG9iYWxpemF0aW9uLkNvbXBhcmVJbmZvCCZTeXN0ZW0uRGF0YS5TcWxUeXBlcy5TcWxDb21wYXJlT3B0aW9ucwIAAAABAgAAAAYDAAAABuSJge+/vQp/AAAABfz///8mU3lzdGVtLkRhdGEuU3FsVHlwZXMuU3FsQ29tcGFyZU9wdGlvbnMBAAAAB3ZhbHVlX18ACAIAAAAAgAAAAQs=" } };
+ yield return new object[] { DBNull.Value, new string[] { "AAEAAAD/////AQAAAAAAAAAEAQAAAB9TeXN0ZW0uVW5pdHlTZXJpYWxpemF0aW9uSG9sZGVyAwAAAAREYXRhCVVuaXR5VHlwZQxBc3NlbWJseU5hbWUBAAEICgIAAAAGAgAAAAAL", "AAEAAAD/////AQAAAAAAAAAEAQAAAB9TeXN0ZW0uVW5pdHlTZXJpYWxpemF0aW9uSG9sZGVyAwAAAAREYXRhCVVuaXR5VHlwZQxBc3NlbWJseU5hbWUBAAEICgIAAAAGAgAAAAAL" } };
yield return new object[] { new BigInteger(), new string[] { "AAEAAAD/////AQAAAAAAAAAMAgAAAEFTeXN0ZW0uTnVtZXJpY3MsIFZlcnNpb249NC4wLjAuMCwgUHVibGljS2V5VG9rZW49Yjc3YTVjNTYxOTM0ZTA4OQUBAAAAGlN5c3RlbS5OdW1lcmljcy5CaWdJbnRlZ2VyAgAAAAVfc2lnbgVfYml0cwAHCA8CAAAAAAAAAAoL", "AAEAAAD/////AQAAAAAAAAAMAgAAAFJTeXN0ZW0uTnVtZXJpY3MsIFZlcnNpb249NC4wLjAuMCwgQ3VsdHVyZT1uZXV0cmFsLCBQdWJsaWNLZXlUb2tlbj1iNzdhNWM1NjE5MzRlMDg5BQEAAAAaU3lzdGVtLk51bWVyaWNzLkJpZ0ludGVnZXICAAAABV9zaWduBV9iaXRzAAcIDwIAAAAAAAAACgs=" } };
yield return new object[] { new BigInteger(10324176), new string[] { "AAEAAAD/////AQAAAAAAAAAMAgAAAEFTeXN0ZW0uTnVtZXJpY3MsIFZlcnNpb249NC4wLjAuMCwgUHVibGljS2V5VG9rZW49Yjc3YTVjNTYxOTM0ZTA4OQUBAAAAGlN5c3RlbS5OdW1lcmljcy5CaWdJbnRlZ2VyAgAAAAVfc2lnbgVfYml0cwAHCA8CAAAA0IidAAoL", "AAEAAAD/////AQAAAAAAAAAMAgAAAFJTeXN0ZW0uTnVtZXJpY3MsIFZlcnNpb249NC4wLjAuMCwgQ3VsdHVyZT1uZXV0cmFsLCBQdWJsaWNLZXlUb2tlbj1iNzdhNWM1NjE5MzRlMDg5BQEAAAAaU3lzdGVtLk51bWVyaWNzLkJpZ0ludGVnZXICAAAABV9zaWduBV9iaXRzAAcIDwIAAADQiJ0ACgs=" } };
@@ -668,7 +639,7 @@ namespace System.Runtime.Serialization.Formatters.Tests
// Extension of core serializable types
if (PlatformDetection.IsNetfx471OrNewer())
{
- // ValueType isn't serializable before ntfx471.
+ // ValueType isn't serializable before netfx471.
yield return new object[] { new ValueTuple(), new string[] { "AAEAAAD/////AQAAAAAAAAAEAQAAABFTeXN0ZW0uVmFsdWVUdXBsZQAAAAAL", "AAEAAAD/////AQAAAAAAAAAEAQAAABFTeXN0ZW0uVmFsdWVUdXBsZQAAAAAL" } };
yield return new object[] { ValueTuple.Create(1), new string[] { "AAEAAAD/////AQAAAAAAAAAEAQAAAHBTeXN0ZW0uVmFsdWVUdXBsZWAxW1tTeXN0ZW0uSW50MzIsIG1zY29ybGliLCBWZXJzaW9uPTQuMC4wLjAsIEN1bHR1cmU9bmV1dHJhbCwgUHVibGljS2V5VG9rZW49Yjc3YTVjNTYxOTM0ZTA4OV1dAQAAAAVJdGVtMQAIAQAAAAs=", "AAEAAAD/////AQAAAAAAAAAEAQAAAHBTeXN0ZW0uVmFsdWVUdXBsZWAxW1tTeXN0ZW0uSW50MzIsIG1zY29ybGliLCBWZXJzaW9uPTQuMC4wLjAsIEN1bHR1cmU9bmV1dHJhbCwgUHVibGljS2V5VG9rZW49Yjc3YTVjNTYxOTM0ZTA4OV1dAQAAAAVJdGVtMQAIAQAAAAs=" } };
yield return new object[] { ValueTuple.Create(1, "2"), new string[] { "AAEAAAD/////AQAAAAAAAAAEAQAAAM0BU3lzdGVtLlZhbHVlVHVwbGVgMltbU3lzdGVtLkludDMyLCBtc2NvcmxpYiwgVmVyc2lvbj00LjAuMC4wLCBDdWx0dXJlPW5ldXRyYWwsIFB1YmxpY0tleVRva2VuPWI3N2E1YzU2MTkzNGUwODldLFtTeXN0ZW0uU3RyaW5nLCBtc2NvcmxpYiwgVmVyc2lvbj00LjAuMC4wLCBDdWx0dXJlPW5ldXRyYWwsIFB1YmxpY0tleVRva2VuPWI3N2E1YzU2MTkzNGUwODldXQIAAAAFSXRlbTEFSXRlbTIAAQgBAAAABgIAAAABMgs=", "AAEAAAD/////AQAAAAAAAAAEAQAAAM0BU3lzdGVtLlZhbHVlVHVwbGVgMltbU3lzdGVtLkludDMyLCBtc2NvcmxpYiwgVmVyc2lvbj00LjAuMC4wLCBDdWx0dXJlPW5ldXRyYWwsIFB1YmxpY0tleVRva2VuPWI3N2E1YzU2MTkzNGUwODldLFtTeXN0ZW0uU3RyaW5nLCBtc2NvcmxpYiwgVmVyc2lvbj00LjAuMC4wLCBDdWx0dXJlPW5ldXRyYWwsIFB1YmxpY0tleVRva2VuPWI3N2E1YzU2MTkzNGUwODldXQIAAAAFSXRlbTEFSXRlbTIAAQgBAAAABgIAAAABMgs=" } };
@@ -683,6 +654,30 @@ namespace System.Runtime.Serialization.Formatters.Tests
// *** NON AUTO UPDATED DATA ***
+ private static void PopulateException<T>(T exception)
+ where T : Exception
+ {
+ exception.HelpLink = "http://msdn.microsoft.com";
+ exception.Source = "Exception_Class_Samples";
+
+ exception.Data.Add("secret", true);
+ exception.Data.Add(1, "one");
+
+ // Exceptions are reflection blocked in uapaot
+ if (!PlatformDetection.IsNetNative)
+ {
+ typeof(Exception)
+ .GetField("_stackTraceString", BindingFlags.Instance | BindingFlags.NonPublic)
+ .SetValue(exception, "StackTrace string...");
+ typeof(Exception)
+ .GetField("_HResult", BindingFlags.Instance | BindingFlags.NonPublic)
+ .SetValue(exception, 1000);
+ typeof(Exception)
+ .GetField("_remoteStackTraceString", BindingFlags.Instance | BindingFlags.NonPublic)
+ .SetValue(exception, "Remote StackTrace string...");
+ }
+ }
+
public static IEnumerable<object> NonSerializableObjects_MemberData()
{
yield return new NonSerializableStruct();
diff --git a/src/System.Runtime.Serialization.Formatters/tests/BinaryFormatterTests.cs b/src/System.Runtime.Serialization.Formatters/tests/BinaryFormatterTests.cs
index bbe17ce508..690071e3d3 100644
--- a/src/System.Runtime.Serialization.Formatters/tests/BinaryFormatterTests.cs
+++ b/src/System.Runtime.Serialization.Formatters/tests/BinaryFormatterTests.cs
@@ -9,6 +9,7 @@ using System.Linq;
using System.Reflection;
using System.Runtime.Serialization.Formatters.Binary;
using System.Text;
+using System.Text.RegularExpressions;
using Xunit;
namespace System.Runtime.Serialization.Formatters.Tests
@@ -20,7 +21,8 @@ namespace System.Runtime.Serialization.Formatters.Tests
public void ValidateBasicObjectsRoundtrip(object obj, FormatterAssemblyStyle assemblyFormat, TypeFilterLevel filterLevel, FormatterTypeStyle typeFormat)
{
object clone = BinaryFormatterHelpers.Clone(obj, null, assemblyFormat, filterLevel, typeFormat);
- if (!ReferenceEquals(obj, string.Empty)) // "" is interned and will roundtrip as the same object
+ // string.Empty and DBNull are both singletons
+ if (!ReferenceEquals(obj, string.Empty) && !(obj is DBNull))
{
Assert.NotSame(obj, clone);
}
@@ -33,8 +35,10 @@ namespace System.Runtime.Serialization.Formatters.Tests
public void UpdateBlobs()
{
string testDataFilePath = GetTestDataFilePath();
- IEnumerable<object[]> coreTypeRecords = GetCoreTypeRecords();
- string[] coreTypeBlobs = GetCoreTypeBlobs(coreTypeRecords, FormatterAssemblyStyle.Full).ToArray();
+ string[] coreTypeBlobs = SerializableEqualityComparers_MemberData()
+ .Concat(SerializableObjects_MemberData())
+ .Select(record => BinaryFormatterHelpers.ToBase64String(record[0]))
+ .ToArray();
var (numberOfBlobs, numberOfFoundBlobs, numberOfUpdatedBlobs) = UpdateCoreTypeBlobs(testDataFilePath, coreTypeBlobs);
Console.WriteLine($"{numberOfBlobs} existing blobs" +
@@ -44,7 +48,15 @@ namespace System.Runtime.Serialization.Formatters.Tests
[Theory]
[MemberData(nameof(SerializableObjects_MemberData))]
- public void ValidateAgainstBlobs(object obj, string[] blobs)
+ public void ValidateAgainstBlobs(object obj, string[] blobs)
+ => ValidateAndRoundtrip(obj, blobs, false);
+
+ [Theory]
+ [MemberData(nameof(SerializableEqualityComparers_MemberData))]
+ public void ValidateEqualityComparersAgainstBlobs(object obj, string[] blobs)
+ => ValidateAndRoundtrip(obj, blobs, true);
+
+ private static void ValidateAndRoundtrip(object obj, string[] blobs, bool isEqualityComparer)
{
if (obj == null)
{
@@ -54,15 +66,23 @@ namespace System.Runtime.Serialization.Formatters.Tests
if (blobs == null || blobs.Length == 0)
{
throw new ArgumentOutOfRangeException($"Type {obj} has no blobs to deserialize and test equality against. Blob: " +
- SerializeObjectToBlob(obj, FormatterAssemblyStyle.Full));
+ BinaryFormatterHelpers.ToBase64String(obj, FormatterAssemblyStyle.Full));
}
SanityCheckBlob(obj, blobs);
foreach (string blob in blobs)
{
- CheckForAnyEquals(obj, DeserializeBlobToObject(blob, FormatterAssemblyStyle.Simple));
- CheckForAnyEquals(obj, DeserializeBlobToObject(blob, FormatterAssemblyStyle.Full));
+ if (isEqualityComparer)
+ {
+ ValidateEqualityComparer(BinaryFormatterHelpers.FromBase64String(blob, FormatterAssemblyStyle.Simple));
+ ValidateEqualityComparer(BinaryFormatterHelpers.FromBase64String(blob, FormatterAssemblyStyle.Full));
+ }
+ else
+ {
+ CheckForAnyEquals(obj, BinaryFormatterHelpers.FromBase64String(blob, FormatterAssemblyStyle.Simple));
+ CheckForAnyEquals(obj, BinaryFormatterHelpers.FromBase64String(blob, FormatterAssemblyStyle.Full));
+ }
}
}
@@ -74,8 +94,8 @@ namespace System.Runtime.Serialization.Formatters.Tests
object obj = new ArraySegment<int>();
string corefxBlob = "AAEAAAD/////AQAAAAAAAAAEAQAAAHJTeXN0ZW0uQXJyYXlTZWdtZW50YDFbW1N5c3RlbS5JbnQzMiwgbXNjb3JsaWIsIFZlcnNpb249NC4wLjAuMCwgQ3VsdHVyZT1uZXV0cmFsLCBQdWJsaWNLZXlUb2tlbj1iNzdhNWM1NjE5MzRlMDg5XV0DAAAABl9hcnJheQdfb2Zmc2V0Bl9jb3VudAcAAAgICAoAAAAAAAAAAAs=";
string netfxBlob = "AAEAAAD/////AQAAAAAAAAAEAQAAAHJTeXN0ZW0uQXJyYXlTZWdtZW50YDFbW1N5c3RlbS5JbnQzMiwgbXNjb3JsaWIsIFZlcnNpb249NC4wLjAuMCwgQ3VsdHVyZT1uZXV0cmFsLCBQdWJsaWNLZXlUb2tlbj1iNzdhNWM1NjE5MzRlMDg5XV0DAAAABl9hcnJheQdfb2Zmc2V0Bl9jb3VudAcAAAgICAoAAAAAAAAAAAs=";
- CheckForAnyEquals(obj, DeserializeBlobToObject(corefxBlob, FormatterAssemblyStyle.Full));
- CheckForAnyEquals(obj, DeserializeBlobToObject(netfxBlob, FormatterAssemblyStyle.Full));
+ CheckForAnyEquals(obj, BinaryFormatterHelpers.FromBase64String(corefxBlob, FormatterAssemblyStyle.Full));
+ CheckForAnyEquals(obj, BinaryFormatterHelpers.FromBase64String(netfxBlob, FormatterAssemblyStyle.Full));
}
[Fact]
@@ -86,7 +106,7 @@ namespace System.Runtime.Serialization.Formatters.Tests
var obj = new SomeType() { SomeField = 7 };
string serializedObj = @"AAEAAAD/////AQAAAAAAAAAMAgAAAHNTeXN0ZW0uUnVudGltZS5TZXJpYWxpemF0aW9uLkZvcm1hdHRlcnMuVGVzdHMsIFZlcnNpb249OS45OC43Ljk4NywgQ3VsdHVyZT1uZXV0cmFsLCBQdWJsaWNLZXlUb2tlbj05ZDc3Y2M3YWQzOWI2OGViBQEAAAA2U3lzdGVtLlJ1bnRpbWUuU2VyaWFsaXphdGlvbi5Gb3JtYXR0ZXJzLlRlc3RzLlNvbWVUeXBlAQAAAAlTb21lRmllbGQACAIAAAAHAAAACw==";
- var deserialized = (SomeType)DeserializeBlobToObject(serializedObj, FormatterAssemblyStyle.Simple);
+ var deserialized = (SomeType)BinaryFormatterHelpers.FromBase64String(serializedObj, FormatterAssemblyStyle.Simple);
Assert.Equal(obj, deserialized);
}
@@ -98,34 +118,10 @@ namespace System.Runtime.Serialization.Formatters.Tests
var obj = new GenericTypeWithArg<SomeType>() { Test = new SomeType() { SomeField = 9 } };
string serializedObj = @"AAEAAAD/////AQAAAAAAAAAMAgAAAHNTeXN0ZW0uUnVudGltZS5TZXJpYWxpemF0aW9uLkZvcm1hdHRlcnMuVGVzdHMsIFZlcnNpb249OS45OC43Ljk4NywgQ3VsdHVyZT1uZXV0cmFsLCBQdWJsaWNLZXlUb2tlbj05ZDc3Y2M3YWQzOWI2OGViBQEAAADxAVN5c3RlbS5SdW50aW1lLlNlcmlhbGl6YXRpb24uRm9ybWF0dGVycy5UZXN0cy5HZW5lcmljVHlwZVdpdGhBcmdgMVtbU3lzdGVtLlJ1bnRpbWUuU2VyaWFsaXphdGlvbi5Gb3JtYXR0ZXJzLlRlc3RzLlNvbWVUeXBlLCBTeXN0ZW0uUnVudGltZS5TZXJpYWxpemF0aW9uLkZvcm1hdHRlcnMuVGVzdHMsIFZlcnNpb249OS45OC43Ljk4NywgQ3VsdHVyZT1uZXV0cmFsLCBQdWJsaWNLZXlUb2tlbj05ZDc3Y2M3YWQzOWI2OGViXV0BAAAABFRlc3QENlN5c3RlbS5SdW50aW1lLlNlcmlhbGl6YXRpb24uRm9ybWF0dGVycy5UZXN0cy5Tb21lVHlwZQIAAAACAAAACQMAAAAFAwAAADZTeXN0ZW0uUnVudGltZS5TZXJpYWxpemF0aW9uLkZvcm1hdHRlcnMuVGVzdHMuU29tZVR5cGUBAAAACVNvbWVGaWVsZAAIAgAAAAkAAAAL";
- var deserialized = (GenericTypeWithArg<SomeType>)DeserializeBlobToObject(serializedObj, FormatterAssemblyStyle.Simple);
+ var deserialized = (GenericTypeWithArg<SomeType>)BinaryFormatterHelpers.FromBase64String(serializedObj, FormatterAssemblyStyle.Simple);
Assert.Equal(obj, deserialized);
}
- [Theory]
- [MemberData(nameof(SerializableEqualityComparers_MemberData))]
- public void ValidateEqualityComparersAgainstBlobs(object obj, string[] blobs)
- {
- if (obj == null)
- {
- throw new ArgumentNullException("The serializable object must not be null", nameof(obj));
- }
-
- if (blobs == null || blobs.Length == 0)
- {
- throw new ArgumentOutOfRangeException($"Type {obj} has no blobs to deserialize and test equality against. Blob: " +
- SerializeObjectToBlob(obj, FormatterAssemblyStyle.Full));
- }
-
- SanityCheckBlob(obj, blobs);
-
- foreach (string blob in blobs)
- {
- ValidateEqualityComparer(DeserializeBlobToObject(blob, FormatterAssemblyStyle.Simple));
- ValidateEqualityComparer(DeserializeBlobToObject(blob, FormatterAssemblyStyle.Full));
- }
- }
-
[Fact]
public void RoundtripManyObjectsInOneStream()
{
@@ -379,7 +375,7 @@ namespace System.Runtime.Serialization.Formatters.Tests
public void Deserialize_FuzzInput(object obj, Random rand)
{
// Get the serialized data for the object
- byte[] data = SerializeObjectToRaw(obj, FormatterAssemblyStyle.Simple);
+ byte[] data = BinaryFormatterHelpers.ToByteArray(obj, FormatterAssemblyStyle.Simple);
// Make some "random" changes to it
for (int i = 1; i < rand.Next(1, 100); i++)
@@ -390,7 +386,7 @@ namespace System.Runtime.Serialization.Formatters.Tests
// Try to deserialize that.
try
{
- DeserializeRawToObject(data, FormatterAssemblyStyle.Simple);
+ BinaryFormatterHelpers.FromByteArray(data, FormatterAssemblyStyle.Simple);
// Since there's no checksum, it's possible we changed data that didn't corrupt the instance
}
catch (ArgumentOutOfRangeException) { }
@@ -465,5 +461,158 @@ namespace System.Runtime.Serialization.Formatters.Tests
{
BinaryFormatterHelpers.Clone(Array.CreateInstance(typeof(uint[]), new[] { 5 }, new[] { 1 }));
}
+
+ private static void CheckForAnyEquals(object obj, object deserializedObj)
+ {
+ Assert.True(EqualityExtensions.CheckEquals(obj, deserializedObj), "Error during equality check of type " + obj?.GetType()?.FullName);
+ }
+
+ private static void ValidateEqualityComparer(object obj)
+ {
+ Type objType = obj.GetType();
+ Assert.True(objType.IsGenericType, $"Type `{objType.FullName}` must be generic.");
+ Assert.Equal("System.Collections.Generic.ObjectEqualityComparer`1", objType.GetGenericTypeDefinition().FullName);
+ Assert.Equal(obj.GetType().GetGenericArguments()[0], objType.GetGenericArguments()[0]);
+ }
+
+ private static void SanityCheckBlob(object obj, string[] blobs)
+ {
+ // These types are unstable during serialization and produce different blobs.
+ if (obj is WeakReference<Point> ||
+ obj is Collections.Specialized.HybridDictionary ||
+ obj is TimeZoneInfo.AdjustmentRule)
+ {
+ return;
+ }
+
+ // Exceptions in Net Native can't be reflected and therefore skipping blob sanity check
+ if (obj is Exception && PlatformDetection.IsNetNative)
+ {
+ return;
+ }
+
+ // Check if runtime generated blob is the same as the stored one
+ int frameworkBlobNumber = PlatformDetection.IsFullFramework ? 1 : 0;
+ if (frameworkBlobNumber < blobs.Length)
+ {
+ string runtimeBlob = BinaryFormatterHelpers.ToBase64String(obj, FormatterAssemblyStyle.Full);
+
+ string storedComparableBlob = CreateComparableBlobInfo(blobs[frameworkBlobNumber]);
+ string runtimeComparableBlob = CreateComparableBlobInfo(runtimeBlob);
+
+ Assert.True(storedComparableBlob == runtimeComparableBlob,
+ $"The stored blob for type {obj.GetType().FullName} is outdated and needs to be updated.{Environment.NewLine}{Environment.NewLine}" +
+ $"-------------------- Stored blob ---------------------{Environment.NewLine}" +
+ $"Encoded: {blobs[frameworkBlobNumber]}{Environment.NewLine}" +
+ $"Decoded: {storedComparableBlob}{Environment.NewLine}{Environment.NewLine}" +
+ $"--------------- Runtime generated blob ---------------{Environment.NewLine}" +
+ $"Encoded: {runtimeBlob}{Environment.NewLine}" +
+ $"Decoded: {runtimeComparableBlob}");
+ }
+ }
+
+ private static string GetTestDataFilePath()
+ {
+ string GetRepoRootPath()
+ {
+ var exeFile = new FileInfo(Assembly.GetExecutingAssembly().Location);
+
+ DirectoryInfo root = exeFile.Directory;
+ while (!Directory.Exists(Path.Combine(root.FullName, ".git")))
+ {
+ if (root.Parent == null)
+ return null;
+
+ root = root.Parent;
+ }
+
+ return root.FullName;
+ }
+
+ // Get path to binary formatter test data
+ string repositoryRootPath = GetRepoRootPath();
+ Assert.NotNull(repositoryRootPath);
+ string testDataFilePath = Path.Combine(repositoryRootPath, "src", "System.Runtime.Serialization.Formatters", "tests", "BinaryFormatterTestData.cs");
+ Assert.True(File.Exists(testDataFilePath));
+
+ return testDataFilePath;
+ }
+
+ private static string CreateComparableBlobInfo(string base64Blob)
+ {
+ string lineSeparator = ((char)0x2028).ToString();
+ string paragraphSeparator = ((char)0x2029).ToString();
+
+ byte[] data = Convert.FromBase64String(base64Blob);
+ base64Blob = Encoding.UTF8.GetString(data);
+
+ return Regex.Replace(base64Blob, @"Version=\d.\d.\d.\d.", "Version=0.0.0.0", RegexOptions.Multiline)
+ .Replace("\r\n", string.Empty)
+ .Replace("\n", string.Empty)
+ .Replace("\r", string.Empty)
+ .Replace(lineSeparator, string.Empty)
+ .Replace(paragraphSeparator, string.Empty);
+ }
+
+ private static (int blobs, int foundBlobs, int updatedBlobs) UpdateCoreTypeBlobs(string testDataFilePath, string[] blobs)
+ {
+ // Replace existing test data blobs with updated ones
+ string[] testDataLines = File.ReadAllLines(testDataFilePath);
+ List<string> updatedTestDataLines = new List<string>();
+ int numberOfBlobs = 0;
+ int numberOfFoundBlobs = 0;
+ int numberOfUpdatedBlobs = 0;
+
+ for (int i = 0; i < testDataLines.Length; i++)
+ {
+ string testDataLine = testDataLines[i];
+ if (!testDataLine.Trim().StartsWith("yield") || numberOfBlobs >= blobs.Length)
+ {
+ updatedTestDataLines.Add(testDataLine);
+ continue;
+ }
+
+ string pattern = null;
+ string replacement = null;
+ if (PlatformDetection.IsFullFramework)
+ {
+ pattern = ", \"AAEAAAD[^\"]+\"(?!,)";
+ replacement = ", \"" + blobs[numberOfBlobs] + "\"";
+ }
+ else
+ {
+ pattern = "\"AAEAAAD[^\"]+\",";
+ replacement = "\"" + blobs[numberOfBlobs] + "\",";
+ }
+
+ Regex regex = new Regex(pattern);
+ Match match = regex.Match(testDataLine);
+ if (match.Success)
+ {
+ numberOfFoundBlobs++;
+ }
+ string updatedLine = regex.Replace(testDataLine, replacement);
+ if (testDataLine != updatedLine)
+ {
+ numberOfUpdatedBlobs++;
+ }
+ testDataLine = updatedLine;
+
+ updatedTestDataLines.Add(testDataLine);
+ numberOfBlobs++;
+ }
+
+ // Check if all blobs were recognized and write updates to file
+ Assert.Equal(numberOfBlobs, blobs.Length);
+ File.WriteAllLines(testDataFilePath, updatedTestDataLines);
+
+ return (numberOfBlobs, numberOfFoundBlobs, numberOfUpdatedBlobs);
+ }
+
+ private class DelegateBinder : SerializationBinder
+ {
+ public Func<string, string, Type> BindToTypeDelegate = null;
+ public override Type BindToType(string assemblyName, string typeName) => BindToTypeDelegate?.Invoke(assemblyName, typeName);
+ }
}
}
diff --git a/src/System.Runtime.Serialization.Formatters/tests/EqualityExtensions.cs b/src/System.Runtime.Serialization.Formatters/tests/EqualityExtensions.cs
index 1c9d72f46c..d0bd9245b1 100644
--- a/src/System.Runtime.Serialization.Formatters/tests/EqualityExtensions.cs
+++ b/src/System.Runtime.Serialization.Formatters/tests/EqualityExtensions.cs
@@ -12,6 +12,7 @@ using System.Data.SqlTypes;
using System.Globalization;
using System.Linq;
using System.Net;
+using System.Reflection;
using System.Runtime.CompilerServices;
using Xunit;
@@ -19,6 +20,104 @@ namespace System.Runtime.Serialization.Formatters.Tests
{
public static class EqualityExtensions
{
+ private static MethodInfo GetExtensionMethod(Type extendedType)
+ {
+ if (extendedType.IsGenericType)
+ {
+ MethodInfo method = typeof(EqualityExtensions).GetMethods()
+ ?.SingleOrDefault(m =>
+ m.Name == "IsEqual" &&
+ m.GetParameters().Length == 2 &&
+ m.GetParameters()[0].ParameterType.Name == extendedType.Name &&
+ m.IsGenericMethodDefinition);
+ if (method != null)
+ return method.MakeGenericMethod(extendedType.GenericTypeArguments[0]);
+ }
+
+ return typeof(EqualityExtensions).GetMethod("IsEqual", new[] { extendedType, extendedType });
+ }
+
+ public static bool CheckEquals(object objA, object objB)
+ {
+ if (objA == null && objB == null)
+ return true;
+
+ if (objA != null && objB != null)
+ {
+ object equalityResult = null;
+ Type objType = objA.GetType();
+
+ // Check if custom equality extension method is available
+ MethodInfo customEqualityCheck = GetExtensionMethod(objType);
+ if (customEqualityCheck != null)
+ {
+ equalityResult = customEqualityCheck.Invoke(objA, new object[] { objA, objB });
+ }
+ else
+ {
+ // Check if object.Equals(object) is overridden and if not check if there is a more concrete equality check implementation
+ bool equalsNotOverridden = objType.GetMethod("Equals", new Type[] { typeof(object) }).DeclaringType == typeof(object);
+ if (equalsNotOverridden)
+ {
+ // If type doesn't override Equals(object) method then check if there is a more concrete implementation
+ // e.g. if type implements IEquatable<T>.
+ MethodInfo equalsMethod = objType.GetMethod("Equals", new Type[] { objType });
+ if (equalsMethod.DeclaringType != typeof(object))
+ {
+ equalityResult = equalsMethod.Invoke(objA, new object[] { objB });
+ }
+ }
+ }
+
+ if (equalityResult != null)
+ {
+ return (bool)equalityResult;
+ }
+ }
+
+ if (objA is IEnumerable objAEnumerable && objB is IEnumerable objBEnumerable)
+ {
+ return CheckSequenceEquals(objAEnumerable, objBEnumerable);
+ }
+
+ return objA.Equals(objB);
+ }
+
+ public static bool CheckSequenceEquals(this IEnumerable @this, IEnumerable other)
+ {
+ if (@this == null || other == null)
+ return @this == other;
+
+ if (@this.GetType() != other.GetType())
+ return false;
+
+ IEnumerator eA = null;
+ IEnumerator eB = null;
+
+ try
+ {
+ eA = (@this as IEnumerable).GetEnumerator();
+ eB = (@this as IEnumerable).GetEnumerator();
+ while (true)
+ {
+ bool moved = eA.MoveNext();
+ if (moved != eB.MoveNext())
+ return false;
+ if (!moved)
+ return true;
+ if (eA.Current == null && eB.Current == null)
+ return true;
+ if (!CheckEquals(eA.Current, eB.Current))
+ return true;
+ }
+ }
+ finally
+ {
+ (eA as IDisposable)?.Dispose();
+ (eB as IDisposable)?.Dispose();
+ }
+ }
+
public static bool IsEqual(this WeakReference @this, WeakReference other)
{
if (@this == null || other == null)
@@ -90,7 +189,7 @@ namespace System.Runtime.Serialization.Formatters.Tests
@this.Locale.LCID == other.Locale.LCID &&
@this.EnforceConstraints == other.EnforceConstraints &&
@this.ExtendedProperties?.Count == other.ExtendedProperties?.Count &&
- BinaryFormatterTests.CheckEquals(@this.ExtendedProperties, other.ExtendedProperties);
+ CheckEquals(@this.ExtendedProperties, other.ExtendedProperties);
}
public static bool IsEqual(this DataTable @this, DataTable other)
@@ -153,7 +252,7 @@ namespace System.Runtime.Serialization.Formatters.Tests
for (int i = 0; i < @this.Count; i++)
{
- if (!BinaryFormatterTests.CheckEquals(@this[i], other[i]))
+ if (!CheckEquals(@this[i], other[i]))
return false;
}
@@ -170,17 +269,17 @@ namespace System.Runtime.Serialization.Formatters.Tests
@this.IsSynchronized == other.IsSynchronized))
return false;
- return BinaryFormatterTests.CheckSequenceEquals(@this, other);
+ return CheckSequenceEquals(@this, other);
}
public static bool IsEqual(this Dictionary<int, string> @this, Dictionary<int, string> other)
{
if (!(@this != null &&
other != null &&
- BinaryFormatterTests.CheckEquals(@this.Comparer, other.Comparer) &&
+ CheckEquals(@this.Comparer, other.Comparer) &&
@this.Count == other.Count &&
- BinaryFormatterTests.CheckSequenceEquals(@this.Keys, other.Keys) &&
- BinaryFormatterTests.CheckSequenceEquals(@this.Values, other.Values)))
+ @this.Keys.CheckSequenceEquals(other.Keys) &&
+ @this.Values.CheckSequenceEquals(other.Values)))
return false;
foreach (var kv in @this)
@@ -203,10 +302,10 @@ namespace System.Runtime.Serialization.Formatters.Tests
if (!(@this != null &&
other != null &&
@this.Count == other.Count &&
- BinaryFormatterTests.CheckEquals(@this.Comparer, other.Comparer)))
+ CheckEquals(@this.Comparer, other.Comparer)))
return false;
- return BinaryFormatterTests.CheckSequenceEquals(@this, other);
+ return @this.CheckSequenceEquals(other);
}
public static bool IsEqual(this LinkedListNode<Point> @this, LinkedListNode<Point> other)
@@ -216,7 +315,7 @@ namespace System.Runtime.Serialization.Formatters.Tests
return @this != null
&& other != null &&
- BinaryFormatterTests.CheckEquals(@this.Value, other.Value);
+ CheckEquals(@this.Value, other.Value);
}
public static bool IsEqual(this LinkedList<Point> @this, LinkedList<Point> other)
@@ -228,7 +327,7 @@ namespace System.Runtime.Serialization.Formatters.Tests
IsEqual(@this.Last, other.Last)))
return false;
- return BinaryFormatterTests.CheckSequenceEquals(@this, other);
+ return @this.CheckSequenceEquals(other);
}
public static bool IsEqual(this List<int> @this, List<int> other)
@@ -239,7 +338,7 @@ namespace System.Runtime.Serialization.Formatters.Tests
@this.Count == other.Count))
return false;
- return BinaryFormatterTests.CheckSequenceEquals(@this, other);
+ return @this.CheckSequenceEquals(other);
}
public static bool IsEqual(this Queue<int> @this, Queue<int> other)
@@ -249,7 +348,7 @@ namespace System.Runtime.Serialization.Formatters.Tests
@this.Count == other.Count))
return false;
- return BinaryFormatterTests.CheckSequenceEquals(@this, other);
+ return @this.CheckSequenceEquals(other);
}
public static bool IsEqual(this SortedList<int, Point> @this, SortedList<int, Point> other)
@@ -257,13 +356,13 @@ namespace System.Runtime.Serialization.Formatters.Tests
if (!(@this != null &&
other != null &&
@this.Capacity == other.Capacity &&
- BinaryFormatterTests.CheckEquals(@this.Comparer, other.Comparer) &&
+ CheckEquals(@this.Comparer, other.Comparer) &&
@this.Count == other.Count &&
- BinaryFormatterTests.CheckSequenceEquals(@this.Keys, other.Keys) &&
- BinaryFormatterTests.CheckSequenceEquals(@this.Values, other.Values)))
+ @this.Keys.CheckSequenceEquals(other.Keys) &&
+ @this.Values.CheckSequenceEquals(other.Values)))
return false;
- return BinaryFormatterTests.CheckSequenceEquals(@this, other);
+ return @this.CheckSequenceEquals(other);
}
public static bool IsEqual(this SortedSet<Point> @this, SortedSet<Point> other)
@@ -271,12 +370,12 @@ namespace System.Runtime.Serialization.Formatters.Tests
if (!(@this != null &&
other != null &&
@this.Count == other.Count &&
- BinaryFormatterTests.CheckEquals(@this.Comparer, other.Comparer) &&
- BinaryFormatterTests.CheckEquals(@this.Min, other.Min) &&
- BinaryFormatterTests.CheckEquals(@this.Max, other.Max)))
+ CheckEquals(@this.Comparer, other.Comparer) &&
+ CheckEquals(@this.Min, other.Min) &&
+ CheckEquals(@this.Max, other.Max)))
return false;
- return BinaryFormatterTests.CheckSequenceEquals(@this, other);
+ return @this.CheckSequenceEquals(other);
}
public static bool IsEqual(this Stack<Point> @this, Stack<Point> other)
@@ -286,7 +385,7 @@ namespace System.Runtime.Serialization.Formatters.Tests
@this.Count == other.Count))
return false;
- return BinaryFormatterTests.CheckSequenceEquals(@this, other);
+ return @this.CheckSequenceEquals(other);
}
public static bool IsEqual(this Hashtable @this, Hashtable other)
@@ -296,14 +395,14 @@ namespace System.Runtime.Serialization.Formatters.Tests
@this.IsReadOnly == other.IsReadOnly &&
@this.IsFixedSize == other.IsFixedSize &&
@this.IsSynchronized == other.IsSynchronized &&
- BinaryFormatterTests.CheckSequenceEquals(@this.Keys, other.Keys) &&
- BinaryFormatterTests.CheckSequenceEquals(@this.Values, other.Values) &&
+ @this.Keys.CheckSequenceEquals(other.Keys) &&
+ @this.Values.CheckSequenceEquals(other.Values) &&
@this.Count == other.Count))
return false;
foreach (var key in @this.Keys)
{
- if (!BinaryFormatterTests.CheckEquals(@this[key], other[key]))
+ if (!CheckEquals(@this[key], other[key]))
return false;
}
@@ -317,7 +416,7 @@ namespace System.Runtime.Serialization.Formatters.Tests
@this.Count == other.Count))
return false;
- return BinaryFormatterTests.CheckSequenceEquals(@this, other);
+ return @this.CheckSequenceEquals(other);
}
public static bool IsEqual(this ObservableCollection<int> @this, ObservableCollection<int> other)
@@ -327,7 +426,7 @@ namespace System.Runtime.Serialization.Formatters.Tests
@this.Count == other.Count))
return false;
- return BinaryFormatterTests.CheckSequenceEquals(@this, other);
+ return @this.CheckSequenceEquals(other);
}
public static bool IsEqual(this ReadOnlyCollection<int> @this, ReadOnlyCollection<int> other)
@@ -337,15 +436,15 @@ namespace System.Runtime.Serialization.Formatters.Tests
@this.Count == other.Count))
return false;
- return BinaryFormatterTests.CheckSequenceEquals(@this, other);
+ return @this.CheckSequenceEquals(other);
}
public static bool IsEqual(this ReadOnlyDictionary<int, string> @this, ReadOnlyDictionary<int, string> other)
{
if (!(@this != null &&
other != null &&
- BinaryFormatterTests.CheckSequenceEquals(@this.Keys, other.Keys) &&
- BinaryFormatterTests.CheckSequenceEquals(@this.Values, other.Values) &&
+ @this.Keys.CheckSequenceEquals(other.Keys) &&
+ @this.Values.CheckSequenceEquals(other.Values) &&
@this.Count == other.Count))
return false;
@@ -365,7 +464,7 @@ namespace System.Runtime.Serialization.Formatters.Tests
@this.Count == other.Count))
return false;
- return BinaryFormatterTests.CheckSequenceEquals(@this, other);
+ return @this.CheckSequenceEquals(other);
}
public static bool IsEqual(this Queue @this, Queue other)
@@ -376,7 +475,7 @@ namespace System.Runtime.Serialization.Formatters.Tests
@this.IsSynchronized == other.IsSynchronized))
return false;
- return BinaryFormatterTests.CheckSequenceEquals(@this, other);
+ return @this.CheckSequenceEquals(other);
}
public static bool IsEqual(this SortedList @this, SortedList other)
@@ -385,14 +484,14 @@ namespace System.Runtime.Serialization.Formatters.Tests
other != null &&
@this.Capacity == other.Capacity &&
@this.Count == other.Count &&
- BinaryFormatterTests.CheckSequenceEquals(@this.Keys, other.Keys) &&
- BinaryFormatterTests.CheckSequenceEquals(@this.Values, other.Values) &&
+ @this.Keys.CheckSequenceEquals(other.Keys) &&
+ @this.Values.CheckSequenceEquals(other.Values) &&
@this.IsReadOnly == other.IsReadOnly &&
@this.IsFixedSize == other.IsFixedSize &&
@this.IsSynchronized == other.IsSynchronized))
return false;
- return BinaryFormatterTests.CheckSequenceEquals(@this, other);
+ return @this.CheckSequenceEquals(other);
}
public static bool IsEqual(this HybridDictionary @this, HybridDictionary other)
@@ -400,16 +499,16 @@ namespace System.Runtime.Serialization.Formatters.Tests
if (!(@this != null &&
other != null &&
@this.Count == other.Count &&
- BinaryFormatterTests.CheckSequenceEquals(@this.Keys, other.Keys) &&
+ @this.Keys.CheckSequenceEquals(other.Keys) &&
@this.IsReadOnly == other.IsReadOnly &&
@this.IsFixedSize == other.IsFixedSize &&
@this.IsSynchronized == other.IsSynchronized &&
- BinaryFormatterTests.CheckSequenceEquals(@this.Values, other.Values)))
+ @this.Values.CheckSequenceEquals(other.Values)))
return false;
foreach (var key in @this.Keys)
{
- if (!BinaryFormatterTests.CheckEquals(@this[key], other[key]))
+ if (!CheckEquals(@this[key], other[key]))
return false;
}
@@ -421,16 +520,16 @@ namespace System.Runtime.Serialization.Formatters.Tests
if (!(@this != null &&
other != null &&
@this.Count == other.Count &&
- BinaryFormatterTests.CheckSequenceEquals(@this.Keys, other.Keys) &&
+ @this.Keys.CheckSequenceEquals(other.Keys) &&
@this.IsReadOnly == other.IsReadOnly &&
@this.IsFixedSize == other.IsFixedSize &&
@this.IsSynchronized == other.IsSynchronized &&
- BinaryFormatterTests.CheckSequenceEquals(@this.Values, other.Values)))
+ @this.Values.CheckSequenceEquals(other.Values)))
return false;
foreach (var key in @this.Keys)
{
- if (!BinaryFormatterTests.CheckEquals(@this[key], other[key]))
+ if (!CheckEquals(@this[key], other[key]))
return false;
}
@@ -441,14 +540,14 @@ namespace System.Runtime.Serialization.Formatters.Tests
{
if (!(@this != null &&
other != null &&
- BinaryFormatterTests.CheckSequenceEquals(@this.AllKeys, other.AllKeys) &&
+ @this.AllKeys.CheckSequenceEquals(other.AllKeys) &&
@this.Count == other.Count &&
- BinaryFormatterTests.CheckSequenceEquals(@this.Keys, other.Keys)))
+ @this.Keys.CheckSequenceEquals(other.Keys)))
return false;
foreach (var key in @this.AllKeys)
{
- if (!BinaryFormatterTests.CheckEquals(@this[key], other[key]))
+ if (!CheckEquals(@this[key], other[key]))
return false;
}
@@ -461,13 +560,13 @@ namespace System.Runtime.Serialization.Formatters.Tests
other != null &&
@this.Count == other.Count &&
@this.IsReadOnly == other.IsReadOnly &&
- BinaryFormatterTests.CheckEquals(@this.Keys, other.Keys) &&
- BinaryFormatterTests.CheckEquals(@this.Values, other.Values)))
+ CheckEquals(@this.Keys, other.Keys) &&
+ CheckEquals(@this.Values, other.Values)))
return false;
foreach (var key in @this.Keys)
{
- if (!BinaryFormatterTests.CheckEquals(@this[key], other[key]))
+ if (!CheckEquals(@this[key], other[key]))
return false;
}
@@ -483,7 +582,7 @@ namespace System.Runtime.Serialization.Formatters.Tests
@this.IsSynchronized == other.IsSynchronized))
return false;
- return BinaryFormatterTests.CheckSequenceEquals(@this, other);
+ return @this.CheckSequenceEquals(other);
}
public static bool IsEqual(this Stack @this, Stack other)
@@ -494,7 +593,7 @@ namespace System.Runtime.Serialization.Formatters.Tests
@this.IsSynchronized == other.IsSynchronized))
return false;
- return BinaryFormatterTests.CheckSequenceEquals(@this, other);
+ return @this.CheckSequenceEquals(other);
}
public static bool IsEqual(this BindingList<int> @this, BindingList<int> other)
@@ -508,7 +607,7 @@ namespace System.Runtime.Serialization.Formatters.Tests
@this.Count == other.Count))
return false;
- return BinaryFormatterTests.CheckSequenceEquals(@this, other);
+ return @this.CheckSequenceEquals(other);
}
public static bool IsEqual(this BindingList<Point> @this, BindingList<Point> other)
@@ -522,7 +621,7 @@ namespace System.Runtime.Serialization.Formatters.Tests
@this.Count == other.Count))
return false;
- return BinaryFormatterTests.CheckSequenceEquals(@this, other);
+ return @this.CheckSequenceEquals(other);
}
public static bool IsEqual(this PropertyCollection @this, PropertyCollection other)
@@ -532,12 +631,12 @@ namespace System.Runtime.Serialization.Formatters.Tests
@this.IsReadOnly == other.IsReadOnly &&
@this.IsFixedSize == other.IsFixedSize &&
@this.IsSynchronized == other.IsSynchronized &&
- BinaryFormatterTests.CheckSequenceEquals(@this.Keys, other.Keys) &&
- BinaryFormatterTests.CheckSequenceEquals(@this.Values, other.Values) &&
+ @this.Keys.CheckSequenceEquals(other.Keys) &&
+ @this.Values.CheckSequenceEquals(other.Values) &&
@this.Count == other.Count))
return false;
- return BinaryFormatterTests.CheckSequenceEquals(@this, other);
+ return @this.CheckSequenceEquals(other);
}
public static bool IsEqual(this CompareInfo @this, CompareInfo other)
@@ -569,14 +668,14 @@ namespace System.Runtime.Serialization.Formatters.Tests
@this.Discard == other.Discard &&
@this.Domain == other.Domain &&
@this.Expired == other.Expired &&
- BinaryFormatterTests.CheckEquals(@this.Expires, other.Expires) &&
+ CheckEquals(@this.Expires, other.Expires) &&
@this.Name == other.Name &&
@this.Path == other.Path &&
@this.Port == other.Port &&
@this.Secure == other.Secure &&
// This needs to have m_Timestamp set by reflection in order to roundtrip correctly
// otherwise this field will change each time you create an object and cause this to fail
- BinaryFormatterTests.CheckEquals(@this.TimeStamp, other.TimeStamp) &&
+ CheckEquals(@this.TimeStamp, other.TimeStamp) &&
@this.Value == other.Value &&
@this.Version == other.Version;
}
@@ -588,7 +687,7 @@ namespace System.Runtime.Serialization.Formatters.Tests
@this.Count == other.Count))
return false;
- return BinaryFormatterTests.CheckSequenceEquals(@this, other);
+ return @this.CheckSequenceEquals(other);
}
public static bool IsEqual(this BasicISerializableObject @this, BasicISerializableObject other)
@@ -672,7 +771,7 @@ namespace System.Runtime.Serialization.Formatters.Tests
return false;
}
- return BinaryFormatterTests.CheckEquals(thisFlattened.Item2, otherFlattened.Item2);
+ return CheckEquals(thisFlattened.Item2, otherFlattened.Item2);
}
public static bool IsEqual(this ArraySegment<int> @this, ArraySegment<int> other)
@@ -682,19 +781,19 @@ namespace System.Runtime.Serialization.Formatters.Tests
@this.Offset == other.Offset))
return false;
- return @this.Array == null || BinaryFormatterTests.CheckSequenceEquals(@this, other);
+ return @this.Array == null || @this.CheckSequenceEquals(other);
}
public static bool IsEqual(this ObjectWithArrays @this, ObjectWithArrays other)
{
return @this != null &&
other != null &&
- BinaryFormatterTests.CheckEquals(@this.IntArray, other.IntArray) &&
- BinaryFormatterTests.CheckEquals(@this.StringArray, other.StringArray) &&
- BinaryFormatterTests.CheckEquals(@this.TreeArray, other.TreeArray) &&
- BinaryFormatterTests.CheckEquals(@this.ByteArray, other.ByteArray) &&
- BinaryFormatterTests.CheckEquals(@this.JaggedArray, other.JaggedArray) &&
- BinaryFormatterTests.CheckEquals(@this.MultiDimensionalArray, other.MultiDimensionalArray);
+ CheckEquals(@this.IntArray, other.IntArray) &&
+ CheckEquals(@this.StringArray, other.StringArray) &&
+ CheckEquals(@this.TreeArray, other.TreeArray) &&
+ CheckEquals(@this.ByteArray, other.ByteArray) &&
+ CheckEquals(@this.JaggedArray, other.JaggedArray) &&
+ CheckEquals(@this.MultiDimensionalArray, other.MultiDimensionalArray);
}
public static bool IsEqual(this ObjectWithIntStringUShortUIntULongAndCustomObjectFields @this, ObjectWithIntStringUShortUIntULongAndCustomObjectFields other)
@@ -750,7 +849,7 @@ namespace System.Runtime.Serialization.Formatters.Tests
@this.Count == other.Count))
return false;
- return BinaryFormatterTests.CheckSequenceEquals(@this, other);
+ return @this.CheckSequenceEquals(other);
}
public static bool IsEqual(this Tree<Colors> @this, Tree<Colors> other)
@@ -908,21 +1007,23 @@ namespace System.Runtime.Serialization.Formatters.Tests
return @this != null &&
other != null &&
// On full framework, line number may be method body start
- (PlatformDetection.IsFullFramework ? true :
+ // On Net Native we can't reflect on Exceptions and change its StackTrace
+ ((PlatformDetection.IsFullFramework || PlatformDetection.IsNetNative) ? true :
(@this.StackTrace == other.StackTrace &&
@this.ToString() == other.ToString())) &&
- BinaryFormatterTests.CheckSequenceEquals(@this.Data, other.Data) &&
+ @this.Data.CheckSequenceEquals(other.Data) &&
@this.Message == other.Message &&
@this.Source == other.Source &&
- @this.HResult == other.HResult &&
+ // On Net Native we can't reflect on Exceptions and change its HResult
+ (PlatformDetection.IsNetNative ? true : @this.HResult == other.HResult) &&
@this.HelpLink == other.HelpLink &&
- BinaryFormatterTests.CheckEquals(@this.InnerException, other.InnerException);
+ CheckEquals(@this.InnerException, other.InnerException);
}
public static bool IsEqual(this AggregateException @this, AggregateException other)
{
return IsEqual(@this as Exception, other as Exception) &&
- BinaryFormatterTests.CheckSequenceEquals(@this.InnerExceptions, other.InnerExceptions);
+ @this.InnerExceptions.CheckSequenceEquals(other.InnerExceptions);
}
public class ReferenceComparer<T> : IEqualityComparer<T> where T: class
diff --git a/src/System.Runtime.Serialization.Formatters/tests/FormatterServicesTests.cs b/src/System.Runtime.Serialization.Formatters/tests/FormatterServicesTests.cs
index 7dd48e984d..7d29a45d2b 100644
--- a/src/System.Runtime.Serialization.Formatters/tests/FormatterServicesTests.cs
+++ b/src/System.Runtime.Serialization.Formatters/tests/FormatterServicesTests.cs
@@ -127,8 +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
+ private ref struct StructWithSpanField
{
Span<byte> _bytes;
int _position;
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 2d3acb6440..4dcd801d24 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
@@ -10,7 +10,6 @@
<PropertyGroup Condition="'$(Configuration)|$(Platform)' == 'netstandard-Debug|AnyCPU'" />
<PropertyGroup Condition="'$(Configuration)|$(Platform)' == 'netstandard-Release|AnyCPU'" />
<ItemGroup>
- <Compile Include="BinaryFormatterHelper.cs" />
<Compile Include="BinaryFormatterTestData.cs" />
<Compile Include="BinaryFormatterTests.cs" />
<Compile Include="EqualityExtensions.cs" />
@@ -40,4 +39,4 @@
<EmbeddedResource Include="BinaryFormatterTests.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.Runtime.Serialization.Json/tests/DataContractJsonSerializer.cs b/src/System.Runtime.Serialization.Json/tests/DataContractJsonSerializer.cs
index 2d7b6341dd..3b859dcc55 100644
--- a/src/System.Runtime.Serialization.Json/tests/DataContractJsonSerializer.cs
+++ b/src/System.Runtime.Serialization.Json/tests/DataContractJsonSerializer.cs
@@ -232,17 +232,41 @@ public static partial class DataContractJsonSerializerTests
var testStrings = new[]
{
+ new { value = "\u0000", baseline = "\\u0000" }, // NULL
+ new { value = "\u0001", baseline = "\\u0001" },
+ new { value = "\u0002", baseline = "\\u0002" },
+ new { value = "\u0003", baseline = "\\u0003" },
+ new { value = "\u0004", baseline = "\\u0004" },
+ new { value = "\u0005", baseline = "\\u0005" },
+ new { value = "\u0006", baseline = "\\u0006" },
+ new { value = "\u0007", baseline = "\\u0007" },
new { value = "\u0008", baseline = "\\b" }, // BACKSPACE
- new { value = "\u000C", baseline = "\\f" }, // FORM FEED (FF)
- new { value = "\u000A", baseline = "\\n" }, // LINE FEED (LF)
- new { value = "\u000D", baseline = "\\r" }, // CARRIAGE RETURN (CR)
new { value = "\u0009", baseline = "\\t" }, // HORIZONTAL TABULATION
- new { value = "\u0022", baseline = "\\\"" }, // QUOTATION MARK
- new { value = "\u005C", baseline = "\\\\" }, // REVERSE SOLIDUS
- new { value = "\u0000", baseline = "\\u0000" }, // NULL
+ new { value = "\u000A", baseline = "\\n" }, // LINE FEED (LF)
new { value = "\u000B", baseline = "\\u000b" }, // LINE TABULATION
+ new { value = "\u000C", baseline = "\\f" }, // FORM FEED (FF)
+ new { value = "\u000D", baseline = "\\r" }, // CARRIAGE RETURN (CR)
+ new { value = "\u000E", baseline = "\\u000e" },
new { value = "\u000F", baseline = "\\u000f" }, // SHIFT IN
+ new { value = "\u0010", baseline = "\\u0010" },
+ new { value = "\u0011", baseline = "\\u0011" },
+ new { value = "\u0012", baseline = "\\u0012" },
+ new { value = "\u0013", baseline = "\\u0013" },
+ new { value = "\u0014", baseline = "\\u0014" },
+ new { value = "\u0015", baseline = "\\u0015" },
+ new { value = "\u0016", baseline = "\\u0016" },
+ new { value = "\u0017", baseline = "\\u0017" },
+ new { value = "\u0018", baseline = "\\u0018" },
+ new { value = "\u0019", baseline = "\\u0019" },
+ new { value = "\u001A", baseline = "\\u001a" },
+ new { value = "\u001B", baseline = "\\u001b" },
+ new { value = "\u001C", baseline = "\\u001c" },
+ new { value = "\u001D", baseline = "\\u001d" },
+ new { value = "\u001E", baseline = "\\u001e" },
+ new { value = "\u001F", baseline = "\\u001f" },
+ new { value = "\u0022", baseline = "\\\"" }, // QUOTATION MARK
new { value = "\u0027", baseline = "'" },
+ new { value = "\u005C", baseline = "\\\\" }, // REVERSE SOLIDUS
};
foreach (var pair in testStrings)
diff --git a/src/System.Runtime.Serialization.Xml/tests/Canonicalization/XmlCanonicalizationTest.cs b/src/System.Runtime.Serialization.Xml/tests/Canonicalization/XmlCanonicalizationTest.cs
index 63fd2cebd9..b210ddc9c7 100644
--- a/src/System.Runtime.Serialization.Xml/tests/Canonicalization/XmlCanonicalizationTest.cs
+++ b/src/System.Runtime.Serialization.Xml/tests/Canonicalization/XmlCanonicalizationTest.cs
@@ -188,9 +188,9 @@ namespace System.Runtime.Serialization.Xml.Canonicalization.Tests
string rwTypeStr = input.Arguments[0].Value;
ReaderWriterFactory.ReaderWriterType rwType = (ReaderWriterFactory.ReaderWriterType)Enum.Parse(typeof(ReaderWriterFactory.ReaderWriterType), rwTypeStr, true);
Encoding encoding = Encoding.GetEncoding((string)input.Arguments[1].Value);
- string sampleXmlFileName = Path.Combine("baselines", input2.Arguments[0].Value);
+ string sampleXmlFileName = input2.Arguments[0].Value;
bool mustSupportV14N = input.Arguments[2].Value == "true";
- string baselineFileName = Path.Combine("baselines", input2.Arguments[1].Value);
+ string baselineFileName = input2.Arguments[1].Value;
bool testWithComments = input3.Arguments[0].Value == "true";
@@ -253,13 +253,13 @@ namespace System.Runtime.Serialization.Xml.Canonicalization.Tests
foreach (var input in params4.Inputs)
{
count++;
- string sampleXmlFileName = Path.Combine("baselines", input.Arguments[3].Value);
+ string sampleXmlFileName = input.Arguments[3].Value;
string rwTypeStr = input.Arguments[0].Value;
ReaderWriterFactory.ReaderWriterType rwType = (ReaderWriterFactory.ReaderWriterType)Enum.Parse(typeof(ReaderWriterFactory.ReaderWriterType), rwTypeStr, true);
Encoding encoding = Encoding.GetEncoding((string)input.Arguments[1].Value);
bool mustSupportV14N = input.Arguments[2].Value == "true";
- string baselineFileName = Path.Combine("baselines", "ReaderWriter_C14N_BaselineXML_OnlyLF.xml");
+ string baselineFileName = "ReaderWriter_C14N_BaselineXML_OnlyLF.xml";
XmlDocument xmlDoc = new XmlDocument();
xmlDoc.PreserveWhitespace = true;
@@ -384,7 +384,7 @@ namespace System.Runtime.Serialization.Xml.Canonicalization.Tests
mode = TestMode.StartAtSpecifiedElement;
}
- xmlBuffer = new XmlBuffer(Path.Combine("baselines", input.Arguments[0].Value));
+ xmlBuffer = new XmlBuffer(input.Arguments[0].Value);
engine = new Engine(includeComments, inclusivePrefixes, mode == TestMode.FullDocument);
XmlReader reader = CreateReader(mode, xmlBuffer, startAt);
diff --git a/src/System.Runtime.Serialization.Xml/tests/DataContractSerializer.cs b/src/System.Runtime.Serialization.Xml/tests/DataContractSerializer.cs
index 77af5c0c49..65c14ab817 100644
--- a/src/System.Runtime.Serialization.Xml/tests/DataContractSerializer.cs
+++ b/src/System.Runtime.Serialization.Xml/tests/DataContractSerializer.cs
@@ -3393,8 +3393,7 @@ public static partial class DataContractSerializerTests
[Fact]
- [ActiveIssue(22776,TargetFrameworkMonikers.UapAot)]
- public static void DCS_BasicPerSerializerRoundTripAndCompare_SampleTypes_FailedInuapaot_IncludeDataSet()
+ public static void DCS_BasicPerSerializerRoundTripAndCompare_DataSet()
{
TestObjectInObjectContainerWithSimpleResolver(new SerializationTestTypes.DCPublicDatasetPublic(true), @"<ObjectContainer xmlns=""http://schemas.datacontract.org/2004/07/SerializationTestTypes"" xmlns:i=""http://www.w3.org/2001/XMLSchema-instance""><_data z:Id=""i1"" i:type=""a:SerializationTestTypes.DCPublicDatasetPublic***"" xmlns:z=""http://schemas.microsoft.com/2003/10/Serialization/"" xmlns:a=""http://schemas.datacontract.org/2004/07/SerializationTestTypes.DCPublicDatasetPublic***""><dataSet><xs:schema id=""MyData"" xmlns:xs=""http://www.w3.org/2001/XMLSchema"" xmlns="""" xmlns:msdata=""urn:schemas-microsoft-com:xml-msdata""><xs:element name=""MyData"" msdata:IsDataSet=""true"" msdata:UseCurrentLocale=""true""><xs:complexType><xs:choice minOccurs=""0"" maxOccurs=""unbounded""><xs:element name=""MyTable""><xs:complexType><xs:sequence><xs:element name=""Data"" type=""xs:string"" minOccurs=""0""/></xs:sequence></xs:complexType></xs:element></xs:choice></xs:complexType></xs:element></xs:schema><diffgr:diffgram xmlns:diffgr=""urn:schemas-microsoft-com:xml-diffgram-v1"" xmlns:msdata=""urn:schemas-microsoft-com:xml-msdata""><MyData xmlns=""""><MyTable diffgr:id=""MyTable1"" msdata:rowOrder=""0"" diffgr:hasChanges=""inserted""><Data>10</Data></MyTable></MyData></diffgr:diffgram></dataSet><dataSet2><xs:schema id=""MyData"" xmlns:xs=""http://www.w3.org/2001/XMLSchema"" xmlns="""" xmlns:msdata=""urn:schemas-microsoft-com:xml-msdata""><xs:element name=""MyData"" msdata:IsDataSet=""true"" msdata:UseCurrentLocale=""true""><xs:complexType><xs:choice minOccurs=""0"" maxOccurs=""unbounded""><xs:element name=""MyTable""><xs:complexType><xs:sequence><xs:element name=""Data"" type=""xs:string"" minOccurs=""0""/></xs:sequence></xs:complexType></xs:element></xs:choice></xs:complexType></xs:element></xs:schema><diffgr:diffgram xmlns:diffgr=""urn:schemas-microsoft-com:xml-diffgram-v1"" xmlns:msdata=""urn:schemas-microsoft-com:xml-msdata""><MyData xmlns=""""><MyTable diffgr:id=""MyTable1"" msdata:rowOrder=""0"" diffgr:hasChanges=""inserted""><Data>10</Data></MyTable></MyData></diffgr:diffgram></dataSet2><dataTable><xs:schema id=""MyData"" xmlns:xs=""http://www.w3.org/2001/XMLSchema"" xmlns="""" xmlns:msdata=""urn:schemas-microsoft-com:xml-msdata""><xs:element name=""MyData"" msdata:IsDataSet=""true"" msdata:MainDataTable=""MyTable"" msdata:UseCurrentLocale=""true""><xs:complexType><xs:choice minOccurs=""0"" maxOccurs=""unbounded""><xs:element name=""MyTable""><xs:complexType><xs:sequence><xs:element name=""Data"" type=""xs:string"" minOccurs=""0""/></xs:sequence></xs:complexType></xs:element></xs:choice></xs:complexType></xs:element></xs:schema><diffgr:diffgram xmlns:diffgr=""urn:schemas-microsoft-com:xml-diffgram-v1"" xmlns:msdata=""urn:schemas-microsoft-com:xml-msdata""><MyData xmlns=""""><MyTable diffgr:id=""MyTable1"" msdata:rowOrder=""0"" diffgr:hasChanges=""inserted""><Data>10</Data></MyTable></MyData></diffgr:diffgram></dataTable><dataTable2><xs:schema id=""MyData"" xmlns:xs=""http://www.w3.org/2001/XMLSchema"" xmlns="""" xmlns:msdata=""urn:schemas-microsoft-com:xml-msdata""><xs:element name=""MyData"" msdata:IsDataSet=""true"" msdata:MainDataTable=""MyTable"" msdata:UseCurrentLocale=""true""><xs:complexType><xs:choice minOccurs=""0"" maxOccurs=""unbounded""><xs:element name=""MyTable""><xs:complexType><xs:sequence><xs:element name=""Data"" type=""xs:string"" minOccurs=""0""/></xs:sequence></xs:complexType></xs:element></xs:choice></xs:complexType></xs:element></xs:schema><diffgr:diffgram xmlns:diffgr=""urn:schemas-microsoft-com:xml-diffgram-v1"" xmlns:msdata=""urn:schemas-microsoft-com:xml-msdata""><MyData xmlns=""""><MyTable diffgr:id=""MyTable1"" msdata:rowOrder=""0"" diffgr:hasChanges=""inserted""><Data>10</Data></MyTable></MyData></diffgr:diffgram></dataTable2></_data><_data2 z:Ref=""i1"" xmlns:z=""http://schemas.microsoft.com/2003/10/Serialization/""/></ObjectContainer>");
@@ -3437,8 +3436,7 @@ public static partial class DataContractSerializerTests
}
[Fact]
- [ActiveIssue(22777, TargetFrameworkMonikers.UapAot)]
- public static void DCS_BasicPerSerializerRoundTripAndCompare_SampleTypes_FailedInuapaot_InheritedFromIList()
+ public static void DCS_BasicPerSerializerRoundTripAndCompare_TypeInheritedFromIListT()
{
string assemblyName = typeof(DataContractSerializerTests).Assembly.FullName;
@@ -3452,8 +3450,7 @@ public static partial class DataContractSerializerTests
}
[Fact]
- [ActiveIssue(22778, TargetFrameworkMonikers.UapAot)]
- public static void DCS_BasicPerSerializerRoundTripAndCompare_SampleTypes_FailedInuapaot_InheritedFromIList_CanPassInReflectionOnly()
+ public static void DCS_BasicPerSerializerRoundTripAndCompare_InheritedFromIList()
{
TestObjectInObjectContainerWithSimpleResolver(new SerializationTestTypes.SampleListExplicitWithoutDC(true), @"<ObjectContainer xmlns=""http://schemas.datacontract.org/2004/07/SerializationTestTypes"" xmlns:i=""http://www.w3.org/2001/XMLSchema-instance""><_data i:type=""a:SerializationTestTypes.SampleListExplicitWithoutDC***"" xmlns:a=""http://schemas.datacontract.org/2004/07/SerializationTestTypes.SampleListExplicitWithoutDC***""><anyType i:type=""b:dateTime"" xmlns:b=""http://www.w3.org/2001/XMLSchema"">0001-01-01T00:00:00</anyType><anyType i:type=""b:duration"" xmlns:b=""http://schemas.microsoft.com/2003/10/Serialization/"">P10675199DT2H48M5.4775807S</anyType><anyType i:type=""b:string"" xmlns:b=""http://www.w3.org/2001/XMLSchema""/><anyType i:type=""b:double"" xmlns:b=""http://www.w3.org/2001/XMLSchema"">1.7976931348623157E+308</anyType><anyType i:type=""b:double"" xmlns:b=""http://www.w3.org/2001/XMLSchema"">-INF</anyType><anyType i:type=""b:guid"" xmlns:b=""http://schemas.microsoft.com/2003/10/Serialization/"">0c9e174e-cdd8-4b68-a70d-aaeb26c7deeb</anyType></_data><_data2 i:type=""a:SerializationTestTypes.SampleListExplicitWithoutDC***"" xmlns:a=""http://schemas.datacontract.org/2004/07/SerializationTestTypes.SampleListExplicitWithoutDC***""><anyType i:type=""b:dateTime"" xmlns:b=""http://www.w3.org/2001/XMLSchema"">0001-01-01T00:00:00</anyType><anyType i:type=""b:duration"" xmlns:b=""http://schemas.microsoft.com/2003/10/Serialization/"">P10675199DT2H48M5.4775807S</anyType><anyType i:type=""b:string"" xmlns:b=""http://www.w3.org/2001/XMLSchema""/><anyType i:type=""b:double"" xmlns:b=""http://www.w3.org/2001/XMLSchema"">1.7976931348623157E+308</anyType><anyType i:type=""b:double"" xmlns:b=""http://www.w3.org/2001/XMLSchema"">-INF</anyType><anyType i:type=""b:guid"" xmlns:b=""http://schemas.microsoft.com/2003/10/Serialization/"">0c9e174e-cdd8-4b68-a70d-aaeb26c7deeb</anyType></_data2></ObjectContainer>");
@@ -3536,8 +3533,7 @@ public static partial class DataContractSerializerTests
}
[Fact]
- [ActiveIssue(22779, TargetFrameworkMonikers.UapAot)]
- public static void DCS_BasicPerSerializerRoundTripAndCompare_Collections_FailedInuapaot_InCollections()
+ public static void DCS_BasicPerSerializerRoundTripAndCompare_CollectionDataContract()
{
string assemblyName = typeof(DataContractSerializerTests).Assembly.FullName;
string corelibAssemblyName = typeof(String).Assembly.FullName;
@@ -4017,6 +4013,49 @@ public static partial class DataContractSerializerTests
Assert.Equal(0, actual.AnIntList.Count);
}
+ [Fact]
+#if !ReflectionOnly
+ [SkipOnTargetFramework(TargetFrameworkMonikers.UapAot, "dotnet-corefx #24265")]
+#endif
+ public static void DCS_TypeWithPrimitiveKnownTypes()
+ {
+ var list = new TypeWithPrimitiveKnownTypes();
+ list.Add(true);
+ list.Add('c');
+ list.Add(new DateTime(100));
+ list.Add(11.1m);
+ list.Add(22.2);
+ list.Add(33.3f);
+ list.Add(new Guid());
+ list.Add(11);
+ list.Add(1111111111111111111L);
+ list.Add(new XmlQualifiedName("NAME", "NS"));
+ list.Add((short)44);
+ list.Add((sbyte)-1);
+ list.Add("test string");
+ list.Add(new TimeSpan(100));
+ list.Add((byte)1);
+ list.Add(uint.MaxValue);
+ list.Add(ulong.MaxValue);
+ list.Add(ushort.MaxValue);
+ list.Add(new Uri("http://foo"));
+ var actual = SerializeAndDeserialize(list, "<TypeWithPrimitiveKnownTypes xmlns=\"http://schemas.datacontract.org/2004/07/\" xmlns:i=\"http://www.w3.org/2001/XMLSchema-instance\"><anyType i:type=\"a:boolean\" xmlns:a=\"http://www.w3.org/2001/XMLSchema\">true</anyType><anyType i:type=\"a:char\" xmlns:a=\"http://schemas.microsoft.com/2003/10/Serialization/\">99</anyType><anyType i:type=\"a:dateTime\" xmlns:a=\"http://www.w3.org/2001/XMLSchema\">0001-01-01T00:00:00.00001</anyType><anyType i:type=\"a:decimal\" xmlns:a=\"http://www.w3.org/2001/XMLSchema\">11.1</anyType><anyType i:type=\"a:double\" xmlns:a=\"http://www.w3.org/2001/XMLSchema\">22.2</anyType><anyType i:type=\"a:float\" xmlns:a=\"http://www.w3.org/2001/XMLSchema\">33.3</anyType><anyType i:type=\"a:guid\" xmlns:a=\"http://schemas.microsoft.com/2003/10/Serialization/\">00000000-0000-0000-0000-000000000000</anyType><anyType i:type=\"a:int\" xmlns:a=\"http://www.w3.org/2001/XMLSchema\">11</anyType><anyType i:type=\"a:long\" xmlns:a=\"http://www.w3.org/2001/XMLSchema\">1111111111111111111</anyType><anyType i:type=\"a:QName\" xmlns:a=\"http://www.w3.org/2001/XMLSchema\" xmlns:b=\"NS\">b:NAME</anyType><anyType i:type=\"a:short\" xmlns:a=\"http://www.w3.org/2001/XMLSchema\">44</anyType><anyType i:type=\"a:byte\" xmlns:a=\"http://www.w3.org/2001/XMLSchema\">-1</anyType><anyType i:type=\"a:string\" xmlns:a=\"http://www.w3.org/2001/XMLSchema\">test string</anyType><anyType i:type=\"a:duration\" xmlns:a=\"http://schemas.microsoft.com/2003/10/Serialization/\">PT0.00001S</anyType><anyType i:type=\"a:unsignedByte\" xmlns:a=\"http://www.w3.org/2001/XMLSchema\">1</anyType><anyType i:type=\"a:unsignedInt\" xmlns:a=\"http://www.w3.org/2001/XMLSchema\">4294967295</anyType><anyType i:type=\"a:unsignedLong\" xmlns:a=\"http://www.w3.org/2001/XMLSchema\">18446744073709551615</anyType><anyType i:type=\"a:unsignedShort\" xmlns:a=\"http://www.w3.org/2001/XMLSchema\">65535</anyType><anyType i:type=\"a:anyURI\" xmlns:a=\"http://www.w3.org/2001/XMLSchema\">http://foo/</anyType></TypeWithPrimitiveKnownTypes>");
+ Assert.True(Enumerable.SequenceEqual(list, actual));
+
+ list.Clear();
+ list.Add(new byte[] { 1, 2 });
+ actual = SerializeAndDeserialize(list, "<TypeWithPrimitiveKnownTypes xmlns=\"http://schemas.datacontract.org/2004/07/\" xmlns:i=\"http://www.w3.org/2001/XMLSchema-instance\"><anyType i:type=\"a:base64Binary\" xmlns:a=\"http://www.w3.org/2001/XMLSchema\">AQI=</anyType></TypeWithPrimitiveKnownTypes>");
+ Assert.NotNull(actual);
+ Assert.Single(actual);
+ Assert.True(actual[0] is byte[]);
+ Assert.True(((byte[])list[0]).SequenceEqual(((byte[])actual[0])));
+
+ list.Clear();
+ list.Add(new object());
+ actual = SerializeAndDeserialize(list, "<TypeWithPrimitiveKnownTypes xmlns=\"http://schemas.datacontract.org/2004/07/\" xmlns:i=\"http://www.w3.org/2001/XMLSchema-instance\"><anyType/></TypeWithPrimitiveKnownTypes>");
+ Assert.NotNull(actual);
+ }
+
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/ReflectionOnly/Resources/System.Runtime.Serialization.Xml.ReflectionOnly.Tests.rd.xml b/src/System.Runtime.Serialization.Xml/tests/ReflectionOnly/Resources/System.Runtime.Serialization.Xml.ReflectionOnly.Tests.rd.xml
index 969d1fe150..8cec5f715a 100644
--- a/src/System.Runtime.Serialization.Xml/tests/ReflectionOnly/Resources/System.Runtime.Serialization.Xml.ReflectionOnly.Tests.rd.xml
+++ b/src/System.Runtime.Serialization.Xml/tests/ReflectionOnly/Resources/System.Runtime.Serialization.Xml.ReflectionOnly.Tests.rd.xml
@@ -25,5 +25,13 @@
<Type Name="ReadOnlyDictionary`2" Dynamic="Required All" />
</Namespace>
<Type Name="System.Version" Dynamic="Required All" />
+ <Namespace Name="System.Data">
+ <Type Name="DataSet">
+ <Method Name="GetDataSetSchema" Dynamic="Required Public"/>
+ </Type>
+ <Type Name="DataTable">
+ <Method Name="GetDataTableSchema" Dynamic="Required Public"/>
+ </Type>
+ </Namespace>
</Library>
</Directives>
diff --git a/src/System.Runtime.Serialization.Xml/tests/Resources/System.Runtime.Serialization.Xml.Tests.rd.xml b/src/System.Runtime.Serialization.Xml/tests/Resources/System.Runtime.Serialization.Xml.Tests.rd.xml
new file mode 100644
index 0000000000..6806e15e9f
--- /dev/null
+++ b/src/System.Runtime.Serialization.Xml/tests/Resources/System.Runtime.Serialization.Xml.Tests.rd.xml
@@ -0,0 +1,16 @@
+<?xml version="1.0" encoding="utf-8" ?>
+<Directives xmlns="http://schemas.microsoft.com/netfx/2013/01/metadata">
+ <Library Name="*System.Runtime.Serialization.Xml.Tests*">
+ <Namespace Name="System.Data">
+ <Type Name="DataSet">
+ <Method Name="GetDataSetSchema" Dynamic="Required Public"/>
+ </Type>
+ <Type Name="DataTable">
+ <Method Name="GetDataTableSchema" Dynamic="Required Public"/>
+ </Type>
+ </Namespace>
+ <Namespace Name="System.Collections">
+ <Type Name="IList" Dynamic="Required All" />
+ </Namespace>
+ </Library>
+</Directives>
diff --git a/src/System.Runtime.Serialization.Xml/tests/SerializationTypes.RuntimeOnly.cs b/src/System.Runtime.Serialization.Xml/tests/SerializationTypes.RuntimeOnly.cs
index 5b961b63d6..9271888fd1 100644
--- a/src/System.Runtime.Serialization.Xml/tests/SerializationTypes.RuntimeOnly.cs
+++ b/src/System.Runtime.Serialization.Xml/tests/SerializationTypes.RuntimeOnly.cs
@@ -4360,3 +4360,30 @@ public class TypeWithCollectionAndDateTimeOffset
public DateTimeOffset DateTimeOffset { get; set; }
}
+
+[KnownType(typeof(bool))]
+[KnownType(typeof(byte[]))]
+[KnownType(typeof(char))]
+[KnownType(typeof(DateTime))]
+[KnownType(typeof(decimal))]
+[KnownType(typeof(double))]
+[KnownType(typeof(float))]
+[KnownType(typeof(Guid))]
+[KnownType(typeof(int))]
+[KnownType(typeof(long))]
+[KnownType(typeof(object))]
+[KnownType(typeof(XmlQualifiedName))]
+[KnownType(typeof(short))]
+[KnownType(typeof(sbyte))]
+[KnownType(typeof(string))]
+[KnownType(typeof(TimeSpan))]
+[KnownType(typeof(byte))]
+[KnownType(typeof(uint))]
+[KnownType(typeof(ulong))]
+[KnownType(typeof(ushort))]
+[KnownType(typeof(Uri))]
+[CollectionDataContract]
+public class TypeWithPrimitiveKnownTypes : List<object>
+{
+
+}
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 568ae146bb..1e93b0e108 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
@@ -40,5 +40,8 @@
<Compile Include="$(TestSourceFolder)SerializationTypes.CoreCLR.cs" />
<Compile Include="$(TestSourceFolder)DataContractSerializer.CoreCLR.cs" />
</ItemGroup>
+ <ItemGroup Condition="'$(TargetGroup)'=='uapaot'">
+ <EmbeddedResource Include="$(MsBuildThisFileDirectory)Resources\$(AssemblyName).rd.xml" />
+ </ItemGroup>
<Import Project="$([MSBuild]::GetDirectoryNameOfFileAbove($(MSBuildThisFileDirectory), dir.targets))\dir.targets" />
</Project> \ No newline at end of file
diff --git a/src/System.Runtime.WindowsRuntime/src/System/IO/NetFxToWinRtStreamAdapter.cs b/src/System.Runtime.WindowsRuntime/src/System/IO/NetFxToWinRtStreamAdapter.cs
index 52ac810801..4bbf2fc978 100644
--- a/src/System.Runtime.WindowsRuntime/src/System/IO/NetFxToWinRtStreamAdapter.cs
+++ b/src/System.Runtime.WindowsRuntime/src/System/IO/NetFxToWinRtStreamAdapter.cs
@@ -193,7 +193,7 @@ namespace System.IO
if (str == null)
{
ObjectDisposedException ex = new ObjectDisposedException(SR.ObjectDisposed_CannotPerformOperation);
- ex.SetErrorCode(HResults.RO_E_CLOSED);
+ ex.SetErrorCode(__HResults.RO_E_CLOSED);
throw ex;
}
@@ -234,14 +234,14 @@ namespace System.IO
if (count < 0 || Int32.MaxValue < count)
{
ArgumentOutOfRangeException ex = new ArgumentOutOfRangeException(nameof(count));
- ex.SetErrorCode(HResults.E_INVALIDARG);
+ ex.SetErrorCode(__HResults.E_INVALIDARG);
throw ex;
}
if (buffer.Capacity < count)
{
ArgumentException ex = new ArgumentException(SR.Argument_InsufficientBufferCapacity);
- ex.SetErrorCode(HResults.E_INVALIDARG);
+ ex.SetErrorCode(__HResults.E_INVALIDARG);
throw ex;
}
@@ -249,7 +249,7 @@ namespace System.IO
{
ArgumentOutOfRangeException ex = new ArgumentOutOfRangeException(nameof(options),
SR.ArgumentOutOfRange_InvalidInputStreamOptionsEnumValue);
- ex.SetErrorCode(HResults.E_INVALIDARG);
+ ex.SetErrorCode(__HResults.E_INVALIDARG);
throw ex;
}
@@ -300,7 +300,7 @@ namespace System.IO
if (buffer.Capacity < buffer.Length)
{
ArgumentException ex = new ArgumentException(SR.Argument_BufferLengthExceedsCapacity);
- ex.SetErrorCode(HResults.E_INVALIDARG);
+ ex.SetErrorCode(__HResults.E_INVALIDARG);
throw ex;
}
@@ -335,7 +335,7 @@ namespace System.IO
if (position > Int64.MaxValue)
{
ArgumentException ex = new ArgumentException(SR.IO_CannotSeekBeyondInt64MaxValue);
- ex.SetErrorCode(HResults.E_INVALIDARG);
+ ex.SetErrorCode(__HResults.E_INVALIDARG);
throw ex;
}
@@ -400,7 +400,7 @@ namespace System.IO
if (value > Int64.MaxValue)
{
ArgumentException ex = new ArgumentException(SR.IO_CannotSetSizeBeyondInt64MaxValue);
- ex.SetErrorCode(HResults.E_INVALIDARG);
+ ex.SetErrorCode(__HResults.E_INVALIDARG);
throw ex;
}
@@ -412,7 +412,7 @@ namespace System.IO
if (!str.CanWrite)
{
InvalidOperationException ex = new InvalidOperationException(SR.InvalidOperation_CannotSetStreamSizeCannotWrite);
- ex.SetErrorCode(HResults.E_ILLEGAL_METHOD_CALL);
+ ex.SetErrorCode(__HResults.E_ILLEGAL_METHOD_CALL);
throw ex;
}
@@ -441,7 +441,7 @@ namespace System.IO
private static void ThrowCloningNotSupported(String methodName)
{
NotSupportedException nse = new NotSupportedException(SR.Format(SR.NotSupported_CloningNotSupported, methodName));
- nse.SetErrorCode(HResults.E_NOTIMPL);
+ nse.SetErrorCode(__HResults.E_NOTIMPL);
throw nse;
}
diff --git a/src/System.Runtime.WindowsRuntime/src/System/Runtime/InteropServices/HResults.cs b/src/System.Runtime.WindowsRuntime/src/System/Runtime/InteropServices/HResults.cs
index f1f0fce6fd..c131895da8 100644
--- a/src/System.Runtime.WindowsRuntime/src/System/Runtime/InteropServices/HResults.cs
+++ b/src/System.Runtime.WindowsRuntime/src/System/Runtime/InteropServices/HResults.cs
@@ -9,7 +9,7 @@ namespace System.Runtime.InteropServices
/// <summary>
/// HRESULT values used in this assembly.
/// </summary>
- internal static class HResults
+ internal static class __HResults
{
internal const Int32 S_OK = unchecked((Int32)0x00000000);
internal const Int32 E_BOUNDS = unchecked((Int32)0x8000000B);
diff --git a/src/System.Runtime.WindowsRuntime/src/System/Runtime/InteropServices/WindowsRuntime/MarshalingHelpers.cs b/src/System.Runtime.WindowsRuntime/src/System/Runtime/InteropServices/WindowsRuntime/MarshalingHelpers.cs
index 28af19341f..8fa8c7217a 100644
--- a/src/System.Runtime.WindowsRuntime/src/System/Runtime/InteropServices/WindowsRuntime/MarshalingHelpers.cs
+++ b/src/System.Runtime.WindowsRuntime/src/System/Runtime/InteropServices/WindowsRuntime/MarshalingHelpers.cs
@@ -182,7 +182,7 @@ namespace System.Runtime.InteropServices.WindowsRuntime
// void CollectionChanged.add(NotifyCollectionChangedEventHandler)
add
{
- INotifyCollectionChanged_WinRT _this = JitHelpers.UnsafeCast<INotifyCollectionChanged_WinRT>(this);
+ INotifyCollectionChanged_WinRT _this = Unsafe.As<INotifyCollectionChanged_WinRT>(this);
// call the WinRT eventing support in mscorlib to subscribe the event
Func<NotifyCollectionChangedEventHandler, EventRegistrationToken> addMethod =
@@ -196,7 +196,7 @@ namespace System.Runtime.InteropServices.WindowsRuntime
// void CollectionChanged.remove(NotifyCollectionChangedEventHandler)
remove
{
- INotifyCollectionChanged_WinRT _this = JitHelpers.UnsafeCast<INotifyCollectionChanged_WinRT>(this);
+ INotifyCollectionChanged_WinRT _this = Unsafe.As<INotifyCollectionChanged_WinRT>(this);
// call the WinRT eventing support in mscorlib to unsubscribe the event
Action<EventRegistrationToken> removeMethod =
@@ -226,7 +226,7 @@ namespace System.Runtime.InteropServices.WindowsRuntime
// EventRegistrationToken CollectionChanged.add(NotifyCollectionChangedEventHandler value)
internal EventRegistrationToken add_CollectionChanged(NotifyCollectionChangedEventHandler value)
{
- INotifyCollectionChanged _this = JitHelpers.UnsafeCast<INotifyCollectionChanged>(this);
+ INotifyCollectionChanged _this = Unsafe.As<INotifyCollectionChanged>(this);
EventRegistrationTokenTable<NotifyCollectionChangedEventHandler> table = s_weakTable.GetOrCreateValue(_this);
EventRegistrationToken token = table.AddEventHandler(value);
@@ -238,7 +238,7 @@ namespace System.Runtime.InteropServices.WindowsRuntime
// void CollectionChanged.remove(EventRegistrationToken token)
internal void remove_CollectionChanged(EventRegistrationToken token)
{
- INotifyCollectionChanged _this = JitHelpers.UnsafeCast<INotifyCollectionChanged>(this);
+ INotifyCollectionChanged _this = Unsafe.As<INotifyCollectionChanged>(this);
EventRegistrationTokenTable<NotifyCollectionChangedEventHandler> table = s_weakTable.GetOrCreateValue(_this);
NotifyCollectionChangedEventHandler handler = table.ExtractHandler(token);
@@ -264,7 +264,7 @@ namespace System.Runtime.InteropServices.WindowsRuntime
// void PropertyChanged.add(PropertyChangedEventHandler)
add
{
- INotifyPropertyChanged_WinRT _this = JitHelpers.UnsafeCast<INotifyPropertyChanged_WinRT>(this);
+ INotifyPropertyChanged_WinRT _this = Unsafe.As<INotifyPropertyChanged_WinRT>(this);
// call the WinRT eventing support in mscorlib to subscribe the event
Func<PropertyChangedEventHandler, EventRegistrationToken> addMethod =
@@ -278,7 +278,7 @@ namespace System.Runtime.InteropServices.WindowsRuntime
// void PropertyChanged.remove(PropertyChangedEventHandler)
remove
{
- INotifyPropertyChanged_WinRT _this = JitHelpers.UnsafeCast<INotifyPropertyChanged_WinRT>(this);
+ INotifyPropertyChanged_WinRT _this = Unsafe.As<INotifyPropertyChanged_WinRT>(this);
// call the WinRT eventing support in mscorlib to unsubscribe the event
Action<EventRegistrationToken> removeMethod =
@@ -308,7 +308,7 @@ namespace System.Runtime.InteropServices.WindowsRuntime
// EventRegistrationToken PropertyChanged.add(PropertyChangedEventHandler value)
internal EventRegistrationToken add_PropertyChanged(PropertyChangedEventHandler value)
{
- INotifyPropertyChanged _this = JitHelpers.UnsafeCast<INotifyPropertyChanged>(this);
+ INotifyPropertyChanged _this = Unsafe.As<INotifyPropertyChanged>(this);
EventRegistrationTokenTable<PropertyChangedEventHandler> table = s_weakTable.GetOrCreateValue(_this);
EventRegistrationToken token = table.AddEventHandler(value);
@@ -320,7 +320,7 @@ namespace System.Runtime.InteropServices.WindowsRuntime
// void PropertyChanged.remove(EventRegistrationToken token)
internal void remove_PropertyChanged(EventRegistrationToken token)
{
- INotifyPropertyChanged _this = JitHelpers.UnsafeCast<INotifyPropertyChanged>(this);
+ INotifyPropertyChanged _this = Unsafe.As<INotifyPropertyChanged>(this);
EventRegistrationTokenTable<PropertyChangedEventHandler> table = s_weakTable.GetOrCreateValue(_this);
PropertyChangedEventHandler handler = table.ExtractHandler(token);
@@ -350,7 +350,7 @@ namespace System.Runtime.InteropServices.WindowsRuntime
// void CanExecuteChanged.add(EventHandler)
add
{
- ICommand_WinRT _this = JitHelpers.UnsafeCast<ICommand_WinRT>(this);
+ ICommand_WinRT _this = Unsafe.As<ICommand_WinRT>(this);
// call the WinRT eventing support in mscorlib to subscribe the event
Func<EventHandler<object>, EventRegistrationToken> addMethod =
@@ -367,7 +367,7 @@ namespace System.Runtime.InteropServices.WindowsRuntime
// void CanExecuteChanged.remove(EventHandler)
remove
{
- ICommand_WinRT _this = JitHelpers.UnsafeCast<ICommand_WinRT>(this);
+ ICommand_WinRT _this = Unsafe.As<ICommand_WinRT>(this);
// call the WinRT eventing support in mscorlib to unsubscribe the event
Action<EventRegistrationToken> removeMethod =
@@ -384,13 +384,13 @@ namespace System.Runtime.InteropServices.WindowsRuntime
private bool CanExecute(object parameter)
{
- ICommand_WinRT _this = JitHelpers.UnsafeCast<ICommand_WinRT>(this);
+ ICommand_WinRT _this = Unsafe.As<ICommand_WinRT>(this);
return _this.CanExecute(parameter);
}
private void Execute(object parameter)
{
- ICommand_WinRT _this = JitHelpers.UnsafeCast<ICommand_WinRT>(this);
+ ICommand_WinRT _this = Unsafe.As<ICommand_WinRT>(this);
_this.Execute(parameter);
}
}
@@ -415,7 +415,7 @@ namespace System.Runtime.InteropServices.WindowsRuntime
// EventRegistrationToken PropertyChanged.add(EventHandler<object> value)
private EventRegistrationToken add_CanExecuteChanged(EventHandler<object> value)
{
- ICommand _this = JitHelpers.UnsafeCast<ICommand>(this);
+ ICommand _this = Unsafe.As<ICommand>(this);
EventRegistrationTokenTable<EventHandler> table = s_weakTable.GetOrCreateValue(_this);
EventHandler handler = ICommandAdapterHelpers.CreateWrapperHandler(value);
@@ -428,7 +428,7 @@ namespace System.Runtime.InteropServices.WindowsRuntime
// void PropertyChanged.remove(EventRegistrationToken token)
private void remove_CanExecuteChanged(EventRegistrationToken token)
{
- ICommand _this = JitHelpers.UnsafeCast<ICommand>(this);
+ ICommand _this = Unsafe.As<ICommand>(this);
EventRegistrationTokenTable<EventHandler> table = s_weakTable.GetOrCreateValue(_this);
EventHandler handler = table.ExtractHandler(token);
@@ -440,13 +440,13 @@ namespace System.Runtime.InteropServices.WindowsRuntime
private bool CanExecute(object parameter)
{
- ICommand _this = JitHelpers.UnsafeCast<ICommand>(this);
+ ICommand _this = Unsafe.As<ICommand>(this);
return _this.CanExecute(parameter);
}
private void Execute(object parameter)
{
- ICommand _this = JitHelpers.UnsafeCast<ICommand>(this);
+ ICommand _this = Unsafe.As<ICommand>(this);
_this.Execute(parameter);
}
}
diff --git a/src/System.Runtime.WindowsRuntime/src/System/Runtime/InteropServices/WindowsRuntime/WindowsRuntimeBuffer.cs b/src/System.Runtime.WindowsRuntime/src/System/Runtime/InteropServices/WindowsRuntime/WindowsRuntimeBuffer.cs
index 0c01d7ebd8..070b2b6adf 100644
--- a/src/System.Runtime.WindowsRuntime/src/System/Runtime/InteropServices/WindowsRuntime/WindowsRuntimeBuffer.cs
+++ b/src/System.Runtime.WindowsRuntime/src/System/Runtime/InteropServices/WindowsRuntime/WindowsRuntimeBuffer.cs
@@ -89,7 +89,7 @@ namespace System.Runtime.InteropServices.WindowsRuntime
Int32 hr = Interop.mincore.RoGetBufferMarshaler(out proxy);
t_winRtMarshalProxy = proxy;
- if (hr != HResults.S_OK)
+ if (hr != __HResults.S_OK)
{
Exception ex = new Exception(String.Format("{0} ({1}!RoGetBufferMarshaler)", SR.WinRtCOM_Error, WinTypesDLL));
ex.SetErrorCode(hr);
@@ -242,7 +242,7 @@ namespace System.Runtime.InteropServices.WindowsRuntime
if (value > ((IBuffer)this).Capacity)
{
ArgumentOutOfRangeException ex = new ArgumentOutOfRangeException(nameof(value), SR.Argument_BufferLengthExceedsCapacity);
- ex.SetErrorCode(HResults.E_BOUNDS);
+ ex.SetErrorCode(__HResults.E_BOUNDS);
throw ex;
}
diff --git a/src/System.Runtime.WindowsRuntime/src/System/Runtime/InteropServices/WindowsRuntime/WindowsRuntimeBufferExtensions.cs b/src/System.Runtime.WindowsRuntime/src/System/Runtime/InteropServices/WindowsRuntime/WindowsRuntimeBufferExtensions.cs
index 5c858cd5b9..5f588d11d7 100644
--- a/src/System.Runtime.WindowsRuntime/src/System/Runtime/InteropServices/WindowsRuntime/WindowsRuntimeBufferExtensions.cs
+++ b/src/System.Runtime.WindowsRuntime/src/System/Runtime/InteropServices/WindowsRuntime/WindowsRuntimeBufferExtensions.cs
@@ -12,7 +12,7 @@ using Windows.Storage.Streams;
namespace System.Runtime.InteropServices.WindowsRuntime
{
/// <summary>
- /// Contains a extension methods that expose operations on WinRT <code>Windows.Foundation.IBuffer</code>.
+ /// Contains extension methods that expose operations on WinRT <code>Windows.Foundation.IBuffer</code>.
/// </summary>
public static class WindowsRuntimeBufferExtensions
{
diff --git a/src/System.Runtime.WindowsRuntime/src/System/Threading/Tasks/TaskToAsyncInfoAdapter.cs b/src/System.Runtime.WindowsRuntime/src/System/Threading/Tasks/TaskToAsyncInfoAdapter.cs
index 2483156cb7..9b9c8880b8 100644
--- a/src/System.Runtime.WindowsRuntime/src/System/Threading/Tasks/TaskToAsyncInfoAdapter.cs
+++ b/src/System.Runtime.WindowsRuntime/src/System/Threading/Tasks/TaskToAsyncInfoAdapter.cs
@@ -77,7 +77,7 @@ namespace System.Threading.Tasks
InvalidOperationException ex = (cause == null)
? new InvalidOperationException(SR.InvalidOperation_CannotGetResultsFromIncompleteOperation)
: new InvalidOperationException(SR.InvalidOperation_CannotGetResultsFromIncompleteOperation, cause);
- ex.SetErrorCode(HResults.E_ILLEGAL_METHOD_CALL);
+ ex.SetErrorCode(__HResults.E_ILLEGAL_METHOD_CALL);
return ex;
}
@@ -397,7 +397,7 @@ namespace System.Threading.Tasks
return;
ObjectDisposedException ex = new ObjectDisposedException(SR.ObjectDisposed_AsyncInfoIsClosed);
- ex.SetErrorCode(HResults.E_ILLEGAL_METHOD_CALL);
+ ex.SetErrorCode(__HResults.E_ILLEGAL_METHOD_CALL);
throw ex;
}
@@ -857,7 +857,7 @@ namespace System.Threading.Tasks
if (handlerBefore != null)
{
InvalidOperationException ex = new InvalidOperationException(SR.InvalidOperation_CannotSetCompletionHanlderMoreThanOnce);
- ex.SetErrorCode(HResults.E_ILLEGAL_DELEGATE_ASSIGNMENT);
+ ex.SetErrorCode(__HResults.E_ILLEGAL_DELEGATE_ASSIGNMENT);
throw ex;
}
@@ -940,7 +940,7 @@ namespace System.Threading.Tasks
if (0 != (_state & STATEMASK_SELECT_ANY_ASYNC_STATE))
{
InvalidOperationException ex = new InvalidOperationException(SR.InvalidOperation_IllegalStateChange);
- ex.SetErrorCode(HResults.E_ILLEGAL_STATE_CHANGE);
+ ex.SetErrorCode(__HResults.E_ILLEGAL_STATE_CHANGE);
throw ex;
}
}
@@ -981,7 +981,7 @@ namespace System.Threading.Tasks
if (aggregateException == null)
{
error = new Exception(SR.WinRtCOM_Error);
- error.SetErrorCode(HResults.E_FAIL);
+ error.SetErrorCode(__HResults.E_FAIL);
}
else
{
diff --git a/src/System.Runtime.WindowsRuntime/tests/System/IO/AsWinRTStreamTests.cs b/src/System.Runtime.WindowsRuntime/tests/System/IO/AsWinRTStreamTests.cs
index 582f1348ca..7b6ad375b6 100644
--- a/src/System.Runtime.WindowsRuntime/tests/System/IO/AsWinRTStreamTests.cs
+++ b/src/System.Runtime.WindowsRuntime/tests/System/IO/AsWinRTStreamTests.cs
@@ -188,7 +188,7 @@ namespace System.IO
// asyncReadOp.Id in a progress callback must match the ID of the asyncReadOp to which the callback was assigned
Assert.Equal(readOpId, asyncReadOp.Id);
- // asyncReadOp.Status must be 'Started' for a asyncReadOp in progress
+ // asyncReadOp.Status must be 'Started' for an asyncReadOp in progress
Assert.Equal(AsyncStatus.Started, asyncReadOp.Status);
// bytesCompleted must be in range [0, maxBytesToRead] asyncReadOp in progress
@@ -322,7 +322,7 @@ namespace System.IO
// asyncWriteOp.Id in a progress callback must match the ID of the asyncWriteOp to which the callback was assigned
Assert.Equal(writeOpId, asyncWriteOp.Id);
- // asyncWriteOp.Status must be 'Started' for a asyncWriteOp in progress
+ // asyncWriteOp.Status must be 'Started' for an asyncWriteOp in progress
Assert.Equal(AsyncStatus.Started, asyncWriteOp.Status);
// bytesCompleted must be in range [0, maxBytesToWrite] asyncWriteOp in progress
diff --git a/src/System.Runtime/ref/System.Runtime.cs b/src/System.Runtime/ref/System.Runtime.cs
index e53bd03ba2..a8cf195db6 100644
--- a/src/System.Runtime/ref/System.Runtime.cs
+++ b/src/System.Runtime/ref/System.Runtime.cs
@@ -1298,6 +1298,7 @@ namespace System
{
public static readonly System.Guid Empty;
public Guid(byte[] b) { throw null; }
+ public Guid(ReadOnlySpan<byte> b) { throw null; }
public Guid(int a, short b, short c, byte d, byte e, byte f, byte g, byte h, byte i, byte j, byte k) { throw null; }
public Guid(int a, short b, short c, byte[] d) { throw null; }
public Guid(string g) { throw null; }
@@ -1312,13 +1313,19 @@ namespace System
public static bool operator ==(System.Guid a, System.Guid b) { throw null; }
public static bool operator !=(System.Guid a, System.Guid b) { throw null; }
public static System.Guid Parse(string input) { throw null; }
+ public static System.Guid Parse(System.ReadOnlySpan<char> input) { throw null; }
public static System.Guid ParseExact(string input, string format) { throw null; }
+ public static System.Guid ParseExact(System.ReadOnlySpan<char> input, string format) { throw null; }
public byte[] ToByteArray() { throw null; }
+ public bool TryWriteBytes(Span<byte> destination) { throw null; }
public override string ToString() { throw null; }
public string ToString(string format) { throw null; }
public string ToString(string format, System.IFormatProvider provider) { throw null; }
+ public bool TryFormat(Span<char> destination, out int charsWritten, string format) { throw null; }
public static bool TryParse(string input, out System.Guid result) { throw null; }
+ public static bool TryParse(System.ReadOnlySpan<char> input, out System.Guid result) { throw null; }
public static bool TryParseExact(string input, string format, out System.Guid result) { throw null; }
+ public static bool TryParseExact(System.ReadOnlySpan<char> input, string format, out System.Guid result) { throw null; }
}
public partial interface IAsyncResult
{
@@ -1630,6 +1637,29 @@ namespace System
public MemberAccessException(string message, System.Exception inner) { }
protected MemberAccessException(System.Runtime.Serialization.SerializationInfo info, System.Runtime.Serialization.StreamingContext context) : base(info, context) { }
}
+ public readonly struct Memory<T>
+ {
+ public static Memory<T> Empty { get { throw null; } }
+ public Memory(T[] array) { throw null;}
+ public Memory(T[] array, int start, int length) { throw null;}
+ internal Memory(Buffers.OwnedMemory<T> owner, int index, int length) { throw null;}
+ public bool IsEmpty { get { throw null; } }
+ public int Length { get { throw null; } }
+ [System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Never)]
+ public override bool Equals(object obj) { throw null; }
+ public bool Equals(Memory<T> other) { throw null; }
+ [System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Never)]
+ public override int GetHashCode() { throw null; }
+ public static implicit operator Memory<T>(T[] array) { throw null; }
+ public static implicit operator Memory<T>(ArraySegment<T> arraySegment) { throw null; }
+ public static implicit operator ReadOnlyMemory<T>(Memory<T> memory) { throw null; }
+ public Memory<T> Slice(int start) { throw null; }
+ public Memory<T> Slice(int start, int length) { throw null; }
+ public Span<T> Span { get { throw null; } }
+ public unsafe Buffers.MemoryHandle Retain(bool pin = false) { throw null; }
+ public T[] ToArray() { throw null; }
+ public bool TryGetArray(out ArraySegment<T> arraySegment) { throw null; }
+ }
public partial class MethodAccessException : System.MemberAccessException
{
public MethodAccessException() { }
@@ -1831,8 +1861,31 @@ namespace System
public RankException(string message, System.Exception innerException) { }
protected RankException(System.Runtime.Serialization.SerializationInfo info, System.Runtime.Serialization.StreamingContext context) : base(info, context) { }
}
+ public readonly struct ReadOnlyMemory<T>
+ {
+ public static ReadOnlyMemory<T> Empty { get { throw null; } }
+ public ReadOnlyMemory(T[] array) { throw null;}
+ public ReadOnlyMemory(T[] array, int start, int length) { throw null;}
+ internal ReadOnlyMemory(Buffers.OwnedMemory<T> owner, int index, int length) { throw null;}
+ public bool IsEmpty { get { throw null; } }
+ public int Length { get { throw null; } }
+ [System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Never)]
+ public override bool Equals(object obj) { throw null; }
+ public bool Equals(ReadOnlyMemory<T> other) { throw null; }
+ [System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Never)]
+ public override int GetHashCode() { throw null; }
+ public static implicit operator ReadOnlyMemory<T>(T[] array) { throw null; }
+ public static implicit operator ReadOnlyMemory<T>(ArraySegment<T> arraySegment) { throw null; }
+ public ReadOnlyMemory<T> Slice(int start) { throw null; }
+ public ReadOnlyMemory<T> Slice(int start, int length) { throw null; }
+ public ReadOnlySpan<T> Span { get { throw null; } }
+ public unsafe Buffers.MemoryHandle Retain(bool pin = false) { throw null; }
+ public T[] ToArray() { throw null; }
+ [System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Never)]
+ public bool DangerousTryGetArray(out ArraySegment<T> arraySegment) { throw null; }
+ }
[System.Runtime.InteropServices.StructLayoutAttribute(System.Runtime.InteropServices.LayoutKind.Sequential)]
- public partial struct ReadOnlySpan<T>
+ public readonly ref struct ReadOnlySpan<T>
{
public static ReadOnlySpan<T> Empty { get { throw null; } }
public ReadOnlySpan(T[] array) { throw null; }
@@ -1843,7 +1896,9 @@ namespace System
public T this[int index] { get { throw null; } }
public int Length { get { throw null; } }
public void CopyTo(Span<T> destination) { }
+ [System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Never)]
public static ReadOnlySpan<T> DangerousCreate(object obj, ref T objectData, int length) { throw null; }
+ [System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Never)]
public ref T DangerousGetPinnableReference() { throw null; }
#pragma warning disable 0809
[System.ObsoleteAttribute("Equals() on ReadOnlySpan will always throw an exception. Use == instead.")]
@@ -2017,7 +2072,7 @@ namespace System
public static bool TryParse(ReadOnlySpan<char> s, out float result, System.Globalization.NumberStyles style = System.Globalization.NumberStyles.Integer, System.IFormatProvider provider = null) { throw null; }
}
[System.Runtime.InteropServices.StructLayoutAttribute(System.Runtime.InteropServices.LayoutKind.Sequential)]
- public partial struct Span<T>
+ public readonly ref struct Span<T>
{
public static Span<T> Empty { get { throw null; } }
public Span(T[] array) { throw null; }
@@ -2030,7 +2085,9 @@ namespace System
public void Clear() { }
public void Fill(T value) { }
public void CopyTo(Span<T> destination) { }
+ [System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Never)]
public static Span<T> DangerousCreate(object obj, ref T objectData, int length) { throw null; }
+ [System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Never)]
public ref T DangerousGetPinnableReference() { throw null; }
#pragma warning disable 0809
[System.ObsoleteAttribute("Equals() on Span will always throw an exception. Use == instead.")]
@@ -2106,6 +2163,7 @@ namespace System
public bool Contains(string value, StringComparison comparisonType) { throw null; }
public static System.String Copy(System.String str) { throw null; }
public void CopyTo(int sourceIndex, char[] destination, int destinationIndex, int count) { }
+ public static string Create<TState>(int length, TState state, System.Buffers.SpanAction<char, TState> action) { throw null; }
public bool EndsWith(char value) { throw null; }
public bool EndsWith(string value) { throw null; }
public bool EndsWith(System.String value, bool ignoreCase, System.Globalization.CultureInfo culture) { throw null; }
@@ -2323,20 +2381,27 @@ namespace System
public static System.TimeSpan operator +(System.TimeSpan t) { throw null; }
public static System.TimeSpan Parse(string s) { throw null; }
public static System.TimeSpan Parse(string input, System.IFormatProvider formatProvider) { throw null; }
+ public static System.TimeSpan Parse(System.ReadOnlySpan<char> input, System.IFormatProvider formatProvider = null) { throw null; }
public static System.TimeSpan ParseExact(string input, string format, System.IFormatProvider formatProvider) { throw null; }
public static System.TimeSpan ParseExact(string input, string format, System.IFormatProvider formatProvider, System.Globalization.TimeSpanStyles styles) { throw null; }
+ public static System.TimeSpan ParseExact(ReadOnlySpan<char> input, string format, System.IFormatProvider formatProvider, System.Globalization.TimeSpanStyles styles = System.Globalization.TimeSpanStyles.None) { throw null; }
public static System.TimeSpan ParseExact(string input, string[] formats, System.IFormatProvider formatProvider) { throw null; }
public static System.TimeSpan ParseExact(string input, string[] formats, System.IFormatProvider formatProvider, System.Globalization.TimeSpanStyles styles) { throw null; }
+ public static System.TimeSpan ParseExact(System.ReadOnlySpan<char> input, string[] formats, System.IFormatProvider formatProvider, System.Globalization.TimeSpanStyles styles = System.Globalization.TimeSpanStyles.None) { throw null; }
public System.TimeSpan Subtract(System.TimeSpan ts) { throw null; }
public override string ToString() { throw null; }
public string ToString(string format) { throw null; }
public string ToString(string format, System.IFormatProvider formatProvider) { throw null; }
+ public bool TryFormat(System.Span<char> destination, out int charsWritten, string format = null, System.IFormatProvider provider = null) { throw null; }
public static bool TryParse(string input, System.IFormatProvider formatProvider, out System.TimeSpan result) { throw null; }
+ public static bool TryParse(System.ReadOnlySpan<char> input, out System.TimeSpan result, System.IFormatProvider formatProvider = null) { throw null; }
public static bool TryParse(string s, out System.TimeSpan result) { throw null; }
public static bool TryParseExact(string input, string format, System.IFormatProvider formatProvider, System.Globalization.TimeSpanStyles styles, out System.TimeSpan result) { throw null; }
public static bool TryParseExact(string input, string format, System.IFormatProvider formatProvider, out System.TimeSpan result) { throw null; }
+ public static bool TryParseExact(System.ReadOnlySpan<char> input, string format, System.IFormatProvider formatProvider, out System.TimeSpan result, System.Globalization.TimeSpanStyles styles = System.Globalization.TimeSpanStyles.None) { throw null; }
public static bool TryParseExact(string input, string[] formats, System.IFormatProvider formatProvider, System.Globalization.TimeSpanStyles styles, out System.TimeSpan result) { throw null; }
public static bool TryParseExact(string input, string[] formats, System.IFormatProvider formatProvider, out System.TimeSpan result) { throw null; }
+ public static bool TryParseExact(System.ReadOnlySpan<char> input, string[] formats, System.IFormatProvider formatProvider, out System.TimeSpan result, System.Globalization.TimeSpanStyles styles = System.Globalization.TimeSpanStyles.None) { throw null; }
}
[ObsoleteAttribute("System.TimeZone has been deprecated. Please investigate the use of System.TimeZoneInfo instead.")]
public abstract partial class TimeZone
@@ -2729,6 +2794,7 @@ namespace System
public virtual bool IsSecuritySafeCritical { get { throw null; } }
public virtual bool IsSecurityTransparent { get { throw null; } }
public virtual bool IsSerializable { get { throw null; } }
+ public virtual bool IsSignatureType { get { throw null; } }
public bool IsSpecialName { get { throw null; } }
public virtual bool IsTypeDefinition { get { throw null; } }
public virtual bool IsSZArray { get { throw null; } }
@@ -2790,6 +2856,11 @@ namespace System
public System.Reflection.MethodInfo GetMethod(string name, System.Type[] types) { throw null; }
public System.Reflection.MethodInfo GetMethod(string name, System.Type[] types, System.Reflection.ParameterModifier[] modifiers) { throw null; }
protected abstract System.Reflection.MethodInfo GetMethodImpl(string name, System.Reflection.BindingFlags bindingAttr, System.Reflection.Binder binder, System.Reflection.CallingConventions callConvention, System.Type[] types, System.Reflection.ParameterModifier[] modifiers);
+ public System.Reflection.MethodInfo GetMethod(string name, int genericParameterCount, System.Reflection.BindingFlags bindingAttr, System.Reflection.Binder binder, System.Reflection.CallingConventions callConvention, System.Type[] types, System.Reflection.ParameterModifier[] modifiers) { throw null; }
+ public System.Reflection.MethodInfo GetMethod(string name, int genericParameterCount, System.Reflection.BindingFlags bindingAttr, System.Reflection.Binder binder, System.Type[] types, System.Reflection.ParameterModifier[] modifiers) { throw null; }
+ public System.Reflection.MethodInfo GetMethod(string name, int genericParameterCount, System.Type[] types) { throw null; }
+ public System.Reflection.MethodInfo GetMethod(string name, int genericParameterCount, System.Type[] types, System.Reflection.ParameterModifier[] modifiers) { throw null; }
+ protected virtual System.Reflection.MethodInfo GetMethodImpl(string name, int genericParameterCount, System.Reflection.BindingFlags bindingAttr, System.Reflection.Binder binder, System.Reflection.CallingConventions callConvention, System.Type[] types, System.Reflection.ParameterModifier[] modifiers) { throw null; }
public System.Reflection.MethodInfo[] GetMethods() { throw null; }
public abstract System.Reflection.MethodInfo[] GetMethods(System.Reflection.BindingFlags bindingAttr);
public System.Type GetNestedType(string name) { throw null; }
@@ -2848,6 +2919,7 @@ namespace System
public virtual System.Type MakeByRefType() { throw null; }
public virtual System.Type MakeGenericType(params System.Type[] typeArguments) { throw null; }
public virtual System.Type MakePointerType() { throw null; }
+ public static Type MakeGenericMethodParameter(int position) { throw null; }
public static System.Type ReflectionOnlyGetType(System.String typeName, bool throwIfNotFound, bool ignoreCase) { throw null; }
public override string ToString() { throw null; }
}
@@ -3555,9 +3627,13 @@ namespace System
public static bool operator <(System.Version v1, System.Version v2) { throw null; }
public static bool operator <=(System.Version v1, System.Version v2) { throw null; }
public static System.Version Parse(string input) { throw null; }
+ public static System.Version Parse(ReadOnlySpan<char> input) { throw null; }
public override string ToString() { throw null; }
public string ToString(int fieldCount) { throw null; }
+ public bool TryFormat(System.Span<char> destination, out int charsWritten) { throw null; }
+ public bool TryFormat(System.Span<char> destination, int fieldCount, out int charsWritten) { throw null; }
public static bool TryParse(string input, out System.Version result) { throw null; }
+ public static bool TryParse(System.ReadOnlySpan<char> input, out System.Version result) { throw null; }
}
[System.Runtime.InteropServices.StructLayoutAttribute(System.Runtime.InteropServices.LayoutKind.Sequential, Size = 1)]
public partial struct Void
@@ -3757,6 +3833,43 @@ namespace System.Runtime.CompilerServices
}
}
}
+namespace System.Buffers
+{
+ public unsafe struct MemoryHandle : IDisposable
+ {
+ [System.CLSCompliantAttribute(false)]
+ public MemoryHandle(IRetainable owner, void* pinnedPointer = null, System.Runtime.InteropServices.GCHandle handle = default(System.Runtime.InteropServices.GCHandle)) { throw null; }
+ [System.CLSCompliantAttribute(false)]
+ public void* PinnedPointer { get { throw null; } }
+ public void Dispose() { throw null; }
+ }
+
+ public interface IRetainable
+ {
+ bool Release();
+ void Retain();
+ }
+
+ public abstract class OwnedMemory<T> : IDisposable, IRetainable
+ {
+ public Memory<T> Memory { get { throw null; } }
+ public abstract bool IsDisposed { get; }
+ protected abstract bool IsRetained { get; }
+ public abstract int Length { get; }
+ public abstract Span<T> Span { get; }
+ public void Dispose() { throw null; }
+ protected abstract void Dispose(bool disposing);
+ public abstract MemoryHandle Pin();
+ public abstract bool Release();
+ public abstract void Retain();
+ protected internal abstract bool TryGetArray(out ArraySegment<T> arraySegment);
+ }
+}
+namespace System.Buffers
+{
+ public delegate void SpanAction<T, in TArg>(Span<T> span, TArg arg);
+ public delegate void ReadOnlySpanAction<T, in TArg>(ReadOnlySpan<T> span, TArg arg);
+}
namespace System.Collections
{
[System.Runtime.InteropServices.StructLayoutAttribute(System.Runtime.InteropServices.LayoutKind.Sequential)]
@@ -5087,6 +5200,7 @@ namespace System.IO
public virtual int Read(System.Span<byte> destination) { throw null; }
public System.Threading.Tasks.Task<int> ReadAsync(byte[] buffer, int offset, int count) { throw null; }
public virtual System.Threading.Tasks.Task<int> ReadAsync(byte[] buffer, int offset, int count, System.Threading.CancellationToken cancellationToken) { throw null; }
+ public virtual System.Threading.Tasks.ValueTask<int> ReadAsync(Memory<byte> destination, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) { throw null; }
public virtual int ReadByte() { throw null; }
public abstract long Seek(long offset, System.IO.SeekOrigin origin);
public abstract void SetLength(long value);
@@ -5095,6 +5209,7 @@ namespace System.IO
public virtual void Write(System.ReadOnlySpan<byte> source) { }
public System.Threading.Tasks.Task WriteAsync(byte[] buffer, int offset, int count) { throw null; }
public virtual System.Threading.Tasks.Task WriteAsync(byte[] buffer, int offset, int count, System.Threading.CancellationToken cancellationToken) { throw null; }
+ public virtual System.Threading.Tasks.Task WriteAsync(ReadOnlyMemory<byte> source, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) { throw null; }
public virtual void WriteByte(byte value) { }
}
public partial class FileStream : System.IO.Stream
@@ -5430,6 +5545,7 @@ namespace System.Reflection
CreateInstance = 512,
DeclaredOnly = 2,
Default = 0,
+ DoNotWrapExceptions = 33554432,
ExactBinding = 65536,
FlattenHierarchy = 64,
GetField = 1024,
@@ -6727,6 +6843,31 @@ namespace System.Runtime.InteropServices
public FieldOffsetAttribute(int offset) { }
public int Value { get { throw null; } }
}
+ [System.Runtime.InteropServices.StructLayoutAttribute(System.Runtime.InteropServices.LayoutKind.Sequential)]
+ public partial struct GCHandle
+ {
+ public bool IsAllocated { get { throw null; } }
+ public object Target {get { throw null; } set { } }
+ public System.IntPtr AddrOfPinnedObject() { throw null; }
+ public static System.Runtime.InteropServices.GCHandle Alloc(object value) { throw null; }
+ public static System.Runtime.InteropServices.GCHandle Alloc(object value, System.Runtime.InteropServices.GCHandleType type) { throw null; }
+ public override bool Equals(object o) { throw null; }
+ public void Free() { }
+ public static System.Runtime.InteropServices.GCHandle FromIntPtr(System.IntPtr value) { throw null; }
+ public override int GetHashCode() { throw null; }
+ public static bool operator ==(System.Runtime.InteropServices.GCHandle a, System.Runtime.InteropServices.GCHandle b) { throw null; }
+ public static explicit operator System.Runtime.InteropServices.GCHandle(System.IntPtr value) { throw null; }
+ public static explicit operator System.IntPtr(System.Runtime.InteropServices.GCHandle value) { throw null; }
+ public static bool operator !=(System.Runtime.InteropServices.GCHandle a, System.Runtime.InteropServices.GCHandle b) { throw null; }
+ public static System.IntPtr ToIntPtr(System.Runtime.InteropServices.GCHandle value) { throw null; }
+ }
+ public enum GCHandleType
+ {
+ Normal = 2,
+ Pinned = 3,
+ Weak = 0,
+ WeakTrackResurrection = 1,
+ }
public enum LayoutKind
{
Auto = 3,
diff --git a/src/System.Runtime/ref/System.Runtime.csproj b/src/System.Runtime/ref/System.Runtime.csproj
index 349f7efa20..2947fad3fe 100644
--- a/src/System.Runtime/ref/System.Runtime.csproj
+++ b/src/System.Runtime/ref/System.Runtime.csproj
@@ -15,4 +15,4 @@
<Compile Include="System.Runtime.Manual.cs" />
</ItemGroup>
<Import Project="$([MSBuild]::GetDirectoryNameOfFileAbove($(MSBuildThisFileDirectory), dir.targets))\dir.targets" />
-</Project> \ No newline at end of file
+</Project>
diff --git a/src/System.Runtime/src/System.Runtime.Forwards.cs b/src/System.Runtime/src/System.Runtime.Forwards.cs
deleted file mode 100644
index 8b18d3c491..0000000000
--- a/src/System.Runtime/src/System.Runtime.Forwards.cs
+++ /dev/null
@@ -1,6 +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.
-
-[assembly: System.Runtime.CompilerServices.TypeForwardedTo(typeof(System.Runtime.InteropServices.GCHandle))]
-[assembly: System.Runtime.CompilerServices.TypeForwardedTo(typeof(System.Runtime.InteropServices.GCHandleType))]
diff --git a/src/System.Runtime/src/System.Runtime.csproj b/src/System.Runtime/src/System.Runtime.csproj
index 2b8f6a551a..9d633654fc 100644
--- a/src/System.Runtime/src/System.Runtime.csproj
+++ b/src/System.Runtime/src/System.Runtime.csproj
@@ -16,7 +16,6 @@
<PropertyGroup Condition="'$(Configuration)|$(Platform)' == 'uapaot-Windows_NT-Debug|AnyCPU'" />
<PropertyGroup Condition="'$(Configuration)|$(Platform)' == 'uapaot-Windows_NT-Release|AnyCPU'" />
<ItemGroup>
- <Compile Include="System.Runtime.Forwards.cs" />
<Compile Include="System\Action.cs" />
<Compile Include="System\Collections\Generic\ISet.cs" />
<Compile Include="System\Function.cs" />
diff --git a/src/System.Runtime/tests/System.Runtime.Tests.csproj b/src/System.Runtime/tests/System.Runtime.Tests.csproj
index c0223eff79..3e24ee11aa 100644
--- a/src/System.Runtime/tests/System.Runtime.Tests.csproj
+++ b/src/System.Runtime/tests/System.Runtime.Tests.csproj
@@ -112,6 +112,7 @@
<Compile Include="System\UInt32Tests.cs" />
<Compile Include="System\UInt64Tests.cs" />
<Compile Include="System\UIntPtrTests.cs" />
+ <Compile Include="System\UnitySerializationHolderTests.cs" />
<Compile Include="System\Uri.CreateStringTests.cs" />
<Compile Include="System\Uri.CreateUriTests.cs" />
<Compile Include="System\Uri.MethodsTests.cs" />
@@ -183,6 +184,7 @@
<Compile Include="System\DecimalTests.netcoreapp.cs" />
<Compile Include="System\EnumTests.netcoreapp.cs" />
<Compile Include="System\GCTests.netcoreapp.cs" />
+ <Compile Include="System\GuidTests.netcoreapp.cs" />
<Compile Include="System\Int16Tests.netcoreapp.cs" />
<Compile Include="System\Int32Tests.netcoreapp.cs" />
<Compile Include="System\Int64Tests.netcoreapp.cs" />
@@ -198,10 +200,13 @@
<Compile Include="System\UInt16Tests.netcoreapp.cs" />
<Compile Include="System\UInt32Tests.netcoreapp.cs" />
<Compile Include="System\UInt64Tests.netcoreapp.cs" />
+ <Compile Include="System\VersionTests.netcoreapp.cs" />
<Compile Include="System\ComponentModel\DefaultValueAttributeTests.netcoreapp.cs" />
<Compile Include="System\Reflection\AssemblyTests.netcoreapp.cs" />
+ <Compile Include="System\Reflection\BindingFlagsDoNotWrap.netcoreapp.cs" />
<Compile Include="System\Reflection\MethodBaseTests.netcoreapp.cs" />
<Compile Include="System\Reflection\MemberInfoTests.netcoreapp.cs" />
+ <Compile Include="System\Reflection\SignatureTypes.netcoreapp.cs" />
<Compile Include="System\Reflection\TypeDelegatorTests.netcoreapp.cs" />
<Compile Include="System\Reflection\TypeInfoTests.netcoreapp.cs" />
<Compile Include="System\Runtime\CompilerServices\ConditionalWeakTableTests.netcoreapp.cs" />
diff --git a/src/System.Runtime/tests/System/DateTimeTests.cs b/src/System.Runtime/tests/System/DateTimeTests.cs
index f33b1f8ac5..f6d97d3b32 100644
--- a/src/System.Runtime/tests/System/DateTimeTests.cs
+++ b/src/System.Runtime/tests/System/DateTimeTests.cs
@@ -551,9 +551,65 @@ namespace System.Tests
}
[Fact]
- public static void Parse_NullString_ThrowsArgumentNullException()
+ public static void Parse_InvalidArguments_Throws()
{
+ AssertExtensions.Throws<ArgumentNullException>("s", () => DateTime.Parse(null));
+ AssertExtensions.Throws<ArgumentNullException>("s", () => DateTime.Parse(null, new MyFormatter()));
AssertExtensions.Throws<ArgumentNullException>("s", () => DateTime.Parse(null, new MyFormatter(), DateTimeStyles.NoCurrentDateDefault));
+
+ Assert.Throws<FormatException>(() => DateTime.Parse(""));
+ Assert.Throws<FormatException>(() => DateTime.Parse("", new MyFormatter()));
+ Assert.Throws<FormatException>(() => DateTime.Parse("", new MyFormatter(), DateTimeStyles.NoCurrentDateDefault));
+ }
+
+ [Theory]
+ [InlineData(null)]
+ [InlineData("")]
+ public static void TryParse_NullOrEmptyString_ReturnsFalse(string input)
+ {
+ Assert.False(DateTime.TryParse(input, out DateTime result));
+ Assert.False(DateTime.TryParse(input, new MyFormatter(), DateTimeStyles.None, out result));
+ }
+
+ [Fact]
+ public static void ParseExact_InvalidArguments_Throws()
+ {
+ AssertExtensions.Throws<ArgumentNullException>("s", () => DateTime.ParseExact(null, "d", new MyFormatter()));
+ AssertExtensions.Throws<ArgumentNullException>("s", () => DateTime.ParseExact(null, "d", new MyFormatter(), DateTimeStyles.None));
+ AssertExtensions.Throws<ArgumentNullException>("s", () => DateTime.ParseExact(null, new[] { "d" }, new MyFormatter(), DateTimeStyles.NoCurrentDateDefault));
+
+ Assert.Throws<FormatException>(() => DateTime.ParseExact("", "d", new MyFormatter()));
+ Assert.Throws<FormatException>(() => DateTime.ParseExact("", "d", new MyFormatter(), DateTimeStyles.None));
+ Assert.Throws<FormatException>(() => DateTime.ParseExact("", new[] { "d" }, new MyFormatter(), DateTimeStyles.NoCurrentDateDefault));
+
+ AssertExtensions.Throws<ArgumentNullException>("format", () => DateTime.ParseExact("123", null, new MyFormatter()));
+ AssertExtensions.Throws<ArgumentNullException>("format", () => DateTime.ParseExact("123", (string)null, new MyFormatter(), DateTimeStyles.None));
+ AssertExtensions.Throws<ArgumentNullException>("formats", () => DateTime.ParseExact("123", (string[])null, new MyFormatter(), DateTimeStyles.NoCurrentDateDefault));
+
+ Assert.Throws<FormatException>(() => DateTime.ParseExact("123", "", new MyFormatter()));
+ Assert.Throws<FormatException>(() => DateTime.ParseExact("123", "", new MyFormatter(), DateTimeStyles.None));
+ Assert.Throws<FormatException>(() => DateTime.ParseExact("123", new string[0], new MyFormatter(), DateTimeStyles.NoCurrentDateDefault));
+ Assert.Throws<FormatException>(() => DateTime.ParseExact("123", new string[] { null }, new MyFormatter(), DateTimeStyles.NoCurrentDateDefault));
+ Assert.Throws<FormatException>(() => DateTime.ParseExact("123", new[] { "" }, new MyFormatter(), DateTimeStyles.NoCurrentDateDefault));
+ }
+
+ [Fact]
+ public static void TryParseExact_InvalidArguments_ReturnsFalse()
+ {
+ Assert.False(DateTime.TryParseExact(null, "d", new MyFormatter(), DateTimeStyles.None, out DateTime result));
+ Assert.False(DateTime.TryParseExact(null, new[] { "d" }, new MyFormatter(), DateTimeStyles.None, out result));
+
+ Assert.False(DateTime.TryParseExact("", "d", new MyFormatter(), DateTimeStyles.None, out result));
+ Assert.False(DateTime.TryParseExact("", new[] { "d" }, new MyFormatter(), DateTimeStyles.None, out result));
+
+ Assert.False(DateTime.TryParseExact("abc", (string)null, new MyFormatter(), DateTimeStyles.None, out result));
+ Assert.False(DateTime.TryParseExact("abc", (string[])null, new MyFormatter(), DateTimeStyles.None, out result));
+
+ Assert.False(DateTime.TryParseExact("abc", "", new MyFormatter(), DateTimeStyles.None, out result));
+ Assert.False(DateTime.TryParseExact("abc", new string[0], new MyFormatter(), DateTimeStyles.None, out result));
+ Assert.False(DateTime.TryParseExact("abc", new string[] { null }, new MyFormatter(), DateTimeStyles.None, out result));
+ Assert.False(DateTime.TryParseExact("abc", new[] { "" }, new MyFormatter(), DateTimeStyles.None, out result));
+ Assert.False(DateTime.TryParseExact("abc", new[] { "" }, new MyFormatter(), DateTimeStyles.None, out result));
}
[Fact]
@@ -625,45 +681,69 @@ namespace System.Tests
Assert.Equal(0, result.Second);
}
- [Fact]
- public static void ParseExact_String_String_FormatProvider()
- {
- DateTime expected = DateTime.MaxValue;
- string expectedString = expected.ToString("G");
-
- DateTime result = DateTime.ParseExact(expectedString, "G", null);
- Assert.Equal(expectedString, result.ToString("G"));
+ public static IEnumerable<object[]> StandardFormatSpecifiers()
+ {
+ yield return new object[] { "d" };
+ yield return new object[] { "D" };
+ yield return new object[] { "f" };
+ yield return new object[] { "F" };
+ yield return new object[] { "g" };
+ yield return new object[] { "G" };
+ yield return new object[] { "m" };
+ yield return new object[] { "M" };
+ yield return new object[] { "o" };
+ yield return new object[] { "O" };
+ yield return new object[] { "r" };
+ yield return new object[] { "R" };
+ yield return new object[] { "s" };
+ yield return new object[] { "t" };
+ yield return new object[] { "T" };
+ yield return new object[] { "u" };
+ yield return new object[] { "U" };
+ yield return new object[] { "y" };
+ yield return new object[] { "Y" };
}
- [Fact]
- public static void ParseExact_String_String_FormatProvider_DateTimeStyles_U()
+ [Theory]
+ [MemberData(nameof(StandardFormatSpecifiers))]
+ public static void ParseExact_ToStringThenParseExactRoundtrip_Success(string standardFormat)
{
- DateTime expected = DateTime.MaxValue;
- string expectedString = expected.ToString("u");
+ DateTime dt = DateTime.Now;
+ string expected = dt.ToString(standardFormat);
- DateTime result = DateTime.ParseExact(expectedString, "u", null, DateTimeStyles.None);
- Assert.Equal(expectedString, result.ToString("u"));
+ Assert.Equal(expected, DateTime.ParseExact(expected, standardFormat, null).ToString(standardFormat));
+ Assert.Equal(expected, DateTime.ParseExact(expected, standardFormat, null, DateTimeStyles.None).ToString(standardFormat));
+ Assert.Equal(expected, DateTime.ParseExact(expected, new[] { standardFormat }, null, DateTimeStyles.None).ToString(standardFormat));
+
+ Assert.True(DateTime.TryParseExact(expected, standardFormat, null, DateTimeStyles.None, out DateTime actual));
+ Assert.Equal(expected, actual.ToString(standardFormat));
+ Assert.True(DateTime.TryParseExact(expected, new[] { standardFormat }, null, DateTimeStyles.None, out actual));
+ Assert.Equal(expected, actual.ToString(standardFormat));
+
+ // Should also parse with Parse, though may not round trip exactly
+ DateTime.Parse(expected);
}
- [Fact]
- public static void ParseExact_String_String_FormatProvider_DateTimeStyles_G()
+ public static IEnumerable<object[]> InvalidFormatSpecifierRoundtripPairs()
{
- DateTime expected = DateTime.MaxValue;
- string expectedString = expected.ToString("g");
-
- DateTime result = DateTime.ParseExact(expectedString, "g", null, DateTimeStyles.None);
- Assert.Equal(expectedString, result.ToString("g"));
+ yield return new object[] { "d", "f" };
+ yield return new object[] { "o", "r" };
+ yield return new object[] { "u", "y" };
}
[Theory]
- [MemberData(nameof(Format_String_TestData_O))]
- public static void ParseExact_String_String_FormatProvider_DateTimeStyles_O(DateTime dt, string expected)
+ [MemberData(nameof(InvalidFormatSpecifierRoundtripPairs))]
+ public static void ParseExact_ToStringThenParseExact_RoundtripWithOtherFormat_Fails(string toStringFormat, string parseFormat)
{
- string actual = dt.ToString("o");
- Assert.Equal(expected, actual);
+ DateTime dt = DateTime.Now;
+ string expected = dt.ToString(toStringFormat);
+
+ Assert.Throws<FormatException>(() => DateTime.ParseExact(expected, parseFormat, null));
+ Assert.Throws<FormatException>(() => DateTime.ParseExact(expected, parseFormat, null, DateTimeStyles.None));
+ Assert.Throws<FormatException>(() => DateTime.ParseExact(expected, new[] { parseFormat }, null, DateTimeStyles.None));
- DateTime result = DateTime.ParseExact(actual, "o", null, DateTimeStyles.None);
- Assert.Equal(expected, result.ToString("o"));
+ Assert.False(DateTime.TryParseExact(expected, parseFormat, null, DateTimeStyles.None, out DateTime result));
+ Assert.False(DateTime.TryParseExact(expected, new[] { parseFormat }, null, DateTimeStyles.None, out result));
}
public static IEnumerable<object[]> Format_String_TestData_O()
@@ -692,16 +772,6 @@ namespace System.Tests
}
[Fact]
- public static void ParseExact_String_String_FormatProvider_DateTimeStyles_R()
- {
- DateTime expected = DateTime.MaxValue;
- string expectedString = expected.ToString("r");
-
- DateTime result = DateTime.ParseExact(expectedString, "r", null, DateTimeStyles.None);
- Assert.Equal(expectedString, result.ToString("r"));
- }
-
- [Fact]
public static void ParseExact_String_String_FormatProvider_DateTimeStyles_CustomFormatProvider()
{
var formatter = new MyFormatter();
@@ -896,5 +966,160 @@ namespace System.Tests
DateTimeStyles style = DateTimeStyles.AssumeLocal | DateTimeStyles.AssumeUniversal;
AssertExtensions.Throws<ArgumentException>("style", () => DateTime.ParseExact(strDateTime, formats, provider, style));
}
+
+ public static IEnumerable<object[]> Parse_ValidInput_Suceeds_MemberData()
+ {
+ yield return new object[] { "1234 12", CultureInfo.InvariantCulture, new DateTime(1234, 12, 1, 0, 0, 0) };
+ yield return new object[] { "12 1234", CultureInfo.InvariantCulture, new DateTime(1234, 12, 1, 0, 0, 0) };
+ yield return new object[] { "12 1234 11", CultureInfo.InvariantCulture, new DateTime(1234, 12, 11, 0, 0, 0) };
+ yield return new object[] { "1234 12 13", CultureInfo.InvariantCulture, new DateTime(1234, 12, 13, 0, 0, 0) };
+ yield return new object[] { "12 13 1234", CultureInfo.InvariantCulture, new DateTime(1234, 12, 13, 0, 0, 0) };
+ yield return new object[] { "1 1 1", CultureInfo.InvariantCulture, new DateTime(2001, 1, 1, 0, 0, 0) };
+ yield return new object[] { "2 2 2Z", CultureInfo.InvariantCulture, TimeZoneInfo.ConvertTimeFromUtc(new DateTime(2002, 2, 2, 0, 0, 0, DateTimeKind.Utc), TimeZoneInfo.Local) };
+ yield return new object[] { "#10/10/2095#\0", CultureInfo.InvariantCulture, new DateTime(2095, 10, 10, 0, 0, 0) };
+
+ DateTime today = DateTime.Today;
+ var hebrewCulture = new CultureInfo("he-IL");
+ hebrewCulture.DateTimeFormat.Calendar = new HebrewCalendar();
+ yield return new object[] { today.ToString(hebrewCulture), hebrewCulture, today };
+
+ var mongolianCulture = new CultureInfo("mn-MN");
+ yield return new object[] { today.ToString(mongolianCulture), mongolianCulture, today };
+ }
+
+ [Theory]
+ [MemberData(nameof(Parse_ValidInput_Suceeds_MemberData))]
+ public static void Parse_ValidInput_Suceeds(string input, CultureInfo culture, DateTime? expected)
+ {
+ Assert.Equal(expected, DateTime.Parse(input, culture));
+ }
+
+ public static IEnumerable<object[]> ParseExact_ValidInput_Succeeds_MemberData()
+ {
+ yield return new object[] { "9", "%d", CultureInfo.InvariantCulture, DateTimeStyles.None, new DateTime(DateTime.Now.Year, 1, 9, 0, 0, 0) };
+ yield return new object[] { "15", "dd", CultureInfo.InvariantCulture, DateTimeStyles.None, new DateTime(DateTime.Now.Year, 1, 15, 0, 0, 0) };
+
+ yield return new object[] { "9", "%M", CultureInfo.InvariantCulture, DateTimeStyles.None, new DateTime(DateTime.Now.Year, 9, 1, 0, 0, 0) };
+ yield return new object[] { "09", "MM", CultureInfo.InvariantCulture, DateTimeStyles.None, new DateTime(DateTime.Now.Year, 9, 1, 0, 0, 0) };
+ yield return new object[] { "Sep", "MMM", CultureInfo.InvariantCulture, DateTimeStyles.None, new DateTime(DateTime.Now.Year, 9, 1, 0, 0, 0) };
+ yield return new object[] { "September", "MMMM", CultureInfo.InvariantCulture, DateTimeStyles.None, new DateTime(DateTime.Now.Year, 9, 1, 0, 0, 0) };
+
+ yield return new object[] { "1", "%y", CultureInfo.InvariantCulture, DateTimeStyles.None, new DateTime(2001, 1, 1, 0, 0, 0) };
+ yield return new object[] { "01", "yy", CultureInfo.InvariantCulture, DateTimeStyles.None, new DateTime(2001, 1, 1, 0, 0, 0) };
+ yield return new object[] { "2001", "yyyy", CultureInfo.InvariantCulture, DateTimeStyles.None, new DateTime(2001, 1, 1, 0, 0, 0) };
+
+ yield return new object[] { "3", "%H", CultureInfo.InvariantCulture, DateTimeStyles.None, DateTime.Today + TimeSpan.FromHours(3) };
+ yield return new object[] { "03", "HH", CultureInfo.InvariantCulture, DateTimeStyles.None, DateTime.Today + TimeSpan.FromHours(3) };
+
+ yield return new object[] { "3A", "ht", CultureInfo.InvariantCulture, DateTimeStyles.None, DateTime.Today + TimeSpan.FromHours(3) };
+ yield return new object[] { "03A", "hht", CultureInfo.InvariantCulture, DateTimeStyles.None, DateTime.Today + TimeSpan.FromHours(3) };
+ yield return new object[] { "3P", "ht", CultureInfo.InvariantCulture, DateTimeStyles.None, DateTime.Today + TimeSpan.FromHours(12 + 3) };
+ yield return new object[] { "03P", "hht", CultureInfo.InvariantCulture, DateTimeStyles.None, DateTime.Today + TimeSpan.FromHours(12 + 3) };
+
+ yield return new object[] { "2017-10-11 01:23:45Z", "u", CultureInfo.InvariantCulture, DateTimeStyles.None, new DateTime(2017, 10, 11, 1, 23, 45) };
+ yield return new object[] { "9/8/2017 10:11:12 AM", "M/d/yyyy HH':'mm':'ss tt", CultureInfo.InvariantCulture, DateTimeStyles.None, new DateTime(2017, 9, 8, 10, 11, 12) };
+ yield return new object[] { "9/8/2017 20:11:12 PM", "M/d/yyyy HH':'mm':'ss tt", CultureInfo.InvariantCulture, DateTimeStyles.None, new DateTime(2017, 9, 8, 20, 11, 12) };
+ yield return new object[] { "Fri, 08 Sep 2017 11:18:19 -0000", "ddd, d MMM yyyy H:m:s zzz", new CultureInfo("en-US"), DateTimeStyles.AllowInnerWhite, new DateTime(2017, 9, 8, 11, 18, 19, DateTimeKind.Utc) };
+ yield return new object[] { "1234-05-06T07:00:00.8Z", "yyyy-MM-dd'T'HH:mm:ss.FFF'Z'", CultureInfo.InvariantCulture, DateTimeStyles.None, new DateTime(1234, 5, 6, 7, 0, 0, 800) };
+ yield return new object[] { "1234-05-06T07:00:00Z", "yyyy-MM-dd'T'HH:mm:ss.FFF'Z'", CultureInfo.InvariantCulture, DateTimeStyles.None, new DateTime(1234, 5, 6, 7, 0, 0, 0) };
+ yield return new object[] { "1234-05-06T07:00:00Z", "yyyy-MM-dd'T'HH:mm:ssFFF'Z'", CultureInfo.InvariantCulture, DateTimeStyles.None, new DateTime(1234, 5, 6, 7, 0, 0, 0) };
+ yield return new object[] { "1234-05-06T07:00:00Z", "yyyy-MM-dd'T'HH:mm:ssFFF'Z'", CultureInfo.InvariantCulture, DateTimeStyles.None, new DateTime(1234, 5, 6, 7, 0, 0, 0) };
+ yield return new object[] { "1234-05-06T07:00:00Z", "yyyy-MM-dd'T'HH:mm:ssFFFZ", CultureInfo.InvariantCulture, DateTimeStyles.None, TimeZoneInfo.ConvertTimeFromUtc(new DateTime(1234, 5, 6, 7, 0, 0, DateTimeKind.Utc), TimeZoneInfo.Local) };
+ yield return new object[] { "1234-05-06T07:00:00GMT", "yyyy-MM-dd'T'HH:mm:ssFFFZ", CultureInfo.InvariantCulture, DateTimeStyles.None, TimeZoneInfo.ConvertTimeFromUtc(new DateTime(1234, 5, 6, 7, 0, 0, DateTimeKind.Utc), TimeZoneInfo.Local) };
+
+ var hebrewCulture = new CultureInfo("he-IL");
+ hebrewCulture.DateTimeFormat.Calendar = new HebrewCalendar();
+ DateTime today = DateTime.Today;
+ foreach (string pattern in hebrewCulture.DateTimeFormat.GetAllDateTimePatterns())
+ {
+ yield return new object[] { today.ToString(pattern, hebrewCulture), pattern, hebrewCulture, DateTimeStyles.None, null };
+ }
+ }
+
+ [Theory]
+ [MemberData(nameof(ParseExact_ValidInput_Succeeds_MemberData))]
+ public static void ParseExact_ValidInput_Succeeds(string input, string format, CultureInfo culture, DateTimeStyles style, DateTime? expected)
+ {
+ DateTime result1 = DateTime.ParseExact(input, format, culture, style);
+ DateTime result2 = DateTime.ParseExact(input, new[] { format }, culture, style);
+
+ Assert.True(DateTime.TryParseExact(input, format, culture, style, out DateTime result3));
+ Assert.True(DateTime.TryParseExact(input, new[] { format }, culture, style, out DateTime result4));
+
+ Assert.Equal(result1, result2);
+ Assert.Equal(result1, result3);
+ Assert.Equal(result1, result4);
+
+ if (expected != null) // some inputs don't roundtrip well
+ {
+ // Normalize values to make comparison easier
+ if (expected.Value.Kind != DateTimeKind.Utc)
+ {
+ expected = expected.Value.ToUniversalTime();
+ }
+ if (result1.Kind != DateTimeKind.Utc)
+ {
+ result1 = result1.ToUniversalTime();
+ }
+
+ Assert.Equal(expected, result1);
+ }
+ }
+
+ public static IEnumerable<object[]> ParseExact_InvalidInputs_Fail_MemberData()
+ {
+ yield return new object[] { "6/28/2004 13:00:00 AM", "M/d/yyyy HH':'mm':'ss tt", CultureInfo.InvariantCulture, DateTimeStyles.None };
+ yield return new object[] { "6/28/2004 03:00:00 PM", "M/d/yyyy HH':'mm':'ss tt", CultureInfo.InvariantCulture, DateTimeStyles.None };
+
+ yield return new object[] { "1", "dd", CultureInfo.InvariantCulture, DateTimeStyles.None };
+ yield return new object[] { "99", "dd", CultureInfo.InvariantCulture, DateTimeStyles.None };
+ yield return new object[] { "123", "dd", CultureInfo.InvariantCulture, DateTimeStyles.None };
+
+ yield return new object[] { "1", "mm", CultureInfo.InvariantCulture, DateTimeStyles.None };
+ yield return new object[] { "99", "mm", CultureInfo.InvariantCulture, DateTimeStyles.None };
+ yield return new object[] { "123", "mm", CultureInfo.InvariantCulture, DateTimeStyles.None };
+
+ yield return new object[] { "1", "ss", CultureInfo.InvariantCulture, DateTimeStyles.None };
+ yield return new object[] { "99", "ss", CultureInfo.InvariantCulture, DateTimeStyles.None };
+ yield return new object[] { "123", "ss", CultureInfo.InvariantCulture, DateTimeStyles.None };
+
+ yield return new object[] { "1", "MM", CultureInfo.InvariantCulture, DateTimeStyles.None };
+ yield return new object[] { "99", "MM", CultureInfo.InvariantCulture, DateTimeStyles.None };
+ yield return new object[] { "Fep", "MMM", CultureInfo.InvariantCulture, DateTimeStyles.None };
+ yield return new object[] { "Jantember", "MMMM", CultureInfo.InvariantCulture, DateTimeStyles.None };
+
+ yield return new object[] { "123", "YY", CultureInfo.InvariantCulture, DateTimeStyles.None };
+ yield return new object[] { "12345", "YYYY", CultureInfo.InvariantCulture, DateTimeStyles.None };
+
+ yield return new object[] { "1", "HH", CultureInfo.InvariantCulture, DateTimeStyles.None };
+ yield return new object[] { "99", "HH", CultureInfo.InvariantCulture, DateTimeStyles.None };
+ yield return new object[] { "123", "HH", CultureInfo.InvariantCulture, DateTimeStyles.None };
+
+ yield return new object[] { "1", "hh", CultureInfo.InvariantCulture, DateTimeStyles.None };
+ yield return new object[] { "99", "hh", CultureInfo.InvariantCulture, DateTimeStyles.None };
+ yield return new object[] { "123", "hh", CultureInfo.InvariantCulture, DateTimeStyles.None };
+
+ yield return new object[] { "1", "ff", CultureInfo.InvariantCulture, DateTimeStyles.None };
+ yield return new object[] { "123", "ff", CultureInfo.InvariantCulture, DateTimeStyles.None };
+ yield return new object[] { "123456", "fffff", CultureInfo.InvariantCulture, DateTimeStyles.None };
+ yield return new object[] { "1234", "fffff", CultureInfo.InvariantCulture, DateTimeStyles.None };
+
+ yield return new object[] { "AM", "t", CultureInfo.InvariantCulture, DateTimeStyles.None };
+ yield return new object[] { "PM", "t", CultureInfo.InvariantCulture, DateTimeStyles.None };
+ yield return new object[] { "PM", "ttt", CultureInfo.InvariantCulture, DateTimeStyles.None };
+ yield return new object[] { "AAM", "tt", CultureInfo.InvariantCulture, DateTimeStyles.None };
+ yield return new object[] { "CM", "tt", CultureInfo.InvariantCulture, DateTimeStyles.None };
+ }
+
+ [Theory]
+ [MemberData(nameof(ParseExact_InvalidInputs_Fail_MemberData))]
+ public static void ParseExact_InvalidInputs_Fail(string input, string format, CultureInfo culture, DateTimeStyles style)
+ {
+ Assert.Throws<FormatException>(() => DateTime.ParseExact(input, format, culture, style));
+ Assert.Throws<FormatException>(() => DateTime.ParseExact(input, new[] { format }, culture, style));
+
+ Assert.False(DateTime.TryParseExact(input, format, culture, style, out DateTime result));
+ Assert.False(DateTime.TryParseExact(input, new[] { format }, culture, style, out result));
+ }
}
}
diff --git a/src/System.Runtime/tests/System/DecimalTests.cs b/src/System.Runtime/tests/System/DecimalTests.cs
index 1c7738a8ac..ce30b774fd 100644
--- a/src/System.Runtime/tests/System/DecimalTests.cs
+++ b/src/System.Runtime/tests/System/DecimalTests.cs
@@ -5,6 +5,8 @@
using System.Collections.Generic;
using System.Diagnostics;
using System.Globalization;
+using System.Linq;
+using System.Numerics;
using Xunit;
namespace System.Tests
@@ -1293,5 +1295,388 @@ namespace System.Tests
{
Assert.Equal(expected, --d);
}
+
+ public static class BigIntegerCompare
+ {
+ [Fact]
+ public static void Test()
+ {
+ decimal[] decimalValues = GetRandomData(out BigDecimal[] bigDecimals);
+ for (int i = 0; i < decimalValues.Length; i++)
+ {
+ decimal d1 = decimalValues[i];
+ BigDecimal b1 = bigDecimals[i];
+ for (int j = 0; j < decimalValues.Length; j++)
+ {
+ decimal d2 = decimalValues[j];
+ int expected = b1.CompareTo(bigDecimals[j]);
+ int actual = d1.CompareTo(d2);
+ if (expected != actual)
+ throw new Xunit.Sdk.AssertActualExpectedException(expected, actual, d1 + " CMP " + d2);
+ }
+ }
+ }
+ }
+
+ public static class BigIntegerAdd
+ {
+ [Fact]
+ public static void Test()
+ {
+ int overflowBudget = 1000;
+ decimal[] decimalValues = GetRandomData(out BigDecimal[] bigDecimals);
+ for (int i = 0; i < decimalValues.Length; i++)
+ {
+ decimal d1 = decimalValues[i];
+ BigDecimal b1 = bigDecimals[i];
+ for (int j = 0; j < decimalValues.Length; j++)
+ {
+ decimal d2 = decimalValues[j];
+ BigDecimal expected = b1.Add(bigDecimals[j], out bool expectedOverflow);
+ if (expectedOverflow)
+ {
+ if (--overflowBudget < 0)
+ continue;
+ try
+ {
+ decimal actual = d1 + d2;
+ throw new Xunit.Sdk.AssertActualExpectedException(typeof(OverflowException), actual, d1 + " + " + d2);
+ }
+ catch (OverflowException) { }
+ }
+ else
+ unsafe
+ {
+ decimal actual = d1 + d2;
+ if (expected.Scale != (byte)(*(uint*)&actual >> BigDecimal.ScaleShift) || expected.CompareTo(new BigDecimal(actual)) != 0)
+ throw new Xunit.Sdk.AssertActualExpectedException(expected, actual, d1 + " + " + d2);
+ }
+ }
+ }
+ }
+ }
+
+ public static class BigIntegerMul
+ {
+ [Fact]
+ public static void Test()
+ {
+ int overflowBudget = 1000;
+ decimal[] decimalValues = GetRandomData(out BigDecimal[] bigDecimals);
+ for (int i = 0; i < decimalValues.Length; i++)
+ {
+ decimal d1 = decimalValues[i];
+ BigDecimal b1 = bigDecimals[i];
+ for (int j = 0; j < decimalValues.Length; j++)
+ {
+ decimal d2 = decimalValues[j];
+ BigDecimal expected = b1.Mul(bigDecimals[j], out bool expectedOverflow);
+ if (expectedOverflow)
+ {
+ if (--overflowBudget < 0)
+ continue;
+ try
+ {
+ decimal actual = d1 * d2;
+ throw new Xunit.Sdk.AssertActualExpectedException(typeof(OverflowException), actual, d1 + " * " + d2);
+ }
+ catch (OverflowException) { }
+ }
+ else
+ unsafe
+ {
+ decimal actual = d1 * d2;
+ if (expected.Scale != (byte)(*(uint*)&actual >> BigDecimal.ScaleShift) || expected.CompareTo(new BigDecimal(actual)) != 0)
+ throw new Xunit.Sdk.AssertActualExpectedException(expected, actual, d1 + " * " + d2);
+ }
+ }
+ }
+ }
+ }
+
+ public static class BigIntegerDiv
+ {
+ [Fact]
+ public static void Test()
+ {
+ int overflowBudget = 1000;
+ decimal[] decimalValues = GetRandomData(out BigDecimal[] bigDecimals);
+ for (int i = 0; i < decimalValues.Length; i++)
+ {
+ decimal d1 = decimalValues[i];
+ BigDecimal b1 = bigDecimals[i];
+ for (int j = 0; j < decimalValues.Length; j++)
+ {
+ decimal d2 = decimalValues[j];
+ if (Math.Sign(d2) == 0)
+ continue;
+ BigDecimal expected = b1.Div(bigDecimals[j], out bool expectedOverflow);
+ if (expectedOverflow)
+ {
+ if (--overflowBudget < 0)
+ continue;
+ try
+ {
+ decimal actual = d1 / d2;
+ throw new Xunit.Sdk.AssertActualExpectedException(typeof(OverflowException), actual, d1 + " / " + d2);
+ }
+ catch (OverflowException) { }
+ }
+ else
+ unsafe
+ {
+ decimal actual = d1 / d2;
+ if (expected.Scale != (byte)(*(uint*)&actual >> BigDecimal.ScaleShift) || expected.CompareTo(new BigDecimal(actual)) != 0)
+ throw new Xunit.Sdk.AssertActualExpectedException(expected, actual, d1 + " / " + d2);
+ }
+ }
+ }
+ }
+ }
+
+ static decimal[] GetRandomData(out BigDecimal[] bigDecimals)
+ {
+ // some static data to test the limits
+ var list = new List<decimal> { new decimal(0, 0, 0, true, 0), decimal.Zero, decimal.MinusOne, decimal.One, decimal.MinValue, decimal.MaxValue,
+ new decimal(1, 0, 0, true, 28), new decimal(1, 0, 0, false, 28),
+ new decimal(123877878, -16789245, 1086421879, true, 16), new decimal(527635459, -80701438, 1767087216, true, 24), new decimal(253511426, -909347550, -753557281, false, 12) };
+
+ // ~1000 different random decimals covering every scale and sign with ~20 different bitpatterns each
+ var rnd = new Random(42);
+ var unique = new HashSet<string>();
+ for (byte scale = 0; scale <= 28; scale++)
+ for (int sign = 0; sign <= 1; sign++)
+ for (int high = 0; high <= 96; high = IncBitLimits(high))
+ for (int low = 0; low < high || (high | low) == 0; low = IncBitLimits(high))
+ {
+ var d = new decimal(GetDigits(low, high), GetDigits(low - 32, high - 32), GetDigits(low - 64, high - 64), sign != 0, scale);
+ if (!unique.Add(d.ToString(CultureInfo.InvariantCulture)))
+ continue; // skip duplicates
+ list.Add(d);
+ }
+ decimal[] decimalValues = list.ToArray();
+ bigDecimals = Array.ConvertAll(decimalValues, d => new BigDecimal(d));
+ return decimalValues;
+
+ // While the decimals are random in general,
+ // they are particularly focused on numbers starting or ending at bits 0-3, 30-34, 62-66, 94-96 to focus more on the corner cases around uint32 boundaries.
+ int IncBitLimits(int i)
+ {
+ switch (i)
+ {
+ case 3:
+ return 30;
+ case 34:
+ return 62;
+ case 66:
+ return 94;
+ default:
+ return i + 1;
+ }
+ }
+
+ // Generates a random number, only bits between low and high can be set.
+ int GetDigits(int low, int high)
+ {
+ if (high <= 0 || low >= 32)
+ return 0;
+ uint res = 0;
+ if (high <= 32)
+ res = 1u << (high - 1);
+ res |= (uint)Math.Ceiling((uint.MaxValue >> Math.Max(0, 32 - high)) * rnd.NextDouble());
+ if (low > 0)
+ res = (res >> low) << low;
+ return (int)res;
+ }
+ }
+
+ /// <summary>
+ /// Decimal implementation roughly based on the oleaut32 native decimal code (especially ScaleResult), but optimized for simplicity instead of speed
+ /// </summary>
+ struct BigDecimal
+ {
+ public readonly BigInteger Integer;
+ public readonly byte Scale;
+
+ public unsafe BigDecimal(decimal value)
+ {
+ Scale = (byte)(*(uint*)&value >> ScaleShift);
+ *(uint*)&value &= ~ScaleMask;
+ Integer = new BigInteger(value);
+ }
+
+ private const uint ScaleMask = 0x00FF0000;
+ public const int ScaleShift = 16;
+
+ public override string ToString()
+ {
+ if (Scale == 0)
+ return Integer.ToString();
+ var s = Integer.ToString("D" + (Scale + 1));
+ return s.Insert(s.Length - Scale, ".");
+ }
+
+ BigDecimal(BigInteger integer, byte scale)
+ {
+ Integer = integer;
+ Scale = scale;
+ }
+
+ static readonly BigInteger[] Pow10 = Enumerable.Range(0, 60).Select(i => BigInteger.Pow(10, i)).ToArray();
+
+ public int CompareTo(BigDecimal value)
+ {
+ int sd = Scale - value.Scale;
+ if (sd > 0)
+ return Integer.CompareTo(value.Integer * Pow10[sd]);
+ else if (sd < 0)
+ return (Integer * Pow10[-sd]).CompareTo(value.Integer);
+ else
+ return Integer.CompareTo(value.Integer);
+ }
+
+ public BigDecimal Add(BigDecimal value, out bool overflow)
+ {
+ int sd = Scale - value.Scale;
+ BigInteger a = Integer, b = value.Integer;
+ if (sd > 0)
+ b *= Pow10[sd];
+ else if (sd < 0)
+ a *= Pow10[-sd];
+
+ var res = a + b;
+ int scale = Math.Max(Scale, value.Scale);
+ overflow = ScaleResult(ref res, ref scale);
+ return new BigDecimal(res, (byte)scale);
+ }
+
+ public BigDecimal Mul(BigDecimal value, out bool overflow)
+ {
+ var res = Integer * value.Integer;
+ int scale = Scale + value.Scale;
+ if (res.IsZero)
+ {
+ overflow = false;
+ // VarDecMul quirk: multipling by zero results in a scaled zero (e.g., 0.000) only if the intermediate scale is <=47 and both inputs fit in 32 bits!
+ if (scale <= 47 && BigInteger.Abs(Integer) <= MaxInteger32 && BigInteger.Abs(value.Integer) <= MaxInteger32)
+ scale = Math.Min(scale, 28);
+ else
+ scale = 0;
+ }
+ else
+ {
+ overflow = ScaleResult(ref res, ref scale);
+ // VarDecMul quirk: rounding to zero results in a scaled zero (e.g., 0.000), except if the intermediate scale is >47 and both inputs fit in 32 bits!
+ if (res.IsZero && scale == 28 && Scale + value.Scale > 47 && BigInteger.Abs(Integer) <= MaxInteger32 && BigInteger.Abs(value.Integer) <= MaxInteger32)
+ scale = 0;
+ }
+ return new BigDecimal(res, (byte)scale);
+ }
+
+ public BigDecimal Div(BigDecimal value, out bool overflow)
+ {
+ int scale = Scale - value.Scale;
+ var dividend = Integer;
+ if (scale < 0)
+ {
+ dividend *= Pow10[-scale];
+ scale = 0;
+ }
+
+ var quo = BigInteger.DivRem(dividend, value.Integer, out var remainder);
+ if (remainder.IsZero)
+ overflow = BigInteger.Abs(quo) > MaxInteger;
+ else
+ {
+ // We have computed a quotient based on the natural scale ( <dividend scale> - <divisor scale> ).
+ // We have a non-zero remainder, so now we increase the scale to DEC_SCALE_MAX+1 to include more quotient bits.
+ var pow = Pow10[29 - scale];
+ quo *= pow;
+ quo += BigInteger.DivRem(remainder * pow, value.Integer, out remainder);
+ scale = 29;
+
+ overflow = ScaleResult(ref quo, ref scale, !remainder.IsZero);
+
+ // Unscale the result (removes extra zeroes).
+ while (scale > 0 && quo.IsEven)
+ {
+ var tmp = BigInteger.DivRem(quo, 10, out remainder);
+ if (!remainder.IsZero)
+ break;
+ quo = tmp;
+ scale--;
+ }
+ }
+ return new BigDecimal(quo, (byte)scale);
+ }
+
+ static readonly BigInteger MaxInteger = (new BigInteger(ulong.MaxValue) << 32) | uint.MaxValue;
+ static readonly BigInteger MaxInteger32 = uint.MaxValue;
+ static readonly double Log2To10 = Math.Log(2) / Math.Log(10);
+
+ /// <summary>
+ /// Returns Log10 for the given number, offset by 96bits.
+ /// </summary>
+ static int ScaleOverMaxInteger(BigInteger abs) => abs.IsZero ? -28 : (int)(((int)BigInteger.Log(abs, 2) - 95) * Log2To10);
+
+ /// <summary>
+ /// See if we need to scale the result to fit it in 96 bits.
+ /// Perform needed scaling. Adjust scale factor accordingly.
+ /// </summary>
+ static bool ScaleResult(ref BigInteger res, ref int scale, bool sticky = false)
+ {
+ int newScale = 0;
+ var abs = BigInteger.Abs(res);
+ if (abs > MaxInteger)
+ {
+ // Find the min scale factor to make the result to fit it in 96 bits, 0 - 29.
+ // This reduces the scale factor of the result. If it exceeds the current scale of the result, we'll overflow.
+ newScale = Math.Max(1, ScaleOverMaxInteger(abs));
+ if (newScale > scale)
+ return true;
+ }
+ // Make sure we scale by enough to bring the current scale factor into valid range.
+ newScale = Math.Max(newScale, scale - 28);
+
+ if (newScale != 0)
+ {
+ // Scale by the power of 10 given by newScale.
+ // This is not guaranteed to bring the number within 96 bits -- it could be 1 power of 10 short.
+ scale -= newScale;
+ var pow = Pow10[newScale];
+ while (true)
+ {
+ abs = BigInteger.DivRem(abs, pow, out var remainder);
+ // If we didn't scale enough, divide by 10 more.
+ if (abs > MaxInteger)
+ {
+ if (scale == 0)
+ return true;
+ pow = 10;
+ scale--;
+ sticky |= !remainder.IsZero;
+ continue;
+ }
+
+ // Round final result. See if remainder >= 1/2 of divisor.
+ // If remainder == 1/2 divisor, round up if odd or sticky bit set.
+ pow >>= 1;
+ if (remainder < pow || remainder == pow && !sticky && abs.IsEven)
+ break;
+ if (++abs <= MaxInteger)
+ break;
+
+ // The rounding caused us to carry beyond 96 bits. Scale by 10 more.
+ if (scale == 0)
+ return true;
+ pow = 10;
+ scale--;
+ sticky = false;
+ }
+ res = res.Sign < 0 ? -abs : abs;
+ }
+ return false;
+ }
+ }
}
}
diff --git a/src/System.Runtime/tests/System/GuidTests.cs b/src/System.Runtime/tests/System/GuidTests.cs
index 122bb7bad9..1c8b7afc27 100644
--- a/src/System.Runtime/tests/System/GuidTests.cs
+++ b/src/System.Runtime/tests/System/GuidTests.cs
@@ -348,14 +348,14 @@ namespace System.Tests
public static IEnumerable<object[]> ToString_TestData()
{
- yield return new object[] { s_testGuid, "N", "a8a110d5fc4943c5bf46802db8f843ff" };
- yield return new object[] { s_testGuid, "D", "a8a110d5-fc49-43c5-bf46-802db8f843ff" };
- yield return new object[] { s_testGuid, "B", "{a8a110d5-fc49-43c5-bf46-802db8f843ff}" };
- yield return new object[] { s_testGuid, "P", "(a8a110d5-fc49-43c5-bf46-802db8f843ff)" };
- yield return new object[] { s_testGuid, "X", "{0xa8a110d5,0xfc49,0x43c5,{0xbf,0x46,0x80,0x2d,0xb8,0xf8,0x43,0xff}}" };
+ yield return new object[] { s_testGuid, "N", "a8a110d5fc4943c5bf46802db8f843ff"};
+ yield return new object[] { s_testGuid, "D", "a8a110d5-fc49-43c5-bf46-802db8f843ff"};
+ yield return new object[] { s_testGuid, "B", "{a8a110d5-fc49-43c5-bf46-802db8f843ff}"};
+ yield return new object[] { s_testGuid, "P", "(a8a110d5-fc49-43c5-bf46-802db8f843ff)"};
+ yield return new object[] { s_testGuid, "X", "{0xa8a110d5,0xfc49,0x43c5,{0xbf,0x46,0x80,0x2d,0xb8,0xf8,0x43,0xff}}"};
- yield return new object[] { s_testGuid, null, "a8a110d5-fc49-43c5-bf46-802db8f843ff" };
- yield return new object[] { s_testGuid, "", "a8a110d5-fc49-43c5-bf46-802db8f843ff" };
+ yield return new object[] { s_testGuid, null, "a8a110d5-fc49-43c5-bf46-802db8f843ff"};
+ yield return new object[] { s_testGuid, "", "a8a110d5-fc49-43c5-bf46-802db8f843ff"};
}
[Theory]
@@ -372,11 +372,12 @@ namespace System.Tests
Assert.Equal(expected, formattable.ToString(format, null));
}
- [Fact]
- public static void ToString_InvalidFormat_ThrowsFormatException()
+ [Theory]
+ [InlineData("Y")]
+ [InlineData("XX")]
+ public static void ToString_InvalidFormat_ThrowsFormatException(string format)
{
- Assert.Throws<FormatException>(() => s_testGuid.ToString("Y")); // Invalid format
- Assert.Throws<FormatException>(() => s_testGuid.ToString("XX")); // Invalid format
+ Assert.Throws<FormatException>(() => s_testGuid.ToString(format));
}
public static IEnumerable<object[]> GuidStrings_Valid_TestData()
diff --git a/src/System.Runtime/tests/System/GuidTests.netcoreapp.cs b/src/System.Runtime/tests/System/GuidTests.netcoreapp.cs
new file mode 100644
index 0000000000..512f35558b
--- /dev/null
+++ b/src/System.Runtime/tests/System/GuidTests.netcoreapp.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 Xunit;
+
+namespace System.Tests
+{
+ public static partial class GuidTests
+ {
+ [Theory]
+ [MemberData(nameof(Ctor_ByteArray_TestData))]
+ public static void Ctor_ReadOnlySpan(byte[] b, Guid expected)
+ {
+ Assert.Equal(expected, new Guid(new ReadOnlySpan<byte>(b)));
+ }
+
+ [Theory]
+ [InlineData(15)]
+ [InlineData(17)]
+ public static void CtorSpan_InvalidLengthByteArray_ThrowsArgumentException(int length)
+ {
+ AssertExtensions.Throws<ArgumentException>("b", null, () => new Guid(new ReadOnlySpan<byte>(new byte[length])));
+ }
+
+ [Theory]
+ [MemberData(nameof(Ctor_ByteArray_TestData))]
+ public static void TryWriteBytes_ValidLength_ReturnsTrue(byte[] b, Guid guid)
+ {
+ var bytes = new byte[16];
+ Assert.True(guid.TryWriteBytes(new Span<byte>(bytes)));
+ Assert.Equal(b, bytes);
+ }
+
+ [Theory]
+ [InlineData(0)]
+ [InlineData(15)]
+ public static void TryWriteBytes_LengthTooShort_ReturnsFalse(int length)
+ {
+ Assert.False(s_testGuid.TryWriteBytes(new Span<byte>(new byte[length])));
+ }
+
+ [Theory]
+ [InlineData("Y")]
+ [InlineData("XX")]
+ public static void TryFormat_InvalidFormat_ThrowsFormatException(string format)
+ {
+ Assert.Throws<FormatException>(() => s_testGuid.TryFormat(new Span<char>(), out int charsWritten, format));
+ }
+
+ [Theory]
+ [MemberData(nameof(ToString_TestData))]
+ public static void TryFormat_LengthTooSmall_ReturnsFalse(Guid guid, string format, string expected)
+ {
+ Assert.False(guid.TryFormat(new Span<char>(new char[guid.ToString(format).Length - 1]), out int charsWritten, format));
+ Assert.Equal(0, charsWritten);
+ }
+
+ [Theory]
+ [MemberData(nameof(ToString_TestData))]
+ public static void TryFormat_CharsWritten_EqualsZero_WhenSpanTooSmall(Guid guid, string format, string expected)
+ {
+ Assert.False(guid.TryFormat(new Span<char>(new char[guid.ToString(format).Length - 1]), out int charsWritten, format));
+ Assert.Equal(0, charsWritten);
+ }
+
+ [Theory]
+ [MemberData(nameof(ToString_TestData))]
+ public static void TryFormat_ValidLength_ReturnsTrue(Guid guid, string format, string expected)
+ {
+ char[] chars = new char[guid.ToString(format).Length];
+ Assert.True(guid.TryFormat(new Span<char>(chars), out int charsWritten, format));
+ Assert.Equal(chars, expected.ToCharArray());
+ }
+
+ [Theory]
+ [MemberData(nameof(GuidStrings_Valid_TestData))]
+ public static void Parse_Span_ValidInput_Success(string input, string format, Guid expected)
+ {
+ Assert.Equal(expected, Guid.Parse(input.AsReadOnlySpan()));
+ Assert.Equal(expected, Guid.ParseExact(input.AsReadOnlySpan(), format.ToUpperInvariant()));
+ Assert.Equal(expected, Guid.ParseExact(input.AsReadOnlySpan(), format.ToLowerInvariant())); // Format should be case insensitive
+
+ Guid result;
+
+ Assert.True(Guid.TryParse(input.AsReadOnlySpan(), out result));
+ Assert.Equal(expected, result);
+
+ Assert.True(Guid.TryParseExact(input.AsReadOnlySpan(), format.ToUpperInvariant(), out result));
+ Assert.Equal(expected, result);
+
+ Assert.True(Guid.TryParseExact(input.AsReadOnlySpan(), format.ToLowerInvariant(), out result)); // Format should be case insensitive
+ Assert.Equal(expected, result);
+ }
+
+ [Theory]
+ [MemberData(nameof(GuidStrings_Invalid_TestData))]
+ public static void Parse_Span_InvalidInput_Fails(string input, Type exceptionType)
+ {
+ if (input == null)
+ {
+ return;
+ }
+
+ // Overflow exceptions throw as format exceptions in Parse
+ if (exceptionType.Equals(typeof(OverflowException)))
+ {
+ exceptionType = typeof(FormatException);
+ }
+ Assert.Throws(exceptionType, () => Guid.Parse(input.AsReadOnlySpan()));
+
+ Assert.False(Guid.TryParse(input.AsReadOnlySpan(), out Guid result));
+ Assert.Equal(Guid.Empty, result);
+
+ foreach (string format in new[] { "N", "D", "B", "P", "X" })
+ {
+ Assert.Throws(exceptionType, () => Guid.ParseExact(input.AsReadOnlySpan(), format));
+
+ Assert.False(Guid.TryParseExact(input.AsReadOnlySpan(), format, out result));
+ Assert.Equal(Guid.Empty, result);
+ }
+ }
+ }
+}
diff --git a/src/System.Runtime/tests/System/Reflection/BindingFlagsDoNotWrap.netcoreapp.cs b/src/System.Runtime/tests/System/Reflection/BindingFlagsDoNotWrap.netcoreapp.cs
new file mode 100644
index 0000000000..2b0052f154
--- /dev/null
+++ b/src/System.Runtime/tests/System/Reflection/BindingFlagsDoNotWrap.netcoreapp.cs
@@ -0,0 +1,174 @@
+// 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.Linq;
+using Xunit;
+
+namespace System.Reflection.Tests
+{
+ public static class BindingFlagsDoNotWrapTests
+ {
+ [Fact]
+ public static void MethodInvoke()
+ {
+ MethodInfo m = typeof(TestClass).GetMethod(nameof(TestClass.Moo), BindingFlags.Public | BindingFlags.Static | BindingFlags.Instance | BindingFlags.DeclaredOnly);
+ TestDoNotWrap<MyException1>((bf) => m.Invoke(null, bf, null, Array.Empty<object>(), null));
+ }
+
+ [Fact]
+ public static void ConstructorInvoke()
+ {
+ ConstructorInfo c = typeof(TestClass).GetConstructor(BindingFlags.Public|BindingFlags.Instance, null, Array.Empty<Type>(), null);
+ TestDoNotWrap<MyException2>((bf) => c.Invoke(bf, null, Array.Empty<object>(), null));
+ }
+
+ [Fact]
+ public static void ConstructorInvokeStringCtor()
+ {
+ // Code coverage: Project N - String constructors go through a separate code path.
+ ConstructorInfo c = typeof(string).GetConstructor(BindingFlags.Public | BindingFlags.Instance, null, new Type[] { typeof(char[]), typeof(int), typeof(int) }, null);
+ TestDoNotWrap<ArgumentNullException>((bf) => c.Invoke(bf, null, new object[] { null, 0, 0 }, null));
+ }
+
+ [Fact]
+ public static void ConstructorInvokeUsingMethodInfoInvoke()
+ {
+ ConstructorInfo c = typeof(TestClass).GetConstructor(BindingFlags.Public | BindingFlags.Instance, null, Array.Empty<Type>(), null);
+ TestDoNotWrap<MyException2>((bf) => c.Invoke(new TestClass(0), bf, null, Array.Empty<object>(), null));
+ }
+
+ [Fact]
+ public static void PropertyGet()
+ {
+ PropertyInfo p = typeof(TestClass).GetProperty(nameof(TestClass.MyProperty));
+ TestDoNotWrap<MyException3>((bf) => p.GetValue(null, bf, null, null, null));
+ }
+
+ [Fact]
+ public static void PropertySet()
+ {
+ PropertyInfo p = typeof(TestClass).GetProperty(nameof(TestClass.MyProperty));
+ TestDoNotWrap<MyException4>((bf) => p.SetValue(null, 42, bf, null, null, null));
+ }
+
+ [Fact]
+ public static void InvokeMember_Method()
+ {
+ Type t = typeof(TestClass);
+ const BindingFlags flags = BindingFlags.Public | BindingFlags.Static | BindingFlags.DeclaredOnly | BindingFlags.InvokeMethod;
+ TestDoNotWrap<MyException1>((bf) => t.InvokeMember(nameof(TestClass.Moo), bf | flags, null, null, Array.Empty<object>(), null, null, null));
+ }
+
+ [Fact]
+ public static void InvokeMember_PropertyGet()
+ {
+ Type t = typeof(TestClass);
+ const BindingFlags flags = BindingFlags.Public | BindingFlags.Static | BindingFlags.DeclaredOnly | BindingFlags.GetProperty;
+ TestDoNotWrap<MyException3>((bf) => t.InvokeMember(nameof(TestClass.MyProperty), bf | flags, null, null, Array.Empty<object>(), null, null, null));
+ }
+
+ [Fact]
+ public static void InvokeMember_PropertySet()
+ {
+ Type t = typeof(TestClass);
+ const BindingFlags flags = BindingFlags.Public | BindingFlags.Static | BindingFlags.DeclaredOnly | BindingFlags.SetProperty;
+ TestDoNotWrap<MyException4>((bf) => t.InvokeMember(nameof(TestClass.MyProperty), bf | flags, null, null, new object[] { 42 }, null, null, null));
+ }
+
+ [Fact]
+ public static void ActivatorCreateInstance()
+ {
+ const BindingFlags flags = BindingFlags.Public | BindingFlags.Instance;
+ TestDoNotWrap<MyException2>((bf) => Activator.CreateInstance(typeof(TestClass), bf | flags, null, Array.Empty<object>(), null, null));
+ }
+
+ [Fact]
+ public static void ActivatorCreateInstanceOneArgument()
+ {
+ // For code coverage on CoreCLR: Activator.CreateInstance with parameters uses different code path from one without parameters.
+ const BindingFlags flags = BindingFlags.Public | BindingFlags.Instance;
+ TestDoNotWrap<MyException5>((bf) => Activator.CreateInstance(typeof(TestClass), bf | flags, null, new object[] { "Hello" }, null, null));
+ }
+
+ [Fact]
+ public static void ActivatorCreateInstanceCaching()
+ {
+ // For code coverage on CoreCLR: Activator.CreateInstance - second call after non-throwing call goes through a different path
+ const BindingFlags flags = BindingFlags.Public | BindingFlags.Instance;
+ TestClassConditional.ThrowInConstructor = true;
+ TestDoNotWrap<MyException6>((bf) => Activator.CreateInstance(typeof(TestClassConditional), bf | flags, null, Array.Empty<object>(), null, null));
+
+ TestClassConditional.ThrowInConstructor = false;
+ Assert.True(Activator.CreateInstance(typeof(TestClassConditional), flags, null, Array.Empty<object>(), null, null) is TestClassConditional);
+
+ TestClassConditional.ThrowInConstructor = true;
+ TestDoNotWrap<MyException6>((bf) => Activator.CreateInstance(typeof(TestClassConditional), bf | flags, null, Array.Empty<object>(), null, null));
+ }
+
+ [Fact]
+ public static void ActivatorCreateInstance_BadCCtor()
+ {
+ const BindingFlags flags = BindingFlags.Public | BindingFlags.Instance;
+ TestDoNotWrap<TypeInitializationException>((bf) => Activator.CreateInstance(typeof(TestClassBadCCtor), bf | flags, null, Array.Empty<object>(), null, null));
+ }
+
+ [Fact]
+ public static void AssemblyCreateInstance()
+ {
+ Assembly a = typeof(TestClass).Assembly;
+ const BindingFlags flags = BindingFlags.Public | BindingFlags.Instance;
+ TestDoNotWrap<MyException2>((bf) => a.CreateInstance(typeof(TestClass).FullName, false, bf | flags, null, Array.Empty<object>(), null, null));
+ }
+
+ [Fact]
+ public static void AssemblyCreateInstance_BadCCtor()
+ {
+ Assembly a = typeof(TestClass).Assembly;
+ const BindingFlags flags = BindingFlags.Public | BindingFlags.Instance;
+ TestDoNotWrap<TypeInitializationException>((bf) => a.CreateInstance(typeof(TestClassBadCCtor).FullName, false, bf | flags, null, Array.Empty<object>(), null, null));
+ }
+
+ private static void TestDoNotWrap<T>(Action<BindingFlags> action) where T : Exception
+ {
+ Assert.Throws<T>(() => action(BindingFlags.DoNotWrapExceptions));
+ TargetInvocationException tie = Assert.Throws<TargetInvocationException>(() => action(default(BindingFlags)));
+ Assert.Equal(typeof(T), tie.InnerException.GetType());
+ }
+
+ private sealed class TestClass
+ {
+ public TestClass() => throw new MyException2();
+ public TestClass(int _) { }
+ public TestClass(string s) => throw new MyException5();
+ public static void Moo() => throw new MyException1();
+ public static int MyProperty { get { throw new MyException3(); } set { throw new MyException4(); } }
+ }
+
+ public sealed class TestClassBadCCtor
+ {
+ public TestClassBadCCtor() { }
+
+ static TestClassBadCCtor()
+ {
+ throw new MyException1();
+ }
+ }
+
+ private sealed class TestClassConditional
+ {
+ public TestClassConditional() { if (ThrowInConstructor) throw new MyException6(); }
+
+ public static bool ThrowInConstructor;
+ }
+
+ private sealed class MyException1 : Exception { }
+ private sealed class MyException2 : Exception { }
+ private sealed class MyException3 : Exception { }
+ private sealed class MyException4 : Exception { }
+ private sealed class MyException5 : Exception { }
+ private sealed class MyException6 : Exception { }
+ }
+}
diff --git a/src/System.Runtime/tests/System/Reflection/MemberInfoTests.netcoreapp.cs b/src/System.Runtime/tests/System/Reflection/MemberInfoTests.netcoreapp.cs
index 34af6255df..cbbbe2805a 100644
--- a/src/System.Runtime/tests/System/Reflection/MemberInfoTests.netcoreapp.cs
+++ b/src/System.Runtime/tests/System/Reflection/MemberInfoTests.netcoreapp.cs
@@ -267,7 +267,7 @@ namespace System.Reflection.Tests
[Fact]
public static void HasSameMetadataDefinitionAs__CornerCase_HasElementTypes()
{
- // HasSameMetadataDefinitionAs on a array/byref/pointer type is uninteresting (they'll never be an actual member of a type)
+ // HasSameMetadataDefinitionAs on an array/byref/pointer type is uninteresting (they'll never be an actual member of a type)
// but for future compat, we'll establish their known behavior here. Since these types all return a MetadataToken of 0x02000000,
// they'll all "match" each other.
diff --git a/src/System.Runtime/tests/System/Reflection/SignatureTypes.netcoreapp.cs b/src/System.Runtime/tests/System/Reflection/SignatureTypes.netcoreapp.cs
new file mode 100644
index 0000000000..dbc081f7d7
--- /dev/null
+++ b/src/System.Runtime/tests/System/Reflection/SignatureTypes.netcoreapp.cs
@@ -0,0 +1,529 @@
+// 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.Linq;
+using Xunit;
+
+namespace System.Reflection.Tests
+{
+ public static class SignatureTypeTests
+ {
+ [Fact]
+ public static void IsSignatureType()
+ {
+ // Executing [Theory] logic manually. Signature Types cannot be used in theory data because Xunit preemptively invokes an unguarded
+ // System.Type pretty printer that invokes members that Signature Types don't support.
+ foreach (object[] pair in IsSignatureTypeTestData)
+ {
+ Type type = (Type)(pair[0]);
+ bool expected = (bool)(pair[1]);
+
+ Assert.Equal(expected, type.IsSignatureType);
+ }
+ }
+
+ private static IEnumerable<object[]> IsSignatureTypeTestData
+ {
+ get
+ {
+ yield return new object[] { typeof(int), false };
+ yield return new object[] { typeof(int).MakeArrayType(), false };
+ yield return new object[] { typeof(int).MakeArrayType(1), false };
+ yield return new object[] { typeof(int).MakeArrayType(2), false };
+ yield return new object[] { typeof(int).MakeByRefType(), false };
+ yield return new object[] { typeof(int).MakePointerType(), false };
+ yield return new object[] { typeof(List<>).MakeGenericType(typeof(int)), false };
+ yield return new object[] { typeof(List<>).GetGenericArguments()[0], false };
+
+ Type sigType = Type.MakeGenericMethodParameter(2);
+
+ yield return new object[] { sigType, true };
+ yield return new object[] { sigType.MakeArrayType(), true };
+ yield return new object[] { sigType.MakeArrayType(1), true };
+ yield return new object[] { sigType.MakeArrayType(2), true };
+ yield return new object[] { sigType.MakeByRefType(), true };
+ yield return new object[] { sigType.MakePointerType(), true };
+ yield return new object[] { typeof(List<>).MakeGenericType(sigType), true };
+ }
+ }
+
+ [Fact]
+ public static void GetMethodWithGenericParameterCount()
+ {
+ Type t = typeof(TestClass1);
+ const BindingFlags bf = BindingFlags.Public | BindingFlags.Static | BindingFlags.DeclaredOnly;
+ Type[] args = { typeof(int) };
+ MethodInfo m;
+
+ Assert.Throws<AmbiguousMatchException>(() => t.GetMethod("Moo", bf, null, args, null));
+
+ for (int genericParameterCount = 0; genericParameterCount < 4; genericParameterCount++)
+ {
+ m = t.GetMethod("Moo", genericParameterCount, bf, null, args, null);
+ Assert.NotNull(m);
+ AssertIsMarked(m, genericParameterCount);
+
+ // Verify that generic parameter count filtering occurs before candidates are passed to the binder.
+ m = t.GetMethod("Moo", genericParameterCount, bf, new InflexibleBinder(genericParameterCount), args, null);
+ Assert.NotNull(m);
+ AssertIsMarked(m, genericParameterCount);
+ }
+
+ m = t.GetMethod("Moo", 4, bf, null, args, null);
+ Assert.Null(m);
+ }
+
+ private sealed class InflexibleBinder : Binder
+ {
+ public InflexibleBinder(int genericParameterCount)
+ {
+ _genericParameterCount = genericParameterCount;
+ }
+
+ public sealed override FieldInfo BindToField(BindingFlags bindingAttr, FieldInfo[] match, object value, CultureInfo culture) => throw null;
+ public sealed override MethodBase BindToMethod(BindingFlags bindingAttr, MethodBase[] match, ref object[] args, ParameterModifier[] modifiers, CultureInfo culture, string[] names, out object state) => throw null;
+ public sealed override object ChangeType(object value, Type type, CultureInfo culture) => throw null;
+ public sealed override void ReorderArgumentArray(ref object[] args, object state) => throw null;
+
+ public sealed override MethodBase SelectMethod(BindingFlags bindingAttr, MethodBase[] match, Type[] types, ParameterModifier[] modifiers)
+ {
+ foreach (MethodBase methodBase in match)
+ {
+ Assert.True(methodBase is MethodInfo methodInfo && methodInfo.GetGenericArguments().Length == _genericParameterCount);
+ }
+ return Type.DefaultBinder.SelectMethod(bindingAttr, match, types, modifiers);
+ }
+
+ public sealed override PropertyInfo SelectProperty(BindingFlags bindingAttr, PropertyInfo[] match, Type returnType, Type[] indexes, ParameterModifier[] modifiers) { throw null; }
+
+ private readonly int _genericParameterCount;
+ }
+
+ [Fact]
+ public static void GetMethodWithNegativeGenericParameterCount()
+ {
+ Type t = typeof(TestClass1);
+ const BindingFlags bf = BindingFlags.Public | BindingFlags.Static | BindingFlags.DeclaredOnly;
+ Type[] args = { typeof(int) };
+ Assert.Throws<ArgumentException>(() => t.GetMethod("Moo", -1, bf, null, args, null));
+ }
+
+ [Theory]
+ [InlineData(true)]
+ [InlineData(false)]
+ public static void GetMethodOverloadTest(bool exactBinding)
+ {
+ Type t = typeof(TestClass2);
+ BindingFlags bf = BindingFlags.Public | BindingFlags.Static | BindingFlags.DeclaredOnly;
+ if (exactBinding)
+ {
+ bf |= BindingFlags.ExactBinding;
+ }
+ Type[] args = { Type.MakeGenericMethodParameter(0), Type.MakeGenericMethodParameter(1).MakeArrayType() };
+ MethodInfo moo = t.GetMethod("Moo", 2, bf, null, args, null);
+ AssertIsMarked(moo, 3);
+ }
+
+ [Theory]
+ [InlineData(true)]
+ [InlineData(false)]
+ public static void SignatureTypeComparisonLogicCodeCoverage(bool exactBinding)
+ {
+ Type t = typeof(TestClass3<,>);
+ MethodInfo[] methods = t.GetMethods(BindingFlags.Public | BindingFlags.Static | BindingFlags.DeclaredOnly);
+ BindingFlags bf = BindingFlags.Public | BindingFlags.Static | BindingFlags.DeclaredOnly;
+ if (exactBinding)
+ {
+ bf |= BindingFlags.ExactBinding;
+ }
+
+ foreach (MethodInfo m in methods)
+ {
+ ParameterInfo[] parameters = m.GetParameters();
+ Type[] sigTypes = new Type[parameters.Length];
+ for (int i = 0; i < sigTypes.Length; i++)
+ {
+ sigTypes[i] = parameters[i].ParameterType.ToSignatureType();
+ }
+ MethodInfo match = t.GetMethod("Moo", m.GetGenericArguments().Length, bf, null, sigTypes, null);
+ Assert.NotNull(match);
+ Assert.True(m.HasSameMetadataDefinitionAs(match));
+ }
+ }
+
+ [Fact]
+ public static void SigTypeResolutionResilience()
+ {
+ // Make sure the framework can't be tricked into throwing an exception because it tried to look up a nonexistent method generic parameter
+ // or trying to construct a generic type where the constraints don't validate.
+ Type t = typeof(TestClass4<>);
+ Type[] args = { typeof(TestClass4<>).MakeGenericType(Type.MakeGenericMethodParameter(1)), Type.MakeGenericMethodParameter(500) };
+ CountingBinder binder = new CountingBinder();
+ Assert.Null(t.GetMethod("Moo", BindingFlags.Public | BindingFlags.Static | BindingFlags.DeclaredOnly, binder, args, null));
+ Assert.Equal(3, binder.NumCandidatesReceived);
+ }
+
+ private sealed class CountingBinder : Binder
+ {
+ public sealed override FieldInfo BindToField(BindingFlags bindingAttr, FieldInfo[] match, object value, CultureInfo culture) => throw null;
+ public sealed override MethodBase BindToMethod(BindingFlags bindingAttr, MethodBase[] match, ref object[] args, ParameterModifier[] modifiers, CultureInfo culture, string[] names, out object state) => throw null;
+ public sealed override object ChangeType(object value, Type type, CultureInfo culture) => throw null;
+ public sealed override void ReorderArgumentArray(ref object[] args, object state) => throw null;
+
+ public sealed override MethodBase SelectMethod(BindingFlags bindingAttr, MethodBase[] match, Type[] types, ParameterModifier[] modifiers)
+ {
+ NumCandidatesReceived += match.Length;
+ return Type.DefaultBinder.SelectMethod(bindingAttr, match, types, modifiers);
+ }
+
+ public sealed override PropertyInfo SelectProperty(BindingFlags bindingAttr, PropertyInfo[] match, Type returnType, Type[] indexes, ParameterModifier[] modifiers) { throw null; }
+
+ public int NumCandidatesReceived { get; private set; }
+ }
+
+ [Theory]
+ [InlineData(0)]
+ [InlineData(3)]
+ [InlineData(400)]
+ [InlineData(int.MaxValue)]
+ public static void MakeGenericMethodParameter(int position)
+ {
+ Type t = Type.MakeGenericMethodParameter(position);
+ Assert.True(t.IsGenericParameter);
+ Assert.Equal(position, t.GenericParameterPosition);
+ TestSignatureTypeInvariants(t);
+ }
+
+ [Theory]
+ [InlineData(-1)]
+ [InlineData(-5)]
+ [InlineData(int.MinValue)]
+ public static void MakeGenericMethodParameterNegative(int position)
+ {
+ Assert.Throws<ArgumentException>(() => Type.MakeGenericMethodParameter(position));
+ }
+
+ [Fact]
+ public static void MakeSignatureArrayType()
+ {
+ Type t = Type.MakeGenericMethodParameter(5);
+ t = t.MakeArrayType();
+ Assert.True(t.IsArray);
+ Assert.True(t.IsSZArray);
+ Assert.Equal(1, t.GetArrayRank());
+
+ Type et = t.GetElementType();
+ Assert.True(et.IsSignatureType);
+ Assert.True(et.IsGenericParameter);
+ Assert.Equal(5, et.GenericParameterPosition);
+
+ TestSignatureTypeInvariants(t);
+ }
+
+ [Theory]
+ [InlineData(1)]
+ [InlineData(2)]
+ [InlineData(3)]
+ public static void MakeSignatureMdArrayType(int rank)
+ {
+ Type t = Type.MakeGenericMethodParameter(5);
+ t = t.MakeArrayType(rank);
+ Assert.True(t.IsArray);
+ Assert.True(t.IsVariableBoundArray);
+ Assert.Equal(rank, t.GetArrayRank());
+
+ TestSignatureTypeInvariants(t);
+ }
+
+ [Fact]
+ public static void MakeSignatureByRefType()
+ {
+ Type t = Type.MakeGenericMethodParameter(5);
+ t = t.MakeByRefType();
+ Assert.True(t.IsByRef);
+
+ Type et = t.GetElementType();
+ Assert.True(et.IsSignatureType);
+ Assert.True(et.IsGenericParameter);
+ Assert.Equal(5, et.GenericParameterPosition);
+
+ TestSignatureTypeInvariants(t);
+ }
+
+ [Fact]
+ public static void MakeSignaturePointerType()
+ {
+ Type t = Type.MakeGenericMethodParameter(5);
+ t = t.MakePointerType();
+ Assert.True(t.IsPointer);
+
+ Type et = t.GetElementType();
+ Assert.True(et.IsSignatureType);
+ Assert.True(et.IsGenericParameter);
+ Assert.Equal(5, et.GenericParameterPosition);
+
+ TestSignatureTypeInvariants(t);
+ }
+
+ [Theory]
+ [InlineData(typeof(List<>))]
+ [InlineData(typeof(Span<>))]
+ public static void MakeSignatureConstructedGenericType(Type genericTypeDefinition)
+ {
+ Type t = Type.MakeGenericMethodParameter(5);
+ t = genericTypeDefinition.MakeGenericType(t);
+
+ Assert.True(t.IsConstructedGenericType);
+ Assert.Equal(genericTypeDefinition, t.GetGenericTypeDefinition());
+ Assert.Equal(1, t.GenericTypeArguments.Length);
+
+ Type et = t.GenericTypeArguments[0];
+ Assert.True(et.IsSignatureType);
+ Assert.True(et.IsGenericParameter);
+ Assert.Equal(5, et.GenericParameterPosition);
+
+ TestSignatureTypeInvariants(t);
+ }
+
+ private static Type ToSignatureType(this Type type)
+ {
+ if (type.IsTypeDefinition)
+ return type;
+ if (type.IsSZArray)
+ return type.GetElementType().ToSignatureType().MakeArrayType();
+ if (type.IsVariableBoundArray)
+ return type.GetElementType().ToSignatureType().MakeArrayType(type.GetArrayRank());
+ if (type.IsByRef)
+ return type.GetElementType().ToSignatureType().MakeByRefType();
+ if (type.IsPointer)
+ return type.GetElementType().ToSignatureType().MakePointerType();
+ if (type.IsConstructedGenericType)
+ {
+ Type[] genericTypeArguments = type.GenericTypeArguments.Select(t => t.ToSignatureType()).ToArray();
+ return type.GetGenericTypeDefinition().MakeGenericType(genericTypeArguments);
+ }
+ if (type.IsGenericParameter)
+ {
+ if (type.DeclaringMethod == null)
+ return type;
+ return Type.MakeGenericMethodParameter(type.GenericParameterPosition);
+ }
+ throw new Exception("Unknown type flavor.");
+ }
+
+ private static void AssertIsMarked(MemberInfo member, int value)
+ {
+ MarkerAttribute marker = member.GetCustomAttribute<MarkerAttribute>(inherit: false);
+ Assert.NotNull(marker);
+ Assert.Equal(value, marker.Value);
+ }
+
+ [AttributeUsage(AttributeTargets.All, Inherited = false)]
+ private sealed class MarkerAttribute : Attribute
+ {
+ public MarkerAttribute(int value)
+ {
+ Value = value;
+ }
+
+ public int Value { get; }
+ }
+
+ private sealed class TestClass1
+ {
+ [Marker(0)] public static void Moo(int x) { }
+ [Marker(1)] public static void Moo<T1>(int x) { }
+ [Marker(2)] public static void Moo<T1, T2>(int x) { }
+ [Marker(3)] public static void Moo<T1, T2, T3>(int x) {}
+ }
+
+ private class TestClass2
+ {
+ [Marker(0)] public static void Moo(int x, int[] y) { }
+ [Marker(1)] public static void Moo<T>(T x, T[] y) { }
+ [Marker(2)] public static void Moo<T>(int x, int[] y) { }
+ [Marker(3)] public static void Moo<T, U>(T x, U[] y) { }
+ [Marker(4)] public static void Moo<T, U>(int x, int[] y) { }
+ }
+
+ private class TestClass3<T,U>
+ {
+ public static void Moo(T p1, T[] p2, T[,] p3, ref T p4, TestClass3<T, T> p5, ref TestClass3<T, T[]>[,] p6) { }
+ public static void Moo(U p1, U[] p2, U[,] p3, ref U p4, TestClass3<U, U> p5, ref TestClass3<U, U[]>[,] p6) { }
+ public static void Moo<M>(T p1, T[] p2, T[,] p3, ref T p4, TestClass3<T, T> p5, ref TestClass3<T, T[]>[,] p6) { }
+ public static void Moo<M>(U p1, U[] p2, U[,] p3, ref U p4, TestClass3<U, U> p5, ref TestClass3<U, U[]>[,] p6) { }
+ public static void Moo<M>(M p1, M[] p2, M[,] p3, ref M p4, TestClass3<M, M> p5, ref TestClass3<M, M[]>[,] p6) { }
+ public static void Moo<M, N>(T p1, T[] p2, T[,] p3, ref T p4, TestClass3<T, T> p5, ref TestClass3<T, T[]>[,] p6) { }
+ public static void Moo<M, N>(U p1, U[] p2, U[,] p3, ref U p4, TestClass3<U, U> p5, ref TestClass3<U, U[]>[,] p6) { }
+ public static void Moo<M, N>(M p1, M[] p2, M[,] p3, ref M p4, TestClass3<M, M> p5, ref TestClass3<M, M[]>[,] p6) { }
+ public static void Moo<M, N>(N p1, N[] p2, N[,] p3, ref N p4, TestClass3<N, N> p5, ref TestClass3<N, N[]>[,] p6) { }
+ }
+
+ private class TestClass4<T> where T: NoOneSubclasses, new()
+ {
+ public static void Moo<M>(int p1, int p2) where M : NoOneSubclassesThisEither { }
+ public static void Moo<N, O>(TestClass4<N> p1, int p2) where N : NoOneSubclasses, new() { }
+ public static void Moo<N, O>(O p1, int p2) where N : NoOneSubclasses, new() { }
+ }
+
+ private class NoOneSubclasses { }
+ private class NoOneSubclassesThisEither { }
+
+ private static void TestSignatureTypeInvariants(Type type)
+ {
+ Assert.True(type.IsSignatureType);
+ Assert.False(type.IsTypeDefinition);
+ Assert.False(type.IsGenericTypeDefinition);
+ Assert.NotNull(type.Name);
+ Assert.Null(type.FullName);
+ Assert.Null(type.AssemblyQualifiedName);
+ Assert.NotNull(type.ToString());
+ Assert.Equal(MemberTypes.TypeInfo, type.MemberType);
+ Assert.Same(type, type.UnderlyingSystemType);
+
+ // SignatureTypes don't override Equality/GetHashCode at this time, but they don't promise never to do so either.
+ // Thus, we'll only test the most basic behavior.
+ Assert.True(type.Equals((object)type));
+ Assert.True(type.Equals((Type)type));
+ Assert.False(type.Equals((object)null));
+ Assert.False(type.Equals((Type)null));
+ int _ = type.GetHashCode();
+
+ bool categorized = false;
+ if (type.IsArray)
+ {
+ Assert.False(categorized);
+ categorized = true;
+ Assert.True(type.HasElementType);
+ Assert.True(type.IsSZArray != type.IsVariableBoundArray);
+ Assert.Equal(type.GetElementType().ContainsGenericParameters, type.ContainsGenericParameters);
+ string elementTypeName = type.GetElementType().Name;
+ if (type.IsSZArray)
+ {
+ Assert.Equal(1, type.GetArrayRank());
+
+ Assert.Equal(elementTypeName + "[]", type.Name);
+ }
+ else
+ {
+ int rank = type.GetArrayRank();
+ Assert.True(rank >= 1);
+ if (rank == 1)
+ {
+ Assert.Equal(elementTypeName + "[*]", type.Name);
+ }
+ else
+ {
+ Assert.Equal(elementTypeName + "[" + new string(',', rank - 1) + "]", type.Name);
+ }
+ }
+ }
+
+ if (type.IsByRef)
+ {
+ Assert.False(categorized);
+ categorized = true;
+
+ Assert.True(type.HasElementType);
+ Assert.Equal(type.GetElementType().ContainsGenericParameters, type.ContainsGenericParameters);
+ string elementTypeName = type.GetElementType().Name;
+ Assert.Equal(elementTypeName + "&", type.Name);
+ }
+
+ if (type.IsPointer)
+ {
+ Assert.False(categorized);
+ categorized = true;
+
+ Assert.True(type.HasElementType);
+ Assert.Equal(type.GetElementType().ContainsGenericParameters, type.ContainsGenericParameters);
+ string elementTypeName = type.GetElementType().Name;
+ Assert.Equal(elementTypeName + "*", type.Name);
+ }
+
+ if (type.IsConstructedGenericType)
+ {
+ Assert.False(categorized);
+ categorized = true;
+
+ Assert.True(type.IsGenericType);
+ Assert.False(type.HasElementType);
+ Type genericTypeDefinition = type.GetGenericTypeDefinition();
+ Assert.Equal(genericTypeDefinition.IsByRefLike, type.IsByRefLike);
+ Assert.NotNull(genericTypeDefinition);
+ Assert.True(genericTypeDefinition.IsGenericTypeDefinition);
+ Type[] genericTypeArguments = type.GetGenericArguments();
+ Type[] genericTypeArgumentsClone = type.GetGenericArguments();
+ Assert.NotSame(genericTypeArguments, genericTypeArgumentsClone);
+ Type[] genericTypeArgumentsFromProperty = type.GenericTypeArguments;
+ Type[] genericTypeArgumentsFromPropertyClone = type.GenericTypeArguments;
+ Assert.NotSame(genericTypeArgumentsFromProperty, genericTypeArgumentsFromPropertyClone);
+ for (int i = 0; i < genericTypeArguments.Length; i++)
+ {
+ if (genericTypeArguments[i].IsSignatureType)
+ {
+ TestSignatureTypeInvariants(genericTypeArguments[i]);
+ }
+ }
+ Assert.Equal(genericTypeDefinition.Name, type.Name);
+ Assert.Equal(genericTypeDefinition.Namespace, type.Namespace);
+
+
+ bool containsGenericParameters = false;
+ for (int i = 0; i < genericTypeArguments.Length; i++)
+ {
+ containsGenericParameters = containsGenericParameters || genericTypeArguments[i].ContainsGenericParameters;
+ }
+ Assert.Equal(containsGenericParameters, type.ContainsGenericParameters);
+ }
+
+ if (type.IsGenericParameter)
+ {
+ Assert.False(categorized);
+ categorized = true;
+
+ Assert.False(type.HasElementType);
+ Assert.True(type.ContainsGenericParameters);
+ Assert.Null(type.Namespace);
+
+ int position = type.GenericParameterPosition;
+ Assert.True(position >= 0);
+ Assert.Equal("!!" + position, type.Name);
+ }
+
+ Assert.True(categorized);
+
+ if (type.HasElementType)
+ {
+ TestSignatureTypeInvariants(type.GetElementType());
+ Assert.Equal(type.GetElementType().Namespace, type.Namespace);
+ }
+ else
+ {
+ Assert.Null(type.GetElementType());
+ }
+
+ if (!type.IsConstructedGenericType)
+ {
+ Assert.Throws<InvalidOperationException>(() => type.GetGenericTypeDefinition());
+ Assert.Equal(0, type.GetGenericArguments().Length);
+ Assert.Equal(0, type.GenericTypeArguments.Length);
+ Assert.False(type.IsGenericType);
+ Assert.False(type.IsByRefLike);
+ }
+
+ if (!type.IsArray)
+ {
+ Assert.Throws<ArgumentException>(() => type.GetArrayRank());
+ }
+
+ if (!type.IsGenericParameter)
+ {
+ Assert.Throws<InvalidOperationException>(() => type.GenericParameterPosition);
+ }
+ }
+ }
+}
diff --git a/src/System.Runtime/tests/System/StringTests.netcoreapp.cs b/src/System.Runtime/tests/System/StringTests.netcoreapp.cs
index 9cb554590e..f2a5039afa 100644
--- a/src/System.Runtime/tests/System/StringTests.netcoreapp.cs
+++ b/src/System.Runtime/tests/System/StringTests.netcoreapp.cs
@@ -32,6 +32,64 @@ namespace System.Tests
Assert.Equal(expected, new string(span));
}
+ [Fact]
+ public static void Create_InvalidArguments_Throw()
+ {
+ AssertExtensions.Throws<ArgumentNullException>("action", () => string.Create(-1, 0, null));
+ AssertExtensions.Throws<ArgumentOutOfRangeException>("length", () => string.Create(-1, 0, (span, state) => { }));
+ }
+
+ [Fact]
+ public static void Create_Length0_ReturnsEmptyString()
+ {
+ bool actionInvoked = false;
+ Assert.Same(string.Empty, string.Create(0, 0, (span, state) => actionInvoked = true));
+ Assert.False(actionInvoked);
+ }
+
+ [Fact]
+ public static void Create_NullState_Allowed()
+ {
+ string result = string.Create(1, (object)null, (span, state) =>
+ {
+ span[0] = 'a';
+ Assert.Null(state);
+ });
+ Assert.Equal("a", result);
+ }
+
+ [Fact]
+ public static void Create_ClearsMemory()
+ {
+ const int Length = 10;
+ string result = string.Create(Length, (object)null, (span, state) =>
+ {
+ for (int i = 0; i < span.Length; i++)
+ {
+ Assert.Equal('\0', span[i]);
+ }
+ });
+ Assert.Equal(new string('\0', Length), result);
+ }
+
+ [Theory]
+ [InlineData("a")]
+ [InlineData("this is a test")]
+ [InlineData("\0\u8001\u8002\ufffd\u1234\ud800\udfff")]
+ public static void Create_ReturnsExpectedString(string expected)
+ {
+ char[] input = expected.ToCharArray();
+ string result = string.Create(input.Length, input, (span, state) =>
+ {
+ Assert.Same(input, state);
+ for (int i = 0; i < state.Length; i++)
+ {
+ span[i] = state[i];
+ }
+ });
+ Assert.Equal(expected, result);
+ }
+
[Theory]
// CurrentCulture
[InlineData("Hello", "ello", StringComparison.CurrentCulture, true)]
diff --git a/src/System.Runtime/tests/System/TimeSpanTests.cs b/src/System.Runtime/tests/System/TimeSpanTests.cs
index 61e136eb12..9efe0b0aeb 100644
--- a/src/System.Runtime/tests/System/TimeSpanTests.cs
+++ b/src/System.Runtime/tests/System/TimeSpanTests.cs
@@ -508,16 +508,71 @@ namespace System.Tests
public static IEnumerable<object[]> Parse_Valid_TestData()
{
+ // Space is trimmed before and after
yield return new object[] { " 12:24:02", null, new TimeSpan(0, 12, 24, 2, 0) };
+ yield return new object[] { "12:24:02 ", null, new TimeSpan(0, 12, 24, 2, 0) };
+ yield return new object[] { " 12:24:02 ", null, new TimeSpan(0, 12, 24, 2, 0) };
+ // Positive and negative 0 are both valid
+ yield return new object[] { "0", null, new TimeSpan(0, 0, 0, 0, 0) };
+
+ // HH:MM
yield return new object[] { "12:24", null, new TimeSpan(0, 12, 24, 0, 0) };
+
+ // HH:MM:SS
yield return new object[] { "12:24:02", null, new TimeSpan(0, 12, 24, 2, 0) };
+
+ // DD.HH:MM
+ yield return new object[] { "12.03:04", null, new TimeSpan(12, 3, 4, 0, 0) };
+
+ // HH:MM:SS.FF
+ yield return new object[] { "12:24:02.01", CultureInfo.InvariantCulture, new TimeSpan(0, 12, 24, 2, 10) };
+
+ // HH:MM:SS.FF w/ varying length zero prefixes on the fraction
+ yield return new object[] { "1:1:1.0", CultureInfo.InvariantCulture, new TimeSpan(1, 1, 1) };
+ yield return new object[] { "1:1:1.0000000", CultureInfo.InvariantCulture, new TimeSpan(1, 1, 1) };
+ yield return new object[] { "1:1:1.1", CultureInfo.InvariantCulture, new TimeSpan(0, 1, 1, 1, 100) };
+ yield return new object[] { "1:1:1.01", CultureInfo.InvariantCulture, new TimeSpan(0, 1, 1, 1, 10) };
+ yield return new object[] { "1:1:1.001", CultureInfo.InvariantCulture, new TimeSpan(0, 1, 1, 1, 1) };
+ yield return new object[] { "1:1:1.0001", CultureInfo.InvariantCulture, new TimeSpan(36610001000) };
+ yield return new object[] { "1:1:1.00001", CultureInfo.InvariantCulture, new TimeSpan(36610000100) };
+ yield return new object[] { "1:1:1.000001", CultureInfo.InvariantCulture, new TimeSpan(36610000010) };
+ yield return new object[] { "1:1:1.0000001", CultureInfo.InvariantCulture, new TimeSpan(36610000001) };
+ yield return new object[] { "1:1:1.00000001", CultureInfo.InvariantCulture, new TimeSpan(36610000001) };
+
+ // DD.HH:MM:SS
yield return new object[] { "1.12:24:02", null, new TimeSpan(1, 12, 24, 2, 0) };
+
+ // DD:HH:MM:SS
yield return new object[] { "1:12:24:02", null, new TimeSpan(1, 12, 24, 2, 0) };
- yield return new object[] { "1.12:24:02.999", null, new TimeSpan(1, 12, 24, 2, 999) };
- yield return new object[] { "-12:24:02", null, new TimeSpan(0, -12, -24, -2, 0) };
- yield return new object[] { "-1.12:24:02.999", null, new TimeSpan(-1, -12, -24, -2, -999) };
+ // DD.HH:MM:.FF
+ yield return new object[] { "01.23:45:.67", CultureInfo.InvariantCulture, new TimeSpan(1, 23, 45, 0, 670) };
+
+ // DD.HH.MM:SS.FFF
+ yield return new object[] { "1.12:24:02.999", CultureInfo.InvariantCulture, new TimeSpan(1, 12, 24, 2, 999) };
+
+ // HH:MM::.FF w/ varying length zero prefixes on the fraction
+ yield return new object[] { "1:1:.1", CultureInfo.InvariantCulture, new TimeSpan(36601000000) };
+ yield return new object[] { "1:1:.01", CultureInfo.InvariantCulture, new TimeSpan(36600100000) };
+ yield return new object[] { "1:1:.001", CultureInfo.InvariantCulture, new TimeSpan(36600010000) };
+ yield return new object[] { "1:1:.0001", CultureInfo.InvariantCulture, new TimeSpan(36600001000) };
+ yield return new object[] { "1:1:.00001", CultureInfo.InvariantCulture, new TimeSpan(36600000100) };
+ yield return new object[] { "1:1:.000001", CultureInfo.InvariantCulture, new TimeSpan(36600000010) };
+ yield return new object[] { "1:1:.0000001", CultureInfo.InvariantCulture, new TimeSpan(36600000001) };
+ yield return new object[] { "1:1:.00000001", CultureInfo.InvariantCulture, new TimeSpan(36600000001) };
+
+ // Just below overflow on various components
+ yield return new object[] { "10675199", null, new TimeSpan(9223371936000000000) };
+ yield return new object[] { "10675199:00:00", null, new TimeSpan(9223371936000000000) };
+ yield return new object[] { "10675199:02:00:00", null, new TimeSpan(9223372008000000000) };
+ yield return new object[] { "10675199:02:48:00", null, new TimeSpan(9223372036800000000) };
+ yield return new object[] { "10675199:02:48:05", null, new TimeSpan(9223372036850000000) };
+ yield return new object[] { "10675199:02:48:05.4775", CultureInfo.InvariantCulture, new TimeSpan(9223372036854775000) };
+ yield return new object[] { "00:00:59", null, new TimeSpan(0, 0, 59) };
+ yield return new object[] { "00:59:00", null, new TimeSpan(0, 59, 0) };
+ yield return new object[] { "23:00:00", null, new TimeSpan(23, 0, 0) };
+ yield return new object[] { "24:00:00", null, new TimeSpan(24, 0, 0, 0) };
// Croatia uses ',' in place of '.'
CultureInfo croatianCulture = new CultureInfo("hr-HR");
@@ -540,22 +595,50 @@ namespace System.Tests
Assert.Equal(expected, result);
Assert.Equal(expected, TimeSpan.Parse(input, provider));
+
+ // Also negate
+ if (!char.IsWhiteSpace(input[0]))
+ {
+ Assert.Equal(-expected, TimeSpan.Parse("-" + input, provider));
+ Assert.True(TimeSpan.TryParse("-" + input, provider, out result));
+ Assert.Equal(-expected, result);
+ }
}
public static IEnumerable<object[]> Parse_Invalid_TestData()
{
- yield return new object[] { null, null, typeof(ArgumentNullException) };
-
- yield return new object[] { "", null, typeof(FormatException) };
- yield return new object[] { "-", null, typeof(FormatException) };
- yield return new object[] { "garbage", null, typeof(FormatException) };
- yield return new object[] { "12/12/12", null, typeof(FormatException) };
-
- yield return new object[] { "1:1:1.99999999", null, typeof(OverflowException) };
-
- // Croatia uses ',' in place of '.'
- CultureInfo croatianCulture = new CultureInfo("hr-HR");
- yield return new object[] { "6:12:14:45.3448", croatianCulture, typeof(FormatException) };
+ // FormatExceptions
+ yield return new object[] { null, null, typeof(ArgumentNullException) }; // null input
+ yield return new object[] { "", null, typeof(FormatException) }; // empty input
+ yield return new object[] { "-", null, typeof(FormatException) }; // invalid sole separator
+ yield return new object[] { "garbage", null, typeof(FormatException) }; // garbage input
+ yield return new object[] { "12/12/12", null, typeof(FormatException) }; // unexpected separators
+ yield return new object[] { "00:", null, typeof(FormatException) }; // missing number at end
+ yield return new object[] { "00:00:-01", null, typeof(FormatException) }; // misplaced negative
+ yield return new object[] { "\012:34:56", null, typeof(FormatException) }; // null char at front
+ yield return new object[] { "1\02:34:56", null, typeof(FormatException) }; // null char in HH
+ yield return new object[] { "12\0:34:56", null, typeof(FormatException) }; // null char at end of component
+ yield return new object[] { "00:00::00", null, typeof(FormatException) }; // duplicated separator
+ yield return new object[] { "00:00:00:", null, typeof(FormatException) }; // extra separator at end
+ yield return new object[] { "00:00:00:00:00:00:00:00", null, typeof(FormatException) }; // too many components
+ yield return new object[] { "6:12:14:45.3448", new CultureInfo("hr-HR"), typeof(FormatException) }; // culture that uses ',' rather than '.'
+
+ // OverflowExceptions
+ yield return new object[] { "1:1:1.99999999", null, typeof(OverflowException) }; // overflowing fraction
+ yield return new object[] { "1:1:1.000000001", null, typeof(OverflowException) }; // too many leading zeroes in fraction
+ yield return new object[] { "2147483647", null, typeof(OverflowException) }; // overflowing value == int.MaxValue
+ yield return new object[] { "2147483648", null, typeof(OverflowException) }; // overflowing value == int.MaxValue + 1
+ yield return new object[] { "10675200", null, typeof(OverflowException) }; // overflowing number of days
+ yield return new object[] { "10675200:00:00", null, typeof(OverflowException) }; // overflowing number of hours
+ yield return new object[] { "10675199:03:00:00", null, typeof(OverflowException) }; // overflowing number of days + hours
+ yield return new object[] { "10675199:02:49:00", null, typeof(OverflowException) }; // overflowing number of days + hours + minutes
+ yield return new object[] { "10675199:02:48:06", null, typeof(OverflowException) }; // overflowing number of days + hours + minutes + seconds
+ yield return new object[] { "-10675199:02:48:06", null, typeof(OverflowException) }; // negative overflowing d + h + m + s
+ yield return new object[] { "10675199:02:48:05.4776", CultureInfo.InvariantCulture, typeof(OverflowException) }; // overflowing days + hours + minutes + seconds + fraction
+ yield return new object[] { "-10675199:02:48:05.4776", CultureInfo.InvariantCulture, typeof(OverflowException) }; // negative overflowing d + h + m + s +f
+ yield return new object[] { "00:00:60", null, typeof(OverflowException) }; // overflowing seconds
+ yield return new object[] { "00:60:00", null, typeof(OverflowException) }; // overflowing minutes
+ yield return new object[] { "24:00", null, typeof(OverflowException) }; // overflowing hours
}
[Theory]
@@ -579,20 +662,47 @@ namespace System.Tests
public static IEnumerable<object[]> ParseExact_Valid_TestData()
{
// Standard timespan formats 'c', 'g', 'G'
- yield return new object[] { "12:24:02", "c", new TimeSpan(0, 12, 24, 2) };
- yield return new object[] { "1.12:24:02", "c", new TimeSpan(1, 12, 24, 2) };
- yield return new object[] { "-01.07:45:16.999", "c", new TimeSpan(1, 7, 45, 16, 999).Negate() };
- yield return new object[] { "12:24:02", "g", new TimeSpan(0, 12, 24, 2) };
- yield return new object[] { "1:12:24:02", "g", new TimeSpan(1, 12, 24, 2) };
- yield return new object[] { "-01:07:45:16.999", "g", new TimeSpan(1, 7, 45, 16, 999).Negate() };
- yield return new object[] { "1:12:24:02.243", "G", new TimeSpan(1, 12, 24, 2, 243) };
- yield return new object[] { "-01:07:45:16.999", "G", new TimeSpan(1, 7, 45, 16, 999).Negate() };
+ foreach (string constFormat in new[] { "c", "t", "T" }) // "t" and "T" are the same as "c"
+ {
+ yield return new object[] { "12:24:02", constFormat, new TimeSpan(0, 12, 24, 2) }; // HH:MM:SS
+ yield return new object[] { "1.12:24:02", constFormat, new TimeSpan(1, 12, 24, 2) }; // DD.HH:MM:SS
+ yield return new object[] { "-01.07:45:16.999", constFormat, -new TimeSpan(1, 7, 45, 16, 999) }; // -DD.HH:MM:SS.FFF
+ }
+
+ // "g"
+ yield return new object[] { "12", "g", new TimeSpan(12, 0, 0, 0) }; // days
+ yield return new object[] { "-12", "g", new TimeSpan(-12, 0, 0, 0) }; // negative days
+ yield return new object[] { "12:34", "g", new TimeSpan(12, 34, 00) }; // HH:MM
+ yield return new object[] { "-12:34", "g", -new TimeSpan(12, 34, 00) }; // -HH:MM
+ yield return new object[] { "1:2:.3", "g", new TimeSpan(0, 1, 2, 0, 300) }; // HH:MM:.FF
+ yield return new object[] { "-1:2:.3", "g", -new TimeSpan(0, 1, 2, 0, 300) }; // -HH:MM:.FF
+ yield return new object[] { "12:24:02", "g", new TimeSpan(0, 12, 24, 2) }; // HH:MM:SS
+ yield return new object[] { "12:24:02.123", "g", new TimeSpan(0, 12, 24, 2, 123) }; // HH:MM:SS.FFF
+ yield return new object[] { "-12:24:02.123", "g", -new TimeSpan(0, 12, 24, 2, 123) }; // -HH:MM:SS.FFF
+ yield return new object[] { "1:2:3:.4", "g", new TimeSpan(1, 2, 3, 0, 400) }; // DD:HH:MM:.FF
+ yield return new object[] { "-1:2:3:.4", "g", -new TimeSpan(1, 2, 3, 0, 400) }; // -DD:HH:MM:.FF
+ yield return new object[] { "1:12:24:02", "g", new TimeSpan(1, 12, 24, 2) }; // DD:HH:MM:SS
+ yield return new object[] { "-01:07:45:16.999", "g", -new TimeSpan(1, 7, 45, 16, 999) }; // -DD:HH:MM:SS.FFF
+
+ // "G"
+ yield return new object[] { "1:12:24:02.243", "G", new TimeSpan(1, 12, 24, 2, 243) }; // DD:MM:HH:SS.FFF
+ yield return new object[] { "-01:07:45:16.999", "G", -new TimeSpan(1, 7, 45, 16, 999) }; // -DD:MM:HH:SS.FFF
// Custom timespan formats
yield return new object[] { "12.23:32:43", @"dd\.h\:m\:s", new TimeSpan(12, 23, 32, 43) };
yield return new object[] { "012.23:32:43.893", @"ddd\.h\:m\:s\.fff", new TimeSpan(12, 23, 32, 43, 893) };
yield return new object[] { "12.05:02:03", @"d\.hh\:mm\:ss", new TimeSpan(12, 5, 2, 3) };
yield return new object[] { "12:34 minutes", @"mm\:ss\ \m\i\n\u\t\e\s", new TimeSpan(0, 12, 34) };
+ yield return new object[] { "12:34 minutes", @"mm\:ss\ ""minutes""", new TimeSpan(0, 12, 34) };
+ yield return new object[] { "12:34 minutes", @"mm\:ss\ 'minutes'", new TimeSpan(0, 12, 34) };
+ yield return new object[] { "678", "fff", new TimeSpan(0, 0, 0, 0, 678) };
+ yield return new object[] { "678", "FFF", new TimeSpan(0, 0, 0, 0, 678) };
+ yield return new object[] { "3", "%d", new TimeSpan(3, 0, 0, 0, 0) };
+ yield return new object[] { "3", "%h", new TimeSpan(3, 0, 0) };
+ yield return new object[] { "3", "%m", new TimeSpan(0, 3, 0) };
+ yield return new object[] { "3", "%s", new TimeSpan(0, 0, 3) };
+ yield return new object[] { "3", "%f", new TimeSpan(0, 0, 0, 0, 300) };
+ yield return new object[] { "3", "%F", new TimeSpan(0, 0, 0, 0, 300) };
}
[Theory]
@@ -601,30 +711,49 @@ namespace System.Tests
{
TimeSpan result;
Assert.Equal(expected, TimeSpan.ParseExact(input, format, new CultureInfo("en-US")));
+ Assert.Equal(expected, TimeSpan.ParseExact(input, new[] { format }, new CultureInfo("en-US")));
Assert.True(TimeSpan.TryParseExact(input, format, new CultureInfo("en-US"), out result));
Assert.Equal(expected, result);
- // TimeSpanStyles is interpreted only for custom formats
- if (format != "c" && format != "g" && format != "G")
+ Assert.True(TimeSpan.TryParseExact(input, new[] { format }, new CultureInfo("en-US"), out result));
+ Assert.Equal(expected, result);
+
+ if (format != "c" && format != "t" && format != "T" && format != "g" && format != "G")
{
+ // TimeSpanStyles is interpreted only for custom formats
Assert.Equal(expected.Negate(), TimeSpan.ParseExact(input, format, new CultureInfo("en-US"), TimeSpanStyles.AssumeNegative));
Assert.True(TimeSpan.TryParseExact(input, format, new CultureInfo("en-US"), TimeSpanStyles.AssumeNegative, out result));
Assert.Equal(expected.Negate(), result);
}
+ else
+ {
+ // Inputs that can be parsed in standard formats with ParseExact should also be parsable with Parse
+ Assert.Equal(expected, TimeSpan.Parse(input, CultureInfo.InvariantCulture));
+
+ Assert.True(TimeSpan.TryParse(input, CultureInfo.InvariantCulture, out result));
+ Assert.Equal(expected, result);
+ }
}
public static IEnumerable<object[]> ParseExact_Invalid_TestData()
{
yield return new object[] { null, "c", typeof(ArgumentNullException) };
-
+ yield return new object[] { "00:00:00", null, typeof(ArgumentNullException) };
yield return new object[] { "", "c", typeof(FormatException) };
yield return new object[] { "-", "c", typeof(FormatException) };
yield return new object[] { "garbage", "c", typeof(FormatException) };
// Standard timespan formats 'c', 'g', 'G'
yield return new object[] { "24:24:02", "c", typeof(OverflowException) };
+ yield return new object[] { "1:60:02", "c", typeof(OverflowException) };
+ yield return new object[] { "1:59:60", "c", typeof(OverflowException) };
+ yield return new object[] { "1.24:59:02", "c", typeof(OverflowException) };
+ yield return new object[] { "1.2:60:02", "c", typeof(OverflowException) };
+ yield return new object[] { "1?59:02", "c", typeof(FormatException) };
+ yield return new object[] { "1:59?02", "c", typeof(FormatException) };
+ yield return new object[] { "1:59:02?123", "c", typeof(FormatException) };
yield return new object[] { "1:12:24:02", "c", typeof(FormatException) };
yield return new object[] { "12:61:02", "g", typeof(OverflowException) };
yield return new object[] { "1.12:24:02", "g", typeof(FormatException) };
@@ -635,6 +764,31 @@ namespace System.Tests
yield return new object[] { "12.35:32:43", @"dd\.h\:m\:s", typeof(OverflowException) };
yield return new object[] { "12.5:2:3", @"d\.hh\:mm\:ss", typeof(FormatException) };
yield return new object[] { "12.5:2", @"d\.hh\:mm\:ss", typeof(FormatException) };
+ yield return new object[] { "678", @"ffff", typeof(FormatException) };
+ yield return new object[] { "00000012", @"FFFFFFFF", typeof(FormatException) };
+ yield return new object[] { "12:034:56", @"hh\mm\ss", typeof(FormatException) };
+ yield return new object[] { "12:34:056", @"hh\mm\ss", typeof(FormatException) };
+ yield return new object[] { "12:34 minutes", @"mm\:ss\ ""minutes", typeof(FormatException) };
+ yield return new object[] { "12:34 minutes", @"mm\:ss\ 'minutes", typeof(FormatException) };
+ yield return new object[] { "12:34 mints", @"mm\:ss\ ""minutes""", typeof(FormatException) };
+ yield return new object[] { "12:34 mints", @"mm\:ss\ 'minutes'", typeof(FormatException) };
+ yield return new object[] { "1", @"d%", typeof(FormatException) };
+ yield return new object[] { "1", @"%%d", typeof(FormatException) };
+ yield return new object[] { "12:34:56", @"hhh\:mm\:ss", typeof(FormatException) };
+ yield return new object[] { "12:34:56", @"hh\:hh\:ss", typeof(FormatException) };
+ yield return new object[] { "123:34:56", @"hh\:mm\:ss", typeof(FormatException) };
+ yield return new object[] { "12:34:56", @"hh\:mmm\:ss", typeof(FormatException) };
+ yield return new object[] { "12:34:56", @"hh\:mm\:mm", typeof(FormatException) };
+ yield return new object[] { "12:345:56", @"hh\:mm\:ss", typeof(FormatException) };
+ yield return new object[] { "12:34:56", @"hh\:mm\:sss", typeof(FormatException) };
+ yield return new object[] { "12:34:56", @"hh\:ss\:ss", typeof(FormatException) };
+ yield return new object[] { "12:45", @"ff:ff", typeof(FormatException) };
+ yield return new object[] { "000000123", @"ddddddddd", typeof(FormatException) };
+ yield return new object[] { "12:34:56", @"dd:dd:hh", typeof(FormatException) };
+ yield return new object[] { "123:45", @"dd:hh", typeof(FormatException) };
+ yield return new object[] { "12:34", @"dd:vv", typeof(FormatException) };
+ yield return new object[] { "00:00:00", "", typeof(FormatException) };
+ yield return new object[] { "12.5:2", @"V", typeof(FormatException) };
}
[Theory]
@@ -646,6 +800,21 @@ namespace System.Tests
TimeSpan result;
Assert.False(TimeSpan.TryParseExact(input, format, new CultureInfo("en-US"), out result));
Assert.Equal(TimeSpan.Zero, result);
+
+ Assert.False(TimeSpan.TryParseExact(input, new[] { format }, new CultureInfo("en-US"), out result));
+ Assert.Equal(TimeSpan.Zero, result);
+ }
+
+ [Fact]
+ public static void ParseExactMultiple_InvalidNullEmptyFormats()
+ {
+ TimeSpan result;
+
+ AssertExtensions.Throws<ArgumentNullException>("formats", () => TimeSpan.ParseExact("12:34:56", (string[])null, null));
+ Assert.False(TimeSpan.TryParseExact("12:34:56", (string[])null, null, out result));
+
+ Assert.Throws<FormatException>(() => TimeSpan.ParseExact("12:34:56", new string[0], null));
+ Assert.False(TimeSpan.TryParseExact("12:34:56", new string[0], null, out result));
}
public static IEnumerable<object[]> Subtract_TestData()
@@ -677,38 +846,42 @@ namespace System.Tests
Assert.Throws<OverflowException>(() => TimeSpan.MinValue - new TimeSpan(1)); // Result < TimeSpan.MinValue
}
- [Fact]
- public static void ToStringTest()
- {
- var timeSpan1 = new TimeSpan(1, 2, 3);
- var timeSpan2 = new TimeSpan(1, 2, 3);
- var timeSpan3 = new TimeSpan(1, 2, 4);
-
- var timeSpan4 = new TimeSpan(1, 2, 3, 4);
- var timeSpan5 = new TimeSpan(1, 2, 3, 4);
- var timeSpan6 = new TimeSpan(1, 2, 3, 5);
-
- var timeSpan7 = new TimeSpan(1, 2, 3, 4, 5);
- var timeSpan8 = new TimeSpan(1, 2, 3, 4, 5);
- var timeSpan9 = new TimeSpan(1, 2, 3, 4, 6);
-
- Assert.Equal(timeSpan1.ToString(), timeSpan2.ToString());
- Assert.Equal(timeSpan1.ToString("c"), timeSpan2.ToString("c"));
- Assert.Equal(timeSpan1.ToString("c", null), timeSpan2.ToString("c", null));
- Assert.NotEqual(timeSpan1.ToString(), timeSpan3.ToString());
- Assert.NotEqual(timeSpan1.ToString(), timeSpan4.ToString());
- Assert.NotEqual(timeSpan1.ToString(), timeSpan7.ToString());
-
- Assert.Equal(timeSpan4.ToString(), timeSpan5.ToString());
- Assert.Equal(timeSpan4.ToString("c"), timeSpan5.ToString("c"));
- Assert.Equal(timeSpan4.ToString("c", null), timeSpan5.ToString("c", null));
- Assert.NotEqual(timeSpan4.ToString(), timeSpan6.ToString());
- Assert.NotEqual(timeSpan4.ToString(), timeSpan7.ToString());
-
- Assert.Equal(timeSpan7.ToString(), timeSpan8.ToString());
- Assert.Equal(timeSpan7.ToString("c"), timeSpan8.ToString("c"));
- Assert.Equal(timeSpan7.ToString("c", null), timeSpan8.ToString("c", null));
- Assert.NotEqual(timeSpan7.ToString(), timeSpan9.ToString());
+ public static IEnumerable<object[]> ToString_MemberData()
+ {
+ var input = new TimeSpan(123456789101112);
+
+ yield return new object[] { input, null, "142.21:21:18.9101112" };
+ yield return new object[] { input, "c", "142.21:21:18.9101112" };
+ yield return new object[] { input, "t", "142.21:21:18.9101112" };
+ yield return new object[] { input, "T", "142.21:21:18.9101112" };
+ yield return new object[] { input, "g", "142:21:21:18.9101112" };
+ yield return new object[] { input, "%d", "142" };
+ yield return new object[] { input, "dd", "142" };
+ yield return new object[] { input, "%h", "21" };
+ yield return new object[] { input, "hh", "21" };
+ yield return new object[] { input, "%m", "21" };
+ yield return new object[] { input, "mm", "21" };
+ yield return new object[] { input, "%s", "18" };
+ yield return new object[] { input, "ss", "18" };
+ yield return new object[] { input, "%f", "9" };
+ yield return new object[] { input, "ff", "91" };
+ yield return new object[] { input, "fff", "910" };
+ yield return new object[] { input, "ffff", "9101" };
+ yield return new object[] { input, "fffff", "91011" };
+ yield return new object[] { input, "ffffff", "910111" };
+ yield return new object[] { input, "fffffff", "9101112" };
+ yield return new object[] { input, "dd\\.ss", "142.18" };
+ }
+
+ [Theory]
+ [MemberData(nameof(ToString_MemberData))]
+ public static void ToString_Valid(TimeSpan input, string format, string expected)
+ {
+ Assert.Equal(expected, input.ToString(format, CultureInfo.InvariantCulture));
+ if (format == null)
+ {
+ Assert.Equal(expected, input.ToString());
+ }
}
[Fact]
diff --git a/src/System.Runtime/tests/System/TimeSpanTests.netcoreapp.cs b/src/System.Runtime/tests/System/TimeSpanTests.netcoreapp.cs
index f4c6ef025f..7afccf4d8e 100644
--- a/src/System.Runtime/tests/System/TimeSpanTests.netcoreapp.cs
+++ b/src/System.Runtime/tests/System/TimeSpanTests.netcoreapp.cs
@@ -3,6 +3,7 @@
// See the LICENSE file in the project root for more information.
using System.Collections.Generic;
+using System.Globalization;
using Xunit;
namespace System.Tests
@@ -109,5 +110,128 @@ namespace System.Tests
{
AssertExtensions.Throws<ArgumentException>("divisor", () => TimeSpan.FromDays(1).Divide(double.NaN));
}
+
+ [Theory]
+ [MemberData(nameof(Parse_Valid_TestData))]
+ public static void Parse_Span(string inputString, IFormatProvider provider, TimeSpan expected)
+ {
+ ReadOnlySpan<char> input = inputString.AsReadOnlySpan();
+ TimeSpan result;
+
+ Assert.Equal(expected, TimeSpan.Parse(input, provider));
+ Assert.True(TimeSpan.TryParse(input, out result, provider));
+ Assert.Equal(expected, result);
+
+ // Also negate
+ if (!char.IsWhiteSpace(input[0]))
+ {
+ input = ("-" + inputString).AsReadOnlySpan();
+ expected = -expected;
+
+ Assert.Equal(expected, TimeSpan.Parse(input, provider));
+ Assert.True(TimeSpan.TryParse(input, out result, provider));
+ Assert.Equal(expected, result);
+ }
+ }
+
+ [Theory]
+ [MemberData(nameof(Parse_Invalid_TestData))]
+ public static void Parse_Span_Invalid(string inputString, IFormatProvider provider, Type exceptionType)
+ {
+ if (inputString != null)
+ {
+ Assert.Throws(exceptionType, () => TimeSpan.Parse(inputString.AsReadOnlySpan(), provider));
+ Assert.False(TimeSpan.TryParse(inputString.AsReadOnlySpan(), out TimeSpan result, provider));
+ Assert.Equal(TimeSpan.Zero, result);
+ }
+ }
+
+
+
+ [Theory]
+ [MemberData(nameof(ParseExact_Valid_TestData))]
+ public static void ParseExact_Span_Valid(string inputString, string format, TimeSpan expected)
+ {
+ ReadOnlySpan<char> input = inputString.AsReadOnlySpan();
+
+ TimeSpan result;
+ Assert.Equal(expected, TimeSpan.ParseExact(input, format, new CultureInfo("en-US")));
+ Assert.Equal(expected, TimeSpan.ParseExact(input, new[] { format }, new CultureInfo("en-US")));
+
+ Assert.True(TimeSpan.TryParseExact(input, format, new CultureInfo("en-US"), out result));
+ Assert.Equal(expected, result);
+
+ Assert.True(TimeSpan.TryParseExact(input, new[] { format }, new CultureInfo("en-US"), out result));
+ Assert.Equal(expected, result);
+
+ if (format != "c" && format != "t" && format != "T" && format != "g" && format != "G")
+ {
+ // TimeSpanStyles is interpreted only for custom formats
+ Assert.Equal(expected.Negate(), TimeSpan.ParseExact(input, format, new CultureInfo("en-US"), TimeSpanStyles.AssumeNegative));
+
+ Assert.True(TimeSpan.TryParseExact(input, format, new CultureInfo("en-US"), out result, TimeSpanStyles.AssumeNegative));
+ Assert.Equal(expected.Negate(), result);
+ }
+ else
+ {
+ // Inputs that can be parsed in standard formats with ParseExact should also be parsable with Parse
+ Assert.Equal(expected, TimeSpan.Parse(input, CultureInfo.InvariantCulture));
+
+ Assert.True(TimeSpan.TryParse(input, out result, CultureInfo.InvariantCulture));
+ Assert.Equal(expected, result);
+ }
+ }
+
+ [Theory]
+ [MemberData(nameof(ParseExact_Invalid_TestData))]
+ public static void ParseExactTest__Span_Invalid(string inputString, string format, Type exceptionType)
+ {
+ if (inputString != null)
+ {
+ Assert.Throws(exceptionType, () => TimeSpan.ParseExact(inputString.AsReadOnlySpan(), format, new CultureInfo("en-US")));
+
+ TimeSpan result;
+ Assert.False(TimeSpan.TryParseExact(inputString.AsReadOnlySpan(), format, new CultureInfo("en-US"), out result));
+ Assert.Equal(TimeSpan.Zero, result);
+
+ Assert.False(TimeSpan.TryParseExact(inputString.AsReadOnlySpan(), new[] { format }, new CultureInfo("en-US"), out result));
+ Assert.Equal(TimeSpan.Zero, result);
+ }
+ }
+
+ [Fact]
+ public static void ParseExactMultiple_Span_InvalidNullEmptyFormats()
+ {
+ TimeSpan result;
+
+ AssertExtensions.Throws<ArgumentNullException>("formats", () => TimeSpan.ParseExact("12:34:56".AsReadOnlySpan(), (string[])null, null));
+ Assert.False(TimeSpan.TryParseExact("12:34:56".AsReadOnlySpan(), (string[])null, null, out result));
+
+ Assert.Throws<FormatException>(() => TimeSpan.ParseExact("12:34:56".AsReadOnlySpan(), new string[0], null));
+ Assert.False(TimeSpan.TryParseExact("12:34:56".AsReadOnlySpan(), new string[0], null, out result));
+ }
+
+ [Theory]
+ [MemberData(nameof(ToString_MemberData))]
+ public static void TryFormat_Valid(TimeSpan input, string format, string expected)
+ {
+ int charsWritten;
+ Span<char> dst;
+
+ dst = new char[expected.Length - 1];
+ Assert.False(input.TryFormat(dst, out charsWritten, format, CultureInfo.InvariantCulture));
+ Assert.Equal(0, charsWritten);
+
+ dst = new char[expected.Length];
+ Assert.True(input.TryFormat(dst, out charsWritten, format, CultureInfo.InvariantCulture));
+ Assert.Equal(expected.Length, charsWritten);
+ Assert.Equal(expected, new string(dst));
+
+ dst = new char[expected.Length + 1];
+ Assert.True(input.TryFormat(dst, out charsWritten, format, CultureInfo.InvariantCulture));
+ Assert.Equal(expected.Length, charsWritten);
+ Assert.Equal(expected, new string(dst.Slice(0, dst.Length - 1)));
+ Assert.Equal(0, dst[dst.Length - 1]);
+ }
}
}
diff --git a/src/System.Runtime/tests/System/TypeTests.netcoreapp.cs b/src/System.Runtime/tests/System/TypeTests.netcoreapp.cs
index 5d8bb59277..521ead10e9 100644
--- a/src/System.Runtime/tests/System/TypeTests.netcoreapp.cs
+++ b/src/System.Runtime/tests/System/TypeTests.netcoreapp.cs
@@ -233,8 +233,7 @@ namespace System.Tests
}
}
- [IsByRefLike]
- private struct ByRefLikeStruct
+ private ref struct ByRefLikeStruct
{
public ByRefLikeStruct(int dummy)
{
diff --git a/src/System.Runtime/tests/System/UnitySerializationHolderTests.cs b/src/System.Runtime/tests/System/UnitySerializationHolderTests.cs
new file mode 100644
index 0000000000..ab28b42bad
--- /dev/null
+++ b/src/System.Runtime/tests/System/UnitySerializationHolderTests.cs
@@ -0,0 +1,20 @@
+// 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.Serialization.Formatters.Tests;
+using Xunit;
+
+namespace System.Tests
+{
+ public class UnitySerializationHolderTests
+ {
+ [Fact]
+ public void UnitySerializationHolderWithAssemblySingleton()
+ {
+ const string UnitySerializationHolderAssemblyBase64String = "AAEAAAD/////AQAAAAAAAAAEAQAAAB9TeXN0ZW0uVW5pdHlTZXJpYWxpemF0aW9uSG9sZGVyAwAAAAREYXRhCVVuaXR5VHlwZQxBc3NlbWJseU5hbWUBAAEIBgIAAABLbXNjb3JsaWIsIFZlcnNpb249NC4wLjAuMCwgQ3VsdHVyZT1uZXV0cmFsLCBQdWJsaWNLZXlUb2tlbj1iNzdhNWM1NjE5MzRlMDg5BgAAAAkCAAAACw==";
+ AssertExtensions.ThrowsIf<ArgumentException>(!PlatformDetection.IsFullFramework,
+ () => BinaryFormatterHelpers.FromBase64String(UnitySerializationHolderAssemblyBase64String));
+ }
+ }
+}
diff --git a/src/System.Runtime/tests/System/VersionTests.netcoreapp.cs b/src/System.Runtime/tests/System/VersionTests.netcoreapp.cs
new file mode 100644
index 0000000000..95dea7888d
--- /dev/null
+++ b/src/System.Runtime/tests/System/VersionTests.netcoreapp.cs
@@ -0,0 +1,82 @@
+// 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 partial class VersionTests
+ {
+ [Theory]
+ [MemberData(nameof(Parse_Valid_TestData))]
+ public static void Parse_Span_ValidInput_ReturnsExpected(string input, Version expected)
+ {
+ if (input == null)
+ {
+ return;
+ }
+
+ Assert.Equal(expected, Version.Parse(input.AsReadOnlySpan()));
+
+ Assert.True(Version.TryParse(input.AsReadOnlySpan(), out Version version));
+ Assert.Equal(expected, version);
+ }
+
+ [Theory]
+ [MemberData(nameof(Parse_Invalid_TestData))]
+ public static void Parse_Span_InvalidInput_ThrowsException(string input, Type exceptionType)
+ {
+ if (input == null)
+ {
+ return;
+ }
+
+ Assert.Throws(exceptionType, () => Version.Parse(input.AsReadOnlySpan()));
+
+ Assert.False(Version.TryParse(input.AsReadOnlySpan(), out Version version));
+ Assert.Null(version);
+ }
+
+ [Theory]
+ [MemberData(nameof(ToString_TestData))]
+ public static void TryFormat_Invoke_WritesExpected(Version version, string[] expected)
+ {
+ char[] dest;
+ int charsWritten;
+
+ for (int i = 0; i < expected.Length; i++)
+ {
+ if (i > 0)
+ {
+ // Too small
+ dest = new char[expected[i].Length - 1];
+ Assert.False(version.TryFormat(dest, i, out charsWritten));
+ Assert.Equal(0, charsWritten);
+ }
+
+ // Just right
+ dest = new char[expected[i].Length];
+ Assert.True(version.TryFormat(dest, i, out charsWritten));
+ Assert.Equal(expected[i].Length, charsWritten);
+ Assert.Equal(expected[i], new string(dest, 0, charsWritten));
+
+ // More than needed
+ dest = new char[expected[i].Length + 10];
+ Assert.True(version.TryFormat(dest, i, out charsWritten));
+ Assert.Equal(expected[i].Length, charsWritten);
+ Assert.Equal(expected[i], new string(dest, 0, charsWritten));
+ }
+
+ int maxFieldCount = expected.Length - 1;
+ dest = new char[expected[maxFieldCount].Length];
+ Assert.True(version.TryFormat(dest, out charsWritten));
+ Assert.Equal(expected[maxFieldCount].Length, charsWritten);
+ Assert.Equal(expected[maxFieldCount], new string(dest, 0, charsWritten));
+
+ dest = new char[0];
+ AssertExtensions.Throws<ArgumentException>("fieldCount", () => version.TryFormat(dest, -1, out charsWritten)); // Index < 0
+ AssertExtensions.Throws<ArgumentException>("fieldCount", () => version.TryFormat(dest, maxFieldCount + 1, out charsWritten)); // Index > version.fieldCount
+ }
+ }
+}
diff --git a/src/System.Security.AccessControl/ref/System.Security.AccessControl.csproj b/src/System.Security.AccessControl/ref/System.Security.AccessControl.csproj
index 47bdd6b6d3..60b67fc31b 100644
--- a/src/System.Security.AccessControl/ref/System.Security.AccessControl.csproj
+++ b/src/System.Security.AccessControl/ref/System.Security.AccessControl.csproj
@@ -4,6 +4,9 @@
<PropertyGroup>
<ProjectGuid>{F80C478C-48EE-46A5-89C4-EE0CFB23A14F}</ProjectGuid>
<IsPartialFacadeAssembly Condition="'$(TargetGroup)' == 'netfx'">true</IsPartialFacadeAssembly>
+ <!-- Must match version supported by frameworks which support 4.1.* inbox.
+ Can be removed when API is added and this assembly is versioned to 4.2.* -->
+ <AssemblyVersion Condition="'$(TargetsNetFx)' != 'true'">4.1.1.0</AssemblyVersion>
</PropertyGroup>
<PropertyGroup Condition="'$(Configuration)|$(Platform)' == 'netfx-Debug|AnyCPU'" />
<PropertyGroup Condition="'$(Configuration)|$(Platform)' == 'netfx-Release|AnyCPU'" />
diff --git a/src/System.Security.Cryptography.Cng/ref/System.Security.Cryptography.Cng.csproj b/src/System.Security.Cryptography.Cng/ref/System.Security.Cryptography.Cng.csproj
index 5e9e9935ef..2eb01023c3 100644
--- a/src/System.Security.Cryptography.Cng/ref/System.Security.Cryptography.Cng.csproj
+++ b/src/System.Security.Cryptography.Cng/ref/System.Security.Cryptography.Cng.csproj
@@ -6,6 +6,9 @@
<ProjectGuid>{9FD12550-3A7C-49D3-9A1E-C4B7410989DD}</ProjectGuid>
<DefineConstants Condition="'$(TargetGroup)' == 'uap' Or '$(TargeGroup)' == 'netcoreapp'">$(DefineConstants);FEATURE_HASHDATA</DefineConstants>
<IsPartialFacadeAssembly Condition="'$(TargetGroup)' == 'netfx' OR '$(TargetGroup)' == 'net462' OR '$(TargetGroup)' == 'net47'">true</IsPartialFacadeAssembly>
+ <!-- Must match version supported by frameworks which support 4.3.* inbox.
+ Can be removed when API is added and this assembly is versioned to 4.4.* -->
+ <AssemblyVersion Condition="'$(TargetsNetFx)' != 'true'">4.3.1.0</AssemblyVersion>
</PropertyGroup>
<PropertyGroup Condition="'$(Configuration)|$(Platform)' == 'netcoreapp-Debug|AnyCPU'" />
<PropertyGroup Condition="'$(Configuration)|$(Platform)' == 'netcoreapp-Release|AnyCPU'" />
diff --git a/src/System.Security.Cryptography.Xml/ref/System.Security.Cryptography.Xml.cs b/src/System.Security.Cryptography.Xml/ref/System.Security.Cryptography.Xml.cs
index 19967e36c9..d97dcfc823 100644
--- a/src/System.Security.Cryptography.Xml/ref/System.Security.Cryptography.Xml.cs
+++ b/src/System.Security.Cryptography.Xml/ref/System.Security.Cryptography.Xml.cs
@@ -116,6 +116,8 @@ namespace System.Security.Cryptography.Xml
public const string XmlEncTripleDESUrl = "http://www.w3.org/2001/04/xmlenc#tripledes-cbc";
public EncryptedXml() { }
public EncryptedXml(System.Xml.XmlDocument document) { }
+ public EncryptedXml(System.Xml.XmlDocument document, System.Security.Policy.Evidence evidence) { }
+ public System.Security.Policy.Evidence DocumentEvidence { get { throw null; } set { } }
public System.Text.Encoding Encoding { get { throw null; } set { } }
public System.Security.Cryptography.CipherMode Mode { get { throw null; } set { } }
public System.Security.Cryptography.PaddingMode Padding { get { throw null; } set { } }
diff --git a/src/System.Security.Cryptography.Xml/ref/System.Security.Cryptography.Xml.csproj b/src/System.Security.Cryptography.Xml/ref/System.Security.Cryptography.Xml.csproj
index 8193ab2888..47069c0130 100644
--- a/src/System.Security.Cryptography.Xml/ref/System.Security.Cryptography.Xml.csproj
+++ b/src/System.Security.Cryptography.Xml/ref/System.Security.Cryptography.Xml.csproj
@@ -9,7 +9,10 @@
<PropertyGroup Condition="'$(Configuration)|$(Platform)' == 'netfx-Release|AnyCPU'" />
<PropertyGroup Condition="'$(Configuration)|$(Platform)' == 'netstandard-Debug|AnyCPU'" />
<PropertyGroup Condition="'$(Configuration)|$(Platform)' == 'netstandard-Release|AnyCPU'" />
- <ItemGroup Condition="'$(IsPartialFacadeAssembly)' == 'true'">
+ <ItemGroup Condition="'$(IsPartialFacadeAssembly)' != 'true'">
+ <ProjectReference Include="..\..\System.Security.Permissions\ref\System.Security.Permissions.csproj" />
+ </ItemGroup>
+ <ItemGroup Condition="'$(IsPartialFacadeAssembly)' == 'true'">
<Reference Include="mscorlib" />
<Reference Include="System" />
<Reference Include="System.Core" />
@@ -20,4 +23,4 @@
<Compile Include="System.Security.Cryptography.Xml.cs" />
</ItemGroup>
<Import Project="$([MSBuild]::GetDirectoryNameOfFileAbove($(MSBuildThisFileDirectory), dir.targets))\dir.targets" />
-</Project> \ No newline at end of file
+</Project>
diff --git a/src/System.Security.Cryptography.Xml/src/System.Security.Cryptography.Xml.csproj b/src/System.Security.Cryptography.Xml/src/System.Security.Cryptography.Xml.csproj
index e951a362e2..c16b4e66a3 100644
--- a/src/System.Security.Cryptography.Xml/src/System.Security.Cryptography.Xml.csproj
+++ b/src/System.Security.Cryptography.Xml/src/System.Security.Cryptography.Xml.csproj
@@ -107,6 +107,7 @@
<Reference Include="System.Security.Cryptography.Encoding" />
<Reference Include="System.Security.Cryptography.Primitives" />
<Reference Include="System.Security.Cryptography.X509Certificates" />
+ <Reference Include="System.Security.Permissions" />
<Reference Include="System.Text.Encoding.Extensions" />
<Reference Include="System.Xml.ReaderWriter" />
<Reference Include="System.Xml.XPath" />
@@ -117,4 +118,4 @@
<Reference Include="System.Security" />
</ItemGroup>
<Import Project="$([MSBuild]::GetDirectoryNameOfFileAbove($(MSBuildThisFileDirectory), dir.targets))\dir.targets" />
-</Project> \ No newline at end of file
+</Project>
diff --git a/src/System.Security.Cryptography.Xml/src/System/Security/Cryptography/Xml/EncryptedXml.cs b/src/System.Security.Cryptography.Xml/src/System/Security/Cryptography/Xml/EncryptedXml.cs
index 936b8f0a7e..19202e33b2 100644
--- a/src/System.Security.Cryptography.Xml/src/System/Security/Cryptography/Xml/EncryptedXml.cs
+++ b/src/System.Security.Cryptography.Xml/src/System/Security/Cryptography/Xml/EncryptedXml.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;
using System.Collections;
using System.IO;
using System.Net;
-using System.Security;
-using System.Security.Cryptography;
using System.Security.Cryptography.X509Certificates;
+using System.Security.Policy;
using System.Text;
using System.Xml;
@@ -63,6 +61,7 @@ namespace System.Security.Cryptography.Xml
//
private XmlDocument _document;
+ private Evidence _evidence;
private XmlResolver _xmlResolver;
// hash table defining the key name mapping
private const int _capacity = 4; // 4 is a reasonable capacity for
@@ -80,9 +79,12 @@ namespace System.Security.Cryptography.Xml
//
public EncryptedXml() : this(new XmlDocument()) { }
- public EncryptedXml(XmlDocument document)
+ public EncryptedXml(XmlDocument document) : this(document, null) { }
+
+ public EncryptedXml(XmlDocument document, Evidence evidence)
{
_document = document;
+ _evidence = evidence;
_xmlResolver = null;
// set the default padding to ISO-10126
_padding = PaddingMode.ISO10126;
@@ -123,6 +125,13 @@ namespace System.Security.Cryptography.Xml
}
}
+ // The evidence of the document being loaded: will be used to resolve external URIs
+ public Evidence DocumentEvidence
+ {
+ get { return _evidence; }
+ set { _evidence = value; }
+ }
+
// The resolver to use for external entities
public XmlResolver Resolver
{
@@ -207,7 +216,7 @@ namespace System.Security.Cryptography.Xml
}
else
{
- throw new CryptographicException(SR.Cryptography_Xml_UriNotResolved, cipherData.CipherReference.Uri);
+ throw new CryptographicException(SR.Cryptography_Xml_UriNotResolved, cipherData.CipherReference.Uri);
}
// read the output stream into a memory stream
byte[] cipherValue = null;
diff --git a/src/System.Security.Cryptography.Xml/tests/EncryptedXmlTest.cs b/src/System.Security.Cryptography.Xml/tests/EncryptedXmlTest.cs
index 74a1aca6f5..7e9f2ffeca 100644
--- a/src/System.Security.Cryptography.Xml/tests/EncryptedXmlTest.cs
+++ b/src/System.Security.Cryptography.Xml/tests/EncryptedXmlTest.cs
@@ -10,11 +10,9 @@
// See the LICENSE file in the project root for more information.
-using System;
using System.Collections;
using System.Collections.Generic;
using System.IO;
-using System.Reflection;
using System.Security.Cryptography.X509Certificates;
using System.Text;
using System.Xml;
@@ -47,28 +45,47 @@ namespace System.Security.Cryptography.Xml.Tests
}
}
+ private static readonly Encoding DefaultEncoding = Encoding.UTF8;
+ private const CipherMode DefaultCipherMode = CipherMode.CBC;
+ private const PaddingMode DefaultPaddingMode = PaddingMode.ISO10126;
+ private const string DefaultRecipient = "";
+ private static readonly XmlResolver DefaultXmlResolver = null;
+ private const int DefaultXmlDSigSearchDepth = 20;
+
[Fact]
public void Constructor_Default()
{
EncryptedXml encryptedXml = new EncryptedXml();
- Assert.Equal(Encoding.UTF8, encryptedXml.Encoding);
- Assert.Equal(CipherMode.CBC, encryptedXml.Mode);
- Assert.Equal(PaddingMode.ISO10126, encryptedXml.Padding);
- Assert.Equal(string.Empty, encryptedXml.Recipient);
- Assert.Equal(null, encryptedXml.Resolver);
- Assert.Equal(20, encryptedXml.XmlDSigSearchDepth);
+ Assert.Equal(DefaultEncoding, encryptedXml.Encoding);
+ Assert.Equal(DefaultCipherMode, encryptedXml.Mode);
+ Assert.Equal(DefaultPaddingMode, encryptedXml.Padding);
+ Assert.Equal(DefaultRecipient, encryptedXml.Recipient);
+ Assert.Equal(DefaultXmlResolver, encryptedXml.Resolver);
+ Assert.Equal(DefaultXmlDSigSearchDepth, encryptedXml.XmlDSigSearchDepth);
}
[Fact]
public void Constructor_XmlDocument()
{
EncryptedXml encryptedXml = new EncryptedXml(null);
- Assert.Equal(Encoding.UTF8, encryptedXml.Encoding);
- Assert.Equal(CipherMode.CBC, encryptedXml.Mode);
- Assert.Equal(PaddingMode.ISO10126, encryptedXml.Padding);
- Assert.Equal(string.Empty, encryptedXml.Recipient);
- Assert.Equal(null, encryptedXml.Resolver);
- Assert.Equal(20, encryptedXml.XmlDSigSearchDepth);
+ Assert.Equal(DefaultEncoding, encryptedXml.Encoding);
+ Assert.Equal(DefaultCipherMode, encryptedXml.Mode);
+ Assert.Equal(DefaultPaddingMode, encryptedXml.Padding);
+ Assert.Equal(DefaultRecipient, encryptedXml.Recipient);
+ Assert.Equal(DefaultXmlResolver, encryptedXml.Resolver);
+ Assert.Equal(DefaultXmlDSigSearchDepth, encryptedXml.XmlDSigSearchDepth);
+ }
+
+ [Fact]
+ public void Constructor_XmlDocumentAndEvidence()
+ {
+ EncryptedXml encryptedXml = new EncryptedXml(null, null);
+ Assert.Equal(DefaultEncoding, encryptedXml.Encoding);
+ Assert.Equal(DefaultCipherMode, encryptedXml.Mode);
+ Assert.Equal(DefaultPaddingMode, encryptedXml.Padding);
+ Assert.Equal(DefaultRecipient, encryptedXml.Recipient);
+ Assert.Equal(DefaultXmlResolver, encryptedXml.Resolver);
+ Assert.Equal(DefaultXmlDSigSearchDepth, encryptedXml.XmlDSigSearchDepth);
}
[Theory]
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 cfc538ffa1..f4eb172e09 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
@@ -4,6 +4,9 @@
<PropertyGroup>
<ProjectGuid>{25A02E40-D12C-4184-B599-E4F954D142DB}</ProjectGuid>
<IsPartialFacadeAssembly Condition="'$(TargetGroup)' == 'netfx'">true</IsPartialFacadeAssembly>
+ <!-- Must match version supported by frameworks which support 4.1.* inbox.
+ Can be removed when API is added and this assembly is versioned to 4.2.* -->
+ <AssemblyVersion Condition="'$(TargetsNetFx)' != 'true'">4.1.1.0</AssemblyVersion>
</PropertyGroup>
<PropertyGroup Condition="'$(Configuration)|$(Platform)' == 'netfx-Debug|AnyCPU'" />
<PropertyGroup Condition="'$(Configuration)|$(Platform)' == 'netfx-Release|AnyCPU'" />
diff --git a/src/System.ServiceModel.Syndication/System.ServiceModel.Syndication.sln b/src/System.ServiceModel.Syndication/System.ServiceModel.Syndication.sln
new file mode 100644
index 0000000000..7a9b5eb4a8
--- /dev/null
+++ b/src/System.ServiceModel.Syndication/System.ServiceModel.Syndication.sln
@@ -0,0 +1,31 @@
+
+Microsoft Visual Studio Solution File, Format Version 12.00
+# Visual Studio 15
+VisualStudioVersion = 15.0.26906.1
+MinimumVisualStudioVersion = 10.0.40219.1
+Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "System.ServiceModel.Syndication", "src\System.ServiceModel.Syndication.csproj", "{C2AB129B-E3EC-465B-B1B7-0F7D414B1E74}"
+EndProject
+Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "System.ServiceModel.Syndication.Tests", "tests\System.ServiceModel.Syndication.Tests.csproj", "{A622B2C0-DD74-4218-9CF0-F9B2E52F4E91}"
+EndProject
+Global
+ GlobalSection(SolutionConfigurationPlatforms) = preSolution
+ netstandard-Debug|Any CPU = netstandard-Debug|Any CPU
+ netstandard-Release|Any CPU = netstandard-Release|Any CPU
+ EndGlobalSection
+ GlobalSection(ProjectConfigurationPlatforms) = postSolution
+ {C2AB129B-E3EC-465B-B1B7-0F7D414B1E74}.netstandard-Debug|Any CPU.ActiveCfg = netstandard-Debug|Any CPU
+ {C2AB129B-E3EC-465B-B1B7-0F7D414B1E74}.netstandard-Debug|Any CPU.Build.0 = netstandard-Debug|Any CPU
+ {C2AB129B-E3EC-465B-B1B7-0F7D414B1E74}.netstandard-Release|Any CPU.ActiveCfg = netstandard-Release|Any CPU
+ {C2AB129B-E3EC-465B-B1B7-0F7D414B1E74}.netstandard-Release|Any CPU.Build.0 = netstandard-Release|Any CPU
+ {A622B2C0-DD74-4218-9CF0-F9B2E52F4E91}.netstandard-Debug|Any CPU.ActiveCfg = netstandard-Debug|Any CPU
+ {A622B2C0-DD74-4218-9CF0-F9B2E52F4E91}.netstandard-Debug|Any CPU.Build.0 = netstandard-Debug|Any CPU
+ {A622B2C0-DD74-4218-9CF0-F9B2E52F4E91}.netstandard-Release|Any CPU.ActiveCfg = netstandard-Release|Any CPU
+ {A622B2C0-DD74-4218-9CF0-F9B2E52F4E91}.netstandard-Release|Any CPU.Build.0 = netstandard-Release|Any CPU
+ EndGlobalSection
+ GlobalSection(SolutionProperties) = preSolution
+ HideSolutionNode = FALSE
+ EndGlobalSection
+ GlobalSection(ExtensibilityGlobals) = postSolution
+ SolutionGuid = {C509160C-D427-4B6F-A515-169B6BB2B210}
+ EndGlobalSection
+EndGlobal
diff --git a/src/System.ServiceModel.Syndication/dir.props b/src/System.ServiceModel.Syndication/dir.props
new file mode 100644
index 0000000000..4356decc45
--- /dev/null
+++ b/src/System.ServiceModel.Syndication/dir.props
@@ -0,0 +1,8 @@
+<?xml version="1.0" encoding="utf-8"?>
+<Project ToolsVersion="14.0" DefaultTargets="Build" xmlns="http://schemas.microsoft.com/developer/msbuild/2003">
+ <Import Project="..\dir.props" />
+ <PropertyGroup>
+ <AssemblyVersion>4.0.0.0</AssemblyVersion>
+ <AssemblyKey>Open</AssemblyKey>
+ </PropertyGroup>
+</Project> \ No newline at end of file
diff --git a/src/System.ServiceModel.Syndication/src/Configurations.props b/src/System.ServiceModel.Syndication/src/Configurations.props
new file mode 100644
index 0000000000..c398e42e89
--- /dev/null
+++ b/src/System.ServiceModel.Syndication/src/Configurations.props
@@ -0,0 +1,8 @@
+<?xml version="1.0" encoding="utf-8"?>
+<Project ToolsVersion="14.0" DefaultTargets="Build" xmlns="http://schemas.microsoft.com/developer/msbuild/2003">
+ <PropertyGroup>
+ <BuildConfigurations>
+ netstandard;
+ </BuildConfigurations>
+ </PropertyGroup>
+</Project> \ No newline at end of file
diff --git a/src/System.ServiceModel.Syndication/src/Resources/Strings.resx b/src/System.ServiceModel.Syndication/src/Resources/Strings.resx
new file mode 100644
index 0000000000..5534250e89
--- /dev/null
+++ b/src/System.ServiceModel.Syndication/src/Resources/Strings.resx
@@ -0,0 +1,7928 @@
+<?xml version="1.0" encoding="utf-8"?>
+<root>
+ <!--
+ Microsoft ResX Schema
+
+ Version 2.0
+
+ The primary goals of this format is to allow a simple XML format
+ that is mostly human readable. The generation and parsing of the
+ various data types are done through the TypeConverter classes
+ associated with the data types.
+
+ Example:
+
+ ... ado.net/XML headers & schema ...
+ <resheader name="resmimetype">text/microsoft-resx</resheader>
+ <resheader name="version">2.0</resheader>
+ <resheader name="reader">System.Resources.ResXResourceReader, System.Windows.Forms, ...</resheader>
+ <resheader name="writer">System.Resources.ResXResourceWriter, System.Windows.Forms, ...</resheader>
+ <data name="Name1"><value>this is my long string</value><comment>this is a comment</comment></data>
+ <data name="Color1" type="System.Drawing.Color, System.Drawing">Blue</data>
+ <data name="Bitmap1" mimetype="application/x-microsoft.net.object.binary.base64">
+ <value>[base64 mime encoded serialized .NET Framework object]</value>
+ </data>
+ <data name="Icon1" type="System.Drawing.Icon, System.Drawing" mimetype="application/x-microsoft.net.object.bytearray.base64">
+ <value>[base64 mime encoded string representing a byte array form of the .NET Framework object]</value>
+ <comment>This is a comment</comment>
+ </data>
+
+ There are any number of "resheader" rows that contain simple
+ name/value pairs.
+
+ Each data row contains a name, and value. The row also contains a
+ type or mimetype. Type corresponds to a .NET class that support
+ text/value conversion through the TypeConverter architecture.
+ Classes that don't support this are serialized and stored with the
+ mimetype set.
+
+ The mimetype is used for serialized objects, and tells the
+ ResXResourceReader how to depersist the object. This is currently not
+ extensible. For a given mimetype the value must be set accordingly:
+
+ Note - application/x-microsoft.net.object.binary.base64 is the format
+ that the ResXResourceWriter will generate, however the reader can
+ read any of the formats listed below.
+
+ mimetype: application/x-microsoft.net.object.binary.base64
+ value : The object must be serialized with
+ : System.Runtime.Serialization.Formatters.Binary.BinaryFormatter
+ : and then encoded with base64 encoding.
+
+ mimetype: application/x-microsoft.net.object.soap.base64
+ value : The object must be serialized with
+ : System.Runtime.Serialization.Formatters.Soap.SoapFormatter
+ : and then encoded with base64 encoding.
+
+ mimetype: application/x-microsoft.net.object.bytearray.base64
+ value : The object must be serialized into a byte array
+ : using a System.ComponentModel.TypeConverter
+ : and then encoded with base64 encoding.
+ -->
+ <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="XmlNodeIsNotAnElement" xml:space="preserve">
+ <value>The XmlReader is not currently in a node of type Element.</value>
+ </data>
+ <data name="InvalidSkipHours" xml:space="preserve">
+ <value>The hour can't be lower than 0 or greater than 23.</value>
+ </data>
+ <data name="NoIPEndpointsFoundForHost" xml:space="preserve">
+ <value>No IPEndpoints were found for host {0}.</value>
+ </data>
+ <data name="DnsResolveFailed" xml:space="preserve">
+ <value>No DNS entries exist for host {0}.</value>
+ </data>
+ <data name="RequiredAttributeMissing" xml:space="preserve">
+ <value>Attribute '{0}' is required on element '{1}'.</value>
+ </data>
+ <data name="UnsupportedCryptoAlgorithm" xml:space="preserve">
+ <value>Crypto algorithm {0} not supported in this context.</value>
+ </data>
+ <data name="CustomCryptoAlgorithmIsNotValidHashAlgorithm" xml:space="preserve">
+ <value>The custom crypto algorithm '{0}' obtained using CryptoConfig is not a valid or supported hash algorithm.</value>
+ </data>
+ <data name="InvalidClientCredentials" xml:space="preserve">
+ <value>The client credential entered was invalid.</value>
+ </data>
+ <data name="SspiErrorOrInvalidClientCredentials" xml:space="preserve">
+ <value>Either the client credential was invalid or there was an error collecting the client credentials by the SSPI.</value>
+ </data>
+ <data name="CustomCryptoAlgorithmIsNotValidAsymmetricSignature" xml:space="preserve">
+ <value>The custom crypto algorithm '{0}' obtained using CryptoConfig is not a valid or supported asymmetric signature algorithm.</value>
+ </data>
+ <data name="TokenSerializerNotSetonFederationProvider" xml:space="preserve">
+ <value>The security token serializer must be specified on the security token provider.</value>
+ </data>
+ <data name="IssuerBindingNotPresentInTokenRequirement" xml:space="preserve">
+ <value>The key length '{0}' is not a multiple of 8 for symmetric keys.</value>
+ </data>
+ <data name="IssuerChannelBehaviorsCannotContainSecurityCredentialsManager" xml:space="preserve">
+ <value>The channel behaviors configured for the issuer address '{0}' cannot contain a behavior of type '{1}'.</value>
+ </data>
+ <data name="ServiceBusyCountTrace" xml:space="preserve">
+ <value>Operation Action={0}</value>
+ </data>
+ <data name="SecurityTokenManagerCannotCreateProviderForRequirement" xml:space="preserve">
+ <value>The security token manager cannot create a token provider for requirement '{0}'.</value>
+ </data>
+ <data name="SecurityTokenManagerCannotCreateAuthenticatorForRequirement" xml:space="preserve">
+ <value>The security token manager cannot create a token authenticator for requirement '{0}'.</value>
+ </data>
+ <data name="FailedSignatureVerification" xml:space="preserve">
+ <value>The signature verification failed. Please see inner exception for fault details.</value>
+ </data>
+ <data name="SecurityTokenManagerCannotCreateSerializerForVersion" xml:space="preserve">
+ <value>The security token manager cannot create a token serializer for security token version '{0}'.</value>
+ </data>
+ <data name="SupportingSignatureIsNotDerivedFrom" xml:space="preserve">
+ <value>The supporting signature is not signed with a derived key. The binding's supporting token parameter '{0}' requires key derivation.</value>
+ </data>
+ <data name="PrimarySignatureWasNotSignedByDerivedKey" xml:space="preserve">
+ <value>The primary signature is not signed with a derived key. The binding's primary token parameter '{0}' requires key derivation.</value>
+ </data>
+ <data name="PrimarySignatureWasNotSignedByDerivedWrappedKey" xml:space="preserve">
+ <value>The primary signature is not signed with a key derived from the encrypted key. The binding's token parameter '{0}' requires key derivation.</value>
+ </data>
+ <data name="MessageWasNotEncryptedByDerivedWrappedKey" xml:space="preserve">
+ <value>The message is not encrypted with a key derived from the encrypted key. The binding's token parameter '{0}' requires key derivation.</value>
+ </data>
+ <data name="SecurityStateEncoderDecodingFailure" xml:space="preserve">
+ <value>The DataProtectionSecurityStateEncoder is unable to decode the byte array. Ensure that a 'UserProfile' is loaded, if this is a 'web farm scenario' ensure all servers are running as the same user with the roaming profiles or provide a custom SecurityStateEncoder'.</value>
+ </data>
+ <data name="SecurityStateEncoderEncodingFailure" xml:space="preserve">
+ <value>The DataProtectionSecurityStateEncoder is unable to encode the byte array. Ensure that a 'UserProfile' is loaded, if this is a 'web farm scenario' ensure all servers are running as the same user with the roaming profiles or provide a custom SecurityStateEncoder'.</value>
+ </data>
+ <data name="MessageWasNotEncryptedByDerivedEncryptionToken" xml:space="preserve">
+ <value>The message is not encrypted with a key derived from the encryption token. The binding's token parameter '{0}' requires key derivation.</value>
+ </data>
+ <data name="TokenAuthenticatorRequiresSecurityBindingElement" xml:space="preserve">
+ <value>The security token manager requires the security binding element to be specified in order to create a token authenticator for requirement '{0}'.</value>
+ </data>
+ <data name="TokenProviderRequiresSecurityBindingElement" xml:space="preserve">
+ <value>The security token manager requires the security binding element to be specified in order to create a token provider for requirement '{0}'.</value>
+ </data>
+ <data name="UnexpectedSecuritySessionCloseResponse" xml:space="preserve">
+ <value>The security session received an unexpected close response from the other party.</value>
+ </data>
+ <data name="UnexpectedSecuritySessionClose" xml:space="preserve">
+ <value>The security session received an unexpected close from the other party.</value>
+ </data>
+ <data name="CannotObtainSslConnectionInfo" xml:space="preserve">
+ <value>The service was unable to verify the cipher strengths negotiated as part of the SSL handshake.</value>
+ </data>
+ <data name="HeaderEncryptionNotSupportedInWsSecurityJan2004" xml:space="preserve">
+ <value>SecurityVersion.WSSecurityJan2004 does not support header encryption. Header with name '{0}' and namespace '{1}' is configured for encryption. Consider using SecurityVersion.WsSecurity11 and above or use transport security to encrypt the full message.</value>
+ </data>
+ <data name="EncryptedHeaderNotSigned" xml:space="preserve">
+ <value>The Header ('{0}', '{1}') was encrypted but not signed. All encrypted headers outside the security header should be signed.</value>
+ </data>
+ <data name="EncodingBindingElementDoesNotHandleReaderQuotas" xml:space="preserve">
+ <value>Unable to obtain XmlDictionaryReaderQuotas from the Binding. If you have specified a custom EncodingBindingElement, verify that the EncodingBindingElement can handle XmlDictionaryReaderQuotas in its GetProperty&lt;T&gt;() method.</value>
+ </data>
+ <data name="HeaderDecryptionNotSupportedInWsSecurityJan2004" xml:space="preserve">
+ <value>SecurityVersion.WSSecurityJan2004 does not support header decryption. Use SecurityVersion.WsSecurity11 and above or use transport security to encrypt the full message.</value>
+ </data>
+ <data name="DecryptionFailed" xml:space="preserve">
+ <value>Unable to decrypt an encrypted data block. Please verify that the encryption algorithm and keys used by the sender and receiver match.</value>
+ </data>
+ <data name="AuthenticationManagerShouldNotReturnNull" xml:space="preserve">
+ <value>The authenticate method in the ServiceAuthenticationManager returned null. If you do not want to return any authorization policies in the collection then return an empty ReadOnlyCollection instead. </value>
+ </data>
+ <data name="ErrorSerializingSecurityToken" xml:space="preserve">
+ <value>There was an error serializing the security token. Please see the inner exception for more details.</value>
+ </data>
+ <data name="ErrorDeserializingKeyIdentifierClauseFromTokenXml" xml:space="preserve">
+ <value>There was an error creating the security key identifier clause from the security token XML. Please see the inner exception for more details.</value>
+ </data>
+ <data name="ErrorDeserializingTokenXml" xml:space="preserve">
+ <value>There was an error deserializing the security token XML. Please see the inner exception for more details.</value>
+ </data>
+ <data name="TokenRequirementDoesNotSpecifyTargetAddress" xml:space="preserve">
+ <value>The token requirement '{0}' does not specify the target address. This is required by the token manager for creating the corresponding security token provider.</value>
+ </data>
+ <data name="DerivedKeyNotInitialized" xml:space="preserve">
+ <value>The derived key has not been computed for the security token.</value>
+ </data>
+ <data name="IssuedKeySizeNotCompatibleWithAlgorithmSuite" xml:space="preserve">
+ <value>The binding ('{0}', '{1}') has been configured with a security algorithm suite '{2}' that is incompatible with the issued token key size '{3}' specified on the binding.</value>
+ </data>
+ <data name="IssuedTokenAuthenticationModeRequiresSymmetricIssuedKey" xml:space="preserve">
+ <value>The IssuedToken security authentication mode requires the issued token to contain a symmetric key.</value>
+ </data>
+ <data name="InvalidBearerKeyUsage" xml:space="preserve">
+ <value>The binding ('{0}', '{1}') uses an Issued Token with Bearer Key Type in a invalid context. The Issued Token with a Bearer Key Type can only be used as a Signed Supporting token or a Signed Encrypted Supporting token. See the SecurityBindingElement.EndpointSupportingTokenParameters property.</value>
+ </data>
+ <data name="MultipleIssuerEndpointsFound" xml:space="preserve">
+ <value>Policy for multiple issuer endpoints was retrieved from '{0}' but the relying party's policy does not specify which issuer endpoint to use. One of the endpoints was selected as the issuer endpoint to use. If you are using svcutil, the other endpoints will be available in commented form in the configuration as &lt;alternativeIssuedTokenParameters&gt;. Check the configuration to ensure that the right issuer endpoint was selected.</value>
+ </data>
+ <data name="MultipleAuthenticationManagersInServiceBindingParameters" xml:space="preserve">
+ <value>The AuthenticationManager cannot be added to the binding parameters because the binding parameters already contains a AuthenticationManager '{0}'. If you are configuring a custom AuthenticationManager for the service, please first remove any existing AuthenticationManagers from the behaviors collection before adding the custom AuthenticationManager.</value>
+ </data>
+ <data name="MultipleAuthenticationSchemesInServiceBindingParameters" xml:space="preserve">
+ <value>The AuthenticationSchemes cannot be added to the binding parameters because the binding parameters already contains AuthenticationSchemes '{0}'. If you are configuring custom AuthenticationSchemes for the service, please first remove any existing AuthenticationSchemes from the behaviors collection before adding custom AuthenticationSchemes.</value>
+ </data>
+ <data name="NoSecurityBindingElementFound" xml:space="preserve">
+ <value>Unable to find a SecurityBindingElement.</value>
+ </data>
+ <data name="MultipleSecurityCredentialsManagersInServiceBindingParameters" xml:space="preserve">
+ <value>The ServiceCredentials cannot be added to the binding parameters because the binding parameters already contains a SecurityCredentialsManager '{0}'. If you are configuring custom credentials for the service, please first remove any existing ServiceCredentials from the behaviors collection before adding the custom credential.</value>
+ </data>
+ <data name="MultipleSecurityCredentialsManagersInChannelBindingParameters" xml:space="preserve">
+ <value>The ClientCredentials cannot be added to the binding parameters because the binding parameters already contains a SecurityCredentialsManager '{0}'. If you are configuring custom credentials for the channel, please first remove any existing ClientCredentials from the behaviors collection before adding the custom credential.</value>
+ </data>
+ <data name="NoClientCertificate" xml:space="preserve">
+ <value>The binding ('{0}', '{1}') has been configured with a MutualCertificateDuplexBindingElement that requires a client certificate. The client certificate is currently missing.</value>
+ </data>
+ <data name="SecurityTokenParametersHasIncompatibleInclusionMode" xml:space="preserve">
+ <value>The binding ('{0}', '{1}') is configured with a security token parameter '{2}' that has an incompatible security token inclusion mode '{3}'. Specify an alternate security token inclusion mode (for example, '{4}').</value>
+ </data>
+ <data name="CannotCreateTwoWayListenerForNegotiation" xml:space="preserve">
+ <value>Unable to create a bi-directional (request-reply or duplex) channel for security negotiation. Please ensure that the binding is capable of creating a bi-directional channel.</value>
+ </data>
+ <data name="NegotiationQuotasExceededFaultReason" xml:space="preserve">
+ <value>There are too many active security negotiations or secure conversations at the service. Please retry later.</value>
+ </data>
+ <data name="PendingSessionsExceededFaultReason" xml:space="preserve">
+ <value>There are too many pending secure conversations on the server. Please retry later.</value>
+ </data>
+ <data name="RequestSecurityTokenDoesNotMatchEndpointFilters" xml:space="preserve">
+ <value>The RequestSecurityToken message does not match the endpoint filters the service '{0}' is expecting incoming messages to match. This may be because the RequestSecurityToken was intended to be sent to a different service.</value>
+ </data>
+ <data name="SecuritySessionRequiresIssuanceAuthenticator" xml:space="preserve">
+ <value>The security session requires a security token authenticator that implements '{0}'. '{1}' does not implement '{0}'.</value>
+ </data>
+ <data name="SecuritySessionRequiresSecurityContextTokenCache" xml:space="preserve">
+ <value>The security session requires a security token resolver that implements '{1}'. The security token resolver '{0}' does not implement '{1}'.</value>
+ </data>
+ <data name="SessionTokenIsNotSecurityContextToken" xml:space="preserve">
+ <value>The session security token authenticator returned a token of type '{0}'. The token type expected is '{1}'.</value>
+ </data>
+ <data name="SessionTokenIsNotGenericXmlToken" xml:space="preserve">
+ <value>The session security token provider returned a token of type '{0}'. The token type expected is '{1}'.</value>
+ </data>
+ <data name="SecurityStandardsManagerNotSet" xml:space="preserve">
+ <value>The security standards manager was not specified on '{0}'.</value>
+ </data>
+ <data name="SecurityNegotiationMessageTooLarge" xml:space="preserve">
+ <value>The security negotiation message with action '{0}' is larger than the maximum allowed buffer size '{1}'. If you are using a streamed transport consider increasing the maximum buffer size on the transport.</value>
+ </data>
+ <data name="PreviousChannelDemuxerOpenFailed" xml:space="preserve">
+ <value>The channel demuxer Open failed previously with exception '{0}'.</value>
+ </data>
+ <data name="SecurityChannelListenerNotSet" xml:space="preserve">
+ <value>The security channel listener was not specified on '{0}'.</value>
+ </data>
+ <data name="SecurityChannelListenerChannelExtendedProtectionNotSupported" xml:space="preserve">
+ <value>ExtendedProtectionPolicy specified a PolicyEnforcement of 'Always' which is not supported for the authentication mode requested. This prevents the ExtendedProtectionPolicy from being enforced. For StandardBindings use a SecurityMode of TransportWithMessageCredential and a ClientCredential type of Windows. For CustomBindings use SspiNegotiationOverTransport or KerberosOverTransport. Alternatively, specify a PolicyEnforcement of 'Never'.</value>
+ </data>
+ <data name="SecurityChannelBindingMissing" xml:space="preserve">
+ <value>ExtendedProtectionPolicy specified a PolicyEnforcement of 'Always' and a ChannelBinding was not found. This prevents the ExtendedProtectionPolicy from being enforced. Change the binding to make a ChannelBinding available, for StandardBindings use a SecurityMode of TransportWithMessageCredential and a ClientCredential type of Windows. For CustomBindings use SspiNegotiationOverTransport or KerberosOverTransport. Alternatively, specify a PolicyEnforcement of 'Never'.</value>
+ </data>
+ <data name="SecuritySettingsLifetimeManagerNotSet" xml:space="preserve">
+ <value>The security settings lifetime manager was not specified on '{0}'.</value>
+ </data>
+ <data name="SecurityListenerClosing" xml:space="preserve">
+ <value>The listener is not accepting new secure conversations because it is closing.</value>
+ </data>
+ <data name="SecurityListenerClosingFaultReason" xml:space="preserve">
+ <value>The server is not accepting new secure conversations currently because it is closing. Please retry later.</value>
+ </data>
+ <data name="SslCipherKeyTooSmall" xml:space="preserve">
+ <value>The cipher key negotiated by SSL is too small ('{0}' bits). Keys of such lengths are not allowed as they may result in information disclosure. Please configure the initiator machine to negotiate SSL cipher keys that are '{1}' bits or longer.</value>
+ </data>
+ <data name="DerivedKeyTokenNonceTooLong" xml:space="preserve">
+ <value>The length ('{0}' bytes) of the derived key's Nonce exceeds the maximum length ('{1}' bytes) allowed.</value>
+ </data>
+ <data name="DerivedKeyTokenLabelTooLong" xml:space="preserve">
+ <value>The length ('{0}' bytes) of the derived key's Label exceeds the maximum length ('{1}' bytes) allowed.</value>
+ </data>
+ <data name="DerivedKeyTokenOffsetTooHigh" xml:space="preserve">
+ <value>The derived key's Offset ('{0}' bytes) exceeds the maximum offset ('{1}' bytes) allowed.</value>
+ </data>
+ <data name="DerivedKeyTokenGenerationAndLengthTooHigh" xml:space="preserve">
+ <value>The derived key's generation ('{0}') and length ('{1}' bytes) result in a key derivation offset that is greater than the maximum offset ('{2}' bytes) allowed.</value>
+ </data>
+ <data name="DerivedKeyLimitExceeded" xml:space="preserve">
+ <value>The number of derived keys in the message has exceeded the maximum allowed number '{0}'.</value>
+ </data>
+ <data name="WrappedKeyLimitExceeded" xml:space="preserve">
+ <value>The number of encrypted keys in the message has exceeded the maximum allowed number '{0}'.</value>
+ </data>
+ <data name="BufferQuotaExceededReadingBase64" xml:space="preserve">
+ <value>Unable to finish reading Base64 data as the given buffer quota has been exceeded. Buffer quota: {0}. Consider increasing the MaxReceivedMessageSize quota on the TransportBindingElement. Please note that a very high value for MaxReceivedMessageSize will result in buffering a large message and might open the system to DOS attacks.</value>
+ </data>
+ <data name="MessageSecurityDoesNotWorkWithManualAddressing" xml:space="preserve">
+ <value>Manual addressing is not supported with message level security. Configure the binding ('{0}', '{1}') to use transport security or to not do manual addressing.</value>
+ </data>
+ <data name="TargetAddressIsNotSet" xml:space="preserve">
+ <value>The target service address was not specified on '{0}'.</value>
+ </data>
+ <data name="IssuedTokenCacheNotSet" xml:space="preserve">
+ <value>The issued token cache was not specified on '{0}'.</value>
+ </data>
+ <data name="SecurityAlgorithmSuiteNotSet" xml:space="preserve">
+ <value>The security algorithm suite was not specified on '{0}'.</value>
+ </data>
+ <data name="SecurityTokenFoundOutsideSecurityHeader" xml:space="preserve">
+ <value>A security token ('{0}', '{1}') was found outside the security header. The message may have been altered in transit.</value>
+ </data>
+ <data name="SecurityTokenNotResolved" xml:space="preserve">
+ <value>The SecurityTokenProvider '{0}' could not resolve the token.</value>
+ </data>
+ <data name="SecureConversationCancelNotAllowedFaultReason" xml:space="preserve">
+ <value>A secure conversation cancellation is not allowed by the binding.</value>
+ </data>
+ <data name="BootstrapSecurityBindingElementNotSet" xml:space="preserve">
+ <value>The security binding element for bootstrap security was not specified on '{0}'.</value>
+ </data>
+ <data name="IssuerBuildContextNotSet" xml:space="preserve">
+ <value>The context for building the issuer channel was not specified on '{0}'.</value>
+ </data>
+ <data name="StsBindingNotSet" xml:space="preserve">
+ <value>The binding to use to communicate to the federation service at '{0}' is not specified.</value>
+ </data>
+ <data name="SslCertMayNotDoKeyExchange" xml:space="preserve">
+ <value>It is likely that certificate '{0}' may not have a private key that is capable of key exchange or the process may not have access rights for the private key. Please see inner exception for detail.</value>
+ </data>
+ <data name="SslCertMustHavePrivateKey" xml:space="preserve">
+ <value>The certificate '{0}' must have a private key. The process must have access rights for the private key.</value>
+ </data>
+ <data name="NoOutgoingEndpointAddressAvailableForDoingIdentityCheck" xml:space="preserve">
+ <value>No outgoing EndpointAddress is available to check the identity on a message to be sent.</value>
+ </data>
+ <data name="NoOutgoingEndpointAddressAvailableForDoingIdentityCheckOnReply" xml:space="preserve">
+ <value>No outgoing EndpointAddress is available to check the identity on a received reply.</value>
+ </data>
+ <data name="NoSigningTokenAvailableToDoIncomingIdentityCheck" xml:space="preserve">
+ <value>No signing token is available to do an incoming identity check.</value>
+ </data>
+ <data name="Psha1KeyLengthInvalid" xml:space="preserve">
+ <value>The PSHA1 key length '{0}' is invalid.</value>
+ </data>
+ <data name="CloneNotImplementedCorrectly" xml:space="preserve">
+ <value>Clone() was not implemented properly by '{0}'. The cloned object was '{1}'.</value>
+ </data>
+ <data name="BadIssuedTokenType" xml:space="preserve">
+ <value>The issued token is of unexpected type '{0}'. Expected token type '{1}'.</value>
+ </data>
+ <data name="OperationDoesNotAllowImpersonation" xml:space="preserve">
+ <value>The service operation '{0}' that belongs to the contract with the '{1}' name and the '{2}' namespace does not allow impersonation.</value>
+ </data>
+ <data name="RstrHasMultipleIssuedTokens" xml:space="preserve">
+ <value>The RequestSecurityTokenResponse has multiple RequestedSecurityToken elements.</value>
+ </data>
+ <data name="RstrHasMultipleProofTokens" xml:space="preserve">
+ <value>The RequestSecurityTokenResponse has multiple RequestedProofToken elements.</value>
+ </data>
+ <data name="ProofTokenXmlUnexpectedInRstr" xml:space="preserve">
+ <value>The proof token XML element is not expected in the response.</value>
+ </data>
+ <data name="InvalidKeyLengthRequested" xml:space="preserve">
+ <value>The key length '{0}' requested is invalid.</value>
+ </data>
+ <data name="IssuedSecurityTokenParametersNotSet" xml:space="preserve">
+ <value>The security token parameters to use for the issued token are not set on '{0}'.</value>
+ </data>
+ <data name="InvalidOrUnrecognizedAction" xml:space="preserve">
+ <value>The message could not be processed because the action '{0}' is invalid or unrecognized.</value>
+ </data>
+ <data name="UnsupportedTokenInclusionMode" xml:space="preserve">
+ <value>Token inclusion mode '{0}' is not supported.</value>
+ </data>
+ <data name="CannotImportProtectionLevelForContract" xml:space="preserve">
+ <value>The policy to import a process cannot import a binding for contract ({0},{1}). The protection requirements for the binding are not compatible with a binding already imported for the contract. You must reconfigure the binding.</value>
+ </data>
+ <data name="OnlyOneOfEncryptedKeyOrSymmetricBindingCanBeSelected" xml:space="preserve">
+ <value>The symmetric security protocol can either be configured with a symmetric token provider and a symmetric token authenticator or an asymmetric token provider. It cannot be configured with both.</value>
+ </data>
+ <data name="ClientCredentialTypeMustBeSpecifiedForMixedMode" xml:space="preserve">
+ <value>ClientCredentialType.None is not valid for the TransportWithMessageCredential security mode. Specify a message credential type or use a different security mode.</value>
+ </data>
+ <data name="SecuritySessionIdAlreadyPresentInFilterTable" xml:space="preserve">
+ <value>The security session id '{0}' is already present in the filter table.</value>
+ </data>
+ <data name="SupportingTokenNotProvided" xml:space="preserve">
+ <value>A supporting token that satisfies parameters '{0}' and attachment mode '{1}' was not provided.</value>
+ </data>
+ <data name="SupportingTokenIsNotEndorsing" xml:space="preserve">
+ <value>The supporting token provided for parameters '{0}' did not endorse the primary signature.</value>
+ </data>
+ <data name="SupportingTokenIsNotSigned" xml:space="preserve">
+ <value>The supporting token provided for parameters '{0}' was not signed as part of the primary signature.</value>
+ </data>
+ <data name="SupportingTokenIsNotEncrypted" xml:space="preserve">
+ <value>The supporting token provided for parameters '{0}' was not encrypted.</value>
+ </data>
+ <data name="BasicTokenNotExpected" xml:space="preserve">
+ <value>A basic token is not expected in the security header in this context.</value>
+ </data>
+ <data name="FailedAuthenticationTrustFaultCode" xml:space="preserve">
+ <value>The request for security token could not be satisfied because authentication failed.</value>
+ </data>
+ <data name="AuthenticationOfClientFailed" xml:space="preserve">
+ <value>The caller was not authenticated by the service.</value>
+ </data>
+ <data name="InvalidRequestTrustFaultCode" xml:space="preserve">
+ <value>The request for security token has invalid or malformed elements.</value>
+ </data>
+ <data name="SignedSupportingTokenNotExpected" xml:space="preserve">
+ <value>A signed supporting token is not expected in the security header in this context.</value>
+ </data>
+ <data name="SenderSideSupportingTokensMustSpecifySecurityTokenParameters" xml:space="preserve">
+ <value>Security token parameters must be specified with supporting tokens for each message.</value>
+ </data>
+ <data name="SignatureAndEncryptionTokenMismatch" xml:space="preserve">
+ <value>The signature token '{0}' is not the same token as the encryption token '{1}'.</value>
+ </data>
+ <data name="RevertingPrivilegeFailed" xml:space="preserve">
+ <value>The reverting operation failed with the exception '{0}'.</value>
+ </data>
+ <data name="UnknownSupportingToken" xml:space="preserve">
+ <value>Unrecognized supporting token '{0}' was encountered.</value>
+ </data>
+ <data name="MoreThanOneSupportingSignature" xml:space="preserve">
+ <value>More than one supporting signature was encountered using the same supporting token '{0}'.</value>
+ </data>
+ <data name="UnsecuredMessageFaultReceived" xml:space="preserve">
+ <value>An unsecured or incorrectly secured fault was received from the other party. See the inner FaultException for the fault code and detail.</value>
+ </data>
+ <data name="FailedAuthenticationFaultReason" xml:space="preserve">
+ <value>At least one security token in the message could not be validated.</value>
+ </data>
+ <data name="BadContextTokenOrActionFaultReason" xml:space="preserve">
+ <value>The message could not be processed. This is most likely because the action '{0}' is incorrect or because the message contains an invalid or expired security context token or because there is a mismatch between bindings. The security context token would be invalid if the service aborted the channel due to inactivity. To prevent the service from aborting idle sessions prematurely increase the Receive timeout on the service endpoint's binding.</value>
+ </data>
+ <data name="BadContextTokenFaultReason" xml:space="preserve">
+ <value>The security context token is expired or is not valid. The message was not processed.</value>
+ </data>
+ <data name="NegotiationFailedIO" xml:space="preserve">
+ <value>Transport security negotiation failed due to an underlying IO error: {0}.</value>
+ </data>
+ <data name="SecurityNegotiationCannotProtectConfidentialEndpointHeader" xml:space="preserve">
+ <value>The security negotiation with '{0}' cannot be initiated because the confidential endpoint address header ('{1}', '{2}') cannot be encrypted during the course of the negotiation.</value>
+ </data>
+ <data name="InvalidSecurityTokenFaultReason" xml:space="preserve">
+ <value>An error occurred when processing the security tokens in the message.</value>
+ </data>
+ <data name="InvalidSecurityFaultReason" xml:space="preserve">
+ <value>An error occurred when verifying security for the message.</value>
+ </data>
+ <data name="AnonymousLogonsAreNotAllowed" xml:space="preserve">
+ <value>The service does not allow you to log on anonymously.</value>
+ </data>
+ <data name="UnableToObtainIssuerMetadata" xml:space="preserve">
+ <value>Obtaining metadata from issuer '{0}' failed with error '{1}'.</value>
+ </data>
+ <data name="ErrorImportingIssuerMetadata" xml:space="preserve">
+ <value>Importing metadata from issuer '{0}' failed with error '{1}'.</value>
+ </data>
+ <data name="MultipleCorrelationTokensFound" xml:space="preserve">
+ <value>Multiple correlation tokens were found in the security correlation state.</value>
+ </data>
+ <data name="NoCorrelationTokenFound" xml:space="preserve">
+ <value>No correlation token was found in the security correlation state.</value>
+ </data>
+ <data name="MultipleSupportingAuthenticatorsOfSameType" xml:space="preserve">
+ <value>Multiple supporting token authenticators with the token parameter type equal to '{0}' cannot be specified. If more than one Supporting Token of the same type is expected in the response, then configure the supporting token collection with just one entry for that SecurityTokenParameters. The SecurityTokenAuthenticator that gets created from the SecurityTokenParameters will be used to authenticate multiple tokens. It is not possible to add SecurityTokenParameters of the same type in the SupportingTokenParameters collection or repeat it across EndpointSupportingTokenParameters and OperationSupportingTokenParameters.</value>
+ </data>
+ <data name="TooManyIssuedSecurityTokenParameters" xml:space="preserve">
+ <value>A leg of the federated security chain contains multiple IssuedSecurityTokenParameters. The InfoCard system only supports one IssuedSecurityTokenParameters for each leg.</value>
+ </data>
+ <data name="UnknownTokenAuthenticatorUsedInTokenProcessing" xml:space="preserve">
+ <value>An unrecognized token authenticator '{0}' was used for token processing.</value>
+ </data>
+ <data name="TokenMustBeNullWhenTokenParametersAre" xml:space="preserve">
+ <value>The SecurityTokenParameters and SecurityToken tuple specified for use in the security header must both be null or must both be non-null.</value>
+ </data>
+ <data name="SecurityTokenParametersCloneInvalidResult" xml:space="preserve">
+ <value>The CloneCore method of {0} type returned an invalid result. </value>
+ </data>
+ <data name="CertificateUnsupportedForHttpTransportCredentialOnly" xml:space="preserve">
+ <value>Certificate-based client authentication is not supported in TransportCredentialOnly security mode. Select the Transport security mode.</value>
+ </data>
+ <data name="BasicHttpMessageSecurityRequiresCertificate" xml:space="preserve">
+ <value>BasicHttp binding requires that BasicHttpBinding.Security.Message.ClientCredentialType be equivalent to the BasicHttpMessageCredentialType.Certificate credential type for secure messages. Select Transport or TransportWithMessageCredential security for UserName credentials.</value>
+ </data>
+ <data name="EntropyModeRequiresRequestorEntropy" xml:space="preserve">
+ <value>The client must provide key entropy in key entropy mode '{0}'.</value>
+ </data>
+ <data name="BearerKeyTypeCannotHaveProofKey" xml:space="preserve">
+ <value>A Proof Token was found in the response that was returned by the Security Token Service for a Bearer Key Type token request. Note that Proof Tokens should not be generated when a Bearer Key Type request is made.</value>
+ </data>
+ <data name="BearerKeyIncompatibleWithWSFederationHttpBinding" xml:space="preserve">
+ <value>Bearer Key Type is not supported with WSFederationHttpBinding. Please use WS2007FederationHttpBinding.</value>
+ </data>
+ <data name="UnableToCreateKeyTypeElementForUnknownKeyType" xml:space="preserve">
+ <value>Unable to create Key Type element for the Key Type '{0}'. This might be due to a wrong version of MessageSecurityVersion set on the SecurityBindingElement.</value>
+ </data>
+ <data name="EntropyModeCannotHaveProofTokenOrIssuerEntropy" xml:space="preserve">
+ <value>The issuer cannot provide key entropy or a proof token in key entropy mode '{0}'.</value>
+ </data>
+ <data name="EntropyModeCannotHaveRequestorEntropy" xml:space="preserve">
+ <value>The client cannot provide key entropy in key entropy mode '{0}'.</value>
+ </data>
+ <data name="EntropyModeRequiresProofToken" xml:space="preserve">
+ <value>The issuer must provide a proof token in key entropy mode '{0}'.</value>
+ </data>
+ <data name="EntropyModeRequiresComputedKey" xml:space="preserve">
+ <value>The issuer must provide a computed key in key entropy mode '{0}'.</value>
+ </data>
+ <data name="EntropyModeRequiresIssuerEntropy" xml:space="preserve">
+ <value>The issuer must provide key entropy in key entropy mode '{0}'.</value>
+ </data>
+ <data name="EntropyModeCannotHaveComputedKey" xml:space="preserve">
+ <value>The issuer cannot provide a computed key in key entropy mode '{0}'.</value>
+ </data>
+ <data name="UnknownComputedKeyAlgorithm" xml:space="preserve">
+ <value>The computed key algorithm '{0}' is not supported.</value>
+ </data>
+ <data name="NoncesCachedInfinitely" xml:space="preserve">
+ <value>The ReplayWindow and ClockSkew cannot be the maximum possible value when replay detection is enabled.</value>
+ </data>
+ <data name="ChannelMustBeOpenedToGetSessionId" xml:space="preserve">
+ <value>The session channel must be opened before the session ID can be accessed.</value>
+ </data>
+ <data name="SecurityVersionDoesNotSupportEncryptedKeyBinding" xml:space="preserve">
+ <value>The binding ('{0}','{1}') for contract ('{2}','{3}') has been configured with an incompatible security version that does not support unattached references to EncryptedKeys. Use '{4}' or higher as the security version for the binding.</value>
+ </data>
+ <data name="SecurityVersionDoesNotSupportThumbprintX509KeyIdentifierClause" xml:space="preserve">
+ <value>The '{0}','{1}' binding for the '{2}','{3}' contract is configured with a security version that does not support external references to X.509 tokens using the certificate's thumbprint value. Use '{4}' or higher as the security version for the binding.</value>
+ </data>
+ <data name="SecurityBindingSupportsOneWayOnly" xml:space="preserve">
+ <value>The SecurityBinding for the ('{0}','{1}') binding for the ('{2}','{3}') contract only supports the OneWay operation.</value>
+ </data>
+ <data name="DownlevelNameCannotMapToUpn" xml:space="preserve">
+ <value>Cannot map Windows user '{0}' to a UserPrincipalName that can be used for S4U impersonation.</value>
+ </data>
+ <data name="ResolvingExternalTokensRequireSecurityTokenParameters" xml:space="preserve">
+ <value>Resolving an External reference token requires appropriate SecurityTokenParameters to be specified.</value>
+ </data>
+ <data name="SecurityRenewFaultReason" xml:space="preserve">
+ <value>The SecurityContextSecurityToken's key needs to be renewed.</value>
+ </data>
+ <data name="ClientSecurityOutputSessionCloseTimeout" xml:space="preserve">
+ <value>The client's security session was not able to close its output session within the configured timeout ({0}).</value>
+ </data>
+ <data name="ClientSecurityNegotiationTimeout" xml:space="preserve">
+ <value>Client is unable to finish the security negotiation within the configured timeout ({0}). The current negotiation leg is {1} ({2}). </value>
+ </data>
+ <data name="ClientSecuritySessionRequestTimeout" xml:space="preserve">
+ <value>Client is unable to request the security session within the configured timeout ({0}).</value>
+ </data>
+ <data name="ServiceSecurityCloseOutputSessionTimeout" xml:space="preserve">
+ <value>The service's security session was not able to close its output session within the configured timeout ({0}).</value>
+ </data>
+ <data name="ServiceSecurityCloseTimeout" xml:space="preserve">
+ <value>The service's security session did not receive a 'close' message from the client within the configured timeout ({0}).</value>
+ </data>
+ <data name="ClientSecurityCloseTimeout" xml:space="preserve">
+ <value>The client's security session did not receive a 'close response' message from the service within the configured timeout ({0}).</value>
+ </data>
+ <data name="UnableToRenewSessionKey" xml:space="preserve">
+ <value>Cannot renew the security session key.</value>
+ </data>
+ <data name="SessionKeyRenewalNotSupported" xml:space="preserve">
+ <value>Cannot renew the security session key. Session Key Renewal is not supported.</value>
+ </data>
+ <data name="SctCookieXmlParseError" xml:space="preserve">
+ <value>Error parsing SecurityContextSecurityToken Cookie XML.</value>
+ </data>
+ <data name="SctCookieValueMissingOrIncorrect" xml:space="preserve">
+ <value>The SecurityContextSecurityToken's Cookie element either does not contain '{0}' or has a wrong value for it.</value>
+ </data>
+ <data name="SctCookieBlobDecodeFailure" xml:space="preserve">
+ <value>Error decoding the Cookie element of SecurityContextSecurityToken.</value>
+ </data>
+ <data name="SctCookieNotSupported" xml:space="preserve">
+ <value>Issuing cookie SecurityContextSecurityToken is not supported.</value>
+ </data>
+ <data name="CannotImportSupportingTokensForOperationWithoutRequestAction" xml:space="preserve">
+ <value>Security policy import failed. The security policy contains supporting token requirements at the operation scope. The contract description does not specify the action for the request message associated with this operation.</value>
+ </data>
+ <data name="SignatureConfirmationsNotExpected" xml:space="preserve">
+ <value>Signature confirmation is not expected in the security header.</value>
+ </data>
+ <data name="SignatureConfirmationsOccursAfterPrimarySignature" xml:space="preserve">
+ <value>The signature confirmation elements cannot occur after the primary signature.</value>
+ </data>
+ <data name="SignatureConfirmationWasExpected" xml:space="preserve">
+ <value>Signature confirmation was expected to be present in the security header.</value>
+ </data>
+ <data name="SecurityVersionDoesNotSupportSignatureConfirmation" xml:space="preserve">
+ <value>The SecurityVersion '{0}' does not support signature confirmation. Use a later SecurityVersion.</value>
+ </data>
+ <data name="SignatureConfirmationRequiresRequestReply" xml:space="preserve">
+ <value>The protocol factory must support Request/Reply security in order to offer signature confirmation.</value>
+ </data>
+ <data name="NotAllSignaturesConfirmed" xml:space="preserve">
+ <value>Not all the signatures in the request message were confirmed in the reply message.</value>
+ </data>
+ <data name="FoundUnexpectedSignatureConfirmations" xml:space="preserve">
+ <value>The request did not have any signatures but the reply has signature confirmations.</value>
+ </data>
+ <data name="TooManyPendingSessionKeys" xml:space="preserve">
+ <value>There are too many renewed session keys that have not been used.</value>
+ </data>
+ <data name="SecuritySessionKeyIsStale" xml:space="preserve">
+ <value>The session key must be renewed before it can secure application messages.</value>
+ </data>
+ <data name="MultipleMatchingCryptosFound" xml:space="preserve">
+ <value>The token's crypto collection has multiple objects of type '{0}'.</value>
+ </data>
+ <data name="CannotFindMatchingCrypto" xml:space="preserve">
+ <value>The token's crypto collection does not support algorithm '{0}'.</value>
+ </data>
+ <data name="SymmetricSecurityBindingElementNeedsProtectionTokenParameters" xml:space="preserve">
+ <value>SymmetricSecurityBindingElement cannot build a channel or listener factory. The ProtectionTokenParameters property is required but not set. Binding element configuration: {0}</value>
+ </data>
+ <data name="AsymmetricSecurityBindingElementNeedsInitiatorTokenParameters" xml:space="preserve">
+ <value>AsymmetricSecurityBindingElement cannot build a channel or listener factory. The InitiatorTokenParameters property is required but not set. Binding element configuration: {0}</value>
+ </data>
+ <data name="AsymmetricSecurityBindingElementNeedsRecipientTokenParameters" xml:space="preserve">
+ <value>AsymmetricSecurityBindingElement cannot build a channel or listener factory. The RecipientTokenParameters property is required but not set. Binding element configuration: {0}</value>
+ </data>
+ <data name="CachedNegotiationStateQuotaReached" xml:space="preserve">
+ <value>The service cannot cache the negotiation state as the capacity '{0}' has been reached. Retry the request.</value>
+ </data>
+ <data name="LsaAuthorityNotContacted" xml:space="preserve">
+ <value>Internal SSL error (refer to Win32 status code for details). Check the server certificate to determine if it is capable of key exchange.</value>
+ </data>
+ <data name="KeyRolloverGreaterThanKeyRenewal" xml:space="preserve">
+ <value>The key rollover interval cannot be greater than the key renewal interval.</value>
+ </data>
+ <data name="AtLeastOneContractOperationRequestRequiresProtectionLevelNotSupportedByBinding" xml:space="preserve">
+ <value>The request message must be protected. This is required by an operation of the contract ('{0}','{1}'). The protection must be provided by the binding ('{2}','{3}').</value>
+ </data>
+ <data name="AtLeastOneContractOperationResponseRequiresProtectionLevelNotSupportedByBinding" xml:space="preserve">
+ <value>The response message must be protected. This is required by an operation of the contract ('{0}', '{1}'). The protection must be provided by the binding ('{2}', '{3}').</value>
+ </data>
+ <data name="UnknownHeaderCannotProtected" xml:space="preserve">
+ <value>The contract ('{0}','{1}') contains some unknown header ('{2}','{3}') which cannot be secured. Please choose ProtectionLevel.None for this header. </value>
+ </data>
+ <data name="NoStreamingWithSecurity" xml:space="preserve">
+ <value>The binding ('{0}','{1}') supports streaming which cannot be configured together with message level security. Consider choosing a different transfer mode or choosing the transport level security.</value>
+ </data>
+ <data name="CurrentSessionTokenNotRenewed" xml:space="preserve">
+ <value>The supporting token in the renew message has a different generation '{0}' than the current session token's generation '{1}'.</value>
+ </data>
+ <data name="IncorrectSpnOrUpnSpecified" xml:space="preserve">
+ <value>Security Support Provider Interface (SSPI) authentication failed. The server may not be running in an account with identity '{0}'. If the server is running in a service account (Network Service for example), specify the account's ServicePrincipalName as the identity in the EndpointAddress for the server. If the server is running in a user account, specify the account's UserPrincipalName as the identity in the EndpointAddress for the server.</value>
+ </data>
+ <data name="IncomingSigningTokenMustBeAnEncryptedKey" xml:space="preserve">
+ <value>For this security protocol, the incoming signing token must be an EncryptedKey.</value>
+ </data>
+ <data name="SecuritySessionAbortedFaultReason" xml:space="preserve">
+ <value>The security session was terminated This may be because no messages were received on the session for too long.</value>
+ </data>
+ <data name="NoAppliesToPresent" xml:space="preserve">
+ <value>No AppliesTo element is present in the deserialized RequestSecurityToken/RequestSecurityTokenResponse.</value>
+ </data>
+ <data name="UnsupportedKeyLength" xml:space="preserve">
+ <value>Symmetric Key length {0} is not supported by the algorithm suite '{1}'.</value>
+ </data>
+ <data name="ForReplayDetectionToBeDoneRequireIntegrityMustBeSet" xml:space="preserve">
+ <value>For replay detection to be done ProtectionLevel must be Sign or EncryptAndSign.</value>
+ </data>
+ <data name="CantInferReferenceForToken" xml:space="preserve">
+ <value>Can't infer an external reference for '{0}' token type.</value>
+ </data>
+ <data name="TrustDriverIsUnableToCreatedNecessaryAttachedOrUnattachedReferences" xml:space="preserve">
+ <value>Unable to create Attached or Unattached reference for '{0}'.</value>
+ </data>
+ <data name="TrustDriverVersionDoesNotSupportSession" xml:space="preserve">
+ <value>The configured Trust version does not support sessions. Use WSTrustFeb2005 or above.</value>
+ </data>
+ <data name="TrustDriverVersionDoesNotSupportIssuedTokens" xml:space="preserve">
+ <value>The configured WS-Trust version does not support issued tokens. WS-Trust February 2005 or later is required.</value>
+ </data>
+ <data name="CannotPerformS4UImpersonationOnPlatform" xml:space="preserve">
+ <value>The binding ('{0}','{1}') for contract ('{2}','{3}') supports impersonation only on Windows 2003 Server and newer version of Windows. Use SspiNegotiated authentication and a binding with Secure Conversation with cancellation enabled.</value>
+ </data>
+ <data name="CannotPerformImpersonationOnUsernameToken" xml:space="preserve">
+ <value>Impersonation using the client token is not possible. The binding ('{0}', '{1}') for contract ('{2}', '{3}') uses the Username Security Token for client authentication with a Membership Provider registered. Use a different type of security token for the client.</value>
+ </data>
+ <data name="SecureConversationRequiredByReliableSession" xml:space="preserve">
+ <value>Cannot establish a reliable session without secure conversation. Enable secure conversation.</value>
+ </data>
+ <data name="RevertImpersonationFailure" xml:space="preserve">
+ <value>Failed to revert impersonation. {0}</value>
+ </data>
+ <data name="TransactionFlowRequiredIssuedTokens" xml:space="preserve">
+ <value>In order to flow a transaction, flowing issued tokens must also be supported.</value>
+ </data>
+ <data name="SignatureConfirmationNotSupported" xml:space="preserve">
+ <value>The configured SecurityVersion does not support signature confirmation. Use WsSecurity11 or above.</value>
+ </data>
+ <data name="SecureConversationDriverVersionDoesNotSupportSession" xml:space="preserve">
+ <value>The configured SecureConversation version does not support sessions. Use WSSecureConversationFeb2005 or above.</value>
+ </data>
+ <data name="SoapSecurityNegotiationFailed" xml:space="preserve">
+ <value>SOAP security negotiation failed. See inner exception for more details.</value>
+ </data>
+ <data name="SoapSecurityNegotiationFailedForIssuerAndTarget" xml:space="preserve">
+ <value>SOAP security negotiation with '{0}' for target '{1}' failed. See inner exception for more details.</value>
+ </data>
+ <data name="OneWayOperationReturnedFault" xml:space="preserve">
+ <value>The one-way operation returned a fault message. The reason for the fault was '{0}'.</value>
+ </data>
+ <data name="OneWayOperationReturnedLargeFault" xml:space="preserve">
+ <value>The one-way operation returned a fault message with Action='{0}'.</value>
+ </data>
+ <data name="OneWayOperationReturnedMessage" xml:space="preserve">
+ <value>The one-way operation returned a non-null message with Action='{0}'.</value>
+ </data>
+ <data name="CannotFindSecuritySession" xml:space="preserve">
+ <value>Cannot find the security session with the ID '{0}'.</value>
+ </data>
+ <data name="SecurityContextKeyExpired" xml:space="preserve">
+ <value>The SecurityContextSecurityToken with Context-id={0} (generation-id={1}) has expired.</value>
+ </data>
+ <data name="SecurityContextKeyExpiredNoKeyGeneration" xml:space="preserve">
+ <value>The SecurityContextSecurityToken with Context-id={0} (no key generation-id) has expired.</value>
+ </data>
+ <data name="SecuritySessionRequiresMessageIntegrity" xml:space="preserve">
+ <value>Security sessions require all messages to be signed.</value>
+ </data>
+ <data name="RequiredTimestampMissingInSecurityHeader" xml:space="preserve">
+ <value>Required timestamp missing in security header.</value>
+ </data>
+ <data name="ReceivedMessageInRequestContextNull" xml:space="preserve">
+ <value>The request message in the request context received from channel '{0}' is null.</value>
+ </data>
+ <data name="KeyLifetimeNotWithinTokenLifetime" xml:space="preserve">
+ <value>The key effective and expiration times must be bounded by the token effective and expiration times.</value>
+ </data>
+ <data name="EffectiveGreaterThanExpiration" xml:space="preserve">
+ <value>The valid from time is greater than the valid to time.</value>
+ </data>
+ <data name="NoSessionTokenPresentInMessage" xml:space="preserve">
+ <value>No session token was present in the message.</value>
+ </data>
+ <data name="KeyLengthMustBeMultipleOfEight" xml:space="preserve">
+ <value>Key length '{0}' is not a multiple of 8 for symmetric keys.</value>
+ </data>
+ <data name="InvalidX509RawData" xml:space="preserve">
+ <value>Invalid binary representation of an X.509 certificate.</value>
+ </data>
+ <data name="ExportOfBindingWithTransportSecurityBindingElementAndNoTransportSecurityNotSupported" xml:space="preserve">
+ <value>Security policy export failed. The binding contains a TransportSecurityBindingElement but no transport binding element that implements ITransportTokenAssertionProvider. Policy export for such a binding is not supported. Make sure the transport binding element in the binding implements the ITransportTokenAssertionProvider interface.</value>
+ </data>
+ <data name="UnsupportedSecureConversationBootstrapProtectionRequirements" xml:space="preserve">
+ <value>Cannot import the security policy. The protection requirements for the secure conversation bootstrap binding are not supported. Protection requirements for the secure conversation bootstrap must require both the request and the response to be signed and encrypted.</value>
+ </data>
+ <data name="UnsupportedBooleanAttribute" xml:space="preserve">
+ <value>Cannot import the policy. The value of the attribute '{0}' must be either 'true', 'false', '1' or '0'. The following error occurred: '{1}'.</value>
+ </data>
+ <data name="NoTransportTokenAssertionProvided" xml:space="preserve">
+ <value>The security policy expert failed. The provided transport token assertion of type '{0}' did not create a transport token assertion to include the sp:TransportBinding security policy assertion.</value>
+ </data>
+ <data name="PolicyRequiresConfidentialityWithoutIntegrity" xml:space="preserve">
+ <value>Message security policy for the '{0}' action requires confidentiality without integrity. Confidentiality without integrity is not supported.</value>
+ </data>
+ <data name="PrimarySignatureIsRequiredToBeEncrypted" xml:space="preserve">
+ <value>The primary signature must be encrypted.</value>
+ </data>
+ <data name="TokenCannotCreateSymmetricCrypto" xml:space="preserve">
+ <value>A symmetric crypto could not be created from token '{0}'.</value>
+ </data>
+ <data name="TokenDoesNotMeetKeySizeRequirements" xml:space="preserve">
+ <value>The key size requirements for the '{0}' algorithm suite are not met by the '{1}' token which has key size of '{2}'.</value>
+ </data>
+ <data name="MessageProtectionOrderMismatch" xml:space="preserve">
+ <value>The received message does not meet the required message protection order '{0}'.</value>
+ </data>
+ <data name="PrimarySignatureMustBeComputedBeforeSupportingTokenSignatures" xml:space="preserve">
+ <value>Primary signature must be computed before supporting token signatures.</value>
+ </data>
+ <data name="ElementToSignMustHaveId" xml:space="preserve">
+ <value>Element to sign must have id.</value>
+ </data>
+ <data name="StandardsManagerCannotWriteObject" xml:space="preserve">
+ <value>The token Serializer cannot serialize '{0}'. If this is a custom type you must supply a custom serializer.</value>
+ </data>
+ <data name="SigningWithoutPrimarySignatureRequiresTimestamp" xml:space="preserve">
+ <value>Signing without primary signature requires timestamp.</value>
+ </data>
+ <data name="OperationCannotBeDoneAfterProcessingIsStarted" xml:space="preserve">
+ <value>This operation cannot be done after processing is started.</value>
+ </data>
+ <data name="MaximumPolicyRedirectionsExceeded" xml:space="preserve">
+ <value>The recursive policy fetching limit has been reached. Check to determine if there is a loop in the federation service chain.</value>
+ </data>
+ <data name="InvalidAttributeInSignedHeader" xml:space="preserve">
+ <value>The ('{0}', '{1}') signed header contains the ('{2}', '{3}') attribute. The expected attribute is ('{4}', '{5}').</value>
+ </data>
+ <data name="StsAddressNotSet" xml:space="preserve">
+ <value>The address of the security token issuer is not specified. An explicit issuer address must be specified in the binding for target '{0}' or the local issuer address must be configured in the credentials.</value>
+ </data>
+ <data name="MoreThanOneSecurityBindingElementInTheBinding" xml:space="preserve">
+ <value>More than one SecurityBindingElement found in the binding ('{0}', '{1}) for contract ('{2}', '{3}'). Only one SecurityBindingElement is allowed. </value>
+ </data>
+ <data name="ClientCredentialsUnableToCreateLocalTokenProvider" xml:space="preserve">
+ <value>ClientCredentials cannot create a local token provider for token requirement {0}.</value>
+ </data>
+ <data name="SecurityBindingElementCannotBeExpressedInConfig" xml:space="preserve">
+ <value>A security policy was imported for the endpoint. The security policy contains requirements that cannot be represented in a Windows Communication Foundation configuration. Look for a comment about the SecurityBindingElement parameters that are required in the configuration file that was generated. Create the correct binding element with code. The binding configuration that is in the configuration file is not secure.</value>
+ </data>
+ <data name="ConfigurationSchemaInsuffientForSecurityBindingElementInstance" xml:space="preserve">
+ <value>The configuration schema is insufficient to describe the non-standard configuration of the following security binding element: </value>
+ </data>
+ <data name="ConfigurationSchemaContainsX509IssuerSerialReference" xml:space="preserve">
+ <value>The wsdl schema that was used to create this configuration file contained a 'RequireIssuerSerialReference' assertion for a X509Token. This can not be represented in configuration, you will need to programatically adjust the appropriate X509SecurityTokenParameters.X509KeyIdentifierClauseType to X509KeyIdentifierClauseType.IssuerSerial. The default of X509KeyIdentifierClauseType.Thumbprint will be used, which may cause interop issues.</value>
+ </data>
+ <data name="SecurityProtocolCannotDoReplayDetection" xml:space="preserve">
+ <value>The security protocol '{0}' cannot do replay detection.</value>
+ </data>
+ <data name="UnableToFindSecurityHeaderInMessage" xml:space="preserve">
+ <value>Security processor was unable to find a security header with actor '{0}' in the message. This might be because the message is an unsecured fault or because there is a binding mismatch between the communicating parties. This can occur if the service is configured for security and the client is not using security.</value>
+ </data>
+ <data name="UnableToFindSecurityHeaderInMessageNoActor" xml:space="preserve">
+ <value>Security processor was unable to find a security header in the message. This might be because the message is an unsecured fault or because there is a binding mismatch between the communicating parties. This can occur if the service is configured for security and the client is not using security.</value>
+ </data>
+ <data name="NoPrimarySignatureAvailableForSupportingTokenSignatureVerification" xml:space="preserve">
+ <value>No primary signature available for supporting token signature verification.</value>
+ </data>
+ <data name="SupportingTokenSignaturesNotExpected" xml:space="preserve">
+ <value>Supporting token signatures not expected.</value>
+ </data>
+ <data name="CannotReadToken" xml:space="preserve">
+ <value>Cannot read the token from the '{0}' element with the '{1}' namespace for BinarySecretSecurityToken, with a '{2}' ValueType. If this element is expected to be valid, ensure that security is configured to consume tokens with the name, namespace and value type specified.</value>
+ </data>
+ <data name="ExpectedElementMissing" xml:space="preserve">
+ <value>Element '{0}' with namespace '{1}' not found.</value>
+ </data>
+ <data name="ExpectedOneOfTwoElementsFromNamespace" xml:space="preserve">
+ <value>Expected element '{0}' or element '{1}' (from namespace '{2}').</value>
+ </data>
+ <data name="RstDirectDoesNotExpectRstr" xml:space="preserve">
+ <value>AcceleratedTokenAuthenticator does not expect RequestSecurityTokenResponse from the client.</value>
+ </data>
+ <data name="RequireNonCookieMode" xml:space="preserve">
+ <value>The '{0}' binding with the '{1}' namespace is configured to issue cookie security context tokens. COM+ Integration services does not support cookie security context tokens.</value>
+ </data>
+ <data name="RequiredSignatureMissing" xml:space="preserve">
+ <value>The signature must be in the security header.</value>
+ </data>
+ <data name="RequiredMessagePartNotSigned" xml:space="preserve">
+ <value>The '{0}' required message part was not signed.</value>
+ </data>
+ <data name="RequiredMessagePartNotSignedNs" xml:space="preserve">
+ <value>The '{0}', '{1}' required message part was not signed.</value>
+ </data>
+ <data name="RequiredMessagePartNotEncrypted" xml:space="preserve">
+ <value>The '{0}' required message part was not encrypted.</value>
+ </data>
+ <data name="RequiredMessagePartNotEncryptedNs" xml:space="preserve">
+ <value>The '{0}', '{1}' required message part was not encrypted.</value>
+ </data>
+ <data name="SignatureVerificationFailed" xml:space="preserve">
+ <value>Signature verification failed.</value>
+ </data>
+ <data name="CannotIssueRstTokenType" xml:space="preserve">
+ <value>Cannot issue the token type '{0}'.</value>
+ </data>
+ <data name="NoNegotiationMessageToSend" xml:space="preserve">
+ <value>There is no negotiation message to send.</value>
+ </data>
+ <data name="InvalidIssuedTokenKeySize" xml:space="preserve">
+ <value>The issued token has an invalid key size '{0}'.</value>
+ </data>
+ <data name="CannotObtainIssuedTokenKeySize" xml:space="preserve">
+ <value>Cannot determine the key size of the issued token.</value>
+ </data>
+ <data name="NegotiationIsNotCompleted" xml:space="preserve">
+ <value>The negotiation has not yet completed.</value>
+ </data>
+ <data name="NegotiationIsCompleted" xml:space="preserve">
+ <value>The negotiation has already completed.</value>
+ </data>
+ <data name="MissingMessageID" xml:space="preserve">
+ <value>Request Message is missing a MessageID header. One is required to correlate a reply.</value>
+ </data>
+ <data name="SecuritySessionLimitReached" xml:space="preserve">
+ <value>Cannot create a security session. Retry later.</value>
+ </data>
+ <data name="SecuritySessionAlreadyPending" xml:space="preserve">
+ <value>The security session with id '{0}' is already pending.</value>
+ </data>
+ <data name="SecuritySessionNotPending" xml:space="preserve">
+ <value>No security session with id '{0}' is pending.</value>
+ </data>
+ <data name="SecuritySessionListenerNotFound" xml:space="preserve">
+ <value>No security session listener was found for message with action '{0}'.</value>
+ </data>
+ <data name="SessionTokenWasNotClosed" xml:space="preserve">
+ <value>The session token was not closed by the server.</value>
+ </data>
+ <data name="ProtocolMustBeInitiator" xml:space="preserve">
+ <value>'{0}' protocol can only be used by the Initiator.</value>
+ </data>
+ <data name="ProtocolMustBeRecipient" xml:space="preserve">
+ <value>'{0}' protocol can only be used at the Recipient.</value>
+ </data>
+ <data name="SendingOutgoingmessageOnRecipient" xml:space="preserve">
+ <value>Unexpected code path for server security application, sending outgoing message on Recipient.</value>
+ </data>
+ <data name="OnlyBodyReturnValuesSupported" xml:space="preserve">
+ <value>Only body return values are supported currently for protection, MessagePartDescription was specified.</value>
+ </data>
+ <data name="UnknownTokenAttachmentMode" xml:space="preserve">
+ <value>Unknown token attachment mode: {0}.</value>
+ </data>
+ <data name="ProtocolMisMatch" xml:space="preserve">
+ <value>Security protocol must be '{0}', type is: '{1}'.;</value>
+ </data>
+ <data name="AttemptToCreateMultipleRequestContext" xml:space="preserve">
+ <value>The initial request context was already specified. Can not create two for same message.</value>
+ </data>
+ <data name="ServerReceivedCloseMessageStateIsCreated" xml:space="preserve">
+ <value>{0}.OnCloseMessageReceived when state == Created.</value>
+ </data>
+ <data name="ShutdownRequestWasNotReceived" xml:space="preserve">
+ <value>Shutdown request was not received.</value>
+ </data>
+ <data name="UnknownFilterType" xml:space="preserve">
+ <value>Unknown filter type: '{0}'.</value>
+ </data>
+ <data name="StandardsManagerDoesNotMatch" xml:space="preserve">
+ <value>Standards manager of filter does not match that of filter table. Can not have two different filters.</value>
+ </data>
+ <data name="FilterStrictModeDifferent" xml:space="preserve">
+ <value>Session filter's isStrictMode differs from filter table's isStrictMode.</value>
+ </data>
+ <data name="SSSSCreateAcceptor" xml:space="preserve">
+ <value>SecuritySessionServerSettings.CreateAcceptor, channelAcceptor must be null, can not create twice.</value>
+ </data>
+ <data name="TransactionFlowBadOption" xml:space="preserve">
+ <value>Invalid TransactionFlowOption value.</value>
+ </data>
+ <data name="TokenManagerCouldNotReadToken" xml:space="preserve">
+ <value>Security token manager could not parse token with name '{0}', namespace '{1}', valueType '{2}'.</value>
+ </data>
+ <data name="InvalidActionForNegotiationMessage" xml:space="preserve">
+ <value>Security negotiation message has incorrect action '{0}'.</value>
+ </data>
+ <data name="InvalidKeySizeSpecifiedInNegotiation" xml:space="preserve">
+ <value>The specified key size {0} is invalid. The key size must be between {1} and {2}.</value>
+ </data>
+ <data name="GetTokenInfoFailed" xml:space="preserve">
+ <value>Could not get token information (error=0x{0:X}).</value>
+ </data>
+ <data name="UnexpectedEndOfFile" xml:space="preserve">
+ <value>Unexpected end of file.</value>
+ </data>
+ <data name="TimeStampHasCreationAheadOfExpiry" xml:space="preserve">
+ <value>The security timestamp is invalid because its creation time ('{0}') is greater than or equal to its expiration time ('{1}').</value>
+ </data>
+ <data name="TimeStampHasExpiryTimeInPast" xml:space="preserve">
+ <value>The security timestamp is stale because its expiration time ('{0}') is in the past. Current time is '{1}' and allowed clock skew is '{2}'.</value>
+ </data>
+ <data name="TimeStampHasCreationTimeInFuture" xml:space="preserve">
+ <value>The security timestamp is invalid because its creation time ('{0}') is in the future. Current time is '{1}' and allowed clock skew is '{2}'.</value>
+ </data>
+ <data name="TimeStampWasCreatedTooLongAgo" xml:space="preserve">
+ <value>The security timestamp is stale because its creation time ('{0}') is too far back in the past. Current time is '{1}', maximum timestamp lifetime is '{2}' and allowed clock skew is '{3}'.</value>
+ </data>
+ <data name="InvalidOrReplayedNonce" xml:space="preserve">
+ <value>The nonce is invalid or replayed.</value>
+ </data>
+ <data name="MessagePartSpecificationMustBeImmutable" xml:space="preserve">
+ <value>Message part specification must be made constant before being set.</value>
+ </data>
+ <data name="UnsupportedIssuerEntropyType" xml:space="preserve">
+ <value>Issuer entropy is not BinarySecretSecurityToken or WrappedKeySecurityToken.</value>
+ </data>
+ <data name="NoRequestSecurityTokenResponseElements" xml:space="preserve">
+ <value>No RequestSecurityTokenResponse elements were found.</value>
+ </data>
+ <data name="NoCookieInSct" xml:space="preserve">
+ <value>The SecurityContextSecurityToken does not have a cookie.</value>
+ </data>
+ <data name="TokenProviderReturnedBadToken" xml:space="preserve">
+ <value>TokenProvider returned token of incorrect type '{0}'.</value>
+ </data>
+ <data name="ItemNotAvailableInDeserializedRST" xml:space="preserve">
+ <value>{0} is not available in deserialized RequestSecurityToken.</value>
+ </data>
+ <data name="ItemAvailableInDeserializedRSTOnly" xml:space="preserve">
+ <value>{0} is only available in a deserialized RequestSecurityToken.</value>
+ </data>
+ <data name="ItemNotAvailableInDeserializedRSTR" xml:space="preserve">
+ <value>{0} is not available in deserialized RequestSecurityTokenResponse.</value>
+ </data>
+ <data name="ItemAvailableInDeserializedRSTROnly" xml:space="preserve">
+ <value>{0} is only available in a deserialized RequestSecurityTokenResponse.</value>
+ </data>
+ <data name="MoreThanOneRSTRInRSTRC" xml:space="preserve">
+ <value>The RequestSecurityTokenResponseCollection received has more than one RequestSecurityTokenResponse element. Only one RequestSecurityTokenResponse element was expected.</value>
+ </data>
+ <data name="Hosting_VirtualPathExtenstionCanNotBeDetached" xml:space="preserve">
+ <value>VirtualPathExtension is not allowed to be removed.</value>
+ </data>
+ <data name="Hosting_NotSupportedProtocol" xml:space="preserve">
+ <value>The protocol '{0}' is not supported.</value>
+ </data>
+ <data name="Hosting_BaseUriDeserializedNotValid" xml:space="preserve">
+ <value>The BaseUriWithWildcard object has invalid fields after deserialization.</value>
+ </data>
+ <data name="Hosting_RelativeAddressFormatError" xml:space="preserve">
+ <value>Registered relativeAddress '{0}' in configuration file is not a valid one. Possible causes could be : You specified an empty addreess or an absolute address (i.e., starting with '/' or '\'), or the address contains invalid character[s]. The supported relativeAddress formats are "[folder/]filename" or "~/[folder/]filename". </value>
+ </data>
+ <data name="Hosting_NoAbsoluteRelativeAddress" xml:space="preserve">
+ <value>'{0}' is an absolute address. The supported relativeAddress formats are "[subfolder/]filename" or "~/[subfolder/]filename". </value>
+ </data>
+ <data name="SecureConversationNeedsBootstrapSecurity" xml:space="preserve">
+ <value>Cannot create security binding element based on the configuration data. When secure conversation authentication mode is selected, the secure conversation bootstrap binding element must also be specified. </value>
+ </data>
+ <data name="Hosting_MemoryGatesCheckFailedUnderPartialTrust" xml:space="preserve">
+ <value>Setting minFreeMemoryPercentageToActivateService requires full trust privilege. Please change the application's trust level or remove this setting from the configuration file.</value>
+ </data>
+ <data name="Hosting_CompatibilityServiceNotHosted" xml:space="preserve">
+ <value>This service requires ASP.NET compatibility and must be hosted in IIS. Either host the service in IIS with ASP.NET compatibility turned on in web.config or set the AspNetCompatibilityRequirementsAttribute.AspNetCompatibilityRequirementsMode property to a value other than Required.</value>
+ </data>
+ <data name="Hosting_MisformattedPort" xml:space="preserve">
+ <value>The '{0}' protocol binding '{1}' specifies an invalid port number '{2}'.</value>
+ </data>
+ <data name="Hosting_MisformattedBinding" xml:space="preserve">
+ <value>The protocol binding '{0}' does not conform to the syntax for '{1}'. The following is an example of valid '{1}' protocol bindings: '{2}'.</value>
+ </data>
+ <data name="Hosting_MisformattedBindingData" xml:space="preserve">
+ <value>The protocol binding '{0}' is not valid for '{1}'. This might be because the port number is out of range.</value>
+ </data>
+ <data name="Hosting_NoHttpTransportManagerForUri" xml:space="preserve">
+ <value>There is no compatible TransportManager found for URI '{0}'. This may be because you have used an absolute address that points outside of the virtual application. Please use a relative address instead.</value>
+ </data>
+ <data name="Hosting_NoTcpPipeTransportManagerForUri" xml:space="preserve">
+ <value>There is no compatible TransportManager found for URI '{0}'. This may be because you have used an absolute address that points outside of the virtual application, or the binding settings of the endpoint do not match those that have been set by other services or endpoints. Note that all bindings for the same protocol should have the same settings in the same application.</value>
+ </data>
+ <data name="Hosting_ProcessNotExecutingUnderHostedContext" xml:space="preserve">
+ <value>'{0}' cannot be invoked within the current hosting environment. This API requires that the calling application be hosted in IIS or WAS.</value>
+ </data>
+ <data name="Hosting_ServiceActivationFailed" xml:space="preserve">
+ <value>The requested service, '{0}' could not be activated. See the server's diagnostic trace logs for more information.</value>
+ </data>
+ <data name="Hosting_ServiceTypeNotProvided" xml:space="preserve">
+ <value>The value for the Service attribute was not provided in the ServiceHost directive.</value>
+ </data>
+ <data name="SharedEndpointReadDenied" xml:space="preserve">
+ <value>The service endpoint failed to listen on the URI '{0}' because access was denied. Verify that the current user is granted access in the appropriate allowAccounts section of SMSvcHost.exe.config.</value>
+ </data>
+ <data name="SharedEndpointReadNotFound" xml:space="preserve">
+ <value>The service endpoint failed to listen on the URI '{0}' because the shared memory section was not found. Verify that the '{1}' service is running.</value>
+ </data>
+ <data name="SharedManagerBase" xml:space="preserve">
+ <value>The TransportManager failed to listen on the supplied URI using the {0} service: {1}.</value>
+ </data>
+ <data name="SharedManagerServiceStartFailure" xml:space="preserve">
+ <value>failed to start the service ({0}). Refer to the Event Log for more details</value>
+ </data>
+ <data name="SharedManagerServiceStartFailureDisabled" xml:space="preserve">
+ <value>failed to start the service because it is disabled. An administrator can enable it by running 'sc.exe config {0} start= demand'.</value>
+ </data>
+ <data name="SharedManagerServiceStartFailureNoError" xml:space="preserve">
+ <value>failed to start the service. Refer to the Event Log for more details</value>
+ </data>
+ <data name="SharedManagerServiceLookupFailure" xml:space="preserve">
+ <value>failed to look up the service process in the SCM ({0})</value>
+ </data>
+ <data name="SharedManagerServiceSidLookupFailure" xml:space="preserve">
+ <value>failed to look up the service SID in the SCM ({0})</value>
+ </data>
+ <data name="SharedManagerServiceEndpointReadFailure" xml:space="preserve">
+ <value>failed to read the service's endpoint with native error code {0}. See inner exception for details</value>
+ </data>
+ <data name="SharedManagerServiceSecurityFailed" xml:space="preserve">
+ <value>the service failed the security checks</value>
+ </data>
+ <data name="SharedManagerUserSidLookupFailure" xml:space="preserve">
+ <value>failed to retrieve the UserSid of the service process ({0})</value>
+ </data>
+ <data name="SharedManagerCurrentUserSidLookupFailure" xml:space="preserve">
+ <value>failed to retrieve the UserSid of the current process</value>
+ </data>
+ <data name="SharedManagerLogonSidLookupFailure" xml:space="preserve">
+ <value>failed to retrieve the LogonSid of the service process ({0})</value>
+ </data>
+ <data name="SharedManagerDataConnectionFailure" xml:space="preserve">
+ <value>failed to establish a data connection to the service</value>
+ </data>
+ <data name="SharedManagerDataConnectionCreateFailure" xml:space="preserve">
+ <value>failed to create a data connection to the service</value>
+ </data>
+ <data name="SharedManagerDataConnectionPipeFailed" xml:space="preserve">
+ <value>failed to establish the data connection because of an I/O error</value>
+ </data>
+ <data name="SharedManagerVersionUnsupported" xml:space="preserve">
+ <value>the version is not supported by the service</value>
+ </data>
+ <data name="SharedManagerAllowDupHandleFailed" xml:space="preserve">
+ <value>failed to grant the PROCESS_DUP_HANDLE access right to the target service's account SID '{0}'.</value>
+ </data>
+ <data name="SharedManagerPathTooLong" xml:space="preserve">
+ <value>the URI is too long</value>
+ </data>
+ <data name="SharedManagerRegistrationQuotaExceeded" xml:space="preserve">
+ <value>the quota was exceeded</value>
+ </data>
+ <data name="SharedManagerProtocolUnsupported" xml:space="preserve">
+ <value>the protocol is not supported</value>
+ </data>
+ <data name="SharedManagerConflictingRegistration" xml:space="preserve">
+ <value>the URI is already registered with the service</value>
+ </data>
+ <data name="SharedManagerFailedToListen" xml:space="preserve">
+ <value>the service failed to listen</value>
+ </data>
+ <data name="Sharing_ConnectionDispatchFailed" xml:space="preserve">
+ <value>The message could not be dispatched to the service at address '{0}'. Refer to the server Event Log for more details</value>
+ </data>
+ <data name="Sharing_EndpointUnavailable" xml:space="preserve">
+ <value>The message could not be dispatched because the service at the endpoint address '{0}' is unavailable for the protocol of the address.</value>
+ </data>
+ <data name="Sharing_EmptyListenerEndpoint" xml:space="preserve">
+ <value>The endpoint address for the NT service '{0}' read from shared memory is empty.</value>
+ </data>
+ <data name="Sharing_ListenerProxyStopped" xml:space="preserve">
+ <value>The message could not be dispatched because the transport manager has been stopped. This can happen if the application is being recycled or disabled.</value>
+ </data>
+ <data name="UnexpectedEmptyElementExpectingClaim" xml:space="preserve">
+ <value>The '{0}' from the '{1}' namespace is empty and does not specify a valid identity claim. </value>
+ </data>
+ <data name="UnexpectedElementExpectingElement" xml:space="preserve">
+ <value>'{0}' from namespace '{1}' is not expected. Expecting element '{2}' from namespace '{3}'</value>
+ </data>
+ <data name="UnexpectedDuplicateElement" xml:space="preserve">
+ <value>'{0}' from namespace '{1}' is not expected to appear more than once</value>
+ </data>
+ <data name="UnsupportedSecurityPolicyAssertion" xml:space="preserve">
+ <value>An unsupported security policy assertion was detected during the security policy import: {0}</value>
+ </data>
+ <data name="MultipleIdentities" xml:space="preserve">
+ <value>The extensions cannot contain an Identity if one is supplied as a constructor argument.</value>
+ </data>
+ <data name="InvalidUriValue" xml:space="preserve">
+ <value>Value '{0}' provided for '{1}' from namespace '{2}' is an invalid absolute URI.</value>
+ </data>
+ <data name="BindingDoesNotSupportProtectionForRst" xml:space="preserve">
+ <value>The binding ('{0}','{1}') for contract ('{2}','{3}') is configured with SecureConversation, but the authentication mode is not able to provide the request/reply-based integrity and confidentiality required for the negotiation.</value>
+ </data>
+ <data name="TransportDoesNotProtectMessage" xml:space="preserve">
+ <value>The '{0}'.'{1}' binding for the '{2}'.'{3}' contract is configured with an authentication mode that requires transport level integrity and confidentiality. However the transport cannot provide integrity and confidentiality.</value>
+ </data>
+ <data name="BindingDoesNotSupportWindowsIdenityForImpersonation" xml:space="preserve">
+ <value>The contract operation '{0}' requires Windows identity for automatic impersonation. A Windows identity that represents the caller is not provided by binding ('{1}','{2}') for contract ('{3}','{4}'.</value>
+ </data>
+ <data name="ListenUriNotSet" xml:space="preserve">
+ <value>A listen URI must be specified in order to open this {0}.</value>
+ </data>
+ <data name="UnsupportedChannelInterfaceType" xml:space="preserve">
+ <value>Channel interface type '{0}' is not supported.</value>
+ </data>
+ <data name="TransportManagerOpen" xml:space="preserve">
+ <value>This property cannot be changed after the transport manager has been opened.</value>
+ </data>
+ <data name="TransportManagerNotOpen" xml:space="preserve">
+ <value>This operation is only valid after the transport manager has been opened.</value>
+ </data>
+ <data name="UnrecognizedIdentityType" xml:space="preserve">
+ <value>Unrecognized identity type Name='{0}', Namespace='{1}'.</value>
+ </data>
+ <data name="InvalidIdentityElement" xml:space="preserve">
+ <value>Cannot read the Identity element. The Identity type is not supported or the Identity element is empty.</value>
+ </data>
+ <data name="UnableToLoadCertificateIdentity" xml:space="preserve">
+ <value>Cannot load the X.509 certificate identity specified in the configuration.</value>
+ </data>
+ <data name="UnrecognizedClaimTypeForIdentity" xml:space="preserve">
+ <value>The ClaimType '{0}' is not recognized. Expected ClaimType '{1}'.</value>
+ </data>
+ <data name="AsyncCallbackException" xml:space="preserve">
+ <value>An AsyncCallback threw an exception.</value>
+ </data>
+ <data name="SendCannotBeCalledAfterCloseOutputSession" xml:space="preserve">
+ <value>You cannot Send messages on a channel after CloseOutputSession has been called.</value>
+ </data>
+ <data name="CommunicationObjectCannotBeModifiedInState" xml:space="preserve">
+ <value>The communication object, {0}, cannot be modified while it is in the {1} state.</value>
+ </data>
+ <data name="CommunicationObjectCannotBeModified" xml:space="preserve">
+ <value>The communication object, {0}, cannot be modified unless it is in the Created state.</value>
+ </data>
+ <data name="CommunicationObjectCannotBeUsed" xml:space="preserve">
+ <value>The communication object, {0}, is in the {1} state. Communication objects cannot be used for communication unless they are in the Opened state.</value>
+ </data>
+ <data name="CommunicationObjectFaulted1" xml:space="preserve">
+ <value>The communication object, {0}, cannot be used for communication because it is in the Faulted state.</value>
+ </data>
+ <data name="CommunicationObjectFaultedStack2" xml:space="preserve">
+ <value>The communication object, {0}, cannot be used for communication because it is in the Faulted state: {1}</value>
+ </data>
+ <data name="CommunicationObjectAborted1" xml:space="preserve">
+ <value>The communication object, {0}, cannot be used for communication because it has been Aborted.</value>
+ </data>
+ <data name="CommunicationObjectAbortedStack2" xml:space="preserve">
+ <value>The communication object, {0}, cannot be used for communication because it has been Aborted: {1}</value>
+ </data>
+ <data name="CommunicationObjectBaseClassMethodNotCalled" xml:space="preserve">
+ <value>The communication object, {0}, has overridden the virtual function {1} but it does not call version defined in the base class.</value>
+ </data>
+ <data name="CommunicationObjectInInvalidState" xml:space="preserve">
+ <value>The communication object, {0}, is not part of WCF and is in an unsupported state '{1}'. This indicates an internal error in the implementation of that communication object.</value>
+ </data>
+ <data name="CommunicationObjectCloseInterrupted1" xml:space="preserve">
+ <value>The communication object, {0}, cannot be used due to an error that occurred during close.</value>
+ </data>
+ <data name="ChannelFactoryCannotBeUsedToCreateChannels" xml:space="preserve">
+ <value>A call to IChannelFactory.CreateChannel made on an object of type {0} failed because Open has not been called on this object.</value>
+ </data>
+ <data name="ChannelParametersCannotBeModified" xml:space="preserve">
+ <value>Cannot modify channel parameters because the {0} is in the {1} state. This operation is only supported in the Created state.</value>
+ </data>
+ <data name="ChannelParametersCannotBePropagated" xml:space="preserve">
+ <value>Cannot propagate channel parameters because the {0} is in the {1} state. This operation is only supported in the Opening or Opened state when the collection is locked.</value>
+ </data>
+ <data name="OneWayInternalTypeNotSupported" xml:space="preserve">
+ <value>Binding '{0}' is not configured properly. OneWayBindingElement requires an inner binding element that supports IRequestChannel/IReplyChannel or IDuplexSessionChannel. </value>
+ </data>
+ <data name="ChannelTypeNotSupported" xml:space="preserve">
+ <value>The specified channel type {0} is not supported by this channel manager.</value>
+ </data>
+ <data name="SecurityContextMissing" xml:space="preserve">
+ <value>SecurityContext for the UltimateReceiver role is missing from the SecurityContextProperty of the request message with action '{0}'.</value>
+ </data>
+ <data name="SecurityContextDoesNotAllowImpersonation" xml:space="preserve">
+ <value>Cannot start impersonation because the SecurityContext for the UltimateReceiver role from the request message with the '{0}' action is not mapped to a Windows identity.</value>
+ </data>
+ <data name="InvalidEnumValue" xml:space="preserve">
+ <value>Unexpected internal enum value: {0}.</value>
+ </data>
+ <data name="InvalidDecoderStateMachine" xml:space="preserve">
+ <value>Invalid decoder state machine.</value>
+ </data>
+ <data name="OperationPropertyIsRequiredForAttributeGeneration" xml:space="preserve">
+ <value>Operation property of OperationAttributeGenerationContext is required to generate an attribute based on settings. </value>
+ </data>
+ <data name="InvalidMembershipProviderSpecifiedInConfig" xml:space="preserve">
+ <value>The username/password Membership provider {0} specified in the configuration is invalid. No such provider was found registered under system.web/membership/providers.</value>
+ </data>
+ <data name="InvalidRoleProviderSpecifiedInConfig" xml:space="preserve">
+ <value>The RoleProvider {0} specified in the configuration is invalid. No such provider was found registered under system.web/roleManager/providers.</value>
+ </data>
+ <data name="ObjectDisposed" xml:space="preserve">
+ <value>The {0} object has been disposed.</value>
+ </data>
+ <data name="InvalidReaderPositionOnCreateMessage" xml:space="preserve">
+ <value>The XmlReader used for the body of the message must be positioned on an element.</value>
+ </data>
+ <data name="DuplicateMessageProperty" xml:space="preserve">
+ <value>A property with the name '{0}' already exists.</value>
+ </data>
+ <data name="MessagePropertyNotFound" xml:space="preserve">
+ <value>A property with the name '{0}' is not present.</value>
+ </data>
+ <data name="HeaderAlreadyUnderstood" xml:space="preserve">
+ <value>The message header with name '{0}' and namespace '{1}' is already present in the set of understood headers.</value>
+ </data>
+ <data name="HeaderAlreadyNotUnderstood" xml:space="preserve">
+ <value>The message header with name '{0}' and namespace '{1}' is not present in the set of understood headers.</value>
+ </data>
+ <data name="MultipleMessageHeaders" xml:space="preserve">
+ <value>Multiple headers with name '{0}' and namespace '{1}' found.</value>
+ </data>
+ <data name="MultipleMessageHeadersWithActor" xml:space="preserve">
+ <value>Multiple headers with name '{0}' and namespace '{1}' and role '{2}' found.</value>
+ </data>
+ <data name="MultipleRelatesToHeaders" xml:space="preserve">
+ <value>Multiple RelatesTo headers with relationship '{0}' found. Only one is allowed per relationship.</value>
+ </data>
+ <data name="ExtraContentIsPresentInFaultDetail" xml:space="preserve">
+ <value>Additional XML content is present in the fault detail element. Only a single element is allowed.</value>
+ </data>
+ <data name="MessageIsEmpty" xml:space="preserve">
+ <value>The body of the message cannot be read because it is empty.</value>
+ </data>
+ <data name="MessageClosed" xml:space="preserve">
+ <value>Message is closed.</value>
+ </data>
+ <data name="StreamClosed" xml:space="preserve">
+ <value>The operation cannot be completed because the stream is closed.</value>
+ </data>
+ <data name="BodyWriterReturnedIsNotBuffered" xml:space="preserve">
+ <value>The body writer returned from OnCreateBufferedCopy was not buffered.</value>
+ </data>
+ <data name="BodyWriterCanOnlyBeWrittenOnce" xml:space="preserve">
+ <value>The body writer does not support writing more than once because it is not buffered.</value>
+ </data>
+ <data name="RstrKeySizeNotProvided" xml:space="preserve">
+ <value>KeySize element not present in RequestSecurityTokenResponse.</value>
+ </data>
+ <data name="RequestMessageDoesNotHaveAMessageID" xml:space="preserve">
+ <value>A reply message cannot be created because the request message does not have a MessageID.</value>
+ </data>
+ <data name="HeaderNotFound" xml:space="preserve">
+ <value>There is not a header with name {0} and namespace {1} in the message.</value>
+ </data>
+ <data name="MessageBufferIsClosed" xml:space="preserve">
+ <value>MessageBuffer is closed.</value>
+ </data>
+ <data name="MessageTextEncodingNotSupported" xml:space="preserve">
+ <value>The text encoding '{0}' used in the text message format is not supported.</value>
+ </data>
+ <data name="AtLeastOneFaultReasonMustBeSpecified" xml:space="preserve">
+ <value>At least one fault reason must be specified.</value>
+ </data>
+ <data name="NoNullTranslations" xml:space="preserve">
+ <value>The translation set cannot contain nulls.</value>
+ </data>
+ <data name="FaultDoesNotHaveAnyDetail" xml:space="preserve">
+ <value>The fault does not have detail information.</value>
+ </data>
+ <data name="InvalidXmlQualifiedName" xml:space="preserve">
+ <value>Expected XML qualified name, found '{0}'.</value>
+ </data>
+ <data name="UnboundPrefixInQName" xml:space="preserve">
+ <value>Unbound prefix used in qualified name '{0}'.</value>
+ </data>
+ <data name="MessageBodyIsUnknown" xml:space="preserve">
+ <value>...</value>
+ </data>
+ <data name="MessageBodyIsStream" xml:space="preserve">
+ <value>... stream ...</value>
+ </data>
+ <data name="MessageBodyToStringError" xml:space="preserve">
+ <value>... Error reading body: {0}: {1} ...</value>
+ </data>
+ <data name="NoMatchingTranslationFoundForFaultText" xml:space="preserve">
+ <value>The fault reason does not contain any text translations.</value>
+ </data>
+ <data name="CannotDetermineSPNBasedOnAddress" xml:space="preserve">
+ <value>Client cannot determine the Service Principal Name based on the identity in the target address '{0}' for the purpose of SspiNegotiation/Kerberos. The target address identity must be a UPN identity (like acmedomain\alice) or SPN identity (like host/bobs-machine).</value>
+ </data>
+ <data name="XmlLangAttributeMissing" xml:space="preserve">
+ <value>Required xml:lang attribute value is missing.</value>
+ </data>
+ <data name="EncoderUnrecognizedCharSet" xml:space="preserve">
+ <value>Unrecognized charSet '{0}' in contentType.</value>
+ </data>
+ <data name="EncoderUnrecognizedContentType" xml:space="preserve">
+ <value>Unrecognized contentType ({0}). Expected: {1}.</value>
+ </data>
+ <data name="EncoderBadContentType" xml:space="preserve">
+ <value>Cannot process contentType.</value>
+ </data>
+ <data name="EncoderEnvelopeVersionMismatch" xml:space="preserve">
+ <value>The envelope version of the incoming message ({0}) does not match that of the encoder ({1}). Make sure the binding is configured with the same version as the expected messages.</value>
+ </data>
+ <data name="EncoderMessageVersionMismatch" xml:space="preserve">
+ <value>The message version of the outgoing message ({0}) does not match that of the encoder ({1}). Make sure the binding is configured with the same version as the message.</value>
+ </data>
+ <data name="MtomEncoderBadMessageVersion" xml:space="preserve">
+ <value>MessageVersion '{0}' not supported by MTOM encoder.</value>
+ </data>
+ <data name="ReadNotSupported" xml:space="preserve">
+ <value>Read is not supported on this stream.</value>
+ </data>
+ <data name="SeekNotSupported" xml:space="preserve">
+ <value>Seek is not supported on this stream.</value>
+ </data>
+ <data name="WriterAsyncWritePending" xml:space="preserve">
+ <value>An asynchronous write is pending on the stream. Ensure that there are no uncompleted asynchronous writes before attempting the next write. </value>
+ </data>
+ <data name="ChannelInitializationTimeout" xml:space="preserve">
+ <value>A newly accepted connection did not receive initialization data from the sender within the configured ChannelInitializationTimeout ({0}). As a result, the connection will be aborted. If you are on a highly congested network, or your sending machine is heavily loaded, consider increasing this value or load-balancing your server.</value>
+ </data>
+ <data name="SocketCloseReadTimeout" xml:space="preserve">
+ <value>The remote endpoint of the socket ({0}) did not respond to a close request within the allotted timeout ({1}). It is likely that the remote endpoint is not calling Close after receiving the EOF signal (null) from Receive. The time allotted to this operation may have been a portion of a longer timeout.</value>
+ </data>
+ <data name="SocketCloseReadReceivedData" xml:space="preserve">
+ <value>A graceful close was attempted on the socket, but the other side ({0}) is still sending data.</value>
+ </data>
+ <data name="PipeCantCloseWithPendingWrite" xml:space="preserve">
+ <value>The pipe cannot be closed while a write to the pipe is pending.</value>
+ </data>
+ <data name="PipeShutdownWriteError" xml:space="preserve">
+ <value>The shutdown indicator could not be written to the pipe. The application on the other end of the pipe may not be listening for it. The pipe will still be closed.</value>
+ </data>
+ <data name="PipeShutdownReadError" xml:space="preserve">
+ <value>The shutdown indicator was not received from the pipe. The application on the other end of the pipe may not have sent it. The pipe will still be closed.</value>
+ </data>
+ <data name="PipeNameCanNotBeAccessed" xml:space="preserve">
+ <value>The pipe name could not be obtained for the pipe URI: {0}</value>
+ </data>
+ <data name="PipeNameCanNotBeAccessed2" xml:space="preserve">
+ <value>The pipe name could not be obtained for {0}.</value>
+ </data>
+ <data name="PipeModeChangeFailed" xml:space="preserve">
+ <value>The pipe was not able to be set to message mode: {0}</value>
+ </data>
+ <data name="PipeCloseFailed" xml:space="preserve">
+ <value>The pipe could not close gracefully. This may be caused by the application on the other end of the pipe exiting.</value>
+ </data>
+ <data name="PipeAlreadyShuttingDown" xml:space="preserve">
+ <value>The pipe cannot be written to because it is already in the process of shutting down.</value>
+ </data>
+ <data name="PipeSignalExpected" xml:space="preserve">
+ <value>The read from the pipe expected just a signal, but received actual data.</value>
+ </data>
+ <data name="PipeAlreadyClosing" xml:space="preserve">
+ <value>The pipe cannot be written to or read from because it is already in the process of being closed.</value>
+ </data>
+ <data name="PipeAcceptFailed" xml:space="preserve">
+ <value>Server cannot accept pipe: {0}</value>
+ </data>
+ <data name="PipeListenFailed" xml:space="preserve">
+ <value>Cannot listen on pipe '{0}': {1}</value>
+ </data>
+ <data name="PipeNameInUse" xml:space="preserve">
+ <value>Cannot listen on pipe name '{0}' because another pipe endpoint is already listening on that name.</value>
+ </data>
+ <data name="PipeNameCantBeReserved" xml:space="preserve">
+ <value>Cannot listen on pipe '{0}' because the pipe name could not be reserved: {1}</value>
+ </data>
+ <data name="PipeListenerDisposed" xml:space="preserve">
+ <value>The pipe listener has been disposed.</value>
+ </data>
+ <data name="PipeListenerNotListening" xml:space="preserve">
+ <value>Connections cannot be created until the pipe has started listening. Call Listen() before attempting to accept a connection.</value>
+ </data>
+ <data name="PipeConnectAddressFailed" xml:space="preserve">
+ <value>A pipe endpoint exists for '{0}', but the connect failed: {1}</value>
+ </data>
+ <data name="PipeConnectFailed" xml:space="preserve">
+ <value>Cannot connect to endpoint '{0}'. </value>
+ </data>
+ <data name="PipeConnectTimedOut" xml:space="preserve">
+ <value>Cannot connect to endpoint '{0}' within the allotted timeout of {1}. The time allotted to this operation may have been a portion of a longer timeout.</value>
+ </data>
+ <data name="PipeConnectTimedOutServerTooBusy" xml:space="preserve">
+ <value>Cannot connect to endpoint '{0}' within the allotted timeout of {1}. The server has likely reached the MaxConnections quota and is too busy to accept new connections. The time allotted to this operation may have been a portion of a longer timeout.</value>
+ </data>
+ <data name="PipeEndpointNotFound" xml:space="preserve">
+ <value>The pipe endpoint '{0}' could not be found on your local machine. </value>
+ </data>
+ <data name="PipeUriSchemeWrong" xml:space="preserve">
+ <value>URIs used with pipes must use the scheme: 'net.pipe'.</value>
+ </data>
+ <data name="PipeWriteIncomplete" xml:space="preserve">
+ <value>The pipe write did not write all the bytes.</value>
+ </data>
+ <data name="PipeClosed" xml:space="preserve">
+ <value>The operation cannot be completed because the pipe was closed. This may have been caused by the application on the other end of the pipe exiting.</value>
+ </data>
+ <data name="PipeReadTimedOut" xml:space="preserve">
+ <value>The read from the pipe did not complete within the allotted timeout of {0}. The time allotted to this operation may have been a portion of a longer timeout.</value>
+ </data>
+ <data name="PipeWriteTimedOut" xml:space="preserve">
+ <value>The write to the pipe did not complete within the allotted timeout of {0}. The time allotted to this operation may have been a portion of a longer timeout.</value>
+ </data>
+ <data name="PipeConnectionAbortedReadTimedOut" xml:space="preserve">
+ <value>The pipe connection was aborted because an asynchronous read from the pipe did not complete within the allotted timeout of {0}. The time allotted to this operation may have been a portion of a longer timeout.</value>
+ </data>
+ <data name="PipeConnectionAbortedWriteTimedOut" xml:space="preserve">
+ <value>The pipe connection was aborted because an asynchronous write to the pipe did not complete within the allotted timeout of {0}. The time allotted to this operation may have been a portion of a longer timeout.</value>
+ </data>
+ <data name="PipeWriteError" xml:space="preserve">
+ <value>There was an error writing to the pipe: {0}.</value>
+ </data>
+ <data name="PipeReadError" xml:space="preserve">
+ <value>There was an error reading from the pipe: {0}.</value>
+ </data>
+ <data name="PipeUnknownWin32Error" xml:space="preserve">
+ <value>Unrecognized error {0} (0x{1})</value>
+ </data>
+ <data name="PipeKnownWin32Error" xml:space="preserve">
+ <value>{0} ({1}, 0x{2})</value>
+ </data>
+ <data name="PipeWritePending" xml:space="preserve">
+ <value>There is already a write in progress for the pipe. Wait for the first operation to complete before attempting to write again.</value>
+ </data>
+ <data name="PipeReadPending" xml:space="preserve">
+ <value>There is already a read in progress for the pipe. Wait for the first operation to complete before attempting to read again.</value>
+ </data>
+ <data name="PipeDuplicationFailed" xml:space="preserve">
+ <value>There was an error duplicating the.</value>
+ </data>
+ <data name="SessionValueInvalid" xml:space="preserve">
+ <value>The Session value '{0}' is invalid. Please specify 'CurrentSession','ServiceSession' or a valid non-negative Windows Session Id.</value>
+ </data>
+ <data name="PackageFullNameInvalid" xml:space="preserve">
+ <value>The package full name '{0}' is invalid.</value>
+ </data>
+ <data name="SocketAbortedReceiveTimedOut" xml:space="preserve">
+ <value>The socket was aborted because an asynchronous receive from the socket did not complete within the allotted timeout of {0}. The time allotted to this operation may have been a portion of a longer timeout.</value>
+ </data>
+ <data name="SocketAbortedSendTimedOut" xml:space="preserve">
+ <value>The socket connection was aborted because an asynchronous send to the socket did not complete within the allotted timeout of {0}. The time allotted to this operation may have been a portion of a longer timeout.</value>
+ </data>
+ <data name="OperationInvalidBeforeSecurityNegotiation" xml:space="preserve">
+ <value>This operation is not valid until security negotiation is complete.</value>
+ </data>
+ <data name="FramingError" xml:space="preserve">
+ <value>Error while reading message framing format at position {0} of stream (state: {1})</value>
+ </data>
+ <data name="FramingPrematureEOF" xml:space="preserve">
+ <value>More data was expected, but EOF was reached.</value>
+ </data>
+ <data name="FramingRecordTypeMismatch" xml:space="preserve">
+ <value>Expected record type '{0}', found '{1}'.</value>
+ </data>
+ <data name="FramingVersionNotSupported" xml:space="preserve">
+ <value>Framing major version {0} is not supported.</value>
+ </data>
+ <data name="FramingModeNotSupported" xml:space="preserve">
+ <value>Framing mode {0} is not supported.</value>
+ </data>
+ <data name="FramingSizeTooLarge" xml:space="preserve">
+ <value>Specified size is too large for this implementation.</value>
+ </data>
+ <data name="FramingViaTooLong" xml:space="preserve">
+ <value>The framing via size ({0}) exceeds the quota.</value>
+ </data>
+ <data name="FramingViaNotUri" xml:space="preserve">
+ <value>The framing via ({0}) is not a valid URI.</value>
+ </data>
+ <data name="FramingFaultTooLong" xml:space="preserve">
+ <value>The framing fault size ({0}) exceeds the quota.</value>
+ </data>
+ <data name="FramingContentTypeTooLong" xml:space="preserve">
+ <value>The framing content type size ({0}) exceeds the quota.</value>
+ </data>
+ <data name="FramingValueNotAvailable" xml:space="preserve">
+ <value>The value cannot be accessed because it has not yet been fully decoded.</value>
+ </data>
+ <data name="FramingAtEnd" xml:space="preserve">
+ <value>An attempt was made to decode a value after the framing stream was ended.</value>
+ </data>
+ <data name="RemoteSecurityNotNegotiatedOnStreamUpgrade" xml:space="preserve">
+ <value>Stream Security is required at {0}, but no security context was negotiated. This is likely caused by the remote endpoint missing a StreamSecurityBindingElement from its binding.</value>
+ </data>
+ <data name="BinaryEncoderSessionTooLarge" xml:space="preserve">
+ <value>The binary encoder session information exceeded the maximum size quota ({0}). To increase this quota, use the MaxSessionSize property on the BinaryMessageEncodingBindingElement.</value>
+ </data>
+ <data name="BinaryEncoderSessionInvalid" xml:space="preserve">
+ <value>The binary encoder session is not valid. There was an error decoding a previous message.</value>
+ </data>
+ <data name="BinaryEncoderSessionMalformed" xml:space="preserve">
+ <value>The binary encoder session information is not properly formed.</value>
+ </data>
+ <data name="ReceiveShutdownReturnedFault" xml:space="preserve">
+ <value>The channel received an unexpected fault input message while closing. The fault reason given is: '{0}'</value>
+ </data>
+ <data name="ReceiveShutdownReturnedLargeFault" xml:space="preserve">
+ <value>The channel received an unexpected fault input message with Action = '{0}' while closing. You should only close your channel when you are not expecting any more input messages.</value>
+ </data>
+ <data name="ReceiveShutdownReturnedMessage" xml:space="preserve">
+ <value>The channel received an unexpected input message with Action '{0}' while closing. You should only close your channel when you are not expecting any more input messages.</value>
+ </data>
+ <data name="MaxReceivedMessageSizeExceeded" xml:space="preserve">
+ <value>The maximum message size quota for incoming messages ({0}) has been exceeded. To increase the quota, use the MaxReceivedMessageSize property on the appropriate binding element.</value>
+ </data>
+ <data name="MaxSentMessageSizeExceeded" xml:space="preserve">
+ <value>The maximum message size quota for outgoing messages ({0}) has been exceeded.</value>
+ </data>
+ <data name="FramingMaxMessageSizeExceeded" xml:space="preserve">
+ <value>The maximum message size quota for incoming messages has been exceeded for the remote channel. See the server logs for more details.</value>
+ </data>
+ <data name="StreamDoesNotSupportTimeout" xml:space="preserve">
+ <value>TimeoutStream requires an inner Stream that supports timeouts; its CanTimeout property must be true.</value>
+ </data>
+ <data name="FilterExists" xml:space="preserve">
+ <value>The filter already exists in the filter table.</value>
+ </data>
+ <data name="FilterUnexpectedError" xml:space="preserve">
+ <value>An internal error has occurred. Unexpected error modifying filter table.</value>
+ </data>
+ <data name="FilterNodeQuotaExceeded" xml:space="preserve">
+ <value>The number of XML infoset nodes inspected by the navigator has exceeded the quota ({0}).</value>
+ </data>
+ <data name="FilterCapacityNegative" xml:space="preserve">
+ <value>Value cannot be negative.</value>
+ </data>
+ <data name="ActionFilterEmptyList" xml:space="preserve">
+ <value>The set of actions cannot be empty.</value>
+ </data>
+ <data name="FilterUndefinedPrefix" xml:space="preserve">
+ <value>The prefix '{0}' is not defined.</value>
+ </data>
+ <data name="FilterMultipleMatches" xml:space="preserve">
+ <value>Multiple filters matched.</value>
+ </data>
+ <data name="FilterTableTypeMismatch" xml:space="preserve">
+ <value>The type of IMessageFilterTable created for a particular Filter type must always be the same.</value>
+ </data>
+ <data name="FilterTableInvalidForLookup" xml:space="preserve">
+ <value>The MessageFilterTable state is corrupt. The requested lookup cannot be performed.</value>
+ </data>
+ <data name="FilterBadTableType" xml:space="preserve">
+ <value>The IMessageFilterTable created for a Filter cannot be a MessageFilterTable or a subclass of MessageFilterTable.</value>
+ </data>
+ <data name="FilterQuotaRange" xml:space="preserve">
+ <value>NodeQuota must be greater than 0.</value>
+ </data>
+ <data name="FilterEmptyString" xml:space="preserve">
+ <value>Parameter value cannot be an empty string.</value>
+ </data>
+ <data name="FilterInvalidInner" xml:space="preserve">
+ <value>Required inner element '{0}' was not found.</value>
+ </data>
+ <data name="FilterInvalidAttribute" xml:space="preserve">
+ <value>Invalid attribute on the XPath.</value>
+ </data>
+ <data name="FilterInvalidDialect" xml:space="preserve">
+ <value>When present, the dialect attribute must have the value '{0}'.</value>
+ </data>
+ <data name="FilterCouldNotCompile" xml:space="preserve">
+ <value>Could not compile the XPath expression '{0}' with the given XsltContext.</value>
+ </data>
+ <data name="FilterReaderNotStartElem" xml:space="preserve">
+ <value>XmlReader not positioned at a start element.</value>
+ </data>
+ <data name="SeekableMessageNavInvalidPosition" xml:space="preserve">
+ <value>The position is not valid for this navigator.</value>
+ </data>
+ <data name="SeekableMessageNavNonAtomized" xml:space="preserve">
+ <value>Cannot call '{0}' on a non-atomized navigator.</value>
+ </data>
+ <data name="SeekableMessageNavIDNotSupported" xml:space="preserve">
+ <value>XML unique ID not supported.</value>
+ </data>
+ <data name="SeekableMessageNavBodyForbidden" xml:space="preserve">
+ <value>A filter has attempted to access the body of a Message. Use a MessageBuffer instead if body filtering is required.</value>
+ </data>
+ <data name="SeekableMessageNavOverrideForbidden" xml:space="preserve">
+ <value>Not allowed to override prefix '{0}'.</value>
+ </data>
+ <data name="QueryNotImplemented" xml:space="preserve">
+ <value>The function '{0}' is not implemented.</value>
+ </data>
+ <data name="QueryNotSortable" xml:space="preserve">
+ <value>XPathNavigator positions cannot be compared.</value>
+ </data>
+ <data name="QueryMustBeSeekable" xml:space="preserve">
+ <value>XPathNavigator must be a SeekableXPathNavigator.</value>
+ </data>
+ <data name="QueryContextNotSupportedInSequences" xml:space="preserve">
+ <value>Context node is not supported in node sequences.</value>
+ </data>
+ <data name="QueryFunctionTypeNotSupported" xml:space="preserve">
+ <value>IXsltContextFunction return type '{0}' not supported.</value>
+ </data>
+ <data name="QueryVariableTypeNotSupported" xml:space="preserve">
+ <value>IXsltContextVariable type '{0}' not supported.</value>
+ </data>
+ <data name="QueryVariableNull" xml:space="preserve">
+ <value>IXsltContextVariables cannot return null.</value>
+ </data>
+ <data name="QueryFunctionStringArg" xml:space="preserve">
+ <value>The argument to an IXsltContextFunction could not be converted to a string.</value>
+ </data>
+ <data name="QueryItemAlreadyExists" xml:space="preserve">
+ <value>An internal error has occurred. Item already exists.</value>
+ </data>
+ <data name="QueryBeforeNodes" xml:space="preserve">
+ <value>Positioned before first element.</value>
+ </data>
+ <data name="QueryAfterNodes" xml:space="preserve">
+ <value>Positioned after last element.</value>
+ </data>
+ <data name="QueryIteratorOutOfScope" xml:space="preserve">
+ <value>The XPathNodeIterator has been invalidated. XPathNodeIterators passed as arguments to IXsltContextFunctions are only valid within the function. They cannot be cached for later use or returned as the result of the function.</value>
+ </data>
+ <data name="QueryCantGetStringForMovedIterator" xml:space="preserve">
+ <value>The string value can't be determined because the XPathNodeIterator has been moved past the first node.</value>
+ </data>
+ <data name="MessageVersionToStringFormat" xml:space="preserve">
+ <value>{0} {1}</value>
+ </data>
+ <data name="Addressing10ToStringFormat" xml:space="preserve">
+ <value>Addressing10 ({0})</value>
+ </data>
+ <data name="Addressing200408ToStringFormat" xml:space="preserve">
+ <value>Addressing200408 ({0})</value>
+ </data>
+ <data name="AddressingNoneToStringFormat" xml:space="preserve">
+ <value>AddressingNone ({0})</value>
+ </data>
+ <data name="AddressingVersionNotSupported" xml:space="preserve">
+ <value>Addressing Version '{0}' is not supported.</value>
+ </data>
+ <data name="SupportedAddressingModeNotSupported" xml:space="preserve">
+ <value>The '{0}' addressing mode is not supported.</value>
+ </data>
+ <data name="Soap11ToStringFormat" xml:space="preserve">
+ <value>Soap11 ({0})</value>
+ </data>
+ <data name="Soap12ToStringFormat" xml:space="preserve">
+ <value>Soap12 ({0})</value>
+ </data>
+ <data name="EnvelopeNoneToStringFormat" xml:space="preserve">
+ <value>EnvelopeNone ({0})</value>
+ </data>
+ <data name="MessagePropertyReturnedNullCopy" xml:space="preserve">
+ <value>The IMessageProperty could not be copied. CreateCopy returned null.</value>
+ </data>
+ <data name="MessageVersionUnknown" xml:space="preserve">
+ <value>Unrecognized message version.</value>
+ </data>
+ <data name="EnvelopeVersionUnknown" xml:space="preserve">
+ <value>Unrecognized envelope version: {0}.</value>
+ </data>
+ <data name="EnvelopeVersionNotSupported" xml:space="preserve">
+ <value>Envelope Version '{0}' is not supported.</value>
+ </data>
+ <data name="CannotDetectAddressingVersion" xml:space="preserve">
+ <value>Cannot detect WS-Addressing version. EndpointReference does not start with an Element.</value>
+ </data>
+ <data name="HeadersCannotBeAddedToEnvelopeVersion" xml:space="preserve">
+ <value>Envelope Version '{0}' does not support adding Message Headers.</value>
+ </data>
+ <data name="AddressingHeadersCannotBeAddedToAddressingVersion" xml:space="preserve">
+ <value>Addressing Version '{0}' does not support adding WS-Addressing headers.</value>
+ </data>
+ <data name="AddressingExtensionInBadNS" xml:space="preserve">
+ <value>The element '{0}' in namespace '{1}' is not valid. This either means that element '{0}' is a duplicate element, or that it is not a legal extension because extension elements cannot be in the addressing namespace.</value>
+ </data>
+ <data name="MessageHeaderVersionNotSupported" xml:space="preserve">
+ <value>The '{0}' header cannot be added because it does not support the specified message version '{1}'.</value>
+ </data>
+ <data name="MessageHasBeenCopied" xml:space="preserve">
+ <value>This message cannot support the operation because it has been copied.</value>
+ </data>
+ <data name="MessageHasBeenWritten" xml:space="preserve">
+ <value>This message cannot support the operation because it has been written.</value>
+ </data>
+ <data name="MessageHasBeenRead" xml:space="preserve">
+ <value>This message cannot support the operation because it has been read.</value>
+ </data>
+ <data name="InvalidMessageState" xml:space="preserve">
+ <value>An internal error has occurred. Invalid MessageState.</value>
+ </data>
+ <data name="MessageBodyReaderInvalidReadState" xml:space="preserve">
+ <value>The body reader is in ReadState '{0}' and cannot be consumed.</value>
+ </data>
+ <data name="XmlBufferQuotaExceeded" xml:space="preserve">
+ <value>The size necessary to buffer the XML content exceeded the buffer quota.</value>
+ </data>
+ <data name="XmlBufferInInvalidState" xml:space="preserve">
+ <value>An internal error has occurred. The XML buffer is not in the correct state to perform the operation.</value>
+ </data>
+ <data name="MessageBodyMissing" xml:space="preserve">
+ <value>A body element was not found inside the message envelope.</value>
+ </data>
+ <data name="MessageHeaderVersionMismatch" xml:space="preserve">
+ <value>The version of the header(s) ({0}) differs from the version of the message ({1}).</value>
+ </data>
+ <data name="ManualAddressingRequiresAddressedMessages" xml:space="preserve">
+ <value>Manual addressing is enabled on this factory, so all messages sent must be pre-addressed.</value>
+ </data>
+ <data name="OneWayHeaderNotFound" xml:space="preserve">
+ <value>A one-way header was expected on this message and none was found. It is possible that your bindings are mismatched.</value>
+ </data>
+ <data name="ReceiveTimedOut" xml:space="preserve">
+ <value>Receive on local address {0} timed out after {1}. The time allotted to this operation may have been a portion of a longer timeout.</value>
+ </data>
+ <data name="ReceiveTimedOut2" xml:space="preserve">
+ <value>Receive timed out after {0}. The time allotted to this operation may have been a portion of a longer timeout.</value>
+ </data>
+ <data name="WaitForMessageTimedOut" xml:space="preserve">
+ <value>WaitForMessage timed out after {0}. The time allotted to this operation may have been a portion of a longer timeout.</value>
+ </data>
+ <data name="ReceiveTimedOutNoLocalAddress" xml:space="preserve">
+ <value>Receive timed out after {0}. The time allotted to this operation may have been a portion of a longer timeout.</value>
+ </data>
+ <data name="ReceiveRequestTimedOutNoLocalAddress" xml:space="preserve">
+ <value>Receive request timed out after {0}. The time allotted to this operation may have been a portion of a longer timeout.</value>
+ </data>
+ <data name="ReceiveRequestTimedOut" xml:space="preserve">
+ <value>Receive request on local address {0} timed out after {1}. The time allotted to this operation may have been a portion of a longer timeout.</value>
+ </data>
+ <data name="SendToViaTimedOut" xml:space="preserve">
+ <value>Sending to via {0} timed out after {1}. The time allotted to this operation may have been a portion of a longer timeout.</value>
+ </data>
+ <data name="CloseTimedOut" xml:space="preserve">
+ <value>Close timed out after {0}. Increase the timeout value passed to the call to Close or increase the CloseTimeout value on the Binding. The time allotted to this operation may have been a portion of a longer timeout.</value>
+ </data>
+ <data name="OpenTimedOutEstablishingTransportSession" xml:space="preserve">
+ <value>Open timed out after {0} while establishing a transport session to {1}. The time allotted to this operation may have been a portion of a longer timeout.</value>
+ </data>
+ <data name="RequestTimedOutEstablishingTransportSession" xml:space="preserve">
+ <value>Request timed out after {0} while establishing a transport connection to {1}. The time allotted to this operation may have been a portion of a longer timeout.</value>
+ </data>
+ <data name="TcpConnectingToViaTimedOut" xml:space="preserve">
+ <value>Connecting to via {0} timed out after {1}. Connection attempts were made to {2} of {3} available addresses ({4}). Check the RemoteAddress of your channel and verify that the DNS records for this endpoint correspond to valid IP Addresses. The time allotted to this operation may have been a portion of a longer timeout.</value>
+ </data>
+ <data name="RequestChannelSendTimedOut" xml:space="preserve">
+ <value>The request channel timed out attempting to send after {0}. Increase the timeout value passed to the call to Request or increase the SendTimeout value on the Binding. The time allotted to this operation may have been a portion of a longer timeout.</value>
+ </data>
+ <data name="RequestChannelWaitForReplyTimedOut" xml:space="preserve">
+ <value>The request channel timed out while waiting for a reply after {0}. Increase the timeout value passed to the call to Request or increase the SendTimeout value on the Binding. The time allotted to this operation may have been a portion of a longer timeout.</value>
+ </data>
+ <data name="HttpTransportCannotHaveMultipleAuthenticationSchemes" xml:space="preserve">
+ <value>The policy being imported for contract '{0}:{1}' contains multiple HTTP authentication scheme assertions. Since at most one such assertion is allowed, policy import has failed. This may be resolved by updating the policy to contain no more than one HTTP authentication scheme assertion.</value>
+ </data>
+ <data name="MultipleCCbesInParameters" xml:space="preserve">
+ <value>More than one '{0}' objects were found in the BindingParameters of the BindingContext. This is usually caused by having multiple '{0}' objects in a CustomBinding. Remove all but one of these elements.</value>
+ </data>
+ <data name="CookieContainerBindingElementNeedsHttp" xml:space="preserve">
+ <value>The '{0}' can only be used with HTTP (or HTTPS) transport.</value>
+ </data>
+ <data name="HttpIfModifiedSinceParseError" xml:space="preserve">
+ <value>The value specified, '{0}', for the If-Modified-Since header does not parse into a valid date. Check the property value and ensure that it is of the proper format.</value>
+ </data>
+ <data name="HttpSoapActionMismatch" xml:space="preserve">
+ <value>The SOAP action specified on the message, '{0}', does not match the action specified on the HttpRequestMessageProperty, '{1}'.</value>
+ </data>
+ <data name="HttpSoapActionMismatchContentType" xml:space="preserve">
+ <value>The SOAP action specified on the message, '{0}', does not match the action specified in the content-type of the HttpRequestMessageProperty, '{1}'.</value>
+ </data>
+ <data name="HttpSoapActionMismatchFault" xml:space="preserve">
+ <value>The SOAP action specified on the message, '{0}', does not match the HTTP SOAP Action, '{1}'. </value>
+ </data>
+ <data name="HttpContentTypeFormatException" xml:space="preserve">
+ <value>An error ({0}) occurred while parsing the content type of the HTTP request. The content type was: {1}.</value>
+ </data>
+ <data name="HttpServerTooBusy" xml:space="preserve">
+ <value>The HTTP service located at {0} is unavailable. This could be because the service is too busy or because no endpoint was found listening at the specified address. Please ensure that the address is correct and try accessing the service again later.</value>
+ </data>
+ <data name="HttpRequestAborted" xml:space="preserve">
+ <value>The HTTP request to '{0}' was aborted. This may be due to the local channel being closed while the request was still in progress. If this behavior is not desired, then update your code so that it does not close the channel while request operations are still in progress.</value>
+ </data>
+ <data name="HttpRequestTimedOut" xml:space="preserve">
+ <value>The HTTP request to '{0}' has exceeded the allotted timeout of {1}. The time allotted to this operation may have been a portion of a longer timeout.</value>
+ </data>
+ <data name="HttpResponseTimedOut" xml:space="preserve">
+ <value>The HTTP request to '{0}' has exceeded the allotted timeout of {1} while reading the response. The time allotted to this operation may have been a portion of a longer timeout.</value>
+ </data>
+ <data name="HttpTransferError" xml:space="preserve">
+ <value>An error ({0}) occurred while transmitting data over the HTTP channel.</value>
+ </data>
+ <data name="HttpReceiveFailure" xml:space="preserve">
+ <value>An error occurred while receiving the HTTP response to {0}. This could be due to the service endpoint binding not using the HTTP protocol. This could also be due to an HTTP request context being aborted by the server (possibly due to the service shutting down). See server logs for more details.</value>
+ </data>
+ <data name="HttpSendFailure" xml:space="preserve">
+ <value>An error occurred while making the HTTP request to {0}. This could be due to the fact that the server certificate is not configured properly with HTTP.SYS in the HTTPS case. This could also be caused by a mismatch of the security binding between the client and the server.</value>
+ </data>
+ <data name="HttpAuthDoesNotSupportRequestStreaming" xml:space="preserve">
+ <value>HTTP request streaming cannot be used in conjunction with HTTP authentication. Either disable request streaming or specify anonymous HTTP authentication.</value>
+ </data>
+ <data name="ReplyAlreadySent" xml:space="preserve">
+ <value>A reply has already been sent from this RequestContext.</value>
+ </data>
+ <data name="HttpInvalidListenURI" xml:space="preserve">
+ <value>Unable to start the HTTP listener. The URI provided, '{0}', is invalid for listening. Check the base address of your service and verify that it is a valid URI.</value>
+ </data>
+ <data name="RequestContextAborted" xml:space="preserve">
+ <value>The requestContext has been aborted.</value>
+ </data>
+ <data name="ReceiveContextCannotBeUsed" xml:space="preserve">
+ <value>The receive context, {0}, is in the {1} state. Receive contexts cannot be used for sending delayed acks unless they are in the Received state.</value>
+ </data>
+ <data name="ReceiveContextInInvalidState" xml:space="preserve">
+ <value>The receive context, {0}, is in an unsupported state '{1}'. This indicates an internal error in the implementation of that receive context.</value>
+ </data>
+ <data name="ReceiveContextFaulted" xml:space="preserve">
+ <value>The receive context, {0}, cannot be used for sending delayed acks because it is in the Faulted state.</value>
+ </data>
+ <data name="UnrecognizedHostNameComparisonMode" xml:space="preserve">
+ <value>Invalid HostNameComparisonMode value: {0}.</value>
+ </data>
+ <data name="BadData" xml:space="preserve">
+ <value>Invalid data buffer.</value>
+ </data>
+ <data name="InvalidRenewResponseAction" xml:space="preserve">
+ <value>A security session renew response was received with an invalid action '{0}'.</value>
+ </data>
+ <data name="InvalidCloseResponseAction" xml:space="preserve">
+ <value>A security session close response was received with an invalid action '{0}',</value>
+ </data>
+ <data name="IncompatibleBehaviors" xml:space="preserve">
+ <value>TransactedBatchingBehavior cannot be used when ReceiveContext is being used.</value>
+ </data>
+ <data name="NullSessionRequestMessage" xml:space="preserve">
+ <value>Could not formulate request message for security session operation '{0}'.</value>
+ </data>
+ <data name="IssueSessionTokenHandlerNotSet" xml:space="preserve">
+ <value>There is no handler registered for session token issuance event.</value>
+ </data>
+ <data name="RenewSessionTokenHandlerNotSet" xml:space="preserve">
+ <value>There is no handler registered for session token renew event.</value>
+ </data>
+ <data name="WrongIdentityRenewingToken" xml:space="preserve">
+ <value>The identity of the security session renew message does not match the identity of the session token.</value>
+ </data>
+ <data name="InvalidRstRequestType" xml:space="preserve">
+ <value>The RequestSecurityToken has an invalid or unspecified RequestType '{0}'.</value>
+ </data>
+ <data name="NoCloseTargetSpecified" xml:space="preserve">
+ <value>The RequestSecurityToken must specify a CloseTarget.</value>
+ </data>
+ <data name="FailedSspiNegotiation" xml:space="preserve">
+ <value>Secure channel cannot be opened because security negotiation with the remote endpoint has failed. This may be due to absent or incorrectly specified EndpointIdentity in the EndpointAddress used to create the channel. Please verify the EndpointIdentity specified or implied by the EndpointAddress correctly identifies the remote endpoint. </value>
+ </data>
+ <data name="BadCloseTarget" xml:space="preserve">
+ <value>The CloseTarget specified '{0}' does not identify the security token that signed the message.</value>
+ </data>
+ <data name="RenewSessionMissingSupportingToken" xml:space="preserve">
+ <value>The renew security session message does not have the session token as a supporting token.</value>
+ </data>
+ <data name="NoRenewTargetSpecified" xml:space="preserve">
+ <value>The RequestSecurityToken must specify a RenewTarget.</value>
+ </data>
+ <data name="BadRenewTarget" xml:space="preserve">
+ <value>There is no endorsing session token that matches the specified RenewTarget '{0}'.</value>
+ </data>
+ <data name="BadEncryptedBody" xml:space="preserve">
+ <value>Invalid format for encrypted body.</value>
+ </data>
+ <data name="BadEncryptionState" xml:space="preserve">
+ <value>The EncryptedData or EncryptedKey is in an invalid state for this operation.</value>
+ </data>
+ <data name="NoSignaturePartsSpecified" xml:space="preserve">
+ <value>No signature message parts were specified for messages with the '{0}' action.</value>
+ </data>
+ <data name="NoEncryptionPartsSpecified" xml:space="preserve">
+ <value>No encryption message parts were specified for messages with the '{0}' action.</value>
+ </data>
+ <data name="SecuritySessionFaultReplyWasSent" xml:space="preserve">
+ <value>The receiver sent back a security session fault message. Retry the request.</value>
+ </data>
+ <data name="InnerListenerFactoryNotSet" xml:space="preserve">
+ <value>The Inner listener factory of {0} must be set before this operation.</value>
+ </data>
+ <data name="SecureConversationBootstrapCannotUseSecureConversation" xml:space="preserve">
+ <value>Cannot create security binding element based on configuration data. The secure conversation bootstrap requires another secure conversation which is not supported. </value>
+ </data>
+ <data name="InnerChannelFactoryWasNotSet" xml:space="preserve">
+ <value>Cannot open ChannelFactory as the inner channel factory was not set during the initialization process.</value>
+ </data>
+ <data name="SecurityProtocolFactoryDoesNotSupportDuplex" xml:space="preserve">
+ <value>Duplex security is not supported by the security protocol factory '{0}'.</value>
+ </data>
+ <data name="SecurityProtocolFactoryDoesNotSupportRequestReply" xml:space="preserve">
+ <value>Request-reply security is not supported by the security protocol factory '{0}'.</value>
+ </data>
+ <data name="SecurityProtocolFactoryShouldBeSetBeforeThisOperation" xml:space="preserve">
+ <value>The security protocol factory must be set before this operation is performed.</value>
+ </data>
+ <data name="SecuritySessionProtocolFactoryShouldBeSetBeforeThisOperation" xml:space="preserve">
+ <value>Security session protocol factory must be set before this operation is performed.</value>
+ </data>
+ <data name="SecureConversationSecurityTokenParametersRequireBootstrapBinding" xml:space="preserve">
+ <value>Security channel or listener factory creation failed. Secure conversation security token parameters do not specify the bootstrap security binding element.</value>
+ </data>
+ <data name="PropertySettingErrorOnProtocolFactory" xml:space="preserve">
+ <value>The required '{0}' property on the '{1}' security protocol factory is not set or has an invalid value.</value>
+ </data>
+ <data name="ProtocolFactoryCouldNotCreateProtocol" xml:space="preserve">
+ <value>The protocol factory cannot create a protocol.</value>
+ </data>
+ <data name="IdentityCheckFailedForOutgoingMessage" xml:space="preserve">
+ <value>The identity check failed for the outgoing message. The expected identity is '{0}' for the '{1}' target endpoint.</value>
+ </data>
+ <data name="IdentityCheckFailedForIncomingMessage" xml:space="preserve">
+ <value>The identity check failed for the incoming message. The expected identity is '{0}' for the '{1}' target endpoint.</value>
+ </data>
+ <data name="DnsIdentityCheckFailedForIncomingMessageLackOfDnsClaim" xml:space="preserve">
+ <value>The Identity check failed for the incoming message. The remote endpoint did not provide a domain name system (DNS) claim and therefore did not satisfied DNS identity '{0}'. This may be caused by lack of DNS or CN name in the remote endpoint X.509 certificate's distinguished name.</value>
+ </data>
+ <data name="DnsIdentityCheckFailedForOutgoingMessageLackOfDnsClaim" xml:space="preserve">
+ <value>The Identity check failed for the outgoing message. The remote endpoint did not provide a domain name system (DNS) claim and therefore did not satisfied DNS identity '{0}'. This may be caused by lack of DNS or CN name in the remote endpoint X.509 certificate's distinguished name.</value>
+ </data>
+ <data name="DnsIdentityCheckFailedForIncomingMessage" xml:space="preserve">
+ <value>Identity check failed for incoming message. The expected DNS identity of the remote endpoint was '{0}' but the remote endpoint provided DNS claim '{1}'. If this is a legitimate remote endpoint, you can fix the problem by explicitly specifying DNS identity '{1}' as the Identity property of EndpointAddress when creating channel proxy. </value>
+ </data>
+ <data name="DnsIdentityCheckFailedForOutgoingMessage" xml:space="preserve">
+ <value>Identity check failed for outgoing message. The expected DNS identity of the remote endpoint was '{0}' but the remote endpoint provided DNS claim '{1}'. If this is a legitimate remote endpoint, you can fix the problem by explicitly specifying DNS identity '{1}' as the Identity property of EndpointAddress when creating channel proxy. </value>
+ </data>
+ <data name="SerializedTokenVersionUnsupported" xml:space="preserve">
+ <value>The serialized token version {0} is unsupported.</value>
+ </data>
+ <data name="AuthenticatorNotPresentInRSTRCollection" xml:space="preserve">
+ <value>The RequestSecurityTokenResponseCollection does not contain an authenticator.</value>
+ </data>
+ <data name="RSTRAuthenticatorHasBadContext" xml:space="preserve">
+ <value>The negotiation RequestSecurityTokenResponse has a different context from the authenticator RequestSecurityTokenResponse.</value>
+ </data>
+ <data name="ServerCertificateNotProvided" xml:space="preserve">
+ <value>The recipient did not provide its certificate. This certificate is required by the TLS protocol. Both parties must have access to their certificates.</value>
+ </data>
+ <data name="RSTRAuthenticatorNotPresent" xml:space="preserve">
+ <value>The authenticator was not included in the final leg of negotiation.</value>
+ </data>
+ <data name="RSTRAuthenticatorIncorrect" xml:space="preserve">
+ <value>The RequestSecurityTokenResponse CombinedHash is incorrect.</value>
+ </data>
+ <data name="ClientCertificateNotProvided" xml:space="preserve">
+ <value>The certificate for the client has not been provided. The certificate can be set on the ClientCredentials or ServiceCredentials.</value>
+ </data>
+ <data name="ClientCertificateNotProvidedOnServiceCredentials" xml:space="preserve">
+ <value>The client certificate is not provided. Specify a client certificate in ServiceCredentials. </value>
+ </data>
+ <data name="ClientCertificateNotProvidedOnClientCredentials" xml:space="preserve">
+ <value>The client certificate is not provided. Specify a client certificate in ClientCredentials. </value>
+ </data>
+ <data name="ServiceCertificateNotProvidedOnServiceCredentials" xml:space="preserve">
+ <value>The service certificate is not provided. Specify a service certificate in ServiceCredentials. </value>
+ </data>
+ <data name="ServiceCertificateNotProvidedOnClientCredentials" xml:space="preserve">
+ <value>The service certificate is not provided for target '{0}'. Specify a service certificate in ClientCredentials. </value>
+ </data>
+ <data name="UserNamePasswordNotProvidedOnClientCredentials" xml:space="preserve">
+ <value>The username is not provided. Specify username in ClientCredentials.</value>
+ </data>
+ <data name="ObjectIsReadOnly" xml:space="preserve">
+ <value>Object is read-only.</value>
+ </data>
+ <data name="EmptyXmlElementError" xml:space="preserve">
+ <value>Element {0} cannot be empty.</value>
+ </data>
+ <data name="UnexpectedXmlChildNode" xml:space="preserve">
+ <value>XML child node {0} of type {1} is unexpected for element {2}.</value>
+ </data>
+ <data name="ContextAlreadyRegistered" xml:space="preserve">
+ <value>The context-id={0} (generation-id={1}) is already registered with SecurityContextSecurityTokenAuthenticator.</value>
+ </data>
+ <data name="ContextAlreadyRegisteredNoKeyGeneration" xml:space="preserve">
+ <value>The context-id={0} (no key generation-id) is already registered with SecurityContextSecurityTokenAuthenticator.</value>
+ </data>
+ <data name="ContextNotPresent" xml:space="preserve">
+ <value>There is no SecurityContextSecurityToken with context-id={0} (generation-id={1}) registered with SecurityContextSecurityTokenAuthenticator.</value>
+ </data>
+ <data name="ContextNotPresentNoKeyGeneration" xml:space="preserve">
+ <value>There is no SecurityContextSecurityToken with context-id={0} (no key generation-id) registered with SecurityContextSecurityTokenAuthenticator.</value>
+ </data>
+ <data name="InvalidSecurityContextCookie" xml:space="preserve">
+ <value>The SecurityContextSecurityToken has an invalid Cookie. The following error occurred when processing the Cookie: '{0}'.</value>
+ </data>
+ <data name="SecurityContextNotRegistered" xml:space="preserve">
+ <value>The SecurityContextSecurityToken with context-id={0} (key generation-id={1}) is not registered.</value>
+ </data>
+ <data name="SecurityContextExpired" xml:space="preserve">
+ <value>The SecurityContextSecurityToken with context-id={0} (key generation-id={1}) has expired.</value>
+ </data>
+ <data name="SecurityContextExpiredNoKeyGeneration" xml:space="preserve">
+ <value>The SecurityContextSecurityToken with context-id={0} (no key generation-id) has expired.</value>
+ </data>
+ <data name="NoSecurityContextIdentifier" xml:space="preserve">
+ <value>The SecurityContextSecurityToken does not have a context-id.</value>
+ </data>
+ <data name="MessageMustHaveViaOrToSetForSendingOnServerSideCompositeDuplexChannels" xml:space="preserve">
+ <value>For sending a message on server side composite duplex channels, the message must have either the 'Via' property or the 'To' header set.</value>
+ </data>
+ <data name="MessageViaCannotBeAddressedToAnonymousOnServerSideCompositeDuplexChannels" xml:space="preserve">
+ <value>The 'Via' property on the message is set to Anonymous Uri '{0}'. Please set the 'Via' property to a non-anonymous address as message cannot be addressed to anonymous Uri on server side composite duplex channels.</value>
+ </data>
+ <data name="MessageToCannotBeAddressedToAnonymousOnServerSideCompositeDuplexChannels" xml:space="preserve">
+ <value>The 'To' header on the message is set to Anonymous Uri '{0}'. Please set the 'To' header to a non-anonymous address as message cannot be addressed to anonymous Uri on server side composite duplex channels.</value>
+ </data>
+ <data name="SecurityBindingNotSetUpToProcessOutgoingMessages" xml:space="preserve">
+ <value>This SecurityProtocol instance was not set up to process outgoing messages.</value>
+ </data>
+ <data name="SecurityBindingNotSetUpToProcessIncomingMessages" xml:space="preserve">
+ <value>This SecurityProtocol instance was not set up to process incoming messages.</value>
+ </data>
+ <data name="TokenProviderCannotGetTokensForTarget" xml:space="preserve">
+ <value>The token provider cannot get tokens for target '{0}'.</value>
+ </data>
+ <data name="UnsupportedKeyDerivationAlgorithm" xml:space="preserve">
+ <value>Key derivation algorithm '{0}' is not supported.</value>
+ </data>
+ <data name="CannotFindCorrelationStateForApplyingSecurity" xml:space="preserve">
+ <value>Cannot find the correlation state for applying security to reply at the responder.</value>
+ </data>
+ <data name="ReplyWasNotSignedWithRequiredSigningToken" xml:space="preserve">
+ <value>The reply was not signed with the required signing token.</value>
+ </data>
+ <data name="EncryptionNotExpected" xml:space="preserve">
+ <value>Encryption not expected for this message.</value>
+ </data>
+ <data name="SignatureNotExpected" xml:space="preserve">
+ <value>A signature is not expected for this message.</value>
+ </data>
+ <data name="InvalidQName" xml:space="preserve">
+ <value>The QName is invalid.</value>
+ </data>
+ <data name="UnknownICryptoType" xml:space="preserve">
+ <value>The ICrypto implementation '{0}' is not supported.</value>
+ </data>
+ <data name="SameProtocolFactoryCannotBeSetForBothDuplexDirections" xml:space="preserve">
+ <value>On DuplexSecurityProtocolFactory, the same protocol factory cannot be set for the forward and reverse directions.</value>
+ </data>
+ <data name="SuiteDoesNotAcceptAlgorithm" xml:space="preserve">
+ <value>The algorithm '{0}' is not accepted for operation '{1}' by algorithm suite {2}.</value>
+ </data>
+ <data name="TokenDoesNotSupportKeyIdentifierClauseCreation" xml:space="preserve">
+ <value>'{0}' does not support '{1}' creation.</value>
+ </data>
+ <data name="UnableToCreateICryptoFromTokenForSignatureVerification" xml:space="preserve">
+ <value>Cannot create an ICrypto interface from the '{0}' token for signature verification.</value>
+ </data>
+ <data name="MessageSecurityVerificationFailed" xml:space="preserve">
+ <value>Message security verification failed.</value>
+ </data>
+ <data name="TransportSecurityRequireToHeader" xml:space="preserve">
+ <value>Transport secured messages should have the 'To' header specified.</value>
+ </data>
+ <data name="TransportSecuredMessageMissingToHeader" xml:space="preserve">
+ <value>The message received over Transport security was missing the 'To' header.</value>
+ </data>
+ <data name="UnsignedToHeaderInTransportSecuredMessage" xml:space="preserve">
+ <value>The message received over Transport security has unsigned 'To' header.</value>
+ </data>
+ <data name="TransportSecuredMessageHasMoreThanOneToHeader" xml:space="preserve">
+ <value>More than one 'To' header specified in a message secured by Transport Security.</value>
+ </data>
+ <data name="TokenNotExpectedInSecurityHeader" xml:space="preserve">
+ <value>Received security header contains unexpected token '{0}'.</value>
+ </data>
+ <data name="CannotFindCert" xml:space="preserve">
+ <value>Cannot find the X.509 certificate using the following search criteria: StoreName '{0}', StoreLocation '{1}', FindType '{2}', FindValue '{3}'.</value>
+ </data>
+ <data name="CannotFindCertForTarget" xml:space="preserve">
+ <value>Cannot find The X.509 certificate using the following search criteria: StoreName '{0}', StoreLocation '{1}', FindType '{2}', FindValue '{3}' for target '{4}'.</value>
+ </data>
+ <data name="FoundMultipleCerts" xml:space="preserve">
+ <value>Found multiple X.509 certificates using the following search criteria: StoreName '{0}', StoreLocation '{1}', FindType '{2}', FindValue '{3}'. Provide a more specific find value.</value>
+ </data>
+ <data name="FoundMultipleCertsForTarget" xml:space="preserve">
+ <value>Found multiple X.509 certificates using the following search criteria: StoreName '{0}', StoreLocation '{1}', FindType '{2}', FindValue '{3}' for target '{4}'. Provide a more specific find value.</value>
+ </data>
+ <data name="MissingKeyInfoInEncryptedKey" xml:space="preserve">
+ <value>The KeyInfo clause is missing or empty in EncryptedKey.</value>
+ </data>
+ <data name="EncryptedKeyWasNotEncryptedWithTheRequiredEncryptingToken" xml:space="preserve">
+ <value>The EncryptedKey clause was not wrapped with the required encryption token '{0}'.</value>
+ </data>
+ <data name="MessageWasNotEncryptedWithTheRequiredEncryptingToken" xml:space="preserve">
+ <value>The message was not encrypted with the required encryption token.</value>
+ </data>
+ <data name="TimestampMustOccurFirstInSecurityHeaderLayout" xml:space="preserve">
+ <value>The timestamp must occur first in this security header layout.</value>
+ </data>
+ <data name="TimestampMustOccurLastInSecurityHeaderLayout" xml:space="preserve">
+ <value>The timestamp must occur last in this security header layout.</value>
+ </data>
+ <data name="AtMostOnePrimarySignatureInReceiveSecurityHeader" xml:space="preserve">
+ <value>Only one primary signature is allowed in a security header.</value>
+ </data>
+ <data name="SigningTokenHasNoKeys" xml:space="preserve">
+ <value>The signing token {0} has no keys. The security token is used in a context that requires it to perform cryptographic operations, but the token contains no cryptographic keys. Either the token type does not support cryptographic operations, or the particular token instance does not contain cryptographic keys. Check your configuration to ensure that cryptographically disabled token types (for example, UserNameSecurityToken) are not specified in a context that requires cryptographic operations (for example, an endorsing supporting token).</value>
+ </data>
+ <data name="SigningTokenHasNoKeysSupportingTheAlgorithmSuite" xml:space="preserve">
+ <value>The signing token {0} has no key that supports the algorithm suite {1}.</value>
+ </data>
+ <data name="DelayedSecurityApplicationAlreadyCompleted" xml:space="preserve">
+ <value>Delayed security application has already been completed.</value>
+ </data>
+ <data name="UnableToResolveKeyInfoClauseInDerivedKeyToken" xml:space="preserve">
+ <value>Cannot resolve KeyInfo in derived key token for resolving source token: KeyInfoClause '{0}'.</value>
+ </data>
+ <data name="UnableToDeriveKeyFromKeyInfoClause" xml:space="preserve">
+ <value>KeyInfo clause '{0}' resolved to token '{1}', which does not contain a Symmetric key that can be used for derivation.</value>
+ </data>
+ <data name="UnableToResolveKeyInfoForVerifyingSignature" xml:space="preserve">
+ <value>Cannot resolve KeyInfo for verifying signature: KeyInfo '{0}', available tokens '{1}'.</value>
+ </data>
+ <data name="UnableToResolveKeyInfoForUnwrappingToken" xml:space="preserve">
+ <value>Cannot resolve KeyInfo for unwrapping key: KeyInfo '{0}', available tokens '{1}'.</value>
+ </data>
+ <data name="UnableToResolveKeyInfoForDecryption" xml:space="preserve">
+ <value>Cannot resolve KeyInfo for decryption: KeyInfo '{0}', available tokens '{1}'.</value>
+ </data>
+ <data name="EmptyBase64Attribute" xml:space="preserve">
+ <value>An empty value was found for the required base-64 attribute name '{0}', namespace '{1}'.</value>
+ </data>
+ <data name="RequiredSecurityHeaderElementNotSigned" xml:space="preserve">
+ <value>The security header element '{0}' with the '{1}' id must be signed.</value>
+ </data>
+ <data name="RequiredSecurityTokenNotSigned" xml:space="preserve">
+ <value>The '{0}' security token with the '{1}' attachment mode must be signed.</value>
+ </data>
+ <data name="RequiredSecurityTokenNotEncrypted" xml:space="preserve">
+ <value>The '{0}' security token with the '{1}' attachment mode must be encrypted.</value>
+ </data>
+ <data name="MessageBodyOperationNotValidInBodyState" xml:space="preserve">
+ <value>Operation '{0}' is not valid in message body state '{1}'.</value>
+ </data>
+ <data name="EncryptedKeyWithReferenceListNotAllowed" xml:space="preserve">
+ <value>EncryptedKey with ReferenceList is not allowed according to the current settings.</value>
+ </data>
+ <data name="UnableToFindTokenAuthenticator" xml:space="preserve">
+ <value>Cannot find a token authenticator for the '{0}' token type. Tokens of that type cannot be accepted according to current security settings.</value>
+ </data>
+ <data name="NoPartsOfMessageMatchedPartsToSign" xml:space="preserve">
+ <value>No signature was created because not part of the message matched the supplied message part specification.</value>
+ </data>
+ <data name="BasicTokenCannotBeWrittenWithoutEncryption" xml:space="preserve">
+ <value>Supporting SecurityToken cannot be written without encryption.</value>
+ </data>
+ <data name="DuplicateIdInMessageToBeVerified" xml:space="preserve">
+ <value>The '{0}' id occurred twice in the message that is supplied for verification.</value>
+ </data>
+ <data name="UnsupportedCanonicalizationAlgorithm" xml:space="preserve">
+ <value>Canonicalization algorithm '{0}' is not supported.</value>
+ </data>
+ <data name="NoKeyInfoInEncryptedItemToFindDecryptingToken" xml:space="preserve">
+ <value>The KeyInfo value was not found in the encrypted item to find the decrypting token.</value>
+ </data>
+ <data name="NoKeyInfoInSignatureToFindVerificationToken" xml:space="preserve">
+ <value>No KeyInfo in signature to find verification token.</value>
+ </data>
+ <data name="SecurityHeaderIsEmpty" xml:space="preserve">
+ <value>Security header is empty.</value>
+ </data>
+ <data name="EncryptionMethodMissingInEncryptedData" xml:space="preserve">
+ <value>The encryption method is missing in encrypted data.</value>
+ </data>
+ <data name="EncryptedHeaderAttributeMismatch" xml:space="preserve">
+ <value>The Encrypted Header and the Security Header '{0}' attribute did not match. Encrypted Header: {1}. Security Header: {2}.</value>
+ </data>
+ <data name="AtMostOneReferenceListIsSupportedWithDefaultPolicyCheck" xml:space="preserve">
+ <value>At most one reference list is supported with default policy check.</value>
+ </data>
+ <data name="AtMostOneSignatureIsSupportedWithDefaultPolicyCheck" xml:space="preserve">
+ <value>At most one signature is supported with default policy check.</value>
+ </data>
+ <data name="UnexpectedEncryptedElementInSecurityHeader" xml:space="preserve">
+ <value>Unexpected encrypted element in security header.</value>
+ </data>
+ <data name="MissingIdInEncryptedElement" xml:space="preserve">
+ <value>Id is missing in encrypted item in security header.</value>
+ </data>
+ <data name="TokenManagerCannotCreateTokenReference" xml:space="preserve">
+ <value>The supplied token manager cannot create a token reference.</value>
+ </data>
+ <data name="TimestampToSignHasNoId" xml:space="preserve">
+ <value>The timestamp element added to security header to sign has no id.</value>
+ </data>
+ <data name="EncryptedHeaderXmlMustHaveId" xml:space="preserve">
+ <value>An encrypted header must have an id.</value>
+ </data>
+ <data name="UnableToResolveDataReference" xml:space="preserve">
+ <value>The data reference '{0}' could not be resolved in the received message.</value>
+ </data>
+ <data name="TimestampAlreadySetForSecurityHeader" xml:space="preserve">
+ <value>A timestamp element has already been set for this security header.</value>
+ </data>
+ <data name="DuplicateTimestampInSecurityHeader" xml:space="preserve">
+ <value>More than one Timestamp element was present in security header.</value>
+ </data>
+ <data name="MismatchInSecurityOperationToken" xml:space="preserve">
+ <value>The incoming message was signed with a token which was different from what used to encrypt the body. This was not expected.</value>
+ </data>
+ <data name="UnableToCreateSymmetricAlgorithmFromToken" xml:space="preserve">
+ <value>Cannot create the '{0}' symmetric algorithm from the token.</value>
+ </data>
+ <data name="UnknownEncodingInBinarySecurityToken" xml:space="preserve">
+ <value>Unrecognized encoding occurred while reading the binary security token.</value>
+ </data>
+ <data name="UnableToResolveReferenceUriForSignature" xml:space="preserve">
+ <value>Cannot resolve reference URI '{0}' in signature to compute digest.</value>
+ </data>
+ <data name="NoTimestampAvailableInSecurityHeaderToDoReplayDetection" xml:space="preserve">
+ <value>No timestamp is available in the security header to do replay detection.</value>
+ </data>
+ <data name="NoSignatureAvailableInSecurityHeaderToDoReplayDetection" xml:space="preserve">
+ <value>No signature is available in the security header to provide the nonce for replay detection.</value>
+ </data>
+ <data name="CouldNotFindNamespaceForPrefix" xml:space="preserve">
+ <value>There is no namespace binding for prefix '{0}' in scope.</value>
+ </data>
+ <data name="DerivedKeyCannotDeriveFromSecret" xml:space="preserve">
+ <value>Derived Key Token cannot derive key from the secret.</value>
+ </data>
+ <data name="DerivedKeyPosAndGenBothSpecified" xml:space="preserve">
+ <value>Both offset and generation cannot be specified for Derived Key Token.</value>
+ </data>
+ <data name="DerivedKeyPosAndGenNotSpecified" xml:space="preserve">
+ <value>Either offset or generation must be specified for Derived Key Token.</value>
+ </data>
+ <data name="DerivedKeyTokenRequiresTokenReference" xml:space="preserve">
+ <value>DerivedKeyToken requires a reference to a token.</value>
+ </data>
+ <data name="DerivedKeyLengthTooLong" xml:space="preserve">
+ <value>DerivedKey length ({0}) exceeds the allowed settings ({1}).</value>
+ </data>
+ <data name="DerivedKeyLengthSpecifiedInImplicitDerivedKeyClauseTooLong" xml:space="preserve">
+ <value>The Implicit derived key clause '{0}' specifies a derivation key length ({1}) which exceeds the allowed maximum length ({2}).</value>
+ </data>
+ <data name="DerivedKeyInvalidOffsetSpecified" xml:space="preserve">
+ <value>The received derived key token has a invalid offset value specified. Value: {0}. The value should be greater than or equal to zero.</value>
+ </data>
+ <data name="DerivedKeyInvalidGenerationSpecified" xml:space="preserve">
+ <value>The received derived key token has a invalid generation value specified. Value: {0}. The value should be greater than or equal to zero.</value>
+ </data>
+ <data name="ChildNodeTypeMissing" xml:space="preserve">
+ <value>The XML element {0} does not have a child of type {1}.</value>
+ </data>
+ <data name="NoLicenseXml" xml:space="preserve">
+ <value>RequestedSecurityToken not specified in RequestSecurityTokenResponse.</value>
+ </data>
+ <data name="UnsupportedBinaryEncoding" xml:space="preserve">
+ <value>Binary encoding {0} is not supported.</value>
+ </data>
+ <data name="BadKeyEncryptionAlgorithm" xml:space="preserve">
+ <value>Invalid key encryption algorithm {0}.</value>
+ </data>
+ <data name="InvalidAsyncResult" xml:space="preserve">
+ <value>The asynchronous result object used to end this operation was not the object that was returned when the operation was initiated.</value>
+ </data>
+ <data name="UnableToCreateTokenReference" xml:space="preserve">
+ <value>Unable to create token reference.</value>
+ </data>
+ <data name="ConfigNull" xml:space="preserve">
+ <value>null</value>
+ </data>
+ <data name="NonceLengthTooShort" xml:space="preserve">
+ <value>The specified nonce is too short. The minimum required nonce length is 4 bytes.</value>
+ </data>
+ <data name="NoBinaryNegoToSend" xml:space="preserve">
+ <value>There is no binary negotiation to send to the other party.</value>
+ </data>
+ <data name="BadSecurityNegotiationContext" xml:space="preserve">
+ <value>Security negotiation failure because an incorrect Context attribute specified in RequestSecurityToken/RequestSecurityTokenResponse from the other party.</value>
+ </data>
+ <data name="NoBinaryNegoToReceive" xml:space="preserve">
+ <value>No binary negotiation was received from the other party.</value>
+ </data>
+ <data name="ProofTokenWasNotWrappedCorrectly" xml:space="preserve">
+ <value>The proof token was not wrapped correctly in the RequestSecurityTokenResponse.</value>
+ </data>
+ <data name="NoServiceTokenReceived" xml:space="preserve">
+ <value>Final RSTR from other party does not contain a service token.</value>
+ </data>
+ <data name="InvalidSspiNegotiation" xml:space="preserve">
+ <value>The Security Support Provider Interface (SSPI) negotiation failed.</value>
+ </data>
+ <data name="CannotAuthenticateServer" xml:space="preserve">
+ <value>Cannot authenticate the other party.</value>
+ </data>
+ <data name="IncorrectBinaryNegotiationValueType" xml:space="preserve">
+ <value>Incoming binary negotiation has invalid ValueType {0}.</value>
+ </data>
+ <data name="ChannelNotOpen" xml:space="preserve">
+ <value>The channel is not open.</value>
+ </data>
+ <data name="FailToRecieveReplyFromNegotiation" xml:space="preserve">
+ <value>Security negotiation failed because the remote party did not send back a reply in a timely manner. This may be because the underlying transport connection was aborted.</value>
+ </data>
+ <data name="MessageSecurityVersionOutOfRange" xml:space="preserve">
+ <value>SecurityVersion must be WsSecurity10 or WsSecurity11.</value>
+ </data>
+ <data name="CreationTimeUtcIsAfterExpiryTime" xml:space="preserve">
+ <value>Creation time must be before expiration time.</value>
+ </data>
+ <data name="NegotiationStateAlreadyPresent" xml:space="preserve">
+ <value>Negotiation state already exists for context '{0}'.</value>
+ </data>
+ <data name="CannotFindNegotiationState" xml:space="preserve">
+ <value>Cannot find the negotiation state for the context '{0}'.</value>
+ </data>
+ <data name="OutputNotExpected" xml:space="preserve">
+ <value>Send cannot be called when the session does not expect output.</value>
+ </data>
+ <data name="SessionClosedBeforeDone" xml:space="preserve">
+ <value>The session was closed before message transfer was complete.</value>
+ </data>
+ <data name="CacheQuotaReached" xml:space="preserve">
+ <value>The item cannot be added. The maximum cache size is ({0} items).</value>
+ </data>
+ <data name="NoServerX509TokenProvider" xml:space="preserve">
+ <value>The server's X509SecurityTokenProvider cannot be null.</value>
+ </data>
+ <data name="UnexpectedBinarySecretType" xml:space="preserve">
+ <value>Expected binary secret of type {0} but got secret of type {1}.</value>
+ </data>
+ <data name="UnsupportedPasswordType" xml:space="preserve">
+ <value>The '{0}' username token has an unsupported password type.</value>
+ </data>
+ <data name="UnrecognizedIdentityPropertyType" xml:space="preserve">
+ <value>Unrecognized identity property type: '{0}'.</value>
+ </data>
+ <data name="UnableToDemuxChannel" xml:space="preserve">
+ <value>There was no channel that could accept the message with action '{0}'.</value>
+ </data>
+ <data name="EndpointNotFound" xml:space="preserve">
+ <value>There was no endpoint listening at {0} that could accept the message. This is often caused by an incorrect address or SOAP action. See InnerException, if present, for more details.</value>
+ </data>
+ <data name="MaxReceivedMessageSizeMustBeInIntegerRange" xml:space="preserve">
+ <value>This factory buffers messages, so the message sizes must be in the range of an integer value.</value>
+ </data>
+ <data name="MaxBufferSizeMustMatchMaxReceivedMessageSize" xml:space="preserve">
+ <value>For TransferMode.Buffered, MaxReceivedMessageSize and MaxBufferSize must be the same value.</value>
+ </data>
+ <data name="MaxBufferSizeMustNotExceedMaxReceivedMessageSize" xml:space="preserve">
+ <value>MaxBufferSize must not exceed MaxReceivedMessageSize.</value>
+ </data>
+ <data name="MessageSizeMustBeInIntegerRange" xml:space="preserve">
+ <value>This Factory buffers messages, so the message sizes must be in the range of a int value.</value>
+ </data>
+ <data name="UriLengthExceedsMaxSupportedSize" xml:space="preserve">
+ <value>URI {0} could not be set because its size ({1}) exceeds the max supported size ({2}).</value>
+ </data>
+ <data name="InValidateIdPrefix" xml:space="preserve">
+ <value>Expecting first char - c - to be in set [Char.IsLetter(c) &amp;&amp; c == '_', found '{0}'.</value>
+ </data>
+ <data name="InValidateId" xml:space="preserve">
+ <value>Expecting all chars - c - of id to be in set [Char.IsLetter(c), Char.IsNumber(c), '.', '_', '-'], found '{0}'.</value>
+ </data>
+ <data name="HttpRegistrationAlreadyExists" xml:space="preserve">
+ <value>HTTP could not register URL {0}. Another application has already registered this URL with HTTP.SYS.</value>
+ </data>
+ <data name="HttpRegistrationAccessDenied" xml:space="preserve">
+ <value>HTTP could not register URL {0}. Your process does not have access rights to this namespace (see http://go.microsoft.com/fwlink/?LinkId=70353 for details).</value>
+ </data>
+ <data name="HttpRegistrationPortInUse" xml:space="preserve">
+ <value>HTTP could not register URL {0} because TCP port {1} is being used by another application.</value>
+ </data>
+ <data name="HttpRegistrationLimitExceeded" xml:space="preserve">
+ <value>HTTP could not register URL {0} because the MaxEndpoints quota has been exceeded. To correct this, either close other HTTP-based services, or increase your MaxEndpoints registry key setting (see http://go.microsoft.com/fwlink/?LinkId=70352 for details).</value>
+ </data>
+ <data name="UnexpectedHttpResponseCode" xml:space="preserve">
+ <value>The remote server returned an unexpected response: ({0}) {1}.</value>
+ </data>
+ <data name="HttpContentLengthIncorrect" xml:space="preserve">
+ <value>The number of bytes available is inconsistent with the HTTP Content-Length header. There may have been a network error or the client may be sending invalid requests.</value>
+ </data>
+ <data name="OneWayUnexpectedResponse" xml:space="preserve">
+ <value>A response was received from a one-way send over the underlying IRequestChannel. Make sure the remote endpoint has a compatible binding at its endpoint (one that contains OneWayBindingElement).</value>
+ </data>
+ <data name="MissingContentType" xml:space="preserve">
+ <value>The receiver returned an error indicating that the content type was missing on the request to {0}. See the inner exception for more information.</value>
+ </data>
+ <data name="DuplexChannelAbortedDuringOpen" xml:space="preserve">
+ <value>Duplex channel to {0} was aborted during the open process.</value>
+ </data>
+ <data name="OperationAbortedDuringConnectionEstablishment" xml:space="preserve">
+ <value>Operation was aborted while establishing a connection to {0}.</value>
+ </data>
+ <data name="HttpAddressingNoneHeaderOnWire" xml:space="preserve">
+ <value>The incoming message contains a SOAP header representing the WS-Addressing '{0}', yet the HTTP transport is configured with AddressingVersion.None. As a result, the message is being dropped. If this is not desired, then update your HTTP binding to support a different AddressingVersion.</value>
+ </data>
+ <data name="MessageXmlProtocolError" xml:space="preserve">
+ <value>There is a problem with the XML that was received from the network. See inner exception for more details.</value>
+ </data>
+ <data name="TcpV4AddressInvalid" xml:space="preserve">
+ <value>An IPv4 address was specified ({0}), but IPv4 is not enabled on this machine. </value>
+ </data>
+ <data name="TcpV6AddressInvalid" xml:space="preserve">
+ <value>An IPv6 address was specified ({0}), but IPv6 is not enabled on this machine. </value>
+ </data>
+ <data name="UniquePortNotAvailable" xml:space="preserve">
+ <value>Cannot find a unique port number that is available for both IPv4 and IPv6.</value>
+ </data>
+ <data name="TcpAddressInUse" xml:space="preserve">
+ <value>There is already a listener on IP endpoint {0}. This could happen if there is another application already listening on this endpoint or if you have multiple service endpoints in your service host with the same IP endpoint but with incompatible binding configurations.</value>
+ </data>
+ <data name="TcpConnectNoBufs" xml:space="preserve">
+ <value>Insufficient winsock resources available to complete socket connection initiation.</value>
+ </data>
+ <data name="InsufficentMemory" xml:space="preserve">
+ <value>Insufficient memory avaliable to complete the operation.</value>
+ </data>
+ <data name="TcpConnectError" xml:space="preserve">
+ <value>Could not connect to {0}. TCP error code {1}: {2}. </value>
+ </data>
+ <data name="TcpConnectErrorWithTimeSpan" xml:space="preserve">
+ <value>Could not connect to {0}. The connection attempt lasted for a time span of {3}. TCP error code {1}: {2}. </value>
+ </data>
+ <data name="TcpListenError" xml:space="preserve">
+ <value>A TCP error ({0}: {1}) occurred while listening on IP Endpoint={2}.</value>
+ </data>
+ <data name="TcpTransferError" xml:space="preserve">
+ <value>A TCP error ({0}: {1}) occurred while transmitting data.</value>
+ </data>
+ <data name="TcpTransferErrorWithIP" xml:space="preserve">
+ <value>A TCP error ({0}: {1}) occurred while transmitting data. The local IP address and port is {2}. The remote IP address and port is {3}.</value>
+ </data>
+ <data name="TcpLocalConnectionAborted" xml:space="preserve">
+ <value>The socket connection was aborted by your local machine. This could be caused by a channel Abort(), or a transmission error from another thread using this socket.</value>
+ </data>
+ <data name="HttpResponseAborted" xml:space="preserve">
+ <value>The HTTP request context was aborted while writing the response. As a result, the response may not have been completely written to the network. This can be remedied by gracefully closing the request context rather than aborting it.</value>
+ </data>
+ <data name="TcpConnectionResetError" xml:space="preserve">
+ <value>The socket connection was aborted. This could be caused by an error processing your message or a receive timeout being exceeded by the remote host, or an underlying network resource issue. Local socket timeout was '{0}'.</value>
+ </data>
+ <data name="TcpConnectionResetErrorWithIP" xml:space="preserve">
+ <value>The socket connection was aborted. This could be caused by an error processing your message or a receive timeout being exceeded by the remote host, or an underlying network resource issue. Local socket timeout was '{0}'. The local IP address and port is {1}. The remote IP address and port is {2}.</value>
+ </data>
+ <data name="TcpConnectionTimedOut" xml:space="preserve">
+ <value>The socket transfer timed out after {0}. You have exceeded the timeout set on your binding. The time allotted to this operation may have been a portion of a longer timeout.</value>
+ </data>
+ <data name="TcpConnectionTimedOutWithIP" xml:space="preserve">
+ <value>The socket transfer timed out after {0}. You have exceeded the timeout set on your binding. The time allotted to this operation may have been a portion of a longer timeout. The local IP address and port is {1}. The remote IP address and port is {2}.</value>
+ </data>
+ <data name="SocketConnectionDisposed" xml:space="preserve">
+ <value>The socket connection has been disposed.</value>
+ </data>
+ <data name="SocketListenerDisposed" xml:space="preserve">
+ <value>The socket listener has been disposed.</value>
+ </data>
+ <data name="SocketListenerNotListening" xml:space="preserve">
+ <value>The socket listener is not listening.</value>
+ </data>
+ <data name="DuplexSessionListenerNotFound" xml:space="preserve">
+ <value>No duplex session listener was listening at {0}. This could be due to an incorrect via set on the client or a binding mismatch.</value>
+ </data>
+ <data name="HttpTargetNameDictionaryConflict" xml:space="preserve">
+ <value>The entry found in AuthenticationManager's CustomTargetNameDictionary for {0} does not match the requested identity of {1}.</value>
+ </data>
+ <data name="HttpContentTypeHeaderRequired" xml:space="preserve">
+ <value>An HTTP Content-Type header is required for SOAP messaging and none was found.</value>
+ </data>
+ <data name="ContentTypeMismatch" xml:space="preserve">
+ <value>Content Type {0} was sent to a service expecting {1}. The client and service bindings may be mismatched.</value>
+ </data>
+ <data name="ResponseContentTypeMismatch" xml:space="preserve">
+ <value>The content type {0} of the response message does not match the content type of the binding ({1}). If using a custom encoder, be sure that the IsContentTypeSupported method is implemented properly. The first {2} bytes of the response were: '{3}'.</value>
+ </data>
+ <data name="ResponseContentTypeNotSupported" xml:space="preserve">
+ <value>The content type {0} of the message is not supported by the encoder.</value>
+ </data>
+ <data name="HttpToMustEqualVia" xml:space="preserve">
+ <value>The binding specified requires that the to and via URIs must match because the Addressing Version is set to None. The to URI specified was '{0}'. The via URI specified was '{1}'.</value>
+ </data>
+ <data name="NullReferenceOnHttpResponse" xml:space="preserve">
+ <value>The server challenged this request and streamed requests cannot be resubmitted. To enable HTTP server challenges, set your TransferMode to Buffered or StreamedResponse.</value>
+ </data>
+ <data name="FramingContentTypeMismatch" xml:space="preserve">
+ <value>Content Type {0} was not supported by service {1}. The client and service bindings may be mismatched.</value>
+ </data>
+ <data name="FramingFaultUnrecognized" xml:space="preserve">
+ <value>Server faulted with code '{0}'.</value>
+ </data>
+ <data name="FramingContentTypeTooLongFault" xml:space="preserve">
+ <value>Content type '{0}' is too long to be processed by the remote host. See the server logs for more details.</value>
+ </data>
+ <data name="FramingViaTooLongFault" xml:space="preserve">
+ <value>Via '{0}' is too long to be processed by the remote host. See the server logs for more details.</value>
+ </data>
+ <data name="FramingModeNotSupportedFault" xml:space="preserve">
+ <value>The .Net Framing mode being used is not supported by '{0}'. See the server logs for more details.</value>
+ </data>
+ <data name="FramingVersionNotSupportedFault" xml:space="preserve">
+ <value>The .Net Framing version being used is not supported by '{0}'. See the server logs for more details.</value>
+ </data>
+ <data name="FramingUpgradeInvalid" xml:space="preserve">
+ <value>The requested upgrade is not supported by '{0}'. This could be due to mismatched bindings (for example security enabled on the client and not on the server).</value>
+ </data>
+ <data name="SecurityServerTooBusy" xml:space="preserve">
+ <value>Server '{0}' sent back a fault indicating it is too busy to process the request. Please retry later. Please see the inner exception for fault details.</value>
+ </data>
+ <data name="SecurityEndpointNotFound" xml:space="preserve">
+ <value>Server '{0}' sent back a fault indicating it is in the process of shutting down. Please see the inner exception for fault details.</value>
+ </data>
+ <data name="ServerTooBusy" xml:space="preserve">
+ <value>Server '{0}' is too busy to process this request. Try again later.</value>
+ </data>
+ <data name="UpgradeProtocolNotSupported" xml:space="preserve">
+ <value>Protocol Type {0} was sent to a service that does not support that type of upgrade.</value>
+ </data>
+ <data name="UpgradeRequestToNonupgradableService" xml:space="preserve">
+ <value>.Net Framing upgrade request for {0} was sent to a service that is not setup to receive upgrades.</value>
+ </data>
+ <data name="PreambleAckIncorrect" xml:space="preserve">
+ <value>You have tried to create a channel to a service that does not support .Net Framing. </value>
+ </data>
+ <data name="PreambleAckIncorrectMaybeHttp" xml:space="preserve">
+ <value>You have tried to create a channel to a service that does not support .Net Framing. It is possible that you are encountering an HTTP endpoint.</value>
+ </data>
+ <data name="StreamError" xml:space="preserve">
+ <value>An error occurred while transmitting data.</value>
+ </data>
+ <data name="ServerRejectedUpgradeRequest" xml:space="preserve">
+ <value>The server rejected the upgrade request.</value>
+ </data>
+ <data name="ServerRejectedSessionPreamble" xml:space="preserve">
+ <value>The server at {0} rejected the session-establishment request.</value>
+ </data>
+ <data name="UnableToResolveHost" xml:space="preserve">
+ <value>Cannot resolve the host name of URI "{0}" using DNS.</value>
+ </data>
+ <data name="HttpRequiresSingleAuthScheme" xml:space="preserve">
+ <value>The '{0}' authentication scheme has been specified on the HTTP factory. However, the factory only supports specification of exactly one authentication scheme. Valid authentication schemes are Digest, Negotiate, NTLM, Basic, or Anonymous.</value>
+ </data>
+ <data name="HttpAuthSchemeCannotBeNone" xml:space="preserve">
+ <value>The value specified for the AuthenticationScheme property on the HttpTransportBindingElement ('{0}') is not allowed when building a ChannelFactory. If you used a standard binding, ensure the ClientCredentialType is not set to HttpClientCredentialType.InheritedFromHost, a value which is invalid on a client. If you set the value to '{0}' directly on the HttpTransportBindingElement, please set it to Digest, Negotiate, NTLM, Basic, or Anonymous.</value>
+ </data>
+ <data name="HttpProxyRequiresSingleAuthScheme" xml:space="preserve">
+ <value>The '{0}' authentication scheme has been specified for the proxy on the HTTP factory. However, the factory only supports specification of exactly one authentication scheme. Valid authentication schemes are Digest, Negotiate, NTLM, Basic, or Anonymous.</value>
+ </data>
+ <data name="HttpMutualAuthNotSatisfied" xml:space="preserve">
+ <value>The remote HTTP server did not satisfy the mutual authentication requirement.</value>
+ </data>
+ <data name="HttpAuthorizationFailed" xml:space="preserve">
+ <value>The HTTP request is unauthorized with client authentication scheme '{0}'. The authentication header received from the server was '{1}'.</value>
+ </data>
+ <data name="HttpAuthenticationFailed" xml:space="preserve">
+ <value>The HTTP request with client authentication scheme '{0}' failed with '{1}' status.</value>
+ </data>
+ <data name="HttpAuthorizationForbidden" xml:space="preserve">
+ <value>The HTTP request was forbidden with client authentication scheme '{0}'.</value>
+ </data>
+ <data name="InvalidUriScheme" xml:space="preserve">
+ <value>The provided URI scheme '{0}' is invalid; expected '{1}'.</value>
+ </data>
+ <data name="HttpAuthSchemeAndClientCert" xml:space="preserve">
+ <value>The HTTPS listener factory was configured to require a client certificate and the '{0}' authentication scheme. However, only one form of client authentication can be required at once.</value>
+ </data>
+ <data name="NoTransportManagerForUri" xml:space="preserve">
+ <value>Could not find an appropriate transport manager for listen URI '{0}'.</value>
+ </data>
+ <data name="ListenerFactoryNotRegistered" xml:space="preserve">
+ <value>The specified channel listener at '{0}' is not registered with this transport manager.</value>
+ </data>
+ <data name="HttpsExplicitIdentity" xml:space="preserve">
+ <value>The HTTPS channel factory does not support explicit specification of an identity in the EndpointAddress unless the authentication scheme is NTLM or Negotiate.</value>
+ </data>
+ <data name="HttpsIdentityMultipleCerts" xml:space="preserve">
+ <value>The endpoint identity specified when creating the HTTPS channel to '{0}' contains multiple server certificates. However, the HTTPS transport only supports the specification of a single server certificate. In order to create an HTTPS channel, please specify no more than one server certificate in the endpoint identity.</value>
+ </data>
+ <data name="HttpsServerCertThumbprintMismatch" xml:space="preserve">
+ <value>The server certificate with name '{0}' failed identity verification because its thumbprint ('{1}') does not match the one specified in the endpoint identity ('{2}'). As a result, the current HTTPS request has failed. Please update the endpoint identity used on the client or the certificate used by the server.</value>
+ </data>
+ <data name="DuplicateRegistration" xml:space="preserve">
+ <value>A registration already exists for URI '{0}'.</value>
+ </data>
+ <data name="SecureChannelFailure" xml:space="preserve">
+ <value>Could not establish secure channel for SSL/TLS with authority '{0}'.</value>
+ </data>
+ <data name="TrustFailure" xml:space="preserve">
+ <value>Could not establish trust relationship for the SSL/TLS secure channel with authority '{0}'.</value>
+ </data>
+ <data name="NoCompatibleTransportManagerForUri" xml:space="preserve">
+ <value>Could not find a compatible transport manager for URI '{0}'.</value>
+ </data>
+ <data name="HttpSpnNotFound" xml:space="preserve">
+ <value>The SPN for the responding server at URI '{0}' could not be determined.</value>
+ </data>
+ <data name="StreamMutualAuthNotSatisfied" xml:space="preserve">
+ <value>The remote server did not satisfy the mutual authentication requirement.</value>
+ </data>
+ <data name="TransferModeNotSupported" xml:space="preserve">
+ <value>Transfer mode {0} is not supported by {1}.</value>
+ </data>
+ <data name="InvalidTokenProvided" xml:space="preserve">
+ <value>The token provider of type '{0}' did not return a token of type '{1}'. Check the credential configuration.</value>
+ </data>
+ <data name="NoUserNameTokenProvided" xml:space="preserve">
+ <value>The required UserNameSecurityToken was not provided.</value>
+ </data>
+ <data name="RemoteIdentityFailedVerification" xml:space="preserve">
+ <value>The following remote identity failed verification: '{0}'.</value>
+ </data>
+ <data name="UseDefaultWebProxyCantBeUsedWithExplicitProxyAddress" xml:space="preserve">
+ <value>You cannot specify an explicit Proxy Address as well as UseDefaultWebProxy=true in your HTTP Transport Binding Element.</value>
+ </data>
+ <data name="ProxyImpersonationLevelMismatch" xml:space="preserve">
+ <value>The HTTP proxy authentication credential specified an impersonation level restriction ({0}) that is stricter than the restriction for target server authentication ({1}).</value>
+ </data>
+ <data name="ProxyAuthenticationLevelMismatch" xml:space="preserve">
+ <value>The HTTP proxy authentication credential specified an mutual authentication requirement ({0}) that is stricter than the requirement for target server authentication ({1}).</value>
+ </data>
+ <data name="CredentialDisallowsNtlm" xml:space="preserve">
+ <value>The NTLM authentication scheme was specified, but the target credential does not allow NTLM.</value>
+ </data>
+ <data name="DigestExplicitCredsImpersonationLevel" xml:space="preserve">
+ <value>The impersonation level '{0}' was specified, yet HTTP Digest authentication can only support 'Impersonation' level when used with an explicit credential.</value>
+ </data>
+ <data name="UriGeneratorSchemeMustNotBeEmpty" xml:space="preserve">
+ <value>The scheme parameter must not be empty.</value>
+ </data>
+ <data name="UnsupportedSslProtectionLevel" xml:space="preserve">
+ <value>The protection level '{0}' was specified, yet SSL transport security only supports EncryptAndSign.</value>
+ </data>
+ <data name="HttpNoTrackingService" xml:space="preserve">
+ <value>{0}. This often indicates that a service that HTTP.SYS depends upon (such as httpfilter) is not started.</value>
+ </data>
+ <data name="HttpNetnameDeleted" xml:space="preserve">
+ <value>{0}. This often indicates that the HTTP client has prematurely closed the underlying TCP connection.</value>
+ </data>
+ <data name="TimeoutServiceChannelConcurrentOpen1" xml:space="preserve">
+ <value>Opening the channel timed out after {0}. The time allotted to this operation may have been a portion of a longer timeout.</value>
+ </data>
+ <data name="TimeoutServiceChannelConcurrentOpen2" xml:space="preserve">
+ <value>Opening the {0} channel timed out after {1}. The time allotted to this operation may have been a portion of a longer timeout.</value>
+ </data>
+ <data name="TimeSpanMustbeGreaterThanTimeSpanZero" xml:space="preserve">
+ <value>TimeSpan must be greater than TimeSpan.Zero.</value>
+ </data>
+ <data name="TimeSpanCannotBeLessThanTimeSpanZero" xml:space="preserve">
+ <value>TimeSpan cannot be less than TimeSpan.Zero.</value>
+ </data>
+ <data name="ValueMustBeNonNegative" xml:space="preserve">
+ <value>The value of this argument must be non-negative.</value>
+ </data>
+ <data name="ValueMustBePositive" xml:space="preserve">
+ <value>The value of this argument must be positive.</value>
+ </data>
+ <data name="ValueMustBeGreaterThanZero" xml:space="preserve">
+ <value>The value of this argument must be greater than 0.</value>
+ </data>
+ <data name="ValueMustBeInRange" xml:space="preserve">
+ <value>The value of this argument must fall within the range {0} to {1}.</value>
+ </data>
+ <data name="OffsetExceedsBufferBound" xml:space="preserve">
+ <value>The specified offset exceeds the upper bound of the buffer ({0}).</value>
+ </data>
+ <data name="OffsetExceedsBufferSize" xml:space="preserve">
+ <value>The specified offset exceeds the buffer size ({0} bytes).</value>
+ </data>
+ <data name="SizeExceedsRemainingBufferSpace" xml:space="preserve">
+ <value>The specified size exceeds the remaining buffer space ({0} bytes).</value>
+ </data>
+ <data name="SpaceNeededExceedsMessageFrameOffset" xml:space="preserve">
+ <value>The space needed for encoding ({0} bytes) exceeds the message frame offset.</value>
+ </data>
+ <data name="FaultConverterDidNotCreateFaultMessage" xml:space="preserve">
+ <value>{0} returned true from OnTryCreateFaultMessage, but did not return a fault message.</value>
+ </data>
+ <data name="FaultConverterCreatedFaultMessage" xml:space="preserve">
+ <value>{0} returned false from OnTryCreateFaultMessage, but returned a non-null fault message.</value>
+ </data>
+ <data name="FaultConverterDidNotCreateException" xml:space="preserve">
+ <value>{0} returned true from OnTryCreateException, but did not return an Exception.</value>
+ </data>
+ <data name="FaultConverterCreatedException" xml:space="preserve">
+ <value>{0} returned false from OnTryCreateException, but returned a non-null Exception (See InnerException for details).</value>
+ </data>
+ <data name="InfoCardInvalidChain" xml:space="preserve">
+ <value>Policy chain contains self issued URI or a managed issuer in the wrong position.</value>
+ </data>
+ <data name="FullTrustOnlyBindingElementSecurityCheck1" xml:space="preserve">
+ <value>The Binding with name {0} failed validation because it contains a BindingElement with type {1} which is not supported in partial trust. Consider using BasicHttpBinding or WSHttpBinding, or hosting your application in a full-trust environment.</value>
+ </data>
+ <data name="FullTrustOnlyBindingElementSecurityCheckWSHttpBinding1" xml:space="preserve">
+ <value>The WSHttpBinding with name {0} failed validation because it contains a BindingElement with type {1} which is not supported in partial trust. Consider disabling the message security and reliable session options, using BasicHttpBinding, or hosting your application in a full-trust environment.</value>
+ </data>
+ <data name="FullTrustOnlyBindingSecurityCheck1" xml:space="preserve">
+ <value>The Binding with name {0} failed validation because the Binding type {1} is not supported in partial trust. Consider using BasicHttpBinding or WSHttpBinding, or hosting your application in a full-trust environment.</value>
+ </data>
+ <data name="PartialTrustServiceCtorNotVisible" xml:space="preserve">
+ <value>The Service with name '{0}' could not be constructed because the application does not have permission to construct the type: both the Type and its default parameter-less constructor must be public.</value>
+ </data>
+ <data name="PartialTrustServiceMethodNotVisible" xml:space="preserve">
+ <value>The Method with name '{1}' in Type '{0}' could not be invoked because the application does not have permission to invoke the method: both the Method and its containing Type must be public.</value>
+ </data>
+ <data name="PartialTrustPerformanceCountersNotEnabled" xml:space="preserve">
+ <value>Access to performance counters is denied. Application may be running in partial trust. Either disable performance counters or configure the application to run in full trust.</value>
+ </data>
+ <data name="EnsureCategoriesExistFailedPermission" xml:space="preserve">
+ <value>Performance counter instance names may not be unique. See "http://go.microsoft.com/fwlink/?LinkId=524462" for details.</value>
+ </data>
+ <data name="PartialTrustWMINotEnabled" xml:space="preserve">
+ <value>Access to windows management instrumentation (WMI) is denied. Application may be running in partial trust. Either disable WMI or configure the application to run in full trust.</value>
+ </data>
+ <data name="PartialTrustMessageLoggingNotEnabled" xml:space="preserve">
+ <value>Unable to log messages. Application may be running in partial trust. Either disable message logging or configure the application to run in full trust.</value>
+ </data>
+ <data name="ScopeNameMustBeSpecified" xml:space="preserve">
+ <value>The 'scopeName' argument to the InstanceKey constructor must be a non-empty string which indicates the scope of uniqueness for the key. Durable services use the service namespace and name as the scope of uniqueness.</value>
+ </data>
+ <data name="ProviderCannotBeEmptyString" xml:space="preserve">
+ <value>The 'provider' argument to the InstanceKey constructor must be a non-empty string which identifies the source of the key data. The 'provider' argument can be null, in which case the default correlation provider name is used.</value>
+ </data>
+ <data name="CannotSetNameOnTheInvalidKey" xml:space="preserve">
+ <value>The 'Name' property cannot be set on an invalid InstanceKey.</value>
+ </data>
+ <data name="UnsupportedMessageQueryResultType" xml:space="preserve">
+ <value>The type {0} is not a supported result type.</value>
+ </data>
+ <data name="CannotRepresentResultAsNodeset" xml:space="preserve">
+ <value>The result cannot be represented as a nodeset. Only results of type XPathResultType.NodeSet can be represented as nodesets.</value>
+ </data>
+ <data name="MessageNotInLockedState" xml:space="preserve">
+ <value>Message with id {0} was not in a locked state.</value>
+ </data>
+ <data name="MessageValidityExpired" xml:space="preserve">
+ <value>Validity of message with id {0} has expired.</value>
+ </data>
+ <data name="UnsupportedUpgradeInitiator" xml:space="preserve">
+ <value>The StreamUpgradeInitiator specified ({0}) is not supported by this IStreamUpgradeChannelBindingProvider implementation. The most likely cause of this is passing a StreamUpgradeInitiator that was not created by the StreamUpgradeProvider associated with the current IStreamUpgradeChannelBindingProvider implementation.</value>
+ </data>
+ <data name="UnsupportedUpgradeAcceptor" xml:space="preserve">
+ <value>The StreamUpgradeAcceptor specified ({0}) is not supported by this IStreamUpgradeChannelBindingProvider implementation. The most likely cause of this is passing a StreamUpgradeAcceptor that was not created by the StreamUpgradeProvider associated with this IStreamUpgradeChannelBindingProvider implementation.</value>
+ </data>
+ <data name="StreamUpgradeUnsupportedChannelBindingKind" xml:space="preserve">
+ <value>The StreamUpgradeProvider {0} does not support the specified ChannelBindingKind ({1}). </value>
+ </data>
+ <data name="ExtendedProtectionNotSupported" xml:space="preserve">
+ <value>Extended protection is not supported on this platform. Please install the appropriate patch or change the ExtendedProtectionPolicy on the Binding or BindingElement to a value with a PolicyEnforcement value of "Never" or "WhenSupported".</value>
+ </data>
+ <data name="ExtendedProtectionPolicyBasicAuthNotSupported" xml:space="preserve">
+ <value>The Authentication Scheme "Basic" does not support Extended Protection. Please use a different authentication scheme or disable the ExtendedProtectionPolicy on the Binding or BindingElement by creating a new ExtendedProtectionPolicy with a PolicyEnforcement value of "Never".</value>
+ </data>
+ <data name="ExtendedProtectionPolicyCustomChannelBindingNotSupported" xml:space="preserve">
+ <value>CustomChannelBindings are not supported. Please remove the CustomChannelBinding from the ExtendedProtectionPolicy".</value>
+ </data>
+ <data name="HttpClientCredentialTypeInvalid" xml:space="preserve">
+ <value>ClientCredentialType '{0}' can only be used on the server side, not the client side. Please use one of the following values instead 'None, Basic, Client, Digest, Ntlm, Windows'.</value>
+ </data>
+ <data name="SecurityTokenProviderIncludeWindowsGroupsInconsistent" xml:space="preserve">
+ <value>When authentication schemes 'Basic' and also '{0}' are enabled, the value of IncludeWindowsGroups for Windows ('{1}') and UserName authentication ('{2}') must match. Please consider using the same value in both places.</value>
+ </data>
+ <data name="AuthenticationSchemesCannotBeInheritedFromHost" xml:space="preserve">
+ <value>The authentication schemes cannot be inherited from the host for binding '{0}'. No AuthenticationScheme was specified on the ServiceHost or in the virtual application in IIS. This may be resolved by enabling at least one authentication scheme for this virtual application in IIS, through the ServiceHost.Authentication.AuthenticationSchemes property or in the configuration at the &lt;serviceAuthenticationManager&gt; element.</value>
+ </data>
+ <data name="AuthenticationSchemes_BindingAndHostConflict" xml:space="preserve">
+ <value>The authentication schemes configured on the host ('{0}') do not allow those configured on the binding '{1}' ('{2}'). Please ensure that the SecurityMode is set to Transport or TransportCredentialOnly. Additionally, this may be resolved by changing the authentication schemes for this application through the IIS management tool, through the ServiceHost.Authentication.AuthenticationSchemes property, in the application configuration file at the &lt;serviceAuthenticationManager&gt; element, by updating the ClientCredentialType property on the binding, or by adjusting the AuthenticationScheme property on the HttpTransportBindingElement.</value>
+ </data>
+ <data name="FlagEnumTypeExpected" xml:space="preserve">
+ <value>Object type must be an enum with the flag attribute. '{0}' is not an enum - or the flag attribute is not set. Please use an enum type with the flag attribute instead.</value>
+ </data>
+ <data name="InvalidFlagEnumType" xml:space="preserve">
+ <value>Object type must be an enum with the flag attribute and may only contain powers of two for the flags enum values or a combination of such values. Please use an enum type according to these rules.</value>
+ </data>
+ <data name="NoAsyncWritePending" xml:space="preserve">
+ <value>There is no pending asynchronous write on this stream. Ensure that there is pending write on the stream or verify that the implementation does not try to complete the same operation multiple times.</value>
+ </data>
+ <data name="FlushBufferAlreadyInUse" xml:space="preserve">
+ <value>Cannot write to a buffer which is currently being flushed. </value>
+ </data>
+ <data name="WriteAsyncWithoutFreeBuffer" xml:space="preserve">
+ <value>An asynchronous write was called on the stream without a free buffer.</value>
+ </data>
+ <data name="TransportDoesNotSupportCompression" xml:space="preserve">
+ <value>The transport configured on this binding does not appear to support the CompressionFormat specified ({0}) on the message encoder. To resolve this issue, set the CompressionFormat on the {1} to '{2}' or use a different transport.</value>
+ </data>
+ <data name="UnsupportedSecuritySetting" xml:space="preserve">
+ <value>The value '{1}' is not supported in this context for the binding security property '{0}'.</value>
+ </data>
+ <data name="UnsupportedBindingProperty" xml:space="preserve">
+ <value>The value '{1}' is not supported in this context for the binding property '{0}'.</value>
+ </data>
+ <data name="HttpMaxPendingAcceptsTooLargeError" xml:space="preserve">
+ <value>The value of MaxPendingAccepts should not be larger than {0}.</value>
+ </data>
+ <data name="RequestInitializationTimeoutReached" xml:space="preserve">
+ <value>The initialization process of the request message timed out after {0}. To increase this quota, use the '{1}' property on the '{2}'.</value>
+ </data>
+ <data name="UnsupportedTokenImpersonationLevel" xml:space="preserve">
+ <value>The value '{1}' for the '{0}' property is not supported in Windows Store apps.</value>
+ </data>
+ <data name="AcksToMustBeSameAsRemoteAddress" xml:space="preserve">
+ <value>The remote endpoint requested an address for acknowledgements that is not the same as the address for application messages. The channel could not be opened because this is not supported. Ensure the endpoint address used to create the channel is identical to the one the remote endpoint was set up with.</value>
+ </data>
+ <data name="AcksToMustBeSameAsRemoteAddressReason" xml:space="preserve">
+ <value>The address for acknowledgements must be the same as the address for application messages. Verify that your endpoint is configured to use the same URI for these two addresses.</value>
+ </data>
+ <data name="AssertionNotSupported" xml:space="preserve">
+ <value>The {0}:{1} assertion is not supported.</value>
+ </data>
+ <data name="CloseOutputSessionErrorReason" xml:space="preserve">
+ <value>An unexpected error occurred while attempting to close the output half of the duplex reliable session.</value>
+ </data>
+ <data name="ConflictingAddress" xml:space="preserve">
+ <value>The remote endpoint sent conflicting requests to create a reliable session. The conflicting requests have inconsistent filter criteria such as address or action. The reliable session has been faulted.</value>
+ </data>
+ <data name="ConflictingOffer" xml:space="preserve">
+ <value>The remote endpoint sent conflicting requests to create a reliable session. The remote endpoint requested both a one way and a two way session. The reliable session has been faulted.</value>
+ </data>
+ <data name="CouldNotParseWithAction" xml:space="preserve">
+ <value>A message with action {0} could not be parsed.</value>
+ </data>
+ <data name="CSRefused" xml:space="preserve">
+ <value>The request to create a reliable session has been refused by the RM Destination. {0} The channel could not be opened.</value>
+ </data>
+ <data name="CSRefusedAcksToMustEqualEndpoint" xml:space="preserve">
+ <value>The endpoint processing requests to create a reliable session only supports sessions in which the AcksTo Uri and the Endpoint Uri are the same.</value>
+ </data>
+ <data name="CSRefusedAcksToMustEqualReplyTo" xml:space="preserve">
+ <value>The endpoint processing requests to create a reliable session only supports sessions in which the AcksTo Uri and the ReplyTo Uri are the same.</value>
+ </data>
+ <data name="CSRefusedDuplexNoOffer" xml:space="preserve">
+ <value>The endpoint at {0} processes duplex sessions. The create sequence request must contain an offer for a return sequence. This is likely caused by a binding mismatch.</value>
+ </data>
+ <data name="CSRefusedInputOffer" xml:space="preserve">
+ <value>The endpoint at {0} processes input sessions. The create sequence request must not contain an offer for a return sequence. This is likely caused by a binding mismatch.</value>
+ </data>
+ <data name="CSRefusedInvalidIncompleteSequenceBehavior" xml:space="preserve">
+ <value>The request to create a reliable session contains an invalid wsrm:IncompleteSequenceBehavior value. This is a WS-ReliableMessaging protocol violation.</value>
+ </data>
+ <data name="CSRefusedNoSTRWSSecurity" xml:space="preserve">
+ <value>The request to create a reliable session contains the wsse:SecurityTokenReference but does not carry a wsrm:UsesSequenceSTR header. This is a WS-ReliableMessaging protocol violation. The session could not be created.</value>
+ </data>
+ <data name="CSRefusedReplyNoOffer" xml:space="preserve">
+ <value>The endpoint at {0} processes reply sessions. The create sequence request must contain an offer for a return sequence. This is likely caused by a binding mismatch.</value>
+ </data>
+ <data name="CSRefusedRequiredSecurityElementMissing" xml:space="preserve">
+ <value>The RM Destination requires the WS-SecureConversation protocol in the binding. This is likely caused by a binding mismatch.</value>
+ </data>
+ <data name="CSRefusedSSLNotSupported" xml:space="preserve">
+ <value>The endpoint processing requests to create a reliable session does not support sessions that use SSL. This is likely caused by a binding mismatch. The session could not be created.</value>
+ </data>
+ <data name="CSRefusedSTRNoWSSecurity" xml:space="preserve">
+ <value>The request to create a reliable session carries a wsrm:UsesSequenceSTR header, but does not contain the wsse:SecurityTokenReference. This is a WS-ReliableMessaging protocol violation. The session could not be created.</value>
+ </data>
+ <data name="CSRefusedUnexpectedElementAtEndOfCSMessage" xml:space="preserve">
+ <value>The message is not a valid SOAP message. The body contains more than 1 root element.</value>
+ </data>
+ <data name="CSResponseOfferRejected" xml:space="preserve">
+ <value>The remote endpoint replied to a request for a two way session with an offer for a one way session. This is likely caused by a binding mismatch. The channel could not be opened.</value>
+ </data>
+ <data name="CSResponseOfferRejectedReason" xml:space="preserve">
+ <value>The client requested creation of a two way session. A one way session was created. The session cannot continue without as a one way session. This is likely caused by a binding mismatch.</value>
+ </data>
+ <data name="CSResponseWithInvalidIncompleteSequenceBehavior" xml:space="preserve">
+ <value>The response to the request to create a reliable session contains an invalid wsrm:IncompleteSequenceBehavior value. This is a WS-ReliableMessaging protocol violation.</value>
+ </data>
+ <data name="CSResponseWithOffer" xml:space="preserve">
+ <value>The remote endpoint replied to a request for a one way session with an offer for a two way session. This is a WS-ReliableMessaging protocol violation. The channel could not be opened.</value>
+ </data>
+ <data name="CSResponseWithOfferReason" xml:space="preserve">
+ <value>A return sequence was not offered by the create sequence request. The create sequence response cannot accept a return sequence.</value>
+ </data>
+ <data name="CSResponseWithoutOffer" xml:space="preserve">
+ <value>The remote endpoint replied to a request for a two way session with an offer for a one way session. This is a WS-ReliableMessaging protocol violation. The channel could not be opened.</value>
+ </data>
+ <data name="CSResponseWithoutOfferReason" xml:space="preserve">
+ <value>A return sequence was offered by the create sequence request but the create sequence response did not accept this sequence.</value>
+ </data>
+ <data name="DeliveryAssuranceRequiredNothingFound" xml:space="preserve">
+ <value>The WS-RM policy under the namespace {0} requires the wsrmp:ExactlyOnce, wsrmp:AtLeastOnce, or wsrmp:AtMostOnce assertion. Nothing was found.</value>
+ </data>
+ <data name="DeliveryAssuranceRequired" xml:space="preserve">
+ <value>The WS-RM policy under the namespace {0} requires the wsrmp:ExactlyOnce, wsrmp:AtLeastOnce, or wsrmp:AtMostOnce assertion. The {1} element under the {2} namespace was found.</value>
+ </data>
+ <data name="EarlyRequestTerminateSequence" xml:space="preserve">
+ <value>The remote endpoint sent a TerminateSequence protocol message before fully acknowledging all messages in the reply sequence. This is a violation of the reliable request reply protocol. The reliable session was faulted.</value>
+ </data>
+ <data name="EarlySecurityClose" xml:space="preserve">
+ <value>The remote endpoint has closed the underlying secure session before the reliable session fully completed. The reliable session was faulted.</value>
+ </data>
+ <data name="EarlySecurityFaulted" xml:space="preserve">
+ <value>The underlying secure session has faulted before the reliable session fully completed. The reliable session was faulted.</value>
+ </data>
+ <data name="EarlyTerminateSequence" xml:space="preserve">
+ <value>The remote endpoint has errantly sent a TerminateSequence protocol message before the sequence finished.</value>
+ </data>
+ <data name="ElementFound" xml:space="preserve">
+ <value>The {0}:{1} element requires a {2}:{3} child element but has the {4} child element under the {5} namespace.</value>
+ </data>
+ <data name="ElementRequired" xml:space="preserve">
+ <value>The {0}:{1} element requires a {2}:{3} child element but has no child elements.</value>
+ </data>
+ <data name="InconsistentLastMsgNumberExceptionString" xml:space="preserve">
+ <value>The remote endpoint specified two different last message numbers. The reliable session is in an inconsistent state since it cannot determine the actual last message. The reliable session was faulted.</value>
+ </data>
+ <data name="InvalidAcknowledgementFaultReason" xml:space="preserve">
+ <value>The SequenceAcknowledgement violates the cumulative acknowledgement invariant.</value>
+ </data>
+ <data name="InvalidAcknowledgementReceived" xml:space="preserve">
+ <value>A violation of acknowledgement protocol has been detected. An InvalidAcknowledgement fault was sent to the remote endpoint and the reliable session was faulted.</value>
+ </data>
+ <data name="InvalidBufferRemaining" xml:space="preserve">
+ <value>An acknowledgement was received indicating the remaining buffer space on the remote endpoint is {0}. This number cannot be less than zero. The reliable session was faulted.</value>
+ </data>
+ <data name="InvalidSequenceNumber" xml:space="preserve">
+ <value>A message was received with a sequence number of {0}. Sequence numbers cannot be less than 1. The reliable session was faulted.</value>
+ </data>
+ <data name="InvalidSequenceRange" xml:space="preserve">
+ <value>An acknowledgement range starting at {0} and ending at {1} was received. This is an invalid acknowledgement range. The reliable session was faulted.</value>
+ </data>
+ <data name="InvalidWsrmResponseChannelNotOpened" xml:space="preserve">
+ <value>The remote endpoint responded to the {0} request with a response with action {1}. The response must be a {0}Response with action {2}. The channel could not be opened.</value>
+ </data>
+ <data name="InvalidWsrmResponseSessionFaultedExceptionString" xml:space="preserve">
+ <value>The remote endpoint responded to the {0} request with a response with action {1}. The response must be a {0}Response with action {2}. The channel was faulted.</value>
+ </data>
+ <data name="InvalidWsrmResponseSessionFaultedFaultString" xml:space="preserve">
+ <value>The {0} request's response was a message with action {1}. The response must be a {0}Response with action {2}. The reliable session cannot continue.</value>
+ </data>
+ <data name="LastMessageNumberExceeded" xml:space="preserve">
+ <value>A message was received with a sequence number higher than the sequence number of the last message in this sequence. This is a violation of the sequence number protocol. The reliable session was faulted.</value>
+ </data>
+ <data name="LastMessageNumberExceededFaultReason" xml:space="preserve">
+ <value>The value for wsrm:MessageNumber exceeds the value of the MessageNumber accompanying a LastMessage element in this Sequence.</value>
+ </data>
+ <data name="ManualAddressingNotSupported" xml:space="preserve">
+ <value>Binding validation failed because the TransportBindingElement's ManualAddressing property was set to true on a binding that is configured to create reliable sessions. This combination is not supported and the channel factory or service host was not opened.</value>
+ </data>
+ <data name="MaximumRetryCountExceeded" xml:space="preserve">
+ <value>The maximum retry count has been exceeded with no response from the remote endpoint. The reliable session was faulted. This is often an indication that the remote endpoint is no longer available.</value>
+ </data>
+ <data name="MessageExceptionOccurred" xml:space="preserve">
+ <value>A problem occurred while reading a message. See inner exception for details.</value>
+ </data>
+ <data name="MessageNumberRollover" xml:space="preserve">
+ <value>The maximum message number for this sequence has been exceeded. The reliable session was faulted.</value>
+ </data>
+ <data name="MessageNumberRolloverFaultReason" xml:space="preserve">
+ <value>The maximum value for wsrm:MessageNumber has been exceeded.</value>
+ </data>
+ <data name="MillisecondsNotConvertibleToBindingRange" xml:space="preserve">
+ <value>The {0} assertion's Milliseconds attribute does not fall within the range this binding uses. The ReliableSessionBindingElement could not be created.</value>
+ </data>
+ <data name="MissingFinalAckExceptionString" xml:space="preserve">
+ <value>The remote endpoint did not include a final acknowledgement in the reply to the close sequence request message. This is a violation of the WS-ReliableMessaging protocol. The reliable session was faulted.</value>
+ </data>
+ <data name="MissingMessageIdOnWsrmRequest" xml:space="preserve">
+ <value>The wsa:MessageId header must be present on a wsrm:{0} message.</value>
+ </data>
+ <data name="MissingRelatesToOnWsrmResponseReason" xml:space="preserve">
+ <value>The returned wsrm:{0}Response message was missing the required wsa:RelatesTo header. This is a violation of the WS-Addressing request reply protocol. The reliable session was faulted.</value>
+ </data>
+ <data name="MissingReplyToOnWsrmRequest" xml:space="preserve">
+ <value>The wsa:ReplyTo header must be present on a wsrm:{0} message.</value>
+ </data>
+ <data name="MultipleVersionsFoundInPolicy" xml:space="preserve">
+ <value>More than one version of the {0} assertion was found. The ReliableSessionBindingElement could not be created.</value>
+ </data>
+ <data name="NoActionNoSequenceHeaderReason" xml:space="preserve">
+ <value>The endpoint only processes messages using the WS-ReliableMessaging protocol. The message sent to the endpoint does not have an action or any headers used by the protocol and cannot be processed.</value>
+ </data>
+ <data name="NonEmptyWsrmMessageIsEmpty" xml:space="preserve">
+ <value>A message with action {0} is an empty message. This message cannot be processed because the body of this WS-ReliableMessaging protocol message must carry information pertaining to a reliable session.</value>
+ </data>
+ <data name="NonWsrmFeb2005ActionNotSupported" xml:space="preserve">
+ <value>The action {0} is not supported by this endpoint. Only WS-ReliableMessaging February 2005 messages are processed by this endpoint.</value>
+ </data>
+ <data name="NotAllRepliesAcknowledgedExceptionString" xml:space="preserve">
+ <value>The remote endpoint closed the session before acknowledging all responses. All replies could not be delivered. The reliable session was faulted.</value>
+ </data>
+ <data name="ReceivedResponseBeforeRequestExceptionString" xml:space="preserve">
+ <value>The remote endpoint returned a {0}Response when the {0} request had not been sent. This is a WS-ReliableMessaging protocol violation. The reliable session was faulted.</value>
+ </data>
+ <data name="ReceivedResponseBeforeRequestFaultString" xml:space="preserve">
+ <value>The {0}Response was received when the {0} request had not been sent. This is a WS-ReliableMessaging protocol violation. The reliable session cannot continue.</value>
+ </data>
+ <data name="ReplyMissingAcknowledgement" xml:space="preserve">
+ <value>The remote endpoint failed to include a required SequenceAcknowledgement header on a reliable reply message. The reliable session was faulted.</value>
+ </data>
+ <data name="ReliableRequestContextAborted" xml:space="preserve">
+ <value>Due to a request context abort call, the reliable reply session channel potentially has a gap in its reply sequence. The ExactlyOnce assurance can no longer be satisfied. The reliable session was faulted.</value>
+ </data>
+ <data name="RequiredAttributeIsMissing" xml:space="preserve">
+ <value>The required {0} attribute is missing from the {1} element in the {2} assertion. The ReliableSessionBindingElement could not be created.</value>
+ </data>
+ <data name="RequiredMillisecondsAttributeIncorrect" xml:space="preserve">
+ <value>The {0} assertion's required Milliseconds attribute is not schema compliant. Milliseconds must be convertible to an unsigned long. The ReliableSessionBindingElement could not be created.</value>
+ </data>
+ <data name="RMEndpointNotFoundReason" xml:space="preserve">
+ <value>The endpoint at {0} has stopped accepting wsrm sessions.</value>
+ </data>
+ <data name="SequenceClosedFaultString" xml:space="preserve">
+ <value>The Sequence is closed and cannot accept new messages.</value>
+ </data>
+ <data name="SequenceTerminatedAddLastToWindowTimedOut" xml:space="preserve">
+ <value>The RM Source could not transfer the last message within the timeout the user specified.</value>
+ </data>
+ <data name="SequenceTerminatedBeforeReplySequenceAcked" xml:space="preserve">
+ <value>The server received a TerminateSequence message before all reply sequence messages were acknowledged. This is a violation of the reply sequence acknowledgement protocol.</value>
+ </data>
+ <data name="SequenceTerminatedEarlyTerminateSequence" xml:space="preserve">
+ <value>The wsrm:TerminateSequence protocol message was transmitted before the sequence was successfully completed.</value>
+ </data>
+ <data name="SequenceTerminatedInactivityTimeoutExceeded" xml:space="preserve">
+ <value>The inactivity timeout of ({0}) has been exceeded.</value>
+ </data>
+ <data name="SequenceTerminatedInconsistentLastMsgNumber" xml:space="preserve">
+ <value>Two different wsrm:LastMsgNumber values were specified. Because of this the reliable session cannot complete.</value>
+ </data>
+ <data name="SequenceTerminatedMaximumRetryCountExceeded" xml:space="preserve">
+ <value>The user specified maximum retry count for a particular message has been exceeded. Because of this the reliable session cannot continue.</value>
+ </data>
+ <data name="SequenceTerminatedMissingFinalAck" xml:space="preserve">
+ <value>The CloseSequence request's reply message must carry a final acknowledgement. This is a violation of the WS-ReliableMessaging protocol. The reliable session cannot continue.</value>
+ </data>
+ <data name="SequenceTerminatedOnAbort" xml:space="preserve">
+ <value>Due to a user abort the reliable session cannot continue.</value>
+ </data>
+ <data name="SequenceTerminatedQuotaExceededException" xml:space="preserve">
+ <value>The necessary size to buffer a sequence message has exceeded the configured buffer quota. Because of this the reliable session cannot continue.</value>
+ </data>
+ <data name="SequenceTerminatedReliableRequestThrew" xml:space="preserve">
+ <value>The session has stopped waiting for a particular reply. Because of this the reliable session cannot continue.</value>
+ </data>
+ <data name="SequenceTerminatedReplyMissingAcknowledgement" xml:space="preserve">
+ <value>A reply message was received with no acknowledgement.</value>
+ </data>
+ <data name="SequenceTerminatedNotAllRepliesAcknowledged" xml:space="preserve">
+ <value>All of the reply sequence's messages must be acknowledged prior to closing the request sequence. This is a violation of the reply sequence's delivery guarantee. The session cannot continue.</value>
+ </data>
+ <data name="SequenceTerminatedSessionClosedBeforeDone" xml:space="preserve">
+ <value>The user of the remote endpoint's reliable session expects no more messages and a new message arrived. Due to this the reliable session cannot continue.</value>
+ </data>
+ <data name="SequenceTerminatedSmallLastMsgNumber" xml:space="preserve">
+ <value>The wsrm:LastMsgNumber value is too small. A message with a larger sequence number has already been received.</value>
+ </data>
+ <data name="SequenceTerminatedUnexpectedAcknowledgement" xml:space="preserve">
+ <value>The RM destination received an acknowledgement message. The RM destination does not process acknowledgement messages.</value>
+ </data>
+ <data name="SequenceTerminatedUnexpectedAckRequested" xml:space="preserve">
+ <value>The RM source received an AckRequested message. The RM source does not process AckRequested messages.</value>
+ </data>
+ <data name="SequenceTerminatedUnexpectedCloseSequence" xml:space="preserve">
+ <value>The RM source received an CloseSequence message. The RM source does not process CloseSequence messages.</value>
+ </data>
+ <data name="SequenceTerminatedUnexpectedCloseSequenceResponse" xml:space="preserve">
+ <value>The RM destination received an CloseSequenceResponse message. The RM destination does not process CloseSequenceResponse messages.</value>
+ </data>
+ <data name="SequenceTerminatedUnexpectedCS" xml:space="preserve">
+ <value>The RM source received a CreateSequence request. The RM source does not process CreateSequence requests.</value>
+ </data>
+ <data name="SequenceTerminatedUnexpectedCSOfferId" xml:space="preserve">
+ <value>The RM destination received multiple CreateSequence requests with different OfferId values over the same session.</value>
+ </data>
+ <data name="SequenceTerminatedUnexpectedCSR" xml:space="preserve">
+ <value>The RM destination received a CreateSequenceResponse message. The RM destination does not process CreateSequenceResponse messages.</value>
+ </data>
+ <data name="SequenceTerminatedUnexpectedCSROfferId" xml:space="preserve">
+ <value>The RM source received multiple CreateSequenceResponse messages with different sequence identifiers over the same session.</value>
+ </data>
+ <data name="SequenceTerminatedUnexpectedTerminateSequence" xml:space="preserve">
+ <value>The RM source received a TerminateSequence message. The RM source does not process TerminateSequence messages.</value>
+ </data>
+ <data name="SequenceTerminatedUnexpectedTerminateSequenceResponse" xml:space="preserve">
+ <value>The RM destination received a TerminateSequenceResponse message. The RM destination does not process TerminateSequenceResponse messages.</value>
+ </data>
+ <data name="SequenceTerminatedUnsupportedClose" xml:space="preserve">
+ <value>The RM source does not support an RM destination initiated close since messages can be lost. The reliable session cannot continue.</value>
+ </data>
+ <data name="SequenceTerminatedUnsupportedTerminateSequence" xml:space="preserve">
+ <value>The RM source does not support an RM destination initiated termination since messages can be lost. The reliable session cannot continue.</value>
+ </data>
+ <data name="SequenceTerminatedUnknownAddToWindowError" xml:space="preserve">
+ <value>An unknown error occurred while trying to add a sequence message to the window.</value>
+ </data>
+ <data name="SmallLastMsgNumberExceptionString" xml:space="preserve">
+ <value>The remote endpoint specified a last message number that is smaller than a sequence number that has already been seen. The reliable session is in an inconsistent state since it cannot determine the actual last message. The reliable session was faulted.</value>
+ </data>
+ <data name="TimeoutOnAddToWindow" xml:space="preserve">
+ <value>The message could not be transferred within the allotted timeout of {0}. There was no space available in the reliable channel's transfer window. The time allotted to this operation may have been a portion of a longer timeout.</value>
+ </data>
+ <data name="TimeoutOnClose" xml:space="preserve">
+ <value>The close operation did not complete within the allotted timeout of {0}. The time allotted to this operation may have been a portion of a longer timeout.</value>
+ </data>
+ <data name="TimeoutOnOpen" xml:space="preserve">
+ <value>The open operation did not complete within the allotted timeout of {0}. The time allotted to this operation may have been a portion of a longer timeout.</value>
+ </data>
+ <data name="TimeoutOnOperation" xml:space="preserve">
+ <value>The operation did not complete within the allotted timeout of {0}. The time allotted to this operation may have been a portion of a longer timeout.</value>
+ </data>
+ <data name="TimeoutOnRequest" xml:space="preserve">
+ <value>The request operation did not complete within the allotted timeout of {0}. The time allotted to this operation may have been a portion of a longer timeout.</value>
+ </data>
+ <data name="TimeoutOnSend" xml:space="preserve">
+ <value>The send operation did not complete within the allotted timeout of {0}. The time allotted to this operation may have been a portion of a longer timeout.</value>
+ </data>
+ <data name="UnexpectedAcknowledgement" xml:space="preserve">
+ <value>The remote endpoint sent an unexpected ack. Simplex servers do not process acks.</value>
+ </data>
+ <data name="UnexpectedAckRequested" xml:space="preserve">
+ <value>The remote endpoint sent an unexpected request for an ack. Simplex clients do not send acks and do not process requests for acks.</value>
+ </data>
+ <data name="UnexpectedCloseSequence" xml:space="preserve">
+ <value>The remote endpoint sent an unexpected close sequence message. Simplex clients do not process this message.</value>
+ </data>
+ <data name="UnexpectedCloseSequenceResponse" xml:space="preserve">
+ <value>The remote endpoint sent an unexpected close sequence response message. Simplex servers do not process this message.</value>
+ </data>
+ <data name="UnexpectedCS" xml:space="preserve">
+ <value>The remote endpoint sent an unexpected request to create a sequence. Clients do not process requests for a sequence.</value>
+ </data>
+ <data name="UnexpectedCSR" xml:space="preserve">
+ <value>The remote endpoint sent an unexpected create sequence response. Servers do not process this message.</value>
+ </data>
+ <data name="UnexpectedCSOfferId" xml:space="preserve">
+ <value>The remote endpoint sent inconsistent requests to create the same sequence. The OfferId values are not identical.</value>
+ </data>
+ <data name="UnexpectedCSROfferId" xml:space="preserve">
+ <value>The remote endpoint sent inconsistent responses to the same create sequence request. The sequence identifiers are not identical.</value>
+ </data>
+ <data name="UnexpectedTerminateSequence" xml:space="preserve">
+ <value>The remote endpoint sent an unexpected terminate sequence message. Simplex clients do not process this message.</value>
+ </data>
+ <data name="UnexpectedTerminateSequenceResponse" xml:space="preserve">
+ <value>The remote endpoint sent an unexpected terminate sequence response message. Simplex servers do not process this message.</value>
+ </data>
+ <data name="UnparsableCSResponse" xml:space="preserve">
+ <value>The remote endpoint replied to the request for a sequence with a response that could not be parsed. See inner exception for details. The channel could not be opened.</value>
+ </data>
+ <data name="UnknownSequenceFaultReason" xml:space="preserve">
+ <value>The value of wsrm:Identifier is not a known Sequence identifier.</value>
+ </data>
+ <data name="UnknownSequenceFaultReceived" xml:space="preserve">
+ <value>The remote endpoint no longer recognizes this sequence. This is most likely due to an abort on the remote endpoint. {0} The reliable session was faulted.</value>
+ </data>
+ <data name="UnknownSequenceMessageReceived" xml:space="preserve">
+ <value>The remote endpoint has sent a message containing an unrecognized sequence identifier. The reliable session was faulted.</value>
+ </data>
+ <data name="UnrecognizedFaultReceived" xml:space="preserve">
+ <value>The remote endpoint has sent an unrecognized fault with namespace, {0}, name {1}, and reason {2}. The reliable session was faulted.</value>
+ </data>
+ <data name="UnrecognizedFaultReceivedOnOpen" xml:space="preserve">
+ <value>The remote endpoint has sent an unrecognized fault with namespace, {0}, name {1}, and reason {2}. The channel could not be opened.</value>
+ </data>
+ <data name="UnsupportedCloseExceptionString" xml:space="preserve">
+ <value>The remote endpoint closed the sequence before message transfer was complete. This is not supported since all messages could not be transferred. The reliable session was faulted.</value>
+ </data>
+ <data name="UnsupportedTerminateSequenceExceptionString" xml:space="preserve">
+ <value>The remote endpoint terminated the sequence before message transfer was complete. This is not supported since all messages could not be transferred. The reliable session was faulted.</value>
+ </data>
+ <data name="WrongIdentifierFault" xml:space="preserve">
+ <value>The remote endpoint has sent an fault message with an unexpected sequence identifier over a session. The fault may be intended for a different session. The fault reason is: {0} The reliable session was faulted.</value>
+ </data>
+ <data name="WSHttpDoesNotSupportRMWithHttps" xml:space="preserve">
+ <value>Binding validation failed because the WSHttpBinding does not support reliable sessions over transport security (HTTPS). The channel factory or service host could not be opened. Use message security for secure reliable messaging over HTTP.</value>
+ </data>
+ <data name="WsrmFaultReceived" xml:space="preserve">
+ <value>The sequence has been terminated by the remote endpoint. {0} The reliable session was faulted.</value>
+ </data>
+ <data name="WsrmMessageProcessingError" xml:space="preserve">
+ <value>An error occurred while processing a message. {0}</value>
+ </data>
+ <data name="WsrmMessageWithWrongRelatesToExceptionString" xml:space="preserve">
+ <value>The returned {0}Response was carrying the a wsa:RelatesTo header that does not correlate with the wsa:MessageId header on the {0} request. This is a violation of the WS-Addressing request reply protocol. The reliable session cannot continue.</value>
+ </data>
+ <data name="WsrmMessageWithWrongRelatesToFaultString" xml:space="preserve">
+ <value>The remote endpoint has responded to a {0} request message with an invalid reply. The reply has a wsa:RelatesTo header with an unexpected identifier. The reliable session cannot continue.</value>
+ </data>
+ <data name="WsrmRequestIncorrectReplyToExceptionString" xml:space="preserve">
+ <value>The remote endpoint sent a wsrm:{0} request message with a wsa:ReplyTo address containing a URI which is not equivalent to the remote address. This is not supported. The reliable session was faulted.</value>
+ </data>
+ <data name="WsrmRequestIncorrectReplyToFaultString" xml:space="preserve">
+ <value>The wsrm:{0} request message's wsa:ReplyTo address containing a URI which is not equivalent to the remote address. This is not supported. The reliable session was faulted.</value>
+ </data>
+ <data name="WsrmRequiredExceptionString" xml:space="preserve">
+ <value>The incoming message is not a WS-ReliableMessaging 1.1 message and could not be processed.</value>
+ </data>
+ <data name="WsrmRequiredFaultString" xml:space="preserve">
+ <value>The RM server requires the use of WS-ReliableMessaging 1.1 protocol. This is likely caused by a binding mismatch.</value>
+ </data>
+ <data name="SFxActionDemuxerDuplicate" xml:space="preserve">
+ <value>The operations {0} and {1} have the same action ({2}). Every operation must have a unique action value.</value>
+ </data>
+ <data name="SFxActionMismatch" xml:space="preserve">
+ <value>Cannot create a typed message due to action mismatch, expecting {0} encountered {1}</value>
+ </data>
+ <data name="SFxAnonymousTypeNotSupported" xml:space="preserve">
+ <value>Part {1} in message {0} cannot be exported with RPC or encoded since its type is anonymous.</value>
+ </data>
+ <data name="SFxAsyncResultsDontMatch0" xml:space="preserve">
+ <value>The IAsyncResult returned from Begin and the IAsyncResult supplied to the Callback are on different objects. These are required to be the same object.</value>
+ </data>
+ <data name="SFXBindingNameCannotBeNullOrEmpty" xml:space="preserve">
+ <value>Binding name cannot be null or empty.</value>
+ </data>
+ <data name="SFXUnvalidNamespaceValue" xml:space="preserve">
+ <value>Value '{0}' provided for {1} property is an invalid URI.</value>
+ </data>
+ <data name="SFXUnvalidNamespaceParam" xml:space="preserve">
+ <value>Parameter value '{0}' is an invalid URI.</value>
+ </data>
+ <data name="SFXHeaderNameCannotBeNullOrEmpty" xml:space="preserve">
+ <value>Header name cannot be null or empty.</value>
+ </data>
+ <data name="SFxEndpointNoMatchingScheme" xml:space="preserve">
+ <value>Could not find a base address that matches scheme {0} for the endpoint with binding {1}. Registered base address schemes are [{2}].</value>
+ </data>
+ <data name="SFxBindingSchemeDoesNotMatch" xml:space="preserve">
+ <value>The scheme '{0}' used by binding {1} does not match the required scheme '{2}'.</value>
+ </data>
+ <data name="SFxGetChannelDispatcherDoesNotSupportScheme" xml:space="preserve">
+ <value>Only a '{0}' using '{1}' or '{2}' is supported in this scenario.</value>
+ </data>
+ <data name="SFxIncorrectMessageVersion" xml:space="preserve">
+ <value>MessageVersion '{0}' is not supported in this scenario. Only MessageVersion '{1}' is supported.</value>
+ </data>
+ <data name="SFxBindingNotSupportedForMetadataHttpGet" xml:space="preserve">
+ <value>The binding associated with ServiceMetadataBehavior or ServiceDebugBehavior is not supported. The inner binding elements used by this binding must support IReplyChannel. Verify that HttpGetBinding/HttpsGetBinding (on ServiceMetadataBehavior) and HttpHelpPageBinding/HttpsHelpPageBinding (on ServiceDebugBehavior) are supported.</value>
+ </data>
+ <data name="SFxBadByReferenceParameterMetadata" xml:space="preserve">
+ <value>Method '{0}' in class '{1}' has bad parameter metadata: a pass-by-reference parameter is marked with the 'in' but not the 'out' parameter mode.</value>
+ </data>
+ <data name="SFxBadByValueParameterMetadata" xml:space="preserve">
+ <value>Method '{0}' in class '{1}' has bad parameter metadata: a pass-by-value parameter is marked with the 'out' parameter mode.</value>
+ </data>
+ <data name="SFxBadMetadataMustBePolicy" xml:space="preserve">
+ <value>When calling the CreateFromPolicy method, the policy argument must be an XmlElement instance with LocalName '{1}' and NamespaceUri '{0}'. This XmlElement has LocalName '{3}' and NamespaceUri '{2}'. </value>
+ </data>
+ <data name="SFxBadMetadataLocationUri" xml:space="preserve">
+ <value>The URI supplied to ServiceMetadataBehavior via the ExternalMetadataLocation property or the externalMetadataLocation attribute in the serviceMetadata section in config must be a relative URI or an absolute URI with an http or https scheme. '{0}' was specified, which is a absolute URI with {1} scheme.</value>
+ </data>
+ <data name="SFxBadMetadataLocationNoAppropriateBaseAddress" xml:space="preserve">
+ <value>The URL supplied to ServiceMetadataBehavior via the ExternalMetadataLocation property or the externalMetadataLocation attribute in the serviceMetadata section in config was a relative URL and there is no base address with which to resolve it. '{0}' was specified.</value>
+ </data>
+ <data name="SFxBadMetadataDialect" xml:space="preserve">
+ <value>There was a problem reading the MetadataSet argument: a MetadataSection instance with identifier '{0}' and dialect '{1}' has a Metadata property whose type does not match the dialect. The expected Metadata type for this dialect is '{2}' but was found to be '{3}'.</value>
+ </data>
+ <data name="SFxBadMetadataReference" xml:space="preserve">
+ <value>Metadata contains a reference that cannot be resolved: '{0}'.</value>
+ </data>
+ <data name="SFxMaximumResolvedReferencesOutOfRange" xml:space="preserve">
+ <value>The MaximumResolvedReferences property of MetadataExchangeClient must be greater than or equal to one. '{0}' was specified.</value>
+ </data>
+ <data name="SFxMetadataExchangeClientNoMetadataAddress" xml:space="preserve">
+ <value>The MetadataExchangeClient was not supplied with a MetadataReference or MetadataLocation from which to get metadata. You must supply one to the constructor, to the GetMetadata method, or to the BeginGetMetadata method.</value>
+ </data>
+ <data name="SFxMetadataExchangeClientCouldNotCreateChannelFactory" xml:space="preserve">
+ <value>The MetadataExchangeClient could not create an IChannelFactory for: address='{0}', dialect='{1}', and identifier='{2}'. </value>
+ </data>
+ <data name="SFxMetadataExchangeClientCouldNotCreateWebRequest" xml:space="preserve">
+ <value>The MetadataExchangeClient could not create an HttpWebRequest for: address='{0}', dialect='{1}', and identifier='{2}'. </value>
+ </data>
+ <data name="SFxMetadataExchangeClientCouldNotCreateChannelFactoryBadScheme" xml:space="preserve">
+ <value>The MetadataExchangeClient instance could not be initialized because no Binding is available for scheme '{0}'. You can supply a Binding in the constructor, or specify a configurationName.</value>
+ </data>
+ <data name="SFxBadTransactionProtocols" xml:space="preserve">
+ <value>The TransactionProtocol setting was not understood. A supported protocol must be specified.</value>
+ </data>
+ <data name="SFxMetadataResolverKnownContractsArgumentCannotBeEmpty" xml:space="preserve">
+ <value>The MetadataResolver cannot recieve an empty contracts argument to the Resolve or BeginResolve methods. You must supply at least one ContractDescription.</value>
+ </data>
+ <data name="SFxMetadataResolverKnownContractsUniqueQNames" xml:space="preserve">
+ <value>The ContractDescriptions in contracts must all have unique Name and Namespace pairs. More than one ContractDescription had the pair Name='{0}' and Namespace='{1}'. </value>
+ </data>
+ <data name="SFxMetadataResolverKnownContractsCannotContainNull" xml:space="preserve">
+ <value>The contracts argument to the Resolve or BeginResolve methods cannot contain a null ContractDescription.</value>
+ </data>
+ <data name="SFxBindingDoesNotHaveATransportBindingElement" xml:space="preserve">
+ <value>The binding specified to do metadata exchange does not contain a TransportBindingElement.</value>
+ </data>
+ <data name="SFxBindingMustContainTransport2" xml:space="preserve">
+ <value>The binding (Name={0}, Namespace={1}) does not contain a TransportBindingElement.</value>
+ </data>
+ <data name="SFxBodyCannotBeNull" xml:space="preserve">
+ <value>Body object cannot be null in message {0}</value>
+ </data>
+ <data name="SFxBodyObjectTypeCannotBeInherited" xml:space="preserve">
+ <value>Type {0} cannot inherit from any class other than object to be used as body object in RPC style.</value>
+ </data>
+ <data name="SFxBodyObjectTypeCannotBeInterface" xml:space="preserve">
+ <value>Type {0} implements interface {1} which is not supported for body object in RPC style.</value>
+ </data>
+ <data name="SFxCallbackBehaviorAttributeOnlyOnDuplex" xml:space="preserve">
+ <value>CallbackBehaviorAttribute can only be run as a behavior on an endpoint with a duplex contract. Contract '{0}' is not duplex, as it contains no callback operations.</value>
+ </data>
+ <data name="SFxCallbackRequestReplyInOrder1" xml:space="preserve">
+ <value>This operation would deadlock because the reply cannot be received until the current Message completes processing. If you want to allow out-of-order message processing, specify ConcurrencyMode of Reentrant or Multiple on {0}.</value>
+ </data>
+ <data name="SfxCallbackTypeCannotBeNull" xml:space="preserve">
+ <value>In order to use the contract '{0}' with DuplexChannelFactory, the contract must specify a valid callback contract. If your contract does not have a callback contract, consider using ChannelFactory instead of DuplexChannelFactory.</value>
+ </data>
+ <data name="SFxCannotActivateCallbackInstace" xml:space="preserve">
+ <value>The dispatch instance for duplex callbacks cannot be activated - you must provide an instance.</value>
+ </data>
+ <data name="SFxCannotCallAddBaseAddress" xml:space="preserve">
+ <value>ServiceHostBase's AddBaseAddress method cannot be called after the InitializeDescription method has completed.</value>
+ </data>
+ <data name="SFxCannotCallAutoOpenWhenExplicitOpenCalled" xml:space="preserve">
+ <value>Cannot make a call on this channel because a call to Open() is in progress.</value>
+ </data>
+ <data name="SFxCannotGetMetadataFromRelativeAddress" xml:space="preserve">
+ <value>The MetadataExchangeClient can only get metadata from absolute addresses. It cannot get metadata from '{0}'.</value>
+ </data>
+ <data name="SFxCannotHttpGetMetadataFromAddress" xml:space="preserve">
+ <value>The MetadataExchangeClient can only get metadata from http or https addresses when using MetadataExchangeClientMode HttpGet. It cannot get metadata from '{0}'.</value>
+ </data>
+ <data name="SFxCannotGetMetadataFromLocation" xml:space="preserve">
+ <value>The MetadataExchangeClient can only get metadata from http and https MetadataLocations. It cannot get metadata from '{0}'.</value>
+ </data>
+ <data name="SFxCannotHaveDifferentTransactionProtocolsInOneBinding" xml:space="preserve">
+ <value>The configured policy specifies more than one TransactionProtocol across the operations. A single TransactionProtocol for each endpoint must be specified.</value>
+ </data>
+ <data name="SFxCannotImportAsParameters_Bare" xml:space="preserve">
+ <value>Generating message contract since the operation {0} is neither RPC nor document wrapped.</value>
+ </data>
+ <data name="SFxCannotImportAsParameters_DifferentWrapperNs" xml:space="preserve">
+ <value>Generating message contract since the wrapper namespace ({1}) of message {0} does not match the default value ({2})</value>
+ </data>
+ <data name="SFxCannotImportAsParameters_DifferentWrapperName" xml:space="preserve">
+ <value>Generating message contract since the wrapper name ({1}) of message {0} does not match the default value ({2})</value>
+ </data>
+ <data name="SFxCannotImportAsParameters_ElementIsNotNillable" xml:space="preserve">
+ <value>Generating message contract since element name {0} from namespace {1} is not marked nillable</value>
+ </data>
+ <data name="SFxCannotImportAsParameters_MessageHasProtectionLevel" xml:space="preserve">
+ <value>Generating message contract since message {0} requires protection.</value>
+ </data>
+ <data name="SFxCannotImportAsParameters_HeadersAreIgnoredInEncoded" xml:space="preserve">
+ <value>Headers are not supported in RPC encoded format. Headers are ignored in message {0}.</value>
+ </data>
+ <data name="SFxCannotImportAsParameters_HeadersAreUnsupported" xml:space="preserve">
+ <value>Generating message contract since message {0} has headers</value>
+ </data>
+ <data name="SFxCannotImportAsParameters_Message" xml:space="preserve">
+ <value>Generating message contract since the operation {0} has untyped Message as argument or return type</value>
+ </data>
+ <data name="SFxCannotImportAsParameters_NamespaceMismatch" xml:space="preserve">
+ <value>Generating message contract since message part namespace ({0}) does not match the default value ({1})</value>
+ </data>
+ <data name="SFxCannotRequireBothSessionAndDatagram3" xml:space="preserve">
+ <value>There are two contracts listening on the same binding ({2}) and address with conflicting settings. Specifically, the contract '{0}' specifies SessionMode.NotAllowed while the contract '{1}' specifies SessionMode.Required. You should either change one of the SessionMode values or specify a different address (or ListenUri) for each endpoint.</value>
+ </data>
+ <data name="SFxCannotSetExtensionsByIndex" xml:space="preserve">
+ <value>This collection does not support setting extensions by index. Please consider using the InsertItem or RemoveItem methods.</value>
+ </data>
+ <data name="SFxChannelDispatcherDifferentHost0" xml:space="preserve">
+ <value>This ChannelDispatcher is not currently attached to the provided ServiceHost.</value>
+ </data>
+ <data name="SFxChannelDispatcherMultipleHost0" xml:space="preserve">
+ <value>Cannot add a ChannelDispatcher to more than one ServiceHost.</value>
+ </data>
+ <data name="SFxChannelDispatcherNoHost0" xml:space="preserve">
+ <value>Cannot open ChannelDispatcher because it is not attached to a ServiceHost.</value>
+ </data>
+ <data name="SFxChannelDispatcherNoMessageVersion" xml:space="preserve">
+ <value>Cannot open ChannelDispatcher because it is does not have a MessageVersion set.</value>
+ </data>
+ <data name="SFxChannelDispatcherUnableToOpen1" xml:space="preserve">
+ <value>The ChannelDispatcher at '{0}' is unable to open its IChannelListener as there are no endpoints for the ChannelDispatcher.</value>
+ </data>
+ <data name="SFxChannelDispatcherUnableToOpen2" xml:space="preserve">
+ <value>The ChannelDispatcher at '{0}' with contract(s) '{1}' is unable to open its IChannelListener.</value>
+ </data>
+ <data name="SFxChannelFactoryTypeMustBeInterface" xml:space="preserve">
+ <value>The type argument passed to the generic ChannelFactory class must be an interface type.</value>
+ </data>
+ <data name="SFxChannelFactoryCannotApplyConfigurationWithoutEndpoint" xml:space="preserve">
+ <value>ApplyConfiguration requires that the Endpoint property be initialized. Either provide a valid ServiceEndpoint in the CreateDescription method or override the ApplyConfiguration method to provide an alternative implementation.</value>
+ </data>
+ <data name="SFxChannelFactoryCannotCreateFactoryWithoutDescription" xml:space="preserve">
+ <value>CreateFactory requires that the Endpoint property be initialized. Either provide a valid ServiceEndpoint in the CreateDescription method or override the CreateFactory method to provide an alternative implementation.</value>
+ </data>
+ <data name="SFxChannelTerminated0" xml:space="preserve">
+ <value>An operation marked as IsTerminating has already been invoked on this channel, causing the channel's connection to terminate. No more operations may be invoked on this channel. Please re-create the channel to continue communication.</value>
+ </data>
+ <data name="SFxClientOutputSessionAutoClosed" xml:space="preserve">
+ <value>This channel can no longer be used to send messages as the output session was auto-closed due to a server-initiated shutdown. Either disable auto-close by setting the DispatchRuntime.AutomaticInputSessionShutdown to false, or consider modifying the shutdown protocol with the remote server.</value>
+ </data>
+ <data name="SFxCodeGenArrayTypeIsNotSupported" xml:space="preserve">
+ <value>Array of type {0} is not supported.</value>
+ </data>
+ <data name="SFxCodeGenCanOnlyStoreIntoArgOrLocGot0" xml:space="preserve">
+ <value>Can only store into ArgBuilder or LocalBuilder. Got: {0}.</value>
+ </data>
+ <data name="SFxCodeGenExpectingEnd" xml:space="preserve">
+ <value>Expecting End {0}.</value>
+ </data>
+ <data name="SFxCodeGenIsNotAssignableFrom" xml:space="preserve">
+ <value>{0} is not assignable from {1}.</value>
+ </data>
+ <data name="SFxCodeGenNoConversionPossibleTo" xml:space="preserve">
+ <value>No conversion possible to {0}.</value>
+ </data>
+ <data name="SFxCodeGenWarning" xml:space="preserve">
+ <value>CODEGEN: {0}</value>
+ </data>
+ <data name="SFxCodeGenUnknownConstantType" xml:space="preserve">
+ <value>Internal Error: Unrecognized constant type {0}.</value>
+ </data>
+ <data name="SFxCollectionDoesNotSupportSet0" xml:space="preserve">
+ <value>This collection does not support setting items by index.</value>
+ </data>
+ <data name="SFxCollectionReadOnly" xml:space="preserve">
+ <value>This operation is not supported because the collection is read-only.</value>
+ </data>
+ <data name="SFxCollectionWrongType2" xml:space="preserve">
+ <value>The collection of type {0} does not support values of type {1}.</value>
+ </data>
+ <data name="SFxConflictingGlobalElement" xml:space="preserve">
+ <value>Top level XML element with name {0} in namespace {1} cannot reference {2} type because it already references a different type ({3}). Use a different operation name or MessageBodyMemberAttribute to specify a different name for the Message or Message parts.</value>
+ </data>
+ <data name="SFxConflictingGlobalType" xml:space="preserve">
+ <value>Duplicate top level XML Schema type with name {0} in namespace {1}.</value>
+ </data>
+ <data name="SFxContextModifiedInsideScope0" xml:space="preserve">
+ <value>The value of OperationContext.Current is not the OperationContext value installed by this OperationContextScope.</value>
+ </data>
+ <data name="SFxContractDescriptionNameCannotBeEmpty" xml:space="preserve">
+ <value>ContractDescription's Name must be a non-empty string.</value>
+ </data>
+ <data name="SFxContractHasZeroOperations" xml:space="preserve">
+ <value>ContractDescription '{0}' has zero operations; a contract must have at least one operation.</value>
+ </data>
+ <data name="SFxContractHasZeroInitiatingOperations" xml:space="preserve">
+ <value>ContractDescription '{0}' has zero IsInitiating=true operations; a contract must have at least one IsInitiating=true operation.</value>
+ </data>
+ <data name="SFxContractInheritanceRequiresInterfaces" xml:space="preserve">
+ <value>The service class of type {0} both defines a ServiceContract and inherits a ServiceContract from type {1}. Contract inheritance can only be used among interface types. If a class is marked with ServiceContractAttribute, it must be the only type in the hierarchy with ServiceContractAttribute. Consider moving the ServiceContractAttribute on type {1} to a separate interface that type {1} implements.</value>
+ </data>
+ <data name="SFxContractInheritanceRequiresInterfaces2" xml:space="preserve">
+ <value>The service class of type {0} both defines a ServiceContract and inherits a ServiceContract from type {1}. Contract inheritance can only be used among interface types. If a class is marked with ServiceContractAttribute, then another service class cannot derive from it.</value>
+ </data>
+ <data name="SFxCopyToRequiresICollection" xml:space="preserve">
+ <value>SynchronizedReadOnlyCollection's CopyTo only works if the underlying list implements ICollection.</value>
+ </data>
+ <data name="SFxCreateDuplexChannel1" xml:space="preserve">
+ <value>The callback contract of contract {0} either does not exist or does not define any operations. If this is not a duplex contract, consider using ChannelFactory instead of DuplexChannelFactory.</value>
+ </data>
+ <data name="SFxCreateDuplexChannelNoCallback" xml:space="preserve">
+ <value>This CreateChannel overload cannot be called on this instance of DuplexChannelFactory, as the DuplexChannelFactory was not initialized with an InstanceContext. Please call the CreateChannel overload that takes an InstanceContext.</value>
+ </data>
+ <data name="SFxCreateDuplexChannelNoCallback1" xml:space="preserve">
+ <value>This CreateChannel overload cannot be called on this instance of DuplexChannelFactory, as the DuplexChannelFactory was initialized with a Type and no valid InstanceContext was provided. Please call the CreateChannel overload that takes an InstanceContext.</value>
+ </data>
+ <data name="SFxCreateDuplexChannelNoCallbackUserObject" xml:space="preserve">
+ <value>This CreateChannel overload cannot be called on this instance of DuplexChannelFactory, as the InstanceContext provided to the DuplexChannelFactory does not contain a valid UserObject.</value>
+ </data>
+ <data name="SFxCreateDuplexChannelBadCallbackUserObject" xml:space="preserve">
+ <value>The InstanceContext provided to the ChannelFactory contains a UserObject that does not implement the CallbackContractType '{0}'.</value>
+ </data>
+ <data name="SFxCreateNonDuplexChannel1" xml:space="preserve">
+ <value>ChannelFactory does not support the contract {0} as it defines a callback contract with one or more operations. Please consider using DuplexChannelFactory instead of ChannelFactory.</value>
+ </data>
+ <data name="SFxCustomBindingNeedsTransport1" xml:space="preserve">
+ <value>The CustomBinding on the ServiceEndpoint with contract '{0}' lacks a TransportBindingElement. Every binding must have at least one binding element that derives from TransportBindingElement.</value>
+ </data>
+ <data name="SFxCustomBindingWithoutTransport" xml:space="preserve">
+ <value>The Scheme cannot be computed for this binding because this CustomBinding lacks a TransportBindingElement. Every binding must have at least one binding element that derives from TransportBindingElement.</value>
+ </data>
+ <data name="SFxDeserializationFailed1" xml:space="preserve">
+ <value>The formatter threw an exception while trying to deserialize the message: {0}</value>
+ </data>
+ <data name="SFxDictionaryIsEmpty" xml:space="preserve">
+ <value>This operation is not possible since the dictionary is empty.</value>
+ </data>
+ <data name="SFxDisallowedAttributeCombination" xml:space="preserve">
+ <value>The type or member named '{0}' could not be loaded because it has two incompatible attributes: '{1}' and '{2}'. To fix the problem, remove one of the attributes from the type or member.</value>
+ </data>
+ <data name="SFxEndpointAddressNotSpecified" xml:space="preserve">
+ <value>The endpoint's address is not specified. </value>
+ </data>
+ <data name="SFxEndpointContractNotSpecified" xml:space="preserve">
+ <value>The endpoint's contract is not specified.</value>
+ </data>
+ <data name="SFxEndpointBindingNotSpecified" xml:space="preserve">
+ <value>The endpoint's binding is not specified.</value>
+ </data>
+ <data name="SFxInitializationUINotCalled" xml:space="preserve">
+ <value>The channel is configured to use interactive initializer '{0}', but the channel was Opened without calling DisplayInitializationUI. Call DisplayInitializationUI before calling Open or other methods on this channel.</value>
+ </data>
+ <data name="SFxInitializationUIDisallowed" xml:space="preserve">
+ <value>AllowInitializationUI was set to false for this channel, but the channel is configured to use the '{0}' as an interactive initializer.</value>
+ </data>
+ <data name="SFxDocExt_NoMetadataSection1" xml:space="preserve">
+ <value>This is a Windows&amp;#169; Communication Foundation service.&lt;BR/&gt;&lt;BR/&gt;&lt;B&gt;Metadata publishing for this service is currently disabled.&lt;/B&gt;&lt;BR/&gt;&lt;BR/&gt;If you have access to the service, you can enable metadata publishing by completing the following steps to modify your web or application configuration file:&lt;BR/&gt;&lt;BR/&gt;1. Create the following service behavior configuration, or add the &amp;lt;serviceMetadata&amp;gt; element to an existing service behavior configuration:</value>
+ </data>
+ <data name="SFxDocExt_NoMetadataSection2" xml:space="preserve">
+ <value>2. Add the behavior configuration to the service:</value>
+ </data>
+ <data name="SFxDocExt_NoMetadataSection3" xml:space="preserve">
+ <value>Note: the service name must match the configuration name for the service implementation.&lt;BR/&gt;&lt;BR/&gt;3. Add the following endpoint to your service configuration:</value>
+ </data>
+ <data name="SFxDocExt_NoMetadataSection4" xml:space="preserve">
+ <value>Note: your service must have an http base address to add this endpoint.&lt;BR/&gt;&lt;BR/&gt;The following is an example service configuration file with metadata publishing enabled:</value>
+ </data>
+ <data name="SFxDocExt_NoMetadataSection5" xml:space="preserve">
+ <value>For more information on publishing metadata please see the following documentation: &lt;a href="http://go.microsoft.com/fwlink/?LinkId=65455"&gt;http://go.microsoft.com/fwlink/?LinkId=65455&lt;/a&gt;.</value>
+ </data>
+ <data name="SFxDocExt_NoMetadataConfigComment1" xml:space="preserve">
+ <value>Note: the service name must match the configuration name for the service implementation.</value>
+ </data>
+ <data name="SFxDocExt_NoMetadataConfigComment2" xml:space="preserve">
+ <value>Add the following endpoint. </value>
+ </data>
+ <data name="SFxDocExt_NoMetadataConfigComment3" xml:space="preserve">
+ <value>Note: your service must have an http base address to add this endpoint.</value>
+ </data>
+ <data name="SFxDocExt_NoMetadataConfigComment4" xml:space="preserve">
+ <value>Add the following element to your service behavior configuration.</value>
+ </data>
+ <data name="SFxDocExt_CS" xml:space="preserve">
+ <value>&lt;P class='intro'&gt;&lt;B&gt;C#&lt;/B&gt;&lt;/P&gt;</value>
+ </data>
+ <data name="SFxDocExt_VB" xml:space="preserve">
+ <value>&lt;P class='intro'&gt;&lt;B&gt;Visual Basic&lt;/B&gt;&lt;/P&gt;</value>
+ </data>
+ <data name="SFxDocExt_MainPageTitleNoServiceName" xml:space="preserve">
+ <value>Service</value>
+ </data>
+ <data name="SFxDocExt_MainPageTitle" xml:space="preserve">
+ <value>{0} Service</value>
+ </data>
+ <data name="SFxDocExt_MainPageIntro1a" xml:space="preserve">
+ <value>You have created a service.&lt;P class='intro'&gt;To test this service, you will need to create a client and use it to call the service. You can do this using the svcutil.exe tool from the command line with the following syntax:&lt;/P&gt; </value>
+ </data>
+ <data name="SFxDocExt_MainPageIntro1b" xml:space="preserve">
+ <value>You have created a service.&lt;P class='intro'&gt;To test this service, you will need to create a client and use it to call the service; however, metadata publishing via ?WSDL is currently disabled. This can be enabled via the service's configuration file. &lt;/P&gt;</value>
+ </data>
+ <data name="SFxDocExt_MainPageIntro2" xml:space="preserve">
+ <value>This will generate a configuration file and a code file that contains the client class. Add the two files to your client application and use the generated client class to call the Service. For example:&lt;BR/&gt;</value>
+ </data>
+ <data name="SFxDocExt_MainPageComment" xml:space="preserve">
+ <value>Use the 'client' variable to call operations on the service.</value>
+ </data>
+ <data name="SFxDocExt_MainPageComment2" xml:space="preserve">
+ <value>Always close the client.</value>
+ </data>
+ <data name="SFxDocExt_Error" xml:space="preserve">
+ <value>The service encountered an error.</value>
+ </data>
+ <data name="SFxDocEncodedNotSupported" xml:space="preserve">
+ <value>Operation '{0}' could not be loaded as it uses an unsupported combination of Use and Style settings: Document with Encoded. To fix the problem, change the Use setting to Literal or change the Style setting to Rpc.</value>
+ </data>
+ <data name="SFxDocEncodedFaultNotSupported" xml:space="preserve">
+ <value>Fault could not be loaded as the Use setting is Encoded and it references a schema definition using Element attribute. To fix the problem, change the Use setting to Literal.</value>
+ </data>
+ <data name="SFxDuplicateMessageParts" xml:space="preserve">
+ <value>Message part {0} in namespace {1} appears more than once in Message.</value>
+ </data>
+ <data name="SFxDuplicateInitiatingActionAtSameVia" xml:space="preserve">
+ <value>This service has multiple endpoints listening at '{0}' which share the same initiating action '{1}'. As a result, messages with this action would be dropped since the dispatcher would not be able to determine the correct endpoint for handling the message. Please consider hosting these Endpoints at separate ListenUris.</value>
+ </data>
+ <data name="SFXEndpointBehaviorUsedOnWrongSide" xml:space="preserve">
+ <value>The IEndpointBehavior '{0}' cannot be used on the server side; this behavior can only be applied to clients.</value>
+ </data>
+ <data name="SFxEndpointDispatcherMultipleChannelDispatcher0" xml:space="preserve">
+ <value>Cannot add EndpointDispatcher to more than one ChannelDispatcher.</value>
+ </data>
+ <data name="SFxEndpointDispatcherDifferentChannelDispatcher0" xml:space="preserve">
+ <value>This EndpointDispatcher is not currently attached to the provided ChannelDispatcher.</value>
+ </data>
+ <data name="SFxErrorCreatingMtomReader" xml:space="preserve">
+ <value>Error creating a reader for the MTOM message</value>
+ </data>
+ <data name="SFxErrorDeserializingRequestBody" xml:space="preserve">
+ <value>Error in deserializing body of request message for operation '{0}'.</value>
+ </data>
+ <data name="SFxErrorDeserializingRequestBodyMore" xml:space="preserve">
+ <value>Error in deserializing body of request message for operation '{0}'. {1}</value>
+ </data>
+ <data name="SFxErrorDeserializingReplyBody" xml:space="preserve">
+ <value>Error in deserializing body of reply message for operation '{0}'.</value>
+ </data>
+ <data name="SFxErrorDeserializingReplyBodyMore" xml:space="preserve">
+ <value>Error in deserializing body of reply message for operation '{0}'. {1}</value>
+ </data>
+ <data name="SFxErrorSerializingBody" xml:space="preserve">
+ <value>There was an error in serializing body of message {0}: '{1}'. Please see InnerException for more details.</value>
+ </data>
+ <data name="SFxErrorDeserializingHeader" xml:space="preserve">
+ <value>There was an error in deserializing one of the headers in message {0}. Please see InnerException for more details.</value>
+ </data>
+ <data name="SFxErrorSerializingHeader" xml:space="preserve">
+ <value>There was an error in serializing one of the headers in message {0}: '{1}'. Please see InnerException for more details.</value>
+ </data>
+ <data name="SFxErrorDeserializingFault" xml:space="preserve">
+ <value>Server returned an invalid SOAP Fault. Please see InnerException for more details.</value>
+ </data>
+ <data name="SFxErrorReflectingOnType2" xml:space="preserve">
+ <value>An error occurred while loading attribute '{0}' on type '{1}'. Please see InnerException for more details.</value>
+ </data>
+ <data name="SFxErrorReflectingOnMethod3" xml:space="preserve">
+ <value>An error occurred while loading attribute '{0}' on method '{1}' in type '{2}'. Please see InnerException for more details.</value>
+ </data>
+ <data name="SFxErrorReflectingOnParameter4" xml:space="preserve">
+ <value>An error occurred while loading attribute '{0}' on parameter {1} of method '{2}' in type '{3}'. Please see InnerException for more details.</value>
+ </data>
+ <data name="SFxErrorReflectionOnUnknown1" xml:space="preserve">
+ <value>An error occurred while loading attribute '{0}'. Please see InnerException for more details.</value>
+ </data>
+ <data name="SFxExceptionDetailEndOfInner" xml:space="preserve">
+ <value>--- End of inner ExceptionDetail stack trace ---</value>
+ </data>
+ <data name="SFxExceptionDetailFormat" xml:space="preserve">
+ <value>An ExceptionDetail, likely created by IncludeExceptionDetailInFaults=true, whose value is:</value>
+ </data>
+ <data name="SFxExpectedIMethodCallMessage" xml:space="preserve">
+ <value>Internal Error: Message must be a valid IMethodCallMessage.</value>
+ </data>
+ <data name="SFxExportMustHaveType" xml:space="preserve">
+ <value>The specified ContractDescription could not be exported to WSDL because the Type property of the MessagePartDescription with name '{1}' in the OperationDescription with name '{0}' is not set. The Type property must be set in order to create WSDL.</value>
+ </data>
+ <data name="SFxFaultCannotBeImported" xml:space="preserve">
+ <value>Fault named {0} in operation {1} cannot be imported. {2}</value>
+ </data>
+ <data name="SFxFaultContractDuplicateDetailType" xml:space="preserve">
+ <value>In operation {0}, more than one fault is declared with detail type {1}</value>
+ </data>
+ <data name="SFxFaultContractDuplicateElement" xml:space="preserve">
+ <value>In operation {0}, more than one fault is declared with element name {1} in namespace {2}</value>
+ </data>
+ <data name="SFxFaultExceptionToString3" xml:space="preserve">
+ <value>{0}: {1} (Fault Detail is equal to {2}).</value>
+ </data>
+ <data name="SFxFaultReason" xml:space="preserve">
+ <value>The creator of this fault did not specify a Reason.</value>
+ </data>
+ <data name="SFxFaultTypeAnonymous" xml:space="preserve">
+ <value>In operation {0}, the schema type corresponding to the fault detail type {1} is anonymous. Please set Fault name explicitly to export anonymous types.</value>
+ </data>
+ <data name="SFxHeaderNameMismatchInMessageContract" xml:space="preserve">
+ <value>Header name mismatch in member {1} of type {0}. The header name found in the description is {2}. The element name deduced by the formatter is {3}. This mismatch can happen if the ElementName specified in XmlElementAttribute or XmlArrayAttribute does not match the name specified in the MessageHeaderAttribute or MessageHeaderArrayAttribute or the member name.</value>
+ </data>
+ <data name="SFxHeaderNameMismatchInOperation" xml:space="preserve">
+ <value>Header name mismatch in operation {0} from contract {1}:{2}. The header name found in the description is {3}. The element name deduced by the formatter is {4}. This mismatch can happen if the ElementName specified in XmlElementAttribute or XmlArrayAttribute does not match the name specified in the MessageHeaderAttribute or MessageHeaderArrayAttribute or the member name.</value>
+ </data>
+ <data name="SFxHeaderNamespaceMismatchInMessageContract" xml:space="preserve">
+ <value>Header namespace mismatch in member {1} of type {0}. The header namespace found in the description is {2}. The element namespace deduced by the formatter is {3}. This mismatch can happen if the Namespace specified in XmlElementAttribute or XmlArrayAttribute does not match the namespace specified in the MessageHeaderAttribute or MessageHeaderArrayAttribute or the contract namespace.</value>
+ </data>
+ <data name="SFxHeaderNamespaceMismatchInOperation" xml:space="preserve">
+ <value>Header namespace mismatch in operation {0} from contract {1}:{2}. The header namespace found in the description is {3}. The element namespace deduced by the formatter is {4}. This mismatch can happen if the Namespace specified in XmlElementAttribute or XmlArrayAttribute does not match the namespace specified in the MessageHeaderAttribute or MessageHeaderArrayAttribute or the contract namespace.</value>
+ </data>
+ <data name="SFxHeaderNotUnderstood" xml:space="preserve">
+ <value>The header '{0}' from the namespace '{1}' was not understood by the recipient of this message, causing the message to not be processed. This error typically indicates that the sender of this message has enabled a communication protocol that the receiver cannot process. Please ensure that the configuration of the client's binding is consistent with the service's binding. </value>
+ </data>
+ <data name="SFxHeadersAreNotSupportedInEncoded" xml:space="preserve">
+ <value>Message {0} must not have headers to be used in RPC encoded style.</value>
+ </data>
+ <data name="SFxImmutableServiceHostBehavior0" xml:space="preserve">
+ <value>This value cannot be changed after the ServiceHost has opened.</value>
+ </data>
+ <data name="SFxImmutableChannelFactoryBehavior0" xml:space="preserve">
+ <value>This value cannot be changed after the ChannelFactory has opened.</value>
+ </data>
+ <data name="SFxImmutableClientBaseCacheSetting" xml:space="preserve">
+ <value>This value cannot be changed after the first ClientBase of type '{0}' has been created.</value>
+ </data>
+ <data name="SFxImmutableThrottle1" xml:space="preserve">
+ <value>{0} cannot be changed after the ServiceHost has opened.</value>
+ </data>
+ <data name="SFxInconsistentBindingBodyParts" xml:space="preserve">
+ <value>Operation {0} binding {1} has extra part {2} that is not present in other bindings</value>
+ </data>
+ <data name="SFxInconsistentWsdlOperationStyleInHeader" xml:space="preserve">
+ <value>Style {1} on header {0} does not match expected style {2}.</value>
+ </data>
+ <data name="SFxInconsistentWsdlOperationStyleInMessageParts" xml:space="preserve">
+ <value>All parts of message in operation {0} must either contain type or element. </value>
+ </data>
+ <data name="SFxInconsistentWsdlOperationStyleInOperationMessages" xml:space="preserve">
+ <value>Style {1} inferred from messages in operation {0} does not match expected style {2} specified via bindings.</value>
+ </data>
+ <data name="SFxInconsistentWsdlOperationUseAndStyleInBinding" xml:space="preserve">
+ <value>Bindings for operation {0} cannot specify different use and style values. Binding {1} specifies use {2} and style {3} while binding {4} specifies use {5} and style {6}.</value>
+ </data>
+ <data name="SFxInconsistentWsdlOperationUseInBindingExtensions" xml:space="preserve">
+ <value>Extensions for operation {0} in binding {1} cannot specify different use values.</value>
+ </data>
+ <data name="SFxInconsistentWsdlOperationUseInBindingMessages" xml:space="preserve">
+ <value>Message bindings for operation {0} in binding {1} cannot specify different use values.</value>
+ </data>
+ <data name="SFxInconsistentWsdlOperationUseInBindingFaults" xml:space="preserve">
+ <value>Fault bindings for operation {0} in binding {1} cannot specify different use values.</value>
+ </data>
+ <data name="SFxInputParametersToServiceInvalid" xml:space="preserve">
+ <value>Service implementation object invoked with wrong number of input parameters, operation expects {0} parameters but was called with {1} parameters.</value>
+ </data>
+ <data name="SFxInputParametersToServiceNull" xml:space="preserve">
+ <value>Service implementation object invoked with null input parameters, but operation expects {0} parameters.</value>
+ </data>
+ <data name="SFxInstanceNotInitialized" xml:space="preserve">
+ <value>The InstanceContext has no provider for creating Service implementation objects.</value>
+ </data>
+ <data name="SFxInterleavedContextScopes0" xml:space="preserve">
+ <value>This OperationContextScope is being disposed out of order.</value>
+ </data>
+ <data name="SFxInternalServerError" xml:space="preserve">
+ <value>The server was unable to process the request due to an internal error. For more information about the error, either turn on IncludeExceptionDetailInFaults (either from ServiceBehaviorAttribute or from the &lt;serviceDebug&gt; configuration behavior) on the server in order to send the exception information back to the client, or turn on tracing as per the Microsoft .NET Framework SDK documentation and inspect the server trace logs.</value>
+ </data>
+ <data name="SFxInternalCallbackError" xml:space="preserve">
+ <value>The client was unable to process the callback request due to an internal error. For more information about the error, either turn on IncludeExceptionDetailInFaults (either from CallbackBehaviorAttribute or from the &lt;clientDebug&gt; configuration behavior) on the client in order to send the exception information back to the server, or turn on tracing as per the Microsoft .NET Framework SDK documentation and inspect the client trace logs.</value>
+ </data>
+ <data name="SFxInvalidAsyncResultState0" xml:space="preserve">
+ <value>IAsyncResult's State must be the state argument passed to your Begin call.</value>
+ </data>
+ <data name="SFxInvalidCallbackIAsyncResult" xml:space="preserve">
+ <value>IAsyncResult not provided or of wrong type.</value>
+ </data>
+ <data name="SFxInvalidCallbackContractType" xml:space="preserve">
+ <value>The CallbackContract {0} is invalid because it is not an interface type.</value>
+ </data>
+ <data name="SFxInvalidChannelToOperationContext" xml:space="preserve">
+ <value>Invalid IContextChannel passed to OperationContext. Must be either a server dispatching channel or a client proxy channel.</value>
+ </data>
+ <data name="SFxInvalidContextScopeThread0" xml:space="preserve">
+ <value>This OperationContextScope is being disposed on a different thread than it was created.</value>
+ </data>
+ <data name="SFxInvalidMessageBody" xml:space="preserve">
+ <value>OperationFormatter encountered an invalid Message body. Expected to find node type 'Element' with name '{0}' and namespace '{1}'. Found node type '{2}' with name '{3}' and namespace '{4}'</value>
+ </data>
+ <data name="SFxInvalidMessageBodyEmptyMessage" xml:space="preserve">
+ <value>The OperationFormatter could not deserialize any information from the Message because the Message is empty (IsEmpty = true).</value>
+ </data>
+ <data name="SFxInvalidMessageBodyErrorSerializingParameter" xml:space="preserve">
+ <value>There was an error while trying to serialize parameter {0}:{1}. The InnerException message was '{2}'. Please see InnerException for more details.</value>
+ </data>
+ <data name="SFxInvalidMessageBodyErrorDeserializingParameter" xml:space="preserve">
+ <value>There was an error while trying to deserialize parameter {0}:{1}. Please see InnerException for more details.</value>
+ </data>
+ <data name="SFxInvalidMessageBodyErrorDeserializingParameterMore" xml:space="preserve">
+ <value>There was an error while trying to deserialize parameter {0}:{1}. The InnerException message was '{2}'. Please see InnerException for more details.</value>
+ </data>
+ <data name="SFxInvalidMessageContractSignature" xml:space="preserve">
+ <value>The operation {0} either has a parameter or a return type that is attributed with MessageContractAttribute. In order to represent the request message using a Message Contract, the operation must have a single parameter attributed with MessageContractAttribute. In order to represent the response message using a Message Contract, the operation's return value must be a type that is attributed with MessageContractAttribute and the operation may not have any out or ref parameters.</value>
+ </data>
+ <data name="SFxInvalidMessageHeaderArrayType" xml:space="preserve">
+ <value>MessageHeaderArrayAttribute found on member {0} is not a single dimensional array.</value>
+ </data>
+ <data name="SFxInvalidRequestAction" xml:space="preserve">
+ <value>Outgoing request message for operation '{0}' specified Action='{1}', but contract for that operation specifies Action='{2}'. The Action specified in the Message must match the Action in the contract, or the operation contract must specify Action='*'.</value>
+ </data>
+ <data name="SFxInvalidReplyAction" xml:space="preserve">
+ <value>Outgoing reply message for operation '{0}' specified Action='{1}', but contract for that operation specifies ReplyAction='{2}'. The Action specified in the Message must match the ReplyAction in the contract, or the operation contract must specify ReplyAction='*'.</value>
+ </data>
+ <data name="SFxInvalidStreamInTypedMessage" xml:space="preserve">
+ <value>In order to use Streams with the MessageContract programming model, the type {0} must have a single member with MessageBodyMember attribute and the member type must be Stream.</value>
+ </data>
+ <data name="SFxInvalidStreamInRequest" xml:space="preserve">
+ <value>For request in operation {0} to be a stream the operation must have a single parameter whose type is Stream.</value>
+ </data>
+ <data name="SFxInvalidStreamInResponse" xml:space="preserve">
+ <value>For response in operation {0} to be a stream the operation must have a single out parameter or return value whose type is Stream.</value>
+ </data>
+ <data name="SFxInvalidStreamOffsetLength" xml:space="preserve">
+ <value>Buffer size must be at least {0} bytes.</value>
+ </data>
+ <data name="SFxInvalidUseOfPrimitiveOperationFormatter" xml:space="preserve">
+ <value>The PrimitiveOperationFormatter was given a parameter or return type which it does not support.</value>
+ </data>
+ <data name="SFxInvalidStaticOverloadCalledForDuplexChannelFactory1" xml:space="preserve">
+ <value>The static CreateChannel method cannot be used with the contract {0} because that contract defines a callback contract. Please try using one of the static CreateChannel overloads on DuplexChannelFactory&lt;TChannel&gt;.</value>
+ </data>
+ <data name="SFxInvalidSoapAttribute" xml:space="preserve">
+ <value>XmlSerializer attribute {0} is not valid in {1}. Only SoapElement attribute is supported.</value>
+ </data>
+ <data name="SFxInvalidXmlAttributeInBare" xml:space="preserve">
+ <value>XmlSerializer attribute {0} is not valid in {1}. Only XmlElement, XmlArray, XmlArrayItem and XmlAnyElement attributes are supported in MessageContract when IsWrapped is false.</value>
+ </data>
+ <data name="SFxInvalidXmlAttributeInWrapped" xml:space="preserve">
+ <value>XmlSerializer attribute {0} is not valid in {1}. Only XmlElement, XmlArray, XmlArrayItem, XmlAnyAttribute and XmlAnyElement attributes are supported when IsWrapped is true.</value>
+ </data>
+ <data name="SFxKnownTypeAttributeInvalid1" xml:space="preserve">
+ <value>{0} must contain either a single ServiceKnownTypeAttribute that refers to a method or a set of ServiceKnownTypeAttributes, each specifying a valid type</value>
+ </data>
+ <data name="SFxKnownTypeAttributeReturnType3" xml:space="preserve">
+ <value>The return type of method {1} in type {2} must be IEnumerable&lt;Type&gt; to be used by ServiceKnownTypeAttribute in {0}</value>
+ </data>
+ <data name="SFxKnownTypeAttributeUnknownMethod3" xml:space="preserve">
+ <value>ServiceKnownTypeAttribute in {0} refers to a method {1} that does not exist in type {2}</value>
+ </data>
+ <data name="SFxKnownTypeNull" xml:space="preserve">
+ <value>KnownType cannot be null in operation {0}</value>
+ </data>
+ <data name="SFxMessageContractBaseTypeNotValid" xml:space="preserve">
+ <value>The type {1} defines a MessageContract but also derives from a type {0} that does not define a MessageContract. All of the objects in the inheritance hierarchy of {1} must defines a MessageContract.</value>
+ </data>
+ <data name="SFxMessageContractRequiresDefaultConstructor" xml:space="preserve">
+ <value>The message cannot be deserialized into MessageContract type {0} since it does not have a default (parameterless) constructor.</value>
+ </data>
+ <data name="SFxMessageOperationFormatterCannotSerializeFault" xml:space="preserve">
+ <value>MessageOperationFormatter cannot serialize faults.</value>
+ </data>
+ <data name="SFxMetadataReferenceInvalidLocation" xml:space="preserve">
+ <value>The value '{0}' is not valid for the Location property. The Location property must be a valid absolute or relative URI.</value>
+ </data>
+ <data name="SFxMethodNotSupported1" xml:space="preserve">
+ <value>Method {0} is not supported on this proxy, this can happen if the method is not marked with OperationContractAttribute or if the interface type is not marked with ServiceContractAttribute.</value>
+ </data>
+ <data name="SFxMethodNotSupportedOnCallback1" xml:space="preserve">
+ <value>Callback method {0} is not supported, this can happen if the method is not marked with OperationContractAttribute or if its interface type is not the target of the ServiceContractAttribute's CallbackContract.</value>
+ </data>
+ <data name="SFxMethodNotSupportedByType2" xml:space="preserve">
+ <value>ServiceHost implementation type {0} does not implement ServiceContract {1}.</value>
+ </data>
+ <data name="SFxMismatchedOperationParent" xml:space="preserve">
+ <value>A DispatchOperation (or ClientOperation) can only be added to its parent DispatchRuntime (or ClientRuntime).</value>
+ </data>
+ <data name="SFxMissingActionHeader" xml:space="preserve">
+ <value>No Action header was found with namespace '{0}' for the given message.</value>
+ </data>
+ <data name="SFxMultipleCallbackFromSynchronizationContext" xml:space="preserve">
+ <value>Calling Post() on '{0}' resulted in multiple callbacks. This indicates a problem in '{0}'.</value>
+ </data>
+ <data name="SFxMultipleCallbackFromAsyncOperation" xml:space="preserve">
+ <value>The callback passed to operation '{0}' was called more than once. This indicates an internal error in the implementation of that operation.</value>
+ </data>
+ <data name="SFxMultipleUnknownHeaders" xml:space="preserve">
+ <value>Method {0} in type {1} has more than one header part of type array of XmlElement.</value>
+ </data>
+ <data name="SFxMultipleContractStarOperations0" xml:space="preserve">
+ <value>A ServiceContract has more the one operation with an Action of "*". A ServiceContract can have at most one operation an Action = "*".</value>
+ </data>
+ <data name="SFxMultipleContractsWithSameName" xml:space="preserve">
+ <value>The Service contains multiple ServiceEndpoints with different ContractDescriptions which each have Name='{0}' and Namespace='{1}'. Either provide ContractDescriptions with unique Name and Namespaces, or ensure the ServiceEndpoints have the same ContractDescription instance.</value>
+ </data>
+ <data name="SFxMultiplePartsNotAllowedInEncoded" xml:space="preserve">
+ <value>Part {1}:{0} is repeating and is not supported in Soap Encoding.</value>
+ </data>
+ <data name="SFxNameCannotBeEmpty" xml:space="preserve">
+ <value>The Name property must be a non-empty string.</value>
+ </data>
+ <data name="SFxConfigurationNameCannotBeEmpty" xml:space="preserve">
+ <value>The ConfigurationName property must be a non-empty string.</value>
+ </data>
+ <data name="SFxNeedProxyBehaviorOperationSelector2" xml:space="preserve">
+ <value>Cannot handle invocation of {0} on interface {1} because the OperationSelector on ClientRuntime is null.</value>
+ </data>
+ <data name="SFxNoDefaultConstructor" xml:space="preserve">
+ <value>The service type provided could not be loaded as a service because it does not have a default (parameter-less) constructor. To fix the problem, add a default constructor to the type, or pass an instance of the type to the host.</value>
+ </data>
+ <data name="SFxNoMostDerivedContract" xml:space="preserve">
+ <value>The contract specified by type '{0}' is ambiguous. The type derives from at least two different types that each define its own service contract. For this type to be used as a contract type, exactly one of its inherited contracts must be more derived than any of the others.</value>
+ </data>
+ <data name="SFxNullReplyFromExtension2" xml:space="preserve">
+ <value>Extension {0} prevented call to operation '{1}' from replying by setting the reply to null.</value>
+ </data>
+ <data name="SFxNullReplyFromFormatter2" xml:space="preserve">
+ <value>Formatter {0} returned a null reply message for call to operation '{1}'.</value>
+ </data>
+ <data name="SFxServiceChannelIdleAborted" xml:space="preserve">
+ <value>The operation '{0}' could not be completed because the sessionful channel timed out waiting to receive a message. To increase the timeout, either set the receiveTimeout property on the binding in your configuration file, or set the ReceiveTimeout property on the Binding directly.</value>
+ </data>
+ <data name="SFxServiceMetadataBehaviorUrlMustBeHttpOrRelative" xml:space="preserve">
+ <value>{0} must be a relative URI or an absolute URI with scheme '{1}'. '{2}' is an absolute URI with scheme '{3}'. </value>
+ </data>
+ <data name="SFxServiceMetadataBehaviorNoHttpBaseAddress" xml:space="preserve">
+ <value>The HttpGetEnabled property of ServiceMetadataBehavior is set to true and the HttpGetUrl property is a relative address, but there is no http base address. Either supply an http base address or set HttpGetUrl to an absolute address.</value>
+ </data>
+ <data name="SFxServiceMetadataBehaviorNoHttpsBaseAddress" xml:space="preserve">
+ <value>The HttpsGetEnabled property of ServiceMetadataBehavior is set to true and the HttpsGetUrl property is a relative address, but there is no https base address. Either supply an https base address or set HttpsGetUrl to an absolute address.</value>
+ </data>
+ <data name="SFxServiceMetadataBehaviorInstancingError" xml:space="preserve">
+ <value>The ChannelDispatcher with ListenUri '{0}' has endpoints with the following contracts: {1}. Metadata endpoints cannot share ListenUris. The conflicting endpoints were either specified in AddServiceEndpoint() calls, in a config file, or a combination of AddServiceEndpoint() and config.</value>
+ </data>
+ <data name="SFxServiceTypeNotCreatable" xml:space="preserve">
+ <value>Service implementation type is an interface or abstract class and no implementation object was provided.</value>
+ </data>
+ <data name="SFxSetEnableFaultsOnChannelDispatcher0" xml:space="preserve">
+ <value>This property sets EnableFaults on the client. To set EnableFaults on the server, use ChannelDispatcher's EnableFaults.</value>
+ </data>
+ <data name="SFxSetManualAddresssingOnChannelDispatcher0" xml:space="preserve">
+ <value>This property sets ManualAddressing on the client. To set ManualAddressing on the server, use ChannelDispatcher's ManualAddressing.</value>
+ </data>
+ <data name="SFxNoBatchingForSession" xml:space="preserve">
+ <value>TransactedBatchingBehavior validation failed. Service or client cannot be started. Transacted batching is not supported for session contracts. Remove transacted batching behavior from the endpoint or define a non-sessionful contract.</value>
+ </data>
+ <data name="SFxNoBatchingForReleaseOnComplete" xml:space="preserve">
+ <value>TransactedBatchingBehavior validation failed. Service cannot be started. Transacted batching requires ServiceBehavior.ReleaseServiceInstanceOnTransactionComplete to be false.</value>
+ </data>
+ <data name="SFxNoServiceObject" xml:space="preserve">
+ <value>The service implementation object was not initialized or is not available.</value>
+ </data>
+ <data name="SFxNone2004" xml:space="preserve">
+ <value>The WS-Addressing "none" value is not valid for the August 2004 version of WS-Addressing.</value>
+ </data>
+ <data name="SFxNonExceptionThrown" xml:space="preserve">
+ <value>An object that is not an exception was thrown.</value>
+ </data>
+ <data name="SFxNonInitiatingOperation1" xml:space="preserve">
+ <value>The operation '{0}' cannot be the first operation to be called because IsInitiating is false.</value>
+ </data>
+ <data name="SfxNoTypeSpecifiedForParameter" xml:space="preserve">
+ <value>There was no CLR type specified for parameter {0}, preventing the operation from being generated.</value>
+ </data>
+ <data name="SFxOneWayAndTransactionsIncompatible" xml:space="preserve">
+ <value>The one-way operation '{1}' on ServiceContract '{0}' is configured for transaction flow. Transactions cannot be flowed over one-way operations.</value>
+ </data>
+ <data name="SFxOneWayMessageToTwoWayMethod0" xml:space="preserve">
+ <value>The incoming message with action could not be processed because it is targeted at a request-reply operation, but cannot be replied to as the MessageId property is not set.</value>
+ </data>
+ <data name="SFxOperationBehaviorAttributeOnlyOnServiceClass" xml:space="preserve">
+ <value>OperationBehaviorAttribute can only go on the service class, it cannot be put on the ServiceContract interface. Method '{0}' on type '{1}' violates this.</value>
+ </data>
+ <data name="SFxOperationBehaviorAttributeReleaseInstanceModeDoesNotApplyToCallback" xml:space="preserve">
+ <value>The ReleaseInstanceMode property on OperationBehaviorAttribute can only be set on non-callback operations. Method '{0}' violates this.</value>
+ </data>
+ <data name="SFxOperationContractOnNonServiceContract" xml:space="preserve">
+ <value>Method '{0}' has OperationContractAttribute, but enclosing type '{1}' does not have ServiceContractAttribute. OperationContractAttribute can only be used on methods in ServiceContractAttribute types or on their CallbackContract types.</value>
+ </data>
+ <data name="SFxOperationContractProviderOnNonServiceContract" xml:space="preserve">
+ <value>Method '{1}' has {0}, but enclosing type '{2}' does not have ServiceContractAttribute. {0} can only be used on methods in ServiceContractAttribute types.</value>
+ </data>
+ <data name="SFxOperationDescriptionNameCannotBeEmpty" xml:space="preserve">
+ <value>OperationDescription's Name must be a non-empty string.</value>
+ </data>
+ <data name="SFxParameterNameCannotBeNull" xml:space="preserve">
+ <value>All parameter names used in operations that make up a service contract must not be null.</value>
+ </data>
+ <data name="SFxOperationMustHaveOneOrTwoMessages" xml:space="preserve">
+ <value>OperationDescription '{0}' is invalid because its Messages property contains an invalid number of MessageDescription instances. Each OperationDescription must have one or two messages.</value>
+ </data>
+ <data name="SFxParameterCountMismatch" xml:space="preserve">
+ <value>There was a mismatch between the number of supplied arguments and the number of expected arguments. Specifically, the argument '{0}' has '{1}' elements while the argument '{2}' has '{3}' elements.</value>
+ </data>
+ <data name="SFxParameterMustBeMessage" xml:space="preserve">
+ <value>The 'parameters' argument must be an array that contains a single Message object.</value>
+ </data>
+ <data name="SFxParametersMustBeEmpty" xml:space="preserve">
+ <value>The 'parameters' argument must be either null or an empty array.</value>
+ </data>
+ <data name="SFxParameterMustBeArrayOfOneElement" xml:space="preserve">
+ <value>The 'parameters' argument must be an array of one element.</value>
+ </data>
+ <data name="SFxPartNameMustBeUniqueInRpc" xml:space="preserve">
+ <value>Message part name {0} is not unique in an RPC Message.</value>
+ </data>
+ <data name="SFxReceiveContextSettingsPropertyMissing" xml:space="preserve">
+ <value>The contract '{0}' has at least one operation annotated with '{1}', but the binding used for the contract endpoint at address '{2}' does not support required binding property '{3}'. Please ensure that the binding used for the contract supports the ReceiveContext capability.</value>
+ </data>
+ <data name="SFxReceiveContextPropertyMissing" xml:space="preserve">
+ <value>Required message property '{0}' is missing from the IncomingProperties collections of the received message. Ensure that when the receive context is enabled on the binding, the created channel ensures that '{0}' is present on all received messages.</value>
+ </data>
+ <data name="SFxRequestHasInvalidReplyToOnClient" xml:space="preserve">
+ <value>The request message has ReplyTo='{0}' but IContextChannel.LocalAddress is '{1}'. When ManualAddressing is false, these values must be the same, null, or EndpointAddress.AnonymousAddress. Enable ManualAddressing or avoid setting ReplyTo on the message.</value>
+ </data>
+ <data name="SFxRequestHasInvalidFaultToOnClient" xml:space="preserve">
+ <value>The request message has FaultTo='{0}' but IContextChannel.LocalAddress is '{1}'. When ManualAddressing is false, these values must be the same, null, or EndpointAddress.AnonymousAddress. Enable ManualAddressing or avoid setting FaultTo on the message.</value>
+ </data>
+ <data name="SFxRequestHasInvalidFromOnClient" xml:space="preserve">
+ <value>The request message has From='{0}' but IContextChannel.LocalAddress is '{1}'. When ManualAddressing is false, these values must be the same, null, or EndpointAddress.AnonymousAddress. Enable ManualAddressing or avoid setting From on the message.</value>
+ </data>
+ <data name="SFxRequestHasInvalidReplyToOnServer" xml:space="preserve">
+ <value>The request message has ReplyTo='{0}' but IContextChannel.RemoteAddress is '{1}'. When ManualAddressing is false, these values must be the same, null, or EndpointAddress.AnonymousAddress because sending a reply to a different address than the original sender can create a security risk. If you want to process such messages, enable ManualAddressing.</value>
+ </data>
+ <data name="SFxRequestHasInvalidFaultToOnServer" xml:space="preserve">
+ <value>The request message has FaultTo='{0}' but IContextChannel.RemoteAddress is '{1}'. When ManualAddressing is false, these values must be the same, null, or EndpointAddress.AnonymousAddress because sending a reply to a different address than the original sender can create a security risk. If you want to process such messages, enable ManualAddressing.</value>
+ </data>
+ <data name="SFxRequestHasInvalidFromOnServer" xml:space="preserve">
+ <value>The request message has From='{0}' but IContextChannel.RemoteAddress is '{1}'. When ManualAddressing is false, these values must be the same, null, or EndpointAddress.AnonymousAddress because sending a reply to a different address than the original sender can create a security risk. If you want to process such messages, enable ManualAddressing.</value>
+ </data>
+ <data name="SFxRequestReplyNone" xml:space="preserve">
+ <value>A message was received with a WS-Addressing ReplyTo or FaultTo header targeted at the "None" address. These values are not valid for request-reply operations. Please consider using a one-way operation or enabling ManualAddressing if you need to support ReplyTo or FaultTo values of "None."</value>
+ </data>
+ <data name="SFxRequestTimedOut1" xml:space="preserve">
+ <value>This request operation did not receive a reply within the configured timeout ({0}). The time allotted to this operation may have been a portion of a longer timeout. This may be because the service is still processing the operation or because the service was unable to send a reply message. Please consider increasing the operation timeout (by casting the channel/proxy to IContextChannel and setting the OperationTimeout property) and ensure that the service is able to connect to the client.</value>
+ </data>
+ <data name="SFxRequestTimedOut2" xml:space="preserve">
+ <value>This request operation sent to {0} did not receive a reply within the configured timeout ({1}). The time allotted to this operation may have been a portion of a longer timeout. This may be because the service is still processing the operation or because the service was unable to send a reply message. Please consider increasing the operation timeout (by casting the channel/proxy to IContextChannel and setting the OperationTimeout property) and ensure that the service is able to connect to the client.</value>
+ </data>
+ <data name="SFxReplyActionMismatch3" xml:space="preserve">
+ <value>A reply message was received for operation '{0}' with action '{1}'. However, your client code requires action '{2}'.</value>
+ </data>
+ <data name="SFxRequiredRuntimePropertyMissing" xml:space="preserve">
+ <value>Required runtime property '{0}' is not initialized on DispatchRuntime. Do not remove ServiceBehaviorAttribute from ServiceDescription.Behaviors or ensure that you include a third-party service behavior that supplies this value.</value>
+ </data>
+ <data name="SFxResolvedMaxResolvedReferences" xml:space="preserve">
+ <value>The MetadataExchangeClient has resolved more than MaximumResolvedReferences.</value>
+ </data>
+ <data name="SFxResultMustBeMessage" xml:space="preserve">
+ <value>The 'result' argument must be of type Message.</value>
+ </data>
+ <data name="SFxRevertImpersonationFailed0" xml:space="preserve">
+ <value>Could not revert impersonation on current thread. Continuing would compromise system security. Terminating process.</value>
+ </data>
+ <data name="SFxRpcMessageBodyPartNameInvalid" xml:space="preserve">
+ <value>RPC Message {1} in operation {0} has an invalid body name {2}. It must be {3}</value>
+ </data>
+ <data name="SFxRpcMessageMustHaveASingleBody" xml:space="preserve">
+ <value>RPC Message {1} in operation {0} must have a single MessageBodyMember.</value>
+ </data>
+ <data name="SFxSchemaDoesNotContainElement" xml:space="preserve">
+ <value>There was a problem loading the XSD documents provided: a reference to a schema element with name '{0}' and namespace '{1}' could not be resolved because the element definition could not be found in the schema for targetNamespace '{1}'. Please check the XSD documents provided and try again.</value>
+ </data>
+ <data name="SFxSchemaDoesNotContainType" xml:space="preserve">
+ <value>There was a problem loading the XSD documents provided: a reference to a schema type with name '{0}' and namespace '{1}' could not be resolved because the type definition could not be found in the schema for targetNamespace '{1}'. Please check the XSD documents provided and try again.</value>
+ </data>
+ <data name="SFxWsdlMessageDoesNotContainPart3" xml:space="preserve">
+ <value>Service description message '{1}' from target namespace '{2}' does not contain part named '{0}'.</value>
+ </data>
+ <data name="SFxSchemaNotFound" xml:space="preserve">
+ <value>Schema with target namespace '{0}' could not be found.</value>
+ </data>
+ <data name="SFxSecurityContextPropertyMissingFromRequestMessage" xml:space="preserve">
+ <value>SecurityContextProperty is missing from the request Message, this may indicate security is configured incorrectly.</value>
+ </data>
+ <data name="SFxServerDidNotReply" xml:space="preserve">
+ <value>The server did not provide a meaningful reply; this might be caused by a contract mismatch, a premature session shutdown or an internal server error.</value>
+ </data>
+ <data name="SFxServiceHostBaseCannotAddEndpointAfterOpen" xml:space="preserve">
+ <value>Endpoints cannot be added after the ServiceHost has been opened/faulted/aborted/closed.</value>
+ </data>
+ <data name="SFxServiceHostBaseCannotAddEndpointWithoutDescription" xml:space="preserve">
+ <value>Endpoints cannot be added before the Description property has been initialized.</value>
+ </data>
+ <data name="SFxServiceHostBaseCannotApplyConfigurationWithoutDescription" xml:space="preserve">
+ <value>ApplyConfiguration requires that the Description property be initialized. Either provide a valid ServiceDescription in the CreateDescription method or override the ApplyConfiguration method to provide an alternative implementation.</value>
+ </data>
+ <data name="SFxServiceHostBaseCannotLoadConfigurationSectionWithoutDescription" xml:space="preserve">
+ <value>LoadConfigurationSection requires that the Description property be initialized. Provide a valid ServiceDescription in the CreateDescription method.</value>
+ </data>
+ <data name="SFxServiceHostBaseCannotInitializeRuntimeWithoutDescription" xml:space="preserve">
+ <value>InitializeRuntime requires that the Description property be initialized. Either provide a valid ServiceDescription in the CreateDescription method or override the InitializeRuntime method to provide an alternative implementation.</value>
+ </data>
+ <data name="SFxServiceHostCannotCreateDescriptionWithoutServiceType" xml:space="preserve">
+ <value>InitializeDescription must be called with a serviceType or singletonInstance parameter.</value>
+ </data>
+ <data name="SFxStaticMessageHeaderPropertiesNotAllowed" xml:space="preserve">
+ <value>Header properties cannot be set in MessageHeaderAttribute of {0} as its type is MessageHeader&lt;T&gt;.</value>
+ </data>
+ <data name="SFxStreamIOException" xml:space="preserve">
+ <value>An exception has been thrown when reading the stream.</value>
+ </data>
+ <data name="SFxStreamRequestMessageClosed" xml:space="preserve">
+ <value>The message containing this stream has been closed. Note that request streams cannot be accessed after the service operation returns.</value>
+ </data>
+ <data name="SFxStreamResponseMessageClosed" xml:space="preserve">
+ <value>The message containing this stream has been closed. </value>
+ </data>
+ <data name="SFxTerminatingOperationAlreadyCalled1" xml:space="preserve">
+ <value>This channel cannot send any more messages because IsTerminating operation '{0}' has already been called.</value>
+ </data>
+ <data name="SFxThrottleLimitMustBeGreaterThanZero0" xml:space="preserve">
+ <value>Throttle limit must be greater than zero. To disable, set to Int32.MaxValue.</value>
+ </data>
+ <data name="SFxTimeoutInvalidStringFormat" xml:space="preserve">
+ <value>The timeout value provided was not of a recognized format. Please see InnerException for more details.</value>
+ </data>
+ <data name="SFxTimeoutOutOfRange0" xml:space="preserve">
+ <value>Timeout must be greater than or equal to TimeSpan.Zero. To disable timeout, specify TimeSpan.MaxValue.</value>
+ </data>
+ <data name="SFxTimeoutOutOfRangeTooBig" xml:space="preserve">
+ <value>Timeouts larger than Int32.MaxValue TotalMilliseconds (approximately 24 days) cannot be honored. To disable timeout, specify TimeSpan.MaxValue.</value>
+ </data>
+ <data name="SFxTooManyPartsWithSameName" xml:space="preserve">
+ <value>Cannot create a unique part name for {0}.</value>
+ </data>
+ <data name="SFxTraceCodeElementIgnored" xml:space="preserve">
+ <value>An unrecognized element was encountered in the XML during deserialization which was ignored.</value>
+ </data>
+ <data name="SfxTransactedBindingNeeded" xml:space="preserve">
+ <value>TransactedBatchingBehavior validation failed. The service endpoint cannot be started. TransactedBatchingBehavior requires a binding that contains a binding element ITransactedBindingElement that returns true for ITransactedBindingElement.TransactedReceiveEnabled. If you are using NetMsmqBinding or MsmqIntegrationBinding make sure that ExactlyOnce is set to true.</value>
+ </data>
+ <data name="SFxTransactionNonConcurrentOrAutoComplete2" xml:space="preserve">
+ <value>TThe operation '{1}' on contract '{0}' is configured with TransactionAutoComplete set to false and with ConcurrencyMode not set to Single. TransactionAutoComplete set to false requires ConcurrencyMode.Single.</value>
+ </data>
+ <data name="SFxTransactionNonConcurrentOrReleaseServiceInstanceOnTxComplete" xml:space="preserve">
+ <value>The '{0}' service is configured with ReleaseServiceInstanceOnTransactionComplete set to true, but the ConcurrencyMode is not set to Single. The ReleaseServiceInstanceOnTransactionComplete requires the use of ConcurrencyMode.Single.</value>
+ </data>
+ <data name="SFxNonConcurrentOrEnsureOrderedDispatch" xml:space="preserve">
+ <value>The '{0}' service is configured with EnsureOrderedDispatch set to true, but the ConcurrencyMode is not set to Single. EnsureOrderedDispatch requires the use of ConcurrencyMode.Single.</value>
+ </data>
+ <data name="SfxDispatchRuntimeNonConcurrentOrEnsureOrderedDispatch" xml:space="preserve">
+ <value>The DispatchRuntime.EnsureOrderedDispatch property is set to true, but the DispatchRuntime.ConcurrencyMode is not set to Single. EnsureOrderedDispatch requires the use of ConcurrencyMode.Single.</value>
+ </data>
+ <data name="SFxTransactionsNotSupported" xml:space="preserve">
+ <value>The service does not support concurrent transactions.</value>
+ </data>
+ <data name="SFxTransactionAsyncAborted" xml:space="preserve">
+ <value>The transaction under which this method call was executing was asynchronously aborted.</value>
+ </data>
+ <data name="SFxTransactionInvalidSetTransactionComplete" xml:space="preserve">
+ <value>The SetTransactionComplete method was called in the operation '{0}' on contract '{1}' when TransactionAutoComplete was set to true. The SetTransactionComplete method can only be called when TransactionAutoComplete is set to false. This is an invalid scenario and the current transaction was aborted.</value>
+ </data>
+ <data name="SFxMultiSetTransactionComplete" xml:space="preserve">
+ <value>The SetTransactionComplete method was wrongly called more than once in the operation '{0}' on contract '{1}'. The SetTransactionComplete method can only be called once. This is an invalid scenario and the current transaction was aborted.</value>
+ </data>
+ <data name="SFxTransactionFlowAndMSMQ" xml:space="preserve">
+ <value>The binding for the endpoint at address '{0}' is configured with both the MsmqTransportBindingElement and the TransactionFlowBindingElement. These two elements cannot be used together.</value>
+ </data>
+ <data name="SFxTransactionAutoCompleteFalseAndInstanceContextMode" xml:space="preserve">
+ <value>The operation '{1}' on contract '{0}' is configured with TransactionAutoComplete set to false and the InstanceContextMode is not set to PerSession. TransactionAutoComplete set to false requires the use of InstanceContextMode.PerSession.</value>
+ </data>
+ <data name="SFxTransactionAutoCompleteFalseOnCallbackContract" xml:space="preserve">
+ <value>The operation '{0}' on callback contract '{1}' is configured with TransactionAutoComplete set to false. TransactionAutoComplete set to false cannot be used with operations on callback contracts.</value>
+ </data>
+ <data name="SFxTransactionAutoCompleteFalseAndSupportsSession" xml:space="preserve">
+ <value>The operation '{1}' on contract '{0}' is configured with TransactionAutoComplete set to false but SessionMode is not set to Required. TransactionAutoComplete set to false requires SessionMode.Required.</value>
+ </data>
+ <data name="SFxTransactionAutoCompleteOnSessionCloseNoSession" xml:space="preserve">
+ <value>The service '{0}' is configured with TransactionAutoCompleteOnSessionClose set to true and with an InstanceContextMode not set to PerSession. TransactionAutoCompleteOnSessionClose set to true requires an instancing mode that uses sessions.</value>
+ </data>
+ <data name="SFxTransactionTransactionTimeoutNeedsScope" xml:space="preserve">
+ <value>The service '{0}' is configured with a TransactionTimeout but no operations are configured with TransactionScopeRequired set to true. TransactionTimeout requires at least one operation with TransactionScopeRequired set to true.</value>
+ </data>
+ <data name="SFxTransactionIsolationLevelNeedsScope" xml:space="preserve">
+ <value>The service '{0}' is configured with a TransactionIsolationLevel but no operations are configured with TransactionScopeRequired set to true. TransactionIsolationLevel requires at least one operation with TransactionScopeRequired set to true.</value>
+ </data>
+ <data name="SFxTransactionReleaseServiceInstanceOnTransactionCompleteNeedsScope" xml:space="preserve">
+ <value>The service '{0}' is configured with ReleaseServiceInstanceOnTransactionComplete but no operations are configured with TransactionScopeRequired set to true. The ReleaseServiceInstanceOnTransactionComplete property requires at least one operation with TransactionScopeRequired set to true. Remove the ReleaseServiceInstanceOnTransactionComplete property from the service if this is the case.</value>
+ </data>
+ <data name="SFxTransactionTransactionAutoCompleteOnSessionCloseNeedsScope" xml:space="preserve">
+ <value>The service '{0}' is configured with TransactionAutoCompleteOnSessionClose, but no operations are configured with TransactionScopeRequired set to true. The TransactionAutoCompleteOnSessionClose property requires at least one operation with TransactionScopeRequired set to true. Remove the TransactionAutoCompleteOnSessionClose property from the service if this is the case.</value>
+ </data>
+ <data name="SFxTransactionFlowRequired" xml:space="preserve">
+ <value>The service operation requires a transaction to be flowed.</value>
+ </data>
+ <data name="SFxTransactionUnmarshalFailed" xml:space="preserve">
+ <value>The flowed transaction could not be unmarshaled. The following exception occurred: {0}</value>
+ </data>
+ <data name="SFxTransactionDeserializationFailed" xml:space="preserve">
+ <value>The incoming transaction cannot be deserialized. The transaction header in the message was either malformed or in an unrecognized format. The client and the service must be configured to use the same protocol and protocol version. The following exception occurred: {0}</value>
+ </data>
+ <data name="SFxTransactionHeaderNotUnderstood" xml:space="preserve">
+ <value>The transaction header '{0}' within the namespace '{1}' was not understood by the service. The client and the service must be configured to use the same protocol and protocol version ('{2}').</value>
+ </data>
+ <data name="SFxTryAddMultipleTransactionsOnMessage" xml:space="preserve">
+ <value>An attempt was made to add more than one transaction to a message. At most one transaction can be added.</value>
+ </data>
+ <data name="SFxTypedMessageCannotBeNull" xml:space="preserve">
+ <value>Internal Error: The instance of the MessageContract cannot be null in {0}.</value>
+ </data>
+ <data name="SFxTypedMessageCannotBeRpcLiteral" xml:space="preserve">
+ <value>The operation '{0}' could not be loaded because it specifies "rpc-style" in "literal" mode, but uses message contract types or the System.ServiceModel.Channels.Message. This combination is disallowed -- specify a different value for style or use parameters other than message contract types or System.ServiceModel.Channels.Message.</value>
+ </data>
+ <data name="SFxTypedOrUntypedMessageCannotBeMixedWithParameters" xml:space="preserve">
+ <value>The operation '{0}' could not be loaded because it has a parameter or return type of type System.ServiceModel.Channels.Message or a type that has MessageContractAttribute and other parameters of different types. When using System.ServiceModel.Channels.Message or types with MessageContractAttribute, the method must not use any other types of parameters.</value>
+ </data>
+ <data name="SFxTypedOrUntypedMessageCannotBeMixedWithVoidInRpc" xml:space="preserve">
+ <value>When using the rpc-encoded style, message contract types or the System.ServiceModel.Channels.Message type cannot be used if the operation has no parameters or has a void return value. Add a blank message contract type as a parameter or return type to operation '{0}'.</value>
+ </data>
+ <data name="SFxUnknownFaultNoMatchingTranslation1" xml:space="preserve">
+ <value>This fault did not provide a matching translation: {0}</value>
+ </data>
+ <data name="SFxUnknownFaultNullReason0" xml:space="preserve">
+ <value>This fault did not provide a reason (MessageFault.Reason was null).</value>
+ </data>
+ <data name="SFxUnknownFaultZeroReasons0" xml:space="preserve">
+ <value>This fault did not provide a reason (MessageFault.Reason.Translations.Count was 0).</value>
+ </data>
+ <data name="SFxUserCodeThrewException" xml:space="preserve">
+ <value>User operation '{0}.{1}' threw an exception that is unhandled in user code. This exception will be rethrown. If this is a recurring problem, it may indicate an error in the implementation of the '{0}.{1}' method.</value>
+ </data>
+ <data name="SfxUseTypedMessageForCustomAttributes" xml:space="preserve">
+ <value>Parameter '{0}' requires additional schema information that cannot be captured using the parameter mode. The specific attribute is '{1}'.</value>
+ </data>
+ <data name="SFxWellKnownNonSingleton0" xml:space="preserve">
+ <value>In order to use one of the ServiceHost constructors that takes a service instance, the InstanceContextMode of the service must be set to InstanceContextMode.Single. This can be configured via the ServiceBehaviorAttribute. Otherwise, please consider using the ServiceHost constructors that take a Type argument.</value>
+ </data>
+ <data name="SFxVersionMismatchInOperationContextAndMessage2" xml:space="preserve">
+ <value>Cannot add outgoing headers to message as MessageVersion in OperationContext.Current '{0}' does not match with the header version of message being processed '{1}'.</value>
+ </data>
+ <data name="SFxWhenMultipleEndpointsShareAListenUriTheyMustHaveSameIdentity" xml:space="preserve">
+ <value>When multiple endpoints on a service share the same ListenUri, those endpoints must all have the same Identity in their EndpointAddress. The endpoints at ListenUri '{0}' do not meet this criteria.</value>
+ </data>
+ <data name="SFxWrapperNameCannotBeEmpty" xml:space="preserve">
+ <value>Wrapper element name cannot be empty.</value>
+ </data>
+ <data name="SFxWrapperTypeHasMultipleNamespaces" xml:space="preserve">
+ <value>Wrapper type for message {0} cannot be projected as a data contract type since it has multiple namespaces. Consider using the XmlSerializer</value>
+ </data>
+ <data name="SFxWsdlPartMustHaveElementOrType" xml:space="preserve">
+ <value>WSDL part {0} in message {1} from namespace {2} must have either an element or a type name</value>
+ </data>
+ <data name="SFxDataContractSerializerDoesNotSupportBareArray" xml:space="preserve">
+ <value>DataContractSerializer does not support collection specified on element '{0}' </value>
+ </data>
+ <data name="SFxDataContractSerializerDoesNotSupportEncoded" xml:space="preserve">
+ <value>Invalid OperationFormatUse specified in the OperationFormatStyle of operation {0}, DataContractSerializer supports only Literal.</value>
+ </data>
+ <data name="SFxXmlArrayNotAllowedForMultiple" xml:space="preserve">
+ <value>XmlArrayAttribute cannot be used in repeating part {1}:{0}.</value>
+ </data>
+ <data name="SFxConfigContractNotFound" xml:space="preserve">
+ <value>Could not find default endpoint element that references contract '{0}' in the ServiceModel client configuration section. This might be because no configuration file was found for your application, or because no endpoint element matching this contract could be found in the client element.</value>
+ </data>
+ <data name="SFxConfigChannelConfigurationNotFound" xml:space="preserve">
+ <value>Could not find endpoint element with name '{0}' and contract '{1}' in the ServiceModel client configuration section. This might be because no configuration file was found for your application, or because no endpoint element matching this name could be found in the client element.</value>
+ </data>
+ <data name="SFxChannelFactoryEndpointAddressUri" xml:space="preserve">
+ <value>The Address property on ChannelFactory.Endpoint was null. The ChannelFactory's Endpoint must have a valid Address specified.</value>
+ </data>
+ <data name="SFxServiceContractGeneratorConfigRequired" xml:space="preserve">
+ <value>In order to generate configuration information using the GenerateServiceEndpoint method, the ServiceContractGenerator instance must have been initialized with a valid Configuration object.</value>
+ </data>
+ <data name="SFxCloseTimedOut1" xml:space="preserve">
+ <value>The ServiceHost close operation timed out after {0}. This could be because a client failed to close a sessionful channel within the required time. The time allotted to this operation may have been a portion of a longer timeout.</value>
+ </data>
+ <data name="SfxCloseTimedOutWaitingForDispatchToComplete" xml:space="preserve">
+ <value>Close process timed out waiting for service dispatch to complete.</value>
+ </data>
+ <data name="SFxInvalidWsdlBindingOpMismatch2" xml:space="preserve">
+ <value>The WSDL binding named {0} is not valid because no match for operation {1} was found in the corresponding portType definition.</value>
+ </data>
+ <data name="SFxInvalidWsdlBindingOpNoName" xml:space="preserve">
+ <value>The WSDL binding named {0} is not valid because an operation binding doesn't have a name specified.</value>
+ </data>
+ <data name="SFxChannelFactoryNoBindingFoundInConfig1" xml:space="preserve">
+ <value>The underlying channel factory could not be created because no binding information was found in the configuration file for endpoint with name '{0}'. Please check the endpoint configuration section with name '{0}' to ensure that binding information is present and correct.</value>
+ </data>
+ <data name="SFxChannelFactoryNoBindingFoundInConfigOrCode" xml:space="preserve">
+ <value>The underlying channel factory could not be created because no Binding was passed to the ChannelFactory. Please supply a valid Binding instance via the ChannelFactory constructor.</value>
+ </data>
+ <data name="SFxConfigLoaderMultipleEndpointMatchesSpecified2" xml:space="preserve">
+ <value>The endpoint configuration section for contract '{0}' with name '{1}' could not be loaded because more than one endpoint configuration with the same name and contract were found. Please check your config and try again.</value>
+ </data>
+ <data name="SFxConfigLoaderMultipleEndpointMatchesWildcard1" xml:space="preserve">
+ <value>An endpoint configuration section for contract '{0}' could not be loaded because more than one endpoint configuration for that contract was found. Please indicate the preferred endpoint configuration section by name.</value>
+ </data>
+ <data name="SFxProxyRuntimeMessageCannotBeNull" xml:space="preserve">
+ <value>In operation '{0}', cannot pass null to methods that take Message as input parameter.</value>
+ </data>
+ <data name="SFxDispatchRuntimeMessageCannotBeNull" xml:space="preserve">
+ <value>In operation '{0}', cannot return null from methods that return Message.</value>
+ </data>
+ <data name="SFxServiceHostNeedsClass" xml:space="preserve">
+ <value>ServiceHost only supports class service types.</value>
+ </data>
+ <data name="SfxReflectedContractKeyNotFound2" xml:space="preserve">
+ <value>The contract name '{0}' could not be found in the list of contracts implemented by the service '{1}'.</value>
+ </data>
+ <data name="SfxReflectedContractKeyNotFoundEmpty" xml:space="preserve">
+ <value>In order to add an endpoint to the service '{0}', a non-empty contract name must be specified.</value>
+ </data>
+ <data name="SfxReflectedContractKeyNotFoundIMetadataExchange" xml:space="preserve">
+ <value>The contract name 'IMetadataExchange' could not be found in the list of contracts implemented by the service {0}. Add a ServiceMetadataBehavior to the configuration file or to the ServiceHost directly to enable support for this contract.</value>
+ </data>
+ <data name="SfxServiceContractAttributeNotFound" xml:space="preserve">
+ <value>The contract type {0} is not attributed with ServiceContractAttribute. In order to define a valid contract, the specified type (either contract interface or service class) must be attributed with ServiceContractAttribute.</value>
+ </data>
+ <data name="SfxReflectedContractsNotInitialized1" xml:space="preserve">
+ <value>An endpoint for type '{0}' could not be added because the ServiceHost instance was not initialized properly. In order to add endpoints by Type, the CreateDescription method must be called. If you are using a class derived from ServiceHost, ensure that the class is properly calling base.CreateDescription.</value>
+ </data>
+ <data name="SFxMessagePartDescriptionMissingType" xml:space="preserve">
+ <value>Instance of MessagePartDescription Name='{0}' Namespace='{1}' cannot be used in this context: required 'Type' property was not set.</value>
+ </data>
+ <data name="SFxWsdlOperationInputNeedsMessageAttribute2" xml:space="preserve">
+ <value>The wsdl operation input {0} in portType {1} does not reference a message. This is either because the message attribute is missing or empty.</value>
+ </data>
+ <data name="SFxWsdlOperationOutputNeedsMessageAttribute2" xml:space="preserve">
+ <value>The wsdl operation output {0} in portType {1} does not reference a message. This is either because the message attribute is missing or empty.</value>
+ </data>
+ <data name="SFxWsdlOperationFaultNeedsMessageAttribute2" xml:space="preserve">
+ <value>The wsdl operation {0} in portType {1} contains a fault that does not reference a message. This is either because the message attribute is missing or empty.</value>
+ </data>
+ <data name="SFxMessageContractAttributeRequired" xml:space="preserve">
+ <value>Cannot create a typed message from type '{0}'. The functionality only valid for types decorated with MessageContractAttribute.</value>
+ </data>
+ <data name="AChannelServiceEndpointIsNull0" xml:space="preserve">
+ <value>A Channel/Service Endpoint is null.</value>
+ </data>
+ <data name="AChannelServiceEndpointSBindingIsNull0" xml:space="preserve">
+ <value>A Channel/Service endpoint's Binding is null.</value>
+ </data>
+ <data name="AChannelServiceEndpointSContractIsNull0" xml:space="preserve">
+ <value>A Channel/Service endpoint's Contract is null.</value>
+ </data>
+ <data name="AChannelServiceEndpointSContractSNameIsNull0" xml:space="preserve">
+ <value>A Channel/Service endpoint's Contract's name is null or empty.</value>
+ </data>
+ <data name="AChannelServiceEndpointSContractSNamespace0" xml:space="preserve">
+ <value>A Channel/Service endpoint's Contract's namespace is null.</value>
+ </data>
+ <data name="ServiceHasZeroAppEndpoints" xml:space="preserve">
+ <value>Service '{0}' has zero application (non-infrastructure) endpoints. This might be because no configuration file was found for your application, or because no service element matching the service name could be found in the configuration file, or because no endpoints were defined in the service element.</value>
+ </data>
+ <data name="BindingRequirementsAttributeRequiresQueuedDelivery1" xml:space="preserve">
+ <value>DeliveryRequirementsAttribute requires QueuedDelivery, but binding for the endpoint with contract '{0}' doesn't support it or isn't configured properly to support it.</value>
+ </data>
+ <data name="BindingRequirementsAttributeDisallowsQueuedDelivery1" xml:space="preserve">
+ <value>DeliveryRequirementsAttribute disallows QueuedDelivery, but binding for the endpoint with contract '{0}' supports it.</value>
+ </data>
+ <data name="SinceTheBindingForDoesnTSupportIBindingCapabilities1_1" xml:space="preserve">
+ <value>The DeliveryRequirementsAttribute on contract '{0}' specifies that the binding must support ordered delivery (RequireOrderedDelivery). This condition could not be verified because the configured binding does not implement IBindingDeliveryCapabilities. The DeliveryRequirementsAttribute may only be used with bindings that implement the IBindingDeliveryCapabilities interface.</value>
+ </data>
+ <data name="SinceTheBindingForDoesnTSupportIBindingCapabilities2_1" xml:space="preserve">
+ <value>The DeliveryRequirementsAttribute on contract '{0}' specifies a QueuedDeliveryRequirements constraint. This condition could not be verified because the configured binding does not implement IBindingDeliveryCapabilities. The DeliveryRequirementsAttribute may only be used with bindings that implement the IBindingDeliveryCapabilities interface.</value>
+ </data>
+ <data name="TheBindingForDoesnTSupportOrderedDelivery1" xml:space="preserve">
+ <value>The DeliveryRequirementsAttribute on contract '{0}' specifies a QueuedDeliveryRequirements value of NotAllowed. However, the configured binding for this contract specifies that it does support queued delivery. A queued binding may not be used with this contract.</value>
+ </data>
+ <data name="ChannelHasAtLeastOneOperationWithTransactionFlowEnabled" xml:space="preserve">
+ <value>At least one operation on the '{0}' contract is configured with the TransactionFlowAttribute attribute set to Mandatory but the channel's binding '{1}' is not configured with a TransactionFlowBindingElement. The TransactionFlowAttribute attribute set to Mandatory cannot be used without a TransactionFlowBindingElement.</value>
+ </data>
+ <data name="ServiceHasAtLeastOneOperationWithTransactionFlowEnabled" xml:space="preserve">
+ <value>At least one operation on the '{0}' contract is configured with the TransactionFlowAttribute attribute set to Mandatory but the channel's binding '{1}' is not configured with a TransactionFlowBindingElement. The TransactionFlowAttribute attribute set to Mandatory cannot be used without a TransactionFlowBindingElement.</value>
+ </data>
+ <data name="SFxNoEndpointMatchingContract" xml:space="preserve">
+ <value>The message with Action '{0}' cannot be processed at the receiver, due to a ContractFilter mismatch at the EndpointDispatcher. This may be because of either a contract mismatch (mismatched Actions between sender and receiver) or a binding/security mismatch between the sender and the receiver. Check that sender and receiver have the same contract and the same binding (including security requirements, e.g. Message, Transport, None).</value>
+ </data>
+ <data name="SFxNoEndpointMatchingAddress" xml:space="preserve">
+ <value>The message with To '{0}' cannot be processed at the receiver, due to an AddressFilter mismatch at the EndpointDispatcher. Check that the sender and receiver's EndpointAddresses agree.</value>
+ </data>
+ <data name="SFxNoEndpointMatchingAddressForConnectionOpeningMessage" xml:space="preserve">
+ <value>The message with Action '{0}' cannot be processed at the receiver because this Action is reserved for the connection opening messages only and cannot be sent from client to server. To invoke this operation on the server, call the '{1}' method on the client proxy instead.</value>
+ </data>
+ <data name="SFxServiceChannelCannotBeCalledBecauseIsSessionOpenNotificationEnabled" xml:space="preserve">
+ <value>The operation '{0}' could not be invoked because the property '{1}' on the OperationContract is set to '{2}'. To invoke this operation on the server, call the '{3}' method on the client proxy instead.</value>
+ </data>
+ <data name="EndMethodsCannotBeDecoratedWithOperationContractAttribute" xml:space="preserve">
+ <value>When using the IAsyncResult design pattern, the End method cannot be decorated with OperationContractAttribute. Only the corresponding Begin method can be decorated with OperationContractAttribute; that attribute will apply to the Begin-End pair of methods. Method '{0}' in type '{1}' violates this.</value>
+ </data>
+ <data name="WsatMessagingInitializationFailed" xml:space="preserve">
+ <value>The WS-AT messaging library failed to initialize.</value>
+ </data>
+ <data name="WsatProxyCreationFailed" xml:space="preserve">
+ <value>A client-side channel to the WS-AT protocol service could not be created.</value>
+ </data>
+ <data name="DispatchRuntimeRequiresFormatter0" xml:space="preserve">
+ <value>The DispatchOperation '{0}' requires Formatter, since DeserializeRequest and SerializeReply are not both false.</value>
+ </data>
+ <data name="ClientRuntimeRequiresFormatter0" xml:space="preserve">
+ <value>The ClientOperation '{0}' requires Formatter, since SerializeRequest and DeserializeReply are not both false.</value>
+ </data>
+ <data name="RuntimeRequiresInvoker0" xml:space="preserve">
+ <value>DispatchOperation requires Invoker.</value>
+ </data>
+ <data name="CouldnTCreateChannelForType2" xml:space="preserve">
+ <value>Channel requirements cannot be met by the ChannelFactory for Binding '{0}' since the contract requires support for one of these channel types '{1}' but the binding doesn't support any of them.</value>
+ </data>
+ <data name="CouldnTCreateChannelForChannelType2" xml:space="preserve">
+ <value>Channel type '{1}' was requested, but Binding '{0}' doesn't support it or isn't configured properly to support it.</value>
+ </data>
+ <data name="EndpointListenerRequirementsCannotBeMetBy3" xml:space="preserve">
+ <value>ChannelDispatcher requirements cannot be met by the IChannelListener for Binding '{0}' since the contract requires support for one of these channel types '{1}' but the binding only supports these channel types '{2}'.</value>
+ </data>
+ <data name="UnknownListenerType1" xml:space="preserve">
+ <value>The listener at Uri '{0}' could not be initialized because it was created for an unrecognized channel type.</value>
+ </data>
+ <data name="BindingDoesnTSupportSessionButContractRequires1" xml:space="preserve">
+ <value>Contract requires Session, but Binding '{0}' doesn't support it or isn't configured properly to support it.</value>
+ </data>
+ <data name="BindingDoesntSupportDatagramButContractRequires" xml:space="preserve">
+ <value>Contract does not allow Session, but Binding '{0}' does not support Datagram or is not configured properly to support it.</value>
+ </data>
+ <data name="BindingDoesnTSupportOneWayButContractRequires1" xml:space="preserve">
+ <value>Contract requires OneWay, but Binding '{0}' doesn't support it or isn't configured properly to support it.</value>
+ </data>
+ <data name="BindingDoesnTSupportTwoWayButContractRequires1" xml:space="preserve">
+ <value>Contract requires TwoWay (either request-reply or duplex), but Binding '{0}' doesn't support it or isn't configured properly to support it.</value>
+ </data>
+ <data name="BindingDoesnTSupportRequestReplyButContract1" xml:space="preserve">
+ <value>Contract requires Request/Reply, but Binding '{0}' doesn't support it or isn't configured properly to support it.</value>
+ </data>
+ <data name="BindingDoesnTSupportDuplexButContractRequires1" xml:space="preserve">
+ <value>Contract requires Duplex, but Binding '{0}' doesn't support it or isn't configured properly to support it.</value>
+ </data>
+ <data name="BindingDoesnTSupportAnyChannelTypes1" xml:space="preserve">
+ <value>Binding '{0}' doesn't support creating any channel types. This often indicates that the BindingElements in a CustomBinding have been stacked incorrectly or in the wrong order. A Transport is required at the bottom of the stack. The recommended order for BindingElements is: TransactionFlow, ReliableSession, Security, CompositeDuplex, OneWay, StreamSecurity, MessageEncoding, Transport. </value>
+ </data>
+ <data name="ContractIsNotSelfConsistentItHasOneOrMore2" xml:space="preserve">
+ <value>The contract '{0}' is not self-consistent -- it has one or more IsTerminating or non-IsInitiating operations, but it does not have the SessionMode property set to SessionMode.Required. The IsInitiating and IsTerminating attributes can only be used in the context of a session.</value>
+ </data>
+ <data name="ContractIsNotSelfConsistentWhenIsSessionOpenNotificationEnabled" xml:space="preserve">
+ <value>The operation contract '{0}' is not self-consistent. When the '{1}' is set to '{2}', both '{3}' and '{4}' properties must be true, and the operation must not have any input parameters.</value>
+ </data>
+ <data name="InstanceSettingsMustHaveTypeOrWellKnownObject0" xml:space="preserve">
+ <value>The ServiceHost must be configured with either a serviceType or a serviceInstance. Both of these values are currently null.</value>
+ </data>
+ <data name="TheServiceMetadataExtensionInstanceCouldNot2_0" xml:space="preserve">
+ <value>The ServiceMetadataExtension instance could not be added to the ServiceHost instance because it has already been added to another ServiceHost instance.</value>
+ </data>
+ <data name="TheServiceMetadataExtensionInstanceCouldNot3_0" xml:space="preserve">
+ <value>The ServiceMetadataExtension instance could not be removed from the ServiceHost instance because it has not been added to any ServiceHost instance.</value>
+ </data>
+ <data name="TheServiceMetadataExtensionInstanceCouldNot4_0" xml:space="preserve">
+ <value>The ServiceMetadataExtension instance could not be removed from the ServiceHost instance because it has already been added to a different ServiceHost instance.</value>
+ </data>
+ <data name="SynchronizedCollectionWrongType1" xml:space="preserve">
+ <value>A value of type '{0}' cannot be added to the generic collection, because the collection has been parameterized with a different type.</value>
+ </data>
+ <data name="SynchronizedCollectionWrongTypeNull" xml:space="preserve">
+ <value>A null value cannot be added to the generic collection, because the collection has been parameterized with a value type.</value>
+ </data>
+ <data name="CannotAddTwoItemsWithTheSameKeyToSynchronizedKeyedCollection0" xml:space="preserve">
+ <value>Cannot add two items with the same key to SynchronizedKeyedCollection.</value>
+ </data>
+ <data name="ItemDoesNotExistInSynchronizedKeyedCollection0" xml:space="preserve">
+ <value>Item does not exist in SynchronizedKeyedCollection.</value>
+ </data>
+ <data name="SuppliedMessageIsNotAReplyItHasNoRelatesTo0" xml:space="preserve">
+ <value>A reply message was received without a valid RelatesTo header. This may have been caused by a missing RelatesTo header or a RelatesTo header with an invalid WS-Addressing Relationship type.</value>
+ </data>
+ <data name="channelIsNotAvailable0" xml:space="preserve">
+ <value>Internal Error: The InnerChannel property is null.</value>
+ </data>
+ <data name="channelDoesNotHaveADuplexSession0" xml:space="preserve">
+ <value>The current channel does not support closing the output session as this channel does not implement ISessionChannel&lt;IDuplexSession&gt;.</value>
+ </data>
+ <data name="EndpointsMustHaveAValidBinding1" xml:space="preserve">
+ <value>The ServiceEndpoint with name '{0}' could not be exported to WSDL because the Binding property is null. To fix this, set the Binding property to a valid Binding instance.</value>
+ </data>
+ <data name="ABindingInstanceHasAlreadyBeenAssociatedTo1" xml:space="preserve">
+ <value>A binding instance has already been associated to listen URI '{0}'. If two endpoints want to share the same ListenUri, they must also share the same binding object instance. The two conflicting endpoints were either specified in AddServiceEndpoint() calls, in a config file, or a combination of AddServiceEndpoint() and config. </value>
+ </data>
+ <data name="UnabletoImportPolicy" xml:space="preserve">
+ <value>The following Policy Assertions were not Imported:
+</value>
+ </data>
+ <data name="UnImportedAssertionList" xml:space="preserve">
+ <value> XPath:{0}
+ Assertions:</value>
+ </data>
+ <data name="XPathUnavailable" xml:space="preserve">
+ <value>"XPath Unavailable"</value>
+ </data>
+ <data name="DuplicatePolicyInWsdlSkipped" xml:space="preserve">
+ <value>A policy expression was ignored because another policy expression with that ID has already been read in this document.
+XPath:{0}</value>
+ </data>
+ <data name="DuplicatePolicyDocumentSkipped" xml:space="preserve">
+ <value>A policy document was ignored because a policy expression with that ID has already been imported.
+Policy ID:{0}</value>
+ </data>
+ <data name="PolicyDocumentMustHaveIdentifier" xml:space="preserve">
+ <value>A metadata section containing policy did not have an identifier so it cannot be referenced. </value>
+ </data>
+ <data name="XPathPointer" xml:space="preserve">
+ <value>XPath:{0}</value>
+ </data>
+ <data name="UnableToFindPolicyWithId" xml:space="preserve">
+ <value>A policy reference was ignored because the policy with ID '{0}' could not be found.</value>
+ </data>
+ <data name="PolicyReferenceInvalidId" xml:space="preserve">
+ <value>A policy reference was ignored because the URI of the reference was empty.</value>
+ </data>
+ <data name="PolicyReferenceMissingURI" xml:space="preserve">
+ <value>A policy reference was ignored because the required {0} attribute was missing.</value>
+ </data>
+ <data name="ExceededMaxPolicyComplexity" xml:space="preserve">
+ <value>The policy expression was not fully imported because it exceeded the maximum allowable complexity. The import stopped at element '{0}' '{1}'.</value>
+ </data>
+ <data name="ExceededMaxPolicySize" xml:space="preserve">
+ <value>The policy expression was not fully imported because its normalized form was too large.</value>
+ </data>
+ <data name="UnrecognizedPolicyElementInNamespace" xml:space="preserve">
+ <value>Unrecognized policy element {0} in namespace {1}.</value>
+ </data>
+ <data name="UnsupportedPolicyDocumentRoot" xml:space="preserve">
+ <value>"{0}" is not a supported WS-Policy document root element.</value>
+ </data>
+ <data name="UnrecognizedPolicyDocumentNamespace" xml:space="preserve">
+ <value>The "{0}" namespace is not a recognized WS-Policy namespace.</value>
+ </data>
+ <data name="NoUsablePolicyAssertions" xml:space="preserve">
+ <value>Cannot find usable policy alternatives.</value>
+ </data>
+ <data name="PolicyInWsdlMustHaveFragmentId" xml:space="preserve">
+ <value>Unreachable policy detected.
+A WS-Policy element embedded in WSDL is missing a fragment identifier. This policy cannot be referenced by any WS-PolicyAttachment mechanisms.
+XPath:{0}</value>
+ </data>
+ <data name="FailedImportOfWsdl" xml:space="preserve">
+ <value>The processing of the WSDL parameter failed. Error: {0}</value>
+ </data>
+ <data name="OptionalWSDLExtensionIgnored" xml:space="preserve">
+ <value>The optional WSDL extension element '{0}' from namespace '{1}' was not handled.
+XPath: {2}</value>
+ </data>
+ <data name="RequiredWSDLExtensionIgnored" xml:space="preserve">
+ <value>The required WSDL extension element '{0}' from namespace '{1}' was not handled.</value>
+ </data>
+ <data name="UnknownWSDLExtensionIgnored" xml:space="preserve">
+ <value>An unrecognized WSDL extension of Type '{0}' was not handled.</value>
+ </data>
+ <data name="WsdlExporterIsFaulted" xml:space="preserve">
+ <value>A previous call to this WsdlExporter left it in a faulted state. It is no longer usable.</value>
+ </data>
+ <data name="WsdlImporterIsFaulted" xml:space="preserve">
+ <value>A previous call to this WsdlImporter left it in a faulted state. It is no longer usable.</value>
+ </data>
+ <data name="WsdlImporterContractMustBeInKnownContracts" xml:space="preserve">
+ <value>The ContractDescription argument to ImportEndpoints must be contained in the KnownContracts collection.</value>
+ </data>
+ <data name="WsdlItemAlreadyFaulted" xml:space="preserve">
+ <value>A previous attempt to import this {0} already failed.</value>
+ </data>
+ <data name="InvalidPolicyExtensionTypeInConfig" xml:space="preserve">
+ <value>The type {0} registered as a policy extension does not implement IPolicyImportExtension</value>
+ </data>
+ <data name="PolicyExtensionTypeRequiresDefaultConstructor" xml:space="preserve">
+ <value>The type {0} registered as a policy extension does not have a public default constructor. Policy extensions must have a public default constructor</value>
+ </data>
+ <data name="PolicyExtensionImportError" xml:space="preserve">
+ <value>An exception was thrown in a call to a policy import extension.
+Extension: {0}
+Error: {1}</value>
+ </data>
+ <data name="PolicyExtensionExportError" xml:space="preserve">
+ <value>An exception was thrown in a call to a policy export extension.
+Extension: {0}
+Error: {1}</value>
+ </data>
+ <data name="MultipleCallsToExportContractWithSameContract" xml:space="preserve">
+ <value>Calling IWsdlExportExtension.ExportContract twice with the same ContractDescription is not supported.</value>
+ </data>
+ <data name="DuplicateContractQNameNameOnExport" xml:space="preserve">
+ <value>Duplicate contract XmlQualifiedNames are not supported.
+Another ContractDescription with the Name: {0} and Namespace: {1} has already been exported.</value>
+ </data>
+ <data name="WarnDuplicateBindingQNameNameOnExport" xml:space="preserve">
+ <value>Similar ServiceEndpoints were exported. The WSDL export process was forced to suffix wsdl:binding names to avoid naming conflicts.
+ Similar ServiceEndpoints means different binding instances having the Name: {0} and Namespace: {1} and either the same ContractDescription or at least the same contract Name: {2}.</value>
+ </data>
+ <data name="WarnSkippingOpertationWithWildcardAction" xml:space="preserve">
+ <value>An operation was skipped during export because it has a wildcard action. This is not supported in WSDL.
+Contract Name:{0}
+Contract Namespace:{1}
+Operation Name:{2}</value>
+ </data>
+ <data name="WarnSkippingOpertationWithSessionOpenNotificationEnabled" xml:space="preserve">
+ <value>An operation was skipped during export because the property '{0}' is set to '{1}'. This operation should be used for server only and should not be exposed from WSDL.
+Contract Name:{2}
+Contract Namespace:{3}
+Operation Name:{4}</value>
+ </data>
+ <data name="InvalidWsdlExtensionTypeInConfig" xml:space="preserve">
+ <value>The type {0} registered as a WSDL extension does not implement IWsdlImportExtension.</value>
+ </data>
+ <data name="WsdlExtensionTypeRequiresDefaultConstructor" xml:space="preserve">
+ <value>The type {0} registered as a WSDL extension does not have a public default constructor. WSDL extensions must have a public default constructor.</value>
+ </data>
+ <data name="WsdlExtensionContractExportError" xml:space="preserve">
+ <value>An exception was thrown in a call to a WSDL export extension: {0}
+ contract: {1}</value>
+ </data>
+ <data name="WsdlExtensionEndpointExportError" xml:space="preserve">
+ <value>An exception was thrown in a call to a WSDL export extension: {0}
+ Endpoint: {1}</value>
+ </data>
+ <data name="WsdlExtensionBeforeImportError" xml:space="preserve">
+ <value>A WSDL import extension threw an exception during the BeforeImport call: {0}
+Error: {1}</value>
+ </data>
+ <data name="WsdlExtensionImportError" xml:space="preserve">
+ <value>An exception was thrown while running a WSDL import extension: {0}
+Error: {1}</value>
+ </data>
+ <data name="WsdlImportErrorMessageDetail" xml:space="preserve">
+ <value>Cannot import {0}
+Detail: {2}
+XPath to Error Source: {1}</value>
+ </data>
+ <data name="WsdlImportErrorDependencyDetail" xml:space="preserve">
+ <value>There was an error importing a {0} that the {1} is dependent on.
+XPath to {0}: {2}</value>
+ </data>
+ <data name="UnsupportedEnvelopeVersion" xml:space="preserve">
+ <value>The {0} binding element requires envelope version '{1}' It doesn't support '{2}'.</value>
+ </data>
+ <data name="NoValue0" xml:space="preserve">
+ <value>No value.</value>
+ </data>
+ <data name="UnsupportedBindingElementClone" xml:space="preserve">
+ <value>The '{0}' binding element does not support cloning.</value>
+ </data>
+ <data name="UnrecognizedBindingAssertions1" xml:space="preserve">
+ <value>WsdlImporter encountered unrecognized policy assertions in ServiceDescription '{0}':</value>
+ </data>
+ <data name="ServicesWithoutAServiceContractAttributeCan2" xml:space="preserve">
+ <value>The {0} declared on method '{1}' in type '{2}' is invalid. {0}s are only valid on methods that are declared in a type that has ServiceContractAttribute. Either add ServiceContractAttribute to type '{2}' or remove {0} from method '{1}'.</value>
+ </data>
+ <data name="tooManyAttributesOfTypeOn2" xml:space="preserve">
+ <value>Too many attributes of type {0} on {1}.</value>
+ </data>
+ <data name="couldnTFindRequiredAttributeOfTypeOn2" xml:space="preserve">
+ <value>Couldn't find required attribute of type {0} on {1}.</value>
+ </data>
+ <data name="AttemptedToGetContractTypeForButThatTypeIs1" xml:space="preserve">
+ <value>Attempted to get contract type for {0}, but that type is not a ServiceContract, nor does it inherit a ServiceContract.</value>
+ </data>
+ <data name="NoEndMethodFoundForAsyncBeginMethod3" xml:space="preserve">
+ <value>OperationContract method '{0}' in type '{1}' does not properly implement the async pattern, as no corresponding method '{2}' could be found. Either provide a method called '{2}' or set the AsyncPattern property on method '{0}' to false.</value>
+ </data>
+ <data name="MoreThanOneEndMethodFoundForAsyncBeginMethod3" xml:space="preserve">
+ <value>OperationContract method '{0}' in type '{1}' does not properly implement the async pattern, as more than one corresponding method '{2}' was found. When using the async pattern, exactly one end method must be provided. Either remove or rename one or more of the '{2}' methods such that there is just one, or set the AsyncPattern property on method '{0}' to false.</value>
+ </data>
+ <data name="InvalidAsyncEndMethodSignatureForMethod2" xml:space="preserve">
+ <value>Invalid async End method signature for method {0} in ServiceContract type {1}. Your end method must take an IAsyncResult as the last argument.</value>
+ </data>
+ <data name="InvalidAsyncBeginMethodSignatureForMethod2" xml:space="preserve">
+ <value>Invalid async Begin method signature for method {0} in ServiceContract type {1}. Your begin method must take an AsyncCallback and an object as the last two arguments and return an IAsyncResult.</value>
+ </data>
+ <data name="InAContractInheritanceHierarchyIfParentHasCallbackChildMustToo" xml:space="preserve">
+ <value>Because base ServiceContract '{0}' has a CallbackContract '{1}', derived ServiceContract '{2}' must also specify either '{1}' or a derived type as its CallbackContract.</value>
+ </data>
+ <data name="InAContractInheritanceHierarchyTheServiceContract3_2" xml:space="preserve">
+ <value>In a contract inheritance hierarchy, the ServiceContract's CallbackContract must be a subtype of the CallbackContracts of all of the CallbackContracts of the ServiceContracts inherited by the original ServiceContract, Types {0} and {1} violate this rule.</value>
+ </data>
+ <data name="CannotHaveTwoOperationsWithTheSameName3" xml:space="preserve">
+ <value>Cannot have two operations in the same contract with the same name, methods {0} and {1} in type {2} violate this rule. You can change the name of one of the operations by changing the method name or by using the Name property of OperationContractAttribute.</value>
+ </data>
+ <data name="CannotHaveTwoOperationsWithTheSameElement5" xml:space="preserve">
+ <value>The {0}.{1} operation references a message element [{2}] that has already been exported from the {3}.{4} operation. You can change the name of one of the operations by changing the method name or using the Name property of OperationContractAttribute. Alternatively, you can control the element name in greater detail using the MessageContract programming model.</value>
+ </data>
+ <data name="CannotInheritTwoOperationsWithTheSameName3" xml:space="preserve">
+ <value>Cannot inherit two different operations with the same name, operation '{0}' from contracts '{1}' and '{2}' violate this rule. You can change the name of one of the operations by changing the method name or by using the Name property of OperationContractAttribute.</value>
+ </data>
+ <data name="SyncAsyncMatchConsistency_Parameters5" xml:space="preserve">
+ <value>The synchronous OperationContract method '{0}' in type '{1}' was matched with the asynchronous OperationContract methods '{2}' and '{3}' because they have the same operation name '{4}'. When a synchronous OperationContract method is matched to a pair of asynchronous OperationContract methods, the two OperationContracts must define the same number and types of parameters. In this case, some of the arguments are different. To fix it, ensure that the OperationContracts define the same number and types of arguments, in the same order. Alternatively, changing the name of one of the methods will prevent matching. </value>
+ </data>
+ <data name="SyncTaskMatchConsistency_Parameters5" xml:space="preserve">
+ <value>The synchronous OperationContract method '{0}' in type '{1}' was matched with the task-based asynchronous OperationContract method '{2}' because they have the same operation name '{3}'. When a synchronous OperationContract method is matched to a task-based asynchronous OperationContract method, the two OperationContracts must define the same number and types of parameters. In this case, some of the arguments are different. To fix it, ensure that the OperationContracts define the same number and types of arguments, in the same order. Alternatively, changing the name of one of the methods will prevent matching. </value>
+ </data>
+ <data name="TaskAsyncMatchConsistency_Parameters5" xml:space="preserve">
+ <value>The task-based asynchronous OperationContract method '{0}' in type '{1}' was matched with the asynchronous OperationContract methods '{2}' and '{3}' because they have the same operation name '{4}'. When a task-based asynchronous OperationContract method is matched to a pair of asynchronous OperationContract methods, the two OperationContracts must define the same number and types of parameters. In this case, some of the arguments are different. To fix it, ensure that the OperationContracts define the same number and types of arguments, in the same order. Alternatively, changing the name of one of the methods will prevent matching.</value>
+ </data>
+ <data name="SyncAsyncMatchConsistency_ReturnType5" xml:space="preserve">
+ <value>The synchronous OperationContract method '{0}' in type '{1}' was matched with the asynchronous OperationContract methods '{2}' and '{3}' because they have the same operation name '{4}'. When a synchronous OperationContract method is matched to a pair of asynchronous OperationContract methods, the two OperationContracts must define the same return type. In this case, the return types are different. To fix it, ensure that method '{0}' and method '{3}' have the same return type. Alternatively, changing the name of one of the methods will prevent matching. </value>
+ </data>
+ <data name="SyncTaskMatchConsistency_ReturnType5" xml:space="preserve">
+ <value>The synchronous OperationContract method '{0}' in type '{1}' was matched with the task-based asynchronous OperationContract method '{2}' because they have the same operation name '{3}'. When a synchronous OperationContract method is matched to a task-based asynchronous OperationContract method, the two OperationContracts must define the same return type. In this case, the return types are different. To fix it, ensure that method '{0}' and method '{2}' have the same return type. Alternatively, changing the name of one of the methods will prevent matching. </value>
+ </data>
+ <data name="TaskAsyncMatchConsistency_ReturnType5" xml:space="preserve">
+ <value>The task-based asynchronous OperationContract method '{0}' in type '{1}' was matched with the asynchronous OperationContract methods '{2}' and '{3}' because they have the same operation name '{4}'. When a synchronous OperationContract method is matched to a pair of asynchronous OperationContract methods, the two OperationContracts must define the same return type. In this case, the return types are different. To fix it, ensure that method '{0}' and method '{3}' have the same return type. Alternatively, changing the name of one of the methods will prevent matching. </value>
+ </data>
+ <data name="SyncAsyncMatchConsistency_Attributes6" xml:space="preserve">
+ <value>The synchronous OperationContract method '{0}' in type '{1}' was matched with the asynchronous OperationContract methods '{2}' and '{3}' because they have the same operation name '{4}'. When a synchronous OperationContract method is matched to a pair of asynchronous OperationContract methods, any additional attributes must be declared on the synchronous OperationContract method. In this case, the asynchronous OperationContract method '{2}' has one or more attributes of type '{5}'. To fix it, remove the '{5}' attribute or attributes from method '{2}'. Alternatively, changing the name of one of the methods will prevent matching. </value>
+ </data>
+ <data name="SyncTaskMatchConsistency_Attributes6" xml:space="preserve">
+ <value>The synchronous OperationContract method '{0}' in type '{1}' was matched with the task-based asynchronous OperationContract method '{2}' because they have the same operation name '{3}'. When a synchronous OperationContract method is matched to a task-based asynchronous OperationContract method, any additional attributes must be declared on the synchronous OperationContract method. In this case, the task-based asynchronous OperationContract method '{2}' has one or more attributes of type '{4}'. To fix it, remove the '{4}' attribute or attributes from method '{2}'. Alternatively, changing the name of one of the methods will prevent matching. </value>
+ </data>
+ <data name="TaskAsyncMatchConsistency_Attributes6" xml:space="preserve">
+ <value>The task-based asynchronous OperationContract method '{0}' in type '{1}' was matched with the asynchronous OperationContract methods '{2}' and '{3}' because they have the same operation name '{4}'. When a task-based asynchronous OperationContract method is matched to a pair of asynchronous OperationContract methods, any additional attributes must be declared on the task-based asynchronous OperationContract method. In this case, the asynchronous OperationContract method '{2}' has one or more attributes of type '{5}'. To fix it, remove the '{5}' attribute or attributes from method '{2}'. Alternatively, changing the name of one of the methods will prevent matching. </value>
+ </data>
+ <data name="SyncAsyncMatchConsistency_Property6" xml:space="preserve">
+ <value>The synchronous OperationContract method '{0}' in type '{1}' was matched with the asynchronous OperationContract methods '{2}' and '{3}' because they have the same operation name '{4}'. When a synchronous OperationContract method is matched to a pair of asynchronous OperationContract methods, the two OperationContracts must have the same value for the '{5}' property. In this case, the values are different. To fix it, change the '{5} property of one of the OperationContracts to match the other. Alternatively, changing the name of one of the methods will prevent matching. </value>
+ </data>
+ <data name="SyncTaskMatchConsistency_Property6" xml:space="preserve">
+ <value>The synchronous OperationContract method '{0}' in type '{1}' was matched with the task-based asynchronous OperationContract method '{2}' because they have the same operation name '{3}'. When a synchronous OperationContract method is matched to a task-based asynchronous OperationContract method, the two OperationContracts must have the same value for the '{4}' property. In this case, the values are different. To fix it, change the '{4} property of one of the OperationContracts to match the other. Alternatively, changing the name of one of the methods will prevent matching. </value>
+ </data>
+ <data name="TaskAsyncMatchConsistency_Property6" xml:space="preserve">
+ <value>The task-based asynchronous OperationContract method '{0}' in type '{1}' was matched with the asynchronous OperationContract methods '{2}' and '{3}' because they have the same operation name '{4}'. When a task-based asynchronous OperationContract method is matched to a pair of asynchronous OperationContract methods, the two OperationContracts must have the same value for the '{5}' property. In this case, the values are different. To fix it, change the '{5} property of one of the OperationContracts to match the other. Alternatively, changing the name of one of the methods will prevent matching. </value>
+ </data>
+ <data name="ServiceOperationsMarkedWithIsOneWayTrueMust0" xml:space="preserve">
+ <value>Operations marked with IsOneWay=true must not declare output parameters, by-reference parameters or return values.</value>
+ </data>
+ <data name="OneWayOperationShouldNotSpecifyAReplyAction1" xml:space="preserve">
+ <value>One way operation {0} cannot not specify a reply action.</value>
+ </data>
+ <data name="OneWayAndFaultsIncompatible2" xml:space="preserve">
+ <value>The method '{1}' in type '{0}' is marked IsOneWay=true and declares one or more FaultContractAttributes. One-way methods cannot declare FaultContractAttributes. To fix it, change IsOneWay to false or remove the FaultContractAttributes.</value>
+ </data>
+ <data name="OnlyMalformedMessagesAreSupported" xml:space="preserve">
+ <value>Only malformed Messages are supported.</value>
+ </data>
+ <data name="UnableToLocateOperation2" xml:space="preserve">
+ <value>Cannot locate operation {0} in Contract {1}.</value>
+ </data>
+ <data name="UnsupportedWSDLOnlyOneMessage" xml:space="preserve">
+ <value>Unsupported WSDL, only one message part is supported for fault messages. This fault message references zero or more than one message part. If you have edit access to the WSDL file, you can fix the problem by removing the extra message parts such that fault message references just one part.</value>
+ </data>
+ <data name="UnsupportedWSDLTheFault" xml:space="preserve">
+ <value>Unsupported WSDL, the fault message part must reference an element. This fault message does not reference an element. If you have edit access to the WSDL document, you can fix the problem by referencing a schema element using the 'element' attribute.</value>
+ </data>
+ <data name="AsyncEndCalledOnWrongChannel" xml:space="preserve">
+ <value>Async End called on wrong channel.</value>
+ </data>
+ <data name="AsyncEndCalledWithAnIAsyncResult" xml:space="preserve">
+ <value>Async End called with an IAsyncResult from a different Begin method.</value>
+ </data>
+ <data name="IsolationLevelMismatch2" xml:space="preserve">
+ <value>The received transaction has an isolation level of '{0}' but the service is configured with a TransactionIsolationLevel of '{1}'. The isolation level for received transactions and the service must be the same.</value>
+ </data>
+ <data name="MessageHeaderIsNull0" xml:space="preserve">
+ <value>The value of the addressHeaders argument is invalid because the collection contains null values. Null is not a valid value for the AddressHeaderCollection.</value>
+ </data>
+ <data name="MessagePropertiesArraySize0" xml:space="preserve">
+ <value>The array passed does not have enough space to hold all the properties contained by this collection.</value>
+ </data>
+ <data name="DuplicateBehavior1" xml:space="preserve">
+ <value>The value could not be added to the collection, as the collection already contains an item of the same type: '{0}'. This collection only supports one instance of each type.</value>
+ </data>
+ <data name="CantCreateChannelWithManualAddressing" xml:space="preserve">
+ <value>Cannot create channel for a contract that requires request/reply and a binding that requires manual addressing but only supports duplex communication.</value>
+ </data>
+ <data name="XsdMissingRequiredAttribute1" xml:space="preserve">
+ <value>Missing required '{0}' attribute.</value>
+ </data>
+ <data name="IgnoreSoapHeaderBinding3" xml:space="preserve">
+ <value>Ignoring invalid SOAP header extension in wsdl:operation name='{0}' from targetNamespace='{1}'. Reason: {2}</value>
+ </data>
+ <data name="IgnoreSoapFaultBinding3" xml:space="preserve">
+ <value>Ignoring invalid SOAP fault extension in wsdl:operation name='{0}' from targetNamespace='{1}'. Reason: {2}</value>
+ </data>
+ <data name="IgnoreMessagePart3" xml:space="preserve">
+ <value>Ignoring invalid part in wsdl:message name='{0}' from targetNamespace='{1}'. Reason: {2}</value>
+ </data>
+ <data name="CannotImportPrivacyNoticeElementWithoutVersionAttribute" xml:space="preserve">
+ <value>PrivacyNotice element must have a Version attribute.</value>
+ </data>
+ <data name="PrivacyNoticeElementVersionAttributeInvalid" xml:space="preserve">
+ <value>PrivacyNotice element Version attribute must have an integer value.</value>
+ </data>
+ <data name="MsmqActiveDirectoryRequiresNativeTransfer" xml:space="preserve">
+ <value>Binding validation failed. The client cannot send messages. A conflict in the binding properties caused this failure. The UseActiveDirectory is set to true and QueueTransferProtocol is set to Native. To resolve the conflict, correct one of the properties.</value>
+ </data>
+ <data name="MsmqAdvancedPoisonHandlingRequired" xml:space="preserve">
+ <value>Binding validation failed because the binding's ReceiveErrorHandlig property is set to Move or Reject while the version of MSMQ installed on this system is not 4.0 or higher. The channel listener cannot be opened. Resolve the conflict by setting the ReceiveErrorHandling property to Drop or Fault, or by upgrading to MSMQ v4.0.</value>
+ </data>
+ <data name="MsmqAmbientTransactionInactive" xml:space="preserve">
+ <value>The Ambient transaction used to Complete the ReceiveContext Operation is not in an active state. </value>
+ </data>
+ <data name="MsmqAuthCertificateRequiresProtectionSign" xml:space="preserve">
+ <value>Binding validation failed because the binding's MsmqAuthenticationMode property is set to Certificate while the MsmqProtectionLevel property is not set to Sign or EncryptAndSign. The channel factory or service host cannot be opened. Resolve the conflict by correcting one of the properties.</value>
+ </data>
+ <data name="MsmqAuthNoneRequiresProtectionNone" xml:space="preserve">
+ <value>Binding validation failed. The service or the client cannot be started. A conflict in the binding properties caused this failure. The MsmqAuthenticationMode is set to None and MsmqProtectionLevel is not set to None. To resolve to conflict, correct one of the properties.</value>
+ </data>
+ <data name="MsmqAuthWindowsRequiresProtectionNotNone" xml:space="preserve">
+ <value>Binding validation failed because the binding's MsmqAuthenticationMode property is set to WindowsDomain while the MsmqProtectionLevel property is not set to Sign or EncryptAndSign. The channel factory or service host cannot be opened. Resolve the conflict by correcting one of the properties.</value>
+ </data>
+ <data name="MsmqBadCertificate" xml:space="preserve">
+ <value>Creation of a message security context failed because the attached sender certificate was invalid or cannot be validated. The message cannot be received. Ensure that a valid certificate is attached to the message and that the certificate is present in the receiver's certificate store.</value>
+ </data>
+ <data name="MsmqBadContentType" xml:space="preserve">
+ <value>The content type of an incoming message is unknown or not supported. The message cannot be received. Ensure that the sender was configured to use the same message encoder as the receiver.</value>
+ </data>
+ <data name="MsmqBadFrame" xml:space="preserve">
+ <value>An incoming MSMQ message contained invalid or unexpected .NET Message Framing information in its body. The message cannot be received. Ensure that the sender is using a compatible service contract with a matching SessionMode.</value>
+ </data>
+ <data name="MsmqBadXml" xml:space="preserve">
+ <value>An XML error was encountered while reading a WCF message. The message cannot be received. Ensure the message was sent by a WCF client which used an identical message encoder.</value>
+ </data>
+ <data name="MsmqBatchRequiresTransactionScope" xml:space="preserve">
+ <value>TransactedBatchingBehavior validation failed because none of the service operations had the TransactionScopeRequired property set to true on their OperationBehavior attribute. The service host cannot be started. Ensure this requirement is met if you wish to use this behavior.</value>
+ </data>
+ <data name="MsmqByteArrayBodyExpected" xml:space="preserve">
+ <value>A mismatch was detected between the serialization format specified in the MsmqIntegrationMessageProperty and the body of the MSMQ message. The message cannot be sent. The serialization format ByteArray requires the body of the MSMQ message to be of type byte[].</value>
+ </data>
+ <data name="MsmqCannotDeserializeActiveXMessage" xml:space="preserve">
+ <value>An error occurred while deserializing an MSMQ message's ActiveX body. The message cannot be received. The specified variant type for the body does not match the actual MSMQ message body.</value>
+ </data>
+ <data name="MsmqCannotDeserializeXmlMessage" xml:space="preserve">
+ <value>An error occurred while deserializing an MSMQ message's XML body. The message cannot be received. Ensure that the service contract is decorated with appropriate [ServiceKnownType] attributes or the TargetSerializationTypes property is set on the MsmqIntegrationBindingElement.</value>
+ </data>
+ <data name="MsmqCannotUseBodyTypeWithActiveXSerialization" xml:space="preserve">
+ <value>The properties of the message are mismatched. The message cannot be sent. The BodyType message property cannot be specified if the ActiveX serialization format is used.</value>
+ </data>
+ <data name="MsmqCertificateNotFound" xml:space="preserve">
+ <value>The sender's X.509 certificate was not found. The message cannot be sent. Ensure the certificate is available in the sender's certificate store.</value>
+ </data>
+ <data name="MsmqCustomRequiresPerAppDLQ" xml:space="preserve">
+ <value>Binding validation failed. The client cannot send the message. The DeadLetterQueue is set to Custom, but the CustomDeadLetterQueue is not specified. Specify the URI of the dead letter queue for each application in the CustomDeadLetterQueue property.</value>
+ </data>
+ <data name="MsmqDeserializationError" xml:space="preserve">
+ <value>An error was encountered while deserializing the message. The message cannot be received.</value>
+ </data>
+ <data name="MsmqDirectFormatNameRequiredForPoison" xml:space="preserve">
+ <value>Binding validation failed because the endpoint listen URI does not represent an MSMQ direct format name. The service host cannot be opened. Make sure you use a direct format name for the endpoint's listen URI.</value>
+ </data>
+ <data name="MsmqDLQNotLocal" xml:space="preserve">
+ <value>The host in the CustomDeadLetterQueue URI is not "localhost" or the local machine name. A custom DLQ must reside on the sender's machine.</value>
+ </data>
+ <data name="MsmqDLQNotWriteable" xml:space="preserve">
+ <value>Binding validation failed. The client cannot send a message. The specified dead letter queue does not exist or cannot be written. Ensure the queue exists with the proper authorization to write to it.</value>
+ </data>
+ <data name="MsmqEncryptRequiresUseAD" xml:space="preserve">
+ <value>Binding validation failed because the binding's MsmqProtectionLevel property is set to EncryptAndSign while the UseActiveDirectory is not set to true. The channel factory or the service host cannot be opened. Resolve the conflict by correcting one of the properties.</value>
+ </data>
+ <data name="MsmqExactlyOnceNeededForReceiveContext" xml:space="preserve">
+ <value>Binding validation failed. The service or the client cannot be started. The ExactlyOnce property is set to false and ReceiveContext is enabled. This is not supported. To resolve the conflict, either set ExactlyOnce to true or disable ReceiveContext.</value>
+ </data>
+ <data name="MsmqGetPrivateComputerInformationError" xml:space="preserve">
+ <value>The version check failed with the error: '{0}'. The version of MSMQ cannot be detected All operations that are on the queued channel will fail. Ensure that MSMQ is installed and is available.</value>
+ </data>
+ <data name="MsmqInvalidMessageId" xml:space="preserve">
+ <value>The message ID '{0}' is not in the right format.</value>
+ </data>
+ <data name="MsmqInvalidScheme" xml:space="preserve">
+ <value>The specified addressing scheme is invalid for this binding. The NetMsmqBinding scheme must be net.msmq. The MsmqIntegrationBinding scheme must be msmq.formatname.</value>
+ </data>
+ <data name="MsmqInvalidServiceOperationForMsmqIntegrationBinding" xml:space="preserve">
+ <value>The MsmqIntegrationBinding validation failed. The service cannot be started. The {0} binding does not support the method signature for the service operation {1} in the {2} contract. Correct the service operation to use the MsmqIntegrationBinding.</value>
+ </data>
+ <data name="MsmqInvalidTypeDeserialization" xml:space="preserve">
+ <value>The ActiveX serialization failed because the serialization format cannot be recognized. The message cannot be received.</value>
+ </data>
+ <data name="MsmqInvalidTypeSerialization" xml:space="preserve">
+ <value>The variant type is not recognized. The ActiveX serialization failed. The message cannot be sent. The specified variant type is not supported.</value>
+ </data>
+ <data name="MsmqKnownWin32Error" xml:space="preserve">
+ <value>{0} ({1}, 0x{2})</value>
+ </data>
+ <data name="MsmqMessageDoesntHaveIntegrationProperty" xml:space="preserve">
+ <value>The message cannot be sent because it's missing an MsmqIntegrationMessageProperty. All messages sent over MSMQ integration channels must carry the MsmqIntegrationMessageProperty.</value>
+ </data>
+ <data name="MsmqNoAssurancesForVolatile" xml:space="preserve">
+ <value>Binding validation failed. The service or the client cannot be started. The ExactlyOnce property is set to true and the Durable property is set to false. This is not supported. To resolve the conflict, correct one of these properties.</value>
+ </data>
+ <data name="MsmqNonNegativeArgumentExpected" xml:space="preserve">
+ <value>Argument must be a positive number or zero.</value>
+ </data>
+ <data name="MsmqNonTransactionalQueueNeeded" xml:space="preserve">
+ <value>A mismatch between the binding and MSMQ queue configuration was detected. The service cannot be started. The ExactlyOnce property is set to false and the queue to read messages from is a transactional queue, Correct the error by setting the ExactlyOnce property to true or create a non-transactional binding.</value>
+ </data>
+ <data name="MsmqNoMoveForSubqueues" xml:space="preserve">
+ <value>Binding validation failed because the URI represents a subqueue and the ReceiveErrorHandling parameter is set to Move. The service host or channel listener cannot be opened. Resolve this conflict by setting the ReceiveErrorHandling to Fault, Drop or Reject.</value>
+ </data>
+ <data name="MsmqNoSid" xml:space="preserve">
+ <value>Creation of a message security context failed because the sender's SID was not found in the message. The message cannot be received. The WindowsDomain MsmqAuthenticationMode requires the sender's SID.</value>
+ </data>
+ <data name="MsmqOpenError" xml:space="preserve">
+ <value>An error occurred while opening the queue:{0}. The message cannot be sent or received from the queue. Ensure that MSMQ is installed and running. Also ensure that the queue is available to open with the required access mode and authorization.</value>
+ </data>
+ <data name="MsmqPathLookupError" xml:space="preserve">
+ <value>An error occurred when converting the '{0}' queue path name to the format name: {1}. All operations on the queued channel failed. Ensure that the queue address is valid. MSMQ must be installed with Active Directory integration enabled and access to it is available.</value>
+ </data>
+ <data name="MsmqPerAppDLQRequiresCustom" xml:space="preserve">
+ <value>Binding validation failed. The client cannot send messages. The CustomDeadLetterQueue property is set, but the DeadLetterQueue property is not set to Custom. Set the DeadLetterQueue property to Custom.</value>
+ </data>
+ <data name="MsmqPerAppDLQRequiresExactlyOnce" xml:space="preserve">
+ <value>Binding validation failed. The client cannot send messages. A conflict in the binding properties is causing the failure. To use the custom dead letter queue, ExactlyOnce must be set to true to resolve to conflict.</value>
+ </data>
+ <data name="MsmqPerAppDLQRequiresMsmq4" xml:space="preserve">
+ <value>A mismatch between the binding and MSMQ configuration was detected. The client cannot send messages. To use the custom dead letter queue, you must have MSMQ version 4.0 or higher. If you do not have MSMQ version 4.0 or higher set the DeadLetterQueue property to System or None. </value>
+ </data>
+ <data name="MsmqPoisonMessage" xml:space="preserve">
+ <value>The transport channel detected a poison message. This occurred because the message exceeded the maximum number of delivery attempts or because the channel detected a fundamental problem with the message. The inner exception may contain additional information.</value>
+ </data>
+ <data name="MsmqQueueNotReadable" xml:space="preserve">
+ <value>There was an error opening the queue. Ensure that MSMQ is installed and running, the queue exists and has proper authorization to be read from. The inner exception may contain additional information.</value>
+ </data>
+ <data name="MsmqReceiveContextMessageNotReceived" xml:space="preserve">
+ <value>The ReceiveContext delete operation failed because the message with Id '{0}' could not be received from the lock subqueue. </value>
+ </data>
+ <data name="MsmqReceiveContextMessageNotMoved" xml:space="preserve">
+ <value>The ReceiveContext unlock operation failed because the message with Id '{0}' could not be moved from the lock subqueue to the main queue.</value>
+ </data>
+ <data name="MsmqReceiveContextSubqueuesNotSupported" xml:space="preserve">
+ <value>The queue could not be opened because the ReceiveContext feature is not supported on subqueues. Specify a different queue to receive from, or disable ReceiveContext.</value>
+ </data>
+ <data name="MsmqReceiveError" xml:space="preserve">
+ <value>An error occurred while receiving a message from the queue: {0}. Ensure that MSMQ is installed and running. Make sure the queue is available to receive from.</value>
+ </data>
+ <data name="MsmqSameTransactionExpected" xml:space="preserve">
+ <value>A transaction error occurred for this session. The session channel is faulted. Messages in the session cannot be sent or received. A queued session cannot be associated with more than one transaction. Ensure that all messages in the session are sent or received using a single transaction.</value>
+ </data>
+ <data name="MsmqSendError" xml:space="preserve">
+ <value>An error occurred while sending to the queue: {0}.Ensure that MSMQ is installed and running. If you are sending to a local queue, ensure the queue exists with the required access mode and authorization.</value>
+ </data>
+ <data name="MsmqSerializationTableFull" xml:space="preserve">
+ <value>A serialization error occurred. The message cannot be sent or received. The MSMQ integration channel is able to serialize no more than {0} types.</value>
+ </data>
+ <data name="MsmqSessionChannelAbort" xml:space="preserve">
+ <value>The transaction associated with this session channel has been rolled back because Abort was called on the session channel before the transaction committed. </value>
+ </data>
+ <data name="MsmqSessionChannelHasPendingItems" xml:space="preserve">
+ <value>Session channels must not have pending messages when the transactions associated with these channels are committed. Pending messages are either messages that have not been received from the session channel or messages that have been received but Complete has not been called for them. The channel has faulted and the transaction was rolled back.</value>
+ </data>
+ <data name="MsmqSessionChannelsMustBeClosed" xml:space="preserve">
+ <value>Session channels must be closed before the transaction is committed. The channel has faulted and the transaction was rolled back.</value>
+ </data>
+ <data name="MsmqSessionGramSizeMustBeInIntegerRange" xml:space="preserve">
+ <value>The total size of messages sent in this session exceeded the maximum value of Int32. The messages in this session cannot be sent.</value>
+ </data>
+ <data name="MsmqSessionMessagesNotConsumed" xml:space="preserve">
+ <value>An attempt made to close the session channel while there are still messages pending in the session. Current transaction will be rolled back and the session channel will be faulted. Messages in a session must be consumed all at once.</value>
+ </data>
+ <data name="MsmqSessionPrematureClose" xml:space="preserve">
+ <value>An attempt was made to close the session channel while there are still messages pending in the session. The sessiongram will be rolled back to the queue and the session channel will be faulted. </value>
+ </data>
+ <data name="MsmqStreamBodyExpected" xml:space="preserve">
+ <value>A serialization error occurred because of a mismatch between the value of the SerializationFormat property and the type of the body. The message cannot be sent. Ensure the type of the body is Stream or use a different SerializationFormat.</value>
+ </data>
+ <data name="MsmqTimeSpanTooLarge" xml:space="preserve">
+ <value>The message time to live (TTL) is too large. The message cannot be sent. The message TTL cannot exceed the Int32 maximum value.</value>
+ </data>
+ <data name="MsmqTokenProviderNeededForCertificates" xml:space="preserve">
+ <value>A client X.509 certificate was not specified through the channel factory's Credentials property, but one is required when the binding's MsmqAuthenticationMode property is set to Certificate. The message cannot be sent.</value>
+ </data>
+ <data name="MsmqTransactionNotActive" xml:space="preserve">
+ <value>The current transaction is not active. Messages in this session cannot be sent or received and the session channel will be faulted. All messages in a session must be sent or received using a single transaction.</value>
+ </data>
+ <data name="MsmqTransactionalQueueNeeded" xml:space="preserve">
+ <value>Binding validation failed because the binding's ExactlyOnce property is set to true while the destination queue is non-transactional. The service host cannot be opened. Resolve this conflict by setting the ExactlyOnce property to false or creating a transactional queue for this binding.</value>
+ </data>
+ <data name="MsmqTransactionCurrentRequired" xml:space="preserve">
+ <value>A transaction was not found in Transaction.Current but one is required for this operation. The channel cannot be opened. Ensure this operation is being called within a transaction scope.</value>
+ </data>
+ <data name="MsmqTransactionRequired" xml:space="preserve">
+ <value>A transaction is required but is not available. Messages cannot be sent or received. Ensure that the transaction scope is specified to send or receive messages.</value>
+ </data>
+ <data name="MsmqTransactedDLQExpected" xml:space="preserve">
+ <value>A mismatch occurred between the binding and the MSMQ configuration. Messages cannot be sent. The custom dead letter queue specified in the binding must be a transactional queue. Ensure that the custom dead letter queue address is correct and the queue is a transactional queue.</value>
+ </data>
+ <data name="MsmqUnexpectedPort" xml:space="preserve">
+ <value>The net.msmq scheme does not support port numbers. To correct this, remove the port number from the URI.</value>
+ </data>
+ <data name="MsmqUnknownWin32Error" xml:space="preserve">
+ <value>Unrecognized error {0} (0x{1})</value>
+ </data>
+ <data name="MsmqUnsupportedSerializationFormat" xml:space="preserve">
+ <value>The serialization failed because the serialization format '{0}' is not supported. The message cannot be sent or received.</value>
+ </data>
+ <data name="MsmqWindowsAuthnRequiresAD" xml:space="preserve">
+ <value>Binding validation failed because the binding's MsmqAuthenticationMode property is set to WindowsDomain but MSMQ is installed with Active Directory integration disabled. The channel factory or service host cannot be opened.</value>
+ </data>
+ <data name="MsmqWrongPrivateQueueSyntax" xml:space="preserve">
+ <value>The URL in invalid. The URL for the queue cannot contain the '$' character. Use the syntax in net.msmq://machine/private/queueName to address a private queue.</value>
+ </data>
+ <data name="MsmqWrongUri" xml:space="preserve">
+ <value>The URI is invalid because it is missing a host.</value>
+ </data>
+ <data name="MsmqCannotReacquireLock" xml:space="preserve">
+ <value>Failed to reacquire lock for message. </value>
+ </data>
+ <data name="XDCannotFindValueInDictionaryString" xml:space="preserve">
+ <value>Cannot find '{0}' value in dictionary string.</value>
+ </data>
+ <data name="WmiGetObject" xml:space="preserve">
+ <value>WMI GetObject Query: {0}</value>
+ </data>
+ <data name="WmiPutInstance" xml:space="preserve">
+ <value>WMI PutInstance Class: {0}</value>
+ </data>
+ <data name="ObjectMustBeOpenedToDequeue" xml:space="preserve">
+ <value>Cannot dequeue a '{0}' object while in the Created state.</value>
+ </data>
+ <data name="NoChannelBuilderAvailable" xml:space="preserve">
+ <value>The binding (Name={0}, Namespace={1}) cannot be used to create a ChannelFactory or a ChannelListener because it appears to be missing a TransportBindingElement. Every binding must have at least one binding element that derives from TransportBindingElement.</value>
+ </data>
+ <data name="InvalidBindingScheme" xml:space="preserve">
+ <value>The TransportBindingElement of type '{0}' in this CustomBinding returned a null or empty string for the Scheme. TransportBindingElement's Scheme must be a non-empty string.</value>
+ </data>
+ <data name="CustomBindingRequiresTransport" xml:space="preserve">
+ <value>Binding '{0}' lacks a TransportBindingElement. Every binding must have a binding element that derives from TransportBindingElement. This binding element must appear last in the BindingElementCollection.</value>
+ </data>
+ <data name="TransportBindingElementMustBeLast" xml:space="preserve">
+ <value>In Binding '{0}', TransportBindingElement '{1}' does not appear last in the BindingElementCollection. Please change the order of elements such that the TransportBindingElement is last.</value>
+ </data>
+ <data name="MessageVersionMissingFromBinding" xml:space="preserve">
+ <value>None of the binding elements in binding '{0}' define a message version. At least one binding element must define a message version and return it from the GetProperty&lt;MessageVersion&gt; method.</value>
+ </data>
+ <data name="NotAllBindingElementsBuilt" xml:space="preserve">
+ <value>Some of the binding elements in this binding were not used when building the ChannelFactory / ChannelListener. This may be have been caused by the binding elements being misordered. The recommended order for binding elements is: TransactionFlow, ReliableSession, Security, CompositeDuplex, OneWay, StreamSecurity, MessageEncoding, Transport. Note that the TransportBindingElement must be last. The following binding elements were not built: {0}.</value>
+ </data>
+ <data name="MultipleMebesInParameters" xml:space="preserve">
+ <value>More than one MessageEncodingBindingElement was found in the BindingParameters of the BindingContext. This usually is caused by having multiple MessageEncodingBindingElements in a CustomBinding. Remove all but one of these elements.</value>
+ </data>
+ <data name="MultipleStreamUpgradeProvidersInParameters" xml:space="preserve">
+ <value>More than one IStreamUpgradeProviderElement was found in the BindingParameters of the BindingContext. This usually is caused by having multiple IStreamUpgradeProviderElements in a CustomBinding. Remove all but one of these elements.</value>
+ </data>
+ <data name="MultiplePeerResolverBindingElementsinParameters" xml:space="preserve">
+ <value>More than one PeerResolverBindingElement was found in the BindingParameters of the BindingContext. This usually is caused by having multiple PeerResolverBindingElements in a CustomBinding. Remove all but one of these elements.</value>
+ </data>
+ <data name="MultiplePeerCustomResolverBindingElementsInParameters" xml:space="preserve">
+ <value>More than one PeerCustomResolverBindingElement was found in the BindingParameters of the BindingContext. This usually is caused by having multiple PeerCustomResolverBindingElement in a CustomBinding. Remove all but one of these elements.</value>
+ </data>
+ <data name="SecurityCapabilitiesMismatched" xml:space="preserve">
+ <value>The security capabilities of binding '{0}' do not match those of the generated runtime object. Most likely this means the binding contains a StreamSecurityBindingElement, but lacks a TransportBindingElement that supports Stream Security (such as TCP or Named Pipes). Either remove the unused StreamSecurityBindingElement or use a transport that supports this element.</value>
+ </data>
+ <data name="BaseAddressMustBeAbsolute" xml:space="preserve">
+ <value>Only an absolute Uri can be used as a base address.</value>
+ </data>
+ <data name="BaseAddressDuplicateScheme" xml:space="preserve">
+ <value>This collection already contains an address with scheme {0}. There can be at most one address per scheme in this collection. If your service is being hosted in IIS you can fix the problem by setting 'system.serviceModel/serviceHostingEnvironment/multipleSiteBindingsEnabled' to true or specifying 'system.serviceModel/serviceHostingEnvironment/baseAddressPrefixFilters'.</value>
+ </data>
+ <data name="BaseAddressCannotHaveUserInfo" xml:space="preserve">
+ <value>A base address cannot contain a Uri user info section.</value>
+ </data>
+ <data name="TransportBindingElementNotFound" xml:space="preserve">
+ <value>The binding does not contain a TransportBindingElement.</value>
+ </data>
+ <data name="ChannelDemuxerBindingElementNotFound" xml:space="preserve">
+ <value>The binding does not contain a ChannelDemuxerBindingElement.</value>
+ </data>
+ <data name="BaseAddressCannotHaveQuery" xml:space="preserve">
+ <value>A base address cannot contain a Uri query string.</value>
+ </data>
+ <data name="BaseAddressCannotHaveFragment" xml:space="preserve">
+ <value>A base address cannot contain a Uri fragment.</value>
+ </data>
+ <data name="UriMustBeAbsolute" xml:space="preserve">
+ <value>The given URI must be absolute.</value>
+ </data>
+ <data name="BindingProtocolMappingNotDefined" xml:space="preserve">
+ <value>The binding for scheme '{0}' specified in the protocol mapping does not exist and must be created.</value>
+ </data>
+ <data name="ConfigBindingCannotBeConfigured" xml:space="preserve">
+ <value>The binding on the service endpoint cannot be configured.</value>
+ </data>
+ <data name="ConfigBindingExtensionNotFound" xml:space="preserve">
+ <value>Configuration binding extension '{0}' could not be found. Verify that this binding extension is properly registered in system.serviceModel/extensions/bindingExtensions and that it is spelled correctly.</value>
+ </data>
+ <data name="ConfigBindingReferenceCycleDetected" xml:space="preserve">
+ <value>A binding reference cycle was detected in your configuration. The following reference cycle must be removed: {0}.</value>
+ </data>
+ <data name="ConfigBindingTypeCannotBeNullOrEmpty" xml:space="preserve">
+ <value>The binding specified cannot be null or an empty string. Please specify a valid binding. Valid binding values can be found in the system.serviceModel/extensions/bindingExtensions collection.</value>
+ </data>
+ <data name="ConfigCannotParseXPathFilter" xml:space="preserve">
+ <value>Cannot parse type '{0}' into a System.ServiceModel.Dispatcher.XPathMessageFilter.</value>
+ </data>
+ <data name="ConfigEndpointExtensionNotFound" xml:space="preserve">
+ <value>Configuration endpoint extension '{0}' could not be found. Verify that this endpoint extension is properly registered in system.serviceModel/extensions/endpointExtensions and that it is spelled correctly.</value>
+ </data>
+ <data name="ConfigEndpointReferenceCycleDetected" xml:space="preserve">
+ <value>An endpoint reference cycle was detected in your configuration. The following reference cycle must be removed: {0}.</value>
+ </data>
+ <data name="ConfigEndpointTypeCannotBeNullOrEmpty" xml:space="preserve">
+ <value>The endpoint specified cannot be null or an empty string. Please specify a valid endpoint. Valid endpoint values can be found in the system.serviceModel/extensions/endpointExtensions collection.</value>
+ </data>
+ <data name="ConfigXPathFilterMustNotBeEmpty" xml:space="preserve">
+ <value>Filter element body must not be empty.</value>
+ </data>
+ <data name="ConfigDuplicateItem" xml:space="preserve">
+ <value>An extension named {0} already appears in the {1}. Extension names must be unique.</value>
+ </data>
+ <data name="ConfigDuplicateExtensionName" xml:space="preserve">
+ <value>An extension of name '{0}' already appears in extension collection. Extension names must be unique.</value>
+ </data>
+ <data name="ConfigDuplicateExtensionType" xml:space="preserve">
+ <value>An extension of type '{0}' already appears in extension collection. Extension types must be unique.</value>
+ </data>
+ <data name="ConfigDuplicateKey" xml:space="preserve">
+ <value>A child element with the element name '{0}' already exists. Child elements can only be added once.</value>
+ </data>
+ <data name="ConfigDuplicateKeyAtSameScope" xml:space="preserve">
+ <value>A child element named '{0}' with same key already exists at the same configuration scope. Collection elements must be unique within the same configuration scope (e.g. the same application.config file). Duplicate key value: '{1}'.</value>
+ </data>
+ <data name="ConfigElementKeyNull" xml:space="preserve">
+ <value>The '{0}' configuration element key cannot be null.</value>
+ </data>
+ <data name="ConfigElementKeysNull" xml:space="preserve">
+ <value>At least one of the configuration element keys '{0}' must not be null.</value>
+ </data>
+ <data name="ConfigElementTypeNotAllowed" xml:space="preserve">
+ <value>Extension element '{0}' cannot be added to this element. Verify that the extension is registered in the extension collection at system.serviceModel/extensions/{1}.</value>
+ </data>
+ <data name="ConfigExtensionCollectionNotFound" xml:space="preserve">
+ <value>Extension collection '{0}' not found.</value>
+ </data>
+ <data name="ConfigExtensionTypeNotRegisteredInCollection" xml:space="preserve">
+ <value>The extension of type '{0}' is not registered in the extension collection '{1}'.</value>
+ </data>
+ <data name="ConfigInvalidServiceAuthenticationManagerType" xml:space="preserve">
+ <value>Invalid value for serviceAuthenticationManagerType. The serviceAuthenticationManagerType '{0}' does not derive from '{1}'. </value>
+ </data>
+ <data name="ConfigInvalidAuthorizationPolicyType" xml:space="preserve">
+ <value>Invalid value in policyType. The policyType '{0}' does not implement from '{1}'. </value>
+ </data>
+ <data name="ConfigInvalidBindingConfigurationName" xml:space="preserve">
+ <value>The {1} binding does not have a configured binding named '{0}'.</value>
+ </data>
+ <data name="ConfigInvalidBindingName" xml:space="preserve">
+ <value>The binding at {1} does not have a configured binding named '{0}'. This is an invalid value for {2}.</value>
+ </data>
+ <data name="ConfigInvalidCommonEndpointBehaviorType" xml:space="preserve">
+ <value>Cannot add the behavior extension '{0}' to the common endpoint behavior because it does not implement '{1}'.</value>
+ </data>
+ <data name="ConfigInvalidCommonServiceBehaviorType" xml:space="preserve">
+ <value>Cannot add the behavior extension '{0}' to the common service behavior because it does not implement '{1}'.</value>
+ </data>
+ <data name="ConfigInvalidCertificateValidatorType" xml:space="preserve">
+ <value>Invalid value for the certificate validator type. The type '{0}' does not derive from the appropriate base class '{1}'.</value>
+ </data>
+ <data name="ConfigInvalidClientCredentialsType" xml:space="preserve">
+ <value>Invalid value for the client credentials type. The type '{0}' does not derive from the appropriate base class '{1}'.</value>
+ </data>
+ <data name="ConfigInvalidClassFactoryValue" xml:space="preserve">
+ <value>The value '{0}' is not a valid instance of type '{1}'.</value>
+ </data>
+ <data name="ConfigInvalidClassInstanceValue" xml:space="preserve">
+ <value>The instance is not a valid configurable value of type '{0}'.</value>
+ </data>
+ <data name="ConfigInvalidEncodingValue" xml:space="preserve">
+ <value>{0} is not a valid encoding string for System.Text.Encoding.GetEncoding(string).</value>
+ </data>
+ <data name="ConfigInvalidEndpointBehavior" xml:space="preserve">
+ <value>There is no endpoint behavior named '{0}'.</value>
+ </data>
+ <data name="ConfigInvalidEndpointBehaviorType" xml:space="preserve">
+ <value>Cannot add the '{0}' behavior extension to '{1}' endpoint behavior because the underlying behavior type does not implement the IEndpointBehavior interface.</value>
+ </data>
+ <data name="ConfigInvalidEndpointName" xml:space="preserve">
+ <value>The endpoint at {1} does not have a configured endpoint named '{0}'. This is an invalid value for {2}.</value>
+ </data>
+ <data name="ConfigInvalidAttribute" xml:space="preserve">
+ <value>The attribute '{0}' cannot be specified on element '{1}' when attribute '{2}' is not specified.</value>
+ </data>
+ <data name="ConfigNoEndpointCreated" xml:space="preserve">
+ <value>The CreateServiceEndpoint method in type '{0}' returned null instead of an instance of type '{1}'.</value>
+ </data>
+ <data name="ConfigInvalidExtensionElement" xml:space="preserve">
+ <value>Invalid element in configuration. The extension '{0}' does not derive from correct extension base type '{1}'. </value>
+ </data>
+ <data name="ConfigInvalidExtensionElementName" xml:space="preserve">
+ <value>Invalid element in configuration. The extension name '{0}' is not registered in the collection at system.serviceModel/extensions/{1}. </value>
+ </data>
+ <data name="ConfigInvalidExtensionType" xml:space="preserve">
+ <value>The '{0}' type must derive from {1} to be used in the {2} collection.</value>
+ </data>
+ <data name="ConfigInvalidKeyType" xml:space="preserve">
+ <value>The element {0} requires a key of type '{1}'. Type of the key passed in: '{2}'.</value>
+ </data>
+ <data name="ConfigInvalidReliableMessagingVersionValue" xml:space="preserve">
+ <value>'{0}' is not a valid reliable messaging version. Valid values are 'WSReliableMessagingFebruary2005' and 'WSReliableMessaging11'.</value>
+ </data>
+ <data name="ConfigInvalidSamlSerializerType" xml:space="preserve">
+ <value>Invalid value for the saml serializer type. The type '{0}' does not derive from the appropriate base class: '{1}'.</value>
+ </data>
+ <data name="ConfigInvalidSection" xml:space="preserve">
+ <value>Invalid binding path. There is no binding registered with the configuration path '{0}'.</value>
+ </data>
+ <data name="ConfigInvalidServiceCredentialsType" xml:space="preserve">
+ <value>Invalid value for the service credentials type. The type '{0}' does not derive from the appropriate base class '{1}'.</value>
+ </data>
+ <data name="ConfigInvalidSecurityStateEncoderType" xml:space="preserve">
+ <value>Invalid value for the security state encoder type. The type '{0}' does not derive from the appropriate base class '{1}'.</value>
+ </data>
+ <data name="ConfigInvalidUserNamePasswordValidatorType" xml:space="preserve">
+ <value>Invalid value for the username password validator type. The type '{0}' does not derive from the appropriate base class '{1}'.</value>
+ </data>
+ <data name="ConfigInvalidServiceAuthorizationManagerType" xml:space="preserve">
+ <value>Invalid value for serviceAuthorizationManagerType. The serviceAuthorizationManagerType '{0}' does not derive from '{1}'. </value>
+ </data>
+ <data name="ConfigInvalidServiceBehavior" xml:space="preserve">
+ <value>There is no service behavior named '{0}'.</value>
+ </data>
+ <data name="ConfigInvalidServiceBehaviorType" xml:space="preserve">
+ <value>Cannot add the behavior extension '{0}' to the service behavior named '{1}' because the underlying behavior type does not implement the IServiceBehavior interface.</value>
+ </data>
+ <data name="ConfigInvalidStartValue" xml:space="preserve">
+ <value>Start must be between 0 and {0}. Value passed in is {1}.</value>
+ </data>
+ <data name="ConfigInvalidTransactionFlowProtocolValue" xml:space="preserve">
+ <value>'{0}' is not a valid transaction protocol. Valid values are 'OleTransactions', 'WSAtomicTransactionOctober2004', and 'WSAtomicTransaction11'.</value>
+ </data>
+ <data name="ConfigInvalidType" xml:space="preserve">
+ <value>The type '{0}' registered for extension '{1}' could not be loaded.</value>
+ </data>
+ <data name="ConfigInvalidTypeForBinding" xml:space="preserve">
+ <value>Invalid binding type for binding extension configuration object. This binding extension manages configuration of binding type '{0}' and cannot act upon type '{1}'.</value>
+ </data>
+ <data name="ConfigInvalidTypeForBindingElement" xml:space="preserve">
+ <value>Invalid binding element type for binding element extension configuration object. This binding element extension manages configuration of binding element type '{0}' and cannot act upon type '{1}'.</value>
+ </data>
+ <data name="ConfigInvalidTypeForEndpoint" xml:space="preserve">
+ <value>Invalid endpoint type for endpoint extension configuration object. This endpoint extension manages configuration of endpoint type '{0}' and cannot act upon type '{1}'.</value>
+ </data>
+ <data name="ConfigKeyNotFoundInElementCollection" xml:space="preserve">
+ <value>No elements matching the key '{0}' were found in the configuration element collection.</value>
+ </data>
+ <data name="ConfigKeysDoNotMatch" xml:space="preserve">
+ <value>The key does not match the indexer key. When setting the value of a specific index, the key of the desired value must match the index at which it is being set. Key on element (expected value): {0}. Key provided to indexer: {1}.</value>
+ </data>
+ <data name="ConfigMessageEncodingAlreadyInBinding" xml:space="preserve">
+ <value>Cannot add the message encoding element '{0}'. Another message encoding element already exists in the binding '{1}'. There can only be one message encoding element for each binding.</value>
+ </data>
+ <data name="ConfigNoExtensionCollectionAssociatedWithType" xml:space="preserve">
+ <value>Cannot find the extension collection associated with extension of type '{0}'.</value>
+ </data>
+ <data name="ConfigNullIssuerAddress" xml:space="preserve">
+ <value>Federated issuer address cannot be null when specifying an issuer binding.</value>
+ </data>
+ <data name="ConfigReadOnly" xml:space="preserve">
+ <value>The configuration is read only.</value>
+ </data>
+ <data name="ConfigSectionNotFound" xml:space="preserve">
+ <value>The '{0}' configuration section cannot be created. The machine.config file is missing information. Verify that this configuration section is properly registered and that you have correctly spelled the section name. For Windows Communication Foundation sections, run ServiceModelReg.exe -i to fix this error.</value>
+ </data>
+ <data name="ConfigStreamUpgradeElementAlreadyInBinding" xml:space="preserve">
+ <value>Cannot add stream upgrade element '{0}'. Another stream upgrade element already exists in the binding '{1}'. There can only be one stream update element per binding.</value>
+ </data>
+ <data name="ConfigTransportAlreadyInBinding" xml:space="preserve">
+ <value>Cannot add the transport element '{0}'. Another transport element already exists in the binding '{1}'. There can only be one transport element for each binding.</value>
+ </data>
+ <data name="ConfigXmlElementMustBeSet" xml:space="preserve">
+ <value>The XmlElement must contain XML content.</value>
+ </data>
+ <data name="ConfigXPathFilterIsNull" xml:space="preserve">
+ <value>The XPathFilter for an XPathFilterElement cannot be null.</value>
+ </data>
+ <data name="ConfigXPathNamespacePrefixNotFound" xml:space="preserve">
+ <value>Namespace prefix '{0}' referenced in XPath expression was not found.</value>
+ </data>
+ <data name="Default" xml:space="preserve">
+ <value>(Default)</value>
+ </data>
+ <data name="AdminMTAWorkerThreadException" xml:space="preserve">
+ <value>MTAWorkerThread exception</value>
+ </data>
+ <data name="InternalError" xml:space="preserve">
+ <value>An unexpected error has occurred.</value>
+ </data>
+ <data name="ClsidNotInApplication" xml:space="preserve">
+ <value>The CLSID specified in the service file is not configured in the specified application. (The CLSID is {0}, the AppID is {1}.)</value>
+ </data>
+ <data name="ClsidNotInConfiguration" xml:space="preserve">
+ <value>The CLSID specified in the service file does not have a service element in a configuration file. (The CLSID is {0}.)</value>
+ </data>
+ <data name="EndpointNotAnIID" xml:space="preserve">
+ <value>An endpoint configured for the COM+ CLSID {0} is not a configured interface on the class. (The contract type is {1}.)</value>
+ </data>
+ <data name="ServiceStringFormatError" xml:space="preserve">
+ <value>The COM+ string in the .svc file was formatted incorrectly. (The string is "{0}".)</value>
+ </data>
+ <data name="ContractTypeNotAnIID" xml:space="preserve">
+ <value>The contract type name in the configuration file was not in the form of an interface identifier. (The string is "{0}".)</value>
+ </data>
+ <data name="ApplicationNotFound" xml:space="preserve">
+ <value>The configured application was not found. (The Application ID was {0}.)</value>
+ </data>
+ <data name="NoVoteIssued" xml:space="preserve">
+ <value>A transaction vote request was completed, but there was no outstanding vote request.</value>
+ </data>
+ <data name="FailedToConvertTypelibraryToAssembly" xml:space="preserve">
+ <value>Failed to convert type library to assembly</value>
+ </data>
+ <data name="BadInterfaceVersion" xml:space="preserve">
+ <value>Incorrect Interface version in registry</value>
+ </data>
+ <data name="FailedToLoadTypeLibrary" xml:space="preserve">
+ <value>Failed to load type library</value>
+ </data>
+ <data name="NativeTypeLibraryNotAllowed" xml:space="preserve">
+ <value>An attempt to load the native type library '{0}' was made. Native type libraries cannot be loaded.</value>
+ </data>
+ <data name="InterfaceNotFoundInAssembly" xml:space="preserve">
+ <value>Could not find interface in the Assembly</value>
+ </data>
+ <data name="UdtNotFoundInAssembly" xml:space="preserve">
+ <value>The '{0}' user-defined type could not be found. Ensure that the correct type and type library are registered and specified.</value>
+ </data>
+ <data name="UnknownMonikerKeyword" xml:space="preserve">
+ <value>Could not find keyword {0}.</value>
+ </data>
+ <data name="MonikerIncorectSerializer" xml:space="preserve">
+ <value>Invalid serializer specified. The only valid values are 'xml' and 'datacontract'.</value>
+ </data>
+ <data name="NoEqualSignFound" xml:space="preserve">
+ <value>The keyword '{0}' has no equal sign following it. Ensure that each keyword is followed by an equal sign and a value. </value>
+ </data>
+ <data name="KewordMissingValue" xml:space="preserve">
+ <value>No value found for a keyword.</value>
+ </data>
+ <data name="BadlyTerminatedValue" xml:space="preserve">
+ <value>Badly terminated value {0}.</value>
+ </data>
+ <data name="MissingQuote" xml:space="preserve">
+ <value>Missing Quote in value {0}.</value>
+ </data>
+ <data name="RepeatedKeyword" xml:space="preserve">
+ <value>Repeated moniker keyword.</value>
+ </data>
+ <data name="InterfaceNotFoundInConfig" xml:space="preserve">
+ <value>Interface {0} not found in configuration.</value>
+ </data>
+ <data name="CannotHaveNullOrEmptyNameOrNamespaceForIID" xml:space="preserve">
+ <value>Interface {0} has a null namespace or name.</value>
+ </data>
+ <data name="MethodGivenInConfigNotFoundOnInterface" xml:space="preserve">
+ <value>Method {0} given in config was not found on interface {1}.</value>
+ </data>
+ <data name="MonikerIncorrectServerIdentityForMex" xml:space="preserve">
+ <value>Only one type of server identity can be specified.</value>
+ </data>
+ <data name="MonikerAddressNotSpecified" xml:space="preserve">
+ <value>Address not specified.</value>
+ </data>
+ <data name="MonikerMexBindingSectionNameNotSpecified" xml:space="preserve">
+ <value>Mex binding section name attribute not specified.</value>
+ </data>
+ <data name="MonikerMexAddressNotSpecified" xml:space="preserve">
+ <value>Mex address not specified.</value>
+ </data>
+ <data name="MonikerContractNotSpecified" xml:space="preserve">
+ <value>Contract not specified.</value>
+ </data>
+ <data name="MonikerBindingNotSpecified" xml:space="preserve">
+ <value>Binding not specified.</value>
+ </data>
+ <data name="MonikerBindingNamespacetNotSpecified" xml:space="preserve">
+ <value>Binding namespace not specified.</value>
+ </data>
+ <data name="MonikerFailedToDoMexRetrieve" xml:space="preserve">
+ <value>Failed to do mex retrieval:{0}.</value>
+ </data>
+ <data name="MonikerContractNotFoundInRetreivedMex" xml:space="preserve">
+ <value>None of the contract in metadata matched the contract specified.</value>
+ </data>
+ <data name="MonikerNoneOfTheBindingMatchedTheSpecifiedBinding" xml:space="preserve">
+ <value>The contract does not have an endpoint supporting the binding specified.</value>
+ </data>
+ <data name="MonikerMissingColon" xml:space="preserve">
+ <value>Moniker Missing Colon</value>
+ </data>
+ <data name="MonikerIncorrectServerIdentity" xml:space="preserve">
+ <value>Multiple server identity keywords were specified. Ensure that at most one identity keyword is specified.</value>
+ </data>
+ <data name="NoInterface" xml:space="preserve">
+ <value>The object does not support the interface '{0}'.</value>
+ </data>
+ <data name="DuplicateTokenExFailed" xml:space="preserve">
+ <value>Could not duplicate the token (error=0x{0:X}).</value>
+ </data>
+ <data name="AccessCheckFailed" xml:space="preserve">
+ <value>Could not perform an AccessCheck (error=0x{0:X}).</value>
+ </data>
+ <data name="ImpersonateAnonymousTokenFailed" xml:space="preserve">
+ <value>Could not impersonate the anonymous user (error=0x{0:X}).</value>
+ </data>
+ <data name="OnlyByRefVariantSafeArraysAllowed" xml:space="preserve">
+ <value>The provided SafeArray parameter was passed by value. SafeArray parameters must be passed by reference.</value>
+ </data>
+ <data name="OnlyOneDimensionalSafeArraysAllowed" xml:space="preserve">
+ <value>Multi-dimensional SafeArray parameters cannot be used.</value>
+ </data>
+ <data name="OnlyVariantTypeElementsAllowed" xml:space="preserve">
+ <value>The elements of the SafeArray must be of the type VARIANT.</value>
+ </data>
+ <data name="OnlyZeroLBoundAllowed" xml:space="preserve">
+ <value>The lower bound of the SafeArray was not zero. SafeArrays with a lower bound other than zero cannot be used.</value>
+ </data>
+ <data name="OpenThreadTokenFailed" xml:space="preserve">
+ <value>Could not open the thread token (error=0x{0:X}).</value>
+ </data>
+ <data name="OpenProcessTokenFailed" xml:space="preserve">
+ <value>Could not open the process token (error=0x{0:X}).</value>
+ </data>
+ <data name="InvalidIsolationLevelValue" xml:space="preserve">
+ <value>The isolation level for component {0} is invalid. (The value was {1}.)</value>
+ </data>
+ <data name="UnsupportedConversion" xml:space="preserve">
+ <value>The conversion between the client parameter type '{0}' to the required server parameter type '{1}' cannot be performed.</value>
+ </data>
+ <data name="FailedProxyProviderCreation" xml:space="preserve">
+ <value>The required outer proxy could not be created. Ensure that the service moniker is correctly installed and registered.</value>
+ </data>
+ <data name="UnableToLoadDll" xml:space="preserve">
+ <value>Cannot load library {0}. Ensure that WCF is properly installed.</value>
+ </data>
+ <data name="InterfaceNotRegistered" xml:space="preserve">
+ <value>Interface Not Registered</value>
+ </data>
+ <data name="BadInterfaceRegistration" xml:space="preserve">
+ <value>Bad Interface Registration</value>
+ </data>
+ <data name="NotAComObject" xml:space="preserve">
+ <value>The argument passed to SetObject is not a COM object.</value>
+ </data>
+ <data name="NoTypeLibraryFoundForInterface" xml:space="preserve">
+ <value>No type library available for interface</value>
+ </data>
+ <data name="CannotFindClsidInApplication" xml:space="preserve">
+ <value>Cannot find CLSID {0} in COM+ application {1}.</value>
+ </data>
+ <data name="ComActivationAccessDenied" xml:space="preserve">
+ <value>Cannot create an instance of the specified service: access is denied.</value>
+ </data>
+ <data name="ComActivationFailure" xml:space="preserve">
+ <value>An internal error occurred attempting to create an instance of the specified service.</value>
+ </data>
+ <data name="ComDllHostInitializerFoundNoServices" xml:space="preserve">
+ <value>No services are configured for the application.</value>
+ </data>
+ <data name="ComRequiresWindowsSecurity" xml:space="preserve">
+ <value>Access is denied. The message was not authenticated with a valid windows identity.</value>
+ </data>
+ <data name="ComInconsistentSessionRequirements" xml:space="preserve">
+ <value>The session requirements of the contracts are inconsistent. All COM contracts in a service must have the same session requirement.</value>
+ </data>
+ <data name="ComMessageAccessDenied" xml:space="preserve">
+ <value>Access is denied.</value>
+ </data>
+ <data name="VariantArrayNull" xml:space="preserve">
+ <value>Parameter at index {0} is null.</value>
+ </data>
+ <data name="UnableToRetrievepUnk" xml:space="preserve">
+ <value>Unable to retrieve IUnknown for object.</value>
+ </data>
+ <data name="PersistWrapperIsNull" xml:space="preserve">
+ <value>QueryInterface succeeded but the persistable type wrapper was null.</value>
+ </data>
+ <data name="UnexpectedThreadingModel" xml:space="preserve">
+ <value>Unexpected threading model. WCF/COM+ integration only supports STA and MTA threading models.</value>
+ </data>
+ <data name="NoneOfTheMethodsForInterfaceFoundInConfig" xml:space="preserve">
+ <value>None of the methods were found for interface {0}.</value>
+ </data>
+ <data name="ComOperationNotFound" xml:space="preserve">
+ <value>The {0} operation on the service {1} could not be found in the catalog.</value>
+ </data>
+ <data name="InvalidWebServiceInterface" xml:space="preserve">
+ <value>The interface with IID {0} cannot be exposed as a web service</value>
+ </data>
+ <data name="InvalidWebServiceParameter" xml:space="preserve">
+ <value>The parameter named {0} of type {1} on method {2} of interface {3} cannot be serialized.</value>
+ </data>
+ <data name="InvalidWebServiceReturnValue" xml:space="preserve">
+ <value>The return value of type {0} on method {1} of interface {2} cannot be serialized.</value>
+ </data>
+ <data name="OnlyClsidsAllowedForServiceType" xml:space="preserve">
+ <value>The COM+ Integration service '{0}' specified in configuration is not in a supported format and could not be started. Ensure that the configuration is correctly specified.</value>
+ </data>
+ <data name="OperationNotFound" xml:space="preserve">
+ <value>The method '{0}' could not be found. Ensure that the correct method name is specified.</value>
+ </data>
+ <data name="BadDispID" xml:space="preserve">
+ <value>The Dispatch ID '{0}' could not be found or is invalid.</value>
+ </data>
+ <data name="ComNoAsyncOperationsAllowed" xml:space="preserve">
+ <value>At least one operation is asynchronous. Asynchronous operations are not allowed.</value>
+ </data>
+ <data name="ComDuplicateOperation" xml:space="preserve">
+ <value>There are duplicate operations, which is invalid. Remove the duplicates.</value>
+ </data>
+ <data name="BadParamCount" xml:space="preserve">
+ <value>The number of parameters in the request did not match the number supported by the method. Ensure that the correct number of parameters are specified.</value>
+ </data>
+ <data name="BindingNotFoundInConfig" xml:space="preserve">
+ <value>Binding type {0} instance {1} not found in config.</value>
+ </data>
+ <data name="AddressNotSpecified" xml:space="preserve">
+ <value>The required address keyword was not specified.</value>
+ </data>
+ <data name="BindingNotSpecified" xml:space="preserve">
+ <value>The required binding keyword was not specified or is not valid.</value>
+ </data>
+ <data name="OnlyVariantAllowedByRef" xml:space="preserve">
+ <value>A VARIANT parameter was passed by value. VARIANT parameters must be passed by reference.</value>
+ </data>
+ <data name="CannotResolveTypeForParamInMessageDescription" xml:space="preserve">
+ <value>The type for the '{0}' parameter in '{1}' within the namespace '{2}' cannot not be resolved.</value>
+ </data>
+ <data name="TooLate" xml:space="preserve">
+ <value>The operation cannot be performed after the communications channel has been created.</value>
+ </data>
+ <data name="RequireConfiguredMethods" xml:space="preserve">
+ <value>The interface with IID {0} has no methods configured in the COM+ catalog and cannot be exposed as a web service.</value>
+ </data>
+ <data name="RequireConfiguredInterfaces" xml:space="preserve">
+ <value>The interface with IID {0} is not configured in the COM+ catalog and cannot be exposed as a web service.</value>
+ </data>
+ <data name="CannotCreateChannelOption" xml:space="preserve">
+ <value>The channeloption intrinsic object cannot be created because the channel builder is not initialized.</value>
+ </data>
+ <data name="NoTransactionInContext" xml:space="preserve">
+ <value>There is no transaction in the context of the operation.</value>
+ </data>
+ <data name="IssuedTokenFlowNotAllowed" xml:space="preserve">
+ <value>The service does not accept issued tokens.</value>
+ </data>
+ <data name="GeneralSchemaValidationError" xml:space="preserve">
+ <value>There was an error verifying some XML Schemas generated during export:
+{0}</value>
+ </data>
+ <data name="SchemaValidationError" xml:space="preserve">
+ <value>There was a validation error on a schema generated during export:
+ Source: {0}
+ Line: {1} Column: {2}
+ Validation Error: {3}</value>
+ </data>
+ <data name="ContractBindingAddressCannotBeNull" xml:space="preserve">
+ <value>The Address, Binding and Contract keywords are required.</value>
+ </data>
+ <data name="TypeLoadForContractTypeIIDFailedWith" xml:space="preserve">
+ <value>Type load for contract interface ID {0} failed with Error:{1}.</value>
+ </data>
+ <data name="BindingLoadFromConfigFailedWith" xml:space="preserve">
+ <value>Fail to load binding {0} from config. Error:{1}.</value>
+ </data>
+ <data name="PooledApplicationNotSupportedForComplusHostedScenarios" xml:space="preserve">
+ <value>Application {0} is marked Pooled. Pooled applications are not supported under COM+ hosting.</value>
+ </data>
+ <data name="RecycledApplicationNotSupportedForComplusHostedScenarios" xml:space="preserve">
+ <value>Application {0} has recycling enabled. Recycling of applications is not supported under COM+ hosting.</value>
+ </data>
+ <data name="BadImpersonationLevelForOutOfProcWas" xml:space="preserve">
+ <value>The client token at least needs to have the SecurityImpersonationLevel of at least Impersonation for Out of process Webhost activations.</value>
+ </data>
+ <data name="ComPlusInstanceProviderRequiresMessage0" xml:space="preserve">
+ <value>This InstanceContext requires a valid Message to obtain the instance.</value>
+ </data>
+ <data name="ComPlusInstanceCreationRequestSchema" xml:space="preserve">
+ <value>From: {0}
+AppId: {1}
+ClsId: {2}
+Incoming TransactionId: {3}
+Requesting Identity: {4}</value>
+ </data>
+ <data name="ComPlusMethodCallSchema" xml:space="preserve">
+ <value>From: {0}
+AppId: {1}
+ClsId: {2}
+Iid: {3}
+Action: {4}
+Instance Id: {5}
+Managed Thread Id: {6}
+Unmanaged Thread Id: {7}
+Requesting Identity: {8}</value>
+ </data>
+ <data name="ComPlusServiceSchema" xml:space="preserve">
+ <value>AppId: {0}
+ClsId: {1}
+</value>
+ </data>
+ <data name="ComPlusServiceSchemaDllHost" xml:space="preserve">
+ <value>AppId: {0}</value>
+ </data>
+ <data name="ComPlusTLBImportSchema" xml:space="preserve">
+ <value>Iid: {0}
+Type Library ID: {1}</value>
+ </data>
+ <data name="ComPlusServiceHostStartingServiceErrorNoQFE" xml:space="preserve">
+ <value>A Windows hotfix or later service pack is required on Windows XP and Windows Server 2003 to use WS-AtomicTransaction and COM+ Integration Web service transaction functionality. See the Microsoft .NET Framework release notes for instructions on installing the required hotfix.</value>
+ </data>
+ <data name="ComIntegrationManifestCreationFailed" xml:space="preserve">
+ <value>Generating manifest file {0} failed with {1}.</value>
+ </data>
+ <data name="TempDirectoryNotFound" xml:space="preserve">
+ <value>Directory {0} not found.</value>
+ </data>
+ <data name="CannotAccessDirectory" xml:space="preserve">
+ <value>Cannot access directory {0}.</value>
+ </data>
+ <data name="CLSIDDoesNotSupportIPersistStream" xml:space="preserve">
+ <value>The object with CLSID '{0}' does not support the required IPersistStream interface.</value>
+ </data>
+ <data name="CLSIDOfTypeDoesNotMatch" xml:space="preserve">
+ <value>CLSID of type {0} does not match the CLSID on PersistStreamTypeWrapper which is {1}.</value>
+ </data>
+ <data name="TargetObjectDoesNotSupportIPersistStream" xml:space="preserve">
+ <value>Target object does not support IPersistStream.</value>
+ </data>
+ <data name="TargetTypeIsAnIntefaceButCorrespoindingTypeIsNotPersistStreamTypeWrapper" xml:space="preserve">
+ <value>Target type is an interface but corresponding type is not PersistStreamTypeWrapper.</value>
+ </data>
+ <data name="NotAllowedPersistableCLSID" xml:space="preserve">
+ <value>CLSID {0} is not allowed.</value>
+ </data>
+ <data name="TransferringToComplus" xml:space="preserve">
+ <value>Transferring to ComPlus logical thread {0}.</value>
+ </data>
+ <data name="NamedArgsNotSupported" xml:space="preserve">
+ <value>The cNamedArgs parameter is not supported and must be 0.</value>
+ </data>
+ <data name="MexBindingNotFoundInConfig" xml:space="preserve">
+ <value>Binding '{0}' was not found in config. The config file must be present and contain a binding matching the one specified in the moniker.</value>
+ </data>
+ <data name="ClaimTypeCannotBeEmpty" xml:space="preserve">
+ <value>The claimType cannot be an empty string.</value>
+ </data>
+ <data name="X509ChainIsEmpty" xml:space="preserve">
+ <value>X509Chain does not have any valid certificates.</value>
+ </data>
+ <data name="MissingCustomCertificateValidator" xml:space="preserve">
+ <value>X509CertificateValidationMode.Custom requires a CustomCertificateValidator. Specify the CustomCertificateValidator property.</value>
+ </data>
+ <data name="MissingMembershipProvider" xml:space="preserve">
+ <value>UserNamePasswordValidationMode.MembershipProvider requires a MembershipProvider. Specify the MembershipProvider property.</value>
+ </data>
+ <data name="MissingCustomUserNamePasswordValidator" xml:space="preserve">
+ <value>UserNamePasswordValidationMode.Custom requires a CustomUserNamePasswordValidator. Specify the CustomUserNamePasswordValidator property.</value>
+ </data>
+ <data name="SpnegoImpersonationLevelCannotBeSetToNone" xml:space="preserve">
+ <value>The Security Support Provider Interface does not support Impersonation level 'None'. Specify Identification, Impersonation or Delegation level.</value>
+ </data>
+ <data name="PublicKeyNotRSA" xml:space="preserve">
+ <value>The public key is not an RSA key.</value>
+ </data>
+ <data name="SecurityAuditFailToLoadDll" xml:space="preserve">
+ <value>The '{0}' dynamic link library (dll) failed to load.</value>
+ </data>
+ <data name="SecurityAuditPlatformNotSupported" xml:space="preserve">
+ <value>Writing audit messages to the Security log is not supported by the current platform. You must write audit messages to the Application log.</value>
+ </data>
+ <data name="NoPrincipalSpecifiedInAuthorizationContext" xml:space="preserve">
+ <value>No custom principal is specified in the authorization context.</value>
+ </data>
+ <data name="AccessDenied" xml:space="preserve">
+ <value>Access is denied.</value>
+ </data>
+ <data name="SecurityAuditNotSupportedOnChannelFactory" xml:space="preserve">
+ <value>SecurityAuditBehavior is not supported on the channel factory.</value>
+ </data>
+ <data name="ExpiredTokenInChannelParameters" xml:space="preserve">
+ <value>The Infocard token created during channel intialization has expired. Please create a new channel to reacquire token. </value>
+ </data>
+ <data name="NoTokenInChannelParameters" xml:space="preserve">
+ <value>No Infocard token was found in the ChannelParameters. Infocard requires that the security token be created during channel intialization.</value>
+ </data>
+ <data name="PeerMessageMustHaveVia" xml:space="preserve">
+ <value>Message with action {0} received from a neighbor is missing a via Header.</value>
+ </data>
+ <data name="PeerLinkUtilityInvalidValues" xml:space="preserve">
+ <value>The LinkUtility message received from a neighbor has invalid values for usefull '{0}' and total '{1}'.</value>
+ </data>
+ <data name="PeerNeighborInvalidState" xml:space="preserve">
+ <value>Internal Error: Peer Neighbor state change from {0} to {1} is invalid.</value>
+ </data>
+ <data name="PeerMaxReceivedMessageSizeConflict" xml:space="preserve">
+ <value>The MaxReceivedMessageSize of the associated listener ({0}) is greater than the MaxReceivedMessageSize of the PeerNode ({1}) with the meshid ({2}), ensure that all ChannelFactories and Endpoints for this mesh have the same configuration for MaxRecievedMessageSize.</value>
+ </data>
+ <data name="PeerConflictingPeerNodeSettings" xml:space="preserve">
+ <value>Binding settings conflict with an existing instance that is using the same mesh name. Check the value of the property {0}.</value>
+ </data>
+ <data name="ArgumentOutOfRange" xml:space="preserve">
+ <value>value must be &gt;= {0} and &lt;= {1}.</value>
+ </data>
+ <data name="PeerChannelViaTooLong" xml:space="preserve">
+ <value>Invalid message: the peer channel via ({0}) has a size of ({1}) it exceeds the maximum via size of ({2}).</value>
+ </data>
+ <data name="PeerNodeAborted" xml:space="preserve">
+ <value>The PeerNode cannot be opened because it has been Aborted.</value>
+ </data>
+ <data name="PeerPnrpNotAvailable" xml:space="preserve">
+ <value>PNRP is not available. Please refer to the documentation with your system for details on how to install and enable PNRP.</value>
+ </data>
+ <data name="PeerPnrpNotInstalled" xml:space="preserve">
+ <value>The PNRP service is not installed on this machine. Please refer to the documentation with your system for details on how to install and enable PNRP.</value>
+ </data>
+ <data name="PeerResolverBindingElementRequired" xml:space="preserve">
+ <value>A PeerResolverBindingElement is required in the {0} binding. The default resolver (PNRP) is not available.</value>
+ </data>
+ <data name="PeerResolverRequired" xml:space="preserve">
+ <value>Resolver must be specified. The default resolver (PNRP) is not available. Please refer to the documentation with your system for details on how to install and enable PNRP.</value>
+ </data>
+ <data name="PeerResolverInvalid" xml:space="preserve">
+ <value>The specified ResolverType: {0} cannot be loaded. Please ensure that the type name specified refers to a type that can be loaded.</value>
+ </data>
+ <data name="PeerResolverSettingsInvalid" xml:space="preserve">
+ <value>Specified resolver settings are not enough to create a valid resolver. Please ensure that a ResolverType and an Address is specified for the custom resolver.</value>
+ </data>
+ <data name="PeerListenIPAddressInvalid" xml:space="preserve">
+ <value>The ListenIPAddress {0} is invalid.</value>
+ </data>
+ <data name="PeerFlooderDisposed" xml:space="preserve">
+ <value>Internal Error. PeerFlooder instance is already disposed. It cannot be used to send messages.</value>
+ </data>
+ <data name="PeerPnrpIllegalUri" xml:space="preserve">
+ <value>Internal Error. Address of the Service cannot be registered with PNRP.</value>
+ </data>
+ <data name="PeerInvalidRegistrationId" xml:space="preserve">
+ <value>The registrationId {0} is invalid.</value>
+ </data>
+ <data name="PeerConflictingHeader" xml:space="preserve">
+ <value>Application message contains a header that conflicts with a PeerChannel specific header. Name = {0} and Namespace = {1}.</value>
+ </data>
+ <data name="PnrpNoClouds" xml:space="preserve">
+ <value>PNRP could not find any clouds that match the current operation.</value>
+ </data>
+ <data name="PnrpAddressesUnsupported" xml:space="preserve">
+ <value>"Specified addresses can not be registered with PNRP because either PNRP is not enabled or the specified addresses do not have corresponding clouds. Please refer to the documentation with your system for details on how to install and enable PNRP."</value>
+ </data>
+ <data name="InsufficientCryptoSupport" xml:space="preserve">
+ <value>The binding's PeerTransportSecuritySettings can not be supported under the current system security configuration.</value>
+ </data>
+ <data name="InsufficientCredentials" xml:space="preserve">
+ <value>Credentials specified are not sufficient to carry requested operation. Please specify a valid value for {0}. </value>
+ </data>
+ <data name="UnexpectedSecurityTokensDuringHandshake" xml:space="preserve">
+ <value>Connection was not accepted because the SecurityContext contained tokens that do not match the current security settings.</value>
+ </data>
+ <data name="PnrpAddressesExceedLimit" xml:space="preserve">
+ <value>Addresses specified in the registration exceed PNRP's per registration address limit.</value>
+ </data>
+ <data name="InsufficientResolverSettings" xml:space="preserve">
+ <value>Provided information is Insufficient to create a valid connection to the resolver service.</value>
+ </data>
+ <data name="InvalidResolverMode" xml:space="preserve">
+ <value>Specified PeerResolverMode value {0} is invalid. Please specify either PeerResolveMode.Auto, Default, or Pnrp.</value>
+ </data>
+ <data name="MustOverrideInitialize" xml:space="preserve">
+ <value>concrete PeerResolver implementation must override Initialize to accept metadata about resolver service.</value>
+ </data>
+ <data name="NotValidWhenOpen" xml:space="preserve">
+ <value>The operation: {0} is not valid while the object is in open state.</value>
+ </data>
+ <data name="NotValidWhenClosed" xml:space="preserve">
+ <value>The operation: {0} is not valid while the object is in closed state.</value>
+ </data>
+ <data name="PeerNullRegistrationInfo" xml:space="preserve">
+ <value>Registration info can not be null. Please ensure that the Register operation is invoked with a valid RegistrationInfo object.</value>
+ </data>
+ <data name="PeerNullResolveInfo" xml:space="preserve">
+ <value>Resolve info can not be null. Please ensure that the Resolve operation is invoked with a valid ResolveInfo object.</value>
+ </data>
+ <data name="PeerNullRefreshInfo" xml:space="preserve">
+ <value>Refresh info can not be null. Please ensure that the Refresh operation is invoked with a valid RefreshInfo object.</value>
+ </data>
+ <data name="PeerInvalidMessageBody" xml:space="preserve">
+ <value>MessageBody does not contain a valid {0} message. Please ensure that the message is well formed.</value>
+ </data>
+ <data name="DuplicatePeerRegistration" xml:space="preserve">
+ <value>A peer registration with the service address {0} already exists.</value>
+ </data>
+ <data name="PeerNodeToStringFormat" xml:space="preserve">
+ <value>MeshId: {0}, Node Id: {1}, Online: {2}, Open: {3}, Port: {4}</value>
+ </data>
+ <data name="MessagePropagationException" xml:space="preserve">
+ <value>The MessagePropagationFilter threw an exception. Please refer to InnerException.</value>
+ </data>
+ <data name="NotificationException" xml:space="preserve">
+ <value>An event notification threw an exception. Please refer to InnerException.</value>
+ </data>
+ <data name="ResolverException" xml:space="preserve">
+ <value>The Peer resolver threw an exception. Please refer to InnerException.</value>
+ </data>
+ <data name="PnrpCloudNotFound" xml:space="preserve">
+ <value>One of the addresses specified doesn't match any PNRP cloud for registration.{0}</value>
+ </data>
+ <data name="PnrpCloudDisabled" xml:space="preserve">
+ <value>Specified cloud {0} could not be used for the specified operation because it is disabled.</value>
+ </data>
+ <data name="PnrpCloudResolveOnly" xml:space="preserve">
+ <value>Specified cloud {0} is configured for Resolve operations only.</value>
+ </data>
+ <data name="PnrpPortBlocked" xml:space="preserve">
+ <value>Requested PNRP operation {0} could not be performed because the port is blocked possibly by a firewall.</value>
+ </data>
+ <data name="PnrpDuplicatePeerName" xml:space="preserve">
+ <value>Specified mesh name {0} cannot be used because a name can only be registered once per process.</value>
+ </data>
+ <data name="RefreshIntervalMustBeGreaterThanZero" xml:space="preserve">
+ <value>Invalid RefreshInterval value of {0}; it must be greater than zero</value>
+ </data>
+ <data name="CleanupIntervalMustBeGreaterThanZero" xml:space="preserve">
+ <value>Invalid CleanupInterval value of {0}; it must be greater than zero</value>
+ </data>
+ <data name="AmbiguousConnectivitySpec" xml:space="preserve">
+ <value>Multiple link-local only interfaces detected. Please specifiy the interface you require by using the ListenIpAddress attribute in the PeerTransportBindingElement</value>
+ </data>
+ <data name="MustRegisterMoreThanZeroAddresses" xml:space="preserve">
+ <value>Registration with zero addresses detected. Please call Register with more than zero addresses.</value>
+ </data>
+ <data name="PeerCertGenFailure" xml:space="preserve">
+ <value>Certificate generation has failed. Please see the inner exception for more information.</value>
+ </data>
+ <data name="PeerThrottleWaiting" xml:space="preserve">
+ <value>Throttle on the mesh {0} waiting.</value>
+ </data>
+ <data name="PeerThrottlePruning" xml:space="preserve">
+ <value>Attempting to prune the slow neighbor for the mesh {0}.</value>
+ </data>
+ <data name="PeerMaintainerStarting" xml:space="preserve">
+ <value>Maintainer is starting for the mesh {0}.</value>
+ </data>
+ <data name="PeerMaintainerConnect" xml:space="preserve">
+ <value>Maintainer is attempting a connection to Peer {0} for the mesh {1}.</value>
+ </data>
+ <data name="PeerMaintainerConnectFailure" xml:space="preserve">
+ <value>Maintainer encountered exception when attempting a connection to Peer {0} for the mesh {1}. Exception is {2}.</value>
+ </data>
+ <data name="PeerMaintainerInitialConnect" xml:space="preserve">
+ <value>Mantainer's InitialConnect is running for the mesh {0}.</value>
+ </data>
+ <data name="PeerMaintainerPruneMode" xml:space="preserve">
+ <value>Mantainer is attempting to prune connections for the mesh {0}.</value>
+ </data>
+ <data name="PeerMaintainerConnectMode" xml:space="preserve">
+ <value>Mantainer is attempting to establish additional connections for the mesh {0}.</value>
+ </data>
+ <data name="BasicHttpContextBindingRequiresAllowCookie" xml:space="preserve">
+ <value>BasicHttpContextBinding {0}:{1} requires that AllowCookies property is set to true.</value>
+ </data>
+ <data name="CallbackContextOnlySupportedInWSAddressing10" xml:space="preserve">
+ <value>The message contains a callback context header with an endpoint reference for AddressingVersion '{0}'. Callback context can only be transmitted when the AddressingVersion is configured with 'WSAddressing10'.</value>
+ </data>
+ <data name="ListenAddressAlreadyContainsContext" xml:space="preserve">
+ <value>The callback address already has a context header in it.</value>
+ </data>
+ <data name="MultipleContextHeadersFoundInCallbackAddress" xml:space="preserve">
+ <value>The callback address contains multiple context headers. There can be at most one context header in a callback address.</value>
+ </data>
+ <data name="CallbackContextNotExpectedOnIncomingMessageAtClient" xml:space="preserve">
+ <value>The incoming message with action '{0}' contains a callback context header with name '{1}' and namespace '{2}'. Callback context headers are not expected in incoming messages at the client.</value>
+ </data>
+ <data name="CallbackContextOnlySupportedInSoap" xml:space="preserve">
+ <value>The message contains a callback context message property. Callback context can be transmitted only when the ContextBindingElement is configured with ContextExchangeMechanism of ContextSoapHeader.</value>
+ </data>
+ <data name="ContextBindingElementCannotProvideChannelFactory" xml:space="preserve">
+ <value>ContextBindingElement cannot provide channel factory for the requested channel shape {0}.</value>
+ </data>
+ <data name="ContextBindingElementCannotProvideChannelListener" xml:space="preserve">
+ <value>ContextBindingElement cannot provide channel listener for the requested channel shape {0}.</value>
+ </data>
+ <data name="InvalidCookieContent" xml:space="preserve">
+ <value>Value '{0}' specified for 'name' attribute of ContextMessageProperty is either null or has invalid character(s). Please ensure value of 'name' is within the allowed value space.</value>
+ </data>
+ <data name="SchemaViolationInsideContextHeader" xml:space="preserve">
+ <value>Context protocol was unable to parse the context header. Nodes disallowed by the context header schema were found inside the context header.</value>
+ </data>
+ <data name="CallbackContextNotExpectedOnOutgoingMessageAtServer" xml:space="preserve">
+ <value>The outgoing message with action '{0}' contains a callback context message property. Callback context cannot be transmitted in outgoing messages at the server.</value>
+ </data>
+ <data name="ChannelIsOpen" xml:space="preserve">
+ <value>Channel context management cannot be enabled or disabled after the channel is opened.</value>
+ </data>
+ <data name="ContextManagementNotEnabled" xml:space="preserve">
+ <value>Context cached at the channel cannot be set or retrieved when the context management is disabled at the channel layer. Ensure context channel property 'IContextManager.Enabled' is set to true.</value>
+ </data>
+ <data name="CachedContextIsImmutable" xml:space="preserve">
+ <value>Context cached at the channel layer cannot be changed after the channel is opened.</value>
+ </data>
+ <data name="InvalidMessageContext" xml:space="preserve">
+ <value>Cannot specify 'ContextMessageProperty' in message when using context channel with context management enabled. Ensure the message does not have 'ContextMessageProperty' or disable context management by setting channel property 'IContextManager.Enabled' to false.</value>
+ </data>
+ <data name="InvalidContextReceived" xml:space="preserve">
+ <value>Context channel received a message with context which does not match the current context cached at the channel. Ensure service does not change context after it was originally set or disable context management by setting channel property 'IContextManager.Enabled' to false.</value>
+ </data>
+ <data name="BehaviorRequiresContextProtocolSupportInBinding" xml:space="preserve">
+ <value>Service behavior {0} requires that the binding associated with endpoint {1} listening on {2} supports the context protocol, because the contract associated with this endpoint may require a session. Currently configured binding for this endpoint does not support the context protocol. Please modify the binding to add support for the context protocol or modify the SessionMode on the contract to NotAllowed.</value>
+ </data>
+ <data name="HttpCookieContextExchangeMechanismNotCompatibleWithTransportType" xml:space="preserve">
+ <value>Binding {1}:{2} is configured with ContextExchangeMechanism.HttpCookie which is not compatible with the transport type {0}. Please modify the ContextExchangeMechanism or use HTTP or HTTPS transport.</value>
+ </data>
+ <data name="HttpCookieContextExchangeMechanismNotCompatibleWithTransportCookieSetting" xml:space="preserve">
+ <value>ContextBindingElement of binding {0}:{1} is configured with ContextExchangeMode.HttpCookie but the configuration of this binding's HttpTransportBindingElement prevents upper channel layers from managing cookies. Please set the HttpTransportBindingElement.AllowCookies property to false or change the ContextExchangeMechanism of ContextBindingElement to SoapHeader.</value>
+ </data>
+ <data name="PolicyImportContextBindingElementCollectionIsNull" xml:space="preserve">
+ <value>ContextBindingElementImporter cannot import policy because PolicyImportContext.BindingElements collection is null.</value>
+ </data>
+ <data name="ContextChannelFactoryChannelCreatedDetail" xml:space="preserve">
+ <value>EndpointAddress: {0}, Via:{1}</value>
+ </data>
+ <data name="XmlFormatViolationInContextHeader" xml:space="preserve">
+ <value>Context protocol was unable to parse the context header.</value>
+ </data>
+ <data name="XmlFormatViolationInCallbackContextHeader" xml:space="preserve">
+ <value>Context protocol was unable to parse the callback context header.</value>
+ </data>
+ <data name="OleTxHeaderCorrupt" xml:space="preserve">
+ <value>The OLE Transactions header was invalid or corrupt.</value>
+ </data>
+ <data name="WsatHeaderCorrupt" xml:space="preserve">
+ <value>The WS-AtomicTransaction header was invalid or corrupt.</value>
+ </data>
+ <data name="FailedToDeserializeIssuedToken" xml:space="preserve">
+ <value>The issued token accompanying the WS-AtomicTransaction coordination context was invalid or corrupt.</value>
+ </data>
+ <data name="InvalidPropagationToken" xml:space="preserve">
+ <value>The OLE Transactions propagation token received in the message could not be used to unmarshal a transaction. It may be invalid or corrupt.</value>
+ </data>
+ <data name="InvalidWsatExtendedInfo" xml:space="preserve">
+ <value>The WS-AtomicTransaction extended information included in the OLE Transactions propagation token was invalid or corrupt.</value>
+ </data>
+ <data name="TMCommunicationError" xml:space="preserve">
+ <value>An error occurred communicating with the distributed transaction manager.</value>
+ </data>
+ <data name="UnmarshalTransactionFaulted" xml:space="preserve">
+ <value>The WS-AtomicTransaction protocol service could not unmarshal the flowed transaction. The following exception occured: {0}</value>
+ </data>
+ <data name="InvalidRegistrationHeaderTransactionId" xml:space="preserve">
+ <value>The transaction identifier element in the registration header is invalid</value>
+ </data>
+ <data name="InvalidRegistrationHeaderIdentifier" xml:space="preserve">
+ <value>The context identifier element in the registration header is invalid.</value>
+ </data>
+ <data name="InvalidRegistrationHeaderTokenId" xml:space="preserve">
+ <value>The token identifier element in the registration header is invalid.</value>
+ </data>
+ <data name="InvalidCoordinationContextTransactionId" xml:space="preserve">
+ <value>The transaction identifier element in the coordination context is invalid.</value>
+ </data>
+ <data name="WsatRegistryValueReadError" xml:space="preserve">
+ <value>The WS-AtomicTransaction transaction formatter could not read the registry value '{0}'.</value>
+ </data>
+ <data name="WsatProtocolServiceDisabled" xml:space="preserve">
+ <value>The MSDTC transaction manager's WS-AtomicTransaction protocol service '{0}' is disabled and cannot unmarshal incoming transactions.</value>
+ </data>
+ <data name="InboundTransactionsDisabled" xml:space="preserve">
+ <value>The MSDTC transaction manager has disabled incoming transactions.</value>
+ </data>
+ <data name="SourceTransactionsDisabled" xml:space="preserve">
+ <value>The incoming transaction cannot be unmarshaled because the source MSDTC transaction manager has either disabled outbound transactions or disabled its WS-AtomicTransaction protocol service.</value>
+ </data>
+ <data name="WsatUriCreationFailed" xml:space="preserve">
+ <value>A registration service address could not be created from MSDTC whereabouts information.</value>
+ </data>
+ <data name="WhereaboutsReadFailed" xml:space="preserve">
+ <value>The MSDTC whereabouts information could not be deserialized.</value>
+ </data>
+ <data name="WhereaboutsSignatureMissing" xml:space="preserve">
+ <value>The standard whereabouts signature was missing from the MSDTC whereabouts information.</value>
+ </data>
+ <data name="WhereaboutsImplausibleProtocolCount" xml:space="preserve">
+ <value>The MSDTC whereabouts information's protocol count was invalid.</value>
+ </data>
+ <data name="WhereaboutsImplausibleHostNameByteCount" xml:space="preserve">
+ <value>The MSDTC whereabouts information's host name byte count was invalid.</value>
+ </data>
+ <data name="WhereaboutsInvalidHostName" xml:space="preserve">
+ <value>The MSDTC whereabouts information's host name was invalid.</value>
+ </data>
+ <data name="WhereaboutsNoHostName" xml:space="preserve">
+ <value>The MSDTC whereabouts information did not contain a host name.</value>
+ </data>
+ <data name="InvalidWsatProtocolVersion" xml:space="preserve">
+ <value>The specified WSAT protocol version is invalid.</value>
+ </data>
+ <data name="ParameterCannotBeEmpty" xml:space="preserve">
+ <value>The parameter cannot be empty.</value>
+ </data>
+ <data name="RedirectCache" xml:space="preserve">
+ <value>The requested resouce has not changed and should be taken from cache.</value>
+ </data>
+ <data name="RedirectResource" xml:space="preserve">
+ <value>The requested resource has moved to one of the following locations:
+{0}</value>
+ </data>
+ <data name="RedirectUseIntermediary" xml:space="preserve">
+ <value>The requested resource must be accessed through one of the following intermediary service locations:
+{0}</value>
+ </data>
+ <data name="RedirectGenericMessage" xml:space="preserve">
+ <value>The requested resource has been moved.</value>
+ </data>
+ <data name="RedirectMustProvideLocation" xml:space="preserve">
+ <value>At least one RedirectionLocation must be provided for this RedirectionType.</value>
+ </data>
+ <data name="RedirectCacheNoLocationAllowed" xml:space="preserve">
+ <value>RedirectionType 'Cache' does not allow any RedirectionLocation objects be passed into the constructor.</value>
+ </data>
+ <data name="RedirectionInfoStringFormatWithNamespace" xml:space="preserve">
+ <value>{0} ({1})</value>
+ </data>
+ <data name="RedirectionInfoStringFormatNoNamespace" xml:space="preserve">
+ <value>{0}</value>
+ </data>
+ <data name="RetryGenericMessage" xml:space="preserve">
+ <value>The requested resource is available.</value>
+ </data>
+ <data name="ActivityCallback" xml:space="preserve">
+ <value>Executing user callback.</value>
+ </data>
+ <data name="ActivityClose" xml:space="preserve">
+ <value>Close '{0}'.</value>
+ </data>
+ <data name="ActivityConstructChannelFactory" xml:space="preserve">
+ <value>Construct ChannelFactory. Contract type: '{0}'.</value>
+ </data>
+ <data name="ActivityConstructServiceHost" xml:space="preserve">
+ <value>Construct ServiceHost '{0}'.</value>
+ </data>
+ <data name="ActivityExecuteMethod" xml:space="preserve">
+ <value>Execute '{0}.{1}'.</value>
+ </data>
+ <data name="ActivityExecuteAsyncMethod" xml:space="preserve">
+ <value>Execute Async: Begin: '{0}.{1}'; End: '{2}.{3}'.</value>
+ </data>
+ <data name="ActivityCloseChannelFactory" xml:space="preserve">
+ <value>Close ChannelFactory. Contract type: '{0}'.</value>
+ </data>
+ <data name="ActivityCloseClientBase" xml:space="preserve">
+ <value>Close ClientBase. Contract type: '{0}'.</value>
+ </data>
+ <data name="ActivityCloseServiceHost" xml:space="preserve">
+ <value>Close ServiceHost '{0}'.</value>
+ </data>
+ <data name="ActivityListenAt" xml:space="preserve">
+ <value>Listen at '{0}'.</value>
+ </data>
+ <data name="ActivityOpen" xml:space="preserve">
+ <value>Open '{0}'.</value>
+ </data>
+ <data name="ActivityOpenServiceHost" xml:space="preserve">
+ <value>Open ServiceHost '{0}'.</value>
+ </data>
+ <data name="ActivityOpenChannelFactory" xml:space="preserve">
+ <value>Open ChannelFactory. Contract type: '{0}'.</value>
+ </data>
+ <data name="ActivityOpenClientBase" xml:space="preserve">
+ <value>Open ClientBase. Contract type: '{0}'.</value>
+ </data>
+ <data name="ActivityProcessAction" xml:space="preserve">
+ <value>Process action '{0}'.</value>
+ </data>
+ <data name="ActivityProcessingMessage" xml:space="preserve">
+ <value>Processing message {0}.</value>
+ </data>
+ <data name="ActivityReceiveBytes" xml:space="preserve">
+ <value>Receive bytes on connection '{0}'.</value>
+ </data>
+ <data name="ActivitySecuritySetup" xml:space="preserve">
+ <value>Set up Secure Session.</value>
+ </data>
+ <data name="ActivitySecurityRenew" xml:space="preserve">
+ <value>Renew Secure Session.</value>
+ </data>
+ <data name="ActivitySecurityClose" xml:space="preserve">
+ <value>Close Security Session.</value>
+ </data>
+ <data name="ActivitySharedListenerConnection" xml:space="preserve">
+ <value>Shared listener connection: '{0}'.</value>
+ </data>
+ <data name="ActivitySocketConnection" xml:space="preserve">
+ <value>Socket connection: '{0}'.</value>
+ </data>
+ <data name="ActivityReadOnConnection" xml:space="preserve">
+ <value>Reading data from connection on '{0}'.</value>
+ </data>
+ <data name="ActivityReceiveAtVia" xml:space="preserve">
+ <value>Receiving data at via '{0}'.</value>
+ </data>
+ <data name="TraceCodeBeginExecuteMethod" xml:space="preserve">
+ <value>Begin method execution.</value>
+ </data>
+ <data name="TraceCodeChannelCreated" xml:space="preserve">
+ <value>Created: {0}</value>
+ </data>
+ <data name="TraceCodeChannelDisposed" xml:space="preserve">
+ <value>Disposed: {0}</value>
+ </data>
+ <data name="TraceCodeChannelMessageSent" xml:space="preserve">
+ <value>Sent a message over a channel</value>
+ </data>
+ <data name="TraceCodeChannelPreparedMessage" xml:space="preserve">
+ <value>Prepared message for sending over a channel</value>
+ </data>
+ <data name="TraceCodeComIntegrationChannelCreated" xml:space="preserve">
+ <value>ComPlus:channel created.</value>
+ </data>
+ <data name="TraceCodeComIntegrationDispatchMethod" xml:space="preserve">
+ <value>ComPlus:Dispatch method details.</value>
+ </data>
+ <data name="TraceCodeComIntegrationDllHostInitializerAddingHost" xml:space="preserve">
+ <value>ComPlus:DllHost initializer:Adding host.</value>
+ </data>
+ <data name="TraceCodeComIntegrationDllHostInitializerStarted" xml:space="preserve">
+ <value>ComPlus:Started DllHost initializer.</value>
+ </data>
+ <data name="TraceCodeComIntegrationDllHostInitializerStarting" xml:space="preserve">
+ <value>ComPlus:Starting DllHost initializer.</value>
+ </data>
+ <data name="TraceCodeComIntegrationDllHostInitializerStopped" xml:space="preserve">
+ <value>ComPlus:Stopped DllHost initializer.</value>
+ </data>
+ <data name="TraceCodeComIntegrationDllHostInitializerStopping" xml:space="preserve">
+ <value>ComPlus:Stopping DllHost initializer.</value>
+ </data>
+ <data name="TraceCodeComIntegrationEnteringActivity" xml:space="preserve">
+ <value>ComPlus:Entering COM+ activity.</value>
+ </data>
+ <data name="TraceCodeComIntegrationExecutingCall" xml:space="preserve">
+ <value>ComPlus:Executing COM call.</value>
+ </data>
+ <data name="TraceCodeComIntegrationInstanceCreationRequest" xml:space="preserve">
+ <value>ComPlus:Received instance creation request.</value>
+ </data>
+ <data name="TraceCodeComIntegrationInstanceCreationSuccess" xml:space="preserve">
+ <value>ComPlus:Created instance.</value>
+ </data>
+ <data name="TraceCodeComIntegrationInstanceReleased" xml:space="preserve">
+ <value>ComPlus:Released instance.</value>
+ </data>
+ <data name="TraceCodeComIntegrationInvokedMethod" xml:space="preserve">
+ <value>ComPlus:Invoked method.</value>
+ </data>
+ <data name="TraceCodeComIntegrationInvokingMethod" xml:space="preserve">
+ <value>ComPlus:Invoking method.</value>
+ </data>
+ <data name="TraceCodeComIntegrationInvokingMethodContextTransaction" xml:space="preserve">
+ <value>Complus:Invoking method with transaction in COM+ context.</value>
+ </data>
+ <data name="TraceCodeComIntegrationInvokingMethodNewTransaction" xml:space="preserve">
+ <value>Complus:Invoking method with new incoming transaction.</value>
+ </data>
+ <data name="TraceCodeComIntegrationLeftActivity" xml:space="preserve">
+ <value>ComPlus:Left COM+ activity.</value>
+ </data>
+ <data name="TraceCodeComIntegrationMexChannelBuilderLoaded" xml:space="preserve">
+ <value>Complus:Mex channel loader loaded.</value>
+ </data>
+ <data name="TraceCodeComIntegrationMexMonikerMetadataExchangeComplete" xml:space="preserve">
+ <value>Complus:Metadata exchange completed successfully.</value>
+ </data>
+ <data name="TraceCodeComIntegrationServiceHostCreatedServiceContract" xml:space="preserve">
+ <value>ComPlus:Created service contract.</value>
+ </data>
+ <data name="TraceCodeComIntegrationServiceHostCreatedServiceEndpoint" xml:space="preserve">
+ <value>ComPlus:Created service endpoint.</value>
+ </data>
+ <data name="TraceCodeComIntegrationServiceHostStartedService" xml:space="preserve">
+ <value>ComPlus:Started service.</value>
+ </data>
+ <data name="TraceCodeComIntegrationServiceHostStartedServiceDetails" xml:space="preserve">
+ <value>ComPlus:Started service:details.</value>
+ </data>
+ <data name="TraceCodeComIntegrationServiceHostStartingService" xml:space="preserve">
+ <value>ComPlus:Starting service.</value>
+ </data>
+ <data name="TraceCodeComIntegrationServiceHostStoppedService" xml:space="preserve">
+ <value>ComPlus:Stopped service.</value>
+ </data>
+ <data name="TraceCodeComIntegrationServiceHostStoppingService" xml:space="preserve">
+ <value>ComPlus:Stopping service.</value>
+ </data>
+ <data name="TraceCodeComIntegrationServiceMonikerParsed" xml:space="preserve">
+ <value>ComPlus:Service moniker parsed.</value>
+ </data>
+ <data name="TraceCodeComIntegrationTLBImportConverterEvent" xml:space="preserve">
+ <value>ComPlus:Type library converter event.</value>
+ </data>
+ <data name="TraceCodeComIntegrationTLBImportFinished" xml:space="preserve">
+ <value>ComPlus:Finished type library import.</value>
+ </data>
+ <data name="TraceCodeComIntegrationTLBImportFromAssembly" xml:space="preserve">
+ <value>ComPlus:Type library import: using assembly.</value>
+ </data>
+ <data name="TraceCodeComIntegrationTLBImportFromTypelib" xml:space="preserve">
+ <value>ComPlus:Type library import: using type library.</value>
+ </data>
+ <data name="TraceCodeComIntegrationTLBImportStarting" xml:space="preserve">
+ <value>ComPlus:Starting type library import.</value>
+ </data>
+ <data name="TraceCodeComIntegrationTxProxyTxAbortedByContext" xml:space="preserve">
+ <value>ComPlus:Transaction aborted by COM+ context.</value>
+ </data>
+ <data name="TraceCodeComIntegrationTxProxyTxAbortedByTM" xml:space="preserve">
+ <value>ComPlus:Transaction aborted by Transaction Manager.</value>
+ </data>
+ <data name="TraceCodeComIntegrationTxProxyTxCommitted" xml:space="preserve">
+ <value>ComPlus:Transaction committed.</value>
+ </data>
+ <data name="TraceCodeComIntegrationTypedChannelBuilderLoaded" xml:space="preserve">
+ <value>ComPlus:Typed channel builder loaded.</value>
+ </data>
+ <data name="TraceCodeComIntegrationWsdlChannelBuilderLoaded" xml:space="preserve">
+ <value>ComPlus:WSDL channel builder loaded.</value>
+ </data>
+ <data name="TraceCodeCommunicationObjectAborted" xml:space="preserve">
+ <value>Aborted '{0}'.</value>
+ </data>
+ <data name="TraceCodeCommunicationObjectAbortFailed" xml:space="preserve">
+ <value>Failed to abort {0}</value>
+ </data>
+ <data name="TraceCodeCommunicationObjectCloseFailed" xml:space="preserve">
+ <value>Failed to close {0}</value>
+ </data>
+ <data name="TraceCodeCommunicationObjectClosed" xml:space="preserve">
+ <value>Closed {0}</value>
+ </data>
+ <data name="TraceCodeCommunicationObjectCreated" xml:space="preserve">
+ <value>Created {0}</value>
+ </data>
+ <data name="TraceCodeCommunicationObjectClosing" xml:space="preserve">
+ <value>Closing {0}</value>
+ </data>
+ <data name="TraceCodeCommunicationObjectDisposing" xml:space="preserve">
+ <value>Disposing {0}</value>
+ </data>
+ <data name="TraceCodeCommunicationObjectFaultReason" xml:space="preserve">
+ <value>CommunicationObject faulted due to exception.</value>
+ </data>
+ <data name="TraceCodeCommunicationObjectFaulted" xml:space="preserve">
+ <value>Faulted {0}</value>
+ </data>
+ <data name="TraceCodeCommunicationObjectOpenFailed" xml:space="preserve">
+ <value>Failed to open {0}</value>
+ </data>
+ <data name="TraceCodeCommunicationObjectOpened" xml:space="preserve">
+ <value>Opened {0}</value>
+ </data>
+ <data name="TraceCodeCommunicationObjectOpening" xml:space="preserve">
+ <value>Opening {0}</value>
+ </data>
+ <data name="TraceCodeConfigurationIsReadOnly" xml:space="preserve">
+ <value>The configuration is read-only.</value>
+ </data>
+ <data name="TraceCodeConfiguredExtensionTypeNotFound" xml:space="preserve">
+ <value>Extension type is not configured.</value>
+ </data>
+ <data name="TraceCodeConnectionAbandoned" xml:space="preserve">
+ <value>The connection has been abandoned.</value>
+ </data>
+ <data name="TraceCodeConnectToIPEndpoint" xml:space="preserve">
+ <value>Connection information.</value>
+ </data>
+ <data name="TraceCodeConnectionPoolCloseException" xml:space="preserve">
+ <value>An exception occurred while closing the connections in this connection pool.</value>
+ </data>
+ <data name="TraceCodeConnectionPoolIdleTimeoutReached" xml:space="preserve">
+ <value>A connection has exceeded the idle timeout of this connection pool ({0}) and been closed.</value>
+ </data>
+ <data name="TraceCodeConnectionPoolLeaseTimeoutReached" xml:space="preserve">
+ <value>A connection has exceeded the connection lease timeout of this connection pool ({0}) and been closed.</value>
+ </data>
+ <data name="TraceCodeConnectionPoolMaxOutboundConnectionsPerEndpointQuotaReached" xml:space="preserve">
+ <value>MaxOutboundConnectionsPerEndpoint quota ({0}) has been reached, so connection was closed and not stored in this connection pool.</value>
+ </data>
+ <data name="TraceCodeServerMaxPooledConnectionsQuotaReached" xml:space="preserve">
+ <value>MaxOutboundConnectionsPerEndpoint quota ({0}) has been reached, so the connection was closed and not reused by the listener.</value>
+ </data>
+ <data name="TraceCodeDefaultEndpointsAdded" xml:space="preserve">
+ <value>No matching &lt;service&gt; tag was found. Default endpoints added.</value>
+ </data>
+ <data name="TraceCodeDiagnosticsFailedMessageTrace" xml:space="preserve">
+ <value>Failed to trace a message</value>
+ </data>
+ <data name="TraceCodeDidNotUnderstandMessageHeader" xml:space="preserve">
+ <value>Did not understand message header.</value>
+ </data>
+ <data name="TraceCodeDroppedAMessage" xml:space="preserve">
+ <value>A response message was received, but there are no outstanding requests waiting for this message. The message is being dropped.</value>
+ </data>
+ <data name="TraceCodeCannotBeImportedInCurrentFormat" xml:space="preserve">
+ <value>The given schema cannot be imported in this format.</value>
+ </data>
+ <data name="TraceCodeElementTypeDoesntMatchConfiguredType" xml:space="preserve">
+ <value>The type of the element does not match the configuration type.</value>
+ </data>
+ <data name="TraceCodeEndExecuteMethod" xml:space="preserve">
+ <value>End method execution.</value>
+ </data>
+ <data name="TraceCodeEndpointListenerClose" xml:space="preserve">
+ <value>Endpoint listener closed.</value>
+ </data>
+ <data name="TraceCodeEndpointListenerOpen" xml:space="preserve">
+ <value>Endpoint listener opened.</value>
+ </data>
+ <data name="TraceCodeErrorInvokingUserCode" xml:space="preserve">
+ <value>Error invoking user code</value>
+ </data>
+ <data name="TraceCodeEvaluationContextNotFound" xml:space="preserve">
+ <value>Configuration evaluation context not found.</value>
+ </data>
+ <data name="TraceCodeExportSecurityChannelBindingEntry" xml:space="preserve">
+ <value>Starting Security ExportChannelBinding</value>
+ </data>
+ <data name="TraceCodeExportSecurityChannelBindingExit" xml:space="preserve">
+ <value>Finished Security ExportChannelBinding</value>
+ </data>
+ <data name="TraceCodeExtensionCollectionDoesNotExist" xml:space="preserve">
+ <value>The extension collection does not exist.</value>
+ </data>
+ <data name="TraceCodeExtensionCollectionIsEmpty" xml:space="preserve">
+ <value>The extension collection is empty.</value>
+ </data>
+ <data name="TraceCodeExtensionCollectionNameNotFound" xml:space="preserve">
+ <value>Extension element not associated with an extension collection.</value>
+ </data>
+ <data name="TraceCodeExtensionElementAlreadyExistsInCollection" xml:space="preserve">
+ <value>The extension element already exists in the collection.</value>
+ </data>
+ <data name="TraceCodeExtensionTypeNotFound" xml:space="preserve">
+ <value>Extension type not found.</value>
+ </data>
+ <data name="TraceCodeFailedToAddAnActivityIdHeader" xml:space="preserve">
+ <value>Failed to set an activity id header on an outgoing message</value>
+ </data>
+ <data name="TraceCodeFailedToReadAnActivityIdHeader" xml:space="preserve">
+ <value>Failed to read an activity id header on a message</value>
+ </data>
+ <data name="TraceCodeFilterNotMatchedNodeQuotaExceeded" xml:space="preserve">
+ <value>Evaluating message logging filter against the message exceeded the node quota set on the filter.</value>
+ </data>
+ <data name="TraceCodeGetBehaviorElement" xml:space="preserve">
+ <value>Get BehaviorElement.</value>
+ </data>
+ <data name="TraceCodeGetChannelEndpointElement" xml:space="preserve">
+ <value>Get ChannelEndpointElement.</value>
+ </data>
+ <data name="TraceCodeGetCommonBehaviors" xml:space="preserve">
+ <value>Get machine.config common behaviors.</value>
+ </data>
+ <data name="TraceCodeGetConfigurationSection" xml:space="preserve">
+ <value>Get configuration section.</value>
+ </data>
+ <data name="TraceCodeGetConfiguredBinding" xml:space="preserve">
+ <value>Get configured binding.</value>
+ </data>
+ <data name="TraceCodeGetDefaultConfiguredBinding" xml:space="preserve">
+ <value>Get default configured binding.</value>
+ </data>
+ <data name="TraceCodeGetConfiguredEndpoint" xml:space="preserve">
+ <value>Get configured endpoint.</value>
+ </data>
+ <data name="TraceCodeGetDefaultConfiguredEndpoint" xml:space="preserve">
+ <value>Get default configured endpoint.</value>
+ </data>
+ <data name="TraceCodeGetServiceElement" xml:space="preserve">
+ <value>Get ServiceElement.</value>
+ </data>
+ <data name="TraceCodeHttpAuthFailed" xml:space="preserve">
+ <value>Authentication failed for HTTP(S) connection</value>
+ </data>
+ <data name="TraceCodeHttpActionMismatch" xml:space="preserve">
+ <value>The HTTP SOAPAction header and the wsa:Action SOAP header did not match. </value>
+ </data>
+ <data name="TraceCodeHttpChannelMessageReceiveFailed" xml:space="preserve">
+ <value>Failed to lookup a channel to receive an incoming message. Either the endpoint or the SOAP action was not found.</value>
+ </data>
+ <data name="TraceCodeHttpChannelRequestAborted" xml:space="preserve">
+ <value>Failed to send request message over HTTP</value>
+ </data>
+ <data name="TraceCodeHttpChannelResponseAborted" xml:space="preserve">
+ <value>Failed to send response message over HTTP</value>
+ </data>
+ <data name="TraceCodeHttpChannelUnexpectedResponse" xml:space="preserve">
+ <value>Received bad HTTP response</value>
+ </data>
+ <data name="TraceCodeHttpResponseReceived" xml:space="preserve">
+ <value>HTTP response was received</value>
+ </data>
+ <data name="TraceCodeHttpChannelConcurrentReceiveQuotaReached" xml:space="preserve">
+ <value>The HTTP concurrent receive quota was reached.</value>
+ </data>
+ <data name="TraceCodeHttpsClientCertificateInvalid" xml:space="preserve">
+ <value>Client certificate is invalid.</value>
+ </data>
+ <data name="TraceCodeHttpsClientCertificateInvalid1" xml:space="preserve">
+ <value>Client certificate is invalid with native error code {0} (see http://go.microsoft.com/fwlink/?LinkId=187517 for details).</value>
+ </data>
+ <data name="TraceCodeHttpsClientCertificateNotPresent" xml:space="preserve">
+ <value>Client certificate is required. No certificate was found in the request. This might be because the client certificate could not be successfully validated by the operating system or IIS. For information on how to bypass those validations and use a custom X509CertificateValidator in WCF please see http://go.microsoft.com/fwlink/?LinkId=208540.</value>
+ </data>
+ <data name="TraceCodeImportSecurityChannelBindingEntry" xml:space="preserve">
+ <value>Starting Security ImportChannelBinding</value>
+ </data>
+ <data name="TraceCodeImportSecurityChannelBindingExit" xml:space="preserve">
+ <value>Finished Security ImportChannelBinding</value>
+ </data>
+ <data name="TraceCodeIncompatibleExistingTransportManager" xml:space="preserve">
+ <value>An existing incompatible transport manager was found for the specified URI.</value>
+ </data>
+ <data name="TraceCodeInitiatingNamedPipeConnection" xml:space="preserve">
+ <value>Initiating Named Pipe connection.</value>
+ </data>
+ <data name="TraceCodeInitiatingTcpConnection" xml:space="preserve">
+ <value>Initiating TCP connection.</value>
+ </data>
+ <data name="TraceCodeIssuanceTokenProviderBeginSecurityNegotiation" xml:space="preserve">
+ <value>The IssuanceTokenProvider has started a new security negotiation.</value>
+ </data>
+ <data name="TraceCodeIssuanceTokenProviderEndSecurityNegotiation" xml:space="preserve">
+ <value>The IssuanceTokenProvider has completed the security negotiation.</value>
+ </data>
+ <data name="TraceCodeIssuanceTokenProviderRedirectApplied" xml:space="preserve">
+ <value>The IssuanceTokenProvider applied a redirection header.</value>
+ </data>
+ <data name="TraceCodeIssuanceTokenProviderRemovedCachedToken" xml:space="preserve">
+ <value>The IssuanceTokenProvider removed the expired service token.</value>
+ </data>
+ <data name="TraceCodeIssuanceTokenProviderServiceTokenCacheFull" xml:space="preserve">
+ <value>IssuanceTokenProvider pruned service token cache.</value>
+ </data>
+ <data name="TraceCodeIssuanceTokenProviderUsingCachedToken" xml:space="preserve">
+ <value>The IssuanceTokenProvider used the cached service token.</value>
+ </data>
+ <data name="TraceCodeListenerCreated" xml:space="preserve">
+ <value>Listener created</value>
+ </data>
+ <data name="TraceCodeListenerDisposed" xml:space="preserve">
+ <value>Listener disposed</value>
+ </data>
+ <data name="TraceCodeMaxPendingConnectionsReached" xml:space="preserve">
+ <value>Maximum number of pending connections has been reached. </value>
+ </data>
+ <data name="TraceCodeMaxAcceptedChannelsReached" xml:space="preserve">
+ <value>Maximum number of inbound session channel has been reached. </value>
+ </data>
+ <data name="TraceCodeMessageClosed" xml:space="preserve">
+ <value>A message was closed</value>
+ </data>
+ <data name="TraceCodeMessageClosedAgain" xml:space="preserve">
+ <value>A message was closed again</value>
+ </data>
+ <data name="TraceCodeMessageCopied" xml:space="preserve">
+ <value>A message was copied</value>
+ </data>
+ <data name="TraceCodeMessageCountLimitExceeded" xml:space="preserve">
+ <value>Reached the limit of messages to log. Message logging is stopping. </value>
+ </data>
+ <data name="TraceCodeMessageNotLoggedQuotaExceeded" xml:space="preserve">
+ <value>Message not logged because its size exceeds configured quota</value>
+ </data>
+ <data name="TraceCodeMessageRead" xml:space="preserve">
+ <value>A message was read</value>
+ </data>
+ <data name="TraceCodeMessageSent" xml:space="preserve">
+ <value>Sent a message over a channel.</value>
+ </data>
+ <data name="TraceCodeMessageReceived" xml:space="preserve">
+ <value>Received a message over a channel.</value>
+ </data>
+ <data name="TraceCodeMessageWritten" xml:space="preserve">
+ <value>A message was written</value>
+ </data>
+ <data name="TraceCodeMessageProcessingPaused" xml:space="preserve">
+ <value>Switched threads while processing a message.</value>
+ </data>
+ <data name="TraceCodeMsmqCannotPeekOnQueue" xml:space="preserve">
+ <value>MsmqActivation service cannot peek on the queue.</value>
+ </data>
+ <data name="TraceCodeMsmqCannotReadQueues" xml:space="preserve">
+ <value>MsmqActivation service cannot discover queues.</value>
+ </data>
+ <data name="TraceCodeMsmqDatagramReceived" xml:space="preserve">
+ <value>MSMQ datagram message received.</value>
+ </data>
+ <data name="TraceCodeMsmqDatagramSent" xml:space="preserve">
+ <value>MSMQ datagram message sent.</value>
+ </data>
+ <data name="TraceCodeMsmqDetected" xml:space="preserve">
+ <value>MSMQ detected successfully.</value>
+ </data>
+ <data name="TraceCodeMsmqEnteredBatch" xml:space="preserve">
+ <value>Entered batching mode.</value>
+ </data>
+ <data name="TraceCodeMsmqExpectedException" xml:space="preserve">
+ <value>Expected exception caught.</value>
+ </data>
+ <data name="TraceCodeMsmqFoundBaseAddress" xml:space="preserve">
+ <value>Hosting environment found the base address for the service.</value>
+ </data>
+ <data name="TraceCodeMsmqLeftBatch" xml:space="preserve">
+ <value>Left batching mode.</value>
+ </data>
+ <data name="TraceCodeMsmqMatchedApplicationFound" xml:space="preserve">
+ <value>MsmqActivation service found application matching queue.</value>
+ </data>
+ <data name="TraceCodeMsmqMessageLockedUnderTheTransaction" xml:space="preserve">
+ <value>Cannot move or delete message because it is still locked under the transaction.</value>
+ </data>
+ <data name="TraceCodeMsmqMessageDropped" xml:space="preserve">
+ <value>Message was dropped.</value>
+ </data>
+ <data name="TraceCodeMsmqMessageRejected" xml:space="preserve">
+ <value>Message was rejected.</value>
+ </data>
+ <data name="TraceCodeMsmqMoveOrDeleteAttemptFailed" xml:space="preserve">
+ <value>Cannot move or delete message.</value>
+ </data>
+ <data name="TraceCodeMsmqPoisonMessageMovedPoison" xml:space="preserve">
+ <value>Poison message moved to the poison subqueue.</value>
+ </data>
+ <data name="TraceCodeMsmqPoisonMessageMovedRetry" xml:space="preserve">
+ <value>Poison message moved to the retry subqueue.</value>
+ </data>
+ <data name="TraceCodeMsmqPoisonMessageRejected" xml:space="preserve">
+ <value>Poison message rejected.</value>
+ </data>
+ <data name="TraceCodeMsmqPoolFull" xml:space="preserve">
+ <value>Pool of the native MSMQ messages is full. This may affect performance.</value>
+ </data>
+ <data name="TraceCodeMsmqPotentiallyPoisonMessageDetected" xml:space="preserve">
+ <value>Transaction which received this message was aborted at least once.</value>
+ </data>
+ <data name="TraceCodeMsmqQueueClosed" xml:space="preserve">
+ <value>MSMQ queue closed.</value>
+ </data>
+ <data name="TraceCodeMsmqQueueOpened" xml:space="preserve">
+ <value>MSMQ queue opened.</value>
+ </data>
+ <data name="TraceCodeMsmqQueueTransactionalStatusUnknown" xml:space="preserve">
+ <value>Cannot detect if the queue is transactional.</value>
+ </data>
+ <data name="TraceCodeMsmqScanStarted" xml:space="preserve">
+ <value>MsmqActivation service started scan for queues.</value>
+ </data>
+ <data name="TraceCodeMsmqSessiongramReceived" xml:space="preserve">
+ <value>MSMQ transport session received.</value>
+ </data>
+ <data name="TraceCodeMsmqSessiongramSent" xml:space="preserve">
+ <value>MSMQ transport session sent.</value>
+ </data>
+ <data name="TraceCodeMsmqStartingApplication" xml:space="preserve">
+ <value>MSMQ Activation service started application.</value>
+ </data>
+ <data name="TraceCodeMsmqStartingService" xml:space="preserve">
+ <value>Hosting environment started service.</value>
+ </data>
+ <data name="TraceCodeMsmqUnexpectedAcknowledgment" xml:space="preserve">
+ <value>Unexpected acknowledgment value.</value>
+ </data>
+ <data name="TraceCodeNamedPipeChannelMessageReceiveFailed" xml:space="preserve">
+ <value>Failed to receive a message over a named pipe channel.</value>
+ </data>
+ <data name="TraceCodeNamedPipeChannelMessageReceived" xml:space="preserve">
+ <value>Received a message over a named pipe channel.</value>
+ </data>
+ <data name="TraceCodeNegotiationAuthenticatorAttached" xml:space="preserve">
+ <value>NegotiationTokenAuthenticator was attached.</value>
+ </data>
+ <data name="TraceCodeNegotiationTokenProviderAttached" xml:space="preserve">
+ <value>NegotiationTokenProvider was attached.</value>
+ </data>
+ <data name="TraceCodeNoExistingTransportManager" xml:space="preserve">
+ <value>No existing transport manager was found for the specified URI.</value>
+ </data>
+ <data name="TraceCodeOpenedListener" xml:space="preserve">
+ <value>Transport is listening at base URI.</value>
+ </data>
+ <data name="TraceCodeOverridingDuplicateConfigurationKey" xml:space="preserve">
+ <value>The configuration system has detected a duplicate key in a different configuration scope and is overriding with the more recent value.</value>
+ </data>
+ <data name="TraceCodePeerChannelMessageReceived" xml:space="preserve">
+ <value>A message was received by a peer channel.</value>
+ </data>
+ <data name="TraceCodePeerChannelMessageSent" xml:space="preserve">
+ <value>A message was sent on a peer channel.</value>
+ </data>
+ <data name="TraceCodePeerFloodedMessageNotMatched" xml:space="preserve">
+ <value>A PeerNode received a message that did not match any local channels.</value>
+ </data>
+ <data name="TraceCodePeerFloodedMessageNotPropagated" xml:space="preserve">
+ <value>A PeerNode received a flooded message that was not propagated further.</value>
+ </data>
+ <data name="TraceCodePeerFloodedMessageReceived" xml:space="preserve">
+ <value>A PeerNode received a flooded message.</value>
+ </data>
+ <data name="TraceCodePeerFlooderReceiveMessageQuotaExceeded" xml:space="preserve">
+ <value>Received message could not be forwarded to other neighbors since it exceeded the quota set for the peer node.</value>
+ </data>
+ <data name="TraceCodePeerNeighborCloseFailed" xml:space="preserve">
+ <value>A Peer Neighbor close has failed.</value>
+ </data>
+ <data name="TraceCodePeerNeighborClosingFailed" xml:space="preserve">
+ <value>A Peer Neighbor closing has failed.</value>
+ </data>
+ <data name="TraceCodePeerNeighborManagerOffline" xml:space="preserve">
+ <value>A Peer Neighbor Manager is offline.</value>
+ </data>
+ <data name="TraceCodePeerNeighborManagerOnline" xml:space="preserve">
+ <value>A Peer Neighbor Manager is online.</value>
+ </data>
+ <data name="TraceCodePeerNeighborMessageReceived" xml:space="preserve">
+ <value>A message was received by a Peer Neighbor.</value>
+ </data>
+ <data name="TraceCodePeerNeighborNotAccepted" xml:space="preserve">
+ <value>A Peer Neighbor was not accepted.</value>
+ </data>
+ <data name="TraceCodePeerNeighborNotFound" xml:space="preserve">
+ <value>A Peer Neighbor was not found.</value>
+ </data>
+ <data name="TraceCodePeerNeighborOpenFailed" xml:space="preserve">
+ <value>A Peer Neighbor open has failed.</value>
+ </data>
+ <data name="TraceCodePeerNeighborStateChangeFailed" xml:space="preserve">
+ <value>A Peer Neighbor state change has failed.</value>
+ </data>
+ <data name="TraceCodePeerNeighborStateChanged" xml:space="preserve">
+ <value>A Peer Neighbor state has changed.</value>
+ </data>
+ <data name="TraceCodePeerNodeAddressChanged" xml:space="preserve">
+ <value>A PeerNode address has changed.</value>
+ </data>
+ <data name="TraceCodePeerNodeAuthenticationFailure" xml:space="preserve">
+ <value>A neighbor connection could not be established due to insufficient or wrong credentials.</value>
+ </data>
+ <data name="TraceCodePeerNodeAuthenticationTimeout" xml:space="preserve">
+ <value>A neighbor security handshake as timed out.</value>
+ </data>
+ <data name="TraceCodePeerNodeClosed" xml:space="preserve">
+ <value>A PeerNode was closed.</value>
+ </data>
+ <data name="TraceCodePeerNodeClosing" xml:space="preserve">
+ <value>A PeerNode is closing.</value>
+ </data>
+ <data name="TraceCodePeerNodeOpenFailed" xml:space="preserve">
+ <value>Peer node open failed.</value>
+ </data>
+ <data name="TraceCodePeerNodeOpened" xml:space="preserve">
+ <value>A PeerNode was opened.</value>
+ </data>
+ <data name="TraceCodePeerNodeOpening" xml:space="preserve">
+ <value>A PeerNode is opening.</value>
+ </data>
+ <data name="TraceCodePeerReceiveMessageAuthenticationFailure" xml:space="preserve">
+ <value>Message source could not be authenticated.</value>
+ </data>
+ <data name="TraceCodePeerServiceOpened" xml:space="preserve">
+ <value>PeerService Opened and listening at '{0}'.</value>
+ </data>
+ <data name="TraceCodePerformanceCounterFailedToLoad" xml:space="preserve">
+ <value>A performance counter failed to load. Some performance counters will not be available.</value>
+ </data>
+ <data name="TraceCodePerformanceCountersFailed" xml:space="preserve">
+ <value>Failed to load the performance counter '{0}'. Some performance counters will not be available</value>
+ </data>
+ <data name="TraceCodePerformanceCountersFailedDuringUpdate" xml:space="preserve">
+ <value>There was an error while updating the performance counter '{0}'. This performance counter will be disabled.</value>
+ </data>
+ <data name="TraceCodePerformanceCountersFailedForService" xml:space="preserve">
+ <value>Loading performance counters for the service failed. Performance counters will not be available for this service.</value>
+ </data>
+ <data name="TraceCodePerformanceCountersFailedOnRelease" xml:space="preserve">
+ <value>Unloading the performance counters failed.</value>
+ </data>
+ <data name="TraceCodePnrpRegisteredAddresses" xml:space="preserve">
+ <value>Registered addresses in PNRP.</value>
+ </data>
+ <data name="TraceCodePnrpResolvedAddresses" xml:space="preserve">
+ <value>Resolved addresses in PNRP.</value>
+ </data>
+ <data name="TraceCodePnrpResolveException" xml:space="preserve">
+ <value>Unexpected Exception during PNRP resolve operation.</value>
+ </data>
+ <data name="TraceCodePnrpUnregisteredAddresses" xml:space="preserve">
+ <value>Unregistered addresses in PNRP.</value>
+ </data>
+ <data name="TraceCodePrematureDatagramEof" xml:space="preserve">
+ <value>A null Message (signalling end of channel) was received from a datagram channel, but the channel is still in the Opened state. This indicates a bug in the datagram channel, and the demuxer receive loop has been prematurely stalled. </value>
+ </data>
+ <data name="TraceCodePeerMaintainerActivity" xml:space="preserve">
+ <value>PeerMaintainer Activity.</value>
+ </data>
+ <data name="TraceCodeReliableChannelOpened" xml:space="preserve">
+ <value>A reliable channel has been opened.</value>
+ </data>
+ <data name="TraceCodeRemoveBehavior" xml:space="preserve">
+ <value>Behavior type already exists in the collection</value>
+ </data>
+ <data name="TraceCodeRequestChannelReplyReceived" xml:space="preserve">
+ <value>Received reply over request channel</value>
+ </data>
+ <data name="TraceCodeSecurity" xml:space="preserve">
+ <value>A failure occured while performing a security related operation.</value>
+ </data>
+ <data name="TraceCodeSecurityActiveServerSessionRemoved" xml:space="preserve">
+ <value>An active security session was removed by the server.</value>
+ </data>
+ <data name="TraceCodeSecurityAuditWrittenFailure" xml:space="preserve">
+ <value>A failure occurred while writing to the security audit log.</value>
+ </data>
+ <data name="TraceCodeSecurityAuditWrittenSuccess" xml:space="preserve">
+ <value>The security audit log is written successfully.</value>
+ </data>
+ <data name="TraceCodeSecurityBindingIncomingMessageVerified" xml:space="preserve">
+ <value>The security protocol verified the incoming message.</value>
+ </data>
+ <data name="TraceCodeSecurityBindingOutgoingMessageSecured" xml:space="preserve">
+ <value>The security protocol secured the outgoing message.</value>
+ </data>
+ <data name="TraceCodeSecurityBindingSecureOutgoingMessageFailure" xml:space="preserve">
+ <value>The security protocol cannot secure the outgoing message.</value>
+ </data>
+ <data name="TraceCodeSecurityBindingVerifyIncomingMessageFailure" xml:space="preserve">
+ <value>The security protocol cannot verify the incoming message.</value>
+ </data>
+ <data name="TraceCodeSecurityClientSessionKeyRenewed" xml:space="preserve">
+ <value>The client security session renewed the session key.</value>
+ </data>
+ <data name="TraceCodeSecurityClientSessionCloseSent" xml:space="preserve">
+ <value>A Close message was sent by the client security session.</value>
+ </data>
+ <data name="TraceCodeSecurityClientSessionCloseResponseSent" xml:space="preserve">
+ <value>Close response message was sent by client security session.</value>
+ </data>
+ <data name="TraceCodeSecurityClientSessionCloseMessageReceived" xml:space="preserve">
+ <value>Close message was received by client security session.TraceCodeSecurityClientSessionKeyRenewed=Client security session renewed session key.</value>
+ </data>
+ <data name="TraceCodeSecurityClientSessionPreviousKeyDiscarded" xml:space="preserve">
+ <value>The client security session discarded the previous session key.</value>
+ </data>
+ <data name="TraceCodeSecurityContextTokenCacheFull" xml:space="preserve">
+ <value>The SecurityContextSecurityToken cache is full.</value>
+ </data>
+ <data name="TraceCodeSecurityIdentityDeterminationFailure" xml:space="preserve">
+ <value>Identity cannot be determined for an EndpointReference.</value>
+ </data>
+ <data name="TraceCodeSecurityIdentityDeterminationSuccess" xml:space="preserve">
+ <value>Identity was determined for an EndpointReference.</value>
+ </data>
+ <data name="TraceCodeSecurityIdentityHostNameNormalizationFailure" xml:space="preserve">
+ <value>The HostName portion of an endpoint address cannot be normalized.</value>
+ </data>
+ <data name="TraceCodeSecurityIdentityVerificationFailure" xml:space="preserve">
+ <value>Identity verification failed.</value>
+ </data>
+ <data name="TraceCodeSecurityIdentityVerificationSuccess" xml:space="preserve">
+ <value>Identity verification succeeded.</value>
+ </data>
+ <data name="TraceCodeSecurityImpersonationFailure" xml:space="preserve">
+ <value>Security impersonation failed at the server.</value>
+ </data>
+ <data name="TraceCodeSecurityImpersonationSuccess" xml:space="preserve">
+ <value>Security Impersonation succeeded at the server.</value>
+ </data>
+ <data name="TraceCodeSecurityInactiveSessionFaulted" xml:space="preserve">
+ <value>An inactive security session was faulted by the server.</value>
+ </data>
+ <data name="TraceCodeSecurityNegotiationProcessingFailure" xml:space="preserve">
+ <value>Service security negotiation processing failure.</value>
+ </data>
+ <data name="TraceCodeSecurityNewServerSessionKeyIssued" xml:space="preserve">
+ <value>A new security session key was issued by the server.</value>
+ </data>
+ <data name="TraceCodeSecurityPendingServerSessionAdded" xml:space="preserve">
+ <value>A pending security session was added to the server.</value>
+ </data>
+ <data name="TraceCodeSecurityPendingServerSessionClosed" xml:space="preserve">
+ <value>The pending security session was closed by the server.</value>
+ </data>
+ <data name="TraceCodeSecurityPendingServerSessionActivated" xml:space="preserve">
+ <value>A pending security session was activated by the server.</value>
+ </data>
+ <data name="TraceCodeSecurityServerSessionCloseReceived" xml:space="preserve">
+ <value>The server security session received a close message from the client.</value>
+ </data>
+ <data name="TraceCodeSecurityServerSessionCloseResponseReceived" xml:space="preserve">
+ <value>Server security session received Close response message from client.</value>
+ </data>
+ <data name="TraceCodeSecurityServerSessionAbortedFaultSent" xml:space="preserve">
+ <value>Server security session sent session aborted fault to client.</value>
+ </data>
+ <data name="TraceCodeSecurityServerSessionKeyUpdated" xml:space="preserve">
+ <value>The security session key was updated by the server.</value>
+ </data>
+ <data name="TraceCodeSecurityServerSessionRenewalFaultSent" xml:space="preserve">
+ <value>The server security session sent a key renewal fault to the client.</value>
+ </data>
+ <data name="TraceCodeSecuritySessionCloseResponseSent" xml:space="preserve">
+ <value>The server security session sent a close response to the client.</value>
+ </data>
+ <data name="TraceCodeSecuritySessionServerCloseSent" xml:space="preserve">
+ <value>Server security session sent Close to client.</value>
+ </data>
+ <data name="TraceCodeSecuritySessionAbortedFaultReceived" xml:space="preserve">
+ <value>Client security session received session aborted fault from server.</value>
+ </data>
+ <data name="TraceCodeSecuritySessionAbortedFaultSendFailure" xml:space="preserve">
+ <value>Failure sending security session aborted fault to client.</value>
+ </data>
+ <data name="TraceCodeSecuritySessionClosedResponseReceived" xml:space="preserve">
+ <value>The client security session received a closed reponse from the server.</value>
+ </data>
+ <data name="TraceCodeSecuritySessionClosedResponseSendFailure" xml:space="preserve">
+ <value>A failure occurred when sending a security session Close response to the client.</value>
+ </data>
+ <data name="TraceCodeSecuritySessionServerCloseSendFailure" xml:space="preserve">
+ <value>Failure sending security session Close to client.</value>
+ </data>
+ <data name="TraceCodeSecuritySessionKeyRenewalFaultReceived" xml:space="preserve">
+ <value>The client security session received a key renewal fault from the server.</value>
+ </data>
+ <data name="TraceCodeSecuritySessionRedirectApplied" xml:space="preserve">
+ <value>The client security session was redirected.</value>
+ </data>
+ <data name="TraceCodeSecuritySessionRenewFaultSendFailure" xml:space="preserve">
+ <value>A failure occurred when sending a renewal fault on the security session key to the client.</value>
+ </data>
+ <data name="TraceCodeSecuritySessionRequestorOperationFailure" xml:space="preserve">
+ <value>The client security session operation failed.</value>
+ </data>
+ <data name="TraceCodeSecuritySessionRequestorOperationSuccess" xml:space="preserve">
+ <value>The security session operation completed successfully at the client.</value>
+ </data>
+ <data name="TraceCodeSecuritySessionRequestorStartOperation" xml:space="preserve">
+ <value>A security session operation was started at the client.</value>
+ </data>
+ <data name="TraceCodeSecuritySessionResponderOperationFailure" xml:space="preserve">
+ <value>The security session operation failed at the server.</value>
+ </data>
+ <data name="TraceCodeSecuritySpnToSidMappingFailure" xml:space="preserve">
+ <value>The ServicePrincipalName could not be mapped to a SecurityIdentifier.</value>
+ </data>
+ <data name="TraceCodeSecurityTokenAuthenticatorClosed" xml:space="preserve">
+ <value>Security Token Authenticator was closed.</value>
+ </data>
+ <data name="TraceCodeSecurityTokenAuthenticatorOpened" xml:space="preserve">
+ <value>Security Token Authenticator was opened.</value>
+ </data>
+ <data name="TraceCodeSecurityTokenProviderClosed" xml:space="preserve">
+ <value>Security Token Provider was closed.</value>
+ </data>
+ <data name="TraceCodeSecurityTokenProviderOpened" xml:space="preserve">
+ <value>Security Token Provider was opened.</value>
+ </data>
+ <data name="TraceCodeServiceChannelLifetime" xml:space="preserve">
+ <value>ServiceChannel information.</value>
+ </data>
+ <data name="TraceCodeServiceHostBaseAddresses" xml:space="preserve">
+ <value>ServiceHost base addresses.</value>
+ </data>
+ <data name="TraceCodeServiceHostTimeoutOnClose" xml:space="preserve">
+ <value>ServiceHost close operation timedout.</value>
+ </data>
+ <data name="TraceCodeServiceHostFaulted" xml:space="preserve">
+ <value>ServiceHost faulted.</value>
+ </data>
+ <data name="TraceCodeServiceHostErrorOnReleasePerformanceCounter" xml:space="preserve">
+ <value>ServiceHost error on calling ReleasePerformanceCounters.</value>
+ </data>
+ <data name="TraceCodeServiceThrottleLimitReached" xml:space="preserve">
+ <value>The system hit the limit set for throttle '{0}'. Limit for this throttle was set to {1}. Throttle value can be changed by modifying attribute '{2}' in serviceThrottle element or by modifying '{0}' property on behavior ServiceThrottlingBehavior.</value>
+ </data>
+ <data name="TraceCodeServiceThrottleLimitReachedInternal" xml:space="preserve">
+ <value>The system hit an internal throttle limit. Limit for this throttle was set to {0}. This throttle cannot be configured.</value>
+ </data>
+ <data name="TraceCodeManualFlowThrottleLimitReached" xml:space="preserve">
+ <value>The system hit the limit set for the '{0}' throttle. Throttle value can be changed by modifying {0} property on {1}.</value>
+ </data>
+ <data name="TraceCodeProcessMessage2Paused" xml:space="preserve">
+ <value>Switched threads while processing a message for Contract '{0}' at Address '{1}'. ConcurrencyMode for service is set to Single/Reentrant and the service is currently processing another message.</value>
+ </data>
+ <data name="TraceCodeProcessMessage3Paused" xml:space="preserve">
+ <value>Switched threads while processing a message for Contract '{0}' at Address '{1}'. Cannot process more than one transaction at a time and the transaction associated with the previous message is not yet complete. Ensure that the caller has committed the transaction.</value>
+ </data>
+ <data name="TraceCodeProcessMessage31Paused" xml:space="preserve">
+ <value>Switched threads while processing a message for Contract '{0}' at Address '{1}'. Waiting for the completion of ReceiveContext acknowledgement. If your service seems to be not processing the message ensure that the channel implementation of receive context completes the operation.</value>
+ </data>
+ <data name="TraceCodeProcessMessage4Paused" xml:space="preserve">
+ <value>Switched threads while processing a message for Contract '{0}' at Address '{1}'. UseSynchronizationContext property on ServiceBehaviorAttribute is set to true, and SynchronizationContext.Current was non-null when opening ServiceHost. If your service seems to be not processing messages, consider setting UseSynchronizationContext to false.</value>
+ </data>
+ <data name="TraceCodeServiceOperationExceptionOnReply" xml:space="preserve">
+ <value>Replying to an operation threw a exception.</value>
+ </data>
+ <data name="TraceCodeServiceOperationMissingReply" xml:space="preserve">
+ <value>The Request/Reply operation {0} has no Reply Message.</value>
+ </data>
+ <data name="TraceCodeServiceOperationMissingReplyContext" xml:space="preserve">
+ <value>The Request/Reply operation {0} has no IRequestContext to use for the reply.</value>
+ </data>
+ <data name="TraceCodeServiceSecurityNegotiationCompleted" xml:space="preserve">
+ <value>Service security negotiation completed.</value>
+ </data>
+ <data name="TraceCodeSecuritySessionDemuxFailure" xml:space="preserve">
+ <value>The incoming message is not part of an existing security session.</value>
+ </data>
+ <data name="TraceCodeServiceHostCreation" xml:space="preserve">
+ <value>Create ServiceHost.</value>
+ </data>
+ <data name="TraceCodePortSharingClosed" xml:space="preserve">
+ <value>The TransportManager was successfully closed.</value>
+ </data>
+ <data name="TraceCodePortSharingDuplicatedPipe" xml:space="preserve">
+ <value>A named pipe was successfully duplicated.</value>
+ </data>
+ <data name="TraceCodePortSharingDuplicatedSocket" xml:space="preserve">
+ <value>A socket was successfully duplicated.</value>
+ </data>
+ <data name="TraceCodePortSharingDupHandleGranted" xml:space="preserve">
+ <value>The PROCESS_DUP_HANDLE access right has been granted to the {0} service's account with SID '{1}'.</value>
+ </data>
+ <data name="TraceCodePortSharingListening" xml:space="preserve">
+ <value>The TransportManager is now successfully listening.</value>
+ </data>
+ <data name="TraceCodeSkipBehavior" xml:space="preserve">
+ <value>Behavior type is not of expected type</value>
+ </data>
+ <data name="TraceCodeFailedAcceptFromPool" xml:space="preserve">
+ <value>An attempt to reuse a pooled connection failed. Another attempt will be made with {0} remaining in the overall timeout.</value>
+ </data>
+ <data name="TraceCodeFailedPipeConnect" xml:space="preserve">
+ <value>An attempt to connect to the named pipe endpoint at '{1}' failed. Another attempt will be made with {0} remaining in the overall timeout.</value>
+ </data>
+ <data name="TraceCodeSystemTimeResolution" xml:space="preserve">
+ <value>The operating system's timer resolution was detected as {0} ticks, which is about {1} milliseconds.</value>
+ </data>
+ <data name="TraceCodeRequestContextAbort" xml:space="preserve">
+ <value>RequestContext aborted</value>
+ </data>
+ <data name="TraceCodePipeConnectionAbort" xml:space="preserve">
+ <value>PipeConnection aborted</value>
+ </data>
+ <data name="TraceCodeSharedManagerServiceEndpointNotExist" xml:space="preserve">
+ <value>The shared memory for the endpoint of the service '{0}' does not exist. The service may not be started.</value>
+ </data>
+ <data name="TraceCodeSocketConnectionAbort" xml:space="preserve">
+ <value>SocketConnection aborted</value>
+ </data>
+ <data name="TraceCodeSocketConnectionAbortClose" xml:space="preserve">
+ <value>SocketConnection aborted under Close</value>
+ </data>
+ <data name="TraceCodeSocketConnectionClose" xml:space="preserve">
+ <value>SocketConnection close</value>
+ </data>
+ <data name="TraceCodeSocketConnectionCreate" xml:space="preserve">
+ <value>SocketConnection create</value>
+ </data>
+ <data name="TraceCodeSpnegoClientNegotiationCompleted" xml:space="preserve">
+ <value>SpnegoTokenProvider completed SSPI negotiation.</value>
+ </data>
+ <data name="TraceCodeSpnegoServiceNegotiationCompleted" xml:space="preserve">
+ <value>SpnegoTokenAuthenticator completed SSPI negotiation.</value>
+ </data>
+ <data name="TraceCodeSpnegoClientNegotiation" xml:space="preserve">
+ <value>Client's outgoing SSPI negotiation.</value>
+ </data>
+ <data name="TraceCodeSpnegoServiceNegotiation" xml:space="preserve">
+ <value>Service's outgoing SSPI negotiation.</value>
+ </data>
+ <data name="TraceCodeSslClientCertMissing" xml:space="preserve">
+ <value>The remote SSL client failed to provide a required certificate.</value>
+ </data>
+ <data name="TraceCodeStreamSecurityUpgradeAccepted" xml:space="preserve">
+ <value>The stream security upgrade was accepted successfully.</value>
+ </data>
+ <data name="TraceCodeTcpChannelMessageReceiveFailed" xml:space="preserve">
+ <value>Failed to receive a message over TCP channel</value>
+ </data>
+ <data name="TraceCodeTcpChannelMessageReceived" xml:space="preserve">
+ <value>Received a message over TCP channel</value>
+ </data>
+ <data name="TraceCodeUnderstoodMessageHeader" xml:space="preserve">
+ <value>Understood message header.</value>
+ </data>
+ <data name="TraceCodeUnhandledAction" xml:space="preserve">
+ <value>No service available to handle this action</value>
+ </data>
+ <data name="TraceCodeUnhandledExceptionInUserOperation" xml:space="preserve">
+ <value>Unhandled exception in user operation '{0}.{1}'.</value>
+ </data>
+ <data name="TraceCodeWebHostFailedToActivateService" xml:space="preserve">
+ <value>Webhost could not activate service</value>
+ </data>
+ <data name="TraceCodeWebHostFailedToCompile" xml:space="preserve">
+ <value>Webhost couldn't compile service</value>
+ </data>
+ <data name="TraceCodeWmiPut" xml:space="preserve">
+ <value>Setting a value via WMI.</value>
+ </data>
+ <data name="TraceCodeWsmexNonCriticalWsdlExportError" xml:space="preserve">
+ <value>A non-critical error or warning occurred during WSDL Export</value>
+ </data>
+ <data name="TraceCodeWsmexNonCriticalWsdlImportError" xml:space="preserve">
+ <value>A non-critical error or warning occurred in the MetadataExchangeClient during WSDL Import This could result in some endpoints not being imported.</value>
+ </data>
+ <data name="TraceCodeFailedToOpenIncomingChannel" xml:space="preserve">
+ <value>An incoming channel was disposed because there was an error while attempting to open it.</value>
+ </data>
+ <data name="TraceCodeTransportListen" xml:space="preserve">
+ <value>Listen at '{0}'.</value>
+ </data>
+ <data name="TraceCodeWsrmInvalidCreateSequence" xml:space="preserve">
+ <value>An invalid create sequence message was received.</value>
+ </data>
+ <data name="TraceCodeWsrmInvalidMessage" xml:space="preserve">
+ <value>An invalid WS-RM message was received.</value>
+ </data>
+ <data name="TraceCodeWsrmMaxPendingChannelsReached" xml:space="preserve">
+ <value>An incoming create sequence request was rejected because the maximum pending channel count was reached.</value>
+ </data>
+ <data name="TraceCodeWsrmMessageDropped" xml:space="preserve">
+ <value>A message in a WS-RM sequence has been dropped because it could not be buffered.</value>
+ </data>
+ <data name="TraceCodeWsrmNegativeElapsedTimeDetected" xml:space="preserve">
+ <value>The reliable session infrastructure detected a system clock change. This will temporarily result in a less optimal message retry strategy.</value>
+ </data>
+ <data name="TraceCodeWsrmReceiveAcknowledgement" xml:space="preserve">
+ <value>WS-RM SequenceAcknowledgement received.</value>
+ </data>
+ <data name="TraceCodeWsrmReceiveLastSequenceMessage" xml:space="preserve">
+ <value>WS-RM Last Sequence message received.</value>
+ </data>
+ <data name="TraceCodeWsrmReceiveSequenceMessage" xml:space="preserve">
+ <value>WS-RM Sequence message received.</value>
+ </data>
+ <data name="TraceCodeWsrmSendAcknowledgement" xml:space="preserve">
+ <value>WS-RM SequenceAcknowledgement sent.</value>
+ </data>
+ <data name="TraceCodeWsrmSendLastSequenceMessage" xml:space="preserve">
+ <value>WS-RM Last Sequence message sent.</value>
+ </data>
+ <data name="TraceCodeWsrmSendSequenceMessage" xml:space="preserve">
+ <value>WS-RM Sequence message sent.</value>
+ </data>
+ <data name="TraceCodeWsrmSequenceFaulted" xml:space="preserve">
+ <value>A WS-RM sequence has faulted.</value>
+ </data>
+ <data name="TraceCodeChannelConnectionDropped" xml:space="preserve">
+ <value>Channel connection was dropped</value>
+ </data>
+ <data name="TraceCodeAsyncCallbackThrewException" xml:space="preserve">
+ <value>An async callback threw an exception!</value>
+ </data>
+ <data name="TraceCodeMetadataExchangeClientSendRequest" xml:space="preserve">
+ <value>The MetadataExchangeClient is sending a request for metadata.</value>
+ </data>
+ <data name="TraceCodeMetadataExchangeClientReceiveReply" xml:space="preserve">
+ <value>The MetadataExchangeClient received a reply.</value>
+ </data>
+ <data name="TraceCodeWarnHelpPageEnabledNoBaseAddress" xml:space="preserve">
+ <value>The ServiceDebugBehavior Help Page is enabled at a relative address and cannot be created because there is no base address.</value>
+ </data>
+ <data name="TraceCodeTcpConnectError" xml:space="preserve">
+ <value>The TCP connect operation failed.</value>
+ </data>
+ <data name="TraceCodeTxSourceTxScopeRequiredIsTransactedTransport" xml:space="preserve">
+ <value>The transaction '{0}' was received for operation '{1}' from a transacted transport, such as MSMQ.</value>
+ </data>
+ <data name="TraceCodeTxSourceTxScopeRequiredIsTransactionFlow" xml:space="preserve">
+ <value>The transaction '{0}' was flowed to operation '{1}'.</value>
+ </data>
+ <data name="TraceCodeTxSourceTxScopeRequiredIsAttachedTransaction" xml:space="preserve">
+ <value>The transaction '{0}' was received for operation '{1}' from an InstanceContext transaction.</value>
+ </data>
+ <data name="TraceCodeTxSourceTxScopeRequiredUsingExistingTransaction" xml:space="preserve">
+ <value>Existing transaction '{0}' being used for operation '{1}'.</value>
+ </data>
+ <data name="TraceCodeTxCompletionStatusCompletedForAutocomplete" xml:space="preserve">
+ <value>The transaction '{0}' for operation '{1}' was completed due to the TransactionAutoComplete OperationBehaviorAttribute member being set to true.</value>
+ </data>
+ <data name="TraceCodeTxCompletionStatusCompletedForError" xml:space="preserve">
+ <value>The transaction '{0}' for operation '{1}' was completed due to an unhandled execution exception.</value>
+ </data>
+ <data name="TraceCodeTxCompletionStatusCompletedForSetComplete" xml:space="preserve">
+ <value>The transaction '{0}' for operation '{1}' was completed due to a call to SetTransactionComplete.</value>
+ </data>
+ <data name="TraceCodeTxCompletionStatusCompletedForTACOSC" xml:space="preserve">
+ <value>The transaction '{0}' was completed when the session was closed due to the TransactionAutoCompleteOnSessionClose ServiceBehaviorAttribute member.</value>
+ </data>
+ <data name="TraceCodeTxCompletionStatusCompletedForAsyncAbort" xml:space="preserve">
+ <value>The transaction '{0}' for operation '{1}' was completed due to asynchronous abort.</value>
+ </data>
+ <data name="TraceCodeTxCompletionStatusRemainsAttached" xml:space="preserve">
+ <value>The transaction '{0}' for operation '{1}' remains attached to the InstanceContext.</value>
+ </data>
+ <data name="TraceCodeTxCompletionStatusAbortedOnSessionClose" xml:space="preserve">
+ <value>The transaction '{0}' was aborted because it was uncompleted when the session was closed and the TransactionAutoCompleteOnSessionClose OperationBehaviorAttribute was set to false.</value>
+ </data>
+ <data name="TraceCodeTxReleaseServiceInstanceOnCompletion" xml:space="preserve">
+ <value>The service instance was released on the completion of the transaction '{0}' because the ReleaseServiceInstanceOnTransactionComplete ServiceBehaviorAttribute was set to true.</value>
+ </data>
+ <data name="TraceCodeTxAsyncAbort" xml:space="preserve">
+ <value>The transaction '{0}' was asynchronously aborted.</value>
+ </data>
+ <data name="TraceCodeTxFailedToNegotiateOleTx" xml:space="preserve">
+ <value>The OleTransactions protocol negotiation failed for coordination context '{0}'.</value>
+ </data>
+ <data name="TraceCodeTxSourceTxScopeRequiredIsCreateNewTransaction" xml:space="preserve">
+ <value>The transaction '{0}' for operation '{1}' was newly created.</value>
+ </data>
+ <data name="TraceCodeActivatingMessageReceived" xml:space="preserve">
+ <value>Activating message received.</value>
+ </data>
+ <data name="TraceCodeDICPInstanceContextCached" xml:space="preserve">
+ <value>InstanceContext cached for InstanceId {0}.</value>
+ </data>
+ <data name="TraceCodeDICPInstanceContextRemovedFromCache" xml:space="preserve">
+ <value>InstanceContext for InstanceId {0} removed from cache.</value>
+ </data>
+ <data name="TraceCodeInstanceContextBoundToDurableInstance" xml:space="preserve">
+ <value>DurableInstance's InstanceContext refcount incremented.</value>
+ </data>
+ <data name="TraceCodeInstanceContextDetachedFromDurableInstance" xml:space="preserve">
+ <value>DurableInstance's InstanceContext refcount decremented.</value>
+ </data>
+ <data name="TraceCodeContextChannelFactoryChannelCreated" xml:space="preserve">
+ <value>ContextChannel created.</value>
+ </data>
+ <data name="TraceCodeContextChannelListenerChannelAccepted" xml:space="preserve">
+ <value>A new ContextChannel was accepted.</value>
+ </data>
+ <data name="TraceCodeContextProtocolContextAddedToMessage" xml:space="preserve">
+ <value>Context added to Message.</value>
+ </data>
+ <data name="TraceCodeContextProtocolContextRetrievedFromMessage" xml:space="preserve">
+ <value>Context retrieved from Message.</value>
+ </data>
+ <data name="TraceCodeWorkflowServiceHostCreated" xml:space="preserve">
+ <value>WorkflowServiceHost created.</value>
+ </data>
+ <data name="TraceCodeServiceDurableInstanceDeleted" xml:space="preserve">
+ <value>ServiceDurableInstance '{0}' deleted from persistence store.</value>
+ </data>
+ <data name="TraceCodeServiceDurableInstanceDisposed" xml:space="preserve">
+ <value>ServiceDurableInstance '{0}' disposed.</value>
+ </data>
+ <data name="TraceCodeServiceDurableInstanceLoaded" xml:space="preserve">
+ <value>ServiceDurableInstance loaded from persistence store.</value>
+ </data>
+ <data name="TraceCodeServiceDurableInstanceSaved" xml:space="preserve">
+ <value>ServiceDurableInstance saved to persistence store.</value>
+ </data>
+ <data name="TraceCodeWorkflowDurableInstanceLoaded" xml:space="preserve">
+ <value>WorkflowDurableInstance '{0}' loaded.</value>
+ </data>
+ <data name="TraceCodeWorkflowDurableInstanceActivated" xml:space="preserve">
+ <value>WorkflowDurableInstance '{0}' activated.</value>
+ </data>
+ <data name="TraceCodeWorkflowDurableInstanceAborted" xml:space="preserve">
+ <value>WorkflowDurableInstance aborted.</value>
+ </data>
+ <data name="TraceCodeWorkflowOperationInvokerItemQueued" xml:space="preserve">
+ <value>Work item enqueued.</value>
+ </data>
+ <data name="TraceCodeWorkflowRequestContextReplySent" xml:space="preserve">
+ <value>Reply sent for InstanceId {0}.</value>
+ </data>
+ <data name="TraceCodeWorkflowRequestContextFaultSent" xml:space="preserve">
+ <value>Fault Sent for InstanceId {0}.</value>
+ </data>
+ <data name="TraceCodeSqlPersistenceProviderSQLCallStart" xml:space="preserve">
+ <value>Sql execution started.</value>
+ </data>
+ <data name="TraceCodeSqlPersistenceProviderSQLCallEnd" xml:space="preserve">
+ <value>Sql execution complete.</value>
+ </data>
+ <data name="TraceCodeSqlPersistenceProviderOpenParameters" xml:space="preserve">
+ <value>SqlPersistenceProvider.Open() parameters.</value>
+ </data>
+ <data name="TraceCodeSyncContextSchedulerServiceTimerCancelled" xml:space="preserve">
+ <value>SynchronizationContextWorkflowSchedulerService - Timer {0} cancelled.</value>
+ </data>
+ <data name="TraceCodeSyncContextSchedulerServiceTimerCreated" xml:space="preserve">
+ <value>SynchronizationContextWorkflowSchedulerService - Timer {0} created for InstanceId {1}.</value>
+ </data>
+ <data name="TraceCodeSyndicationReadFeedBegin" xml:space="preserve">
+ <value>Reading of a syndication feed started.</value>
+ </data>
+ <data name="TraceCodeSyndicationReadFeedEnd" xml:space="preserve">
+ <value>Reading of a syndication feed completed.</value>
+ </data>
+ <data name="TraceCodeSyndicationReadItemBegin" xml:space="preserve">
+ <value>Reading of a syndication item started.</value>
+ </data>
+ <data name="TraceCodeSyndicationReadItemEnd" xml:space="preserve">
+ <value>Reading of a syndication item completed.</value>
+ </data>
+ <data name="TraceCodeSyndicationWriteFeedBegin" xml:space="preserve">
+ <value>Writing of a syndication feed started.</value>
+ </data>
+ <data name="TraceCodeSyndicationWriteFeedEnd" xml:space="preserve">
+ <value>Writing of a syndication feed completed.</value>
+ </data>
+ <data name="TraceCodeSyndicationWriteItemBegin" xml:space="preserve">
+ <value>Writing of a syndication item started.</value>
+ </data>
+ <data name="TraceCodeSyndicationWriteItemEnd" xml:space="preserve">
+ <value>Writing of a syndication item completed.</value>
+ </data>
+ <data name="TraceCodeSyndicationProtocolElementIgnoredOnWrite" xml:space="preserve">
+ <value>Syndication element with name '{0}' and namespace '{1}' was not written.</value>
+ </data>
+ <data name="TraceCodeSyndicationProtocolElementInvalid" xml:space="preserve">
+ <value>Syndication element with name '{0}' and namespace '{1}' is invalid.</value>
+ </data>
+ <data name="TraceCodeWebUnknownQueryParameterIgnored" xml:space="preserve">
+ <value>HTTP query string parameter with name '{0}' was ignored.</value>
+ </data>
+ <data name="TraceCodeWebRequestMatchesOperation" xml:space="preserve">
+ <value>Incoming HTTP request with URI '{0}' matched operation '{1}'.</value>
+ </data>
+ <data name="TraceCodeWebRequestDoesNotMatchOperations" xml:space="preserve">
+ <value>Incoming HTTP request with URI '{0}' does not match any operation.</value>
+ </data>
+ <data name="UTTMustBeAbsolute" xml:space="preserve">
+ <value>Parameter 'baseAddress' must an absolute uri.</value>
+ </data>
+ <data name="UTTBaseAddressMustBeAbsolute" xml:space="preserve">
+ <value>BaseAddress must an absolute uri.</value>
+ </data>
+ <data name="UTTCannotChangeBaseAddress" xml:space="preserve">
+ <value>Cannot change BaseAddress after calling MakeReadOnly.</value>
+ </data>
+ <data name="UTTMultipleMatches" xml:space="preserve">
+ <value>There were multiple UriTemplateMatch results, but MatchSingle was called.</value>
+ </data>
+ <data name="UTTBaseAddressNotSet" xml:space="preserve">
+ <value>BaseAddress has not been set. Set the BaseAddress property before calling MakeReadOnly, Match, or MatchSingle.</value>
+ </data>
+ <data name="UTTEmptyKeyValuePairs" xml:space="preserve">
+ <value>KeyValuePairs must have at least one element.</value>
+ </data>
+ <data name="UTBindByPositionWrongCount" xml:space="preserve">
+ <value>UriTemplate '{0}' contains {1} path variables and {2} query variables but {3} values were passed to the BindByPosition method. The number of values passed to BindByPosition should be greater than or equal to the number of path variables in the template and cannot be greater than the total number of variables in the template.</value>
+ </data>
+ <data name="UTBadBaseAddress" xml:space="preserve">
+ <value>baseAddress must an absolute Uri.</value>
+ </data>
+ <data name="UTQueryNamesMustBeUnique" xml:space="preserve">
+ <value>The UriTemplate '{0}' is not valid; each portion of the query string must be of the form 'name' or of the form 'name=value', where each name is unique. Note that the names are case-insensitive. See the documentation for UriTemplate for more details.</value>
+ </data>
+ <data name="UTQueryCannotEndInAmpersand" xml:space="preserve">
+ <value>The UriTemplate '{0}' is not valid; the query string cannot end with '&amp;amp;'. See the documentation for UriTemplate for more details.</value>
+ </data>
+ <data name="UTQueryCannotHaveEmptyName" xml:space="preserve">
+ <value>The UriTemplate '{0}' is not valid; each portion of the query string must be of the form 'name' or of the form 'name=value'. See the documentation for UriTemplate for more details.</value>
+ </data>
+ <data name="UTVarNamesMustBeUnique" xml:space="preserve">
+ <value>The UriTemplate '{0}' is not valid; the UriTemplate variable named '{1}' appears multiple times in the template. Note that UriTemplate variable names are case-insensitive. See the documentation for UriTemplate for more details.</value>
+ </data>
+ <data name="UTTAmbiguousQueries" xml:space="preserve">
+ <value>UriTemplateTable does not support '{0}' and '{1}' since they are not equivalent, but cannot be disambiguated because they have equivalent paths and the same common literal values for the query string. See the documentation for UriTemplateTable for more detail.</value>
+ </data>
+ <data name="UTTOtherAmbiguousQueries" xml:space="preserve">
+ <value>UriTemplateTable does not support multiple templates that have equivalent path as template '{0}' but have different query strings, where the query strings cannot all be disambiguated via literal values. See the documentation for UriTemplateTable for more detail.</value>
+ </data>
+ <data name="UTTDuplicate" xml:space="preserve">
+ <value>UriTemplateTable (with allowDuplicateEquivalentUriTemplates = false) does not support both '{0}' and '{1}', since they are equivalent. Call MakeReadOnly with allowDuplicateEquivalentUriTemplates = true to use both of these UriTemplates in the same table. See the documentation for UriTemplateTable for more detail.</value>
+ </data>
+ <data name="UTInvalidFormatSegmentOrQueryPart" xml:space="preserve">
+ <value>UriTemplate does not support '{0}' as a valid format for a segment or a query part.</value>
+ </data>
+ <data name="BindUriTemplateToNullOrEmptyPathParam" xml:space="preserve">
+ <value>The path variable '{0}' in the UriTemplate must be bound to a non-empty string value.</value>
+ </data>
+ <data name="UTBindByPositionNoVariables" xml:space="preserve">
+ <value>UriTemplate '{0}' contains no variables; yet the BindByPosition method was called with {1} values.</value>
+ </data>
+ <data name="UTCSRLookupBeforeMatch" xml:space="preserve">
+ <value>UTCSR - Lookup was called before match</value>
+ </data>
+ <data name="UTDoesNotSupportAdjacentVarsInCompoundSegment" xml:space="preserve">
+ <value>The UriTemplate '{0}' is not valid; UriTemplate does not support two adjacent variables with no literal in compound segments, such as in the segment '{1}'.</value>
+ </data>
+ <data name="UTQueryCannotHaveCompoundValue" xml:space="preserve">
+ <value>The UriTemplate '{0}' is not valid; each portion of the query string must be of the form 'name=value', when value cannot be a compound segment. See the documentation for UriTemplate for more details.</value>
+ </data>
+ <data name="UTQueryMustHaveLiteralNames" xml:space="preserve">
+ <value>The UriTemplate '{0}' is not valid; each portion of the query string must be of the form 'name' or of the form 'name=value', where name is a simple literal. See the documentation for UriTemplate for more details.</value>
+ </data>
+ <data name="UTAdditionalDefaultIsInvalid" xml:space="preserve">
+ <value>Changing an inline default value with information from the additional default values is not supported; the default value to the variable '{0}' was already provided as part of the UriTemplate '{1}'. See the documentation for UriTemplate for more details.</value>
+ </data>
+ <data name="UTDefaultValuesAreImmutable" xml:space="preserve">
+ <value>The default values of UriTemplate are immutable; they cannot be modified after the construction of the UriTemplate instance. See the documentation of UriTemplate for more details.</value>
+ </data>
+ <data name="UTDefaultValueToCompoundSegmentVar" xml:space="preserve">
+ <value>The UriTemplate '{0}' is not valid; the UriTemplate compound path segment '{1}' provides a default value to variable '{2}'. Note that UriTemplate doesn't support default values to variables in compound segments. See the documentation for UriTemplate for more details.</value>
+ </data>
+ <data name="UTDefaultValueToQueryVar" xml:space="preserve">
+ <value>The UriTemplate '{0}' is not valid; the UriTemplate variable declaration '{1}' provides a default value to query variable '{2}'. Note that UriTemplate doesn't support default values to query variables. See the documentation for UriTemplate for more details.</value>
+ </data>
+ <data name="UTInvalidDefaultPathValue" xml:space="preserve">
+ <value>The UriTemplate '{0}' is not valid; the UriTemplate variable declaration '{1}' provides an empty default value to path variable '{2}'. Note that UriTemplate path variables cannot be bound to a null or empty value. See the documentation for UriTemplate for more details.</value>
+ </data>
+ <data name="UTInvalidVarDeclaration" xml:space="preserve">
+ <value>The UriTemplate '{0}' is not valid; the UriTemplate variable declaration '{1}' isn't a valid variable construct. Note that UriTemplate variable definitions are either a simple, non-empty, variable name or a 'name=value' format, where the name must not be empty and the value provides a default value to the variable. See the documentation for UriTemplate for more details.</value>
+ </data>
+ <data name="UTInvalidWildcardInVariableOrLiteral" xml:space="preserve">
+ <value>The UriTemplate '{0}' is not valid; the wildcard ('{1}') cannot appear in a variable name or literal, unless as a construct for a wildcard segment. Note that a wildcard segment, either a literal or a variable, is valid only as the last path segment in the template; the wildcard can appear only once. See the documentation for UriTemplate for more details.</value>
+ </data>
+ <data name="UTStarVariableWithDefaults" xml:space="preserve">
+ <value>The UriTemplate '{0}' is not valid; the UriTemplate last path segment '{1}' provides a default value to final star variable '{2}'. Note that UriTemplate doesn't support default values to final star variable. See the documentation for UriTemplate for more details.</value>
+ </data>
+ <data name="UTDefaultValueToCompoundSegmentVarFromAdditionalDefaults" xml:space="preserve">
+ <value>The UriTemplate '{0}' is not valid; the path variable '{1}', defined as part of a compound path segment has been provided with a default value as part of the additional defaults. Note that UriTemplate doesn't support default values to variables in compound segments. See the documentation for UriTemplate for more details.</value>
+ </data>
+ <data name="UTDefaultValueToQueryVarFromAdditionalDefaults" xml:space="preserve">
+ <value>The UriTemplate '{0}' is not valid; the query variable '{1}' has been provided a default value as part of the additional defaults. Note that UriTemplate doesn't support default values to query variables. See the documentation for UriTemplate for more details.</value>
+ </data>
+ <data name="UTNullableDefaultAtAdditionalDefaults" xml:space="preserve">
+ <value>The UriTemplate '{0}' is not valid; the additional default value '{1}' has a null value as default value. Note that null default values must be only provided to concrete path variables. See the documentation for UriTemplate for more details.</value>
+ </data>
+ <data name="UTNullableDefaultMustBeFollowedWithNullables" xml:space="preserve">
+ <value>The UriTemplate '{0}' is not valid; the UriTemplate path variable '{1}' has a null default value while following path variable '{2}' has no defaults or provides a non-null default value. Note that UriTemplate path variable with null default value must be followed only with other path variables with null defaulted values. See the documentation for UriTemplate for more details.</value>
+ </data>
+ <data name="UTNullableDefaultMustNotBeFollowedWithLiteral" xml:space="preserve">
+ <value>The UriTemplate '{0}' is not valid; the UriTemplate path variable '{1}' has a null default value while the following path segment '{2}' is not a variable segment with a null default value. Note that UriTemplate path variable with null default values must be followed only with other path variables with null defaulted value. See the documentation for UriTemplate for more details.</value>
+ </data>
+ <data name="UTNullableDefaultMustNotBeFollowedWithWildcard" xml:space="preserve">
+ <value>The UriTemplate '{0}' is not valid; the UriTemplate path variable '{1}' has a null default value while the template is finished with a wildcard. Note that UriTemplate path variable with null default values must be followed only with other path variables with null defaulted value. See the documentation for UriTemplate for more details.</value>
+ </data>
+ <data name="UTStarVariableWithDefaultsFromAdditionalDefaults" xml:space="preserve">
+ <value>The UriTemplate '{0}' is not valid; the UriTemplate final star variable '{1}' has been provides a default value as part of the additional defaults information. Note that UriTemplate doesn't support default values to final star variable. See the documentation for UriTemplate for more details.</value>
+ </data>
+ <data name="UTTInvalidTemplateKey" xml:space="preserve">
+ <value>An invalid template '{0}' was passed as the key in a pair of template and its associated object. UriTemplateTable Key-Value pairs must always contain a valid UriTemplate object as key; note that UriTemplateTable doesn't support templates that are ignoring the trailing slash in respect to matching. See the documentation for UriTemplateTable for more details.</value>
+ </data>
+ <data name="UTTNullTemplateKey" xml:space="preserve">
+ <value>A null UriTemplate was passed as the key in a pair of template and its associated object. UriTemplateTable Key-Value pairs must always contain a valid UriTemplate object as key. See the documentation for UriTemplateTable for more details.</value>
+ </data>
+ <data name="UTBindByNameCalledWithEmptyKey" xml:space="preserve">
+ <value>The BindByName method of UriTemplate was called with an empty name in the collection of arguments for the bind. Note that the NameValueCollection or the Dictionary passed to BindByName cannot contain an empty (or null) name as a key. See the documentation of UriTemplate for more details.</value>
+ </data>
+ <data name="UTBothLiteralAndNameValueCollectionKey" xml:space="preserve">
+ <value>The UriTemplate contains a literal value for query key '{0}', but that key also is present in the NameValueCollection. Either remove that key from the NameValueCollection, or else change the UriTemplate to not have a query literal for that key.</value>
+ </data>
+ <data name="ExtensionNameNotSpecified" xml:space="preserve">
+ <value>The name of the extension element must be specified.</value>
+ </data>
+ <data name="UnsupportedRssVersion" xml:space="preserve">
+ <value>The Rss20Serializer does not support RSS version '{0}'.</value>
+ </data>
+ <data name="Atom10SpecRequiresTextConstruct" xml:space="preserve">
+ <value>The Atom10 specification requires '{0}' to have one of these values: "text", "html", "xhtml", however this value is '{1}' in the document being deserialized.</value>
+ </data>
+ <data name="ErrorInLine" xml:space="preserve">
+ <value>Error in line {0} position {1}.</value>
+ </data>
+ <data name="ErrorParsingFeed" xml:space="preserve">
+ <value>An error was encountered when parsing the feed's XML. Refer to the inner exception for more details.</value>
+ </data>
+ <data name="ErrorParsingDocument" xml:space="preserve">
+ <value>An error was encountered when parsing the document's XML. Refer to the inner exception for more details.</value>
+ </data>
+ <data name="ErrorParsingItem" xml:space="preserve">
+ <value>An error was encountered when parsing the item's XML. Refer to the inner exception for more details.</value>
+ </data>
+ <data name="ErrorParsingDateTime" xml:space="preserve">
+ <value>An error was encountered when parsing a DateTime value in the XML.</value>
+ </data>
+ <data name="OuterElementNameNotSpecified" xml:space="preserve">
+ <value>The outer element name must be specified.</value>
+ </data>
+ <data name="UnknownFeedXml" xml:space="preserve">
+ <value>The element with name '{0}' and namespace '{1}' is not an allowed feed format.</value>
+ </data>
+ <data name="UnknownDocumentXml" xml:space="preserve">
+ <value>The element with name '{0}' and namespace '{1}' is not an allowed document format.</value>
+ </data>
+ <data name="UnknownItemXml" xml:space="preserve">
+ <value>The element with name '{0}' and namespace '{1}' is not an allowed item format.</value>
+ </data>
+ <data name="FeedFormatterDoesNotHaveFeed" xml:space="preserve">
+ <value>The syndication feed formatter must be configured with a syndication feed.</value>
+ </data>
+ <data name="DocumentFormatterDoesNotHaveDocument" xml:space="preserve">
+ <value>The document formatter must be configured with a document.</value>
+ </data>
+ <data name="ItemFormatterDoesNotHaveItem" xml:space="preserve">
+ <value>The syndication item formatter must be configured with a syndication item.</value>
+ </data>
+ <data name="UnbufferedItemsCannotBeCloned" xml:space="preserve">
+ <value>A feed containing items that are not buffered (i.e. the items are not stored in an IList) cannot clone its items. Buffer the items in the feed before calling Clone on it or pass false to the Clone method.</value>
+ </data>
+ <data name="FeedHasNonContiguousItems" xml:space="preserve">
+ <value>The feed being deserialized has non-contiguous sets of items in it. This is not supported by '{0}'.</value>
+ </data>
+ <data name="FeedCreatedNullCategory" xml:space="preserve">
+ <value>The feed created a null category.</value>
+ </data>
+ <data name="ItemCreatedNullCategory" xml:space="preserve">
+ <value>The item created a null category.</value>
+ </data>
+ <data name="FeedCreatedNullPerson" xml:space="preserve">
+ <value>The feed created a null person.</value>
+ </data>
+ <data name="ItemCreatedNullPerson" xml:space="preserve">
+ <value>The item created a null person.</value>
+ </data>
+ <data name="FeedCreatedNullItem" xml:space="preserve">
+ <value>=The feed created a null item.</value>
+ </data>
+ <data name="TraceCodeSyndicationFeedReadBegin" xml:space="preserve">
+ <value>Reading of a syndication feed started.</value>
+ </data>
+ <data name="TraceCodeSyndicationFeedReadEnd" xml:space="preserve">
+ <value>Reading of a syndication feed completed.</value>
+ </data>
+ <data name="TraceCodeSyndicationItemReadBegin" xml:space="preserve">
+ <value>Reading of a syndication item started.</value>
+ </data>
+ <data name="TraceCodeSyndicationItemReadEnd" xml:space="preserve">
+ <value>Reading of a syndication item completed.</value>
+ </data>
+ <data name="TraceCodeSyndicationFeedWriteBegin" xml:space="preserve">
+ <value>Writing of a syndication feed started.</value>
+ </data>
+ <data name="TraceCodeSyndicationFeedWriteEnd" xml:space="preserve">
+ <value>Writing of a syndication feed completed.</value>
+ </data>
+ <data name="TraceCodeSyndicationItemWriteBegin" xml:space="preserve">
+ <value>Writing of a syndication item started.</value>
+ </data>
+ <data name="TraceCodeSyndicationItemWriteEnd" xml:space="preserve">
+ <value>Writing of a syndication item completed.</value>
+ </data>
+ <data name="TraceCodeSyndicationProtocolElementIgnoredOnRead" xml:space="preserve">
+ <value>Syndication XML node of type '{0}' with name '{1}' and namespace '{2}' ignored on read.</value>
+ </data>
+ <data name="TraceCodeSyndicationReadServiceDocumentBegin" xml:space="preserve">
+ <value>Reading of a service document started.</value>
+ </data>
+ <data name="TraceCodeSyndicationReadServiceDocumentEnd" xml:space="preserve">
+ <value>Reading of a service document completed.</value>
+ </data>
+ <data name="TraceCodeSyndicationWriteServiceDocumentBegin" xml:space="preserve">
+ <value>Writing of a service document started.</value>
+ </data>
+ <data name="TraceCodeSyndicationWriteServiceDocumentEnd" xml:space="preserve">
+ <value>Writing of a service document completed.</value>
+ </data>
+ <data name="TraceCodeSyndicationReadCategoriesDocumentBegin" xml:space="preserve">
+ <value>Reading of a categories document started.</value>
+ </data>
+ <data name="TraceCodeSyndicationReadCategoriesDocumentEnd" xml:space="preserve">
+ <value>Reading of a categories document completed.</value>
+ </data>
+ <data name="TraceCodeSyndicationWriteCategoriesDocumentBegin" xml:space="preserve">
+ <value>Writing of a categories document started.</value>
+ </data>
+ <data name="TraceCodeSyndicationWriteCategoriesDocumentEnd" xml:space="preserve">
+ <value>Writing of a categories document completed.</value>
+ </data>
+ <data name="FeedAuthorsIgnoredOnWrite" xml:space="preserve">
+ <value>The feed's authors were not serialized as part of serializing the feed in RSS 2.0 format.</value>
+ </data>
+ <data name="FeedContributorsIgnoredOnWrite" xml:space="preserve">
+ <value>The feed's contributors were not serialized as part of serializing the feed in RSS 2.0 format.</value>
+ </data>
+ <data name="FeedIdIgnoredOnWrite" xml:space="preserve">
+ <value>The feed's id was not serialized as part of serializing the feed in RSS 2.0 format.</value>
+ </data>
+ <data name="FeedLinksIgnoredOnWrite" xml:space="preserve">
+ <value>The feed's links were not serialized as part of serializing the feed in RSS 2.0 format.</value>
+ </data>
+ <data name="ItemAuthorsIgnoredOnWrite" xml:space="preserve">
+ <value>The item's authors were not serialized as part of serializing the feed in RSS 2.0 format.</value>
+ </data>
+ <data name="ItemContributorsIgnoredOnWrite" xml:space="preserve">
+ <value>The item's contributors were not serialized as part of serializing the feed in RSS 2.0 format.</value>
+ </data>
+ <data name="ItemLinksIgnoredOnWrite" xml:space="preserve">
+ <value>The item's links were not serialized as part of serializing the feed in RSS 2.0 format.</value>
+ </data>
+ <data name="ItemCopyrightIgnoredOnWrite" xml:space="preserve">
+ <value>The item's copyrights were not serialized as part of serializing the feed in RSS 2.0 format.</value>
+ </data>
+ <data name="ItemContentIgnoredOnWrite" xml:space="preserve">
+ <value>The item's content was not serialized as part of serializing the feed in RSS 2.0 format.</value>
+ </data>
+ <data name="ItemLastUpdatedTimeIgnoredOnWrite" xml:space="preserve">
+ <value>The item's last updated time was not serialized as part of serializing the feed in RSS 2.0 format.</value>
+ </data>
+ <data name="OuterNameOfElementExtensionEmpty" xml:space="preserve">
+ <value>The outer name of the element extension cannot be empty.</value>
+ </data>
+ <data name="InvalidObjectTypePassed" xml:space="preserve">
+ <value>The Type of object passed as parameter '{0}' is not derived from {1}. Ensure that the type of object passed is either of type {1} or derived from {1}.</value>
+ </data>
+ <data name="UnableToImpersonateWhileSerializingReponse" xml:space="preserve">
+ <value>Failed to impersonate client identity during serialization of the response message.</value>
+ </data>
+ <data name="XmlLineInfo" xml:space="preserve">
+ <value>Line {0}, position {1}.</value>
+ </data>
+ <data name="XmlFoundEndOfFile" xml:space="preserve">
+ <value>end of file</value>
+ </data>
+ <data name="XmlFoundElement" xml:space="preserve">
+ <value>element '{0}' from namespace '{1}'</value>
+ </data>
+ <data name="XmlFoundEndElement" xml:space="preserve">
+ <value>end element '{0}' from namespace '{1}'</value>
+ </data>
+ <data name="XmlFoundText" xml:space="preserve">
+ <value>text '{0}'</value>
+ </data>
+ <data name="XmlFoundCData" xml:space="preserve">
+ <value>cdata '{0}'</value>
+ </data>
+ <data name="XmlFoundComment" xml:space="preserve">
+ <value>comment '{0}'</value>
+ </data>
+ <data name="XmlFoundNodeType" xml:space="preserve">
+ <value>node {0}</value>
+ </data>
+ <data name="XmlStartElementExpected" xml:space="preserve">
+ <value>Start element expected. Found {0}.</value>
+ </data>
+ <data name="SingleWsdlNotGenerated" xml:space="preserve">
+ <value>A single WSDL document could not be generated for this service. Multiple service contract namespaces were found ({0}). Ensure that all your service contracts have the same namespace.</value>
+ </data>
+ <data name="SFxDocExt_MainPageIntroSingleWsdl" xml:space="preserve">
+ <value>You can also access the service description as a single file:</value>
+ </data>
+ <data name="TaskMethodParameterNotSupported" xml:space="preserve">
+ <value>The use of '{0}' on the task-based asynchronous method is not supported.</value>
+ </data>
+ <data name="TaskMethodMustNotHaveOutParameter" xml:space="preserve">
+ <value>Client side task-based asynchronous method must not have any out or ref parameters. Any data that would have been returned through an out or ref parameter should instead be returned as part of the TResult in the resulting task.</value>
+ </data>
+ <data name="SFxCannotImportAsParameters_OutputParameterAndTask" xml:space="preserve">
+ <value>Generating message contract since the operation has multiple return values.</value>
+ </data>
+ <data name="ID0020" xml:space="preserve">
+ <value>ID0020: The collection is empty.</value>
+ </data>
+ <data name="ID2004" xml:space="preserve">
+ <value>ID2004: IAsyncResult must be the AsyncResult instance returned from the Begin call. The runtime is expecting '{0}', and the actual type is '{1}'.</value>
+ </data>
+ <data name="ID3002" xml:space="preserve">
+ <value>ID3002: WSTrustServiceContract could not create a SecurityTokenService instance from WSTrustServiceContract.SecurityTokenServiceConfiguration.</value>
+ </data>
+ <data name="ID3004" xml:space="preserve">
+ <value>ID3004: Cannot obtain the schema for namespace: '{0}'.</value>
+ </data>
+ <data name="ID3022" xml:space="preserve">
+ <value>ID3022: The WSTrustServiceContract only supports receiving RequestSecurityToken messages. If you need to support more message types, override the WSTrustServiceContract.DispatchRequest method.</value>
+ </data>
+ <data name="ID3023" xml:space="preserve">
+ <value>ID3023: The WSTrustServiceContract only supports receiving RequestSecurityToken messages asynchronously. If you need to support more message types, override the WSTrustServiceContract.BeginDispatchRequest and EndDispatchRequest.</value>
+ </data>
+ <data name="ID3097" xml:space="preserve">
+ <value>ID3097: ServiceHost does not contain any valid Endpoints. Add at least one valid endpoint in the SecurityTokenServiceConfiguration.TrustEndpoints collection.</value>
+ </data>
+ <data name="ID3112" xml:space="preserve">
+ <value>ID3112: Unrecognized RequestType '{0}' specified in the incoming request.</value>
+ </data>
+ <data name="ID3113" xml:space="preserve">
+ <value>ID3113: The WSTrustServiceContract does not support receiving '{0}' messages with the '{1}' SOAP action. If you need to support this, override the ValidateDispatchContext method.</value>
+ </data>
+ <data name="ID3114" xml:space="preserve">
+ <value>ID3114: The WSTrustServiceContract cannot deserialize the WS-Trust request.</value>
+ </data>
+ <data name="ID3137" xml:space="preserve">
+ <value>ID3137: The TrustVersion '{0}', is not supported, only 'TrustVersion.WSTrust13' and 'TrustVersion.WSTrustFeb2005' is supported.</value>
+ </data>
+ <data name="ID3138" xml:space="preserve">
+ <value>ID3138: The RequestSecurityTokenResponse that was received did not contain a SecurityToken.</value>
+ </data>
+ <data name="ID3139" xml:space="preserve">
+ <value>ID3139: The WSTrustChannel cannot compute a proof key. The KeyType '{0}' is not supported. Valid proof key types supported by the WSTrustChannel are WSTrust13 and WSTrustFeb2005.</value>
+ </data>
+ <data name="ID3140" xml:space="preserve">
+ <value>ID3140: Specify one or more BaseAddresses to enable metadata or set DisableWsdl to true in the SecurityTokenServiceConfiguration.</value>
+ </data>
+ <data name="ID3141" xml:space="preserve">
+ <value>ID3141: The RequestType '{0}', is not supported. If you need to support this RequestType, override the corresponding virtual method in your SecurityTokenService derived class.</value>
+ </data>
+ <data name="ID3144" xml:space="preserve">
+ <value>ID3144: The PortType '{0}' Operation '{1}' has Message '{2}' is expected to have only one part but contains '{3}'.</value>
+ </data>
+ <data name="ID3146" xml:space="preserve">
+ <value>ID3146: WsdlEndpointConversionContext.WsdlPort cannot be null.</value>
+ </data>
+ <data name="ID3147" xml:space="preserve">
+ <value>ID3147: WsdlEndpointConversionContext.WsdlPort.Service cannot be null.</value>
+ </data>
+ <data name="ID3148" xml:space="preserve">
+ <value>ID3148: WsdlEndpointConversionContext.WsdlPort.Service.ServiceDescription cannot be null.</value>
+ </data>
+ <data name="ID3149" xml:space="preserve">
+ <value>ID3149: Cannot find an input message type for PortType '({0}, {1})' for operation '{2}' in the given ServiceDescription.</value>
+ </data>
+ <data name="ID3150" xml:space="preserve">
+ <value>ID3150: Cannot find an output message type for PortType '({0}, {1})' for operation '{2}' in the given ServiceDescription.</value>
+ </data>
+ <data name="ID3190" xml:space="preserve">
+ <value>ID3190: The WSTrustChannel cannot compute a proof key without a valid SecurityToken set as the RequestSecurityToken.UseKey when the RequestSecurityToken.KeyType is '{0}'.</value>
+ </data>
+ <data name="ID3191" xml:space="preserve">
+ <value>ID3191: The WSTrustChannel received a RequestedSecurityTokenResponse message containing an Entropy without a ComputedKeyAlgorithm.</value>
+ </data>
+ <data name="ID3192" xml:space="preserve">
+ <value>ID3192: The WSTrustChannel cannot compute a proof key. The received RequestedSecurityTokenResponse does not contain a RequestedProofToken and the ComputedKeyAlgorithm specified in the response is not supported: '{0}'.</value>
+ </data>
+ <data name="ID3193" xml:space="preserve">
+ <value>ID3193: The WSTrustChannel cannot compute a proof key. The received RequestedSecurityTokenResponse indicates that the proof key is computed using combined entropy. However, the response does not include an entropy.</value>
+ </data>
+ <data name="ID3194" xml:space="preserve">
+ <value>ID3194: The WSTrustChannel cannot compute a proof key. The received RequestedSecurityTokenResponse indicates that the proof key is computed using combined entropy. However, the request does not include an entropy.</value>
+ </data>
+ <data name="ID3269" xml:space="preserve">
+ <value>ID3269: Cannot determine the TrustVersion. It must either be specified explicitly, or a SecurityBindingElement must be present in the binding.</value>
+ </data>
+ <data name="ID3270" xml:space="preserve">
+ <value>ID3270: The WSTrustChannel does not support multi-leg issuance protocols. The RSTR received from the STS must be enclosed in a RequestSecurityTokenResponseCollection element.</value>
+ </data>
+ <data name="ID3285" xml:space="preserve">
+ <value>ID3285: The WS-Trust operation '{0}' is not valid or unsupported.</value>
+ </data>
+ <data name="ID3286" xml:space="preserve">
+ <value>ID3286: The 'inner' parameter must implement the 'System.ServiceModel.Channels.IChannel' interface.</value>
+ </data>
+ <data name="ID3287" xml:space="preserve">
+ <value>ID3287: WSTrustChannelFactory does not support changing the value of this property after a channel is created.</value>
+ </data>
+ <data name="ID4008" xml:space="preserve">
+ <value>ID4008: '{0}' does not provide an implementation for '{1}'.</value>
+ </data>
+ <data name="ID4039" xml:space="preserve">
+ <value>ID4039: A custom ServiceAuthorizationManager has been configured. Any custom ServiceAuthorizationManager must be derived from IdentityModelServiceAuthorizationManager.</value>
+ </data>
+ <data name="ID4041" xml:space="preserve">
+ <value>ID4041: Cannot configure the ServiceHost '{0}'. The ServiceHost is in a bad state and cannot be configured.</value>
+ </data>
+ <data name="ID4053" xml:space="preserve">
+ <value>ID4053: The token has WS-SecureConversation version '{0}'. Version '{1}' was expected.</value>
+ </data>
+ <data name="ID4072" xml:space="preserve">
+ <value>ID4072: The SecurityTokenHandler '{0}' registered for TokenType '{1}' must derive from '{2}'.</value>
+ </data>
+ <data name="ID4101" xml:space="preserve">
+ <value>ID4101: The token cannot be validated because it is not a SamlSecurityToken or a Saml2SecurityToken. Token type: '{0}'</value>
+ </data>
+ <data name="ID4192" xml:space="preserve">
+ <value>ID4192: The reader is not positioned on a KeyInfo element that can be read.</value>
+ </data>
+ <data name="ID4240" xml:space="preserve">
+ <value>ID4240: The tokenRequirement must derived from 'RecipientServiceModelSecurityTokenRequirement' for SecureConversationSecurityTokens. The tokenRequirement is of type '{0}'.</value>
+ </data>
+ <data name="ID4244" xml:space="preserve">
+ <value>ID4244: Internal error: sessionAuthenticator must support IIssuanceSecurityTokenAuthenticator.</value>
+ </data>
+ <data name="ID4245" xml:space="preserve">
+ <value>ID4245: Internal error: sessionAuthenticator must support ICommunicationObject.</value>
+ </data>
+ <data name="ID4268" xml:space="preserve">
+ <value>ID4268: MergeClaims must have at least one identity that is not null.</value>
+ </data>
+ <data name="ID4271" xml:space="preserve">
+ <value>ID4271: No IAuthorizationPolicy was found for the Transport security token '{0}'.</value>
+ </data>
+ <data name="ID4274" xml:space="preserve">
+ <value>ID4274: The Configuration property of this SecurityTokenHandler is set to null. Tokens cannot be read or validated in this state. Set this property or add this SecurityTokenHandler to a SecurityTokenHandlerCollection with a valid Configuration property.</value>
+ </data>
+ <data name="ID4285" xml:space="preserve">
+ <value>ID4285: Cannot replace SecurityToken with Id '{0}' in cache with new one. Token must exist in cache to be replaced.</value>
+ </data>
+ <data name="ID4287" xml:space="preserve">
+ <value>ID4287: The SecurityTokenRequirement '{0}' doesn't contain a ListenUri.</value>
+ </data>
+ <data name="ID5004" xml:space="preserve">
+ <value>ID5004: Unrecognized namespace: '{0}'.</value>
+ </data>
+ <data name="TraceAuthorize" xml:space="preserve">
+ <value>Authorize</value>
+ </data>
+ <data name="TraceOnAuthorizeRequestFailed" xml:space="preserve">
+ <value>OnAuthorizeRequest Failed.</value>
+ </data>
+ <data name="TraceOnAuthorizeRequestSucceed" xml:space="preserve">
+ <value>OnAuthorizeRequest Succeeded.</value>
+ </data>
+ <data name="AuthFailed" xml:space="preserve">
+ <value>Authentication failed.</value>
+ </data>
+ <data name="DuplicateFederatedClientCredentialsParameters" xml:space="preserve">
+ <value>The IssuedSecurityTokenProvider cannot support the FederatedClientCredentialsParameters. The FederatedClientCredentialsParameters has already provided the '{0}' parameter.</value>
+ </data>
+ <data name="UnsupportedTrustVersion" xml:space="preserve">
+ <value>The TrustVersion '{0}', is not supported, only 'TrustVersion.WSTrust13' and 'TrustVersion.WSTrustFeb2005' is supported.</value>
+ </data>
+ <data name="InputMustBeDelegatingHandlerElementError" xml:space="preserve">
+ <value>The input {0} must be a '{1}' object.</value>
+ </data>
+ <data name="InputTypeListEmptyError" xml:space="preserve">
+ <value>The input handler list cannot be empty.</value>
+ </data>
+ <data name="DelegatingHandlerArrayHasNonNullInnerHandler" xml:space="preserve">
+ <value>The '{0}' list is invalid because the property '{1}' of '{2}' is not null.</value>
+ </data>
+ <data name="DelegatingHandlerArrayFromFuncContainsNullItem" xml:space="preserve">
+ <value>The '{0}' list created by the Func '{1}' is invalid because it contains one or more null items.</value>
+ </data>
+ <data name="HttpMessageHandlerFactoryConfigInvalid_WithBothTypeAndHandlerList" xml:space="preserve">
+ <value>The config element '{0}' is invalid because the attribute '{1}' and the sub element '{2}' were both specified. These are mutually exclusive items and cannot be used simultaneouly.</value>
+ </data>
+ <data name="HttpMessageHandlerFactoryWithFuncCannotGenerateConfig" xml:space="preserve">
+ <value>This '{0}' object cannot be used to generate configuration because it was created with the constructor that takes a '{1}' as the paramter. This functionality is not supported through configuration files. Please use a different constructor if you wish to generate a configuration file.</value>
+ </data>
+ <data name="HttpMessageHandlerTypeNotSupported" xml:space="preserve">
+ <value>Invalid type: '{0}'. It must inherit from base type '{1}', cannot be abstract, and must expose a public default constructor.</value>
+ </data>
+ <data name="HttpMessageHandlerChannelFactoryNullPipeline" xml:space="preserve">
+ <value>'{0}' cannot return a null '{1}' instance. Please ensure that '{0}' returns a valid '{1}' instance.</value>
+ </data>
+ <data name="HttpPipelineOperationCanceledError" xml:space="preserve">
+ <value>HTTP pipeline operation cancelled.</value>
+ </data>
+ <data name="HttpPipelineMessagePropertyMissingError" xml:space="preserve">
+ <value>The message property '{0}' is missing in the HttpRequestMessage. Please make sure this property not removed or changed from the properties of the HttpRequestMessage. If you are creating a new HttpRequestMessage, please copy this property from the old message to the new one.</value>
+ </data>
+ <data name="HttpPipelineMessagePropertyTypeError" xml:space="preserve">
+ <value>The message property '{0}' inside the HttpRequestMessage is not with expected type '{1}'. Please make sure this property not removed or changed from the properties of the HttpRequestMessage. If you are creating a new HttpRequestMessage, please copy this property from the old message to the new one.</value>
+ </data>
+ <data name="InvalidContentTypeError" xml:space="preserve">
+ <value>The value '{0}' is not a valid content type.</value>
+ </data>
+ <data name="HttpPipelineNotSupportedOnClientSide" xml:space="preserve">
+ <value>The property '{0}' is not supported when building a ChannelFactory. The property value must be null when calling BuildChannelFactory.</value>
+ </data>
+ <data name="CanNotLoadTypeGotFromConfig" xml:space="preserve">
+ <value>Cound not load type '{0}' from the assemblies in current AppDomain.</value>
+ </data>
+ <data name="HttpPipelineNotSupportNullResponseMessage" xml:space="preserve">
+ <value>The HTTP response message should not be null. Please ensure your '{0}' instance returns a non-null '{1}' object.</value>
+ </data>
+ <data name="WebSocketInvalidProtocolNoHeader" xml:space="preserve">
+ <value>The subprotocol '{0}' was not requested by the client - no '{1}' header was included in the request.</value>
+ </data>
+ <data name="WebSocketInvalidProtocolNotInClientList" xml:space="preserve">
+ <value>The subprotocol '{0}' was not requested by the client. The client requested the following subprotocol(s): '{1}'.</value>
+ </data>
+ <data name="WebSocketInvalidProtocolInvalidCharInProtocolString" xml:space="preserve">
+ <value>The subprotocol '{0}' is invalid because it contains the invalid character '{1}'.</value>
+ </data>
+ <data name="WebSocketInvalidProtocolContainsMultipleSubProtocolString" xml:space="preserve">
+ <value>The value specified ('{0}') contains more than one subprotocol which is not supported.</value>
+ </data>
+ <data name="WebSocketInvalidProtocolEmptySubprotocolString" xml:space="preserve">
+ <value>Empty string is not a valid subprotocol value. Please use "null" to specify no value.</value>
+ </data>
+ <data name="WebSocketOpaqueStreamContentNotSupportError" xml:space="preserve">
+ <value>This method is not supported for this HTTP content.</value>
+ </data>
+ <data name="WebSocketElementConfigInvalidHttpMessageHandlerFactoryType" xml:space="preserve">
+ <value>Invalid value for the {0} type. The type '{1}' does not derive from the appropriate base class '{2}' or is abstract.</value>
+ </data>
+ <data name="WebSocketEndpointOnlySupportWebSocketError" xml:space="preserve">
+ <value>This service only supports WebSocket connections.</value>
+ </data>
+ <data name="WebSocketEndpointDoesNotSupportWebSocketError" xml:space="preserve">
+ <value>This service does not support WebSocket connections.</value>
+ </data>
+ <data name="WebSocketUpgradeFailedError" xml:space="preserve">
+ <value>WebSocket upgrade request failed. Received response status code '{0} ({1})', expected: '{2} ({3})'.</value>
+ </data>
+ <data name="WebSocketUpgradeFailedHeaderMissingError" xml:space="preserve">
+ <value>WebSocket upgrade request failed. The header '{0}' is missing in the response.</value>
+ </data>
+ <data name="WebSocketUpgradeFailedWrongHeaderError" xml:space="preserve">
+ <value>WebSocket upgrade request failed. The value of header '{0}' is '{1}'. The expected value is '{2}'.</value>
+ </data>
+ <data name="WebSocketUpgradeFailedInvalidProtocolError" xml:space="preserve">
+ <value>Unexpected response - the server accepted the upgrade request but specified the subprotocol '{0}' when no subprotocol was requested.</value>
+ </data>
+ <data name="WebSocketContextWebSocketCannotBeAccessedError" xml:space="preserve">
+ <value>WebSocket object cannot be accessed directly.</value>
+ </data>
+ <data name="WebSocketTransportError" xml:space="preserve">
+ <value>A WebSocket error occurred.</value>
+ </data>
+ <data name="WebSocketUnexpectedCloseMessageError" xml:space="preserve">
+ <value>Unexpected WebSocket close message received when receiving a message.</value>
+ </data>
+ <data name="WebSocketStreamWriteCalledAfterEOMSent" xml:space="preserve">
+ <value>Cannot write to the stream because the end of the stream marker was already written.</value>
+ </data>
+ <data name="WebSocketCannotCreateRequestClientChannelWithCertainWebSocketTransportUsage" xml:space="preserve">
+ <value>HttpChannelFactory cannot create the channel with shape '{0}' when the {1} of {2} was set as '{3}'.</value>
+ </data>
+ <data name="WebSocketMaxPendingConnectionsReached" xml:space="preserve">
+ <value>Maximum number of pending WebSocket connections ({0}) has been reached. Consider increasing the '{1}' quota on the '{2}' property of the transport.</value>
+ </data>
+ <data name="WebSocketOpeningHandshakePropertiesNotAvailable" xml:space="preserve">
+ <value>The opening handshake properties associated with the current WebSocket connection are not available. The most likely cause is that the property '{0}' on the '{1}' object returned from the custom '{2}' is not set.</value>
+ </data>
+ <data name="AcceptWebSocketTimedOutError" xml:space="preserve">
+ <value>The operation to establish the WebSocket connection timed out. To increase this time limit, use the OpenTimeout property on the service endpoint's binding.</value>
+ </data>
+ <data name="TaskCancelledError" xml:space="preserve">
+ <value>The task was cancelled.</value>
+ </data>
+ <data name="ClientWebSocketFactory_GetWebSocketVersionFailed" xml:space="preserve">
+ <value>An error occured when getting the WebSocketVersion from the WebSocket factory of type '{0}'. See the inner exception for details.</value>
+ </data>
+ <data name="ClientWebSocketFactory_InvalidWebSocketVersion" xml:space="preserve">
+ <value>The WebSocketVersion returned by the WebSocket factory of type '{0}' is either null, empty or invalid.</value>
+ </data>
+ <data name="ClientWebSocketFactory_CreateWebSocketFailed" xml:space="preserve">
+ <value>An error occurred when creating the WebSocket with the factory of type '{0}'. See the inner exception for details.</value>
+ </data>
+ <data name="ClientWebSocketFactory_InvalidWebSocket" xml:space="preserve">
+ <value>WebSocket creation failed. The '{0}' returned a WebSocket that is either null or not opened.</value>
+ </data>
+ <data name="ClientWebSocketFactory_InvalidSubProtocol" xml:space="preserve">
+ <value>The WebSocket returned by the factory of type '{0}' has the SubProtocol '{1}' that doesn't match the requested SubProtocol value '{2}'.</value>
+ </data>
+ <data name="MultipleClientWebSocketFactoriesSpecified" xml:space="preserve">
+ <value>The '{0}' contains multiple '{1}' objects, which is invalid. At most one '{1}' should be specified.</value>
+ </data>
+ <data name="WebSocketSendTimedOut" xml:space="preserve">
+ <value>The Send operation timed out after '{0}'. Increase the SendTimeout value on the Binding. The time allotted to this operation may have been a portion of a longer timeout.</value>
+ </data>
+ <data name="WebSocketReceiveTimedOut" xml:space="preserve">
+ <value>The Receive operation timed out after '{0}'. For duplex sessionful channels, the receive timeout is also the idle timeout for the channel, so consider setting a suitably large value for the ReceiveTimeout value on the Binding. The time allotted to this operation may have been a portion of a longer timeout.</value>
+ </data>
+ <data name="WebSocketOperationTimedOut" xml:space="preserve">
+ <value>The '{0}' operation timed out after '{1}'. The time allotted to this operation may have been a portion of a longer timeout.</value>
+ </data>
+ <data name="WebSocketsServerSideNotSupported" xml:space="preserve">
+ <value>This platform does not support server side WebSockets.</value>
+ </data>
+ <data name="WebSocketsClientSideNotSupported" xml:space="preserve">
+ <value>This platform does not support client side WebSockets natively. Support for client side WebSockets can be enabled on this platform by providing an implementation of {0}.</value>
+ </data>
+ <data name="WebSocketsNotSupportedInClassicPipeline" xml:space="preserve">
+ <value>WebSockets are not supported in the classic pipeline mode. Consider using the integrated pipeline mode for the application pool.</value>
+ </data>
+ <data name="WebSocketModuleNotLoaded" xml:space="preserve">
+ <value>The WebSocketModule is not loaded. Check if the WebSocket feature is installed and the WebSocketModule is enabled in the list of IIS modules (see http://go.microsoft.com/fwlink/?LinkId=231398 for details).</value>
+ </data>
+ <data name="WebSocketTransportPolicyAssertionInvalid" xml:space="preserve">
+ <value>The name of the policy being imported for contract '{0}:{1}' is invalid:'{2}'. It should be either '{3}', '{4}' or '{5}'.</value>
+ </data>
+ <data name="WebSocketVersionMismatchFromServer" xml:space="preserve">
+ <value>The server didn't accept the connection request. It is possible that the WebSocket protocol version on your client doesn't match the one on the server('{0}').</value>
+ </data>
+ <data name="WebSocketSubProtocolMismatchFromServer" xml:space="preserve">
+ <value>The server didn't accept the connection request. It is possible that the WebSocket subprotocol sent by your client is not supported by the server. Protocol(s) supported by the server are '{0}'.</value>
+ </data>
+ <data name="WebSocketContentTypeMismatchFromServer" xml:space="preserve">
+ <value>The server didn't accept the connection request. It is possible that the client side message encoding format doesn't match the setting on the server side. Please check your binding settings.</value>
+ </data>
+ <data name="WebSocketContentTypeAndTransferModeMismatchFromServer" xml:space="preserve">
+ <value>The server didn't accept the connection request. It is possible that the client side message encoding format or message transfer mode doesn't match the setting on the server side. Please check your binding settings.</value>
+ </data>
+ <data name="ResponseHeaderWithRequestHeadersCollection" xml:space="preserve">
+ <value>This collection holds request headers and cannot contain the specified response header '{0}'.</value>
+ </data>
+ <data name="RequestHeaderWithResponseHeadersCollection" xml:space="preserve">
+ <value>This collection holds response headers and cannot contain the specified request header '{0}'.</value>
+ </data>
+ <data name="MessageVersionNoneRequiredForHttpMessageSupport" xml:space="preserve">
+ <value>Support for {0} and {1} can not be enabled with {2} when the {3} of the {4} is '{5}'. Ensure the {4} used with the binding has a {3} of '{6}'. </value>
+ </data>
+ <data name="WebHeaderEnumOperationCantHappen" xml:space="preserve">
+ <value>Enumeration has either not started or has already finished.</value>
+ </data>
+ <data name="WebHeaderEmptyStringCall" xml:space="preserve">
+ <value>The parameter '{0}' cannot be an empty string.</value>
+ </data>
+ <data name="WebHeaderInvalidControlChars" xml:space="preserve">
+ <value>Specified value has invalid Control characters.</value>
+ </data>
+ <data name="WebHeaderInvalidCRLFChars" xml:space="preserve">
+ <value>Specified value has invalid CRLF characters.</value>
+ </data>
+ <data name="WebHeaderInvalidHeaderChars" xml:space="preserve">
+ <value>Specified value has invalid HTTP Header characters.</value>
+ </data>
+ <data name="WebHeaderInvalidNonAsciiChars" xml:space="preserve">
+ <value>Specified value has invalid non-ASCII characters.</value>
+ </data>
+ <data name="WebHeaderArgumentOutOfRange" xml:space="preserve">
+ <value>Specified argument was out of the range of valid values.</value>
+ </data>
+ <data name="CopyHttpHeaderFailed" xml:space="preserve">
+ <value>Failed to copy the HTTP header '{0}' with value '{1}' to '{2}'.</value>
+ </data>
+</root> \ No newline at end of file
diff --git a/src/System.ServiceModel.Syndication/src/System.ServiceModel.Syndication.csproj b/src/System.ServiceModel.Syndication/src/System.ServiceModel.Syndication.csproj
new file mode 100644
index 0000000000..b580434a36
--- /dev/null
+++ b/src/System.ServiceModel.Syndication/src/System.ServiceModel.Syndication.csproj
@@ -0,0 +1,15 @@
+<?xml version="1.0" encoding="utf-8"?>
+<Project ToolsVersion="14.0" xmlns="http://schemas.microsoft.com/developer/msbuild/2003" DefaultTargets="Build">
+ <Import Project="$([MSBuild]::GetDirectoryNameOfFileAbove($(MSBuildThisFileDirectory), dir.props))\dir.props" />
+ <PropertyGroup>
+ <AssemblyName>System.ServiceModel.Syndication</AssemblyName>
+ <ProjectGuid>{C2AB129B-E3EC-465B-B1B7-0F7D414B1E74}</ProjectGuid>
+ <NoWarn>$(NoWarn);1634;1691;649</NoWarn>
+ </PropertyGroup>
+ <PropertyGroup Condition="'$(Configuration)|$(Platform)'=='netstandard-Debug|AnyCPU'" />
+ <PropertyGroup Condition="'$(Configuration)|$(Platform)'=='netstandard-Release|AnyCPU'" />
+ <ItemGroup>
+ <Compile Include="$(MsBuildThisFileDirectory)\**\*.cs" />
+ </ItemGroup>
+ <Import Project="$([MSBuild]::GetDirectoryNameOfFileAbove($(MSBuildThisFileDirectory), dir.targets))\dir.targets" />
+</Project> \ No newline at end of file
diff --git a/src/System.ServiceModel.Syndication/src/System/ServiceModel/Channels/UriGenerator.cs b/src/System.ServiceModel.Syndication/src/System/ServiceModel/Channels/UriGenerator.cs
new file mode 100644
index 0000000000..5e9bec3aaf
--- /dev/null
+++ b/src/System.ServiceModel.Syndication/src/System/ServiceModel/Channels/UriGenerator.cs
@@ -0,0 +1,44 @@
+// 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.ServiceModel.Channels
+{
+ using System.Threading;
+ using System.Globalization;
+ using System.ServiceModel;
+
+ internal class UriGenerator
+ {
+ private long _id;
+ private string _prefix;
+
+ public UriGenerator()
+ : this("uuid")
+ {
+ }
+
+ public UriGenerator(string scheme)
+ : this(scheme, ";")
+ {
+ }
+
+ public UriGenerator(string scheme, string delimiter)
+ {
+ if (scheme == null)
+ throw new ArgumentException("scheme");
+ //throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new ArgumentNullException("scheme"));
+
+ if (scheme.Length == 0)
+ throw new ArgumentException(string.Format(SR.UriGeneratorSchemeMustNotBeEmpty, "scheme"));
+
+ _prefix = string.Concat(scheme, ":", Guid.NewGuid().ToString(), delimiter, "id=");
+ }
+
+ public string Next()
+ {
+ long nextId = Interlocked.Increment(ref _id);
+ return _prefix + nextId.ToString(CultureInfo.InvariantCulture);
+ }
+ }
+}
diff --git a/src/System.ServiceModel.Syndication/src/System/ServiceModel/Syndication/App10Constants.cs b/src/System.ServiceModel.Syndication/src/System/ServiceModel/Syndication/App10Constants.cs
new file mode 100644
index 0000000000..c1e8663b49
--- /dev/null
+++ b/src/System.ServiceModel.Syndication/src/System/ServiceModel/Syndication/App10Constants.cs
@@ -0,0 +1,20 @@
+// 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.ServiceModel.Syndication
+{
+ internal static class App10Constants
+ {
+ public const string Accept = "accept";
+ public const string Categories = "categories";
+ public const string Collection = "collection";
+ public const string Fixed = "fixed";
+ public const string Href = "href";
+ public const string Namespace = "http://www.w3.org/2007/app";
+ public const string Prefix = "app";
+ public const string Service = "service";
+ public const string Workspace = "workspace";
+ }
+}
diff --git a/src/System.ServiceModel.Syndication/src/System/ServiceModel/Syndication/Atom10Constants.cs b/src/System.ServiceModel.Syndication/src/System/ServiceModel/Syndication/Atom10Constants.cs
new file mode 100644
index 0000000000..55f12e230f
--- /dev/null
+++ b/src/System.ServiceModel.Syndication/src/System/ServiceModel/Syndication/Atom10Constants.cs
@@ -0,0 +1,53 @@
+// 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.ServiceModel.Syndication
+{
+ public static class Atom10Constants
+ {
+ public const string AlternateTag = "alternate";
+ public const string Atom10Namespace = "http://www.w3.org/2005/Atom";
+ public const string Atom10Prefix = "a10";
+ public const string AtomMediaType = "application/atom+xml";
+ public const string AuthorTag = "author";
+ public const string CategoryTag = "category";
+ public const string ContentTag = "content";
+ public const string ContributorTag = "contributor";
+ public const string EmailTag = "email";
+ public const string EntryTag = "entry";
+ public const string FeedTag = "feed";
+ public const string GeneratorTag = "generator";
+ public const string HrefTag = "href";
+ public const string HtmlMediaType = "text/html";
+ public const string HtmlType = "html";
+ public const string IdTag = "id";
+ public const string LabelTag = "label";
+ public const string LengthTag = "length";
+ public const string LinkTag = "link";
+ public const string LogoTag = "logo";
+ public const string NameTag = "name";
+ public const string PlaintextType = "text";
+ public const string PublishedTag = "published";
+ public const string RelativeTag = "rel";
+ public const string RightsTag = "rights";
+ public const string SchemeTag = "scheme";
+ public const string SelfTag = "self";
+ public const string SourceFeedTag = "source";
+ public const string SourceTag = "src";
+ public const string SpecificationLink = "http://atompub.org/2005/08/17/draft-ietf-atompub-format-11.html";
+ public const string SubtitleTag = "subtitle";
+ public const string SummaryTag = "summary";
+ public const string TermTag = "term";
+ public const string TitleTag = "title";
+ public const string TypeTag = "type";
+ public const string UpdatedTag = "updated";
+ public const string UriTag = "uri";
+ public const string XHtmlMediaType = "application/xhtml+xml";
+ public const string XHtmlType = "xhtml";
+ public const string XmlMediaType = "text/xml";
+ public const string IconTag = "icon";
+ }
+}
diff --git a/src/System.ServiceModel.Syndication/src/System/ServiceModel/Syndication/Atom10FeedFormatter.cs b/src/System.ServiceModel.Syndication/src/System/ServiceModel/Syndication/Atom10FeedFormatter.cs
new file mode 100644
index 0000000000..03bf2d4e5e
--- /dev/null
+++ b/src/System.ServiceModel.Syndication/src/System/ServiceModel/Syndication/Atom10FeedFormatter.cs
@@ -0,0 +1,1403 @@
+// 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.ServiceModel.Syndication
+{
+ using System;
+ using System.Collections.Generic;
+ using System.Collections.ObjectModel;
+ using System.Globalization;
+ using System.Runtime.CompilerServices;
+ using System.ServiceModel.Channels;
+ using System.Threading;
+ using System.Threading.Tasks;
+ using System.Xml;
+ using System.Xml.Serialization;
+
+ [XmlRoot(ElementName = Atom10Constants.FeedTag, Namespace = Atom10Constants.Atom10Namespace)]
+ public class Atom10FeedFormatter : SyndicationFeedFormatter
+ {
+ internal static readonly TimeSpan zeroOffset = new TimeSpan(0, 0, 0);
+ internal const string XmlNs = "http://www.w3.org/XML/1998/namespace";
+ internal const string XmlNsNs = "http://www.w3.org/2000/xmlns/";
+ private static readonly XmlQualifiedName s_atom10Href = new XmlQualifiedName(Atom10Constants.HrefTag, string.Empty);
+ private static readonly XmlQualifiedName s_atom10Label = new XmlQualifiedName(Atom10Constants.LabelTag, string.Empty);
+ private static readonly XmlQualifiedName s_atom10Length = new XmlQualifiedName(Atom10Constants.LengthTag, string.Empty);
+ private static readonly XmlQualifiedName s_atom10Relative = new XmlQualifiedName(Atom10Constants.RelativeTag, string.Empty);
+ private static readonly XmlQualifiedName s_atom10Scheme = new XmlQualifiedName(Atom10Constants.SchemeTag, string.Empty);
+ private static readonly XmlQualifiedName s_atom10Term = new XmlQualifiedName(Atom10Constants.TermTag, string.Empty);
+ private static readonly XmlQualifiedName s_atom10Title = new XmlQualifiedName(Atom10Constants.TitleTag, string.Empty);
+ private static readonly XmlQualifiedName s_atom10Type = new XmlQualifiedName(Atom10Constants.TypeTag, string.Empty);
+ private static readonly UriGenerator s_idGenerator = new UriGenerator();
+ private const string Rfc3339LocalDateTimeFormat = "yyyy-MM-ddTHH:mm:sszzz";
+ private const string Rfc3339UTCDateTimeFormat = "yyyy-MM-ddTHH:mm:ssZ";
+ private Type _feedType;
+ private int _maxExtensionSize;
+ private bool _preserveAttributeExtensions;
+ private bool _preserveElementExtensions;
+
+ //Custom parsing
+ // value, localname , ns , result
+ public Func<string, string, string, string> stringParser = DefaultStringParser;
+ public Func<string, string, string, DateTimeOffset> dateParser = DefaultDateFromString;
+ public Func<string, UriKind, string, string, Uri> uriParser = DefaultUriParser;
+
+ private static string DefaultStringParser(string value, string localName, string ns)
+ {
+ return value;
+ }
+
+ private static Uri DefaultUriParser(string value, UriKind kind, string localName, string ns)
+ {
+ return new Uri(value,kind);
+ }
+
+ public Atom10FeedFormatter()
+ : this(typeof(SyndicationFeed))
+ {
+ }
+
+ public Atom10FeedFormatter(Type feedTypeToCreate)
+ : base()
+ {
+ if (feedTypeToCreate == null)
+ {
+ throw new ArgumentException(nameof(feedTypeToCreate));
+ }
+ if (!typeof(SyndicationFeed).IsAssignableFrom(feedTypeToCreate))
+ {
+ throw new ArgumentException(string.Format(SR.InvalidObjectTypePassed, nameof(feedTypeToCreate), nameof(SyndicationFeed)));
+ }
+ _maxExtensionSize = int.MaxValue;
+ _preserveAttributeExtensions = _preserveElementExtensions = true;
+ _feedType = feedTypeToCreate;
+ }
+
+ public Atom10FeedFormatter(SyndicationFeed feedToWrite)
+ : base(feedToWrite)
+ {
+ // No need to check that the parameter passed is valid - it is checked by the c'tor of the base class
+ _maxExtensionSize = int.MaxValue;
+ _preserveAttributeExtensions = _preserveElementExtensions = true;
+ _feedType = feedToWrite.GetType();
+ }
+
+ public bool PreserveAttributeExtensions
+ {
+ get { return _preserveAttributeExtensions; }
+ set { _preserveAttributeExtensions = value; }
+ }
+
+ public bool PreserveElementExtensions
+ {
+ get { return _preserveElementExtensions; }
+ set { _preserveElementExtensions = value; }
+ }
+
+ public override string Version
+ {
+ get { return SyndicationVersions.Atom10; }
+ }
+
+ protected Type FeedType
+ {
+ get
+ {
+ return _feedType;
+ }
+ }
+
+ public override bool CanRead(XmlReader reader)
+ {
+ if (reader == null)
+ {
+ throw new ArgumentNullException(nameof(reader));
+ }
+
+ return reader.IsStartElement(Atom10Constants.FeedTag, Atom10Constants.Atom10Namespace);
+ }
+
+ public override async Task ReadFromAsync(XmlReader reader, CancellationToken ct)
+ {
+ if (!CanRead(reader))
+ {
+ throw new XmlException(string.Format(SR.UnknownFeedXml, reader.LocalName, reader.NamespaceURI));
+ }
+
+ SetFeed(CreateFeedInstance());
+ await ReadFeedFromAsync(XmlReaderWrapper.CreateFromReader(reader), this.Feed, false);
+ }
+
+ public override async Task WriteToAsync(XmlWriter writer, CancellationToken ct)
+ {
+ if (writer == null)
+ {
+ throw new ArgumentNullException(nameof(writer));
+ }
+
+ writer = XmlWriterWrapper.CreateFromWriter(writer);
+
+ await writer.WriteStartElementAsync(Atom10Constants.FeedTag, Atom10Constants.Atom10Namespace);
+ await WriteFeedAsync(writer);
+ await writer.WriteEndElementAsync();
+ }
+
+ internal static async Task<SyndicationCategory> ReadCategoryAsync(XmlReaderWrapper reader, SyndicationCategory category, string version, bool preserveAttributeExtensions, bool preserveElementExtensions, int _maxExtensionSize)
+ {
+ await MoveToStartElementAsync(reader);
+ bool isEmpty = reader.IsEmptyElement;
+ if (reader.HasAttributes)
+ {
+ while (reader.MoveToNextAttribute())
+ {
+ string value = await reader.GetValueAsync();
+ bool notHandled = false;
+
+ if(reader.NamespaceURI == string.Empty)
+ {
+ switch (reader.LocalName)
+ {
+ case Atom10Constants.TermTag:
+ category.Name = value;
+ break;
+
+ case Atom10Constants.SchemeTag:
+ category.Scheme = value;
+ break;
+
+ case Atom10Constants.LabelTag:
+ category.Label = value;
+ break;
+
+ default:
+ notHandled = true;
+ break;
+ }
+ }
+ else
+ {
+ notHandled = true;
+ }
+
+ if (notHandled)
+ {
+ string ns = reader.NamespaceURI;
+ string name = reader.LocalName;
+ if (FeedUtils.IsXmlns(name, ns))
+ {
+ continue;
+ }
+
+ if (!TryParseAttribute(name, ns, value, category, version))
+ {
+ if (preserveAttributeExtensions)
+ {
+ category.AttributeExtensions.Add(new XmlQualifiedName(name, ns), value);
+ }
+ }
+ }
+ }
+ }
+
+ if (!isEmpty)
+ {
+ await reader.ReadStartElementAsync();
+ XmlBuffer buffer = null;
+ XmlDictionaryWriter extWriter = null;
+ try
+ {
+ while (await reader.IsStartElementAsync())
+ {
+ if (TryParseElement(reader, category, version))
+ {
+ continue;
+ }
+ else if (!preserveElementExtensions)
+ {
+ await reader.SkipAsync();
+ }
+ else
+ {
+ var tuple = await CreateBufferIfRequiredAndWriteNodeAsync(buffer, extWriter, reader, _maxExtensionSize);
+ buffer = tuple.Item1;
+ extWriter = tuple.Item2;
+ }
+ }
+
+ LoadElementExtensions(buffer, extWriter, category);
+ }
+ finally
+ {
+ if (extWriter != null)
+ {
+ ((IDisposable)extWriter).Dispose();
+ }
+ }
+
+ await reader.ReadEndElementAsync();
+ }
+ else
+ {
+ await reader.ReadStartElementAsync();
+ }
+
+ return category;
+ }
+
+ internal Task<TextSyndicationContent> ReadTextContentFromAsync(XmlReaderWrapper reader, string context, bool preserveAttributeExtensions)
+ {
+ string type = reader.GetAttribute(Atom10Constants.TypeTag);
+ return ReadTextContentFromHelperAsync(reader, type, context, preserveAttributeExtensions);
+ }
+
+ internal static async Task WriteCategoryAsync(XmlWriter writer, SyndicationCategory category, string version)
+ {
+ await writer.WriteStartElementAsync(Atom10Constants.CategoryTag, Atom10Constants.Atom10Namespace);
+ await WriteAttributeExtensionsAsync(writer, category, version);
+ string categoryName = category.Name ?? string.Empty;
+ if (!category.AttributeExtensions.ContainsKey(s_atom10Term))
+ {
+ await writer.WriteAttributeStringAsync(Atom10Constants.TermTag, categoryName);
+ }
+
+ if (!string.IsNullOrEmpty(category.Label) && !category.AttributeExtensions.ContainsKey(s_atom10Label))
+ {
+ await writer.WriteAttributeStringAsync(Atom10Constants.LabelTag, category.Label);
+ }
+
+ if (!string.IsNullOrEmpty(category.Scheme) && !category.AttributeExtensions.ContainsKey(s_atom10Scheme))
+ {
+ await writer.WriteAttributeStringAsync(Atom10Constants.SchemeTag, category.Scheme);
+ }
+
+ await WriteElementExtensionsAsync(writer, category, version);
+ await writer.WriteEndElementAsync();
+ }
+
+ internal async Task ReadItemFromAsync(XmlReaderWrapper reader, SyndicationItem result)
+ {
+ await ReadItemFromAsync(reader, result, null);
+ }
+
+ internal async Task<bool> TryParseFeedElementFromAsync(XmlReaderWrapper reader, SyndicationFeed result)
+ {
+ if (await reader.MoveToContentAsync() != XmlNodeType.Element)
+ {
+ return false;
+ }
+
+ string name = reader.LocalName;
+ string ns = reader.NamespaceURI;
+
+ if(ns == Atom10Constants.Atom10Namespace)
+ {
+ switch (name)
+ {
+ case Atom10Constants.AuthorTag:
+ result.Authors.Add(await ReadPersonFromAsync(reader, result));
+ break;
+ case Atom10Constants.CategoryTag:
+ result.Categories.Add(await ReadCategoryFromAsync(reader, result));
+ break;
+ case Atom10Constants.ContributorTag:
+ result.Contributors.Add(await ReadPersonFromAsync(reader, result));
+ break;
+ case Atom10Constants.GeneratorTag:
+ result.Generator = stringParser(await reader.ReadElementStringAsync(),Atom10Constants.GeneratorTag,ns);
+ break;
+ case Atom10Constants.IdTag:
+ result.Id = stringParser(await reader.ReadElementStringAsync(),Atom10Constants.IdTag,ns);
+ break;
+ case Atom10Constants.LinkTag:
+ result.Links.Add(await ReadLinkFromAsync(reader, result));
+ break;
+ case Atom10Constants.LogoTag:
+ result.ImageUrl = uriParser(await reader.ReadElementStringAsync(), UriKind.RelativeOrAbsolute, Atom10Constants.LogoTag, ns); //new Uri(await reader.ReadElementStringAsync(), UriKind.RelativeOrAbsolute);
+ break;
+ case Atom10Constants.RightsTag:
+ result.Copyright = await ReadTextContentFromAsync(reader, "//atom:feed/atom:rights[@type]");
+ break;
+ case Atom10Constants.SubtitleTag:
+ result.Description = await ReadTextContentFromAsync(reader, "//atom:feed/atom:subtitle[@type]");
+ break;
+ case Atom10Constants.TitleTag:
+ result.Title = await ReadTextContentFromAsync(reader, "//atom:feed/atom:title[@type]");
+ break;
+ case Atom10Constants.UpdatedTag:
+ await reader.ReadStartElementAsync();
+ result.LastUpdatedTime = dateParser(await reader.ReadStringAsync(), Atom10Constants.UpdatedTag, ns);
+ await reader.ReadEndElementAsync();
+ break;
+ case Atom10Constants.IconTag:
+ result.IconImage = uriParser(await reader.ReadElementStringAsync(), UriKind.RelativeOrAbsolute, Atom10Constants.IconTag, ns);
+ break;
+ default:
+ return false;
+ }
+
+ return true;
+ }
+
+ return false;
+ }
+
+ internal async Task<bool> TryParseItemElementFromAsync(XmlReaderWrapper reader, SyndicationItem result)
+ {
+ if (await reader.MoveToContentAsync() != XmlNodeType.Element)
+ {
+ return false;
+ }
+
+ string name = reader.LocalName;
+ string ns = reader.NamespaceURI;
+
+ if(ns == Atom10Constants.Atom10Namespace)
+ {
+ switch (name)
+ {
+ case Atom10Constants.AuthorTag:
+ result.Authors.Add(await ReadPersonFromAsync(reader, result));
+ break;
+ case Atom10Constants.CategoryTag:
+ result.Categories.Add(await ReadCategoryFromAsync(reader, result));
+ break;
+ case Atom10Constants.ContentTag:
+ result.Content = await ReadContentFromAsync(reader, result);
+ break;
+ case Atom10Constants.ContributorTag:
+ result.Contributors.Add(await ReadPersonFromAsync(reader, result));
+ break;
+ case Atom10Constants.IdTag:
+ result.Id = stringParser(await reader.ReadElementStringAsync(),Atom10Constants.IdTag,ns);
+ break;
+ case Atom10Constants.LinkTag:
+ result.Links.Add(await ReadLinkFromAsync(reader, result));
+ break;
+ case Atom10Constants.PublishedTag:
+ await reader.ReadStartElementAsync();
+ result.PublishDate = dateParser(await reader.ReadStringAsync(), Atom10Constants.UpdatedTag, ns);
+ await reader.ReadEndElementAsync();
+ break;
+ case Atom10Constants.RightsTag:
+ result.Copyright = await ReadTextContentFromAsync(reader, "//atom:feed/atom:entry/atom:rights[@type]");
+ break;
+ case Atom10Constants.SourceFeedTag:
+ await reader.ReadStartElementAsync();
+ result.SourceFeed = await ReadFeedFromAsync(reader, new SyndicationFeed(), true); // isSourceFeed
+ await reader.ReadEndElementAsync();
+ break;
+ case Atom10Constants.SummaryTag:
+ result.Summary = await ReadTextContentFromAsync(reader, "//atom:feed/atom:entry/atom:summary[@type]");
+ break;
+ case Atom10Constants.TitleTag:
+ result.Title = await ReadTextContentFromAsync(reader, "//atom:feed/atom:entry/atom:title[@type]");
+ break;
+ case Atom10Constants.UpdatedTag:
+ await reader.ReadStartElementAsync();
+ result.LastUpdatedTime = dateParser(await reader.ReadStringAsync(), Atom10Constants.UpdatedTag, ns);
+ await reader.ReadEndElementAsync();
+ break;
+ default:
+ return false;
+ }
+
+ return true;
+ }
+
+ return false;
+ }
+
+ internal Task WriteContentToAsync(XmlWriter writer, string elementName, SyndicationContent content)
+ {
+ if (content != null)
+ {
+ return content.WriteToAsync(writer, elementName, Atom10Constants.Atom10Namespace);
+ }
+ return Task.CompletedTask;
+ }
+
+ internal async Task WriteElementAsync(XmlWriter writer, string elementName, string value)
+ {
+ if (value != null)
+ {
+ await writer.WriteElementStringAsync(elementName, Atom10Constants.Atom10Namespace, value);
+ }
+ }
+
+ internal async Task WriteFeedAuthorsToAsync(XmlWriter writer, Collection<SyndicationPerson> authors)
+ {
+ writer = XmlWriterWrapper.CreateFromWriter(writer);
+ for (int i = 0; i < authors.Count; ++i)
+ {
+ SyndicationPerson p = authors[i];
+ await WritePersonToAsync(writer, p, Atom10Constants.AuthorTag);
+ }
+ }
+
+ internal async Task WriteFeedContributorsToAsync(XmlWriter writer, Collection<SyndicationPerson> contributors)
+ {
+ writer = XmlWriterWrapper.CreateFromWriter(writer);
+ for (int i = 0; i < contributors.Count; ++i)
+ {
+ SyndicationPerson p = contributors[i];
+ await WritePersonToAsync(writer, p, Atom10Constants.ContributorTag);
+ }
+ }
+
+ internal Task WriteFeedLastUpdatedTimeToAsync(XmlWriter writer, DateTimeOffset lastUpdatedTime, bool isRequired)
+ {
+ if (lastUpdatedTime == DateTimeOffset.MinValue && isRequired)
+ {
+ lastUpdatedTime = DateTimeOffset.UtcNow;
+ }
+
+ if (lastUpdatedTime != DateTimeOffset.MinValue)
+ {
+ return WriteElementAsync(writer, Atom10Constants.UpdatedTag, AsString(lastUpdatedTime));
+ }
+
+ return Task.CompletedTask;
+ }
+
+ internal async Task WriteItemAuthorsToAsync(XmlWriter writer, Collection<SyndicationPerson> authors)
+ {
+ writer = XmlWriterWrapper.CreateFromWriter(writer);
+ for (int i = 0; i < authors.Count; ++i)
+ {
+ SyndicationPerson p = authors[i];
+ await WritePersonToAsync(writer, p, Atom10Constants.AuthorTag);
+ }
+ }
+
+ internal Task WriteItemContentsAsync(XmlWriter dictWriter, SyndicationItem item)
+ {
+ return WriteItemContentsAsync(dictWriter, item, null);
+ }
+
+ internal async Task WriteItemContributorsToAsync(XmlWriter writer, Collection<SyndicationPerson> contributors)
+ {
+ writer = XmlWriterWrapper.CreateFromWriter(writer);
+
+ for (int i = 0; i < contributors.Count; ++i)
+ {
+ SyndicationPerson p = contributors[i];
+ await WritePersonToAsync(writer, p, Atom10Constants.ContributorTag);
+ }
+ }
+
+ internal Task WriteItemLastUpdatedTimeToAsync(XmlWriter writer, DateTimeOffset lastUpdatedTime)
+ {
+ if (lastUpdatedTime == DateTimeOffset.MinValue)
+ {
+ lastUpdatedTime = DateTimeOffset.UtcNow;
+ }
+
+ return writer.WriteElementStringAsync(Atom10Constants.UpdatedTag,
+ Atom10Constants.Atom10Namespace,
+ AsString(lastUpdatedTime));
+ }
+
+ internal async Task WriteLinkAsync(XmlWriter writer, SyndicationLink link, Uri baseUri)
+ {
+ await writer.WriteStartElementAsync(Atom10Constants.LinkTag, Atom10Constants.Atom10Namespace);
+ Uri baseUriToWrite = FeedUtils.GetBaseUriToWrite(baseUri, link.BaseUri);
+ if (baseUriToWrite != null)
+ {
+ await writer.WriteAttributeStringAsync("xml", "base", XmlNs, FeedUtils.GetUriString(baseUriToWrite));
+ }
+
+ await link.WriteAttributeExtensionsAsync(writer, SyndicationVersions.Atom10);
+ if (!string.IsNullOrEmpty(link.RelationshipType) && !link.AttributeExtensions.ContainsKey(s_atom10Relative))
+ {
+ await writer.WriteAttributeStringAsync(Atom10Constants.RelativeTag, link.RelationshipType);
+ }
+
+ if (!string.IsNullOrEmpty(link.MediaType) && !link.AttributeExtensions.ContainsKey(s_atom10Type))
+ {
+ await writer.WriteAttributeStringAsync(Atom10Constants.TypeTag, link.MediaType);
+ }
+
+ if (!string.IsNullOrEmpty(link.Title) && !link.AttributeExtensions.ContainsKey(s_atom10Title))
+ {
+ await writer.WriteAttributeStringAsync(Atom10Constants.TitleTag, link.Title);
+ }
+
+ if (link.Length != 0 && !link.AttributeExtensions.ContainsKey(s_atom10Length))
+ {
+ await writer.WriteAttributeStringAsync(Atom10Constants.LengthTag, Convert.ToString(link.Length, CultureInfo.InvariantCulture));
+ }
+
+ if (!link.AttributeExtensions.ContainsKey(s_atom10Href))
+ {
+ await writer.WriteAttributeStringAsync(Atom10Constants.HrefTag, FeedUtils.GetUriString(link.Uri));
+ }
+
+ await link.WriteElementExtensionsAsync(writer, SyndicationVersions.Atom10);
+ await writer.WriteEndElementAsync();
+ }
+
+ protected override SyndicationFeed CreateFeedInstance()
+ {
+ return SyndicationFeedFormatter.CreateFeedInstance(_feedType);
+ }
+
+ protected virtual async Task<SyndicationItem> ReadItemAsync(XmlReader reader, SyndicationFeed feed)
+ {
+ if (feed == null)
+ {
+ throw new ArgumentNullException(nameof(feed));
+ }
+
+ if (reader == null)
+ {
+ throw new ArgumentNullException(nameof(reader));
+ }
+
+ SyndicationItem item = CreateItem(feed);
+ XmlReaderWrapper readerWrapper = XmlReaderWrapper.CreateFromReader(reader);
+ await ReadItemFromAsync(readerWrapper, item, feed.BaseUri);
+ return item;
+ }
+
+ //not referenced anymore
+ protected virtual async Task<IEnumerable<SyndicationItem>> ReadItemsAsync(XmlReader reader, SyndicationFeed feed)
+ {
+ if (feed == null)
+ {
+ throw new ArgumentNullException(nameof(feed));
+ }
+
+ if (reader == null)
+ {
+ throw new ArgumentNullException(nameof(reader));
+ }
+
+ NullNotAllowedCollection<SyndicationItem> items = new NullNotAllowedCollection<SyndicationItem>();
+ XmlReaderWrapper readerWrapper = XmlReaderWrapper.CreateFromReader(reader);
+
+ while (await readerWrapper.IsStartElementAsync(Atom10Constants.EntryTag, Atom10Constants.Atom10Namespace))
+ {
+ items.Add(await ReadItemAsync(reader, feed));
+ }
+
+ return items;
+ }
+
+ protected virtual async Task WriteItemAsync(XmlWriter writer, SyndicationItem item, Uri feedBaseUri)
+ {
+ writer = XmlWriterWrapper.CreateFromWriter(writer);
+ await writer.WriteStartElementAsync(Atom10Constants.EntryTag, Atom10Constants.Atom10Namespace);
+ await WriteItemContentsAsync(writer, item, feedBaseUri);
+ await writer.WriteEndElementAsync();
+ }
+
+ protected virtual async Task WriteItemsAsync(XmlWriter writer, IEnumerable<SyndicationItem> items, Uri feedBaseUri)
+ {
+ if (items == null)
+ {
+ return;
+ }
+
+ foreach (SyndicationItem item in items)
+ {
+ await this.WriteItemAsync(writer, item, feedBaseUri);
+ }
+ }
+
+ private async Task<TextSyndicationContent> ReadTextContentFromHelperAsync(XmlReaderWrapper reader, string type, string context, bool preserveAttributeExtensions)
+ {
+ if (string.IsNullOrEmpty(type))
+ {
+ type = Atom10Constants.PlaintextType;
+ }
+
+ TextSyndicationContentKind kind = new TextSyndicationContentKind();
+ switch (type)
+ {
+ case Atom10Constants.PlaintextType:
+ kind = TextSyndicationContentKind.Plaintext;
+ break;
+ case Atom10Constants.HtmlType:
+ kind = TextSyndicationContentKind.Html;
+ break;
+ case Atom10Constants.XHtmlType:
+ kind = TextSyndicationContentKind.XHtml;
+ break;
+
+ throw new XmlException(string.Format(SR.Atom10SpecRequiresTextConstruct, context, type));
+ }
+
+ Dictionary<XmlQualifiedName, string> attrs = null;
+ if (reader.HasAttributes)
+ {
+ while (reader.MoveToNextAttribute())
+ {
+ if (reader.LocalName == Atom10Constants.TypeTag && reader.NamespaceURI == string.Empty)
+ {
+ continue;
+ }
+ string ns = reader.NamespaceURI;
+ string name = reader.LocalName;
+ if (FeedUtils.IsXmlns(name, ns))
+ {
+ continue;
+ }
+ if (preserveAttributeExtensions)
+ {
+ string value = await reader.GetValueAsync();
+ if (attrs == null)
+ {
+ attrs = new Dictionary<XmlQualifiedName, string>();
+ }
+ attrs.Add(new XmlQualifiedName(name, ns), value);
+ }
+ }
+ }
+ reader.MoveToElement();
+ string localName = reader.LocalName;
+ string nameSpace = reader.NamespaceURI;
+ string val = (kind == TextSyndicationContentKind.XHtml) ? await reader.ReadInnerXmlAsync() : stringParser(await reader.ReadElementStringAsync(),localName,nameSpace); // cant custom parse because its static
+ TextSyndicationContent result = new TextSyndicationContent(val, kind);
+ if (attrs != null)
+ {
+ foreach (XmlQualifiedName attr in attrs.Keys)
+ {
+ if (!FeedUtils.IsXmlns(attr.Name, attr.Namespace))
+ {
+ result.AttributeExtensions.Add(attr, attrs[attr]);
+ }
+ }
+ }
+ return result;
+ }
+
+ private string AsString(DateTimeOffset dateTime)
+ {
+ if (dateTime.Offset == zeroOffset)
+ {
+ return dateTime.ToUniversalTime().ToString(Rfc3339UTCDateTimeFormat, CultureInfo.InvariantCulture);
+ }
+ else
+ {
+ return dateTime.ToString(Rfc3339LocalDateTimeFormat, CultureInfo.InvariantCulture);
+ }
+ }
+
+ private static DateTimeOffset DefaultDateFromString(string dateTimeString, string localName, string ns)
+ {
+ dateTimeString = dateTimeString.Trim();
+ if (dateTimeString.Length < 20)
+ {
+ throw new XmlException(SR.ErrorParsingDateTime);
+ }
+ if (dateTimeString[19] == '.')
+ {
+ // remove any fractional seconds, we choose to ignore them
+ int i = 20;
+ while (dateTimeString.Length > i && char.IsDigit(dateTimeString[i]))
+ {
+ ++i;
+ }
+ dateTimeString = dateTimeString.Substring(0, 19) + dateTimeString.Substring(i);
+ }
+ DateTimeOffset localTime;
+ if (DateTimeOffset.TryParseExact(dateTimeString, Rfc3339LocalDateTimeFormat,
+ CultureInfo.InvariantCulture.DateTimeFormat,
+ DateTimeStyles.None, out localTime))
+ {
+ return localTime;
+ }
+ DateTimeOffset utcTime;
+ if (DateTimeOffset.TryParseExact(dateTimeString, Rfc3339UTCDateTimeFormat,
+ CultureInfo.InvariantCulture.DateTimeFormat,
+ DateTimeStyles.AssumeUniversal | DateTimeStyles.AdjustToUniversal, out utcTime))
+ {
+ return utcTime;
+ }
+
+ //throw new XmlException(FeedUtils.AddLineInfo(reader, SR.ErrorParsingDateTime));
+
+ //if imposible to parse, return default date
+ return new DateTimeOffset();
+ }
+
+ private Task<SyndicationCategory> ReadCategoryAsync(XmlReaderWrapper reader, SyndicationCategory category)
+ {
+ return ReadCategoryAsync(reader, category, this.Version, this.PreserveAttributeExtensions, this.PreserveElementExtensions, _maxExtensionSize);
+ }
+
+ private Task<SyndicationCategory> ReadCategoryFromAsync(XmlReaderWrapper reader, SyndicationFeed feed)
+
+ {
+ SyndicationCategory result = CreateCategory(feed);
+ return ReadCategoryAsync(reader, result);
+ }
+
+ private async Task<SyndicationCategory> ReadCategoryFromAsync(XmlReaderWrapper reader, SyndicationItem item)
+ {
+ SyndicationCategory result = CreateCategory(item);
+ await ReadCategoryAsync(reader, result);
+ return result;
+ }
+
+ private async Task<SyndicationContent> ReadContentFromAsync(XmlReaderWrapper reader, SyndicationItem item)
+ {
+ await MoveToStartElementAsync(reader);
+ string type = reader.GetAttribute(Atom10Constants.TypeTag, string.Empty);
+
+ SyndicationContent result;
+ if (TryParseContent(reader, item, type, this.Version, out result))
+ {
+ return result;
+ }
+
+ if (string.IsNullOrEmpty(type))
+ {
+ type = Atom10Constants.PlaintextType;
+ }
+ string src = reader.GetAttribute(Atom10Constants.SourceTag, string.Empty);
+
+ if (string.IsNullOrEmpty(src) && type != Atom10Constants.PlaintextType && type != Atom10Constants.HtmlType && type != Atom10Constants.XHtmlType)
+ {
+ return new XmlSyndicationContent(reader);
+ }
+
+ if (!string.IsNullOrEmpty(src))
+ {
+ result = new UrlSyndicationContent(new Uri(src, UriKind.RelativeOrAbsolute), type);
+ bool isEmpty = reader.IsEmptyElement;
+ if (reader.HasAttributes)
+ {
+ while (reader.MoveToNextAttribute())
+ {
+ if (reader.LocalName == Atom10Constants.TypeTag && reader.NamespaceURI == string.Empty)
+ {
+ continue;
+ }
+ else if (reader.LocalName == Atom10Constants.SourceTag && reader.NamespaceURI == string.Empty)
+ {
+ continue;
+ }
+ else if (!FeedUtils.IsXmlns(reader.LocalName, reader.NamespaceURI))
+ {
+ if (_preserveAttributeExtensions)
+ {
+ result.AttributeExtensions.Add(new XmlQualifiedName(reader.LocalName, reader.NamespaceURI), await reader.GetValueAsync());
+ }
+ else
+ {
+ //result.AttributeExtensions.Add(new XmlQualifiedName(reader.LocalName, reader.NamespaceURI), await reader.GetValueAsync());
+ }
+ }
+ }
+ }
+
+ await reader.ReadStartElementAsync();
+ if (!isEmpty)
+ {
+ await reader.ReadEndElementAsync();
+ }
+
+ return result;
+ }
+ else
+ {
+ return await ReadTextContentFromHelperAsync(reader, type, "//atom:feed/atom:entry/atom:content[@type]", _preserveAttributeExtensions);
+ }
+ }
+
+ private async Task<SyndicationFeed> ReadFeedFromAsync(XmlReaderWrapper reader, SyndicationFeed result, bool isSourceFeed)
+ {
+ await reader.MoveToContentAsync();
+ //fix to accept non contiguous items
+ NullNotAllowedCollection<SyndicationItem> feedItems = new NullNotAllowedCollection<SyndicationItem>();
+
+ bool elementIsEmpty = false;
+ if (!isSourceFeed)
+ {
+ await MoveToStartElementAsync(reader);
+ elementIsEmpty = reader.IsEmptyElement;
+ if (reader.HasAttributes)
+ {
+ while (reader.MoveToNextAttribute())
+ {
+ if (reader.LocalName == "lang" && reader.NamespaceURI == XmlNs)
+ {
+ result.Language = await reader.GetValueAsync();
+ }
+ else if (reader.LocalName == "base" && reader.NamespaceURI == XmlNs)
+ {
+ result.BaseUri = FeedUtils.CombineXmlBase(result.BaseUri, await reader.GetValueAsync());
+ }
+ else
+ {
+ string ns = reader.NamespaceURI;
+ string name = reader.LocalName;
+ if (FeedUtils.IsXmlns(name, ns) || FeedUtils.IsXmlSchemaType(name, ns))
+ {
+ continue;
+ }
+
+ string val = await reader.GetValueAsync();
+
+ if (!TryParseAttribute(name, ns, val, result, this.Version))
+ {
+ if (_preserveAttributeExtensions)
+ {
+ result.AttributeExtensions.Add(new XmlQualifiedName(reader.LocalName, reader.NamespaceURI), val);
+ }
+ }
+ }
+ }
+ }
+ await reader.ReadStartElementAsync();
+ }
+
+ XmlBuffer buffer = null;
+ XmlDictionaryWriter extWriter = null;
+
+ if (!elementIsEmpty)
+ {
+ try
+ {
+ while (await reader.IsStartElementAsync())
+ {
+ if (await TryParseFeedElementFromAsync(reader, result))
+ {
+ // nothing, we parsed something, great
+ }
+ else if (await reader.IsStartElementAsync(Atom10Constants.EntryTag, Atom10Constants.Atom10Namespace) && !isSourceFeed)
+ {
+ while (await reader.IsStartElementAsync(Atom10Constants.EntryTag, Atom10Constants.Atom10Namespace))
+ {
+ feedItems.Add(await ReadItemAsync(reader, result));
+ }
+ }
+ else
+ {
+ if (!TryParseElement(reader, result, this.Version))
+ {
+ if (_preserveElementExtensions)
+ {
+ if (buffer == null)
+ {
+ buffer = new XmlBuffer(_maxExtensionSize);
+ extWriter = buffer.OpenSection(XmlDictionaryReaderQuotas.Max);
+ extWriter.WriteStartElement(Rss20Constants.ExtensionWrapperTag);
+ }
+
+ await XmlReaderWrapper.WriteNodeAsync(extWriter, reader, false);
+ }
+ else
+ {
+ await reader.SkipAsync();
+ }
+ }
+ }
+ }
+ //Add all read items to the feed
+ result.Items = feedItems;
+ LoadElementExtensions(buffer, extWriter, result);
+ }
+ catch (FormatException e)
+ {
+ throw new XmlException(FeedUtils.AddLineInfo(reader, SR.ErrorParsingFeed), e);
+ }
+ catch (ArgumentException e)
+ {
+ throw new XmlException(FeedUtils.AddLineInfo(reader, SR.ErrorParsingFeed), e);
+ }
+ finally
+ {
+ if (extWriter != null)
+ {
+ ((IDisposable)extWriter).Dispose();
+ }
+ }
+ }
+ if (!isSourceFeed)
+ {
+ await reader.ReadEndElementAsync(); // feed
+ }
+
+ return result;
+ }
+
+
+ private async Task ReadItemFromAsync(XmlReaderWrapper reader, SyndicationItem result, Uri feedBaseUri)
+ {
+ try
+ {
+ result.BaseUri = feedBaseUri;
+ await MoveToStartElementAsync(reader);
+ bool isEmpty = reader.IsEmptyElement;
+ if (reader.HasAttributes)
+ {
+ while (reader.MoveToNextAttribute())
+ {
+ string ns = reader.NamespaceURI;
+ string name = reader.LocalName;
+ if (name == "base" && ns == XmlNs)
+ {
+ result.BaseUri = FeedUtils.CombineXmlBase(result.BaseUri, await reader.GetValueAsync());
+ continue;
+ }
+
+ if (FeedUtils.IsXmlns(name, ns) || FeedUtils.IsXmlSchemaType(name, ns))
+ {
+ continue;
+ }
+
+ string val = await reader.GetValueAsync();
+ if (!TryParseAttribute(name, ns, val, result, this.Version))
+ {
+ if (_preserveAttributeExtensions)
+ {
+ result.AttributeExtensions.Add(new XmlQualifiedName(reader.LocalName, reader.NamespaceURI), reader.Value);
+ }
+ }
+ }
+ }
+ await reader.ReadStartElementAsync();
+
+ if (!isEmpty)
+ {
+ XmlBuffer buffer = null;
+ XmlDictionaryWriter extWriter = null;
+ try
+ {
+ while (await reader.IsStartElementAsync())
+ {
+ if (await TryParseItemElementFromAsync(reader, result))
+ {
+ // nothing, we parsed something, great
+ }
+ else
+ {
+ if (!TryParseElement(reader, result, this.Version))
+ {
+ if (_preserveElementExtensions)
+ {
+ var tuple = await CreateBufferIfRequiredAndWriteNodeAsync(buffer, extWriter, reader, _maxExtensionSize);
+ buffer = tuple.Item1;
+ extWriter = tuple.Item2;
+ }
+ else
+ {
+ await reader.SkipAsync();
+ }
+ }
+ }
+ }
+ LoadElementExtensions(buffer, extWriter, result);
+ }
+ finally
+ {
+ if (extWriter != null)
+ {
+ ((IDisposable)extWriter).Dispose();
+ }
+ }
+ await reader.ReadEndElementAsync(); // item
+ }
+ }
+ catch (FormatException e)
+ {
+ throw new XmlException(FeedUtils.AddLineInfo(reader, SR.ErrorParsingItem), e);
+
+ }
+ catch (ArgumentException e)
+ {
+ throw new XmlException(FeedUtils.AddLineInfo(reader, SR.ErrorParsingItem), e);
+ }
+ }
+
+ private async Task ReadLinkAsync(XmlReaderWrapper reader, SyndicationLink link, Uri baseUri)
+ {
+ bool isEmpty = reader.IsEmptyElement;
+ string mediaType = null;
+ string relationship = null;
+ string title = null;
+ string lengthStr = null;
+ string val = null;
+ string ns = null;
+ link.BaseUri = baseUri;
+ if (reader.HasAttributes)
+ {
+ while (reader.MoveToNextAttribute())
+ {
+ bool notHandled = false;
+ if (reader.LocalName == "base" && reader.NamespaceURI == XmlNs)
+ {
+ link.BaseUri = FeedUtils.CombineXmlBase(link.BaseUri, await reader.GetValueAsync());
+ }
+ else if(reader.NamespaceURI == string.Empty)
+ {
+ switch (reader.LocalName)
+ {
+ case Atom10Constants.TypeTag:
+ mediaType = await reader.GetValueAsync();
+ break;
+ case Atom10Constants.RelativeTag:
+ relationship = await reader.GetValueAsync();
+ break;
+ case Atom10Constants.TitleTag:
+ title = await reader.GetValueAsync();
+ break;
+ case Atom10Constants.LengthTag:
+ lengthStr = await reader.GetValueAsync();
+ break;
+ case Atom10Constants.HrefTag:
+ val = await reader.GetValueAsync();
+ ns = reader.NamespaceURI;
+ break;
+ default:
+ notHandled = true;
+ break;
+ }
+ }
+ else
+ {
+ notHandled = true;
+ }
+
+ if (notHandled && !FeedUtils.IsXmlns(reader.LocalName, reader.NamespaceURI))
+ {
+ if (_preserveAttributeExtensions)
+ {
+ link.AttributeExtensions.Add(new XmlQualifiedName(reader.LocalName, reader.NamespaceURI), await reader.GetValueAsync());
+ }
+ }
+ }
+ }
+
+ long length = 0;
+ if (!string.IsNullOrEmpty(lengthStr))
+ {
+ length = Convert.ToInt64(lengthStr, CultureInfo.InvariantCulture.NumberFormat);
+ }
+
+ await reader.ReadStartElementAsync();
+ if (!isEmpty)
+ {
+ XmlBuffer buffer = null;
+ XmlDictionaryWriter extWriter = null;
+ try
+ {
+ while (await reader.IsStartElementAsync())
+ {
+ if (TryParseElement(reader, link, this.Version))
+ {
+ continue;
+ }
+ else if (!_preserveElementExtensions)
+ {
+ await reader.SkipAsync();
+ }
+ else
+ {
+ if (buffer == null)
+ {
+ buffer = new XmlBuffer(_maxExtensionSize);
+ extWriter = buffer.OpenSection(XmlDictionaryReaderQuotas.Max);
+ extWriter.WriteStartElement(Rss20Constants.ExtensionWrapperTag);
+ }
+
+ await XmlReaderWrapper.WriteNodeAsync(extWriter, reader, false);
+ }
+ }
+
+ LoadElementExtensions(buffer, extWriter, link);
+ }
+ finally
+ {
+ if (extWriter != null)
+ {
+ ((IDisposable)extWriter).Dispose();
+ }
+ }
+
+ await reader.ReadEndElementAsync();
+ }
+
+ link.Length = length;
+ link.MediaType = mediaType;
+ link.RelationshipType = relationship;
+ link.Title = title;
+ link.Uri = (val != null) ? uriParser(val,UriKind.RelativeOrAbsolute,Atom10Constants.LinkTag,ns) /*new Uri(val, UriKind.RelativeOrAbsolute)*/ : null;
+ }
+
+ private async Task<SyndicationLink> ReadLinkFromAsync(XmlReaderWrapper reader, SyndicationFeed feed)
+ {
+ SyndicationLink result = CreateLink(feed);
+ await ReadLinkAsync(reader, result, feed.BaseUri);
+ return result;
+ }
+
+ private async Task<SyndicationLink> ReadLinkFromAsync(XmlReaderWrapper reader, SyndicationItem item)
+ {
+ SyndicationLink result = CreateLink(item);
+ await ReadLinkAsync(reader, result, item.BaseUri);
+ return result;
+ }
+
+ private async Task<SyndicationPerson> ReadPersonFromAsync(XmlReaderWrapper reader, SyndicationFeed feed)
+ {
+ SyndicationPerson result = CreatePerson(feed);
+ await ReadPersonFromAsync(reader, result);
+ return result;
+ }
+
+ private async Task<SyndicationPerson> ReadPersonFromAsync(XmlReaderWrapper reader, SyndicationItem item)
+ {
+ SyndicationPerson result = CreatePerson(item);
+ await ReadPersonFromAsync(reader, result);
+ return result;
+ }
+
+ private async Task ReadPersonFromAsync(XmlReaderWrapper reader, SyndicationPerson result)
+ {
+ bool isEmpty = reader.IsEmptyElement;
+ if (reader.HasAttributes)
+ {
+ while (reader.MoveToNextAttribute())
+ {
+ string ns = reader.NamespaceURI;
+ string name = reader.LocalName;
+ if (FeedUtils.IsXmlns(name, ns))
+ {
+ continue;
+ }
+ string val = await reader.GetValueAsync();
+ if (!TryParseAttribute(name, ns, val, result, this.Version))
+ {
+ if (_preserveAttributeExtensions)
+ {
+ result.AttributeExtensions.Add(new XmlQualifiedName(reader.LocalName, reader.NamespaceURI), await reader.GetValueAsync());
+ }
+ }
+ }
+ }
+
+ await reader.ReadStartElementAsync();
+ if (!isEmpty)
+ {
+ XmlBuffer buffer = null;
+ XmlDictionaryWriter extWriter = null;
+ try
+ {
+ while (await reader.IsStartElementAsync())
+ {
+ string name = reader.LocalName;
+ string ns = reader.NamespaceURI;
+ bool notHandled = false;
+
+ switch (name)
+ {
+ case Atom10Constants.NameTag:
+ result.Name = stringParser(await reader.ReadElementStringAsync(),Atom10Constants.NameTag,ns);
+ break;
+ case Atom10Constants.UriTag:
+ result.Uri = stringParser(await reader.ReadElementStringAsync(),Atom10Constants.UriTag,ns);
+ break;
+ case Atom10Constants.EmailTag:
+ result.Email = stringParser(await reader.ReadElementStringAsync(),Atom10Constants.EmailTag,ns);
+ break;
+ default:
+ notHandled = true;
+ break;
+ }
+
+ if(notHandled && !TryParseElement(reader, result, this.Version))
+ {
+ if (_preserveElementExtensions)
+ {
+ if (buffer == null)
+ {
+ buffer = new XmlBuffer(_maxExtensionSize);
+ extWriter = buffer.OpenSection(XmlDictionaryReaderQuotas.Max);
+ extWriter.WriteStartElement(Rss20Constants.ExtensionWrapperTag);
+ }
+
+ await XmlReaderWrapper.WriteNodeAsync(extWriter, reader, false);
+ }
+ else
+ {
+ await reader.SkipAsync();
+ }
+ }
+ }
+
+ LoadElementExtensions(buffer, extWriter, result);
+ }
+ finally
+ {
+ if (extWriter != null)
+ {
+ ((IDisposable)extWriter).Dispose();
+ }
+ }
+
+ await reader.ReadEndElementAsync();
+ }
+ }
+
+ private Task<TextSyndicationContent> ReadTextContentFromAsync(XmlReaderWrapper reader, string context)
+ {
+ return ReadTextContentFromAsync(reader, context, this.PreserveAttributeExtensions);
+ }
+
+ private async Task WriteCategoriesToAsync(XmlWriter writer, Collection<SyndicationCategory> categories)
+ {
+ writer = XmlWriterWrapper.CreateFromWriter(writer);
+ for (int i = 0; i < categories.Count; ++i)
+ {
+ await WriteCategoryAsync(writer, categories[i], this.Version);
+ }
+ }
+
+ private Task WriteFeedAsync(XmlWriter writer)
+ {
+ if (this.Feed == null)
+ {
+ throw new InvalidOperationException(SR.FeedFormatterDoesNotHaveFeed);
+ }
+ return WriteFeedToAsync(writer, this.Feed, false); // isSourceFeed
+ }
+
+ private async Task WriteFeedToAsync(XmlWriter writer, SyndicationFeed feed, bool isSourceFeed)
+ {
+ if (!isSourceFeed)
+ {
+ if (!string.IsNullOrEmpty(feed.Language))
+ {
+ await writer.WriteAttributeStringAsync("xml", "lang", XmlNs, feed.Language);
+ }
+ if (feed.BaseUri != null)
+ {
+ await writer.InternalWriteAttributeStringAsync("xml", "base", XmlNs, FeedUtils.GetUriString(feed.BaseUri));
+ }
+ await WriteAttributeExtensionsAsync(writer, feed, this.Version);
+ }
+ bool isElementRequired = !isSourceFeed;
+ TextSyndicationContent title = feed.Title;
+ if (isElementRequired)
+ {
+ title = title ?? new TextSyndicationContent(string.Empty);
+ }
+ await WriteContentToAsync(writer, Atom10Constants.TitleTag, title);
+ await WriteContentToAsync(writer, Atom10Constants.SubtitleTag, feed.Description);
+ string id = feed.Id;
+ if (isElementRequired)
+ {
+ id = id ?? s_idGenerator.Next();
+ }
+ await WriteElementAsync(writer, Atom10Constants.IdTag, id);
+ await WriteContentToAsync(writer, Atom10Constants.RightsTag, feed.Copyright);
+ await WriteFeedLastUpdatedTimeToAsync(writer, feed.LastUpdatedTime, isElementRequired);
+ await WriteCategoriesToAsync(writer, feed.Categories);
+ if (feed.ImageUrl != null)
+ {
+ await WriteElementAsync(writer, Atom10Constants.LogoTag, feed.ImageUrl.ToString());
+ }
+ await WriteFeedAuthorsToAsync(writer, feed.Authors);
+ await WriteFeedContributorsToAsync(writer, feed.Contributors);
+ await WriteElementAsync(writer, Atom10Constants.GeneratorTag, feed.Generator);
+
+ if(feed.IconImage != null)
+ {
+ await WriteElementAsync(writer, Atom10Constants.IconTag, feed.IconImage.AbsoluteUri);
+ }
+
+ for (int i = 0; i < feed.Links.Count; ++i)
+ {
+ await WriteLinkAsync(writer, feed.Links[i], feed.BaseUri);
+ }
+
+ await WriteElementExtensionsAsync(writer, feed, this.Version);
+
+ if (!isSourceFeed)
+ {
+ await WriteItemsAsync(writer, feed.Items, feed.BaseUri);
+ }
+ }
+
+ private async Task WriteItemContentsAsync(XmlWriter dictWriter, SyndicationItem item, Uri feedBaseUri)
+ {
+ Uri baseUriToWrite = FeedUtils.GetBaseUriToWrite(feedBaseUri, item.BaseUri);
+ if (baseUriToWrite != null)
+ {
+ await dictWriter.InternalWriteAttributeStringAsync("xml", "base", XmlNs, FeedUtils.GetUriString(baseUriToWrite));
+ }
+ await WriteAttributeExtensionsAsync(dictWriter, item, this.Version);
+
+ string id = item.Id ?? s_idGenerator.Next();
+ await WriteElementAsync(dictWriter, Atom10Constants.IdTag, id);
+
+ TextSyndicationContent title = item.Title ?? new TextSyndicationContent(string.Empty);
+ await WriteContentToAsync(dictWriter, Atom10Constants.TitleTag, title);
+ await WriteContentToAsync(dictWriter, Atom10Constants.SummaryTag, item.Summary);
+ if (item.PublishDate != DateTimeOffset.MinValue)
+ {
+ await dictWriter.WriteElementStringAsync(Atom10Constants.PublishedTag,
+ Atom10Constants.Atom10Namespace,
+ AsString(item.PublishDate));
+ }
+ await WriteItemLastUpdatedTimeToAsync(dictWriter, item.LastUpdatedTime);
+ await WriteItemAuthorsToAsync(dictWriter, item.Authors);
+ await WriteItemContributorsToAsync(dictWriter, item.Contributors);
+ for (int i = 0; i < item.Links.Count; ++i)
+ {
+ await WriteLinkAsync(dictWriter, item.Links[i], item.BaseUri);
+ }
+ await WriteCategoriesToAsync(dictWriter, item.Categories);
+ await WriteContentToAsync(dictWriter, Atom10Constants.ContentTag, item.Content);
+ await WriteContentToAsync(dictWriter, Atom10Constants.RightsTag, item.Copyright);
+ if (item.SourceFeed != null)
+ {
+ await dictWriter.WriteStartElementAsync(Atom10Constants.SourceFeedTag, Atom10Constants.Atom10Namespace);
+ await WriteFeedToAsync(dictWriter, item.SourceFeed, true); // isSourceFeed
+ await dictWriter.WriteEndElementAsync();
+ }
+ await WriteElementExtensionsAsync(dictWriter, item, this.Version);
+ }
+
+ private async Task WritePersonToAsync(XmlWriter writer, SyndicationPerson p, string elementName)
+ {
+ await writer.WriteStartElementAsync(elementName, Atom10Constants.Atom10Namespace);
+ await WriteAttributeExtensionsAsync(writer, p, this.Version);
+ await WriteElementAsync(writer, Atom10Constants.NameTag, p.Name);
+ if (!string.IsNullOrEmpty(p.Uri))
+ {
+ await writer.WriteElementStringAsync(Atom10Constants.UriTag, Atom10Constants.Atom10Namespace, p.Uri);
+ }
+ if (!string.IsNullOrEmpty(p.Email))
+ {
+ await writer.WriteElementStringAsync(Atom10Constants.EmailTag, Atom10Constants.Atom10Namespace, p.Email);
+ }
+ await WriteElementExtensionsAsync(writer, p, this.Version);
+ await writer.WriteEndElementAsync();
+ }
+ }
+
+ [XmlRoot(ElementName = Atom10Constants.FeedTag, Namespace = Atom10Constants.Atom10Namespace)]
+ public class Atom10FeedFormatter<TSyndicationFeed> : Atom10FeedFormatter
+ where TSyndicationFeed : SyndicationFeed, new()
+ {
+ // constructors
+ public Atom10FeedFormatter()
+ : base(typeof(TSyndicationFeed))
+ {
+ }
+ public Atom10FeedFormatter(TSyndicationFeed feedToWrite)
+ : base(feedToWrite)
+ {
+ }
+
+ protected override SyndicationFeed CreateFeedInstance()
+ {
+ return new TSyndicationFeed();
+ }
+ }
+}
diff --git a/src/System.ServiceModel.Syndication/src/System/ServiceModel/Syndication/Atom10ItemFormatter.cs b/src/System.ServiceModel.Syndication/src/System/ServiceModel/Syndication/Atom10ItemFormatter.cs
new file mode 100644
index 0000000000..8fe387d1e5
--- /dev/null
+++ b/src/System.ServiceModel.Syndication/src/System/ServiceModel/Syndication/Atom10ItemFormatter.cs
@@ -0,0 +1,168 @@
+// 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.
+
+
+/*
+ * Some diagnostic lines have been commented
+ *
+ * */
+
+namespace System.ServiceModel.Syndication
+{
+ using System;
+ using System.Diagnostics.CodeAnalysis;
+ using System.Runtime.CompilerServices;
+ using System.Threading.Tasks;
+ using System.Xml;
+ using System.Xml.Schema;
+ using System.Xml.Serialization;
+
+ [XmlRoot(ElementName = Atom10Constants.EntryTag, Namespace = Atom10Constants.Atom10Namespace)]
+ public class Atom10ItemFormatter : SyndicationItemFormatter
+ {
+ private Atom10FeedFormatter _feedSerializer;
+ private Type _itemType;
+ private bool _preserveAttributeExtensions;
+ private bool _preserveElementExtensions;
+
+ public Atom10ItemFormatter()
+ : this(typeof(SyndicationItem))
+ {
+ }
+
+ public Atom10ItemFormatter(Type itemTypeToCreate)
+ : base()
+ {
+ if (itemTypeToCreate == null)
+ {
+ throw new ArgumentNullException(nameof(itemTypeToCreate));
+ }
+ if (!typeof(SyndicationItem).IsAssignableFrom(itemTypeToCreate))
+ {
+ throw new ArgumentException(string.Format(SR.InvalidObjectTypePassed, nameof(itemTypeToCreate), nameof(SyndicationItem)));
+ }
+ _feedSerializer = new Atom10FeedFormatter();
+ _feedSerializer.PreserveAttributeExtensions = _preserveAttributeExtensions = true;
+ _feedSerializer.PreserveElementExtensions = _preserveElementExtensions = true;
+ _itemType = itemTypeToCreate;
+ }
+
+ public Atom10ItemFormatter(SyndicationItem itemToWrite)
+ : base(itemToWrite)
+ {
+ // No need to check that the parameter passed is valid - it is checked by the c'tor of the base class
+ _feedSerializer = new Atom10FeedFormatter();
+ _feedSerializer.PreserveAttributeExtensions = _preserveAttributeExtensions = true;
+ _feedSerializer.PreserveElementExtensions = _preserveElementExtensions = true;
+ _itemType = itemToWrite.GetType();
+ }
+
+ public bool PreserveAttributeExtensions
+ {
+ get { return _preserveAttributeExtensions; }
+ set
+ {
+ _preserveAttributeExtensions = value;
+ _feedSerializer.PreserveAttributeExtensions = value;
+ }
+ }
+
+ public bool PreserveElementExtensions
+ {
+ get { return _preserveElementExtensions; }
+ set
+ {
+ _preserveElementExtensions = value;
+ _feedSerializer.PreserveElementExtensions = value;
+ }
+ }
+
+ public override string Version
+ {
+ get { return SyndicationVersions.Atom10; }
+ }
+
+ protected Type ItemType
+ {
+ get
+ {
+ return _itemType;
+ }
+ }
+
+ public override bool CanRead(XmlReader reader)
+ {
+ if (reader == null)
+ {
+ throw new ArgumentNullException(nameof(reader));
+ }
+ return reader.IsStartElement(Atom10Constants.EntryTag, Atom10Constants.Atom10Namespace);
+ }
+
+ public override Task ReadFromAsync(XmlReader reader)
+ {
+ if (!CanRead(reader))
+ {
+ throw new XmlException(string.Format(SR.UnknownItemXml, reader.LocalName, reader.NamespaceURI));
+ }
+
+ return ReadItemAsync(reader);
+ }
+
+ public override async Task WriteToAsync(XmlWriter writer)
+ {
+ if (writer == null)
+ {
+ throw new ArgumentNullException(nameof(writer));
+ }
+
+ writer = XmlWriterWrapper.CreateFromWriter(writer);
+
+ await writer.WriteStartElementAsync(Atom10Constants.EntryTag, Atom10Constants.Atom10Namespace);
+ await WriteItemAsync(writer);
+ await writer.WriteEndElementAsync();
+ }
+
+ protected override SyndicationItem CreateItemInstance()
+ {
+ return SyndicationItemFormatter.CreateItemInstance(_itemType);
+ }
+
+ private Task ReadItemAsync(XmlReader reader)
+ {
+ SetItem(CreateItemInstance());
+ return _feedSerializer.ReadItemFromAsync(XmlReaderWrapper.CreateFromReader(XmlDictionaryReader.CreateDictionaryReader(reader)), this.Item);
+ }
+
+ private Task WriteItemAsync(XmlWriter writer)
+ {
+ if (this.Item == null)
+ {
+ throw new InvalidOperationException(SR.ItemFormatterDoesNotHaveItem);
+ }
+ XmlDictionaryWriter w = XmlDictionaryWriter.CreateDictionaryWriter(writer);
+ return _feedSerializer.WriteItemContentsAsync(w, this.Item);
+ }
+ }
+
+ [XmlRoot(ElementName = Atom10Constants.EntryTag, Namespace = Atom10Constants.Atom10Namespace)]
+ public class Atom10ItemFormatter<TSyndicationItem> : Atom10ItemFormatter
+ where TSyndicationItem : SyndicationItem, new()
+ {
+ // constructors
+ public Atom10ItemFormatter()
+ : base(typeof(TSyndicationItem))
+ {
+ }
+ public Atom10ItemFormatter(TSyndicationItem itemToWrite)
+ : base(itemToWrite)
+ {
+ }
+
+ protected override SyndicationItem CreateItemInstance()
+ {
+ return new TSyndicationItem();
+ }
+ }
+}
diff --git a/src/System.ServiceModel.Syndication/src/System/ServiceModel/Syndication/AtomPub10CategoriesDocumentFormatter.cs b/src/System.ServiceModel.Syndication/src/System/ServiceModel/Syndication/AtomPub10CategoriesDocumentFormatter.cs
new file mode 100644
index 0000000000..53314beee1
--- /dev/null
+++ b/src/System.ServiceModel.Syndication/src/System/ServiceModel/Syndication/AtomPub10CategoriesDocumentFormatter.cs
@@ -0,0 +1,214 @@
+// 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.ServiceModel.Syndication
+{
+
+ using System;
+ using System.Runtime.CompilerServices;
+ using System.Threading.Tasks;
+ using System.Xml;
+ using System.Xml.Serialization;
+
+ [XmlRoot(ElementName = App10Constants.Categories, Namespace = App10Constants.Namespace)]
+ public class AtomPub10CategoriesDocumentFormatter : CategoriesDocumentFormatter
+ {
+ private Type _inlineDocumentType;
+ private int _maxExtensionSize;
+ private bool _preserveAttributeExtensions;
+ private bool _preserveElementExtensions;
+ private Type _referencedDocumentType;
+
+ public AtomPub10CategoriesDocumentFormatter()
+ : this(typeof(InlineCategoriesDocument), typeof(ReferencedCategoriesDocument))
+ {
+ }
+
+ public AtomPub10CategoriesDocumentFormatter(Type inlineDocumentType, Type referencedDocumentType)
+ : base()
+ {
+ if (inlineDocumentType == null)
+ {
+ throw new ArgumentNullException(nameof(inlineDocumentType));
+ }
+
+ if (!typeof(InlineCategoriesDocument).IsAssignableFrom(inlineDocumentType))
+ {
+ throw new ArgumentException(string.Format(SR.InvalidObjectTypePassed, nameof(inlineDocumentType), nameof(InlineCategoriesDocument)));
+ }
+
+ if (referencedDocumentType == null)
+ {
+ throw new ArgumentNullException(nameof(referencedDocumentType));
+ }
+
+ if (!typeof(ReferencedCategoriesDocument).IsAssignableFrom(referencedDocumentType))
+ {
+ throw new ArgumentException(string.Format(SR.InvalidObjectTypePassed, nameof(referencedDocumentType), nameof(ReferencedCategoriesDocument)));
+ }
+
+ _maxExtensionSize = int.MaxValue;
+ _preserveAttributeExtensions = true;
+ _preserveElementExtensions = true;
+ _inlineDocumentType = inlineDocumentType;
+ _referencedDocumentType = referencedDocumentType;
+ }
+
+ public AtomPub10CategoriesDocumentFormatter(CategoriesDocument documentToWrite)
+ : base(documentToWrite)
+ {
+ // No need to check that the parameter passed is valid - it is checked by the c'tor of the base class
+ _maxExtensionSize = int.MaxValue;
+ _preserveAttributeExtensions = true;
+ _preserveElementExtensions = true;
+ if (documentToWrite.IsInline)
+ {
+ _inlineDocumentType = documentToWrite.GetType();
+ _referencedDocumentType = typeof(ReferencedCategoriesDocument);
+ }
+ else
+ {
+ _referencedDocumentType = documentToWrite.GetType();
+ _inlineDocumentType = typeof(InlineCategoriesDocument);
+ }
+ }
+
+ public override string Version
+ {
+ get { return App10Constants.Namespace; }
+ }
+
+ public override Task<bool> CanReadAsync(XmlReader reader)
+ {
+ if (reader == null)
+ {
+ throw new ArgumentNullException(nameof(reader));
+ }
+
+ XmlReaderWrapper wrappedReader = XmlReaderWrapper.CreateFromReader(reader);
+ return wrappedReader.IsStartElementAsync(App10Constants.Categories, App10Constants.Namespace);
+ }
+
+
+
+ Task ReadXmlAsync(XmlReaderWrapper reader)
+ {
+ if (reader == null)
+ {
+ throw new ArgumentNullException(nameof(reader));
+ }
+
+ return ReadDocumentAsync(reader);
+ }
+
+ Task WriteXmlAsync(XmlWriter writer)
+ {
+ if (writer == null)
+ {
+ throw new ArgumentNullException(nameof(writer));
+ }
+
+ if (this.Document == null)
+ {
+ throw new InvalidOperationException(SR.DocumentFormatterDoesNotHaveDocument);
+ }
+
+ return WriteDocumentAsync(writer);
+ }
+
+ public override async Task ReadFromAsync(XmlReader reader)
+ {
+ if (reader == null)
+ {
+ throw new ArgumentNullException(nameof(reader));
+ }
+
+ if (!await CanReadAsync(reader))
+ {
+ throw new XmlException(string.Format(SR.UnknownDocumentXml, reader.LocalName, reader.NamespaceURI));
+ }
+
+ await ReadDocumentAsync(XmlReaderWrapper.CreateFromReader(reader));
+ }
+
+ public override async Task WriteTo(XmlWriter writer)
+ {
+ if (writer == null)
+ {
+ throw new ArgumentNullException(nameof(writer));
+ }
+
+ if (this.Document == null)
+ {
+ throw new InvalidOperationException(SR.DocumentFormatterDoesNotHaveDocument);
+ }
+
+ writer.WriteStartElement(App10Constants.Prefix, App10Constants.Categories, App10Constants.Namespace);
+ await WriteDocumentAsync(writer);
+ writer.WriteEndElement();
+ }
+
+ protected override InlineCategoriesDocument CreateInlineCategoriesDocument()
+ {
+ if (_inlineDocumentType == typeof(InlineCategoriesDocument))
+ {
+ return new InlineCategoriesDocument();
+ }
+ else
+ {
+ return (InlineCategoriesDocument)Activator.CreateInstance(_inlineDocumentType);
+ }
+ }
+
+ protected override ReferencedCategoriesDocument CreateReferencedCategoriesDocument()
+ {
+ if (_referencedDocumentType == typeof(ReferencedCategoriesDocument))
+ {
+ return new ReferencedCategoriesDocument();
+ }
+ else
+ {
+ return (ReferencedCategoriesDocument)Activator.CreateInstance(_referencedDocumentType);
+ }
+ }
+
+ private async Task ReadDocumentAsync(XmlReaderWrapper reader)
+ {
+ try
+ {
+ await SyndicationFeedFormatter.MoveToStartElementAsync(reader);
+ SetDocument(await AtomPub10ServiceDocumentFormatter.ReadCategories(reader, null,
+ delegate ()
+ {
+ return this.CreateInlineCategoriesDocument();
+ },
+
+ delegate ()
+ {
+ return this.CreateReferencedCategoriesDocument();
+ },
+ this.Version,
+ _preserveElementExtensions,
+ _preserveAttributeExtensions,
+ _maxExtensionSize));
+ }
+ catch (FormatException e)
+ {
+ throw new XmlException(FeedUtils.AddLineInfo(reader, SR.ErrorParsingDocument), e);
+ }
+ catch (ArgumentException e)
+ {
+ throw new XmlException(FeedUtils.AddLineInfo(reader, SR.ErrorParsingDocument), e);
+ }
+ }
+
+ private Task WriteDocumentAsync(XmlWriter writer)
+ {
+ // declare the atom10 namespace upfront for compactness
+ writer.WriteAttributeString(Atom10Constants.Atom10Prefix, Atom10FeedFormatter.XmlNsNs, Atom10Constants.Atom10Namespace);
+ return AtomPub10ServiceDocumentFormatter.WriteCategoriesInnerXml(writer, this.Document, null, this.Version);
+ }
+ }
+}
diff --git a/src/System.ServiceModel.Syndication/src/System/ServiceModel/Syndication/AtomPub10ServiceDocumentFormatter.cs b/src/System.ServiceModel.Syndication/src/System/ServiceModel/Syndication/AtomPub10ServiceDocumentFormatter.cs
new file mode 100644
index 0000000000..61f83aba3f
--- /dev/null
+++ b/src/System.ServiceModel.Syndication/src/System/ServiceModel/Syndication/AtomPub10ServiceDocumentFormatter.cs
@@ -0,0 +1,792 @@
+// 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.ServiceModel.Syndication
+{
+
+ using System;
+ using System.Diagnostics.CodeAnalysis;
+ using System.Runtime.CompilerServices;
+ using System.Threading.Tasks;
+ using System.Xml;
+ using System.Xml.Schema;
+ using System.Xml.Serialization;
+
+ internal delegate InlineCategoriesDocument CreateInlineCategoriesDelegate();
+ internal delegate ReferencedCategoriesDocument CreateReferencedCategoriesDelegate();
+
+ [XmlRoot(ElementName = App10Constants.Service, Namespace = App10Constants.Namespace)]
+ public class AtomPub10ServiceDocumentFormatter : ServiceDocumentFormatter
+ {
+ private Type _documentType;
+ private int _maxExtensionSize;
+ private bool _preserveAttributeExtensions;
+ private bool _preserveElementExtensions;
+
+ public AtomPub10ServiceDocumentFormatter()
+ : this(typeof(ServiceDocument))
+ {
+ }
+
+ public AtomPub10ServiceDocumentFormatter(Type documentTypeToCreate)
+ : base()
+ {
+ if (documentTypeToCreate == null)
+ {
+ throw new ArgumentNullException(nameof(documentTypeToCreate));
+ }
+ if (!typeof(ServiceDocument).IsAssignableFrom(documentTypeToCreate))
+ {
+ throw new ArgumentException(string.Format(SR.InvalidObjectTypePassed, nameof(documentTypeToCreate), nameof(ServiceDocument)));
+ }
+ _maxExtensionSize = int.MaxValue;
+ _preserveAttributeExtensions = true;
+ _preserveElementExtensions = true;
+ _documentType = documentTypeToCreate;
+ }
+
+ public AtomPub10ServiceDocumentFormatter(ServiceDocument documentToWrite)
+ : base(documentToWrite)
+ {
+ // No need to check that the parameter passed is valid - it is checked by the c'tor of the base class
+ _maxExtensionSize = int.MaxValue;
+ _preserveAttributeExtensions = true;
+ _preserveElementExtensions = true;
+ _documentType = documentToWrite.GetType();
+ }
+
+ public override string Version
+ {
+ get { return App10Constants.Namespace; }
+ }
+
+ public override Task<bool> CanReadAsync(XmlReader reader)
+ {
+ if (reader == null)
+ {
+ throw new ArgumentNullException(nameof(reader));
+ }
+
+ XmlReaderWrapper readerWrapper = XmlReaderWrapper.CreateFromReader(reader);
+ return readerWrapper.IsStartElementAsync(App10Constants.Service, App10Constants.Namespace);
+ }
+
+ Task ReadXml(XmlReaderWrapper reader)
+ {
+ if (reader == null)
+ {
+ throw new ArgumentNullException(nameof(reader));
+ }
+
+ return ReadDocumentAsync(reader);
+ }
+
+ Task WriteXml(XmlWriter writer)
+ {
+ if (writer == null)
+ {
+ throw new ArgumentNullException(nameof(writer));
+ }
+
+ if (this.Document == null)
+ {
+ throw new InvalidOperationException(SR.DocumentFormatterDoesNotHaveDocument);
+ }
+
+ return WriteDocumentAsync(XmlWriterWrapper.CreateFromWriter(writer));
+ }
+
+ public override async Task ReadFromAsync(XmlReader reader)
+ {
+ if (reader == null)
+ {
+ throw new ArgumentNullException(nameof(reader));
+ }
+
+ XmlReaderWrapper wrappedReader = XmlReaderWrapper.CreateFromReader(reader);
+ await wrappedReader.MoveToContentAsync();
+
+ if (!await CanReadAsync(reader))
+ {
+ throw new XmlException(string.Format(SR.UnknownDocumentXml, reader.LocalName, reader.NamespaceURI));
+ }
+
+ await ReadDocumentAsync(wrappedReader);
+ }
+
+ public override async Task WriteToAsync(XmlWriter writer)
+ {
+ if (writer == null)
+ {
+ throw new ArgumentNullException(nameof(writer));
+ }
+
+ if (this.Document == null)
+ {
+ throw new InvalidOperationException(SR.DocumentFormatterDoesNotHaveDocument);
+ }
+
+ writer = XmlWriterWrapper.CreateFromWriter(writer);
+
+ await writer.WriteStartElementAsync(App10Constants.Prefix, App10Constants.Service, App10Constants.Namespace);
+ await WriteDocumentAsync(writer);
+ await writer.WriteEndElementAsync();
+ }
+
+ internal static async Task<CategoriesDocument> ReadCategories(XmlReaderWrapper reader, Uri baseUri, CreateInlineCategoriesDelegate inlineCategoriesFactory, CreateReferencedCategoriesDelegate referencedCategoriesFactory, string version, bool preserveElementExtensions, bool preserveAttributeExtensions, int maxExtensionSize)
+ {
+ string link = reader.GetAttribute(App10Constants.Href, string.Empty);
+ if (string.IsNullOrEmpty(link))
+ {
+ InlineCategoriesDocument inlineCategories = inlineCategoriesFactory();
+ await ReadInlineCategoriesAsync(reader, inlineCategories, baseUri, version, preserveElementExtensions, preserveAttributeExtensions, maxExtensionSize);
+ return inlineCategories;
+ }
+ else
+ {
+ ReferencedCategoriesDocument referencedCategories = referencedCategoriesFactory();
+ await ReadReferencedCategoriesAsync(reader, referencedCategories, baseUri, new Uri(link, UriKind.RelativeOrAbsolute), version, preserveElementExtensions, preserveAttributeExtensions, maxExtensionSize);
+ return referencedCategories;
+ }
+ }
+
+
+
+ internal static async Task WriteCategoriesInnerXml(XmlWriter writer, CategoriesDocument categories, Uri baseUri, string version)
+ {
+ Uri baseUriToWrite = FeedUtils.GetBaseUriToWrite(baseUri, categories.BaseUri);
+ if (baseUriToWrite != null)
+ {
+ WriteXmlBase(writer, baseUriToWrite);
+ }
+
+ if (!string.IsNullOrEmpty(categories.Language))
+ {
+ WriteXmlLang(writer, categories.Language);
+ }
+
+ if (categories.IsInline)
+ {
+ await WriteInlineCategoriesContentAsync(XmlWriterWrapper.CreateFromWriter(writer), (InlineCategoriesDocument)categories, version);
+ }
+ else
+ {
+ WriteReferencedCategoriesContent(writer, (ReferencedCategoriesDocument)categories, version);
+ }
+ }
+
+ protected override ServiceDocument CreateDocumentInstance()
+ {
+ if (_documentType == typeof(ServiceDocument))
+ {
+ return new ServiceDocument();
+ }
+ else
+ {
+ return (ServiceDocument)Activator.CreateInstance(_documentType);
+ }
+ }
+
+ private static async Task ReadInlineCategoriesAsync(XmlReaderWrapper reader, InlineCategoriesDocument inlineCategories, Uri baseUri, string version, bool preserveElementExtensions, bool preserveAttributeExtensions, int _maxExtensionSize)
+ {
+ inlineCategories.BaseUri = baseUri;
+ if (reader.HasAttributes)
+ {
+ while (reader.MoveToNextAttribute())
+ {
+ if (reader.LocalName == "base" && reader.NamespaceURI == Atom10FeedFormatter.XmlNs)
+ {
+ inlineCategories.BaseUri = FeedUtils.CombineXmlBase(inlineCategories.BaseUri, await reader.GetValueAsync());
+ }
+ else if (reader.LocalName == "lang" && reader.NamespaceURI == Atom10FeedFormatter.XmlNs)
+ {
+ inlineCategories.Language = await reader.GetValueAsync();
+ }
+ else if (reader.LocalName == App10Constants.Fixed && reader.NamespaceURI == string.Empty)
+ {
+ inlineCategories.IsFixed = (reader.Value == "yes");
+ }
+ else if (reader.LocalName == Atom10Constants.SchemeTag && reader.NamespaceURI == string.Empty)
+ {
+ inlineCategories.Scheme = await reader.GetValueAsync();
+ }
+ else
+ {
+ string ns = reader.NamespaceURI;
+ string name = reader.LocalName;
+ if (FeedUtils.IsXmlns(name, ns) || FeedUtils.IsXmlSchemaType(name, ns))
+ {
+ continue;
+ }
+ string val = await reader.GetValueAsync();
+ if (!TryParseAttribute(name, ns, val, inlineCategories, version))
+ {
+ if (preserveAttributeExtensions)
+ {
+ inlineCategories.AttributeExtensions.Add(new XmlQualifiedName(reader.LocalName, reader.NamespaceURI), await reader.GetValueAsync());
+ }
+ }
+ }
+ }
+ }
+
+ await SyndicationFeedFormatter.MoveToStartElementAsync(reader);
+ bool isEmptyElement = reader.IsEmptyElement;
+ await reader.ReadStartElementAsync();
+ if (!isEmptyElement)
+ {
+ XmlBuffer buffer = null;
+ XmlDictionaryWriter extWriter = null;
+ try
+ {
+ while (await reader.IsStartElementAsync())
+ {
+ if (await reader.IsStartElementAsync(Atom10Constants.CategoryTag, Atom10Constants.Atom10Namespace))
+ {
+ SyndicationCategory category = CreateCategory(inlineCategories);
+ await Atom10FeedFormatter.ReadCategoryAsync(reader, category, version, preserveAttributeExtensions, preserveElementExtensions, _maxExtensionSize);
+ if (category.Scheme == null)
+ {
+ category.Scheme = inlineCategories.Scheme;
+ }
+
+ inlineCategories.Categories.Add(category);
+ }
+ else if (!TryParseElement(reader, inlineCategories, version))
+ {
+ if (preserveElementExtensions)
+ {
+ var tuple = await SyndicationFeedFormatter.CreateBufferIfRequiredAndWriteNodeAsync(buffer, extWriter, reader, _maxExtensionSize);
+ buffer = tuple.Item1;
+ extWriter = tuple.Item2;
+ }
+ else
+ {
+ await reader.SkipAsync();
+ }
+ }
+ }
+ LoadElementExtensions(buffer, extWriter, inlineCategories);
+ }
+ finally
+ {
+ if (extWriter != null)
+ {
+ extWriter.Close();
+ }
+ }
+
+ await reader.ReadEndElementAsync();
+ }
+ }
+
+ private static async Task ReadReferencedCategoriesAsync(XmlReaderWrapper reader, ReferencedCategoriesDocument referencedCategories, Uri baseUri, Uri link, string version, bool preserveElementExtensions, bool preserveAttributeExtensions, int maxExtensionSize)
+ {
+ referencedCategories.BaseUri = baseUri;
+ referencedCategories.Link = link;
+ if (reader.HasAttributes)
+ {
+ while (reader.MoveToNextAttribute())
+ {
+ if (reader.LocalName == "base" && reader.NamespaceURI == Atom10FeedFormatter.XmlNs)
+ {
+ referencedCategories.BaseUri = FeedUtils.CombineXmlBase(referencedCategories.BaseUri, await reader.GetValueAsync());
+ }
+ else if (reader.LocalName == "lang" && reader.NamespaceURI == Atom10FeedFormatter.XmlNs)
+ {
+ referencedCategories.Language = await reader.GetValueAsync();
+ }
+ else if (reader.LocalName == App10Constants.Href && reader.NamespaceURI == string.Empty)
+ {
+ continue;
+ }
+ else
+ {
+ string ns = reader.NamespaceURI;
+ string name = reader.LocalName;
+ if (FeedUtils.IsXmlns(name, ns) || FeedUtils.IsXmlSchemaType(name, ns))
+ {
+ continue;
+ }
+
+ string val = await reader.GetValueAsync();
+ if (!TryParseAttribute(name, ns, val, referencedCategories, version))
+ {
+ if (preserveAttributeExtensions)
+ {
+ referencedCategories.AttributeExtensions.Add(new XmlQualifiedName(reader.LocalName, reader.NamespaceURI), await reader.GetValueAsync());
+ }
+ }
+ }
+ }
+ }
+
+ reader.MoveToElement();
+ bool isEmptyElement = reader.IsEmptyElement;
+ await reader.ReadStartElementAsync();
+ if (!isEmptyElement)
+ {
+ XmlBuffer buffer = null;
+ XmlDictionaryWriter extWriter = null;
+ try
+ {
+ while (await reader.IsStartElementAsync())
+ {
+ if (!TryParseElement(reader, referencedCategories, version))
+ {
+ if (preserveElementExtensions)
+ {
+ var tuple = await SyndicationFeedFormatter.CreateBufferIfRequiredAndWriteNodeAsync(buffer, extWriter, reader, maxExtensionSize);
+ buffer = tuple.Item1;
+ extWriter = tuple.Item2;
+ }
+ }
+ }
+
+ LoadElementExtensions(buffer, extWriter, referencedCategories);
+ }
+ finally
+ {
+ if (extWriter != null)
+ {
+ extWriter.Close();
+ }
+ }
+
+ await reader.ReadEndElementAsync();
+ }
+ }
+
+ private static async Task WriteCategoriesAsync(XmlWriter writer, CategoriesDocument categories, Uri baseUri, string version)
+ {
+ await writer.WriteStartElementAsync(App10Constants.Prefix, App10Constants.Categories, App10Constants.Namespace);
+ await WriteCategoriesInnerXml(writer, categories, baseUri, version);
+ await writer.WriteEndElementAsync();
+ }
+
+ private static async Task WriteInlineCategoriesContentAsync(XmlWriter writer, InlineCategoriesDocument categories, string version)
+ {
+ writer = XmlWriterWrapper.CreateFromWriter(writer);
+ if (!string.IsNullOrEmpty(categories.Scheme))
+ {
+ await writer.WriteAttributeStringAsync(Atom10Constants.SchemeTag, categories.Scheme);
+ }
+ // by default, categories are not fixed
+ if (categories.IsFixed)
+ {
+ await writer.WriteAttributeStringAsync(App10Constants.Fixed, "yes");
+ }
+
+ await WriteAttributeExtensionsAsync(writer, categories, version);
+
+ for (int i = 0; i < categories.Categories.Count; ++i)
+ {
+ await Atom10FeedFormatter.WriteCategoryAsync(writer, categories.Categories[i], version);
+ }
+
+ await WriteElementExtensionsAsync(writer, categories, version);
+ }
+
+ private static void WriteReferencedCategoriesContent(XmlWriter writer, ReferencedCategoriesDocument categories, string version)
+ {
+ if (categories.Link != null)
+ {
+ writer.WriteAttributeString(App10Constants.Href, FeedUtils.GetUriString(categories.Link));
+ }
+
+ WriteAttributeExtensionsAsync(writer, categories, version);
+ WriteElementExtensionsAsync(writer, categories, version);
+ }
+
+ private static void WriteXmlBase(XmlWriter writer, Uri baseUri)
+ {
+ writer.WriteAttributeString("xml", "base", Atom10FeedFormatter.XmlNs, FeedUtils.GetUriString(baseUri));
+ }
+
+ private static void WriteXmlLang(XmlWriter writer, string lang)
+ {
+ writer.WriteAttributeString("xml", "lang", Atom10FeedFormatter.XmlNs, lang);
+ }
+
+ private async Task<ResourceCollectionInfo> ReadCollection(XmlReaderWrapper reader, Workspace workspace)
+ {
+ ResourceCollectionInfo result = CreateCollection(workspace);
+ result.BaseUri = workspace.BaseUri;
+ if (reader.HasAttributes)
+ {
+ while (reader.MoveToNextAttribute())
+ {
+ if (reader.LocalName == "base" && reader.NamespaceURI == Atom10FeedFormatter.XmlNs)
+ {
+ result.BaseUri = FeedUtils.CombineXmlBase(result.BaseUri, await reader.GetValueAsync());
+ }
+ else if (reader.LocalName == App10Constants.Href && reader.NamespaceURI == string.Empty)
+ {
+ result.Link = new Uri(await reader.GetValueAsync(), UriKind.RelativeOrAbsolute);
+ }
+ else
+ {
+ string ns = reader.NamespaceURI;
+ string name = reader.LocalName;
+ if (FeedUtils.IsXmlns(name, ns) || FeedUtils.IsXmlSchemaType(name, ns))
+ {
+ continue;
+ }
+
+ string val = await reader.GetValueAsync();
+ if (!TryParseAttribute(name, ns, val, result, this.Version))
+ {
+ if (_preserveAttributeExtensions)
+ {
+ result.AttributeExtensions.Add(new XmlQualifiedName(reader.LocalName, reader.NamespaceURI), val);
+ }
+ }
+ }
+ }
+ }
+
+ XmlBuffer buffer = null;
+ XmlDictionaryWriter extWriter = null;
+
+ reader.ReadStartElement();
+ try
+ {
+ while (await reader.IsStartElementAsync())
+ {
+ if (await reader.IsStartElementAsync(Atom10Constants.TitleTag, Atom10Constants.Atom10Namespace))
+ {
+ result.Title = await new Atom10FeedFormatter().ReadTextContentFromAsync(reader, "//app:service/app:workspace/app:collection/atom:title[@type]", _preserveAttributeExtensions);
+ }
+ else if (await reader.IsStartElementAsync(App10Constants.Categories, App10Constants.Namespace))
+ {
+ result.Categories.Add(await ReadCategories(reader,
+ result.BaseUri,
+ delegate ()
+ {
+ return CreateInlineCategories(result);
+ },
+
+ delegate ()
+ {
+ return CreateReferencedCategories(result);
+ },
+ this.Version,
+ _preserveElementExtensions,
+ _preserveAttributeExtensions,
+ _maxExtensionSize));
+ }
+ else if (await reader.IsStartElementAsync(App10Constants.Accept, App10Constants.Namespace))
+ {
+ result.Accepts.Add(reader.ReadElementString());
+ }
+ else if (!TryParseElement(reader, result, this.Version))
+ {
+ if (_preserveElementExtensions)
+ {
+ if (buffer == null)
+ {
+ buffer = new XmlBuffer(_maxExtensionSize);
+ extWriter = buffer.OpenSection(XmlDictionaryReaderQuotas.Max);
+ extWriter.WriteStartElement(Rss20Constants.ExtensionWrapperTag);
+ }
+
+ await XmlReaderWrapper.WriteNodeAsync(extWriter, reader, false);
+ }
+ else
+ {
+ reader.Skip();
+ }
+ }
+ }
+
+ LoadElementExtensions(buffer, extWriter, result);
+ }
+ finally
+ {
+ if (extWriter != null)
+ {
+ extWriter.Close();
+ }
+ }
+
+ reader.ReadEndElement();
+ return result;
+ }
+
+ private async Task ReadDocumentAsync(XmlReaderWrapper reader)
+ {
+ ServiceDocument result = CreateDocumentInstance();
+ try
+ {
+ await SyndicationFeedFormatter.MoveToStartElementAsync(reader);
+ bool elementIsEmpty = reader.IsEmptyElement;
+ if (reader.HasAttributes)
+ {
+ while (reader.MoveToNextAttribute())
+ {
+ if (reader.LocalName == "lang" && reader.NamespaceURI == Atom10FeedFormatter.XmlNs)
+ {
+ result.Language = await reader.GetValueAsync();
+ }
+ else if (reader.LocalName == "base" && reader.NamespaceURI == Atom10FeedFormatter.XmlNs)
+ {
+ result.BaseUri = new Uri(await reader.GetValueAsync(), UriKind.RelativeOrAbsolute);
+ }
+ else
+ {
+ string ns = reader.NamespaceURI;
+ string name = reader.LocalName;
+ if (FeedUtils.IsXmlns(name, ns) || FeedUtils.IsXmlSchemaType(name, ns))
+ {
+ continue;
+ }
+
+ string val = await reader.GetValueAsync();
+ if (!TryParseAttribute(name, ns, val, result, this.Version))
+ {
+ if (_preserveAttributeExtensions)
+ {
+ result.AttributeExtensions.Add(new XmlQualifiedName(reader.LocalName, reader.NamespaceURI), val);
+ }
+ }
+ }
+ }
+ }
+ XmlBuffer buffer = null;
+ XmlDictionaryWriter extWriter = null;
+
+ await reader.ReadStartElementAsync();
+ if (!elementIsEmpty)
+ {
+ try
+ {
+ while (await reader.IsStartElementAsync())
+ {
+ if (await reader.IsStartElementAsync(App10Constants.Workspace, App10Constants.Namespace))
+ {
+ result.Workspaces.Add(ReadWorkspace(reader, result).Result);
+ }
+ else if (!TryParseElement(reader, result, this.Version))
+ {
+ if (_preserveElementExtensions)
+ {
+ var tuple = await SyndicationFeedFormatter.CreateBufferIfRequiredAndWriteNodeAsync(buffer, extWriter, reader, _maxExtensionSize);
+ buffer = tuple.Item1;
+ extWriter = tuple.Item2;
+ }
+ else
+ {
+ await reader.SkipAsync();
+ }
+ }
+ }
+
+ LoadElementExtensions(buffer, extWriter, result);
+ }
+ finally
+ {
+ if (extWriter != null)
+ {
+ extWriter.Close();
+ }
+ }
+ }
+
+ await reader.ReadEndElementAsync();
+ }
+ catch (FormatException e)
+ {
+ throw new XmlException(FeedUtils.AddLineInfo(reader, SR.ErrorParsingDocument), e);
+ }
+ catch (ArgumentException e)
+ {
+ new XmlException(FeedUtils.AddLineInfo(reader, SR.ErrorParsingDocument), e);
+ }
+
+ SetDocument(result);
+ }
+
+ private async Task<Workspace> ReadWorkspace(XmlReaderWrapper reader, ServiceDocument document)
+ {
+ Workspace result = CreateWorkspace(document);
+ result.BaseUri = document.BaseUri;
+ if (reader.HasAttributes)
+ {
+ while (reader.MoveToNextAttribute())
+ {
+ if (reader.LocalName == "base" && reader.NamespaceURI == Atom10FeedFormatter.XmlNs)
+ {
+ result.BaseUri = FeedUtils.CombineXmlBase(result.BaseUri,await reader.GetValueAsync());
+ }
+ else
+ {
+ string ns = reader.NamespaceURI;
+ string name = reader.LocalName;
+ if (FeedUtils.IsXmlns(name, ns) || FeedUtils.IsXmlSchemaType(name, ns))
+ {
+ continue;
+ }
+
+ string val = await reader.GetValueAsync();
+ if (!TryParseAttribute(name, ns, val, result, this.Version))
+ {
+ if (_preserveAttributeExtensions)
+ {
+ result.AttributeExtensions.Add(new XmlQualifiedName(reader.LocalName, reader.NamespaceURI), val);
+ }
+ }
+ }
+ }
+ }
+
+ XmlBuffer buffer = null;
+ XmlDictionaryWriter extWriter = null;
+ await reader.ReadStartElementAsync();
+ try
+ {
+ while (await reader.IsStartElementAsync())
+ {
+ if (await reader.IsStartElementAsync(Atom10Constants.TitleTag, Atom10Constants.Atom10Namespace))
+ {
+ result.Title = await new Atom10FeedFormatter().ReadTextContentFromAsync(reader, "//app:service/app:workspace/atom:title[@type]", _preserveAttributeExtensions);
+ }
+ else if (await reader.IsStartElementAsync(App10Constants.Collection, App10Constants.Namespace))
+ {
+ result.Collections.Add(ReadCollection(reader, result).Result);
+ }
+ else if (!TryParseElement(reader, result, this.Version))
+ {
+ if (_preserveElementExtensions)
+ {
+ var tuple = await SyndicationFeedFormatter.CreateBufferIfRequiredAndWriteNodeAsync(buffer, extWriter, reader, _maxExtensionSize);
+ buffer = tuple.Item1;
+ extWriter = tuple.Item2;
+ }
+ else
+ {
+ await reader.SkipAsync();
+ }
+ }
+ }
+
+ LoadElementExtensions(buffer, extWriter, result);
+ }
+ finally
+ {
+ if (extWriter != null)
+ {
+ extWriter.Close();
+ }
+ }
+
+ await reader.ReadEndElementAsync();
+ return result;
+ }
+
+ private async Task WriteCollectionAsync(XmlWriter writer, ResourceCollectionInfo collection, Uri baseUri)
+ {
+ await writer.WriteStartElementAsync(App10Constants.Prefix, App10Constants.Collection, App10Constants.Namespace);
+ Uri baseUriToWrite = FeedUtils.GetBaseUriToWrite(baseUri, collection.BaseUri);
+ if (baseUriToWrite != null)
+ {
+ baseUri = collection.BaseUri;
+ WriteXmlBase(writer, baseUriToWrite);
+ }
+
+ if (collection.Link != null)
+ {
+ await writer.WriteAttributeStringAsync(App10Constants.Href, FeedUtils.GetUriString(collection.Link));
+ }
+
+ await WriteAttributeExtensionsAsync(writer, collection, this.Version);
+ if (collection.Title != null)
+ {
+ await collection.Title.WriteToAsync(writer, Atom10Constants.TitleTag, Atom10Constants.Atom10Namespace);
+ }
+
+ for (int i = 0; i < collection.Accepts.Count; ++i)
+ {
+ await writer.WriteElementStringAsync(App10Constants.Prefix, App10Constants.Accept, App10Constants.Namespace, collection.Accepts[i]);
+ }
+
+ for (int i = 0; i < collection.Categories.Count; ++i)
+ {
+ await WriteCategoriesAsync(writer, collection.Categories[i], baseUri, this.Version);
+ }
+
+ await WriteElementExtensionsAsync(writer, collection, this.Version);
+ await writer.WriteEndElementAsync();
+ }
+
+ private async Task WriteDocumentAsync(XmlWriter writer)
+ {
+ // declare the atom10 namespace upfront for compactness
+ await writer.WriteAttributeStringAsync(Atom10Constants.Atom10Prefix, Atom10FeedFormatter.XmlNsNs, Atom10Constants.Atom10Namespace);
+ if (!string.IsNullOrEmpty(this.Document.Language))
+ {
+ WriteXmlLang(writer, this.Document.Language);
+ }
+
+ Uri baseUri = this.Document.BaseUri;
+ if (baseUri != null)
+ {
+ WriteXmlBase(writer, baseUri);
+ }
+
+ WriteAttributeExtensions(writer, this.Document, this.Version);
+
+ for (int i = 0; i < this.Document.Workspaces.Count; ++i)
+ {
+ await WriteWorkspaceAsync(writer, this.Document.Workspaces[i], baseUri);
+ }
+
+ await WriteElementExtensionsAsync(writer, this.Document, this.Version);
+ }
+
+ private async Task WriteWorkspaceAsync(XmlWriter writer, Workspace workspace, Uri baseUri)
+ {
+ await writer.WriteStartElementAsync(App10Constants.Prefix, App10Constants.Workspace, App10Constants.Namespace);
+ Uri baseUriToWrite = FeedUtils.GetBaseUriToWrite(baseUri, workspace.BaseUri);
+ if (baseUriToWrite != null)
+ {
+ baseUri = workspace.BaseUri;
+ WriteXmlBase(writer, baseUriToWrite);
+ }
+
+ WriteAttributeExtensions(writer, workspace, this.Version);
+ if (workspace.Title != null)
+ {
+ await workspace.Title.WriteToAsync(writer, Atom10Constants.TitleTag, Atom10Constants.Atom10Namespace);
+ }
+
+ for (int i = 0; i < workspace.Collections.Count; ++i)
+ {
+ await WriteCollectionAsync(writer, workspace.Collections[i], baseUri);
+ }
+
+ await WriteElementExtensionsAsync(writer, workspace, this.Version);
+ await writer.WriteEndElementAsync();
+ }
+ }
+
+ [XmlRoot(ElementName = App10Constants.Service, Namespace = App10Constants.Namespace)]
+ public class AtomPub10ServiceDocumentFormatter<TServiceDocument> : AtomPub10ServiceDocumentFormatter
+ where TServiceDocument : ServiceDocument, new()
+ {
+ public AtomPub10ServiceDocumentFormatter() :
+ base(typeof(TServiceDocument))
+ {
+ }
+
+ public AtomPub10ServiceDocumentFormatter(TServiceDocument documentToWrite)
+ : base(documentToWrite)
+ {
+ }
+
+ protected override ServiceDocument CreateDocumentInstance()
+ {
+ return new TServiceDocument();
+ }
+ }
+}
diff --git a/src/System.ServiceModel.Syndication/src/System/ServiceModel/Syndication/CategoriesDocument.cs b/src/System.ServiceModel.Syndication/src/System/ServiceModel/Syndication/CategoriesDocument.cs
new file mode 100644
index 0000000000..e9f74202d9
--- /dev/null
+++ b/src/System.ServiceModel.Syndication/src/System/ServiceModel/Syndication/CategoriesDocument.cs
@@ -0,0 +1,119 @@
+// 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.ServiceModel.Syndication
+{
+ using System;
+ using System.Collections.Generic;
+ using System.Collections.ObjectModel;
+ using System.Runtime.CompilerServices;
+ using System.Threading.Tasks;
+ using System.Xml;
+
+ public abstract class CategoriesDocument : IExtensibleSyndicationObject
+ {
+ private Uri _baseUri;
+ private ExtensibleSyndicationObject _extensions = new ExtensibleSyndicationObject();
+ private string _language;
+
+ internal CategoriesDocument()
+ {
+ }
+
+ public Dictionary<XmlQualifiedName, string> AttributeExtensions
+ {
+ get
+ {
+ return _extensions.AttributeExtensions;
+ }
+ }
+
+ public Uri BaseUri
+ {
+ get { return _baseUri; }
+ set { _baseUri = value; }
+ }
+
+ public SyndicationElementExtensionCollection ElementExtensions
+ {
+ get
+ {
+ return _extensions.ElementExtensions;
+ }
+ }
+
+ public string Language
+ {
+ get { return _language; }
+ set { _language = value; }
+ }
+
+ internal abstract bool IsInline
+ {
+ get;
+ }
+
+ public static InlineCategoriesDocument Create(Collection<SyndicationCategory> categories)
+ {
+ return new InlineCategoriesDocument(categories);
+ }
+
+ public static InlineCategoriesDocument Create(Collection<SyndicationCategory> categories, bool isFixed, string scheme)
+ {
+ return new InlineCategoriesDocument(categories, isFixed, scheme);
+ }
+
+ public static ReferencedCategoriesDocument Create(Uri linkToCategoriesDocument)
+ {
+ return new ReferencedCategoriesDocument(linkToCategoriesDocument);
+ }
+
+ public static async Task<CategoriesDocument> LoadAsync(XmlReader reader)
+ {
+ AtomPub10CategoriesDocumentFormatter formatter = new AtomPub10CategoriesDocumentFormatter();
+ await formatter.ReadFromAsync(reader);
+ return formatter.Document;
+ }
+
+ public CategoriesDocumentFormatter GetFormatter()
+ {
+ return new AtomPub10CategoriesDocumentFormatter(this);
+ }
+
+ public void Save(XmlWriter writer)
+ {
+ this.GetFormatter().WriteTo(writer);
+ }
+
+ protected internal virtual bool TryParseAttribute(string name, string ns, string value, string version)
+ {
+ return false;
+ }
+
+ protected internal virtual bool TryParseElement(XmlReader reader, string version)
+ {
+ return false;
+ }
+
+ protected internal virtual Task WriteAttributeExtensionsAsync(XmlWriter writer, string version)
+ {
+ return _extensions.WriteAttributeExtensionsAsync(writer);
+ }
+
+ protected internal virtual Task WriteElementExtensionsAsync(XmlWriter writer, string version)
+ {
+ return _extensions.WriteElementExtensionsAsync(writer);
+ }
+
+ internal void LoadElementExtensions(XmlReaderWrapper readerOverUnparsedExtensions, int maxExtensionSize)
+ {
+ _extensions.LoadElementExtensions(readerOverUnparsedExtensions, maxExtensionSize);
+ }
+
+ internal void LoadElementExtensions(XmlBuffer buffer)
+ {
+ _extensions.LoadElementExtensions(buffer);
+ }
+ }
+}
diff --git a/src/System.ServiceModel.Syndication/src/System/ServiceModel/Syndication/CategoriesDocumentFormatter.cs b/src/System.ServiceModel.Syndication/src/System/ServiceModel/Syndication/CategoriesDocumentFormatter.cs
new file mode 100644
index 0000000000..c3883c2a14
--- /dev/null
+++ b/src/System.ServiceModel.Syndication/src/System/ServiceModel/Syndication/CategoriesDocumentFormatter.cs
@@ -0,0 +1,56 @@
+// 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.ServiceModel.Syndication
+{
+ using System;
+ using System.Runtime.CompilerServices;
+ using System.Runtime.Serialization;
+ using System.Threading.Tasks;
+ using System.Xml;
+
+ public abstract class CategoriesDocumentFormatter
+ {
+ private CategoriesDocument _document;
+
+ protected CategoriesDocumentFormatter()
+ {
+ }
+ protected CategoriesDocumentFormatter(CategoriesDocument documentToWrite)
+ {
+ if (documentToWrite == null)
+ {
+ throw new ArgumentNullException(nameof(documentToWrite));
+ }
+ _document = documentToWrite;
+ }
+
+ public CategoriesDocument Document
+ {
+ get { return _document; }
+ }
+
+ public abstract string Version
+ { get; }
+
+ public abstract Task<bool> CanReadAsync(XmlReader reader);
+ public abstract Task ReadFromAsync(XmlReader reader);
+ public abstract Task WriteTo(XmlWriter writer);
+
+ protected virtual InlineCategoriesDocument CreateInlineCategoriesDocument()
+ {
+ return new InlineCategoriesDocument();
+ }
+
+ protected virtual ReferencedCategoriesDocument CreateReferencedCategoriesDocument()
+ {
+ return new ReferencedCategoriesDocument();
+ }
+
+ protected virtual void SetDocument(CategoriesDocument document)
+ {
+ _document = document;
+ }
+ }
+}
diff --git a/src/System.ServiceModel.Syndication/src/System/ServiceModel/Syndication/ExtensibleSyndicationObject.cs b/src/System.ServiceModel.Syndication/src/System/ServiceModel/Syndication/ExtensibleSyndicationObject.cs
new file mode 100644
index 0000000000..c3ad0d3f41
--- /dev/null
+++ b/src/System.ServiceModel.Syndication/src/System/ServiceModel/Syndication/ExtensibleSyndicationObject.cs
@@ -0,0 +1,142 @@
+// 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.ServiceModel.Syndication
+{
+ using System;
+ using System.Collections.ObjectModel;
+ using System.Collections.Generic;
+ using System.Xml;
+ using System.Threading.Tasks;
+
+ // NOTE: This class implements Clone so if you add any members, please update the copy ctor
+ internal struct ExtensibleSyndicationObject : IExtensibleSyndicationObject
+ {
+ private Dictionary<XmlQualifiedName, string> _attributeExtensions;
+ private SyndicationElementExtensionCollection _elementExtensions;
+
+ private ExtensibleSyndicationObject(ExtensibleSyndicationObject source)
+ {
+ if (source._attributeExtensions != null)
+ {
+ _attributeExtensions = new Dictionary<XmlQualifiedName, string>();
+ foreach (XmlQualifiedName key in source._attributeExtensions.Keys)
+ {
+ _attributeExtensions.Add(key, source._attributeExtensions[key]);
+ }
+ }
+ else
+ {
+ _attributeExtensions = null;
+ }
+ if (source._elementExtensions != null)
+ {
+ _elementExtensions = new SyndicationElementExtensionCollection(source._elementExtensions);
+ }
+ else
+ {
+ _elementExtensions = null;
+ }
+ }
+
+ public Dictionary<XmlQualifiedName, string> AttributeExtensions
+ {
+ get
+ {
+ if (_attributeExtensions == null)
+ {
+ _attributeExtensions = new Dictionary<XmlQualifiedName, string>();
+ }
+ return _attributeExtensions;
+ }
+ }
+
+ public SyndicationElementExtensionCollection ElementExtensions
+ {
+ get
+ {
+ if (_elementExtensions == null)
+ {
+ _elementExtensions = new SyndicationElementExtensionCollection();
+ }
+ return _elementExtensions;
+ }
+ }
+
+ private static XmlBuffer CreateXmlBuffer(XmlDictionaryReader unparsedExtensionsReader, int maxExtensionSize)
+ {
+ XmlBuffer buffer = new XmlBuffer(maxExtensionSize);
+ using (XmlDictionaryWriter writer = buffer.OpenSection(unparsedExtensionsReader.Quotas))
+ {
+ writer.WriteStartElement(Rss20Constants.ExtensionWrapperTag);
+ while (unparsedExtensionsReader.IsStartElement())
+ {
+ writer.WriteNode(unparsedExtensionsReader, false);
+ }
+ writer.WriteEndElement();
+ }
+ buffer.CloseSection();
+ buffer.Close();
+ return buffer;
+ }
+
+ internal void LoadElementExtensions(XmlReader readerOverUnparsedExtensions, int maxExtensionSize)
+ {
+ if (readerOverUnparsedExtensions == null)
+ {
+ throw new ArgumentNullException(nameof(readerOverUnparsedExtensions));
+ }
+
+ if (maxExtensionSize < 0)
+ {
+ throw new ArgumentOutOfRangeException(nameof(maxExtensionSize));
+ }
+ XmlDictionaryReader r = XmlDictionaryReader.CreateDictionaryReader(readerOverUnparsedExtensions);
+ _elementExtensions = new SyndicationElementExtensionCollection(CreateXmlBuffer(r, maxExtensionSize));
+ }
+
+
+ internal void LoadElementExtensions(XmlBuffer buffer)
+ {
+ _elementExtensions = new SyndicationElementExtensionCollection(buffer);
+ }
+
+ internal async Task WriteAttributeExtensionsAsync(XmlWriter writer)
+ {
+ if (writer == null)
+ {
+ throw new ArgumentNullException(nameof(writer));
+ }
+
+ writer = XmlWriterWrapper.CreateFromWriter(writer);
+
+ if (_attributeExtensions != null)
+ {
+ foreach (XmlQualifiedName qname in _attributeExtensions.Keys)
+ {
+ string value = _attributeExtensions[qname];
+ await writer.WriteAttributeStringAsync(qname.Name, qname.Namespace, value);
+ }
+ }
+ }
+
+ internal async Task WriteElementExtensionsAsync(XmlWriter writer)
+ {
+ if (writer == null)
+ {
+ throw new ArgumentNullException(nameof(writer));
+ }
+
+ if (_elementExtensions != null)
+ {
+ await _elementExtensions.WriteToAsync(writer);
+ }
+ }
+
+ public ExtensibleSyndicationObject Clone()
+ {
+ return new ExtensibleSyndicationObject(this);
+ }
+ }
+}
diff --git a/src/System.ServiceModel.Syndication/src/System/ServiceModel/Syndication/FeedUtils.cs b/src/System.ServiceModel.Syndication/src/System/ServiceModel/Syndication/FeedUtils.cs
new file mode 100644
index 0000000000..51ac061848
--- /dev/null
+++ b/src/System.ServiceModel.Syndication/src/System/ServiceModel/Syndication/FeedUtils.cs
@@ -0,0 +1,144 @@
+// 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.ServiceModel.Syndication
+{
+ using System;
+ using System.Collections.ObjectModel;
+ using System.Globalization;
+ using System.Xml;
+
+ internal static class FeedUtils
+ {
+ public static string AddLineInfo(XmlReader reader, string error)
+ {
+ IXmlLineInfo lineInfo = reader as IXmlLineInfo;
+ if (lineInfo != null && lineInfo.HasLineInfo())
+ {
+ error = string.Format(CultureInfo.InvariantCulture, "{0} {1}", string.Format(SR.ErrorInLine, lineInfo.LineNumber, lineInfo.LinePosition), error);
+ }
+ return error;
+ }
+
+ static internal Collection<SyndicationCategory> CloneCategories(Collection<SyndicationCategory> categories)
+ {
+ if (categories == null)
+ {
+ return null;
+ }
+ Collection<SyndicationCategory> result = new NullNotAllowedCollection<SyndicationCategory>();
+ for (int i = 0; i < categories.Count; ++i)
+ {
+ result.Add(categories[i].Clone());
+ }
+ return result;
+ }
+
+ static internal Collection<SyndicationLink> CloneLinks(Collection<SyndicationLink> links)
+ {
+ if (links == null)
+ {
+ return null;
+ }
+ Collection<SyndicationLink> result = new NullNotAllowedCollection<SyndicationLink>();
+ for (int i = 0; i < links.Count; ++i)
+ {
+ result.Add(links[i].Clone());
+ }
+ return result;
+ }
+
+ static internal Collection<SyndicationPerson> ClonePersons(Collection<SyndicationPerson> persons)
+ {
+ if (persons == null)
+ {
+ return null;
+ }
+ Collection<SyndicationPerson> result = new NullNotAllowedCollection<SyndicationPerson>();
+ for (int i = 0; i < persons.Count; ++i)
+ {
+ result.Add(persons[i].Clone());
+ }
+ return result;
+ }
+
+ static internal TextSyndicationContent CloneTextContent(TextSyndicationContent content)
+ {
+ if (content == null)
+ {
+ return null;
+ }
+ return (TextSyndicationContent)(content.Clone());
+ }
+
+ internal static Uri CombineXmlBase(Uri rootBase, string newBase)
+ {
+ if (string.IsNullOrEmpty(newBase))
+ {
+ return rootBase;
+ }
+
+ Uri newBaseUri = new Uri(newBase, UriKind.RelativeOrAbsolute);
+ if (rootBase == null || newBaseUri.IsAbsoluteUri)
+ {
+ return newBaseUri;
+ }
+
+ return new Uri(rootBase, newBase);
+ }
+
+ internal static Uri GetBaseUriToWrite(Uri rootBase, Uri currentBase)
+ {
+ Uri uriToWrite;
+ if (rootBase == currentBase || currentBase == null)
+ {
+ uriToWrite = null;
+ }
+ else if (rootBase == null)
+ {
+ uriToWrite = currentBase;
+ }
+ else
+ {
+ // rootBase != currentBase and both are not null
+ // Write the relative base if possible
+ if (rootBase.IsAbsoluteUri && currentBase.IsAbsoluteUri && rootBase.IsBaseOf(currentBase))
+ {
+ uriToWrite = rootBase.MakeRelativeUri(currentBase);
+ }
+ else
+ {
+ uriToWrite = currentBase;
+ }
+ }
+ return uriToWrite;
+ }
+
+ static internal string GetUriString(Uri uri)
+ {
+ if (uri == null)
+ {
+ return null;
+ }
+ if (uri.IsAbsoluteUri)
+ {
+ return uri.AbsoluteUri;
+ }
+ else
+ {
+ return uri.ToString();
+ }
+ }
+
+ static internal bool IsXmlns(string name, string ns)
+ {
+ return name == "xmlns" || ns == "http://www.w3.org/2000/xmlns/";
+ }
+
+ internal static bool IsXmlSchemaType(string name, string ns)
+ {
+ return name == "type" && ns == "http://www.w3.org/2001/XMLSchema-instance";
+ }
+ }
+}
diff --git a/src/System.ServiceModel.Syndication/src/System/ServiceModel/Syndication/IExtensibleSyndicationObject.cs b/src/System.ServiceModel.Syndication/src/System/ServiceModel/Syndication/IExtensibleSyndicationObject.cs
new file mode 100644
index 0000000000..cc1f32f82f
--- /dev/null
+++ b/src/System.ServiceModel.Syndication/src/System/ServiceModel/Syndication/IExtensibleSyndicationObject.cs
@@ -0,0 +1,17 @@
+// 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.ServiceModel.Syndication
+{
+ using System.Collections.Generic;
+ using System.Xml;
+
+ internal interface IExtensibleSyndicationObject
+ {
+ Dictionary<XmlQualifiedName, string> AttributeExtensions
+ { get; }
+ SyndicationElementExtensionCollection ElementExtensions
+ { get; }
+ }
+}
diff --git a/src/System.ServiceModel.Syndication/src/System/ServiceModel/Syndication/InlineCategoriesDocument.cs b/src/System.ServiceModel.Syndication/src/System/ServiceModel/Syndication/InlineCategoriesDocument.cs
new file mode 100644
index 0000000000..48cbb9ce60
--- /dev/null
+++ b/src/System.ServiceModel.Syndication/src/System/ServiceModel/Syndication/InlineCategoriesDocument.cs
@@ -0,0 +1,74 @@
+// 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.ServiceModel.Syndication
+{
+ using System.Collections.Generic;
+ using System.Collections.ObjectModel;
+ using System.Runtime.CompilerServices;
+
+ public class InlineCategoriesDocument : CategoriesDocument
+ {
+ private Collection<SyndicationCategory> _categories;
+ private bool _isFixed;
+ private string _scheme;
+
+ public InlineCategoriesDocument()
+ {
+ }
+
+ public InlineCategoriesDocument(IEnumerable<SyndicationCategory> categories)
+ : this(categories, false, null)
+ {
+ }
+
+ public InlineCategoriesDocument(IEnumerable<SyndicationCategory> categories, bool isFixed, string scheme)
+ {
+ if (categories != null)
+ {
+ _categories = new NullNotAllowedCollection<SyndicationCategory>();
+ foreach (SyndicationCategory category in categories)
+ {
+ _categories.Add(category);
+ }
+ }
+ _isFixed = isFixed;
+ _scheme = scheme;
+ }
+
+ public Collection<SyndicationCategory> Categories
+ {
+ get
+ {
+ if (_categories == null)
+ {
+ _categories = new NullNotAllowedCollection<SyndicationCategory>();
+ }
+ return _categories;
+ }
+ }
+
+ public bool IsFixed
+ {
+ get { return _isFixed; }
+ set { _isFixed = value; }
+ }
+
+ public string Scheme
+ {
+ get { return _scheme; }
+ set { _scheme = value; }
+ }
+
+ internal override bool IsInline
+ {
+ get { return true; }
+ }
+
+ internal protected virtual SyndicationCategory CreateCategory()
+ {
+ return new SyndicationCategory();
+ }
+ }
+}
diff --git a/src/System.ServiceModel.Syndication/src/System/ServiceModel/Syndication/NullNotAllowedCollection.cs b/src/System.ServiceModel.Syndication/src/System/ServiceModel/Syndication/NullNotAllowedCollection.cs
new file mode 100644
index 0000000000..420d089816
--- /dev/null
+++ b/src/System.ServiceModel.Syndication/src/System/ServiceModel/Syndication/NullNotAllowedCollection.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.
+
+namespace System.ServiceModel.Syndication
+{
+ using System;
+ using System.Collections.ObjectModel;
+
+ internal class NullNotAllowedCollection<TCollectionItem> : Collection<TCollectionItem>
+ where TCollectionItem : class
+ {
+ public NullNotAllowedCollection()
+ : base()
+ {
+ }
+
+ protected override void InsertItem(int index, TCollectionItem item)
+ {
+ if (item == null)
+ {
+ throw new ArgumentNullException(nameof(item));
+ }
+ base.InsertItem(index, item);
+ }
+
+ protected override void SetItem(int index, TCollectionItem item)
+ {
+ if (item == null)
+ {
+ throw new ArgumentNullException(nameof(item));
+ }
+ base.SetItem(index, item);
+ }
+ }
+}
diff --git a/src/System.ServiceModel.Syndication/src/System/ServiceModel/Syndication/ReferencedCategoriesDocument.cs b/src/System.ServiceModel.Syndication/src/System/ServiceModel/Syndication/ReferencedCategoriesDocument.cs
new file mode 100644
index 0000000000..75686a2f30
--- /dev/null
+++ b/src/System.ServiceModel.Syndication/src/System/ServiceModel/Syndication/ReferencedCategoriesDocument.cs
@@ -0,0 +1,39 @@
+// 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.ServiceModel.Syndication
+{
+ using System;
+ using System.Runtime.CompilerServices;
+
+ public class ReferencedCategoriesDocument : CategoriesDocument
+ {
+ private Uri _link;
+
+ public ReferencedCategoriesDocument()
+ {
+ }
+
+ public ReferencedCategoriesDocument(Uri link)
+ : base()
+ {
+ if (link == null)
+ {
+ throw new ArgumentNullException(nameof(link));
+ }
+ _link = link;
+ }
+
+ public Uri Link
+ {
+ get { return _link; }
+ set { _link = value; }
+ }
+
+ internal override bool IsInline
+ {
+ get { return false; }
+ }
+ }
+}
diff --git a/src/System.ServiceModel.Syndication/src/System/ServiceModel/Syndication/ResourceCollectionInfo.cs b/src/System.ServiceModel.Syndication/src/System/ServiceModel/Syndication/ResourceCollectionInfo.cs
new file mode 100644
index 0000000000..33605efe0a
--- /dev/null
+++ b/src/System.ServiceModel.Syndication/src/System/ServiceModel/Syndication/ResourceCollectionInfo.cs
@@ -0,0 +1,182 @@
+// 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.ServiceModel.Syndication
+{
+ using System;
+ using System.Collections.Generic;
+ using System.Collections.ObjectModel;
+ using System.Runtime.CompilerServices;
+ using System.Threading.Tasks;
+ using System.Xml;
+
+ public class ResourceCollectionInfo : IExtensibleSyndicationObject
+ {
+ private static IEnumerable<string> s_singleEmptyAccept;
+ private Collection<string> _accepts;
+ private Uri _baseUri;
+ private Collection<CategoriesDocument> _categories;
+ private ExtensibleSyndicationObject _extensions = new ExtensibleSyndicationObject();
+ private Uri _link;
+ private TextSyndicationContent _title;
+
+ public ResourceCollectionInfo()
+ {
+ }
+
+ public ResourceCollectionInfo(string title, Uri link)
+ : this((title == null) ? null : new TextSyndicationContent(title), link)
+ {
+ }
+
+ public ResourceCollectionInfo(TextSyndicationContent title, Uri link)
+ : this(title, link, null, null)
+ {
+ }
+
+ public ResourceCollectionInfo(TextSyndicationContent title, Uri link, IEnumerable<CategoriesDocument> categories, bool allowsNewEntries)
+ : this(title, link, categories, (allowsNewEntries) ? null : CreateSingleEmptyAccept())
+ {
+ }
+
+ public ResourceCollectionInfo(TextSyndicationContent title, Uri link, IEnumerable<CategoriesDocument> categories, IEnumerable<string> accepts)
+ {
+ if (title == null)
+ {
+ throw new ArgumentNullException(nameof(title));
+ }
+ if (link == null)
+ {
+ throw new ArgumentNullException(nameof(link));
+ }
+ _title = title;
+ _link = link;
+ if (categories != null)
+ {
+ _categories = new NullNotAllowedCollection<CategoriesDocument>();
+ foreach (CategoriesDocument category in categories)
+ {
+ _categories.Add(category);
+ }
+ }
+ if (accepts != null)
+ {
+ _accepts = new NullNotAllowedCollection<string>();
+ foreach (string accept in accepts)
+ {
+ _accepts.Add(accept);
+ }
+ }
+ }
+
+ public Collection<string> Accepts
+ {
+ get
+ {
+ if (_accepts == null)
+ {
+ _accepts = new NullNotAllowedCollection<string>();
+ }
+ return _accepts;
+ }
+ }
+
+ public Dictionary<XmlQualifiedName, string> AttributeExtensions
+ {
+ get
+ {
+ return _extensions.AttributeExtensions;
+ }
+ }
+
+ public Uri BaseUri
+ {
+ get { return _baseUri; }
+ set { _baseUri = value; }
+ }
+
+ public Collection<CategoriesDocument> Categories
+ {
+ get
+ {
+ if (_categories == null)
+ {
+ _categories = new NullNotAllowedCollection<CategoriesDocument>();
+ }
+ return _categories;
+ }
+ }
+
+ public SyndicationElementExtensionCollection ElementExtensions
+ {
+ get
+ {
+ return _extensions.ElementExtensions;
+ }
+ }
+
+ public Uri Link
+ {
+ get { return _link; }
+ set { _link = value; }
+ }
+
+ public TextSyndicationContent Title
+ {
+ get { return _title; }
+ set { _title = value; }
+ }
+
+ protected internal virtual InlineCategoriesDocument CreateInlineCategoriesDocument()
+ {
+ return new InlineCategoriesDocument();
+ }
+
+ protected internal virtual ReferencedCategoriesDocument CreateReferencedCategoriesDocument()
+ {
+ return new ReferencedCategoriesDocument();
+ }
+
+ protected internal virtual bool TryParseAttribute(string name, string ns, string value, string version)
+ {
+ return false;
+ }
+
+ protected internal virtual bool TryParseElement(XmlReader reader, string version)
+ {
+ return false;
+ }
+
+ protected internal virtual Task WriteAttributeExtensionsAsync(XmlWriter writer, string version)
+ {
+ return _extensions.WriteAttributeExtensionsAsync(writer);
+ }
+
+ protected internal virtual Task WriteElementExtensionsAsync(XmlWriter writer, string version)
+ {
+ return _extensions.WriteElementExtensionsAsync(writer);
+ }
+
+ internal void LoadElementExtensions(XmlReaderWrapper readerOverUnparsedExtensions, int maxExtensionSize)
+ {
+ _extensions.LoadElementExtensions(readerOverUnparsedExtensions, maxExtensionSize);
+ }
+
+ internal void LoadElementExtensions(XmlBuffer buffer)
+ {
+ _extensions.LoadElementExtensions(buffer);
+ }
+
+ private static IEnumerable<string> CreateSingleEmptyAccept()
+ {
+ if (s_singleEmptyAccept == null)
+ {
+ List<string> tmp = new List<string>(1);
+ tmp.Add(string.Empty);
+ s_singleEmptyAccept = tmp.AsReadOnly();
+ }
+ return s_singleEmptyAccept;
+ }
+ }
+}
diff --git a/src/System.ServiceModel.Syndication/src/System/ServiceModel/Syndication/Rss20Constants.cs b/src/System.ServiceModel.Syndication/src/System/ServiceModel/Syndication/Rss20Constants.cs
new file mode 100644
index 0000000000..a811e7ec76
--- /dev/null
+++ b/src/System.ServiceModel.Syndication/src/System/ServiceModel/Syndication/Rss20Constants.cs
@@ -0,0 +1,46 @@
+// 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.ServiceModel.Syndication
+{
+ internal static class Rss20Constants
+ {
+ public const string AuthorTag = "author";
+ public const string CategoryTag = "category";
+ public const string ChannelTag = "channel";
+ public const string CopyrightTag = "copyright";
+ public const string DescriptionTag = "description";
+ public const string DomainTag = "domain";
+ public const string EnclosureTag = "enclosure";
+ public const string ExtensionWrapperTag = "extensionWrapper";
+ public const string GeneratorTag = "generator";
+ public const string GuidTag = "guid";
+ public const string ImageTag = "image";
+ public const string IsPermaLinkTag = "isPermaLink";
+ public const string ItemTag = "item";
+ public const string LanguageTag = "language";
+ public const string LastBuildDateTag = "lastBuildDate";
+ public const string LengthTag = "length";
+ public const string LinkTag = "link";
+ public const string ManagingEditorTag = "managingEditor";
+ public const string PubDateTag = "pubDate";
+ public const string Rss20Namespace = "";
+ public const string RssTag = "rss";
+ public const string SourceTag = "source";
+ public const string SpecificationLink = "http://blogs.law.harvard.edu/tech/rss";
+ public const string TitleTag = "title";
+ public const string TypeTag = "type";
+ public const string UrlTag = "url";
+ public const string Version = "2.0";
+ public const string VersionTag = "version";
+ public const string DocumentationTag = "docs";
+ public const string TimeToLiveTag = "ttl";
+ public const string TextInputTag = "textInput";
+ public const string SkipHoursTag = "skipHours";
+ public const string SkipDaysTag = "skipDays";
+ public const string HourTag = "hour";
+ public const string DayTag = "day";
+ public const string NameTag = "name";
+ }
+}
diff --git a/src/System.ServiceModel.Syndication/src/System/ServiceModel/Syndication/Rss20FeedFormatter.cs b/src/System.ServiceModel.Syndication/src/System/ServiceModel/Syndication/Rss20FeedFormatter.cs
new file mode 100644
index 0000000000..10b65da082
--- /dev/null
+++ b/src/System.ServiceModel.Syndication/src/System/ServiceModel/Syndication/Rss20FeedFormatter.cs
@@ -0,0 +1,1661 @@
+// 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.ServiceModel.Syndication
+{
+ using System;
+ using System.Collections.Generic;
+ using System.Diagnostics;
+ using System.Diagnostics.CodeAnalysis;
+ using System.Globalization;
+ using System.Text;
+ using System.Threading;
+ using System.Threading.Tasks;
+ using System.Xml;
+ using System.Xml.Schema;
+ using System.Xml.Serialization;
+
+
+ [XmlRoot(ElementName = Rss20Constants.RssTag, Namespace = Rss20Constants.Rss20Namespace)]
+ public class Rss20FeedFormatter : SyndicationFeedFormatter
+ {
+ private static readonly XmlQualifiedName s_rss20Domain = new XmlQualifiedName(Rss20Constants.DomainTag, string.Empty);
+ private static readonly XmlQualifiedName s_rss20Length = new XmlQualifiedName(Rss20Constants.LengthTag, string.Empty);
+ private static readonly XmlQualifiedName s_rss20Type = new XmlQualifiedName(Rss20Constants.TypeTag, string.Empty);
+ private static readonly XmlQualifiedName s_rss20Url = new XmlQualifiedName(Rss20Constants.UrlTag, string.Empty);
+ private static List<string> acceptedDays = new List<string> { "monday", "tuesday", "wednesday", "thursday", "friday", "saturday", "sunday" };
+ private const string Rfc822OutputLocalDateTimeFormat = "ddd, dd MMM yyyy HH:mm:ss zzz";
+ private const string Rfc822OutputUtcDateTimeFormat = "ddd, dd MMM yyyy HH:mm:ss Z";
+
+ private Atom10FeedFormatter _atomSerializer;
+ private Type _feedType;
+ private int _maxExtensionSize;
+ private bool _preserveAttributeExtensions;
+ private bool _preserveElementExtensions;
+ private bool _serializeExtensionsAsAtom;
+
+ //Custom Parsers
+ // value, localname , ns , result
+ public Func<string, string, string, string> StringParser { get; set; } = DefaultStringParser;
+ public Func<string, string, string, DateTimeOffset> DateParser { get; set; } = DefaultDateParser;
+ public Func<string, string, string, Uri> UriParser { get; set; } = DefaultUriParser;
+
+ static private string DefaultStringParser(string value, string localName, string ns)
+ {
+ return value;
+ }
+
+ static private Uri DefaultUriParser(string value, string localName, string ns)
+ {
+ return new Uri(value, UriKind.RelativeOrAbsolute);
+ }
+
+ private async Task<bool> OnReadImage(XmlReaderWrapper reader, SyndicationFeed result)
+ {
+ await reader.ReadStartElementAsync();
+ string localName = string.Empty;
+
+ while (await reader.IsStartElementAsync())
+ {
+ if (await reader.IsStartElementAsync(Rss20Constants.UrlTag, Rss20Constants.Rss20Namespace))
+ {
+ result.ImageUrl = UriParser(await reader.ReadElementStringAsync(), Rss20Constants.UrlTag, Rss20Constants.Rss20Namespace);
+ }
+ else if(await reader.IsStartElementAsync(Rss20Constants.LinkTag, Rss20Constants.Rss20Namespace))
+ {
+ result.ImageLink = UriParser(await reader.ReadElementStringAsync(), Rss20Constants.LinkTag, Rss20Constants.Rss20Namespace);
+ }
+ else if (await reader.IsStartElementAsync(Rss20Constants.TitleTag, Rss20Constants.Rss20Namespace))
+ {
+ result.ImageTitle = new TextSyndicationContent(StringParser(await reader.ReadElementStringAsync(), Rss20Constants.TitleTag, Rss20Constants.Rss20Namespace));
+ }
+ }
+ await reader.ReadEndElementAsync(); // image
+ return true;
+ }
+
+ public Rss20FeedFormatter()
+ : this(typeof(SyndicationFeed))
+ {
+ }
+
+ public Rss20FeedFormatter(Type feedTypeToCreate)
+ : base()
+ {
+ if (feedTypeToCreate == null)
+ {
+ throw new ArgumentNullException(nameof(feedTypeToCreate));
+ }
+ if (!typeof(SyndicationFeed).IsAssignableFrom(feedTypeToCreate))
+ {
+ throw new ArgumentException(string.Format(SR.InvalidObjectTypePassed, nameof(feedTypeToCreate), nameof(SyndicationFeed)));
+ }
+ _serializeExtensionsAsAtom = true;
+ _maxExtensionSize = int.MaxValue;
+ _preserveElementExtensions = true;
+ _preserveAttributeExtensions = true;
+ _atomSerializer = new Atom10FeedFormatter(feedTypeToCreate);
+ _feedType = feedTypeToCreate;
+ }
+
+ public Rss20FeedFormatter(SyndicationFeed feedToWrite)
+ : this(feedToWrite, true)
+ {
+ }
+
+ public Rss20FeedFormatter(SyndicationFeed feedToWrite, bool serializeExtensionsAsAtom)
+ : base(feedToWrite)
+ {
+ // No need to check that the parameter passed is valid - it is checked by the c'tor of the base class
+ _serializeExtensionsAsAtom = serializeExtensionsAsAtom;
+ _maxExtensionSize = int.MaxValue;
+ _preserveElementExtensions = true;
+ _preserveAttributeExtensions = true;
+ _atomSerializer = new Atom10FeedFormatter(this.Feed);
+ _feedType = feedToWrite.GetType();
+ }
+
+ public bool PreserveAttributeExtensions
+ {
+ get { return _preserveAttributeExtensions; }
+ set { _preserveAttributeExtensions = value; }
+ }
+
+ public bool PreserveElementExtensions
+ {
+ get { return _preserveElementExtensions; }
+ set { _preserveElementExtensions = value; }
+ }
+
+ public bool SerializeExtensionsAsAtom
+ {
+ get { return _serializeExtensionsAsAtom; }
+ set { _serializeExtensionsAsAtom = value; }
+ }
+
+ public override string Version
+ {
+ get { return SyndicationVersions.Rss20; }
+ }
+
+ protected Type FeedType
+ {
+ get
+ {
+ return _feedType;
+ }
+ }
+
+ public override bool CanRead(XmlReader reader)
+ {
+ if (reader == null)
+ {
+ throw new ArgumentNullException(nameof(reader));
+ }
+
+ return reader.IsStartElement(Rss20Constants.RssTag, Rss20Constants.Rss20Namespace);
+ }
+
+ public override Task ReadFromAsync(XmlReader reader, CancellationToken ct)
+ {
+ if (!CanRead(reader))
+ {
+ throw new XmlException(string.Format(SR.UnknownFeedXml, reader.LocalName, reader.NamespaceURI));
+ }
+
+ SetFeed(CreateFeedInstance());
+ return ReadXmlAsync(XmlReaderWrapper.CreateFromReader(reader), this.Feed);
+ }
+
+ private Task WriteXmlAsync(XmlWriter writer)
+ {
+ if (writer == null)
+ {
+ throw new ArgumentNullException(nameof(writer));
+ }
+
+ return WriteFeedAsync(writer);
+ }
+
+ public override async Task WriteToAsync(XmlWriter writer, CancellationToken ct)
+ {
+ if (writer == null)
+ {
+ throw new ArgumentNullException(nameof(writer));
+ }
+
+ writer = XmlWriterWrapper.CreateFromWriter(writer);
+
+ await writer.WriteStartElementAsync(Rss20Constants.RssTag, Rss20Constants.Rss20Namespace);
+ await WriteFeedAsync(writer);
+ await writer.WriteEndElementAsync();
+ }
+
+ protected internal override void SetFeed(SyndicationFeed feed)
+ {
+ base.SetFeed(feed);
+ _atomSerializer.SetFeed(this.Feed);
+ }
+
+ private async Task ReadItemFromAsync(XmlReaderWrapper reader, SyndicationItem result, Uri feedBaseUri)
+ {
+ result.BaseUri = feedBaseUri;
+ await reader.MoveToContentAsync();
+ bool isEmpty = reader.IsEmptyElement;
+ if (reader.HasAttributes)
+ {
+ while (reader.MoveToNextAttribute())
+ {
+ string ns = reader.NamespaceURI;
+ string name = reader.LocalName;
+ if (name == "base" && ns == Atom10FeedFormatter.XmlNs)
+ {
+ result.BaseUri = FeedUtils.CombineXmlBase(result.BaseUri, await reader.GetValueAsync());
+ continue;
+ }
+
+ if (FeedUtils.IsXmlns(name, ns) || FeedUtils.IsXmlSchemaType(name, ns))
+ {
+ continue;
+ }
+
+ string val = await reader.GetValueAsync();
+ if (!TryParseAttribute(name, ns, val, result, this.Version))
+ {
+ if (_preserveAttributeExtensions)
+ {
+ result.AttributeExtensions.Add(new XmlQualifiedName(name, ns), val);
+ }
+ }
+ }
+ }
+
+ await reader.ReadStartElementAsync();
+
+ if (!isEmpty)
+ {
+ string fallbackAlternateLink = null;
+ XmlDictionaryWriter extWriter = null;
+ bool readAlternateLink = false;
+ try
+ {
+ XmlBuffer buffer = null;
+ while (await reader.IsStartElementAsync())
+ {
+ bool notHandled = false;
+ if (await reader.MoveToContentAsync() == XmlNodeType.Element && reader.NamespaceURI == Rss20Constants.Rss20Namespace)
+ {
+ switch (reader.LocalName)
+ {
+ case Rss20Constants.TitleTag:
+ result.Title = new TextSyndicationContent(StringParser(await reader.ReadElementStringAsync(), Rss20Constants.TitleTag, Rss20Constants.Rss20Namespace));
+ break;
+
+ case Rss20Constants.LinkTag:
+ result.Links.Add(await ReadAlternateLinkAsync(reader, result.BaseUri));
+ readAlternateLink = true;
+ break;
+
+ case Rss20Constants.DescriptionTag:
+ result.Summary = new TextSyndicationContent(StringParser(await reader.ReadElementStringAsync(), Rss20Constants.DescriptionTag, Rss20Constants.Rss20Namespace));
+ break;
+
+ case Rss20Constants.AuthorTag:
+ result.Authors.Add(await ReadPersonAsync(reader, result));
+ break;
+
+ case Rss20Constants.CategoryTag:
+ result.Categories.Add(await ReadCategoryAsync(reader, result));
+ break;
+
+ case Rss20Constants.EnclosureTag:
+ result.Links.Add(await ReadMediaEnclosureAsync(reader, result.BaseUri));
+ break;
+
+ case Rss20Constants.GuidTag:
+ {
+ bool isPermalink = true;
+ string permalinkString = reader.GetAttribute(Rss20Constants.IsPermaLinkTag, Rss20Constants.Rss20Namespace);
+ if (permalinkString != null && permalinkString.Equals("false",StringComparison.OrdinalIgnoreCase))
+ {
+ isPermalink = false;
+ }
+ string localName = reader.LocalName;
+ string namespaceUri = reader.NamespaceURI;
+ result.Id = StringParser(await reader.ReadElementStringAsync(), localName, namespaceUri);
+ if (isPermalink)
+ {
+ fallbackAlternateLink = result.Id;
+ }
+
+ break;
+ }
+
+ case Rss20Constants.PubDateTag:
+ {
+ bool canReadContent = !reader.IsEmptyElement;
+ await reader.ReadStartElementAsync();
+ if (canReadContent)
+ {
+ string str = await reader.ReadStringAsync();
+ if (!string.IsNullOrEmpty(str))
+ {
+ result.PublishDate = DateParser(str, reader.LocalName, reader.NamespaceURI);
+ }
+
+ await reader.ReadEndElementAsync();
+ }
+
+ break;
+ }
+
+ case Rss20Constants.SourceTag:
+ {
+ SyndicationFeed feed = new SyndicationFeed();
+ if (reader.HasAttributes)
+ {
+ while (reader.MoveToNextAttribute())
+ {
+ string ns = reader.NamespaceURI;
+ string name = reader.LocalName;
+ if (FeedUtils.IsXmlns(name, ns))
+ {
+ continue;
+ }
+ string val = await reader.GetValueAsync();
+ if (name == Rss20Constants.UrlTag && ns == Rss20Constants.Rss20Namespace)
+ {
+ feed.Links.Add(SyndicationLink.CreateSelfLink(UriParser(val, Rss20Constants.UrlTag,ns)));
+ }
+ else if (!FeedUtils.IsXmlns(name, ns))
+ {
+ if (_preserveAttributeExtensions)
+ {
+ feed.AttributeExtensions.Add(new XmlQualifiedName(name, ns), val);
+ }
+ }
+ }
+ }
+ string localName = reader.LocalName;
+ string namespaceUri = reader.NamespaceURI;
+ string feedTitle = StringParser(await reader.ReadElementStringAsync(), localName, namespaceUri);
+ feed.Title = new TextSyndicationContent(feedTitle);
+ result.SourceFeed = feed;
+
+ break;
+ }
+
+ default:
+ notHandled = true;
+ break;
+ }
+ }
+ else
+ {
+ notHandled = true;
+ }
+
+ if (notHandled)
+ {
+ bool parsedExtension = _serializeExtensionsAsAtom && _atomSerializer.TryParseItemElementFromAsync(reader, result).Result;
+
+ if (!parsedExtension)
+ {
+ parsedExtension = TryParseElement(reader, result, this.Version);
+ }
+
+ if (!parsedExtension)
+ {
+ if (_preserveElementExtensions)
+ {
+ if (buffer == null)
+ {
+ buffer = new XmlBuffer(_maxExtensionSize);
+ extWriter = buffer.OpenSection(XmlDictionaryReaderQuotas.Max);
+ extWriter.WriteStartElement(Rss20Constants.ExtensionWrapperTag);
+ }
+
+ await XmlReaderWrapper.WriteNodeAsync(extWriter, reader, false);
+ }
+ else
+ {
+ await reader.SkipAsync();
+ }
+ }
+ }
+ }
+
+ LoadElementExtensions(buffer, extWriter, result);
+ }
+ finally
+ {
+ if (extWriter != null)
+ {
+ ((IDisposable)extWriter).Dispose();
+ }
+ }
+
+ await reader.ReadEndElementAsync(); // item
+
+ if (!readAlternateLink && fallbackAlternateLink != null)
+ {
+ result.Links.Add(SyndicationLink.CreateAlternateLink(new Uri(fallbackAlternateLink, UriKind.RelativeOrAbsolute)));
+ readAlternateLink = true;
+ }
+
+ // if there's no content and no alternate link set the summary as the item content
+ if (result.Content == null && !readAlternateLink)
+ {
+ result.Content = result.Summary;
+ result.Summary = null;
+ }
+ }
+ }
+
+ internal Task ReadItemFromAsync(XmlReaderWrapper reader, SyndicationItem result)
+ {
+ return ReadItemFromAsync(reader, result, null);
+ }
+
+ internal Task WriteItemContentsAsync(XmlWriter writer, SyndicationItem item)
+ {
+ writer = XmlWriterWrapper.CreateFromWriter(writer);
+ return WriteItemContentsAsync(writer, item, null);
+ }
+
+ protected override SyndicationFeed CreateFeedInstance()
+ {
+ return SyndicationFeedFormatter.CreateFeedInstance(_feedType);
+ }
+
+ protected virtual async Task<SyndicationItem> ReadItemAsync(XmlReader reader, SyndicationFeed feed)
+ {
+ if (feed == null)
+ {
+ throw new ArgumentNullException(nameof(feed));
+ }
+ if (reader == null)
+ {
+ throw new ArgumentNullException(nameof(reader));
+ }
+ SyndicationItem item = CreateItem(feed);
+ XmlReaderWrapper readerWrapper = XmlReaderWrapper.CreateFromReader(reader);
+ await ReadItemFromAsync(readerWrapper, item, feed.BaseUri); // delegate => ItemParser(reader,item,feed.BaseUri);//
+ return item;
+ }
+
+ protected virtual async Task WriteItemAsync(XmlWriter writer, SyndicationItem item, Uri feedBaseUri)
+ {
+ writer = XmlWriterWrapper.CreateFromWriter(writer);
+
+ await writer.WriteStartElementAsync(Rss20Constants.ItemTag, Rss20Constants.Rss20Namespace);
+ await WriteItemContentsAsync(writer, item, feedBaseUri);
+ await writer.WriteEndElementAsync();
+ }
+
+ protected virtual async Task WriteItemsAsync(XmlWriter writer, IEnumerable<SyndicationItem> items, Uri feedBaseUri)
+ {
+ if (items == null)
+ {
+ return;
+ }
+
+ foreach (SyndicationItem item in items)
+ {
+ await this.WriteItemAsync(writer, item, feedBaseUri);
+ }
+ }
+
+ private static string NormalizeTimeZone(string rfc822TimeZone, out bool isUtc)
+ {
+ isUtc = false;
+ // return a string in "-08:00" format
+ if (rfc822TimeZone[0] == '+' || rfc822TimeZone[0] == '-')
+ {
+ // the time zone is supposed to be 4 digits but some feeds omit the initial 0
+ StringBuilder result = new StringBuilder(rfc822TimeZone);
+ if (result.Length == 4)
+ {
+ // the timezone is +/-HMM. Convert to +/-HHMM
+ result.Insert(1, '0');
+ }
+ result.Insert(3, ':');
+ return result.ToString();
+ }
+ switch (rfc822TimeZone)
+ {
+ case "UT":
+ case "Z":
+ isUtc = true;
+ return "-00:00";
+ case "GMT":
+ return "-00:00";
+ case "A":
+ return "-01:00";
+ case "B":
+ return "-02:00";
+ case "C":
+ return "-03:00";
+ case "D":
+ case "EDT":
+ return "-04:00";
+ case "E":
+ case "EST":
+ case "CDT":
+ return "-05:00";
+ case "F":
+ case "CST":
+ case "MDT":
+ return "-06:00";
+ case "G":
+ case "MST":
+ case "PDT":
+ return "-07:00";
+ case "H":
+ case "PST":
+ return "-08:00";
+ case "I":
+ return "-09:00";
+ case "K":
+ return "-10:00";
+ case "L":
+ return "-11:00";
+ case "M":
+ return "-12:00";
+ case "N":
+ return "+01:00";
+ case "O":
+ return "+02:00";
+ case "P":
+ return "+03:00";
+ case "Q":
+ return "+04:00";
+ case "R":
+ return "+05:00";
+ case "S":
+ return "+06:00";
+ case "T":
+ return "+07:00";
+ case "U":
+ return "+08:00";
+ case "V":
+ return "+09:00";
+ case "W":
+ return "+10:00";
+ case "X":
+ return "+11:00";
+ case "Y":
+ return "+12:00";
+ default:
+ return "";
+ }
+ }
+
+ private async Task ReadSkipHoursAsync(XmlReaderWrapper reader, SyndicationFeed result)
+ {
+ await reader.ReadStartElementAsync();
+
+ while (await reader.IsStartElementAsync())
+ {
+
+ if(reader.LocalName == Rss20Constants.HourTag)
+ {
+ string val = StringParser(await reader.ReadElementStringAsync(), Rss20Constants.HourTag, Rss20Constants.Rss20Namespace);
+ int hour = int.Parse(val);
+ bool parsed = false;
+ parsed = int.TryParse(val,NumberStyles.Integer,NumberFormatInfo.InvariantInfo,out hour);
+
+ if(parsed == false)
+ {
+ throw new ArgumentException("The number on skip hours must be an integer betwen 0 and 23.");
+ }
+
+ if (hour < 0 || hour > 23)
+ {
+ throw new ArgumentException("The hour can't be lower than 0 or greater than 23.");
+ }
+
+ result.SkipHours.Add(hour);
+ }
+ else
+ {
+ await reader.SkipAsync();
+ }
+
+ }
+
+ await reader.ReadEndElementAsync();
+ }
+
+
+ private bool checkDay(string day)
+ {
+ if (acceptedDays.Contains(day.ToLower()))
+ {
+ return true;
+ }
+
+ return false;
+ }
+
+ private async Task ReadSkipDaysAsync(XmlReaderWrapper reader, SyndicationFeed result)
+ {
+ await reader.ReadStartElementAsync();
+
+ while (await reader.IsStartElementAsync())
+ {
+ if (reader.LocalName == Rss20Constants.DayTag)
+ {
+ string day = StringParser(await reader.ReadElementStringAsync(), Rss20Constants.DayTag, Rss20Constants.Rss20Namespace);
+
+ //Check if the day is actually an accepted day.
+ if (checkDay(day))
+ {
+ result.SkipDays.Add(day);
+ }
+ }
+ else
+ {
+ await reader.SkipAsync();
+ }
+ }
+
+ await reader.ReadEndElementAsync();
+ }
+
+ internal static void RemoveExtraWhiteSpaceAtStart(StringBuilder stringBuilder)
+ {
+ int i = 0;
+ while (i < stringBuilder.Length)
+ {
+ if (!char.IsWhiteSpace(stringBuilder[i]))
+ {
+ break;
+ }
+ ++i;
+ }
+ if (i > 0)
+ {
+ stringBuilder.Remove(0, i);
+ }
+ }
+
+ private static void ReplaceMultipleWhiteSpaceWithSingleWhiteSpace(StringBuilder builder)
+ {
+ int index = 0;
+ int whiteSpaceStart = -1;
+ while (index < builder.Length)
+ {
+ if (char.IsWhiteSpace(builder[index]))
+ {
+ if (whiteSpaceStart < 0)
+ {
+ whiteSpaceStart = index;
+ // normalize all white spaces to be ' ' so that the date time parsing works
+ builder[index] = ' ';
+ }
+ }
+ else if (whiteSpaceStart >= 0)
+ {
+ if (index > whiteSpaceStart + 1)
+ {
+ // there are at least 2 spaces... replace by 1
+ builder.Remove(whiteSpaceStart, index - whiteSpaceStart - 1);
+ index = whiteSpaceStart + 1;
+ }
+ whiteSpaceStart = -1;
+ }
+ ++index;
+ }
+ // we have already trimmed the start and end so there cannot be a trail of white spaces in the end
+ Debug.Assert(builder.Length == 0 || builder[builder.Length - 1] != ' ', "The string builder doesnt end in a white space");
+ }
+
+ private string AsString(DateTimeOffset dateTime)
+ {
+ if (dateTime.Offset == Atom10FeedFormatter.zeroOffset)
+ {
+ return dateTime.ToUniversalTime().ToString(Rfc822OutputUtcDateTimeFormat, CultureInfo.InvariantCulture);
+ }
+ else
+ {
+ StringBuilder sb = new StringBuilder(dateTime.ToString(Rfc822OutputLocalDateTimeFormat, CultureInfo.InvariantCulture));
+ // the zzz in Rfc822OutputLocalDateTimeFormat makes the timezone e.g. "-08:00" but we require e.g. "-0800" without the ':'
+ sb.Remove(sb.Length - 3, 1);
+ return sb.ToString();
+ }
+ }
+
+ private async Task<SyndicationLink> ReadAlternateLinkAsync(XmlReaderWrapper reader, Uri baseUri)
+ {
+ SyndicationLink link = new SyndicationLink();
+ link.BaseUri = baseUri;
+ link.RelationshipType = Atom10Constants.AlternateTag;
+ if (reader.HasAttributes)
+ {
+ while (reader.MoveToNextAttribute())
+ {
+ if (reader.LocalName == "base" && reader.NamespaceURI == Atom10FeedFormatter.XmlNs)
+ {
+ link.BaseUri = FeedUtils.CombineXmlBase(link.BaseUri, await reader.GetValueAsync());
+ }
+ else if (!FeedUtils.IsXmlns(reader.LocalName, reader.NamespaceURI))
+ {
+ if (this.PreserveAttributeExtensions)
+ {
+ link.AttributeExtensions.Add(new XmlQualifiedName(reader.LocalName, reader.NamespaceURI), await reader.GetValueAsync());
+ }
+ }
+ }
+ }
+ string localName = reader.LocalName;
+ string namespaceUri = reader.NamespaceURI;
+ link.Uri = UriParser(await reader.ReadElementStringAsync(), localName, namespaceUri);//new Uri(uri, UriKind.RelativeOrAbsolute);
+ return link;
+ }
+
+ private async Task<SyndicationCategory> ReadCategoryAsync(XmlReaderWrapper reader, SyndicationFeed feed)
+ {
+ SyndicationCategory result = CreateCategory(feed);
+ await ReadCategoryAsync(reader, result);
+ return result;
+ }
+
+ private async Task ReadCategoryAsync(XmlReaderWrapper reader, SyndicationCategory category)
+ {
+ bool isEmpty = reader.IsEmptyElement;
+ if (reader.HasAttributes)
+ {
+ while (reader.MoveToNextAttribute())
+ {
+ string ns = reader.NamespaceURI;
+ string name = reader.LocalName;
+ if (FeedUtils.IsXmlns(name, ns))
+ {
+ continue;
+ }
+ string val = await reader.GetValueAsync();
+ if (name == Rss20Constants.DomainTag && ns == Rss20Constants.Rss20Namespace)
+ {
+ category.Scheme = val;
+ }
+ else if (!TryParseAttribute(name, ns, val, category, this.Version))
+ {
+ if (_preserveAttributeExtensions)
+ {
+ category.AttributeExtensions.Add(new XmlQualifiedName(name, ns), val);
+ }
+ }
+ }
+ }
+
+ await reader.ReadStartElementAsync(Rss20Constants.CategoryTag, Rss20Constants.Rss20Namespace);
+
+ if (!isEmpty)
+ {
+ category.Name = StringParser(await reader.ReadStringAsync(), reader.LocalName, Rss20Constants.Rss20Namespace);
+ await reader.ReadEndElementAsync();
+ }
+ }
+
+ private async Task<SyndicationCategory> ReadCategoryAsync(XmlReaderWrapper reader, SyndicationItem item)
+ {
+ SyndicationCategory result = CreateCategory(item);
+ await ReadCategoryAsync(reader, result);
+ return result;
+ }
+
+
+ private async Task<SyndicationLink> ReadMediaEnclosureAsync(XmlReaderWrapper reader, Uri baseUri)
+ {
+ SyndicationLink link = new SyndicationLink();
+ link.BaseUri = baseUri;
+ link.RelationshipType = Rss20Constants.EnclosureTag;
+ bool isEmptyElement = reader.IsEmptyElement;
+ if (reader.HasAttributes)
+ {
+ while (reader.MoveToNextAttribute())
+ {
+ string ns = reader.NamespaceURI;
+ string name = reader.LocalName;
+ if (name == "base" && ns == Atom10FeedFormatter.XmlNs)
+ {
+ link.BaseUri = FeedUtils.CombineXmlBase(link.BaseUri, await reader.GetValueAsync());
+ continue;
+ }
+ if (FeedUtils.IsXmlns(name, ns))
+ {
+ continue;
+ }
+ string val = await reader.GetValueAsync();
+ if (name == Rss20Constants.UrlTag && ns == Rss20Constants.Rss20Namespace)
+ {
+ link.Uri = new Uri(val, UriKind.RelativeOrAbsolute);
+ }
+ else if (name == Rss20Constants.TypeTag && ns == Rss20Constants.Rss20Namespace)
+ {
+ link.MediaType = val;
+ }
+ else if (name == Rss20Constants.LengthTag && ns == Rss20Constants.Rss20Namespace)
+ {
+ link.Length = !string.IsNullOrEmpty(val) ? Convert.ToInt64(val, CultureInfo.InvariantCulture.NumberFormat) : 0;
+ }
+ else if (!FeedUtils.IsXmlns(name, ns))
+ {
+ if (_preserveAttributeExtensions)
+ {
+ link.AttributeExtensions.Add(new XmlQualifiedName(name, ns), val);
+ }
+ }
+ }
+ }
+
+ await reader.ReadStartElementAsync(Rss20Constants.EnclosureTag, Rss20Constants.Rss20Namespace);
+
+ if (!isEmptyElement)
+ {
+ await reader.ReadEndElementAsync();
+ }
+
+ return link;
+ }
+
+ private async Task<SyndicationPerson> ReadPersonAsync(XmlReaderWrapper reader, SyndicationFeed feed)
+ {
+ SyndicationPerson result = CreatePerson(feed);
+ await ReadPersonAsync(reader, result);
+ return result;
+ }
+
+ private async Task ReadPersonAsync(XmlReaderWrapper reader, SyndicationPerson person)
+ {
+ bool isEmpty = reader.IsEmptyElement;
+ if (reader.HasAttributes)
+ {
+ while (reader.MoveToNextAttribute())
+ {
+ string ns = reader.NamespaceURI;
+ string name = reader.LocalName;
+ if (FeedUtils.IsXmlns(name, ns))
+ {
+ continue;
+ }
+ string val = await reader.GetValueAsync();
+ if (!TryParseAttribute(name, ns, val, person, this.Version))
+ {
+ if (_preserveAttributeExtensions)
+ {
+ person.AttributeExtensions.Add(new XmlQualifiedName(name, ns), val);
+ }
+ }
+ }
+ }
+
+ await reader.ReadStartElementAsync();
+ if (!isEmpty)
+ {
+ string email = StringParser(await reader.ReadStringAsync(),reader.LocalName,reader.NamespaceURI);
+ await reader.ReadEndElementAsync();
+ person.Email = email;
+ }
+ }
+
+ private async Task<SyndicationPerson> ReadPersonAsync(XmlReaderWrapper reader, SyndicationItem item)
+ {
+ SyndicationPerson result = CreatePerson(item);
+ await ReadPersonAsync(reader, result);
+ return result;
+ }
+
+ private bool checkTextInput(SyndicationTextInput textInput)
+ {
+ //All textInput items are required, we check if all items were instantiated.
+ return (textInput.Description != null && textInput.title != null && textInput.name != null && textInput.link != null);
+ }
+
+ private async Task readTextInputTag(XmlReaderWrapper reader, SyndicationFeed result)
+ {
+ await reader.ReadStartElementAsync();
+
+ SyndicationTextInput textInput = new SyndicationTextInput();
+ string val = String.Empty;
+
+ while (await reader.IsStartElementAsync())
+ {
+ string name = reader.LocalName;
+ string namespaceUri = reader.NamespaceURI;
+ val = StringParser(await reader.ReadElementStringAsync(), name, Rss20Constants.Rss20Namespace);
+
+ switch (name)
+ {
+ case Rss20Constants.DescriptionTag:
+ textInput.Description = val;
+ break;
+
+ case Rss20Constants.TitleTag:
+ textInput.title = val;
+ break;
+
+ case Rss20Constants.LinkTag:
+ textInput.link = new SyndicationLink(UriParser(val, name, namespaceUri));
+ break;
+
+ case Rss20Constants.NameTag:
+ textInput.name = val;
+ break;
+
+ default:
+ //ignore!
+ break;
+ }
+ }
+
+ if(checkTextInput(textInput) == true)
+ {
+ result.TextInput = textInput;
+ }
+
+ await reader.ReadEndElementAsync();
+ }
+
+ private async Task ReadXmlAsync(XmlReaderWrapper reader, SyndicationFeed result)
+ {
+ string baseUri = null;
+ await reader.MoveToContentAsync();
+
+ string version = reader.GetAttribute(Rss20Constants.VersionTag, Rss20Constants.Rss20Namespace);
+ if (version != Rss20Constants.Version)
+ {
+ throw new NotSupportedException(FeedUtils.AddLineInfo(reader, (string.Format(SR.UnsupportedRssVersion, version))));
+ }
+
+ if (reader.AttributeCount > 1)
+ {
+ string tmp = reader.GetAttribute("base", Atom10FeedFormatter.XmlNs);
+ if (!string.IsNullOrEmpty(tmp))
+ {
+ baseUri = tmp;
+ }
+ }
+
+ await reader.ReadStartElementAsync();
+ await reader.MoveToContentAsync();
+
+ if (reader.HasAttributes)
+ {
+ while (reader.MoveToNextAttribute())
+ {
+ string ns = reader.NamespaceURI;
+ string name = reader.LocalName;
+
+ if (name == "base" && ns == Atom10FeedFormatter.XmlNs)
+ {
+ baseUri = await reader.GetValueAsync();
+ continue;
+ }
+
+ if (FeedUtils.IsXmlns(name, ns) || FeedUtils.IsXmlSchemaType(name, ns))
+ {
+ continue;
+ }
+
+ string val = await reader.GetValueAsync();
+ if (!TryParseAttribute(name, ns, val, result, this.Version))
+ {
+ if (_preserveAttributeExtensions)
+ {
+ result.AttributeExtensions.Add(new XmlQualifiedName(name, ns), val);
+ }
+ }
+ }
+ }
+
+ if (!string.IsNullOrEmpty(baseUri))
+ {
+ result.BaseUri = new Uri(baseUri, UriKind.RelativeOrAbsolute);
+ }
+
+ bool areAllItemsRead = true;
+ await reader.ReadStartElementAsync(Rss20Constants.ChannelTag, Rss20Constants.Rss20Namespace);
+
+ XmlBuffer buffer = null;
+ XmlDictionaryWriter extWriter = null;
+ NullNotAllowedCollection<SyndicationItem> feedItems = new NullNotAllowedCollection<SyndicationItem>();
+
+ try
+ {
+ while (await reader.IsStartElementAsync())
+ {
+ bool notHandled = false;
+ if (await reader.MoveToContentAsync() == XmlNodeType.Element && reader.NamespaceURI == Rss20Constants.Rss20Namespace)
+ {
+ switch (reader.LocalName)
+ {
+ case Rss20Constants.TitleTag:
+ result.Title = new TextSyndicationContent(StringParser(await reader.ReadElementStringAsync(), Rss20Constants.TitleTag, Rss20Constants.Rss20Namespace));
+ break;
+
+ case Rss20Constants.LinkTag:
+ result.Links.Add(await ReadAlternateLinkAsync(reader, result.BaseUri));
+ break;
+
+ case Rss20Constants.DescriptionTag:
+ result.Description = new TextSyndicationContent(StringParser(await reader.ReadElementStringAsync(), Rss20Constants.DescriptionTag, Rss20Constants.Rss20Namespace));
+ break;
+
+ case Rss20Constants.LanguageTag:
+
+ result.Language = StringParser(await reader.ReadElementStringAsync(), Rss20Constants.LanguageTag, Rss20Constants.Rss20Namespace);
+ break;
+
+ case Rss20Constants.CopyrightTag:
+ result.Copyright = new TextSyndicationContent(StringParser(await reader.ReadElementStringAsync(), Rss20Constants.CopyrightTag, Rss20Constants.Rss20Namespace));
+ break;
+
+ case Rss20Constants.ManagingEditorTag:
+ result.Authors.Add(await ReadPersonAsync(reader, result));
+ break;
+
+ case Rss20Constants.LastBuildDateTag:
+ {
+ bool canReadContent = !reader.IsEmptyElement;
+ await reader.ReadStartElementAsync();
+ if (canReadContent)
+ {
+ string str = await reader.ReadStringAsync();
+
+ if (!string.IsNullOrEmpty(str))
+ {
+ result.LastUpdatedTime = DateParser(str, Rss20Constants.LastBuildDateTag, reader.NamespaceURI);
+ }
+
+ await reader.ReadEndElementAsync();
+ }
+
+ break;
+ }
+
+ case Rss20Constants.CategoryTag:
+ result.Categories.Add(await ReadCategoryAsync(reader, result));
+ break;
+
+ case Rss20Constants.GeneratorTag:
+ result.Generator = StringParser(await reader.ReadElementStringAsync(), Rss20Constants.GeneratorTag, Rss20Constants.Rss20Namespace);
+ break;
+
+ case Rss20Constants.ImageTag:
+ {
+ await OnReadImage(reader, result);
+ break;
+ }
+
+ case Rss20Constants.ItemTag:
+ {
+ NullNotAllowedCollection<SyndicationItem> items = new NullNotAllowedCollection<SyndicationItem>();
+ while (await reader.IsStartElementAsync(Rss20Constants.ItemTag, Rss20Constants.Rss20Namespace))
+ {
+ feedItems.Add(await ReadItemAsync(reader, result));
+ }
+
+
+ areAllItemsRead = true;
+ break;
+ }
+
+ //Optional tags
+ case Rss20Constants.DocumentationTag:
+ result.Documentation = await ReadAlternateLinkAsync(reader, result.BaseUri);
+ break;
+
+ case Rss20Constants.TimeToLiveTag:
+ string value = StringParser(await reader.ReadElementStringAsync(), Rss20Constants.TimeToLiveTag, Rss20Constants.Rss20Namespace);
+ int timeToLive = int.Parse(value);
+ result.TimeToLive = timeToLive;
+ break;
+
+ case Rss20Constants.TextInputTag:
+ await readTextInputTag(reader, result);
+ break;
+
+ case Rss20Constants.SkipHoursTag:
+ await ReadSkipHoursAsync(reader, result);
+ break;
+
+ case Rss20Constants.SkipDaysTag:
+ await ReadSkipDaysAsync(reader, result);
+ break;
+
+ default:
+ notHandled = true;
+ break;
+ }
+ }
+ else
+ {
+ notHandled = true;
+ }
+
+ if (notHandled)
+ {
+ bool parsedExtension = _serializeExtensionsAsAtom && await _atomSerializer.TryParseFeedElementFromAsync(reader, result);
+
+ if (!parsedExtension)
+ {
+ parsedExtension = TryParseElement(reader, result, this.Version);
+ }
+
+ if (!parsedExtension)
+ {
+ if (_preserveElementExtensions)
+ {
+ if (buffer == null)
+ {
+ buffer = new XmlBuffer(_maxExtensionSize);
+ extWriter = buffer.OpenSection(XmlDictionaryReaderQuotas.Max);
+ extWriter.WriteStartElement(Rss20Constants.ExtensionWrapperTag);
+ }
+
+ await XmlReaderWrapper.WriteNodeAsync(extWriter, reader, false);
+ }
+ else
+ {
+ await reader.SkipAsync();
+ }
+ }
+ }
+
+ if (!areAllItemsRead)
+ {
+ break;
+ }
+ }
+
+ //asign all read items to feed items.
+ result.Items = feedItems;
+ LoadElementExtensions(buffer, extWriter, result);
+ }
+ catch (FormatException e)
+ {
+ throw new XmlException(FeedUtils.AddLineInfo(reader, SR.ErrorParsingFeed), e);
+ }
+ catch (ArgumentException e)
+ {
+ throw new XmlException(FeedUtils.AddLineInfo(reader, SR.ErrorParsingFeed), e);
+ }
+ finally
+ {
+ if (extWriter != null)
+ {
+ ((IDisposable)extWriter).Dispose();
+ }
+ }
+ if (areAllItemsRead)
+ {
+ await reader.ReadEndElementAsync(); // channel
+ await reader.ReadEndElementAsync(); // rss
+ }
+ }
+
+ private async Task WriteAlternateLinkAsync(XmlWriter writer, SyndicationLink link, Uri baseUri)
+ {
+ await writer.WriteStartElementAsync(Rss20Constants.LinkTag, Rss20Constants.Rss20Namespace);
+ Uri baseUriToWrite = FeedUtils.GetBaseUriToWrite(baseUri, link.BaseUri);
+ if (baseUriToWrite != null)
+ {
+ await writer.WriteAttributeStringAsync("xml", "base", Atom10FeedFormatter.XmlNs, FeedUtils.GetUriString(baseUriToWrite));
+ }
+ await link.WriteAttributeExtensionsAsync(writer, SyndicationVersions.Rss20);
+ await writer.WriteStringAsync(FeedUtils.GetUriString(link.Uri));
+ await writer.WriteEndElementAsync();
+ }
+
+ private async Task WriteCategoryAsync(XmlWriter writer, SyndicationCategory category)
+ {
+ if (category == null)
+ {
+ return;
+ }
+ await writer.WriteStartElementAsync(Rss20Constants.CategoryTag, Rss20Constants.Rss20Namespace);
+ await WriteAttributeExtensionsAsync(writer, category, this.Version);
+ if (!string.IsNullOrEmpty(category.Scheme) && !category.AttributeExtensions.ContainsKey(s_rss20Domain))
+ {
+ await writer.WriteAttributeStringAsync(Rss20Constants.DomainTag, Rss20Constants.Rss20Namespace, category.Scheme);
+ }
+ await writer.WriteStringAsync(category.Name);
+ await writer.WriteEndElementAsync();
+ }
+
+ private async Task WriteFeedAsync(XmlWriter writer)
+ {
+ if (this.Feed == null)
+ {
+ throw new InvalidOperationException(SR.FeedFormatterDoesNotHaveFeed);
+ }
+ if (_serializeExtensionsAsAtom)
+ {
+ await writer.InternalWriteAttributeStringAsync("xmlns", Atom10Constants.Atom10Prefix, null, Atom10Constants.Atom10Namespace);
+ }
+ await writer.WriteAttributeStringAsync(Rss20Constants.VersionTag, Rss20Constants.Version);
+ await writer.WriteStartElementAsync(Rss20Constants.ChannelTag, Rss20Constants.Rss20Namespace);
+ if (this.Feed.BaseUri != null)
+ {
+ await writer.InternalWriteAttributeStringAsync("xml", "base", Atom10FeedFormatter.XmlNs, FeedUtils.GetUriString(this.Feed.BaseUri));
+ }
+ await WriteAttributeExtensionsAsync(writer, this.Feed, this.Version);
+ string title = this.Feed.Title != null ? this.Feed.Title.Text : string.Empty;
+ await writer.WriteElementStringAsync(Rss20Constants.TitleTag, Rss20Constants.Rss20Namespace, title);
+
+ SyndicationLink alternateLink = null;
+ for (int i = 0; i < this.Feed.Links.Count; ++i)
+ {
+ if (this.Feed.Links[i].RelationshipType == Atom10Constants.AlternateTag)
+ {
+ alternateLink = this.Feed.Links[i];
+ await WriteAlternateLinkAsync(writer, alternateLink, this.Feed.BaseUri);
+ break;
+ }
+ }
+
+ string description = this.Feed.Description != null ? this.Feed.Description.Text : string.Empty;
+ await writer.WriteElementStringAsync(Rss20Constants.DescriptionTag, Rss20Constants.Rss20Namespace, description);
+
+ if (this.Feed.Language != null)
+ {
+ await writer.WriteElementStringAsync(Rss20Constants.LanguageTag, this.Feed.Language);
+ }
+
+ if (this.Feed.Copyright != null)
+ {
+ await writer.WriteElementStringAsync(Rss20Constants.CopyrightTag, Rss20Constants.Rss20Namespace, this.Feed.Copyright.Text);
+ }
+
+ // if there's a single author with an email address, then serialize as the managingEditor
+ // else serialize the authors as Atom extensions
+ if ((this.Feed.Authors.Count == 1) && (this.Feed.Authors[0].Email != null))
+ {
+ await WritePersonAsync(writer, Rss20Constants.ManagingEditorTag, this.Feed.Authors[0]);
+ }
+ else
+ {
+ if (_serializeExtensionsAsAtom)
+ {
+ await _atomSerializer.WriteFeedAuthorsToAsync(writer, this.Feed.Authors);
+ }
+ }
+
+ if (this.Feed.LastUpdatedTime > DateTimeOffset.MinValue)
+ {
+ await writer.WriteStartElementAsync(Rss20Constants.LastBuildDateTag);
+ await writer.WriteStringAsync(AsString(this.Feed.LastUpdatedTime));
+ await writer.WriteEndElementAsync();
+ }
+
+ for (int i = 0; i < this.Feed.Categories.Count; ++i)
+ {
+ await WriteCategoryAsync(writer, this.Feed.Categories[i]);
+ }
+
+ if (!string.IsNullOrEmpty(this.Feed.Generator))
+ {
+ await writer.WriteElementStringAsync(Rss20Constants.GeneratorTag, this.Feed.Generator);
+ }
+
+ if (this.Feed.Contributors.Count > 0)
+ {
+ if (_serializeExtensionsAsAtom)
+ {
+ await _atomSerializer.WriteFeedContributorsToAsync(writer, this.Feed.Contributors);
+ }
+ }
+
+ if (this.Feed.ImageUrl != null)
+ {
+ await writer.WriteStartElementAsync(Rss20Constants.ImageTag);
+ await writer.WriteElementStringAsync(Rss20Constants.UrlTag, FeedUtils.GetUriString(this.Feed.ImageUrl));
+
+ string imageTitle = Feed.ImageTitle == null ? title : Feed.ImageTitle.Text;
+ await writer.WriteElementStringAsync(Rss20Constants.TitleTag, Rss20Constants.Rss20Namespace, imageTitle);
+
+ string imgAlternateLink = alternateLink != null ? FeedUtils.GetUriString(alternateLink.Uri) : string.Empty;
+
+ string imageLink = Feed.ImageLink == null ? imgAlternateLink : FeedUtils.GetUriString(Feed.ImageLink);
+ await writer.WriteElementStringAsync(Rss20Constants.LinkTag, Rss20Constants.Rss20Namespace, imageLink);
+ await writer.WriteEndElementAsync(); // image
+ }
+
+ //Optional spec items
+ //time to live
+ if(this.Feed.TimeToLive != 0)
+ {
+ await writer.WriteElementStringAsync(Rss20Constants.TimeToLiveTag, this.Feed.TimeToLive.ToString());
+ }
+
+ //skiphours
+ if(this.Feed.SkipHours.Count > 0)
+ {
+ await writer.WriteStartElementAsync(Rss20Constants.SkipHoursTag);
+
+ foreach(int hour in this.Feed.SkipHours)
+ {
+ writer.WriteElementString(Rss20Constants.HourTag,hour.ToString());
+ }
+
+ await writer.WriteEndElementAsync();
+ }
+
+ //skipDays
+ if(this.Feed.SkipDays.Count > 0)
+ {
+ await writer.WriteStartElementAsync(Rss20Constants.SkipDaysTag);
+
+ foreach(string day in this.Feed.SkipDays)
+ {
+ await writer.WriteElementStringAsync(Rss20Constants.DayTag,day);
+ }
+
+ await writer.WriteEndElementAsync();
+ }
+
+ //textinput
+ if(this.Feed.TextInput != null)
+ {
+ await writer.WriteStartElementAsync(Rss20Constants.TextInputTag);
+
+ await writer.WriteElementStringAsync(Rss20Constants.DescriptionTag, this.Feed.TextInput.Description);
+ await writer.WriteElementStringAsync(Rss20Constants.TitleTag, this.Feed.TextInput.title);
+ await writer.WriteElementStringAsync(Rss20Constants.LinkTag, this.Feed.TextInput.link.GetAbsoluteUri().ToString());
+ await writer.WriteElementStringAsync(Rss20Constants.NameTag, this.Feed.TextInput.name);
+
+ await writer.WriteEndElementAsync();
+ }
+
+ if (_serializeExtensionsAsAtom)
+ {
+ await _atomSerializer.WriteElementAsync(writer, Atom10Constants.IdTag, this.Feed.Id);
+
+ // dont write out the 1st alternate link since that would have been written out anyway
+ bool isFirstAlternateLink = true;
+ for (int i = 0; i < this.Feed.Links.Count; ++i)
+ {
+ if (this.Feed.Links[i].RelationshipType == Atom10Constants.AlternateTag && isFirstAlternateLink)
+ {
+ isFirstAlternateLink = false;
+ continue;
+ }
+ await _atomSerializer.WriteLinkAsync(writer, this.Feed.Links[i], this.Feed.BaseUri);
+ }
+ }
+
+ await WriteElementExtensionsAsync(writer, this.Feed, this.Version);
+ await WriteItemsAsync(writer, this.Feed.Items, this.Feed.BaseUri);
+ await writer.WriteEndElementAsync(); // channel
+ }
+
+ private async Task WriteItemContentsAsync(XmlWriter writer, SyndicationItem item, Uri feedBaseUri)
+ {
+ Uri baseUriToWrite = FeedUtils.GetBaseUriToWrite(feedBaseUri, item.BaseUri);
+ if (baseUriToWrite != null)
+ {
+ await writer.InternalWriteAttributeStringAsync("xml", "base", Atom10FeedFormatter.XmlNs, FeedUtils.GetUriString(baseUriToWrite));
+ }
+ await WriteAttributeExtensionsAsync(writer, item, this.Version);
+ string guid = item.Id ?? string.Empty;
+ bool isPermalink = false;
+ SyndicationLink firstAlternateLink = null;
+ for (int i = 0; i < item.Links.Count; ++i)
+ {
+ if (item.Links[i].RelationshipType == Atom10Constants.AlternateTag)
+ {
+ if (firstAlternateLink == null)
+ {
+ firstAlternateLink = item.Links[i];
+ }
+ if (guid == FeedUtils.GetUriString(item.Links[i].Uri))
+ {
+ isPermalink = true;
+ break;
+ }
+ }
+ }
+ if (!string.IsNullOrEmpty(guid))
+ {
+ await writer.WriteStartElementAsync(Rss20Constants.GuidTag);
+ if (isPermalink)
+ {
+ await writer.WriteAttributeStringAsync(Rss20Constants.IsPermaLinkTag, "true");
+ }
+ else
+ {
+ await writer.WriteAttributeStringAsync(Rss20Constants.IsPermaLinkTag, "false");
+ }
+ await writer.WriteStringAsync(guid);
+ await writer.WriteEndElementAsync();
+ }
+ if (firstAlternateLink != null)
+ {
+ await WriteAlternateLinkAsync(writer, firstAlternateLink, (item.BaseUri != null ? item.BaseUri : feedBaseUri));
+ }
+
+ if (item.Authors.Count == 1 && !string.IsNullOrEmpty(item.Authors[0].Email))
+ {
+ await WritePersonAsync(writer, Rss20Constants.AuthorTag, item.Authors[0]);
+ }
+ else
+ {
+ if (_serializeExtensionsAsAtom)
+ {
+ await _atomSerializer.WriteItemAuthorsToAsync(writer, item.Authors);
+ }
+ }
+
+ for (int i = 0; i < item.Categories.Count; ++i)
+ {
+ await WriteCategoryAsync(writer, item.Categories[i]);
+ }
+
+ bool serializedTitle = false;
+ if (item.Title != null)
+ {
+ await writer.WriteElementStringAsync(Rss20Constants.TitleTag, item.Title.Text);
+ serializedTitle = true;
+ }
+
+ bool serializedContentAsDescription = false;
+ TextSyndicationContent summary = item.Summary;
+ if (summary == null)
+ {
+ summary = (item.Content as TextSyndicationContent);
+ serializedContentAsDescription = (summary != null);
+ }
+ // the spec requires the wire to have a title or a description
+ if (!serializedTitle && summary == null)
+ {
+ summary = new TextSyndicationContent(string.Empty);
+ }
+ if (summary != null)
+ {
+ await writer.WriteElementStringAsync(Rss20Constants.DescriptionTag, Rss20Constants.Rss20Namespace, summary.Text);
+ }
+
+ if (item.SourceFeed != null)
+ {
+ await writer.WriteStartElementAsync(Rss20Constants.SourceTag, Rss20Constants.Rss20Namespace);
+ await WriteAttributeExtensionsAsync(writer, item.SourceFeed, this.Version);
+ SyndicationLink selfLink = null;
+ for (int i = 0; i < item.SourceFeed.Links.Count; ++i)
+ {
+ if (item.SourceFeed.Links[i].RelationshipType == Atom10Constants.SelfTag)
+ {
+ selfLink = item.SourceFeed.Links[i];
+ break;
+ }
+ }
+ if (selfLink != null && !item.SourceFeed.AttributeExtensions.ContainsKey(s_rss20Url))
+ {
+ await writer.WriteAttributeStringAsync(Rss20Constants.UrlTag, Rss20Constants.Rss20Namespace, FeedUtils.GetUriString(selfLink.Uri));
+ }
+ string title = (item.SourceFeed.Title != null) ? item.SourceFeed.Title.Text : string.Empty;
+ await writer.WriteStringAsync(title);
+ await writer.WriteEndElementAsync();
+ }
+
+ if (item.PublishDate > DateTimeOffset.MinValue)
+ {
+ await writer.WriteElementStringAsync(Rss20Constants.PubDateTag, Rss20Constants.Rss20Namespace, AsString(item.PublishDate));
+ }
+
+ // serialize the enclosures
+ SyndicationLink firstEnclosureLink = null;
+ bool passedFirstAlternateLink = false;
+
+ for (int i = 0; i < item.Links.Count; ++i)
+ {
+ if (item.Links[i].RelationshipType == Rss20Constants.EnclosureTag)
+ {
+ if (firstEnclosureLink == null)
+ {
+ firstEnclosureLink = item.Links[i];
+ await WriteMediaEnclosureAsync(writer, item.Links[i], item.BaseUri);
+ continue;
+ }
+ }
+ else if (item.Links[i].RelationshipType == Atom10Constants.AlternateTag)
+ {
+ if (!passedFirstAlternateLink)
+ {
+ passedFirstAlternateLink = true;
+ continue;
+ }
+ }
+ if (_serializeExtensionsAsAtom)
+ {
+ await _atomSerializer.WriteLinkAsync(writer, item.Links[i], item.BaseUri);
+ }
+ }
+
+
+ if (item.LastUpdatedTime > DateTimeOffset.MinValue)
+ {
+ if (_serializeExtensionsAsAtom)
+ {
+ await _atomSerializer.WriteItemLastUpdatedTimeToAsync(writer, item.LastUpdatedTime);
+ }
+ }
+
+ if (_serializeExtensionsAsAtom)
+ {
+ await _atomSerializer.WriteContentToAsync(writer, Atom10Constants.RightsTag, item.Copyright);
+ }
+
+ if (!serializedContentAsDescription)
+ {
+ if (_serializeExtensionsAsAtom)
+ {
+ await _atomSerializer.WriteContentToAsync(writer, Atom10Constants.ContentTag, item.Content);
+ }
+ }
+
+ if (item.Contributors.Count > 0)
+ {
+ if (_serializeExtensionsAsAtom)
+ {
+ await _atomSerializer.WriteItemContributorsToAsync(writer, item.Contributors);
+ }
+ }
+
+ await WriteElementExtensionsAsync(writer, item, this.Version);
+ }
+
+ private async Task WriteMediaEnclosureAsync(XmlWriter writer, SyndicationLink link, Uri baseUri)
+ {
+ await writer.WriteStartElementAsync(Rss20Constants.EnclosureTag, Rss20Constants.Rss20Namespace);
+ Uri baseUriToWrite = FeedUtils.GetBaseUriToWrite(baseUri, link.BaseUri);
+ if (baseUriToWrite != null)
+ {
+ await writer.InternalWriteAttributeStringAsync("xml", "base", Atom10FeedFormatter.XmlNs, FeedUtils.GetUriString(baseUriToWrite));
+ }
+ await link.WriteAttributeExtensionsAsync(writer, SyndicationVersions.Rss20);
+ if (!link.AttributeExtensions.ContainsKey(s_rss20Url))
+ {
+ await writer.WriteAttributeStringAsync(Rss20Constants.UrlTag, Rss20Constants.Rss20Namespace, FeedUtils.GetUriString(link.Uri));
+ }
+ if (link.MediaType != null && !link.AttributeExtensions.ContainsKey(s_rss20Type))
+ {
+ await writer.WriteAttributeStringAsync(Rss20Constants.TypeTag, Rss20Constants.Rss20Namespace, link.MediaType);
+ }
+ if (link.Length != 0 && !link.AttributeExtensions.ContainsKey(s_rss20Length))
+ {
+ await writer.WriteAttributeStringAsync(Rss20Constants.LengthTag, Rss20Constants.Rss20Namespace, Convert.ToString(link.Length, CultureInfo.InvariantCulture));
+ }
+ await writer.WriteEndElementAsync();
+ }
+
+ private async Task WritePersonAsync(XmlWriter writer, string elementTag, SyndicationPerson person)
+ {
+ await writer.WriteStartElementAsync(elementTag, Rss20Constants.Rss20Namespace);
+ await WriteAttributeExtensionsAsync(writer, person, this.Version);
+ await writer.WriteStringAsync(person.Email);
+ await writer.WriteEndElementAsync();
+ }
+
+ private static bool OriginalDateParser(string dateTimeString, out DateTimeOffset dto)
+ {
+ StringBuilder dateTimeStringBuilder = new StringBuilder(dateTimeString.Trim());
+ if (dateTimeStringBuilder.Length < 18)
+ {
+ return false;
+ }
+
+ int timeZoneStartIndex;
+ for (timeZoneStartIndex = dateTimeStringBuilder.Length-1; dateTimeStringBuilder[timeZoneStartIndex] != ' '; timeZoneStartIndex--);
+ timeZoneStartIndex++;
+
+ string timeZoneSuffix = dateTimeStringBuilder.ToString().Substring(timeZoneStartIndex);
+ dateTimeStringBuilder.Remove(timeZoneStartIndex, dateTimeStringBuilder.Length - timeZoneStartIndex);
+ bool isUtc;
+ dateTimeStringBuilder.Append(NormalizeTimeZone(timeZoneSuffix, out isUtc));
+ string wellFormattedString = dateTimeStringBuilder.ToString();
+
+ DateTimeOffset theTime;
+ string[] parseFormat =
+ {
+ "ddd, dd MMMM yyyy HH:mm:ss zzz",
+ "dd MMMM yyyy HH:mm:ss zzz",
+ "ddd, dd MMM yyyy HH:mm:ss zzz",
+ "dd MMM yyyy HH:mm:ss zzz",
+
+ "ddd, dd MMMM yyyy HH:mm zzz",
+ "dd MMMM yyyy HH:mm zzz",
+ "ddd, dd MMM yyyy HH:mm zzz",
+ "dd MMM yyyy HH:mm zzz"
+ };
+
+ if (DateTimeOffset.TryParseExact(wellFormattedString, parseFormat,
+ CultureInfo.InvariantCulture.DateTimeFormat,
+ (isUtc ? DateTimeStyles.AdjustToUniversal : DateTimeStyles.None), out theTime))
+ {
+ dto = theTime;
+ return true;
+ }
+
+ return false;
+ }
+
+ // Custom parsers
+ public static DateTimeOffset DefaultDateParser(string dateTimeString, string localName, string ns)
+ {
+ bool parsed = false;
+ DateTimeOffset dto;
+ parsed = DateTimeOffset.TryParse(dateTimeString, out dto);
+ if (parsed)
+ return dto;
+
+
+ //original parser here
+ parsed = OriginalDateParser(dateTimeString,out dto);
+ if (parsed)
+ return dto;
+
+ //Impossible to parse - using a default date;
+ return new DateTimeOffset();
+ }
+ }
+
+ [XmlRoot(ElementName = Rss20Constants.RssTag, Namespace = Rss20Constants.Rss20Namespace)]
+ public class Rss20FeedFormatter<TSyndicationFeed> : Rss20FeedFormatter
+ where TSyndicationFeed : SyndicationFeed, new()
+ {
+ // constructors
+ public Rss20FeedFormatter()
+ : base(typeof(TSyndicationFeed))
+ {
+ }
+ public Rss20FeedFormatter(TSyndicationFeed feedToWrite)
+ : base(feedToWrite)
+ {
+ }
+ public Rss20FeedFormatter(TSyndicationFeed feedToWrite, bool serializeExtensionsAsAtom)
+ : base(feedToWrite, serializeExtensionsAsAtom)
+ {
+ }
+
+ protected override SyndicationFeed CreateFeedInstance()
+ {
+ return new TSyndicationFeed();
+ }
+ }
+
+
+ internal class ItemParseOptions
+ {
+ public bool readItemsAtLeastOnce;
+ public bool areAllItemsRead;
+
+ public ItemParseOptions(bool readItemsAtLeastOnce, bool areAllItemsRead)
+ {
+ this.readItemsAtLeastOnce = readItemsAtLeastOnce;
+ this.areAllItemsRead = areAllItemsRead;
+ }
+ }
+}
diff --git a/src/System.ServiceModel.Syndication/src/System/ServiceModel/Syndication/Rss20ItemFormatter.cs b/src/System.ServiceModel.Syndication/src/System/ServiceModel/Syndication/Rss20ItemFormatter.cs
new file mode 100644
index 0000000000..6581dff9c9
--- /dev/null
+++ b/src/System.ServiceModel.Syndication/src/System/ServiceModel/Syndication/Rss20ItemFormatter.cs
@@ -0,0 +1,195 @@
+// 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.ServiceModel.Syndication
+{
+ using System;
+ using System.Diagnostics.CodeAnalysis;
+ using System.Runtime.CompilerServices;
+ using System.Threading.Tasks;
+ using System.Xml;
+ using System.Xml.Schema;
+ using System.Xml.Serialization;
+
+
+ [XmlRoot(ElementName = Rss20Constants.ItemTag, Namespace = Rss20Constants.Rss20Namespace)]
+ public class Rss20ItemFormatter : SyndicationItemFormatter
+ {
+ private Rss20FeedFormatter _feedSerializer;
+ private Type _itemType;
+ private bool _preserveAttributeExtensions;
+ private bool _preserveElementExtensions;
+ private bool _serializeExtensionsAsAtom;
+
+ public Rss20ItemFormatter()
+ : this(typeof(SyndicationItem))
+ {
+ }
+
+ public Rss20ItemFormatter(Type itemTypeToCreate)
+ : base()
+ {
+ if (itemTypeToCreate == null)
+ {
+ throw new ArgumentNullException(nameof(itemTypeToCreate));
+ }
+ if (!typeof(SyndicationItem).IsAssignableFrom(itemTypeToCreate))
+ {
+ throw new ArgumentException(string.Format(SR.InvalidObjectTypePassed, nameof(itemTypeToCreate), nameof(SyndicationItem)));
+ }
+ _feedSerializer = new Rss20FeedFormatter();
+ _feedSerializer.PreserveAttributeExtensions = _preserveAttributeExtensions = true;
+ _feedSerializer.PreserveElementExtensions = _preserveElementExtensions = true;
+ _feedSerializer.SerializeExtensionsAsAtom = _serializeExtensionsAsAtom = true;
+ _itemType = itemTypeToCreate;
+ }
+
+ public Rss20ItemFormatter(SyndicationItem itemToWrite)
+ : this(itemToWrite, true)
+ {
+ }
+
+ public Rss20ItemFormatter(SyndicationItem itemToWrite, bool serializeExtensionsAsAtom)
+ : base(itemToWrite)
+ {
+ // No need to check that the parameter passed is valid - it is checked by the c'tor of the base class
+ _feedSerializer = new Rss20FeedFormatter();
+ _feedSerializer.PreserveAttributeExtensions = _preserveAttributeExtensions = true;
+ _feedSerializer.PreserveElementExtensions = _preserveElementExtensions = true;
+ _feedSerializer.SerializeExtensionsAsAtom = _serializeExtensionsAsAtom = serializeExtensionsAsAtom;
+ _itemType = itemToWrite.GetType();
+ }
+
+ public bool PreserveAttributeExtensions
+ {
+ get { return _preserveAttributeExtensions; }
+ set
+ {
+ _preserveAttributeExtensions = value;
+ _feedSerializer.PreserveAttributeExtensions = value;
+ }
+ }
+
+ public bool PreserveElementExtensions
+ {
+ get { return _preserveElementExtensions; }
+ set
+ {
+ _preserveElementExtensions = value;
+ _feedSerializer.PreserveElementExtensions = value;
+ }
+ }
+
+ public bool SerializeExtensionsAsAtom
+ {
+ get { return _serializeExtensionsAsAtom; }
+ set
+ {
+ _serializeExtensionsAsAtom = value;
+ _feedSerializer.SerializeExtensionsAsAtom = value;
+ }
+ }
+
+ public override string Version
+ {
+ get { return SyndicationVersions.Rss20; }
+ }
+
+ protected Type ItemType
+ {
+ get
+ {
+ return _itemType;
+ }
+ }
+
+ public override bool CanRead(XmlReader reader)
+ {
+ if (reader == null)
+ {
+ throw new ArgumentNullException(nameof(reader));
+ }
+
+ return reader.IsStartElement(Rss20Constants.ItemTag, Rss20Constants.Rss20Namespace);
+ }
+
+
+ async Task WriteXml(XmlWriter writer)
+ {
+ if (writer == null)
+ {
+ throw new ArgumentNullException(nameof(writer));
+ }
+ await WriteItem(writer);
+ }
+
+ public override Task ReadFromAsync(XmlReader reader)
+ {
+ if (!CanRead(reader))
+ {
+ throw new XmlException(string.Format(SR.UnknownItemXml, reader.LocalName, reader.NamespaceURI));
+ }
+
+ return ReadItemAsync(XmlReaderWrapper.CreateFromReader(reader));
+ }
+
+ public override async Task WriteToAsync(XmlWriter writer)
+ {
+ if (writer == null)
+ {
+ throw new ArgumentNullException(nameof(writer));
+ }
+
+ writer = XmlWriterWrapper.CreateFromWriter(writer);
+
+ await writer.WriteStartElementAsync(Rss20Constants.ItemTag, Rss20Constants.Rss20Namespace);
+ await WriteItem(writer);
+ await writer.WriteEndElementAsync();
+ }
+
+ protected override SyndicationItem CreateItemInstance()
+ {
+ return SyndicationItemFormatter.CreateItemInstance(_itemType);
+ }
+
+ private Task ReadItemAsync(XmlReaderWrapper reader)
+ {
+ SetItem(CreateItemInstance());
+ return _feedSerializer.ReadItemFromAsync(XmlReaderWrapper.CreateFromReader(XmlDictionaryReader.CreateDictionaryReader(reader)), this.Item);
+ }
+
+ private Task WriteItem(XmlWriter writer)
+ {
+ if (this.Item == null)
+ {
+ throw new InvalidOperationException(SR.ItemFormatterDoesNotHaveItem);
+ }
+ XmlDictionaryWriter w = XmlDictionaryWriter.CreateDictionaryWriter(writer);
+ return _feedSerializer.WriteItemContentsAsync(w, this.Item);
+ }
+ }
+
+ [XmlRoot(ElementName = Rss20Constants.ItemTag, Namespace = Rss20Constants.Rss20Namespace)]
+ public class Rss20ItemFormatter<TSyndicationItem> : Rss20ItemFormatter
+ where TSyndicationItem : SyndicationItem, new()
+ {
+ public Rss20ItemFormatter()
+ : base(typeof(TSyndicationItem))
+ {
+ }
+ public Rss20ItemFormatter(TSyndicationItem itemToWrite)
+ : base(itemToWrite)
+ {
+ }
+ public Rss20ItemFormatter(TSyndicationItem itemToWrite, bool serializeExtensionsAsAtom)
+ : base(itemToWrite, serializeExtensionsAsAtom)
+ {
+ }
+
+ protected override SyndicationItem CreateItemInstance()
+ {
+ return new TSyndicationItem();
+ }
+ }
+}
diff --git a/src/System.ServiceModel.Syndication/src/System/ServiceModel/Syndication/ServiceDocument.cs b/src/System.ServiceModel.Syndication/src/System/ServiceModel/Syndication/ServiceDocument.cs
new file mode 100644
index 0000000000..f21e658cbc
--- /dev/null
+++ b/src/System.ServiceModel.Syndication/src/System/ServiceModel/Syndication/ServiceDocument.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.
+
+namespace System.ServiceModel.Syndication
+{
+ using System;
+ using System.Collections.Generic;
+ using System.Collections.ObjectModel;
+ using System.Runtime.CompilerServices;
+ using System.Threading.Tasks;
+ using System.Xml;
+
+ public class ServiceDocument : IExtensibleSyndicationObject
+ {
+ private Uri _baseUri;
+ private ExtensibleSyndicationObject _extensions = new ExtensibleSyndicationObject();
+ private string _language;
+ private Collection<Workspace> _workspaces;
+
+ public ServiceDocument() : this(null)
+ {
+ }
+
+ public ServiceDocument(IEnumerable<Workspace> workspaces)
+ {
+ if (workspaces != null)
+ {
+ _workspaces = new NullNotAllowedCollection<Workspace>();
+ foreach (Workspace workspace in workspaces)
+ {
+ _workspaces.Add(workspace);
+ }
+ }
+ }
+
+ public Dictionary<XmlQualifiedName, string> AttributeExtensions
+ {
+ get { return _extensions.AttributeExtensions; }
+ }
+
+ public Uri BaseUri
+ {
+ get { return _baseUri; }
+ set { _baseUri = value; }
+ }
+
+ public SyndicationElementExtensionCollection ElementExtensions
+ {
+ get { return _extensions.ElementExtensions; }
+ }
+
+ public string Language
+ {
+ get { return _language; }
+ set { _language = value; }
+ }
+
+ public Collection<Workspace> Workspaces
+ {
+ get
+ {
+ if (_workspaces == null)
+ {
+ _workspaces = new NullNotAllowedCollection<Workspace>();
+ }
+ return _workspaces;
+ }
+ }
+
+ public static async Task<TServiceDocument> LoadAsync<TServiceDocument>(XmlReader reader)
+ where TServiceDocument : ServiceDocument, new()
+ {
+ AtomPub10ServiceDocumentFormatter<TServiceDocument> formatter = new AtomPub10ServiceDocumentFormatter<TServiceDocument>();
+ await formatter.ReadFromAsync(reader);
+ return (TServiceDocument)(object)formatter.Document;
+ }
+
+ public ServiceDocumentFormatter GetFormatter()
+ {
+ return new AtomPub10ServiceDocumentFormatter(this);
+ }
+
+ public Task Save(XmlWriter writer)
+ {
+ return new AtomPub10ServiceDocumentFormatter(this).WriteToAsync(writer);
+ }
+
+ protected internal virtual Workspace CreateWorkspace()
+ {
+ return new Workspace();
+ }
+
+ protected internal virtual bool TryParseAttribute(string name, string ns, string value, string version)
+ {
+ return false;
+ }
+
+ protected internal virtual bool TryParseElement(XmlReader reader, string version)
+ {
+ return false;
+ }
+
+ protected internal virtual Task WriteAttributeExtensionsAsync(XmlWriter writer, string version)
+ {
+ return _extensions.WriteAttributeExtensionsAsync(writer);
+ }
+
+ protected internal virtual Task WriteElementExtensionsAsync(XmlWriter writer, string version)
+ {
+ return _extensions.WriteElementExtensionsAsync(writer);
+ }
+
+ internal void LoadElementExtensions(XmlReaderWrapper readerOverUnparsedExtensions, int maxExtensionSize)
+ {
+ _extensions.LoadElementExtensions(readerOverUnparsedExtensions, maxExtensionSize);
+ }
+
+ internal void LoadElementExtensions(XmlBuffer buffer)
+ {
+ _extensions.LoadElementExtensions(buffer);
+ }
+ }
+}
diff --git a/src/System.ServiceModel.Syndication/src/System/ServiceModel/Syndication/ServiceDocumentFormatter.cs b/src/System.ServiceModel.Syndication/src/System/ServiceModel/Syndication/ServiceDocumentFormatter.cs
new file mode 100644
index 0000000000..1dcfd04bc4
--- /dev/null
+++ b/src/System.ServiceModel.Syndication/src/System/ServiceModel/Syndication/ServiceDocumentFormatter.cs
@@ -0,0 +1,329 @@
+// 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.ServiceModel.Syndication
+{
+ using System;
+ using System.Runtime.CompilerServices;
+ using System.Runtime.Serialization;
+ using System.Threading.Tasks;
+ using System.Xml;
+
+ [DataContract]
+ public abstract class ServiceDocumentFormatter
+ {
+ private ServiceDocument _document;
+
+ protected ServiceDocumentFormatter()
+ {
+ }
+ protected ServiceDocumentFormatter(ServiceDocument documentToWrite)
+ {
+ if (documentToWrite == null)
+ {
+ throw new ArgumentNullException(nameof(documentToWrite));
+ }
+ _document = documentToWrite;
+ }
+
+ public ServiceDocument Document
+ {
+ get { return _document; }
+ }
+
+ public abstract string Version
+ { get; }
+
+ public abstract Task<bool> CanReadAsync(XmlReader reader);
+ public abstract Task ReadFromAsync(XmlReader reader);
+ public abstract Task WriteToAsync(XmlWriter writer);
+
+ internal static void LoadElementExtensions(XmlBuffer buffer, XmlDictionaryWriter writer, CategoriesDocument categories)
+ {
+ if (categories == null)
+ {
+ throw new ArgumentNullException(nameof(categories));
+ }
+ Atom10FeedFormatter.CloseBuffer(buffer, writer);
+ categories.LoadElementExtensions(buffer);
+ }
+
+ internal static void LoadElementExtensions(XmlBuffer buffer, XmlDictionaryWriter writer, ResourceCollectionInfo collection)
+ {
+ if (collection == null)
+ {
+ throw new ArgumentNullException(nameof(collection));
+ }
+ Atom10FeedFormatter.CloseBuffer(buffer, writer);
+ collection.LoadElementExtensions(buffer);
+ }
+
+ internal static void LoadElementExtensions(XmlBuffer buffer, XmlDictionaryWriter writer, Workspace workspace)
+ {
+ if (workspace == null)
+ {
+ throw new ArgumentNullException(nameof(workspace));
+ }
+ Atom10FeedFormatter.CloseBuffer(buffer, writer);
+ workspace.LoadElementExtensions(buffer);
+ }
+
+ internal static void LoadElementExtensions(XmlBuffer buffer, XmlDictionaryWriter writer, ServiceDocument document)
+ {
+ if (document == null)
+ {
+ throw new ArgumentNullException(nameof(document));
+ }
+ Atom10FeedFormatter.CloseBuffer(buffer, writer);
+ document.LoadElementExtensions(buffer);
+ }
+
+ protected static SyndicationCategory CreateCategory(InlineCategoriesDocument inlineCategories)
+ {
+ if (inlineCategories == null)
+ {
+ throw new ArgumentNullException(nameof(inlineCategories));
+ }
+ return inlineCategories.CreateCategory();
+ }
+
+ protected static ResourceCollectionInfo CreateCollection(Workspace workspace)
+ {
+ if (workspace == null)
+ {
+ throw new ArgumentNullException(nameof(workspace));
+ }
+ return workspace.CreateResourceCollection();
+ }
+
+ protected static InlineCategoriesDocument CreateInlineCategories(ResourceCollectionInfo collection)
+ {
+ return collection.CreateInlineCategoriesDocument();
+ }
+
+ protected static ReferencedCategoriesDocument CreateReferencedCategories(ResourceCollectionInfo collection)
+ {
+ return collection.CreateReferencedCategoriesDocument();
+ }
+
+ protected static Workspace CreateWorkspace(ServiceDocument document)
+ {
+ if (document == null)
+ {
+ throw new ArgumentNullException(nameof(document));
+ }
+ return document.CreateWorkspace();
+ }
+
+ protected static void LoadElementExtensions(XmlReader reader, CategoriesDocument categories, int maxExtensionSize)
+ {
+ if (categories == null)
+ {
+ throw new ArgumentNullException(nameof(categories));
+ }
+
+ categories.LoadElementExtensions(XmlReaderWrapper.CreateFromReader(reader), maxExtensionSize);
+ }
+
+ protected static void LoadElementExtensions(XmlReader reader, ResourceCollectionInfo collection, int maxExtensionSize)
+ {
+ if (collection == null)
+ {
+ throw new ArgumentNullException(nameof(collection));
+ }
+
+ collection.LoadElementExtensions(XmlReaderWrapper.CreateFromReader(reader), maxExtensionSize);
+ }
+
+ protected static void LoadElementExtensions(XmlReader reader, Workspace workspace, int maxExtensionSize)
+ {
+ if (workspace == null)
+ {
+ throw new ArgumentNullException(nameof(workspace));
+ }
+
+ workspace.LoadElementExtensions(XmlReaderWrapper.CreateFromReader(reader), maxExtensionSize);
+ }
+
+ protected static void LoadElementExtensions(XmlReader reader, ServiceDocument document, int maxExtensionSize)
+ {
+ if (document == null)
+ {
+ throw new ArgumentNullException(nameof(document));
+ }
+
+ document.LoadElementExtensions(XmlReaderWrapper.CreateFromReader(reader), maxExtensionSize);
+ }
+
+ protected static bool TryParseAttribute(string name, string ns, string value, ServiceDocument document, string version)
+ {
+ if (document == null)
+ {
+ throw new ArgumentNullException(nameof(document));
+ }
+
+ return document.TryParseAttribute(name, ns, value, version);
+ }
+
+ protected static bool TryParseAttribute(string name, string ns, string value, ResourceCollectionInfo collection, string version)
+ {
+ if (collection == null)
+ {
+ throw new ArgumentNullException(nameof(collection));
+ }
+
+ return collection.TryParseAttribute(name, ns, value, version);
+ }
+
+ protected static bool TryParseAttribute(string name, string ns, string value, CategoriesDocument categories, string version)
+ {
+ if (categories == null)
+ {
+ throw new ArgumentNullException(nameof(categories));
+ }
+
+ return categories.TryParseAttribute(name, ns, value, version);
+ }
+
+ protected static bool TryParseAttribute(string name, string ns, string value, Workspace workspace, string version)
+ {
+ if (workspace == null)
+ {
+ throw new ArgumentNullException(nameof(workspace));
+ }
+
+ return workspace.TryParseAttribute(name, ns, value, version);
+ }
+
+ protected static bool TryParseElement(XmlReader reader, ResourceCollectionInfo collection, string version)
+ {
+ if (collection == null)
+ {
+ throw new ArgumentNullException(nameof(collection));
+ }
+
+ return collection.TryParseElement(XmlReaderWrapper.CreateFromReader(reader), version);
+ }
+
+ protected static bool TryParseElement(XmlReader reader, ServiceDocument document, string version)
+ {
+ if (document == null)
+ {
+ throw new ArgumentNullException(nameof(document));
+ }
+
+ return document.TryParseElement(XmlReaderWrapper.CreateFromReader(reader), version);
+ }
+
+ protected static bool TryParseElement(XmlReader reader, Workspace workspace, string version)
+ {
+ if (workspace == null)
+ {
+ throw new ArgumentNullException(nameof(workspace));
+ }
+
+ return workspace.TryParseElement(XmlReaderWrapper.CreateFromReader(reader), version);
+ }
+
+ protected static bool TryParseElement(XmlReader reader, CategoriesDocument categories, string version)
+ {
+ if (categories == null)
+ {
+ throw new ArgumentNullException(nameof(categories));
+ }
+
+ return categories.TryParseElement(XmlReaderWrapper.CreateFromReader(reader), version);
+ }
+
+ protected static void WriteAttributeExtensions(XmlWriter writer, ServiceDocument document, string version)
+ {
+ if (document == null)
+ {
+ throw new ArgumentNullException(nameof(document));
+ }
+
+ document.WriteAttributeExtensionsAsync(writer, version);
+ }
+
+ protected static void WriteAttributeExtensions(XmlWriter writer, Workspace workspace, string version)
+ {
+ if (workspace == null)
+ {
+ throw new ArgumentNullException(nameof(workspace));
+ }
+
+ workspace.WriteAttributeExtensions(writer, version);
+ }
+
+ protected static Task WriteAttributeExtensionsAsync(XmlWriter writer, ResourceCollectionInfo collection, string version)
+ {
+ if (collection == null)
+ {
+ throw new ArgumentNullException(nameof(collection));
+ }
+
+ return collection.WriteAttributeExtensionsAsync(writer, version);
+ }
+
+ protected static Task WriteAttributeExtensionsAsync(XmlWriter writer, CategoriesDocument categories, string version)
+ {
+ if (categories == null)
+ {
+ throw new ArgumentNullException(nameof(categories));
+ }
+
+ return categories.WriteAttributeExtensionsAsync(writer, version);
+ }
+
+ protected static Task WriteElementExtensionsAsync(XmlWriter writer, ServiceDocument document, string version)
+ {
+ if (document == null)
+ {
+ throw new ArgumentNullException(nameof(document));
+ }
+
+ return document.WriteElementExtensionsAsync(writer, version);
+ }
+
+ protected static Task WriteElementExtensionsAsync(XmlWriter writer, Workspace workspace, string version)
+ {
+ if (workspace == null)
+ {
+ throw new ArgumentNullException(nameof(workspace));
+ }
+
+ return workspace.WriteElementExtensionsAsync(writer, version);
+ }
+
+ protected static Task WriteElementExtensionsAsync(XmlWriter writer, ResourceCollectionInfo collection, string version)
+ {
+ if (collection == null)
+ {
+ throw new ArgumentNullException(nameof(collection));
+ }
+
+ return collection.WriteElementExtensionsAsync(writer, version);
+ }
+
+ protected static Task WriteElementExtensionsAsync(XmlWriter writer, CategoriesDocument categories, string version)
+ {
+ if (categories == null)
+ {
+ throw new ArgumentNullException(nameof(categories));
+ }
+
+ return categories.WriteElementExtensionsAsync(writer, version);
+ }
+
+ protected virtual ServiceDocument CreateDocumentInstance()
+ {
+ return new ServiceDocument();
+ }
+
+ protected virtual void SetDocument(ServiceDocument document)
+ {
+ _document = document;
+ }
+ }
+}
diff --git a/src/System.ServiceModel.Syndication/src/System/ServiceModel/Syndication/SyndicationCategory.cs b/src/System.ServiceModel.Syndication/src/System/ServiceModel/Syndication/SyndicationCategory.cs
new file mode 100644
index 0000000000..77660de24f
--- /dev/null
+++ b/src/System.ServiceModel.Syndication/src/System/ServiceModel/Syndication/SyndicationCategory.cs
@@ -0,0 +1,113 @@
+// 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.ServiceModel.Syndication
+{
+ using System;
+ using System.Collections.Generic;
+ using System.Runtime.CompilerServices;
+ using System.Threading.Tasks;
+ using System.Xml;
+
+ // NOTE: This class implements Clone so if you add any members, please update the copy ctor
+ public class SyndicationCategory : IExtensibleSyndicationObject
+ {
+ private ExtensibleSyndicationObject _extensions = new ExtensibleSyndicationObject();
+ private string _label;
+ private string _name;
+ private string _scheme;
+
+ public SyndicationCategory()
+ : this((string)null)
+ {
+ }
+
+ public SyndicationCategory(string name)
+ : this(name, null, null)
+ {
+ }
+
+ public SyndicationCategory(string name, string scheme, string label)
+ {
+ _name = name;
+ _scheme = scheme;
+ _label = label;
+ }
+
+ protected SyndicationCategory(SyndicationCategory source)
+ {
+ if (source == null)
+ {
+ throw new ArgumentNullException(nameof(source));
+ }
+ _label = source._label;
+ _name = source._name;
+ _scheme = source._scheme;
+ _extensions = source._extensions.Clone();
+ }
+
+ public Dictionary<XmlQualifiedName, string> AttributeExtensions
+ {
+ get { return _extensions.AttributeExtensions; }
+ }
+
+ public SyndicationElementExtensionCollection ElementExtensions
+ {
+ get { return _extensions.ElementExtensions; }
+ }
+
+ public string Label
+ {
+ get { return _label; }
+ set { _label = value; }
+ }
+
+ public string Name
+ {
+ get { return _name; }
+ set { _name = value; }
+ }
+
+ public string Scheme
+ {
+ get { return _scheme; }
+ set { _scheme = value; }
+ }
+
+ public virtual SyndicationCategory Clone()
+ {
+ return new SyndicationCategory(this);
+ }
+
+ protected internal virtual bool TryParseAttribute(string name, string ns, string value, string version)
+ {
+ return false;
+ }
+
+ protected internal virtual bool TryParseElement(XmlReader reader, string version)
+ {
+ return false;
+ }
+
+ protected internal virtual Task WriteAttributeExtensionsAsync(XmlWriter writer, string version)
+ {
+ return _extensions.WriteAttributeExtensionsAsync(writer);
+ }
+
+ protected internal virtual Task WriteElementExtensionsAsync(XmlWriter writer, string version)
+ {
+ return _extensions.WriteElementExtensionsAsync(writer);
+ }
+
+ internal void LoadElementExtensions(XmlReader readerOverUnparsedExtensions, int maxExtensionSize)
+ {
+ _extensions.LoadElementExtensions(readerOverUnparsedExtensions, maxExtensionSize);
+ }
+
+ internal void LoadElementExtensions(XmlBuffer buffer)
+ {
+ _extensions.LoadElementExtensions(buffer);
+ }
+ }
+}
diff --git a/src/System.ServiceModel.Syndication/src/System/ServiceModel/Syndication/SyndicationContent.cs b/src/System.ServiceModel.Syndication/src/System/ServiceModel/Syndication/SyndicationContent.cs
new file mode 100644
index 0000000000..7465df37a5
--- /dev/null
+++ b/src/System.ServiceModel.Syndication/src/System/ServiceModel/Syndication/SyndicationContent.cs
@@ -0,0 +1,138 @@
+// 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.ServiceModel.Syndication
+{
+ using System;
+ using System.Collections.Generic;
+ using System.Runtime.CompilerServices;
+ using System.Runtime.Serialization;
+ using System.Threading.Tasks;
+ using System.Xml;
+ using System.Xml.Serialization;
+
+ public abstract class SyndicationContent
+ {
+ private Dictionary<XmlQualifiedName, string> _attributeExtensions;
+
+ protected SyndicationContent()
+ {
+ }
+
+ protected SyndicationContent(SyndicationContent source)
+ {
+ CopyAttributeExtensions(source);
+ }
+
+ public Dictionary<XmlQualifiedName, string> AttributeExtensions
+ {
+ get
+ {
+ if (_attributeExtensions == null)
+ {
+ _attributeExtensions = new Dictionary<XmlQualifiedName, string>();
+ }
+ return _attributeExtensions;
+ }
+ }
+
+ public abstract string Type
+ {
+ get;
+ }
+
+ public static TextSyndicationContent CreateHtmlContent(string content)
+ {
+ return new TextSyndicationContent(content, TextSyndicationContentKind.Html);
+ }
+
+ public static TextSyndicationContent CreatePlaintextContent(string content)
+ {
+ return new TextSyndicationContent(content);
+ }
+
+ public static UrlSyndicationContent CreateUrlContent(Uri url, string mediaType)
+ {
+ return new UrlSyndicationContent(url, mediaType);
+ }
+
+ public static TextSyndicationContent CreateXhtmlContent(string content)
+ {
+ return new TextSyndicationContent(content, TextSyndicationContentKind.XHtml);
+ }
+
+ public static XmlSyndicationContent CreateXmlContent(object dataContractObject)
+ {
+ return new XmlSyndicationContent(Atom10Constants.XmlMediaType, dataContractObject, (DataContractSerializer)null);
+ }
+
+ public static XmlSyndicationContent CreateXmlContent(object dataContractObject, XmlObjectSerializer dataContractSerializer)
+ {
+ return new XmlSyndicationContent(Atom10Constants.XmlMediaType, dataContractObject, dataContractSerializer);
+ }
+
+ public static XmlSyndicationContent CreateXmlContent(XmlReader XmlReaderWrapper)
+ {
+ return new XmlSyndicationContent(XmlReaderWrapper);
+ }
+
+ public static XmlSyndicationContent CreateXmlContent(object xmlSerializerObject, XmlSerializer serializer)
+ {
+ return new XmlSyndicationContent(Atom10Constants.XmlMediaType, xmlSerializerObject, serializer);
+ }
+
+ public abstract SyndicationContent Clone();
+
+ public async Task WriteToAsync(XmlWriter writer, string outerElementName, string outerElementNamespace)
+ {
+ if (writer == null)
+ {
+ throw new ArgumentNullException(nameof(writer));
+ }
+ if (string.IsNullOrEmpty(outerElementName))
+ {
+ throw new ArgumentException(SR.OuterElementNameNotSpecified);
+ }
+
+ writer = XmlWriterWrapper.CreateFromWriter(writer);
+
+ await writer.WriteStartElementAsync(outerElementName, outerElementNamespace);
+ await writer.WriteAttributeStringAsync(Atom10Constants.TypeTag, string.Empty, this.Type);
+ if (_attributeExtensions != null)
+ {
+ foreach (XmlQualifiedName key in _attributeExtensions.Keys)
+ {
+ if (key.Name == Atom10Constants.TypeTag && key.Namespace == string.Empty)
+ {
+ continue;
+ }
+ string attrValue;
+ if (_attributeExtensions.TryGetValue(key, out attrValue))
+ {
+ await writer.WriteAttributeStringAsync(key.Name, key.Namespace, attrValue);
+ }
+ }
+ }
+ WriteContentsTo(writer);
+ await writer.WriteEndElementAsync();
+ }
+
+ internal void CopyAttributeExtensions(SyndicationContent source)
+ {
+ if (source == null)
+ {
+ throw new ArgumentNullException(nameof(source));
+ }
+ if (source._attributeExtensions != null)
+ {
+ foreach (XmlQualifiedName key in source._attributeExtensions.Keys)
+ {
+ this.AttributeExtensions.Add(key, source._attributeExtensions[key]);
+ }
+ }
+ }
+
+ protected abstract void WriteContentsTo(XmlWriter writer);
+ }
+}
diff --git a/src/System.ServiceModel.Syndication/src/System/ServiceModel/Syndication/SyndicationElementExtension.cs b/src/System.ServiceModel.Syndication/src/System/ServiceModel/Syndication/SyndicationElementExtension.cs
new file mode 100644
index 0000000000..3b2ff90f92
--- /dev/null
+++ b/src/System.ServiceModel.Syndication/src/System/ServiceModel/Syndication/SyndicationElementExtension.cs
@@ -0,0 +1,348 @@
+// 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.ServiceModel.Syndication
+{
+ using System;
+ using System.Diagnostics;
+ using System.IO;
+ using System.Runtime.CompilerServices;
+ using System.Runtime.Serialization;
+ using System.Threading.Tasks;
+ using System.Xml;
+ using System.Xml.Serialization;
+
+ public class SyndicationElementExtension
+ {
+ private XmlBuffer _buffer;
+ private int _bufferElementIndex;
+ // extensionData and extensionDataWriter are only present on the send side
+ private object _extensionData;
+ private ExtensionDataWriter _extensionDataWriter;
+ private string _outerName;
+ private string _outerNamespace;
+
+ public SyndicationElementExtension(XmlReader reader)
+ {
+ if (reader == null)
+ {
+ throw new ArgumentNullException(nameof(reader));
+ }
+ SyndicationFeedFormatter.MoveToStartElement(reader);
+ _outerName = reader.LocalName;
+ _outerNamespace = reader.NamespaceURI;
+ _buffer = new XmlBuffer(int.MaxValue);
+ using (XmlDictionaryWriter writer = _buffer.OpenSection(XmlDictionaryReaderQuotas.Max))
+ {
+ writer.WriteStartElement(Rss20Constants.ExtensionWrapperTag);
+ writer.WriteNode(reader, false);
+ writer.WriteEndElement();
+ }
+ _buffer.CloseSection();
+ _buffer.Close();
+ _bufferElementIndex = 0;
+ }
+
+ public SyndicationElementExtension(object dataContractExtension)
+ : this(dataContractExtension, (XmlObjectSerializer)null)
+ {
+ }
+
+ public SyndicationElementExtension(object dataContractExtension, XmlObjectSerializer dataContractSerializer)
+ : this(null, null, dataContractExtension, dataContractSerializer)
+ {
+ }
+
+ public SyndicationElementExtension(string outerName, string outerNamespace, object dataContractExtension)
+ : this(outerName, outerNamespace, dataContractExtension, null)
+ {
+ }
+
+ public SyndicationElementExtension(string outerName, string outerNamespace, object dataContractExtension, XmlObjectSerializer dataContractSerializer)
+ {
+ if (dataContractExtension == null)
+ {
+ throw new ArgumentNullException(nameof(dataContractExtension));
+ }
+ if (outerName == string.Empty)
+ {
+ throw new ArgumentNullException(SR.OuterNameOfElementExtensionEmpty);
+ }
+ if (dataContractSerializer == null)
+ {
+ dataContractSerializer = new DataContractSerializer(dataContractExtension.GetType());
+ }
+ _outerName = outerName;
+ _outerNamespace = outerNamespace;
+ _extensionData = dataContractExtension;
+ _extensionDataWriter = new ExtensionDataWriter(_extensionData, dataContractSerializer, _outerName, _outerNamespace);
+ }
+
+ public SyndicationElementExtension(object xmlSerializerExtension, XmlSerializer serializer)
+ {
+ if (xmlSerializerExtension == null)
+ {
+ throw new ArgumentNullException(nameof(xmlSerializerExtension));
+ }
+ if (serializer == null)
+ {
+ serializer = new XmlSerializer(xmlSerializerExtension.GetType());
+ }
+ _extensionData = xmlSerializerExtension;
+ _extensionDataWriter = new ExtensionDataWriter(_extensionData, serializer);
+ }
+
+ internal SyndicationElementExtension(XmlBuffer buffer, int bufferElementIndex, string outerName, string outerNamespace)
+ {
+ _buffer = buffer;
+ _bufferElementIndex = bufferElementIndex;
+ _outerName = outerName;
+ _outerNamespace = outerNamespace;
+ }
+
+ public string OuterName
+ {
+ get
+ {
+ if (_outerName == null)
+ {
+ EnsureOuterNameAndNs();
+ }
+ return _outerName;
+ }
+ }
+
+ public string OuterNamespace
+ {
+ get
+ {
+ if (_outerName == null)
+ {
+ EnsureOuterNameAndNs();
+ }
+ return _outerNamespace;
+ }
+ }
+
+ public Task<TExtension> GetObject<TExtension>()
+ {
+ return GetObject<TExtension>(new DataContractSerializer(typeof(TExtension)));
+ }
+
+ public async Task<TExtension> GetObject<TExtension>(XmlObjectSerializer serializer)
+ {
+ if (serializer == null)
+ {
+ throw new ArgumentNullException(nameof(serializer));
+ }
+ if (_extensionData != null && typeof(TExtension).IsAssignableFrom(_extensionData.GetType()))
+ {
+ return (TExtension)_extensionData;
+ }
+
+ using (XmlReader reader = await GetReaderAsync())
+ {
+ return (TExtension)serializer.ReadObject(reader, false);
+ }
+ }
+
+ public async Task<TExtension> GetObject<TExtension>(XmlSerializer serializer)
+ {
+ if (serializer == null)
+ {
+ throw new ArgumentNullException(nameof(serializer));
+ }
+ if (_extensionData != null && typeof(TExtension).IsAssignableFrom(_extensionData.GetType()))
+ {
+ return (TExtension)_extensionData;
+ }
+
+ using (XmlReader reader = await GetReaderAsync())
+ {
+ return (TExtension)serializer.Deserialize(reader);
+ }
+ }
+
+ public async Task<XmlReader> GetReaderAsync()
+ {
+ await this.EnsureBuffer();
+ XmlReaderWrapper reader = XmlReaderWrapper.CreateFromReader(_buffer.GetReader(0));
+ int index = 0;
+ reader.ReadStartElement(Rss20Constants.ExtensionWrapperTag);
+ while (reader.IsStartElement())
+ {
+ if (index == _bufferElementIndex)
+ {
+ break;
+ }
+ ++index;
+
+ await reader.SkipAsync();
+ }
+
+ return reader;
+ }
+
+ //public Task<XmlReader> GetReader()
+ //{
+ // return GetReaderAsync();
+ //}
+
+ public async Task WriteToAsync(XmlWriter writer)
+ {
+ if (writer == null)
+ {
+ throw new ArgumentNullException(nameof(writer));
+ }
+ if (_extensionDataWriter != null)
+ {
+ _extensionDataWriter.WriteToAsync(writer);
+ }
+ else
+ {
+ writer = XmlWriterWrapper.CreateFromWriter(writer);
+ using (XmlReader reader = await GetReaderAsync())
+ {
+ await writer.WriteNodeAsync(reader, false);
+ }
+ }
+ }
+
+ private async Task EnsureBuffer()
+ {
+ if (_buffer == null)
+ {
+ _buffer = new XmlBuffer(int.MaxValue);
+ using (XmlDictionaryWriter writer = _buffer.OpenSection(XmlDictionaryReaderQuotas.Max))
+ {
+ writer.WriteStartElement(Rss20Constants.ExtensionWrapperTag);
+ await this.WriteToAsync(writer);
+ writer.WriteEndElement();
+ }
+ _buffer.CloseSection();
+ _buffer.Close();
+ _bufferElementIndex = 0;
+ }
+ }
+
+ private void EnsureOuterNameAndNs()
+ {
+ Debug.Assert(_extensionDataWriter != null, "outer name is null only for datacontract and xmlserializer cases");
+ _extensionDataWriter.ComputeOuterNameAndNs(out _outerName, out _outerNamespace);
+ }
+
+ // this class holds the extension data and the associated serializer (either DataContractSerializer or XmlSerializer but not both)
+ private class ExtensionDataWriter
+ {
+ private readonly XmlObjectSerializer _dataContractSerializer;
+ private readonly object _extensionData;
+ private readonly string _outerName;
+ private readonly string _outerNamespace;
+ private readonly XmlSerializer _xmlSerializer;
+
+ public ExtensionDataWriter(object extensionData, XmlObjectSerializer dataContractSerializer, string outerName, string outerNamespace)
+ {
+ Debug.Assert(extensionData != null && dataContractSerializer != null, "null check");
+
+ _dataContractSerializer = dataContractSerializer;
+ _extensionData = extensionData;
+ _outerName = outerName;
+ _outerNamespace = outerNamespace;
+ }
+
+ public ExtensionDataWriter(object extensionData, XmlSerializer serializer)
+ {
+ Debug.Assert(extensionData != null && serializer != null, "null check");
+ _xmlSerializer = serializer;
+ _extensionData = extensionData;
+ }
+
+ public void WriteToAsync(XmlWriter writer)
+ {
+ if (_xmlSerializer != null)
+ {
+ Debug.Assert((_dataContractSerializer == null && _outerName == null && _outerNamespace == null), "Xml serializer cannot have outer name, ns");
+ _xmlSerializer.Serialize(writer, _extensionData);
+ }
+ else
+ {
+ Debug.Assert(_xmlSerializer == null, "Xml serializer cannot be configured");
+ writer = XmlWriterWrapper.CreateFromWriter(writer);
+ if (_outerName != null)
+ {
+ writer.WriteStartElementAsync(_outerName, _outerNamespace);
+ _dataContractSerializer.WriteObjectContent(writer, _extensionData);
+ writer.WriteEndElementAsync();
+ }
+ else
+ {
+ _dataContractSerializer.WriteObject(writer, _extensionData);
+ }
+ }
+ }
+
+ internal void ComputeOuterNameAndNs(out string name, out string ns)
+ {
+ if (_outerName != null)
+ {
+ Debug.Assert(_xmlSerializer == null, "outer name is not null for data contract extension only");
+ name = _outerName;
+ ns = _outerNamespace;
+ }
+ else if (_dataContractSerializer != null)
+ {
+ Debug.Assert(_xmlSerializer == null, "only one of xmlserializer or datacontract serializer can be present");
+ XsdDataContractExporter dcExporter = new XsdDataContractExporter();
+ XmlQualifiedName qName = dcExporter.GetRootElementName(_extensionData.GetType());
+ if (qName != null)
+ {
+ name = qName.Name;
+ ns = qName.Namespace;
+ }
+ else
+ {
+ // this can happen if an IXmlSerializable type is specified with IsAny=true
+ ReadOuterNameAndNs(out name, out ns);
+ }
+ }
+ else
+ {
+ Debug.Assert(_dataContractSerializer == null, "only one of xmlserializer or datacontract serializer can be present");
+ XmlReflectionImporter importer = new XmlReflectionImporter();
+ XmlTypeMapping typeMapping = importer.ImportTypeMapping(_extensionData.GetType());
+ if (typeMapping != null && !string.IsNullOrEmpty(typeMapping.ElementName))
+ {
+ name = typeMapping.ElementName;
+ ns = typeMapping.Namespace;
+ }
+ else
+ {
+ // this can happen if an IXmlSerializable type is specified with IsAny=true
+ ReadOuterNameAndNs(out name, out ns);
+ }
+ }
+ }
+
+ internal void ReadOuterNameAndNs(out string name, out string ns)
+ {
+ using (MemoryStream stream = new MemoryStream())
+ {
+ using (XmlWriter writer = XmlWriter.Create(stream))
+ {
+ this.WriteToAsync(writer);
+ }
+
+ stream.Seek(0, SeekOrigin.Begin);
+
+ using (XmlReader reader = XmlReader.Create(stream))
+ {
+ SyndicationFeedFormatter.MoveToStartElement(reader);
+ name = reader.LocalName;
+ ns = reader.NamespaceURI;
+ }
+ }
+ }
+ }
+ }
+}
diff --git a/src/System.ServiceModel.Syndication/src/System/ServiceModel/Syndication/SyndicationElementExtensionCollection.cs b/src/System.ServiceModel.Syndication/src/System/ServiceModel/Syndication/SyndicationElementExtensionCollection.cs
new file mode 100644
index 0000000000..cb09d65b1f
--- /dev/null
+++ b/src/System.ServiceModel.Syndication/src/System/ServiceModel/Syndication/SyndicationElementExtensionCollection.cs
@@ -0,0 +1,277 @@
+// 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.ServiceModel.Syndication
+{
+ using System;
+ using System.Collections.ObjectModel;
+ using System.Diagnostics;
+ using System.Runtime.CompilerServices;
+ using System.Runtime.Serialization;
+ using System.Threading.Tasks;
+ using System.Xml;
+ using System.Xml.Serialization;
+
+ // sealed because the ctor results in a call to the virtual InsertItem method
+ public sealed class SyndicationElementExtensionCollection : Collection<SyndicationElementExtension>
+ {
+ private XmlBuffer _buffer;
+ private bool _initialized;
+
+ internal SyndicationElementExtensionCollection()
+ : this((XmlBuffer)null)
+ {
+ }
+
+ internal SyndicationElementExtensionCollection(XmlBuffer buffer)
+ : base()
+ {
+ _buffer = buffer;
+ if (_buffer != null)
+ {
+ PopulateElements();
+ }
+ _initialized = true;
+ }
+
+ internal SyndicationElementExtensionCollection(SyndicationElementExtensionCollection source)
+ : base()
+ {
+ _buffer = source._buffer;
+ for (int i = 0; i < source.Items.Count; ++i)
+ {
+ base.Add(source.Items[i]);
+ }
+ _initialized = true;
+ }
+
+ public void Add(object extension)
+ {
+ if (extension is SyndicationElementExtension)
+ {
+ base.Add((SyndicationElementExtension)extension);
+ }
+ else
+ {
+ this.Add(extension, (DataContractSerializer)null);
+ }
+ }
+
+ public void Add(string outerName, string outerNamespace, object dataContractExtension)
+ {
+ this.Add(outerName, outerNamespace, dataContractExtension, null);
+ }
+
+ public void Add(object dataContractExtension, DataContractSerializer serializer)
+ {
+ this.Add(null, null, dataContractExtension, serializer);
+ }
+
+ public void Add(string outerName, string outerNamespace, object dataContractExtension, XmlObjectSerializer dataContractSerializer)
+ {
+ if (dataContractExtension == null)
+ {
+ throw new ArgumentNullException(nameof(dataContractExtension));
+ }
+ if (dataContractSerializer == null)
+ {
+ dataContractSerializer = new DataContractSerializer(dataContractExtension.GetType());
+ }
+ base.Add(new SyndicationElementExtension(outerName, outerNamespace, dataContractExtension, dataContractSerializer));
+ }
+
+ public void Add(object xmlSerializerExtension, XmlSerializer serializer)
+ {
+ if (xmlSerializerExtension == null)
+ {
+ throw new ArgumentNullException(nameof(xmlSerializerExtension));
+ }
+ if (serializer == null)
+ {
+ serializer = new XmlSerializer(xmlSerializerExtension.GetType());
+ }
+ base.Add(new SyndicationElementExtension(xmlSerializerExtension, serializer));
+ }
+
+ public void Add(XmlReader reader)
+ {
+ if (reader == null)
+ {
+ throw new ArgumentNullException(nameof(reader));
+ }
+ base.Add(new SyndicationElementExtension(reader));
+ }
+
+ public async Task<XmlReader> GetReaderAtElementExtensions()
+ {
+ XmlBuffer extensionsBuffer = await GetOrCreateBufferOverExtensions();
+ XmlReader reader = extensionsBuffer.GetReader(0);
+ reader.ReadStartElement();
+ return reader;
+ }
+
+ public Task<Collection<TExtension>> ReadElementExtensions<TExtension>(string extensionName, string extensionNamespace)
+ {
+ return ReadElementExtensions<TExtension>(extensionName, extensionNamespace, new DataContractSerializer(typeof(TExtension)));
+ }
+
+ public Task<Collection<TExtension>> ReadElementExtensions<TExtension>(string extensionName, string extensionNamespace, XmlObjectSerializer serializer)
+ {
+ if (serializer == null)
+ {
+ throw new ArgumentNullException(nameof(serializer));
+ }
+ return ReadExtensions<TExtension>(extensionName, extensionNamespace, serializer, null);
+ }
+
+ public Task<Collection<TExtension>> ReadElementExtensions<TExtension>(string extensionName, string extensionNamespace, XmlSerializer serializer)
+ {
+ if (serializer == null)
+ {
+ throw new ArgumentNullException(nameof(serializer));
+ }
+ return ReadExtensions<TExtension>(extensionName, extensionNamespace, null, serializer);
+ }
+
+ internal async Task WriteToAsync(XmlWriter writer)
+ {
+ if (_buffer != null)
+ {
+ using (XmlDictionaryReader reader = _buffer.GetReader(0))
+ {
+ reader.ReadStartElement();
+ while (reader.IsStartElement())
+ {
+ await writer.WriteNodeAsync(reader, false);
+ }
+ }
+ }
+ else
+ {
+ for (int i = 0; i < this.Items.Count; ++i)
+ {
+ await this.Items[i].WriteToAsync(writer);
+ }
+ }
+ }
+
+ protected override void ClearItems()
+ {
+ base.ClearItems();
+ // clear the cached buffer if the operation is happening outside the constructor
+ if (_initialized)
+ {
+ _buffer = null;
+ }
+ }
+
+ protected override void InsertItem(int index, SyndicationElementExtension item)
+ {
+ if (item == null)
+ {
+ throw new ArgumentNullException(nameof(item));
+ }
+ base.InsertItem(index, item);
+ // clear the cached buffer if the operation is happening outside the constructor
+ if (_initialized)
+ {
+ _buffer = null;
+ }
+ }
+
+ protected override void RemoveItem(int index)
+ {
+ base.RemoveItem(index);
+ // clear the cached buffer if the operation is happening outside the constructor
+ if (_initialized)
+ {
+ _buffer = null;
+ }
+ }
+
+ protected override void SetItem(int index, SyndicationElementExtension item)
+ {
+ if (item == null)
+ {
+ throw new ArgumentNullException(nameof(item));
+ }
+ base.SetItem(index, item);
+ // clear the cached buffer if the operation is happening outside the constructor
+ if (_initialized)
+ {
+ _buffer = null;
+ }
+ }
+
+ private async Task<XmlBuffer> GetOrCreateBufferOverExtensions()
+ {
+ if (_buffer != null)
+ {
+ return _buffer;
+ }
+ XmlBuffer newBuffer = new XmlBuffer(int.MaxValue);
+ using (XmlWriter writer = newBuffer.OpenSection(XmlDictionaryReaderQuotas.Max))
+ {
+ writer.WriteStartElement(Rss20Constants.ExtensionWrapperTag);
+ for (int i = 0; i < this.Count; ++i)
+ {
+ await this[i].WriteToAsync(writer);
+ }
+ writer.WriteEndElement();
+ }
+ newBuffer.CloseSection();
+ newBuffer.Close();
+ _buffer = newBuffer;
+ return newBuffer;
+ }
+
+ private void PopulateElements()
+ {
+ using (XmlDictionaryReader reader = _buffer.GetReader(0))
+ {
+ reader.ReadStartElement();
+ int index = 0;
+ while (reader.IsStartElement())
+ {
+ base.Add(new SyndicationElementExtension(_buffer, index, reader.LocalName, reader.NamespaceURI));
+ reader.Skip();
+ ++index;
+ }
+ }
+ }
+
+ private async Task<Collection<TExtension>> ReadExtensions<TExtension>(string extensionName, string extensionNamespace, XmlObjectSerializer dcSerializer, XmlSerializer xmlSerializer)
+ {
+ if (string.IsNullOrEmpty(extensionName))
+ {
+ throw new ArgumentNullException(SR.ExtensionNameNotSpecified);
+ }
+ Debug.Assert((dcSerializer == null) != (xmlSerializer == null), "exactly one serializer should be supplied");
+ // normalize the null and empty namespace
+ if (extensionNamespace == null)
+ {
+ extensionNamespace = string.Empty;
+ }
+
+ Collection<TExtension> results = new Collection<TExtension>();
+ for (int i = 0; i < this.Count; ++i)
+ {
+ if (extensionName != this[i].OuterName || extensionNamespace != this[i].OuterNamespace)
+ {
+ continue;
+ }
+
+ if (dcSerializer != null)
+ {
+ results.Add(await this[i].GetObject<TExtension>(dcSerializer));
+ }
+ else
+ {
+ results.Add(await this[i].GetObject<TExtension>(xmlSerializer));
+ }
+ }
+ return results;
+ }
+ }
+}
diff --git a/src/System.ServiceModel.Syndication/src/System/ServiceModel/Syndication/SyndicationElementExtensionKindHelper.cs b/src/System.ServiceModel.Syndication/src/System/ServiceModel/Syndication/SyndicationElementExtensionKindHelper.cs
new file mode 100644
index 0000000000..f1ebc22e56
--- /dev/null
+++ b/src/System.ServiceModel.Syndication/src/System/ServiceModel/Syndication/SyndicationElementExtensionKindHelper.cs
@@ -0,0 +1,23 @@
+// 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.ServiceModel.Syndication
+{
+ internal static class SyndicationElementExtensionKindHelper
+ {
+ internal static bool IsDefined(SyndicationElementExtensionKind value)
+ {
+ return (value == SyndicationElementExtensionKind.DataContract ||
+ value == SyndicationElementExtensionKind.XmlElement ||
+ value == SyndicationElementExtensionKind.XmlSerializer);
+ }
+
+ internal enum SyndicationElementExtensionKind
+ {
+ DataContract,
+ XmlElement,
+ XmlSerializer
+ }
+ }
+}
diff --git a/src/System.ServiceModel.Syndication/src/System/ServiceModel/Syndication/SyndicationFeed.cs b/src/System.ServiceModel.Syndication/src/System/ServiceModel/Syndication/SyndicationFeed.cs
new file mode 100644
index 0000000000..1bac5e8c55
--- /dev/null
+++ b/src/System.ServiceModel.Syndication/src/System/ServiceModel/Syndication/SyndicationFeed.cs
@@ -0,0 +1,502 @@
+// 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.ServiceModel.Syndication
+{
+ using System.ServiceModel;
+ using System;
+ using System.Collections.Generic;
+ using System.Collections.ObjectModel;
+ using System.Runtime.CompilerServices;
+ using System.Threading;
+ using System.Threading.Tasks;
+ using System.Xml;
+
+
+ // NOTE: This class implements Clone so if you add any members, please update the copy ctor
+ public class SyndicationFeed : IExtensibleSyndicationObject
+ {
+ private Collection<SyndicationPerson> _authors;
+ private Uri _baseUri;
+ private Collection<SyndicationCategory> _categories;
+ private Collection<SyndicationPerson> _contributors;
+ private TextSyndicationContent _copyright;
+ private TextSyndicationContent _description;
+ private ExtensibleSyndicationObject _extensions = new ExtensibleSyndicationObject();
+ private string _generator;
+ private string _id;
+
+ private Uri _imageUrl;
+ private TextSyndicationContent _imageTitle;
+ private Uri _imageLink;
+
+ private IEnumerable<SyndicationItem> _items;
+ private string _language;
+ private DateTimeOffset _lastUpdatedTime;
+ private Collection<SyndicationLink> _links;
+ private TextSyndicationContent _title;
+
+ // optional RSS tags
+ private SyndicationLink _documentation;
+ private int _timeToLive;
+ private Collection<int> _skipHours;
+ private Collection<string> _skipDays;
+ private SyndicationTextInput _textInput;
+ private Uri _iconImage;
+
+ public Uri IconImage
+ {
+ get
+ {
+ return _iconImage;
+ }
+ set
+ {
+ if (value == null)
+ throw new ArgumentNullException(nameof(value));
+ _iconImage = value;
+ }
+ }
+
+ public SyndicationTextInput TextInput
+ {
+ get
+ {
+ return _textInput;
+ }
+ set
+ {
+ if (value == null)
+ throw new ArgumentNullException(nameof(value));
+ _textInput = value;
+ }
+ }
+
+ public SyndicationLink Documentation
+ {
+ get
+ {
+ return _documentation;
+ }
+ set
+ {
+ _documentation = value;
+ }
+ }
+
+ public int TimeToLive
+ {
+ get {
+ return _timeToLive;
+ }
+ set
+ {
+ _timeToLive = value;
+ }
+ }
+
+ public Collection<int> SkipHours
+ {
+ get
+ {
+ if (_skipHours == null)
+ _skipHours = new Collection<int>();
+ return _skipHours;
+ }
+ }
+
+ public Collection<string> SkipDays
+ {
+ get
+ {
+ if (_skipDays == null)
+ _skipDays = new Collection<string>();
+ return _skipDays;
+ }
+ }
+
+ //======================================
+
+ public SyndicationFeed()
+ : this((IEnumerable<SyndicationItem>)null)
+ {
+ }
+
+ public SyndicationFeed(IEnumerable<SyndicationItem> items)
+ : this(null, null, null, items)
+ {
+ }
+
+ public SyndicationFeed(string title, string description, Uri feedAlternateLink)
+ : this(title, description, feedAlternateLink, null)
+ {
+ }
+
+ public SyndicationFeed(string title, string description, Uri feedAlternateLink, IEnumerable<SyndicationItem> items)
+ : this(title, description, feedAlternateLink, null, DateTimeOffset.MinValue, items)
+ {
+ }
+
+ public SyndicationFeed(string title, string description, Uri feedAlternateLink, string id, DateTimeOffset lastUpdatedTime)
+ : this(title, description, feedAlternateLink, id, lastUpdatedTime, null)
+ {
+ }
+
+ public SyndicationFeed(string title, string description, Uri feedAlternateLink, string id, DateTimeOffset lastUpdatedTime, IEnumerable<SyndicationItem> items)
+ {
+ if (title != null)
+ {
+ _title = new TextSyndicationContent(title);
+ }
+ if (description != null)
+ {
+ _description = new TextSyndicationContent(description);
+ }
+ if (feedAlternateLink != null)
+ {
+ this.Links.Add(SyndicationLink.CreateAlternateLink(feedAlternateLink));
+ }
+ _id = id;
+ _lastUpdatedTime = lastUpdatedTime;
+ _items = items;
+ }
+
+ protected SyndicationFeed(SyndicationFeed source, bool cloneItems)
+ {
+ if (source == null)
+ {
+ throw new ArgumentNullException(nameof(source));
+ }
+ _authors = FeedUtils.ClonePersons(source._authors);
+ _categories = FeedUtils.CloneCategories(source._categories);
+ _contributors = FeedUtils.ClonePersons(source._contributors);
+ _copyright = FeedUtils.CloneTextContent(source._copyright);
+ _description = FeedUtils.CloneTextContent(source._description);
+ _extensions = source._extensions.Clone();
+ _generator = source._generator;
+ _id = source._id;
+ _imageUrl = source._imageUrl;
+ _language = source._language;
+ _lastUpdatedTime = source._lastUpdatedTime;
+ _links = FeedUtils.CloneLinks(source._links);
+ _title = FeedUtils.CloneTextContent(source._title);
+ _baseUri = source._baseUri;
+ IList<SyndicationItem> srcList = source._items as IList<SyndicationItem>;
+ if (srcList != null)
+ {
+ Collection<SyndicationItem> tmp = new NullNotAllowedCollection<SyndicationItem>();
+ for (int i = 0; i < srcList.Count; ++i)
+ {
+ tmp.Add((cloneItems) ? srcList[i].Clone() : srcList[i]);
+ }
+ _items = tmp;
+ }
+ else
+ {
+ if (cloneItems)
+ {
+ throw new InvalidOperationException(SR.UnbufferedItemsCannotBeCloned);
+ }
+ _items = source._items;
+ }
+ }
+
+ public Dictionary<XmlQualifiedName, string> AttributeExtensions
+ {
+ get { return _extensions.AttributeExtensions; }
+ }
+
+ public Collection<SyndicationPerson> Authors
+ {
+ get
+ {
+ if (_authors == null)
+ {
+ _authors = new NullNotAllowedCollection<SyndicationPerson>();
+ }
+ return _authors;
+ }
+ }
+
+
+ public Uri BaseUri
+ {
+ get { return _baseUri; }
+ set { _baseUri = value; }
+ }
+
+ public Collection<SyndicationCategory> Categories
+ {
+ get
+ {
+ if (_categories == null)
+ {
+ _categories = new NullNotAllowedCollection<SyndicationCategory>();
+ }
+ return _categories;
+ }
+ }
+
+ public Collection<SyndicationPerson> Contributors
+ {
+ get
+ {
+ if (_contributors == null)
+ {
+ _contributors = new NullNotAllowedCollection<SyndicationPerson>();
+ }
+ return _contributors;
+ }
+ }
+
+ public TextSyndicationContent Copyright
+ {
+ get { return _copyright; }
+ set { _copyright = value; }
+ }
+
+ public TextSyndicationContent Description
+ {
+ get { return _description; }
+ set { _description = value; }
+ }
+
+ public SyndicationElementExtensionCollection ElementExtensions
+ {
+ get { return _extensions.ElementExtensions; }
+ }
+
+ public string Generator
+ {
+ get { return _generator; }
+ set { _generator = value; }
+ }
+
+ public string Id
+ {
+ get { return _id; }
+ set { _id = value; }
+ }
+
+ public Uri ImageUrl
+ {
+ get { return _imageUrl; }
+ set { _imageUrl = value; }
+ }
+
+ public TextSyndicationContent ImageTitle {
+ get { return _imageTitle; }
+ set { _imageTitle = value; }
+ }
+
+ public Uri ImageLink {
+ get { return _imageLink; }
+ set { _imageLink = value; }
+ }
+
+ public IEnumerable<SyndicationItem> Items
+ {
+ get
+ {
+ if (_items == null)
+ {
+ _items = new NullNotAllowedCollection<SyndicationItem>();
+ }
+ return _items;
+ }
+ set
+ {
+ if (value == null)
+ {
+ throw new ArgumentNullException(nameof(value));
+ }
+ _items = value;
+ }
+ }
+
+ public string Language
+ {
+ get { return _language; }
+ set { _language = value; }
+ }
+
+ public DateTimeOffset LastUpdatedTime
+ {
+ get { return _lastUpdatedTime; }
+ set { _lastUpdatedTime = value; }
+ }
+
+ public Collection<SyndicationLink> Links
+ {
+ get
+ {
+ if (_links == null)
+ {
+ _links = new NullNotAllowedCollection<SyndicationLink>();
+ }
+ return _links;
+ }
+ }
+
+ public TextSyndicationContent Title
+ {
+ get { return _title; }
+ set { _title = value; }
+ }
+
+ //// Custom Parsing
+ public static async Task<SyndicationFeed> LoadAsync(XmlReader reader, Rss20FeedFormatter formatter, CancellationToken ct)
+ {
+ return await LoadAsync(reader, formatter, new Atom10FeedFormatter(), ct);
+ }
+
+ public static async Task<SyndicationFeed> LoadAsync(XmlReader reader, Atom10FeedFormatter formatter, CancellationToken ct)
+ {
+ return await LoadAsync(reader, new Rss20FeedFormatter(), formatter, ct);
+ }
+
+ public static async Task<SyndicationFeed> LoadAsync(XmlReader reader, Rss20FeedFormatter Rssformatter, Atom10FeedFormatter Atomformatter, CancellationToken ct)
+ {
+ if (reader == null)
+ {
+ throw new ArgumentNullException(nameof(reader));
+ }
+
+ XmlReaderWrapper wrappedReader = XmlReaderWrapper.CreateFromReader(reader);
+
+ Atom10FeedFormatter atomSerializer = Atomformatter;
+ if (atomSerializer.CanRead(wrappedReader))
+ {
+ await atomSerializer.ReadFromAsync(wrappedReader, new CancellationToken());
+ return atomSerializer.Feed;
+ }
+ Rss20FeedFormatter rssSerializer = Rssformatter;
+ if (rssSerializer.CanRead(wrappedReader))
+ {
+ await rssSerializer.ReadFromAsync(wrappedReader, new CancellationToken());
+ return rssSerializer.Feed;
+ }
+ throw new XmlException(string.Format(SR.UnknownFeedXml, wrappedReader.LocalName, wrappedReader.NamespaceURI));
+ }
+
+ //=================================
+
+ public static SyndicationFeed Load(XmlReader reader)
+ {
+ return Load<SyndicationFeed>(reader);
+ }
+
+ public static TSyndicationFeed Load<TSyndicationFeed>(XmlReader reader)
+ where TSyndicationFeed : SyndicationFeed, new()
+ {
+ CancellationToken ct = new CancellationToken();
+ return LoadAsync<TSyndicationFeed>(reader,ct).GetAwaiter().GetResult();
+ }
+
+ public static async Task<SyndicationFeed> LoadAsync(XmlReader reader, CancellationToken ct)
+ {
+ return await LoadAsync<SyndicationFeed>(reader, ct);
+ }
+
+ public static async Task<TSyndicationFeed> LoadAsync<TSyndicationFeed>(XmlReader reader, CancellationToken ct)
+ where TSyndicationFeed : SyndicationFeed, new()
+ {
+ Atom10FeedFormatter<TSyndicationFeed> atomSerializer = new Atom10FeedFormatter<TSyndicationFeed>();
+ if (atomSerializer.CanRead(reader))
+ {
+ await atomSerializer.ReadFromAsync(reader, ct);
+ return atomSerializer.Feed as TSyndicationFeed;
+ }
+
+ Rss20FeedFormatter<TSyndicationFeed> rssSerializer = new Rss20FeedFormatter<TSyndicationFeed>();
+ if (rssSerializer.CanRead(reader))
+ {
+ await rssSerializer.ReadFromAsync(reader, ct);
+ return rssSerializer.Feed as TSyndicationFeed;
+ }
+
+ throw new XmlException(string.Format(SR.UnknownFeedXml, reader.LocalName, reader.NamespaceURI));
+ }
+
+ public virtual SyndicationFeed Clone(bool cloneItems)
+ {
+ return new SyndicationFeed(this, cloneItems);
+ }
+
+ public Atom10FeedFormatter GetAtom10Formatter()
+ {
+ return new Atom10FeedFormatter(this);
+ }
+
+ public Rss20FeedFormatter GetRss20Formatter()
+ {
+ return GetRss20Formatter(true);
+ }
+
+ public Rss20FeedFormatter GetRss20Formatter(bool serializeExtensionsAsAtom)
+ {
+ return new Rss20FeedFormatter(this, serializeExtensionsAsAtom);
+ }
+
+ public Task SaveAsAtom10Async(XmlWriter writer, CancellationToken ct)
+ {
+ return GetAtom10Formatter().WriteToAsync(writer, ct);
+ }
+
+ public Task SaveAsRss20Async(XmlWriter writer, CancellationToken ct)
+ {
+ return GetRss20Formatter().WriteToAsync(writer, ct);
+ }
+
+ protected internal virtual SyndicationCategory CreateCategory()
+ {
+ return new SyndicationCategory();
+ }
+
+ protected internal virtual SyndicationItem CreateItem()
+ {
+ return new SyndicationItem();
+ }
+
+ protected internal virtual SyndicationLink CreateLink()
+ {
+ return new SyndicationLink();
+ }
+
+ protected internal virtual SyndicationPerson CreatePerson()
+ {
+ return new SyndicationPerson();
+ }
+
+ protected internal virtual bool TryParseAttribute(string name, string ns, string value, string version)
+ {
+ return false;
+ }
+
+ protected internal virtual bool TryParseElement(XmlReader reader, string version)
+ {
+ return false;
+ }
+
+ protected internal virtual Task WriteAttributeExtensionsAsync(XmlWriter writer, string version)
+ {
+ return _extensions.WriteAttributeExtensionsAsync(writer);
+ }
+
+ protected internal virtual Task WriteElementExtensionsAsync(XmlWriter writer, string version)
+ {
+ return _extensions.WriteElementExtensionsAsync(writer);
+ }
+
+ internal void LoadElementExtensions(XmlReader readerOverUnparsedExtensions, int maxExtensionSize)
+ {
+ _extensions.LoadElementExtensions(readerOverUnparsedExtensions, maxExtensionSize);
+ }
+
+ internal void LoadElementExtensions(XmlBuffer buffer)
+ {
+ _extensions.LoadElementExtensions(buffer);
+ }
+ }
+}
diff --git a/src/System.ServiceModel.Syndication/src/System/ServiceModel/Syndication/SyndicationFeedFormatter.cs b/src/System.ServiceModel.Syndication/src/System/ServiceModel/Syndication/SyndicationFeedFormatter.cs
new file mode 100644
index 0000000000..7b2ab9609d
--- /dev/null
+++ b/src/System.ServiceModel.Syndication/src/System/ServiceModel/Syndication/SyndicationFeedFormatter.cs
@@ -0,0 +1,555 @@
+// 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.
+
+// DEBUG!!! #if disabled statements
+
+namespace System.ServiceModel.Syndication
+{
+ using System;
+ using System.Globalization;
+ using System.Runtime.Serialization;
+ using System.Threading;
+ using System.Threading.Tasks;
+ using System.Xml;
+
+ [DataContract]
+ public abstract class SyndicationFeedFormatter
+ {
+ private SyndicationFeed _feed;
+
+ protected SyndicationFeedFormatter()
+ {
+ _feed = null;
+ }
+
+ protected SyndicationFeedFormatter(SyndicationFeed feedToWrite)
+ {
+ if (feedToWrite == null)
+ {
+ throw new ArgumentNullException(nameof(feedToWrite));
+ }
+ _feed = feedToWrite;
+ }
+
+ public SyndicationFeed Feed
+ {
+ get
+ {
+ return _feed;
+ }
+ }
+
+ public abstract string Version { get; }
+
+ public abstract bool CanRead(XmlReader reader);
+
+ public abstract Task ReadFromAsync(XmlReader reader, CancellationToken ct);
+
+ public override string ToString()
+ {
+ return string.Format(CultureInfo.CurrentCulture, "{0}, SyndicationVersion={1}", this.GetType(), this.Version);
+ }
+
+ public abstract Task WriteToAsync(XmlWriter writer, CancellationToken ct);
+
+ internal static protected SyndicationCategory CreateCategory(SyndicationFeed feed)
+ {
+ if (feed == null)
+ {
+ throw new ArgumentNullException(nameof(feed));
+ }
+ return GetNonNullValue<SyndicationCategory>(feed.CreateCategory(), SR.FeedCreatedNullCategory);
+ }
+
+ internal static protected SyndicationCategory CreateCategory(SyndicationItem item)
+ {
+ if (item == null)
+ {
+ throw new ArgumentNullException(nameof(item));
+ }
+ return GetNonNullValue<SyndicationCategory>(item.CreateCategory(), SR.ItemCreatedNullCategory);
+ }
+
+ internal static protected SyndicationItem CreateItem(SyndicationFeed feed)
+ {
+ if (feed == null)
+ {
+ throw new ArgumentNullException(nameof(feed));
+ }
+ return GetNonNullValue<SyndicationItem>(feed.CreateItem(), SR.FeedCreatedNullItem);
+ }
+
+ internal static protected SyndicationLink CreateLink(SyndicationFeed feed)
+ {
+ if (feed == null)
+ {
+ throw new ArgumentNullException(nameof(feed));
+ }
+ return GetNonNullValue<SyndicationLink>(feed.CreateLink(), SR.FeedCreatedNullPerson);
+ }
+
+ internal static protected SyndicationLink CreateLink(SyndicationItem item)
+ {
+ if (item == null)
+ {
+ throw new ArgumentNullException(nameof(item));
+ }
+ return GetNonNullValue<SyndicationLink>(item.CreateLink(), SR.ItemCreatedNullPerson);
+ }
+
+ internal static protected SyndicationPerson CreatePerson(SyndicationFeed feed)
+ {
+ if (feed == null)
+ {
+ throw new ArgumentNullException(nameof(feed));
+ }
+ return GetNonNullValue<SyndicationPerson>(feed.CreatePerson(), SR.FeedCreatedNullPerson);
+ }
+
+ internal static protected SyndicationPerson CreatePerson(SyndicationItem item)
+ {
+ if (item == null)
+ {
+ throw new ArgumentNullException(nameof(item));
+ }
+ return GetNonNullValue<SyndicationPerson>(item.CreatePerson(), SR.ItemCreatedNullPerson);
+ }
+
+ internal static protected void LoadElementExtensions(XmlReader reader, SyndicationFeed feed, int maxExtensionSize)
+ {
+ if (feed == null)
+ {
+ throw new ArgumentNullException(nameof(feed));
+ }
+ feed.LoadElementExtensions(reader, maxExtensionSize);
+ }
+
+ internal static protected void LoadElementExtensions(XmlReader reader, SyndicationItem item, int maxExtensionSize)
+ {
+ if (item == null)
+ {
+ throw new ArgumentNullException(nameof(item));
+ }
+ item.LoadElementExtensions(reader, maxExtensionSize);
+ }
+
+ internal static protected void LoadElementExtensions(XmlReader reader, SyndicationCategory category, int maxExtensionSize)
+ {
+ if (category == null)
+ {
+ throw new ArgumentNullException(nameof(category));
+ }
+ category.LoadElementExtensions(reader, maxExtensionSize);
+ }
+
+ internal static protected void LoadElementExtensions(XmlReader reader, SyndicationLink link, int maxExtensionSize)
+ {
+ if (link == null)
+ {
+ throw new ArgumentNullException(nameof(link));
+ }
+ link.LoadElementExtensions(reader, maxExtensionSize);
+ }
+
+ internal static protected void LoadElementExtensions(XmlReader reader, SyndicationPerson person, int maxExtensionSize)
+ {
+ if (person == null)
+ {
+ throw new ArgumentNullException(nameof(person));
+ }
+ person.LoadElementExtensions(reader, maxExtensionSize);
+ }
+
+ internal static protected bool TryParseAttribute(string name, string ns, string value, SyndicationFeed feed, string version)
+ {
+ if (feed == null)
+ {
+ throw new ArgumentNullException(nameof(feed));
+ }
+
+ if (FeedUtils.IsXmlns(name, ns))
+ {
+ return true;
+ }
+
+ return feed.TryParseAttribute(name, ns, value, version);
+ }
+
+ internal static protected bool TryParseAttribute(string name, string ns, string value, SyndicationItem item, string version)
+ {
+ if (item == null)
+ {
+ throw new ArgumentNullException(nameof(item));
+ }
+ if (FeedUtils.IsXmlns(name, ns))
+ {
+ return true;
+ }
+ return item.TryParseAttribute(name, ns, value, version);
+ }
+
+ internal static protected bool TryParseAttribute(string name, string ns, string value, SyndicationCategory category, string version)
+ {
+ if (category == null)
+ {
+ throw new ArgumentNullException(nameof(category));
+ }
+ if (FeedUtils.IsXmlns(name, ns))
+ {
+ return true;
+ }
+ return category.TryParseAttribute(name, ns, value, version);
+ }
+
+ internal static protected bool TryParseAttribute(string name, string ns, string value, SyndicationLink link, string version)
+ {
+ if (link == null)
+ {
+ throw new ArgumentNullException(nameof(link));
+ }
+ if (FeedUtils.IsXmlns(name, ns))
+ {
+ return true;
+ }
+ return link.TryParseAttribute(name, ns, value, version);
+ }
+
+ internal static protected bool TryParseAttribute(string name, string ns, string value, SyndicationPerson person, string version)
+ {
+ if (person == null)
+ {
+ throw new ArgumentNullException(nameof(person));
+ }
+ if (FeedUtils.IsXmlns(name, ns))
+ {
+ return true;
+ }
+ return person.TryParseAttribute(name, ns, value, version);
+ }
+
+ internal static protected bool TryParseContent(XmlReader reader, SyndicationItem item, string contentType, string version, out SyndicationContent content)
+ {
+ return item.TryParseContent(reader, contentType, version, out content);
+ }
+
+ internal static protected bool TryParseElement(XmlReader reader, SyndicationFeed feed, string version)
+ {
+ if (feed == null)
+ {
+ throw new ArgumentNullException(nameof(feed));
+ }
+
+ return feed.TryParseElement(reader, version);
+ }
+
+ internal static protected bool TryParseElement(XmlReader reader, SyndicationItem item, string version)
+ {
+ if (item == null)
+ {
+ throw new ArgumentNullException(nameof(item));
+ }
+ return item.TryParseElement(reader, version);
+ }
+
+ internal static protected bool TryParseElement(XmlReader reader, SyndicationCategory category, string version)
+ {
+ if (category == null)
+ {
+ throw new ArgumentNullException(nameof(category));
+ }
+ return category.TryParseElement(reader, version);
+ }
+
+ internal static protected bool TryParseElement(XmlReader reader, SyndicationLink link, string version)
+ {
+ if (link == null)
+ {
+ throw new ArgumentNullException(nameof(link));
+ }
+ return link.TryParseElement(reader, version);
+ }
+
+ internal static protected bool TryParseElement(XmlReader reader, SyndicationPerson person, string version)
+ {
+ if (person == null)
+ {
+ throw new ArgumentNullException(nameof(person));
+ }
+ return person.TryParseElement(reader, version);
+ }
+
+ internal static protected async Task WriteAttributeExtensionsAsync(XmlWriter writer, SyndicationFeed feed, string version)
+ {
+ if (feed == null)
+ {
+ throw new ArgumentNullException(nameof(feed));
+ }
+ await feed.WriteAttributeExtensionsAsync(writer, version);
+ }
+
+ internal static protected Task WriteAttributeExtensionsAsync(XmlWriter writer, SyndicationItem item, string version)
+ {
+ if (item == null)
+ {
+ throw new ArgumentNullException(nameof(item));
+ }
+ return item.WriteAttributeExtensionsAsync(writer, version);
+ }
+
+ internal static protected Task WriteAttributeExtensionsAsync(XmlWriter writer, SyndicationCategory category, string version)
+ {
+ if (category == null)
+ {
+ throw new ArgumentNullException(nameof(category));
+ }
+ return category.WriteAttributeExtensionsAsync(writer, version);
+ }
+
+ internal static protected Task WriteAttributeExtensions(XmlWriter writer, SyndicationLink link, string version)
+ {
+ if (link == null)
+ {
+ throw new ArgumentNullException(nameof(link));
+ }
+ return link.WriteAttributeExtensionsAsync(writer, version);
+ }
+
+ internal static protected Task WriteAttributeExtensionsAsync(XmlWriter writer, SyndicationPerson person, string version)
+ {
+ if (person == null)
+ {
+ throw new ArgumentNullException(nameof(person));
+ }
+ return person.WriteAttributeExtensionsAsync(writer, version);
+ }
+
+ internal static protected Task WriteElementExtensionsAsync(XmlWriter writer, SyndicationFeed feed, string version)
+ {
+ if (feed == null)
+ {
+ throw new ArgumentNullException(nameof(feed));
+ }
+ return feed.WriteElementExtensionsAsync(writer, version);
+ }
+
+ internal static protected Task WriteElementExtensionsAsync(XmlWriter writer, SyndicationItem item, string version)
+ {
+ if (item == null)
+ {
+ throw new ArgumentNullException(nameof(item));
+ }
+ return item.WriteElementExtensionsAsync(writer, version);
+ }
+
+ internal static protected Task WriteElementExtensionsAsync(XmlWriter writer, SyndicationCategory category, string version)
+ {
+ if (category == null)
+ {
+ throw new ArgumentNullException(nameof(category));
+ }
+ return category.WriteElementExtensionsAsync(writer, version);
+ }
+
+ internal static protected Task WriteElementExtensionsAsync(XmlWriter writer, SyndicationLink link, string version)
+ {
+ if (link == null)
+ {
+ throw new ArgumentNullException(nameof(link));
+ }
+ return link.WriteElementExtensionsAsync(writer, version);
+ }
+
+ internal static protected Task WriteElementExtensionsAsync(XmlWriter writer, SyndicationPerson person, string version)
+ {
+ if (person == null)
+ {
+ throw new ArgumentNullException(nameof(person));
+ }
+
+ return person.WriteElementExtensionsAsync(writer, version);
+ }
+
+ internal protected virtual void SetFeed(SyndicationFeed feed) {
+ _feed = feed ?? throw new ArgumentNullException(nameof(feed));
+ }
+
+ internal static void CloseBuffer(XmlBuffer buffer, XmlDictionaryWriter extWriter)
+ {
+
+ if (buffer == null)
+ {
+ return;
+ }
+ extWriter.WriteEndElement();
+ buffer.CloseSection();
+ buffer.Close();
+ }
+
+ internal static async Task<Tuple<XmlBuffer,XmlDictionaryWriter>> CreateBufferIfRequiredAndWriteNodeAsync(XmlBuffer buffer, XmlDictionaryWriter extWriter, XmlReader reader, int maxExtensionSize)
+ {
+ if (buffer == null)
+ {
+ buffer = new XmlBuffer(maxExtensionSize);
+ extWriter = buffer.OpenSection(XmlDictionaryReaderQuotas.Max);
+ extWriter.WriteStartElement(Rss20Constants.ExtensionWrapperTag);
+ }
+
+ XmlDictionaryReader dictionaryReader = reader as XmlDictionaryReader;
+ if (dictionaryReader != null)
+ {
+ // Reimplementing WriteNode for XmlDictionaryWriter asynchronously depends on multiple internal methods
+ // so isn't feasible to reimplement here. As the primary scenario will be usage with an XmlReader which
+ // isn't an XmlDictionaryReader, deferring to the synchronous implementation is a reasonable fallback.
+ extWriter.WriteNode(reader, false);
+ }
+ else
+ {
+ await extWriter.WriteNodeAsync(reader, false);
+ }
+
+ return Tuple.Create(buffer, extWriter);
+ }
+
+ internal static SyndicationFeed CreateFeedInstance(Type feedType)
+ {
+ if (feedType.Equals(typeof(SyndicationFeed)))
+ {
+ return new SyndicationFeed();
+ }
+ else
+ {
+ return (SyndicationFeed)Activator.CreateInstance(feedType);
+ }
+ }
+
+ internal static void LoadElementExtensions(XmlBuffer buffer, XmlDictionaryWriter writer, SyndicationFeed feed)
+ {
+ if (feed == null)
+ {
+ throw new ArgumentNullException(nameof(feed));
+ }
+
+ CloseBuffer(buffer, writer);
+ feed.LoadElementExtensions(buffer);
+ }
+
+ internal static void LoadElementExtensions(XmlBuffer buffer, XmlDictionaryWriter writer, SyndicationItem item)
+ {
+
+ if (item == null)
+ {
+ throw new ArgumentNullException(nameof(item));
+ }
+ CloseBuffer(buffer, writer);
+ item.LoadElementExtensions(buffer);
+ }
+
+ internal static void LoadElementExtensions(XmlBuffer buffer, XmlDictionaryWriter writer, SyndicationCategory category)
+ {
+ if (category == null)
+ {
+ throw new ArgumentNullException(nameof(category));
+ }
+
+ CloseBuffer(buffer, writer);
+ category.LoadElementExtensions(buffer);
+ }
+
+ internal static void LoadElementExtensions(XmlBuffer buffer, XmlDictionaryWriter writer, SyndicationLink link)
+ {
+ if (link == null)
+ {
+ throw new ArgumentNullException(nameof(link));
+ }
+
+ CloseBuffer(buffer, writer);
+ link.LoadElementExtensions(buffer);
+ }
+
+ internal static void LoadElementExtensions(XmlBuffer buffer, XmlDictionaryWriter writer, SyndicationPerson person)
+ {
+ if (person == null)
+ {
+ throw new ArgumentNullException(nameof(person));
+ }
+
+ CloseBuffer(buffer, writer);
+ person.LoadElementExtensions(buffer);
+ }
+
+ internal static async Task MoveToStartElementAsync(XmlReaderWrapper reader)
+ {
+ if (!await reader.IsStartElementAsync())
+ {
+ XmlExceptionHelper.ThrowStartElementExpected(XmlDictionaryReader.CreateDictionaryReader(reader));
+ }
+ }
+
+ internal static void MoveToStartElement(XmlReader reader)
+ {
+ if (!reader.IsStartElement())
+ {
+ XmlExceptionHelper.ThrowStartElementExpected(XmlDictionaryReader.CreateDictionaryReader(reader));
+ }
+ }
+
+
+ protected abstract SyndicationFeed CreateFeedInstance();
+
+ private static T GetNonNullValue<T>(T value, string errorMsg)
+ {
+ return value;
+ }
+
+ private static class XmlExceptionHelper
+ {
+ private static void ThrowXmlException(XmlDictionaryReader reader, string res, string arg1)
+ {
+ string s = string.Format(res, arg1);
+ IXmlLineInfo lineInfo = reader as IXmlLineInfo;
+ if (lineInfo != null && lineInfo.HasLineInfo())
+ {
+ s += " " + string.Format(SR.XmlLineInfo, lineInfo.LineNumber, lineInfo.LinePosition);
+ }
+
+ throw new XmlException(s);
+ }
+
+ private static string GetName(string prefix, string localName)
+ {
+ if (prefix.Length == 0)
+ return localName;
+ else
+ return string.Concat(prefix, ":", localName);
+ }
+
+ private static string GetWhatWasFound(XmlDictionaryReader reader)
+ {
+ if (reader.EOF)
+ return SR.XmlFoundEndOfFile;
+ switch (reader.NodeType)
+ {
+ case XmlNodeType.Element:
+ return string.Format(SR.XmlFoundElement, GetName(reader.Prefix, reader.LocalName), reader.NamespaceURI);
+ case XmlNodeType.EndElement:
+ return string.Format(SR.XmlFoundEndElement, GetName(reader.Prefix, reader.LocalName), reader.NamespaceURI);
+ case XmlNodeType.Text:
+ case XmlNodeType.Whitespace:
+ case XmlNodeType.SignificantWhitespace:
+ return string.Format(SR.XmlFoundText, reader.Value);
+ case XmlNodeType.Comment:
+ return string.Format(SR.XmlFoundComment, reader.Value);
+ case XmlNodeType.CDATA:
+ return string.Format(SR.XmlFoundCData, reader.Value);
+ }
+ return string.Format(SR.XmlFoundNodeType, reader.NodeType);
+ }
+
+ static public void ThrowStartElementExpected(XmlDictionaryReader reader)
+ {
+ ThrowXmlException(reader, SR.XmlStartElementExpected, GetWhatWasFound(reader));
+ }
+ }
+ }
+}
diff --git a/src/System.ServiceModel.Syndication/src/System/ServiceModel/Syndication/SyndicationItem.cs b/src/System.ServiceModel.Syndication/src/System/ServiceModel/Syndication/SyndicationItem.cs
new file mode 100644
index 0000000000..7d3408233c
--- /dev/null
+++ b/src/System.ServiceModel.Syndication/src/System/ServiceModel/Syndication/SyndicationItem.cs
@@ -0,0 +1,318 @@
+// 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.ServiceModel.Syndication
+{
+ using System;
+ using System.Collections.Generic;
+ using System.Collections.ObjectModel;
+ using System.Threading.Tasks;
+ using System.Xml;
+
+ // NOTE: This class implements Clone so if you add any members, please update the copy ctor
+ public class SyndicationItem : IExtensibleSyndicationObject
+ {
+ private Collection<SyndicationPerson> _authors;
+ private Uri _baseUri;
+ private Collection<SyndicationCategory> _categories;
+ private SyndicationContent _content;
+ private Collection<SyndicationPerson> _contributors;
+ private TextSyndicationContent _copyright;
+ private ExtensibleSyndicationObject _extensions = new ExtensibleSyndicationObject();
+ private string _id;
+ private DateTimeOffset _lastUpdatedTime;
+ private Collection<SyndicationLink> _links;
+ private DateTimeOffset _publishDate;
+ private SyndicationFeed _sourceFeed;
+ private TextSyndicationContent _summary;
+ private TextSyndicationContent _title;
+
+ public SyndicationItem()
+ : this(null, null, null)
+ {
+ }
+
+ public SyndicationItem(string title, string content, Uri itemAlternateLink)
+ : this(title, content, itemAlternateLink, null, DateTimeOffset.MinValue)
+ {
+ }
+
+ public SyndicationItem(string title, string content, Uri itemAlternateLink, string id, DateTimeOffset lastUpdatedTime)
+ : this(title, (content != null) ? new TextSyndicationContent(content) : null, itemAlternateLink, id, lastUpdatedTime)
+ {
+ }
+
+ public SyndicationItem(string title, SyndicationContent content, Uri itemAlternateLink, string id, DateTimeOffset lastUpdatedTime)
+ {
+ if (title != null)
+ {
+ this.Title = new TextSyndicationContent(title);
+ }
+
+ _content = content;
+ if (itemAlternateLink != null)
+ {
+ this.Links.Add(SyndicationLink.CreateAlternateLink(itemAlternateLink));
+ }
+ _id = id;
+ _lastUpdatedTime = lastUpdatedTime;
+ }
+
+ protected SyndicationItem(SyndicationItem source)
+ {
+ if (source == null)
+ {
+ throw new ArgumentNullException(nameof(source));
+ }
+ _extensions = source._extensions.Clone();
+ _authors = FeedUtils.ClonePersons(source._authors);
+ _categories = FeedUtils.CloneCategories(source._categories);
+ _content = (source._content != null) ? source._content.Clone() : null;
+ _contributors = FeedUtils.ClonePersons(source._contributors);
+ _copyright = FeedUtils.CloneTextContent(source._copyright);
+ _id = source._id;
+ _lastUpdatedTime = source._lastUpdatedTime;
+ _links = FeedUtils.CloneLinks(source._links);
+ _publishDate = source._publishDate;
+ if (source.SourceFeed != null)
+ {
+ _sourceFeed = source._sourceFeed.Clone(false);
+ _sourceFeed.Items = new Collection<SyndicationItem>();
+ }
+ _summary = FeedUtils.CloneTextContent(source._summary);
+ _baseUri = source._baseUri;
+ _title = FeedUtils.CloneTextContent(source._title);
+ }
+
+ public Dictionary<XmlQualifiedName, string> AttributeExtensions
+ {
+ get { return _extensions.AttributeExtensions; }
+ }
+
+ public Collection<SyndicationPerson> Authors
+ {
+ get
+ {
+ if (_authors == null)
+ {
+ _authors = new NullNotAllowedCollection<SyndicationPerson>();
+ }
+ return _authors;
+ }
+ }
+
+ public Uri BaseUri
+ {
+ get { return _baseUri; }
+ set { _baseUri = value; }
+ }
+
+ public Collection<SyndicationCategory> Categories
+ {
+ get
+ {
+ if (_categories == null)
+ {
+ _categories = new NullNotAllowedCollection<SyndicationCategory>();
+ }
+ return _categories;
+ }
+ }
+
+ public SyndicationContent Content
+ {
+ get { return _content; }
+ set { _content = value; }
+ }
+
+ public Collection<SyndicationPerson> Contributors
+ {
+ get
+ {
+ if (_contributors == null)
+ {
+ _contributors = new NullNotAllowedCollection<SyndicationPerson>();
+ }
+ return _contributors;
+ }
+ }
+
+ public TextSyndicationContent Copyright
+ {
+ get { return _copyright; }
+ set { _copyright = value; }
+ }
+
+ public SyndicationElementExtensionCollection ElementExtensions
+ {
+ get { return _extensions.ElementExtensions; }
+ }
+
+ public string Id
+ {
+ get { return _id; }
+ set { _id = value; }
+ }
+
+ public DateTimeOffset LastUpdatedTime
+ {
+ get { return _lastUpdatedTime; }
+ set { _lastUpdatedTime = value; }
+ }
+
+ public Collection<SyndicationLink> Links
+ {
+ get
+ {
+ if (_links == null)
+ {
+ _links = new NullNotAllowedCollection<SyndicationLink>();
+ }
+ return _links;
+ }
+ }
+
+ public DateTimeOffset PublishDate
+ {
+ get { return _publishDate; }
+ set { _publishDate = value; }
+ }
+
+ public SyndicationFeed SourceFeed
+ {
+ get { return _sourceFeed; }
+ set { _sourceFeed = value; }
+ }
+
+ public TextSyndicationContent Summary
+ {
+ get { return _summary; }
+ set { _summary = value; }
+ }
+
+ public TextSyndicationContent Title
+ {
+ get { return _title; }
+ set { _title = value; }
+ }
+
+ public static Task<SyndicationItem> LoadAsync(XmlReader reader)
+ {
+ return LoadAsync<SyndicationItem>(reader);
+ }
+
+ public static async Task<TSyndicationItem> LoadAsync<TSyndicationItem>(XmlReader reader)
+ where TSyndicationItem : SyndicationItem, new()
+ {
+ if (reader == null)
+ {
+ throw new ArgumentNullException(nameof(reader));
+ }
+
+ Rss20ItemFormatter<TSyndicationItem> rssSerializer = new Rss20ItemFormatter<TSyndicationItem>();
+
+ if (rssSerializer.CanRead(reader))
+ {
+ await rssSerializer.ReadFromAsync(reader);
+ return rssSerializer.Item as TSyndicationItem;
+ }
+
+ throw new XmlException(string.Format(SR.UnknownItemXml, reader.LocalName, reader.NamespaceURI));
+ }
+
+
+ public void AddPermalink(Uri permalink)
+ {
+ if (permalink == null)
+ {
+ throw new ArgumentNullException(nameof(permalink));
+ }
+ this.Id = permalink.AbsoluteUri;
+ this.Links.Add(SyndicationLink.CreateAlternateLink(permalink));
+ }
+
+ public virtual SyndicationItem Clone()
+ {
+ return new SyndicationItem(this);
+ }
+
+ public Atom10ItemFormatter GetAtom10Formatter()
+ {
+ return new Atom10ItemFormatter(this);
+ }
+
+ public Rss20ItemFormatter GetRss20Formatter()
+ {
+ return GetRss20Formatter(true);
+ }
+
+ public Rss20ItemFormatter GetRss20Formatter(bool serializeExtensionsAsAtom)
+ {
+ return new Rss20ItemFormatter(this, serializeExtensionsAsAtom);
+ }
+
+ public Task SaveAsAtom10(XmlWriter writer)
+ {
+ return GetAtom10Formatter().WriteToAsync(writer);
+ }
+
+ public Task SaveAsRss20(XmlWriter writer)
+ {
+ return GetRss20Formatter().WriteToAsync(writer);
+ }
+
+ protected internal virtual SyndicationCategory CreateCategory()
+ {
+ return new SyndicationCategory();
+ }
+
+ protected internal virtual SyndicationLink CreateLink()
+ {
+ return new SyndicationLink();
+ }
+
+ protected internal virtual SyndicationPerson CreatePerson()
+ {
+ return new SyndicationPerson();
+ }
+
+ protected internal virtual bool TryParseAttribute(string name, string ns, string value, string version)
+ {
+ return false;
+ }
+
+ protected internal virtual bool TryParseContent(XmlReader reader, string contentType, string version, out SyndicationContent content)
+ {
+ content = null;
+ return false;
+ }
+
+ protected internal virtual bool TryParseElement(XmlReader reader, string version)
+ {
+ return false;
+ }
+
+ protected internal virtual Task WriteAttributeExtensionsAsync(XmlWriter writer, string version)
+ {
+ return _extensions.WriteAttributeExtensionsAsync(writer);
+ }
+
+ protected internal virtual Task WriteElementExtensionsAsync(XmlWriter writer, string version)
+ {
+ return _extensions.WriteElementExtensionsAsync(writer);
+ }
+
+ internal void LoadElementExtensions(XmlReader readerOverUnparsedExtensions, int maxExtensionSize)
+ {
+ _extensions.LoadElementExtensions(readerOverUnparsedExtensions, maxExtensionSize);
+ }
+
+ internal void LoadElementExtensions(XmlBuffer buffer)
+ {
+ _extensions.LoadElementExtensions(buffer);
+ }
+ }
+}
+
+
diff --git a/src/System.ServiceModel.Syndication/src/System/ServiceModel/Syndication/SyndicationItemFormatter.cs b/src/System.ServiceModel.Syndication/src/System/ServiceModel/Syndication/SyndicationItemFormatter.cs
new file mode 100644
index 0000000000..884255d276
--- /dev/null
+++ b/src/System.ServiceModel.Syndication/src/System/ServiceModel/Syndication/SyndicationItemFormatter.cs
@@ -0,0 +1,220 @@
+// 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.ServiceModel.Syndication
+{
+ using System;
+ using System.Globalization;
+ using System.Runtime.CompilerServices;
+ using System.Runtime.Serialization;
+ using System.Threading.Tasks;
+ using System.Xml;
+
+ [DataContract]
+ public abstract class SyndicationItemFormatter
+ {
+ private SyndicationItem _item;
+
+ protected SyndicationItemFormatter()
+ {
+ _item = null;
+ }
+
+ protected SyndicationItemFormatter(SyndicationItem itemToWrite)
+ {
+ if (itemToWrite == null)
+ {
+ throw new ArgumentNullException(nameof(itemToWrite));
+ }
+ _item = itemToWrite;
+ }
+
+ public SyndicationItem Item
+ {
+ get
+ {
+ return _item;
+ }
+ }
+
+ public abstract String Version
+ { get; }
+
+ public abstract bool CanRead(XmlReader reader);
+
+ public abstract Task ReadFromAsync(XmlReader reader);
+
+ public override string ToString()
+ {
+ return string.Format(CultureInfo.CurrentCulture, "{0}, SyndicationVersion={1}", this.GetType(), this.Version);
+ }
+
+ public abstract Task WriteToAsync(XmlWriter writer);
+
+ internal protected virtual void SetItem(SyndicationItem item)
+ {
+ if (item == null)
+ {
+ throw new ArgumentNullException(nameof(item));
+ }
+ _item = item;
+ }
+
+ internal static SyndicationItem CreateItemInstance(Type itemType)
+ {
+ if (itemType.Equals(typeof(SyndicationItem)))
+ {
+ return new SyndicationItem();
+ }
+ else
+ {
+ return (SyndicationItem)Activator.CreateInstance(itemType);
+ }
+ }
+
+ internal static void LoadElementExtensions(XmlBuffer buffer, XmlDictionaryWriter writer, SyndicationItem item)
+ {
+ SyndicationFeedFormatter.LoadElementExtensions(buffer, writer, item);
+ }
+
+ internal static void LoadElementExtensions(XmlBuffer buffer, XmlDictionaryWriter writer, SyndicationCategory category)
+ {
+ SyndicationFeedFormatter.LoadElementExtensions(buffer, writer, category);
+ }
+
+ internal static void LoadElementExtensions(XmlBuffer buffer, XmlDictionaryWriter writer, SyndicationLink link)
+ {
+ SyndicationFeedFormatter.LoadElementExtensions(buffer, writer, link);
+ }
+
+ internal static void LoadElementExtensions(XmlBuffer buffer, XmlDictionaryWriter writer, SyndicationPerson person)
+ {
+ SyndicationFeedFormatter.LoadElementExtensions(buffer, writer, person);
+ }
+
+ protected static SyndicationCategory CreateCategory(SyndicationItem item)
+ {
+ return SyndicationFeedFormatter.CreateCategory(item);
+ }
+
+ protected static SyndicationLink CreateLink(SyndicationItem item)
+ {
+ return SyndicationFeedFormatter.CreateLink(item);
+ }
+
+ protected static SyndicationPerson CreatePerson(SyndicationItem item)
+ {
+ return SyndicationFeedFormatter.CreatePerson(item);
+ }
+
+ protected static void LoadElementExtensions(XmlReader reader, SyndicationItem item, int maxExtensionSize)
+ {
+ SyndicationFeedFormatter.LoadElementExtensions(reader, item, maxExtensionSize);
+ }
+
+ protected static void LoadElementExtensions(XmlReader reader, SyndicationCategory category, int maxExtensionSize)
+ {
+ SyndicationFeedFormatter.LoadElementExtensions(reader, category, maxExtensionSize);
+ }
+
+ protected static void LoadElementExtensions(XmlReader reader, SyndicationLink link, int maxExtensionSize)
+ {
+ SyndicationFeedFormatter.LoadElementExtensions(reader, link, maxExtensionSize);
+ }
+
+ protected static void LoadElementExtensions(XmlReader reader, SyndicationPerson person, int maxExtensionSize)
+ {
+ SyndicationFeedFormatter.LoadElementExtensions(reader, person, maxExtensionSize);
+ }
+
+ protected static bool TryParseAttribute(string name, string ns, string value, SyndicationItem item, string version)
+ {
+ return SyndicationFeedFormatter.TryParseAttribute(name, ns, value, item, version);
+ }
+
+ protected static bool TryParseAttribute(string name, string ns, string value, SyndicationCategory category, string version)
+ {
+ return SyndicationFeedFormatter.TryParseAttribute(name, ns, value, category, version);
+ }
+
+ protected static bool TryParseAttribute(string name, string ns, string value, SyndicationLink link, string version)
+ {
+ return SyndicationFeedFormatter.TryParseAttribute(name, ns, value, link, version);
+ }
+
+ protected static bool TryParseAttribute(string name, string ns, string value, SyndicationPerson person, string version)
+ {
+ return SyndicationFeedFormatter.TryParseAttribute(name, ns, value, person, version);
+ }
+
+
+ protected static bool TryParseContent(XmlReader reader, SyndicationItem item, string contentType, string version, out SyndicationContent content)
+ {
+ return SyndicationFeedFormatter.TryParseContent(reader, item, contentType, version, out content);
+ }
+
+
+ protected static bool TryParseElement(XmlReader reader, SyndicationItem item, string version)
+ {
+ return SyndicationFeedFormatter.TryParseElement(reader, item, version);
+ }
+
+ protected static bool TryParseElement(XmlReader reader, SyndicationCategory category, string version)
+ {
+ return SyndicationFeedFormatter.TryParseElement(reader, category, version);
+ }
+
+ protected static bool TryParseElement(XmlReader reader, SyndicationLink link, string version)
+ {
+ return SyndicationFeedFormatter.TryParseElement(reader, link, version);
+ }
+
+ protected static bool TryParseElement(XmlReader reader, SyndicationPerson person, string version)
+ {
+ return SyndicationFeedFormatter.TryParseElement(reader, person, version);
+ }
+
+ protected static async Task WriteAttributeExtensionsAsync(XmlWriter writer, SyndicationItem item, string version)
+ {
+ await SyndicationFeedFormatter.WriteAttributeExtensionsAsync(writer, item, version);
+ }
+
+ protected static async Task WriteAttributeExtensionsAsync(XmlWriter writer, SyndicationCategory category, string version)
+ {
+ await SyndicationFeedFormatter.WriteAttributeExtensionsAsync(writer, category, version);
+ }
+
+ protected static async Task WriteAttributeExtensionsAsync(XmlWriter writer, SyndicationLink link, string version)
+ {
+ await SyndicationFeedFormatter.WriteAttributeExtensions(writer, link, version);
+ }
+
+ protected static async Task WriteAttributeExtensionsAsync(XmlWriter writer, SyndicationPerson person, string version)
+ {
+ await SyndicationFeedFormatter.WriteAttributeExtensionsAsync(writer, person, version);
+ }
+
+ protected static async Task WriteElementExtensionsAsync(XmlWriter writer, SyndicationItem item, string version)
+ {
+ await SyndicationFeedFormatter.WriteElementExtensionsAsync(writer, item, version);
+ }
+
+ protected abstract SyndicationItem CreateItemInstance();
+
+ protected Task WriteElementExtensionsAsync(XmlWriter writer, SyndicationCategory category, string version)
+ {
+ return SyndicationFeedFormatter.WriteElementExtensionsAsync(writer, category, version);
+ }
+
+ protected Task WriteElementExtensionsAsync(XmlWriter writer, SyndicationLink link, string version)
+ {
+ return SyndicationFeedFormatter.WriteElementExtensionsAsync(writer, link, version);
+ }
+
+ protected Task WriteElementExtensionsAsync(XmlWriter writer, SyndicationPerson person, string version)
+ {
+ return SyndicationFeedFormatter.WriteElementExtensionsAsync(writer, person, version);
+ }
+ }
+}
diff --git a/src/System.ServiceModel.Syndication/src/System/ServiceModel/Syndication/SyndicationLink.cs b/src/System.ServiceModel.Syndication/src/System/ServiceModel/Syndication/SyndicationLink.cs
new file mode 100644
index 0000000000..9743cb0cb9
--- /dev/null
+++ b/src/System.ServiceModel.Syndication/src/System/ServiceModel/Syndication/SyndicationLink.cs
@@ -0,0 +1,199 @@
+// 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.ServiceModel.Syndication
+{
+ using System;
+ using System.Collections.Generic;
+ using System.Runtime.CompilerServices;
+ using System.Threading.Tasks;
+ using System.Xml;
+
+ // NOTE: This class implements Clone so if you add any members, please update the copy ctor
+ public class SyndicationLink : IExtensibleSyndicationObject
+ {
+ private Uri _baseUri;
+ private ExtensibleSyndicationObject _extensions = new ExtensibleSyndicationObject();
+ private long _length;
+ private string _mediaType;
+ private string _relationshipType;
+ private string _title;
+ private Uri _uri;
+
+ public SyndicationLink(Uri uri)
+ : this(uri, null, null, null, 0)
+ {
+ }
+
+ public SyndicationLink(Uri uri, string relationshipType, string title, string mediaType, long length)
+ {
+ if (length < 0)
+ {
+ throw new ArgumentOutOfRangeException(nameof(length));
+ }
+ _baseUri = null;
+ _uri = uri;
+ _title = title;
+ _relationshipType = relationshipType;
+ _mediaType = mediaType;
+ _length = length;
+ }
+
+ public SyndicationLink()
+ : this(null, null, null, null, 0)
+ {
+ }
+
+ protected SyndicationLink(SyndicationLink source)
+ {
+ if (source == null)
+ {
+ throw new ArgumentNullException(nameof(source));
+ }
+ _length = source._length;
+ _mediaType = source._mediaType;
+ _relationshipType = source._relationshipType;
+ _title = source._title;
+ _baseUri = source._baseUri;
+ _uri = source._uri;
+ _extensions = source._extensions.Clone();
+ }
+
+ public Dictionary<XmlQualifiedName, string> AttributeExtensions
+ {
+ get { return _extensions.AttributeExtensions; }
+ }
+
+ public Uri BaseUri
+ {
+ get { return _baseUri; }
+ set { _baseUri = value; }
+ }
+
+ public SyndicationElementExtensionCollection ElementExtensions
+ {
+ get { return _extensions.ElementExtensions; }
+ }
+
+ public long Length
+ {
+ get { return _length; }
+ set
+ {
+ if (value < 0)
+ {
+ throw new ArgumentOutOfRangeException(nameof(value));
+ }
+ _length = value;
+ }
+ }
+
+ public string MediaType
+ {
+ get { return _mediaType; }
+ set { _mediaType = value; }
+ }
+
+ public string RelationshipType
+ {
+ get { return _relationshipType; }
+ set { _relationshipType = value; }
+ }
+
+ public string Title
+ {
+ get { return _title; }
+ set { _title = value; }
+ }
+
+ public Uri Uri
+ {
+ get { return _uri; }
+ set { _uri = value; }
+ }
+
+ public static SyndicationLink CreateAlternateLink(Uri uri)
+ {
+ return CreateAlternateLink(uri, null);
+ }
+
+ public static SyndicationLink CreateAlternateLink(Uri uri, string mediaType)
+ {
+ return new SyndicationLink(uri, Atom10Constants.AlternateTag, null, mediaType, 0);
+ }
+
+ public static SyndicationLink CreateMediaEnclosureLink(Uri uri, string mediaType, long length)
+ {
+ return new SyndicationLink(uri, Rss20Constants.EnclosureTag, null, mediaType, length);
+ }
+
+ public static SyndicationLink CreateSelfLink(Uri uri)
+ {
+ return CreateSelfLink(uri, null);
+ }
+
+ public static SyndicationLink CreateSelfLink(Uri uri, string mediaType)
+ {
+ return new SyndicationLink(uri, Atom10Constants.SelfTag, null, mediaType, 0);
+ }
+
+ public virtual SyndicationLink Clone()
+ {
+ return new SyndicationLink(this);
+ }
+
+ public Uri GetAbsoluteUri()
+ {
+ if (_uri != null)
+ {
+ if (_uri.IsAbsoluteUri)
+ {
+ return _uri;
+ }
+ else if (_baseUri != null)
+ {
+ return new Uri(_baseUri, _uri);
+ }
+ else
+ {
+ return null;
+ }
+ }
+ else
+ {
+ return null;
+ }
+ }
+
+ protected internal virtual bool TryParseAttribute(string name, string ns, string value, string version)
+ {
+ return false;
+ }
+
+ protected internal virtual bool TryParseElement(XmlReader reader, string version)
+ {
+ return false;
+ }
+
+ protected internal virtual Task WriteAttributeExtensionsAsync(XmlWriter writer, string version)
+ {
+ return _extensions.WriteAttributeExtensionsAsync(writer);
+ }
+
+ protected internal virtual Task WriteElementExtensionsAsync(XmlWriter writer, string version)
+ {
+ return _extensions.WriteElementExtensionsAsync(writer);
+ }
+
+ internal void LoadElementExtensions(XmlReader readerOverUnparsedExtensions, int maxExtensionSize)
+ {
+ _extensions.LoadElementExtensions(readerOverUnparsedExtensions, maxExtensionSize);
+ }
+
+ internal void LoadElementExtensions(XmlBuffer buffer)
+ {
+ _extensions.LoadElementExtensions(buffer);
+ }
+ }
+}
diff --git a/src/System.ServiceModel.Syndication/src/System/ServiceModel/Syndication/SyndicationPerson.cs b/src/System.ServiceModel.Syndication/src/System/ServiceModel/Syndication/SyndicationPerson.cs
new file mode 100644
index 0000000000..e69a76f300
--- /dev/null
+++ b/src/System.ServiceModel.Syndication/src/System/ServiceModel/Syndication/SyndicationPerson.cs
@@ -0,0 +1,116 @@
+// 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.ServiceModel.Syndication
+{
+ using System;
+ using System.Collections.Generic;
+ using System.Diagnostics.CodeAnalysis;
+ using System.Runtime.CompilerServices;
+ using System.Threading.Tasks;
+ using System.Xml;
+
+ // NOTE: This class implements Clone so if you add any members, please update the copy ctor
+ public class SyndicationPerson : IExtensibleSyndicationObject
+ {
+ private string _email;
+ private ExtensibleSyndicationObject _extensions = new ExtensibleSyndicationObject();
+ private string _name;
+ private string _uri;
+
+ public SyndicationPerson()
+ : this((string)null)
+ {
+ }
+
+ public SyndicationPerson(string email)
+ : this(email, null, null)
+ {
+ }
+
+ [SuppressMessage("Microsoft.Design", "CA1054:UriParametersShouldNotBeStrings", MessageId = "2#", Justification = "The Uri represents a unique category and not a network location")]
+ public SyndicationPerson(string email, string name, string uri)
+ {
+ _name = name;
+ _email = email;
+ _uri = uri;
+ }
+
+ protected SyndicationPerson(SyndicationPerson source)
+ {
+ if (source == null)
+ {
+ throw new ArgumentNullException(nameof(source));
+ }
+ _email = source._email;
+ _name = source._name;
+ _uri = source._uri;
+ _extensions = source._extensions.Clone();
+ }
+
+ public Dictionary<XmlQualifiedName, string> AttributeExtensions
+ {
+ get { return _extensions.AttributeExtensions; }
+ }
+
+ public SyndicationElementExtensionCollection ElementExtensions
+ {
+ get { return _extensions.ElementExtensions; }
+ }
+
+ public string Email
+ {
+ get { return _email; }
+ set { _email = value; }
+ }
+
+ public string Name
+ {
+ get { return _name; }
+ set { _name = value; }
+ }
+
+ [SuppressMessage("Microsoft.Design", "CA1056:UriPropertiesShouldNotBeStrings", Scope = "property", Justification = "The Uri represents a unique category and not a network location")]
+ public string Uri
+ {
+ get { return _uri; }
+ set { _uri = value; }
+ }
+
+ public virtual SyndicationPerson Clone()
+ {
+ return new SyndicationPerson(this);
+ }
+
+ protected internal virtual bool TryParseAttribute(string name, string ns, string value, string version)
+ {
+ return false;
+ }
+
+ protected internal virtual bool TryParseElement(XmlReader reader, string version)
+ {
+ return false;
+ }
+
+ protected internal virtual Task WriteAttributeExtensionsAsync(XmlWriter writer, string version)
+ {
+ return _extensions.WriteAttributeExtensionsAsync(writer);
+ }
+
+ protected internal virtual Task WriteElementExtensionsAsync(XmlWriter writer, string version)
+ {
+ return _extensions.WriteElementExtensionsAsync(writer);
+ }
+
+ internal void LoadElementExtensions(XmlReader readerOverUnparsedExtensions, int maxExtensionSize)
+ {
+ _extensions.LoadElementExtensions(readerOverUnparsedExtensions, maxExtensionSize);
+ }
+
+ internal void LoadElementExtensions(XmlBuffer buffer)
+ {
+ _extensions.LoadElementExtensions(buffer);
+ }
+ }
+}
diff --git a/src/System.ServiceModel.Syndication/src/System/ServiceModel/Syndication/SyndicationTextInput.cs b/src/System.ServiceModel.Syndication/src/System/ServiceModel/Syndication/SyndicationTextInput.cs
new file mode 100644
index 0000000000..d0c8d2f34a
--- /dev/null
+++ b/src/System.ServiceModel.Syndication/src/System/ServiceModel/Syndication/SyndicationTextInput.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.ServiceModel.Syndication
+{
+ public class SyndicationTextInput
+ {
+ public string Description;
+ public string title;
+ public SyndicationLink link;
+ public string name;
+ }
+}
diff --git a/src/System.ServiceModel.Syndication/src/System/ServiceModel/Syndication/SyndicationVersions.cs b/src/System.ServiceModel.Syndication/src/System/ServiceModel/Syndication/SyndicationVersions.cs
new file mode 100644
index 0000000000..cca8ac3133
--- /dev/null
+++ b/src/System.ServiceModel.Syndication/src/System/ServiceModel/Syndication/SyndicationVersions.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.ServiceModel.Syndication
+{
+ using System.Runtime.CompilerServices;
+
+ public static class SyndicationVersions
+ {
+ public const string Atom10 = "Atom10";
+ public const string Rss20 = "Rss20";
+ }
+}
diff --git a/src/System.ServiceModel.Syndication/src/System/ServiceModel/Syndication/TextSyndicationContent.cs b/src/System.ServiceModel.Syndication/src/System/ServiceModel/Syndication/TextSyndicationContent.cs
new file mode 100644
index 0000000000..7953f66636
--- /dev/null
+++ b/src/System.ServiceModel.Syndication/src/System/ServiceModel/Syndication/TextSyndicationContent.cs
@@ -0,0 +1,81 @@
+// 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.ServiceModel.Syndication
+{
+ using System;
+ using System.Runtime.CompilerServices;
+ using System.Xml;
+
+ // NOTE: This class implements Clone so if you add any members, please update the copy ctor
+ public class TextSyndicationContent : SyndicationContent
+ {
+ private string _text;
+ private TextSyndicationContentKind _textKind;
+
+ public TextSyndicationContent(string text) : this(text, TextSyndicationContentKind.Plaintext)
+ {
+ }
+
+ public TextSyndicationContent(string text, TextSyndicationContentKind textKind)
+ {
+ if (!TextSyndicationContentKindHelper.IsDefined(textKind))
+ {
+ throw new ArgumentOutOfRangeException(nameof(textKind));
+ }
+ _text = text;
+ _textKind = textKind;
+ }
+
+ protected TextSyndicationContent(TextSyndicationContent source)
+ : base(source)
+ {
+ if (source == null)
+ {
+ throw new ArgumentNullException(nameof(source));
+ }
+ _text = source._text;
+ _textKind = source._textKind;
+ }
+
+ public string Text
+ {
+ get { return _text; }
+ }
+
+ public override string Type
+ {
+ get
+ {
+ switch (_textKind)
+ {
+ case TextSyndicationContentKind.Html:
+ return Atom10Constants.HtmlType;
+ case TextSyndicationContentKind.XHtml:
+ return Atom10Constants.XHtmlType;
+ default:
+ return Atom10Constants.PlaintextType;
+ }
+ }
+ }
+
+ public override SyndicationContent Clone()
+ {
+ return new TextSyndicationContent(this);
+ }
+
+ protected override void WriteContentsTo(XmlWriter writer)
+ {
+ string val = _text ?? string.Empty;
+ if (_textKind == TextSyndicationContentKind.XHtml)
+ {
+ writer.WriteRaw(val);
+ }
+ else
+ {
+ writer.WriteString(val);
+ }
+ }
+ }
+}
diff --git a/src/System.ServiceModel.Syndication/src/System/ServiceModel/Syndication/TextSyndicationContentKind.cs b/src/System.ServiceModel.Syndication/src/System/ServiceModel/Syndication/TextSyndicationContentKind.cs
new file mode 100644
index 0000000000..1dda2a2e36
--- /dev/null
+++ b/src/System.ServiceModel.Syndication/src/System/ServiceModel/Syndication/TextSyndicationContentKind.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.
+
+namespace System.ServiceModel.Syndication
+{
+ using System.Runtime.CompilerServices;
+
+ public enum TextSyndicationContentKind
+ {
+ Plaintext,
+ Html,
+ XHtml
+ }
+}
diff --git a/src/System.ServiceModel.Syndication/src/System/ServiceModel/Syndication/TextSyndicationContentKindHelper.cs b/src/System.ServiceModel.Syndication/src/System/ServiceModel/Syndication/TextSyndicationContentKindHelper.cs
new file mode 100644
index 0000000000..2fdb263005
--- /dev/null
+++ b/src/System.ServiceModel.Syndication/src/System/ServiceModel/Syndication/TextSyndicationContentKindHelper.cs
@@ -0,0 +1,16 @@
+// 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.ServiceModel.Syndication
+{
+ internal static class TextSyndicationContentKindHelper
+ {
+ public static bool IsDefined(TextSyndicationContentKind kind)
+ {
+ return (kind == TextSyndicationContentKind.Plaintext
+ || kind == TextSyndicationContentKind.Html
+ || kind == TextSyndicationContentKind.XHtml);
+ }
+ }
+}
diff --git a/src/System.ServiceModel.Syndication/src/System/ServiceModel/Syndication/UrlSyndicationContent.cs b/src/System.ServiceModel.Syndication/src/System/ServiceModel/Syndication/UrlSyndicationContent.cs
new file mode 100644
index 0000000000..86bce8777f
--- /dev/null
+++ b/src/System.ServiceModel.Syndication/src/System/ServiceModel/Syndication/UrlSyndicationContent.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.
+
+namespace System.ServiceModel.Syndication
+{
+ using System;
+ using System.Runtime.CompilerServices;
+ using System.Xml;
+
+ // NOTE: This class implements Clone so if you add any members, please update the copy ctor
+ public class UrlSyndicationContent : SyndicationContent
+ {
+ private string _mediaType;
+ private Uri _url;
+
+ public UrlSyndicationContent(Uri url, string mediaType) : base()
+ {
+ if (url == null)
+ {
+ throw new ArgumentNullException(nameof(url));
+ }
+ _url = url;
+ _mediaType = mediaType;
+ }
+
+ protected UrlSyndicationContent(UrlSyndicationContent source)
+ : base(source)
+ {
+ if (source == null)
+ {
+ throw new ArgumentNullException(nameof(source));
+ }
+ _url = source._url;
+ _mediaType = source._mediaType;
+ }
+
+ public override string Type
+ {
+ get { return _mediaType; }
+ }
+
+ public Uri Url
+ {
+ get { return _url; }
+ }
+
+ public override SyndicationContent Clone()
+ {
+ return new UrlSyndicationContent(this);
+ }
+
+ protected override void WriteContentsTo(XmlWriter writer)
+ {
+ writer.WriteAttributeString(Atom10Constants.SourceTag, string.Empty, FeedUtils.GetUriString(_url));
+ }
+ }
+}
diff --git a/src/System.ServiceModel.Syndication/src/System/ServiceModel/Syndication/Workspace.cs b/src/System.ServiceModel.Syndication/src/System/ServiceModel/Syndication/Workspace.cs
new file mode 100644
index 0000000000..b8d2641343
--- /dev/null
+++ b/src/System.ServiceModel.Syndication/src/System/ServiceModel/Syndication/Workspace.cs
@@ -0,0 +1,118 @@
+// 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.ServiceModel.Syndication
+{
+ using System;
+ using System.Collections.Generic;
+ using System.Collections.ObjectModel;
+ using System.Runtime.CompilerServices;
+ using System.Threading.Tasks;
+ using System.Xml;
+
+ public class Workspace : IExtensibleSyndicationObject
+ {
+ private Uri _baseUri;
+ private Collection<ResourceCollectionInfo> _collections;
+ private ExtensibleSyndicationObject _extensions = new ExtensibleSyndicationObject();
+ private TextSyndicationContent _title;
+
+ public Workspace()
+ {
+ }
+
+ public Workspace(string title, IEnumerable<ResourceCollectionInfo> collections)
+ : this((title != null) ? new TextSyndicationContent(title) : null, collections)
+ {
+ }
+
+ public Workspace(TextSyndicationContent title, IEnumerable<ResourceCollectionInfo> collections)
+ {
+ _title = title;
+ if (collections != null)
+ {
+ _collections = new NullNotAllowedCollection<ResourceCollectionInfo>();
+ foreach (ResourceCollectionInfo collection in collections)
+ {
+ _collections.Add(collection);
+ }
+ }
+ }
+
+ public Dictionary<XmlQualifiedName, string> AttributeExtensions
+ {
+ get
+ {
+ return _extensions.AttributeExtensions;
+ }
+ }
+
+ public Uri BaseUri
+ {
+ get { return _baseUri; }
+ set { _baseUri = value; }
+ }
+
+ public Collection<ResourceCollectionInfo> Collections
+ {
+ get
+ {
+ if (_collections == null)
+ {
+ _collections = new NullNotAllowedCollection<ResourceCollectionInfo>();
+ }
+ return _collections;
+ }
+ }
+
+ public SyndicationElementExtensionCollection ElementExtensions
+ {
+ get
+ {
+ return _extensions.ElementExtensions;
+ }
+ }
+
+ public TextSyndicationContent Title
+ {
+ get { return _title; }
+ set { _title = value; }
+ }
+
+ protected internal virtual ResourceCollectionInfo CreateResourceCollection()
+ {
+ return new ResourceCollectionInfo();
+ }
+
+ protected internal virtual bool TryParseAttribute(string name, string ns, string value, string version)
+ {
+ return false;
+ }
+
+ protected internal virtual bool TryParseElement(XmlReader reader, string version)
+ {
+ return false;
+ }
+
+ protected internal virtual Task WriteAttributeExtensions(XmlWriter writer, string version)
+ {
+ return _extensions.WriteAttributeExtensionsAsync(writer);
+ }
+
+ protected internal virtual Task WriteElementExtensionsAsync(XmlWriter writer, string version)
+ {
+ return _extensions.WriteElementExtensionsAsync(writer);
+ }
+
+ internal void LoadElementExtensions(XmlReaderWrapper readerOverUnparsedExtensions, int maxExtensionSize)
+ {
+ _extensions.LoadElementExtensions(readerOverUnparsedExtensions, maxExtensionSize);
+ }
+
+ internal void LoadElementExtensions(XmlBuffer buffer)
+ {
+ _extensions.LoadElementExtensions(buffer);
+ }
+ }
+}
diff --git a/src/System.ServiceModel.Syndication/src/System/ServiceModel/Syndication/XmlReaderWrapper.cs b/src/System.ServiceModel.Syndication/src/System/ServiceModel/Syndication/XmlReaderWrapper.cs
new file mode 100644
index 0000000000..5e8d8d2925
--- /dev/null
+++ b/src/System.ServiceModel.Syndication/src/System/ServiceModel/Syndication/XmlReaderWrapper.cs
@@ -0,0 +1,549 @@
+using System;
+using System.Diagnostics;
+using System.Threading.Tasks;
+using System.Xml;
+
+namespace System.ServiceModel.Syndication
+{
+ internal class XmlReaderWrapper : XmlReader
+ {
+ private XmlReader reader;
+
+ private Func<XmlReaderWrapper, Task<string>> getValueFunc;
+ private Func<XmlReaderWrapper, Task<XmlNodeType>> moveToContentFunc;
+ private Func<XmlReaderWrapper, Task> skipFunc;
+ private Func<XmlReaderWrapper, Task<bool>> readFunc;
+ private Func<XmlReaderWrapper, Task<string>> readInnerXmlFunc;
+
+ private XmlReaderWrapper(XmlReader reader)
+ {
+ if (reader == null)
+ {
+ throw new ArgumentNullException(nameof(reader));
+ }
+
+ this.reader = reader;
+
+ if (this.reader.Settings.Async)
+ {
+ InitAsync();
+ }
+ else
+ {
+ Init();
+ }
+ }
+
+ public static XmlReaderWrapper CreateFromReader(XmlReader reader)
+ {
+ XmlReaderWrapper wrappedReader = reader as XmlReaderWrapper;
+ return wrappedReader != null ? wrappedReader : new XmlReaderWrapper(reader);
+ }
+
+ private void InitAsync()
+ {
+ this.getValueFunc = new Func<XmlReaderWrapper, Task<string>>((thisPtr) => { return thisPtr.reader.GetValueAsync(); });
+ this.moveToContentFunc = new Func<XmlReaderWrapper, Task<XmlNodeType>>((thisPtr) => { return thisPtr.reader.MoveToContentAsync(); });
+ this.skipFunc = new Func<XmlReaderWrapper, Task>((thisPtr) => { return thisPtr.reader.SkipAsync(); });
+ this.readFunc = new Func<XmlReaderWrapper, Task<bool>>((thisPtr) => { return thisPtr.reader.ReadAsync(); });
+ this.readInnerXmlFunc = new Func<XmlReaderWrapper, Task<string>>((thisPtr) => { return thisPtr.reader.ReadInnerXmlAsync(); });
+ }
+
+ private void Init()
+ {
+ this.getValueFunc = new Func<XmlReaderWrapper, Task<string>>((thisPtr) => { return Task.FromResult<string>(thisPtr.reader.Value); });
+ this.moveToContentFunc = new Func<XmlReaderWrapper, Task<XmlNodeType>>((thisPtr) => { return Task.FromResult<XmlNodeType>(this.reader.MoveToContent()); });
+ this.skipFunc = new Func<XmlReaderWrapper, Task>((thisPtr) => { this.reader.Skip(); return Task.CompletedTask; });
+ this.readFunc = new Func<XmlReaderWrapper, Task<bool>>((thisPtr) => { return Task.FromResult<bool>(this.reader.Read()); });
+ this.readInnerXmlFunc = new Func<XmlReaderWrapper, Task<string>>((thisPtr) => { return Task.FromResult<string>(this.reader.ReadInnerXml()); });
+ }
+
+ public override XmlNodeType NodeType
+ {
+ get
+ {
+ return this.reader.NodeType;
+ }
+ }
+
+ public override string LocalName
+ {
+ get
+ {
+ return this.reader.LocalName;
+ }
+ }
+
+ public override string NamespaceURI
+ {
+ get
+ {
+ return this.reader.NamespaceURI;
+ }
+ }
+
+ public override string Prefix
+ {
+ get
+ {
+ return this.reader.Prefix;
+ }
+ }
+
+ public override string Value
+ {
+ get
+ {
+ return this.reader.Value;
+ }
+ }
+
+ public override int Depth
+ {
+ get
+ {
+ return this.reader.Depth;
+ }
+ }
+
+ public override string BaseURI
+ {
+ get
+ {
+ return this.reader.BaseURI;
+ }
+ }
+
+ public override bool IsEmptyElement
+ {
+ get
+ {
+ return this.reader.IsEmptyElement;
+ }
+ }
+
+ public override int AttributeCount
+ {
+ get
+ {
+ return this.reader.AttributeCount;
+ }
+ }
+
+ public override bool EOF
+ {
+ get
+ {
+ return this.reader.EOF;
+ }
+ }
+
+ public override ReadState ReadState
+ {
+ get
+ {
+ return this.reader.ReadState;
+ }
+ }
+
+ public override XmlNameTable NameTable
+ {
+ get
+ {
+ return this.reader.NameTable;
+ }
+ }
+
+ public override string GetAttribute(string name)
+ {
+ return this.reader.GetAttribute(name);
+ }
+
+ public override string GetAttribute(string name, string namespaceURI)
+ {
+ return this.reader.GetAttribute(name, namespaceURI);
+ }
+
+ public override string GetAttribute(int i)
+ {
+ return this.reader.GetAttribute(i);
+ }
+
+ public override string LookupNamespace(string prefix)
+ {
+ return this.reader.LookupNamespace(prefix);
+ }
+
+ public override bool MoveToAttribute(string name)
+ {
+ return this.reader.MoveToAttribute(name);
+ }
+
+ public override bool MoveToAttribute(string name, string ns)
+ {
+ return this.reader.MoveToAttribute(name, ns);
+ }
+
+ public override bool MoveToElement()
+ {
+ return this.reader.MoveToElement();
+ }
+
+ public override bool MoveToFirstAttribute()
+ {
+ return this.reader.MoveToFirstAttribute();
+ }
+
+ public override bool MoveToNextAttribute()
+ {
+ return this.reader.MoveToNextAttribute();
+ }
+
+ public override bool Read()
+ {
+ return this.reader.Read();
+ }
+
+ public override bool ReadAttributeValue()
+ {
+ return this.reader.ReadAttributeValue();
+ }
+
+ public override void ResolveEntity()
+ {
+ this.reader.ResolveEntity();
+ }
+
+ public override Task<string> GetValueAsync()
+ {
+ return this.getValueFunc(this);
+ }
+
+ public override Task<XmlNodeType> MoveToContentAsync()
+ {
+ return this.moveToContentFunc(this);
+ }
+
+ public override Task SkipAsync()
+ {
+ return this.skipFunc(this);
+ }
+
+ public override Task<bool> ReadAsync()
+ {
+ return this.readFunc(this);
+ }
+
+ public override Task<string> ReadInnerXmlAsync()
+ {
+ return readInnerXmlFunc(this);
+ }
+
+ public static async Task WriteNodeAsync(XmlDictionaryWriter writer, XmlReader reader, bool defattr)
+ {
+ char[] writeNodeBuffer = null;
+ const int WriteNodeBufferSize = 1024;
+
+ if (null == reader)
+ {
+ throw new ArgumentNullException(nameof(reader));
+ }
+
+ bool canReadChunk = reader.CanReadValueChunk;
+ int d = reader.NodeType == XmlNodeType.None ? -1 : reader.Depth;
+ do
+ {
+ switch (reader.NodeType)
+ {
+ case XmlNodeType.Element:
+ writer.WriteStartElement(reader.Prefix, reader.LocalName, reader.NamespaceURI);
+ writer.WriteAttributes(reader, defattr);
+ if (reader.IsEmptyElement)
+ {
+ writer.WriteEndElement();
+ break;
+ }
+ break;
+ case XmlNodeType.Text:
+ if (canReadChunk)
+ {
+ if (writeNodeBuffer == null)
+ {
+ writeNodeBuffer = new char[WriteNodeBufferSize];
+ }
+ int read;
+ while ((read = reader.ReadValueChunk(writeNodeBuffer, 0, WriteNodeBufferSize)) > 0)
+ {
+ writer.WriteChars(writeNodeBuffer, 0, read);
+ }
+ }
+ else
+ {
+ writer.WriteString(await reader.GetValueAsync());
+ }
+ break;
+
+ case XmlNodeType.Whitespace:
+ case XmlNodeType.SignificantWhitespace:
+ writer.WriteWhitespace(await reader.GetValueAsync());
+ break;
+
+ case XmlNodeType.CDATA:
+ writer.WriteCData(await reader.GetValueAsync());
+ break;
+
+ case XmlNodeType.EntityReference:
+ writer.WriteEntityRef(reader.Name);
+ break;
+
+ case XmlNodeType.XmlDeclaration:
+ case XmlNodeType.ProcessingInstruction:
+ writer.WriteProcessingInstruction(reader.Name, await reader.GetValueAsync());
+ break;
+
+ case XmlNodeType.DocumentType:
+ writer.WriteDocType(reader.Name, reader.GetAttribute("PUBLIC"), reader.GetAttribute("SYSTEM"), await reader.GetValueAsync());
+ break;
+
+ case XmlNodeType.Comment:
+ writer.WriteComment(await reader.GetValueAsync());
+ break;
+
+ case XmlNodeType.EndElement:
+ writer.WriteFullEndElement();
+ break;
+ }
+ } while (await reader.ReadAsync() && (d < reader.Depth || (d == reader.Depth && reader.NodeType == XmlNodeType.EndElement)));
+ }
+ }
+
+ internal static class XmlReaderExtensions
+ {
+ static private uint IsTextualNodeBitmap = 0x6018; // 00 0110 0000 0001 1000
+
+ public static async Task ReadStartElementAsync(this XmlReader reader)
+ {
+ if (await reader.MoveToContentAsync() != XmlNodeType.Element)
+ {
+ throw new InvalidOperationException(reader.NodeType.ToString() + " is an invalid XmlNodeType");
+ }
+
+ await reader.ReadAsync();
+ }
+
+ public static async Task<string> ReadElementStringAsync(this XmlReader reader)
+ {
+ string result = string.Empty;
+
+ if (await reader.MoveToContentAsync() != XmlNodeType.Element)
+ {
+ //throw new XmlException(Res.Xml_InvalidNodeType, this.NodeType.ToString(), this as IXmlLineInfo);
+ throw new InvalidOperationException(reader.NodeType.ToString() + " is an invalid XmlNodeType");
+ }
+ if (!reader.IsEmptyElement)
+ {
+ await reader.ReadAsync();
+ result = reader.ReadString();
+ if (reader.NodeType != XmlNodeType.EndElement)
+ {
+ throw new XmlException();
+ throw new XmlException(reader.NodeType.ToString() + " is an invalid XmlNodeType");
+ //throw new XmlException(Res.Xml_UnexpectedNodeInSimpleContent, new string[] { this.NodeType.ToString(), "ReadElementString" }, this as IXmlLineInfo);
+ }
+ await reader.ReadAsync();
+ }
+ else
+ {
+ await reader.ReadAsync();
+ }
+ return result;
+
+ }
+
+ public static async Task<string> ReadStringAsync(this XmlReader reader)
+ {
+ if (reader.ReadState != ReadState.Interactive)
+ {
+ return string.Empty;
+ }
+ reader.MoveToElement();
+ if (reader.NodeType == XmlNodeType.Element)
+ {
+ if (reader.IsEmptyElement)
+ {
+ return string.Empty;
+ }
+ else if (!await reader.ReadAsync())
+ {
+ throw new XmlException(reader.NodeType.ToString() + " is an invalid XmlNodeType");
+ //throw new InvalidOperationException(Res.GetString(Res.Xml_InvalidOperation));
+ }
+ if (reader.NodeType == XmlNodeType.EndElement)
+ {
+ return string.Empty;
+ }
+ }
+ string result = string.Empty;
+ while (IsTextualNode(reader.NodeType))
+ {
+ result += await reader.GetValueAsync();
+ if (!await reader.ReadAsync())
+ {
+ break;
+ }
+ }
+ return result;
+
+ }
+
+ static internal bool IsTextualNode(XmlNodeType nodeType)
+ {
+#if DEBUG
+ // This code verifies IsTextualNodeBitmap mapping of XmlNodeType to a bool specifying
+ // whether the node is 'textual' = Text, CDATA, Whitespace or SignificantWhitespace.
+ Debug.Assert(0 == (IsTextualNodeBitmap & (1 << (int)XmlNodeType.None)));
+ Debug.Assert(0 == (IsTextualNodeBitmap & (1 << (int)XmlNodeType.Element)));
+ Debug.Assert(0 == (IsTextualNodeBitmap & (1 << (int)XmlNodeType.Attribute)));
+ Debug.Assert(0 != (IsTextualNodeBitmap & (1 << (int)XmlNodeType.Text)));
+ Debug.Assert(0 != (IsTextualNodeBitmap & (1 << (int)XmlNodeType.CDATA)));
+ Debug.Assert(0 == (IsTextualNodeBitmap & (1 << (int)XmlNodeType.EntityReference)));
+ Debug.Assert(0 == (IsTextualNodeBitmap & (1 << (int)XmlNodeType.Entity)));
+ Debug.Assert(0 == (IsTextualNodeBitmap & (1 << (int)XmlNodeType.ProcessingInstruction)));
+ Debug.Assert(0 == (IsTextualNodeBitmap & (1 << (int)XmlNodeType.Comment)));
+ Debug.Assert(0 == (IsTextualNodeBitmap & (1 << (int)XmlNodeType.Document)));
+ Debug.Assert(0 == (IsTextualNodeBitmap & (1 << (int)XmlNodeType.DocumentType)));
+ Debug.Assert(0 == (IsTextualNodeBitmap & (1 << (int)XmlNodeType.DocumentFragment)));
+ Debug.Assert(0 == (IsTextualNodeBitmap & (1 << (int)XmlNodeType.Notation)));
+ Debug.Assert(0 != (IsTextualNodeBitmap & (1 << (int)XmlNodeType.Whitespace)));
+ Debug.Assert(0 != (IsTextualNodeBitmap & (1 << (int)XmlNodeType.SignificantWhitespace)));
+ Debug.Assert(0 == (IsTextualNodeBitmap & (1 << (int)XmlNodeType.EndElement)));
+ Debug.Assert(0 == (IsTextualNodeBitmap & (1 << (int)XmlNodeType.EndEntity)));
+ Debug.Assert(0 == (IsTextualNodeBitmap & (1 << (int)XmlNodeType.XmlDeclaration)));
+#endif
+ return 0 != (IsTextualNodeBitmap & (1 << (int)nodeType));
+ }
+
+ public static async Task ReadEndElementAsync(this XmlReader reader)
+ {
+ if (await reader.MoveToContentAsync() != XmlNodeType.EndElement)
+ {
+ throw new XmlException(reader.NodeType.ToString() + " is an invalid XmlNodeType");
+ //throw new XmlException(Res.Xml_InvalidNodeType, this.NodeType.ToString(), this as IXmlLineInfo);
+ }
+ await reader.ReadAsync();
+ }
+
+ public static async Task ReadStartElementAsync(this XmlReader reader, string localname, string ns)
+ {
+ if (await reader.MoveToContentAsync() != XmlNodeType.Element)
+ {
+ //throw new XmlException(Res.Xml_InvalidNodeType, this.NodeType.ToString(), this as IXmlLineInfo);
+ throw new XmlException(reader.NodeType.ToString() + " is an invalid XmlNodeType");
+ }
+ if (reader.LocalName == localname && reader.NamespaceURI == ns)
+ {
+ await reader.ReadAsync();
+ }
+ else
+ {
+ throw new XmlException(reader.NodeType.ToString() + " is an invalid XmlNodeType");
+ //throw new XmlException(Res.Xml_ElementNotFoundNs, new string[2] { localname, ns }, this as IXmlLineInfo);
+ }
+
+ }
+
+ public static async Task<bool> IsStartElementAsync(this XmlReader reader)
+ {
+ return await reader.MoveToContentAsync() == XmlNodeType.Element;
+ }
+
+ public static async Task<bool> IsStartElementAsync(this XmlReader reader, string localname, string ns)
+ {
+ return (await reader.MoveToContentAsync() == XmlNodeType.Element) && (reader.LocalName == localname && reader.NamespaceURI == ns);
+ }
+
+ private static async Task ReadStartElementAsync(this XmlReader reader, string name)
+ {
+ if (await reader.MoveToContentAsync() != XmlNodeType.Element)
+ {
+ throw new InvalidOperationException(reader.NodeType.ToString() + " is an invalid XmlNodeType");
+ }
+ if (reader.Name == name)
+ {
+ await reader.ReadAsync();
+ }
+ else
+ {
+ throw new InvalidOperationException("name doesn’t match");
+ }
+ }
+
+ private static async Task<bool> IsStartElementAsync(this XmlReader reader, string name)
+ {
+ return await reader.MoveToContentAsync() == XmlNodeType.Element && reader.Name == name;
+ }
+
+ private static async Task<string> ReadElementStringAsync(this XmlReader reader, string name)
+ {
+ string result = string.Empty;
+
+ if (await reader.MoveToContentAsync() != XmlNodeType.Element)
+ {
+ throw new XmlException("InvalidNodeType");
+ }
+ if (reader.Name != name)
+ {
+ throw new XmlException("ElementNotFound");
+ }
+
+ if (!reader.IsEmptyElement)
+ {
+ result = await ReadStringAsync(reader);
+
+ if (reader.NodeType != XmlNodeType.EndElement)
+ {
+ throw new XmlException("InvalidNodeType");
+ }
+ await reader.ReadAsync();
+ }
+ else
+ {
+ await reader.ReadAsync();
+ }
+ return result;
+ }
+
+ private static async Task<string> ReadElementStringAsync(XmlReader reader, string localname, string ns)
+ {
+ string result = string.Empty;
+
+ if (await reader.MoveToContentAsync() != XmlNodeType.Element)
+ {
+ throw new XmlException("InvalidNodeType");
+ }
+
+ if (reader.LocalName != localname || reader.NamespaceURI != ns)
+ {
+ throw new XmlException("ElementNotFound");
+ }
+
+ if (!reader.IsEmptyElement)
+ {
+ result = await ReadStringAsync(reader);
+
+ if (reader.NodeType != XmlNodeType.EndElement)
+ {
+ throw new XmlException("InvalidNodeType");
+ }
+ await reader.ReadAsync();
+ }
+ else
+ {
+ await reader.ReadAsync();
+ }
+ return result;
+ }
+
+ }
+
+}
diff --git a/src/System.ServiceModel.Syndication/src/System/ServiceModel/Syndication/XmlSyndicationContent.cs b/src/System.ServiceModel.Syndication/src/System/ServiceModel/Syndication/XmlSyndicationContent.cs
new file mode 100644
index 0000000000..a50234921a
--- /dev/null
+++ b/src/System.ServiceModel.Syndication/src/System/ServiceModel/Syndication/XmlSyndicationContent.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.
+
+namespace System.ServiceModel.Syndication
+{
+ using System;
+ using System.Diagnostics;
+ using System.Runtime.CompilerServices;
+ using System.Runtime.Serialization;
+ using System.Threading.Tasks;
+ using System.Xml;
+ using System.Xml.Serialization;
+
+ public class XmlSyndicationContent : SyndicationContent
+ {
+ private XmlBuffer _contentBuffer;
+ private SyndicationElementExtension _extension;
+ private string _type;
+
+ // Saves the element in the reader to the buffer (attributes preserved)
+ // Type is populated from type attribute on reader
+ // Reader must be positioned at an element
+ public XmlSyndicationContent(XmlReader reader)
+ {
+ if (reader == null)
+ {
+ throw new ArgumentNullException(nameof(reader));
+ }
+ SyndicationFeedFormatter.MoveToStartElement(reader);
+ if (reader.HasAttributes)
+ {
+ while (reader.MoveToNextAttribute())
+ {
+ string name = reader.LocalName;
+ string ns = reader.NamespaceURI;
+ string value = reader.Value;
+ if (name == Atom10Constants.TypeTag && ns == string.Empty)
+ {
+ _type = value;
+ }
+ else if (!FeedUtils.IsXmlns(name, ns))
+ {
+ base.AttributeExtensions.Add(new XmlQualifiedName(name, ns), value);
+ }
+ }
+ reader.MoveToElement();
+ }
+ _type = string.IsNullOrEmpty(_type) ? Atom10Constants.XmlMediaType : _type;
+ _contentBuffer = new XmlBuffer(int.MaxValue);
+ using (XmlDictionaryWriter writer = _contentBuffer.OpenSection(XmlDictionaryReaderQuotas.Max))
+ {
+ writer.WriteNode(reader, false);
+ }
+ _contentBuffer.CloseSection();
+ _contentBuffer.Close();
+ }
+
+ public XmlSyndicationContent(string type, object dataContractExtension, XmlObjectSerializer dataContractSerializer)
+ {
+ _type = string.IsNullOrEmpty(type) ? Atom10Constants.XmlMediaType : type;
+ _extension = new SyndicationElementExtension(dataContractExtension, dataContractSerializer);
+ }
+
+ public XmlSyndicationContent(string type, object xmlSerializerExtension, XmlSerializer serializer)
+ {
+ _type = string.IsNullOrEmpty(type) ? Atom10Constants.XmlMediaType : type;
+ _extension = new SyndicationElementExtension(xmlSerializerExtension, serializer);
+ }
+
+ public XmlSyndicationContent(string type, SyndicationElementExtension extension)
+ {
+ if (extension == null)
+ {
+ throw new ArgumentNullException(nameof(extension));
+ }
+ _type = string.IsNullOrEmpty(type) ? Atom10Constants.XmlMediaType : type;
+ _extension = extension;
+ }
+
+ protected XmlSyndicationContent(XmlSyndicationContent source)
+ : base(source)
+ {
+ if (source == null)
+ {
+ throw new ArgumentNullException(nameof(source));
+ }
+ _contentBuffer = source._contentBuffer;
+ _extension = source._extension;
+ _type = source._type;
+ }
+
+ public SyndicationElementExtension Extension
+ {
+ get
+ {
+ return _extension;
+ }
+ }
+
+ public override string Type
+ {
+ get { return _type; }
+ }
+
+ public override SyndicationContent Clone()
+ {
+ return new XmlSyndicationContent(this);
+ }
+
+ public async Task<XmlDictionaryReader> GetReaderAtContent()
+ {
+ await EnsureContentBufferAsync();
+ return _contentBuffer.GetReader(0);
+ }
+
+ public Task<TContent> ReadContent<TContent>()
+ {
+ return ReadContent<TContent>((DataContractSerializer)null);
+ }
+
+ public async Task<TContent> ReadContent<TContent>(XmlObjectSerializer dataContractSerializer)
+ {
+ if (dataContractSerializer == null)
+ {
+ dataContractSerializer = new DataContractSerializer(typeof(TContent));
+ }
+ if (_extension != null)
+ {
+ return await _extension.GetObject<TContent>(dataContractSerializer);
+ }
+ else
+ {
+ Debug.Assert(_contentBuffer != null, "contentBuffer cannot be null");
+ using (XmlDictionaryReader reader = _contentBuffer.GetReader(0))
+ {
+ // skip past the content element
+ reader.ReadStartElement();
+ return (TContent)dataContractSerializer.ReadObject(reader, false);
+ }
+ }
+ }
+
+ public Task<TContent> ReadContent<TContent>(XmlSerializer serializer)
+ {
+ if (serializer == null)
+ {
+ serializer = new XmlSerializer(typeof(TContent));
+ }
+ if (_extension != null)
+ {
+ return _extension.GetObject<TContent>(serializer);
+ }
+ else
+ {
+ Debug.Assert(_contentBuffer != null, "contentBuffer cannot be null");
+ using (XmlDictionaryReader reader = _contentBuffer.GetReader(0))
+ {
+ // skip past the content element
+ reader.ReadStartElement();
+ return Task.FromResult((TContent)serializer.Deserialize(reader));
+ //return (TContent)serializer.Deserialize(reader);
+ }
+ }
+ }
+
+ // does not write start element or type attribute, writes other attributes and rest of content
+ protected override void WriteContentsTo(XmlWriter writer)
+ {
+ if (writer == null)
+ {
+ throw new ArgumentNullException(nameof(writer));
+ }
+ if (_extension != null)
+ {
+ _extension.WriteToAsync(writer).GetAwaiter().GetResult();
+ }
+ else if (_contentBuffer != null)
+ {
+ using (XmlDictionaryReader reader = _contentBuffer.GetReader(0))
+ {
+ reader.MoveToStartElement();
+ if (!reader.IsEmptyElement)
+ {
+ reader.ReadStartElement();
+ while (reader.Depth >= 1 && reader.ReadState == ReadState.Interactive)
+ {
+ writer.WriteNode(reader, false);
+ }
+ }
+ }
+ }
+ }
+
+ private async Task EnsureContentBufferAsync()
+ {
+ if (_contentBuffer == null)
+ {
+ XmlBuffer tmp = new XmlBuffer(int.MaxValue);
+ using (XmlDictionaryWriter writer = tmp.OpenSection(XmlDictionaryReaderQuotas.Max))
+ {
+ await this.WriteToAsync(writer, Atom10Constants.ContentTag, Atom10Constants.Atom10Namespace);
+ }
+ tmp.CloseSection();
+ tmp.Close();
+ _contentBuffer = tmp;
+ }
+ }
+ }
+}
diff --git a/src/System.ServiceModel.Syndication/src/System/ServiceModel/Syndication/XmlWriterWrapper.cs b/src/System.ServiceModel.Syndication/src/System/ServiceModel/Syndication/XmlWriterWrapper.cs
new file mode 100644
index 0000000000..a35027a359
--- /dev/null
+++ b/src/System.ServiceModel.Syndication/src/System/ServiceModel/Syndication/XmlWriterWrapper.cs
@@ -0,0 +1,268 @@
+using System;
+using System.Threading.Tasks;
+using System.Xml;
+
+namespace System.ServiceModel.Syndication
+{
+ internal class XmlWriterWrapper : XmlWriter
+ {
+
+ private XmlWriter writer;
+
+ private Func<XmlWriterWrapper, string, Task> writeStringFunc;
+ private Func<XmlWriterWrapper, string, string, Task> writeStartElementFunc2;
+ private Func<XmlWriterWrapper, Task> writeEndElementFunc;
+ private Func<XmlWriterWrapper, string, string, Task> writeAttributeStringFunc2;
+ private Func<XmlWriterWrapper, string, string, string, Task> writeAttributeStringFunc3;
+ private Func<XmlWriterWrapper, string, string, string, string, Task> writeAttributeStringFunc4;
+ private Func<XmlWriterWrapper, XmlReader, bool, Task> WriteNodeFunc;
+
+
+ private void InitAsync()
+ {
+ this.writeStringFunc = new Func<XmlWriterWrapper, string, Task>((thisPtr, text) => { return thisPtr.writer.WriteStringAsync(text); });
+ this.writeStartElementFunc2 = new Func<XmlWriterWrapper, string, string, Task>((thisPtr, localName, ns) => { return this.writer.WriteStartElementAsync("", localName, ns); });
+ this.writeEndElementFunc = new Func<XmlWriterWrapper, Task>((thisPtr) => { return thisPtr.writer.WriteEndElementAsync(); });
+ this.writeAttributeStringFunc2 = new Func<XmlWriterWrapper, string, string, Task>((thisPtr, localname, value) => { return thisPtr.writer.WriteAttributeStringAsync("", localname, "", value); });
+ this.writeAttributeStringFunc3 = new Func<XmlWriterWrapper, string, string, string, Task>((thisPtr, localName, ns, value) => { return thisPtr.writer.WriteAttributeStringAsync("", localName, ns, value); });
+ this.writeAttributeStringFunc4 = new Func<XmlWriterWrapper, string, string, string, string, Task>((thisPtr, prefix, localName, ns, value) => { return thisPtr.writer.WriteAttributeStringAsync(prefix, localName, ns, value); });
+ this.WriteNodeFunc = new Func<XmlWriterWrapper, XmlReader, bool, Task>((thisPtr, reader, defattr) => { return thisPtr.writer.WriteNodeAsync(reader, defattr); });
+ }
+
+ private void Init()
+ {
+ this.writeStringFunc = new Func<XmlWriterWrapper, string, Task>((thisPtr, text) => { thisPtr.writer.WriteString(text); return Task.CompletedTask; });
+ this.writeStartElementFunc2 = new Func<XmlWriterWrapper, string, string, Task>((thisPtr, localName, ns) => { this.writer.WriteStartElement(localName, ns); return Task.CompletedTask; });
+ this.writeEndElementFunc = new Func<XmlWriterWrapper, Task>((thisPtr) => { thisPtr.writer.WriteEndElement(); return Task.CompletedTask; });
+ this.writeAttributeStringFunc2 = new Func<XmlWriterWrapper, string, string, Task>((thisPtr, localname, value) => { thisPtr.writer.WriteAttributeString("", localname, "", value); return Task.CompletedTask; });
+ this.writeAttributeStringFunc3 = new Func<XmlWriterWrapper, string, string, string, Task>((thisPtr, localName, ns, value) => { thisPtr.writer.WriteAttributeString(localName, ns, value); return Task.CompletedTask; });
+ this.writeAttributeStringFunc4 = new Func<XmlWriterWrapper, string, string, string, string, Task>((thisPtr, prefix, localName, ns, value) => { thisPtr.writer.WriteAttributeString(prefix, localName, ns, value); return Task.CompletedTask; });
+ this.WriteNodeFunc = new Func<XmlWriterWrapper, XmlReader, bool, Task>((thisPtr, reader, defattr) => { thisPtr.writer.WriteNode(reader, defattr); return Task.CompletedTask; });
+ }
+
+ public static XmlWriter CreateFromWriter(XmlWriter writer)
+ {
+ if (writer is XmlWriterWrapper || writer.Settings.Async)
+ {
+ return writer;
+ }
+
+ return new XmlWriterWrapper(writer);
+ }
+
+
+ public XmlWriterWrapper(XmlWriter writer)
+ {
+ if (writer == null)
+ throw new ArgumentNullException(nameof(writer));
+
+ this.writer = writer;
+
+ if (this.writer.Settings.Async)
+ {
+ InitAsync();
+ }
+ else
+ {
+ Init();
+ }
+ }
+
+ // wrapper methods
+
+ public override Task WriteNodeAsync(XmlReader reader, bool defattr)
+ {
+ return WriteNodeFunc(this, reader, defattr);
+ }
+
+ public override Task WriteStringAsync(string text)
+ {
+ return writeStringFunc(this, text);
+ }
+
+ public override Task WriteStartElementAsync(string prefix, string localName, string ns)
+ {
+ writer.WriteStartElement(prefix, localName, ns);
+ return Task.CompletedTask;
+ }
+
+ public override Task WriteEndElementAsync()
+ {
+ return writeEndElementFunc(this);
+ }
+
+ public override Task WriteAttributesAsync(XmlReader reader, bool defattr)
+ {
+ writer.WriteAttributes(reader, defattr);
+ return Task.CompletedTask;
+ }
+
+ // inherited methods
+ public override WriteState WriteState
+ {
+ get
+ {
+ return this.writer.WriteState;
+ }
+ }
+
+ public override void Flush()
+ {
+ this.writer.Flush();
+ }
+
+ public override string LookupPrefix(string ns)
+ {
+ return this.writer.LookupPrefix(ns);
+ }
+
+ public override void WriteBase64(byte[] buffer, int index, int count)
+ {
+ this.writer.WriteBase64(buffer, index, count);
+ }
+
+ public override void WriteCData(string text)
+ {
+ this.writer.WriteCData(text);
+ }
+
+ public override void WriteCharEntity(char ch)
+ {
+ this.writer.WriteCharEntity(ch);
+ }
+
+ public override void WriteChars(char[] buffer, int index, int count)
+ {
+ this.writer.WriteChars(buffer, index, count);
+ }
+
+ public override void WriteComment(string text)
+ {
+ this.writer.WriteComment(text);
+ }
+
+ public override void WriteDocType(string name, string pubid, string sysid, string subset)
+ {
+ this.writer.WriteDocType(name, pubid, sysid, subset);
+ }
+
+ public override void WriteEndAttribute()
+ {
+ this.writer.WriteEndAttribute();
+ }
+
+ public override void WriteEndDocument()
+ {
+ this.writer.WriteEndDocument();
+ }
+
+ public override void WriteEndElement()
+ {
+ this.writer.WriteEndElement();
+ }
+
+ public override void WriteEntityRef(string name)
+ {
+ this.writer.WriteEntityRef(name);
+ }
+
+ public override void WriteFullEndElement()
+ {
+ this.writer.WriteFullEndElement();
+ }
+
+ public override void WriteProcessingInstruction(string name, string text)
+ {
+ this.writer.WriteProcessingInstruction(name, text);
+ }
+
+ public override void WriteRaw(char[] buffer, int index, int count)
+ {
+ this.writer.WriteRaw(buffer, index, count);
+ }
+
+ public override void WriteRaw(string data)
+ {
+ this.writer.WriteRaw(data);
+ }
+
+ public override void WriteStartAttribute(string prefix, string localName, string ns)
+ {
+ this.writer.WriteStartAttribute(prefix, localName, ns);
+ }
+
+ public override void WriteStartDocument()
+ {
+ this.writer.WriteStartDocument();
+ }
+
+ public override void WriteStartDocument(bool standalone)
+ {
+ this.writer.WriteStartDocument(standalone);
+ }
+
+ public override void WriteStartElement(string prefix, string localName, string ns)
+ {
+ this.writer.WriteStartElement(prefix, localName, ns);
+ }
+
+ public override void WriteString(string text)
+ {
+ this.writer.WriteString(text);
+ }
+
+ public override void WriteSurrogateCharEntity(char lowChar, char highChar)
+ {
+ this.writer.WriteSurrogateCharEntity(lowChar, highChar);
+ }
+
+ public override void WriteWhitespace(string ws)
+ {
+ this.writer.WriteWhitespace(ws);
+ }
+ }
+
+ internal static class XmlWriterExtensions
+ {
+ public static Task WriteStartElementAsync(this XmlWriter writer, string localName)
+ {
+ return writer.WriteStartElementAsync(null, localName, (string)null);
+ }
+
+ public static Task WriteStartElementAsync(this XmlWriter writer, string localName, string ns)
+ {
+ return writer.WriteStartElementAsync(null, localName, ns);
+ }
+
+ public static Task WriteElementStringAsync(this XmlWriter writer, string localName, string value)
+ {
+ return writer.WriteElementStringAsync(null, localName, null, value);
+ }
+
+ public static Task WriteElementStringAsync(this XmlWriter writer, string localName, string ns, string value)
+ {
+ return writer.WriteElementStringAsync(null, localName, ns, value);
+ }
+
+ public static Task WriteAttributeStringAsync(this XmlWriter writer, string localName, string ns, string value)
+ {
+ return writer.InternalWriteAttributeStringAsync(null, localName, ns, value);
+ }
+
+ public static Task WriteAttributeStringAsync(this XmlWriter writer, string localName, string value)
+ {
+ return writer.InternalWriteAttributeStringAsync(null, localName, null, value);
+ }
+
+ public static Task InternalWriteAttributeStringAsync(this XmlWriter writer, string prefix, string localName, string ns, string value)
+ {
+ if (writer is XmlWriterWrapper)
+ {
+ writer.WriteAttributeString(prefix, localName, ns, value);
+ return Task.CompletedTask;
+ }
+
+ return writer.WriteAttributeStringAsync(prefix, localName, ns, value);
+ }
+ }
+}
diff --git a/src/System.ServiceModel.Syndication/src/System/ServiceModel/XmlBuffer.cs b/src/System.ServiceModel.Syndication/src/System/ServiceModel/XmlBuffer.cs
new file mode 100644
index 0000000000..40560e1248
--- /dev/null
+++ b/src/System.ServiceModel.Syndication/src/System/ServiceModel/XmlBuffer.cs
@@ -0,0 +1,151 @@
+// 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.ServiceModel
+{
+ using System;
+ using System.Collections.Generic;
+ using System.IO;
+ using System.Xml;
+
+ internal class XmlBuffer
+ {
+ private List<Section> _sections;
+ private byte[] _buffer;
+ private int _offset;
+ private BufferedStream _stream;
+ private BufferState _bufferState;
+ private XmlDictionaryWriter _writer;
+ private XmlDictionaryReaderQuotas _quotas;
+
+ private enum BufferState
+ {
+ Created,
+ Writing,
+ Reading,
+ }
+
+ private struct Section
+ {
+ private int _offset;
+ private int _size;
+ private XmlDictionaryReaderQuotas _quotas;
+
+ public Section(int offset, int size, XmlDictionaryReaderQuotas quotas)
+ {
+ _offset = offset;
+ _size = size;
+ _quotas = quotas;
+ }
+
+ public int Offset
+ {
+ get { return _offset; }
+ }
+
+ public int Size
+ {
+ get { return _size; }
+ }
+
+ public XmlDictionaryReaderQuotas Quotas
+ {
+ get { return _quotas; }
+ }
+ }
+
+ public XmlBuffer(int maxBufferSize)
+ {
+ if (maxBufferSize < 0)
+ throw new ArgumentOutOfRangeException(nameof(maxBufferSize), maxBufferSize, SR.ValueMustBeNonNegative);
+
+ int initialBufferSize = Math.Min(512, maxBufferSize);
+ _stream = new BufferedStream(new MemoryStream(), initialBufferSize);
+ _sections = new List<Section>(1);
+ }
+
+ public int BufferSize
+ {
+ get
+ {
+ return _buffer.Length;
+ }
+ }
+
+ public int SectionCount
+ {
+ get { return _sections.Count; }
+ }
+
+ public XmlDictionaryWriter OpenSection(XmlDictionaryReaderQuotas quotas)
+ {
+ if (_bufferState != BufferState.Created)
+ throw CreateInvalidStateException();
+ _bufferState = BufferState.Writing;
+ _quotas = new XmlDictionaryReaderQuotas();
+ quotas.CopyTo(_quotas);
+
+ _writer = XmlDictionaryWriter.CreateBinaryWriter(_stream, null, null, false);
+
+ return _writer;
+ }
+
+ public void CloseSection()
+ {
+ if (_bufferState != BufferState.Writing)
+ throw CreateInvalidStateException();
+ _writer.Close();
+ _bufferState = BufferState.Created;
+
+ int size = (int)_stream.Length - _offset;
+ _sections.Add(new Section(_offset, size, _quotas));
+ _offset += size;
+ }
+
+ public void Close()
+ {
+ if (_bufferState != BufferState.Created)
+ throw CreateInvalidStateException();
+ _bufferState = BufferState.Reading;
+ _buffer = new byte[_stream.Length];
+ _stream.Position = 0;
+ _stream.Read(_buffer, 0, _buffer.Length);
+
+ _writer = null;
+ _stream = null;
+ }
+
+ private Exception CreateInvalidStateException()
+ {
+ return new InvalidOperationException(SR.XmlBufferInInvalidState);
+ }
+
+
+ public XmlDictionaryReader GetReader(int sectionIndex)
+ {
+ if (_bufferState != BufferState.Reading)
+ throw CreateInvalidStateException();
+ Section section = _sections[sectionIndex];
+ XmlDictionaryReader reader = XmlDictionaryReader.CreateBinaryReader(_buffer, section.Offset, section.Size, null, section.Quotas, null, null);
+
+ reader.MoveToContent();
+ return reader;
+ }
+
+ public void WriteTo(int sectionIndex, XmlWriter writer)
+ {
+ if (_bufferState != BufferState.Reading)
+ throw CreateInvalidStateException();
+ XmlDictionaryReader reader = GetReader(sectionIndex);
+ try
+ {
+ writer.WriteNode(reader, false);
+ }
+ finally
+ {
+ reader.Close();
+ }
+ }
+ }
+}
diff --git a/src/System.ServiceModel.Syndication/tests/BasicScenarioTests.cs b/src/System.ServiceModel.Syndication/tests/BasicScenarioTests.cs
new file mode 100644
index 0000000000..1462307a40
--- /dev/null
+++ b/src/System.ServiceModel.Syndication/tests/BasicScenarioTests.cs
@@ -0,0 +1,702 @@
+// 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.Text;
+using System.ServiceModel.Syndication;
+using System.Xml;
+using System.IO;
+using System.Threading.Tasks;
+using System.Threading;
+using Xunit;
+
+namespace System.ServiceModel.Syndication.Tests
+{
+ public static class BasicScenarioTests
+ {
+
+ [Fact]
+ public static void SyndicationFeed_CreateNewFeed()
+ {
+
+ string filePath = Path.GetTempFileName();
+
+ try
+ {
+ // *** SETUP *** \\
+ SyndicationFeed sf = new SyndicationFeed("First feed on .net core ever!!", "This is the first feed on .net core ever!", new Uri("https://github.com/dotnet/wcf"));
+ Assert.True(sf != null);
+
+ XmlWriter xmlw = XmlWriter.Create(filePath);
+ Rss20FeedFormatter rssf = new Rss20FeedFormatter(sf);
+
+ // *** EXECUTE *** \\
+ CancellationToken ct = new CancellationToken();
+ rssf.WriteToAsync(xmlw, ct).GetAwaiter().GetResult();
+ xmlw.Close();
+
+ // *** VALIDATE *** \\
+ Assert.True(File.Exists(filePath));
+ }
+ finally
+ {
+ // *** CLEANUP *** \\
+ File.Delete(filePath);
+ }
+ }
+
+ [Fact]
+ public static void SyndicationFeed_Load_Write_RSS_Feed()
+ {
+ string path = Path.GetTempFileName();
+
+ try
+ {
+ // *** SETUP *** \\\
+ XmlReader xmlr = XmlReader.Create(@"SimpleRssFeed.xml");
+ SyndicationFeed sf = SyndicationFeed.Load(xmlr);
+ Assert.True(sf != null);
+ CancellationToken ct = new CancellationToken();
+
+ // *** EXECUTE *** \\
+ //Write the same feed that was read.
+ XmlWriter xmlw = XmlWriter.Create(path);
+ Rss20FeedFormatter atomFeed = new Rss20FeedFormatter(sf);
+ atomFeed.WriteToAsync(xmlw, ct).GetAwaiter().GetResult();
+ xmlw.Close();
+
+ // *** VALIDATE *** \\
+ Assert.True(File.Exists(path));
+ }
+ finally
+ {
+ // *** CLEANUP *** \\
+ File.Delete(path);
+ }
+ }
+
+ [Fact]
+ public static void SyndicationFeed_Load_Write_RSS_Feed_Async()
+ {
+ string path = Path.GetTempFileName();
+
+ try
+ {
+ // *** SETUP *** \\\
+ XmlReaderSettings settingsReader = new XmlReaderSettings();
+ settingsReader.Async = true;
+ XmlReader xmlr = XmlReader.Create(@"rssSpecExample.xml",settingsReader);
+ SyndicationFeed sf;
+ Task < SyndicationFeed > rss = null;
+ CancellationToken ct = new CancellationToken();
+ rss = SyndicationFeed.LoadAsync(xmlr, ct);
+
+ Task.WhenAll(rss);
+ sf = rss.Result;
+ Assert.True(sf != null);
+
+ // *** EXECUTE *** \\
+ //Write the same feed that was read.
+ XmlWriterSettings settingsWriter = new XmlWriterSettings();
+ settingsWriter.Async = true;
+ XmlWriter xmlw = XmlWriter.Create(path,settingsWriter);
+ Rss20FeedFormatter atomFeed = new Rss20FeedFormatter(sf);
+ Task write = atomFeed.WriteToAsync(xmlw, ct);
+
+ Task.WhenAll(write);
+
+ xmlw.Close();
+
+ // *** VALIDATE *** \\
+ Assert.True(File.Exists(path));
+ }
+ finally
+ {
+ // *** CLEANUP *** \\
+ File.Delete(path);
+ }
+ }
+
+ [Fact]
+ public static void SyndicationFeed_Load_Write_Atom_Feed()
+ {
+ string path = Path.GetTempFileName();
+
+ try
+ {
+ // *** SETUP *** \\\
+ XmlReaderSettings setting = new XmlReaderSettings();
+ setting.Async = true;
+ XmlReader xmlr = XmlReader.Create(@"SimpleAtomFeed.xml",setting);
+ SyndicationFeed sf = SyndicationFeed.Load(xmlr);
+ Assert.True(sf != null);
+ CancellationToken ct = new CancellationToken();
+
+ // *** EXECUTE *** \\
+ //Write the same feed that was read.
+ XmlWriter xmlw = XmlWriter.Create(path);
+ Atom10FeedFormatter atomFeed = new Atom10FeedFormatter(sf);
+ atomFeed.WriteToAsync(xmlw,ct).GetAwaiter().GetResult();
+ xmlw.Close();
+
+ // *** VALIDATE *** \\
+ Assert.True(File.Exists(path));
+ }
+ finally
+ {
+ // *** CLEANUP *** \\
+ File.Delete(path);
+ }
+ }
+
+ [Fact]
+ public static void SyndicationFeed_Load_Write_Atom_Feed_Async()
+ {
+ string path = Path.GetTempFileName();
+
+ try
+ {
+ // *** SETUP *** \\\
+ XmlReaderSettings readerSettings = new XmlReaderSettings();
+ readerSettings.Async = true;
+ XmlReader xmlr = XmlReader.Create(@"atom_spec_example.xml", readerSettings);
+ CancellationToken ct = new CancellationToken();
+ Task<SyndicationFeed> rss = SyndicationFeed.LoadAsync(xmlr,ct);
+ SyndicationFeed sf = rss.Result;
+ Assert.True(sf != null);
+
+ // *** EXECUTE *** \\
+ //Write the same feed that was read.
+ XmlWriterSettings writerSettings = new XmlWriterSettings();
+ writerSettings.Async = true;
+
+ XmlWriter xmlw = XmlWriter.Create(path,writerSettings);
+ Atom10FeedFormatter atomFeed = new Atom10FeedFormatter(sf);
+ Task write = atomFeed.WriteToAsync(xmlw,ct);
+
+ Task.WhenAll(write);
+ xmlw.Close();
+
+ // *** VALIDATE *** \\
+ Assert.True(File.Exists(path));
+ }
+ finally
+ {
+ // *** CLEANUP *** \\
+ File.Delete(path);
+ }
+ }
+
+ [Fact]
+ public static void SyndicationFeed_Write_RSS_Atom()
+ {
+ string RssPath = Path.GetTempFileName();
+ string AtomPath = Path.GetTempFileName();
+
+ try
+ {
+ // *** SETUP *** \\
+ SyndicationFeed feed = new SyndicationFeed("Contoso News", "<div>Most recent news from Contoso</div>", new Uri("http://www.Contoso.com/news"), "123FeedID", DateTime.Now);
+ CancellationToken ct = new CancellationToken();
+
+ //Add an author
+ SyndicationPerson author = new SyndicationPerson("jerry@Contoso.com");
+ feed.Authors.Add(author);
+
+ //Create item
+ SyndicationItem item1 = new SyndicationItem("SyndicationFeed released for .net Core", "A lot of text describing the release of .net core feature", new Uri("http://Contoso.com/news/path"));
+
+ //Add item to feed
+ List<SyndicationItem> feedList = new List<SyndicationItem> { item1 };
+ feed.Items = feedList;
+ feed.ElementExtensions.Add("CustomElement", "", "asd");
+
+ //add an image
+ feed.ImageUrl = new Uri("http://2.bp.blogspot.com/-NA5Jb-64eUg/URx8CSdcj_I/AAAAAAAAAUo/eCx0irI0rq0/s1600/bg_Contoso_logo3-20120824073001907469-620x349.jpg");
+ //feed.ImageTitle = new TextSyndicationContent("Titulo loco");
+
+ feed.BaseUri = new Uri("http://mypage.com");
+
+ // Write to XML > rss
+
+ XmlWriterSettings settings = new XmlWriterSettings();
+ settings.Async = true;
+
+ XmlWriter xmlwRss = XmlWriter.Create(RssPath,settings);
+ Rss20FeedFormatter rssff = new Rss20FeedFormatter(feed);
+
+ // Write to XML > atom
+
+ XmlWriter xmlwAtom = XmlWriter.Create(AtomPath);
+ Atom10FeedFormatter atomf = new Atom10FeedFormatter(feed);
+
+
+ // *** EXECUTE *** \\
+ Task rss = rssff.WriteToAsync(xmlwRss,ct);
+ Task.WaitAll(rss);
+
+ xmlwRss.Close();
+
+ atomf.WriteToAsync(xmlwAtom,ct).GetAwaiter().GetResult(); ;
+ xmlwAtom.Close();
+
+ // *** ASSERT *** \\
+ Assert.True(File.Exists(RssPath));
+ Assert.True(File.Exists(AtomPath));
+ }
+ finally
+ {
+ // *** CLEANUP *** \\
+ File.Delete(RssPath);
+ File.Delete(AtomPath);
+ }
+ }
+
+ [Fact]
+ public static void SyndicationFeed_RSS20_Load_customImageDataInFeed()
+ {
+ // *** SETUP *** \\
+ XmlReader reader = XmlReader.Create(@"RssFeedWithCustomImageName.xml");
+
+ // *** EXECUTE *** \\
+ SyndicationFeed sf = SyndicationFeed.Load(reader);
+
+ // *** ASSERT *** \\
+ Assert.True("The title is not the same to the original one" == sf.ImageTitle.Text);
+ Assert.True(sf.ImageLink.AbsoluteUri != sf.Links[0].GetAbsoluteUri().AbsoluteUri);
+
+ // *** CLEANUP *** \\
+ reader.Close();
+ }
+
+ [Fact]
+ public static void SyndicationFeed_RSS20_Write_customImageDataInFeed()
+ {
+ // *** SETUP *** \\
+ SyndicationFeed sf = new SyndicationFeed();
+ string feedTitle = "Feed title";
+ string imageTitle = "Image title";
+ string resultPath = Path.GetTempFileName();
+
+ sf.Title = new TextSyndicationContent(feedTitle);
+ sf.ImageTitle = new TextSyndicationContent(imageTitle);
+ sf.ImageLink = new Uri("http://myimage.com");
+ sf.ImageUrl = new Uri("http://www.myownimagesrc.com");
+ XmlWriter writer = XmlWriter.Create(resultPath);
+ Rss20FeedFormatter rssff = sf.GetRss20Formatter();
+ CancellationToken ct = new CancellationToken();
+
+ try
+ {
+ // *** EXECUTE *** \\
+ rssff.WriteToAsync(writer,ct).GetAwaiter().GetResult(); ;
+ writer.Close();
+
+ // *** ASSERT *** \\
+ Assert.True(File.Exists(resultPath));
+
+ }
+ finally
+ {
+ // *** CLEANUP *** \\
+ File.Delete(resultPath);
+ }
+ }
+
+ [Fact]
+ public static async Task SyndicationFeed_LoadAsync_Rss() {
+
+ // *** SETUP *** \\
+ XmlReaderSettings setting = new XmlReaderSettings();
+ setting.Async = true;
+ XmlReader reader = null;
+ Task<SyndicationFeed> rss = null;
+ CancellationToken ct = new CancellationToken();
+
+ try
+ {
+ // *** EXECUTE *** \\
+ reader = XmlReader.Create(@"rssSpecExample.xml", setting);
+ rss = SyndicationFeed.LoadAsync(reader,ct);
+ await Task.WhenAll(rss);
+
+ // *** ASSERT *** \\
+ }
+ finally
+ {
+ // *** CLEANUP *** \\
+ Assert.True(rss.Result.Items != null);
+ reader.Close();
+ }
+ }
+
+ [Fact]
+ public static async Task SyndicationFeed_LoadAsync_Atom()
+ {
+
+ // *** SETUP *** \\
+ XmlReaderSettings setting = new XmlReaderSettings();
+ setting.Async = true;
+ XmlReader reader = null;
+ CancellationToken ct = new CancellationToken();
+
+ try
+ {
+ reader = XmlReader.Create(@"atom_spec_example.xml", setting);
+ // *** EXECUTE *** \\
+ Task<SyndicationFeed> atom = SyndicationFeed.LoadAsync(reader,ct);
+ await Task.WhenAll(atom);
+ // *** ASSERT *** \\
+ Assert.True(atom.Result.Items != null);
+ }
+ finally
+ {
+ // *** CLEANUP *** \\
+ reader.Close();
+ }
+ }
+
+ [Fact]
+ public static void SyndicationFeed_Rss_TestDisjointItems()
+ {
+ // *** SETUP *** \\
+ XmlReader reader = XmlReader.Create(@"RssDisjointItems.xml");
+
+ try
+ {
+ // *** EXECUTE *** \\
+ SyndicationFeed sf = SyndicationFeed.Load(reader);
+
+ // *** ASSERT *** \\
+ int count = 0;
+ foreach (var item in sf.Items)
+ {
+ count++;
+ }
+
+ Assert.True(count == 2);
+ }
+ catch
+ {
+ // *** CLEANUP *** \\
+ reader.Close();
+ }
+ }
+
+
+ [Fact]
+ public static void SyndicationFeed_Atom_TestDisjointItems()
+ {
+ // *** SETUP *** \\
+ XmlReader reader = XmlReader.Create(@"AtomDisjointItems.xml");
+
+ try
+ {
+ // *** EXECUTE *** \\
+ SyndicationFeed sf = SyndicationFeed.Load(reader);
+
+ // *** ASSERT *** \\
+ int count = 0;
+ foreach (var item in sf.Items)
+ {
+ count++;
+ }
+
+ Assert.True(count == 2);
+ }
+ finally
+ {
+ // *** CLEANUP *** \\
+ reader.Close();
+ }
+ }
+
+ [Fact]
+ public static async Task SyndicationFeed_RSS_Optional_Documentation()
+ {
+ // *** SETUP *** \\
+ XmlReaderSettings setting = new XmlReaderSettings();
+ setting.Async = true;
+ XmlReader reader = null;
+ Task<SyndicationFeed> rss = null;
+ CancellationToken ct = new CancellationToken();
+
+ try
+ {
+ // *** EXECUTE *** \\
+ reader = XmlReader.Create(@"rssSpecExample.xml", setting);
+ rss = SyndicationFeed.LoadAsync(reader,ct);
+ await Task.WhenAll(rss);
+
+ // *** ASSERT *** \\
+ Assert.True(rss.Result.Documentation.GetAbsoluteUri().ToString() == "http://blogs.law.harvard.edu/tech/rss");
+ }
+ finally
+ {
+ // *** CLEANUP *** \\
+ Assert.True(rss.Result.Items != null);
+ reader.Close();
+ }
+ }
+
+ [Fact]
+ public static async Task SyndicationFeed_RSS_Optional_TimeToLiveTag()
+ {
+ // *** SETUP *** \\
+ XmlReaderSettings setting = new XmlReaderSettings();
+ setting.Async = true;
+ XmlReader reader = null;
+ Task<SyndicationFeed> rss = null;
+ CancellationToken ct = new CancellationToken();
+
+ try
+ {
+ // *** EXECUTE *** \\
+ reader = XmlReader.Create(@"rssSpecExample.xml", setting);
+ rss = SyndicationFeed.LoadAsync(reader, ct);
+ await Task.WhenAll(rss);
+
+ // *** ASSERT *** \\
+ Assert.True(rss.Result.TimeToLive == 60);
+ }
+ finally
+ {
+ // *** CLEANUP *** \\
+ Assert.True(rss.Result.Items != null);
+ reader.Close();
+ }
+ }
+
+ [Fact]
+ public static async Task SyndicationFeed_RSS_Optional_SkipHours()
+ {
+ // *** SETUP *** \\
+ XmlReaderSettings setting = new XmlReaderSettings();
+ setting.Async = true;
+ XmlReader reader = null;
+ Task<SyndicationFeed> rss = null;
+ CancellationToken ct = new CancellationToken();
+
+ try
+ {
+ // *** EXECUTE *** \\
+ reader = XmlReader.Create(@"rssSpecExample.xml", setting);
+ rss = SyndicationFeed.LoadAsync(reader, ct);
+ await Task.WhenAll(rss);
+
+ // *** ASSERT *** \\
+ Assert.True(rss.Result.SkipHours.Count == 3);
+ }
+ finally
+ {
+ // *** CLEANUP *** \\
+ Assert.True(rss.Result.Items != null);
+ reader.Close();
+ }
+ }
+
+ [Fact]
+ public static async Task SyndicationFeed_RSS_Optional_SkipDays()
+ {
+ // *** SETUP *** \\
+ XmlReaderSettings setting = new XmlReaderSettings();
+ setting.Async = true;
+ XmlReader reader = null;
+ Task<SyndicationFeed> rss = null;
+ CancellationToken ct = new CancellationToken();
+
+ try
+ {
+ // *** EXECUTE *** \\
+ reader = XmlReader.Create(@"rssSpecExample.xml", setting);
+ rss = SyndicationFeed.LoadAsync(reader, ct);
+ await Task.WhenAll(rss);
+
+ // *** ASSERT *** \\
+ Assert.True(rss.Result.SkipDays.Count == 2);
+ Assert.True(rss.Result.SkipDays[0] == "Saturday");
+ Assert.True(rss.Result.SkipDays[1] == "Sunday");
+ }
+ finally
+ {
+ // *** CLEANUP *** \\
+ Assert.True(rss.Result.Items != null);
+ reader.Close();
+ }
+ }
+
+ [Fact]
+ public static async Task SyndicationFeed_RSS_Optional_TextInput()
+ {
+ // *** SETUP *** \\
+ XmlReaderSettings setting = new XmlReaderSettings();
+ setting.Async = true;
+ XmlReader reader = null;
+ Task<SyndicationFeed> rss = null;
+ CancellationToken ct = new CancellationToken();
+
+ try
+ {
+ // *** EXECUTE *** \\
+ reader = XmlReader.Create(@"rssSpecExample.xml", setting);
+ rss = SyndicationFeed.LoadAsync(reader, ct);
+ await Task.WhenAll(rss);
+
+ // *** ASSERT *** \\
+ Assert.True(rss.Result.TextInput.Description == "Search Online");
+ Assert.True(rss.Result.TextInput.title == "Search");
+ Assert.True(rss.Result.TextInput.name == "input Name");
+ Assert.True(rss.Result.TextInput.link.GetAbsoluteUri().ToString() == "http://www.contoso.no/search?");
+ }
+ finally
+ {
+ // *** CLEANUP *** \\
+ Assert.True(rss.Result.Items != null);
+ reader.Close();
+ }
+ }
+
+ [Fact]
+ public static async Task SyndicationFeed__Atom_Optional_Icon()
+ {
+
+ // *** SETUP *** \\
+ XmlReaderSettings setting = new XmlReaderSettings();
+ setting.Async = true;
+ XmlReader reader = null;
+ CancellationToken ct = new CancellationToken();
+
+ try
+ {
+ reader = XmlReader.Create(@"atom_spec_example.xml", setting);
+ // *** EXECUTE *** \\
+ Task<SyndicationFeed> atom = SyndicationFeed.LoadAsync(reader, ct);
+ await Task.WhenAll(atom);
+ // *** ASSERT *** \\
+ Assert.True(atom.Result.IconImage.AbsoluteUri == "https://avatars0.githubusercontent.com/u/9141961");
+ }
+ finally
+ {
+ // *** CLEANUP *** \\
+ reader.Close();
+ }
+ }
+
+ [Fact]
+ public static void SyndicationFeed_Rss_TestCustomParsing()
+ {
+ // *** SETUP *** \\
+ Rss20FeedFormatter rssformatter = new Rss20FeedFormatter();
+
+ rssformatter.StringParser = (val, name, ns) =>
+ {
+ Assert.False(string.IsNullOrEmpty(name));
+ switch (name)
+ {
+ case "ttl":
+ case "hour":
+ return "5";
+ case "link":
+ case "image":
+ case "url":
+ return "http://customparsedlink.com";
+ case "title":
+ return "new title";
+ default:
+ return "Custom Text";
+ }
+ };
+
+ XmlReader reader = XmlReader.Create(@"rssSpecExample.xml");
+ CancellationToken ct = new CancellationToken();
+
+ // *** EXECUTE *** \\
+ Task<SyndicationFeed> task = SyndicationFeed.LoadAsync(reader,rssformatter,ct);
+ Task.WhenAll(task);
+ SyndicationFeed res = task.Result;
+
+ // *** ASSERT *** \\
+ Assert.True(res.Title.Text == "new title");
+ foreach(int hour in res.SkipHours)
+ {
+ Assert.True(hour == 5);
+ }
+ }
+
+ [Fact]
+ public static void SyndicationFeed_Atom_TestCustomParsing()
+ {
+ // *** SETUP *** \\
+ Atom10FeedFormatter atomformatter = new Atom10FeedFormatter();
+
+ atomformatter.stringParser = (val, name, ns) =>
+ {
+ Assert.False(string.IsNullOrEmpty(name));
+ switch (name)
+ {
+ case Atom10Constants.IdTag:
+ return "No id!";
+ case Atom10Constants.NameTag:
+ return "new name";
+ case Atom10Constants.TitleTag:
+ return "new title";
+ default:
+ return "Custom Text";
+ }
+ };
+
+ XmlReader reader = XmlReader.Create(@"atom_spec_example.xml");
+ CancellationToken ct = new CancellationToken();
+
+ // *** EXECUTE *** \\
+ Task<SyndicationFeed> task = SyndicationFeed.LoadAsync(reader, atomformatter, ct);
+ Task.WhenAll(task);
+ SyndicationFeed res = task.Result;
+
+ // *** ASSERT *** \\
+ Assert.True(res.Id == "No id!");
+ Assert.True(res.Title.Text == "new title");
+ }
+
+ [Fact]
+ public static void SyndicationFeed_Rss_TestWrongSkipDays()
+ {
+ // *** SETUP *** \\
+ Rss20FeedFormatter rssformatter = new Rss20FeedFormatter();
+
+ XmlReader reader = XmlReader.Create(@"rssSpecExampleWrongSkipDays.xml");
+ CancellationToken ct = new CancellationToken();
+
+ // *** EXECUTE *** \\
+ Task<SyndicationFeed> task = SyndicationFeed.LoadAsync(reader,ct);
+ Task.WhenAll(task);
+ SyndicationFeed res = task.Result;
+
+ // *** ASSERT *** \\
+ Assert.True(res.SkipDays.Count == 2);
+ Assert.True(res.SkipDays[0] == "Saturday");
+ Assert.True(res.SkipDays[1] == "Sunday");
+ }
+
+ [Fact]
+ public static void SyndicationFeed_Rss_WrongDateFormat()
+ {
+ // *** SETUP *** \\
+ Rss20FeedFormatter rssformatter = new Rss20FeedFormatter();
+
+ XmlReader reader = XmlReader.Create(@"rssSpecExampleWrongDateFormat.xml");
+ CancellationToken ct = new CancellationToken();
+
+ // *** EXECUTE *** \\
+ Task<SyndicationFeed> task = SyndicationFeed.LoadAsync(reader, ct);
+ Task.WhenAll(task);
+ SyndicationFeed res = task.Result;
+
+ // *** ASSERT *** \\
+ Assert.True(!res.LastUpdatedTime.Equals(new DateTimeOffset()));
+ }
+
+ }
+}
diff --git a/src/System.ServiceModel.Syndication/tests/Configurations.props b/src/System.ServiceModel.Syndication/tests/Configurations.props
new file mode 100644
index 0000000000..c398e42e89
--- /dev/null
+++ b/src/System.ServiceModel.Syndication/tests/Configurations.props
@@ -0,0 +1,8 @@
+<?xml version="1.0" encoding="utf-8"?>
+<Project ToolsVersion="14.0" DefaultTargets="Build" xmlns="http://schemas.microsoft.com/developer/msbuild/2003">
+ <PropertyGroup>
+ <BuildConfigurations>
+ netstandard;
+ </BuildConfigurations>
+ </PropertyGroup>
+</Project> \ No newline at end of file
diff --git a/src/System.ServiceModel.Syndication/tests/System.ServiceModel.Syndication.Tests.csproj b/src/System.ServiceModel.Syndication/tests/System.ServiceModel.Syndication.Tests.csproj
new file mode 100644
index 0000000000..66230d199f
--- /dev/null
+++ b/src/System.ServiceModel.Syndication/tests/System.ServiceModel.Syndication.Tests.csproj
@@ -0,0 +1,25 @@
+<?xml version="1.0" encoding="utf-8"?>
+<Project ToolsVersion="14.0" xmlns="http://schemas.microsoft.com/developer/msbuild/2003" DefaultTargets="Build">
+ <Import Project="$([MSBuild]::GetDirectoryNameOfFileAbove($(MSBuildThisFileDirectory), dir.props))\dir.props" />
+ <PropertyGroup>
+ <ProjectGuid>{A622B2C0-DD74-4218-9CF0-F9B2E52F4E91}</ProjectGuid>
+ </PropertyGroup>
+ <PropertyGroup Condition="'$(Configuration)|$(Platform)'=='netstandard-Debug|AnyCPU'" />
+ <PropertyGroup Condition="'$(Configuration)|$(Platform)'=='netstandard-Release|AnyCPU'" />
+ <ItemGroup>
+ <Compile Include="$(MsBuildThisFileDirectory)\**\*.cs" />
+ </ItemGroup>
+ <ItemGroup>
+ <Content Include="$(MsBuildThisFileDirectory)\TestFeeds\*.xml">
+ <CopyToOutputDirectory>Always</CopyToOutputDirectory>
+ </Content>
+ </ItemGroup>
+ <ItemGroup>
+ <ReferenceFromRuntime Include="System.ServiceModel.Syndication">
+ <!-- Copy this to our test output directory and run from there.
+ This is required so that we can stage the application with a custom runtimeconfig that lets it run on the test shared framework. -->
+ <Private>true</Private>
+ </ReferenceFromRuntime>
+ </ItemGroup>
+ <Import Project="$([MSBuild]::GetDirectoryNameOfFileAbove($(MSBuildThisFileDirectory), dir.targets))\dir.targets" />
+</Project>
diff --git a/src/System.ServiceModel.Syndication/tests/TestFeeds/AtomDisjointItems.xml b/src/System.ServiceModel.Syndication/tests/TestFeeds/AtomDisjointItems.xml
new file mode 100644
index 0000000000..00c432b730
--- /dev/null
+++ b/src/System.ServiceModel.Syndication/tests/TestFeeds/AtomDisjointItems.xml
@@ -0,0 +1,81 @@
+<?xml version="1.0" encoding="utf-8"?>
+<feed xmlns="http://www.w3.org/2005/Atom">
+ <title type="text">dive into mark</title>
+ <subtitle type="html">
+ A &lt;em&gt;lot&lt;/em&gt; of effort
+ went into making this effortless
+ </subtitle>
+ <updated>2005-07-31T12:29:29Z</updated>
+ <id>tag:example.org,2003:3</id>
+ <link rel="alternate" type="text/html"
+ hreflang="en" href="http://example.org/"/>
+ <link rel="self" type="application/atom+xml"
+ href="http://example.org/feed.atom"/>
+ <rights>Copyright (c) 2003, Mark Pilgrim</rights>
+ <generator uri="http://www.example.com/" version="1.0">
+ Example Toolkit
+ </generator>
+ <entry>
+ <title>Atom draft-07 snapshot</title>
+ <link rel="alternate" type="text/html"
+ href="http://example.org/2005/04/02/atom"/>
+ <link rel="enclosure" type="audio/mpeg" length="1337"
+ href="http://example.org/audio/ph34r_my_podcast.mp3"/>
+ <id>tag:example.org,2003:3.2397</id>
+ <updated>2005-07-31T12:29:29Z</updated>
+ <published>2003-12-13T08:29:29-04:00</published>
+ <author>
+ <name>Mark Pilgrim</name>
+ <uri>http://example.org/</uri>
+ <email>f8dy@example.com</email>
+ </author>
+ <contributor>
+ <name>Sam Ruby</name>
+ </contributor>
+ <contributor>
+ <name>Joe Gregorio</name>
+ </contributor>
+ <content type="xhtml" xml:lang="en"
+ xml:base="http://diveintomark.org/">
+ <div xmlns="http://www.w3.org/1999/xhtml">
+ <p>
+ <i>[Update: The Atom draft is finished.]</i>
+ </p>
+ </div>
+ </content>
+ </entry>
+
+ <author>
+ <name>Jerry</name>
+ </author>
+
+ <entry>
+ <title>Atom draft-07 snapshot</title>
+ <link rel="alternate" type="text/html"
+ href="http://example.org/2005/04/02/atom"/>
+ <link rel="enclosure" type="audio/mpeg" length="1337"
+ href="http://example.org/audio/ph34r_my_podcast.mp3"/>
+ <id>tag:example.org,2003:3.2397</id>
+ <updated>2005-07-31T12:29:29Z</updated>
+ <published>2003-12-13T08:29:29-04:00</published>
+ <author>
+ <name>Mark Pilgrim</name>
+ <uri>http://example.org/</uri>
+ <email>f8dy@example.com</email>
+ </author>
+ <contributor>
+ <name>Sam Ruby</name>
+ </contributor>
+ <contributor>
+ <name>Joe Gregorio</name>
+ </contributor>
+ <content type="xhtml" xml:lang="en"
+ xml:base="http://diveintomark.org/">
+ <div xmlns="http://www.w3.org/1999/xhtml">
+ <p>
+ <i>[Update: The Atom draft is finished.]</i>
+ </p>
+ </div>
+ </content>
+ </entry>
+</feed>
diff --git a/src/System.ServiceModel.Syndication/tests/TestFeeds/RssDisjointItems.xml b/src/System.ServiceModel.Syndication/tests/TestFeeds/RssDisjointItems.xml
new file mode 100644
index 0000000000..ae78e43fa4
--- /dev/null
+++ b/src/System.ServiceModel.Syndication/tests/TestFeeds/RssDisjointItems.xml
@@ -0,0 +1,38 @@
+<?xml version="1.0" encoding="utf-8"?>
+<rss xmlns:a10="http://www.w3.org/2005/Atom" version="2.0">
+ <channel xml:base="http://mypage.com/">
+ <title>Contoso News</title>
+ <link>http://www.Contoso.com/news</link>
+ <description>&lt;div&gt;Most recent news from Contoso&lt;/div&gt;</description>
+ <language>en-us</language>
+ <pubDate>Mon, 19 Jun 2017 11:52:39 -0700</pubDate>
+ <managingEditor>jerry@Contoso.com</managingEditor>
+ <category>Newspaperts</category>
+ <generator>SyndicationFeed Feature</generator>
+
+ <lastBuildDate>Mon, 19 Jun 2017 11:52:39 -0700</lastBuildDate>
+ <image>
+ <url>http://2.bp.blogspot.com/-NA5Jb-64eUg/URx8CSdcj_I/AAAAAAAAAUo/eCx0irI0rq0/s1600/bg_Contoso_logo3-20120824073001907469-620x349.jpg</url>
+ <title>The title is not the same to the original one</title>
+ <link>http://www.contoso.com/notnews</link>
+ </image>
+ <a10:id>123FeedID</a10:id>
+ <item>
+ <link>http://Contoso.com/news/path</link>
+ <title>SyndicationFeed released for .net Core</title>
+ <description>A lot of text describing the release of .net core feature</description>
+ <author>Contoso Item author</author>
+ <category>Item Category</category>
+ <pubdate>Mon, 19 Jun 2017 11:52:39 -0700</pubdate>
+ </item>
+ <CustomElement>asd</CustomElement>
+ <item>
+ <link>http://Contoso.com/news/path</link>
+ <title>SyndicationFeed released for .net Core</title>
+ <description>A lot of text describing the release of .net core feature</description>
+ <author>Contoso Item author</author>
+ <category>Item Category</category>
+ <pubdate>Mon, 19 Jun 2017 11:52:39 -0700</pubdate>
+ </item>
+ </channel>
+</rss> \ No newline at end of file
diff --git a/src/System.ServiceModel.Syndication/tests/TestFeeds/RssFeedWithCustomImageName.xml b/src/System.ServiceModel.Syndication/tests/TestFeeds/RssFeedWithCustomImageName.xml
new file mode 100644
index 0000000000..4b5b96f529
--- /dev/null
+++ b/src/System.ServiceModel.Syndication/tests/TestFeeds/RssFeedWithCustomImageName.xml
@@ -0,0 +1,30 @@
+<?xml version="1.0" encoding="utf-8"?>
+<rss xmlns:a10="http://www.w3.org/2005/Atom" version="2.0">
+ <channel xml:base="http://mypage.com/">
+ <title>Contoso News</title>
+ <link>http://www.Contoso.com/news</link>
+ <description>&lt;div&gt;Most recent news from Contoso&lt;/div&gt;</description>
+ <language>en-us</language>
+ <pubDate>Mon, 19 Jun 2017 11:52:39 -0700</pubDate>
+ <managingEditor>jerry@Contoso.com</managingEditor>
+ <category>Newspaperts</category>
+ <generator>SyndicationFeed Feature</generator>
+
+ <lastBuildDate>Mon, 19 Jun 2017 11:52:39 -0700</lastBuildDate>
+ <image>
+ <url>http://2.bp.blogspot.com/-NA5Jb-64eUg/URx8CSdcj_I/AAAAAAAAAUo/eCx0irI0rq0/s1600/bg_Contoso_logo3-20120824073001907469-620x349.jpg</url>
+ <title>The title is not the same to the original one</title>
+ <link>http://www.contoso.com/notnews</link>
+ </image>
+ <a10:id>123FeedID</a10:id>
+ <CustomElement>asd</CustomElement>
+ <item>
+ <link>http://Contoso.com/news/path</link>
+ <title>SyndicationFeed released for .net Core</title>
+ <description>A lot of text describing the release of .net core feature</description>
+ <author>Contoso Item author</author>
+ <category>Item Category</category>
+ <pubdate>Mon, 19 Jun 2017 11:52:39 -0700</pubdate>
+ </item>
+ </channel>
+</rss> \ No newline at end of file
diff --git a/src/System.ServiceModel.Syndication/tests/TestFeeds/SimpleAtomFeed.xml b/src/System.ServiceModel.Syndication/tests/TestFeeds/SimpleAtomFeed.xml
new file mode 100644
index 0000000000..824f2ba47b
--- /dev/null
+++ b/src/System.ServiceModel.Syndication/tests/TestFeeds/SimpleAtomFeed.xml
@@ -0,0 +1,20 @@
+<?xml version="1.0" encoding="utf-8"?>
+<feed xml:base="http://mypage.com/" xmlns="http://www.w3.org/2005/Atom">
+ <title type="text">Contoso News</title>
+ <subtitle type="text">&lt;div&gt;Most recent news from Contoso&lt;/div&gt;</subtitle>
+ <id>123FeedID</id>
+ <updated>2017-06-26T14:41:43-07:00</updated>
+ <logo>http://2.bp.blogspot.com/-NA5Jb-64eUg/URx8CSdcj_I/AAAAAAAAAUo/eCx0irI0rq0/s1600/bg_Contoso_logo3-20120824073001907469-620x349.jpg</logo>
+ <author>
+ <email>jerry@Contoso.com</email>
+ </author>
+ <link rel="alternate" href="http://www.contoso.com/news" />
+ <CustomElement xmlns="">asd</CustomElement>
+ <entry>
+ <id>uuid:71d91f91-f5f9-4175-9065-4b7cb357fc4d;id=1</id>
+ <title type="text">SyndicationFeed released for .net Core</title>
+ <updated>2017-06-26T21:41:43Z</updated>
+ <link rel="alternate" href="http://contoso.com/news/path" />
+ <content type="text">A lot of text describing the release of .net core feature</content>
+ </entry>
+</feed> \ No newline at end of file
diff --git a/src/System.ServiceModel.Syndication/tests/TestFeeds/SimpleRssFeed.xml b/src/System.ServiceModel.Syndication/tests/TestFeeds/SimpleRssFeed.xml
new file mode 100644
index 0000000000..1b69a3fd7b
--- /dev/null
+++ b/src/System.ServiceModel.Syndication/tests/TestFeeds/SimpleRssFeed.xml
@@ -0,0 +1,29 @@
+<?xml version="1.0" encoding="utf-8"?>
+<rss xmlns:a10="http://www.w3.org/2005/Atom" version="2.0">
+ <channel xml:base="http://mypage.com/">
+ <title>Contoso News</title>
+ <link>http://www.Contoso.com/news</link>
+ <description>&lt;div&gt;Most recent news from Contoso&lt;/div&gt;</description>
+ <language>en-us</language>
+ <pubDate>Mon, 19 Jun 2017 11:52:39 -0700</pubDate>
+ <managingEditor>jerry@Contoso.com</managingEditor>
+ <category>Newspaperts</category>
+ <generator>SyndicationFeed Feature</generator>
+ <lastBuildDate>Mon, 19 Jun 2017 11:52:39 -0700</lastBuildDate>
+ <image>
+ <url>http://2.bp.blogspot.com/-NA5Jb-64eUg/URx8CSdcj_I/AAAAAAAAAUo/eCx0irI0rq0/s1600/bg_Contoso_logo3-20120824073001907469-620x349.jpg</url>
+ <title>The title is not the same to the original one</title>
+ <link>http://www.contoso.com/notnews</link>
+ </image>
+ <a10:id>123FeedID</a10:id>
+ <CustomElement>asd</CustomElement>
+ <item>
+ <link>http://Contoso.com/news/path</link>
+ <title>SyndicationFeed released for .net Core</title>
+ <description>A lot of text describing the release of .net core feature</description>
+ <author>Contoso Item author</author>
+ <category>Item Category</category>
+ <pubdate>Mon, 19 Jun 2017 11:52:39 -0700</pubdate>
+ </item>
+ </channel>
+</rss> \ No newline at end of file
diff --git a/src/System.ServiceModel.Syndication/tests/TestFeeds/atom_spec_example.xml b/src/System.ServiceModel.Syndication/tests/TestFeeds/atom_spec_example.xml
new file mode 100644
index 0000000000..4efadc6568
--- /dev/null
+++ b/src/System.ServiceModel.Syndication/tests/TestFeeds/atom_spec_example.xml
@@ -0,0 +1,48 @@
+<?xml version="1.0" encoding="utf-8"?>
+<feed xmlns="http://www.w3.org/2005/Atom">
+ <title type="text">dive into mark</title>
+ <icon>https://avatars0.githubusercontent.com/u/9141961</icon>
+ <subtitle type="html">
+ A &lt;em&gt;lot&lt;/em&gt; of effort
+ went into making this effortless
+ </subtitle>
+ <updated>2005-07-31T12:29:29Z</updated>
+ <id>tag:example.org,2003:3</id>
+ <link rel="alternate" type="text/html"
+ hreflang="en" href="http://example.org/"/>
+ <link rel="self" type="application/atom+xml"
+ href="http://example.org/feed.atom"/>
+ <rights>Copyright (c) 2003, Mark Pilgrim</rights>
+ <generator uri="http://www.example.com/" version="1.0">
+ Example Toolkit
+ </generator>
+ <entry>
+ <title>Atom draft-07 snapshot</title>
+ <link rel="alternate" type="text/html"
+ href="http://example.org/2005/04/02/atom"/>
+ <link rel="enclosure" type="audio/mpeg" length="1337"
+ href="http://example.org/audio/ph34r_my_podcast.mp3"/>
+ <id>tag:example.org,2003:3.2397</id>
+ <updated>2005-07-31T12:29:29Z</updated>
+ <published>2003-12-13T08:29:29-04:00</published>
+ <author>
+ <name>Mark Pilgrim</name>
+ <uri>http://example.org/</uri>
+ <email>f8dy@example.com</email>
+ </author>
+ <contributor>
+ <name>Sam Ruby</name>
+ </contributor>
+ <contributor>
+ <name>Joe Gregorio</name>
+ </contributor>
+ <content type="xhtml" xml:lang="en"
+ xml:base="http://diveintomark.org/">
+ <div xmlns="http://www.w3.org/1999/xhtml">
+ <p>
+ <i>[Update: The Atom draft is finished.]</i>
+ </p>
+ </div>
+ </content>
+ </entry>
+</feed>
diff --git a/src/System.ServiceModel.Syndication/tests/TestFeeds/example_feed_xml_atom.xml b/src/System.ServiceModel.Syndication/tests/TestFeeds/example_feed_xml_atom.xml
new file mode 100644
index 0000000000..8c412bf2d8
--- /dev/null
+++ b/src/System.ServiceModel.Syndication/tests/TestFeeds/example_feed_xml_atom.xml
@@ -0,0 +1,187 @@
+<?xml version="1.0"?>
+<feed xmlns="http://www.w3.org/2005/Atom" xmlns:g="http://base.google.com/ns/1.0">
+ <title>Example - Online Store</title>
+ <link rel="self" href="http://www.example.com"/>
+ <updated>2011-07-11T12:00:00Z</updated>
+
+ <!-- First example shows what attributes are required and recommended for items that are not in the apparel category -->
+ <entry>
+ <!-- The following attributes are always required -->
+ <g:id>TV_123456</g:id>
+ <g:title>LG 22LB4510 - 22" LED TV - 1080p (FullHD)</g:title>
+ <g:description>Attractively styled and boasting stunning picture quality, the LG 22LB4510 - 22&quot; LED TV - 1080p (FullHD) is an excellent television/monitor. The LG 22LB4510 - 22&quot; LED TV - 1080p (FullHD) sports a widescreen 1080p panel, perfect for watching movies in their original format, whilst also providing plenty of working space for your other applications.</g:description>
+ <g:link>http://www.example.com/electronics/tv/22LB4510.html</g:link>
+ <g:image_link>http://images.example.com/TV_123456.png</g:image_link>
+ <g:condition>used</g:condition>
+ <g:availability>in stock</g:availability>
+ <g:price>159.00 USD</g:price>
+ <g:shipping>
+ <g:country>US</g:country>
+ <g:service>Standard</g:service>
+ <g:price>14.95 USD</g:price>
+ </g:shipping>
+
+ <!-- 2 of the following 3 attributes are required fot this item according to the Unique Product Identifier Rules -->
+ <g:gtin>71919219405200</g:gtin>
+ <g:brand>LG</g:brand>
+ <g:mpn>22LB4510/US</g:mpn>
+
+ <!-- The following attributes are not required for this item, but supplying them is recommended -->
+ <g:google_product_category>Electronics > Video > Televisions > Flat Panel Televisions</g:google_product_category>
+ <g:product_type>Consumer Electronics &gt; TVs &gt; Flat Panel TVs</g:product_type>
+ </entry>
+
+ <!-- Second example demonstrates the use of CDATA sections instead of entities to deal with special characters. Note that CDATA sections can be used for any attribute -->
+ <entry>
+ <!-- The following attributes are always required -->
+ <g:id>DVD-0564738</g:id>
+ <g:title><![CDATA[Merlin: Series 3 - Volume 2 - 3 DVD Box set]]></g:title>
+ <g:description><![CDATA[Episodes 7-13 from the third series of the BBC fantasy drama set in the mythical city of Camelot, telling the tale of the relationship between the young King Arthur (Bradley James) & Merlin (Colin Morgan), the wise sorcerer who guides him to power and beyond. Episodes are: 'The Castle of Fyrien', 'The Eye of the Phoenix', 'Love in the Time of Dragons', 'Queen of Hearts', 'The Sorcerer's Shadow', 'The Coming of Arthur: Part 1' & 'The Coming of Arthur: Part 2']]></g:description>
+ <g:link><![CDATA[http://www.example.com/media/dvd/?sku=384616&src=gshopping&lang=en]]></g:link>
+ <g:image_link><![CDATA[http://images.example.com/DVD-0564738?size=large&format=PNG]]></g:image_link>
+ <g:condition>new</g:condition>
+ <g:availability>in stock</g:availability>
+ <g:price>11.99 USD</g:price>
+ <g:shipping>
+ <g:country>US</g:country>
+ <g:service>Express Mail</g:service>
+ <g:price>3.80 USD</g:price>
+ </g:shipping>
+
+ <!-- 2 out of the 3 unique product identifer attributes are required for this item -->
+ <g:gtin>88392916560500</g:gtin>
+ <g:brand>BBC</g:brand>
+
+ <!-- The following attribute is required because this item is in the 'Media' category -->
+ <g:google_product_category><![CDATA[Media > DVDs & Videos]]></g:google_product_category>
+
+ <!-- The following attributes are not required for this item, but supplying them is recommended if applicable -->
+ <g:product_type><![CDATA[DVDs & Movies > TV Series > Fantasy Drama]]></g:product_type>
+ </entry>
+
+ <!-- Third example shows how to include multiple images and shipping types-->
+ <entry>
+ <!-- The following attributes are always required -->
+ <g:id>PFM654321</g:id>
+ <g:title>Dior Capture XP Ultimate Wrinkle Correction Creme 1.7 oz</g:title>
+ <g:description>Dior Capture XP Ultimate Wrinkle Correction Creme 1.7 oz reinvents anti-wrinkle care by protecting and relaunching skin cell activity to encourage faster, healthier regeneration.</g:description>
+ <g:link>http://www.example.com/perfumes/product?Dior%20Capture%20R6080%20XP</g:link>
+ <g:image_link>http://images.example.com/PFM654321_1.jpg</g:image_link>
+ <g:condition>new</g:condition>
+ <g:availability>in stock</g:availability>
+ <g:price>99 USD</g:price>
+ <g:shipping>
+ <g:country>US</g:country>
+ <g:service>Standard Rate</g:service>
+ <g:price>4.95 USD</g:price>
+ </g:shipping>
+ <g:shipping>
+ <g:country>US</g:country>
+ <g:service>Next Day</g:service>
+ <g:price>8.50 USD</g:price>
+ </g:shipping>
+
+ <!-- 2 out of the 3 unique product identifer attributes are required for this item -->
+ <g:gtin>3348901056069</g:gtin>
+ <g:brand>Dior</g:brand>
+
+ <!-- The following attributes are not required for this item, but supplying them is recommended if applicable -->
+ <g:product_type>Health &amp; Beauty &gt; Personal Care &gt; Cosmetics &gt; Skin Care &gt; Lotion</g:product_type>
+ <g:google_product_category>Health &amp; Beauty &gt; Personal Care &gt; Cosmetics &gt; Skin Care &gt; Anti-Aging Skin Care Kits</g:google_product_category>
+ <g:additional_image_link>http://images.example.com/PFM654321_2.jpg</g:additional_image_link>
+ <g:additional_image_link>http://images.example.com/PFM654321_3.jpg</g:additional_image_link>
+ </entry>
+
+ <!-- Fourth example shows what attributes are required and recommended for items that are in the apparel category -->
+ <entry>
+ <!-- The following attributes are always required -->
+ <g:id>CLO-29473856-1</g:id>
+ <g:title>Roma Cotton Rich Bootcut Jeans - Size 8 Standard</g:title>
+ <g:description>A smart pair of bootcut jeans in stretch cotton.</g:description>
+ <g:link>http://www.example.com/clothing/women/Roma-Cotton-Bootcut-Jeans/?extid=CLO-29473856</g:link>
+ <g:image_link>http://images.example.com/CLO-29473856-front.jpg</g:image_link>
+ <g:condition>new</g:condition>
+ <g:availability>out of stock</g:availability>
+ <g:price>29.50 USD</g:price>
+
+ <!-- The following attributes are required because this item is apparel -->
+ <g:google_product_category>Apparel &amp; Accessories &gt; Clothing &gt; Pants &gt; Jeans</g:google_product_category>
+ <g:brand>M&amp;S</g:brand>
+ <g:gender>Female</g:gender>
+ <g:age_group>Adult</g:age_group>
+ <g:color>Navy</g:color>
+ <g:size>8 Standard</g:size>
+
+ <!-- The following attribute is required because this item has variants -->
+ <g:item_group_id>CLO-29473856</g:item_group_id>
+
+ <!-- The following attributes are not required for this item, but supplying them is recommended if applicable -->
+ <g:mpn>B003J5F5EY</g:mpn>
+ <g:product_type>Women's Clothing &gt; Jeans &gt; Bootcut Jeans</g:product_type>
+ <g:additional_image_link>http://images.example.com/CLO-29473856-side.jpg</g:additional_image_link>
+ <g:additional_image_link>http://images.example.com/CLO-29473856-back.jpg</g:additional_image_link>
+ </entry>
+
+ <!-- This is a variant of the last item (same 'item group id'). In this case the variant is only by size, but the item could be repeated in the same way for other variants -->
+ <entry>
+ <!-- The following attributes are always required -->
+ <g:id>CLO-29473856-2</g:id>
+ <g:title>Roma Cotton Rich Bootcut Jeans - Size 8 Tall</g:title>
+ <g:description>A smart pair of bootcut jeans in stretch cotton.</g:description>
+ <g:link>http://www.example.com/clothing/women/Roma-Cotton-Bootcut-Jeans/?extid=CLO-29473856</g:link>
+ <g:image_link>http://images.example.com/CLO-29473856-front.jpg</g:image_link>
+ <g:condition>new</g:condition>
+ <g:availability>in stock</g:availability>
+ <g:price>29.50 USD</g:price>
+
+ <!-- The following attributes are required because this item is apparel -->
+ <g:google_product_category>Apparel &amp; Accessories &gt; Clothing &gt; Pants &gt; Jeans</g:google_product_category>
+ <g:brand>M&amp;S</g:brand>
+ <g:gender>Female</g:gender>
+ <g:age_group>Adult</g:age_group>
+ <g:color>Navy</g:color>
+ <g:size>8 Tall</g:size>
+
+ <!-- The following attribute is required because this item has variants -->
+ <g:item_group_id>CLO-29473856</g:item_group_id>
+
+ <!-- The following attributes are not required for this item, but supplying them is recommended if applicable -->
+ <g:mpn>B003J5F5EY</g:mpn>
+ <g:product_type>Women's Clothing &gt; Jeans &gt; Bootcut Jeans</g:product_type>
+ <g:additional_image_link>http://images.example.com/CLO-29473856-side.jpg</g:additional_image_link>
+ <g:additional_image_link>http://images.example.com/CLO-29473856-back.jpg</g:additional_image_link>
+ </entry>
+
+ <!-- Fifth example demonstrates the use of the sale price attributes -->
+ <entry>
+ <!-- The following attributes are always required -->
+ <g:id>CLO-1029384</g:id>
+ <g:title>Tenn Cool Flow Ladies Long Sleeved Cycle Jersey</g:title>
+ <g:description>A ladies' cycling jersey designed for the serious cyclist, tailored to fit a feminine frame. This sporty, vibrant red, black and white jersey is constructed of a special polyester weave that is extremely effective at drawing moisture away from your body, helping to keep you dry. With an elasticised, gripping waist, it will stay in place for the duration of your cycle, and won't creep up like many other products. It has two elasticised rear pockets and the sleeves are elasticated to prevent creep-up.</g:description>
+ <g:link>http://www.example.com/clothing/sports/product?id=CLO1029384&amp;src=gshopping&amp;popup=false</g:link>
+ <g:image_link>http://images.example.com/CLO-1029384.jpg</g:image_link>
+ <g:condition>new</g:condition>
+ <g:availability>in stock</g:availability>
+ <g:price>33.99 USD</g:price>
+ <g:shipping>
+ <g:country>US</g:country>
+ <g:service>Standard Free Shipping</g:service>
+ <g:price>0 USD</g:price>
+ </g:shipping>
+
+ <!-- The following attributes are required because this item is apparel -->
+ <g:brand>Tenn Cool</g:brand>
+ <g:google_product_category>Apparel &amp; Accessories &gt; Clothing &gt; Activewear &gt; Bicycle Activewear &gt; Bicycle Jerseys</g:google_product_category>
+ <g:gender>Female</g:gender>
+ <g:age_group>Adult</g:age_group>
+ <g:color>Black/Red/White</g:color> <!-- Indicates all the colours found on the garment in order of dominance -->
+ <g:size>M</g:size>
+
+ <!-- The following demonstrate the use of the 'sale price' and 'sale price effective date' and attributes -->
+ <g:sale_price>25.49 USD</g:sale_price>
+ <g:sale_price_effective_date>2011-09-01T16:00-08:00/2011-09-03T16:00-08:00</g:sale_price_effective_date>
+
+ <!-- The following attributes are not required for this item, but supplying them is recommended if applicable -->
+ <g:gtin>5060155240282</g:gtin>
+ </entry>
+</feed> \ No newline at end of file
diff --git a/src/System.ServiceModel.Syndication/tests/TestFeeds/rssSpecExample.xml b/src/System.ServiceModel.Syndication/tests/TestFeeds/rssSpecExample.xml
new file mode 100644
index 0000000000..8be629d90d
--- /dev/null
+++ b/src/System.ServiceModel.Syndication/tests/TestFeeds/rssSpecExample.xml
@@ -0,0 +1,69 @@
+<?xml version="1.0"?>
+<rss version="2.0">
+ <channel customAttribute="customAtt">
+ <title>Liftoff News</title>
+ <link>http://liftoff.msfc.nasa.gov/</link>
+ <description>Liftoff to Space Exploration.</description>
+ <language>en-us</language>
+ <lastBuildDate>Tue, 10 Jun 2003 09:41:01 GMT</lastBuildDate>
+ <docs>http://blogs.law.harvard.edu/tech/rss</docs>
+ <generator>Weblog Editor 2.0</generator>
+ <managingEditor>editor@example.com</managingEditor>
+ <category>TestingFeeds</category>
+ <copyright>Contoso Rights.</copyright>
+ <ttl>60</ttl>
+ <skipHours>
+ <hour>1</hour>
+ <hour>2</hour>
+ <hour>3</hour>
+ </skipHours>
+ <skipDays>
+ <day>Saturday</day>
+ <day>Sunday</day>
+ </skipDays>
+
+ <textInput>
+ <description>Search Online</description>
+ <title>Search</title>
+ <asdasdasd>asdasdasdasdasd</asdasdasd>
+ <link>http://www.contoso.no/search?</link>
+ <name>input Name</name>
+ </textInput>
+
+ <image>
+ <url>http://2.bp.blogspot.com/-NA5Jb-64eUg/URx8CSdcj_I/AAAAAAAAAUo/eCx0irI0rq0/s1600/bg_Contoso_logo3-20120824073001907469-620x349.jpg</url>
+ <title>The title is not the same to the original one</title>
+ <link>http://www.contoso.com/notnews</link>
+ </image>
+ <item>
+ <title>Star City</title>
+ <link>http://liftoff.msfc.nasa.gov/news/2003/news-starcity.asp</link>
+ <description>
+ How do Americans get ready to work with Russians aboard the International Space Station? They take a crash course in culture, language and protocol at Russia's Star City.
+ </description>
+ <pubDate>Tue, 03 Jun 2003 09:39:21 GMT</pubDate>
+ <guid>http://liftoff.msfc.nasa.gov/2003/06/03.html#item573</guid>
+ </item>
+ <item>
+ <description>
+ Sky watchers in Europe, Asia, and parts of Alaska and Canada will experience a partial eclipse of the Sun on Saturday, May 31st.
+ </description>
+ <pubDate>Fri, 30 May 2003 11:06:42 GMT</pubDate>
+ <guid>http://liftoff.msfc.nasa.gov/2003/05/30.html#item572</guid>
+ </item>
+ <item>
+ <title>The Engine That Does More</title>
+ <link>http://liftoff.msfc.nasa.gov/news/2003/news-VASIMR.asp</link>
+ <description>Before man travels to Mars, NASA hopes to design new engines that will let us fly through the Solar System more quickly. The proposed VASIMR engine would do that.</description>
+ <pubDate>Tue, 27 May 2003 08:37:32 GMT</pubDate>
+ <guid>http://liftoff.msfc.nasa.gov/2003/05/27.html#item571</guid>
+ </item>
+ <item>
+ <title>Astronauts' Dirty Laundry</title>
+ <link>http://liftoff.msfc.nasa.gov/news/2003/news-laundry.asp</link>
+ <description>Compared to earlier spacecraft, the International Space Station has many luxuries, but laundry facilities are not one of them. Instead, astronauts have other options.</description>
+ <pubDate>Tue, 20 May 2003 08:56:02 GMT</pubDate>
+ <guid>http://liftoff.msfc.nasa.gov/2003/05/20.html#item570</guid>
+ </item>
+ </channel>
+</rss> \ No newline at end of file
diff --git a/src/System.ServiceModel.Syndication/tests/TestFeeds/rssSpecExampleWrongDateFormat.xml b/src/System.ServiceModel.Syndication/tests/TestFeeds/rssSpecExampleWrongDateFormat.xml
new file mode 100644
index 0000000000..5a0febe7c4
--- /dev/null
+++ b/src/System.ServiceModel.Syndication/tests/TestFeeds/rssSpecExampleWrongDateFormat.xml
@@ -0,0 +1,69 @@
+<?xml version="1.0"?>
+<rss version="2.0">
+ <channel customAttribute="customAtt">
+ <title>Liftoff News</title>
+ <link>http://liftoff.msfc.nasa.gov/</link>
+ <description>Liftoff to Space Exploration.</description>
+ <language>en-us</language>
+ <lastBuildDate>Tue, 23 August 2016 16:08:00 EDT</lastBuildDate>
+ <docs>http://blogs.law.harvard.edu/tech/rss</docs>
+ <generator>Weblog Editor 2.0</generator>
+ <managingEditor>editor@example.com</managingEditor>
+ <category>TestingFeeds</category>
+ <copyright>Contoso Rights.</copyright>
+ <ttl>60</ttl>
+ <skipHours>
+ <hour>1</hour>
+ <hour>2</hour>
+ <hour>3</hour>
+ </skipHours>
+ <skipDays>
+ <day>Saturday</day>
+ <day>Sunday</day>
+ </skipDays>
+
+ <textInput>
+ <description>Search Online</description>
+ <title>Search</title>
+ <asdasdasd>asdasdasdasdasd</asdasdasd>
+ <link>http://www.contoso.no/search?</link>
+ <name>input Name</name>
+ </textInput>
+
+ <image>
+ <url>http://2.bp.blogspot.com/-NA5Jb-64eUg/URx8CSdcj_I/AAAAAAAAAUo/eCx0irI0rq0/s1600/bg_Contoso_logo3-20120824073001907469-620x349.jpg</url>
+ <title>The title is not the same to the original one</title>
+ <link>http://www.contoso.com/notnews</link>
+ </image>
+ <item>
+ <title>Star City</title>
+ <link>http://liftoff.msfc.nasa.gov/news/2003/news-starcity.asp</link>
+ <description>
+ How do Americans get ready to work with Russians aboard the International Space Station? They take a crash course in culture, language and protocol at Russia's Star City.
+ </description>
+ <pubDate>Tue, 03 Jun 2003 09:39:21 GMT</pubDate>
+ <guid>http://liftoff.msfc.nasa.gov/2003/06/03.html#item573</guid>
+ </item>
+ <item>
+ <description>
+ Sky watchers in Europe, Asia, and parts of Alaska and Canada will experience a partial eclipse of the Sun on Saturday, May 31st.
+ </description>
+ <pubDate>Thu, 16 Oct 08 14:23:26 -0700</pubDate>
+ <guid>http://liftoff.msfc.nasa.gov/2003/05/30.html#item572</guid>
+ </item>
+ <item>
+ <title>The Engine That Does More</title>
+ <link>http://liftoff.msfc.nasa.gov/news/2003/news-VASIMR.asp</link>
+ <description>Before man travels to Mars, NASA hopes to design new engines that will let us fly through the Solar System more quickly. The proposed VASIMR engine would do that.</description>
+ <pubDate>Tue, 27 May 2003 08:37:32 GMTtttt</pubDate>
+ <guid>http://liftoff.msfc.nasa.gov/2003/05/27.html#item571</guid>
+ </item>
+ <item>
+ <title>Astronauts' Dirty Laundry</title>
+ <link>http://liftoff.msfc.nasa.gov/news/2003/news-laundry.asp</link>
+ <description>Compared to earlier spacecraft, the International Space Station has many luxuries, but laundry facilities are not one of them. Instead, astronauts have other options.</description>
+ <pubDate>Tue, 20 May 2003 08:56:02 GMT</pubDate>
+ <guid>http://liftoff.msfc.nasa.gov/2003/05/20.html#item570</guid>
+ </item>
+ </channel>
+</rss> \ No newline at end of file
diff --git a/src/System.ServiceModel.Syndication/tests/TestFeeds/rssSpecExampleWrongSkipDays.xml b/src/System.ServiceModel.Syndication/tests/TestFeeds/rssSpecExampleWrongSkipDays.xml
new file mode 100644
index 0000000000..bbfd75b673
--- /dev/null
+++ b/src/System.ServiceModel.Syndication/tests/TestFeeds/rssSpecExampleWrongSkipDays.xml
@@ -0,0 +1,70 @@
+<?xml version="1.0"?>
+<rss version="2.0">
+ <channel customAttribute="customAtt">
+ <title>Liftoff News</title>
+ <link>http://liftoff.msfc.nasa.gov/</link>
+ <description>Liftoff to Space Exploration.</description>
+ <language>en-us</language>
+ <lastBuildDate>Tue, 10 Jun 2003 09:41:01 GMT</lastBuildDate>
+ <docs>http://blogs.law.harvard.edu/tech/rss</docs>
+ <generator>Weblog Editor 2.0</generator>
+ <managingEditor>editor@example.com</managingEditor>
+ <category>TestingFeeds</category>
+ <copyright>Contoso Rights.</copyright>
+ <ttl>60</ttl>
+ <skipHours>
+ <hour>1</hour>
+ <hour>2</hour>
+ <hour>3</hour>
+ </skipHours>
+ <skipDays>
+ <day>Saturday</day>
+ <day>Sunday</day>
+ <day>tomorrow</day>
+ </skipDays>
+
+ <textInput>
+ <description>Search Online</description>
+ <title>Search</title>
+ <asdasdasd>asdasdasdasdasd</asdasdasd>
+ <link>http://www.contoso.no/search?</link>
+ <name>input Name</name>
+ </textInput>
+
+ <image>
+ <url>http://2.bp.blogspot.com/-NA5Jb-64eUg/URx8CSdcj_I/AAAAAAAAAUo/eCx0irI0rq0/s1600/bg_Contoso_logo3-20120824073001907469-620x349.jpg</url>
+ <title>The title is not the same to the original one</title>
+ <link>http://www.contoso.com/notnews</link>
+ </image>
+ <item>
+ <title>Star City</title>
+ <link>http://liftoff.msfc.nasa.gov/news/2003/news-starcity.asp</link>
+ <description>
+ How do Americans get ready to work with Russians aboard the International Space Station? They take a crash course in culture, language and protocol at Russia's Star City.
+ </description>
+ <pubDate>Tue, 03 Jun 2003 09:39:21 GMT</pubDate>
+ <guid>http://liftoff.msfc.nasa.gov/2003/06/03.html#item573</guid>
+ </item>
+ <item>
+ <description>
+ Sky watchers in Europe, Asia, and parts of Alaska and Canada will experience a partial eclipse of the Sun on Saturday, May 31st.
+ </description>
+ <pubDate>Fri, 30 May 2003 11:06:42 GMT</pubDate>
+ <guid>http://liftoff.msfc.nasa.gov/2003/05/30.html#item572</guid>
+ </item>
+ <item>
+ <title>The Engine That Does More</title>
+ <link>http://liftoff.msfc.nasa.gov/news/2003/news-VASIMR.asp</link>
+ <description>Before man travels to Mars, NASA hopes to design new engines that will let us fly through the Solar System more quickly. The proposed VASIMR engine would do that.</description>
+ <pubDate>Tue, 27 May 2003 08:37:32 GMT</pubDate>
+ <guid>http://liftoff.msfc.nasa.gov/2003/05/27.html#item571</guid>
+ </item>
+ <item>
+ <title>Astronauts' Dirty Laundry</title>
+ <link>http://liftoff.msfc.nasa.gov/news/2003/news-laundry.asp</link>
+ <description>Compared to earlier spacecraft, the International Space Station has many luxuries, but laundry facilities are not one of them. Instead, astronauts have other options.</description>
+ <pubDate>Tue, 20 May 2003 08:56:02 GMT</pubDate>
+ <guid>http://liftoff.msfc.nasa.gov/2003/05/20.html#item570</guid>
+ </item>
+ </channel>
+</rss> \ No newline at end of file
diff --git a/src/System.ServiceProcess.ServiceController/tests/ServiceBaseTests.cs b/src/System.ServiceProcess.ServiceController/tests/ServiceBaseTests.cs
index daf0ccc49e..96fd003295 100644
--- a/src/System.ServiceProcess.ServiceController/tests/ServiceBaseTests.cs
+++ b/src/System.ServiceProcess.ServiceController/tests/ServiceBaseTests.cs
@@ -21,6 +21,8 @@ namespace System.ServiceProcess.Tests
private static readonly Lazy<bool> s_isElevated = new Lazy<bool>(() => AdminHelpers.IsProcessElevated());
protected static bool IsProcessElevated => s_isElevated.Value;
+ private bool _disposed;
+
public ServiceBaseTests()
{
_testService = new TestServiceProvider();
@@ -174,7 +176,11 @@ OnStop
public void Dispose()
{
- _testService.DeleteTestServices();
+ if (!_disposed)
+ {
+ _testService.DeleteTestServices();
+ _disposed = true;
+ }
}
}
}
diff --git a/src/System.ServiceProcess.ServiceController/tests/ServiceControllerTests.cs b/src/System.ServiceProcess.ServiceController/tests/ServiceControllerTests.cs
index 2511ca5e18..11978dfe06 100644
--- a/src/System.ServiceProcess.ServiceController/tests/ServiceControllerTests.cs
+++ b/src/System.ServiceProcess.ServiceController/tests/ServiceControllerTests.cs
@@ -19,6 +19,7 @@ namespace System.ServiceProcess.Tests
protected static bool IsProcessElevated => s_isElevated.Value;
private const int ExpectedDependentServiceCount = 3;
+ private bool _disposed;
public ServiceControllerTests()
{
@@ -190,7 +191,11 @@ namespace System.ServiceProcess.Tests
public void Dispose()
{
- _testService.DeleteTestServices();
+ if (!_disposed)
+ {
+ _testService.DeleteTestServices();
+ _disposed = true;
+ }
}
private static ServiceController AssertHasDependent(ServiceController controller, string serviceName, string displayName)
diff --git a/src/System.ServiceProcess.ServiceController/tests/System.ServiceProcess.ServiceController.TestService/TestServiceInstaller.cs b/src/System.ServiceProcess.ServiceController/tests/System.ServiceProcess.ServiceController.TestService/TestServiceInstaller.cs
index 9bd9c12807..878f560386 100644
--- a/src/System.ServiceProcess.ServiceController/tests/System.ServiceProcess.ServiceController.TestService/TestServiceInstaller.cs
+++ b/src/System.ServiceProcess.ServiceController/tests/System.ServiceProcess.ServiceController.TestService/TestServiceInstaller.cs
@@ -14,6 +14,8 @@ namespace System.ServiceProcess.Tests
{
public const string LocalServiceName = "NT AUTHORITY\\LocalService";
+ private string _removalStack;
+
public TestServiceInstaller()
{
}
@@ -128,6 +130,19 @@ namespace System.ServiceProcess.Tests
public void RemoveService()
{
+ if (ServiceName == null)
+ throw new InvalidOperationException($"Already removed service at stack ${_removalStack}");
+
+ // Store the stack for logging in case we're called twice
+ try
+ {
+ throw new Exception();
+ }
+ catch (Exception e)
+ {
+ _removalStack = e.StackTrace;
+ }
+
// Stop the service
using (ServiceController svc = new ServiceController(ServiceName))
{
@@ -161,6 +176,8 @@ namespace System.ServiceProcess.Tests
Interop.Advapi32.CloseServiceHandle(serviceManagerHandle);
}
+
+ ServiceName = null;
}
}
-}
+} \ No newline at end of file
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 4b05771c72..a798cf4fe1 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
@@ -10,15 +10,21 @@
<HarvestIncludePaths Include="ref/netstandard1.3;runtimes/win/lib/netstandard1.3;lib/netstandard1.3" />
</ItemGroup>
<ItemGroup>
- <InboxOnTargetFramework Include="$(UAPvNextTFM)">
- <PackageTargetRuntime>win</PackageTargetRuntime>
- </InboxOnTargetFramework>
<InboxOnTargetFramework Include="MonoAndroid10" />
<InboxOnTargetFramework Include="MonoTouch10" />
<InboxOnTargetFramework Include="xamarinios10" />
<InboxOnTargetFramework Include="xamarinmac20" />
<InboxOnTargetFramework Include="xamarintvos10" />
<InboxOnTargetFramework Include="xamarinwatchos10" />
+
+ <!-- Since UAP and .NETCoreApp are package based we still want to enable
+ OOBing libraries that happen to overlap with their framework package.
+ This avoids us having to lock the API in our NuGet packages just
+ to match what shipped inbox: since we can provide a new library
+ we can update it to add API without raising the netstandard version. -->
+ <ValidatePackageSuppression Include="TreatAsOutOfBox">
+ <Value>.NETCoreApp;UAP</Value>
+ </ValidatePackageSuppression>
</ItemGroup>
<Import Project="$([MSBuild]::GetDirectoryNameOfFileAbove($(MSBuildThisFileDirectory), dir.targets))\dir.targets" />
</Project> \ No newline at end of file
diff --git a/src/System.Text.Encoding/tests/Decoder/DecoderConvert2.cs b/src/System.Text.Encoding/tests/Decoder/DecoderConvert2.cs
index 567eb371ed..6bc7546f9d 100644
--- a/src/System.Text.Encoding/tests/Decoder/DecoderConvert2.cs
+++ b/src/System.Text.Encoding/tests/Decoder/DecoderConvert2.cs
@@ -37,7 +37,7 @@ namespace System.Text.Tests
private const int c_SIZE_OF_ARRAY = 127;
private readonly RandomDataGenerator _generator = new RandomDataGenerator();
- // PosTest1: Call Convert to convert a arbitrary byte array to character array by using ASCII decoder
+ // PosTest1: Call Convert to convert an arbitrary byte array to character array by using ASCII decoder
[Fact]
public void PosTest1()
{
@@ -59,7 +59,7 @@ namespace System.Text.Tests
decoder.Reset();
}
- // PosTest2: Call Convert to convert a arbitrary byte array to character array by using Unicode decoder"
+ // PosTest2: Call Convert to convert an arbitrary byte array to character array by using Unicode decoder"
[Fact]
public void PosTest2()
{
diff --git a/src/System.Text.Encoding/tests/Encoder/EncoderConvert2.cs b/src/System.Text.Encoding/tests/Encoder/EncoderConvert2.cs
index f693c87a7c..e6e0a81945 100644
--- a/src/System.Text.Encoding/tests/Encoder/EncoderConvert2.cs
+++ b/src/System.Text.Encoding/tests/Encoder/EncoderConvert2.cs
@@ -50,7 +50,7 @@ namespace System.Text.Tests
yield return new object[] { Encoding.Unicode.GetEncoder(), 2 };
}
- // Call Convert to convert a arbitrary character array encoders
+ // Call Convert to convert an arbitrary character array encoders
[Theory]
[MemberData(nameof(Encoders_RandomInput))]
public void EncoderConvertRandomCharArray(Encoder encoder)
diff --git a/src/System.Text.RegularExpressions/ref/System.Text.RegularExpressions.cs b/src/System.Text.RegularExpressions/ref/System.Text.RegularExpressions.cs
index 4d6197c018..b87202e46b 100644
--- a/src/System.Text.RegularExpressions/ref/System.Text.RegularExpressions.cs
+++ b/src/System.Text.RegularExpressions/ref/System.Text.RegularExpressions.cs
@@ -6,6 +6,8 @@
// ------------------------------------------------------------------------------
+using System.Reflection;
+
namespace System.Text.RegularExpressions
{
public partial class Capture
@@ -16,7 +18,7 @@ namespace System.Text.RegularExpressions
public string Value { get { throw null; } }
public override string ToString() { throw null; }
}
- public partial class CaptureCollection : System.Collections.ICollection, System.Collections.IEnumerable
+ public partial class CaptureCollection : System.Collections.Generic.ICollection<System.Text.RegularExpressions.Capture>, System.Collections.Generic.IEnumerable<System.Text.RegularExpressions.Capture>, System.Collections.Generic.IList<System.Text.RegularExpressions.Capture>, System.Collections.Generic.IReadOnlyCollection<System.Text.RegularExpressions.Capture>, System.Collections.Generic.IReadOnlyList<System.Text.RegularExpressions.Capture>, System.Collections.ICollection, System.Collections.IEnumerable, System.Collections.IList
{
internal CaptureCollection() { }
public int Count { get { throw null; } }
@@ -25,16 +27,36 @@ namespace System.Text.RegularExpressions
public System.Text.RegularExpressions.Capture this[int i] { get { throw null; } }
public object SyncRoot { get { throw null; } }
public void CopyTo(System.Array array, int arrayIndex) { }
+ public void CopyTo(System.Text.RegularExpressions.Capture[] array, int arrayIndex) { }
public System.Collections.IEnumerator GetEnumerator() { throw null; }
+ System.Collections.Generic.IEnumerator<System.Text.RegularExpressions.Capture> System.Collections.Generic.IEnumerable<System.Text.RegularExpressions.Capture>.GetEnumerator() { throw null; }
+ int System.Collections.Generic.IList<System.Text.RegularExpressions.Capture>.IndexOf(System.Text.RegularExpressions.Capture item) { throw null; }
+ void System.Collections.Generic.IList<System.Text.RegularExpressions.Capture>.Insert(int index, System.Text.RegularExpressions.Capture item) { }
+ void System.Collections.Generic.IList<System.Text.RegularExpressions.Capture>.RemoveAt(int index) { }
+ System.Text.RegularExpressions.Capture System.Collections.Generic.IList<System.Text.RegularExpressions.Capture>.this[int index] { get { throw null; } set { } }
+ void System.Collections.Generic.ICollection<System.Text.RegularExpressions.Capture>.Add(System.Text.RegularExpressions.Capture item) { }
+ void System.Collections.Generic.ICollection<System.Text.RegularExpressions.Capture>.Clear() { }
+ bool System.Collections.Generic.ICollection<System.Text.RegularExpressions.Capture>.Contains(System.Text.RegularExpressions.Capture item) { throw null; }
+ bool System.Collections.Generic.ICollection<System.Text.RegularExpressions.Capture>.Remove(System.Text.RegularExpressions.Capture item) { throw null; }
+ int System.Collections.IList.Add(object value) { throw null; }
+ void System.Collections.IList.Clear() { }
+ bool System.Collections.IList.Contains(object value) { throw null; }
+ int System.Collections.IList.IndexOf(object value) { throw null; }
+ void System.Collections.IList.Insert(int index, object value) { }
+ bool System.Collections.IList.IsFixedSize { get { throw null; } }
+ void System.Collections.IList.Remove(object value) { }
+ void System.Collections.IList.RemoveAt(int index) { }
+ object System.Collections.IList.this[int index] { get { throw null; } set { } }
}
public partial class Group : System.Text.RegularExpressions.Capture
{
internal Group() { }
public System.Text.RegularExpressions.CaptureCollection Captures { get { throw null; } }
+ public string Name { get { throw null; } }
public bool Success { get { throw null; } }
public static System.Text.RegularExpressions.Group Synchronized(System.Text.RegularExpressions.Group inner) { throw null; }
}
- public partial class GroupCollection : System.Collections.ICollection, System.Collections.IEnumerable
+ public partial class GroupCollection : System.Collections.ICollection, System.Collections.IEnumerable, System.Collections.Generic.ICollection<System.Text.RegularExpressions.Group>, System.Collections.Generic.IEnumerable<System.Text.RegularExpressions.Group>, System.Collections.Generic.IList<System.Text.RegularExpressions.Group>, System.Collections.Generic.IReadOnlyCollection<System.Text.RegularExpressions.Group>, System.Collections.Generic.IReadOnlyList<System.Text.RegularExpressions.Group>, System.Collections.IList
{
internal GroupCollection() { }
public int Count { get { throw null; } }
@@ -44,7 +66,26 @@ namespace System.Text.RegularExpressions
public System.Text.RegularExpressions.Group this[string groupname] { get { throw null; } }
public object SyncRoot { get { throw null; } }
public void CopyTo(System.Array array, int arrayIndex) { }
+ public void CopyTo(System.Text.RegularExpressions.Group[] array, int arrayIndex) { }
public System.Collections.IEnumerator GetEnumerator() { throw null; }
+ System.Collections.Generic.IEnumerator<System.Text.RegularExpressions.Group> System.Collections.Generic.IEnumerable<System.Text.RegularExpressions.Group>.GetEnumerator() { throw null; }
+ int System.Collections.Generic.IList<System.Text.RegularExpressions.Group>.IndexOf(System.Text.RegularExpressions.Group item) { throw null; }
+ void System.Collections.Generic.IList<System.Text.RegularExpressions.Group>.Insert(int index, System.Text.RegularExpressions.Group item) { }
+ void System.Collections.Generic.IList<System.Text.RegularExpressions.Group>.RemoveAt(int index) { }
+ System.Text.RegularExpressions.Group System.Collections.Generic.IList<System.Text.RegularExpressions.Group>.this[int index] { get { throw null; } set { } }
+ void System.Collections.Generic.ICollection<System.Text.RegularExpressions.Group>.Add(System.Text.RegularExpressions.Group item) { }
+ void System.Collections.Generic.ICollection<System.Text.RegularExpressions.Group>.Clear() { }
+ bool System.Collections.Generic.ICollection<System.Text.RegularExpressions.Group>.Contains(System.Text.RegularExpressions.Group item) { throw null; }
+ bool System.Collections.Generic.ICollection<System.Text.RegularExpressions.Group>.Remove(System.Text.RegularExpressions.Group item) { throw null; }
+ int System.Collections.IList.Add(object value) { throw null; }
+ void System.Collections.IList.Clear() { }
+ bool System.Collections.IList.Contains(object value) { throw null; }
+ int System.Collections.IList.IndexOf(object value) { throw null; }
+ void System.Collections.IList.Insert(int index, object value) { }
+ bool System.Collections.IList.IsFixedSize { get { throw null; } }
+ void System.Collections.IList.Remove(object value) { }
+ void System.Collections.IList.RemoveAt(int index) { }
+ object System.Collections.IList.this[int index] { get { throw null; } set { } }
}
public partial class Match : System.Text.RegularExpressions.Group
{
@@ -55,7 +96,7 @@ namespace System.Text.RegularExpressions
public virtual string Result(string replacement) { throw null; }
public static System.Text.RegularExpressions.Match Synchronized(System.Text.RegularExpressions.Match inner) { throw null; }
}
- public partial class MatchCollection : System.Collections.ICollection, System.Collections.IEnumerable
+ public partial class MatchCollection : System.Collections.Generic.ICollection<System.Text.RegularExpressions.Match>, System.Collections.Generic.IEnumerable<System.Text.RegularExpressions.Match>, System.Collections.Generic.IList<System.Text.RegularExpressions.Match>, System.Collections.Generic.IReadOnlyCollection<System.Text.RegularExpressions.Match>, System.Collections.Generic.IReadOnlyList<System.Text.RegularExpressions.Match>, System.Collections.ICollection, System.Collections.IEnumerable, System.Collections.IList
{
internal MatchCollection() { }
public int Count { get { throw null; } }
@@ -64,7 +105,26 @@ namespace System.Text.RegularExpressions
public virtual System.Text.RegularExpressions.Match this[int i] { get { throw null; } }
public object SyncRoot { get { throw null; } }
public void CopyTo(System.Array array, int arrayIndex) { }
+ public void CopyTo(System.Text.RegularExpressions.Match[] array, int arrayIndex) { }
public System.Collections.IEnumerator GetEnumerator() { throw null; }
+ System.Collections.Generic.IEnumerator<System.Text.RegularExpressions.Match> System.Collections.Generic.IEnumerable<System.Text.RegularExpressions.Match>.GetEnumerator() { throw null; }
+ int System.Collections.Generic.IList<System.Text.RegularExpressions.Match>.IndexOf(System.Text.RegularExpressions.Match item) { throw null; }
+ void System.Collections.Generic.IList<System.Text.RegularExpressions.Match>.Insert(int index, System.Text.RegularExpressions.Match item) { }
+ void System.Collections.Generic.IList<System.Text.RegularExpressions.Match>.RemoveAt(int index) { }
+ System.Text.RegularExpressions.Match System.Collections.Generic.IList<System.Text.RegularExpressions.Match>.this[int index] { get { throw null; } set { } }
+ void System.Collections.Generic.ICollection<System.Text.RegularExpressions.Match>.Add(System.Text.RegularExpressions.Match item) { }
+ void System.Collections.Generic.ICollection<System.Text.RegularExpressions.Match>.Clear() { }
+ bool System.Collections.Generic.ICollection<System.Text.RegularExpressions.Match>.Contains(System.Text.RegularExpressions.Match item) { throw null; }
+ bool System.Collections.Generic.ICollection<System.Text.RegularExpressions.Match>.Remove(System.Text.RegularExpressions.Match item) { throw null; }
+ int System.Collections.IList.Add(object value) { throw null; }
+ void System.Collections.IList.Clear() { }
+ bool System.Collections.IList.Contains(object value) { throw null; }
+ int System.Collections.IList.IndexOf(object value) { throw null; }
+ void System.Collections.IList.Insert(int index, object value) { }
+ bool System.Collections.IList.IsFixedSize { get { throw null; } }
+ void System.Collections.IList.Remove(object value) { }
+ void System.Collections.IList.RemoveAt(int index) { }
+ object System.Collections.IList.this[int index] { get { throw null; } set { } }
}
public delegate string MatchEvaluator(System.Text.RegularExpressions.Match match);
public partial class Regex : System.Runtime.Serialization.ISerializable
@@ -84,6 +144,10 @@ namespace System.Text.RegularExpressions
public Regex(string pattern, System.Text.RegularExpressions.RegexOptions options) { }
public Regex(string pattern, System.Text.RegularExpressions.RegexOptions options, System.TimeSpan matchTimeout) { }
public static int CacheSize { get { throw null; } set { } }
+ [System.CLSCompliant(false)]
+ protected System.Collections.IDictionary Caps { get { throw null; } set { } }
+ [System.CLSCompliant(false)]
+ protected System.Collections.IDictionary CapNames { get { throw null; } set { } }
public System.TimeSpan MatchTimeout { get { throw null; } }
public System.Text.RegularExpressions.RegexOptions Options { get { throw null; } }
public bool RightToLeft { get { throw null; } }
@@ -134,6 +198,17 @@ namespace System.Text.RegularExpressions
protected bool UseOptionR() { throw null; }
protected internal static void ValidateMatchTimeout(System.TimeSpan matchTimeout) { }
}
+ public partial class RegexCompilationInfo
+ {
+ public RegexCompilationInfo(string pattern, RegexOptions options, string name, string fullnamespace, bool ispublic) { }
+ public RegexCompilationInfo(string pattern, RegexOptions options, string name, string fullnamespace, bool ispublic, TimeSpan matchTimeout) { }
+ public bool IsPublic { get; set; }
+ public TimeSpan MatchTimeout { get; set; }
+ public string Name { get; set; }
+ public string Namespace { get; set; }
+ public RegexOptions Options { get; set; }
+ public string Pattern { get; set; }
+ }
public partial class RegexMatchTimeoutException : System.TimeoutException, System.Runtime.Serialization.ISerializable
{
public RegexMatchTimeoutException() { }
diff --git a/src/System.Text.RegularExpressions/ref/System.Text.RegularExpressions.csproj b/src/System.Text.RegularExpressions/ref/System.Text.RegularExpressions.csproj
index 7cbdb75d2c..ae39f4e450 100644
--- a/src/System.Text.RegularExpressions/ref/System.Text.RegularExpressions.csproj
+++ b/src/System.Text.RegularExpressions/ref/System.Text.RegularExpressions.csproj
@@ -10,6 +10,9 @@
<PropertyGroup Condition="'$(Configuration)|$(Platform)' == 'uap-Release|AnyCPU'" />
<ItemGroup>
<Compile Include="System.Text.RegularExpressions.cs" />
+ </ItemGroup>
+ <!-- Files required to enable compiled feature -->
+ <ItemGroup Condition="'$(TargetGroup)' == 'netcoreapp'">
<Compile Include="System.Text.RegularExpressions.netcoreapp.cs" />
</ItemGroup>
<ItemGroup>
@@ -17,5 +20,9 @@
<ProjectReference Include="..\..\System.Runtime.Extensions\ref\System.Runtime.Extensions.csproj" />
<ProjectReference Include="..\..\System.Collections.NonGeneric\ref\System.Collections.NonGeneric.csproj" />
</ItemGroup>
+ <!-- Required for CompileToAssembly API -->
+ <ItemGroup Condition="'$(TargetGroup)' == 'netcoreapp'">
+ <ProjectReference Include="..\..\System.Reflection.Emit.ILGeneration\ref\System.Reflection.Emit.ILGeneration.csproj" />
+ </ItemGroup>
<Import Project="$([MSBuild]::GetDirectoryNameOfFileAbove($(MSBuildThisFileDirectory), dir.targets))\dir.targets" />
</Project> \ No newline at end of file
diff --git a/src/System.Text.RegularExpressions/ref/System.Text.RegularExpressions.netcoreapp.cs b/src/System.Text.RegularExpressions/ref/System.Text.RegularExpressions.netcoreapp.cs
index 5f05f9f850..d52614b990 100644
--- a/src/System.Text.RegularExpressions/ref/System.Text.RegularExpressions.netcoreapp.cs
+++ b/src/System.Text.RegularExpressions/ref/System.Text.RegularExpressions.netcoreapp.cs
@@ -8,81 +8,10 @@
namespace System.Text.RegularExpressions
{
- public partial class Group
- {
- public string Name { get { throw null; } }
- }
public partial class Regex
{
- [System.CLSCompliant(false)]
- protected System.Collections.IDictionary Caps { get { throw null; } set { } }
- [System.CLSCompliant(false)]
- protected System.Collections.IDictionary CapNames { get { throw null; } set { } }
- }
- public partial class CaptureCollection : System.Collections.Generic.ICollection<System.Text.RegularExpressions.Capture>, System.Collections.Generic.IEnumerable<System.Text.RegularExpressions.Capture>, System.Collections.Generic.IList<System.Text.RegularExpressions.Capture>, System.Collections.Generic.IReadOnlyCollection<System.Text.RegularExpressions.Capture>, System.Collections.Generic.IReadOnlyList<System.Text.RegularExpressions.Capture>, System.Collections.ICollection, System.Collections.IEnumerable, System.Collections.IList
- {
- public void CopyTo(System.Text.RegularExpressions.Capture[] array, int arrayIndex) { }
- System.Collections.Generic.IEnumerator<System.Text.RegularExpressions.Capture> System.Collections.Generic.IEnumerable<System.Text.RegularExpressions.Capture>.GetEnumerator() { throw null; }
- int System.Collections.Generic.IList<System.Text.RegularExpressions.Capture>.IndexOf(System.Text.RegularExpressions.Capture item) { throw null; }
- void System.Collections.Generic.IList<System.Text.RegularExpressions.Capture>.Insert(int index, System.Text.RegularExpressions.Capture item) { }
- void System.Collections.Generic.IList<System.Text.RegularExpressions.Capture>.RemoveAt(int index) { }
- System.Text.RegularExpressions.Capture System.Collections.Generic.IList<System.Text.RegularExpressions.Capture>.this[int index] { get { throw null; } set { } }
- void System.Collections.Generic.ICollection<System.Text.RegularExpressions.Capture>.Add(System.Text.RegularExpressions.Capture item) { }
- void System.Collections.Generic.ICollection<System.Text.RegularExpressions.Capture>.Clear() { }
- bool System.Collections.Generic.ICollection<System.Text.RegularExpressions.Capture>.Contains(System.Text.RegularExpressions.Capture item) { throw null; }
- bool System.Collections.Generic.ICollection<System.Text.RegularExpressions.Capture>.Remove(System.Text.RegularExpressions.Capture item) { throw null; }
- int System.Collections.IList.Add(object value) { throw null; }
- void System.Collections.IList.Clear() { }
- bool System.Collections.IList.Contains(object value) { throw null; }
- int System.Collections.IList.IndexOf(object value) { throw null; }
- void System.Collections.IList.Insert(int index, object value) { }
- bool System.Collections.IList.IsFixedSize { get { throw null; } }
- void System.Collections.IList.Remove(object value) { }
- void System.Collections.IList.RemoveAt(int index) { }
- object System.Collections.IList.this[int index] { get { throw null; } set { } }
- }
- public partial class GroupCollection : System.Collections.Generic.ICollection<System.Text.RegularExpressions.Group>, System.Collections.Generic.IEnumerable<System.Text.RegularExpressions.Group>, System.Collections.Generic.IList<System.Text.RegularExpressions.Group>, System.Collections.Generic.IReadOnlyCollection<System.Text.RegularExpressions.Group>, System.Collections.Generic.IReadOnlyList<System.Text.RegularExpressions.Group>, System.Collections.ICollection, System.Collections.IEnumerable, System.Collections.IList
- {
- public void CopyTo(System.Text.RegularExpressions.Group[] array, int arrayIndex) { }
- System.Collections.Generic.IEnumerator<System.Text.RegularExpressions.Group> System.Collections.Generic.IEnumerable<System.Text.RegularExpressions.Group>.GetEnumerator() { throw null; }
- int System.Collections.Generic.IList<System.Text.RegularExpressions.Group>.IndexOf(System.Text.RegularExpressions.Group item) { throw null; }
- void System.Collections.Generic.IList<System.Text.RegularExpressions.Group>.Insert(int index, System.Text.RegularExpressions.Group item) { }
- void System.Collections.Generic.IList<System.Text.RegularExpressions.Group>.RemoveAt(int index) { }
- System.Text.RegularExpressions.Group System.Collections.Generic.IList<System.Text.RegularExpressions.Group>.this[int index] { get { throw null; } set { } }
- void System.Collections.Generic.ICollection<System.Text.RegularExpressions.Group>.Add(System.Text.RegularExpressions.Group item) { }
- void System.Collections.Generic.ICollection<System.Text.RegularExpressions.Group>.Clear() { }
- bool System.Collections.Generic.ICollection<System.Text.RegularExpressions.Group>.Contains(System.Text.RegularExpressions.Group item) { throw null; }
- bool System.Collections.Generic.ICollection<System.Text.RegularExpressions.Group>.Remove(System.Text.RegularExpressions.Group item) { throw null; }
- int System.Collections.IList.Add(object value) { throw null; }
- void System.Collections.IList.Clear() { }
- bool System.Collections.IList.Contains(object value) { throw null; }
- int System.Collections.IList.IndexOf(object value) { throw null; }
- void System.Collections.IList.Insert(int index, object value) { }
- bool System.Collections.IList.IsFixedSize { get { throw null; } }
- void System.Collections.IList.Remove(object value) { }
- void System.Collections.IList.RemoveAt(int index) { }
- object System.Collections.IList.this[int index] { get { throw null; } set { } }
- }
- public partial class MatchCollection : System.Collections.Generic.ICollection<System.Text.RegularExpressions.Match>, System.Collections.Generic.IEnumerable<System.Text.RegularExpressions.Match>, System.Collections.Generic.IList<System.Text.RegularExpressions.Match>, System.Collections.Generic.IReadOnlyCollection<System.Text.RegularExpressions.Match>, System.Collections.Generic.IReadOnlyList<System.Text.RegularExpressions.Match>, System.Collections.ICollection, System.Collections.IEnumerable, System.Collections.IList
- {
- public void CopyTo(System.Text.RegularExpressions.Match[] array, int arrayIndex) { }
- System.Collections.Generic.IEnumerator<System.Text.RegularExpressions.Match> System.Collections.Generic.IEnumerable<System.Text.RegularExpressions.Match>.GetEnumerator() { throw null; }
- int System.Collections.Generic.IList<System.Text.RegularExpressions.Match>.IndexOf(System.Text.RegularExpressions.Match item) { throw null; }
- void System.Collections.Generic.IList<System.Text.RegularExpressions.Match>.Insert(int index, System.Text.RegularExpressions.Match item) { }
- void System.Collections.Generic.IList<System.Text.RegularExpressions.Match>.RemoveAt(int index) { }
- System.Text.RegularExpressions.Match System.Collections.Generic.IList<System.Text.RegularExpressions.Match>.this[int index] { get { throw null; } set { } }
- void System.Collections.Generic.ICollection<System.Text.RegularExpressions.Match>.Add(System.Text.RegularExpressions.Match item) { }
- void System.Collections.Generic.ICollection<System.Text.RegularExpressions.Match>.Clear() { }
- bool System.Collections.Generic.ICollection<System.Text.RegularExpressions.Match>.Contains(System.Text.RegularExpressions.Match item) { throw null; }
- bool System.Collections.Generic.ICollection<System.Text.RegularExpressions.Match>.Remove(System.Text.RegularExpressions.Match item) { throw null; }
- int System.Collections.IList.Add(object value) { throw null; }
- void System.Collections.IList.Clear() { }
- bool System.Collections.IList.Contains(object value) { throw null; }
- int System.Collections.IList.IndexOf(object value) { throw null; }
- void System.Collections.IList.Insert(int index, object value) { }
- bool System.Collections.IList.IsFixedSize { get { throw null; } }
- void System.Collections.IList.Remove(object value) { }
- void System.Collections.IList.RemoveAt(int index) { }
- object System.Collections.IList.this[int index] { get { throw null; } set { } }
+ public static void CompileToAssembly(RegexCompilationInfo[] regexinfos, System.Reflection.AssemblyName assemblyname) { }
+ public static void CompileToAssembly(RegexCompilationInfo[] regexinfos, System.Reflection.AssemblyName assemblyname, System.Reflection.Emit.CustomAttributeBuilder[] attributes) { }
+ public static void CompileToAssembly(RegexCompilationInfo[] regexinfos, System.Reflection.AssemblyName assemblyname, System.Reflection.Emit.CustomAttributeBuilder[] attributes, string resourceFile) { }
}
}
diff --git a/src/System.Text.RegularExpressions/src/Resources/Strings.resx b/src/System.Text.RegularExpressions/src/Resources/Strings.resx
index e2bb24a50f..dea3a7fe4a 100644
--- a/src/System.Text.RegularExpressions/src/Resources/Strings.resx
+++ b/src/System.Text.RegularExpressions/src/Resources/Strings.resx
@@ -67,6 +67,9 @@
<data name="Arg_ArrayPlusOffTooSmall" xml:space="preserve">
<value>Destination array is not long enough to copy all the items in the collection. Check array index and length.</value>
</data>
+ <data name="ArgumentNull_ArrayWithNullElements" xml:space="preserve">
+ <value>The array cannot contain null elements.</value>
+ </data>
<data name="BadClassInCharRange" xml:space="preserve">
<value>Cannot include class \\{0} in character range.</value>
</data>
@@ -88,6 +91,9 @@
<data name="IllegalCondition" xml:space="preserve">
<value>Illegal conditional (?(...)) expression.</value>
</data>
+ <data name="IllegalDefaultRegexMatchTimeoutInAppDomain" xml:space="preserve">
+ <value>AppDomain data '{0}' contains the invalid value or object '{1}' for specifying a default matching timeout for System.Text.RegularExpressions.Regex.</value>
+ </data>
<data name="IllegalEndEscape" xml:space="preserve">
<value>Illegal \\ at end of pattern.</value>
</data>
@@ -103,6 +109,9 @@
<data name="InvalidGroupName" xml:space="preserve">
<value>Invalid group name: Group names must begin with a word character.</value>
</data>
+ <data name="InvalidEmptyArgument" xml:space="preserve">
+ <value>Argument {0} cannot be zero-length.</value>
+ </data>
<data name="LengthNotNegative" xml:space="preserve">
<value>Length cannot be less than 0 or exceed input length.</value>
</data>
@@ -136,6 +145,9 @@
<data name="OnlyAllowedOnce" xml:space="preserve">
<value>This operation is only allowed once per object.</value>
</data>
+ <data name="PlatformNotSupported_CompileToAssembly" xml:space="preserve">
+ <value>This platform does not support writing compiled regular expressions to an assembly.</value>
+ </data>
<data name="QuantifyAfterNothing" xml:space="preserve">
<value>Quantifier {x,y} following nothing.</value>
</data>
@@ -193,4 +205,4 @@
<data name="UnterminatedComment" xml:space="preserve">
<value>Unterminated (?#...) comment.</value>
</data>
-</root> \ No newline at end of file
+</root>
diff --git a/src/System.Text.RegularExpressions/src/System.Text.RegularExpressions.csproj b/src/System.Text.RegularExpressions/src/System.Text.RegularExpressions.csproj
index a46adb1e42..7ccb1589a4 100644
--- a/src/System.Text.RegularExpressions/src/System.Text.RegularExpressions.csproj
+++ b/src/System.Text.RegularExpressions/src/System.Text.RegularExpressions.csproj
@@ -4,6 +4,7 @@
<PropertyGroup>
<ProjectGuid>{2C58640B-5BED-4E83-9554-CD2B9762643F}</ProjectGuid>
<AssemblyName>System.Text.RegularExpressions</AssemblyName>
+ <DefineConstants Condition="'$(TargetGroup)' == 'netcoreapp'">$(DefineConstants);FEATURE_COMPILED</DefineConstants>
</PropertyGroup>
<!-- Default configurations to help VS understand the configurations -->
<PropertyGroup Condition="'$(Configuration)|$(Platform)' == 'netcoreapp-Debug|AnyCPU'" />
@@ -19,6 +20,7 @@
<Compile Include="System\Text\RegularExpressions\RegexCharClass.cs" />
<Compile Include="System\Text\RegularExpressions\RegexCode.cs" />
<Compile Include="System\Text\RegularExpressions\RegexCollectionDebuggerProxy.cs" />
+ <Compile Include="System\Text\RegularExpressions\RegexCompilationInfo.cs" />
<Compile Include="System\Text\RegularExpressions\RegexFCD.cs" />
<Compile Include="System\Text\RegularExpressions\RegexGroup.cs" />
<Compile Include="System\Text\RegularExpressions\RegexGroupCollection.cs" />
@@ -42,6 +44,13 @@
<Link>Common\System\IO\StringBuilderCache.cs</Link>
</Compile>
</ItemGroup>
+ <!-- Files that enable compiled feature -->
+ <ItemGroup Condition="'$(TargetGroup)' == 'netcoreapp'">
+ <Compile Include="System\Text\RegularExpressions\CompiledRegexRunnerFactory.cs" />
+ <Compile Include="System\Text\RegularExpressions\CompiledRegexRunner.cs" />
+ <Compile Include="System\Text\RegularExpressions\RegexCompiler.cs" />
+ <Compile Include="System\Text\RegularExpressions\RegexLWCGCompiler.cs" />
+ </ItemGroup>
<ItemGroup>
<Reference Include="System.Collections" />
<Reference Include="System.Diagnostics.Debug" />
@@ -51,5 +60,11 @@
<Reference Include="System.Runtime.Extensions" />
<Reference Include="System.Threading" />
</ItemGroup>
+ <!-- References required for compiled feature -->
+ <ItemGroup Condition="'$(TargetGroup)' == 'netcoreapp'">
+ <Reference Include="System.Reflection.Emit.ILGeneration" />
+ <Reference Include="System.Reflection.Emit.Lightweight" />
+ <Reference Include="System.Reflection.Primitives" />
+ </ItemGroup>
<Import Project="$([MSBuild]::GetDirectoryNameOfFileAbove($(MSBuildThisFileDirectory), dir.targets))\dir.targets" />
-</Project> \ No newline at end of file
+</Project>
diff --git a/src/System.Text.RegularExpressions/src/System/Text/RegularExpressions/CompiledRegexRunner.cs b/src/System.Text.RegularExpressions/src/System/Text/RegularExpressions/CompiledRegexRunner.cs
new file mode 100644
index 0000000000..2ae5caf18d
--- /dev/null
+++ b/src/System.Text.RegularExpressions/src/System/Text/RegularExpressions/CompiledRegexRunner.cs
@@ -0,0 +1,37 @@
+// 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.Text.RegularExpressions
+{
+ internal sealed class CompiledRegexRunner : RegexRunner
+ {
+ private Action<RegexRunner> _goMethod;
+ private Func<RegexRunner, bool> _findFirstCharMethod;
+ private Action<RegexRunner> _initTrackCountMethod;
+
+ internal CompiledRegexRunner() { }
+
+ internal void SetDelegates(Action<RegexRunner> go, Func<RegexRunner,bool> firstChar, Action<RegexRunner> trackCount)
+ {
+ _goMethod = go;
+ _findFirstCharMethod = firstChar;
+ _initTrackCountMethod = trackCount;
+ }
+
+ protected override void Go()
+ {
+ _goMethod(this);
+ }
+
+ protected override bool FindFirstChar()
+ {
+ return _findFirstCharMethod(this);
+ }
+
+ protected override void InitTrackCount()
+ {
+ _initTrackCountMethod(this);
+ }
+ }
+}
diff --git a/src/System.Text.RegularExpressions/src/System/Text/RegularExpressions/CompiledRegexRunnerFactory.cs b/src/System.Text.RegularExpressions/src/System/Text/RegularExpressions/CompiledRegexRunnerFactory.cs
new file mode 100644
index 0000000000..1f81283199
--- /dev/null
+++ b/src/System.Text.RegularExpressions/src/System/Text/RegularExpressions/CompiledRegexRunnerFactory.cs
@@ -0,0 +1,32 @@
+// 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.Reflection.Emit;
+
+namespace System.Text.RegularExpressions
+{
+ internal sealed class CompiledRegexRunnerFactory : RegexRunnerFactory
+ {
+ private readonly DynamicMethod _goMethod;
+ private readonly DynamicMethod _findFirstCharMethod;
+ private readonly DynamicMethod _initTrackCountMethod;
+
+ internal CompiledRegexRunnerFactory(DynamicMethod go, DynamicMethod firstChar, DynamicMethod trackCount)
+ {
+ _goMethod = go;
+ _findFirstCharMethod = firstChar;
+ _initTrackCountMethod = trackCount;
+ }
+
+ protected internal override RegexRunner CreateInstance()
+ {
+ CompiledRegexRunner runner = new CompiledRegexRunner();
+ runner.SetDelegates((Action<RegexRunner>)_goMethod.CreateDelegate(typeof(Action<RegexRunner>)),
+ (Func<RegexRunner, bool>)_findFirstCharMethod.CreateDelegate(typeof(Func<RegexRunner, bool>)),
+ (Action<RegexRunner>)_initTrackCountMethod.CreateDelegate(typeof(Action<RegexRunner>)));
+
+ return runner;
+ }
+ }
+}
diff --git a/src/System.Text.RegularExpressions/src/System/Text/RegularExpressions/Regex.cs b/src/System.Text.RegularExpressions/src/System/Text/RegularExpressions/Regex.cs
index 70d494f623..ce8c5dd81e 100644
--- a/src/System.Text.RegularExpressions/src/System/Text/RegularExpressions/Regex.cs
+++ b/src/System.Text.RegularExpressions/src/System/Text/RegularExpressions/Regex.cs
@@ -9,6 +9,11 @@ using System.Collections;
using System.Collections.Generic;
using System.Diagnostics.CodeAnalysis;
using System.Globalization;
+using System.Reflection;
+using System.Reflection.Emit;
+#if FEATURE_COMPILED
+using System.Runtime.CompilerServices;
+#endif
using System.Runtime.Serialization;
using System.Threading;
@@ -43,9 +48,12 @@ namespace System.Text.RegularExpressions
protected internal TimeSpan internalMatchTimeout; // timeout for the execution of this regex
+ // During static initialisation of Regex we check
+ private const string DefaultMatchTimeout_ConfigKeyName = "REGEX_DEFAULT_MATCH_TIMEOUT";
+
// DefaultMatchTimeout specifies the match timeout to use if no other timeout was specified
// by one means or another. Typically, it is set to InfiniteMatchTimeout.
- internal static readonly TimeSpan DefaultMatchTimeout = InfiniteMatchTimeout;
+ internal static readonly TimeSpan DefaultMatchTimeout = InitDefaultMatchTimeout();
// *********** } match timeout fields ***********
@@ -147,16 +155,18 @@ namespace System.Text.RegularExpressions
throw new PlatformNotSupportedException();
}
- private Regex(string pattern, RegexOptions options, TimeSpan matchTimeout, bool useCache)
+ private Regex(string pattern, RegexOptions options, TimeSpan matchTimeout, bool addToCache)
{
- RegexTree tree;
- CachedCodeEntry cached = null;
- string cultureKey = null;
-
if (pattern == null)
+ {
throw new ArgumentNullException(nameof(pattern));
+ }
+
if (options < RegexOptions.None || (((int)options) >> MaxOptionShift) != 0)
+ {
throw new ArgumentOutOfRangeException(nameof(options));
+ }
+
if ((options & RegexOptions.ECMAScript) != 0
&& (options & ~(RegexOptions.ECMAScript |
RegexOptions.IgnoreCase |
@@ -167,29 +177,30 @@ namespace System.Text.RegularExpressions
| RegexOptions.Debug
#endif
)) != 0)
+ {
throw new ArgumentOutOfRangeException(nameof(options));
+ }
ValidateMatchTimeout(matchTimeout);
- // Try to look up this regex in the cache. We do this regardless of whether useCache is true since there's
- // really no reason not to.
+ string cultureKey;
if ((options & RegexOptions.CultureInvariant) != 0)
- cultureKey = CultureInfo.InvariantCulture.ToString(); // "English (United States)"
+ cultureKey = CultureInfo.InvariantCulture.ToString();
else
cultureKey = CultureInfo.CurrentCulture.ToString();
+ // Try to look up this regex in the cache.
var key = new CachedCodeEntryKey(options, cultureKey, pattern);
- cached = LookupCachedAndUpdate(key);
+ CachedCodeEntry cached = LookupCachedAndUpdate(key);
this.pattern = pattern;
roptions = options;
-
internalMatchTimeout = matchTimeout;
if (cached == null)
{
// Parse the input
- tree = RegexParser.Parse(pattern, roptions);
+ RegexTree tree = RegexParser.Parse(pattern, roptions);
// Extract the relevant information
capnames = tree._capnames;
@@ -201,7 +212,7 @@ namespace System.Text.RegularExpressions
InitializeReferences();
tree = null;
- if (useCache)
+ if (addToCache)
cached = CacheCode(key);
}
else
@@ -211,10 +222,28 @@ namespace System.Text.RegularExpressions
capslist = cached._capslist;
capsize = cached._capsize;
_code = cached._code;
+#if FEATURE_COMPILED
+ factory = cached._factory;
+#endif
_runnerref = cached._runnerref;
_replref = cached._replref;
_refsInitialized = true;
}
+
+#if FEATURE_COMPILED
+ // if the compile option is set, then compile the code if it's not already
+ if (UseOptionC() && factory == null)
+ {
+ factory = Compile(_code, roptions);
+
+ if (addToCache && cached != null)
+ {
+ cached.AddCompiled(factory);
+ }
+
+ _code = null;
+ }
+#endif
}
// Note: "&lt;" is the XML entity for smaller ("<").
@@ -238,6 +267,58 @@ namespace System.Text.RegularExpressions
}
/// <summary>
+ /// Specifies the default RegEx matching timeout value (i.e. the timeout that will be used if no
+ /// explicit timeout is specified).
+ /// The default is queried from the current <code>AppDomain</code>.
+ /// If the AddDomain's data value for that key is not a <code>TimeSpan</code> value or if it is outside the
+ /// valid range, an exception is thrown.
+ /// If the AddDomain's data value for that key is <code>null</code>, a fallback value is returned.
+ /// </summary>
+ /// <returns>The default RegEx matching timeout for this AppDomain</returns>
+ private static TimeSpan InitDefaultMatchTimeout()
+ {
+ // Query AppDomain
+ AppDomain ad = AppDomain.CurrentDomain;
+ object defaultMatchTimeoutObj = ad.GetData(DefaultMatchTimeout_ConfigKeyName);
+
+ // If no default is specified, use fallback
+ if (defaultMatchTimeoutObj == null)
+ {
+ return InfiniteMatchTimeout;
+ }
+
+ if (defaultMatchTimeoutObj is TimeSpan defaultMatchTimeOut)
+ {
+ // If default timeout is outside the valid range, throw. It will result in a TypeInitializationException:
+ try
+ {
+ ValidateMatchTimeout(defaultMatchTimeOut);
+ }
+ catch (ArgumentOutOfRangeException)
+ {
+ throw new ArgumentOutOfRangeException(SR.Format(SR.IllegalDefaultRegexMatchTimeoutInAppDomain, DefaultMatchTimeout_ConfigKeyName, defaultMatchTimeOut));
+ }
+
+ return defaultMatchTimeOut;
+ }
+
+ throw new InvalidCastException(SR.Format(SR.IllegalDefaultRegexMatchTimeoutInAppDomain, DefaultMatchTimeout_ConfigKeyName, defaultMatchTimeoutObj));
+ }
+
+#if FEATURE_COMPILED
+ /// <summary>
+ /// This method is here for perf reasons: if the call to RegexCompiler is NOT in the
+ /// Regex constructor, we don't load RegexCompiler and its reflection classes when
+ /// instantiating a non-compiled regex.
+ /// </summary>
+ [MethodImplAttribute(MethodImplOptions.NoInlining)]
+ private RegexRunnerFactory Compile(RegexCode code, RegexOptions roptions)
+ {
+ return RegexCompiler.Compile(code, roptions);
+ }
+#endif
+
+ /// <summary>
/// Escapes a minimal set of metacharacters (\, *, +, ?, |, {, [, (, ), ^, $, ., #, and
/// whitespace) by replacing them with their \ codes. This converts a string so that
/// it can be used as a constant within a regular expression safely. (Note that the
@@ -854,8 +935,7 @@ namespace System.Text.RegularExpressions
}
/// <summary>
- /// Splits the <paramref name="input"/> string at the position defined by a
- /// previous pattern.
+ /// Splits the <paramref name="input"/> string at the position defined by a previous pattern.
/// </summary>
public string[] Split(string input, int count, int startat)
{
@@ -865,6 +945,26 @@ namespace System.Text.RegularExpressions
return RegexReplacement.Split(this, input, count, startat);
}
+#if FEATURE_COMPILED
+ [SuppressMessage("Microsoft.Naming", "CA1704:IdentifiersShouldBeSpelledCorrectly", MessageId = "assemblyname", Justification = "Microsoft: already shipped since v1 - can't fix without causing a breaking change")]
+ public static void CompileToAssembly(RegexCompilationInfo[] regexinfos, AssemblyName assemblyname)
+ {
+ throw new PlatformNotSupportedException(SR.PlatformNotSupported_CompileToAssembly);
+ }
+
+ [SuppressMessage("Microsoft.Naming", "CA1704:IdentifiersShouldBeSpelledCorrectly", MessageId = "assemblyname", Justification = "Microsoft: already shipped since v1 - can't fix without causing a breaking change")]
+ public static void CompileToAssembly(RegexCompilationInfo[] regexinfos, AssemblyName assemblyname, CustomAttributeBuilder[] attributes)
+ {
+ throw new PlatformNotSupportedException(SR.PlatformNotSupported_CompileToAssembly);
+ }
+
+ [SuppressMessage("Microsoft.Naming", "CA1704:IdentifiersShouldBeSpelledCorrectly", MessageId = "assemblyname", Justification = "Microsoft: already shipped since v1 - can't fix without causing a breaking change")]
+ public static void CompileToAssembly(RegexCompilationInfo[] regexinfos, AssemblyName assemblyname, CustomAttributeBuilder[] attributes, string resourceFile)
+ {
+ throw new PlatformNotSupportedException(SR.PlatformNotSupported_CompileToAssembly);
+ }
+#endif
+
protected void InitializeReferences()
{
if (_refsInitialized)
@@ -898,6 +998,8 @@ namespace System.Text.RegularExpressions
if (runner == null)
{
+ // Use the compiled RegexRunner factory if the code was compiled to MSIL
+
if (factory != null)
runner = factory.CreateInstance();
else
@@ -1067,6 +1169,9 @@ namespace System.Text.RegularExpressions
internal Hashtable _caps;
internal Hashtable _capnames;
internal string[] _capslist;
+#if FEATURE_COMPILED
+ internal RegexRunnerFactory _factory;
+#endif
internal int _capsize;
internal ExclusiveReference _runnerref;
internal SharedReference _replref;
@@ -1084,6 +1189,14 @@ namespace System.Text.RegularExpressions
_runnerref = runner;
_replref = repl;
}
+
+#if FEATURE_COMPILED
+ internal void AddCompiled(RegexRunnerFactory factory)
+ {
+ _factory = factory;
+ _code = null;
+ }
+#endif
}
/*
diff --git a/src/System.Text.RegularExpressions/src/System/Text/RegularExpressions/RegexBoyerMoore.cs b/src/System.Text.RegularExpressions/src/System/Text/RegularExpressions/RegexBoyerMoore.cs
index 894a6875f1..d70e2d906b 100644
--- a/src/System.Text.RegularExpressions/src/System/Text/RegularExpressions/RegexBoyerMoore.cs
+++ b/src/System.Text.RegularExpressions/src/System/Text/RegularExpressions/RegexBoyerMoore.cs
@@ -19,14 +19,14 @@ namespace System.Text.RegularExpressions
{
internal sealed class RegexBoyerMoore
{
- private readonly int[] _positive;
- private readonly int[] _negativeASCII;
- private readonly int[][] _negativeUnicode;
- private readonly string _pattern;
- private readonly int _lowASCII;
- private readonly int _highASCII;
+ internal readonly int[] _positive;
+ internal readonly int[] _negativeASCII;
+ internal readonly int[][] _negativeUnicode;
+ internal readonly string _pattern;
+ internal readonly int _lowASCII;
+ internal readonly int _highASCII;
private readonly bool _rightToLeft;
- private readonly bool _caseInsensitive;
+ internal readonly bool _caseInsensitive;
private readonly CultureInfo _culture;
/// <summary>
diff --git a/src/System.Text.RegularExpressions/src/System/Text/RegularExpressions/RegexCode.cs b/src/System.Text.RegularExpressions/src/System/Text/RegularExpressions/RegexCode.cs
index 545a5292af..b500772081 100644
--- a/src/System.Text.RegularExpressions/src/System/Text/RegularExpressions/RegexCode.cs
+++ b/src/System.Text.RegularExpressions/src/System/Text/RegularExpressions/RegexCode.cs
@@ -151,7 +151,6 @@ namespace System.Text.RegularExpressions
}
}
-#if DEBUG
internal static int OpcodeSize(int opcode)
{
opcode &= Mask;
@@ -212,6 +211,7 @@ namespace System.Text.RegularExpressions
}
}
+#if DEBUG
private static readonly string[] CodeStr = new string[]
{
"Onerep", "Notonerep", "Setrep",
diff --git a/src/System.Text.RegularExpressions/src/System/Text/RegularExpressions/RegexCompilationInfo.cs b/src/System.Text.RegularExpressions/src/System/Text/RegularExpressions/RegexCompilationInfo.cs
new file mode 100644
index 0000000000..1c4106b870
--- /dev/null
+++ b/src/System.Text.RegularExpressions/src/System/Text/RegularExpressions/RegexCompilationInfo.cs
@@ -0,0 +1,77 @@
+// 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.Text.RegularExpressions
+{
+ public class RegexCompilationInfo
+ {
+ private string _pattern;
+ private string _name;
+ private string _nspace;
+ private TimeSpan _matchTimeout;
+
+ public RegexCompilationInfo(string pattern, RegexOptions options, string name, string fullnamespace, bool ispublic)
+ : this(pattern, options, name, fullnamespace, ispublic, Regex.DefaultMatchTimeout)
+ {
+ }
+
+ public RegexCompilationInfo(string pattern, RegexOptions options, string name, string fullnamespace, bool ispublic, TimeSpan matchTimeout)
+ {
+ Pattern = pattern;
+ Name = name;
+ Namespace = fullnamespace;
+ Options = options;
+ IsPublic = ispublic;
+ MatchTimeout = matchTimeout;
+ }
+
+ public bool IsPublic { get; set; }
+
+ public TimeSpan MatchTimeout
+ {
+ get => _matchTimeout;
+ set
+ {
+ Regex.ValidateMatchTimeout(value);
+ _matchTimeout = value;
+ }
+ }
+
+ public string Name
+ {
+ get => _name;
+ set
+ {
+ if (value == null)
+ {
+ throw new ArgumentNullException(nameof(Name));
+ }
+
+ if (value.Length == 0)
+ {
+ throw new ArgumentException(SR.Format(SR.InvalidEmptyArgument, nameof(Name)), nameof(Name));
+ }
+
+ _name = value;
+ }
+ }
+
+ public string Namespace
+ {
+ get => _nspace;
+ set
+ {
+ _nspace = value ?? throw new ArgumentNullException(nameof(Namespace));
+ }
+ }
+
+ public RegexOptions Options { get; set; }
+
+ public string Pattern
+ {
+ get => _pattern;
+ set => _pattern = value ?? throw new ArgumentNullException(nameof(Pattern));
+ }
+ }
+}
diff --git a/src/System.Text.RegularExpressions/src/System/Text/RegularExpressions/RegexCompiler.cs b/src/System.Text.RegularExpressions/src/System/Text/RegularExpressions/RegexCompiler.cs
new file mode 100644
index 0000000000..fac86269ec
--- /dev/null
+++ b/src/System.Text.RegularExpressions/src/System/Text/RegularExpressions/RegexCompiler.cs
@@ -0,0 +1,3092 @@
+// 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.
+
+// The RegexCompiler class is internal to the Regex package.
+// It translates a block of RegexCode to MSIL, and creates a
+// subclass of the RegexRunner type.
+
+using System.Diagnostics;
+using System.Diagnostics.CodeAnalysis;
+using System.Globalization;
+using System.Reflection;
+using System.Reflection.Emit;
+using System.Runtime.Versioning;
+
+namespace System.Text.RegularExpressions
+{
+ /*
+ * RegexDynamicModule
+ *
+ * Because dynamic modules are expensive and not thread-safe, we create
+ * one dynamic module per-thread, and cache as much information about it
+ * as we can.
+ *
+ * While we're at it, we just create one RegexCompiler per thread
+ * as well, and have RegexCompiler inherit from RegexDynamicModule.
+ */
+ internal abstract class RegexCompiler
+ {
+ // fields that never change (making them saves about 6% overall running time)
+ internal static FieldInfo s_textbegF;
+ internal static FieldInfo s_textendF;
+ internal static FieldInfo s_textstartF;
+ internal static FieldInfo s_textposF;
+ internal static FieldInfo s_textF;
+ internal static FieldInfo s_trackposF;
+ internal static FieldInfo s_trackF;
+ internal static FieldInfo s_stackposF;
+ internal static FieldInfo s_stackF;
+ internal static FieldInfo s_trackcountF;
+
+ internal static MethodInfo s_ensurestorageM;
+ internal static MethodInfo s_captureM;
+ internal static MethodInfo s_transferM;
+ internal static MethodInfo s_uncaptureM;
+ internal static MethodInfo s_ismatchedM;
+ internal static MethodInfo s_matchlengthM;
+ internal static MethodInfo s_matchindexM;
+ internal static MethodInfo s_isboundaryM;
+ internal static MethodInfo s_isECMABoundaryM;
+ internal static MethodInfo s_chartolowerM;
+ internal static MethodInfo s_getcharM;
+ internal static MethodInfo s_crawlposM;
+ internal static MethodInfo s_charInSetM;
+ internal static MethodInfo s_getCurrentCulture;
+ internal static MethodInfo s_getInvariantCulture;
+ internal static MethodInfo s_checkTimeoutM;
+#if DEBUG
+ internal static MethodInfo s_dumpstateM;
+#endif
+
+ internal ILGenerator _ilg;
+
+ // tokens representing local variables
+ internal LocalBuilder _textstartV;
+ internal LocalBuilder _textbegV;
+ internal LocalBuilder _textendV;
+ internal LocalBuilder _textposV;
+ internal LocalBuilder _textV;
+ internal LocalBuilder _trackposV;
+ internal LocalBuilder _trackV;
+ internal LocalBuilder _stackposV;
+ internal LocalBuilder _stackV;
+ internal LocalBuilder _tempV;
+ internal LocalBuilder _temp2V;
+ internal LocalBuilder _temp3V;
+
+ internal RegexCode _code; // the RegexCode object (used for debugging only)
+ internal int[] _codes; // the RegexCodes being translated
+ internal string[] _strings; // the stringtable associated with the RegexCodes
+ internal RegexPrefix _fcPrefix; // the possible first chars computed by RegexFCD
+ internal RegexBoyerMoore _bmPrefix; // a prefix as a boyer-moore machine
+ internal int _anchors; // the set of anchors
+
+ internal Label[] _labels; // a label for every operation in _codes
+ internal BacktrackNote[] _notes; // a list of the backtracking states to be generated
+ internal int _notecount; // true count of _notes (allocation grows exponentially)
+ internal int _trackcount; // count of backtracking states (used to reduce allocations)
+
+ internal Label _backtrack; // label for backtracking
+
+
+ internal int _regexopcode; // the current opcode being processed
+ internal int _codepos; // the current code being translated
+ internal int _backpos; // the current backtrack-note being translated
+
+ internal RegexOptions _options; // options
+
+ // special code fragments
+ internal int[] _uniquenote; // _notes indices for code that should be emitted <= once
+ internal int[] _goto; // indices for forward-jumps-through-switch (for allocations)
+
+ // indices for unique code fragments
+ internal const int Stackpop = 0; // pop one
+ internal const int Stackpop2 = 1; // pop two
+ internal const int Stackpop3 = 2; // pop three
+ internal const int Capback = 3; // uncapture
+ internal const int Capback2 = 4; // uncapture 2
+ internal const int Branchmarkback2 = 5; // back2 part of branchmark
+ internal const int Lazybranchmarkback2 = 6; // back2 part of lazybranchmark
+ internal const int Branchcountback2 = 7; // back2 part of branchcount
+ internal const int Lazybranchcountback2 = 8; // back2 part of lazybranchcount
+ internal const int Forejumpback = 9; // back part of forejump
+ internal const int Uniquecount = 10;
+
+ static RegexCompiler()
+ {
+ // fields
+ s_textbegF = RegexRunnerField("runtextbeg");
+ s_textendF = RegexRunnerField("runtextend");
+ s_textstartF = RegexRunnerField("runtextstart");
+ s_textposF = RegexRunnerField("runtextpos");
+ s_textF = RegexRunnerField("runtext");
+ s_trackposF = RegexRunnerField("runtrackpos");
+ s_trackF = RegexRunnerField("runtrack");
+ s_stackposF = RegexRunnerField("runstackpos");
+ s_stackF = RegexRunnerField("runstack");
+ s_trackcountF = RegexRunnerField("runtrackcount");
+
+ // methods
+ s_ensurestorageM = RegexRunnerMethod("EnsureStorage");
+ s_captureM = RegexRunnerMethod("Capture");
+ s_transferM = RegexRunnerMethod("TransferCapture");
+ s_uncaptureM = RegexRunnerMethod("Uncapture");
+ s_ismatchedM = RegexRunnerMethod("IsMatched");
+ s_matchlengthM = RegexRunnerMethod("MatchLength");
+ s_matchindexM = RegexRunnerMethod("MatchIndex");
+ s_isboundaryM = RegexRunnerMethod("IsBoundary");
+ s_charInSetM = RegexRunnerMethod("CharInClass");
+ s_isECMABoundaryM = RegexRunnerMethod("IsECMABoundary");
+ s_crawlposM = RegexRunnerMethod("Crawlpos");
+ s_checkTimeoutM = RegexRunnerMethod("CheckTimeout");
+
+ s_chartolowerM = typeof(char).GetMethod("ToLower", new Type[] { typeof(char), typeof(CultureInfo) });
+ s_getcharM = typeof(string).GetMethod("get_Chars", new Type[] { typeof(int) });
+ s_getCurrentCulture = typeof(CultureInfo).GetMethod("get_CurrentCulture");
+ s_getInvariantCulture = typeof(CultureInfo).GetMethod("get_InvariantCulture");
+
+#if DEBUG
+ s_dumpstateM = RegexRunnerMethod("DumpState");
+#endif
+ }
+
+ private static FieldInfo RegexRunnerField(string fieldname)
+ {
+ return typeof(RegexRunner).GetField(fieldname, BindingFlags.NonPublic | BindingFlags.Public | BindingFlags.Instance | BindingFlags.Static);
+ }
+
+ private static MethodInfo RegexRunnerMethod(string methname)
+ {
+ return typeof(RegexRunner).GetMethod(methname, BindingFlags.NonPublic | BindingFlags.Public | BindingFlags.Instance | BindingFlags.Static);
+ }
+
+
+ /*
+ * Entry point to dynamically compile a regular expression. The expression is compiled to
+ * an in-memory assembly.
+ */
+ internal static RegexRunnerFactory Compile(RegexCode code, RegexOptions options)
+ {
+ return new RegexLWCGCompiler().FactoryInstanceFromCode(code, options);
+ }
+
+ /*
+ * Keeps track of an operation that needs to be referenced in the backtrack-jump
+ * switch table, and that needs backtracking code to be emitted (if flags != 0)
+ */
+ internal sealed class BacktrackNote
+ {
+ internal BacktrackNote(int flags, Label label, int codepos)
+ {
+ _codepos = codepos;
+ _flags = flags;
+ _label = label;
+ }
+
+ internal int _codepos;
+ internal int _flags;
+ internal Label _label;
+ }
+
+ /*
+ * Adds a backtrack note to the list of them, and returns the index of the new
+ * note (which is also the index for the jump used by the switch table)
+ */
+ internal int AddBacktrackNote(int flags, Label l, int codepos)
+ {
+ if (_notes == null || _notecount >= _notes.Length)
+ {
+ BacktrackNote[] newnotes = new BacktrackNote[_notes == null ? 16 : _notes.Length * 2];
+ if (_notes != null)
+ System.Array.Copy(_notes, 0, newnotes, 0, _notecount);
+ _notes = newnotes;
+ }
+
+ _notes[_notecount] = new BacktrackNote(flags, l, codepos);
+
+ return _notecount++;
+ }
+
+ /*
+ * Adds a backtrack note for the current operation; creates a new label for
+ * where the code will be, and returns the switch index.
+ */
+ internal int AddTrack()
+ {
+ return AddTrack(RegexCode.Back);
+ }
+
+ /*
+ * Adds a backtrack note for the current operation; creates a new label for
+ * where the code will be, and returns the switch index.
+ */
+ internal int AddTrack(int flags)
+ {
+ return AddBacktrackNote(flags, DefineLabel(), _codepos);
+ }
+
+ /*
+ * Adds a switchtable entry for the specified position (for the forward
+ * logic; does not cause backtracking logic to be generated)
+ */
+ internal int AddGoto(int destpos)
+ {
+ if (_goto[destpos] == -1)
+ _goto[destpos] = AddBacktrackNote(0, _labels[destpos], destpos);
+
+ return _goto[destpos];
+ }
+
+ /*
+ * Adds a note for backtracking code that only needs to be generated once;
+ * if it's already marked to be generated, returns the switch index
+ * for the unique piece of code.
+ */
+ internal int AddUniqueTrack(int i)
+ {
+ return AddUniqueTrack(i, RegexCode.Back);
+ }
+
+ /*
+ * Adds a note for backtracking code that only needs to be generated once;
+ * if it's already marked to be generated, returns the switch index
+ * for the unique piece of code.
+ */
+ internal int AddUniqueTrack(int i, int flags)
+ {
+ if (_uniquenote[i] == -1)
+ _uniquenote[i] = AddTrack(flags);
+
+ return _uniquenote[i];
+ }
+
+ /*
+ * A macro for _ilg.DefineLabel
+ */
+ internal Label DefineLabel()
+ {
+ return _ilg.DefineLabel();
+ }
+
+ /*
+ * A macro for _ilg.MarkLabel
+ */
+ internal void MarkLabel(Label l)
+ {
+ _ilg.MarkLabel(l);
+ }
+
+ /*
+ * Returns the ith operand of the current operation
+ */
+ internal int Operand(int i)
+ {
+ return _codes[_codepos + i + 1];
+ }
+
+ /*
+ * True if the current operation is marked for the leftward direction
+ */
+ internal bool IsRtl()
+ {
+ return (_regexopcode & RegexCode.Rtl) != 0;
+ }
+
+ /*
+ * True if the current operation is marked for case insensitive operation
+ */
+ internal bool IsCi()
+ {
+ return (_regexopcode & RegexCode.Ci) != 0;
+ }
+
+#if DEBUG
+ /*
+ * True if we need to do the backtrack logic for the current operation
+ */
+ internal bool IsBack() {
+ return(_regexopcode & RegexCode.Back) != 0;
+ }
+
+ /*
+ * True if we need to do the second-backtrack logic for the current operation
+ */
+ internal bool IsBack2() {
+ return(_regexopcode & RegexCode.Back2) != 0;
+ }
+#endif
+
+ /*
+ * Returns the raw regex opcode (masking out Back and Rtl)
+ */
+ internal int Code()
+ {
+ return _regexopcode & RegexCode.Mask;
+ }
+
+ internal void Ldstr(string str)
+ {
+ _ilg.Emit(OpCodes.Ldstr, str);
+ }
+
+ /*
+ * A macro for the various forms of Ldc
+ */
+ internal void Ldc(int i)
+ {
+ if (i <= 127 && i >= -128)
+ _ilg.Emit(OpCodes.Ldc_I4_S, (byte)i);
+ else
+ _ilg.Emit(OpCodes.Ldc_I4, i);
+ }
+
+ internal void LdcI8(long i)
+ {
+ if (i <= int.MaxValue && i >= int.MinValue)
+ {
+ Ldc((int)i);
+ _ilg.Emit(OpCodes.Conv_I8);
+ }
+ else
+ {
+ _ilg.Emit(OpCodes.Ldc_I8, i);
+ }
+ }
+
+ /*
+ * A macro for _ilg.Emit(OpCodes.Dup)
+ */
+ internal void Dup()
+ {
+ _ilg.Emit(OpCodes.Dup);
+ }
+
+ /*
+ * A macro for _ilg.Emit(OpCodes.Ret)
+ */
+ internal void Ret()
+ {
+ _ilg.Emit(OpCodes.Ret);
+ }
+
+ /*
+ * A macro for _ilg.Emit(OpCodes.Pop)
+ */
+ internal void Pop()
+ {
+ _ilg.Emit(OpCodes.Pop);
+ }
+
+ /*
+ * A macro for _ilg.Emit(OpCodes.Add)
+ */
+ internal void Add()
+ {
+ _ilg.Emit(OpCodes.Add);
+ }
+
+ /*
+ * A macro for _ilg.Emit(OpCodes.Add); a true flag can turn it into a Sub
+ */
+ internal void Add(bool negate)
+ {
+ if (negate)
+ _ilg.Emit(OpCodes.Sub);
+ else
+ _ilg.Emit(OpCodes.Add);
+ }
+
+ /*
+ * A macro for _ilg.Emit(OpCodes.Sub)
+ */
+ internal void Sub()
+ {
+ _ilg.Emit(OpCodes.Sub);
+ }
+
+ /*
+ * A macro for _ilg.Emit(OpCodes.Sub); a true flag can turn it into a Add
+ */
+ internal void Sub(bool negate)
+ {
+ if (negate)
+ _ilg.Emit(OpCodes.Add);
+ else
+ _ilg.Emit(OpCodes.Sub);
+ }
+
+ /*
+ * A macro for _ilg.Emit(OpCodes.Ldloc);
+ */
+ internal void Ldloc(LocalBuilder lt)
+ {
+ _ilg.Emit(OpCodes.Ldloc_S, lt);
+ }
+
+ /*
+ * A macro for _ilg.Emit(OpCodes.Stloc);
+ */
+ internal void Stloc(LocalBuilder lt)
+ {
+ _ilg.Emit(OpCodes.Stloc_S, lt);
+ }
+
+ /*
+ * A macro for _ilg.Emit(OpCodes.Ldarg_0);
+ */
+ internal void Ldthis()
+ {
+ _ilg.Emit(OpCodes.Ldarg_0);
+ }
+
+ /*
+ * A macro for Ldthis(); Ldfld();
+ */
+ internal void Ldthisfld(FieldInfo ft)
+ {
+ Ldthis();
+ _ilg.Emit(OpCodes.Ldfld, ft);
+ }
+
+ /*
+ * A macro for Ldthis(); Ldfld(); Stloc();
+ */
+ internal void Mvfldloc(FieldInfo ft, LocalBuilder lt)
+ {
+ Ldthisfld(ft);
+ Stloc(lt);
+ }
+
+ /*
+ * A macro for Ldthis(); Ldthisfld(); Stloc();
+ */
+ internal void Mvlocfld(LocalBuilder lt, FieldInfo ft)
+ {
+ Ldthis();
+ Ldloc(lt);
+ Stfld(ft);
+ }
+
+ /*
+ * A macro for _ilg.Emit(OpCodes.Stfld);
+ */
+ internal void Stfld(FieldInfo ft)
+ {
+ _ilg.Emit(OpCodes.Stfld, ft);
+ }
+
+ /*
+ * A macro for _ilg.Emit(OpCodes.Callvirt);
+ */
+ internal void Callvirt(MethodInfo mt)
+ {
+ _ilg.Emit(OpCodes.Callvirt, mt);
+ }
+
+ /*
+ * A macro for _ilg.Emit(OpCodes.Call);
+ */
+ internal void Call(MethodInfo mt)
+ {
+ _ilg.Emit(OpCodes.Call, mt);
+ }
+
+ /*
+ * A macro for _ilg.Emit(OpCodes.Newobj);
+ */
+ internal void Newobj(ConstructorInfo ct)
+ {
+ _ilg.Emit(OpCodes.Newobj, ct);
+ }
+
+ /*
+ * A macro for _ilg.Emit(OpCodes.Brfalse) (long form)
+ */
+ internal void BrfalseFar(Label l)
+ {
+ _ilg.Emit(OpCodes.Brfalse, l);
+ }
+
+ /*
+ * A macro for _ilg.Emit(OpCodes.Brtrue) (long form)
+ */
+ internal void BrtrueFar(Label l)
+ {
+ _ilg.Emit(OpCodes.Brtrue, l);
+ }
+
+ /*
+ * A macro for _ilg.Emit(OpCodes.Br) (long form)
+ */
+ internal void BrFar(Label l)
+ {
+ _ilg.Emit(OpCodes.Br, l);
+ }
+
+ /*
+ * A macro for _ilg.Emit(OpCodes.Ble) (long form)
+ */
+ internal void BleFar(Label l)
+ {
+ _ilg.Emit(OpCodes.Ble, l);
+ }
+
+ /*
+ * A macro for _ilg.Emit(OpCodes.Blt) (long form)
+ */
+ internal void BltFar(Label l)
+ {
+ _ilg.Emit(OpCodes.Blt, l);
+ }
+
+ /*
+ * A macro for _ilg.Emit(OpCodes.Bge) (long form)
+ */
+ internal void BgeFar(Label l)
+ {
+ _ilg.Emit(OpCodes.Bge, l);
+ }
+
+ /*
+ * A macro for _ilg.Emit(OpCodes.Bgt) (long form)
+ */
+ internal void BgtFar(Label l)
+ {
+ _ilg.Emit(OpCodes.Bgt, l);
+ }
+
+ /*
+ * A macro for _ilg.Emit(OpCodes.Bne) (long form)
+ */
+ internal void BneFar(Label l)
+ {
+ _ilg.Emit(OpCodes.Bne_Un, l);
+ }
+
+ /*
+ * A macro for _ilg.Emit(OpCodes.Beq) (long form)
+ */
+ internal void BeqFar(Label l)
+ {
+ _ilg.Emit(OpCodes.Beq, l);
+ }
+
+ /*
+ * A macro for _ilg.Emit(OpCodes.Brfalse_S) (short jump)
+ */
+ internal void Brfalse(Label l)
+ {
+ _ilg.Emit(OpCodes.Brfalse_S, l);
+ }
+
+ /*
+ * A macro for _ilg.Emit(OpCodes.Br_S) (short jump)
+ */
+ internal void Br(Label l)
+ {
+ _ilg.Emit(OpCodes.Br_S, l);
+ }
+
+ /*
+ * A macro for _ilg.Emit(OpCodes.Ble_S) (short jump)
+ */
+ internal void Ble(Label l)
+ {
+ _ilg.Emit(OpCodes.Ble_S, l);
+ }
+
+ /*
+ * A macro for _ilg.Emit(OpCodes.Blt_S) (short jump)
+ */
+ internal void Blt(Label l)
+ {
+ _ilg.Emit(OpCodes.Blt_S, l);
+ }
+
+ /*
+ * A macro for _ilg.Emit(OpCodes.Bge_S) (short jump)
+ */
+ internal void Bge(Label l)
+ {
+ _ilg.Emit(OpCodes.Bge_S, l);
+ }
+
+ /*
+ * A macro for _ilg.Emit(OpCodes.Bgt_S) (short jump)
+ */
+ internal void Bgt(Label l)
+ {
+ _ilg.Emit(OpCodes.Bgt_S, l);
+ }
+
+ /*
+ * A macro for _ilg.Emit(OpCodes.Bleun_S) (short jump)
+ */
+ internal void Bgtun(Label l)
+ {
+ _ilg.Emit(OpCodes.Bgt_Un_S, l);
+ }
+
+ /*
+ * A macro for _ilg.Emit(OpCodes.Bne_S) (short jump)
+ */
+ internal void Bne(Label l)
+ {
+ _ilg.Emit(OpCodes.Bne_Un_S, l);
+ }
+
+ /*
+ * A macro for _ilg.Emit(OpCodes.Beq_S) (short jump)
+ */
+ internal void Beq(Label l)
+ {
+ _ilg.Emit(OpCodes.Beq_S, l);
+ }
+
+ /*
+ * A macro for the Ldlen instruction
+ */
+ internal void Ldlen()
+ {
+ _ilg.Emit(OpCodes.Ldlen);
+ }
+
+ /*
+ * Loads the char to the right of the current position
+ */
+ internal void Rightchar()
+ {
+ Ldloc(_textV);
+ Ldloc(_textposV);
+ Callvirt(s_getcharM);
+ }
+
+ /*
+ * Loads the char to the right of the current position and advances the current position
+ */
+ internal void Rightcharnext()
+ {
+ Ldloc(_textV);
+ Ldloc(_textposV);
+ Dup();
+ Ldc(1);
+ Add();
+ Stloc(_textposV);
+ Callvirt(s_getcharM);
+ }
+
+ /*
+ * Loads the char to the left of the current position
+ */
+ internal void Leftchar()
+ {
+ Ldloc(_textV);
+ Ldloc(_textposV);
+ Ldc(1);
+ Sub();
+ Callvirt(s_getcharM);
+ }
+
+ /*
+ * Loads the char to the left of the current position and advances (leftward)
+ */
+ internal void Leftcharnext()
+ {
+ Ldloc(_textV);
+ Ldloc(_textposV);
+ Ldc(1);
+ Sub();
+ Dup();
+ Stloc(_textposV);
+ Callvirt(s_getcharM);
+ }
+
+ /*
+ * Creates a backtrack note and pushes the switch index it on the tracking stack
+ */
+ internal void Track()
+ {
+ ReadyPushTrack();
+ Ldc(AddTrack());
+ DoPush();
+ }
+
+ /*
+ * Pushes the current switch index on the tracking stack so the backtracking
+ * logic will be repeated again next time we backtrack here.
+ *
+ * <
+
+*/
+ internal void Trackagain()
+ {
+ ReadyPushTrack();
+ Ldc(_backpos);
+ DoPush();
+ }
+
+ /*
+ * Saves the value of a local variable on the tracking stack
+ */
+ internal void PushTrack(LocalBuilder lt)
+ {
+ ReadyPushTrack();
+ Ldloc(lt);
+ DoPush();
+ }
+
+ /*
+ * Creates a backtrack note for a piece of code that should only be generated once,
+ * and emits code that pushes the switch index on the backtracking stack.
+ */
+ internal void TrackUnique(int i)
+ {
+ ReadyPushTrack();
+ Ldc(AddUniqueTrack(i));
+ DoPush();
+ }
+
+ /*
+ * Creates a second-backtrack note for a piece of code that should only be
+ * generated once, and emits code that pushes the switch index on the
+ * backtracking stack.
+ */
+ internal void TrackUnique2(int i)
+ {
+ ReadyPushTrack();
+ Ldc(AddUniqueTrack(i, RegexCode.Back2));
+ DoPush();
+ }
+
+ /*
+ * Prologue to code that will push an element on the tracking stack
+ */
+ internal void ReadyPushTrack()
+ {
+ _ilg.Emit(OpCodes.Ldloc_S, _trackV);
+ _ilg.Emit(OpCodes.Ldloc_S, _trackposV);
+ _ilg.Emit(OpCodes.Ldc_I4_1);
+ _ilg.Emit(OpCodes.Sub);
+ _ilg.Emit(OpCodes.Dup);
+ _ilg.Emit(OpCodes.Stloc_S, _trackposV);
+ }
+
+ /*
+ * Pops an element off the tracking stack (leave it on the operand stack)
+ */
+ internal void PopTrack()
+ {
+ _ilg.Emit(OpCodes.Ldloc_S, _trackV);
+ _ilg.Emit(OpCodes.Ldloc_S, _trackposV);
+ _ilg.Emit(OpCodes.Dup);
+ _ilg.Emit(OpCodes.Ldc_I4_1);
+ _ilg.Emit(OpCodes.Add);
+ _ilg.Emit(OpCodes.Stloc_S, _trackposV);
+ _ilg.Emit(OpCodes.Ldelem_I4);
+ }
+
+ /*
+ * Retrieves the top entry on the tracking stack without popping
+ */
+ internal void TopTrack()
+ {
+ _ilg.Emit(OpCodes.Ldloc_S, _trackV);
+ _ilg.Emit(OpCodes.Ldloc_S, _trackposV);
+ _ilg.Emit(OpCodes.Ldelem_I4);
+ }
+
+ /*
+ * Saves the value of a local variable on the grouping stack
+ */
+ internal void PushStack(LocalBuilder lt)
+ {
+ ReadyPushStack();
+ _ilg.Emit(OpCodes.Ldloc_S, lt);
+ DoPush();
+ }
+
+ /*
+ * Prologue to code that will replace the ith element on the grouping stack
+ */
+ internal void ReadyReplaceStack(int i)
+ {
+ _ilg.Emit(OpCodes.Ldloc_S, _stackV);
+ _ilg.Emit(OpCodes.Ldloc_S, _stackposV);
+ if (i != 0)
+ {
+ Ldc(i);
+ _ilg.Emit(OpCodes.Add);
+ }
+ }
+
+ /*
+ * Prologue to code that will push an element on the grouping stack
+ */
+ internal void ReadyPushStack()
+ {
+ _ilg.Emit(OpCodes.Ldloc_S, _stackV);
+ _ilg.Emit(OpCodes.Ldloc_S, _stackposV);
+ _ilg.Emit(OpCodes.Ldc_I4_1);
+ _ilg.Emit(OpCodes.Sub);
+ _ilg.Emit(OpCodes.Dup);
+ _ilg.Emit(OpCodes.Stloc_S, _stackposV);
+ }
+
+ /*
+ * Retrieves the top entry on the stack without popping
+ */
+ internal void TopStack()
+ {
+ _ilg.Emit(OpCodes.Ldloc_S, _stackV);
+ _ilg.Emit(OpCodes.Ldloc_S, _stackposV);
+ _ilg.Emit(OpCodes.Ldelem_I4);
+ }
+
+ /*
+ * Pops an element off the grouping stack (leave it on the operand stack)
+ */
+ internal void PopStack()
+ {
+ _ilg.Emit(OpCodes.Ldloc_S, _stackV);
+ _ilg.Emit(OpCodes.Ldloc_S, _stackposV);
+ _ilg.Emit(OpCodes.Dup);
+ _ilg.Emit(OpCodes.Ldc_I4_1);
+ _ilg.Emit(OpCodes.Add);
+ _ilg.Emit(OpCodes.Stloc_S, _stackposV);
+ _ilg.Emit(OpCodes.Ldelem_I4);
+ }
+
+ /*
+ * Pops 1 element off the grouping stack and discards it
+ */
+ internal void PopDiscardStack()
+ {
+ PopDiscardStack(1);
+ }
+
+ /*
+ * Pops i elements off the grouping stack and discards them
+ */
+ internal void PopDiscardStack(int i)
+ {
+ _ilg.Emit(OpCodes.Ldloc_S, _stackposV);
+ Ldc(i);
+ _ilg.Emit(OpCodes.Add);
+ _ilg.Emit(OpCodes.Stloc_S, _stackposV);
+ }
+
+ /*
+ * Epilogue to code that will replace an element on a stack (use Ld* in between)
+ */
+ internal void DoReplace()
+ {
+ _ilg.Emit(OpCodes.Stelem_I4);
+ }
+
+ /*
+ * Epilogue to code that will push an element on a stack (use Ld* in between)
+ */
+ internal void DoPush()
+ {
+ _ilg.Emit(OpCodes.Stelem_I4);
+ }
+
+ /*
+ * Jump to the backtracking switch
+ */
+ internal void Back()
+ {
+ _ilg.Emit(OpCodes.Br, _backtrack);
+ }
+
+ /*
+ * Branch to the MSIL corresponding to the regex code at i
+ *
+ * A trick: since track and stack space is gobbled up unboundedly
+ * only as a result of branching backwards, this is where we check
+ * for sufficient space and trigger reallocations.
+ *
+ * If the "goto" is backwards, we generate code that checks
+ * available space against the amount of space that would be needed
+ * in the worst case by code that will only go forward; if there's
+ * not enough, we push the destination on the tracking stack, then
+ * we jump to the place where we invoke the allocator.
+ *
+ * Since forward gotos pose no threat, they just turn into a Br.
+ */
+ internal void Goto(int i)
+ {
+ if (i < _codepos)
+ {
+ Label l1 = DefineLabel();
+
+ // When going backwards, ensure enough space.
+ Ldloc(_trackposV);
+ Ldc(_trackcount * 4);
+ Ble(l1);
+ Ldloc(_stackposV);
+ Ldc(_trackcount * 3);
+ BgtFar(_labels[i]);
+ MarkLabel(l1);
+ ReadyPushTrack();
+ Ldc(AddGoto(i));
+ DoPush();
+ BrFar(_backtrack);
+ }
+ else
+ {
+ BrFar(_labels[i]);
+ }
+ }
+
+ /*
+ * Returns the position of the next operation in the regex code, taking
+ * into account the different numbers of arguments taken by operations
+ */
+ internal int NextCodepos()
+ {
+ return _codepos + RegexCode.OpcodeSize(_codes[_codepos]);
+ }
+
+ /*
+ * The label for the next (forward) operation
+ */
+ internal Label AdvanceLabel()
+ {
+ return _labels[NextCodepos()];
+ }
+
+ /*
+ * Goto the next (forward) operation
+ */
+ internal void Advance()
+ {
+ _ilg.Emit(OpCodes.Br, AdvanceLabel());
+ }
+
+ internal void CallToLower()
+ {
+ if ((_options & RegexOptions.CultureInvariant) != 0)
+ Call(s_getInvariantCulture);
+ else
+ Call(s_getCurrentCulture);
+
+ Call(s_chartolowerM);
+ }
+
+ /*
+ * Generates the first section of the MSIL. This section contains all
+ * the forward logic, and corresponds directly to the regex codes.
+ *
+ * In the absence of backtracking, this is all we would need.
+ */
+ internal void GenerateForwardSection()
+ {
+ int codepos;
+
+ _labels = new Label[_codes.Length];
+ _goto = new int[_codes.Length];
+
+ // initialize
+
+ for (codepos = 0; codepos < _codes.Length; codepos += RegexCode.OpcodeSize(_codes[codepos]))
+ {
+ _goto[codepos] = -1;
+ _labels[codepos] = _ilg.DefineLabel();
+ }
+
+ _uniquenote = new int[Uniquecount];
+ for (int i = 0; i < Uniquecount; i++)
+ _uniquenote[i] = -1;
+
+ // emit variable initializers
+
+ Mvfldloc(s_textF, _textV);
+ Mvfldloc(s_textstartF, _textstartV);
+ Mvfldloc(s_textbegF, _textbegV);
+ Mvfldloc(s_textendF, _textendV);
+ Mvfldloc(s_textposF, _textposV);
+ Mvfldloc(s_trackF, _trackV);
+ Mvfldloc(s_trackposF, _trackposV);
+ Mvfldloc(s_stackF, _stackV);
+ Mvfldloc(s_stackposF, _stackposV);
+
+ _backpos = -1;
+
+ for (codepos = 0; codepos < _codes.Length; codepos += RegexCode.OpcodeSize(_codes[codepos]))
+ {
+ MarkLabel(_labels[codepos]);
+ _codepos = codepos;
+ _regexopcode = _codes[codepos];
+ GenerateOneCode();
+ }
+ }
+
+ /*
+ * Generates the middle section of the MSIL. This section contains the
+ * big switch jump that allows us to simulate a stack of addresses,
+ * and it also contains the calls that expand the tracking and the
+ * grouping stack when they get too full.
+ */
+ internal void GenerateMiddleSection()
+ {
+ Label l1 = DefineLabel();
+ Label[] table;
+ int i;
+
+ // Backtrack switch
+ MarkLabel(_backtrack);
+
+ // first call EnsureStorage
+ Mvlocfld(_trackposV, s_trackposF);
+ Mvlocfld(_stackposV, s_stackposF);
+ Ldthis();
+ Callvirt(s_ensurestorageM);
+ Mvfldloc(s_trackposF, _trackposV);
+ Mvfldloc(s_stackposF, _stackposV);
+ Mvfldloc(s_trackF, _trackV);
+ Mvfldloc(s_stackF, _stackV);
+
+
+ PopTrack();
+
+ table = new Label[_notecount];
+ for (i = 0; i < _notecount; i++)
+ table[i] = _notes[i]._label;
+
+ _ilg.Emit(OpCodes.Switch, table);
+
+ }
+
+ /*
+ * Generates the last section of the MSIL. This section contains all of
+ * the backtracking logic.
+ */
+ internal void GenerateBacktrackSection()
+ {
+ int i;
+
+ for (i = 0; i < _notecount; i++)
+ {
+ BacktrackNote n = _notes[i];
+ if (n._flags != 0)
+ {
+ _ilg.MarkLabel(n._label);
+ _codepos = n._codepos;
+ _backpos = i;
+ _regexopcode = _codes[n._codepos] | n._flags;
+ GenerateOneCode();
+ }
+ }
+ }
+
+ /*
+ * Generates FindFirstChar
+ */
+ // !!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!
+ // !!!! This function must be kept synchronized with FindFirstChar in !!!!
+ // !!!! RegexInterpreter.cs !!!!
+ // !!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!
+ internal void GenerateFindFirstChar()
+ {
+ _textposV = DeclareInt();
+ _textV = DeclareString();
+ _tempV = DeclareInt();
+ _temp2V = DeclareInt();
+
+ if (0 != (_anchors & (RegexFCD.Beginning | RegexFCD.Start | RegexFCD.EndZ | RegexFCD.End)))
+ {
+ if (!_code._rightToLeft)
+ {
+ if (0 != (_anchors & RegexFCD.Beginning))
+ {
+ Label l1 = DefineLabel();
+ Ldthisfld(s_textposF);
+ Ldthisfld(s_textbegF);
+ Ble(l1);
+ Ldthis();
+ Ldthisfld(s_textendF);
+ Stfld(s_textposF);
+ Ldc(0);
+ Ret();
+ MarkLabel(l1);
+ }
+
+ if (0 != (_anchors & RegexFCD.Start))
+ {
+ Label l1 = DefineLabel();
+ Ldthisfld(s_textposF);
+ Ldthisfld(s_textstartF);
+ Ble(l1);
+ Ldthis();
+ Ldthisfld(s_textendF);
+ Stfld(s_textposF);
+ Ldc(0);
+ Ret();
+ MarkLabel(l1);
+ }
+
+ if (0 != (_anchors & RegexFCD.EndZ))
+ {
+ Label l1 = DefineLabel();
+ Ldthisfld(s_textposF);
+ Ldthisfld(s_textendF);
+ Ldc(1);
+ Sub();
+ Bge(l1);
+ Ldthis();
+ Ldthisfld(s_textendF);
+ Ldc(1);
+ Sub();
+ Stfld(s_textposF);
+ MarkLabel(l1);
+ }
+
+ if (0 != (_anchors & RegexFCD.End))
+ {
+ Label l1 = DefineLabel();
+ Ldthisfld(s_textposF);
+ Ldthisfld(s_textendF);
+ Bge(l1);
+ Ldthis();
+ Ldthisfld(s_textendF);
+ Stfld(s_textposF);
+ MarkLabel(l1);
+ }
+ }
+ else
+ {
+ if (0 != (_anchors & RegexFCD.End))
+ {
+ Label l1 = DefineLabel();
+ Ldthisfld(s_textposF);
+ Ldthisfld(s_textendF);
+ Bge(l1);
+ Ldthis();
+ Ldthisfld(s_textbegF);
+ Stfld(s_textposF);
+ Ldc(0);
+ Ret();
+ MarkLabel(l1);
+ }
+
+ if (0 != (_anchors & RegexFCD.EndZ))
+ {
+ Label l1 = DefineLabel();
+ Label l2 = DefineLabel();
+ Ldthisfld(s_textposF);
+ Ldthisfld(s_textendF);
+ Ldc(1);
+ Sub();
+ Blt(l1);
+ Ldthisfld(s_textposF);
+ Ldthisfld(s_textendF);
+ Beq(l2);
+ Ldthisfld(s_textF);
+ Ldthisfld(s_textposF);
+ Callvirt(s_getcharM);
+ Ldc((int)'\n');
+ Beq(l2);
+ MarkLabel(l1);
+ Ldthis();
+ Ldthisfld(s_textbegF);
+ Stfld(s_textposF);
+ Ldc(0);
+ Ret();
+ MarkLabel(l2);
+ }
+
+ if (0 != (_anchors & RegexFCD.Start))
+ {
+ Label l1 = DefineLabel();
+ Ldthisfld(s_textposF);
+ Ldthisfld(s_textstartF);
+ Bge(l1);
+ Ldthis();
+ Ldthisfld(s_textbegF);
+ Stfld(s_textposF);
+ Ldc(0);
+ Ret();
+ MarkLabel(l1);
+ }
+
+ if (0 != (_anchors & RegexFCD.Beginning))
+ {
+ Label l1 = DefineLabel();
+ Ldthisfld(s_textposF);
+ Ldthisfld(s_textbegF);
+ Ble(l1);
+ Ldthis();
+ Ldthisfld(s_textbegF);
+ Stfld(s_textposF);
+ MarkLabel(l1);
+ }
+ }
+
+ // <
+
+
+ Ldc(1);
+ Ret();
+ }
+ else if (_bmPrefix != null && _bmPrefix._negativeUnicode == null)
+ {
+ // Compiled Boyer-Moore string matching
+ // <
+
+
+ LocalBuilder chV = _tempV;
+ LocalBuilder testV = _tempV;
+ LocalBuilder limitV = _temp2V;
+ Label lDefaultAdvance = DefineLabel();
+ Label lAdvance = DefineLabel();
+ Label lFail = DefineLabel();
+ Label lStart = DefineLabel();
+ Label lOutOfRange = DefineLabel();
+ Label lPartialMatch = DefineLabel();
+
+
+ int chLast;
+ int i;
+ int beforefirst;
+ int last;
+ Label[] table;
+
+ if (!_code._rightToLeft)
+ {
+ beforefirst = -1;
+ last = _bmPrefix._pattern.Length - 1;
+ }
+ else
+ {
+ beforefirst = _bmPrefix._pattern.Length;
+ last = 0;
+ }
+
+ chLast = _bmPrefix._pattern[last];
+
+ Mvfldloc(s_textF, _textV);
+ if (!_code._rightToLeft)
+ Ldthisfld(s_textendF);
+ else
+ Ldthisfld(s_textbegF);
+ Stloc(limitV);
+
+ Ldthisfld(s_textposF);
+ if (!_code._rightToLeft)
+ {
+ Ldc(_bmPrefix._pattern.Length - 1);
+ Add();
+ }
+ else
+ {
+ Ldc(_bmPrefix._pattern.Length);
+ Sub();
+ }
+ Stloc(_textposV);
+ Br(lStart);
+
+ MarkLabel(lDefaultAdvance);
+
+ if (!_code._rightToLeft)
+ Ldc(_bmPrefix._pattern.Length);
+ else
+ Ldc(-_bmPrefix._pattern.Length);
+
+ MarkLabel(lAdvance);
+
+ Ldloc(_textposV);
+ Add();
+ Stloc(_textposV);
+
+ MarkLabel(lStart);
+
+ Ldloc(_textposV);
+ Ldloc(limitV);
+ if (!_code._rightToLeft)
+ BgeFar(lFail);
+ else
+ BltFar(lFail);
+
+ Rightchar();
+ if (_bmPrefix._caseInsensitive)
+ CallToLower();
+
+ Dup();
+ Stloc(chV);
+ Ldc(chLast);
+ BeqFar(lPartialMatch);
+
+ Ldloc(chV);
+ Ldc(_bmPrefix._lowASCII);
+ Sub();
+ Dup();
+ Stloc(chV);
+ Ldc(_bmPrefix._highASCII - _bmPrefix._lowASCII);
+ Bgtun(lDefaultAdvance);
+
+ table = new Label[_bmPrefix._highASCII - _bmPrefix._lowASCII + 1];
+
+ for (i = _bmPrefix._lowASCII; i <= _bmPrefix._highASCII; i++)
+ {
+ if (_bmPrefix._negativeASCII[i] == beforefirst)
+ table[i - _bmPrefix._lowASCII] = lDefaultAdvance;
+ else
+ table[i - _bmPrefix._lowASCII] = DefineLabel();
+ }
+
+ Ldloc(chV);
+ _ilg.Emit(OpCodes.Switch, table);
+
+ for (i = _bmPrefix._lowASCII; i <= _bmPrefix._highASCII; i++)
+ {
+ if (_bmPrefix._negativeASCII[i] == beforefirst)
+ continue;
+
+ MarkLabel(table[i - _bmPrefix._lowASCII]);
+
+ Ldc(_bmPrefix._negativeASCII[i]);
+ BrFar(lAdvance);
+ }
+
+ MarkLabel(lPartialMatch);
+
+ Ldloc(_textposV);
+ Stloc(testV);
+
+ for (i = _bmPrefix._pattern.Length - 2; i >= 0; i--)
+ {
+ Label lNext = DefineLabel();
+ int charindex;
+
+ if (!_code._rightToLeft)
+ charindex = i;
+ else
+ charindex = _bmPrefix._pattern.Length - 1 - i;
+
+ Ldloc(_textV);
+ Ldloc(testV);
+ Ldc(1);
+ Sub(_code._rightToLeft);
+ Dup();
+ Stloc(testV);
+ Callvirt(s_getcharM);
+ if (_bmPrefix._caseInsensitive)
+ CallToLower();
+
+ Ldc(_bmPrefix._pattern[charindex]);
+ Beq(lNext);
+ Ldc(_bmPrefix._positive[charindex]);
+ BrFar(lAdvance);
+
+ MarkLabel(lNext);
+
+ }
+
+ Ldthis();
+ Ldloc(testV);
+ if (_code._rightToLeft)
+ {
+ Ldc(1);
+ Add();
+ }
+ Stfld(s_textposF);
+ Ldc(1);
+ Ret();
+
+ MarkLabel(lFail);
+
+ Ldthis();
+ if (!_code._rightToLeft)
+ Ldthisfld(s_textendF);
+ else
+ Ldthisfld(s_textbegF);
+ Stfld(s_textposF);
+ Ldc(0);
+ Ret();
+ }
+ else if (_fcPrefix == null)
+ {
+ Ldc(1);
+ Ret();
+ }
+ else
+ {
+ LocalBuilder cV = _temp2V;
+ LocalBuilder chV = _tempV;
+ Label l1 = DefineLabel();
+ Label l2 = DefineLabel();
+ Label l3 = DefineLabel();
+ Label l4 = DefineLabel();
+ Label l5 = DefineLabel();
+
+ Mvfldloc(s_textposF, _textposV);
+ Mvfldloc(s_textF, _textV);
+
+ if (!_code._rightToLeft)
+ {
+ Ldthisfld(s_textendF);
+ Ldloc(_textposV);
+ }
+ else
+ {
+ Ldloc(_textposV);
+ Ldthisfld(s_textbegF);
+ }
+ Sub();
+ Stloc(cV);
+
+ Ldloc(cV);
+ Ldc(0);
+ BleFar(l4);
+
+ MarkLabel(l1);
+
+ Ldloc(cV);
+ Ldc(1);
+ Sub();
+ Stloc(cV);
+
+ if (_code._rightToLeft)
+ Leftcharnext();
+ else
+ Rightcharnext();
+
+ if (_fcPrefix.CaseInsensitive)
+ CallToLower();
+
+ if (!RegexCharClass.IsSingleton(_fcPrefix.Prefix))
+ {
+ Ldstr(_fcPrefix.Prefix);
+ Call(s_charInSetM);
+
+ BrtrueFar(l2);
+ }
+ else
+ {
+ Ldc(RegexCharClass.SingletonChar(_fcPrefix.Prefix));
+ Beq(l2);
+ }
+
+ MarkLabel(l5);
+
+ Ldloc(cV);
+ Ldc(0);
+ if (!RegexCharClass.IsSingleton(_fcPrefix.Prefix))
+ BgtFar(l1);
+ else
+ Bgt(l1);
+
+ Ldc(0);
+ BrFar(l3);
+
+ MarkLabel(l2);
+
+ /* // CURRENTLY DISABLED
+ // If for some reason we have a prefix we didn't use, use it now.
+
+ if (_bmPrefix != null) {
+ if (!_code._rightToLeft) {
+ Ldthisfld(_textendF);
+ Ldloc(_textposV);
+ }
+ else {
+ Ldloc(_textposV);
+ Ldthisfld(_textbegF);
+ }
+ Sub();
+ Ldc(_bmPrefix._pattern.Length - 1);
+ BltFar(l5);
+
+ for (int i = 1; i < _bmPrefix._pattern.Length; i++) {
+ Ldloc(_textV);
+ Ldloc(_textposV);
+ if (!_code._rightToLeft) {
+ Ldc(i - 1);
+ Add();
+ }
+ else {
+ Ldc(i);
+ Sub();
+ }
+ Callvirt(_getcharM);
+ if (!_code._rightToLeft)
+ Ldc(_bmPrefix._pattern[i]);
+ else
+ Ldc(_bmPrefix._pattern[_bmPrefix._pattern.Length - 1 - i]);
+ BneFar(l5);
+ }
+ }
+ */
+
+ Ldloc(_textposV);
+ Ldc(1);
+ Sub(_code._rightToLeft);
+ Stloc(_textposV);
+ Ldc(1);
+
+ MarkLabel(l3);
+
+ Mvlocfld(_textposV, s_textposF);
+ Ret();
+
+ MarkLabel(l4);
+ Ldc(0);
+ Ret();
+ }
+
+ }
+
+ /*
+ * Generates a very simple method that sets the _trackcount field.
+ */
+ internal void GenerateInitTrackCount()
+ {
+ Ldthis();
+ Ldc(_trackcount);
+ Stfld(s_trackcountF);
+ Ret();
+ }
+
+ /*
+ * Declares a local int
+ */
+ internal LocalBuilder DeclareInt()
+ {
+ return _ilg.DeclareLocal(typeof(int));
+ }
+
+ /*
+ * Declares a local int array
+ */
+ internal LocalBuilder DeclareIntArray()
+ {
+ return _ilg.DeclareLocal(typeof(int[]));
+ }
+
+ /*
+ * Declares a local string
+ */
+ internal LocalBuilder DeclareString()
+ {
+ return _ilg.DeclareLocal(typeof(string));
+ }
+
+ /*
+ * Generates the code for "RegexRunner.Go"
+ */
+ internal void GenerateGo()
+ {
+ // declare some locals
+
+ _textposV = DeclareInt();
+ _textV = DeclareString();
+ _trackposV = DeclareInt();
+ _trackV = DeclareIntArray();
+ _stackposV = DeclareInt();
+ _stackV = DeclareIntArray();
+ _tempV = DeclareInt();
+ _temp2V = DeclareInt();
+ _temp3V = DeclareInt();
+ _textbegV = DeclareInt();
+ _textendV = DeclareInt();
+ _textstartV = DeclareInt();
+
+ // clear some tables
+
+ _labels = null;
+ _notes = null;
+ _notecount = 0;
+
+ // globally used labels
+
+ _backtrack = DefineLabel();
+
+ // emit the code!
+
+ GenerateForwardSection();
+ GenerateMiddleSection();
+ GenerateBacktrackSection();
+ }
+
+#if DEBUG
+ /*
+ * Some simple debugging stuff
+ */
+ internal static MethodInfo s_debugWriteLine = typeof(Debug).GetMethod("WriteLine", new Type[] {typeof(string)});
+
+ /*
+ * Debug only: emit code to print out a message
+ */
+ internal void Message(string str) {
+ Ldstr(str);
+ Call(s_debugWriteLine);
+ }
+
+#endif
+
+ /*
+ * The main translation function. It translates the logic for a single opcode at
+ * the current position. The structure of this function exactly mirrors
+ * the structure of the inner loop of RegexInterpreter.Go().
+ *
+ * The C# code from RegexInterpreter.Go() that corresponds to each case is
+ * included as a comment.
+ *
+ * Note that since we're generating code, we can collapse many cases that are
+ * dealt with one-at-a-time in RegexIntepreter. We can also unroll loops that
+ * iterate over constant strings or sets.
+ */
+ internal void GenerateOneCode()
+ {
+#if DEBUG
+ if ((_options & RegexOptions.Debug) != 0) {
+ Mvlocfld(_textposV, s_textposF);
+ Mvlocfld(_trackposV, s_trackposF);
+ Mvlocfld(_stackposV, s_stackposF);
+ Ldthis();
+ Callvirt(s_dumpstateM);
+ StringBuilder sb = new StringBuilder();
+ if (_backpos > 0)
+ sb.AppendFormat("{0:D6} ", _backpos);
+ else
+ sb.Append(" ");
+ sb.Append(_code.OpcodeDescription(_codepos));
+ if (IsBack())
+ sb.Append(" Back");
+ if (IsBack2())
+ sb.Append(" Back2");
+ Message(sb.ToString());
+ }
+#endif
+
+ // Before executing any RegEx code in the unrolled loop,
+ // we try checking for the match timeout:
+
+ Ldthis();
+ Callvirt(s_checkTimeoutM);
+
+ // Now generate the IL for the RegEx code saved in _regexopcode.
+ // We unroll the loop done by the RegexCompiler creating as very long method
+ // that is longer if the pattern is longer:
+
+ switch (_regexopcode)
+ {
+ case RegexCode.Stop:
+ //: return;
+ Mvlocfld(_textposV, s_textposF); // update _textpos
+ Ret();
+ break;
+
+ case RegexCode.Nothing:
+ //: break Backward;
+ Back();
+ break;
+
+ case RegexCode.Goto:
+ //: Goto(Operand(0));
+ Goto(Operand(0));
+ break;
+
+ case RegexCode.Testref:
+ //: if (!_match.IsMatched(Operand(0)))
+ //: break Backward;
+ Ldthis();
+ Ldc(Operand(0));
+ Callvirt(s_ismatchedM);
+ BrfalseFar(_backtrack);
+ break;
+
+ case RegexCode.Lazybranch:
+ //: Track(Textpos());
+ PushTrack(_textposV);
+ Track();
+ break;
+
+ case RegexCode.Lazybranch | RegexCode.Back:
+ //: Trackframe(1);
+ //: Textto(Tracked(0));
+ //: Goto(Operand(0));
+ PopTrack();
+ Stloc(_textposV);
+ Goto(Operand(0));
+ break;
+
+ case RegexCode.Nullmark:
+ //: Stack(-1);
+ //: Track();
+ ReadyPushStack();
+ Ldc(-1);
+ DoPush();
+ TrackUnique(Stackpop);
+ break;
+
+ case RegexCode.Setmark:
+ //: Stack(Textpos());
+ //: Track();
+ PushStack(_textposV);
+ TrackUnique(Stackpop);
+ break;
+
+ case RegexCode.Nullmark | RegexCode.Back:
+ case RegexCode.Setmark | RegexCode.Back:
+ //: Stackframe(1);
+ //: break Backward;
+ PopDiscardStack();
+ Back();
+ break;
+
+ case RegexCode.Getmark:
+ //: Stackframe(1);
+ //: Track(Stacked(0));
+ //: Textto(Stacked(0));
+ ReadyPushTrack();
+ PopStack();
+ Dup();
+ Stloc(_textposV);
+ DoPush();
+
+ Track();
+ break;
+
+ case RegexCode.Getmark | RegexCode.Back:
+ //: Trackframe(1);
+ //: Stack(Tracked(0));
+ //: break Backward;
+ ReadyPushStack();
+ PopTrack();
+ DoPush();
+ Back();
+ break;
+
+ case RegexCode.Capturemark:
+ //: if (!IsMatched(Operand(1)))
+ //: break Backward;
+ //: Stackframe(1);
+ //: if (Operand(1) != -1)
+ //: TransferCapture(Operand(0), Operand(1), Stacked(0), Textpos());
+ //: else
+ //: Capture(Operand(0), Stacked(0), Textpos());
+ //: Track(Stacked(0));
+
+ //: Stackframe(1);
+ //: Capture(Operand(0), Stacked(0), Textpos());
+ //: Track(Stacked(0));
+
+ if (Operand(1) != -1)
+ {
+ Ldthis();
+ Ldc(Operand(1));
+ Callvirt(s_ismatchedM);
+ BrfalseFar(_backtrack);
+ }
+
+ PopStack();
+ Stloc(_tempV);
+
+ if (Operand(1) != -1)
+ {
+ Ldthis();
+ Ldc(Operand(0));
+ Ldc(Operand(1));
+ Ldloc(_tempV);
+ Ldloc(_textposV);
+ Callvirt(s_transferM);
+ }
+ else
+ {
+ Ldthis();
+ Ldc(Operand(0));
+ Ldloc(_tempV);
+ Ldloc(_textposV);
+ Callvirt(s_captureM);
+ }
+
+ PushTrack(_tempV);
+
+ if (Operand(0) != -1 && Operand(1) != -1)
+ TrackUnique(Capback2);
+ else
+ TrackUnique(Capback);
+
+ break;
+
+
+ case RegexCode.Capturemark | RegexCode.Back:
+ //: Trackframe(1);
+ //: Stack(Tracked(0));
+ //: Uncapture();
+ //: if (Operand(0) != -1 && Operand(1) != -1)
+ //: Uncapture();
+ //: break Backward;
+ ReadyPushStack();
+ PopTrack();
+ DoPush();
+ Ldthis();
+ Callvirt(s_uncaptureM);
+ if (Operand(0) != -1 && Operand(1) != -1)
+ {
+ Ldthis();
+ Callvirt(s_uncaptureM);
+ }
+ Back();
+ break;
+
+ case RegexCode.Branchmark:
+ //: Stackframe(1);
+ //:
+ //: if (Textpos() != Stacked(0))
+ //: { // Nonempty match -> loop now
+ //: Track(Stacked(0), Textpos()); // Save old mark, textpos
+ //: Stack(Textpos()); // Make new mark
+ //: Goto(Operand(0)); // Loop
+ //: }
+ //: else
+ //: { // Empty match -> straight now
+ //: Track2(Stacked(0)); // Save old mark
+ //: Advance(1); // Straight
+ //: }
+ //: continue Forward;
+ {
+ LocalBuilder mark = _tempV;
+ Label l1 = DefineLabel();
+
+ PopStack();
+ Dup();
+ Stloc(mark); // Stacked(0) -> temp
+ PushTrack(mark);
+ Ldloc(_textposV);
+ Beq(l1); // mark == textpos -> branch
+
+ // (matched != 0)
+
+ PushTrack(_textposV);
+ PushStack(_textposV);
+ Track();
+ Goto(Operand(0)); // Goto(Operand(0))
+
+ // else
+
+ MarkLabel(l1);
+ TrackUnique2(Branchmarkback2);
+ break;
+ }
+
+ case RegexCode.Branchmark | RegexCode.Back:
+ //: Trackframe(2);
+ //: Stackframe(1);
+ //: Textto(Tracked(1)); // Recall position
+ //: Track2(Tracked(0)); // Save old mark
+ //: Advance(1);
+ PopTrack();
+ Stloc(_textposV);
+ PopStack();
+ Pop();
+ // track spot 0 is already in place
+ TrackUnique2(Branchmarkback2);
+ Advance();
+ break;
+
+ case RegexCode.Branchmark | RegexCode.Back2:
+ //: Trackframe(1);
+ //: Stack(Tracked(0)); // Recall old mark
+ //: break Backward; // Backtrack
+ ReadyPushStack();
+ PopTrack();
+ DoPush();
+ Back();
+ break;
+
+
+ case RegexCode.Lazybranchmark:
+ //: StackPop();
+ //: int oldMarkPos = StackPeek();
+ //:
+ //: if (Textpos() != oldMarkPos) { // Nonempty match -> next loop
+ //: { // Nonempty match -> next loop
+ //: if (oldMarkPos != -1)
+ //: Track(Stacked(0), Textpos()); // Save old mark, textpos
+ //: else
+ //: TrackPush(Textpos(), Textpos());
+ //: }
+ //: else
+ //: { // Empty match -> no loop
+ //: Track2(Stacked(0)); // Save old mark
+ //: }
+ //: Advance(1);
+ //: continue Forward;
+ {
+ LocalBuilder mark = _tempV;
+ Label l1 = DefineLabel();
+ Label l2 = DefineLabel();
+ Label l3 = DefineLabel();
+
+ PopStack();
+ Dup();
+ Stloc(mark); // Stacked(0) -> temp
+
+ // if (oldMarkPos != -1)
+ Ldloc(mark);
+ Ldc(-1);
+ Beq(l2); // mark == -1 -> branch
+ PushTrack(mark);
+ Br(l3);
+ // else
+ MarkLabel(l2);
+ PushTrack(_textposV);
+ MarkLabel(l3);
+
+ // if (Textpos() != mark)
+ Ldloc(_textposV);
+ Beq(l1); // mark == textpos -> branch
+ PushTrack(_textposV);
+ Track();
+ Br(AdvanceLabel()); // Advance (near)
+ // else
+ MarkLabel(l1);
+ ReadyPushStack(); // push the current textPos on the stack.
+ // May be ignored by 'back2' or used by a true empty match.
+ Ldloc(mark);
+
+ DoPush();
+ TrackUnique2(Lazybranchmarkback2);
+
+ break;
+ }
+
+ case RegexCode.Lazybranchmark | RegexCode.Back:
+ //: Trackframe(2);
+ //: Track2(Tracked(0)); // Save old mark
+ //: Stack(Textpos()); // Make new mark
+ //: Textto(Tracked(1)); // Recall position
+ //: Goto(Operand(0)); // Loop
+
+ PopTrack();
+ Stloc(_textposV);
+ PushStack(_textposV);
+ TrackUnique2(Lazybranchmarkback2);
+ Goto(Operand(0));
+ break;
+
+ case RegexCode.Lazybranchmark | RegexCode.Back2:
+ //: Stackframe(1);
+ //: Trackframe(1);
+ //: Stack(Tracked(0)); // Recall old mark
+ //: break Backward;
+ ReadyReplaceStack(0);
+ PopTrack();
+ DoReplace();
+ Back();
+ break;
+
+ case RegexCode.Nullcount:
+ //: Stack(-1, Operand(0));
+ //: Track();
+ ReadyPushStack();
+ Ldc(-1);
+ DoPush();
+ ReadyPushStack();
+ Ldc(Operand(0));
+ DoPush();
+ TrackUnique(Stackpop2);
+ break;
+
+ case RegexCode.Setcount:
+ //: Stack(Textpos(), Operand(0));
+ //: Track();
+ PushStack(_textposV);
+ ReadyPushStack();
+ Ldc(Operand(0));
+ DoPush();
+ TrackUnique(Stackpop2);
+ break;
+
+
+ case RegexCode.Nullcount | RegexCode.Back:
+ case RegexCode.Setcount | RegexCode.Back:
+ //: Stackframe(2);
+ //: break Backward;
+ PopDiscardStack(2);
+ Back();
+ break;
+
+
+ case RegexCode.Branchcount:
+ //: Stackframe(2);
+ //: int mark = Stacked(0);
+ //: int count = Stacked(1);
+ //:
+ //: if (count >= Operand(1) || Textpos() == mark && count >= 0)
+ //: { // Max loops or empty match -> straight now
+ //: Track2(mark, count); // Save old mark, count
+ //: Advance(2); // Straight
+ //: }
+ //: else
+ //: { // Nonempty match -> count+loop now
+ //: Track(mark); // remember mark
+ //: Stack(Textpos(), count + 1); // Make new mark, incr count
+ //: Goto(Operand(0)); // Loop
+ //: }
+ //: continue Forward;
+ {
+ LocalBuilder count = _tempV;
+ LocalBuilder mark = _temp2V;
+ Label l1 = DefineLabel();
+ Label l2 = DefineLabel();
+
+ PopStack();
+ Stloc(count); // count -> temp
+ PopStack();
+ Dup();
+ Stloc(mark); // mark -> temp2
+ PushTrack(mark);
+
+ Ldloc(_textposV);
+ Bne(l1); // mark != textpos -> l1
+ Ldloc(count);
+ Ldc(0);
+ Bge(l2); // count >= 0 && mark == textpos -> l2
+
+ MarkLabel(l1);
+ Ldloc(count);
+ Ldc(Operand(1));
+ Bge(l2); // count >= Operand(1) -> l2
+
+ // else
+ PushStack(_textposV);
+ ReadyPushStack();
+ Ldloc(count); // mark already on track
+ Ldc(1);
+ Add();
+ DoPush();
+ Track();
+ Goto(Operand(0));
+
+ // if (count >= Operand(1) || Textpos() == mark)
+ MarkLabel(l2);
+ PushTrack(count); // mark already on track
+ TrackUnique2(Branchcountback2);
+ break;
+ }
+
+ case RegexCode.Branchcount | RegexCode.Back:
+ //: Trackframe(1);
+ //: Stackframe(2);
+ //: if (Stacked(1) > 0) // Positive -> can go straight
+ //: {
+ //: Textto(Stacked(0)); // Zap to mark
+ //: Track2(Tracked(0), Stacked(1) - 1); // Save old mark, old count
+ //: Advance(2); // Straight
+ //: continue Forward;
+ //: }
+ //: Stack(Tracked(0), Stacked(1) - 1); // recall old mark, old count
+ //: break Backward;
+ {
+
+ LocalBuilder count = _tempV;
+ Label l1 = DefineLabel();
+ PopStack();
+ Ldc(1);
+ Sub();
+ Dup();
+ Stloc(count);
+ Ldc(0);
+ Blt(l1);
+
+ // if (count >= 0)
+ PopStack();
+ Stloc(_textposV);
+ PushTrack(count); // Tracked(0) is alredy on the track
+ TrackUnique2(Branchcountback2);
+ Advance();
+
+ // else
+ MarkLabel(l1);
+ ReadyReplaceStack(0);
+ PopTrack();
+ DoReplace();
+ PushStack(count);
+ Back();
+ break;
+ }
+
+ case RegexCode.Branchcount | RegexCode.Back2:
+ //: Trackframe(2);
+ //: Stack(Tracked(0), Tracked(1)); // Recall old mark, old count
+ //: break Backward; // Backtrack
+
+ PopTrack();
+ Stloc(_tempV);
+ ReadyPushStack();
+ PopTrack();
+ DoPush();
+ PushStack(_tempV);
+ Back();
+ break;
+
+ case RegexCode.Lazybranchcount:
+ //: Stackframe(2);
+ //: int mark = Stacked(0);
+ //: int count = Stacked(1);
+ //:
+ //: if (count < 0)
+ //: { // Negative count -> loop now
+ //: Track2(mark); // Save old mark
+ //: Stack(Textpos(), count + 1); // Make new mark, incr count
+ //: Goto(Operand(0)); // Loop
+ //: }
+ //: else
+ //: { // Nonneg count or empty match -> straight now
+ //: Track(mark, count, Textpos()); // Save mark, count, position
+ //: }
+ {
+ LocalBuilder count = _tempV;
+ LocalBuilder mark = _temp2V;
+ Label l1 = DefineLabel();
+ Label l2 = DefineLabel();
+ Label l3 = _labels[NextCodepos()];
+
+ PopStack();
+ Stloc(count); // count -> temp
+ PopStack();
+ Stloc(mark); // mark -> temp2
+
+ Ldloc(count);
+ Ldc(0);
+ Bge(l1); // count >= 0 -> l1
+
+ // if (count < 0)
+ PushTrack(mark);
+ PushStack(_textposV);
+ ReadyPushStack();
+ Ldloc(count);
+ Ldc(1);
+ Add();
+ DoPush();
+ TrackUnique2(Lazybranchcountback2);
+ Goto(Operand(0));
+
+ // else
+ MarkLabel(l1);
+ PushTrack(mark);
+ PushTrack(count);
+ PushTrack(_textposV);
+ Track();
+ break;
+ }
+
+ case RegexCode.Lazybranchcount | RegexCode.Back:
+ //: Trackframe(3);
+ //: int mark = Tracked(0);
+ //: int textpos = Tracked(2);
+ //: if (Tracked(1) < Operand(1) && textpos != mark)
+ //: { // Under limit and not empty match -> loop
+ //: Textto(Tracked(2)); // Recall position
+ //: Stack(Textpos(), Tracked(1) + 1); // Make new mark, incr count
+ //: Track2(Tracked(0)); // Save old mark
+ //: Goto(Operand(0)); // Loop
+ //: continue Forward;
+ //: }
+ //: else
+ //: {
+ //: Stack(Tracked(0), Tracked(1)); // Recall old mark, count
+ //: break Backward; // backtrack
+ //: }
+ {
+ Label l1 = DefineLabel();
+ LocalBuilder cV = _tempV;
+ PopTrack();
+ Stloc(_textposV);
+ PopTrack();
+ Dup();
+ Stloc(cV);
+ Ldc(Operand(1));
+ Bge(l1); // Tracked(1) >= Operand(1) -> l1
+
+ Ldloc(_textposV);
+ TopTrack();
+ Beq(l1); // textpos == mark -> l1
+
+ PushStack(_textposV);
+ ReadyPushStack();
+ Ldloc(cV);
+ Ldc(1);
+ Add();
+ DoPush();
+ TrackUnique2(Lazybranchcountback2);
+ Goto(Operand(0));
+
+ MarkLabel(l1);
+ ReadyPushStack();
+ PopTrack();
+ DoPush();
+ PushStack(cV);
+ Back();
+ break;
+ }
+
+ case RegexCode.Lazybranchcount | RegexCode.Back2:
+ // <
+
+
+
+
+
+ ReadyReplaceStack(1);
+ PopTrack();
+ DoReplace();
+ ReadyReplaceStack(0);
+ TopStack();
+ Ldc(1);
+ Sub();
+ DoReplace();
+ Back();
+ break;
+
+
+ case RegexCode.Setjump:
+ //: Stack(Trackpos(), Crawlpos());
+ //: Track();
+ ReadyPushStack();
+ Ldthisfld(s_trackF);
+ Ldlen();
+ Ldloc(_trackposV);
+ Sub();
+ DoPush();
+ ReadyPushStack();
+ Ldthis();
+ Callvirt(s_crawlposM);
+ DoPush();
+ TrackUnique(Stackpop2);
+ break;
+
+ case RegexCode.Setjump | RegexCode.Back:
+ //: Stackframe(2);
+ PopDiscardStack(2);
+ Back();
+ break;
+
+
+ case RegexCode.Backjump:
+ //: Stackframe(2);
+ //: Trackto(Stacked(0));
+ //: while (Crawlpos() != Stacked(1))
+ //: Uncapture();
+ //: break Backward;
+ {
+ Label l1 = DefineLabel();
+ Label l2 = DefineLabel();
+
+ PopStack();
+ Ldthisfld(s_trackF);
+ Ldlen();
+ PopStack();
+ Sub();
+ Stloc(_trackposV);
+ Dup();
+ Ldthis();
+ Callvirt(s_crawlposM);
+ Beq(l2);
+
+ MarkLabel(l1);
+ Ldthis();
+ Callvirt(s_uncaptureM);
+ Dup();
+ Ldthis();
+ Callvirt(s_crawlposM);
+ Bne(l1);
+
+ MarkLabel(l2);
+ Pop();
+ Back();
+ break;
+ }
+
+ case RegexCode.Forejump:
+ //: Stackframe(2);
+ //: Trackto(Stacked(0));
+ //: Track(Stacked(1));
+ PopStack();
+ Stloc(_tempV);
+ Ldthisfld(s_trackF);
+ Ldlen();
+ PopStack();
+ Sub();
+ Stloc(_trackposV);
+ PushTrack(_tempV);
+ TrackUnique(Forejumpback);
+ break;
+
+ case RegexCode.Forejump | RegexCode.Back:
+ //: Trackframe(1);
+ //: while (Crawlpos() != Tracked(0))
+ //: Uncapture();
+ //: break Backward;
+ {
+ Label l1 = DefineLabel();
+ Label l2 = DefineLabel();
+
+ PopTrack();
+
+ Dup();
+ Ldthis();
+ Callvirt(s_crawlposM);
+ Beq(l2);
+
+ MarkLabel(l1);
+ Ldthis();
+ Callvirt(s_uncaptureM);
+ Dup();
+ Ldthis();
+ Callvirt(s_crawlposM);
+ Bne(l1);
+
+ MarkLabel(l2);
+ Pop();
+ Back();
+ break;
+ }
+
+ case RegexCode.Bol:
+ //: if (Leftchars() > 0 && CharAt(Textpos() - 1) != '\n')
+ //: break Backward;
+ {
+ Label l1 = _labels[NextCodepos()];
+ Ldloc(_textposV);
+ Ldloc(_textbegV);
+ Ble(l1);
+ Leftchar();
+ Ldc((int)'\n');
+ BneFar(_backtrack);
+ break;
+ }
+
+ case RegexCode.Eol:
+ //: if (Rightchars() > 0 && CharAt(Textpos()) != '\n')
+ //: break Backward;
+ {
+ Label l1 = _labels[NextCodepos()];
+ Ldloc(_textposV);
+ Ldloc(_textendV);
+ Bge(l1);
+ Rightchar();
+ Ldc((int)'\n');
+ BneFar(_backtrack);
+ break;
+ }
+
+ case RegexCode.Boundary:
+ case RegexCode.Nonboundary:
+ //: if (!IsBoundary(Textpos(), _textbeg, _textend))
+ //: break Backward;
+ Ldthis();
+ Ldloc(_textposV);
+ Ldloc(_textbegV);
+ Ldloc(_textendV);
+ Callvirt(s_isboundaryM);
+ if (Code() == RegexCode.Boundary)
+ BrfalseFar(_backtrack);
+ else
+ BrtrueFar(_backtrack);
+ break;
+
+ case RegexCode.ECMABoundary:
+ case RegexCode.NonECMABoundary:
+ //: if (!IsECMABoundary(Textpos(), _textbeg, _textend))
+ //: break Backward;
+ Ldthis();
+ Ldloc(_textposV);
+ Ldloc(_textbegV);
+ Ldloc(_textendV);
+ Callvirt(s_isECMABoundaryM);
+ if (Code() == RegexCode.ECMABoundary)
+ BrfalseFar(_backtrack);
+ else
+ BrtrueFar(_backtrack);
+ break;
+
+ case RegexCode.Beginning:
+ //: if (Leftchars() > 0)
+ //: break Backward;
+ Ldloc(_textposV);
+ Ldloc(_textbegV);
+ BgtFar(_backtrack);
+ break;
+
+ case RegexCode.Start:
+ //: if (Textpos() != Textstart())
+ //: break Backward;
+ Ldloc(_textposV);
+ Ldthisfld(s_textstartF);
+ BneFar(_backtrack);
+ break;
+
+ case RegexCode.EndZ:
+ //: if (Rightchars() > 1 || Rightchars() == 1 && CharAt(Textpos()) != '\n')
+ //: break Backward;
+ Ldloc(_textposV);
+ Ldloc(_textendV);
+ Ldc(1);
+ Sub();
+ BltFar(_backtrack);
+ Ldloc(_textposV);
+ Ldloc(_textendV);
+ Bge(_labels[NextCodepos()]);
+ Rightchar();
+ Ldc((int)'\n');
+ BneFar(_backtrack);
+ break;
+
+ case RegexCode.End:
+ //: if (Rightchars() > 0)
+ //: break Backward;
+ Ldloc(_textposV);
+ Ldloc(_textendV);
+ BltFar(_backtrack);
+ break;
+
+ case RegexCode.One:
+ case RegexCode.Notone:
+ case RegexCode.Set:
+ case RegexCode.One | RegexCode.Rtl:
+ case RegexCode.Notone | RegexCode.Rtl:
+ case RegexCode.Set | RegexCode.Rtl:
+ case RegexCode.One | RegexCode.Ci:
+ case RegexCode.Notone | RegexCode.Ci:
+ case RegexCode.Set | RegexCode.Ci:
+ case RegexCode.One | RegexCode.Ci | RegexCode.Rtl:
+ case RegexCode.Notone | RegexCode.Ci | RegexCode.Rtl:
+ case RegexCode.Set | RegexCode.Ci | RegexCode.Rtl:
+
+ //: if (Rightchars() < 1 || Rightcharnext() != (char)Operand(0))
+ //: break Backward;
+ Ldloc(_textposV);
+
+ if (!IsRtl())
+ {
+ Ldloc(_textendV);
+ BgeFar(_backtrack);
+ Rightcharnext();
+ }
+ else
+ {
+ Ldloc(_textbegV);
+ BleFar(_backtrack);
+ Leftcharnext();
+ }
+
+ if (IsCi())
+ CallToLower();
+
+ if (Code() == RegexCode.Set)
+ {
+
+ Ldstr(_strings[Operand(0)]);
+ Call(s_charInSetM);
+
+ BrfalseFar(_backtrack);
+ }
+ else
+ {
+ Ldc(Operand(0));
+ if (Code() == RegexCode.One)
+ BneFar(_backtrack);
+ else
+ BeqFar(_backtrack);
+ }
+ break;
+
+ case RegexCode.Multi:
+ case RegexCode.Multi | RegexCode.Ci:
+ //
+ // <
+ //: String Str = _strings[Operand(0)];
+ //: int i, c;
+ //: if (Rightchars() < (c = Str.Length))
+ //: break Backward;
+ //: for (i = 0; c > 0; i++, c--)
+ //: if (Str[i] != Rightcharnext())
+ //: break Backward;
+ {
+ int i;
+ string str;
+
+ str = _strings[Operand(0)];
+
+ Ldc(str.Length);
+ Ldloc(_textendV);
+ Ldloc(_textposV);
+ Sub();
+ BgtFar(_backtrack);
+
+ // unroll the string
+ for (i = 0; i < str.Length; i++)
+ {
+ Ldloc(_textV);
+ Ldloc(_textposV);
+ if (i != 0)
+ {
+ Ldc(i);
+ Add();
+ }
+ Callvirt(s_getcharM);
+ if (IsCi())
+ CallToLower();
+
+ Ldc((int)str[i]);
+ BneFar(_backtrack);
+ }
+
+ Ldloc(_textposV);
+ Ldc(str.Length);
+ Add();
+ Stloc(_textposV);
+ break;
+ }
+
+
+ case RegexCode.Multi | RegexCode.Rtl:
+ case RegexCode.Multi | RegexCode.Ci | RegexCode.Rtl:
+ //: String Str = _strings[Operand(0)];
+ //: int c;
+ //: if (Leftchars() < (c = Str.Length))
+ //: break Backward;
+ //: while (c > 0)
+ //: if (Str[--c] != Leftcharnext())
+ //: break Backward;
+ {
+ int i;
+ string str;
+
+ str = _strings[Operand(0)];
+
+ Ldc(str.Length);
+ Ldloc(_textposV);
+ Ldloc(_textbegV);
+ Sub();
+ BgtFar(_backtrack);
+
+ // unroll the string
+ for (i = str.Length; i > 0;)
+ {
+ i--;
+ Ldloc(_textV);
+ Ldloc(_textposV);
+ Ldc(str.Length - i);
+ Sub();
+ Callvirt(s_getcharM);
+ if (IsCi())
+ {
+ CallToLower();
+ }
+ Ldc((int)str[i]);
+ BneFar(_backtrack);
+ }
+
+ Ldloc(_textposV);
+ Ldc(str.Length);
+ Sub();
+ Stloc(_textposV);
+
+ break;
+ }
+
+ case RegexCode.Ref:
+ case RegexCode.Ref | RegexCode.Rtl:
+ case RegexCode.Ref | RegexCode.Ci:
+ case RegexCode.Ref | RegexCode.Ci | RegexCode.Rtl:
+ //: int capnum = Operand(0);
+ //: int j, c;
+ //: if (!_match.IsMatched(capnum)) {
+ //: if (!RegexOptions.ECMAScript)
+ //: break Backward;
+ //: } else {
+ //: if (Rightchars() < (c = _match.MatchLength(capnum)))
+ //: break Backward;
+ //: for (j = _match.MatchIndex(capnum); c > 0; j++, c--)
+ //: if (CharAt(j) != Rightcharnext())
+ //: break Backward;
+ //: }
+ {
+ LocalBuilder lenV = _tempV;
+ LocalBuilder indexV = _temp2V;
+ Label l1 = DefineLabel();
+
+ Ldthis();
+ Ldc(Operand(0));
+ Callvirt(s_ismatchedM);
+ if ((_options & RegexOptions.ECMAScript) != 0)
+ Brfalse(AdvanceLabel());
+ else
+ BrfalseFar(_backtrack); // !IsMatched() -> back
+
+ Ldthis();
+ Ldc(Operand(0));
+ Callvirt(s_matchlengthM);
+ Dup();
+ Stloc(lenV);
+ if (!IsRtl())
+ {
+ Ldloc(_textendV);
+ Ldloc(_textposV);
+ }
+ else
+ {
+ Ldloc(_textposV);
+ Ldloc(_textbegV);
+ }
+ Sub();
+ BgtFar(_backtrack); // Matchlength() > Rightchars() -> back
+
+ Ldthis();
+ Ldc(Operand(0));
+ Callvirt(s_matchindexM);
+ if (!IsRtl())
+ {
+ Ldloc(lenV);
+ Add(IsRtl());
+ }
+ Stloc(indexV); // index += len
+
+ Ldloc(_textposV);
+ Ldloc(lenV);
+ Add(IsRtl());
+ Stloc(_textposV); // texpos += len
+
+ MarkLabel(l1);
+ Ldloc(lenV);
+ Ldc(0);
+ Ble(AdvanceLabel());
+ Ldloc(_textV);
+ Ldloc(indexV);
+ Ldloc(lenV);
+ if (IsRtl())
+ {
+ Ldc(1);
+ Sub();
+ Dup();
+ Stloc(lenV);
+ }
+ Sub(IsRtl());
+ Callvirt(s_getcharM);
+ if (IsCi())
+ CallToLower();
+
+ Ldloc(_textV);
+ Ldloc(_textposV);
+ Ldloc(lenV);
+ if (!IsRtl())
+ {
+ Dup();
+ Ldc(1);
+ Sub();
+ Stloc(lenV);
+ }
+ Sub(IsRtl());
+ Callvirt(s_getcharM);
+ if (IsCi())
+ CallToLower();
+
+ Beq(l1);
+ Back();
+ break;
+ }
+
+
+ case RegexCode.Onerep:
+ case RegexCode.Notonerep:
+ case RegexCode.Setrep:
+ case RegexCode.Onerep | RegexCode.Rtl:
+ case RegexCode.Notonerep | RegexCode.Rtl:
+ case RegexCode.Setrep | RegexCode.Rtl:
+ case RegexCode.Onerep | RegexCode.Ci:
+ case RegexCode.Notonerep | RegexCode.Ci:
+ case RegexCode.Setrep | RegexCode.Ci:
+ case RegexCode.Onerep | RegexCode.Ci | RegexCode.Rtl:
+ case RegexCode.Notonerep | RegexCode.Ci | RegexCode.Rtl:
+ case RegexCode.Setrep | RegexCode.Ci | RegexCode.Rtl:
+ //: int c = Operand(1);
+ //: if (Rightchars() < c)
+ //: break Backward;
+ //: char ch = (char)Operand(0);
+ //: while (c-- > 0)
+ //: if (Rightcharnext() != ch)
+ //: break Backward;
+ {
+ LocalBuilder lenV = _tempV;
+ Label l1 = DefineLabel();
+
+ int c = Operand(1);
+
+ if (c == 0)
+ break;
+
+ Ldc(c);
+ if (!IsRtl())
+ {
+ Ldloc(_textendV);
+ Ldloc(_textposV);
+ }
+ else
+ {
+ Ldloc(_textposV);
+ Ldloc(_textbegV);
+ }
+ Sub();
+ BgtFar(_backtrack); // Matchlength() > Rightchars() -> back
+
+ Ldloc(_textposV);
+ Ldc(c);
+ Add(IsRtl());
+ Stloc(_textposV); // texpos += len
+
+ Ldc(c);
+ Stloc(lenV);
+
+ MarkLabel(l1);
+ Ldloc(_textV);
+ Ldloc(_textposV);
+ Ldloc(lenV);
+ if (IsRtl())
+ {
+ Ldc(1);
+ Sub();
+ Dup();
+ Stloc(lenV);
+ Add();
+ }
+ else
+ {
+ Dup();
+ Ldc(1);
+ Sub();
+ Stloc(lenV);
+ Sub();
+ }
+ Callvirt(s_getcharM);
+ if (IsCi())
+ CallToLower();
+
+ if (Code() == RegexCode.Setrep)
+ {
+ Ldstr(_strings[Operand(0)]);
+ Call(s_charInSetM);
+
+ BrfalseFar(_backtrack);
+ }
+ else
+ {
+ Ldc(Operand(0));
+ if (Code() == RegexCode.Onerep)
+ BneFar(_backtrack);
+ else
+ BeqFar(_backtrack);
+ }
+ Ldloc(lenV);
+ Ldc(0);
+ if (Code() == RegexCode.Setrep)
+ BgtFar(l1);
+ else
+ Bgt(l1);
+ break;
+ }
+
+
+ case RegexCode.Oneloop:
+ case RegexCode.Notoneloop:
+ case RegexCode.Setloop:
+ case RegexCode.Oneloop | RegexCode.Rtl:
+ case RegexCode.Notoneloop | RegexCode.Rtl:
+ case RegexCode.Setloop | RegexCode.Rtl:
+ case RegexCode.Oneloop | RegexCode.Ci:
+ case RegexCode.Notoneloop | RegexCode.Ci:
+ case RegexCode.Setloop | RegexCode.Ci:
+ case RegexCode.Oneloop | RegexCode.Ci | RegexCode.Rtl:
+ case RegexCode.Notoneloop | RegexCode.Ci | RegexCode.Rtl:
+ case RegexCode.Setloop | RegexCode.Ci | RegexCode.Rtl:
+ //: int c = Operand(1);
+ //: if (c > Rightchars())
+ //: c = Rightchars();
+ //: char ch = (char)Operand(0);
+ //: int i;
+ //: for (i = c; i > 0; i--)
+ //: {
+ //: if (Rightcharnext() != ch)
+ //: {
+ //: Leftnext();
+ //: break;
+ //: }
+ //: }
+ //: if (c > i)
+ //: Track(c - i - 1, Textpos() - 1);
+
+ {
+ LocalBuilder cV = _tempV;
+ LocalBuilder lenV = _temp2V;
+ Label l1 = DefineLabel();
+ Label l2 = DefineLabel();
+
+ int c = Operand(1);
+
+ if (c == 0)
+ break;
+ if (!IsRtl())
+ {
+ Ldloc(_textendV);
+ Ldloc(_textposV);
+ }
+ else
+ {
+ Ldloc(_textposV);
+ Ldloc(_textbegV);
+ }
+ Sub();
+ if (c != int.MaxValue)
+ {
+ Label l4 = DefineLabel();
+ Dup();
+ Ldc(c);
+ Blt(l4);
+ Pop();
+ Ldc(c);
+ MarkLabel(l4);
+ }
+ Dup();
+ Stloc(lenV);
+ Ldc(1);
+ Add();
+ Stloc(cV);
+
+ MarkLabel(l1);
+ Ldloc(cV);
+ Ldc(1);
+ Sub();
+ Dup();
+ Stloc(cV);
+ Ldc(0);
+ if (Code() == RegexCode.Setloop)
+ BleFar(l2);
+ else
+ Ble(l2);
+
+ if (IsRtl())
+ Leftcharnext();
+ else
+ Rightcharnext();
+ if (IsCi())
+ CallToLower();
+
+ if (Code() == RegexCode.Setloop)
+ {
+ Ldstr(_strings[Operand(0)]);
+ Call(s_charInSetM);
+
+ BrtrueFar(l1);
+ }
+ else
+ {
+ Ldc(Operand(0));
+ if (Code() == RegexCode.Oneloop)
+ Beq(l1);
+ else
+ Bne(l1);
+ }
+
+ Ldloc(_textposV);
+ Ldc(1);
+ Sub(IsRtl());
+ Stloc(_textposV);
+
+ MarkLabel(l2);
+ Ldloc(lenV);
+ Ldloc(cV);
+ Ble(AdvanceLabel());
+
+ ReadyPushTrack();
+ Ldloc(lenV);
+ Ldloc(cV);
+ Sub();
+ Ldc(1);
+ Sub();
+ DoPush();
+
+ ReadyPushTrack();
+ Ldloc(_textposV);
+ Ldc(1);
+ Sub(IsRtl());
+ DoPush();
+
+ Track();
+ break;
+ }
+
+ case RegexCode.Oneloop | RegexCode.Back:
+ case RegexCode.Notoneloop | RegexCode.Back:
+ case RegexCode.Setloop | RegexCode.Back:
+ case RegexCode.Oneloop | RegexCode.Rtl | RegexCode.Back:
+ case RegexCode.Notoneloop | RegexCode.Rtl | RegexCode.Back:
+ case RegexCode.Setloop | RegexCode.Rtl | RegexCode.Back:
+ case RegexCode.Oneloop | RegexCode.Ci | RegexCode.Back:
+ case RegexCode.Notoneloop | RegexCode.Ci | RegexCode.Back:
+ case RegexCode.Setloop | RegexCode.Ci | RegexCode.Back:
+ case RegexCode.Oneloop | RegexCode.Ci | RegexCode.Rtl | RegexCode.Back:
+ case RegexCode.Notoneloop | RegexCode.Ci | RegexCode.Rtl | RegexCode.Back:
+ case RegexCode.Setloop | RegexCode.Ci | RegexCode.Rtl | RegexCode.Back:
+ //: Trackframe(2);
+ //: int i = Tracked(0);
+ //: int pos = Tracked(1);
+ //: Textto(pos);
+ //: if (i > 0)
+ //: Track(i - 1, pos - 1);
+ //: Advance(2);
+ PopTrack();
+ Stloc(_textposV);
+ PopTrack();
+ Stloc(_tempV);
+ Ldloc(_tempV);
+ Ldc(0);
+ BleFar(AdvanceLabel());
+ ReadyPushTrack();
+ Ldloc(_tempV);
+ Ldc(1);
+ Sub();
+ DoPush();
+ ReadyPushTrack();
+ Ldloc(_textposV);
+ Ldc(1);
+ Sub(IsRtl());
+ DoPush();
+ Trackagain();
+ Advance();
+ break;
+
+ case RegexCode.Onelazy:
+ case RegexCode.Notonelazy:
+ case RegexCode.Setlazy:
+ case RegexCode.Onelazy | RegexCode.Rtl:
+ case RegexCode.Notonelazy | RegexCode.Rtl:
+ case RegexCode.Setlazy | RegexCode.Rtl:
+ case RegexCode.Onelazy | RegexCode.Ci:
+ case RegexCode.Notonelazy | RegexCode.Ci:
+ case RegexCode.Setlazy | RegexCode.Ci:
+ case RegexCode.Onelazy | RegexCode.Ci | RegexCode.Rtl:
+ case RegexCode.Notonelazy | RegexCode.Ci | RegexCode.Rtl:
+ case RegexCode.Setlazy | RegexCode.Ci | RegexCode.Rtl:
+ //: int c = Operand(1);
+ //: if (c > Rightchars())
+ //: c = Rightchars();
+ //: if (c > 0)
+ //: Track(c - 1, Textpos());
+ {
+ LocalBuilder cV = _tempV;
+
+ int c = Operand(1);
+
+ if (c == 0)
+ break;
+
+ if (!IsRtl())
+ {
+ Ldloc(_textendV);
+ Ldloc(_textposV);
+ }
+ else
+ {
+ Ldloc(_textposV);
+ Ldloc(_textbegV);
+ }
+ Sub();
+ if (c != int.MaxValue)
+ {
+ Label l4 = DefineLabel();
+ Dup();
+ Ldc(c);
+ Blt(l4);
+ Pop();
+ Ldc(c);
+ MarkLabel(l4);
+ }
+ Dup();
+ Stloc(cV);
+ Ldc(0);
+ Ble(AdvanceLabel());
+ ReadyPushTrack();
+ Ldloc(cV);
+ Ldc(1);
+ Sub();
+ DoPush();
+ PushTrack(_textposV);
+ Track();
+ break;
+ }
+
+ case RegexCode.Onelazy | RegexCode.Back:
+ case RegexCode.Notonelazy | RegexCode.Back:
+ case RegexCode.Setlazy | RegexCode.Back:
+ case RegexCode.Onelazy | RegexCode.Rtl | RegexCode.Back:
+ case RegexCode.Notonelazy | RegexCode.Rtl | RegexCode.Back:
+ case RegexCode.Setlazy | RegexCode.Rtl | RegexCode.Back:
+ case RegexCode.Onelazy | RegexCode.Ci | RegexCode.Back:
+ case RegexCode.Notonelazy | RegexCode.Ci | RegexCode.Back:
+ case RegexCode.Setlazy | RegexCode.Ci | RegexCode.Back:
+ case RegexCode.Onelazy | RegexCode.Ci | RegexCode.Rtl | RegexCode.Back:
+ case RegexCode.Notonelazy | RegexCode.Ci | RegexCode.Rtl | RegexCode.Back:
+ case RegexCode.Setlazy | RegexCode.Ci | RegexCode.Rtl | RegexCode.Back:
+ //: Trackframe(2);
+ //: int pos = Tracked(1);
+ //: Textto(pos);
+ //: if (Rightcharnext() != (char)Operand(0))
+ //: break Backward;
+ //: int i = Tracked(0);
+ //: if (i > 0)
+ //: Track(i - 1, pos + 1);
+
+ PopTrack();
+ Stloc(_textposV);
+ PopTrack();
+ Stloc(_temp2V);
+
+ if (!IsRtl())
+ Rightcharnext();
+ else
+ Leftcharnext();
+
+ if (IsCi())
+ CallToLower();
+
+ if (Code() == RegexCode.Setlazy)
+ {
+ Ldstr(_strings[Operand(0)]);
+ Call(s_charInSetM);
+
+ BrfalseFar(_backtrack);
+ }
+ else
+ {
+ Ldc(Operand(0));
+ if (Code() == RegexCode.Onelazy)
+ BneFar(_backtrack);
+ else
+ BeqFar(_backtrack);
+ }
+
+ Ldloc(_temp2V);
+ Ldc(0);
+ BleFar(AdvanceLabel());
+ ReadyPushTrack();
+ Ldloc(_temp2V);
+ Ldc(1);
+ Sub();
+ DoPush();
+ PushTrack(_textposV);
+ Trackagain();
+ Advance();
+ break;
+
+ default:
+ throw new NotImplementedException(SR.UnimplementedState);
+ }
+ }
+ }
+}
diff --git a/src/System.Text.RegularExpressions/src/System/Text/RegularExpressions/RegexLWCGCompiler.cs b/src/System.Text.RegularExpressions/src/System/Text/RegularExpressions/RegexLWCGCompiler.cs
new file mode 100644
index 0000000000..d37ab1a0bd
--- /dev/null
+++ b/src/System.Text.RegularExpressions/src/System/Text/RegularExpressions/RegexLWCGCompiler.cs
@@ -0,0 +1,68 @@
+// 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.Reflection;
+using System.Reflection.Emit;
+using System.Globalization;
+
+namespace System.Text.RegularExpressions
+{
+ internal class RegexLWCGCompiler : RegexCompiler
+ {
+ private static int s_regexCount = 0;
+ private static Type[] s_paramTypes = new Type[] { typeof(RegexRunner) };
+
+ internal RegexLWCGCompiler()
+ {
+ }
+
+ /*
+ * The top-level driver. Initializes everything then calls the Generate* methods.
+ */
+ internal RegexRunnerFactory FactoryInstanceFromCode(RegexCode code, RegexOptions options)
+ {
+ _code = code;
+ _codes = code._codes;
+ _strings = code._strings;
+ _fcPrefix = code._fcPrefix;
+ _bmPrefix = code._bmPrefix;
+ _anchors = code._anchors;
+ _trackcount = code._trackcount;
+ _options = options;
+
+ // pick a unique number for the methods we generate
+ int regexnum = Interlocked.Increment(ref s_regexCount);
+ string regexnumString = regexnum.ToString(CultureInfo.InvariantCulture);
+
+ DynamicMethod goMethod = DefineDynamicMethod("Go" + regexnumString, null, typeof(CompiledRegexRunner));
+ GenerateGo();
+
+ DynamicMethod firstCharMethod = DefineDynamicMethod("FindFirstChar" + regexnumString, typeof(bool), typeof(CompiledRegexRunner));
+ GenerateFindFirstChar();
+
+ DynamicMethod trackCountMethod = DefineDynamicMethod("InitTrackCount" + regexnumString, null, typeof(CompiledRegexRunner));
+ GenerateInitTrackCount();
+
+ return new CompiledRegexRunnerFactory(goMethod, firstCharMethod, trackCountMethod);
+ }
+
+ /*
+ * Begins the definition of a new method (no args) with a specified return value
+ */
+ internal DynamicMethod DefineDynamicMethod(string methname, Type returntype, Type hostType)
+ {
+ // We're claiming that these are static methods, but really they are instance methods.
+ // By giving them a parameter which represents "this", we're tricking them into
+ // being instance methods.
+
+ MethodAttributes attribs = MethodAttributes.Public | MethodAttributes.Static;
+ CallingConventions conventions = CallingConventions.Standard;
+
+ DynamicMethod dm = new DynamicMethod(methname, attribs, conventions, returntype, s_paramTypes, hostType, false /*skipVisibility*/);
+ _ilg = dm.GetILGenerator();
+ return dm;
+ }
+ }
+}
diff --git a/src/System.Text.RegularExpressions/tests/CaptureCollectionTests.netcoreapp.cs b/src/System.Text.RegularExpressions/tests/CaptureCollectionTests2.cs
index cc842597f7..5348e1af12 100644
--- a/src/System.Text.RegularExpressions/tests/CaptureCollectionTests.netcoreapp.cs
+++ b/src/System.Text.RegularExpressions/tests/CaptureCollectionTests2.cs
@@ -164,6 +164,7 @@ namespace System.Text.RegularExpressions.Tests
}
[Fact]
+ [SkipOnTargetFramework(TargetFrameworkMonikers.UapAot)]
public static void DebuggerAttributeTests()
{
CaptureCollection col = CreateCollection();
@@ -175,6 +176,7 @@ namespace System.Text.RegularExpressions.Tests
}
[Fact]
+ [SkipOnTargetFramework(TargetFrameworkMonikers.UapAot)]
public static void DebuggerAttributeTests_Null()
{
TargetInvocationException ex = Assert.Throws<TargetInvocationException>(() => DebuggerAttributes.ValidateDebuggerTypeProxyProperties(typeof(CaptureCollection), null));
diff --git a/src/System.Text.RegularExpressions/tests/GroupCollectionTests.netcoreapp.cs b/src/System.Text.RegularExpressions/tests/GroupCollectionTests2.cs
index 8442cb81f6..0f5d46cb17 100644
--- a/src/System.Text.RegularExpressions/tests/GroupCollectionTests.netcoreapp.cs
+++ b/src/System.Text.RegularExpressions/tests/GroupCollectionTests2.cs
@@ -161,6 +161,7 @@ namespace System.Text.RegularExpressions.Tests
}
[Fact]
+ [SkipOnTargetFramework(TargetFrameworkMonikers.UapAot)]
public static void DebuggerAttributeTests()
{
GroupCollection col = CreateCollection();
@@ -172,6 +173,7 @@ namespace System.Text.RegularExpressions.Tests
}
[Fact]
+ [SkipOnTargetFramework(TargetFrameworkMonikers.UapAot)]
public static void DebuggerAttributeTests_Null()
{
TargetInvocationException ex = Assert.Throws<TargetInvocationException>(() => DebuggerAttributes.ValidateDebuggerTypeProxyProperties(typeof(GroupCollection), null));
diff --git a/src/System.Text.RegularExpressions/tests/MatchCollectionTests.netcoreapp.cs b/src/System.Text.RegularExpressions/tests/MatchCollectionTests2.cs
index 945a5b680a..02f118f575 100644
--- a/src/System.Text.RegularExpressions/tests/MatchCollectionTests.netcoreapp.cs
+++ b/src/System.Text.RegularExpressions/tests/MatchCollectionTests2.cs
@@ -158,6 +158,7 @@ namespace System.Text.RegularExpressions.Tests
}
[Fact]
+ [SkipOnTargetFramework(TargetFrameworkMonikers.UapAot)]
public static void DebuggerAttributeTests()
{
MatchCollection col = CreateCollection();
@@ -169,6 +170,7 @@ namespace System.Text.RegularExpressions.Tests
}
[Fact]
+ [SkipOnTargetFramework(TargetFrameworkMonikers.UapAot)]
public static void DebuggerAttributeTests_Null()
{
TargetInvocationException ex = Assert.Throws<TargetInvocationException>(() => DebuggerAttributes.ValidateDebuggerTypeProxyProperties(typeof(MatchCollection), null));
diff --git a/src/System.Text.RegularExpressions/tests/Regex.Ctor.Tests.cs b/src/System.Text.RegularExpressions/tests/Regex.Ctor.Tests.cs
index 16d121ee7d..fc63daef93 100644
--- a/src/System.Text.RegularExpressions/tests/Regex.Ctor.Tests.cs
+++ b/src/System.Text.RegularExpressions/tests/Regex.Ctor.Tests.cs
@@ -3,13 +3,14 @@
// See the LICENSE file in the project root for more information.
using System.Collections.Generic;
+using System.Diagnostics;
using System.Runtime.InteropServices;
using System.Threading;
using Xunit;
namespace System.Text.RegularExpressions.Tests
{
- public class RegexConstructorTests
+ public class RegexConstructorTests : RemoteExecutorTestBase
{
public static IEnumerable<object[]> Ctor_TestData()
{
@@ -76,6 +77,30 @@ namespace System.Text.RegularExpressions.Tests
}
[Fact]
+ public static void StaticCtor_InvalidTimeoutObject_ExceptionThrown()
+ {
+ RemoteInvoke(() =>
+ {
+ AppDomain.CurrentDomain.SetData(RegexHelpers.DefaultMatchTimeout_ConfigKeyName, true);
+ Assert.Throws<TypeInitializationException>(() => Regex.InfiniteMatchTimeout);
+
+ return SuccessExitCode;
+ });
+ }
+
+ [Fact]
+ public static void StaticCtor_InvalidTimeoutRange_ExceptionThrown()
+ {
+ RemoteInvoke(() =>
+ {
+ AppDomain.CurrentDomain.SetData(RegexHelpers.DefaultMatchTimeout_ConfigKeyName, TimeSpan.Zero);
+ Assert.Throws<TypeInitializationException>(() => Regex.InfiniteMatchTimeout);
+
+ return SuccessExitCode;
+ });
+ }
+
+ [Fact]
public void CacheSize_Get()
{
Assert.Equal(15, Regex.CacheSize);
diff --git a/src/System.Text.RegularExpressions/tests/Regex.Match.Tests.cs b/src/System.Text.RegularExpressions/tests/Regex.Match.Tests.cs
index 43d51f009b..672f29ce88 100644
--- a/src/System.Text.RegularExpressions/tests/Regex.Match.Tests.cs
+++ b/src/System.Text.RegularExpressions/tests/Regex.Match.Tests.cs
@@ -5,6 +5,7 @@
using System.Collections.Generic;
using System.Diagnostics;
using System.Globalization;
+using System.Linq;
using Xunit;
namespace System.Text.RegularExpressions.Tests
@@ -266,6 +267,7 @@ namespace System.Text.RegularExpressions.Tests
[Theory]
[MemberData(nameof(Match_Basic_TestData))]
+ [MemberData(nameof(RegexCompilationHelper.TransformRegexOptions), nameof(Match_Basic_TestData), 2, MemberType = typeof(RegexCompilationHelper))]
public void Match(string pattern, string input, RegexOptions options, int beginning, int length, bool expectedSuccess, string expectedValue)
{
bool isDefaultStart = RegexHelpers.IsDefaultStart(input, options, beginning);
@@ -328,6 +330,21 @@ namespace System.Text.RegularExpressions.Tests
Assert.Equal("a", match.Value);
}
+ [Fact]
+ public void Match_Timeout_Throws()
+ {
+ RemoteInvoke(() =>
+ {
+ const string Pattern = @"^([0-9a-zA-Z]([-.\w]*[0-9a-zA-Z])*@(([0-9a-zA-Z])+([-\w]*[0-9a-zA-Z])*\.)+[a-zA-Z]{2,9})$";
+ string input = new string('a', 50) + "@a.a";
+
+ AppDomain.CurrentDomain.SetData(RegexHelpers.DefaultMatchTimeout_ConfigKeyName, TimeSpan.FromMilliseconds(100));
+ Assert.Throws<RegexMatchTimeoutException>(() => new Regex(Pattern).Match(input));
+
+ return SuccessExitCode;
+ });
+ }
+
public static IEnumerable<object[]> Match_Advanced_TestData()
{
// \B special character escape: ".*\\B(SUCCESS)\\B.*"
@@ -596,7 +613,7 @@ namespace System.Text.RegularExpressions.Tests
bool isDefaultCount = RegexHelpers.IsDefaultStart(input, options, length);
if (options == RegexOptions.None)
{
- if (isDefaultStart && isDefaultCount)
+ if (isDefaultStart && isDefaultCount)
{
// Use Match(string) or Match(string, string)
VerifyMatch(new Regex(pattern).Match(input), true, expected);
diff --git a/src/System.Text.RegularExpressions/tests/Regex.Replace.Tests.cs b/src/System.Text.RegularExpressions/tests/Regex.Replace.Tests.cs
index 44f4d94573..0cbf545bd7 100644
--- a/src/System.Text.RegularExpressions/tests/Regex.Replace.Tests.cs
+++ b/src/System.Text.RegularExpressions/tests/Regex.Replace.Tests.cs
@@ -3,6 +3,7 @@
// See the LICENSE file in the project root for more information.
using System.Collections.Generic;
+using System.Linq;
using Xunit;
namespace System.Text.RegularExpressions.Tests
@@ -109,6 +110,7 @@ namespace System.Text.RegularExpressions.Tests
[Theory]
[MemberData(nameof(Replace_String_TestData))]
+ [MemberData(nameof(RegexCompilationHelper.TransformRegexOptions), nameof(Replace_String_TestData), 3, MemberType = typeof(RegexCompilationHelper))]
public void Replace(string pattern, string input, string replacement, RegexOptions options, int count, int start, string expected)
{
bool isDefaultStart = RegexHelpers.IsDefaultStart(input, options, start);
@@ -178,6 +180,7 @@ namespace System.Text.RegularExpressions.Tests
[Theory]
[MemberData(nameof(Replace_MatchEvaluator_TestData))]
+ [MemberData(nameof(RegexCompilationHelper.TransformRegexOptions), nameof(Replace_MatchEvaluator_TestData), 3, MemberType = typeof(RegexCompilationHelper))]
public void Replace(string pattern, string input, MatchEvaluator evaluator, RegexOptions options, int count, int start, string expected)
{
bool isDefaultStart = RegexHelpers.IsDefaultStart(input, options, start);
diff --git a/src/System.Text.RegularExpressions/tests/Regex.Split.Tests.cs b/src/System.Text.RegularExpressions/tests/Regex.Split.Tests.cs
index 5d90f21871..00df350bf5 100644
--- a/src/System.Text.RegularExpressions/tests/Regex.Split.Tests.cs
+++ b/src/System.Text.RegularExpressions/tests/Regex.Split.Tests.cs
@@ -9,7 +9,7 @@ namespace System.Text.RegularExpressions.Tests
{
public class RegexSplitTests
{
- public static IEnumerable<object[]> Split_TestData()
+ public static IEnumerable<object[]> Split_NonCompiled_TestData()
{
yield return new object[] { " ", "word0 word1 word2 word3", RegexOptions.None, 32, 0, new string[] { "word0", "word1", "word2", "word3" } };
@@ -50,7 +50,8 @@ namespace System.Text.RegularExpressions.Tests
}
[Theory]
- [MemberData(nameof(Split_TestData))]
+ [MemberData(nameof(Split_NonCompiled_TestData))]
+ [MemberData(nameof(RegexCompilationHelper.TransformRegexOptions), nameof(Split_NonCompiled_TestData), 2, MemberType = typeof(RegexCompilationHelper))]
public void Split(string pattern, string input, RegexOptions options, int count, int start, string[] expected)
{
bool isDefaultStart = RegexHelpers.IsDefaultStart(input, options, start);
diff --git a/src/System.Text.RegularExpressions/tests/Regex.Tests.Common.cs b/src/System.Text.RegularExpressions/tests/Regex.Tests.Common.cs
index 0ec9c4462f..45d87187dd 100644
--- a/src/System.Text.RegularExpressions/tests/Regex.Tests.Common.cs
+++ b/src/System.Text.RegularExpressions/tests/Regex.Tests.Common.cs
@@ -6,6 +6,8 @@ namespace System.Text.RegularExpressions.Tests
{
public static class RegexHelpers
{
+ public const string DefaultMatchTimeout_ConfigKeyName = "REGEX_DEFAULT_MATCH_TIMEOUT";
+
public static bool IsDefaultCount(string input, RegexOptions options, int count)
{
if ((options & RegexOptions.RightToLeft) != 0)
diff --git a/src/System.Text.RegularExpressions/tests/RegexCompilationHelper.cs b/src/System.Text.RegularExpressions/tests/RegexCompilationHelper.cs
new file mode 100644
index 0000000000..5a20e154f2
--- /dev/null
+++ b/src/System.Text.RegularExpressions/tests/RegexCompilationHelper.cs
@@ -0,0 +1,52 @@
+// 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.Linq;
+using System.Reflection;
+
+namespace System.Text.RegularExpressions.Tests
+{
+ public class RegexCompilationHelper
+ {
+ /// <summary>
+ /// Adds RegexOptions.Compiled to the RegexOptions of each item in a given array of test data.
+ /// </summary>
+ /// <param name="regexOptionsArrayIndex">The index in the object array of the CompilationOptions enum.</param>
+ /// <returns></returns>
+ public static IEnumerable<object[]> TransformRegexOptions(string testDataMethodName, int regexOptionsArrayIndex)
+ {
+ // On Uap or NetNative the compiled feature isn't currently enabled,
+ // therefore we don't need the additional test data.
+ if (PlatformDetection.IsUap)
+ {
+ return Enumerable.Empty<object[]>();
+ }
+
+ IEnumerable<Type> types = Assembly.GetExecutingAssembly().GetTypes().Where(t => t.Namespace == typeof(RegexCompilationHelper).Namespace);
+ foreach (Type type in types)
+ {
+ IEnumerable<object[]> result = InvokeTransform(type, testDataMethodName, regexOptionsArrayIndex);
+ if (result != null)
+ {
+ return result;
+ }
+ }
+
+ throw new Exception($"Test method '{testDataMethodName}' not found");
+ }
+
+ private static IEnumerable<object[]> InvokeTransform(Type type, string methodName, int regexOptionsArrayIndex)
+ {
+ MethodInfo methodInfo = type.GetMethod(methodName, BindingFlags.Public | BindingFlags.Static);
+ var data = methodInfo?.Invoke(null, null) as IEnumerable<object[]>;
+
+ return data?.Select(obj =>
+ {
+ obj[regexOptionsArrayIndex] = (RegexOptions)obj[regexOptionsArrayIndex] | RegexOptions.Compiled;
+ return obj;
+ });
+ }
+ }
+}
diff --git a/src/System.Text.RegularExpressions/tests/RegexCompilationInfoTests.cs b/src/System.Text.RegularExpressions/tests/RegexCompilationInfoTests.cs
new file mode 100644
index 0000000000..ab7d512b9a
--- /dev/null
+++ b/src/System.Text.RegularExpressions/tests/RegexCompilationInfoTests.cs
@@ -0,0 +1,119 @@
+// 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.Text.RegularExpressions.Tests
+{
+ public class RegexCompilationInfoTests
+ {
+ private RegexCompilationInfo Instance
+ {
+ get => new RegexCompilationInfo("pattern", RegexOptions.None, "name", "fullnamespace", true, TimeSpan.FromSeconds(60));
+ }
+
+ public static IEnumerable<object[]> Ctor_MemberData()
+ {
+ yield return new object[] { string.Empty, RegexOptions.None, "name", string.Empty, false, TimeSpan.FromSeconds(60) };
+ yield return new object[] { "pattern", RegexOptions.Compiled, "name", "fullnamespace", true, TimeSpan.FromSeconds(60) };
+ }
+
+ [Theory]
+ [MemberData(nameof(Ctor_MemberData))]
+ public void Ctor_ValidArguments_CheckProperties(string pattern, RegexOptions options, string name, string fullnamespace, bool ispublic, TimeSpan matchTimeout)
+ {
+ var regexCompilationInfo = new RegexCompilationInfo(pattern, options, name, fullnamespace, ispublic, matchTimeout);
+ Assert.Equal(pattern, regexCompilationInfo.Pattern);
+ Assert.Equal(options, regexCompilationInfo.Options);
+ Assert.Equal(name, regexCompilationInfo.Name);
+ Assert.Equal(fullnamespace, regexCompilationInfo.Namespace);
+ Assert.Equal(ispublic, regexCompilationInfo.IsPublic);
+ Assert.Equal(matchTimeout, regexCompilationInfo.MatchTimeout);
+ }
+
+ [Theory]
+ [InlineData(true)]
+ [InlineData(false)]
+ public void IsPublic_GetSet(bool isPublic)
+ {
+ RegexCompilationInfo regexCompilationInfo = Instance;
+ regexCompilationInfo.IsPublic = isPublic;
+ Assert.Equal(isPublic, regexCompilationInfo.IsPublic);
+ }
+
+ public static IEnumerable<object[]> MatchTimeout_GetSet_Throws_MemberData()
+ {
+ yield return new object[] { TimeSpan.Zero };
+ yield return new object[] { TimeSpan.FromMilliseconds(int.MaxValue) };
+ yield return new object[] { TimeSpan.MinValue };
+ }
+
+ public static IEnumerable<object[]> MatchTimeout_GetSet_Success_MemberData()
+ {
+ yield return new object[] { TimeSpan.Zero.Add(TimeSpan.FromMilliseconds(1)) };
+ yield return new object[] { TimeSpan.FromMilliseconds(int.MaxValue - 1) };
+ }
+
+ [Theory]
+ [MemberData(nameof(MatchTimeout_GetSet_Throws_MemberData))]
+ public void MatchTimeout_GetSet_Throws(TimeSpan matchTimeout)
+ {
+ RegexCompilationInfo regexCompilationInfo = Instance;
+ AssertExtensions.Throws<ArgumentOutOfRangeException>("matchTimeout", () =>
+ regexCompilationInfo.MatchTimeout = matchTimeout);
+ }
+
+ [Theory]
+ [MemberData(nameof(MatchTimeout_GetSet_Success_MemberData))]
+ public void MatchTimeout_GetSet_Success(TimeSpan matchTimeout)
+ {
+ RegexCompilationInfo regexCompilationInfo = Instance;
+ regexCompilationInfo.MatchTimeout = matchTimeout;
+ Assert.Equal(matchTimeout, regexCompilationInfo.MatchTimeout);
+ }
+
+ [Fact]
+ public void Name_GetSet()
+ {
+ RegexCompilationInfo regexCompilationInfo = Instance;
+ AssertExtensions.Throws<ArgumentNullException>("Name", "value", () => regexCompilationInfo.Name = null);
+ AssertExtensions.Throws<ArgumentException>("Name", "value", () => regexCompilationInfo.Name = string.Empty);
+ regexCompilationInfo.Name = "Name";
+ Assert.Equal("Name", regexCompilationInfo.Name);
+ }
+
+ [Fact]
+ public void Namespace_GetSet()
+ {
+ RegexCompilationInfo regexCompilationInfo = Instance;
+ AssertExtensions.Throws<ArgumentNullException>("Namespace", "value", () => regexCompilationInfo.Namespace = null);
+ regexCompilationInfo.Namespace = string.Empty;
+ Assert.Equal(string.Empty, regexCompilationInfo.Namespace);
+ regexCompilationInfo.Namespace = "Namespace";
+ Assert.Equal("Namespace", regexCompilationInfo.Namespace);
+ }
+
+ [Fact]
+ public void Options_GetSet()
+ {
+ RegexCompilationInfo regexCompilationInfo = Instance;
+ regexCompilationInfo.Options = RegexOptions.None;
+ Assert.Equal(RegexOptions.None, regexCompilationInfo.Options);
+ regexCompilationInfo.Options = RegexOptions.Compiled | RegexOptions.CultureInvariant;
+ Assert.Equal(RegexOptions.Compiled | RegexOptions.CultureInvariant, regexCompilationInfo.Options);
+ }
+
+ [Fact]
+ public void Pattern_GetSet()
+ {
+ RegexCompilationInfo regexCompilationInfo = Instance;
+ AssertExtensions.Throws<ArgumentNullException>("Pattern", "value", () => regexCompilationInfo.Pattern = null);
+ regexCompilationInfo.Pattern = string.Empty;
+ Assert.Equal(string.Empty, regexCompilationInfo.Pattern);
+ regexCompilationInfo.Pattern = "Pattern";
+ Assert.Equal("Pattern", regexCompilationInfo.Pattern);
+ }
+ }
+}
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 20ab32749d..aca9ba82ba 100644
--- a/src/System.Text.RegularExpressions/tests/System.Text.RegularExpressions.Tests.csproj
+++ b/src/System.Text.RegularExpressions/tests/System.Text.RegularExpressions.Tests.csproj
@@ -26,23 +26,22 @@
<Compile Include="Regex.Split.Tests.cs" />
<Compile Include="Regex.Match.Tests.cs" />
<Compile Include="Regex.Tests.Common.cs" />
- <Compile Include="$(CommonTestPath)\System\Runtime\Serialization\Formatters\BinaryFormatterHelpers.cs">
- <Link>System\Runtime\Serialization\Formatters\BinaryFormatterHelpers.cs</Link>
- </Compile>
+ <Compile Include="RegexCompilationHelper.cs" />
<ProjectReference Include="$(CommonTestPath)\System\Diagnostics\RemoteExecutorConsoleApp\RemoteExecutorConsoleApp.csproj">
<Name>RemoteExecutorConsoleApp</Name>
</ProjectReference>
</ItemGroup>
- <ItemGroup Condition="'$(TargetGroup)' == 'netcoreapp'">
+ <ItemGroup Condition="'$(TargetGroup)' != 'netstandard'">
+ <Compile Include="CaptureCollectionTests2.cs" />
+ <Compile Include="GroupCollectionTests2.cs" />
+ <Compile Include="MatchCollectionTests2.cs" />
<Compile Include="PrecompiledRegexScenarioTest.cs" />
+ <Compile Include="RegexCompilationInfoTests.cs" />
<Compile Include="RegexGroupNameTests.cs" />
- <Compile Include="CaptureCollectionTests.netcoreapp.cs" />
- <Compile Include="GroupCollectionTests.netcoreapp.cs" />
- <Compile Include="MatchCollectionTests.netcoreapp.cs" />
<Compile Include="$(CommonTestPath)\System\Diagnostics\DebuggerAttributes.cs">
<Link>Common\System\Diagnostics\DebuggerAttributes.cs</Link>
</Compile>
</ItemGroup>
<!-- Automatically added by VS -->
<Import Project="$([MSBuild]::GetDirectoryNameOfFileAbove($(MSBuildThisFileDirectory), dir.targets))\dir.targets" />
-</Project> \ No newline at end of file
+</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 c8942a024b..2c1ebf5fd4 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
@@ -9,8 +9,15 @@
<ProjectReference Include="..\src\System.Threading.Tasks.Dataflow.csproj">
<SupportedFramework>net45;netcore45;wp8;wpa81;netcoreapp1.0;$(AllXamarinFrameworks)</SupportedFramework>
</ProjectReference>
- <InboxOnTargetFramework Include="netcoreapp2.0" />
- <InboxOnTargetFramework Include="$(UAPvNextTFM)" />
+
+ <!-- Since UAP and .NETCoreApp are package based we still want to enable
+ OOBing libraries that happen to overlap with their framework package.
+ This avoids us having to lock the API in our NuGet packages just
+ to match what shipped inbox: since we can provide a new library
+ we can update it to add API without raising the netstandard version. -->
+ <ValidatePackageSuppression Include="TreatAsOutOfBox">
+ <Value>.NETCoreApp;UAP</Value>
+ </ValidatePackageSuppression>
</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/src/Internal/ProducerConsumerQueues.cs b/src/System.Threading.Tasks.Dataflow/src/Internal/ProducerConsumerQueues.cs
index d14fd60cec..44b10b3dc8 100644
--- a/src/System.Threading.Tasks.Dataflow/src/Internal/ProducerConsumerQueues.cs
+++ b/src/System.Threading.Tasks.Dataflow/src/Internal/ProducerConsumerQueues.cs
@@ -551,7 +551,7 @@ namespace System.Threading.Tasks
}
/// <summary>Padding structure used to minimize false sharing in SingleProducerSingleConsumerQueue{T}.</summary>
- [StructLayout(LayoutKind.Explicit, Size = PaddingHelpers.CACHE_LINE_SIZE - sizeof(Int32))] // Based on common case of 64-byte cache lines
+ [StructLayout(LayoutKind.Explicit, Size = PaddingHelpers.CACHE_LINE_SIZE - sizeof(Int32))]
struct PaddingFor32
{
}
diff --git a/src/System.Threading.Tasks.Extensions/pkg/System.Threading.Tasks.Extensions.pkgproj b/src/System.Threading.Tasks.Extensions/pkg/System.Threading.Tasks.Extensions.pkgproj
index 62b45af567..1020a4bb8b 100644
--- a/src/System.Threading.Tasks.Extensions/pkg/System.Threading.Tasks.Extensions.pkgproj
+++ b/src/System.Threading.Tasks.Extensions/pkg/System.Threading.Tasks.Extensions.pkgproj
@@ -9,7 +9,15 @@
<ProjectReference Include="..\src\System.Threading.Tasks.Extensions.csproj">
<SupportedFramework>net45;netcore45;netcoreapp1.0;wpa81;wp8;$(AllXamarinFrameworks)</SupportedFramework>
</ProjectReference>
- <InboxOnTargetFramework Include="netcoreapp2.0" />
+
+ <!-- Since UAP and .NETCoreApp are package based we still want to enable
+ OOBing libraries that happen to overlap with their framework package.
+ This avoids us having to lock the API in our NuGet packages just
+ to match what shipped inbox: since we can provide a new library
+ we can update it to add API without raising the netstandard version. -->
+ <ValidatePackageSuppression Include="TreatAsOutOfBox">
+ <Value>.NETCoreApp;UAP</Value>
+ </ValidatePackageSuppression>
<!-- this package is part of the implementation closure of NETStandard.Library
therefore it cannot reference NETStandard.Library -->
diff --git a/src/System.Threading.Tasks.Extensions/tests/AsyncValueTaskMethodBuilderTests.cs b/src/System.Threading.Tasks.Extensions/tests/AsyncValueTaskMethodBuilderTests.cs
index 66b1986c2a..94827c91b5 100644
--- a/src/System.Threading.Tasks.Extensions/tests/AsyncValueTaskMethodBuilderTests.cs
+++ b/src/System.Threading.Tasks.Extensions/tests/AsyncValueTaskMethodBuilderTests.cs
@@ -119,7 +119,6 @@ namespace System.Threading.Tasks.Tests
{
AsyncValueTaskMethodBuilder<int> b = ValueTask<int>.CreateAsyncMethodBuilder();
AssertExtensions.Throws<ArgumentNullException>("stateMachine", () => b.SetStateMachine(null));
- b.SetStateMachine(new DelegateStateMachine());
}
[Fact]
diff --git a/src/System.Threading.Tasks/tests/CESchedulerPairTests.cs b/src/System.Threading.Tasks/tests/CESchedulerPairTests.cs
index cd1eb50622..ef8ec6a94f 100644
--- a/src/System.Threading.Tasks/tests/CESchedulerPairTests.cs
+++ b/src/System.Threading.Tasks/tests/CESchedulerPairTests.cs
@@ -317,7 +317,7 @@ namespace System.Threading.Tasks.Tests
conTask.Wait();
Assert.True(conTask.Result, "The concurrenttask when executed successfully should have returned true");
- //Now scehdule a exclusive task that is blocked(thereby preventing other concurrent tasks to finish)
+ //Now scehdule an exclusive task that is blocked(thereby preventing other concurrent tasks to finish)
Task<bool> exclusiveTask = writers.StartNew<bool>(() => { blockMainThreadEvent.Set(); blockExclusiveTaskEvent.WaitOne(); return true; });
//With exclusive task in execution mode, schedule a number of concurrent tasks and ensure they are not executed
@@ -328,7 +328,7 @@ namespace System.Threading.Tasks.Tests
foreach (Task task in taskList)
{
bool wasTaskStarted = (task.Status != TaskStatus.Running) && (task.Status != TaskStatus.RanToCompletion);
- Assert.True(wasTaskStarted, "Concurrent tasks should not be executed when a exclusive task is getting executed");
+ Assert.True(wasTaskStarted, "Concurrent tasks should not be executed when an exclusive task is getting executed");
}
blockExclusiveTaskEvent.Set();
diff --git a/src/System.Threading.Tasks/tests/Task/TaskRunSyncTests.cs b/src/System.Threading.Tasks/tests/Task/TaskRunSyncTests.cs
index b9bbe59bf2..37e3d023bd 100644
--- a/src/System.Threading.Tasks/tests/Task/TaskRunSyncTests.cs
+++ b/src/System.Threading.Tasks/tests/Task/TaskRunSyncTests.cs
@@ -41,7 +41,7 @@ namespace System.Threading.Tasks.Tests
public enum WorkloadType
{
- CreateChildTask, //Start a attached childTask in the workload
+ CreateChildTask, //Start an attached childTask in the workload
CreateDetachedChildTask, //start a detached childTask in the workload
ContinueInside, //Invoke continuewith as the workload inside the task
RunWithUserScheduler, //create a task with custom task scheduler that runs that task inline
diff --git a/src/System.Threading/tests/MutexTests.cs b/src/System.Threading/tests/MutexTests.cs
index 9647593698..88f6a3a121 100644
--- a/src/System.Threading/tests/MutexTests.cs
+++ b/src/System.Threading/tests/MutexTests.cs
@@ -71,7 +71,7 @@ namespace System.Threading.Tests
}
[PlatformSpecific(TestPlatforms.Windows)]
- [ConditionalFact(typeof(PlatformDetection), nameof(PlatformDetection.IsNotWinRT))] // Can't create global objects in appcontainer
+ [ConditionalFact(typeof(PlatformDetection), nameof(PlatformDetection.IsNotInAppContainer))] // Can't create global objects in appcontainer
[SkipOnTargetFramework(
TargetFrameworkMonikers.NetFramework,
"The fix necessary for this test (PR https://github.com/dotnet/coreclr/pull/12381) is not in the .NET Framework.")]
@@ -90,7 +90,7 @@ namespace System.Threading.Tests
});
}
- [ConditionalFact(typeof(PlatformDetection), nameof(PlatformDetection.IsWinRT))] // Can't create global objects in appcontainer
+ [ConditionalFact(typeof(PlatformDetection), nameof(PlatformDetection.IsInAppContainer))] // Can't create global objects in appcontainer
[PlatformSpecific(TestPlatforms.Windows)]
public void Ctor_TryCreateGlobalMutexTest_Uwp()
{
diff --git a/src/System.Transactions.Local/tests/TransactionScopeTest.cs b/src/System.Transactions.Local/tests/TransactionScopeTest.cs
index 1838ba4961..e96ec2ef2a 100644
--- a/src/System.Transactions.Local/tests/TransactionScopeTest.cs
+++ b/src/System.Transactions.Local/tests/TransactionScopeTest.cs
@@ -761,7 +761,7 @@ namespace System.Transactions.Tests
irm.Value = 2;
ct.Commit();
- /* Using a already committed transaction in a new
+ /* Using an already committed transaction in a new
* TransactionScope
*/
TransactionScope scope = new TransactionScope(ct);
diff --git a/src/System.ValueTuple/ref/System.ValueTuple.csproj b/src/System.ValueTuple/ref/System.ValueTuple.csproj
index fd405598a5..888a39f5a0 100644
--- a/src/System.ValueTuple/ref/System.ValueTuple.csproj
+++ b/src/System.ValueTuple/ref/System.ValueTuple.csproj
@@ -4,6 +4,9 @@
<PropertyGroup>
<ProjectGuid>{11AE73F7-3532-47B9-8FF6-B4F22D76456D}</ProjectGuid>
<RootNamespace>System</RootNamespace>
+ <!-- Must match version supported by frameworks which support 4.0.* inbox.
+ Can be removed when API is added and this assembly is versioned to 4.1.* -->
+ <AssemblyVersion Condition="'$(TargetGroup)' != 'netfx'">4.0.3.0</AssemblyVersion>
</PropertyGroup>
<!-- Default configurations to help VS understand the options -->
<PropertyGroup Condition="'$(Configuration)|$(Platform)' == 'netcoreapp-Debug|AnyCPU'" />
diff --git a/src/System.Web.HttpUtility/src/System/Web/HttpUtility.cs b/src/System.Web.HttpUtility/src/System/Web/HttpUtility.cs
index d906040649..ea585a1cd6 100644
--- a/src/System.Web.HttpUtility/src/System/Web/HttpUtility.cs
+++ b/src/System.Web.HttpUtility/src/System/Web/HttpUtility.cs
@@ -2,6 +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.
+// Authors:
+// Patrik Torstensson (Patrik.Torstensson@labs2.com)
+// Wictor Wilén (decode/encode functions) (wictor@ibizkit.se)
+// Tim Coleman (tim@timcoleman.com)
+// Gonzalo Paniagua Javier (gonzalo@ximian.com)
+//
+// Copyright (C) 2005-2010 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.Specialized;
using System.Globalization;
using System.IO;
@@ -44,47 +72,37 @@ namespace System.Web
public static NameValueCollection ParseQueryString(string query, Encoding encoding)
{
if (query == null)
+ {
throw new ArgumentNullException(nameof(query));
+ }
if (encoding == null)
+ {
throw new ArgumentNullException(nameof(encoding));
+ }
- if ((query.Length > 0) && (query[0] == '?'))
- query = query.Substring(1);
-
- var result = new HttpQSCollection();
- ParseQueryString(query, encoding, result);
- return result;
- }
+ HttpQSCollection result = new HttpQSCollection();
+ int queryLength = query.Length;
+ int namePos = queryLength > 0 && query[0] == '?' ? 1 : 0;
+ if (queryLength == namePos)
+ {
+ return result;
+ }
- private static void ParseQueryString(string query, Encoding encoding, NameValueCollection result)
- {
- if (query.Length == 0)
- return;
-
- var decoded = HtmlDecode(query);
- var decodedLength = decoded.Length;
- var namePos = 0;
- var first = true;
- while (namePos <= decodedLength)
+ while (namePos <= queryLength)
{
int valuePos = -1, valueEnd = -1;
- for (var q = namePos; q < decodedLength; q++)
- if ((valuePos == -1) && (decoded[q] == '='))
+ for (int q = namePos; q < queryLength; q++)
+ {
+ if (valuePos == -1 && query[q] == '=')
{
valuePos = q + 1;
}
- else if (decoded[q] == '&')
+ else if (query[q] == '&')
{
valueEnd = q;
break;
}
-
- if (first)
- {
- first = false;
- if (decoded[namePos] == '?')
- namePos++;
}
string name;
@@ -95,23 +113,20 @@ namespace System.Web
}
else
{
- name = UrlDecode(decoded.Substring(namePos, valuePos - namePos - 1), encoding);
+ name = UrlDecode(query.Substring(namePos, valuePos - namePos - 1), encoding);
}
+
if (valueEnd < 0)
{
- namePos = -1;
- valueEnd = decoded.Length;
+ valueEnd = query.Length;
}
- else
- {
- namePos = valueEnd + 1;
- }
- var value = UrlDecode(decoded.Substring(valuePos, valueEnd - valuePos), encoding);
+ namePos = valueEnd + 1;
+ string value = UrlDecode(query.Substring(valuePos, valueEnd - valuePos), encoding);
result.Add(name, value);
- if (namePos == -1)
- break;
}
+
+ return result;
}
public static string HtmlDecode(string s)
@@ -298,4 +313,4 @@ namespace System.Web
return addDoubleQuotes ? "\"" + encoded + "\"" : encoded;
}
}
-} \ No newline at end of file
+}
diff --git a/src/System.Web.HttpUtility/tests/HttpUtility/HttpUtilityTest.cs b/src/System.Web.HttpUtility/tests/HttpUtility/HttpUtilityTest.cs
index 357f526408..aabfd4fd9b 100644
--- a/src/System.Web.HttpUtility/tests/HttpUtility/HttpUtilityTest.cs
+++ b/src/System.Web.HttpUtility/tests/HttpUtility/HttpUtilityTest.cs
@@ -33,7 +33,6 @@ using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
-using System.Web;
using Xunit;
namespace System.Web.Tests
@@ -51,6 +50,8 @@ namespace System.Web.Tests
new object[] {"&lt;script>", "<script>"},
new object[] {"&quot;a&amp;b&quot;", "\"a&b\""},
new object[] {"&#39;string&#39;", "'string'"},
+ new object[] {"abc + def!", "abc + def!"},
+ new object[] {"This is an &lt;element>!", "This is an <element>!"},
};
[Theory]
@@ -240,11 +241,9 @@ namespace System.Web.Tests
{
"\u00A0¡¢£¤¥¦§¨©ª«¬­®¯°±²³´µ¶·¸¹º»¼½¾¿ÀÁÂÃÄÅÆÇÈÉÊËÌÍÎÏÐÑÒÓÔÕÖ×ØÙÚÛÜÝÞßàáâãäåæçèéêëìíîïðñòóôõö÷øùúûüýþÿ",
@"&#160;&#161;&#162;&#163;&#164;&#165;&#166;&#167;&#168;&#169;&#170;&#171;&#172;&#173;&#174;&#175;&#176;&#177;&#178;&#179;&#180;&#181;&#182;&#183;&#184;&#185;&#186;&#187;&#188;&#189;&#190;&#191;&#192;&#193;&#194;&#195;&#196;&#197;&#198;&#199;&#200;&#201;&#202;&#203;&#204;&#205;&#206;&#207;&#208;&#209;&#210;&#211;&#212;&#213;&#214;&#215;&#216;&#217;&#218;&#219;&#220;&#221;&#222;&#223;&#224;&#225;&#226;&#227;&#228;&#229;&#230;&#231;&#232;&#233;&#234;&#235;&#236;&#237;&#238;&#239;&#240;&#241;&#242;&#243;&#244;&#245;&#246;&#247;&#248;&#249;&#250;&#251;&#252;&#253;&#254;&#255;",
- },
+ }
};
-
-
[Theory]
[MemberData(nameof(HtmlEncodeDecodeData))]
[MemberData(nameof(HtmlEncodeData))]
@@ -257,6 +256,16 @@ namespace System.Web.Tests
[Theory]
[MemberData(nameof(HtmlEncodeDecodeData))]
[MemberData(nameof(HtmlEncodeData))]
+ [InlineData(null, null)]
+ [InlineData(2, "2")]
+ public void HtmlEncodeObject(string decoded, string encoded)
+ {
+ Assert.Equal(encoded, HttpUtility.HtmlEncode((object)decoded));
+ }
+
+ [Theory]
+ [MemberData(nameof(HtmlEncodeDecodeData))]
+ [MemberData(nameof(HtmlEncodeData))]
[InlineData(null, "")]
public void HtmlEncode_TextWriter(string decoded, string encoded)
{
@@ -284,6 +293,8 @@ namespace System.Web.Tests
{
yield return new object[] { null, "" };
yield return new object[] { "", "" };
+ yield return new object[] {"No escaping needed.", "No escaping needed."};
+ yield return new object[] {"The \t and \n will need to be escaped.", "The \\t and \\n will need to be escaped."};
for (char c = char.MinValue; c < TestMaxChar; c++)
{
if (c >= 0 && c <= 7 || c == 11 || c >= 14 && c <= 31 || c == 38 || c == 39 || c == 60 || c == 62 || c == 133 || c == 8232 || c == 8233)
@@ -365,10 +376,18 @@ namespace System.Web.Tests
new[] {new[] {UnicodeStr}}
},
new object[] {"name=value=test", new[] {"name"}, new[] {new[] {"value=test"}}},
+ new object[] { "name=value&#xe9;", new[] {"name", null}, new[] {new[] {"value"}, new[] { "#xe9;" } }},
+ new object[] { "name=value&amp;name2=value2", new[] {"name", "amp;name2"}, new[] {new[] {"value"}, new[] { "value2" } }},
+ new object[] {"name=value=test+phrase", new[] {"name"}, new[] {new[] {"value=test phrase"}}},
};
public static IEnumerable<object[]> ParseQueryStringDataQ =>
- ParseQueryStringData.Select(a => new object[] { "?" + (string)a[0] }.Concat(a.Skip(1)).ToArray());
+ ParseQueryStringData.Select(a => new object[] { "?" + (string)a[0] }.Concat(a.Skip(1)).ToArray())
+ .Concat(new[]
+ {
+ new object[] { "??name=value=test", new[] { "?name" }, new[] { new[] { "value=test" }}},
+ new object[] { "?", Array.Empty<string>(), Array.Empty<IList<string>>()}
+ });
[Theory]
[MemberData(nameof(ParseQueryStringData))]
@@ -407,10 +426,12 @@ namespace System.Web.Tests
public void ParseQueryString_ToString()
{
var parsed = HttpUtility.ParseQueryString("");
+ Assert.Empty(parsed.ToString());
parsed.Add("ReturnUrl", @"http://localhost/login/authenticate?ReturnUrl=http://localhost/secured_area&__provider__=google");
var expected = "ReturnUrl=http%3a%2f%2flocalhost%2flogin%2fauthenticate%3fReturnUrl%3dhttp%3a%2f%2flocalhost%2fsecured_area%26__provider__%3dgoogle";
Assert.Equal(expected, parsed.ToString());
+ Assert.Equal(expected, HttpUtility.ParseQueryString(expected).ToString());
}
#endregion ParseQueryString
@@ -428,6 +449,12 @@ namespace System.Web.Tests
new object[] {"http://127.0.0.1:8080/appDir/page.aspx?foo=bar", "http://127.0.0.1:8080/appDir/page.aspx?foo=b%u0061r"},
new object[] {"http://127.0.0.1:8080/appDir/page.aspx?foo=b%ar", "http://127.0.0.1:8080/appDir/page.aspx?foo=b%%u0061r"},
new object[] {"http://127.0.0.1:8080/appDir/page.aspx?foo=b%uu0061r", "http://127.0.0.1:8080/appDir/page.aspx?foo=b%uu0061r"},
+ new object[] {"http://127.0.0.1:8080/appDir/page.aspx?foo=bar baz", "http://127.0.0.1:8080/appDir/page.aspx?foo=bar+baz"},
+ new object[] { "http://example.net/\U00010000", "http://example.net/\U00010000" },
+ new object[] { "http://example.net/\uFFFD", "http://example.net/\uD800" },
+ new object[] { "http://example.net/\uFFFDa", "http://example.net/\uD800a" },
+ new object[] { "http://example.net/\uFFFD", "http://example.net/\uDC00" },
+ new object[] { "http://example.net/\uFFFDa", "http://example.net/\uDC00a" }
};
public static IEnumerable<object[]> UrlDecodeDataToBytes =>
@@ -441,6 +468,12 @@ namespace System.Web.Tests
new object[] {"http://127.0.0.1:8080/appDir/page.aspx?foo=b%uu0061r", "http://127.0.0.1:8080/appDir/page.aspx?foo=b%uu0061r"},
new object[] {"http://127.0.0.1:8080/appDir/page.aspx?foo=b%u0061r", "http://127.0.0.1:8080/appDir/page.aspx?foo=b%u0061r"},
new object[] {"http://127.0.0.1:8080/appDir/page.aspx?foo=b%%u0061r", "http://127.0.0.1:8080/appDir/page.aspx?foo=b%%u0061r"},
+ new object[] {"http://127.0.0.1:8080/appDir/page.aspx?foo=bar baz", "http://127.0.0.1:8080/appDir/page.aspx?foo=bar+baz"},
+ new object[] { "http://example.net/\U00010000", "http://example.net/\U00010000" },
+ new object[] { "http://example.net/\uFFFD", "http://example.net/\uD800" },
+ new object[] { "http://example.net/\uFFFDa", "http://example.net/\uD800a" },
+ new object[] { "http://example.net/\uFFFD", "http://example.net/\uDC00" },
+ new object[] { "http://example.net/\uFFFDa", "http://example.net/\uDC00a" }
};
[Theory]
@@ -450,6 +483,26 @@ namespace System.Web.Tests
Assert.Equal(decoded, HttpUtility.UrlDecode(encoded));
}
+ [Fact]
+ public void UrlDecode_null()
+ {
+ Assert.Null(HttpUtility.UrlDecode(default(string), Encoding.UTF8));
+ Assert.Null(HttpUtility.UrlDecode(default(byte[]), Encoding.UTF8));
+ Assert.Null(HttpUtility.UrlDecode(null));
+ Assert.Null(HttpUtility.UrlDecode(null, 2, 0, Encoding.UTF8));
+ Assert.Throws<ArgumentNullException>("bytes", () => HttpUtility.UrlDecode(null, 2, 3, Encoding.UTF8));
+ }
+
+ [Fact]
+ public void UrlDecode_OutOfRange()
+ {
+ byte[] bytes = { 0, 1, 2 };
+ Assert.Throws<ArgumentOutOfRangeException>("offset", () => HttpUtility.UrlDecode(bytes, -1, 2, Encoding.UTF8));
+ Assert.Throws<ArgumentOutOfRangeException>("offset", () => HttpUtility.UrlDecode(bytes, 14, 2, Encoding.UTF8));
+ Assert.Throws<ArgumentOutOfRangeException>("count", () => HttpUtility.UrlDecode(bytes, 1, 12, Encoding.UTF8));
+ Assert.Throws<ArgumentOutOfRangeException>("count", () => HttpUtility.UrlDecode(bytes, 1, -12, Encoding.UTF8));
+ }
+
[Theory]
[MemberData(nameof(UrlDecodeDataToBytes))]
public void UrlDecodeToBytes(string decoded, string encoded)
@@ -458,6 +511,33 @@ namespace System.Web.Tests
}
[Theory]
+ [MemberData(nameof(UrlDecodeDataToBytes))]
+ public void UrlDecodeToBytes_DefaultEncoding(string decoded, string encoded)
+ {
+ Assert.Equal(decoded, Encoding.UTF8.GetString(HttpUtility.UrlDecodeToBytes(encoded)));
+ }
+
+ [Fact]
+ public void UrlDecodeToBytes_null()
+ {
+ Assert.Null(HttpUtility.UrlDecodeToBytes(default(byte[])));
+ Assert.Null(HttpUtility.UrlDecodeToBytes(default(string)));
+ Assert.Null(HttpUtility.UrlDecodeToBytes(default(string), Encoding.UTF8));
+ Assert.Null(HttpUtility.UrlDecodeToBytes(default(byte[]), 2, 0));
+ Assert.Throws<ArgumentNullException>("bytes", () => HttpUtility.UrlDecodeToBytes(default(byte[]), 2, 3));
+ }
+
+ [Fact]
+ public void UrlDecodeToBytes_OutOfRange()
+ {
+ byte[] bytes = { 0, 1, 2 };
+ Assert.Throws<ArgumentOutOfRangeException>("offset", () => HttpUtility.UrlDecodeToBytes(bytes, -1, 2));
+ Assert.Throws<ArgumentOutOfRangeException>("offset", () => HttpUtility.UrlDecodeToBytes(bytes, 14, 2));
+ Assert.Throws<ArgumentOutOfRangeException>("count", () => HttpUtility.UrlDecodeToBytes(bytes, 1, 12));
+ Assert.Throws<ArgumentOutOfRangeException>("count", () => HttpUtility.UrlDecodeToBytes(bytes, 1, -12));
+ }
+
+ [Theory]
[MemberData(nameof(UrlDecodeData))]
public void UrlDecode_ByteArray(string decoded, string encoded)
{
@@ -529,10 +609,57 @@ namespace System.Web.Tests
Assert.Equal(encoded, Encoding.UTF8.GetString(HttpUtility.UrlEncodeToBytes(decoded, Encoding.UTF8)));
}
+ [Theory]
+ [MemberData(nameof(UrlEncodeData))]
+ public void UrlEncodeToBytes_DefaultEncoding(string decoded, string encoded)
+ {
+ Assert.Equal(encoded, Encoding.UTF8.GetString(HttpUtility.UrlEncodeToBytes(decoded)));
+ }
+
+ [Theory, MemberData(nameof(UrlEncodeData))]
+ public void UrlEncodeToBytesExplicitSize(string decoded, string encoded)
+ {
+ byte[] bytes = Encoding.UTF8.GetBytes(decoded);
+ Assert.Equal(encoded, Encoding.UTF8.GetString(HttpUtility.UrlEncodeToBytes(bytes, 0, bytes.Length)));
+ }
+
+
+ [Theory]
+ [InlineData(" abc defgh", "abc+def", 1, 7)]
+ [InlineData(" abc defgh", "", 1, 0)]
+ public void UrlEncodeToBytesExplicitSize(string decoded, string encoded, int offset, int count)
+ {
+ byte[] bytes = Encoding.UTF8.GetBytes(decoded);
+ Assert.Equal(encoded, Encoding.UTF8.GetString(HttpUtility.UrlEncodeToBytes(bytes, offset, count)));
+ }
+
+ [Theory]
+ [InlineData("abc def", " abc+defgh", 1, 7)]
+ [InlineData("", " abc defgh", 1, 0)]
+ public void UrlDecodeToBytesExplicitSize(string decoded, string encoded, int offset, int count)
+ {
+ byte[] bytes = Encoding.UTF8.GetBytes(encoded);
+ Assert.Equal(decoded, Encoding.UTF8.GetString(HttpUtility.UrlDecodeToBytes(bytes, offset, count)));
+ }
+
[Fact]
public void UrlEncodeToBytes_null()
{
Assert.Null(HttpUtility.UrlEncodeToBytes(null, Encoding.UTF8));
+ Assert.Null(HttpUtility.UrlEncodeToBytes(default(byte[])));
+ Assert.Null(HttpUtility.UrlEncodeToBytes(default(string)));
+ Assert.Null(HttpUtility.UrlEncodeToBytes(null, 2, 0));
+ Assert.Throws<ArgumentNullException>("bytes", () => HttpUtility.UrlEncodeToBytes(null, 2, 3));
+ }
+
+ [Fact]
+ public void UrlEncodeToBytes_OutOfRange()
+ {
+ byte[] bytes = { 0, 1, 2 };
+ Assert.Throws<ArgumentOutOfRangeException>("offset", () => HttpUtility.UrlEncodeToBytes(bytes, -1, 2));
+ Assert.Throws<ArgumentOutOfRangeException>("offset", () => HttpUtility.UrlEncodeToBytes(bytes, 14, 2));
+ Assert.Throws<ArgumentOutOfRangeException>("count", () => HttpUtility.UrlEncodeToBytes(bytes, 1, 12));
+ Assert.Throws<ArgumentOutOfRangeException>("count", () => HttpUtility.UrlEncodeToBytes(bytes, 1, -12));
}
[Theory]
@@ -543,9 +670,22 @@ namespace System.Web.Tests
}
[Fact]
- public void UrlEncode_ByteArray_null()
+ public void UrlEncode_null()
+ {
+ Assert.Null(HttpUtility.UrlEncode((byte[])null));
+ Assert.Null(HttpUtility.UrlEncode((string)null));
+ Assert.Null(HttpUtility.UrlEncode(null, Encoding.UTF8));
+ Assert.Null(HttpUtility.UrlEncode(null, 2, 3));
+ }
+
+ [Fact]
+ public void UrlEncode_OutOfRange()
{
- Assert.Null(HttpUtility.UrlEncode((byte[]) null));
+ byte[] bytes = {0, 1, 2};
+ Assert.Throws<ArgumentOutOfRangeException>("offset", () => HttpUtility.UrlEncode(bytes, -1, 2));
+ Assert.Throws<ArgumentOutOfRangeException>("offset", () => HttpUtility.UrlEncode(bytes, 14, 2));
+ Assert.Throws<ArgumentOutOfRangeException>("count", () => HttpUtility.UrlEncode(bytes, 1, 12));
+ Assert.Throws<ArgumentOutOfRangeException>("count", () => HttpUtility.UrlEncode(bytes, 1, -12));
}
#endregion UrlEncode(ToBytes)
@@ -591,6 +731,15 @@ namespace System.Web.Tests
[InlineData(" ", "%20")]
[InlineData("\n", "%0a")]
[InlineData("default.xxx?sdsd=sds", "default.xxx?sdsd=sds")]
+ [InlineData("?sdsd=sds", "?sdsd=sds")]
+ [InlineData("", "")]
+ [InlineData("http://example.net/default.xxx?sdsd=sds", "http://example.net/default.xxx?sdsd=sds")]
+ [InlineData("http://example.net:8080/default.xxx?sdsd=sds", "http://example.net:8080/default.xxx?sdsd=sds")]
+ [InlineData("http://eXample.net:80/default.xxx?sdsd=sds", "http://eXample.net:80/default.xxx?sdsd=sds")]
+ [InlineData("http://EXAMPLE.NET/default.xxx?sdsd=sds", "http://EXAMPLE.NET/default.xxx?sdsd=sds")]
+ [InlineData("http://EXAMPLE.NET/défault.xxx?sdsd=sds", "http://EXAMPLE.NET/d%c3%a9fault.xxx?sdsd=sds")]
+ [InlineData("file:///C/Users", "file:///C/Users")]
+ [InlineData("mailto:user@example.net", "mailto:user@example.net")]
public void UrlPathEncode(string decoded, string encoded)
{
Assert.Equal(encoded, HttpUtility.UrlPathEncode(decoded));
diff --git a/src/shims/ApiCompatBaseline.netcoreapp.netfx461.ignore.txt b/src/shims/ApiCompatBaseline.netcoreapp.netfx461.ignore.txt
index dbcbdd697f..6ded52988e 100644
--- a/src/shims/ApiCompatBaseline.netcoreapp.netfx461.ignore.txt
+++ b/src/shims/ApiCompatBaseline.netcoreapp.netfx461.ignore.txt
@@ -198,6 +198,7 @@ MembersMustExist : Member 'System.Reflection.Emit.TypeBuilder.DefinePInvokeMetho
MembersMustExist : Member 'System.Reflection.Emit.TypeBuilder.TypeToken.get()' does not exist in the implementation but it does exist in the contract.
// Interfaces were intentional removals
+CannotRemoveBaseTypeOrInterface : Type 'System.ServiceProcess.TimeoutException' does not implement interface 'System.Runtime.InteropServices._Exception' in the implementation but it does in the contract.
CannotRemoveBaseTypeOrInterface : Type 'System.Net.NetworkInformation.PingException' does not implement interface 'System.Runtime.InteropServices._Exception' in the implementation but it does in the contract.
CannotRemoveBaseTypeOrInterface : Type 'System.AccessViolationException' does not implement interface 'System.Runtime.InteropServices._Exception' in the implementation but it does in the contract.
CannotRemoveBaseTypeOrInterface : Type 'System.Activator' does not implement interface 'System.Runtime.InteropServices._Activator' in the implementation but it does in the contract.
@@ -614,7 +615,6 @@ CannotRemoveBaseTypeOrInterface : Type 'System.Security.Authentication.Authentic
CannotRemoveBaseTypeOrInterface : Type 'System.Security.Authentication.InvalidCredentialException' does not implement interface 'System.Runtime.InteropServices._Exception' in the implementation but it does in the contract.
CannotRemoveBaseTypeOrInterface : Type 'System.Security.Permissions.StorePermissionAttribute' does not implement interface 'System.Runtime.InteropServices._Attribute' in the implementation but it does in the contract.
CannotRemoveBaseTypeOrInterface : Type 'System.Security.Permissions.TypeDescriptorPermissionAttribute' does not implement interface 'System.Runtime.InteropServices._Attribute' in the implementation but it does in the contract.
-CannotRemoveBaseTypeOrInterface : Type 'System.Text.RegularExpressions.RegexMatchTimeoutException' does not implement interface 'System.Runtime.InteropServices._Exception' in the implementation but it does in the contract.
CannotRemoveBaseTypeOrInterface : Type 'System.Threading.BarrierPostPhaseException' does not implement interface 'System.Runtime.InteropServices._Exception' in the implementation but it does in the contract.
CannotRemoveBaseTypeOrInterface : Type 'System.Threading.SemaphoreFullException' does not implement interface 'System.Runtime.InteropServices._Exception' in the implementation but it does in the contract.
CannotRemoveBaseTypeOrInterface : Type 'System.Timers.TimersDescriptionAttribute' does not implement interface 'System.Runtime.InteropServices._Attribute' in the implementation but it does in the contract.
@@ -778,7 +778,6 @@ CannotRemoveBaseTypeOrInterface : Type 'System.Configuration.ConfigurationValida
CannotRemoveBaseTypeOrInterface : Type 'System.Configuration.IntegerValidatorAttribute' does not implement interface 'System.Runtime.InteropServices._Attribute' in the implementation but it does in the contract.
CannotRemoveBaseTypeOrInterface : Type 'System.Configuration.LongValidatorAttribute' does not implement interface 'System.Runtime.InteropServices._Attribute' in the implementation but it does in the contract.
CannotRemoveBaseTypeOrInterface : Type 'System.Configuration.PositiveTimeSpanValidatorAttribute' does not implement interface 'System.Runtime.InteropServices._Attribute' in the implementation but it does in the contract.
-CannotRemoveBaseTypeOrInterface : Type 'System.Configuration.RegexStringValidatorAttribute' does not implement interface 'System.Runtime.InteropServices._Attribute' in the implementation but it does in the contract.
CannotRemoveBaseTypeOrInterface : Type 'System.Configuration.StringValidatorAttribute' does not implement interface 'System.Runtime.InteropServices._Attribute' in the implementation but it does in the contract.
CannotRemoveBaseTypeOrInterface : Type 'System.Configuration.SubclassTypeValidatorAttribute' does not implement interface 'System.Runtime.InteropServices._Attribute' in the implementation but it does in the contract.
CannotRemoveBaseTypeOrInterface : Type 'System.Configuration.TimeSpanValidatorAttribute' does not implement interface 'System.Runtime.InteropServices._Attribute' in the implementation but it does in the contract.
@@ -1205,7 +1204,6 @@ TypesMustExist : Type 'System.Security.Authentication.ExtendedProtection.Configu
TypesMustExist : Type 'System.Security.Authentication.ExtendedProtection.Configuration.ServiceNameElement' does not exist in the implementation but it does exist in the contract.
TypesMustExist : Type 'System.Security.Authentication.ExtendedProtection.Configuration.ServiceNameElementCollection' does not exist in the implementation but it does exist in the contract.
TypesMustExist : Type 'System.Security.Claims.DynamicRoleClaimProvider' does not exist in the implementation but it does exist in the contract.
-TypesMustExist : Type 'System.Text.RegularExpressions.RegexCompilationInfo' does not exist in the implementation but it does exist in the contract.
TypesMustExist : Type 'System.Web.AspNetHostingPermission' does not exist in the implementation but it does exist in the contract.
TypesMustExist : Type 'System.Web.AspNetHostingPermissionAttribute' does not exist in the implementation but it does exist in the contract.
TypesMustExist : Type 'System.Web.AspNetHostingPermissionLevel' does not exist in the implementation but it does exist in the contract.
@@ -3190,9 +3188,6 @@ MembersMustExist : Member 'System.Security.SecurityException.Zone.get()' does no
MembersMustExist : Member 'System.Security.SecurityException.Zone.set(System.Security.SecurityZone)' does not exist in the implementation but it does exist in the contract.
MembersMustExist : Member 'System.Threading.Thread.CurrentContext.get()' does not exist in the implementation but it does exist in the contract.
MembersMustExist : Member 'System.String System.Resources.ResourceManager.BaseNameField' does not exist in the implementation but it does exist in the contract.
-MembersMustExist : Member 'System.Text.RegularExpressions.Regex.CompileToAssembly(System.Text.RegularExpressions.RegexCompilationInfo[], System.Reflection.AssemblyName)' does not exist in the implementation but it does exist in the contract.
-MembersMustExist : Member 'System.Text.RegularExpressions.Regex.CompileToAssembly(System.Text.RegularExpressions.RegexCompilationInfo[], System.Reflection.AssemblyName, System.Reflection.Emit.CustomAttributeBuilder[])' does not exist in the implementation but it does exist in the contract.
-MembersMustExist : Member 'System.Text.RegularExpressions.Regex.CompileToAssembly(System.Text.RegularExpressions.RegexCompilationInfo[], System.Reflection.AssemblyName, System.Reflection.Emit.CustomAttributeBuilder[], System.String)' does not exist in the implementation but it does exist in the contract.
MembersMustExist : Member 'System.Threading.EventWaitHandle..ctor(System.Boolean, System.Threading.EventResetMode, System.String, System.Boolean, System.Security.AccessControl.EventWaitHandleSecurity)' does not exist in the implementation but it does exist in the contract.
MembersMustExist : Member 'System.Threading.EventWaitHandle.GetAccessControl()' does not exist in the implementation but it does exist in the contract.
MembersMustExist : Member 'System.Threading.EventWaitHandle.OpenExisting(System.String, System.Security.AccessControl.EventWaitHandleRights)' does not exist in the implementation but it does exist in the contract.
@@ -3225,4 +3220,24 @@ MembersMustExist : Member 'System.Xml.Xsl.XslCompiledTransform.CompileToType(Sys
MembersMustExist : Member 'System.Xml.Xsl.XslCompiledTransform.TemporaryFiles.get()' does not exist in the implementation but it does exist in the contract
MembersMustExist : Member 'System.Xml.Xsl.XslTransform.Load(System.Xml.XmlReader, System.Xml.XmlResolver, System.Security.Policy.Evidence)' does not exist in the implementation but it does exist in the contract.
MembersMustExist : Member 'System.Xml.Xsl.XslTransform.Load(System.Xml.XPath.IXPathNavigable, System.Xml.XmlResolver, System.Security.Policy.Evidence)' does not exist in the implementation but it does exist in the contract.
-MembersMustExist : Member 'System.Xml.Xsl.XslTransform.Load(System.Xml.XPath.XPathNavigator, System.Xml.XmlResolver, Syste \ No newline at end of file
+MembersMustExist : Member 'System.Xml.Xsl.XslTransform.Load(System.Xml.XPath.XPathNavigator, System.Xml.XmlResolver, Syste
+
+// Negligible usage, CAS
+TypesMustExist : Type 'System.ServiceProcess.ServiceControllerPermission' does not exist in the implementation but it does exist in the contract.
+TypesMustExist : Type 'System.ServiceProcess.ServiceControllerPermissionAccess' does not exist in the implementation but it does exist in the contract.
+TypesMustExist : Type 'System.ServiceProcess.ServiceControllerPermissionAttribute' does not exist in the implementation but it does exist in the contract.
+TypesMustExist : Type 'System.ServiceProcess.ServiceControllerPermissionEntry' does not exist in the implementation but it does exist in the contract.
+TypesMustExist : Type 'System.ServiceProcess.ServiceControllerPermissionEntryCollection' does not exist in the implementation but it does exist in the contract.
+
+// Undesirable dependencies
+TypesMustExist : Type 'System.ServiceProcess.Design.ServiceInstallerDialog' does not exist in the implementation but it does exist in the contract.
+TypesMustExist : Type 'System.ServiceProcess.Design.ServiceInstallerDialogResult' does not exist in the implementation but it does exist in the contract.
+TypesMustExist : Type 'System.ServiceProcess.ServiceInstaller' does not exist in the implementation but it does exist in the contract.
+TypesMustExist : Type 'System.ServiceProcess.ServiceProcessDescriptionAttribute' does not exist in the implementation but it does exist in the contract.
+TypesMustExist : Type 'System.ServiceProcess.ServiceProcessInstaller' does not exist in the implementation but it does exist in the contract.
+
+// Not bringing back argiterator
+TypesMustExist : Type 'System.ArgIterator' does not exist in the implementation but it does exist in the contract.
+MembersMustExist : Member 'System.Console.Write(System.String, System.Object, System.Object, System.Object, System.Object, __arglist)' does not exist in the implementation but it does exist in the contract.
+MembersMustExist : Member 'System.Console.WriteLine(System.String, System.Object, System.Object, System.Object, System.Object, __arglist)' does not exist in the implementation but it does exist in the contract.
+MembersMustExist : Member 'System.String.Concat(System.Object, System.Object, System.Object, System.Object, __arglist)' does not exist in the implementation but it does exist in the contract.
diff --git a/src/shims/ApiCompatBaseline.netcoreapp.netfx461.txt b/src/shims/ApiCompatBaseline.netcoreapp.netfx461.txt
index 2820a54b9e..7ac14f39f1 100644
--- a/src/shims/ApiCompatBaseline.netcoreapp.netfx461.txt
+++ b/src/shims/ApiCompatBaseline.netcoreapp.netfx461.txt
@@ -2,11 +2,11 @@ ApiCompat Error: 0 : Unable to resolve assembly 'Assembly(Name=System.ServiceMod
ApiCompat Error: 0 : Unable to resolve assembly 'Assembly(Name=System.Web.ApplicationServices, Version=4.0.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35)' referenced by the contract assembly 'Assembly(Name=System.Web, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a)'.
ApiCompat Error: 0 : Unable to resolve assembly 'Assembly(Name=System.ServiceModel, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089)' referenced by the contract assembly 'Assembly(Name=System.Xml.Serialization, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089)'.
ApiCompat Error: 0 : Unable to resolve assembly 'Assembly(Name=System.Xaml, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089)' referenced by the contract assembly 'Assembly(Name=WindowsBase, Version=4.0.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35)'.
-Compat issues with assembly mscorlib:
-TypesMustExist : Type 'System.ArgIterator' does not exist in the implementation but it does exist in the contract.
-MembersMustExist : Member 'System.Console.Write(System.String, System.Object, System.Object, System.Object, System.Object, __arglist)' does not exist in the implementation but it does exist in the contract.
-MembersMustExist : Member 'System.Console.WriteLine(System.String, System.Object, System.Object, System.Object, System.Object, __arglist)' does not exist in the implementation but it does exist in the contract.
-MembersMustExist : Member 'System.String.Concat(System.Object, System.Object, System.Object, System.Object, __arglist)' does not exist in the implementation but it does exist in the contract.
+ApiCompat Error: 0 : Unable to resolve assembly 'Assembly(Name=netstandard, Version=2.0.0.0, Culture=neutral, PublicKeyToken=cc7b13ffcd2ddd51)' referenced by the contract assembly 'Assembly(Name=System.DirectoryServices, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a)'.
+ApiCompat Error: 0 : Unable to resolve assembly 'Assembly(Name=netstandard, Version=2.0.0.0, Culture=neutral, PublicKeyToken=cc7b13ffcd2ddd51)' referenced by the contract assembly 'Assembly(Name=System.DirectoryServices.AccountManagement, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089)'.
+ApiCompat Error: 0 : Unable to resolve assembly 'Assembly(Name=System.Security.AccessControl, Version=4.1.1.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a)' referenced by the contract assembly 'Assembly(Name=System.DirectoryServices, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a)'.
+ApiCompat Error: 0 : Unable to resolve assembly 'Assembly(Name=System.IO.FileSystem.AccessControl, Version=4.0.3.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a)' referenced by the contract assembly 'Assembly(Name=System.DirectoryServices, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a)'.
+ApiCompat Error: 0 : Unable to resolve assembly 'Assembly(Name=netstandard, Version=2.0.0.0, Culture=neutral, PublicKeyToken=cc7b13ffcd2ddd51)' referenced by the contract assembly 'Assembly(Name=System.DirectoryServices.Protocols, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a)'.
Compat issues with assembly System:
MembersMustExist : Member 'System.CodeDom.Compiler.CompilerParameters.Evidence.get()' does not exist in the implementation but it does exist in the contract.
MembersMustExist : Member 'System.CodeDom.Compiler.CompilerParameters.Evidence.set(System.Security.Policy.Evidence)' does not exist in the implementation but it does exist in the contract.
@@ -67,45 +67,11 @@ MembersMustExist : Member 'System.Data.SqlClient.SqlConnectionStringBuilder.Netw
MembersMustExist : Member 'System.Data.SqlClient.SqlConnectionStringBuilder.TransparentNetworkIPResolution.get()' does not exist in the implementation but it does exist in the contract.
MembersMustExist : Member 'System.Data.SqlClient.SqlConnectionStringBuilder.TransparentNetworkIPResolution.set(System.Boolean)' does not exist in the implementation but it does exist in the contract.
MembersMustExist : Member 'System.Data.SqlClient.SqlDataReader.IsCommandBehavior(System.Data.CommandBehavior)' does not exist in the implementation but it does exist in the contract.
-MembersMustExist : Member 'System.Data.SqlClient.SqlParameter..ctor(System.String, System.Data.SqlDbType, System.Int32, System.Data.ParameterDirection, System.Boolean, System.Byte, System.Byte, System.String, System.Data.DataRowVersion, System.Object)' does not exist in the implementation but it does exist in the contract.
MembersMustExist : Member 'System.Data.SqlClient.SqlParameter.ForceColumnEncryption.get()' does not exist in the implementation but it does exist in the contract.
MembersMustExist : Member 'System.Data.SqlClient.SqlParameter.ForceColumnEncryption.set(System.Boolean)' does not exist in the implementation but it does exist in the contract.
MembersMustExist : Member 'System.Data.SqlClient.SqlParameter.UdtTypeName.get()' does not exist in the implementation but it does exist in the contract.
MembersMustExist : Member 'System.Data.SqlClient.SqlParameter.UdtTypeName.set(System.String)' does not exist in the implementation but it does exist in the contract.
MembersMustExist : Member 'System.Data.SqlClient.SqlParameterCollection.Add(System.String, System.Object)' does not exist in the implementation but it does exist in the contract.
-Compat issues with assembly System.DirectoryServices:
-TypesMustExist : Type 'System.DirectoryServices.DirectoryServicesPermission' does not exist in the implementation but it does exist in the contract.
-TypesMustExist : Type 'System.DirectoryServices.DirectoryServicesPermissionAccess' does not exist in the implementation but it does exist in the contract.
-TypesMustExist : Type 'System.DirectoryServices.DirectoryServicesPermissionAttribute' does not exist in the implementation but it does exist in the contract.
-TypesMustExist : Type 'System.DirectoryServices.DirectoryServicesPermissionEntry' does not exist in the implementation but it does exist in the contract.
-TypesMustExist : Type 'System.DirectoryServices.DirectoryServicesPermissionEntryCollection' does not exist in the implementation but it does exist in the contract.
-TypesMustExist : Type 'System.DirectoryServices.DSDescriptionAttribute' does not exist in the implementation but it does exist in the contract.
-Compat issues with assembly System.DirectoryServices.Protocols:
-MembersMustExist : Member 'System.DirectoryServices.Protocols.AddRequest.ToXmlNode(System.Xml.XmlDocument)' does not exist in the implementation but it does exist in the contract.
-CannotMakeTypeAbstract : Type 'System.DirectoryServices.Protocols.BerConverter' is abstract in the implementation but is not abstract in the contract.
-MembersMustExist : Member 'System.DirectoryServices.Protocols.CompareRequest.ToXmlNode(System.Xml.XmlDocument)' does not exist in the implementation but it does exist in the contract.
-MembersMustExist : Member 'System.DirectoryServices.Protocols.DeleteRequest.ToXmlNode(System.Xml.XmlDocument)' does not exist in the implementation but it does exist in the contract.
-MembersMustExist : Member 'System.DirectoryServices.Protocols.DirectoryRequest.ToXmlNode(System.Xml.XmlDocument)' does not exist in the implementation but it does exist in the contract.
-MembersMustExist : Member 'System.DirectoryServices.Protocols.DsmlAuthRequest.ToXmlNode(System.Xml.XmlDocument)' does not exist in the implementation but it does exist in the contract.
-TypesMustExist : Type 'System.DirectoryServices.Protocols.DsmlAuthResponse' does not exist in the implementation but it does exist in the contract.
-TypesMustExist : Type 'System.DirectoryServices.Protocols.DsmlDirectoryIdentifier' does not exist in the implementation but it does exist in the contract.
-TypesMustExist : Type 'System.DirectoryServices.Protocols.DsmlDocument' does not exist in the implementation but it does exist in the contract.
-TypesMustExist : Type 'System.DirectoryServices.Protocols.DsmlDocumentProcessing' does not exist in the implementation but it does exist in the contract.
-TypesMustExist : Type 'System.DirectoryServices.Protocols.DsmlErrorProcessing' does not exist in the implementation but it does exist in the contract.
-TypesMustExist : Type 'System.DirectoryServices.Protocols.DsmlErrorResponse' does not exist in the implementation but it does exist in the contract.
-TypesMustExist : Type 'System.DirectoryServices.Protocols.DsmlInvalidDocumentException' does not exist in the implementation but it does exist in the contract.
-TypesMustExist : Type 'System.DirectoryServices.Protocols.DsmlRequestDocument' does not exist in the implementation but it does exist in the contract.
-TypesMustExist : Type 'System.DirectoryServices.Protocols.DsmlResponseDocument' does not exist in the implementation but it does exist in the contract.
-TypesMustExist : Type 'System.DirectoryServices.Protocols.DsmlResponseOrder' does not exist in the implementation but it does exist in the contract.
-TypesMustExist : Type 'System.DirectoryServices.Protocols.DsmlSoapConnection' does not exist in the implementation but it does exist in the contract.
-TypesMustExist : Type 'System.DirectoryServices.Protocols.DsmlSoapHttpConnection' does not exist in the implementation but it does exist in the contract.
-TypesMustExist : Type 'System.DirectoryServices.Protocols.ErrorResponseCategory' does not exist in the implementation but it does exist in the contract.
-TypesMustExist : Type 'System.DirectoryServices.Protocols.ErrorResponseException' does not exist in the implementation but it does exist in the contract.
-MembersMustExist : Member 'System.DirectoryServices.Protocols.ExtendedRequest.ToXmlNode(System.Xml.XmlDocument)' does not exist in the implementation but it does exist in the contract.
-MembersMustExist : Member 'System.DirectoryServices.Protocols.ModifyDNRequest.ToXmlNode(System.Xml.XmlDocument)' does not exist in the implementation but it does exist in the contract.
-MembersMustExist : Member 'System.DirectoryServices.Protocols.ModifyRequest.ToXmlNode(System.Xml.XmlDocument)' does not exist in the implementation but it does exist in the contract.
-MembersMustExist : Member 'System.DirectoryServices.Protocols.SearchRequest..ctor(System.String, System.Xml.XmlDocument, System.DirectoryServices.Protocols.SearchScope, System.String[])' does not exist in the implementation but it does exist in the contract.
-MembersMustExist : Member 'System.DirectoryServices.Protocols.SearchRequest.ToXmlNode(System.Xml.XmlDocument)' does not exist in the implementation but it does exist in the contract.
Compat issues with assembly System.Security:
MembersMustExist : Member 'System.Security.Cryptography.CryptographicAttributeObjectCollection.IsSynchronized.get()' does not exist in the implementation but it does exist in the contract.
MembersMustExist : Member 'System.Security.Cryptography.CryptographicAttributeObjectCollection.SyncRoot.get()' does not exist in the implementation but it does exist in the contract.
@@ -130,36 +96,14 @@ TypesMustExist : Type 'System.Security.Cryptography.Pkcs.SignerInfoCollection' d
TypesMustExist : Type 'System.Security.Cryptography.Pkcs.SignerInfoEnumerator' does not exist in the implementation but it does exist in the contract.
TypesMustExist : Type 'System.Security.Cryptography.X509Certificates.X509Certificate2UI' does not exist in the implementation but it does exist in the contract.
TypesMustExist : Type 'System.Security.Cryptography.X509Certificates.X509SelectionFlag' does not exist in the implementation but it does exist in the contract.
-MembersMustExist : Member 'System.Security.Cryptography.Xml.EncryptedXml..ctor(System.Xml.XmlDocument, System.Security.Policy.Evidence)' does not exist in the implementation but it does exist in the contract.
-MembersMustExist : Member 'System.Security.Cryptography.Xml.EncryptedXml.DocumentEvidence.get()' does not exist in the implementation but it does exist in the contract.
-MembersMustExist : Member 'System.Security.Cryptography.Xml.EncryptedXml.DocumentEvidence.set(System.Security.Policy.Evidence)' does not exist in the implementation but it does exist in the contract.
TypesMustExist : Type 'System.Security.Permissions.DataProtectionPermission' does not exist in the implementation but it does exist in the contract.
TypesMustExist : Type 'System.Security.Permissions.DataProtectionPermissionAttribute' does not exist in the implementation but it does exist in the contract.
TypesMustExist : Type 'System.Security.Permissions.DataProtectionPermissionFlags' does not exist in the implementation but it does exist in the contract.
Compat issues with assembly System.ServiceProcess:
-TypesMustExist : Type 'System.ServiceProcess.PowerBroadcastStatus' does not exist in the implementation but it does exist in the contract.
TypesMustExist : Type 'System.ServiceProcess.ServiceAccount' does not exist in the implementation but it does exist in the contract.
-TypesMustExist : Type 'System.ServiceProcess.ServiceBase' does not exist in the implementation but it does exist in the contract.
-CannotRemoveBaseTypeOrInterface : Type 'System.ServiceProcess.ServiceController' does not inherit from base type 'System.ComponentModel.Component' in the implementation but it does in the contract.
-MembersMustExist : Member 'System.ServiceProcess.ServiceController..ctor()' does not exist in the implementation but it does exist in the contract.
-MembersMustExist : Member 'System.ServiceProcess.ServiceController.Close()' does not exist in the implementation but it does exist in the contract.
-MembersMustExist : Member 'System.ServiceProcess.ServiceController.DisplayName.set(System.String)' does not exist in the implementation but it does exist in the contract.
-MembersMustExist : Member 'System.ServiceProcess.ServiceController.ExecuteCommand(System.Int32)' does not exist in the implementation but it does exist in the contract.
-MembersMustExist : Member 'System.ServiceProcess.ServiceController.MachineName.set(System.String)' does not exist in the implementation but it does exist in the contract.
-MembersMustExist : Member 'System.ServiceProcess.ServiceController.ServiceName.set(System.String)' does not exist in the implementation but it does exist in the contract.
-TypesMustExist : Type 'System.ServiceProcess.ServiceControllerPermission' does not exist in the implementation but it does exist in the contract.
-TypesMustExist : Type 'System.ServiceProcess.ServiceControllerPermissionAccess' does not exist in the implementation but it does exist in the contract.
-TypesMustExist : Type 'System.ServiceProcess.ServiceControllerPermissionAttribute' does not exist in the implementation but it does exist in the contract.
-TypesMustExist : Type 'System.ServiceProcess.ServiceControllerPermissionEntry' does not exist in the implementation but it does exist in the contract.
-TypesMustExist : Type 'System.ServiceProcess.ServiceControllerPermissionEntryCollection' does not exist in the implementation but it does exist in the contract.
-TypesMustExist : Type 'System.ServiceProcess.ServiceInstaller' does not exist in the implementation but it does exist in the contract.
-TypesMustExist : Type 'System.ServiceProcess.ServiceProcessDescriptionAttribute' does not exist in the implementation but it does exist in the contract.
-TypesMustExist : Type 'System.ServiceProcess.ServiceProcessInstaller' does not exist in the implementation but it does exist in the contract.
-TypesMustExist : Type 'System.ServiceProcess.SessionChangeDescription' does not exist in the implementation but it does exist in the contract.
-TypesMustExist : Type 'System.ServiceProcess.SessionChangeReason' does not exist in the implementation but it does exist in the contract.
-CannotRemoveBaseTypeOrInterface : Type 'System.ServiceProcess.TimeoutException' does not inherit from base type 'System.SystemException' in the implementation but it does in the contract.
-TypesMustExist : Type 'System.ServiceProcess.Design.ServiceInstallerDialog' does not exist in the implementation but it does exist in the contract.
-TypesMustExist : Type 'System.ServiceProcess.Design.ServiceInstallerDialogResult' does not exist in the implementation but it does exist in the contract.
+MembersMustExist : Member 'System.ServiceProcess.ServiceBase.AutoLog.get()' does not exist in the implementation but it does exist in the contract.
+MembersMustExist : Member 'System.ServiceProcess.ServiceBase.AutoLog.set(System.Boolean)' does not exist in the implementation but it does exist in the contract.
+MembersMustExist : Member 'System.ServiceProcess.ServiceBase.EventLog.get()' does not exist in the implementation but it does exist in the contract.
Compat issues with assembly System.Xml:
MembersMustExist : Member 'System.Xml.Xsl.XslCompiledTransform.TemporaryFiles.get()' does not exist in the implementation but it does exist in the contract.
MembersMustExist : Member 'System.Xml.Xsl.XslTransform.Load(System.Xml.XPath.XPathNavigator, System.Xml.XmlResolver, System.Security.Policy.Evidence)' does not exist in the implementation but it does exist in the contract.
@@ -312,4 +256,4 @@ TypesMustExist : Type 'System.Windows.Threading.DispatcherUnhandledExceptionEven
TypesMustExist : Type 'System.Windows.Threading.DispatcherUnhandledExceptionEventHandler' does not exist in the implementation but it does exist in the contract.
TypesMustExist : Type 'System.Windows.Threading.DispatcherUnhandledExceptionFilterEventArgs' does not exist in the implementation but it does exist in the contract.
TypesMustExist : Type 'System.Windows.Threading.DispatcherUnhandledExceptionFilterEventHandler' does not exist in the implementation but it does exist in the contract.
-Total Issues: 300
+Total Issues: 242
diff --git a/src/shims/manual/mscorlib.forwards.cs b/src/shims/manual/mscorlib.forwards.cs
index 6494ab6d1c..1aa08e3505 100644
--- a/src/shims/manual/mscorlib.forwards.cs
+++ b/src/shims/manual/mscorlib.forwards.cs
@@ -20,6 +20,7 @@
[assembly:System.Runtime.CompilerServices.TypeForwardedTo(typeof(System.Collections.Generic.ShortEnumEqualityComparer<>))]
[assembly:System.Runtime.CompilerServices.TypeForwardedTo(typeof(System.Collections.Generic.LongEnumEqualityComparer<>))]
[assembly:System.Runtime.CompilerServices.TypeForwardedTo(typeof(System.Collections.ListDictionaryInternal))]
+[assembly:System.Runtime.CompilerServices.TypeForwardedTo(typeof(System.UnitySerializationHolder))]
// This is temporary as we are building the mscorlib shim against netfx461 which doesn't contain ValueTuples.
[assembly:System.Runtime.CompilerServices.TypeForwardedTo(typeof(System.ValueTuple))]
diff --git a/src/src.builds b/src/src.builds
index b6f33f1e6a..40124b0f79 100644
--- a/src/src.builds
+++ b/src/src.builds
@@ -28,6 +28,7 @@
</PropertyGroup>
<GenerateDepsJson DepsJsonPath="$(_OriginalDepsJsonPath)"
+ GenerateNewDepsJson="true"
RuntimeDirectory="$(NETCoreAppTestSharedFrameworkPath)"
DepsExceptions="@(ExceptionForDepsJson)"
OutputPath="$(_OutputTestSharedFrameworkDepsPath)"/>