Initial release of mscorlib for nanoFramework

Signed-off-by: José Simões <jose.simoes@eclo.solutions>
This commit is contained in:
José Simões 2017-04-27 17:08:25 +01:00
Родитель 2cee8113c9
Коммит 8db304c6ca
178 изменённых файлов: 14176 добавлений и 0 удалений

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

@ -0,0 +1,33 @@
using System.Reflection;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
// General Information about an assembly is controlled through the following
// set of attributes. Change these attribute values to modify the information
// associated with an assembly.
[assembly: AssemblyTitle("CSharp.BlankApplication")]
[assembly: AssemblyDescription("")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("")]
[assembly: AssemblyProduct("CSharp.BlankApplication")]
[assembly: AssemblyCopyright("Copyright © ")]
[assembly: AssemblyTrademark("")]
[assembly: AssemblyCulture("")]
// Setting ComVisible to false makes the types in this assembly not visible
// to COM components. If you need to access a type in this assembly from
// COM, set the ComVisible attribute to true on that type.
[assembly: ComVisible(false)]
// Version information for an assembly consists of the following four values:
//
// Major Version
// Minor Version
// Build Number
// Revision
//
// You can specify all the values or you can default the Build and Revision Numbers
// by using the '*' as shown below:
// [assembly: AssemblyVersion("1.0.*")]
[assembly: AssemblyVersion("1.0.0.0")]
[assembly: AssemblyFileVersion("1.0.0.0")]

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

@ -0,0 +1,72 @@
//
// Copyright (c) 2017 The nanoFramework project contributors
// Portions Copyright (c) Microsoft Corporation. All rights reserved.
// See LICENSE file in the project root for full license information.
//
using System.Reflection;
using System.Threading;
using System.Runtime.CompilerServices;
namespace System
{
public sealed class AppDomain : MarshalByRefObject
{
[System.Reflection.FieldNoReflection]
private object m_appDomain;
private string m_friendlyName;
private AppDomain()
{
throw new Exception();
}
[MethodImplAttribute(MethodImplOptions.InternalCall)]
public extern static AppDomain CreateDomain(String friendlyName);
public Object CreateInstanceAndUnwrap(String assemblyName, String typeName)
{
Assembly assembly = Assembly.Load(assemblyName);
Type type = assembly.GetType(typeName);
ConstructorInfo ci = type.GetConstructor(new Type[0]);
object obj = ci.Invoke(null);
return obj;
}
public static AppDomain CurrentDomain
{
get { return Thread.GetDomain(); }
}
public String FriendlyName
{
get
{
return m_friendlyName;
}
}
public Assembly Load(String assemblyString)
{
bool fVersion = false;
int[] ver = new int[4];
string name = Assembly.ParseAssemblyName(assemblyString, ref fVersion, ref ver);
return LoadInternal(name, fVersion, ver[0], ver[1], ver[2], ver[3]);
}
[MethodImplAttribute(MethodImplOptions.InternalCall)]
public extern Assembly[] GetAssemblies();
[MethodImplAttribute(MethodImplOptions.InternalCall)]
private extern Assembly LoadInternal(String assemblyString, bool fVersion, int maj, int min, int build, int rev);
[MethodImplAttribute(MethodImplOptions.InternalCall)]
public static extern void Unload(AppDomain domain);
}
}

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

@ -0,0 +1,21 @@
namespace System
{
[Serializable()]
public class AppDomainUnloadedException : SystemException
{
public AppDomainUnloadedException()
: base()
{
}
public AppDomainUnloadedException(String message)
: base(message)
{
}
public AppDomainUnloadedException(String message, Exception innerException)
: base(message, innerException)
{
}
}
}

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

@ -0,0 +1,22 @@
namespace System
{
[Serializable()]
public class ApplicationException : Exception
{
public ApplicationException()
: base()
{
}
public ApplicationException(String message)
: base(message)
{
}
public ApplicationException(String message, Exception innerException)
: base(message, innerException)
{
}
}
}

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

@ -0,0 +1,72 @@
//
// Copyright (c) 2017 The nanoFramework project contributors
// Portions Copyright (c) Microsoft Corporation. All rights reserved.
// See LICENSE file in the project root for full license information.
//
namespace System
{
using System;
// The ArgumentException is thrown when an argument does not meet
// the contract of the method. Ideally it should give a meaningful error
// message describing what was wrong and which parameter is incorrect.
//
[Serializable()]
public class ArgumentException : SystemException
{
private String m_paramName;
// Creates a new ArgumentException with its message
// string set to the empty string.
public ArgumentException()
: base()
{
}
// Creates a new ArgumentException with its message
// string set to message.
//
public ArgumentException(String message)
: base(message)
{
}
public ArgumentException(String message, Exception innerException)
: base(message, innerException)
{
}
public ArgumentException(String message, String paramName, Exception innerException)
: base(message, innerException)
{
m_paramName = paramName;
}
public ArgumentException(String message, String paramName)
: base(message)
{
m_paramName = paramName;
}
public override String Message
{
get
{
String s = base.Message;
if (!((m_paramName == null) ||
(m_paramName.Length == 0)))
return s + "\n" + "Invalid argument " + "'" + m_paramName + "'";
else
return s;
}
}
public virtual String ParamName
{
get { return m_paramName; }
}
}
}

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

@ -0,0 +1,10 @@
namespace System
{
[Serializable]
public class ArgumentNullException : ArgumentException
{
public ArgumentNullException() : base() { }
public ArgumentNullException(string argument) : base(null, argument) { }
public ArgumentNullException(String paramName, String message) : base(message, paramName) { }
}
}

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

@ -0,0 +1,46 @@
//
// Copyright (c) 2017 The nanoFramework project contributors
// Portions Copyright (c) Microsoft Corporation. All rights reserved.
// See LICENSE file in the project root for full license information.
//
namespace System
{
using System;
// The ArgumentOutOfRangeException is thrown when an argument
// is outside the legal range for that argument. This may often be caused
// by
//
[Serializable()]
public class ArgumentOutOfRangeException : ArgumentException
{
// Creates a new ArgumentOutOfRangeException with its message
// string set to a default message explaining an argument was out of range.
public ArgumentOutOfRangeException()
: this(null)
{
}
public ArgumentOutOfRangeException(String paramName)
: base(null, paramName)
{
}
public ArgumentOutOfRangeException(String paramName, String message)
: base(message, paramName)
{
}
// We will not use this in the classlibs, but we'll provide it for
// anyone that's really interested so they don't have to stick a bunch
// of printf's in their code.
// Gets the value of the argument that caused the exception.
// Note - we don't set this anywhere in the class libraries in
// version 1, but it might come in handy for other developers who
// want to avoid sticking printf's in their code.
}
}

276
_mscorlib/System/Array.cs Normal file
Просмотреть файл

@ -0,0 +1,276 @@
//
// Copyright (c) 2017 The nanoFramework project contributors
// Portions Copyright (c) Microsoft Corporation. All rights reserved.
// See LICENSE file in the project root for full license information.
//
using System.Collections;
using System.Runtime.CompilerServices;
namespace System
{
[Serializable]
public abstract class Array : ICloneable, IList
{
[MethodImplAttribute(MethodImplOptions.InternalCall)]
public static extern Array CreateInstance(Type elementType, int length);
public static void Copy(Array sourceArray, Array destinationArray, int length)
{
Copy(sourceArray, 0, destinationArray, 0, length);
}
[MethodImplAttribute(MethodImplOptions.InternalCall)]
public static extern void Copy(Array sourceArray, int sourceIndex, Array destinationArray, int destinationIndex, int length);
[MethodImplAttribute(MethodImplOptions.InternalCall)]
public static extern void Clear(Array array, int index, int length);
public Object GetValue(int index)
{
return ((IList)this)[index];
}
public extern int Length
{
[MethodImplAttribute(MethodImplOptions.InternalCall)]
get;
}
int ICollection.Count
{
get
{
return this.Length;
}
}
public Object SyncRoot
{
get { return this; }
}
public bool IsReadOnly
{
get { return false; }
}
public bool IsFixedSize
{
get { return true; }
}
public bool IsSynchronized
{
get { return false; }
}
extern Object IList.this[int index]
{
[MethodImplAttribute(MethodImplOptions.InternalCall)]
get;
[MethodImplAttribute(MethodImplOptions.InternalCall)]
set;
}
int IList.Add(Object value)
{
throw new NotSupportedException();
}
bool IList.Contains(Object value)
{
return Array.IndexOf(this, value) >= 0;
}
void IList.Clear()
{
Array.Clear(this, 0, this.Length);
}
int IList.IndexOf(Object value)
{
return Array.IndexOf(this, value);
}
void IList.Insert(int index, Object value)
{
throw new NotSupportedException();
}
void IList.Remove(Object value)
{
throw new NotSupportedException();
}
void IList.RemoveAt(int index)
{
throw new NotSupportedException();
}
public Object Clone()
{
int length = this.Length;
Array destArray = Array.CreateInstance(this.GetType().GetElementType(), length);
Array.Copy(this, destArray, length);
return destArray;
}
public static int BinarySearch(Array array, Object value, IComparer comparer)
{
return BinarySearch(array, 0, array.Length, value, comparer);
}
public static int BinarySearch(Array array, int index, int length, Object value, IComparer comparer)
{
int lo = index;
int hi = index + length - 1;
while (lo <= hi)
{
int i = (lo + hi) >> 1;
int c;
if (comparer == null)
{
try
{
var elementComparer = array.GetValue(i) as IComparable;
c = elementComparer.CompareTo(value);
}
catch (Exception e)
{
throw new InvalidOperationException("Failed to compare two elements in the array", e);
}
}
else
{
c = comparer.Compare(array.GetValue(i), value);
}
if (c == 0) return i;
if (c < 0)
{
lo = i + 1;
}
else
{
hi = i - 1;
}
}
return ~lo;
}
public void CopyTo(Array array, int index)
{
Array.Copy(this, 0, array, index, this.Length);
}
public IEnumerator GetEnumerator()
{
return new SZArrayEnumerator(this);
}
public static int IndexOf(Array array, Object value)
{
return IndexOf(array, value, 0, array.Length);
}
public static int IndexOf(Array array, Object value, int startIndex)
{
return IndexOf(array, value, startIndex, array.Length - startIndex);
}
public static int IndexOf(Array array, Object value, int startIndex, int count)
{
// Try calling a quick native method to handle primitive types.
int retVal;
if (TrySZIndexOf(array, startIndex, count, value, out retVal))
{
return retVal;
}
int endIndex = startIndex + count;
for (int i = startIndex; i < endIndex; i++)
{
Object obj = array.GetValue(i);
if (Object.Equals(obj, value)) return i;
}
return -1;
}
[MethodImplAttribute(MethodImplOptions.InternalCall)]
private static extern bool TrySZIndexOf(Array sourceArray, int sourceIndex, int count, Object value, out int retVal);
// This is the underlying Enumerator for all of our array-based data structures (Array, ArrayList, Stack, and Queue)
// It supports enumerating over an array, a part of an array, and also will wrap around when the endIndex
// specified is larger than the size of the array (to support Queue's internal circular array)
internal class SZArrayEnumerator : IEnumerator
{
private Array _array;
private int _index;
private int _endIndex;
private int _startIndex;
private int _arrayLength;
internal SZArrayEnumerator(Array array)
{
_array = array;
_arrayLength = _array.Length;
_endIndex = _arrayLength;
_startIndex = 0;
_index = -1;
}
// By specifying the startIndex and endIndex, the enumerator will enumerate
// only a subset of the array. Note that startIndex is inclusive, while
// endIndex is NOT inclusive.
// For example, if array is of size 5,
// new SZArrayEnumerator(array, 0, 3) will enumerate through
// array[0], array[1], array[2]
//
// This also supports an array acting as a circular data structure.
// For example, if array is of size 5,
// new SZArrayEnumerator(array, 4, 7) will enumerate through
// array[4], array[0], array[1]
internal SZArrayEnumerator(Array array, int startIndex, int endIndex)
{
_array = array;
_arrayLength = _array.Length;
_endIndex = endIndex;
_startIndex = startIndex;
_index = _startIndex - 1;
}
public bool MoveNext()
{
if (_index < _endIndex)
{
_index++;
return (_index < _endIndex);
}
return false;
}
public Object Current
{
get
{
return _array.GetValue(_index % _arrayLength);
}
}
public void Reset()
{
_index = _startIndex - 1;
}
}
}
}

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

@ -0,0 +1,5 @@
using System;
using System.Reflection;
using System.Runtime.CompilerServices;
[assembly: CLSCompliant(true)]

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

@ -0,0 +1,12 @@
//
// Copyright (c) 2017 The nanoFramework project contributors
// Portions Copyright (c) Microsoft Corporation. All rights reserved.
// See LICENSE file in the project root for full license information.
//
namespace System
{
[Serializable()]
public delegate void AsyncCallback(IAsyncResult ar);
}

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

@ -0,0 +1,19 @@
//
// Copyright (c) 2017 The nanoFramework project contributors
// Portions Copyright (c) Microsoft Corporation. All rights reserved.
// See LICENSE file in the project root for full license information.
//
namespace System
{
using System;
using System.Reflection;
using System.Collections;
[Serializable, AttributeUsageAttribute(AttributeTargets.All, Inherited = true, AllowMultiple = false)] // Base class for all attributes
public abstract class Attribute
{
protected Attribute() { }
}
}

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

@ -0,0 +1,33 @@
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
// Copyright (c) Microsoft Corporation. All rights reserved.
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////namespace System
namespace System
{
using System;
/** Enum used to indicate all the elements of the
* VOS it is valid to attach this element to.
*/
[Flags, Serializable]
public enum AttributeTargets
{
Assembly = 0x0001,
Module = 0x0002,
Class = 0x0004,
Struct = 0x0008,
Enum = 0x0010,
Constructor = 0x0020,
Method = 0x0040,
Property = 0x0080,
Field = 0x0100,
Event = 0x0200,
Interface = 0x0400,
Parameter = 0x0800,
Delegate = 0x1000,
ReturnValue = 0x2000,
All = Assembly | Module | Class | Struct | Enum | Constructor |
Method | Property | Field | Event | Interface | Parameter | Delegate | ReturnValue,
}
}

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

@ -0,0 +1,45 @@
//
// Copyright (c) 2017 The nanoFramework project contributors
// Portions Copyright (c) Microsoft Corporation. All rights reserved.
// See LICENSE file in the project root for full license information.
//
namespace System
{
using System.Reflection;
/* By default, attributes are inherited and multiple attributes are not allowed */
[AttributeUsage(AttributeTargets.Class, Inherited = true), Serializable()]
public sealed class AttributeUsageAttribute : Attribute
{
internal AttributeTargets m_attributeTarget = AttributeTargets.All; // Defaults to all
internal bool m_allowMultiple = false; // Defaults to false
internal bool m_inherited = true; // Defaults to true
internal static AttributeUsageAttribute Default = new AttributeUsageAttribute(AttributeTargets.All);
//Constructors
public AttributeUsageAttribute(AttributeTargets validOn)
{
m_attributeTarget = validOn;
}
//Properties
public AttributeTargets ValidOn
{
get { return m_attributeTarget; }
}
public bool AllowMultiple
{
get { return m_allowMultiple; }
set { m_allowMultiple = value; }
}
public bool Inherited
{
get { return m_inherited; }
set { m_inherited = value; }
}
}
}

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

@ -0,0 +1,239 @@
//
// Copyright (c) 2017 The nanoFramework project contributors
// Portions Copyright (c) Microsoft Corporation. All rights reserved.
// See LICENSE file in the project root for full license information.
//
using System;
using System.Runtime.CompilerServices;
namespace System
{
public static class BitConverter
{
/// <summary>
/// Indicates the byte order ("endianess") in which data is stored in this computer architecture.
/// </summary>
extern public static bool IsLittleEndian
{
[MethodImplAttribute(MethodImplOptions.InternalCall)]
get;
}
/// <summary>
/// Converts the specified double-precision floating point number to a 64-bit signed integer.
/// </summary>
/// <param name="value">The number to convert.</param>
/// <returns></returns>
[MethodImplAttribute(MethodImplOptions.InternalCall)]
extern public static long DoubleToInt64Bits(double value);
/// <summary>
/// Returns the specified Boolean value as an array of bytes.
/// </summary>
/// <param name="value">A Boolean value.</param>
/// <returns>An array of bytes with length 1.</returns>
[MethodImplAttribute(MethodImplOptions.InternalCall)]
extern public static byte[] GetBytes(bool value);
/// <summary>
/// Returns the specified Unicode character value as an array of bytes.
/// </summary>
/// <param name="value">A character to convert.</param>
/// <returns>An array of bytes with length 2.</returns>
[MethodImplAttribute(MethodImplOptions.InternalCall)]
extern public static byte[] GetBytes(char value);
/// <summary>
/// Returns the specified double-precision floating point value as an array of bytes.
/// </summary>
/// <param name="value">The number to convert.</param>
/// <returns>An array of bytes with length 8.</returns>
[MethodImplAttribute(MethodImplOptions.InternalCall)]
extern public static byte[] GetBytes(double value);
/// <summary>
/// Returns the specified single-precision floating point value as an array of bytes.
/// </summary>
/// <param name="value">The number to convert.</param>
/// <returns>An array of bytes with length 4.</returns>
[MethodImplAttribute(MethodImplOptions.InternalCall)]
extern public static byte[] GetBytes(float value);
/// <summary>
/// Returns the specified 32-bit signed integer value as an array of bytes.
/// </summary>
/// <param name="value">The number to convert.</param>
/// <returns>An array of bytes with length 4.</returns>
[MethodImplAttribute(MethodImplOptions.InternalCall)]
extern public static byte[] GetBytes(int value);
/// <summary>
/// Returns the specified 64-bit signed integer value as an array of bytes.
/// </summary>
/// <param name="value">The number to convert.</param>
/// <returns>An array of bytes with length 8.</returns>
[MethodImplAttribute(MethodImplOptions.InternalCall)]
extern public static byte[] GetBytes(long value);
/// <summary>
/// Returns the specified 16-bit signed integer value as an array of bytes.
/// </summary>
/// <param name="value">The number to convert.</param>
/// <returns>An array of bytes with length 2.</returns>
[MethodImplAttribute(MethodImplOptions.InternalCall)]
extern public static byte[] GetBytes(short value);
/// <summary>
/// Returns the specified 32-bit unsigned integer value as an array of bytes.
/// </summary>
/// <param name="value">The number to convert.</param>
/// <returns>An array of bytes with length 4.</returns>
[MethodImplAttribute(MethodImplOptions.InternalCall)]
extern public static byte[] GetBytes(uint value);
/// <summary>
/// Returns the specified 64-bit unsigned integer value as an array of bytes.
/// </summary>
/// <param name="value">The number to convert.</param>
/// <returns>An array of bytes with length 8.</returns>
[MethodImplAttribute(MethodImplOptions.InternalCall)]
extern public static byte[] GetBytes(ulong value);
/// <summary>
/// Returns the specified 16-bit unsigned integer value as an array of bytes.
/// </summary>
/// <param name="value">The number to convert.</param>
/// <returns>An array of bytes with length 2.</returns>
[MethodImplAttribute(MethodImplOptions.InternalCall)]
extern public static byte[] GetBytes(ushort value);
/// <summary>
/// Converts the specified 64-bit signed integer to a double-precision floating point number.
/// </summary>
/// <param name="value">The number to convert.</param>
/// <returns>A double-precision floating point number whose value is equivalent to value.</returns>
[MethodImplAttribute(MethodImplOptions.InternalCall)]
extern public static double Int64BitsToDouble(long value);
/// <summary>
/// Returns a Boolean value converted from one byte at a specified position in a byte array.
/// </summary>
/// <param name="value">An array of bytes.</param>
/// <param name="startIndex">The starting position within value.</param>
/// <returns>true if the byte at startIndex in value is nonzero; otherwise, false.</returns>
[MethodImplAttribute(MethodImplOptions.InternalCall)]
extern public static bool ToBoolean(byte[] value, int startIndex);
/// <summary>
/// Returns a Unicode character converted from two bytes at a specified position in a byte array.
/// </summary>
/// <param name="value">An array of bytes.</param>
/// <param name="startIndex">The starting position within value.</param>
/// <returns>A character formed by two bytes beginning at startIndex.</returns>
[MethodImplAttribute(MethodImplOptions.InternalCall)]
extern public static char ToChar(byte[] value, int startIndex);
/// <summary>
/// Returns a double-precision floating point number converted from eight bytes at a specified position in a byte array.
/// </summary>
/// <param name="value">An array of bytes.</param>
/// <param name="startIndex">The starting position within value.</param>
/// <returns>A double precision floating point number formed by eight bytes beginning at startIndex.</returns>
[MethodImplAttribute(MethodImplOptions.InternalCall)]
extern public static double ToDouble(byte[] value, int startIndex);
/// <summary>
/// Returns a 16-bit signed integer converted from two bytes at a specified position in a byte array.
/// </summary>
/// <param name="value">An array of bytes.</param>
/// <param name="startIndex">The starting position within value.</param>
/// <returns>A 16-bit signed integer formed by two bytes beginning at startIndex.</returns>
[MethodImplAttribute(MethodImplOptions.InternalCall)]
extern public static short ToInt16(byte[] value, int startIndex);
/// <summary>
/// Returns a 32-bit signed integer converted from four bytes at a specified position in a byte array.
/// </summary>
/// <param name="value">An array of bytes.</param>
/// <param name="startIndex">The starting position within value.</param>
/// <returns>A 32-bit signed integer formed by four bytes beginning at startIndex.</returns>
[MethodImplAttribute(MethodImplOptions.InternalCall)]
extern public static int ToInt32(byte[] value, int startIndex);
/// <summary>
/// Returns a 64-bit signed integer converted from eight bytes at a specified position in a byte array.
/// </summary>
/// <param name="value">An array of bytes.</param>
/// <param name="startIndex">The starting position within value.</param>
/// <returns>A 64-bit signed integer formed by eight bytes beginning at startIndex.</returns>
[MethodImplAttribute(MethodImplOptions.InternalCall)]
extern public static long ToInt64(byte[] value, int startIndex);
/// <summary>
/// Returns a single-precision floating point number converted from four bytes at a specified position in a byte array.
/// </summary>
/// <param name="value">An array of bytes.</param>
/// <param name="startIndex">The starting position within value.</param>
/// <returns>A single-precision floating point number formed by four bytes beginning at startIndex.</returns>
[MethodImplAttribute(MethodImplOptions.InternalCall)]
extern public static float ToSingle(byte[] value, int startIndex);
/// <summary>
/// Converts the numeric value of each element of a specified array of bytes to its equivalent hexadecimal string representation.
/// </summary>
/// <param name="value">An array of bytes.</param>
/// <returns>A String of hexadecimal pairs separated by hyphens, where each pair represents the corresponding element in value; for example, "7F-2C-4A".</returns>
[MethodImplAttribute(MethodImplOptions.InternalCall)]
extern public static string ToString(byte[] value);
/// <summary>
/// Converts the numeric value of each element of a specified subarray of bytes to its equivalent hexadecimal string representation.
/// </summary>
/// <param name="value">An array of bytes.</param>
/// <param name="startIndex">The starting position within value.</param>
/// <returns>A String of hexadecimal pairs separated by hyphens, where each pair represents the corresponding element in a subarray of value; for example, "7F-2C-4A".</returns>
[MethodImplAttribute(MethodImplOptions.InternalCall)]
extern public static string ToString(byte[] value, int startIndex);
/// <summary>
/// Converts the numeric value of each element of a specified subarray of bytes to its equivalent hexadecimal string representation.
/// </summary>
/// <param name="value">An array of bytes.</param>
/// <param name="startIndex">The starting position within value.</param>
/// <param name="length">The number of array elements in value to convert.</param>
/// <returns>A String of hexadecimal pairs separated by hyphens, where each pair represents the corresponding element in a subarray of value; for example, "7F-2C-4A".</returns>
[MethodImplAttribute(MethodImplOptions.InternalCall)]
extern public static string ToString(byte[] value, int startIndex, int length);
/// <summary>
/// Returns a 16-bit unsigned integer converted from two bytes at a specified position in a byte array.
/// </summary>
/// <param name="value">An array of bytes.</param>
/// <param name="startIndex">The starting position within value.</param>
/// <returns>A 16-bit unsigned integer formed by two bytes beginning at startIndex.</returns>
[CLSCompliant(false)]
[MethodImplAttribute(MethodImplOptions.InternalCall)]
extern public static ushort ToUInt16(byte[] value, int startIndex);
/// <summary>
/// Returns a 32-bit unsigned integer converted from two bytes at a specified position in a byte array.
/// </summary>
/// <param name="value">The array of bytes.</param>
/// <param name="startIndex">The starting position within value.</param>
/// <returns>A 32-bit unsigned integer formed by two bytes beginning at startIndex.</returns>
[CLSCompliant(false)]
[MethodImplAttribute(MethodImplOptions.InternalCall)]
extern public static uint ToUInt32(byte[] value, int startIndex);
/// <summary>
/// Returns a 64-bit unsigned integer converted from two bytes at a specified position in a byte array.
/// </summary>
/// <param name="value">The array of bytes.</param>
/// <param name="startIndex">The starting position within value.</param>
/// <returns>A 64-bit unsigned integer formed by two bytes beginning at startIndex.</returns>
[CLSCompliant(false)]
[MethodImplAttribute(MethodImplOptions.InternalCall)]
extern public static ulong ToUInt64(byte[] value, int startIndex);
}
}

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

@ -0,0 +1,31 @@
//
// Copyright (c) 2017 The nanoFramework project contributors
// Portions Copyright (c) Microsoft Corporation. All rights reserved.
// See LICENSE file in the project root for full license information.
//
namespace System
{
using System;
using System.Runtime.CompilerServices;
/**
* A place holder class for boolean.
* @author Jay Roxe (jroxe)
* @version
*/
[Serializable]
public struct Boolean
{
public static readonly string FalseString = "False";
public static readonly string TrueString = "True";
private bool m_value;
public override String ToString()
{
return (m_value) ? TrueString : FalseString;
}
}
}

55
_mscorlib/System/Byte.cs Normal file
Просмотреть файл

@ -0,0 +1,55 @@
//
// Copyright (c) 2017 The nanoFramework project contributors
// Portions Copyright (c) Microsoft Corporation. All rights reserved.
// See LICENSE file in the project root for full license information.
//
namespace System
{
using System.Globalization;
using System;
using System.Runtime.CompilerServices;
/**
* A place holder class for signed bytes.
* @author Jay Roxe (jroxe)
* @version
*/
[Serializable]
public struct Byte
{
private byte m_value;
/**
* The maximum value that a <code>Byte</code> may represent: 127.
*/
public const byte MaxValue = (byte)0xFF;
/**
* The minimum value that a <code>Byte</code> may represent: -128.
*/
public const byte MinValue = 0;
public override String ToString()
{
return Number.Format(m_value, true, "G", NumberFormatInfo.CurrentInfo);
}
public String ToString(String format)
{
return Number.Format(m_value, true, format, NumberFormatInfo.CurrentInfo);
}
[CLSCompliant(false)]
public static byte Parse(String s)
{
if (s == null)
{
throw new ArgumentNullException();
}
return Convert.ToByte(s);
}
}
}

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

@ -0,0 +1,27 @@
//
// Copyright (c) 2017 The nanoFramework project contributors
// Portions Copyright (c) Microsoft Corporation. All rights reserved.
// See LICENSE file in the project root for full license information.
//
namespace System
{
[AttributeUsage(AttributeTargets.All, Inherited = true, AllowMultiple = false), Serializable]
public sealed class CLSCompliantAttribute : Attribute
{
private bool m_compliant;
public CLSCompliantAttribute(bool isCompliant)
{
m_compliant = isCompliant;
}
public bool IsCompliant
{
get
{
return m_compliant;
}
}
}
}

58
_mscorlib/System/Char.cs Normal file
Просмотреть файл

@ -0,0 +1,58 @@
//
// Copyright (c) 2017 The nanoFramework project contributors
// Portions Copyright (c) Microsoft Corporation. All rights reserved.
// See LICENSE file in the project root for full license information.
//
namespace System
{
using System;
using System.Runtime.CompilerServices;
[Serializable]
public struct Char
{
//
// Member Variables
//
internal char m_value;
//
// Public Constants
//
/**
* The maximum character value.
*/
public const char MaxValue = (char)0xFFFF;
/**
* The minimum character value.
*/
public const char MinValue = (char)0x00;
public override String ToString()
{
return new String(m_value, 1);
}
public char ToLower()
{
if('A' <= m_value && m_value <= 'Z')
{
return (char)(m_value - ('A' - 'a'));
}
return m_value;
}
public char ToUpper()
{
if('a' <= m_value && m_value <= 'z')
{
return (char)(m_value + ('A' - 'a'));
}
return m_value;
}
}
}

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

