<Compile Include="System\Buffers\PoisonPagePlacement.cs" />
<Compile Include="System\IO\FileCleanupTestBase.cs" />
<Compile Include="System\TestEnvironment.cs" />
+ <Compile Include="System\ThreadCultureChange.cs" />
+ <Compile Include="System\Diagnostics\RemoteExecutorForUap.cs" />
<!-- We don't compile per but and instead use runtime platform checks. -->
<Compile Include="System\PlatformDetection.cs" />
<Compile Include="System\PlatformDetection.Unix.cs" />
</Compile>
</ItemGroup>
<ItemGroup>
+ <PackageReference Include="Microsoft.DotNet.RemoteExecutor" Version="$(MicrosoftDotNetRemoteExecutorPackageVersion)" />
<PackageReference Include="Microsoft.DotNet.XUnitExtensions" Version="$(MicrosoftDotNetXUnitExtensionsPackageVersion)" />
<PackageReference Include="xunit.core" Version="$(XUnitPackageVersion)" ExcludeAssets="build" />
<PackageReference Include="xunit.assert" Version="$(XUnitPackageVersion)" />
--- /dev/null
+// 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;
+
+namespace Microsoft.DotNet.RemoteExecutor
+{
+ /// <summary>
+ /// Wraps <see cref="RemoteExecutor"/>, using it only when running on UAP, and otherwise
+ /// invoking the action synchronously without any additional sandboxing.
+ /// </summary>
+ /// <remarks>
+ /// This is a workaround for UAP's current behavior for CultureInfo.Current{UI}Culture,
+ /// which is process-wide rather than thread-specific. When that behavior is fixed,
+ /// all use of this type should be removable.
+ /// </remarks>
+ public static class RemoteExecutorForUap
+ {
+ public static RemoteInvokeHandle Invoke(Action action)
+ {
+ if (PlatformDetection.IsUap)
+ {
+ return RemoteExecutor.Invoke(action);
+ }
+
+ action();
+ return new RemoteInvokeHandle(null, null);
+ }
+
+ public static RemoteInvokeHandle Invoke(Action<string> action, string arg)
+ {
+ if (PlatformDetection.IsUap)
+ {
+ return RemoteExecutor.Invoke(action, arg);
+ }
+
+ action(arg);
+ return new RemoteInvokeHandle(null, null);
+ }
+
+ public static RemoteInvokeHandle Invoke(Action<string, string> action, string arg1, string arg2)
+ {
+ if (PlatformDetection.IsUap)
+ {
+ return RemoteExecutor.Invoke(action, arg1, arg2);
+ }
+
+ action(arg1, arg2);
+ return new RemoteInvokeHandle(null, null);
+ }
+
+ public static RemoteInvokeHandle Invoke(Action<string, string, string> action, string arg1, string arg2, string arg3)
+ {
+ if (PlatformDetection.IsUap)
+ {
+ return RemoteExecutor.Invoke(action, arg1, arg2, arg3);
+ }
+
+ action(arg1, arg2, arg3);
+ return new RemoteInvokeHandle(null, null);
+ }
+
+ public static RemoteInvokeHandle Invoke(Action<string, string, string, string> action, string arg1, string arg2, string arg3, string arg4)
+ {
+ if (PlatformDetection.IsUap)
+ {
+ return RemoteExecutor.Invoke(action, arg1, arg2, arg3, arg4);
+ }
+
+ action(arg1, arg2, arg3, arg4);
+ return new RemoteInvokeHandle(null, null);
+ }
+
+ public static RemoteInvokeHandle Invoke(Func<string, string, string, string, string, int> func, string arg1, string arg2, string arg3, string arg4, string arg5)
+ {
+ if (PlatformDetection.IsUap)
+ {
+ return RemoteExecutor.Invoke(func, arg1, arg2, arg3, arg4, arg5);
+ }
+
+ func(arg1, arg2, arg3, arg4, arg5); // ignore return value for now, though it should really be marshaled out through the RemoteInvokeHandle
+ return new RemoteInvokeHandle(null, null);
+ }
+ }
+}
--- /dev/null
+// 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.
+
+#nullable enable
+using System.Globalization;
+
+namespace System.Tests
+{
+ public sealed class ThreadCultureChange : IDisposable
+ {
+ private readonly CultureInfo _origCulture = CultureInfo.CurrentCulture;
+ private readonly CultureInfo _origUICulture = CultureInfo.CurrentUICulture;
+
+ public ThreadCultureChange(string? cultureName) :
+ this(cultureName != null ? new CultureInfo(cultureName) : null)
+ {
+ }
+
+ public ThreadCultureChange(CultureInfo? newCulture) :
+ this(newCulture, null)
+ {
+ }
+
+ public ThreadCultureChange(CultureInfo? newCulture, CultureInfo? newUICulture)
+ {
+ if (newCulture != null)
+ {
+ _origCulture = CultureInfo.CurrentCulture;
+ CultureInfo.CurrentCulture = newCulture;
+ }
+
+ if (newUICulture != null)
+ {
+ _origUICulture = CultureInfo.CurrentUICulture;
+ CultureInfo.CurrentUICulture = newUICulture;
+ }
+ }
+
+ public void Dispose()
+ {
+ CultureInfo.CurrentCulture = _origCulture;
+ CultureInfo.CurrentUICulture = _origUICulture;
+ }
+ }
+}
+++ /dev/null
-// 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.Globalization;
-
-namespace System.Common.Tests
-{
- public sealed class ThreadCultureChange : IDisposable
- {
- private readonly CultureInfo _originalCultureInfo = CultureInfo.CurrentCulture;
- private readonly CultureInfo _originalUICultureInfo = CultureInfo.CurrentUICulture;
-
- public ThreadCultureChange() { }
-
- public ThreadCultureChange(string culture) : this()
- {
- ChangeCultureInfo(culture);
- }
-
- public ThreadCultureChange(CultureInfo newCulture) : this()
- {
- ChangeCultureInfo(newCulture);
- }
-
- public void ChangeCultureInfo(string culture) => ChangeCultureInfo(new CultureInfo(culture));
-
- public void ChangeCultureInfo(CultureInfo newCulture)
- {
- CultureInfo.CurrentCulture = newCulture;
- CultureInfo.CurrentUICulture = newCulture;
- }
-
- public void Dispose()
- {
- CultureInfo.CurrentCulture = _originalCultureInfo;
- CultureInfo.CurrentUICulture = _originalUICultureInfo;
- }
- }
-}
[Fact]
public static void EndsWithMatchNonOrdinal_StringComparison()
{
- RemoteExecutor.Invoke(() =>
+ RemoteExecutorForUap.Invoke(() =>
{
string s = "dabc";
string value = "aBc";
Assert.False(span.EndsWith(spanValue, StringComparison.Ordinal));
Assert.True(span.EndsWith(spanValue, StringComparison.OrdinalIgnoreCase));
- CultureInfo backupCulture = CultureInfo.CurrentCulture;
-
- Thread.CurrentThread.CurrentCulture = new CultureInfo("el-GR");
-
- s = "\u03b4\u03b1\u03b2\u03b3"; // \u03B4\u03B1\u03B2\u03B3
- value = "\u03b1\u03b2\u03b3"; // \u03B1\u03B2\u03B3
-
- Assert.True(s.EndsWith(value, StringComparison.CurrentCulture));
- Assert.True(s.EndsWith(value, StringComparison.CurrentCultureIgnoreCase));
+ using (new ThreadCultureChange("el-GR"))
+ {
+ s = "\u03b4\u03b1\u03b2\u03b3"; // \u03B4\u03B1\u03B2\u03B3
+ value = "\u03b1\u03b2\u03b3"; // \u03B1\u03B2\u03B3
- span = s.AsSpan(); // \u03B4\u03B1\u03B2\u03B3
- spanValue = value.AsSpan(); // \u03B1\u03B2\u03B3
+ Assert.True(s.EndsWith(value, StringComparison.CurrentCulture));
+ Assert.True(s.EndsWith(value, StringComparison.CurrentCultureIgnoreCase));
- Assert.True(span.EndsWith(spanValue, StringComparison.CurrentCulture));
- Assert.True(span.EndsWith(spanValue, StringComparison.CurrentCultureIgnoreCase));
+ span = s.AsSpan(); // \u03B4\u03B1\u03B2\u03B3
+ spanValue = value.AsSpan(); // \u03B1\u03B2\u03B3
- value = "\u03b1\u0392\u03b3"; // \u03B1\u0392\u03B3
- Assert.False(s.EndsWith(value, StringComparison.CurrentCulture));
- Assert.True(s.EndsWith(value, StringComparison.CurrentCultureIgnoreCase));
+ Assert.True(span.EndsWith(spanValue, StringComparison.CurrentCulture));
+ Assert.True(span.EndsWith(spanValue, StringComparison.CurrentCultureIgnoreCase));
- spanValue = value.AsSpan(); // \u03B1\u0392\u03B3
- Assert.False(span.EndsWith(spanValue, StringComparison.CurrentCulture));
- Assert.True(span.EndsWith(spanValue, StringComparison.CurrentCultureIgnoreCase));
+ value = "\u03b1\u0392\u03b3"; // \u03B1\u0392\u03B3
+ Assert.False(s.EndsWith(value, StringComparison.CurrentCulture));
+ Assert.True(s.EndsWith(value, StringComparison.CurrentCultureIgnoreCase));
- Thread.CurrentThread.CurrentCulture = backupCulture;
+ spanValue = value.AsSpan(); // \u03B1\u0392\u03B3
+ Assert.False(span.EndsWith(spanValue, StringComparison.CurrentCulture));
+ Assert.True(span.EndsWith(spanValue, StringComparison.CurrentCultureIgnoreCase));
+ }
s = "\u03b4\u0069\u00df\u0049"; // \u03B4i\u00DFI
value = "\u0069\u0073\u0073\u0049"; // issI
[Fact]
public static void EndsWithNoMatchNonOrdinal_StringComparison()
{
- RemoteExecutor.Invoke(() =>
+ RemoteExecutorForUap.Invoke(() =>
{
string s = "dabc";
string value = "aDc";
Assert.False(span.EndsWith(spanValue, StringComparison.Ordinal));
Assert.False(span.EndsWith(spanValue, StringComparison.OrdinalIgnoreCase));
- CultureInfo backupCulture = CultureInfo.CurrentCulture;
-
- Thread.CurrentThread.CurrentCulture = new CultureInfo("el-GR");
-
- s = "\u03b4\u03b1\u03b2\u03b3"; // \u03B4\u03B1\u03B2\u03B3
- value = "\u03b1\u03b4\u03b3"; // \u03B1\u03B4\u03B3
-
- Assert.False(s.EndsWith(value, StringComparison.CurrentCulture));
- Assert.False(s.EndsWith(value, StringComparison.CurrentCultureIgnoreCase));
+ using (new ThreadCultureChange("el-GR"))
+ {
+ s = "\u03b4\u03b1\u03b2\u03b3"; // \u03B4\u03B1\u03B2\u03B3
+ value = "\u03b1\u03b4\u03b3"; // \u03B1\u03B4\u03B3
- span = s.AsSpan(); // \u03B4\u03B1\u03B2\u03B3
- spanValue = value.AsSpan(); // \u03B1\u03B4\u03B3
+ Assert.False(s.EndsWith(value, StringComparison.CurrentCulture));
+ Assert.False(s.EndsWith(value, StringComparison.CurrentCultureIgnoreCase));
- Assert.False(span.EndsWith(spanValue, StringComparison.CurrentCulture));
- Assert.False(span.EndsWith(spanValue, StringComparison.CurrentCultureIgnoreCase));
+ span = s.AsSpan(); // \u03B4\u03B1\u03B2\u03B3
+ spanValue = value.AsSpan(); // \u03B1\u03B4\u03B3
- value = "\u03b1\u0394\u03b3"; // \u03B1\u0394\u03B3
- Assert.False(s.EndsWith(value, StringComparison.CurrentCulture));
- Assert.False(s.EndsWith(value, StringComparison.CurrentCultureIgnoreCase));
+ Assert.False(span.EndsWith(spanValue, StringComparison.CurrentCulture));
+ Assert.False(span.EndsWith(spanValue, StringComparison.CurrentCultureIgnoreCase));
- spanValue = value.AsSpan(); // \u03B1\u0394\u03B3
- Assert.False(span.EndsWith(spanValue, StringComparison.CurrentCulture));
- Assert.False(span.EndsWith(spanValue, StringComparison.CurrentCultureIgnoreCase));
+ value = "\u03b1\u0394\u03b3"; // \u03B1\u0394\u03B3
+ Assert.False(s.EndsWith(value, StringComparison.CurrentCulture));
+ Assert.False(s.EndsWith(value, StringComparison.CurrentCultureIgnoreCase));
- Thread.CurrentThread.CurrentCulture = backupCulture;
+ spanValue = value.AsSpan(); // \u03B1\u0394\u03B3
+ Assert.False(span.EndsWith(spanValue, StringComparison.CurrentCulture));
+ Assert.False(span.EndsWith(spanValue, StringComparison.CurrentCultureIgnoreCase));
+ }
s = "\u03b4\u0069\u00df\u0049"; // \u03B4i\u00DFI
value = "\u0069\u03b4\u03b4\u0049"; // i\u03B4\u03B4I
[MemberData(nameof(Equals_EncyclopaediaData))]
public void Equals_Encyclopaedia_ReturnsExpected(StringComparison comparison, bool expected)
{
- RemoteExecutor.Invoke((comparisonString, expectedString) =>
+ RemoteExecutorForUap.Invoke((comparisonString, expectedString) =>
{
string source = "encyclop\u00e6dia";
string target = "encyclopaedia";
- CultureInfo.CurrentCulture = new CultureInfo("se-SE");
- StringComparison comparisonType = (StringComparison)Enum.Parse(typeof(StringComparison), comparisonString);
- Assert.Equal(bool.Parse(expectedString), string.Equals(source, target, comparisonType));
-
- Assert.Equal(bool.Parse(expectedString), source.AsSpan().Equals(target.AsSpan(), comparisonType));
-
- return RemoteExecutor.SuccessExitCode;
+ using (new ThreadCultureChange("se-SE"))
+ {
+ StringComparison comparisonType = (StringComparison)Enum.Parse(typeof(StringComparison), comparisonString);
+ Assert.Equal(bool.Parse(expectedString), string.Equals(source, target, comparisonType));
+ Assert.Equal(bool.Parse(expectedString), source.AsSpan().Equals(target.AsSpan(), comparisonType));
+ }
}, comparison.ToString(), expected.ToString()).Dispose();
}
[Fact]
public static void IndexOf_TurkishI_TurkishCulture()
{
- RemoteExecutor.Invoke(() =>
+ RemoteExecutorForUap.Invoke(() =>
{
- CultureInfo.CurrentCulture = new CultureInfo("tr-TR");
-
- string s = "Turkish I \u0131s TROUBL\u0130NG!";
- string value = "\u0130";
- Assert.Equal(19, s.IndexOf(value));
- Assert.Equal(19, s.IndexOf(value, StringComparison.CurrentCulture));
- Assert.Equal(4, s.IndexOf(value, StringComparison.CurrentCultureIgnoreCase));
- Assert.Equal(19, s.IndexOf(value, StringComparison.Ordinal));
- Assert.Equal(19, s.IndexOf(value, StringComparison.OrdinalIgnoreCase));
-
- ReadOnlySpan<char> span = s.AsSpan();
- Assert.Equal(19, span.IndexOf(value.AsSpan(), StringComparison.CurrentCulture));
- Assert.Equal(4, span.IndexOf(value.AsSpan(), StringComparison.CurrentCultureIgnoreCase));
- Assert.Equal(19, span.IndexOf(value.AsSpan(), StringComparison.Ordinal));
- Assert.Equal(19, span.IndexOf(value.AsSpan(), StringComparison.OrdinalIgnoreCase));
-
- value = "\u0131";
- Assert.Equal(10, s.IndexOf(value, StringComparison.CurrentCulture));
- Assert.Equal(8, s.IndexOf(value, StringComparison.CurrentCultureIgnoreCase));
- Assert.Equal(10, s.IndexOf(value, StringComparison.Ordinal));
- Assert.Equal(10, s.IndexOf(value, StringComparison.OrdinalIgnoreCase));
-
- Assert.Equal(10, span.IndexOf(value.AsSpan(), StringComparison.CurrentCulture));
- Assert.Equal(8, span.IndexOf(value.AsSpan(), StringComparison.CurrentCultureIgnoreCase));
- Assert.Equal(10, span.IndexOf(value.AsSpan(), StringComparison.Ordinal));
- Assert.Equal(10, span.IndexOf(value.AsSpan(), StringComparison.OrdinalIgnoreCase));
-
- return RemoteExecutor.SuccessExitCode;
+ using (new ThreadCultureChange("tr-TR"))
+ {
+ string s = "Turkish I \u0131s TROUBL\u0130NG!";
+ string value = "\u0130";
+ Assert.Equal(19, s.IndexOf(value));
+ Assert.Equal(19, s.IndexOf(value, StringComparison.CurrentCulture));
+ Assert.Equal(4, s.IndexOf(value, StringComparison.CurrentCultureIgnoreCase));
+ Assert.Equal(19, s.IndexOf(value, StringComparison.Ordinal));
+ Assert.Equal(19, s.IndexOf(value, StringComparison.OrdinalIgnoreCase));
+
+ ReadOnlySpan<char> span = s.AsSpan();
+ Assert.Equal(19, span.IndexOf(value.AsSpan(), StringComparison.CurrentCulture));
+ Assert.Equal(4, span.IndexOf(value.AsSpan(), StringComparison.CurrentCultureIgnoreCase));
+ Assert.Equal(19, span.IndexOf(value.AsSpan(), StringComparison.Ordinal));
+ Assert.Equal(19, span.IndexOf(value.AsSpan(), StringComparison.OrdinalIgnoreCase));
+
+ value = "\u0131";
+ Assert.Equal(10, s.IndexOf(value, StringComparison.CurrentCulture));
+ Assert.Equal(8, s.IndexOf(value, StringComparison.CurrentCultureIgnoreCase));
+ Assert.Equal(10, s.IndexOf(value, StringComparison.Ordinal));
+ Assert.Equal(10, s.IndexOf(value, StringComparison.OrdinalIgnoreCase));
+
+ Assert.Equal(10, span.IndexOf(value.AsSpan(), StringComparison.CurrentCulture));
+ Assert.Equal(8, span.IndexOf(value.AsSpan(), StringComparison.CurrentCultureIgnoreCase));
+ Assert.Equal(10, span.IndexOf(value.AsSpan(), StringComparison.Ordinal));
+ Assert.Equal(10, span.IndexOf(value.AsSpan(), StringComparison.OrdinalIgnoreCase));
+ }
}).Dispose();
}
[Fact]
public static void IndexOf_TurkishI_InvariantCulture()
{
- RemoteExecutor.Invoke(() =>
+ RemoteExecutorForUap.Invoke(() =>
{
- CultureInfo.CurrentCulture = CultureInfo.InvariantCulture;
-
- string s = "Turkish I \u0131s TROUBL\u0130NG!";
- string value = "\u0130";
-
- Assert.Equal(19, s.IndexOf(value));
- Assert.Equal(19, s.IndexOf(value, StringComparison.CurrentCulture));
- Assert.Equal(19, s.IndexOf(value, StringComparison.CurrentCultureIgnoreCase));
+ using (new ThreadCultureChange(CultureInfo.InvariantCulture))
+ {
+ string s = "Turkish I \u0131s TROUBL\u0130NG!";
+ string value = "\u0130";
- ReadOnlySpan<char> span = s.AsSpan();
- Assert.Equal(19, span.IndexOf(value.AsSpan(), StringComparison.CurrentCulture));
- Assert.Equal(19, span.IndexOf(value.AsSpan(), StringComparison.CurrentCultureIgnoreCase));
+ Assert.Equal(19, s.IndexOf(value));
+ Assert.Equal(19, s.IndexOf(value, StringComparison.CurrentCulture));
+ Assert.Equal(19, s.IndexOf(value, StringComparison.CurrentCultureIgnoreCase));
- value = "\u0131";
- Assert.Equal(10, s.IndexOf(value, StringComparison.CurrentCulture));
- Assert.Equal(10, s.IndexOf(value, StringComparison.CurrentCultureIgnoreCase));
+ ReadOnlySpan<char> span = s.AsSpan();
+ Assert.Equal(19, span.IndexOf(value.AsSpan(), StringComparison.CurrentCulture));
+ Assert.Equal(19, span.IndexOf(value.AsSpan(), StringComparison.CurrentCultureIgnoreCase));
- Assert.Equal(10, span.IndexOf(value.AsSpan(), StringComparison.CurrentCulture));
- Assert.Equal(10, span.IndexOf(value.AsSpan(), StringComparison.CurrentCultureIgnoreCase));
+ value = "\u0131";
+ Assert.Equal(10, s.IndexOf(value, StringComparison.CurrentCulture));
+ Assert.Equal(10, s.IndexOf(value, StringComparison.CurrentCultureIgnoreCase));
- return RemoteExecutor.SuccessExitCode;
+ Assert.Equal(10, span.IndexOf(value.AsSpan(), StringComparison.CurrentCulture));
+ Assert.Equal(10, span.IndexOf(value.AsSpan(), StringComparison.CurrentCultureIgnoreCase));
+ }
}).Dispose();
}
[Fact]
public static void IndexOf_TurkishI_EnglishUSCulture()
{
- RemoteExecutor.Invoke(() =>
+ RemoteExecutorForUap.Invoke(() =>
{
- CultureInfo.CurrentCulture = new CultureInfo("en-US");
-
- string s = "Turkish I \u0131s TROUBL\u0130NG!";
- string value = "\u0130";
-
- value = "\u0130";
- Assert.Equal(19, s.IndexOf(value));
- Assert.Equal(19, s.IndexOf(value, StringComparison.CurrentCulture));
- Assert.Equal(19, s.IndexOf(value, StringComparison.CurrentCultureIgnoreCase));
+ using (new ThreadCultureChange("en-US"))
+ {
+ string s = "Turkish I \u0131s TROUBL\u0130NG!";
+ string value = "\u0130";
- ReadOnlySpan<char> span = s.AsSpan();
- Assert.Equal(19, span.IndexOf(value.AsSpan(), StringComparison.CurrentCulture));
- Assert.Equal(19, span.IndexOf(value.AsSpan(), StringComparison.CurrentCultureIgnoreCase));
+ value = "\u0130";
+ Assert.Equal(19, s.IndexOf(value));
+ Assert.Equal(19, s.IndexOf(value, StringComparison.CurrentCulture));
+ Assert.Equal(19, s.IndexOf(value, StringComparison.CurrentCultureIgnoreCase));
- value = "\u0131";
- Assert.Equal(10, s.IndexOf(value, StringComparison.CurrentCulture));
- Assert.Equal(10, s.IndexOf(value, StringComparison.CurrentCultureIgnoreCase));
+ ReadOnlySpan<char> span = s.AsSpan();
+ Assert.Equal(19, span.IndexOf(value.AsSpan(), StringComparison.CurrentCulture));
+ Assert.Equal(19, span.IndexOf(value.AsSpan(), StringComparison.CurrentCultureIgnoreCase));
- Assert.Equal(10, span.IndexOf(value.AsSpan(), StringComparison.CurrentCulture));
- Assert.Equal(10, span.IndexOf(value.AsSpan(), StringComparison.CurrentCultureIgnoreCase));
+ value = "\u0131";
+ Assert.Equal(10, s.IndexOf(value, StringComparison.CurrentCulture));
+ Assert.Equal(10, s.IndexOf(value, StringComparison.CurrentCultureIgnoreCase));
- return RemoteExecutor.SuccessExitCode;
+ Assert.Equal(10, span.IndexOf(value.AsSpan(), StringComparison.CurrentCulture));
+ Assert.Equal(10, span.IndexOf(value.AsSpan(), StringComparison.CurrentCultureIgnoreCase));
+ }
}).Dispose();
}
[Fact]
public static void IndexOf_HungarianDoubleCompression_HungarianCulture()
{
- RemoteExecutor.Invoke(() =>
+ RemoteExecutorForUap.Invoke(() =>
{
- string source = "dzsdzs";
- string target = "ddzs";
-
- CultureInfo.CurrentCulture = new CultureInfo("hu-HU");
- /*
- There are differences between Windows and ICU regarding contractions.
- Windows has equal contraction collation weights, including case (target="Ddzs" same behavior as "ddzs").
- ICU has different contraction collation weights, depending on locale collation rules.
- If CurrentCultureIgnoreCase is specified, ICU will use 'secondary' collation rules
- which ignore the contraction collation weights (defined as 'tertiary' rules)
- */
- Assert.Equal(PlatformDetection.IsWindows ? 0 : -1, source.IndexOf(target));
- Assert.Equal(PlatformDetection.IsWindows ? 0 : -1, source.IndexOf(target, StringComparison.CurrentCulture));
-
- Assert.Equal(0, source.IndexOf(target, StringComparison.CurrentCultureIgnoreCase));
- Assert.Equal(-1, source.IndexOf(target, StringComparison.Ordinal));
- Assert.Equal(-1, source.IndexOf(target, StringComparison.OrdinalIgnoreCase));
-
- ReadOnlySpan<char> span = source.AsSpan();
-
- Assert.Equal(PlatformDetection.IsWindows ? 0 : -1, span.IndexOf(target.AsSpan(), StringComparison.CurrentCulture));
-
- Assert.Equal(0, span.IndexOf(target.AsSpan(), StringComparison.CurrentCultureIgnoreCase));
- Assert.Equal(-1, span.IndexOf(target.AsSpan(), StringComparison.Ordinal));
- Assert.Equal(-1, span.IndexOf(target.AsSpan(), StringComparison.OrdinalIgnoreCase));
-
- return RemoteExecutor.SuccessExitCode;
+ using (new ThreadCultureChange("hu-HU"))
+ {
+ string source = "dzsdzs";
+ string target = "ddzs";
+
+ /*
+ There are differences between Windows and ICU regarding contractions.
+ Windows has equal contraction collation weights, including case (target="Ddzs" same behavior as "ddzs").
+ ICU has different contraction collation weights, depending on locale collation rules.
+ If CurrentCultureIgnoreCase is specified, ICU will use 'secondary' collation rules
+ which ignore the contraction collation weights (defined as 'tertiary' rules)
+ */
+ Assert.Equal(PlatformDetection.IsWindows ? 0 : -1, source.IndexOf(target));
+ Assert.Equal(PlatformDetection.IsWindows ? 0 : -1, source.IndexOf(target, StringComparison.CurrentCulture));
+
+ Assert.Equal(0, source.IndexOf(target, StringComparison.CurrentCultureIgnoreCase));
+ Assert.Equal(-1, source.IndexOf(target, StringComparison.Ordinal));
+ Assert.Equal(-1, source.IndexOf(target, StringComparison.OrdinalIgnoreCase));
+
+ ReadOnlySpan<char> span = source.AsSpan();
+
+ Assert.Equal(PlatformDetection.IsWindows ? 0 : -1, span.IndexOf(target.AsSpan(), StringComparison.CurrentCulture));
+
+ Assert.Equal(0, span.IndexOf(target.AsSpan(), StringComparison.CurrentCultureIgnoreCase));
+ Assert.Equal(-1, span.IndexOf(target.AsSpan(), StringComparison.Ordinal));
+ Assert.Equal(-1, span.IndexOf(target.AsSpan(), StringComparison.OrdinalIgnoreCase));
+ }
}).Dispose();
}
[Fact]
public static void IndexOf_HungarianDoubleCompression_InvariantCulture()
{
- RemoteExecutor.Invoke(() =>
+ RemoteExecutorForUap.Invoke(() =>
{
- string source = "dzsdzs";
- string target = "ddzs";
-
- CultureInfo.CurrentCulture = CultureInfo.InvariantCulture;
- Assert.Equal(-1, source.IndexOf(target));
- Assert.Equal(-1, source.IndexOf(target, StringComparison.CurrentCulture));
- Assert.Equal(-1, source.IndexOf(target, StringComparison.CurrentCultureIgnoreCase));
+ using (new ThreadCultureChange(CultureInfo.InvariantCulture))
+ {
+ string source = "dzsdzs";
+ string target = "ddzs";
- ReadOnlySpan<char> span = source.AsSpan();
- Assert.Equal(-1, span.IndexOf(target.AsSpan(), StringComparison.CurrentCulture));
- Assert.Equal(-1, span.IndexOf(target.AsSpan(), StringComparison.CurrentCultureIgnoreCase));
+ Assert.Equal(-1, source.IndexOf(target));
+ Assert.Equal(-1, source.IndexOf(target, StringComparison.CurrentCulture));
+ Assert.Equal(-1, source.IndexOf(target, StringComparison.CurrentCultureIgnoreCase));
- return RemoteExecutor.SuccessExitCode;
+ ReadOnlySpan<char> span = source.AsSpan();
+ Assert.Equal(-1, span.IndexOf(target.AsSpan(), StringComparison.CurrentCulture));
+ Assert.Equal(-1, span.IndexOf(target.AsSpan(), StringComparison.CurrentCultureIgnoreCase));
+ }
}).Dispose();
}
[Fact]
public static void IndexOf_EquivalentDiacritics_EnglishUSCulture()
{
- RemoteExecutor.Invoke(() =>
+ RemoteExecutorForUap.Invoke(() =>
{
- string s = "Exhibit a\u0300\u00C0";
- string value = "\u00C0";
-
- CultureInfo.CurrentCulture = new CultureInfo("en-US");
- Assert.Equal(10, s.IndexOf(value));
- Assert.Equal(10, s.IndexOf(value, StringComparison.CurrentCulture));
- Assert.Equal(8, s.IndexOf(value, StringComparison.CurrentCultureIgnoreCase));
- Assert.Equal(10, s.IndexOf(value, StringComparison.Ordinal));
- Assert.Equal(10, s.IndexOf(value, StringComparison.OrdinalIgnoreCase));
-
- ReadOnlySpan<char> span = s.AsSpan();
- Assert.Equal(10, span.IndexOf(value.AsSpan(), StringComparison.CurrentCulture));
- Assert.Equal(8, span.IndexOf(value.AsSpan(), StringComparison.CurrentCultureIgnoreCase));
- Assert.Equal(10, span.IndexOf(value.AsSpan(), StringComparison.Ordinal));
- Assert.Equal(10, span.IndexOf(value.AsSpan(), StringComparison.OrdinalIgnoreCase));
-
- value = "a\u0300"; // this diacritic combines with preceding character
- Assert.Equal(8, s.IndexOf(value));
- Assert.Equal(8, s.IndexOf(value, StringComparison.CurrentCulture));
- Assert.Equal(8, s.IndexOf(value, StringComparison.CurrentCultureIgnoreCase));
- Assert.Equal(8, s.IndexOf(value, StringComparison.Ordinal));
- Assert.Equal(8, s.IndexOf(value, StringComparison.OrdinalIgnoreCase));
-
- Assert.Equal(8, span.IndexOf(value.AsSpan(), StringComparison.CurrentCulture));
- Assert.Equal(8, span.IndexOf(value.AsSpan(), StringComparison.CurrentCultureIgnoreCase));
- Assert.Equal(8, span.IndexOf(value.AsSpan(), StringComparison.Ordinal));
- Assert.Equal(8, span.IndexOf(value.AsSpan(), StringComparison.OrdinalIgnoreCase));
-
- return RemoteExecutor.SuccessExitCode;
+ using (new ThreadCultureChange("en-US"))
+ {
+ string s = "Exhibit a\u0300\u00C0";
+ string value = "\u00C0";
+
+ Assert.Equal(10, s.IndexOf(value));
+ Assert.Equal(10, s.IndexOf(value, StringComparison.CurrentCulture));
+ Assert.Equal(8, s.IndexOf(value, StringComparison.CurrentCultureIgnoreCase));
+ Assert.Equal(10, s.IndexOf(value, StringComparison.Ordinal));
+ Assert.Equal(10, s.IndexOf(value, StringComparison.OrdinalIgnoreCase));
+
+ ReadOnlySpan<char> span = s.AsSpan();
+ Assert.Equal(10, span.IndexOf(value.AsSpan(), StringComparison.CurrentCulture));
+ Assert.Equal(8, span.IndexOf(value.AsSpan(), StringComparison.CurrentCultureIgnoreCase));
+ Assert.Equal(10, span.IndexOf(value.AsSpan(), StringComparison.Ordinal));
+ Assert.Equal(10, span.IndexOf(value.AsSpan(), StringComparison.OrdinalIgnoreCase));
+
+ value = "a\u0300"; // this diacritic combines with preceding character
+ Assert.Equal(8, s.IndexOf(value));
+ Assert.Equal(8, s.IndexOf(value, StringComparison.CurrentCulture));
+ Assert.Equal(8, s.IndexOf(value, StringComparison.CurrentCultureIgnoreCase));
+ Assert.Equal(8, s.IndexOf(value, StringComparison.Ordinal));
+ Assert.Equal(8, s.IndexOf(value, StringComparison.OrdinalIgnoreCase));
+
+ Assert.Equal(8, span.IndexOf(value.AsSpan(), StringComparison.CurrentCulture));
+ Assert.Equal(8, span.IndexOf(value.AsSpan(), StringComparison.CurrentCultureIgnoreCase));
+ Assert.Equal(8, span.IndexOf(value.AsSpan(), StringComparison.Ordinal));
+ Assert.Equal(8, span.IndexOf(value.AsSpan(), StringComparison.OrdinalIgnoreCase));
+ }
}).Dispose();
}
[Fact]
public static void IndexOf_EquivalentDiacritics_InvariantCulture()
{
- RemoteExecutor.Invoke(() =>
+ RemoteExecutorForUap.Invoke(() =>
{
- string s = "Exhibit a\u0300\u00C0";
- string value = "\u00C0";
-
- CultureInfo.CurrentCulture = CultureInfo.InvariantCulture;
- Assert.Equal(10, s.IndexOf(value));
- Assert.Equal(10, s.IndexOf(value, StringComparison.CurrentCulture));
- Assert.Equal(8, s.IndexOf(value, StringComparison.CurrentCultureIgnoreCase));
+ using (new ThreadCultureChange(CultureInfo.InvariantCulture))
+ {
+ string s = "Exhibit a\u0300\u00C0";
+ string value = "\u00C0";
- ReadOnlySpan<char> span = s.AsSpan();
- Assert.Equal(10, span.IndexOf(value.AsSpan(), StringComparison.CurrentCulture));
- Assert.Equal(8, span.IndexOf(value.AsSpan(), StringComparison.CurrentCultureIgnoreCase));
+ CultureInfo.CurrentCulture = CultureInfo.InvariantCulture;
+ Assert.Equal(10, s.IndexOf(value));
+ Assert.Equal(10, s.IndexOf(value, StringComparison.CurrentCulture));
+ Assert.Equal(8, s.IndexOf(value, StringComparison.CurrentCultureIgnoreCase));
- value = "a\u0300"; // this diacritic combines with preceding character
- Assert.Equal(8, s.IndexOf(value));
- Assert.Equal(8, s.IndexOf(value, StringComparison.CurrentCulture));
- Assert.Equal(8, s.IndexOf(value, StringComparison.CurrentCultureIgnoreCase));
+ ReadOnlySpan<char> span = s.AsSpan();
+ Assert.Equal(10, span.IndexOf(value.AsSpan(), StringComparison.CurrentCulture));
+ Assert.Equal(8, span.IndexOf(value.AsSpan(), StringComparison.CurrentCultureIgnoreCase));
- Assert.Equal(8, span.IndexOf(value.AsSpan(), StringComparison.CurrentCulture));
- Assert.Equal(8, span.IndexOf(value.AsSpan(), StringComparison.CurrentCultureIgnoreCase));
+ value = "a\u0300"; // this diacritic combines with preceding character
+ Assert.Equal(8, s.IndexOf(value));
+ Assert.Equal(8, s.IndexOf(value, StringComparison.CurrentCulture));
+ Assert.Equal(8, s.IndexOf(value, StringComparison.CurrentCultureIgnoreCase));
- return RemoteExecutor.SuccessExitCode;
+ Assert.Equal(8, span.IndexOf(value.AsSpan(), StringComparison.CurrentCulture));
+ Assert.Equal(8, span.IndexOf(value.AsSpan(), StringComparison.CurrentCultureIgnoreCase));
+ }
}).Dispose();
}
[Fact]
public static void IndexOf_CyrillicE_EnglishUSCulture()
{
- RemoteExecutor.Invoke(() =>
+ RemoteExecutorForUap.Invoke(() =>
{
- string s = "Foo\u0400Bar";
- string value = "\u0400";
-
- CultureInfo.CurrentCulture = new CultureInfo("en-US");
- Assert.Equal(3, s.IndexOf(value));
- Assert.Equal(3, s.IndexOf(value, StringComparison.CurrentCulture));
- Assert.Equal(3, s.IndexOf(value, StringComparison.CurrentCultureIgnoreCase));
- Assert.Equal(3, s.IndexOf(value, StringComparison.Ordinal));
- Assert.Equal(3, s.IndexOf(value, StringComparison.OrdinalIgnoreCase));
-
- ReadOnlySpan<char> span = s.AsSpan();
- Assert.Equal(3, span.IndexOf(value.AsSpan(), StringComparison.CurrentCulture));
- Assert.Equal(3, span.IndexOf(value.AsSpan(), StringComparison.CurrentCultureIgnoreCase));
- Assert.Equal(3, span.IndexOf(value.AsSpan(), StringComparison.Ordinal));
- Assert.Equal(3, span.IndexOf(value.AsSpan(), StringComparison.OrdinalIgnoreCase));
-
- value = "bar";
- Assert.Equal(-1, s.IndexOf(value));
- Assert.Equal(-1, s.IndexOf(value, StringComparison.CurrentCulture));
- Assert.Equal(4, s.IndexOf(value, StringComparison.CurrentCultureIgnoreCase));
- Assert.Equal(-1, s.IndexOf(value, StringComparison.Ordinal));
- Assert.Equal(4, s.IndexOf(value, StringComparison.OrdinalIgnoreCase));
-
- Assert.Equal(-1, span.IndexOf(value.AsSpan(), StringComparison.CurrentCulture));
- Assert.Equal(4, span.IndexOf(value.AsSpan(), StringComparison.CurrentCultureIgnoreCase));
- Assert.Equal(-1, span.IndexOf(value.AsSpan(), StringComparison.Ordinal));
- Assert.Equal(4, span.IndexOf(value.AsSpan(), StringComparison.OrdinalIgnoreCase));
-
- return RemoteExecutor.SuccessExitCode;
+ using (new ThreadCultureChange("en-US"))
+ {
+ string s = "Foo\u0400Bar";
+ string value = "\u0400";
+
+ Assert.Equal(3, s.IndexOf(value));
+ Assert.Equal(3, s.IndexOf(value, StringComparison.CurrentCulture));
+ Assert.Equal(3, s.IndexOf(value, StringComparison.CurrentCultureIgnoreCase));
+ Assert.Equal(3, s.IndexOf(value, StringComparison.Ordinal));
+ Assert.Equal(3, s.IndexOf(value, StringComparison.OrdinalIgnoreCase));
+
+ ReadOnlySpan<char> span = s.AsSpan();
+ Assert.Equal(3, span.IndexOf(value.AsSpan(), StringComparison.CurrentCulture));
+ Assert.Equal(3, span.IndexOf(value.AsSpan(), StringComparison.CurrentCultureIgnoreCase));
+ Assert.Equal(3, span.IndexOf(value.AsSpan(), StringComparison.Ordinal));
+ Assert.Equal(3, span.IndexOf(value.AsSpan(), StringComparison.OrdinalIgnoreCase));
+
+ value = "bar";
+ Assert.Equal(-1, s.IndexOf(value));
+ Assert.Equal(-1, s.IndexOf(value, StringComparison.CurrentCulture));
+ Assert.Equal(4, s.IndexOf(value, StringComparison.CurrentCultureIgnoreCase));
+ Assert.Equal(-1, s.IndexOf(value, StringComparison.Ordinal));
+ Assert.Equal(4, s.IndexOf(value, StringComparison.OrdinalIgnoreCase));
+
+ Assert.Equal(-1, span.IndexOf(value.AsSpan(), StringComparison.CurrentCulture));
+ Assert.Equal(4, span.IndexOf(value.AsSpan(), StringComparison.CurrentCultureIgnoreCase));
+ Assert.Equal(-1, span.IndexOf(value.AsSpan(), StringComparison.Ordinal));
+ Assert.Equal(4, span.IndexOf(value.AsSpan(), StringComparison.OrdinalIgnoreCase));
+ }
}).Dispose();
}
[Fact]
public static void IndexOf_CyrillicE_InvariantCulture()
{
- RemoteExecutor.Invoke(() =>
+ RemoteExecutorForUap.Invoke(() =>
{
- string s = "Foo\u0400Bar";
- string value = "\u0400";
-
- CultureInfo.CurrentCulture = CultureInfo.InvariantCulture;
- Assert.Equal(3, s.IndexOf(value));
- Assert.Equal(3, s.IndexOf(value, StringComparison.CurrentCulture));
- Assert.Equal(3, s.IndexOf(value, StringComparison.CurrentCultureIgnoreCase));
+ using (new ThreadCultureChange(CultureInfo.InvariantCulture))
+ {
+ string s = "Foo\u0400Bar";
+ string value = "\u0400";
- ReadOnlySpan<char> span = s.AsSpan();
- Assert.Equal(3, span.IndexOf(value.AsSpan(), StringComparison.CurrentCulture));
- Assert.Equal(3, span.IndexOf(value.AsSpan(), StringComparison.CurrentCultureIgnoreCase));
+ Assert.Equal(3, s.IndexOf(value));
+ Assert.Equal(3, s.IndexOf(value, StringComparison.CurrentCulture));
+ Assert.Equal(3, s.IndexOf(value, StringComparison.CurrentCultureIgnoreCase));
- value = "bar";
- Assert.Equal(-1, s.IndexOf(value));
- Assert.Equal(-1, s.IndexOf(value, StringComparison.CurrentCulture));
- Assert.Equal(4, s.IndexOf(value, StringComparison.CurrentCultureIgnoreCase));
+ ReadOnlySpan<char> span = s.AsSpan();
+ Assert.Equal(3, span.IndexOf(value.AsSpan(), StringComparison.CurrentCulture));
+ Assert.Equal(3, span.IndexOf(value.AsSpan(), StringComparison.CurrentCultureIgnoreCase));
- Assert.Equal(-1, span.IndexOf(value.AsSpan(), StringComparison.CurrentCulture));
- Assert.Equal(4, span.IndexOf(value.AsSpan(), StringComparison.CurrentCultureIgnoreCase));
+ value = "bar";
+ Assert.Equal(-1, s.IndexOf(value));
+ Assert.Equal(-1, s.IndexOf(value, StringComparison.CurrentCulture));
+ Assert.Equal(4, s.IndexOf(value, StringComparison.CurrentCultureIgnoreCase));
- return RemoteExecutor.SuccessExitCode;
+ Assert.Equal(-1, span.IndexOf(value.AsSpan(), StringComparison.CurrentCulture));
+ Assert.Equal(4, span.IndexOf(value.AsSpan(), StringComparison.CurrentCultureIgnoreCase));
+ }
}).Dispose();
}
[Fact]
public static void LastIndexOf_TurkishI_TurkishCulture()
{
- RemoteExecutor.Invoke(() =>
+ RemoteExecutorForUap.Invoke(() =>
{
- CultureInfo.CurrentCulture = new CultureInfo("tr-TR");
-
- string s = "Turkish I \u0131s TROUBL\u0130NG!";
- ReadOnlySpan<char> span = s.AsSpan();
- string value = "\u0130";
-
- Assert.Equal(19, s.LastIndexOf(value));
- Assert.Equal(19, s.LastIndexOf(value, StringComparison.CurrentCulture));
- Assert.Equal(19, s.LastIndexOf(value, StringComparison.CurrentCultureIgnoreCase));
- Assert.Equal(19, s.LastIndexOf(value, StringComparison.Ordinal));
- Assert.Equal(19, s.LastIndexOf(value, StringComparison.OrdinalIgnoreCase));
- Assert.Equal(19, span.LastIndexOf(value.AsSpan()));
- Assert.Equal(19, span.LastIndexOf(value.AsSpan(), StringComparison.CurrentCulture));
- Assert.Equal(19, span.LastIndexOf(value.AsSpan(), StringComparison.CurrentCultureIgnoreCase));
- Assert.Equal(19, span.LastIndexOf(value.AsSpan(), StringComparison.Ordinal));
- Assert.Equal(19, span.LastIndexOf(value.AsSpan(), StringComparison.OrdinalIgnoreCase));
-
- value = "\u0131";
- Assert.Equal(10, s.LastIndexOf(value, StringComparison.CurrentCulture));
- Assert.Equal(10, s.LastIndexOf(value, StringComparison.CurrentCultureIgnoreCase));
- Assert.Equal(10, s.LastIndexOf(value, StringComparison.Ordinal));
- Assert.Equal(10, s.LastIndexOf(value, StringComparison.OrdinalIgnoreCase));
- Assert.Equal(10, span.LastIndexOf(value.AsSpan(), StringComparison.CurrentCulture));
- Assert.Equal(10, span.LastIndexOf(value.AsSpan(), StringComparison.CurrentCultureIgnoreCase));
- Assert.Equal(10, span.LastIndexOf(value.AsSpan(), StringComparison.Ordinal));
- Assert.Equal(10, span.LastIndexOf(value.AsSpan(), StringComparison.OrdinalIgnoreCase));
-
- return RemoteExecutor.SuccessExitCode;
+ using (new ThreadCultureChange("tr-TR"))
+ {
+ string s = "Turkish I \u0131s TROUBL\u0130NG!";
+ ReadOnlySpan<char> span = s.AsSpan();
+ string value = "\u0130";
+
+ Assert.Equal(19, s.LastIndexOf(value));
+ Assert.Equal(19, s.LastIndexOf(value, StringComparison.CurrentCulture));
+ Assert.Equal(19, s.LastIndexOf(value, StringComparison.CurrentCultureIgnoreCase));
+ Assert.Equal(19, s.LastIndexOf(value, StringComparison.Ordinal));
+ Assert.Equal(19, s.LastIndexOf(value, StringComparison.OrdinalIgnoreCase));
+ Assert.Equal(19, span.LastIndexOf(value.AsSpan()));
+ Assert.Equal(19, span.LastIndexOf(value.AsSpan(), StringComparison.CurrentCulture));
+ Assert.Equal(19, span.LastIndexOf(value.AsSpan(), StringComparison.CurrentCultureIgnoreCase));
+ Assert.Equal(19, span.LastIndexOf(value.AsSpan(), StringComparison.Ordinal));
+ Assert.Equal(19, span.LastIndexOf(value.AsSpan(), StringComparison.OrdinalIgnoreCase));
+
+ value = "\u0131";
+ Assert.Equal(10, s.LastIndexOf(value, StringComparison.CurrentCulture));
+ Assert.Equal(10, s.LastIndexOf(value, StringComparison.CurrentCultureIgnoreCase));
+ Assert.Equal(10, s.LastIndexOf(value, StringComparison.Ordinal));
+ Assert.Equal(10, s.LastIndexOf(value, StringComparison.OrdinalIgnoreCase));
+ Assert.Equal(10, span.LastIndexOf(value.AsSpan(), StringComparison.CurrentCulture));
+ Assert.Equal(10, span.LastIndexOf(value.AsSpan(), StringComparison.CurrentCultureIgnoreCase));
+ Assert.Equal(10, span.LastIndexOf(value.AsSpan(), StringComparison.Ordinal));
+ Assert.Equal(10, span.LastIndexOf(value.AsSpan(), StringComparison.OrdinalIgnoreCase));
+ }
}).Dispose();
}
[Fact]
public static void LastIndexOf_TurkishI_InvariantCulture()
{
- RemoteExecutor.Invoke(() =>
+ RemoteExecutorForUap.Invoke(() =>
{
- CultureInfo.CurrentCulture = CultureInfo.InvariantCulture;
-
- string s = "Turkish I \u0131s TROUBL\u0130NG!";
- ReadOnlySpan<char> span = s.AsSpan();
- string value = "\u0130";
-
- Assert.Equal(19, s.LastIndexOf(value));
- Assert.Equal(19, s.LastIndexOf(value, StringComparison.CurrentCulture));
- Assert.Equal(19, s.LastIndexOf(value, StringComparison.CurrentCultureIgnoreCase));
- Assert.Equal(19, span.LastIndexOf(value.AsSpan()));
- Assert.Equal(19, span.LastIndexOf(value.AsSpan(), StringComparison.CurrentCulture));
- Assert.Equal(19, span.LastIndexOf(value.AsSpan(), StringComparison.CurrentCultureIgnoreCase));
-
- value = "\u0131";
- Assert.Equal(10, s.LastIndexOf(value, StringComparison.CurrentCulture));
- Assert.Equal(10, s.LastIndexOf(value, StringComparison.CurrentCultureIgnoreCase));
- Assert.Equal(10, span.LastIndexOf(value.AsSpan(), StringComparison.CurrentCulture));
- Assert.Equal(10, span.LastIndexOf(value.AsSpan(), StringComparison.CurrentCultureIgnoreCase));
-
- return RemoteExecutor.SuccessExitCode;
+ using (new ThreadCultureChange(CultureInfo.InvariantCulture))
+ {
+ string s = "Turkish I \u0131s TROUBL\u0130NG!";
+ ReadOnlySpan<char> span = s.AsSpan();
+ string value = "\u0130";
+
+ Assert.Equal(19, s.LastIndexOf(value));
+ Assert.Equal(19, s.LastIndexOf(value, StringComparison.CurrentCulture));
+ Assert.Equal(19, s.LastIndexOf(value, StringComparison.CurrentCultureIgnoreCase));
+ Assert.Equal(19, span.LastIndexOf(value.AsSpan()));
+ Assert.Equal(19, span.LastIndexOf(value.AsSpan(), StringComparison.CurrentCulture));
+ Assert.Equal(19, span.LastIndexOf(value.AsSpan(), StringComparison.CurrentCultureIgnoreCase));
+
+ value = "\u0131";
+ Assert.Equal(10, s.LastIndexOf(value, StringComparison.CurrentCulture));
+ Assert.Equal(10, s.LastIndexOf(value, StringComparison.CurrentCultureIgnoreCase));
+ Assert.Equal(10, span.LastIndexOf(value.AsSpan(), StringComparison.CurrentCulture));
+ Assert.Equal(10, span.LastIndexOf(value.AsSpan(), StringComparison.CurrentCultureIgnoreCase));
+ }
}).Dispose();
}
[Fact]
public static void LastIndexOf_TurkishI_EnglishUSCulture()
{
- RemoteExecutor.Invoke(() =>
+ RemoteExecutorForUap.Invoke(() =>
{
- CultureInfo.CurrentCulture = new CultureInfo("en-US");
-
- string s = "Turkish I \u0131s TROUBL\u0130NG!";
- ReadOnlySpan<char> span = s.AsSpan();
- string value = "\u0130";
-
- Assert.Equal(19, s.LastIndexOf(value));
- Assert.Equal(19, s.LastIndexOf(value, StringComparison.CurrentCulture));
- Assert.Equal(19, s.LastIndexOf(value, StringComparison.CurrentCultureIgnoreCase));
- Assert.Equal(19, span.LastIndexOf(value.AsSpan()));
- Assert.Equal(19, span.LastIndexOf(value.AsSpan(), StringComparison.CurrentCulture));
- Assert.Equal(19, span.LastIndexOf(value.AsSpan(), StringComparison.CurrentCultureIgnoreCase));
-
- value = "\u0131";
- Assert.Equal(10, s.LastIndexOf(value, StringComparison.CurrentCulture));
- Assert.Equal(10, s.LastIndexOf(value, StringComparison.CurrentCultureIgnoreCase));
- Assert.Equal(10, span.LastIndexOf(value.AsSpan(), StringComparison.CurrentCulture));
- Assert.Equal(10, span.LastIndexOf(value.AsSpan(), StringComparison.CurrentCultureIgnoreCase));
-
- return RemoteExecutor.SuccessExitCode;
+ using (new ThreadCultureChange("en-US"))
+ {
+ string s = "Turkish I \u0131s TROUBL\u0130NG!";
+ ReadOnlySpan<char> span = s.AsSpan();
+ string value = "\u0130";
+
+ Assert.Equal(19, s.LastIndexOf(value));
+ Assert.Equal(19, s.LastIndexOf(value, StringComparison.CurrentCulture));
+ Assert.Equal(19, s.LastIndexOf(value, StringComparison.CurrentCultureIgnoreCase));
+ Assert.Equal(19, span.LastIndexOf(value.AsSpan()));
+ Assert.Equal(19, span.LastIndexOf(value.AsSpan(), StringComparison.CurrentCulture));
+ Assert.Equal(19, span.LastIndexOf(value.AsSpan(), StringComparison.CurrentCultureIgnoreCase));
+
+ value = "\u0131";
+ Assert.Equal(10, s.LastIndexOf(value, StringComparison.CurrentCulture));
+ Assert.Equal(10, s.LastIndexOf(value, StringComparison.CurrentCultureIgnoreCase));
+ Assert.Equal(10, span.LastIndexOf(value.AsSpan(), StringComparison.CurrentCulture));
+ Assert.Equal(10, span.LastIndexOf(value.AsSpan(), StringComparison.CurrentCultureIgnoreCase));
+ }
}).Dispose();
}
[Fact]
public static void Test_ToLower_Culture()
{
- RemoteExecutor.Invoke(() =>
+ RemoteExecutorForUap.Invoke(() =>
{
- foreach (var testdata in ToLower_Culture_TestData())
+ foreach (object[] testdata in ToLower_Culture_TestData())
{
ToLower_Culture((string)testdata[0], (string)testdata[1], (CultureInfo)testdata[2]);
}
- return RemoteExecutor.SuccessExitCode;
}).Dispose();
}
private static void ToLower_Culture(string input, string expected, CultureInfo culture)
{
- CultureInfo.CurrentCulture = culture;
- Assert.True(input.ToLower().Equals(expected, StringComparison.Ordinal), $"Input: {input}, Expected: {expected}, Actual: {input.ToLower()}");
+ using (new ThreadCultureChange(culture))
+ {
+ Assert.True(input.ToLower().Equals(expected, StringComparison.Ordinal), $"Input: {input}, Expected: {expected}, Actual: {input.ToLower()}");
- Span<char> destination = new char[input.Length];
- Assert.Equal(input.Length, input.AsSpan().ToLower(destination, culture));
- Assert.Equal(expected, destination.ToString());
+ Span<char> destination = new char[input.Length];
+ Assert.Equal(input.Length, input.AsSpan().ToLower(destination, culture));
+ Assert.Equal(expected, destination.ToString());
+ }
}
[Theory]
[MemberData(nameof(ToUpper_TurkishI_TurkishCulture_MemberData))]
public static void ToUpper_TurkishI_TurkishCulture(string s, string expected)
{
- RemoteExecutor.Invoke((str, expectedString) =>
+ RemoteExecutorForUap.Invoke((str, expectedString) =>
{
- CultureInfo.CurrentCulture = new CultureInfo("tr-TR");
-
- Assert.True(str.ToUpper().Equals(expectedString, StringComparison.Ordinal), "Actual: " + str.ToUpper());
-
- Span<char> destination = new char[str.Length];
- Assert.Equal(str.Length, str.AsSpan().ToUpper(destination, CultureInfo.CurrentCulture));
- Assert.Equal(expectedString, destination.ToString());
+ using (new ThreadCultureChange("tr-TR"))
+ {
+ Assert.True(str.ToUpper().Equals(expectedString, StringComparison.Ordinal), "Actual: " + str.ToUpper());
- return RemoteExecutor.SuccessExitCode;
+ Span<char> destination = new char[str.Length];
+ Assert.Equal(str.Length, str.AsSpan().ToUpper(destination, CultureInfo.CurrentCulture));
+ Assert.Equal(expectedString, destination.ToString());
+ }
}, s.ToString(), expected.ToString()).Dispose();
}
[MemberData(nameof(ToUpper_TurkishI_EnglishUSCulture_MemberData))]
public static void ToUpper_TurkishI_EnglishUSCulture(string s, string expected)
{
- RemoteExecutor.Invoke((str, expectedString) =>
+ RemoteExecutorForUap.Invoke((str, expectedString) =>
{
- CultureInfo.CurrentCulture = new CultureInfo("en-US");
-
- Assert.True(str.ToUpper().Equals(expectedString, StringComparison.Ordinal), "Actual: " + str.ToUpper());
-
- Span<char> destination = new char[str.Length];
- Assert.Equal(str.Length, str.AsSpan().ToUpper(destination, CultureInfo.CurrentCulture));
- Assert.Equal(expectedString, destination.ToString());
+ using (new ThreadCultureChange("en-US"))
+ {
+ Assert.True(str.ToUpper().Equals(expectedString, StringComparison.Ordinal), "Actual: " + str.ToUpper());
- return RemoteExecutor.SuccessExitCode;
+ Span<char> destination = new char[str.Length];
+ Assert.Equal(str.Length, str.AsSpan().ToUpper(destination, CultureInfo.CurrentCulture));
+ Assert.Equal(expectedString, destination.ToString());
+ }
}, s.ToString(), expected.ToString()).Dispose();
}
[MemberData(nameof(ToUpper_TurkishI_InvariantCulture_MemberData))]
public static void ToUpper_TurkishI_InvariantCulture(string s, string expected)
{
- RemoteExecutor.Invoke((str, expectedString) =>
+ RemoteExecutorForUap.Invoke((str, expectedString) =>
{
- CultureInfo.CurrentCulture = CultureInfo.InvariantCulture;
-
- Assert.True(str.ToUpper().Equals(expectedString, StringComparison.Ordinal));
-
- Span<char> destination = new char[str.Length];
- Assert.Equal(str.Length, str.AsSpan().ToUpper(destination, CultureInfo.CurrentCulture));
- Assert.Equal(expectedString, destination.ToString());
+ using (new ThreadCultureChange(CultureInfo.InvariantCulture))
+ {
+ Assert.True(str.ToUpper().Equals(expectedString, StringComparison.Ordinal));
- return RemoteExecutor.SuccessExitCode;
+ Span<char> destination = new char[str.Length];
+ Assert.Equal(str.Length, str.AsSpan().ToUpper(destination, CultureInfo.CurrentCulture));
+ Assert.Equal(expectedString, destination.ToString());
+ }
}, s.ToString(), expected.ToString()).Dispose();
}
public static void CompareTest(string aS1, string aS2, string aCultureName, bool aIgnoreCase, int aExpected)
{
const string nullPlaceholder = "<null>";
- RemoteExecutor.Invoke((string s1, string s2, string cultureName, string bIgnoreCase, string iExpected) => {
+ RemoteExecutorForUap.Invoke((string s1, string s2, string cultureName, string bIgnoreCase, string iExpected) => {
if (s1 == nullPlaceholder)
s1 = null;
if (ci != null)
{
- CultureInfo.CurrentCulture = ci;
- Assert.Equal(expected, String.Compare(s1, 0, s2, 0, s1 == null ? 0 : s1.Length, ignoreCase));
+ using (new ThreadCultureChange(ci))
+ {
+ Assert.Equal(expected, String.Compare(s1, 0, s2, 0, s1 == null ? 0 : s1.Length, ignoreCase));
+ }
}
return RemoteExecutor.SuccessExitCode;
[Fact]
public static void StartsWithMatchNonOrdinal_StringComparison()
{
- RemoteExecutor.Invoke(() =>
+ RemoteExecutorForUap.Invoke(() =>
{
string s1 = "abcd";
string s2 = "aBc";
Assert.False(span.StartsWith(value, StringComparison.Ordinal));
Assert.True(span.StartsWith(value, StringComparison.OrdinalIgnoreCase));
- CultureInfo backupCulture = CultureInfo.CurrentCulture;
-
- Thread.CurrentThread.CurrentCulture = new CultureInfo("el-GR");
-
- s1 = "\u03b1\u03b2\u03b3\u03b4"; // \u03B1\u03B2\u03B3\u03B4
- s2 = "\u03b1\u03b2\u03b3"; // \u03B1\u03B2\u03B3
-
- Assert.True(s1.StartsWith(s2, StringComparison.CurrentCulture));
- Assert.True(s1.StartsWith(s2, StringComparison.CurrentCultureIgnoreCase));
+ using (new ThreadCultureChange("el-GR"))
+ {
+ s1 = "\u03b1\u03b2\u03b3\u03b4"; // \u03B1\u03B2\u03B3\u03B4
+ s2 = "\u03b1\u03b2\u03b3"; // \u03B1\u03B2\u03B3
- span = s1.AsSpan();
- value = s2.AsSpan();
+ Assert.True(s1.StartsWith(s2, StringComparison.CurrentCulture));
+ Assert.True(s1.StartsWith(s2, StringComparison.CurrentCultureIgnoreCase));
- Assert.True(span.StartsWith(value, StringComparison.CurrentCulture));
- Assert.True(span.StartsWith(value, StringComparison.CurrentCultureIgnoreCase));
+ span = s1.AsSpan();
+ value = s2.AsSpan();
- s2 = "\u03b1\u0392\u03b3"; // \u03B1\u0392\u03B3
- Assert.False(s1.StartsWith(s2, StringComparison.CurrentCulture));
- Assert.True(s1.StartsWith(s2, StringComparison.CurrentCultureIgnoreCase));
+ Assert.True(span.StartsWith(value, StringComparison.CurrentCulture));
+ Assert.True(span.StartsWith(value, StringComparison.CurrentCultureIgnoreCase));
- value = s2.AsSpan();
- Assert.False(span.StartsWith(value, StringComparison.CurrentCulture));
- Assert.True(span.StartsWith(value, StringComparison.CurrentCultureIgnoreCase));
+ s2 = "\u03b1\u0392\u03b3"; // \u03B1\u0392\u03B3
+ Assert.False(s1.StartsWith(s2, StringComparison.CurrentCulture));
+ Assert.True(s1.StartsWith(s2, StringComparison.CurrentCultureIgnoreCase));
- Thread.CurrentThread.CurrentCulture = backupCulture;
+ value = s2.AsSpan();
+ Assert.False(span.StartsWith(value, StringComparison.CurrentCulture));
+ Assert.True(span.StartsWith(value, StringComparison.CurrentCultureIgnoreCase));
+ }
s1 = "\u0069\u00df\u0049\u03b4"; // i\u00DFI\u03B4
s2 = "\u0069\u0073\u0073\u0049"; // issI
[Fact]
public static void StartsWithNoMatchNonOrdinal_StringComparison()
{
- RemoteExecutor.Invoke(() =>
+ RemoteExecutorForUap.Invoke(() =>
{
string s1 = "abcd";
string s2 = "aDc";
Assert.False(span.StartsWith(value, StringComparison.Ordinal));
Assert.False(span.StartsWith(value, StringComparison.OrdinalIgnoreCase));
- CultureInfo backupCulture = CultureInfo.CurrentCulture;
-
- Thread.CurrentThread.CurrentCulture = new CultureInfo("el-GR");
-
- s1 = "\u03b1\u03b2\u03b3\u03b4"; // \u03B1\u03B2\u03B3\u03B4
- s2 = "\u03b1\u03b4\u03b3"; // \u03B1\u03B4\u03B3
-
- Assert.False(s1.StartsWith(s2, StringComparison.CurrentCulture));
- Assert.False(s1.StartsWith(s2, StringComparison.CurrentCultureIgnoreCase));
+ using (new ThreadCultureChange("el-GR"))
+ {
+ s1 = "\u03b1\u03b2\u03b3\u03b4"; // \u03B1\u03B2\u03B3\u03B4
+ s2 = "\u03b1\u03b4\u03b3"; // \u03B1\u03B4\u03B3
- span = s1.AsSpan();
- value = s2.AsSpan();
+ Assert.False(s1.StartsWith(s2, StringComparison.CurrentCulture));
+ Assert.False(s1.StartsWith(s2, StringComparison.CurrentCultureIgnoreCase));
- Assert.False(span.StartsWith(value, StringComparison.CurrentCulture));
- Assert.False(span.StartsWith(value, StringComparison.CurrentCultureIgnoreCase));
+ span = s1.AsSpan();
+ value = s2.AsSpan();
- s2 = "\u03b1\u0394\u03b3"; // \u03B1\u0394\u03B3
- Assert.False(s1.StartsWith(s2, StringComparison.CurrentCulture));
- Assert.False(s1.StartsWith(s2, StringComparison.CurrentCultureIgnoreCase));
+ Assert.False(span.StartsWith(value, StringComparison.CurrentCulture));
+ Assert.False(span.StartsWith(value, StringComparison.CurrentCultureIgnoreCase));
- value = s2.AsSpan();
- Assert.False(span.StartsWith(value, StringComparison.CurrentCulture));
- Assert.False(span.StartsWith(value, StringComparison.CurrentCultureIgnoreCase));
+ s2 = "\u03b1\u0394\u03b3"; // \u03B1\u0394\u03B3
+ Assert.False(s1.StartsWith(s2, StringComparison.CurrentCulture));
+ Assert.False(s1.StartsWith(s2, StringComparison.CurrentCultureIgnoreCase));
- Thread.CurrentThread.CurrentCulture = backupCulture;
+ value = s2.AsSpan();
+ Assert.False(span.StartsWith(value, StringComparison.CurrentCulture));
+ Assert.False(span.StartsWith(value, StringComparison.CurrentCultureIgnoreCase));
+ }
s1 = "\u0069\u00df\u0049\u03b4"; // i\u00DFI\u03B4
s2 = "\u0069\u03b4\u03b4\u0049"; // i\u03B4\u03B4I
// See the LICENSE file in the project root for more information.
using System;
+using System.Tests;
using System.Collections.Generic;
using System.Globalization;
using System.Runtime.InteropServices;
[InlineData(256)]
public void Chr_CharCodeOutOfRange_ThrowsNotSupportedException(int charCode)
{
- RemoteExecutor.Invoke(charCodeInner =>
+ RemoteExecutorForUap.Invoke(charCodeInner =>
{
Encoding.RegisterProvider(CodePagesEncodingProvider.Instance);
- CultureInfo.CurrentCulture = new CultureInfo("en-US"); // Strings.Chr doesn't fail on these inputs for all code pages, e.g. 949
- AssertExtensions.Throws<ArgumentException>(null, () => Strings.Chr(int.Parse(charCodeInner, CultureInfo.InvariantCulture)));
+ using (new ThreadCultureChange("en-US")) // Strings.Chr doesn't fail on these inputs for all code pages, e.g. 949
+ {
+ AssertExtensions.Throws<ArgumentException>(null, () => Strings.Chr(int.Parse(charCodeInner, CultureInfo.InvariantCulture)));
+ }
}, charCode.ToString(CultureInfo.InvariantCulture)).Dispose();
}
[InlineData(255, 255)]
public void Asc_Chr_Invariant(int charCode, int expected)
{
- RemoteExecutor.Invoke((charCodeString, expectedString) =>
+ RemoteExecutorForUap.Invoke((charCodeString, expectedString) =>
{
int charCode = int.Parse(charCodeString);
int expected = int.Parse(expectedString);
Encoding.RegisterProvider(CodePagesEncodingProvider.Instance);
- CultureInfo.CurrentCulture = CultureInfo.InvariantCulture;
- Assert.Equal(1252, CultureInfo.CurrentCulture.TextInfo.ANSICodePage);
-
- Assert.Equal(expected, Strings.Asc(Strings.Chr(charCode)));
+ using (new ThreadCultureChange(CultureInfo.InvariantCulture))
+ {
+ Assert.Equal(1252, CultureInfo.CurrentCulture.TextInfo.ANSICodePage);
+ Assert.Equal(expected, Strings.Asc(Strings.Chr(charCode)));
+ }
}, charCode.ToString(), expected.ToString()).Dispose();
}
[InlineData(0xFFFF, 0xFF)]
public void Asc_Chr_DoubleByte(int charCode, int expected)
{
- RemoteExecutor.Invoke((charCodeString, expectedString) =>
+ RemoteExecutorForUap.Invoke((charCodeString, expectedString) =>
{
int charCode = int.Parse(charCodeString);
int expected = int.Parse(expectedString);
Encoding.RegisterProvider(CodePagesEncodingProvider.Instance);
- CultureInfo.CurrentCulture = new CultureInfo("ko-KR");
- Assert.Equal(949, CultureInfo.CurrentCulture.TextInfo.ANSICodePage);
-
- Assert.Equal(expected, (ushort)Strings.Asc(Strings.Chr(charCode)));
+ using (new ThreadCultureChange("ko-KR"))
+ {
+ Assert.Equal(949, CultureInfo.CurrentCulture.TextInfo.ANSICodePage);
+ Assert.Equal(expected, (ushort)Strings.Asc(Strings.Chr(charCode)));
+ }
}, charCode.ToString(), expected.ToString()).Dispose();
}
RemoteExecutor.Invoke(action).Dispose();
}
- protected static void RemoteInvokeWithTrimming(Func<string, int> method, bool trim = false, int timeout = RemoteExecutor.FailWaitTimeoutMilliseconds)
+ protected static void RemoteInvokeWithTrimming(Action<string> method, bool trim = false, int timeout = RemoteExecutor.FailWaitTimeoutMilliseconds)
{
var options = new RemoteInvokeOptions
{
// Should only have found a new buffer if we're trimming
Assert.Equal(parsedTrim, foundNewBuffer);
- return RemoteExecutor.SuccessExitCode;
}, trim, 3 * 60 * 1000); // This test has to wait for the buffers to go stale (give it three minutes)
}
// Disabled, should not have trimmed buffer
Assert.Same(buffer, pool.Rent(BufferSize));
}
-
- return RemoteExecutor.SuccessExitCode;
}, trim);
}
// Polling events should only fire when trimming is enabled
Assert.Equal(parsedTrim, pollEventFired);
- return RemoteExecutor.SuccessExitCode;
}, trim);
}
}
using System.Collections.Generic;
using System.Globalization;
using System.Reflection;
+using System.Tests;
using Microsoft.CSharp;
using Microsoft.DotNet.RemoteExecutor;
using Xunit;
[SkipOnTargetFramework(TargetFrameworkMonikers.NetFramework)]
public void MetadataAttributes()
{
- RemoteExecutor.Invoke(() =>
+ RemoteExecutorForUap.Invoke(() =>
{
- CultureInfo.CurrentUICulture = CultureInfo.InvariantCulture;
-
- var cu = new CodeCompileUnit();
-
- var ns = new CodeNamespace();
- ns.Name = "MyNamespace";
- ns.Imports.Add(new CodeNamespaceImport("System"));
- ns.Imports.Add(new CodeNamespaceImport("System.Drawing"));
- ns.Imports.Add(new CodeNamespaceImport("System.Windows.Forms"));
- ns.Imports.Add(new CodeNamespaceImport("System.ComponentModel"));
- cu.Namespaces.Add(ns);
-
- var attrs = cu.AssemblyCustomAttributes;
- attrs.Add(new CodeAttributeDeclaration("System.Reflection.AssemblyTitle", new CodeAttributeArgument(new CodePrimitiveExpression("MyAssembly"))));
- attrs.Add(new CodeAttributeDeclaration("System.Reflection.AssemblyVersion", new CodeAttributeArgument(new CodePrimitiveExpression("1.0.6.2"))));
- attrs.Add(new CodeAttributeDeclaration("System.CLSCompliantAttribute", new CodeAttributeArgument(new CodePrimitiveExpression(false))));
-
- var class1 = new CodeTypeDeclaration() { Name = "MyClass" };
- class1.CustomAttributes.Add(new CodeAttributeDeclaration("System.Serializable"));
- class1.CustomAttributes.Add(new CodeAttributeDeclaration("System.Obsolete", new CodeAttributeArgument(new CodePrimitiveExpression("Don't use this Class"))));
- ns.Types.Add(class1);
-
- var nestedClass = new CodeTypeDeclaration("NestedClass") { IsClass = true, TypeAttributes = TypeAttributes.NestedPublic };
- nestedClass.CustomAttributes.Add(new CodeAttributeDeclaration("System.Serializable"));
- class1.Members.Add(nestedClass);
-
- var method1 = new CodeMemberMethod() { Name = "MyMethod" };
- method1.CustomAttributes.Add(new CodeAttributeDeclaration("System.Obsolete", new CodeAttributeArgument(new CodePrimitiveExpression("Don't use this Method"))));
- method1.CustomAttributes.Add(new CodeAttributeDeclaration("System.ComponentModel.Editor", new CodeAttributeArgument(new CodePrimitiveExpression("This")), new CodeAttributeArgument(new CodePrimitiveExpression("That"))));
- var param1 = new CodeParameterDeclarationExpression(typeof(string), "blah");
- param1.CustomAttributes.Add(new CodeAttributeDeclaration("System.Xml.Serialization.XmlElementAttribute",
- new CodeAttributeArgument("Form", new CodeFieldReferenceExpression(new CodeTypeReferenceExpression("System.Xml.Schema.XmlSchemaForm"), "Unqualified")),
- new CodeAttributeArgument("IsNullable", new CodePrimitiveExpression(false))));
- method1.Parameters.Add(param1);
- var param2 = new CodeParameterDeclarationExpression(typeof(int[]), "arrayit");
- param2.CustomAttributes.Add(
- new CodeAttributeDeclaration("System.Xml.Serialization.XmlElementAttribute",
- new CodeAttributeArgument("Form", new CodeFieldReferenceExpression(new CodeTypeReferenceExpression("System.Xml.Schema.XmlSchemaForm"), "Unqualified")),
- new CodeAttributeArgument("IsNullable", new CodePrimitiveExpression(false))));
- method1.Parameters.Add(param2);
- class1.Members.Add(method1);
-
- var function1 = new CodeMemberMethod();
- function1.Name = "MyFunction";
- function1.ReturnType = new CodeTypeReference(typeof(string));
- function1.CustomAttributes.Add(new CodeAttributeDeclaration("System.Obsolete", new CodeAttributeArgument(new CodePrimitiveExpression("Don't use this Function"))));
- function1.ReturnTypeCustomAttributes.Add(new CodeAttributeDeclaration("System.Xml.Serialization.XmlIgnoreAttribute"));
- function1.ReturnTypeCustomAttributes.Add(new CodeAttributeDeclaration("System.Xml.Serialization.XmlRootAttribute", new
- CodeAttributeArgument("Namespace", new CodePrimitiveExpression("Namespace Value")), new
- CodeAttributeArgument("ElementName", new CodePrimitiveExpression("Root, hehehe"))));
- function1.Statements.Add(new CodeMethodReturnStatement(new CodePrimitiveExpression("Return")));
- class1.Members.Add(function1);
-
- CodeMemberMethod function2 = new CodeMemberMethod();
- function2.Name = "GlobalKeywordFunction";
- function2.CustomAttributes.Add(new CodeAttributeDeclaration(new CodeTypeReference(typeof(ObsoleteAttribute), CodeTypeReferenceOptions.GlobalReference), new
- CodeAttributeArgument(new CodePrimitiveExpression("Don't use this Function"))));
- CodeTypeReference typeRef = new CodeTypeReference("System.Xml.Serialization.XmlIgnoreAttribute", CodeTypeReferenceOptions.GlobalReference);
- CodeAttributeDeclaration codeAttrib = new CodeAttributeDeclaration(typeRef);
- function2.ReturnTypeCustomAttributes.Add(codeAttrib);
- class1.Members.Add(function2);
-
- CodeMemberField field1 = new CodeMemberField();
- field1.Name = "myField";
- field1.Type = new CodeTypeReference(typeof(string));
- field1.CustomAttributes.Add(new CodeAttributeDeclaration("System.Xml.Serialization.XmlElementAttribute"));
- field1.InitExpression = new CodePrimitiveExpression("hi!");
- class1.Members.Add(field1);
-
- CodeMemberProperty prop1 = new CodeMemberProperty();
- prop1.Name = "MyProperty";
- prop1.Type = new CodeTypeReference(typeof(string));
- prop1.CustomAttributes.Add(new CodeAttributeDeclaration("System.Obsolete", new CodeAttributeArgument(new CodePrimitiveExpression("Don't use this Property"))));
- prop1.GetStatements.Add(new CodeMethodReturnStatement(new CodeFieldReferenceExpression(new CodeThisReferenceExpression(), "myField")));
- class1.Members.Add(prop1);
-
- CodeConstructor const1 = new CodeConstructor();
- const1.CustomAttributes.Add(new CodeAttributeDeclaration("System.Obsolete", new CodeAttributeArgument(new CodePrimitiveExpression("Don't use this Constructor"))));
- class1.Members.Add(const1);
-
- class1 = new CodeTypeDeclaration("Test");
- class1.IsClass = true;
- class1.BaseTypes.Add(new CodeTypeReference("Form"));
- ns.Types.Add(class1);
-
- CodeMemberField mfield = new CodeMemberField(new CodeTypeReference("Button"), "b");
- mfield.InitExpression = new CodeObjectCreateExpression(new CodeTypeReference("Button"));
- class1.Members.Add(mfield);
-
- CodeConstructor ctor = new CodeConstructor();
- ctor.Attributes = MemberAttributes.Public;
- ctor.Statements.Add(new CodeAssignStatement(new CodeFieldReferenceExpression(new CodeThisReferenceExpression(),
- "Size"), new CodeObjectCreateExpression(new CodeTypeReference("Size"),
- new CodePrimitiveExpression(600), new CodePrimitiveExpression(600))));
- ctor.Statements.Add(new CodeAssignStatement(new CodeFieldReferenceExpression(new CodeTypeReferenceExpression("b"),
- "Text"), new CodePrimitiveExpression("Test")));
- ctor.Statements.Add(new CodeAssignStatement(new CodeFieldReferenceExpression(new CodeTypeReferenceExpression("b"),
- "TabIndex"), new CodePrimitiveExpression(0)));
- ctor.Statements.Add(new CodeAssignStatement(new CodeFieldReferenceExpression(new CodeTypeReferenceExpression("b"),
- "Location"), new CodeObjectCreateExpression(new CodeTypeReference("Point"),
- new CodePrimitiveExpression(400), new CodePrimitiveExpression(525))));
- ctor.Statements.Add(new CodeAttachEventStatement(new CodeEventReferenceExpression(new
- CodeThisReferenceExpression(), "MyEvent"), new CodeDelegateCreateExpression(new CodeTypeReference("EventHandler")
- , new CodeThisReferenceExpression(), "b_Click")));
- class1.Members.Add(ctor);
-
- CodeMemberEvent evt = new CodeMemberEvent();
- evt.Name = "MyEvent";
- evt.Type = new CodeTypeReference("System.EventHandler");
- evt.Attributes = MemberAttributes.Public;
- evt.CustomAttributes.Add(new CodeAttributeDeclaration("System.CLSCompliantAttribute", new CodeAttributeArgument(new CodePrimitiveExpression(false))));
- class1.Members.Add(evt);
-
- var cmm = new CodeMemberMethod();
- cmm.Name = "b_Click";
- cmm.Parameters.Add(new CodeParameterDeclarationExpression(typeof(object), "sender"));
- cmm.Parameters.Add(new CodeParameterDeclarationExpression(typeof(EventArgs), "e"));
- class1.Members.Add(cmm);
-
- AssertEqual(cu,
- @"//------------------------------------------------------------------------------
+ using (new ThreadCultureChange(CultureInfo.InvariantCulture))
+ {
+ var cu = new CodeCompileUnit();
+
+ var ns = new CodeNamespace();
+ ns.Name = "MyNamespace";
+ ns.Imports.Add(new CodeNamespaceImport("System"));
+ ns.Imports.Add(new CodeNamespaceImport("System.Drawing"));
+ ns.Imports.Add(new CodeNamespaceImport("System.Windows.Forms"));
+ ns.Imports.Add(new CodeNamespaceImport("System.ComponentModel"));
+ cu.Namespaces.Add(ns);
+
+ var attrs = cu.AssemblyCustomAttributes;
+ attrs.Add(new CodeAttributeDeclaration("System.Reflection.AssemblyTitle", new CodeAttributeArgument(new CodePrimitiveExpression("MyAssembly"))));
+ attrs.Add(new CodeAttributeDeclaration("System.Reflection.AssemblyVersion", new CodeAttributeArgument(new CodePrimitiveExpression("1.0.6.2"))));
+ attrs.Add(new CodeAttributeDeclaration("System.CLSCompliantAttribute", new CodeAttributeArgument(new CodePrimitiveExpression(false))));
+
+ var class1 = new CodeTypeDeclaration() { Name = "MyClass" };
+ class1.CustomAttributes.Add(new CodeAttributeDeclaration("System.Serializable"));
+ class1.CustomAttributes.Add(new CodeAttributeDeclaration("System.Obsolete", new CodeAttributeArgument(new CodePrimitiveExpression("Don't use this Class"))));
+ ns.Types.Add(class1);
+
+ var nestedClass = new CodeTypeDeclaration("NestedClass") { IsClass = true, TypeAttributes = TypeAttributes.NestedPublic };
+ nestedClass.CustomAttributes.Add(new CodeAttributeDeclaration("System.Serializable"));
+ class1.Members.Add(nestedClass);
+
+ var method1 = new CodeMemberMethod() { Name = "MyMethod" };
+ method1.CustomAttributes.Add(new CodeAttributeDeclaration("System.Obsolete", new CodeAttributeArgument(new CodePrimitiveExpression("Don't use this Method"))));
+ method1.CustomAttributes.Add(new CodeAttributeDeclaration("System.ComponentModel.Editor", new CodeAttributeArgument(new CodePrimitiveExpression("This")), new CodeAttributeArgument(new CodePrimitiveExpression("That"))));
+ var param1 = new CodeParameterDeclarationExpression(typeof(string), "blah");
+ param1.CustomAttributes.Add(new CodeAttributeDeclaration("System.Xml.Serialization.XmlElementAttribute",
+ new CodeAttributeArgument("Form", new CodeFieldReferenceExpression(new CodeTypeReferenceExpression("System.Xml.Schema.XmlSchemaForm"), "Unqualified")),
+ new CodeAttributeArgument("IsNullable", new CodePrimitiveExpression(false))));
+ method1.Parameters.Add(param1);
+ var param2 = new CodeParameterDeclarationExpression(typeof(int[]), "arrayit");
+ param2.CustomAttributes.Add(
+ new CodeAttributeDeclaration("System.Xml.Serialization.XmlElementAttribute",
+ new CodeAttributeArgument("Form", new CodeFieldReferenceExpression(new CodeTypeReferenceExpression("System.Xml.Schema.XmlSchemaForm"), "Unqualified")),
+ new CodeAttributeArgument("IsNullable", new CodePrimitiveExpression(false))));
+ method1.Parameters.Add(param2);
+ class1.Members.Add(method1);
+
+ var function1 = new CodeMemberMethod();
+ function1.Name = "MyFunction";
+ function1.ReturnType = new CodeTypeReference(typeof(string));
+ function1.CustomAttributes.Add(new CodeAttributeDeclaration("System.Obsolete", new CodeAttributeArgument(new CodePrimitiveExpression("Don't use this Function"))));
+ function1.ReturnTypeCustomAttributes.Add(new CodeAttributeDeclaration("System.Xml.Serialization.XmlIgnoreAttribute"));
+ function1.ReturnTypeCustomAttributes.Add(new CodeAttributeDeclaration("System.Xml.Serialization.XmlRootAttribute", new
+ CodeAttributeArgument("Namespace", new CodePrimitiveExpression("Namespace Value")), new
+ CodeAttributeArgument("ElementName", new CodePrimitiveExpression("Root, hehehe"))));
+ function1.Statements.Add(new CodeMethodReturnStatement(new CodePrimitiveExpression("Return")));
+ class1.Members.Add(function1);
+
+ CodeMemberMethod function2 = new CodeMemberMethod();
+ function2.Name = "GlobalKeywordFunction";
+ function2.CustomAttributes.Add(new CodeAttributeDeclaration(new CodeTypeReference(typeof(ObsoleteAttribute), CodeTypeReferenceOptions.GlobalReference), new
+ CodeAttributeArgument(new CodePrimitiveExpression("Don't use this Function"))));
+ CodeTypeReference typeRef = new CodeTypeReference("System.Xml.Serialization.XmlIgnoreAttribute", CodeTypeReferenceOptions.GlobalReference);
+ CodeAttributeDeclaration codeAttrib = new CodeAttributeDeclaration(typeRef);
+ function2.ReturnTypeCustomAttributes.Add(codeAttrib);
+ class1.Members.Add(function2);
+
+ CodeMemberField field1 = new CodeMemberField();
+ field1.Name = "myField";
+ field1.Type = new CodeTypeReference(typeof(string));
+ field1.CustomAttributes.Add(new CodeAttributeDeclaration("System.Xml.Serialization.XmlElementAttribute"));
+ field1.InitExpression = new CodePrimitiveExpression("hi!");
+ class1.Members.Add(field1);
+
+ CodeMemberProperty prop1 = new CodeMemberProperty();
+ prop1.Name = "MyProperty";
+ prop1.Type = new CodeTypeReference(typeof(string));
+ prop1.CustomAttributes.Add(new CodeAttributeDeclaration("System.Obsolete", new CodeAttributeArgument(new CodePrimitiveExpression("Don't use this Property"))));
+ prop1.GetStatements.Add(new CodeMethodReturnStatement(new CodeFieldReferenceExpression(new CodeThisReferenceExpression(), "myField")));
+ class1.Members.Add(prop1);
+
+ CodeConstructor const1 = new CodeConstructor();
+ const1.CustomAttributes.Add(new CodeAttributeDeclaration("System.Obsolete", new CodeAttributeArgument(new CodePrimitiveExpression("Don't use this Constructor"))));
+ class1.Members.Add(const1);
+
+ class1 = new CodeTypeDeclaration("Test");
+ class1.IsClass = true;
+ class1.BaseTypes.Add(new CodeTypeReference("Form"));
+ ns.Types.Add(class1);
+
+ CodeMemberField mfield = new CodeMemberField(new CodeTypeReference("Button"), "b");
+ mfield.InitExpression = new CodeObjectCreateExpression(new CodeTypeReference("Button"));
+ class1.Members.Add(mfield);
+
+ CodeConstructor ctor = new CodeConstructor();
+ ctor.Attributes = MemberAttributes.Public;
+ ctor.Statements.Add(new CodeAssignStatement(new CodeFieldReferenceExpression(new CodeThisReferenceExpression(),
+ "Size"), new CodeObjectCreateExpression(new CodeTypeReference("Size"),
+ new CodePrimitiveExpression(600), new CodePrimitiveExpression(600))));
+ ctor.Statements.Add(new CodeAssignStatement(new CodeFieldReferenceExpression(new CodeTypeReferenceExpression("b"),
+ "Text"), new CodePrimitiveExpression("Test")));
+ ctor.Statements.Add(new CodeAssignStatement(new CodeFieldReferenceExpression(new CodeTypeReferenceExpression("b"),
+ "TabIndex"), new CodePrimitiveExpression(0)));
+ ctor.Statements.Add(new CodeAssignStatement(new CodeFieldReferenceExpression(new CodeTypeReferenceExpression("b"),
+ "Location"), new CodeObjectCreateExpression(new CodeTypeReference("Point"),
+ new CodePrimitiveExpression(400), new CodePrimitiveExpression(525))));
+ ctor.Statements.Add(new CodeAttachEventStatement(new CodeEventReferenceExpression(new
+ CodeThisReferenceExpression(), "MyEvent"), new CodeDelegateCreateExpression(new CodeTypeReference("EventHandler")
+ , new CodeThisReferenceExpression(), "b_Click")));
+ class1.Members.Add(ctor);
+
+ CodeMemberEvent evt = new CodeMemberEvent();
+ evt.Name = "MyEvent";
+ evt.Type = new CodeTypeReference("System.EventHandler");
+ evt.Attributes = MemberAttributes.Public;
+ evt.CustomAttributes.Add(new CodeAttributeDeclaration("System.CLSCompliantAttribute", new CodeAttributeArgument(new CodePrimitiveExpression(false))));
+ class1.Members.Add(evt);
+
+ var cmm = new CodeMemberMethod();
+ cmm.Name = "b_Click";
+ cmm.Parameters.Add(new CodeParameterDeclarationExpression(typeof(object), "sender"));
+ cmm.Parameters.Add(new CodeParameterDeclarationExpression(typeof(EventArgs), "e"));
+ class1.Members.Add(cmm);
+
+ AssertEqual(cu,
+ @"//------------------------------------------------------------------------------
// <auto-generated>
// This code was generated by a tool.
//
}
}
}");
+ }
}).Dispose();
}
[SkipOnTargetFramework(TargetFrameworkMonikers.NetFramework)]
public void RegionsSnippetsAndLinePragmas()
{
- RemoteExecutor.Invoke(() =>
+ RemoteExecutorForUap.Invoke(() =>
{
- CultureInfo.CurrentUICulture = CultureInfo.InvariantCulture;
-
- var cu = new CodeCompileUnit();
- CodeNamespace ns = new CodeNamespace("Namespace1");
+ using (new ThreadCultureChange(CultureInfo.InvariantCulture))
+ {
+ var cu = new CodeCompileUnit();
+ CodeNamespace ns = new CodeNamespace("Namespace1");
- cu.StartDirectives.Add(new CodeRegionDirective(CodeRegionMode.Start, "Compile Unit Region"));
- cu.EndDirectives.Add(new CodeRegionDirective(CodeRegionMode.End, string.Empty));
+ cu.StartDirectives.Add(new CodeRegionDirective(CodeRegionMode.Start, "Compile Unit Region"));
+ cu.EndDirectives.Add(new CodeRegionDirective(CodeRegionMode.End, string.Empty));
- cu.Namespaces.Add(ns);
+ cu.Namespaces.Add(ns);
- var cd = new CodeTypeDeclaration("Class1");
- ns.Types.Add(cd);
+ var cd = new CodeTypeDeclaration("Class1");
+ ns.Types.Add(cd);
- cd.StartDirectives.Add(new CodeRegionDirective(CodeRegionMode.Start, "Outer Type Region"));
- cd.EndDirectives.Add(new CodeRegionDirective(CodeRegionMode.End, string.Empty));
+ cd.StartDirectives.Add(new CodeRegionDirective(CodeRegionMode.Start, "Outer Type Region"));
+ cd.EndDirectives.Add(new CodeRegionDirective(CodeRegionMode.End, string.Empty));
- cd.Comments.Add(new CodeCommentStatement("Outer Type Comment"));
+ cd.Comments.Add(new CodeCommentStatement("Outer Type Comment"));
- CodeMemberField field1 = new CodeMemberField(typeof(String), "field1");
- CodeMemberField field2 = new CodeMemberField(typeof(String), "field2");
- field1.Comments.Add(new CodeCommentStatement("Field 1 Comment"));
- field2.StartDirectives.Add(new CodeRegionDirective(CodeRegionMode.Start, "Field Region"));
- field2.EndDirectives.Add(new CodeRegionDirective(CodeRegionMode.End, string.Empty));
+ CodeMemberField field1 = new CodeMemberField(typeof(String), "field1");
+ CodeMemberField field2 = new CodeMemberField(typeof(String), "field2");
+ field1.Comments.Add(new CodeCommentStatement("Field 1 Comment"));
+ field2.StartDirectives.Add(new CodeRegionDirective(CodeRegionMode.Start, "Field Region"));
+ field2.EndDirectives.Add(new CodeRegionDirective(CodeRegionMode.End, string.Empty));
- CodeMemberEvent evt1 = new CodeMemberEvent();
- evt1.Name = "Event1";
- evt1.Type = new CodeTypeReference(typeof(System.EventHandler));
- evt1.Attributes = (evt1.Attributes & ~MemberAttributes.AccessMask) | MemberAttributes.Public;
+ CodeMemberEvent evt1 = new CodeMemberEvent();
+ evt1.Name = "Event1";
+ evt1.Type = new CodeTypeReference(typeof(System.EventHandler));
+ evt1.Attributes = (evt1.Attributes & ~MemberAttributes.AccessMask) | MemberAttributes.Public;
- CodeMemberEvent evt2 = new CodeMemberEvent();
- evt2.Name = "Event2";
- evt2.Type = new CodeTypeReference(typeof(System.EventHandler));
- evt2.Attributes = (evt2.Attributes & ~MemberAttributes.AccessMask) | MemberAttributes.Public;
+ CodeMemberEvent evt2 = new CodeMemberEvent();
+ evt2.Name = "Event2";
+ evt2.Type = new CodeTypeReference(typeof(System.EventHandler));
+ evt2.Attributes = (evt2.Attributes & ~MemberAttributes.AccessMask) | MemberAttributes.Public;
- evt2.StartDirectives.Add(new CodeRegionDirective(CodeRegionMode.Start, "Event Region"));
- evt2.EndDirectives.Add(new CodeRegionDirective(CodeRegionMode.End, string.Empty));
+ evt2.StartDirectives.Add(new CodeRegionDirective(CodeRegionMode.Start, "Event Region"));
+ evt2.EndDirectives.Add(new CodeRegionDirective(CodeRegionMode.End, string.Empty));
- CodeMemberMethod method1 = new CodeMemberMethod();
- method1.Name = "Method1";
- method1.Attributes = (method1.Attributes & ~MemberAttributes.AccessMask) | MemberAttributes.Public;
- method1.Statements.Add(
- new CodeDelegateInvokeExpression(
- new CodeEventReferenceExpression(new CodeThisReferenceExpression(), "Event1"),
- new CodeExpression[] {
+ CodeMemberMethod method1 = new CodeMemberMethod();
+ method1.Name = "Method1";
+ method1.Attributes = (method1.Attributes & ~MemberAttributes.AccessMask) | MemberAttributes.Public;
+ method1.Statements.Add(
+ new CodeDelegateInvokeExpression(
+ new CodeEventReferenceExpression(new CodeThisReferenceExpression(), "Event1"),
+ new CodeExpression[] {
new CodeThisReferenceExpression(),
new CodeFieldReferenceExpression(new CodeTypeReferenceExpression("System.EventArgs"), "Empty")
- }));
-
- CodeMemberMethod method2 = new CodeMemberMethod();
- method2.Name = "Method2";
- method2.Attributes = (method2.Attributes & ~MemberAttributes.AccessMask) | MemberAttributes.Public;
- method2.Statements.Add(
- new CodeDelegateInvokeExpression(
- new CodeEventReferenceExpression(new CodeThisReferenceExpression(), "Event2"),
- new CodeExpression[] {
+ }));
+
+ CodeMemberMethod method2 = new CodeMemberMethod();
+ method2.Name = "Method2";
+ method2.Attributes = (method2.Attributes & ~MemberAttributes.AccessMask) | MemberAttributes.Public;
+ method2.Statements.Add(
+ new CodeDelegateInvokeExpression(
+ new CodeEventReferenceExpression(new CodeThisReferenceExpression(), "Event2"),
+ new CodeExpression[] {
new CodeThisReferenceExpression(),
new CodeFieldReferenceExpression(new CodeTypeReferenceExpression("System.EventArgs"), "Empty")
- }));
- method2.LinePragma = new CodeLinePragma("MethodLinePragma.txt", 500);
- method2.Comments.Add(new CodeCommentStatement("Method 2 Comment"));
-
- method2.StartDirectives.Add(new CodeRegionDirective(CodeRegionMode.Start, "Method Region"));
- method2.EndDirectives.Add(new CodeRegionDirective(CodeRegionMode.End, string.Empty));
-
- CodeMemberProperty property1 = new CodeMemberProperty();
- property1.Name = "Property1";
- property1.Type = new CodeTypeReference(typeof(string));
- property1.Attributes = (property1.Attributes & ~MemberAttributes.AccessMask) | MemberAttributes.Public;
- property1.GetStatements.Add(
- new CodeMethodReturnStatement(
- new CodeFieldReferenceExpression(
- new CodeThisReferenceExpression(),
- "field1")));
-
- CodeMemberProperty property2 = new CodeMemberProperty();
- property2.Name = "Property2";
- property2.Type = new CodeTypeReference(typeof(string));
- property2.Attributes = (property2.Attributes & ~MemberAttributes.AccessMask) | MemberAttributes.Public;
- property2.GetStatements.Add(
- new CodeMethodReturnStatement(
- new CodeFieldReferenceExpression(
- new CodeThisReferenceExpression(),
- "field2")));
-
- property2.StartDirectives.Add(new CodeRegionDirective(CodeRegionMode.Start, "Property Region"));
- property2.EndDirectives.Add(new CodeRegionDirective(CodeRegionMode.End, string.Empty));
-
- CodeConstructor constructor1 = new CodeConstructor();
- constructor1.Attributes = (constructor1.Attributes & ~MemberAttributes.AccessMask) | MemberAttributes.Public;
- CodeStatement conState1 = new CodeAssignStatement(
- new CodeFieldReferenceExpression(
- new CodeThisReferenceExpression(),
- "field1"),
- new CodePrimitiveExpression("value1"));
- conState1.StartDirectives.Add(new CodeRegionDirective(CodeRegionMode.Start, "Statements Region"));
- constructor1.Statements.Add(conState1);
- CodeStatement conState2 = new CodeAssignStatement(
- new CodeFieldReferenceExpression(
- new CodeThisReferenceExpression(),
- "field2"),
- new CodePrimitiveExpression("value2"));
- conState2.EndDirectives.Add(new CodeRegionDirective(CodeRegionMode.End, string.Empty));
- constructor1.Statements.Add(conState2);
-
- constructor1.StartDirectives.Add(new CodeRegionDirective(CodeRegionMode.Start, "Constructor Region"));
- constructor1.EndDirectives.Add(new CodeRegionDirective(CodeRegionMode.End, string.Empty));
-
- CodeConstructor constructor2 = new CodeConstructor();
- constructor2.Attributes = (constructor2.Attributes & ~MemberAttributes.AccessMask) | MemberAttributes.Public;
- constructor2.Parameters.Add(new CodeParameterDeclarationExpression(typeof(string), "value1"));
- constructor2.Parameters.Add(new CodeParameterDeclarationExpression(typeof(string), "value2"));
-
- CodeTypeConstructor typeConstructor2 = new CodeTypeConstructor();
-
- typeConstructor2.StartDirectives.Add(new CodeRegionDirective(CodeRegionMode.Start, "Type Constructor Region"));
- typeConstructor2.EndDirectives.Add(new CodeRegionDirective(CodeRegionMode.End, string.Empty));
-
- CodeEntryPointMethod methodMain = new CodeEntryPointMethod();
-
- CodeTypeDeclaration nestedClass1 = new CodeTypeDeclaration("NestedClass1");
- CodeTypeDeclaration nestedClass2 = new CodeTypeDeclaration("NestedClass2");
- nestedClass2.LinePragma = new CodeLinePragma("NestedTypeLinePragma.txt", 400);
- nestedClass2.Comments.Add(new CodeCommentStatement("Nested Type Comment"));
-
- nestedClass2.StartDirectives.Add(new CodeRegionDirective(CodeRegionMode.Start, "Nested Type Region"));
- nestedClass2.EndDirectives.Add(new CodeRegionDirective(CodeRegionMode.End, string.Empty));
-
- CodeTypeDelegate delegate1 = new CodeTypeDelegate();
- delegate1.Name = "nestedDelegate1";
- delegate1.Parameters.Add(new CodeParameterDeclarationExpression(new CodeTypeReference("System.Object"), "sender"));
- delegate1.Parameters.Add(new CodeParameterDeclarationExpression(new CodeTypeReference("System.EventArgs"), "e"));
-
- CodeTypeDelegate delegate2 = new CodeTypeDelegate();
- delegate2.Name = "nestedDelegate2";
- delegate2.Parameters.Add(new CodeParameterDeclarationExpression(new CodeTypeReference("System.Object"), "sender"));
- delegate2.Parameters.Add(new CodeParameterDeclarationExpression(new CodeTypeReference("System.EventArgs"), "e"));
-
- delegate2.StartDirectives.Add(new CodeRegionDirective(CodeRegionMode.Start, "Delegate Region"));
- delegate2.EndDirectives.Add(new CodeRegionDirective(CodeRegionMode.End, string.Empty));
-
- var snippet1 = new CodeSnippetTypeMember();
- var snippet2 = new CodeSnippetTypeMember();
-
- CodeRegionDirective regionStart = new CodeRegionDirective(CodeRegionMode.End, "");
- regionStart.RegionText = "Snippet Region";
- regionStart.RegionMode = CodeRegionMode.Start;
- snippet2.StartDirectives.Add(regionStart);
- snippet2.EndDirectives.Add(new CodeRegionDirective(CodeRegionMode.End, string.Empty));
-
- cd.Members.Add(field1);
- cd.Members.Add(method1);
- cd.Members.Add(constructor1);
- cd.Members.Add(property1);
- cd.Members.Add(methodMain);
-
- cd.Members.Add(evt1);
- cd.Members.Add(nestedClass1);
- cd.Members.Add(delegate1);
-
- cd.Members.Add(snippet1);
-
- cd.Members.Add(field2);
- cd.Members.Add(method2);
- cd.Members.Add(constructor2);
- cd.Members.Add(property2);
-
- cd.Members.Add(typeConstructor2);
- cd.Members.Add(evt2);
- cd.Members.Add(nestedClass2);
- cd.Members.Add(delegate2);
- cd.Members.Add(snippet2);
-
- AssertEqual(cu,
- @"#region Compile Unit Region
+ }));
+ method2.LinePragma = new CodeLinePragma("MethodLinePragma.txt", 500);
+ method2.Comments.Add(new CodeCommentStatement("Method 2 Comment"));
+
+ method2.StartDirectives.Add(new CodeRegionDirective(CodeRegionMode.Start, "Method Region"));
+ method2.EndDirectives.Add(new CodeRegionDirective(CodeRegionMode.End, string.Empty));
+
+ CodeMemberProperty property1 = new CodeMemberProperty();
+ property1.Name = "Property1";
+ property1.Type = new CodeTypeReference(typeof(string));
+ property1.Attributes = (property1.Attributes & ~MemberAttributes.AccessMask) | MemberAttributes.Public;
+ property1.GetStatements.Add(
+ new CodeMethodReturnStatement(
+ new CodeFieldReferenceExpression(
+ new CodeThisReferenceExpression(),
+ "field1")));
+
+ CodeMemberProperty property2 = new CodeMemberProperty();
+ property2.Name = "Property2";
+ property2.Type = new CodeTypeReference(typeof(string));
+ property2.Attributes = (property2.Attributes & ~MemberAttributes.AccessMask) | MemberAttributes.Public;
+ property2.GetStatements.Add(
+ new CodeMethodReturnStatement(
+ new CodeFieldReferenceExpression(
+ new CodeThisReferenceExpression(),
+ "field2")));
+
+ property2.StartDirectives.Add(new CodeRegionDirective(CodeRegionMode.Start, "Property Region"));
+ property2.EndDirectives.Add(new CodeRegionDirective(CodeRegionMode.End, string.Empty));
+
+ CodeConstructor constructor1 = new CodeConstructor();
+ constructor1.Attributes = (constructor1.Attributes & ~MemberAttributes.AccessMask) | MemberAttributes.Public;
+ CodeStatement conState1 = new CodeAssignStatement(
+ new CodeFieldReferenceExpression(
+ new CodeThisReferenceExpression(),
+ "field1"),
+ new CodePrimitiveExpression("value1"));
+ conState1.StartDirectives.Add(new CodeRegionDirective(CodeRegionMode.Start, "Statements Region"));
+ constructor1.Statements.Add(conState1);
+ CodeStatement conState2 = new CodeAssignStatement(
+ new CodeFieldReferenceExpression(
+ new CodeThisReferenceExpression(),
+ "field2"),
+ new CodePrimitiveExpression("value2"));
+ conState2.EndDirectives.Add(new CodeRegionDirective(CodeRegionMode.End, string.Empty));
+ constructor1.Statements.Add(conState2);
+
+ constructor1.StartDirectives.Add(new CodeRegionDirective(CodeRegionMode.Start, "Constructor Region"));
+ constructor1.EndDirectives.Add(new CodeRegionDirective(CodeRegionMode.End, string.Empty));
+
+ CodeConstructor constructor2 = new CodeConstructor();
+ constructor2.Attributes = (constructor2.Attributes & ~MemberAttributes.AccessMask) | MemberAttributes.Public;
+ constructor2.Parameters.Add(new CodeParameterDeclarationExpression(typeof(string), "value1"));
+ constructor2.Parameters.Add(new CodeParameterDeclarationExpression(typeof(string), "value2"));
+
+ CodeTypeConstructor typeConstructor2 = new CodeTypeConstructor();
+
+ typeConstructor2.StartDirectives.Add(new CodeRegionDirective(CodeRegionMode.Start, "Type Constructor Region"));
+ typeConstructor2.EndDirectives.Add(new CodeRegionDirective(CodeRegionMode.End, string.Empty));
+
+ CodeEntryPointMethod methodMain = new CodeEntryPointMethod();
+
+ CodeTypeDeclaration nestedClass1 = new CodeTypeDeclaration("NestedClass1");
+ CodeTypeDeclaration nestedClass2 = new CodeTypeDeclaration("NestedClass2");
+ nestedClass2.LinePragma = new CodeLinePragma("NestedTypeLinePragma.txt", 400);
+ nestedClass2.Comments.Add(new CodeCommentStatement("Nested Type Comment"));
+
+ nestedClass2.StartDirectives.Add(new CodeRegionDirective(CodeRegionMode.Start, "Nested Type Region"));
+ nestedClass2.EndDirectives.Add(new CodeRegionDirective(CodeRegionMode.End, string.Empty));
+
+ CodeTypeDelegate delegate1 = new CodeTypeDelegate();
+ delegate1.Name = "nestedDelegate1";
+ delegate1.Parameters.Add(new CodeParameterDeclarationExpression(new CodeTypeReference("System.Object"), "sender"));
+ delegate1.Parameters.Add(new CodeParameterDeclarationExpression(new CodeTypeReference("System.EventArgs"), "e"));
+
+ CodeTypeDelegate delegate2 = new CodeTypeDelegate();
+ delegate2.Name = "nestedDelegate2";
+ delegate2.Parameters.Add(new CodeParameterDeclarationExpression(new CodeTypeReference("System.Object"), "sender"));
+ delegate2.Parameters.Add(new CodeParameterDeclarationExpression(new CodeTypeReference("System.EventArgs"), "e"));
+
+ delegate2.StartDirectives.Add(new CodeRegionDirective(CodeRegionMode.Start, "Delegate Region"));
+ delegate2.EndDirectives.Add(new CodeRegionDirective(CodeRegionMode.End, string.Empty));
+
+ var snippet1 = new CodeSnippetTypeMember();
+ var snippet2 = new CodeSnippetTypeMember();
+
+ CodeRegionDirective regionStart = new CodeRegionDirective(CodeRegionMode.End, "");
+ regionStart.RegionText = "Snippet Region";
+ regionStart.RegionMode = CodeRegionMode.Start;
+ snippet2.StartDirectives.Add(regionStart);
+ snippet2.EndDirectives.Add(new CodeRegionDirective(CodeRegionMode.End, string.Empty));
+
+ cd.Members.Add(field1);
+ cd.Members.Add(method1);
+ cd.Members.Add(constructor1);
+ cd.Members.Add(property1);
+ cd.Members.Add(methodMain);
+
+ cd.Members.Add(evt1);
+ cd.Members.Add(nestedClass1);
+ cd.Members.Add(delegate1);
+
+ cd.Members.Add(snippet1);
+
+ cd.Members.Add(field2);
+ cd.Members.Add(method2);
+ cd.Members.Add(constructor2);
+ cd.Members.Add(property2);
+
+ cd.Members.Add(typeConstructor2);
+ cd.Members.Add(evt2);
+ cd.Members.Add(nestedClass2);
+ cd.Members.Add(delegate2);
+ cd.Members.Add(snippet2);
+
+ AssertEqual(cu,
+ @"#region Compile Unit Region
//------------------------------------------------------------------------------
// <auto-generated>
// This code was generated by a tool.
#endregion
}
#endregion");
+ }
}).Dispose();
}
[SkipOnTargetFramework(TargetFrameworkMonikers.NetFramework)]
public void ProviderSupports()
{
- RemoteExecutor.Invoke(() =>
+ RemoteExecutorForUap.Invoke(() =>
{
- CultureInfo.CurrentUICulture = CultureInfo.InvariantCulture;
-
- CodeDomProvider provider = GetProvider();
-
- var cu = new CodeCompileUnit();
- var nspace = new CodeNamespace("NSPC");
- nspace.Imports.Add(new CodeNamespaceImport("System"));
- nspace.Imports.Add(new CodeNamespaceImport("System.Drawing"));
- nspace.Imports.Add(new CodeNamespaceImport("System.Windows.Forms"));
- nspace.Imports.Add(new CodeNamespaceImport("System.ComponentModel"));
- cu.Namespaces.Add(nspace);
-
- var cd = new CodeTypeDeclaration("TEST");
- cd.IsClass = true;
- nspace.Types.Add(cd);
-
- // Arrays of Arrays
- var cmm = new CodeMemberMethod();
- cmm.Name = "ArraysOfArrays";
- cmm.ReturnType = new CodeTypeReference(typeof(int));
- cmm.Attributes = MemberAttributes.Final | MemberAttributes.Public;
- if (provider.Supports(GeneratorSupport.ArraysOfArrays))
- {
- cmm.Statements.Add(new CodeVariableDeclarationStatement(new CodeTypeReference(typeof(int[][])),
- "arrayOfArrays", new CodeArrayCreateExpression(typeof(int[][]),
- new CodeArrayCreateExpression(typeof(int[]), new CodePrimitiveExpression(3), new CodePrimitiveExpression(4)),
- new CodeArrayCreateExpression(typeof(int[]), new CodeExpression[] { new CodePrimitiveExpression(1) }))));
- cmm.Statements.Add(new CodeMethodReturnStatement(new CodeArrayIndexerExpression(
- new CodeArrayIndexerExpression(new CodeVariableReferenceExpression("arrayOfArrays"), new CodePrimitiveExpression(0))
- , new CodePrimitiveExpression(1))));
- }
- else
+ using (new ThreadCultureChange(CultureInfo.InvariantCulture))
{
- cmm.Statements.Add(new CodeMethodReturnStatement(new CodePrimitiveExpression(0)));
- }
- cd.Members.Add(cmm);
-
- // assembly attributes
- if (provider.Supports(GeneratorSupport.AssemblyAttributes))
- {
- CodeAttributeDeclarationCollection attrs = cu.AssemblyCustomAttributes;
- attrs.Add(new CodeAttributeDeclaration("System.Reflection.AssemblyTitle", new
- CodeAttributeArgument(new CodePrimitiveExpression("MyAssembly"))));
- attrs.Add(new CodeAttributeDeclaration("System.Reflection.AssemblyVersion", new
- CodeAttributeArgument(new CodePrimitiveExpression("1.0.6.2"))));
- }
-
- CodeTypeDeclaration class1 = new CodeTypeDeclaration();
- if (provider.Supports(GeneratorSupport.ChainedConstructorArguments))
- {
- class1.Name = "Test2";
- class1.IsClass = true;
- nspace.Types.Add(class1);
-
- class1.Members.Add(new CodeMemberField(new CodeTypeReference(typeof(String)), "stringField"));
- CodeMemberProperty prop = new CodeMemberProperty();
- prop.Name = "accessStringField";
- prop.Attributes = MemberAttributes.Public | MemberAttributes.Final;
- prop.Type = new CodeTypeReference(typeof(String));
- prop.GetStatements.Add(new CodeMethodReturnStatement(new CodeFieldReferenceExpression(new CodeThisReferenceExpression(),
- "stringField")));
- prop.SetStatements.Add(new CodeAssignStatement(new CodeFieldReferenceExpression(new
- CodeThisReferenceExpression(), "stringField"),
- new CodePropertySetValueReferenceExpression()));
- class1.Members.Add(prop);
-
- CodeConstructor cctor = new CodeConstructor();
- cctor.Attributes = MemberAttributes.Public;
- cctor.ChainedConstructorArgs.Add(new CodePrimitiveExpression("testingString"));
- cctor.ChainedConstructorArgs.Add(new CodePrimitiveExpression(null));
- cctor.ChainedConstructorArgs.Add(new CodePrimitiveExpression(null));
- class1.Members.Add(cctor);
-
- CodeConstructor cc = new CodeConstructor();
- cc.Attributes = MemberAttributes.Public | MemberAttributes.Overloaded;
- cc.Parameters.Add(new CodeParameterDeclarationExpression(typeof(string), "p1"));
- cc.Parameters.Add(new CodeParameterDeclarationExpression(typeof(string), "p2"));
- cc.Parameters.Add(new CodeParameterDeclarationExpression(typeof(string), "p3"));
- cc.Statements.Add(new CodeAssignStatement(new CodeFieldReferenceExpression(new CodeThisReferenceExpression()
- , "stringField"), new CodeVariableReferenceExpression("p1")));
- class1.Members.Add(cc);
- // verify chained constructors work
- cmm = new CodeMemberMethod();
- cmm.Name = "ChainedConstructorUse";
- cmm.Attributes = MemberAttributes.Public | MemberAttributes.Static;
- cmm.ReturnType = new CodeTypeReference(typeof(String));
- // utilize constructor
- cmm.Statements.Add(new CodeVariableDeclarationStatement("Test2", "t", new CodeObjectCreateExpression("Test2")));
- cmm.Statements.Add(new CodeMethodReturnStatement(new CodeMethodReferenceExpression(
- new CodeVariableReferenceExpression("t"), "accessStringField")));
- cd.Members.Add(cmm);
- }
-
- // complex expressions
- if (provider.Supports(GeneratorSupport.ComplexExpressions))
- {
- cmm = new CodeMemberMethod();
- cmm.Name = "ComplexExpressions";
+ CodeDomProvider provider = GetProvider();
+
+ var cu = new CodeCompileUnit();
+ var nspace = new CodeNamespace("NSPC");
+ nspace.Imports.Add(new CodeNamespaceImport("System"));
+ nspace.Imports.Add(new CodeNamespaceImport("System.Drawing"));
+ nspace.Imports.Add(new CodeNamespaceImport("System.Windows.Forms"));
+ nspace.Imports.Add(new CodeNamespaceImport("System.ComponentModel"));
+ cu.Namespaces.Add(nspace);
+
+ var cd = new CodeTypeDeclaration("TEST");
+ cd.IsClass = true;
+ nspace.Types.Add(cd);
+
+ // Arrays of Arrays
+ var cmm = new CodeMemberMethod();
+ cmm.Name = "ArraysOfArrays";
cmm.ReturnType = new CodeTypeReference(typeof(int));
cmm.Attributes = MemberAttributes.Final | MemberAttributes.Public;
- cmm.Parameters.Add(new CodeParameterDeclarationExpression(new CodeTypeReference(typeof(int)), "i"));
- cmm.Statements.Add(new CodeAssignStatement(new CodeVariableReferenceExpression("i"),
- new CodeBinaryOperatorExpression(new CodeVariableReferenceExpression("i"), CodeBinaryOperatorType.Multiply,
- new CodeBinaryOperatorExpression(new CodeVariableReferenceExpression("i"), CodeBinaryOperatorType.Add,
- new CodePrimitiveExpression(3)))));
- cmm.Statements.Add(new CodeMethodReturnStatement(new CodeVariableReferenceExpression("i")));
+ if (provider.Supports(GeneratorSupport.ArraysOfArrays))
+ {
+ cmm.Statements.Add(new CodeVariableDeclarationStatement(new CodeTypeReference(typeof(int[][])),
+ "arrayOfArrays", new CodeArrayCreateExpression(typeof(int[][]),
+ new CodeArrayCreateExpression(typeof(int[]), new CodePrimitiveExpression(3), new CodePrimitiveExpression(4)),
+ new CodeArrayCreateExpression(typeof(int[]), new CodeExpression[] { new CodePrimitiveExpression(1) }))));
+ cmm.Statements.Add(new CodeMethodReturnStatement(new CodeArrayIndexerExpression(
+ new CodeArrayIndexerExpression(new CodeVariableReferenceExpression("arrayOfArrays"), new CodePrimitiveExpression(0))
+ , new CodePrimitiveExpression(1))));
+ }
+ else
+ {
+ cmm.Statements.Add(new CodeMethodReturnStatement(new CodePrimitiveExpression(0)));
+ }
cd.Members.Add(cmm);
- }
- if (provider.Supports(GeneratorSupport.DeclareEnums))
- {
- CodeTypeDeclaration ce = new CodeTypeDeclaration("DecimalEnum");
- ce.IsEnum = true;
- nspace.Types.Add(ce);
+ // assembly attributes
+ if (provider.Supports(GeneratorSupport.AssemblyAttributes))
+ {
+ CodeAttributeDeclarationCollection attrs = cu.AssemblyCustomAttributes;
+ attrs.Add(new CodeAttributeDeclaration("System.Reflection.AssemblyTitle", new
+ CodeAttributeArgument(new CodePrimitiveExpression("MyAssembly"))));
+ attrs.Add(new CodeAttributeDeclaration("System.Reflection.AssemblyVersion", new
+ CodeAttributeArgument(new CodePrimitiveExpression("1.0.6.2"))));
+ }
- // things to enumerate
- for (int k = 0; k < 5; k++)
+ CodeTypeDeclaration class1 = new CodeTypeDeclaration();
+ if (provider.Supports(GeneratorSupport.ChainedConstructorArguments))
{
- CodeMemberField Field = new CodeMemberField("System.Int32", "Num" + (k).ToString());
- Field.InitExpression = new CodePrimitiveExpression(k);
- ce.Members.Add(Field);
+ class1.Name = "Test2";
+ class1.IsClass = true;
+ nspace.Types.Add(class1);
+
+ class1.Members.Add(new CodeMemberField(new CodeTypeReference(typeof(String)), "stringField"));
+ CodeMemberProperty prop = new CodeMemberProperty();
+ prop.Name = "accessStringField";
+ prop.Attributes = MemberAttributes.Public | MemberAttributes.Final;
+ prop.Type = new CodeTypeReference(typeof(String));
+ prop.GetStatements.Add(new CodeMethodReturnStatement(new CodeFieldReferenceExpression(new CodeThisReferenceExpression(),
+ "stringField")));
+ prop.SetStatements.Add(new CodeAssignStatement(new CodeFieldReferenceExpression(new
+ CodeThisReferenceExpression(), "stringField"),
+ new CodePropertySetValueReferenceExpression()));
+ class1.Members.Add(prop);
+
+ CodeConstructor cctor = new CodeConstructor();
+ cctor.Attributes = MemberAttributes.Public;
+ cctor.ChainedConstructorArgs.Add(new CodePrimitiveExpression("testingString"));
+ cctor.ChainedConstructorArgs.Add(new CodePrimitiveExpression(null));
+ cctor.ChainedConstructorArgs.Add(new CodePrimitiveExpression(null));
+ class1.Members.Add(cctor);
+
+ CodeConstructor cc = new CodeConstructor();
+ cc.Attributes = MemberAttributes.Public | MemberAttributes.Overloaded;
+ cc.Parameters.Add(new CodeParameterDeclarationExpression(typeof(string), "p1"));
+ cc.Parameters.Add(new CodeParameterDeclarationExpression(typeof(string), "p2"));
+ cc.Parameters.Add(new CodeParameterDeclarationExpression(typeof(string), "p3"));
+ cc.Statements.Add(new CodeAssignStatement(new CodeFieldReferenceExpression(new CodeThisReferenceExpression()
+ , "stringField"), new CodeVariableReferenceExpression("p1")));
+ class1.Members.Add(cc);
+ // verify chained constructors work
+ cmm = new CodeMemberMethod();
+ cmm.Name = "ChainedConstructorUse";
+ cmm.Attributes = MemberAttributes.Public | MemberAttributes.Static;
+ cmm.ReturnType = new CodeTypeReference(typeof(String));
+ // utilize constructor
+ cmm.Statements.Add(new CodeVariableDeclarationStatement("Test2", "t", new CodeObjectCreateExpression("Test2")));
+ cmm.Statements.Add(new CodeMethodReturnStatement(new CodeMethodReferenceExpression(
+ new CodeVariableReferenceExpression("t"), "accessStringField")));
+ cd.Members.Add(cmm);
}
- cmm = new CodeMemberMethod();
- cmm.Name = "OutputDecimalEnumVal";
- cmm.Attributes = MemberAttributes.Public | MemberAttributes.Static;
- CodeParameterDeclarationExpression param = new CodeParameterDeclarationExpression(typeof(int), "i");
- cmm.Parameters.Add(param);
- CodeBinaryOperatorExpression eq = new CodeBinaryOperatorExpression(
- new CodeVariableReferenceExpression("i"), CodeBinaryOperatorType.ValueEquality,
- new CodePrimitiveExpression(3));
- CodeMethodReturnStatement truestmt = new CodeMethodReturnStatement(
- new CodeCastExpression(typeof(int),
- new CodeFieldReferenceExpression(new CodeTypeReferenceExpression("DecimalEnum"), "Num3")));
- CodeConditionStatement condstmt = new CodeConditionStatement(eq, truestmt);
- cmm.Statements.Add(condstmt);
-
- eq = new CodeBinaryOperatorExpression(new CodeVariableReferenceExpression("i"),
- CodeBinaryOperatorType.ValueEquality, new CodePrimitiveExpression(4));
- truestmt = new CodeMethodReturnStatement(new CodeCastExpression(typeof(int),
- new CodeFieldReferenceExpression(new CodeTypeReferenceExpression("DecimalEnum"), "Num4")));
- condstmt = new CodeConditionStatement(eq, truestmt);
- cmm.Statements.Add(condstmt);
- eq = new CodeBinaryOperatorExpression(new CodeVariableReferenceExpression("i"),
- CodeBinaryOperatorType.ValueEquality, new CodePrimitiveExpression(2));
- truestmt = new CodeMethodReturnStatement(new CodeCastExpression(typeof(int),
- new CodeFieldReferenceExpression(new CodeTypeReferenceExpression("DecimalEnum"), "Num2")));
- condstmt = new CodeConditionStatement(eq, truestmt);
- cmm.Statements.Add(condstmt);
-
- eq = new CodeBinaryOperatorExpression(new CodeVariableReferenceExpression("i"),
- CodeBinaryOperatorType.ValueEquality, new CodePrimitiveExpression(1));
- truestmt = new CodeMethodReturnStatement(new CodeCastExpression(typeof(int),
- new CodeFieldReferenceExpression(new CodeTypeReferenceExpression("DecimalEnum"), "Num1")));
- condstmt = new CodeConditionStatement(eq, truestmt);
- cmm.Statements.Add(condstmt);
-
- eq = new CodeBinaryOperatorExpression(new CodeVariableReferenceExpression("i"),
- CodeBinaryOperatorType.ValueEquality, new CodePrimitiveExpression(0));
- truestmt = new CodeMethodReturnStatement(new CodeCastExpression(typeof(int),
- new CodeFieldReferenceExpression(new CodeTypeReferenceExpression("DecimalEnum"), "Num0")));
- condstmt = new CodeConditionStatement(eq, truestmt);
- cmm.Statements.Add(condstmt);
-
- cmm.ReturnType = new CodeTypeReference("System.int32");
-
- cmm.Statements.Add(new CodeMethodReturnStatement(new CodeBinaryOperatorExpression(
- new CodeVariableReferenceExpression("i"), CodeBinaryOperatorType.Add, new CodePrimitiveExpression(10))));
- cd.Members.Add(cmm);
- }
- if (provider.Supports(GeneratorSupport.DeclareInterfaces))
- {
- cmm = new CodeMemberMethod();
- cmm.Name = "TestSingleInterface";
- cmm.ReturnType = new CodeTypeReference(typeof(int));
- cmm.Parameters.Add(new CodeParameterDeclarationExpression(typeof(int), "i"));
- cmm.Attributes = MemberAttributes.Public | MemberAttributes.Static;
- cmm.Statements.Add(new CodeVariableDeclarationStatement("TestSingleInterfaceImp", "t", new CodeObjectCreateExpression("TestSingleInterfaceImp")));
- CodeMethodInvokeExpression methodinvoke = new CodeMethodInvokeExpression(new CodeVariableReferenceExpression("t")
- , "InterfaceMethod");
- methodinvoke.Parameters.Add(new CodeVariableReferenceExpression("i"));
- cmm.Statements.Add(new CodeMethodReturnStatement(methodinvoke));
- cd.Members.Add(cmm);
+ // complex expressions
+ if (provider.Supports(GeneratorSupport.ComplexExpressions))
+ {
+ cmm = new CodeMemberMethod();
+ cmm.Name = "ComplexExpressions";
+ cmm.ReturnType = new CodeTypeReference(typeof(int));
+ cmm.Attributes = MemberAttributes.Final | MemberAttributes.Public;
+ cmm.Parameters.Add(new CodeParameterDeclarationExpression(new CodeTypeReference(typeof(int)), "i"));
+ cmm.Statements.Add(new CodeAssignStatement(new CodeVariableReferenceExpression("i"),
+ new CodeBinaryOperatorExpression(new CodeVariableReferenceExpression("i"), CodeBinaryOperatorType.Multiply,
+ new CodeBinaryOperatorExpression(new CodeVariableReferenceExpression("i"), CodeBinaryOperatorType.Add,
+ new CodePrimitiveExpression(3)))));
+ cmm.Statements.Add(new CodeMethodReturnStatement(new CodeVariableReferenceExpression("i")));
+ cd.Members.Add(cmm);
+ }
- class1 = new CodeTypeDeclaration("InterfaceA");
- class1.IsInterface = true;
- nspace.Types.Add(class1);
- cmm = new CodeMemberMethod();
- cmm.Attributes = MemberAttributes.Public;
- cmm.Name = "InterfaceMethod";
- cmm.ReturnType = new CodeTypeReference(typeof(int));
- cmm.Parameters.Add(new CodeParameterDeclarationExpression(typeof(int), "a"));
- class1.Members.Add(cmm);
+ if (provider.Supports(GeneratorSupport.DeclareEnums))
+ {
+ CodeTypeDeclaration ce = new CodeTypeDeclaration("DecimalEnum");
+ ce.IsEnum = true;
+ nspace.Types.Add(ce);
+
+ // things to enumerate
+ for (int k = 0; k < 5; k++)
+ {
+ CodeMemberField Field = new CodeMemberField("System.Int32", "Num" + (k).ToString());
+ Field.InitExpression = new CodePrimitiveExpression(k);
+ ce.Members.Add(Field);
+ }
+ cmm = new CodeMemberMethod();
+ cmm.Name = "OutputDecimalEnumVal";
+ cmm.Attributes = MemberAttributes.Public | MemberAttributes.Static;
+ CodeParameterDeclarationExpression param = new CodeParameterDeclarationExpression(typeof(int), "i");
+ cmm.Parameters.Add(param);
+ CodeBinaryOperatorExpression eq = new CodeBinaryOperatorExpression(
+ new CodeVariableReferenceExpression("i"), CodeBinaryOperatorType.ValueEquality,
+ new CodePrimitiveExpression(3));
+ CodeMethodReturnStatement truestmt = new CodeMethodReturnStatement(
+ new CodeCastExpression(typeof(int),
+ new CodeFieldReferenceExpression(new CodeTypeReferenceExpression("DecimalEnum"), "Num3")));
+ CodeConditionStatement condstmt = new CodeConditionStatement(eq, truestmt);
+ cmm.Statements.Add(condstmt);
+
+ eq = new CodeBinaryOperatorExpression(new CodeVariableReferenceExpression("i"),
+ CodeBinaryOperatorType.ValueEquality, new CodePrimitiveExpression(4));
+ truestmt = new CodeMethodReturnStatement(new CodeCastExpression(typeof(int),
+ new CodeFieldReferenceExpression(new CodeTypeReferenceExpression("DecimalEnum"), "Num4")));
+ condstmt = new CodeConditionStatement(eq, truestmt);
+ cmm.Statements.Add(condstmt);
+ eq = new CodeBinaryOperatorExpression(new CodeVariableReferenceExpression("i"),
+ CodeBinaryOperatorType.ValueEquality, new CodePrimitiveExpression(2));
+ truestmt = new CodeMethodReturnStatement(new CodeCastExpression(typeof(int),
+ new CodeFieldReferenceExpression(new CodeTypeReferenceExpression("DecimalEnum"), "Num2")));
+ condstmt = new CodeConditionStatement(eq, truestmt);
+ cmm.Statements.Add(condstmt);
+
+ eq = new CodeBinaryOperatorExpression(new CodeVariableReferenceExpression("i"),
+ CodeBinaryOperatorType.ValueEquality, new CodePrimitiveExpression(1));
+ truestmt = new CodeMethodReturnStatement(new CodeCastExpression(typeof(int),
+ new CodeFieldReferenceExpression(new CodeTypeReferenceExpression("DecimalEnum"), "Num1")));
+ condstmt = new CodeConditionStatement(eq, truestmt);
+ cmm.Statements.Add(condstmt);
+
+ eq = new CodeBinaryOperatorExpression(new CodeVariableReferenceExpression("i"),
+ CodeBinaryOperatorType.ValueEquality, new CodePrimitiveExpression(0));
+ truestmt = new CodeMethodReturnStatement(new CodeCastExpression(typeof(int),
+ new CodeFieldReferenceExpression(new CodeTypeReferenceExpression("DecimalEnum"), "Num0")));
+ condstmt = new CodeConditionStatement(eq, truestmt);
+ cmm.Statements.Add(condstmt);
+
+ cmm.ReturnType = new CodeTypeReference("System.int32");
- if (provider.Supports(GeneratorSupport.MultipleInterfaceMembers))
+ cmm.Statements.Add(new CodeMethodReturnStatement(new CodeBinaryOperatorExpression(
+ new CodeVariableReferenceExpression("i"), CodeBinaryOperatorType.Add, new CodePrimitiveExpression(10))));
+ cd.Members.Add(cmm);
+ }
+
+ if (provider.Supports(GeneratorSupport.DeclareInterfaces))
{
- CodeTypeDeclaration classDecl = new CodeTypeDeclaration("InterfaceB");
- classDecl.IsInterface = true;
- nspace.Types.Add(classDecl);
cmm = new CodeMemberMethod();
- cmm.Name = "InterfaceMethod";
+ cmm.Name = "TestSingleInterface";
+ cmm.ReturnType = new CodeTypeReference(typeof(int));
+ cmm.Parameters.Add(new CodeParameterDeclarationExpression(typeof(int), "i"));
+ cmm.Attributes = MemberAttributes.Public | MemberAttributes.Static;
+ cmm.Statements.Add(new CodeVariableDeclarationStatement("TestSingleInterfaceImp", "t", new CodeObjectCreateExpression("TestSingleInterfaceImp")));
+ CodeMethodInvokeExpression methodinvoke = new CodeMethodInvokeExpression(new CodeVariableReferenceExpression("t")
+ , "InterfaceMethod");
+ methodinvoke.Parameters.Add(new CodeVariableReferenceExpression("i"));
+ cmm.Statements.Add(new CodeMethodReturnStatement(methodinvoke));
+ cd.Members.Add(cmm);
+
+ class1 = new CodeTypeDeclaration("InterfaceA");
+ class1.IsInterface = true;
+ nspace.Types.Add(class1);
+ cmm = new CodeMemberMethod();
cmm.Attributes = MemberAttributes.Public;
+ cmm.Name = "InterfaceMethod";
cmm.ReturnType = new CodeTypeReference(typeof(int));
cmm.Parameters.Add(new CodeParameterDeclarationExpression(typeof(int), "a"));
- classDecl.Members.Add(cmm);
-
- CodeTypeDeclaration class2 = new CodeTypeDeclaration("TestMultipleInterfaceImp");
- class2.BaseTypes.Add(new CodeTypeReference("System.Object"));
- class2.BaseTypes.Add(new CodeTypeReference("InterfaceB"));
- class2.BaseTypes.Add(new CodeTypeReference("InterfaceA"));
- class2.IsClass = true;
- nspace.Types.Add(class2);
+ class1.Members.Add(cmm);
+
+ if (provider.Supports(GeneratorSupport.MultipleInterfaceMembers))
+ {
+ CodeTypeDeclaration classDecl = new CodeTypeDeclaration("InterfaceB");
+ classDecl.IsInterface = true;
+ nspace.Types.Add(classDecl);
+ cmm = new CodeMemberMethod();
+ cmm.Name = "InterfaceMethod";
+ cmm.Attributes = MemberAttributes.Public;
+ cmm.ReturnType = new CodeTypeReference(typeof(int));
+ cmm.Parameters.Add(new CodeParameterDeclarationExpression(typeof(int), "a"));
+ classDecl.Members.Add(cmm);
+
+ CodeTypeDeclaration class2 = new CodeTypeDeclaration("TestMultipleInterfaceImp");
+ class2.BaseTypes.Add(new CodeTypeReference("System.Object"));
+ class2.BaseTypes.Add(new CodeTypeReference("InterfaceB"));
+ class2.BaseTypes.Add(new CodeTypeReference("InterfaceA"));
+ class2.IsClass = true;
+ nspace.Types.Add(class2);
+ cmm = new CodeMemberMethod();
+ cmm.ImplementationTypes.Add(new CodeTypeReference("InterfaceA"));
+ cmm.ImplementationTypes.Add(new CodeTypeReference("InterfaceB"));
+ cmm.Name = "InterfaceMethod";
+ cmm.ReturnType = new CodeTypeReference(typeof(int));
+ cmm.Parameters.Add(new CodeParameterDeclarationExpression(typeof(int), "a"));
+ cmm.Attributes = MemberAttributes.Public | MemberAttributes.Final;
+ cmm.Statements.Add(new CodeMethodReturnStatement(new CodeVariableReferenceExpression("a")));
+ class2.Members.Add(cmm);
+
+ cmm = new CodeMemberMethod();
+ cmm.Name = "TestMultipleInterfaces";
+ cmm.ReturnType = new CodeTypeReference(typeof(int));
+ cmm.Parameters.Add(new CodeParameterDeclarationExpression(typeof(int), "i"));
+ cmm.Attributes = MemberAttributes.Public | MemberAttributes.Static;
+ cmm.Statements.Add(new CodeVariableDeclarationStatement("TestMultipleInterfaceImp", "t", new CodeObjectCreateExpression("TestMultipleInterfaceImp")));
+ cmm.Statements.Add(new CodeVariableDeclarationStatement("InterfaceA", "interfaceAobject", new CodeCastExpression("InterfaceA",
+ new CodeVariableReferenceExpression("t"))));
+ cmm.Statements.Add(new CodeVariableDeclarationStatement("InterfaceB", "interfaceBobject", new CodeCastExpression("InterfaceB",
+ new CodeVariableReferenceExpression("t"))));
+ methodinvoke = new CodeMethodInvokeExpression(new CodeVariableReferenceExpression("interfaceAobject")
+ , "InterfaceMethod");
+ methodinvoke.Parameters.Add(new CodeVariableReferenceExpression("i"));
+ CodeMethodInvokeExpression methodinvoke2 = new CodeMethodInvokeExpression(new CodeVariableReferenceExpression("interfaceBobject")
+ , "InterfaceMethod");
+ methodinvoke2.Parameters.Add(new CodeVariableReferenceExpression("i"));
+ cmm.Statements.Add(new CodeMethodReturnStatement(new CodeBinaryOperatorExpression(
+ methodinvoke,
+ CodeBinaryOperatorType.Subtract, methodinvoke2)));
+ cd.Members.Add(cmm);
+ }
+
+ class1 = new CodeTypeDeclaration("TestSingleInterfaceImp");
+ class1.BaseTypes.Add(new CodeTypeReference("System.Object"));
+ class1.BaseTypes.Add(new CodeTypeReference("InterfaceA"));
+ class1.IsClass = true;
+ nspace.Types.Add(class1);
cmm = new CodeMemberMethod();
cmm.ImplementationTypes.Add(new CodeTypeReference("InterfaceA"));
- cmm.ImplementationTypes.Add(new CodeTypeReference("InterfaceB"));
cmm.Name = "InterfaceMethod";
cmm.ReturnType = new CodeTypeReference(typeof(int));
cmm.Parameters.Add(new CodeParameterDeclarationExpression(typeof(int), "a"));
- cmm.Attributes = MemberAttributes.Public | MemberAttributes.Final;
+ cmm.Attributes = MemberAttributes.Public;
cmm.Statements.Add(new CodeMethodReturnStatement(new CodeVariableReferenceExpression("a")));
- class2.Members.Add(cmm);
+ class1.Members.Add(cmm);
+ }
+ if (provider.Supports(GeneratorSupport.DeclareValueTypes))
+ {
+ CodeTypeDeclaration structA = new CodeTypeDeclaration("structA");
+ structA.IsStruct = true;
+
+ CodeTypeDeclaration structB = new CodeTypeDeclaration("structB");
+ structB.Attributes = MemberAttributes.Public;
+ structB.IsStruct = true;
+
+ CodeMemberField firstInt = new CodeMemberField(typeof(int), "int1");
+ firstInt.Attributes = MemberAttributes.Public;
+ structB.Members.Add(firstInt);
+
+ CodeMemberField innerStruct = new CodeMemberField("structB", "innerStruct");
+ innerStruct.Attributes = MemberAttributes.Public;
+
+ structA.Members.Add(structB);
+ structA.Members.Add(innerStruct);
+ nspace.Types.Add(structA);
+
+ CodeMemberMethod nestedStructMethod = new CodeMemberMethod();
+ nestedStructMethod.Name = "NestedStructMethod";
+ nestedStructMethod.ReturnType = new CodeTypeReference(typeof(int));
+ nestedStructMethod.Attributes = MemberAttributes.Public | MemberAttributes.Static;
+ CodeVariableDeclarationStatement varStructA = new CodeVariableDeclarationStatement("structA", "varStructA");
+ nestedStructMethod.Statements.Add(varStructA);
+ nestedStructMethod.Statements.Add
+ (
+ new CodeAssignStatement
+ (
+ /* Expression1 */ new CodeFieldReferenceExpression(new CodeFieldReferenceExpression(new CodeVariableReferenceExpression("varStructA"), "innerStruct"), "int1"),
+ /* Expression1 */ new CodePrimitiveExpression(3)
+ )
+ );
+ nestedStructMethod.Statements.Add(new CodeMethodReturnStatement(new CodeFieldReferenceExpression(new CodeFieldReferenceExpression(new CodeVariableReferenceExpression("varStructA"), "innerStruct"), "int1")));
+ cd.Members.Add(nestedStructMethod);
+ }
+ if (provider.Supports(GeneratorSupport.EntryPointMethod))
+ {
+ CodeEntryPointMethod cep = new CodeEntryPointMethod();
+ cd.Members.Add(cep);
+ }
+ // goto statements
+ if (provider.Supports(GeneratorSupport.GotoStatements))
+ {
cmm = new CodeMemberMethod();
- cmm.Name = "TestMultipleInterfaces";
+ cmm.Name = "GoToMethod";
cmm.ReturnType = new CodeTypeReference(typeof(int));
+ cmm.Attributes = MemberAttributes.Public | MemberAttributes.Final;
+ CodeParameterDeclarationExpression param = new CodeParameterDeclarationExpression(typeof(int), "i");
+ cmm.Parameters.Add(param);
+ CodeConditionStatement condstmt = new CodeConditionStatement(new CodeBinaryOperatorExpression(
+ new CodeVariableReferenceExpression("i"), CodeBinaryOperatorType.LessThan, new CodePrimitiveExpression(1)),
+ new CodeGotoStatement("comehere"));
+ cmm.Statements.Add(condstmt);
+ cmm.Statements.Add(new CodeMethodReturnStatement(new CodePrimitiveExpression(6)));
+ cmm.Statements.Add(new CodeLabeledStatement("comehere",
+ new CodeMethodReturnStatement(new CodePrimitiveExpression(7))));
+ cd.Members.Add(cmm);
+ }
+ if (provider.Supports(GeneratorSupport.NestedTypes))
+ {
+ cmm = new CodeMemberMethod();
+ cmm.Name = "CallingPublicNestedScenario";
cmm.Parameters.Add(new CodeParameterDeclarationExpression(typeof(int), "i"));
+ cmm.ReturnType = new CodeTypeReference(typeof(int));
cmm.Attributes = MemberAttributes.Public | MemberAttributes.Static;
- cmm.Statements.Add(new CodeVariableDeclarationStatement("TestMultipleInterfaceImp", "t", new CodeObjectCreateExpression("TestMultipleInterfaceImp")));
- cmm.Statements.Add(new CodeVariableDeclarationStatement("InterfaceA", "interfaceAobject", new CodeCastExpression("InterfaceA",
- new CodeVariableReferenceExpression("t"))));
- cmm.Statements.Add(new CodeVariableDeclarationStatement("InterfaceB", "interfaceBobject", new CodeCastExpression("InterfaceB",
- new CodeVariableReferenceExpression("t"))));
- methodinvoke = new CodeMethodInvokeExpression(new CodeVariableReferenceExpression("interfaceAobject")
- , "InterfaceMethod");
- methodinvoke.Parameters.Add(new CodeVariableReferenceExpression("i"));
- CodeMethodInvokeExpression methodinvoke2 = new CodeMethodInvokeExpression(new CodeVariableReferenceExpression("interfaceBobject")
- , "InterfaceMethod");
- methodinvoke2.Parameters.Add(new CodeVariableReferenceExpression("i"));
- cmm.Statements.Add(new CodeMethodReturnStatement(new CodeBinaryOperatorExpression(
- methodinvoke,
- CodeBinaryOperatorType.Subtract, methodinvoke2)));
+ cmm.Statements.Add(new CodeVariableDeclarationStatement(new CodeTypeReference
+ ("PublicNestedClassA+PublicNestedClassB2+PublicNestedClassC"), "t",
+ new CodeObjectCreateExpression(new CodeTypeReference
+ ("PublicNestedClassA+PublicNestedClassB2+PublicNestedClassC"))));
+ cmm.Statements.Add(new CodeMethodReturnStatement(new CodeMethodInvokeExpression(new CodeVariableReferenceExpression("t"),
+ "publicNestedClassesMethod",
+ new CodeVariableReferenceExpression("i"))));
cd.Members.Add(cmm);
- }
-
- class1 = new CodeTypeDeclaration("TestSingleInterfaceImp");
- class1.BaseTypes.Add(new CodeTypeReference("System.Object"));
- class1.BaseTypes.Add(new CodeTypeReference("InterfaceA"));
- class1.IsClass = true;
- nspace.Types.Add(class1);
- cmm = new CodeMemberMethod();
- cmm.ImplementationTypes.Add(new CodeTypeReference("InterfaceA"));
- cmm.Name = "InterfaceMethod";
- cmm.ReturnType = new CodeTypeReference(typeof(int));
- cmm.Parameters.Add(new CodeParameterDeclarationExpression(typeof(int), "a"));
- cmm.Attributes = MemberAttributes.Public;
- cmm.Statements.Add(new CodeMethodReturnStatement(new CodeVariableReferenceExpression("a")));
- class1.Members.Add(cmm);
- }
-
- if (provider.Supports(GeneratorSupport.DeclareValueTypes))
- {
- CodeTypeDeclaration structA = new CodeTypeDeclaration("structA");
- structA.IsStruct = true;
-
- CodeTypeDeclaration structB = new CodeTypeDeclaration("structB");
- structB.Attributes = MemberAttributes.Public;
- structB.IsStruct = true;
-
- CodeMemberField firstInt = new CodeMemberField(typeof(int), "int1");
- firstInt.Attributes = MemberAttributes.Public;
- structB.Members.Add(firstInt);
-
- CodeMemberField innerStruct = new CodeMemberField("structB", "innerStruct");
- innerStruct.Attributes = MemberAttributes.Public;
-
- structA.Members.Add(structB);
- structA.Members.Add(innerStruct);
- nspace.Types.Add(structA);
-
- CodeMemberMethod nestedStructMethod = new CodeMemberMethod();
- nestedStructMethod.Name = "NestedStructMethod";
- nestedStructMethod.ReturnType = new CodeTypeReference(typeof(int));
- nestedStructMethod.Attributes = MemberAttributes.Public | MemberAttributes.Static;
- CodeVariableDeclarationStatement varStructA = new CodeVariableDeclarationStatement("structA", "varStructA");
- nestedStructMethod.Statements.Add(varStructA);
- nestedStructMethod.Statements.Add
- (
- new CodeAssignStatement
- (
- /* Expression1 */ new CodeFieldReferenceExpression(new CodeFieldReferenceExpression(new CodeVariableReferenceExpression("varStructA"), "innerStruct"), "int1"),
- /* Expression1 */ new CodePrimitiveExpression(3)
- )
- );
- nestedStructMethod.Statements.Add(new CodeMethodReturnStatement(new CodeFieldReferenceExpression(new CodeFieldReferenceExpression(new CodeVariableReferenceExpression("varStructA"), "innerStruct"), "int1")));
- cd.Members.Add(nestedStructMethod);
- }
- if (provider.Supports(GeneratorSupport.EntryPointMethod))
- {
- CodeEntryPointMethod cep = new CodeEntryPointMethod();
- cd.Members.Add(cep);
- }
- // goto statements
- if (provider.Supports(GeneratorSupport.GotoStatements))
- {
- cmm = new CodeMemberMethod();
- cmm.Name = "GoToMethod";
- cmm.ReturnType = new CodeTypeReference(typeof(int));
- cmm.Attributes = MemberAttributes.Public | MemberAttributes.Final;
- CodeParameterDeclarationExpression param = new CodeParameterDeclarationExpression(typeof(int), "i");
- cmm.Parameters.Add(param);
- CodeConditionStatement condstmt = new CodeConditionStatement(new CodeBinaryOperatorExpression(
- new CodeVariableReferenceExpression("i"), CodeBinaryOperatorType.LessThan, new CodePrimitiveExpression(1)),
- new CodeGotoStatement("comehere"));
- cmm.Statements.Add(condstmt);
- cmm.Statements.Add(new CodeMethodReturnStatement(new CodePrimitiveExpression(6)));
- cmm.Statements.Add(new CodeLabeledStatement("comehere",
- new CodeMethodReturnStatement(new CodePrimitiveExpression(7))));
- cd.Members.Add(cmm);
- }
- if (provider.Supports(GeneratorSupport.NestedTypes))
- {
- cmm = new CodeMemberMethod();
- cmm.Name = "CallingPublicNestedScenario";
- cmm.Parameters.Add(new CodeParameterDeclarationExpression(typeof(int), "i"));
- cmm.ReturnType = new CodeTypeReference(typeof(int));
- cmm.Attributes = MemberAttributes.Public | MemberAttributes.Static;
- cmm.Statements.Add(new CodeVariableDeclarationStatement(new CodeTypeReference
- ("PublicNestedClassA+PublicNestedClassB2+PublicNestedClassC"), "t",
- new CodeObjectCreateExpression(new CodeTypeReference
- ("PublicNestedClassA+PublicNestedClassB2+PublicNestedClassC"))));
- cmm.Statements.Add(new CodeMethodReturnStatement(new CodeMethodInvokeExpression(new CodeVariableReferenceExpression("t"),
- "publicNestedClassesMethod",
- new CodeVariableReferenceExpression("i"))));
- cd.Members.Add(cmm);
-
- class1 = new CodeTypeDeclaration("PublicNestedClassA");
- class1.IsClass = true;
- nspace.Types.Add(class1);
- CodeTypeDeclaration nestedClass = new CodeTypeDeclaration("PublicNestedClassB1");
- nestedClass.IsClass = true;
- nestedClass.TypeAttributes = TypeAttributes.NestedPublic;
- class1.Members.Add(nestedClass);
- nestedClass = new CodeTypeDeclaration("PublicNestedClassB2");
- nestedClass.TypeAttributes = TypeAttributes.NestedPublic;
- nestedClass.IsClass = true;
- class1.Members.Add(nestedClass);
- CodeTypeDeclaration innerNestedClass = new CodeTypeDeclaration("PublicNestedClassC");
- innerNestedClass.TypeAttributes = TypeAttributes.NestedPublic;
- innerNestedClass.IsClass = true;
- nestedClass.Members.Add(innerNestedClass);
- cmm = new CodeMemberMethod();
- cmm.Name = "publicNestedClassesMethod";
- cmm.ReturnType = new CodeTypeReference(typeof(int));
- cmm.Parameters.Add(new CodeParameterDeclarationExpression(typeof(int), "a"));
- cmm.Attributes = MemberAttributes.Public | MemberAttributes.Final;
- cmm.Statements.Add(new CodeMethodReturnStatement(new CodeVariableReferenceExpression("a")));
- innerNestedClass.Members.Add(cmm);
- }
- // Parameter Attributes
- if (provider.Supports(GeneratorSupport.ParameterAttributes))
- {
- CodeMemberMethod method1 = new CodeMemberMethod();
- method1.Name = "MyMethod";
- method1.Attributes = MemberAttributes.Public | MemberAttributes.Final;
- CodeParameterDeclarationExpression param1 = new CodeParameterDeclarationExpression(typeof(string), "blah");
- param1.CustomAttributes.Add(
- new CodeAttributeDeclaration(
- "System.Xml.Serialization.XmlElementAttribute",
- new CodeAttributeArgument(
- "Form",
- new CodeFieldReferenceExpression(new CodeTypeReferenceExpression("System.Xml.Schema.XmlSchemaForm"), "Unqualified")),
- new CodeAttributeArgument(
- "IsNullable",
- new CodePrimitiveExpression(false))));
- method1.Parameters.Add(param1);
- cd.Members.Add(method1);
- }
- // public static members
- if (provider.Supports(GeneratorSupport.PublicStaticMembers))
- {
- cmm = new CodeMemberMethod();
- cmm.Name = "PublicStaticMethod";
- cmm.ReturnType = new CodeTypeReference(typeof(int));
- cmm.Attributes = MemberAttributes.Public | MemberAttributes.Static;
- cmm.Statements.Add(new CodeMethodReturnStatement(new CodePrimitiveExpression(16)));
- cd.Members.Add(cmm);
- }
- // reference parameters
- if (provider.Supports(GeneratorSupport.ReferenceParameters))
- {
- cmm = new CodeMemberMethod();
- cmm.Name = "Work";
- cmm.ReturnType = new CodeTypeReference("System.void");
- cmm.Attributes = MemberAttributes.Static;
- // add parameter with ref direction
- CodeParameterDeclarationExpression param = new CodeParameterDeclarationExpression(typeof(int), "i");
- param.Direction = FieldDirection.Ref;
- cmm.Parameters.Add(param);
- // add parameter with out direction
- param = new CodeParameterDeclarationExpression(typeof(int), "j");
- param.Direction = FieldDirection.Out;
- cmm.Parameters.Add(param);
- cmm.Statements.Add(new CodeAssignStatement(new CodeArgumentReferenceExpression("i"),
- new CodeBinaryOperatorExpression(new CodeArgumentReferenceExpression("i"),
- CodeBinaryOperatorType.Add, new CodePrimitiveExpression(4))));
- cmm.Statements.Add(new CodeAssignStatement(new CodeArgumentReferenceExpression("j"),
- new CodePrimitiveExpression(5)));
- cd.Members.Add(cmm);
-
- cmm = new CodeMemberMethod();
- cmm.Name = "CallingWork";
- cmm.Attributes = MemberAttributes.Public | MemberAttributes.Static;
- CodeParameterDeclarationExpression parames = new CodeParameterDeclarationExpression(typeof(int), "a");
- cmm.Parameters.Add(parames);
- cmm.ReturnType = new CodeTypeReference("System.int32");
- cmm.Statements.Add(new CodeAssignStatement(new CodeVariableReferenceExpression("a"),
- new CodePrimitiveExpression(10)));
- cmm.Statements.Add(new CodeVariableDeclarationStatement(typeof(int), "b"));
- // invoke the method called "work"
- CodeMethodInvokeExpression methodinvoked = new CodeMethodInvokeExpression(new CodeMethodReferenceExpression
- (new CodeTypeReferenceExpression("TEST"), "Work"));
- // add parameter with ref direction
- CodeDirectionExpression parameter = new CodeDirectionExpression(FieldDirection.Ref,
- new CodeVariableReferenceExpression("a"));
- methodinvoked.Parameters.Add(parameter);
- // add parameter with out direction
- parameter = new CodeDirectionExpression(FieldDirection.Out, new CodeVariableReferenceExpression("b"));
- methodinvoked.Parameters.Add(parameter);
- cmm.Statements.Add(methodinvoked);
- cmm.Statements.Add(new CodeMethodReturnStatement(new CodeBinaryOperatorExpression
- (new CodeVariableReferenceExpression("a"), CodeBinaryOperatorType.Add, new CodeVariableReferenceExpression("b"))));
- cd.Members.Add(cmm);
- }
- if (provider.Supports(GeneratorSupport.ReturnTypeAttributes))
- {
- CodeMemberMethod function1 = new CodeMemberMethod();
- function1.Name = "MyFunction";
- function1.ReturnType = new CodeTypeReference(typeof(string));
- function1.Attributes = MemberAttributes.Public | MemberAttributes.Final;
- function1.ReturnTypeCustomAttributes.Add(new
- CodeAttributeDeclaration("System.Xml.Serialization.XmlIgnoreAttribute"));
- function1.ReturnTypeCustomAttributes.Add(new CodeAttributeDeclaration("System.Xml.Serialization.XmlRootAttribute", new
- CodeAttributeArgument("Namespace", new CodePrimitiveExpression("Namespace Value")), new
- CodeAttributeArgument("ElementName", new CodePrimitiveExpression("Root, hehehe"))));
- function1.Statements.Add(new CodeMethodReturnStatement(new CodePrimitiveExpression("Return")));
- cd.Members.Add(function1);
- }
- if (provider.Supports(GeneratorSupport.StaticConstructors))
- {
- cmm = new CodeMemberMethod();
- cmm.Name = "TestStaticConstructor";
- cmm.Attributes = MemberAttributes.Public | MemberAttributes.Static;
- cmm.ReturnType = new CodeTypeReference(typeof(int));
- CodeParameterDeclarationExpression param = new CodeParameterDeclarationExpression(typeof(int), "a");
- cmm.Parameters.Add(param);
- // utilize constructor
- cmm.Statements.Add(new CodeVariableDeclarationStatement("Test4", "t", new CodeObjectCreateExpression("Test4")));
- // set then get number
- cmm.Statements.Add(new CodeAssignStatement(new CodePropertyReferenceExpression(new CodeVariableReferenceExpression("t"), "i")
- , new CodeVariableReferenceExpression("a")));
- cmm.Statements.Add(new CodeMethodReturnStatement(new CodeMethodReferenceExpression(
- new CodeVariableReferenceExpression("t"), "i")));
- cd.Members.Add(cmm);
-
- class1 = new CodeTypeDeclaration();
- class1.Name = "Test4";
- class1.IsClass = true;
- nspace.Types.Add(class1);
-
- class1.Members.Add(new CodeMemberField(new CodeTypeReference(typeof(int)), "number"));
- CodeMemberProperty prop = new CodeMemberProperty();
- prop.Name = "i";
- prop.Attributes = MemberAttributes.Public | MemberAttributes.Final;
- prop.Type = new CodeTypeReference(typeof(int));
- prop.GetStatements.Add(new CodeMethodReturnStatement(new CodeVariableReferenceExpression("number")));
- prop.SetStatements.Add(new CodeAssignStatement(new CodeVariableReferenceExpression("number"),
- new CodePropertySetValueReferenceExpression()));
- class1.Members.Add(prop);
- CodeTypeConstructor ctc = new CodeTypeConstructor();
- class1.Members.Add(ctc);
- }
- if (provider.Supports(GeneratorSupport.TryCatchStatements))
- {
- cmm = new CodeMemberMethod();
- cmm.Name = "TryCatchMethod";
- cmm.ReturnType = new CodeTypeReference(typeof(int));
- cmm.Attributes = MemberAttributes.Public | MemberAttributes.Static;
- CodeParameterDeclarationExpression param = new CodeParameterDeclarationExpression(typeof(int), "a");
- cmm.Parameters.Add(param);
-
- CodeTryCatchFinallyStatement tcfstmt = new CodeTryCatchFinallyStatement();
- tcfstmt.FinallyStatements.Add(new CodeAssignStatement(new CodeVariableReferenceExpression("a"), new
- CodeBinaryOperatorExpression(new CodeVariableReferenceExpression("a"), CodeBinaryOperatorType.Add,
- new CodePrimitiveExpression(5))));
- cmm.Statements.Add(tcfstmt);
- cmm.Statements.Add(new CodeMethodReturnStatement(new CodeVariableReferenceExpression("a")));
- cd.Members.Add(cmm);
- }
- if (provider.Supports(GeneratorSupport.DeclareEvents))
- {
- CodeNamespace ns = new CodeNamespace();
- ns.Name = "MyNamespace";
- ns.Imports.Add(new CodeNamespaceImport("System"));
- ns.Imports.Add(new CodeNamespaceImport("System.Drawing"));
- ns.Imports.Add(new CodeNamespaceImport("System.Windows.Forms"));
- ns.Imports.Add(new CodeNamespaceImport("System.ComponentModel"));
- cu.Namespaces.Add(ns);
- class1 = new CodeTypeDeclaration("Test");
- class1.IsClass = true;
- class1.BaseTypes.Add(new CodeTypeReference("Form"));
- ns.Types.Add(class1);
- CodeMemberField mfield = new CodeMemberField(new CodeTypeReference("Button"), "b");
- mfield.InitExpression = new CodeObjectCreateExpression(new CodeTypeReference("Button"));
- class1.Members.Add(mfield);
+ class1 = new CodeTypeDeclaration("PublicNestedClassA");
+ class1.IsClass = true;
+ nspace.Types.Add(class1);
+ CodeTypeDeclaration nestedClass = new CodeTypeDeclaration("PublicNestedClassB1");
+ nestedClass.IsClass = true;
+ nestedClass.TypeAttributes = TypeAttributes.NestedPublic;
+ class1.Members.Add(nestedClass);
+ nestedClass = new CodeTypeDeclaration("PublicNestedClassB2");
+ nestedClass.TypeAttributes = TypeAttributes.NestedPublic;
+ nestedClass.IsClass = true;
+ class1.Members.Add(nestedClass);
+ CodeTypeDeclaration innerNestedClass = new CodeTypeDeclaration("PublicNestedClassC");
+ innerNestedClass.TypeAttributes = TypeAttributes.NestedPublic;
+ innerNestedClass.IsClass = true;
+ nestedClass.Members.Add(innerNestedClass);
+ cmm = new CodeMemberMethod();
+ cmm.Name = "publicNestedClassesMethod";
+ cmm.ReturnType = new CodeTypeReference(typeof(int));
+ cmm.Parameters.Add(new CodeParameterDeclarationExpression(typeof(int), "a"));
+ cmm.Attributes = MemberAttributes.Public | MemberAttributes.Final;
+ cmm.Statements.Add(new CodeMethodReturnStatement(new CodeVariableReferenceExpression("a")));
+ innerNestedClass.Members.Add(cmm);
+ }
+ // Parameter Attributes
+ if (provider.Supports(GeneratorSupport.ParameterAttributes))
+ {
+ CodeMemberMethod method1 = new CodeMemberMethod();
+ method1.Name = "MyMethod";
+ method1.Attributes = MemberAttributes.Public | MemberAttributes.Final;
+ CodeParameterDeclarationExpression param1 = new CodeParameterDeclarationExpression(typeof(string), "blah");
+ param1.CustomAttributes.Add(
+ new CodeAttributeDeclaration(
+ "System.Xml.Serialization.XmlElementAttribute",
+ new CodeAttributeArgument(
+ "Form",
+ new CodeFieldReferenceExpression(new CodeTypeReferenceExpression("System.Xml.Schema.XmlSchemaForm"), "Unqualified")),
+ new CodeAttributeArgument(
+ "IsNullable",
+ new CodePrimitiveExpression(false))));
+ method1.Parameters.Add(param1);
+ cd.Members.Add(method1);
+ }
+ // public static members
+ if (provider.Supports(GeneratorSupport.PublicStaticMembers))
+ {
+ cmm = new CodeMemberMethod();
+ cmm.Name = "PublicStaticMethod";
+ cmm.ReturnType = new CodeTypeReference(typeof(int));
+ cmm.Attributes = MemberAttributes.Public | MemberAttributes.Static;
+ cmm.Statements.Add(new CodeMethodReturnStatement(new CodePrimitiveExpression(16)));
+ cd.Members.Add(cmm);
+ }
+ // reference parameters
+ if (provider.Supports(GeneratorSupport.ReferenceParameters))
+ {
+ cmm = new CodeMemberMethod();
+ cmm.Name = "Work";
+ cmm.ReturnType = new CodeTypeReference("System.void");
+ cmm.Attributes = MemberAttributes.Static;
+ // add parameter with ref direction
+ CodeParameterDeclarationExpression param = new CodeParameterDeclarationExpression(typeof(int), "i");
+ param.Direction = FieldDirection.Ref;
+ cmm.Parameters.Add(param);
+ // add parameter with out direction
+ param = new CodeParameterDeclarationExpression(typeof(int), "j");
+ param.Direction = FieldDirection.Out;
+ cmm.Parameters.Add(param);
+ cmm.Statements.Add(new CodeAssignStatement(new CodeArgumentReferenceExpression("i"),
+ new CodeBinaryOperatorExpression(new CodeArgumentReferenceExpression("i"),
+ CodeBinaryOperatorType.Add, new CodePrimitiveExpression(4))));
+ cmm.Statements.Add(new CodeAssignStatement(new CodeArgumentReferenceExpression("j"),
+ new CodePrimitiveExpression(5)));
+ cd.Members.Add(cmm);
- CodeConstructor ctor = new CodeConstructor();
- ctor.Attributes = MemberAttributes.Public;
- ctor.Statements.Add(new CodeAssignStatement(new CodeFieldReferenceExpression(new CodeThisReferenceExpression(),
- "Size"), new CodeObjectCreateExpression(new CodeTypeReference("Size"),
- new CodePrimitiveExpression(600), new CodePrimitiveExpression(600))));
- ctor.Statements.Add(new CodeAssignStatement(new CodeFieldReferenceExpression(new CodeTypeReferenceExpression("b"),
- "Text"), new CodePrimitiveExpression("Test")));
- ctor.Statements.Add(new CodeAssignStatement(new CodeFieldReferenceExpression(new CodeTypeReferenceExpression("b"),
- "TabIndex"), new CodePrimitiveExpression(0)));
- ctor.Statements.Add(new CodeAssignStatement(new CodeFieldReferenceExpression(new CodeTypeReferenceExpression("b"),
- "Location"), new CodeObjectCreateExpression(new CodeTypeReference("Point"),
- new CodePrimitiveExpression(400), new CodePrimitiveExpression(525))));
- ctor.Statements.Add(new CodeAttachEventStatement(new CodeEventReferenceExpression(new
- CodeThisReferenceExpression(), "MyEvent"), new CodeDelegateCreateExpression(new CodeTypeReference("EventHandler")
- , new CodeThisReferenceExpression(), "b_Click")));
- class1.Members.Add(ctor);
+ cmm = new CodeMemberMethod();
+ cmm.Name = "CallingWork";
+ cmm.Attributes = MemberAttributes.Public | MemberAttributes.Static;
+ CodeParameterDeclarationExpression parames = new CodeParameterDeclarationExpression(typeof(int), "a");
+ cmm.Parameters.Add(parames);
+ cmm.ReturnType = new CodeTypeReference("System.int32");
+ cmm.Statements.Add(new CodeAssignStatement(new CodeVariableReferenceExpression("a"),
+ new CodePrimitiveExpression(10)));
+ cmm.Statements.Add(new CodeVariableDeclarationStatement(typeof(int), "b"));
+ // invoke the method called "work"
+ CodeMethodInvokeExpression methodinvoked = new CodeMethodInvokeExpression(new CodeMethodReferenceExpression
+ (new CodeTypeReferenceExpression("TEST"), "Work"));
+ // add parameter with ref direction
+ CodeDirectionExpression parameter = new CodeDirectionExpression(FieldDirection.Ref,
+ new CodeVariableReferenceExpression("a"));
+ methodinvoked.Parameters.Add(parameter);
+ // add parameter with out direction
+ parameter = new CodeDirectionExpression(FieldDirection.Out, new CodeVariableReferenceExpression("b"));
+ methodinvoked.Parameters.Add(parameter);
+ cmm.Statements.Add(methodinvoked);
+ cmm.Statements.Add(new CodeMethodReturnStatement(new CodeBinaryOperatorExpression
+ (new CodeVariableReferenceExpression("a"), CodeBinaryOperatorType.Add, new CodeVariableReferenceExpression("b"))));
+ cd.Members.Add(cmm);
+ }
+ if (provider.Supports(GeneratorSupport.ReturnTypeAttributes))
+ {
+ CodeMemberMethod function1 = new CodeMemberMethod();
+ function1.Name = "MyFunction";
+ function1.ReturnType = new CodeTypeReference(typeof(string));
+ function1.Attributes = MemberAttributes.Public | MemberAttributes.Final;
+ function1.ReturnTypeCustomAttributes.Add(new
+ CodeAttributeDeclaration("System.Xml.Serialization.XmlIgnoreAttribute"));
+ function1.ReturnTypeCustomAttributes.Add(new CodeAttributeDeclaration("System.Xml.Serialization.XmlRootAttribute", new
+ CodeAttributeArgument("Namespace", new CodePrimitiveExpression("Namespace Value")), new
+ CodeAttributeArgument("ElementName", new CodePrimitiveExpression("Root, hehehe"))));
+ function1.Statements.Add(new CodeMethodReturnStatement(new CodePrimitiveExpression("Return")));
+ cd.Members.Add(function1);
+ }
+ if (provider.Supports(GeneratorSupport.StaticConstructors))
+ {
+ cmm = new CodeMemberMethod();
+ cmm.Name = "TestStaticConstructor";
+ cmm.Attributes = MemberAttributes.Public | MemberAttributes.Static;
+ cmm.ReturnType = new CodeTypeReference(typeof(int));
+ CodeParameterDeclarationExpression param = new CodeParameterDeclarationExpression(typeof(int), "a");
+ cmm.Parameters.Add(param);
+ // utilize constructor
+ cmm.Statements.Add(new CodeVariableDeclarationStatement("Test4", "t", new CodeObjectCreateExpression("Test4")));
+ // set then get number
+ cmm.Statements.Add(new CodeAssignStatement(new CodePropertyReferenceExpression(new CodeVariableReferenceExpression("t"), "i")
+ , new CodeVariableReferenceExpression("a")));
+ cmm.Statements.Add(new CodeMethodReturnStatement(new CodeMethodReferenceExpression(
+ new CodeVariableReferenceExpression("t"), "i")));
+ cd.Members.Add(cmm);
- CodeMemberEvent evt = new CodeMemberEvent();
- evt.Name = "MyEvent";
- evt.Type = new CodeTypeReference("System.EventHandler");
- evt.Attributes = MemberAttributes.Public;
- class1.Members.Add(evt);
+ class1 = new CodeTypeDeclaration();
+ class1.Name = "Test4";
+ class1.IsClass = true;
+ nspace.Types.Add(class1);
+
+ class1.Members.Add(new CodeMemberField(new CodeTypeReference(typeof(int)), "number"));
+ CodeMemberProperty prop = new CodeMemberProperty();
+ prop.Name = "i";
+ prop.Attributes = MemberAttributes.Public | MemberAttributes.Final;
+ prop.Type = new CodeTypeReference(typeof(int));
+ prop.GetStatements.Add(new CodeMethodReturnStatement(new CodeVariableReferenceExpression("number")));
+ prop.SetStatements.Add(new CodeAssignStatement(new CodeVariableReferenceExpression("number"),
+ new CodePropertySetValueReferenceExpression()));
+ class1.Members.Add(prop);
+ CodeTypeConstructor ctc = new CodeTypeConstructor();
+ class1.Members.Add(ctc);
+ }
+ if (provider.Supports(GeneratorSupport.TryCatchStatements))
+ {
+ cmm = new CodeMemberMethod();
+ cmm.Name = "TryCatchMethod";
+ cmm.ReturnType = new CodeTypeReference(typeof(int));
+ cmm.Attributes = MemberAttributes.Public | MemberAttributes.Static;
+ CodeParameterDeclarationExpression param = new CodeParameterDeclarationExpression(typeof(int), "a");
+ cmm.Parameters.Add(param);
+
+ CodeTryCatchFinallyStatement tcfstmt = new CodeTryCatchFinallyStatement();
+ tcfstmt.FinallyStatements.Add(new CodeAssignStatement(new CodeVariableReferenceExpression("a"), new
+ CodeBinaryOperatorExpression(new CodeVariableReferenceExpression("a"), CodeBinaryOperatorType.Add,
+ new CodePrimitiveExpression(5))));
+ cmm.Statements.Add(tcfstmt);
+ cmm.Statements.Add(new CodeMethodReturnStatement(new CodeVariableReferenceExpression("a")));
+ cd.Members.Add(cmm);
+ }
+ if (provider.Supports(GeneratorSupport.DeclareEvents))
+ {
+ CodeNamespace ns = new CodeNamespace();
+ ns.Name = "MyNamespace";
+ ns.Imports.Add(new CodeNamespaceImport("System"));
+ ns.Imports.Add(new CodeNamespaceImport("System.Drawing"));
+ ns.Imports.Add(new CodeNamespaceImport("System.Windows.Forms"));
+ ns.Imports.Add(new CodeNamespaceImport("System.ComponentModel"));
+ cu.Namespaces.Add(ns);
+ class1 = new CodeTypeDeclaration("Test");
+ class1.IsClass = true;
+ class1.BaseTypes.Add(new CodeTypeReference("Form"));
+ ns.Types.Add(class1);
+
+ CodeMemberField mfield = new CodeMemberField(new CodeTypeReference("Button"), "b");
+ mfield.InitExpression = new CodeObjectCreateExpression(new CodeTypeReference("Button"));
+ class1.Members.Add(mfield);
+
+ CodeConstructor ctor = new CodeConstructor();
+ ctor.Attributes = MemberAttributes.Public;
+ ctor.Statements.Add(new CodeAssignStatement(new CodeFieldReferenceExpression(new CodeThisReferenceExpression(),
+ "Size"), new CodeObjectCreateExpression(new CodeTypeReference("Size"),
+ new CodePrimitiveExpression(600), new CodePrimitiveExpression(600))));
+ ctor.Statements.Add(new CodeAssignStatement(new CodeFieldReferenceExpression(new CodeTypeReferenceExpression("b"),
+ "Text"), new CodePrimitiveExpression("Test")));
+ ctor.Statements.Add(new CodeAssignStatement(new CodeFieldReferenceExpression(new CodeTypeReferenceExpression("b"),
+ "TabIndex"), new CodePrimitiveExpression(0)));
+ ctor.Statements.Add(new CodeAssignStatement(new CodeFieldReferenceExpression(new CodeTypeReferenceExpression("b"),
+ "Location"), new CodeObjectCreateExpression(new CodeTypeReference("Point"),
+ new CodePrimitiveExpression(400), new CodePrimitiveExpression(525))));
+ ctor.Statements.Add(new CodeAttachEventStatement(new CodeEventReferenceExpression(new
+ CodeThisReferenceExpression(), "MyEvent"), new CodeDelegateCreateExpression(new CodeTypeReference("EventHandler")
+ , new CodeThisReferenceExpression(), "b_Click")));
+ class1.Members.Add(ctor);
+
+ CodeMemberEvent evt = new CodeMemberEvent();
+ evt.Name = "MyEvent";
+ evt.Type = new CodeTypeReference("System.EventHandler");
+ evt.Attributes = MemberAttributes.Public;
+ class1.Members.Add(evt);
- cmm = new CodeMemberMethod();
- cmm.Name = "b_Click";
- cmm.Parameters.Add(new CodeParameterDeclarationExpression(typeof(object), "sender"));
- cmm.Parameters.Add(new CodeParameterDeclarationExpression(typeof(EventArgs), "e"));
- class1.Members.Add(cmm);
- }
+ cmm = new CodeMemberMethod();
+ cmm.Name = "b_Click";
+ cmm.Parameters.Add(new CodeParameterDeclarationExpression(typeof(object), "sender"));
+ cmm.Parameters.Add(new CodeParameterDeclarationExpression(typeof(EventArgs), "e"));
+ class1.Members.Add(cmm);
+ }
- AssertEqual(cu,
- @"//------------------------------------------------------------------------------
+ AssertEqual(cu,
+ @"//------------------------------------------------------------------------------
// <auto-generated>
// This code was generated by a tool.
//
}
}
}");
+ }
}).Dispose();
}
using System.Collections.Generic;
using System.Globalization;
using System.Reflection;
-using Microsoft.VisualBasic;
+using System.Tests;
using Microsoft.DotNet.RemoteExecutor;
+using Microsoft.VisualBasic;
using Xunit;
namespace System.CodeDom.Compiler.Tests
[SkipOnTargetFramework(TargetFrameworkMonikers.NetFramework)]
public void MetadataAttributes()
{
- RemoteExecutor.Invoke(() =>
+ RemoteExecutorForUap.Invoke(() =>
{
- CultureInfo.CurrentUICulture = CultureInfo.InvariantCulture;
-
- var cu = new CodeCompileUnit();
-
- var ns = new CodeNamespace();
- ns.Name = "MyNamespace";
- ns.Imports.Add(new CodeNamespaceImport("System"));
- ns.Imports.Add(new CodeNamespaceImport("System.Drawing"));
- ns.Imports.Add(new CodeNamespaceImport("System.Windows.Forms"));
- ns.Imports.Add(new CodeNamespaceImport("System.ComponentModel"));
- cu.Namespaces.Add(ns);
-
- var attrs = cu.AssemblyCustomAttributes;
- attrs.Add(new CodeAttributeDeclaration("System.Reflection.AssemblyTitle", new CodeAttributeArgument(new CodePrimitiveExpression("MyAssembly"))));
- attrs.Add(new CodeAttributeDeclaration("System.Reflection.AssemblyVersion", new CodeAttributeArgument(new CodePrimitiveExpression("1.0.6.2"))));
- attrs.Add(new CodeAttributeDeclaration("System.CLSCompliantAttribute", new CodeAttributeArgument(new CodePrimitiveExpression(false))));
-
- var class1 = new CodeTypeDeclaration() { Name = "MyClass" };
- class1.CustomAttributes.Add(new CodeAttributeDeclaration("System.Serializable"));
- class1.CustomAttributes.Add(new CodeAttributeDeclaration("System.Obsolete", new CodeAttributeArgument(new CodePrimitiveExpression("Don't use this Class"))));
- ns.Types.Add(class1);
-
- var nestedClass = new CodeTypeDeclaration("NestedClass") { IsClass = true, TypeAttributes = TypeAttributes.NestedPublic };
- nestedClass.CustomAttributes.Add(new CodeAttributeDeclaration("System.Serializable"));
- class1.Members.Add(nestedClass);
-
- var method1 = new CodeMemberMethod() { Name = "MyMethod" };
- method1.CustomAttributes.Add(new CodeAttributeDeclaration("System.Obsolete", new CodeAttributeArgument(new CodePrimitiveExpression("Don't use this Method"))));
- method1.CustomAttributes.Add(new CodeAttributeDeclaration("System.ComponentModel.Editor", new CodeAttributeArgument(new CodePrimitiveExpression("This")), new CodeAttributeArgument(new CodePrimitiveExpression("That"))));
- var param1 = new CodeParameterDeclarationExpression(typeof(string), "blah");
- param1.CustomAttributes.Add(new CodeAttributeDeclaration("System.Xml.Serialization.XmlElementAttribute",
- new CodeAttributeArgument("Form", new CodeFieldReferenceExpression(new CodeTypeReferenceExpression("System.Xml.Schema.XmlSchemaForm"), "Unqualified")),
- new CodeAttributeArgument("IsNullable", new CodePrimitiveExpression(false))));
- method1.Parameters.Add(param1);
- var param2 = new CodeParameterDeclarationExpression(typeof(int[]), "arrayit");
- param2.CustomAttributes.Add(
- new CodeAttributeDeclaration("System.Xml.Serialization.XmlElementAttribute",
- new CodeAttributeArgument("Form", new CodeFieldReferenceExpression(new CodeTypeReferenceExpression("System.Xml.Schema.XmlSchemaForm"), "Unqualified")),
- new CodeAttributeArgument("IsNullable", new CodePrimitiveExpression(false))));
- method1.Parameters.Add(param2);
- class1.Members.Add(method1);
-
- var function1 = new CodeMemberMethod();
- function1.Name = "MyFunction";
- function1.ReturnType = new CodeTypeReference(typeof(string));
- function1.CustomAttributes.Add(new CodeAttributeDeclaration("System.Obsolete", new CodeAttributeArgument(new CodePrimitiveExpression("Don't use this Function"))));
- function1.ReturnTypeCustomAttributes.Add(new CodeAttributeDeclaration("System.Xml.Serialization.XmlIgnoreAttribute"));
- function1.ReturnTypeCustomAttributes.Add(new CodeAttributeDeclaration("System.Xml.Serialization.XmlRootAttribute", new
- CodeAttributeArgument("Namespace", new CodePrimitiveExpression("Namespace Value")), new
- CodeAttributeArgument("ElementName", new CodePrimitiveExpression("Root, hehehe"))));
- function1.Statements.Add(new CodeMethodReturnStatement(new CodePrimitiveExpression("Return")));
- class1.Members.Add(function1);
-
- CodeMemberMethod function2 = new CodeMemberMethod();
- function2.Name = "GlobalKeywordFunction";
- function2.CustomAttributes.Add(new CodeAttributeDeclaration(new CodeTypeReference(typeof(ObsoleteAttribute), CodeTypeReferenceOptions.GlobalReference), new
- CodeAttributeArgument(new CodePrimitiveExpression("Don't use this Function"))));
- CodeTypeReference typeRef = new CodeTypeReference("System.Xml.Serialization.XmlIgnoreAttribute", CodeTypeReferenceOptions.GlobalReference);
- CodeAttributeDeclaration codeAttrib = new CodeAttributeDeclaration(typeRef);
- function2.ReturnTypeCustomAttributes.Add(codeAttrib);
- class1.Members.Add(function2);
-
- CodeMemberField field1 = new CodeMemberField();
- field1.Name = "myField";
- field1.Type = new CodeTypeReference(typeof(string));
- field1.CustomAttributes.Add(new CodeAttributeDeclaration("System.Xml.Serialization.XmlElementAttribute"));
- field1.InitExpression = new CodePrimitiveExpression("hi!");
- class1.Members.Add(field1);
-
- CodeMemberProperty prop1 = new CodeMemberProperty();
- prop1.Name = "MyProperty";
- prop1.Type = new CodeTypeReference(typeof(string));
- prop1.CustomAttributes.Add(new CodeAttributeDeclaration("System.Obsolete", new CodeAttributeArgument(new CodePrimitiveExpression("Don't use this Property"))));
- prop1.GetStatements.Add(new CodeMethodReturnStatement(new CodeFieldReferenceExpression(new CodeThisReferenceExpression(), "myField")));
- class1.Members.Add(prop1);
-
- CodeConstructor const1 = new CodeConstructor();
- const1.CustomAttributes.Add(new CodeAttributeDeclaration("System.Obsolete", new CodeAttributeArgument(new CodePrimitiveExpression("Don't use this Constructor"))));
- class1.Members.Add(const1);
-
- class1 = new CodeTypeDeclaration("Test");
- class1.IsClass = true;
- class1.BaseTypes.Add(new CodeTypeReference("Form"));
- ns.Types.Add(class1);
-
- CodeMemberField mfield = new CodeMemberField(new CodeTypeReference("Button"), "b");
- mfield.InitExpression = new CodeObjectCreateExpression(new CodeTypeReference("Button"));
- class1.Members.Add(mfield);
-
- CodeConstructor ctor = new CodeConstructor();
- ctor.Attributes = MemberAttributes.Public;
- ctor.Statements.Add(new CodeAssignStatement(new CodeFieldReferenceExpression(new CodeThisReferenceExpression(),
- "Size"), new CodeObjectCreateExpression(new CodeTypeReference("Size"),
- new CodePrimitiveExpression(600), new CodePrimitiveExpression(600))));
- ctor.Statements.Add(new CodeAssignStatement(new CodeFieldReferenceExpression(new CodeTypeReferenceExpression("b"),
- "Text"), new CodePrimitiveExpression("Test")));
- ctor.Statements.Add(new CodeAssignStatement(new CodeFieldReferenceExpression(new CodeTypeReferenceExpression("b"),
- "TabIndex"), new CodePrimitiveExpression(0)));
- ctor.Statements.Add(new CodeAssignStatement(new CodeFieldReferenceExpression(new CodeTypeReferenceExpression("b"),
- "Location"), new CodeObjectCreateExpression(new CodeTypeReference("Point"),
- new CodePrimitiveExpression(400), new CodePrimitiveExpression(525))));
- ctor.Statements.Add(new CodeAttachEventStatement(new CodeEventReferenceExpression(new
- CodeThisReferenceExpression(), "MyEvent"), new CodeDelegateCreateExpression(new CodeTypeReference("EventHandler")
- , new CodeThisReferenceExpression(), "b_Click")));
- class1.Members.Add(ctor);
-
- CodeMemberEvent evt = new CodeMemberEvent();
- evt.Name = "MyEvent";
- evt.Type = new CodeTypeReference("System.EventHandler");
- evt.Attributes = MemberAttributes.Public;
- evt.CustomAttributes.Add(new CodeAttributeDeclaration("System.CLSCompliantAttribute", new CodeAttributeArgument(new CodePrimitiveExpression(false))));
- class1.Members.Add(evt);
-
- CodeMemberMethod cmm = new CodeMemberMethod();
- cmm.Name = "b_Click";
- cmm.Parameters.Add(new CodeParameterDeclarationExpression(typeof(object), "sender"));
- cmm.Parameters.Add(new CodeParameterDeclarationExpression(typeof(EventArgs), "e"));
- class1.Members.Add(cmm);
-
- AssertEqual(cu,
- @"'------------------------------------------------------------------------------
+ using (new ThreadCultureChange(CultureInfo.InvariantCulture))
+ {
+ var cu = new CodeCompileUnit();
+
+ var ns = new CodeNamespace();
+ ns.Name = "MyNamespace";
+ ns.Imports.Add(new CodeNamespaceImport("System"));
+ ns.Imports.Add(new CodeNamespaceImport("System.Drawing"));
+ ns.Imports.Add(new CodeNamespaceImport("System.Windows.Forms"));
+ ns.Imports.Add(new CodeNamespaceImport("System.ComponentModel"));
+ cu.Namespaces.Add(ns);
+
+ var attrs = cu.AssemblyCustomAttributes;
+ attrs.Add(new CodeAttributeDeclaration("System.Reflection.AssemblyTitle", new CodeAttributeArgument(new CodePrimitiveExpression("MyAssembly"))));
+ attrs.Add(new CodeAttributeDeclaration("System.Reflection.AssemblyVersion", new CodeAttributeArgument(new CodePrimitiveExpression("1.0.6.2"))));
+ attrs.Add(new CodeAttributeDeclaration("System.CLSCompliantAttribute", new CodeAttributeArgument(new CodePrimitiveExpression(false))));
+
+ var class1 = new CodeTypeDeclaration() { Name = "MyClass" };
+ class1.CustomAttributes.Add(new CodeAttributeDeclaration("System.Serializable"));
+ class1.CustomAttributes.Add(new CodeAttributeDeclaration("System.Obsolete", new CodeAttributeArgument(new CodePrimitiveExpression("Don't use this Class"))));
+ ns.Types.Add(class1);
+
+ var nestedClass = new CodeTypeDeclaration("NestedClass") { IsClass = true, TypeAttributes = TypeAttributes.NestedPublic };
+ nestedClass.CustomAttributes.Add(new CodeAttributeDeclaration("System.Serializable"));
+ class1.Members.Add(nestedClass);
+
+ var method1 = new CodeMemberMethod() { Name = "MyMethod" };
+ method1.CustomAttributes.Add(new CodeAttributeDeclaration("System.Obsolete", new CodeAttributeArgument(new CodePrimitiveExpression("Don't use this Method"))));
+ method1.CustomAttributes.Add(new CodeAttributeDeclaration("System.ComponentModel.Editor", new CodeAttributeArgument(new CodePrimitiveExpression("This")), new CodeAttributeArgument(new CodePrimitiveExpression("That"))));
+ var param1 = new CodeParameterDeclarationExpression(typeof(string), "blah");
+ param1.CustomAttributes.Add(new CodeAttributeDeclaration("System.Xml.Serialization.XmlElementAttribute",
+ new CodeAttributeArgument("Form", new CodeFieldReferenceExpression(new CodeTypeReferenceExpression("System.Xml.Schema.XmlSchemaForm"), "Unqualified")),
+ new CodeAttributeArgument("IsNullable", new CodePrimitiveExpression(false))));
+ method1.Parameters.Add(param1);
+ var param2 = new CodeParameterDeclarationExpression(typeof(int[]), "arrayit");
+ param2.CustomAttributes.Add(
+ new CodeAttributeDeclaration("System.Xml.Serialization.XmlElementAttribute",
+ new CodeAttributeArgument("Form", new CodeFieldReferenceExpression(new CodeTypeReferenceExpression("System.Xml.Schema.XmlSchemaForm"), "Unqualified")),
+ new CodeAttributeArgument("IsNullable", new CodePrimitiveExpression(false))));
+ method1.Parameters.Add(param2);
+ class1.Members.Add(method1);
+
+ var function1 = new CodeMemberMethod();
+ function1.Name = "MyFunction";
+ function1.ReturnType = new CodeTypeReference(typeof(string));
+ function1.CustomAttributes.Add(new CodeAttributeDeclaration("System.Obsolete", new CodeAttributeArgument(new CodePrimitiveExpression("Don't use this Function"))));
+ function1.ReturnTypeCustomAttributes.Add(new CodeAttributeDeclaration("System.Xml.Serialization.XmlIgnoreAttribute"));
+ function1.ReturnTypeCustomAttributes.Add(new CodeAttributeDeclaration("System.Xml.Serialization.XmlRootAttribute", new
+ CodeAttributeArgument("Namespace", new CodePrimitiveExpression("Namespace Value")), new
+ CodeAttributeArgument("ElementName", new CodePrimitiveExpression("Root, hehehe"))));
+ function1.Statements.Add(new CodeMethodReturnStatement(new CodePrimitiveExpression("Return")));
+ class1.Members.Add(function1);
+
+ CodeMemberMethod function2 = new CodeMemberMethod();
+ function2.Name = "GlobalKeywordFunction";
+ function2.CustomAttributes.Add(new CodeAttributeDeclaration(new CodeTypeReference(typeof(ObsoleteAttribute), CodeTypeReferenceOptions.GlobalReference), new
+ CodeAttributeArgument(new CodePrimitiveExpression("Don't use this Function"))));
+ CodeTypeReference typeRef = new CodeTypeReference("System.Xml.Serialization.XmlIgnoreAttribute", CodeTypeReferenceOptions.GlobalReference);
+ CodeAttributeDeclaration codeAttrib = new CodeAttributeDeclaration(typeRef);
+ function2.ReturnTypeCustomAttributes.Add(codeAttrib);
+ class1.Members.Add(function2);
+
+ CodeMemberField field1 = new CodeMemberField();
+ field1.Name = "myField";
+ field1.Type = new CodeTypeReference(typeof(string));
+ field1.CustomAttributes.Add(new CodeAttributeDeclaration("System.Xml.Serialization.XmlElementAttribute"));
+ field1.InitExpression = new CodePrimitiveExpression("hi!");
+ class1.Members.Add(field1);
+
+ CodeMemberProperty prop1 = new CodeMemberProperty();
+ prop1.Name = "MyProperty";
+ prop1.Type = new CodeTypeReference(typeof(string));
+ prop1.CustomAttributes.Add(new CodeAttributeDeclaration("System.Obsolete", new CodeAttributeArgument(new CodePrimitiveExpression("Don't use this Property"))));
+ prop1.GetStatements.Add(new CodeMethodReturnStatement(new CodeFieldReferenceExpression(new CodeThisReferenceExpression(), "myField")));
+ class1.Members.Add(prop1);
+
+ CodeConstructor const1 = new CodeConstructor();
+ const1.CustomAttributes.Add(new CodeAttributeDeclaration("System.Obsolete", new CodeAttributeArgument(new CodePrimitiveExpression("Don't use this Constructor"))));
+ class1.Members.Add(const1);
+
+ class1 = new CodeTypeDeclaration("Test");
+ class1.IsClass = true;
+ class1.BaseTypes.Add(new CodeTypeReference("Form"));
+ ns.Types.Add(class1);
+
+ CodeMemberField mfield = new CodeMemberField(new CodeTypeReference("Button"), "b");
+ mfield.InitExpression = new CodeObjectCreateExpression(new CodeTypeReference("Button"));
+ class1.Members.Add(mfield);
+
+ CodeConstructor ctor = new CodeConstructor();
+ ctor.Attributes = MemberAttributes.Public;
+ ctor.Statements.Add(new CodeAssignStatement(new CodeFieldReferenceExpression(new CodeThisReferenceExpression(),
+ "Size"), new CodeObjectCreateExpression(new CodeTypeReference("Size"),
+ new CodePrimitiveExpression(600), new CodePrimitiveExpression(600))));
+ ctor.Statements.Add(new CodeAssignStatement(new CodeFieldReferenceExpression(new CodeTypeReferenceExpression("b"),
+ "Text"), new CodePrimitiveExpression("Test")));
+ ctor.Statements.Add(new CodeAssignStatement(new CodeFieldReferenceExpression(new CodeTypeReferenceExpression("b"),
+ "TabIndex"), new CodePrimitiveExpression(0)));
+ ctor.Statements.Add(new CodeAssignStatement(new CodeFieldReferenceExpression(new CodeTypeReferenceExpression("b"),
+ "Location"), new CodeObjectCreateExpression(new CodeTypeReference("Point"),
+ new CodePrimitiveExpression(400), new CodePrimitiveExpression(525))));
+ ctor.Statements.Add(new CodeAttachEventStatement(new CodeEventReferenceExpression(new
+ CodeThisReferenceExpression(), "MyEvent"), new CodeDelegateCreateExpression(new CodeTypeReference("EventHandler")
+ , new CodeThisReferenceExpression(), "b_Click")));
+ class1.Members.Add(ctor);
+
+ CodeMemberEvent evt = new CodeMemberEvent();
+ evt.Name = "MyEvent";
+ evt.Type = new CodeTypeReference("System.EventHandler");
+ evt.Attributes = MemberAttributes.Public;
+ evt.CustomAttributes.Add(new CodeAttributeDeclaration("System.CLSCompliantAttribute", new CodeAttributeArgument(new CodePrimitiveExpression(false))));
+ class1.Members.Add(evt);
+
+ CodeMemberMethod cmm = new CodeMemberMethod();
+ cmm.Name = "b_Click";
+ cmm.Parameters.Add(new CodeParameterDeclarationExpression(typeof(object), "sender"));
+ cmm.Parameters.Add(new CodeParameterDeclarationExpression(typeof(EventArgs), "e"));
+ class1.Members.Add(cmm);
+
+ AssertEqual(cu,
+ @"'------------------------------------------------------------------------------
' <auto-generated>
' This code was generated by a tool.
'
End Sub
End Class
End Namespace");
+ }
}).Dispose();
}
[SkipOnTargetFramework(TargetFrameworkMonikers.NetFramework)]
public void RegionsSnippetsAndLinePragmas()
{
- RemoteExecutor.Invoke(() =>
+ RemoteExecutorForUap.Invoke(() =>
{
- CultureInfo.CurrentUICulture = CultureInfo.InvariantCulture;
-
- CodeCompileUnit cu = new CodeCompileUnit();
- CodeNamespace ns = new CodeNamespace("Namespace1");
+ using (new ThreadCultureChange(CultureInfo.InvariantCulture))
+ {
+ CodeCompileUnit cu = new CodeCompileUnit();
+ CodeNamespace ns = new CodeNamespace("Namespace1");
- cu.StartDirectives.Add(new CodeRegionDirective(CodeRegionMode.Start, "Compile Unit Region"));
- cu.EndDirectives.Add(new CodeRegionDirective(CodeRegionMode.End, string.Empty));
+ cu.StartDirectives.Add(new CodeRegionDirective(CodeRegionMode.Start, "Compile Unit Region"));
+ cu.EndDirectives.Add(new CodeRegionDirective(CodeRegionMode.End, string.Empty));
- cu.Namespaces.Add(ns);
+ cu.Namespaces.Add(ns);
- CodeTypeDeclaration cd = new CodeTypeDeclaration("Class1");
- ns.Types.Add(cd);
+ CodeTypeDeclaration cd = new CodeTypeDeclaration("Class1");
+ ns.Types.Add(cd);
- cd.StartDirectives.Add(new CodeRegionDirective(CodeRegionMode.Start, "Outer Type Region"));
- cd.EndDirectives.Add(new CodeRegionDirective(CodeRegionMode.End, string.Empty));
+ cd.StartDirectives.Add(new CodeRegionDirective(CodeRegionMode.Start, "Outer Type Region"));
+ cd.EndDirectives.Add(new CodeRegionDirective(CodeRegionMode.End, string.Empty));
- cd.Comments.Add(new CodeCommentStatement("Outer Type Comment"));
+ cd.Comments.Add(new CodeCommentStatement("Outer Type Comment"));
- CodeMemberField field1 = new CodeMemberField(typeof(String), "field1");
- CodeMemberField field2 = new CodeMemberField(typeof(String), "field2");
- field1.Comments.Add(new CodeCommentStatement("Field 1 Comment"));
- field2.StartDirectives.Add(new CodeRegionDirective(CodeRegionMode.Start, "Field Region"));
- field2.EndDirectives.Add(new CodeRegionDirective(CodeRegionMode.End, string.Empty));
+ CodeMemberField field1 = new CodeMemberField(typeof(String), "field1");
+ CodeMemberField field2 = new CodeMemberField(typeof(String), "field2");
+ field1.Comments.Add(new CodeCommentStatement("Field 1 Comment"));
+ field2.StartDirectives.Add(new CodeRegionDirective(CodeRegionMode.Start, "Field Region"));
+ field2.EndDirectives.Add(new CodeRegionDirective(CodeRegionMode.End, string.Empty));
- CodeMemberEvent evt1 = new CodeMemberEvent();
- evt1.Name = "Event1";
- evt1.Type = new CodeTypeReference(typeof(System.EventHandler));
- evt1.Attributes = (evt1.Attributes & ~MemberAttributes.AccessMask) | MemberAttributes.Public;
+ CodeMemberEvent evt1 = new CodeMemberEvent();
+ evt1.Name = "Event1";
+ evt1.Type = new CodeTypeReference(typeof(System.EventHandler));
+ evt1.Attributes = (evt1.Attributes & ~MemberAttributes.AccessMask) | MemberAttributes.Public;
- CodeMemberEvent evt2 = new CodeMemberEvent();
- evt2.Name = "Event2";
- evt2.Type = new CodeTypeReference(typeof(System.EventHandler));
- evt2.Attributes = (evt2.Attributes & ~MemberAttributes.AccessMask) | MemberAttributes.Public;
+ CodeMemberEvent evt2 = new CodeMemberEvent();
+ evt2.Name = "Event2";
+ evt2.Type = new CodeTypeReference(typeof(System.EventHandler));
+ evt2.Attributes = (evt2.Attributes & ~MemberAttributes.AccessMask) | MemberAttributes.Public;
- evt2.StartDirectives.Add(new CodeRegionDirective(CodeRegionMode.Start, "Event Region"));
- evt2.EndDirectives.Add(new CodeRegionDirective(CodeRegionMode.End, string.Empty));
+ evt2.StartDirectives.Add(new CodeRegionDirective(CodeRegionMode.Start, "Event Region"));
+ evt2.EndDirectives.Add(new CodeRegionDirective(CodeRegionMode.End, string.Empty));
- CodeMemberMethod method1 = new CodeMemberMethod();
- method1.Name = "Method1";
- method1.Attributes = (method1.Attributes & ~MemberAttributes.AccessMask) | MemberAttributes.Public;
- method1.Statements.Add(
- new CodeDelegateInvokeExpression(
- new CodeEventReferenceExpression(new CodeThisReferenceExpression(), "Event1"),
- new CodeExpression[] {
+ CodeMemberMethod method1 = new CodeMemberMethod();
+ method1.Name = "Method1";
+ method1.Attributes = (method1.Attributes & ~MemberAttributes.AccessMask) | MemberAttributes.Public;
+ method1.Statements.Add(
+ new CodeDelegateInvokeExpression(
+ new CodeEventReferenceExpression(new CodeThisReferenceExpression(), "Event1"),
+ new CodeExpression[] {
new CodeThisReferenceExpression(),
new CodeFieldReferenceExpression(new CodeTypeReferenceExpression("System.EventArgs"), "Empty")
- }));
-
- CodeMemberMethod method2 = new CodeMemberMethod();
- method2.Name = "Method2";
- method2.Attributes = (method2.Attributes & ~MemberAttributes.AccessMask) | MemberAttributes.Public;
- method2.Statements.Add(
- new CodeDelegateInvokeExpression(
- new CodeEventReferenceExpression(new CodeThisReferenceExpression(), "Event2"),
- new CodeExpression[] {
+ }));
+
+ CodeMemberMethod method2 = new CodeMemberMethod();
+ method2.Name = "Method2";
+ method2.Attributes = (method2.Attributes & ~MemberAttributes.AccessMask) | MemberAttributes.Public;
+ method2.Statements.Add(
+ new CodeDelegateInvokeExpression(
+ new CodeEventReferenceExpression(new CodeThisReferenceExpression(), "Event2"),
+ new CodeExpression[] {
new CodeThisReferenceExpression(),
new CodeFieldReferenceExpression(new CodeTypeReferenceExpression("System.EventArgs"), "Empty")
- }));
- method2.LinePragma = new CodeLinePragma("MethodLinePragma.txt", 500);
- method2.Comments.Add(new CodeCommentStatement("Method 2 Comment"));
-
- method2.StartDirectives.Add(new CodeRegionDirective(CodeRegionMode.Start, "Method Region"));
- method2.EndDirectives.Add(new CodeRegionDirective(CodeRegionMode.End, string.Empty));
-
- CodeMemberProperty property1 = new CodeMemberProperty();
- property1.Name = "Property1";
- property1.Type = new CodeTypeReference(typeof(string));
- property1.Attributes = (property1.Attributes & ~MemberAttributes.AccessMask) | MemberAttributes.Public;
- property1.GetStatements.Add(
- new CodeMethodReturnStatement(
- new CodeFieldReferenceExpression(
- new CodeThisReferenceExpression(),
- "field1")));
-
- CodeMemberProperty property2 = new CodeMemberProperty();
- property2.Name = "Property2";
- property2.Type = new CodeTypeReference(typeof(string));
- property2.Attributes = (property2.Attributes & ~MemberAttributes.AccessMask) | MemberAttributes.Public;
- property2.GetStatements.Add(
- new CodeMethodReturnStatement(
- new CodeFieldReferenceExpression(
- new CodeThisReferenceExpression(),
- "field2")));
-
- property2.StartDirectives.Add(new CodeRegionDirective(CodeRegionMode.Start, "Property Region"));
- property2.EndDirectives.Add(new CodeRegionDirective(CodeRegionMode.End, string.Empty));
-
- CodeConstructor constructor1 = new CodeConstructor();
- constructor1.Attributes = (constructor1.Attributes & ~MemberAttributes.AccessMask) | MemberAttributes.Public;
- CodeStatement conState1 = new CodeAssignStatement(
- new CodeFieldReferenceExpression(
- new CodeThisReferenceExpression(),
- "field1"),
- new CodePrimitiveExpression("value1"));
- conState1.StartDirectives.Add(new CodeRegionDirective(CodeRegionMode.Start, "Statements Region"));
- constructor1.Statements.Add(conState1);
- CodeStatement conState2 = new CodeAssignStatement(
- new CodeFieldReferenceExpression(
- new CodeThisReferenceExpression(),
- "field2"),
- new CodePrimitiveExpression("value2"));
- conState2.EndDirectives.Add(new CodeRegionDirective(CodeRegionMode.End, string.Empty));
- constructor1.Statements.Add(conState2);
-
- constructor1.StartDirectives.Add(new CodeRegionDirective(CodeRegionMode.Start, "Constructor Region"));
- constructor1.EndDirectives.Add(new CodeRegionDirective(CodeRegionMode.End, string.Empty));
-
- CodeConstructor constructor2 = new CodeConstructor();
- constructor2.Attributes = (constructor2.Attributes & ~MemberAttributes.AccessMask) | MemberAttributes.Public;
- constructor2.Parameters.Add(new CodeParameterDeclarationExpression(typeof(string), "value1"));
- constructor2.Parameters.Add(new CodeParameterDeclarationExpression(typeof(string), "value2"));
-
- CodeTypeConstructor typeConstructor2 = new CodeTypeConstructor();
-
- typeConstructor2.StartDirectives.Add(new CodeRegionDirective(CodeRegionMode.Start, "Type Constructor Region"));
- typeConstructor2.EndDirectives.Add(new CodeRegionDirective(CodeRegionMode.End, string.Empty));
-
- CodeEntryPointMethod methodMain = new CodeEntryPointMethod();
-
- CodeTypeDeclaration nestedClass1 = new CodeTypeDeclaration("NestedClass1");
- CodeTypeDeclaration nestedClass2 = new CodeTypeDeclaration("NestedClass2");
- nestedClass2.LinePragma = new CodeLinePragma("NestedTypeLinePragma.txt", 400);
- nestedClass2.Comments.Add(new CodeCommentStatement("Nested Type Comment"));
-
- nestedClass2.StartDirectives.Add(new CodeRegionDirective(CodeRegionMode.Start, "Nested Type Region"));
- nestedClass2.EndDirectives.Add(new CodeRegionDirective(CodeRegionMode.End, string.Empty));
-
- CodeTypeDelegate delegate1 = new CodeTypeDelegate();
- delegate1.Name = "nestedDelegate1";
- delegate1.Parameters.Add(new CodeParameterDeclarationExpression(new CodeTypeReference("System.Object"), "sender"));
- delegate1.Parameters.Add(new CodeParameterDeclarationExpression(new CodeTypeReference("System.EventArgs"), "e"));
-
- CodeTypeDelegate delegate2 = new CodeTypeDelegate();
- delegate2.Name = "nestedDelegate2";
- delegate2.Parameters.Add(new CodeParameterDeclarationExpression(new CodeTypeReference("System.Object"), "sender"));
- delegate2.Parameters.Add(new CodeParameterDeclarationExpression(new CodeTypeReference("System.EventArgs"), "e"));
-
- delegate2.StartDirectives.Add(new CodeRegionDirective(CodeRegionMode.Start, "Delegate Region"));
- delegate2.EndDirectives.Add(new CodeRegionDirective(CodeRegionMode.End, string.Empty));
-
- var snippet1 = new CodeSnippetTypeMember();
- var snippet2 = new CodeSnippetTypeMember();
-
- CodeRegionDirective regionStart = new CodeRegionDirective(CodeRegionMode.End, "");
- regionStart.RegionText = "Snippet Region";
- regionStart.RegionMode = CodeRegionMode.Start;
- snippet2.StartDirectives.Add(regionStart);
- snippet2.EndDirectives.Add(new CodeRegionDirective(CodeRegionMode.End, string.Empty));
-
- cd.Members.Add(field1);
- cd.Members.Add(method1);
- cd.Members.Add(constructor1);
- cd.Members.Add(property1);
- cd.Members.Add(methodMain);
-
- cd.Members.Add(evt1);
- cd.Members.Add(nestedClass1);
- cd.Members.Add(delegate1);
-
- cd.Members.Add(snippet1);
-
- cd.Members.Add(field2);
- cd.Members.Add(method2);
- cd.Members.Add(constructor2);
- cd.Members.Add(property2);
-
- cd.Members.Add(typeConstructor2);
- cd.Members.Add(evt2);
- cd.Members.Add(nestedClass2);
- cd.Members.Add(delegate2);
- cd.Members.Add(snippet2);
-
- AssertEqual(cu,
- @"#Region ""Compile Unit Region""
+ }));
+ method2.LinePragma = new CodeLinePragma("MethodLinePragma.txt", 500);
+ method2.Comments.Add(new CodeCommentStatement("Method 2 Comment"));
+
+ method2.StartDirectives.Add(new CodeRegionDirective(CodeRegionMode.Start, "Method Region"));
+ method2.EndDirectives.Add(new CodeRegionDirective(CodeRegionMode.End, string.Empty));
+
+ CodeMemberProperty property1 = new CodeMemberProperty();
+ property1.Name = "Property1";
+ property1.Type = new CodeTypeReference(typeof(string));
+ property1.Attributes = (property1.Attributes & ~MemberAttributes.AccessMask) | MemberAttributes.Public;
+ property1.GetStatements.Add(
+ new CodeMethodReturnStatement(
+ new CodeFieldReferenceExpression(
+ new CodeThisReferenceExpression(),
+ "field1")));
+
+ CodeMemberProperty property2 = new CodeMemberProperty();
+ property2.Name = "Property2";
+ property2.Type = new CodeTypeReference(typeof(string));
+ property2.Attributes = (property2.Attributes & ~MemberAttributes.AccessMask) | MemberAttributes.Public;
+ property2.GetStatements.Add(
+ new CodeMethodReturnStatement(
+ new CodeFieldReferenceExpression(
+ new CodeThisReferenceExpression(),
+ "field2")));
+
+ property2.StartDirectives.Add(new CodeRegionDirective(CodeRegionMode.Start, "Property Region"));
+ property2.EndDirectives.Add(new CodeRegionDirective(CodeRegionMode.End, string.Empty));
+
+ CodeConstructor constructor1 = new CodeConstructor();
+ constructor1.Attributes = (constructor1.Attributes & ~MemberAttributes.AccessMask) | MemberAttributes.Public;
+ CodeStatement conState1 = new CodeAssignStatement(
+ new CodeFieldReferenceExpression(
+ new CodeThisReferenceExpression(),
+ "field1"),
+ new CodePrimitiveExpression("value1"));
+ conState1.StartDirectives.Add(new CodeRegionDirective(CodeRegionMode.Start, "Statements Region"));
+ constructor1.Statements.Add(conState1);
+ CodeStatement conState2 = new CodeAssignStatement(
+ new CodeFieldReferenceExpression(
+ new CodeThisReferenceExpression(),
+ "field2"),
+ new CodePrimitiveExpression("value2"));
+ conState2.EndDirectives.Add(new CodeRegionDirective(CodeRegionMode.End, string.Empty));
+ constructor1.Statements.Add(conState2);
+
+ constructor1.StartDirectives.Add(new CodeRegionDirective(CodeRegionMode.Start, "Constructor Region"));
+ constructor1.EndDirectives.Add(new CodeRegionDirective(CodeRegionMode.End, string.Empty));
+
+ CodeConstructor constructor2 = new CodeConstructor();
+ constructor2.Attributes = (constructor2.Attributes & ~MemberAttributes.AccessMask) | MemberAttributes.Public;
+ constructor2.Parameters.Add(new CodeParameterDeclarationExpression(typeof(string), "value1"));
+ constructor2.Parameters.Add(new CodeParameterDeclarationExpression(typeof(string), "value2"));
+
+ CodeTypeConstructor typeConstructor2 = new CodeTypeConstructor();
+
+ typeConstructor2.StartDirectives.Add(new CodeRegionDirective(CodeRegionMode.Start, "Type Constructor Region"));
+ typeConstructor2.EndDirectives.Add(new CodeRegionDirective(CodeRegionMode.End, string.Empty));
+
+ CodeEntryPointMethod methodMain = new CodeEntryPointMethod();
+
+ CodeTypeDeclaration nestedClass1 = new CodeTypeDeclaration("NestedClass1");
+ CodeTypeDeclaration nestedClass2 = new CodeTypeDeclaration("NestedClass2");
+ nestedClass2.LinePragma = new CodeLinePragma("NestedTypeLinePragma.txt", 400);
+ nestedClass2.Comments.Add(new CodeCommentStatement("Nested Type Comment"));
+
+ nestedClass2.StartDirectives.Add(new CodeRegionDirective(CodeRegionMode.Start, "Nested Type Region"));
+ nestedClass2.EndDirectives.Add(new CodeRegionDirective(CodeRegionMode.End, string.Empty));
+
+ CodeTypeDelegate delegate1 = new CodeTypeDelegate();
+ delegate1.Name = "nestedDelegate1";
+ delegate1.Parameters.Add(new CodeParameterDeclarationExpression(new CodeTypeReference("System.Object"), "sender"));
+ delegate1.Parameters.Add(new CodeParameterDeclarationExpression(new CodeTypeReference("System.EventArgs"), "e"));
+
+ CodeTypeDelegate delegate2 = new CodeTypeDelegate();
+ delegate2.Name = "nestedDelegate2";
+ delegate2.Parameters.Add(new CodeParameterDeclarationExpression(new CodeTypeReference("System.Object"), "sender"));
+ delegate2.Parameters.Add(new CodeParameterDeclarationExpression(new CodeTypeReference("System.EventArgs"), "e"));
+
+ delegate2.StartDirectives.Add(new CodeRegionDirective(CodeRegionMode.Start, "Delegate Region"));
+ delegate2.EndDirectives.Add(new CodeRegionDirective(CodeRegionMode.End, string.Empty));
+
+ var snippet1 = new CodeSnippetTypeMember();
+ var snippet2 = new CodeSnippetTypeMember();
+
+ CodeRegionDirective regionStart = new CodeRegionDirective(CodeRegionMode.End, "");
+ regionStart.RegionText = "Snippet Region";
+ regionStart.RegionMode = CodeRegionMode.Start;
+ snippet2.StartDirectives.Add(regionStart);
+ snippet2.EndDirectives.Add(new CodeRegionDirective(CodeRegionMode.End, string.Empty));
+
+ cd.Members.Add(field1);
+ cd.Members.Add(method1);
+ cd.Members.Add(constructor1);
+ cd.Members.Add(property1);
+ cd.Members.Add(methodMain);
+
+ cd.Members.Add(evt1);
+ cd.Members.Add(nestedClass1);
+ cd.Members.Add(delegate1);
+
+ cd.Members.Add(snippet1);
+
+ cd.Members.Add(field2);
+ cd.Members.Add(method2);
+ cd.Members.Add(constructor2);
+ cd.Members.Add(property2);
+
+ cd.Members.Add(typeConstructor2);
+ cd.Members.Add(evt2);
+ cd.Members.Add(nestedClass2);
+ cd.Members.Add(delegate2);
+ cd.Members.Add(snippet2);
+
+ AssertEqual(cu,
+ @"#Region ""Compile Unit Region""
'------------------------------------------------------------------------------
' <auto-generated>
' This code was generated by a tool.
#End Region
End Namespace
#End Region");
+ }
}).Dispose();
}
[SkipOnTargetFramework(TargetFrameworkMonikers.NetFramework)]
public void ProviderSupports()
{
- RemoteExecutor.Invoke(() =>
+ RemoteExecutorForUap.Invoke(() =>
{
- CultureInfo.CurrentUICulture = CultureInfo.InvariantCulture;
-
- CodeDomProvider provider = GetProvider();
-
- CodeCompileUnit cu = new CodeCompileUnit();
- CodeNamespace nspace = new CodeNamespace("NSPC");
- nspace.Imports.Add(new CodeNamespaceImport("System"));
- nspace.Imports.Add(new CodeNamespaceImport("System.Drawing"));
- nspace.Imports.Add(new CodeNamespaceImport("System.Windows.Forms"));
- nspace.Imports.Add(new CodeNamespaceImport("System.ComponentModel"));
- cu.Namespaces.Add(nspace);
-
- CodeTypeDeclaration cd = new CodeTypeDeclaration("TEST");
- cd.IsClass = true;
- nspace.Types.Add(cd);
-
- // Arrays of Arrays
- CodeMemberMethod cmm = new CodeMemberMethod();
- cmm.Name = "ArraysOfArrays";
- cmm.ReturnType = new CodeTypeReference(typeof(int));
- cmm.Attributes = MemberAttributes.Final | MemberAttributes.Public;
- if (provider.Supports(GeneratorSupport.ArraysOfArrays))
+ using (new ThreadCultureChange(CultureInfo.InvariantCulture))
{
- cmm.Statements.Add(new CodeVariableDeclarationStatement(new CodeTypeReference(typeof(int[][])),
- "arrayOfArrays", new CodeArrayCreateExpression(typeof(int[][]),
- new CodeArrayCreateExpression(typeof(int[]), new CodePrimitiveExpression(3), new CodePrimitiveExpression(4)),
- new CodeArrayCreateExpression(typeof(int[]), new CodeExpression[] { new CodePrimitiveExpression(1) }))));
- cmm.Statements.Add(new CodeMethodReturnStatement(new CodeArrayIndexerExpression(
- new CodeArrayIndexerExpression(new CodeVariableReferenceExpression("arrayOfArrays"), new CodePrimitiveExpression(0))
- , new CodePrimitiveExpression(1))));
- }
- else
- {
- throw new Exception("not supported");
- }
- cd.Members.Add(cmm);
-
- // assembly attributes
- if (provider.Supports(GeneratorSupport.AssemblyAttributes))
- {
- CodeAttributeDeclarationCollection attrs = cu.AssemblyCustomAttributes;
- attrs.Add(new CodeAttributeDeclaration("System.Reflection.AssemblyTitle", new
- CodeAttributeArgument(new CodePrimitiveExpression("MyAssembly"))));
- attrs.Add(new CodeAttributeDeclaration("System.Reflection.AssemblyVersion", new
- CodeAttributeArgument(new CodePrimitiveExpression("1.0.6.2"))));
- }
-
- CodeTypeDeclaration class1 = new CodeTypeDeclaration();
- if (provider.Supports(GeneratorSupport.ChainedConstructorArguments))
- {
- class1.Name = "Test2";
- class1.IsClass = true;
- nspace.Types.Add(class1);
-
- class1.Members.Add(new CodeMemberField(new CodeTypeReference(typeof(String)), "stringField"));
- CodeMemberProperty prop = new CodeMemberProperty();
- prop.Name = "accessStringField";
- prop.Attributes = MemberAttributes.Public | MemberAttributes.Final;
- prop.Type = new CodeTypeReference(typeof(String));
- prop.GetStatements.Add(new CodeMethodReturnStatement(new CodeFieldReferenceExpression(new CodeThisReferenceExpression(),
- "stringField")));
- prop.SetStatements.Add(new CodeAssignStatement(new CodeFieldReferenceExpression(new
- CodeThisReferenceExpression(), "stringField"),
- new CodePropertySetValueReferenceExpression()));
- class1.Members.Add(prop);
-
- CodeConstructor cctor = new CodeConstructor();
- cctor.Attributes = MemberAttributes.Public;
- cctor.ChainedConstructorArgs.Add(new CodePrimitiveExpression("testingString"));
- cctor.ChainedConstructorArgs.Add(new CodePrimitiveExpression(null));
- cctor.ChainedConstructorArgs.Add(new CodePrimitiveExpression(null));
- class1.Members.Add(cctor);
-
- CodeConstructor cc = new CodeConstructor();
- cc.Attributes = MemberAttributes.Public | MemberAttributes.Overloaded;
- cc.Parameters.Add(new CodeParameterDeclarationExpression(typeof(string), "p1"));
- cc.Parameters.Add(new CodeParameterDeclarationExpression(typeof(string), "p2"));
- cc.Parameters.Add(new CodeParameterDeclarationExpression(typeof(string), "p3"));
- cc.Statements.Add(new CodeAssignStatement(new CodeFieldReferenceExpression(new CodeThisReferenceExpression()
- , "stringField"), new CodeVariableReferenceExpression("p1")));
- class1.Members.Add(cc);
- // verify chained constructors work
- cmm = new CodeMemberMethod();
- cmm.Name = "ChainedConstructorUse";
- cmm.Attributes = MemberAttributes.Public | MemberAttributes.Static;
- cmm.ReturnType = new CodeTypeReference(typeof(String));
- // utilize constructor
- cmm.Statements.Add(new CodeVariableDeclarationStatement("Test2", "t", new CodeObjectCreateExpression("Test2")));
- cmm.Statements.Add(new CodeMethodReturnStatement(new CodeMethodReferenceExpression(
- new CodeVariableReferenceExpression("t"), "accessStringField")));
- cd.Members.Add(cmm);
- }
-
- // complex expressions
- if (provider.Supports(GeneratorSupport.ComplexExpressions))
- {
- cmm = new CodeMemberMethod();
- cmm.Name = "ComplexExpressions";
+ CodeDomProvider provider = GetProvider();
+
+ CodeCompileUnit cu = new CodeCompileUnit();
+ CodeNamespace nspace = new CodeNamespace("NSPC");
+ nspace.Imports.Add(new CodeNamespaceImport("System"));
+ nspace.Imports.Add(new CodeNamespaceImport("System.Drawing"));
+ nspace.Imports.Add(new CodeNamespaceImport("System.Windows.Forms"));
+ nspace.Imports.Add(new CodeNamespaceImport("System.ComponentModel"));
+ cu.Namespaces.Add(nspace);
+
+ CodeTypeDeclaration cd = new CodeTypeDeclaration("TEST");
+ cd.IsClass = true;
+ nspace.Types.Add(cd);
+
+ // Arrays of Arrays
+ CodeMemberMethod cmm = new CodeMemberMethod();
+ cmm.Name = "ArraysOfArrays";
cmm.ReturnType = new CodeTypeReference(typeof(int));
cmm.Attributes = MemberAttributes.Final | MemberAttributes.Public;
- cmm.Parameters.Add(new CodeParameterDeclarationExpression(new CodeTypeReference(typeof(int)), "i"));
- cmm.Statements.Add(new CodeAssignStatement(new CodeVariableReferenceExpression("i"),
- new CodeBinaryOperatorExpression(new CodeVariableReferenceExpression("i"), CodeBinaryOperatorType.Multiply,
- new CodeBinaryOperatorExpression(new CodeVariableReferenceExpression("i"), CodeBinaryOperatorType.Add,
- new CodePrimitiveExpression(3)))));
- cmm.Statements.Add(new CodeMethodReturnStatement(new CodeVariableReferenceExpression("i")));
+ if (provider.Supports(GeneratorSupport.ArraysOfArrays))
+ {
+ cmm.Statements.Add(new CodeVariableDeclarationStatement(new CodeTypeReference(typeof(int[][])),
+ "arrayOfArrays", new CodeArrayCreateExpression(typeof(int[][]),
+ new CodeArrayCreateExpression(typeof(int[]), new CodePrimitiveExpression(3), new CodePrimitiveExpression(4)),
+ new CodeArrayCreateExpression(typeof(int[]), new CodeExpression[] { new CodePrimitiveExpression(1) }))));
+ cmm.Statements.Add(new CodeMethodReturnStatement(new CodeArrayIndexerExpression(
+ new CodeArrayIndexerExpression(new CodeVariableReferenceExpression("arrayOfArrays"), new CodePrimitiveExpression(0))
+ , new CodePrimitiveExpression(1))));
+ }
+ else
+ {
+ throw new Exception("not supported");
+ }
cd.Members.Add(cmm);
- }
- if (provider.Supports(GeneratorSupport.DeclareEnums))
- {
- CodeTypeDeclaration ce = new CodeTypeDeclaration("DecimalEnum");
- ce.IsEnum = true;
- nspace.Types.Add(ce);
+ // assembly attributes
+ if (provider.Supports(GeneratorSupport.AssemblyAttributes))
+ {
+ CodeAttributeDeclarationCollection attrs = cu.AssemblyCustomAttributes;
+ attrs.Add(new CodeAttributeDeclaration("System.Reflection.AssemblyTitle", new
+ CodeAttributeArgument(new CodePrimitiveExpression("MyAssembly"))));
+ attrs.Add(new CodeAttributeDeclaration("System.Reflection.AssemblyVersion", new
+ CodeAttributeArgument(new CodePrimitiveExpression("1.0.6.2"))));
+ }
- // things to enumerate
- for (int k = 0; k < 5; k++)
+ CodeTypeDeclaration class1 = new CodeTypeDeclaration();
+ if (provider.Supports(GeneratorSupport.ChainedConstructorArguments))
{
- CodeMemberField Field = new CodeMemberField("System.Int32", "Num" + (k).ToString());
- Field.InitExpression = new CodePrimitiveExpression(k);
- ce.Members.Add(Field);
+ class1.Name = "Test2";
+ class1.IsClass = true;
+ nspace.Types.Add(class1);
+
+ class1.Members.Add(new CodeMemberField(new CodeTypeReference(typeof(String)), "stringField"));
+ CodeMemberProperty prop = new CodeMemberProperty();
+ prop.Name = "accessStringField";
+ prop.Attributes = MemberAttributes.Public | MemberAttributes.Final;
+ prop.Type = new CodeTypeReference(typeof(String));
+ prop.GetStatements.Add(new CodeMethodReturnStatement(new CodeFieldReferenceExpression(new CodeThisReferenceExpression(),
+ "stringField")));
+ prop.SetStatements.Add(new CodeAssignStatement(new CodeFieldReferenceExpression(new
+ CodeThisReferenceExpression(), "stringField"),
+ new CodePropertySetValueReferenceExpression()));
+ class1.Members.Add(prop);
+
+ CodeConstructor cctor = new CodeConstructor();
+ cctor.Attributes = MemberAttributes.Public;
+ cctor.ChainedConstructorArgs.Add(new CodePrimitiveExpression("testingString"));
+ cctor.ChainedConstructorArgs.Add(new CodePrimitiveExpression(null));
+ cctor.ChainedConstructorArgs.Add(new CodePrimitiveExpression(null));
+ class1.Members.Add(cctor);
+
+ CodeConstructor cc = new CodeConstructor();
+ cc.Attributes = MemberAttributes.Public | MemberAttributes.Overloaded;
+ cc.Parameters.Add(new CodeParameterDeclarationExpression(typeof(string), "p1"));
+ cc.Parameters.Add(new CodeParameterDeclarationExpression(typeof(string), "p2"));
+ cc.Parameters.Add(new CodeParameterDeclarationExpression(typeof(string), "p3"));
+ cc.Statements.Add(new CodeAssignStatement(new CodeFieldReferenceExpression(new CodeThisReferenceExpression()
+ , "stringField"), new CodeVariableReferenceExpression("p1")));
+ class1.Members.Add(cc);
+ // verify chained constructors work
+ cmm = new CodeMemberMethod();
+ cmm.Name = "ChainedConstructorUse";
+ cmm.Attributes = MemberAttributes.Public | MemberAttributes.Static;
+ cmm.ReturnType = new CodeTypeReference(typeof(String));
+ // utilize constructor
+ cmm.Statements.Add(new CodeVariableDeclarationStatement("Test2", "t", new CodeObjectCreateExpression("Test2")));
+ cmm.Statements.Add(new CodeMethodReturnStatement(new CodeMethodReferenceExpression(
+ new CodeVariableReferenceExpression("t"), "accessStringField")));
+ cd.Members.Add(cmm);
}
- cmm = new CodeMemberMethod();
- cmm.Name = "OutputDecimalEnumVal";
- cmm.Attributes = MemberAttributes.Public | MemberAttributes.Static;
- CodeParameterDeclarationExpression param = new CodeParameterDeclarationExpression(typeof(int), "i");
- cmm.Parameters.Add(param);
- CodeBinaryOperatorExpression eq = new CodeBinaryOperatorExpression(
- new CodeVariableReferenceExpression("i"), CodeBinaryOperatorType.ValueEquality,
- new CodePrimitiveExpression(3));
- CodeMethodReturnStatement truestmt = new CodeMethodReturnStatement(
- new CodeCastExpression(typeof(int),
- new CodeFieldReferenceExpression(new CodeTypeReferenceExpression("DecimalEnum"), "Num3")));
- CodeConditionStatement condstmt = new CodeConditionStatement(eq, truestmt);
- cmm.Statements.Add(condstmt);
-
- eq = new CodeBinaryOperatorExpression(new CodeVariableReferenceExpression("i"),
- CodeBinaryOperatorType.ValueEquality, new CodePrimitiveExpression(4));
- truestmt = new CodeMethodReturnStatement(new CodeCastExpression(typeof(int),
- new CodeFieldReferenceExpression(new CodeTypeReferenceExpression("DecimalEnum"), "Num4")));
- condstmt = new CodeConditionStatement(eq, truestmt);
- cmm.Statements.Add(condstmt);
- eq = new CodeBinaryOperatorExpression(new CodeVariableReferenceExpression("i"),
- CodeBinaryOperatorType.ValueEquality, new CodePrimitiveExpression(2));
- truestmt = new CodeMethodReturnStatement(new CodeCastExpression(typeof(int),
- new CodeFieldReferenceExpression(new CodeTypeReferenceExpression("DecimalEnum"), "Num2")));
- condstmt = new CodeConditionStatement(eq, truestmt);
- cmm.Statements.Add(condstmt);
-
- eq = new CodeBinaryOperatorExpression(new CodeVariableReferenceExpression("i"),
- CodeBinaryOperatorType.ValueEquality, new CodePrimitiveExpression(1));
- truestmt = new CodeMethodReturnStatement(new CodeCastExpression(typeof(int),
- new CodeFieldReferenceExpression(new CodeTypeReferenceExpression("DecimalEnum"), "Num1")));
- condstmt = new CodeConditionStatement(eq, truestmt);
- cmm.Statements.Add(condstmt);
-
- eq = new CodeBinaryOperatorExpression(new CodeVariableReferenceExpression("i"),
- CodeBinaryOperatorType.ValueEquality, new CodePrimitiveExpression(0));
- truestmt = new CodeMethodReturnStatement(new CodeCastExpression(typeof(int),
- new CodeFieldReferenceExpression(new CodeTypeReferenceExpression("DecimalEnum"), "Num0")));
- condstmt = new CodeConditionStatement(eq, truestmt);
- cmm.Statements.Add(condstmt);
-
- cmm.ReturnType = new CodeTypeReference("System.int32");
-
- cmm.Statements.Add(new CodeMethodReturnStatement(new CodeBinaryOperatorExpression(
- new CodeVariableReferenceExpression("i"), CodeBinaryOperatorType.Add, new CodePrimitiveExpression(10))));
- cd.Members.Add(cmm);
- }
- if (provider.Supports(GeneratorSupport.DeclareInterfaces))
- {
- cmm = new CodeMemberMethod();
- cmm.Name = "TestSingleInterface";
- cmm.ReturnType = new CodeTypeReference(typeof(int));
- cmm.Parameters.Add(new CodeParameterDeclarationExpression(typeof(int), "i"));
- cmm.Attributes = MemberAttributes.Public | MemberAttributes.Static;
- cmm.Statements.Add(new CodeVariableDeclarationStatement("TestSingleInterfaceImp", "t", new CodeObjectCreateExpression("TestSingleInterfaceImp")));
- CodeMethodInvokeExpression methodinvoke = new CodeMethodInvokeExpression(new CodeVariableReferenceExpression("t")
- , "InterfaceMethod");
- methodinvoke.Parameters.Add(new CodeVariableReferenceExpression("i"));
- cmm.Statements.Add(new CodeMethodReturnStatement(methodinvoke));
- cd.Members.Add(cmm);
+ // complex expressions
+ if (provider.Supports(GeneratorSupport.ComplexExpressions))
+ {
+ cmm = new CodeMemberMethod();
+ cmm.Name = "ComplexExpressions";
+ cmm.ReturnType = new CodeTypeReference(typeof(int));
+ cmm.Attributes = MemberAttributes.Final | MemberAttributes.Public;
+ cmm.Parameters.Add(new CodeParameterDeclarationExpression(new CodeTypeReference(typeof(int)), "i"));
+ cmm.Statements.Add(new CodeAssignStatement(new CodeVariableReferenceExpression("i"),
+ new CodeBinaryOperatorExpression(new CodeVariableReferenceExpression("i"), CodeBinaryOperatorType.Multiply,
+ new CodeBinaryOperatorExpression(new CodeVariableReferenceExpression("i"), CodeBinaryOperatorType.Add,
+ new CodePrimitiveExpression(3)))));
+ cmm.Statements.Add(new CodeMethodReturnStatement(new CodeVariableReferenceExpression("i")));
+ cd.Members.Add(cmm);
+ }
- class1 = new CodeTypeDeclaration("InterfaceA");
- class1.IsInterface = true;
- nspace.Types.Add(class1);
- cmm = new CodeMemberMethod();
- cmm.Attributes = MemberAttributes.Public;
- cmm.Name = "InterfaceMethod";
- cmm.ReturnType = new CodeTypeReference(typeof(int));
- cmm.Parameters.Add(new CodeParameterDeclarationExpression(typeof(int), "a"));
- class1.Members.Add(cmm);
+ if (provider.Supports(GeneratorSupport.DeclareEnums))
+ {
+ CodeTypeDeclaration ce = new CodeTypeDeclaration("DecimalEnum");
+ ce.IsEnum = true;
+ nspace.Types.Add(ce);
+
+ // things to enumerate
+ for (int k = 0; k < 5; k++)
+ {
+ CodeMemberField Field = new CodeMemberField("System.Int32", "Num" + (k).ToString());
+ Field.InitExpression = new CodePrimitiveExpression(k);
+ ce.Members.Add(Field);
+ }
+ cmm = new CodeMemberMethod();
+ cmm.Name = "OutputDecimalEnumVal";
+ cmm.Attributes = MemberAttributes.Public | MemberAttributes.Static;
+ CodeParameterDeclarationExpression param = new CodeParameterDeclarationExpression(typeof(int), "i");
+ cmm.Parameters.Add(param);
+ CodeBinaryOperatorExpression eq = new CodeBinaryOperatorExpression(
+ new CodeVariableReferenceExpression("i"), CodeBinaryOperatorType.ValueEquality,
+ new CodePrimitiveExpression(3));
+ CodeMethodReturnStatement truestmt = new CodeMethodReturnStatement(
+ new CodeCastExpression(typeof(int),
+ new CodeFieldReferenceExpression(new CodeTypeReferenceExpression("DecimalEnum"), "Num3")));
+ CodeConditionStatement condstmt = new CodeConditionStatement(eq, truestmt);
+ cmm.Statements.Add(condstmt);
+
+ eq = new CodeBinaryOperatorExpression(new CodeVariableReferenceExpression("i"),
+ CodeBinaryOperatorType.ValueEquality, new CodePrimitiveExpression(4));
+ truestmt = new CodeMethodReturnStatement(new CodeCastExpression(typeof(int),
+ new CodeFieldReferenceExpression(new CodeTypeReferenceExpression("DecimalEnum"), "Num4")));
+ condstmt = new CodeConditionStatement(eq, truestmt);
+ cmm.Statements.Add(condstmt);
+ eq = new CodeBinaryOperatorExpression(new CodeVariableReferenceExpression("i"),
+ CodeBinaryOperatorType.ValueEquality, new CodePrimitiveExpression(2));
+ truestmt = new CodeMethodReturnStatement(new CodeCastExpression(typeof(int),
+ new CodeFieldReferenceExpression(new CodeTypeReferenceExpression("DecimalEnum"), "Num2")));
+ condstmt = new CodeConditionStatement(eq, truestmt);
+ cmm.Statements.Add(condstmt);
+
+ eq = new CodeBinaryOperatorExpression(new CodeVariableReferenceExpression("i"),
+ CodeBinaryOperatorType.ValueEquality, new CodePrimitiveExpression(1));
+ truestmt = new CodeMethodReturnStatement(new CodeCastExpression(typeof(int),
+ new CodeFieldReferenceExpression(new CodeTypeReferenceExpression("DecimalEnum"), "Num1")));
+ condstmt = new CodeConditionStatement(eq, truestmt);
+ cmm.Statements.Add(condstmt);
+
+ eq = new CodeBinaryOperatorExpression(new CodeVariableReferenceExpression("i"),
+ CodeBinaryOperatorType.ValueEquality, new CodePrimitiveExpression(0));
+ truestmt = new CodeMethodReturnStatement(new CodeCastExpression(typeof(int),
+ new CodeFieldReferenceExpression(new CodeTypeReferenceExpression("DecimalEnum"), "Num0")));
+ condstmt = new CodeConditionStatement(eq, truestmt);
+ cmm.Statements.Add(condstmt);
+
+ cmm.ReturnType = new CodeTypeReference("System.int32");
+
+ cmm.Statements.Add(new CodeMethodReturnStatement(new CodeBinaryOperatorExpression(
+ new CodeVariableReferenceExpression("i"), CodeBinaryOperatorType.Add, new CodePrimitiveExpression(10))));
+ cd.Members.Add(cmm);
+ }
- if (provider.Supports(GeneratorSupport.MultipleInterfaceMembers))
+ if (provider.Supports(GeneratorSupport.DeclareInterfaces))
{
- CodeTypeDeclaration classDecl = new CodeTypeDeclaration("InterfaceB");
- classDecl.IsInterface = true;
- nspace.Types.Add(classDecl);
cmm = new CodeMemberMethod();
- cmm.Name = "InterfaceMethod";
+ cmm.Name = "TestSingleInterface";
+ cmm.ReturnType = new CodeTypeReference(typeof(int));
+ cmm.Parameters.Add(new CodeParameterDeclarationExpression(typeof(int), "i"));
+ cmm.Attributes = MemberAttributes.Public | MemberAttributes.Static;
+ cmm.Statements.Add(new CodeVariableDeclarationStatement("TestSingleInterfaceImp", "t", new CodeObjectCreateExpression("TestSingleInterfaceImp")));
+ CodeMethodInvokeExpression methodinvoke = new CodeMethodInvokeExpression(new CodeVariableReferenceExpression("t")
+ , "InterfaceMethod");
+ methodinvoke.Parameters.Add(new CodeVariableReferenceExpression("i"));
+ cmm.Statements.Add(new CodeMethodReturnStatement(methodinvoke));
+ cd.Members.Add(cmm);
+
+ class1 = new CodeTypeDeclaration("InterfaceA");
+ class1.IsInterface = true;
+ nspace.Types.Add(class1);
+ cmm = new CodeMemberMethod();
cmm.Attributes = MemberAttributes.Public;
+ cmm.Name = "InterfaceMethod";
cmm.ReturnType = new CodeTypeReference(typeof(int));
cmm.Parameters.Add(new CodeParameterDeclarationExpression(typeof(int), "a"));
- classDecl.Members.Add(cmm);
-
- CodeTypeDeclaration class2 = new CodeTypeDeclaration("TestMultipleInterfaceImp");
- class2.BaseTypes.Add(new CodeTypeReference("System.Object"));
- class2.BaseTypes.Add(new CodeTypeReference("InterfaceB"));
- class2.BaseTypes.Add(new CodeTypeReference("InterfaceA"));
- class2.IsClass = true;
- nspace.Types.Add(class2);
+ class1.Members.Add(cmm);
+
+ if (provider.Supports(GeneratorSupport.MultipleInterfaceMembers))
+ {
+ CodeTypeDeclaration classDecl = new CodeTypeDeclaration("InterfaceB");
+ classDecl.IsInterface = true;
+ nspace.Types.Add(classDecl);
+ cmm = new CodeMemberMethod();
+ cmm.Name = "InterfaceMethod";
+ cmm.Attributes = MemberAttributes.Public;
+ cmm.ReturnType = new CodeTypeReference(typeof(int));
+ cmm.Parameters.Add(new CodeParameterDeclarationExpression(typeof(int), "a"));
+ classDecl.Members.Add(cmm);
+
+ CodeTypeDeclaration class2 = new CodeTypeDeclaration("TestMultipleInterfaceImp");
+ class2.BaseTypes.Add(new CodeTypeReference("System.Object"));
+ class2.BaseTypes.Add(new CodeTypeReference("InterfaceB"));
+ class2.BaseTypes.Add(new CodeTypeReference("InterfaceA"));
+ class2.IsClass = true;
+ nspace.Types.Add(class2);
+ cmm = new CodeMemberMethod();
+ cmm.ImplementationTypes.Add(new CodeTypeReference("InterfaceA"));
+ cmm.ImplementationTypes.Add(new CodeTypeReference("InterfaceB"));
+ cmm.Name = "InterfaceMethod";
+ cmm.ReturnType = new CodeTypeReference(typeof(int));
+ cmm.Parameters.Add(new CodeParameterDeclarationExpression(typeof(int), "a"));
+ cmm.Attributes = MemberAttributes.Public | MemberAttributes.Final;
+ cmm.Statements.Add(new CodeMethodReturnStatement(new CodeVariableReferenceExpression("a")));
+ class2.Members.Add(cmm);
+
+ cmm = new CodeMemberMethod();
+ cmm.Name = "TestMultipleInterfaces";
+ cmm.ReturnType = new CodeTypeReference(typeof(int));
+ cmm.Parameters.Add(new CodeParameterDeclarationExpression(typeof(int), "i"));
+ cmm.Attributes = MemberAttributes.Public | MemberAttributes.Static;
+ cmm.Statements.Add(new CodeVariableDeclarationStatement("TestMultipleInterfaceImp", "t", new CodeObjectCreateExpression("TestMultipleInterfaceImp")));
+ cmm.Statements.Add(new CodeVariableDeclarationStatement("InterfaceA", "interfaceAobject", new CodeCastExpression("InterfaceA",
+ new CodeVariableReferenceExpression("t"))));
+ cmm.Statements.Add(new CodeVariableDeclarationStatement("InterfaceB", "interfaceBobject", new CodeCastExpression("InterfaceB",
+ new CodeVariableReferenceExpression("t"))));
+ methodinvoke = new CodeMethodInvokeExpression(new CodeVariableReferenceExpression("interfaceAobject")
+ , "InterfaceMethod");
+ methodinvoke.Parameters.Add(new CodeVariableReferenceExpression("i"));
+ CodeMethodInvokeExpression methodinvoke2 = new CodeMethodInvokeExpression(new CodeVariableReferenceExpression("interfaceBobject")
+ , "InterfaceMethod");
+ methodinvoke2.Parameters.Add(new CodeVariableReferenceExpression("i"));
+ cmm.Statements.Add(new CodeMethodReturnStatement(new CodeBinaryOperatorExpression(
+ methodinvoke,
+ CodeBinaryOperatorType.Subtract, methodinvoke2)));
+ cd.Members.Add(cmm);
+ }
+
+ class1 = new CodeTypeDeclaration("TestSingleInterfaceImp");
+ class1.BaseTypes.Add(new CodeTypeReference("System.Object"));
+ class1.BaseTypes.Add(new CodeTypeReference("InterfaceA"));
+ class1.IsClass = true;
+ nspace.Types.Add(class1);
cmm = new CodeMemberMethod();
cmm.ImplementationTypes.Add(new CodeTypeReference("InterfaceA"));
- cmm.ImplementationTypes.Add(new CodeTypeReference("InterfaceB"));
cmm.Name = "InterfaceMethod";
cmm.ReturnType = new CodeTypeReference(typeof(int));
cmm.Parameters.Add(new CodeParameterDeclarationExpression(typeof(int), "a"));
- cmm.Attributes = MemberAttributes.Public | MemberAttributes.Final;
+ cmm.Attributes = MemberAttributes.Public;
cmm.Statements.Add(new CodeMethodReturnStatement(new CodeVariableReferenceExpression("a")));
- class2.Members.Add(cmm);
+ class1.Members.Add(cmm);
+ }
+ if (provider.Supports(GeneratorSupport.DeclareValueTypes))
+ {
+ CodeTypeDeclaration structA = new CodeTypeDeclaration("structA");
+ structA.IsStruct = true;
+
+ CodeTypeDeclaration structB = new CodeTypeDeclaration("structB");
+ structB.Attributes = MemberAttributes.Public;
+ structB.IsStruct = true;
+
+ CodeMemberField firstInt = new CodeMemberField(typeof(int), "int1");
+ firstInt.Attributes = MemberAttributes.Public;
+ structB.Members.Add(firstInt);
+
+ CodeMemberField innerStruct = new CodeMemberField("structB", "innerStruct");
+ innerStruct.Attributes = MemberAttributes.Public;
+
+ structA.Members.Add(structB);
+ structA.Members.Add(innerStruct);
+ nspace.Types.Add(structA);
+
+ CodeMemberMethod nestedStructMethod = new CodeMemberMethod();
+ nestedStructMethod.Name = "NestedStructMethod";
+ nestedStructMethod.ReturnType = new CodeTypeReference(typeof(int));
+ nestedStructMethod.Attributes = MemberAttributes.Public | MemberAttributes.Static;
+ CodeVariableDeclarationStatement varStructA = new CodeVariableDeclarationStatement("structA", "varStructA");
+ nestedStructMethod.Statements.Add(varStructA);
+ nestedStructMethod.Statements.Add
+ (
+ new CodeAssignStatement
+ (
+ /* Expression1 */ new CodeFieldReferenceExpression(new CodeFieldReferenceExpression(new CodeVariableReferenceExpression("varStructA"), "innerStruct"), "int1"),
+ /* Expression1 */ new CodePrimitiveExpression(3)
+ )
+ );
+ nestedStructMethod.Statements.Add(new CodeMethodReturnStatement(new CodeFieldReferenceExpression(new CodeFieldReferenceExpression(new CodeVariableReferenceExpression("varStructA"), "innerStruct"), "int1")));
+ cd.Members.Add(nestedStructMethod);
+ }
+
+ if (provider.Supports(GeneratorSupport.EntryPointMethod))
+ {
+ CodeEntryPointMethod cep = new CodeEntryPointMethod();
+ cd.Members.Add(cep);
+ }
+
+ // goto statements
+ if (provider.Supports(GeneratorSupport.GotoStatements))
+ {
cmm = new CodeMemberMethod();
- cmm.Name = "TestMultipleInterfaces";
+ cmm.Name = "GoToMethod";
cmm.ReturnType = new CodeTypeReference(typeof(int));
- cmm.Parameters.Add(new CodeParameterDeclarationExpression(typeof(int), "i"));
- cmm.Attributes = MemberAttributes.Public | MemberAttributes.Static;
- cmm.Statements.Add(new CodeVariableDeclarationStatement("TestMultipleInterfaceImp", "t", new CodeObjectCreateExpression("TestMultipleInterfaceImp")));
- cmm.Statements.Add(new CodeVariableDeclarationStatement("InterfaceA", "interfaceAobject", new CodeCastExpression("InterfaceA",
- new CodeVariableReferenceExpression("t"))));
- cmm.Statements.Add(new CodeVariableDeclarationStatement("InterfaceB", "interfaceBobject", new CodeCastExpression("InterfaceB",
- new CodeVariableReferenceExpression("t"))));
- methodinvoke = new CodeMethodInvokeExpression(new CodeVariableReferenceExpression("interfaceAobject")
- , "InterfaceMethod");
- methodinvoke.Parameters.Add(new CodeVariableReferenceExpression("i"));
- CodeMethodInvokeExpression methodinvoke2 = new CodeMethodInvokeExpression(new CodeVariableReferenceExpression("interfaceBobject")
- , "InterfaceMethod");
- methodinvoke2.Parameters.Add(new CodeVariableReferenceExpression("i"));
- cmm.Statements.Add(new CodeMethodReturnStatement(new CodeBinaryOperatorExpression(
- methodinvoke,
- CodeBinaryOperatorType.Subtract, methodinvoke2)));
+ cmm.Attributes = MemberAttributes.Public | MemberAttributes.Final;
+ CodeParameterDeclarationExpression param = new CodeParameterDeclarationExpression(typeof(int), "i");
+ cmm.Parameters.Add(param);
+ CodeConditionStatement condstmt = new CodeConditionStatement(new CodeBinaryOperatorExpression(
+ new CodeVariableReferenceExpression("i"), CodeBinaryOperatorType.LessThan, new CodePrimitiveExpression(1)),
+ new CodeGotoStatement("comehere"));
+ cmm.Statements.Add(condstmt);
+ cmm.Statements.Add(new CodeMethodReturnStatement(new CodePrimitiveExpression(6)));
+ cmm.Statements.Add(new CodeLabeledStatement("comehere",
+ new CodeMethodReturnStatement(new CodePrimitiveExpression(7))));
cd.Members.Add(cmm);
}
- class1 = new CodeTypeDeclaration("TestSingleInterfaceImp");
- class1.BaseTypes.Add(new CodeTypeReference("System.Object"));
- class1.BaseTypes.Add(new CodeTypeReference("InterfaceA"));
- class1.IsClass = true;
- nspace.Types.Add(class1);
- cmm = new CodeMemberMethod();
- cmm.ImplementationTypes.Add(new CodeTypeReference("InterfaceA"));
- cmm.Name = "InterfaceMethod";
- cmm.ReturnType = new CodeTypeReference(typeof(int));
- cmm.Parameters.Add(new CodeParameterDeclarationExpression(typeof(int), "a"));
- cmm.Attributes = MemberAttributes.Public;
- cmm.Statements.Add(new CodeMethodReturnStatement(new CodeVariableReferenceExpression("a")));
- class1.Members.Add(cmm);
- }
-
- if (provider.Supports(GeneratorSupport.DeclareValueTypes))
- {
- CodeTypeDeclaration structA = new CodeTypeDeclaration("structA");
- structA.IsStruct = true;
-
- CodeTypeDeclaration structB = new CodeTypeDeclaration("structB");
- structB.Attributes = MemberAttributes.Public;
- structB.IsStruct = true;
-
- CodeMemberField firstInt = new CodeMemberField(typeof(int), "int1");
- firstInt.Attributes = MemberAttributes.Public;
- structB.Members.Add(firstInt);
-
- CodeMemberField innerStruct = new CodeMemberField("structB", "innerStruct");
- innerStruct.Attributes = MemberAttributes.Public;
-
- structA.Members.Add(structB);
- structA.Members.Add(innerStruct);
- nspace.Types.Add(structA);
-
- CodeMemberMethod nestedStructMethod = new CodeMemberMethod();
- nestedStructMethod.Name = "NestedStructMethod";
- nestedStructMethod.ReturnType = new CodeTypeReference(typeof(int));
- nestedStructMethod.Attributes = MemberAttributes.Public | MemberAttributes.Static;
- CodeVariableDeclarationStatement varStructA = new CodeVariableDeclarationStatement("structA", "varStructA");
- nestedStructMethod.Statements.Add(varStructA);
- nestedStructMethod.Statements.Add
- (
- new CodeAssignStatement
- (
- /* Expression1 */ new CodeFieldReferenceExpression(new CodeFieldReferenceExpression(new CodeVariableReferenceExpression("varStructA"), "innerStruct"), "int1"),
- /* Expression1 */ new CodePrimitiveExpression(3)
- )
- );
- nestedStructMethod.Statements.Add(new CodeMethodReturnStatement(new CodeFieldReferenceExpression(new CodeFieldReferenceExpression(new CodeVariableReferenceExpression("varStructA"), "innerStruct"), "int1")));
- cd.Members.Add(nestedStructMethod);
- }
-
- if (provider.Supports(GeneratorSupport.EntryPointMethod))
- {
- CodeEntryPointMethod cep = new CodeEntryPointMethod();
- cd.Members.Add(cep);
- }
-
- // goto statements
- if (provider.Supports(GeneratorSupport.GotoStatements))
- {
- cmm = new CodeMemberMethod();
- cmm.Name = "GoToMethod";
- cmm.ReturnType = new CodeTypeReference(typeof(int));
- cmm.Attributes = MemberAttributes.Public | MemberAttributes.Final;
- CodeParameterDeclarationExpression param = new CodeParameterDeclarationExpression(typeof(int), "i");
- cmm.Parameters.Add(param);
- CodeConditionStatement condstmt = new CodeConditionStatement(new CodeBinaryOperatorExpression(
- new CodeVariableReferenceExpression("i"), CodeBinaryOperatorType.LessThan, new CodePrimitiveExpression(1)),
- new CodeGotoStatement("comehere"));
- cmm.Statements.Add(condstmt);
- cmm.Statements.Add(new CodeMethodReturnStatement(new CodePrimitiveExpression(6)));
- cmm.Statements.Add(new CodeLabeledStatement("comehere",
- new CodeMethodReturnStatement(new CodePrimitiveExpression(7))));
- cd.Members.Add(cmm);
- }
-
- if (provider.Supports(GeneratorSupport.NestedTypes))
- {
- cmm = new CodeMemberMethod();
- cmm.Name = "CallingPublicNestedScenario";
- cmm.Parameters.Add(new CodeParameterDeclarationExpression(typeof(int), "i"));
- cmm.ReturnType = new CodeTypeReference(typeof(int));
- cmm.Attributes = MemberAttributes.Public | MemberAttributes.Static;
- cmm.Statements.Add(new CodeVariableDeclarationStatement(new CodeTypeReference
- ("PublicNestedClassA+PublicNestedClassB2+PublicNestedClassC"), "t",
- new CodeObjectCreateExpression(new CodeTypeReference
- ("PublicNestedClassA+PublicNestedClassB2+PublicNestedClassC"))));
- cmm.Statements.Add(new CodeMethodReturnStatement(new CodeMethodInvokeExpression(new CodeVariableReferenceExpression("t"),
- "publicNestedClassesMethod",
- new CodeVariableReferenceExpression("i"))));
- cd.Members.Add(cmm);
-
- class1 = new CodeTypeDeclaration("PublicNestedClassA");
- class1.IsClass = true;
- nspace.Types.Add(class1);
- CodeTypeDeclaration nestedClass = new CodeTypeDeclaration("PublicNestedClassB1");
- nestedClass.IsClass = true;
- nestedClass.TypeAttributes = TypeAttributes.NestedPublic;
- class1.Members.Add(nestedClass);
- nestedClass = new CodeTypeDeclaration("PublicNestedClassB2");
- nestedClass.TypeAttributes = TypeAttributes.NestedPublic;
- nestedClass.IsClass = true;
- class1.Members.Add(nestedClass);
- CodeTypeDeclaration innerNestedClass = new CodeTypeDeclaration("PublicNestedClassC");
- innerNestedClass.TypeAttributes = TypeAttributes.NestedPublic;
- innerNestedClass.IsClass = true;
- nestedClass.Members.Add(innerNestedClass);
- cmm = new CodeMemberMethod();
- cmm.Name = "publicNestedClassesMethod";
- cmm.ReturnType = new CodeTypeReference(typeof(int));
- cmm.Parameters.Add(new CodeParameterDeclarationExpression(typeof(int), "a"));
- cmm.Attributes = MemberAttributes.Public | MemberAttributes.Final;
- cmm.Statements.Add(new CodeMethodReturnStatement(new CodeVariableReferenceExpression("a")));
- innerNestedClass.Members.Add(cmm);
- }
-
- // Parameter Attributes
- if (provider.Supports(GeneratorSupport.ParameterAttributes))
- {
- CodeMemberMethod method1 = new CodeMemberMethod();
- method1.Name = "MyMethod";
- method1.Attributes = MemberAttributes.Public | MemberAttributes.Final;
- CodeParameterDeclarationExpression param1 = new CodeParameterDeclarationExpression(typeof(string), "blah");
- param1.CustomAttributes.Add(
- new CodeAttributeDeclaration(
- "System.Xml.Serialization.XmlElementAttribute",
- new CodeAttributeArgument(
- "Form",
- new CodeFieldReferenceExpression(new CodeTypeReferenceExpression("System.Xml.Schema.XmlSchemaForm"), "Unqualified")),
- new CodeAttributeArgument(
- "IsNullable",
- new CodePrimitiveExpression(false))));
- method1.Parameters.Add(param1);
- cd.Members.Add(method1);
- }
-
- // public static members
- if (provider.Supports(GeneratorSupport.PublicStaticMembers))
- {
- cmm = new CodeMemberMethod();
- cmm.Name = "PublicStaticMethod";
- cmm.ReturnType = new CodeTypeReference(typeof(int));
- cmm.Attributes = MemberAttributes.Public | MemberAttributes.Static;
- cmm.Statements.Add(new CodeMethodReturnStatement(new CodePrimitiveExpression(16)));
- cd.Members.Add(cmm);
- }
+ if (provider.Supports(GeneratorSupport.NestedTypes))
+ {
+ cmm = new CodeMemberMethod();
+ cmm.Name = "CallingPublicNestedScenario";
+ cmm.Parameters.Add(new CodeParameterDeclarationExpression(typeof(int), "i"));
+ cmm.ReturnType = new CodeTypeReference(typeof(int));
+ cmm.Attributes = MemberAttributes.Public | MemberAttributes.Static;
+ cmm.Statements.Add(new CodeVariableDeclarationStatement(new CodeTypeReference
+ ("PublicNestedClassA+PublicNestedClassB2+PublicNestedClassC"), "t",
+ new CodeObjectCreateExpression(new CodeTypeReference
+ ("PublicNestedClassA+PublicNestedClassB2+PublicNestedClassC"))));
+ cmm.Statements.Add(new CodeMethodReturnStatement(new CodeMethodInvokeExpression(new CodeVariableReferenceExpression("t"),
+ "publicNestedClassesMethod",
+ new CodeVariableReferenceExpression("i"))));
+ cd.Members.Add(cmm);
- // reference parameters
- if (provider.Supports(GeneratorSupport.ReferenceParameters))
- {
- cmm = new CodeMemberMethod();
- cmm.Name = "Work";
- cmm.ReturnType = new CodeTypeReference("System.void");
- cmm.Attributes = MemberAttributes.Static;
- // add parameter with ref direction
- CodeParameterDeclarationExpression param = new CodeParameterDeclarationExpression(typeof(int), "i");
- param.Direction = FieldDirection.Ref;
- cmm.Parameters.Add(param);
- // add parameter with out direction
- param = new CodeParameterDeclarationExpression(typeof(int), "j");
- param.Direction = FieldDirection.Out;
- cmm.Parameters.Add(param);
- cmm.Statements.Add(new CodeAssignStatement(new CodeArgumentReferenceExpression("i"),
- new CodeBinaryOperatorExpression(new CodeArgumentReferenceExpression("i"),
- CodeBinaryOperatorType.Add, new CodePrimitiveExpression(4))));
- cmm.Statements.Add(new CodeAssignStatement(new CodeArgumentReferenceExpression("j"),
- new CodePrimitiveExpression(5)));
- cd.Members.Add(cmm);
+ class1 = new CodeTypeDeclaration("PublicNestedClassA");
+ class1.IsClass = true;
+ nspace.Types.Add(class1);
+ CodeTypeDeclaration nestedClass = new CodeTypeDeclaration("PublicNestedClassB1");
+ nestedClass.IsClass = true;
+ nestedClass.TypeAttributes = TypeAttributes.NestedPublic;
+ class1.Members.Add(nestedClass);
+ nestedClass = new CodeTypeDeclaration("PublicNestedClassB2");
+ nestedClass.TypeAttributes = TypeAttributes.NestedPublic;
+ nestedClass.IsClass = true;
+ class1.Members.Add(nestedClass);
+ CodeTypeDeclaration innerNestedClass = new CodeTypeDeclaration("PublicNestedClassC");
+ innerNestedClass.TypeAttributes = TypeAttributes.NestedPublic;
+ innerNestedClass.IsClass = true;
+ nestedClass.Members.Add(innerNestedClass);
+ cmm = new CodeMemberMethod();
+ cmm.Name = "publicNestedClassesMethod";
+ cmm.ReturnType = new CodeTypeReference(typeof(int));
+ cmm.Parameters.Add(new CodeParameterDeclarationExpression(typeof(int), "a"));
+ cmm.Attributes = MemberAttributes.Public | MemberAttributes.Final;
+ cmm.Statements.Add(new CodeMethodReturnStatement(new CodeVariableReferenceExpression("a")));
+ innerNestedClass.Members.Add(cmm);
+ }
- cmm = new CodeMemberMethod();
- cmm.Name = "CallingWork";
- cmm.Attributes = MemberAttributes.Public | MemberAttributes.Static;
- CodeParameterDeclarationExpression parames = new CodeParameterDeclarationExpression(typeof(int), "a");
- cmm.Parameters.Add(parames);
- cmm.ReturnType = new CodeTypeReference("System.int32");
- cmm.Statements.Add(new CodeAssignStatement(new CodeVariableReferenceExpression("a"),
- new CodePrimitiveExpression(10)));
- cmm.Statements.Add(new CodeVariableDeclarationStatement(typeof(int), "b"));
- // invoke the method called "work"
- CodeMethodInvokeExpression methodinvoked = new CodeMethodInvokeExpression(new CodeMethodReferenceExpression
- (new CodeTypeReferenceExpression("TEST"), "Work"));
- // add parameter with ref direction
- CodeDirectionExpression parameter = new CodeDirectionExpression(FieldDirection.Ref,
- new CodeVariableReferenceExpression("a"));
- methodinvoked.Parameters.Add(parameter);
- // add parameter with out direction
- parameter = new CodeDirectionExpression(FieldDirection.Out, new CodeVariableReferenceExpression("b"));
- methodinvoked.Parameters.Add(parameter);
- cmm.Statements.Add(methodinvoked);
- cmm.Statements.Add(new CodeMethodReturnStatement(new CodeBinaryOperatorExpression
- (new CodeVariableReferenceExpression("a"), CodeBinaryOperatorType.Add, new CodeVariableReferenceExpression("b"))));
- cd.Members.Add(cmm);
- }
+ // Parameter Attributes
+ if (provider.Supports(GeneratorSupport.ParameterAttributes))
+ {
+ CodeMemberMethod method1 = new CodeMemberMethod();
+ method1.Name = "MyMethod";
+ method1.Attributes = MemberAttributes.Public | MemberAttributes.Final;
+ CodeParameterDeclarationExpression param1 = new CodeParameterDeclarationExpression(typeof(string), "blah");
+ param1.CustomAttributes.Add(
+ new CodeAttributeDeclaration(
+ "System.Xml.Serialization.XmlElementAttribute",
+ new CodeAttributeArgument(
+ "Form",
+ new CodeFieldReferenceExpression(new CodeTypeReferenceExpression("System.Xml.Schema.XmlSchemaForm"), "Unqualified")),
+ new CodeAttributeArgument(
+ "IsNullable",
+ new CodePrimitiveExpression(false))));
+ method1.Parameters.Add(param1);
+ cd.Members.Add(method1);
+ }
- if (provider.Supports(GeneratorSupport.ReturnTypeAttributes))
- {
- CodeMemberMethod function1 = new CodeMemberMethod();
- function1.Name = "MyFunction";
- function1.ReturnType = new CodeTypeReference(typeof(string));
- function1.Attributes = MemberAttributes.Public | MemberAttributes.Final;
- function1.ReturnTypeCustomAttributes.Add(new
- CodeAttributeDeclaration("System.Xml.Serialization.XmlIgnoreAttribute"));
- function1.ReturnTypeCustomAttributes.Add(new CodeAttributeDeclaration("System.Xml.Serialization.XmlRootAttribute", new
- CodeAttributeArgument("Namespace", new CodePrimitiveExpression("Namespace Value")), new
- CodeAttributeArgument("ElementName", new CodePrimitiveExpression("Root, hehehe"))));
- function1.Statements.Add(new CodeMethodReturnStatement(new CodePrimitiveExpression("Return")));
- cd.Members.Add(function1);
- }
+ // public static members
+ if (provider.Supports(GeneratorSupport.PublicStaticMembers))
+ {
+ cmm = new CodeMemberMethod();
+ cmm.Name = "PublicStaticMethod";
+ cmm.ReturnType = new CodeTypeReference(typeof(int));
+ cmm.Attributes = MemberAttributes.Public | MemberAttributes.Static;
+ cmm.Statements.Add(new CodeMethodReturnStatement(new CodePrimitiveExpression(16)));
+ cd.Members.Add(cmm);
+ }
- if (provider.Supports(GeneratorSupport.StaticConstructors))
- {
- cmm = new CodeMemberMethod();
- cmm.Name = "TestStaticConstructor";
- cmm.Attributes = MemberAttributes.Public | MemberAttributes.Static;
- cmm.ReturnType = new CodeTypeReference(typeof(int));
- CodeParameterDeclarationExpression param = new CodeParameterDeclarationExpression(typeof(int), "a");
- cmm.Parameters.Add(param);
- // utilize constructor
- cmm.Statements.Add(new CodeVariableDeclarationStatement("Test4", "t", new CodeObjectCreateExpression("Test4")));
- // set then get number
- cmm.Statements.Add(new CodeAssignStatement(new CodePropertyReferenceExpression(new CodeVariableReferenceExpression("t"), "i")
- , new CodeVariableReferenceExpression("a")));
- cmm.Statements.Add(new CodeMethodReturnStatement(new CodeMethodReferenceExpression(
- new CodeVariableReferenceExpression("t"), "i")));
- cd.Members.Add(cmm);
+ // reference parameters
+ if (provider.Supports(GeneratorSupport.ReferenceParameters))
+ {
+ cmm = new CodeMemberMethod();
+ cmm.Name = "Work";
+ cmm.ReturnType = new CodeTypeReference("System.void");
+ cmm.Attributes = MemberAttributes.Static;
+ // add parameter with ref direction
+ CodeParameterDeclarationExpression param = new CodeParameterDeclarationExpression(typeof(int), "i");
+ param.Direction = FieldDirection.Ref;
+ cmm.Parameters.Add(param);
+ // add parameter with out direction
+ param = new CodeParameterDeclarationExpression(typeof(int), "j");
+ param.Direction = FieldDirection.Out;
+ cmm.Parameters.Add(param);
+ cmm.Statements.Add(new CodeAssignStatement(new CodeArgumentReferenceExpression("i"),
+ new CodeBinaryOperatorExpression(new CodeArgumentReferenceExpression("i"),
+ CodeBinaryOperatorType.Add, new CodePrimitiveExpression(4))));
+ cmm.Statements.Add(new CodeAssignStatement(new CodeArgumentReferenceExpression("j"),
+ new CodePrimitiveExpression(5)));
+ cd.Members.Add(cmm);
- class1 = new CodeTypeDeclaration();
- class1.Name = "Test4";
- class1.IsClass = true;
- nspace.Types.Add(class1);
-
- class1.Members.Add(new CodeMemberField(new CodeTypeReference(typeof(int)), "number"));
- CodeMemberProperty prop = new CodeMemberProperty();
- prop.Name = "i";
- prop.Attributes = MemberAttributes.Public | MemberAttributes.Final;
- prop.Type = new CodeTypeReference(typeof(int));
- prop.GetStatements.Add(new CodeMethodReturnStatement(new CodeVariableReferenceExpression("number")));
- prop.SetStatements.Add(new CodeAssignStatement(new CodeVariableReferenceExpression("number"),
- new CodePropertySetValueReferenceExpression()));
- class1.Members.Add(prop);
- CodeTypeConstructor ctc = new CodeTypeConstructor();
- class1.Members.Add(ctc);
- }
+ cmm = new CodeMemberMethod();
+ cmm.Name = "CallingWork";
+ cmm.Attributes = MemberAttributes.Public | MemberAttributes.Static;
+ CodeParameterDeclarationExpression parames = new CodeParameterDeclarationExpression(typeof(int), "a");
+ cmm.Parameters.Add(parames);
+ cmm.ReturnType = new CodeTypeReference("System.int32");
+ cmm.Statements.Add(new CodeAssignStatement(new CodeVariableReferenceExpression("a"),
+ new CodePrimitiveExpression(10)));
+ cmm.Statements.Add(new CodeVariableDeclarationStatement(typeof(int), "b"));
+ // invoke the method called "work"
+ CodeMethodInvokeExpression methodinvoked = new CodeMethodInvokeExpression(new CodeMethodReferenceExpression
+ (new CodeTypeReferenceExpression("TEST"), "Work"));
+ // add parameter with ref direction
+ CodeDirectionExpression parameter = new CodeDirectionExpression(FieldDirection.Ref,
+ new CodeVariableReferenceExpression("a"));
+ methodinvoked.Parameters.Add(parameter);
+ // add parameter with out direction
+ parameter = new CodeDirectionExpression(FieldDirection.Out, new CodeVariableReferenceExpression("b"));
+ methodinvoked.Parameters.Add(parameter);
+ cmm.Statements.Add(methodinvoked);
+ cmm.Statements.Add(new CodeMethodReturnStatement(new CodeBinaryOperatorExpression
+ (new CodeVariableReferenceExpression("a"), CodeBinaryOperatorType.Add, new CodeVariableReferenceExpression("b"))));
+ cd.Members.Add(cmm);
+ }
- if (provider.Supports(GeneratorSupport.TryCatchStatements))
- {
- cmm = new CodeMemberMethod();
- cmm.Name = "TryCatchMethod";
- cmm.ReturnType = new CodeTypeReference(typeof(int));
- cmm.Attributes = MemberAttributes.Public | MemberAttributes.Static;
- CodeParameterDeclarationExpression param = new CodeParameterDeclarationExpression(typeof(int), "a");
- cmm.Parameters.Add(param);
-
- CodeTryCatchFinallyStatement tcfstmt = new CodeTryCatchFinallyStatement();
- tcfstmt.FinallyStatements.Add(new CodeAssignStatement(new CodeVariableReferenceExpression("a"), new
- CodeBinaryOperatorExpression(new CodeVariableReferenceExpression("a"), CodeBinaryOperatorType.Add,
- new CodePrimitiveExpression(5))));
- cmm.Statements.Add(tcfstmt);
- cmm.Statements.Add(new CodeMethodReturnStatement(new CodeVariableReferenceExpression("a")));
- cd.Members.Add(cmm);
- }
+ if (provider.Supports(GeneratorSupport.ReturnTypeAttributes))
+ {
+ CodeMemberMethod function1 = new CodeMemberMethod();
+ function1.Name = "MyFunction";
+ function1.ReturnType = new CodeTypeReference(typeof(string));
+ function1.Attributes = MemberAttributes.Public | MemberAttributes.Final;
+ function1.ReturnTypeCustomAttributes.Add(new
+ CodeAttributeDeclaration("System.Xml.Serialization.XmlIgnoreAttribute"));
+ function1.ReturnTypeCustomAttributes.Add(new CodeAttributeDeclaration("System.Xml.Serialization.XmlRootAttribute", new
+ CodeAttributeArgument("Namespace", new CodePrimitiveExpression("Namespace Value")), new
+ CodeAttributeArgument("ElementName", new CodePrimitiveExpression("Root, hehehe"))));
+ function1.Statements.Add(new CodeMethodReturnStatement(new CodePrimitiveExpression("Return")));
+ cd.Members.Add(function1);
+ }
- if (provider.Supports(GeneratorSupport.DeclareEvents))
- {
- CodeNamespace ns = new CodeNamespace();
- ns.Name = "MyNamespace";
- ns.Imports.Add(new CodeNamespaceImport("System"));
- ns.Imports.Add(new CodeNamespaceImport("System.Drawing"));
- ns.Imports.Add(new CodeNamespaceImport("System.Windows.Forms"));
- ns.Imports.Add(new CodeNamespaceImport("System.ComponentModel"));
- cu.Namespaces.Add(ns);
- class1 = new CodeTypeDeclaration("Test");
- class1.IsClass = true;
- class1.BaseTypes.Add(new CodeTypeReference("Form"));
- ns.Types.Add(class1);
+ if (provider.Supports(GeneratorSupport.StaticConstructors))
+ {
+ cmm = new CodeMemberMethod();
+ cmm.Name = "TestStaticConstructor";
+ cmm.Attributes = MemberAttributes.Public | MemberAttributes.Static;
+ cmm.ReturnType = new CodeTypeReference(typeof(int));
+ CodeParameterDeclarationExpression param = new CodeParameterDeclarationExpression(typeof(int), "a");
+ cmm.Parameters.Add(param);
+ // utilize constructor
+ cmm.Statements.Add(new CodeVariableDeclarationStatement("Test4", "t", new CodeObjectCreateExpression("Test4")));
+ // set then get number
+ cmm.Statements.Add(new CodeAssignStatement(new CodePropertyReferenceExpression(new CodeVariableReferenceExpression("t"), "i")
+ , new CodeVariableReferenceExpression("a")));
+ cmm.Statements.Add(new CodeMethodReturnStatement(new CodeMethodReferenceExpression(
+ new CodeVariableReferenceExpression("t"), "i")));
+ cd.Members.Add(cmm);
- CodeMemberField mfield = new CodeMemberField(new CodeTypeReference("Button"), "b");
- mfield.InitExpression = new CodeObjectCreateExpression(new CodeTypeReference("Button"));
- class1.Members.Add(mfield);
+ class1 = new CodeTypeDeclaration();
+ class1.Name = "Test4";
+ class1.IsClass = true;
+ nspace.Types.Add(class1);
+
+ class1.Members.Add(new CodeMemberField(new CodeTypeReference(typeof(int)), "number"));
+ CodeMemberProperty prop = new CodeMemberProperty();
+ prop.Name = "i";
+ prop.Attributes = MemberAttributes.Public | MemberAttributes.Final;
+ prop.Type = new CodeTypeReference(typeof(int));
+ prop.GetStatements.Add(new CodeMethodReturnStatement(new CodeVariableReferenceExpression("number")));
+ prop.SetStatements.Add(new CodeAssignStatement(new CodeVariableReferenceExpression("number"),
+ new CodePropertySetValueReferenceExpression()));
+ class1.Members.Add(prop);
+ CodeTypeConstructor ctc = new CodeTypeConstructor();
+ class1.Members.Add(ctc);
+ }
- CodeConstructor ctor = new CodeConstructor();
- ctor.Attributes = MemberAttributes.Public;
- ctor.Statements.Add(new CodeAssignStatement(new CodeFieldReferenceExpression(new CodeThisReferenceExpression(),
- "Size"), new CodeObjectCreateExpression(new CodeTypeReference("Size"),
- new CodePrimitiveExpression(600), new CodePrimitiveExpression(600))));
- ctor.Statements.Add(new CodeAssignStatement(new CodeFieldReferenceExpression(new CodeTypeReferenceExpression("b"),
- "Text"), new CodePrimitiveExpression("Test")));
- ctor.Statements.Add(new CodeAssignStatement(new CodeFieldReferenceExpression(new CodeTypeReferenceExpression("b"),
- "TabIndex"), new CodePrimitiveExpression(0)));
- ctor.Statements.Add(new CodeAssignStatement(new CodeFieldReferenceExpression(new CodeTypeReferenceExpression("b"),
- "Location"), new CodeObjectCreateExpression(new CodeTypeReference("Point"),
- new CodePrimitiveExpression(400), new CodePrimitiveExpression(525))));
- ctor.Statements.Add(new CodeAttachEventStatement(new CodeEventReferenceExpression(new
- CodeThisReferenceExpression(), "MyEvent"), new CodeDelegateCreateExpression(new CodeTypeReference("EventHandler")
- , new CodeThisReferenceExpression(), "b_Click")));
- class1.Members.Add(ctor);
+ if (provider.Supports(GeneratorSupport.TryCatchStatements))
+ {
+ cmm = new CodeMemberMethod();
+ cmm.Name = "TryCatchMethod";
+ cmm.ReturnType = new CodeTypeReference(typeof(int));
+ cmm.Attributes = MemberAttributes.Public | MemberAttributes.Static;
+ CodeParameterDeclarationExpression param = new CodeParameterDeclarationExpression(typeof(int), "a");
+ cmm.Parameters.Add(param);
+
+ CodeTryCatchFinallyStatement tcfstmt = new CodeTryCatchFinallyStatement();
+ tcfstmt.FinallyStatements.Add(new CodeAssignStatement(new CodeVariableReferenceExpression("a"), new
+ CodeBinaryOperatorExpression(new CodeVariableReferenceExpression("a"), CodeBinaryOperatorType.Add,
+ new CodePrimitiveExpression(5))));
+ cmm.Statements.Add(tcfstmt);
+ cmm.Statements.Add(new CodeMethodReturnStatement(new CodeVariableReferenceExpression("a")));
+ cd.Members.Add(cmm);
+ }
- CodeMemberEvent evt = new CodeMemberEvent();
- evt.Name = "MyEvent";
- evt.Type = new CodeTypeReference("System.EventHandler");
- evt.Attributes = MemberAttributes.Public;
- class1.Members.Add(evt);
+ if (provider.Supports(GeneratorSupport.DeclareEvents))
+ {
+ CodeNamespace ns = new CodeNamespace();
+ ns.Name = "MyNamespace";
+ ns.Imports.Add(new CodeNamespaceImport("System"));
+ ns.Imports.Add(new CodeNamespaceImport("System.Drawing"));
+ ns.Imports.Add(new CodeNamespaceImport("System.Windows.Forms"));
+ ns.Imports.Add(new CodeNamespaceImport("System.ComponentModel"));
+ cu.Namespaces.Add(ns);
+ class1 = new CodeTypeDeclaration("Test");
+ class1.IsClass = true;
+ class1.BaseTypes.Add(new CodeTypeReference("Form"));
+ ns.Types.Add(class1);
+
+ CodeMemberField mfield = new CodeMemberField(new CodeTypeReference("Button"), "b");
+ mfield.InitExpression = new CodeObjectCreateExpression(new CodeTypeReference("Button"));
+ class1.Members.Add(mfield);
+
+ CodeConstructor ctor = new CodeConstructor();
+ ctor.Attributes = MemberAttributes.Public;
+ ctor.Statements.Add(new CodeAssignStatement(new CodeFieldReferenceExpression(new CodeThisReferenceExpression(),
+ "Size"), new CodeObjectCreateExpression(new CodeTypeReference("Size"),
+ new CodePrimitiveExpression(600), new CodePrimitiveExpression(600))));
+ ctor.Statements.Add(new CodeAssignStatement(new CodeFieldReferenceExpression(new CodeTypeReferenceExpression("b"),
+ "Text"), new CodePrimitiveExpression("Test")));
+ ctor.Statements.Add(new CodeAssignStatement(new CodeFieldReferenceExpression(new CodeTypeReferenceExpression("b"),
+ "TabIndex"), new CodePrimitiveExpression(0)));
+ ctor.Statements.Add(new CodeAssignStatement(new CodeFieldReferenceExpression(new CodeTypeReferenceExpression("b"),
+ "Location"), new CodeObjectCreateExpression(new CodeTypeReference("Point"),
+ new CodePrimitiveExpression(400), new CodePrimitiveExpression(525))));
+ ctor.Statements.Add(new CodeAttachEventStatement(new CodeEventReferenceExpression(new
+ CodeThisReferenceExpression(), "MyEvent"), new CodeDelegateCreateExpression(new CodeTypeReference("EventHandler")
+ , new CodeThisReferenceExpression(), "b_Click")));
+ class1.Members.Add(ctor);
+
+ CodeMemberEvent evt = new CodeMemberEvent();
+ evt.Name = "MyEvent";
+ evt.Type = new CodeTypeReference("System.EventHandler");
+ evt.Attributes = MemberAttributes.Public;
+ class1.Members.Add(evt);
- cmm = new CodeMemberMethod();
- cmm.Name = "b_Click";
- cmm.Parameters.Add(new CodeParameterDeclarationExpression(typeof(object), "sender"));
- cmm.Parameters.Add(new CodeParameterDeclarationExpression(typeof(EventArgs), "e"));
- class1.Members.Add(cmm);
- }
+ cmm = new CodeMemberMethod();
+ cmm.Name = "b_Click";
+ cmm.Parameters.Add(new CodeParameterDeclarationExpression(typeof(object), "sender"));
+ cmm.Parameters.Add(new CodeParameterDeclarationExpression(typeof(EventArgs), "e"));
+ class1.Members.Add(cmm);
+ }
- AssertEqual(cu,
- @"'------------------------------------------------------------------------------
+ AssertEqual(cu,
+ @"'------------------------------------------------------------------------------
' <auto-generated>
' This code was generated by a tool.
'
End Sub
End Class
End Namespace");
+ }
}).Dispose();
}
using System.Diagnostics;
using Microsoft.DotNet.RemoteExecutor;
using Xunit;
+using System.Tests;
namespace System.Collections.Tests
{
[InlineData("null", "null", 0)]
public void DefaultInvariant_Compare(object a, object b, int expected)
{
- RemoteExecutor.Invoke((ra, rb, rexpected) =>
+ RemoteExecutorForUap.Invoke((ra, rb, rexpected) =>
{
Func<string, object> convert = (string o) =>
{
var rexpected_val = convert(rexpected);
var cultureNames = new string[]
-{
- "cs-CZ","da-DK","de-DE","el-GR","en-US",
- "es-ES","fi-FI","fr-FR","hu-HU","it-IT",
- "ja-JP","ko-KR","nb-NO","nl-NL","pl-PL",
- "pt-BR","pt-PT","ru-RU","sv-SE","tr-TR",
- "zh-CN","zh-HK","zh-TW"
-};
+ {
+ "cs-CZ","da-DK","de-DE","el-GR","en-US",
+ "es-ES","fi-FI","fr-FR","hu-HU","it-IT",
+ "ja-JP","ko-KR","nb-NO","nl-NL","pl-PL",
+ "pt-BR","pt-PT","ru-RU","sv-SE","tr-TR",
+ "zh-CN","zh-HK","zh-TW"
+ };
foreach (string cultureName in cultureNames)
{
}
// Set current culture
- CultureInfo.CurrentCulture = culture;
- CultureInfo.CurrentUICulture = culture;
-
- // All cultures should sort the same way, irrespective of the thread's culture
- CaseInsensitiveComparer defaultInvComparer = CaseInsensitiveComparer.DefaultInvariant;
- Assert.Equal(rexpected_val, Math.Sign(defaultInvComparer.Compare(ra_val, rb_val)));
+ using (new ThreadCultureChange(culture, culture))
+ {
+ // All cultures should sort the same way, irrespective of the thread's culture
+ CaseInsensitiveComparer defaultInvComparer = CaseInsensitiveComparer.DefaultInvariant;
+ Assert.Equal(rexpected_val, Math.Sign(defaultInvComparer.Compare(ra_val, rb_val)));
+ }
}
- return RemoteExecutor.SuccessExitCode;
}, a.ToString(), b.ToString(), expected.ToString()).Dispose();
}
using System.Diagnostics;
using Microsoft.DotNet.RemoteExecutor;
using Xunit;
+using System.Tests;
#pragma warning disable 618 // obsolete types
[InlineData(5, 10, false)]
public void Ctor_Empty_ChangeCurrentCulture_GetHashCodeCompare(object a, object b, bool expected)
{
- RemoteExecutor.Invoke((ra, rb, rexpected) =>
+ RemoteExecutorForUap.Invoke((ra, rb, rexpected) =>
{
var cultureNames = new string[]
{
continue;
}
- CultureInfo.CurrentCulture = newCulture;
- var provider = new CaseInsensitiveHashCodeProvider();
- Assert.Equal(provider.GetHashCode(ra), provider.GetHashCode(ra));
- Assert.Equal(provider.GetHashCode(rb), provider.GetHashCode(rb));
- Assert.Equal(expectedResult, provider.GetHashCode(ra) == provider.GetHashCode(rb));
+ using (new ThreadCultureChange(newCulture))
+ {
+ var provider = new CaseInsensitiveHashCodeProvider();
+ Assert.Equal(provider.GetHashCode(ra), provider.GetHashCode(ra));
+ Assert.Equal(provider.GetHashCode(rb), provider.GetHashCode(rb));
+ Assert.Equal(expectedResult, provider.GetHashCode(ra) == provider.GetHashCode(rb));
+ }
}
- return RemoteExecutor.SuccessExitCode;
}, a.ToString(), b.ToString(), expected.ToString()).Dispose();
}
{
// Turkish has lower-case and upper-case version of the dotted "i", so the upper case of "i" (U+0069) isn't "I" (U+0049)
// but rather U+0130.
- RemoteExecutor.Invoke(() =>
+ RemoteExecutorForUap.Invoke(() =>
{
- CultureInfo.CurrentCulture = new CultureInfo("tr-TR");
- Assert.False(CaseInsensitiveHashCodeProvider.Default.GetHashCode("file") == CaseInsensitiveHashCodeProvider.Default.GetHashCode("FILE"));
- Assert.True(CaseInsensitiveHashCodeProvider.DefaultInvariant.GetHashCode("file") == CaseInsensitiveHashCodeProvider.DefaultInvariant.GetHashCode("FILE"));
+ using (new ThreadCultureChange("tr-TR"))
+ {
+ Assert.False(CaseInsensitiveHashCodeProvider.Default.GetHashCode("file") == CaseInsensitiveHashCodeProvider.Default.GetHashCode("FILE"));
+ Assert.True(CaseInsensitiveHashCodeProvider.DefaultInvariant.GetHashCode("file") == CaseInsensitiveHashCodeProvider.DefaultInvariant.GetHashCode("FILE"));
+ }
- CultureInfo.CurrentCulture = new CultureInfo("en-US");
- Assert.True(CaseInsensitiveHashCodeProvider.Default.GetHashCode("file") == CaseInsensitiveHashCodeProvider.Default.GetHashCode("FILE"));
- return RemoteExecutor.SuccessExitCode;
+ using (new ThreadCultureChange("en-US"))
+ {
+ Assert.True(CaseInsensitiveHashCodeProvider.Default.GetHashCode("file") == CaseInsensitiveHashCodeProvider.Default.GetHashCode("FILE"));
+ }
}).Dispose();
}
}
using System.Collections.Generic;
using System.Diagnostics;
using System.Globalization;
+using System.Tests;
using Microsoft.DotNet.RemoteExecutor;
using Xunit;
[Fact]
public void DefaultInvariant_Compare()
{
- RemoteExecutor.Invoke(() =>
+ RemoteExecutorForUap.Invoke(() =>
{
var cultureNames = new string[]
-{
+ {
"cs-CZ","da-DK","de-DE","el-GR","en-US",
"es-ES","fi-FI","fr-FR","hu-HU","it-IT",
"ja-JP","ko-KR","nb-NO","nl-NL","pl-PL",
"pt-BR","pt-PT","ru-RU","sv-SE","tr-TR",
"zh-CN","zh-HK","zh-TW"
-};
+ };
var string1 = new string[] { "Apple", "abc", };
var string2 = new string[] { "\u00C6ble", "ABC" };
continue;
}
- // Set current culture
- CultureInfo.CurrentCulture = culture;
- CultureInfo.CurrentUICulture = culture;
-
// All cultures should sort the same way, irrespective of the thread's culture
- Comparer comp = Comparer.DefaultInvariant;
- Assert.Equal(1, comp.Compare(string1[0], string2[0]));
- Assert.Equal(-1, comp.Compare(string1[1], string2[1]));
+ using (new ThreadCultureChange(culture, culture))
+ {
+ Comparer comp = Comparer.DefaultInvariant;
+ Assert.Equal(1, comp.Compare(string1[0], string2[0]));
+ Assert.Equal(-1, comp.Compare(string1[1], string2[1]));
+ }
}
- return RemoteExecutor.SuccessExitCode;
}).Dispose();
}
[Fact]
public void Ctor_IEqualityComparer()
{
- RemoteExecutor.Invoke(() =>
- {
- // Null comparer
- var hash = new ComparableHashtable((IEqualityComparer)null);
- VerifyHashtable(hash, null, null);
-
- // Custom comparer
- IEqualityComparer comparer = StringComparer.CurrentCulture;
- hash = new ComparableHashtable(comparer);
- VerifyHashtable(hash, null, comparer);
+ // Null comparer
+ var hash = new ComparableHashtable((IEqualityComparer)null);
+ VerifyHashtable(hash, null, null);
- return RemoteExecutor.SuccessExitCode;
- }).Dispose();
+ // Custom comparer
+ IEqualityComparer comparer = StringComparer.CurrentCulture;
+ hash = new ComparableHashtable(comparer);
+ VerifyHashtable(hash, null, comparer);
}
[Theory]
[Fact]
public void Ctor_IDictionary_IEqualityComparer()
{
- RemoteExecutor.Invoke(() =>
- {
- // No exception
- var hash1 = new ComparableHashtable(new Hashtable(), null);
- Assert.Equal(0, hash1.Count);
-
- hash1 = new ComparableHashtable(new Hashtable(new Hashtable(new Hashtable(new Hashtable(new Hashtable(), null), null), null), null), null);
- Assert.Equal(0, hash1.Count);
+ // No exception
+ var hash1 = new ComparableHashtable(new Hashtable(), null);
+ Assert.Equal(0, hash1.Count);
- // Null comparer
- Hashtable hash2 = Helpers.CreateIntHashtable(100);
- hash1 = new ComparableHashtable(hash2, null);
- VerifyHashtable(hash1, hash2, null);
+ hash1 = new ComparableHashtable(new Hashtable(new Hashtable(new Hashtable(new Hashtable(new Hashtable(), null), null), null), null), null);
+ Assert.Equal(0, hash1.Count);
- // Custom comparer
- hash2 = Helpers.CreateIntHashtable(100);
- IEqualityComparer comparer = StringComparer.CurrentCulture;
- hash1 = new ComparableHashtable(hash2, comparer);
- VerifyHashtable(hash1, hash2, comparer);
+ // Null comparer
+ Hashtable hash2 = Helpers.CreateIntHashtable(100);
+ hash1 = new ComparableHashtable(hash2, null);
+ VerifyHashtable(hash1, hash2, null);
- return RemoteExecutor.SuccessExitCode;
- }).Dispose();
+ // Custom comparer
+ hash2 = Helpers.CreateIntHashtable(100);
+ IEqualityComparer comparer = StringComparer.CurrentCulture;
+ hash1 = new ComparableHashtable(hash2, comparer);
+ VerifyHashtable(hash1, hash2, comparer);
}
[Fact]
[InlineData(1000)]
public void Ctor_Int_IEqualityComparer(int capacity)
{
- RemoteExecutor.Invoke((rcapacity) =>
- {
- int.TryParse(rcapacity, out int capacityint);
-
- // Null comparer
- var hash = new ComparableHashtable(capacityint, null);
- VerifyHashtable(hash, null, null);
+ // Null comparer
+ var hash = new ComparableHashtable(capacity, null);
+ VerifyHashtable(hash, null, null);
- // Custom comparer
- IEqualityComparer comparer = StringComparer.CurrentCulture;
- hash = new ComparableHashtable(capacityint, comparer);
- VerifyHashtable(hash, null, comparer);
- return RemoteExecutor.SuccessExitCode;
- }, capacity.ToString()).Dispose();
+ // Custom comparer
+ IEqualityComparer comparer = StringComparer.CurrentCulture;
+ hash = new ComparableHashtable(capacity, comparer);
+ VerifyHashtable(hash, null, comparer);
}
[Fact]
[Fact]
public void Ctor_IDictionary_Int_IEqualityComparer()
{
- RemoteExecutor.Invoke(() => {
- // No exception
- var hash1 = new ComparableHashtable(new Hashtable(), 1f, null);
- Assert.Equal(0, hash1.Count);
+ // No exception
+ var hash1 = new ComparableHashtable(new Hashtable(), 1f, null);
+ Assert.Equal(0, hash1.Count);
- hash1 = new ComparableHashtable(new Hashtable(new Hashtable(
- new Hashtable(new Hashtable(new Hashtable(), 1f, null), 1f, null), 1f, null), 1f, null), 1f, null);
- Assert.Equal(0, hash1.Count);
+ hash1 = new ComparableHashtable(new Hashtable(new Hashtable(
+ new Hashtable(new Hashtable(new Hashtable(), 1f, null), 1f, null), 1f, null), 1f, null), 1f, null);
+ Assert.Equal(0, hash1.Count);
- // Null comparer
- Hashtable hash2 = Helpers.CreateIntHashtable(100);
- hash1 = new ComparableHashtable(hash2, 1f, null);
- VerifyHashtable(hash1, hash2, null);
+ // Null comparer
+ Hashtable hash2 = Helpers.CreateIntHashtable(100);
+ hash1 = new ComparableHashtable(hash2, 1f, null);
+ VerifyHashtable(hash1, hash2, null);
- hash2 = Helpers.CreateIntHashtable(100);
- // Custom comparer
- IEqualityComparer comparer = StringComparer.CurrentCulture;
- hash1 = new ComparableHashtable(hash2, 1f, comparer);
- VerifyHashtable(hash1, hash2, comparer);
- return RemoteExecutor.SuccessExitCode;
- }).Dispose();
+ hash2 = Helpers.CreateIntHashtable(100);
+ // Custom comparer
+ IEqualityComparer comparer = StringComparer.CurrentCulture;
+ hash1 = new ComparableHashtable(hash2, 1f, comparer);
+ VerifyHashtable(hash1, hash2, comparer);
}
[Fact]
[InlineData(1000, 1)]
public void Ctor_Int_Int_IEqualityComparer(int capacity, float loadFactor)
{
- RemoteExecutor.Invoke((rcapacity, rloadFactor) =>
- {
- int.TryParse(rcapacity, out int capacityint);
- float.TryParse(rloadFactor, out float loadFactorFloat);
-
- // Null comparer
- var hash = new ComparableHashtable(capacityint, loadFactorFloat, null);
- VerifyHashtable(hash, null, null);
- Assert.Null(hash.EqualityComparer);
-
- // Custom compare
- IEqualityComparer comparer = StringComparer.CurrentCulture;
- hash = new ComparableHashtable(capacityint, loadFactorFloat, comparer);
- VerifyHashtable(hash, null, comparer);
+ // Null comparer
+ var hash = new ComparableHashtable(capacity, loadFactor, null);
+ VerifyHashtable(hash, null, null);
+ Assert.Null(hash.EqualityComparer);
- return RemoteExecutor.SuccessExitCode;
- }, capacity.ToString(), loadFactor.ToString()).Dispose();
+ // Custom compare
+ IEqualityComparer comparer = StringComparer.CurrentCulture;
+ hash = new ComparableHashtable(capacity, loadFactor, comparer);
+ VerifyHashtable(hash, null, comparer);
}
[Fact]
using System.Globalization;
using System.Linq;
using System.Reflection;
+using System.Tests;
using System.Threading.Tasks;
using Microsoft.DotNet.RemoteExecutor;
using Xunit;
[Fact]
public void Item_Get_DifferentCulture()
{
- RemoteExecutor.Invoke(() =>
+ RemoteExecutorForUap.Invoke(() =>
{
var sortList = new SortedList();
{
var cultureNames = new string[]
{
- "cs-CZ","da-DK","de-DE","el-GR","en-US",
- "es-ES","fi-FI","fr-FR","hu-HU","it-IT",
- "ja-JP","ko-KR","nb-NO","nl-NL","pl-PL",
- "pt-BR","pt-PT","ru-RU","sv-SE","tr-TR",
- "zh-CN","zh-HK","zh-TW"
+ "cs-CZ","da-DK","de-DE","el-GR","en-US",
+ "es-ES","fi-FI","fr-FR","hu-HU","it-IT",
+ "ja-JP","ko-KR","nb-NO","nl-NL","pl-PL",
+ "pt-BR","pt-PT","ru-RU","sv-SE","tr-TR",
+ "zh-CN","zh-HK","zh-TW"
};
var installedCultures = new CultureInfo[cultureNames.Length];
// In Czech ch comes after h if the comparer changes based on the current culture of the thread
// we will not be able to find some items
- CultureInfo.CurrentCulture = new CultureInfo("cs-CZ");
-
- for (int i = 0; i < uniqueDisplayNameCount; i++)
+ using (new ThreadCultureChange("cs-CZ"))
{
- Assert.Equal(installedCultures[i], sortList[installedCultures[i].DisplayName]);
+ for (int i = 0; i < uniqueDisplayNameCount; i++)
+ {
+ Assert.Equal(installedCultures[i], sortList[installedCultures[i].DisplayName]);
+ }
}
}
catch (CultureNotFoundException)
{
}
-
- return RemoteExecutor.SuccessExitCode;
}).Dispose();
}
// See the LICENSE file in the project root for more information.
using System.Collections.Generic;
-using System.Globalization;
-using System.IO;
-using System.Threading;
+using System.Tests;
using Microsoft.DotNet.RemoteExecutor;
using Xunit;
yield return new object[] { typeof(double), "1,0", "3,0", 2.99999999999999 };
}
- private class TempCulture : IDisposable
- {
- private readonly CultureInfo _original;
-
- public TempCulture(string culture)
- {
- Thread currentThread = Thread.CurrentThread;
- _original = currentThread.CurrentCulture;
- currentThread.CurrentCulture = CultureInfo.GetCultureInfoByIetfLanguageTag(culture);
- }
-
- public void Dispose()
- {
- Thread.CurrentThread.CurrentCulture = _original;
- }
- }
-
[Theory]
[MemberData(nameof(DotDecimalRanges))]
[SkipOnTargetFramework(TargetFrameworkMonikers.NetFramework, "2648 not fixed on NetFX")]
public static void ParseDotSeparatorExtremaInCommaSeparatorCultures(Type type, string min, string max)
{
- RemoteExecutor.Invoke((t, m1, m2) =>
+ RemoteExecutorForUap.Invoke((t, m1, m2) =>
{
- Thread.CurrentThread.CurrentCulture = CultureInfo.GetCultureInfoByIetfLanguageTag("en-US");
-
- Assert.True(new RangeAttribute(Type.GetType(t), m1, m2).IsValid(null));
-
- Thread.CurrentThread.CurrentCulture = CultureInfo.GetCultureInfoByIetfLanguageTag("fr-FR");
+ using (new ThreadCultureChange("en-US"))
+ {
+ Assert.True(new RangeAttribute(Type.GetType(t), m1, m2).IsValid(null));
+ }
- RangeAttribute range = new RangeAttribute(Type.GetType(t), m1, m2);
- AssertExtensions.Throws<ArgumentException>("value", () => range.IsValid(null));
+ using (new ThreadCultureChange("fr-FR"))
+ {
+ var range = new RangeAttribute(Type.GetType(t), m1, m2);
+ AssertExtensions.Throws<ArgumentException>("value", () => range.IsValid(null));
+ }
}, type.ToString(), min, max).Dispose();
}
[SkipOnTargetFramework(TargetFrameworkMonikers.NetFramework, "2648 not fixed on NetFX")]
public static void ParseDotSeparatorInvariantExtremaInCommaSeparatorCultures(Type type, string min, string max)
{
- RemoteExecutor.Invoke((t, m1, m2) =>
+ RemoteExecutorForUap.Invoke((t, m1, m2) =>
{
- Thread.CurrentThread.CurrentCulture = CultureInfo.GetCultureInfoByIetfLanguageTag("en-US");
-
- Assert.True(
- new RangeAttribute(Type.GetType(t), m1, m2)
- {
- ParseLimitsInInvariantCulture = true
- }.IsValid(null));
-
- Thread.CurrentThread.CurrentCulture = CultureInfo.GetCultureInfoByIetfLanguageTag("fr-FR");
-
- Assert.True(
- new RangeAttribute(Type.GetType(t), m1, m2)
- {
- ParseLimitsInInvariantCulture = true
- }.IsValid(null));
+ using (new ThreadCultureChange("en-US"))
+ {
+ Assert.True(
+ new RangeAttribute(Type.GetType(t), m1, m2)
+ {
+ ParseLimitsInInvariantCulture = true
+ }.IsValid(null));
+ }
+
+ using (new ThreadCultureChange("fr-FR"))
+ {
+ Assert.True(
+ new RangeAttribute(Type.GetType(t), m1, m2)
+ {
+ ParseLimitsInInvariantCulture = true
+ }.IsValid(null));
+ }
}, type.ToString(), min, max).Dispose();
}
[SkipOnTargetFramework(TargetFrameworkMonikers.NetFramework, "2648 not fixed on NetFX")]
public static void ParseCommaSeparatorExtremaInCommaSeparatorCultures(Type type, string min, string max)
{
- RemoteExecutor.Invoke((t, m1, m2) =>
+ RemoteExecutorForUap.Invoke((t, m1, m2) =>
{
- Thread.CurrentThread.CurrentCulture = CultureInfo.GetCultureInfoByIetfLanguageTag("en-US");
-
- RangeAttribute range = new RangeAttribute(Type.GetType(t), m1, m2);
- AssertExtensions.Throws<ArgumentException>("value", () => range.IsValid(null));
-
- Thread.CurrentThread.CurrentCulture = CultureInfo.GetCultureInfoByIetfLanguageTag("fr-FR");
+ using (new ThreadCultureChange("en-US"))
+ {
+ var range = new RangeAttribute(Type.GetType(t), m1, m2);
+ AssertExtensions.Throws<ArgumentException>("value", () => range.IsValid(null));
+ }
- Assert.True(new RangeAttribute(Type.GetType(t), m1, m2).IsValid(null));
+ using (new ThreadCultureChange("fr-FR"))
+ {
+ Assert.True(new RangeAttribute(Type.GetType(t), m1, m2).IsValid(null));
+ }
}, type.ToString(), min, max).Dispose();
}
[SkipOnTargetFramework(TargetFrameworkMonikers.NetFramework, "2648 not fixed on NetFX")]
public static void ParseCommaSeparatorInvariantExtremaInCommaSeparatorCultures(Type type, string min, string max)
{
- RemoteExecutor.Invoke((t, m1, m2) =>
+ RemoteExecutorForUap.Invoke((t, m1, m2) =>
{
- Thread.CurrentThread.CurrentCulture = CultureInfo.GetCultureInfoByIetfLanguageTag("en-US");
-
- RangeAttribute range = new RangeAttribute(Type.GetType(t), m1, m2);
- AssertExtensions.Throws<ArgumentException>("value", () => range.IsValid(null));
-
- Thread.CurrentThread.CurrentCulture = CultureInfo.GetCultureInfoByIetfLanguageTag("fr-FR");
+ using (new ThreadCultureChange("en-US"))
+ {
+ var range = new RangeAttribute(Type.GetType(t), m1, m2);
+ AssertExtensions.Throws<ArgumentException>("value", () => range.IsValid(null));
+ }
- Assert.True(new RangeAttribute(Type.GetType(t), m1, m2).IsValid(null));
+ using (new ThreadCultureChange("fr-FR"))
+ {
+ Assert.True(new RangeAttribute(Type.GetType(t), m1, m2).IsValid(null));
+ }
}, type.ToString(), min, max).Dispose();
}
[SkipOnTargetFramework(TargetFrameworkMonikers.NetFramework, "2648 not fixed on NetFX")]
public static void DotDecimalExtremaAndValues(Type type, string min, string max, string value)
{
- RemoteExecutor.Invoke((t, m1, m2, v) =>
+ RemoteExecutorForUap.Invoke((t, m1, m2, v) =>
{
- Thread.CurrentThread.CurrentCulture = CultureInfo.GetCultureInfoByIetfLanguageTag("en-US");
-
- Assert.True(new RangeAttribute(Type.GetType(t), m1, m2).IsValid(v));
-
- Thread.CurrentThread.CurrentCulture = CultureInfo.GetCultureInfoByIetfLanguageTag("fr-FR");
+ using (new ThreadCultureChange("en-US"))
+ {
+ Assert.True(new RangeAttribute(Type.GetType(t), m1, m2).IsValid(v));
+ }
- RangeAttribute range = new RangeAttribute(Type.GetType(t), m1, m2);
- AssertExtensions.Throws<ArgumentException>("value", () => range.IsValid(v));
+ using (new ThreadCultureChange("fr-FR"))
+ {
+ var range = new RangeAttribute(Type.GetType(t), m1, m2);
+ AssertExtensions.Throws<ArgumentException>("value", () => range.IsValid(v));
+ }
}, type.ToString(), min, max, value).Dispose();
}
[SkipOnTargetFramework(TargetFrameworkMonikers.NetFramework, "2648 not fixed on NetFX")]
public static void DotDecimalExtremaAndValuesInvariantParse(Type type, string min, string max, string value)
{
- RemoteExecutor.Invoke((t, m1, m2, v) =>
+ RemoteExecutorForUap.Invoke((t, m1, m2, v) =>
{
- Thread.CurrentThread.CurrentCulture = CultureInfo.GetCultureInfoByIetfLanguageTag("en-US");
-
- Assert.True(
- new RangeAttribute(Type.GetType(t), m1, m2)
+ using (new ThreadCultureChange("en-US"))
+ {
+ Assert.True(
+ new RangeAttribute(Type.GetType(t), m1, m2)
+ {
+ ParseLimitsInInvariantCulture = true
+ }.IsValid(v));
+ }
+
+ using (new ThreadCultureChange("fr-FR"))
+ {
+ var range = new RangeAttribute(Type.GetType(t), m1, m2)
{
ParseLimitsInInvariantCulture = true
- }.IsValid(v));
-
- Thread.CurrentThread.CurrentCulture = CultureInfo.GetCultureInfoByIetfLanguageTag("fr-FR");
-
- RangeAttribute range = new RangeAttribute(Type.GetType(t), m1, m2)
- {
- ParseLimitsInInvariantCulture = true
- };
- AssertExtensions.Throws<ArgumentException>("value", () => range.IsValid(v));
+ };
+ AssertExtensions.Throws<ArgumentException>("value", () => range.IsValid(v));
+ }
}, type.ToString(), min, max, value).Dispose();
}
[SkipOnTargetFramework(TargetFrameworkMonikers.NetFramework, "2648 not fixed on NetFX")]
public static void DotDecimalExtremaAndValuesInvariantConvert(Type type, string min, string max, string value)
{
- RemoteExecutor.Invoke((t, m1, m2, v) =>
+ RemoteExecutorForUap.Invoke((t, m1, m2, v) =>
{
- Thread.CurrentThread.CurrentCulture = CultureInfo.GetCultureInfoByIetfLanguageTag("en-US");
-
- Assert.True(
- new RangeAttribute(Type.GetType(t), m1, m2)
+ using (new ThreadCultureChange("en-US"))
+ {
+ Assert.True(
+ new RangeAttribute(Type.GetType(t), m1, m2)
+ {
+ ConvertValueInInvariantCulture = true
+ }.IsValid(v));
+ }
+
+ using (new ThreadCultureChange("fr-FR"))
+ {
+ var range = new RangeAttribute(Type.GetType(t), m1, m2)
{
ConvertValueInInvariantCulture = true
- }.IsValid(v));
-
- Thread.CurrentThread.CurrentCulture = CultureInfo.GetCultureInfoByIetfLanguageTag("fr-FR");
-
- RangeAttribute range = new RangeAttribute(Type.GetType(t), m1, m2)
- {
- ConvertValueInInvariantCulture = true
- };
- AssertExtensions.Throws<ArgumentException>("value", () => range.IsValid(v));
+ };
+ AssertExtensions.Throws<ArgumentException>("value", () => range.IsValid(v));
+ }
}, type.ToString(), min, max, value).Dispose();
}
[SkipOnTargetFramework(TargetFrameworkMonikers.NetFramework, "2648 not fixed on NetFX")]
public static void DotDecimalExtremaAndValuesInvariantBoth(Type type, string min, string max, string value)
{
- RemoteExecutor.Invoke((t, m1, m2, v) =>
+ RemoteExecutorForUap.Invoke((t, m1, m2, v) =>
{
- Thread.CurrentThread.CurrentCulture = CultureInfo.GetCultureInfoByIetfLanguageTag("en-US");
-
- Assert.True(
- new RangeAttribute(Type.GetType(t), m1, m2)
- {
- ConvertValueInInvariantCulture = true,
- ParseLimitsInInvariantCulture = true
- }.IsValid(v));
-
- Thread.CurrentThread.CurrentCulture = CultureInfo.GetCultureInfoByIetfLanguageTag("fr-FR");
-
- Assert.True(
- new RangeAttribute(Type.GetType(t), m1, m2)
- {
- ConvertValueInInvariantCulture = true,
- ParseLimitsInInvariantCulture = true
- }.IsValid(v));
+ using (new ThreadCultureChange("en-US"))
+ {
+ Assert.True(
+ new RangeAttribute(Type.GetType(t), m1, m2)
+ {
+ ConvertValueInInvariantCulture = true,
+ ParseLimitsInInvariantCulture = true
+ }.IsValid(v));
+ }
+
+ using (new ThreadCultureChange("fr-FR"))
+ {
+ Assert.True(
+ new RangeAttribute(Type.GetType(t), m1, m2)
+ {
+ ConvertValueInInvariantCulture = true,
+ ParseLimitsInInvariantCulture = true
+ }.IsValid(v));
+ }
}, type.ToString(), min, max, value).Dispose();
}
[Theory]
[SkipOnTargetFramework(TargetFrameworkMonikers.NetFramework, "2648 not fixed on NetFX")]
public static void DotDecimalExtremaAndNonStringValues(Type type, string min, string max, object value)
{
- using (new TempCulture("en-US"))
+ using (new ThreadCultureChange("en-US"))
{
Assert.True(new RangeAttribute(type, min, max).IsValid(value));
}
- using (new TempCulture("fr-FR"))
+ using (new ThreadCultureChange("fr-FR"))
{
- RangeAttribute range = new RangeAttribute(type, min, max);
+ var range = new RangeAttribute(type, min, max);
AssertExtensions.Throws<ArgumentException>("value", () => range.IsValid(value));
}
}
[SkipOnTargetFramework(TargetFrameworkMonikers.NetFramework, "2648 not fixed on NetFX")]
public static void DotDecimalExtremaAndNonStringValuesInvariantParse(Type type, string min, string max, object value)
{
- using (new TempCulture("en-US"))
+ using (new ThreadCultureChange("en-US"))
{
Assert.True(
new RangeAttribute(type, min, max)
}.IsValid(value));
}
- using (new TempCulture("fr-FR"))
+ using (new ThreadCultureChange("fr-FR"))
{
Assert.True(
new RangeAttribute(type, min, max)
[MemberData(nameof(DotDecimalNonStringValidValues))][SkipOnTargetFramework(TargetFrameworkMonikers.NetFramework, "2648 not fixed on NetFX")]
public static void DotDecimalExtremaAndNonStringValuesInvariantConvert(Type type, string min, string max, object value)
{
- using (new TempCulture("en-US"))
+ using (new ThreadCultureChange("en-US"))
{
Assert.True(
new RangeAttribute(type, min, max)
}.IsValid(value));
}
- using (new TempCulture("fr-FR"))
+ using (new ThreadCultureChange("fr-FR"))
{
- RangeAttribute range = new RangeAttribute(type, min, max)
+ var range = new RangeAttribute(type, min, max)
{
ConvertValueInInvariantCulture = true
};
[MemberData(nameof(DotDecimalNonStringValidValues))][SkipOnTargetFramework(TargetFrameworkMonikers.NetFramework, "2648 not fixed on NetFX")]
public static void DotDecimalExtremaAndNonStringValuesInvariantBoth(Type type, string min, string max, object value)
{
- using (new TempCulture("en-US"))
+ using (new ThreadCultureChange("en-US"))
{
Assert.True(
new RangeAttribute(type, min, max)
}.IsValid(value));
}
- using (new TempCulture("fr-FR"))
+ using (new ThreadCultureChange("fr-FR"))
{
Assert.True(
new RangeAttribute(type, min, max)
[SkipOnTargetFramework(TargetFrameworkMonikers.NetFramework, "2648 not fixed on NetFX")]
public static void CommaDecimalExtremaAndNonStringValues(Type type, string min, string max, object value)
{
- using (new TempCulture("en-US"))
+ using (new ThreadCultureChange("en-US"))
{
- RangeAttribute range = new RangeAttribute(type, min, max);
+ var range = new RangeAttribute(type, min, max);
AssertExtensions.Throws<ArgumentException>("value", () => range.IsValid(value));
}
- using (new TempCulture("fr-FR"))
+ using (new ThreadCultureChange("fr-FR"))
{
Assert.True(new RangeAttribute(type, min, max).IsValid(value));
}
[SkipOnTargetFramework(TargetFrameworkMonikers.NetFramework, "2648 not fixed on NetFX")]
public static void CommaDecimalExtremaAndNonStringValuesInvariantParse(Type type, string min, string max, object value)
{
- using (new TempCulture("en-US"))
+ using (new ThreadCultureChange("en-US"))
{
- RangeAttribute range = new RangeAttribute(type, min, max)
+ var range = new RangeAttribute(type, min, max)
{
ParseLimitsInInvariantCulture = true
};
AssertExtensions.Throws<ArgumentException>("value", () => range.IsValid(value));
}
- using (new TempCulture("fr-FR"))
+ using (new ThreadCultureChange("fr-FR"))
{
- RangeAttribute range = new RangeAttribute(type, min, max)
+ var range = new RangeAttribute(type, min, max)
{
ParseLimitsInInvariantCulture = true
};
[SkipOnTargetFramework(TargetFrameworkMonikers.NetFramework, "2648 not fixed on NetFX")]
public static void CommaDecimalExtremaAndNonStringValuesInvariantConvert(Type type, string min, string max, object value)
{
- using (new TempCulture("en-US"))
+ using (new ThreadCultureChange("en-US"))
{
- RangeAttribute range = new RangeAttribute(type, min, max)
+ var range = new RangeAttribute(type, min, max)
{
ConvertValueInInvariantCulture = true
};
AssertExtensions.Throws<ArgumentException>("value", () => range.IsValid(value));
}
- using (new TempCulture("fr-FR"))
+ using (new ThreadCultureChange("fr-FR"))
{
Assert.True(
new RangeAttribute(type, min, max)
[SkipOnTargetFramework(TargetFrameworkMonikers.NetFramework, "2648 not fixed on NetFX")]
public static void CommaDecimalExtremaAndNonStringValuesInvariantBoth(Type type, string min, string max, object value)
{
- using (new TempCulture("en-US"))
+ using (new ThreadCultureChange("en-US"))
{
- RangeAttribute range = new RangeAttribute(type, min, max)
+ var range = new RangeAttribute(type, min, max)
{
ConvertValueInInvariantCulture = true,
ParseLimitsInInvariantCulture = true
AssertExtensions.Throws<ArgumentException>("value", () => range.IsValid(value));
}
- using (new TempCulture("fr-FR"))
+ using (new ThreadCultureChange("fr-FR"))
{
- RangeAttribute range = new RangeAttribute(type, min, max)
+ var range = new RangeAttribute(type, min, max)
{
ConvertValueInInvariantCulture = true,
ParseLimitsInInvariantCulture = true
[SkipOnTargetFramework(TargetFrameworkMonikers.NetFramework, "2648 not fixed on NetFX")]
public static void DotDecimalExtremaAndInvalidValues(Type type, string min, string max, string value)
{
- RemoteExecutor.Invoke((t, m1, m2, v) =>
+ RemoteExecutorForUap.Invoke((t, m1, m2, v) =>
{
- Thread.CurrentThread.CurrentCulture = CultureInfo.GetCultureInfoByIetfLanguageTag("en-US");
-
- Assert.False(new RangeAttribute(Type.GetType(t), m1, m2).IsValid(v));
-
- Thread.CurrentThread.CurrentCulture = CultureInfo.GetCultureInfoByIetfLanguageTag("fr-FR");
+ using (new ThreadCultureChange("en-US"))
+ {
+ Assert.False(new RangeAttribute(Type.GetType(t), m1, m2).IsValid(v));
+ }
- RangeAttribute range = new RangeAttribute(Type.GetType(t), m1, m2);
- AssertExtensions.Throws<ArgumentException>("value", () => range.IsValid(v));
+ using (new ThreadCultureChange("fr-FR"))
+ {
+ var range = new RangeAttribute(Type.GetType(t), m1, m2);
+ AssertExtensions.Throws<ArgumentException>("value", () => range.IsValid(v));
+ }
}, type.ToString(), min, max, value).Dispose();
}
[SkipOnTargetFramework(TargetFrameworkMonikers.NetFramework, "2648 not fixed on NetFX")]
public static void DotDecimalExtremaAndInvalidValuesInvariantParse(Type type, string min, string max, string value)
{
- RemoteExecutor.Invoke((t, m1, m2, v) =>
+ RemoteExecutorForUap.Invoke((t, m1, m2, v) =>
{
- Thread.CurrentThread.CurrentCulture = CultureInfo.GetCultureInfoByIetfLanguageTag("en-US");
-
- Assert.False(
- new RangeAttribute(Type.GetType(t), m1, m2)
+ using (new ThreadCultureChange("en-US"))
+ {
+ Assert.False(
+ new RangeAttribute(Type.GetType(t), m1, m2)
+ {
+ ParseLimitsInInvariantCulture = true
+ }.IsValid(v));
+ }
+
+ using (new ThreadCultureChange("fr-FR"))
+ {
+ var range = new RangeAttribute(Type.GetType(t), m1, m2)
{
ParseLimitsInInvariantCulture = true
- }.IsValid(v));
-
- Thread.CurrentThread.CurrentCulture = CultureInfo.GetCultureInfoByIetfLanguageTag("fr-FR");
-
- RangeAttribute range = new RangeAttribute(Type.GetType(t), m1, m2)
- {
- ParseLimitsInInvariantCulture = true
- };
- AssertExtensions.Throws<ArgumentException>("value", () => range.IsValid(v));
+ };
+ AssertExtensions.Throws<ArgumentException>("value", () => range.IsValid(v));
+ }
}, type.ToString(), min, max, value).Dispose();
}
[SkipOnTargetFramework(TargetFrameworkMonikers.NetFramework, "2648 not fixed on NetFX")]
public static void DotDecimalExtremaAndInvalidValuesInvariantConvert(Type type, string min, string max, string value)
{
- RemoteExecutor.Invoke((t, m1, m2, v) =>
+ RemoteExecutorForUap.Invoke((t, m1, m2, v) =>
{
- Thread.CurrentThread.CurrentCulture = CultureInfo.GetCultureInfoByIetfLanguageTag("en-US");
-
- Assert.False(
- new RangeAttribute(Type.GetType(t), m1, m2)
+ using (new ThreadCultureChange("en-US"))
+ {
+ Assert.False(
+ new RangeAttribute(Type.GetType(t), m1, m2)
+ {
+ ConvertValueInInvariantCulture = true
+ }.IsValid(v));
+ }
+
+ using (new ThreadCultureChange("fr-FR"))
+ {
+ var range = new RangeAttribute(Type.GetType(t), m1, m2)
{
ConvertValueInInvariantCulture = true
- }.IsValid(v));
-
- Thread.CurrentThread.CurrentCulture = CultureInfo.GetCultureInfoByIetfLanguageTag("fr-FR");
-
- RangeAttribute range = new RangeAttribute(Type.GetType(t), m1, m2)
- {
- ConvertValueInInvariantCulture = true
- };
- AssertExtensions.Throws<ArgumentException>("value", () => range.IsValid(v));
+ };
+ AssertExtensions.Throws<ArgumentException>("value", () => range.IsValid(v));
+ }
}, type.ToString(), min, max, value).Dispose();
}
[SkipOnTargetFramework(TargetFrameworkMonikers.NetFramework, "2648 not fixed on NetFX")]
public static void DotDecimalExtremaAndInvalidValuesInvariantBoth(Type type, string min, string max, string value)
{
- RemoteExecutor.Invoke((t, m1, m2, v) =>
+ RemoteExecutorForUap.Invoke((t, m1, m2, v) =>
{
- Thread.CurrentThread.CurrentCulture = CultureInfo.GetCultureInfoByIetfLanguageTag("en-US");
-
- Assert.False(
- new RangeAttribute(Type.GetType(t), m1, m2)
- {
- ConvertValueInInvariantCulture = true,
- ParseLimitsInInvariantCulture = true
- }.IsValid(v));
-
- Thread.CurrentThread.CurrentCulture = CultureInfo.GetCultureInfoByIetfLanguageTag("fr-FR");
-
- Assert.False(
- new RangeAttribute(Type.GetType(t), m1, m2)
- {
- ConvertValueInInvariantCulture = true,
- ParseLimitsInInvariantCulture = true
- }.IsValid(v));
+ using (new ThreadCultureChange("en-US"))
+ {
+ Assert.False(
+ new RangeAttribute(Type.GetType(t), m1, m2)
+ {
+ ConvertValueInInvariantCulture = true,
+ ParseLimitsInInvariantCulture = true
+ }.IsValid(v));
+ }
+
+ using (new ThreadCultureChange("fr-FR"))
+ {
+ Assert.False(
+ new RangeAttribute(Type.GetType(t), m1, m2)
+ {
+ ConvertValueInInvariantCulture = true,
+ ParseLimitsInInvariantCulture = true
+ }.IsValid(v));
+ }
}, type.ToString(), min, max, value).Dispose();
}
[SkipOnTargetFramework(TargetFrameworkMonikers.NetFramework, "2648 not fixed on NetFX")]
public static void CommaDecimalExtremaAndValues(Type type, string min, string max, string value)
{
- RemoteExecutor.Invoke((t, m1, m2, v) =>
+ RemoteExecutorForUap.Invoke((t, m1, m2, v) =>
{
- Thread.CurrentThread.CurrentCulture = CultureInfo.GetCultureInfoByIetfLanguageTag("en-US");
-
- RangeAttribute range = new RangeAttribute(Type.GetType(t), m1, m2);
- AssertExtensions.Throws<ArgumentException>("value", () => range.IsValid(v));
-
- Thread.CurrentThread.CurrentCulture = CultureInfo.GetCultureInfoByIetfLanguageTag("fr-FR");
+ using (new ThreadCultureChange("en-US"))
+ {
+ var range = new RangeAttribute(Type.GetType(t), m1, m2);
+ AssertExtensions.Throws<ArgumentException>("value", () => range.IsValid(v));
+ }
- Assert.True(new RangeAttribute(Type.GetType(t), m1, m2).IsValid(v));
+ using (new ThreadCultureChange("fr-FR"))
+ {
+ Assert.True(new RangeAttribute(Type.GetType(t), m1, m2).IsValid(v));
+ }
}, type.ToString(), min, max, value).Dispose();
}
[SkipOnTargetFramework(TargetFrameworkMonikers.NetFramework, "2648 not fixed on NetFX")]
public static void CommaDecimalExtremaAndValuesInvariantParse(Type type, string min, string max, string value)
{
- RemoteExecutor.Invoke((t, m1, m2, v) =>
+ RemoteExecutorForUap.Invoke((t, m1, m2, v) =>
{
- Thread.CurrentThread.CurrentCulture = CultureInfo.GetCultureInfoByIetfLanguageTag("en-US");
-
- RangeAttribute range = new RangeAttribute(Type.GetType(t), m1, m2)
+ using (new ThreadCultureChange("en-US"))
{
- ParseLimitsInInvariantCulture = true
- };
- AssertExtensions.Throws<ArgumentException>("value", () => range.IsValid(v));
-
- Thread.CurrentThread.CurrentCulture = CultureInfo.GetCultureInfoByIetfLanguageTag("fr-FR");
+ var range = new RangeAttribute(Type.GetType(t), m1, m2)
+ {
+ ParseLimitsInInvariantCulture = true
+ };
+ AssertExtensions.Throws<ArgumentException>("value", () => range.IsValid(v));
+ }
- range = new RangeAttribute(Type.GetType(t), m1, m2)
+ using (new ThreadCultureChange("fr-FR"))
{
- ParseLimitsInInvariantCulture = true
- };
- AssertExtensions.Throws<ArgumentException>("value", () => range.IsValid(v));
+ var range = new RangeAttribute(Type.GetType(t), m1, m2)
+ {
+ ParseLimitsInInvariantCulture = true
+ };
+ AssertExtensions.Throws<ArgumentException>("value", () => range.IsValid(v));
+ }
}, type.ToString(), min, max, value).Dispose();
}
[SkipOnTargetFramework(TargetFrameworkMonikers.NetFramework, "2648 not fixed on NetFX")]
public static void CommaDecimalExtremaAndValuesInvariantConvert(Type type, string min, string max, string value)
{
- RemoteExecutor.Invoke((t, m1, m2, v) =>
+ RemoteExecutorForUap.Invoke((t, m1, m2, v) =>
{
- Thread.CurrentThread.CurrentCulture = CultureInfo.GetCultureInfoByIetfLanguageTag("en-US");
-
- RangeAttribute range = new RangeAttribute(Type.GetType(t), m1, m2)
+ using (new ThreadCultureChange("en-US"))
{
- ConvertValueInInvariantCulture = true
- };
- AssertExtensions.Throws<ArgumentException>("value", () => range.IsValid(v));
-
- Thread.CurrentThread.CurrentCulture = CultureInfo.GetCultureInfoByIetfLanguageTag("fr-FR");
+ var range = new RangeAttribute(Type.GetType(t), m1, m2)
+ {
+ ConvertValueInInvariantCulture = true
+ };
+ AssertExtensions.Throws<ArgumentException>("value", () => range.IsValid(v));
+ }
- range = new RangeAttribute(Type.GetType(t), m1, m2)
+ using (new ThreadCultureChange("fr-FR"))
{
- ConvertValueInInvariantCulture = true
- };
- AssertExtensions.Throws<ArgumentException>("value", () => range.IsValid(v));
+ var range = new RangeAttribute(Type.GetType(t), m1, m2)
+ {
+ ConvertValueInInvariantCulture = true
+ };
+ AssertExtensions.Throws<ArgumentException>("value", () => range.IsValid(v));
+ }
}, type.ToString(), min, max, value).Dispose();
}
[SkipOnTargetFramework(TargetFrameworkMonikers.NetFramework, "2648 not fixed on NetFX")]
public static void CommaDecimalExtremaAndValuesInvariantBoth(Type type, string min, string max, string value)
{
- RemoteExecutor.Invoke((t, m1, m2, v) =>
+ RemoteExecutorForUap.Invoke((t, m1, m2, v) =>
{
- Thread.CurrentThread.CurrentCulture = CultureInfo.GetCultureInfoByIetfLanguageTag("en-US");
-
- RangeAttribute range = new RangeAttribute(Type.GetType(t), m1, m2)
+ using (new ThreadCultureChange("en-US"))
{
- ConvertValueInInvariantCulture = true,
- ParseLimitsInInvariantCulture = true
- };
- AssertExtensions.Throws<ArgumentException>("value", () => range.IsValid(v));
-
- Thread.CurrentThread.CurrentCulture = CultureInfo.GetCultureInfoByIetfLanguageTag("fr-FR");
+ var range = new RangeAttribute(Type.GetType(t), m1, m2)
+ {
+ ConvertValueInInvariantCulture = true,
+ ParseLimitsInInvariantCulture = true
+ };
+ AssertExtensions.Throws<ArgumentException>("value", () => range.IsValid(v));
+ }
- range = new RangeAttribute(Type.GetType(t), m1, m2)
+ using (new ThreadCultureChange("fr-FR"))
{
- ConvertValueInInvariantCulture = true,
- ParseLimitsInInvariantCulture = true
- };
- AssertExtensions.Throws<ArgumentException>("value", () => range.IsValid(v));
+ var range = new RangeAttribute(Type.GetType(t), m1, m2)
+ {
+ ConvertValueInInvariantCulture = true,
+ ParseLimitsInInvariantCulture = true
+ };
+ AssertExtensions.Throws<ArgumentException>("value", () => range.IsValid(v));
+ }
}, type.ToString(), min, max, value).Dispose();
}
[SkipOnTargetFramework(TargetFrameworkMonikers.NetFramework, "2648 not fixed on NetFX")]
public static void CommaDecimalExtremaAndInvalidValues(Type type, string min, string max, string value)
{
- RemoteExecutor.Invoke((t, m1, m2, v) =>
+ RemoteExecutorForUap.Invoke((t, m1, m2, v) =>
{
- Thread.CurrentThread.CurrentCulture = CultureInfo.GetCultureInfoByIetfLanguageTag("en-US");
-
- RangeAttribute range = new RangeAttribute(Type.GetType(t), m1, m2);
- AssertExtensions.Throws<ArgumentException>("value", () => range.IsValid(v));
-
- Thread.CurrentThread.CurrentCulture = CultureInfo.GetCultureInfoByIetfLanguageTag("fr-FR");
+ using (new ThreadCultureChange("en-US"))
+ {
+ var range = new RangeAttribute(Type.GetType(t), m1, m2);
+ AssertExtensions.Throws<ArgumentException>("value", () => range.IsValid(v));
+ }
- Assert.False(new RangeAttribute(Type.GetType(t), m1, m2).IsValid(v));
+ using (new ThreadCultureChange("fr-FR"))
+ {
+ Assert.False(new RangeAttribute(Type.GetType(t), m1, m2).IsValid(v));
+ }
}, type.ToString(), min, max, value).Dispose();
}
[SkipOnTargetFramework(TargetFrameworkMonikers.NetFramework, "2648 not fixed on NetFX")]
public static void CommaDecimalExtremaAndInvalidValuesInvariantParse(Type type, string min, string max, string value)
{
- RemoteExecutor.Invoke((t, m1, m2, v) =>
+ RemoteExecutorForUap.Invoke((t, m1, m2, v) =>
{
- Thread.CurrentThread.CurrentCulture = CultureInfo.GetCultureInfoByIetfLanguageTag("en-US");
-
- RangeAttribute range = new RangeAttribute(Type.GetType(t), m1, m2)
+ using (new ThreadCultureChange("en-US"))
{
- ParseLimitsInInvariantCulture = true
- };
- AssertExtensions.Throws<ArgumentException>("value", () => range.IsValid(v));
-
- Thread.CurrentThread.CurrentCulture = CultureInfo.GetCultureInfoByIetfLanguageTag("fr-FR");
+ var range = new RangeAttribute(Type.GetType(t), m1, m2)
+ {
+ ParseLimitsInInvariantCulture = true
+ };
+ AssertExtensions.Throws<ArgumentException>("value", () => range.IsValid(v));
+ }
- range = new RangeAttribute(Type.GetType(t), m1, m2)
+ using (new ThreadCultureChange("fr-FR"))
{
- ParseLimitsInInvariantCulture = true
- };
- AssertExtensions.Throws<ArgumentException>("value", () => range.IsValid(v));
+ var range = new RangeAttribute(Type.GetType(t), m1, m2)
+ {
+ ParseLimitsInInvariantCulture = true
+ };
+ AssertExtensions.Throws<ArgumentException>("value", () => range.IsValid(v));
+ }
}, type.ToString(), min, max, value).Dispose();
}
[SkipOnTargetFramework(TargetFrameworkMonikers.NetFramework, "2648 not fixed on NetFX")]
public static void CommaDecimalExtremaAndInvalidValuesInvariantConvert(Type type, string min, string max, string value)
{
- RemoteExecutor.Invoke((t, m1, m2, v) =>
+ RemoteExecutorForUap.Invoke((t, m1, m2, v) =>
{
- Thread.CurrentThread.CurrentCulture = CultureInfo.GetCultureInfoByIetfLanguageTag("en-US");
-
- RangeAttribute range = new RangeAttribute(Type.GetType(t), m1, m2)
+ using (new ThreadCultureChange("en-US"))
{
- ConvertValueInInvariantCulture = true
- };
- AssertExtensions.Throws<ArgumentException>("value", () => range.IsValid(v));
-
- Thread.CurrentThread.CurrentCulture = CultureInfo.GetCultureInfoByIetfLanguageTag("fr-FR");
+ var range = new RangeAttribute(Type.GetType(t), m1, m2)
+ {
+ ConvertValueInInvariantCulture = true
+ };
+ AssertExtensions.Throws<ArgumentException>("value", () => range.IsValid(v));
+ }
- range = new RangeAttribute(Type.GetType(t), m1, m2)
+ using (new ThreadCultureChange("fr-FR"))
{
- ConvertValueInInvariantCulture = true
- };
- AssertExtensions.Throws<ArgumentException>("value", () => range.IsValid(v));
+ var range = new RangeAttribute(Type.GetType(t), m1, m2)
+ {
+ ConvertValueInInvariantCulture = true
+ };
+ AssertExtensions.Throws<ArgumentException>("value", () => range.IsValid(v));
+ }
}, type.ToString(), min, max, value).Dispose();
}
[SkipOnTargetFramework(TargetFrameworkMonikers.NetFramework, "2648 not fixed on NetFX")]
public static void CommaDecimalExtremaAndInvalidValuesInvariantBoth(Type type, string min, string max, string value)
{
- RemoteExecutor.Invoke((t, m1, m2, v) =>
+ RemoteExecutorForUap.Invoke((t, m1, m2, v) =>
{
- Thread.CurrentThread.CurrentCulture = CultureInfo.GetCultureInfoByIetfLanguageTag("en-US");
-
- RangeAttribute range = new RangeAttribute(Type.GetType(t), m1, m2)
+ using (new ThreadCultureChange("en-US"))
{
- ConvertValueInInvariantCulture = true,
- ParseLimitsInInvariantCulture = true
- };
- AssertExtensions.Throws<ArgumentException>("value", () => range.IsValid(v));
-
- Thread.CurrentThread.CurrentCulture = CultureInfo.GetCultureInfoByIetfLanguageTag("fr-FR");
+ var range = new RangeAttribute(Type.GetType(t), m1, m2)
+ {
+ ConvertValueInInvariantCulture = true,
+ ParseLimitsInInvariantCulture = true
+ };
+ AssertExtensions.Throws<ArgumentException>("value", () => range.IsValid(v));
+ }
- range = new RangeAttribute(Type.GetType(t), m1, m2)
+ using (new ThreadCultureChange("fr-FR"))
{
- ConvertValueInInvariantCulture = true,
- ParseLimitsInInvariantCulture = true
- };
- AssertExtensions.Throws<ArgumentException>("value", () => range.IsValid(v));
+ var range = new RangeAttribute(Type.GetType(t), m1, m2)
+ {
+ ConvertValueInInvariantCulture = true,
+ ParseLimitsInInvariantCulture = true
+ };
+ AssertExtensions.Throws<ArgumentException>("value", () => range.IsValid(v));
+ }
}, type.ToString(), min, max, value).Dispose();
}
<Compile Include="System\UnitTesting\ExtendedAssert.cs" />
<Compile Include="System\UnitTesting\RetryMode.cs" />
<Compile Include="System\UnitTesting\TestServices.cs" />
- <Compile Include="$(CommonTestPath)\System\ThreadCultureChange.cs">
- <Link>Common\System\ThreadCultureChange.cs</Link>
- </Compile>
</ItemGroup>
<ItemGroup>
<ProjectReference Include="System.ComponentModel.Composition.Noop.Assembly/System.ComponentModel.Composition.Noop.Assembly.csproj">
<CopyToOutputDirectory>PreserveNewest</CopyToOutputDirectory>
</ProjectReference>
</ItemGroup>
-</Project>
\ No newline at end of file
+</Project>
// See the LICENSE file in the project root for more information.
using System.Collections.Generic;
-using System.Common.Tests;
using System.ComponentModel.Composition.Factories;
using System.ComponentModel.Composition.Primitives;
using System.Diagnostics;
using System.Globalization;
using System.IO;
using System.Linq;
+using System.Tests;
using System.Text;
using System.UnitTesting;
using Microsoft.DotNet.RemoteExecutor;
foreach (CultureInfo culture in cultures)
{
// Save old culture and set a fixed culture for object instantiation
- using (new ThreadCultureChange(culture))
+ using (new ThreadCultureChange(culture, culture))
{
CompositionError[] errors = CreateCompositionErrors(1000);
CompositionException exception = CreateCompositionException(errors);
AssertMessage(exception, 1, culture);
}
}
- return RemoteExecutor.SuccessExitCode;
}).Dispose();
}
GC.Collect();
GC.WaitForPendingFinalizers();
-
- return RemoteExecutor.SuccessExitCode;
}).Dispose();
}
GC.WaitForPendingFinalizers();
Assert.True(tracker.OperationDidComplete);
-
- return RemoteExecutor.SuccessExitCode;
}).Dispose();
}
using System.Diagnostics;
using System.Globalization;
using System.Linq;
+using System.Tests;
using Microsoft.DotNet.RemoteExecutor;
using Xunit;
[Fact]
public void DesignerOptionConverter_ConvertToString_ReturnsExpected()
{
- RemoteExecutor.Invoke(() =>
+ RemoteExecutorForUap.Invoke(() =>
{
- CultureInfo.CurrentUICulture = CultureInfo.InvariantCulture;
-
- TypeConverter converter = TypeDescriptor.GetConverter(typeof(DesignerOptionService.DesignerOptionCollection));
- Assert.Equal("(Collection)", converter.ConvertToString(null));
+ using (new ThreadCultureChange(null, CultureInfo.InvariantCulture))
+ {
+ TypeConverter converter = TypeDescriptor.GetConverter(typeof(DesignerOptionService.DesignerOptionCollection));
+ Assert.Equal("(Collection)", converter.ConvertToString(null));
+ }
}).Dispose();
}
// See the LICENSE file in the project root for more information.
using System.Globalization;
+using System.Tests;
using Microsoft.DotNet.RemoteExecutor;
using Xunit;
[Fact]
public static void ConvertTo_WithContext()
{
- RemoteExecutor.Invoke(() =>
+ RemoteExecutorForUap.Invoke(() =>
{
- CultureInfo.CurrentUICulture = CultureInfo.InvariantCulture;
-
- ConvertTo_WithContext(new object[1, 3]
- {
- { "any string", "(Text)", null }
- },
- new MultilineStringConverter());
+ using (new ThreadCultureChange(null, CultureInfo.InvariantCulture))
+ {
+ ConvertTo_WithContext(new object[1, 3]
+ {
+ { "any string", "(Text)", null }
+ },
+ new MultilineStringConverter());
+ }
}).Dispose();
}
}
using System.Runtime.Serialization.Formatters.Binary;
using Microsoft.DotNet.RemoteExecutor;
using Xunit;
+using System.Tests;
namespace System.ComponentModel.Tests
{
}
else
{
- RemoteExecutor.Invoke((typeName, testString) =>
+ RemoteExecutorForUap.Invoke((typeName, testString) =>
{
// Deserialize the current test.
TypeConverterTestBase testBase = (TypeConverterTestBase)Activator.CreateInstance(Type.GetType(typeName));
ConvertTest test = ConvertTest.FromSerializedString(testString);
- CultureInfo.CurrentCulture = test.RemoteInvokeCulture;
- Assert.Equal(test.CanConvert, testBase.Converter.CanConvertTo(test.Context, test.DestinationType));
-
- if (test.CanConvert)
- {
- object actual = testBase.Converter.ConvertTo(test.Context, test.Culture, test.Source, test.DestinationType);
- Assert.Equal(test.Expected, actual);
- }
- else
+ using (new ThreadCultureChange(test.RemoteInvokeCulture))
{
- Assert.Throws<NotSupportedException>(() => testBase.Converter.ConvertTo(test.Context, test.Culture, test.Source, test.DestinationType));
+ Assert.Equal(test.CanConvert, testBase.Converter.CanConvertTo(test.Context, test.DestinationType));
+
+ if (test.CanConvert)
+ {
+ object actual = testBase.Converter.ConvertTo(test.Context, test.Culture, test.Source, test.DestinationType);
+ Assert.Equal(test.Expected, actual);
+ }
+ else
+ {
+ Assert.Throws<NotSupportedException>(() => testBase.Converter.ConvertTo(test.Context, test.Culture, test.Source, test.DestinationType));
+ }
}
-
- return RemoteExecutor.SuccessExitCode;
}, this.GetType().AssemblyQualifiedName, convertTest.GetSerializedString()).Dispose();
}
});
}
else
{
- RemoteExecutor.Invoke((typeName, testString) =>
+ RemoteExecutorForUap.Invoke((typeName, testString) =>
{
// Deserialize the current test.
TypeConverterTestBase testBase = (TypeConverterTestBase)Activator.CreateInstance(Type.GetType(typeName));
ConvertTest test = ConvertTest.FromSerializedString(testString);
- CultureInfo.CurrentCulture = test.RemoteInvokeCulture;
- if (test.Source != null)
- {
- Assert.Equal(test.CanConvert, testBase.Converter.CanConvertFrom(test.Context, test.Source.GetType()));
- }
-
- if (test.NetCoreExceptionType == null)
+ using (new ThreadCultureChange(test.RemoteInvokeCulture))
{
- object actual = testBase.Converter.ConvertFrom(test.Context, test.Culture, test.Source);
- Assert.Equal(test.Expected, actual);
+ if (test.Source != null)
+ {
+ Assert.Equal(test.CanConvert, testBase.Converter.CanConvertFrom(test.Context, test.Source.GetType()));
+ }
+
+ if (test.NetCoreExceptionType == null)
+ {
+ object actual = testBase.Converter.ConvertFrom(test.Context, test.Culture, test.Source);
+ Assert.Equal(test.Expected, actual);
+ }
+ else
+ {
+ AssertExtensions.Throws(test.NetCoreExceptionType, test.NetFrameworkExceptionType, () => testBase.Converter.ConvertFrom(test.Context, test.Culture, test.Source));
+ }
}
- else
- {
- AssertExtensions.Throws(test.NetCoreExceptionType, test.NetFrameworkExceptionType, () => testBase.Converter.ConvertFrom(test.Context, test.Culture, test.Source));
- }
-
- return RemoteExecutor.SuccessExitCode;
}, this.GetType().AssemblyQualifiedName, convertTest.GetSerializedString()).Dispose();
}
});
public override string ToString() => nameof(CustomToString);
}
}
-}
\ No newline at end of file
+}
using System.Diagnostics;
using System.Globalization;
using System.Reflection;
+using System.Tests;
using Microsoft.DotNet.RemoteExecutor;
using Xunit;
[Fact]
public static void ConvertFrom_InstanceDescriptor()
{
- RemoteExecutor.Invoke(() =>
+ RemoteExecutorForUap.Invoke(() =>
{
- CultureInfo.CurrentCulture = CultureInfo.GetCultureInfo("fr-FR");
- DateTime testDateAndTime = DateTime.UtcNow;
- ConstructorInfo ctor = typeof(DateTime).GetConstructor(new Type[]
+ using (new ThreadCultureChange("fr-FR"))
{
- typeof(int), typeof(int), typeof(int), typeof(int),
- typeof(int), typeof(int), typeof(int)
- });
-
- InstanceDescriptor descriptor = new InstanceDescriptor(ctor, new object[]
- {
- testDateAndTime.Year, testDateAndTime.Month, testDateAndTime.Day, testDateAndTime.Hour,
- testDateAndTime.Minute, testDateAndTime.Second, testDateAndTime.Millisecond
- });
-
- const string format = "dd MMM yyyy hh:mm";
- object o = s_converter.ConvertFrom(descriptor);
- Assert.Equal(testDateAndTime.ToString(format), ((DateTime)o).ToString(format));
+ DateTime testDateAndTime = DateTime.UtcNow;
+ ConstructorInfo ctor = typeof(DateTime).GetConstructor(new Type[]
+ {
+ typeof(int), typeof(int), typeof(int), typeof(int),
+ typeof(int), typeof(int), typeof(int)
+ });
+
+ InstanceDescriptor descriptor = new InstanceDescriptor(ctor, new object[]
+ {
+ testDateAndTime.Year, testDateAndTime.Month, testDateAndTime.Day, testDateAndTime.Hour,
+ testDateAndTime.Minute, testDateAndTime.Second, testDateAndTime.Millisecond
+ });
+
+ const string format = "dd MMM yyyy hh:mm";
+ object o = s_converter.ConvertFrom(descriptor);
+ Assert.Equal(testDateAndTime.ToString(format), ((DateTime)o).ToString(format));
+ }
}).Dispose();
}
[Fact]
public static void ConvertTo_WithContext()
{
- RemoteExecutor.Invoke(() =>
+ RemoteExecutorForUap.Invoke(() =>
{
- CultureInfo.CurrentCulture = new CultureInfo("pl-PL");
-
- Assert.Throws<ArgumentNullException>(
- () => s_converter.ConvertTo(s_context, null, c_conversionInputValue, null));
+ using (new ThreadCultureChange("pl-PL"))
+ {
+ Assert.Throws<ArgumentNullException>(
+ () => s_converter.ConvertTo(s_context, null, c_conversionInputValue, null));
- Assert.Throws<NotSupportedException>(
- () => s_converter.ConvertTo(s_context, null, c_conversionInputValue, typeof(int)));
+ Assert.Throws<NotSupportedException>(
+ () => s_converter.ConvertTo(s_context, null, c_conversionInputValue, typeof(int)));
- object o = s_converter.ConvertTo(s_context, null, c_conversionInputValue, typeof(string));
- VerifyConversionToString(o);
+ object o = s_converter.ConvertTo(s_context, null, c_conversionInputValue, typeof(string));
+ VerifyConversionToString(o);
- o = s_converter.ConvertTo(
- s_context, CultureInfo.CurrentCulture, c_conversionInputValue, typeof(string));
- VerifyConversionToString(o);
+ o = s_converter.ConvertTo(
+ s_context, CultureInfo.CurrentCulture, c_conversionInputValue, typeof(string));
+ VerifyConversionToString(o);
- o = s_converter.ConvertTo(
- s_context, CultureInfo.InvariantCulture, c_conversionInputValue, typeof(string));
- VerifyConversionToString(o);
+ o = s_converter.ConvertTo(
+ s_context, CultureInfo.InvariantCulture, c_conversionInputValue, typeof(string));
+ VerifyConversionToString(o);
- string s = s_converter.ConvertTo(
- s_context, CultureInfo.InvariantCulture, new FormattableClass(), typeof(string)) as string;
- Assert.NotNull(s);
- Assert.Equal(FormattableClass.Token, s);
- return RemoteExecutor.SuccessExitCode;
+ string s = s_converter.ConvertTo(
+ s_context, CultureInfo.InvariantCulture, new FormattableClass(), typeof(string)) as string;
+ Assert.NotNull(s);
+ Assert.Equal(FormattableClass.Token, s);
+ }
}).Dispose();
}
// See the LICENSE file in the project root for more information.
using System.Globalization;
+using System.Tests;
using Microsoft.DotNet.RemoteExecutor;
using Xunit;
[Fact]
public static void ConvertTo_WithContext()
{
- RemoteExecutor.Invoke(() =>
+ RemoteExecutorForUap.Invoke(() =>
{
- CultureInfo.CurrentUICulture = CultureInfo.InvariantCulture;
-
- ConvertTo_WithContext(new object[2, 3]
- {
- { typeof(char), "System.Char", null }, // the base class is not verifying if this type is not in the list
- { null, "(none)", CultureInfo.InvariantCulture }
- },
- TypeListConverterTests.s_converter);
+ using (new ThreadCultureChange(CultureInfo.InvariantCulture))
+ {
+ ConvertTo_WithContext(new object[2, 3]
+ {
+ { typeof(char), "System.Char", null }, // the base class is not verifying if this type is not in the list
+ { null, "(none)", CultureInfo.InvariantCulture }
+ },
+ TypeListConverterTests.s_converter);
+ }
}).Dispose();
}
using System.Configuration;
using System.Diagnostics;
using System.Globalization;
+using System.Tests;
using Microsoft.DotNet.RemoteExecutor;
using Xunit;
[Fact]
public void MinValueString_TooSmall()
{
- RemoteExecutor.Invoke(() =>
+ RemoteExecutorForUap.Invoke(() =>
{
- CultureInfo.CurrentUICulture = CultureInfo.InvariantCulture;
-
- TimeSpanValidatorAttribute attribute = new TimeSpanValidatorAttribute();
-
- attribute.MaxValueString = new TimeSpan(2, 2, 2, 2).ToString();
- ArgumentOutOfRangeException result = Assert.Throws<ArgumentOutOfRangeException>(() =>
- attribute.MinValueString = new TimeSpan(3, 3, 3, 3).ToString());
- ArgumentOutOfRangeException expectedException =
- new ArgumentOutOfRangeException("value", SR.Validator_min_greater_than_max);
- Assert.Equal(expectedException.Message, result.Message);
+ using (new ThreadCultureChange(CultureInfo.InvariantCulture))
+ {
+ TimeSpanValidatorAttribute attribute = new TimeSpanValidatorAttribute();
+
+ attribute.MaxValueString = new TimeSpan(2, 2, 2, 2).ToString();
+ ArgumentOutOfRangeException result = Assert.Throws<ArgumentOutOfRangeException>(() =>
+ attribute.MinValueString = new TimeSpan(3, 3, 3, 3).ToString());
+ ArgumentOutOfRangeException expectedException =
+ new ArgumentOutOfRangeException("value", SR.Validator_min_greater_than_max);
+ Assert.Equal(expectedException.Message, result.Message);
+ }
}).Dispose();
}
[Fact]
public void MaxValueString_TooBig()
{
- RemoteExecutor.Invoke(() =>
+ RemoteExecutorForUap.Invoke(() =>
{
- CultureInfo.CurrentUICulture = CultureInfo.InvariantCulture;
-
- TimeSpanValidatorAttribute attribute = new TimeSpanValidatorAttribute();
-
- attribute.MinValueString = new TimeSpan(2, 2, 2, 2).ToString();
- ArgumentOutOfRangeException result = Assert.Throws<ArgumentOutOfRangeException>(() =>
- attribute.MaxValueString = new TimeSpan(1, 1, 1, 1).ToString());
- ArgumentOutOfRangeException expectedException =
- new ArgumentOutOfRangeException("value", SR.Validator_min_greater_than_max);
- Assert.Equal(expectedException.Message, result.Message);
+ using (new ThreadCultureChange(CultureInfo.InvariantCulture))
+ {
+ TimeSpanValidatorAttribute attribute = new TimeSpanValidatorAttribute();
+
+ attribute.MinValueString = new TimeSpan(2, 2, 2, 2).ToString();
+ ArgumentOutOfRangeException result = Assert.Throws<ArgumentOutOfRangeException>(() =>
+ attribute.MaxValueString = new TimeSpan(1, 1, 1, 1).ToString());
+ ArgumentOutOfRangeException expectedException =
+ new ArgumentOutOfRangeException("value", SR.Validator_min_greater_than_max);
+ Assert.Equal(expectedException.Message, result.Message);
+ }
}).Dispose();
}
}
// Release CancelKeyPress
mre.Set();
-
- return RemoteExecutor.SuccessExitCode;
}).Dispose();
}
{
Console.CancelKeyPress -= handler;
}
-
- return RemoteExecutor.SuccessExitCode;
}, signalOuter.ToString()).Dispose();
}
{
CanAddAndRemoveHandler();
CanAddAndRemoveHandler(); // add and remove again
- return RemoteExecutor.SuccessExitCode;
}).Dispose();
}
}
Console.InputEncoding = encoding;
Assert.Equal(encoding, Console.InputEncoding);
Assert.Equal((uint)encoding.CodePage, GetConsoleCP());
-
- return RemoteExecutor.SuccessExitCode;
}).Dispose();
}
Console.InputEncoding = unicodeEncoding;
Assert.Equal(unicodeEncoding, Console.InputEncoding);
Assert.Equal((uint)oldEncoding.CodePage, GetConsoleCP());
-
- return RemoteExecutor.SuccessExitCode;
}).Dispose();
}
Console.OutputEncoding = encoding;
Assert.Equal(encoding, Console.OutputEncoding);
Assert.Equal((uint)encoding.CodePage, GetConsoleOutputCP());
-
- return RemoteExecutor.SuccessExitCode;
}).Dispose();
}
Assert.Equal(unicodeEncoding, Console.OutputEncoding);
Assert.Equal((uint)oldEncoding.CodePage, GetConsoleOutputCP());
-
- return RemoteExecutor.SuccessExitCode;
}).Dispose();
}
// (assuming input isn't redirected).
Assert.NotSame(inReader, Console.In);
}
-
- return RemoteExecutor.SuccessExitCode;
}).Dispose();
}
Assert.NotSame(errorWriter, Console.Error);
Assert.NotSame(outWriter, Console.Out);
-
- return RemoteExecutor.SuccessExitCode;
}).Dispose();
}
{
Console.Write(data);
}
-
- return RemoteExecutor.SuccessExitCode;
}, new RemoteInvokeOptions { StartInfo = new ProcessStartInfo() { RedirectStandardOutput = true } });
using (remote)
RemoteExecutor.Invoke(() =>
{
Console.Title = "Title set by unit test";
- return RemoteExecutor.SuccessExitCode;
}).Dispose();
}
{
Assert.Equal(newTitle, Console.Title);
}
- return RemoteExecutor.SuccessExitCode;
}, lengthOfTitle.ToString()).Dispose();
}
using System.Xml;
using Microsoft.DotNet.RemoteExecutor;
using Xunit;
+using System.Tests;
namespace System.Data.Tests
{
[Fact]
public void LocaleOnRootWithoutIsDataSet()
{
- RemoteExecutor.Invoke(() =>
+ RemoteExecutorForUap.Invoke(() =>
{
- CultureInfo.CurrentCulture = new CultureInfo("fi-FI");
- string xs = @"<xs:schema xmlns:xs='http://www.w3.org/2001/XMLSchema' xmlns:msdata='urn:schemas-microsoft-com:xml-msdata'>
+ using (new ThreadCultureChange("fi-FI"))
+ {
+ string xs = @"<xs:schema xmlns:xs='http://www.w3.org/2001/XMLSchema' xmlns:msdata='urn:schemas-microsoft-com:xml-msdata'>
<xs:element name='Root' msdata:Locale='ja-JP'>
<xs:complexType>
<xs:sequence>
</xs:element>
</xs:schema>";
- var ds = new DataSet();
- ds.ReadXmlSchema(new StringReader(xs));
- DataSetAssertion.AssertDataSet("ds", ds, "NewDataSet", 1, 0);
- Assert.Equal("fi-FI", ds.Locale.Name); // DataSet's Locale comes from current thread
- DataTable dt = ds.Tables[0];
- DataSetAssertion.AssertDataTable("dt", dt, "Root", 2, 0, 0, 0, 0, 0);
- Assert.Equal("ja-JP", dt.Locale.Name); // DataTable's Locale comes from msdata:Locale
- DataSetAssertion.AssertDataColumn("col1", dt.Columns[0], "Attr", true, false, 0, 1, "Attr", MappingType.Attribute, typeof(long), DBNull.Value, string.Empty, -1, string.Empty, 0, string.Empty, false, false);
- DataSetAssertion.AssertDataColumn("col2", dt.Columns[1], "Child", false, false, 0, 1, "Child", MappingType.Element, typeof(string), DBNull.Value, string.Empty, -1, string.Empty, 1, string.Empty, false, false);
-
- return RemoteExecutor.SuccessExitCode;
+ var ds = new DataSet();
+ ds.ReadXmlSchema(new StringReader(xs));
+ DataSetAssertion.AssertDataSet("ds", ds, "NewDataSet", 1, 0);
+ Assert.Equal("fi-FI", ds.Locale.Name); // DataSet's Locale comes from current thread
+ DataTable dt = ds.Tables[0];
+ DataSetAssertion.AssertDataTable("dt", dt, "Root", 2, 0, 0, 0, 0, 0);
+ Assert.Equal("ja-JP", dt.Locale.Name); // DataTable's Locale comes from msdata:Locale
+ DataSetAssertion.AssertDataColumn("col1", dt.Columns[0], "Attr", true, false, 0, 1, "Attr", MappingType.Attribute, typeof(long), DBNull.Value, string.Empty, -1, string.Empty, 0, string.Empty, false, false);
+ DataSetAssertion.AssertDataColumn("col2", dt.Columns[1], "Child", false, false, 0, 1, "Child", MappingType.Element, typeof(string), DBNull.Value, string.Empty, -1, string.Empty, 1, string.Empty, false, false);
+ }
}).Dispose();
}
using System.Diagnostics;
using Microsoft.DotNet.RemoteExecutor;
using Xunit;
+using System.Tests;
namespace System.Data.Tests
{
[Fact]
public void WriteXmlSchema()
{
- RemoteExecutor.Invoke(() =>
+ RemoteExecutorForUap.Invoke(() =>
{
- CultureInfo.CurrentCulture = new CultureInfo("fi-FI");
-
- var ds = new DataSet();
- ds.ReadXml(new StringReader(DataProvider.region));
- TextWriter writer = new StringWriter();
- ds.WriteXmlSchema(writer);
-
-
- string TextString = DataSetAssertion.GetNormalizedSchema(writer.ToString());
- // string TextString = writer.ToString ();
-
- string substring = TextString.Substring(0, TextString.IndexOfAny(new[] { '\r', '\n' }));
- TextString = TextString.Substring(TextString.IndexOf('\n') + 1);
- Assert.Equal("<?xml version=\"1.0\" encoding=\"utf-16\"?>", substring);
-
- substring = TextString.Substring(0, TextString.IndexOfAny(new[] { '\r', '\n' }));
- TextString = TextString.Substring(TextString.IndexOf('\n') + 1);
- // This is original DataSet.WriteXmlSchema() output
- // Assert.Equal ("<xs:schema id=\"Root\" xmlns=\"\" xmlns:xs=\"http://www.w3.org/2001/XMLSchema\" xmlns:msdata=\"urn:schemas-microsoft-com:xml-msdata\">", substring);
- Assert.Equal("<xs:schema id=\"Root\" xmlns:msdata=\"urn:schemas-microsoft-com:xml-msdata\" xmlns:xs=\"http://www.w3.org/2001/XMLSchema\">", substring);
-
- substring = TextString.Substring(0, TextString.IndexOfAny(new[] { '\r', '\n' }));
- TextString = TextString.Substring(TextString.IndexOf('\n') + 1);
- Assert.Equal(" <xs:element msdata:IsDataSet=\"true\" msdata:Locale=\"en-US\" name=\"Root\">", substring);
-
- substring = TextString.Substring(0, TextString.IndexOfAny(new[] { '\r', '\n' }));
- TextString = TextString.Substring(TextString.IndexOf('\n') + 1);
- Assert.Equal(" <xs:complexType>", substring);
-
- substring = TextString.Substring(0, TextString.IndexOfAny(new[] { '\r', '\n' }));
- TextString = TextString.Substring(TextString.IndexOf('\n') + 1);
- Assert.Equal(" <xs:choice maxOccurs=\"unbounded\" minOccurs=\"0\">", substring);
-
- substring = TextString.Substring(0, TextString.IndexOfAny(new[] { '\r', '\n' }));
- TextString = TextString.Substring(TextString.IndexOf('\n') + 1);
- Assert.Equal(" <xs:element name=\"Region\">", substring);
-
- substring = TextString.Substring(0, TextString.IndexOfAny(new[] { '\r', '\n' }));
- TextString = TextString.Substring(TextString.IndexOf('\n') + 1);
- Assert.Equal(" <xs:complexType>", substring);
-
- substring = TextString.Substring(0, TextString.IndexOfAny(new[] { '\r', '\n' }));
- TextString = TextString.Substring(TextString.IndexOf('\n') + 1);
- Assert.Equal(" <xs:sequence>", substring);
-
- substring = TextString.Substring(0, TextString.IndexOfAny(new[] { '\r', '\n' }));
- TextString = TextString.Substring(TextString.IndexOf('\n') + 1);
- // This is original DataSet.WriteXmlSchema() output
- // Assert.Equal (" <xs:element name=\"RegionID\" type=\"xs:string\" minOccurs=\"0\" />", substring);
- Assert.Equal(" <xs:element minOccurs=\"0\" name=\"RegionID\" type=\"xs:string\" />", substring);
-
- substring = TextString.Substring(0, TextString.IndexOfAny(new[] { '\r', '\n' }));
- TextString = TextString.Substring(TextString.IndexOf('\n') + 1);
- // This is original DataSet.WriteXmlSchema() output
- // Assert.Equal (" <xs:element name=\"RegionDescription\" type=\"xs:string\" minOccurs=\"0\" />", substring);
- Assert.Equal(" <xs:element minOccurs=\"0\" name=\"RegionDescription\" type=\"xs:string\" />", substring);
-
- substring = TextString.Substring(0, TextString.IndexOfAny(new[] { '\r', '\n' }));
- TextString = TextString.Substring(TextString.IndexOf('\n') + 1);
- Assert.Equal(" </xs:sequence>", substring);
-
- substring = TextString.Substring(0, TextString.IndexOfAny(new[] { '\r', '\n' }));
- TextString = TextString.Substring(TextString.IndexOf('\n') + 1);
- Assert.Equal(" </xs:complexType>", substring);
-
- substring = TextString.Substring(0, TextString.IndexOfAny(new[] { '\r', '\n' }));
- TextString = TextString.Substring(TextString.IndexOf('\n') + 1);
- Assert.Equal(" </xs:element>", substring);
-
- substring = TextString.Substring(0, TextString.IndexOfAny(new[] { '\r', '\n' }));
- TextString = TextString.Substring(TextString.IndexOf('\n') + 1);
- Assert.Equal(" </xs:choice>", substring);
-
- substring = TextString.Substring(0, TextString.IndexOfAny(new[] { '\r', '\n' }));
- TextString = TextString.Substring(TextString.IndexOf('\n') + 1);
- Assert.Equal(" </xs:complexType>", substring);
-
- substring = TextString.Substring(0, TextString.IndexOfAny(new[] { '\r', '\n' }));
- TextString = TextString.Substring(TextString.IndexOf('\n') + 1);
- Assert.Equal(" </xs:element>", substring);
-
- Assert.Equal("</xs:schema>", TextString);
-
- return RemoteExecutor.SuccessExitCode;
+ using (new ThreadCultureChange("fi-FI"))
+ {
+ var ds = new DataSet();
+ ds.ReadXml(new StringReader(DataProvider.region));
+ TextWriter writer = new StringWriter();
+ ds.WriteXmlSchema(writer);
+
+
+ string TextString = DataSetAssertion.GetNormalizedSchema(writer.ToString());
+ // string TextString = writer.ToString ();
+
+ string substring = TextString.Substring(0, TextString.IndexOfAny(new[] { '\r', '\n' }));
+ TextString = TextString.Substring(TextString.IndexOf('\n') + 1);
+ Assert.Equal("<?xml version=\"1.0\" encoding=\"utf-16\"?>", substring);
+
+ substring = TextString.Substring(0, TextString.IndexOfAny(new[] { '\r', '\n' }));
+ TextString = TextString.Substring(TextString.IndexOf('\n') + 1);
+ // This is original DataSet.WriteXmlSchema() output
+ // Assert.Equal ("<xs:schema id=\"Root\" xmlns=\"\" xmlns:xs=\"http://www.w3.org/2001/XMLSchema\" xmlns:msdata=\"urn:schemas-microsoft-com:xml-msdata\">", substring);
+ Assert.Equal("<xs:schema id=\"Root\" xmlns:msdata=\"urn:schemas-microsoft-com:xml-msdata\" xmlns:xs=\"http://www.w3.org/2001/XMLSchema\">", substring);
+
+ substring = TextString.Substring(0, TextString.IndexOfAny(new[] { '\r', '\n' }));
+ TextString = TextString.Substring(TextString.IndexOf('\n') + 1);
+ Assert.Equal(" <xs:element msdata:IsDataSet=\"true\" msdata:Locale=\"en-US\" name=\"Root\">", substring);
+
+ substring = TextString.Substring(0, TextString.IndexOfAny(new[] { '\r', '\n' }));
+ TextString = TextString.Substring(TextString.IndexOf('\n') + 1);
+ Assert.Equal(" <xs:complexType>", substring);
+
+ substring = TextString.Substring(0, TextString.IndexOfAny(new[] { '\r', '\n' }));
+ TextString = TextString.Substring(TextString.IndexOf('\n') + 1);
+ Assert.Equal(" <xs:choice maxOccurs=\"unbounded\" minOccurs=\"0\">", substring);
+
+ substring = TextString.Substring(0, TextString.IndexOfAny(new[] { '\r', '\n' }));
+ TextString = TextString.Substring(TextString.IndexOf('\n') + 1);
+ Assert.Equal(" <xs:element name=\"Region\">", substring);
+
+ substring = TextString.Substring(0, TextString.IndexOfAny(new[] { '\r', '\n' }));
+ TextString = TextString.Substring(TextString.IndexOf('\n') + 1);
+ Assert.Equal(" <xs:complexType>", substring);
+
+ substring = TextString.Substring(0, TextString.IndexOfAny(new[] { '\r', '\n' }));
+ TextString = TextString.Substring(TextString.IndexOf('\n') + 1);
+ Assert.Equal(" <xs:sequence>", substring);
+
+ substring = TextString.Substring(0, TextString.IndexOfAny(new[] { '\r', '\n' }));
+ TextString = TextString.Substring(TextString.IndexOf('\n') + 1);
+ // This is original DataSet.WriteXmlSchema() output
+ // Assert.Equal (" <xs:element name=\"RegionID\" type=\"xs:string\" minOccurs=\"0\" />", substring);
+ Assert.Equal(" <xs:element minOccurs=\"0\" name=\"RegionID\" type=\"xs:string\" />", substring);
+
+ substring = TextString.Substring(0, TextString.IndexOfAny(new[] { '\r', '\n' }));
+ TextString = TextString.Substring(TextString.IndexOf('\n') + 1);
+ // This is original DataSet.WriteXmlSchema() output
+ // Assert.Equal (" <xs:element name=\"RegionDescription\" type=\"xs:string\" minOccurs=\"0\" />", substring);
+ Assert.Equal(" <xs:element minOccurs=\"0\" name=\"RegionDescription\" type=\"xs:string\" />", substring);
+
+ substring = TextString.Substring(0, TextString.IndexOfAny(new[] { '\r', '\n' }));
+ TextString = TextString.Substring(TextString.IndexOf('\n') + 1);
+ Assert.Equal(" </xs:sequence>", substring);
+
+ substring = TextString.Substring(0, TextString.IndexOfAny(new[] { '\r', '\n' }));
+ TextString = TextString.Substring(TextString.IndexOf('\n') + 1);
+ Assert.Equal(" </xs:complexType>", substring);
+
+ substring = TextString.Substring(0, TextString.IndexOfAny(new[] { '\r', '\n' }));
+ TextString = TextString.Substring(TextString.IndexOf('\n') + 1);
+ Assert.Equal(" </xs:element>", substring);
+
+ substring = TextString.Substring(0, TextString.IndexOfAny(new[] { '\r', '\n' }));
+ TextString = TextString.Substring(TextString.IndexOf('\n') + 1);
+ Assert.Equal(" </xs:choice>", substring);
+
+ substring = TextString.Substring(0, TextString.IndexOfAny(new[] { '\r', '\n' }));
+ TextString = TextString.Substring(TextString.IndexOf('\n') + 1);
+ Assert.Equal(" </xs:complexType>", substring);
+
+ substring = TextString.Substring(0, TextString.IndexOfAny(new[] { '\r', '\n' }));
+ TextString = TextString.Substring(TextString.IndexOf('\n') + 1);
+ Assert.Equal(" </xs:element>", substring);
+
+ Assert.Equal("</xs:schema>", TextString);
+ }
}).Dispose();
}
[Fact]
public void WriteXmlModeSchema1()
{
- RemoteExecutor.Invoke(() =>
+ RemoteExecutorForUap.Invoke(() =>
{
- CultureInfo.CurrentCulture = new CultureInfo("fi-FI");
- string SerializedDataTable =
-@"<rdData>
+ using (new ThreadCultureChange("fi-FI"))
+ {
+ string SerializedDataTable =
+ @"<rdData>
<MyDataTable CustomerID='VINET' CompanyName='Vins et alcools Chevalier' ContactName='Paul Henriot' />
</rdData>";
- string expected =
- @"<rdData>
+ string expected =
+ @"<rdData>
<xs:schema id=""rdData"" xmlns="""" xmlns:xs=""http://www.w3.org/2001/XMLSchema"" xmlns:msdata=""urn:schemas-microsoft-com:xml-msdata"">
<xs:element name=""rdData"" msdata:IsDataSet=""true"" " +
- @"msdata:Locale=""en-US"">" +
- @"
+ @"msdata:Locale=""en-US"">" +
+ @"
<xs:complexType>
<xs:choice minOccurs=""0"" maxOccurs=""unbounded"">
<xs:element name=""MyDataTable"">
</xs:schema>
<MyDataTable CustomerID=""VINET"" CompanyName=""Vins et alcools Chevalier"" ContactName=""Paul Henriot"" />
</rdData>";
- DataSet set;
- set = new DataSet();
- set.ReadXml(new StringReader(SerializedDataTable));
-
- StringWriter w = new StringWriter();
- set.WriteXml(w, XmlWriteMode.WriteSchema);
- string result = w.ToString();
- Assert.Equal(expected.Replace("\r", ""), result.Replace("\r", ""));
-
- return RemoteExecutor.SuccessExitCode;
+ DataSet set;
+ set = new DataSet();
+ set.ReadXml(new StringReader(SerializedDataTable));
+
+ StringWriter w = new StringWriter();
+ set.WriteXml(w, XmlWriteMode.WriteSchema);
+ string result = w.ToString();
+ Assert.Equal(expected.Replace("\r", ""), result.Replace("\r", ""));
+ }
}).Dispose();
}
using System.Globalization;
using Microsoft.DotNet.RemoteExecutor;
using Xunit;
+using System.Tests;
namespace System.Data.Tests
{
[Fact]
public void DataSetSpecificCulture()
{
- RemoteExecutor.Invoke(() =>
+ RemoteExecutorForUap.Invoke(() =>
{
- CultureInfo.CurrentCulture = new CultureInfo("cs-CZ");
-
- var ds = new DataSet();
- ds.Locale = CultureInfo.GetCultureInfo(1033);
- var dt = ds.Tables.Add("machine");
- dt.Locale = ds.Locale;
- Assert.Same(dt, ds.Tables["MACHINE"]);
-
- return RemoteExecutor.SuccessExitCode;
+ using (new ThreadCultureChange("cs-CZ"))
+ {
+ var ds = new DataSet();
+ ds.Locale = CultureInfo.GetCultureInfo(1033);
+ var dt = ds.Tables.Add("machine");
+ dt.Locale = ds.Locale;
+ Assert.Same(dt, ds.Tables["MACHINE"]);
+ }
}).Dispose();
}
using System.Runtime.Serialization.Formatters.Binary;
using Microsoft.DotNet.RemoteExecutor;
using Xunit;
+using System.Tests;
namespace System.Data.Tests
{
[Fact]
public void XsdSchemaSerializationIgnoresLocale()
{
- RemoteExecutor.Invoke(() =>
+ RemoteExecutorForUap.Invoke(() =>
{
var serializer = new BinaryFormatter();
var table = new DataTable();
table.Rows.Add(2, "Data");
var buffer = new MemoryStream();
- var savedCulture = CultureInfo.CurrentCulture;
- try
+ using (new ThreadCultureChange(new CultureInfo("en-US") { NumberFormat = new NumberFormatInfo() { NegativeSign = "()" } }))
{
// Before serializing, update the culture to use a weird negative number format. This test is ensuring that this is ignored.
- CultureInfo.CurrentCulture = new CultureInfo("en-US")
- {
- NumberFormat = new NumberFormatInfo()
- {
- NegativeSign = "()"
- }
- };
serializer.Serialize(buffer, table);
}
- finally
- {
- CultureInfo.CurrentCulture = savedCulture;
- }
// The raw serialized data now contains an embedded XML schema. We need to verify that this embedded schema used "-1" for the numeric value
// negative 1, instead of "()1" as indicated by the current culture.
[SkipOnTargetFramework(TargetFrameworkMonikers.NetFramework, "Full framework does not yet have the fix for this bug")]
public void XsdSchemaDeserializationIgnoresLocale()
{
- RemoteExecutor.Invoke(() =>
+ RemoteExecutorForUap.Invoke(() =>
{
var serializer = new BinaryFormatter();
});
DataTable table;
- var savedCulture = CultureInfo.CurrentCulture;
- try
+ using (new ThreadCultureChange(new CultureInfo("en-US") { NumberFormat = new NumberFormatInfo() { NegativeSign = "()" } }))
{
// Before deserializing, update the culture to use a weird negative number format. This test is ensuring that this is ignored.
// The bug this test is testing would cause "-1" to no longer be treated as a valid representation of the value -1, instead
// only accepting the string "()1".
- CultureInfo.CurrentCulture = new CultureInfo("en-US")
- {
- NumberFormat = new NumberFormatInfo()
- {
- NegativeSign = "()"
- }
- };
table = (DataTable)serializer.Deserialize(buffer); // BUG: System.Exception: "-1 is not a valid value for Int64." }
}
- finally
- {
- CultureInfo.CurrentCulture = savedCulture;
- }
DataColumn rowIDColumn = table.Columns["RowID"];
Assert.Equal(-1, rowIDColumn.AutoIncrementSeed);
using System.IO;
using System.Runtime.Serialization.Formatters.Binary;
using System.Runtime.Serialization.Formatters.Tests;
+using System.Tests;
using System.Text.RegularExpressions;
using System.Xml;
using Microsoft.DotNet.RemoteExecutor;
[Fact]
public void PropertyExceptions()
{
- RemoteExecutor.Invoke(() =>
- {
- DataSet set = new DataSet();
- DataTable table = new DataTable();
- DataTable table1 = new DataTable();
- set.Tables.Add(table);
- set.Tables.Add(table1);
-
- DataColumn col = new DataColumn();
- col.ColumnName = "Id";
- col.DataType = typeof(int);
- table.Columns.Add(col);
- UniqueConstraint uc = new UniqueConstraint("UK1", table.Columns[0]);
- table.Constraints.Add(uc);
- table.CaseSensitive = false;
-
- col = new DataColumn();
- col.ColumnName = "Name";
- col.DataType = typeof(string);
- table.Columns.Add(col);
-
- col = new DataColumn();
- col.ColumnName = "Id";
- col.DataType = typeof(int);
- table1.Columns.Add(col);
- col = new DataColumn();
- col.ColumnName = "Name";
- col.DataType = typeof(string);
- table1.Columns.Add(col);
-
- DataRelation dr = new DataRelation("DR", table.Columns[0], table1.Columns[0]);
- set.Relations.Add(dr);
-
- Assert.Throws<ArgumentException>(() =>
- {
- // Set to a different sensitivity than before: this breaks the DataRelation constraint
- // because it is not the sensitivity of the related table
- table.CaseSensitive = true;
- });
+ DataSet set = new DataSet();
+ DataTable table = new DataTable();
+ DataTable table1 = new DataTable();
+ set.Tables.Add(table);
+ set.Tables.Add(table1);
- Assert.Throws<ArgumentException>(() =>
- {
- // Set to a different culture than before: this breaks the DataRelation constraint
- // because it is not the locale of the related table
- CultureInfo cultureInfo = table.Locale.Name == "en-US" ? new CultureInfo("en-GB") : new CultureInfo("en-US");
- table.Locale = cultureInfo;
- });
+ DataColumn col = new DataColumn();
+ col.ColumnName = "Id";
+ col.DataType = typeof(int);
+ table.Columns.Add(col);
+ UniqueConstraint uc = new UniqueConstraint("UK1", table.Columns[0]);
+ table.Constraints.Add(uc);
+ table.CaseSensitive = false;
- Assert.Throws<DataException>(() => table.Prefix = "Prefix#1");
+ col = new DataColumn();
+ col.ColumnName = "Name";
+ col.DataType = typeof(string);
+ table.Columns.Add(col);
- return RemoteExecutor.SuccessExitCode;
- }).Dispose();
+ col = new DataColumn();
+ col.ColumnName = "Id";
+ col.DataType = typeof(int);
+ table1.Columns.Add(col);
+ col = new DataColumn();
+ col.ColumnName = "Name";
+ col.DataType = typeof(string);
+ table1.Columns.Add(col);
+
+ DataRelation dr = new DataRelation("DR", table.Columns[0], table1.Columns[0]);
+ set.Relations.Add(dr);
+
+ Assert.Throws<ArgumentException>(() =>
+ {
+ // Set to a different sensitivity than before: this breaks the DataRelation constraint
+ // because it is not the sensitivity of the related table
+ table.CaseSensitive = true;
+ });
+
+ Assert.Throws<ArgumentException>(() =>
+ {
+ // Set to a different culture than before: this breaks the DataRelation constraint
+ // because it is not the locale of the related table
+ CultureInfo cultureInfo = table.Locale.Name == "en-US" ? new CultureInfo("en-GB") : new CultureInfo("en-US");
+ table.Locale = cultureInfo;
+ });
+
+ Assert.Throws<DataException>(() => table.Prefix = "Prefix#1");
}
[Fact]
[Fact]
public void WriteXmlSchema()
{
- RemoteExecutor.Invoke(() =>
+ RemoteExecutorForUap.Invoke(() =>
{
- CultureInfo.CurrentCulture = new CultureInfo("en-GB");
-
- var ds = new DataSet();
- ds.ReadXml(new StringReader(DataProvider.region));
- TextWriter writer = new StringWriter();
- ds.Tables[0].WriteXmlSchema(writer);
-
- string TextString = DataSetAssertion.GetNormalizedSchema(writer.ToString());
- //string TextString = writer.ToString ();
+ using (new ThreadCultureChange("en-GB"))
+ {
+ var ds = new DataSet();
+ ds.ReadXml(new StringReader(DataProvider.region));
+ TextWriter writer = new StringWriter();
+ ds.Tables[0].WriteXmlSchema(writer);
- string substring = TextString.Substring(0, TextString.IndexOfAny(new[] { '\r', '\n' }));
- TextString = TextString.Substring(TextString.IndexOf('\n') + 1);
- Assert.Equal("<?xml version=\"1.0\" encoding=\"utf-16\"?>", substring);
+ string TextString = DataSetAssertion.GetNormalizedSchema(writer.ToString());
+ //string TextString = writer.ToString ();
- substring = TextString.Substring(0, TextString.IndexOfAny(new[] { '\r', '\n' }));
- TextString = TextString.Substring(TextString.IndexOf('\n') + 1);
- Assert.Equal("<xs:schema id=\"Root\" xmlns:msdata=\"urn:schemas-microsoft-com:xml-msdata\" xmlns:xs=\"http://www.w3.org/2001/XMLSchema\">", substring);
+ string substring = TextString.Substring(0, TextString.IndexOfAny(new[] { '\r', '\n' }));
+ TextString = TextString.Substring(TextString.IndexOf('\n') + 1);
+ Assert.Equal("<?xml version=\"1.0\" encoding=\"utf-16\"?>", substring);
- substring = TextString.Substring(0, TextString.IndexOfAny(new[] { '\r', '\n' }));
- TextString = TextString.Substring(TextString.IndexOf('\n') + 1);
- // Looks like whoever added this test depended on English culture, which is wrong.
- Assert.Equal(" <xs:element msdata:IsDataSet=\"true\" msdata:Locale=\"en-US\" msdata:MainDataTable=\"Region\" name=\"Root\">", substring);
+ substring = TextString.Substring(0, TextString.IndexOfAny(new[] { '\r', '\n' }));
+ TextString = TextString.Substring(TextString.IndexOf('\n') + 1);
+ Assert.Equal("<xs:schema id=\"Root\" xmlns:msdata=\"urn:schemas-microsoft-com:xml-msdata\" xmlns:xs=\"http://www.w3.org/2001/XMLSchema\">", substring);
- substring = TextString.Substring(0, TextString.IndexOfAny(new[] { '\r', '\n' }));
- TextString = TextString.Substring(TextString.IndexOf('\n') + 1);
- Assert.Equal(" <xs:complexType>", substring);
+ substring = TextString.Substring(0, TextString.IndexOfAny(new[] { '\r', '\n' }));
+ TextString = TextString.Substring(TextString.IndexOf('\n') + 1);
+ // Looks like whoever added this test depended on English culture, which is wrong.
+ Assert.Equal(" <xs:element msdata:IsDataSet=\"true\" msdata:Locale=\"en-US\" msdata:MainDataTable=\"Region\" name=\"Root\">", substring);
- substring = TextString.Substring(0, TextString.IndexOfAny(new[] { '\r', '\n' }));
- TextString = TextString.Substring(TextString.IndexOf('\n') + 1);
- Assert.Equal(" <xs:choice maxOccurs=\"unbounded\" minOccurs=\"0\">", substring);
+ substring = TextString.Substring(0, TextString.IndexOfAny(new[] { '\r', '\n' }));
+ TextString = TextString.Substring(TextString.IndexOf('\n') + 1);
+ Assert.Equal(" <xs:complexType>", substring);
- substring = TextString.Substring(0, TextString.IndexOfAny(new[] { '\r', '\n' }));
- TextString = TextString.Substring(TextString.IndexOf('\n') + 1);
- Assert.Equal(" <xs:element name=\"Region\">", substring);
+ substring = TextString.Substring(0, TextString.IndexOfAny(new[] { '\r', '\n' }));
+ TextString = TextString.Substring(TextString.IndexOf('\n') + 1);
+ Assert.Equal(" <xs:choice maxOccurs=\"unbounded\" minOccurs=\"0\">", substring);
- substring = TextString.Substring(0, TextString.IndexOfAny(new[] { '\r', '\n' }));
- TextString = TextString.Substring(TextString.IndexOf('\n') + 1);
- Assert.Equal(" <xs:complexType>", substring);
+ substring = TextString.Substring(0, TextString.IndexOfAny(new[] { '\r', '\n' }));
+ TextString = TextString.Substring(TextString.IndexOf('\n') + 1);
+ Assert.Equal(" <xs:element name=\"Region\">", substring);
- substring = TextString.Substring(0, TextString.IndexOfAny(new[] { '\r', '\n' }));
- TextString = TextString.Substring(TextString.IndexOf('\n') + 1);
- Assert.Equal(" <xs:sequence>", substring);
+ substring = TextString.Substring(0, TextString.IndexOfAny(new[] { '\r', '\n' }));
+ TextString = TextString.Substring(TextString.IndexOf('\n') + 1);
+ Assert.Equal(" <xs:complexType>", substring);
- substring = TextString.Substring(0, TextString.IndexOfAny(new[] { '\r', '\n' }));
- TextString = TextString.Substring(TextString.IndexOf('\n') + 1);
- Assert.Equal(" <xs:element minOccurs=\"0\" name=\"RegionID\" type=\"xs:string\" />", substring);
+ substring = TextString.Substring(0, TextString.IndexOfAny(new[] { '\r', '\n' }));
+ TextString = TextString.Substring(TextString.IndexOf('\n') + 1);
+ Assert.Equal(" <xs:sequence>", substring);
- substring = TextString.Substring(0, TextString.IndexOfAny(new[] { '\r', '\n' }));
- TextString = TextString.Substring(TextString.IndexOf('\n') + 1);
- Assert.Equal(" <xs:element minOccurs=\"0\" name=\"RegionDescription\" type=\"xs:string\" />", substring);
+ substring = TextString.Substring(0, TextString.IndexOfAny(new[] { '\r', '\n' }));
+ TextString = TextString.Substring(TextString.IndexOf('\n') + 1);
+ Assert.Equal(" <xs:element minOccurs=\"0\" name=\"RegionID\" type=\"xs:string\" />", substring);
- substring = TextString.Substring(0, TextString.IndexOfAny(new[] { '\r', '\n' }));
- TextString = TextString.Substring(TextString.IndexOf('\n') + 1);
- Assert.Equal(" </xs:sequence>", substring);
+ substring = TextString.Substring(0, TextString.IndexOfAny(new[] { '\r', '\n' }));
+ TextString = TextString.Substring(TextString.IndexOf('\n') + 1);
+ Assert.Equal(" <xs:element minOccurs=\"0\" name=\"RegionDescription\" type=\"xs:string\" />", substring);
- substring = TextString.Substring(0, TextString.IndexOfAny(new[] { '\r', '\n' }));
- TextString = TextString.Substring(TextString.IndexOf('\n') + 1);
- Assert.Equal(" </xs:complexType>", substring);
+ substring = TextString.Substring(0, TextString.IndexOfAny(new[] { '\r', '\n' }));
+ TextString = TextString.Substring(TextString.IndexOf('\n') + 1);
+ Assert.Equal(" </xs:sequence>", substring);
- substring = TextString.Substring(0, TextString.IndexOfAny(new[] { '\r', '\n' }));
- TextString = TextString.Substring(TextString.IndexOf('\n') + 1);
- Assert.Equal(" </xs:element>", substring);
+ substring = TextString.Substring(0, TextString.IndexOfAny(new[] { '\r', '\n' }));
+ TextString = TextString.Substring(TextString.IndexOf('\n') + 1);
+ Assert.Equal(" </xs:complexType>", substring);
- substring = TextString.Substring(0, TextString.IndexOfAny(new[] { '\r', '\n' }));
- TextString = TextString.Substring(TextString.IndexOf('\n') + 1);
- Assert.Equal(" </xs:choice>", substring);
+ substring = TextString.Substring(0, TextString.IndexOfAny(new[] { '\r', '\n' }));
+ TextString = TextString.Substring(TextString.IndexOf('\n') + 1);
+ Assert.Equal(" </xs:element>", substring);
- substring = TextString.Substring(0, TextString.IndexOfAny(new[] { '\r', '\n' }));
- TextString = TextString.Substring(TextString.IndexOf('\n') + 1);
- Assert.Equal(" </xs:complexType>", substring);
+ substring = TextString.Substring(0, TextString.IndexOfAny(new[] { '\r', '\n' }));
+ TextString = TextString.Substring(TextString.IndexOf('\n') + 1);
+ Assert.Equal(" </xs:choice>", substring);
- substring = TextString.Substring(0, TextString.IndexOfAny(new[] { '\r', '\n' }));
- TextString = TextString.Substring(TextString.IndexOf('\n') + 1);
- Assert.Equal(" </xs:element>", substring);
+ substring = TextString.Substring(0, TextString.IndexOfAny(new[] { '\r', '\n' }));
+ TextString = TextString.Substring(TextString.IndexOf('\n') + 1);
+ Assert.Equal(" </xs:complexType>", substring);
- Assert.Equal("</xs:schema>", TextString);
+ substring = TextString.Substring(0, TextString.IndexOfAny(new[] { '\r', '\n' }));
+ TextString = TextString.Substring(TextString.IndexOf('\n') + 1);
+ Assert.Equal(" </xs:element>", substring);
- return RemoteExecutor.SuccessExitCode;
+ Assert.Equal("</xs:schema>", TextString);
+ }
}).Dispose();
}
[Fact]
public void Bug82109()
{
- RemoteExecutor.Invoke(() =>
+ RemoteExecutorForUap.Invoke(() =>
{
DataTable tbl = new DataTable();
tbl.Columns.Add("data", typeof(DateTime));
row["Data"] = new DateTime(2007, 7, 1);
tbl.Rows.Add(row);
- CultureInfo.CurrentCulture = CultureInfo.InvariantCulture;
- Select(tbl);
-
- CultureInfo.CurrentCulture = new CultureInfo("it-IT");
- Select(tbl);
+ using (new ThreadCultureChange(CultureInfo.InvariantCulture))
+ {
+ Select(tbl);
+ }
- CultureInfo.CurrentCulture = new CultureInfo("fr-FR");
- Select(tbl);
+ using (new ThreadCultureChange("it-IT"))
+ {
+ Select(tbl);
+ }
- return RemoteExecutor.SuccessExitCode;
+ using (new ThreadCultureChange("fr-FR"))
+ {
+ Select(tbl);
+ }
}).Dispose();
}
using System.Diagnostics;
using Microsoft.DotNet.RemoteExecutor;
using Xunit;
+using System.Tests;
namespace System.Data.Tests.SqlTypes
{
[Fact]
public void Properties()
{
- RemoteExecutor.Invoke(() =>
+ RemoteExecutorForUap.Invoke(() =>
{
- CultureInfo.CurrentCulture = new CultureInfo("en-AU");
- var one = new SqlString("First TestString");
+ using (new ThreadCultureChange("en-AU"))
+ {
+ var one = new SqlString("First TestString");
- // CompareInfo
- Assert.Equal(3081, one.CompareInfo.LCID);
+ // CompareInfo
+ Assert.Equal(3081, one.CompareInfo.LCID);
- // CultureInfo
- Assert.Equal(3081, one.CultureInfo.LCID);
+ // CultureInfo
+ Assert.Equal(3081, one.CultureInfo.LCID);
- // LCID
- Assert.Equal(3081, one.LCID);
+ // LCID
+ Assert.Equal(3081, one.LCID);
- // IsNull
- Assert.True(!one.IsNull);
- Assert.True(SqlString.Null.IsNull);
+ // IsNull
+ Assert.True(!one.IsNull);
+ Assert.True(SqlString.Null.IsNull);
- // SqlCompareOptions
- Assert.Equal("IgnoreCase, IgnoreKanaType, IgnoreWidth", one.SqlCompareOptions.ToString());
+ // SqlCompareOptions
+ Assert.Equal("IgnoreCase, IgnoreKanaType, IgnoreWidth", one.SqlCompareOptions.ToString());
- // Value
- Assert.Equal("First TestString", one.Value);
-
- return RemoteExecutor.SuccessExitCode;
+ // Value
+ Assert.Equal("First TestString", one.Value);
+ }
}).Dispose();
}
var output = cmd.ExecuteScalar();
}
});
- return RemoteExecutor.SuccessExitCode;
}).Dispose();
}
catch { }
}
});
- return RemoteExecutor.SuccessExitCode;
}).Dispose();
}
var output = cmd.ExecuteNonQuery();
}
});
- return RemoteExecutor.SuccessExitCode;
}).Dispose();
}
}
Console.WriteLine("SqlClient.DiagnosticTest.ExecuteNonQueryErrorTest Connection Disposed");
});
- return RemoteExecutor.SuccessExitCode;
}).Dispose();
}
while (reader.Read()) { }
}
});
- return RemoteExecutor.SuccessExitCode;
}).Dispose();
}
catch { }
}
});
- return RemoteExecutor.SuccessExitCode;
}).Dispose();
}
while (reader.Read()) { }
}
});
- return RemoteExecutor.SuccessExitCode;
}).Dispose();
}
while (reader.Read()) { }
}
});
- return RemoteExecutor.SuccessExitCode;
}, s_tcpConnStr).Dispose();
}
catch { }
}
});
- return RemoteExecutor.SuccessExitCode;
}).Dispose();
}
var output = await cmd.ExecuteScalarAsync();
}
}).GetAwaiter().GetResult();
- return RemoteExecutor.SuccessExitCode;
}).Dispose();
}
catch { }
}
}).GetAwaiter().GetResult();
- return RemoteExecutor.SuccessExitCode;
}).Dispose();
}
var output = await cmd.ExecuteNonQueryAsync();
}
}).GetAwaiter().GetResult();
- return RemoteExecutor.SuccessExitCode;
}).Dispose();
}
catch { }
}
}).GetAwaiter().GetResult();
- return RemoteExecutor.SuccessExitCode;
}).Dispose();
}
while (reader.Read()) { }
}
}).GetAwaiter().GetResult();
- return RemoteExecutor.SuccessExitCode;
}).Dispose();
}
catch { }
}
}).GetAwaiter().GetResult();
- return RemoteExecutor.SuccessExitCode;
}).Dispose();
}
while (reader.Read()) { }
}
}).GetAwaiter().GetResult();
- return RemoteExecutor.SuccessExitCode;
}, s_tcpConnStr).Dispose();
}
catch { }
}
}).GetAwaiter().GetResult();
- return RemoteExecutor.SuccessExitCode;
}, s_tcpConnStr).Dispose();
}
}, true);
Console.WriteLine("SqlClient.DiagnosticsTest.ConnectionOpenTest:: Done with Diagnostics collection");
- return RemoteExecutor.SuccessExitCode;
}).Dispose();
}
try { sqlConnection.Open(); } catch { }
}
});
- return RemoteExecutor.SuccessExitCode;
}).Dispose();
}
await sqlConnection.OpenAsync();
}
}).GetAwaiter().GetResult();
- return RemoteExecutor.SuccessExitCode;
}).Dispose();
}
try { await sqlConnection.OpenAsync(); } catch { }
}
}).GetAwaiter().GetResult();
- return RemoteExecutor.SuccessExitCode;
}).Dispose();
}
Assert.DoesNotContain(Environment.NewLine, writerOutput);
}
}
-
- return RemoteExecutor.SuccessExitCode;
}, value.ToString()).Dispose();
}
Assert.Contains(message, stringWriter.ToString() + Environment.NewLine);
}
}
-
- return RemoteExecutor.SuccessExitCode;
}, value.ToString()).Dispose();
}
}
// See the LICENSE file in the project root for more information.
using System.Collections.Generic;
-using System.Common.Tests;
using System.Globalization;
using System.Reflection;
+using System.Tests;
using System.Threading;
using Xunit;
[MemberData(nameof(FromHtml_TestData))]
public void FromHtml_String_ReturnsExpected(string htmlColor, Color expected)
{
- using (new ThreadCultureChange(CultureInfo.InvariantCulture))
+ using (new ThreadCultureChange(CultureInfo.InvariantCulture, CultureInfo.InvariantCulture))
{
Assert.Equal(expected, ColorTranslator.FromHtml(htmlColor));
}
[InlineData("&hG12")]
public void FromHtml_Invalid_Throws(string htmlColor)
{
- using (new ThreadCultureChange(CultureInfo.InvariantCulture))
+ using (new ThreadCultureChange(CultureInfo.InvariantCulture, CultureInfo.InvariantCulture))
{
Exception exception = AssertExtensions.Throws<ArgumentException, Exception>(() => ColorTranslator.FromHtml(htmlColor));
if (exception is ArgumentException argumentException)
[InlineData("1,2,256", typeof(ArgumentException))]
public void FromHtml_Invalid_Throw(string htmlColor, Type exception)
{
- using (new ThreadCultureChange(CultureInfo.InvariantCulture))
+ using (new ThreadCultureChange(CultureInfo.InvariantCulture, CultureInfo.InvariantCulture))
{
Assert.Throws(exception, () => ColorTranslator.FromHtml(htmlColor));
}
{
AppContext.SetSwitch(DontSupportPngFramesInIcons, false);
VerifyPng();
- return RemoteExecutor.SuccessExitCode;
}).Dispose();
}
else
{
AppContext.SetSwitch(DontSupportPngFramesInIcons, true);
VerifyPngNotSupported();
- return RemoteExecutor.SuccessExitCode;
}).Dispose();
}
else
<Compile Include="$(CommonTestPath)\System\Drawing\Helpers.cs">
<Link>Common\System\Drawing\Helpers.cs</Link>
</Compile>
- <Compile Include="$(CommonTestPath)\System\ThreadCultureChange.cs">
- <Link>Common\System\ThreadCultureChange.cs</Link>
- </Compile>
<Compile Include="$(CommonTestPath)\System\IO\TempFile.cs">
<Link>Common\System\IO\TempFile.cs</Link>
</Compile>
<LogicalName>System.Drawing.Tests.Icon_toolboxBitmapAttributeTest</LogicalName>
</EmbeddedResource>
</ItemGroup>
-</Project>
\ No newline at end of file
+</Project>
// See the LICENSE file in the project root for more information.
using System.Collections.Generic;
-using System.Common.Tests;
using System.Globalization;
using System.Reflection;
+using System.Tests;
using System.Threading;
using Xunit;
[MemberData(nameof(FromHtml_TestData))]
public void FromHtml_String_ReturnsExpected(string htmlColor, Color expected)
{
- using (new ThreadCultureChange(CultureInfo.InvariantCulture))
+ using (new ThreadCultureChange(CultureInfo.InvariantCulture, CultureInfo.InvariantCulture))
{
Assert.Equal(expected, ColorTranslator.FromHtml(htmlColor));
}
[InlineData("&hG12")]
public void FromHtml_Invalid_Throws(string htmlColor)
{
- using (new ThreadCultureChange(CultureInfo.InvariantCulture))
+ using (new ThreadCultureChange(CultureInfo.InvariantCulture, CultureInfo.InvariantCulture))
{
Exception exception = AssertExtensions.Throws<ArgumentException, Exception>(() => ColorTranslator.FromHtml(htmlColor));
if (exception is ArgumentException argumentException)
[InlineData("1,2,256", typeof(ArgumentException))]
public void FromHtml_Invalid_Throw(string htmlColor, Type exception)
{
- using (new ThreadCultureChange(CultureInfo.InvariantCulture))
+ using (new ThreadCultureChange(CultureInfo.InvariantCulture, CultureInfo.InvariantCulture))
{
Assert.Throws(exception, () => ColorTranslator.FromHtml(htmlColor));
}
<Compile Include="$(CommonTestPath)\System\Diagnostics\DebuggerAttributes.cs">
<Link>Common\System\Diagnostics\DebuggerAttributes.cs</Link>
</Compile>
- <Compile Include="$(CommonTestPath)\System\ThreadCultureChange.cs">
- <Link>Common\System\ThreadCultureChange.cs</Link>
- </Compile>
<Compile Include="$(CommonTestPath)\System\Runtime\Serialization\DataContractSerializerHelper.cs">
<Link>Common\System\Runtime\Serialization\DataContractSerializerHelper.cs</Link>
</Compile>
<Compile Include="ColorTests.netcoreapp.cs" />
<Compile Include="SizeTests.netcoreapp.cs" />
</ItemGroup>
-</Project>
\ No newline at end of file
+</Project>
// See the LICENSE file in the project root for more information.
using System.Diagnostics;
+using System.Tests;
using System.Threading.Tasks;
using Microsoft.DotNet.RemoteExecutor;
using Xunit;
[Fact]
public void TestCurrentCulturesAsync()
{
- RemoteExecutor.Invoke(() =>
+ RemoteExecutorForUap.Invoke(() =>
{
- CultureInfo currentCulture = CultureInfo.CurrentCulture;
- CultureInfo currentUICulture = CultureInfo.CurrentUICulture;
-
- CultureInfo newCurrentCulture = new CultureInfo(currentCulture.Name.Equals("ja-JP", StringComparison.OrdinalIgnoreCase) ? "en-US" : "ja-JP");
- CultureInfo newCurrentUICulture = new CultureInfo(currentUICulture.Name.Equals("ja-JP", StringComparison.OrdinalIgnoreCase) ? "en-US" : "ja-JP");
-
- CultureInfo.CurrentCulture = newCurrentCulture;
- CultureInfo.CurrentUICulture = newCurrentUICulture;
-
- try
+ var newCurrentCulture = new CultureInfo(CultureInfo.CurrentCulture.Name.Equals("ja-JP", StringComparison.OrdinalIgnoreCase) ? "en-US" : "ja-JP");
+ var newCurrentUICulture = new CultureInfo(CultureInfo.CurrentUICulture.Name.Equals("ja-JP", StringComparison.OrdinalIgnoreCase) ? "en-US" : "ja-JP");
+ using (new ThreadCultureChange(newCurrentCulture, newCurrentUICulture))
{
Task t = Task.Run(() =>
{
((IAsyncResult)t).AsyncWaitHandle.WaitOne();
t.Wait();
}
- finally
- {
- CultureInfo.CurrentCulture = currentCulture;
- CultureInfo.CurrentUICulture = currentUICulture;
- }
}).Dispose();
}
[Fact]
public void TestCurrentCulturesWithAwait()
{
- RemoteExecutor.Invoke(() =>
+ RemoteExecutorForUap.Invoke(() =>
{
- CultureInfo currentCulture = CultureInfo.CurrentCulture;
- CultureInfo currentUICulture = CultureInfo.CurrentUICulture;
-
- CultureInfo newCurrentCulture = new CultureInfo(currentCulture.Name.Equals("ja-JP", StringComparison.OrdinalIgnoreCase) ? "en-US" : "ja-JP");
- CultureInfo newCurrentUICulture = new CultureInfo(currentUICulture.Name.Equals("ja-JP", StringComparison.OrdinalIgnoreCase) ? "en-US" : "ja-JP");
-
- CultureInfo.CurrentCulture = newCurrentCulture;
- CultureInfo.CurrentUICulture = newCurrentUICulture;
-
- async Task MainAsync()
+ var newCurrentCulture = new CultureInfo(CultureInfo.CurrentCulture.Name.Equals("ja-JP", StringComparison.OrdinalIgnoreCase) ? "en-US" : "ja-JP");
+ var newCurrentUICulture = new CultureInfo(CultureInfo.CurrentUICulture.Name.Equals("ja-JP", StringComparison.OrdinalIgnoreCase) ? "en-US" : "ja-JP");
+ using (new ThreadCultureChange(newCurrentCulture, newCurrentUICulture))
{
- await Task.Delay(1).ConfigureAwait(false);
+ MainAsync().Wait();
- Assert.Equal(CultureInfo.CurrentCulture, newCurrentCulture);
- Assert.Equal(CultureInfo.CurrentUICulture, newCurrentUICulture);
- }
+ async Task MainAsync()
+ {
+ await Task.Delay(1).ConfigureAwait(false);
- try
- {
- MainAsync().Wait();
- }
- finally
- {
- CultureInfo.CurrentCulture = currentCulture;
- CultureInfo.CurrentUICulture = currentUICulture;
+ Assert.Equal(CultureInfo.CurrentCulture, newCurrentCulture);
+ Assert.Equal(CultureInfo.CurrentUICulture, newCurrentUICulture);
+ }
}
}).Dispose();
}
using System.Collections;
using System.Collections.Generic;
using System.Diagnostics;
+using System.Tests;
using System.Threading.Tasks;
using Microsoft.DotNet.RemoteExecutor;
using Xunit;
[Fact]
public void CurrentCulture()
{
- RemoteExecutor.Invoke(() =>
+ RemoteExecutorForUap.Invoke(() =>
{
- CultureInfo newCulture = new CultureInfo(CultureInfo.CurrentCulture.Name.Equals("ja-JP", StringComparison.OrdinalIgnoreCase) ? "ar-SA" : "ja-JP");
- CultureInfo.CurrentCulture = newCulture;
-
- Assert.Equal(CultureInfo.CurrentCulture, newCulture);
+ var newCulture = new CultureInfo(CultureInfo.CurrentCulture.Name.Equals("ja-JP", StringComparison.OrdinalIgnoreCase) ? "ar-SA" : "ja-JP");
+ using (new ThreadCultureChange(newCulture))
+ {
+ Assert.Equal(CultureInfo.CurrentCulture, newCulture);
+ }
newCulture = new CultureInfo("de-DE_phoneb");
- CultureInfo.CurrentCulture = newCulture;
-
- Assert.Equal(CultureInfo.CurrentCulture, newCulture);
- Assert.Equal("de-DE_phoneb", newCulture.CompareInfo.Name);
-
- return RemoteExecutor.SuccessExitCode;
+ using (new ThreadCultureChange(newCulture))
+ {
+ Assert.Equal(CultureInfo.CurrentCulture, newCulture);
+ Assert.Equal("de-DE_phoneb", newCulture.CompareInfo.Name);
+ }
}).Dispose();
}
[Fact]
public void CurrentUICulture()
{
- RemoteExecutor.Invoke(() =>
+ RemoteExecutorForUap.Invoke(() =>
{
- CultureInfo newUICulture = new CultureInfo(CultureInfo.CurrentUICulture.Name.Equals("ja-JP", StringComparison.OrdinalIgnoreCase) ? "ar-SA" : "ja-JP");
- CultureInfo.CurrentUICulture = newUICulture;
-
- Assert.Equal(CultureInfo.CurrentUICulture, newUICulture);
+ var newUICulture = new CultureInfo(CultureInfo.CurrentUICulture.Name.Equals("ja-JP", StringComparison.OrdinalIgnoreCase) ? "ar-SA" : "ja-JP");
+ using (new ThreadCultureChange(null, newUICulture))
+ {
+ Assert.Equal(CultureInfo.CurrentUICulture, newUICulture);
+ }
newUICulture = new CultureInfo("de-DE_phoneb");
- CultureInfo.CurrentUICulture = newUICulture;
-
- Assert.Equal(CultureInfo.CurrentUICulture, newUICulture);
- Assert.Equal("de-DE_phoneb", newUICulture.CompareInfo.Name);
- return RemoteExecutor.SuccessExitCode;
+ using (new ThreadCultureChange(null, newUICulture))
+ {
+ Assert.Equal(CultureInfo.CurrentUICulture, newUICulture);
+ Assert.Equal("de-DE_phoneb", newUICulture.CompareInfo.Name);
+ }
}).Dispose();
}
});
((IAsyncResult)task).AsyncWaitHandle.WaitOne();
task.Wait();
-
- return RemoteExecutor.SuccessExitCode;
}).Dispose();
}
});
((IAsyncResult)task).AsyncWaitHandle.WaitOne();
task.Wait();
-
- return RemoteExecutor.SuccessExitCode;
}).Dispose();
}
Assert.Equal(expected, CultureInfo.CurrentCulture.Name);
Assert.Equal(expected, CultureInfo.CurrentUICulture.Name);
-
- return RemoteExecutor.SuccessExitCode;
}, expectedCultureName, new RemoteInvokeOptions { StartInfo = psi }).Dispose();
}
Assert.Equal("", CultureInfo.CurrentCulture.Name);
Assert.Equal("", CultureInfo.CurrentUICulture.Name);
-
- return RemoteExecutor.SuccessExitCode;
}, new RemoteInvokeOptions { StartInfo = psi }).Dispose();
}
using System.Collections.Generic;
using System.Diagnostics;
+using System.Tests;
using Microsoft.DotNet.RemoteExecutor;
using Xunit;
[Fact]
public void TestSettingThreadCultures()
{
- RemoteExecutor.Invoke(() =>
+ RemoteExecutorForUap.Invoke(() =>
{
- CultureInfo culture = new CultureInfo("ja-JP");
- CultureInfo.CurrentCulture = culture;
- DateTime dt = new DateTime(2014, 3, 14, 3, 14, 0);
- Assert.Equal(dt.ToString(), dt.ToString(culture));
- Assert.Equal(dt.ToString(), dt.ToString(culture.DateTimeFormat));
- return RemoteExecutor.SuccessExitCode;
+ var culture = new CultureInfo("ja-JP");
+ using (new ThreadCultureChange(culture))
+ {
+ var dt = new DateTime(2014, 3, 14, 3, 14, 0);
+ Assert.Equal(dt.ToString(), dt.ToString(culture));
+ Assert.Equal(dt.ToString(), dt.ToString(culture.DateTimeFormat));
+ }
}).Dispose();
}
using System.Collections.Generic;
using System.Diagnostics;
+using System.Tests;
using Microsoft.DotNet.RemoteExecutor;
using Xunit;
[MemberData(nameof(CurrentInfo_CustomCulture_TestData))]
public void CurrentInfo_CustomCulture(CultureInfo newCurrentCulture)
{
- RemoteExecutor.Invoke((cultureName) =>
+ RemoteExecutorForUap.Invoke((cultureName) =>
{
- CultureInfo newCulture = CultureInfo.GetCultureInfo(cultureName);
- CultureInfo.CurrentCulture = newCulture;
- Assert.Same(newCulture.NumberFormat, NumberFormatInfo.CurrentInfo);
- return RemoteExecutor.SuccessExitCode;
+ var newCulture = CultureInfo.GetCultureInfo(cultureName);
+ using (new ThreadCultureChange(newCulture))
+ {
+ Assert.Same(newCulture.NumberFormat, NumberFormatInfo.CurrentInfo);
+ }
}, newCurrentCulture.Name).Dispose();
}
[Fact]
public void CurrentInfo_Subclass_OverridesGetFormat()
{
- RemoteExecutor.Invoke(() =>
+ RemoteExecutorForUap.Invoke(() =>
{
- CultureInfo.CurrentCulture = new CultureInfoSubclassOverridesGetFormat("en-US");
- Assert.Same(CultureInfoSubclassOverridesGetFormat.CustomFormat, NumberFormatInfo.CurrentInfo);
- return RemoteExecutor.SuccessExitCode;
+ using (new ThreadCultureChange(new CultureInfoSubclassOverridesGetFormat("en-US")))
+ {
+ Assert.Same(CultureInfoSubclassOverridesGetFormat.CustomFormat, NumberFormatInfo.CurrentInfo);
+ }
}).Dispose();
}
[Fact]
public void CurrentInfo_Subclass_OverridesNumberFormat()
{
- RemoteExecutor.Invoke(() =>
+ RemoteExecutorForUap.Invoke(() =>
{
- CultureInfo.CurrentCulture = new CultureInfoSubclassOverridesNumberFormat("en-US");
- Assert.Same(CultureInfoSubclassOverridesNumberFormat.CustomFormat, NumberFormatInfo.CurrentInfo);
- return RemoteExecutor.SuccessExitCode;
+ using (new ThreadCultureChange(new CultureInfoSubclassOverridesNumberFormat("en-US")))
+ {
+ Assert.Same(CultureInfoSubclassOverridesNumberFormat.CustomFormat, NumberFormatInfo.CurrentInfo);
+ }
}).Dispose();
}
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
+using System.Tests;
using Microsoft.DotNet.RemoteExecutor;
using Xunit;
[Fact]
public void CurrentRegion()
{
- RemoteExecutor.Invoke(() =>
+ RemoteExecutorForUap.Invoke(() =>
{
- CultureInfo.CurrentCulture = new CultureInfo("en-US");
-
- RegionInfo ri = new RegionInfo(new RegionInfo(CultureInfo.CurrentCulture.Name).TwoLetterISORegionName);
- Assert.True(RegionInfo.CurrentRegion.Equals(ri) || RegionInfo.CurrentRegion.Equals(new RegionInfo(CultureInfo.CurrentCulture.Name)));
- Assert.Same(RegionInfo.CurrentRegion, RegionInfo.CurrentRegion);
-
- return RemoteExecutor.SuccessExitCode;
+ using (new ThreadCultureChange("en-US"))
+ {
+ RegionInfo ri = new RegionInfo(new RegionInfo(CultureInfo.CurrentCulture.Name).TwoLetterISORegionName);
+ Assert.True(RegionInfo.CurrentRegion.Equals(ri) || RegionInfo.CurrentRegion.Equals(new RegionInfo(CultureInfo.CurrentCulture.Name)));
+ Assert.Same(RegionInfo.CurrentRegion, RegionInfo.CurrentRegion);
+ }
}).Dispose();
}
[OuterLoop("May fail on machines with multiple language packs installed")] // https://github.com/dotnet/corefx/issues/39177
public void DisplayName(string name, string expected)
{
- RemoteExecutor.Invoke((string _name, string _expected) =>
+ RemoteExecutorForUap.Invoke((string _name, string _expected) =>
{
- CultureInfo.CurrentUICulture = new CultureInfo(_name);
- Assert.Equal(_expected, new RegionInfo(_name).DisplayName);
-
- return RemoteExecutor.SuccessExitCode;
+ using (new ThreadCultureChange(_name))
+ {
+ Assert.Equal(_expected, new RegionInfo(_name).DisplayName);
+ }
}, name, expected).Dispose();
}
Assert.NotEmpty(Directory.EnumerateFiles(Directory.GetCurrentDirectory(), "*"));
Assert.NotEmpty(Directory.EnumerateFiles(Directory.GetCurrentDirectory(), "*", SearchOption.AllDirectories));
Assert.NotEmpty(Directory.EnumerateFiles(Directory.GetCurrentDirectory(), "*", SearchOption.TopDirectoryOnly));
-
- return RemoteExecutor.SuccessExitCode;
}, testDir).Dispose();
}
}
{
Assert.Equal(TestDirectory, Directory.GetCurrentDirectory());
}
- return RemoteExecutor.SuccessExitCode;
}).Dispose();
}
{
Assert.Equal(path, Directory.GetCurrentDirectory());
}
- return RemoteExecutor.SuccessExitCode;
}).Dispose();
}
}
{
FileInfo info = new FileInfo(p);
Assert.True(info.Exists);
- return RemoteExecutor.SuccessExitCode;
}, path).Dispose();
}
}
{
FileInfo info = new FileInfo(p);
Assert.True(info.Exists);
- return RemoteExecutor.SuccessExitCode;
}, path).Dispose();
stream.Unlock(0, 10);
}
Assert.False(writeDisposeInvoked, "Expected finalizer to have been suppressed");
}
- return RemoteExecutor.SuccessExitCode;
}).Dispose();
}
}
Assert.True(writeDisposeInvoked, "Expected finalizer to be invoked but not throw exception");
}
- return RemoteExecutor.SuccessExitCode;
}).Dispose();
}
{
Assert.Throws<IOException>(() => fs2.Lock(long.Parse(secondPos), long.Parse(secondLen)));
}
- return RemoteExecutor.SuccessExitCode;
}, path, secondPosition.ToString(), secondLength.ToString()).Dispose();
fs1.Unlock(firstPosition, firstLength);
fs2.Lock(long.Parse(secondPos), long.Parse(secondLen));
fs2.Unlock(long.Parse(secondPos), long.Parse(secondLen));
}
- return RemoteExecutor.SuccessExitCode;
}, path, secondPosition.ToString(), secondLength.ToString()).Dispose();
}
}
using System;
using System.Globalization;
using System.IO;
+using System.Tests;
using Microsoft.DotNet.RemoteExecutor;
using Xunit;
[Fact]
public void NameReturnsUnknownForHandle()
{
- RemoteExecutor.Invoke(() =>
+ RemoteExecutorForUap.Invoke(() =>
{
- CultureInfo.CurrentUICulture = CultureInfo.InvariantCulture;
-
+ using (new ThreadCultureChange(CultureInfo.InvariantCulture))
using (FileStream fs = new FileStream(GetTestFilePath(), FileMode.Create, FileAccess.ReadWrite))
using (FileStream fsh = new FileStream(fs.SafeFileHandle, FileAccess.ReadWrite))
{
CreateFileStream(fileName, FileMode.Open, access, share | FileShare.Inheritable).Dispose();
}
}
- return RemoteExecutor.SuccessExitCode;
}).Dispose();
}
acc.Flush();
// Spawn and then wait for the other process, which will verify the data and write its own known pattern
- RemoteExecutor.Invoke(new Func<string, int>(DataShared_OtherProcess), file.Path).Dispose();
+ RemoteExecutor.Invoke(new Action<string>(DataShared_OtherProcess), file.Path).Dispose();
// Now verify we're seeing the data from the other process
for (int i = 0; i < capacity; i++)
}
}
- private static int DataShared_OtherProcess(string path)
+ private static void DataShared_OtherProcess(string path)
{
// Open the specified file and load it into a map
using (FileStream fs = new FileStream(path, FileMode.Open, FileAccess.ReadWrite, FileShare.ReadWrite))
acc.Write(i, unchecked((byte)(capacity - i - 1)));
}
acc.Flush();
- return RemoteExecutor.SuccessExitCode;
}
}
// Then spawn another process to communicate with.
using (var outbound = new AnonymousPipeServerStream(PipeDirection.Out, HandleInheritability.Inheritable))
using (var inbound = new AnonymousPipeServerStream(PipeDirection.In, HandleInheritability.Inheritable))
- using (var remote = RemoteExecutor.Invoke(new Func<string, string, int>(ChildFunc), outbound.GetClientHandleAsString(), inbound.GetClientHandleAsString()))
+ using (var remote = RemoteExecutor.Invoke(new Action<string, string>(ChildFunc), outbound.GetClientHandleAsString(), inbound.GetClientHandleAsString()))
{
// Close our local copies of the handles now that we've passed them of to the other process
outbound.DisposeLocalCopyOfClientHandle();
}
}
- int ChildFunc(string inHandle, string outHandle)
+ void ChildFunc(string inHandle, string outHandle)
{
// Create the clients associated with the supplied handles
using (var inbound = new AnonymousPipeClientStream(PipeDirection.In, inHandle))
outbound.WriteByte((byte)b);
}
}
- return RemoteExecutor.SuccessExitCode;
}
}
public void ServerClosesPipe_ClientReceivesEof()
{
using (var pipe = new AnonymousPipeServerStream(PipeDirection.Out, HandleInheritability.Inheritable))
- using (var remote = RemoteExecutor.Invoke(new Func<string, int>(ChildFunc), pipe.GetClientHandleAsString()))
+ using (var remote = RemoteExecutor.Invoke(new Action<string>(ChildFunc), pipe.GetClientHandleAsString()))
{
pipe.DisposeLocalCopyOfClientHandle();
pipe.Write(new byte[] { 1, 2, 3, 4, 5 }, 0, 5);
Assert.True(remote.Process.WaitForExit(30_000));
}
- int ChildFunc(string clientHandle)
+ void ChildFunc(string clientHandle)
{
using (var pipe = new AnonymousPipeClientStream(PipeDirection.In, clientHandle))
{
}
Assert.Equal(-1, pipe.ReadByte());
}
- return RemoteExecutor.SuccessExitCode;
}
}
public void ClientClosesPipe_ServerReceivesEof()
{
using (var pipe = new AnonymousPipeServerStream(PipeDirection.In, HandleInheritability.Inheritable))
- using (var remote = RemoteExecutor.Invoke(new Func<string, int>(ChildFunc), pipe.GetClientHandleAsString(), new RemoteInvokeOptions { CheckExitCode = false }))
+ using (var remote = RemoteExecutor.Invoke(new Action<string>(ChildFunc), pipe.GetClientHandleAsString(), new RemoteInvokeOptions { CheckExitCode = false }))
{
pipe.DisposeLocalCopyOfClientHandle();
remote.Process.Kill();
}
- int ChildFunc(string clientHandle)
+ void ChildFunc(string clientHandle)
{
using (var pipe = new AnonymousPipeClientStream(PipeDirection.Out, clientHandle))
{
pipe.Write(new byte[] { 1, 2, 3, 4, 5 }, 0, 5);
}
Thread.CurrentThread.Join();
- return RemoteExecutor.SuccessExitCode;
}
}
}
using (var client = new NamedPipeClientStream(".", pipeName, PipeDirection.Out, PipeOptions.None, TokenImpersonationLevel.None, HandleInheritability.Inheritable))
{
Task.WaitAll(server.WaitForConnectionAsync(), client.ConnectAsync());
- using (RemoteExecutor.Invoke(new Func<string, int>(ChildFunc), client.SafePipeHandle.DangerousGetHandle().ToString()))
+ using (RemoteExecutor.Invoke(new Action<string>(ChildFunc), client.SafePipeHandle.DangerousGetHandle().ToString()))
{
client.Dispose();
for (int i = 0; i < 5; i++)
}
}
- int ChildFunc(string handle)
+ void ChildFunc(string handle)
{
using (var childClient = new NamedPipeClientStream(PipeDirection.Out, isAsync: false, isConnected: true, new SafePipeHandle((IntPtr)long.Parse(handle, CultureInfo.InvariantCulture), ownsHandle: true)))
{
childClient.WriteByte((byte)i);
}
}
- return RemoteExecutor.SuccessExitCode;
}
}
// another process with which to communicate
using (var outbound = new NamedPipeServerStream(outName, PipeDirection.Out))
using (var inbound = new NamedPipeClientStream(".", inName, PipeDirection.In))
- using (RemoteExecutor.Invoke(new Func<string, string, int>(PingPong_OtherProcess), outName, inName))
+ using (RemoteExecutor.Invoke(new Action<string, string>(PingPong_OtherProcess), outName, inName))
{
// Wait for both pipes to be connected
Task.WaitAll(outbound.WaitForConnectionAsync(), inbound.ConnectAsync());
// another process with which to communicate
using (var outbound = new NamedPipeServerStream(outName, PipeDirection.Out))
using (var inbound = new NamedPipeClientStream(".", inName, PipeDirection.In))
- using (RemoteExecutor.Invoke(new Func<string, string, int>(PingPong_OtherProcess), outName, inName))
+ using (RemoteExecutor.Invoke(new Action<string, string>(PingPong_OtherProcess), outName, inName))
{
// Wait for both pipes to be connected
await Task.WhenAll(outbound.WaitForConnectionAsync(), inbound.ConnectAsync());
}
}
- private static int PingPong_OtherProcess(string inName, string outName)
+ private static void PingPong_OtherProcess(string inName, string outName)
{
// Create pipes with the supplied names
using (var inbound = new NamedPipeClientStream(".", inName, PipeDirection.In))
outbound.WriteByte((byte)b);
}
}
- return RemoteExecutor.SuccessExitCode;
}
private static string GetUniquePipeName()
Task serverTask = server.WaitForConnectionAsync(CancellationToken.None);
using (RemoteExecutor.Invoke(
- new Func<string, string, int>(ConnectClientFromRemoteInvoker),
+ new Action<string, string>(ConnectClientFromRemoteInvoker),
pipeName,
clientPipeOptions == PipeOptions.CurrentUserOnly ? "true" : "false",
new RemoteInvokeOptions { RunAsSudo = true }))
}
}
- private static int ConnectClientFromRemoteInvoker(string pipeName, string isCurrentUserOnly)
+ private static void ConnectClientFromRemoteInvoker(string pipeName, string isCurrentUserOnly)
{
PipeOptions pipeOptions = bool.Parse(isCurrentUserOnly) ? PipeOptions.CurrentUserOnly : PipeOptions.None;
using (var client = new NamedPipeClientStream(".", pipeName, PipeDirection.InOut, pipeOptions))
else
client.Connect();
}
-
- return RemoteExecutor.SuccessExitCode;
}
}
}
{
string pipeName = Path.GetRandomFileName();
uint pairID = (uint)(Math.Abs(new Random(5125123).Next()));
- RemoteExecutor.Invoke(new Func<string, string, int>(ServerConnectAsId), pipeName, pairID.ToString()).Dispose();
+ RemoteExecutor.Invoke(new Action<string, string>(ServerConnectAsId), pipeName, pairID.ToString()).Dispose();
}
- private static int ServerConnectAsId(string pipeName, string pairIDString)
+ private static void ServerConnectAsId(string pipeName, string pairIDString)
{
uint pairID = uint.Parse(pairIDString);
Assert.NotEqual(-1, seteuid(pairID));
using (var outbound = new NamedPipeServerStream(pipeName, PipeDirection.Out))
- using (var handle = RemoteExecutor.Invoke(new Func<string, string, int>(ClientConnectAsID), pipeName, pairIDString))
+ using (var handle = RemoteExecutor.Invoke(new Action<string, string>(ClientConnectAsID), pipeName, pairIDString))
{
// Connect as the unpriveleged user, but RunAsClient as the superuser
outbound.WaitForConnection();
Assert.True(ran, "Expected delegate to have been invoked");
Assert.Equal(pairID, ranAs);
}
- return RemoteExecutor.SuccessExitCode;
}
- private static int ClientConnectAsID(string pipeName, string pairIDString)
+ private static void ClientConnectAsID(string pipeName, string pairIDString)
{
uint pairID = uint.Parse(pairIDString);
using (var inbound = new NamedPipeClientStream(".", pipeName, PipeDirection.In))
Assert.NotEqual(-1, seteuid(pairID));
inbound.Connect();
}
- return RemoteExecutor.SuccessExitCode;
}
}
}
using System.Diagnostics;
using System.Globalization;
using System.IO;
+using System.Tests;
using System.Text;
using System.Threading.Tasks;
using Microsoft.DotNet.RemoteExecutor;
[Fact]
public static void TestWriteMisc()
{
- RemoteExecutor.Invoke(() =>
+ RemoteExecutorForUap.Invoke(() =>
{
- CultureInfo.CurrentCulture = new CultureInfo("en-US"); // floating-point formatting comparison depends on culture
- var sw = new StringWriter();
-
- sw.Write(true);
- sw.Write((char)'a');
- sw.Write(new decimal(1234.01));
- sw.Write((double)3452342.01);
- sw.Write((int)23456);
- sw.Write((long)long.MinValue);
- sw.Write((float)1234.50f);
- sw.Write((uint)uint.MaxValue);
- sw.Write((ulong)ulong.MaxValue);
-
- Assert.Equal("Truea1234.013452342.0123456-92233720368547758081234.5429496729518446744073709551615", sw.ToString());
+ using (new ThreadCultureChange("en-US")) // floating-point formatting comparison depends on culture
+ {
+ var sw = new StringWriter();
+
+ sw.Write(true);
+ sw.Write((char)'a');
+ sw.Write(new decimal(1234.01));
+ sw.Write((double)3452342.01);
+ sw.Write((int)23456);
+ sw.Write((long)long.MinValue);
+ sw.Write((float)1234.50f);
+ sw.Write((uint)uint.MaxValue);
+ sw.Write((ulong)ulong.MaxValue);
+
+ Assert.Equal("Truea1234.013452342.0123456-92233720368547758081234.5429496729518446744073709551615", sw.ToString());
+ }
}).Dispose();
}
[Fact]
public static void TestWriteLineMisc()
{
- RemoteExecutor.Invoke(() =>
+ RemoteExecutorForUap.Invoke(() =>
{
- CultureInfo.CurrentCulture = new CultureInfo("en-US"); // floating-point formatting comparison depends on culture
- var sw = new StringWriter();
- sw.WriteLine((bool)false);
- sw.WriteLine((char)'B');
- sw.WriteLine((int)987);
- sw.WriteLine((long)875634);
- sw.WriteLine((float)1.23457f);
- sw.WriteLine((uint)45634563);
- sw.WriteLine((ulong.MaxValue));
-
- Assert.Equal(
- string.Format("False{0}B{0}987{0}875634{0}1.23457{0}45634563{0}18446744073709551615{0}", Environment.NewLine),
- sw.ToString());
+ using (new ThreadCultureChange("en-US")) // floating-point formatting comparison depends on culture
+ {
+ var sw = new StringWriter();
+ sw.WriteLine((bool)false);
+ sw.WriteLine((char)'B');
+ sw.WriteLine((int)987);
+ sw.WriteLine((long)875634);
+ sw.WriteLine((float)1.23457f);
+ sw.WriteLine((uint)45634563);
+ sw.WriteLine((ulong.MaxValue));
+
+ Assert.Equal(
+ string.Format("False{0}B{0}987{0}875634{0}1.23457{0}45634563{0}18446744073709551615{0}", Environment.NewLine),
+ sw.ToString());
+ }
}).Dispose();
}
using System.Collections.Generic;
using Microsoft.DotNet.RemoteExecutor;
using Xunit;
+using System.Tests;
namespace System.Json.Tests
{
[InlineData("0.000000000000000000000000000011", 1.1E-29)]
public void JsonValue_Parse_Double(string json, double expected)
{
- RemoteExecutor.Invoke((jsonInner, expectedInner) =>
+ RemoteExecutorForUap.Invoke((jsonInner, expectedInner) =>
{
foreach (string culture in new[] { "en", "fr", "de" })
{
- CultureInfo.CurrentCulture = new CultureInfo(culture);
- Assert.Equal(double.Parse(expectedInner, CultureInfo.InvariantCulture), (double)JsonValue.Parse(jsonInner));
+ using (new ThreadCultureChange(culture))
+ {
+ Assert.Equal(double.Parse(expectedInner, CultureInfo.InvariantCulture), (double)JsonValue.Parse(jsonInner));
+ }
}
}, json, expected.ToString("R", CultureInfo.InvariantCulture)).Dispose();
}
[InlineData(1.123456789e-28)] // Values around the smallest positive decimal value
public void JsonValue_Parse_Double_ViaJsonPrimitive(double number)
{
- RemoteExecutor.Invoke(numberText =>
+ RemoteExecutorForUap.Invoke(numberText =>
{
double numberInner = double.Parse(numberText, CultureInfo.InvariantCulture);
foreach (string culture in new[] { "en", "fr", "de" })
{
- CultureInfo.CurrentCulture = new CultureInfo(culture);
- Assert.Equal(numberInner, (double)JsonValue.Parse(new JsonPrimitive(numberInner).ToString()));
+ using (new ThreadCultureChange(culture))
+ {
+ Assert.Equal(numberInner, (double)JsonValue.Parse(new JsonPrimitive(numberInner).ToString()));
+ }
}
}, number.ToString("R", CultureInfo.InvariantCulture)).Dispose();
}
Assert.False(activityLogged, "HttpOutReq was logged while HttpOutReq logging was disabled");
diagnosticListenerObserver.Disable();
}
-
- return RemoteExecutor.SuccessExitCode;
}, UseSocketsHttpHandler.ToString(), UseHttp2.ToString()).Dispose();
}
"Response was logged while logging disabled.");
Assert.False(activityStopLogged, "HttpRequestOut.Stop was logged while logging disabled.");
}
-
- return RemoteExecutor.SuccessExitCode;
}, UseSocketsHttpHandler.ToString(), UseHttp2.ToString()).Dispose();
}
ev => ev.EventId == 0); // make sure there are no event source error messages
Assert.InRange(events.Count, 1, int.MaxValue);
}
-
- return RemoteExecutor.SuccessExitCode;
}, UseSocketsHttpHandler.ToString(), UseHttp2.ToString(), useSsl.ToString()).Dispose();
}
Assert.True(exceptionLogged, "Exception was not logged");
diagnosticListenerObserver.Disable();
}
-
- return RemoteExecutor.SuccessExitCode;
}, UseSocketsHttpHandler.ToString(), UseHttp2.ToString()).Dispose();
}
WaitForTrue(() => Volatile.Read(ref cancelLogged), TimeSpan.FromSeconds(1),
"Cancellation was not logged within 1 second timeout.");
diagnosticListenerObserver.Disable();
-
- return RemoteExecutor.SuccessExitCode;
}, UseSocketsHttpHandler.ToString(), UseHttp2.ToString()).Dispose();
}
Assert.False(responseLogged, "Response was logged when Activity logging was enabled.");
diagnosticListenerObserver.Disable();
}
-
- return RemoteExecutor.SuccessExitCode;
}, UseSocketsHttpHandler.ToString(), UseHttp2.ToString()).Dispose();
}
Assert.False(responseLogged, "Response was logged when Activity logging was enabled.");
diagnosticListenerObserver.Disable();
}
-
- return RemoteExecutor.SuccessExitCode;
}, UseSocketsHttpHandler.ToString(), UseHttp2.ToString()).Dispose();
}
Assert.False(exceptionLogged, "Exception was logged for successful request");
diagnosticListenerObserver.Disable();
}
-
- return RemoteExecutor.SuccessExitCode;
}, UseSocketsHttpHandler.ToString(), UseHttp2.ToString()).Dispose();
}
"HttpRequestOut.Stop was not logged within 1 second timeout.");
diagnosticListenerObserver.Disable();
}
-
- return RemoteExecutor.SuccessExitCode;
}, UseSocketsHttpHandler.ToString(), UseHttp2.ToString()).Dispose();
}
"HttpRequestOut.Stop was not logged within 1 second timeout.");
diagnosticListenerObserver.Disable();
}
-
- return RemoteExecutor.SuccessExitCode;
}, UseSocketsHttpHandler.ToString(), UseHttp2.ToString()).Dispose();
}
Assert.False(activityStopLogged, "HttpRequestOut.Stop was logged while URL disabled.");
diagnosticListenerObserver.Disable();
}
-
- return RemoteExecutor.SuccessExitCode;
}, UseSocketsHttpHandler.ToString(), UseHttp2.ToString()).Dispose();
}
Assert.True(exceptionLogged, "Exception was not logged");
diagnosticListenerObserver.Disable();
}
-
- return RemoteExecutor.SuccessExitCode;
}, UseSocketsHttpHandler.ToString(), UseHttp2.ToString()).Dispose();
}
Assert.True(exceptionLogged, "Exception was not logged");
diagnosticListenerObserver.Disable();
}
-
- return RemoteExecutor.SuccessExitCode;
}, UseSocketsHttpHandler.ToString(), UseHttp2.ToString()).Dispose();
}
Assert.True(responseLogged, "Response was not logged.");
diagnosticListenerObserver.Disable();
}
-
- return RemoteExecutor.SuccessExitCode;
}, UseSocketsHttpHandler.ToString(), UseHttp2.ToString()).Dispose();
}
Assert.False(activityLogged, "HttpOutReq was logged when logging was disabled");
diagnosticListenerObserver.Disable();
}
-
- return RemoteExecutor.SuccessExitCode;
}, UseSocketsHttpHandler.ToString(), UseHttp2.ToString()).Dispose();
}
"HttpRequestOut.Start was logged when start logging was disabled");
diagnosticListenerObserver.Disable();
}
-
- return RemoteExecutor.SuccessExitCode;
}, UseSocketsHttpHandler.ToString(), UseHttp2.ToString()).Dispose();
}
Assert.True(response.RequestMessage.Headers.Contains(parent.IdFormat == ActivityIdFormat.Hierarchical ? "Request-Id" : "traceparent"));
parent.Stop();
}
-
- return RemoteExecutor.SuccessExitCode;
}, UseSocketsHttpHandler.ToString(), UseHttp2.ToString()).Dispose();
}
Assert.False(response.RequestMessage.Headers.Contains("tracestate"));
Assert.False(response.RequestMessage.Headers.Contains("Correlation-Context"));
}
-
- return RemoteExecutor.SuccessExitCode;
}, UseSocketsHttpHandler.ToString(), UseHttp2.ToString()).Dispose();
}
diagnosticListenerObserver.Disable();
}
-
- return RemoteExecutor.SuccessExitCode;
}, envVarValue, isInstrumentationEnabled.ToString()).Dispose();
}
Assert.Equal(bool.Parse(innerSwitchValue), response.RequestMessage.Headers.Contains(
parent.IdFormat == ActivityIdFormat.Hierarchical ? "Request-Id" : "traceparent"));
}
-
- return RemoteExecutor.SuccessExitCode;
}, switchValue.ToString()).Dispose();
}
WaitForTrue(() => Volatile.Read(ref cancelLogged), TimeSpan.FromSeconds(1),
"Cancellation was not logged within 1 second timeout.");
diagnosticListenerObserver.Disable();
-
- return RemoteExecutor.SuccessExitCode;
}, UseSocketsHttpHandler.ToString(), UseHttp2.ToString()).Dispose();
}
}
diagnosticListenerObserver.Disable();
- return RemoteExecutor.SuccessExitCode;
}).Dispose();
}
var receivedCert = new X509Certificate2(bytes);
Assert.Equal(clientCert, receivedCert);
}
-
- return RemoteExecutor.SuccessExitCode;
}
}, certIndex.ToString(), expectedStatusCode.ToString(), UseSocketsHttpHandler.ToString(), UseHttp2.ToString()).Dispose();
}
// Correctness of user and password is done in server part.
Assert.True(response.StatusCode == HttpStatusCode.OK);
}
- return RemoteExecutor.SuccessExitCode;
}, useProxy.ToString(), UseSocketsHttpHandler.ToString(), UseHttp2.ToString(), new RemoteInvokeOptions { StartInfo = psi }).Dispose();
if (useProxy)
{
string body = await response.Content.ReadAsStringAsync();
Assert.Contains(proxyServer.ViaHeader, body);
}
-
- return RemoteExecutor.SuccessExitCode;
}
}, UseSocketsHttpHandler.ToString(), UseHttp2.ToString()).Dispose();
}
{
await Assert.ThrowsAsync<HttpRequestException>(() => client.GetAsync(Url));
}
- return RemoteExecutor.SuccessExitCode;
}, UseSocketsHttpHandler.ToString(), UseHttp2.ToString(), new RemoteInvokeOptions { StartInfo = psi }).Dispose();
}
}
useSocketsHttpHandlerString,
useHttp2String,
(SslPolicyErrors)Enum.Parse(typeof(SslPolicyErrors), remoteExpectedErrors)).Wait();
-
- return RemoteExecutor.SuccessExitCode;
}, url, expectedErrors.ToString(), UseSocketsHttpHandler.ToString(), UseHttp2.ToString()).Dispose();
}
else
{
Assert.Equal(HttpStatusCode.Unauthorized, response.StatusCode);
}
-
- return RemoteExecutor.SuccessExitCode;
}
}, UseSocketsHttpHandler.ToString(), UseHttp2.ToString()).Dispose();
}
IWebProxy proxy = new WebProxy("http://localhost:3128/");
HttpClient.DefaultProxy = proxy;
Assert.True(Object.ReferenceEquals(proxy, HttpClient.DefaultProxy));
-
- return RemoteExecutor.SuccessExitCode;
}).Dispose();
}
await Assert.ThrowsAsync<HttpRequestException>(() => client.PostAsync(uri, content));
}
-
- return RemoteExecutor.SuccessExitCode;
}, UseSocketsHttpHandler.ToString(), UseHttp2.ToString()).Dispose();
}
await Assert.ThrowsAsync<HttpRequestException>(() => client.PostAsync(uri, content));
}
-
- return RemoteExecutor.SuccessExitCode;
}, UseSocketsHttpHandler.ToString(), UseHttp2.ToString()).Dispose();
}
string responseContent = await response.Content.ReadAsStringAsync();
}
}
-
- return RemoteExecutor.SuccessExitCode;
}, UseSocketsHttpHandler.ToString(), UseHttp2.ToString()).Dispose();
}
string responseContent = await response.Content.ReadAsStringAsync();
}
}
-
- return RemoteExecutor.SuccessExitCode;
}, UseSocketsHttpHandler.ToString(), UseHttp2.ToString()).Dispose();
}
string responseContent = await response.Content.ReadAsStringAsync();
}
}
-
- return RemoteExecutor.SuccessExitCode;
}, UseSocketsHttpHandler.ToString(), UseHttp2.ToString()).Dispose();
}
}
await releaseServer.Task;
}),
new LoopbackServer.Options { UseSsl = bool.Parse(secureString) });
- return RemoteExecutor.SuccessExitCode;
}, secure.ToString(), UseHttp2.ToString()).Dispose();
}
{
Assert.Equal(bool.Parse(innerExpectedUseSocketsHandler), IsSocketsHttpHandler(handler));
}
- return RemoteExecutor.SuccessExitCode;
}, envVarValue, expectedUseSocketsHandler.ToString()).Dispose();
}
{
Assert.False(IsSocketsHttpHandler(handler));
}
-
- return RemoteExecutor.SuccessExitCode;
}).Dispose();
}
{
Assert.True(IsSocketsHttpHandler(handler));
}
-
- return RemoteExecutor.SuccessExitCode;
}).Dispose();
}
}
Assert.True(u != null && u.Host == "1.1.1.3" && u.Port == 3003);
u = p.GetProxy(fooHttps);
Assert.True(u != null && u.Host == "1.1.1.5" && u.Port == 3005);
-
- return RemoteExecutor.SuccessExitCode;
}).Dispose();
}
// This should not match Proxy Uri
Assert.Null(p.Credentials.GetCredential(fooHttp, "Basic"));
Assert.Null(p.Credentials.GetCredential(null, null));
-
- return RemoteExecutor.SuccessExitCode;
}).Dispose();
}
Assert.True(p.IsBypassed(new Uri("http://test.com")));
Assert.False(p.IsBypassed(new Uri("http://1test.com")));
Assert.True(p.IsBypassed(new Uri("http://www.test.com")));
-
- return RemoteExecutor.SuccessExitCode;
}).Dispose();
}
Assert.True(p.IsBypassed(directUri));
Assert.False(p.IsBypassed(thruProxyUri));
Assert.Equal(new Uri(proxy), p.GetProxy(thruProxyUri));
-
- return RemoteExecutor.SuccessExitCode;
}, proxy, options).Dispose();
}
{
Assert.False(created);
}
-
- return RemoteExecutor.SuccessExitCode;
}, proxy, expectedProxyUse.ToString(), options).Dispose();
}
}
Assert.Equal(!string.IsNullOrEmpty(secureProxy) ? new Uri(secureProxy) : null, p.GetProxy(new Uri(fooHttps)));
Assert.Equal(!string.IsNullOrEmpty(insecureProxy) ? new Uri(insecureProxy) : null, p.GetProxy(new Uri(fooWs)));
Assert.Equal(!string.IsNullOrEmpty(secureProxy) ? new Uri(secureProxy) : null, p.GetProxy(new Uri(fooWss)));
- return RemoteExecutor.SuccessExitCode;
}, rawProxyString, rawInsecureUri ?? string.Empty, rawSecureUri ?? string.Empty).Dispose();
}
Assert.Equal(!string.IsNullOrEmpty(secureProxy) ? new Uri(secureProxy) : null, p.GetProxy(new Uri(fooHttps)));
Assert.Equal(!string.IsNullOrEmpty(insecureProxy) ? new Uri(insecureProxy) : null, p.GetProxy(new Uri(fooWs)));
Assert.Equal(!string.IsNullOrEmpty(secureProxy) ? new Uri(secureProxy) : null, p.GetProxy(new Uri(fooWss)));
- return RemoteExecutor.SuccessExitCode;
}, rawProxyString, rawInsecureUri ?? string.Empty, rawSecureUri ?? string.Empty).Dispose();
}
Assert.NotNull(p);
Assert.Equal(expectedString, p.GetProxy(new Uri(fooHttp)).ToString());
Assert.Equal(expectedString, p.GetProxy(new Uri(fooHttps)).ToString());
-
- return RemoteExecutor.SuccessExitCode;
}, rawProxyString, expectedUri).Dispose();
}
Uri u = new Uri(url);
Assert.Equal(expectedResult, p.GetProxy(u) == null);
-
- return RemoteExecutor.SuccessExitCode;
}, name, shouldBypass.ToString()).Dispose();
}
{
Assert.Null(sp.BypassList);
}
- return RemoteExecutor.SuccessExitCode;
}, bypass, count.ToString()).Dispose();
}
Assert.Null(p.GetProxy(new Uri(fooHttps)));
Assert.Null(p.GetProxy(new Uri(fooWs)));
Assert.Null(p.GetProxy(new Uri(fooWss)));
- return RemoteExecutor.SuccessExitCode;
}, rawProxyString).Dispose();
}
}
Assert.False(multi.ReadNext(out _, out _));
-
- return RemoteExecutor.SuccessExitCode;
}, manualConfig.ToString(), proxyConfig, url, expected).Dispose();
}
Assert.True(multiC.ReadNext(out Uri proxyC, out _));
Assert.Equal(firstProxy, proxyC);
Assert.False(multiC.ReadNext(out proxyC, out _));
- return RemoteExecutor.SuccessExitCode;
}, manualConfig.ToString()).Dispose();
}
}
HttpEnvironmentProxy envProxy = proxy as HttpEnvironmentProxy;
Assert.Null(envProxy);
-
- return RemoteExecutor.SuccessExitCode;
}).Dispose();
}
IWebProxy proxy = SystemProxyInfo.ConstructSystemProxy();
HttpEnvironmentProxy envProxy = proxy as HttpEnvironmentProxy;
Assert.NotNull(envProxy);
-
- return RemoteExecutor.SuccessExitCode;
}, options).Dispose();
}
}
Assert.DoesNotContain(events, ev => ev.EventId == 0); // errors from the EventSource itself
Assert.InRange(events.Count, 1, int.MaxValue);
}
- return RemoteExecutor.SuccessExitCode;
}).Dispose();
}
}
Assert.DoesNotContain(events, ev => ev.EventId == 0); // errors from the EventSource itself
Assert.InRange(events.Count, 1, int.MaxValue);
}
- return RemoteExecutor.SuccessExitCode;
}).Dispose();
}
}
AuthenticationManager.Register(module);
AuthenticationManager.Unregister(module);
Assert.Equal(initialCount, GetModuleCount());
-
- return RemoteExecutor.SuccessExitCode;
}).Dispose();
}
AuthenticationManager.Register(module);
AuthenticationManager.Unregister("custom");
Assert.Equal(initialCount, GetModuleCount());
-
- return RemoteExecutor.SuccessExitCode;
}).Dispose();
}
AuthenticationManager.CredentialPolicy = null;
Assert.Null(AuthenticationManager.CredentialPolicy);
-
- return RemoteExecutor.SuccessExitCode;
}).Dispose();
}
AuthenticationManager.CustomTargetNameDictionary.Clear();
Assert.Equal(0, AuthenticationManager.CustomTargetNameDictionary.Count);
-
- return RemoteExecutor.SuccessExitCode;
}).Dispose();
}
Assert.NotNull(GlobalProxySelection.Select);
Assert.True(GlobalProxySelection.Select.IsBypassed(null)); // This is true for EmptyWebProxy, but not for most proxies
#pragma warning restore 0618
-
- return RemoteExecutor.SuccessExitCode;
}).Dispose();
}
{
HttpWebRequest.DefaultMaximumResponseHeadersLength = defaultMaximumResponseHeadersLength;
}
-
- return RemoteExecutor.SuccessExitCode;
}).Dispose();
}
{
HttpWebRequest.DefaultMaximumErrorResponseLength = defaultMaximumErrorsResponseLength;
}
-
- return RemoteExecutor.SuccessExitCode;
}).Dispose();
}
{
HttpWebRequest.DefaultCachePolicy = requestCachePolicy;
}
-
- return RemoteExecutor.SuccessExitCode;
}).Dispose();
}
{
Assert.Equal(HttpStatusCode.OK, response.StatusCode);
}
-
- return RemoteExecutor.SuccessExitCode;
}, cred.UserName, cred.Password, new RemoteInvokeOptions { StartInfo = psi }).Dispose();
await proxyTask;
}
}
}
- return RemoteExecutor.SuccessExitCode;
}, JsonSerializer.Serialize<HttpWebRequestParameters>(requestParameters), connectionReusedParameter.ToString()).Dispose();
}
}
}
}
- return RemoteExecutor.SuccessExitCode;
}).Dispose();
}
WebRequest.DefaultWebProxy = p;
Assert.Same(p, WebRequest.DefaultWebProxy);
-
- return RemoteExecutor.SuccessExitCode;
}).Dispose();
}
Assert.DoesNotContain(events, ev => ev.EventId == 0); // errors from the EventSource itself
Assert.InRange(events.Count, 1, int.MaxValue);
}
- return RemoteExecutor.SuccessExitCode;
}).Dispose();
}
}
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
-using System;
-using System.Diagnostics;
using System.Net.Security;
-using System.Security.Cryptography.X509Certificates;
+using System.Runtime.CompilerServices;
using Microsoft.DotNet.RemoteExecutor;
using Xunit;
[Fact]
public static void RequireEncryption_ExpectedDefault()
{
- RemoteExecutor.Invoke(() => Assert.Equal(EncryptionPolicy.RequireEncryption, ServicePointManager.EncryptionPolicy)).Dispose();
+ Assert.Equal(EncryptionPolicy.RequireEncryption, ServicePointManager.EncryptionPolicy);
}
[Fact]
public static void CheckCertificateRevocationList_Roundtrips()
{
- RemoteExecutor.Invoke(() =>
+ Assert.False(ServicePointManager.CheckCertificateRevocationList);
+ try
{
- Assert.False(ServicePointManager.CheckCertificateRevocationList);
-
ServicePointManager.CheckCertificateRevocationList = true;
Assert.True(ServicePointManager.CheckCertificateRevocationList);
-
+ }
+ finally
+ {
ServicePointManager.CheckCertificateRevocationList = false;
Assert.False(ServicePointManager.CheckCertificateRevocationList);
- }).Dispose();
+ }
}
[Fact]
public static void DefaultConnectionLimit_Roundtrips()
{
- RemoteExecutor.Invoke(() =>
+ Assert.Equal(2, ServicePointManager.DefaultConnectionLimit);
+ try
{
- Assert.Equal(2, ServicePointManager.DefaultConnectionLimit);
-
ServicePointManager.DefaultConnectionLimit = 20;
Assert.Equal(20, ServicePointManager.DefaultConnectionLimit);
-
+ }
+ finally
+ {
ServicePointManager.DefaultConnectionLimit = 2;
Assert.Equal(2, ServicePointManager.DefaultConnectionLimit);
- }).Dispose();
+ }
}
[Fact]
public static void DnsRefreshTimeout_Roundtrips()
{
- RemoteExecutor.Invoke(() =>
+ Assert.Equal(120_000, ServicePointManager.DnsRefreshTimeout);
+ try
{
- Assert.Equal(120000, ServicePointManager.DnsRefreshTimeout);
-
ServicePointManager.DnsRefreshTimeout = 42;
Assert.Equal(42, ServicePointManager.DnsRefreshTimeout);
-
- ServicePointManager.DnsRefreshTimeout = 120000;
- Assert.Equal(120000, ServicePointManager.DnsRefreshTimeout);
- }).Dispose();
+ }
+ finally
+ {
+ ServicePointManager.DnsRefreshTimeout = 120_000;
+ Assert.Equal(120_000, ServicePointManager.DnsRefreshTimeout);
+ }
}
[Fact]
public static void EnableDnsRoundRobin_Roundtrips()
{
- RemoteExecutor.Invoke(() =>
+ Assert.False(ServicePointManager.EnableDnsRoundRobin);
+ try
{
- Assert.False(ServicePointManager.EnableDnsRoundRobin);
-
ServicePointManager.EnableDnsRoundRobin = true;
Assert.True(ServicePointManager.EnableDnsRoundRobin);
-
+ }
+ finally
+ {
ServicePointManager.EnableDnsRoundRobin = false;
Assert.False(ServicePointManager.EnableDnsRoundRobin);
- }).Dispose();
+ }
}
[Fact]
public static void Expect100Continue_Roundtrips()
{
- RemoteExecutor.Invoke(() =>
+ Assert.True(ServicePointManager.Expect100Continue);
+ try
{
- Assert.True(ServicePointManager.Expect100Continue);
-
ServicePointManager.Expect100Continue = false;
Assert.False(ServicePointManager.Expect100Continue);
-
+ }
+ finally
+ {
ServicePointManager.Expect100Continue = true;
Assert.True(ServicePointManager.Expect100Continue);
- }).Dispose();
+ }
}
[Fact]
public static void MaxServicePointIdleTime_Roundtrips()
{
- RemoteExecutor.Invoke(() =>
+ Assert.Equal(100_000, ServicePointManager.MaxServicePointIdleTime);
+ try
{
- Assert.Equal(100000, ServicePointManager.MaxServicePointIdleTime);
-
ServicePointManager.MaxServicePointIdleTime = 42;
Assert.Equal(42, ServicePointManager.MaxServicePointIdleTime);
-
- ServicePointManager.MaxServicePointIdleTime = 100000;
- Assert.Equal(100000, ServicePointManager.MaxServicePointIdleTime);
- }).Dispose();
+ }
+ finally
+ {
+ ServicePointManager.MaxServicePointIdleTime = 100_000;
+ Assert.Equal(100_000, ServicePointManager.MaxServicePointIdleTime);
+ }
}
[Fact]
public static void MaxServicePoints_Roundtrips()
{
- RemoteExecutor.Invoke(() =>
+ Assert.Equal(0, ServicePointManager.MaxServicePoints);
+ try
{
- Assert.Equal(0, ServicePointManager.MaxServicePoints);
-
ServicePointManager.MaxServicePoints = 42;
Assert.Equal(42, ServicePointManager.MaxServicePoints);
-
+ }
+ finally
+ {
ServicePointManager.MaxServicePoints = 0;
Assert.Equal(0, ServicePointManager.MaxServicePoints);
- }).Dispose();
+ }
}
[Fact]
public static void ReusePort_Roundtrips()
{
- RemoteExecutor.Invoke(() =>
+ Assert.False(ServicePointManager.ReusePort);
+ try
{
- Assert.False(ServicePointManager.ReusePort);
-
ServicePointManager.ReusePort = true;
Assert.True(ServicePointManager.ReusePort);
-
+ }
+ finally
+ {
ServicePointManager.ReusePort = false;
Assert.False(ServicePointManager.ReusePort);
- }).Dispose();
+ }
}
[Fact]
public static void SecurityProtocol_Roundtrips()
{
- RemoteExecutor.Invoke(() =>
+ var orig = (SecurityProtocolType)0; // SystemDefault.
+ Assert.Equal(orig, ServicePointManager.SecurityProtocol);
+ try
{
- var orig = (SecurityProtocolType)0; // SystemDefault.
- Assert.Equal(orig, ServicePointManager.SecurityProtocol);
-
ServicePointManager.SecurityProtocol = SecurityProtocolType.Tls11;
Assert.Equal(SecurityProtocolType.Tls11, ServicePointManager.SecurityProtocol);
-
+ }
+ finally
+ {
ServicePointManager.SecurityProtocol = orig;
Assert.Equal(orig, ServicePointManager.SecurityProtocol);
- }).Dispose();
+ }
}
[Fact]
public static void ServerCertificateValidationCallback_Roundtrips()
{
- RemoteExecutor.Invoke(() =>
+ Assert.Null(ServicePointManager.ServerCertificateValidationCallback);
+ try
{
- Assert.Null(ServicePointManager.ServerCertificateValidationCallback);
-
RemoteCertificateValidationCallback callback = delegate { return true; };
ServicePointManager.ServerCertificateValidationCallback = callback;
Assert.Same(callback, ServicePointManager.ServerCertificateValidationCallback);
-
+ }
+ finally
+ {
ServicePointManager.ServerCertificateValidationCallback = null;
Assert.Null(ServicePointManager.ServerCertificateValidationCallback);
- }).Dispose();
+ }
}
[Fact]
public static void UseNagleAlgorithm_Roundtrips()
{
- RemoteExecutor.Invoke(() =>
+ Assert.True(ServicePointManager.UseNagleAlgorithm);
+ try
{
- Assert.True(ServicePointManager.UseNagleAlgorithm);
-
ServicePointManager.UseNagleAlgorithm = false;
Assert.False(ServicePointManager.UseNagleAlgorithm);
-
+ }
+ finally
+ {
ServicePointManager.UseNagleAlgorithm = true;
Assert.True(ServicePointManager.UseNagleAlgorithm);
- }).Dispose();
+ }
}
[Fact]
[Fact]
public static void SecurityProtocol_Ssl3_NotSupported()
{
- RemoteExecutor.Invoke(() =>
- {
- const int ssl2Client = 0x00000008;
- const int ssl2Server = 0x00000004;
- const SecurityProtocolType ssl2 = (SecurityProtocolType)(ssl2Client | ssl2Server);
+ const int ssl2Client = 0x00000008;
+ const int ssl2Server = 0x00000004;
+ const SecurityProtocolType ssl2 = (SecurityProtocolType)(ssl2Client | ssl2Server);
+ SecurityProtocolType orig = ServicePointManager.SecurityProtocol;
+ try
+ {
#pragma warning disable 0618 // Ssl2, Ssl3 are deprecated.
Assert.Throws<NotSupportedException>(() => ServicePointManager.SecurityProtocol = SecurityProtocolType.Ssl3);
Assert.Throws<NotSupportedException>(() => ServicePointManager.SecurityProtocol = SecurityProtocolType.Ssl3 | ssl2);
#pragma warning restore
- }).Dispose();
+ }
+ finally
+ {
+ ServicePointManager.SecurityProtocol = orig;
+ }
}
[Fact]
}
// Separated out to avoid the JIT in debug builds interfering with object lifetimes
+ [MethodImpl(MethodImplOptions.NoInlining)]
private static bool GetExpect100Continue(string address) =>
ServicePointManager.FindServicePoint(address, null).Expect100Continue;
+
+ [MethodImpl(MethodImplOptions.NoInlining)]
private static void SetExpect100Continue(string address, bool value) =>
ServicePointManager.FindServicePoint(address, null).Expect100Continue = value;
// 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 Microsoft.DotNet.RemoteExecutor;
using Xunit;
namespace System.Net.Tests
[Fact]
public void ServicePointManager_SecurityProtocolDefault_Ok()
{
- RemoteExecutor.Invoke(() => Assert.Equal(SecurityProtocolType.SystemDefault, ServicePointManager.SecurityProtocol)).Dispose();
+ Assert.Equal(SecurityProtocolType.SystemDefault, ServicePointManager.SecurityProtocol);
}
[Fact]
public void ServicePointManager_CheckAllowedProtocols_SystemDefault_Allowed()
{
- RemoteExecutor.Invoke(() => ServicePointManager.SecurityProtocol = SecurityProtocolType.SystemDefault).Dispose();
+ SecurityProtocolType orig = ServicePointManager.SecurityProtocol;
+ try
+ {
+ ServicePointManager.SecurityProtocol = SecurityProtocolType.SystemDefault;
+ Assert.Equal(orig, ServicePointManager.SecurityProtocol);
+ }
+ finally
+ {
+ ServicePointManager.SecurityProtocol = orig;
+ }
}
}
}
--- /dev/null
+// 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;
+
+// Most tests read or write global state. By running all tests serially, as long as those tests reset the state,
+// we can avoid forcing the tests to run in an isolated process.
+[assembly: CollectionBehavior(CollectionBehavior.CollectionPerAssembly, DisableTestParallelization = true, MaxParallelThreads = 1)]
Assert.DoesNotContain(events, ev => ev.EventId == 0); // errors from the EventSource itself
Assert.InRange(events.Count, 1, int.MaxValue);
}
- return RemoteExecutor.SuccessExitCode;
}).Dispose();
}
}
// 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.Common.Tests;
using System.Globalization;
+using System.Tests;
using System.Threading;
using System.Threading.Tasks;
using (var cws = new ClientWebSocket())
{
InvalidOperationException exception;
- using (var tcc = new ThreadCultureChange())
+ using (var tcc = new ThreadCultureChange(CultureInfo.InvariantCulture, CultureInfo.InvariantCulture))
{
- tcc.ChangeCultureInfo(CultureInfo.InvariantCulture);
-
exception = await Assert.ThrowsAsync<InvalidOperationException>(
() => cws.CloseOutputAsync(WebSocketCloseStatus.Empty, "", new CancellationToken()));
}
InvalidOperationException exception;
- using (var tcc = new ThreadCultureChange())
+ using (var tcc = new ThreadCultureChange(CultureInfo.InvariantCulture, CultureInfo.InvariantCulture))
{
- tcc.ChangeCultureInfo(CultureInfo.InvariantCulture);
exception = await Assert.ThrowsAsync<InvalidOperationException>(
() => cws.ReceiveAsync(segment, ct));
}
var ct = new CancellationToken();
InvalidOperationException exception;
- using (var tcc = new ThreadCultureChange())
+ using (var tcc = new ThreadCultureChange(CultureInfo.InvariantCulture, CultureInfo.InvariantCulture))
{
- tcc.ChangeCultureInfo(CultureInfo.InvariantCulture);
exception = await Assert.ThrowsAsync<InvalidOperationException>(
() => cws.SendAsync(segment, WebSocketMessageType.Text, false, ct));
}
<Compile Include="$(CommonTestPath)\System\Threading\Tasks\TaskTimeoutExtensions.cs">
<Link>Common\System\Threading\Tasks\TaskTimeoutExtensions.cs</Link>
</Compile>
- <Compile Include="$(CommonTestPath)\System\ThreadCultureChange.cs">
- <Link>Common\System\ThreadCultureChange.cs</Link>
- </Compile>
<Compile Include="AbortTest.cs" />
<Compile Include="CancelTest.cs" />
<Compile Include="ClientWebSocketOptionsTests.cs" />
<ItemGroup>
<Compile Include="UriRelativeResolutionTest.cs" />
<Compile Include="UriTests.cs" />
- <!-- Test common -->
- <Compile Include="$(CommonTestPath)\System\ThreadCultureChange.cs">
- <Link>Common\System\ThreadCultureChange.cs</Link>
- </Compile>
</ItemGroup>
-</Project>
\ No newline at end of file
+</Project>
// See the LICENSE file in the project root for more information.
using System.Net;
-using System.Common.Tests;
+using System.Tests;
using Xunit;
[Fact]
public void IdnCheckHostName_UnicodeIdnOffIriOn_Dns()
{
- using (var helper = new ThreadCultureChange())
+ Assert.Equal(UriHostNameType.Dns, Uri.CheckHostName("nZMot\u00E1\u00D3\u0063vKi\u00CD.contoso.com"));
+ using (var helper = new ThreadCultureChange("zh-cn"))
{
Assert.Equal(UriHostNameType.Dns, Uri.CheckHostName("nZMot\u00E1\u00D3\u0063vKi\u00CD.contoso.com"));
- helper.ChangeCultureInfo("zh-cn");
- Assert.Equal(UriHostNameType.Dns, Uri.CheckHostName("nZMot\u00E1\u00D3\u0063vKi\u00CD.contoso.com"));
}
}
}
// See the LICENSE file in the project root for more information.
using System.Collections.Generic;
-using System.Common.Tests;
using System.Linq;
+using System.Tests;
using System.Text;
using Xunit;
UriComponents.UserInfo,
};
- using (ThreadCultureChange helper = new ThreadCultureChange())
+ string[] results1 = new string[components.Length];
+ using (new ThreadCultureChange(_testedLocales[0]))
{
- string[] results1 = new string[components.Length];
-
- helper.ChangeCultureInfo(_testedLocales[0]);
for (int i = 0; i < components.Length; i++)
{
results1[i] = EscapeUnescapeTestComponent(uriInput, components[i]);
}
+ }
- for (int j = 1; j < _testedLocales.Length; j++)
+ for (int j = 1; j < _testedLocales.Length; j++)
+ {
+ using (new ThreadCultureChange(_testedLocales[j]))
{
- helper.ChangeCultureInfo(_testedLocales[j]);
-
string[] results2 = new string[components.Length];
for (int i = 0; i < components.Length; i++)
{
<Compile Include="UriRelativeResolutionTest.cs" />
<Compile Include="UriTests.cs" />
<Compile Include="WebSocketsUriParserTest.cs" />
- <!-- Test common -->
- <Compile Include="$(CommonTestPath)\System\ThreadCultureChange.cs">
- <Link>Common\System\ThreadCultureChange.cs</Link>
- </Compile>
</ItemGroup>
-</Project>
\ No newline at end of file
+</Project>
// 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.Common.Tests;
using System.Collections.Generic;
using System.Linq;
+using System.Tests;
using System.Text;
using Xunit;
[Fact]
public void UriEscapingDataString_UnicodeWithIRI_Escaped()
{
- using (var iriHelper = new ThreadCultureChange())
- {
- string input = "\u30AF";
- string output = Uri.EscapeDataString(input);
- Assert.Equal("%E3%82%AF", output);
+ string input = "\u30AF";
- iriHelper.ChangeCultureInfo("zh-cn");
- string outputZhCn = Uri.EscapeDataString(input);
- Assert.Equal(output, outputZhCn); //, "Same normalized result expected in different locales."
+ string output = Uri.EscapeDataString(input);
+ Assert.Equal("%E3%82%AF", output);
+
+ using (new ThreadCultureChange("zh-cn"))
+ {
+ Assert.Equal(output, Uri.EscapeDataString(input)); //, "Same normalized result expected in different locales."
}
}
[Fact]
public void UriEscapingDataString_Unicode_SurrogatePair()
{
- using (ThreadCultureChange iriHelper = new ThreadCultureChange())
- {
- string output = Uri.EscapeDataString(GB18030CertificationString1);
- Assert.Equal(
+ string output = Uri.EscapeDataString(GB18030CertificationString1);
+ Assert.Equal(
@"%E6%95%B0%E6%8D%AE%20eq" +
"%20%27%F0%A0%80%80%F0%A0%80%81%F0%A0%80%82%F0%A0%80%83%F0%AA%9B%91" +
"%F0%AA%9B%92%F0%AA%9B%93%F0%AA%9B%94%F0%AA%9B%95%F0%AA%9B%96%27",
output);
- iriHelper.ChangeCultureInfo("zh-cn");
- string outputZhCn = Uri.EscapeDataString(GB18030CertificationString1);
- Assert.Equal(output, outputZhCn); //"Same normalized result expected in different locales."
+ using (new ThreadCultureChange("zh-cn"))
+ {
+ Assert.Equal(output, Uri.EscapeDataString(GB18030CertificationString1)); //"Same normalized result expected in different locales."
}
}
[Fact]
public void UriUnescapingDataString_UnicodeWithIRI_Unescaped()
{
- using (ThreadCultureChange helper = new ThreadCultureChange())
- {
- string input = @"\u30AF";
- string output = Uri.UnescapeDataString(Escape(input));
- Assert.Equal(input, output);
+ string input = @"\u30AF";
+ string output = Uri.UnescapeDataString(Escape(input));
+ Assert.Equal(input, output);
- helper.ChangeCultureInfo("zh-cn");
- string outputZhCn = Uri.UnescapeDataString(Escape(input));
- Assert.Equal(output, outputZhCn); // Same normalized result expected in different locales.
+ using (new ThreadCultureChange("zh-cn"))
+ {
+ Assert.Equal(output, Uri.UnescapeDataString(Escape(input))); // Same normalized result expected in different locales.
}
}
[Fact]
public void UriUnescapingDataString_Unicode_SurrogatePair()
{
- using (ThreadCultureChange iriHelper = new ThreadCultureChange())
- {
- string escapedInput = Uri.EscapeDataString(GB18030CertificationString1);
- string output = Uri.UnescapeDataString(escapedInput);
- Assert.Equal(GB18030CertificationString1, output);
+ string escapedInput = Uri.EscapeDataString(GB18030CertificationString1);
+ string output = Uri.UnescapeDataString(escapedInput);
+ Assert.Equal(GB18030CertificationString1, output);
- iriHelper.ChangeCultureInfo("zh-cn");
- string outputZhCn = Uri.UnescapeDataString(escapedInput);
- Assert.Equal(output, outputZhCn); //Same normalized result expected in different locales.
+ using (new ThreadCultureChange("zh-cn"))
+ {
+ Assert.Equal(output, Uri.UnescapeDataString(escapedInput)); // Same normalized result expected in different locales.
}
}
[Fact]
public void UriEscapingUriString_UnicodeWithIRI_Escaped()
{
- using (ThreadCultureChange helper = new ThreadCultureChange())
- {
- string input = "\u30AF";
- string output = Uri.EscapeUriString(input);
- Assert.Equal("%E3%82%AF", output);
+ string input = "\u30AF";
+ string output = Uri.EscapeUriString(input);
+ Assert.Equal("%E3%82%AF", output);
- helper.ChangeCultureInfo("zh-cn");
- string outputZhCn = Uri.EscapeUriString(input);
- Assert.Equal(output, outputZhCn); // Same normalized result expected in different locales.
+ using (new ThreadCultureChange("zh-cn"))
+ {
+ Assert.Equal(output, Uri.EscapeUriString(input)); // Same normalized result expected in different locales.
}
}
string expectedString = uriString + "%E6%95%B0%E6%8D%AE%20eq%20%27%F0%A0%80%80%F0%A0%80%81%F0%A0%80%82%F0%A0%80%83%F0" +
"%AA%9B%91%F0%AA%9B%92%F0%AA%9B%93%F0%AA%9B%94%F0%AA%9B%95%F0%AA%9B%96%27";
- using (ThreadCultureChange iriHelper = new ThreadCultureChange())
- {
- Uri uri = new Uri(uriString + Uri.EscapeDataString(GB18030CertificationString1));
- Assert.Equal(expectedString, uri.AbsoluteUri);
+ Uri uri = new Uri(uriString + Uri.EscapeDataString(GB18030CertificationString1));
+ Assert.Equal(expectedString, uri.AbsoluteUri);
- iriHelper.ChangeCultureInfo("zh-cn");
+ using (new ThreadCultureChange("zh-cn"))
+ {
Uri uriZhCn = new Uri(uriString + Uri.EscapeDataString(GB18030CertificationString1));
Assert.Equal(uri.AbsoluteUri, uriZhCn.AbsoluteUri); // Same normalized result expected in different locales.
}
[Fact]
public void UriUnescape_AsciiUtf8AsciiIriOn_ValidUnescaped()
{
- using (ThreadCultureChange irihelper = new ThreadCultureChange())
- {
- string input = "http://host/%5A%E6%9C%88%5A";
-
- string output = Uri.UnescapeDataString(input);
- Assert.Equal("http://host/Z\u6708Z", output);
+ string input = "http://host/%5A%E6%9C%88%5A";
- Uri uri = new Uri(input);
- Assert.Equal("http://host/Z%E6%9C%88Z", uri.AbsoluteUri);
+ string output = Uri.UnescapeDataString(input);
+ Assert.Equal("http://host/Z\u6708Z", output);
- irihelper.ChangeCultureInfo("zh-cn");
- string outputZhCn = Uri.UnescapeDataString(input);
- Assert.Equal(output, outputZhCn);
+ Uri uri = new Uri(input);
+ Assert.Equal("http://host/Z%E6%9C%88Z", uri.AbsoluteUri);
- Uri uriZhCn = new Uri(input);
- Assert.Equal(uri.AbsoluteUri, uriZhCn.AbsoluteUri);
+ using (new ThreadCultureChange("zh-cn"))
+ {
+ Assert.Equal(output, Uri.UnescapeDataString(input));
+ Assert.Equal(uri.AbsoluteUri, new Uri(input).AbsoluteUri);
}
}
[Fact]
public void UriUnescapeInvalid_AsciiIncompleteUtf8AsciiIriOn_InvalidUtf8LeftAlone()
{
- using (ThreadCultureChange irihelper = new ThreadCultureChange())
- {
- string input = "http://host/%5A%E5%9B%5A";
+ string input = "http://host/%5A%E5%9B%5A";
- string output = Uri.UnescapeDataString(input);
- Assert.Equal("http://host/Z%E5%9BZ", output);
+ string output = Uri.UnescapeDataString(input);
+ Assert.Equal("http://host/Z%E5%9BZ", output);
- Uri uri = new Uri(input);
- Assert.Equal("http://host/Z%E5%9BZ", uri.ToString());
- Assert.Equal("http://host/Z%E5%9BZ", uri.AbsoluteUri);
+ Uri uri = new Uri(input);
+ Assert.Equal("http://host/Z%E5%9BZ", uri.ToString());
+ Assert.Equal("http://host/Z%E5%9BZ", uri.AbsoluteUri);
- irihelper.ChangeCultureInfo("zh-cn");
- string outputZhCn = Uri.UnescapeDataString(input);
- Assert.Equal(output, outputZhCn);
+ using (new ThreadCultureChange("zh-cn"))
+ {
+ Assert.Equal(output, Uri.UnescapeDataString(input));
Uri uriZhCn = new Uri(input);
Assert.Equal(uri.AbsoluteUri, uriZhCn.AbsoluteUri);
[Fact]
public void UriUnescapeInvalid_IncompleteUtf8BetweenValidUtf8IriOn_InvalidUtf8LeftAlone()
{
- using (ThreadCultureChange irihelper = new ThreadCultureChange())
- {
- string input = "http://host/%E6%9C%88%E5%9B%E6%9C%88";
+ string input = "http://host/%E6%9C%88%E5%9B%E6%9C%88";
- string output = Uri.UnescapeDataString(input);
- Assert.Equal("http://host/\u6708%E5%9B\u6708", output);
-
- Uri uri = new Uri(input);
- Assert.Equal(input, uri.AbsoluteUri);
+ string output = Uri.UnescapeDataString(input);
+ Assert.Equal("http://host/\u6708%E5%9B\u6708", output);
- irihelper.ChangeCultureInfo("zh-cn");
- string outputZhCn = Uri.UnescapeDataString(input);
- Assert.Equal(output, outputZhCn);
+ Uri uri = new Uri(input);
+ Assert.Equal(input, uri.AbsoluteUri);
- Uri uriZhCn = new Uri(input);
- Assert.Equal(uri.AbsoluteUri, uriZhCn.AbsoluteUri);
+ using (new ThreadCultureChange("zh-cn"))
+ {
+ Assert.Equal(output, Uri.UnescapeDataString(input));
+ Assert.Equal(uri.AbsoluteUri, new Uri(input).AbsoluteUri);
}
}
[Fact]
public void UriUnescapeInvalid_IncompleteUtf8AfterValidUtf8IriOn_InvalidUtf8LeftAlone()
{
- using (ThreadCultureChange irihelper = new ThreadCultureChange())
- {
- string input = "http://host/%59%E6%9C%88%E5%9B";
+ string input = "http://host/%59%E6%9C%88%E5%9B";
- Uri uri = new Uri(input);
- Assert.Equal("http://host/Y%E6%9C%88%E5%9B", uri.AbsoluteUri);
- Assert.Equal("http://host/Y\u6708%E5%9B", uri.ToString());
+ Uri uri = new Uri(input);
+ Assert.Equal("http://host/Y%E6%9C%88%E5%9B", uri.AbsoluteUri);
+ Assert.Equal("http://host/Y\u6708%E5%9B", uri.ToString());
- string output = Uri.UnescapeDataString(input);
- Assert.Equal("http://host/Y\u6708%E5%9B", output);
+ string output = Uri.UnescapeDataString(input);
+ Assert.Equal("http://host/Y\u6708%E5%9B", output);
- irihelper.ChangeCultureInfo("zh-cn");
+ using (new ThreadCultureChange("zh-cn"))
+ {
Uri uriZhCn = new Uri(input);
Assert.Equal(uri.ToString(), uriZhCn.ToString());
Assert.Equal(uri.AbsoluteUri, uriZhCn.AbsoluteUri);
- string outputZhCn = Uri.UnescapeDataString(input);
- Assert.Equal(output, outputZhCn);
+ Assert.Equal(output, Uri.UnescapeDataString(input));
}
}
[Fact]
public void UriUnescapeInvalid_ValidUtf8IncompleteUtf8AsciiIriOn_InvalidUtf8LeftAlone()
{
- using (ThreadCultureChange irihelper = new ThreadCultureChange())
- {
- string input = "http://host/%E6%9C%88%E6%9C%59";
+ string input = "http://host/%E6%9C%88%E6%9C%59";
- Uri uri = new Uri(input);
- Assert.Equal("http://host/%E6%9C%88%E6%9CY", uri.AbsoluteUri);
- Assert.Equal("http://host/\u6708%E6%9CY", uri.ToString());
+ Uri uri = new Uri(input);
+ Assert.Equal("http://host/%E6%9C%88%E6%9CY", uri.AbsoluteUri);
+ Assert.Equal("http://host/\u6708%E6%9CY", uri.ToString());
- string output = Uri.UnescapeDataString(input);
- Assert.Equal("http://host/\u6708%E6%9CY", output);
+ string output = Uri.UnescapeDataString(input);
+ Assert.Equal("http://host/\u6708%E6%9CY", output);
- irihelper.ChangeCultureInfo("zh-cn");
+ using (new ThreadCultureChange("zh-cn"))
+ {
Uri uriZhCn = new Uri(input);
Assert.Equal(uri.ToString(), uriZhCn.ToString());
Assert.Equal(uri.AbsoluteUri, uriZhCn.AbsoluteUri);
- string outputZhCn = Uri.UnescapeDataString(input);
- Assert.Equal(output, outputZhCn);
+ Assert.Equal(output, Uri.UnescapeDataString(input));
}
}
// See the LICENSE file in the project root for more information.
using System.Text;
-using System.Common.Tests;
+using System.Tests;
using Xunit;
string[] results_en = new string[components.Length];
string[] results_zh = new string[components.Length];
-
- using (ThreadCultureChange helper = new ThreadCultureChange())
+ for (int i = 0; i < components.Length; i++)
{
- for (int i = 0; i < components.Length; i++)
- {
- results_en[i] = EscapeUnescapeTestComponent(uriInput, components[i]);
- }
-
- helper.ChangeCultureInfo("zh-cn");
+ results_en[i] = EscapeUnescapeTestComponent(uriInput, components[i]);
+ }
+ using (new ThreadCultureChange("zh-cn"))
+ {
for (int i = 0; i < components.Length; i++)
{
results_zh[i] = EscapeUnescapeTestComponent(uriInput, components[i]);
private void MatchUTF8SequenceTest(byte[] inbytes, int numBytes)
{
- using (ThreadCultureChange helper = new ThreadCultureChange())
- {
- MatchUTF8SequenceOverrunTest(inbytes, numBytes, true, false);
- MatchUTF8SequenceOverrunTest(inbytes, numBytes, true, true);
- MatchUTF8SequenceOverrunTest(inbytes, numBytes, false, false);
- MatchUTF8SequenceOverrunTest(inbytes, numBytes, false, true);
-
- helper.ChangeCultureInfo("zh-cn");
+ MatchUTF8SequenceOverrunTest(inbytes, numBytes, true, false);
+ MatchUTF8SequenceOverrunTest(inbytes, numBytes, true, true);
+ MatchUTF8SequenceOverrunTest(inbytes, numBytes, false, false);
+ MatchUTF8SequenceOverrunTest(inbytes, numBytes, false, true);
+ using (new ThreadCultureChange("zh-cn"))
+ {
MatchUTF8SequenceOverrunTest(inbytes, numBytes, true, false);
MatchUTF8SequenceOverrunTest(inbytes, numBytes, true, true);
MatchUTF8SequenceOverrunTest(inbytes, numBytes, false, false);
<Compile Include="Fakes\FakeUri.cs" />
<Compile Include="Fakes\FakeUriParser.cs" />
<Compile Include="IriEscapeUnescapeTest.cs" />
- <!-- Test common -->
- <Compile Include="$(CommonTestPath)\System\ThreadCultureChange.cs">
- <Link>Common\System\ThreadCultureChange.cs</Link>
- </Compile>
</ItemGroup>
<ItemGroup>
<!-- Production code references -->
<Compile Include="..\..\src\System\IriHelper.cs" />
<Compile Include="..\..\src\System\UriEnumTypes.cs" />
</ItemGroup>
-</Project>
\ No newline at end of file
+</Project>
RemoteExecutor.Invoke(() => {
AppDomain.CurrentDomain.UnhandledException += new UnhandledExceptionEventHandler(MyHandler);
AppDomain.CurrentDomain.UnhandledException -= new UnhandledExceptionEventHandler(MyHandler);
- return RemoteExecutor.SuccessExitCode;
}).Dispose();
}
{
}
AppDomain.CurrentDomain.UnhandledException -= new UnhandledExceptionEventHandler(NotExpectedToBeCalledHandler);
- return RemoteExecutor.SuccessExitCode;
}).Dispose();
}
AppDomain.CurrentDomain.UnhandledException += new UnhandledExceptionEventHandler(MyHandler);
throw new Exception("****This Unhandled Exception is Expected****");
#pragma warning disable 0162
- return RemoteExecutor.SuccessExitCode;
+ return RemoteExecutor.SuccessExitCode;
#pragma warning restore 0162
}, options).Dispose();
// if running directly on some platforms Xunit may be Id = 1
RemoteExecutor.Invoke(() => {
Assert.Equal(1, AppDomain.CurrentDomain.Id);
- return RemoteExecutor.SuccessExitCode;
}).Dispose();
}
public void FirstChanceException_Add_Remove()
{
RemoteExecutor.Invoke(() => {
- EventHandler<FirstChanceExceptionEventArgs> handler = (sender, e) =>
- {
- };
+ EventHandler<FirstChanceExceptionEventArgs> handler = (sender, e) => { };
AppDomain.CurrentDomain.FirstChanceException += handler;
AppDomain.CurrentDomain.FirstChanceException -= handler;
- return RemoteExecutor.SuccessExitCode;
}).Dispose();
}
}
AppDomain.CurrentDomain.FirstChanceException -= handler;
Assert.True(flag, "FirstChanceHandler not called");
- return RemoteExecutor.SuccessExitCode;
}).Dispose();
}
public void ProcessExit_Add_Remove()
{
RemoteExecutor.Invoke(() => {
- EventHandler handler = (sender, e) =>
- {
- };
+ EventHandler handler = (sender, e) => { };
AppDomain.CurrentDomain.ProcessExit += handler;
AppDomain.CurrentDomain.ProcessExit -= handler;
- return RemoteExecutor.SuccessExitCode;
}).Dispose();
}
};
AppDomain.CurrentDomain.ProcessExit += handler;
- return RemoteExecutor.SuccessExitCode;
}, path).Dispose();
Assert.True(File.Exists(path));
AssemblyName assemblyName = assembly.GetName();
assemblyName.CodeBase = null;
Assert.Equal(105, AppDomain.CurrentDomain.ExecuteAssemblyByName(assemblyName, new string[3] { "50", "25", "25" }));
- return RemoteExecutor.SuccessExitCode;
}).Dispose();
}
Assert.Null(AppDomain.CurrentDomain.GetData(""));
AppDomain.CurrentDomain.SetData("randomkey", 4);
Assert.Equal(4, AppDomain.CurrentDomain.GetData("randomkey"));
- return RemoteExecutor.SuccessExitCode;
}).Dispose();
}
Assert.Equal(i.ToString(), AppDomain.CurrentDomain.GetData(key));
}
AppDomain.CurrentDomain.SetData(key, null);
- return RemoteExecutor.SuccessExitCode;
}).Dispose();
}
RemoteExecutor.Invoke(() =>
{
Assert.True(AppDomain.CurrentDomain.IsDefaultAppDomain());
- return RemoteExecutor.SuccessExitCode;
}).Dispose();
}
RemoteExecutor.Invoke(() => {
AssertExtensions.Throws<ArgumentNullException>("domain", () => { AppDomain.Unload(null); });
Assert.Throws<CannotUnloadAppDomainException>(() => { AppDomain.Unload(AppDomain.CurrentDomain); });
- return RemoteExecutor.SuccessExitCode;
}).Dispose();
}
{
RemoteExecutor.Invoke(() => {
AppDomain.CurrentDomain.AppendPrivatePath("test");
- return RemoteExecutor.SuccessExitCode;
}).Dispose();
}
{
RemoteExecutor.Invoke(() => {
AppDomain.CurrentDomain.ClearPrivatePath();
- return RemoteExecutor.SuccessExitCode;
}).Dispose();
}
{
RemoteExecutor.Invoke(() => {
AppDomain.CurrentDomain.ClearShadowCopyPath();
- return RemoteExecutor.SuccessExitCode;
}).Dispose();
}
{
RemoteExecutor.Invoke(() => {
AppDomain.CurrentDomain.SetCachePath("test");
- return RemoteExecutor.SuccessExitCode;
}).Dispose();
}
{
RemoteExecutor.Invoke(() => {
AppDomain.CurrentDomain.SetShadowCopyFiles();
- return RemoteExecutor.SuccessExitCode;
}).Dispose();
}
{
RemoteExecutor.Invoke(() => {
AppDomain.CurrentDomain.SetShadowCopyPath("test");
- return RemoteExecutor.SuccessExitCode;
}).Dispose();
}
}
}
Assert.True(ctr > 0, "Assembly.LoadFile should cause file to be loaded again");
- return RemoteExecutor.SuccessExitCode;
}).Dispose();
}
AppDomain.CurrentDomain.AssemblyLoad -= handler;
}
Assert.True(AssemblyLoadFlag);
- return RemoteExecutor.SuccessExitCode;
}).Dispose();
}
Type t = Type.GetType("AssemblyResolveTestApp.Class1, InvalidAssemblyName", throwOnError : false);
Assert.Null(t);
Assert.True(AssemblyResolveFlag);
- return RemoteExecutor.SuccessExitCode;
}).Dispose();
}
Assert.NotNull(t);
// https://github.com/dotnet/corefx/issues/38361
// Assert.True(AssemblyResolveFlag);
- return RemoteExecutor.SuccessExitCode;
}).Dispose();
}
Assert.NotNull(ret);
// https://github.com/dotnet/corefx/issues/38361
// Assert.True(AssemblyResolveFlag);
- return RemoteExecutor.SuccessExitCode;
}).Dispose();
}
{
CultureInfo.CurrentUICulture = previousUICulture;
}
-
- return RemoteExecutor.SuccessExitCode;
}).Dispose();
}
AppDomain.CurrentDomain.TypeResolve -= handler;
}
Assert.NotNull(t);
- return RemoteExecutor.SuccessExitCode;
}).Dispose();
}
AppDomain.CurrentDomain.ResourceResolve -= handler;
}
Assert.Equal("Happy Halloween", s);
- return RemoteExecutor.SuccessExitCode;
}).Dispose();
}
var identity = new System.Security.Principal.GenericIdentity("NewUser");
var principal = new System.Security.Principal.GenericPrincipal(identity, null);
AppDomain.CurrentDomain.SetThreadPrincipal(principal);
- return RemoteExecutor.SuccessExitCode;
}).Dispose();
}
RemoteExecutor.Invoke(() => {
Assert.Equal(AppContext.BaseDirectory, AppDomain.CurrentDomain.SetupInformation.ApplicationBase);
Assert.Equal(AppContext.TargetFrameworkName, AppDomain.CurrentDomain.SetupInformation.TargetFrameworkName);
- return RemoteExecutor.SuccessExitCode;
}).Dispose();
}
{
RemoteExecutor.Invoke(() => {
Assert.Equal(new PermissionSet(PermissionState.Unrestricted), AppDomain.CurrentDomain.PermissionSet);
- return RemoteExecutor.SuccessExitCode;
}).Dispose();
}
Exception thrown = Assert.Throws<FileNotFoundException>(() => assembly.GetType("System.Tests.AGenericClass`1[[Bogus, AnotherBogusAssembly]]", true));
Assert.Same(firstChanceExceptionThrown, thrown);
-
- return RemoteExecutor.SuccessExitCode;
}).Dispose();
}
}
// path that followed the symlink.
Assert.Equal(TestDirectory, Directory.GetCurrentDirectory());
}
-
- return RemoteExecutor.SuccessExitCode;
}).Dispose();
}
[ActiveIssue("21404", TargetFrameworkMonikers.Uap)]
public void FailFast_ExpectFailureExitCode()
{
- using (RemoteInvokeHandle handle = RemoteExecutor.Invoke(() => { Environment.FailFast("message"); return RemoteExecutor.SuccessExitCode; }))
+ using (RemoteInvokeHandle handle = RemoteExecutor.Invoke(() => Environment.FailFast("message")))
{
Process p = handle.Process;
handle.Process = null;
Assert.NotEqual(RemoteExecutor.SuccessExitCode, p.ExitCode);
}
- using (RemoteInvokeHandle handle = RemoteExecutor.Invoke(() => { Environment.FailFast("message", new Exception("uh oh")); return RemoteExecutor.SuccessExitCode; }))
+ using (RemoteInvokeHandle handle = RemoteExecutor.Invoke(() => Environment.FailFast("message", new Exception("uh oh"))))
{
Process p = handle.Process;
handle.Process = null;
psi.RedirectStandardOutput = true;
using (RemoteInvokeHandle handle = RemoteExecutor.Invoke(
- () => { Environment.FailFast("message", new ArgumentException("bad arg")); return RemoteExecutor.SuccessExitCode; },
+ () => Environment.FailFast("message", new ArgumentException("bad arg")),
new RemoteInvokeOptions { StartInfo = psi }))
{
Process p = handle.Process;
psi.RedirectStandardOutput = true;
using (RemoteInvokeHandle handle = RemoteExecutor.Invoke(
- () => { Environment.FailFast("message", new StackOverflowException("SO exception")); return RemoteExecutor.SuccessExitCode; },
+ () => Environment.FailFast("message", new StackOverflowException("SO exception")),
new RemoteInvokeOptions { StartInfo = psi }))
{
Process p = handle.Process;
psi.RedirectStandardOutput = true;
using (RemoteInvokeHandle handle = RemoteExecutor.Invoke(
- () => { Environment.FailFast("message", new ArgumentException("first exception", new NullReferenceException("inner exception"))); return RemoteExecutor.SuccessExitCode; },
+ () => Environment.FailFast("message", new ArgumentException("first exception", new NullReferenceException("inner exception"))),
new RemoteInvokeOptions { StartInfo = psi }))
{
Process p = handle.Process;
File.WriteAllText(fileName, string.Empty);
- Func<string, int> otherProcess = f =>
+ Action<string> otherProcess = f =>
{
Action<int> OnUnloading = i => File.AppendAllText(f, string.Format("u{0}", i));
Action<int> OnProcessExit = i => File.AppendAllText(f, string.Format("e{0}", i));
AppDomain.CurrentDomain.ProcessExit += (sender, e) => OnProcessExit(1);
System.Runtime.Loader.AssemblyLoadContext.Default.Unloading += acl => OnUnloading(1);
File.AppendAllText(f, "h");
-
- return RemoteExecutor.SuccessExitCode;
};
using (var remote = RemoteExecutor.Invoke(otherProcess, fileName))
RemoteExecutor.Invoke(() =>
{
Assert.Null(AssemblyLoadContext.CurrentContextualReflectionContext);
-
- return RemoteExecutor.SuccessExitCode;
}).Dispose();
}
using System.Collections.Generic;
using System.Diagnostics;
using System.Globalization;
+using System.Tests;
using Microsoft.DotNet.RemoteExecutor;
using Xunit;
[Fact]
public static void RunRegionSpecificStandardFormatToStringTests()
{
- RemoteExecutor.Invoke(() =>
+ RemoteExecutorForUap.Invoke(() =>
{
CultureInfo[] cultures = new CultureInfo[] { new CultureInfo("en-US"), new CultureInfo("en-GB"), new CultureInfo("fr-CA"),
new CultureInfo("ar-SA"), new CultureInfo("de-DE"), new CultureInfo("he-IL"),
foreach (CultureInfo culture in cultures)
{
// Set CurrentCulture to simulate different locales
- CultureInfo.CurrentCulture = culture;
-
- // Currency
- RunStandardFormatToStringTests(s_random, "C", culture.NumberFormat.NegativeSign, culture.NumberFormat.CurrencyDecimalDigits, CurrencyFormatter);
- RunStandardFormatToStringTests(s_random, "c0", culture.NumberFormat.NegativeSign, 0, CurrencyFormatter);
- RunStandardFormatToStringTests(s_random, "C1", culture.NumberFormat.NegativeSign, 1, CurrencyFormatter);
- RunStandardFormatToStringTests(s_random, "c2", culture.NumberFormat.NegativeSign, 2, CurrencyFormatter);
- RunStandardFormatToStringTests(s_random, "C5", culture.NumberFormat.NegativeSign, 5, CurrencyFormatter);
- RunStandardFormatToStringTests(s_random, "c33", culture.NumberFormat.NegativeSign, 33, CurrencyFormatter);
- RunStandardFormatToStringTests(s_random, "C99", culture.NumberFormat.NegativeSign, 99, CurrencyFormatter);
-
- // Decimal
- RunStandardFormatToStringTests(s_random, "D", culture.NumberFormat.NegativeSign, 0, DecimalFormatter);
- RunStandardFormatToStringTests(s_random, "d0", culture.NumberFormat.NegativeSign, 0, DecimalFormatter);
- RunStandardFormatToStringTests(s_random, "D1", culture.NumberFormat.NegativeSign, 1, DecimalFormatter);
- RunStandardFormatToStringTests(s_random, "d2", culture.NumberFormat.NegativeSign, 2, DecimalFormatter);
- RunStandardFormatToStringTests(s_random, "D5", culture.NumberFormat.NegativeSign, 5, DecimalFormatter);
- RunStandardFormatToStringTests(s_random, "d33", culture.NumberFormat.NegativeSign, 33, DecimalFormatter);
- RunStandardFormatToStringTests(s_random, "D99", culture.NumberFormat.NegativeSign, 99, DecimalFormatter);
-
- // Exponential (note: negative precision means lower case e)
- RunStandardFormatToStringTests(s_random, "E", culture.NumberFormat.NegativeSign, 6, ExponentialFormatter);
- RunStandardFormatToStringTests(s_random, "E0", culture.NumberFormat.NegativeSign, 0, ExponentialFormatter);
- RunStandardFormatToStringTests(s_random, "E1", culture.NumberFormat.NegativeSign, 1, ExponentialFormatter);
- RunStandardFormatToStringTests(s_random, "e2", culture.NumberFormat.NegativeSign, -2, ExponentialFormatter);
- RunStandardFormatToStringTests(s_random, "E5", culture.NumberFormat.NegativeSign, 5, ExponentialFormatter);
- RunStandardFormatToStringTests(s_random, "e33", culture.NumberFormat.NegativeSign, -33, ExponentialFormatter);
- RunStandardFormatToStringTests(s_random, "E99", culture.NumberFormat.NegativeSign, 99, ExponentialFormatter);
-
- // Fixed-Point
- RunStandardFormatToStringTests(s_random, "f", culture.NumberFormat.NegativeSign, culture.NumberFormat.NumberDecimalDigits, FixedFormatter);
- RunStandardFormatToStringTests(s_random, "F0", culture.NumberFormat.NegativeSign, 0, FixedFormatter);
- RunStandardFormatToStringTests(s_random, "f1", culture.NumberFormat.NegativeSign, 1, FixedFormatter);
- RunStandardFormatToStringTests(s_random, "F2", culture.NumberFormat.NegativeSign, 2, FixedFormatter);
- RunStandardFormatToStringTests(s_random, "f5", culture.NumberFormat.NegativeSign, 5, FixedFormatter);
- RunStandardFormatToStringTests(s_random, "F33", culture.NumberFormat.NegativeSign, 33, FixedFormatter);
- RunStandardFormatToStringTests(s_random, "f99", culture.NumberFormat.NegativeSign, 99, FixedFormatter);
-
- // General
- RunStandardFormatToStringTests(s_random, "g", culture.NumberFormat.NegativeSign, 0, DecimalFormatter);
- RunStandardFormatToStringTests(s_random, "G0", culture.NumberFormat.NegativeSign, 0, DecimalFormatter);
- RunStandardFormatToStringTests(s_random, "G1", culture.NumberFormat.NegativeSign, 1, DecimalFormatter);
- RunStandardFormatToStringTests(s_random, "G2", culture.NumberFormat.NegativeSign, 2, DecimalFormatter);
- RunStandardFormatToStringTests(s_random, "g5", culture.NumberFormat.NegativeSign, 5, DecimalFormatter);
- RunStandardFormatToStringTests(s_random, "G33", culture.NumberFormat.NegativeSign, 33, DecimalFormatter);
- RunStandardFormatToStringTests(s_random, "g99", culture.NumberFormat.NegativeSign, 99, DecimalFormatter);
-
- // Number
- RunStandardFormatToStringTests(s_random, "n", culture.NumberFormat.NegativeSign, culture.NumberFormat.NumberDecimalDigits, NumberFormatter);
- RunStandardFormatToStringTests(s_random, "N0", culture.NumberFormat.NegativeSign, 0, NumberFormatter);
- RunStandardFormatToStringTests(s_random, "N1", culture.NumberFormat.NegativeSign, 1, NumberFormatter);
- RunStandardFormatToStringTests(s_random, "N2", culture.NumberFormat.NegativeSign, 2, NumberFormatter);
- RunStandardFormatToStringTests(s_random, "n5", culture.NumberFormat.NegativeSign, 5, NumberFormatter);
- RunStandardFormatToStringTests(s_random, "N33", culture.NumberFormat.NegativeSign, 33, NumberFormatter);
- RunStandardFormatToStringTests(s_random, "n99", culture.NumberFormat.NegativeSign, 99, NumberFormatter);
-
- // Percent
- RunStandardFormatToStringTests(s_random, "p", culture.NumberFormat.NegativeSign, culture.NumberFormat.PercentDecimalDigits, PercentFormatter);
- RunStandardFormatToStringTests(s_random, "P0", culture.NumberFormat.NegativeSign, 0, PercentFormatter);
- RunStandardFormatToStringTests(s_random, "P1", culture.NumberFormat.NegativeSign, 1, PercentFormatter);
- RunStandardFormatToStringTests(s_random, "P2", culture.NumberFormat.NegativeSign, 2, PercentFormatter);
- RunStandardFormatToStringTests(s_random, "p5", culture.NumberFormat.NegativeSign, 5, PercentFormatter);
- RunStandardFormatToStringTests(s_random, "P33", culture.NumberFormat.NegativeSign, 33, PercentFormatter);
- RunStandardFormatToStringTests(s_random, "p99", culture.NumberFormat.NegativeSign, 99, PercentFormatter);
-
- // Hex
- RunStandardFormatToStringTests(s_random, "X", culture.NumberFormat.NegativeSign, 0, HexFormatter);
- RunStandardFormatToStringTests(s_random, "X0", culture.NumberFormat.NegativeSign, 0, HexFormatter);
- RunStandardFormatToStringTests(s_random, "x1", culture.NumberFormat.NegativeSign, -1, HexFormatter);
- RunStandardFormatToStringTests(s_random, "X2", culture.NumberFormat.NegativeSign, 2, HexFormatter);
- RunStandardFormatToStringTests(s_random, "x5", culture.NumberFormat.NegativeSign, -5, HexFormatter);
- RunStandardFormatToStringTests(s_random, "X33", culture.NumberFormat.NegativeSign, 33, HexFormatter);
- RunStandardFormatToStringTests(s_random, "x99", culture.NumberFormat.NegativeSign, -99, HexFormatter);
-
- // RoundTrip
- RunStandardFormatToStringTests(s_random, "R", culture.NumberFormat.NegativeSign, 0, DecimalFormatter);
- RunStandardFormatToStringTests(s_random, "R0", culture.NumberFormat.NegativeSign, 0, DecimalFormatter);
- RunStandardFormatToStringTests(s_random, "r1", culture.NumberFormat.NegativeSign, 1, DecimalFormatter);
- RunStandardFormatToStringTests(s_random, "R2", culture.NumberFormat.NegativeSign, 2, DecimalFormatter);
- RunStandardFormatToStringTests(s_random, "r5", culture.NumberFormat.NegativeSign, 5, DecimalFormatter);
- RunStandardFormatToStringTests(s_random, "R33", culture.NumberFormat.NegativeSign, 33, DecimalFormatter);
- RunStandardFormatToStringTests(s_random, "r99", culture.NumberFormat.NegativeSign, 99, DecimalFormatter);
+ using (new ThreadCultureChange(culture))
+ {
+ // Currency
+ RunStandardFormatToStringTests(s_random, "C", culture.NumberFormat.NegativeSign, culture.NumberFormat.CurrencyDecimalDigits, CurrencyFormatter);
+ RunStandardFormatToStringTests(s_random, "c0", culture.NumberFormat.NegativeSign, 0, CurrencyFormatter);
+ RunStandardFormatToStringTests(s_random, "C1", culture.NumberFormat.NegativeSign, 1, CurrencyFormatter);
+ RunStandardFormatToStringTests(s_random, "c2", culture.NumberFormat.NegativeSign, 2, CurrencyFormatter);
+ RunStandardFormatToStringTests(s_random, "C5", culture.NumberFormat.NegativeSign, 5, CurrencyFormatter);
+ RunStandardFormatToStringTests(s_random, "c33", culture.NumberFormat.NegativeSign, 33, CurrencyFormatter);
+ RunStandardFormatToStringTests(s_random, "C99", culture.NumberFormat.NegativeSign, 99, CurrencyFormatter);
+
+ // Decimal
+ RunStandardFormatToStringTests(s_random, "D", culture.NumberFormat.NegativeSign, 0, DecimalFormatter);
+ RunStandardFormatToStringTests(s_random, "d0", culture.NumberFormat.NegativeSign, 0, DecimalFormatter);
+ RunStandardFormatToStringTests(s_random, "D1", culture.NumberFormat.NegativeSign, 1, DecimalFormatter);
+ RunStandardFormatToStringTests(s_random, "d2", culture.NumberFormat.NegativeSign, 2, DecimalFormatter);
+ RunStandardFormatToStringTests(s_random, "D5", culture.NumberFormat.NegativeSign, 5, DecimalFormatter);
+ RunStandardFormatToStringTests(s_random, "d33", culture.NumberFormat.NegativeSign, 33, DecimalFormatter);
+ RunStandardFormatToStringTests(s_random, "D99", culture.NumberFormat.NegativeSign, 99, DecimalFormatter);
+
+ // Exponential (note: negative precision means lower case e)
+ RunStandardFormatToStringTests(s_random, "E", culture.NumberFormat.NegativeSign, 6, ExponentialFormatter);
+ RunStandardFormatToStringTests(s_random, "E0", culture.NumberFormat.NegativeSign, 0, ExponentialFormatter);
+ RunStandardFormatToStringTests(s_random, "E1", culture.NumberFormat.NegativeSign, 1, ExponentialFormatter);
+ RunStandardFormatToStringTests(s_random, "e2", culture.NumberFormat.NegativeSign, -2, ExponentialFormatter);
+ RunStandardFormatToStringTests(s_random, "E5", culture.NumberFormat.NegativeSign, 5, ExponentialFormatter);
+ RunStandardFormatToStringTests(s_random, "e33", culture.NumberFormat.NegativeSign, -33, ExponentialFormatter);
+ RunStandardFormatToStringTests(s_random, "E99", culture.NumberFormat.NegativeSign, 99, ExponentialFormatter);
+
+ // Fixed-Point
+ RunStandardFormatToStringTests(s_random, "f", culture.NumberFormat.NegativeSign, culture.NumberFormat.NumberDecimalDigits, FixedFormatter);
+ RunStandardFormatToStringTests(s_random, "F0", culture.NumberFormat.NegativeSign, 0, FixedFormatter);
+ RunStandardFormatToStringTests(s_random, "f1", culture.NumberFormat.NegativeSign, 1, FixedFormatter);
+ RunStandardFormatToStringTests(s_random, "F2", culture.NumberFormat.NegativeSign, 2, FixedFormatter);
+ RunStandardFormatToStringTests(s_random, "f5", culture.NumberFormat.NegativeSign, 5, FixedFormatter);
+ RunStandardFormatToStringTests(s_random, "F33", culture.NumberFormat.NegativeSign, 33, FixedFormatter);
+ RunStandardFormatToStringTests(s_random, "f99", culture.NumberFormat.NegativeSign, 99, FixedFormatter);
+
+ // General
+ RunStandardFormatToStringTests(s_random, "g", culture.NumberFormat.NegativeSign, 0, DecimalFormatter);
+ RunStandardFormatToStringTests(s_random, "G0", culture.NumberFormat.NegativeSign, 0, DecimalFormatter);
+ RunStandardFormatToStringTests(s_random, "G1", culture.NumberFormat.NegativeSign, 1, DecimalFormatter);
+ RunStandardFormatToStringTests(s_random, "G2", culture.NumberFormat.NegativeSign, 2, DecimalFormatter);
+ RunStandardFormatToStringTests(s_random, "g5", culture.NumberFormat.NegativeSign, 5, DecimalFormatter);
+ RunStandardFormatToStringTests(s_random, "G33", culture.NumberFormat.NegativeSign, 33, DecimalFormatter);
+ RunStandardFormatToStringTests(s_random, "g99", culture.NumberFormat.NegativeSign, 99, DecimalFormatter);
+
+ // Number
+ RunStandardFormatToStringTests(s_random, "n", culture.NumberFormat.NegativeSign, culture.NumberFormat.NumberDecimalDigits, NumberFormatter);
+ RunStandardFormatToStringTests(s_random, "N0", culture.NumberFormat.NegativeSign, 0, NumberFormatter);
+ RunStandardFormatToStringTests(s_random, "N1", culture.NumberFormat.NegativeSign, 1, NumberFormatter);
+ RunStandardFormatToStringTests(s_random, "N2", culture.NumberFormat.NegativeSign, 2, NumberFormatter);
+ RunStandardFormatToStringTests(s_random, "n5", culture.NumberFormat.NegativeSign, 5, NumberFormatter);
+ RunStandardFormatToStringTests(s_random, "N33", culture.NumberFormat.NegativeSign, 33, NumberFormatter);
+ RunStandardFormatToStringTests(s_random, "n99", culture.NumberFormat.NegativeSign, 99, NumberFormatter);
+
+ // Percent
+ RunStandardFormatToStringTests(s_random, "p", culture.NumberFormat.NegativeSign, culture.NumberFormat.PercentDecimalDigits, PercentFormatter);
+ RunStandardFormatToStringTests(s_random, "P0", culture.NumberFormat.NegativeSign, 0, PercentFormatter);
+ RunStandardFormatToStringTests(s_random, "P1", culture.NumberFormat.NegativeSign, 1, PercentFormatter);
+ RunStandardFormatToStringTests(s_random, "P2", culture.NumberFormat.NegativeSign, 2, PercentFormatter);
+ RunStandardFormatToStringTests(s_random, "p5", culture.NumberFormat.NegativeSign, 5, PercentFormatter);
+ RunStandardFormatToStringTests(s_random, "P33", culture.NumberFormat.NegativeSign, 33, PercentFormatter);
+ RunStandardFormatToStringTests(s_random, "p99", culture.NumberFormat.NegativeSign, 99, PercentFormatter);
+
+ // Hex
+ RunStandardFormatToStringTests(s_random, "X", culture.NumberFormat.NegativeSign, 0, HexFormatter);
+ RunStandardFormatToStringTests(s_random, "X0", culture.NumberFormat.NegativeSign, 0, HexFormatter);
+ RunStandardFormatToStringTests(s_random, "x1", culture.NumberFormat.NegativeSign, -1, HexFormatter);
+ RunStandardFormatToStringTests(s_random, "X2", culture.NumberFormat.NegativeSign, 2, HexFormatter);
+ RunStandardFormatToStringTests(s_random, "x5", culture.NumberFormat.NegativeSign, -5, HexFormatter);
+ RunStandardFormatToStringTests(s_random, "X33", culture.NumberFormat.NegativeSign, 33, HexFormatter);
+ RunStandardFormatToStringTests(s_random, "x99", culture.NumberFormat.NegativeSign, -99, HexFormatter);
+
+ // RoundTrip
+ RunStandardFormatToStringTests(s_random, "R", culture.NumberFormat.NegativeSign, 0, DecimalFormatter);
+ RunStandardFormatToStringTests(s_random, "R0", culture.NumberFormat.NegativeSign, 0, DecimalFormatter);
+ RunStandardFormatToStringTests(s_random, "r1", culture.NumberFormat.NegativeSign, 1, DecimalFormatter);
+ RunStandardFormatToStringTests(s_random, "R2", culture.NumberFormat.NegativeSign, 2, DecimalFormatter);
+ RunStandardFormatToStringTests(s_random, "r5", culture.NumberFormat.NegativeSign, 5, DecimalFormatter);
+ RunStandardFormatToStringTests(s_random, "R33", culture.NumberFormat.NegativeSign, 33, DecimalFormatter);
+ RunStandardFormatToStringTests(s_random, "r99", culture.NumberFormat.NegativeSign, 99, DecimalFormatter);
+ }
}
}).Dispose();
}
using System.Collections.Generic;
using System.Diagnostics;
using System.Globalization;
+using System.Tests;
using System.Threading;
using Microsoft.DotNet.RemoteExecutor;
using Xunit;
[OuterLoop]
public static void RunParseToStringTests(CultureInfo culture)
{
- RemoteExecutor.Invoke((cultureName) =>
+ RemoteExecutorForUap.Invoke((cultureName) =>
{
byte[] tempByteArray1 = new byte[0];
-
- Thread.CurrentThread.CurrentCulture = CultureInfo.GetCultureInfo(cultureName);
-
- //default style
- VerifyDefaultParse(s_random);
-
- //single NumberStyles
- VerifyNumberStyles(NumberStyles.None, s_random);
- VerifyNumberStyles(NumberStyles.AllowLeadingWhite, s_random);
- VerifyNumberStyles(NumberStyles.AllowTrailingWhite, s_random);
- VerifyNumberStyles(NumberStyles.AllowLeadingSign, s_random);
- VerifyNumberStyles(NumberStyles.AllowTrailingSign, s_random);
- VerifyNumberStyles(NumberStyles.AllowParentheses, s_random);
- VerifyNumberStyles(NumberStyles.AllowDecimalPoint, s_random);
- VerifyNumberStyles(NumberStyles.AllowThousands, s_random);
- VerifyNumberStyles(NumberStyles.AllowExponent, s_random);
- VerifyNumberStyles(NumberStyles.AllowCurrencySymbol, s_random);
- VerifyNumberStyles(NumberStyles.AllowHexSpecifier, s_random);
-
- //composite NumberStyles
- VerifyNumberStyles(NumberStyles.Integer, s_random);
- VerifyNumberStyles(NumberStyles.HexNumber, s_random);
- VerifyNumberStyles(NumberStyles.Number, s_random);
- VerifyNumberStyles(NumberStyles.Float, s_random);
- VerifyNumberStyles(NumberStyles.Currency, s_random);
- VerifyNumberStyles(NumberStyles.Any, s_random);
-
- //invalid number style
- // ******InvalidNumberStyles
- NumberStyles invalid = (NumberStyles)0x7c00;
- AssertExtensions.Throws<ArgumentException>(null, () =>
- {
- BigInteger.Parse("1", invalid).ToString("d");
- });
- AssertExtensions.Throws<ArgumentException>(null, () =>
+ using (new ThreadCultureChange(cultureName))
{
- BigInteger junk;
- BigInteger.TryParse("1", invalid, null, out junk);
- Assert.Equal("1", junk.ToString("d"));
- });
-
- //FormatProvider tests
- RunFormatProviderParseStrings();
+ //default style
+ VerifyDefaultParse(s_random);
+
+ //single NumberStyles
+ VerifyNumberStyles(NumberStyles.None, s_random);
+ VerifyNumberStyles(NumberStyles.AllowLeadingWhite, s_random);
+ VerifyNumberStyles(NumberStyles.AllowTrailingWhite, s_random);
+ VerifyNumberStyles(NumberStyles.AllowLeadingSign, s_random);
+ VerifyNumberStyles(NumberStyles.AllowTrailingSign, s_random);
+ VerifyNumberStyles(NumberStyles.AllowParentheses, s_random);
+ VerifyNumberStyles(NumberStyles.AllowDecimalPoint, s_random);
+ VerifyNumberStyles(NumberStyles.AllowThousands, s_random);
+ VerifyNumberStyles(NumberStyles.AllowExponent, s_random);
+ VerifyNumberStyles(NumberStyles.AllowCurrencySymbol, s_random);
+ VerifyNumberStyles(NumberStyles.AllowHexSpecifier, s_random);
+
+ //composite NumberStyles
+ VerifyNumberStyles(NumberStyles.Integer, s_random);
+ VerifyNumberStyles(NumberStyles.HexNumber, s_random);
+ VerifyNumberStyles(NumberStyles.Number, s_random);
+ VerifyNumberStyles(NumberStyles.Float, s_random);
+ VerifyNumberStyles(NumberStyles.Currency, s_random);
+ VerifyNumberStyles(NumberStyles.Any, s_random);
+
+ //invalid number style
+ // ******InvalidNumberStyles
+ NumberStyles invalid = (NumberStyles)0x7c00;
+ AssertExtensions.Throws<ArgumentException>(null, () =>
+ {
+ BigInteger.Parse("1", invalid).ToString("d");
+ });
+ AssertExtensions.Throws<ArgumentException>(null, () =>
+ {
+ BigInteger junk;
+ BigInteger.TryParse("1", invalid, null, out junk);
+ Assert.Equal("1", junk.ToString("d"));
+ });
+ //FormatProvider tests
+ RunFormatProviderParseStrings();
+ }
}, culture.ToString()).Dispose();
}
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Collections.Specialized;
-using System.Common.Tests;
+using System.Tests;
using System.ComponentModel;
using System.ComponentModel.Composition;
using System.ComponentModel.DataAnnotations;
public static IEnumerable<object[]> SerializableObjects_MemberData()
{
// Save old culture and set a fixed culture for object instantiation
- using (new ThreadCultureChange(CultureInfo.InvariantCulture))
+ using (new ThreadCultureChange(CultureInfo.InvariantCulture, CultureInfo.InvariantCulture))
{
return SerializableObjects().ToArray();
}
{
var b = new BinaryFormatter();
b.Serialize(output, b.Deserialize(input));
- return RemoteExecutor.SuccessExitCode;
}
}, outputPath, inputPath).Dispose();
<Compile Include="$(CommonTestPath)\System\Runtime\Serialization\Formatters\BinaryFormatterHelpers.cs">
<Link>Common\System\Runtime\Serialization\Formatters\BinaryFormatterHelpers.cs</Link>
</Compile>
- <Compile Include="$(CommonTestPath)\System\ThreadCultureChange.cs">
- <Link>Common\System\ThreadCultureChange.cs</Link>
- </Compile>
</ItemGroup>
<ItemGroup Condition="'$(TargetsNetCoreApp)' == 'true'">
<Reference Include="System.Text.Json" />
</ItemGroup>
-</Project>
\ No newline at end of file
+</Project>
[Fact]
public static void Test_ToString()
{
- RemoteExecutor.Invoke(() =>
+ RemoteExecutorForUap.Invoke(() =>
{
- CultureInfo.CurrentCulture = CultureInfo.InvariantCulture;
-
- foreach (var testdata in ToString_TestData())
+ using (new ThreadCultureChange(CultureInfo.InvariantCulture))
{
- ToString((decimal)testdata[0], (string)testdata[1], (IFormatProvider)testdata[2], (string)testdata[3]);
+ foreach (object[] testdata in ToString_TestData())
+ {
+ ToString((decimal)testdata[0], (string)testdata[1], (IFormatProvider)testdata[2], (string)testdata[3]);
+ }
}
- return RemoteExecutor.SuccessExitCode;
}).Dispose();
}
[Fact]
public static void TryFormat()
{
- RemoteExecutor.Invoke(() =>
+ RemoteExecutorForUap.Invoke(() =>
{
- CultureInfo.CurrentCulture = CultureInfo.InvariantCulture;
-
- foreach (var testdata in ToString_TestData())
+ using (new ThreadCultureChange(CultureInfo.InvariantCulture))
{
- decimal localI = (decimal)testdata[0];
- string localFormat = (string)testdata[1];
- IFormatProvider localProvider = (IFormatProvider)testdata[2];
- string localExpected = (string)testdata[3];
-
- try
+ foreach (object[] testdata in ToString_TestData())
{
- char[] actual;
- int charsWritten;
-
- // Just right
- actual = new char[localExpected.Length];
- Assert.True(localI.TryFormat(actual.AsSpan(), out charsWritten, localFormat, localProvider));
- Assert.Equal(localExpected.Length, charsWritten);
- Assert.Equal(localExpected, new string(actual));
-
- // Longer than needed
- actual = new char[localExpected.Length + 1];
- Assert.True(localI.TryFormat(actual.AsSpan(), out charsWritten, localFormat, localProvider));
- Assert.Equal(localExpected.Length, charsWritten);
- Assert.Equal(localExpected, new string(actual, 0, charsWritten));
-
- // Too short
- if (localExpected.Length > 0)
- {
- actual = new char[localExpected.Length - 1];
- Assert.False(localI.TryFormat(actual.AsSpan(), out charsWritten, localFormat, localProvider));
- Assert.Equal(0, charsWritten);
- }
+ decimal localI = (decimal)testdata[0];
+ string localFormat = (string)testdata[1];
+ IFormatProvider localProvider = (IFormatProvider)testdata[2];
+ string localExpected = (string)testdata[3];
- if (localFormat != null)
+ try
{
- // Upper localFormat
+ char[] actual;
+ int charsWritten;
+
+ // Just right
actual = new char[localExpected.Length];
- Assert.True(localI.TryFormat(actual.AsSpan(), out charsWritten, localFormat.ToUpperInvariant(), localProvider));
+ Assert.True(localI.TryFormat(actual.AsSpan(), out charsWritten, localFormat, localProvider));
Assert.Equal(localExpected.Length, charsWritten);
- Assert.Equal(localExpected.ToUpperInvariant(), new string(actual));
+ Assert.Equal(localExpected, new string(actual));
- // Lower format
- actual = new char[localExpected.Length];
- Assert.True(localI.TryFormat(actual.AsSpan(), out charsWritten, localFormat.ToLowerInvariant(), localProvider));
+ // Longer than needed
+ actual = new char[localExpected.Length + 1];
+ Assert.True(localI.TryFormat(actual.AsSpan(), out charsWritten, localFormat, localProvider));
Assert.Equal(localExpected.Length, charsWritten);
- Assert.Equal(localExpected.ToLowerInvariant(), new string(actual));
+ Assert.Equal(localExpected, new string(actual, 0, charsWritten));
+
+ // Too short
+ if (localExpected.Length > 0)
+ {
+ actual = new char[localExpected.Length - 1];
+ Assert.False(localI.TryFormat(actual.AsSpan(), out charsWritten, localFormat, localProvider));
+ Assert.Equal(0, charsWritten);
+ }
+
+ if (localFormat != null)
+ {
+ // Upper localFormat
+ actual = new char[localExpected.Length];
+ Assert.True(localI.TryFormat(actual.AsSpan(), out charsWritten, localFormat.ToUpperInvariant(), localProvider));
+ Assert.Equal(localExpected.Length, charsWritten);
+ Assert.Equal(localExpected.ToUpperInvariant(), new string(actual));
+
+ // Lower format
+ actual = new char[localExpected.Length];
+ Assert.True(localI.TryFormat(actual.AsSpan(), out charsWritten, localFormat.ToLowerInvariant(), localProvider));
+ Assert.Equal(localExpected.Length, charsWritten);
+ Assert.Equal(localExpected.ToLowerInvariant(), new string(actual));
+ }
+ }
+ catch (Exception exc)
+ {
+ throw new Exception($"Failed on `{localI}`, `{localFormat}`, `{localProvider}`, `{localExpected}`. {exc}");
}
- }
- catch (Exception exc)
- {
- throw new Exception($"Failed on `{localI}`, `{localFormat}`, `{localProvider}`, `{localExpected}`. {exc}");
}
}
-
- return RemoteExecutor.SuccessExitCode;
}).Dispose();
}
}
[Fact]
public static void Test_ToString_NotNetFramework()
{
- RemoteExecutor.Invoke(() =>
+ RemoteExecutorForUap.Invoke(() =>
{
- CultureInfo.CurrentCulture = CultureInfo.InvariantCulture;
-
- foreach (var testdata in ToString_TestData_NotNetFramework())
+ using (new ThreadCultureChange(CultureInfo.InvariantCulture))
{
- ToString((double)testdata[0], (string)testdata[1], (IFormatProvider)testdata[2], (string)testdata[3]);
+ foreach (object[] testdata in ToString_TestData_NotNetFramework())
+ {
+ ToString((double)testdata[0], (string)testdata[1], (IFormatProvider)testdata[2], (string)testdata[3]);
+ }
}
- return RemoteExecutor.SuccessExitCode;
}).Dispose();
}
[Fact]
public static void TryFormat()
{
- RemoteExecutor.Invoke(() =>
+ RemoteExecutorForUap.Invoke(() =>
{
- CultureInfo.CurrentCulture = CultureInfo.InvariantCulture;
-
- foreach (var testdata in ToString_TestData_NotNetFramework())
+ using (new ThreadCultureChange(CultureInfo.InvariantCulture))
{
- double localI = (double)testdata[0];
- string localFormat = (string)testdata[1];
- IFormatProvider localProvider = (IFormatProvider)testdata[2];
- string localExpected = (string)testdata[3];
-
- try
+ foreach (var testdata in ToString_TestData_NotNetFramework())
{
- char[] actual;
- int charsWritten;
-
- // Just right
- actual = new char[localExpected.Length];
- Assert.True(localI.TryFormat(actual.AsSpan(), out charsWritten, localFormat, localProvider));
- Assert.Equal(localExpected.Length, charsWritten);
- Assert.Equal(localExpected, new string(actual));
-
- // Longer than needed
- actual = new char[localExpected.Length + 1];
- Assert.True(localI.TryFormat(actual.AsSpan(), out charsWritten, localFormat, localProvider));
- Assert.Equal(localExpected.Length, charsWritten);
- Assert.Equal(localExpected, new string(actual, 0, charsWritten));
-
- // Too short
- if (localExpected.Length > 0)
+ double localI = (double)testdata[0];
+ string localFormat = (string)testdata[1];
+ IFormatProvider localProvider = (IFormatProvider)testdata[2];
+ string localExpected = (string)testdata[3];
+
+ try
{
- actual = new char[localExpected.Length - 1];
- Assert.False(localI.TryFormat(actual.AsSpan(), out charsWritten, localFormat, localProvider));
- Assert.Equal(0, charsWritten);
+ char[] actual;
+ int charsWritten;
+
+ // Just right
+ actual = new char[localExpected.Length];
+ Assert.True(localI.TryFormat(actual.AsSpan(), out charsWritten, localFormat, localProvider));
+ Assert.Equal(localExpected.Length, charsWritten);
+ Assert.Equal(localExpected, new string(actual));
+
+ // Longer than needed
+ actual = new char[localExpected.Length + 1];
+ Assert.True(localI.TryFormat(actual.AsSpan(), out charsWritten, localFormat, localProvider));
+ Assert.Equal(localExpected.Length, charsWritten);
+ Assert.Equal(localExpected, new string(actual, 0, charsWritten));
+
+ // Too short
+ if (localExpected.Length > 0)
+ {
+ actual = new char[localExpected.Length - 1];
+ Assert.False(localI.TryFormat(actual.AsSpan(), out charsWritten, localFormat, localProvider));
+ Assert.Equal(0, charsWritten);
+ }
+ }
+ catch (Exception exc)
+ {
+ throw new Exception($"Failed on `{localI}`, `{localFormat}`, `{localProvider}`, `{localExpected}`. {exc}");
}
- }
- catch (Exception exc)
- {
- throw new Exception($"Failed on `{localI}`, `{localFormat}`, `{localProvider}`, `{localExpected}`. {exc}");
}
}
-
- return RemoteExecutor.SuccessExitCode;
}).Dispose();
}
[Fact]
public static void Invariant_DutchCulture_FormatsDoubleBasedOnInvariantCulture()
{
- RemoteExecutor.Invoke(
- () =>
+ RemoteExecutorForUap.Invoke(() =>
+ {
+ using (new ThreadCultureChange("nl"))
{
- CultureInfo.CurrentCulture = new CultureInfo("nl"); // would be 123,456 in Dutch
- double d = 123.456;
+ double d = 123.456; // would be 123,456 in Dutch
string expected = string.Format(CultureInfo.InvariantCulture, "Invariant culture is used {0}", d);
string actual = FormattableString.Invariant($"Invariant culture is used {d}");
Assert.Equal(expected, actual);
-
- return RemoteExecutor.SuccessExitCode;
- }).Dispose();
+ }
+ }).Dispose();
}
[Fact]
[Fact]
public static void IFormattableToString_UsesSuppliedFormatProvider()
{
- RemoteExecutor.Invoke(() =>
+ RemoteExecutorForUap.Invoke(() =>
{
- CultureInfo.CurrentCulture = new CultureInfo("nl"); // would be 123,456 in Dutch
- double d = 123.456;
- string expected = string.Format(CultureInfo.InvariantCulture, "Invariant culture is used {0}", d);
- string actual = ((IFormattable)((FormattableString)$"Invariant culture is used {d}")).ToString(null, CultureInfo.InvariantCulture);
- Assert.Equal(expected, actual);
-
- return RemoteExecutor.SuccessExitCode;
+ using (new ThreadCultureChange("nl"))
+ {
+ double d = 123.456; // would be 123,456 in Dutch
+ string expected = string.Format(CultureInfo.InvariantCulture, "Invariant culture is used {0}", d);
+ string actual = ((IFormattable)((FormattableString)$"Invariant culture is used {d}")).ToString(null, CultureInfo.InvariantCulture);
+ Assert.Equal(expected, actual);
+ }
}).Dispose();
}
[Fact]
public static void CurrentCulture_DutchCulture_FormatsDoubleBasedOnCurrentCulture()
{
- RemoteExecutor.Invoke(() =>
+ RemoteExecutorForUap.Invoke(() =>
{
var dutchCulture = new CultureInfo("nl");
- CultureInfo.CurrentCulture = dutchCulture;
- double d = 123.456;
- string expected = string.Format(dutchCulture, "Dutch decimal separator is comma {0}", d);
- string actual = FormattableString.CurrentCulture($"Dutch decimal separator is comma {d}");
- Assert.Equal(expected, actual);
-
- return RemoteExecutor.SuccessExitCode;
+ using (new ThreadCultureChange(dutchCulture))
+ {
+ double d = 123.456;
+ string expected = string.Format(dutchCulture, "Dutch decimal separator is comma {0}", d);
+ string actual = FormattableString.CurrentCulture($"Dutch decimal separator is comma {d}");
+ Assert.Equal(expected, actual);
+ }
}).Dispose();
}
}
GC.Collect(GC.MaxGeneration, GCCollectionMode.Forced, true, true);
Assert.Throws<ArgumentNullException>(() => GC.GetGeneration(weakref));
#endif
- return RemoteExecutor.SuccessExitCode;
}, options).Dispose();
}
RemoteExecutor.Invoke((approachString, timeoutString) =>
{
TestWait(bool.Parse(approachString), int.Parse(timeoutString));
- return RemoteExecutor.SuccessExitCode;
}, approach.ToString(), timeout.ToString(), options).Dispose();
}
RemoteExecutor.Invoke(() =>
{
Assert.Throws<InvalidOperationException>(() => GC.EndNoGCRegion());
- return RemoteExecutor.SuccessExitCode;
}, options).Dispose();
}
// at this point, the GC should have booted us out of the no GC region
// since we allocated too much.
Assert.Throws<InvalidOperationException>(() => GC.EndNoGCRegion());
- return RemoteExecutor.SuccessExitCode;
}, options).Dispose();
}
Assert.Throws<InvalidOperationException>(() => GC.TryStartNoGCRegion(NoGCRequestedBudget));
Assert.Throws<InvalidOperationException>(() => GC.EndNoGCRegion());
-
- return RemoteExecutor.SuccessExitCode;
}, options).Dispose();
}
Assert.Throws<InvalidOperationException>(() => GC.TryStartNoGCRegion(NoGCRequestedBudget, true));
Assert.Throws<InvalidOperationException>(() => GC.EndNoGCRegion());
-
- return RemoteExecutor.SuccessExitCode;
}, options).Dispose();
}
Assert.Throws<InvalidOperationException>(() => GC.TryStartNoGCRegion(NoGCRequestedBudget, NoGCRequestedBudget));
Assert.Throws<InvalidOperationException>(() => GC.EndNoGCRegion());
-
- return RemoteExecutor.SuccessExitCode;
}, options).Dispose();
}
Assert.Throws<InvalidOperationException>(() => GC.TryStartNoGCRegion(NoGCRequestedBudget, NoGCRequestedBudget, true));
Assert.Throws<InvalidOperationException>(() => GC.EndNoGCRegion());
-
- return RemoteExecutor.SuccessExitCode;
}, options).Dispose();
}
Assert.Throws<InvalidOperationException>(() => GCSettings.LatencyMode = GCLatencyMode.LowLatency);
GC.EndNoGCRegion();
-
- return RemoteExecutor.SuccessExitCode;
}, options).Dispose();
}
options.TimeOut = TimeoutMilliseconds;
RemoteExecutor.Invoke(() =>
{
-
Assert.True(GC.TryStartNoGCRegion(NoGCRequestedBudget));
Assert.Equal(GCLatencyMode.NoGCRegion, GCSettings.LatencyMode);
GC.EndNoGCRegion();
-
- return RemoteExecutor.SuccessExitCode;
-
}, options).Dispose();
}
Assert.True(GC.TryStartNoGCRegion(NoGCRequestedBudget, true));
Assert.Equal(GCLatencyMode.NoGCRegion, GCSettings.LatencyMode);
GC.EndNoGCRegion();
-
- return RemoteExecutor.SuccessExitCode;
-
}, options).Dispose();
}
Assert.True(GC.TryStartNoGCRegion(NoGCRequestedBudget, NoGCRequestedBudget));
Assert.Equal(GCLatencyMode.NoGCRegion, GCSettings.LatencyMode);
GC.EndNoGCRegion();
-
- return RemoteExecutor.SuccessExitCode;
-
}, options).Dispose();
}
Assert.True(GC.TryStartNoGCRegion(NoGCRequestedBudget, NoGCRequestedBudget, true));
Assert.Equal(GCLatencyMode.NoGCRegion, GCSettings.LatencyMode);
GC.EndNoGCRegion();
-
- return RemoteExecutor.SuccessExitCode;
-
}, options).Dispose();
}
RemoteExecutor.Invoke(sizeString =>
{
AssertExtensions.Throws<ArgumentOutOfRangeException>("totalSize", () => GC.TryStartNoGCRegion(long.Parse(sizeString)));
- return RemoteExecutor.SuccessExitCode;
}, size.ToString(), options).Dispose();
}
RemoteExecutor.Invoke(sizeString =>
{
AssertExtensions.Throws<ArgumentOutOfRangeException>("lohSize", () => GC.TryStartNoGCRegion(1024, long.Parse(sizeString)));
- return RemoteExecutor.SuccessExitCode;
}, size.ToString(), options).Dispose();
}
Assert.Contains("System.Runtime.Loader.DefaultAssemblyLoadContext", alc.ToString());
Assert.Contains(alc, AssemblyLoadContext.All);
Assert.Contains(asm, alc.Assemblies);
-
- return RemoteExecutor.SuccessExitCode;
}).Dispose();
}
Assert.Contains("System.Runtime.Loader.AssemblyLoadContext", alc.ToString());
Assert.Contains(alc, AssemblyLoadContext.All);
Assert.Contains(asm, alc.Assemblies);
-
- return RemoteExecutor.SuccessExitCode;
}).Dispose();
}
Assert.Contains("System.Reflection.Tests.TestAssemblyLoadContext", alc.ToString());
Assert.Contains(alc, AssemblyLoadContext.All);
Assert.Contains(asm, alc.Assemblies);
-
- return RemoteExecutor.SuccessExitCode;
}).Dispose();
}
Assert.NotNull(member);
Assert.False(member.IsCollectible);
-
- return RemoteExecutor.SuccessExitCode;
}, memberName).Dispose();
}
Assert.NotNull(member);
Assert.False(member.IsCollectible);
-
- return RemoteExecutor.SuccessExitCode;
}, memberName).Dispose();
}
Assert.NotNull(member);
Assert.True(member.IsCollectible);
-
- return RemoteExecutor.SuccessExitCode;
}, memberName).Dispose();
}
Assert.NotNull(member);
Assert.True(member.IsCollectible);
-
- return RemoteExecutor.SuccessExitCode;
}, memberName).Dispose();
}
Assert.NotNull(t1);
Assert.True(t1.IsCollectible);
-
- return RemoteExecutor.SuccessExitCode;
}).Dispose();
}
}
// We expect the launched process to crash; don't let it write the resulting AV message to the console.
var psi = new ProcessStartInfo() { RedirectStandardError = true, RedirectStandardOutput = true };
- using (RemoteInvokeHandle handle = RemoteExecutor.Invoke(() => { CauseAVInNative(); return RemoteExecutor.SuccessExitCode; }, new RemoteInvokeOptions { CheckExitCode = false, StartInfo = psi }))
+ using (RemoteInvokeHandle handle = RemoteExecutor.Invoke(() => CauseAVInNative(), new RemoteInvokeOptions { CheckExitCode = false, StartInfo = psi }))
{
Process p = handle.Process;
p.WaitForExit();
[Fact]
public static void Test_ToString_NotNetFramework()
{
- RemoteExecutor.Invoke(() =>
+ RemoteExecutorForUap.Invoke(() =>
{
- CultureInfo.CurrentCulture = CultureInfo.InvariantCulture;
-
- foreach (var testdata in ToString_TestData_NotNetFramework())
+ using (new ThreadCultureChange(CultureInfo.InvariantCulture))
{
- ToString((float)testdata[0], (string)testdata[1], (IFormatProvider)testdata[2], (string)testdata[3]);
+ foreach (object[] testdata in ToString_TestData_NotNetFramework())
+ {
+ ToString((float)testdata[0], (string)testdata[1], (IFormatProvider)testdata[2], (string)testdata[3]);
+ }
}
- return RemoteExecutor.SuccessExitCode;
}).Dispose();
}
[Fact]
public static void TryFormat()
{
- RemoteExecutor.Invoke(() =>
+ RemoteExecutorForUap.Invoke(() =>
{
- CultureInfo.CurrentCulture = CultureInfo.InvariantCulture;
-
- foreach (var testdata in ToString_TestData())
+ using (new ThreadCultureChange(CultureInfo.InvariantCulture))
{
- float localI = (float)testdata[0];
- string localFormat = (string)testdata[1];
- IFormatProvider localProvider = (IFormatProvider)testdata[2];
- string localExpected = (string)testdata[3];
-
- try
+ foreach (object[] testdata in ToString_TestData())
{
- char[] actual;
- int charsWritten;
-
- // Just right
- actual = new char[localExpected.Length];
- Assert.True(localI.TryFormat(actual.AsSpan(), out charsWritten, localFormat, localProvider));
- Assert.Equal(localExpected.Length, charsWritten);
- Assert.Equal(localExpected, new string(actual));
-
- // Longer than needed
- actual = new char[localExpected.Length + 1];
- Assert.True(localI.TryFormat(actual.AsSpan(), out charsWritten, localFormat, localProvider));
- Assert.Equal(localExpected.Length, charsWritten);
- Assert.Equal(localExpected, new string(actual, 0, charsWritten));
-
- // Too short
- if (localExpected.Length > 0)
+ float localI = (float)testdata[0];
+ string localFormat = (string)testdata[1];
+ IFormatProvider localProvider = (IFormatProvider)testdata[2];
+ string localExpected = (string)testdata[3];
+
+ try
{
- actual = new char[localExpected.Length - 1];
- Assert.False(localI.TryFormat(actual.AsSpan(), out charsWritten, localFormat, localProvider));
- Assert.Equal(0, charsWritten);
+ char[] actual;
+ int charsWritten;
+
+ // Just right
+ actual = new char[localExpected.Length];
+ Assert.True(localI.TryFormat(actual.AsSpan(), out charsWritten, localFormat, localProvider));
+ Assert.Equal(localExpected.Length, charsWritten);
+ Assert.Equal(localExpected, new string(actual));
+
+ // Longer than needed
+ actual = new char[localExpected.Length + 1];
+ Assert.True(localI.TryFormat(actual.AsSpan(), out charsWritten, localFormat, localProvider));
+ Assert.Equal(localExpected.Length, charsWritten);
+ Assert.Equal(localExpected, new string(actual, 0, charsWritten));
+
+ // Too short
+ if (localExpected.Length > 0)
+ {
+ actual = new char[localExpected.Length - 1];
+ Assert.False(localI.TryFormat(actual.AsSpan(), out charsWritten, localFormat, localProvider));
+ Assert.Equal(0, charsWritten);
+ }
+ }
+ catch (Exception exc)
+ {
+ throw new Exception($"Failed on `{localI}`, `{localFormat}`, `{localProvider}`, `{localExpected}`. {exc}");
}
- }
- catch (Exception exc)
- {
- throw new Exception($"Failed on `{localI}`, `{localFormat}`, `{localProvider}`, `{localExpected}`. {exc}");
}
}
-
- return RemoteExecutor.SuccessExitCode;
}).Dispose();
}
[Fact]
public static void Contains_StringComparison_TurkishI()
{
- string str = "\u0069\u0130";
- RemoteExecutor.Invoke((source) =>
+ RemoteExecutorForUap.Invoke(() =>
{
- CultureInfo.CurrentCulture = new CultureInfo("tr-TR");
+ const string Source = "\u0069\u0130";
- Assert.True(source.Contains("\u0069\u0069", StringComparison.CurrentCultureIgnoreCase));
- Assert.True(source.AsSpan().Contains("\u0069\u0069", StringComparison.CurrentCultureIgnoreCase));
-
- return RemoteExecutor.SuccessExitCode;
- }, str).Dispose();
-
- RemoteExecutor.Invoke((source) =>
- {
- CultureInfo.CurrentCulture = new CultureInfo("en-US");
-
- Assert.False(source.Contains("\u0069\u0069", StringComparison.CurrentCultureIgnoreCase));
- Assert.False(source.AsSpan().Contains("\u0069\u0069", StringComparison.CurrentCultureIgnoreCase));
+ using (new ThreadCultureChange("tr-TR"))
+ {
+ Assert.True(Source.Contains("\u0069\u0069", StringComparison.CurrentCultureIgnoreCase));
+ Assert.True(Source.AsSpan().Contains("\u0069\u0069", StringComparison.CurrentCultureIgnoreCase));
+ }
- return RemoteExecutor.SuccessExitCode;
- }, str).Dispose();
+ using (new ThreadCultureChange("en-US"))
+ {
+ Assert.False(Source.Contains("\u0069\u0069", StringComparison.CurrentCultureIgnoreCase));
+ Assert.False(Source.AsSpan().Contains("\u0069\u0069", StringComparison.CurrentCultureIgnoreCase));
+ }
+ }).Dispose();
}
[Fact]
[Fact]
public void Replace_StringComparison_TurkishI()
{
- string src = "\u0069\u0130";
-
- RemoteExecutor.Invoke((source) =>
+ RemoteExecutorForUap.Invoke(() =>
{
- CultureInfo.CurrentCulture = new CultureInfo("tr-TR");
-
- Assert.True("\u0069".Equals("\u0130", StringComparison.CurrentCultureIgnoreCase));
+ const string Source = "\u0069\u0130";
- Assert.Equal("a\u0130", source.Replace("\u0069", "a", StringComparison.CurrentCulture));
- Assert.Equal("aa", source.Replace("\u0069", "a", StringComparison.CurrentCultureIgnoreCase));
- Assert.Equal("\u0069a", source.Replace("\u0130", "a", StringComparison.CurrentCulture));
- Assert.Equal("aa", source.Replace("\u0130", "a", StringComparison.CurrentCultureIgnoreCase));
-
- return RemoteExecutor.SuccessExitCode;
- }, src).Dispose();
-
- RemoteExecutor.Invoke((source) =>
- {
- CultureInfo.CurrentCulture = new CultureInfo("en-US");
+ using (new ThreadCultureChange("tr-TR"))
+ {
+ Assert.True("\u0069".Equals("\u0130", StringComparison.CurrentCultureIgnoreCase));
- Assert.False("\u0069".Equals("\u0130", StringComparison.CurrentCultureIgnoreCase));
+ Assert.Equal("a\u0130", Source.Replace("\u0069", "a", StringComparison.CurrentCulture));
+ Assert.Equal("aa", Source.Replace("\u0069", "a", StringComparison.CurrentCultureIgnoreCase));
+ Assert.Equal("\u0069a", Source.Replace("\u0130", "a", StringComparison.CurrentCulture));
+ Assert.Equal("aa", Source.Replace("\u0130", "a", StringComparison.CurrentCultureIgnoreCase));
+ }
- Assert.Equal("a\u0130", source.Replace("\u0069", "a", StringComparison.CurrentCulture));
- Assert.Equal("a\u0130", source.Replace("\u0069", "a", StringComparison.CurrentCultureIgnoreCase));
- Assert.Equal("\u0069a", source.Replace("\u0130", "a", StringComparison.CurrentCulture));
- Assert.Equal("\u0069a", source.Replace("\u0130", "a", StringComparison.CurrentCultureIgnoreCase));
+ using (new ThreadCultureChange("en-US"))
+ {
+ Assert.False("\u0069".Equals("\u0130", StringComparison.CurrentCultureIgnoreCase));
- return RemoteExecutor.SuccessExitCode;
- }, src).Dispose();
+ Assert.Equal("a\u0130", Source.Replace("\u0069", "a", StringComparison.CurrentCulture));
+ Assert.Equal("a\u0130", Source.Replace("\u0069", "a", StringComparison.CurrentCultureIgnoreCase));
+ Assert.Equal("\u0069a", Source.Replace("\u0130", "a", StringComparison.CurrentCulture));
+ Assert.Equal("\u0069a", Source.Replace("\u0130", "a", StringComparison.CurrentCultureIgnoreCase));
+ }
+ }).Dispose();
}
public static IEnumerable<object[]> Replace_StringComparisonCulture_TestData()
[Fact]
public static void IndexOf_TurkishI_TurkishCulture_Char()
{
- RemoteExecutor.Invoke(() =>
+ RemoteExecutorForUap.Invoke(() =>
{
- CultureInfo.CurrentCulture = new CultureInfo("tr-TR");
-
- string s = "Turkish I \u0131s TROUBL\u0130NG!";
- char value = '\u0130';
- Assert.Equal(19, s.IndexOf(value));
- Assert.Equal(19, s.IndexOf(value, StringComparison.CurrentCulture));
- Assert.Equal(4, s.IndexOf(value, StringComparison.CurrentCultureIgnoreCase));
- Assert.Equal(19, s.IndexOf(value, StringComparison.Ordinal));
- Assert.Equal(19, s.IndexOf(value, StringComparison.OrdinalIgnoreCase));
-
- ReadOnlySpan<char> span = s.AsSpan();
- Assert.Equal(19, span.IndexOf(new char[] { value }, StringComparison.CurrentCulture));
- Assert.Equal(4, span.IndexOf(new char[] { value }, StringComparison.CurrentCultureIgnoreCase));
- Assert.Equal(19, span.IndexOf(new char[] { value }, StringComparison.Ordinal));
- Assert.Equal(19, span.IndexOf(new char[] { value }, StringComparison.OrdinalIgnoreCase));
-
- value = '\u0131';
- Assert.Equal(10, s.IndexOf(value, StringComparison.CurrentCulture));
- Assert.Equal(8, s.IndexOf(value, StringComparison.CurrentCultureIgnoreCase));
- Assert.Equal(10, s.IndexOf(value, StringComparison.Ordinal));
- Assert.Equal(10, s.IndexOf(value, StringComparison.OrdinalIgnoreCase));
-
- Assert.Equal(10, span.IndexOf(new char[] { value }, StringComparison.CurrentCulture));
- Assert.Equal(8, span.IndexOf(new char[] { value }, StringComparison.CurrentCultureIgnoreCase));
- Assert.Equal(10, span.IndexOf(new char[] { value }, StringComparison.Ordinal));
- Assert.Equal(10, span.IndexOf(new char[] { value }, StringComparison.OrdinalIgnoreCase));
-
- return RemoteExecutor.SuccessExitCode;
+ using (new ThreadCultureChange("tr-TR"))
+ {
+ string s = "Turkish I \u0131s TROUBL\u0130NG!";
+ char value = '\u0130';
+ Assert.Equal(19, s.IndexOf(value));
+ Assert.Equal(19, s.IndexOf(value, StringComparison.CurrentCulture));
+ Assert.Equal(4, s.IndexOf(value, StringComparison.CurrentCultureIgnoreCase));
+ Assert.Equal(19, s.IndexOf(value, StringComparison.Ordinal));
+ Assert.Equal(19, s.IndexOf(value, StringComparison.OrdinalIgnoreCase));
+
+ ReadOnlySpan<char> span = s.AsSpan();
+ Assert.Equal(19, span.IndexOf(new char[] { value }, StringComparison.CurrentCulture));
+ Assert.Equal(4, span.IndexOf(new char[] { value }, StringComparison.CurrentCultureIgnoreCase));
+ Assert.Equal(19, span.IndexOf(new char[] { value }, StringComparison.Ordinal));
+ Assert.Equal(19, span.IndexOf(new char[] { value }, StringComparison.OrdinalIgnoreCase));
+
+ value = '\u0131';
+ Assert.Equal(10, s.IndexOf(value, StringComparison.CurrentCulture));
+ Assert.Equal(8, s.IndexOf(value, StringComparison.CurrentCultureIgnoreCase));
+ Assert.Equal(10, s.IndexOf(value, StringComparison.Ordinal));
+ Assert.Equal(10, s.IndexOf(value, StringComparison.OrdinalIgnoreCase));
+
+ Assert.Equal(10, span.IndexOf(new char[] { value }, StringComparison.CurrentCulture));
+ Assert.Equal(8, span.IndexOf(new char[] { value }, StringComparison.CurrentCultureIgnoreCase));
+ Assert.Equal(10, span.IndexOf(new char[] { value }, StringComparison.Ordinal));
+ Assert.Equal(10, span.IndexOf(new char[] { value }, StringComparison.OrdinalIgnoreCase));
+ }
}).Dispose();
}
[Fact]
public static void IndexOf_TurkishI_InvariantCulture_Char()
{
- RemoteExecutor.Invoke(() =>
+ RemoteExecutorForUap.Invoke(() =>
{
- CultureInfo.CurrentCulture = CultureInfo.InvariantCulture;
-
- string s = "Turkish I \u0131s TROUBL\u0130NG!";
- char value = '\u0130';
-
- Assert.Equal(19, s.IndexOf(value));
- Assert.Equal(19, s.IndexOf(value, StringComparison.CurrentCulture));
- Assert.Equal(19, s.IndexOf(value, StringComparison.CurrentCultureIgnoreCase));
+ using (new ThreadCultureChange(CultureInfo.InvariantCulture))
+ {
+ string s = "Turkish I \u0131s TROUBL\u0130NG!";
+ char value = '\u0130';
- value = '\u0131';
- Assert.Equal(10, s.IndexOf(value, StringComparison.CurrentCulture));
- Assert.Equal(10, s.IndexOf(value, StringComparison.CurrentCultureIgnoreCase));
+ Assert.Equal(19, s.IndexOf(value));
+ Assert.Equal(19, s.IndexOf(value, StringComparison.CurrentCulture));
+ Assert.Equal(19, s.IndexOf(value, StringComparison.CurrentCultureIgnoreCase));
- return RemoteExecutor.SuccessExitCode;
+ value = '\u0131';
+ Assert.Equal(10, s.IndexOf(value, StringComparison.CurrentCulture));
+ Assert.Equal(10, s.IndexOf(value, StringComparison.CurrentCultureIgnoreCase));
+ }
}).Dispose();
}
[Fact]
public static void IndexOf_TurkishI_EnglishUSCulture_Char()
{
- RemoteExecutor.Invoke(() =>
+ RemoteExecutorForUap.Invoke(() =>
{
- CultureInfo.CurrentCulture = new CultureInfo("en-US");
-
- string s = "Turkish I \u0131s TROUBL\u0130NG!";
- char value = '\u0130';
-
- Assert.Equal(19, s.IndexOf(value));
- Assert.Equal(19, s.IndexOf(value, StringComparison.CurrentCulture));
- Assert.Equal(19, s.IndexOf(value, StringComparison.CurrentCultureIgnoreCase));
+ using (new ThreadCultureChange("en-US"))
+ {
+ string s = "Turkish I \u0131s TROUBL\u0130NG!";
+ char value = '\u0130';
- value = '\u0131';
- Assert.Equal(10, s.IndexOf(value, StringComparison.CurrentCulture));
- Assert.Equal(10, s.IndexOf(value, StringComparison.CurrentCultureIgnoreCase));
+ Assert.Equal(19, s.IndexOf(value));
+ Assert.Equal(19, s.IndexOf(value, StringComparison.CurrentCulture));
+ Assert.Equal(19, s.IndexOf(value, StringComparison.CurrentCultureIgnoreCase));
- return RemoteExecutor.SuccessExitCode;
+ value = '\u0131';
+ Assert.Equal(10, s.IndexOf(value, StringComparison.CurrentCulture));
+ Assert.Equal(10, s.IndexOf(value, StringComparison.CurrentCultureIgnoreCase));
+ }
}).Dispose();
}
[Fact]
public static void IndexOf_EquivalentDiacritics_EnglishUSCulture_Char()
{
- RemoteExecutor.Invoke(() =>
+ RemoteExecutorForUap.Invoke(() =>
{
string s = "Exhibit a\u0300\u00C0";
char value = '\u00C0';
- CultureInfo.CurrentCulture = new CultureInfo("en-US");
- Assert.Equal(10, s.IndexOf(value));
- Assert.Equal(10, s.IndexOf(value, StringComparison.CurrentCulture));
- Assert.Equal(8, s.IndexOf(value, StringComparison.CurrentCultureIgnoreCase));
- Assert.Equal(10, s.IndexOf(value, StringComparison.Ordinal));
- Assert.Equal(10, s.IndexOf(value, StringComparison.OrdinalIgnoreCase));
-
- return RemoteExecutor.SuccessExitCode;
+ using (new ThreadCultureChange("en-US"))
+ {
+ Assert.Equal(10, s.IndexOf(value));
+ Assert.Equal(10, s.IndexOf(value, StringComparison.CurrentCulture));
+ Assert.Equal(8, s.IndexOf(value, StringComparison.CurrentCultureIgnoreCase));
+ Assert.Equal(10, s.IndexOf(value, StringComparison.Ordinal));
+ Assert.Equal(10, s.IndexOf(value, StringComparison.OrdinalIgnoreCase));
+ }
}).Dispose();
}
[Fact]
public static void IndexOf_EquivalentDiacritics_InvariantCulture_Char()
{
- RemoteExecutor.Invoke(() =>
+ RemoteExecutorForUap.Invoke(() =>
{
string s = "Exhibit a\u0300\u00C0";
char value = '\u00C0';
- CultureInfo.CurrentCulture = CultureInfo.InvariantCulture;
- Assert.Equal(10, s.IndexOf(value));
- Assert.Equal(10, s.IndexOf(value, StringComparison.CurrentCulture));
- Assert.Equal(8, s.IndexOf(value, StringComparison.CurrentCultureIgnoreCase));
-
- return RemoteExecutor.SuccessExitCode;
+ using (new ThreadCultureChange(CultureInfo.InvariantCulture))
+ {
+ Assert.Equal(10, s.IndexOf(value));
+ Assert.Equal(10, s.IndexOf(value, StringComparison.CurrentCulture));
+ Assert.Equal(8, s.IndexOf(value, StringComparison.CurrentCultureIgnoreCase));
+ }
}).Dispose();
}
[Fact]
public static void IndexOf_CyrillicE_EnglishUSCulture_Char()
{
- RemoteExecutor.Invoke(() =>
+ RemoteExecutorForUap.Invoke(() =>
{
string s = "Foo\u0400Bar";
char value = '\u0400';
- CultureInfo.CurrentCulture = new CultureInfo("en-US");
- Assert.Equal(3, s.IndexOf(value));
- Assert.Equal(3, s.IndexOf(value, StringComparison.CurrentCulture));
- Assert.Equal(3, s.IndexOf(value, StringComparison.CurrentCultureIgnoreCase));
- Assert.Equal(3, s.IndexOf(value, StringComparison.Ordinal));
- Assert.Equal(3, s.IndexOf(value, StringComparison.OrdinalIgnoreCase));
-
- return RemoteExecutor.SuccessExitCode;
+ using (new ThreadCultureChange("en-US"))
+ {
+ Assert.Equal(3, s.IndexOf(value));
+ Assert.Equal(3, s.IndexOf(value, StringComparison.CurrentCulture));
+ Assert.Equal(3, s.IndexOf(value, StringComparison.CurrentCultureIgnoreCase));
+ Assert.Equal(3, s.IndexOf(value, StringComparison.Ordinal));
+ Assert.Equal(3, s.IndexOf(value, StringComparison.OrdinalIgnoreCase));
+ }
}).Dispose();
}
[Fact]
public static void IndexOf_CyrillicE_InvariantCulture_Char()
{
- RemoteExecutor.Invoke(() =>
+ RemoteExecutorForUap.Invoke(() =>
{
string s = "Foo\u0400Bar";
char value = '\u0400';
- CultureInfo.CurrentCulture = CultureInfo.InvariantCulture;
- Assert.Equal(3, s.IndexOf(value));
- Assert.Equal(3, s.IndexOf(value, StringComparison.CurrentCulture));
- Assert.Equal(3, s.IndexOf(value, StringComparison.CurrentCultureIgnoreCase));
-
- return RemoteExecutor.SuccessExitCode;
+ using (new ThreadCultureChange(CultureInfo.InvariantCulture))
+ {
+ Assert.Equal(3, s.IndexOf(value));
+ Assert.Equal(3, s.IndexOf(value, StringComparison.CurrentCulture));
+ Assert.Equal(3, s.IndexOf(value, StringComparison.CurrentCultureIgnoreCase));
+ }
}).Dispose();
}
[Fact]
public static void Test_Append_Decimal()
{
- RemoteExecutor.Invoke(() =>
+ RemoteExecutorForUap.Invoke(() =>
{
- CultureInfo.CurrentCulture = CultureInfo.InvariantCulture;
-
- foreach (var testdata in Append_Decimal_TestData())
+ using (new ThreadCultureChange(CultureInfo.InvariantCulture))
{
- Append_Decimal((string)testdata[0], (double)testdata[1], (string)testdata[2]);
+ foreach (var testdata in Append_Decimal_TestData())
+ {
+ Append_Decimal((string)testdata[0], (double)testdata[1], (string)testdata[2]);
+ }
}
- return RemoteExecutor.SuccessExitCode;
}).Dispose();
}
[Fact]
public static void Test_Append_Double()
{
- RemoteExecutor.Invoke(() =>
+ RemoteExecutorForUap.Invoke(() =>
{
- CultureInfo.CurrentCulture = CultureInfo.InvariantCulture;
- foreach (var testdata in Append_Double_TestData())
+ using (new ThreadCultureChange(CultureInfo.InvariantCulture))
{
- Append_Double((string)testdata[0], (double)testdata[1], (string)testdata[2]);
+ foreach (var testdata in Append_Double_TestData())
+ {
+ Append_Double((string)testdata[0], (double)testdata[1], (string)testdata[2]);
+ }
}
- return RemoteExecutor.SuccessExitCode;
}).Dispose();
}
[Fact]
public static void Test_Append_Float()
{
- RemoteExecutor.Invoke(() =>
+ RemoteExecutorForUap.Invoke(() =>
{
- CultureInfo.CurrentCulture = CultureInfo.InvariantCulture;
- foreach (var testdata in Append_Float_TestData())
+ using (new ThreadCultureChange(CultureInfo.InvariantCulture))
{
- Append_Float((string)testdata[0], (float)testdata[1], (string)testdata[2]);
+ foreach (var testdata in Append_Float_TestData())
+ {
+ Append_Float((string)testdata[0], (float)testdata[1], (string)testdata[2]);
+ }
}
- return RemoteExecutor.SuccessExitCode;
}).Dispose();
}
[Fact]
public static void Test_Insert_Float()
{
- RemoteExecutor.Invoke(() =>
+ RemoteExecutorForUap.Invoke(() =>
{
- CultureInfo.CurrentCulture = CultureInfo.InvariantCulture;
- foreach (var testdata in Insert_Float_TestData())
+ using (new ThreadCultureChange(CultureInfo.InvariantCulture))
{
- Insert_Float((string)testdata[0], (int)testdata[1], (float)testdata[2], (string)testdata[3]);
+ foreach (var testdata in Insert_Float_TestData())
+ {
+ Insert_Float((string)testdata[0], (int)testdata[1], (float)testdata[2], (string)testdata[3]);
+ }
}
- return RemoteExecutor.SuccessExitCode;
}).Dispose();
}
[Fact]
public static void Test_Insert_Double()
{
- RemoteExecutor.Invoke(() =>
+ RemoteExecutorForUap.Invoke(() =>
{
- CultureInfo.CurrentCulture = CultureInfo.InvariantCulture;
- foreach (var testdata in Insert_Double_TestData())
+ using (new ThreadCultureChange(CultureInfo.InvariantCulture))
{
- Insert_Double((string)testdata[0], (int)testdata[1], (double)testdata[2], (string)testdata[3]);
+ foreach (var testdata in Insert_Double_TestData())
+ {
+ Insert_Double((string)testdata[0], (int)testdata[1], (double)testdata[2], (string)testdata[3]);
+ }
}
- return RemoteExecutor.SuccessExitCode;
}).Dispose();
}
[Fact]
public static void Test_Insert_Decimal()
{
- RemoteExecutor.Invoke(() =>
+ RemoteExecutorForUap.Invoke(() =>
{
- CultureInfo.CurrentCulture = CultureInfo.InvariantCulture;
- foreach (var testdata in Test_Insert_Decimal_TestData())
+ using (new ThreadCultureChange(CultureInfo.InvariantCulture))
{
- Insert_Decimal((string)testdata[0], (int)testdata[1], (double)testdata[2], (string)testdata[3]);
+ foreach (var testdata in Test_Insert_Decimal_TestData())
+ {
+ Insert_Decimal((string)testdata[0], (int)testdata[1], (double)testdata[2], (string)testdata[3]);
+ }
}
- return RemoteExecutor.SuccessExitCode;
}).Dispose();
}
Assert.NotNull(t2);
Assert.Equal(t1, t2);
-
- return RemoteExecutor.SuccessExitCode;
}, options).Dispose();
}
{
Assert.Throws<TypeLoadException>(() => Type.GetType(marshalledTypeName, assemblyloader, typeloader, true));
Assert.Null(Type.GetType(marshalledTypeName, assemblyloader, typeloader, false));
-
- return RemoteExecutor.SuccessExitCode;
}, typeName).Dispose();
}
);
Assert.Null(t2);
-
- return RemoteExecutor.SuccessExitCode;
}, options).Dispose();
}
// Check nr of certificates in store.
Assert.Equal(2, store.Certificates.Count);
}
- return RemoteExecutor.SuccessExitCode;
}, new RemoteInvokeOptions { StartInfo = psi }).Dispose();
}
using System.Diagnostics;
using System.Globalization;
+using System.Tests;
using Microsoft.DotNet.RemoteExecutor;
using Xunit;
[Fact]
public void GetEncoding_EncodingName()
{
- // Workaround issue: UWP culture is process wide
- RemoteExecutor.Invoke(() =>
+ RemoteExecutorForUap.Invoke(() =>
{
- CultureInfo.CurrentUICulture = CultureInfo.InvariantCulture;
-
- foreach (var map in s_mapping)
+ using (new ThreadCultureChange(CultureInfo.InvariantCulture))
{
- Encoding encoding = Encoding.GetEncoding(map.Name);
+ foreach (CodePageMapping map in s_mapping)
+ {
+ Encoding encoding = Encoding.GetEncoding(map.Name);
- string name = encoding.EncodingName;
+ string name = encoding.EncodingName;
- Assert.NotNull(name);
- Assert.NotEqual(string.Empty, name);
+ Assert.NotNull(name);
+ Assert.NotEqual(string.Empty, name);
- Assert.All(name, ch => Assert.InRange(ch, 0, 127));
+ Assert.All(name, ch => Assert.InRange(ch, 0, 127));
+ }
}
}).Dispose();
}
Assert.True(Regex.IsMatch("1", "1"));
Assert.True(Regex.IsMatch("2", "2")); // previous removed from cache
Assert.True(GetCachedItemsNum() == 1);
- return RemoteExecutor.SuccessExitCode;
}).Dispose();
}
Assert.True(GetCachedItemsNum() == 1);
Regex.CacheSize = 0; // clear
Assert.True(GetCachedItemsNum() == 0);
- return RemoteExecutor.SuccessExitCode;
}).Dispose();
}
Assert.True(GetCachedItemsNum() == 3);
Regex.CacheSize = 1; // only 1 stays
Assert.True(GetCachedItemsNum() == 1);
- return RemoteExecutor.SuccessExitCode;
}).Dispose();
}
CultureInfo.CurrentCulture = CultureInfo.CurrentCulture.Equals(CultureInfo.GetCultureInfo("de-DE")) ? CultureInfo.InvariantCulture : CultureInfo.GetCultureInfo("de-DE");
Assert.True(Regex.IsMatch("1", "1", RegexOptions.Multiline));
Assert.True(GetCachedItemsNum() == 3);
- return RemoteExecutor.SuccessExitCode;
}).Dispose();
}
Assert.True(GetCachedItemsNum() == i + 1);
}
}
+
void Remove(int n)
{
for (int i = 0; i < original; i++)
Assert.True(GetCachedItemsNum() == Regex.CacheSize);
}
}
- return RemoteExecutor.SuccessExitCode;
}).Dispose();
}
{
AppDomain.CurrentDomain.SetData(RegexHelpers.DefaultMatchTimeout_ConfigKeyName, true);
Assert.Throws<TypeInitializationException>(() => Regex.InfiniteMatchTimeout);
-
- return RemoteExecutor.SuccessExitCode;
}).Dispose();
}
{
AppDomain.CurrentDomain.SetData(RegexHelpers.DefaultMatchTimeout_ConfigKeyName, TimeSpan.Zero);
Assert.Throws<TypeInitializationException>(() => Regex.InfiniteMatchTimeout);
-
- return RemoteExecutor.SuccessExitCode;
}).Dispose();
}
}
using System.Diagnostics;
using System.Globalization;
using System.Linq;
+using System.Tests;
using Microsoft.DotNet.RemoteExecutor;
using Xunit;
[Fact]
public void GroupsEnUS()
{
- RemoteExecutor.Invoke(() => {
- CultureInfo.CurrentCulture = s_enUSCulture;
- foreach (object[] testCase in Groups_CustomCulture_TestData_enUS())
+ RemoteExecutorForUap.Invoke(() => {
+ using (new ThreadCultureChange(s_enUSCulture))
{
- GroupsTest(testCase);
+ foreach (object[] testCase in Groups_CustomCulture_TestData_enUS())
+ {
+ GroupsTest(testCase);
+ }
}
-
- return RemoteExecutor.SuccessExitCode;
}).Dispose();
}
[Fact]
public void GroupsCzech()
{
- RemoteExecutor.Invoke(() => {
- CultureInfo.CurrentCulture = s_czechCulture;
- foreach (object[] testCase in Groups_CustomCulture_TestData_Czech())
+ RemoteExecutorForUap.Invoke(() => {
+ using (new ThreadCultureChange(s_czechCulture))
{
- GroupsTest(testCase);
+ foreach (object[] testCase in Groups_CustomCulture_TestData_Czech())
+ {
+ GroupsTest(testCase);
+ }
}
-
- return RemoteExecutor.SuccessExitCode;
}).Dispose();
}
[Fact]
public void GroupsDanish()
{
- RemoteExecutor.Invoke(() => {
- CultureInfo.CurrentCulture = s_danishCulture;
- foreach (object[] testCase in Groups_CustomCulture_TestData_Danish())
+ RemoteExecutorForUap.Invoke(() => {
+ using (new ThreadCultureChange(s_danishCulture))
{
- GroupsTest(testCase);
+ foreach (object[] testCase in Groups_CustomCulture_TestData_Danish())
+ {
+ GroupsTest(testCase);
+ }
}
-
- return RemoteExecutor.SuccessExitCode;
}).Dispose();
}
[Fact]
public void GroupsTurkish()
{
- RemoteExecutor.Invoke(() => {
- CultureInfo.CurrentCulture = s_turkishCulture;
- foreach (object[] testCase in Groups_CustomCulture_TestData_Turkish())
+ RemoteExecutorForUap.Invoke(() => {
+ using (new ThreadCultureChange(s_turkishCulture))
{
- GroupsTest(testCase);
+ foreach (object[] testCase in Groups_CustomCulture_TestData_Turkish())
+ {
+ GroupsTest(testCase);
+ }
}
-
- return RemoteExecutor.SuccessExitCode;
}).Dispose();
}
[Fact]
public void GroupsAzeriLatin()
{
- RemoteExecutor.Invoke(() => {
- CultureInfo.CurrentCulture = s_azeriLatinCulture;
- foreach (object[] testCase in Groups_CustomCulture_TestData_AzeriLatin())
+ RemoteExecutorForUap.Invoke(() => {
+ using (new ThreadCultureChange(s_azeriLatinCulture))
{
- GroupsTest(testCase);
+ foreach (object[] testCase in Groups_CustomCulture_TestData_AzeriLatin())
+ {
+ GroupsTest(testCase);
+ }
}
-
- return RemoteExecutor.SuccessExitCode;
}).Dispose();
}
[Fact]
public void GroupsBasic()
{
- RemoteExecutor.Invoke(() => {
- CultureInfo.CurrentCulture = GetDefaultCultureForTests();
- foreach (object[] testCase in Groups_Basic_TestData())
+ RemoteExecutorForUap.Invoke(() => {
+ using (new ThreadCultureChange(GetDefaultCultureForTests()))
{
- GroupsTest(testCase);
+ foreach (object[] testCase in Groups_Basic_TestData())
+ {
+ GroupsTest(testCase);
+ }
}
-
- return RemoteExecutor.SuccessExitCode;
}).Dispose();
}
using System.Diagnostics;
using System.Globalization;
using System.Linq;
+using System.Tests;
using Microsoft.DotNet.RemoteExecutor;
using Xunit;
AppDomain.CurrentDomain.SetData(RegexHelpers.DefaultMatchTimeout_ConfigKeyName, TimeSpan.FromMilliseconds(100));
Assert.Throws<RegexMatchTimeoutException>(() => new Regex(Pattern).Match(input));
-
- return RemoteExecutor.SuccessExitCode;
}).Dispose();
}
[Fact]
public void Match_SpecialUnicodeCharacters_enUS()
{
- RemoteExecutor.Invoke(() =>
+ RemoteExecutorForUap.Invoke(() =>
{
- CultureInfo.CurrentCulture = new CultureInfo("en-US");
- Match("\u0131", "\u0049", RegexOptions.IgnoreCase, 0, 1, false, string.Empty);
- Match("\u0131", "\u0069", RegexOptions.IgnoreCase, 0, 1, false, string.Empty);
-
- return RemoteExecutor.SuccessExitCode;
+ using (new ThreadCultureChange("en-US"))
+ {
+ Match("\u0131", "\u0049", RegexOptions.IgnoreCase, 0, 1, false, string.Empty);
+ Match("\u0131", "\u0069", RegexOptions.IgnoreCase, 0, 1, false, string.Empty);
+ }
}).Dispose();
}
[Fact]
public void Match_SpecialUnicodeCharacters_Invariant()
{
- RemoteExecutor.Invoke(() =>
+ RemoteExecutorForUap.Invoke(() =>
{
- CultureInfo.CurrentCulture = CultureInfo.InvariantCulture;
- Match("\u0131", "\u0049", RegexOptions.IgnoreCase, 0, 1, false, string.Empty);
- Match("\u0131", "\u0069", RegexOptions.IgnoreCase, 0, 1, false, string.Empty);
- Match("\u0130", "\u0049", RegexOptions.IgnoreCase, 0, 1, false, string.Empty);
- Match("\u0130", "\u0069", RegexOptions.IgnoreCase, 0, 1, false, string.Empty);
-
- return RemoteExecutor.SuccessExitCode;
+ using (new ThreadCultureChange(CultureInfo.InvariantCulture))
+ {
+ Match("\u0131", "\u0049", RegexOptions.IgnoreCase, 0, 1, false, string.Empty);
+ Match("\u0131", "\u0069", RegexOptions.IgnoreCase, 0, 1, false, string.Empty);
+ Match("\u0130", "\u0049", RegexOptions.IgnoreCase, 0, 1, false, string.Empty);
+ Match("\u0130", "\u0069", RegexOptions.IgnoreCase, 0, 1, false, string.Empty);
+ }
}).Dispose();
}
// See the LICENSE file in the project root for more information.
using System.Globalization;
+using System.Tests;
using Microsoft.DotNet.RemoteExecutor;
using Xunit;
[Fact]
public void TurkishI_Is_Differently_LowerUpperCased_In_Turkish_Culture()
{
- RemoteExecutor.Invoke(() =>
+ RemoteExecutorForUap.Invoke(() =>
{
var turkish = new CultureInfo("tr-TR");
string input = "I\u0131\u0130i";
/// <returns></returns>
Regex[] Create(string input, CultureInfo info, RegexOptions additional)
{
- CultureInfo current = CultureInfo.CurrentCulture;
- try
+ using (new ThreadCultureChange(info))
{
- CultureInfo.CurrentCulture = info;
-
// When RegexOptions.IgnoreCase is supplied the current thread culture is used to lowercase the input string.
// Except if RegexOptions.CultureInvariant is additionally added locale dependent effects on the generated code or state machine may happen.
- var localizedRegex = new Regex[] { new Regex(input, additional), new Regex(input, RegexOptions.Compiled | additional) };
- return localizedRegex;
- }
- finally
- {
- CultureInfo.CurrentCulture = current;
+ return new Regex[]
+ {
+ new Regex(input, additional),
+ new Regex(input, RegexOptions.Compiled | additional)
+ };
}
}
}
Assert.Equal(expected: 0, actual: ce.CurrentCount);
});
}
-
- return RemoteExecutor.SuccessExitCode;
}).Dispose();
}
Assert.Contains("42", description);
Assert.Contains("stored data", description);
}
-
- return RemoteExecutor.SuccessExitCode;
}).Dispose();
}
}
}
- private static int PingPong_OtherProcess(string modeName, string inboundName, string outboundName)
+ private static void PingPong_OtherProcess(string modeName, string inboundName, string outboundName)
{
EventResetMode mode = (EventResetMode)Enum.Parse(typeof(EventResetMode), modeName);
outbound.Set();
}
}
-
- return RemoteExecutor.SuccessExitCode;
}
public static TheoryData<string> GetValidNames()
string mutexName = prefix + Guid.NewGuid().ToString("N");
string fileName = GetTestFilePath();
- Func<string, string, int> otherProcess = (m, f) =>
+ Action<string, string> otherProcess = (m, f) =>
{
using (var mutex = Mutex.OpenExisting(m))
{
IncrementValueInFileNTimes(mutex, f, 10);
}
- return RemoteExecutor.SuccessExitCode;
};
using (var mutex = new Mutex(false, mutexName))
// Create the two semaphores and the other process with which to synchronize
using (var inbound = new Semaphore(1, 1, inboundName))
using (var outbound = new Semaphore(0, 1, outboundName))
- using (var remote = RemoteExecutor.Invoke(new Func<string, string, int>(PingPong_OtherProcess), outboundName, inboundName))
+ using (var remote = RemoteExecutor.Invoke(new Action<string, string>(PingPong_OtherProcess), outboundName, inboundName))
{
// Repeatedly wait for count in one semaphore and then release count into the other
for (int i = 0; i < 10; i++)
}
}
- private static int PingPong_OtherProcess(string inboundName, string outboundName)
+ private static void PingPong_OtherProcess(string inboundName, string outboundName)
{
// Open the two semaphores
using (var inbound = Semaphore.OpenExisting(inboundName))
outbound.Release();
}
}
-
- return RemoteExecutor.SuccessExitCode;
}
public static TheoryData<string> GetValidNames()
{
Func<string, string, string, string, string, int> action = (str1, str2, comparison, culture, shouldCompareAsEqual) =>
{
- if (culture != null)
+ using (new ThreadCultureChange(culture))
{
- CultureInfo.CurrentCulture = new CultureInfo(culture);
- }
-
- using BoundedUtf8Span boundedSpan1 = new BoundedUtf8Span(str1);
- using BoundedUtf8Span boundedSpan2 = new BoundedUtf8Span(str2);
+ using BoundedUtf8Span boundedSpan1 = new BoundedUtf8Span(str1);
+ using BoundedUtf8Span boundedSpan2 = new BoundedUtf8Span(str2);
- Utf8Span span1 = boundedSpan1.Span;
- Utf8Span span2 = boundedSpan2.Span;
+ Utf8Span span1 = boundedSpan1.Span;
+ Utf8Span span2 = boundedSpan2.Span;
- StringComparison comparisonType = Enum.Parse<StringComparison>(comparison);
- bool expected = bool.Parse(shouldCompareAsEqual);
+ StringComparison comparisonType = Enum.Parse<StringComparison>(comparison);
+ bool expected = bool.Parse(shouldCompareAsEqual);
- Assert.Equal(expected, span1.Equals(span2, comparisonType));
- Assert.Equal(expected, span2.Equals(span1, comparisonType));
- Assert.Equal(expected, Utf8Span.Equals(span1, span2, comparisonType));
- Assert.Equal(expected, Utf8Span.Equals(span2, span1, comparisonType));
+ Assert.Equal(expected, span1.Equals(span2, comparisonType));
+ Assert.Equal(expected, span2.Equals(span1, comparisonType));
+ Assert.Equal(expected, Utf8Span.Equals(span1, span2, comparisonType));
+ Assert.Equal(expected, Utf8Span.Equals(span2, span1, comparisonType));
+ }
return RemoteExecutor.SuccessExitCode;
};
- if (culture != null)
+ if (culture != null && PlatformDetection.IsUap) // need to apply a culture to the current thread
{
- // need to apply a culture to the current thread
RemoteExecutor.Invoke(action, str1, str2, comparison.ToString(), culture, shouldCompareAsEqual.ToString()).Dispose();
}
else