diff options
Diffstat (limited to 'src/mscorlib/src/System/Globalization')
41 files changed, 765 insertions, 1536 deletions
diff --git a/src/mscorlib/src/System/Globalization/Calendar.cs b/src/mscorlib/src/System/Globalization/Calendar.cs index d6dfdc9f4b..d0460386b6 100644 --- a/src/mscorlib/src/System/Globalization/Calendar.cs +++ b/src/mscorlib/src/System/Globalization/Calendar.cs @@ -7,6 +7,7 @@ namespace System.Globalization { using System.Runtime.CompilerServices; using System.Globalization; using System.Runtime.Versioning; + using System.Diagnostics; using System.Diagnostics.Contracts; // This abstract class represents a calendar. A calendar reckons time in @@ -192,7 +193,7 @@ namespace System.Globalization { [System.Runtime.InteropServices.ComVisible(false)] public static Calendar ReadOnly(Calendar calendar) { - if (calendar == null) { throw new ArgumentNullException("calendar"); } + if (calendar == null) { throw new ArgumentNullException(nameof(calendar)); } Contract.EndContractBlock(); if (calendar.IsReadOnly) { return (calendar); } @@ -229,7 +230,7 @@ namespace System.Globalization { get { // The following code assumes that the current era value can not be -1. if (m_currentEraValue == -1) { - Contract.Assert(BaseCalendarID > 0, "[Calendar.CurrentEraValue] Expected ID > 0"); + Debug.Assert(BaseCalendarID > 0, "[Calendar.CurrentEraValue] Expected ID > 0"); m_currentEraValue = CalendarData.GetCalendarData(BaseCalendarID).iCurrentEra; } return (m_currentEraValue); @@ -262,7 +263,7 @@ namespace System.Globalization { double tempMillis = (value * scale + (value >= 0 ? 0.5 : -0.5)); if (!((tempMillis > -(double)MaxMillis) && (tempMillis < (double)MaxMillis))) { - throw new ArgumentOutOfRangeException("value", Environment.GetResourceString("ArgumentOutOfRange_AddValue")); + throw new ArgumentOutOfRangeException(nameof(value), Environment.GetResourceString("ArgumentOutOfRange_AddValue")); } long millis = (long)tempMillis; @@ -529,7 +530,7 @@ namespace System.Globalization { // this value can be less than 0. It's fine since we are making it positive again in calculating offset. int dayForJan1 = (int)GetDayOfWeek(time) - (dayOfYear % 7); int offset = (dayForJan1 - firstDayOfWeek + 14) % 7; - Contract.Assert(offset >= 0, "Calendar.GetFirstDayWeekOfYear(): offset >= 0"); + Debug.Assert(offset >= 0, "Calendar.GetFirstDayWeekOfYear(): offset >= 0"); return ((dayOfYear + offset) / 7 + 1); } @@ -651,7 +652,7 @@ namespace System.Globalization { { if ((int)firstDayOfWeek < 0 || (int)firstDayOfWeek > 6) { throw new ArgumentOutOfRangeException( - "firstDayOfWeek", Environment.GetResourceString("ArgumentOutOfRange_Range", + nameof(firstDayOfWeek), Environment.GetResourceString("ArgumentOutOfRange_Range", DayOfWeek.Sunday, DayOfWeek.Saturday)); } Contract.EndContractBlock(); @@ -664,7 +665,7 @@ namespace System.Globalization { return (GetWeekOfYearFullDays(time, (int)firstDayOfWeek, 4)); } throw new ArgumentOutOfRangeException( - "rule", Environment.GetResourceString("ArgumentOutOfRange_Range", + nameof(rule), Environment.GetResourceString("ArgumentOutOfRange_Range", CalendarWeekRule.FirstDay, CalendarWeekRule.FirstFourDayWeek)); } @@ -815,7 +816,7 @@ namespace System.Globalization { public virtual int ToFourDigitYear(int year) { if (year < 0) { - throw new ArgumentOutOfRangeException("year", + throw new ArgumentOutOfRangeException(nameof(year), Environment.GetResourceString("ArgumentOutOfRange_NeedNonNegNum")); } Contract.EndContractBlock(); @@ -835,7 +836,7 @@ namespace System.Globalization { { if (millisecond < 0 || millisecond >= MillisPerSecond) { throw new ArgumentOutOfRangeException( - "millisecond", + nameof(millisecond), String.Format( CultureInfo.InvariantCulture, Environment.GetResourceString("ArgumentOutOfRange_Range"), 0, MillisPerSecond - 1)); @@ -845,7 +846,6 @@ namespace System.Globalization { throw new ArgumentOutOfRangeException(null, Environment.GetResourceString("ArgumentOutOfRange_BadHourMinuteSecond")); } - [System.Security.SecuritySafeCritical] // auto-generated internal static int GetSystemTwoDigitYearSetting(int CalID, int defaultYearValue) { // Call nativeGetTwoDigitYearMax diff --git a/src/mscorlib/src/System/Globalization/CalendarData.cs b/src/mscorlib/src/System/Globalization/CalendarData.cs index 8c187f0033..6f583fbcbc 100644 --- a/src/mscorlib/src/System/Globalization/CalendarData.cs +++ b/src/mscorlib/src/System/Globalization/CalendarData.cs @@ -9,6 +9,7 @@ namespace System.Globalization using System.Runtime.InteropServices; using System.Runtime.CompilerServices; using System.Runtime.Versioning; + using System.Diagnostics; using System.Diagnostics.Contracts; // // List of calendar data @@ -121,7 +122,7 @@ namespace System.Globalization this.bUseUserOverrides = bUseUserOverrides; if (!nativeGetCalendarData(this, localeName, calendarId)) { - Contract.Assert(false, "[CalendarData] nativeGetCalendarData call isn't expected to fail for calendar " + calendarId + " locale " +localeName); + Debug.Assert(false, "[CalendarData] nativeGetCalendarData call isn't expected to fail for calendar " + calendarId + " locale " +localeName); // Something failed, try invariant for missing parts // This is really not good, but we don't want the callers to crash. @@ -436,17 +437,14 @@ namespace System.Globalization // Get native two digit year max - [System.Security.SecurityCritical] // auto-generated [MethodImplAttribute(MethodImplOptions.InternalCall)] internal static extern int nativeGetTwoDigitYearMax(int calID); // Call native side to load our calendar data - [System.Security.SecuritySafeCritical] // auto-generated [MethodImplAttribute(MethodImplOptions.InternalCall)] private static extern bool nativeGetCalendarData(CalendarData data, String localeName, int calendar); // Call native side to figure out which calendars are allowed - [System.Security.SecuritySafeCritical] // auto-generated [MethodImplAttribute(MethodImplOptions.InternalCall)] internal static extern int nativeGetCalendars(String localeName, bool useUserOverride, [In, Out] int[] calendars); diff --git a/src/mscorlib/src/System/Globalization/CalendricalCalculationsHelper.cs b/src/mscorlib/src/System/Globalization/CalendricalCalculationsHelper.cs index 7084511ce9..1113cd58ba 100644 --- a/src/mscorlib/src/System/Globalization/CalendricalCalculationsHelper.cs +++ b/src/mscorlib/src/System/Globalization/CalendricalCalculationsHelper.cs @@ -5,6 +5,7 @@ namespace System.Globalization { using System; + using System.Diagnostics; using System.Diagnostics.Contracts; internal class CalendricalCalculationsHelper @@ -153,7 +154,7 @@ namespace System.Globalization // the following formulas defines a polynomial function which gives us the amount that the earth is slowing down for specific year ranges static double DefaultEphemerisCorrection(int gregorianYear) { - Contract.Assert(gregorianYear < 1620 || 2020 <= gregorianYear); + Debug.Assert(gregorianYear < 1620 || 2020 <= gregorianYear); long january1stOfYear = GetNumberOfDays(new DateTime(gregorianYear, 1, 1)); double daysSinceStartOf1810 = january1stOfYear - StartOf1810; double x = TwelveHours + daysSinceStartOf1810; @@ -162,34 +163,34 @@ namespace System.Globalization static double EphemerisCorrection1988to2019(int gregorianYear) { - Contract.Assert(1988 <= gregorianYear && gregorianYear <= 2019); + Debug.Assert(1988 <= gregorianYear && gregorianYear <= 2019); return (double)(gregorianYear - 1933) / SecondsPerDay; } static double EphemerisCorrection1900to1987(int gregorianYear) { - Contract.Assert(1900 <= gregorianYear && gregorianYear <= 1987); + Debug.Assert(1900 <= gregorianYear && gregorianYear <= 1987); double centuriesFrom1900 = CenturiesFrom1900(gregorianYear); return PolynomialSum(Coefficients1900to1987, centuriesFrom1900); } static double EphemerisCorrection1800to1899(int gregorianYear) { - Contract.Assert(1800 <= gregorianYear && gregorianYear <= 1899); + Debug.Assert(1800 <= gregorianYear && gregorianYear <= 1899); double centuriesFrom1900 = CenturiesFrom1900(gregorianYear); return PolynomialSum(Coefficients1800to1899, centuriesFrom1900); } static double EphemerisCorrection1700to1799(int gregorianYear) { - Contract.Assert(1700 <= gregorianYear && gregorianYear <= 1799); + Debug.Assert(1700 <= gregorianYear && gregorianYear <= 1799); double yearsSince1700 = gregorianYear - 1700; return PolynomialSum(Coefficients1700to1799, yearsSince1700) / SecondsPerDay; } static double EphemerisCorrection1620to1699(int gregorianYear) { - Contract.Assert(1620 <= gregorianYear && gregorianYear <= 1699); + Debug.Assert(1620 <= gregorianYear && gregorianYear <= 1699); double yearsSince1600 = gregorianYear - 1600; return PolynomialSum(Coefficients1620to1699, yearsSince1600) / SecondsPerDay; } @@ -216,7 +217,7 @@ namespace System.Globalization } } - Contract.Assert(false, "Not expected to come here"); + Debug.Assert(false, "Not expected to come here"); return DefaultEphemerisCorrection(year); } @@ -405,7 +406,7 @@ namespace System.Globalization break; } } - Contract.Assert(day != upperBoundNewYearDay); + Debug.Assert(day != upperBoundNewYearDay); return day - 1; } diff --git a/src/mscorlib/src/System/Globalization/CharUnicodeInfo.cs b/src/mscorlib/src/System/Globalization/CharUnicodeInfo.cs index 63151951f9..2822b418ef 100644 --- a/src/mscorlib/src/System/Globalization/CharUnicodeInfo.cs +++ b/src/mscorlib/src/System/Globalization/CharUnicodeInfo.cs @@ -23,6 +23,7 @@ namespace System.Globalization { using System.Runtime.Versioning; using System.Reflection; using System.Security; + using System.Diagnostics; using System.Diagnostics.Contracts; @@ -46,14 +47,11 @@ namespace System.Globalization { static bool s_initialized = InitTable(); // The native pointer to the 12:4:4 index table of the Unicode cateogry data. - [SecurityCritical] unsafe static ushort* s_pCategoryLevel1Index; - [SecurityCritical] unsafe static byte* s_pCategoriesValue; // The native pointer to the 12:4:4 index table of the Unicode numeric data. // The value of this index table is an index into the real value table stored in s_pNumericValues. - [SecurityCritical] unsafe static ushort* s_pNumericLevel1Index; // The numeric value table, which is indexed by s_pNumericLevel1Index. @@ -61,12 +59,10 @@ namespace System.Globalization { // unsafe static double* s_pNumericValues; // To get around the IA64 alignment issue. Our double data is aligned in 8-byte boundary, but loader loads the embeded table starting // at 4-byte boundary. This cause a alignment issue since double is 8-byte. - [SecurityCritical] unsafe static byte* s_pNumericValues; // The digit value table, which is indexed by s_pNumericLevel1Index. It shares the same indice as s_pNumericValues. // Every item contains the value for decimal digit/digit value. - [SecurityCritical] unsafe static DigitValues* s_pDigitValues; internal const String UNICODE_INFO_FILE_NAME = "charinfo.nlp"; @@ -111,7 +107,6 @@ namespace System.Globalization { //use. We allocate this once in the class initializer and then we don't need to worry //about it again. // - [System.Security.SecuritySafeCritical] // auto-generated unsafe static bool InitTable() { // Go to native side and get pointer to the native table @@ -143,8 +138,8 @@ namespace System.Globalization { //////////////////////////////////////////////////////////////////////// internal static int InternalConvertToUtf32(String s, int index) { - Contract.Assert(s != null, "s != null"); - Contract.Assert(index >= 0 && index < s.Length, "index < s.Length"); + Debug.Assert(s != null, "s != null"); + Debug.Assert(index >= 0 && index < s.Length, "index < s.Length"); if (index < s.Length - 1) { int temp1 = (int)s[index] - HIGH_SURROGATE_START; if (temp1 >= 0 && temp1 <= 0x3ff) { @@ -181,9 +176,9 @@ namespace System.Globalization { //////////////////////////////////////////////////////////////////////// internal static int InternalConvertToUtf32(String s, int index, out int charLength) { - Contract.Assert(s != null, "s != null"); - Contract.Assert(s.Length > 0, "s.Length > 0"); - Contract.Assert(index >= 0 && index < s.Length, "index >= 0 && index < s.Length"); + Debug.Assert(s != null, "s != null"); + Debug.Assert(s.Length > 0, "s.Length > 0"); + Debug.Assert(index >= 0 && index < s.Length, "index >= 0 && index < s.Length"); charLength = 1; if (index < s.Length - 1) { int temp1 = (int)s[index] - HIGH_SURROGATE_START; @@ -209,8 +204,8 @@ namespace System.Globalization { internal static bool IsWhiteSpace(String s, int index) { - Contract.Assert(s != null, "s!=null"); - Contract.Assert(index >= 0 && index < s.Length, "index >= 0 && index < s.Length"); + Debug.Assert(s != null, "s!=null"); + Debug.Assert(index >= 0 && index < s.Length, "index >= 0 && index < s.Length"); UnicodeCategory uc = GetUnicodeCategory(s, index); // In Unicode 3.0, U+2028 is the only character which is under the category "LineSeparator". @@ -245,9 +240,8 @@ namespace System.Globalization { // // Note that for ch in the range D800-DFFF we just treat it as any other non-numeric character // - [System.Security.SecuritySafeCritical] // auto-generated internal unsafe static double InternalGetNumericValue(int ch) { - Contract.Assert(ch >= 0 && ch <= 0x10ffff, "ch is not in valid Unicode range."); + Debug.Assert(ch >= 0 && ch <= 0x10ffff, "ch is not in valid Unicode range."); // Get the level 2 item from the highest 12 bit (8 - 19) of ch. ushort index = s_pNumericLevel1Index[ch >> 8]; // Get the level 2 WORD offset from the 4 - 7 bit of ch. This provides the base offset of the level 3 table. @@ -278,9 +272,8 @@ namespace System.Globalization { // // Note that for ch in the range D800-DFFF we just treat it as any other non-numeric character // - [System.Security.SecuritySafeCritical] // auto-generated internal unsafe static DigitValues* InternalGetDigitValues(int ch) { - Contract.Assert(ch >= 0 && ch <= 0x10ffff, "ch is not in valid Unicode range."); + Debug.Assert(ch >= 0 && ch <= 0x10ffff, "ch is not in valid Unicode range."); // Get the level 2 item from the highest 12 bit (8 - 19) of ch. ushort index = s_pNumericLevel1Index[ch >> 8]; // Get the level 2 WORD offset from the 4 - 7 bit of ch. This provides the base offset of the level 3 table. @@ -292,12 +285,10 @@ namespace System.Globalization { return &(s_pDigitValues[pBytePtr[(ch & 0x000f)]]); } - [System.Security.SecuritySafeCritical] // auto-generated internal unsafe static sbyte InternalGetDecimalDigitValue(int ch) { return (InternalGetDigitValues(ch)->decimalDigit); } - [System.Security.SecuritySafeCritical] // auto-generated internal unsafe static sbyte InternalGetDigitValue(int ch) { return (InternalGetDigitValues(ch)->digit); } @@ -326,10 +317,10 @@ namespace System.Globalization { public static double GetNumericValue(String s, int index) { if (s == null) { - throw new ArgumentNullException("s"); + throw new ArgumentNullException(nameof(s)); } if (index < 0 || index >= s.Length) { - throw new ArgumentOutOfRangeException("index", Environment.GetResourceString("ArgumentOutOfRange_Index")); + throw new ArgumentOutOfRangeException(nameof(index), Environment.GetResourceString("ArgumentOutOfRange_Index")); } Contract.EndContractBlock(); return (InternalGetNumericValue(InternalConvertToUtf32(s, index))); @@ -361,10 +352,10 @@ namespace System.Globalization { public static int GetDecimalDigitValue(String s, int index) { if (s == null) { - throw new ArgumentNullException("s"); + throw new ArgumentNullException(nameof(s)); } if (index < 0 || index >= s.Length) { - throw new ArgumentOutOfRangeException("index", Environment.GetResourceString("ArgumentOutOfRange_Index")); + throw new ArgumentOutOfRangeException(nameof(index), Environment.GetResourceString("ArgumentOutOfRange_Index")); } Contract.EndContractBlock(); @@ -398,10 +389,10 @@ namespace System.Globalization { public static int GetDigitValue(String s, int index) { if (s == null) { - throw new ArgumentNullException("s"); + throw new ArgumentNullException(nameof(s)); } if (index < 0 || index >= s.Length) { - throw new ArgumentOutOfRangeException("index", Environment.GetResourceString("ArgumentOutOfRange_Index")); + throw new ArgumentOutOfRangeException(nameof(index), Environment.GetResourceString("ArgumentOutOfRange_Index")); } Contract.EndContractBlock(); return (InternalGetDigitValue(InternalConvertToUtf32(s, index))); @@ -415,9 +406,9 @@ namespace System.Globalization { public static UnicodeCategory GetUnicodeCategory(String s, int index) { if (s==null) - throw new ArgumentNullException("s"); + throw new ArgumentNullException(nameof(s)); if (((uint)index)>=((uint)s.Length)) { - throw new ArgumentOutOfRangeException("index"); + throw new ArgumentOutOfRangeException(nameof(index)); } Contract.EndContractBlock(); return InternalGetUnicodeCategory(s, index); @@ -441,9 +432,8 @@ namespace System.Globalization { // //////////////////////////////////////////////////////////////////////// - [System.Security.SecuritySafeCritical] // auto-generated internal unsafe static byte InternalGetCategoryValue(int ch, int offset) { - Contract.Assert(ch >= 0 && ch <= 0x10ffff, "ch is not in valid Unicode range."); + Debug.Assert(ch >= 0 && ch <= 0x10ffff, "ch is not in valid Unicode range."); // Get the level 2 item from the highest 12 bit (8 - 19) of ch. ushort index = s_pCategoryLevel1Index[ch >> 8]; // Get the level 2 WORD offset from the 4 - 7 bit of ch. This provides the base offset of the level 3 table. @@ -457,7 +447,7 @@ namespace System.Globalization { // Make sure that OtherNotAssigned is the last category in UnicodeCategory. // If that changes, change the following assertion as well. // - //Contract.Assert(uc >= 0 && uc <= UnicodeCategory.OtherNotAssigned, "Table returns incorrect Unicode category"); + //Debug.Assert(uc >= 0 && uc <= UnicodeCategory.OtherNotAssigned, "Table returns incorrect Unicode category"); return (uc); } @@ -467,9 +457,9 @@ namespace System.Globalization { internal static BidiCategory GetBidiCategory(String s, int index) { if (s==null) - throw new ArgumentNullException("s"); + throw new ArgumentNullException(nameof(s)); if (((uint)index)>=((uint)s.Length)) { - throw new ArgumentOutOfRangeException("index"); + throw new ArgumentOutOfRangeException(nameof(index)); } Contract.EndContractBlock(); return ((BidiCategory)InternalGetCategoryValue(InternalConvertToUtf32(s, index), BIDI_CATEGORY_OFFSET)); @@ -489,8 +479,8 @@ namespace System.Globalization { //////////////////////////////////////////////////////////////////////// internal static UnicodeCategory InternalGetUnicodeCategory(String value, int index) { - Contract.Assert(value != null, "value can not be null"); - Contract.Assert(index < value.Length, "index < value.Length"); + Debug.Assert(value != null, "value can not be null"); + Debug.Assert(index < value.Length, "index < value.Length"); return (InternalGetUnicodeCategory(InternalConvertToUtf32(value, index))); } @@ -503,15 +493,15 @@ namespace System.Globalization { //////////////////////////////////////////////////////////////////////// internal static UnicodeCategory InternalGetUnicodeCategory(String str, int index, out int charLength) { - Contract.Assert(str != null, "str can not be null"); - Contract.Assert(str.Length > 0, "str.Length > 0");; - Contract.Assert(index >= 0 && index < str.Length, "index >= 0 && index < str.Length"); + Debug.Assert(str != null, "str can not be null"); + Debug.Assert(str.Length > 0, "str.Length > 0");; + Debug.Assert(index >= 0 && index < str.Length, "index >= 0 && index < str.Length"); return (InternalGetUnicodeCategory(InternalConvertToUtf32(str, index, out charLength))); } internal static bool IsCombiningCategory(UnicodeCategory uc) { - Contract.Assert(uc >= 0, "uc >= 0"); + Debug.Assert(uc >= 0, "uc >= 0"); return ( uc == UnicodeCategory.NonSpacingMark || uc == UnicodeCategory.SpacingCombiningMark || diff --git a/src/mscorlib/src/System/Globalization/ChineseLunisolarCalendar.cs b/src/mscorlib/src/System/Globalization/ChineseLunisolarCalendar.cs index a5cf37f712..6479152e09 100644 --- a/src/mscorlib/src/System/Globalization/ChineseLunisolarCalendar.cs +++ b/src/mscorlib/src/System/Globalization/ChineseLunisolarCalendar.cs @@ -331,12 +331,12 @@ namespace System.Globalization { internal override int GetGregorianYear(int year, int era) { if (era != CurrentEra && era != ChineseEra) { - throw new ArgumentOutOfRangeException("era", Environment.GetResourceString("ArgumentOutOfRange_InvalidEraValue")); + throw new ArgumentOutOfRangeException(nameof(era), Environment.GetResourceString("ArgumentOutOfRange_InvalidEraValue")); } if (year < MIN_LUNISOLAR_YEAR || year > MAX_LUNISOLAR_YEAR) { throw new ArgumentOutOfRangeException( - "year", + nameof(year), String.Format( CultureInfo.CurrentCulture, Environment.GetResourceString("ArgumentOutOfRange_Range"), MIN_LUNISOLAR_YEAR, MAX_LUNISOLAR_YEAR)); diff --git a/src/mscorlib/src/System/Globalization/CompareInfo.cs b/src/mscorlib/src/System/Globalization/CompareInfo.cs index 0b14f05264..dcf1f32e4a 100644 --- a/src/mscorlib/src/System/Globalization/CompareInfo.cs +++ b/src/mscorlib/src/System/Globalization/CompareInfo.cs @@ -32,6 +32,7 @@ namespace System.Globalization { using System.Security.Permissions; using Microsoft.Win32; using System.Security; + using System.Diagnostics; using System.Diagnostics.Contracts; // @@ -135,7 +136,7 @@ namespace System.Globalization { public static CompareInfo GetCompareInfo(int culture, Assembly assembly){ // Parameter checking. if (assembly == null) { - throw new ArgumentNullException("assembly"); + throw new ArgumentNullException(nameof(assembly)); } if (assembly!=typeof(Object).Module.Assembly) { throw new ArgumentException(Environment.GetResourceString("Argument_OnlyMscorlib")); @@ -161,7 +162,7 @@ namespace System.Globalization { // Assembly constructor should be deprecated, we don't act on the assembly information any more public static CompareInfo GetCompareInfo(String name, Assembly assembly){ if (name == null || assembly == null) { - throw new ArgumentNullException(name == null ? "name" : "assembly"); + throw new ArgumentNullException(name == null ? nameof(name) : nameof(assembly)); } Contract.EndContractBlock(); @@ -189,7 +190,7 @@ namespace System.Globalization { if (CultureData.IsCustomCultureId(culture)) { // Customized culture cannot be created by the LCID. - throw new ArgumentException(Environment.GetResourceString("Argument_CustomCultureCannotBePassedByNumber", "culture")); + throw new ArgumentException(Environment.GetResourceString("Argument_CustomCultureCannotBePassedByNumber", nameof(culture))); } return CultureInfo.GetCultureInfo(culture).CompareInfo; @@ -209,7 +210,7 @@ namespace System.Globalization { { if (name == null) { - throw new ArgumentNullException("name"); + throw new ArgumentNullException(nameof(name)); } Contract.EndContractBlock(); @@ -221,12 +222,11 @@ namespace System.Globalization { return(IsSortable(ch.ToString())); } - [System.Security.SecuritySafeCritical] [System.Runtime.InteropServices.ComVisible(false)] public static bool IsSortable(String text) { if (text == null) { // A null param is invalid here. - throw new ArgumentNullException("text"); + throw new ArgumentNullException(nameof(text)); } if (0 == text.Length) { @@ -291,7 +291,7 @@ namespace System.Globalization { #if FEATURE_USE_LCID // This is merely for serialization compatibility with Whidbey/Orcas, it can go away when we don't want that compat any more. culture = CultureInfo.GetCultureInfo(this.Name).LCID; // This is the lcid of the constructing culture (still have to dereference to get target sort) - Contract.Assert(m_name != null, "CompareInfo.OnSerializing - expected m_name to be set already"); + Debug.Assert(m_name != null, "CompareInfo.OnSerializing - expected m_name to be set already"); #endif } @@ -321,12 +321,7 @@ namespace System.Globalization { { get { - Contract.Assert(m_name != null, "CompareInfo.Name Expected m_name to be set"); - if (m_name == "zh-CHT" || m_name == "zh-CHS") - { - return m_name; - } - + Debug.Assert(m_name != null, "CompareInfo.Name Expected m_name to be set"); return (m_sortName); } } @@ -352,7 +347,7 @@ namespace System.Globalization { // some NLS VM functions can handle COMPARE_OPTIONS_ORDINAL // in which case options should be simply cast to int instead of using this function // Does not look like the best approach to me but for now I am going to leave it as it is - Contract.Assert(options != CompareOptions.OrdinalIgnoreCase, "[CompareInfo.GetNativeCompareFlags]CompareOptions.OrdinalIgnoreCase should be handled separately"); + Debug.Assert(options != CompareOptions.OrdinalIgnoreCase, "[CompareInfo.GetNativeCompareFlags]CompareOptions.OrdinalIgnoreCase should be handled separately"); // Use "linguistic casing" by default (load the culture's casing exception tables) int nativeCompareFlags = NORM_LINGUISTIC_CASING; @@ -367,7 +362,7 @@ namespace System.Globalization { // Suffix & Prefix shouldn't use this, make sure to turn off the NORM_LINGUISTIC_CASING flag if (options == CompareOptions.Ordinal) { nativeCompareFlags = COMPARE_OPTIONS_ORDINAL; } - Contract.Assert(((options & ~(CompareOptions.IgnoreCase | + Debug.Assert(((options & ~(CompareOptions.IgnoreCase | CompareOptions.IgnoreKanaType | CompareOptions.IgnoreNonSpace | CompareOptions.IgnoreSymbols | @@ -375,7 +370,7 @@ namespace System.Globalization { CompareOptions.StringSort)) == 0) || (options == CompareOptions.Ordinal), "[CompareInfo.GetNativeCompareFlags]Expected all flags to be handled"); - Contract.Assert((nativeCompareFlags & RESERVED_FIND_ASCII_STRING) == 0, "[CompareInfo.GetNativeCompareFlags] RESERVED_FIND_ASCII_STRING shouldn't be set here"); + Debug.Assert((nativeCompareFlags & RESERVED_FIND_ASCII_STRING) == 0, "[CompareInfo.GetNativeCompareFlags] RESERVED_FIND_ASCII_STRING shouldn't be set here"); return nativeCompareFlags; } @@ -398,7 +393,6 @@ namespace System.Globalization { return (Compare(string1, string2, CompareOptions.None)); } - [System.Security.SecuritySafeCritical] // auto-generated public unsafe virtual int Compare(String string1, String string2, CompareOptions options){ if (options == CompareOptions.OrdinalIgnoreCase) @@ -411,14 +405,14 @@ namespace System.Globalization { { if (options != CompareOptions.Ordinal) { - throw new ArgumentException(Environment.GetResourceString("Argument_CompareOptionOrdinal"), "options"); + throw new ArgumentException(Environment.GetResourceString("Argument_CompareOptionOrdinal"), nameof(options)); } return String.CompareOrdinal(string1, string2); } if ((options & ValidCompareMaskOffFlags) != 0) { - throw new ArgumentException(Environment.GetResourceString("Argument_InvalidFlag"), "options"); + throw new ArgumentException(Environment.GetResourceString("Argument_InvalidFlag"), nameof(options)); } //Our paradigm is that null sorts less than any other string and @@ -469,7 +463,6 @@ namespace System.Globalization { } - [System.Security.SecuritySafeCritical] // auto-generated public unsafe virtual int Compare(String string1, int offset1, int length1, String string2, int offset2, int length2, CompareOptions options) { if (options == CompareOptions.OrdinalIgnoreCase) @@ -483,31 +476,31 @@ namespace System.Globalization { // Verify inputs if (length1 < 0 || length2 < 0) { - throw new ArgumentOutOfRangeException((length1 < 0) ? "length1" : "length2", Environment.GetResourceString("ArgumentOutOfRange_NeedPosNum")); + throw new ArgumentOutOfRangeException((length1 < 0) ? nameof(length1) : nameof(length2), Environment.GetResourceString("ArgumentOutOfRange_NeedPosNum")); } if (offset1 < 0 || offset2 < 0) { - throw new ArgumentOutOfRangeException((offset1 < 0) ? "offset1" : "offset2", Environment.GetResourceString("ArgumentOutOfRange_NeedPosNum")); + throw new ArgumentOutOfRangeException((offset1 < 0) ? nameof(offset1) : nameof(offset2), Environment.GetResourceString("ArgumentOutOfRange_NeedPosNum")); } if (offset1 > (string1 == null ? 0 : string1.Length) - length1) { - throw new ArgumentOutOfRangeException("string1", Environment.GetResourceString("ArgumentOutOfRange_OffsetLength")); + throw new ArgumentOutOfRangeException(nameof(string1), Environment.GetResourceString("ArgumentOutOfRange_OffsetLength")); } if (offset2 > (string2 == null ? 0 : string2.Length) - length2) { - throw new ArgumentOutOfRangeException("string2", Environment.GetResourceString("ArgumentOutOfRange_OffsetLength")); + throw new ArgumentOutOfRangeException(nameof(string2), Environment.GetResourceString("ArgumentOutOfRange_OffsetLength")); } if ((options & CompareOptions.Ordinal) != 0) { if (options != CompareOptions.Ordinal) { throw new ArgumentException(Environment.GetResourceString("Argument_CompareOptionOrdinal"), - "options"); + nameof(options)); } } else if ((options & ValidCompareMaskOffFlags) != 0) { - throw new ArgumentException(Environment.GetResourceString("Argument_InvalidFlag"), "options"); + throw new ArgumentException(Environment.GetResourceString("Argument_InvalidFlag"), nameof(options)); } // @@ -546,11 +539,10 @@ namespace System.Globalization { //////////////////////////////////////////////////////////////////////// - [System.Security.SecuritySafeCritical] // auto-generated public unsafe virtual bool IsPrefix(String source, String prefix, CompareOptions options) { if (source == null || prefix == null) { - throw new ArgumentNullException((source == null ? "source" : "prefix"), + throw new ArgumentNullException((source == null ? nameof(source) : nameof(prefix)), Environment.GetResourceString("ArgumentNull_String")); } Contract.EndContractBlock(); @@ -572,7 +564,7 @@ namespace System.Globalization { } if ((options & ValidIndexMaskOffFlags) != 0) { - throw new ArgumentException(Environment.GetResourceString("Argument_InvalidFlag"), "options"); + throw new ArgumentException(Environment.GetResourceString("Argument_InvalidFlag"), nameof(options)); } @@ -601,11 +593,10 @@ namespace System.Globalization { //////////////////////////////////////////////////////////////////////// - [System.Security.SecuritySafeCritical] // auto-generated public unsafe virtual bool IsSuffix(String source, String suffix, CompareOptions options) { if (source == null || suffix == null) { - throw new ArgumentNullException((source == null ? "source" : "suffix"), + throw new ArgumentNullException((source == null ? nameof(source) : nameof(suffix)), Environment.GetResourceString("ArgumentNull_String")); } Contract.EndContractBlock(); @@ -625,7 +616,7 @@ namespace System.Globalization { } if ((options & ValidIndexMaskOffFlags) != 0) { - throw new ArgumentException(Environment.GetResourceString("Argument_InvalidFlag"), "options"); + throw new ArgumentException(Environment.GetResourceString("Argument_InvalidFlag"), nameof(options)); } // to let the sorting DLL do the call optimization in case of Ascii strings, we check if the strings are in Ascii and then send the flag RESERVED_FIND_ASCII_STRING to @@ -659,7 +650,7 @@ namespace System.Globalization { public unsafe virtual int IndexOf(String source, char value) { if (source==null) - throw new ArgumentNullException("source"); + throw new ArgumentNullException(nameof(source)); Contract.EndContractBlock(); return IndexOf(source, value, 0, source.Length, CompareOptions.None); @@ -669,7 +660,7 @@ namespace System.Globalization { public unsafe virtual int IndexOf(String source, String value) { if (source==null) - throw new ArgumentNullException("source"); + throw new ArgumentNullException(nameof(source)); Contract.EndContractBlock(); return IndexOf(source, value, 0, source.Length, CompareOptions.None); @@ -679,7 +670,7 @@ namespace System.Globalization { public unsafe virtual int IndexOf(String source, char value, CompareOptions options) { if (source==null) - throw new ArgumentNullException("source"); + throw new ArgumentNullException(nameof(source)); Contract.EndContractBlock(); return IndexOf(source, value, 0, source.Length, options); @@ -689,7 +680,7 @@ namespace System.Globalization { public unsafe virtual int IndexOf(String source, String value, CompareOptions options) { if (source==null) - throw new ArgumentNullException("source"); + throw new ArgumentNullException(nameof(source)); Contract.EndContractBlock(); return IndexOf(source, value, 0, source.Length, options); @@ -699,7 +690,7 @@ namespace System.Globalization { public unsafe virtual int IndexOf(String source, char value, int startIndex) { if (source == null) - throw new ArgumentNullException("source"); + throw new ArgumentNullException(nameof(source)); Contract.EndContractBlock(); return IndexOf(source, value, startIndex, source.Length - startIndex, CompareOptions.None); @@ -709,7 +700,7 @@ namespace System.Globalization { public unsafe virtual int IndexOf(String source, String value, int startIndex) { if (source == null) - throw new ArgumentNullException("source"); + throw new ArgumentNullException(nameof(source)); Contract.EndContractBlock(); return IndexOf(source, value, startIndex, source.Length - startIndex, CompareOptions.None); @@ -719,7 +710,7 @@ namespace System.Globalization { public unsafe virtual int IndexOf(String source, char value, int startIndex, CompareOptions options) { if (source == null) - throw new ArgumentNullException("source"); + throw new ArgumentNullException(nameof(source)); Contract.EndContractBlock(); return IndexOf(source, value, startIndex, source.Length - startIndex, options); @@ -729,7 +720,7 @@ namespace System.Globalization { public unsafe virtual int IndexOf(String source, String value, int startIndex, CompareOptions options) { if (source == null) - throw new ArgumentNullException("source"); + throw new ArgumentNullException(nameof(source)); Contract.EndContractBlock(); return IndexOf(source, value, startIndex, source.Length - startIndex, options); @@ -747,18 +738,17 @@ namespace System.Globalization { return IndexOf(source, value, startIndex, count, CompareOptions.None); } - [System.Security.SecuritySafeCritical] // auto-generated public unsafe virtual int IndexOf(String source, char value, int startIndex, int count, CompareOptions options) { // Validate inputs if (source == null) - throw new ArgumentNullException("source"); + throw new ArgumentNullException(nameof(source)); if (startIndex < 0 || startIndex > source.Length) - throw new ArgumentOutOfRangeException("startIndex", Environment.GetResourceString("ArgumentOutOfRange_Index")); + throw new ArgumentOutOfRangeException(nameof(startIndex), Environment.GetResourceString("ArgumentOutOfRange_Index")); if (count < 0 || startIndex > source.Length - count) - throw new ArgumentOutOfRangeException("count", Environment.GetResourceString("ArgumentOutOfRange_Count")); + throw new ArgumentOutOfRangeException(nameof(count), Environment.GetResourceString("ArgumentOutOfRange_Count")); Contract.EndContractBlock(); if (options == CompareOptions.OrdinalIgnoreCase) @@ -769,7 +759,7 @@ namespace System.Globalization { // Validate CompareOptions // Ordinal can't be selected with other flags if ((options & ValidIndexMaskOffFlags) != 0 && (options != CompareOptions.Ordinal)) - throw new ArgumentException(Environment.GetResourceString("Argument_InvalidFlag"), "options"); + throw new ArgumentException(Environment.GetResourceString("Argument_InvalidFlag"), nameof(options)); // to let the sorting DLL do the call optimization in case of Ascii strings, we check if the strings are in Ascii and then send the flag RESERVED_FIND_ASCII_STRING to // the sorting DLL API SortFindString so sorting DLL don't have to check if the string is Ascii with every call to SortFindString. @@ -780,18 +770,17 @@ namespace System.Globalization { } - [System.Security.SecuritySafeCritical] // auto-generated public unsafe virtual int IndexOf(String source, String value, int startIndex, int count, CompareOptions options) { // Validate inputs if (source == null) - throw new ArgumentNullException("source"); + throw new ArgumentNullException(nameof(source)); if (value == null) - throw new ArgumentNullException("value"); + throw new ArgumentNullException(nameof(value)); if (startIndex > source.Length) { - throw new ArgumentOutOfRangeException("startIndex", Environment.GetResourceString("ArgumentOutOfRange_Index")); + throw new ArgumentOutOfRangeException(nameof(startIndex), Environment.GetResourceString("ArgumentOutOfRange_Index")); } Contract.EndContractBlock(); @@ -808,11 +797,11 @@ namespace System.Globalization { if (startIndex < 0) { - throw new ArgumentOutOfRangeException("startIndex", Environment.GetResourceString("ArgumentOutOfRange_Index")); + throw new ArgumentOutOfRangeException(nameof(startIndex), Environment.GetResourceString("ArgumentOutOfRange_Index")); } if (count < 0 || startIndex > source.Length - count) - throw new ArgumentOutOfRangeException("count",Environment.GetResourceString("ArgumentOutOfRange_Count")); + throw new ArgumentOutOfRangeException(nameof(count),Environment.GetResourceString("ArgumentOutOfRange_Count")); if (options == CompareOptions.OrdinalIgnoreCase) { @@ -822,7 +811,7 @@ namespace System.Globalization { // Validate CompareOptions // Ordinal can't be selected with other flags if ((options & ValidIndexMaskOffFlags) != 0 && (options != CompareOptions.Ordinal)) - throw new ArgumentException(Environment.GetResourceString("Argument_InvalidFlag"), "options"); + throw new ArgumentException(Environment.GetResourceString("Argument_InvalidFlag"), nameof(options)); // to let the sorting DLL do the call optimization in case of Ascii strings, we check if the strings are in Ascii and then send the flag RESERVED_FIND_ASCII_STRING to // the sorting DLL API SortFindString so sorting DLL don't have to check if the string is Ascii with every call to SortFindString. @@ -849,7 +838,7 @@ namespace System.Globalization { public unsafe virtual int LastIndexOf(String source, char value) { if (source==null) - throw new ArgumentNullException("source"); + throw new ArgumentNullException(nameof(source)); Contract.EndContractBlock(); // Can't start at negative index, so make sure we check for the length == 0 case. @@ -861,7 +850,7 @@ namespace System.Globalization { public virtual int LastIndexOf(String source, String value) { if (source==null) - throw new ArgumentNullException("source"); + throw new ArgumentNullException(nameof(source)); Contract.EndContractBlock(); // Can't start at negative index, so make sure we check for the length == 0 case. @@ -873,7 +862,7 @@ namespace System.Globalization { public virtual int LastIndexOf(String source, char value, CompareOptions options) { if (source==null) - throw new ArgumentNullException("source"); + throw new ArgumentNullException(nameof(source)); Contract.EndContractBlock(); // Can't start at negative index, so make sure we check for the length == 0 case. @@ -884,7 +873,7 @@ namespace System.Globalization { public unsafe virtual int LastIndexOf(String source, String value, CompareOptions options) { if (source==null) - throw new ArgumentNullException("source"); + throw new ArgumentNullException(nameof(source)); Contract.EndContractBlock(); // Can't start at negative index, so make sure we check for the length == 0 case. @@ -929,12 +918,11 @@ namespace System.Globalization { } - [System.Security.SecuritySafeCritical] // auto-generated public unsafe virtual int LastIndexOf(String source, char value, int startIndex, int count, CompareOptions options) { // Verify Arguments if (source==null) - throw new ArgumentNullException("source"); + throw new ArgumentNullException(nameof(source)); Contract.EndContractBlock(); // Validate CompareOptions @@ -942,7 +930,7 @@ namespace System.Globalization { if ((options & ValidIndexMaskOffFlags) != 0 && (options != CompareOptions.Ordinal) && (options != CompareOptions.OrdinalIgnoreCase)) - throw new ArgumentException(Environment.GetResourceString("Argument_InvalidFlag"), "options"); + throw new ArgumentException(Environment.GetResourceString("Argument_InvalidFlag"), nameof(options)); // Special case for 0 length input strings if (source.Length == 0 && (startIndex == -1 || startIndex == 0)) @@ -950,7 +938,7 @@ namespace System.Globalization { // Make sure we're not out of range if (startIndex < 0 || startIndex > source.Length) - throw new ArgumentOutOfRangeException("startIndex", Environment.GetResourceString("ArgumentOutOfRange_Index")); + throw new ArgumentOutOfRangeException(nameof(startIndex), Environment.GetResourceString("ArgumentOutOfRange_Index")); // Make sure that we allow startIndex == source.Length if (startIndex == source.Length) @@ -962,7 +950,7 @@ namespace System.Globalization { // 2nd have of this also catches when startIndex == MAXINT, so MAXINT - 0 + 1 == -1, which is < 0. if (count < 0 || startIndex - count + 1 < 0) - throw new ArgumentOutOfRangeException("count", Environment.GetResourceString("ArgumentOutOfRange_Count")); + throw new ArgumentOutOfRangeException(nameof(count), Environment.GetResourceString("ArgumentOutOfRange_Count")); if (options == CompareOptions.OrdinalIgnoreCase) { @@ -978,14 +966,13 @@ namespace System.Globalization { } - [System.Security.SecuritySafeCritical] // auto-generated public unsafe virtual int LastIndexOf(String source, String value, int startIndex, int count, CompareOptions options) { // Verify Arguments if (source == null) - throw new ArgumentNullException("source"); + throw new ArgumentNullException(nameof(source)); if (value == null) - throw new ArgumentNullException("value"); + throw new ArgumentNullException(nameof(value)); Contract.EndContractBlock(); // Validate CompareOptions @@ -993,7 +980,7 @@ namespace System.Globalization { if ((options & ValidIndexMaskOffFlags) != 0 && (options != CompareOptions.Ordinal) && (options != CompareOptions.OrdinalIgnoreCase)) - throw new ArgumentException(Environment.GetResourceString("Argument_InvalidFlag"), "options"); + throw new ArgumentException(Environment.GetResourceString("Argument_InvalidFlag"), nameof(options)); // Special case for 0 length input strings if (source.Length == 0 && (startIndex == -1 || startIndex == 0)) @@ -1001,7 +988,7 @@ namespace System.Globalization { // Make sure we're not out of range if (startIndex < 0 || startIndex > source.Length) - throw new ArgumentOutOfRangeException("startIndex", Environment.GetResourceString("ArgumentOutOfRange_Index")); + throw new ArgumentOutOfRangeException(nameof(startIndex), Environment.GetResourceString("ArgumentOutOfRange_Index")); // Make sure that we allow startIndex == source.Length if (startIndex == source.Length) @@ -1017,7 +1004,7 @@ namespace System.Globalization { // 2nd half of this also catches when startIndex == MAXINT, so MAXINT - 0 + 1 == -1, which is < 0. if (count < 0 || startIndex - count + 1 < 0) - throw new ArgumentOutOfRangeException("count", Environment.GetResourceString("ArgumentOutOfRange_Count")); + throw new ArgumentOutOfRangeException(nameof(count), Environment.GetResourceString("ArgumentOutOfRange_Count")); if (options == CompareOptions.OrdinalIgnoreCase) { @@ -1051,10 +1038,9 @@ namespace System.Globalization { return CreateSortKey(source, CompareOptions.None); } - [System.Security.SecuritySafeCritical] private SortKey CreateSortKey(String source, CompareOptions options) { - if (source==null) { throw new ArgumentNullException("source"); } + if (source==null) { throw new ArgumentNullException(nameof(source)); } Contract.EndContractBlock(); // Mask used to check if we have the right flags. @@ -1067,7 +1053,7 @@ namespace System.Globalization { if ((options & ValidSortkeyCtorMaskOffFlags) != 0) { - throw new ArgumentException(Environment.GetResourceString("Argument_InvalidFlag"), "options"); + throw new ArgumentException(Environment.GetResourceString("Argument_InvalidFlag"), nameof(options)); } byte[] keyData = null; // The OS doesn't have quite the same behavior so we have to test for empty inputs @@ -1088,7 +1074,7 @@ namespace System.Globalization { // If there was an error, return an error if (length == 0) { - throw new ArgumentException(Environment.GetResourceString("Argument_InvalidFlag"), "source"); + throw new ArgumentException(Environment.GetResourceString("Argument_InvalidFlag"), nameof(source)); } // If input was empty, return the empty byte[] we made earlier and skip this @@ -1157,7 +1143,7 @@ namespace System.Globalization { { if (source == null) { - throw new ArgumentNullException("source"); + throw new ArgumentNullException(nameof(source)); } if (options == CompareOptions.Ordinal) @@ -1207,7 +1193,6 @@ namespace System.Globalization { return GetHashCodeOfString(source, options, false, 0); } - [System.Security.SecuritySafeCritical] // auto-generated internal int GetHashCodeOfString(string source, CompareOptions options, bool forceRandomizedHashing, long additionalEntropy) { // @@ -1215,12 +1200,12 @@ namespace System.Globalization { // if(null == source) { - throw new ArgumentNullException("source"); + throw new ArgumentNullException(nameof(source)); } if ((options & ValidHashCodeOfStringMaskOffFlags) != 0) { - throw new ArgumentException(Environment.GetResourceString("Argument_InvalidFlag"), "options"); + throw new ArgumentException(Environment.GetResourceString("Argument_InvalidFlag"), nameof(options)); } Contract.EndContractBlock(); @@ -1259,39 +1244,16 @@ namespace System.Globalization { } #endif - [System.Security.SecuritySafeCritical] internal static IntPtr InternalInitSortHandle(String localeName, out IntPtr handleOrigin) { return NativeInternalInitSortHandle(localeName, out handleOrigin); } -#if !FEATURE_CORECLR - private const int SORT_VERSION_WHIDBEY = 0x00001000; - private const int SORT_VERSION_V4 = 0x00060101; - - internal static bool IsLegacy20SortingBehaviorRequested - { - get - { - return InternalSortVersion == SORT_VERSION_WHIDBEY; - } - } - - private static uint InternalSortVersion - { - [System.Security.SecuritySafeCritical] - get - { - return InternalGetSortVersion(); - } - } - [OptionalField(VersionAdded = 3)] private SortVersion m_SortVersion; public SortVersion Version { - [SecuritySafeCritical] get { if(m_SortVersion == null) @@ -1306,38 +1268,27 @@ namespace System.Globalization { } } - [System.Security.SecurityCritical] [DllImport(JitHelpers.QCall, CharSet = CharSet.Unicode)] [SuppressUnmanagedCodeSecurity] [return: MarshalAs(UnmanagedType.Bool)] private static extern bool InternalGetNlsVersionEx(IntPtr handle, IntPtr handleOrigin, String localeName, ref Win32Native.NlsVersionInfoEx lpNlsVersionInformation); - [System.Security.SecurityCritical] - [DllImport(JitHelpers.QCall, CharSet = CharSet.Unicode)] - [SuppressUnmanagedCodeSecurity] - private static extern uint InternalGetSortVersion(); - -#endif - [System.Security.SecurityCritical] [DllImport(JitHelpers.QCall, CharSet = CharSet.Unicode)] [SuppressUnmanagedCodeSecurity] private static extern IntPtr NativeInternalInitSortHandle(String localeName, out IntPtr handleOrigin); // Get a locale sensitive sort hash code from native code -- COMNlsInfo::InternalGetGlobalizedHashCode - [System.Security.SecurityCritical] // auto-generated [DllImport(JitHelpers.QCall, CharSet = CharSet.Unicode)] [SuppressUnmanagedCodeSecurity] private static extern int InternalGetGlobalizedHashCode(IntPtr handle, IntPtr handleOrigin, string localeName, string source, int length, int dwFlags, bool forceRandomizedHashing, long additionalEntropy); // Use native API calls to see if this string is entirely defined -- COMNlsInfo::InternalIsSortable - [System.Security.SecurityCritical] // auto-generated [DllImport(JitHelpers.QCall, CharSet = CharSet.Unicode)] [SuppressUnmanagedCodeSecurity] [return: MarshalAs(UnmanagedType.Bool)] private static extern bool InternalIsSortable(IntPtr handle, IntPtr handleOrigin, String localeName, String source, int length); // Compare a string using the native API calls -- COMNlsInfo::InternalCompareString - [System.Security.SecurityCritical] // auto-generated [DllImport(JitHelpers.QCall, CharSet = CharSet.Unicode)] [SuppressUnmanagedCodeSecurity] private static extern int InternalCompareString(IntPtr handle, IntPtr handleOrigin, String localeName, String string1, int offset1, int length1, @@ -1345,13 +1296,11 @@ namespace System.Globalization { // InternalFindNLSStringEx parameters is not exactly matching kernel32::FindNLSStringEx parameters. // Call through to NewApis::FindNLSStringEx so we can get the right behavior - [System.Security.SecurityCritical] // auto-generated [DllImport(JitHelpers.QCall, CharSet = CharSet.Unicode)] [SuppressUnmanagedCodeSecurity] private static extern int InternalFindNLSStringEx(IntPtr handle, IntPtr handleOrigin, String localeName, int flags, String source, int sourceCount, int startIndex, string target, int targetCount); // Call through to NewAPis::LCMapStringEx so we can get appropriate behavior for all platforms - [System.Security.SecurityCritical] // auto-generated [DllImport(JitHelpers.QCall, CharSet = CharSet.Unicode)] [SuppressUnmanagedCodeSecurity] private static extern int InternalGetSortKey(IntPtr handle, IntPtr handleOrigin, String localeName, int flags, String source, int sourceCount, byte[] target, int targetCount); diff --git a/src/mscorlib/src/System/Globalization/CultureData.cs b/src/mscorlib/src/System/Globalization/CultureData.cs index ae1eeea298..0bcb796152 100644 --- a/src/mscorlib/src/System/Globalization/CultureData.cs +++ b/src/mscorlib/src/System/Globalization/CultureData.cs @@ -10,13 +10,10 @@ namespace System.Globalization using System.Collections.Generic; using System.Text; using System.Threading; -#if !FEATURE_CORECLR - using System.Reflection; - using System.Resources; -#endif using System.Runtime.CompilerServices; using System.Runtime.InteropServices; using System.Runtime.Versioning; + using System.Diagnostics; using System.Diagnostics.Contracts; using System.Security; @@ -451,8 +448,8 @@ namespace System.Globalization invariant.iDefaultOemCodePage = 437; // default oem code page ID (OCP or OEM) invariant.iDefaultMacCodePage = 10000; // default macintosh code page invariant.iDefaultEbcdicCodePage = 037; // default EBCDIC code page - invariant.sAbbrevLang = "IVL"; // abbreviated language name (Windows Language Name) - invariant.sAbbrevCountry = "IVC"; // abbreviated country name (RegionInfo) (Windows Region Name) + invariant.sAbbrevLang = "IVL"; // abbreviated language name (Windows Language Name) + invariant.sAbbrevCountry = "IVC"; // abbreviated country name (RegionInfo) (Windows Region Name) invariant.sISO639Language2 = "ivl"; // 3 char ISO 639 lang name 2 invariant.sISO3166CountryName2 = "ivc"; // 3 char ISO 3166 country name 2 2(RegionInfo) invariant.iInputLanguageHandle = 0x007f; // input language handle @@ -466,23 +463,6 @@ namespace System.Globalization } private volatile static CultureData s_Invariant; - -#if !FEATURE_CORECLR - internal static volatile ResourceSet MscorlibResourceSet; -#endif - -#if !FEATURE_CORECLR - [System.Security.SecurityCritical] // auto-generated - private static bool IsResourcePresent(String resourceKey) - { - if (MscorlibResourceSet == null) - { - MscorlibResourceSet = new ResourceSet(typeof(Environment).Assembly.GetManifestResourceStream("mscorlib.resources")); - } - return MscorlibResourceSet.GetString(resourceKey) != null; - } -#endif - /////////////// // Constructors // /////////////// @@ -549,13 +529,7 @@ namespace System.Globalization // Ask native code if that one's real if (culture.InitCultureData() == false) { -#if !FEATURE_CORECLR - if (culture.InitCompatibilityCultureData() == false - && culture.InitLegacyAlternateSortData() == false) -#endif - { - return null; - } + return null; } return culture; @@ -567,142 +541,12 @@ namespace System.Globalization { return false; } - -#if !FEATURE_CORECLR - if (CultureInfo.IsTaiwanSku) - { - TreatTaiwanParentChainAsHavingTaiwanAsSpecific(); - } -#endif - return true; - } - -#if !FEATURE_CORECLR - [System.Security.SecuritySafeCritical] - private void TreatTaiwanParentChainAsHavingTaiwanAsSpecific() - { - if (IsNeutralInParentChainOfTaiwan() && IsOsPriorToWin7() && !IsReplacementCulture) - { - // force population of fields that should have information that is - // different than zh-TW: - string s = SNATIVELANGUAGE; - s = SENGLISHLANGUAGE; - s = SLOCALIZEDLANGUAGE; - s = STEXTINFO; - s = SCOMPAREINFO; - s = FONTSIGNATURE; - int i = IDEFAULTANSICODEPAGE; - i = IDEFAULTOEMCODEPAGE; - i = IDEFAULTMACCODEPAGE; - - this.sSpecificCulture = "zh-TW"; - this.sWindowsName = "zh-TW"; - } - } - - private bool IsNeutralInParentChainOfTaiwan() - { - return this.sRealName == "zh" || this.sRealName == "zh-Hant"; - } - - static readonly Version s_win7Version = new Version(6, 1); - static private bool IsOsPriorToWin7() - { - return Environment.OSVersion.Platform == PlatformID.Win32NT && - Environment.OSVersion.Version < s_win7Version; - } - static private bool IsOsWin7OrPrior() - { - return Environment.OSVersion.Platform == PlatformID.Win32NT && - Environment.OSVersion.Version < new Version(6, 2); // Win7 is 6.1.Build.Revision so we have to check for anything less than 6.2 - } - - private bool InitCompatibilityCultureData() - { - // for compatibility handle the deprecated ids: zh-chs, zh-cht - string cultureName = this.sRealName; - - string fallbackCultureName; - string realCultureName; - switch (AnsiToLower(cultureName)) - { - case "zh-chs": - fallbackCultureName = "zh-Hans"; - realCultureName = "zh-CHS"; - break; - case "zh-cht": - fallbackCultureName = "zh-Hant"; - realCultureName = "zh-CHT"; - break; - default: - return false; - } - - this.sRealName = fallbackCultureName; - if (InitCultureData() == false) - { - return false; - } - // fixup our data - this.sName = realCultureName; // the name that goes back to the user - this.sParent = fallbackCultureName; - this.bFramework = true; - - return true; - } - - private bool InitLegacyAlternateSortData() - { - if (!CompareInfo.IsLegacy20SortingBehaviorRequested) - { - return false; - } - - // For V2 compatibility, handle deprecated alternate sorts - string cultureName = this.sRealName; - - switch (AnsiToLower(cultureName)) - { - case "ko-kr_unicod": - cultureName = "ko-KR_unicod"; - this.sRealName = "ko-KR"; - this.iLanguage = 0x00010412; - break; - case "ja-jp_unicod": - cultureName = "ja-JP_unicod"; - this.sRealName = "ja-JP"; - this.iLanguage = 0x00010411; - break; - case "zh-hk_stroke": - cultureName = "zh-HK_stroke"; - this.sRealName = "zh-HK"; - this.iLanguage = 0x00020c04; - break; - default: - return false; - } - - if (nativeInitCultureData(this) == false) - { - return false; - } - - this.sRealName = cultureName; - this.sCompareInfo = cultureName; - this.bFramework = true; - return true; } -#if FEATURE_WIN32_REGISTRY - private static String s_RegionKey = @"System\CurrentControlSet\Control\Nls\RegionMapping"; -#endif // FEATURE_WIN32_REGISTRY - -#endif // !FEATURE_CORECLR // Cache of regions we've already looked up private static volatile Dictionary<String, CultureData> s_cachedRegions; - [System.Security.SecurityCritical] // auto-generated internal static CultureData GetCultureDataForRegion(String cultureName, bool useUserOverride) { // First do a shortcut for Invariant @@ -749,41 +593,6 @@ namespace System.Globalization // // Not found in the hash table, look it up the hard way // -#if !FEATURE_CORECLR -#if FEATURE_WIN32_REGISTRY - // First try the registry in case there are overrides of our table - try - { - // Open in read-only mode. - // Use InternalOpenSubKey so that we avoid the security check. - Microsoft.Win32.RegistryKey key = Microsoft.Win32.Registry.LocalMachine.InternalOpenSubKey(s_RegionKey, false); - - if (key != null) - { - try - { - Object value = key.InternalGetValue(cultureName, null, false, false); - - if (value != null) - { - // Get the name of the locale to try. - String specificForRegion = value.ToString(); - - // See if it's real - retVal = GetCultureData(specificForRegion, useUserOverride); - } - } - finally - { - key.Close(); - } - } - } - // If this fails for any reason, we'll just ignore it, likely it just isn't there. - catch (ObjectDisposedException) { } - catch (ArgumentException) { } -#endif // FEATURE_WIN32_REGISTRY -#endif // !FEATURE_CORECLR // If not a valid mapping from the registry we'll have to try the hard coded table if (retVal == null || (retVal.IsNeutralCulture == true)) @@ -841,7 +650,6 @@ namespace System.Globalization #if FEATURE_USE_LCID // Obtain locale name from LCID // NOTE: This will get neutral names, unlike the OS API - [System.Security.SecuritySafeCritical] // auto-generated [MethodImplAttribute(MethodImplOptions.InternalCall)] internal static extern String LCIDToLocaleName(int lcid); @@ -851,25 +659,6 @@ namespace System.Globalization String localeName = null; CultureData retVal = null; -#if !FEATURE_CORECLR - // If V2 legacy sort is requested, then provide deprecated alternate sorts - if (CompareInfo.IsLegacy20SortingBehaviorRequested) - { - switch (culture) - { - case 0x00010412: - localeName = "ko-KR_unicod"; - break; - case 0x00010411: - localeName = "ja-JP_unicod"; - break; - case 0x00020c04: - localeName = "zh-HK_stroke"; - break; - } - } -#endif - if (localeName == null) { // Convert the lcid to a name, then use that @@ -886,19 +675,6 @@ namespace System.Globalization } else { -#if !FEATURE_CORECLR - switch (localeName) - { - // for compatibility with Whidbey, when requesting - // a locale from LCID, return the old localeName - case "zh-Hans": - localeName = "zh-CHS"; - break; - case "zh-Hant": - localeName = "zh-CHT"; - break; - } -#endif // Valid name, use it retVal = GetCultureData(localeName, bUseUserOverride); } @@ -906,7 +682,7 @@ namespace System.Globalization // If not successful, throw if (retVal == null) throw new CultureNotFoundException( - "culture", culture, Environment.GetResourceString("Argument_CultureNotSupported")); + nameof(culture), culture, Environment.GetResourceString("Argument_CultureNotSupported")); // Return the one we found return retVal; @@ -921,7 +697,6 @@ namespace System.Globalization s_replacementCultureNames = null; } - [System.Security.SecuritySafeCritical] // auto-generated internal static CultureInfo[] GetCultures(CultureTypes types) { // Disable warning 618: System.Globalization.CultureTypes.FrameworkCultures' is obsolete @@ -933,7 +708,7 @@ namespace System.Globalization CultureTypes.FrameworkCultures)) != 0) { throw new ArgumentOutOfRangeException( - "types", + nameof(types), String.Format( CultureInfo.CurrentCulture, Environment.GetResourceString("ArgumentOutOfRange_Range"), CultureTypes.NeutralCultures, CultureTypes.FrameworkCultures)); @@ -972,25 +747,12 @@ namespace System.Globalization int arrayLength = cultureNames.Length; - if ((types & (CultureTypes.NeutralCultures | CultureTypes.FrameworkCultures)) != 0) // add zh-CHT and zh-CHS - { - arrayLength += 2; - } - CultureInfo[] cultures = new CultureInfo[arrayLength]; for (int i = 0; i < cultureNames.Length; i++) { cultures[i] = new CultureInfo(cultureNames[i]); } - - if ((types & (CultureTypes.NeutralCultures | CultureTypes.FrameworkCultures)) != 0) // add zh-CHT and zh-CHS - { - Contract.Assert(arrayLength == cultureNames.Length + 2, "CultureData.nativeEnumCultureNames() Incorrect array size"); - cultures[cultureNames.Length] = new CultureInfo("zh-CHS"); - cultures[cultureNames.Length + 1] = new CultureInfo("zh-CHT"); - } - #pragma warning restore 618 return cultures; @@ -1028,10 +790,9 @@ namespace System.Globalization //////////////////////////////////////////////////////////////////////// - [System.Security.SecuritySafeCritical] // auto-generated private static bool IsReplacementCultureName(String name) { - Contract.Assert(name != null, "IsReplacementCultureName(): name should not be null"); + Debug.Assert(name != null, "IsReplacementCultureName(): name should not be null"); String[] replacementCultureNames = s_replacementCultureNames; if (replacementCultureNames == null) { @@ -1041,7 +802,7 @@ namespace System.Globalization } // Even if we don't have any replacement cultures, the returned replacementCultureNames will still an empty string array, not null. - Contract.Assert(name != null, "IsReplacementCultureName(): replacementCultureNames should not be null"); + Debug.Assert(name != null, "IsReplacementCultureName(): replacementCultureNames should not be null"); Array.Sort(replacementCultureNames); s_replacementCultureNames = replacementCultureNames; } @@ -1065,7 +826,7 @@ namespace System.Globalization { get { - Contract.Assert(this.sRealName != null, "[CultureData.CultureName] Expected this.sRealName to be populated by COMNlsInfo::nativeInitCultureData already"); + Debug.Assert(this.sRealName != null, "[CultureData.CultureName] Expected this.sRealName to be populated by COMNlsInfo::nativeInitCultureData already"); // since windows doesn't know about zh-CHS and zh-CHT, // we leave sRealName == zh-Hanx but we still need to // pretend that it was zh-CHX. @@ -1093,7 +854,7 @@ namespace System.Globalization { get { - // Contract.Assert(this.sName != null, + // Debug.Assert(this.sName != null, // "[CultureData.SNAME] Expected this.sName to be populated by COMNlsInfo::nativeInitCultureData already"); if (this.sName == null) { @@ -1106,31 +867,12 @@ namespace System.Globalization // Parent name (which may be a custom locale/culture) internal String SPARENT { - [System.Security.SecurityCritical] // auto-generated get { if (this.sParent == null) { // Ask using the real name, so that we get parents of neutrals this.sParent = DoGetLocaleInfo(this.sRealName, LOCALE_SPARENT); - -#if !FEATURE_CORECLR - // for compatibility, the chain should be: - // zh-CN -> zh-CHS -> zh-Hans -> zh - // zh-TW -> zh-CHT -> zh-Hant -> zh - Contract.Assert(this.sName != "zh-CHS" && this.sName != "zh-CHT", - "sParent should have been initialized for zh-CHS and zh-CHT when they were constructed, otherwise we get recursion"); - switch (this.sParent) - { - case "zh-Hans": - this.sParent = "zh-CHS"; - break; - case "zh-Hant": - this.sParent = "zh-CHT"; - break; - } -#endif - } return this.sParent; } @@ -1139,18 +881,10 @@ namespace System.Globalization // Localized pretty name for this locale (ie: Inglis (estados Unitos)) internal String SLOCALIZEDDISPLAYNAME { - [System.Security.SecurityCritical] // auto-generated get { if (this.sLocalizedDisplayName == null) { -#if !FEATURE_CORECLR - String resourceKey = "Globalization.ci_" + this.sName; - if (IsResourcePresent(resourceKey)) - { - this.sLocalizedDisplayName = Environment.GetResourceString(resourceKey); - } -#endif // If it hasn't been found (Windows 8 and up), fallback to the system if (String.IsNullOrEmpty(this.sLocalizedDisplayName)) { @@ -1180,7 +914,6 @@ namespace System.Globalization // English pretty name for this locale (ie: English (United States)) internal String SENGDISPLAYNAME { - [System.Security.SecurityCritical] // auto-generated get { if (this.sEnglishDisplayName == null) @@ -1189,17 +922,6 @@ namespace System.Globalization if (this.IsNeutralCulture) { this.sEnglishDisplayName = this.SENGLISHLANGUAGE; -#if !FEATURE_CORECLR - // differentiate the legacy display names - switch (this.sName) - { - case "zh-CHS": - case "zh-CHT": - this.sEnglishDisplayName += " Legacy"; - break; - } -#endif - } else { @@ -1233,7 +955,6 @@ namespace System.Globalization // Native pretty name for this locale (ie: Deutsch (Deutschland)) internal String SNATIVEDISPLAYNAME { - [System.Security.SecurityCritical] // auto-generated get { if (this.sNativeDisplayName == null) @@ -1242,32 +963,10 @@ namespace System.Globalization if (this.IsNeutralCulture) { this.sNativeDisplayName = this.SNATIVELANGUAGE; -#if !FEATURE_CORECLR - // differentiate the legacy display names - switch (this.sName) - { - case "zh-CHS": - this.sNativeDisplayName += " \u65E7\u7248"; - break; - case "zh-CHT": - this.sNativeDisplayName += " \u820A\u7248"; - break; - } -#endif } else { -#if !FEATURE_CORECLR - if (IsIncorrectNativeLanguageForSinhala()) - { - // work around bug in Windows 7 for native name of Sinhala - this.sNativeDisplayName ="\x0dc3\x0dd2\x0d82\x0dc4\x0dbd (\x0DC1\x0DCA\x200D\x0DBB\x0DD3\x0020\x0DBD\x0D82\x0D9A\x0DCF)"; - } - else -#endif - { - this.sNativeDisplayName = DoGetLocaleInfo(LOCALE_SNATIVEDISPLAYNAME); - } + this.sNativeDisplayName = DoGetLocaleInfo(LOCALE_SNATIVEDISPLAYNAME); // if it isn't found build one: if (String.IsNullOrEmpty(this.sNativeDisplayName)) @@ -1287,7 +986,7 @@ namespace System.Globalization get { // This got populated when ComNlsInfo::nativeInitCultureData told us we had a culture - Contract.Assert(this.sSpecificCulture != null, "[CultureData.SSPECIFICCULTURE] Expected this.sSpecificCulture to be populated by COMNlsInfo::nativeInitCultureData already"); + Debug.Assert(this.sSpecificCulture != null, "[CultureData.SSPECIFICCULTURE] Expected this.sSpecificCulture to be populated by COMNlsInfo::nativeInitCultureData already"); return this.sSpecificCulture; } } @@ -1299,7 +998,6 @@ namespace System.Globalization // iso 639 language name, ie: en internal String SISO639LANGNAME { - [System.Security.SecurityCritical] // auto-generated get { if (this.sISO639Language == null) @@ -1313,7 +1011,6 @@ namespace System.Globalization // iso 639 language name, ie: eng internal String SISO639LANGNAME2 { - [System.Security.SecurityCritical] // auto-generated get { if (this.sISO639Language2 == null) @@ -1327,7 +1024,6 @@ namespace System.Globalization // abbreviated windows language name (ie: enu) (non-standard, avoid this) internal String SABBREVLANGNAME { - [System.Security.SecurityCritical] // auto-generated get { if (this.sAbbrevLang == null) @@ -1342,7 +1038,6 @@ namespace System.Globalization // This is only valid for Windows 8 and higher neutrals: internal String SLOCALIZEDLANGUAGE { - [System.Security.SecurityCritical] // auto-generated get { if (this.sLocalizedLanguage == null) @@ -1365,7 +1060,6 @@ namespace System.Globalization // English name for this language (Windows Only) ie: German internal String SENGLISHLANGUAGE { - [System.Security.SecurityCritical] // auto-generated get { if (this.sEnglishLanguage == null) @@ -1379,18 +1073,10 @@ namespace System.Globalization // Native name of this language (Windows Only) ie: Deutsch internal String SNATIVELANGUAGE { - [System.Security.SecurityCritical] // auto-generated get { if (this.sNativeLanguage == null) { -#if !FEATURE_CORECLR - if (IsIncorrectNativeLanguageForSinhala()) - { - this.sNativeLanguage = "\x0dc3\x0dd2\x0d82\x0dc4\x0dbd"; - } - else -#endif { this.sNativeLanguage = DoGetLocaleInfo(LOCALE_SNATIVELANGUAGENAME); } @@ -1399,15 +1085,6 @@ namespace System.Globalization } } -#if !FEATURE_CORECLR - private bool IsIncorrectNativeLanguageForSinhala() - { - return IsOsWin7OrPrior() - && (sName == "si-LK" || sName == "si") - && !IsReplacementCulture; - } -#endif - /////////// // Region // /////////// @@ -1415,7 +1092,6 @@ namespace System.Globalization // region name (eg US) internal String SREGIONNAME { - [System.Security.SecurityCritical] // auto-generated get { if (this.sRegionName == null) @@ -1451,18 +1127,10 @@ namespace System.Globalization // localized name for the country internal string SLOCALIZEDCOUNTRY { - [System.Security.SecurityCritical] // auto-generated get { if (this.sLocalizedCountry == null) { -#if !FEATURE_CORECLR - String resourceKey = "Globalization.ri_" + this.SREGIONNAME; - if (IsResourcePresent(resourceKey)) - { - this.sLocalizedCountry = Environment.GetResourceString(resourceKey); - } -#endif // If it hasn't been found (Windows 8 and up), fallback to the system if (String.IsNullOrEmpty(this.sLocalizedCountry)) { @@ -1484,7 +1152,6 @@ namespace System.Globalization // english country name (RegionInfo) ie: Germany internal String SENGCOUNTRY { - [System.Security.SecurityCritical] // auto-generated get { if (this.sEnglishCountry == null) @@ -1498,7 +1165,6 @@ namespace System.Globalization // native country name (RegionInfo) ie: Deutschland internal String SNATIVECOUNTRY { - [System.Security.SecurityCritical] // auto-generated get { if (this.sNativeCountry == null) @@ -1512,7 +1178,6 @@ namespace System.Globalization // ISO 3166 Country Name internal String SISO3166CTRYNAME { - [System.Security.SecurityCritical] // auto-generated get { if (this.sISO3166CountryName == null) @@ -1526,7 +1191,6 @@ namespace System.Globalization // ISO 3166 Country Name internal String SISO3166CTRYNAME2 { - [System.Security.SecurityCritical] // auto-generated get { if (this.sISO3166CountryName2 == null) @@ -1540,7 +1204,6 @@ namespace System.Globalization // abbreviated Country Name (windows version, non-standard, avoid) internal String SABBREVCTRYNAME { - [System.Security.SecurityCritical] // auto-generated get { if (this.sAbbrevCountry == null) @@ -1584,7 +1247,6 @@ namespace System.Globalization // Console fallback name (ie: locale to use for console apps for unicode-only locales) internal String SCONSOLEFALLBACKNAME { - [System.Security.SecurityCritical] // auto-generated get { if (this.sConsoleFallbackName == null) @@ -1624,7 +1286,6 @@ namespace System.Globalization // (user can override) grouping of digits internal int[] WAGROUPING { - [System.Security.SecurityCritical] // auto-generated get { if (this.waGrouping == null || UseUserOverride) @@ -1642,7 +1303,6 @@ namespace System.Globalization // Not a Number internal String SNAN { - [System.Security.SecurityCritical] // auto-generated get { if (this.sNaN == null) @@ -1656,7 +1316,6 @@ namespace System.Globalization // + Infinity internal String SPOSINFINITY { - [System.Security.SecurityCritical] // auto-generated get { if (this.sPositiveInfinity == null) @@ -1670,7 +1329,6 @@ namespace System.Globalization // - Infinity internal String SNEGINFINITY { - [System.Security.SecurityCritical] // auto-generated get { if (this.sNegativeInfinity == null) @@ -1717,7 +1375,6 @@ namespace System.Globalization // Percent (%) symbol internal String SPERCENT { - [System.Security.SecurityCritical] // auto-generated get { if (this.sPercent == null) @@ -1732,7 +1389,6 @@ namespace System.Globalization // PerMille (‰) symbol internal String SPERMILLE { - [System.Security.SecurityCritical] // auto-generated get { if (this.sPerMille == null) @@ -1751,7 +1407,6 @@ namespace System.Globalization // (user can override) local monetary symbol, eg: $ internal String SCURRENCY { - [System.Security.SecurityCritical] // auto-generated get { if (this.sCurrency == null || UseUserOverride) @@ -1765,7 +1420,6 @@ namespace System.Globalization // international monetary symbol (RegionInfo), eg: USD internal String SINTLSYMBOL { - [System.Security.SecurityCritical] // auto-generated get { if (this.sIntlMonetarySymbol == null) @@ -1779,7 +1433,6 @@ namespace System.Globalization // English name for this currency (RegionInfo), eg: US Dollar internal String SENGLISHCURRENCY { - [System.Security.SecurityCritical] // auto-generated get { if (this.sEnglishCurrency == null) @@ -1793,7 +1446,6 @@ namespace System.Globalization // Native name for this currency (RegionInfo), eg: Schweiz Frank internal String SNATIVECURRENCY { - [System.Security.SecurityCritical] // auto-generated get { if (this.sNativeCurrency == null) @@ -1811,7 +1463,6 @@ namespace System.Globalization // (user can override) monetary grouping of digits internal int[] WAMONGROUPING { - [System.Security.SecurityCritical] // auto-generated get { if (this.waMonetaryGrouping == null || UseUserOverride) @@ -1845,7 +1496,6 @@ namespace System.Globalization // (user can override) list Separator internal String SLIST { - [System.Security.SecurityCritical] // auto-generated get { if (this.sListSeparator == null || UseUserOverride) @@ -1872,7 +1522,6 @@ namespace System.Globalization // (user can override) AM designator internal String SAM1159 { - [System.Security.SecurityCritical] // auto-generated get { if (this.sAM1159 == null || UseUserOverride) @@ -1886,7 +1535,6 @@ namespace System.Globalization // (user can override) PM designator internal String SPM2359 { - [System.Security.SecurityCritical] // auto-generated get { if (this.sPM2359 == null || UseUserOverride) @@ -2067,7 +1715,6 @@ namespace System.Globalization // time duration format internal String[] SADURATION { - [System.Security.SecurityCritical] // auto-generated get { if (this.saDurationFormats == null) @@ -2198,7 +1845,7 @@ namespace System.Globalization // We then have to copy that list to a new array of the right size. // Default calendar should be first int[] calendarInts = new int[23]; - Contract.Assert(this.sWindowsName != null, "[CultureData.CalendarIds] Expected this.sWindowsName to be populated by COMNlsInfo::nativeInitCultureData already"); + Debug.Assert(this.sWindowsName != null, "[CultureData.CalendarIds] Expected this.sWindowsName to be populated by COMNlsInfo::nativeInitCultureData already"); int count = CalendarData.nativeGetCalendars(this.sWindowsName, this.bUseOverrides, calendarInts); // See if we had a calendar to add. @@ -2243,7 +1890,6 @@ namespace System.Globalization // Want 1st calendar to be default // Prior to Vista the enumeration didn't have default calendar first // Only a coreclr concern, culture.dll does the right thing. -#if FEATURE_CORECLR if (temp.Length > 1) { int i = DoGetLocaleInfoInt(LOCALE_ICALENDARTYPE); @@ -2253,7 +1899,6 @@ namespace System.Globalization temp[0] = i; } } -#endif this.waCalendars = temp; } @@ -2272,7 +1917,7 @@ namespace System.Globalization internal CalendarData GetCalendar(int calendarId) { - Contract.Assert(calendarId > 0 && calendarId <= CalendarData.MAX_CALENDARS, + Debug.Assert(calendarId > 0 && calendarId <= CalendarData.MAX_CALENDARS, "[CultureData.GetCalendar] Expect calendarId to be in a valid range"); // arrays are 0 based, calendarIds are 1 based @@ -2291,16 +1936,8 @@ namespace System.Globalization // Make sure that calendar has data if (calendarData == null || UseUserOverride) { - Contract.Assert(this.sWindowsName != null, "[CultureData.GetCalendar] Expected this.sWindowsName to be populated by COMNlsInfo::nativeInitCultureData already"); + Debug.Assert(this.sWindowsName != null, "[CultureData.GetCalendar] Expected this.sWindowsName to be populated by COMNlsInfo::nativeInitCultureData already"); calendarData = new CalendarData(this.sWindowsName, calendarId, this.UseUserOverride); -#if !FEATURE_CORECLR - //Work around issue where Win7 data for MonthDay contains invalid two sets of data separated by semicolon - //even though MonthDay is not enumerated - if (IsOsWin7OrPrior() && !IsSupplementalCustomCulture && !IsReplacementCulture) - { - calendarData.FixupWin7MonthDaySemicolonBug(); - } -#endif calendars[calendarIndex] = calendarData; } @@ -2344,7 +1981,7 @@ namespace System.Globalization { if (this.iReadingLayout == undef) { - Contract.Assert(this.sRealName != null, "[CultureData.IsRightToLeft] Expected this.sRealName to be populated by COMNlsInfo::nativeInitCultureData already"); + Debug.Assert(this.sRealName != null, "[CultureData.IsRightToLeft] Expected this.sRealName to be populated by COMNlsInfo::nativeInitCultureData already"); this.iReadingLayout = DoGetLocaleInfoInt(LOCALE_IREADINGLAYOUT); } @@ -2361,7 +1998,6 @@ namespace System.Globalization // es-ES_tradnl -> es-ES internal String STEXTINFO // Text info name to use for text information { - [System.Security.SecuritySafeCritical] get { if (this.sTextInfo == null) @@ -2387,7 +2023,6 @@ namespace System.Globalization // Compare info name (including sorting key) to use if custom internal String SCOMPAREINFO { - [System.Security.SecuritySafeCritical] get { if (this.sCompareInfo == null) @@ -2423,7 +2058,6 @@ namespace System.Globalization private String SSCRIPTS { - [System.Security.SecuritySafeCritical] // auto-generated get { if (this.sScripts == null) @@ -2436,7 +2070,6 @@ namespace System.Globalization private String SOPENTYPELANGUAGETAG { - [System.Security.SecuritySafeCritical] // auto-generated get { return DoGetLocaleInfo(LOCALE_SOPENTYPELANGUAGETAG); @@ -2445,7 +2078,6 @@ namespace System.Globalization private String FONTSIGNATURE { - [System.Security.SecuritySafeCritical] // auto-generated get { if (this.fontSignature == null) @@ -2458,7 +2090,6 @@ namespace System.Globalization private String SKEYBOARDSTOINSTALL { - [System.Security.SecuritySafeCritical] // auto-generated get { return DoGetLocaleInfo(LOCALE_SKEYBOARDSTOINSTALL); @@ -2516,7 +2147,6 @@ namespace System.Globalization // Obtain locale name from LCID // NOTE: This will get neutral names, unlike the OS API - [System.Security.SecuritySafeCritical] // auto-generated [MethodImplAttribute(MethodImplOptions.InternalCall)] internal static extern int LocaleNameToLCID(String localeName); @@ -2528,7 +2158,7 @@ namespace System.Globalization { if (this.iLanguage == 0) { - Contract.Assert(this.sRealName != null, "[CultureData.ILANGUAGE] Expected this.sRealName to be populated by COMNlsInfo::nativeInitCultureData already"); + Debug.Assert(this.sRealName != null, "[CultureData.ILANGUAGE] Expected this.sRealName to be populated by COMNlsInfo::nativeInitCultureData already"); this.iLanguage = LocaleNameToLCID(this.sRealName); } return this.iLanguage; @@ -2584,21 +2214,21 @@ namespace System.Globalization // All of our era names internal String[] EraNames(int calendarId) { - Contract.Assert(calendarId > 0, "[CultureData.saEraNames] Expected Calendar.ID > 0"); + Debug.Assert(calendarId > 0, "[CultureData.saEraNames] Expected Calendar.ID > 0"); return this.GetCalendar(calendarId).saEraNames; } internal String[] AbbrevEraNames(int calendarId) { - Contract.Assert(calendarId > 0, "[CultureData.saAbbrevEraNames] Expected Calendar.ID > 0"); + Debug.Assert(calendarId > 0, "[CultureData.saAbbrevEraNames] Expected Calendar.ID > 0"); return this.GetCalendar(calendarId).saAbbrevEraNames; } internal String[] AbbreviatedEnglishEraNames(int calendarId) { - Contract.Assert(calendarId > 0, "[CultureData.saAbbrevEraNames] Expected Calendar.ID > 0"); + Debug.Assert(calendarId > 0, "[CultureData.saAbbrevEraNames] Expected Calendar.ID > 0"); return this.GetCalendar(calendarId).saAbbrevEnglishEraNames; } @@ -2610,7 +2240,6 @@ namespace System.Globalization // Time separator (derived from time format) internal String TimeSeparator { - [System.Security.SecuritySafeCritical] // auto-generated get { if (sTimeSeparator == null || UseUserOverride) @@ -2856,8 +2485,8 @@ namespace System.Globalization private static int IndexOfTimePart(string format, int startIndex, string timeParts) { - Contract.Assert(startIndex >= 0, "startIndex cannot be negative"); - Contract.Assert(timeParts.IndexOfAny(new char[] { '\'', '\\' }) == -1, "timeParts cannot include quote characters"); + Debug.Assert(startIndex >= 0, "startIndex cannot be negative"); + Debug.Assert(timeParts.IndexOfAny(new char[] { '\'', '\\' }) == -1, "timeParts cannot include quote characters"); bool inQuote = false; for (int i = startIndex; i < format.Length; ++i) { @@ -2892,16 +2521,14 @@ namespace System.Globalization return -1; } - [System.Security.SecurityCritical] string DoGetLocaleInfo(uint lctype) { - Contract.Assert(this.sWindowsName != null, "[CultureData.DoGetLocaleInfo] Expected this.sWindowsName to be populated by COMNlsInfo::nativeInitCultureData already"); + Debug.Assert(this.sWindowsName != null, "[CultureData.DoGetLocaleInfo] Expected this.sWindowsName to be populated by COMNlsInfo::nativeInitCultureData already"); return DoGetLocaleInfo(this.sWindowsName, lctype); } // For LOCALE_SPARENT we need the option of using the "real" name (forcing neutral names) instead of the // "windows" name, which can be specific for downlevel (< windows 7) os's. - [System.Security.SecurityCritical] // auto-generated string DoGetLocaleInfo(string localeName, uint lctype) { // Fix lctype if we don't want overrides @@ -2911,7 +2538,7 @@ namespace System.Globalization } // Ask OS for data - Contract.Assert(localeName != null, "[CultureData.DoGetLocaleInfo] Expected localeName to be not be null"); + Debug.Assert(localeName != null, "[CultureData.DoGetLocaleInfo] Expected localeName to be not be null"); string result = CultureInfo.nativeGetLocaleInfoEx(localeName, lctype); if (result == null) { @@ -2932,7 +2559,7 @@ namespace System.Globalization // Ask OS for data, note that we presume it returns success, so we have to know that // sWindowsName is valid before calling. - Contract.Assert(this.sWindowsName != null, "[CultureData.DoGetLocaleInfoInt] Expected this.sWindowsName to be populated by COMNlsInfo::nativeInitCultureData already"); + Debug.Assert(this.sWindowsName != null, "[CultureData.DoGetLocaleInfoInt] Expected this.sWindowsName to be populated by COMNlsInfo::nativeInitCultureData already"); int result = CultureInfo.nativeGetLocaleInfoExInt(this.sWindowsName, lctype); return result; @@ -2941,7 +2568,7 @@ namespace System.Globalization String[] DoEnumTimeFormats() { // Note that this gets overrides for us all the time - Contract.Assert(this.sWindowsName != null, "[CultureData.DoEnumTimeFormats] Expected this.sWindowsName to be populated by COMNlsInfo::nativeInitCultureData already"); + Debug.Assert(this.sWindowsName != null, "[CultureData.DoEnumTimeFormats] Expected this.sWindowsName to be populated by COMNlsInfo::nativeInitCultureData already"); String[] result = ReescapeWin32Strings(nativeEnumTimeFormats(this.sWindowsName, 0, UseUserOverride)); return result; @@ -2950,7 +2577,7 @@ namespace System.Globalization String[] DoEnumShortTimeFormats() { // Note that this gets overrides for us all the time - Contract.Assert(this.sWindowsName != null, "[CultureData.DoEnumShortTimeFormats] Expected this.sWindowsName to be populated by COMNlsInfo::nativeInitCultureData already"); + Debug.Assert(this.sWindowsName != null, "[CultureData.DoEnumShortTimeFormats] Expected this.sWindowsName to be populated by COMNlsInfo::nativeInitCultureData already"); String[] result = ReescapeWin32Strings(nativeEnumTimeFormats(this.sWindowsName, TIME_NOSECONDS, UseUserOverride)); return result; @@ -2975,7 +2602,6 @@ namespace System.Globalization // not affected by the Calendar property in DTFI. // //////////////////////////////////////////////////////////////////////////// - [System.Security.SecurityCritical] // auto-generated internal void GetNFIValues(NumberFormatInfo nfi) { if (this.IsInvariantCulture) @@ -3013,7 +2639,7 @@ namespace System.Globalization // // Ask native side for our data. // - Contract.Assert(this.sWindowsName != null, "[CultureData.GetNFIValues] Expected this.sWindowsName to be populated by COMNlsInfo::nativeInitCultureData already"); + Debug.Assert(this.sWindowsName != null, "[CultureData.GetNFIValues] Expected this.sWindowsName to be populated by COMNlsInfo::nativeInitCultureData already"); CultureData.nativeGetNumberFormatInfoValues(this.sWindowsName, nfi, UseUserOverride); } @@ -3056,17 +2682,6 @@ namespace System.Globalization { nfi.currencyDecimalSeparator = nfi.numberDecimalSeparator; } - -#if !FEATURE_CORECLR - if ((932 == this.IDEFAULTANSICODEPAGE) || - (949 == this.IDEFAULTANSICODEPAGE)) - { - // Legacy behavior for cultures that use Japanese/Korean default ANSI code pages - // Note that this is a code point, not a character. On Japanese/Korean machines this - // will be rendered as their currency symbol, not rendered as a "\" - nfi.ansiCurrencySymbol = "\x5c"; - } -#endif // !FEATURE_CORECLR } static private int ConvertFirstDayOfWeekMonToSun(int iTemp) @@ -3333,20 +2948,16 @@ namespace System.Globalization internal const uint TIME_NOSECONDS = 0x00000002; // Don't use seconds (get short time format for enumtimeformats on win7+) // Get our initial minimal culture data (name, parent, etc.) - [System.Security.SecuritySafeCritical] // auto-generated [MethodImplAttribute(MethodImplOptions.InternalCall)] internal static extern bool nativeInitCultureData(CultureData cultureData); // Grab the NumberFormatInfo data - [System.Security.SecuritySafeCritical] // auto-generated [MethodImplAttribute(MethodImplOptions.InternalCall)] internal static extern bool nativeGetNumberFormatInfoValues(String localeName, NumberFormatInfo nfi, bool useUserOverride); - [System.Security.SecuritySafeCritical] // auto-generated [MethodImplAttribute(MethodImplOptions.InternalCall)] private static extern String[] nativeEnumTimeFormats(String localeName, uint dwFlags, bool useUserOverride); - [System.Security.SecurityCritical] // auto-generated [SuppressUnmanagedCodeSecurityAttribute()] [DllImport(JitHelpers.QCall, CharSet = CharSet.Unicode)] internal static extern int nativeEnumCultureNames(int cultureTypes, ObjectHandleOnStack retStringArray); diff --git a/src/mscorlib/src/System/Globalization/CultureInfo.cs b/src/mscorlib/src/System/Globalization/CultureInfo.cs index d620d2dc24..9f306c3c99 100644 --- a/src/mscorlib/src/System/Globalization/CultureInfo.cs +++ b/src/mscorlib/src/System/Globalization/CultureInfo.cs @@ -39,6 +39,7 @@ namespace System.Globalization { using System.Security.Permissions; using System.Reflection; using Microsoft.Win32; + using System.Diagnostics; using System.Diagnostics.Contracts; using System.Resources; @@ -66,10 +67,6 @@ namespace System.Globalization { internal bool m_isReadOnly; internal CompareInfo compareInfo; internal TextInfo textInfo; - // Not serialized for now since we only build it privately for use in the CARIB (so rebuilding is OK) -#if !FEATURE_CORECLR - [NonSerialized]internal RegionInfo regionInfo; -#endif internal NumberFormatInfo numInfo; internal DateTimeFormatInfo dateTimeInfo; internal Calendar calendar; @@ -88,10 +85,8 @@ namespace System.Globalization { #if FEATURE_LEAK_CULTURE_INFO [NonSerialized]private bool m_isSafeCrossDomain; [NonSerialized]private int m_createdDomainID; -#endif // !FEATURE_CORECLR -#if !FEATURE_CORECLR +#endif // !FEATURE_LEAK_CULTURE_INFO [NonSerialized]private CultureInfo m_consoleFallbackCulture; -#endif // !FEATURE_CORECLR // Names are confusing. Here are 3 names we have: // @@ -152,7 +147,6 @@ namespace System.Globalization { #if FEATURE_APPX // When running under AppX, we use this to get some information about the language list - [SecurityCritical] private static volatile WindowsRuntimeResourceManagerBase s_WindowsRuntimeResourceManager; [ThreadStatic] @@ -197,7 +191,6 @@ namespace System.Globalization { return true; } - [System.Security.SecuritySafeCritical] // auto-generated static CultureInfo InitUserDefaultCulture() { String strDefault = GetDefaultLocaleName(LOCALE_USER_DEFAULT); @@ -241,7 +234,6 @@ namespace System.Globalization { } #if FEATURE_APPX - [SecuritySafeCritical] internal static CultureInfo GetCultureInfoForUserPreferredLanguageInAppX() { // If a call to GetCultureInfoForUserPreferredLanguageInAppX() generated a recursive @@ -287,7 +279,6 @@ namespace System.Globalization { return toReturn; } - [SecuritySafeCritical] internal static bool SetCultureInfoForUserPreferredLanguageInAppX(CultureInfo ci) { // If running within a compilation process (mscorsvw.exe, for example), it is illegal to @@ -323,7 +314,7 @@ namespace System.Globalization { public CultureInfo(String name, bool useUserOverride) { if (name==null) { - throw new ArgumentNullException("name", + throw new ArgumentNullException(nameof(name), Environment.GetResourceString("ArgumentNull_String")); } Contract.EndContractBlock(); @@ -332,7 +323,7 @@ namespace System.Globalization { this.m_cultureData = CultureData.GetCultureData(name, useUserOverride); if (this.m_cultureData == null) { - throw new CultureNotFoundException("name", name, Environment.GetResourceString("Argument_CultureNotSupported")); + throw new CultureNotFoundException(nameof(name), name, Environment.GetResourceString("Argument_CultureNotSupported")); } this.m_name = this.m_cultureData.CultureName; @@ -347,7 +338,7 @@ namespace System.Globalization { public CultureInfo(int culture, bool useUserOverride) { // We don't check for other invalid LCIDS here... if (culture < 0) { - throw new ArgumentOutOfRangeException("culture", + throw new ArgumentOutOfRangeException(nameof(culture), Environment.GetResourceString("ArgumentOutOfRange_NeedPosNum")); } Contract.EndContractBlock(); @@ -367,7 +358,7 @@ namespace System.Globalization { // Can't support unknown custom cultures and we do not support neutral or // non-custom user locales. throw new CultureNotFoundException( - "culture", culture, Environment.GetResourceString("Argument_CultureNotSupported")); + nameof(culture), culture, Environment.GetResourceString("Argument_CultureNotSupported")); default: // Now see if this LCID is supported in the system default CultureData table. @@ -413,18 +404,18 @@ namespace System.Globalization { // e.g. for es-ES_tradnl: v2 puts es-ES in m_name; v4 puts es-ES_tradnl if (m_name == null || IsAlternateSortLcid(cultureID)) { - Contract.Assert(cultureID >=0, "[CultureInfo.OnDeserialized] cultureID >= 0"); + Debug.Assert(cultureID >=0, "[CultureInfo.OnDeserialized] cultureID >= 0"); InitializeFromCultureId(cultureID, m_useUserOverride); } else { #endif - Contract.Assert(m_name != null, "[CultureInfo.OnDeserialized] m_name != null"); + Debug.Assert(m_name != null, "[CultureInfo.OnDeserialized] m_name != null"); this.m_cultureData = CultureData.GetCultureData(m_name, m_useUserOverride); if (this.m_cultureData == null) throw new CultureNotFoundException( - "m_name", m_name, Environment.GetResourceString("Argument_CultureNotSupported")); + nameof(m_name), m_name, Environment.GetResourceString("Argument_CultureNotSupported")); #if FEATURE_USE_LCID } @@ -486,14 +477,14 @@ namespace System.Globalization { // For Silverlight, the answer is always no. internal bool IsSafeCrossDomain { get { - Contract.Assert(m_createdDomainID != 0, "[CultureInfo.IsSafeCrossDomain] m_createdDomainID != 0"); + Debug.Assert(m_createdDomainID != 0, "[CultureInfo.IsSafeCrossDomain] m_createdDomainID != 0"); return m_isSafeCrossDomain; } } internal int CreatedDomainID { get { - Contract.Assert(m_createdDomainID != 0, "[CultureInfo.CreatedDomain] m_createdDomainID != 0"); + Debug.Assert(m_createdDomainID != 0, "[CultureInfo.CreatedDomain] m_createdDomainID != 0"); return m_createdDomainID; } } @@ -540,7 +531,7 @@ namespace System.Globalization { internal CultureInfo(String cultureName, String textAndCompareCultureName) { if (cultureName==null) { - throw new ArgumentNullException("cultureName", + throw new ArgumentNullException(nameof(cultureName), Environment.GetResourceString("ArgumentNull_String")); } Contract.EndContractBlock(); @@ -548,7 +539,7 @@ namespace System.Globalization { this.m_cultureData = CultureData.GetCultureData(cultureName, false); if (this.m_cultureData == null) throw new CultureNotFoundException( - "cultureName", cultureName, Environment.GetResourceString("Argument_CultureNotSupported")); + nameof(cultureName), cultureName, Environment.GetResourceString("Argument_CultureNotSupported")); this.m_name = this.m_cultureData.CultureName; @@ -644,7 +635,7 @@ namespace System.Globalization { } internal static bool VerifyCultureName(CultureInfo culture, bool throwException) { - Contract.Assert(culture!=null, "[CultureInfo.VerifyCultureName]culture!=null"); + Debug.Assert(culture!=null, "[CultureInfo.VerifyCultureName]culture!=null"); //If we have an instance of one of our CultureInfos, the user can't have changed the //name and we know that all names are valid in files. @@ -672,9 +663,6 @@ namespace System.Globalization { get { Contract.Ensures(Contract.Result<CultureInfo>() != null); -#if !FEATURE_CORECLR - return Thread.CurrentThread.CurrentCulture; -#else // In the case of CoreCLR, Thread.m_CurrentCulture and // Thread.m_CurrentUICulture are thread static so as not to let // CultureInfo objects leak across AppDomain boundaries. The @@ -695,13 +683,12 @@ namespace System.Globalization { s_DefaultThreadCurrentCulture ?? s_userDefaultCulture ?? UserDefaultCulture; -#endif } set { #if FEATURE_APPX if (value == null) { - throw new ArgumentNullException("value"); + throw new ArgumentNullException(nameof(value)); } if (AppDomain.IsAppXModel()) { @@ -770,9 +757,6 @@ namespace System.Globalization { get { Contract.Ensures(Contract.Result<CultureInfo>() != null); -#if !FEATURE_CORECLR - return Thread.CurrentThread.CurrentUICulture; -#else // In the case of CoreCLR, Thread.m_CurrentCulture and // Thread.m_CurrentUICulture are thread static so as not to let // CultureInfo objects leak across AppDomain boundaries. The @@ -793,13 +777,12 @@ namespace System.Globalization { s_DefaultThreadCurrentUICulture ?? s_userDefaultUICulture ?? UserDefaultUICulture; -#endif } set { #if FEATURE_APPX if (value == null) { - throw new ArgumentNullException("value"); + throw new ArgumentNullException(nameof(value)); } if (AppDomain.IsAppXModel()) { @@ -843,10 +826,6 @@ namespace System.Globalization { return s_DefaultThreadCurrentCulture; } - [System.Security.SecuritySafeCritical] // auto-generated -#pragma warning disable 618 - [SecurityPermission(SecurityAction.Demand, ControlThread = true)] -#pragma warning restore 618 set { // If you add pre-conditions to this method, check to see if you also need to @@ -861,10 +840,6 @@ namespace System.Globalization { return s_DefaultThreadCurrentUICulture; } - [System.Security.SecuritySafeCritical] // auto-generated -#pragma warning disable 618 - [SecurityPermission(SecurityAction.Demand, ControlThread = true)] -#pragma warning restore 618 set { //If they're trying to use a Culture with a name that we can't use in resource lookup, @@ -915,24 +890,23 @@ namespace System.Globalization { public virtual CultureInfo Parent { - [System.Security.SecuritySafeCritical] // auto-generated get { Contract.Ensures(Contract.Result<CultureInfo>() != null); + CultureInfo culture = null; if (null == m_parent) { try { string parentName = this.m_cultureData.SPARENT; - if (String.IsNullOrEmpty(parentName)) { - m_parent = InvariantCulture; + culture = InvariantCulture; } else { - m_parent = new CultureInfo(parentName, this.m_cultureData.UseUserOverride); + culture = new CultureInfo(parentName, this.m_cultureData.UseUserOverride); } } catch (ArgumentException) @@ -940,8 +914,10 @@ namespace System.Globalization { // For whatever reason our IPARENT or SPARENT wasn't correct, so use invariant // We can't allow ourselves to fail. In case of custom cultures the parent of the // current custom culture isn't installed. - m_parent = InvariantCulture; + culture = InvariantCulture; } + + Interlocked.CompareExchange<CultureInfo>(ref m_parent, culture, null); } return m_parent; } @@ -1034,7 +1010,6 @@ namespace System.Globalization { } } -#if !FEATURE_CORECLR [System.Runtime.InteropServices.ComVisible(false)] public String IetfLanguageTag { @@ -1054,7 +1029,6 @@ namespace System.Globalization { } } } -#endif //////////////////////////////////////////////////////////////////////// // @@ -1067,11 +1041,10 @@ namespace System.Globalization { //////////////////////////////////////////////////////////////////////// public virtual String DisplayName { - [System.Security.SecuritySafeCritical] // auto-generated get { Contract.Ensures(Contract.Result<String>() != null); - Contract.Assert(m_name != null, "[CultureInfo.DisplayName]Always expect m_name to be set"); + Debug.Assert(m_name != null, "[CultureInfo.DisplayName]Always expect m_name to be set"); return m_cultureData.SLOCALIZEDDISPLAYNAME; } @@ -1087,7 +1060,6 @@ namespace System.Globalization { // //////////////////////////////////////////////////////////////////////// public virtual String NativeName { - [System.Security.SecuritySafeCritical] // auto-generated get { Contract.Ensures(Contract.Result<String>() != null); return (this.m_cultureData.SNATIVEDISPLAYNAME); @@ -1104,7 +1076,6 @@ namespace System.Globalization { // //////////////////////////////////////////////////////////////////////// public virtual String EnglishName { - [System.Security.SecuritySafeCritical] // auto-generated get { Contract.Ensures(Contract.Result<String>() != null); return (this.m_cultureData.SENGDISPLAYNAME); @@ -1113,7 +1084,6 @@ namespace System.Globalization { // ie: en public virtual String TwoLetterISOLanguageName { - [System.Security.SecuritySafeCritical] // auto-generated get { Contract.Ensures(Contract.Result<String>() != null); return (this.m_cultureData.SISO639LANGNAME); @@ -1122,7 +1092,6 @@ namespace System.Globalization { // ie: eng public virtual String ThreeLetterISOLanguageName { - [System.Security.SecuritySafeCritical] // auto-generated get { Contract.Ensures(Contract.Result<String>() != null); return (this.m_cultureData.SISO639LANGNAME2); @@ -1138,7 +1107,6 @@ namespace System.Globalization { // //////////////////////////////////////////////////////////////////////// public virtual String ThreeLetterWindowsLanguageName { - [System.Security.SecuritySafeCritical] // auto-generated get { Contract.Ensures(Contract.Result<String>() != null); return (this.m_cultureData.SABBREVLANGNAME); @@ -1178,31 +1146,6 @@ namespace System.Globalization { } } -#if !FEATURE_CORECLR - //////////////////////////////////////////////////////////////////////// - // - // RegionInfo - // - // Gets the RegionInfo for this culture. - // - //////////////////////////////////////////////////////////////////////// - private RegionInfo Region - { - get - { - if (regionInfo==null) - { - // Make a new regionInfo - RegionInfo tempRegionInfo = new RegionInfo(this.m_cultureData); - regionInfo = tempRegionInfo; - } - return (regionInfo); - } - } -#endif // FEATURE_CORECLR - - - //////////////////////////////////////////////////////////////////////// // // TextInfo @@ -1294,7 +1237,7 @@ namespace System.Globalization { { Contract.Ensures(Contract.Result<String>() != null); - Contract.Assert(m_name != null, "[CultureInfo.ToString]Always expect m_name to be set"); + Debug.Assert(m_name != null, "[CultureInfo.ToString]Always expect m_name to be set"); return m_name; } @@ -1315,7 +1258,6 @@ namespace System.Globalization { } } -#if !FEATURE_CORECLR [System.Runtime.InteropServices.ComVisible(false)] public CultureTypes CultureTypes { @@ -1333,15 +1275,14 @@ namespace System.Globalization { // Disable warning 618: System.Globalization.CultureTypes.FrameworkCultures' is obsolete #pragma warning disable 618 types |= m_cultureData.IsFramework ? CultureTypes.FrameworkCultures : 0; - #pragma warning restore 618 + types |= m_cultureData.IsSupplementalCustomCulture ? CultureTypes.UserCustomCulture : 0; types |= m_cultureData.IsReplacementCulture ? CultureTypes.ReplacementCultures | CultureTypes.UserCustomCulture : 0; return types; } } -#endif public virtual NumberFormatInfo NumberFormat { get @@ -1351,13 +1292,13 @@ namespace System.Globalization { if (numInfo == null) { NumberFormatInfo temp = new NumberFormatInfo(this.m_cultureData); temp.isReadOnly = m_isReadOnly; - numInfo = temp; + Interlocked.CompareExchange(ref numInfo, temp, null); } return (numInfo); } set { if (value == null) { - throw new ArgumentNullException("value", + throw new ArgumentNullException(nameof(value), Environment.GetResourceString("ArgumentNull_Obj")); } Contract.EndContractBlock(); @@ -1385,15 +1326,14 @@ namespace System.Globalization { DateTimeFormatInfo temp = new DateTimeFormatInfo( this.m_cultureData, this.Calendar); temp.m_isReadOnly = m_isReadOnly; - System.Threading.Thread.MemoryBarrier(); - dateTimeInfo = temp; + Interlocked.CompareExchange(ref dateTimeInfo, temp, null); } return (dateTimeInfo); } set { if (value == null) { - throw new ArgumentNullException("value", + throw new ArgumentNullException(nameof(value), Environment.GetResourceString("ArgumentNull_Obj")); } Contract.EndContractBlock(); @@ -1402,17 +1342,16 @@ namespace System.Globalization { } } - - public void ClearCachedData() { s_userDefaultUICulture = null; s_userDefaultCulture = null; RegionInfo.s_currentRegionInfo = null; -#if !FEATURE_CORECLR // System.TimeZone does not exist in CoreCLR +#pragma warning disable CS0618 TimeZone.ResetTimeZone(); -#endif // FEATURE_CORECLR +#pragma warning restore CS0618 TimeZoneInfo.ClearCachedData(); + // Delete the cached cultures. s_LcidCachedCultures = null; s_NameCachedCultures = null; @@ -1438,7 +1377,7 @@ namespace System.Globalization { //This function exists as a shortcut to prevent us from loading all of the non-gregorian //calendars unless they're required. internal static Calendar GetCalendarInstanceRare(int calType) { - Contract.Assert(calType!=Calendar.CAL_GREGORIAN, "calType!=Calendar.CAL_GREGORIAN"); + Debug.Assert(calType!=Calendar.CAL_GREGORIAN, "calType!=Calendar.CAL_GREGORIAN"); switch (calType) { case Calendar.CAL_GREGORIAN_US: // Gregorian (U.S.) calendar @@ -1490,7 +1429,7 @@ namespace System.Globalization { get { Contract.Ensures(Contract.Result<Calendar>() != null); if (calendar == null) { - Contract.Assert(this.m_cultureData.CalendarIds.Length > 0, "this.m_cultureData.CalendarIds.Length > 0"); + Debug.Assert(this.m_cultureData.CalendarIds.Length > 0, "this.m_cultureData.CalendarIds.Length > 0"); // Get the default calendar for this culture. Note that the value can be // from registry if this is a user default culture. Calendar newObj = this.m_cultureData.DefaultCalendar; @@ -1534,8 +1473,6 @@ namespace System.Globalization { } } -#if !FEATURE_CORECLR - [System.Security.SecuritySafeCritical] // auto-generated [System.Runtime.InteropServices.ComVisible(false)] public CultureInfo GetConsoleFallbackUICulture() { @@ -1550,7 +1487,6 @@ namespace System.Globalization { } return (temp); } -#endif public virtual Object Clone() { @@ -1595,7 +1531,7 @@ namespace System.Globalization { public static CultureInfo ReadOnly(CultureInfo ci) { if (ci == null) { - throw new ArgumentNullException("ci"); + throw new ArgumentNullException(nameof(ci)); } Contract.Ensures(Contract.Result<CultureInfo>() != null); Contract.EndContractBlock(); @@ -1827,7 +1763,7 @@ namespace System.Globalization { // the altCulture code path for SQL Server. // Also check for zero as this would fail trying to add as a key to the hash. if (culture <= 0) { - throw new ArgumentOutOfRangeException("culture", + throw new ArgumentOutOfRangeException(nameof(culture), Environment.GetResourceString("ArgumentOutOfRange_NeedPosNum")); } Contract.Ensures(Contract.Result<CultureInfo>() != null); @@ -1836,7 +1772,7 @@ namespace System.Globalization { if (null == retval) { throw new CultureNotFoundException( - "culture", culture, Environment.GetResourceString("Argument_CultureNotSupported")); + nameof(culture), culture, Environment.GetResourceString("Argument_CultureNotSupported")); } return retval; } @@ -1849,7 +1785,7 @@ namespace System.Globalization { // Make sure we have a valid, non-zero length string as name if (name == null) { - throw new ArgumentNullException("name"); + throw new ArgumentNullException(nameof(name)); } Contract.Ensures(Contract.Result<CultureInfo>() != null); Contract.EndContractBlock(); @@ -1858,7 +1794,7 @@ namespace System.Globalization { if (retval == null) { throw new CultureNotFoundException( - "name", name, Environment.GetResourceString("Argument_CultureNotSupported")); + nameof(name), name, Environment.GetResourceString("Argument_CultureNotSupported")); } return retval; @@ -1871,12 +1807,12 @@ namespace System.Globalization { // Make sure we have a valid, non-zero length string as name if (null == name) { - throw new ArgumentNullException("name"); + throw new ArgumentNullException(nameof(name)); } if (null == altName) { - throw new ArgumentNullException("altName"); + throw new ArgumentNullException(nameof(altName)); } Contract.Ensures(Contract.Result<CultureInfo>() != null); Contract.EndContractBlock(); @@ -1884,7 +1820,7 @@ namespace System.Globalization { CultureInfo retval = GetCultureInfoHelper(-1, name, altName); if (retval == null) { - throw new CultureNotFoundException("name or altName", + throw new CultureNotFoundException(nameof(name) + " or " + nameof(altName), String.Format( CultureInfo.CurrentCulture, Environment.GetResourceString("Argument_OneOfCulturesNotSupported"), @@ -1904,7 +1840,7 @@ namespace System.Globalization { if (name == "zh-CHT" || name == "zh-CHS") { throw new CultureNotFoundException( - "name", + nameof(name), String.Format(CultureInfo.CurrentCulture, Environment.GetResourceString("Argument_CultureIetfNotSupported"), name) ); } @@ -1915,7 +1851,7 @@ namespace System.Globalization { if (ci.LCID > 0xffff || ci.LCID == 0x040a) { throw new CultureNotFoundException( - "name", + nameof(name), String.Format(CultureInfo.CurrentCulture, Environment.GetResourceString("Argument_CultureIetfNotSupported"), name) ); } @@ -1943,22 +1879,18 @@ namespace System.Globalization { // // Get Locale Info Ex calls. So we don't have to muck with the different int/string return types we declared two of these: - [System.Security.SecurityCritical] // auto-generated [MethodImplAttribute(MethodImplOptions.InternalCall)] internal static extern String nativeGetLocaleInfoEx(String localeName, uint field); - [System.Security.SecuritySafeCritical] // auto-generated [MethodImplAttribute(MethodImplOptions.InternalCall)] internal static extern int nativeGetLocaleInfoExInt(String localeName, uint field); - [System.Security.SecurityCritical] // auto-generated [MethodImplAttribute(MethodImplOptions.InternalCall)] internal static extern bool nativeSetThreadLocale(String localeName); - [System.Security.SecurityCritical] private static String GetDefaultLocaleName(int localeType) { - Contract.Assert(localeType == LOCALE_USER_DEFAULT || localeType == LOCALE_SYSTEM_DEFAULT, "[CultureInfo.GetDefaultLocaleName] localeType must be LOCALE_USER_DEFAULT or LOCALE_SYSTEM_DEFAULT"); + Debug.Assert(localeType == LOCALE_USER_DEFAULT || localeType == LOCALE_SYSTEM_DEFAULT, "[CultureInfo.GetDefaultLocaleName] localeType must be LOCALE_USER_DEFAULT or LOCALE_SYSTEM_DEFAULT"); string localeName = null; if(InternalGetDefaultLocaleName(localeType, JitHelpers.GetStringHandleOnStack(ref localeName))) @@ -1969,13 +1901,11 @@ namespace System.Globalization { } // Get the default locale name - [System.Security.SecurityCritical] // auto-generated [SuppressUnmanagedCodeSecurity] [DllImport(JitHelpers.QCall, CharSet = CharSet.Unicode)] [return: MarshalAs(UnmanagedType.Bool)] private static extern bool InternalGetDefaultLocaleName(int localetype, StringHandleOnStack localeString); - [System.Security.SecuritySafeCritical] // auto-generated private static String GetUserDefaultUILanguage() { string userDefaultUiLanguage = null; @@ -1987,13 +1917,11 @@ namespace System.Globalization { } // Get the user's default UI language, return locale name - [System.Security.SecurityCritical] // auto-generated [SuppressUnmanagedCodeSecurity] [DllImport(JitHelpers.QCall, CharSet = CharSet.Unicode)] [return: MarshalAs(UnmanagedType.Bool)] private static extern bool InternalGetUserDefaultUILanguage(StringHandleOnStack userDefaultUiLanguage); - [System.Security.SecuritySafeCritical] // auto-generated private static String GetSystemDefaultUILanguage() { string systemDefaultUiLanguage = null; @@ -2005,19 +1933,14 @@ namespace System.Globalization { } - [System.Security.SecurityCritical] // auto-generated [MethodImplAttribute(MethodImplOptions.InternalCall)] [SuppressUnmanagedCodeSecurity] [DllImport(JitHelpers.QCall, CharSet = CharSet.Unicode)] [return: MarshalAs(UnmanagedType.Bool)] private static extern bool InternalGetSystemDefaultUILanguage(StringHandleOnStack systemDefaultUiLanguage); -// Added but disabled from desktop in .NET 4.0, stayed disabled in .NET 4.5 -#if FEATURE_CORECLR - [System.Security.SecurityCritical] // auto-generated [MethodImplAttribute(MethodImplOptions.InternalCall)] internal static extern String[] nativeGetResourceFallbackArray(); -#endif } } diff --git a/src/mscorlib/src/System/Globalization/CultureNotFoundException.cs b/src/mscorlib/src/System/Globalization/CultureNotFoundException.cs index 0486cc9d17..17c0b43f9c 100644 --- a/src/mscorlib/src/System/Globalization/CultureNotFoundException.cs +++ b/src/mscorlib/src/System/Globalization/CultureNotFoundException.cs @@ -66,10 +66,9 @@ namespace System.Globalization { m_invalidCultureName = (string) info.GetValue("InvalidCultureName", typeof(string)); } - [System.Security.SecurityCritical] // auto-generated_required public override void GetObjectData(SerializationInfo info, StreamingContext context) { if (info==null) { - throw new ArgumentNullException("info"); + throw new ArgumentNullException(nameof(info)); } Contract.EndContractBlock(); base.GetObjectData(info, context); diff --git a/src/mscorlib/src/System/Globalization/DateTimeFormat.cs b/src/mscorlib/src/System/Globalization/DateTimeFormat.cs index 228e5f56a2..c6e0591a74 100644 --- a/src/mscorlib/src/System/Globalization/DateTimeFormat.cs +++ b/src/mscorlib/src/System/Globalization/DateTimeFormat.cs @@ -11,6 +11,7 @@ namespace System { using System.Runtime.InteropServices; using System.Runtime.Versioning; using System.Security; + using System.Diagnostics; using System.Diagnostics.Contracts; /* @@ -139,8 +140,13 @@ namespace System { internal const String RoundtripFormat = "yyyy'-'MM'-'dd'T'HH':'mm':'ss.fffffffK"; internal const String RoundtripDateTimeUnfixed = "yyyy'-'MM'-'ddTHH':'mm':'ss zzz"; - private const int DEFAULT_ALL_DATETIMES_SIZE = 132; - + private const int DEFAULT_ALL_DATETIMES_SIZE = 132; + + internal static readonly DateTimeFormatInfo InvariantFormatInfo = CultureInfo.InvariantCulture.DateTimeFormat; + internal static readonly string[] InvariantAbbreviatedMonthNames = InvariantFormatInfo.AbbreviatedMonthNames; + internal static readonly string[] InvariantAbbreviatedDayNames = InvariantFormatInfo.AbbreviatedDayNames; + internal const string Gmt = "GMT"; + internal static String[] fixedNumberFormats = new String[] { "0", "00", @@ -166,13 +172,12 @@ namespace System { // //////////////////////////////////////////////////////////////////////////// internal static void FormatDigits(StringBuilder outputBuffer, int value, int len) { - Contract.Assert(value >= 0, "DateTimeFormat.FormatDigits(): value >= 0"); + Debug.Assert(value >= 0, "DateTimeFormat.FormatDigits(): value >= 0"); FormatDigits(outputBuffer, value, len, false); } - [System.Security.SecuritySafeCritical] // auto-generated internal unsafe static void FormatDigits(StringBuilder outputBuffer, int value, int len, bool overrideLengthLimit) { - Contract.Assert(value >= 0, "DateTimeFormat.FormatDigits(): value >= 0"); + Debug.Assert(value >= 0, "DateTimeFormat.FormatDigits(): value >= 0"); // Limit the use of this function to be two-digits, so that we have the same behavior // as RTM bits. @@ -218,7 +223,7 @@ namespace System { private static String FormatDayOfWeek(int dayOfWeek, int repeat, DateTimeFormatInfo dtfi) { - Contract.Assert(dayOfWeek >= 0 && dayOfWeek <= 6, "dayOfWeek >= 0 && dayOfWeek <= 6"); + Debug.Assert(dayOfWeek >= 0 && dayOfWeek <= 6, "dayOfWeek >= 0 && dayOfWeek <= 6"); if (repeat == 3) { return (dtfi.GetAbbreviatedDayName((DayOfWeek)dayOfWeek)); @@ -230,7 +235,7 @@ namespace System { private static String FormatMonth(int month, int repeatCount, DateTimeFormatInfo dtfi) { - Contract.Assert(month >=1 && month <= 12, "month >=1 && month <= 12"); + Debug.Assert(month >=1 && month <= 12, "month >=1 && month <= 12"); if (repeatCount == 3) { return (dtfi.GetAbbreviatedMonthName(month)); @@ -271,7 +276,7 @@ namespace System { */ private static String FormatHebrewMonthName(DateTime time, int month, int repeatCount, DateTimeFormatInfo dtfi) { - Contract.Assert(repeatCount != 3 || repeatCount != 4, "repeateCount should be 3 or 4"); + Debug.Assert(repeatCount != 3 || repeatCount != 4, "repeateCount should be 3 or 4"); if (dtfi.Calendar.IsLeapYear(dtfi.Calendar.GetYear(time))) { // This month is in a leap year return (dtfi.internalGetMonthName(month, MonthNameStyles.LeapYear, (repeatCount == 3))); @@ -703,24 +708,13 @@ namespace System { // accurate than the system's current offset because of daylight saving time. offset = TimeZoneInfo.GetLocalUtcOffset(DateTime.Now, TimeZoneInfoOptions.NoThrowOnInvalidTime); } else if (dateTime.Kind == DateTimeKind.Utc) { -#if FEATURE_CORECLR offset = TimeSpan.Zero; -#else // FEATURE_CORECLR - // This code path points to a bug in user code. It would make sense to return a 0 offset in this case. - // However, because it was only possible to detect this in Whidbey, there is user code that takes a - // dependency on being serialize a UTC DateTime using the 'z' format, and it will work almost all the - // time if it is offset by an incorrect conversion to local time when parsed. Therefore, we need to - // explicitly emit the local time offset, which we can do by removing the UTC flag. - InvalidFormatForUtc(format, dateTime); - dateTime = DateTime.SpecifyKind(dateTime, DateTimeKind.Local); - offset = TimeZoneInfo.GetLocalUtcOffset(dateTime, TimeZoneInfoOptions.NoThrowOnInvalidTime); -#endif // FEATURE_CORECLR } else { offset = TimeZoneInfo.GetLocalUtcOffset(dateTime, TimeZoneInfoOptions.NoThrowOnInvalidTime); } } if (offset >= TimeSpan.Zero) { - result.Append('+'); + result.Append('+'); } else { result.Append('-'); @@ -739,7 +733,7 @@ namespace System { // 'zzz*' or longer format e.g "-07:30" result.AppendFormat(CultureInfo.InvariantCulture, ":{0:00}", offset.Minutes); } - } + } } // output the 'K' format, which is for round-tripping the data @@ -775,7 +769,9 @@ namespace System { offset = offset.Negate(); } - result.AppendFormat(CultureInfo.InvariantCulture, "{0:00}:{1:00}", offset.Hours, offset.Minutes); + AppendNumber(result, offset.Hours, 2); + result.Append(':'); + AppendNumber(result, offset.Minutes, 2); } @@ -957,12 +953,101 @@ namespace System { } if (format.Length == 1) { + switch (format[0]) + { + case 'O': + case 'o': + return FastFormatRoundtrip(dateTime, offset); + case 'R': + case 'r': + return FastFormatRfc1123(dateTime, offset, dtfi); + } + format = ExpandPredefinedFormat(format, ref dateTime, ref dtfi, ref offset); - } + } return (FormatCustomized(dateTime, format, dtfi, offset)); } - + + internal static string FastFormatRfc1123(DateTime dateTime, TimeSpan offset, DateTimeFormatInfo dtfi) + { + // ddd, dd MMM yyyy HH:mm:ss GMT + const int Rfc1123FormatLength = 29; + StringBuilder result = StringBuilderCache.Acquire(Rfc1123FormatLength); + + if (offset != NullOffset) + { + // Convert to UTC invariants + dateTime = dateTime - offset; + } + + result.Append(InvariantAbbreviatedDayNames[(int)dateTime.DayOfWeek]); + result.Append(','); + result.Append(' '); + AppendNumber(result, dateTime.Day, 2); + result.Append(' '); + result.Append(InvariantAbbreviatedMonthNames[dateTime.Month - 1]); + result.Append(' '); + AppendNumber(result, dateTime.Year, 4); + result.Append(' '); + AppendHHmmssTimeOfDay(result, dateTime); + result.Append(' '); + result.Append(Gmt); + + return StringBuilderCache.GetStringAndRelease(result); + } + + internal static string FastFormatRoundtrip(DateTime dateTime, TimeSpan offset) + { + // yyyy-MM-ddTHH:mm:ss.fffffffK + const int roundTripFormatLength = 28; + StringBuilder result = StringBuilderCache.Acquire(roundTripFormatLength); + + AppendNumber(result, dateTime.Year, 4); + result.Append('-'); + AppendNumber(result, dateTime.Month, 2); + result.Append('-'); + AppendNumber(result, dateTime.Day, 2); + result.Append('T'); + AppendHHmmssTimeOfDay(result, dateTime); + result.Append('.'); + + long fraction = dateTime.Ticks % TimeSpan.TicksPerSecond; + AppendNumber(result, fraction, 7); + + FormatCustomizedRoundripTimeZone(dateTime, offset, result); + + return StringBuilderCache.GetStringAndRelease(result); + } + + private static void AppendHHmmssTimeOfDay(StringBuilder result, DateTime dateTime) + { + // HH:mm:ss + AppendNumber(result, dateTime.Hour, 2); + result.Append(':'); + AppendNumber(result, dateTime.Minute, 2); + result.Append(':'); + AppendNumber(result, dateTime.Second, 2); + } + + internal static void AppendNumber(StringBuilder builder, long val, int digits) + { + for (int i = 0; i < digits; i++) + { + builder.Append('0'); + } + + int index = 1; + while (val > 0 && index <= digits) + { + builder[builder.Length - index] = (char)('0' + (val % 10)); + val = val / 10; + index++; + } + + Debug.Assert(val == 0, "DateTimeFormat.AppendNumber(): digits less than size of val"); + } + internal static String[] GetAllDateTimes(DateTime dateTime, char format, DateTimeFormatInfo dtfi) { Contract.Requires(dtfi != null); @@ -1042,7 +1127,6 @@ namespace System { // This is an MDA for cases when the user is using a local format with // a Utc DateTime. - [System.Security.SecuritySafeCritical] // auto-generated internal static void InvalidFormatForUtc(String format, DateTime dateTime) { #if MDA_SUPPORTED Mda.DateTimeInvalidLocalFormat(); diff --git a/src/mscorlib/src/System/Globalization/DateTimeFormatInfo.cs b/src/mscorlib/src/System/Globalization/DateTimeFormatInfo.cs index 00c2d1f439..14cdeb60e9 100644 --- a/src/mscorlib/src/System/Globalization/DateTimeFormatInfo.cs +++ b/src/mscorlib/src/System/Globalization/DateTimeFormatInfo.cs @@ -14,6 +14,7 @@ namespace System.Globalization { using System.Runtime.InteropServices; using System.Runtime.Versioning; using System.Text; + using System.Diagnostics; using System.Diagnostics.Contracts; // @@ -181,18 +182,6 @@ namespace System.Globalization { // genitive form or leap year month names. [OptionalField(VersionAdded = 2)] internal DateTimeFormatFlags formatFlags = DateTimeFormatFlags.NotInitialized; - internal static bool preferExistingTokens = InitPreferExistingTokens(); - - - [System.Security.SecuritySafeCritical] - static bool InitPreferExistingTokens() - { - bool ret = false; -#if !FEATURE_CORECLR - ret = DateTime.LegacyParseMode(); -#endif - return ret; - } private String CultureName { @@ -220,7 +209,6 @@ namespace System.Globalization { private String LanguageName { - [System.Security.SecurityCritical] // auto-generated get { if (m_langName == null) @@ -243,7 +231,7 @@ namespace System.Globalization { { // Get the abbreviated day names for our current calendar this.abbreviatedDayNames = this.m_cultureData.AbbreviatedDayNames(Calendar.ID); - Contract.Assert(this.abbreviatedDayNames.Length == 7, "[DateTimeFormatInfo.GetAbbreviatedDayOfWeekNames] Expected 7 day names in a week"); + Debug.Assert(this.abbreviatedDayNames.Length == 7, "[DateTimeFormatInfo.GetAbbreviatedDayOfWeekNames] Expected 7 day names in a week"); } return (this.abbreviatedDayNames); } @@ -266,7 +254,7 @@ namespace System.Globalization { { // Get the super short day names for our current calendar this.m_superShortDayNames = this.m_cultureData.SuperShortDayNames(Calendar.ID); - Contract.Assert(this.m_superShortDayNames.Length == 7, "[DateTimeFormatInfo.internalGetSuperShortDayNames] Expected 7 day names in a week"); + Debug.Assert(this.m_superShortDayNames.Length == 7, "[DateTimeFormatInfo.internalGetSuperShortDayNames] Expected 7 day names in a week"); } return (this.m_superShortDayNames); } @@ -283,7 +271,7 @@ namespace System.Globalization { { // Get the day names for our current calendar this.dayNames = this.m_cultureData.DayNames(Calendar.ID); - Contract.Assert(this.dayNames.Length == 7, "[DateTimeFormatInfo.GetDayOfWeekNames] Expected 7 day names in a week"); + Debug.Assert(this.dayNames.Length == 7, "[DateTimeFormatInfo.GetDayOfWeekNames] Expected 7 day names in a week"); } return (this.dayNames); } @@ -300,7 +288,7 @@ namespace System.Globalization { { // Get the month names for our current calendar this.abbreviatedMonthNames = this.m_cultureData.AbbreviatedMonthNames(Calendar.ID); - Contract.Assert(this.abbreviatedMonthNames.Length == 12 || this.abbreviatedMonthNames.Length == 13, + Debug.Assert(this.abbreviatedMonthNames.Length == 12 || this.abbreviatedMonthNames.Length == 13, "[DateTimeFormatInfo.GetAbbreviatedMonthNames] Expected 12 or 13 month names in a year"); } return (this.abbreviatedMonthNames); @@ -319,7 +307,7 @@ namespace System.Globalization { { // Get the month names for our current calendar this.monthNames = this.m_cultureData.MonthNames(Calendar.ID); - Contract.Assert(this.monthNames.Length == 12 || this.monthNames.Length == 13, + Debug.Assert(this.monthNames.Length == 12 || this.monthNames.Length == 13, "[DateTimeFormatInfo.GetMonthNames] Expected 12 or 13 month names in a year"); } @@ -347,16 +335,12 @@ namespace System.Globalization { // m_isDefaultCalendar is set in the setter of Calendar below. this.Calendar = cal; } - -#if !FEATURE_CORECLR - [System.Security.SecuritySafeCritical] -#endif private void InitializeOverridableProperties(CultureData cultureData, int calendarID) { // Silverlight 2.0 never took a snapshot of the user's overridable properties // This has a substantial performance impact so skip when CoreCLR Contract.Requires(cultureData != null); - Contract.Assert(calendarID > 0, "[DateTimeFormatInfo.Populate] Expected Calendar.ID > 0"); + Debug.Assert(calendarID > 0, "[DateTimeFormatInfo.Populate] Expected Calendar.ID > 0"); if (this.firstDayOfWeek == -1) { this.firstDayOfWeek = cultureData.IFIRSTDAYOFWEEK; } if (this.calendarWeekRule == -1) { this.calendarWeekRule = cultureData.IFIRSTWEEKOFYEAR; } @@ -367,19 +351,19 @@ namespace System.Globalization { if (this.dateSeparator == null) { this.dateSeparator = cultureData.DateSeparator(calendarID); } this.allLongTimePatterns = this.m_cultureData.LongTimes; - Contract.Assert(this.allLongTimePatterns.Length > 0, "[DateTimeFormatInfo.Populate] Expected some long time patterns"); + Debug.Assert(this.allLongTimePatterns.Length > 0, "[DateTimeFormatInfo.Populate] Expected some long time patterns"); this.allShortTimePatterns = this.m_cultureData.ShortTimes; - Contract.Assert(this.allShortTimePatterns.Length > 0, "[DateTimeFormatInfo.Populate] Expected some short time patterns"); + Debug.Assert(this.allShortTimePatterns.Length > 0, "[DateTimeFormatInfo.Populate] Expected some short time patterns"); this.allLongDatePatterns = cultureData.LongDates(calendarID); - Contract.Assert(this.allLongDatePatterns.Length > 0, "[DateTimeFormatInfo.Populate] Expected some long date patterns"); + Debug.Assert(this.allLongDatePatterns.Length > 0, "[DateTimeFormatInfo.Populate] Expected some long date patterns"); this.allShortDatePatterns = cultureData.ShortDates(calendarID); - Contract.Assert(this.allShortDatePatterns.Length > 0, "[DateTimeFormatInfo.Populate] Expected some short date patterns"); + Debug.Assert(this.allShortDatePatterns.Length > 0, "[DateTimeFormatInfo.Populate] Expected some short date patterns"); this.allYearMonthPatterns = cultureData.YearMonths(calendarID); - Contract.Assert(this.allYearMonthPatterns.Length > 0, "[DateTimeFormatInfo.Populate] Expected some year month patterns"); + Debug.Assert(this.allYearMonthPatterns.Length > 0, "[DateTimeFormatInfo.Populate] Expected some year month patterns"); } #region Serialization @@ -411,7 +395,7 @@ namespace System.Globalization { if (this.m_cultureData == null) throw new CultureNotFoundException( - "m_name", m_name, Environment.GetResourceString("Argument_CultureNotSupported")); + nameof(m_name), m_name, Environment.GetResourceString("Argument_CultureNotSupported")); } // Note: This is for Everett compatibility @@ -458,11 +442,6 @@ namespace System.Globalization { // make sure the m_name is initialized. m_name = this.CultureName; -#if !FEATURE_CORECLR - if (s_calendarNativeNames == null) - s_calendarNativeNames = new Hashtable(); -#endif // FEATURE_CORECLR - // Important to initialize these fields otherwise we may run into exception when deserializing on Whidbey // because Whidbey try to initialize some of these fields using calendar data which could be null values // and then we get exceptions. So we call the accessors to force the caches to get loaded. @@ -561,18 +540,14 @@ namespace System.Globalization { public String AMDesignator { -#if FEATURE_CORECLR - [System.Security.SecuritySafeCritical] // auto-generated -#endif get { -#if FEATURE_CORECLR if (this.amDesignator == null) { this.amDesignator = this.m_cultureData.SAM1159; } -#endif - Contract.Assert(this.amDesignator != null, "DateTimeFormatInfo.AMDesignator, amDesignator != null"); + + Debug.Assert(this.amDesignator != null, "DateTimeFormatInfo.AMDesignator, amDesignator != null"); return (this.amDesignator); } @@ -582,7 +557,7 @@ namespace System.Globalization { throw new InvalidOperationException(Environment.GetResourceString("InvalidOperation_ReadOnly")); if (value == null) { - throw new ArgumentNullException("value", + throw new ArgumentNullException(nameof(value), Environment.GetResourceString("ArgumentNull_String")); } Contract.EndContractBlock(); @@ -596,7 +571,7 @@ namespace System.Globalization { get { Contract.Ensures(Contract.Result<Calendar>() != null); - Contract.Assert(this.calendar != null, "DateTimeFormatInfo.Calendar: calendar != null"); + Debug.Assert(this.calendar != null, "DateTimeFormatInfo.Calendar: calendar != null"); return (this.calendar); } @@ -604,7 +579,7 @@ namespace System.Globalization { if (IsReadOnly) throw new InvalidOperationException(Environment.GetResourceString("InvalidOperation_ReadOnly")); if (value == null) { - throw new ArgumentNullException("value", + throw new ArgumentNullException(nameof(value), Environment.GetResourceString("ArgumentNull_Obj")); } Contract.EndContractBlock(); @@ -694,7 +669,7 @@ namespace System.Globalization { } // The assigned calendar is not a valid calendar for this culture, throw - throw new ArgumentOutOfRangeException("value", Environment.GetResourceString("Argument_InvalidCalendar")); + throw new ArgumentOutOfRangeException(nameof(value), Environment.GetResourceString("Argument_InvalidCalendar")); } } @@ -718,7 +693,7 @@ namespace System.Globalization { public int GetEra(String eraName) { if (eraName == null) { - throw new ArgumentNullException("eraName", + throw new ArgumentNullException(nameof(eraName), Environment.GetResourceString("ArgumentNull_String")); } Contract.EndContractBlock(); @@ -795,7 +770,7 @@ namespace System.Globalization { if ((--era) < EraNames.Length && (era >= 0)) { return (m_eraNames[era]); } - throw new ArgumentOutOfRangeException("era", Environment.GetResourceString("ArgumentOutOfRange_InvalidEraValue")); + throw new ArgumentOutOfRangeException(nameof(era), Environment.GetResourceString("ArgumentOutOfRange_InvalidEraValue")); } internal String[] AbbreviatedEraNames @@ -823,7 +798,7 @@ namespace System.Globalization { if ((--era) < m_abbrevEraNames.Length && (era >= 0)) { return (m_abbrevEraNames[era]); } - throw new ArgumentOutOfRangeException("era", Environment.GetResourceString("ArgumentOutOfRange_InvalidEraValue")); + throw new ArgumentOutOfRangeException(nameof(era), Environment.GetResourceString("ArgumentOutOfRange_InvalidEraValue")); } internal String[] AbbreviatedEnglishEraNames @@ -832,7 +807,7 @@ namespace System.Globalization { { if (this.m_abbrevEnglishEraNames == null) { - Contract.Assert(Calendar.ID > 0, "[DateTimeFormatInfo.AbbreviatedEnglishEraNames] Expected Calendar.ID > 0"); + Debug.Assert(Calendar.ID > 0, "[DateTimeFormatInfo.AbbreviatedEnglishEraNames] Expected Calendar.ID > 0"); this.m_abbrevEnglishEraNames = this.m_cultureData.AbbreviatedEnglishEraNames(Calendar.ID); } return (this.m_abbrevEnglishEraNames); @@ -846,13 +821,12 @@ namespace System.Globalization { { get { -#if FEATURE_CORECLR if (this.dateSeparator == null) { this.dateSeparator = this.m_cultureData.DateSeparator(Calendar.ID); } -#endif - Contract.Assert(this.dateSeparator != null, "DateTimeFormatInfo.DateSeparator, dateSeparator != null"); + + Debug.Assert(this.dateSeparator != null, "DateTimeFormatInfo.DateSeparator, dateSeparator != null"); return (this.dateSeparator); } @@ -862,7 +836,7 @@ namespace System.Globalization { throw new InvalidOperationException(Environment.GetResourceString("InvalidOperation_ReadOnly")); if (value == null) { - throw new ArgumentNullException("value", + throw new ArgumentNullException(nameof(value), Environment.GetResourceString("ArgumentNull_String")); } Contract.EndContractBlock(); @@ -876,14 +850,12 @@ namespace System.Globalization { { get { -#if FEATURE_CORECLR if (this.firstDayOfWeek == -1) { this.firstDayOfWeek = this.m_cultureData.IFIRSTDAYOFWEEK; } -#endif - Contract.Assert(this.firstDayOfWeek != -1, "DateTimeFormatInfo.FirstDayOfWeek, firstDayOfWeek != -1"); - + + Debug.Assert(this.firstDayOfWeek != -1, "DateTimeFormatInfo.FirstDayOfWeek, firstDayOfWeek != -1"); return ((DayOfWeek)this.firstDayOfWeek); } @@ -894,7 +866,7 @@ namespace System.Globalization { firstDayOfWeek = (int)value; } else { throw new ArgumentOutOfRangeException( - "value", Environment.GetResourceString("ArgumentOutOfRange_Range", + nameof(value), Environment.GetResourceString("ArgumentOutOfRange_Range", DayOfWeek.Sunday, DayOfWeek.Saturday)); } } @@ -905,13 +877,12 @@ namespace System.Globalization { { get { -#if FEATURE_CORECLR if (this.calendarWeekRule == -1) { this.calendarWeekRule = this.m_cultureData.IFIRSTWEEKOFYEAR; } -#endif - Contract.Assert(this.calendarWeekRule != -1, "DateTimeFormatInfo.CalendarWeekRule, calendarWeekRule != -1"); + + Debug.Assert(this.calendarWeekRule != -1, "DateTimeFormatInfo.CalendarWeekRule, calendarWeekRule != -1"); return ((CalendarWeekRule)this.calendarWeekRule); } @@ -922,7 +893,7 @@ namespace System.Globalization { calendarWeekRule = (int)value; } else { throw new ArgumentOutOfRangeException( - "value", Environment.GetResourceString("ArgumentOutOfRange_Range", + nameof(value), Environment.GetResourceString("ArgumentOutOfRange_Range", CalendarWeekRule.FirstDay, CalendarWeekRule.FirstFourDayWeek)); } } @@ -945,7 +916,7 @@ namespace System.Globalization { if (IsReadOnly) throw new InvalidOperationException(Environment.GetResourceString("InvalidOperation_ReadOnly")); if (value == null) { - throw new ArgumentNullException("value", + throw new ArgumentNullException(nameof(value), Environment.GetResourceString("ArgumentNull_String")); } Contract.EndContractBlock(); @@ -977,7 +948,7 @@ namespace System.Globalization { if (IsReadOnly) throw new InvalidOperationException(Environment.GetResourceString("InvalidOperation_ReadOnly")); if (value == null) { - throw new ArgumentNullException("value", + throw new ArgumentNullException(nameof(value), Environment.GetResourceString("ArgumentNull_String")); } Contract.EndContractBlock(); @@ -1016,7 +987,7 @@ namespace System.Globalization { if (IsReadOnly) throw new InvalidOperationException(Environment.GetResourceString("InvalidOperation_ReadOnly")); if (value == null) { - throw new ArgumentNullException("value", + throw new ArgumentNullException(nameof(value), Environment.GetResourceString("ArgumentNull_String")); } Contract.EndContractBlock(); @@ -1042,10 +1013,10 @@ namespace System.Globalization { { if (this.monthDayPattern == null) { - Contract.Assert(Calendar.ID > 0, "[DateTimeFormatInfo.MonthDayPattern] Expected calID > 0"); + Debug.Assert(Calendar.ID > 0, "[DateTimeFormatInfo.MonthDayPattern] Expected calID > 0"); this.monthDayPattern = this.m_cultureData.MonthDay(Calendar.ID); } - Contract.Assert(this.monthDayPattern != null, "DateTimeFormatInfo.MonthDayPattern, monthDayPattern != null"); + Debug.Assert(this.monthDayPattern != null, "DateTimeFormatInfo.MonthDayPattern, monthDayPattern != null"); return (this.monthDayPattern); } @@ -1053,7 +1024,7 @@ namespace System.Globalization { if (IsReadOnly) throw new InvalidOperationException(Environment.GetResourceString("InvalidOperation_ReadOnly")); if (value == null) { - throw new ArgumentNullException("value", + throw new ArgumentNullException(nameof(value), Environment.GetResourceString("ArgumentNull_String")); } Contract.EndContractBlock(); @@ -1065,18 +1036,14 @@ namespace System.Globalization { public String PMDesignator { -#if FEATURE_CORECLR - [System.Security.SecuritySafeCritical] // auto-generated -#endif get { -#if FEATURE_CORECLR if (this.pmDesignator == null) { this.pmDesignator = this.m_cultureData.SPM2359; } -#endif - Contract.Assert(this.pmDesignator != null, "DateTimeFormatInfo.PMDesignator, pmDesignator != null"); + + Debug.Assert(this.pmDesignator != null, "DateTimeFormatInfo.PMDesignator, pmDesignator != null"); return (this.pmDesignator); } @@ -1084,7 +1051,7 @@ namespace System.Globalization { if (IsReadOnly) throw new InvalidOperationException(Environment.GetResourceString("InvalidOperation_ReadOnly")); if (value == null) { - throw new ArgumentNullException("value", + throw new ArgumentNullException(nameof(value), Environment.GetResourceString("ArgumentNull_String")); } Contract.EndContractBlock(); @@ -1128,7 +1095,7 @@ namespace System.Globalization { if (IsReadOnly) throw new InvalidOperationException(Environment.GetResourceString("InvalidOperation_ReadOnly")); if (value == null) - throw new ArgumentNullException("value", + throw new ArgumentNullException(nameof(value), Environment.GetResourceString("ArgumentNull_String")); Contract.EndContractBlock(); @@ -1168,7 +1135,7 @@ namespace System.Globalization { if (IsReadOnly) throw new InvalidOperationException(Environment.GetResourceString("InvalidOperation_ReadOnly")); if (value == null) { - throw new ArgumentNullException("value", + throw new ArgumentNullException(nameof(value), Environment.GetResourceString("ArgumentNull_String")); } Contract.EndContractBlock(); @@ -1292,13 +1259,12 @@ namespace System.Globalization { { get { -#if FEATURE_CORECLR if (timeSeparator == null) { timeSeparator = this.m_cultureData.TimeSeparator; } -#endif - Contract.Assert(this.timeSeparator != null, "DateTimeFormatInfo.TimeSeparator, timeSeparator != null"); + + Debug.Assert(this.timeSeparator != null, "DateTimeFormatInfo.TimeSeparator, timeSeparator != null"); return (timeSeparator); } @@ -1308,7 +1274,7 @@ namespace System.Globalization { throw new InvalidOperationException(Environment.GetResourceString("InvalidOperation_ReadOnly")); if (value == null) { - throw new ArgumentNullException("value", + throw new ArgumentNullException(nameof(value), Environment.GetResourceString("ArgumentNull_String")); } Contract.EndContractBlock(); @@ -1349,7 +1315,7 @@ namespace System.Globalization { if (IsReadOnly) throw new InvalidOperationException(Environment.GetResourceString("InvalidOperation_ReadOnly")); if (value == null) { - throw new ArgumentNullException("value", + throw new ArgumentNullException(nameof(value), Environment.GetResourceString("ArgumentNull_String")); } Contract.EndContractBlock(); @@ -1388,11 +1354,11 @@ namespace System.Globalization { if (IsReadOnly) throw new InvalidOperationException(Environment.GetResourceString("InvalidOperation_ReadOnly")); if (value == null) { - throw new ArgumentNullException("value", + throw new ArgumentNullException(nameof(value), Environment.GetResourceString("ArgumentNull_Array")); } if (value.Length != 7) { - throw new ArgumentException(Environment.GetResourceString("Argument_InvalidArrayLength", 7), "value"); + throw new ArgumentException(Environment.GetResourceString("Argument_InvalidArrayLength", 7), nameof(value)); } Contract.EndContractBlock(); CheckNullValue(value, value.Length); @@ -1416,12 +1382,12 @@ namespace System.Globalization { if (IsReadOnly) throw new InvalidOperationException(Environment.GetResourceString("InvalidOperation_ReadOnly")); if (value == null) { - throw new ArgumentNullException("value", + throw new ArgumentNullException(nameof(value), Environment.GetResourceString("ArgumentNull_Array")); } if (value.Length != 7) { - throw new ArgumentException(Environment.GetResourceString("Argument_InvalidArrayLength", 7), "value"); + throw new ArgumentException(Environment.GetResourceString("Argument_InvalidArrayLength", 7), nameof(value)); } Contract.EndContractBlock(); CheckNullValue(value, value.Length); @@ -1441,12 +1407,12 @@ namespace System.Globalization { if (IsReadOnly) throw new InvalidOperationException(Environment.GetResourceString("InvalidOperation_ReadOnly")); if (value == null) { - throw new ArgumentNullException("value", + throw new ArgumentNullException(nameof(value), Environment.GetResourceString("ArgumentNull_Array")); } if (value.Length != 7) { - throw new ArgumentException(Environment.GetResourceString("Argument_InvalidArrayLength", 7), "value"); + throw new ArgumentException(Environment.GetResourceString("Argument_InvalidArrayLength", 7), nameof(value)); } Contract.EndContractBlock(); CheckNullValue(value, value.Length); @@ -1466,12 +1432,12 @@ namespace System.Globalization { if (IsReadOnly) throw new InvalidOperationException(Environment.GetResourceString("InvalidOperation_ReadOnly")); if (value == null) { - throw new ArgumentNullException("value", + throw new ArgumentNullException(nameof(value), Environment.GetResourceString("ArgumentNull_Array")); } if (value.Length != 13) { - throw new ArgumentException(Environment.GetResourceString("Argument_InvalidArrayLength", 13), "value"); + throw new ArgumentException(Environment.GetResourceString("Argument_InvalidArrayLength", 13), nameof(value)); } Contract.EndContractBlock(); CheckNullValue(value, value.Length - 1); @@ -1492,12 +1458,12 @@ namespace System.Globalization { if (IsReadOnly) throw new InvalidOperationException(Environment.GetResourceString("InvalidOperation_ReadOnly")); if (value == null) { - throw new ArgumentNullException("value", + throw new ArgumentNullException(nameof(value), Environment.GetResourceString("ArgumentNull_Array")); } if (value.Length != 13) { - throw new ArgumentException(Environment.GetResourceString("Argument_InvalidArrayLength", 13), "value"); + throw new ArgumentException(Environment.GetResourceString("Argument_InvalidArrayLength", 13), nameof(value)); } Contract.EndContractBlock(); CheckNullValue(value, value.Length - 1); @@ -1556,7 +1522,7 @@ namespace System.Globalization { // (actually is 13 right now for all cases) if ((month < 1) || (month > monthNamesArray.Length)) { throw new ArgumentOutOfRangeException( - "month", Environment.GetResourceString("ArgumentOutOfRange_Range", + nameof(month), Environment.GetResourceString("ArgumentOutOfRange_Range", 1, monthNamesArray.Length)); } return (monthNamesArray[month-1]); @@ -1575,7 +1541,7 @@ namespace System.Globalization { if (this.m_genitiveAbbreviatedMonthNames == null) { this.m_genitiveAbbreviatedMonthNames = this.m_cultureData.AbbreviatedGenitiveMonthNames(this.Calendar.ID); - Contract.Assert(this.m_genitiveAbbreviatedMonthNames.Length == 13, + Debug.Assert(this.m_genitiveAbbreviatedMonthNames.Length == 13, "[DateTimeFormatInfo.GetGenitiveMonthNames] Expected 13 abbreviated genitive month names in a year"); } return (this.m_genitiveAbbreviatedMonthNames); @@ -1584,7 +1550,7 @@ namespace System.Globalization { if (this.genitiveMonthNames == null) { this.genitiveMonthNames = this.m_cultureData.GenitiveMonthNames(this.Calendar.ID); - Contract.Assert(this.genitiveMonthNames.Length == 13, + Debug.Assert(this.genitiveMonthNames.Length == 13, "[DateTimeFormatInfo.GetGenitiveMonthNames] Expected 13 genitive month names in a year"); } return (this.genitiveMonthNames); @@ -1600,9 +1566,9 @@ namespace System.Globalization { internal String[] internalGetLeapYearMonthNames(/*bool abbreviated*/) { if (this.leapYearMonthNames == null) { - Contract.Assert(Calendar.ID > 0, "[DateTimeFormatInfo.internalGetLeapYearMonthNames] Expected Calendar.ID > 0"); + Debug.Assert(Calendar.ID > 0, "[DateTimeFormatInfo.internalGetLeapYearMonthNames] Expected Calendar.ID > 0"); this.leapYearMonthNames = this.m_cultureData.LeapYearMonthNames(Calendar.ID); - Contract.Assert(this.leapYearMonthNames.Length == 13, + Debug.Assert(this.leapYearMonthNames.Length == 13, "[DateTimeFormatInfo.internalGetLeapYearMonthNames] Expepcted 13 leap year month names"); } return (leapYearMonthNames); @@ -1614,7 +1580,7 @@ namespace System.Globalization { if ((int)dayofweek < 0 || (int)dayofweek > 6) { throw new ArgumentOutOfRangeException( - "dayofweek", Environment.GetResourceString("ArgumentOutOfRange_Range", + nameof(dayofweek), Environment.GetResourceString("ArgumentOutOfRange_Range", DayOfWeek.Sunday, DayOfWeek.Saturday)); } Contract.EndContractBlock(); @@ -1633,7 +1599,7 @@ namespace System.Globalization { if ((int)dayOfWeek < 0 || (int)dayOfWeek > 6) { throw new ArgumentOutOfRangeException( - "dayOfWeek", Environment.GetResourceString("ArgumentOutOfRange_Range", + nameof(dayOfWeek), Environment.GetResourceString("ArgumentOutOfRange_Range", DayOfWeek.Sunday, DayOfWeek.Saturday)); } Contract.EndContractBlock(); @@ -1740,7 +1706,7 @@ namespace System.Globalization { result = this.AllYearMonthPatterns; break; default: - throw new ArgumentException(Environment.GetResourceString("Format_BadFormatSpecifier"), "format"); + throw new ArgumentException(Environment.GetResourceString("Format_BadFormatSpecifier"), nameof(format)); } return (result); } @@ -1750,7 +1716,7 @@ namespace System.Globalization { { if ((int)dayofweek < 0 || (int)dayofweek > 6) { throw new ArgumentOutOfRangeException( - "dayofweek", Environment.GetResourceString("ArgumentOutOfRange_Range", + nameof(dayofweek), Environment.GetResourceString("ArgumentOutOfRange_Range", DayOfWeek.Sunday, DayOfWeek.Saturday)); } Contract.EndContractBlock(); @@ -1765,7 +1731,7 @@ namespace System.Globalization { { if (month < 1 || month > 13) { throw new ArgumentOutOfRangeException( - "month", Environment.GetResourceString("ArgumentOutOfRange_Range", + nameof(month), Environment.GetResourceString("ArgumentOutOfRange_Range", 1, 13)); } Contract.EndContractBlock(); @@ -1778,7 +1744,7 @@ namespace System.Globalization { { if (month < 1 || month > 13) { throw new ArgumentOutOfRangeException( - "month", Environment.GetResourceString("ArgumentOutOfRange_Range", + nameof(month), Environment.GetResourceString("ArgumentOutOfRange_Range", 1, 13)); } Contract.EndContractBlock(); @@ -1795,9 +1761,9 @@ namespace System.Globalization { // The resulting [] can get returned to the calling app, so clone it. private static string[] GetMergedPatterns(string [] patterns, string defaultPattern) { - Contract.Assert(patterns != null && patterns.Length > 0, + Debug.Assert(patterns != null && patterns.Length > 0, "[DateTimeFormatInfo.GetMergedPatterns]Expected array of at least one pattern"); - Contract.Assert(defaultPattern != null, + Debug.Assert(defaultPattern != null, "[DateTimeFormatInfo.GetMergedPatterns]Expected non null default string"); // If the default happens to be the first in the list just return (a cloned) copy @@ -1894,9 +1860,9 @@ namespace System.Globalization { { if (this.allYearMonthPatterns == null) { - Contract.Assert(Calendar.ID > 0, "[DateTimeFormatInfo.UnclonedYearMonthPatterns] Expected Calendar.ID > 0"); + Debug.Assert(Calendar.ID > 0, "[DateTimeFormatInfo.UnclonedYearMonthPatterns] Expected Calendar.ID > 0"); this.allYearMonthPatterns = this.m_cultureData.YearMonths(this.Calendar.ID); - Contract.Assert(this.allYearMonthPatterns.Length > 0, + Debug.Assert(this.allYearMonthPatterns.Length > 0, "[DateTimeFormatInfo.UnclonedYearMonthPatterns] Expected some year month patterns"); } @@ -1913,9 +1879,9 @@ namespace System.Globalization { { if (allShortDatePatterns == null) { - Contract.Assert(Calendar.ID > 0, "[DateTimeFormatInfo.UnclonedShortDatePatterns] Expected Calendar.ID > 0"); + Debug.Assert(Calendar.ID > 0, "[DateTimeFormatInfo.UnclonedShortDatePatterns] Expected Calendar.ID > 0"); this.allShortDatePatterns = this.m_cultureData.ShortDates(this.Calendar.ID); - Contract.Assert(this.allShortDatePatterns.Length > 0, + Debug.Assert(this.allShortDatePatterns.Length > 0, "[DateTimeFormatInfo.UnclonedShortDatePatterns] Expected some short date patterns"); } @@ -1931,9 +1897,9 @@ namespace System.Globalization { { if (allLongDatePatterns == null) { - Contract.Assert(Calendar.ID > 0, "[DateTimeFormatInfo.UnclonedLongDatePatterns] Expected Calendar.ID > 0"); + Debug.Assert(Calendar.ID > 0, "[DateTimeFormatInfo.UnclonedLongDatePatterns] Expected Calendar.ID > 0"); this.allLongDatePatterns = this.m_cultureData.LongDates(this.Calendar.ID); - Contract.Assert(this.allLongDatePatterns.Length > 0, + Debug.Assert(this.allLongDatePatterns.Length > 0, "[DateTimeFormatInfo.UnclonedLongDatePatterns] Expected some long date patterns"); } @@ -1950,7 +1916,7 @@ namespace System.Globalization { if (this.allShortTimePatterns == null) { this.allShortTimePatterns = this.m_cultureData.ShortTimes; - Contract.Assert(this.allShortTimePatterns.Length > 0, + Debug.Assert(this.allShortTimePatterns.Length > 0, "[DateTimeFormatInfo.UnclonedShortTimePatterns] Expected some short time patterns"); } @@ -1967,7 +1933,7 @@ namespace System.Globalization { if (this.allLongTimePatterns == null) { this.allLongTimePatterns = this.m_cultureData.LongTimes; - Contract.Assert(this.allLongTimePatterns.Length > 0, + Debug.Assert(this.allLongTimePatterns.Length > 0, "[DateTimeFormatInfo.UnclonedLongTimePatterns] Expected some long time patterns"); } @@ -1977,7 +1943,7 @@ namespace System.Globalization { public static DateTimeFormatInfo ReadOnly(DateTimeFormatInfo dtfi) { if (dtfi == null) { - throw new ArgumentNullException("dtfi", + throw new ArgumentNullException(nameof(dtfi), Environment.GetResourceString("ArgumentNull_Obj")); } Contract.EndContractBlock(); @@ -2038,13 +2004,13 @@ namespace System.Globalization { if (IsReadOnly) throw new InvalidOperationException(Environment.GetResourceString("InvalidOperation_ReadOnly")); if (patterns == null) { - throw new ArgumentNullException("patterns", + throw new ArgumentNullException(nameof(patterns), Environment.GetResourceString("ArgumentNull_Array")); } if (patterns.Length == 0) { - throw new ArgumentException(Environment.GetResourceString("Arg_ArrayZeroError"), "patterns"); + throw new ArgumentException(Environment.GetResourceString("Arg_ArrayZeroError"), nameof(patterns)); } Contract.EndContractBlock(); @@ -2086,7 +2052,7 @@ namespace System.Globalization { break; default: - throw new ArgumentException(Environment.GetResourceString("Format_BadFormatSpecifier"), "format"); + throw new ArgumentException(Environment.GetResourceString("Format_BadFormatSpecifier"), nameof(format)); } // Clear the token hash table, note that even short dates could require this @@ -2109,12 +2075,12 @@ namespace System.Globalization { throw new InvalidOperationException(Environment.GetResourceString("InvalidOperation_ReadOnly")); if (value == null) { - throw new ArgumentNullException("value", + throw new ArgumentNullException(nameof(value), Environment.GetResourceString("ArgumentNull_Array")); } if (value.Length != 13) { - throw new ArgumentException(Environment.GetResourceString("Argument_InvalidArrayLength", 13), "value"); + throw new ArgumentException(Environment.GetResourceString("Argument_InvalidArrayLength", 13), nameof(value)); } Contract.EndContractBlock(); CheckNullValue(value, value.Length - 1); @@ -2137,12 +2103,12 @@ namespace System.Globalization { throw new InvalidOperationException(Environment.GetResourceString("InvalidOperation_ReadOnly")); if (value == null) { - throw new ArgumentNullException("value", + throw new ArgumentNullException(nameof(value), Environment.GetResourceString("ArgumentNull_Array")); } if (value.Length != 13) { - throw new ArgumentException(Environment.GetResourceString("Argument_InvalidArrayLength", 13), "value"); + throw new ArgumentException(Environment.GetResourceString("Argument_InvalidArrayLength", 13), nameof(value)); } Contract.EndContractBlock(); CheckNullValue(value, value.Length - 1); @@ -2396,7 +2362,6 @@ namespace System.Globalization { formatFlags = DateTimeFormatFlags.NotInitialized; } - [System.Security.SecurityCritical] // auto-generated internal TokenHashValue[] CreateTokenHashTable() { TokenHashValue[] temp = m_dtfiTokenHash; if (temp == null) { @@ -2689,7 +2654,7 @@ namespace System.Globalization { } while (i < str.Value.Length && (state != HebrewNumberParsingState.FoundEndOfHebrewNumber)); // When we are here, we are either at the end of the string, or we find a valid Hebrew number. - Contract.Assert(state == HebrewNumberParsingState.ContinueParsing || state == HebrewNumberParsingState.FoundEndOfHebrewNumber, + Debug.Assert(state == HebrewNumberParsingState.ContinueParsing || state == HebrewNumberParsingState.FoundEndOfHebrewNumber, "Invalid returned state from HebrewNumber.ParseByChar()"); if (state != HebrewNumberParsingState.FoundEndOfHebrewNumber) { @@ -2710,13 +2675,12 @@ namespace System.Globalization { return (ch >= '\x0590' && ch <= '\x05ff'); } - [System.Security.SecurityCritical] // auto-generated internal bool Tokenize(TokenType TokenMask, out TokenType tokenType, out int tokenValue, ref __DTString str) { tokenType = TokenType.UnknownToken; tokenValue = 0; TokenHashValue value; - Contract.Assert(str.Index < str.Value.Length, "DateTimeFormatInfo.Tokenize(): start < value.Length"); + Debug.Assert(str.Index < str.Value.Length, "DateTimeFormatInfo.Tokenize(): start < value.Length"); char ch = str.m_current; bool isLetter = Char.IsLetter(ch); @@ -2825,7 +2789,7 @@ namespace System.Globalization { } previousNode = temp; } ; - Contract.Assert(false, "The hashtable is full. This should not happen."); + Debug.Assert(false, "The hashtable is full. This should not happen."); } void InsertHash(TokenHashValue[] hashTable, String str, TokenType tokenType, int tokenValue) { @@ -2877,35 +2841,13 @@ namespace System.Globalization { int nTokenType = (int)tokenType; int nCurrentTokenTypeInHash = (int)value.tokenType; - // The idea behind this check is: - // - if the app is targetting 4.5.1 or above OR the compat flag is set, use the correct behavior by default. - // - if the app is targetting 4.5 or below AND the compat switch is set, use the correct behavior - // - if the app is targetting 4.5 or below AND the compat switch is NOT set, use the incorrect behavior - if (preferExistingTokens || BinaryCompatibility.TargetsAtLeast_Desktop_V4_5_1) + if (((nCurrentTokenTypeInHash & (int)TokenType.RegularTokenMask) == 0) && ((nTokenType & (int)TokenType.RegularTokenMask) != 0) || + ((nCurrentTokenTypeInHash & (int)TokenType.SeparatorTokenMask) == 0) && ((nTokenType & (int)TokenType.SeparatorTokenMask) != 0)) { - if (((nCurrentTokenTypeInHash & (int)TokenType.RegularTokenMask) == 0) && ((nTokenType & (int)TokenType.RegularTokenMask) != 0) || - ((nCurrentTokenTypeInHash & (int)TokenType.SeparatorTokenMask) == 0) && ((nTokenType & (int)TokenType.SeparatorTokenMask) != 0)) - { - value.tokenType |= tokenType; - if (tokenValue != 0) - { - value.tokenValue = tokenValue; - } - } - } - else - { - // The following logic is incorrect and causes updates to happen depending on the bitwise relationship between the existing token type and the - // the stored token type. It was this way in .NET 4 RTM. The behavior above is correct and will be adopted going forward. - - if ((((nTokenType | nCurrentTokenTypeInHash) & (int)TokenType.RegularTokenMask) == nTokenType) || - (((nTokenType | nCurrentTokenTypeInHash) & (int)TokenType.SeparatorTokenMask) == nTokenType)) + value.tokenType |= tokenType; + if (tokenValue != 0) { - value.tokenType |= tokenType; - if (tokenValue != 0) - { - value.tokenValue = tokenValue; - } + value.tokenValue = tokenValue; } } // The token to be inserted is already in the table. Skip it. @@ -2918,7 +2860,7 @@ namespace System.Globalization { hashcode += hashProbe; if (hashcode >= TOKEN_HASH_SIZE) hashcode -= TOKEN_HASH_SIZE; } while (i < TOKEN_HASH_SIZE); - Contract.Assert(false, "The hashtable is full. This should not happen."); + Debug.Assert(false, "The hashtable is full. This should not happen."); } } // class DateTimeFormatInfo diff --git a/src/mscorlib/src/System/Globalization/DateTimeFormatInfoScanner.cs b/src/mscorlib/src/System/Globalization/DateTimeFormatInfoScanner.cs index 40cbabc096..4555bb2463 100644 --- a/src/mscorlib/src/System/Globalization/DateTimeFormatInfoScanner.cs +++ b/src/mscorlib/src/System/Globalization/DateTimeFormatInfoScanner.cs @@ -498,9 +498,6 @@ namespace System.Globalization // //////////////////////////////////////////////////////////////////////////// - #if FEATURE_CORECLR - [System.Security.SecurityCritical] // auto-generated - #endif internal String[] GetDateWordsOfDTFI(DateTimeFormatInfo dtfi) { // Enumarate all LongDatePatterns, and get the DateWords and scan for month postfix. String[] datePatterns = dtfi.GetAllDateTimePatterns('D'); diff --git a/src/mscorlib/src/System/Globalization/DateTimeParse.cs b/src/mscorlib/src/System/Globalization/DateTimeParse.cs index 8de3242f30..363747cfc3 100644 --- a/src/mscorlib/src/System/Globalization/DateTimeParse.cs +++ b/src/mscorlib/src/System/Globalization/DateTimeParse.cs @@ -35,16 +35,6 @@ namespace System { internal static MatchNumberDelegate m_hebrewNumberParser = new MatchNumberDelegate(DateTimeParse.MatchHebrewDigits); -#if !FEATURE_CORECLR - [SecuritySafeCritical] - internal static bool GetAmPmParseFlag() - { - return DateTime.EnableAmPmParseAdjustment(); - } - - internal static bool enableAmPmParseAdjustment = GetAmPmParseFlag(); -#endif - internal static DateTime ParseExact(String s, String format, DateTimeFormatInfo dtfi, DateTimeStyles style) { DateTimeResult result = new DateTimeResult(); // The buffer to store the parsing result. result.Init(); @@ -97,11 +87,11 @@ namespace System { internal static bool TryParseExact(String s, String format, DateTimeFormatInfo dtfi, DateTimeStyles style, ref DateTimeResult result) { if (s == null) { - result.SetFailure(ParseFailureKind.ArgumentNull, "ArgumentNull_String", null, "s"); + result.SetFailure(ParseFailureKind.ArgumentNull, "ArgumentNull_String", null, nameof(s)); return false; } if (format == null) { - result.SetFailure(ParseFailureKind.ArgumentNull, "ArgumentNull_String", null, "format"); + result.SetFailure(ParseFailureKind.ArgumentNull, "ArgumentNull_String", null, nameof(format)); return false; } if (s.Length == 0) { @@ -114,7 +104,7 @@ namespace System { return false; } - Contract.Assert(dtfi != null, "dtfi == null"); + Debug.Assert(dtfi != null, "dtfi == null"); return DoStrictParse(s, format, style, dtfi, ref result); } @@ -178,11 +168,11 @@ namespace System { internal static bool TryParseExactMultiple(String s, String[] formats, DateTimeFormatInfo dtfi, DateTimeStyles style, ref DateTimeResult result) { if (s == null) { - result.SetFailure(ParseFailureKind.ArgumentNull, "ArgumentNull_String", null, "s"); + result.SetFailure(ParseFailureKind.ArgumentNull, "ArgumentNull_String", null, nameof(s)); return false; } if (formats == null) { - result.SetFailure(ParseFailureKind.ArgumentNull, "ArgumentNull_String", null, "formats"); + result.SetFailure(ParseFailureKind.ArgumentNull, "ArgumentNull_String", null, nameof(formats)); return false; } @@ -196,7 +186,7 @@ namespace System { return false; } - Contract.Assert(dtfi != null, "dtfi == null"); + Debug.Assert(dtfi != null, "dtfi == null"); // // Do a loop through the provided formats and see if we can parse succesfully in @@ -546,8 +536,8 @@ new DS[] { DS.ERROR, DS.TX_NNN, DS.TX_NNN, DS.TX_NNN, DS.ERROR, DS.ERROR, // Wrong number of digits return false; } - Contract.Assert(hourOffset >= 0 && hourOffset <= 99, "hourOffset >= 0 && hourOffset <= 99"); - Contract.Assert(minuteOffset >= 0 && minuteOffset <= 99, "minuteOffset >= 0 && minuteOffset <= 99"); + Debug.Assert(hourOffset >= 0 && hourOffset <= 99, "hourOffset >= 0 && hourOffset <= 99"); + Debug.Assert(minuteOffset >= 0 && minuteOffset <= 99, "minuteOffset >= 0 && minuteOffset <= 99"); if (minuteOffset < 0 || minuteOffset >= 60) { return false; } @@ -591,7 +581,6 @@ new DS[] { DS.ERROR, DS.TX_NNN, DS.TX_NNN, DS.TX_NNN, DS.ERROR, DS.ERROR, // This is the lexer. Check the character at the current index, and put the found token in dtok and // some raw date/time information in raw. // - [System.Security.SecuritySafeCritical] // auto-generated private static Boolean Lex(DS dps, ref __DTString str, ref DateTimeToken dtok, ref DateTimeRawInfo raw, ref DateTimeResult result, ref DateTimeFormatInfo dtfi, DateTimeStyles styles) { @@ -761,11 +750,7 @@ new DS[] { DS.ERROR, DS.TX_NNN, DS.TX_NNN, DS.TX_NNN, DS.ERROR, DS.ERROR, raw.timeMark = (sep == TokenType.SEP_Am ? TM.AM : TM.PM); dtok.dtt = DTT.NumAmpm; // Fix AM/PM parsing case, e.g. "1/10 5 AM" - if (dps == DS.D_NN -#if !FEATURE_CORECLR - && enableAmPmParseAdjustment -#endif - ) + if (dps == DS.D_NN) { if (!ProcessTerminaltState(DS.DX_NN, ref result, ref styles, ref raw, dtfi)) { @@ -1076,16 +1061,6 @@ new DS[] { DS.ERROR, DS.TX_NNN, DS.TX_NNN, DS.TX_NNN, DS.ERROR, DS.ERROR, return (false); } -#if !FEATURE_CORECLR - // If DateTimeParseIgnorePunctuation is defined, we want to have the V1.1 behavior of just - // ignoring any unrecognized punctuation and moving on to the next character - if (Environment.GetCompatibilityFlag(CompatibilityFlag.DateTimeParseIgnorePunctuation) && ((result.flags & ParseFlags.CaptureOffset) == 0)) { - str.GetNext(); - LexTraceExit("0210 (success)", dps); - return true; - } -#endif // FEATURE_CORECLR - if ((str.m_current == '-' || str.m_current == '+') && ((result.flags & ParseFlags.TimeZoneUsed) == 0)) { Int32 originalIndex = str.Index; if (ParseTimeZone(ref str, ref result.timeZoneOffset)) { @@ -1096,7 +1071,7 @@ new DS[] { DS.ERROR, DS.TX_NNN, DS.TX_NNN, DS.TX_NNN, DS.ERROR, DS.ERROR, else { // Time zone parse attempt failed. Fall through to punctuation handling. str.Index = originalIndex; - } + } } // Visual Basic implements string to date conversions on top of DateTime.Parse: @@ -1104,7 +1079,7 @@ new DS[] { DS.ERROR, DS.TX_NNN, DS.TX_NNN, DS.TX_NNN, DS.ERROR, DS.ERROR, // if (VerifyValidPunctuation(ref str)) { LexTraceExit("0230 (success)", dps); - return true; + return true; } result.SetFailure(ParseFailureKind.Format, "Format_BadDateTime", null); @@ -1936,7 +1911,7 @@ new DS[] { DS.ERROR, DS.TX_NNN, DS.TX_NNN, DS.TX_NNN, DS.ERROR, DS.ERROR, private static Boolean GetTimeOfNN(DateTimeFormatInfo dtfi, ref DateTimeResult result, ref DateTimeRawInfo raw) { - Contract.Assert(raw.numCount >= 2, "raw.numCount >= 2"); + Debug.Assert(raw.numCount >= 2, "raw.numCount >= 2"); if ((result.flags & ParseFlags.HaveTime) != 0) { // Multiple times in the input string result.SetFailure(ParseFailureKind.Format, "Format_BadDateTime", null); @@ -1956,7 +1931,7 @@ new DS[] { DS.ERROR, DS.TX_NNN, DS.TX_NNN, DS.TX_NNN, DS.ERROR, DS.ERROR, result.SetFailure(ParseFailureKind.Format, "Format_BadDateTime", null); return false; } - Contract.Assert(raw.numCount >= 3, "raw.numCount >= 3"); + Debug.Assert(raw.numCount >= 3, "raw.numCount >= 3"); result.Hour = raw.GetNumber(0); result.Minute = raw.GetNumber(1); result.Second = raw.GetNumber(2); @@ -2316,10 +2291,9 @@ new DS[] { DS.ERROR, DS.TX_NNN, DS.TX_NNN, DS.TX_NNN, DS.ERROR, DS.ERROR, // // This is the real method to do the parsing work. // - [System.Security.SecuritySafeCritical] // auto-generated internal static bool TryParse(String s, DateTimeFormatInfo dtfi, DateTimeStyles styles, ref DateTimeResult result) { if (s == null) { - result.SetFailure(ParseFailureKind.ArgumentNull, "ArgumentNull_String", null, "s"); + result.SetFailure(ParseFailureKind.ArgumentNull, "ArgumentNull_String", null, nameof(s)); return false; } if (s.Length == 0) { @@ -2327,7 +2301,7 @@ new DS[] { DS.ERROR, DS.TX_NNN, DS.TX_NNN, DS.TX_NNN, DS.ERROR, DS.ERROR, return false; } - Contract.Assert(dtfi != null, "dtfi == null"); + Debug.Assert(dtfi != null, "dtfi == null"); #if _LOGGING DTFITrace(dtfi); @@ -2548,17 +2522,15 @@ new DS[] { DS.ERROR, DS.TX_NNN, DS.TX_NNN, DS.TX_NNN, DS.ERROR, DS.ERROR, // no adjustment is required in most cases return DateTimeOffsetTimeZonePostProcessing(ref result, styles); } -#if FEATURE_CORECLR // on CoreCLR DateTime is also restricted to +- 14:00, just like DateTimeOffset else { Int64 offsetTicks = result.timeZoneOffset.Ticks; - + // the DateTime offset must be within +- 14:00 hours. if (offsetTicks < DateTimeOffset.MinOffset || offsetTicks > DateTimeOffset.MaxOffset) { result.SetFailure(ParseFailureKind.Format, "Format_OffsetOutOfRange", null); return false; } } -#endif // FEATURE_CORECLR // The flags AssumeUniveral and AssumeLocal only apply when the input does not have a time zone if ((result.flags & ParseFlags.TimeZoneUsed) == 0) { @@ -2592,7 +2564,7 @@ new DS[] { DS.ERROR, DS.TX_NNN, DS.TX_NNN, DS.TX_NNN, DS.ERROR, DS.ERROR, } else { // No time zone and no Assume flags, so DateTimeKind.Unspecified is fine - Contract.Assert(result.parsedDate.Kind == DateTimeKind.Unspecified, "result.parsedDate.Kind == DateTimeKind.Unspecified"); + Debug.Assert(result.parsedDate.Kind == DateTimeKind.Unspecified, "result.parsedDate.Kind == DateTimeKind.Unspecified"); return true; } } @@ -2882,9 +2854,9 @@ new DS[] { DS.ERROR, DS.TX_NNN, DS.TX_NNN, DS.TX_NNN, DS.ERROR, DS.ERROR, } internal static bool ParseDigits(ref __DTString str, int minDigitLen, int maxDigitLen, out int result) { - Contract.Assert(minDigitLen > 0, "minDigitLen > 0"); - Contract.Assert(maxDigitLen < 9, "maxDigitLen < 9"); - Contract.Assert(minDigitLen <= maxDigitLen, "minDigitLen <= maxDigitLen"); + Debug.Assert(minDigitLen > 0, "minDigitLen > 0"); + Debug.Assert(maxDigitLen < 9, "maxDigitLen < 9"); + Debug.Assert(minDigitLen <= maxDigitLen, "minDigitLen <= maxDigitLen"); result = 0; int startingIndex = str.Index; int tokenLength = 0; @@ -4151,7 +4123,7 @@ new DS[] { DS.ERROR, DS.TX_NNN, DS.TX_NNN, DS.TX_NNN, DS.ERROR, DS.ERROR, case ParseFailureKind.FormatBadDateTimeCalendar: return new FormatException(Environment.GetResourceString(result.failureMessageID, result.calendar)); default: - Contract.Assert(false, "Unkown DateTimeParseFailure: " + result); + Debug.Assert(false, "Unkown DateTimeParseFailure: " + result); return null; } @@ -4373,7 +4345,7 @@ new DS[] { DS.ERROR, DS.TX_NNN, DS.TX_NNN, DS.TX_NNN, DS.ERROR, DS.ERROR, } internal bool Advance(int count) { - Contract.Assert(Index + count <= len, "__DTString::Advance: Index + count <= len"); + Debug.Assert(Index + count <= len, "__DTString::Advance: Index + count <= len"); Index += count; if (Index < len) { m_current = Value[Index]; @@ -4384,7 +4356,6 @@ new DS[] { DS.ERROR, DS.TX_NNN, DS.TX_NNN, DS.TX_NNN, DS.ERROR, DS.ERROR, // Used by DateTime.Parse() to get the next token. - [System.Security.SecurityCritical] // auto-generated internal void GetRegularToken(out TokenType tokenType, out int tokenValue, DateTimeFormatInfo dtfi) { tokenValue = 0; if (Index >= len) { @@ -4464,7 +4435,6 @@ Start: } } - [System.Security.SecurityCritical] // auto-generated internal TokenType GetSeparatorToken(DateTimeFormatInfo dtfi, out int indexBeforeSeparator, out char charBeforeSeparator) { indexBeforeSeparator = Index; charBeforeSeparator = m_current; @@ -4668,7 +4638,7 @@ Start: // Get the current character. // internal char GetChar() { - Contract.Assert(Index >= 0 && Index < len, "Index >= 0 && Index < len"); + Debug.Assert(Index >= 0 && Index < len, "Index >= 0 && Index < len"); return (Value[Index]); } @@ -4676,8 +4646,8 @@ Start: // Convert the current character to a digit, and return it. // internal int GetDigit() { - Contract.Assert(Index >= 0 && Index < len, "Index >= 0 && Index < len"); - Contract.Assert(DateTimeParse.IsDigit(Value[Index]), "IsDigit(Value[Index])"); + Debug.Assert(Index >= 0 && Index < len, "Index >= 0 && Index < len"); + Debug.Assert(DateTimeParse.IsDigit(Value[Index]), "IsDigit(Value[Index])"); return (Value[Index] - '0'); } @@ -4810,7 +4780,7 @@ Start: return sub; } int number = ch - '0'; - Contract.Assert(number >= 0 && number <= 9, "number >= 0 && number <= 9"); + Debug.Assert(number >= 0 && number <= 9, "number >= 0 && number <= 9"); sub.value = sub.value * 10 + number; } else { @@ -4829,8 +4799,8 @@ Start: } internal void ConsumeSubString(DTSubString sub) { - Contract.Assert(sub.index == Index, "sub.index == Index"); - Contract.Assert(sub.index + sub.length <= len, "sub.index + sub.length <= len"); + Debug.Assert(sub.index == Index, "sub.index == Index"); + Debug.Assert(sub.index + sub.length <= len, "sub.index + sub.length <= len"); Index = sub.index + sub.length; if (Index < len) { m_current = Value[Index]; @@ -4875,7 +4845,6 @@ Start: // internal unsafe struct DateTimeRawInfo { - [SecurityCritical] private int* num; internal int numCount; internal int month; @@ -4889,7 +4858,6 @@ Start: internal bool timeZone; - [System.Security.SecurityCritical] // auto-generated internal void Init(int * numberBuffer) { month = -1; year = -1; @@ -4899,11 +4867,9 @@ Start: fraction = -1; num = numberBuffer; } - [System.Security.SecuritySafeCritical] // auto-generated internal unsafe void AddNumber(int value) { num[numCount++] = value; } - [System.Security.SecuritySafeCritical] // auto-generated internal unsafe int GetNumber(int index) { return num[index]; } diff --git a/src/mscorlib/src/System/Globalization/DaylightTime.cs b/src/mscorlib/src/System/Globalization/DaylightTime.cs index 037d9ffdf3..a164867576 100644 --- a/src/mscorlib/src/System/Globalization/DaylightTime.cs +++ b/src/mscorlib/src/System/Globalization/DaylightTime.cs @@ -2,12 +2,13 @@ // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. -namespace System.Globalization { - - using System; +using System.Runtime.InteropServices; + +namespace System.Globalization +{ // This class represents a starting/ending time for a period of daylight saving time. [Serializable] - [System.Runtime.InteropServices.ComVisible(true)] + [ComVisible(true)] public class DaylightTime { internal DateTime m_start; @@ -46,4 +47,18 @@ namespace System.Globalization { } + // Value type version of DaylightTime + internal struct DaylightTimeStruct + { + public DaylightTimeStruct(DateTime start, DateTime end, TimeSpan delta) + { + Start = start; + End = end; + Delta = delta; + } + + public DateTime Start { get; } + public DateTime End { get; } + public TimeSpan Delta { get; } + } } diff --git a/src/mscorlib/src/System/Globalization/EastAsianLunisolarCalendar.cs b/src/mscorlib/src/System/Globalization/EastAsianLunisolarCalendar.cs index 2460eee3af..3c9391fa63 100644 --- a/src/mscorlib/src/System/Globalization/EastAsianLunisolarCalendar.cs +++ b/src/mscorlib/src/System/Globalization/EastAsianLunisolarCalendar.cs @@ -65,7 +65,7 @@ namespace System.Globalization { public int GetCelestialStem(int sexagenaryYear) { if ((sexagenaryYear < 1) || (sexagenaryYear > 60)) { throw new ArgumentOutOfRangeException( - "sexagenaryYear", + nameof(sexagenaryYear), Environment.GetResourceString("ArgumentOutOfRange_Range", 1, 60)); } Contract.EndContractBlock(); @@ -80,7 +80,7 @@ namespace System.Globalization { public int GetTerrestrialBranch(int sexagenaryYear) { if ((sexagenaryYear < 1) || (sexagenaryYear > 60)) { throw new ArgumentOutOfRangeException( - "sexagenaryYear", + nameof(sexagenaryYear), Environment.GetResourceString("ArgumentOutOfRange_Range", 1, 60)); } Contract.EndContractBlock(); @@ -121,7 +121,7 @@ namespace System.Globalization { return (mEraInfo[i].minEraYear); } } - throw new ArgumentOutOfRangeException("era", Environment.GetResourceString("ArgumentOutOfRange_InvalidEraValue")); + throw new ArgumentOutOfRangeException(nameof(era), Environment.GetResourceString("ArgumentOutOfRange_InvalidEraValue")); } internal int MaxEraCalendarYear (int era) { @@ -144,7 +144,7 @@ namespace System.Globalization { return (mEraInfo[i].maxEraYear); } } - throw new ArgumentOutOfRangeException("era", Environment.GetResourceString("ArgumentOutOfRange_InvalidEraValue")); + throw new ArgumentOutOfRangeException(nameof(era), Environment.GetResourceString("ArgumentOutOfRange_InvalidEraValue")); } // Construct an instance of EastAsianLunisolar calendar. @@ -168,7 +168,7 @@ namespace System.Globalization { } if ((era <GetEra(MinDate)) || (era > GetEra(MaxDate))) { - throw new ArgumentOutOfRangeException("era", Environment.GetResourceString("ArgumentOutOfRange_InvalidEraValue")); + throw new ArgumentOutOfRangeException(nameof(era), Environment.GetResourceString("ArgumentOutOfRange_InvalidEraValue")); } } @@ -178,7 +178,7 @@ namespace System.Globalization { if ((year < MinCalendarYear) || (year > MaxCalendarYear)) { throw new ArgumentOutOfRangeException( - "year", + nameof(year), Environment.GetResourceString("ArgumentOutOfRange_Range", MinEraCalendarYear(era), MaxEraCalendarYear(era))); } return year; @@ -191,11 +191,11 @@ namespace System.Globalization { { //Reject if there is no leap month this year if (GetYearInfo(year , LeapMonth) == 0) - throw new ArgumentOutOfRangeException("month", Environment.GetResourceString("ArgumentOutOfRange_Month")); + throw new ArgumentOutOfRangeException(nameof(month), Environment.GetResourceString("ArgumentOutOfRange_Month")); } if (month < 1 || month > 13) { - throw new ArgumentOutOfRangeException("month", Environment.GetResourceString("ArgumentOutOfRange_Month")); + throw new ArgumentOutOfRangeException(nameof(month), Environment.GetResourceString("ArgumentOutOfRange_Month")); } return year; } @@ -236,7 +236,7 @@ namespace System.Globalization { if (day < 1 || day > daysInMonth) { BCLDebug.Log("year = " + year + ", month = " + month + ", day = " + day); throw new ArgumentOutOfRangeException( - "day", + nameof(day), Environment.GetResourceString("ArgumentOutOfRange_Day", daysInMonth, month)); } @@ -399,7 +399,7 @@ namespace System.Globalization { public override DateTime AddMonths(DateTime time, int months) { if (months < -120000 || months > 120000) { throw new ArgumentOutOfRangeException( - "months", + nameof(months), Environment.GetResourceString("ArgumentOutOfRange_Range", -120000, 120000)); } Contract.EndContractBlock(); @@ -561,7 +561,7 @@ namespace System.Globalization { if (day < 1 || day > daysInMonth) { throw new ArgumentOutOfRangeException( - "day", + nameof(day), Environment.GetResourceString("ArgumentOutOfRange_Day", daysInMonth, month)); } int m = GetYearInfo(year, LeapMonth); @@ -620,7 +620,7 @@ namespace System.Globalization { if (value < 99 || value > MaxCalendarYear) { throw new ArgumentOutOfRangeException( - "value", + nameof(value), Environment.GetResourceString("ArgumentOutOfRange_Range", 99, MaxCalendarYear)); } twoDigitYearMax = value; @@ -630,7 +630,7 @@ namespace System.Globalization { public override int ToFourDigitYear(int year) { if (year < 0) { - throw new ArgumentOutOfRangeException("year", + throw new ArgumentOutOfRangeException(nameof(year), Environment.GetResourceString("ArgumentOutOfRange_NeedNonNegNum")); } Contract.EndContractBlock(); diff --git a/src/mscorlib/src/System/Globalization/EncodingDataItem.cs b/src/mscorlib/src/System/Globalization/EncodingDataItem.cs index 1dc1bd2eaf..89ac780587 100644 --- a/src/mscorlib/src/System/Globalization/EncodingDataItem.cs +++ b/src/mscorlib/src/System/Globalization/EncodingDataItem.cs @@ -27,14 +27,12 @@ namespace System.Globalization { internal String m_bodyName; internal uint m_flags; - [SecurityCritical] unsafe internal CodePageDataItem(int dataIndex) { m_dataIndex = dataIndex; m_uiFamilyCodePage = EncodingTable.codePageDataPtr[dataIndex].uiFamilyCodePage; m_flags = EncodingTable.codePageDataPtr[dataIndex].flags; } - [System.Security.SecurityCritical] unsafe internal static String CreateString(sbyte* pStrings, uint index) { if (pStrings[0] == '|') // |str1|str2|str3 @@ -62,7 +60,7 @@ namespace System.Globalization { } } - throw new ArgumentException("pStrings"); + throw new ArgumentException(null, nameof(pStrings)); } else { @@ -71,7 +69,6 @@ namespace System.Globalization { } unsafe public String WebName { - [System.Security.SecuritySafeCritical] // auto-generated get { if (m_webName==null) { m_webName = CreateString(EncodingTable.codePageDataPtr[m_dataIndex].Names, 0); @@ -87,7 +84,6 @@ namespace System.Globalization { } unsafe public String HeaderName { - [System.Security.SecuritySafeCritical] // auto-generated get { if (m_headerName==null) { m_headerName = CreateString(EncodingTable.codePageDataPtr[m_dataIndex].Names, 1); @@ -97,7 +93,6 @@ namespace System.Globalization { } unsafe public String BodyName { - [System.Security.SecuritySafeCritical] // auto-generated get { if (m_bodyName==null) { m_bodyName = CreateString(EncodingTable.codePageDataPtr[m_dataIndex].Names, 2); diff --git a/src/mscorlib/src/System/Globalization/EncodingTable.Unix.cs b/src/mscorlib/src/System/Globalization/EncodingTable.Unix.cs index 5628a2def9..0fce2e58fc 100644 --- a/src/mscorlib/src/System/Globalization/EncodingTable.Unix.cs +++ b/src/mscorlib/src/System/Globalization/EncodingTable.Unix.cs @@ -3,6 +3,7 @@ // See the LICENSE file in the project root for more information. using System.Collections.Generic; +using System.Diagnostics; using System.Diagnostics.Contracts; using System.Text; @@ -30,7 +31,7 @@ namespace System.Globalization { if (name == null) { - throw new ArgumentNullException("name"); + throw new ArgumentNullException(nameof(name)); } Contract.EndContractBlock(); @@ -44,7 +45,7 @@ namespace System.Globalization throw new ArgumentException( string.Format( CultureInfo.CurrentCulture, - Environment.GetResourceString("Argument_EncodingNotSupported"), name), "name"); + Environment.GetResourceString("Argument_EncodingNotSupported"), name), nameof(name)); } internal static CodePageDataItem GetCodePageDataItem(int codepage) @@ -82,7 +83,7 @@ namespace System.Globalization break; } - Contract.Assert(item == null || item.CodePage == codepage, "item.CodePage needs to equal the specified codepage"); + Debug.Assert(item == null || item.CodePage == codepage, "item.CodePage needs to equal the specified codepage"); return item; } @@ -91,7 +92,7 @@ namespace System.Globalization #if DEBUG static EncodingTable() { - Contract.Assert( + Debug.Assert( s_encodingDataTable.Count == EncodingTableCapacity, string.Format(CultureInfo.InvariantCulture, "EncodingTable s_encodingDataTable's initial capacity (EncodingTableCapacity) is incorrect.{0}Expected (s_encodingDataTable.Count): {1}, Actual (EncodingTableCapacity): {2}", diff --git a/src/mscorlib/src/System/Globalization/EncodingTable.cs b/src/mscorlib/src/System/Globalization/EncodingTable.cs index cdda9eaf6d..d908a2ac2b 100644 --- a/src/mscorlib/src/System/Globalization/EncodingTable.cs +++ b/src/mscorlib/src/System/Globalization/EncodingTable.cs @@ -34,13 +34,11 @@ namespace System.Globalization // // This points to a native data table which maps an encoding name to the correct code page. // - [SecurityCritical] unsafe internal static InternalEncodingDataItem *encodingDataPtr = GetEncodingData(); // // This points to a native data table which stores the properties for the code page, and // the table is indexed by code page. // - [SecurityCritical] unsafe internal static InternalCodePageDataItem *codePageDataPtr = GetCodePageData(); // // This caches the mapping of an encoding name to a code page. @@ -51,14 +49,12 @@ namespace System.Globalization // private static Hashtable hashByCodePage = Hashtable.Synchronized(new Hashtable()); - [System.Security.SecuritySafeCritical] // static constructors should be safe to call static EncodingTable() { } // Find the data item by binary searching the table that we have in native. // nativeCompareOrdinalWC is an internal-only function. - [System.Security.SecuritySafeCritical] // auto-generated unsafe private static int internalGetCodePageFromName(String name) { int left = 0; int right = lastEncodingItem; @@ -94,11 +90,10 @@ namespace System.Globalization throw new ArgumentException( String.Format( CultureInfo.CurrentCulture, - Environment.GetResourceString("Argument_EncodingNotSupported"), name), "name"); + Environment.GetResourceString("Argument_EncodingNotSupported"), name), nameof(name)); } // Return a list of all EncodingInfo objects describing all of our encodings - [System.Security.SecuritySafeCritical] // auto-generated internal static unsafe EncodingInfo[] GetEncodings() { if (lastCodePageItem == 0) @@ -136,7 +131,7 @@ namespace System.Globalization internal static int GetCodePageFromName(String name) { if (name==null) { - throw new ArgumentNullException("name"); + throw new ArgumentNullException(nameof(name)); } Contract.EndContractBlock(); @@ -161,7 +156,6 @@ namespace System.Globalization return codePage; } - [System.Security.SecuritySafeCritical] // auto-generated unsafe internal static CodePageDataItem GetCodePageDataItem(int codepage) { CodePageDataItem dataItem; @@ -198,22 +192,18 @@ namespace System.Globalization return null; } - [System.Security.SecurityCritical] // auto-generated [MethodImplAttribute(MethodImplOptions.InternalCall)] private unsafe static extern InternalEncodingDataItem *GetEncodingData(); // // Return the number of encoding data items. // - [System.Security.SecurityCritical] // auto-generated [MethodImplAttribute(MethodImplOptions.InternalCall)] private static extern int GetNumEncodingItems(); - [System.Security.SecurityCritical] // auto-generated [MethodImplAttribute(MethodImplOptions.InternalCall)] private unsafe static extern InternalCodePageDataItem* GetCodePageData(); - [System.Security.SecurityCritical] // auto-generated [MethodImplAttribute(MethodImplOptions.InternalCall)] internal unsafe static extern byte* nativeCreateOpenFileMapping( String inSectionName, int inBytesToAllocate, out IntPtr mappedFileHandle); @@ -228,7 +218,6 @@ namespace System.Globalization [System.Runtime.InteropServices.StructLayout(LayoutKind.Sequential)] internal unsafe struct InternalEncodingDataItem { - [SecurityCritical] internal sbyte * webName; internal UInt16 codePage; } @@ -243,7 +232,6 @@ namespace System.Globalization internal UInt16 codePage; internal UInt16 uiFamilyCodePage; internal uint flags; - [SecurityCritical] internal sbyte * Names; } diff --git a/src/mscorlib/src/System/Globalization/GlobalizationAssembly.cs b/src/mscorlib/src/System/Globalization/GlobalizationAssembly.cs index 4de3fd399b..0810d67b59 100644 --- a/src/mscorlib/src/System/Globalization/GlobalizationAssembly.cs +++ b/src/mscorlib/src/System/Globalization/GlobalizationAssembly.cs @@ -15,6 +15,7 @@ namespace System.Globalization { using System.Runtime.ConstrainedExecution; using System.Runtime.Versioning; using System.IO; + using System.Diagnostics; using System.Diagnostics.Contracts; @@ -32,10 +33,9 @@ namespace System.Globalization { // Instance data members and instance methods. // // ---------------------------------------------------------------------------------------------------- - [System.Security.SecurityCritical] // auto-generated internal unsafe static byte* GetGlobalizationResourceBytePtr(Assembly assembly, String tableName) { - Contract.Assert(assembly != null, "assembly can not be null. This should be generally the "+System.CoreLib.Name+" assembly."); - Contract.Assert(tableName != null, "table name can not be null"); + Debug.Assert(assembly != null, "assembly can not be null. This should be generally the "+System.CoreLib.Name+" assembly."); + Debug.Assert(tableName != null, "table name can not be null"); Stream stream = assembly.GetManifestResourceStream(tableName); UnmanagedMemoryStream bytesStream = stream as UnmanagedMemoryStream; @@ -46,7 +46,7 @@ namespace System.Globalization { } } - Contract.Assert( + Debug.Assert( false, String.Format( CultureInfo.CurrentCulture, diff --git a/src/mscorlib/src/System/Globalization/GregorianCalendar.cs b/src/mscorlib/src/System/Globalization/GregorianCalendar.cs index e540adda9f..6cf9b2eb85 100644 --- a/src/mscorlib/src/System/Globalization/GregorianCalendar.cs +++ b/src/mscorlib/src/System/Globalization/GregorianCalendar.cs @@ -132,7 +132,7 @@ namespace System.Globalization { public GregorianCalendar(GregorianCalendarTypes type) { if ((int)type < (int)GregorianCalendarTypes.Localized || (int)type > (int)GregorianCalendarTypes.TransliteratedFrench) { throw new ArgumentOutOfRangeException( - "type", + nameof(type), Environment.GetResourceString("ArgumentOutOfRange_Range", GregorianCalendarTypes.Localized, GregorianCalendarTypes.TransliteratedFrench)); } @@ -159,7 +159,7 @@ namespace System.Globalization { break; default: - throw new ArgumentOutOfRangeException("m_type", Environment.GetResourceString("ArgumentOutOfRange_Enum")); + throw new ArgumentOutOfRangeException(nameof(m_type), Environment.GetResourceString("ArgumentOutOfRange_Enum")); } } } @@ -217,7 +217,7 @@ namespace System.Globalization { int[] days = leapYear? DaysToMonth366: DaysToMonth365; // All months have less than 32 days, so n >> 5 is a good conservative // estimate for the month - int m = n >> 5 + 1; + int m = (n >> 5) + 1; // m = 1-based month number while (n >= days[m]) m++; // If month was requested, return it @@ -285,7 +285,7 @@ namespace System.Globalization { { if (months < -120000 || months > 120000) { throw new ArgumentOutOfRangeException( - "months", + nameof(months), String.Format( CultureInfo.CurrentCulture, Environment.GetResourceString("ArgumentOutOfRange_Range"), @@ -371,16 +371,16 @@ namespace System.Globalization { public override int GetDaysInMonth(int year, int month, int era) { if (era == CurrentEra || era == ADEra) { if (year < 1 || year > MaxYear) { - throw new ArgumentOutOfRangeException("year", Environment.GetResourceString("ArgumentOutOfRange_Range", + throw new ArgumentOutOfRangeException(nameof(year), Environment.GetResourceString("ArgumentOutOfRange_Range", 1, MaxYear)); } if (month < 1 || month > 12) { - throw new ArgumentOutOfRangeException("month", Environment.GetResourceString("ArgumentOutOfRange_Month")); + throw new ArgumentOutOfRangeException(nameof(month), Environment.GetResourceString("ArgumentOutOfRange_Month")); } int[] days = ((year % 4 == 0 && (year % 100 != 0 || year % 400 == 0)) ? DaysToMonth366: DaysToMonth365); return (days[month] - days[month - 1]); } - throw new ArgumentOutOfRangeException("era", Environment.GetResourceString("ArgumentOutOfRange_InvalidEraValue")); + throw new ArgumentOutOfRangeException(nameof(era), Environment.GetResourceString("ArgumentOutOfRange_InvalidEraValue")); } // Returns the number of days in the year given by the year argument for the current era. @@ -393,14 +393,14 @@ namespace System.Globalization { return ((year % 4 == 0 && (year % 100 != 0 || year % 400 == 0)) ? 366:365); } throw new ArgumentOutOfRangeException( - "year", + nameof(year), String.Format( CultureInfo.CurrentCulture, Environment.GetResourceString("ArgumentOutOfRange_Range"), 1, MaxYear)); } - throw new ArgumentOutOfRangeException("era", Environment.GetResourceString("ArgumentOutOfRange_InvalidEraValue")); + throw new ArgumentOutOfRangeException(nameof(era), Environment.GetResourceString("ArgumentOutOfRange_InvalidEraValue")); } // Returns the era for the specified DateTime value. @@ -437,14 +437,14 @@ namespace System.Globalization { return (12); } throw new ArgumentOutOfRangeException( - "year", + nameof(year), String.Format( CultureInfo.CurrentCulture, Environment.GetResourceString("ArgumentOutOfRange_Range"), 1, MaxYear)); } - throw new ArgumentOutOfRangeException("era", Environment.GetResourceString("ArgumentOutOfRange_InvalidEraValue")); + throw new ArgumentOutOfRangeException(nameof(era), Environment.GetResourceString("ArgumentOutOfRange_InvalidEraValue")); } // Returns the year part of the specified DateTime. The returned value is an @@ -463,23 +463,23 @@ namespace System.Globalization { public override bool IsLeapDay(int year, int month, int day, int era) { if (month < 1 || month > 12) { - throw new ArgumentOutOfRangeException("month", Environment.GetResourceString("ArgumentOutOfRange_Range", + throw new ArgumentOutOfRangeException(nameof(month), Environment.GetResourceString("ArgumentOutOfRange_Range", 1, 12)); } Contract.EndContractBlock(); if (era != CurrentEra && era != ADEra) { - throw new ArgumentOutOfRangeException("era", Environment.GetResourceString("ArgumentOutOfRange_InvalidEraValue")); + throw new ArgumentOutOfRangeException(nameof(era), Environment.GetResourceString("ArgumentOutOfRange_InvalidEraValue")); } if (year < 1 || year > MaxYear) { throw new ArgumentOutOfRangeException( - "year", + nameof(year), Environment.GetResourceString("ArgumentOutOfRange_Range", 1, MaxYear)); } if (day < 1 || day > GetDaysInMonth(year, month)) { - throw new ArgumentOutOfRangeException("day", Environment.GetResourceString("ArgumentOutOfRange_Range", + throw new ArgumentOutOfRangeException(nameof(day), Environment.GetResourceString("ArgumentOutOfRange_Range", 1, GetDaysInMonth(year, month))); } if (!IsLeapYear(year)) { @@ -500,11 +500,11 @@ namespace System.Globalization { { if (era != CurrentEra && era != ADEra) { - throw new ArgumentOutOfRangeException("era", Environment.GetResourceString("ArgumentOutOfRange_InvalidEraValue")); + throw new ArgumentOutOfRangeException(nameof(era), Environment.GetResourceString("ArgumentOutOfRange_InvalidEraValue")); } if (year < 1 || year > MaxYear) { throw new ArgumentOutOfRangeException( - "year", + nameof(year), String.Format( CultureInfo.CurrentCulture, Environment.GetResourceString("ArgumentOutOfRange_Range"), 1, MaxYear)); @@ -520,19 +520,19 @@ namespace System.Globalization { public override bool IsLeapMonth(int year, int month, int era) { if (era != CurrentEra && era != ADEra) { - throw new ArgumentOutOfRangeException("era", Environment.GetResourceString("ArgumentOutOfRange_InvalidEraValue")); + throw new ArgumentOutOfRangeException(nameof(era), Environment.GetResourceString("ArgumentOutOfRange_InvalidEraValue")); } if (year < 1 || year > MaxYear) { throw new ArgumentOutOfRangeException( - "year", + nameof(year), String.Format( CultureInfo.CurrentCulture, Environment.GetResourceString("ArgumentOutOfRange_Range"), 1, MaxYear)); } if (month < 1 || month > 12) { - throw new ArgumentOutOfRangeException("month", Environment.GetResourceString("ArgumentOutOfRange_Range", + throw new ArgumentOutOfRangeException(nameof(month), Environment.GetResourceString("ArgumentOutOfRange_Range", 1, 12)); } Contract.EndContractBlock(); @@ -551,12 +551,12 @@ namespace System.Globalization { } throw new ArgumentOutOfRangeException( - "year", + nameof(year), String.Format( CultureInfo.CurrentCulture, Environment.GetResourceString("ArgumentOutOfRange_Range"), 1, MaxYear)); } - throw new ArgumentOutOfRangeException("era", Environment.GetResourceString("ArgumentOutOfRange_InvalidEraValue")); + throw new ArgumentOutOfRangeException(nameof(era), Environment.GetResourceString("ArgumentOutOfRange_InvalidEraValue")); } // Returns the date and time converted to a DateTime value. Throws an exception if the n-tuple is invalid. @@ -567,7 +567,7 @@ namespace System.Globalization { if (era == CurrentEra || era == ADEra) { return new DateTime(year, month, day, hour, minute, second, millisecond); } - throw new ArgumentOutOfRangeException("era", Environment.GetResourceString("ArgumentOutOfRange_InvalidEraValue")); + throw new ArgumentOutOfRangeException(nameof(era), Environment.GetResourceString("ArgumentOutOfRange_InvalidEraValue")); } internal override Boolean TryToDateTime(int year, int month, int day, int hour, int minute, int second, int millisecond, int era, out DateTime result) { @@ -609,14 +609,14 @@ namespace System.Globalization { public override int ToFourDigitYear(int year) { if (year < 0) { - throw new ArgumentOutOfRangeException("year", + throw new ArgumentOutOfRangeException(nameof(year), Environment.GetResourceString("ArgumentOutOfRange_NeedNonNegNum")); } Contract.EndContractBlock(); if (year > MaxYear) { throw new ArgumentOutOfRangeException( - "year", + nameof(year), String.Format( CultureInfo.CurrentCulture, Environment.GetResourceString("ArgumentOutOfRange_Range"), 1, MaxYear)); diff --git a/src/mscorlib/src/System/Globalization/GregorianCalendarHelper.cs b/src/mscorlib/src/System/Globalization/GregorianCalendarHelper.cs index 75b280d457..062ae4818a 100644 --- a/src/mscorlib/src/System/Globalization/GregorianCalendarHelper.cs +++ b/src/mscorlib/src/System/Globalization/GregorianCalendarHelper.cs @@ -153,7 +153,7 @@ namespace System.Globalization { internal int GetGregorianYear(int year, int era) { if (year < 0) { - throw new ArgumentOutOfRangeException("year", + throw new ArgumentOutOfRangeException(nameof(year), Environment.GetResourceString("ArgumentOutOfRange_NeedNonNegNum")); } Contract.EndContractBlock(); @@ -166,7 +166,7 @@ namespace System.Globalization { if (era == m_EraInfo[i].era) { if (year < m_EraInfo[i].minEraYear || year > m_EraInfo[i].maxEraYear) { throw new ArgumentOutOfRangeException( - "year", + nameof(year), String.Format( CultureInfo.CurrentCulture, Environment.GetResourceString("ArgumentOutOfRange_Range"), @@ -176,7 +176,7 @@ namespace System.Globalization { return (m_EraInfo[i].yearOffset + year); } } - throw new ArgumentOutOfRangeException("era", Environment.GetResourceString("ArgumentOutOfRange_InvalidEraValue")); + throw new ArgumentOutOfRangeException(nameof(era), Environment.GetResourceString("ArgumentOutOfRange_InvalidEraValue")); } internal bool IsValidYear(int year, int era) { @@ -243,7 +243,7 @@ namespace System.Globalization { int[] days = leapYear? DaysToMonth366: DaysToMonth365; // All months have less than 32 days, so n >> 5 is a good conservative // estimate for the month - int m = n >> 5 + 1; + int m = (n >> 5) + 1; // m = 1-based month number while (n >= days[m]) m++; // If month was requested, return it @@ -299,7 +299,7 @@ namespace System.Globalization { { if (millisecond < 0 || millisecond >= MillisPerSecond) { throw new ArgumentOutOfRangeException( - "millisecond", + nameof(millisecond), String.Format( CultureInfo.CurrentCulture, Environment.GetResourceString("ArgumentOutOfRange_Range"), @@ -346,7 +346,7 @@ namespace System.Globalization { { if (months < -120000 || months > 120000) { throw new ArgumentOutOfRangeException( - "months", + nameof(months), String.Format( CultureInfo.CurrentCulture, Environment.GetResourceString("ArgumentOutOfRange_Range"), @@ -432,7 +432,7 @@ namespace System.Globalization { // year = GetGregorianYear(year, era); if (month < 1 || month > 12) { - throw new ArgumentOutOfRangeException("month", Environment.GetResourceString("ArgumentOutOfRange_Month")); + throw new ArgumentOutOfRangeException(nameof(month), Environment.GetResourceString("ArgumentOutOfRange_Month")); } int[] days = ((year % 4 == 0 && (year % 100 != 0 || year % 400 == 0)) ? DaysToMonth366: DaysToMonth365); return (days[month] - days[month - 1]); @@ -460,7 +460,7 @@ namespace System.Globalization { return (m_EraInfo[i].era); } } - throw new ArgumentOutOfRangeException("time", Environment.GetResourceString("ArgumentOutOfRange_Era")); + throw new ArgumentOutOfRangeException(nameof(time), Environment.GetResourceString("ArgumentOutOfRange_Era")); } @@ -533,7 +533,7 @@ namespace System.Globalization { // year/month/era checking is done in GetDaysInMonth() if (day < 1 || day > GetDaysInMonth(year, month, era)) { throw new ArgumentOutOfRangeException( - "day", + nameof(day), String.Format( CultureInfo.CurrentCulture, Environment.GetResourceString("ArgumentOutOfRange_Range"), @@ -570,7 +570,7 @@ namespace System.Globalization { year = GetGregorianYear(year, era); if (month < 1 || month > 12) { throw new ArgumentOutOfRangeException( - "month", + nameof(month), String.Format( CultureInfo.CurrentCulture, Environment.GetResourceString("ArgumentOutOfRange_Range"), @@ -607,7 +607,7 @@ namespace System.Globalization { public int ToFourDigitYear(int year, int twoDigitYearMax) { if (year < 0) { - throw new ArgumentOutOfRangeException("year", + throw new ArgumentOutOfRangeException(nameof(year), Environment.GetResourceString("ArgumentOutOfRange_NeedPosNum")); } Contract.EndContractBlock(); @@ -619,7 +619,7 @@ namespace System.Globalization { if (year < m_minYear || year > m_maxYear) { throw new ArgumentOutOfRangeException( - "year", + nameof(year), String.Format( CultureInfo.CurrentCulture, Environment.GetResourceString("ArgumentOutOfRange_Range"), m_minYear, m_maxYear)); diff --git a/src/mscorlib/src/System/Globalization/HebrewCalendar.cs b/src/mscorlib/src/System/Globalization/HebrewCalendar.cs index 3a17494001..44cbdb8bde 100644 --- a/src/mscorlib/src/System/Globalization/HebrewCalendar.cs +++ b/src/mscorlib/src/System/Globalization/HebrewCalendar.cs @@ -5,6 +5,7 @@ namespace System.Globalization { using System; using System.Text; + using System.Diagnostics; using System.Diagnostics.Contracts; //////////////////////////////////////////////////////////////////////////// @@ -397,7 +398,7 @@ namespace System.Globalization { int monthsInYear = GetMonthsInYear(year, era); if (month < 1 || month > monthsInYear) { throw new ArgumentOutOfRangeException( - "month", + nameof(month), String.Format( CultureInfo.CurrentCulture, Environment.GetResourceString("ArgumentOutOfRange_Range"), @@ -421,7 +422,7 @@ namespace System.Globalization { int daysInMonth = GetDaysInMonth(year, month, era); if (day < 1 || day > daysInMonth) { throw new ArgumentOutOfRangeException( - "day", + nameof(day), String.Format( CultureInfo.CurrentCulture, Environment.GetResourceString("ArgumentOutOfRange_Range"), @@ -432,7 +433,7 @@ namespace System.Globalization { static internal void CheckEraRange(int era) { if (era != CurrentEra && era != HebrewEra) { - throw new ArgumentOutOfRangeException("era", Environment.GetResourceString("ArgumentOutOfRange_InvalidEraValue")); + throw new ArgumentOutOfRangeException(nameof(era), Environment.GetResourceString("ArgumentOutOfRange_InvalidEraValue")); } } @@ -486,7 +487,7 @@ namespace System.Globalization { // int index = gregorianYear - FirstGregorianTableYear; if (index < 0 || index > TABLESIZE) { - throw new ArgumentOutOfRangeException("gregorianYear"); + throw new ArgumentOutOfRangeException(nameof(gregorianYear)); } index *= 2; @@ -607,7 +608,7 @@ namespace System.Globalization { // is true. // NumDays -= (long)(LunarMonthLen[hebrewYearType, lunarDate.month] - lunarDate.day); - Contract.Assert(NumDays >= 1, "NumDays >= 1"); + Debug.Assert(NumDays >= 1, "NumDays >= 1"); // If NumDays is 1, then we are done. Otherwise, find the correct Hebrew month // and day. @@ -705,7 +706,7 @@ namespace System.Globalization { catch (ArgumentException) { throw new ArgumentOutOfRangeException( - "months", + nameof(months), String.Format( CultureInfo.CurrentCulture, Environment.GetResourceString("ArgumentOutOfRange_AddValue"))); @@ -727,7 +728,7 @@ namespace System.Globalization { int d = GetDatePart(time.Ticks, DatePartDay); y += years; - CheckHebrewYearValue(y, Calendar.CurrentEra, "years"); + CheckHebrewYearValue(y, Calendar.CurrentEra, nameof(years)); int months = GetMonthsInYear(y, CurrentEra); if (m > months) { @@ -765,7 +766,7 @@ namespace System.Globalization { } static internal int GetHebrewYearType(int year, int era) { - CheckHebrewYearValue(year, era, "year"); + CheckHebrewYearValue(year, era, nameof(year)); // The HebrewTable is indexed by Gregorian year and starts from FirstGregorianYear. // So we need to convert year (Hebrew year value) to Gregorian Year below. return (HebrewTable[(year - HebrewYearOf1AD - FirstGregorianTableYear) * 2 + 1]); @@ -811,11 +812,11 @@ namespace System.Globalization { int hebrewYearType = GetHebrewYearType(year, era); CheckHebrewMonthValue(year, month, era); - Contract.Assert(hebrewYearType>= 1 && hebrewYearType <= 6, + Debug.Assert(hebrewYearType>= 1 && hebrewYearType <= 6, "hebrewYearType should be from 1 to 6, but now hebrewYearType = " + hebrewYearType + " for hebrew year " + year); int monthDays = LunarMonthLen[hebrewYearType, month]; if (monthDays == 0) { - throw new ArgumentOutOfRangeException("month", Environment.GetResourceString("ArgumentOutOfRange_Month")); + throw new ArgumentOutOfRangeException(nameof(month), Environment.GetResourceString("ArgumentOutOfRange_Month")); } return (monthDays); } @@ -931,7 +932,7 @@ namespace System.Globalization { // public override bool IsLeapYear(int year, int era) { - CheckHebrewYearValue(year, era, "year"); + CheckHebrewYearValue(year, era, nameof(year)); return (((7 * (long)year + 1) % 19) < 7); } @@ -1015,7 +1016,7 @@ namespace System.Globalization { // public override DateTime ToDateTime(int year, int month, int day, int hour, int minute, int second, int millisecond, int era) { - CheckHebrewYearValue(year, era, "year"); + CheckHebrewYearValue(year, era, nameof(year)); CheckHebrewMonthValue(year, month, era); CheckHebrewDayValue(year, month, day, era); DateTime dt = HebrewToGregorian(year, month, day, hour, minute, second, millisecond); @@ -1042,7 +1043,7 @@ namespace System.Globalization { } else { - CheckHebrewYearValue(value, HebrewEra, "value"); + CheckHebrewYearValue(value, HebrewEra, nameof(value)); } twoDigitYearMax = value; } @@ -1051,7 +1052,7 @@ namespace System.Globalization { public override int ToFourDigitYear(int year) { if (year < 0) { - throw new ArgumentOutOfRangeException("year", + throw new ArgumentOutOfRangeException(nameof(year), Environment.GetResourceString("ArgumentOutOfRange_NeedNonNegNum")); } Contract.EndContractBlock(); @@ -1062,7 +1063,7 @@ namespace System.Globalization { if (year > MaxHebrewYear || year < MinHebrewYear) { throw new ArgumentOutOfRangeException( - "year", + nameof(year), String.Format( CultureInfo.CurrentCulture, Environment.GetResourceString("ArgumentOutOfRange_Range"), diff --git a/src/mscorlib/src/System/Globalization/HebrewNumber.cs b/src/mscorlib/src/System/Globalization/HebrewNumber.cs index cf0595585a..5517cb14ea 100644 --- a/src/mscorlib/src/System/Globalization/HebrewNumber.cs +++ b/src/mscorlib/src/System/Globalization/HebrewNumber.cs @@ -6,6 +6,7 @@ namespace System.Globalization { using System; using System.Text; + using System.Diagnostics; using System.Diagnostics.Contracts; //////////////////////////////////////////////////////////////////////////// @@ -98,7 +99,7 @@ namespace System.Globalization { Number -= 5000; } - Contract.Assert(Number > 0 && Number <= 999, "Number is out of range.");; + Debug.Assert(Number > 0 && Number <= 999, "Number is out of range.");; // // Get the Hundreds. diff --git a/src/mscorlib/src/System/Globalization/HijriCalendar.cs b/src/mscorlib/src/System/Globalization/HijriCalendar.cs index 194d329d25..39a01e5774 100644 --- a/src/mscorlib/src/System/Globalization/HijriCalendar.cs +++ b/src/mscorlib/src/System/Globalization/HijriCalendar.cs @@ -209,7 +209,6 @@ namespace System.Globalization { public int HijriAdjustment { - [System.Security.SecuritySafeCritical] // auto-generated get { if (m_HijriAdvance == Int32.MinValue) { // Never been set before. Use the system value from registry. @@ -222,7 +221,7 @@ namespace System.Globalization { // NOTE: Check the value of Min/MaxAdavncedHijri with Arabic speakers to see if the assumption is good. if (value < MinAdvancedHijri || value > MaxAdvancedHijri) { throw new ArgumentOutOfRangeException( - "HijriAdjustment", + nameof(HijriAdjustment), String.Format( CultureInfo.CurrentCulture, Environment.GetResourceString("ArgumentOutOfRange_Bounds_Lower_Upper"), @@ -252,7 +251,6 @@ namespace System.Globalization { ** "AddHijriDate+1" => Add +1 days to the current calculated Hijri date. ** "AddHijriDate+2" => Add +2 days to the current calculated Hijri date. ============================================================================*/ - [System.Security.SecurityCritical] // auto-generated static int GetAdvanceHijriDate() { #if FEATURE_WIN32_REGISTRY @@ -320,7 +318,7 @@ namespace System.Globalization { static internal void CheckEraRange(int era) { if (era != CurrentEra && era != HijriEra) { - throw new ArgumentOutOfRangeException("era", Environment.GetResourceString("ArgumentOutOfRange_InvalidEraValue")); + throw new ArgumentOutOfRangeException(nameof(era), Environment.GetResourceString("ArgumentOutOfRange_InvalidEraValue")); } } @@ -328,7 +326,7 @@ namespace System.Globalization { CheckEraRange(era); if (year < 1 || year > MaxCalendarYear) { throw new ArgumentOutOfRangeException( - "year", + nameof(year), String.Format( CultureInfo.CurrentCulture, Environment.GetResourceString("ArgumentOutOfRange_Range"), @@ -342,7 +340,7 @@ namespace System.Globalization { if (year == MaxCalendarYear) { if (month > MaxCalendarMonth) { throw new ArgumentOutOfRangeException( - "month", + nameof(month), String.Format( CultureInfo.CurrentCulture, Environment.GetResourceString("ArgumentOutOfRange_Range"), @@ -352,7 +350,7 @@ namespace System.Globalization { } if (month < 1 || month > 12) { - throw new ArgumentOutOfRangeException("month", Environment.GetResourceString("ArgumentOutOfRange_Month")); + throw new ArgumentOutOfRangeException(nameof(month), Environment.GetResourceString("ArgumentOutOfRange_Month")); } } @@ -465,7 +463,7 @@ namespace System.Globalization { public override DateTime AddMonths(DateTime time, int months) { if (months < -120000 || months > 120000) { throw new ArgumentOutOfRangeException( - "months", + nameof(months), String.Format( CultureInfo.CurrentCulture, Environment.GetResourceString("ArgumentOutOfRange_Range"), @@ -602,7 +600,7 @@ namespace System.Globalization { int daysInMonth = GetDaysInMonth(year, month, era); if (day < 1 || day > daysInMonth) { throw new ArgumentOutOfRangeException( - "day", + nameof(day), String.Format( CultureInfo.CurrentCulture, Environment.GetResourceString("ArgumentOutOfRange_Day"), @@ -650,7 +648,7 @@ namespace System.Globalization { if (day < 1 || day > daysInMonth) { BCLDebug.Log("year = " + year + ", month = " + month + ", day = " + day); throw new ArgumentOutOfRangeException( - "day", + nameof(day), String.Format( CultureInfo.CurrentCulture, Environment.GetResourceString("ArgumentOutOfRange_Day"), @@ -683,7 +681,7 @@ namespace System.Globalization { if (value < 99 || value > MaxCalendarYear) { throw new ArgumentOutOfRangeException( - "value", + nameof(value), String.Format( CultureInfo.CurrentCulture, Environment.GetResourceString("ArgumentOutOfRange_Range"), @@ -698,7 +696,7 @@ namespace System.Globalization { public override int ToFourDigitYear(int year) { if (year < 0) { - throw new ArgumentOutOfRangeException("year", + throw new ArgumentOutOfRangeException(nameof(year), Environment.GetResourceString("ArgumentOutOfRange_NeedNonNegNum")); } Contract.EndContractBlock(); @@ -709,7 +707,7 @@ namespace System.Globalization { if (year > MaxCalendarYear) { throw new ArgumentOutOfRangeException( - "year", + nameof(year), String.Format( CultureInfo.CurrentCulture, Environment.GetResourceString("ArgumentOutOfRange_Range"), diff --git a/src/mscorlib/src/System/Globalization/IdnMapping.cs b/src/mscorlib/src/System/Globalization/IdnMapping.cs index 599a32ad87..bf75f5be3c 100644 --- a/src/mscorlib/src/System/Globalization/IdnMapping.cs +++ b/src/mscorlib/src/System/Globalization/IdnMapping.cs @@ -65,6 +65,7 @@ namespace System.Globalization using System.Text; using System.Runtime.Versioning; using System.Runtime.InteropServices; + using System.Diagnostics; using System.Diagnostics.Contracts; // IdnMapping class used to map names to Punycode @@ -125,23 +126,22 @@ namespace System.Globalization public String GetAscii(String unicode, int index) { - if (unicode==null) throw new ArgumentNullException("unicode"); + if (unicode==null) throw new ArgumentNullException(nameof(unicode)); Contract.EndContractBlock(); return GetAscii(unicode, index, unicode.Length - index); } - public String GetAscii(String unicode, int index, int count) + public string GetAscii(String unicode, int index, int count) { - throw null; - /*if (unicode==null) throw new ArgumentNullException("unicode"); + if (unicode == null) throw new ArgumentNullException(nameof(unicode)); if (index < 0 || count < 0) - throw new ArgumentOutOfRangeException((index < 0) ? "index" : "count", + throw new ArgumentOutOfRangeException((index < 0) ? nameof(index) : nameof(count), Environment.GetResourceString("ArgumentOutOfRange_NeedNonNegNum")); if (index > unicode.Length) - throw new ArgumentOutOfRangeException("byteIndex", + throw new ArgumentOutOfRangeException(nameof(index), Environment.GetResourceString("ArgumentOutOfRange_Index")); if (index > unicode.Length - count) - throw new ArgumentOutOfRangeException("unicode", + throw new ArgumentOutOfRangeException(nameof(unicode), Environment.GetResourceString("ArgumentOutOfRange_IndexCountBuffer")); Contract.EndContractBlock(); @@ -161,12 +161,12 @@ namespace System.Globalization // Cannot be null terminated (normalization won't help us with this one, and // may have returned false before checking the whole string above) - Contract.Assert(unicode.Length >= 1, "[IdnMapping.GetAscii]Expected 0 length strings to fail before now."); + Debug.Assert(unicode.Length >= 1, "[IdnMapping.GetAscii]Expected 0 length strings to fail before now."); if (unicode[unicode.Length - 1] <= 0x1f) { throw new ArgumentException( Environment.GetResourceString("Argument_InvalidCharSequence", unicode.Length-1 ), - "unicode"); + nameof(unicode)); } // Have to correctly IDNA normalize the string and Unassigned flags @@ -178,7 +178,7 @@ namespace System.Globalization if ((!bHasLastDot) && unicode.Length > 0 && IsDot(unicode[unicode.Length - 1])) { throw new ArgumentException(Environment.GetResourceString( - "Argument_IdnBadLabelSize"), "unicode"); + "Argument_IdnBadLabelSize"), nameof(unicode)); } // May need to check Std3 rules again for non-ascii @@ -188,24 +188,23 @@ namespace System.Globalization } // Go ahead and encode it - return punycode_encode(unicode);*/ + return punycode_encode(unicode); } - [System.Security.SecuritySafeCritical] private String GetAsciiUsingOS(String unicode) { if (unicode.Length == 0) { throw new ArgumentException(Environment.GetResourceString( - "Argument_IdnBadLabelSize"), "unicode"); + "Argument_IdnBadLabelSize"), nameof(unicode)); } if (unicode[unicode.Length - 1] == 0) { throw new ArgumentException( Environment.GetResourceString("Argument_InvalidCharSequence", unicode.Length - 1), - "unicode"); + nameof(unicode)); } uint flags = (uint) ((AllowUnassigned ? IDN_ALLOW_UNASSIGNED : 0) | (UseStd3AsciiRules ? IDN_USE_STD3_ASCII_RULES : 0)); @@ -218,10 +217,10 @@ namespace System.Globalization lastError = Marshal.GetLastWin32Error(); if (lastError == ERROR_INVALID_NAME) { - throw new ArgumentException(Environment.GetResourceString("Argument_IdnIllegalName"), "unicode"); + throw new ArgumentException(Environment.GetResourceString("Argument_IdnIllegalName"), nameof(unicode)); } - throw new ArgumentException(Environment.GetResourceString("Argument_InvalidCharSequenceNoIndex"), "unicode"); + throw new ArgumentException(Environment.GetResourceString("Argument_InvalidCharSequenceNoIndex"), nameof(unicode)); } char [] output = new char[length]; @@ -232,10 +231,10 @@ namespace System.Globalization lastError = Marshal.GetLastWin32Error(); if (lastError == ERROR_INVALID_NAME) { - throw new ArgumentException(Environment.GetResourceString("Argument_IdnIllegalName"), "unicode"); + throw new ArgumentException(Environment.GetResourceString("Argument_IdnIllegalName"), nameof(unicode)); } - throw new ArgumentException(Environment.GetResourceString("Argument_InvalidCharSequenceNoIndex"), "unicode"); + throw new ArgumentException(Environment.GetResourceString("Argument_InvalidCharSequenceNoIndex"), nameof(unicode)); } return new String(output, 0, length); @@ -249,30 +248,30 @@ namespace System.Globalization public String GetUnicode(String ascii, int index) { - if (ascii==null) throw new ArgumentNullException("ascii"); + if (ascii==null) throw new ArgumentNullException(nameof(ascii)); Contract.EndContractBlock(); return GetUnicode(ascii, index, ascii.Length - index); } public String GetUnicode(String ascii, int index, int count) { - if (ascii==null) throw new ArgumentNullException("ascii"); + if (ascii==null) throw new ArgumentNullException(nameof(ascii)); if (index < 0 || count < 0) - throw new ArgumentOutOfRangeException((index < 0) ? "index" : "count", + throw new ArgumentOutOfRangeException((index < 0) ? nameof(index) : nameof(count), Environment.GetResourceString("ArgumentOutOfRange_NeedNonNegNum")); if (index > ascii.Length) throw new ArgumentOutOfRangeException("byteIndex", Environment.GetResourceString("ArgumentOutOfRange_Index")); if (index > ascii.Length - count) - throw new ArgumentOutOfRangeException("ascii", + throw new ArgumentOutOfRangeException(nameof(ascii), Environment.GetResourceString("ArgumentOutOfRange_IndexCountBuffer")); // This is a case (i.e. explicitly null-terminated input) where behavior in .NET and Win32 intentionally differ. // The .NET APIs should (and did in v4.0 and earlier) throw an ArgumentException on input that includes a terminating null. // The Win32 APIs fail on an embedded null, but not on a terminating null. if (count > 0 && ascii[index + count - 1] == (char)0) - throw new ArgumentException("ascii", - Environment.GetResourceString("Argument_IdnBadPunycode")); + throw new ArgumentException(Environment.GetResourceString("Argument_IdnBadPunycode"), + nameof(ascii)); Contract.EndContractBlock(); // We're only using part of the string @@ -289,13 +288,12 @@ namespace System.Globalization // Output name MUST obey IDNA rules & round trip (casing differences are allowed) if (!ascii.Equals(GetAscii(strUnicode), StringComparison.OrdinalIgnoreCase)) throw new ArgumentException(Environment.GetResourceString( - "Argument_IdnIllegalName"), "ascii"); + "Argument_IdnIllegalName"), nameof(ascii)); return strUnicode; } - [System.Security.SecuritySafeCritical] private string GetUnicodeUsingOS(string ascii) { uint flags = (uint)((AllowUnassigned ? IDN_ALLOW_UNASSIGNED : 0) | (UseStd3AsciiRules ? IDN_USE_STD3_ASCII_RULES : 0)); @@ -307,10 +305,10 @@ namespace System.Globalization lastError = Marshal.GetLastWin32Error(); if (lastError == ERROR_INVALID_NAME) { - throw new ArgumentException(Environment.GetResourceString("Argument_IdnIllegalName"), "ascii"); + throw new ArgumentException(Environment.GetResourceString("Argument_IdnIllegalName"), nameof(ascii)); } - throw new ArgumentException(Environment.GetResourceString("Argument_IdnBadPunycode"), "ascii"); + throw new ArgumentException(Environment.GetResourceString("Argument_IdnBadPunycode"), nameof(ascii)); } char [] output = new char[length]; @@ -321,10 +319,10 @@ namespace System.Globalization lastError = Marshal.GetLastWin32Error(); if (lastError == ERROR_INVALID_NAME) { - throw new ArgumentException(Environment.GetResourceString("Argument_IdnIllegalName"), "ascii"); + throw new ArgumentException(Environment.GetResourceString("Argument_IdnIllegalName"), nameof(ascii)); } - throw new ArgumentException(Environment.GetResourceString("Argument_IdnBadPunycode"), "ascii"); + throw new ArgumentException(Environment.GetResourceString("Argument_IdnBadPunycode"), nameof(ascii)); } return new String(output, 0, length); @@ -370,7 +368,7 @@ namespace System.Globalization // If its empty, then its too small if (unicode.Length == 0) throw new ArgumentException(Environment.GetResourceString( - "Argument_IdnBadLabelSize"), "unicode"); + "Argument_IdnBadLabelSize"), nameof(unicode)); Contract.EndContractBlock(); int iLastDot = -1; @@ -383,7 +381,7 @@ namespace System.Globalization { throw new ArgumentException( Environment.GetResourceString("Argument_InvalidCharSequence", i ), - "unicode"); + nameof(unicode)); } // If its Unicode or a control character, return false (non-ascii) @@ -396,12 +394,12 @@ namespace System.Globalization // Can't have 2 dots in a row if (i == iLastDot + 1) throw new ArgumentException(Environment.GetResourceString( - "Argument_IdnBadLabelSize"), "unicode"); + "Argument_IdnBadLabelSize"), nameof(unicode)); // If its too far between dots then fail if (i - iLastDot > M_labelLimit + 1) throw new ArgumentException(Environment.GetResourceString( - "Argument_IdnBadLabelSize"), "Unicode"); + "Argument_IdnBadLabelSize"), nameof(unicode)); // If validating Std3, then char before dot can't be - char if (bUseStd3 && i > 0) @@ -422,14 +420,14 @@ namespace System.Globalization // If we never had a dot, then we need to be shorter than the label limit if (iLastDot == -1 && unicode.Length > M_labelLimit) throw new ArgumentException(Environment.GetResourceString( - "Argument_IdnBadLabelSize"), "unicode"); + "Argument_IdnBadLabelSize"), nameof(unicode)); // Need to validate entire string length, 1 shorter if last char wasn't a dot if (unicode.Length > M_defaultNameLimit - (IsDot(unicode[unicode.Length-1])? 0 : 1)) throw new ArgumentException(Environment.GetResourceString( "Argument_IdnBadNameSize", M_defaultNameLimit - (IsDot(unicode[unicode.Length-1]) ? 0 : 1)), - "unicode"); + nameof(unicode)); // If last char wasn't a dot we need to check for trailing - if (bUseStd3 && !IsDot(unicode[unicode.Length-1])) @@ -510,7 +508,7 @@ namespace System.Globalization static char encode_digit(int d) { - Contract.Assert(d >= 0 && d < punycodeBase, "[IdnMapping.encode_digit]Expected 0 <= d < punycodeBase"); + Debug.Assert(d >= 0 && d < punycodeBase, "[IdnMapping.encode_digit]Expected 0 <= d < punycodeBase"); // 26-35 map to ASCII 0-9 if (d > 25) return (char)(d - 26 + '0'); @@ -547,7 +545,7 @@ namespace System.Globalization uint k; delta = firsttime ? delta / damp : delta / 2; - Contract.Assert(numpoints != 0, "[IdnMapping.adapt]Expected non-zero numpoints."); + Debug.Assert(numpoints != 0, "[IdnMapping.adapt]Expected non-zero numpoints."); delta += delta / numpoints; for (k = 0; delta > ((punycodeBase - tmin) * tmax) / 2; k += punycodeBase) @@ -555,7 +553,7 @@ namespace System.Globalization delta /= punycodeBase - tmin; } - Contract.Assert(delta + skew != 0, "[IdnMapping.adapt]Expected non-zero delta+skew."); + Debug.Assert(delta + skew != 0, "[IdnMapping.adapt]Expected non-zero delta+skew."); return (int)(k + (punycodeBase - tmin + 1) * delta / (delta + skew)); } @@ -592,7 +590,7 @@ namespace System.Globalization // 0 length strings aren't allowed if (unicode.Length == 0) throw new ArgumentException(Environment.GetResourceString( - "Argument_IdnBadLabelSize"), "unicode"); + "Argument_IdnBadLabelSize"), nameof(unicode)); Contract.EndContractBlock(); StringBuilder output = new StringBuilder(unicode.Length); @@ -605,7 +603,7 @@ namespace System.Globalization { // Find end of this segment iNextDot = unicode.IndexOfAny(M_Dots, iAfterLastDot); - Contract.Assert(iNextDot <= unicode.Length, "[IdnMapping.punycode_encode]IndexOfAny is broken"); + Debug.Assert(iNextDot <= unicode.Length, "[IdnMapping.punycode_encode]IndexOfAny is broken"); if (iNextDot < 0) iNextDot = unicode.Length; @@ -615,7 +613,7 @@ namespace System.Globalization // Only allowed to have empty sections as trailing . if (iNextDot != unicode.Length) throw new ArgumentException(Environment.GetResourceString( - "Argument_IdnBadLabelSize"), "unicode"); + "Argument_IdnBadLabelSize"), nameof(unicode)); // Last dot, stop break; } @@ -645,7 +643,7 @@ namespace System.Globalization { // Oops, last wasn't RTL, last should be RTL if first is RTL throw new ArgumentException(Environment.GetResourceString( - "Argument_IdnBadBidi"), "unicode"); + "Argument_IdnBadBidi"), nameof(unicode)); } } @@ -655,7 +653,7 @@ namespace System.Globalization for (basicCount = iAfterLastDot; basicCount < iNextDot; basicCount++) { // Can't be lonely surrogate because it would've thrown in normalization - Contract.Assert(Char.IsLowSurrogate(unicode, basicCount) == false, + Debug.Assert(Char.IsLowSurrogate(unicode, basicCount) == false, "[IdnMapping.punycode_encode]Unexpected low surrogate"); // Double check our bidi rules @@ -666,7 +664,7 @@ namespace System.Globalization { // Oops, throw error throw new ArgumentException(Environment.GetResourceString( - "Argument_IdnBadBidi"), "unicode"); + "Argument_IdnBadBidi"), nameof(unicode)); } // If we're not RTL we can't have RTL chars @@ -675,7 +673,7 @@ namespace System.Globalization { // Oops, throw error throw new ArgumentException(Environment.GetResourceString( - "Argument_IdnBadBidi"), "unicode"); + "Argument_IdnBadBidi"), nameof(unicode)); } // If its basic then add it @@ -704,7 +702,7 @@ namespace System.Globalization unicode.Substring(iAfterLastDot, M_strAcePrefix.Length).Equals( M_strAcePrefix, StringComparison.OrdinalIgnoreCase)) throw new ArgumentException(Environment.GetResourceString( - "Argument_IdnBadPunycode"), "unicode"); + "Argument_IdnBadPunycode"), nameof(unicode)); // Need to do ACE encoding int numSurrogatePairs = 0; // number of surrogate pairs so far @@ -739,7 +737,7 @@ namespace System.Globalization /* Increase delta enough to advance the decoder's */ /* <n,i> state to <m,0>, but guard against overflow: */ delta += (int)((m - n) * ((numProcessed - numSurrogatePairs) + 1)); - Contract.Assert(delta > 0, "[IdnMapping.cs]1 punycode_encode - delta overflowed int"); + Debug.Assert(delta > 0, "[IdnMapping.cs]1 punycode_encode - delta overflowed int"); n = m; for (j = iAfterLastDot; j < iNextDot; j+= IsSupplementary(test) ? 2 : 1) @@ -753,7 +751,7 @@ namespace System.Globalization if (test < n) { delta++; - Contract.Assert(delta > 0, "[IdnMapping.cs]2 punycode_encode - delta overflowed int"); + Debug.Assert(delta > 0, "[IdnMapping.cs]2 punycode_encode - delta overflowed int"); } if (test == n) @@ -765,9 +763,11 @@ namespace System.Globalization int t = k <= bias ? tmin : k >= bias + tmax ? tmax : k - bias; if (q < t) break; - Contract.Assert(punycodeBase != t, "[IdnMapping.punycode_encode]Expected punycodeBase (36) to be != t"); - output.Append(encode_digit(t + (q - t) % (punycodeBase - t))); - q = (q - t) / (punycodeBase - t); + Debug.Assert(punycodeBase != t, "[IdnMapping.punycode_encode]Expected punycodeBase (36) to be != t"); + + int mod; + q = Math.DivRem(q - t, punycodeBase - t, out mod); + output.Append(encode_digit(t + mod)); } output.Append(encode_digit(q)); @@ -784,14 +784,14 @@ namespace System.Globalization } ++delta; ++n; - Contract.Assert(delta > 0, "[IdnMapping.cs]3 punycode_encode - delta overflowed int"); + Debug.Assert(delta > 0, "[IdnMapping.cs]3 punycode_encode - delta overflowed int"); } } // Make sure its not too big if (output.Length - iOutputAfterLastDot > M_labelLimit) throw new ArgumentException(Environment.GetResourceString( - "Argument_IdnBadLabelSize"), "unicode"); + "Argument_IdnBadLabelSize"), nameof(unicode)); // Done with this segment, add dot if necessary if (iNextDot != unicode.Length) @@ -806,7 +806,7 @@ namespace System.Globalization throw new ArgumentException(Environment.GetResourceString( "Argument_IdnBadNameSize", M_defaultNameLimit - (IsDot(unicode[unicode.Length-1]) ? 0 : 1)), - "unicode"); + nameof(unicode)); // Return our output string return output.ToString(); @@ -840,14 +840,14 @@ namespace System.Globalization // 0 length strings aren't allowed if (ascii.Length == 0) throw new ArgumentException(Environment.GetResourceString( - "Argument_IdnBadLabelSize"), "ascii"); + "Argument_IdnBadLabelSize"), nameof(ascii)); Contract.EndContractBlock(); // Throw if we're too long if (ascii.Length > M_defaultNameLimit - (IsDot(ascii[ascii.Length-1]) ? 0 : 1)) throw new ArgumentException(Environment.GetResourceString( "Argument_IdnBadNameSize", - M_defaultNameLimit - (IsDot(ascii[ascii.Length-1]) ? 0 : 1)), "ascii"); + M_defaultNameLimit - (IsDot(ascii[ascii.Length-1]) ? 0 : 1)), nameof(ascii)); // output stringbuilder StringBuilder output = new StringBuilder(ascii.Length); @@ -870,7 +870,7 @@ namespace System.Globalization // Only allowed to have empty sections as trailing . if (iNextDot != ascii.Length) throw new ArgumentException(Environment.GetResourceString( - "Argument_IdnBadLabelSize"), "ascii"); + "Argument_IdnBadLabelSize"), nameof(ascii)); // Last dot, stop break; @@ -879,7 +879,7 @@ namespace System.Globalization // In either case it can't be bigger than segment size if (iNextDot - iAfterLastDot > M_labelLimit) throw new ArgumentException(Environment.GetResourceString( - "Argument_IdnBadLabelSize"), "ascii"); + "Argument_IdnBadLabelSize"), nameof(ascii)); // See if this section's ASCII or ACE if (ascii.Length < M_strAcePrefix.Length + iAfterLastDot || @@ -893,7 +893,7 @@ namespace System.Globalization // // Only ASCII is allowed // if (ascii[i] >= 0x80) // throw new ArgumentException(Environment.GetResourceString( - // "Argument_IdnBadPunycode"), "ascii"); + // "Argument_IdnBadPunycode"), nameof(ascii)); // } // Its ASCII, copy it @@ -913,7 +913,7 @@ namespace System.Globalization // Trailing - not allowed if (iTemp == iNextDot - 1) throw new ArgumentException(Environment.GetResourceString( - "Argument_IdnBadPunycode"), "ascii"); + "Argument_IdnBadPunycode"), nameof(ascii)); int numBasicCodePoints; if (iTemp <= iAfterLastDot) @@ -931,7 +931,7 @@ namespace System.Globalization // Make sure we don't allow unicode in the ascii part if (ascii[copyAscii] > 0x7f) throw new ArgumentException(Environment.GetResourceString( - "Argument_IdnBadPunycode"), "ascii"); + "Argument_IdnBadPunycode"), nameof(ascii)); // When appending make sure they get lower cased output.Append((char)(ascii[copyAscii] >= 'A' && ascii[copyAscii] <='Z' ? @@ -970,24 +970,24 @@ namespace System.Globalization // Check to make sure we aren't overrunning our ascii string if (asciiIndex >= iNextDot) throw new ArgumentException(Environment.GetResourceString( - "Argument_IdnBadPunycode"), "ascii"); + "Argument_IdnBadPunycode"), nameof(ascii)); // decode the digit from the next char int digit = decode_digit(ascii[asciiIndex++]); - Contract.Assert(w > 0, "[IdnMapping.punycode_decode]Expected w > 0"); + Debug.Assert(w > 0, "[IdnMapping.punycode_decode]Expected w > 0"); if (digit > (maxint - i) / w) throw new ArgumentException(Environment.GetResourceString( - "Argument_IdnBadPunycode"), "ascii"); + "Argument_IdnBadPunycode"), nameof(ascii)); i += (int)(digit * w); int t = k <= bias ? tmin : k >= bias + tmax ? tmax : k - bias; if (digit < t) break; - Contract.Assert(punycodeBase != t, "[IdnMapping.punycode_decode]Expected t != punycodeBase (36)"); + Debug.Assert(punycodeBase != t, "[IdnMapping.punycode_decode]Expected t != punycodeBase (36)"); if (w > maxint / (punycodeBase - t)) throw new ArgumentException(Environment.GetResourceString( - "Argument_IdnBadPunycode"), "ascii"); + "Argument_IdnBadPunycode"), nameof(ascii)); w *= (punycodeBase - t); } @@ -996,11 +996,11 @@ namespace System.Globalization /* i was supposed to wrap around from output.Length to 0, */ /* incrementing n each time, so we'll fix that now: */ - Contract.Assert((output.Length - iOutputAfterLastDot - numSurrogatePairs) + 1 > 0, + Debug.Assert((output.Length - iOutputAfterLastDot - numSurrogatePairs) + 1 > 0, "[IdnMapping.punycode_decode]Expected to have added > 0 characters this segment"); if (i / ((output.Length - iOutputAfterLastDot - numSurrogatePairs) + 1) > maxint - n) throw new ArgumentException(Environment.GetResourceString( - "Argument_IdnBadPunycode"), "ascii"); + "Argument_IdnBadPunycode"), nameof(ascii)); n += (int)(i / (output.Length - iOutputAfterLastDot - numSurrogatePairs + 1)); i %= (output.Length - iOutputAfterLastDot - numSurrogatePairs + 1); @@ -1016,7 +1016,7 @@ namespace System.Globalization // Make sure n is legal if ((n < 0 || n > 0x10ffff) || (n >= 0xD800 && n <= 0xDFFF)) throw new ArgumentException(Environment.GetResourceString( - "Argument_IdnBadPunycode"), "ascii"); + "Argument_IdnBadPunycode"), nameof(ascii)); // insert n at position i of the output: Really tricky if we have surrogates int iUseInsertLocation; @@ -1034,7 +1034,7 @@ namespace System.Globalization // If its a surrogate, we have to go one more if (iUseInsertLocation >= output.Length) throw new ArgumentException(Environment.GetResourceString( - "Argument_IdnBadPunycode"), "ascii"); + "Argument_IdnBadPunycode"), nameof(ascii)); if (Char.IsSurrogate(output[iUseInsertLocation])) iUseInsertLocation++; } @@ -1079,7 +1079,7 @@ namespace System.Globalization (!bRightToLeft && (eBidi == BidiCategory.RightToLeft || eBidi == BidiCategory.RightToLeftArabic))) throw new ArgumentException(Environment.GetResourceString( - "Argument_IdnBadBidi"), "ascii"); + "Argument_IdnBadBidi"), nameof(ascii)); // Make it lower case if we must (so we can test IsNormalized later) // if (output[iTest] >= 'A' && output[iTest] <= 'Z') @@ -1091,14 +1091,14 @@ namespace System.Globalization { // Oops, last wasn't RTL, last should be RTL if first is RTL throw new ArgumentException(Environment.GetResourceString( - "Argument_IdnBadBidi"), "ascii"); + "Argument_IdnBadBidi"), nameof(ascii)); } } // See if this label was too long if (iNextDot - iAfterLastDot > M_labelLimit) throw new ArgumentException(Environment.GetResourceString( - "Argument_IdnBadLabelSize"), "ascii"); + "Argument_IdnBadLabelSize"), nameof(ascii)); // Done with this segment, add dot if necessary if (iNextDot != ascii.Length) @@ -1112,7 +1112,7 @@ namespace System.Globalization if (output.Length > M_defaultNameLimit - (IsDot(output[output.Length-1]) ? 0 : 1)) throw new ArgumentException(Environment.GetResourceString( "Argument_IdnBadNameSize", - M_defaultNameLimit -(IsDot(output[output.Length-1]) ? 0 : 1)), "ascii"); + M_defaultNameLimit -(IsDot(output[output.Length-1]) ? 0 : 1)), nameof(ascii)); // Return our output string return output.ToString(); @@ -1157,9 +1157,8 @@ namespace System.Globalization private const int ERROR_INVALID_NAME = 123; - [System.Security.SecurityCritical] [SuppressUnmanagedCodeSecurityAttribute()] - [DllImport("kernel32.dll", CharSet=CharSet.Unicode, SetLastError=true)] + [DllImport("normaliz.dll", CharSet=CharSet.Unicode, SetLastError=true)] private static extern int IdnToAscii( uint dwFlags, [InAttribute()] @@ -1171,9 +1170,8 @@ namespace System.Globalization char [] lpASCIICharStr, int cchASCIIChar); - [System.Security.SecurityCritical] [SuppressUnmanagedCodeSecurityAttribute()] - [DllImport("kernel32.dll", CharSet=CharSet.Unicode, SetLastError=true)] + [DllImport("normaliz.dll", CharSet=CharSet.Unicode, SetLastError=true)] private static extern int IdnToUnicode( uint dwFlags, [InAttribute()] diff --git a/src/mscorlib/src/System/Globalization/JapaneseCalendar.cs b/src/mscorlib/src/System/Globalization/JapaneseCalendar.cs index 2984d08ab3..6b168ce916 100644 --- a/src/mscorlib/src/System/Globalization/JapaneseCalendar.cs +++ b/src/mscorlib/src/System/Globalization/JapaneseCalendar.cs @@ -159,7 +159,6 @@ namespace System.Globalization { // . is a delimiter, but the value of . doesn't matter. // '_' marks the space between the japanese era name, japanese abbreviated era name // english name, and abbreviated english names. - [System.Security.SecuritySafeCritical] // auto-generated private static EraInfo[] GetErasFromRegistry() { // Look in the registry key and see if we can find any ranges @@ -491,14 +490,14 @@ namespace System.Globalization { public override int ToFourDigitYear(int year) { if (year <= 0) { - throw new ArgumentOutOfRangeException("year", + throw new ArgumentOutOfRangeException(nameof(year), Environment.GetResourceString("ArgumentOutOfRange_NeedPosNum")); } Contract.EndContractBlock(); if (year > helper.MaxYear) { throw new ArgumentOutOfRangeException( - "year", + nameof(year), String.Format( CultureInfo.CurrentCulture, Environment.GetResourceString("ArgumentOutOfRange_Range"), diff --git a/src/mscorlib/src/System/Globalization/JulianCalendar.cs b/src/mscorlib/src/System/Globalization/JulianCalendar.cs index 9c8db3415c..db286e0363 100644 --- a/src/mscorlib/src/System/Globalization/JulianCalendar.cs +++ b/src/mscorlib/src/System/Globalization/JulianCalendar.cs @@ -112,7 +112,7 @@ namespace System.Globalization { static internal void CheckEraRange(int era) { if (era != CurrentEra && era != JulianEra) { - throw new ArgumentOutOfRangeException("era", Environment.GetResourceString("ArgumentOutOfRange_InvalidEraValue")); + throw new ArgumentOutOfRangeException(nameof(era), Environment.GetResourceString("ArgumentOutOfRange_InvalidEraValue")); } } @@ -120,7 +120,7 @@ namespace System.Globalization { CheckEraRange(era); if (year <= 0 || year > MaxYear) { throw new ArgumentOutOfRangeException( - "year", + nameof(year), String.Format( CultureInfo.CurrentCulture, Environment.GetResourceString("ArgumentOutOfRange_Range"), @@ -131,7 +131,7 @@ namespace System.Globalization { static internal void CheckMonthRange(int month) { if (month < 1 || month > 12) { - throw new ArgumentOutOfRangeException("month", Environment.GetResourceString("ArgumentOutOfRange_Month")); + throw new ArgumentOutOfRangeException(nameof(month), Environment.GetResourceString("ArgumentOutOfRange_Month")); } } @@ -159,7 +159,7 @@ namespace System.Globalization { int monthDays = days[month] - days[month - 1]; if (day < 1 || day > monthDays) { throw new ArgumentOutOfRangeException( - "day", + nameof(day), String.Format( CultureInfo.CurrentCulture, Environment.GetResourceString("ArgumentOutOfRange_Range"), @@ -204,7 +204,7 @@ namespace System.Globalization { int[] days = leapYear? DaysToMonth366: DaysToMonth365; // All months have less than 32 days, so n >> 5 is a good conservative // estimate for the month - int m = n >> 5 + 1; + int m = (n >> 5) + 1; // m = 1-based month number while (n >= days[m]) m++; // If month was requested, return it @@ -230,7 +230,7 @@ namespace System.Globalization { { if (months < -120000 || months > 120000) { throw new ArgumentOutOfRangeException( - "months", + nameof(months), String.Format( CultureInfo.CurrentCulture, Environment.GetResourceString("ArgumentOutOfRange_Range"), @@ -377,7 +377,7 @@ namespace System.Globalization { CheckDayRange(year, month, day); if (millisecond < 0 || millisecond >= MillisPerSecond) { throw new ArgumentOutOfRangeException( - "millisecond", + nameof(millisecond), String.Format( CultureInfo.CurrentCulture, Environment.GetResourceString("ArgumentOutOfRange_Range"), @@ -420,14 +420,14 @@ namespace System.Globalization { public override int ToFourDigitYear(int year) { if (year < 0) { - throw new ArgumentOutOfRangeException("year", + throw new ArgumentOutOfRangeException(nameof(year), Environment.GetResourceString("ArgumentOutOfRange_NeedNonNegNum")); } Contract.EndContractBlock(); if (year > MaxYear) { throw new ArgumentOutOfRangeException( - "year", + nameof(year), String.Format( CultureInfo.CurrentCulture, Environment.GetResourceString("ArgumentOutOfRange_Bounds_Lower_Upper"), diff --git a/src/mscorlib/src/System/Globalization/KoreanCalendar.cs b/src/mscorlib/src/System/Globalization/KoreanCalendar.cs index 9343884445..dde82b6e6b 100644 --- a/src/mscorlib/src/System/Globalization/KoreanCalendar.cs +++ b/src/mscorlib/src/System/Globalization/KoreanCalendar.cs @@ -254,7 +254,7 @@ namespace System.Globalization { public override int ToFourDigitYear(int year) { if (year < 0) { - throw new ArgumentOutOfRangeException("year", + throw new ArgumentOutOfRangeException(nameof(year), Environment.GetResourceString("ArgumentOutOfRange_NeedNonNegNum")); } Contract.EndContractBlock(); diff --git a/src/mscorlib/src/System/Globalization/KoreanLunisolarCalendar.cs b/src/mscorlib/src/System/Globalization/KoreanLunisolarCalendar.cs index eb0a810864..9e36b435e7 100644 --- a/src/mscorlib/src/System/Globalization/KoreanLunisolarCalendar.cs +++ b/src/mscorlib/src/System/Globalization/KoreanLunisolarCalendar.cs @@ -1267,12 +1267,12 @@ namespace System.Globalization { internal override int GetGregorianYear(int year, int era) { if (era != CurrentEra && era != GregorianEra) - throw new ArgumentOutOfRangeException("era", Environment.GetResourceString("ArgumentOutOfRange_InvalidEraValue")); + throw new ArgumentOutOfRangeException(nameof(era), Environment.GetResourceString("ArgumentOutOfRange_InvalidEraValue")); if (year < MIN_LUNISOLAR_YEAR || year > MAX_LUNISOLAR_YEAR) { throw new ArgumentOutOfRangeException( - "year", + nameof(year), String.Format( CultureInfo.CurrentCulture, Environment.GetResourceString("ArgumentOutOfRange_Range"), MIN_LUNISOLAR_YEAR, MAX_LUNISOLAR_YEAR)); diff --git a/src/mscorlib/src/System/Globalization/NumberFormatInfo.cs b/src/mscorlib/src/System/Globalization/NumberFormatInfo.cs index fae91c2a1d..a5dce46aa4 100644 --- a/src/mscorlib/src/System/Globalization/NumberFormatInfo.cs +++ b/src/mscorlib/src/System/Globalization/NumberFormatInfo.cs @@ -120,28 +120,8 @@ namespace System.Globalization { [OnSerializing] private void OnSerializing(StreamingContext ctx) { -#if !FEATURE_CORECLR - // Update these legacy flags, so that 1.1/2.0 versions of the framework - // can still throw while parsing; even when using a de-serialized - // NumberFormatInfo from a 4.0+ version of the framework - if (numberDecimalSeparator != numberGroupSeparator) { - validForParseAsNumber = true; - } else { - validForParseAsNumber = false; - } - - if ((numberDecimalSeparator != numberGroupSeparator) && - (numberDecimalSeparator != currencyGroupSeparator) && - (currencyDecimalSeparator != numberGroupSeparator) && - (currencyDecimalSeparator != currencyGroupSeparator)) { - validForParseAsCurrency = true; - } else { - validForParseAsCurrency = false; - } -#endif // !FEATURE_CORECLR } - [OnDeserializing] private void OnDeserializing(StreamingContext ctx) { @@ -153,7 +133,6 @@ namespace System.Globalization { } #endregion Serialization - static private void VerifyDecimalSeparator(String decSep, String propertyName) { if (decSep==null) { throw new ArgumentNullException(propertyName, @@ -231,7 +210,6 @@ namespace System.Globalization { // We aren't persisting dataItem any more (since its useless & we weren't using it), // Ditto with m_useUserOverride. Don't use them, we use a local copy of everything. - [System.Security.SecuritySafeCritical] // auto-generated internal NumberFormatInfo(CultureData cultureData) { if (cultureData != null) @@ -316,7 +294,7 @@ namespace System.Globalization { set { if (value < 0 || value > 99) { throw new ArgumentOutOfRangeException( - "CurrencyDecimalDigits", + nameof(CurrencyDecimalDigits), String.Format( CultureInfo.CurrentCulture, Environment.GetResourceString("ArgumentOutOfRange_Range"), @@ -376,7 +354,7 @@ namespace System.Globalization { } set { if (value == null) { - throw new ArgumentNullException("CurrencyGroupSizes", + throw new ArgumentNullException(nameof(CurrencyGroupSizes), Environment.GetResourceString("ArgumentNull_Obj")); } Contract.EndContractBlock(); @@ -397,7 +375,7 @@ namespace System.Globalization { } set { if (value == null) { - throw new ArgumentNullException("NumberGroupSizes", + throw new ArgumentNullException(nameof(NumberGroupSizes), Environment.GetResourceString("ArgumentNull_Obj")); } Contract.EndContractBlock(); @@ -416,7 +394,7 @@ namespace System.Globalization { } set { if (value == null) { - throw new ArgumentNullException("PercentGroupSizes", + throw new ArgumentNullException(nameof(PercentGroupSizes), Environment.GetResourceString("ArgumentNull_Obj")); } Contract.EndContractBlock(); @@ -443,7 +421,7 @@ namespace System.Globalization { get { return currencySymbol; } set { if (value == null) { - throw new ArgumentNullException("CurrencySymbol", + throw new ArgumentNullException(nameof(CurrencySymbol), Environment.GetResourceString("ArgumentNull_String")); } Contract.EndContractBlock(); @@ -475,7 +453,7 @@ namespace System.Globalization { } set { if (value == null) { - throw new ArgumentNullException("NaNSymbol", + throw new ArgumentNullException(nameof(NaNSymbol), Environment.GetResourceString("ArgumentNull_String")); } Contract.EndContractBlock(); @@ -491,7 +469,7 @@ namespace System.Globalization { set { if (value < 0 || value > 15) { throw new ArgumentOutOfRangeException( - "CurrencyNegativePattern", + nameof(CurrencyNegativePattern), String.Format( CultureInfo.CurrentCulture, Environment.GetResourceString("ArgumentOutOfRange_Range"), @@ -513,7 +491,7 @@ namespace System.Globalization { // if (value < 0 || value > 4) { throw new ArgumentOutOfRangeException( - "NumberNegativePattern", + nameof(NumberNegativePattern), String.Format( CultureInfo.CurrentCulture, Environment.GetResourceString("ArgumentOutOfRange_Range"), @@ -535,7 +513,7 @@ namespace System.Globalization { // if (value < 0 || value > 3) { throw new ArgumentOutOfRangeException( - "PercentPositivePattern", + nameof(PercentPositivePattern), String.Format( CultureInfo.CurrentCulture, Environment.GetResourceString("ArgumentOutOfRange_Range"), @@ -557,7 +535,7 @@ namespace System.Globalization { // if (value < 0 || value > 11) { throw new ArgumentOutOfRangeException( - "PercentNegativePattern", + nameof(PercentNegativePattern), String.Format( CultureInfo.CurrentCulture, Environment.GetResourceString("ArgumentOutOfRange_Range"), @@ -577,7 +555,7 @@ namespace System.Globalization { } set { if (value == null) { - throw new ArgumentNullException("NegativeInfinitySymbol", + throw new ArgumentNullException(nameof(NegativeInfinitySymbol), Environment.GetResourceString("ArgumentNull_String")); } Contract.EndContractBlock(); @@ -591,7 +569,7 @@ namespace System.Globalization { get { return negativeSign; } set { if (value == null) { - throw new ArgumentNullException("NegativeSign", + throw new ArgumentNullException(nameof(NegativeSign), Environment.GetResourceString("ArgumentNull_String")); } Contract.EndContractBlock(); @@ -606,7 +584,7 @@ namespace System.Globalization { set { if (value < 0 || value > 99) { throw new ArgumentOutOfRangeException( - "NumberDecimalDigits", + nameof(NumberDecimalDigits), String.Format( CultureInfo.CurrentCulture, Environment.GetResourceString("ArgumentOutOfRange_Range"), @@ -645,7 +623,7 @@ namespace System.Globalization { set { if (value < 0 || value > 3) { throw new ArgumentOutOfRangeException( - "CurrencyPositivePattern", + nameof(CurrencyPositivePattern), String.Format( CultureInfo.CurrentCulture, Environment.GetResourceString("ArgumentOutOfRange_Range"), @@ -665,7 +643,7 @@ namespace System.Globalization { } set { if (value == null) { - throw new ArgumentNullException("PositiveInfinitySymbol", + throw new ArgumentNullException(nameof(PositiveInfinitySymbol), Environment.GetResourceString("ArgumentNull_String")); } Contract.EndContractBlock(); @@ -679,7 +657,7 @@ namespace System.Globalization { get { return positiveSign; } set { if (value == null) { - throw new ArgumentNullException("PositiveSign", + throw new ArgumentNullException(nameof(PositiveSign), Environment.GetResourceString("ArgumentNull_String")); } Contract.EndContractBlock(); @@ -694,7 +672,7 @@ namespace System.Globalization { set { if (value < 0 || value > 99) { throw new ArgumentOutOfRangeException( - "PercentDecimalDigits", + nameof(PercentDecimalDigits), String.Format( CultureInfo.CurrentCulture, Environment.GetResourceString("ArgumentOutOfRange_Range"), @@ -734,7 +712,7 @@ namespace System.Globalization { } set { if (value == null) { - throw new ArgumentNullException("PercentSymbol", + throw new ArgumentNullException(nameof(PercentSymbol), Environment.GetResourceString("ArgumentNull_String")); } Contract.EndContractBlock(); @@ -748,7 +726,7 @@ namespace System.Globalization { get { return perMilleSymbol; } set { if (value == null) { - throw new ArgumentNullException("PerMilleSymbol", + throw new ArgumentNullException(nameof(PerMilleSymbol), Environment.GetResourceString("ArgumentNull_String")); } Contract.EndContractBlock(); @@ -788,7 +766,7 @@ namespace System.Globalization { public static NumberFormatInfo ReadOnly(NumberFormatInfo nfi) { if (nfi == null) { - throw new ArgumentNullException("nfi"); + throw new ArgumentNullException(nameof(nfi)); } Contract.EndContractBlock(); if (nfi.IsReadOnly) { @@ -809,7 +787,7 @@ namespace System.Globalization { internal static void ValidateParseStyleInteger(NumberStyles style) { // Check for undefined flags if ((style & InvalidNumberStyles) != 0) { - throw new ArgumentException(Environment.GetResourceString("Argument_InvalidNumberStyles"), "style"); + throw new ArgumentException(Environment.GetResourceString("Argument_InvalidNumberStyles"), nameof(style)); } Contract.EndContractBlock(); if ((style & NumberStyles.AllowHexSpecifier) != 0) { // Check for hex number @@ -822,7 +800,7 @@ namespace System.Globalization { internal static void ValidateParseStyleFloatingPoint(NumberStyles style) { // Check for undefined flags if ((style & InvalidNumberStyles) != 0) { - throw new ArgumentException(Environment.GetResourceString("Argument_InvalidNumberStyles"), "style"); + throw new ArgumentException(Environment.GetResourceString("Argument_InvalidNumberStyles"), nameof(style)); } Contract.EndContractBlock(); if ((style & NumberStyles.AllowHexSpecifier) != 0) { // Check for hex number diff --git a/src/mscorlib/src/System/Globalization/PersianCalendar.cs b/src/mscorlib/src/System/Globalization/PersianCalendar.cs index 2f1ffacee7..e61a007a02 100644 --- a/src/mscorlib/src/System/Globalization/PersianCalendar.cs +++ b/src/mscorlib/src/System/Globalization/PersianCalendar.cs @@ -4,6 +4,7 @@ namespace System.Globalization { using System; + using System.Diagnostics; using System.Diagnostics.Contracts; //////////////////////////////////////////////////////////////////////////// @@ -147,7 +148,7 @@ namespace System.Globalization { static internal void CheckEraRange(int era) { if (era != CurrentEra && era != PersianEra) { - throw new ArgumentOutOfRangeException("era", Environment.GetResourceString("ArgumentOutOfRange_InvalidEraValue")); + throw new ArgumentOutOfRangeException(nameof(era), Environment.GetResourceString("ArgumentOutOfRange_InvalidEraValue")); } } @@ -155,7 +156,7 @@ namespace System.Globalization { CheckEraRange(era); if (year < 1 || year > MaxCalendarYear) { throw new ArgumentOutOfRangeException( - "year", + nameof(year), String.Format( CultureInfo.CurrentCulture, Environment.GetResourceString("ArgumentOutOfRange_Range"), @@ -169,7 +170,7 @@ namespace System.Globalization { if (year == MaxCalendarYear) { if (month > MaxCalendarMonth) { throw new ArgumentOutOfRangeException( - "month", + nameof(month), String.Format( CultureInfo.CurrentCulture, Environment.GetResourceString("ArgumentOutOfRange_Range"), @@ -179,13 +180,13 @@ namespace System.Globalization { } if (month < 1 || month > 12) { - throw new ArgumentOutOfRangeException("month", Environment.GetResourceString("ArgumentOutOfRange_Month")); + throw new ArgumentOutOfRangeException(nameof(month), Environment.GetResourceString("ArgumentOutOfRange_Month")); } } static int MonthFromOrdinalDay(int ordinalDay) { - Contract.Assert(ordinalDay <= 366); + Debug.Assert(ordinalDay <= 366); int index = 0; while (ordinalDay > DaysToMonth[index]) index++; @@ -195,7 +196,7 @@ namespace System.Globalization { static int DaysInPreviousMonths(int month) { - Contract.Assert(1 <= month && month <= 12); + Debug.Assert(1 <= month && month <= 12); --month; // months are one based but for calculations use 0 based return DaysToMonth[month]; } @@ -225,7 +226,7 @@ namespace System.Globalization { long yearStart = CalendricalCalculationsHelper.PersianNewYearOnOrBefore(NumDays); int y = (int)(Math.Floor(((yearStart - PersianEpoch) / CalendricalCalculationsHelper.MeanTropicalYearInDays) + 0.5)) + 1; - Contract.Assert(y >= 1); + Debug.Assert(y >= 1); if (part == DatePartYear) { @@ -244,16 +245,16 @@ namespace System.Globalization { } int m = MonthFromOrdinalDay(ordinalDay); - Contract.Assert(ordinalDay >= 1); - Contract.Assert(m >= 1 && m <= 12); + Debug.Assert(ordinalDay >= 1); + Debug.Assert(m >= 1 && m <= 12); if (part == DatePartMonth) { return m; } int d = ordinalDay - DaysInPreviousMonths(m); - Contract.Assert(1 <= d); - Contract.Assert(d <= 31); + Debug.Assert(1 <= d); + Debug.Assert(d <= 31); // // Calculate the Persian Day. @@ -290,7 +291,7 @@ namespace System.Globalization { public override DateTime AddMonths(DateTime time, int months) { if (months < -120000 || months > 120000) { throw new ArgumentOutOfRangeException( - "months", + nameof(months), String.Format( CultureInfo.CurrentCulture, Environment.GetResourceString("ArgumentOutOfRange_Range"), @@ -377,7 +378,7 @@ namespace System.Globalization { int daysInMonth = DaysToMonth[month] - DaysToMonth[month - 1]; if ((month == MonthsPerYear) && !IsLeapYear(year)) { - Contract.Assert(daysInMonth == 30); + Debug.Assert(daysInMonth == 30); --daysInMonth; } return daysInMonth; @@ -450,7 +451,7 @@ namespace System.Globalization { int daysInMonth = GetDaysInMonth(year, month, era); if (day < 1 || day > daysInMonth) { throw new ArgumentOutOfRangeException( - "day", + nameof(day), String.Format( CultureInfo.CurrentCulture, Environment.GetResourceString("ArgumentOutOfRange_Day"), @@ -506,7 +507,7 @@ namespace System.Globalization { if (day < 1 || day > daysInMonth) { BCLDebug.Log("year = " + year + ", month = " + month + ", day = " + day); throw new ArgumentOutOfRangeException( - "day", + nameof(day), String.Format( CultureInfo.CurrentCulture, Environment.GetResourceString("ArgumentOutOfRange_Day"), @@ -538,7 +539,7 @@ namespace System.Globalization { if (value < 99 || value > MaxCalendarYear) { throw new ArgumentOutOfRangeException( - "value", + nameof(value), String.Format( CultureInfo.CurrentCulture, Environment.GetResourceString("ArgumentOutOfRange_Range"), @@ -553,7 +554,7 @@ namespace System.Globalization { public override int ToFourDigitYear(int year) { if (year < 0) { - throw new ArgumentOutOfRangeException("year", + throw new ArgumentOutOfRangeException(nameof(year), Environment.GetResourceString("ArgumentOutOfRange_NeedNonNegNum")); } Contract.EndContractBlock(); @@ -564,7 +565,7 @@ namespace System.Globalization { if (year > MaxCalendarYear) { throw new ArgumentOutOfRangeException( - "year", + nameof(year), String.Format( CultureInfo.CurrentCulture, Environment.GetResourceString("ArgumentOutOfRange_Range"), diff --git a/src/mscorlib/src/System/Globalization/RegionInfo.cs b/src/mscorlib/src/System/Globalization/RegionInfo.cs index f06d63f1d2..4bed87570f 100644 --- a/src/mscorlib/src/System/Globalization/RegionInfo.cs +++ b/src/mscorlib/src/System/Globalization/RegionInfo.cs @@ -19,6 +19,7 @@ namespace System.Globalization { using System; using System.Runtime.Serialization; + using System.Diagnostics; using System.Diagnostics.Contracts; [Serializable] @@ -59,14 +60,13 @@ namespace System.Globalization { // In Silverlight we enforce that RegionInfos must be created with a full culture name // //////////////////////////////////////////////////////////////////////// - [System.Security.SecuritySafeCritical] // auto-generated public RegionInfo(String name) { if (name==null) - throw new ArgumentNullException("name"); + throw new ArgumentNullException(nameof(name)); if (name.Length == 0) //The InvariantCulture has no matching region { - throw new ArgumentException(Environment.GetResourceString("Argument_NoRegionInvariantCulture"), "name"); + throw new ArgumentException(Environment.GetResourceString("Argument_NoRegionInvariantCulture"), nameof(name)); } Contract.EndContractBlock(); @@ -83,19 +83,18 @@ namespace System.Globalization { throw new ArgumentException( String.Format( CultureInfo.CurrentCulture, - Environment.GetResourceString("Argument_InvalidCultureName"), name), "name"); + Environment.GetResourceString("Argument_InvalidCultureName"), name), nameof(name)); // Not supposed to be neutral if (this.m_cultureData.IsNeutralCulture) - throw new ArgumentException(Environment.GetResourceString("Argument_InvalidNeutralRegionName", name), "name"); + throw new ArgumentException(Environment.GetResourceString("Argument_InvalidNeutralRegionName", name), nameof(name)); SetName(name); } #if FEATURE_USE_LCID // We'd rather people use the named version since this doesn't allow custom locales - [System.Security.SecuritySafeCritical] // auto-generated public RegionInfo(int culture) { if (culture == CultureInfo.LOCALE_INVARIANT) //The InvariantCulture has no matching region @@ -106,13 +105,13 @@ namespace System.Globalization { if (culture == CultureInfo.LOCALE_NEUTRAL) { // Not supposed to be neutral - throw new ArgumentException(Environment.GetResourceString("Argument_CultureIsNeutral", culture), "culture"); + throw new ArgumentException(Environment.GetResourceString("Argument_CultureIsNeutral", culture), nameof(culture)); } if (culture == CultureInfo.LOCALE_CUSTOM_DEFAULT) { // Not supposed to be neutral - throw new ArgumentException(Environment.GetResourceString("Argument_CustomCultureCannotBePassedByNumber", culture), "culture"); + throw new ArgumentException(Environment.GetResourceString("Argument_CustomCultureCannotBePassedByNumber", culture), nameof(culture)); } this.m_cultureData = CultureData.GetCultureData(culture,true); @@ -121,34 +120,23 @@ namespace System.Globalization { if (this.m_cultureData.IsNeutralCulture) { // Not supposed to be neutral - throw new ArgumentException(Environment.GetResourceString("Argument_CultureIsNeutral", culture), "culture"); + throw new ArgumentException(Environment.GetResourceString("Argument_CultureIsNeutral", culture), nameof(culture)); } m_cultureId = culture; } #endif - [System.Security.SecuritySafeCritical] // auto-generated internal RegionInfo(CultureData cultureData) { this.m_cultureData = cultureData; this.m_name = this.m_cultureData.SREGIONNAME; } - [System.Security.SecurityCritical] // auto-generated private void SetName(string name) { -#if FEATURE_CORECLR // Use the name of the region we found this.m_name = this.m_cultureData.SREGIONNAME; -#else - // when creating region by culture name, we keep the region name as the culture name so regions - // created by custom culture names can be differentiated from built in regions. - this.m_name = name.Equals(this.m_cultureData.SREGIONNAME, StringComparison.OrdinalIgnoreCase) ? - this.m_cultureData.SREGIONNAME : - this.m_cultureData.CultureName; -#endif // FEATURE_CORECLR } - #region Serialization // @@ -163,174 +151,17 @@ namespace System.Globalization { [OptionalField(VersionAdded = 2)] internal int m_dataItem = 0; -#if !FEATURE_CORECLR - static private readonly int[] IdFromEverettRegionInfoDataItem = - { - 0x3801, /* 0 */ // AE ar-AE Arabic (U.A.E.) - 0x041C, /* 1 */ // AL sq-AL Albanian (Albania) - 0x042B, /* 2 */ // AM hy-AM Armenian (Armenia) - 0x2C0A, /* 3 */ // AR es-AR Spanish (Argentina) - 0x0C07, /* 4 */ // AT de-AT German (Austria) - 0x0C09, /* 5 */ // AU en-AU English (Australia) - 0x042C, /* 6 */ // AZ az-AZ-Latn Azeri (Latin) (Azerbaijan) - // 0x082C, 6, // AZ az-AZ-Cyrl Azeri (Cyrillic) (Azerbaijan) - 0x080C, /* 7 */ // BE fr-BE French (Belgium) - // 0x0813, 7, // BE nl-BE Dutch (Belgium) - 0x0402, /* 8 */ // BG bg-BG Bulgarian (Bulgaria) - 0x3C01, /* 9 */ // BH ar-BH Arabic (Bahrain) - 0x083E, /* 10 */ // BN ms-BN Malay (Brunei Darussalam) - 0x400A, /* 11 */ // BO es-BO Spanish (Bolivia) - 0x0416, /* 12 */ // BR pt-BR Portuguese (Brazil) - 0x0423, /* 13 */ // BY be-BY Belarusian (Belarus) - 0x2809, /* 14 */ // BZ en-BZ English (Belize) - 0x0C0C, /* 15 */ // CA fr-CA French (Canada) - // 0x1009, 15, // CA en-CA English (Canada) - 0x2409, /* 16 */ // CB en-CB English (Caribbean) - 0x0807, /* 17 */ // CH de-CH German (Switzerland) - // 0x0810, 17, // CH it-CH Italian (Switzerland) - // 0x100C, 17, // CH fr-CH French (Switzerland) - 0x340A, /* 18 */ // CL es-CL Spanish (Chile) - 0x0804, /* 19 */ // CN zh-CN Chinese (People's Republic of China) - 0x240A, /* 20 */ // CO es-CO Spanish (Colombia) - 0x140A, /* 21 */ // CR es-CR Spanish (Costa Rica) - 0x0405, /* 22 */ // CZ cs-CZ Czech (Czech Republic) - 0x0407, /* 23 */ // DE de-DE German (Germany) - 0x0406, /* 24 */ // DK da-DK Danish (Denmark) - 0x1C0A, /* 25 */ // DO es-DO Spanish (Dominican Republic) - 0x1401, /* 26 */ // DZ ar-DZ Arabic (Algeria) - 0x300A, /* 27 */ // EC es-EC Spanish (Ecuador) - 0x0425, /* 28 */ // EE et-EE Estonian (Estonia) - 0x0C01, /* 29 */ // EG ar-EG Arabic (Egypt) - 0x0403, /* 30 */ // ES ca-ES Catalan (Catalan) - // 0x042D, 30, // ES eu-ES Basque (Basque) - // 0x0456, 30, // ES gl-ES Galician (Galician) - // 0x0C0A, 30, // ES es-ES Spanish (Spain) - 0x040B, /* 31 */ // FI fi-FI Finnish (Finland) - // 0x081D, 31, // FI sv-FI Swedish (Finland) - 0x0438, /* 32 */ // FO fo-FO Faroese (Faroe Islands) - 0x040C, /* 33 */ // FR fr-FR French (France) - 0x0809, /* 34 */ // GB en-GB English (United Kingdom) - 0x0437, /* 35 */ // GE ka-GE Georgian (Georgia) - 0x0408, /* 36 */ // GR el-GR Greek (Greece) - 0x100A, /* 37 */ // GT es-GT Spanish (Guatemala) - 0x0C04, /* 38 */ // HK zh-HK Chinese (Hong Kong S.A.R.) - 0x480A, /* 39 */ // HN es-HN Spanish (Honduras) - 0x041A, /* 40 */ // HR hr-HR Croatian (Croatia) - 0x040E, /* 41 */ // HU hu-HU Hungarian (Hungary) - 0x0421, /* 42 */ // ID id-ID Indonesian (Indonesia) - 0x1809, /* 43 */ // IE en-IE English (Ireland) - 0x040D, /* 44 */ // IL he-IL Hebrew (Israel) - 0x0439, /* 45 */ // IN hi-IN Hindi (India) - // 0x0446, 45, // IN pa-IN Punjabi (India) - // 0x0447, 45, // IN gu-IN Gujarati (India) - // 0x0449, 45, // IN ta-IN Tamil (India) - // 0x044A, 45, // IN te-IN Telugu (India) - // 0x044B, 45, // IN kn-IN Kannada (India) - // 0x044E, 45, // IN mr-IN Marathi (India) - // 0x044F, 45, // IN sa-IN Sanskrit (India) - // 0x0457, 45, // IN kok-IN Konkani (India) - 0x0801, /* 46 */ // IQ ar-IQ Arabic (Iraq) - 0x0429, /* 47 */ // IR fa-IR (Iran) - 0x040F, /* 48 */ // IS is-IS Icelandic (Iceland) - 0x0410, /* 49 */ // IT it-IT Italian (Italy) - 0x2009, /* 50 */ // JM en-JM English (Jamaica) - 0x2C01, /* 51 */ // JO ar-JO Arabic (Jordan) - 0x0411, /* 52 */ // JP ja-JP Japanese (Japan) - 0x0441, /* 53 */ // KE sw-KE Swahili (Kenya) - 0x0440, /* 54 */ // KG ky-KG Kyrgyz (Kyrgyzstan) - 0x0412, /* 55 */ // KR ko-KR Korean (Korea) - 0x3401, /* 56 */ // KW ar-KW Arabic (Kuwait) - 0x043F, /* 57 */ // KZ kk-KZ Kazakh (Kazakhstan) - 0x3001, /* 58 */ // LB ar-LB Arabic (Lebanon) - 0x1407, /* 59 */ // LI de-LI German (Liechtenstein) - 0x0427, /* 60 */ // LT lt-LT Lithuanian (Lithuania) - 0x1007, /* 61 */ // LU de-LU German (Luxembourg) - // 0x140C, 61, // LU fr-LU French (Luxembourg) - 0x0426, /* 62 */ // LV lv-LV Latvian (Latvia) - 0x1001, /* 63 */ // LY ar-LY Arabic (Libya) - 0x1801, /* 64 */ // MA ar-MA Arabic (Morocco) - 0x180C, /* 65 */ // MC fr-MC French (Principality of Monaco) - 0x042F, /* 66 */ // MK mk-MK Macedonian (Macedonia, FYRO) - 0x0450, /* 67 */ // MN mn-MN Mongolian (Mongolia) - 0x1404, /* 68 */ // MO zh-MO Chinese (Macau S.A.R.) - 0x0465, /* 69 */ // MV div-MV Divehi (Maldives) - 0x080A, /* 70 */ // MX es-MX Spanish (Mexico) - 0x043E, /* 71 */ // MY ms-MY Malay (Malaysia) - 0x4C0A, /* 72 */ // NI es-NI Spanish (Nicaragua) - 0x0413, /* 73 */ // NL nl-NL Dutch (Netherlands) - 0x0414, /* 74 */ // NO nb-NO Norwegian (Bokm?) (Norway) - // 0x0814, 74, // NO nn-NO Norwegian (Nynorsk) (Norway) - 0x1409, /* 75 */ // NZ en-NZ English (New Zealand) - 0x2001, /* 76 */ // OM ar-OM Arabic (Oman) - 0x180A, /* 77 */ // PA es-PA Spanish (Panama) - 0x280A, /* 78 */ // PE es-PE Spanish (Peru) - 0x3409, /* 79 */ // PH en-PH English (Republic of the Philippines) - 0x0420, /* 80 */ // PK ur-PK Urdu (Islamic Republic of Pakistan) - 0x0415, /* 81 */ // PL pl-PL Polish (Poland) - 0x500A, /* 82 */ // PR es-PR Spanish (Puerto Rico) - 0x0816, /* 83 */ // PT pt-PT Portuguese (Portugal) - 0x3C0A, /* 84 */ // PY es-PY Spanish (Paraguay) - 0x4001, /* 85 */ // QA ar-QA Arabic (Qatar) - 0x0418, /* 86 */ // RO ro-RO Romanian (Romania) - 0x0419, /* 87 */ // RU ru-RU Russian (Russia) - // 0x0444, 87, // RU tt-RU Tatar (Russia) - 0x0401, /* 88 */ // SA ar-SA Arabic (Saudi Arabia) - 0x041D, /* 89 */ // SE sv-SE Swedish (Sweden) - 0x1004, /* 90 */ // SG zh-SG Chinese (Singapore) - 0x0424, /* 91 */ // SI sl-SI Slovenian (Slovenia) - 0x041B, /* 92 */ // SK sk-SK Slovak (Slovakia) - 0x081A, /* 93 */ // SP sr-SP-Latn Serbian (Latin) (Serbia) - // 0x0C1A, 93, // SP sr-SP-Cyrl Serbian (Cyrillic) (Serbia) - 0x440A, /* 94 */ // SV es-SV Spanish (El Salvador) - 0x045A, /* 95 */ // SY syr-SY Syriac (Syria) - // 0x2801, 95, // SY ar-SY Arabic (Syria) - 0x041E, /* 96 */ // TH th-TH Thai (Thailand) - 0x1C01, /* 97 */ // TN ar-TN Arabic (Tunisia) - 0x041F, /* 98 */ // TR tr-TR Turkish (Turkey) - 0x2C09, /* 99 */ // TT en-TT English (Trinidad and Tobago) - 0x0404, /*100 */ // TW zh-TW Chinese (Taiwan) - 0x0422, /*101 */ // UA uk-UA Ukrainian (Ukraine) - 0x0409, /*102 */ // US en-US English (United States) - 0x380A, /*103 */ // UY es-UY Spanish (Uruguay) - 0x0443, /*104 */ // UZ uz-UZ-Latn Uzbek (Latin) (Uzbekistan) - // 0x0843, 104 // UZ uz-UZ-Cyrl Uzbek (Cyrillic) (Uzbekistan) - 0x200A, /*105*/ // VE es-VE Spanish (Venezuela) - 0x042A, /*106*/ // VN vi-VN Vietnamese (Viet Nam) - 0x2401, /*107*/ // YE ar-YE Arabic (Yemen) - 0x0436, /*108*/ // ZA af-ZA Afrikaans (South Africa) - // 0x1C09, 108, // ZA en-ZA English (South Africa) - 0x3009, /*109*/ // ZW en-ZW English (Zimbabwe) - }; -#endif - [System.Security.SecurityCritical] // auto-generated [OnDeserialized] private void OnDeserialized(StreamingContext ctx) { -#if FEATURE_CORECLR // This won't happen anyway since CoreCLR doesn't support serialization this.m_cultureData = CultureData.GetCultureData(m_name, true); -#else - if (m_name == null) - { - Contract.Assert(m_dataItem >= 0, "[RegionInfo.OnDeserialized] null name and invalid dataItem"); - m_cultureId = IdFromEverettRegionInfoDataItem[m_dataItem]; - } - if (m_cultureId == 0) - { - this.m_cultureData = CultureData.GetCultureDataForRegion(this.m_name, true); - } - else - { - this.m_cultureData = CultureData.GetCultureData(m_cultureId, true); - } - -#endif if (this.m_cultureData == null) throw new ArgumentException( String.Format( CultureInfo.CurrentCulture, - Environment.GetResourceString("Argument_InvalidCultureName"), m_name), "m_name"); + Environment.GetResourceString("Argument_InvalidCultureName"), m_name), nameof(m_name)); if (m_cultureId == 0) { @@ -359,7 +190,6 @@ namespace System.Globalization { // //////////////////////////////////////////////////////////////////////// public static RegionInfo CurrentRegion { - [System.Security.SecuritySafeCritical] // auto-generated get { RegionInfo temp = s_currentRegionInfo; if (temp == null) @@ -383,7 +213,7 @@ namespace System.Globalization { //////////////////////////////////////////////////////////////////////// public virtual String Name { get { - Contract.Assert(m_name != null, "Expected RegionInfo.m_name to be populated already"); + Debug.Assert(m_name != null, "Expected RegionInfo.m_name to be populated already"); return (m_name); } } @@ -397,7 +227,6 @@ namespace System.Globalization { //////////////////////////////////////////////////////////////////////// public virtual String EnglishName { - [System.Security.SecuritySafeCritical] // auto-generated get { return (this.m_cultureData.SENGCOUNTRY); @@ -415,7 +244,6 @@ namespace System.Globalization { //////////////////////////////////////////////////////////////////////// public virtual String DisplayName { - [System.Security.SecuritySafeCritical] // auto-generated get { return (this.m_cultureData.SLOCALIZEDCOUNTRY); @@ -434,7 +262,6 @@ namespace System.Globalization { [System.Runtime.InteropServices.ComVisible(false)] public virtual String NativeName { - [System.Security.SecuritySafeCritical] // auto-generated get { return (this.m_cultureData.SNATIVECOUNTRY); @@ -450,7 +277,6 @@ namespace System.Globalization { //////////////////////////////////////////////////////////////////////// public virtual String TwoLetterISORegionName { - [System.Security.SecuritySafeCritical] // auto-generated get { return (this.m_cultureData.SISO3166CTRYNAME); @@ -467,7 +293,6 @@ namespace System.Globalization { //////////////////////////////////////////////////////////////////////// public virtual String ThreeLetterISORegionName { - [System.Security.SecuritySafeCritical] // auto-generated get { return (this.m_cultureData.SISO3166CTRYNAME2); @@ -483,7 +308,6 @@ namespace System.Globalization { //////////////////////////////////////////////////////////////////////// public virtual String ThreeLetterWindowsRegionName { - [System.Security.SecuritySafeCritical] // auto-generated get { return (this.m_cultureData.SABBREVCTRYNAME); @@ -524,7 +348,6 @@ namespace System.Globalization { [System.Runtime.InteropServices.ComVisible(false)] public virtual String CurrencyEnglishName { - [System.Security.SecuritySafeCritical] // auto-generated get { return (this.m_cultureData.SENGLISHCURRENCY); @@ -542,7 +365,6 @@ namespace System.Globalization { [System.Runtime.InteropServices.ComVisible(false)] public virtual String CurrencyNativeName { - [System.Security.SecuritySafeCritical] // auto-generated get { return (this.m_cultureData.SNATIVECURRENCY); @@ -557,7 +379,6 @@ namespace System.Globalization { // //////////////////////////////////////////////////////////////////////// public virtual String CurrencySymbol { - [System.Security.SecuritySafeCritical] // auto-generated get { return (this.m_cultureData.SCURRENCY); } @@ -571,7 +392,6 @@ namespace System.Globalization { // //////////////////////////////////////////////////////////////////////// public virtual String ISOCurrencySymbol { - [System.Security.SecuritySafeCritical] // auto-generated get { return (this.m_cultureData.SINTLSYMBOL); } diff --git a/src/mscorlib/src/System/Globalization/SortKey.cs b/src/mscorlib/src/System/Globalization/SortKey.cs index e3308dc4f8..9c35f485e5 100644 --- a/src/mscorlib/src/System/Globalization/SortKey.cs +++ b/src/mscorlib/src/System/Globalization/SortKey.cs @@ -16,6 +16,7 @@ namespace System.Globalization { using System; using System.Runtime.CompilerServices; using System.Runtime.Serialization; + using System.Diagnostics; using System.Diagnostics.Contracts; [System.Runtime.InteropServices.ComVisible(true)] @@ -119,15 +120,15 @@ namespace System.Globalization { public static int Compare(SortKey sortkey1, SortKey sortkey2) { if (sortkey1==null || sortkey2==null) { - throw new ArgumentNullException((sortkey1==null ? "sortkey1": "sortkey2")); + throw new ArgumentNullException((sortkey1==null ? nameof(sortkey1): nameof(sortkey2))); } Contract.EndContractBlock(); byte[] key1Data = sortkey1.m_KeyData; byte[] key2Data = sortkey2.m_KeyData; - Contract.Assert(key1Data!=null, "key1Data!=null"); - Contract.Assert(key2Data!=null, "key2Data!=null"); + Debug.Assert(key1Data!=null, "key1Data!=null"); + Debug.Assert(key2Data!=null, "key2Data!=null"); if (key1Data.Length == 0) { if (key2Data.Length == 0) { diff --git a/src/mscorlib/src/System/Globalization/StringInfo.cs b/src/mscorlib/src/System/Globalization/StringInfo.cs index b1151bde4f..d86e11592e 100644 --- a/src/mscorlib/src/System/Globalization/StringInfo.cs +++ b/src/mscorlib/src/System/Globalization/StringInfo.cs @@ -17,6 +17,7 @@ namespace System.Globalization { using System; using System.Runtime.Serialization; using System.Security.Permissions; + using System.Diagnostics; using System.Diagnostics.Contracts; [Serializable] @@ -92,7 +93,7 @@ namespace System.Globalization { } set { if (null == value) { - throw new ArgumentNullException("String", + throw new ArgumentNullException(nameof(String), Environment.GetResourceString("ArgumentNull_String")); } Contract.EndContractBlock(); @@ -118,11 +119,11 @@ namespace System.Globalization { if(null == this.Indexes) { // Just decide which error to give depending on the param they gave us.... if(startingTextElement < 0) { - throw new ArgumentOutOfRangeException("startingTextElement", + throw new ArgumentOutOfRangeException(nameof(startingTextElement), Environment.GetResourceString("ArgumentOutOfRange_NeedPosNum")); } else { - throw new ArgumentOutOfRangeException("startingTextElement", + throw new ArgumentOutOfRangeException(nameof(startingTextElement), Environment.GetResourceString("Arg_ArgumentOutOfRangeException")); } } @@ -135,22 +136,22 @@ namespace System.Globalization { // Parameter checking // if(startingTextElement < 0) { - throw new ArgumentOutOfRangeException("startingTextElement", + throw new ArgumentOutOfRangeException(nameof(startingTextElement), Environment.GetResourceString("ArgumentOutOfRange_NeedPosNum")); } if(this.String.Length == 0 || startingTextElement >= this.Indexes.Length) { - throw new ArgumentOutOfRangeException("startingTextElement", + throw new ArgumentOutOfRangeException(nameof(startingTextElement), Environment.GetResourceString("Arg_ArgumentOutOfRangeException")); } if(lengthInTextElements < 0) { - throw new ArgumentOutOfRangeException("lengthInTextElements", + throw new ArgumentOutOfRangeException(nameof(lengthInTextElements), Environment.GetResourceString("ArgumentOutOfRange_NeedPosNum")); } if(startingTextElement > this.Indexes.Length - lengthInTextElements) { - throw new ArgumentOutOfRangeException("lengthInTextElements", + throw new ArgumentOutOfRangeException(nameof(lengthInTextElements), Environment.GetResourceString("Arg_ArgumentOutOfRangeException")); } @@ -206,8 +207,8 @@ namespace System.Globalization { internal static int GetCurrentTextElementLen(String str, int index, int len, ref UnicodeCategory ucCurrent, ref int currentCharCount) { - Contract.Assert(index >= 0 && len >= 0, "StringInfo.GetCurrentTextElementLen() : index = " + index + ", len = " + len); - Contract.Assert(index < len, "StringInfo.GetCurrentTextElementLen() : index = " + index + ", len = " + len); + Debug.Assert(index >= 0 && len >= 0, "StringInfo.GetCurrentTextElementLen() : index = " + index + ", len = " + len); + Debug.Assert(index < len, "StringInfo.GetCurrentTextElementLen() : index = " + index + ", len = " + len); if (index + currentCharCount == len) { // This is the last character/surrogate in the string. @@ -268,7 +269,7 @@ namespace System.Globalization { // Validate parameters. // if (str==null) { - throw new ArgumentNullException("str"); + throw new ArgumentNullException(nameof(str)); } Contract.EndContractBlock(); @@ -277,7 +278,7 @@ namespace System.Globalization { if (index == len) { return (String.Empty); } - throw new ArgumentOutOfRangeException("index", Environment.GetResourceString("ArgumentOutOfRange_Index")); + throw new ArgumentOutOfRangeException(nameof(index), Environment.GetResourceString("ArgumentOutOfRange_Index")); } int charLen; @@ -297,14 +298,14 @@ namespace System.Globalization { // if (str==null) { - throw new ArgumentNullException("str"); + throw new ArgumentNullException(nameof(str)); } Contract.EndContractBlock(); int len = str.Length; if (index < 0 || (index > len)) { - throw new ArgumentOutOfRangeException("index", Environment.GetResourceString("ArgumentOutOfRange_Index")); + throw new ArgumentOutOfRangeException(nameof(index), Environment.GetResourceString("ArgumentOutOfRange_Index")); } return (new TextElementEnumerator(str, index, len)); @@ -326,7 +327,7 @@ namespace System.Globalization { { if (str == null) { - throw new ArgumentNullException("str"); + throw new ArgumentNullException(nameof(str)); } Contract.EndContractBlock(); diff --git a/src/mscorlib/src/System/Globalization/TaiwanCalendar.cs b/src/mscorlib/src/System/Globalization/TaiwanCalendar.cs index 013e2cd50e..476ddeef7c 100644 --- a/src/mscorlib/src/System/Globalization/TaiwanCalendar.cs +++ b/src/mscorlib/src/System/Globalization/TaiwanCalendar.cs @@ -241,14 +241,14 @@ namespace System.Globalization { public override int ToFourDigitYear(int year) { if (year <= 0) { - throw new ArgumentOutOfRangeException("year", + throw new ArgumentOutOfRangeException(nameof(year), Environment.GetResourceString("ArgumentOutOfRange_NeedPosNum")); } Contract.EndContractBlock(); if (year > helper.MaxYear) { throw new ArgumentOutOfRangeException( - "year", + nameof(year), String.Format( CultureInfo.CurrentCulture, Environment.GetResourceString("ArgumentOutOfRange_Range"), diff --git a/src/mscorlib/src/System/Globalization/TextElementEnumerator.cs b/src/mscorlib/src/System/Globalization/TextElementEnumerator.cs index 5f47f5fbd4..049ccf6f81 100644 --- a/src/mscorlib/src/System/Globalization/TextElementEnumerator.cs +++ b/src/mscorlib/src/System/Globalization/TextElementEnumerator.cs @@ -15,6 +15,7 @@ using System.Runtime.Serialization; namespace System.Globalization { using System.Collections; + using System.Diagnostics; using System.Diagnostics.Contracts; // @@ -43,9 +44,9 @@ namespace System.Globalization { internal TextElementEnumerator(String str, int startIndex, int strLen) { - Contract.Assert(str != null, "TextElementEnumerator(): str != null"); - Contract.Assert(startIndex >= 0 && strLen >= 0, "TextElementEnumerator(): startIndex >= 0 && strLen >= 0"); - Contract.Assert(strLen >= startIndex, "TextElementEnumerator(): strLen >= startIndex"); + Debug.Assert(str != null, "TextElementEnumerator(): str != null"); + Debug.Assert(startIndex >= 0 && strLen >= 0, "TextElementEnumerator(): startIndex >= 0 && strLen >= 0"); + Debug.Assert(strLen >= startIndex, "TextElementEnumerator(): strLen >= startIndex"); this.str = str; this.startIndex = startIndex; this.strLen = strLen; diff --git a/src/mscorlib/src/System/Globalization/TextInfo.cs b/src/mscorlib/src/System/Globalization/TextInfo.cs index 9b84486f4e..c8108e4922 100644 --- a/src/mscorlib/src/System/Globalization/TextInfo.cs +++ b/src/mscorlib/src/System/Globalization/TextInfo.cs @@ -24,6 +24,7 @@ namespace System.Globalization { using System.Runtime.Serialization; using System.Runtime.Versioning; using System.Security.Permissions; + using System.Diagnostics; using System.Diagnostics.Contracts; @@ -106,11 +107,6 @@ namespace System.Globalization { this.m_cultureData = cultureData; this.m_cultureName = this.m_cultureData.CultureName; this.m_textInfoName = this.m_cultureData.STEXTINFO; -#if !FEATURE_CORECLR - IntPtr handleOrigin; - this.m_dataHandle = CompareInfo.InternalInitSortHandle(m_textInfoName, out handleOrigin); - this.m_handleOrigin = handleOrigin; -#endif } //////////////////////////////////////////////////////////////////////// @@ -179,30 +175,18 @@ namespace System.Globalization { // Get the text info name belonging to that culture this.m_cultureData = CultureInfo.GetCultureInfo(m_cultureName).m_cultureData; this.m_textInfoName = this.m_cultureData.STEXTINFO; -#if !FEATURE_CORECLR - IntPtr handleOrigin; - this.m_dataHandle = CompareInfo.InternalInitSortHandle(m_textInfoName, out handleOrigin); - this.m_handleOrigin = handleOrigin; -#endif - } + } } - [OnDeserialized] private void OnDeserialized(StreamingContext ctx) { OnDeserialized(); - } - + } + [OnSerializing] private void OnSerializing(StreamingContext ctx) - { -#if !FEATURE_CORECLR - // Initialize the fields Whidbey expects: - // Whidbey expected this, so set it, but the value doesn't matter much - this.m_useUserOverride = false; -#endif // FEATURE_CORECLR - + { // Relabel our name since Whidbey expects it to be called customCultureName this.customCultureName = this.m_cultureName; @@ -229,7 +213,6 @@ namespace System.Globalization { return (Invariant.GetCaseInsensitiveHashCode(s, forceRandomizedHashing, additionalEntropy)); } - [System.Security.SecuritySafeCritical] internal static unsafe bool TryFastFindStringOrdinalIgnoreCase(int searchFlags, String source, int startIndex, String value, int count, ref int foundIndex) { return InternalTryFindStringOrdinalIgnoreCase(searchFlags, source, count, startIndex, value, value.Length, ref foundIndex); @@ -237,7 +220,6 @@ namespace System.Globalization { // This function doesn't check arguments. Please do check in the caller. // The underlying unmanaged code will assert the sanity of arguments. - [System.Security.SecuritySafeCritical] // auto-generated internal static unsafe int CompareOrdinalIgnoreCase(String str1, String str2) { // Compare the whole string and ignore case. @@ -246,19 +228,18 @@ namespace System.Globalization { // This function doesn't check arguments. Please do check in the caller. // The underlying unmanaged code will assert the sanity of arguments. - [System.Security.SecuritySafeCritical] // auto-generated internal static unsafe int CompareOrdinalIgnoreCaseEx(String strA, int indexA, String strB, int indexB, int lengthA, int lengthB ) { - Contract.Assert(strA.Length >= indexA + lengthA, "[TextInfo.CompareOrdinalIgnoreCaseEx] Caller should've validated strA.Length >= indexA + lengthA"); - Contract.Assert(strB.Length >= indexB + lengthB, "[TextInfo.CompareOrdinalIgnoreCaseEx] Caller should've validated strB.Length >= indexB + lengthB"); + Debug.Assert(strA.Length >= indexA + lengthA, "[TextInfo.CompareOrdinalIgnoreCaseEx] Caller should've validated strA.Length >= indexA + lengthA"); + Debug.Assert(strB.Length >= indexB + lengthB, "[TextInfo.CompareOrdinalIgnoreCaseEx] Caller should've validated strB.Length >= indexB + lengthB"); return InternalCompareStringOrdinalIgnoreCase(strA, indexA, strB, indexB, lengthA, lengthB); } internal static int IndexOfStringOrdinalIgnoreCase(String source, String value, int startIndex, int count) { - Contract.Assert(source != null, "[TextInfo.IndexOfStringOrdinalIgnoreCase] Caller should've validated source != null"); - Contract.Assert(value != null, "[TextInfo.IndexOfStringOrdinalIgnoreCase] Caller should've validated value != null"); - Contract.Assert(startIndex + count <= source.Length, "[TextInfo.IndexOfStringOrdinalIgnoreCase] Caller should've validated startIndex + count <= source.Length"); + Debug.Assert(source != null, "[TextInfo.IndexOfStringOrdinalIgnoreCase] Caller should've validated source != null"); + Debug.Assert(value != null, "[TextInfo.IndexOfStringOrdinalIgnoreCase] Caller should've validated value != null"); + Debug.Assert(startIndex + count <= source.Length, "[TextInfo.IndexOfStringOrdinalIgnoreCase] Caller should've validated startIndex + count <= source.Length"); // We return 0 if both inputs are empty strings if (source.Length == 0 && value.Length == 0) @@ -285,7 +266,7 @@ namespace System.Globalization { for (; startIndex <= maxStartIndex; startIndex++) { // We should always have the same or more characters left to search than our actual pattern - Contract.Assert(end - startIndex >= value.Length); + Debug.Assert(end - startIndex >= value.Length); // since this is an ordinal comparison, we can assume that the lengths must match if (CompareOrdinalIgnoreCaseEx(source, startIndex, value, 0, value.Length, value.Length) == 0) { @@ -299,10 +280,10 @@ namespace System.Globalization { internal static int LastIndexOfStringOrdinalIgnoreCase(String source, String value, int startIndex, int count) { - Contract.Assert(source != null, "[TextInfo.LastIndexOfStringOrdinalIgnoreCase] Caller should've validated source != null"); - Contract.Assert(value != null, "[TextInfo.LastIndexOfStringOrdinalIgnoreCase] Caller should've validated value != null"); - Contract.Assert(startIndex - count+1 >= 0, "[TextInfo.LastIndexOfStringOrdinalIgnoreCase] Caller should've validated startIndex - count+1 >= 0"); - Contract.Assert(startIndex <= source.Length, "[TextInfo.LastIndexOfStringOrdinalIgnoreCase] Caller should've validated startIndex <= source.Length"); + Debug.Assert(source != null, "[TextInfo.LastIndexOfStringOrdinalIgnoreCase] Caller should've validated source != null"); + Debug.Assert(value != null, "[TextInfo.LastIndexOfStringOrdinalIgnoreCase] Caller should've validated value != null"); + Debug.Assert(startIndex - count+1 >= 0, "[TextInfo.LastIndexOfStringOrdinalIgnoreCase] Caller should've validated startIndex - count+1 >= 0"); + Debug.Assert(startIndex <= source.Length, "[TextInfo.LastIndexOfStringOrdinalIgnoreCase] Caller should've validated startIndex <= source.Length"); // If value is Empty, the return value is startIndex if (value.Length == 0) @@ -462,7 +443,7 @@ namespace System.Globalization { [System.Runtime.InteropServices.ComVisible(false)] public static TextInfo ReadOnly(TextInfo textInfo) { - if (textInfo == null) { throw new ArgumentNullException("textInfo"); } + if (textInfo == null) { throw new ArgumentNullException(nameof(textInfo)); } Contract.EndContractBlock(); if (textInfo.IsReadOnly) { return (textInfo); } @@ -498,7 +479,6 @@ namespace System.Globalization { public virtual String ListSeparator { - [System.Security.SecuritySafeCritical] // auto-generated get { if (m_listSeparator == null) { @@ -512,7 +492,7 @@ namespace System.Globalization { { if (value == null) { - throw new ArgumentNullException("value", Environment.GetResourceString("ArgumentNull_String")); + throw new ArgumentNullException(nameof(value), Environment.GetResourceString("ArgumentNull_String")); } Contract.EndContractBlock(); VerifyWritable(); @@ -529,7 +509,6 @@ namespace System.Globalization { // //////////////////////////////////////////////////////////////////////// - [System.Security.SecuritySafeCritical] // auto-generated public unsafe virtual char ToLower(char c) { if(IsAscii(c) && IsAsciiCasingSameAsInvariant) @@ -539,10 +518,9 @@ namespace System.Globalization { return (InternalChangeCaseChar(this.m_dataHandle, this.m_handleOrigin, this.m_textInfoName, c, false)); } - [System.Security.SecuritySafeCritical] // auto-generated public unsafe virtual String ToLower(String str) { - if (str == null) { throw new ArgumentNullException("str"); } + if (str == null) { throw new ArgumentNullException(nameof(str)); } Contract.EndContractBlock(); return InternalChangeCaseString(this.m_dataHandle, this.m_handleOrigin, this.m_textInfoName, str, false); @@ -567,7 +545,6 @@ namespace System.Globalization { // //////////////////////////////////////////////////////////////////////// - [System.Security.SecuritySafeCritical] // auto-generated public unsafe virtual char ToUpper(char c) { if (IsAscii(c) && IsAsciiCasingSameAsInvariant) @@ -578,10 +555,9 @@ namespace System.Globalization { } - [System.Security.SecuritySafeCritical] // auto-generated public unsafe virtual String ToUpper(String str) { - if (str == null) { throw new ArgumentNullException("str"); } + if (str == null) { throw new ArgumentNullException(nameof(str)); } Contract.EndContractBlock(); return InternalChangeCaseString(this.m_dataHandle, this.m_handleOrigin, this.m_textInfoName, str, true); } @@ -698,7 +674,7 @@ namespace System.Globalization { { if (str == null) { - throw new ArgumentNullException("str"); + throw new ArgumentNullException(nameof(str)); } Contract.EndContractBlock(); if (str.Length == 0) @@ -809,7 +785,7 @@ namespace System.Globalization { private static int AddNonLetter(ref StringBuilder result, ref String input, int inputIndex, int charLen) { - Contract.Assert(charLen == 1 || charLen == 2, "[TextInfo.AddNonLetter] CharUnicodeInfo.InternalGetUnicodeCategory returned an unexpected charLen!"); + Debug.Assert(charLen == 1 || charLen == 2, "[TextInfo.AddNonLetter] CharUnicodeInfo.InternalGetUnicodeCategory returned an unexpected charLen!"); if (charLen == 2) { // Surrogate pair @@ -826,7 +802,7 @@ namespace System.Globalization { private int AddTitlecaseLetter(ref StringBuilder result, ref String input, int inputIndex, int charLen) { - Contract.Assert(charLen == 1 || charLen == 2, "[TextInfo.AddTitlecaseLetter] CharUnicodeInfo.InternalGetUnicodeCategory returned an unexpected charLen!"); + Debug.Assert(charLen == 1 || charLen == 2, "[TextInfo.AddTitlecaseLetter] CharUnicodeInfo.InternalGetUnicodeCategory returned an unexpected charLen!"); // for surrogate pairs do a simple ToUpper operation on the substring if (charLen == 2) @@ -947,19 +923,17 @@ namespace System.Globalization { // is not null before calling this. Currenlty, CaseInsensitiveHashCodeProvider // does that. // - [System.Security.SecuritySafeCritical] // auto-generated internal unsafe int GetCaseInsensitiveHashCode(String str) { return GetCaseInsensitiveHashCode(str, false, 0); } - [System.Security.SecuritySafeCritical] // auto-generated internal unsafe int GetCaseInsensitiveHashCode(String str, bool forceRandomizedHashing, long additionalEntropy) { // Validate inputs if (str==null) { - throw new ArgumentNullException("str"); + throw new ArgumentNullException(nameof(str)); } Contract.EndContractBlock(); @@ -968,23 +942,19 @@ namespace System.Globalization { } // Change case (ToUpper/ToLower) -- COMNlsInfo::InternalChangeCaseChar - [System.Security.SecurityCritical] // auto-generated [MethodImplAttribute(MethodImplOptions.InternalCall)] private static unsafe extern char InternalChangeCaseChar(IntPtr handle, IntPtr handleOrigin, String localeName, char ch, bool isToUpper); // Change case (ToUpper/ToLower) -- COMNlsInfo::InternalChangeCaseString - [System.Security.SecurityCritical] // auto-generated [MethodImplAttribute(MethodImplOptions.InternalCall)] private static unsafe extern String InternalChangeCaseString(IntPtr handle, IntPtr handleOrigin, String localeName, String str, bool isToUpper); // Get case insensitive hash -- ComNlsInfo::InternalGetCaseInsHash - [System.Security.SecurityCritical] // auto-generated [MethodImplAttribute(MethodImplOptions.InternalCall)] private static unsafe extern int InternalGetCaseInsHash(IntPtr handle, IntPtr handleOrigin, String localeName, String str, bool forceRandomizedHashing, long additionalEntropy); // Call ::CompareStringOrdinal -- ComNlsInfo::InternalCompareStringOrdinalIgnoreCase // Start at indexes and compare for length characters (or remainder of string if length == -1) - [System.Security.SecurityCritical] // auto-generated [DllImport(JitHelpers.QCall, CharSet = CharSet.Unicode)] [SuppressUnmanagedCodeSecurity] private static unsafe extern int InternalCompareStringOrdinalIgnoreCase(String string1, int index1, String string2, int index2, int length1, int length2); @@ -992,7 +962,6 @@ namespace System.Globalization { // ComNlsInfo::InternalTryFindStringOrdinalIgnoreCase attempts a faster IndexOf/LastIndexOf OrdinalIgnoreCase using a kernel function. // Returns true if FindStringOrdinal was handled, with foundIndex set to the target's index into the source // Returns false when FindStringOrdinal wasn't handled - [System.Security.SecurityCritical] // auto-generated [DllImport(JitHelpers.QCall, CharSet = CharSet.Unicode)] [SuppressUnmanagedCodeSecurity] [return: MarshalAs(UnmanagedType.Bool)] diff --git a/src/mscorlib/src/System/Globalization/ThaiBuddhistCalendar.cs b/src/mscorlib/src/System/Globalization/ThaiBuddhistCalendar.cs index f26c68adce..e294b51325 100644 --- a/src/mscorlib/src/System/Globalization/ThaiBuddhistCalendar.cs +++ b/src/mscorlib/src/System/Globalization/ThaiBuddhistCalendar.cs @@ -213,7 +213,7 @@ namespace System.Globalization { public override int ToFourDigitYear(int year) { if (year < 0) { - throw new ArgumentOutOfRangeException("year", + throw new ArgumentOutOfRangeException(nameof(year), Environment.GetResourceString("ArgumentOutOfRange_NeedNonNegNum")); } Contract.EndContractBlock(); diff --git a/src/mscorlib/src/System/Globalization/TimeSpanFormat.cs b/src/mscorlib/src/System/Globalization/TimeSpanFormat.cs index 8f58623868..e5e615f1b3 100644 --- a/src/mscorlib/src/System/Globalization/TimeSpanFormat.cs +++ b/src/mscorlib/src/System/Globalization/TimeSpanFormat.cs @@ -6,12 +6,12 @@ namespace System.Globalization { using System.Text; using System; + using System.Diagnostics; using System.Diagnostics.Contracts; using System.Globalization; internal static class TimeSpanFormat { - [System.Security.SecuritySafeCritical] // auto-generated private static String IntToString(int n, int digits) { return ParseNumbers.IntToString(n, 10, digits, '0', 0); } @@ -143,7 +143,7 @@ namespace System.Globalization { // internal static String FormatCustomized(TimeSpan value, String format, DateTimeFormatInfo dtfi) { - Contract.Assert(dtfi != null, "dtfi == null"); + Debug.Assert(dtfi != null, "dtfi == null"); int day = (int)(value._ticks / TimeSpan.TicksPerDay); long time = value._ticks % TimeSpan.TicksPerDay; @@ -369,7 +369,7 @@ namespace System.Globalization { case '\"': if (inQuote && (quote == format[i])) { /* we were in a quote and found a matching exit quote, so we are outside a quote now */ - Contract.Assert(field >= 0 && field <= 5, "field >= 0 && field <= 5"); + Debug.Assert(field >= 0 && field <= 5, "field >= 0 && field <= 5"); if (field >= 0 && field <= 5) { literals[field] = sb.ToString(); sb.Length = 0; @@ -389,7 +389,7 @@ namespace System.Globalization { } break; case '%': - Contract.Assert(false, "Unexpected special token '%', Bug in DateTimeFormatInfo.FullTimeSpan[Positive|Negative]Pattern"); + Debug.Assert(false, "Unexpected special token '%', Bug in DateTimeFormatInfo.FullTimeSpan[Positive|Negative]Pattern"); goto default; case '\\': if (!inQuote) { @@ -399,7 +399,7 @@ namespace System.Globalization { goto default; case 'd': if (!inQuote) { - Contract.Assert((field == 0 && sb.Length == 0) || field == 1, + Debug.Assert((field == 0 && sb.Length == 0) || field == 1, "field == 0 || field == 1, Bug in DateTimeFormatInfo.FullTimeSpan[Positive|Negative]Pattern"); field = 1; // DayHourSep dd++; @@ -407,7 +407,7 @@ namespace System.Globalization { break; case 'h': if (!inQuote) { - Contract.Assert((field == 1 && sb.Length == 0) || field == 2, + Debug.Assert((field == 1 && sb.Length == 0) || field == 2, "field == 1 || field == 2, Bug in DateTimeFormatInfo.FullTimeSpan[Positive|Negative]Pattern"); field = 2; // HourMinuteSep hh++; @@ -415,7 +415,7 @@ namespace System.Globalization { break; case 'm': if (!inQuote) { - Contract.Assert((field == 2 && sb.Length == 0) || field == 3, + Debug.Assert((field == 2 && sb.Length == 0) || field == 3, "field == 2 || field == 3, Bug in DateTimeFormatInfo.FullTimeSpan[Positive|Negative]Pattern"); field = 3; // MinuteSecondSep mm++; @@ -423,7 +423,7 @@ namespace System.Globalization { break; case 's': if (!inQuote) { - Contract.Assert((field == 3 && sb.Length == 0) || field == 4, + Debug.Assert((field == 3 && sb.Length == 0) || field == 4, "field == 3 || field == 4, Bug in DateTimeFormatInfo.FullTimeSpan[Positive|Negative]Pattern"); field = 4; // SecondFractionSep ss++; @@ -432,7 +432,7 @@ namespace System.Globalization { case 'f': case 'F': if (!inQuote) { - Contract.Assert((field == 4 && sb.Length == 0) || field == 5, + Debug.Assert((field == 4 && sb.Length == 0) || field == 5, "field == 4 || field == 5, Bug in DateTimeFormatInfo.FullTimeSpan[Positive|Negative]Pattern"); field = 5; // End ff++; @@ -444,14 +444,14 @@ namespace System.Globalization { } } - Contract.Assert(field == 5); + Debug.Assert(field == 5); AppCompatLiteral = MinuteSecondSep + SecondFractionSep; - Contract.Assert(0 < dd && dd < 3, "0 < dd && dd < 3, Bug in System.Globalization.DateTimeFormatInfo.FullTimeSpan[Positive|Negative]Pattern"); - Contract.Assert(0 < hh && hh < 3, "0 < hh && hh < 3, Bug in System.Globalization.DateTimeFormatInfo.FullTimeSpan[Positive|Negative]Pattern"); - Contract.Assert(0 < mm && mm < 3, "0 < mm && mm < 3, Bug in System.Globalization.DateTimeFormatInfo.FullTimeSpan[Positive|Negative]Pattern"); - Contract.Assert(0 < ss && ss < 3, "0 < ss && ss < 3, Bug in System.Globalization.DateTimeFormatInfo.FullTimeSpan[Positive|Negative]Pattern"); - Contract.Assert(0 < ff && ff < 8, "0 < ff && ff < 8, Bug in System.Globalization.DateTimeFormatInfo.FullTimeSpan[Positive|Negative]Pattern"); + Debug.Assert(0 < dd && dd < 3, "0 < dd && dd < 3, Bug in System.Globalization.DateTimeFormatInfo.FullTimeSpan[Positive|Negative]Pattern"); + Debug.Assert(0 < hh && hh < 3, "0 < hh && hh < 3, Bug in System.Globalization.DateTimeFormatInfo.FullTimeSpan[Positive|Negative]Pattern"); + Debug.Assert(0 < mm && mm < 3, "0 < mm && mm < 3, Bug in System.Globalization.DateTimeFormatInfo.FullTimeSpan[Positive|Negative]Pattern"); + Debug.Assert(0 < ss && ss < 3, "0 < ss && ss < 3, Bug in System.Globalization.DateTimeFormatInfo.FullTimeSpan[Positive|Negative]Pattern"); + Debug.Assert(0 < ff && ff < 8, "0 < ff && ff < 8, Bug in System.Globalization.DateTimeFormatInfo.FullTimeSpan[Positive|Negative]Pattern"); if (useInvariantFieldLengths) { dd = 2; diff --git a/src/mscorlib/src/System/Globalization/TimeSpanParse.cs b/src/mscorlib/src/System/Globalization/TimeSpanParse.cs index e72e582a97..d83c5fa151 100644 --- a/src/mscorlib/src/System/Globalization/TimeSpanParse.cs +++ b/src/mscorlib/src/System/Globalization/TimeSpanParse.cs @@ -53,6 +53,7 @@ namespace System.Globalization { using System.Text; using System; + using System.Diagnostics; using System.Diagnostics.Contracts; using System.Globalization; @@ -126,10 +127,10 @@ namespace System.Globalization { } public bool IsInvalidNumber(int maxValue, int maxPrecision) { - Contract.Assert(ttt == TTT.Num); - Contract.Assert(num > -1); - Contract.Assert(maxValue > 0); - Contract.Assert(maxPrecision == maxFractionDigits || maxPrecision == unlimitedDigits); + Debug.Assert(ttt == TTT.Num); + Debug.Assert(num > -1); + Debug.Assert(maxValue > 0); + Debug.Assert(maxPrecision == maxFractionDigits || maxPrecision == unlimitedDigits); if (num > maxValue) return true; @@ -163,7 +164,7 @@ namespace System.Globalization { } // used by the parsing routines that operate on standard-formats internal TimeSpanToken GetNextToken() { - Contract.Assert(m_pos > -1); + Debug.Assert(m_pos > -1); TimeSpanToken tok = new TimeSpanToken(); char ch = CurrentChar; @@ -374,7 +375,7 @@ namespace System.Globalization { private const int MaxNumericTokens = 5; internal void Init(DateTimeFormatInfo dtfi) { - Contract.Assert(dtfi != null); + Debug.Assert(dtfi != null); lastSeenTTT = TTT.None; tokenCount = 0; @@ -416,7 +417,7 @@ namespace System.Globalization { } lastSeenTTT = tok.ttt; - Contract.Assert(tokenCount == (SepCount + NumCount), "tokenCount == (SepCount + NumCount)"); + Debug.Assert(tokenCount == (SepCount + NumCount), "tokenCount == (SepCount + NumCount)"); return true; } @@ -486,7 +487,7 @@ namespace System.Globalization { return new OverflowException(Environment.GetResourceString(m_failureMessageID)); default: - Contract.Assert(false, "Unknown TimeSpanParseFailure: " + m_failure); + Debug.Assert(false, "Unknown TimeSpanParseFailure: " + m_failure); return new FormatException(Environment.GetResourceString("Format_InvalidString")); } } @@ -627,7 +628,7 @@ namespace System.Globalization { // private static Boolean TryParseTimeSpan(String input, TimeSpanStandardStyles style, IFormatProvider formatProvider, ref TimeSpanResult result) { if (input == null) { - result.SetFailure(ParseFailureKind.ArgumentNull, "ArgumentNull_String", null, "input"); + result.SetFailure(ParseFailureKind.ArgumentNull, "ArgumentNull_String", null, nameof(input)); return false; } @@ -1117,11 +1118,11 @@ namespace System.Globalization { // private static Boolean TryParseExactTimeSpan(String input, String format, IFormatProvider formatProvider, TimeSpanStyles styles, ref TimeSpanResult result) { if (input == null) { - result.SetFailure(ParseFailureKind.ArgumentNull, "ArgumentNull_String", null, "input"); + result.SetFailure(ParseFailureKind.ArgumentNull, "ArgumentNull_String", null, nameof(input)); return false; } if (format == null) { - result.SetFailure(ParseFailureKind.ArgumentNull, "ArgumentNull_String", null, "format"); + result.SetFailure(ParseFailureKind.ArgumentNull, "ArgumentNull_String", null, nameof(format)); return false; } if (format.Length == 0) { @@ -1158,8 +1159,8 @@ namespace System.Globalization { // Actions: Parse the TimeSpan instance using the specified format. Used by TryParseExactTimeSpan. // private static Boolean TryParseByFormat(String input, String format, TimeSpanStyles styles, ref TimeSpanResult result) { - Contract.Assert(input != null, "input != null"); - Contract.Assert(format != null, "format != null"); + Debug.Assert(input != null, "input != null"); + Debug.Assert(format != null, "format != null"); bool seenDD = false; // already processed days? bool seenHH = false; // already processed hours? @@ -1376,7 +1377,7 @@ namespace System.Globalization { result.parsedTimeSpan._ticks = 0; if (input == null) { - result.SetFailure(ParseFailureKind.ArgumentNull, "ArgumentNull_String", null, "input"); + result.SetFailure(ParseFailureKind.ArgumentNull, "ArgumentNull_String", null, nameof(input)); return false; } str = input; @@ -1511,11 +1512,11 @@ namespace System.Globalization { // private static Boolean TryParseExactMultipleTimeSpan(String input, String[] formats, IFormatProvider formatProvider, TimeSpanStyles styles, ref TimeSpanResult result) { if (input == null) { - result.SetFailure(ParseFailureKind.ArgumentNull, "ArgumentNull_String", null, "input"); + result.SetFailure(ParseFailureKind.ArgumentNull, "ArgumentNull_String", null, nameof(input)); return false; } if (formats == null) { - result.SetFailure(ParseFailureKind.ArgumentNull, "ArgumentNull_String", null, "formats"); + result.SetFailure(ParseFailureKind.ArgumentNull, "ArgumentNull_String", null, nameof(formats)); return false; } diff --git a/src/mscorlib/src/System/Globalization/UmAlQuraCalendar.cs b/src/mscorlib/src/System/Globalization/UmAlQuraCalendar.cs index 94b235085e..06e7c7d75a 100644 --- a/src/mscorlib/src/System/Globalization/UmAlQuraCalendar.cs +++ b/src/mscorlib/src/System/Globalization/UmAlQuraCalendar.cs @@ -4,6 +4,7 @@ namespace System.Globalization { using System; + using System.Diagnostics; using System.Diagnostics.Contracts; @@ -338,9 +339,9 @@ namespace System.Globalization { =========================ConvertHijriToGregorian============================*/ static void ConvertHijriToGregorian(int HijriYear, int HijriMonth, int HijriDay, ref int yg, ref int mg, ref int dg) { - Contract.Assert( (HijriYear >= MinCalendarYear) && (HijriYear <= MaxCalendarYear), "Hijri year is out of range."); - Contract.Assert( HijriMonth >= 1, "Hijri month is out of range."); - Contract.Assert( HijriDay >= 1, "Hijri day is out of range."); + Debug.Assert( (HijriYear >= MinCalendarYear) && (HijriYear <= MaxCalendarYear), "Hijri year is out of range."); + Debug.Assert( HijriMonth >= 1, "Hijri month is out of range."); + Debug.Assert( HijriDay >= 1, "Hijri day is out of range."); int index, b, nDays = HijriDay-1; DateTime dt; @@ -392,7 +393,7 @@ namespace System.Globalization { static internal void CheckEraRange(int era) { if (era != CurrentEra && era != UmAlQuraEra) { - throw new ArgumentOutOfRangeException("era", Environment.GetResourceString("ArgumentOutOfRange_InvalidEraValue")); + throw new ArgumentOutOfRangeException(nameof(era), Environment.GetResourceString("ArgumentOutOfRange_InvalidEraValue")); } } @@ -400,7 +401,7 @@ namespace System.Globalization { CheckEraRange(era); if (year < MinCalendarYear || year > MaxCalendarYear) { throw new ArgumentOutOfRangeException( - "year", + nameof(year), String.Format( CultureInfo.CurrentCulture, Environment.GetResourceString("ArgumentOutOfRange_Range"), @@ -412,7 +413,7 @@ namespace System.Globalization { static internal void CheckYearMonthRange(int year, int month, int era) { CheckYearRange(year, era); if (month < 1 || month > 12) { - throw new ArgumentOutOfRangeException("month", Environment.GetResourceString("ArgumentOutOfRange_Month")); + throw new ArgumentOutOfRangeException(nameof(month), Environment.GetResourceString("ArgumentOutOfRange_Month")); } } @@ -430,7 +431,7 @@ namespace System.Globalization { TimeSpan ts; int yh1=0, mh1=0, dh1=0; - Contract.Assert((time.Ticks >= minDate.Ticks) && (time.Ticks <= maxDate.Ticks), "Gregorian date is out of range."); + Debug.Assert((time.Ticks >= minDate.Ticks) && (time.Ticks <= maxDate.Ticks), "Gregorian date is out of range."); // Find the index where we should start our search by quessing the Hijri year that we will be in HijriYearInfo. // A Hijri year is 354 or 355 days. Use 355 days so that we will search from a lower index. @@ -528,7 +529,7 @@ namespace System.Globalization { public override DateTime AddMonths(DateTime time, int months) { if (months < -120000 || months > 120000) { throw new ArgumentOutOfRangeException( - "months", + nameof(months), String.Format( CultureInfo.CurrentCulture, Environment.GetResourceString("ArgumentOutOfRange_Range"), @@ -631,7 +632,7 @@ namespace System.Globalization { { int days = 0, b; - Contract.Assert( (year >= MinCalendarYear) && (year <= MaxCalendarYear), "Hijri year is out of range."); + Debug.Assert( (year >= MinCalendarYear) && (year <= MaxCalendarYear), "Hijri year is out of range."); b = HijriYearInfo[year-MinCalendarYear].HijriMonthsLengthFlags; @@ -640,7 +641,7 @@ namespace System.Globalization { days += 29 + (b & 0x1); b = b >> 1; } - Contract.Assert((days == 354)||(days == 355), "Hijri year has to be 354 or 355 days."); + Debug.Assert((days == 354)||(days == 355), "Hijri year has to be 354 or 355 days."); return days; } @@ -712,7 +713,7 @@ namespace System.Globalization { int daysInMonth = GetDaysInMonth(year, month, era); if (day < 1 || day > daysInMonth) { throw new ArgumentOutOfRangeException( - "day", + nameof(day), String.Format( CultureInfo.CurrentCulture, Environment.GetResourceString("ArgumentOutOfRange_Day"), @@ -774,7 +775,7 @@ namespace System.Globalization { if (day < 1 || day > daysInMonth) { BCLDebug.Log("year = " + year + ", month = " + month + ", day = " + day); throw new ArgumentOutOfRangeException( - "day", + nameof(day), String.Format( CultureInfo.CurrentCulture, Environment.GetResourceString("ArgumentOutOfRange_Day"), @@ -806,7 +807,7 @@ DayInRang: set { if (value != 99 && (value < MinCalendarYear || value > MaxCalendarYear)) { throw new ArgumentOutOfRangeException( - "value", + nameof(value), String.Format( CultureInfo.CurrentCulture, Environment.GetResourceString("ArgumentOutOfRange_Range"), @@ -824,7 +825,7 @@ DayInRang: public override int ToFourDigitYear(int year) { if (year < 0) { - throw new ArgumentOutOfRangeException("year", + throw new ArgumentOutOfRangeException(nameof(year), Environment.GetResourceString("ArgumentOutOfRange_NeedNonNegNum")); } Contract.EndContractBlock(); @@ -835,7 +836,7 @@ DayInRang: if ((year < MinCalendarYear) || (year > MaxCalendarYear)) { throw new ArgumentOutOfRangeException( - "year", + nameof(year), String.Format( CultureInfo.CurrentCulture, Environment.GetResourceString("ArgumentOutOfRange_Range"), |