@ -0,0 +1,166 @@
//
// Copyright (c) 2017 The nanoFramework project contributors
// Portions Copyright (c) Microsoft Corporation. All rights reserved.
// See LICENSE file in the project root for full license information.
//
using System.Diagnostics;
using System.Runtime.CompilerServices;
namespace System.Collections
{
[Serializable()]
[DebuggerDisplay("Count = {Count}")]
public class ArrayList : IList, ICloneable
{
private Object[] _items;
private int _size;
// Keep in-sync with c_DefaultCapacity in CLR_RT_HeapBlock_ArrayList in TinyCLR_Runtime__HeapBlock.h
private const int _defaultCapacity = 4;
public ArrayList()
{
_items = new Object[_defaultCapacity];
}
public virtual int Capacity
{
get { return _items.Length; }
set
{
SetCapacity(value);
}
}
[MethodImplAttribute(MethodImplOptions.InternalCall)]
private extern void SetCapacity(int capacity);
public virtual int Count
{
get { return _size; }
}
public virtual bool IsFixedSize
{
get { return false; }
}
public virtual bool IsReadOnly
{
get { return false; }
}
public virtual bool IsSynchronized
{
get { return false; }
}
public virtual Object SyncRoot
{
get { return this; }
}
public extern virtual Object this[int index]
{
[MethodImplAttribute(MethodImplOptions.InternalCall)]
get;
[MethodImplAttribute(MethodImplOptions.InternalCall)]
set;
}
[MethodImplAttribute(MethodImplOptions.InternalCall)]
public extern virtual int Add(Object value);
public virtual int BinarySearch(Object value, IComparer comparer)
{
return Array.BinarySearch(_items, 0, _size, value, comparer);
}
[MethodImplAttribute(MethodImplOptions.InternalCall)]
public extern virtual void Clear();
public virtual Object Clone()
{
ArrayList la = new ArrayList();
if (_size > _defaultCapacity)
{
// only re-allocate a new array if the size isn't what we need.
// otherwise, the one allocated in the constructor will be just fine
la._items = new Object[_size];
}
la._size = _size;
Array.Copy(_items, 0, la._items, 0, _size);
return la;
}
public virtual bool Contains(Object item)
{
return Array.IndexOf(_items, item, 0, _size) >= 0;
}
public virtual void CopyTo(Array array)
{
CopyTo(array, 0);
}
public virtual void CopyTo(Array array, int arrayIndex)
{
Array.Copy(_items, 0, array, arrayIndex, _size);
}
public virtual IEnumerator GetEnumerator()
{
return new Array.SZArrayEnumerator(_items, 0, _size);
}
public virtual int IndexOf(Object value)
{
return Array.IndexOf(_items, value, 0, _size);
}
public virtual int IndexOf(Object value, int startIndex)
{
return Array.IndexOf(_items, value, startIndex, _size - startIndex);
}
public virtual int IndexOf(Object value, int startIndex, int count)
{
return Array.IndexOf(_items, value, startIndex, count);
}
[MethodImplAttribute(MethodImplOptions.InternalCall)]
public extern virtual void Insert(int index, Object value);
public virtual void Remove(Object obj)
{
int index = Array.IndexOf(_items, obj, 0, _size);
if (index >= 0)
{
RemoveAt(index);
}
}
[MethodImplAttribute(MethodImplOptions.InternalCall)]
public extern virtual void RemoveAt(int index);
public virtual Object[] ToArray()
{
return (Object[])ToArray(typeof(object));
}
public virtual Array ToArray(Type type)
{
Array array = Array.CreateInstance(type, _size);
Array.Copy(_items, 0, array, 0, _size);
return array;
}
}
}

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

@ -0,0 +1,22 @@
//
// Copyright (c) 2017 The nanoFramework project contributors
// Portions Copyright (c) Microsoft Corporation. All rights reserved.
// See LICENSE file in the project root for full license information.
//
using System;
namespace System.Collections
{
public class DictionaryEntry
{
public Object Key;
public Object Value;
public DictionaryEntry(Object key, Object value)
{
Key = key;
Value = value;
}
}
}

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

@ -0,0 +1,536 @@
//
// Copyright (c) 2017 The nanoFramework project contributors
// Portions Copyright (c) Microsoft Corporation. All rights reserved.
// See LICENSE file in the project root for full license information.
//
using System;
namespace System.Collections
{
/// <summary>
/// HashTable is an Associative Container.
/// Created in March 2010.
/// by Eric Harlow.
/// </summary>
public class Hashtable : ICloneable, IDictionary
{
Entry[] _buckets;
int _numberOfBuckets;
int _count;
int _loadFactor;
int _maxLoadFactor;
double _growthFactor;
const int _defaultCapacity = 4;
const int _defaultLoadFactor = 2;
/// <summary>
/// Initializes a new, empty instance of the Hashtable class using the default initial capacity and load factor.
/// </summary>
public Hashtable()
{
InitializeHashTable(_defaultCapacity, _defaultLoadFactor);
}
/// <summary>
/// Initializes a new, empty instance of the Hashtable class using the specified initial capacity,
/// and the default load factor.
/// </summary>
/// <param name="capacity">The initial capacity of the HashTable</param>
public Hashtable(int capacity)
{
InitializeHashTable(capacity, _defaultLoadFactor);
}
/// <summary>
/// Initializes a new, empty instance of the Hashtable class using the specified initial capacity,
/// load factor.
/// </summary>
/// <param name="capacity">The initial capacity of the HashTable</param>
/// <param name="maxLoadFactor">The load factor to cause a rehash</param>
public Hashtable(int capacity, int maxLoadFactor)
{
InitializeHashTable(capacity, maxLoadFactor);
}
//initialize attributes
private void InitializeHashTable(int capacity, int maxLoadFactor)
{
_buckets = new Entry[capacity];
_numberOfBuckets = capacity;
_maxLoadFactor = maxLoadFactor;
_growthFactor = 2;
}
/// <summary>
/// MaxLoadFactor Property is the value used to trigger a rehash.
/// Default value is 2.
/// A higher number can decrease lookup performance for large collections.
/// While a value of 1 maintains a constant time complexity at the cost of increased memory requirements.
/// </summary>
public int MaxLoadFactor
{
get { return _maxLoadFactor; }
set { _maxLoadFactor = value; }
}
/// <summary>
/// GrowthFactor Property is a multiplier to increase the HashTable size by during a rehash.
/// Default value is 2.
/// </summary>
public double GrowthFactor
{
get { return _growthFactor; }
set { _growthFactor = value; }
}
//adding for internal purposes
private void Add(ref Entry[] buckets, object key, object value, bool overwrite)
{
int whichBucket = Hash(key, _numberOfBuckets);
Entry match = EntryForKey(key, buckets[whichBucket]);
if (match != null && overwrite)
{ //i.e. already exists in table
match.value = value;
return;
}
else if ((match != null && !overwrite))
{
throw new ArgumentException("key exists");
}
else
{ // insert at front
Entry newOne = new Entry(key, value, ref buckets[whichBucket]);
buckets[whichBucket] = newOne;
_count++;
}
_loadFactor = _count / _numberOfBuckets;
}
// Hash function.
private int Hash(object key, int numOfBuckets)
{
int hashcode = key.GetHashCode();
if (hashcode < 0) // don't know how to mod with a negative number
hashcode = hashcode * -1;
return hashcode % numOfBuckets;
}
//looks up value in bucket
private Entry EntryForKey(object key, Entry head)
{
for (Entry cur = head; cur != null; cur = cur.next)
if (cur.key.Equals(key)) return cur;
return null;
}
//Rehashes the table to reduce the load factor
private void Rehash(int newSize)
{
Entry[] newTable = new Entry[newSize];
_numberOfBuckets = newSize;
_count = 0;
for (int i = 0; i < _buckets.Length; i++)
{
if (_buckets[i] != null)
{
for (Entry cur = _buckets[i]; cur != null; cur = cur.next)
Add(ref newTable, cur.key, cur.value, false);
}
}
_buckets = newTable;
}
//implementation for KeyCollection and ValueCollection copyTo method
private void CopyToCollection(Array array, int index, EnumeratorType type)
{
if (index < 0 && index > _numberOfBuckets)
throw new IndexOutOfRangeException("index");
int j = 0;
int len = array.Length;
for (int i = index; i < _numberOfBuckets; i++)
{
for (Entry cur = _buckets[i]; cur != null && j < len; cur = cur.next)
{
if (type == EnumeratorType.KEY)
((IList)array)[j] = cur.key;
else
((IList)array)[j] = cur.value;
j++;
}
}
}
#region ICloneable Members
//shallow copy
public object Clone()
{
Hashtable ht = new Hashtable();
ht.InitializeHashTable(_numberOfBuckets, _maxLoadFactor);
ht._count = _count;
ht._loadFactor = _loadFactor;
Array.Copy(_buckets, ht._buckets, _numberOfBuckets);
return ht;
}
#endregion ICloneable Members
#region IEnumerable Members
public IEnumerator GetEnumerator()
{
return new HashtableEnumerator(this, EnumeratorType.DE);
}
#endregion IEnumerable Members
#region ICollection Members
public int Count
{
get { return _count; }
}
public bool IsSynchronized
{
get { return false; }
}
public object SyncRoot
{
get { return this; }
}
public void CopyTo(Array array, int index)
{
if (index < 0 && index > _buckets.Length)
throw new IndexOutOfRangeException("index");
int j = 0;
int len = array.Length;
for (int i = index; i < _buckets.Length; i++)
{
for (Entry cur = _buckets[i]; cur != null && j<len; cur = cur.next)
{
((IList)array)[j] = new DictionaryEntry(cur.key, cur.value);
j++;
}
}
}
#endregion ICollection Members
#region IDictionary Members
public bool IsReadOnly
{
get { return false; }
}
public bool IsFixedSize
{
get { return false; }
}
public ICollection Keys
{
get
{
return new KeyCollection(this);
}
}
public ICollection Values
{
get
{
return new ValueCollection(this);
}
}
public object this[object key]
{
get
{
if (key == null) throw new ArgumentNullException("key is null");
int whichBucket = Hash(key, _numberOfBuckets);
Entry match = EntryForKey(key, _buckets[whichBucket]);
if (match != null)
return match.value;
return null;
}
set
{
if (key == null) throw new ArgumentNullException("key is null");
Add(ref _buckets ,key,value,true);
if (_loadFactor >= _maxLoadFactor)
Rehash((int)(_numberOfBuckets * _growthFactor));
}
}
public void Add(object key, object value)
{
if (key == null) throw new ArgumentNullException("key is null");
Add(ref _buckets, key, value, false);
if (_loadFactor >= _maxLoadFactor)
Rehash((int)(_numberOfBuckets * _growthFactor));
}
public void Clear()
{
_buckets = new Entry[_defaultCapacity];
_numberOfBuckets = _defaultCapacity;
_loadFactor = 0;
_count = 0;
}
public bool Contains(object key)
{
if (key == null) throw new ArgumentNullException("key is null");
int whichBucket = Hash(key, _numberOfBuckets);
Entry match = EntryForKey(key, _buckets[whichBucket]);
if (match != null)
return true;
return false;
}
public void Remove(object key)
{
if (key == null) throw new ArgumentNullException("key is null");
int whichBucket = Hash(key, _numberOfBuckets);
Entry match = EntryForKey(key, _buckets[whichBucket]);
//does entry exist?
if (match == null)
return;
//is entry at front?
if (_buckets[whichBucket] == match)
{
_buckets[whichBucket] = match.next;
_count--;
return;
}
//handle entry in middle and at the end
for (Entry cur = _buckets[whichBucket]; cur != null; cur = cur.next)
{
if (cur.next == match)
{
cur.next = match.next;
_count--;
return;
}
}
}
#endregion IDictionary Members
private class Entry
{
public Object key;
public Object value;
public Entry next;
public Entry(object key, object value, ref Entry n)
{
this.key = key;
this.value = value;
this.next = n;
}
}
private class HashtableEnumerator : IEnumerator
{
Hashtable ht;
Entry temp;
Int32 index = -1;
EnumeratorType returnType;
public HashtableEnumerator(Hashtable hashtable, EnumeratorType type)
{
ht = hashtable;
returnType = type;
}
// Return the current item.
public Object Current
{
get
{
switch (returnType)
{
case EnumeratorType.DE:
return new DictionaryEntry(temp.key, temp.value);
case EnumeratorType.KEY:
return temp.key;
case EnumeratorType.VALUE:
return temp.value;
default:
break;
}
return new DictionaryEntry(temp.key, temp.value);
}
}
// Advance to the next item.
public Boolean MoveNext()
{
startLoop:
//iterate index or list
if (temp == null)
{
index++;
if (index < ht._numberOfBuckets)
temp = ht._buckets[index];
else
return false;
}
else
temp = temp.next;
//null check
if (temp == null)
goto startLoop;
return true;
}
// Reset the index to restart the enumeration.
public void Reset()
{
index = -1;
}
}
// EnumeratorType - Enum that describes which object the Enumerator's Current property will return.
private enum EnumeratorType
{
// DictionaryEntry object.
DE,
// Key object.
KEY,
// Value object.
VALUE
}
private class KeyCollection : ICollection
{
Hashtable ht;
public KeyCollection(Hashtable hashtable)
{
ht = hashtable;
}
#region ICollection Members
public int Count
{
get
{
return ht._count;
}
}
public bool IsSynchronized
{
get
{
return ht.IsSynchronized;
}
}
public object SyncRoot
{
get
{
return ht.SyncRoot;
}
}
public void CopyTo(Array array, int index)
{
ht.CopyToCollection(array, index, EnumeratorType.KEY);
}
#endregion
#region IEnumerable Members
public IEnumerator GetEnumerator()
{
return new HashtableEnumerator(ht, EnumeratorType.KEY);
}
#endregion
}
private class ValueCollection : ICollection
{
Hashtable ht;
public ValueCollection(Hashtable hashtable)
{
ht = hashtable;
}
#region ICollection Members
public int Count
{
get
{
return ht._count;
}
}
public bool IsSynchronized
{
get
{
return ht.IsSynchronized;
}
}
public object SyncRoot
{
get
{
return ht.SyncRoot;
}
}
public void CopyTo(Array array, int index)
{
ht.CopyToCollection(array, index, EnumeratorType.VALUE);
}
#endregion
#region IEnumerable Members
public IEnumerator GetEnumerator()
{
return new HashtableEnumerator(ht, EnumeratorType.VALUE);
}
#endregion
}
}
}

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

@ -0,0 +1,41 @@
//
// Copyright (c) 2017 The nanoFramework project contributors
// Portions Copyright (c) Microsoft Corporation. All rights reserved.
// See LICENSE file in the project root for full license information.
//
namespace System.Collections
{
using System;
/**
* Base interface for all collections, defining enumerators, size, and
* synchronization methods.
*/
public interface ICollection : IEnumerable
{
// Interfaces are not serialable
/**
* CopyTo copies a collection into an Array, starting at a particular
* index into the array.
*
* @param array array to copy collection into
* @param index Index into <var>array</var>.
* @exception ArgumentNullException if <var>array</var> is null.
*/
void CopyTo(Array array, int index);
/**
* Number of items in the collections.
*/
int Count
{ get; }
Object SyncRoot
{ get; }
bool IsSynchronized
{ get; }
}
}

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

@ -0,0 +1,39 @@
//
// Copyright (c) 2017 The nanoFramework project contributors
// Portions Copyright (c) Microsoft Corporation. All rights reserved.
// See LICENSE file in the project root for full license information.
//
namespace System.Collections
{
using System;
/**
* The IComparer interface implements a method that compares two objects. It is
* used in conjunction with the <i>Sort</i> and <i>BinarySearch</i> methods on
* the <i>Array</i> and <i>List</i> classes.
*
* @see System.Array
* @see System.Collections.List
*
* @author Anders Hejlsberg
* @version 1.00 8/13/98
*/
// Interfaces are not serializable
public interface IComparer
{
/**
* Compares two objects. An implementation of this method must return a
* value less than zero if x is less than y, zero if x is equal to y, or a
* value greater than zero if x is greater than y.
*
* @param x The first object to compare.
* @param y The second object to compare.
* @return A value less than zero if x < y, zero if x = y, or a value
* greater than zero if x > y.
*/
int Compare(Object x, Object y);
}
}

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

@ -0,0 +1,51 @@
//
// Copyright (c) 2017 The nanoFramework project contributors
// Portions Copyright (c) Microsoft Corporation. All rights reserved.
// See LICENSE file in the project root for full license information.
//
using System;
namespace System.Collections
{
public interface IDictionary : ICollection
{
bool IsReadOnly { get; }
bool IsFixedSize { get; }
ICollection Keys { get; }
ICollection Values { get; }
/// <summary>
/// The Item property provides methods to read and edit entries in the Dictionary.
/// </summary>
/// <param name="key"></param>
/// <returns></returns>
object this[object key]{ get; set; }
/// <summary>
/// Adds a key/value pair to the dictionary. The exact position in the dictionary is
/// implementation-dependent. A hashtable will always hash the same key to the same position.
/// This position may be different if a different hash function is used.
/// </summary>
/// <param name="key"></param>
void Add(object key, object value);
/// <summary>
/// Removes all items from the dictionary.
/// </summary>
void Clear();
/// <summary>
/// Returns whether the dictionary contains a particular item.
/// </summary>
/// <param name="key"></param>
/// <returns>True if found otherwise false</returns>
bool Contains(object key);
/// <summary>
/// Removes an item from the dictionary.
/// </summary>
/// <param name="key"></param>
void Remove(object key);
}
}

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

@ -0,0 +1,25 @@
//
// Copyright (c) 2017 The nanoFramework project contributors
// Portions Copyright (c) Microsoft Corporation. All rights reserved.
// See LICENSE file in the project root for full license information.
//
namespace System.Collections
{
using System;
/**
* Implement this interface if you need to support VB's foreach semantics.
* Also, COM classes that support an enumerator will also implement this interface.
*/
public interface IEnumerable
{
// Interfaces are not serializable
/**
* Returns an IEnumerator for this enumerable Object. The enumerator provides
* a simple way to access all the contents of a collection.
*/
IEnumerator GetEnumerator();
}
}

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

@ -0,0 +1,63 @@
//
// Copyright (c) 2017 The nanoFramework project contributors
// Portions Copyright (c) Microsoft Corporation. All rights reserved.
// See LICENSE file in the project root for full license information.
//
namespace System.Collections
{
using System;
/**
* Base interface for all enumerators, providing a simple approach
* to iterating over a collection.
*/
public interface IEnumerator
{
// Interfaces are not serializable
/**
* Advances the enumerator to the next element of the enumeration and
* returns a boolean indicating whether an element is available. Upon
* creation, an enumerator is conceptually positioned before the first
* element of the enumeration, and the first call to <code>MoveNext</code>
* brings the first element of the enumeration into view.
*
* @return true if the enumerator was succesfully advanced to the next
* element, false if the enumeration has been completed.
* @exception InvalidOperationException Thrown if the underlying set of objects
* has been modified since this enumerator was created.
*/
bool MoveNext();
/**
* Returns the current element of the enumeration. The returned value is
* undefined before the first call to <code>MoveNext</code> and following a
* call to <code>MoveNext</code> that returned false. Multiple calls to
* <code>GetCurrent</code> with no intervening calls to <code>MoveNext</code>
* will return the same object.
*
* @return The current element of the enumeration.
* @exception InvalidOperationException Thrown if the underlying set of objects
* has been modified since this enumerator was created, or if the Enumerator
* is positioned before or after the valid range.
*/
Object Current
{
get;
}
/**
* Resets the enumerator to the beginning of the enumeration, starting over.
* The preferred behavior for Reset is to return the exact same enumeration.
* This means if you modify the underlying collection then call Reset, your
* IEnumerator will be invalid, just as it would have been if you had called
* MoveNext or Current.
*
* @exception InvalidOperationException Thrown if the underlying set of
* objects has been modified since this enumerator was created.
*/
void Reset();
}
}

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

@ -0,0 +1,9 @@
namespace System.Collections
{
using System;
public interface IEqualityComparer
{
bool Equals(Object x,Object y);
int GetHashCode(Object obj);
}
}

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

@ -0,0 +1,80 @@
//
// Copyright (c) 2017 The nanoFramework project contributors
// Portions Copyright (c) Microsoft Corporation. All rights reserved.
// See LICENSE file in the project root for full license information.
//
namespace System.Collections
{
using System;
/**
* An IList is an ordered collection of objects. The exact ordering
* is up to the implementation of the list, ranging from a sorted
* order to insertion order.
*/
public interface IList : ICollection
{
// Interfaces are not serializable
/**
* The Item property provides methods to read and edit entries in the List.
*/
Object this[int index]
{
get;
set;
}
/**
* Adds an item to the list. The exact position in the list is
* implementation-dependent, so while ArrayList may always insert
* in the last available location, a SortedList most likely would not.
* The return value is the position the new element was inserted in.
*/
int Add(Object value);
/**
* Returns whether the list contains a particular item.
*/
bool Contains(Object value);
/**
* Removes all items from the list.
*/
void Clear();
bool IsReadOnly
{ get; }
bool IsFixedSize
{
get;
}
/**
* Returns the index of a particular item, if it is in the list.
* Returns -1 if the item isn't in the list.
*/
int IndexOf(Object value);
/**
* Inserts <var>value</var> into the list at position <var>index</var>.
* <var>index</var> must be non-negative and less than or equal to the
* number of elements in the list. If <var>index</var> equals the number
* of items in the list, then <var>value</var> is appended to the end.
*/
void Insert(int index, Object value);
/**
* Removes an item from the list.
*/
void Remove(Object value);
/**
* Removes the item at position <var>index</var>.
*/
void RemoveAt(int index);
}
}

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

@ -0,0 +1,179 @@
//
// Copyright (c) 2017 The nanoFramework project contributors
// Portions Copyright (c) Microsoft Corporation. All rights reserved.
// See LICENSE file in the project root for full license information.
//
using System;
using System.Diagnostics;
using System.Runtime.CompilerServices;
namespace System.Collections
{
/// <summary>
/// A circular-array implementation of a queue. Enqueue can be O(n). Dequeue is O(1).
/// </summary>
[DebuggerDisplay("Count = {Count}")]
[Serializable()]
public class Queue : ICollection, ICloneable
{
private Object[] _array;
private int _head; // First valid element in the queue
private int _tail; // Last valid element in the queue
private int _size; // Number of elements.
// Keep in-sync with c_DefaultCapacity in CLR_RT_HeapBlock_Queue in TinyCLR_Runtime__HeapBlock.h
private const int _defaultCapacity = 4;
/// <summary>
/// Initializes a new instance of the Queue class that is empty, has the default initial
/// capacity, and uses the default growth factor (2x).
/// </summary>
public Queue()
{
_array = new Object[_defaultCapacity];
_head = 0;
_tail = 0;
_size = 0;
}
/// <summary>
/// Gets the number of elements contained in the Queue.
/// </summary>
public virtual int Count
{
get { return _size; }
}
/// <summary>
/// Creates a shallow copy of the Queue.
/// </summary>
/// <returns>A shallow copy of the Queue.</returns>
public virtual Object Clone()
{
Queue q = new Queue();
if (_size > _defaultCapacity)
{
// only re-allocate a new array if the size isn't what we need.
// otherwise, the one allocated in the constructor will be just fine
q._array = new Object[_size];
}
else
{
// if size is not the same as capacity, we need to adjust tail accordingly
q._tail = _size % _defaultCapacity;
}
q._size = _size;
CopyTo(q._array, 0);
return q;
}
/// <summary>
/// Gets a value indicating whether access to the Queue is synchronized (thread safe).
/// Always return false.
/// </summary>
public virtual bool IsSynchronized
{
get { return false; }
}
/// <summary>
/// Gets an object that can be used to synchronize access to the Queue.
/// </summary>
public virtual Object SyncRoot
{
get { return this; }
}
/// <summary>
/// Removes all objects from the Queue.
/// </summary>
[MethodImplAttribute(MethodImplOptions.InternalCall)]
public extern virtual void Clear();
/// <summary>
/// Copies the Queue elements to an existing one-dimensional Array, starting at
/// the specified array index.
/// </summary>
/// <param name="array">The one-dimensional Array that is the destination of the elements copied from Queue.</param>
/// <param name="index">The zero-based index in array at which copying begins.</param>
[MethodImplAttribute(MethodImplOptions.InternalCall)]
public extern virtual void CopyTo(Array array, int index);
/// <summary>
/// Adds an object to the end of the Queue.
/// </summary>
/// <param name="obj">The object to add to the Queue.</param>
[MethodImplAttribute(MethodImplOptions.InternalCall)]
public extern virtual void Enqueue(Object obj);
/// <summary>
/// Returns an enumerator that iterates through the Queue.
/// </summary>
/// <returns>An IEnumerator for the Queue.</returns>
public virtual IEnumerator GetEnumerator()
{
int endIndex = _tail;
if (_size > 0 && _tail <= _head) endIndex += _array.Length;
return new Array.SZArrayEnumerator(_array, _head, endIndex);
}
/// <summary>
/// Removes and returns the object at the beginning of the Queue.
/// </summary>
/// <returns>The object that is removed from the beginning of the Queue.</returns>
[MethodImplAttribute(MethodImplOptions.InternalCall)]
public extern virtual Object Dequeue();
/// <summary>
/// Returns the object at the beginning of the Queue without removing it.
/// </summary>
/// <returns>The object at the beginning of the Queue.</returns>
[MethodImplAttribute(MethodImplOptions.InternalCall)]
public extern virtual Object Peek();
/// <summary>
/// Determines whether an element is in the Queue.
/// </summary>
/// <param name="obj">The Object to locate in the Queue.</param>
/// <returns>true if obj is found in the Queue; otherwise, false.</returns>
public virtual bool Contains(Object obj)
{
if (_size == 0)
return false;
if (_head < _tail)
{
return Array.IndexOf(_array, obj, _head, _size) >= 0;
}
else
{
return (Array.IndexOf(_array, obj, _head, _array.Length - _head) >= 0) ||
(Array.IndexOf(_array, obj, 0, _tail) >= 0);
}
}
/// <summary>
/// Copies the Queue elements to a new array. The order of the elements in the new
/// array is the same as the order of the elements from the beginning of the Queue
/// to its end.
/// </summary>
/// <returns>A new array containing elements copied from the Queue.</returns>
public virtual Object[] ToArray()
{
Object[] arr = new Object[_size];
CopyTo(arr, 0);
return arr;
}
}
}

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

@ -0,0 +1,152 @@
//
// Copyright (c) 2017 The nanoFramework project contributors
// Portions Copyright (c) Microsoft Corporation. All rights reserved.
// See LICENSE file in the project root for full license information.
//
using System.Diagnostics;
using System.Runtime.CompilerServices;
namespace System.Collections
{
/// <summary>
/// An array implementation of a stack. Push can be O(n). Pop is O(1).
/// </summary>
[Serializable()]
[DebuggerDisplay("Count = {Count}")]
public class Stack : ICollection, ICloneable
{
private Object[] _array; // Storage for stack elements
private int _size; // Number of items in the stack.
// Keep in-sync with c_DefaultCapacity in CLR_RT_HeapBlock_Stack in TinyCLR_Runtime__HeapBlock.h
private const int _defaultCapacity = 4;
/// <summary>
/// Initializes a new instance of the Stack class that is empty and has the default initial capacity.
/// </summary>
public Stack()
{
_array = new Object[_defaultCapacity];
_size = 0;
}
/// <summary>
/// Size of the stack
/// </summary>
public virtual int Count
{
get { return _size; }
}
/// <summary>
/// Returns whether the current stack is synchornized. Always return false.
/// </summary>
public virtual bool IsSynchronized
{
get { return false; }
}
/// <summary>
/// Gets an object that can be used to synchronize access to the Stack.
/// </summary>
public virtual Object SyncRoot
{
get { return this; }
}
/// <summary>
/// Removes all Objects from the Stack.
/// </summary>
[MethodImplAttribute(MethodImplOptions.InternalCall)]
public extern virtual void Clear();
/// <summary>
/// Creates a shallow copy of the Stack.
/// </summary>
/// <returns>A shallow copy of the Stack.</returns>
public virtual Object Clone()
{
Stack s = new Stack();
int capacity = _defaultCapacity;
if (_size > _defaultCapacity)
{
// only re-allocate a new array if the size isn't what we need.
// otherwise, the one allocated in the constructor will be just fine
s._array = new Object[_size];
capacity = _size;
}
s._size = _size;
Array.Copy(_array, _array.Length - _size, s._array, capacity - _size, _size);
return s;
}
/// <summary>
/// Determines whether an element is in the Stack.
/// </summary>
/// <param name="obj">The Object to locate in the Stack.</param>
/// <returns>true, if obj is found in the Stack; otherwise, false</returns>
public virtual bool Contains(Object obj)
{
return Array.IndexOf(_array, obj, _array.Length - _size, _size) >= 0;
}
/// <summary>
/// Copies the Stack to an existing one-dimensional Array, starting at the specified array index.
/// </summary>
/// <param name="array">The one-dimensional Array that is the destination of the elements copied from Stack.</param>
/// <param name="index">The zero-based index in array at which copying begins.</param>
public virtual void CopyTo(Array array, int index)
{
Array.Copy(_array, _array.Length - _size, array, index, _size);
}
/// <summary>
/// Returns an IEnumerator for this Stack.
/// </summary>
/// <returns>An IEnumerator for the Stack.</returns>
public virtual IEnumerator GetEnumerator()
{
int capacity = _array.Length;
return new Array.SZArrayEnumerator(_array, capacity - _size, capacity);
}
/// <summary>
/// Returns the object at the top of the Stack without removing it.
/// </summary>
/// <returns>The Object at the top of the Stack.</returns>
[MethodImplAttribute(MethodImplOptions.InternalCall)]
public extern virtual Object Peek();
/// <summary>
/// Removes and returns the object at the top of the Stack.
/// </summary>
/// <returns>The Object removed from the top of the Stack.</returns>
[MethodImplAttribute(MethodImplOptions.InternalCall)]
public extern virtual Object Pop();
/// <summary>
/// Inserts an object at the top of the Stack.
/// </summary>
/// <param name="obj">The Object to push onto the Stack.</param>
[MethodImplAttribute(MethodImplOptions.InternalCall)]
public extern virtual void Push(Object obj);
/// <summary>
/// Copies the Stack to a new array, in the same order Pop would return the items.
/// </summary>
/// <returns>A new array containing copies of the elements of the Stack.</returns>
public virtual Object[] ToArray()
{
Object[] objArray = new Object[_size];
Array.Copy(_array, _array.Length - _size, objArray, 0, _size);
return objArray;
}
}
}

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

@ -0,0 +1,59 @@
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
// Copyright (c) Microsoft Corporation. All rights reserved.
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////namespace System.ComponentModel
namespace System.ComponentModel
{
using System;
public enum EditorBrowsableState
{
Always,
Never,
Advanced
}
/** Custom attribute to indicate that a specified object
* should be hidden from the editor. (i.e Intellisence filtering)
*/
[AttributeUsageAttribute(AttributeTargets.Class | AttributeTargets.Struct | AttributeTargets.Enum | AttributeTargets.Constructor | AttributeTargets.Method | AttributeTargets.Property | AttributeTargets.Field | AttributeTargets.Event | AttributeTargets.Interface | AttributeTargets.Delegate)]
public sealed class EditorBrowsableAttribute : Attribute
{
private EditorBrowsableState browsableState;
public EditorBrowsableAttribute() : this(EditorBrowsableState.Always) { }
public EditorBrowsableAttribute(EditorBrowsableState state)
{
this.browsableState = state;
}
public override bool Equals(object obj)
{
if (obj == this)
{
return true;
}
EditorBrowsableAttribute attribute1 = obj as EditorBrowsableAttribute;
if (attribute1 != null)
{
return (attribute1.browsableState == this.browsableState);
}
return false;
}
public EditorBrowsableState State
{
get
{
return this.browsableState;
}
}
}
}

730
_mscorlib/System/Convert.cs Normal file
Просмотреть файл

@ -0,0 +1,730 @@
//
// Copyright (c) 2017 The nanoFramework project contributors
// Portions Copyright (c) Microsoft Corporation. All rights reserved.
// See LICENSE file in the project root for full license information.
//
using System;
namespace System
{
//We don't want to implement this whole class, but VB needs an external function to convert any integer type to a Char.
[System.ComponentModel.EditorBrowsableAttribute(System.ComponentModel.EditorBrowsableState.Never)]
public static class Convert
{
[CLSCompliant(false)]
public static char ToChar(ushort value)
{
return (char)value;
}
[CLSCompliant(false)]
public static sbyte ToSByte(string value)
{
return (sbyte)ToInt64(value, true, SByte.MinValue, SByte.MaxValue);
}
public static byte ToByte(string value)
{
return (byte)ToInt64(value, false, Byte.MinValue, Byte.MaxValue);
}
public static short ToInt16(string value)
{
return (short)ToInt64(value, true, Int16.MinValue, Int16.MaxValue);
}
[CLSCompliant(false)]
public static ushort ToUInt16(string value)
{
return (ushort)ToInt64(value, false, UInt16.MinValue, UInt16.MaxValue);;
}
public static int ToInt32(string value)
{
return (int)ToInt64(value, true, Int32.MinValue, Int32.MaxValue);
}
[CLSCompliant(false)]
public static uint ToUInt32(string value)
{
return (uint)ToInt64(value, false, UInt32.MinValue, UInt32.MaxValue);
}
public static long ToInt64(string value)
{
return ToInt64(value, true, Int64.MinValue, Int64.MaxValue);
}
[CLSCompliant(false)]
public static ulong ToUInt64(string value)
{
return (ulong)ToInt64(value, false, 0, 0);
}
//--//
public static int ToInt32(string hexNumber, int fromBase)
{
if (hexNumber == null)
return 0;
if (fromBase != 16)
throw new ArgumentException();
int result = 0;
int digit;
char[] hexDigit = hexNumber.Trim(' ').ToUpper().ToCharArray();
// Trim hex sentinal if present
int len = hexDigit.Length;
int i = (len >= 2 && hexDigit[0] == '0' && hexDigit[1] == 'X') ? 2 : 0;
// 8 hex chars == 4 bytes == sizeof(Int32)
if ((len - i) > 8) throw new ArgumentException();
// Convert hex to integer
for (; i < len; i++)
{
char c = hexDigit[i];
switch (c)
{
case '0':
digit = 0;
break;
case '1':
digit = 1;
break;
case '2':
digit = 2;
break;
case '3':
digit = 3;
break;
case '4':
digit = 4;
break;
case '5':
digit = 5;
break;
case '6':
digit = 6;
break;
case '7':
digit = 7;
break;
case '8':
digit = 8;
break;
case '9':
digit = 9;
break;
case 'A':
digit = 10;
break;
case 'B':
digit = 11;
break;
case 'C':
digit = 12;
break;
case 'D':
digit = 13;
break;
case 'E':
digit = 14;
break;
case 'F':
digit = 15;
break;
default:
throw new ArgumentException();
}
result <<= 4;
result += digit;
}
return result;
}
public static double ToDouble(string s)
{
if (s == null)
return 0;
s = s.Trim(' ').ToLower();
if(s.Length == 0) return 0;
int decimalpoint = s.IndexOf('.');
int exp = s.IndexOf('e');
if (exp != -1 && decimalpoint > exp)
throw new Exception();
char [] chars = s.ToCharArray();
int len = chars.Length;
double power = 0;
double rightDecimal = 0;
int decLeadingZeros = 0;
double leftDecimal = 0;
int leftDecLen = 0;
bool isNeg = chars[0] == '-';
// convert the exponential portion to a number
if (exp != -1 && exp + 1 < len - 1)
{
int tmp;
power = GetDoubleNumber(chars, exp + 1, len - (exp + 1), out tmp);
}
// convert the decimal portion to a number
if (decimalpoint != -1)
{
double number;
int decLen;
if (exp == -1)
{
decLen = len - (decimalpoint + 1);
}
else
{
decLen = (exp - (decimalpoint + 1));
}
number = GetDoubleNumber(chars, decimalpoint + 1, decLen, out decLeadingZeros);
rightDecimal = number * System.Math.Pow(10, -decLen);
}
// convert the integer portion to a number
if (decimalpoint != 0)
{
int leadingZeros;
if (decimalpoint == -1 && exp == -1) leftDecLen = len;
else if (decimalpoint != -1) leftDecLen = decimalpoint;
else leftDecLen = exp;
leftDecimal = GetDoubleNumber(chars, 0, leftDecLen, out leadingZeros);
// subtract leading zeros from integer length
leftDecLen -= leadingZeros;
if (chars[0] == '-' || chars[0] == '+') leftDecLen--;
}
double value = 0;
if (leftDecimal < 0)
{
value = -leftDecimal + rightDecimal;
value = -value;
}
else
{
value = leftDecimal + rightDecimal;
}
// lets normalize the integer portion first
while(leftDecLen > 1)
{
switch(leftDecLen)
{
case 2:
value /= 10.0;
power += 1;
leftDecLen -= 1;
break;
case 3:
value /= 100.0;
power += 2;
leftDecLen -= 2;
break;
case 4:
value /= 1000.0;
power += 3;
leftDecLen -= 3;
break;
default:
value /= 10000.0;
power += 4;
leftDecLen -= 4;
break;
}
}
// now normalize the decimal portion
if (value != 0.0 && value < 1.0 && value > -1.0)
{
// for normalization we want x.xxx instead of 0.xxx
decLeadingZeros++;
while(decLeadingZeros > 0)
{
switch (decLeadingZeros)
{
case 1:
value *= 10.0;
power -= 1;
decLeadingZeros -= 1;
break;
case 2:
value *= 100.0;
power -= 2;
decLeadingZeros -= 2;
break;
case 3:
value *= 1000.0;
power -= 3;
decLeadingZeros -= 3;
break;
default:
value *= 10000.0;
power -= 4;
decLeadingZeros -= 4;
break;
}
}
}
// special case for epsilon (the System.Math.Pow native method will return zero for -324)
if (power == -324)
{
value = value * System.Math.Pow(10, power + 1);
value /= 10.0;
}
else
{
value = value * System.Math.Pow(10, power);
}
if (value == double.PositiveInfinity || value == double.NegativeInfinity)
{
throw new Exception();
}
if(isNeg && value > 0)
{
value = -value;
}
return value;
}
//--//
private static long ToInt64(string value, bool signed, long min, long max)
{
if (value == null)
return 0;
value = value.Trim(' ');
char[] num = value.ToCharArray();
int len = num.Length;
ulong result = 0;
int index = 0;
bool isNeg = false;
// check the sign
if (num[0] == '-')
{
isNeg = true;
index = 1;
}
else if (num[0] == '+')
{
index = 1;
}
for (int i = index; i < len; i++)
{
ulong digit;
char c = num[i];
// switch statement is faster than subtracting '0'
switch(c)
{
case '0':
digit = 0;
break;
case '1':
digit = 1;
break;
case '2':
digit = 2;
break;
case '3':
digit = 3;
break;
case '4':
digit = 4;
break;
case '5':
digit = 5;
break;
case '6':
digit = 6;
break;
case '7':
digit = 7;
break;
case '8':
digit = 8;
break;
case '9':
digit = 9;
break;
default:
throw new Exception();
}
// check for overflow - any number greater than this number will cause an overflow
// when multiplied by 10
if(( signed && result > 0x0CCCCCCCCCCCCCCC) ||
(!signed && result > 0x1999999999999999))
{
throw new Exception();
}
result *= 10;
result += digit;
}
if (isNeg && !signed && result != 0) throw new Exception();
long res;
if (isNeg)
{
res = -(long)result;
// if the result is not negative, we had an overflow
if(res > 0) throw new Exception();
}
else
{
res = (long)result;
// if the result is negative and we are not converting a
// UInt64, we had an overflow
if(max != 0 && res < 0) throw new Exception();
}
// final check for max/min
if (max != 0 && (res < min || res > max)) throw new Exception();
return res;
}
private static double GetDoubleNumber(char[] chars, int start, int length, out int numLeadingZeros)
{
double number = 0;
bool isNeg = false;
int end = start + length;
numLeadingZeros = 0;
if(chars[start] == '-')
{
isNeg = true;
start++;
}
else if(chars[start] == '+')
{
start++;
}
for (int i = start; i < end; i++)
{
int digit;
char c = chars[i];
// switch statement is faster than subtracting '0'
switch(c)
{
case '0':
// update the number of leading zeros (used for normalizing)
if((numLeadingZeros + start) == i)
{
numLeadingZeros++;
}
digit = 0;
break;
case '1':
digit = 1;
break;
case '2':
digit = 2;
break;
case '3':
digit = 3;
break;
case '4':
digit = 4;
break;
case '5':
digit = 5;
break;
case '6':
digit = 6;
break;
case '7':
digit = 7;
break;
case '8':
digit = 8;
break;
case '9':
digit = 9;
break;
default:
throw new Exception();
}
number *= 10;
number += digit;
}
return isNeg ? -number : number;
}
/// <summary>
/// Conversion array from 6 bit of value into base64 encoded character.
/// </summary>
static char[] s_rgchBase64EncodingDefault = new char[]
{
'A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J', 'K', 'L', /* 12 */
'M', 'N', 'O', 'P', 'Q', 'R', 'S', 'T', 'U', 'V', 'W', 'X', /* 24 */
'Y', 'Z', 'a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', /* 36 */
'k', 'l', 'm', 'n', 'o', 'p', 'q', 'r', 's', 't', 'u', 'v', /* 48 */
'w', 'x', 'y', 'z', '0', '1', '2', '3', '4', '5', '6', '7', /* 60 */
'8', '9', '!', '*' /* 64 */
};
static char[] s_rgchBase64EncodingRFC4648 = new char[]
{
'A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J', 'K', 'L', /* 12 */
'M', 'N', 'O', 'P', 'Q', 'R', 'S', 'T', 'U', 'V', 'W', 'X', /* 24 */
'Y', 'Z', 'a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', /* 36 */
'k', 'l', 'm', 'n', 'o', 'p', 'q', 'r', 's', 't', 'u', 'v', /* 48 */
'w', 'x', 'y', 'z', '0', '1', '2', '3', '4', '5', '6', '7', /* 60 */
'8', '9', '+', '/' /* 64 */
};
static char[] s_rgchBase64Encoding = s_rgchBase64EncodingDefault;
static byte[] s_rgbBase64Decode = new byte[]
{
// Note we also accept ! and + interchangably.
// Note we also accept * and / interchangably.
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, /* 0 - 7 */
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, /* 8 - 15 */
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, /* 16 - 23 */
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, /* 24 - 31 */
0x00, 0x3E, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, /* 32 - 39 */
0x00, 0x00, 0x3f, 0x3e, 0x00, 0x00, 0x00, 0x3f, /* 40 - 47 */
0x34, 0x35, 0x36, 0x37, 0x38, 0x39, 0x3a, 0x3b, /* 48 - 55 */
0x3c, 0x3d, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, /* 56 - 63 */
0x00, 0x00, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, /* 64 - 71 */
0x07, 0x08, 0x09, 0x0a, 0x0b, 0x0c, 0x0d, 0x0e, /* 72 - 79 */
0x0f, 0x10, 0x11, 0x12, 0x13, 0x14, 0x15, 0x16, /* 80 - 87 */
0x17, 0x18, 0x19, 0x00, 0x00, 0x00, 0x00, 0x00, /* 88 - 95 */
0x00, 0x1a, 0x1b, 0x1c, 0x1d, 0x1e, 0x1f, 0x20, /* 96 - 103 */
0x21, 0x22, 0x23, 0x24, 0x25, 0x26, 0x27, 0x28, /* 104 - 111 */
0x29, 0x2a, 0x2b, 0x2c, 0x2d, 0x2e, 0x2f, 0x30, /* 112 - 119 */
0x31, 0x32, 0x33, 0x00, 0x00, 0x00, 0x00, 0x00 /* 120 - 127 */
};
private const int CCH_B64_IN_QUARTET = 4;
private const int CB_B64_OUT_TRIO = 3;
static private int GetBase64EncodedLength(int binaryLen)
{
return (((binaryLen / 3) + (((binaryLen % 3) != 0) ? 1 : 0)) * 4);
}
public static bool UseRFC4648Encoding
{
get { return s_rgchBase64Encoding == s_rgchBase64EncodingRFC4648; }
set { s_rgchBase64Encoding = (value ? s_rgchBase64EncodingRFC4648 : s_rgchBase64EncodingDefault); }
}
/// <summary>
/// Converts an array of 8-bit unsigned integers to its equivalent String representation encoded with base 64 digits.
/// </summary>
/// <param name="inArray">An array of 8-bit unsigned integers. </param>
/// <returns>The String representation, in base 64, of the contents of inArray.</returns>
public static string ToBase64String(byte[] inArray)
{
return ToBase64String(inArray, 0, inArray.Length);
}
public static string ToBase64String(byte[] inArray, int offset, int length)
{
if (inArray == null)
{
throw new ArgumentNullException();
}
if(length == 0) return "";
if(offset + length > inArray.Length) throw new ArgumentOutOfRangeException();
// Create array of characters with appropriate length.
int inArrayLen = length;
int outArrayLen = GetBase64EncodedLength(inArrayLen);
char[] outArray = new char[outArrayLen];
/* encoding starts from end of string */
/*
** Convert the input buffer bytes through the encoding table and
** out into the output buffer.
*/
int iInputEnd = offset + (outArrayLen / CCH_B64_IN_QUARTET - 1) * CB_B64_OUT_TRIO;
int iInput = offset, iOutput = 0;
byte uc0 = 0, uc1 = 0, uc2 = 0;
// Loop is for all trios except of last one.
for (; iInput < iInputEnd; iInput += CB_B64_OUT_TRIO, iOutput += CCH_B64_IN_QUARTET)
{
uc0 = inArray[iInput];
uc1 = inArray[iInput + 1];
uc2 = inArray[iInput + 2];
// Writes data to output character array.
outArray[iOutput] = s_rgchBase64Encoding[uc0 >> 2];
outArray[iOutput + 1] = s_rgchBase64Encoding[((uc0 << 4) & 0x30) | ((uc1 >> 4) & 0xf)];
outArray[iOutput + 2] = s_rgchBase64Encoding[((uc1 << 2) & 0x3c) | ((uc2 >> 6) & 0x3)];
outArray[iOutput + 3] = s_rgchBase64Encoding[uc2 & 0x3f];
}
// Now we process the last trio of bytes. This trio might be incomplete and thus require special handling.
// This code could be incorporated into main "for" loop, but hte code would be slower becuase of extra 2 "if"
uc0 = inArray[iInput];
uc1 = ((iInput + 1) < (offset + inArrayLen)) ? inArray[iInput + 1] : (byte)0;
uc2 = ((iInput + 2) < (offset + inArrayLen)) ? inArray[iInput + 2] : (byte)0;
// Writes data to output character array.
outArray[iOutput] = s_rgchBase64Encoding[uc0 >> 2];
outArray[iOutput + 1] = s_rgchBase64Encoding[((uc0 << 4) & 0x30) | ((uc1 >> 4) & 0xf)];
outArray[iOutput + 2] = s_rgchBase64Encoding[((uc1 << 2) & 0x3c) | ((uc2 >> 6) & 0x3)];
outArray[iOutput + 3] = s_rgchBase64Encoding[uc2 & 0x3f];
switch (inArrayLen % CB_B64_OUT_TRIO)
{
/*
** One byte out of three, add padding and fall through
*/
case 1:
outArray[outArrayLen - 2] = '=';
goto case 2;
/*
** Two bytes out of three, add padding.
*/
case 2:
outArray[outArrayLen - 1] = '=';
break;
}
// Creates string out of character array and return it.
return new string(outArray);
}
/// <summary>
/// Converts the specified String, which encodes binary data as base 64 digits, to an equivalent 8-bit unsigned integer array.
/// </summary>
/// <param name="inString">Base64 encoded string to convert</param>
/// <returns>An array of 8-bit unsigned integers equivalent to s.</returns>
/// <remarks>s is composed of base 64 digits, white space characters, and trailing padding characters.
/// The base 64 digits in ascending order from zero are the uppercase characters 'A' to 'Z',
/// lowercase characters 'a' to 'z', numerals '0' to '9', and the symbols '+' and '/'.
/// An arbitrary number of white space characters can appear in s because all white space characters are ignored.
/// The valueless character, '=', is used for trailing padding. The end of s can consist of zero, one, or two padding characters.
/// </remarks>
public static byte[] FromBase64String(string inString)
{
if (inString == null)
{
throw new ArgumentNullException();
}
char []chArray = inString.ToCharArray();
return FromBase64CharArray(chArray, 0, chArray.Length);
}
public static byte[] FromBase64CharArray(char[] inString, int offset, int length)
{
if(length == 0) return new byte[0];
// Checks that length of string is multiple of 4
int inLength = length;
if (inLength % CCH_B64_IN_QUARTET != 0)
{
throw new ArgumentException("Encoded string length should be multiple of 4");
}
// Maximum buffer size needed.
int outCurPos = (((inLength + (CCH_B64_IN_QUARTET - 1)) / CCH_B64_IN_QUARTET) * CB_B64_OUT_TRIO);
if (inString[offset + inLength - 1] == '=')
{ // If the last was "=" - it means last byte was padded/
--outCurPos;
// If one more '=' - two bytes were actually padded.
if (inString[offset + inLength - 2] == '=')
{
--outCurPos;
}
}
// Output array.
byte[] retArray = new byte[outCurPos];
// Array of 4 bytes - temporary.
byte[] rgbOutput = new byte[CCH_B64_IN_QUARTET];
// Loops over each 4 bytes quartet.
for (int inCurPos = offset + inLength;
inCurPos > offset;
inCurPos -= CCH_B64_IN_QUARTET)
{
int ibDest = 0;
for (; ibDest < CB_B64_OUT_TRIO + 1; ibDest++)
{
int ichGet = inCurPos + ibDest - CCH_B64_IN_QUARTET;
// Equal sign can be only at the end and maximum of 2
if (inString[ichGet] == '=')
{
if (ibDest < 2 || inCurPos != (offset + inLength))
{
throw new ArgumentException("Invalid base64 encoded string");
}
break;
}
// Applies decoding table to the character.
rgbOutput[ibDest] = s_rgbBase64Decode[inString[ichGet]];
}
// Convert 4 bytes in rgbOutput, each having 6 bits into three bytes in final data.
switch (ibDest)
{
default:
retArray[--outCurPos] = (byte)(((rgbOutput[2] & 0x03) << 6) | rgbOutput[3]);
goto case 3;
case 3:
retArray[--outCurPos] = (byte)(((rgbOutput[1] & 0x0F) << 4) | (((rgbOutput[2]) & 0x3C) >> 2));
goto case 2;
case 2:
retArray[--outCurPos] = (byte)(((rgbOutput[0]) << 2) | (((rgbOutput[1]) & 0x30) >> 4));
break;
}
}
return retArray;
}
}
}

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

@ -0,0 +1,18 @@
//
// Copyright (c) 2017 The nanoFramework project contributors
// Portions Copyright (c) Microsoft Corporation. All rights reserved.
// See LICENSE file in the project root for full license information.
//
namespace System
{
[System.ComponentModel.EditorBrowsableAttribute(System.ComponentModel.EditorBrowsableState.Never)]
public sealed class DBNull
{
public static readonly DBNull Value = new DBNull();
private DBNull() { }
}
}

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

@ -0,0 +1,475 @@
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
// Copyright (c) Microsoft Corporation. All rights reserved.
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////namespace System
namespace System
{
using System;
using System.Runtime.CompilerServices;
using System.Threading;
using System.Globalization;
// Summary:
// Specifies whether a System.DateTime object represents a local time, a Coordinated
// Universal Time (UTC), or is not specified as either local time or UTC.
[Serializable]
public enum DateTimeKind
{
// Summary:
// The time represented is not specified as either local time or Coordinated
// Universal Time (UTC).
// MF does not support Unspecified type. Constructor for DateTime always creates local time.
// Use SpecifyKind to set Kind property to UTC or ToUniversalTime to convert local to UTC
//Unspecified = 0,
//
// Summary:
// The time represented is UTC.
Utc = 1,
//
// Summary:
// The time represented is local time.
Local = 2,
}
/**
* This value type represents a date and time. Every DateTime
* object has a private field (Ticks) of type Int64 that stores the
* date and time as the number of 100 nanosecond intervals since
* 12:00 AM January 1, year 1601 A.D. in the proleptic Gregorian Calendar.
*
* <p>For a description of various calendar issues, look at
* <a href="http://serendipity.nofadz.com/hermetic/cal_stud.htm">
* Calendar Studies web site</a>, at
* http://serendipity.nofadz.com/hermetic/cal_stud.htm.
*
* <p>
* <h2>Warning about 2 digit years</h2>
* <p>As a temporary hack until we get new DateTime &lt;-&gt; String code,
* some systems won't be able to round trip dates less than 1930. This
* is because we're using OleAut's string parsing routines, which look
* at your computer's default short date string format, which uses 2 digit
* years on most computers. To fix this, go to Control Panel -&gt; Regional
* Settings -&gt; Date and change the short date style to something like
* "M/d/yyyy" (specifying four digits for the year).
*
*/
[Serializable()]
public struct DateTime
{
// Number of 100ns ticks per time unit
private const long TicksPerMillisecond = 10000;
private const long TicksPerSecond = TicksPerMillisecond * 1000;
private const long TicksPerMinute = TicksPerSecond * 60;
private const long TicksPerHour = TicksPerMinute * 60;
private const long TicksPerDay = TicksPerHour * 24;
// Number of milliseconds per time unit
private const int MillisPerSecond = 1000;
private const int MillisPerMinute = MillisPerSecond * 60;
private const int MillisPerHour = MillisPerMinute * 60;
private const int MillisPerDay = MillisPerHour * 24;
// Number of days in a non-leap year
private const int DaysPerYear = 365;
// Number of days in 4 years
private const int DaysPer4Years = DaysPerYear * 4 + 1;
// Number of days in 100 years
private const int DaysPer100Years = DaysPer4Years * 25 - 1;
// Number of days in 400 years
private const int DaysPer400Years = DaysPer100Years * 4 + 1;
// Number of days from 1/1/0001 to 12/31/1600
private const int DaysTo1601 = DaysPer400Years * 4;
// Number of days from 1/1/0001 to 12/30/1899
private const int DaysTo1899 = DaysPer400Years * 4 + DaysPer100Years * 3 - 367;
// Number of days from 1/1/0001 to 12/31/9999
private const int DaysTo10000 = DaysPer400Years * 25 - 366;
private const long MinTicks = 0;
private const long MaxTicks = 441796895990000000;
private const long MaxMillis = (long)DaysTo10000 * MillisPerDay;
// This is mask to extract ticks from m_ticks
private const ulong TickMask = 0x7FFFFFFFFFFFFFFFL;
private const ulong UTCMask = 0x8000000000000000L;
public static readonly DateTime MinValue = new DateTime(MinTicks);
public static readonly DateTime MaxValue = new DateTime(MaxTicks);
private ulong m_ticks;
public DateTime(long ticks)
{
if (((ticks & (long)TickMask) < MinTicks) || ((ticks & (long)TickMask) > MaxTicks))
{
throw new ArgumentOutOfRangeException("ticks", "Ticks must be between DateTime.MinValue.Ticks and DateTime.MaxValue.Ticks.");
}
m_ticks = (ulong)ticks;
}
public DateTime(long ticks, DateTimeKind kind)
: this(ticks)
{
if (kind == DateTimeKind.Local)
{
m_ticks &= ~UTCMask;
}
else
{
m_ticks |= UTCMask;
}
}
public DateTime(int year, int month, int day)
: this(year, month, day, 0, 0, 0)
{
}
public DateTime(int year, int month, int day, int hour, int minute, int second)
: this(year, month, day, hour, minute, second, 0)
{
}
[MethodImplAttribute(MethodImplOptions.InternalCall)]
public extern DateTime(int year, int month, int day, int hour, int minute, int second, int millisecond);
public DateTime Add(TimeSpan val)
{
return new DateTime((long)m_ticks + val.Ticks);
}
private DateTime Add(double val, int scale)
{
return new DateTime((long)((long)m_ticks + (long)(val * scale * TicksPerMillisecond + (val >= 0 ? 0.5 : -0.5))));
}
public DateTime AddDays(double val)
{
return Add(val, MillisPerDay);
}
public DateTime AddHours(double val)
{
return Add(val, MillisPerHour);
}
public DateTime AddMilliseconds(double val)
{
return Add(val, 1);
}
public DateTime AddMinutes(double val)
{
return Add(val, MillisPerMinute);
}
public DateTime AddSeconds(double val)
{
return Add(val, MillisPerSecond);
}
public DateTime AddTicks(long val)
{
return new DateTime((long)m_ticks + val);
}
public static int Compare(DateTime t1, DateTime t2)
{
// Get ticks, clear UTC mask
ulong t1_ticks = t1.m_ticks & TickMask;
ulong t2_ticks = t2.m_ticks & TickMask;
// Compare ticks, ignore the Kind property.
if (t1_ticks > t2_ticks)
{
return 1;
}
if (t1_ticks < t2_ticks)
{
return -1;
}
// Values are equal
return 0;
}
public int CompareTo(Object val)
{
if (val == null) return 1;
return DateTime.Compare(this, (DateTime)val);
}
[MethodImplAttribute(MethodImplOptions.InternalCall)]
public extern static int DaysInMonth(int year, int month);
public override bool Equals(Object val)
{
if (val is DateTime)
{
// Call compare for proper comparison of 2 DateTime objects
// Since DateTime is optimized value and internally represented by int64
// "this" may still have type int64.
// Convertion to object and back is a workaround.
object o = this;
DateTime thisTime = (DateTime)o;
return Compare(thisTime, (DateTime)val) == 0;
}
return false;
}
public static bool Equals(DateTime t1, DateTime t2)
{
return Compare(t1, t2) == 0;
}
public DateTime Date
{
get
{
// Need to remove UTC mask before arithmetic operations. Then set it back.
if ((m_ticks & UTCMask) != 0)
{
return new DateTime((long)(((m_ticks & TickMask) - (m_ticks & TickMask) % TicksPerDay) | UTCMask));
}
else
{
return new DateTime((long)(m_ticks - m_ticks % TicksPerDay));
}
}
}
public int Day
{
[MethodImplAttribute(MethodImplOptions.InternalCall)]
get
{
return 0;
}
}
public DayOfWeek DayOfWeek
{
[MethodImplAttribute(MethodImplOptions.InternalCall)]
get
{
return DayOfWeek.Monday;
}
}
public int DayOfYear
{
[MethodImplAttribute(MethodImplOptions.InternalCall)]
get
{
return 0;
}
}
/// Reduce size by calling a single method?
public int Hour
{
[MethodImplAttribute(MethodImplOptions.InternalCall)]
get
{
return 0;
}
}
public DateTimeKind Kind
{
get
{
// If mask for UTC time is set - return UTC. If no maskk - return local.
return (m_ticks & UTCMask) != 0 ? DateTimeKind.Utc : DateTimeKind.Local;
}
}
public static DateTime SpecifyKind(DateTime value, DateTimeKind kind)
{
DateTime retVal = new DateTime((long)value.m_ticks);
if (kind == DateTimeKind.Utc)
{
// Set UTC mask
retVal.m_ticks = value.m_ticks | UTCMask;
}
else
{ // Clear UTC mask
retVal.m_ticks = value.m_ticks & ~UTCMask;
}
return retVal;
}
public int Millisecond
{
[MethodImplAttribute(MethodImplOptions.InternalCall)]
get
{
return 0;
}
}
public int Minute
{
[MethodImplAttribute(MethodImplOptions.InternalCall)]
get
{
return 0;
}
}
public int Month
{
[MethodImplAttribute(MethodImplOptions.InternalCall)]
get
{
return 0;
}
}
public static DateTime Now
{
[MethodImplAttribute(MethodImplOptions.InternalCall)]
get
{
return new DateTime();
}
}
public static DateTime UtcNow
{
[MethodImplAttribute(MethodImplOptions.InternalCall)]
get
{
return new DateTime();
}
}
public int Second
{
[MethodImplAttribute(MethodImplOptions.InternalCall)]
get
{
return 0;
}
}
/// Our origin is at 1601/01/01:00:00:00.000
/// While desktop CLR's origin is at 0001/01/01:00:00:00.000.
/// There are 504911232000000000 ticks between them which we are subtracting.
/// See DeviceCode\PAL\time_decl.h for explanation of why we are taking
/// year 1601 as origin for our HAL, PAL, and CLR.
// static Int64 ticksAtOrigin = 504911232000000000;
static Int64 ticksAtOrigin = 0;
public long Ticks
{
get
{
return (long)(m_ticks & TickMask) + ticksAtOrigin;
}
}
public TimeSpan TimeOfDay
{
get
{
return new TimeSpan((long)((m_ticks & TickMask) % TicksPerDay));
}
}
public static DateTime Today
{
[MethodImplAttribute(MethodImplOptions.InternalCall)]
get
{
return new DateTime();
}
}
public int Year
{
[MethodImplAttribute(MethodImplOptions.InternalCall)]
get
{
return 0;
}
}
public TimeSpan Subtract(DateTime val)
{
return new TimeSpan((long)(m_ticks & TickMask) - (long)(val.m_ticks & TickMask));
}
public DateTime Subtract(TimeSpan val)
{
return new DateTime((long)(m_ticks - (ulong)val.m_ticks));
}
[MethodImplAttribute(MethodImplOptions.InternalCall)]
public extern DateTime ToLocalTime();
public override String ToString()
{
return DateTimeFormat.Format(this, null, DateTimeFormatInfo.CurrentInfo);
}
public String ToString(String format)
{
return DateTimeFormat.Format(this, format, DateTimeFormatInfo.CurrentInfo);
}
[MethodImplAttribute(MethodImplOptions.InternalCall)]
public extern DateTime ToUniversalTime();
public static DateTime operator +(DateTime d, TimeSpan t)
{
return new DateTime((long)(d.m_ticks + (ulong)t.m_ticks));
}
public static DateTime operator -(DateTime d, TimeSpan t)
{
return new DateTime((long)(d.m_ticks - (ulong)t.m_ticks));
}
public static TimeSpan operator -(DateTime d1, DateTime d2)
{
return d1.Subtract(d2);
}
public static bool operator ==(DateTime d1, DateTime d2)
{
return Compare(d1, d2) == 0;
}
public static bool operator !=(DateTime t1, DateTime t2)
{
return Compare(t1, t2) != 0;
}
public static bool operator <(DateTime t1, DateTime t2)
{
return Compare(t1, t2) < 0;
}
public static bool operator <=(DateTime t1, DateTime t2)
{
return Compare(t1, t2) <= 0;
}
public static bool operator >(DateTime t1, DateTime t2)
{
return Compare(t1, t2) > 0;
}
public static bool operator >=(DateTime t1, DateTime t2)
{
return Compare(t1, t2) >= 0;
}
}
}

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

@ -0,0 +1,21 @@
//
// Copyright (c) 2017 The nanoFramework project contributors
// Portions Copyright (c) Microsoft Corporation. All rights reserved.
// See LICENSE file in the project root for full license information.
//
namespace System
{
[Serializable]
public enum DayOfWeek
{
Sunday = 0,
Monday = 1,
Tuesday = 2,
Wednesday = 3,
Thursday = 4,
Friday = 5,
Saturday = 6,
}
}

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

@ -0,0 +1,36 @@
//
// Copyright (c) 2017 The nanoFramework project contributors
// Portions Copyright (c) Microsoft Corporation. All rights reserved.
// See LICENSE file in the project root for full license information.
//
using System;
namespace System
{
[System.ComponentModel.EditorBrowsableAttribute(System.ComponentModel.EditorBrowsableState.Never)]
public struct Decimal
{
//The VB IDE starts to run amuck when it tries to do syntax checking on sources that contain Decimal
//and causes the compiler to repeatedly crash unless it finds a constructor.
public Decimal(int value) { }
[CLSCompliant(false)]
public Decimal(uint value) { }
public Decimal(long value) { }
[CLSCompliant(false)]
public Decimal(ulong value) { }
public Decimal(float value) { }
public Decimal(double value) { }
//internal Decimal(Currency value) { }
public Decimal(int[] bits) { }
public Decimal(int lo, int mid, int hi, bool isNegative, byte scale) { }
}
}

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

@ -0,0 +1,43 @@
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
// Copyright (c) Microsoft Corporation. All rights reserved.
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////namespace System
namespace System
{
using System;
using System.Reflection;
using System.Threading;
using System.Runtime.CompilerServices;
[Serializable()]
public abstract class Delegate
{
[MethodImplAttribute(MethodImplOptions.InternalCall)]
public override extern bool Equals(Object obj);
[MethodImplAttribute(MethodImplOptions.InternalCall)]
public static extern Delegate Combine(Delegate a, Delegate b);
extern public MethodInfo Method
{
[MethodImplAttribute(MethodImplOptions.InternalCall)]
get;
}
extern public Object Target
{
[MethodImplAttribute(MethodImplOptions.InternalCall)]
get;
}
[MethodImplAttribute(MethodImplOptions.InternalCall)]
public static extern Delegate Remove(Delegate source, Delegate value);
[MethodImplAttribute(MethodImplOptions.InternalCall)]
public static extern bool operator ==(Delegate d1, Delegate d2);
[MethodImplAttribute(MethodImplOptions.InternalCall)]
public static extern bool operator !=(Delegate d1, Delegate d2);
}
}

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

@ -0,0 +1,31 @@
//
// Copyright (c) 2017 The nanoFramework project contributors
// Portions Copyright (c) Microsoft Corporation. All rights reserved.
// See LICENSE file in the project root for full license information.
//
using System;
namespace System.Diagnostics
{
[AttributeUsage(AttributeTargets.Method, AllowMultiple = true), Serializable]
public sealed class ConditionalAttribute : Attribute
{
public ConditionalAttribute(String conditionString)
{
m_conditionString = conditionString;
}
public String ConditionString
{
get
{
return m_conditionString;
}
}
private String m_conditionString;
}
}

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

@ -0,0 +1,18 @@
using System.Runtime.CompilerServices;
namespace System.Diagnostics
{
public static class Debugger
{
public static extern bool IsAttached
{
[MethodImplAttribute(MethodImplOptions.InternalCall)]
get;
}
[MethodImplAttribute(MethodImplOptions.InternalCall)]
public static extern void Break();
}
}

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

@ -0,0 +1,260 @@
//
// Copyright (c) 2017 The nanoFramework project contributors
// Portions Copyright (c) Microsoft Corporation. All rights reserved.
// See LICENSE file in the project root for full license information.
//
namespace System.Diagnostics
{
using System;
using System.Runtime.InteropServices;
[Serializable, AttributeUsage(AttributeTargets.Class | AttributeTargets.Struct | AttributeTargets.Method | AttributeTargets.Constructor, Inherited = false)]
public sealed class DebuggerStepThroughAttribute : Attribute
{
public DebuggerStepThroughAttribute() { }
}
[Serializable, AttributeUsage(AttributeTargets.Method | AttributeTargets.Constructor, Inherited = false)]
public sealed class DebuggerStepperBoundaryAttribute : Attribute
{
public DebuggerStepperBoundaryAttribute() { }
}
[Serializable, AttributeUsage(AttributeTargets.Method | AttributeTargets.Property | AttributeTargets.Constructor, Inherited = false)]
public sealed class DebuggerHiddenAttribute : Attribute
{
public DebuggerHiddenAttribute() { }
}
[Serializable, AttributeUsage(AttributeTargets.Class | AttributeTargets.Method | AttributeTargets.Property | AttributeTargets.Constructor | AttributeTargets.Struct, Inherited = false)]
public sealed class DebuggerNonUserCodeAttribute : Attribute
{
public DebuggerNonUserCodeAttribute() { }
}
// Attribute class used by the compiler to mark modules.
// If present, then debugging information for everything in the
// assembly was generated by the compiler, and will be preserved
// by the Runtime so that the debugger can provide full functionality
// in the case of JIT attach. If not present, then the compiler may
// or may not have included debugging information, and the Runtime
// won't preserve the debugging info, which will make debugging after
// a JIT attach difficult.
[AttributeUsage(AttributeTargets.Assembly | AttributeTargets.Module, AllowMultiple = false)]
public sealed class DebuggableAttribute : Attribute
{
[Flags]
public enum DebuggingModes
{
None = 0x0,
Default = 0x1,
DisableOptimizations = 0x100,
IgnoreSymbolStoreSequencePoints = 0x2,
EnableEditAndContinue = 0x4
}
private DebuggingModes m_debuggingModes;
public DebuggableAttribute(bool isJITTrackingEnabled,
bool isJITOptimizerDisabled)
{
m_debuggingModes = 0;
if (isJITTrackingEnabled)
{
m_debuggingModes |= DebuggingModes.Default;
}
if (isJITOptimizerDisabled)
{
m_debuggingModes |= DebuggingModes.DisableOptimizations;
}
}
public DebuggableAttribute(DebuggingModes modes)
{
m_debuggingModes = modes;
}
public bool IsJITTrackingEnabled
{
get { return ((m_debuggingModes & DebuggingModes.Default) != 0); }
}
public bool IsJITOptimizerDisabled
{
get { return ((m_debuggingModes & DebuggingModes.DisableOptimizations) != 0); }
}
public DebuggingModes DebuggingFlags
{
get { return m_debuggingModes; }
}
}
// DebuggerBrowsableState states are defined as follows:
// Never never show this element
// Expanded expansion of the class is done, so that all visible internal members are shown
// Collapsed expansion of the class is not performed. Internal visible members are hidden
// RootHidden The target element itself should not be shown, but should instead be
// automatically expanded to have its members displayed.
// Default value is collapsed
// Please also change the code which validates DebuggerBrowsableState variable (in this file)
// if you change this enum.
public enum DebuggerBrowsableState
{
Never = 0,
Collapsed = 2,
RootHidden = 3
}
// the one currently supported with the csee.dat
// (mcee.dat, autoexp.dat) file.
[AttributeUsage(AttributeTargets.Field | AttributeTargets.Property, AllowMultiple = false)]
public sealed class DebuggerBrowsableAttribute : Attribute
{
private DebuggerBrowsableState state;
public DebuggerBrowsableAttribute(DebuggerBrowsableState state)
{
if (state < DebuggerBrowsableState.Never || state > DebuggerBrowsableState.RootHidden)
throw new ArgumentOutOfRangeException("state");
this.state = state;
}
public DebuggerBrowsableState State
{
get { return state; }
}
}
// DebuggerTypeProxyAttribute
[AttributeUsage(AttributeTargets.Struct | AttributeTargets.Class | AttributeTargets.Assembly, AllowMultiple = true)]
public sealed class DebuggerTypeProxyAttribute : Attribute
{
private string typeName;
private string targetName;
private Type target;
public DebuggerTypeProxyAttribute(Type type)
{
if (type == null)
{
throw new ArgumentNullException("type");
}
this.typeName = type.FullName + "," + type.Assembly.FullName;
}
public DebuggerTypeProxyAttribute(string typeName)
{
this.typeName = typeName;
}
public string ProxyTypeName
{
get { return typeName; }
}
public Type Target
{
set
{
if (value == null)
{
throw new ArgumentNullException("value");
}
targetName = value.FullName + "," + value.Assembly.FullName;
target = value;
}
get { return target; }
}
public string TargetTypeName
{
get { return targetName; }
set { targetName = value; }
}
}
// This attribute is used to control what is displayed for the given class or field
// in the data windows in the debugger. The single argument to this attribute is
// the string that will be displayed in the value column for instances of the type.
// This string can include text between { and } which can be either a field,
// property or method (as will be documented in mscorlib). In the C# case,
// a general expression will be allowed which only has implicit access to the this pointer
// for the current instance of the target type. The expression will be limited,
// however: there is no access to aliases, locals, or pointers.
// In addition, attributes on properties referenced in the expression are not processed.
[AttributeUsage(AttributeTargets.Class | AttributeTargets.Struct | AttributeTargets.Delegate | AttributeTargets.Enum | AttributeTargets.Field | AttributeTargets.Property | AttributeTargets.Assembly, AllowMultiple = true)]
public sealed class DebuggerDisplayAttribute : Attribute
{
private string name;
private string value;
private string type;
private string targetName;
private Type target;
public DebuggerDisplayAttribute(string value)
{
if (value == null)
{
this.value = "";
}
else
{
this.value = value;
}
name = "";
type = "";
}
public string Value
{
get { return this.value; }
}
public string Name
{
get { return name; }
set { name = value; }
}
public string Type
{
get { return type; }
set { type = value; }
}
public Type Target
{
set
{
if (value == null)
{
throw new ArgumentNullException("value");
}
targetName = value.FullName + "," + value.Assembly.FullName;
target = value;
}
get { return target; }
}
public string TargetTypeName
{
get { return targetName; }
set { targetName = value; }
}
}
}

299
_mscorlib/System/Double.cs Normal file
Просмотреть файл

@ -0,0 +1,299 @@
//
// Copyright (c) 2017 The nanoFramework project contributors
// Portions Copyright (c) Microsoft Corporation. All rights reserved.
// See LICENSE file in the project root for full license information.
//
namespace System
{
using System;
using System.Globalization;
using System.Runtime.CompilerServices;
[Serializable]
public struct Double
{
internal double m_value;
// Public Constants
// Summary:
// Represents the smallest possible value of a System.Double. This field is
// constant.
public const double MinValue = -1.7976931348623157E+308;
//
// Summary:
// Represents the largest possible value of a System.Double. This field is constant.
public const double MaxValue = 1.7976931348623157E+308;
//
// Summary:
// Represents the smallest positive System.Double value that is greater than
// zero. This field is constant.
//
// Note:
// Real value of Epsilon: 4.9406564584124654e-324 (0x1), but JVC misparses that
// number, giving 2*Epsilon (0x2).
public const double Epsilon = 4.9406564584124650E-324;
//
// Summary:
// Represents negative infinity. This field is constant.
public const double NegativeInfinity = (double)-1.0 / (double)(0.0);
//
// Summary:
// Represents positive infinity. This field is constant.
public const double PositiveInfinity = (double)1.0 / (double)(0.0);
//
// Summary:
// Represents a value that is not a number (NaN). This field is constant.
public const double NaN = 0.0 / 0.0;
//
// Summary:
// Compares this instance to a specified double-precision floating-point number
// and returns an integer that indicates whether the value of this instance
// is less than, equal to, or greater than the value of the specified double-precision
// floating-point number.
//
// Parameters:
// value:
// A double-precision floating-point number to compare.
//
// Returns:
// A signed number indicating the relative values of this instance and value.Return
// Value Description Less than zero This instance is less than value.-or- This
// instance is not a number (System.Double.NaN) and value is a number. Zero
// This instance is equal to value.-or- Both this instance and value are not
// a number (System.Double.NaN), System.Double.PositiveInfinity, or System.Double.NegativeInfinity.
// Greater than zero This instance is greater than value.-or- This instance
// is a number and value is not a number (System.Double.NaN).
[MethodImplAttribute(MethodImplOptions.InternalCall)]
public static extern int CompareTo(double d, double value);
//
// Summary:
// Returns a value indicating whether the specified number evaluates to negative
// or positive infinity
//
// Parameters:
// d:
// A double-precision floating-point number.
//
// Returns:
// true if d evaluates to System.Double.PositiveInfinity or System.Double.NegativeInfinity;
// otherwise, false.
[MethodImplAttribute(MethodImplOptions.InternalCall)]
public static extern bool IsInfinity(double d);
//
// Summary:
// Returns a value indicating whether the specified number evaluates to a value
// that is not a number (System.Double.NaN).
//
// Parameters:
// d:
// A double-precision floating-point number.
//
// Returns:
// true if d evaluates to System.Double.NaN; otherwise, false.
[MethodImplAttribute(MethodImplOptions.InternalCall)]
public static extern bool IsNaN(double d);
//
// Summary:
// Returns a value indicating whether the specified number evaluates to negative
// infinity.
//
// Parameters:
// d:
// A double-precision floating-point number.
//
// Returns:
// true if d evaluates to System.Double.NegativeInfinity; otherwise, false.
[MethodImplAttribute(MethodImplOptions.InternalCall)]
public static extern bool IsNegativeInfinity(double d);
//
// Summary:
// Returns a value indicating whether the specified number evaluates to positive
// infinity.
//
// Parameters:
// d:
// A double-precision floating-point number.
//
// Returns:
// true if d evaluates to System.Double.PositiveInfinity; otherwise, false.
[MethodImplAttribute(MethodImplOptions.InternalCall)]
public static extern bool IsPositiveInfinity(double d);
//
// Summary:
// Converts the string representation of a number in a specified style and culture-specific
// format to its double-precision floating-point number equivalent.
//
// Parameters:
// s:
// A string that contains a number to convert.
//
// style:
// A bitwise combination of enumeration values that indicate the style elements
// that can be present in s. A typical value to specify is System.Globalization.NumberStyles.Float
// combined with System.Globalization.NumberStyles.AllowThousands.
//
// provider:
// An object that supplies culture-specific formatting information about s.
//
// Returns:
// A double-precision floating-point number that is equivalent to the numeric
// value or symbol specified in s.
//
// Exceptions:
// System.ArgumentNullException:
// s is null.
//
// System.FormatException:
// s does not represent a numeric value.
//
// System.ArgumentException:
// style is not a System.Globalization.NumberStyles value. -or-style is the
// System.Globalization.NumberStyles.AllowHexSpecifier value.
//
// System.OverflowException:
// s represents a number that is less than System.Double.MinValue or greater
// than System.Double.MaxValue.
public static double Parse(String s)
{
if (s == null)
{
throw new ArgumentNullException();
}
return Convert.ToDouble(s);
}
//
// Summary:
// Converts the numeric value of this instance to its equivalent string representation.
//
// Returns:
// The string representation of the value of this instance.
public override String ToString()
{
if(IsPositiveInfinity(this))
{
return "Infinity";
}
else if(IsNegativeInfinity(this))
{
return "-Infinity";
}
else if(IsNaN(this))
{
return "NaN";
}
return Number.Format(m_value, false, "G", NumberFormatInfo.CurrentInfo);
}
//
// Summary:
// Converts the numeric value of this instance to its equivalent string representation,
// using the specified format.
//
// Parameters:
// format:
// A numeric format string.
//
// Returns:
// The string representation of the value of this instance as specified by format.
//
// Exceptions:
// System.FormatException:
// format is invalid.
public String ToString(String format)
{
if (IsPositiveInfinity(this))
{
return "Infinity";
}
else if (IsNegativeInfinity(this))
{
return "-Infinity";
}
else if (IsNaN(this))
{
return "NaN";
}
return Number.Format(m_value, false, format, NumberFormatInfo.CurrentInfo);
}
//
// Summary:
// Converts the string representation of a number to its double-precision floating-point
// number equivalent. A return value indicates whether the conversion succeeded
// or failed.
//
// Parameters:
// s:
// A string containing a number to convert.
//
// result:
// When this method returns, contains the double-precision floating-point number
// equivalent to the s parameter, if the conversion succeeded, or zero if the
// conversion failed. The conversion fails if the s parameter is null, is not
// a number in a valid format, or represents a number less than System.Double.MinValue
// or greater than System.Double.MaxValue. This parameter is passed uninitialized.
//
// Returns:
// true if s was converted successfully; otherwise, false.
public static bool TryParse(string s, out double result)
{
result = 0.0;
if (s == null)
{
return false;
}
try
{
result = Convert.ToDouble(s);
return true;
}
catch
{
result = 0.0;
}
return false;
}
//
// Summary:
// Converts the string representation of a number in a specified style and culture-specific
// format to its double-precision floating-point number equivalent. A return
// value indicates whether the conversion succeeded or failed.
//
// Parameters:
// s:
// A string containing a number to convert.
//
// style:
// A bitwise combination of System.Globalization.NumberStyles values that indicates
// the permitted format of s. A typical value to specify is System.Globalization.NumberStyles.Float
// combined with System.Globalization.NumberStyles.AllowThousands.
//
// provider:
// An System.IFormatProvider that supplies culture-specific formatting information
// about s.
//
// result:
// When this method returns, contains a double-precision floating-point number
// equivalent to the numeric value or symbol contained in s, if the conversion
// succeeded, or zero if the conversion failed. The conversion fails if the
// s parameter is null, is not in a format compliant with style, represents
// a number less than System.SByte.MinValue or greater than System.SByte.MaxValue,
// or if style is not a valid combination of System.Globalization.NumberStyles
// enumerated constants. This parameter is passed uninitialized.
//
// Returns:
// true if s was converted successfully; otherwise, false.
//
// Exceptions:
// System.ArgumentException:
// style is not a System.Globalization.NumberStyles value. -or-style includes
// the System.Globalization.NumberStyles.AllowHexSpecifier value.
// public static bool TryParse(string s, NumberStyles style, IFormatProvider provider, out double result);
}
}

27
_mscorlib/System/Enum.cs Normal file
Просмотреть файл

@ -0,0 +1,27 @@
//
// Copyright (c) 2017 The nanoFramework project contributors
// Portions Copyright (c) Microsoft Corporation. All rights reserved.
// See LICENSE file in the project root for full license information.
//
namespace System
{
using System.Reflection;
using System.Collections;
using System.Runtime.CompilerServices;
[Serializable]
public abstract class Enum : ValueType
{
public override String ToString()
{
Type eT = this.GetType();
FieldInfo fi = eT.GetField("value__");
object obj = fi.GetValue(this);
return obj.ToString();
}
}
}

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

@ -0,0 +1,77 @@
//
// Copyright (c) 2017 The nanoFramework project contributors
// Portions Copyright (c) Microsoft Corporation. All rights reserved.
// See LICENSE file in the project root for full license information.
//
namespace System
{
using System;
using System.Runtime.CompilerServices;
using System.Reflection;
[Serializable()]
public class Exception
{
private string _message;
private Exception m_innerException;
private object m_stackTrace;
protected int m_HResult;
public Exception()
{
}
public Exception(String message)
{
_message = message;
}
public Exception(String message, Exception innerException)
{
_message = message;
m_innerException = innerException;
}
public virtual String Message
{
get
{
if (_message == null)
{
return "Exception was thrown: " + this.GetType().FullName;
}
else
{
return _message;
}
}
}
public Exception InnerException
{
get { return m_innerException; }
}
public extern virtual String StackTrace
{
[MethodImplAttribute(MethodImplOptions.InternalCall)]
get;
}
public override String ToString()
{
String message = Message;
String s = base.ToString();
if (message != null && message.Length > 0)
{
s += ": " + message;
}
return s;
}
}
}

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

@ -0,0 +1,20 @@
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
// Copyright (c) Microsoft Corporation. All rights reserved.
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////namespace System
namespace System
{
using System;
/** Custom attribute to indicate that the enum
* should be treated as a bitfield (or set of flags).
* An IDE may use this information to provide a richer
* development experince.
*/
[AttributeUsage(AttributeTargets.Enum, Inherited = false), Serializable]
public class FlagsAttribute : Attribute
{
public FlagsAttribute()
{
}
}
}

32
_mscorlib/System/GC.cs Normal file
Просмотреть файл

@ -0,0 +1,32 @@
//
// Copyright (c) 2017 The nanoFramework project contributors
// Portions Copyright (c) Microsoft Corporation. All rights reserved.
// See LICENSE file in the project root for full license information.
//
namespace System
{
//This class only static members and doesn't require the serializable keyword.
using System;
using System.Runtime.CompilerServices;
public static class GC
{
[MethodImplAttribute(MethodImplOptions.InternalCall)]
private static extern bool AnyPendingFinalizers();
public static void WaitForPendingFinalizers()
{
while (AnyPendingFinalizers()) System.Threading.Thread.Sleep(10);
}
[MethodImplAttribute(MethodImplOptions.InternalCall)]
public static extern void SuppressFinalize(Object obj);
[MethodImplAttribute(MethodImplOptions.InternalCall)]
public static extern void ReRegisterForFinalize(Object obj);
}
}

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

@ -0,0 +1,247 @@
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
// Copyright (c) Microsoft Corporation. All rights reserved.
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////#define ENABLE_CROSS_APPDOMAIN
#define ENABLE_CROSS_APPDOMAIN
namespace System.Globalization
{
using System;
using System.Threading;
using System.Collections;
using System.Runtime.CompilerServices;
using System.Reflection;
using System.Resources;
public class CultureInfo /*: ICloneable , IFormatProvider*/ {
internal NumberFormatInfo numInfo = null;
internal DateTimeFormatInfo dateTimeInfo = null;
internal string m_name = null;
internal ResourceManager m_rm;
[NonSerialized]
private CultureInfo m_parent;
const string c_ResourceBase = "System.Globalization.Resources.CultureInfo";
internal string EnsureStringResource(ref string str, System.Globalization.Resources.CultureInfo.StringResources id)
{
if (str == null)
{
str = (string)ResourceManager.GetObject(m_rm, id);
}
return str;
}
internal string[] EnsureStringArrayResource(ref string[] strArray, System.Globalization.Resources.CultureInfo.StringResources id)
{
if (strArray == null)
{
string str = (string)ResourceManager.GetObject(m_rm, id);
strArray = str.Split('|');
}
return (string[])strArray.Clone();
}
public CultureInfo(string name)
{
if (name == null)
{
throw new ArgumentNullException("name");
}
m_rm = new ResourceManager(c_ResourceBase, typeof(CultureInfo).Assembly, name, true);
m_name = m_rm.m_cultureName;
}
internal CultureInfo(ResourceManager resourceManager)
{
m_rm = resourceManager;
m_name = resourceManager.m_cultureName;
}
public static CultureInfo CurrentUICulture
{
get
{
//only one system-wide culture. We do not currently support per-thread cultures
CultureInfo culture = CurrentUICultureInternal;
if (culture == null)
{
culture = new CultureInfo("");
CurrentUICultureInternal = culture;
}
return culture;
}
}
private extern static CultureInfo CurrentUICultureInternal
{
[MethodImplAttribute(MethodImplOptions.InternalCall)]
get;
[MethodImplAttribute(MethodImplOptions.InternalCall)]
set;
}
public virtual CultureInfo Parent
{
get
{
if (m_parent == null)
{
if (m_name == "") //Invariant culture
{
m_parent = this;
}
else
{
string parentName = m_name;
int iDash = m_name.LastIndexOf('-');
if (iDash >= 0)
{
parentName = parentName.Substring(0, iDash);
}
else
{
parentName = "";
}
m_parent = new CultureInfo(parentName);
}
}
return m_parent;
}
}
public static CultureInfo[] GetCultures(CultureTypes types)
{
ArrayList listCultures = new ArrayList();
//Look for all assemblies/satellite assemblies
Assembly[] assemblies = AppDomain.CurrentDomain.GetAssemblies();
for (int iAssembly = 0; iAssembly < assemblies.Length; iAssembly++)
{
Assembly assembly = assemblies[iAssembly];
string mscorlib = "mscorlib";
string fullName = assembly.FullName;
// consider adding startswith ?
if ((mscorlib.Length <= fullName.Length) && (fullName.Substring(0, mscorlib.Length) == mscorlib))
{
string[] resources = assembly.GetManifestResourceNames();
for (int iResource = 0; iResource < resources.Length; iResource++)
{
string resource = resources[iResource];
string ciResource = c_ResourceBase;
if (ciResource.Length < resource.Length && resource.Substring(0, ciResource.Length) == ciResource)
{
//System.Globalization.Resources.CultureInfo.<culture>.tinyresources
string cultureName = resource.Substring(ciResource.Length, resource.Length - ciResource.Length - System.Resources.ResourceManager.s_fileExtension.Length);
// remove the leading "."
if (cultureName != "")
{
cultureName = cultureName.Substring(1, cultureName.Length - 1);
}
// if GetManifestResourceNames() changes, we need to change this code to ensure the index is the same.
listCultures.Add(new CultureInfo(new ResourceManager(c_ResourceBase, cultureName, iResource, typeof(CultureInfo).Assembly, assembly)));
}
}
}
}
return (CultureInfo[])listCultures.ToArray(typeof(CultureInfo));
}
public virtual String Name
{
get
{
return m_name;
}
}
public override String ToString()
{
return m_name;
}
// public virtual Object GetFormat(Type formatType) {
// if (formatType == typeof(NumberFormatInfo)) {
// return (NumberFormat);
// }
// if (formatType == typeof(DateTimeFormatInfo)) {
// return (DateTimeFormat);
// }
// return (null);
// }
// internal static void CheckNeutral(CultureInfo culture) {
// if (culture.IsNeutralCulture) {
// BCLDebug.Assert(culture.m_name != null, "[CultureInfo.CheckNeutral]Always expect m_name to be set");
// throw new NotSupportedException(
// Environment.GetResourceString("Argument_CultureInvalidFormat",
// culture.m_name));
// }
// }
// [System.Runtime.InteropServices.ComVisible(false)]
// public CultureTypes CultureTypes
// {
// get
// {
// CultureTypes types = 0;
// if (m_cultureTableRecord.IsNeutralCulture)
// types |= CultureTypes.NeutralCultures;
// else
// types |= CultureTypes.SpecificCultures;
// if (m_cultureTableRecord.IsSynthetic)
// types |= CultureTypes.WindowsOnlyCultures | CultureTypes.InstalledWin32Cultures; // Synthetic is installed culture too.
// else
// {
// // Not Synthetic
// if (CultureTable.IsInstalledLCID(cultureID))
// types |= CultureTypes.InstalledWin32Cultures;
// if (!m_cultureTableRecord.IsCustomCulture || m_cultureTableRecord.IsReplacementCulture)
// types |= CultureTypes.FrameworkCultures;
// }
// if (m_cultureTableRecord.IsCustomCulture)
// {
// types |= CultureTypes.UserCustomCulture;
// if (m_cultureTableRecord.IsReplacementCulture)
// types |= CultureTypes.ReplacementCultures;
// }
// return types;
// }
// }
public virtual NumberFormatInfo NumberFormat {
get {
if(numInfo == null)
{
numInfo = new NumberFormatInfo(this);
}
return numInfo;
}
}
public virtual DateTimeFormatInfo DateTimeFormat
{
get
{
if (dateTimeInfo == null)
{
dateTimeInfo = new DateTimeFormatInfo(this);
}
return dateTimeInfo;
}
}
}
}

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

@ -0,0 +1,27 @@
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
// Copyright (c) Microsoft Corporation. All rights reserved.
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////#define ENABLE_CROSS_APPDOMAIN
#define ENABLE_CROSS_APPDOMAIN
namespace System.Globalization
{
using System;
using System.Threading;
using System.Collections;
using System.Runtime.CompilerServices;
using System.Reflection;
using System.Resources;
public enum CultureTypes
{
AllCultures,
FrameworkCultures,
InstalledWin32Cultures,
NeutralCultures,
ReplacementCultures,
SpecificCultures,
UserCustomCulture,
WindowsOnlyCultures
}
}

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

@ -0,0 +1,549 @@
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
// Copyright (c) Microsoft Corporation. All rights reserved.
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////namespace System.Globalization
namespace System.Globalization
{
using System;
using System.Threading;
using ArrayList = System.Collections.ArrayList;
using System.Runtime.CompilerServices;
/*
Customized format patterns:
P.S. Format in the table below is the internal number format used to display the pattern.
Patterns Format Description Example
========= ========== ===================================== ========
"h" "0" hour (12-hour clock)w/o leading zero 3
"hh" "00" hour (12-hour clock)with leading zero 03
"hh*" "00" hour (12-hour clock)with leading zero 03
"H" "0" hour (24-hour clock)w/o leading zero 8
"HH" "00" hour (24-hour clock)with leading zero 08
"HH*" "00" hour (24-hour clock) 08
"m" "0" minute w/o leading zero
"mm" "00" minute with leading zero
"mm*" "00" minute with leading zero
"s" "0" second w/o leading zero
"ss" "00" second with leading zero
"ss*" "00" second with leading zero
"f" "0" second fraction (1 digit)
"ff" "00" second fraction (2 digit)
"fff" "000" second fraction (3 digit)
"ffff" "0000" second fraction (4 digit)
"fffff" "00000" second fraction (5 digit)
"ffffff" "000000" second fraction (6 digit)
"fffffff" "0000000" second fraction (7 digit)
"F" "0" second fraction (up to 1 digit)
"FF" "00" second fraction (up to 2 digit)
"FFF" "000" second fraction (up to 3 digit)
"FFFF" "0000" second fraction (up to 4 digit)
"FFFFF" "00000" second fraction (up to 5 digit)
"FFFFFF" "000000" second fraction (up to 6 digit)
"FFFFFFF" "0000000" second fraction (up to 7 digit)
"t" first character of AM/PM designator A
"tt" AM/PM designator AM
"tt*" AM/PM designator PM
"d" "0" day w/o leading zero 1
"dd" "00" day with leading zero 01
"ddd" short weekday name (abbreviation) Mon
"dddd" full weekday name Monday
"dddd*" full weekday name Monday
"M" "0" month w/o leading zero 2
"MM" "00" month with leading zero 02
"MMM" short month name (abbreviation) Feb
"MMMM" full month name Febuary
"MMMM*" full month name Febuary
"y" "0" two digit year (year % 100) w/o leading zero 0
"yy" "00" two digit year (year % 100) with leading zero 00
"yyy" "D3" year 2000
"yyyy" "D4" year 2000
"yyyyy" "D5" year 2000
...
"z" "+0;-0" timezone offset w/o leading zero -8
"zz" "+00;-00" timezone offset with leading zero -08
"zzz" "+00;-00" for hour offset, "00" for minute offset full timezone offset -08:00
"zzz*" "+00;-00" for hour offset, "00" for minute offset full timezone offset -08:00
"K" -Local "zzz", e.g. -08:00
-Utc "'Z'", representing UTC
-Unspecified ""
"g*" the current era name A.D.
":" time separator :
"/" date separator /
"'" quoted string 'ABC' will insert ABC into the formatted string.
'"' quoted string "ABC" will insert ABC into the formatted string.
"%" used to quote a single pattern characters E.g.The format character "%y" is to print two digit year.
"\" escaped character E.g. '\d' insert the character 'd' into the format string.
other characters insert the character into the format string.
Pre-defined format characters:
(U) to indicate Universal time is used.
(G) to indicate Gregorian calendar is used.
Format Description Real format Example
========= ================================= ====================== =======================
"d" short date culture-specific 10/31/1999
"D" long data culture-specific Sunday, October 31, 1999
"f" full date (long date + short time) culture-specific Sunday, October 31, 1999 2:00 AM
"F" full date (long date + long time) culture-specific Sunday, October 31, 1999 2:00:00 AM
"g" general date (short date + short time) culture-specific 10/31/1999 2:00 AM
"G" general date (short date + long time) culture-specific 10/31/1999 2:00:00 AM
"m"/"M" Month/Day date culture-specific October 31
(G) "o"/"O" Round Trip XML "yyyy-MM-ddTHH:mm:ss.fffffffK" 1999-10-31 02:00:00.0000000Z
(G) "r"/"R" RFC 1123 date, "ddd, dd MMM yyyy HH':'mm':'ss 'GMT'" Sun, 31 Oct 1999 10:00:00 GMT
(G) "s" Sortable format, based on ISO 8601. "yyyy-MM-dd'T'HH:mm:ss" 1999-10-31T02:00:00
('T' for local time)
"t" short time culture-specific 2:00 AM
"T" long time culture-specific 2:00:00 AM
(G) "u" Universal time with sortable format, "yyyy'-'MM'-'dd HH':'mm':'ss'Z'" 1999-10-31 10:00:00Z
based on ISO 8601.
(U) "U" Universal time with full culture-specific Sunday, October 31, 1999 10:00:00 AM
(long date + long time) format
"y"/"Y" Year/Month day culture-specific October, 1999
*/
//This class contains only static members and does not require the serializable attribute.
internal static
class DateTimeFormat
{
internal const int MaxSecondsFractionDigits = 3;
////////////////////////////////////////////////////////////////////////////
//
// Format the positive integer value to a string and perfix with assigned
// length of leading zero.
//
// Parameters:
// value: The value to format
// len: The maximum length for leading zero.
// If the digits of the value is greater than len, no leading zero is added.
// (If len > 2, we'll treat it as 2)
//
// Notes:
// The function can format to Int32.MaxValue.
//
////////////////////////////////////////////////////////////////////////////
[MethodImplAttribute(MethodImplOptions.InternalCall)]
private static extern String FormatDigits(int value, int len);
static int ParseRepeatPattern(String format, int pos, char patternChar)
{
int len = format.Length;
int index = pos + 1;
while ((index < len) && (format[index] == patternChar))
{
index++;
}
return (index - pos);
}
//
// The pos should point to a quote character. This method will
// get the string encloed by the quote character.
//
internal static String ParseQuoteString(String format, int pos, out int count)
{
//
// NOTE : pos will be the index of the quote character in the 'format' string.
//
String result = String.Empty;
int formatLen = format.Length;
int beginPos = pos;
char quoteChar = format[pos++]; // Get the character used to quote the following string.
bool foundQuote = false;
while (pos < formatLen)
{
char ch = format[pos++];
if (ch == quoteChar)
{
foundQuote = true;
break;
}
else if (ch == '\\')
{
// The following are used to support escaped character.
// Escaped character is also supported in the quoted string.
// Therefore, someone can use a format like "'minute:' mm\"" to display:
// minute: 45"
// because the second double quote is escaped.
if (pos < formatLen)
{
result += format[pos++];
}
else
{
//
// This means that '\' is at the end of the formatting string.
//
throw new ArgumentException("Format_InvalidString");
//throw new FormatException( Environment.GetResourceString( "Format_InvalidString" ) );
}
}
else
{
result += ch;
}
}
if (!foundQuote)
{
// Here we can't find the matching quote.
throw new ArgumentException("Format_BadQuote");
}
//
// Return the character count including the begin/end quote characters and enclosed string.
//
count = pos - beginPos;
return result;
}
//
// Get the next character at the index of 'pos' in the 'format' string.
// Return value of -1 means 'pos' is already at the end of the 'format' string.
// Otherwise, return value is the int value of the next character.
//
private static int ParseNextChar(String format, int pos)
{
if (pos >= format.Length - 1)
{
return (-1);
}
return ((int)format[pos + 1]);
}
//
// FormatCustomized
//
// Actions: Format the DateTime instance using the specified format.
//
private static String FormatCustomized(DateTime dateTime, String format, DateTimeFormatInfo dtfi)
{
String result = String.Empty;
int i = 0;
int tokenLen = 1, hour12;
int formatLen = format.Length;
while (i < formatLen)
{
char ch = format[i];
int nextChar;
bool doneParsingCh = true;
String tempResult = String.Empty;
switch (ch)
{
case ':':
tempResult = dtfi.TimeSeparator;
tokenLen = 1;
break;
case '/':
tempResult = dtfi.DateSeparator;
tokenLen = 1;
break;
case '\'':
case '\"':
tempResult = ParseQuoteString(format, i, out tokenLen);
break;
case '%':
// Optional format character.
// For example, format string "%d" will print day of month
// without leading zero. Most of the cases, "%" can be ignored.
nextChar = ParseNextChar(format, i);
// nextChar will be -1 if we already reach the end of the format string.
// Besides, we will not allow "%%" appear in the pattern.
if (nextChar >= 0 && nextChar != (int)'%')
{
tempResult = FormatCustomized(dateTime, ((char)nextChar).ToString(), dtfi);
tokenLen = 2;
}
else
{
//
// This means that '%' is at the end of the format string or
// "%%" appears in the format string.
//
throw new ArgumentException("Format_InvalidString");
}
break;
case '\\':
// Escaped character. Can be used to insert character into the format string.
// For exmple, "\d" will insert the character 'd' into the string.
//
// NOTENOTE : we can remove this format character if we enforce the enforced quote
// character rule.
// That is, we ask everyone to use single quote or double quote to insert characters,
// then we can remove this character.
//
nextChar = ParseNextChar(format, i);
if (nextChar >= 0)
{
tempResult = ((char)nextChar).ToString();
tokenLen = 2;
}
else
{
//
// This means that '\' is at the end of the formatting string.
//
throw new ArgumentException("Format_InvalidString");
}
break;
default:
doneParsingCh = false;
break;
}
if (!doneParsingCh)
{
tokenLen = ParseRepeatPattern(format, i, ch);
switch (ch)
{
case 'h':
hour12 = dateTime.Hour % 12;
if (hour12 == 0)
{
hour12 = 12;
}
tempResult = FormatDigits(hour12, tokenLen);
break;
case 'H':
tempResult = FormatDigits(dateTime.Hour, tokenLen);
break;
case 'm':
tempResult = FormatDigits(dateTime.Minute, tokenLen);
break;
case 's':
tempResult = FormatDigits(dateTime.Second, tokenLen);
break;
case 'f':
if (tokenLen <= MaxSecondsFractionDigits)
{
int precision = 3;
int fraction = dateTime.Millisecond;
// Note: Need to add special case when tokenLen > precision to begin with
// if we're to change MaxSecondsFractionDigits to be more than 3
while (tokenLen < precision)
{
fraction /= 10;
precision--;
}
tempResult = FormatDigits(fraction, tokenLen);
}
else
{
throw new ArgumentException("Format_InvalidString");
}
break;
case 't':
if (tokenLen == 1)
{
if (dateTime.Hour < 12)
{
if (dtfi.AMDesignator.Length >= 1)
{
tempResult = dtfi.AMDesignator[0].ToString();
}
}
else
{
if (dtfi.PMDesignator.Length >= 1)
{
tempResult = dtfi.PMDesignator[0].ToString();
}
}
}
else
{
tempResult = (dateTime.Hour < 12 ? dtfi.AMDesignator : dtfi.PMDesignator);
}
break;
case 'd':
//
// tokenLen == 1 : Day of month as digits with no leading zero.
// tokenLen == 2 : Day of month as digits with leading zero for single-digit months.
// tokenLen == 3 : Day of week as a three-leter abbreviation.
// tokenLen >= 4 : Day of week as its full name.
//
if (tokenLen <= 2)
{
tempResult = FormatDigits(dateTime.Day, tokenLen);
}
else
{
int dayOfWeek = (int)dateTime.DayOfWeek;
if (tokenLen == 3)
{
tempResult = dtfi.AbbreviatedDayNames[dayOfWeek];
}
else
{
tempResult = dtfi.DayNames[dayOfWeek];
}
}
break;
case 'M':
//
// tokenLen == 1 : Month as digits with no leading zero.
// tokenLen == 2 : Month as digits with leading zero for single-digit months.
// tokenLen == 3 : Month as a three-letter abbreviation.
// tokenLen >= 4 : Month as its full name.
//
int month = dateTime.Month;
if (tokenLen <= 2)
{
tempResult = FormatDigits(month, tokenLen);
}
else
{
if (tokenLen == 3)
{
tempResult = dtfi.AbbreviatedMonthNames[month - 1];
}
else
{
tempResult = dtfi.MonthNames[month - 1];
}
}
break;
case 'y':
// Notes about OS behavior:
// y: Always print (year % 100). No leading zero.
// yy: Always print (year % 100) with leading zero.
// yyy/yyyy/yyyyy/... : Print year value. With leading zeros.
int year = dateTime.Year;
if (tokenLen <= 2)
{
tempResult = FormatDigits(year % 100, tokenLen);
}
else
{
tempResult = year.ToString();
}
if (tempResult.Length < tokenLen)
{
tempResult = new string('0', tokenLen - tempResult.Length) + tempResult;
}
break;
default:
if (tokenLen == 1)
{
tempResult = ch.ToString();
}
else
{
tempResult = new String(ch, tokenLen);
}
break;
}
}
result += tempResult;
i += tokenLen;
}
return result;
}
internal static String GetRealFormat(String format, DateTimeFormatInfo dtfi)
{
String realFormat = null;
switch (format[0])
{
case 'd': // Short Date
realFormat = dtfi.ShortDatePattern;
break;
case 'D': // Long Date
realFormat = dtfi.LongDatePattern;
break;
case 'f': // Full (long date + short time)
realFormat = dtfi.LongDatePattern + " " + dtfi.ShortTimePattern;
break;
case 'F': // Full (long date + long time)
realFormat = dtfi.FullDateTimePattern;
break;
case 'g': // General (short date + short time)
realFormat = dtfi.GeneralShortTimePattern;
break;
case 'G': // General (short date + long time)
realFormat = dtfi.GeneralLongTimePattern;
break;
case 'm':
case 'M': // Month/Day Date
realFormat = dtfi.MonthDayPattern;
break;
case 'r':
case 'R': // RFC 1123 Standard
realFormat = dtfi.RFC1123Pattern;
break;
case 's': // Sortable without Time Zone Info
realFormat = dtfi.SortableDateTimePattern;
break;
case 't': // Short Time
realFormat = dtfi.ShortTimePattern;
break;
case 'T': // Long Time
realFormat = dtfi.LongTimePattern;
break;
case 'u': // Universal with Sortable format
realFormat = dtfi.UniversalSortableDateTimePattern;
break;
case 'U': // Universal with Full (long date + long time) format
realFormat = dtfi.FullDateTimePattern;
break;
case 'y':
case 'Y': // Year/Month Date
realFormat = dtfi.YearMonthPattern;
break;
default:
throw new ArgumentException("Format_InvalidString");
}
return (realFormat);
}
internal static String Format(DateTime dateTime, String format, DateTimeFormatInfo dtfi)
{
if (format == null || format.Length == 0)
{
format = "G";
}
if (format.Length == 1)
{
format = GetRealFormat(format, dtfi);
}
return (FormatCustomized(dateTime, format, dtfi));
}
}
}

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

@ -0,0 +1,228 @@
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
// Copyright (c) Microsoft Corporation. All rights reserved.
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////#define ENABLE_CROSS_APPDOMAIN
#define ENABLE_CROSS_APPDOMAIN
namespace System.Globalization
{
using System;
using System.Collections;
public sealed class DateTimeFormatInfo /*: ICloneable, IFormatProvider*/
{
internal String amDesignator = null;
internal String pmDesignator = null;
internal String dateSeparator = null;
internal String longTimePattern = null;
internal String shortTimePattern = null;
internal String generalShortTimePattern = null;
internal String generalLongTimePattern = null;
internal String timeSeparator = null;
internal String monthDayPattern = null;
internal const String rfc1123Pattern = "ddd, dd MMM yyyy HH':'mm':'ss 'GMT'";
internal const String sortableDateTimePattern = "yyyy'-'MM'-'dd'T'HH':'mm':'ss";
internal const String universalSortableDateTimePattern = "yyyy'-'MM'-'dd HH':'mm':'ss'Z'";
internal String fullDateTimePattern = null;
internal String longDatePattern = null;
internal String shortDatePattern = null;
internal String yearMonthPattern = null;
internal String[] abbreviatedDayNames = null;
internal String[] dayNames = null;
internal String[] abbreviatedMonthNames = null;
internal String[] monthNames = null;
CultureInfo m_cultureInfo;
internal DateTimeFormatInfo(CultureInfo cultureInfo)
{
m_cultureInfo = cultureInfo;
}
public static DateTimeFormatInfo CurrentInfo
{
get
{
return CultureInfo.CurrentUICulture.DateTimeFormat;
}
}
public String AMDesignator
{
get
{
return m_cultureInfo.EnsureStringResource(ref this.amDesignator, System.Globalization.Resources.CultureInfo.StringResources.AMDesignator);
}
}
public String DateSeparator
{
get
{
return m_cultureInfo.EnsureStringResource(ref this.dateSeparator, System.Globalization.Resources.CultureInfo.StringResources.DateSeparator);
}
}
public String FullDateTimePattern
{
get
{
if (fullDateTimePattern == null)
{
fullDateTimePattern = LongDatePattern + " " + LongTimePattern;
}
return (fullDateTimePattern);
}
}
public String LongDatePattern
{
get
{
return m_cultureInfo.EnsureStringResource(ref longDatePattern, System.Globalization.Resources.CultureInfo.StringResources.LongDatePattern);
}
}
public String LongTimePattern
{
get
{
return m_cultureInfo.EnsureStringResource(ref this.longTimePattern, System.Globalization.Resources.CultureInfo.StringResources.LongTimePattern);
}
}
public String MonthDayPattern
{
get
{
return m_cultureInfo.EnsureStringResource(ref this.monthDayPattern, System.Globalization.Resources.CultureInfo.StringResources.MonthDayPattern);
}
}
public String PMDesignator
{
get
{
return m_cultureInfo.EnsureStringResource(ref this.pmDesignator, System.Globalization.Resources.CultureInfo.StringResources.PMDesignator);
}
}
public String RFC1123Pattern
{
get
{
return (rfc1123Pattern);
}
}
public String ShortDatePattern
{
get
{
return m_cultureInfo.EnsureStringResource(ref this.shortDatePattern, System.Globalization.Resources.CultureInfo.StringResources.ShortDatePattern);
}
}
public String ShortTimePattern
{
get
{
return m_cultureInfo.EnsureStringResource(ref this.shortTimePattern, System.Globalization.Resources.CultureInfo.StringResources.ShortTimePattern);
}
}
public String SortableDateTimePattern
{
get
{
return (sortableDateTimePattern);
}
}
internal String GeneralShortTimePattern
{
get
{
if (generalShortTimePattern == null)
{
generalShortTimePattern = ShortDatePattern + " " + ShortTimePattern;
}
return (generalShortTimePattern);
}
}
/*=================================GeneralLongTimePattern=====================
**Property: Return the pattern for 'g' general format: shortDate + Long time
**Note: This is used by DateTimeFormat.cs to get the pattern for 'g'
** We put this internal property here so that we can avoid doing the
** concatation every time somebody asks for the general format.
==============================================================================*/
internal String GeneralLongTimePattern
{
get
{
if (generalLongTimePattern == null)
{
generalLongTimePattern = ShortDatePattern + " " + LongTimePattern;
}
return (generalLongTimePattern);
}
}
public String TimeSeparator
{
get
{
return m_cultureInfo.EnsureStringResource(ref this.timeSeparator, System.Globalization.Resources.CultureInfo.StringResources.TimeSeparator);
}
}
public String UniversalSortableDateTimePattern
{
get
{
return (universalSortableDateTimePattern);
}
}
public String YearMonthPattern
{
get
{
return m_cultureInfo.EnsureStringResource(ref this.yearMonthPattern, System.Globalization.Resources.CultureInfo.StringResources.YearMonthPattern);
}
}
public String[] AbbreviatedDayNames
{
get
{
return m_cultureInfo.EnsureStringArrayResource(ref abbreviatedDayNames, System.Globalization.Resources.CultureInfo.StringResources.AbbreviatedDayNames);
}
}
public String[] DayNames
{
get
{
return m_cultureInfo.EnsureStringArrayResource(ref dayNames, System.Globalization.Resources.CultureInfo.StringResources.DayNames);
}
}
public String[] AbbreviatedMonthNames
{
get
{
return m_cultureInfo.EnsureStringArrayResource(ref abbreviatedMonthNames, System.Globalization.Resources.CultureInfo.StringResources.AbbreviatedMonthNames);
}
}
public String[] MonthNames
{
get
{
return m_cultureInfo.EnsureStringArrayResource(ref monthNames, System.Globalization.Resources.CultureInfo.StringResources.MonthNames);
}
}
}
}

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

@ -0,0 +1,64 @@
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
// Copyright (c) Microsoft Corporation. All rights reserved.
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////namespace System.Globalization
namespace System.Globalization
{
using System;
/**
* This class represents a starting/ending time for a period of daylight saving time.
*/
[Serializable]
public class DaylightTime
{
internal DateTime m_start;
internal DateTime m_end;
internal TimeSpan m_delta;
private DaylightTime()
{
}
public DaylightTime(DateTime start, DateTime end, TimeSpan delta)
{
m_start = start;
m_end = end;
m_delta = delta;
}
/**
* The start date of a daylight saving period.
*/
public DateTime Start
{
get
{
return m_start;
}
}
/**
* The end date of a daylight saving period.
*/
public DateTime End
{
get
{
return m_end;
}
}
/**
* Delta to stardard offset in ticks.
*/
public TimeSpan Delta
{
get
{
return m_delta;
}
}
}
}

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

@ -0,0 +1,126 @@
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
// Copyright (c) Microsoft Corporation. All rights reserved.
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////namespace System.Globalization
namespace System.Globalization
{
using System;
//
// Property Default Description
// PositiveSign '+' Character used to indicate positive values.
// NegativeSign '-' Character used to indicate negative values.
// NumberDecimalSeparator '.' The character used as the decimal separator.
// NumberGroupSeparator ',' The character used to separate groups of
// digits to the left of the decimal point.
// NumberDecimalDigits 2 The default number of decimal places.
// NumberGroupSizes 3 The number of digits in each group to the
// left of the decimal point.
// NaNSymbol "NaN" The string used to represent NaN values.
// PositiveInfinitySymbol"Infinity" The string used to represent positive
// infinities.
// NegativeInfinitySymbol"-Infinity" The string used to represent negative
// infinities.
//
//
//
// Property Default Description
// CurrencyDecimalSeparator '.' The character used as the decimal
// separator.
// CurrencyGroupSeparator ',' The character used to separate groups
// of digits to the left of the decimal
// point.
// CurrencyDecimalDigits 2 The default number of decimal places.
// CurrencyGroupSizes 3 The number of digits in each group to
// the left of the decimal point.
// CurrencyPositivePattern 0 The format of positive values.
// CurrencyNegativePattern 0 The format of negative values.
// CurrencySymbol "$" String used as local monetary symbol.
//
[Serializable]
sealed public class NumberFormatInfo /*: ICloneable, IFormatProvider*/
{
internal int[] numberGroupSizes = null;//new int[] { 3 };
internal String positiveSign = null;//"+";
internal String negativeSign = null;//"-";
internal String numberDecimalSeparator = null;//".";
internal String numberGroupSeparator = null;//",";
private CultureInfo m_cultureInfo;
internal NumberFormatInfo(CultureInfo cultureInfo)
{
m_cultureInfo = cultureInfo;
}
public int[] NumberGroupSizes
{
get
{
if (numberGroupSizes == null)
{
String sizesStr = null;
m_cultureInfo.EnsureStringResource(ref sizesStr, System.Globalization.Resources.CultureInfo.StringResources.NumberGroupSizes);
int sizesLen = sizesStr.Length;
numberGroupSizes = new int[sizesLen];
int size;
for (int i = 0; i < sizesLen; i++)
{
size = sizesStr[i] - '0';
if (size > 9 || size < 0)
{
numberGroupSizes = null;
throw new InvalidOperationException();
}
numberGroupSizes[i] = size;
}
}
return ((int[])numberGroupSizes.Clone());
}
}
public static NumberFormatInfo CurrentInfo
{
get
{
return CultureInfo.CurrentUICulture.NumberFormat;
}
}
public String NegativeSign
{
get
{
return m_cultureInfo.EnsureStringResource(ref this.negativeSign, System.Globalization.Resources.CultureInfo.StringResources.NegativeSign);
}
}
public String NumberDecimalSeparator
{
get
{
return m_cultureInfo.EnsureStringResource(ref this.numberDecimalSeparator, System.Globalization.Resources.CultureInfo.StringResources.NumberDecimalSeparator);
}
}
public String NumberGroupSeparator
{
get
{
return m_cultureInfo.EnsureStringResource(ref this.numberGroupSeparator, System.Globalization.Resources.CultureInfo.StringResources.NumberGroupSeparator);
}
}
public String PositiveSign
{
get
{
return m_cultureInfo.EnsureStringResource(ref this.positiveSign, System.Globalization.Resources.CultureInfo.StringResources.PositiveSign);
}
}
} // NumberFormatInfo
}

61
_mscorlib/System/Globalization/Resources/CultureInfo.designer.cs сгенерированный Normal file
Просмотреть файл

@ -0,0 +1,61 @@
//------------------------------------------------------------------------------
// <auto-generated>
// This code was generated by a tool.
// Runtime Version:2.0.50215.44
//
// Changes to this file may cause incorrect behavior and will be lost if
// the code is regenerated.
// </auto-generated>
//------------------------------------------------------------------------------
namespace System.Globalization.Resources
{
internal class CultureInfo
{
private static System.Resources.ResourceManager manager;
internal static System.Resources.ResourceManager ResourceManager
{
get
{
if ((CultureInfo.manager == null))
{
CultureInfo.manager = new System.Resources.ResourceManager("System.Globalization.Resources.CultureInfo", typeof(CultureInfo).Assembly);
}
return CultureInfo.manager;
}
}
internal static string GetString(CultureInfo.StringResources id)
{
return ((string)(System.Resources.ResourceManager.GetObject(ResourceManager, id)));
}
[System.SerializableAttribute()]
internal enum StringResources : short
{
LongDatePattern = -30643,
PositiveSign = -24864,
DayNames = -21087,
NumberDecimalSeparator = -20751,
ShortDatePattern = -19957,
NumberGroupSeparator = -15642,
AMDesignator = -15501,
ShortTimePattern = -14376,
NegativeSign = -11738,
PMDesignator = -6760,
YearMonthPattern = 3936,
MonthNames = 7086,
AbbreviatedDayNames = 9268,
NumberGroupSizes = 9393,
TimeSeparator = 9689,
MonthDayPattern = 11943,
DateSeparator = 21845,
AbbreviatedMonthNames = 25574,
LongTimePattern = 30813,
}
}
}

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

@ -0,0 +1,144 @@
<?xml version="1.0" encoding="utf-8"?>
<root>
<!--
Microsoft ResX Schema
Version 2.0
The primary goals of this format is to allow a simple XML format
that is mostly human readable. The generation and parsing of the
various data types are done through the TypeConverter classes
associated with the data types.
Example:
... ado.net/XML headers & schema ...
<resheader name="resmimetype">text/microsoft-resx</resheader>
<resheader name="version">2.0</resheader>
<resheader name="reader">System.Resources.ResXResourceReader, System.Windows.Forms, ...</resheader>
<resheader name="writer">System.Resources.ResXResourceWriter, System.Windows.Forms, ...</resheader>
<data name="Name1"><value>this is my long string</value><comment>this is a comment</comment></data>
<data name="Color1" type="System.Drawing.Color, System.Drawing">Blue</data>
<data name="Bitmap1" mimetype="application/x-microsoft.net.object.binary.base64">
<value>[base64 mime encoded serialized .NET Framework object]</value>
</data>
<data name="Icon1" type="System.Drawing.Icon, System.Drawing" mimetype="application/x-microsoft.net.object.bytearray.base64">
<value>[base64 mime encoded string representing a byte array form of the .NET Framework object]</value>
<comment>This is a comment</comment>
</data>
There are any number of "resheader" rows that contain simple
name/value pairs.
Each data row contains a name, and value. The row also contains a
type or mimetype. Type corresponds to a .NET class that support
text/value conversion through the TypeConverter architecture.
Classes that don't support this are serialized and stored with the
mimetype set.
The mimetype is used for serialized objects, and tells the
ResXResourceReader how to depersist the object. This is currently not
extensible. For a given mimetype the value must be set accordingly:
Note - application/x-microsoft.net.object.binary.base64 is the format
that the ResXResourceWriter will generate, however the reader can
read any of the formats listed below.
mimetype: application/x-microsoft.net.object.binary.base64
value : The object must be serialized with
: System.Runtime.Serialization.Formatters.Binary.BinaryFormatter
: and then encoded with base64 encoding.
mimetype: application/x-microsoft.net.object.soap.base64
value : The object must be serialized with
: System.Runtime.Serialization.Formatters.Soap.SoapFormatter
: and then encoded with base64 encoding.
mimetype: application/x-microsoft.net.object.bytearray.base64
value : The object must be serialized into a byte array
: using a System.ComponentModel.TypeConverter
: and then encoded with base64 encoding.
-->
<xsd:schema id="root" xmlns="" xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns:msdata="urn:schemas-microsoft-com:xml-msdata">
<xsd:element name="root" msdata:IsDataSet="true">
<xsd:complexType>
<xsd:choice maxOccurs="unbounded">
<xsd:element name="metadata">
<xsd:complexType>
<xsd:sequence>
<xsd:element name="value" type="xsd:string" minOccurs="0" />
</xsd:sequence>
<xsd:attribute name="name" use="required" type="xsd:string" />
<xsd:attribute name="type" type="xsd:string" />
<xsd:attribute name="mimetype" type="xsd:string" />
</xsd:complexType>
</xsd:element>
<xsd:element name="assembly">
<xsd:complexType>
<xsd:attribute name="alias" type="xsd:string" />
<xsd:attribute name="name" type="xsd:string" />
</xsd:complexType>
</xsd:element>
<xsd:element name="data">
<xsd:complexType>
<xsd:sequence>
<xsd:element name="value" type="xsd:string" minOccurs="0" msdata:Ordinal="1" />
<xsd:element name="comment" type="xsd:string" minOccurs="0" msdata:Ordinal="2" />
</xsd:sequence>
<xsd:attribute name="name" type="xsd:string" use="required" msdata:Ordinal="1" />
<xsd:attribute name="type" type="xsd:string" msdata:Ordinal="3" />
<xsd:attribute name="mimetype" type="xsd:string" msdata:Ordinal="4" />
</xsd:complexType>
</xsd:element>
<xsd:element name="resheader">
<xsd:complexType>
<xsd:sequence>
<xsd:element name="value" type="xsd:string" minOccurs="0" msdata:Ordinal="1" />
</xsd:sequence>
<xsd:attribute name="name" type="xsd:string" use="required" />
</xsd:complexType>
</xsd:element>
</xsd:choice>
</xsd:complexType>
</xsd:element>
</xsd:schema>
<resheader name="resmimetype">
<value>text/microsoft-resx</value>
</resheader>
<resheader name="version">
<value>2.0</value>
</resheader>
<resheader name="reader">
<value>System.Resources.ResXResourceReader, System.Windows.Forms, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089</value>
</resheader>
<resheader name="writer">
<value>System.Resources.ResXResourceWriter, System.Windows.Forms, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089</value>
</resheader>
<data name="FullDateTimePattern">
<value xml:space="preserve">dddd, MMMM dd, yyyy h:mm:ss tt</value>
</data>
<data name="GeneralLongTimePattern">
<value xml:space="preserve">M/d/yyyy h:mm:ss tt</value>
</data>
<data name="GeneralShortTimePattern">
<value xml:space="preserve">M/d/yyyy h:mm tt</value>
</data>
<data name="LongDatePattern">
<value xml:space="preserve">dddd, MMMM dd, yyyy</value>
</data>
<data name="LongTimePattern">
<value xml:space="preserve">h:mm:ss tt</value>
</data>
<data name="MonthDayPattern">
<value xml:space="preserve">MMMM dd</value>
</data>
<data name="ShortDatePattern">
<value xml:space="preserve">M/d/yyyy</value>
</data>
<data name="ShortTimePattern">
<value xml:space="preserve">h:mm tt</value>
</data>
<data name="YearMonthPattern">
<value xml:space="preserve">MMMM, yyyy</value>
</data>
</root>

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

@ -0,0 +1,174 @@
<?xml version="1.0" encoding="utf-8"?>
<root>
<!--
Microsoft ResX Schema
Version 2.0
The primary goals of this format is to allow a simple XML format
that is mostly human readable. The generation and parsing of the
various data types are done through the TypeConverter classes
associated with the data types.
Example:
... ado.net/XML headers & schema ...
<resheader name="resmimetype">text/microsoft-resx</resheader>
<resheader name="version">2.0</resheader>
<resheader name="reader">System.Resources.ResXResourceReader, System.Windows.Forms, ...</resheader>
<resheader name="writer">System.Resources.ResXResourceWriter, System.Windows.Forms, ...</resheader>
<data name="Name1"><value>this is my long string</value><comment>this is a comment</comment></data>
<data name="Color1" type="System.Drawing.Color, System.Drawing">Blue</data>
<data name="Bitmap1" mimetype="application/x-microsoft.net.object.binary.base64">
<value>[base64 mime encoded serialized .NET Framework object]</value>
</data>
<data name="Icon1" type="System.Drawing.Icon, System.Drawing" mimetype="application/x-microsoft.net.object.bytearray.base64">
<value>[base64 mime encoded string representing a byte array form of the .NET Framework object]</value>
<comment>This is a comment</comment>
</data>
There are any number of "resheader" rows that contain simple
name/value pairs.
Each data row contains a name, and value. The row also contains a
type or mimetype. Type corresponds to a .NET class that support
text/value conversion through the TypeConverter architecture.
Classes that don't support this are serialized and stored with the
mimetype set.
The mimetype is used for serialized objects, and tells the
ResXResourceReader how to depersist the object. This is currently not
extensible. For a given mimetype the value must be set accordingly:
Note - application/x-microsoft.net.object.binary.base64 is the format
that the ResXResourceWriter will generate, however the reader can
read any of the formats listed below.
mimetype: application/x-microsoft.net.object.binary.base64
value : The object must be serialized with
: System.Runtime.Serialization.Formatters.Binary.BinaryFormatter
: and then encoded with base64 encoding.
mimetype: application/x-microsoft.net.object.soap.base64
value : The object must be serialized with
: System.Runtime.Serialization.Formatters.Soap.SoapFormatter
: and then encoded with base64 encoding.
mimetype: application/x-microsoft.net.object.bytearray.base64
value : The object must be serialized into a byte array
: using a System.ComponentModel.TypeConverter
: and then encoded with base64 encoding.
-->
<xsd:schema id="root" xmlns="" xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns:msdata="urn:schemas-microsoft-com:xml-msdata">
<xsd:element name="root" msdata:IsDataSet="true">
<xsd:complexType>
<xsd:choice maxOccurs="unbounded">
<xsd:element name="metadata">
<xsd:complexType>
<xsd:sequence>
<xsd:element name="value" type="xsd:string" minOccurs="0" />
</xsd:sequence>
<xsd:attribute name="name" use="required" type="xsd:string" />
<xsd:attribute name="type" type="xsd:string" />
<xsd:attribute name="mimetype" type="xsd:string" />
</xsd:complexType>
</xsd:element>
<xsd:element name="assembly">
<xsd:complexType>
<xsd:attribute name="alias" type="xsd:string" />
<xsd:attribute name="name" type="xsd:string" />
</xsd:complexType>
</xsd:element>
<xsd:element name="data">
<xsd:complexType>
<xsd:sequence>
<xsd:element name="value" type="xsd:string" minOccurs="0" msdata:Ordinal="1" />
<xsd:element name="comment" type="xsd:string" minOccurs="0" msdata:Ordinal="2" />
</xsd:sequence>
<xsd:attribute name="name" type="xsd:string" use="required" msdata:Ordinal="1" />
<xsd:attribute name="type" type="xsd:string" msdata:Ordinal="3" />
<xsd:attribute name="mimetype" type="xsd:string" msdata:Ordinal="4" />
</xsd:complexType>
</xsd:element>
<xsd:element name="resheader">
<xsd:complexType>
<xsd:sequence>
<xsd:element name="value" type="xsd:string" minOccurs="0" msdata:Ordinal="1" />
</xsd:sequence>
<xsd:attribute name="name" type="xsd:string" use="required" />
</xsd:complexType>
</xsd:element>
</xsd:choice>
</xsd:complexType>
</xsd:element>
</xsd:schema>
<resheader name="resmimetype">
<value>text/microsoft-resx</value>
</resheader>
<resheader name="version">
<value>2.0</value>
</resheader>
<resheader name="reader">
<value>System.Resources.ResXResourceReader, System.Windows.Forms, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089</value>
</resheader>
<resheader name="writer">
<value>System.Resources.ResXResourceWriter, System.Windows.Forms, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089</value>
</resheader>
<data name="AbbreviatedDayNames">
<value xml:space="preserve">Sun|Mon|Tue|Wed|Thu|Fri|Sat</value>
</data>
<data name="AbbreviatedMonthNames">
<value xml:space="preserve">Jan|Feb|Mar|Apr|May|Jun|Jul|Aug|Sep|Oct|Nov|Dec</value>
</data>
<data name="AMDesignator">
<value xml:space="preserve">AM</value>
</data>
<data name="DateSeparator">
<value xml:space="preserve">/</value>
</data>
<data name="DayNames">
<value xml:space="preserve">Sunday|Monday|Tuesday|Wednesday|Thursday|Friday|Saturday</value>
</data>
<data name="LongDatePattern">
<value xml:space="preserve">dddd, dd MMMM yyyy</value>
</data>
<data name="LongTimePattern">
<value xml:space="preserve">HH:mm:ss</value>
</data>
<data name="MonthDayPattern">
<value xml:space="preserve">MMMM dd</value>
</data>
<data name="MonthNames">
<value xml:space="preserve">January|February|March|April|May|June|July|August|September|October|November|December</value>
</data>
<data name="NegativeSign">
<value xml:space="preserve">-</value>
</data>
<data name="NumberDecimalSeparator">
<value xml:space="preserve">.</value>
</data>
<data name="NumberGroupSeparator">
<value xml:space="preserve">,</value>
</data>
<data name="NumberGroupSizes">
<value xml:space="preserve">3</value>
</data>
<data name="PMDesignator">
<value xml:space="preserve">PM</value>
</data>
<data name="PositiveSign">
<value xml:space="preserve">+</value>
</data>
<data name="ShortDatePattern">
<value xml:space="preserve">MM/dd/yyyy</value>
</data>
<data name="ShortTimePattern">
<value xml:space="preserve">HH:mm</value>
</data>
<data name="TimeSeparator">
<value xml:space="preserve">:</value>
</data>
<data name="YearMonthPattern">
<value xml:space="preserve">yyyy MMMM</value>
</data>
</root>

242
_mscorlib/System/Guid.cs Normal file
Просмотреть файл

@ -0,0 +1,242 @@
namespace System
{
[Serializable]
public struct Guid
{
internal int[] m_data;
private static Random m_rand = new Random();
/// <summary>
/// A read-only instance of the Guid class which consists of all zeros.
/// </summary>
public static readonly Guid Empty = new Guid(0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0);
/// <summary>
/// Initializes an instanace of the Guid class.
/// </summary>
/// <param name="a">The first 4 bytes of the Guid.</param>
/// <param name="b">The next 2 bytes of the Guid.</param>
/// <param name="c">The next 2 bytes of the Guid.</param>
/// <param name="d">The next byte of the Guid.</param>
/// <param name="e">The next byte of the Guid.</param>
/// <param name="f">The next byte of the Guid.</param>
/// <param name="g">The next byte of the Guid.</param>
/// <param name="h">The next byte of the Guid.</param>
/// <param name="i">The next byte of the Guid.</param>
/// <param name="j">The next byte of the Guid.</param>
/// <param name="k">The next byte of the Guid.</param>
public Guid(int a, short b, short c, byte d, byte e, byte f, byte g, byte h, byte i, byte j, byte k)
{
m_data = new int[4];
m_data[0] = a;
m_data[1] = (ushort)b | (ushort)c << 16;
m_data[2] = d | (e | (f | g << 8) << 8) << 8;
m_data[3] = h | (i | (j | k << 8) << 8) << 8;
}
/// <summary>
/// Initializes an instanace of the Guid class.
/// </summary>
/// <param name="a">The first 4 bytes of the Guid.</param>
/// <param name="b">The next 2 bytes of the Guid.</param>
/// <param name="c">The next 2 bytes of the Guid.</param>
/// <param name="d">The next byte of the Guid.</param>
/// <param name="e">The next byte of the Guid.</param>
/// <param name="f">The next byte of the Guid.</param>
/// <param name="g">The next byte of the Guid.</param>
/// <param name="h">The next byte of the Guid.</param>
/// <param name="i">The next byte of the Guid.</param>
/// <param name="j">The next byte of the Guid.</param>
/// <param name="k">The next byte of the Guid.</param>
[CLSCompliant(false)]
public Guid(uint a, ushort b, ushort c, byte d, byte e, byte f, byte g, byte h, byte i, byte j, byte k)
{
m_data = new int[4];
m_data[0] = (int)a;
m_data[1] = b | c << 16;
m_data[2] = d | (e | (f | g << 8) << 8) << 8;
m_data[3] = h | (i | (j | k << 8) << 8) << 8;
}
/// <summary>
/// Initializes an instance of the Guid class
/// </summary>
/// <param name="b">A 16 element byte array containing the values with which to initialize the Guid.</param>
public Guid(byte[] b)
{
if (b == null)
{
throw new ArgumentNullException();
}
if (b.Length != 16)
{
throw new ArgumentException();
}
m_data = new int[4];
int i = 0;
for (int j = 0; j < 4; j++)
{
m_data[j] = b[i] | (b[i + 1] | (b[i + 2] | b[i + 3] << 8) << 8) << 8;
i += 4;
}
}
/// <summary>
/// Compares this instance to another Guid instance and returns an indication of their relative values
/// </summary>
/// <param name="value">Guid instance to compare, or null.</param>
/// <returns>Indication of the relative values (0 = equal, -1 = this instance less, +1 = this instance greater)</returns>
public int CompareTo(Object value)
{
if (value == null)
{
return 1;
}
if (!(value is Guid))
{
throw new ArgumentException();
}
int[] other = ((Guid)value).m_data;
for (int i = 0; i < 4; i++)
{
if (m_data[i] != other[i])
{
return m_data[i] - other[i];
}
}
return 0;
}
/// <summary>
/// Gets the instance value as a byte array
/// </summary>
/// <returns>16 element byte array containing the value of the Guid instance.</returns>
public byte[] ToByteArray()
{
byte[] buffer = new byte[16];
int index = 0;
for (int i = 0; i < 4; i++)
{
int value = m_data[i];
for (int j = 0; j < 4; j++)
{
buffer[index++] = (byte)(value & 0xFF);
value = value >> 8;
}
}
return buffer;
}
public override string ToString()
{
// registry format is 08B03E06-01A8-4cd9-9971-ED45E2E84A53
if (m_data == null) m_data = new int[4];
byte[] bytes = ToByteArray();
char[] chars = new char[36];
int i = -1, j;
for (j = 3; j >= 0; --j)
{
chars[++i] = HexToChar((bytes[j] & 0xF0) >> 4);
chars[++i] = HexToChar((bytes[j] & 0x0F));
}
chars[++i] = '-';
for (j = 5; j >= 4; --j)
{
chars[++i] = HexToChar((bytes[j] & 0xF0) >> 4);
chars[++i] = HexToChar((bytes[j] & 0x0F));
}
chars[++i] = '-';
for (j = 7; j >= 6; --j)
{
chars[++i] = HexToChar((bytes[j] & 0xF0) >> 4);
chars[++i] = HexToChar((bytes[j] & 0x0F));
}
chars[++i] = '-';
for (j = 8; j <= 9; ++j)
{
chars[++i] = HexToChar((bytes[j] & 0xF0) >> 4);
chars[++i] = HexToChar((bytes[j] & 0x0F));
}
chars[++i] = '-';
for (j = 10; j <= 15; ++j)
{
chars[++i] = HexToChar((bytes[j] & 0xF0) >> 4);
chars[++i] = HexToChar((bytes[j] & 0x0F));
}
return new string(chars);
}
/// <summary>
/// Overriden. Compares this instance to another Guid and returns whether they are equal or not.
/// </summary>
public override bool Equals(Object obj)
{
if (!(obj is Guid))
{
return false;
}
int[] other = ((Guid)obj).m_data;
return (m_data[0] == other[0]) && (m_data[1] == other[1]) && (m_data[2] == other[2]) && (m_data[3] == other[3]);
}
/// <summary>
/// Overriden. Returns a hash value for the Guid instance.
/// </summary>
public override int GetHashCode()
{
return m_data[0] ^ m_data[1] ^ m_data[2] ^ m_data[3];
}
//--//
public static Guid NewGuid()
{
Guid newGuid = new Guid();
newGuid.m_data = new int[4];
newGuid.m_data[0] = m_rand.Next();
newGuid.m_data[1] = m_rand.Next();
newGuid.m_data[2] = m_rand.Next();
newGuid.m_data[3] = m_rand.Next();
newGuid.m_data[1] &= -1;
newGuid.m_data[1] |= 0x00000052; // the number '4'
return newGuid;
}
//--//
private static char HexToChar(int a)
{
return (char)((a > 9) ? a - 10 + 0x61 : a + 0x30);
}
}
}

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

@ -0,0 +1,16 @@
//
// Copyright (c) 2017 The nanoFramework project contributors
// Portions Copyright (c) Microsoft Corporation. All rights reserved.
// See LICENSE file in the project root for full license information.
//
namespace System
{
using System;
using System.Threading;
public interface IAsyncResult
{
}
}

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

@ -0,0 +1,31 @@
//
// Copyright (c) 2017 The nanoFramework project contributors
// Portions Copyright (c) Microsoft Corporation. All rights reserved.
// See LICENSE file in the project root for full license information.
//
namespace System
{
using System;
/**
* Defines an interface indicating that an object may be cloned. Only objects
* that implement <i>ICloneable</i> may be cloned. The interface defines a single
* method which is called to create a clone of the object. Object defines a method
* <i>MemberwiseClone</i> to support default clone operations.
*
* @see System.Object
*/
public interface ICloneable
{
// Interface does not need to be marked with the serializable attribute
/**
* Make a new object which is a copy of the object instanced. This object may be either
* deep copy or a shallow copy depending on the implementation of clone. The default
* Object support for clone does a shallow copy.
*
* @return A new object that represents a clone of the object.
*/
Object Clone();
}
}

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

@ -0,0 +1,38 @@
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
// Copyright (c) Microsoft Corporation. All rights reserved.
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////namespace System
namespace System
{
using System;
/**
* The <i>IComparable</i> interface is implemented by classes that support an
* <i>ordering</i> of instances of the class. The ordering represented by
* <i>IComparable</i> can be used to sort arrays and collections of objects
* that implement the interface.
*
* @see System.Array#Sort
* @see System.Array#BinarySearch
* @see System.List#Sort
* @see System.List#BinarySearch
* @see System.SortedList
*/
public interface IComparable
{
// Interface does not need to be marked with the serializable attribute
/**
* Compares this object to another object, returning an integer that
* indicates the relationship. An implementation of this method must return
* a value less than zero if <i>this</i> is less than <i>object</i>, zero
* if <i>this</i> is equal to <i>object</i>, or a value greater than zero
* if <i>this</i> is greater than <i>object</i>.
*
* @param object The object to compare with this object.
* @return A value less than zero if <i>this</i> < <i>object</i>, zero if
* <i>this</i> = <i>object</i>, or a value greater than zero if <i>this</i>
* > <i>object</i>.
*/
int CompareTo(Object obj);
}
}

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

@ -0,0 +1,17 @@
//
// Copyright (c) 2017 The nanoFramework project contributors
// Portions Copyright (c) Microsoft Corporation. All rights reserved.
// See LICENSE file in the project root for full license information.
//
namespace System
{
using System;
public interface ICustomFormatter
{
// Interface does not need to be marked with the serializable attribute
String Format(String format, Object arg, IFormatProvider formatProvider);
}
}

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

@ -0,0 +1,52 @@
//
// Copyright (c) 2017 The nanoFramework project contributors
// Portions Copyright (c) Microsoft Corporation. All rights reserved.
// See LICENSE file in the project root for full license information.
//
namespace System
{
// IDisposable is an attempt at helping to solve problems with deterministic
// finalization. The GC of course doesn't leave any way to deterministically
// know when a finalizer will run. This forces classes that hold onto OS
// resources or some sort of important state (such as a FileStream or a
// network connection) to provide a Close or Dispose method so users can
// run clean up code deterministically. We have formalized this into an
// interface with one method. Classes may privately implement IDisposable and
// provide a Close method instead, if that name is by far the expected name
// for objects in that domain (ie, you don't Dispose of a FileStream, you Close
// it).
//
// This interface could be theoretically used as a marker by a compiler to
// ensure a disposable object has been cleaned up along all code paths if it's
// been allocated in that method, though in practice any compiler that
// draconian may tick off any number of people. Perhaps an external tool (like
// like Purify or BoundsChecker) could do this. Instead, C# has added a using
// clause, which will generate a try/finally statement where the resource
// passed into the using clause will always have it's Dispose method called.
// Syntax is using(FileStream fs = ...) { .. };
//
// Dispose should meet the following conditions:
// 1) Be safely callable multiple times
// 2) Release any resources associated with the instance
// 3) Call the base class's Dispose method, if necessary
// 4) Suppress finalization of this class to help the GC by reducing the
// number of objects on the finalization queue.
// 5) Dispose shouldn't generally throw exceptions, except for very serious
// errors that are particularly unexpected. (ie, OutOfMemoryException)
// Ideally, nothing should go wrong with your object by calling Dispose.
//
// If possible, a class should define a finalizer that calls Dispose.
// However, in many situations, this is impractical. For instance, take the
// classic example of a Stream and a StreamWriter (which has an internal
// buffer of data to write to the Stream). If both objects are collected
// before Close or Dispose has been called on either, then the GC may run the
// finalizer for the Stream first, before the StreamWriter. At that point, any
// data buffered by the StreamWriter cannot be written to the Stream. In this
// case, it doesn't make much sense to provide a finalizer on the StreamWriter
// since you cannot solve this problem correctly.
public interface IDisposable
{
void Dispose();
}
}

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

@ -0,0 +1,16 @@
//
// Copyright (c) 2017 The nanoFramework project contributors
// Portions Copyright (c) Microsoft Corporation. All rights reserved.
// See LICENSE file in the project root for full license information.
//
namespace System
{
using System;
public interface IFormatProvider
{
// Interface does not need to be marked with the serializable attribute
Object GetFormat(Type formatType);
}
}

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

@ -0,0 +1,12 @@
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
// Copyright (c) Microsoft Corporation. All rights reserved.
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////namespace System
namespace System
{
using System;
public interface IFormattable
{
String ToString(String format, IFormatProvider formatProvider);
}
}

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

@ -0,0 +1,57 @@
//
// Copyright (c) 2017 The nanoFramework project contributors
// Portions Copyright (c) Microsoft Corporation. All rights reserved.
// See LICENSE file in the project root for full license information.
//
using System;
namespace System.IO
{
[Serializable]
public class IOException : SystemException
{
public enum IOExceptionErrorCode : int
{
Others = unchecked((int)0xE0000000), // CLR_E_FILE_IO
InvalidDriver = unchecked((int)0xE1000000), // CLR_E_INVALID_DRIVER
FileNotFound = unchecked((int)0xE2000000), // CLR_E_FILE_NOT_FOUND
DirectoryNotFound = unchecked((int)0xE3000000), // CLR_E_DIRECTORY_NOT_FOUND
VolumeNotFound = unchecked((int)0xE4000000), // CLR_E_VOLUME_NOT_FOUND
PathTooLong = unchecked((int)0xE5000000), // CLR_E_PATH_TOO_LONG
DirectoryNotEmpty = unchecked((int)0xE6000000), // CLR_E_DIRECTORY_NOT_EMPTY
UnauthorizedAccess = unchecked((int)0xE7000000), // CLR_E_UNAUTHORIZED_ACCESS
PathAlreadyExists = unchecked((int)0xE8000000), // CLR_E_PATH_ALREADY_EXISTS
TooManyOpenHandles = unchecked((int)0xE9000000), // CLR_E_TOO_MANY_OPEN_HANDLES
}
public IOException()
: base()
{
}
public IOException(String message)
: base(message)
{
}
public IOException(String message, int hresult)
: base(message)
{
m_HResult = hresult;
}
public IOException(String message, Exception innerException)
: base(message, innerException)
{
}
public IOExceptionErrorCode ErrorCode
{
get { return (IOExceptionErrorCode)m_HResult; }
}
}
}

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

@ -0,0 +1,23 @@
//
// Copyright (c) 2017 The nanoFramework project contributors
// Portions Copyright (c) Microsoft Corporation. All rights reserved.
// See LICENSE file in the project root for full license information.
//
using System;
namespace System.IO
{
// Provides seek reference points. To seek to the end of a stream,
// call stream.Seek(0, SeekOrigin.End).
[Serializable()]
public enum SeekOrigin
{
// These constants match Win32's FILE_BEGIN, FILE_CURRENT, and FILE_END
Begin = 0,
Current = 1,
End = 2,
}
}

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

@ -0,0 +1,148 @@
//
// Copyright (c) 2017 The nanoFramework project contributors
// Portions Copyright (c) Microsoft Corporation. All rights reserved.
// See LICENSE file in the project root for full license information.
//
using System.Threading;
using System.Runtime.InteropServices;
namespace System.IO
{
[Serializable()]
public abstract class Stream : MarshalByRefObject, IDisposable
{
public abstract bool CanRead
{
get;
}
// If CanSeek is false, Position, Seek, Length, and SetLength should throw.
public abstract bool CanSeek
{
get;
}
public virtual bool CanTimeout
{
get
{
return false;
}
}
public abstract bool CanWrite
{
get;
}
public abstract long Length
{
get;
}
public abstract long Position
{
get;
set;
}
public virtual int ReadTimeout
{
get
{
throw new InvalidOperationException();
}
set
{
throw new InvalidOperationException();
}
}
public virtual int WriteTimeout
{
get
{
throw new InvalidOperationException();
}
set
{
throw new InvalidOperationException();
}
}
// Stream used to require that all cleanup logic went into Close(),
// which was thought up before we invented IDisposable. However, we
// need to follow the IDisposable pattern so that users can write
// sensible subclasses without needing to inspect all their base
// classes, and without worrying about version brittleness, from a
// base class switching to the Dispose pattern. We're moving
// Stream to the Dispose(bool) pattern - that's where all subclasses
// should put their cleanup starting in V2.
public virtual void Close()
{
Dispose(true);
GC.SuppressFinalize(this);
}
public void Dispose()
{
try
{
Close();
}
catch
{
}
}
~Stream()
{
Dispose(false);
}
protected virtual void Dispose(bool disposing)
{
}
public abstract void Flush();
public abstract long Seek(long offset, SeekOrigin origin);
public abstract void SetLength(long value);
public abstract int Read(/*[In, Out]*/ byte[] buffer, int offset, int count);
// Reads one byte from the stream by calling Read(byte[], int, int).
// Will return an unsigned byte cast to an int or -1 on end of stream.
// This implementation does not perform well because it allocates a new
// byte[] each time you call it, and should be overridden by any
// subclass that maintains an internal buffer. Then, it can help perf
// significantly for people who are reading one byte at a time.
public virtual int ReadByte()
{
byte[] oneByteArray = new byte[1];
int r = Read(oneByteArray, 0, 1);
if (r == 0)
return -1;
return oneByteArray[0];
}
public abstract void Write(byte[] buffer, int offset, int count);
// Writes one byte from the stream by calling Write(byte[], int, int).
// This implementation does not perform well because it allocates a new
// byte[] each time you call it, and should be overridden by any
// subclass that maintains an internal buffer. Then, it can help perf
// significantly for people who are writing one byte at a time.
public virtual void WriteByte(byte value)
{
byte[] oneByteArray = new byte[1];
oneByteArray[0] = value;
Write(oneByteArray, 0, 1);
}
}
}

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

@ -0,0 +1,21 @@
namespace System
{
[Serializable()]
public class IndexOutOfRangeException : SystemException
{
public IndexOutOfRangeException()
: base()
{
}
public IndexOutOfRangeException(String message)
: base(message)
{
}
public IndexOutOfRangeException(String message, Exception innerException)
: base(message, innerException)
{
}
}
}

43
_mscorlib/System/Int16.cs Normal file
Просмотреть файл

@ -0,0 +1,43 @@
//
// Copyright (c) 2017 The nanoFramework project contributors
// Portions Copyright (c) Microsoft Corporation. All rights reserved.
// See LICENSE file in the project root for full license information.
//
namespace System
{
using System;
using System.Runtime.CompilerServices;
using System.Globalization;
[Serializable]
public struct Int16
{
internal short m_value;
public const short MaxValue = (short)0x7FFF;
public const short MinValue = unchecked((short)0x8000);
public override String ToString()
{
return Number.Format(m_value, true, "G", NumberFormatInfo.CurrentInfo);
}
public String ToString(String format)
{
return Number.Format(m_value, true, format, NumberFormatInfo.CurrentInfo);
}
public static short Parse(String s)
{
if (s == null)
{
throw new ArgumentNullException();
}
return Convert.ToInt16(s);
}
}
}

43
_mscorlib/System/Int32.cs Normal file
Просмотреть файл

@ -0,0 +1,43 @@
//
// Copyright (c) 2017 The nanoFramework project contributors
// Portions Copyright (c) Microsoft Corporation. All rights reserved.
// See LICENSE file in the project root for full license information.
//
namespace System
{
using System;
using System.Runtime.CompilerServices;
using System.Globalization;
[Serializable]
public struct Int32
{
internal int m_value;
public const int MaxValue = 0x7fffffff;
public const int MinValue = unchecked((int)0x80000000);
public override String ToString()
{
return Number.Format(m_value, true, "G", NumberFormatInfo.CurrentInfo);
}
public String ToString(String format)
{
return Number.Format(m_value, true, format, NumberFormatInfo.CurrentInfo);
}
public static int Parse(String s)
{
if (s == null)
{
throw new ArgumentNullException();
}
return Convert.ToInt32(s);
}
}
}

43
_mscorlib/System/Int64.cs Normal file
Просмотреть файл

@ -0,0 +1,43 @@
//
// Copyright (c) 2017 The nanoFramework project contributors
// Portions Copyright (c) Microsoft Corporation. All rights reserved.
// See LICENSE file in the project root for full license information.
//
namespace System
{
using System;
using System.Runtime.CompilerServices;
using System.Globalization;
[Serializable]
public struct Int64
{
internal long m_value;
public const long MaxValue = 0x7fffffffffffffffL;
public const long MinValue = unchecked((long)0x8000000000000000L);
public override String ToString()
{
return Number.Format(m_value, true, "G", NumberFormatInfo.CurrentInfo);
}
public String ToString(String format)
{
return Number.Format(m_value, true, format, NumberFormatInfo.CurrentInfo);
}
public static long Parse(String s)
{
if (s == null)
{
throw new ArgumentNullException();
}
return Convert.ToInt64(s);
}
}
}

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

@ -0,0 +1,16 @@
//
// Copyright (c) 2017 The nanoFramework project contributors
// Portions Copyright (c) Microsoft Corporation. All rights reserved.
// See LICENSE file in the project root for full license information.
//
namespace System
{
using System;
[Serializable]
public struct IntPtr
{
}
}

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

@ -0,0 +1,21 @@
namespace System
{
[Serializable()]
public class InvalidCastException : SystemException
{
public InvalidCastException()
: base()
{
}
public InvalidCastException(String message)
: base(message)
{
}
public InvalidCastException(String message, Exception innerException)
: base(message, innerException)
{
}
}
}

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

@ -0,0 +1,30 @@
//
// Copyright (c) 2017 The nanoFramework project contributors
// Portions Copyright (c) Microsoft Corporation. All rights reserved.
// See LICENSE file in the project root for full license information.
//
namespace System
{
using System;
[Serializable()]
public class InvalidOperationException : SystemException
{
public InvalidOperationException()
: base()
{
}
public InvalidOperationException(String message)
: base(message)
{
}
public InvalidOperationException(String message, Exception innerException)
: base(message, innerException)
{
}
}
}

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

@ -0,0 +1,18 @@
//
// Copyright (c) 2017 The nanoFramework project contributors
// Portions Copyright (c) Microsoft Corporation. All rights reserved.
// See LICENSE file in the project root for full license information.
//
namespace System
{
using System;
using System.Threading;
using System.Runtime.CompilerServices;
[Serializable()]
public abstract class MarshalByRefObject
{
}
} // namespace

435
_mscorlib/System/Math.cs Normal file
Просмотреть файл

@ -0,0 +1,435 @@
//
// Copyright (c) 2017 The nanoFramework project contributors
// Portions Copyright (c) Microsoft Corporation. All rights reserved.
// See LICENSE file in the project root for full license information.
//
namespace System
{
//This class contains only static members and doesn't require serialization.
using System;
using System.Runtime.CompilerServices;
public static class Math
{
// Public Constants
// Summary:
// Represents the ratio of the circumference of a circle to its diameter, specified
// by the constant, p.
public const double PI = 3.14159265358979323846;
// Summary:
// Represents the natural logarithmic base, specified by the constant, e
public const double E = 2.7182818284590452354;
// Methods
// Summary:
// Returns the absolute value of an integer number.
//
// Parameters:
// value:
// A number in the range System.Double.MinValue=value=System.Double.MaxValue.
//
// Returns:
// An integer, x, such that 0 = x =System.Integer.MaxValue.
public static int Abs(int val)
{
return (val >= 0) ? val : -val;
}
//
// Summary:
// Returns the larger of two integer numbers.
//
// Parameters:
// val1:
// The first of two integert numbers to compare.
//
// val2:
// The second of two integer numbers to compare.
//
// Returns:
// Parameter val1 or val2, whichever is larger.
public static int Max(int val1, int val2)
{
return (val1 >= val2) ? val1 : val2;
}
//
// Summary:
// Returns the smaller of two integer numbers.
//
// Parameters:
// val1:
// The first of two integer numbers to compare.
//
// val2:
// The second of two integer numbers to compare.
//
// Returns:
// Parameter val1 or val2, whichever is smaller.
public static int Min(int val1, int val2)
{
return (val1 <= val2) ? val1 : val2;
}
// Summary:
// Returns the absolute value of a double-precision floating-point number.
//
// Parameters:
// value:
// A number in the range System.Double.MinValue=value=System.Double.MaxValue.
//
// Returns:
// A double-precision floating-point number, x, such that 0 = x =System.Double.MaxValue.
public static double Abs(double val)
{
return (val >= 0) ? val : -val;
}
//
// Summary:
// Returns the angle whose cosine is the specified number.
//
// Parameters:
// d:
// A number representing a cosine, where -1 =d= 1.
//
// Returns:
// An angle, ?, measured in radians, such that 0 =?=p -or- System.Double.NaN
// if d < -1 or d > 1.
[MethodImplAttribute(MethodImplOptions.InternalCall)]
public static extern double Acos(double d);
//
// Summary:
// Returns the angle whose sine is the specified number.
//
// Parameters:
// d:
// A number representing a sine, where -1 =d= 1.
//
// Returns:
// An angle, ?, measured in radians, such that -p/2 =?=p/2 -or- System.Double.NaN
// if d < -1 or d > 1.
[MethodImplAttribute(MethodImplOptions.InternalCall)]
public static extern double Asin(double d);
//
// Summary:
// Returns the angle whose tangent is the specified number.
//
// Parameters:
// d:
// A number representing a tangent.
//
// Returns:
// An angle, ?, measured in radians, such that -p/2 =?=p/2. -or- System.Double.NaN
// if d equals System.Double.NaN, -p/2 rounded to double precision (-1.5707963267949)
// if d equals System.Double.NegativeInfinity, or p/2 rounded to double precision
// (1.5707963267949) if d equals System.Double.PositiveInfinity.
[MethodImplAttribute(MethodImplOptions.InternalCall)]
public static extern double Atan(double d);
//
// Summary:
// Returns the angle whose tangent is the quotient of two specified numbers.
//
// Parameters:
// y:
// The y coordinate of a point.
//
// x:
// The x coordinate of a point.
//
// Returns:
// An angle, ?, measured in radians, such that -p=?=p, and tan(?) = y / x, where
// (x, y) is a point in the Cartesian plane. Observe the following: For (x,
// y) in quadrant 1, 0 < ? < p/2. For (x, y) in quadrant 2, p/2 < ?=p. For
// (x, y) in quadrant 3, -p < ? < -p/2. For (x, y) in quadrant 4, -p/2 < ?
// < 0. For points on the boundaries of the quadrants, the return value is
// the following: If y is 0 and x is not negative, ? = 0. If y is 0 and x is
// negative, ? = p. If y is positive and x is 0, ? = p/2. If y is negative
// and x is 0, ? = -p/2.
[MethodImplAttribute(MethodImplOptions.InternalCall)]
public static extern double Atan2(double y, double x); //
// Summary:
// Returns the smallest integer greater than or equal to the specified double-precision
// floating-point number.
//
// Parameters:
// a:
// A double-precision floating-point number.
//
// Returns:
// The smallest integer greater than or equal to a. If a is equal to System.Double.NaN,
// System.Double.NegativeInfinity, or System.Double.PositiveInfinity, that value
// is returned.
[MethodImplAttribute(MethodImplOptions.InternalCall)]
public static extern double Ceiling(double d); //
// Summary:
// Returns the cosine of the specified angle.
//
// Parameters:
// d:
// An angle, measured in radians.
//
// Returns:
// The cosine of d.
[MethodImplAttribute(MethodImplOptions.InternalCall)]
public static extern double Cos(double a);
//
// Summary:
// Returns the hyperbolic cosine of the specified angle.
//
// Parameters:
// value:
// An angle, measured in radians.
//
// Returns:
// The hyperbolic cosine of value. If value is equal to System.Double.NegativeInfinity
// or System.Double.PositiveInfinity, System.Double.PositiveInfinity is returned.
// If value is equal to System.Double.NaN, System.Double.NaN is returned.
[MethodImplAttribute(MethodImplOptions.InternalCall)]
public static extern double Cosh(double a);
//
// Summary:
// Returns the remainder resulting from the division of a specified number by
// another specified number.
//
// Parameters:
// x:
// A dividend.
//
// y:
// A divisor.
//
// Returns:
// A number equal to x - (y Q), where Q is the quotient of x / y rounded to
// the nearest integer (if x / y falls halfway between two integers, the even
// integer is returned). If x - (y Q) is zero, the value +0 is returned if
// x is positive, or -0 if x is negative. If y = 0, System.Double.NaN (Not-A-Number)
// is returned.
[MethodImplAttribute(MethodImplOptions.InternalCall)]
public static extern double IEEERemainder(double x, double y);
//
// Summary:
// Returns e raised to the specified power.
//
// Parameters:
// d:
// A number specifying a power.
//
// Returns:
// The number e raised to the power d. If d equals System.Double.NaN or System.Double.PositiveInfinity,
// that value is returned. If d equals System.Double.NegativeInfinity, 0 is
// returned.
[MethodImplAttribute(MethodImplOptions.InternalCall)]
public static extern double Exp(double d);
//
// Summary:
// Returns the largest integer less than or equal to the specified double-precision
// floating-point number.
//
// Parameters:
// d:
// A double-precision floating-point number.
//
// Returns:
// The largest integer less than or equal to d. If d is equal to System.Double.NaN,
// System.Double.NegativeInfinity, or System.Double.PositiveInfinity, that value
// is returned.
[MethodImplAttribute(MethodImplOptions.InternalCall)]
public static extern double Floor(double d);
//
// Summary:
// Returns the natural (base e) logarithm of a specified number.
//
// Parameters:
// d:
// A number whose logarithm is to be found.
//
// Returns:
// Sign of d Returns Positive The natural logarithm of d; that is, ln d, or
// log ed Zero System.Double.NegativeInfinity Negative System.Double.NaN If
// d is equal to System.Double.NaN, returns System.Double.NaN. If d is equal
// to System.Double.PositiveInfinity, returns System.Double.PositiveInfinity.
[MethodImplAttribute(MethodImplOptions.InternalCall)]
public static extern double Log(double d);
//
// Summary:
// Returns the base 10 logarithm of a specified number.
//
// Parameters:
// d:
// A number whose logarithm is to be found.
//
// Returns:
// Sign of d Returns Positive The base 10 log of d; that is, log 10d. Zero System.Double.NegativeInfinity
// Negative System.Double.NaN If d is equal to System.Double.NaN, this method
// returns System.Double.NaN. If d is equal to System.Double.PositiveInfinity,
// this method returns System.Double.PositiveInfinity.
[MethodImplAttribute(MethodImplOptions.InternalCall)]
public static extern double Log10(double d);
//
// Summary:
// Returns the larger of two double-precision floating-point numbers.
//
// Parameters:
// val1:
// The first of two double-precision floating-point numbers to compare.
//
// val2:
// The second of two double-precision floating-point numbers to compare.
//
// Returns:
// Parameter val1 or val2, whichever is larger. If val1, val2, or both val1
// and val2 are equal to System.Double.NaN, System.Double.NaN is returned.
public static double Max(double x, double y)
{
return (x >= y) ? x : y;
}
//
// Summary:
// Returns the smaller of two double-precision floating-point numbers.
//
// Parameters:
// val1:
// The first of two double-precision floating-point numbers to compare.
//
// val2:
// The second of two double-precision floating-point numbers to compare.
//
// Returns:
// Parameter val1 or val2, whichever is smaller. If val1, val2, or both val1
// and val2 are equal to System.Double.NaN, System.Double.NaN is returned.
public static double Min(double x, double y)
{
return (x <= y) ? x : y;
}
//
// Summary:
// Returns a specified number raised to the specified power.
//
// Parameters:
// x:
// A double-precision floating-point number to be raised to a power.
//
// y:
// A double-precision floating-point number that specifies a power.
//
// Returns:
// The number x raised to the power y.
[MethodImplAttribute(MethodImplOptions.InternalCall)]
public static extern double Pow(double x, double y); //
// Summary:
// Rounds a double-precision floating-point value to the nearest integer.
//
// Parameters:
// a:
// A double-precision floating-point number to be rounded.
//
// Returns:
// The integer nearest a. If the fractional component of a is halfway between
// two integers, one of which is even and the other odd, then the even number
// is returned.
[MethodImplAttribute(MethodImplOptions.InternalCall)]
public static extern double Round(double d); //
//
// Summary:
// Returns a value indicating the sign of a double-precision floating-point
// number.
//
// Parameters:
// value:
// A signed number.
//
// Returns:
// A number indicating the sign of value. Number Description -1 value is less
// than zero. 0 value is equal to zero. 1 value is greater than zero.
//
// Exceptions:
// System.ArithmeticException:
// value is equal to System.Double.NaN.
// is returned.
[MethodImplAttribute(MethodImplOptions.InternalCall)]
public static extern int Sign(double value);
// Summary:
// Returns the sine of the specified angle.
//
// Parameters:
// a:
// An angle, measured in radians.
//
// Returns:
// The sine of a. If a is equal to System.Double.NaN, System.Double.NegativeInfinity,
// or System.Double.PositiveInfinity, this method returns System.Double.NaN.
[MethodImplAttribute(MethodImplOptions.InternalCall)]
public static extern double Sin(double a);
//
// Summary:
// Returns the hyperbolic sine of the specified angle.
//
// Parameters:
// value:
// An angle, measured in radians.
//
// Returns:
// The hyperbolic sine of value. If value is equal to System.Double.NegativeInfinity,
// System.Double.PositiveInfinity, or System.Double.NaN, this method returns
// a System.Double equal to value.
[MethodImplAttribute(MethodImplOptions.InternalCall)]
public static extern double Sinh(double value);
//
// Summary:
// Returns the square root of a specified number.
//
// Parameters:
// d:
// A number.
//
// Returns:
// Value of d Returns Zero, or positive The positive square root of d. Negative
// System.Double.NaN If d is equal to System.Double.NaN or System.Double.PositiveInfinity,
// that value is returned.
[MethodImplAttribute(MethodImplOptions.InternalCall)]
public static extern double Sqrt(double d);
//
// Summary:
// Returns the tangent of the specified angle.
//
// Parameters:
// a:
// An angle, measured in radians.
//
// Returns:
// The tangent of a. If a is equal to System.Double.NaN, System.Double.NegativeInfinity,
// or System.Double.PositiveInfinity, this method returns System.Double.NaN.
[MethodImplAttribute(MethodImplOptions.InternalCall)]
public static extern double Tan(double a);
//
// Summary:
// Returns the hyperbolic tangent of the specified angle.
//
// Parameters:
// value:
// An angle, measured in radians.
//
// Returns:
// The hyperbolic tangent of value. If value is equal to System.Double.NegativeInfinity,
// this method returns -1. If value is equal to System.Double.PositiveInfinity,
// this method returns 1. If value is equal to System.Double.NaN, this method
// returns System.Double.NaN.
[MethodImplAttribute(MethodImplOptions.InternalCall)]
public static extern double Tanh(double value);
//
// Summary:
// Calculates the integral part of a specified double-precision floating-point
// number.
//
// Parameters:
// d:
// A number to truncate.
//
// Returns:
// The integral part of d; that is, the number that remains after any fractional
// digits have been discarded.
[MethodImplAttribute(MethodImplOptions.InternalCall)]
public static extern double Truncate(double d);
}
}

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

@ -0,0 +1,21 @@
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
// Copyright (c) Microsoft Corporation. All rights reserved.
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////namespace System
namespace System
{
using System;
using System.Reflection;
using System.Runtime.CompilerServices;
[Serializable()]
public abstract class MulticastDelegate : Delegate
{
[MethodImplAttribute(MethodImplOptions.InternalCall)]
public extern static bool operator ==(MulticastDelegate d1, MulticastDelegate d2);
[MethodImplAttribute(MethodImplOptions.InternalCall)]
public extern static bool operator !=(MulticastDelegate d1, MulticastDelegate d2);
}
}

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

@ -0,0 +1,18 @@
//
// Copyright (c) 2017 The nanoFramework project contributors
// Portions Copyright (c) Microsoft Corporation. All rights reserved.
// See LICENSE file in the project root for full license information.
//
namespace System
{
[AttributeUsage(AttributeTargets.Field, Inherited = false)]
public sealed class NonSerializedAttribute : Attribute
{
public NonSerializedAttribute()
{
}
}
}

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

@ -0,0 +1,21 @@
namespace System
{
[Serializable()]
public class NotImplementedException : SystemException
{
public NotImplementedException()
: base()
{
}
public NotImplementedException(String message)
: base(message)
{
}
public NotImplementedException(String message, Exception innerException)
: base(message, innerException)
{
}
}
}

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

@ -0,0 +1,30 @@
//
// Copyright (c) 2017 The nanoFramework project contributors
// Portions Copyright (c) Microsoft Corporation. All rights reserved.
// See LICENSE file in the project root for full license information.
//
namespace System
{
using System;
[Serializable()]
public class NotSupportedException : SystemException
{
public NotSupportedException()
: base()
{
}
public NotSupportedException(String message)
: base(message)
{
}
public NotSupportedException(String message, Exception innerException)
: base(message, innerException)
{
}
}
}

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

@ -0,0 +1,21 @@
namespace System
{
[Serializable()]
public class NullReferenceException : SystemException
{
public NullReferenceException()
: base()
{
}
public NullReferenceException(String message)
: base(message)
{
}
public NullReferenceException(String message, Exception innerException)
: base(message, innerException)
{
}
}
}

505
_mscorlib/System/Number.cs Normal file
Просмотреть файл

@ -0,0 +1,505 @@
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
// Copyright (c) Microsoft Corporation. All rights reserved.
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////namespace System
namespace System
{
using System;
using System.Globalization;
using System.Runtime.CompilerServices;
// The Number class implements methods for formatting and parsing
// numeric values. To format and parse numeric values, applications should
// use the Format and Parse methods provided by the numeric
// classes (Byte, Int16, Int32, Int64,
// Single, Double, Currency, and Decimal). Those
// Format and Parse methods share a common implementation
// provided by this class, and are thus documented in detail here.
//
// Formatting
//
// The Format methods provided by the numeric classes are all of the
// form
//
// public static String Format(XXX value, String format);
// public static String Format(XXX value, String format, NumberFormatInfo info);
//
// where XXX is the name of the particular numeric class. The methods convert
// the numeric value to a string using the format string given by the
// format parameter. If the format parameter is null or
// an empty string, the number is formatted as if the string "G" (general
// format) was specified. The info parameter specifies the
// NumberFormatInfo instance to use when formatting the number. If the
// info parameter is null or omitted, the numeric formatting information
// is obtained from the current culture. The NumberFormatInfo supplies
// such information as the characters to use for decimal and thousand
// separators, and the spelling and placement of currency symbols in monetary
// values.
//
// Format strings fall into two categories: Standard format strings and
// user-defined format strings. A format string consisting of a single
// alphabetic character (A-Z or a-z), optionally followed by a sequence of
// digits (0-9), is a standard format string. All other format strings are
// used-defined format strings.
//
// A standard format string takes the form Axx, where A is an
// alphabetic character called the format specifier and xx is a
// sequence of digits called the precision specifier. The format
// specifier controls the type of formatting applied to the number and the
// precision specifier controls the number of significant digits or decimal
// places of the formatting operation. The following table describes the
// supported standard formats.
//
// C c - Currency format. The number is
// converted to a string that represents a currency amount. The conversion is
// controlled by the currency format information of the NumberFormatInfo
// used to format the number. The precision specifier indicates the desired
// number of decimal places. If the precision specifier is omitted, the default
// currency precision given by the NumberFormatInfo is used.
//
// D d - Decimal format. This format is
// supported for integral types only. The number is converted to a string of
// decimal digits, prefixed by a minus sign if the number is negative. The
// precision specifier indicates the minimum number of digits desired in the
// resulting string. If required, the number will be left-padded with zeros to
// produce the number of digits given by the precision specifier.
//
// E e Engineering (scientific) format.
// The number is converted to a string of the form
// "-d.ddd...E+ddd" or "-d.ddd...e+ddd", where each
// 'd' indicates a digit (0-9). The string starts with a minus sign if the
// number is negative, and one digit always precedes the decimal point. The
// precision specifier indicates the desired number of digits after the decimal
// point. If the precision specifier is omitted, a default of 6 digits after
// the decimal point is used. The format specifier indicates whether to prefix
// the exponent with an 'E' or an 'e'. The exponent is always consists of a
// plus or minus sign and three digits.
//
// F f Fixed point format. The number is
// converted to a string of the form "-ddd.ddd....", where each
// 'd' indicates a digit (0-9). The string starts with a minus sign if the
// number is negative. The precision specifier indicates the desired number of
// decimal places. If the precision specifier is omitted, the default numeric
// precision given by the NumberFormatInfo is used.
//
// G g - General format. The number is
// converted to the shortest possible decimal representation using fixed point
// or scientific format. The precision specifier determines the number of
// significant digits in the resulting string. If the precision specifier is
// omitted, the number of significant digits is determined by the type of the
// number being converted (10 for int, 19 for long, 7 for
// float, 15 for double, 19 for Currency, and 29 for
// Decimal). Trailing zeros after the decimal point are removed, and the
// resulting string contains a decimal point only if required. The resulting
// string uses fixed point format if the exponent of the number is less than
// the number of significant digits and greater than or equal to -4. Otherwise,
// the resulting string uses scientific format, and the case of the format
// specifier controls whether the exponent is prefixed with an 'E' or an
// 'e'.
//
// N n Number format. The number is
// converted to a string of the form "-d,ddd,ddd.ddd....", where
// each 'd' indicates a digit (0-9). The string starts with a minus sign if the
// number is negative. Thousand separators are inserted between each group of
// three digits to the left of the decimal point. The precision specifier
// indicates the desired number of decimal places. If the precision specifier
// is omitted, the default numeric precision given by the
// NumberFormatInfo is used.
//
// X x - Hexadecimal format. This format is
// supported for integral types only. The number is converted to a string of
// hexadecimal digits. The format specifier indicates whether to use upper or
// lower case characters for the hexadecimal digits above 9 ('X' for 'ABCDEF',
// and 'x' for 'abcdef'). The precision specifier indicates the minimum number
// of digits desired in the resulting string. If required, the number will be
// left-padded with zeros to produce the number of digits given by the
// precision specifier.
//
// Some examples of standard format strings and their results are shown in the
// table below. (The examples all assume a default NumberFormatInfo.)
//
// Value Format Result
// 12345.6789 C $12,345.68
// -12345.6789 C ($12,345.68)
// 12345 D 12345
// 12345 D8 00012345
// 12345.6789 E 1.234568E+004
// 12345.6789 E10 1.2345678900E+004
// 12345.6789 e4 1.2346e+004
// 12345.6789 F 12345.68
// 12345.6789 F0 12346
// 12345.6789 F6 12345.678900
// 12345.6789 G 12345.6789
// 12345.6789 G7 12345.68
// 123456789 G7 1.234568E8
// 12345.6789 N 12,345.68
// 123456789 N4 123,456,789.0000
// 0x2c45e x 2c45e
// 0x2c45e X 2C45E
// 0x2c45e X8 0002C45E
//
// Format strings that do not start with an alphabetic character, or that start
// with an alphabetic character followed by a non-digit, are called
// user-defined format strings. The following table describes the formatting
// characters that are supported in user defined format strings.
//
//
// 0 - Digit placeholder. If the value being
// formatted has a digit in the position where the '0' appears in the format
// string, then that digit is copied to the output string. Otherwise, a '0' is
// stored in that position in the output string. The position of the leftmost
// '0' before the decimal point and the rightmost '0' after the decimal point
// determines the range of digits that are always present in the output
// string.
//
// # - Digit placeholder. If the value being
// formatted has a digit in the position where the '#' appears in the format
// string, then that digit is copied to the output string. Otherwise, nothing
// is stored in that position in the output string.
//
// . - Decimal point. The first '.' character
// in the format string determines the location of the decimal separator in the
// formatted value; any additional '.' characters are ignored. The actual
// character used as a the decimal separator in the output string is given by
// the NumberFormatInfo used to format the number.
//
// , - Thousand separator and number scaling.
// The ',' character serves two purposes. First, if the format string contains
// a ',' character between two digit placeholders (0 or #) and to the left of
// the decimal point if one is present, then the output will have thousand
// separators inserted between each group of three digits to the left of the
// decimal separator. The actual character used as a the decimal separator in
// the output string is given by the NumberFormatInfo used to format the
// number. Second, if the format string contains one or more ',' characters
// immediately to the left of the decimal point, or after the last digit
// placeholder if there is no decimal point, then the number will be divided by
// 1000 times the number of ',' characters before it is formatted. For example,
// the format string '0,,' will represent 100 million as just 100. Use of the
// ',' character to indicate scaling does not also cause the formatted number
// to have thousand separators. Thus, to scale a number by 1 million and insert
// thousand separators you would use the format string '#,##0,,'.
//
// % - Percentage placeholder. The presence of
// a '%' character in the format string causes the number to be multiplied by
// 100 before it is formatted. The '%' character itself is inserted in the
// output string where it appears in the format string.
//
// E+ E- e+ e- - Scientific notation.
// If any of the strings 'E+', 'E-', 'e+', or 'e-' are present in the format
// string and are immediately followed by at least one '0' character, then the
// number is formatted using scientific notation with an 'E' or 'e' inserted
// between the number and the exponent. The number of '0' characters following
// the scientific notation indicator determines the minimum number of digits to
// output for the exponent. The 'E+' and 'e+' formats indicate that a sign
// character (plus or minus) should always precede the exponent. The 'E-' and
// 'e-' formats indicate that a sign character should only precede negative
// exponents.
//
// \ - Literal character. A backslash character
// causes the next character in the format string to be copied to the output
// string as-is. The backslash itself isn't copied, so to place a backslash
// character in the output string, use two backslashes (\\) in the format
// string.
//
// 'ABC' "ABC" - Literal string. Characters
// enclosed in single or double quotation marks are copied to the output string
// as-is and do not affect formatting.
//
// ; - Section separator. The ';' character is
// used to separate sections for positive, negative, and zero numbers in the
// format string.
//
// Other - All other characters are copied to
// the output string in the position they appear.
//
// For fixed point formats (formats not containing an 'E+', 'E-', 'e+', or
// 'e-'), the number is rounded to as many decimal places as there are digit
// placeholders to the right of the decimal point. If the format string does
// not contain a decimal point, the number is rounded to the nearest
// integer. If the number has more digits than there are digit placeholders to
// the left of the decimal point, the extra digits are copied to the output
// string immediately before the first digit placeholder.
//
// For scientific formats, the number is rounded to as many significant digits
// as there are digit placeholders in the format string.
//
// To allow for different formatting of positive, negative, and zero values, a
// user-defined format string may contain up to three sections separated by
// semicolons. The results of having one, two, or three sections in the format
// string are described in the table below.
//
// Sections:
//
// One - The format string applies to all values.
//
// Two - The first section applies to positive values
// and zeros, and the second section applies to negative values. If the number
// to be formatted is negative, but becomes zero after rounding according to
// the format in the second section, then the resulting zero is formatted
// according to the first section.
//
// Three - The first section applies to positive
// values, the second section applies to negative values, and the third section
// applies to zeros. The second section may be left empty (by having no
// characters between the semicolons), in which case the first section applies
// to all non-zero values. If the number to be formatted is non-zero, but
// becomes zero after rounding according to the format in the first or second
// section, then the resulting zero is formatted according to the third
// section.
//
// For both standard and user-defined formatting operations on values of type
// float and double, if the value being formatted is a NaN (Not
// a Number) or a positive or negative infinity, then regardless of the format
// string, the resulting string is given by the NaNSymbol,
// PositiveInfinitySymbol, or NegativeInfinitySymbol property of
// the NumberFormatInfo used to format the number.
//
// Parsing
//
// The Parse methods provided by the numeric classes are all of the form
//
// public static XXX Parse(String s);
// public static XXX Parse(String s, int style);
// public static XXX Parse(String s, int style, NumberFormatInfo info);
//
// where XXX is the name of the particular numeric class. The methods convert a
// string to a numeric value. The optional style parameter specifies the
// permitted style of the numeric string. It must be a combination of bit flags
// from the NumberStyles enumeration. The optional info parameter
// specifies the NumberFormatInfo instance to use when parsing the
// string. If the info parameter is null or omitted, the numeric
// formatting information is obtained from the current culture.
//
// Numeric strings produced by the Format methods using the Currency,
// Decimal, Engineering, Fixed point, General, or Number standard formats
// (the C, D, E, F, G, and N format specifiers) are guaranteed to be parseable
// by the Parse methods if the NumberStyles.Any style is
// specified. Note, however, that the Parse methods do not accept
// NaNs or Infinities.
//
//This class contains only static members and does not need to be serializable
internal static class Number
{
public static String Format(Object value, bool isInteger, String format, NumberFormatInfo info)
{
char formatCh;
int precision;
ValidateFormat(format, out formatCh, out precision);
String result = FormatNative(value, formatCh, precision);
if (isInteger)
{
return PostProcessInteger(value, result, formatCh, precision, info);
}
else
{
return PostProcessFloat(result, formatCh, info);
}
}
[MethodImplAttribute(MethodImplOptions.InternalCall)]
private static extern String FormatNative(Object value, char format, int precision);
private static void ValidateFormat(String format, out char formatCh, out int precision)
{
precision = 0;
if (format == null || format == "")
{
formatCh = 'G';
return;
}
formatCh = format[0];
// ToUpper, since all the supported format characters are invariant in case
if (formatCh >= 'a' && formatCh <= 'z')
{
formatCh = (char)(formatCh - ('a' - 'A'));
}
int formatLen = format.Length;
if (formatLen > 1)
{
ushort digit;
if (formatLen > 4)
{
// Invalid Format
throw new ArgumentException();
}
for (int i = 1; i < formatLen; i++)
{
digit = (ushort)(format[i] - '0');
if (digit > 9)
{
throw new ArgumentException();
}
precision = precision * 10 + digit;
}
}
// Set default precision, if neccessary + check for valid formatCh
switch (formatCh)
{
case 'G':
break;
case 'X':
case 'F':
case 'N':
case 'D':
if (formatLen == 1) precision = 2; // if no precision is specified, use the default
break;
default:
throw new ArgumentException();
}
}
private static String PostProcessInteger(Object value, String original, char format, int precision, NumberFormatInfo info)
{
String result = original;
switch (format)
{
case 'X':
// truncate negative numbers to
if (result.Length > precision && (result[0] == 'F' || result[0] == 'f'))
{
int len = result.Length;
if(value is sbyte || value is byte)
{
if (len > 2)
{
result = result.Substring(len - 2, 2);
}
}
else if (value is short)
{
if (len > 4)
{
result = result.Substring(len - 4, 4);
}
}
}
break;
case 'N':
// InsertGroupSeperators, AppendTrailingZeros, ReplaceNegativeSign
result = InsertGroupSeperators(result, info);
goto case 'F'; // falls through
case 'F':
// AppendTrailingZeros, ReplaceNegativeSign
result = AppendTrailingZeros(result, precision, info);
goto case 'G'; // falls through
case 'G':
result = ReplaceNegativeSign(result, info);
break;
}
return result;
}
private static String PostProcessFloat(String original, char format, NumberFormatInfo info)
{
String result = original;
if (format == 'N')
{
result = InsertGroupSeperators(result, info);
}
result = ReplaceDecimalSeperator(result, info);
result = ReplaceNegativeSign(result, info);
return result;
}
private static String AppendTrailingZeros(String original, int count, NumberFormatInfo info)
{
if (count > 0)
{
return original + info.NumberDecimalSeparator + new String('0', count);
}
else
{
return original;
}
}
private static String ReplaceNegativeSign(String original, NumberFormatInfo info)
{
if (original[0] == '-')
{
return info.NegativeSign + original.Substring(1);
}
else
{
return original;
}
}
private static String ReplaceDecimalSeperator(String original, NumberFormatInfo info)
{
int pos = original.IndexOf('.');
if (pos != -1)
{
return original.Substring(0, pos) + info.NumberDecimalSeparator + original.Substring(pos + 1);
}
else
{
return original;
}
}
private static String InsertGroupSeperators(String original, NumberFormatInfo info)
{
int digitsStartPos = (original[0] == '-') ? 1 : 0;
int decimalPointPos = original.IndexOf('.');
if (decimalPointPos == -1) decimalPointPos = original.Length;
String prefix = (digitsStartPos == 1) ? "-" : "";
String suffix = original.Substring(decimalPointPos);
String digits = original.Substring(digitsStartPos, decimalPointPos - digitsStartPos);
String result = String.Empty;
int[] groupSizes = info.NumberGroupSizes;
int sizeInd = 0;
int size = groupSizes[sizeInd];
int pos = digits.Length - size;
String seperator = info.NumberGroupSeparator;
int lastSizeInd = groupSizes.Length - 1;
while (pos > 0)
{
result = seperator + digits.Substring(pos, size) + result;
if (sizeInd < lastSizeInd)
{
sizeInd++;
size = groupSizes[sizeInd];
if (size == 0) // per spec, when we see a 0, we leave the remaining digits ungrouped.
{
break;
}
}
pos -= size;
}
result = prefix + digits.Substring(0, size + pos) + result + suffix;
return result;
}
}
}

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

@ -0,0 +1,69 @@
//
// Copyright (c) 2017 The nanoFramework project contributors
// Portions Copyright (c) Microsoft Corporation. All rights reserved.
// See LICENSE file in the project root for full license information.
//
namespace System
{
using System;
using System.Runtime.CompilerServices;
/**
* The <i>Object</i> is the root class for all object in the CLR System. <i>Object</i>
* is the super class for all other CLR objects and provide a set of methods and low level
* services to subclasses. These services include object synchronization and support for clone
* operations.
*
* @see System.ICloneable
*/
//This class contains no data and does not need to be serializable
[Serializable()]
public class Object
{
[Diagnostics.DebuggerHidden]
public Object()
{
}
public virtual String ToString()
{
return GetType().FullName;
}
[MethodImplAttribute(MethodImplOptions.InternalCall)]
public extern virtual bool Equals(Object obj);
public static bool Equals(Object objA, Object objB)
{
if (objA == objB)
{
return true;
}
if (objA == null || objB == null)
{
return false;
}
return objA.Equals(objB);
}
[MethodImplAttribute(MethodImplOptions.InternalCall)]
public extern static bool ReferenceEquals(Object objA, Object objB);
[MethodImplAttribute(MethodImplOptions.InternalCall)]
public extern virtual int GetHashCode();
[MethodImplAttribute(MethodImplOptions.InternalCall)]
public extern Type GetType();
[Diagnostics.DebuggerHidden]
~Object()
{
}
[MethodImplAttribute(MethodImplOptions.InternalCall)]
protected extern Object MemberwiseClone();
}
}

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

@ -0,0 +1,21 @@
namespace System
{
[Serializable()]
public class ObjectDisposedException : SystemException
{
public ObjectDisposedException()
: base()
{
}
public ObjectDisposedException(String message)
: base(message)
{
}
public ObjectDisposedException(String message, Exception innerException)
: base(message, innerException)
{
}
}
}

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

@ -0,0 +1,58 @@
//
// Copyright (c) 2017 The nanoFramework project contributors
// Portions Copyright (c) Microsoft Corporation. All rights reserved.
// See LICENSE file in the project root for full license information.
//
namespace System
{
using System;
/**
* This attribute is attached to members that are not to be used any longer.
* Message is some human readable explanation of what to use
* Error indicates if the compiler should treat usage of such a method as an
* error. (this would be used if the actual implementation of the obsolete
* method's implementation had changed).
*
* Issue: do we need to be able to localize this message string?
*
*/
[Serializable(), AttributeUsage(AttributeTargets.Class | AttributeTargets.Struct | AttributeTargets.Enum |
AttributeTargets.Interface | AttributeTargets.Constructor | AttributeTargets.Method | AttributeTargets.Property | AttributeTargets.Field | AttributeTargets.Event | AttributeTargets.Delegate
, Inherited = false)]
public sealed class ObsoleteAttribute : Attribute
{
private String _message;
private bool _error;
public ObsoleteAttribute()
{
_message = null;
_error = false;
}
public ObsoleteAttribute(String message)
{
_message = message;
_error = false;
}
public ObsoleteAttribute(String message, bool error)
{
_message = message;
_error = error;
}
public String Message
{
get { return _message; }
}
public bool IsError
{
get { return _error; }
}
}
}

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

@ -0,0 +1,21 @@
namespace System
{
[Serializable()]
public class OutOfMemoryException : SystemException
{
public OutOfMemoryException()
: base()
{
}
public OutOfMemoryException(String message)
: base(message)
{
}
public OutOfMemoryException(String message, Exception innerException)
: base(message, innerException)
{
}
}
}

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

@ -0,0 +1,15 @@
//
// Copyright (c) 2017 The nanoFramework project contributors
// Portions Copyright (c) Microsoft Corporation. All rights reserved.
// See LICENSE file in the project root for full license information.
//
namespace System
{
//This class contains only static members and does not need to be serializable
[AttributeUsage(AttributeTargets.Parameter, Inherited = true, AllowMultiple = false)]
public sealed class ParamArrayAttribute : Attribute
{
public ParamArrayAttribute() { }
}
}

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

@ -0,0 +1,70 @@
//
// Copyright (c) 2017 The nanoFramework project contributors
// Portions Copyright (c) Microsoft Corporation. All rights reserved.
// See LICENSE file in the project root for full license information.
//
using System;
using System.Runtime.CompilerServices;
namespace System
{
/// <summary>
/// Represents a pseudo-random number generator, a device that produces a
/// sequence of numbers that meet certain statistical requirements for
/// randomness.
/// </summary>
public class Random
{
private object _random;
/// <summary>
/// Initializes a new instance of the Random class, using a time-
/// dependent default seed value.
/// </summary>
[MethodImplAttribute(MethodImplOptions.InternalCall)]
public extern Random();
/// <summary>
/// Initializes a new instance of the Random class, using the specified
/// seed value.
/// </summary>
/// <param name="seed">A number used to calculate a starting value for
/// the pseudo-random number sequence.</param>
[MethodImplAttribute(MethodImplOptions.InternalCall)]
public extern Random(int seed);
/// <summary>
/// Returns a nonnegative random number.
/// </summary>
/// <returns>A 32-bit signed integer greater than or equal to zero and
/// less than MaxValue.</returns>
[MethodImplAttribute(MethodImplOptions.InternalCall)]
public extern virtual int Next();
/// <summary>
/// Returns a nonnegative random number less than the specified maximum.
/// </summary>
/// <param name="maxValue">The exclusive upper bound of the random number
/// to be generated. maxValue must be greater than or equal to zero.</param>
/// <returns>A 32-bit signed integer greater than or equal to zero, and
/// less than maxValue.</returns>
[MethodImplAttribute(MethodImplOptions.InternalCall)]
public extern virtual int Next(int maxValue);
/// <summary>
/// Returns a random number between 0.0 and 1.0.
/// </summary>
/// <returns>A double-precision floating point number greater than or equal
/// to 0.0, and less than 1.0.</returns>
[MethodImplAttribute(MethodImplOptions.InternalCall)]
public extern virtual double NextDouble();
/// <summary>
/// Fills the elements of a specified array of bytes with random numbers.
/// </summary>
/// <param name="buffer">An array of bytes to contain random numbers.</param>
[MethodImplAttribute(MethodImplOptions.InternalCall)]
public extern virtual void NextBytes(byte[] buffer);
}
}

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

@ -0,0 +1,233 @@
//
// Copyright (c) 2017 The nanoFramework project contributors
// Portions Copyright (c) Microsoft Corporation. All rights reserved.
// See LICENSE file in the project root for full license information.
//
namespace System.Reflection
{
using System;
using CultureInfo = System.Globalization.CultureInfo;
using System.Runtime.CompilerServices;
public sealed class AssemblyName
{
private Assembly _assembly;
//--//
internal AssemblyName(Assembly assm)
{
_assembly = assm;
}
public String Name
{
get
{
return _assembly.FullName.Substring(0, _assembly.FullName.IndexOf(','));
}
}
public String FullName
{
get
{
return _assembly.FullName;
}
}
public Version Version
{
get
{
int major = -1, minor = -1, build = -1, revision = -1;
_assembly.GetVersion(ref major, ref minor, ref build, ref revision);
return new Version(major, minor, build, revision);
}
}
}
[Serializable()]
public class Assembly
{
public extern virtual String FullName
{
[MethodImplAttribute(MethodImplOptions.InternalCall)]
get;
}
[MethodImplAttribute(MethodImplOptions.InternalCall)]
public extern static Assembly GetExecutingAssembly();
[MethodImplAttribute(MethodImplOptions.InternalCall)]
internal extern void GetVersion(ref int major, ref int minor, ref int build, ref int revision);
public AssemblyName GetName()
{
return new AssemblyName(this);
}
public static Assembly GetAssembly(Type type)
{
return type.Assembly;
}
[MethodImplAttribute(MethodImplOptions.InternalCall)]
public extern virtual Type GetType(String name);
public virtual Type GetType(String name, bool throwOnError)
{
Type type = GetType(name);
if (type == null)
{
throw new ArgumentException();
}
return type;
}
[MethodImplAttribute(MethodImplOptions.InternalCall)]
public extern virtual Type[] GetTypes();
public Assembly GetSatelliteAssembly(CultureInfo culture)
{
if (culture == null)
{
throw new ArgumentNullException("culture");
}
Assembly assm = null;
string baseName = this.FullName;
string cultureName;
while (assm == null && (cultureName = culture.Name) != "")
{
string assmName = baseName + "." + cultureName;
assm = Assembly.Load(assmName, false);
culture = culture.Parent;
}
if (assm == null)
{
throw new ArgumentException();
// FIXME -- throw new FileNotFoundException();
}
return assm;
}
public static Assembly Load(String assemblyString)
{
if (assemblyString == null)
{
throw new ArgumentNullException("assemblyString");
}
return Load(assemblyString, true);
}
internal static string ParseAssemblyName(String assemblyString, ref bool fVersion, ref int[] ver)
{
// valid names are in the forms:
// 1) "Microsoft.SPOT.Native" or
// 2) "Microsoft.SPOT.Native, Version=1.2.3.4" or
// 3) "Microsoft.SPOT.Native.resources, Version=1.2.3.4" or
// 4) "Microsoft.SPOT.Native.tinyresources, Version=1.2.3.4"
// 5) (FROM THE DEBUGGER) "Microsoft.SPOT.Native, Version=1.2.3.4, Culture=neutral, PublicKeyToken=null[, ...]
int versionIdx, commaIdx;
string name;
fVersion = false;
// if there is no comma then we have an assembly name in the form with no version
if ((commaIdx = assemblyString.IndexOf(',')) != -1)
{
name = assemblyString.Substring(0, commaIdx);
const string c_versionTag = "version=";
// verify that the format with the version is correct and skip the ", Version=" part of the string
if ((versionIdx = assemblyString.ToLower().IndexOf(c_versionTag)) != 0)
{
fVersion = true;
// the "version=" string must come right after the ' ,'
if (versionIdx == commaIdx + 2)
{
int startIdx = versionIdx + c_versionTag.Length;
int endIdx;
// trim off the Culture, PublicKeyToken, etc for now
if(-1 != (endIdx = assemblyString.IndexOf(',', startIdx)))
{
assemblyString = assemblyString.Substring(startIdx, endIdx - startIdx);
}
else
{
assemblyString = assemblyString.Substring(startIdx);
}
// at this point we have assemblyString = "1.2.3.4"
string[] version = assemblyString.Split('.');
if (version.Length > 0) ver[0] = UInt16.Parse(version[0]);
if (version.Length > 1) ver[1] = UInt16.Parse(version[1]);
// build and revision versions may be -1 (which means "don't care")
if (version.Length > 2) ver[2] = int.Parse(version[2]);
if (version.Length > 3) ver[3] = int.Parse(version[3]);
}
else
{
throw new ArgumentException();
}
}
else
{
throw new ArgumentException();
}
}
else
{
name = assemblyString;
}
return name;
}
internal static Assembly Load(String assemblyString, bool fThrowOnError)
{
bool fVersion = false;
int[] ver = new int[4];
string name = ParseAssemblyName(assemblyString, ref fVersion, ref ver);
Assembly assm = LoadInternal(name, fVersion, ver[0], ver[1], ver[2], ver[3]);
if (assm == null)
{
if (fThrowOnError)
{
// FIXME -- should be FileNotFoundException, per spec.
throw new ArgumentException();
}
}
return assm;
}
[MethodImplAttribute(MethodImplOptions.InternalCall)]
internal extern static Assembly LoadInternal(String assemblyString, bool fVersion, int maj, int min, int build, int rev);
[MethodImplAttribute(MethodImplOptions.InternalCall)]
static extern public Assembly Load(byte[] rawAssembly);
[MethodImplAttribute(MethodImplOptions.InternalCall)]
internal extern String[] GetManifestResourceNames();
}
}

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

@ -0,0 +1,131 @@
//
// Copyright (c) 2017 The nanoFramework project contributors
// Portions Copyright (c) Microsoft Corporation. All rights reserved.
// See LICENSE file in the project root for full license information.
//
namespace System.Reflection
{
using System;
[AttributeUsage(AttributeTargets.Assembly, AllowMultiple = false)]
public sealed class AssemblyCultureAttribute : Attribute
{
private String m_culture;
public AssemblyCultureAttribute(String culture)
{
m_culture = culture;
}
public String Culture
{
get { return m_culture; }
}
}
[AttributeUsage(AttributeTargets.Assembly, AllowMultiple = false)]
public sealed class AssemblyVersionAttribute : Attribute
{
private String m_version;
public AssemblyVersionAttribute(String version)
{
m_version = version;
}
}
[AttributeUsage(AttributeTargets.Assembly, AllowMultiple = false)]
public sealed class AssemblyKeyFileAttribute : Attribute
{
private String m_keyFile;
public AssemblyKeyFileAttribute(String keyFile)
{
m_keyFile = keyFile;
}
public String KeyFile
{
get { return m_keyFile; }
}
}
[AttributeUsage(AttributeTargets.Assembly, AllowMultiple = false)]
public sealed class AssemblyKeyNameAttribute : Attribute
{
private String m_keyName;
public AssemblyKeyNameAttribute(String keyName)
{
m_keyName = keyName;
}
public String KeyName
{
get { return m_keyName; }
}
}
[AttributeUsage(AttributeTargets.Assembly, AllowMultiple = false)]
public sealed class AssemblyDelaySignAttribute : Attribute
{
private bool m_delaySign;
public AssemblyDelaySignAttribute(bool delaySign)
{
m_delaySign = delaySign;
}
public bool DelaySign
{
get
{ return m_delaySign; }
}
}
[AttributeUsage(AttributeTargets.Assembly, AllowMultiple = false)]
public sealed class AssemblyFlagsAttribute : Attribute
{
private AssemblyNameFlags m_flags;
[CLSCompliant(false)]
public AssemblyFlagsAttribute(uint flags)
{
m_flags = (AssemblyNameFlags)flags;
}
[CLSCompliant(false)]
public uint Flags
{
get { return (uint)m_flags; }
}
public AssemblyFlagsAttribute(AssemblyNameFlags assemblyFlags)
{
m_flags = assemblyFlags;
}
}
[AttributeUsage(AttributeTargets.Assembly, Inherited = false)]
public sealed class AssemblyFileVersionAttribute : Attribute
{
private String _version;
public AssemblyFileVersionAttribute(String version)
{
if (version == null)
throw new ArgumentNullException("version");
_version = version;
}
public String Version
{
get { return _version; }
}
}
}

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

@ -0,0 +1,48 @@
//
// Copyright (c) 2017 The nanoFramework project contributors
// Portions Copyright (c) Microsoft Corporation. All rights reserved.
// See LICENSE file in the project root for full license information.
//
namespace System.Reflection
{
using System;
[Serializable, FlagsAttribute()]
public enum AssemblyNameFlags
{
None = 0x0000,
PublicKey = 0x0001,
[Obsolete("This will be removed before Whidbey ships. There will be no replacement for Whidbey.")]
LongevityUnspecified = 0x0000, // Nothing set.
[Obsolete("This will be removed before Whidbey ships. There will be no replacement for Whidbey.")]
Library = 0x0002, // All types in the assembly are Library types.
[Obsolete("This will be removed before Whidbey ships. There will be no replacement for Whidbey.")]
AppDomainPlatform = 0x0004, // All types in the assembly are Platform types.
[Obsolete("This will be removed before Whidbey ships. There will be no replacement for Whidbey.")]
ProcessPlatform = 0x0006, // All types in the assembly are Platform types.
[Obsolete("This will be removed before Whidbey ships. There will be no replacement for Whidbey.")]
SystemPlatform = 0x0008, // All types in the assembly are Platform types.
[Obsolete("This will be removed before Whidbey ships. There will be no replacement for Whidbey.")]
LongevityMask = 0x000E, // Bits describing the platform/library property of the assembly.
// Accessible via AssemblyName.ProcessorArchitecture
EnableJITcompileOptimizer = 0x4000,
EnableJITcompileTracking = 0x8000,
Retargetable = 0x0100,
}
[Serializable]
public enum ProcessorArchitecture
{
None = 0x0000,
MSIL = 0x0001,
X86 = 0x0002,
IA64 = 0x0003,
Amd64 = 0x0004
}
}

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

@ -0,0 +1,157 @@
//
// Copyright (c) 2017 The nanoFramework project contributors
// Portions Copyright (c) Microsoft Corporation. All rights reserved.
// See LICENSE file in the project root for full license information.
//
namespace System.Reflection
{
using System;
[AttributeUsage(AttributeTargets.Assembly, AllowMultiple = false)]
public sealed class AssemblyCopyrightAttribute : Attribute
{
private String m_copyright;
public AssemblyCopyrightAttribute(String copyright)
{
m_copyright = copyright;
}
public String Copyright
{
get { return m_copyright; }
}
}
[AttributeUsage(AttributeTargets.Assembly, AllowMultiple = false)]
public sealed class AssemblyTrademarkAttribute : Attribute
{
private String m_trademark;
public AssemblyTrademarkAttribute(String trademark)
{
m_trademark = trademark;
}
public String Trademark
{
get { return m_trademark; }
}
}
[AttributeUsage(AttributeTargets.Assembly, AllowMultiple = false)]
public sealed class AssemblyProductAttribute : Attribute
{
private String m_product;
public AssemblyProductAttribute(String product)
{
m_product = product;
}
public String Product
{
get { return m_product; }
}
}
[AttributeUsage(AttributeTargets.Assembly, AllowMultiple = false)]
public sealed class AssemblyCompanyAttribute : Attribute
{
private String m_company;
public AssemblyCompanyAttribute(String company)
{
m_company = company;
}
public String Company
{
get { return m_company; }
}
}
[AttributeUsage(AttributeTargets.Assembly, AllowMultiple = false)]
public sealed class AssemblyDescriptionAttribute : Attribute
{
private String m_description;
public AssemblyDescriptionAttribute(String description)
{
m_description = description;
}
public String Description
{
get { return m_description; }
}
}
[AttributeUsage(AttributeTargets.Assembly, AllowMultiple = false)]
public sealed class AssemblyTitleAttribute : Attribute
{
private String m_title;
public AssemblyTitleAttribute(String title)
{
m_title = title;
}
public String Title
{
get { return m_title; }
}
}
[AttributeUsage(AttributeTargets.Assembly, AllowMultiple = false)]
public sealed class AssemblyConfigurationAttribute : Attribute
{
private String m_configuration;
public AssemblyConfigurationAttribute(String configuration)
{
m_configuration = configuration;
}
public String Configuration
{
get { return m_configuration; }
}
}
[AttributeUsage(AttributeTargets.Assembly, AllowMultiple = false)]
public sealed class AssemblyDefaultAliasAttribute : Attribute
{
private String m_defaultAlias;
public AssemblyDefaultAliasAttribute(String defaultAlias)
{
m_defaultAlias = defaultAlias;
}
public String DefaultAlias
{
get { return m_defaultAlias; }
}
}
[AttributeUsage(AttributeTargets.Assembly, AllowMultiple = false)]
public sealed class AssemblyInformationalVersionAttribute : Attribute
{
private String m_informationalVersion;
public AssemblyInformationalVersionAttribute(String informationalVersion)
{
m_informationalVersion = informationalVersion;
}
public String InformationalVersion
{
get { return m_informationalVersion; }
}
}
}

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

@ -0,0 +1,14 @@
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
// Copyright (c) Microsoft Corporation. All rights reserved.
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////namespace System.Reflection
namespace System.Reflection
{
using System;
[Serializable()]
public abstract class Binder
{
}
}

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

@ -0,0 +1,54 @@
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
// Copyright (c) Microsoft Corporation. All rights reserved.
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////namespace System.Reflection
namespace System.Reflection
{
using System;
[Flags, Serializable]
public enum BindingFlags
{
// NOTES: We have lookup masks defined in RuntimeType and Activator. If we
// change the lookup values then these masks may need to change also.
// a place holder for no flag specifed
Default = 0x00,
// These flags indicate what to search for when binding
IgnoreCase = 0x01, // Ignore the case of Names while searching
DeclaredOnly = 0x02, // Only look at the members declared on the Type
Instance = 0x04, // Include Instance members in search
Static = 0x08, // Include Static members in search
Public = 0x10, // Include Public members in search
NonPublic = 0x20, // Include Non-Public members in search
FlattenHierarchy = 0x40, // Rollup the statics into the class.
// These flags are used by InvokeMember to determine
// what type of member we are trying to Invoke.
// BindingAccess = 0xFF00;
InvokeMethod = 0x0100,
CreateInstance = 0x0200,
GetField = 0x0400,
SetField = 0x0800,
GetProperty = 0x1000,
SetProperty = 0x2000,
// These flags are also used by InvokeMember but they should only
// be used when calling InvokeMember on a COM object.
PutDispProperty = 0x4000,
PutRefDispProperty = 0x8000,
ExactBinding = 0x010000, // Bind with Exact Type matching, No Change type
SuppressChangeType = 0x020000,
// DefaultValueBinding will return the set of methods having ArgCount or
// more parameters. This is used for default values, etc.
OptionalParamBinding = 0x040000,
// These are a couple of misc attributes used
IgnoreReturn = 0x01000000, // This is used in COM Interop
}
}

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

@ -0,0 +1,27 @@
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
// Copyright (c) Microsoft Corporation. All rights reserved.
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////namespace System.Reflection
namespace System.Reflection
{
using System;
using System.Runtime.CompilerServices;
//This class is marked serializable, but it's really the subclasses that
//are responsible for handling the actual work of serialization if they need it.
[Serializable()]
abstract public class ConstructorInfo : MethodBase
{
public override MemberTypes MemberType
{
get { return System.Reflection.MemberTypes.Constructor; }
}
[Diagnostics.DebuggerStepThrough]
[Diagnostics.DebuggerHidden]
[MethodImplAttribute(MethodImplOptions.InternalCall)]
public extern Object Invoke(Object[] parameters);
}
}

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

@ -0,0 +1,31 @@
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
// Copyright (c) Microsoft Corporation. All rights reserved.
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////namespace System.Reflection
namespace System.Reflection
{
using System;
[AttributeUsage(AttributeTargets.Class | AttributeTargets.Struct | AttributeTargets.Interface), Serializable]
public sealed class DefaultMemberAttribute : Attribute
{
// The name of the member
private String m_memberName;
// You must provide the name of the member, this is required
public DefaultMemberAttribute(String memberName)
{
m_memberName = memberName;
}
// A get accessor to return the name from the attribute.
// NOTE: There is no setter because the name must be provided
// to the constructor. The name is not optional.
public String MemberName
{
get { return m_memberName; }
}
}
}

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

@ -0,0 +1,39 @@
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
// Copyright (c) Microsoft Corporation. All rights reserved.
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////namespace System.Reflection
namespace System.Reflection
{
using System;
using System.Runtime.CompilerServices;
[Serializable()]
abstract public class FieldInfo : MemberInfo
{
/**
* The Member type Field.
*/
public override MemberTypes MemberType
{
get
{
return System.Reflection.MemberTypes.Field;
}
}
public abstract Type FieldType
{
get;
}
[Diagnostics.DebuggerStepThrough]
[Diagnostics.DebuggerHidden]
public abstract object GetValue(object obj);
[Diagnostics.DebuggerStepThrough]
[Diagnostics.DebuggerHidden]
[MethodImplAttribute(MethodImplOptions.InternalCall)]
public extern virtual void SetValue(Object obj, Object value);
}
}

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

@ -0,0 +1,16 @@
//
// Copyright (c) 2017 The nanoFramework project contributors
// Portions Copyright (c) Microsoft Corporation. All rights reserved.
// See LICENSE file in the project root for full license information.
//
namespace System.Reflection
{
[AttributeUsage(AttributeTargets.Field, AllowMultiple = false)]
internal sealed class FieldNoReflectionAttribute : Attribute
{
}
}

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

@ -0,0 +1,16 @@
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
// Copyright (c) Microsoft Corporation. All rights reserved.
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////namespace System.Reflection
namespace System.Reflection
{
using System;
// Interface does not need to be marked with the serializable attribute
public interface IReflect
{
MethodInfo GetMethod(String name, BindingFlags bindingAttr);
FieldInfo GetField(String name, BindingFlags bindingAttr);
}
}

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

@ -0,0 +1,29 @@
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
// Copyright (c) Microsoft Corporation. All rights reserved.
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////namespace System.Reflection
namespace System.Reflection
{
using System;
[Serializable()]
public abstract class MemberInfo
{
public abstract MemberTypes MemberType
{
get;
}
public abstract String Name
{
get;
}
public abstract Type DeclaringType
{
get;
}
}
}

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

@ -0,0 +1,27 @@
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
// Copyright (c) Microsoft Corporation. All rights reserved.
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////namespace System.Reflection
namespace System.Reflection
{
using System;
/**
* This Enum matchs the CorTypeAttr defined in CorHdr.h
*/
[Serializable()]
public enum MemberTypes
{
// The following are the known classes which extend MemberInfo
Constructor = 0x01,
Event = 0x02,
Field = 0x04,
Method = 0x08,
Property = 0x10,
TypeInfo = 0x20,
Custom = 0x40,
NestedType = 0x80,
All = Constructor | Event | Field | Method | Property | TypeInfo | NestedType,
}
}

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

@ -0,0 +1,65 @@
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
// Copyright (c) Microsoft Corporation. All rights reserved.
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////namespace System.Reflection
namespace System.Reflection
{
using System.Runtime.CompilerServices;
////////////////////////////////////////////////////////////////////////////////
// Method is the class which represents a Method. These are accessed from
// Class through getMethods() or getMethod(). This class contains information
// about each method and also allows the method to be dynamically invoked
// on an instance.
////////////////////////////////////////////////////////////////////////////////
using System;
[Serializable()]
public abstract class MethodBase : MemberInfo
{
public extern bool IsPublic
{
[MethodImplAttribute(MethodImplOptions.InternalCall)]
get;
}
public extern bool IsStatic
{
[MethodImplAttribute(MethodImplOptions.InternalCall)]
get;
}
public extern bool IsFinal
{
[MethodImplAttribute(MethodImplOptions.InternalCall)]
get;
}
public extern bool IsVirtual
{
[MethodImplAttribute(MethodImplOptions.InternalCall)]
get;
}
public extern bool IsAbstract
{
[MethodImplAttribute(MethodImplOptions.InternalCall)]
get;
}
[Diagnostics.DebuggerStepThrough]
[Diagnostics.DebuggerHidden]
[MethodImplAttribute(MethodImplOptions.InternalCall)]
public extern Object Invoke(Object obj, Object[] parameters);
public extern override String Name
{
[MethodImplAttribute(MethodImplOptions.InternalCall)]
get;
}
public extern override Type DeclaringType
{
[MethodImplAttribute(MethodImplOptions.InternalCall)]
get;
}
}
}

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